numpy-1.8.2/0000775000175100017510000000000012371375430014031 5ustar vagrantvagrant00000000000000numpy-1.8.2/MANIFEST.in0000664000175100017510000000203512370216243015562 0ustar vagrantvagrant00000000000000# # Use .add_data_files and .add_data_dir methods in a appropriate # setup.py files to include non-python files such as documentation, # data, etc files to distribution. Avoid using MANIFEST.in for that. # include MANIFEST.in include COMPATIBILITY include *.txt include setupegg.py include site.cfg.example include tools/py3tool.py include numpy/random/mtrand/generate_mtrand_c.py recursive-include numpy/random/mtrand *.pyx *.pxd # Adding scons build related files not found by distutils recursive-include numpy/core/code_generators *.py *.txt recursive-include numpy/core *.in *.h # Add documentation: we don't use add_data_dir since we do not want to include # this at installation, only for sdist-generated tarballs include doc/Makefile doc/postprocess.py recursive-include doc/release * recursive-include doc/source * recursive-include doc/sphinxext * recursive-include doc/cython * recursive-include doc/pyrex * recursive-include doc/swig * recursive-include doc/scipy-sphinx-theme * recursive-include doc/f2py * global-exclude *.pyc *.pyo *.pyd numpy-1.8.2/README.txt0000664000175100017510000000137412370216242015526 0ustar vagrantvagrant00000000000000NumPy is the fundamental package needed for scientific computing with Python. This package contains: * a powerful N-dimensional array object * sophisticated (broadcasting) functions * tools for integrating C/C++ and Fortran code * useful linear algebra, Fourier transform, and random number capabilities. It derives from the old Numeric code base and can be used as a replacement for Numeric. It also adds the features introduced by numarray and can be used to replace numarray. More information can be found at the website: http://www.numpy.org After installation, tests can be run with: python -c 'import numpy; numpy.test()' The most current development version is always available from our git repository: http://github.com/numpy/numpy numpy-1.8.2/LICENSE.txt0000664000175100017510000000300712370216242015646 0ustar vagrantvagrant00000000000000Copyright (c) 2005-2011, NumPy Developers. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the NumPy Developers nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. numpy-1.8.2/doc/0000775000175100017510000000000012371375427014604 5ustar vagrantvagrant00000000000000numpy-1.8.2/doc/cython/0000775000175100017510000000000012371375427016110 5ustar vagrantvagrant00000000000000numpy-1.8.2/doc/cython/README.txt0000664000175100017510000000125712370216243017600 0ustar vagrantvagrant00000000000000================== NumPy and Cython ================== This directory contains a small example of how to use NumPy and Cython together. While much work is planned for the Summer of 2008 as part of the Google Summer of Code project to improve integration between the two, even today Cython can be used effectively to write optimized code that accesses NumPy arrays. The example provided is just a stub showing how to build an extension and access the array objects; improvements to this to show more sophisticated tasks are welcome. To run it locally, simply type:: make help which shows you the currently available targets (these are just handy shorthands for common commands). numpy-1.8.2/doc/cython/setup.py0000775000175100017510000000327612370216243017622 0ustar vagrantvagrant00000000000000#!/usr/bin/env python """Install file for example on how to use Cython with Numpy. Note: Cython is the successor project to Pyrex. For more information, see http://cython.org. """ from __future__ import division, print_function from distutils.core import setup from distutils.extension import Extension import numpy # We detect whether Cython is available, so that below, we can eventually ship # pre-generated C for users to compile the extension without having Cython # installed on their systems. try: from Cython.Distutils import build_ext has_cython = True except ImportError: has_cython = False # Define a cython-based extension module, using the generated sources if cython # is not available. if has_cython: pyx_sources = ['numpyx.pyx'] cmdclass = {'build_ext': build_ext} else: # In production work, you can ship the auto-generated C source yourself to # your users. In this case, we do NOT ship the .c file as part of numpy, # so you'll need to actually have cython installed at least the first # time. Since this is really just an example to show you how to use # *Cython*, it makes more sense NOT to ship the C sources so you can edit # the pyx at will with less chances for source update conflicts when you # update numpy. pyx_sources = ['numpyx.c'] cmdclass = {} # Declare the extension object pyx_ext = Extension('numpyx', pyx_sources, include_dirs = [numpy.get_include()]) # Call the routine which does the real work setup(name = 'numpyx', description = 'Small example on using Cython to write a Numpy extension', ext_modules = [pyx_ext], cmdclass = cmdclass, ) numpy-1.8.2/doc/cython/run_test.py0000775000175100017510000000016712370216243020321 0ustar vagrantvagrant00000000000000#!/usr/bin/env python from __future__ import division, absolute_import, print_function from numpyx import test test() numpy-1.8.2/doc/cython/numpyx.pyx0000664000175100017510000001133712370216243020204 0ustar vagrantvagrant00000000000000# -*- Mode: Python -*- Not really, but close enough """Cython access to Numpy arrays - simple example. """ ############################################################################# # Load C APIs declared in .pxd files via cimport # # A 'cimport' is similar to a Python 'import' statement, but it provides access # to the C part of a library instead of its Python-visible API. See the # Pyrex/Cython documentation for details. cimport c_python as py cimport c_numpy as cnp # NOTE: numpy MUST be initialized before any other code is executed. cnp.import_array() ############################################################################# # Load Python modules via normal import statements import numpy as np ############################################################################# # Regular code section begins # A 'def' function is visible in the Python-imported module def print_array_info(cnp.ndarray arr): """Simple information printer about an array. Code meant to illustrate Cython/NumPy integration only.""" cdef int i print '-='*10 # Note: the double cast here (void * first, then py.Py_intptr_t) is needed # in Cython but not in Pyrex, since the casting behavior of cython is # slightly different (and generally safer) than that of Pyrex. In this # case, we just want the memory address of the actual Array object, so we # cast it to void before doing the py.Py_intptr_t cast: print 'Printing array info for ndarray at 0x%0lx'% \ (arr,) print 'number of dimensions:',arr.nd print 'address of strides: 0x%0lx'%(arr.strides,) print 'strides:' for i from 0<=iarr.strides[i] print 'memory dump:' print_elements( arr.data, arr.strides, arr.dimensions, arr.nd, sizeof(double), arr.dtype ) print '-='*10 print # A 'cdef' function is NOT visible to the python side, but it is accessible to # the rest of this Cython module cdef print_elements(char *data, py.Py_intptr_t* strides, py.Py_intptr_t* dimensions, int nd, int elsize, object dtype): cdef py.Py_intptr_t i,j cdef void* elptr if dtype not in [np.dtype(np.object_), np.dtype(np.float64)]: print ' print_elements() not (yet) implemented for dtype %s'%dtype.name return if nd ==0: if dtype==np.dtype(np.object_): elptr = (data)[0] #[0] dereferences pointer in Pyrex print ' ',elptr elif dtype==np.dtype(np.float64): print ' ',(data)[0] elif nd == 1: for i from 0<=idata)[0] print ' ',elptr elif dtype==np.dtype(np.float64): print ' ',(data)[0] data = data + strides[0] else: for i from 0<=i build the Cython extension module." @echo "html -> create annotated HTML from the .pyx sources" @echo "test -> run a simple test demo." @echo "all -> Call ext, html and finally test." all: ext html test ext: numpyx.so test: ext python run_test.py html: numpyx.pyx.html numpyx.so: numpyx.pyx numpyx.c python setup.py build_ext --inplace numpyx.pyx.html: numpyx.pyx cython -a numpyx.pyx @echo "Annotated HTML of the C code generated in numpyx.html" # Phony targets for cleanup and similar uses .PHONY: clean clean: rm -rf *~ *.so *.c *.o *.html build # Suffix rules %.c : %.pyx cython $< numpy-1.8.2/doc/release/0000775000175100017510000000000012371375427016224 5ustar vagrantvagrant00000000000000numpy-1.8.2/doc/release/time_based_proposal.rst0000664000175100017510000001504612370216242022763 0ustar vagrantvagrant00000000000000.. vim:syntax=rst Introduction ============ This document proposes some enhancements for numpy and scipy releases. Successive numpy and scipy releases are too far apart from a time point of view - some people who are in the numpy release team feel that it cannot improve without a bit more formal release process. The main proposal is to follow a time-based release, with expected dates for code freeze, beta and rc. The goal is two folds: make release more predictable, and move the code forward. Rationale ========= Right now, the release process of numpy is relatively organic. When some features are there, we may decide to make a new release. Because there is not fixed schedule, people don't really know when new features and bug fixes will go into a release. More significantly, having an expected release schedule helps to *coordinate* efforts: at the beginning of a cycle, everybody can jump in and put new code, even break things if needed. But after some point, only bug fixes are accepted: this makes beta and RC releases much easier; calming things down toward the release date helps focusing on bugs and regressions Proposal ======== Time schedule ------------- The proposed schedule is to release numpy every 9 weeks - the exact period can be tweaked if it ends up not working as expected. There will be several stages for the cycle: * Development: anything can happen (by anything, we mean as currently done). The focus is on new features, refactoring, etc... * Beta: no new features. No bug fixing which requires heavy changes. regression fixes which appear on supported platforms and were not caught earlier. * Polish/RC: only docstring changes and blocker regressions are allowed. The schedule would be as follows: +------+-----------------+-----------------+------------------+ | Week | 1.3.0 | 1.4.0 | Release time | +======+=================+=================+==================+ | 1 | Development | | | +------+-----------------+-----------------+------------------+ | 2 | Development | | | +------+-----------------+-----------------+------------------+ | 3 | Development | | | +------+-----------------+-----------------+------------------+ | 4 | Development | | | +------+-----------------+-----------------+------------------+ | 5 | Development | | | +------+-----------------+-----------------+------------------+ | 6 | Development | | | +------+-----------------+-----------------+------------------+ | 7 | Beta | | | +------+-----------------+-----------------+------------------+ | 8 | Beta | | | +------+-----------------+-----------------+------------------+ | 9 | Beta | | 1.3.0 released | +------+-----------------+-----------------+------------------+ | 10 | Polish | Development | | +------+-----------------+-----------------+------------------+ | 11 | Polish | Development | | +------+-----------------+-----------------+------------------+ | 12 | Polish | Development | | +------+-----------------+-----------------+------------------+ | 13 | Polish | Development | | +------+-----------------+-----------------+------------------+ | 14 | | Development | | +------+-----------------+-----------------+------------------+ | 15 | | Development | | +------+-----------------+-----------------+------------------+ | 16 | | Beta | | +------+-----------------+-----------------+------------------+ | 17 | | Beta | | +------+-----------------+-----------------+------------------+ | 18 | | Beta | 1.4.0 released | +------+-----------------+-----------------+------------------+ Each stage can be defined as follows: +------------------+-------------+----------------+----------------+ | | Development | Beta | Polish | +==================+=============+================+================+ | Python Frozen | | slushy | Y | +------------------+-------------+----------------+----------------+ | Docstring Frozen | | slushy | thicker slush | +------------------+-------------+----------------+----------------+ | C code Frozen | | thicker slush | thicker slush | +------------------+-------------+----------------+----------------+ Terminology: * slushy: you can change it if you beg the release team and it's really important and you coordinate with docs/translations; no "big" changes. * thicker slush: you can change it if it's an open bug marked showstopper for the Polish release, you beg the release team, the change is very very small yet very very important, and you feel extremely guilty about your transgressions. The different frozen states are intended to be gradients. The exact meaning is decided by the release manager: he has the last word on what's go in, what doesn't. The proposed schedule means that there would be at most 12 weeks between putting code into the source code repository and being released. Release team ------------ For every release, there would be at least one release manager. We propose to rotate the release manager: rotation means it is not always the same person doing the dirty job, and it should also keep the release manager honest. References ========== * Proposed schedule for Gnome from Havoc Pennington (one of the core GTK and Gnome manager): http://mail.gnome.org/archives/gnome-hackers/2002-June/msg00041.html The proposed schedule is heavily based on this email * http://live.gnome.org/ReleasePlanning/Freezes numpy-1.8.2/doc/release/1.8.2-notes.rst0000664000175100017510000000145012371375326020550 0ustar vagrantvagrant00000000000000NumPy 1.8.2 Release Notes ************************* This is a bugfix only release in the 1.8.x series. Issues fixed ============ * gh-4836: partition produces wrong results for multiple selections in equal ranges * gh-4656: Make fftpack._raw_fft threadsafe * gh-4628: incorrect argument order to _copyto in in np.nanmax, np.nanmin * gh-4642: Hold GIL for converting dtypes types with fields * gh-4733: fix np.linalg.svd(b, compute_uv=False) * gh-4853: avoid unaligned simd load on reductions on i386 * gh-4722: Fix seg fault converting empty string to object * gh-4613: Fix lack of NULL check in array_richcompare * gh-4774: avoid unaligned access for strided byteswap * gh-650: Prevent division by zero when creating arrays from some buffers * gh-4602: ifort has issues with optimization flag O2, use O1 numpy-1.8.2/doc/release/1.6.1-notes.rst0000664000175100017510000000132012370216242020527 0ustar vagrantvagrant00000000000000NumPy 1.6.1 Release Notes ************************* This is a bugfix only release in the 1.6.x series. Issues Fixed ============ * #1834: einsum fails for specific shapes * #1837: einsum throws nan or freezes python for specific array shapes * #1838: object <-> structured type arrays regression * #1851: regression for SWIG based code in 1.6.0 * #1863: Buggy results when operating on array copied with astype() * #1870: Fix corner case of object array assignment * #1843: Py3k: fix error with recarray * #1885: nditer: Error in detecting double reduction loop * #1874: f2py: fix --include_paths bug * #1749: Fix ctypes.load_library() * #1895/1896: iter: writeonly operands weren't always being buffered correctly numpy-1.8.2/doc/release/1.3.0-notes.rst0000664000175100017510000002346612370216242020542 0ustar vagrantvagrant00000000000000NumPy 1.3.0 Release Notes ************************* This minor includes numerous bug fixes, official python 2.6 support, and several new features such as generalized ufuncs. Highlights ========== Python 2.6 support ~~~~~~~~~~~~~~~~~~ Python 2.6 is now supported on all previously supported platforms, including windows. http://www.python.org/dev/peps/pep-0361/ Generalized ufuncs ~~~~~~~~~~~~~~~~~~ There is a general need for looping over not only functions on scalars but also over functions on vectors (or arrays), as explained on http://scipy.org/scipy/numpy/wiki/GeneralLoopingFunctions. We propose to realize this concept by generalizing the universal functions (ufuncs), and provide a C implementation that adds ~500 lines to the numpy code base. In current (specialized) ufuncs, the elementary function is limited to element-by-element operations, whereas the generalized version supports "sub-array" by "sub-array" operations. The Perl vector library PDL provides a similar functionality and its terms are re-used in the following. Each generalized ufunc has information associated with it that states what the "core" dimensionality of the inputs is, as well as the corresponding dimensionality of the outputs (the element-wise ufuncs have zero core dimensions). The list of the core dimensions for all arguments is called the "signature" of a ufunc. For example, the ufunc numpy.add has signature "(),()->()" defining two scalar inputs and one scalar output. Another example is (see the GeneralLoopingFunctions page) the function inner1d(a,b) with a signature of "(i),(i)->()". This applies the inner product along the last axis of each input, but keeps the remaining indices intact. For example, where a is of shape (3,5,N) and b is of shape (5,N), this will return an output of shape (3,5). The underlying elementary function is called 3*5 times. In the signature, we specify one core dimension "(i)" for each input and zero core dimensions "()" for the output, since it takes two 1-d arrays and returns a scalar. By using the same name "i", we specify that the two corresponding dimensions should be of the same size (or one of them is of size 1 and will be broadcasted). The dimensions beyond the core dimensions are called "loop" dimensions. In the above example, this corresponds to (3,5). The usual numpy "broadcasting" rules apply, where the signature determines how the dimensions of each input/output object are split into core and loop dimensions: While an input array has a smaller dimensionality than the corresponding number of core dimensions, 1's are pre-pended to its shape. The core dimensions are removed from all inputs and the remaining dimensions are broadcasted; defining the loop dimensions. The output is given by the loop dimensions plus the output core dimensions. Experimental Windows 64 bits support ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Numpy can now be built on windows 64 bits (amd64 only, not IA64), with both MS compilers and mingw-w64 compilers: This is *highly experimental*: DO NOT USE FOR PRODUCTION USE. See INSTALL.txt, Windows 64 bits section for more information on limitations and how to build it by yourself. New features ============ Formatting issues ~~~~~~~~~~~~~~~~~ Float formatting is now handled by numpy instead of the C runtime: this enables locale independent formatting, more robust fromstring and related methods. Special values (inf and nan) are also more consistent across platforms (nan vs IND/NaN, etc...), and more consistent with recent python formatting work (in 2.6 and later). Nan handling in max/min ~~~~~~~~~~~~~~~~~~~~~~~ The maximum/minimum ufuncs now reliably propagate nans. If one of the arguments is a nan, then nan is retured. This affects np.min/np.max, amin/amax and the array methods max/min. New ufuncs fmax and fmin have been added to deal with non-propagating nans. Nan handling in sign ~~~~~~~~~~~~~~~~~~~~ The ufunc sign now returns nan for the sign of anan. New ufuncs ~~~~~~~~~~ #. fmax - same as maximum for integer types and non-nan floats. Returns the non-nan argument if one argument is nan and returns nan if both arguments are nan. #. fmin - same as minimum for integer types and non-nan floats. Returns the non-nan argument if one argument is nan and returns nan if both arguments are nan. #. deg2rad - converts degrees to radians, same as the radians ufunc. #. rad2deg - converts radians to degrees, same as the degrees ufunc. #. log2 - base 2 logarithm. #. exp2 - base 2 exponential. #. trunc - truncate floats to nearest integer towards zero. #. logaddexp - add numbers stored as logarithms and return the logarithm of the result. #. logaddexp2 - add numbers stored as base 2 logarithms and return the base 2 logarithm of the result result. Masked arrays ~~~~~~~~~~~~~ Several new features and bug fixes, including: * structured arrays should now be fully supported by MaskedArray (r6463, r6324, r6305, r6300, r6294...) * Minor bug fixes (r6356, r6352, r6335, r6299, r6298) * Improved support for __iter__ (r6326) * made baseclass, sharedmask and hardmask accesible to the user (but read-only) * doc update gfortran support on windows ~~~~~~~~~~~~~~~~~~~~~~~~~~~ Gfortran can now be used as a fortran compiler for numpy on windows, even when the C compiler is Visual Studio (VS 2005 and above; VS 2003 will NOT work). Gfortran + Visual studio does not work on windows 64 bits (but gcc + gfortran does). It is unclear whether it will be possible to use gfortran and visual studio at all on x64. Arch option for windows binary ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Automatic arch detection can now be bypassed from the command line for the superpack installed: numpy-1.3.0-superpack-win32.exe /arch=nosse will install a numpy which works on any x86, even if the running computer supports SSE set. Deprecated features =================== Histogram ~~~~~~~~~ The semantics of histogram has been modified to fix long-standing issues with outliers handling. The main changes concern #. the definition of the bin edges, now including the rightmost edge, and #. the handling of upper outliers, now ignored rather than tallied in the rightmost bin. The previous behavior is still accessible using `new=False`, but this is deprecated, and will be removed entirely in 1.4.0. Documentation changes ===================== A lot of documentation has been added. Both user guide and references can be built from sphinx. New C API ========= Multiarray API ~~~~~~~~~~~~~~ The following functions have been added to the multiarray C API: * PyArray_GetEndianness: to get runtime endianness Ufunc API ~~~~~~~~~ The following functions have been added to the ufunc API: * PyUFunc_FromFuncAndDataAndSignature: to declare a more general ufunc (generalized ufunc). New defines ~~~~~~~~~~~ New public C defines are available for ARCH specific code through numpy/npy_cpu.h: * NPY_CPU_X86: x86 arch (32 bits) * NPY_CPU_AMD64: amd64 arch (x86_64, NOT Itanium) * NPY_CPU_PPC: 32 bits ppc * NPY_CPU_PPC64: 64 bits ppc * NPY_CPU_SPARC: 32 bits sparc * NPY_CPU_SPARC64: 64 bits sparc * NPY_CPU_S390: S390 * NPY_CPU_IA64: ia64 * NPY_CPU_PARISC: PARISC New macros for CPU endianness has been added as well (see internal changes below for details): * NPY_BYTE_ORDER: integer * NPY_LITTLE_ENDIAN/NPY_BIG_ENDIAN defines Those provide portable alternatives to glibc endian.h macros for platforms without it. Portable NAN, INFINITY, etc... ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ npy_math.h now makes available several portable macro to get NAN, INFINITY: * NPY_NAN: equivalent to NAN, which is a GNU extension * NPY_INFINITY: equivalent to C99 INFINITY * NPY_PZERO, NPY_NZERO: positive and negative zero respectively Corresponding single and extended precision macros are available as well. All references to NAN, or home-grown computation of NAN on the fly have been removed for consistency. Internal changes ================ numpy.core math configuration revamp ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ This should make the porting to new platforms easier, and more robust. In particular, the configuration stage does not need to execute any code on the target platform, which is a first step toward cross-compilation. http://projects.scipy.org/numpy/browser/trunk/doc/neps/math_config_clean.txt umath refactor ~~~~~~~~~~~~~~ A lot of code cleanup for umath/ufunc code (charris). Improvements to build warnings ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Numpy can now build with -W -Wall without warnings http://projects.scipy.org/numpy/browser/trunk/doc/neps/warnfix.txt Separate core math library ~~~~~~~~~~~~~~~~~~~~~~~~~~ The core math functions (sin, cos, etc... for basic C types) have been put into a separate library; it acts as a compatibility layer, to support most C99 maths functions (real only for now). The library includes platform-specific fixes for various maths functions, such as using those versions should be more robust than using your platform functions directly. The API for existing functions is exactly the same as the C99 math functions API; the only difference is the npy prefix (npy_cos vs cos). The core library will be made available to any extension in 1.4.0. CPU arch detection ~~~~~~~~~~~~~~~~~~ npy_cpu.h defines numpy specific CPU defines, such as NPY_CPU_X86, etc... Those are portable across OS and toolchains, and set up when the header is parsed, so that they can be safely used even in the case of cross-compilation (the values is not set when numpy is built), or for multi-arch binaries (e.g. fat binaries on Max OS X). npy_endian.h defines numpy specific endianness defines, modeled on the glibc endian.h. NPY_BYTE_ORDER is equivalent to BYTE_ORDER, and one of NPY_LITTLE_ENDIAN or NPY_BIG_ENDIAN is defined. As for CPU archs, those are set when the header is parsed by the compiler, and as such can be used for cross-compilation and multi-arch binaries. numpy-1.8.2/doc/release/1.4.0-notes.rst0000664000175100017510000002207312370216242020534 0ustar vagrantvagrant00000000000000NumPy 1.4.0 Release Notes ************************* This minor includes numerous bug fixes, as well as a few new features. It is backward compatible with 1.3.0 release. Highlights ========== * New datetime dtype support to deal with dates in arrays * Faster import time * Extended array wrapping mechanism for ufuncs * New Neighborhood iterator (C-level only) * C99-like complex functions in npymath New features ============ Extended array wrapping mechanism for ufuncs ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ An __array_prepare__ method has been added to ndarray to provide subclasses greater flexibility to interact with ufuncs and ufunc-like functions. ndarray already provided __array_wrap__, which allowed subclasses to set the array type for the result and populate metadata on the way out of the ufunc (as seen in the implementation of MaskedArray). For some applications it is necessary to provide checks and populate metadata *on the way in*. __array_prepare__ is therefore called just after the ufunc has initialized the output array but before computing the results and populating it. This way, checks can be made and errors raised before operations which may modify data in place. Automatic detection of forward incompatibilities ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Previously, if an extension was built against a version N of NumPy, and used on a system with NumPy M < N, the import_array was successfull, which could cause crashes because the version M does not have a function in N. Starting from NumPy 1.4.0, this will cause a failure in import_array, so the error will be catched early on. New iterators ~~~~~~~~~~~~~ A new neighborhood iterator has been added to the C API. It can be used to iterate over the items in a neighborhood of an array, and can handle boundaries conditions automatically. Zero and one padding are available, as well as arbitrary constant value, mirror and circular padding. New polynomial support ~~~~~~~~~~~~~~~~~~~~~~ New modules chebyshev and polynomial have been added. The new polynomial module is not compatible with the current polynomial support in numpy, but is much like the new chebyshev module. The most noticeable difference to most will be that coefficients are specified from low to high power, that the low level functions do *not* work with the Chebyshev and Polynomial classes as arguements, and that the Chebyshev and Polynomial classes include a domain. Mapping between domains is a linear substitution and the two classes can be converted one to the other, allowing, for instance, a Chebyshev series in one domain to be expanded as a polynomial in another domain. The new classes should generally be used instead of the low level functions, the latter are provided for those who wish to build their own classes. The new modules are not automatically imported into the numpy namespace, they must be explicitly brought in with an "import numpy.polynomial" statement. New C API ~~~~~~~~~ The following C functions have been added to the C API: #. PyArray_GetNDArrayCFeatureVersion: return the *API* version of the loaded numpy. #. PyArray_Correlate2 - like PyArray_Correlate, but implements the usual definition of correlation. Inputs are not swapped, and conjugate is taken for complex arrays. #. PyArray_NeighborhoodIterNew - a new iterator to iterate over a neighborhood of a point, with automatic boundaries handling. It is documented in the iterators section of the C-API reference, and you can find some examples in the multiarray_test.c.src file in numpy.core. New ufuncs ~~~~~~~~~~ The following ufuncs have been added to the C API: #. copysign - return the value of the first argument with the sign copied from the second argument. #. nextafter - return the next representable floating point value of the first argument toward the second argument. New defines ~~~~~~~~~~~ The alpha processor is now defined and available in numpy/npy_cpu.h. The failed detection of the PARISC processor has been fixed. The defines are: #. NPY_CPU_HPPA: PARISC #. NPY_CPU_ALPHA: Alpha Testing ~~~~~~~ #. deprecated decorator: this decorator may be used to avoid cluttering testing output while testing DeprecationWarning is effectively raised by the decorated test. #. assert_array_almost_equal_nulps: new method to compare two arrays of floating point values. With this function, two values are considered close if there are not many representable floating point values in between, thus being more robust than assert_array_almost_equal when the values fluctuate a lot. #. assert_array_max_ulp: raise an assertion if there are more than N representable numbers between two floating point values. #. assert_warns: raise an AssertionError if a callable does not generate a warning of the appropriate class, without altering the warning state. Reusing npymath ~~~~~~~~~~~~~~~ In 1.3.0, we started putting portable C math routines in npymath library, so that people can use those to write portable extensions. Unfortunately, it was not possible to easily link against this library: in 1.4.0, support has been added to numpy.distutils so that 3rd party can reuse this library. See coremath documentation for more information. Improved set operations ~~~~~~~~~~~~~~~~~~~~~~~ In previous versions of NumPy some set functions (intersect1d, setxor1d, setdiff1d and setmember1d) could return incorrect results if the input arrays contained duplicate items. These now work correctly for input arrays with duplicates. setmember1d has been renamed to in1d, as with the change to accept arrays with duplicates it is no longer a set operation, and is conceptually similar to an elementwise version of the Python operator 'in'. All of these functions now accept the boolean keyword assume_unique. This is False by default, but can be set True if the input arrays are known not to contain duplicates, which can increase the functions' execution speed. Improvements ============ #. numpy import is noticeably faster (from 20 to 30 % depending on the platform and computer) #. The sort functions now sort nans to the end. * Real sort order is [R, nan] * Complex sort order is [R + Rj, R + nanj, nan + Rj, nan + nanj] Complex numbers with the same nan placements are sorted according to the non-nan part if it exists. #. The type comparison functions have been made consistent with the new sort order of nans. Searchsorted now works with sorted arrays containing nan values. #. Complex division has been made more resistent to overflow. #. Complex floor division has been made more resistent to overflow. Deprecations ============ The following functions are deprecated: #. correlate: it takes a new keyword argument old_behavior. When True (the default), it returns the same result as before. When False, compute the conventional correlation, and take the conjugate for complex arrays. The old behavior will be removed in NumPy 1.5, and raises a DeprecationWarning in 1.4. #. unique1d: use unique instead. unique1d raises a deprecation warning in 1.4, and will be removed in 1.5. #. intersect1d_nu: use intersect1d instead. intersect1d_nu raises a deprecation warning in 1.4, and will be removed in 1.5. #. setmember1d: use in1d instead. setmember1d raises a deprecation warning in 1.4, and will be removed in 1.5. The following raise errors: #. When operating on 0-d arrays, ``numpy.max`` and other functions accept only ``axis=0``, ``axis=-1`` and ``axis=None``. Using an out-of-bounds axes is an indication of a bug, so Numpy raises an error for these cases now. #. Specifying ``axis > MAX_DIMS`` is no longer allowed; Numpy raises now an error instead of behaving similarly as for ``axis=None``. Internal changes ================ Use C99 complex functions when available ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The numpy complex types are now guaranteed to be ABI compatible with C99 complex type, if availble on the platform. Moreoever, the complex ufunc now use the platform C99 functions intead of our own. split multiarray and umath source code ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The source code of multiarray and umath has been split into separate logic compilation units. This should make the source code more amenable for newcomers. Separate compilation ~~~~~~~~~~~~~~~~~~~~ By default, every file of multiarray (and umath) is merged into one for compilation as was the case before, but if NPY_SEPARATE_COMPILATION env variable is set to a non-negative value, experimental individual compilation of each file is enabled. This makes the compile/debug cycle much faster when working on core numpy. Separate core math library ~~~~~~~~~~~~~~~~~~~~~~~~~~ New functions which have been added: * npy_copysign * npy_nextafter * npy_cpack * npy_creal * npy_cimag * npy_cabs * npy_cexp * npy_clog * npy_cpow * npy_csqr * npy_ccos * npy_csin numpy-1.8.2/doc/release/1.6.0-notes.rst0000664000175100017510000001316112370216242020534 0ustar vagrantvagrant00000000000000NumPy 1.6.0 Release Notes ************************* This release includes several new features as well as numerous bug fixes and improved documentation. It is backward compatible with the 1.5.0 release, and supports Python 2.4 - 2.7 and 3.1 - 3.2. Highlights ========== * Re-introduction of datetime dtype support to deal with dates in arrays. * A new 16-bit floating point type. * A new iterator, which improves performance of many functions. New features ============ New 16-bit floating point type ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ This release adds support for the IEEE 754-2008 binary16 format, available as the data type ``numpy.half``. Within Python, the type behaves similarly to `float` or `double`, and C extensions can add support for it with the exposed half-float API. New iterator ~~~~~~~~~~~~ A new iterator has been added, replacing the functionality of the existing iterator and multi-iterator with a single object and API. This iterator works well with general memory layouts different from C or Fortran contiguous, and handles both standard NumPy and customized broadcasting. The buffering, automatic data type conversion, and optional output parameters, offered by ufuncs but difficult to replicate elsewhere, are now exposed by this iterator. Legendre, Laguerre, Hermite, HermiteE polynomials in ``numpy.polynomial`` ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Extend the number of polynomials available in the polynomial package. In addition, a new ``window`` attribute has been added to the classes in order to specify the range the ``domain`` maps to. This is mostly useful for the Laguerre, Hermite, and HermiteE polynomials whose natural domains are infinite and provides a more intuitive way to get the correct mapping of values without playing unnatural tricks with the domain. Fortran assumed shape array and size function support in ``numpy.f2py`` ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ F2py now supports wrapping Fortran 90 routines that use assumed shape arrays. Before such routines could be called from Python but the corresponding Fortran routines received assumed shape arrays as zero length arrays which caused unpredicted results. Thanks to Lorenz Hüdepohl for pointing out the correct way to interface routines with assumed shape arrays. In addition, f2py supports now automatic wrapping of Fortran routines that use two argument ``size`` function in dimension specifications. Other new functions ~~~~~~~~~~~~~~~~~~~ ``numpy.ravel_multi_index`` : Converts a multi-index tuple into an array of flat indices, applying boundary modes to the indices. ``numpy.einsum`` : Evaluate the Einstein summation convention. Using the Einstein summation convention, many common multi-dimensional array operations can be represented in a simple fashion. This function provides a way compute such summations. ``numpy.count_nonzero`` : Counts the number of non-zero elements in an array. ``numpy.result_type`` and ``numpy.min_scalar_type`` : These functions expose the underlying type promotion used by the ufuncs and other operations to determine the types of outputs. These improve upon the ``numpy.common_type`` and ``numpy.mintypecode`` which provide similar functionality but do not match the ufunc implementation. Changes ======= ``default error handling`` ~~~~~~~~~~~~~~~~~~~~~~~~~~ The default error handling has been change from ``print`` to ``warn`` for all except for ``underflow``, which remains as ``ignore``. ``numpy.distutils`` ~~~~~~~~~~~~~~~~~~~ Several new compilers are supported for building Numpy: the Portland Group Fortran compiler on OS X, the PathScale compiler suite and the 64-bit Intel C compiler on Linux. ``numpy.testing`` ~~~~~~~~~~~~~~~~~ The testing framework gained ``numpy.testing.assert_allclose``, which provides a more convenient way to compare floating point arrays than `assert_almost_equal`, `assert_approx_equal` and `assert_array_almost_equal`. ``C API`` ~~~~~~~~~ In addition to the APIs for the new iterator and half data type, a number of other additions have been made to the C API. The type promotion mechanism used by ufuncs is exposed via ``PyArray_PromoteTypes``, ``PyArray_ResultType``, and ``PyArray_MinScalarType``. A new enumeration ``NPY_CASTING`` has been added which controls what types of casts are permitted. This is used by the new functions ``PyArray_CanCastArrayTo`` and ``PyArray_CanCastTypeTo``. A more flexible way to handle conversion of arbitrary python objects into arrays is exposed by ``PyArray_GetArrayParamsFromObject``. Deprecated features =================== The "normed" keyword in ``numpy.histogram`` is deprecated. Its functionality will be replaced by the new "density" keyword. Removed features ================ ``numpy.fft`` ~~~~~~~~~~~~~ The functions `refft`, `refft2`, `refftn`, `irefft`, `irefft2`, `irefftn`, which were aliases for the same functions without the 'e' in the name, were removed. ``numpy.memmap`` ~~~~~~~~~~~~~~~~ The `sync()` and `close()` methods of memmap were removed. Use `flush()` and "del memmap" instead. ``numpy.lib`` ~~~~~~~~~~~~~ The deprecated functions ``numpy.unique1d``, ``numpy.setmember1d``, ``numpy.intersect1d_nu`` and ``numpy.lib.ufunclike.log2`` were removed. ``numpy.ma`` ~~~~~~~~~~~~ Several deprecated items were removed from the ``numpy.ma`` module:: * ``numpy.ma.MaskedArray`` "raw_data" method * ``numpy.ma.MaskedArray`` constructor "flag" keyword * ``numpy.ma.make_mask`` "flag" keyword * ``numpy.ma.allclose`` "fill_value" keyword ``numpy.distutils`` ~~~~~~~~~~~~~~~~~~~ The ``numpy.get_numpy_include`` function was removed, use ``numpy.get_include`` instead. numpy-1.8.2/doc/release/1.5.0-notes.rst0000664000175100017510000001062712370216242020537 0ustar vagrantvagrant00000000000000NumPy 1.5.0 Release Notes ************************* Highlights ========== Python 3 compatibility ~~~~~~~~~~~~~~~~~~~~~~ This is the first NumPy release which is compatible with Python 3. Support for Python 3 and Python 2 is done from a single code base. Extensive notes on changes can be found at ``_. Note that the Numpy testing framework relies on nose, which does not have a Python 3 compatible release yet. A working Python 3 branch of nose can be found at ``_ however. Porting of SciPy to Python 3 is expected to be completed soon. :pep:`3118` compatibility ~~~~~~~~~~~~~~~~~~~~~~~~~ The new buffer protocol described by PEP 3118 is fully supported in this version of Numpy. On Python versions >= 2.6 Numpy arrays expose the buffer interface, and array(), asarray() and other functions accept new-style buffers as input. New features ============ Warning on casting complex to real ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Numpy now emits a `numpy.ComplexWarning` when a complex number is cast into a real number. For example: >>> x = np.array([1,2,3]) >>> x[:2] = np.array([1+2j, 1-2j]) ComplexWarning: Casting complex values to real discards the imaginary part The cast indeed discards the imaginary part, and this may not be the intended behavior in all cases, hence the warning. This warning can be turned off in the standard way: >>> import warnings >>> warnings.simplefilter("ignore", np.ComplexWarning) Dot method for ndarrays ~~~~~~~~~~~~~~~~~~~~~~~ Ndarrays now have the dot product also as a method, which allows writing chains of matrix products as >>> a.dot(b).dot(c) instead of the longer alternative >>> np.dot(a, np.dot(b, c)) linalg.slogdet function ~~~~~~~~~~~~~~~~~~~~~~~ The slogdet function returns the sign and logarithm of the determinant of a matrix. Because the determinant may involve the product of many small/large values, the result is often more accurate than that obtained by simple multiplication. new header ~~~~~~~~~~ The new header file ndarraytypes.h contains the symbols from ndarrayobject.h that do not depend on the PY_ARRAY_UNIQUE_SYMBOL and NO_IMPORT/_ARRAY macros. Broadly, these symbols are types, typedefs, and enumerations; the array function calls are left in ndarrayobject.h. This allows users to include array-related types and enumerations without needing to concern themselves with the macro expansions and their side- effects. Changes ======= polynomial.polynomial ~~~~~~~~~~~~~~~~~~~~~ * The polyint and polyder functions now check that the specified number integrations or derivations is a non-negative integer. The number 0 is a valid value for both functions. * A degree method has been added to the Polynomial class. * A trimdeg method has been added to the Polynomial class. It operates like truncate except that the argument is the desired degree of the result, not the number of coefficients. * Polynomial.fit now uses None as the default domain for the fit. The default Polynomial domain can be specified by using [] as the domain value. * Weights can be used in both polyfit and Polynomial.fit * A linspace method has been added to the Polynomial class to ease plotting. * The polymulx function was added. polynomial.chebyshev ~~~~~~~~~~~~~~~~~~~~ * The chebint and chebder functions now check that the specified number integrations or derivations is a non-negative integer. The number 0 is a valid value for both functions. * A degree method has been added to the Chebyshev class. * A trimdeg method has been added to the Chebyshev class. It operates like truncate except that the argument is the desired degree of the result, not the number of coefficients. * Chebyshev.fit now uses None as the default domain for the fit. The default Chebyshev domain can be specified by using [] as the domain value. * Weights can be used in both chebfit and Chebyshev.fit * A linspace method has been added to the Chebyshev class to ease plotting. * The chebmulx function was added. * Added functions for the Chebyshev points of the first and second kind. histogram ~~~~~~~~~ After a two years transition period, the old behavior of the histogram function has been phased out, and the "new" keyword has been removed. correlate ~~~~~~~~~ The old behavior of correlate was deprecated in 1.4.0, the new behavior (the usual definition for cross-correlation) is now the default. numpy-1.8.2/doc/release/1.6.2-notes.rst0000664000175100017510000000633712370216242020545 0ustar vagrantvagrant00000000000000NumPy 1.6.2 Release Notes ************************* This is a bugfix release in the 1.6.x series. Due to the delay of the NumPy 1.7.0 release, this release contains far more fixes than a regular NumPy bugfix release. It also includes a number of documentation and build improvements. Issues fixed ============ ``numpy.core`` ~~~~~~~~~~~~~~ * #2063: make unique() return consistent index * #1138: allow creating arrays from empty buffers or empty slices * #1446: correct note about correspondence vstack and concatenate * #1149: make argmin() work for datetime * #1672: fix allclose() to work for scalar inf * #1747: make np.median() work for 0-D arrays * #1776: make complex division by zero to yield inf properly * #1675: add scalar support for the format() function * #1905: explicitly check for NaNs in allclose() * #1952: allow floating ddof in std() and var() * #1948: fix regression for indexing chararrays with empty list * #2017: fix type hashing * #2046: deleting array attributes causes segfault * #2033: a**2.0 has incorrect type * #2045: make attribute/iterator_element deletions not segfault * #2021: fix segfault in searchsorted() * #2073: fix float16 __array_interface__ bug ``numpy.lib`` ~~~~~~~~~~~~~ * #2048: break reference cycle in NpzFile * #1573: savetxt() now handles complex arrays * #1387: allow bincount() to accept empty arrays * #1899: fixed histogramdd() bug with empty inputs * #1793: fix failing npyio test under py3k * #1936: fix extra nesting for subarray dtypes * #1848: make tril/triu return the same dtype as the original array * #1918: use Py_TYPE to access ob_type, so it works also on Py3 ``numpy.distutils`` ~~~~~~~~~~~~~~~~~~~ * #1261: change compile flag on AIX from -O5 to -O3 * #1377: update HP compiler flags * #1383: provide better support for C++ code on HPUX * #1857: fix build for py3k + pip * BLD: raise a clearer warning in case of building without cleaning up first * BLD: follow build_ext coding convention in build_clib * BLD: fix up detection of Intel CPU on OS X in system_info.py * BLD: add support for the new X11 directory structure on Ubuntu & co. * BLD: add ufsparse to the libraries search path. * BLD: add 'pgfortran' as a valid compiler in the Portland Group * BLD: update version match regexp for IBM AIX Fortran compilers. ``numpy.random`` ~~~~~~~~~~~~~~~~ * BUG: Use npy_intp instead of long in mtrand Changes ======= ``numpy.f2py`` ~~~~~~~~~~~~~~ * ENH: Introduce new options extra_f77_compiler_args and extra_f90_compiler_args * BLD: Improve reporting of fcompiler value * BUG: Fix f2py test_kind.py test ``numpy.poly`` ~~~~~~~~~~~~~~ * ENH: Add some tests for polynomial printing * ENH: Add companion matrix functions * DOC: Rearrange the polynomial documents * BUG: Fix up links to classes * DOC: Add version added to some of the polynomial package modules * DOC: Document xxxfit functions in the polynomial package modules * BUG: The polynomial convenience classes let different types interact * DOC: Document the use of the polynomial convenience classes * DOC: Improve numpy reference documentation of polynomial classes * ENH: Improve the computation of polynomials from roots * STY: Code cleanup in polynomial [*]fromroots functions * DOC: Remove references to cast and NA, which were added in 1.7 numpy-1.8.2/doc/release/1.7.0-notes.rst0000664000175100017510000002625312370216242020543 0ustar vagrantvagrant00000000000000NumPy 1.7.0 Release Notes ************************* This release includes several new features as well as numerous bug fixes and refactorings. It supports Python 2.4 - 2.7 and 3.1 - 3.3 and is the last release that supports Python 2.4 - 2.5. Highlights ========== * ``where=`` parameter to ufuncs (allows the use of boolean arrays to choose where a computation should be done) * ``vectorize`` improvements (added 'excluded' and 'cache' keyword, general cleanup and bug fixes) * ``numpy.random.choice`` (random sample generating function) Compatibility notes =================== In a future version of numpy, the functions np.diag, np.diagonal, and the diagonal method of ndarrays will return a view onto the original array, instead of producing a copy as they do now. This makes a difference if you write to the array returned by any of these functions. To facilitate this transition, numpy 1.7 produces a FutureWarning if it detects that you may be attempting to write to such an array. See the documentation for np.diagonal for details. Similar to np.diagonal above, in a future version of numpy, indexing a record array by a list of field names will return a view onto the original array, instead of producing a copy as they do now. As with np.diagonal, numpy 1.7 produces a FutureWarning if it detects that you may be attempting to write to such an array. See the documentation for array indexing for details. In a future version of numpy, the default casting rule for UFunc out= parameters will be changed from 'unsafe' to 'same_kind'. (This also applies to in-place operations like a += b, which is equivalent to np.add(a, b, out=a).) Most usages which violate the 'same_kind' rule are likely bugs, so this change may expose previously undetected errors in projects that depend on NumPy. In this version of numpy, such usages will continue to succeed, but will raise a DeprecationWarning. Full-array boolean indexing has been optimized to use a different, optimized code path. This code path should produce the same results, but any feedback about changes to your code would be appreciated. Attempting to write to a read-only array (one with ``arr.flags.writeable`` set to ``False``) used to raise either a RuntimeError, ValueError, or TypeError inconsistently, depending on which code path was taken. It now consistently raises a ValueError. The .reduce functions evaluate some reductions in a different order than in previous versions of NumPy, generally providing higher performance. Because of the nature of floating-point arithmetic, this may subtly change some results, just as linking NumPy to a different BLAS implementations such as MKL can. If upgrading from 1.5, then generally in 1.6 and 1.7 there have been substantial code added and some code paths altered, particularly in the areas of type resolution and buffered iteration over universal functions. This might have an impact on your code particularly if you relied on accidental behavior in the past. New features ============ Reduction UFuncs Generalize axis= Parameter ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Any ufunc.reduce function call, as well as other reductions like sum, prod, any, all, max and min support the ability to choose a subset of the axes to reduce over. Previously, one could say axis=None to mean all the axes or axis=# to pick a single axis. Now, one can also say axis=(#,#) to pick a list of axes for reduction. Reduction UFuncs New keepdims= Parameter ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ There is a new keepdims= parameter, which if set to True, doesn't throw away the reduction axes but instead sets them to have size one. When this option is set, the reduction result will broadcast correctly to the original operand which was reduced. Datetime support ~~~~~~~~~~~~~~~~ .. note:: The datetime API is *experimental* in 1.7.0, and may undergo changes in future versions of NumPy. There have been a lot of fixes and enhancements to datetime64 compared to NumPy 1.6: * the parser is quite strict about only accepting ISO 8601 dates, with a few convenience extensions * converts between units correctly * datetime arithmetic works correctly * business day functionality (allows the datetime to be used in contexts where only certain days of the week are valid) The notes in `doc/source/reference/arrays.datetime.rst `_ (also available in the online docs at `arrays.datetime.html `_) should be consulted for more details. Custom formatter for printing arrays ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ See the new ``formatter`` parameter of the ``numpy.set_printoptions`` function. New function numpy.random.choice ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ A generic sampling function has been added which will generate samples from a given array-like. The samples can be with or without replacement, and with uniform or given non-uniform probabilities. New function isclose ~~~~~~~~~~~~~~~~~~~~ Returns a boolean array where two arrays are element-wise equal within a tolerance. Both relative and absolute tolerance can be specified. Preliminary multi-dimensional support in the polynomial package ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Axis keywords have been added to the integration and differentiation functions and a tensor keyword was added to the evaluation functions. These additions allow multi-dimensional coefficient arrays to be used in those functions. New functions for evaluating 2-D and 3-D coefficient arrays on grids or sets of points were added together with 2-D and 3-D pseudo-Vandermonde matrices that can be used for fitting. Ability to pad rank-n arrays ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ A pad module containing functions for padding n-dimensional arrays has been added. The various private padding functions are exposed as options to a public 'pad' function. Example:: pad(a, 5, mode='mean') Current modes are ``constant``, ``edge``, ``linear_ramp``, ``maximum``, ``mean``, ``median``, ``minimum``, ``reflect``, ``symmetric``, ``wrap``, and ````. New argument to searchsorted ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The function searchsorted now accepts a 'sorter' argument that is a permutation array that sorts the array to search. Build system ~~~~~~~~~~~~ Added experimental support for the AArch64 architecture. C API ~~~~~ New function ``PyArray_RequireWriteable`` provides a consistent interface for checking array writeability -- any C code which works with arrays whose WRITEABLE flag is not known to be True a priori, should make sure to call this function before writing. NumPy C Style Guide added (``doc/C_STYLE_GUIDE.rst.txt``). Changes ======= General ~~~~~~~ The function np.concatenate tries to match the layout of its input arrays. Previously, the layout did not follow any particular reason, and depended in an undesirable way on the particular axis chosen for concatenation. A bug was also fixed which silently allowed out of bounds axis arguments. The ufuncs logical_or, logical_and, and logical_not now follow Python's behavior with object arrays, instead of trying to call methods on the objects. For example the expression (3 and 'test') produces the string 'test', and now np.logical_and(np.array(3, 'O'), np.array('test', 'O')) produces 'test' as well. The ``.base`` attribute on ndarrays, which is used on views to ensure that the underlying array owning the memory is not deallocated prematurely, now collapses out references when you have a view-of-a-view. For example:: a = np.arange(10) b = a[1:] c = b[1:] In numpy 1.6, ``c.base`` is ``b``, and ``c.base.base`` is ``a``. In numpy 1.7, ``c.base`` is ``a``. To increase backwards compatibility for software which relies on the old behaviour of ``.base``, we only 'skip over' objects which have exactly the same type as the newly created view. This makes a difference if you use ``ndarray`` subclasses. For example, if we have a mix of ``ndarray`` and ``matrix`` objects which are all views on the same original ``ndarray``:: a = np.arange(10) b = np.asmatrix(a) c = b[0, 1:] d = c[0, 1:] then ``d.base`` will be ``b``. This is because ``d`` is a ``matrix`` object, and so the collapsing process only continues so long as it encounters other ``matrix`` objects. It considers ``c``, ``b``, and ``a`` in that order, and ``b`` is the last entry in that list which is a ``matrix`` object. Casting Rules ~~~~~~~~~~~~~ Casting rules have undergone some changes in corner cases, due to the NA-related work. In particular for combinations of scalar+scalar: * the `longlong` type (`q`) now stays `longlong` for operations with any other number (`? b h i l q p B H I`), previously it was cast as `int_` (`l`). The `ulonglong` type (`Q`) now stays as `ulonglong` instead of `uint` (`L`). * the `timedelta64` type (`m`) can now be mixed with any integer type (`b h i l q p B H I L Q P`), previously it raised `TypeError`. For array + scalar, the above rules just broadcast except the case when the array and scalars are unsigned/signed integers, then the result gets converted to the array type (of possibly larger size) as illustrated by the following examples:: >>> (np.zeros((2,), dtype=np.uint8) + np.int16(257)).dtype dtype('uint16') >>> (np.zeros((2,), dtype=np.int8) + np.uint16(257)).dtype dtype('int16') >>> (np.zeros((2,), dtype=np.int16) + np.uint32(2**17)).dtype dtype('int32') Whether the size gets increased depends on the size of the scalar, for example:: >>> (np.zeros((2,), dtype=np.uint8) + np.int16(255)).dtype dtype('uint8') >>> (np.zeros((2,), dtype=np.uint8) + np.int16(256)).dtype dtype('uint16') Also a ``complex128`` scalar + ``float32`` array is cast to ``complex64``. In NumPy 1.7 the `datetime64` type (`M`) must be constructed by explicitly specifying the type as the second argument (e.g. ``np.datetime64(2000, 'Y')``). Deprecations ============ General ~~~~~~~ Specifying a custom string formatter with a `_format` array attribute is deprecated. The new `formatter` keyword in ``numpy.set_printoptions`` or ``numpy.array2string`` can be used instead. The deprecated imports in the polynomial package have been removed. ``concatenate`` now raises DepractionWarning for 1D arrays if ``axis != 0``. Versions of numpy < 1.7.0 ignored axis argument value for 1D arrays. We allow this for now, but in due course we will raise an error. C-API ~~~~~ Direct access to the fields of PyArrayObject* has been deprecated. Direct access has been recommended against for many releases. Expect similar deprecations for PyArray_Descr* and other core objects in the future as preparation for NumPy 2.0. The macros in old_defines.h are deprecated and will be removed in the next major release (>= 2.0). The sed script tools/replace_old_macros.sed can be used to replace these macros with the newer versions. You can test your code against the deprecated C API by #defining NPY_NO_DEPRECATED_API to the target version number, for example NPY_1_7_API_VERSION, before including any NumPy headers. The ``NPY_CHAR`` member of the ``NPY_TYPES`` enum is deprecated and will be removed in NumPy 1.8. See the discussion at `gh-2801 `_ for more details. numpy-1.8.2/doc/release/1.8.0-notes.rst0000664000175100017510000004313412370216242020541 0ustar vagrantvagrant00000000000000NumPy 1.8.0 Release Notes ************************* This release supports Python 2.6 -2.7 and 3.2 - 3.3. Highlights ========== * New, no 2to3, Python 2 and Python 3 are supported by a common code base. * New, gufuncs for linear algebra, enabling operations on stacked arrays. * New, inplace fancy indexing for ufuncs with the ``.at`` method. * New, ``partition`` function, partial sorting via selection for fast median. * New, ``nanmean``, ``nanvar``, and ``nanstd`` functions skipping NaNs. * New, ``full`` and ``full_like`` functions to create value initialized arrays. * New, ``PyUFunc_RegisterLoopForDescr``, better ufunc support for user dtypes. * Numerous performance improvements in many areas. Dropped Support =============== Support for Python versions 2.4 and 2.5 has been dropped, Support for SCons has been removed. Future Changes ============== The Datetime64 type remains experimental in this release. In 1.9 there will probably be some changes to make it more useable. The diagonal method currently returns a new array and raises a FutureWarning. In 1.9 it will return a readonly view. Multiple field selection from a array of structured type currently returns a new array and raises a FutureWarning. In 1.9 it will return a readonly view. The numpy/oldnumeric and numpy/numarray compatibility modules will be removed in 1.9. Compatibility notes =================== The doc/sphinxext content has been moved into its own github repository, and is included in numpy as a submodule. See the instructions in doc/HOWTO_BUILD_DOCS.rst.txt for how to access the content. .. _numpydoc: https://github.com/numpy/numpydoc The hash function of numpy.void scalars has been changed. Previously the pointer to the data was hashed as an integer. Now, the hash function uses the tuple-hash algorithm to combine the hash functions of the elements of the scalar, but only if the scalar is read-only. Numpy has switched its build system to using 'separate compilation' by default. In previous releases this was supported, but not default. This should produce the same results as the old system, but if you're trying to do something complicated like link numpy statically or using an unusual compiler, then it's possible you will encounter problems. If so, please file a bug and as a temporary workaround you can re-enable the old build system by exporting the shell variable NPY_SEPARATE_COMPILATION=0. For the AdvancedNew iterator the ``oa_ndim`` flag should now be -1 to indicate that no ``op_axes`` and ``itershape`` are passed in. The ``oa_ndim == 0`` case, now indicates a 0-D iteration and ``op_axes`` being NULL and the old usage is deprecated. This does not effect the ``NpyIter_New`` or ``NpyIter_MultiNew`` functions. The functions nanargmin and nanargmax now return np.iinfo['intp'].min for the index in all-NaN slices. Previously the functions would raise a ValueError for array returns and NaN for scalar returns. NPY_RELAXED_STRIDES_CHECKING ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ There is a new compile time environment variable ``NPY_RELAXED_STRIDES_CHECKING``. If this variable is set to 1, then numpy will consider more arrays to be C- or F-contiguous -- for example, it becomes possible to have a column vector which is considered both C- and F-contiguous simultaneously. The new definition is more accurate, allows for faster code that makes fewer unnecessary copies, and simplifies numpy's code internally. However, it may also break third-party libraries that make too-strong assumptions about the stride values of C- and F-contiguous arrays. (It is also currently known that this breaks Cython code using memoryviews, which will be fixed in Cython.) THIS WILL BECOME THE DEFAULT IN A FUTURE RELEASE, SO PLEASE TEST YOUR CODE NOW AGAINST NUMPY BUILT WITH:: NPY_RELAXED_STRIDES_CHECKING=1 python setup.py install You can check whether NPY_RELAXED_STRIDES_CHECKING is in effect by running:: np.ones((10, 1), order="C").flags.f_contiguous This will be ``True`` if relaxed strides checking is enabled, and ``False`` otherwise. The typical problem we've seen so far is C code that works with C-contiguous arrays, and assumes that the itemsize can be accessed by looking at the last element in the ``PyArray_STRIDES(arr)`` array. When relaxed strides are in effect, this is not true (and in fact, it never was true in some corner cases). Instead, use ``PyArray_ITEMSIZE(arr)``. For more information check the "Internal memory layout of an ndarray" section in the documentation. Binary operations with non-arrays as second argument ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Binary operations of the form `` * `` where ```` declares an ``__array_priority__`` higher than that of ```` will now unconditionally return *NotImplemented*, giving ```` a chance to handle the operation. Previously, `NotImplemented` would only be returned if ```` actually implemented the reversed operation, and after a (potentially expensive) array conversion of ```` had been attempted. (`bug `_, `pull request `_) Function `median` used with `overwrite_input` only partially sorts array ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ If `median` is used with `overwrite_input` option the input array will now only be partially sorted instead of fully sorted. Fix to financial.npv ~~~~~~~~~~~~~~~~~~~~ The npv function had a bug. Contrary to what the documentation stated, it summed from indexes ``1`` to ``M`` instead of from ``0`` to ``M - 1``. The fix changes the returned value. The mirr function called the npv function, but worked around the problem, so that was also fixed and the return value of the mirr function remains unchanged. Runtime warnings when comparing NaN numbers ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Comparing ``NaN`` floating point numbers now raises the ``invalid`` runtime warning. If a ``NaN`` is expected the warning can be ignored using np.errstate. E.g.:: with np.errstate(invalid='ignore'): operation() New Features ============ Support for linear algebra on stacked arrays ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The gufunc machinery is now used for np.linalg, allowing operations on stacked arrays and vectors. For example:: >>> a array([[[ 1., 1.], [ 0., 1.]], [[ 1., 1.], [ 0., 1.]]]) >>> np.linalg.inv(a) array([[[ 1., -1.], [ 0., 1.]], [[ 1., -1.], [ 0., 1.]]]) In place fancy indexing for ufuncs ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The function ``at`` has been added to ufunc objects to allow in place ufuncs with no buffering when fancy indexing is used. For example, the following will increment the first and second items in the array, and will increment the third item twice: ``numpy.add.at(arr, [0, 1, 2, 2], 1)`` This is what many have mistakenly thought ``arr[[0, 1, 2, 2]] += 1`` would do, but that does not work as the incremented value of ``arr[2]`` is simply copied into the third slot in ``arr`` twice, not incremented twice. New functions `partition` and `argpartition` ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ New functions to partially sort arrays via a selection algorithm. A ``partition`` by index ``k`` moves the ``k`` smallest element to the front of an array. All elements before ``k`` are then smaller or equal than the value in position ``k`` and all elements following ``k`` are then greater or equal than the value in position ``k``. The ordering of the values within these bounds is undefined. A sequence of indices can be provided to sort all of them into their sorted position at once iterative partitioning. This can be used to efficiently obtain order statistics like median or percentiles of samples. ``partition`` has a linear time complexity of ``O(n)`` while a full sort has ``O(n log(n))``. New functions `nanmean`, `nanvar` and `nanstd` ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ New nan aware statistical functions are added. In these functions the results are what would be obtained if nan values were ommited from all computations. New functions `full` and `full_like` ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ New convenience functions to create arrays filled with a specific value; complementary to the existing `zeros` and `zeros_like` functions. IO compatibility with large files ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Large NPZ files >2GB can be loaded on 64-bit systems. Building against OpenBLAS ~~~~~~~~~~~~~~~~~~~~~~~~~ It is now possible to build numpy against OpenBLAS by editing site.cfg. New constant ~~~~~~~~~~~~ Euler's constant is now exposed in numpy as euler_gamma. New modes for qr ~~~~~~~~~~~~~~~~ New modes 'complete', 'reduced', and 'raw' have been added to the qr factorization and the old 'full' and 'economic' modes are deprecated. The 'reduced' mode replaces the old 'full' mode and is the default as was the 'full' mode, so backward compatibility can be maintained by not specifying the mode. The 'complete' mode returns a full dimensional factorization, which can be useful for obtaining a basis for the orthogonal complement of the range space. The 'raw' mode returns arrays that contain the Householder reflectors and scaling factors that can be used in the future to apply q without needing to convert to a matrix. The 'economic' mode is simply deprecated, there isn't much use for it and it isn't any more efficient than the 'raw' mode. New `invert` argument to `in1d` ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The function `in1d` now accepts a `invert` argument which, when `True`, causes the returned array to be inverted. Advanced indexing using `np.newaxis` ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ It is now possible to use `np.newaxis`/`None` together with index arrays instead of only in simple indices. This means that ``array[np.newaxis, [0, 1]]`` will now work as expected and select the first two rows while prepending a new axis to the array. C-API ~~~~~ New ufuncs can now be registered with builtin input types and a custom output type. Before this change, NumPy wouldn't be able to find the right ufunc loop function when the ufunc was called from Python, because the ufunc loop signature matching logic wasn't looking at the output operand type. Now the correct ufunc loop is found, as long as the user provides an output argument with the correct output type. runtests.py ~~~~~~~~~~~ A simple test runner script ``runtests.py`` was added. It also builds Numpy via ``setup.py build`` and can be used to run tests easily during development. Improvements ============ IO performance improvements ~~~~~~~~~~~~~~~~~~~~~~~~~~~ Performance in reading large files was improved by chunking (see also IO compatibility). Performance improvements to `pad` ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The `pad` function has a new implementation, greatly improving performance for all inputs except `mode=` (retained for backwards compatibility). Scaling with dimensionality is dramatically improved for rank >= 4. Performance improvements to `isnan`, `isinf`, `isfinite` and `byteswap` ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ `isnan`, `isinf`, `isfinite` and `byteswap` have been improved to take advantage of compiler builtins to avoid expensive calls to libc. This improves performance of these operations by about a factor of two on gnu libc systems. Performance improvements via SSE2 vectorization ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Several functions have been optimized to make use of SSE2 CPU SIMD instructions. * Float32 and float64: * base math (`add`, `subtract`, `divide`, `multiply`) * `sqrt` * `minimum/maximum` * `absolute` * Bool: * `logical_or` * `logical_and` * `logical_not` This improves performance of these operations up to 4x/2x for float32/float64 and up to 10x for bool depending on the location of the data in the CPU caches. The performance gain is greatest for in-place operations. In order to use the improved functions the SSE2 instruction set must be enabled at compile time. It is enabled by default on x86_64 systems. On x86_32 with a capable CPU it must be enabled by passing the appropriate flag to the CFLAGS build variable (-msse2 with gcc). Performance improvements to `median` ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ `median` is now implemented in terms of `partition` instead of `sort` which reduces its time complexity from O(n log(n)) to O(n). If used with the `overwrite_input` option the array will now only be partially sorted instead of fully sorted. Overrideable operand flags in ufunc C-API ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When creating a ufunc, the default ufunc operand flags can be overridden via the new op_flags attribute of the ufunc object. For example, to set the operand flag for the first input to read/write: PyObject \*ufunc = PyUFunc_FromFuncAndData(...); ufunc->op_flags[0] = NPY_ITER_READWRITE; This allows a ufunc to perform an operation in place. Also, global nditer flags can be overridden via the new iter_flags attribute of the ufunc object. For example, to set the reduce flag for a ufunc: ufunc->iter_flags = NPY_ITER_REDUCE_OK; Changes ======= General ~~~~~~~ The function np.take now allows 0-d arrays as indices. The separate compilation mode is now enabled by default. Several changes to np.insert and np.delete: * Previously, negative indices and indices that pointed past the end of the array were simply ignored. Now, this will raise a Future or Deprecation Warning. In the future they will be treated like normal indexing treats them -- negative indices will wrap around, and out-of-bound indices will generate an error. * Previously, boolean indices were treated as if they were integers (always referring to either the 0th or 1st item in the array). In the future, they will be treated as masks. In this release, they raise a FutureWarning warning of this coming change. * In Numpy 1.7. np.insert already allowed the syntax `np.insert(arr, 3, [1,2,3])` to insert multiple items at a single position. In Numpy 1.8. this is also possible for `np.insert(arr, [3], [1, 2, 3])`. Padded regions from np.pad are now correctly rounded, not truncated. C-API Array Additions ~~~~~~~~~~~~~~~~~~~~~ Four new functions have been added to the array C-API. * PyArray_Partition * PyArray_ArgPartition * PyArray_SelectkindConverter * PyDataMem_NEW_ZEROED C-API Ufunc Additions ~~~~~~~~~~~~~~~~~~~~~ One new function has been added to the ufunc C-API that allows to register an inner loop for user types using the descr. * PyUFunc_RegisterLoopForDescr C-API Developer Improvements ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The ``PyArray_Type`` instance creation function ``tp_new`` now uses ``tp_basicsize`` to determine how much memory to allocate. In previous releases only ``sizeof(PyArrayObject)`` bytes of memory were allocated, often requiring C-API subtypes to reimplement ``tp_new``. Deprecations ============ The 'full' and 'economic' modes of qr factorization are deprecated. General ~~~~~~~ The use of non-integer for indices and most integer arguments has been deprecated. Previously float indices and function arguments such as axes or shapes were truncated to integers without warning. For example `arr.reshape(3., -1)` or `arr[0.]` will trigger a deprecation warning in NumPy 1.8., and in some future version of NumPy they will raise an error. Authors ======= This release contains work by the following people who contributed at least one patch to this release. The names are in alphabetical order by first name: * 87 * Adam Ginsburg + * Adam Griffiths + * Alexander Belopolsky + * Alex Barth + * Alex Ford + * Andreas Hilboll + * Andreas Kloeckner + * Andreas Schwab + * Andrew Horton + * argriffing + * Arink Verma + * Bago Amirbekian + * Bartosz Telenczuk + * bebert218 + * Benjamin Root + * Bill Spotz + * Bradley M. Froehle * Carwyn Pelley + * Charles Harris * Chris * Christian Brueffer + * Christoph Dann + * Christoph Gohlke * Dan Hipschman + * Daniel + * Dan Miller + * daveydave400 + * David Cournapeau * David Warde-Farley * Denis Laxalde * dmuellner + * Edward Catmur + * Egor Zindy + * endolith * Eric Firing * Eric Fode * Eric Moore + * Eric Price + * Fazlul Shahriar + * Félix Hartmann + * Fernando Perez * Frank B + * Frank Breitling + * Frederic * Gabriel * GaelVaroquaux * Guillaume Gay + * Han Genuit * HaroldMills + * hklemm + * jamestwebber + * Jason Madden + * Jay Bourque * jeromekelleher + * Jesús Gómez + * jmozmoz + * jnothman + * Johannes Schönberger + * John Benediktsson + * John Salvatier + * John Stechschulte + * Jonathan Waltman + * Joon Ro + * Jos de Kloe + * Joseph Martinot-Lagarde + * Josh Warner (Mac) + * Jostein Bø Fløystad + * Juan Luis Cano Rodríguez + * Julian Taylor + * Julien Phalip + * K.-Michael Aye + * Kumar Appaiah + * Lars Buitinck * Leon Weber + * Luis Pedro Coelho * Marcin Juszkiewicz * Mark Wiebe * Marten van Kerkwijk + * Martin Baeuml + * Martin Spacek * Martin Teichmann + * Matt Davis + * Matthew Brett * Maximilian Albert + * m-d-w + * Michael Droettboom * mwtoews + * Nathaniel J. Smith * Nicolas Scheffer + * Nils Werner + * ochoadavid + * OndÅ™ej ÄŒertík * ovillellas + * Paul Ivanov * Pauli Virtanen * peterjc * Ralf Gommers * Raul Cota + * Richard Hattersley + * Robert Costa + * Robert Kern * Rob Ruana + * Ronan Lamy * Sandro Tosi * Sascha Peilicke + * Sebastian Berg * Skipper Seabold * Stefan van der Walt * Steve + * Takafumi Arakaki + * Thomas Robitaille + * Tomas Tomecek + * Travis E. Oliphant * Valentin Haenel * Vladimir Rutsky + * Warren Weckesser * Yaroslav Halchenko * Yury V. Zaytsev + A total of 119 people contributed to this release. People with a "+" by their names contributed a patch for the first time. numpy-1.8.2/doc/release/1.8.1-notes.rst0000664000175100017510000001077612370216242020550 0ustar vagrantvagrant00000000000000NumPy 1.8.1 Release Notes ************************* This is a bugfix only release in the 1.8.x series. Issues fixed ============ * gh-4276: Fix mean, var, std methods for object arrays * gh-4262: remove insecure mktemp usage * gh-2385: absolute(complex(inf)) raises invalid warning in python3 * gh-4024: Sequence assignment doesn't raise exception on shape mismatch * gh-4027: Fix chunked reading of strings longer than BUFFERSIZE * gh-4109: Fix object scalar return type of 0-d array indices * gh-4018: fix missing check for memory allocation failure in ufuncs * gh-4156: high order linalg.norm discards imaginary elements of complex arrays * gh-4144: linalg: norm fails on longdouble, signed int * gh-4094: fix NaT handling in _strided_to_strided_string_to_datetime * gh-4051: fix uninitialized use in _strided_to_strided_string_to_datetime * gh-4093: Loading compressed .npz file fails under Python 2.6.6 * gh-4138: segfault with non-native endian memoryview in python 3.4 * gh-4123: Fix missing NULL check in lexsort * gh-4170: fix native-only long long check in memoryviews * gh-4187: Fix large file support on 32 bit * gh-4152: fromfile: ensure file handle positions are in sync in python3 * gh-4176: clang compatibility: Typos in conversion_utils * gh-4223: Fetching a non-integer item caused array return * gh-4197: fix minor memory leak in memoryview failure case * gh-4206: fix build with single-threaded python * gh-4220: add versionadded:: 1.8.0 to ufunc.at docstring * gh-4267: improve handling of memory allocation failure * gh-4267: fix use of capi without gil in ufunc.at * gh-4261: Detect vendor versions of GNU Compilers * gh-4253: IRR was returning nan instead of valid negative answer * gh-4254: fix unnecessary byte order flag change for byte arrays * gh-3263: numpy.random.shuffle clobbers mask of a MaskedArray * gh-4270: np.random.shuffle not work with flexible dtypes * gh-3173: Segmentation fault when 'size' argument to random.multinomial * gh-2799: allow using unique with lists of complex * gh-3504: fix linspace truncation for integer array scalar * gh-4191: get_info('openblas') does not read libraries key * gh-3348: Access violation in _descriptor_from_pep3118_format * gh-3175: segmentation fault with numpy.array() from bytearray * gh-4266: histogramdd - wrong result for entries very close to last boundary * gh-4408: Fix stride_stricks.as_strided function for object arrays * gh-4225: fix log1p and exmp1 return for np.inf on windows compiler builds * gh-4359: Fix infinite recursion in str.format of flex arrays * gh-4145: Incorrect shape of broadcast result with the exponent operator * gh-4483: Fix commutativity of {dot,multiply,inner}(scalar, matrix_of_objs) * gh-4466: Delay npyiter size check when size may change * gh-4485: Buffered stride was erroneously marked fixed * gh-4354: byte_bounds fails with datetime dtypes * gh-4486: segfault/error converting from/to high-precision datetime64 objects * gh-4428: einsum(None, None, None, None) causes segfault * gh-4134: uninitialized use for for size 1 object reductions Changes ======= NDIter ~~~~~~ When ``NpyIter_RemoveAxis`` is now called, the iterator range will be reset. When a multi index is being tracked and an iterator is not buffered, it is possible to use ``NpyIter_RemoveAxis``. In this case an iterator can shrink in size. Because the total size of an iterator is limited, the iterator may be too large before these calls. In this case its size will be set to ``-1`` and an error issued not at construction time but when removing the multi index, setting the iterator range, or getting the next function. This has no effect on currently working code, but highlights the necessity of checking for an error return if these conditions can occur. In most cases the arrays being iterated are as large as the iterator so that such a problem cannot occur. Optional reduced verbosity for np.distutils ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Set ``numpy.distutils.system_info.system_info.verbosity = 0`` and then calls to ``numpy.distutils.system_info.get_info('blas_opt')`` will not print anything on the output. This is mostly for other packages using numpy.distutils. Deprecations ============ C-API ~~~~~ The utility function npy_PyFile_Dup and npy_PyFile_DupClose are broken by the internal buffering python 3 applies to its file objects. To fix this two new functions npy_PyFile_Dup2 and npy_PyFile_DupClose2 are declared in npy_3kcompat.h and the old functions are deprecated. Due to the fragile nature of these functions it is recommended to instead use the python API when possible. numpy-1.8.2/doc/release/1.7.1-notes.rst0000664000175100017510000000177012370216242020541 0ustar vagrantvagrant00000000000000NumPy 1.7.1 Release Notes ************************* This is a bugfix only release in the 1.7.x series. It supports Python 2.4 - 2.7 and 3.1 - 3.3 and is the last series that supports Python 2.4 - 2.5. Issues fixed ============ * gh-2973: Fix `1` is printed during numpy.test() * gh-2983: BUG: gh-2969: Backport memory leak fix 80b3a34. * gh-3007: Backport gh-3006 * gh-2984: Backport fix complex polynomial fit * gh-2982: BUG: Make nansum work with booleans. * gh-2985: Backport large sort fixes * gh-3039: Backport object take * gh-3105: Backport nditer fix op axes initialization * gh-3108: BUG: npy-pkg-config ini files were missing after Bento build. * gh-3124: BUG: PyArray_LexSort allocates too much temporary memory. * gh-3131: BUG: Exported f2py_size symbol prevents linking multiple f2py modules. * gh-3117: Backport gh-2992 * gh-3135: DOC: Add mention of PyArray_SetBaseObject stealing a reference * gh-3134: DOC: Fix typo in fft docs (the indexing variable is 'm', not 'n'). * gh-3136: Backport #3128 numpy-1.8.2/doc/release/1.7.2-notes.rst0000664000175100017510000000550712370216242020544 0ustar vagrantvagrant00000000000000NumPy 1.7.2 Release Notes ************************* This is a bugfix only release in the 1.7.x series. It supports Python 2.4 - 2.7 and 3.1 - 3.3 and is the last series that supports Python 2.4 - 2.5. Issues fixed ============ * gh-3153: Do not reuse nditer buffers when not filled enough * gh-3192: f2py crashes with UnboundLocalError exception * gh-442: Concatenate with axis=None now requires equal number of array elements * gh-2485: Fix for astype('S') string truncate issue * gh-3312: bug in count_nonzero * gh-2684: numpy.ma.average casts complex to float under certain conditions * gh-2403: masked array with named components does not behave as expected * gh-2495: np.ma.compress treated inputs in wrong order * gh-576: add __len__ method to ma.mvoid * gh-3364: reduce performance regression of mmap slicing * gh-3421: fix non-swapping strided copies in GetStridedCopySwap * gh-3373: fix small leak in datetime metadata initialization * gh-2791: add platform specific python include directories to search paths * gh-3168: fix undefined function and add integer divisions * gh-3301: memmap does not work with TemporaryFile in python3 * gh-3057: distutils.misc_util.get_shared_lib_extension returns wrong debug extension * gh-3472: add module extensions to load_library search list * gh-3324: Make comparison function (gt, ge, ...) respect __array_priority__ * gh-3497: np.insert behaves incorrectly with argument 'axis=-1' * gh-3541: make preprocessor tests consistent in halffloat.c * gh-3458: array_ass_boolean_subscript() writes 'non-existent' data to array * gh-2892: Regression in ufunc.reduceat with zero-sized index array * gh-3608: Regression when filling struct from tuple * gh-3701: add support for Python 3.4 ast.NameConstant * gh-3712: do not assume that GIL is enabled in xerbla * gh-3712: fix LAPACK error handling in lapack_litemodule * gh-3728: f2py fix decref on wrong object * gh-3743: Hash changed signature in Python 3.3 * gh-3793: scalar int hashing broken on 64 bit python3 * gh-3160: SandboxViolation easyinstalling 1.7.0 on Mac OS X 10.8.3 * gh-3871: npy_math.h has invalid isinf for Solaris with SUNWspro12.2 * gh-2561: Disable check for oldstyle classes in python3 * gh-3900: Ensure NotImplemented is passed on in MaskedArray ufunc's * gh-2052: del scalar subscript causes segfault * gh-3832: fix a few uninitialized uses and memleaks * gh-3971: f2py changed string.lowercase to string.ascii_lowercase for python3 * gh-3480: numpy.random.binomial raised ValueError for n == 0 * gh-3992: hypot(inf, 0) shouldn't raise a warning, hypot(inf, inf) wrong result * gh-4018: Segmentation fault dealing with very large arrays * gh-4094: fix NaT handling in _strided_to_strided_string_to_datetime * gh-4051: fix uninitialized use in _strided_to_strided_string_to_datetime * gh-4123: lexsort segfault * gh-4141: Fix a few issues that show up with python 3.4b1 numpy-1.8.2/doc/postprocess.py0000775000175100017510000000271112370216242017532 0ustar vagrantvagrant00000000000000#!/usr/bin/env python """ %prog MODE FILES... Post-processes HTML and Latex files output by Sphinx. MODE is either 'html' or 'tex'. """ from __future__ import division, absolute_import, print_function import re import optparse import io def main(): p = optparse.OptionParser(__doc__) options, args = p.parse_args() if len(args) < 1: p.error('no mode given') mode = args.pop(0) if mode not in ('html', 'tex'): p.error('unknown mode %s' % mode) for fn in args: f = io.open(fn, 'r', encoding="utf-8") try: if mode == 'html': lines = process_html(fn, f.readlines()) elif mode == 'tex': lines = process_tex(f.readlines()) finally: f.close() f = io.open(fn, 'w', encoding="utf-8") f.write("".join(lines)) f.close() def process_html(fn, lines): return lines def process_tex(lines): """ Remove unnecessary section titles from the LaTeX file. """ new_lines = [] for line in lines: if (line.startswith(r'\section{numpy.') or line.startswith(r'\subsection{numpy.') or line.startswith(r'\subsubsection{numpy.') or line.startswith(r'\paragraph{numpy.') or line.startswith(r'\subparagraph{numpy.') ): pass # skip! else: new_lines.append(line) return new_lines if __name__ == "__main__": main() numpy-1.8.2/doc/sphinxext/0000775000175100017510000000000012371375427016636 5ustar vagrantvagrant00000000000000numpy-1.8.2/doc/sphinxext/MANIFEST.in0000664000175100017510000000006412370216247020365 0ustar vagrantvagrant00000000000000recursive-include numpydoc/tests *.py include *.txt numpy-1.8.2/doc/sphinxext/.git0000664000175100017510000000007512370216246017414 0ustar vagrantvagrant00000000000000gitdir: /home/vagrant/repos/numpy/.git/modules/doc/sphinxext numpy-1.8.2/doc/sphinxext/README.txt0000664000175100017510000000260212370216247020325 0ustar vagrantvagrant00000000000000===================================== numpydoc -- Numpy's Sphinx extensions ===================================== Numpy's documentation uses several custom extensions to Sphinx. These are shipped in this ``numpydoc`` package, in case you want to make use of them in third-party projects. The following extensions are available: - ``numpydoc``: support for the Numpy docstring format in Sphinx, and add the code description directives ``np:function``, ``np-c:function``, etc. that support the Numpy docstring syntax. - ``numpydoc.traitsdoc``: For gathering documentation about Traits attributes. - ``numpydoc.plot_directive``: Adaptation of Matplotlib's ``plot::`` directive. Note that this implementation may still undergo severe changes or eventually be deprecated. numpydoc ======== Numpydoc inserts a hook into Sphinx's autodoc that converts docstrings following the Numpy/Scipy format to a form palatable to Sphinx. Options ------- The following options can be set in conf.py: - numpydoc_use_plots: bool Whether to produce ``plot::`` directives for Examples sections that contain ``import matplotlib``. - numpydoc_show_class_members: bool Whether to show all members of a class in the Methods and Attributes sections automatically. - numpydoc_edit_link: bool (DEPRECATED -- edit your HTML template instead) Whether to insert an edit link after docstrings. numpy-1.8.2/doc/sphinxext/.gitignore0000664000175100017510000000005712370216247020621 0ustar vagrantvagrant00000000000000*~ .#* *.bak *.pyc *.pyo *.egg-info build dist numpy-1.8.2/doc/sphinxext/LICENSE.txt0000664000175100017510000001350712370216247020460 0ustar vagrantvagrant00000000000000------------------------------------------------------------------------------- The files - numpydoc.py - docscrape.py - docscrape_sphinx.py - phantom_import.py have the following license: Copyright (C) 2008 Stefan van der Walt , Pauli Virtanen Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ------------------------------------------------------------------------------- The files - compiler_unparse.py - comment_eater.py - traitsdoc.py have the following license: This software is OSI Certified Open Source Software. OSI Certified is a certification mark of the Open Source Initiative. Copyright (c) 2006, Enthought, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Enthought, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ------------------------------------------------------------------------------- The file - plot_directive.py originates from Matplotlib (http://matplotlib.sf.net/) which has the following license: Copyright (c) 2002-2008 John D. Hunter; All Rights Reserved. 1. This LICENSE AGREEMENT is between John D. Hunter (“JDHâ€), and the Individual or Organization (“Licenseeâ€) accessing and otherwise using matplotlib software in source or binary form and its associated documentation. 2. Subject to the terms and conditions of this License Agreement, JDH hereby grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce, analyze, test, perform and/or display publicly, prepare derivative works, distribute, and otherwise use matplotlib 0.98.3 alone or in any derivative version, provided, however, that JDH’s License Agreement and JDH’s notice of copyright, i.e., “Copyright (c) 2002-2008 John D. Hunter; All Rights Reserved†are retained in matplotlib 0.98.3 alone or in any derivative version prepared by Licensee. 3. In the event Licensee prepares a derivative work that is based on or incorporates matplotlib 0.98.3 or any part thereof, and wants to make the derivative work available to others as provided herein, then Licensee hereby agrees to include in any such work a brief summary of the changes made to matplotlib 0.98.3. 4. JDH is making matplotlib 0.98.3 available to Licensee on an “AS IS†basis. JDH MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, JDH MAKES NO AND DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF MATPLOTLIB 0.98.3 WILL NOT INFRINGE ANY THIRD PARTY RIGHTS. 5. JDH SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF MATPLOTLIB 0.98.3 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING MATPLOTLIB 0.98.3, OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. 6. This License Agreement will automatically terminate upon a material breach of its terms and conditions. 7. Nothing in this License Agreement shall be deemed to create any relationship of agency, partnership, or joint venture between JDH and Licensee. This License Agreement does not grant permission to use JDH trademarks or trade name in a trademark sense to endorse or promote products or services of Licensee, or any third party. 8. By copying, installing or otherwise using matplotlib 0.98.3, Licensee agrees to be bound by the terms and conditions of this License Agreement. numpy-1.8.2/doc/sphinxext/numpydoc/0000775000175100017510000000000012371375427020474 5ustar vagrantvagrant00000000000000numpy-1.8.2/doc/sphinxext/numpydoc/phantom_import.py0000664000175100017510000001333612370216247024105 0ustar vagrantvagrant00000000000000""" ============== phantom_import ============== Sphinx extension to make directives from ``sphinx.ext.autodoc`` and similar extensions to use docstrings loaded from an XML file. This extension loads an XML file in the Pydocweb format [1] and creates a dummy module that contains the specified docstrings. This can be used to get the current docstrings from a Pydocweb instance without needing to rebuild the documented module. .. [1] http://code.google.com/p/pydocweb """ from __future__ import division, absolute_import, print_function import imp, sys, compiler, types, os, inspect, re def setup(app): app.connect('builder-inited', initialize) app.add_config_value('phantom_import_file', None, True) def initialize(app): fn = app.config.phantom_import_file if (fn and os.path.isfile(fn)): print("[numpydoc] Phantom importing modules from", fn, "...") import_phantom_module(fn) #------------------------------------------------------------------------------ # Creating 'phantom' modules from an XML description #------------------------------------------------------------------------------ def import_phantom_module(xml_file): """ Insert a fake Python module to sys.modules, based on a XML file. The XML file is expected to conform to Pydocweb DTD. The fake module will contain dummy objects, which guarantee the following: - Docstrings are correct. - Class inheritance relationships are correct (if present in XML). - Function argspec is *NOT* correct (even if present in XML). Instead, the function signature is prepended to the function docstring. - Class attributes are *NOT* correct; instead, they are dummy objects. Parameters ---------- xml_file : str Name of an XML file to read """ import lxml.etree as etree object_cache = {} tree = etree.parse(xml_file) root = tree.getroot() # Sort items so that # - Base classes come before classes inherited from them # - Modules come before their contents all_nodes = dict([(n.attrib['id'], n) for n in root]) def _get_bases(node, recurse=False): bases = [x.attrib['ref'] for x in node.findall('base')] if recurse: j = 0 while True: try: b = bases[j] except IndexError: break if b in all_nodes: bases.extend(_get_bases(all_nodes[b])) j += 1 return bases type_index = ['module', 'class', 'callable', 'object'] def base_cmp(a, b): x = cmp(type_index.index(a.tag), type_index.index(b.tag)) if x != 0: return x if a.tag == 'class' and b.tag == 'class': a_bases = _get_bases(a, recurse=True) b_bases = _get_bases(b, recurse=True) x = cmp(len(a_bases), len(b_bases)) if x != 0: return x if a.attrib['id'] in b_bases: return -1 if b.attrib['id'] in a_bases: return 1 return cmp(a.attrib['id'].count('.'), b.attrib['id'].count('.')) nodes = root.getchildren() nodes.sort(base_cmp) # Create phantom items for node in nodes: name = node.attrib['id'] doc = (node.text or '').decode('string-escape') + "\n" if doc == "\n": doc = "" # create parent, if missing parent = name while True: parent = '.'.join(parent.split('.')[:-1]) if not parent: break if parent in object_cache: break obj = imp.new_module(parent) object_cache[parent] = obj sys.modules[parent] = obj # create object if node.tag == 'module': obj = imp.new_module(name) obj.__doc__ = doc sys.modules[name] = obj elif node.tag == 'class': bases = [object_cache[b] for b in _get_bases(node) if b in object_cache] bases.append(object) init = lambda self: None init.__doc__ = doc obj = type(name, tuple(bases), {'__doc__': doc, '__init__': init}) obj.__name__ = name.split('.')[-1] elif node.tag == 'callable': funcname = node.attrib['id'].split('.')[-1] argspec = node.attrib.get('argspec') if argspec: argspec = re.sub('^[^(]*', '', argspec) doc = "%s%s\n\n%s" % (funcname, argspec, doc) obj = lambda: 0 obj.__argspec_is_invalid_ = True if sys.version_info[0] >= 3: obj.__name__ = funcname else: obj.func_name = funcname obj.__name__ = name obj.__doc__ = doc if inspect.isclass(object_cache[parent]): obj.__objclass__ = object_cache[parent] else: class Dummy(object): pass obj = Dummy() obj.__name__ = name obj.__doc__ = doc if inspect.isclass(object_cache[parent]): obj.__get__ = lambda: None object_cache[name] = obj if parent: if inspect.ismodule(object_cache[parent]): obj.__module__ = parent setattr(object_cache[parent], name.split('.')[-1], obj) # Populate items for node in root: obj = object_cache.get(node.attrib['id']) if obj is None: continue for ref in node.findall('ref'): if node.tag == 'class': if ref.attrib['ref'].startswith(node.attrib['id'] + '.'): setattr(obj, ref.attrib['name'], object_cache.get(ref.attrib['ref'])) else: setattr(obj, ref.attrib['name'], object_cache.get(ref.attrib['ref'])) numpy-1.8.2/doc/sphinxext/numpydoc/linkcode.py0000664000175100017510000000471312370216247022634 0ustar vagrantvagrant00000000000000# -*- coding: utf-8 -*- """ linkcode ~~~~~~~~ Add external links to module code in Python object descriptions. :copyright: Copyright 2007-2011 by the Sphinx team, see AUTHORS. :license: BSD, see LICENSE for details. """ from __future__ import division, absolute_import, print_function import warnings import collections warnings.warn("This extension has been accepted to Sphinx upstream. " "Use the version from there (Sphinx >= 1.2) " "https://bitbucket.org/birkenfeld/sphinx/pull-request/47/sphinxextlinkcode", FutureWarning, stacklevel=1) from docutils import nodes from sphinx import addnodes from sphinx.locale import _ from sphinx.errors import SphinxError class LinkcodeError(SphinxError): category = "linkcode error" def doctree_read(app, doctree): env = app.builder.env resolve_target = getattr(env.config, 'linkcode_resolve', None) if not isinstance(env.config.linkcode_resolve, collections.Callable): raise LinkcodeError( "Function `linkcode_resolve` is not given in conf.py") domain_keys = dict( py=['module', 'fullname'], c=['names'], cpp=['names'], js=['object', 'fullname'], ) for objnode in doctree.traverse(addnodes.desc): domain = objnode.get('domain') uris = set() for signode in objnode: if not isinstance(signode, addnodes.desc_signature): continue # Convert signode to a specified format info = {} for key in domain_keys.get(domain, []): value = signode.get(key) if not value: value = '' info[key] = value if not info: continue # Call user code to resolve the link uri = resolve_target(domain, info) if not uri: # no source continue if uri in uris or not uri: # only one link per name, please continue uris.add(uri) onlynode = addnodes.only(expr='html') onlynode += nodes.reference('', '', internal=False, refuri=uri) onlynode[0] += nodes.inline('', _('[source]'), classes=['viewcode-link']) signode += onlynode def setup(app): app.connect('doctree-read', doctree_read) app.add_config_value('linkcode_resolve', None, '') numpy-1.8.2/doc/sphinxext/numpydoc/docscrape.py0000664000175100017510000003714712370216247023016 0ustar vagrantvagrant00000000000000"""Extract reference documentation from the NumPy source tree. """ from __future__ import division, absolute_import, print_function import inspect import textwrap import re import pydoc from warnings import warn import collections class Reader(object): """A line-based string reader. """ def __init__(self, data): """ Parameters ---------- data : str String with lines separated by '\n'. """ if isinstance(data,list): self._str = data else: self._str = data.split('\n') # store string as list of lines self.reset() def __getitem__(self, n): return self._str[n] def reset(self): self._l = 0 # current line nr def read(self): if not self.eof(): out = self[self._l] self._l += 1 return out else: return '' def seek_next_non_empty_line(self): for l in self[self._l:]: if l.strip(): break else: self._l += 1 def eof(self): return self._l >= len(self._str) def read_to_condition(self, condition_func): start = self._l for line in self[start:]: if condition_func(line): return self[start:self._l] self._l += 1 if self.eof(): return self[start:self._l+1] return [] def read_to_next_empty_line(self): self.seek_next_non_empty_line() def is_empty(line): return not line.strip() return self.read_to_condition(is_empty) def read_to_next_unindented_line(self): def is_unindented(line): return (line.strip() and (len(line.lstrip()) == len(line))) return self.read_to_condition(is_unindented) def peek(self,n=0): if self._l + n < len(self._str): return self[self._l + n] else: return '' def is_empty(self): return not ''.join(self._str).strip() class NumpyDocString(object): def __init__(self, docstring, config={}): docstring = textwrap.dedent(docstring).split('\n') self._doc = Reader(docstring) self._parsed_data = { 'Signature': '', 'Summary': [''], 'Extended Summary': [], 'Parameters': [], 'Returns': [], 'Raises': [], 'Warns': [], 'Other Parameters': [], 'Attributes': [], 'Methods': [], 'See Also': [], 'Notes': [], 'Warnings': [], 'References': '', 'Examples': '', 'index': {} } self._parse() def __getitem__(self,key): return self._parsed_data[key] def __setitem__(self,key,val): if key not in self._parsed_data: warn("Unknown section %s" % key) else: self._parsed_data[key] = val def _is_at_section(self): self._doc.seek_next_non_empty_line() if self._doc.eof(): return False l1 = self._doc.peek().strip() # e.g. Parameters if l1.startswith('.. index::'): return True l2 = self._doc.peek(1).strip() # ---------- or ========== return l2.startswith('-'*len(l1)) or l2.startswith('='*len(l1)) def _strip(self,doc): i = 0 j = 0 for i,line in enumerate(doc): if line.strip(): break for j,line in enumerate(doc[::-1]): if line.strip(): break return doc[i:len(doc)-j] def _read_to_next_section(self): section = self._doc.read_to_next_empty_line() while not self._is_at_section() and not self._doc.eof(): if not self._doc.peek(-1).strip(): # previous line was empty section += [''] section += self._doc.read_to_next_empty_line() return section def _read_sections(self): while not self._doc.eof(): data = self._read_to_next_section() name = data[0].strip() if name.startswith('..'): # index section yield name, data[1:] elif len(data) < 2: yield StopIteration else: yield name, self._strip(data[2:]) def _parse_param_list(self,content): r = Reader(content) params = [] while not r.eof(): header = r.read().strip() if ' : ' in header: arg_name, arg_type = header.split(' : ')[:2] else: arg_name, arg_type = header, '' desc = r.read_to_next_unindented_line() desc = dedent_lines(desc) params.append((arg_name,arg_type,desc)) return params _name_rgx = re.compile(r"^\s*(:(?P\w+):`(?P[a-zA-Z0-9_.-]+)`|" r" (?P[a-zA-Z0-9_.-]+))\s*", re.X) def _parse_see_also(self, content): """ func_name : Descriptive text continued text another_func_name : Descriptive text func_name1, func_name2, :meth:`func_name`, func_name3 """ items = [] def parse_item_name(text): """Match ':role:`name`' or 'name'""" m = self._name_rgx.match(text) if m: g = m.groups() if g[1] is None: return g[3], None else: return g[2], g[1] raise ValueError("%s is not a item name" % text) def push_item(name, rest): if not name: return name, role = parse_item_name(name) items.append((name, list(rest), role)) del rest[:] current_func = None rest = [] for line in content: if not line.strip(): continue m = self._name_rgx.match(line) if m and line[m.end():].strip().startswith(':'): push_item(current_func, rest) current_func, line = line[:m.end()], line[m.end():] rest = [line.split(':', 1)[1].strip()] if not rest[0]: rest = [] elif not line.startswith(' '): push_item(current_func, rest) current_func = None if ',' in line: for func in line.split(','): if func.strip(): push_item(func, []) elif line.strip(): current_func = line elif current_func is not None: rest.append(line.strip()) push_item(current_func, rest) return items def _parse_index(self, section, content): """ .. index: default :refguide: something, else, and more """ def strip_each_in(lst): return [s.strip() for s in lst] out = {} section = section.split('::') if len(section) > 1: out['default'] = strip_each_in(section[1].split(','))[0] for line in content: line = line.split(':') if len(line) > 2: out[line[1]] = strip_each_in(line[2].split(',')) return out def _parse_summary(self): """Grab signature (if given) and summary""" if self._is_at_section(): return # If several signatures present, take the last one while True: summary = self._doc.read_to_next_empty_line() summary_str = " ".join([s.strip() for s in summary]).strip() if re.compile('^([\w., ]+=)?\s*[\w\.]+\(.*\)$').match(summary_str): self['Signature'] = summary_str if not self._is_at_section(): continue break if summary is not None: self['Summary'] = summary if not self._is_at_section(): self['Extended Summary'] = self._read_to_next_section() def _parse(self): self._doc.reset() self._parse_summary() for (section,content) in self._read_sections(): if not section.startswith('..'): section = ' '.join([s.capitalize() for s in section.split(' ')]) if section in ('Parameters', 'Returns', 'Raises', 'Warns', 'Other Parameters', 'Attributes', 'Methods'): self[section] = self._parse_param_list(content) elif section.startswith('.. index::'): self['index'] = self._parse_index(section, content) elif section == 'See Also': self['See Also'] = self._parse_see_also(content) else: self[section] = content # string conversion routines def _str_header(self, name, symbol='-'): return [name, len(name)*symbol] def _str_indent(self, doc, indent=4): out = [] for line in doc: out += [' '*indent + line] return out def _str_signature(self): if self['Signature']: return [self['Signature'].replace('*','\*')] + [''] else: return [''] def _str_summary(self): if self['Summary']: return self['Summary'] + [''] else: return [] def _str_extended_summary(self): if self['Extended Summary']: return self['Extended Summary'] + [''] else: return [] def _str_param_list(self, name): out = [] if self[name]: out += self._str_header(name) for param,param_type,desc in self[name]: if param_type: out += ['%s : %s' % (param, param_type)] else: out += [param] out += self._str_indent(desc) out += [''] return out def _str_section(self, name): out = [] if self[name]: out += self._str_header(name) out += self[name] out += [''] return out def _str_see_also(self, func_role): if not self['See Also']: return [] out = [] out += self._str_header("See Also") last_had_desc = True for func, desc, role in self['See Also']: if role: link = ':%s:`%s`' % (role, func) elif func_role: link = ':%s:`%s`' % (func_role, func) else: link = "`%s`_" % func if desc or last_had_desc: out += [''] out += [link] else: out[-1] += ", %s" % link if desc: out += self._str_indent([' '.join(desc)]) last_had_desc = True else: last_had_desc = False out += [''] return out def _str_index(self): idx = self['index'] out = [] out += ['.. index:: %s' % idx.get('default','')] for section, references in idx.items(): if section == 'default': continue out += [' :%s: %s' % (section, ', '.join(references))] return out def __str__(self, func_role=''): out = [] out += self._str_signature() out += self._str_summary() out += self._str_extended_summary() for param_list in ('Parameters', 'Returns', 'Other Parameters', 'Raises', 'Warns'): out += self._str_param_list(param_list) out += self._str_section('Warnings') out += self._str_see_also(func_role) for s in ('Notes','References','Examples'): out += self._str_section(s) for param_list in ('Attributes', 'Methods'): out += self._str_param_list(param_list) out += self._str_index() return '\n'.join(out) def indent(str,indent=4): indent_str = ' '*indent if str is None: return indent_str lines = str.split('\n') return '\n'.join(indent_str + l for l in lines) def dedent_lines(lines): """Deindent a list of lines maximally""" return textwrap.dedent("\n".join(lines)).split("\n") def header(text, style='-'): return text + '\n' + style*len(text) + '\n' class FunctionDoc(NumpyDocString): def __init__(self, func, role='func', doc=None, config={}): self._f = func self._role = role # e.g. "func" or "meth" if doc is None: if func is None: raise ValueError("No function or docstring given") doc = inspect.getdoc(func) or '' NumpyDocString.__init__(self, doc) if not self['Signature'] and func is not None: func, func_name = self.get_func() try: # try to read signature argspec = inspect.getargspec(func) argspec = inspect.formatargspec(*argspec) argspec = argspec.replace('*','\*') signature = '%s%s' % (func_name, argspec) except TypeError as e: signature = '%s()' % func_name self['Signature'] = signature def get_func(self): func_name = getattr(self._f, '__name__', self.__class__.__name__) if inspect.isclass(self._f): func = getattr(self._f, '__call__', self._f.__init__) else: func = self._f return func, func_name def __str__(self): out = '' func, func_name = self.get_func() signature = self['Signature'].replace('*', '\*') roles = {'func': 'function', 'meth': 'method'} if self._role: if self._role not in roles: print("Warning: invalid role %s" % self._role) out += '.. %s:: %s\n \n\n' % (roles.get(self._role,''), func_name) out += super(FunctionDoc, self).__str__(func_role=self._role) return out class ClassDoc(NumpyDocString): extra_public_methods = ['__call__'] def __init__(self, cls, doc=None, modulename='', func_doc=FunctionDoc, config={}): if not inspect.isclass(cls) and cls is not None: raise ValueError("Expected a class or None, but got %r" % cls) self._cls = cls if modulename and not modulename.endswith('.'): modulename += '.' self._mod = modulename if doc is None: if cls is None: raise ValueError("No class or documentation string given") doc = pydoc.getdoc(cls) NumpyDocString.__init__(self, doc) if config.get('show_class_members', True): def splitlines_x(s): if not s: return [] else: return s.splitlines() for field, items in [('Methods', self.methods), ('Attributes', self.properties)]: if not self[field]: self[field] = [ (name, '', splitlines_x(pydoc.getdoc(getattr(self._cls, name)))) for name in sorted(items)] @property def methods(self): if self._cls is None: return [] return [name for name,func in inspect.getmembers(self._cls) if ((not name.startswith('_') or name in self.extra_public_methods) and isinstance(func, collections.Callable))] @property def properties(self): if self._cls is None: return [] return [name for name,func in inspect.getmembers(self._cls) if not name.startswith('_') and (func is None or isinstance(func, property) or inspect.isgetsetdescriptor(func))] numpy-1.8.2/doc/sphinxext/numpydoc/compiler_unparse.py0000664000175100017510000006024412370216247024414 0ustar vagrantvagrant00000000000000""" Turn compiler.ast structures back into executable python code. The unparse method takes a compiler.ast tree and transforms it back into valid python code. It is incomplete and currently only works for import statements, function calls, function definitions, assignments, and basic expressions. Inspired by python-2.5-svn/Demo/parser/unparse.py fixme: We may want to move to using _ast trees because the compiler for them is about 6 times faster than compiler.compile. """ from __future__ import division, absolute_import, print_function import sys from compiler.ast import Const, Name, Tuple, Div, Mul, Sub, Add if sys.version_info[0] >= 3: from io import StringIO else: from StringIO import StringIO def unparse(ast, single_line_functions=False): s = StringIO() UnparseCompilerAst(ast, s, single_line_functions) return s.getvalue().lstrip() op_precedence = { 'compiler.ast.Power':3, 'compiler.ast.Mul':2, 'compiler.ast.Div':2, 'compiler.ast.Add':1, 'compiler.ast.Sub':1 } class UnparseCompilerAst: """ Methods in this class recursively traverse an AST and output source code for the abstract syntax; original formatting is disregarged. """ ######################################################################### # object interface. ######################################################################### def __init__(self, tree, file = sys.stdout, single_line_functions=False): """ Unparser(tree, file=sys.stdout) -> None. Print the source for tree to file. """ self.f = file self._single_func = single_line_functions self._do_indent = True self._indent = 0 self._dispatch(tree) self._write("\n") self.f.flush() ######################################################################### # Unparser private interface. ######################################################################### ### format, output, and dispatch methods ################################ def _fill(self, text = ""): "Indent a piece of text, according to the current indentation level" if self._do_indent: self._write("\n"+" "*self._indent + text) else: self._write(text) def _write(self, text): "Append a piece of text to the current line." self.f.write(text) def _enter(self): "Print ':', and increase the indentation." self._write(": ") self._indent += 1 def _leave(self): "Decrease the indentation level." self._indent -= 1 def _dispatch(self, tree): "_dispatcher function, _dispatching tree type T to method _T." if isinstance(tree, list): for t in tree: self._dispatch(t) return meth = getattr(self, "_"+tree.__class__.__name__) if tree.__class__.__name__ == 'NoneType' and not self._do_indent: return meth(tree) ######################################################################### # compiler.ast unparsing methods. # # There should be one method per concrete grammar type. They are # organized in alphabetical order. ######################################################################### def _Add(self, t): self.__binary_op(t, '+') def _And(self, t): self._write(" (") for i, node in enumerate(t.nodes): self._dispatch(node) if i != len(t.nodes)-1: self._write(") and (") self._write(")") def _AssAttr(self, t): """ Handle assigning an attribute of an object """ self._dispatch(t.expr) self._write('.'+t.attrname) def _Assign(self, t): """ Expression Assignment such as "a = 1". This only handles assignment in expressions. Keyword assignment is handled separately. """ self._fill() for target in t.nodes: self._dispatch(target) self._write(" = ") self._dispatch(t.expr) if not self._do_indent: self._write('; ') def _AssName(self, t): """ Name on left hand side of expression. Treat just like a name on the right side of an expression. """ self._Name(t) def _AssTuple(self, t): """ Tuple on left hand side of an expression. """ # _write each elements, separated by a comma. for element in t.nodes[:-1]: self._dispatch(element) self._write(", ") # Handle the last one without writing comma last_element = t.nodes[-1] self._dispatch(last_element) def _AugAssign(self, t): """ +=,-=,*=,/=,**=, etc. operations """ self._fill() self._dispatch(t.node) self._write(' '+t.op+' ') self._dispatch(t.expr) if not self._do_indent: self._write(';') def _Bitand(self, t): """ Bit and operation. """ for i, node in enumerate(t.nodes): self._write("(") self._dispatch(node) self._write(")") if i != len(t.nodes)-1: self._write(" & ") def _Bitor(self, t): """ Bit or operation """ for i, node in enumerate(t.nodes): self._write("(") self._dispatch(node) self._write(")") if i != len(t.nodes)-1: self._write(" | ") def _CallFunc(self, t): """ Function call. """ self._dispatch(t.node) self._write("(") comma = False for e in t.args: if comma: self._write(", ") else: comma = True self._dispatch(e) if t.star_args: if comma: self._write(", ") else: comma = True self._write("*") self._dispatch(t.star_args) if t.dstar_args: if comma: self._write(", ") else: comma = True self._write("**") self._dispatch(t.dstar_args) self._write(")") def _Compare(self, t): self._dispatch(t.expr) for op, expr in t.ops: self._write(" " + op + " ") self._dispatch(expr) def _Const(self, t): """ A constant value such as an integer value, 3, or a string, "hello". """ self._dispatch(t.value) def _Decorators(self, t): """ Handle function decorators (eg. @has_units) """ for node in t.nodes: self._dispatch(node) def _Dict(self, t): self._write("{") for i, (k, v) in enumerate(t.items): self._dispatch(k) self._write(": ") self._dispatch(v) if i < len(t.items)-1: self._write(", ") self._write("}") def _Discard(self, t): """ Node for when return value is ignored such as in "foo(a)". """ self._fill() self._dispatch(t.expr) def _Div(self, t): self.__binary_op(t, '/') def _Ellipsis(self, t): self._write("...") def _From(self, t): """ Handle "from xyz import foo, bar as baz". """ # fixme: Are From and ImportFrom handled differently? self._fill("from ") self._write(t.modname) self._write(" import ") for i, (name,asname) in enumerate(t.names): if i != 0: self._write(", ") self._write(name) if asname is not None: self._write(" as "+asname) def _Function(self, t): """ Handle function definitions """ if t.decorators is not None: self._fill("@") self._dispatch(t.decorators) self._fill("def "+t.name + "(") defaults = [None] * (len(t.argnames) - len(t.defaults)) + list(t.defaults) for i, arg in enumerate(zip(t.argnames, defaults)): self._write(arg[0]) if arg[1] is not None: self._write('=') self._dispatch(arg[1]) if i < len(t.argnames)-1: self._write(', ') self._write(")") if self._single_func: self._do_indent = False self._enter() self._dispatch(t.code) self._leave() self._do_indent = True def _Getattr(self, t): """ Handle getting an attribute of an object """ if isinstance(t.expr, (Div, Mul, Sub, Add)): self._write('(') self._dispatch(t.expr) self._write(')') else: self._dispatch(t.expr) self._write('.'+t.attrname) def _If(self, t): self._fill() for i, (compare,code) in enumerate(t.tests): if i == 0: self._write("if ") else: self._write("elif ") self._dispatch(compare) self._enter() self._fill() self._dispatch(code) self._leave() self._write("\n") if t.else_ is not None: self._write("else") self._enter() self._fill() self._dispatch(t.else_) self._leave() self._write("\n") def _IfExp(self, t): self._dispatch(t.then) self._write(" if ") self._dispatch(t.test) if t.else_ is not None: self._write(" else (") self._dispatch(t.else_) self._write(")") def _Import(self, t): """ Handle "import xyz.foo". """ self._fill("import ") for i, (name,asname) in enumerate(t.names): if i != 0: self._write(", ") self._write(name) if asname is not None: self._write(" as "+asname) def _Keyword(self, t): """ Keyword value assignment within function calls and definitions. """ self._write(t.name) self._write("=") self._dispatch(t.expr) def _List(self, t): self._write("[") for i,node in enumerate(t.nodes): self._dispatch(node) if i < len(t.nodes)-1: self._write(", ") self._write("]") def _Module(self, t): if t.doc is not None: self._dispatch(t.doc) self._dispatch(t.node) def _Mul(self, t): self.__binary_op(t, '*') def _Name(self, t): self._write(t.name) def _NoneType(self, t): self._write("None") def _Not(self, t): self._write('not (') self._dispatch(t.expr) self._write(')') def _Or(self, t): self._write(" (") for i, node in enumerate(t.nodes): self._dispatch(node) if i != len(t.nodes)-1: self._write(") or (") self._write(")") def _Pass(self, t): self._write("pass\n") def _Printnl(self, t): self._fill("print ") if t.dest: self._write(">> ") self._dispatch(t.dest) self._write(", ") comma = False for node in t.nodes: if comma: self._write(', ') else: comma = True self._dispatch(node) def _Power(self, t): self.__binary_op(t, '**') def _Return(self, t): self._fill("return ") if t.value: if isinstance(t.value, Tuple): text = ', '.join([ name.name for name in t.value.asList() ]) self._write(text) else: self._dispatch(t.value) if not self._do_indent: self._write('; ') def _Slice(self, t): self._dispatch(t.expr) self._write("[") if t.lower: self._dispatch(t.lower) self._write(":") if t.upper: self._dispatch(t.upper) #if t.step: # self._write(":") # self._dispatch(t.step) self._write("]") def _Sliceobj(self, t): for i, node in enumerate(t.nodes): if i != 0: self._write(":") if not (isinstance(node, Const) and node.value is None): self._dispatch(node) def _Stmt(self, tree): for node in tree.nodes: self._dispatch(node) def _Sub(self, t): self.__binary_op(t, '-') def _Subscript(self, t): self._dispatch(t.expr) self._write("[") for i, value in enumerate(t.subs): if i != 0: self._write(",") self._dispatch(value) self._write("]") def _TryExcept(self, t): self._fill("try") self._enter() self._dispatch(t.body) self._leave() for handler in t.handlers: self._fill('except ') self._dispatch(handler[0]) if handler[1] is not None: self._write(', ') self._dispatch(handler[1]) self._enter() self._dispatch(handler[2]) self._leave() if t.else_: self._fill("else") self._enter() self._dispatch(t.else_) self._leave() def _Tuple(self, t): if not t.nodes: # Empty tuple. self._write("()") else: self._write("(") # _write each elements, separated by a comma. for element in t.nodes[:-1]: self._dispatch(element) self._write(", ") # Handle the last one without writing comma last_element = t.nodes[-1] self._dispatch(last_element) self._write(")") def _UnaryAdd(self, t): self._write("+") self._dispatch(t.expr) def _UnarySub(self, t): self._write("-") self._dispatch(t.expr) def _With(self, t): self._fill('with ') self._dispatch(t.expr) if t.vars: self._write(' as ') self._dispatch(t.vars.name) self._enter() self._dispatch(t.body) self._leave() self._write('\n') def _int(self, t): self._write(repr(t)) def __binary_op(self, t, symbol): # Check if parenthesis are needed on left side and then dispatch has_paren = False left_class = str(t.left.__class__) if (left_class in op_precedence.keys() and op_precedence[left_class] < op_precedence[str(t.__class__)]): has_paren = True if has_paren: self._write('(') self._dispatch(t.left) if has_paren: self._write(')') # Write the appropriate symbol for operator self._write(symbol) # Check if parenthesis are needed on the right side and then dispatch has_paren = False right_class = str(t.right.__class__) if (right_class in op_precedence.keys() and op_precedence[right_class] < op_precedence[str(t.__class__)]): has_paren = True if has_paren: self._write('(') self._dispatch(t.right) if has_paren: self._write(')') def _float(self, t): # if t is 0.1, str(t)->'0.1' while repr(t)->'0.1000000000001' # We prefer str here. self._write(str(t)) def _str(self, t): self._write(repr(t)) def _tuple(self, t): self._write(str(t)) ######################################################################### # These are the methods from the _ast modules unparse. # # As our needs to handle more advanced code increase, we may want to # modify some of the methods below so that they work for compiler.ast. ######################################################################### # # stmt # def _Expr(self, tree): # self._fill() # self._dispatch(tree.value) # # def _Import(self, t): # self._fill("import ") # first = True # for a in t.names: # if first: # first = False # else: # self._write(", ") # self._write(a.name) # if a.asname: # self._write(" as "+a.asname) # ## def _ImportFrom(self, t): ## self._fill("from ") ## self._write(t.module) ## self._write(" import ") ## for i, a in enumerate(t.names): ## if i == 0: ## self._write(", ") ## self._write(a.name) ## if a.asname: ## self._write(" as "+a.asname) ## # XXX(jpe) what is level for? ## # # def _Break(self, t): # self._fill("break") # # def _Continue(self, t): # self._fill("continue") # # def _Delete(self, t): # self._fill("del ") # self._dispatch(t.targets) # # def _Assert(self, t): # self._fill("assert ") # self._dispatch(t.test) # if t.msg: # self._write(", ") # self._dispatch(t.msg) # # def _Exec(self, t): # self._fill("exec ") # self._dispatch(t.body) # if t.globals: # self._write(" in ") # self._dispatch(t.globals) # if t.locals: # self._write(", ") # self._dispatch(t.locals) # # def _Print(self, t): # self._fill("print ") # do_comma = False # if t.dest: # self._write(">>") # self._dispatch(t.dest) # do_comma = True # for e in t.values: # if do_comma:self._write(", ") # else:do_comma=True # self._dispatch(e) # if not t.nl: # self._write(",") # # def _Global(self, t): # self._fill("global") # for i, n in enumerate(t.names): # if i != 0: # self._write(",") # self._write(" " + n) # # def _Yield(self, t): # self._fill("yield") # if t.value: # self._write(" (") # self._dispatch(t.value) # self._write(")") # # def _Raise(self, t): # self._fill('raise ') # if t.type: # self._dispatch(t.type) # if t.inst: # self._write(", ") # self._dispatch(t.inst) # if t.tback: # self._write(", ") # self._dispatch(t.tback) # # # def _TryFinally(self, t): # self._fill("try") # self._enter() # self._dispatch(t.body) # self._leave() # # self._fill("finally") # self._enter() # self._dispatch(t.finalbody) # self._leave() # # def _excepthandler(self, t): # self._fill("except ") # if t.type: # self._dispatch(t.type) # if t.name: # self._write(", ") # self._dispatch(t.name) # self._enter() # self._dispatch(t.body) # self._leave() # # def _ClassDef(self, t): # self._write("\n") # self._fill("class "+t.name) # if t.bases: # self._write("(") # for a in t.bases: # self._dispatch(a) # self._write(", ") # self._write(")") # self._enter() # self._dispatch(t.body) # self._leave() # # def _FunctionDef(self, t): # self._write("\n") # for deco in t.decorators: # self._fill("@") # self._dispatch(deco) # self._fill("def "+t.name + "(") # self._dispatch(t.args) # self._write(")") # self._enter() # self._dispatch(t.body) # self._leave() # # def _For(self, t): # self._fill("for ") # self._dispatch(t.target) # self._write(" in ") # self._dispatch(t.iter) # self._enter() # self._dispatch(t.body) # self._leave() # if t.orelse: # self._fill("else") # self._enter() # self._dispatch(t.orelse) # self._leave # # def _While(self, t): # self._fill("while ") # self._dispatch(t.test) # self._enter() # self._dispatch(t.body) # self._leave() # if t.orelse: # self._fill("else") # self._enter() # self._dispatch(t.orelse) # self._leave # # # expr # def _Str(self, tree): # self._write(repr(tree.s)) ## # def _Repr(self, t): # self._write("`") # self._dispatch(t.value) # self._write("`") # # def _Num(self, t): # self._write(repr(t.n)) # # def _ListComp(self, t): # self._write("[") # self._dispatch(t.elt) # for gen in t.generators: # self._dispatch(gen) # self._write("]") # # def _GeneratorExp(self, t): # self._write("(") # self._dispatch(t.elt) # for gen in t.generators: # self._dispatch(gen) # self._write(")") # # def _comprehension(self, t): # self._write(" for ") # self._dispatch(t.target) # self._write(" in ") # self._dispatch(t.iter) # for if_clause in t.ifs: # self._write(" if ") # self._dispatch(if_clause) # # def _IfExp(self, t): # self._dispatch(t.body) # self._write(" if ") # self._dispatch(t.test) # if t.orelse: # self._write(" else ") # self._dispatch(t.orelse) # # unop = {"Invert":"~", "Not": "not", "UAdd":"+", "USub":"-"} # def _UnaryOp(self, t): # self._write(self.unop[t.op.__class__.__name__]) # self._write("(") # self._dispatch(t.operand) # self._write(")") # # binop = { "Add":"+", "Sub":"-", "Mult":"*", "Div":"/", "Mod":"%", # "LShift":">>", "RShift":"<<", "BitOr":"|", "BitXor":"^", "BitAnd":"&", # "FloorDiv":"//", "Pow": "**"} # def _BinOp(self, t): # self._write("(") # self._dispatch(t.left) # self._write(")" + self.binop[t.op.__class__.__name__] + "(") # self._dispatch(t.right) # self._write(")") # # boolops = {_ast.And: 'and', _ast.Or: 'or'} # def _BoolOp(self, t): # self._write("(") # self._dispatch(t.values[0]) # for v in t.values[1:]: # self._write(" %s " % self.boolops[t.op.__class__]) # self._dispatch(v) # self._write(")") # # def _Attribute(self,t): # self._dispatch(t.value) # self._write(".") # self._write(t.attr) # ## def _Call(self, t): ## self._dispatch(t.func) ## self._write("(") ## comma = False ## for e in t.args: ## if comma: self._write(", ") ## else: comma = True ## self._dispatch(e) ## for e in t.keywords: ## if comma: self._write(", ") ## else: comma = True ## self._dispatch(e) ## if t.starargs: ## if comma: self._write(", ") ## else: comma = True ## self._write("*") ## self._dispatch(t.starargs) ## if t.kwargs: ## if comma: self._write(", ") ## else: comma = True ## self._write("**") ## self._dispatch(t.kwargs) ## self._write(")") # # # slice # def _Index(self, t): # self._dispatch(t.value) # # def _ExtSlice(self, t): # for i, d in enumerate(t.dims): # if i != 0: # self._write(': ') # self._dispatch(d) # # # others # def _arguments(self, t): # first = True # nonDef = len(t.args)-len(t.defaults) # for a in t.args[0:nonDef]: # if first:first = False # else: self._write(", ") # self._dispatch(a) # for a,d in zip(t.args[nonDef:], t.defaults): # if first:first = False # else: self._write(", ") # self._dispatch(a), # self._write("=") # self._dispatch(d) # if t.vararg: # if first:first = False # else: self._write(", ") # self._write("*"+t.vararg) # if t.kwarg: # if first:first = False # else: self._write(", ") # self._write("**"+t.kwarg) # ## def _keyword(self, t): ## self._write(t.arg) ## self._write("=") ## self._dispatch(t.value) # # def _Lambda(self, t): # self._write("lambda ") # self._dispatch(t.args) # self._write(": ") # self._dispatch(t.body) numpy-1.8.2/doc/sphinxext/numpydoc/tests/0000775000175100017510000000000012371375427021636 5ustar vagrantvagrant00000000000000numpy-1.8.2/doc/sphinxext/numpydoc/tests/test_plot_directive.py0000664000175100017510000000017612370216247026260 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function import numpydoc.plot_directive # No tests at the moment... numpy-1.8.2/doc/sphinxext/numpydoc/tests/test_traitsdoc.py0000664000175100017510000000017112370216247025233 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function import numpydoc.traitsdoc # No tests at the moment... numpy-1.8.2/doc/sphinxext/numpydoc/tests/test_docscrape.py0000664000175100017510000004362612370216247025216 0ustar vagrantvagrant00000000000000# -*- encoding:utf-8 -*- from __future__ import division, absolute_import, print_function import sys, textwrap from numpydoc.docscrape import NumpyDocString, FunctionDoc, ClassDoc from numpydoc.docscrape_sphinx import SphinxDocString, SphinxClassDoc from nose.tools import * if sys.version_info[0] >= 3: sixu = lambda s: s else: sixu = lambda s: unicode(s, 'unicode_escape') doc_txt = '''\ numpy.multivariate_normal(mean, cov, shape=None, spam=None) Draw values from a multivariate normal distribution with specified mean and covariance. The multivariate normal or Gaussian distribution is a generalisation of the one-dimensional normal distribution to higher dimensions. Parameters ---------- mean : (N,) ndarray Mean of the N-dimensional distribution. .. math:: (1+2+3)/3 cov : (N, N) ndarray Covariance matrix of the distribution. shape : tuple of ints 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 each sample is N-dimensional, the output shape is (m,n,k,N). Returns ------- out : ndarray The drawn samples, arranged according to `shape`. If the shape given is (m,n,...), then the shape of `out` is is (m,n,...,N). In other words, each entry ``out[i,j,...,:]`` is an N-dimensional value drawn from the distribution. list of str This is not a real return value. It exists to test anonymous return values. Other Parameters ---------------- spam : parrot A parrot off its mortal coil. Raises ------ RuntimeError Some error Warns ----- RuntimeWarning Some warning Warnings -------- Certain warnings apply. Notes ----- Instead of specifying the full covariance matrix, popular approximations include: - Spherical covariance (`cov` is a multiple of the identity matrix) - Diagonal covariance (`cov` has non-negative elements only on the diagonal) This geometrical property can be seen in two dimensions by plotting generated data-points: >>> mean = [0,0] >>> cov = [[1,0],[0,100]] # diagonal covariance, points lie on x or y-axis >>> x,y = multivariate_normal(mean,cov,5000).T >>> plt.plot(x,y,'x'); plt.axis('equal'); plt.show() Note that the covariance matrix must be symmetric and non-negative definite. References ---------- .. [1] A. Papoulis, "Probability, Random Variables, and Stochastic Processes," 3rd ed., McGraw-Hill Companies, 1991 .. [2] R.O. Duda, P.E. Hart, and D.G. Stork, "Pattern Classification," 2nd ed., Wiley, 2001. See Also -------- some, other, funcs otherfunc : relationship Examples -------- >>> mean = (1,2) >>> cov = [[1,0],[1,0]] >>> x = multivariate_normal(mean,cov,(3,3)) >>> print x.shape (3, 3, 2) The following is probably true, given that 0.6 is roughly twice the standard deviation: >>> print list( (x[0,0,:] - mean) < 0.6 ) [True, True] .. index:: random :refguide: random;distributions, random;gauss ''' doc = NumpyDocString(doc_txt) def test_signature(): assert doc['Signature'].startswith('numpy.multivariate_normal(') assert doc['Signature'].endswith('spam=None)') def test_summary(): assert doc['Summary'][0].startswith('Draw values') assert doc['Summary'][-1].endswith('covariance.') def test_extended_summary(): assert doc['Extended Summary'][0].startswith('The multivariate normal') def test_parameters(): assert_equal(len(doc['Parameters']), 3) assert_equal([n for n,_,_ in doc['Parameters']], ['mean','cov','shape']) arg, arg_type, desc = doc['Parameters'][1] assert_equal(arg_type, '(N, N) ndarray') assert desc[0].startswith('Covariance matrix') assert doc['Parameters'][0][-1][-2] == ' (1+2+3)/3' def test_other_parameters(): assert_equal(len(doc['Other Parameters']), 1) assert_equal([n for n,_,_ in doc['Other Parameters']], ['spam']) arg, arg_type, desc = doc['Other Parameters'][0] assert_equal(arg_type, 'parrot') assert desc[0].startswith('A parrot off its mortal coil') def test_returns(): assert_equal(len(doc['Returns']), 2) arg, arg_type, desc = doc['Returns'][0] assert_equal(arg, 'out') assert_equal(arg_type, 'ndarray') assert desc[0].startswith('The drawn samples') assert desc[-1].endswith('distribution.') arg, arg_type, desc = doc['Returns'][1] assert_equal(arg, 'list of str') assert_equal(arg_type, '') assert desc[0].startswith('This is not a real') assert desc[-1].endswith('anonymous return values.') def test_notes(): assert doc['Notes'][0].startswith('Instead') assert doc['Notes'][-1].endswith('definite.') assert_equal(len(doc['Notes']), 17) def test_references(): assert doc['References'][0].startswith('..') assert doc['References'][-1].endswith('2001.') def test_examples(): assert doc['Examples'][0].startswith('>>>') assert doc['Examples'][-1].endswith('True]') def test_index(): assert_equal(doc['index']['default'], 'random') assert_equal(len(doc['index']), 2) assert_equal(len(doc['index']['refguide']), 2) def non_blank_line_by_line_compare(a,b): a = textwrap.dedent(a) b = textwrap.dedent(b) a = [l.rstrip() for l in a.split('\n') if l.strip()] b = [l.rstrip() for l in b.split('\n') if l.strip()] for n,line in enumerate(a): if not line == b[n]: raise AssertionError("Lines %s of a and b differ: " "\n>>> %s\n<<< %s\n" % (n,line,b[n])) def test_str(): non_blank_line_by_line_compare(str(doc), """numpy.multivariate_normal(mean, cov, shape=None, spam=None) Draw values from a multivariate normal distribution with specified mean and covariance. The multivariate normal or Gaussian distribution is a generalisation of the one-dimensional normal distribution to higher dimensions. Parameters ---------- mean : (N,) ndarray Mean of the N-dimensional distribution. .. math:: (1+2+3)/3 cov : (N, N) ndarray Covariance matrix of the distribution. shape : tuple of ints 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 each sample is N-dimensional, the output shape is (m,n,k,N). Returns ------- out : ndarray The drawn samples, arranged according to `shape`. If the shape given is (m,n,...), then the shape of `out` is is (m,n,...,N). In other words, each entry ``out[i,j,...,:]`` is an N-dimensional value drawn from the distribution. list of str This is not a real return value. It exists to test anonymous return values. Other Parameters ---------------- spam : parrot A parrot off its mortal coil. Raises ------ RuntimeError Some error Warns ----- RuntimeWarning Some warning Warnings -------- Certain warnings apply. See Also -------- `some`_, `other`_, `funcs`_ `otherfunc`_ relationship Notes ----- Instead of specifying the full covariance matrix, popular approximations include: - Spherical covariance (`cov` is a multiple of the identity matrix) - Diagonal covariance (`cov` has non-negative elements only on the diagonal) This geometrical property can be seen in two dimensions by plotting generated data-points: >>> mean = [0,0] >>> cov = [[1,0],[0,100]] # diagonal covariance, points lie on x or y-axis >>> x,y = multivariate_normal(mean,cov,5000).T >>> plt.plot(x,y,'x'); plt.axis('equal'); plt.show() Note that the covariance matrix must be symmetric and non-negative definite. References ---------- .. [1] A. Papoulis, "Probability, Random Variables, and Stochastic Processes," 3rd ed., McGraw-Hill Companies, 1991 .. [2] R.O. Duda, P.E. Hart, and D.G. Stork, "Pattern Classification," 2nd ed., Wiley, 2001. Examples -------- >>> mean = (1,2) >>> cov = [[1,0],[1,0]] >>> x = multivariate_normal(mean,cov,(3,3)) >>> print x.shape (3, 3, 2) The following is probably true, given that 0.6 is roughly twice the standard deviation: >>> print list( (x[0,0,:] - mean) < 0.6 ) [True, True] .. index:: random :refguide: random;distributions, random;gauss""") def test_sphinx_str(): sphinx_doc = SphinxDocString(doc_txt) non_blank_line_by_line_compare(str(sphinx_doc), """ .. index:: random single: random;distributions, random;gauss Draw values from a multivariate normal distribution with specified mean and covariance. The multivariate normal or Gaussian distribution is a generalisation of the one-dimensional normal distribution to higher dimensions. :Parameters: **mean** : (N,) ndarray Mean of the N-dimensional distribution. .. math:: (1+2+3)/3 **cov** : (N, N) ndarray Covariance matrix of the distribution. **shape** : tuple of ints 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 each sample is N-dimensional, the output shape is (m,n,k,N). :Returns: **out** : ndarray The drawn samples, arranged according to `shape`. If the shape given is (m,n,...), then the shape of `out` is is (m,n,...,N). In other words, each entry ``out[i,j,...,:]`` is an N-dimensional value drawn from the distribution. list of str This is not a real return value. It exists to test anonymous return values. :Other Parameters: **spam** : parrot A parrot off its mortal coil. :Raises: **RuntimeError** Some error :Warns: **RuntimeWarning** Some warning .. warning:: Certain warnings apply. .. seealso:: :obj:`some`, :obj:`other`, :obj:`funcs` :obj:`otherfunc` relationship .. rubric:: Notes Instead of specifying the full covariance matrix, popular approximations include: - Spherical covariance (`cov` is a multiple of the identity matrix) - Diagonal covariance (`cov` has non-negative elements only on the diagonal) This geometrical property can be seen in two dimensions by plotting generated data-points: >>> mean = [0,0] >>> cov = [[1,0],[0,100]] # diagonal covariance, points lie on x or y-axis >>> x,y = multivariate_normal(mean,cov,5000).T >>> plt.plot(x,y,'x'); plt.axis('equal'); plt.show() Note that the covariance matrix must be symmetric and non-negative definite. .. rubric:: References .. [1] A. Papoulis, "Probability, Random Variables, and Stochastic Processes," 3rd ed., McGraw-Hill Companies, 1991 .. [2] R.O. Duda, P.E. Hart, and D.G. Stork, "Pattern Classification," 2nd ed., Wiley, 2001. .. only:: latex [1]_, [2]_ .. rubric:: Examples >>> mean = (1,2) >>> cov = [[1,0],[1,0]] >>> x = multivariate_normal(mean,cov,(3,3)) >>> print x.shape (3, 3, 2) The following is probably true, given that 0.6 is roughly twice the standard deviation: >>> print list( (x[0,0,:] - mean) < 0.6 ) [True, True] """) doc2 = NumpyDocString(""" Returns array of indices of the maximum values of along the given axis. Parameters ---------- a : {array_like} Array to look in. axis : {None, integer} If None, the index is into the flattened array, otherwise along the specified axis""") def test_parameters_without_extended_description(): assert_equal(len(doc2['Parameters']), 2) doc3 = NumpyDocString(""" my_signature(*params, **kwds) Return this and that. """) def test_escape_stars(): signature = str(doc3).split('\n')[0] assert_equal(signature, 'my_signature(\*params, \*\*kwds)') doc4 = NumpyDocString( """a.conj() Return an array with all complex-valued elements conjugated.""") def test_empty_extended_summary(): assert_equal(doc4['Extended Summary'], []) doc5 = NumpyDocString( """ a.something() Raises ------ LinAlgException If array is singular. Warns ----- SomeWarning If needed """) def test_raises(): assert_equal(len(doc5['Raises']), 1) name,_,desc = doc5['Raises'][0] assert_equal(name,'LinAlgException') assert_equal(desc,['If array is singular.']) def test_warns(): assert_equal(len(doc5['Warns']), 1) name,_,desc = doc5['Warns'][0] assert_equal(name,'SomeWarning') assert_equal(desc,['If needed']) def test_see_also(): doc6 = NumpyDocString( """ z(x,theta) See Also -------- func_a, func_b, func_c func_d : some equivalent func foo.func_e : some other func over multiple lines func_f, func_g, :meth:`func_h`, func_j, func_k :obj:`baz.obj_q` :class:`class_j`: fubar foobar """) assert len(doc6['See Also']) == 12 for func, desc, role in doc6['See Also']: if func in ('func_a', 'func_b', 'func_c', 'func_f', 'func_g', 'func_h', 'func_j', 'func_k', 'baz.obj_q'): assert(not desc) else: assert(desc) if func == 'func_h': assert role == 'meth' elif func == 'baz.obj_q': assert role == 'obj' elif func == 'class_j': assert role == 'class' else: assert role is None if func == 'func_d': assert desc == ['some equivalent func'] elif func == 'foo.func_e': assert desc == ['some other func over', 'multiple lines'] elif func == 'class_j': assert desc == ['fubar', 'foobar'] def test_see_also_print(): class Dummy(object): """ See Also -------- func_a, func_b func_c : some relationship goes here func_d """ pass obj = Dummy() s = str(FunctionDoc(obj, role='func')) assert(':func:`func_a`, :func:`func_b`' in s) assert(' some relationship' in s) assert(':func:`func_d`' in s) doc7 = NumpyDocString(""" Doc starts on second line. """) def test_empty_first_line(): assert doc7['Summary'][0].startswith('Doc starts') def test_no_summary(): str(SphinxDocString(""" Parameters ----------""")) def test_unicode(): doc = SphinxDocString(""" öäöäöäöäöåååå öäöäöäööäååå Parameters ---------- ååå : äää ööö Returns ------- ååå : ööö äää """) assert isinstance(doc['Summary'][0], str) assert doc['Summary'][0] == 'öäöäöäöäöåååå' def test_plot_examples(): cfg = dict(use_plots=True) doc = SphinxDocString(""" Examples -------- >>> import matplotlib.pyplot as plt >>> plt.plot([1,2,3],[4,5,6]) >>> plt.show() """, config=cfg) assert 'plot::' in str(doc), str(doc) doc = SphinxDocString(""" Examples -------- .. plot:: import matplotlib.pyplot as plt plt.plot([1,2,3],[4,5,6]) plt.show() """, config=cfg) assert str(doc).count('plot::') == 1, str(doc) def test_class_members(): class Dummy(object): """ Dummy class. """ def spam(self, a, b): """Spam\n\nSpam spam.""" pass def ham(self, c, d): """Cheese\n\nNo cheese.""" pass @property def spammity(self): """Spammity index""" return 0.95 class Ignorable(object): """local class, to be ignored""" pass for cls in (ClassDoc, SphinxClassDoc): doc = cls(Dummy, config=dict(show_class_members=False)) assert 'Methods' not in str(doc), (cls, str(doc)) assert 'spam' not in str(doc), (cls, str(doc)) assert 'ham' not in str(doc), (cls, str(doc)) assert 'spammity' not in str(doc), (cls, str(doc)) assert 'Spammity index' not in str(doc), (cls, str(doc)) doc = cls(Dummy, config=dict(show_class_members=True)) assert 'Methods' in str(doc), (cls, str(doc)) assert 'spam' in str(doc), (cls, str(doc)) assert 'ham' in str(doc), (cls, str(doc)) assert 'spammity' in str(doc), (cls, str(doc)) if cls is SphinxClassDoc: assert '.. autosummary::' in str(doc), str(doc) else: assert 'Spammity index' in str(doc), str(doc) def test_duplicate_signature(): # Duplicate function signatures occur e.g. in ufuncs, when the # automatic mechanism adds one, and a more detailed comes from the # docstring itself. doc = NumpyDocString( """ z(x1, x2) z(a, theta) """) assert doc['Signature'].strip() == 'z(a, theta)' class_doc_txt = """ Foo Parameters ---------- f : callable ``f(t, y, *f_args)`` Aaa. jac : callable ``jac(t, y, *jac_args)`` Bbb. Attributes ---------- t : float Current time. y : ndarray Current variable values. Methods ------- a b c Examples -------- For usage examples, see `ode`. """ def test_class_members_doc(): doc = ClassDoc(None, class_doc_txt) non_blank_line_by_line_compare(str(doc), """ Foo Parameters ---------- f : callable ``f(t, y, *f_args)`` Aaa. jac : callable ``jac(t, y, *jac_args)`` Bbb. Examples -------- For usage examples, see `ode`. Attributes ---------- t : float Current time. y : ndarray Current variable values. Methods ------- a b c .. index:: """) def test_class_members_doc_sphinx(): doc = SphinxClassDoc(None, class_doc_txt) non_blank_line_by_line_compare(str(doc), """ Foo :Parameters: **f** : callable ``f(t, y, *f_args)`` Aaa. **jac** : callable ``jac(t, y, *jac_args)`` Bbb. .. rubric:: Examples For usage examples, see `ode`. .. rubric:: Attributes === ========== t (float) Current time. y (ndarray) Current variable values. === ========== .. rubric:: Methods === ========== a b c === ========== """) if __name__ == "__main__": import nose nose.run() numpy-1.8.2/doc/sphinxext/numpydoc/tests/test_linkcode.py0000664000175100017510000000017012370216247025026 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function import numpydoc.linkcode # No tests at the moment... numpy-1.8.2/doc/sphinxext/numpydoc/tests/test_phantom_import.py0000664000175100017510000000017612370216247026304 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function import numpydoc.phantom_import # No tests at the moment... numpy-1.8.2/doc/sphinxext/numpydoc/plot_directive.py0000664000175100017510000005006212370216247024056 0ustar vagrantvagrant00000000000000""" A special directive for generating a matplotlib plot. .. warning:: This is a hacked version of plot_directive.py from Matplotlib. It's very much subject to change! Usage ----- Can be used like this:: .. plot:: examples/example.py .. plot:: import matplotlib.pyplot as plt plt.plot([1,2,3], [4,5,6]) .. plot:: A plotting example: >>> import matplotlib.pyplot as plt >>> plt.plot([1,2,3], [4,5,6]) The content is interpreted as doctest formatted if it has a line starting with ``>>>``. The ``plot`` directive supports the options format : {'python', 'doctest'} Specify the format of the input include-source : bool Whether to display the source code. Default can be changed in conf.py and the ``image`` directive options ``alt``, ``height``, ``width``, ``scale``, ``align``, ``class``. Configuration options --------------------- The plot directive has the following configuration options: plot_include_source Default value for the include-source option plot_pre_code Code that should be executed before each plot. plot_basedir Base directory, to which plot:: file names are relative to. (If None or empty, file names are relative to the directoly where the file containing the directive is.) plot_formats File formats to generate. List of tuples or strings:: [(suffix, dpi), suffix, ...] that determine the file format and the DPI. For entries whose DPI was omitted, sensible defaults are chosen. plot_html_show_formats Whether to show links to the files in HTML. TODO ---- * Refactor Latex output; now it's plain images, but it would be nice to make them appear side-by-side, or in floats. """ from __future__ import division, absolute_import, print_function import sys, os, glob, shutil, imp, warnings, re, textwrap, traceback import sphinx if sys.version_info[0] >= 3: from io import StringIO else: from io import StringIO import warnings warnings.warn("A plot_directive module is also available under " "matplotlib.sphinxext; expect this numpydoc.plot_directive " "module to be deprecated after relevant features have been " "integrated there.", FutureWarning, stacklevel=2) #------------------------------------------------------------------------------ # Registration hook #------------------------------------------------------------------------------ def setup(app): setup.app = app setup.config = app.config setup.confdir = app.confdir app.add_config_value('plot_pre_code', '', True) app.add_config_value('plot_include_source', False, True) app.add_config_value('plot_formats', ['png', 'hires.png', 'pdf'], True) app.add_config_value('plot_basedir', None, True) app.add_config_value('plot_html_show_formats', True, True) app.add_directive('plot', plot_directive, True, (0, 1, False), **plot_directive_options) #------------------------------------------------------------------------------ # plot:: directive #------------------------------------------------------------------------------ from docutils.parsers.rst import directives from docutils import nodes def plot_directive(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine): return run(arguments, content, options, state_machine, state, lineno) plot_directive.__doc__ = __doc__ def _option_boolean(arg): if not arg or not arg.strip(): # no argument given, assume used as a flag return True elif arg.strip().lower() in ('no', '0', 'false'): return False elif arg.strip().lower() in ('yes', '1', 'true'): return True else: raise ValueError('"%s" unknown boolean' % arg) def _option_format(arg): return directives.choice(arg, ('python', 'lisp')) def _option_align(arg): return directives.choice(arg, ("top", "middle", "bottom", "left", "center", "right")) plot_directive_options = {'alt': directives.unchanged, 'height': directives.length_or_unitless, 'width': directives.length_or_percentage_or_unitless, 'scale': directives.nonnegative_int, 'align': _option_align, 'class': directives.class_option, 'include-source': _option_boolean, 'format': _option_format, } #------------------------------------------------------------------------------ # Generating output #------------------------------------------------------------------------------ from docutils import nodes, utils try: # Sphinx depends on either Jinja or Jinja2 import jinja2 def format_template(template, **kw): return jinja2.Template(template).render(**kw) except ImportError: import jinja def format_template(template, **kw): return jinja.from_string(template, **kw) TEMPLATE = """ {{ source_code }} {{ only_html }} {% if source_link or (html_show_formats and not multi_image) %} ( {%- if source_link -%} `Source code <{{ source_link }}>`__ {%- endif -%} {%- if html_show_formats and not multi_image -%} {%- for img in images -%} {%- for fmt in img.formats -%} {%- if source_link or not loop.first -%}, {% endif -%} `{{ fmt }} <{{ dest_dir }}/{{ img.basename }}.{{ fmt }}>`__ {%- endfor -%} {%- endfor -%} {%- endif -%} ) {% endif %} {% for img in images %} .. figure:: {{ build_dir }}/{{ img.basename }}.png {%- for option in options %} {{ option }} {% endfor %} {% if html_show_formats and multi_image -%} ( {%- for fmt in img.formats -%} {%- if not loop.first -%}, {% endif -%} `{{ fmt }} <{{ dest_dir }}/{{ img.basename }}.{{ fmt }}>`__ {%- endfor -%} ) {%- endif -%} {% endfor %} {{ only_latex }} {% for img in images %} .. image:: {{ build_dir }}/{{ img.basename }}.pdf {% endfor %} """ class ImageFile(object): def __init__(self, basename, dirname): self.basename = basename self.dirname = dirname self.formats = [] def filename(self, format): return os.path.join(self.dirname, "%s.%s" % (self.basename, format)) def filenames(self): return [self.filename(fmt) for fmt in self.formats] def run(arguments, content, options, state_machine, state, lineno): if arguments and content: raise RuntimeError("plot:: directive can't have both args and content") document = state_machine.document config = document.settings.env.config options.setdefault('include-source', config.plot_include_source) # determine input rst_file = document.attributes['source'] rst_dir = os.path.dirname(rst_file) if arguments: if not config.plot_basedir: source_file_name = os.path.join(rst_dir, directives.uri(arguments[0])) else: source_file_name = os.path.join(setup.confdir, config.plot_basedir, directives.uri(arguments[0])) code = open(source_file_name, 'r').read() output_base = os.path.basename(source_file_name) else: source_file_name = rst_file code = textwrap.dedent("\n".join(map(str, content))) counter = document.attributes.get('_plot_counter', 0) + 1 document.attributes['_plot_counter'] = counter base, ext = os.path.splitext(os.path.basename(source_file_name)) output_base = '%s-%d.py' % (base, counter) base, source_ext = os.path.splitext(output_base) if source_ext in ('.py', '.rst', '.txt'): output_base = base else: source_ext = '' # ensure that LaTeX includegraphics doesn't choke in foo.bar.pdf filenames output_base = output_base.replace('.', '-') # is it in doctest format? is_doctest = contains_doctest(code) if 'format' in options: if options['format'] == 'python': is_doctest = False else: is_doctest = True # determine output directory name fragment source_rel_name = relpath(source_file_name, setup.confdir) source_rel_dir = os.path.dirname(source_rel_name) while source_rel_dir.startswith(os.path.sep): source_rel_dir = source_rel_dir[1:] # build_dir: where to place output files (temporarily) build_dir = os.path.join(os.path.dirname(setup.app.doctreedir), 'plot_directive', source_rel_dir) if not os.path.exists(build_dir): os.makedirs(build_dir) # output_dir: final location in the builder's directory dest_dir = os.path.abspath(os.path.join(setup.app.builder.outdir, source_rel_dir)) # how to link to files from the RST file dest_dir_link = os.path.join(relpath(setup.confdir, rst_dir), source_rel_dir).replace(os.path.sep, '/') build_dir_link = relpath(build_dir, rst_dir).replace(os.path.sep, '/') source_link = dest_dir_link + '/' + output_base + source_ext # make figures try: results = makefig(code, source_file_name, build_dir, output_base, config) errors = [] except PlotError as err: reporter = state.memo.reporter sm = reporter.system_message( 2, "Exception occurred in plotting %s: %s" % (output_base, err), line=lineno) results = [(code, [])] errors = [sm] # generate output restructuredtext total_lines = [] for j, (code_piece, images) in enumerate(results): if options['include-source']: if is_doctest: lines = [''] lines += [row.rstrip() for row in code_piece.split('\n')] else: lines = ['.. code-block:: python', ''] lines += [' %s' % row.rstrip() for row in code_piece.split('\n')] source_code = "\n".join(lines) else: source_code = "" opts = [':%s: %s' % (key, val) for key, val in list(options.items()) if key in ('alt', 'height', 'width', 'scale', 'align', 'class')] only_html = ".. only:: html" only_latex = ".. only:: latex" if j == 0: src_link = source_link else: src_link = None result = format_template( TEMPLATE, dest_dir=dest_dir_link, build_dir=build_dir_link, source_link=src_link, multi_image=len(images) > 1, only_html=only_html, only_latex=only_latex, options=opts, images=images, source_code=source_code, html_show_formats=config.plot_html_show_formats) total_lines.extend(result.split("\n")) total_lines.extend("\n") if total_lines: state_machine.insert_input(total_lines, source=source_file_name) # copy image files to builder's output directory if not os.path.exists(dest_dir): os.makedirs(dest_dir) for code_piece, images in results: for img in images: for fn in img.filenames(): shutil.copyfile(fn, os.path.join(dest_dir, os.path.basename(fn))) # copy script (if necessary) if source_file_name == rst_file: target_name = os.path.join(dest_dir, output_base + source_ext) f = open(target_name, 'w') f.write(unescape_doctest(code)) f.close() return errors #------------------------------------------------------------------------------ # Run code and capture figures #------------------------------------------------------------------------------ import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import matplotlib.image as image from matplotlib import _pylab_helpers import exceptions def contains_doctest(text): try: # check if it's valid Python as-is compile(text, '', 'exec') return False except SyntaxError: pass r = re.compile(r'^\s*>>>', re.M) m = r.search(text) return bool(m) def unescape_doctest(text): """ Extract code from a piece of text, which contains either Python code or doctests. """ if not contains_doctest(text): return text code = "" for line in text.split("\n"): m = re.match(r'^\s*(>>>|\.\.\.) (.*)$', line) if m: code += m.group(2) + "\n" elif line.strip(): code += "# " + line.strip() + "\n" else: code += "\n" return code def split_code_at_show(text): """ Split code at plt.show() """ parts = [] is_doctest = contains_doctest(text) part = [] for line in text.split("\n"): if (not is_doctest and line.strip() == 'plt.show()') or \ (is_doctest and line.strip() == '>>> plt.show()'): part.append(line) parts.append("\n".join(part)) part = [] else: part.append(line) if "\n".join(part).strip(): parts.append("\n".join(part)) return parts class PlotError(RuntimeError): pass def run_code(code, code_path, ns=None): # Change the working directory to the directory of the example, so # it can get at its data files, if any. pwd = os.getcwd() old_sys_path = list(sys.path) if code_path is not None: dirname = os.path.abspath(os.path.dirname(code_path)) os.chdir(dirname) sys.path.insert(0, dirname) # Redirect stdout stdout = sys.stdout sys.stdout = StringIO() # Reset sys.argv old_sys_argv = sys.argv sys.argv = [code_path] try: try: code = unescape_doctest(code) if ns is None: ns = {} if not ns: exec(setup.config.plot_pre_code, ns) exec(code, ns) except (Exception, SystemExit) as err: raise PlotError(traceback.format_exc()) finally: os.chdir(pwd) sys.argv = old_sys_argv sys.path[:] = old_sys_path sys.stdout = stdout return ns #------------------------------------------------------------------------------ # Generating figures #------------------------------------------------------------------------------ def out_of_date(original, derived): """ Returns True if derivative is out-of-date wrt original, both of which are full file paths. """ return (not os.path.exists(derived) or os.stat(derived).st_mtime < os.stat(original).st_mtime) def makefig(code, code_path, output_dir, output_base, config): """ Run a pyplot script *code* and save the images under *output_dir* with file names derived from *output_base* """ # -- Parse format list default_dpi = {'png': 80, 'hires.png': 200, 'pdf': 50} formats = [] for fmt in config.plot_formats: if isinstance(fmt, str): formats.append((fmt, default_dpi.get(fmt, 80))) elif type(fmt) in (tuple, list) and len(fmt)==2: formats.append((str(fmt[0]), int(fmt[1]))) else: raise PlotError('invalid image format "%r" in plot_formats' % fmt) # -- Try to determine if all images already exist code_pieces = split_code_at_show(code) # Look for single-figure output files first all_exists = True img = ImageFile(output_base, output_dir) for format, dpi in formats: if out_of_date(code_path, img.filename(format)): all_exists = False break img.formats.append(format) if all_exists: return [(code, [img])] # Then look for multi-figure output files results = [] all_exists = True for i, code_piece in enumerate(code_pieces): images = [] for j in range(1000): img = ImageFile('%s_%02d_%02d' % (output_base, i, j), output_dir) for format, dpi in formats: if out_of_date(code_path, img.filename(format)): all_exists = False break img.formats.append(format) # assume that if we have one, we have them all if not all_exists: all_exists = (j > 0) break images.append(img) if not all_exists: break results.append((code_piece, images)) if all_exists: return results # -- We didn't find the files, so build them results = [] ns = {} for i, code_piece in enumerate(code_pieces): # Clear between runs plt.close('all') # Run code run_code(code_piece, code_path, ns) # Collect images images = [] fig_managers = _pylab_helpers.Gcf.get_all_fig_managers() for j, figman in enumerate(fig_managers): if len(fig_managers) == 1 and len(code_pieces) == 1: img = ImageFile(output_base, output_dir) else: img = ImageFile("%s_%02d_%02d" % (output_base, i, j), output_dir) images.append(img) for format, dpi in formats: try: figman.canvas.figure.savefig(img.filename(format), dpi=dpi) except exceptions.BaseException as err: raise PlotError(traceback.format_exc()) img.formats.append(format) # Results results.append((code_piece, images)) return results #------------------------------------------------------------------------------ # Relative pathnames #------------------------------------------------------------------------------ try: from os.path import relpath except ImportError: # Copied from Python 2.7 if 'posix' in sys.builtin_module_names: def relpath(path, start=os.path.curdir): """Return a relative version of a path""" from os.path import sep, curdir, join, abspath, commonprefix, \ pardir if not path: raise ValueError("no path specified") start_list = abspath(start).split(sep) path_list = abspath(path).split(sep) # Work out how much of the filepath is shared by start and path. i = len(commonprefix([start_list, path_list])) rel_list = [pardir] * (len(start_list)-i) + path_list[i:] if not rel_list: return curdir return join(*rel_list) elif 'nt' in sys.builtin_module_names: def relpath(path, start=os.path.curdir): """Return a relative version of a path""" from os.path import sep, curdir, join, abspath, commonprefix, \ pardir, splitunc if not path: raise ValueError("no path specified") start_list = abspath(start).split(sep) path_list = abspath(path).split(sep) if start_list[0].lower() != path_list[0].lower(): unc_path, rest = splitunc(path) unc_start, rest = splitunc(start) if bool(unc_path) ^ bool(unc_start): raise ValueError("Cannot mix UNC and non-UNC paths (%s and %s)" % (path, start)) else: raise ValueError("path is on drive %s, start on drive %s" % (path_list[0], start_list[0])) # Work out how much of the filepath is shared by start and path. for i in range(min(len(start_list), len(path_list))): if start_list[i].lower() != path_list[i].lower(): break else: i += 1 rel_list = [pardir] * (len(start_list)-i) + path_list[i:] if not rel_list: return curdir return join(*rel_list) else: raise RuntimeError("Unsupported platform (no relpath available!)") numpy-1.8.2/doc/sphinxext/numpydoc/docscrape_sphinx.py0000664000175100017510000002201012370216247024366 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function import sys, re, inspect, textwrap, pydoc import sphinx import collections from .docscrape import NumpyDocString, FunctionDoc, ClassDoc if sys.version_info[0] >= 3: sixu = lambda s: s else: sixu = lambda s: unicode(s, 'unicode_escape') class SphinxDocString(NumpyDocString): def __init__(self, docstring, config={}): self.use_plots = config.get('use_plots', False) NumpyDocString.__init__(self, docstring, config=config) # string conversion routines def _str_header(self, name, symbol='`'): return ['.. rubric:: ' + name, ''] def _str_field_list(self, name): return [':' + name + ':'] def _str_indent(self, doc, indent=4): out = [] for line in doc: out += [' '*indent + line] return out def _str_signature(self): return [''] if self['Signature']: return ['``%s``' % self['Signature']] + [''] else: return [''] def _str_summary(self): return self['Summary'] + [''] def _str_extended_summary(self): return self['Extended Summary'] + [''] def _str_returns(self): out = [] if self['Returns']: out += self._str_field_list('Returns') out += [''] for param, param_type, desc in self['Returns']: if param_type: out += self._str_indent(['**%s** : %s' % (param.strip(), param_type)]) else: out += self._str_indent([param.strip()]) if desc: out += [''] out += self._str_indent(desc, 8) out += [''] return out def _str_param_list(self, name): out = [] if self[name]: out += self._str_field_list(name) out += [''] for param, param_type, desc in self[name]: if param_type: out += self._str_indent(['**%s** : %s' % (param.strip(), param_type)]) else: out += self._str_indent(['**%s**' % param.strip()]) if desc: out += [''] out += self._str_indent(desc, 8) out += [''] return out @property def _obj(self): if hasattr(self, '_cls'): return self._cls elif hasattr(self, '_f'): return self._f return None def _str_member_list(self, name): """ Generate a member listing, autosummary:: table where possible, and a table where not. """ out = [] if self[name]: out += ['.. rubric:: %s' % name, ''] prefix = getattr(self, '_name', '') if prefix: prefix = '~%s.' % prefix autosum = [] others = [] for param, param_type, desc in self[name]: param = param.strip() # Check if the referenced member can have a docstring or not param_obj = getattr(self._obj, param, None) if not (callable(param_obj) or isinstance(param_obj, property) or inspect.isgetsetdescriptor(param_obj)): param_obj = None if param_obj and (pydoc.getdoc(param_obj) or not desc): # Referenced object has a docstring autosum += [" %s%s" % (prefix, param)] else: others.append((param, param_type, desc)) if autosum: out += ['.. autosummary::', ' :toctree:', ''] out += autosum if others: maxlen_0 = max(3, max([len(x[0]) for x in others])) hdr = sixu("=")*maxlen_0 + sixu(" ") + sixu("=")*10 fmt = sixu('%%%ds %%s ') % (maxlen_0,) out += ['', hdr] for param, param_type, desc in others: desc = sixu(" ").join(x.strip() for x in desc).strip() if param_type: desc = "(%s) %s" % (param_type, desc) out += [fmt % (param.strip(), desc)] out += [hdr] out += [''] return out def _str_section(self, name): out = [] if self[name]: out += self._str_header(name) out += [''] content = textwrap.dedent("\n".join(self[name])).split("\n") out += content out += [''] return out def _str_see_also(self, func_role): out = [] if self['See Also']: see_also = super(SphinxDocString, self)._str_see_also(func_role) out = ['.. seealso::', ''] out += self._str_indent(see_also[2:]) return out def _str_warnings(self): out = [] if self['Warnings']: out = ['.. warning::', ''] out += self._str_indent(self['Warnings']) return out def _str_index(self): idx = self['index'] out = [] if len(idx) == 0: return out out += ['.. index:: %s' % idx.get('default','')] for section, references in idx.items(): if section == 'default': continue elif section == 'refguide': out += [' single: %s' % (', '.join(references))] else: out += [' %s: %s' % (section, ','.join(references))] return out def _str_references(self): out = [] if self['References']: out += self._str_header('References') if isinstance(self['References'], str): self['References'] = [self['References']] out.extend(self['References']) out += [''] # Latex collects all references to a separate bibliography, # so we need to insert links to it if sphinx.__version__ >= "0.6": out += ['.. only:: latex',''] else: out += ['.. latexonly::',''] items = [] for line in self['References']: m = re.match(r'.. \[([a-z0-9._-]+)\]', line, re.I) if m: items.append(m.group(1)) out += [' ' + ", ".join(["[%s]_" % item for item in items]), ''] return out def _str_examples(self): examples_str = "\n".join(self['Examples']) if (self.use_plots and 'import matplotlib' in examples_str and 'plot::' not in examples_str): out = [] out += self._str_header('Examples') out += ['.. plot::', ''] out += self._str_indent(self['Examples']) out += [''] return out else: return self._str_section('Examples') def __str__(self, indent=0, func_role="obj"): out = [] out += self._str_signature() out += self._str_index() + [''] out += self._str_summary() out += self._str_extended_summary() out += self._str_param_list('Parameters') out += self._str_returns() for param_list in ('Other Parameters', 'Raises', 'Warns'): out += self._str_param_list(param_list) out += self._str_warnings() out += self._str_see_also(func_role) out += self._str_section('Notes') out += self._str_references() out += self._str_examples() for param_list in ('Attributes', 'Methods'): out += self._str_member_list(param_list) out = self._str_indent(out,indent) return '\n'.join(out) class SphinxFunctionDoc(SphinxDocString, FunctionDoc): def __init__(self, obj, doc=None, config={}): self.use_plots = config.get('use_plots', False) FunctionDoc.__init__(self, obj, doc=doc, config=config) class SphinxClassDoc(SphinxDocString, ClassDoc): def __init__(self, obj, doc=None, func_doc=None, config={}): self.use_plots = config.get('use_plots', False) ClassDoc.__init__(self, obj, doc=doc, func_doc=None, config=config) class SphinxObjDoc(SphinxDocString): def __init__(self, obj, doc=None, config={}): self._f = obj SphinxDocString.__init__(self, doc, config=config) def get_doc_object(obj, what=None, doc=None, config={}): if what is None: if inspect.isclass(obj): what = 'class' elif inspect.ismodule(obj): what = 'module' elif isinstance(obj, collections.Callable): what = 'function' else: what = 'object' if what == 'class': return SphinxClassDoc(obj, func_doc=SphinxFunctionDoc, doc=doc, config=config) elif what in ('function', 'method'): return SphinxFunctionDoc(obj, doc=doc, config=config) else: if doc is None: doc = pydoc.getdoc(obj) return SphinxObjDoc(obj, doc, config=config) numpy-1.8.2/doc/sphinxext/numpydoc/comment_eater.py0000664000175100017510000001245112370216247023664 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function import sys if sys.version_info[0] >= 3: from io import StringIO else: from io import StringIO import compiler import inspect import textwrap import tokenize from .compiler_unparse import unparse class Comment(object): """ A comment block. """ is_comment = True def __init__(self, start_lineno, end_lineno, text): # int : The first line number in the block. 1-indexed. self.start_lineno = start_lineno # int : The last line number. Inclusive! self.end_lineno = end_lineno # str : The text block including '#' character but not any leading spaces. self.text = text def add(self, string, start, end, line): """ Add a new comment line. """ self.start_lineno = min(self.start_lineno, start[0]) self.end_lineno = max(self.end_lineno, end[0]) self.text += string def __repr__(self): return '%s(%r, %r, %r)' % (self.__class__.__name__, self.start_lineno, self.end_lineno, self.text) class NonComment(object): """ A non-comment block of code. """ is_comment = False def __init__(self, start_lineno, end_lineno): self.start_lineno = start_lineno self.end_lineno = end_lineno def add(self, string, start, end, line): """ Add lines to the block. """ if string.strip(): # Only add if not entirely whitespace. self.start_lineno = min(self.start_lineno, start[0]) self.end_lineno = max(self.end_lineno, end[0]) def __repr__(self): return '%s(%r, %r)' % (self.__class__.__name__, self.start_lineno, self.end_lineno) class CommentBlocker(object): """ Pull out contiguous comment blocks. """ def __init__(self): # Start with a dummy. self.current_block = NonComment(0, 0) # All of the blocks seen so far. self.blocks = [] # The index mapping lines of code to their associated comment blocks. self.index = {} def process_file(self, file): """ Process a file object. """ if sys.version_info[0] >= 3: nxt = file.__next__ else: nxt = file.next for token in tokenize.generate_tokens(nxt): self.process_token(*token) self.make_index() def process_token(self, kind, string, start, end, line): """ Process a single token. """ if self.current_block.is_comment: if kind == tokenize.COMMENT: self.current_block.add(string, start, end, line) else: self.new_noncomment(start[0], end[0]) else: if kind == tokenize.COMMENT: self.new_comment(string, start, end, line) else: self.current_block.add(string, start, end, line) def new_noncomment(self, start_lineno, end_lineno): """ We are transitioning from a noncomment to a comment. """ block = NonComment(start_lineno, end_lineno) self.blocks.append(block) self.current_block = block def new_comment(self, string, start, end, line): """ Possibly add a new comment. Only adds a new comment if this comment is the only thing on the line. Otherwise, it extends the noncomment block. """ prefix = line[:start[1]] if prefix.strip(): # Oops! Trailing comment, not a comment block. self.current_block.add(string, start, end, line) else: # A comment block. block = Comment(start[0], end[0], string) self.blocks.append(block) self.current_block = block def make_index(self): """ Make the index mapping lines of actual code to their associated prefix comments. """ for prev, block in zip(self.blocks[:-1], self.blocks[1:]): if not block.is_comment: self.index[block.start_lineno] = prev def search_for_comment(self, lineno, default=None): """ Find the comment block just before the given line number. Returns None (or the specified default) if there is no such block. """ if not self.index: self.make_index() block = self.index.get(lineno, None) text = getattr(block, 'text', default) return text def strip_comment_marker(text): """ Strip # markers at the front of a block of comment text. """ lines = [] for line in text.splitlines(): lines.append(line.lstrip('#')) text = textwrap.dedent('\n'.join(lines)) return text def get_class_traits(klass): """ Yield all of the documentation for trait definitions on a class object. """ # FIXME: gracefully handle errors here or in the caller? source = inspect.getsource(klass) cb = CommentBlocker() cb.process_file(StringIO(source)) mod_ast = compiler.parse(source) class_ast = mod_ast.node.nodes[0] for node in class_ast.code.nodes: # FIXME: handle other kinds of assignments? if isinstance(node, compiler.ast.Assign): name = node.nodes[0].name rhs = unparse(node.expr).strip() doc = strip_comment_marker(cb.search_for_comment(node.lineno, default='')) yield name, rhs, doc numpy-1.8.2/doc/sphinxext/numpydoc/__init__.py0000664000175100017510000000013612370216247022576 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function from .numpydoc import setup numpy-1.8.2/doc/sphinxext/numpydoc/numpydoc.py0000664000175100017510000001416212370216247022701 0ustar vagrantvagrant00000000000000""" ======== numpydoc ======== Sphinx extension that handles docstrings in the Numpy standard format. [1] It will: - Convert Parameters etc. sections to field lists. - Convert See Also section to a See also entry. - Renumber references. - Extract the signature from the docstring, if it can't be determined otherwise. .. [1] https://github.com/numpy/numpy/blob/master/doc/HOWTO_DOCUMENT.rst.txt """ from __future__ import division, absolute_import, print_function import os, sys, re, pydoc import sphinx import inspect import collections if sphinx.__version__ < '1.0.1': raise RuntimeError("Sphinx 1.0.1 or newer is required") from .docscrape_sphinx import get_doc_object, SphinxDocString from sphinx.util.compat import Directive if sys.version_info[0] >= 3: sixu = lambda s: s else: sixu = lambda s: unicode(s, 'unicode_escape') def mangle_docstrings(app, what, name, obj, options, lines, reference_offset=[0]): cfg = dict(use_plots=app.config.numpydoc_use_plots, show_class_members=app.config.numpydoc_show_class_members) if what == 'module': # Strip top title title_re = re.compile(sixu('^\\s*[#*=]{4,}\\n[a-z0-9 -]+\\n[#*=]{4,}\\s*'), re.I|re.S) lines[:] = title_re.sub(sixu(''), sixu("\n").join(lines)).split(sixu("\n")) else: doc = get_doc_object(obj, what, sixu("\n").join(lines), config=cfg) if sys.version_info[0] >= 3: doc = str(doc) else: doc = str(doc).decode('utf-8') lines[:] = doc.split(sixu("\n")) if app.config.numpydoc_edit_link and hasattr(obj, '__name__') and \ obj.__name__: if hasattr(obj, '__module__'): v = dict(full_name=sixu("%s.%s") % (obj.__module__, obj.__name__)) else: v = dict(full_name=obj.__name__) lines += [sixu(''), sixu('.. htmlonly::'), sixu('')] lines += [sixu(' %s') % x for x in (app.config.numpydoc_edit_link % v).split("\n")] # replace reference numbers so that there are no duplicates references = [] for line in lines: line = line.strip() m = re.match(sixu('^.. \\[([a-z0-9_.-])\\]'), line, re.I) if m: references.append(m.group(1)) # start renaming from the longest string, to avoid overwriting parts references.sort(key=lambda x: -len(x)) if references: for i, line in enumerate(lines): for r in references: if re.match(sixu('^\\d+$'), r): new_r = sixu("R%d") % (reference_offset[0] + int(r)) else: new_r = sixu("%s%d") % (r, reference_offset[0]) lines[i] = lines[i].replace(sixu('[%s]_') % r, sixu('[%s]_') % new_r) lines[i] = lines[i].replace(sixu('.. [%s]') % r, sixu('.. [%s]') % new_r) reference_offset[0] += len(references) def mangle_signature(app, what, name, obj, options, sig, retann): # Do not try to inspect classes that don't define `__init__` if (inspect.isclass(obj) and (not hasattr(obj, '__init__') or 'initializes x; see ' in pydoc.getdoc(obj.__init__))): return '', '' if not (isinstance(obj, collections.Callable) or hasattr(obj, '__argspec_is_invalid_')): return if not hasattr(obj, '__doc__'): return doc = SphinxDocString(pydoc.getdoc(obj)) if doc['Signature']: sig = re.sub(sixu("^[^(]*"), sixu(""), doc['Signature']) return sig, sixu('') def setup(app, get_doc_object_=get_doc_object): if not hasattr(app, 'add_config_value'): return # probably called by nose, better bail out global get_doc_object get_doc_object = get_doc_object_ app.connect('autodoc-process-docstring', mangle_docstrings) app.connect('autodoc-process-signature', mangle_signature) app.add_config_value('numpydoc_edit_link', None, False) app.add_config_value('numpydoc_use_plots', None, False) app.add_config_value('numpydoc_show_class_members', True, True) # Extra mangling domains app.add_domain(NumpyPythonDomain) app.add_domain(NumpyCDomain) #------------------------------------------------------------------------------ # Docstring-mangling domains #------------------------------------------------------------------------------ from docutils.statemachine import ViewList from sphinx.domains.c import CDomain from sphinx.domains.python import PythonDomain class ManglingDomainBase(object): directive_mangling_map = {} def __init__(self, *a, **kw): super(ManglingDomainBase, self).__init__(*a, **kw) self.wrap_mangling_directives() def wrap_mangling_directives(self): for name, objtype in list(self.directive_mangling_map.items()): self.directives[name] = wrap_mangling_directive( self.directives[name], objtype) class NumpyPythonDomain(ManglingDomainBase, PythonDomain): name = 'np' directive_mangling_map = { 'function': 'function', 'class': 'class', 'exception': 'class', 'method': 'function', 'classmethod': 'function', 'staticmethod': 'function', 'attribute': 'attribute', } indices = [] class NumpyCDomain(ManglingDomainBase, CDomain): name = 'np-c' directive_mangling_map = { 'function': 'function', 'member': 'attribute', 'macro': 'function', 'type': 'class', 'var': 'object', } def wrap_mangling_directive(base_directive, objtype): class directive(base_directive): def run(self): env = self.state.document.settings.env name = None if self.arguments: m = re.match(r'^(.*\s+)?(.*?)(\(.*)?', self.arguments[0]) name = m.group(2).strip() if not name: name = self.arguments[0] lines = list(self.content) mangle_docstrings(env.app, objtype, name, None, None, lines) self.content = ViewList(lines, self.content.parent) return base_directive.run(self) return directive numpy-1.8.2/doc/sphinxext/numpydoc/traitsdoc.py0000664000175100017510000001026112370216247023033 0ustar vagrantvagrant00000000000000""" ========= traitsdoc ========= Sphinx extension that handles docstrings in the Numpy standard format, [1] and support Traits [2]. This extension can be used as a replacement for ``numpydoc`` when support for Traits is required. .. [1] http://projects.scipy.org/numpy/wiki/CodingStyleGuidelines#docstring-standard .. [2] http://code.enthought.com/projects/traits/ """ from __future__ import division, absolute_import, print_function import inspect import os import pydoc import collections from . import docscrape from . import docscrape_sphinx from .docscrape_sphinx import SphinxClassDoc, SphinxFunctionDoc, SphinxDocString from . import numpydoc from . import comment_eater class SphinxTraitsDoc(SphinxClassDoc): def __init__(self, cls, modulename='', func_doc=SphinxFunctionDoc): if not inspect.isclass(cls): raise ValueError("Initialise using a class. Got %r" % cls) self._cls = cls if modulename and not modulename.endswith('.'): modulename += '.' self._mod = modulename self._name = cls.__name__ self._func_doc = func_doc docstring = pydoc.getdoc(cls) docstring = docstring.split('\n') # De-indent paragraph try: indent = min(len(s) - len(s.lstrip()) for s in docstring if s.strip()) except ValueError: indent = 0 for n,line in enumerate(docstring): docstring[n] = docstring[n][indent:] self._doc = docscrape.Reader(docstring) self._parsed_data = { 'Signature': '', 'Summary': '', 'Description': [], 'Extended Summary': [], 'Parameters': [], 'Returns': [], 'Raises': [], 'Warns': [], 'Other Parameters': [], 'Traits': [], 'Methods': [], 'See Also': [], 'Notes': [], 'References': '', 'Example': '', 'Examples': '', 'index': {} } self._parse() def _str_summary(self): return self['Summary'] + [''] def _str_extended_summary(self): return self['Description'] + self['Extended Summary'] + [''] def __str__(self, indent=0, func_role="func"): out = [] out += self._str_signature() out += self._str_index() + [''] out += self._str_summary() out += self._str_extended_summary() for param_list in ('Parameters', 'Traits', 'Methods', 'Returns','Raises'): out += self._str_param_list(param_list) out += self._str_see_also("obj") out += self._str_section('Notes') out += self._str_references() out += self._str_section('Example') out += self._str_section('Examples') out = self._str_indent(out,indent) return '\n'.join(out) def looks_like_issubclass(obj, classname): """ Return True if the object has a class or superclass with the given class name. Ignores old-style classes. """ t = obj if t.__name__ == classname: return True for klass in t.__mro__: if klass.__name__ == classname: return True return False def get_doc_object(obj, what=None, config=None): if what is None: if inspect.isclass(obj): what = 'class' elif inspect.ismodule(obj): what = 'module' elif isinstance(obj, collections.Callable): what = 'function' else: what = 'object' if what == 'class': doc = SphinxTraitsDoc(obj, '', func_doc=SphinxFunctionDoc, config=config) if looks_like_issubclass(obj, 'HasTraits'): for name, trait, comment in comment_eater.get_class_traits(obj): # Exclude private traits. if not name.startswith('_'): doc['Traits'].append((name, trait, comment.splitlines())) return doc elif what in ('function', 'method'): return SphinxFunctionDoc(obj, '', config=config) else: return SphinxDocString(pydoc.getdoc(obj), config=config) def setup(app): # init numpydoc numpydoc.setup(app, get_doc_object) numpy-1.8.2/doc/sphinxext/setup.py0000664000175100017510000000177312370216247020351 0ustar vagrantvagrant00000000000000from __future__ import division, print_function import sys import setuptools from distutils.core import setup if sys.version_info[:2] < (2, 6) or (3, 0) <= sys.version_info[0:2] < (3, 3): raise RuntimeError("Python version 2.6, 2.7 or >= 3.3 required.") version = "0.4.dev" setup( name="numpydoc", packages=["numpydoc"], version=version, description="Sphinx extension to support docstrings in Numpy format", # classifiers from http://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=["Development Status :: 3 - Alpha", "Environment :: Plugins", "License :: OSI Approved :: BSD License", "Topic :: Documentation"], keywords="sphinx numpy", author="Pauli Virtanen and others", author_email="pav@iki.fi", url="http://github.com/numpy/numpy/tree/master/doc/sphinxext", license="BSD", requires=["sphinx (>= 1.0.1)"], package_data={'numpydoc': ['tests/test_*.py']}, test_suite = 'nose.collector', ) numpy-1.8.2/doc/source/0000775000175100017510000000000012371375427016104 5ustar vagrantvagrant00000000000000numpy-1.8.2/doc/source/release.rst0000664000175100017510000000101312370220414020231 0ustar vagrantvagrant00000000000000************* Release Notes ************* .. include:: ../release/1.8.2-notes.rst .. include:: ../release/1.8.1-notes.rst .. include:: ../release/1.8.0-notes.rst .. include:: ../release/1.7.2-notes.rst .. include:: ../release/1.7.1-notes.rst .. include:: ../release/1.7.0-notes.rst .. include:: ../release/1.6.2-notes.rst .. include:: ../release/1.6.1-notes.rst .. include:: ../release/1.6.0-notes.rst .. include:: ../release/1.5.0-notes.rst .. include:: ../release/1.4.0-notes.rst .. include:: ../release/1.3.0-notes.rst numpy-1.8.2/doc/source/user/0000775000175100017510000000000012371375427017062 5ustar vagrantvagrant00000000000000numpy-1.8.2/doc/source/user/howtofind.rst0000664000175100017510000000026612370216242021605 0ustar vagrantvagrant00000000000000************************* How to find documentation ************************* .. seealso:: :ref:`Numpy-specific help functions ` .. automodule:: numpy.doc.howtofind numpy-1.8.2/doc/source/user/basics.byteswapping.rst0000664000175100017510000000012212370216242023552 0ustar vagrantvagrant00000000000000************* Byte-swapping ************* .. automodule:: numpy.doc.byteswapping numpy-1.8.2/doc/source/user/c-info.ufunc-tutorial.rst0000664000175100017510000011102712370216242023735 0ustar vagrantvagrant00000000000000********************** Writing your own ufunc ********************** | I have the Power! | --- *He-Man* .. _`sec:Creating-a-new`: Creating a new universal function ================================= .. index:: pair: ufunc; adding new Before reading this, it may help to familiarize yourself with the basics of C extensions for Python by reading/skimming the tutorials in Section 1 of `Extending and Embedding the Python Interpreter `_ and in `How to extend Numpy `_ The umath module is a computer-generated C-module that creates many ufuncs. It provides a great many examples of how to create a universal function. Creating your own ufunc that will make use of the ufunc machinery is not difficult either. Suppose you have a function that you want to operate element-by-element over its inputs. By creating a new ufunc you will obtain a function that handles - broadcasting - N-dimensional looping - automatic type-conversions with minimal memory usage - optional output arrays It is not difficult to create your own ufunc. All that is required is a 1-d loop for each data-type you want to support. Each 1-d loop must have a specific signature, and only ufuncs for fixed-size data-types can be used. The function call used to create a new ufunc to work on built-in data-types is given below. A different mechanism is used to register ufuncs for user-defined data-types. In the next several sections we give example code that can be easily modified to create your own ufuncs. The examples are successively more complete or complicated versions of the logit function, a common function in statistical modeling. Logit is also interesting because, due to the magic of IEEE standards (specifically IEEE 754), all of the logit functions created below automatically have the following behavior. >>> logit(0) -inf >>> logit(1) inf >>> logit(2) nan >>> logit(-2) nan This is wonderful because the function writer doesn't have to manually propagate infs or nans. .. _`sec:Non-numpy-example`: Example Non-ufunc extension =========================== .. index:: pair: ufunc; adding new For comparison and general edificaiton of the reader we provide a simple implementation of a C extension of logit that uses no numpy. To do this we need two files. The first is the C file which contains the actual code, and the second is the setup.py file used to create the module. .. code-block:: c #include #include /* * spammodule.c * This is the C code for a non-numpy Python extension to * define the logit function, where logit(p) = log(p/(1-p)). * This function will not work on numpy arrays automatically. * numpy.vectorize must be called in python to generate * a numpy-friendly function. * * Details explaining the Python-C API can be found under * 'Extending and Embedding' and 'Python/C API' at * docs.python.org . */ /* This declares the logit function */ static PyObject* spam_logit(PyObject *self, PyObject *args); /* * This tells Python what methods this module has. * See the Python-C API for more information. */ static PyMethodDef SpamMethods[] = { {"logit", spam_logit, METH_VARARGS, "compute logit"}, {NULL, NULL, 0, NULL} }; /* * This actually defines the logit function for * input args from Python. */ static PyObject* spam_logit(PyObject *self, PyObject *args) { double p; /* This parses the Python argument into a double */ if(!PyArg_ParseTuple(args, "d", &p)) { return NULL; } /* THE ACTUAL LOGIT FUNCTION */ p = p/(1-p); p = log(p); /*This builds the answer back into a python object */ return Py_BuildValue("d", p); } /* This initiates the module using the above definitions. */ #if PY_VERSION_HEX >= 0x03000000 static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, "spam", NULL, -1, SpamMethods, NULL, NULL, NULL, NULL }; PyMODINIT_FUNC PyInit_spam(void) { PyObject *m; m = PyModule_Create(&moduledef); if (!m) { return NULL; } return m; } #else PyMODINIT_FUNC initspam(void) { PyObject *m; m = Py_InitModule("spam", SpamMethods); if (m == NULL) { return; } } #endif To use the setup.py file, place setup.py and spammodule.c in the same folder. Then python setup.py build will build the module to import, or setup.py install will install the module to your site-packages directory. .. code-block:: python ''' setup.py file for spammodule.c Calling $python setup.py build_ext --inplace will build the extension library in the current file. Calling $python setup.py build will build a file that looks like ./build/lib*, where lib* is a file that begins with lib. The library will be in this file and end with a C library extension, such as .so Calling $python setup.py install will install the module in your site-packages file. See the distutils section of 'Extending and Embedding the Python Interpreter' at docs.python.org for more information. ''' from distutils.core import setup, Extension module1 = Extension('spam', sources=['spammodule.c'], include_dirs=['/usr/local/lib']) setup(name = 'spam', version='1.0', description='This is my spam package', ext_modules = [module1]) Once the spam module is imported into python, you can call logit via spam.logit. Note that the function used above cannot be applied as-is to numpy arrays. To do so we must call numpy.vectorize on it. For example, if a python interpreter is opened in the file containing the spam library or spam has been installed, one can perform the following commands: >>> import numpy as np >>> import spam >>> spam.logit(0) -inf >>> spam.logit(1) inf >>> spam.logit(0.5) 0.0 >>> x = np.linspace(0,1,10) >>> spam.logit(x) TypeError: only length-1 arrays can be converted to Python scalars >>> f = np.vectorize(spam.logit) >>> f(x) array([ -inf, -2.07944154, -1.25276297, -0.69314718, -0.22314355, 0.22314355, 0.69314718, 1.25276297, 2.07944154, inf]) THE RESULTING LOGIT FUNCTION IS NOT FAST! numpy.vectorize simply loops over spam.logit. The loop is done at the C level, but the numpy array is constantly being parsed and build back up. This is expensive. When the author compared numpy.vectorize(spam.logit) against the logit ufuncs constructed below, the logit ufuncs were almost exactly 4 times faster. Larger or smaller speedups are, of course, possible depending on the nature of the function. .. _`sec:Numpy-one-loop`: Example Numpy ufunc for one dtype ================================= .. index:: pair: ufunc; adding new For simplicity we give a ufunc for a single dtype, the 'f8' double. As in the previous section, we first give the .c file and then the setup.py file used to create the module containing the ufunc. The place in the code corresponding to the actual computations for the ufunc are marked with /\*BEGIN main ufunc computation\*/ and /\*END main ufunc computation\*/. The code in between those lines is the primary thing that must be changed to create your own ufunc. .. code-block:: c #include "Python.h" #include "math.h" #include "numpy/ndarraytypes.h" #include "numpy/ufuncobject.h" #include "numpy/npy_3kcompat.h" /* * single_type_logit.c * This is the C code for creating your own * Numpy ufunc for a logit function. * * In this code we only define the ufunc for * a single dtype. The computations that must * be replaced to create a ufunc for * a different funciton are marked with BEGIN * and END. * * Details explaining the Python-C API can be found under * 'Extending and Embedding' and 'Python/C API' at * docs.python.org . */ static PyMethodDef LogitMethods[] = { {NULL, NULL, 0, NULL} }; /* The loop definition must precede the PyMODINIT_FUNC. */ static void double_logit(char **args, npy_intp *dimensions, npy_intp* steps, void* data) { npy_intp i; npy_intp n = dimensions[0]; char *in = args[0], *out = args[1]; npy_intp in_step = steps[0], out_step = steps[1]; double tmp; for (i = 0; i < n; i++) { /*BEGIN main ufunc computation*/ tmp = *(double *)in; tmp /= 1-tmp; *((double *)out) = log(tmp); /*END main ufunc computation*/ in += in_step; out += out_step; } } /*This a pointer to the above function*/ PyUFuncGenericFunction funcs[1] = {&double_logit}; /* These are the input and return dtypes of logit.*/ static char types[2] = {NPY_DOUBLE, NPY_DOUBLE}; static void *data[1] = {NULL}; #if PY_VERSION_HEX >= 0x03000000 static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, "npufunc", NULL, -1, LogitMethods, NULL, NULL, NULL, NULL }; PyMODINIT_FUNC PyInit_npufunc(void) { PyObject *m, *logit, *d; m = PyModule_Create(&moduledef); if (!m) { return NULL; } import_array(); import_umath(); logit = PyUFunc_FromFuncAndData(funcs, data, types, 1, 1, 1, PyUFunc_None, "logit", "logit_docstring", 0); d = PyModule_GetDict(m); PyDict_SetItemString(d, "logit", logit); Py_DECREF(logit); return m; } #else PyMODINIT_FUNC initnpufunc(void) { PyObject *m, *logit, *d; m = Py_InitModule("npufunc", LogitMethods); if (m == NULL) { return; } import_array(); import_umath(); logit = PyUFunc_FromFuncAndData(funcs, data, types, 1, 1, 1, PyUFunc_None, "logit", "logit_docstring", 0); d = PyModule_GetDict(m); PyDict_SetItemString(d, "logit", logit); Py_DECREF(logit); } #endif This is a setup.py file for the above code. As before, the module can be build via calling python setup.py build at the command prompt, or installed to site-packages via python setup.py install. .. code-block:: python ''' setup.py file for logit.c Note that since this is a numpy extension we use numpy.distutils instead of distutils from the python standard library. Calling $python setup.py build_ext --inplace will build the extension library in the current file. Calling $python setup.py build will build a file that looks like ./build/lib*, where lib* is a file that begins with lib. The library will be in this file and end with a C library extension, such as .so Calling $python setup.py install will install the module in your site-packages file. See the distutils section of 'Extending and Embedding the Python Interpreter' at docs.python.org and the documentation on numpy.distutils for more information. ''' def configuration(parent_package='', top_path=None): import numpy from numpy.distutils.misc_util import Configuration config = Configuration('npufunc_directory', parent_package, top_path) config.add_extension('npufunc', ['single_type_logit.c']) return config if __name__ == "__main__": from numpy.distutils.core import setup setup(configuration=configuration) After the above has been installed, it can be imported and used as follows. >>> import numpy as np >>> import npufunc >>> npufunc.logit(0.5) 0.0 >>> a = np.linspace(0,1,5) >>> npufunc.logit(a) array([ -inf, -1.09861229, 0. , 1.09861229, inf]) .. _`sec:Numpy-many-loop`: Example Numpy ufunc with multiple dtypes ======================================== .. index:: pair: ufunc; adding new We finally give an example of a full ufunc, with inner loops for half-floats, floats, doubles, and long doubles. As in the previous sections we first give the .c file and then the corresponding setup.py file. The places in the code corresponding to the actual computations for the ufunc are marked with /\*BEGIN main ufunc computation\*/ and /\*END main ufunc computation\*/. The code in between those lines is the primary thing that must be changed to create your own ufunc. .. code-block:: c #include "Python.h" #include "math.h" #include "numpy/ndarraytypes.h" #include "numpy/ufuncobject.h" #include "numpy/halffloat.h" /* * multi_type_logit.c * This is the C code for creating your own * Numpy ufunc for a logit function. * * Each function of the form type_logit defines the * logit function for a different numpy dtype. Each * of these functions must be modified when you * create your own ufunc. The computations that must * be replaced to create a ufunc for * a different funciton are marked with BEGIN * and END. * * Details explaining the Python-C API can be found under * 'Extending and Embedding' and 'Python/C API' at * docs.python.org . * */ static PyMethodDef LogitMethods[] = { {NULL, NULL, 0, NULL} }; /* The loop definitions must precede the PyMODINIT_FUNC. */ static void long_double_logit(char **args, npy_intp *dimensions, npy_intp* steps, void* data) { npy_intp i; npy_intp n = dimensions[0]; char *in = args[0], *out=args[1]; npy_intp in_step = steps[0], out_step = steps[1]; long double tmp; for (i = 0; i < n; i++) { /*BEGIN main ufunc computation*/ tmp = *(long double *)in; tmp /= 1-tmp; *((long double *)out) = logl(tmp); /*END main ufunc computation*/ in += in_step; out += out_step; } } static void double_logit(char **args, npy_intp *dimensions, npy_intp* steps, void* data) { npy_intp i; npy_intp n = dimensions[0]; char *in = args[0], *out = args[1]; npy_intp in_step = steps[0], out_step = steps[1]; double tmp; for (i = 0; i < n; i++) { /*BEGIN main ufunc computation*/ tmp = *(double *)in; tmp /= 1-tmp; *((double *)out) = log(tmp); /*END main ufunc computation*/ in += in_step; out += out_step; } } static void float_logit(char **args, npy_intp *dimensions, npy_intp* steps, void* data) { npy_intp i; npy_intp n = dimensions[0]; char *in=args[0], *out = args[1]; npy_intp in_step = steps[0], out_step = steps[1]; float tmp; for (i = 0; i < n; i++) { /*BEGIN main ufunc computation*/ tmp = *(float *)in; tmp /= 1-tmp; *((float *)out) = logf(tmp); /*END main ufunc computation*/ in += in_step; out += out_step; } } static void half_float_logit(char **args, npy_intp *dimensions, npy_intp* steps, void* data) { npy_intp i; npy_intp n = dimensions[0]; char *in = args[0], *out = args[1]; npy_intp in_step = steps[0], out_step = steps[1]; float tmp; for (i = 0; i < n; i++) { /*BEGIN main ufunc computation*/ tmp = *(npy_half *)in; tmp = npy_half_to_float(tmp); tmp /= 1-tmp; tmp = logf(tmp); *((npy_half *)out) = npy_float_to_half(tmp); /*END main ufunc computation*/ in += in_step; out += out_step; } } /*This gives pointers to the above functions*/ PyUFuncGenericFunction funcs[4] = {&half_float_logit, &float_logit, &double_logit, &long_double_logit}; static char types[8] = {NPY_HALF, NPY_HALF, NPY_FLOAT, NPY_FLOAT, NPY_DOUBLE,NPY_DOUBLE, NPY_LONGDOUBLE, NPY_LONGDOUBLE}; static void *data[4] = {NULL, NULL, NULL, NULL}; #if PY_VERSION_HEX >= 0x03000000 static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, "npufunc", NULL, -1, LogitMethods, NULL, NULL, NULL, NULL }; PyMODINIT_FUNC PyInit_npufunc(void) { PyObject *m, *logit, *d; m = PyModule_Create(&moduledef); if (!m) { return NULL; } import_array(); import_umath(); logit = PyUFunc_FromFuncAndData(funcs, data, types, 4, 1, 1, PyUFunc_None, "logit", "logit_docstring", 0); d = PyModule_GetDict(m); PyDict_SetItemString(d, "logit", logit); Py_DECREF(logit); return m; } #else PyMODINIT_FUNC initnpufunc(void) { PyObject *m, *logit, *d; m = Py_InitModule("npufunc", LogitMethods); if (m == NULL) { return; } import_array(); import_umath(); logit = PyUFunc_FromFuncAndData(funcs, data, types, 4, 1, 1, PyUFunc_None, "logit", "logit_docstring", 0); d = PyModule_GetDict(m); PyDict_SetItemString(d, "logit", logit); Py_DECREF(logit); } #endif This is a setup.py file for the above code. As before, the module can be build via calling python setup.py build at the command prompt, or installed to site-packages via python setup.py install. .. code-block:: python ''' setup.py file for logit.c Note that since this is a numpy extension we use numpy.distutils instead of distutils from the python standard library. Calling $python setup.py build_ext --inplace will build the extension library in the current file. Calling $python setup.py build will build a file that looks like ./build/lib*, where lib* is a file that begins with lib. The library will be in this file and end with a C library extension, such as .so Calling $python setup.py install will install the module in your site-packages file. See the distutils section of 'Extending and Embedding the Python Interpreter' at docs.python.org and the documentation on numpy.distutils for more information. ''' def configuration(parent_package='', top_path=None): import numpy from numpy.distutils.misc_util import Configuration from numpy.distutils.misc_util import get_info #Necessary for the half-float d-type. info = get_info('npymath') config = Configuration('npufunc_directory', parent_package, top_path) config.add_extension('npufunc', ['multi_type_logit.c'], extra_info=info) return config if __name__ == "__main__": from numpy.distutils.core import setup setup(configuration=configuration) After the above has been installed, it can be imported and used as follows. >>> import numpy as np >>> import npufunc >>> npufunc.logit(0.5) 0.0 >>> a = np.linspace(0,1,5) >>> npufunc.logit(a) array([ -inf, -1.09861229, 0. , 1.09861229, inf]) .. _`sec:Numpy-many-arg`: Example Numpy ufunc with multiple arguments/return values ========================================================= Our final example is a ufunc with multiple arguments. It is a modification of the code for a logit ufunc for data with a single dtype. We compute (A*B, logit(A*B)). We only give the C code as the setup.py file is exactly the same as the setup.py file in `Example Numpy ufunc for one dtype`_, except that the line .. code-block:: python config.add_extension('npufunc', ['single_type_logit.c']) is replaced with .. code-block:: python config.add_extension('npufunc', ['multi_arg_logit.c']) The C file is given below. The ufunc generated takes two arguments A and B. It returns a tuple whose first element is A*B and whose second element is logit(A*B). Note that it automatically supports broadcasting, as well as all other properties of a ufunc. .. code-block:: c #include "Python.h" #include "math.h" #include "numpy/ndarraytypes.h" #include "numpy/ufuncobject.h" #include "numpy/halffloat.h" /* * multi_arg_logit.c * This is the C code for creating your own * Numpy ufunc for a multiple argument, multiple * return value ufunc. The places where the * ufunc computation is carried out are marked * with comments. * * Details explaining the Python-C API can be found under * 'Extending and Embedding' and 'Python/C API' at * docs.python.org . * */ static PyMethodDef LogitMethods[] = { {NULL, NULL, 0, NULL} }; /* The loop definition must precede the PyMODINIT_FUNC. */ static void double_logitprod(char **args, npy_intp *dimensions, npy_intp* steps, void* data) { npy_intp i; npy_intp n = dimensions[0]; char *in1 = args[0], *in2 = args[1]; char *out1 = args[2], *out2 = args[3]; npy_intp in1_step = steps[0], in2_step = steps[1]; npy_intp out1_step = steps[2], out2_step = steps[3]; double tmp; for (i = 0; i < n; i++) { /*BEGIN main ufunc computation*/ tmp = *(double *)in1; tmp *= *(double *)in2; *((double *)out1) = tmp; *((double *)out2) = log(tmp/(1-tmp)); /*END main ufunc computation*/ in1 += in1_step; in2 += in2_step; out1 += out1_step; out2 += out2_step; } } /*This a pointer to the above function*/ PyUFuncGenericFunction funcs[1] = {&double_logitprod}; /* These are the input and return dtypes of logit.*/ static char types[4] = {NPY_DOUBLE, NPY_DOUBLE, NPY_DOUBLE, NPY_DOUBLE}; static void *data[1] = {NULL}; #if PY_VERSION_HEX >= 0x03000000 static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, "npufunc", NULL, -1, LogitMethods, NULL, NULL, NULL, NULL }; PyMODINIT_FUNC PyInit_npufunc(void) { PyObject *m, *logit, *d; m = PyModule_Create(&moduledef); if (!m) { return NULL; } import_array(); import_umath(); logit = PyUFunc_FromFuncAndData(funcs, data, types, 1, 2, 2, PyUFunc_None, "logit", "logit_docstring", 0); d = PyModule_GetDict(m); PyDict_SetItemString(d, "logit", logit); Py_DECREF(logit); return m; } #else PyMODINIT_FUNC initnpufunc(void) { PyObject *m, *logit, *d; m = Py_InitModule("npufunc", LogitMethods); if (m == NULL) { return; } import_array(); import_umath(); logit = PyUFunc_FromFuncAndData(funcs, data, types, 1, 2, 2, PyUFunc_None, "logit", "logit_docstring", 0); d = PyModule_GetDict(m); PyDict_SetItemString(d, "logit", logit); Py_DECREF(logit); } #endif .. _`sec:Numpy-struct-dtype`: Example Numpy ufunc with structured array dtype arguments ========================================================= This example shows how to create a ufunc for a structured array dtype. For the example we show a trivial ufunc for adding two arrays with dtype 'u8,u8,u8'. The process is a bit different from the other examples since a call to PyUFunc_FromFuncAndData doesn't fully register ufuncs for custom dtypes and structured array dtypes. We need to also call PyUFunc_RegisterLoopForDescr to finish setting up the ufunc. We only give the C code as the setup.py file is exactly the same as the setup.py file in `Example Numpy ufunc for one dtype`_, except that the line .. code-block:: python config.add_extension('npufunc', ['single_type_logit.c']) is replaced with .. code-block:: python config.add_extension('npufunc', ['add_triplet.c']) The C file is given below. .. code-block:: c #include "Python.h" #include "math.h" #include "numpy/ndarraytypes.h" #include "numpy/ufuncobject.h" #include "numpy/npy_3kcompat.h" /* * add_triplet.c * This is the C code for creating your own * Numpy ufunc for a structured array dtype. * * Details explaining the Python-C API can be found under * 'Extending and Embedding' and 'Python/C API' at * docs.python.org . */ static PyMethodDef StructUfuncTestMethods[] = { {NULL, NULL, 0, NULL} }; /* The loop definition must precede the PyMODINIT_FUNC. */ static void add_uint64_triplet(char **args, npy_intp *dimensions, npy_intp* steps, void* data) { npy_intp i; npy_intp is1=steps[0]; npy_intp is2=steps[1]; npy_intp os=steps[2]; npy_intp n=dimensions[0]; uint64_t *x, *y, *z; char *i1=args[0]; char *i2=args[1]; char *op=args[2]; for (i = 0; i < n; i++) { x = (uint64_t*)i1; y = (uint64_t*)i2; z = (uint64_t*)op; z[0] = x[0] + y[0]; z[1] = x[1] + y[1]; z[2] = x[2] + y[2]; i1 += is1; i2 += is2; op += os; } } /* This a pointer to the above function */ PyUFuncGenericFunction funcs[1] = {&add_uint64_triplet}; /* These are the input and return dtypes of add_uint64_triplet. */ static char types[3] = {NPY_UINT64, NPY_UINT64, NPY_UINT64}; static void *data[1] = {NULL}; #if defined(NPY_PY3K) static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, "struct_ufunc_test", NULL, -1, StructUfuncTestMethods, NULL, NULL, NULL, NULL }; #endif #if defined(NPY_PY3K) PyMODINIT_FUNC PyInit_struct_ufunc_test(void) #else PyMODINIT_FUNC initstruct_ufunc_test(void) #endif { PyObject *m, *add_triplet, *d; PyObject *dtype_dict; PyArray_Descr *dtype; PyArray_Descr *dtypes[3]; #if defined(NPY_PY3K) m = PyModule_Create(&moduledef); #else m = Py_InitModule("struct_ufunc_test", StructUfuncTestMethods); #endif if (m == NULL) { #if defined(NPY_PY3K) return NULL; #else return; #endif } import_array(); import_umath(); /* Create a new ufunc object */ add_triplet = PyUFunc_FromFuncAndData(NULL, NULL, NULL, 0, 2, 1, PyUFunc_None, "add_triplet", "add_triplet_docstring", 0); dtype_dict = Py_BuildValue("[(s, s), (s, s), (s, s)]", "f0", "u8", "f1", "u8", "f2", "u8"); PyArray_DescrConverter(dtype_dict, &dtype); Py_DECREF(dtype_dict); dtypes[0] = dtype; dtypes[1] = dtype; dtypes[2] = dtype; /* Register ufunc for structured dtype */ PyUFunc_RegisterLoopForDescr(add_triplet, dtype, &add_uint64_triplet, dtypes, NULL); d = PyModule_GetDict(m); PyDict_SetItemString(d, "add_triplet", add_triplet); Py_DECREF(add_triplet); #if defined(NPY_PY3K) return m; #endif } .. _`sec:PyUFunc-spec`: PyUFunc_FromFuncAndData Specification ===================================== What follows is the full specification of PyUFunc_FromFuncAndData, which automatically generates a ufunc from a C function with the correct signature. .. cfunction:: PyObject *PyUFunc_FromFuncAndData( PyUFuncGenericFunction* func, void** data, char* types, int ntypes, int nin, int nout, int identity, char* name, char* doc, int check_return) *func* A pointer to an array of 1-d functions to use. This array must be at least ntypes long. Each entry in the array must be a ``PyUFuncGenericFunction`` function. This function has the following signature. An example of a valid 1d loop function is also given. .. cfunction:: void loop1d(char** args, npy_intp* dimensions, npy_intp* steps, void* data) *args* An array of pointers to the actual data for the input and output arrays. The input arguments are given first followed by the output arguments. *dimensions* A pointer to the size of the dimension over which this function is looping. *steps* A pointer to the number of bytes to jump to get to the next element in this dimension for each of the input and output arguments. *data* Arbitrary data (extra arguments, function names, *etc.* ) that can be stored with the ufunc and will be passed in when it is called. .. code-block:: c static void double_add(char *args, npy_intp *dimensions, npy_intp *steps, void *extra) { npy_intp i; npy_intp is1 = steps[0], is2 = steps[1]; npy_intp os = steps[2], n = dimensions[0]; char *i1 = args[0], *i2 = args[1], *op = args[2]; for (i = 0; i < n; i++) { *((double *)op) = *((double *)i1) + *((double *)i2); i1 += is1; i2 += is2; op += os; } } *data* An array of data. There should be ntypes entries (or NULL) --- one for every loop function defined for this ufunc. This data will be passed in to the 1-d loop. One common use of this data variable is to pass in an actual function to call to compute the result when a generic 1-d loop (e.g. :cfunc:`PyUFunc_d_d`) is being used. *types* An array of type-number signatures (type ``char`` ). This array should be of size (nin+nout)*ntypes and contain the data-types for the corresponding 1-d loop. The inputs should be first followed by the outputs. For example, suppose I have a ufunc that supports 1 integer and 1 double 1-d loop (length-2 func and data arrays) that takes 2 inputs and returns 1 output that is always a complex double, then the types array would be .. code-block:: c static char types[3] = {NPY_INT, NPY_DOUBLE, NPY_CDOUBLE} The bit-width names can also be used (e.g. :cdata:`NPY_INT32`, :cdata:`NPY_COMPLEX128` ) if desired. *ntypes* The number of data-types supported. This is equal to the number of 1-d loops provided. *nin* The number of input arguments. *nout* The number of output arguments. *identity* Either :cdata:`PyUFunc_One`, :cdata:`PyUFunc_Zero`, :cdata:`PyUFunc_None`. This specifies what should be returned when an empty array is passed to the reduce method of the ufunc. *name* A ``NULL`` -terminated string providing the name of this ufunc (should be the Python name it will be called). *doc* A documentation string for this ufunc (will be used in generating the response to ``{ufunc_name}.__doc__``). Do not include the function signature or the name as this is generated automatically. *check_return* Not presently used, but this integer value does get set in the structure-member of similar name. .. index:: pair: ufunc; adding new The returned ufunc object is a callable Python object. It should be placed in a (module) dictionary under the same name as was used in the name argument to the ufunc-creation routine. The following example is adapted from the umath module .. code-block:: c static PyUFuncGenericFunction atan2_functions[] = { PyUFunc_ff_f, PyUFunc_dd_d, PyUFunc_gg_g, PyUFunc_OO_O_method}; static void* atan2_data[] = { (void *)atan2f,(void *) atan2, (void *)atan2l,(void *)"arctan2"}; static char atan2_signatures[] = { NPY_FLOAT, NPY_FLOAT, NPY_FLOAT, NPY_DOUBLE, NPY_DOUBLE, NPY_DOUBLE, NPY_LONGDOUBLE, NPY_LONGDOUBLE, NPY_LONGDOUBLE NPY_OBJECT, NPY_OBJECT, NPY_OBJECT}; ... /* in the module initialization code */ PyObject *f, *dict, *module; ... dict = PyModule_GetDict(module); ... f = PyUFunc_FromFuncAndData(atan2_functions, atan2_data, atan2_signatures, 4, 2, 1, PyUFunc_None, "arctan2", "a safe and correct arctan(x1/x2)", 0); PyDict_SetItemString(dict, "arctan2", f); Py_DECREF(f); ... numpy-1.8.2/doc/source/user/basics.rec.rst0000664000175100017510000000027512370216242021620 0ustar vagrantvagrant00000000000000.. _structured_arrays: *************************************** Structured arrays (aka "Record arrays") *************************************** .. automodule:: numpy.doc.structured_arrays numpy-1.8.2/doc/source/user/basics.rst0000664000175100017510000000033312370216242021043 0ustar vagrantvagrant00000000000000************ Numpy basics ************ .. toctree:: :maxdepth: 2 basics.types basics.creation basics.io basics.indexing basics.broadcasting basics.byteswapping basics.rec basics.subclassing numpy-1.8.2/doc/source/user/install.rst0000664000175100017510000001404412370216243021252 0ustar vagrantvagrant00000000000000***************************** Building and installing NumPy ***************************** Binary installers ================= In most use cases the best way to install NumPy on your system is by using an installable binary package for your operating system. Windows ------- Good solutions for Windows are, The Enthought Python Distribution `(EPD) `_ (which provides binary installers for Windows, OS X and Redhat) and `Python (x, y) `_. Both of these packages include Python, NumPy and many additional packages. A lightweight alternative is to download the Python installer from `www.python.org `_ and the NumPy installer for your Python version from the Sourceforge `download site `_ The NumPy installer includes binaries for different CPU's (without SSE instructions, with SSE2 or with SSE3) and installs the correct one automatically. If needed, this can be bypassed from the command line with :: numpy-<1.y.z>-superpack-win32.exe /arch nosse or 'sse2' or 'sse3' instead of 'nosse'. Linux ----- Most of the major distributions provide packages for NumPy, but these can lag behind the most recent NumPy release. Pre-built binary packages for Ubuntu are available on the `scipy ppa `_. Redhat binaries are available in the `EPD `_. Mac OS X -------- A universal binary installer for NumPy is available from the `download site `_. The `EPD `_ provides NumPy binaries. Building from source ==================== A general overview of building NumPy from source is given here, with detailed instructions for specific platforms given seperately. Prerequisites ------------- Building NumPy requires the following software installed: 1) Python 2.4.x, 2.5.x or 2.6.x On Debian and derivative (Ubuntu): python, python-dev On Windows: the official python installer at `www.python.org `_ is enough Make sure that the Python package distutils is installed before continuing. For example, in Debian GNU/Linux, distutils is included in the python-dev package. Python must also be compiled with the zlib module enabled. 2) Compilers To build any extension modules for Python, you'll need a C compiler. Various NumPy modules use FORTRAN 77 libraries, so you'll also need a FORTRAN 77 compiler installed. Note that NumPy is developed mainly using GNU compilers. Compilers from other vendors such as Intel, Absoft, Sun, NAG, Compaq, Vast, Porland, Lahey, HP, IBM, Microsoft are only supported in the form of community feedback, and may not work out of the box. GCC 3.x (and later) compilers are recommended. 3) Linear Algebra libraries NumPy does not require any external linear algebra libraries to be installed. However, if these are available, NumPy's setup script can detect them and use them for building. A number of different LAPACK library setups can be used, including optimized LAPACK libraries such as ATLAS, MKL or the Accelerate/vecLib framework on OS X. FORTRAN ABI mismatch -------------------- The two most popular open source fortran compilers are g77 and gfortran. Unfortunately, they are not ABI compatible, which means that concretely you should avoid mixing libraries built with one with another. In particular, if your blas/lapack/atlas is built with g77, you *must* use g77 when building numpy and scipy; on the contrary, if your atlas is built with gfortran, you *must* build numpy/scipy with gfortran. This applies for most other cases where different FORTRAN compilers might have been used. Choosing the fortran compiler ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ To build with g77:: python setup.py build --fcompiler=gnu To build with gfortran:: python setup.py build --fcompiler=gnu95 For more information see:: python setup.py build --help-fcompiler How to check the ABI of blas/lapack/atlas ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ One relatively simple and reliable way to check for the compiler used to build a library is to use ldd on the library. If libg2c.so is a dependency, this means that g77 has been used. If libgfortran.so is a a dependency, gfortran has been used. If both are dependencies, this means both have been used, which is almost always a very bad idea. Disabling ATLAS and other accelerated libraries ----------------------------------------------- Usage of ATLAS and other accelerated libraries in Numpy can be disabled via:: BLAS=None LAPACK=None ATLAS=None python setup.py build Supplying additional compiler flags ----------------------------------- Additional compiler flags can be supplied by setting the ``OPT``, ``FOPT`` (for Fortran), and ``CC`` environment variables. Building with ATLAS support --------------------------- Ubuntu 8.10 (Intrepid) and 9.04 (Jaunty) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ You can install the necessary packages for optimized ATLAS with this command:: sudo apt-get install libatlas-base-dev If you have a recent CPU with SIMD suppport (SSE, SSE2, etc...), you should also install the corresponding package for optimal performances. For example, for SSE2:: sudo apt-get install libatlas3gf-sse2 This package is not available on amd64 platforms. *NOTE*: Ubuntu changed its default fortran compiler from g77 in Hardy to gfortran in Intrepid. If you are building ATLAS from source and are upgrading from Hardy to Intrepid or later versions, you should rebuild everything from scratch, including lapack. Ubuntu 8.04 and lower ~~~~~~~~~~~~~~~~~~~~~ You can install the necessary packages for optimized ATLAS with this command:: sudo apt-get install atlas3-base-dev If you have a recent CPU with SIMD suppport (SSE, SSE2, etc...), you should also install the corresponding package for optimal performances. For example, for SSE2:: sudo apt-get install atlas3-sse2 numpy-1.8.2/doc/source/user/performance.rst0000664000175100017510000000011312370216242022074 0ustar vagrantvagrant00000000000000*********** Performance *********** .. automodule:: numpy.doc.performance numpy-1.8.2/doc/source/user/whatisnumpy.rst0000664000175100017510000001256612370216243022203 0ustar vagrantvagrant00000000000000************** What is NumPy? ************** NumPy is the fundamental package for scientific computing in Python. It is a Python library that provides a multidimensional array object, various derived objects (such as masked arrays and matrices), and an assortment of routines for fast operations on arrays, including mathematical, logical, shape manipulation, sorting, selecting, I/O, discrete Fourier transforms, basic linear algebra, basic statistical operations, random simulation and much more. At the core of the NumPy package, is the `ndarray` object. This encapsulates *n*-dimensional arrays of homogeneous data types, with many operations being performed in compiled code for performance. There are several important differences between NumPy arrays and the standard Python sequences: - NumPy arrays have a fixed size at creation, unlike Python lists (which can grow dynamically). Changing the size of an `ndarray` will create a new array and delete the original. - The elements in a NumPy array are all required to be of the same data type, and thus will be the same size in memory. The exception: one can have arrays of (Python, including NumPy) objects, thereby allowing for arrays of different sized elements. - NumPy arrays facilitate advanced mathematical and other types of operations on large numbers of data. Typically, such operations are executed more efficiently and with less code than is possible using Python's built-in sequences. - A growing plethora of scientific and mathematical Python-based packages are using NumPy arrays; though these typically support Python-sequence input, they convert such input to NumPy arrays prior to processing, and they often output NumPy arrays. In other words, in order to efficiently use much (perhaps even most) of today's scientific/mathematical Python-based software, just knowing how to use Python's built-in sequence types is insufficient - one also needs to know how to use NumPy arrays. The points about sequence size and speed are particularly important in scientific computing. As a simple example, consider the case of multiplying each element in a 1-D sequence with the corresponding element in another sequence of the same length. If the data are stored in two Python lists, ``a`` and ``b``, we could iterate over each element:: c = [] for i in range(len(a)): c.append(a[i]*b[i]) This produces the correct answer, but if ``a`` and ``b`` each contain millions of numbers, we will pay the price for the inefficiencies of looping in Python. We could accomplish the same task much more quickly in C by writing (for clarity we neglect variable declarations and initializations, memory allocation, etc.) :: for (i = 0; i < rows; i++): { c[i] = a[i]*b[i]; } This saves all the overhead involved in interpreting the Python code and manipulating Python objects, but at the expense of the benefits gained from coding in Python. Furthermore, the coding work required increases with the dimensionality of our data. In the case of a 2-D array, for example, the C code (abridged as before) expands to :: for (i = 0; i < rows; i++): { for (j = 0; j < columns; j++): { c[i][j] = a[i][j]*b[i][j]; } } NumPy gives us the best of both worlds: element-by-element operations are the "default mode" when an `ndarray` is involved, but the element-by-element operation is speedily executed by pre-compiled C code. In NumPy :: c = a * b does what the earlier examples do, at near-C speeds, but with the code simplicity we expect from something based on Python (indeed, the NumPy idiom is even simpler!). This last example illustrates two of NumPy's features which are the basis of much of its power: vectorization and broadcasting. Vectorization describes the absence of any explicit looping, indexing, etc., in the code - these things are taking place, of course, just "behind the scenes" (in optimized, pre-compiled C code). Vectorized code has many advantages, among which are: - vectorized code is more concise and easier to read - fewer lines of code generally means fewer bugs - the code more closely resembles standard mathematical notation (making it easier, typically, to correctly code mathematical constructs) - vectorization results in more "Pythonic" code (without vectorization, our code would still be littered with inefficient and difficult to read ``for`` loops. Broadcasting is the term used to describe the implicit element-by-element behavior of operations; generally speaking, in NumPy all operations (i.e., not just arithmetic operations, but logical, bit-wise, functional, etc.) behave in this implicit element-by-element fashion, i.e., they broadcast. Moreover, in the example above, ``a`` and ``b`` could be multidimensional arrays of the same shape, or a scalar and an array, or even two arrays of with different shapes. Provided that the smaller array is "expandable" to the shape of the larger in such a way that the resulting broadcast is unambiguous (for detailed "rules" of broadcasting see `numpy.doc.broadcasting`). NumPy fully supports an object-oriented approach, starting, once again, with `ndarray`. For example, `ndarray` is a class, possessing numerous methods and attributes. Many, of it's methods mirror functions in the outer-most NumPy namespace, giving the programmer has complete freedom to code in whichever paradigm she prefers and/or which seems most appropriate to the task at hand. numpy-1.8.2/doc/source/user/index.rst0000664000175100017510000000170512370216242020712 0ustar vagrantvagrant00000000000000.. _user: ################ NumPy User Guide ################ This guide is intended as an introductory overview of NumPy and explains how to install and make use of the most important features of NumPy. For detailed reference documentation of the functions and classes contained in the package, see the :ref:`reference`. .. warning:: This "User Guide" is still a work in progress; some of the material is not organized, and several aspects of NumPy are not yet covered sufficient detail. We are an open source community continually working to improve the documentation and eagerly encourage interested parties to contribute. For information on how to do so, please visit the NumPy `doc wiki `_. More documentation for NumPy can be found on the `numpy.org `__ website. Thanks! .. toctree:: :maxdepth: 2 introduction basics performance misc c-info numpy-1.8.2/doc/source/user/c-info.how-to-extend.rst0000664000175100017510000007240612370216243023466 0ustar vagrantvagrant00000000000000******************* How to extend NumPy ******************* | That which is static and repetitive is boring. That which is dynamic | and random is confusing. In between lies art. | --- *John A. Locke* | Science is a differential equation. Religion is a boundary condition. | --- *Alan Turing* .. _`sec:Writing-an-extension`: Writing an extension module =========================== While the ndarray object is designed to allow rapid computation in Python, it is also designed to be general-purpose and satisfy a wide- variety of computational needs. As a result, if absolute speed is essential, there is no replacement for a well-crafted, compiled loop specific to your application and hardware. This is one of the reasons that numpy includes f2py so that an easy-to-use mechanisms for linking (simple) C/C++ and (arbitrary) Fortran code directly into Python are available. You are encouraged to use and improve this mechanism. The purpose of this section is not to document this tool but to document the more basic steps to writing an extension module that this tool depends on. .. index:: single: extension module When an extension module is written, compiled, and installed to somewhere in the Python path (sys.path), the code can then be imported into Python as if it were a standard python file. It will contain objects and methods that have been defined and compiled in C code. The basic steps for doing this in Python are well-documented and you can find more information in the documentation for Python itself available online at `www.python.org `_ . In addition to the Python C-API, there is a full and rich C-API for NumPy allowing sophisticated manipulations on a C-level. However, for most applications, only a few API calls will typically be used. If all you need to do is extract a pointer to memory along with some shape information to pass to another calculation routine, then you will use very different calls, then if you are trying to create a new array- like type or add a new data type for ndarrays. This chapter documents the API calls and macros that are most commonly used. Required subroutine =================== There is exactly one function that must be defined in your C-code in order for Python to use it as an extension module. The function must be called init{name} where {name} is the name of the module from Python. This function must be declared so that it is visible to code outside of the routine. Besides adding the methods and constants you desire, this subroutine must also contain calls to import_array() and/or import_ufunc() depending on which C-API is needed. Forgetting to place these commands will show itself as an ugly segmentation fault (crash) as soon as any C-API subroutine is actually called. It is actually possible to have multiple init{name} functions in a single file in which case multiple modules will be defined by that file. However, there are some tricks to get that to work correctly and it is not covered here. A minimal ``init{name}`` method looks like: .. code-block:: c PyMODINIT_FUNC init{name}(void) { (void)Py_InitModule({name}, mymethods); import_array(); } The mymethods must be an array (usually statically declared) of PyMethodDef structures which contain method names, actual C-functions, a variable indicating whether the method uses keyword arguments or not, and docstrings. These are explained in the next section. If you want to add constants to the module, then you store the returned value from Py_InitModule which is a module object. The most general way to add itmes to the module is to get the module dictionary using PyModule_GetDict(module). With the module dictionary, you can add whatever you like to the module manually. An easier way to add objects to the module is to use one of three additional Python C-API calls that do not require a separate extraction of the module dictionary. These are documented in the Python documentation, but repeated here for convenience: .. cfunction:: int PyModule_AddObject(PyObject* module, char* name, PyObject* value) .. cfunction:: int PyModule_AddIntConstant(PyObject* module, char* name, long value) .. cfunction:: int PyModule_AddStringConstant(PyObject* module, char* name, char* value) All three of these functions require the *module* object (the return value of Py_InitModule). The *name* is a string that labels the value in the module. Depending on which function is called, the *value* argument is either a general object (:cfunc:`PyModule_AddObject` steals a reference to it), an integer constant, or a string constant. Defining functions ================== The second argument passed in to the Py_InitModule function is a structure that makes it easy to to define functions in the module. In the example given above, the mymethods structure would have been defined earlier in the file (usually right before the init{name} subroutine) to: .. code-block:: c static PyMethodDef mymethods[] = { { nokeywordfunc,nokeyword_cfunc, METH_VARARGS, Doc string}, { keywordfunc, keyword_cfunc, METH_VARARGS|METH_KEYWORDS, Doc string}, {NULL, NULL, 0, NULL} /* Sentinel */ } Each entry in the mymethods array is a :ctype:`PyMethodDef` structure containing 1) the Python name, 2) the C-function that implements the function, 3) flags indicating whether or not keywords are accepted for this function, and 4) The docstring for the function. Any number of functions may be defined for a single module by adding more entries to this table. The last entry must be all NULL as shown to act as a sentinel. Python looks for this entry to know that all of the functions for the module have been defined. The last thing that must be done to finish the extension module is to actually write the code that performs the desired functions. There are two kinds of functions: those that don't accept keyword arguments, and those that do. Functions without keyword arguments ----------------------------------- Functions that don't accept keyword arguments should be written as: .. code-block:: c static PyObject* nokeyword_cfunc (PyObject *dummy, PyObject *args) { /* convert Python arguments */ /* do function */ /* return something */ } The dummy argument is not used in this context and can be safely ignored. The *args* argument contains all of the arguments passed in to the function as a tuple. You can do anything you want at this point, but usually the easiest way to manage the input arguments is to call :cfunc:`PyArg_ParseTuple` (args, format_string, addresses_to_C_variables...) or :cfunc:`PyArg_UnpackTuple` (tuple, "name" , min, max, ...). A good description of how to use the first function is contained in the Python C-API reference manual under section 5.5 (Parsing arguments and building values). You should pay particular attention to the "O&" format which uses converter functions to go between the Python object and the C object. All of the other format functions can be (mostly) thought of as special cases of this general rule. There are several converter functions defined in the NumPy C-API that may be of use. In particular, the :cfunc:`PyArray_DescrConverter` function is very useful to support arbitrary data-type specification. This function transforms any valid data-type Python object into a :ctype:`PyArray_Descr *` object. Remember to pass in the address of the C-variables that should be filled in. There are lots of examples of how to use :cfunc:`PyArg_ParseTuple` throughout the NumPy source code. The standard usage is like this: .. code-block:: c PyObject *input; PyArray_Descr *dtype; if (!PyArg_ParseTuple(args, "OO&", &input, PyArray_DescrConverter, &dtype)) return NULL; It is important to keep in mind that you get a *borrowed* reference to the object when using the "O" format string. However, the converter functions usually require some form of memory handling. In this example, if the conversion is successful, *dtype* will hold a new reference to a :ctype:`PyArray_Descr *` object, while *input* will hold a borrowed reference. Therefore, if this conversion were mixed with another conversion (say to an integer) and the data-type conversion was successful but the integer conversion failed, then you would need to release the reference count to the data-type object before returning. A typical way to do this is to set *dtype* to ``NULL`` before calling :cfunc:`PyArg_ParseTuple` and then use :cfunc:`Py_XDECREF` on *dtype* before returning. After the input arguments are processed, the code that actually does the work is written (likely calling other functions as needed). The final step of the C-function is to return something. If an error is encountered then ``NULL`` should be returned (making sure an error has actually been set). If nothing should be returned then increment :cdata:`Py_None` and return it. If a single object should be returned then it is returned (ensuring that you own a reference to it first). If multiple objects should be returned then you need to return a tuple. The :cfunc:`Py_BuildValue` (format_string, c_variables...) function makes it easy to build tuples of Python objects from C variables. Pay special attention to the difference between 'N' and 'O' in the format string or you can easily create memory leaks. The 'O' format string increments the reference count of the :ctype:`PyObject *` C-variable it corresponds to, while the 'N' format string steals a reference to the corresponding :ctype:`PyObject *` C-variable. You should use 'N' if you ave already created a reference for the object and just want to give that reference to the tuple. You should use 'O' if you only have a borrowed reference to an object and need to create one to provide for the tuple. Functions with keyword arguments -------------------------------- These functions are very similar to functions without keyword arguments. The only difference is that the function signature is: .. code-block:: c static PyObject* keyword_cfunc (PyObject *dummy, PyObject *args, PyObject *kwds) { ... } The kwds argument holds a Python dictionary whose keys are the names of the keyword arguments and whose values are the corresponding keyword-argument values. This dictionary can be processed however you see fit. The easiest way to handle it, however, is to replace the :cfunc:`PyArg_ParseTuple` (args, format_string, addresses...) function with a call to :cfunc:`PyArg_ParseTupleAndKeywords` (args, kwds, format_string, char \*kwlist[], addresses...). The kwlist parameter to this function is a ``NULL`` -terminated array of strings providing the expected keyword arguments. There should be one string for each entry in the format_string. Using this function will raise a TypeError if invalid keyword arguments are passed in. For more help on this function please see section 1.8 (Keyword Paramters for Extension Functions) of the Extending and Embedding tutorial in the Python documentation. Reference counting ------------------ The biggest difficulty when writing extension modules is reference counting. It is an important reason for the popularity of f2py, weave, pyrex, ctypes, etc.... If you mis-handle reference counts you can get problems from memory-leaks to segmentation faults. The only strategy I know of to handle reference counts correctly is blood, sweat, and tears. First, you force it into your head that every Python variable has a reference count. Then, you understand exactly what each function does to the reference count of your objects, so that you can properly use DECREF and INCREF when you need them. Reference counting can really test the amount of patience and diligence you have towards your programming craft. Despite the grim depiction, most cases of reference counting are quite straightforward with the most common difficulty being not using DECREF on objects before exiting early from a routine due to some error. In second place, is the common error of not owning the reference on an object that is passed to a function or macro that is going to steal the reference ( *e.g.* :cfunc:`PyTuple_SET_ITEM`, and most functions that take :ctype:`PyArray_Descr` objects). .. index:: single: reference counting Typically you get a new reference to a variable when it is created or is the return value of some function (there are some prominent exceptions, however --- such as getting an item out of a tuple or a dictionary). When you own the reference, you are responsible to make sure that :cfunc:`Py_DECREF` (var) is called when the variable is no longer necessary (and no other function has "stolen" its reference). Also, if you are passing a Python object to a function that will "steal" the reference, then you need to make sure you own it (or use :cfunc:`Py_INCREF` to get your own reference). You will also encounter the notion of borrowing a reference. A function that borrows a reference does not alter the reference count of the object and does not expect to "hold on "to the reference. It's just going to use the object temporarily. When you use :cfunc:`PyArg_ParseTuple` or :cfunc:`PyArg_UnpackTuple` you receive a borrowed reference to the objects in the tuple and should not alter their reference count inside your function. With practice, you can learn to get reference counting right, but it can be frustrating at first. One common source of reference-count errors is the :cfunc:`Py_BuildValue` function. Pay careful attention to the difference between the 'N' format character and the 'O' format character. If you create a new object in your subroutine (such as an output array), and you are passing it back in a tuple of return values, then you should most- likely use the 'N' format character in :cfunc:`Py_BuildValue`. The 'O' character will increase the reference count by one. This will leave the caller with two reference counts for a brand-new array. When the variable is deleted and the reference count decremented by one, there will still be that extra reference count, and the array will never be deallocated. You will have a reference-counting induced memory leak. Using the 'N' character will avoid this situation as it will return to the caller an object (inside the tuple) with a single reference count. .. index:: single: reference counting Dealing with array objects ========================== Most extension modules for NumPy will need to access the memory for an ndarray object (or one of it's sub-classes). The easiest way to do this doesn't require you to know much about the internals of NumPy. The method is to 1. Ensure you are dealing with a well-behaved array (aligned, in machine byte-order and single-segment) of the correct type and number of dimensions. 1. By converting it from some Python object using :cfunc:`PyArray_FromAny` or a macro built on it. 2. By constructing a new ndarray of your desired shape and type using :cfunc:`PyArray_NewFromDescr` or a simpler macro or function based on it. 2. Get the shape of the array and a pointer to its actual data. 3. Pass the data and shape information on to a subroutine or other section of code that actually performs the computation. 4. If you are writing the algorithm, then I recommend that you use the stride information contained in the array to access the elements of the array (the :cfunc:`PyArray_GETPTR` macros make this painless). Then, you can relax your requirements so as not to force a single-segment array and the data-copying that might result. Each of these sub-topics is covered in the following sub-sections. Converting an arbitrary sequence object --------------------------------------- The main routine for obtaining an array from any Python object that can be converted to an array is :cfunc:`PyArray_FromAny`. This function is very flexible with many input arguments. Several macros make it easier to use the basic function. :cfunc:`PyArray_FROM_OTF` is arguably the most useful of these macros for the most common uses. It allows you to convert an arbitrary Python object to an array of a specific builtin data-type ( *e.g.* float), while specifying a particular set of requirements ( *e.g.* contiguous, aligned, and writeable). The syntax is .. cfunction:: PyObject *PyArray_FROM_OTF(PyObject* obj, int typenum, int requirements) Return an ndarray from any Python object, *obj*, that can be converted to an array. The number of dimensions in the returned array is determined by the object. The desired data-type of the returned array is provided in *typenum* which should be one of the enumerated types. The *requirements* for the returned array can be any combination of standard array flags. Each of these arguments is explained in more detail below. You receive a new reference to the array on success. On failure, ``NULL`` is returned and an exception is set. *obj* The object can be any Python object convertable to an ndarray. If the object is already (a subclass of) the ndarray that satisfies the requirements then a new reference is returned. Otherwise, a new array is constructed. The contents of *obj* are copied to the new array unless the array interface is used so that data does not have to be copied. Objects that can be converted to an array include: 1) any nested sequence object, 2) any object exposing the array interface, 3) any object with an :obj:`__array__` method (which should return an ndarray), and 4) any scalar object (becomes a zero-dimensional array). Sub-classes of the ndarray that otherwise fit the requirements will be passed through. If you want to ensure a base-class ndarray, then use :cdata:`NPY_ENSUREARRAY` in the requirements flag. A copy is made only if necessary. If you want to guarantee a copy, then pass in :cdata:`NPY_ENSURECOPY` to the requirements flag. *typenum* One of the enumerated types or :cdata:`NPY_NOTYPE` if the data-type should be determined from the object itself. The C-based names can be used: :cdata:`NPY_BOOL`, :cdata:`NPY_BYTE`, :cdata:`NPY_UBYTE`, :cdata:`NPY_SHORT`, :cdata:`NPY_USHORT`, :cdata:`NPY_INT`, :cdata:`NPY_UINT`, :cdata:`NPY_LONG`, :cdata:`NPY_ULONG`, :cdata:`NPY_LONGLONG`, :cdata:`NPY_ULONGLONG`, :cdata:`NPY_DOUBLE`, :cdata:`NPY_LONGDOUBLE`, :cdata:`NPY_CFLOAT`, :cdata:`NPY_CDOUBLE`, :cdata:`NPY_CLONGDOUBLE`, :cdata:`NPY_OBJECT`. Alternatively, the bit-width names can be used as supported on the platform. For example: :cdata:`NPY_INT8`, :cdata:`NPY_INT16`, :cdata:`NPY_INT32`, :cdata:`NPY_INT64`, :cdata:`NPY_UINT8`, :cdata:`NPY_UINT16`, :cdata:`NPY_UINT32`, :cdata:`NPY_UINT64`, :cdata:`NPY_FLOAT32`, :cdata:`NPY_FLOAT64`, :cdata:`NPY_COMPLEX64`, :cdata:`NPY_COMPLEX128`. The object will be converted to the desired type only if it can be done without losing precision. Otherwise ``NULL`` will be returned and an error raised. Use :cdata:`NPY_FORCECAST` in the requirements flag to override this behavior. *requirements* The memory model for an ndarray admits arbitrary strides in each dimension to advance to the next element of the array. Often, however, you need to interface with code that expects a C-contiguous or a Fortran-contiguous memory layout. In addition, an ndarray can be misaligned (the address of an element is not at an integral multiple of the size of the element) which can cause your program to crash (or at least work more slowly) if you try and dereference a pointer into the array data. Both of these problems can be solved by converting the Python object into an array that is more "well-behaved" for your specific usage. The requirements flag allows specification of what kind of array is acceptable. If the object passed in does not satisfy this requirements then a copy is made so that thre returned object will satisfy the requirements. these ndarray can use a very generic pointer to memory. This flag allows specification of the desired properties of the returned array object. All of the flags are explained in the detailed API chapter. The flags most commonly needed are :cdata:`NPY_ARRAY_IN_ARRAY`, :cdata:`NPY_OUT_ARRAY`, and :cdata:`NPY_ARRAY_INOUT_ARRAY`: .. cvar:: NPY_ARRAY_IN_ARRAY Equivalent to :cdata:`NPY_ARRAY_C_CONTIGUOUS` \| :cdata:`NPY_ARRAY_ALIGNED`. This combination of flags is useful for arrays that must be in C-contiguous order and aligned. These kinds of arrays are usually input arrays for some algorithm. .. cvar:: NPY_ARRAY_OUT_ARRAY Equivalent to :cdata:`NPY_ARRAY_C_CONTIGUOUS` \| :cdata:`NPY_ARRAY_ALIGNED` \| :cdata:`NPY_ARRAY_WRITEABLE`. This combination of flags is useful to specify an array that is in C-contiguous order, is aligned, and can be written to as well. Such an array is usually returned as output (although normally such output arrays are created from scratch). .. cvar:: NPY_ARRAY_INOUT_ARRAY Equivalent to :cdata:`NPY_ARRAY_C_CONTIGUOUS` \| :cdata:`NPY_ARRAY_ALIGNED` \| :cdata:`NPY_ARRAY_WRITEABLE` \| :cdata:`NPY_ARRAY_UPDATEIFCOPY`. This combination of flags is useful to specify an array that will be used for both input and output. If a copy is needed, then when the temporary is deleted (by your use of :cfunc:`Py_DECREF` at the end of the interface routine), the temporary array will be copied back into the original array passed in. Use of the :cdata:`NPY_ARRAY_UPDATEIFCOPY` flag requires that the input object is already an array (because other objects cannot be automatically updated in this fashion). If an error occurs use :cfunc:`PyArray_DECREF_ERR` (obj) on an array with the :cdata:`NPY_ARRAY_UPDATEIFCOPY` flag set. This will delete the array without causing the contents to be copied back into the original array. Other useful flags that can be OR'd as additional requirements are: .. cvar:: NPY_ARRAY_FORCECAST Cast to the desired type, even if it can't be done without losing information. .. cvar:: NPY_ARRAY_ENSURECOPY Make sure the resulting array is a copy of the original. .. cvar:: NPY_ARRAY_ENSUREARRAY Make sure the resulting object is an actual ndarray and not a sub- class. .. note:: Whether or not an array is byte-swapped is determined by the data-type of the array. Native byte-order arrays are always requested by :cfunc:`PyArray_FROM_OTF` and so there is no need for a :cdata:`NPY_ARRAY_NOTSWAPPED` flag in the requirements argument. There is also no way to get a byte-swapped array from this routine. Creating a brand-new ndarray ---------------------------- Quite often new arrays must be created from within extension-module code. Perhaps an output array is needed and you don't want the caller to have to supply it. Perhaps only a temporary array is needed to hold an intermediate calculation. Whatever the need there are simple ways to get an ndarray object of whatever data-type is needed. The most general function for doing this is :cfunc:`PyArray_NewFromDescr`. All array creation functions go through this heavily re-used code. Because of its flexibility, it can be somewhat confusing to use. As a result, simpler forms exist that are easier to use. .. cfunction:: PyObject *PyArray_SimpleNew(int nd, npy_intp* dims, int typenum) This function allocates new memory and places it in an ndarray with *nd* dimensions whose shape is determined by the array of at least *nd* items pointed to by *dims*. The memory for the array is uninitialized (unless typenum is :cdata:`NPY_OBJECT` in which case each element in the array is set to NULL). The *typenum* argument allows specification of any of the builtin data-types such as :cdata:`NPY_FLOAT` or :cdata:`NPY_LONG`. The memory for the array can be set to zero if desired using :cfunc:`PyArray_FILLWBYTE` (return_object, 0). .. cfunction:: PyObject *PyArray_SimpleNewFromData( int nd, npy_intp* dims, int typenum, void* data) Sometimes, you want to wrap memory allocated elsewhere into an ndarray object for downstream use. This routine makes it straightforward to do that. The first three arguments are the same as in :cfunc:`PyArray_SimpleNew`, the final argument is a pointer to a block of contiguous memory that the ndarray should use as it's data-buffer which will be interpreted in C-style contiguous fashion. A new reference to an ndarray is returned, but the ndarray will not own its data. When this ndarray is deallocated, the pointer will not be freed. You should ensure that the provided memory is not freed while the returned array is in existence. The easiest way to handle this is if data comes from another reference-counted Python object. The reference count on this object should be increased after the pointer is passed in, and the base member of the returned ndarray should point to the Python object that owns the data. Then, when the ndarray is deallocated, the base-member will be DECREF'd appropriately. If you want the memory to be freed as soon as the ndarray is deallocated then simply set the OWNDATA flag on the returned ndarray. Getting at ndarray memory and accessing elements of the ndarray --------------------------------------------------------------- If obj is an ndarray (:ctype:`PyArrayObject *`), then the data-area of the ndarray is pointed to by the void* pointer :cfunc:`PyArray_DATA` (obj) or the char* pointer :cfunc:`PyArray_BYTES` (obj). Remember that (in general) this data-area may not be aligned according to the data-type, it may represent byte-swapped data, and/or it may not be writeable. If the data area is aligned and in native byte-order, then how to get at a specific element of the array is determined only by the array of npy_intp variables, :cfunc:`PyArray_STRIDES` (obj). In particular, this c-array of integers shows how many **bytes** must be added to the current element pointer to get to the next element in each dimension. For arrays less than 4-dimensions there are :cfunc:`PyArray_GETPTR{k}` (obj, ...) macros where {k} is the integer 1, 2, 3, or 4 that make using the array strides easier. The arguments .... represent {k} non- negative integer indices into the array. For example, suppose ``E`` is a 3-dimensional ndarray. A (void*) pointer to the element ``E[i,j,k]`` is obtained as :cfunc:`PyArray_GETPTR3` (E, i, j, k). As explained previously, C-style contiguous arrays and Fortran-style contiguous arrays have particular striding patterns. Two array flags (:cdata:`NPY_C_CONTIGUOUS` and :cdata`NPY_F_CONTIGUOUS`) indicate whether or not the striding pattern of a particular array matches the C-style contiguous or Fortran-style contiguous or neither. Whether or not the striding pattern matches a standard C or Fortran one can be tested Using :cfunc:`PyArray_ISCONTIGUOUS` (obj) and :cfunc:`PyArray_ISFORTRAN` (obj) respectively. Most third-party libraries expect contiguous arrays. But, often it is not difficult to support general-purpose striding. I encourage you to use the striding information in your own code whenever possible, and reserve single-segment requirements for wrapping third-party code. Using the striding information provided with the ndarray rather than requiring a contiguous striding reduces copying that otherwise must be made. Example ======= .. index:: single: extension module The following example shows how you might write a wrapper that accepts two input arguments (that will be converted to an array) and an output argument (that must be an array). The function returns None and updates the output array. .. code-block:: c static PyObject * example_wrapper(PyObject *dummy, PyObject *args) { PyObject *arg1=NULL, *arg2=NULL, *out=NULL; PyObject *arr1=NULL, *arr2=NULL, *oarr=NULL; if (!PyArg_ParseTuple(args, "OOO!", &arg1, &arg2, &PyArray_Type, &out)) return NULL; arr1 = PyArray_FROM_OTF(arg1, NPY_DOUBLE, NPY_IN_ARRAY); if (arr1 == NULL) return NULL; arr2 = PyArray_FROM_OTF(arg2, NPY_DOUBLE, NPY_IN_ARRAY); if (arr2 == NULL) goto fail; oarr = PyArray_FROM_OTF(out, NPY_DOUBLE, NPY_INOUT_ARRAY); if (oarr == NULL) goto fail; /* code that makes use of arguments */ /* You will probably need at least nd = PyArray_NDIM(<..>) -- number of dimensions dims = PyArray_DIMS(<..>) -- npy_intp array of length nd showing length in each dim. dptr = (double *)PyArray_DATA(<..>) -- pointer to data. If an error occurs goto fail. */ Py_DECREF(arr1); Py_DECREF(arr2); Py_DECREF(oarr); Py_INCREF(Py_None); return Py_None; fail: Py_XDECREF(arr1); Py_XDECREF(arr2); PyArray_XDECREF_ERR(oarr); return NULL; } numpy-1.8.2/doc/source/user/basics.types.rst0000664000175100017510000000017212370216242022207 0ustar vagrantvagrant00000000000000********** Data types ********** .. seealso:: :ref:`Data type objects ` .. automodule:: numpy.doc.basics numpy-1.8.2/doc/source/user/basics.subclassing.rst0000664000175100017510000000017412370216242023362 0ustar vagrantvagrant00000000000000.. _basics.subclassing: ******************* Subclassing ndarray ******************* .. automodule:: numpy.doc.subclassing numpy-1.8.2/doc/source/user/c-info.python-as-glue.rst0000664000175100017510000016773112370216243023646 0ustar vagrantvagrant00000000000000******************** Using Python as glue ******************** | There is no conversation more boring than the one where everybody | agrees. | --- *Michel de Montaigne* | Duct tape is like the force. It has a light side, and a dark side, and | it holds the universe together. | --- *Carl Zwanzig* Many people like to say that Python is a fantastic glue language. Hopefully, this Chapter will convince you that this is true. The first adopters of Python for science were typically people who used it to glue together large application codes running on super-computers. Not only was it much nicer to code in Python than in a shell script or Perl, in addition, the ability to easily extend Python made it relatively easy to create new classes and types specifically adapted to the problems being solved. From the interactions of these early contributors, Numeric emerged as an array-like object that could be used to pass data between these applications. As Numeric has matured and developed into NumPy, people have been able to write more code directly in NumPy. Often this code is fast-enough for production use, but there are still times that there is a need to access compiled code. Either to get that last bit of efficiency out of the algorithm or to make it easier to access widely-available codes written in C/C++ or Fortran. This chapter will review many of the tools that are available for the purpose of accessing code written in other compiled languages. There are many resources available for learning to call other compiled libraries from Python and the purpose of this Chapter is not to make you an expert. The main goal is to make you aware of some of the possibilities so that you will know what to "Google" in order to learn more. The http://www.scipy.org website also contains a great deal of useful information about many of these tools. For example, there is a nice description of using several of the tools explained in this chapter at http://www.scipy.org/PerformancePython. This link provides several ways to solve the same problem showing how to use and connect with compiled code to get the best performance. In the process you can get a taste for several of the approaches that will be discussed in this chapter. Calling other compiled libraries from Python ============================================ While Python is a great language and a pleasure to code in, its dynamic nature results in overhead that can cause some code ( *i.e.* raw computations inside of for loops) to be up 10-100 times slower than equivalent code written in a static compiled language. In addition, it can cause memory usage to be larger than necessary as temporary arrays are created and destroyed during computation. For many types of computing needs the extra slow-down and memory consumption can often not be spared (at least for time- or memory- critical portions of your code). Therefore one of the most common needs is to call out from Python code to a fast, machine-code routine (e.g. compiled using C/C++ or Fortran). The fact that this is relatively easy to do is a big reason why Python is such an excellent high-level language for scientific and engineering programming. Their are two basic approaches to calling compiled code: writing an extension module that is then imported to Python using the import command, or calling a shared-library subroutine directly from Python using the ctypes module (included in the standard distribution with Python 2.5). The first method is the most common (but with the inclusion of ctypes into Python 2.5 this status may change). .. warning:: Calling C-code from Python can result in Python crashes if you are not careful. None of the approaches in this chapter are immune. You have to know something about the way data is handled by both NumPy and by the third-party library being used. Hand-generated wrappers ======================= Extension modules were discussed in Chapter `1 <#sec-writing-an-extension>`__ . The most basic way to interface with compiled code is to write an extension module and construct a module method that calls the compiled code. For improved readability, your method should take advantage of the PyArg_ParseTuple call to convert between Python objects and C data-types. For standard C data-types there is probably already a built-in converter. For others you may need to write your own converter and use the "O&" format string which allows you to specify a function that will be used to perform the conversion from the Python object to whatever C-structures are needed. Once the conversions to the appropriate C-structures and C data-types have been performed, the next step in the wrapper is to call the underlying function. This is straightforward if the underlying function is in C or C++. However, in order to call Fortran code you must be familiar with how Fortran subroutines are called from C/C++ using your compiler and platform. This can vary somewhat platforms and compilers (which is another reason f2py makes life much simpler for interfacing Fortran code) but generally involves underscore mangling of the name and the fact that all variables are passed by reference (i.e. all arguments are pointers). The advantage of the hand-generated wrapper is that you have complete control over how the C-library gets used and called which can lead to a lean and tight interface with minimal over-head. The disadvantage is that you have to write, debug, and maintain C-code, although most of it can be adapted using the time-honored technique of "cutting-pasting-and-modifying" from other extension modules. Because, the procedure of calling out to additional C-code is fairly regimented, code-generation procedures have been developed to make this process easier. One of these code- generation techniques is distributed with NumPy and allows easy integration with Fortran and (simple) C code. This package, f2py, will be covered briefly in the next session. f2py ==== F2py allows you to automatically construct an extension module that interfaces to routines in Fortran 77/90/95 code. It has the ability to parse Fortran 77/90/95 code and automatically generate Python signatures for the subroutines it encounters, or you can guide how the subroutine interfaces with Python by constructing an interface-definition-file (or modifying the f2py-produced one). .. index:: single: f2py Creating source for a basic extension module -------------------------------------------- Probably the easiest way to introduce f2py is to offer a simple example. Here is one of the subroutines contained in a file named :file:`add.f`: .. code-block:: none C SUBROUTINE ZADD(A,B,C,N) C DOUBLE COMPLEX A(*) DOUBLE COMPLEX B(*) DOUBLE COMPLEX C(*) INTEGER N DO 20 J = 1, N C(J) = A(J)+B(J) 20 CONTINUE END This routine simply adds the elements in two contiguous arrays and places the result in a third. The memory for all three arrays must be provided by the calling routine. A very basic interface to this routine can be automatically generated by f2py:: f2py -m add add.f You should be able to run this command assuming your search-path is set-up properly. This command will produce an extension module named addmodule.c in the current directory. This extension module can now be compiled and used from Python just like any other extension module. Creating a compiled extension module ------------------------------------ You can also get f2py to compile add.f and also compile its produced extension module leaving only a shared-library extension file that can be imported from Python:: f2py -c -m add add.f This command leaves a file named add.{ext} in the current directory (where {ext} is the appropriate extension for a python extension module on your platform --- so, pyd, *etc.* ). This module may then be imported from Python. It will contain a method for each subroutine in add (zadd, cadd, dadd, sadd). The docstring of each method contains information about how the module method may be called: >>> import add >>> print add.zadd.__doc__ zadd - Function signature: zadd(a,b,c,n) Required arguments: a : input rank-1 array('D') with bounds (*) b : input rank-1 array('D') with bounds (*) c : input rank-1 array('D') with bounds (*) n : input int Improving the basic interface ----------------------------- The default interface is a very literal translation of the fortran code into Python. The Fortran array arguments must now be NumPy arrays and the integer argument should be an integer. The interface will attempt to convert all arguments to their required types (and shapes) and issue an error if unsuccessful. However, because it knows nothing about the semantics of the arguments (such that C is an output and n should really match the array sizes), it is possible to abuse this function in ways that can cause Python to crash. For example: >>> add.zadd([1,2,3],[1,2],[3,4],1000) will cause a program crash on most systems. Under the covers, the lists are being converted to proper arrays but then the underlying add loop is told to cycle way beyond the borders of the allocated memory. In order to improve the interface, directives should be provided. This is accomplished by constructing an interface definition file. It is usually best to start from the interface file that f2py can produce (where it gets its default behavior from). To get f2py to generate the interface file use the -h option:: f2py -h add.pyf -m add add.f This command leaves the file add.pyf in the current directory. The section of this file corresponding to zadd is: .. code-block:: none subroutine zadd(a,b,c,n) ! in :add:add.f double complex dimension(*) :: a double complex dimension(*) :: b double complex dimension(*) :: c integer :: n end subroutine zadd By placing intent directives and checking code, the interface can be cleaned up quite a bit until the Python module method is both easier to use and more robust. .. code-block:: none subroutine zadd(a,b,c,n) ! in :add:add.f double complex dimension(n) :: a double complex dimension(n) :: b double complex intent(out),dimension(n) :: c integer intent(hide),depend(a) :: n=len(a) end subroutine zadd The intent directive, intent(out) is used to tell f2py that ``c`` is an output variable and should be created by the interface before being passed to the underlying code. The intent(hide) directive tells f2py to not allow the user to specify the variable, ``n``, but instead to get it from the size of ``a``. The depend( ``a`` ) directive is necessary to tell f2py that the value of n depends on the input a (so that it won't try to create the variable n until the variable a is created). The new interface has docstring: >>> print add.zadd.__doc__ zadd - Function signature: c = zadd(a,b) Required arguments: a : input rank-1 array('D') with bounds (n) b : input rank-1 array('D') with bounds (n) Return objects: c : rank-1 array('D') with bounds (n) Now, the function can be called in a much more robust way: >>> add.zadd([1,2,3],[4,5,6]) array([ 5.+0.j, 7.+0.j, 9.+0.j]) Notice the automatic conversion to the correct format that occurred. Inserting directives in Fortran source -------------------------------------- The nice interface can also be generated automatically by placing the variable directives as special comments in the original fortran code. Thus, if I modify the source code to contain: .. code-block:: none C SUBROUTINE ZADD(A,B,C,N) C CF2PY INTENT(OUT) :: C CF2PY INTENT(HIDE) :: N CF2PY DOUBLE COMPLEX :: A(N) CF2PY DOUBLE COMPLEX :: B(N) CF2PY DOUBLE COMPLEX :: C(N) DOUBLE COMPLEX A(*) DOUBLE COMPLEX B(*) DOUBLE COMPLEX C(*) INTEGER N DO 20 J = 1, N C(J) = A(J) + B(J) 20 CONTINUE END Then, I can compile the extension module using:: f2py -c -m add add.f The resulting signature for the function add.zadd is exactly the same one that was created previously. If the original source code had contained A(N) instead of A(\*) and so forth with B and C, then I could obtain (nearly) the same interface simply by placing the INTENT(OUT) :: C comment line in the source code. The only difference is that N would be an optional input that would default to the length of A. A filtering example ------------------- For comparison with the other methods to be discussed. Here is another example of a function that filters a two-dimensional array of double precision floating-point numbers using a fixed averaging filter. The advantage of using Fortran to index into multi-dimensional arrays should be clear from this example. .. code-block:: none SUBROUTINE DFILTER2D(A,B,M,N) C DOUBLE PRECISION A(M,N) DOUBLE PRECISION B(M,N) INTEGER N, M CF2PY INTENT(OUT) :: B CF2PY INTENT(HIDE) :: N CF2PY INTENT(HIDE) :: M DO 20 I = 2,M-1 DO 40 J=2,N-1 B(I,J) = A(I,J) + $ (A(I-1,J)+A(I+1,J) + $ A(I,J-1)+A(I,J+1) )*0.5D0 + $ (A(I-1,J-1) + A(I-1,J+1) + $ A(I+1,J-1) + A(I+1,J+1))*0.25D0 40 CONTINUE 20 CONTINUE END This code can be compiled and linked into an extension module named filter using:: f2py -c -m filter filter.f This will produce an extension module named filter.so in the current directory with a method named dfilter2d that returns a filtered version of the input. Calling f2py from Python ------------------------ The f2py program is written in Python and can be run from inside your module. This provides a facility that is somewhat similar to the use of weave.ext_tools described below. An example of the final interface executed using Python code is: .. code-block:: python import numpy.f2py as f2py fid = open('add.f') source = fid.read() fid.close() f2py.compile(source, modulename='add') import add The source string can be any valid Fortran code. If you want to save the extension-module source code then a suitable file-name can be provided by the source_fn keyword to the compile function. Automatic extension module generation ------------------------------------- If you want to distribute your f2py extension module, then you only need to include the .pyf file and the Fortran code. The distutils extensions in NumPy allow you to define an extension module entirely in terms of this interface file. A valid setup.py file allowing distribution of the add.f module (as part of the package f2py_examples so that it would be loaded as f2py_examples.add) is: .. code-block:: python def configuration(parent_package='', top_path=None) from numpy.distutils.misc_util import Configuration config = Configuration('f2py_examples',parent_package, top_path) config.add_extension('add', sources=['add.pyf','add.f']) return config if __name__ == '__main__': from numpy.distutils.core import setup setup(**configuration(top_path='').todict()) Installation of the new package is easy using:: python setup.py install assuming you have the proper permissions to write to the main site- packages directory for the version of Python you are using. For the resulting package to work, you need to create a file named __init__.py (in the same directory as add.pyf). Notice the extension module is defined entirely in terms of the "add.pyf" and "add.f" files. The conversion of the .pyf file to a .c file is handled by numpy.disutils. Conclusion ---------- The interface definition file (.pyf) is how you can fine-tune the interface between Python and Fortran. There is decent documentation for f2py found in the numpy/f2py/docs directory where-ever NumPy is installed on your system (usually under site-packages). There is also more information on using f2py (including how to use it to wrap C codes) at http://www.scipy.org/Cookbook under the "Using NumPy with Other Languages" heading. The f2py method of linking compiled code is currently the most sophisticated and integrated approach. It allows clean separation of Python with compiled code while still allowing for separate distribution of the extension module. The only draw-back is that it requires the existence of a Fortran compiler in order for a user to install the code. However, with the existence of the free-compilers g77, gfortran, and g95, as well as high-quality commerical compilers, this restriction is not particularly onerous. In my opinion, Fortran is still the easiest way to write fast and clear code for scientific computing. It handles complex numbers, and multi-dimensional indexing in the most straightforward way. Be aware, however, that some Fortran compilers will not be able to optimize code as well as good hand- written C-code. .. index:: single: f2py weave ===== Weave is a scipy package that can be used to automate the process of extending Python with C/C++ code. It can be used to speed up evaluation of an array expression that would otherwise create temporary variables, to directly "inline" C/C++ code into Python, or to create a fully-named extension module. You must either install scipy or get the weave package separately and install it using the standard python setup.py install. You must also have a C/C++-compiler installed and useable by Python distutils in order to use weave. .. index:: single: weave Somewhat dated, but still useful documentation for weave can be found at the link http://www.scipy/Weave. There are also many examples found in the examples directory which is installed under the weave directory in the place where weave is installed on your system. Speed up code involving arrays (also see scipy.numexpr) ------------------------------------------------------- This is the easiest way to use weave and requires minimal changes to your Python code. It involves placing quotes around the expression of interest and calling weave.blitz. Weave will parse the code and generate C++ code using Blitz C++ arrays. It will then compile the code and catalog the shared library so that the next time this exact string is asked for (and the array types are the same), the already- compiled shared library will be loaded and used. Because Blitz makes extensive use of C++ templating, it can take a long time to compile the first time. After that, however, the code should evaluate more quickly than the equivalent NumPy expression. This is especially true if your array sizes are large and the expression would require NumPy to create several temporaries. Only expressions involving basic arithmetic operations and basic array slicing can be converted to Blitz C++ code. For example, consider the expression:: d = 4*a + 5*a*b + 6*b*c where a, b, and c are all arrays of the same type and shape. When the data-type is double-precision and the size is 1000x1000, this expression takes about 0.5 seconds to compute on an 1.1Ghz AMD Athlon machine. When this expression is executed instead using blitz: .. code-block:: python d = empty(a.shape, 'd'); weave.blitz(expr) execution time is only about 0.20 seconds (about 0.14 seconds spent in weave and the rest in allocating space for d). Thus, we've sped up the code by a factor of 2 using only a simnple command (weave.blitz). Your mileage may vary, but factors of 2-8 speed-ups are possible with this very simple technique. If you are interested in using weave in this way, then you should also look at scipy.numexpr which is another similar way to speed up expressions by eliminating the need for temporary variables. Using numexpr does not require a C/C++ compiler. Inline C-code ------------- Probably the most widely-used method of employing weave is to "in-line" C/C++ code into Python in order to speed up a time-critical section of Python code. In this method of using weave, you define a string containing useful C-code and then pass it to the function **weave.inline** ( ``code_string``, ``variables`` ), where code_string is a string of valid C/C++ code and variables is a list of variables that should be passed in from Python. The C/C++ code should refer to the variables with the same names as they are defined with in Python. If weave.line should return anything the the special value return_val should be set to whatever object should be returned. The following example shows how to use weave on basic Python objects: .. code-block:: python code = r""" int i; py::tuple results(2); for (i=0; ic.data)[i].real = \ (a.data)[i].real + \ (b.data)[i].real (c.data)[i].imag = \ (a.data)[i].imag + \ (b.data)[i].imag return c This module shows use of the ``cimport`` statement to load the definitions from the c_numpy.pxd file. As shown, both versions of the import statement are supported. It also shows use of the NumPy C-API to construct NumPy arrays from arbitrary input objects. The array c is created using PyArray_SimpleNew. Then the c-array is filled by addition. Casting to a particiular data-type is accomplished using . Pointers are de-referenced with bracket notation and members of structures are accessed using '.' notation even if the object is techinically a pointer to a structure. The use of the special for loop construct ensures that the underlying code will have a similar C-loop so the addition calculation will proceed quickly. Notice that we have not checked for NULL after calling to the C-API --- a cardinal sin when writing C-code. For routines that return Python objects, Pyrex inserts the checks for NULL into the C-code for you and returns with failure if need be. There is also a way to get Pyrex to automatically check for exceptions when you call functions that don't return Python objects. See the documentation of Pyrex for details. Pyrex-filter ------------ The two-dimensional example we created using weave is a bit uglier to implement in Pyrex because two-dimensional indexing using Pyrex is not as simple. But, it is straightforward (and possibly faster because of pre-computed indices). Here is the Pyrex-file I named image.pyx. .. code-block:: none cimport c_numpy from c_numpy cimport import_array, ndarray, npy_intp,\ NPY_DOUBLE, NPY_CDOUBLE, \ NPY_FLOAT, NPY_CFLOAT, NPY_ALIGNED \ #We need to initialize NumPy import_array() def filter(object ao): cdef ndarray a, b cdef npy_intp i, j, M, N, oS cdef npy_intp r,rm1,rp1,c,cm1,cp1 cdef double value # Require an ALIGNED array # (but not necessarily contiguous) # We will use strides to access the elements. a = c_numpy.PyArray_FROMANY(ao, NPY_DOUBLE, \ 2, 2, NPY_ALIGNED) b = c_numpy.PyArray_SimpleNew(a.nd,a.dimensions, \ a.descr.type_num) M = a.dimensions[0] N = a.dimensions[1] S0 = a.strides[0] S1 = a.strides[1] for i from 1 <= i < M-1: r = i*S0 rm1 = r-S0 rp1 = r+S0 oS = i*N for j from 1 <= j < N-1: c = j*S1 cm1 = c-S1 cp1 = c+S1 (b.data)[oS+j] = \ ((a.data+r+c))[0] + \ (((a.data+rm1+c))[0] + \ ((a.data+rp1+c))[0] + \ ((a.data+r+cm1))[0] + \ ((a.data+r+cp1))[0])*0.5 + \ (((a.data+rm1+cm1))[0] + \ ((a.data+rp1+cm1))[0] + \ ((a.data+rp1+cp1))[0] + \ ((a.data+rm1+cp1))[0])*0.25 return b This 2-d averaging filter runs quickly because the loop is in C and the pointer computations are done only as needed. However, it is not particularly easy to understand what is happening. A 2-d image, ``in`` , can be filtered using this code very quickly using: .. code-block:: python import image out = image.filter(in) Conclusion ---------- There are several disadvantages of using Pyrex: 1. The syntax for Pyrex can get a bit bulky, and it can be confusing at first to understand what kind of objects you are getting and how to interface them with C-like constructs. 2. Inappropriate Pyrex syntax or incorrect calls to C-code or type- mismatches can result in failures such as 1. Pyrex failing to generate the extension module source code, 2. Compiler failure while generating the extension module binary due to incorrect C syntax, 3. Python failure when trying to use the module. 3. It is easy to lose a clean separation between Python and C which makes re-using your C-code for other non-Python-related projects more difficult. 4. Multi-dimensional arrays are "bulky" to index (appropriate macros may be able to fix this). 5. The C-code generated by Pyrex is hard to read and modify (and typically compiles with annoying but harmless warnings). Writing a good Pyrex extension module still takes a bit of effort because not only does it require (a little) familiarity with C, but also with Pyrex's brand of Python-mixed-with C. One big advantage of Pyrex-generated extension modules is that they are easy to distribute using distutils. In summary, Pyrex is a very capable tool for either gluing C-code or generating an extension module quickly and should not be over-looked. It is especially useful for people that can't or won't write C-code or Fortran code. But, if you are already able to write simple subroutines in C or Fortran, then I would use one of the other approaches such as f2py (for Fortran), ctypes (for C shared- libraries), or weave (for inline C-code). .. index:: single: pyrex ctypes ====== Ctypes is a python extension module (downloaded separately for Python <2.5 and included with Python 2.5) that allows you to call an arbitrary function in a shared library directly from Python. This approach allows you to interface with C-code directly from Python. This opens up an enormous number of libraries for use from Python. The drawback, however, is that coding mistakes can lead to ugly program crashes very easily (just as can happen in C) because there is little type or bounds checking done on the parameters. This is especially true when array data is passed in as a pointer to a raw memory location. The responsibility is then on you that the subroutine will not access memory outside the actual array area. But, if you don't mind living a little dangerously ctypes can be an effective tool for quickly taking advantage of a large shared library (or writing extended functionality in your own shared library). .. index:: single: ctypes Because the ctypes approach exposes a raw interface to the compiled code it is not always tolerant of user mistakes. Robust use of the ctypes module typically involves an additional layer of Python code in order to check the data types and array bounds of objects passed to the underlying subroutine. This additional layer of checking (not to mention the conversion from ctypes objects to C-data-types that ctypes itself performs), will make the interface slower than a hand-written extension-module interface. However, this overhead should be neglible if the C-routine being called is doing any significant amount of work. If you are a great Python programmer with weak C-skills, ctypes is an easy way to write a useful interface to a (shared) library of compiled code. To use c-types you must 1. Have a shared library. 2. Load the shared library. 3. Convert the python objects to ctypes-understood arguments. 4. Call the function from the library with the ctypes arguments. Having a shared library ----------------------- There are several requirements for a shared library that can be used with c-types that are platform specific. This guide assumes you have some familiarity with making a shared library on your system (or simply have a shared library available to you). Items to remember are: - A shared library must be compiled in a special way ( *e.g.* using the -shared flag with gcc). - On some platforms (*e.g.* Windows) , a shared library requires a .def file that specifies the functions to be exported. For example a mylib.def file might contain. :: LIBRARY mylib.dll EXPORTS cool_function1 cool_function2 Alternatively, you may be able to use the storage-class specifier __declspec(dllexport) in the C-definition of the function to avoid the need for this .def file. There is no standard way in Python distutils to create a standard shared library (an extension module is a "special" shared library Python understands) in a cross-platform manner. Thus, a big disadvantage of ctypes at the time of writing this book is that it is difficult to distribute in a cross-platform manner a Python extension that uses c-types and includes your own code which should be compiled as a shared library on the users system. Loading the shared library -------------------------- A simple, but robust way to load the shared library is to get the absolute path name and load it using the cdll object of ctypes.: .. code-block:: python lib = ctypes.cdll[] However, on Windows accessing an attribute of the cdll method will load the first DLL by that name found in the current directory or on the PATH. Loading the absolute path name requires a little finesse for cross-platform work since the extension of shared libraries varies. There is a ``ctypes.util.find_library`` utility available that can simplify the process of finding the library to load but it is not foolproof. Complicating matters, different platforms have different default extensions used by shared libraries (e.g. .dll -- Windows, .so -- Linux, .dylib -- Mac OS X). This must also be taken into account if you are using c-types to wrap code that needs to work on several platforms. NumPy provides a convenience function called :func:`ctypeslib.load_library` (name, path). This function takes the name of the shared library (including any prefix like 'lib' but excluding the extension) and a path where the shared library can be located. It returns a ctypes library object or raises an OSError if the library cannot be found or raises an ImportError if the ctypes module is not available. (Windows users: the ctypes library object loaded using :func:`load_library` is always loaded assuming cdecl calling convention. See the ctypes documentation under ctypes.windll and/or ctypes.oledll for ways to load libraries under other calling conventions). The functions in the shared library are available as attributes of the ctypes library object (returned from :func:`ctypeslib.load_library`) or as items using ``lib['func_name']`` syntax. The latter method for retrieving a function name is particularly useful if the function name contains characters that are not allowable in Python variable names. Converting arguments -------------------- Python ints/longs, strings, and unicode objects are automatically converted as needed to equivalent c-types arguments The None object is also converted automatically to a NULL pointer. All other Python objects must be converted to ctypes-specific types. There are two ways around this restriction that allow c-types to integrate with other objects. 1. Don't set the argtypes attribute of the function object and define an :obj:`_as_parameter_` method for the object you want to pass in. The :obj:`_as_parameter_` method must return a Python int which will be passed directly to the function. 2. Set the argtypes attribute to a list whose entries contain objects with a classmethod named from_param that knows how to convert your object to an object that ctypes can understand (an int/long, string, unicode, or object with the :obj:`_as_parameter_` attribute). NumPy uses both methods with a preference for the second method because it can be safer. The ctypes attribute of the ndarray returns an object that has an _as_parameter\_ attribute which returns an integer representing the address of the ndarray to which it is associated. As a result, one can pass this ctypes attribute object directly to a function expecting a pointer to the data in your ndarray. The caller must be sure that the ndarray object is of the correct type, shape, and has the correct flags set or risk nasty crashes if the data-pointer to inappropriate arrays are passsed in. To implement the second method, NumPy provides the class-factory function :func:`ndpointer` in the :mod:`ctypeslib` module. This class-factory function produces an appropriate class that can be placed in an argtypes attribute entry of a ctypes function. The class will contain a from_param method which ctypes will use to convert any ndarray passed in to the function to a ctypes-recognized object. In the process, the conversion will perform checking on any properties of the ndarray that were specified by the user in the call to :func:`ndpointer`. Aspects of the ndarray that can be checked include the data-type, the number-of-dimensions, the shape, and/or the state of the flags on any array passed. The return value of the from_param method is the ctypes attribute of the array which (because it contains the _as_parameter\_ attribute pointing to the array data area) can be used by ctypes directly. The ctypes attribute of an ndarray is also endowed with additional attributes that may be convenient when passing additional information about the array into a ctypes function. The attributes **data**, **shape**, and **strides** can provide c-types compatible types corresponding to the data-area, the shape, and the strides of the array. The data attribute reutrns a ``c_void_p`` representing a pointer to the data area. The shape and strides attributes each return an array of ctypes integers (or None representing a NULL pointer, if a 0-d array). The base ctype of the array is a ctype integer of the same size as a pointer on the platform. There are also methods data_as({ctype}), shape_as(), and strides_as(). These return the data as a ctype object of your choice and the shape/strides arrays using an underlying base type of your choice. For convenience, the **ctypeslib** module also contains **c_intp** as a ctypes integer data-type whose size is the same as the size of ``c_void_p`` on the platform (it's value is None if ctypes is not installed). Calling the function -------------------- The function is accessed as an attribute of or an item from the loaded shared-library. Thus, if "./mylib.so" has a function named "cool_function1" , I could access this function either as: .. code-block:: python lib = numpy.ctypeslib.load_library('mylib','.') func1 = lib.cool_function1 # or equivalently func1 = lib['cool_function1'] In ctypes, the return-value of a function is set to be 'int' by default. This behavior can be changed by setting the restype attribute of the function. Use None for the restype if the function has no return value ('void'): .. code-block:: python func1.restype = None As previously discussed, you can also set the argtypes attribute of the function in order to have ctypes check the types of the input arguments when the function is called. Use the :func:`ndpointer` factory function to generate a ready-made class for data-type, shape, and flags checking on your new function. The :func:`ndpointer` function has the signature .. function:: ndpointer(dtype=None, ndim=None, shape=None, flags=None) Keyword arguments with the value ``None`` are not checked. Specifying a keyword enforces checking of that aspect of the ndarray on conversion to a ctypes-compatible object. The dtype keyword can be any object understood as a data-type object. The ndim keyword should be an integer, and the shape keyword should be an integer or a sequence of integers. The flags keyword specifies the minimal flags that are required on any array passed in. This can be specified as a string of comma separated requirements, an integer indicating the requirement bits OR'd together, or a flags object returned from the flags attribute of an array with the necessary requirements. Using an ndpointer class in the argtypes method can make it significantly safer to call a C-function using ctypes and the data- area of an ndarray. You may still want to wrap the function in an additional Python wrapper to make it user-friendly (hiding some obvious arguments and making some arguments output arguments). In this process, the **requires** function in NumPy may be useful to return the right kind of array from a given input. Complete example ---------------- In this example, I will show how the addition function and the filter function implemented previously using the other approaches can be implemented using ctypes. First, the C-code which implements the algorithms contains the functions zadd, dadd, sadd, cadd, and dfilter2d. The zadd function is: .. code-block:: c /* Add arrays of contiguous data */ typedef struct {double real; double imag;} cdouble; typedef struct {float real; float imag;} cfloat; void zadd(cdouble *a, cdouble *b, cdouble *c, long n) { while (n--) { c->real = a->real + b->real; c->imag = a->imag + b->imag; a++; b++; c++; } } with similar code for cadd, dadd, and sadd that handles complex float, double, and float data-types, respectively: .. code-block:: c void cadd(cfloat *a, cfloat *b, cfloat *c, long n) { while (n--) { c->real = a->real + b->real; c->imag = a->imag + b->imag; a++; b++; c++; } } void dadd(double *a, double *b, double *c, long n) { while (n--) { *c++ = *a++ + *b++; } } void sadd(float *a, float *b, float *c, long n) { while (n--) { *c++ = *a++ + *b++; } } The code.c file also contains the function dfilter2d: .. code-block:: c /* Assumes b is contiguous and a has strides that are multiples of sizeof(double) */ void dfilter2d(double *a, double *b, int *astrides, int *dims) { int i, j, M, N, S0, S1; int r, c, rm1, rp1, cp1, cm1; M = dims[0]; N = dims[1]; S0 = astrides[0]/sizeof(double); S1=astrides[1]/sizeof(double); for (i=1; idimensions[0]; int dims[1]; dims[0] = n; PyArrayObject* ret; ret = (PyArrayObject*) PyArray_FromDims(1, dims, NPY_DOUBLE); int i; char *aj=a->data; char *bj=b->data; double *retj = (double *)ret->data; for (i=0; i < n; i++) { *retj++ = *((double *)aj) + *((double *)bj); aj += a->strides[0]; bj += b->strides[0]; } return (PyObject *)ret; } """ import Instant, numpy ext = Instant.Instant() ext.create_extension(code=s, headers=["numpy/arrayobject.h"], include_dirs=[numpy.get_include()], init_code='import_array();', module="test2b_ext") import test2b_ext a = numpy.arange(1000) b = numpy.arange(1000) d = test2b_ext.add(a,b) Except perhaps for the dependence on SWIG, Instant is a straightforward utility for writing extension modules. PyInline -------- This is a much older module that allows automatic building of extension modules so that C-code can be included with Python code. It's latest release (version 0.03) was in 2001, and it appears that it is not being updated. PyFort ------ PyFort is a nice tool for wrapping Fortran and Fortran-like C-code into Python with support for Numeric arrays. It was written by Paul Dubois, a distinguished computer scientist and the very first maintainer of Numeric (now retired). It is worth mentioning in the hopes that somebody will update PyFort to work with NumPy arrays as well which now support either Fortran or C-style contiguous arrays. numpy-1.8.2/doc/source/user/misc.rst0000664000175100017510000000017212370216242020533 0ustar vagrantvagrant00000000000000************* Miscellaneous ************* .. automodule:: numpy.doc.misc .. automodule:: numpy.doc.methods_vs_functions numpy-1.8.2/doc/source/user/introduction.rst0000664000175100017510000000013612370216242022321 0ustar vagrantvagrant00000000000000************ Introduction ************ .. toctree:: whatisnumpy install howtofind numpy-1.8.2/doc/source/user/basics.io.rst0000664000175100017510000000014412370216242021451 0ustar vagrantvagrant00000000000000************** I/O with Numpy ************** .. toctree:: :maxdepth: 2 basics.io.genfromtxt numpy-1.8.2/doc/source/user/basics.indexing.rst0000664000175100017510000000022012370216242022642 0ustar vagrantvagrant00000000000000.. _basics.indexing: ******** Indexing ******** .. seealso:: :ref:`Indexing routines ` .. automodule:: numpy.doc.indexing numpy-1.8.2/doc/source/user/basics.broadcasting.rst0000664000175100017510000000016612370216242023506 0ustar vagrantvagrant00000000000000************ Broadcasting ************ .. seealso:: :class:`numpy.broadcast` .. automodule:: numpy.doc.broadcasting numpy-1.8.2/doc/source/user/c-info.rst0000664000175100017510000000024712370216242020756 0ustar vagrantvagrant00000000000000################# Using Numpy C-API ################# .. toctree:: c-info.how-to-extend c-info.python-as-glue c-info.ufunc-tutorial c-info.beyond-basics numpy-1.8.2/doc/source/user/c-info.beyond-basics.rst0000664000175100017510000006003212370216242023475 0ustar vagrantvagrant00000000000000***************** Beyond the Basics ***************** | The voyage of discovery is not in seeking new landscapes but in having | new eyes. | --- *Marcel Proust* | Discovery is seeing what everyone else has seen and thinking what no | one else has thought. | --- *Albert Szent-Gyorgi* Iterating over elements in the array ==================================== .. _`sec:array_iterator`: Basic Iteration --------------- One common algorithmic requirement is to be able to walk over all elements in a multidimensional array. The array iterator object makes this easy to do in a generic way that works for arrays of any dimension. Naturally, if you know the number of dimensions you will be using, then you can always write nested for loops to accomplish the iteration. If, however, you want to write code that works with any number of dimensions, then you can make use of the array iterator. An array iterator object is returned when accessing the .flat attribute of an array. .. index:: single: array iterator Basic usage is to call :cfunc:`PyArray_IterNew` ( ``array`` ) where array is an ndarray object (or one of its sub-classes). The returned object is an array-iterator object (the same object returned by the .flat attribute of the ndarray). This object is usually cast to PyArrayIterObject* so that its members can be accessed. The only members that are needed are ``iter->size`` which contains the total size of the array, ``iter->index``, which contains the current 1-d index into the array, and ``iter->dataptr`` which is a pointer to the data for the current element of the array. Sometimes it is also useful to access ``iter->ao`` which is a pointer to the underlying ndarray object. After processing data at the current element of the array, the next element of the array can be obtained using the macro :cfunc:`PyArray_ITER_NEXT` ( ``iter`` ). The iteration always proceeds in a C-style contiguous fashion (last index varying the fastest). The :cfunc:`PyArray_ITER_GOTO` ( ``iter``, ``destination`` ) can be used to jump to a particular point in the array, where ``destination`` is an array of npy_intp data-type with space to handle at least the number of dimensions in the underlying array. Occasionally it is useful to use :cfunc:`PyArray_ITER_GOTO1D` ( ``iter``, ``index`` ) which will jump to the 1-d index given by the value of ``index``. The most common usage, however, is given in the following example. .. code-block:: c PyObject *obj; /* assumed to be some ndarray object */ PyArrayIterObject *iter; ... iter = (PyArrayIterObject *)PyArray_IterNew(obj); if (iter == NULL) goto fail; /* Assume fail has clean-up code */ while (iter->index < iter->size) { /* do something with the data at it->dataptr */ PyArray_ITER_NEXT(it); } ... You can also use :cfunc:`PyArrayIter_Check` ( ``obj`` ) to ensure you have an iterator object and :cfunc:`PyArray_ITER_RESET` ( ``iter`` ) to reset an iterator object back to the beginning of the array. It should be emphasized at this point that you may not need the array iterator if your array is already contiguous (using an array iterator will work but will be slower than the fastest code you could write). The major purpose of array iterators is to encapsulate iteration over N-dimensional arrays with arbitrary strides. They are used in many, many places in the NumPy source code itself. If you already know your array is contiguous (Fortran or C), then simply adding the element- size to a running pointer variable will step you through the array very efficiently. In other words, code like this will probably be faster for you in the contiguous case (assuming doubles). .. code-block:: c npy_intp size; double *dptr; /* could make this any variable type */ size = PyArray_SIZE(obj); dptr = PyArray_DATA(obj); while(size--) { /* do something with the data at dptr */ dptr++; } Iterating over all but one axis ------------------------------- A common algorithm is to loop over all elements of an array and perform some function with each element by issuing a function call. As function calls can be time consuming, one way to speed up this kind of algorithm is to write the function so it takes a vector of data and then write the iteration so the function call is performed for an entire dimension of data at a time. This increases the amount of work done per function call, thereby reducing the function-call over-head to a small(er) fraction of the total time. Even if the interior of the loop is performed without a function call it can be advantageous to perform the inner loop over the dimension with the highest number of elements to take advantage of speed enhancements available on micro- processors that use pipelining to enhance fundmental operations. The :cfunc:`PyArray_IterAllButAxis` ( ``array``, ``&dim`` ) constructs an iterator object that is modified so that it will not iterate over the dimension indicated by dim. The only restriction on this iterator object, is that the :cfunc:`PyArray_Iter_GOTO1D` ( ``it``, ``ind`` ) macro cannot be used (thus flat indexing won't work either if you pass this object back to Python --- so you shouldn't do this). Note that the returned object from this routine is still usually cast to PyArrayIterObject \*. All that's been done is to modify the strides and dimensions of the returned iterator to simulate iterating over array[...,0,...] where 0 is placed on the :math:`\textrm{dim}^{\textrm{th}}` dimension. If dim is negative, then the dimension with the largest axis is found and used. Iterating over multiple arrays ------------------------------ Very often, it is desireable to iterate over several arrays at the same time. The universal functions are an example of this kind of behavior. If all you want to do is iterate over arrays with the same shape, then simply creating several iterator objects is the standard procedure. For example, the following code iterates over two arrays assumed to be the same shape and size (actually obj1 just has to have at least as many total elements as does obj2): .. code-block:: c /* It is already assumed that obj1 and obj2 are ndarrays of the same shape and size. */ iter1 = (PyArrayIterObject *)PyArray_IterNew(obj1); if (iter1 == NULL) goto fail; iter2 = (PyArrayIterObject *)PyArray_IterNew(obj2); if (iter2 == NULL) goto fail; /* assume iter1 is DECREF'd at fail */ while (iter2->index < iter2->size) { /* process with iter1->dataptr and iter2->dataptr */ PyArray_ITER_NEXT(iter1); PyArray_ITER_NEXT(iter2); } Broadcasting over multiple arrays --------------------------------- .. index:: single: broadcasting When multiple arrays are involved in an operation, you may want to use the same broadcasting rules that the math operations (*i.e.* the ufuncs) use. This can be done easily using the :ctype:`PyArrayMultiIterObject`. This is the object returned from the Python command numpy.broadcast and it is almost as easy to use from C. The function :cfunc:`PyArray_MultiIterNew` ( ``n``, ``...`` ) is used (with ``n`` input objects in place of ``...`` ). The input objects can be arrays or anything that can be converted into an array. A pointer to a PyArrayMultiIterObject is returned. Broadcasting has already been accomplished which adjusts the iterators so that all that needs to be done to advance to the next element in each array is for PyArray_ITER_NEXT to be called for each of the inputs. This incrementing is automatically performed by :cfunc:`PyArray_MultiIter_NEXT` ( ``obj`` ) macro (which can handle a multiterator ``obj`` as either a :ctype:`PyArrayMultiObject *` or a :ctype:`PyObject *`). The data from input number ``i`` is available using :cfunc:`PyArray_MultiIter_DATA` ( ``obj``, ``i`` ) and the total (broadcasted) size as :cfunc:`PyArray_MultiIter_SIZE` ( ``obj``). An example of using this feature follows. .. code-block:: c mobj = PyArray_MultiIterNew(2, obj1, obj2); size = PyArray_MultiIter_SIZE(obj); while(size--) { ptr1 = PyArray_MultiIter_DATA(mobj, 0); ptr2 = PyArray_MultiIter_DATA(mobj, 1); /* code using contents of ptr1 and ptr2 */ PyArray_MultiIter_NEXT(mobj); } The function :cfunc:`PyArray_RemoveSmallest` ( ``multi`` ) can be used to take a multi-iterator object and adjust all the iterators so that iteration does not take place over the largest dimension (it makes that dimension of size 1). The code being looped over that makes use of the pointers will very-likely also need the strides data for each of the iterators. This information is stored in multi->iters[i]->strides. .. index:: single: array iterator There are several examples of using the multi-iterator in the NumPy source code as it makes N-dimensional broadcasting-code very simple to write. Browse the source for more examples. .. _user.user-defined-data-types: User-defined data-types ======================= NumPy comes with 24 builtin data-types. While this covers a large majority of possible use cases, it is conceivable that a user may have a need for an additional data-type. There is some support for adding an additional data-type into the NumPy system. This additional data- type will behave much like a regular data-type except ufuncs must have 1-d loops registered to handle it separately. Also checking for whether or not other data-types can be cast "safely" to and from this new type or not will always return "can cast" unless you also register which types your new data-type can be cast to and from. Adding data-types is one of the less well-tested areas for NumPy 1.0, so there may be bugs remaining in the approach. Only add a new data-type if you can't do what you want to do using the OBJECT or VOID data-types that are already available. As an example of what I consider a useful application of the ability to add data-types is the possibility of adding a data-type of arbitrary precision floats to NumPy. .. index:: pair: dtype; adding new Adding the new data-type ------------------------ To begin to make use of the new data-type, you need to first define a new Python type to hold the scalars of your new data-type. It should be acceptable to inherit from one of the array scalars if your new type has a binary compatible layout. This will allow your new data type to have the methods and attributes of array scalars. New data- types must have a fixed memory size (if you want to define a data-type that needs a flexible representation, like a variable-precision number, then use a pointer to the object as the data-type). The memory layout of the object structure for the new Python type must be PyObject_HEAD followed by the fixed-size memory needed for the data- type. For example, a suitable structure for the new Python type is: .. code-block:: c typedef struct { PyObject_HEAD; some_data_type obval; /* the name can be whatever you want */ } PySomeDataTypeObject; After you have defined a new Python type object, you must then define a new :ctype:`PyArray_Descr` structure whose typeobject member will contain a pointer to the data-type you've just defined. In addition, the required functions in the ".f" member must be defined: nonzero, copyswap, copyswapn, setitem, getitem, and cast. The more functions in the ".f" member you define, however, the more useful the new data-type will be. It is very important to intialize unused functions to NULL. This can be achieved using :cfunc:`PyArray_InitArrFuncs` (f). Once a new :ctype:`PyArray_Descr` structure is created and filled with the needed information and useful functions you call :cfunc:`PyArray_RegisterDataType` (new_descr). The return value from this call is an integer providing you with a unique type_number that specifies your data-type. This type number should be stored and made available by your module so that other modules can use it to recognize your data-type (the other mechanism for finding a user-defined data-type number is to search based on the name of the type-object associated with the data-type using :cfunc:`PyArray_TypeNumFromName` ). Registering a casting function ------------------------------ You may want to allow builtin (and other user-defined) data-types to be cast automatically to your data-type. In order to make this possible, you must register a casting function with the data-type you want to be able to cast from. This requires writing low-level casting functions for each conversion you want to support and then registering these functions with the data-type descriptor. A low-level casting function has the signature. .. cfunction:: void castfunc( void* from, void* to, npy_intp n, void* fromarr, void* toarr) Cast ``n`` elements ``from`` one type ``to`` another. The data to cast from is in a contiguous, correctly-swapped and aligned chunk of memory pointed to by from. The buffer to cast to is also contiguous, correctly-swapped and aligned. The fromarr and toarr arguments should only be used for flexible-element-sized arrays (string, unicode, void). An example castfunc is: .. code-block:: c static void double_to_float(double *from, float* to, npy_intp n, void* ig1, void* ig2); while (n--) { (*to++) = (double) *(from++); } This could then be registered to convert doubles to floats using the code: .. code-block:: c doub = PyArray_DescrFromType(NPY_DOUBLE); PyArray_RegisterCastFunc(doub, NPY_FLOAT, (PyArray_VectorUnaryFunc *)double_to_float); Py_DECREF(doub); Registering coercion rules -------------------------- By default, all user-defined data-types are not presumed to be safely castable to any builtin data-types. In addition builtin data-types are not presumed to be safely castable to user-defined data-types. This situation limits the ability of user-defined data-types to participate in the coercion system used by ufuncs and other times when automatic coercion takes place in NumPy. This can be changed by registering data-types as safely castable from a particlar data-type object. The function :cfunc:`PyArray_RegisterCanCast` (from_descr, totype_number, scalarkind) should be used to specify that the data-type object from_descr can be cast to the data-type with type number totype_number. If you are not trying to alter scalar coercion rules, then use :cdata:`NPY_NOSCALAR` for the scalarkind argument. If you want to allow your new data-type to also be able to share in the scalar coercion rules, then you need to specify the scalarkind function in the data-type object's ".f" member to return the kind of scalar the new data-type should be seen as (the value of the scalar is available to that function). Then, you can register data-types that can be cast to separately for each scalar kind that may be returned from your user-defined data-type. If you don't register scalar coercion handling, then all of your user-defined data-types will be seen as :cdata:`NPY_NOSCALAR`. Registering a ufunc loop ------------------------ You may also want to register low-level ufunc loops for your data-type so that an ndarray of your data-type can have math applied to it seamlessly. Registering a new loop with exactly the same arg_types signature, silently replaces any previously registered loops for that data-type. Before you can register a 1-d loop for a ufunc, the ufunc must be previously created. Then you call :cfunc:`PyUFunc_RegisterLoopForType` (...) with the information needed for the loop. The return value of this function is ``0`` if the process was successful and ``-1`` with an error condition set if it was not successful. .. cfunction:: int PyUFunc_RegisterLoopForType( PyUFuncObject* ufunc, int usertype, PyUFuncGenericFunction function, int* arg_types, void* data) *ufunc* The ufunc to attach this loop to. *usertype* The user-defined type this loop should be indexed under. This number must be a user-defined type or an error occurs. *function* The ufunc inner 1-d loop. This function must have the signature as explained in Section `3 <#sec-creating-a-new>`__ . *arg_types* (optional) If given, this should contain an array of integers of at least size ufunc.nargs containing the data-types expected by the loop function. The data will be copied into a NumPy-managed structure so the memory for this argument should be deleted after calling this function. If this is NULL, then it will be assumed that all data-types are of type usertype. *data* (optional) Specify any optional data needed by the function which will be passed when the function is called. .. index:: pair: dtype; adding new Subtyping the ndarray in C ========================== One of the lesser-used features that has been lurking in Python since 2.2 is the ability to sub-class types in C. This facility is one of the important reasons for basing NumPy off of the Numeric code-base which was already in C. A sub-type in C allows much more flexibility with regards to memory management. Sub-typing in C is not difficult even if you have only a rudimentary understanding of how to create new types for Python. While it is easiest to sub-type from a single parent type, sub-typing from multiple parent types is also possible. Multiple inheritence in C is generally less useful than it is in Python because a restriction on Python sub-types is that they have a binary compatible memory layout. Perhaps for this reason, it is somewhat easier to sub-type from a single parent type. .. index:: pair: ndarray; subtyping All C-structures corresponding to Python objects must begin with :cmacro:`PyObject_HEAD` (or :cmacro:`PyObject_VAR_HEAD`). In the same way, any sub-type must have a C-structure that begins with exactly the same memory layout as the parent type (or all of the parent types in the case of multiple-inheritance). The reason for this is that Python may attempt to access a member of the sub-type structure as if it had the parent structure ( *i.e.* it will cast a given pointer to a pointer to the parent structure and then dereference one of it's members). If the memory layouts are not compatible, then this attempt will cause unpredictable behavior (eventually leading to a memory violation and program crash). One of the elements in :cmacro:`PyObject_HEAD` is a pointer to a type-object structure. A new Python type is created by creating a new type-object structure and populating it with functions and pointers to describe the desired behavior of the type. Typically, a new C-structure is also created to contain the instance-specific information needed for each object of the type as well. For example, :cdata:`&PyArray_Type` is a pointer to the type-object table for the ndarray while a :ctype:`PyArrayObject *` variable is a pointer to a particular instance of an ndarray (one of the members of the ndarray structure is, in turn, a pointer to the type- object table :cdata:`&PyArray_Type`). Finally :cfunc:`PyType_Ready` () must be called for every new Python type. Creating sub-types ------------------ To create a sub-type, a similar proceedure must be followed except only behaviors that are different require new entries in the type- object structure. All other entires can be NULL and will be filled in by :cfunc:`PyType_Ready` with appropriate functions from the parent type(s). In particular, to create a sub-type in C follow these steps: 1. If needed create a new C-structure to handle each instance of your type. A typical C-structure would be: .. code-block:: c typedef _new_struct { PyArrayObject base; /* new things here */ } NewArrayObject; Notice that the full PyArrayObject is used as the first entry in order to ensure that the binary layout of instances of the new type is identical to the PyArrayObject. 2. Fill in a new Python type-object structure with pointers to new functions that will over-ride the default behavior while leaving any function that should remain the same unfilled (or NULL). The tp_name element should be different. 3. Fill in the tp_base member of the new type-object structure with a pointer to the (main) parent type object. For multiple-inheritance, also fill in the tp_bases member with a tuple containing all of the parent objects in the order they should be used to define inheritance. Remember, all parent-types must have the same C-structure for multiple inheritance to work properly. 4. Call :cfunc:`PyType_Ready` (). If this function returns a negative number, a failure occurred and the type is not initialized. Otherwise, the type is ready to be used. It is generally important to place a reference to the new type into the module dictionary so it can be accessed from Python. More information on creating sub-types in C can be learned by reading PEP 253 (available at http://www.python.org/dev/peps/pep-0253). Specific features of ndarray sub-typing --------------------------------------- Some special methods and attributes are used by arrays in order to facilitate the interoperation of sub-types with the base ndarray type. The __array_finalize\__ method ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ .. attribute:: ndarray.__array_finalize__ Several array-creation functions of the ndarray allow specification of a particular sub-type to be created. This allows sub-types to be handled seamlessly in many routines. When a sub-type is created in such a fashion, however, neither the __new_\_ method nor the __init\__ method gets called. Instead, the sub-type is allocated and the appropriate instance-structure members are filled in. Finally, the :obj:`__array_finalize__` attribute is looked-up in the object dictionary. If it is present and not None, then it can be either a CObject containing a pointer to a :cfunc:`PyArray_FinalizeFunc` or it can be a method taking a single argument (which could be None). If the :obj:`__array_finalize__` attribute is a CObject, then the pointer must be a pointer to a function with the signature: .. code-block:: c (int) (PyArrayObject *, PyObject *) The first argument is the newly created sub-type. The second argument (if not NULL) is the "parent" array (if the array was created using slicing or some other operation where a clearly-distinguishable parent is present). This routine can do anything it wants to. It should return a -1 on error and 0 otherwise. If the :obj:`__array_finalize__` attribute is not None nor a CObject, then it must be a Python method that takes the parent array as an argument (which could be None if there is no parent), and returns nothing. Errors in this method will be caught and handled. The __array_priority\__ attribute ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ .. attribute:: ndarray.__array_priority__ This attribute allows simple but flexible determination of which sub- type should be considered "primary" when an operation involving two or more sub-types arises. In operations where different sub-types are being used, the sub-type with the largest :obj:`__array_priority__` attribute will determine the sub-type of the output(s). If two sub- types have the same :obj:`__array_priority__` then the sub-type of the first argument determines the output. The default :obj:`__array_priority__` attribute returns a value of 0.0 for the base ndarray type and 1.0 for a sub-type. This attribute can also be defined by objects that are not sub-types of the ndarray and can be used to determine which :obj:`__array_wrap__` method should be called for the return output. The __array_wrap\__ method ^^^^^^^^^^^^^^^^^^^^^^^^^^ .. attribute:: ndarray.__array_wrap__ Any class or type can define this method which should take an ndarray argument and return an instance of the type. It can be seen as the opposite of the :obj:`__array__` method. This method is used by the ufuncs (and other NumPy functions) to allow other objects to pass through. For Python >2.4, it can also be used to write a decorator that converts a function that works only with ndarrays to one that works with any type with :obj:`__array__` and :obj:`__array_wrap__` methods. .. index:: pair: ndarray; subtyping numpy-1.8.2/doc/source/user/basics.io.genfromtxt.rst0000664000175100017510000005035312370216242023654 0ustar vagrantvagrant00000000000000.. sectionauthor:: Pierre Gerard-Marchant ********************************************* Importing data with :func:`~numpy.genfromtxt` ********************************************* Numpy provides several functions to create arrays from tabular data. We focus here on the :func:`~numpy.genfromtxt` function. In a nutshell, :func:`~numpy.genfromtxt` runs two main loops. The first loop converts each line of the file in a sequence of strings. The second loop converts each string to the appropriate data type. This mechanism is slower than a single loop, but gives more flexibility. In particular, :func:`~numpy.genfromtxt` is able to take missing data into account, when other faster and simpler functions like :func:`~numpy.loadtxt` cannot. .. note:: When giving examples, we will use the following conventions:: >>> import numpy as np >>> from StringIO import StringIO Defining the input ================== The only mandatory argument of :func:`~numpy.genfromtxt` is the source of the data. It can be a string corresponding to the name of a local or remote file, or a file-like object with a :meth:`read` method (such as an actual file or a :class:`StringIO.StringIO` object). If the argument is the URL of a remote file, this latter is automatically downloaded in the current directory. The input file can be a text file or an archive. Currently, the function recognizes :class:`gzip` and :class:`bz2` (`bzip2`) archives. The type of the archive is determined by examining the extension of the file: if the filename ends with ``'.gz'``, a :class:`gzip` archive is expected; if it ends with ``'bz2'``, a :class:`bzip2` archive is assumed. Splitting the lines into columns ================================ The :keyword:`delimiter` argument --------------------------------- Once the file is defined and open for reading, :func:`~numpy.genfromtxt` splits each non-empty line into a sequence of strings. Empty or commented lines are just skipped. The :keyword:`delimiter` keyword is used to define how the splitting should take place. Quite often, a single character marks the separation between columns. For example, comma-separated files (CSV) use a comma (``,``) or a semicolon (``;``) as delimiter:: >>> data = "1, 2, 3\n4, 5, 6" >>> np.genfromtxt(StringIO(data), delimiter=",") array([[ 1., 2., 3.], [ 4., 5., 6.]]) Another common separator is ``"\t"``, the tabulation character. However, we are not limited to a single character, any string will do. By default, :func:`~numpy.genfromtxt` assumes ``delimiter=None``, meaning that the line is split along white spaces (including tabs) and that consecutive white spaces are considered as a single white space. Alternatively, we may be dealing with a fixed-width file, where columns are defined as a given number of characters. In that case, we need to set :keyword:`delimiter` to a single integer (if all the columns have the same size) or to a sequence of integers (if columns can have different sizes):: >>> data = " 1 2 3\n 4 5 67\n890123 4" >>> np.genfromtxt(StringIO(data), delimiter=3) array([[ 1., 2., 3.], [ 4., 5., 67.], [ 890., 123., 4.]]) >>> data = "123456789\n 4 7 9\n 4567 9" >>> np.genfromtxt(StringIO(data), delimiter=(4, 3, 2)) array([[ 1234., 567., 89.], [ 4., 7., 9.], [ 4., 567., 9.]]) The :keyword:`autostrip` argument --------------------------------- By default, when a line is decomposed into a series of strings, the individual entries are not stripped of leading nor trailing white spaces. This behavior can be overwritten by setting the optional argument :keyword:`autostrip` to a value of ``True``:: >>> data = "1, abc , 2\n 3, xxx, 4" >>> # Without autostrip >>> np.genfromtxt(StringIO(data), dtype="|S5") array([['1', ' abc ', ' 2'], ['3', ' xxx', ' 4']], dtype='|S5') >>> # With autostrip >>> np.genfromtxt(StringIO(data), dtype="|S5", autostrip=True) array([['1', 'abc', '2'], ['3', 'xxx', '4']], dtype='|S5') The :keyword:`comments` argument -------------------------------- The optional argument :keyword:`comments` is used to define a character string that marks the beginning of a comment. By default, :func:`~numpy.genfromtxt` assumes ``comments='#'``. The comment marker may occur anywhere on the line. Any character present after the comment marker(s) is simply ignored:: >>> data = """# ... # Skip me ! ... # Skip me too ! ... 1, 2 ... 3, 4 ... 5, 6 #This is the third line of the data ... 7, 8 ... # And here comes the last line ... 9, 0 ... """ >>> np.genfromtxt(StringIO(data), comments="#", delimiter=",") [[ 1. 2.] [ 3. 4.] [ 5. 6.] [ 7. 8.] [ 9. 0.]] .. note:: There is one notable exception to this behavior: if the optional argument ``names=True``, the first commented line will be examined for names. Skipping lines and choosing columns =================================== The :keyword:`skip_header` and :keyword:`skip_footer` arguments --------------------------------------------------------------- The presence of a header in the file can hinder data processing. In that case, we need to use the :keyword:`skip_header` optional argument. The values of this argument must be an integer which corresponds to the number of lines to skip at the beginning of the file, before any other action is performed. Similarly, we can skip the last ``n`` lines of the file by using the :keyword:`skip_footer` attribute and giving it a value of ``n``:: >>> data = "\n".join(str(i) for i in range(10)) >>> np.genfromtxt(StringIO(data),) array([ 0., 1., 2., 3., 4., 5., 6., 7., 8., 9.]) >>> np.genfromtxt(StringIO(data), ... skip_header=3, skip_footer=5) array([ 3., 4.]) By default, ``skip_header=0`` and ``skip_footer=0``, meaning that no lines are skipped. The :keyword:`usecols` argument ------------------------------- In some cases, we are not interested in all the columns of the data but only a few of them. We can select which columns to import with the :keyword:`usecols` argument. This argument accepts a single integer or a sequence of integers corresponding to the indices of the columns to import. Remember that by convention, the first column has an index of 0. Negative integers behave the same as regular Python negative indexes. For example, if we want to import only the first and the last columns, we can use ``usecols=(0, -1)``:: >>> data = "1 2 3\n4 5 6" >>> np.genfromtxt(StringIO(data), usecols=(0, -1)) array([[ 1., 3.], [ 4., 6.]]) If the columns have names, we can also select which columns to import by giving their name to the :keyword:`usecols` argument, either as a sequence of strings or a comma-separated string:: >>> data = "1 2 3\n4 5 6" >>> np.genfromtxt(StringIO(data), ... names="a, b, c", usecols=("a", "c")) array([(1.0, 3.0), (4.0, 6.0)], dtype=[('a', '>> np.genfromtxt(StringIO(data), ... names="a, b, c", usecols=("a, c")) array([(1.0, 3.0), (4.0, 6.0)], dtype=[('a', '>> data = StringIO("1 2 3\n 4 5 6") >>> np.genfromtxt(data, dtype=[(_, int) for _ in "abc"]) array([(1, 2, 3), (4, 5, 6)], dtype=[('a', '>> data = StringIO("1 2 3\n 4 5 6") >>> np.genfromtxt(data, names="A, B, C") array([(1.0, 2.0, 3.0), (4.0, 5.0, 6.0)], dtype=[('A', '>> data = StringIO("So it goes\n#a b c\n1 2 3\n 4 5 6") >>> np.genfromtxt(data, skip_header=1, names=True) array([(1.0, 2.0, 3.0), (4.0, 5.0, 6.0)], dtype=[('a', '>> data = StringIO("1 2 3\n 4 5 6") >>> ndtype=[('a',int), ('b', float), ('c', int)] >>> names = ["A", "B", "C"] >>> np.genfromtxt(data, names=names, dtype=ndtype) array([(1, 2.0, 3), (4, 5.0, 6)], dtype=[('A', '>> data = StringIO("1 2 3\n 4 5 6") >>> np.genfromtxt(data, dtype=(int, float, int)) array([(1, 2.0, 3), (4, 5.0, 6)], dtype=[('f0', '>> data = StringIO("1 2 3\n 4 5 6") >>> np.genfromtxt(data, dtype=(int, float, int), names="a") array([(1, 2.0, 3), (4, 5.0, 6)], dtype=[('a', '>> data = StringIO("1 2 3\n 4 5 6") >>> np.genfromtxt(data, dtype=(int, float, int), defaultfmt="var_%02i") array([(1, 2.0, 3), (4, 5.0, 6)], dtype=[('var_00', ',<``. :keyword:`excludelist` Gives a list of the names to exclude, such as ``return``, ``file``, ``print``... If one of the input name is part of this list, an underscore character (``'_'``) will be appended to it. :keyword:`case_sensitive` Whether the names should be case-sensitive (``case_sensitive=True``), converted to upper case (``case_sensitive=False`` or ``case_sensitive='upper'``) or to lower case (``case_sensitive='lower'``). Tweaking the conversion ======================= The :keyword:`converters` argument ---------------------------------- Usually, defining a dtype is sufficient to define how the sequence of strings must be converted. However, some additional control may sometimes be required. For example, we may want to make sure that a date in a format ``YYYY/MM/DD`` is converted to a :class:`datetime` object, or that a string like ``xx%`` is properly converted to a float between 0 and 1. In such cases, we should define conversion functions with the :keyword:`converters` arguments. The value of this argument is typically a dictionary with column indices or column names as keys and a conversion functions as values. These conversion functions can either be actual functions or lambda functions. In any case, they should accept only a string as input and output only a single element of the wanted type. In the following example, the second column is converted from as string representing a percentage to a float between 0 and 1:: >>> convertfunc = lambda x: float(x.strip("%"))/100. >>> data = "1, 2.3%, 45.\n6, 78.9%, 0" >>> names = ("i", "p", "n") >>> # General case ..... >>> np.genfromtxt(StringIO(data), delimiter=",", names=names) array([(1.0, nan, 45.0), (6.0, nan, 0.0)], dtype=[('i', '>> # Converted case ... >>> np.genfromtxt(StringIO(data), delimiter=",", names=names, ... converters={1: convertfunc}) array([(1.0, 0.023, 45.0), (6.0, 0.78900000000000003, 0.0)], dtype=[('i', '>> # Using a name for the converter ... >>> np.genfromtxt(StringIO(data), delimiter=",", names=names, ... converters={"p": convertfunc}) array([(1.0, 0.023, 45.0), (6.0, 0.78900000000000003, 0.0)], dtype=[('i', '>> data = "1, , 3\n 4, 5, 6" >>> convert = lambda x: float(x.strip() or -999) >>> np.genfromtxt(StringIO(data), delimiter=",", ... converter={1: convert}) array([[ 1., -999., 3.], [ 4., 5., 6.]]) Using missing and filling values -------------------------------- Some entries may be missing in the dataset we are trying to import. In a previous example, we used a converter to transform an empty string into a float. However, user-defined converters may rapidly become cumbersome to manage. The :func:`~nummpy.genfromtxt` function provides two other complementary mechanisms: the :keyword:`missing_values` argument is used to recognize missing data and a second argument, :keyword:`filling_values`, is used to process these missing data. :keyword:`missing_values` ------------------------- By default, any empty string is marked as missing. We can also consider more complex strings, such as ``"N/A"`` or ``"???"`` to represent missing or invalid data. The :keyword:`missing_values` argument accepts three kind of values: a string or a comma-separated string This string will be used as the marker for missing data for all the columns a sequence of strings In that case, each item is associated to a column, in order. a dictionary Values of the dictionary are strings or sequence of strings. The corresponding keys can be column indices (integers) or column names (strings). In addition, the special key ``None`` can be used to define a default applicable to all columns. :keyword:`filling_values` ------------------------- We know how to recognize missing data, but we still need to provide a value for these missing entries. By default, this value is determined from the expected dtype according to this table: ============= ============== Expected type Default ============= ============== ``bool`` ``False`` ``int`` ``-1`` ``float`` ``np.nan`` ``complex`` ``np.nan+0j`` ``string`` ``'???'`` ============= ============== We can get a finer control on the conversion of missing values with the :keyword:`filling_values` optional argument. Like :keyword:`missing_values`, this argument accepts different kind of values: a single value This will be the default for all columns a sequence of values Each entry will be the default for the corresponding column a dictionary Each key can be a column index or a column name, and the corresponding value should be a single object. We can use the special key ``None`` to define a default for all columns. In the following example, we suppose that the missing values are flagged with ``"N/A"`` in the first column and by ``"???"`` in the third column. We wish to transform these missing values to 0 if they occur in the first and second column, and to -999 if they occur in the last column:: >>> data = "N/A, 2, 3\n4, ,???" >>> kwargs = dict(delimiter=",", ... dtype=int, ... names="a,b,c", ... missing_values={0:"N/A", 'b':" ", 2:"???"}, ... filling_values={0:0, 'b':0, 2:-999}) >>> np.genfromtxt(StringIO.StringIO(data), **kwargs) array([(0, 2, 3), (4, 0, -999)], dtype=[('a', '` .. automodule:: numpy.doc.creation numpy-1.8.2/doc/source/reference/0000775000175100017510000000000012371375427020042 5ustar vagrantvagrant00000000000000numpy-1.8.2/doc/source/reference/c-api.array.rst0000664000175100017510000041261412370216243022677 0ustar vagrantvagrant00000000000000Array API ========= .. sectionauthor:: Travis E. Oliphant | The test of a first-rate intelligence is the ability to hold two | opposed ideas in the mind at the same time, and still retain the | ability to function. | --- *F. Scott Fitzgerald* | For a successful technology, reality must take precedence over public | relations, for Nature cannot be fooled. | --- *Richard P. Feynman* .. index:: pair: ndarray; C-API pair: C-API; array Array structure and data access ------------------------------- These macros all access the :ctype:`PyArrayObject` structure members. The input argument, arr, can be any :ctype:`PyObject *` that is directly interpretable as a :ctype:`PyArrayObject *` (any instance of the :cdata:`PyArray_Type` and its sub-types). .. cfunction:: int PyArray_NDIM(PyArrayObject *arr) The number of dimensions in the array. .. cfunction:: npy_intp *PyArray_DIMS(PyArrayObject *arr) Returns a pointer to the dimensions/shape of the array. The number of elements matches the number of dimensions of the array. .. cfunction:: npy_intp *PyArray_SHAPE(PyArrayObject *arr) .. versionadded:: 1.7 A synonym for PyArray_DIMS, named to be consistent with the 'shape' usage within Python. .. cfunction:: void *PyArray_DATA(PyArrayObject *arr) .. cfunction:: char *PyArray_BYTES(PyArrayObject *arr) These two macros are similar and obtain the pointer to the data-buffer for the array. The first macro can (and should be) assigned to a particular pointer where the second is for generic processing. If you have not guaranteed a contiguous and/or aligned array then be sure you understand how to access the data in the array to avoid memory and/or alignment problems. .. cfunction:: npy_intp *PyArray_STRIDES(PyArrayObject* arr) Returns a pointer to the strides of the array. The number of elements matches the number of dimensions of the array. .. cfunction:: npy_intp PyArray_DIM(PyArrayObject* arr, int n) Return the shape in the *n* :math:`^{\textrm{th}}` dimension. .. cfunction:: npy_intp PyArray_STRIDE(PyArrayObject* arr, int n) Return the stride in the *n* :math:`^{\textrm{th}}` dimension. .. cfunction:: PyObject *PyArray_BASE(PyArrayObject* arr) This returns the base object of the array. In most cases, this means the object which owns the memory the array is pointing at. If you are constructing an array using the C API, and specifying your own memory, you should use the function :cfunc:`PyArray_SetBaseObject` to set the base to an object which owns the memory. If the :cdata:`NPY_ARRAY_UPDATEIFCOPY` flag is set, it has a different meaning, namely base is the array into which the current array will be copied upon destruction. This overloading of the base property for two functions is likely to change in a future version of NumPy. .. cfunction:: PyArray_Descr *PyArray_DESCR(PyArrayObject* arr) Returns a borrowed reference to the dtype property of the array. .. cfunction:: PyArray_Descr *PyArray_DTYPE(PyArrayObject* arr) .. versionadded:: 1.7 A synonym for PyArray_DESCR, named to be consistent with the 'dtype' usage within Python. .. cfunction:: void PyArray_ENABLEFLAGS(PyArrayObject* arr, int flags) .. versionadded:: 1.7 Enables the specified array flags. This function does no validation, and assumes that you know what you're doing. .. cfunction:: void PyArray_CLEARFLAGS(PyArrayObject* arr, int flags) .. versionadded:: 1.7 Clears the specified array flags. This function does no validation, and assumes that you know what you're doing. .. cfunction:: int PyArray_FLAGS(PyArrayObject* arr) .. cfunction:: int PyArray_ITEMSIZE(PyArrayObject* arr) Return the itemsize for the elements of this array. .. cfunction:: int PyArray_TYPE(PyArrayObject* arr) Return the (builtin) typenumber for the elements of this array. .. cfunction:: PyObject *PyArray_GETITEM(PyArrayObject* arr, void* itemptr) Get a Python object from the ndarray, *arr*, at the location pointed to by itemptr. Return ``NULL`` on failure. .. cfunction:: int PyArray_SETITEM(PyArrayObject* arr, void* itemptr, PyObject* obj) Convert obj and place it in the ndarray, *arr*, at the place pointed to by itemptr. Return -1 if an error occurs or 0 on success. .. cfunction:: npy_intp PyArray_SIZE(PyArrayObject* arr) Returns the total size (in number of elements) of the array. .. cfunction:: npy_intp PyArray_Size(PyArrayObject* obj) Returns 0 if *obj* is not a sub-class of bigndarray. Otherwise, returns the total number of elements in the array. Safer version of :cfunc:`PyArray_SIZE` (*obj*). .. cfunction:: npy_intp PyArray_NBYTES(PyArrayObject* arr) Returns the total number of bytes consumed by the array. Data access ^^^^^^^^^^^ These functions and macros provide easy access to elements of the ndarray from C. These work for all arrays. You may need to take care when accessing the data in the array, however, if it is not in machine byte-order, misaligned, or not writeable. In other words, be sure to respect the state of the flags unless you know what you are doing, or have previously guaranteed an array that is writeable, aligned, and in machine byte-order using :cfunc:`PyArray_FromAny`. If you wish to handle all types of arrays, the copyswap function for each type is useful for handling misbehaved arrays. Some platforms (e.g. Solaris) do not like misaligned data and will crash if you de-reference a misaligned pointer. Other platforms (e.g. x86 Linux) will just work more slowly with misaligned data. .. cfunction:: void* PyArray_GetPtr(PyArrayObject* aobj, npy_intp* ind) Return a pointer to the data of the ndarray, *aobj*, at the N-dimensional index given by the c-array, *ind*, (which must be at least *aobj* ->nd in size). You may want to typecast the returned pointer to the data type of the ndarray. .. cfunction:: void* PyArray_GETPTR1(PyArrayObject* obj, npy_intp i) .. cfunction:: void* PyArray_GETPTR2(PyArrayObject* obj, npy_intp i, npy_intp j) .. cfunction:: void* PyArray_GETPTR3(PyArrayObject* obj, npy_intp i, npy_intp j, npy_intp k) .. cfunction:: void* PyArray_GETPTR4(PyArrayObject* obj, npy_intp i, npy_intp j, npy_intp k, npy_intp l) Quick, inline access to the element at the given coordinates in the ndarray, *obj*, which must have respectively 1, 2, 3, or 4 dimensions (this is not checked). The corresponding *i*, *j*, *k*, and *l* coordinates can be any integer but will be interpreted as ``npy_intp``. You may want to typecast the returned pointer to the data type of the ndarray. Creating arrays --------------- From scratch ^^^^^^^^^^^^ .. cfunction:: PyObject* PyArray_NewFromDescr(PyTypeObject* subtype, PyArray_Descr* descr, int nd, npy_intp* dims, npy_intp* strides, void* data, int flags, PyObject* obj) This function steals a reference to *descr* if it is not NULL. This is the main array creation function. Most new arrays are created with this flexible function. The returned object is an object of Python-type *subtype*, which must be a subtype of :cdata:`PyArray_Type`. The array has *nd* dimensions, described by *dims*. The data-type descriptor of the new array is *descr*. If *subtype* is of an array subclass instead of the base :cdata:`&PyArray_Type`, then *obj* is the object to pass to the :obj:`__array_finalize__` method of the subclass. If *data* is ``NULL``, then new memory will be allocated and *flags* can be non-zero to indicate a Fortran-style contiguous array. If *data* is not ``NULL``, then it is assumed to point to the memory to be used for the array and the *flags* argument is used as the new flags for the array (except the state of :cdata:`NPY_OWNDATA` and :cdata:`NPY_ARRAY_UPDATEIFCOPY` flags of the new array will be reset). In addition, if *data* is non-NULL, then *strides* can also be provided. If *strides* is ``NULL``, then the array strides are computed as C-style contiguous (default) or Fortran-style contiguous (*flags* is nonzero for *data* = ``NULL`` or *flags* & :cdata:`NPY_ARRAY_F_CONTIGUOUS` is nonzero non-NULL *data*). Any provided *dims* and *strides* are copied into newly allocated dimension and strides arrays for the new array object. .. cfunction:: PyObject* PyArray_NewLikeArray(PyArrayObject* prototype, NPY_ORDER order, PyArray_Descr* descr, int subok) .. versionadded:: 1.6 This function steals a reference to *descr* if it is not NULL. This array creation routine allows for the convenient creation of a new array matching an existing array's shapes and memory layout, possibly changing the layout and/or data type. When *order* is :cdata:`NPY_ANYORDER`, the result order is :cdata:`NPY_FORTRANORDER` if *prototype* is a fortran array, :cdata:`NPY_CORDER` otherwise. When *order* is :cdata:`NPY_KEEPORDER`, the result order matches that of *prototype*, even when the axes of *prototype* aren't in C or Fortran order. If *descr* is NULL, the data type of *prototype* is used. If *subok* is 1, the newly created array will use the sub-type of *prototype* to create the new array, otherwise it will create a base-class array. .. cfunction:: PyObject* PyArray_New(PyTypeObject* subtype, int nd, npy_intp* dims, int type_num, npy_intp* strides, void* data, int itemsize, int flags, PyObject* obj) This is similar to :cfunc:`PyArray_DescrNew` (...) except you specify the data-type descriptor with *type_num* and *itemsize*, where *type_num* corresponds to a builtin (or user-defined) type. If the type always has the same number of bytes, then itemsize is ignored. Otherwise, itemsize specifies the particular size of this array. .. warning:: If data is passed to :cfunc:`PyArray_NewFromDescr` or :cfunc:`PyArray_New`, this memory must not be deallocated until the new array is deleted. If this data came from another Python object, this can be accomplished using :cfunc:`Py_INCREF` on that object and setting the base member of the new array to point to that object. If strides are passed in they must be consistent with the dimensions, the itemsize, and the data of the array. .. cfunction:: PyObject* PyArray_SimpleNew(int nd, npy_intp* dims, int typenum) Create a new unitialized array of type, *typenum*, whose size in each of *nd* dimensions is given by the integer array, *dims*. This function cannot be used to create a flexible-type array (no itemsize given). .. cfunction:: PyObject* PyArray_SimpleNewFromData(int nd, npy_intp* dims, int typenum, void* data) Create an array wrapper around *data* pointed to by the given pointer. The array flags will have a default that the data area is well-behaved and C-style contiguous. The shape of the array is given by the *dims* c-array of length *nd*. The data-type of the array is indicated by *typenum*. .. cfunction:: PyObject* PyArray_SimpleNewFromDescr(int nd, npy_intp* dims, PyArray_Descr* descr) This function steals a reference to *descr* if it is not NULL. Create a new array with the provided data-type descriptor, *descr* , of the shape deteremined by *nd* and *dims*. .. cfunction:: PyArray_FILLWBYTE(PyObject* obj, int val) Fill the array pointed to by *obj* ---which must be a (subclass of) bigndarray---with the contents of *val* (evaluated as a byte). This macro calls memset, so obj must be contiguous. .. cfunction:: PyObject* PyArray_Zeros(int nd, npy_intp* dims, PyArray_Descr* dtype, int fortran) Construct a new *nd* -dimensional array with shape given by *dims* and data type given by *dtype*. If *fortran* is non-zero, then a Fortran-order array is created, otherwise a C-order array is created. Fill the memory with zeros (or the 0 object if *dtype* corresponds to :ctype:`NPY_OBJECT` ). .. cfunction:: PyObject* PyArray_ZEROS(int nd, npy_intp* dims, int type_num, int fortran) Macro form of :cfunc:`PyArray_Zeros` which takes a type-number instead of a data-type object. .. cfunction:: PyObject* PyArray_Empty(int nd, npy_intp* dims, PyArray_Descr* dtype, int fortran) Construct a new *nd* -dimensional array with shape given by *dims* and data type given by *dtype*. If *fortran* is non-zero, then a Fortran-order array is created, otherwise a C-order array is created. The array is uninitialized unless the data type corresponds to :ctype:`NPY_OBJECT` in which case the array is filled with :cdata:`Py_None`. .. cfunction:: PyObject* PyArray_EMPTY(int nd, npy_intp* dims, int typenum, int fortran) Macro form of :cfunc:`PyArray_Empty` which takes a type-number, *typenum*, instead of a data-type object. .. cfunction:: PyObject* PyArray_Arange(double start, double stop, double step, int typenum) Construct a new 1-dimensional array of data-type, *typenum*, that ranges from *start* to *stop* (exclusive) in increments of *step* . Equivalent to **arange** (*start*, *stop*, *step*, dtype). .. cfunction:: PyObject* PyArray_ArangeObj(PyObject* start, PyObject* stop, PyObject* step, PyArray_Descr* descr) Construct a new 1-dimensional array of data-type determined by ``descr``, that ranges from ``start`` to ``stop`` (exclusive) in increments of ``step``. Equivalent to arange( ``start``, ``stop``, ``step``, ``typenum`` ). .. cfunction:: int PyArray_SetBaseObject(PyArrayObject* arr, PyObject* obj) .. versionadded:: 1.7 This function **steals a reference** to ``obj`` and sets it as the base property of ``arr``. If you construct an array by passing in your own memory buffer as a parameter, you need to set the array's `base` property to ensure the lifetime of the memory buffer is appropriate. The return value is 0 on success, -1 on failure. If the object provided is an array, this function traverses the chain of `base` pointers so that each array points to the owner of the memory directly. Once the base is set, it may not be changed to another value. From other objects ^^^^^^^^^^^^^^^^^^ .. cfunction:: PyObject* PyArray_FromAny(PyObject* op, PyArray_Descr* dtype, int min_depth, int max_depth, int requirements, PyObject* context) This is the main function used to obtain an array from any nested sequence, or object that exposes the array interface, *op*. The parameters allow specification of the required *dtype*, the minimum (*min_depth*) and maximum (*max_depth*) number of dimensions acceptable, and other *requirements* for the array. The *dtype* argument needs to be a :ctype:`PyArray_Descr` structure indicating the desired data-type (including required byteorder). The *dtype* argument may be NULL, indicating that any data-type (and byteorder) is acceptable. Unless ``FORCECAST`` is present in ``flags``, this call will generate an error if the data type cannot be safely obtained from the object. If you want to use ``NULL`` for the *dtype* and ensure the array is notswapped then use :cfunc:`PyArray_CheckFromAny`. A value of 0 for either of the depth parameters causes the parameter to be ignored. Any of the following array flags can be added (*e.g.* using \|) to get the *requirements* argument. If your code can handle general (*e.g.* strided, byte-swapped, or unaligned arrays) then *requirements* may be 0. Also, if *op* is not already an array (or does not expose the array interface), then a new array will be created (and filled from *op* using the sequence protocol). The new array will have :cdata:`NPY_DEFAULT` as its flags member. The *context* argument is passed to the :obj:`__array__` method of *op* and is only used if the array is constructed that way. Almost always this parameter is ``NULL``. In versions 1.6 and earlier of NumPy, the following flags did not have the _ARRAY_ macro namespace in them. That form of the constant names is deprecated in 1.7. .. cvar:: NPY_ARRAY_C_CONTIGUOUS Make sure the returned array is C-style contiguous .. cvar:: NPY_ARRAY_F_CONTIGUOUS Make sure the returned array is Fortran-style contiguous. .. cvar:: NPY_ARRAY_ALIGNED Make sure the returned array is aligned on proper boundaries for its data type. An aligned array has the data pointer and every strides factor as a multiple of the alignment factor for the data-type- descriptor. .. cvar:: NPY_ARRAY_WRITEABLE Make sure the returned array can be written to. .. cvar:: NPY_ARRAY_ENSURECOPY Make sure a copy is made of *op*. If this flag is not present, data is not copied if it can be avoided. .. cvar:: NPY_ARRAY_ENSUREARRAY Make sure the result is a base-class ndarray or bigndarray. By default, if *op* is an instance of a subclass of the bigndarray, an instance of that same subclass is returned. If this flag is set, an ndarray object will be returned instead. .. cvar:: NPY_ARRAY_FORCECAST Force a cast to the output type even if it cannot be done safely. Without this flag, a data cast will occur only if it can be done safely, otherwise an error is reaised. .. cvar:: NPY_ARRAY_UPDATEIFCOPY If *op* is already an array, but does not satisfy the requirements, then a copy is made (which will satisfy the requirements). If this flag is present and a copy (of an object that is already an array) must be made, then the corresponding :cdata:`NPY_ARRAY_UPDATEIFCOPY` flag is set in the returned copy and *op* is made to be read-only. When the returned copy is deleted (presumably after your calculations are complete), its contents will be copied back into *op* and the *op* array will be made writeable again. If *op* is not writeable to begin with, then an error is raised. If *op* is not already an array, then this flag has no effect. .. cvar:: NPY_ARRAY_BEHAVED :cdata:`NPY_ARRAY_ALIGNED` \| :cdata:`NPY_ARRAY_WRITEABLE` .. cvar:: NPY_ARRAY_CARRAY :cdata:`NPY_ARRAY_C_CONTIGUOUS` \| :cdata:`NPY_ARRAY_BEHAVED` .. cvar:: NPY_ARRAY_CARRAY_RO :cdata:`NPY_ARRAY_C_CONTIGUOUS` \| :cdata:`NPY_ARRAY_ALIGNED` .. cvar:: NPY_ARRAY_FARRAY :cdata:`NPY_ARRAY_F_CONTIGUOUS` \| :cdata:`NPY_ARRAY_BEHAVED` .. cvar:: NPY_ARRAY_FARRAY_RO :cdata:`NPY_ARRAY_F_CONTIGUOUS` \| :cdata:`NPY_ARRAY_ALIGNED` .. cvar:: NPY_ARRAY_DEFAULT :cdata:`NPY_ARRAY_CARRAY` .. cvar:: NPY_ARRAY_IN_ARRAY :cdata:`NPY_ARRAY_CONTIGUOUS` \| :cdata:`NPY_ARRAY_ALIGNED` .. cvar:: NPY_ARRAY_IN_FARRAY :cdata:`NPY_ARRAY_F_CONTIGUOUS` \| :cdata:`NPY_ARRAY_ALIGNED` .. cvar:: NPY_OUT_ARRAY :cdata:`NPY_ARRAY_C_CONTIGUOUS` \| :cdata:`NPY_ARRAY_WRITEABLE` \| :cdata:`NPY_ARRAY_ALIGNED` .. cvar:: NPY_ARRAY_OUT_FARRAY :cdata:`NPY_ARRAY_F_CONTIGUOUS` \| :cdata:`NPY_ARRAY_WRITEABLE` \| :cdata:`NPY_ARRAY_ALIGNED` .. cvar:: NPY_ARRAY_INOUT_ARRAY :cdata:`NPY_ARRAY_C_CONTIGUOUS` \| :cdata:`NPY_ARRAY_WRITEABLE` \| :cdata:`NPY_ARRAY_ALIGNED` \| :cdata:`NPY_ARRAY_UPDATEIFCOPY` .. cvar:: NPY_ARRAY_INOUT_FARRAY :cdata:`NPY_ARRAY_F_CONTIGUOUS` \| :cdata:`NPY_ARRAY_WRITEABLE` \| :cdata:`NPY_ARRAY_ALIGNED` \| :cdata:`NPY_ARRAY_UPDATEIFCOPY` .. cfunction:: int PyArray_GetArrayParamsFromObject(PyObject* op, PyArray_Descr* requested_dtype, npy_bool writeable, PyArray_Descr** out_dtype, int* out_ndim, npy_intp* out_dims, PyArrayObject** out_arr, PyObject* context) .. versionadded:: 1.6 Retrieves the array parameters for viewing/converting an arbitrary PyObject* to a NumPy array. This allows the "innate type and shape" of Python list-of-lists to be discovered without actually converting to an array. PyArray_FromAny calls this function to analyze its input. In some cases, such as structured arrays and the __array__ interface, a data type needs to be used to make sense of the object. When this is needed, provide a Descr for 'requested_dtype', otherwise provide NULL. This reference is not stolen. Also, if the requested dtype doesn't modify the interpretation of the input, out_dtype will still get the "innate" dtype of the object, not the dtype passed in 'requested_dtype'. If writing to the value in 'op' is desired, set the boolean 'writeable' to 1. This raises an error when 'op' is a scalar, list of lists, or other non-writeable 'op'. This differs from passing NPY_ARRAY_WRITEABLE to PyArray_FromAny, where the writeable array may be a copy of the input. When success (0 return value) is returned, either out_arr is filled with a non-NULL PyArrayObject and the rest of the parameters are untouched, or out_arr is filled with NULL, and the rest of the parameters are filled. Typical usage: .. code-block:: c PyArrayObject *arr = NULL; PyArray_Descr *dtype = NULL; int ndim = 0; npy_intp dims[NPY_MAXDIMS]; if (PyArray_GetArrayParamsFromObject(op, NULL, 1, &dtype, &ndim, &dims, &arr, NULL) < 0) { return NULL; } if (arr == NULL) { ... validate/change dtype, validate flags, ndim, etc ... // Could make custom strides here too arr = PyArray_NewFromDescr(&PyArray_Type, dtype, ndim, dims, NULL, fortran ? NPY_ARRAY_F_CONTIGUOUS : 0, NULL); if (arr == NULL) { return NULL; } if (PyArray_CopyObject(arr, op) < 0) { Py_DECREF(arr); return NULL; } } else { ... in this case the other parameters weren't filled, just validate and possibly copy arr itself ... } ... use arr ... .. cfunction:: PyObject* PyArray_CheckFromAny(PyObject* op, PyArray_Descr* dtype, int min_depth, int max_depth, int requirements, PyObject* context) Nearly identical to :cfunc:`PyArray_FromAny` (...) except *requirements* can contain :cdata:`NPY_ARRAY_NOTSWAPPED` (over-riding the specification in *dtype*) and :cdata:`NPY_ARRAY_ELEMENTSTRIDES` which indicates that the array should be aligned in the sense that the strides are multiples of the element size. In versions 1.6 and earlier of NumPy, the following flags did not have the _ARRAY_ macro namespace in them. That form of the constant names is deprecated in 1.7. .. cvar:: NPY_ARRAY_NOTSWAPPED Make sure the returned array has a data-type descriptor that is in machine byte-order, over-riding any specification in the *dtype* argument. Normally, the byte-order requirement is determined by the *dtype* argument. If this flag is set and the dtype argument does not indicate a machine byte-order descriptor (or is NULL and the object is already an array with a data-type descriptor that is not in machine byte- order), then a new data-type descriptor is created and used with its byte-order field set to native. .. cvar:: NPY_ARRAY_BEHAVED_NS :cdata:`NPY_ARRAY_ALIGNED` \| :cdata:`NPY_ARRAY_WRITEABLE` \| :cdata:`NPY_ARRAY_NOTSWAPPED` .. cvar:: NPY_ARRAY_ELEMENTSTRIDES Make sure the returned array has strides that are multiples of the element size. .. cfunction:: PyObject* PyArray_FromArray(PyArrayObject* op, PyArray_Descr* newtype, int requirements) Special case of :cfunc:`PyArray_FromAny` for when *op* is already an array but it needs to be of a specific *newtype* (including byte-order) or has certain *requirements*. .. cfunction:: PyObject* PyArray_FromStructInterface(PyObject* op) Returns an ndarray object from a Python object that exposes the :obj:`__array_struct__`` method and follows the array interface protocol. If the object does not contain this method then a borrowed reference to :cdata:`Py_NotImplemented` is returned. .. cfunction:: PyObject* PyArray_FromInterface(PyObject* op) Returns an ndarray object from a Python object that exposes the :obj:`__array_shape__` and :obj:`__array_typestr__` methods following the array interface protocol. If the object does not contain one of these method then a borrowed reference to :cdata:`Py_NotImplemented` is returned. .. cfunction:: PyObject* PyArray_FromArrayAttr(PyObject* op, PyArray_Descr* dtype, PyObject* context) Return an ndarray object from a Python object that exposes the :obj:`__array__` method. The :obj:`__array__` method can take 0, 1, or 2 arguments ([dtype, context]) where *context* is used to pass information about where the :obj:`__array__` method is being called from (currently only used in ufuncs). .. cfunction:: PyObject* PyArray_ContiguousFromAny(PyObject* op, int typenum, int min_depth, int max_depth) This function returns a (C-style) contiguous and behaved function array from any nested sequence or array interface exporting object, *op*, of (non-flexible) type given by the enumerated *typenum*, of minimum depth *min_depth*, and of maximum depth *max_depth*. Equivalent to a call to :cfunc:`PyArray_FromAny` with requirements set to :cdata:`NPY_DEFAULT` and the type_num member of the type argument set to *typenum*. .. cfunction:: PyObject *PyArray_FromObject(PyObject *op, int typenum, int min_depth, int max_depth) Return an aligned and in native-byteorder array from any nested sequence or array-interface exporting object, op, of a type given by the enumerated typenum. The minimum number of dimensions the array can have is given by min_depth while the maximum is max_depth. This is equivalent to a call to :cfunc:`PyArray_FromAny` with requirements set to BEHAVED. .. cfunction:: PyObject* PyArray_EnsureArray(PyObject* op) This function **steals a reference** to ``op`` and makes sure that ``op`` is a base-class ndarray. It special cases array scalars, but otherwise calls :cfunc:`PyArray_FromAny` ( ``op``, NULL, 0, 0, :cdata:`NPY_ARRAY_ENSUREARRAY`). .. cfunction:: PyObject* PyArray_FromString(char* string, npy_intp slen, PyArray_Descr* dtype, npy_intp num, char* sep) Construct a one-dimensional ndarray of a single type from a binary or (ASCII) text ``string`` of length ``slen``. The data-type of the array to-be-created is given by ``dtype``. If num is -1, then **copy** the entire string and return an appropriately sized array, otherwise, ``num`` is the number of items to **copy** from the string. If ``sep`` is NULL (or ""), then interpret the string as bytes of binary data, otherwise convert the sub-strings separated by ``sep`` to items of data-type ``dtype``. Some data-types may not be readable in text mode and an error will be raised if that occurs. All errors return NULL. .. cfunction:: PyObject* PyArray_FromFile(FILE* fp, PyArray_Descr* dtype, npy_intp num, char* sep) Construct a one-dimensional ndarray of a single type from a binary or text file. The open file pointer is ``fp``, the data-type of the array to be created is given by ``dtype``. This must match the data in the file. If ``num`` is -1, then read until the end of the file and return an appropriately sized array, otherwise, ``num`` is the number of items to read. If ``sep`` is NULL (or ""), then read from the file in binary mode, otherwise read from the file in text mode with ``sep`` providing the item separator. Some array types cannot be read in text mode in which case an error is raised. .. cfunction:: PyObject* PyArray_FromBuffer(PyObject* buf, PyArray_Descr* dtype, npy_intp count, npy_intp offset) Construct a one-dimensional ndarray of a single type from an object, ``buf``, that exports the (single-segment) buffer protocol (or has an attribute __buffer\__ that returns an object that exports the buffer protocol). A writeable buffer will be tried first followed by a read- only buffer. The :cdata:`NPY_ARRAY_WRITEABLE` flag of the returned array will reflect which one was successful. The data is assumed to start at ``offset`` bytes from the start of the memory location for the object. The type of the data in the buffer will be interpreted depending on the data- type descriptor, ``dtype.`` If ``count`` is negative then it will be determined from the size of the buffer and the requested itemsize, otherwise, ``count`` represents how many elements should be converted from the buffer. .. cfunction:: int PyArray_CopyInto(PyArrayObject* dest, PyArrayObject* src) Copy from the source array, ``src``, into the destination array, ``dest``, performing a data-type conversion if necessary. If an error occurs return -1 (otherwise 0). The shape of ``src`` must be broadcastable to the shape of ``dest``. The data areas of dest and src must not overlap. .. cfunction:: int PyArray_MoveInto(PyArrayObject* dest, PyArrayObject* src) Move data from the source array, ``src``, into the destination array, ``dest``, performing a data-type conversion if necessary. If an error occurs return -1 (otherwise 0). The shape of ``src`` must be broadcastable to the shape of ``dest``. The data areas of dest and src may overlap. .. cfunction:: PyArrayObject* PyArray_GETCONTIGUOUS(PyObject* op) If ``op`` is already (C-style) contiguous and well-behaved then just return a reference, otherwise return a (contiguous and well-behaved) copy of the array. The parameter op must be a (sub-class of an) ndarray and no checking for that is done. .. cfunction:: PyObject* PyArray_FROM_O(PyObject* obj) Convert ``obj`` to an ndarray. The argument can be any nested sequence or object that exports the array interface. This is a macro form of :cfunc:`PyArray_FromAny` using ``NULL``, 0, 0, 0 for the other arguments. Your code must be able to handle any data-type descriptor and any combination of data-flags to use this macro. .. cfunction:: PyObject* PyArray_FROM_OF(PyObject* obj, int requirements) Similar to :cfunc:`PyArray_FROM_O` except it can take an argument of *requirements* indicating properties the resulting array must have. Available requirements that can be enforced are :cdata:`NPY_ARRAY_C_CONTIGUOUS`, :cdata:`NPY_ARRAY_F_CONTIGUOUS`, :cdata:`NPY_ARRAY_ALIGNED`, :cdata:`NPY_ARRAY_WRITEABLE`, :cdata:`NPY_ARRAY_NOTSWAPPED`, :cdata:`NPY_ARRAY_ENSURECOPY`, :cdata:`NPY_ARRAY_UPDATEIFCOPY`, :cdata:`NPY_ARRAY_FORCECAST`, and :cdata:`NPY_ARRAY_ENSUREARRAY`. Standard combinations of flags can also be used: .. cfunction:: PyObject* PyArray_FROM_OT(PyObject* obj, int typenum) Similar to :cfunc:`PyArray_FROM_O` except it can take an argument of *typenum* specifying the type-number the returned array. .. cfunction:: PyObject* PyArray_FROM_OTF(PyObject* obj, int typenum, int requirements) Combination of :cfunc:`PyArray_FROM_OF` and :cfunc:`PyArray_FROM_OT` allowing both a *typenum* and a *flags* argument to be provided.. .. cfunction:: PyObject* PyArray_FROMANY(PyObject* obj, int typenum, int min, int max, int requirements) Similar to :cfunc:`PyArray_FromAny` except the data-type is specified using a typenumber. :cfunc:`PyArray_DescrFromType` (*typenum*) is passed directly to :cfunc:`PyArray_FromAny`. This macro also adds :cdata:`NPY_DEFAULT` to requirements if :cdata:`NPY_ARRAY_ENSURECOPY` is passed in as requirements. .. cfunction:: PyObject *PyArray_CheckAxis(PyObject* obj, int* axis, int requirements) Encapsulate the functionality of functions and methods that take the axis= keyword and work properly with None as the axis argument. The input array is ``obj``, while ``*axis`` is a converted integer (so that >=MAXDIMS is the None value), and ``requirements`` gives the needed properties of ``obj``. The output is a converted version of the input so that requirements are met and if needed a flattening has occurred. On output negative values of ``*axis`` are converted and the new value is checked to ensure consistency with the shape of ``obj``. Dealing with types ------------------ General check of Python Type ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ .. cfunction:: PyArray_Check(op) Evaluates true if *op* is a Python object whose type is a sub-type of :cdata:`PyArray_Type`. .. cfunction:: PyArray_CheckExact(op) Evaluates true if *op* is a Python object with type :cdata:`PyArray_Type`. .. cfunction:: PyArray_HasArrayInterface(op, out) If ``op`` implements any part of the array interface, then ``out`` will contain a new reference to the newly created ndarray using the interface or ``out`` will contain ``NULL`` if an error during conversion occurs. Otherwise, out will contain a borrowed reference to :cdata:`Py_NotImplemented` and no error condition is set. .. cfunction:: PyArray_HasArrayInterfaceType(op, type, context, out) If ``op`` implements any part of the array interface, then ``out`` will contain a new reference to the newly created ndarray using the interface or ``out`` will contain ``NULL`` if an error during conversion occurs. Otherwise, out will contain a borrowed reference to Py_NotImplemented and no error condition is set. This version allows setting of the type and context in the part of the array interface that looks for the :obj:`__array__` attribute. .. cfunction:: PyArray_IsZeroDim(op) Evaluates true if *op* is an instance of (a subclass of) :cdata:`PyArray_Type` and has 0 dimensions. .. cfunction:: PyArray_IsScalar(op, cls) Evaluates true if *op* is an instance of :cdata:`Py{cls}ArrType_Type`. .. cfunction:: PyArray_CheckScalar(op) Evaluates true if *op* is either an array scalar (an instance of a sub-type of :cdata:`PyGenericArr_Type` ), or an instance of (a sub-class of) :cdata:`PyArray_Type` whose dimensionality is 0. .. cfunction:: PyArray_IsPythonScalar(op) Evaluates true if *op* is a builtin Python "scalar" object (int, float, complex, str, unicode, long, bool). .. cfunction:: PyArray_IsAnyScalar(op) Evaluates true if *op* is either a Python scalar or an array scalar (an instance of a sub- type of :cdata:`PyGenericArr_Type` ). Data-type checking ^^^^^^^^^^^^^^^^^^ For the typenum macros, the argument is an integer representing an enumerated array data type. For the array type checking macros the argument must be a :ctype:`PyObject *` that can be directly interpreted as a :ctype:`PyArrayObject *`. .. cfunction:: PyTypeNum_ISUNSIGNED(num) .. cfunction:: PyDataType_ISUNSIGNED(descr) .. cfunction:: PyArray_ISUNSIGNED(obj) Type represents an unsigned integer. .. cfunction:: PyTypeNum_ISSIGNED(num) .. cfunction:: PyDataType_ISSIGNED(descr) .. cfunction:: PyArray_ISSIGNED(obj) Type represents a signed integer. .. cfunction:: PyTypeNum_ISINTEGER(num) .. cfunction:: PyDataType_ISINTEGER(descr) .. cfunction:: PyArray_ISINTEGER(obj) Type represents any integer. .. cfunction:: PyTypeNum_ISFLOAT(num) .. cfunction:: PyDataType_ISFLOAT(descr) .. cfunction:: PyArray_ISFLOAT(obj) Type represents any floating point number. .. cfunction:: PyTypeNum_ISCOMPLEX(num) .. cfunction:: PyDataType_ISCOMPLEX(descr) .. cfunction:: PyArray_ISCOMPLEX(obj) Type represents any complex floating point number. .. cfunction:: PyTypeNum_ISNUMBER(num) .. cfunction:: PyDataType_ISNUMBER(descr) .. cfunction:: PyArray_ISNUMBER(obj) Type represents any integer, floating point, or complex floating point number. .. cfunction:: PyTypeNum_ISSTRING(num) .. cfunction:: PyDataType_ISSTRING(descr) .. cfunction:: PyArray_ISSTRING(obj) Type represents a string data type. .. cfunction:: PyTypeNum_ISPYTHON(num) .. cfunction:: PyDataType_ISPYTHON(descr) .. cfunction:: PyArray_ISPYTHON(obj) Type represents an enumerated type corresponding to one of the standard Python scalar (bool, int, float, or complex). .. cfunction:: PyTypeNum_ISFLEXIBLE(num) .. cfunction:: PyDataType_ISFLEXIBLE(descr) .. cfunction:: PyArray_ISFLEXIBLE(obj) Type represents one of the flexible array types ( :cdata:`NPY_STRING`, :cdata:`NPY_UNICODE`, or :cdata:`NPY_VOID` ). .. cfunction:: PyTypeNum_ISUSERDEF(num) .. cfunction:: PyDataType_ISUSERDEF(descr) .. cfunction:: PyArray_ISUSERDEF(obj) Type represents a user-defined type. .. cfunction:: PyTypeNum_ISEXTENDED(num) .. cfunction:: PyDataType_ISEXTENDED(descr) .. cfunction:: PyArray_ISEXTENDED(obj) Type is either flexible or user-defined. .. cfunction:: PyTypeNum_ISOBJECT(num) .. cfunction:: PyDataType_ISOBJECT(descr) .. cfunction:: PyArray_ISOBJECT(obj) Type represents object data type. .. cfunction:: PyTypeNum_ISBOOL(num) .. cfunction:: PyDataType_ISBOOL(descr) .. cfunction:: PyArray_ISBOOL(obj) Type represents Boolean data type. .. cfunction:: PyDataType_HASFIELDS(descr) .. cfunction:: PyArray_HASFIELDS(obj) Type has fields associated with it. .. cfunction:: PyArray_ISNOTSWAPPED(m) Evaluates true if the data area of the ndarray *m* is in machine byte-order according to the array's data-type descriptor. .. cfunction:: PyArray_ISBYTESWAPPED(m) Evaluates true if the data area of the ndarray *m* is **not** in machine byte-order according to the array's data-type descriptor. .. cfunction:: Bool PyArray_EquivTypes(PyArray_Descr* type1, PyArray_Descr* type2) Return :cdata:`NPY_TRUE` if *type1* and *type2* actually represent equivalent types for this platform (the fortran member of each type is ignored). For example, on 32-bit platforms, :cdata:`NPY_LONG` and :cdata:`NPY_INT` are equivalent. Otherwise return :cdata:`NPY_FALSE`. .. cfunction:: Bool PyArray_EquivArrTypes(PyArrayObject* a1, PyArrayObject * a2) Return :cdata:`NPY_TRUE` if *a1* and *a2* are arrays with equivalent types for this platform. .. cfunction:: Bool PyArray_EquivTypenums(int typenum1, int typenum2) Special case of :cfunc:`PyArray_EquivTypes` (...) that does not accept flexible data types but may be easier to call. .. cfunction:: int PyArray_EquivByteorders({byteorder} b1, {byteorder} b2) True if byteorder characters ( :cdata:`NPY_LITTLE`, :cdata:`NPY_BIG`, :cdata:`NPY_NATIVE`, :cdata:`NPY_IGNORE` ) are either equal or equivalent as to their specification of a native byte order. Thus, on a little-endian machine :cdata:`NPY_LITTLE` and :cdata:`NPY_NATIVE` are equivalent where they are not equivalent on a big-endian machine. Converting data types ^^^^^^^^^^^^^^^^^^^^^ .. cfunction:: PyObject* PyArray_Cast(PyArrayObject* arr, int typenum) Mainly for backwards compatibility to the Numeric C-API and for simple casts to non-flexible types. Return a new array object with the elements of *arr* cast to the data-type *typenum* which must be one of the enumerated types and not a flexible type. .. cfunction:: PyObject* PyArray_CastToType(PyArrayObject* arr, PyArray_Descr* type, int fortran) Return a new array of the *type* specified, casting the elements of *arr* as appropriate. The fortran argument specifies the ordering of the output array. .. cfunction:: int PyArray_CastTo(PyArrayObject* out, PyArrayObject* in) As of 1.6, this function simply calls :cfunc:`PyArray_CopyInto`, which handles the casting. Cast the elements of the array *in* into the array *out*. The output array should be writeable, have an integer-multiple of the number of elements in the input array (more than one copy can be placed in out), and have a data type that is one of the builtin types. Returns 0 on success and -1 if an error occurs. .. cfunction:: PyArray_VectorUnaryFunc* PyArray_GetCastFunc(PyArray_Descr* from, int totype) Return the low-level casting function to cast from the given descriptor to the builtin type number. If no casting function exists return ``NULL`` and set an error. Using this function instead of direct access to *from* ->f->cast will allow support of any user-defined casting functions added to a descriptors casting dictionary. .. cfunction:: int PyArray_CanCastSafely(int fromtype, int totype) Returns non-zero if an array of data type *fromtype* can be cast to an array of data type *totype* without losing information. An exception is that 64-bit integers are allowed to be cast to 64-bit floating point values even though this can lose precision on large integers so as not to proliferate the use of long doubles without explict requests. Flexible array types are not checked according to their lengths with this function. .. cfunction:: int PyArray_CanCastTo(PyArray_Descr* fromtype, PyArray_Descr* totype) :cfunc:`PyArray_CanCastTypeTo` supercedes this function in NumPy 1.6 and later. Equivalent to PyArray_CanCastTypeTo(fromtype, totype, NPY_SAFE_CASTING). .. cfunction:: int PyArray_CanCastTypeTo(PyArray_Descr* fromtype, PyArray_Descr* totype, NPY_CASTING casting) .. versionadded:: 1.6 Returns non-zero if an array of data type *fromtype* (which can include flexible types) can be cast safely to an array of data type *totype* (which can include flexible types) according to the casting rule *casting*. For simple types with :cdata:`NPY_SAFE_CASTING`, this is basically a wrapper around :cfunc:`PyArray_CanCastSafely`, but for flexible types such as strings or unicode, it produces results taking into account their sizes. .. cfunction:: int PyArray_CanCastArrayTo(PyArrayObject* arr, PyArray_Descr* totype, NPY_CASTING casting) .. versionadded:: 1.6 Returns non-zero if *arr* can be cast to *totype* according to the casting rule given in *casting*. If *arr* is an array scalar, its value is taken into account, and non-zero is also returned when the value will not overflow or be truncated to an integer when converting to a smaller type. This is almost the same as the result of PyArray_CanCastTypeTo(PyArray_MinScalarType(arr), totype, casting), but it also handles a special case arising because the set of uint values is not a subset of the int values for types with the same number of bits. .. cfunction:: PyArray_Descr* PyArray_MinScalarType(PyArrayObject* arr) .. versionadded:: 1.6 If *arr* is an array, returns its data type descriptor, but if *arr* is an array scalar (has 0 dimensions), it finds the data type of smallest size to which the value may be converted without overflow or truncation to an integer. This function will not demote complex to float or anything to boolean, but will demote a signed integer to an unsigned integer when the scalar value is positive. .. cfunction:: PyArray_Descr* PyArray_PromoteTypes(PyArray_Descr* type1, PyArray_Descr* type2) .. versionadded:: 1.6 Finds the data type of smallest size and kind to which *type1* and *type2* may be safely converted. This function is symmetric and associative. .. cfunction:: PyArray_Descr* PyArray_ResultType(npy_intp narrs, PyArrayObject**arrs, npy_intp ndtypes, PyArray_Descr**dtypes) .. versionadded:: 1.6 This applies type promotion to all the inputs, using the NumPy rules for combining scalars and arrays, to determine the output type of a set of operands. This is the same result type that ufuncs produce. The specific algorithm used is as follows. Categories are determined by first checking which of boolean, integer (int/uint), or floating point (float/complex) the maximum kind of all the arrays and the scalars are. If there are only scalars or the maximum category of the scalars is higher than the maximum category of the arrays, the data types are combined with :cfunc:`PyArray_PromoteTypes` to produce the return value. Otherwise, PyArray_MinScalarType is called on each array, and the resulting data types are all combined with :cfunc:`PyArray_PromoteTypes` to produce the return value. The set of int values is not a subset of the uint values for types with the same number of bits, something not reflected in :cfunc:`PyArray_MinScalarType`, but handled as a special case in PyArray_ResultType. .. cfunction:: int PyArray_ObjectType(PyObject* op, int mintype) This function is superceded by :cfunc:`PyArray_MinScalarType` and/or :cfunc:`PyArray_ResultType`. This function is useful for determining a common type that two or more arrays can be converted to. It only works for non-flexible array types as no itemsize information is passed. The *mintype* argument represents the minimum type acceptable, and *op* represents the object that will be converted to an array. The return value is the enumerated typenumber that represents the data-type that *op* should have. .. cfunction:: void PyArray_ArrayType(PyObject* op, PyArray_Descr* mintype, PyArray_Descr* outtype) This function is superceded by :cfunc:`PyArray_ResultType`. This function works similarly to :cfunc:`PyArray_ObjectType` (...) except it handles flexible arrays. The *mintype* argument can have an itemsize member and the *outtype* argument will have an itemsize member at least as big but perhaps bigger depending on the object *op*. .. cfunction:: PyArrayObject** PyArray_ConvertToCommonType(PyObject* op, int* n) The functionality this provides is largely superceded by iterator :ctype:`NpyIter` introduced in 1.6, with flag :cdata:`NPY_ITER_COMMON_DTYPE` or with the same dtype parameter for all operands. Convert a sequence of Python objects contained in *op* to an array of ndarrays each having the same data type. The type is selected based on the typenumber (larger type number is chosen over a smaller one) ignoring objects that are only scalars. The length of the sequence is returned in *n*, and an *n* -length array of :ctype:`PyArrayObject` pointers is the return value (or ``NULL`` if an error occurs). The returned array must be freed by the caller of this routine (using :cfunc:`PyDataMem_FREE` ) and all the array objects in it ``DECREF`` 'd or a memory-leak will occur. The example template-code below shows a typically usage: .. code-block:: c mps = PyArray_ConvertToCommonType(obj, &n); if (mps==NULL) return NULL; {code} for (i=0; iitemsize that holds the representation of 0 for that type. The returned pointer, *ret*, **must be freed** using :cfunc:`PyDataMem_FREE` (ret) when it is not needed anymore. .. cfunction:: char* PyArray_One(PyArrayObject* arr) A pointer to newly created memory of size *arr* ->itemsize that holds the representation of 1 for that type. The returned pointer, *ret*, **must be freed** using :cfunc:`PyDataMem_FREE` (ret) when it is not needed anymore. .. cfunction:: int PyArray_ValidType(int typenum) Returns :cdata:`NPY_TRUE` if *typenum* represents a valid type-number (builtin or user-defined or character code). Otherwise, this function returns :cdata:`NPY_FALSE`. New data types ^^^^^^^^^^^^^^ .. cfunction:: void PyArray_InitArrFuncs(PyArray_ArrFuncs* f) Initialize all function pointers and members to ``NULL``. .. cfunction:: int PyArray_RegisterDataType(PyArray_Descr* dtype) Register a data-type as a new user-defined data type for arrays. The type must have most of its entries filled in. This is not always checked and errors can produce segfaults. In particular, the typeobj member of the ``dtype`` structure must be filled with a Python type that has a fixed-size element-size that corresponds to the elsize member of *dtype*. Also the ``f`` member must have the required functions: nonzero, copyswap, copyswapn, getitem, setitem, and cast (some of the cast functions may be ``NULL`` if no support is desired). To avoid confusion, you should choose a unique character typecode but this is not enforced and not relied on internally. A user-defined type number is returned that uniquely identifies the type. A pointer to the new structure can then be obtained from :cfunc:`PyArray_DescrFromType` using the returned type number. A -1 is returned if an error occurs. If this *dtype* has already been registered (checked only by the address of the pointer), then return the previously-assigned type-number. .. cfunction:: int PyArray_RegisterCastFunc(PyArray_Descr* descr, int totype, PyArray_VectorUnaryFunc* castfunc) Register a low-level casting function, *castfunc*, to convert from the data-type, *descr*, to the given data-type number, *totype*. Any old casting function is over-written. A ``0`` is returned on success or a ``-1`` on failure. .. cfunction:: int PyArray_RegisterCanCast(PyArray_Descr* descr, int totype, NPY_SCALARKIND scalar) Register the data-type number, *totype*, as castable from data-type object, *descr*, of the given *scalar* kind. Use *scalar* = :cdata:`NPY_NOSCALAR` to register that an array of data-type *descr* can be cast safely to a data-type whose type_number is *totype*. Special functions for NPY_OBJECT ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ .. cfunction:: int PyArray_INCREF(PyArrayObject* op) Used for an array, *op*, that contains any Python objects. It increments the reference count of every object in the array according to the data-type of *op*. A -1 is returned if an error occurs, otherwise 0 is returned. .. cfunction:: void PyArray_Item_INCREF(char* ptr, PyArray_Descr* dtype) A function to INCREF all the objects at the location *ptr* according to the data-type *dtype*. If *ptr* is the start of a record with an object at any offset, then this will (recursively) increment the reference count of all object-like items in the record. .. cfunction:: int PyArray_XDECREF(PyArrayObject* op) Used for an array, *op*, that contains any Python objects. It decrements the reference count of every object in the array according to the data-type of *op*. Normal return value is 0. A -1 is returned if an error occurs. .. cfunction:: void PyArray_Item_XDECREF(char* ptr, PyArray_Descr* dtype) A function to XDECREF all the object-like items at the loacation *ptr* as recorded in the data-type, *dtype*. This works recursively so that if ``dtype`` itself has fields with data-types that contain object-like items, all the object-like fields will be XDECREF ``'d``. .. cfunction:: void PyArray_FillObjectArray(PyArrayObject* arr, PyObject* obj) Fill a newly created array with a single value obj at all locations in the structure with object data-types. No checking is performed but *arr* must be of data-type :ctype:`NPY_OBJECT` and be single-segment and uninitialized (no previous objects in position). Use :cfunc:`PyArray_DECREF` (*arr*) if you need to decrement all the items in the object array prior to calling this function. Array flags ----------- The ``flags`` attribute of the ``PyArrayObject`` structure contains important information about the memory used by the array (pointed to by the data member) This flag information must be kept accurate or strange results and even segfaults may result. There are 6 (binary) flags that describe the memory area used by the data buffer. These constants are defined in ``arrayobject.h`` and determine the bit-position of the flag. Python exposes a nice attribute- based interface as well as a dictionary-like interface for getting (and, if appropriate, setting) these flags. Memory areas of all kinds can be pointed to by an ndarray, necessitating these flags. If you get an arbitrary ``PyArrayObject`` in C-code, you need to be aware of the flags that are set. If you need to guarantee a certain kind of array (like :cdata:`NPY_ARRAY_C_CONTIGUOUS` and :cdata:`NPY_ARRAY_BEHAVED`), then pass these requirements into the PyArray_FromAny function. Basic Array Flags ^^^^^^^^^^^^^^^^^ An ndarray can have a data segment that is not a simple contiguous chunk of well-behaved memory you can manipulate. It may not be aligned with word boundaries (very important on some platforms). It might have its data in a different byte-order than the machine recognizes. It might not be writeable. It might be in Fortan-contiguous order. The array flags are used to indicate what can be said about data associated with an array. In versions 1.6 and earlier of NumPy, the following flags did not have the _ARRAY_ macro namespace in them. That form of the constant names is deprecated in 1.7. .. cvar:: NPY_ARRAY_C_CONTIGUOUS The data area is in C-style contiguous order (last index varies the fastest). .. cvar:: NPY_ARRAY_F_CONTIGUOUS The data area is in Fortran-style contiguous order (first index varies the fastest). .. note:: Arrays can be both C-style and Fortran-style contiguous simultaneously. This is clear for 1-dimensional arrays, but can also be true for higher dimensional arrays. Even for contiguous arrays a stride for a given dimension ``arr.strides[dim]`` may be *arbitrary* if ``arr.shape[dim] == 1`` or the array has no elements. It does *not* generally hold that ``self.strides[-1] == self.itemsize`` for C-style contiguous arrays or ``self.strides[0] == self.itemsize`` for Fortran-style contiguous arrays is true. The correct way to access the ``itemsize`` of an array from the C API is ``PyArray_ITEMSIZE(arr)``. .. seealso:: :ref:`Internal memory layout of an ndarray ` .. cvar:: NPY_ARRAY_OWNDATA The data area is owned by this array. .. cvar:: NPY_ARRAY_ALIGNED The data area and all array elements are aligned appropriately. .. cvar:: NPY_ARRAY_WRITEABLE The data area can be written to. Notice that the above 3 flags are are defined so that a new, well- behaved array has these flags defined as true. .. cvar:: NPY_ARRAY_UPDATEIFCOPY The data area represents a (well-behaved) copy whose information should be transferred back to the original when this array is deleted. This is a special flag that is set if this array represents a copy made because a user required certain flags in :cfunc:`PyArray_FromAny` and a copy had to be made of some other array (and the user asked for this flag to be set in such a situation). The base attribute then points to the "misbehaved" array (which is set read_only). When the array with this flag set is deallocated, it will copy its contents back to the "misbehaved" array (casting if necessary) and will reset the "misbehaved" array to :cdata:`NPY_ARRAY_WRITEABLE`. If the "misbehaved" array was not :cdata:`NPY_ARRAY_WRITEABLE` to begin with then :cfunc:`PyArray_FromAny` would have returned an error because :cdata:`NPY_ARRAY_UPDATEIFCOPY` would not have been possible. :cfunc:`PyArray_UpdateFlags` (obj, flags) will update the ``obj->flags`` for ``flags`` which can be any of :cdata:`NPY_ARRAY_C_CONTIGUOUS`, :cdata:`NPY_ARRAY_F_CONTIGUOUS`, :cdata:`NPY_ARRAY_ALIGNED`, or :cdata:`NPY_ARRAY_WRITEABLE`. Combinations of array flags ^^^^^^^^^^^^^^^^^^^^^^^^^^^ .. cvar:: NPY_ARRAY_BEHAVED :cdata:`NPY_ARRAY_ALIGNED` \| :cdata:`NPY_ARRAY_WRITEABLE` .. cvar:: NPY_ARRAY_CARRAY :cdata:`NPY_ARRAY_C_CONTIGUOUS` \| :cdata:`NPY_ARRAY_BEHAVED` .. cvar:: NPY_ARRAY_CARRAY_RO :cdata:`NPY_ARRAY_C_CONTIGUOUS` \| :cdata:`NPY_ARRAY_ALIGNED` .. cvar:: NPY_ARRAY_FARRAY :cdata:`NPY_ARRAY_F_CONTIGUOUS` \| :cdata:`NPY_ARRAY_BEHAVED` .. cvar:: NPY_ARRAY_FARRAY_RO :cdata:`NPY_ARRAY_F_CONTIGUOUS` \| :cdata:`NPY_ARRAY_ALIGNED` .. cvar:: NPY_ARRAY_DEFAULT :cdata:`NPY_ARRAY_CARRAY` .. cvar:: NPY_ARRAY_UPDATE_ALL :cdata:`NPY_ARRAY_C_CONTIGUOUS` \| :cdata:`NPY_ARRAY_F_CONTIGUOUS` \| :cdata:`NPY_ARRAY_ALIGNED` Flag-like constants ^^^^^^^^^^^^^^^^^^^ These constants are used in :cfunc:`PyArray_FromAny` (and its macro forms) to specify desired properties of the new array. .. cvar:: NPY_ARRAY_FORCECAST Cast to the desired type, even if it can't be done without losing information. .. cvar:: NPY_ARRAY_ENSURECOPY Make sure the resulting array is a copy of the original. .. cvar:: NPY_ARRAY_ENSUREARRAY Make sure the resulting object is an actual ndarray (or bigndarray), and not a sub-class. .. cvar:: NPY_ARRAY_NOTSWAPPED Only used in :cfunc:`PyArray_CheckFromAny` to over-ride the byteorder of the data-type object passed in. .. cvar:: NPY_ARRAY_BEHAVED_NS :cdata:`NPY_ARRAY_ALIGNED` \| :cdata:`NPY_ARRAY_WRITEABLE` \| :cdata:`NPY_ARRAY_NOTSWAPPED` Flag checking ^^^^^^^^^^^^^ For all of these macros *arr* must be an instance of a (subclass of) :cdata:`PyArray_Type`, but no checking is done. .. cfunction:: PyArray_CHKFLAGS(arr, flags) The first parameter, arr, must be an ndarray or subclass. The parameter, *flags*, should be an integer consisting of bitwise combinations of the possible flags an array can have: :cdata:`NPY_ARRAY_C_CONTIGUOUS`, :cdata:`NPY_ARRAY_F_CONTIGUOUS`, :cdata:`NPY_ARRAY_OWNDATA`, :cdata:`NPY_ARRAY_ALIGNED`, :cdata:`NPY_ARRAY_WRITEABLE`, :cdata:`NPY_ARRAY_UPDATEIFCOPY`. .. cfunction:: PyArray_IS_C_CONTIGUOUS(arr) Evaluates true if *arr* is C-style contiguous. .. cfunction:: PyArray_IS_F_CONTIGUOUS(arr) Evaluates true if *arr* is Fortran-style contiguous. .. cfunction:: PyArray_ISFORTRAN(arr) Evaluates true if *arr* is Fortran-style contiguous and *not* C-style contiguous. :cfunc:`PyArray_IS_F_CONTIGUOUS` is the correct way to test for Fortran-style contiguity. .. cfunction:: PyArray_ISWRITEABLE(arr) Evaluates true if the data area of *arr* can be written to .. cfunction:: PyArray_ISALIGNED(arr) Evaluates true if the data area of *arr* is properly aligned on the machine. .. cfunction:: PyArray_ISBEHAVED(arr) Evalutes true if the data area of *arr* is aligned and writeable and in machine byte-order according to its descriptor. .. cfunction:: PyArray_ISBEHAVED_RO(arr) Evaluates true if the data area of *arr* is aligned and in machine byte-order. .. cfunction:: PyArray_ISCARRAY(arr) Evaluates true if the data area of *arr* is C-style contiguous, and :cfunc:`PyArray_ISBEHAVED` (*arr*) is true. .. cfunction:: PyArray_ISFARRAY(arr) Evaluates true if the data area of *arr* is Fortran-style contiguous and :cfunc:`PyArray_ISBEHAVED` (*arr*) is true. .. cfunction:: PyArray_ISCARRAY_RO(arr) Evaluates true if the data area of *arr* is C-style contiguous, aligned, and in machine byte-order. .. cfunction:: PyArray_ISFARRAY_RO(arr) Evaluates true if the data area of *arr* is Fortran-style contiguous, aligned, and in machine byte-order **.** .. cfunction:: PyArray_ISONESEGMENT(arr) Evaluates true if the data area of *arr* consists of a single (C-style or Fortran-style) contiguous segment. .. cfunction:: void PyArray_UpdateFlags(PyArrayObject* arr, int flagmask) The :cdata:`NPY_ARRAY_C_CONTIGUOUS`, :cdata:`NPY_ARRAY_ALIGNED`, and :cdata:`NPY_ARRAY_F_CONTIGUOUS` array flags can be "calculated" from the array object itself. This routine updates one or more of these flags of *arr* as specified in *flagmask* by performing the required calculation. .. warning:: It is important to keep the flags updated (using :cfunc:`PyArray_UpdateFlags` can help) whenever a manipulation with an array is performed that might cause them to change. Later calculations in NumPy that rely on the state of these flags do not repeat the calculation to update them. Array method alternative API ---------------------------- Conversion ^^^^^^^^^^ .. cfunction:: PyObject* PyArray_GetField(PyArrayObject* self, PyArray_Descr* dtype, int offset) Equivalent to :meth:`ndarray.getfield` (*self*, *dtype*, *offset*). Return a new array of the given *dtype* using the data in the current array at a specified *offset* in bytes. The *offset* plus the itemsize of the new array type must be less than *self* ->descr->elsize or an error is raised. The same shape and strides as the original array are used. Therefore, this function has the effect of returning a field from a record array. But, it can also be used to select specific bytes or groups of bytes from any array type. .. cfunction:: int PyArray_SetField(PyArrayObject* self, PyArray_Descr* dtype, int offset, PyObject* val) Equivalent to :meth:`ndarray.setfield` (*self*, *val*, *dtype*, *offset* ). Set the field starting at *offset* in bytes and of the given *dtype* to *val*. The *offset* plus *dtype* ->elsize must be less than *self* ->descr->elsize or an error is raised. Otherwise, the *val* argument is converted to an array and copied into the field pointed to. If necessary, the elements of *val* are repeated to fill the destination array, But, the number of elements in the destination must be an integer multiple of the number of elements in *val*. .. cfunction:: PyObject* PyArray_Byteswap(PyArrayObject* self, Bool inplace) Equivalent to :meth:`ndarray.byteswap` (*self*, *inplace*). Return an array whose data area is byteswapped. If *inplace* is non-zero, then do the byteswap inplace and return a reference to self. Otherwise, create a byteswapped copy and leave self unchanged. .. cfunction:: PyObject* PyArray_NewCopy(PyArrayObject* old, NPY_ORDER order) Equivalent to :meth:`ndarray.copy` (*self*, *fortran*). Make a copy of the *old* array. The returned array is always aligned and writeable with data interpreted the same as the old array. If *order* is :cdata:`NPY_CORDER`, then a C-style contiguous array is returned. If *order* is :cdata:`NPY_FORTRANORDER`, then a Fortran-style contiguous array is returned. If *order is* :cdata:`NPY_ANYORDER`, then the array returned is Fortran-style contiguous only if the old one is; otherwise, it is C-style contiguous. .. cfunction:: PyObject* PyArray_ToList(PyArrayObject* self) Equivalent to :meth:`ndarray.tolist` (*self*). Return a nested Python list from *self*. .. cfunction:: PyObject* PyArray_ToString(PyArrayObject* self, NPY_ORDER order) Equivalent to :meth:`ndarray.tostring` (*self*, *order*). Return the bytes of this array in a Python string. .. cfunction:: PyObject* PyArray_ToFile(PyArrayObject* self, FILE* fp, char* sep, char* format) Write the contents of *self* to the file pointer *fp* in C-style contiguous fashion. Write the data as binary bytes if *sep* is the string ""or ``NULL``. Otherwise, write the contents of *self* as text using the *sep* string as the item separator. Each item will be printed to the file. If the *format* string is not ``NULL`` or "", then it is a Python print statement format string showing how the items are to be written. .. cfunction:: int PyArray_Dump(PyObject* self, PyObject* file, int protocol) Pickle the object in *self* to the given *file* (either a string or a Python file object). If *file* is a Python string it is considered to be the name of a file which is then opened in binary mode. The given *protocol* is used (if *protocol* is negative, or the highest available is used). This is a simple wrapper around cPickle.dump(*self*, *file*, *protocol*). .. cfunction:: PyObject* PyArray_Dumps(PyObject* self, int protocol) Pickle the object in *self* to a Python string and return it. Use the Pickle *protocol* provided (or the highest available if *protocol* is negative). .. cfunction:: int PyArray_FillWithScalar(PyArrayObject* arr, PyObject* obj) Fill the array, *arr*, with the given scalar object, *obj*. The object is first converted to the data type of *arr*, and then copied into every location. A -1 is returned if an error occurs, otherwise 0 is returned. .. cfunction:: PyObject* PyArray_View(PyArrayObject* self, PyArray_Descr* dtype, PyTypeObject *ptype) Equivalent to :meth:`ndarray.view` (*self*, *dtype*). Return a new view of the array *self* as possibly a different data-type, *dtype*, and different array subclass *ptype*. If *dtype* is ``NULL``, then the returned array will have the same data type as *self*. The new data-type must be consistent with the size of *self*. Either the itemsizes must be identical, or *self* must be single-segment and the total number of bytes must be the same. In the latter case the dimensions of the returned array will be altered in the last (or first for Fortran-style contiguous arrays) dimension. The data area of the returned array and self is exactly the same. Shape Manipulation ^^^^^^^^^^^^^^^^^^ .. cfunction:: PyObject* PyArray_Newshape(PyArrayObject* self, PyArray_Dims* newshape) Result will be a new array (pointing to the same memory location as *self* if possible), but having a shape given by *newshape* . If the new shape is not compatible with the strides of *self*, then a copy of the array with the new specified shape will be returned. .. cfunction:: PyObject* PyArray_Reshape(PyArrayObject* self, PyObject* shape) Equivalent to :meth:`ndarray.reshape` (*self*, *shape*) where *shape* is a sequence. Converts *shape* to a :ctype:`PyArray_Dims` structure and calls :cfunc:`PyArray_Newshape` internally. .. cfunction:: PyObject* PyArray_Squeeze(PyArrayObject* self) Equivalent to :meth:`ndarray.squeeze` (*self*). Return a new view of *self* with all of the dimensions of length 1 removed from the shape. .. warning:: matrix objects are always 2-dimensional. Therefore, :cfunc:`PyArray_Squeeze` has no effect on arrays of matrix sub-class. .. cfunction:: PyObject* PyArray_SwapAxes(PyArrayObject* self, int a1, int a2) Equivalent to :meth:`ndarray.swapaxes` (*self*, *a1*, *a2*). The returned array is a new view of the data in *self* with the given axes, *a1* and *a2*, swapped. .. cfunction:: PyObject* PyArray_Resize(PyArrayObject* self, PyArray_Dims* newshape, int refcheck, NPY_ORDER fortran) Equivalent to :meth:`ndarray.resize` (*self*, *newshape*, refcheck ``=`` *refcheck*, order= fortran ). This function only works on single-segment arrays. It changes the shape of *self* inplace and will reallocate the memory for *self* if *newshape* has a different total number of elements then the old shape. If reallocation is necessary, then *self* must own its data, have *self* - ``>base==NULL``, have *self* - ``>weakrefs==NULL``, and (unless refcheck is 0) not be referenced by any other array. A reference to the new array is returned. The fortran argument can be :cdata:`NPY_ANYORDER`, :cdata:`NPY_CORDER`, or :cdata:`NPY_FORTRANORDER`. It currently has no effect. Eventually it could be used to determine how the resize operation should view the data when constructing a differently-dimensioned array. .. cfunction:: PyObject* PyArray_Transpose(PyArrayObject* self, PyArray_Dims* permute) Equivalent to :meth:`ndarray.transpose` (*self*, *permute*). Permute the axes of the ndarray object *self* according to the data structure *permute* and return the result. If *permute* is ``NULL``, then the resulting array has its axes reversed. For example if *self* has shape :math:`10\times20\times30`, and *permute* ``.ptr`` is (0,2,1) the shape of the result is :math:`10\times30\times20.` If *permute* is ``NULL``, the shape of the result is :math:`30\times20\times10.` .. cfunction:: PyObject* PyArray_Flatten(PyArrayObject* self, NPY_ORDER order) Equivalent to :meth:`ndarray.flatten` (*self*, *order*). Return a 1-d copy of the array. If *order* is :cdata:`NPY_FORTRANORDER` the elements are scanned out in Fortran order (first-dimension varies the fastest). If *order* is :cdata:`NPY_CORDER`, the elements of ``self`` are scanned in C-order (last dimension varies the fastest). If *order* :cdata:`NPY_ANYORDER`, then the result of :cfunc:`PyArray_ISFORTRAN` (*self*) is used to determine which order to flatten. .. cfunction:: PyObject* PyArray_Ravel(PyArrayObject* self, NPY_ORDER order) Equivalent to *self*.ravel(*order*). Same basic functionality as :cfunc:`PyArray_Flatten` (*self*, *order*) except if *order* is 0 and *self* is C-style contiguous, the shape is altered but no copy is performed. Item selection and manipulation ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ .. cfunction:: PyObject* PyArray_TakeFrom(PyArrayObject* self, PyObject* indices, int axis, PyArrayObject* ret, NPY_CLIPMODE clipmode) Equivalent to :meth:`ndarray.take` (*self*, *indices*, *axis*, *ret*, *clipmode*) except *axis* =None in Python is obtained by setting *axis* = :cdata:`NPY_MAXDIMS` in C. Extract the items from self indicated by the integer-valued *indices* along the given *axis.* The clipmode argument can be :cdata:`NPY_RAISE`, :cdata:`NPY_WRAP`, or :cdata:`NPY_CLIP` to indicate what to do with out-of-bound indices. The *ret* argument can specify an output array rather than having one created internally. .. cfunction:: PyObject* PyArray_PutTo(PyArrayObject* self, PyObject* values, PyObject* indices, NPY_CLIPMODE clipmode) Equivalent to *self*.put(*values*, *indices*, *clipmode* ). Put *values* into *self* at the corresponding (flattened) *indices*. If *values* is too small it will be repeated as necessary. .. cfunction:: PyObject* PyArray_PutMask(PyArrayObject* self, PyObject* values, PyObject* mask) Place the *values* in *self* wherever corresponding positions (using a flattened context) in *mask* are true. The *mask* and *self* arrays must have the same total number of elements. If *values* is too small, it will be repeated as necessary. .. cfunction:: PyObject* PyArray_Repeat(PyArrayObject* self, PyObject* op, int axis) Equivalent to :meth:`ndarray.repeat` (*self*, *op*, *axis*). Copy the elements of *self*, *op* times along the given *axis*. Either *op* is a scalar integer or a sequence of length *self* ->dimensions[ *axis* ] indicating how many times to repeat each item along the axis. .. cfunction:: PyObject* PyArray_Choose(PyArrayObject* self, PyObject* op, PyArrayObject* ret, NPY_CLIPMODE clipmode) Equivalent to :meth:`ndarray.choose` (*self*, *op*, *ret*, *clipmode*). Create a new array by selecting elements from the sequence of arrays in *op* based on the integer values in *self*. The arrays must all be broadcastable to the same shape and the entries in *self* should be between 0 and len(*op*). The output is placed in *ret* unless it is ``NULL`` in which case a new output is created. The *clipmode* argument determines behavior for when entries in *self* are not between 0 and len(*op*). .. cvar:: NPY_RAISE raise a ValueError; .. cvar:: NPY_WRAP wrap values < 0 by adding len(*op*) and values >=len(*op*) by subtracting len(*op*) until they are in range; .. cvar:: NPY_CLIP all values are clipped to the region [0, len(*op*) ). .. cfunction:: PyObject* PyArray_Sort(PyArrayObject* self, int axis) Equivalent to :meth:`ndarray.sort` (*self*, *axis*). Return an array with the items of *self* sorted along *axis*. .. cfunction:: PyObject* PyArray_ArgSort(PyArrayObject* self, int axis) Equivalent to :meth:`ndarray.argsort` (*self*, *axis*). Return an array of indices such that selection of these indices along the given ``axis`` would return a sorted version of *self*. If *self* ->descr is a data-type with fields defined, then self->descr->names is used to determine the sort order. A comparison where the first field is equal will use the second field and so on. To alter the sort order of a record array, create a new data-type with a different order of names and construct a view of the array with that new data-type. .. cfunction:: PyObject* PyArray_LexSort(PyObject* sort_keys, int axis) Given a sequence of arrays (*sort_keys*) of the same shape, return an array of indices (similar to :cfunc:`PyArray_ArgSort` (...)) that would sort the arrays lexicographically. A lexicographic sort specifies that when two keys are found to be equal, the order is based on comparison of subsequent keys. A merge sort (which leaves equal entries unmoved) is required to be defined for the types. The sort is accomplished by sorting the indices first using the first *sort_key* and then using the second *sort_key* and so forth. This is equivalent to the lexsort(*sort_keys*, *axis*) Python command. Because of the way the merge-sort works, be sure to understand the order the *sort_keys* must be in (reversed from the order you would use when comparing two elements). If these arrays are all collected in a record array, then :cfunc:`PyArray_Sort` (...) can also be used to sort the array directly. .. cfunction:: PyObject* PyArray_SearchSorted(PyArrayObject* self, PyObject* values) Equivalent to :meth:`ndarray.searchsorted` (*self*, *values*). Assuming *self* is a 1-d array in ascending order representing bin boundaries then the output is an array the same shape as *values* of bin numbers, giving the bin into which each item in *values* would be placed. No checking is done on whether or not self is in ascending order. .. cfunction:: int PyArray_Partition(PyArrayObject *self, PyArrayObject * ktharray, int axis, NPY_SELECTKIND which) Equivalent to :meth:`ndarray.partition` (*self*, *ktharray*, *axis*, *kind*). Partitions the array so that the values of the element indexed by *ktharray* are in the positions they would be if the array is fully sorted and places all elements smaller than the kth before and all elements equal or greater after the kth element. The ordering of all elements within the partitions is undefined. If *self*->descr is a data-type with fields defined, then self->descr->names is used to determine the sort order. A comparison where the first field is equal will use the second field and so on. To alter the sort order of a record array, create a new data-type with a different order of names and construct a view of the array with that new data-type. Returns zero on success and -1 on failure. .. cfunction:: PyObject* PyArray_ArgPartition(PyArrayObject *op, PyArrayObject * ktharray, int axis, NPY_SELECTKIND which) Equivalent to :meth:`ndarray.argpartition` (*self*, *ktharray*, *axis*, *kind*). Return an array of indices such that selection of these indices along the given ``axis`` would return a partitioned version of *self*. .. cfunction:: PyObject* PyArray_Diagonal(PyArrayObject* self, int offset, int axis1, int axis2) Equivalent to :meth:`ndarray.diagonal` (*self*, *offset*, *axis1*, *axis2* ). Return the *offset* diagonals of the 2-d arrays defined by *axis1* and *axis2*. .. cfunction:: npy_intp PyArray_CountNonzero(PyArrayObject* self) .. versionadded:: 1.6 Counts the number of non-zero elements in the array object *self*. .. cfunction:: PyObject* PyArray_Nonzero(PyArrayObject* self) Equivalent to :meth:`ndarray.nonzero` (*self*). Returns a tuple of index arrays that select elements of *self* that are nonzero. If (nd= :cfunc:`PyArray_NDIM` ( ``self`` ))==1, then a single index array is returned. The index arrays have data type :cdata:`NPY_INTP`. If a tuple is returned (nd :math:`\neq` 1), then its length is nd. .. cfunction:: PyObject* PyArray_Compress(PyArrayObject* self, PyObject* condition, int axis, PyArrayObject* out) Equivalent to :meth:`ndarray.compress` (*self*, *condition*, *axis* ). Return the elements along *axis* corresponding to elements of *condition* that are true. Calculation ^^^^^^^^^^^ .. tip:: Pass in :cdata:`NPY_MAXDIMS` for axis in order to achieve the same effect that is obtained by passing in *axis* = :const:`None` in Python (treating the array as a 1-d array). .. cfunction:: PyObject* PyArray_ArgMax(PyArrayObject* self, int axis) Equivalent to :meth:`ndarray.argmax` (*self*, *axis*). Return the index of the largest element of *self* along *axis*. .. cfunction:: PyObject* PyArray_ArgMin(PyArrayObject* self, int axis) Equivalent to :meth:`ndarray.argmin` (*self*, *axis*). Return the index of the smallest element of *self* along *axis*. .. cfunction:: PyObject* PyArray_Max(PyArrayObject* self, int axis, PyArrayObject* out) Equivalent to :meth:`ndarray.max` (*self*, *axis*). Return the largest element of *self* along the given *axis*. .. cfunction:: PyObject* PyArray_Min(PyArrayObject* self, int axis, PyArrayObject* out) Equivalent to :meth:`ndarray.min` (*self*, *axis*). Return the smallest element of *self* along the given *axis*. .. cfunction:: PyObject* PyArray_Ptp(PyArrayObject* self, int axis, PyArrayObject* out) Equivalent to :meth:`ndarray.ptp` (*self*, *axis*). Return the difference between the largest element of *self* along *axis* and the smallest element of *self* along *axis*. .. note:: The rtype argument specifies the data-type the reduction should take place over. This is important if the data-type of the array is not "large" enough to handle the output. By default, all integer data-types are made at least as large as :cdata:`NPY_LONG` for the "add" and "multiply" ufuncs (which form the basis for mean, sum, cumsum, prod, and cumprod functions). .. cfunction:: PyObject* PyArray_Mean(PyArrayObject* self, int axis, int rtype, PyArrayObject* out) Equivalent to :meth:`ndarray.mean` (*self*, *axis*, *rtype*). Returns the mean of the elements along the given *axis*, using the enumerated type *rtype* as the data type to sum in. Default sum behavior is obtained using :cdata:`NPY_NOTYPE` for *rtype*. .. cfunction:: PyObject* PyArray_Trace(PyArrayObject* self, int offset, int axis1, int axis2, int rtype, PyArrayObject* out) Equivalent to :meth:`ndarray.trace` (*self*, *offset*, *axis1*, *axis2*, *rtype*). Return the sum (using *rtype* as the data type of summation) over the *offset* diagonal elements of the 2-d arrays defined by *axis1* and *axis2* variables. A positive offset chooses diagonals above the main diagonal. A negative offset selects diagonals below the main diagonal. .. cfunction:: PyObject* PyArray_Clip(PyArrayObject* self, PyObject* min, PyObject* max) Equivalent to :meth:`ndarray.clip` (*self*, *min*, *max*). Clip an array, *self*, so that values larger than *max* are fixed to *max* and values less than *min* are fixed to *min*. .. cfunction:: PyObject* PyArray_Conjugate(PyArrayObject* self) Equivalent to :meth:`ndarray.conjugate` (*self*). Return the complex conjugate of *self*. If *self* is not of complex data type, then return *self* with an reference. .. cfunction:: PyObject* PyArray_Round(PyArrayObject* self, int decimals, PyArrayObject* out) Equivalent to :meth:`ndarray.round` (*self*, *decimals*, *out*). Returns the array with elements rounded to the nearest decimal place. The decimal place is defined as the :math:`10^{-\textrm{decimals}}` digit so that negative *decimals* cause rounding to the nearest 10's, 100's, etc. If out is ``NULL``, then the output array is created, otherwise the output is placed in *out* which must be the correct size and type. .. cfunction:: PyObject* PyArray_Std(PyArrayObject* self, int axis, int rtype, PyArrayObject* out) Equivalent to :meth:`ndarray.std` (*self*, *axis*, *rtype*). Return the standard deviation using data along *axis* converted to data type *rtype*. .. cfunction:: PyObject* PyArray_Sum(PyArrayObject* self, int axis, int rtype, PyArrayObject* out) Equivalent to :meth:`ndarray.sum` (*self*, *axis*, *rtype*). Return 1-d vector sums of elements in *self* along *axis*. Perform the sum after converting data to data type *rtype*. .. cfunction:: PyObject* PyArray_CumSum(PyArrayObject* self, int axis, int rtype, PyArrayObject* out) Equivalent to :meth:`ndarray.cumsum` (*self*, *axis*, *rtype*). Return cumulative 1-d sums of elements in *self* along *axis*. Perform the sum after converting data to data type *rtype*. .. cfunction:: PyObject* PyArray_Prod(PyArrayObject* self, int axis, int rtype, PyArrayObject* out) Equivalent to :meth:`ndarray.prod` (*self*, *axis*, *rtype*). Return 1-d products of elements in *self* along *axis*. Perform the product after converting data to data type *rtype*. .. cfunction:: PyObject* PyArray_CumProd(PyArrayObject* self, int axis, int rtype, PyArrayObject* out) Equivalent to :meth:`ndarray.cumprod` (*self*, *axis*, *rtype*). Return 1-d cumulative products of elements in ``self`` along ``axis``. Perform the product after converting data to data type ``rtype``. .. cfunction:: PyObject* PyArray_All(PyArrayObject* self, int axis, PyArrayObject* out) Equivalent to :meth:`ndarray.all` (*self*, *axis*). Return an array with True elements for every 1-d sub-array of ``self`` defined by ``axis`` in which all the elements are True. .. cfunction:: PyObject* PyArray_Any(PyArrayObject* self, int axis, PyArrayObject* out) Equivalent to :meth:`ndarray.any` (*self*, *axis*). Return an array with True elements for every 1-d sub-array of *self* defined by *axis* in which any of the elements are True. Functions --------- Array Functions ^^^^^^^^^^^^^^^ .. cfunction:: int PyArray_AsCArray(PyObject** op, void* ptr, npy_intp* dims, int nd, int typenum, int itemsize) Sometimes it is useful to access a multidimensional array as a C-style multi-dimensional array so that algorithms can be implemented using C's a[i][j][k] syntax. This routine returns a pointer, *ptr*, that simulates this kind of C-style array, for 1-, 2-, and 3-d ndarrays. :param op: The address to any Python object. This Python object will be replaced with an equivalent well-behaved, C-style contiguous, ndarray of the given data type specifice by the last two arguments. Be sure that stealing a reference in this way to the input object is justified. :param ptr: The address to a (ctype* for 1-d, ctype** for 2-d or ctype*** for 3-d) variable where ctype is the equivalent C-type for the data type. On return, *ptr* will be addressable as a 1-d, 2-d, or 3-d array. :param dims: An output array that contains the shape of the array object. This array gives boundaries on any looping that will take place. :param nd: The dimensionality of the array (1, 2, or 3). :param typenum: The expected data type of the array. :param itemsize: This argument is only needed when *typenum* represents a flexible array. Otherwise it should be 0. .. note:: The simulation of a C-style array is not complete for 2-d and 3-d arrays. For example, the simulated arrays of pointers cannot be passed to subroutines expecting specific, statically-defined 2-d and 3-d arrays. To pass to functions requiring those kind of inputs, you must statically define the required array and copy data. .. cfunction:: int PyArray_Free(PyObject* op, void* ptr) Must be called with the same objects and memory locations returned from :cfunc:`PyArray_AsCArray` (...). This function cleans up memory that otherwise would get leaked. .. cfunction:: PyObject* PyArray_Concatenate(PyObject* obj, int axis) Join the sequence of objects in *obj* together along *axis* into a single array. If the dimensions or types are not compatible an error is raised. .. cfunction:: PyObject* PyArray_InnerProduct(PyObject* obj1, PyObject* obj2) Compute a product-sum over the last dimensions of *obj1* and *obj2*. Neither array is conjugated. .. cfunction:: PyObject* PyArray_MatrixProduct(PyObject* obj1, PyObject* obj) Compute a product-sum over the last dimension of *obj1* and the second-to-last dimension of *obj2*. For 2-d arrays this is a matrix-product. Neither array is conjugated. .. cfunction:: PyObject* PyArray_MatrixProduct2(PyObject* obj1, PyObject* obj, PyObject* out) .. versionadded:: 1.6 Same as PyArray_MatrixProduct, but store the result in *out*. The output array must have the correct shape, type, and be C-contiguous, or an exception is raised. .. cfunction:: PyObject* PyArray_EinsteinSum(char* subscripts, npy_intp nop, PyArrayObject** op_in, PyArray_Descr* dtype, NPY_ORDER order, NPY_CASTING casting, PyArrayObject* out) .. versionadded:: 1.6 Applies the einstein summation convention to the array operands provided, returning a new array or placing the result in *out*. The string in *subscripts* is a comma separated list of index letters. The number of operands is in *nop*, and *op_in* is an array containing those operands. The data type of the output can be forced with *dtype*, the output order can be forced with *order* (:cdata:`NPY_KEEPORDER` is recommended), and when *dtype* is specified, *casting* indicates how permissive the data conversion should be. See the :func:`einsum` function for more details. .. cfunction:: PyObject* PyArray_CopyAndTranspose(PyObject \* op) A specialized copy and transpose function that works only for 2-d arrays. The returned array is a transposed copy of *op*. .. cfunction:: PyObject* PyArray_Correlate(PyObject* op1, PyObject* op2, int mode) Compute the 1-d correlation of the 1-d arrays *op1* and *op2* . The correlation is computed at each output point by multiplying *op1* by a shifted version of *op2* and summing the result. As a result of the shift, needed values outside of the defined range of *op1* and *op2* are interpreted as zero. The mode determines how many shifts to return: 0 - return only shifts that did not need to assume zero- values; 1 - return an object that is the same size as *op1*, 2 - return all possible shifts (any overlap at all is accepted). .. rubric:: Notes This does not compute the usual correlation: if op2 is larger than op1, the arguments are swapped, and the conjugate is never taken for complex arrays. See PyArray_Correlate2 for the usual signal processing correlation. .. cfunction:: PyObject* PyArray_Correlate2(PyObject* op1, PyObject* op2, int mode) Updated version of PyArray_Correlate, which uses the usual definition of correlation for 1d arrays. The correlation is computed at each output point by multiplying *op1* by a shifted version of *op2* and summing the result. As a result of the shift, needed values outside of the defined range of *op1* and *op2* are interpreted as zero. The mode determines how many shifts to return: 0 - return only shifts that did not need to assume zero- values; 1 - return an object that is the same size as *op1*, 2 - return all possible shifts (any overlap at all is accepted). .. rubric:: Notes Compute z as follows:: z[k] = sum_n op1[n] * conj(op2[n+k]) .. cfunction:: PyObject* PyArray_Where(PyObject* condition, PyObject* x, PyObject* y) If both ``x`` and ``y`` are ``NULL``, then return :cfunc:`PyArray_Nonzero` (*condition*). Otherwise, both *x* and *y* must be given and the object returned is shaped like *condition* and has elements of *x* and *y* where *condition* is respectively True or False. Other functions ^^^^^^^^^^^^^^^ .. cfunction:: Bool PyArray_CheckStrides(int elsize, int nd, npy_intp numbytes, npy_intp* dims, npy_intp* newstrides) Determine if *newstrides* is a strides array consistent with the memory of an *nd* -dimensional array with shape ``dims`` and element-size, *elsize*. The *newstrides* array is checked to see if jumping by the provided number of bytes in each direction will ever mean jumping more than *numbytes* which is the assumed size of the available memory segment. If *numbytes* is 0, then an equivalent *numbytes* is computed assuming *nd*, *dims*, and *elsize* refer to a single-segment array. Return :cdata:`NPY_TRUE` if *newstrides* is acceptable, otherwise return :cdata:`NPY_FALSE`. .. cfunction:: npy_intp PyArray_MultiplyList(npy_intp* seq, int n) .. cfunction:: int PyArray_MultiplyIntList(int* seq, int n) Both of these routines multiply an *n* -length array, *seq*, of integers and return the result. No overflow checking is performed. .. cfunction:: int PyArray_CompareLists(npy_intp* l1, npy_intp* l2, int n) Given two *n* -length arrays of integers, *l1*, and *l2*, return 1 if the lists are identical; otherwise, return 0. Auxiliary Data With Object Semantics ------------------------------------ .. versionadded:: 1.7.0 .. ctype:: NpyAuxData When working with more complex dtypes which are composed of other dtypes, such as the struct dtype, creating inner loops that manipulate the dtypes requires carrying along additional data. NumPy supports this idea through a struct :ctype:`NpyAuxData`, mandating a few conventions so that it is possible to do this. Defining an :ctype:`NpyAuxData` is similar to defining a class in C++, but the object semantics have to be tracked manually since the API is in C. Here's an example for a function which doubles up an element using an element copier function as a primitive.:: typedef struct { NpyAuxData base; ElementCopier_Func *func; NpyAuxData *funcdata; } eldoubler_aux_data; void free_element_doubler_aux_data(NpyAuxData *data) { eldoubler_aux_data *d = (eldoubler_aux_data *)data; /* Free the memory owned by this auxadata */ NPY_AUXDATA_FREE(d->funcdata); PyArray_free(d); } NpyAuxData *clone_element_doubler_aux_data(NpyAuxData *data) { eldoubler_aux_data *ret = PyArray_malloc(sizeof(eldoubler_aux_data)); if (ret == NULL) { return NULL; } /* Raw copy of all data */ memcpy(ret, data, sizeof(eldoubler_aux_data)); /* Fix up the owned auxdata so we have our own copy */ ret->funcdata = NPY_AUXDATA_CLONE(ret->funcdata); if (ret->funcdata == NULL) { PyArray_free(ret); return NULL; } return (NpyAuxData *)ret; } NpyAuxData *create_element_doubler_aux_data( ElementCopier_Func *func, NpyAuxData *funcdata) { eldoubler_aux_data *ret = PyArray_malloc(sizeof(eldoubler_aux_data)); if (ret == NULL) { PyErr_NoMemory(); return NULL; } memset(&ret, 0, sizeof(eldoubler_aux_data)); ret->base->free = &free_element_doubler_aux_data; ret->base->clone = &clone_element_doubler_aux_data; ret->func = func; ret->funcdata = funcdata; return (NpyAuxData *)ret; } .. ctype:: NpyAuxData_FreeFunc The function pointer type for NpyAuxData free functions. .. ctype:: NpyAuxData_CloneFunc The function pointer type for NpyAuxData clone functions. These functions should never set the Python exception on error, because they may be called from a multi-threaded context. .. cfunction:: NPY_AUXDATA_FREE(auxdata) A macro which calls the auxdata's free function appropriately, does nothing if auxdata is NULL. .. cfunction:: NPY_AUXDATA_CLONE(auxdata) A macro which calls the auxdata's clone function appropriately, returning a deep copy of the auxiliary data. Array Iterators --------------- As of Numpy 1.6, these array iterators are superceded by the new array iterator, :ctype:`NpyIter`. An array iterator is a simple way to access the elements of an N-dimensional array quickly and efficiently. Section `2 <#sec-array-iterator>`__ provides more description and examples of this useful approach to looping over an array. .. cfunction:: PyObject* PyArray_IterNew(PyObject* arr) Return an array iterator object from the array, *arr*. This is equivalent to *arr*. **flat**. The array iterator object makes it easy to loop over an N-dimensional non-contiguous array in C-style contiguous fashion. .. cfunction:: PyObject* PyArray_IterAllButAxis(PyObject* arr, int \*axis) Return an array iterator that will iterate over all axes but the one provided in *\*axis*. The returned iterator cannot be used with :cfunc:`PyArray_ITER_GOTO1D`. This iterator could be used to write something similar to what ufuncs do wherein the loop over the largest axis is done by a separate sub-routine. If *\*axis* is negative then *\*axis* will be set to the axis having the smallest stride and that axis will be used. .. cfunction:: PyObject *PyArray_BroadcastToShape(PyObject* arr, npy_intp *dimensions, int nd) Return an array iterator that is broadcast to iterate as an array of the shape provided by *dimensions* and *nd*. .. cfunction:: int PyArrayIter_Check(PyObject* op) Evaluates true if *op* is an array iterator (or instance of a subclass of the array iterator type). .. cfunction:: void PyArray_ITER_RESET(PyObject* iterator) Reset an *iterator* to the beginning of the array. .. cfunction:: void PyArray_ITER_NEXT(PyObject* iterator) Incremement the index and the dataptr members of the *iterator* to point to the next element of the array. If the array is not (C-style) contiguous, also increment the N-dimensional coordinates array. .. cfunction:: void *PyArray_ITER_DATA(PyObject* iterator) A pointer to the current element of the array. .. cfunction:: void PyArray_ITER_GOTO(PyObject* iterator, npy_intp* destination) Set the *iterator* index, dataptr, and coordinates members to the location in the array indicated by the N-dimensional c-array, *destination*, which must have size at least *iterator* ->nd_m1+1. .. cfunction:: PyArray_ITER_GOTO1D(PyObject* iterator, npy_intp index) Set the *iterator* index and dataptr to the location in the array indicated by the integer *index* which points to an element in the C-styled flattened array. .. cfunction:: int PyArray_ITER_NOTDONE(PyObject* iterator) Evaluates TRUE as long as the iterator has not looped through all of the elements, otherwise it evaluates FALSE. Broadcasting (multi-iterators) ------------------------------ .. cfunction:: PyObject* PyArray_MultiIterNew(int num, ...) A simplified interface to broadcasting. This function takes the number of arrays to broadcast and then *num* extra ( :ctype:`PyObject *` ) arguments. These arguments are converted to arrays and iterators are created. :cfunc:`PyArray_Broadcast` is then called on the resulting multi-iterator object. The resulting, broadcasted mult-iterator object is then returned. A broadcasted operation can then be performed using a single loop and using :cfunc:`PyArray_MultiIter_NEXT` (..) .. cfunction:: void PyArray_MultiIter_RESET(PyObject* multi) Reset all the iterators to the beginning in a multi-iterator object, *multi*. .. cfunction:: void PyArray_MultiIter_NEXT(PyObject* multi) Advance each iterator in a multi-iterator object, *multi*, to its next (broadcasted) element. .. cfunction:: void *PyArray_MultiIter_DATA(PyObject* multi, int i) Return the data-pointer of the *i* :math:`^{\textrm{th}}` iterator in a multi-iterator object. .. cfunction:: void PyArray_MultiIter_NEXTi(PyObject* multi, int i) Advance the pointer of only the *i* :math:`^{\textrm{th}}` iterator. .. cfunction:: void PyArray_MultiIter_GOTO(PyObject* multi, npy_intp* destination) Advance each iterator in a multi-iterator object, *multi*, to the given :math:`N` -dimensional *destination* where :math:`N` is the number of dimensions in the broadcasted array. .. cfunction:: void PyArray_MultiIter_GOTO1D(PyObject* multi, npy_intp index) Advance each iterator in a multi-iterator object, *multi*, to the corresponding location of the *index* into the flattened broadcasted array. .. cfunction:: int PyArray_MultiIter_NOTDONE(PyObject* multi) Evaluates TRUE as long as the multi-iterator has not looped through all of the elements (of the broadcasted result), otherwise it evaluates FALSE. .. cfunction:: int PyArray_Broadcast(PyArrayMultiIterObject* mit) This function encapsulates the broadcasting rules. The *mit* container should already contain iterators for all the arrays that need to be broadcast. On return, these iterators will be adjusted so that iteration over each simultaneously will accomplish the broadcasting. A negative number is returned if an error occurs. .. cfunction:: int PyArray_RemoveSmallest(PyArrayMultiIterObject* mit) This function takes a multi-iterator object that has been previously "broadcasted," finds the dimension with the smallest "sum of strides" in the broadcasted result and adapts all the iterators so as not to iterate over that dimension (by effectively making them of length-1 in that dimension). The corresponding dimension is returned unless *mit* ->nd is 0, then -1 is returned. This function is useful for constructing ufunc-like routines that broadcast their inputs correctly and then call a strided 1-d version of the routine as the inner-loop. This 1-d version is usually optimized for speed and for this reason the loop should be performed over the axis that won't require large stride jumps. Neighborhood iterator --------------------- .. versionadded:: 1.4.0 Neighborhood iterators are subclasses of the iterator object, and can be used to iter over a neighborhood of a point. For example, you may want to iterate over every voxel of a 3d image, and for every such voxel, iterate over an hypercube. Neighborhood iterator automatically handle boundaries, thus making this kind of code much easier to write than manual boundaries handling, at the cost of a slight overhead. .. cfunction:: PyObject* PyArray_NeighborhoodIterNew(PyArrayIterObject* iter, npy_intp bounds, int mode, PyArrayObject* fill_value) This function creates a new neighborhood iterator from an existing iterator. The neighborhood will be computed relatively to the position currently pointed by *iter*, the bounds define the shape of the neighborhood iterator, and the mode argument the boundaries handling mode. The *bounds* argument is expected to be a (2 * iter->ao->nd) arrays, such as the range bound[2*i]->bounds[2*i+1] defines the range where to walk for dimension i (both bounds are included in the walked coordinates). The bounds should be ordered for each dimension (bounds[2*i] <= bounds[2*i+1]). The mode should be one of: * NPY_NEIGHBORHOOD_ITER_ZERO_PADDING: zero padding. Outside bounds values will be 0. * NPY_NEIGHBORHOOD_ITER_ONE_PADDING: one padding, Outside bounds values will be 1. * NPY_NEIGHBORHOOD_ITER_CONSTANT_PADDING: constant padding. Outside bounds values will be the same as the first item in fill_value. * NPY_NEIGHBORHOOD_ITER_MIRROR_PADDING: mirror padding. Outside bounds values will be as if the array items were mirrored. For example, for the array [1, 2, 3, 4], x[-2] will be 2, x[-2] will be 1, x[4] will be 4, x[5] will be 1, etc... * NPY_NEIGHBORHOOD_ITER_CIRCULAR_PADDING: circular padding. Outside bounds values will be as if the array was repeated. For example, for the array [1, 2, 3, 4], x[-2] will be 3, x[-2] will be 4, x[4] will be 1, x[5] will be 2, etc... If the mode is constant filling (NPY_NEIGHBORHOOD_ITER_CONSTANT_PADDING), fill_value should point to an array object which holds the filling value (the first item will be the filling value if the array contains more than one item). For other cases, fill_value may be NULL. - The iterator holds a reference to iter - Return NULL on failure (in which case the reference count of iter is not changed) - iter itself can be a Neighborhood iterator: this can be useful for .e.g automatic boundaries handling - the object returned by this function should be safe to use as a normal iterator - If the position of iter is changed, any subsequent call to PyArrayNeighborhoodIter_Next is undefined behavior, and PyArrayNeighborhoodIter_Reset must be called. .. code-block:: c PyArrayIterObject \*iter; PyArrayNeighborhoodIterObject \*neigh_iter; iter = PyArray_IterNew(x); //For a 3x3 kernel bounds = {-1, 1, -1, 1}; neigh_iter = (PyArrayNeighborhoodIterObject*)PyArrayNeighborhoodIter_New( iter, bounds, NPY_NEIGHBORHOOD_ITER_ZERO_PADDING, NULL); for(i = 0; i < iter->size; ++i) { for (j = 0; j < neigh_iter->size; ++j) { // Walk around the item currently pointed by iter->dataptr PyArrayNeighborhoodIter_Next(neigh_iter); } // Move to the next point of iter PyArrayIter_Next(iter); PyArrayNeighborhoodIter_Reset(neigh_iter); } .. cfunction:: int PyArrayNeighborhoodIter_Reset(PyArrayNeighborhoodIterObject* iter) Reset the iterator position to the first point of the neighborhood. This should be called whenever the iter argument given at PyArray_NeighborhoodIterObject is changed (see example) .. cfunction:: int PyArrayNeighborhoodIter_Next(PyArrayNeighborhoodIterObject* iter) After this call, iter->dataptr points to the next point of the neighborhood. Calling this function after every point of the neighborhood has been visited is undefined. Array Scalars ------------- .. cfunction:: PyObject* PyArray_Return(PyArrayObject* arr) This function checks to see if *arr* is a 0-dimensional array and, if so, returns the appropriate array scalar. It should be used whenever 0-dimensional arrays could be returned to Python. .. cfunction:: PyObject* PyArray_Scalar(void* data, PyArray_Descr* dtype, PyObject* itemsize) Return an array scalar object of the given enumerated *typenum* and *itemsize* by **copying** from memory pointed to by *data* . If *swap* is nonzero then this function will byteswap the data if appropriate to the data-type because array scalars are always in correct machine-byte order. .. cfunction:: PyObject* PyArray_ToScalar(void* data, PyArrayObject* arr) Return an array scalar object of the type and itemsize indicated by the array object *arr* copied from the memory pointed to by *data* and swapping if the data in *arr* is not in machine byte-order. .. cfunction:: PyObject* PyArray_FromScalar(PyObject* scalar, PyArray_Descr* outcode) Return a 0-dimensional array of type determined by *outcode* from *scalar* which should be an array-scalar object. If *outcode* is NULL, then the type is determined from *scalar*. .. cfunction:: void PyArray_ScalarAsCtype(PyObject* scalar, void* ctypeptr) Return in *ctypeptr* a pointer to the actual value in an array scalar. There is no error checking so *scalar* must be an array-scalar object, and ctypeptr must have enough space to hold the correct type. For flexible-sized types, a pointer to the data is copied into the memory of *ctypeptr*, for all other types, the actual data is copied into the address pointed to by *ctypeptr*. .. cfunction:: void PyArray_CastScalarToCtype(PyObject* scalar, void* ctypeptr, PyArray_Descr* outcode) Return the data (cast to the data type indicated by *outcode*) from the array-scalar, *scalar*, into the memory pointed to by *ctypeptr* (which must be large enough to handle the incoming memory). .. cfunction:: PyObject* PyArray_TypeObjectFromType(int type) Returns a scalar type-object from a type-number, *type* . Equivalent to :cfunc:`PyArray_DescrFromType` (*type*)->typeobj except for reference counting and error-checking. Returns a new reference to the typeobject on success or ``NULL`` on failure. .. cfunction:: NPY_SCALARKIND PyArray_ScalarKind(int typenum, PyArrayObject** arr) See the function :cfunc:`PyArray_MinScalarType` for an alternative mechanism introduced in NumPy 1.6.0. Return the kind of scalar represented by *typenum* and the array in *\*arr* (if *arr* is not ``NULL`` ). The array is assumed to be rank-0 and only used if *typenum* represents a signed integer. If *arr* is not ``NULL`` and the first element is negative then :cdata:`NPY_INTNEG_SCALAR` is returned, otherwise :cdata:`NPY_INTPOS_SCALAR` is returned. The possible return values are :cdata:`NPY_{kind}_SCALAR` where ``{kind}`` can be **INTPOS**, **INTNEG**, **FLOAT**, **COMPLEX**, **BOOL**, or **OBJECT**. :cdata:`NPY_NOSCALAR` is also an enumerated value :ctype:`NPY_SCALARKIND` variables can take on. .. cfunction:: int PyArray_CanCoerceScalar(char thistype, char neededtype, NPY_SCALARKIND scalar) See the function :cfunc:`PyArray_ResultType` for details of NumPy type promotion, updated in NumPy 1.6.0. Implements the rules for scalar coercion. Scalars are only silently coerced from thistype to neededtype if this function returns nonzero. If scalar is :cdata:`NPY_NOSCALAR`, then this function is equivalent to :cfunc:`PyArray_CanCastSafely`. The rule is that scalars of the same KIND can be coerced into arrays of the same KIND. This rule means that high-precision scalars will never cause low-precision arrays of the same KIND to be upcast. Data-type descriptors --------------------- .. warning:: Data-type objects must be reference counted so be aware of the action on the data-type reference of different C-API calls. The standard rule is that when a data-type object is returned it is a new reference. Functions that take :ctype:`PyArray_Descr *` objects and return arrays steal references to the data-type their inputs unless otherwise noted. Therefore, you must own a reference to any data-type object used as input to such a function. .. cfunction:: int PyArrayDescr_Check(PyObject* obj) Evaluates as true if *obj* is a data-type object ( :ctype:`PyArray_Descr *` ). .. cfunction:: PyArray_Descr* PyArray_DescrNew(PyArray_Descr* obj) Return a new data-type object copied from *obj* (the fields reference is just updated so that the new object points to the same fields dictionary if any). .. cfunction:: PyArray_Descr* PyArray_DescrNewFromType(int typenum) Create a new data-type object from the built-in (or user-registered) data-type indicated by *typenum*. All builtin types should not have any of their fields changed. This creates a new copy of the :ctype:`PyArray_Descr` structure so that you can fill it in as appropriate. This function is especially needed for flexible data-types which need to have a new elsize member in order to be meaningful in array construction. .. cfunction:: PyArray_Descr* PyArray_DescrNewByteorder(PyArray_Descr* obj, char newendian) Create a new data-type object with the byteorder set according to *newendian*. All referenced data-type objects (in subdescr and fields members of the data-type object) are also changed (recursively). If a byteorder of :cdata:`NPY_IGNORE` is encountered it is left alone. If newendian is :cdata:`NPY_SWAP`, then all byte-orders are swapped. Other valid newendian values are :cdata:`NPY_NATIVE`, :cdata:`NPY_LITTLE`, and :cdata:`NPY_BIG` which all cause the returned data-typed descriptor (and all it's referenced data-type descriptors) to have the corresponding byte- order. .. cfunction:: PyArray_Descr* PyArray_DescrFromObject(PyObject* op, PyArray_Descr* mintype) Determine an appropriate data-type object from the object *op* (which should be a "nested" sequence object) and the minimum data-type descriptor mintype (which can be ``NULL`` ). Similar in behavior to array(*op*).dtype. Don't confuse this function with :cfunc:`PyArray_DescrConverter`. This function essentially looks at all the objects in the (nested) sequence and determines the data-type from the elements it finds. .. cfunction:: PyArray_Descr* PyArray_DescrFromScalar(PyObject* scalar) Return a data-type object from an array-scalar object. No checking is done to be sure that *scalar* is an array scalar. If no suitable data-type can be determined, then a data-type of :cdata:`NPY_OBJECT` is returned by default. .. cfunction:: PyArray_Descr* PyArray_DescrFromType(int typenum) Returns a data-type object corresponding to *typenum*. The *typenum* can be one of the enumerated types, a character code for one of the enumerated types, or a user-defined type. .. cfunction:: int PyArray_DescrConverter(PyObject* obj, PyArray_Descr** dtype) Convert any compatible Python object, *obj*, to a data-type object in *dtype*. A large number of Python objects can be converted to data-type objects. See :ref:`arrays.dtypes` for a complete description. This version of the converter converts None objects to a :cdata:`NPY_DEFAULT_TYPE` data-type object. This function can be used with the "O&" character code in :cfunc:`PyArg_ParseTuple` processing. .. cfunction:: int PyArray_DescrConverter2(PyObject* obj, PyArray_Descr** dtype) Convert any compatible Python object, *obj*, to a data-type object in *dtype*. This version of the converter converts None objects so that the returned data-type is ``NULL``. This function can also be used with the "O&" character in PyArg_ParseTuple processing. .. cfunction:: int Pyarray_DescrAlignConverter(PyObject* obj, PyArray_Descr** dtype) Like :cfunc:`PyArray_DescrConverter` except it aligns C-struct-like objects on word-boundaries as the compiler would. .. cfunction:: int Pyarray_DescrAlignConverter2(PyObject* obj, PyArray_Descr** dtype) Like :cfunc:`PyArray_DescrConverter2` except it aligns C-struct-like objects on word-boundaries as the compiler would. .. cfunction:: PyObject *PyArray_FieldNames(PyObject* dict) Take the fields dictionary, *dict*, such as the one attached to a data-type object and construct an ordered-list of field names such as is stored in the names field of the :ctype:`PyArray_Descr` object. Conversion Utilities -------------------- For use with :cfunc:`PyArg_ParseTuple` ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ All of these functions can be used in :cfunc:`PyArg_ParseTuple` (...) with the "O&" format specifier to automatically convert any Python object to the required C-object. All of these functions return :cdata:`NPY_SUCCEED` if successful and :cdata:`NPY_FAIL` if not. The first argument to all of these function is a Python object. The second argument is the **address** of the C-type to convert the Python object to. .. warning:: Be sure to understand what steps you should take to manage the memory when using these conversion functions. These functions can require freeing memory, and/or altering the reference counts of specific objects based on your use. .. cfunction:: int PyArray_Converter(PyObject* obj, PyObject** address) Convert any Python object to a :ctype:`PyArrayObject`. If :cfunc:`PyArray_Check` (*obj*) is TRUE then its reference count is incremented and a reference placed in *address*. If *obj* is not an array, then convert it to an array using :cfunc:`PyArray_FromAny` . No matter what is returned, you must DECREF the object returned by this routine in *address* when you are done with it. .. cfunction:: int PyArray_OutputConverter(PyObject* obj, PyArrayObject** address) This is a default converter for output arrays given to functions. If *obj* is :cdata:`Py_None` or ``NULL``, then *\*address* will be ``NULL`` but the call will succeed. If :cfunc:`PyArray_Check` ( *obj*) is TRUE then it is returned in *\*address* without incrementing its reference count. .. cfunction:: int PyArray_IntpConverter(PyObject* obj, PyArray_Dims* seq) Convert any Python sequence, *obj*, smaller than :cdata:`NPY_MAXDIMS` to a C-array of :ctype:`npy_intp`. The Python object could also be a single number. The *seq* variable is a pointer to a structure with members ptr and len. On successful return, *seq* ->ptr contains a pointer to memory that must be freed to avoid a memory leak. The restriction on memory size allows this converter to be conveniently used for sequences intended to be interpreted as array shapes. .. cfunction:: int PyArray_BufferConverter(PyObject* obj, PyArray_Chunk* buf) Convert any Python object, *obj*, with a (single-segment) buffer interface to a variable with members that detail the object's use of its chunk of memory. The *buf* variable is a pointer to a structure with base, ptr, len, and flags members. The :ctype:`PyArray_Chunk` structure is binary compatibile with the Python's buffer object (through its len member on 32-bit platforms and its ptr member on 64-bit platforms or in Python 2.5). On return, the base member is set to *obj* (or its base if *obj* is already a buffer object pointing to another object). If you need to hold on to the memory be sure to INCREF the base member. The chunk of memory is pointed to by *buf* ->ptr member and has length *buf* ->len. The flags member of *buf* is :cdata:`NPY_BEHAVED_RO` with the :cdata:`NPY_ARRAY_WRITEABLE` flag set if *obj* has a writeable buffer interface. .. cfunction:: int PyArray_AxisConverter(PyObject \* obj, int* axis) Convert a Python object, *obj*, representing an axis argument to the proper value for passing to the functions that take an integer axis. Specifically, if *obj* is None, *axis* is set to :cdata:`NPY_MAXDIMS` which is interpreted correctly by the C-API functions that take axis arguments. .. cfunction:: int PyArray_BoolConverter(PyObject* obj, Bool* value) Convert any Python object, *obj*, to :cdata:`NPY_TRUE` or :cdata:`NPY_FALSE`, and place the result in *value*. .. cfunction:: int PyArray_ByteorderConverter(PyObject* obj, char* endian) Convert Python strings into the corresponding byte-order character: '>', '<', 's', '=', or '\|'. .. cfunction:: int PyArray_SortkindConverter(PyObject* obj, NPY_SORTKIND* sort) Convert Python strings into one of :cdata:`NPY_QUICKSORT` (starts with 'q' or 'Q') , :cdata:`NPY_HEAPSORT` (starts with 'h' or 'H'), or :cdata:`NPY_MERGESORT` (starts with 'm' or 'M'). .. cfunction:: int PyArray_SearchsideConverter(PyObject* obj, NPY_SEARCHSIDE* side) Convert Python strings into one of :cdata:`NPY_SEARCHLEFT` (starts with 'l' or 'L'), or :cdata:`NPY_SEARCHRIGHT` (starts with 'r' or 'R'). .. cfunction:: int PyArray_OrderConverter(PyObject* obj, NPY_ORDER* order) Convert the Python strings 'C', 'F', 'A', and 'K' into the :ctype:`NPY_ORDER` enumeration :cdata:`NPY_CORDER`, :cdata:`NPY_FORTRANORDER`, :cdata:`NPY_ANYORDER`, and :cdata:`NPY_KEEPORDER`. .. cfunction:: int PyArray_CastingConverter(PyObject* obj, NPY_CASTING* casting) Convert the Python strings 'no', 'equiv', 'safe', 'same_kind', and 'unsafe' into the :ctype:`NPY_CASTING` enumeration :cdata:`NPY_NO_CASTING`, :cdata:`NPY_EQUIV_CASTING`, :cdata:`NPY_SAFE_CASTING`, :cdata:`NPY_SAME_KIND_CASTING`, and :cdata:`NPY_UNSAFE_CASTING`. .. cfunction:: int PyArray_ClipmodeConverter(PyObject* object, NPY_CLIPMODE* val) Convert the Python strings 'clip', 'wrap', and 'raise' into the :ctype:`NPY_CLIPMODE` enumeration :cdata:`NPY_CLIP`, :cdata:`NPY_WRAP`, and :cdata:`NPY_RAISE`. .. cfunction:: int PyArray_ConvertClipmodeSequence(PyObject* object, NPY_CLIPMODE* modes, int n) Converts either a sequence of clipmodes or a single clipmode into a C array of :ctype:`NPY_CLIPMODE` values. The number of clipmodes *n* must be known before calling this function. This function is provided to help functions allow a different clipmode for each dimension. Other conversions ^^^^^^^^^^^^^^^^^ .. cfunction:: int PyArray_PyIntAsInt(PyObject* op) Convert all kinds of Python objects (including arrays and array scalars) to a standard integer. On error, -1 is returned and an exception set. You may find useful the macro: .. code-block:: c #define error_converting(x) (((x) == -1) && PyErr_Occurred() .. cfunction:: npy_intp PyArray_PyIntAsIntp(PyObject* op) Convert all kinds of Python objects (including arrays and array scalars) to a (platform-pointer-sized) integer. On error, -1 is returned and an exception set. .. cfunction:: int PyArray_IntpFromSequence(PyObject* seq, npy_intp* vals, int maxvals) Convert any Python sequence (or single Python number) passed in as *seq* to (up to) *maxvals* pointer-sized integers and place them in the *vals* array. The sequence can be smaller then *maxvals* as the number of converted objects is returned. .. cfunction:: int PyArray_TypestrConvert(int itemsize, int gentype) Convert typestring characters (with *itemsize*) to basic enumerated data types. The typestring character corresponding to signed and unsigned integers, floating point numbers, and complex-floating point numbers are recognized and converted. Other values of gentype are returned. This function can be used to convert, for example, the string 'f4' to :cdata:`NPY_FLOAT32`. Miscellaneous ------------- Importing the API ^^^^^^^^^^^^^^^^^ In order to make use of the C-API from another extension module, the ``import_array`` () command must be used. If the extension module is self-contained in a single .c file, then that is all that needs to be done. If, however, the extension module involves multiple files where the C-API is needed then some additional steps must be taken. .. cfunction:: void import_array(void) This function must be called in the initialization section of a module that will make use of the C-API. It imports the module where the function-pointer table is stored and points the correct variable to it. .. cmacro:: PY_ARRAY_UNIQUE_SYMBOL .. cmacro:: NO_IMPORT_ARRAY Using these #defines you can use the C-API in multiple files for a single extension module. In each file you must define :cmacro:`PY_ARRAY_UNIQUE_SYMBOL` to some name that will hold the C-API (*e.g.* myextension_ARRAY_API). This must be done **before** including the numpy/arrayobject.h file. In the module intialization routine you call ``import_array`` (). In addition, in the files that do not have the module initialization sub_routine define :cmacro:`NO_IMPORT_ARRAY` prior to including numpy/arrayobject.h. Suppose I have two files coolmodule.c and coolhelper.c which need to be compiled and linked into a single extension module. Suppose coolmodule.c contains the required initcool module initialization function (with the import_array() function called). Then, coolmodule.c would have at the top: .. code-block:: c #define PY_ARRAY_UNIQUE_SYMBOL cool_ARRAY_API #include numpy/arrayobject.h On the other hand, coolhelper.c would contain at the top: .. code-block:: c #define PY_ARRAY_UNIQUE_SYMBOL cool_ARRAY_API #define NO_IMPORT_ARRAY #include numpy/arrayobject.h Checking the API Version ^^^^^^^^^^^^^^^^^^^^^^^^ Because python extensions are not used in the same way as usual libraries on most platforms, some errors cannot be automatically detected at build time or even runtime. For example, if you build an extension using a function available only for numpy >= 1.3.0, and you import the extension later with numpy 1.2, you will not get an import error (but almost certainly a segmentation fault when calling the function). That's why several functions are provided to check for numpy versions. The macros :cdata:`NPY_VERSION` and :cdata:`NPY_FEATURE_VERSION` corresponds to the numpy version used to build the extension, whereas the versions returned by the functions PyArray_GetNDArrayCVersion and PyArray_GetNDArrayCFeatureVersion corresponds to the runtime numpy's version. The rules for ABI and API compatibilities can be summarized as follows: * Whenever :cdata:`NPY_VERSION` != PyArray_GetNDArrayCVersion, the extension has to be recompiled (ABI incompatibility). * :cdata:`NPY_VERSION` == PyArray_GetNDArrayCVersion and :cdata:`NPY_FEATURE_VERSION` <= PyArray_GetNDArrayCFeatureVersion means backward compatible changes. ABI incompatibility is automatically detected in every numpy's version. API incompatibility detection was added in numpy 1.4.0. If you want to supported many different numpy versions with one extension binary, you have to build your extension with the lowest NPY_FEATURE_VERSION as possible. .. cfunction:: unsigned int PyArray_GetNDArrayCVersion(void) This just returns the value :cdata:`NPY_VERSION`. :cdata:`NPY_VERSION` changes whenever a backward incompatible change at the ABI level. Because it is in the C-API, however, comparing the output of this function from the value defined in the current header gives a way to test if the C-API has changed thus requiring a re-compilation of extension modules that use the C-API. This is automatically checked in the function import_array. .. cfunction:: unsigned int PyArray_GetNDArrayCFeatureVersion(void) .. versionadded:: 1.4.0 This just returns the value :cdata:`NPY_FEATURE_VERSION`. :cdata:`NPY_FEATURE_VERSION` changes whenever the API changes (e.g. a function is added). A changed value does not always require a recompile. Internal Flexibility ^^^^^^^^^^^^^^^^^^^^ .. cfunction:: int PyArray_SetNumericOps(PyObject* dict) NumPy stores an internal table of Python callable objects that are used to implement arithmetic operations for arrays as well as certain array calculation methods. This function allows the user to replace any or all of these Python objects with their own versions. The keys of the dictionary, *dict*, are the named functions to replace and the paired value is the Python callable object to use. Care should be taken that the function used to replace an internal array operation does not itself call back to that internal array operation (unless you have designed the function to handle that), or an unchecked infinite recursion can result (possibly causing program crash). The key names that represent operations that can be replaced are: **add**, **subtract**, **multiply**, **divide**, **remainder**, **power**, **square**, **reciprocal**, **ones_like**, **sqrt**, **negative**, **absolute**, **invert**, **left_shift**, **right_shift**, **bitwise_and**, **bitwise_xor**, **bitwise_or**, **less**, **less_equal**, **equal**, **not_equal**, **greater**, **greater_equal**, **floor_divide**, **true_divide**, **logical_or**, **logical_and**, **floor**, **ceil**, **maximum**, **minimum**, **rint**. These functions are included here because they are used at least once in the array object's methods. The function returns -1 (without setting a Python Error) if one of the objects being assigned is not callable. .. cfunction:: PyObject* PyArray_GetNumericOps(void) Return a Python dictionary containing the callable Python objects stored in the the internal arithmetic operation table. The keys of this dictionary are given in the explanation for :cfunc:`PyArray_SetNumericOps`. .. cfunction:: void PyArray_SetStringFunction(PyObject* op, int repr) This function allows you to alter the tp_str and tp_repr methods of the array object to any Python function. Thus you can alter what happens for all arrays when str(arr) or repr(arr) is called from Python. The function to be called is passed in as *op*. If *repr* is non-zero, then this function will be called in response to repr(arr), otherwise the function will be called in response to str(arr). No check on whether or not *op* is callable is performed. The callable passed in to *op* should expect an array argument and should return a string to be printed. Memory management ^^^^^^^^^^^^^^^^^ .. cfunction:: char* PyDataMem_NEW(size_t nbytes) .. cfunction:: PyDataMem_FREE(char* ptr) .. cfunction:: char* PyDataMem_RENEW(void * ptr, size_t newbytes) Macros to allocate, free, and reallocate memory. These macros are used internally to create arrays. .. cfunction:: npy_intp* PyDimMem_NEW(nd) .. cfunction:: PyDimMem_FREE(npy_intp* ptr) .. cfunction:: npy_intp* PyDimMem_RENEW(npy_intp* ptr, npy_intp newnd) Macros to allocate, free, and reallocate dimension and strides memory. .. cfunction:: PyArray_malloc(nbytes) .. cfunction:: PyArray_free(ptr) .. cfunction:: PyArray_realloc(ptr, nbytes) These macros use different memory allocators, depending on the constant :cdata:`NPY_USE_PYMEM`. The system malloc is used when :cdata:`NPY_USE_PYMEM` is 0, if :cdata:`NPY_USE_PYMEM` is 1, then the Python memory allocator is used. Threading support ^^^^^^^^^^^^^^^^^ These macros are only meaningful if :cdata:`NPY_ALLOW_THREADS` evaluates True during compilation of the extension module. Otherwise, these macros are equivalent to whitespace. Python uses a single Global Interpreter Lock (GIL) for each Python process so that only a single thread may excecute at a time (even on multi-cpu machines). When calling out to a compiled function that may take time to compute (and does not have side-effects for other threads like updated global variables), the GIL should be released so that other Python threads can run while the time-consuming calculations are performed. This can be accomplished using two groups of macros. Typically, if one macro in a group is used in a code block, all of them must be used in the same code block. Currently, :cdata:`NPY_ALLOW_THREADS` is defined to the python-defined :cdata:`WITH_THREADS` constant unless the environment variable :cdata:`NPY_NOSMP` is set in which case :cdata:`NPY_ALLOW_THREADS` is defined to be 0. Group 1 """"""" This group is used to call code that may take some time but does not use any Python C-API calls. Thus, the GIL should be released during its calculation. .. cmacro:: NPY_BEGIN_ALLOW_THREADS Equivalent to :cmacro:`Py_BEGIN_ALLOW_THREADS` except it uses :cdata:`NPY_ALLOW_THREADS` to determine if the macro if replaced with white-space or not. .. cmacro:: NPY_END_ALLOW_THREADS Equivalent to :cmacro:`Py_END_ALLOW_THREADS` except it uses :cdata:`NPY_ALLOW_THREADS` to determine if the macro if replaced with white-space or not. .. cmacro:: NPY_BEGIN_THREADS_DEF Place in the variable declaration area. This macro sets up the variable needed for storing the Python state. .. cmacro:: NPY_BEGIN_THREADS Place right before code that does not need the Python interpreter (no Python C-API calls). This macro saves the Python state and releases the GIL. .. cmacro:: NPY_END_THREADS Place right after code that does not need the Python interpreter. This macro acquires the GIL and restores the Python state from the saved variable. .. cfunction:: NPY_BEGIN_THREADS_DESCR(PyArray_Descr *dtype) Useful to release the GIL only if *dtype* does not contain arbitrary Python objects which may need the Python interpreter during execution of the loop. Equivalent to .. cfunction:: NPY_END_THREADS_DESCR(PyArray_Descr *dtype) Useful to regain the GIL in situations where it was released using the BEGIN form of this macro. Group 2 """"""" This group is used to re-acquire the Python GIL after it has been released. For example, suppose the GIL has been released (using the previous calls), and then some path in the code (perhaps in a different subroutine) requires use of the Python C-API, then these macros are useful to acquire the GIL. These macros accomplish essentially a reverse of the previous three (acquire the LOCK saving what state it had) and then re-release it with the saved state. .. cmacro:: NPY_ALLOW_C_API_DEF Place in the variable declaration area to set up the necessary variable. .. cmacro:: NPY_ALLOW_C_API Place before code that needs to call the Python C-API (when it is known that the GIL has already been released). .. cmacro:: NPY_DISABLE_C_API Place after code that needs to call the Python C-API (to re-release the GIL). .. tip:: Never use semicolons after the threading support macros. Priority ^^^^^^^^ .. cvar:: NPY_PRIORITY Default priority for arrays. .. cvar:: NPY_SUBTYPE_PRIORITY Default subtype priority. .. cvar:: NPY_SCALAR_PRIORITY Default scalar priority (very small) .. cfunction:: double PyArray_GetPriority(PyObject* obj, double def) Return the :obj:`__array_priority__` attribute (converted to a double) of *obj* or *def* if no attribute of that name exists. Fast returns that avoid the attribute lookup are provided for objects of type :cdata:`PyArray_Type`. Default buffers ^^^^^^^^^^^^^^^ .. cvar:: NPY_BUFSIZE Default size of the user-settable internal buffers. .. cvar:: NPY_MIN_BUFSIZE Smallest size of user-settable internal buffers. .. cvar:: NPY_MAX_BUFSIZE Largest size allowed for the user-settable buffers. Other constants ^^^^^^^^^^^^^^^ .. cvar:: NPY_NUM_FLOATTYPE The number of floating-point types .. cvar:: NPY_MAXDIMS The maximum number of dimensions allowed in arrays. .. cvar:: NPY_VERSION The current version of the ndarray object (check to see if this variable is defined to guarantee the numpy/arrayobject.h header is being used). .. cvar:: NPY_FALSE Defined as 0 for use with Bool. .. cvar:: NPY_TRUE Defined as 1 for use with Bool. .. cvar:: NPY_FAIL The return value of failed converter functions which are called using the "O&" syntax in :cfunc:`PyArg_ParseTuple`-like functions. .. cvar:: NPY_SUCCEED The return value of successful converter functions which are called using the "O&" syntax in :cfunc:`PyArg_ParseTuple`-like functions. Miscellaneous Macros ^^^^^^^^^^^^^^^^^^^^ .. cfunction:: PyArray_SAMESHAPE(a1, a2) Evaluates as True if arrays *a1* and *a2* have the same shape. .. cfunction:: PyArray_MAX(a,b) Returns the maximum of *a* and *b*. If (*a*) or (*b*) are expressions they are evaluated twice. .. cfunction:: PyArray_MIN(a,b) Returns the minimum of *a* and *b*. If (*a*) or (*b*) are expressions they are evaluated twice. .. cfunction:: PyArray_CLT(a,b) .. cfunction:: PyArray_CGT(a,b) .. cfunction:: PyArray_CLE(a,b) .. cfunction:: PyArray_CGE(a,b) .. cfunction:: PyArray_CEQ(a,b) .. cfunction:: PyArray_CNE(a,b) Implements the complex comparisons between two complex numbers (structures with a real and imag member) using NumPy's definition of the ordering which is lexicographic: comparing the real parts first and then the complex parts if the real parts are equal. .. cfunction:: PyArray_REFCOUNT(PyObject* op) Returns the reference count of any Python object. .. cfunction:: PyArray_XDECREF_ERR(PyObject \*obj) DECREF's an array object which may have the :cdata:`NPY_ARRAY_UPDATEIFCOPY` flag set without causing the contents to be copied back into the original array. Resets the :cdata:`NPY_ARRAY_WRITEABLE` flag on the base object. This is useful for recovering from an error condition when :cdata:`NPY_ARRAY_UPDATEIFCOPY` is used. Enumerated Types ^^^^^^^^^^^^^^^^ .. ctype:: NPY_SORTKIND A special variable-type which can take on the values :cdata:`NPY_{KIND}` where ``{KIND}`` is **QUICKSORT**, **HEAPSORT**, **MERGESORT** .. cvar:: NPY_NSORTS Defined to be the number of sorts. .. ctype:: NPY_SCALARKIND A special variable type indicating the number of "kinds" of scalars distinguished in determining scalar-coercion rules. This variable can take on the values :cdata:`NPY_{KIND}` where ``{KIND}`` can be **NOSCALAR**, **BOOL_SCALAR**, **INTPOS_SCALAR**, **INTNEG_SCALAR**, **FLOAT_SCALAR**, **COMPLEX_SCALAR**, **OBJECT_SCALAR** .. cvar:: NPY_NSCALARKINDS Defined to be the number of scalar kinds (not including :cdata:`NPY_NOSCALAR`). .. ctype:: NPY_ORDER An enumeration type indicating the element order that an array should be interpreted in. When a brand new array is created, generally only **NPY_CORDER** and **NPY_FORTRANORDER** are used, whereas when one or more inputs are provided, the order can be based on them. .. cvar:: NPY_ANYORDER Fortran order if all the inputs are Fortran, C otherwise. .. cvar:: NPY_CORDER C order. .. cvar:: NPY_FORTRANORDER Fortran order. .. cvar:: NPY_KEEPORDER An order as close to the order of the inputs as possible, even if the input is in neither C nor Fortran order. .. ctype:: NPY_CLIPMODE A variable type indicating the kind of clipping that should be applied in certain functions. .. cvar:: NPY_RAISE The default for most operations, raises an exception if an index is out of bounds. .. cvar:: NPY_CLIP Clips an index to the valid range if it is out of bounds. .. cvar:: NPY_WRAP Wraps an index to the valid range if it is out of bounds. .. ctype:: NPY_CASTING .. versionadded:: 1.6 An enumeration type indicating how permissive data conversions should be. This is used by the iterator added in NumPy 1.6, and is intended to be used more broadly in a future version. .. cvar:: NPY_NO_CASTING Only allow identical types. .. cvar:: NPY_EQUIV_CASTING Allow identical and casts involving byte swapping. .. cvar:: NPY_SAFE_CASTING Only allow casts which will not cause values to be rounded, truncated, or otherwise changed. .. cvar:: NPY_SAME_KIND_CASTING Allow any safe casts, and casts between types of the same kind. For example, float64 -> float32 is permitted with this rule. .. cvar:: NPY_UNSAFE_CASTING Allow any cast, no matter what kind of data loss may occur. .. index:: pair: ndarray; C-API numpy-1.8.2/doc/source/reference/c-api.deprecations.rst0000664000175100017510000000543312370216242024235 0ustar vagrantvagrant00000000000000C API Deprecations ================== Background ---------- The API exposed by NumPy for third-party extensions has grown over years of releases, and has allowed programmers to directly access NumPy functionality from C. This API can be best described as "organic". It has emerged from multiple competing desires and from multiple points of view over the years, strongly influenced by the desire to make it easy for users to move to NumPy from Numeric and Numarray. The core API originated with Numeric in 1995 and there are patterns such as the heavy use of macros written to mimic Python's C-API as well as account for compiler technology of the late 90's. There is also only a small group of volunteers who have had very little time to spend on improving this API. There is an ongoing effort to improve the API. It is important in this effort to ensure that code that compiles for NumPy 1.X continues to compile for NumPy 1.X. At the same time, certain API's will be marked as deprecated so that future-looking code can avoid these API's and follow better practices. Another important role played by deprecation markings in the C API is to move towards hiding internal details of the NumPy implementation. For those needing direct, easy, access to the data of ndarrays, this will not remove this ability. Rather, there are many potential performance optimizations which require changing the implementation details, and NumPy developers have been unable to try them because of the high value of preserving ABI compatibility. By deprecating this direct access, we will in the future be able to improve NumPy's performance in ways we cannot presently. Deprecation Mechanism NPY_NO_DEPRECATED_API ------------------------------------------- In C, there is no equivalent to the deprecation warnings that Python supports. One way to do deprecations is to flag them in the documentation and release notes, then remove or change the deprecated features in a future major version (NumPy 2.0 and beyond). Minor versions of NumPy should not have major C-API changes, however, that prevent code that worked on a previous minor release. For example, we will do our best to ensure that code that compiled and worked on NumPy 1.4 should continue to work on NumPy 1.7 (but perhaps with compiler warnings). To use the NPY_NO_DEPRECATED_API mechanism, you need to #define it to the target API version of NumPy before #including any NumPy headers. If you want to confirm that your code is clean against 1.7, use:: #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION On compilers which support a #warning mechanism, NumPy issues a compiler warning if you do not define the symbol NPY_NO_DEPRECATED_API. This way, the fact that there are deprecations will be flagged for third-party developers who may not have read the release notes closely. numpy-1.8.2/doc/source/reference/routines.polynomials.chebyshev.rst0000664000175100017510000000252512370216242026760 0ustar vagrantvagrant00000000000000Chebyshev Module (:mod:`numpy.polynomial.chebyshev`) ==================================================== .. versionadded:: 1.4.0 .. currentmodule:: numpy.polynomial.chebyshev This module provides a number of objects (mostly functions) useful for dealing with Chebyshev series, including a `Chebyshev` class that encapsulates the usual arithmetic operations. (General information on how this module represents and works with such polynomials is in the docstring for its "parent" sub-package, `numpy.polynomial`). Chebyshev Class --------------- .. autosummary:: :toctree: generated/ Chebyshev Basics ------ .. autosummary:: :toctree: generated/ chebval chebval2d chebval3d chebgrid2d chebgrid3d chebroots chebfromroots Fitting ------- .. autosummary:: :toctree: generated/ chebfit chebvander chebvander2d chebvander3d Calculus -------- .. autosummary:: :toctree: generated/ chebder chebint Algebra ------- .. autosummary:: :toctree: generated/ chebadd chebsub chebmul chebmulx chebdiv chebpow Quadrature ---------- .. autosummary:: :toctree: generated/ chebgauss chebweight Miscellaneous ------------- .. autosummary:: :toctree: generated/ chebcompanion chebdomain chebzero chebone chebx chebtrim chebline cheb2poly poly2cheb numpy-1.8.2/doc/source/reference/routines.matlib.rst0000664000175100017510000000115512370216242023701 0ustar vagrantvagrant00000000000000Matrix library (:mod:`numpy.matlib`) ************************************ .. currentmodule:: numpy This module contains all functions in the :mod:`numpy` namespace, with the following replacement functions that return :class:`matrices ` instead of :class:`ndarrays `. .. currentmodule:: numpy Functions that are also in the numpy namespace and return matrices .. autosummary:: mat matrix asmatrix bmat Replacement functions in `matlib` .. currentmodule:: numpy.matlib .. autosummary:: :toctree: generated/ empty zeros ones eye identity repmat rand randn numpy-1.8.2/doc/source/reference/routines.polynomials.legendre.rst0000664000175100017510000000245512370216242026567 0ustar vagrantvagrant00000000000000Legendre Module (:mod:`numpy.polynomial.legendre`) ================================================== .. versionadded:: 1.6.0 .. currentmodule:: numpy.polynomial.legendre This module provides a number of objects (mostly functions) useful for dealing with Legendre series, including a `Legendre` class that encapsulates the usual arithmetic operations. (General information on how this module represents and works with such polynomials is in the docstring for its "parent" sub-package, `numpy.polynomial`). Legendre Class -------------- .. autosummary:: :toctree: generated/ Legendre Basics ------ .. autosummary:: :toctree: generated/ legval legval2d legval3d leggrid2d leggrid3d legroots legfromroots Fitting ------- .. autosummary:: :toctree: generated/ legfit legvander legvander2d legvander3d Calculus -------- .. autosummary:: :toctree: generated/ legder legint Algebra ------- .. autosummary:: :toctree: generated/ legadd legsub legmul legmulx legdiv legpow Quadrature ---------- .. autosummary:: :toctree: generated/ leggauss legweight Miscellaneous ------------- .. autosummary:: :toctree: generated/ legcompanion legdomain legzero legone legx legtrim legline leg2poly poly2leg numpy-1.8.2/doc/source/reference/routines.other.rst0000664000175100017510000000050012370216242023543 0ustar vagrantvagrant00000000000000Miscellaneous routines ********************** .. toctree:: .. currentmodule:: numpy Buffer objects -------------- .. autosummary:: :toctree: generated/ getbuffer newbuffer Performance tuning ------------------ .. autosummary:: :toctree: generated/ alterdot restoredot setbufsize getbufsize numpy-1.8.2/doc/source/reference/c-api.generalized-ufuncs.rst0000664000175100017510000002033212370216243025343 0ustar vagrantvagrant00000000000000================================== Generalized Universal Function API ================================== There is a general need for looping over not only functions on scalars but also over functions on vectors (or arrays), as explained on http://scipy.org/scipy/numpy/wiki/GeneralLoopingFunctions. We propose to realize this concept by generalizing the universal functions (ufuncs), and provide a C implementation that adds ~500 lines to the numpy code base. In current (specialized) ufuncs, the elementary function is limited to element-by-element operations, whereas the generalized version supports "sub-array" by "sub-array" operations. The Perl vector library PDL provides a similar functionality and its terms are re-used in the following. Each generalized ufunc has information associated with it that states what the "core" dimensionality of the inputs is, as well as the corresponding dimensionality of the outputs (the element-wise ufuncs have zero core dimensions). The list of the core dimensions for all arguments is called the "signature" of a ufunc. For example, the ufunc numpy.add has signature ``(),()->()`` defining two scalar inputs and one scalar output. Another example is (see the GeneralLoopingFunctions page) the function ``inner1d(a,b)`` with a signature of ``(i),(i)->()``. This applies the inner product along the last axis of each input, but keeps the remaining indices intact. For example, where ``a`` is of shape ``(3,5,N)`` and ``b`` is of shape ``(5,N)``, this will return an output of shape ``(3,5)``. The underlying elementary function is called 3*5 times. In the signature, we specify one core dimension ``(i)`` for each input and zero core dimensions ``()`` for the output, since it takes two 1-d arrays and returns a scalar. By using the same name ``i``, we specify that the two corresponding dimensions should be of the same size (or one of them is of size 1 and will be broadcasted). The dimensions beyond the core dimensions are called "loop" dimensions. In the above example, this corresponds to ``(3,5)``. The usual numpy "broadcasting" rules apply, where the signature determines how the dimensions of each input/output object are split into core and loop dimensions: #. While an input array has a smaller dimensionality than the corresponding number of core dimensions, 1's are pre-pended to its shape. #. The core dimensions are removed from all inputs and the remaining dimensions are broadcasted; defining the loop dimensions. #. The output is given by the loop dimensions plus the output core dimensions. Definitions ----------- Elementary Function Each ufunc consists of an elementary function that performs the most basic operation on the smallest portion of array arguments (e.g. adding two numbers is the most basic operation in adding two arrays). The ufunc applies the elementary function multiple times on different parts of the arrays. The input/output of elementary functions can be vectors; e.g., the elementary function of inner1d takes two vectors as input. Signature A signature is a string describing the input/output dimensions of the elementary function of a ufunc. See section below for more details. Core Dimension The dimensionality of each input/output of an elementary function is defined by its core dimensions (zero core dimensions correspond to a scalar input/output). The core dimensions are mapped to the last dimensions of the input/output arrays. Dimension Name A dimension name represents a core dimension in the signature. Different dimensions may share a name, indicating that they are of the same size (or are broadcastable). Dimension Index A dimension index is an integer representing a dimension name. It enumerates the dimension names according to the order of the first occurrence of each name in the signature. Details of Signature -------------------- The signature defines "core" dimensionality of input and output variables, and thereby also defines the contraction of the dimensions. The signature is represented by a string of the following format: * Core dimensions of each input or output array are represented by a list of dimension names in parentheses, ``(i_1,...,i_N)``; a scalar input/output is denoted by ``()``. Instead of ``i_1``, ``i_2``, etc, one can use any valid Python variable name. * Dimension lists for different arguments are separated by ``","``. Input/output arguments are separated by ``"->"``. * If one uses the same dimension name in multiple locations, this enforces the same size (or broadcastable size) of the corresponding dimensions. The formal syntax of signatures is as follows:: ::= "->" ::= ::= ::= nil | | "," ::= "(" ")" ::= nil | | "," ::= valid Python variable name Notes: #. All quotes are for clarity. #. Core dimensions that share the same name must be broadcastable, as the two ``i`` in our example above. Each dimension name typically corresponding to one level of looping in the elementary function's implementation. #. White spaces are ignored. Here are some examples of signatures: +-------------+------------------------+-----------------------------------+ | add | ``(),()->()`` | | +-------------+------------------------+-----------------------------------+ | inner1d | ``(i),(i)->()`` | | +-------------+------------------------+-----------------------------------+ | sum1d | ``(i)->()`` | | +-------------+------------------------+-----------------------------------+ | dot2d | ``(m,n),(n,p)->(m,p)`` | matrix multiplication | +-------------+------------------------+-----------------------------------+ | outer_inner | ``(i,t),(j,t)->(i,j)`` | inner over the last dimension, | | | | outer over the second to last, | | | | and loop/broadcast over the rest. | +-------------+------------------------+-----------------------------------+ C-API for implementing Elementary Functions ------------------------------------------- The current interface remains unchanged, and ``PyUFunc_FromFuncAndData`` can still be used to implement (specialized) ufuncs, consisting of scalar elementary functions. One can use ``PyUFunc_FromFuncAndDataAndSignature`` to declare a more general ufunc. The argument list is the same as ``PyUFunc_FromFuncAndData``, with an additional argument specifying the signature as C string. Furthermore, the callback function is of the same type as before, ``void (*foo)(char **args, intp *dimensions, intp *steps, void *func)``. When invoked, ``args`` is a list of length ``nargs`` containing the data of all input/output arguments. For a scalar elementary function, ``steps`` is also of length ``nargs``, denoting the strides used for the arguments. ``dimensions`` is a pointer to a single integer defining the size of the axis to be looped over. For a non-trivial signature, ``dimensions`` will also contain the sizes of the core dimensions as well, starting at the second entry. Only one size is provided for each unique dimension name and the sizes are given according to the first occurrence of a dimension name in the signature. The first ``nargs`` elements of ``steps`` remain the same as for scalar ufuncs. The following elements contain the strides of all core dimensions for all arguments in order. For example, consider a ufunc with signature ``(i,j),(i)->()``. In this case, ``args`` will contain three pointers to the data of the input/output arrays ``a``, ``b``, ``c``. Furthermore, ``dimensions`` will be ``[N, I, J]`` to define the size of ``N`` of the loop and the sizes ``I`` and ``J`` for the core dimensions ``i`` and ``j``. Finally, ``steps`` will be ``[a_N, b_N, c_N, a_i, a_j, b_i]``, containing all necessary strides. numpy-1.8.2/doc/source/reference/arrays.classes.rst0000664000175100017510000003265712370216243023533 0ustar vagrantvagrant00000000000000######################### Standard array subclasses ######################### .. currentmodule:: numpy The :class:`ndarray` in NumPy is a "new-style" Python built-in-type. Therefore, it can be inherited from (in Python or in C) if desired. Therefore, it can form a foundation for many useful classes. Often whether to sub-class the array object or to simply use the core array component as an internal part of a new class is a difficult decision, and can be simply a matter of choice. NumPy has several tools for simplifying how your new object interacts with other array objects, and so the choice may not be significant in the end. One way to simplify the question is by asking yourself if the object you are interested in can be replaced as a single array or does it really require two or more arrays at its core. Note that :func:`asarray` always returns the base-class ndarray. If you are confident that your use of the array object can handle any subclass of an ndarray, then :func:`asanyarray` can be used to allow subclasses to propagate more cleanly through your subroutine. In principal a subclass could redefine any aspect of the array and therefore, under strict guidelines, :func:`asanyarray` would rarely be useful. However, most subclasses of the arrayobject will not redefine certain aspects of the array object such as the buffer interface, or the attributes of the array. One important example, however, of why your subroutine may not be able to handle an arbitrary subclass of an array is that matrices redefine the "*" operator to be matrix-multiplication, rather than element-by-element multiplication. Special attributes and methods ============================== .. seealso:: :ref:`Subclassing ndarray ` Numpy provides several hooks that subclasses of :class:`ndarray` can customize: .. function:: __array_finalize__(self) This method is called whenever the system internally allocates a new array from *obj*, where *obj* is a subclass (subtype) of the :class:`ndarray`. It can be used to change attributes of *self* after construction (so as to ensure a 2-d matrix for example), or to update meta-information from the "parent." Subclasses inherit a default implementation of this method that does nothing. .. function:: __array_prepare__(array, context=None) At the beginning of every :ref:`ufunc `, this method is called on the input object with the highest array priority, or the output object if one was specified. The output array is passed in and whatever is returned is passed to the ufunc. Subclasses inherit a default implementation of this method which simply returns the output array unmodified. Subclasses may opt to use this method to transform the output array into an instance of the subclass and update metadata before returning the array to the ufunc for computation. .. function:: __array_wrap__(array, context=None) At the end of every :ref:`ufunc `, this method is called on the input object with the highest array priority, or the output object if one was specified. The ufunc-computed array is passed in and whatever is returned is passed to the user. Subclasses inherit a default implementation of this method, which transforms the array into a new instance of the object's class. Subclasses may opt to use this method to transform the output array into an instance of the subclass and update metadata before returning the array to the user. .. data:: __array_priority__ The value of this attribute is used to determine what type of object to return in situations where there is more than one possibility for the Python type of the returned object. Subclasses inherit a default value of 1.0 for this attribute. .. function:: __array__([dtype]) If a class having the :obj:`__array__` method is used as the output object of an :ref:`ufunc `, results will be written to the object returned by :obj:`__array__`. Matrix objects ============== .. index:: single: matrix :class:`matrix` objects inherit from the ndarray and therefore, they have the same attributes and methods of ndarrays. There are six important differences of matrix objects, however, that may lead to unexpected results when you use matrices but expect them to act like arrays: 1. Matrix objects can be created using a string notation to allow Matlab-style syntax where spaces separate columns and semicolons (';') separate rows. 2. Matrix objects are always two-dimensional. This has far-reaching implications, in that m.ravel() is still two-dimensional (with a 1 in the first dimension) and item selection returns two-dimensional objects so that sequence behavior is fundamentally different than arrays. 3. Matrix objects over-ride multiplication to be matrix-multiplication. **Make sure you understand this for functions that you may want to receive matrices. Especially in light of the fact that asanyarray(m) returns a matrix when m is a matrix.** 4. Matrix objects over-ride power to be matrix raised to a power. The same warning about using power inside a function that uses asanyarray(...) to get an array object holds for this fact. 5. The default __array_priority\__ of matrix objects is 10.0, and therefore mixed operations with ndarrays always produce matrices. 6. Matrices have special attributes which make calculations easier. These are .. autosummary:: :toctree: generated/ matrix.T matrix.H matrix.I matrix.A .. warning:: Matrix objects over-ride multiplication, '*', and power, '**', to be matrix-multiplication and matrix power, respectively. If your subroutine can accept sub-classes and you do not convert to base- class arrays, then you must use the ufuncs multiply and power to be sure that you are performing the correct operation for all inputs. The matrix class is a Python subclass of the ndarray and can be used as a reference for how to construct your own subclass of the ndarray. Matrices can be created from other matrices, strings, and anything else that can be converted to an ``ndarray`` . The name "mat "is an alias for "matrix "in NumPy. .. autosummary:: :toctree: generated/ matrix asmatrix bmat Example 1: Matrix creation from a string >>> a=mat('1 2 3; 4 5 3') >>> print (a*a.T).I [[ 0.2924 -0.1345] [-0.1345 0.0819]] Example 2: Matrix creation from nested sequence >>> mat([[1,5,10],[1.0,3,4j]]) matrix([[ 1.+0.j, 5.+0.j, 10.+0.j], [ 1.+0.j, 3.+0.j, 0.+4.j]]) Example 3: Matrix creation from an array >>> mat(random.rand(3,3)).T matrix([[ 0.7699, 0.7922, 0.3294], [ 0.2792, 0.0101, 0.9219], [ 0.3398, 0.7571, 0.8197]]) Memory-mapped file arrays ========================= .. index:: single: memory maps .. currentmodule:: numpy Memory-mapped files are useful for reading and/or modifying small segments of a large file with regular layout, without reading the entire file into memory. A simple subclass of the ndarray uses a memory-mapped file for the data buffer of the array. For small files, the over-head of reading the entire file into memory is typically not significant, however for large files using memory mapping can save considerable resources. Memory-mapped-file arrays have one additional method (besides those they inherit from the ndarray): :meth:`.flush() ` which must be called manually by the user to ensure that any changes to the array actually get written to disk. .. note:: Memory-mapped arrays use the the Python memory-map object which (prior to Python 2.5) does not allow files to be larger than a certain size depending on the platform. This size is always < 2GB even on 64-bit systems. .. autosummary:: :toctree: generated/ memmap memmap.flush Example: >>> a = memmap('newfile.dat', dtype=float, mode='w+', shape=1000) >>> a[10] = 10.0 >>> a[30] = 30.0 >>> del a >>> b = fromfile('newfile.dat', dtype=float) >>> print b[10], b[30] 10.0 30.0 >>> a = memmap('newfile.dat', dtype=float) >>> print a[10], a[30] 10.0 30.0 Character arrays (:mod:`numpy.char`) ==================================== .. seealso:: :ref:`routines.array-creation.char` .. index:: single: character arrays .. note:: The `chararray` class exists for backwards compatibility with Numarray, it is not recommended for new development. Starting from numpy 1.4, if one needs arrays of strings, it is recommended to use arrays of `dtype` `object_`, `string_` or `unicode_`, and use the free functions in the `numpy.char` module for fast vectorized string operations. These are enhanced arrays of either :class:`string_` type or :class:`unicode_` type. These arrays inherit from the :class:`ndarray`, but specially-define the operations ``+``, ``*``, and ``%`` on a (broadcasting) element-by-element basis. These operations are not available on the standard :class:`ndarray` of character type. In addition, the :class:`chararray` has all of the standard :class:`string ` (and :class:`unicode`) methods, executing them on an element-by-element basis. Perhaps the easiest way to create a chararray is to use :meth:`self.view(chararray) ` where *self* is an ndarray of str or unicode data-type. However, a chararray can also be created using the :meth:`numpy.chararray` constructor, or via the :func:`numpy.char.array ` function: .. autosummary:: :toctree: generated/ chararray core.defchararray.array Another difference with the standard ndarray of str data-type is that the chararray inherits the feature introduced by Numarray that white-space at the end of any element in the array will be ignored on item retrieval and comparison operations. .. _arrays.classes.rec: Record arrays (:mod:`numpy.rec`) ================================ .. seealso:: :ref:`routines.array-creation.rec`, :ref:`routines.dtype`, :ref:`arrays.dtypes`. Numpy provides the :class:`recarray` class which allows accessing the fields of a record/structured array as attributes, and a corresponding scalar data type object :class:`record`. .. currentmodule:: numpy .. autosummary:: :toctree: generated/ recarray record Masked arrays (:mod:`numpy.ma`) =============================== .. seealso:: :ref:`maskedarray` Standard container class ======================== .. currentmodule:: numpy For backward compatibility and as a standard "container "class, the UserArray from Numeric has been brought over to NumPy and named :class:`numpy.lib.user_array.container` The container class is a Python class whose self.array attribute is an ndarray. Multiple inheritance is probably easier with numpy.lib.user_array.container than with the ndarray itself and so it is included by default. It is not documented here beyond mentioning its existence because you are encouraged to use the ndarray class directly if you can. .. autosummary:: :toctree: generated/ numpy.lib.user_array.container .. index:: single: user_array single: container class Array Iterators =============== .. currentmodule:: numpy .. index:: single: array iterator Iterators are a powerful concept for array processing. Essentially, iterators implement a generalized for-loop. If *myiter* is an iterator object, then the Python code:: for val in myiter: ... some code involving val ... calls ``val = myiter.next()`` repeatedly until :exc:`StopIteration` is raised by the iterator. There are several ways to iterate over an array that may be useful: default iteration, flat iteration, and :math:`N`-dimensional enumeration. Default iteration ----------------- The default iterator of an ndarray object is the default Python iterator of a sequence type. Thus, when the array object itself is used as an iterator. The default behavior is equivalent to:: for i in range(arr.shape[0]): val = arr[i] This default iterator selects a sub-array of dimension :math:`N-1` from the array. This can be a useful construct for defining recursive algorithms. To loop over the entire array requires :math:`N` for-loops. >>> a = arange(24).reshape(3,2,4)+10 >>> for val in a: ... print 'item:', val item: [[10 11 12 13] [14 15 16 17]] item: [[18 19 20 21] [22 23 24 25]] item: [[26 27 28 29] [30 31 32 33]] Flat iteration -------------- .. autosummary:: :toctree: generated/ ndarray.flat As mentioned previously, the flat attribute of ndarray objects returns an iterator that will cycle over the entire array in C-style contiguous order. >>> for i, val in enumerate(a.flat): ... if i%5 == 0: print i, val 0 10 5 15 10 20 15 25 20 30 Here, I've used the built-in enumerate iterator to return the iterator index as well as the value. N-dimensional enumeration ------------------------- .. autosummary:: :toctree: generated/ ndenumerate Sometimes it may be useful to get the N-dimensional index while iterating. The ndenumerate iterator can achieve this. >>> for i, val in ndenumerate(a): ... if sum(i)%5 == 0: print i, val (0, 0, 0) 10 (1, 1, 3) 25 (2, 0, 3) 29 (2, 1, 2) 32 Iterator for broadcasting ------------------------- .. autosummary:: :toctree: generated/ broadcast The general concept of broadcasting is also available from Python using the :class:`broadcast` iterator. This object takes :math:`N` objects as inputs and returns an iterator that returns tuples providing each of the input sequence elements in the broadcasted result. >>> for val in broadcast([[1,0],[2,3]],[0,1]): ... print val (1, 0) (0, 1) (2, 0) (3, 1) numpy-1.8.2/doc/source/reference/routines.datetime.rst0000664000175100017510000000043412370216242024224 0ustar vagrantvagrant00000000000000.. _routines.datetime: Datetime Support Functions ************************** .. currentmodule:: numpy Business Day Functions ====================== .. currentmodule:: numpy .. autosummary:: :toctree: generated/ busdaycalendar is_busday busday_offset busday_count numpy-1.8.2/doc/source/reference/figures/0000775000175100017510000000000012371375427021506 5ustar vagrantvagrant00000000000000numpy-1.8.2/doc/source/reference/figures/threefundamental.fig0000664000175100017510000000361612370216242025515 0ustar vagrantvagrant00000000000000#FIG 3.2 Landscape Center Inches Letter 100.00 Single -2 1200 2 6 1950 2850 4350 3450 2 2 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 5 1950 2850 4350 2850 4350 3450 1950 3450 1950 2850 2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 2 2550 2850 2550 3450 2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 2 3150 2850 3150 3450 2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 2 3750 2850 3750 3450 -6 2 2 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 5 5100 2850 7500 2850 7500 3450 5100 3450 5100 2850 2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 2 5700 2850 5700 3450 2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 2 6300 2850 6300 3450 2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 2 6900 2850 6900 3450 2 4 0 1 0 7 50 -1 -1 0.000 0 0 7 0 0 5 7800 3600 7800 2700 525 2700 525 3600 7800 3600 2 2 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 5 675 2850 1725 2850 1725 3450 675 3450 675 2850 2 2 0 4 0 7 50 -1 -1 0.000 0 0 -1 0 0 5 5700 2850 6300 2850 6300 3450 5700 3450 5700 2850 2 2 0 4 0 7 50 -1 -1 0.000 0 0 -1 0 0 5 5700 1725 6300 1725 6300 2325 5700 2325 5700 1725 2 4 0 1 0 7 50 -1 -1 0.000 0 0 7 0 0 5 6450 2475 6450 1275 5550 1275 5550 2475 6450 2475 2 2 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 5 5700 1350 6300 1350 6300 1575 5700 1575 5700 1350 2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 1 0 3 2 1 1.00 60.00 120.00 900 2850 900 1875 1575 1875 2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 1 0 2 2 1 1.00 60.00 120.00 3375 1800 5550 1800 2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 1 0 2 2 1 1.00 60.00 120.00 6000 2850 6000 2325 2 4 0 1 0 7 50 -1 -1 0.000 0 0 7 0 0 5 3375 2100 3375 1575 1575 1575 1575 2100 3375 2100 4 0 0 50 -1 18 14 0.0000 4 165 720 825 3225 header\001 4 0 0 50 -1 2 40 0.0000 4 105 450 4500 3225 ...\001 4 0 0 50 -1 18 14 0.0000 4 210 810 3600 3900 ndarray\001 4 0 0 50 -1 18 14 0.0000 4 165 630 6600 2175 scalar\001 4 0 0 50 -1 18 14 0.0000 4 165 540 6600 1950 array\001 4 0 0 50 -1 16 12 0.0000 4 135 420 5775 1500 head\001 4 0 0 50 -1 18 14 0.0000 4 210 975 1950 1875 data-type\001 numpy-1.8.2/doc/source/reference/figures/dtype-hierarchy.pdf0000664000175100017510000017050312370216242025274 0ustar vagrantvagrant00000000000000%PDF-1.4 %Çì¢ 5 0 obj <> stream xœ¬}¹–,»n¥¿"í6ª9_оd¾%ëh2ªŒVúýæÞ ™µ´žñî5êÉˆà€˜üßWøŠ¯€ÿí¿þ÷?õ×ü¿¿þöÊõkÎY^ÿ²àÿúWjhµ×ÿÅþ¯ú?¥ÞûWʯšçøŠã5Âüšc¼Jª_qÆ×ýÛ_ÿl½ÿë?þJ3µW­9}þúY;Â$|Õôú¤ÕYßêíµÚ‰¯¯©|…ˆvùü}Áûëž_9-H\_®«GÍ_a =¾úD{~ŸÛx¢Õ¯:¯=¨EÝ×Jb÷5ÃÖ4„QV±Í!Œ¯„!ø•5«ZøÀHê°V/½Ø,«µfƯ­&Ç[æWÒxz[kÈ9>ÐÆWåókFQ3(q·mΡ\=ÖßÄopð«±Zuëú‡ ÿÕû‚´ UJY“êñ+´«½F74 ‡ÌõDFªY­Æ SGÇõ¾5Éʲ¶®Åô1ï\¾zD»cøÚl´SÄïœFåR4¬,Q#'Þ0X|²½AmnÝÀ×N,ß°†Îâ¶X}'üy¿fãZ~Bj _ãÈ£Yí*$]û1ʹöÓP°Ù†Ï¯X3 Ü⪥[+Ñ1ó¾¶ Û³ˆ£j–% Ah_=Ú¢"4‹Xm·mÇg»zîãjwì ÛQcüêšûnç ™û×9üU¸ã‡¹{ý«ã#c.?¤¯ºŒ¤·ÈgŠIgmmgٔȕ\“ê¢ÄÆv^|“ »Á½l"ÿy¡bËö8Ø+[Ð2ÑÉ€Ñ(i 0õ«½¦ç½ÿu.zè"]w A#\ŸhÓØh1â_ë›´‹¹át«"E‘µñ&Y®kJ¶d-ÓÂ~Â…uñË×y ’ƒzîÄŸ¿þý¯žw[ûžÖîä°È²’ ×SÀÛ†hcýN¼ÚY(²F´Þ³Þa|l(cA$âY²‘WÆóÛjûª'JÔ‚zñw½3.¦¨ªŠ·…ÎI`úØÔµp«mØ$®Ó^L´hPYd×ñ‰HÒh‹R¦¾P°œ±€àÑ?ãÉØ %m±æ°0üb!k’…|lwöäëù…#¹<¾0: Þ‡0£˜+X¯öàjâ á±Æ½š@ÜÅR´6)‹/Æ‹›òØ» nCdŸàpkšX³Æ©agbÂZصëúêb uˆžÆUšÑS†r7Gßm<±°9õ«ÇÚ~c­g¶6 ä±öT`Cã¡¿šä©Bz¢é=±µ$ëtü*ϼ!ß‚p³ã)¾5“*?šŒJ‹Ðp±ŽšŒÈУùž‘¹é=_dº£’£î8Œ†ÞàË©ob‰VëÛÅ íGÑ '>ùœ©4®—Õ¼åŸÙÇMŽë_-þ ÁÐ!ëÛÙP:¬ÁÅ.Ò¥x~Ûq‘Ö/}œã"­u)ó>.Òb)žã"-yõ: Ò:K¹O‹”¢hÆ{¬EÌsŸiÉ2qܧEœMŒÒN‹¸ŽÄr oî³ÂvTÄE›!oF÷ë,wNŽàlq^†‹nÒ‡ˆ<›²0Ç1®Ð.Úõ†…^±?¾QnžAtm¹Ÿ»½O‹ÑiÁv:§ÚÝ÷i‘–Ðr>§EZÈÒ9-.žÓ"Å*•bŸ){uZ¤5ÁÒÎY€Ý|iíz¼~_ Óã9+Ré: öYtÉù©šp`‡ÅŽÞóÚ‡úôv€ÄsV$ç|vV࣒ðü¬HëtÄY‘ç×I€=¯í&á”L*ô‘„µÏ ,fÚ" Ñ*ˆÝÚYyÌ~Ί·yñ¬H‹ƒåvŸ9'Ã:d¨yü‰ÜWBª1¨1µe:2ö5–ÅHƒ‡õ/.$e‡Ãb‘âÔ†âk¸ãd(ów‡)¡`´—î1‹;qµ5 >°Æ2Èl²%]3Yíl£Öç8o9›£l7dµ ¶ohSó+À<±þ%1­£—Ü oB¸G³I™ àä´r”°ÓF/™€’;Þqµ‡“ö†lÞû¶‹ä½Ù%þB<ÿ¹ Y‡ötX~…è©ï÷\ƒ3»ÏÁÏäŒúí=uY›È^|a½»¸aEÇse‘ÒYh¼šI Ú¢¹Õa½¢A€Y€êï¼4H¡(¢½•yœ¡@Öo÷‘QÅÝ#/ñ€Òb!»ÌyH¬XgwdñH%*eÝÕ®G½èW{q[ÛC‡@Fç]¦”9AY|#ñ.T§—‘ö‰ŽÐ’Äžg–·°¿ û׫ O™……ÑuÄ`ÊaÞÔU$勼²íàâk«ì& κ”`–• {ÂjQÓ¢€ˆe-¦µ.h&mDžQúªÚKXkIJö2IwO;‡ý.yE2Ò|úƒ\U"©lÓ'æ•"7fž.¡¼@ßmƈ#Ž›4cíÍÚ“á²6L3AéŒÙíµ#IO8¤“³ê Ib~£eµt yL…¦í!¾Ù±æÛsν²ö™8ë=ÀºªΈ…HÝžh6(,-­7KÒÄ~æ,Ê‚â‰<)Múý:ûkõ«zØP×_ÚP×!C¢-EúÓÏÀ@RÄŽIý7È’±šÐ̃ `tw‚HP¸dMÎâêÞæAέ>=–áb@XºÄ:sùÕ]¤Yß l¹”‡€wÖfBP*¬a×™‹Yñ ;«=°ÊkÜ«ºÚS£ZbG´oLp›ÞRªz ¬F¦ë´9ÅâOŒ³‚”Ù÷H]»ºPð†`_l&~†âñj`3‡‘%2®eâ¶þ]m؇ ¸b¡4Àª83›IeïÁÓ8Á^1lðt2{ÛDÒگГ^È¥[øUº¾?µ`öT@ÙKô¡|â플r-ÌýtÒ-Õ¡ßé€u*6;i&þµºP+ZmÚV»ÀäNAa”Ýþ#I!Ý= Tð U¾Ã-siòŒ SGÄâ/|bPeƒ@4+šfK¥`ð‰ÅÉQàyµ†¹<8æ±e‰ìyøÁŸ1ÌI£ ÛÄïuZµv·Ç×~€€Mˆy±‘X…Äê'µCÍûlì[È:›"À«My“s§*¶Ö€Ú\-®÷¤íoµ)ssjvþ%¢ÝšüÄrp*ÛCSYØSËnS˜[ÿº:¸3ô<ƈ³Æ¿ \{^°“k°k Õ Ÿ«´>s &\Baउ¶ŽC°•qš‘üáÏÆ±k—ÎÓÇoƒ½OLòNòó{ r^TU“ß Žš F<‹p!6è˜ÓxšTIV¨cÇx÷ÌR„žhrN’dfÔG %Åiƒ ¨„.¶·Æ–§‹–D¦§çPåbnõÑàôÝ^,áIÿä µÐŠpñ:yXè(“æZêH¥­ªå$RÈ3 ŒpQ=Œ DMbyÌ{…\ÅøÆâ+°>Ànx@©Òs]è^Ù†i6ct…|)c¯“ ‘rá…Œ0ØPYвsc!–Sî[bVš4¥:Ø0ãÝv4oH¨ö‰x4T~!|ñhn²‹dø¼xuê)œt¼¤.S¼åή]=Öd¦IP ÷–ó½¾oò½]‘¶„Ÿ´°vÙIœÙnà!k"J Ç »,H¢!<Ω ែÏ>V)þ_ç*¦Ú»RbÈÚ`Š`kWÄ¥÷‡hÜì䄎všqÊ# ‹A‚òhÉ0:Òˆ ±àšÉ²p¹eÆÒææM9é!ÍÀ{¬Ó…dÛl–]²¸ Hœ„Ûà‹:ë¼FX®Ý² nÔ:Mä¶Öa²v§ m CP¥iƒ±'\{h–md pƒNŸõ²J„ZÊÿF1Û"²45›ÈÁ³·b½zd‘0G´u2ŠÑ¤07P[K¿‰I9õjBÂ+ê.À¢-h/xÚõi¯ÏF½C¬4ã(|¢0¬bó‹&ØÅQ0ÉûXoÝNm0®?¾±Hr-…—e¿Ú˜ØYìÙNß`f@{Pœ#ëÁ`ÙcC°›ð´‘Öä i9˜Œ;©<¶LŸ‹Äsm‰°“.ÒÕnb FYØÌq“^¾~‡ÛÓEb<·'¹Tr\­`Àjó”¢H GÉ~ÞsZ3©ä'è#e”oALTÁÉŽ—RE[ç1ykFŠéK¦®kÄe"j´‡ýn§Íu1ÍÕ{(GÂGÓBJ-Ìf&j á‘¢BJCô›©¯¿OŒäÙ£ñ±}f:äHÍÆèù+¤pS ©zj1t}}£ø‰¹šYôwŒ } Ї‹™!zîv" ½{¡}å"€^$Êx‡J0_Ù®´+5F°jíi•’_”j UT™®Ê³Óß,|°ÁØH­´ÎcäZÓˆÞópÓb,i¿½ãLoCXê?cPRG,Xÿ=±$©@©7 b<È!‡EošÌ ´ TÞS•¾ÿªªMùâÈ}žú„È0ö€TúͦôݯìÓ3µaëo]$ À©†EŸ]\ŒýT®‡þ0HQ œÕÕ’:Ð| Od*òÖĹ™kJÐ 2i¥«×£ÀslâÀ¹LΪ˜LÑŒYË„W ŠŽ«]e*T› âŒÞèÞô†l£&UwÆ¢p^2Æ@ZÝ|&#Â.;ýn·!óÍÙû‘mµ?!{_÷SM$ïC²™5ÉX$X„d!xŒ…¤±Píßÿj¡qRjZ€ØT³ÌĤšÕ޲jHªii©—P³¨kšéŒBMCdÔ‘[XøPê%Ó,y~ÒÞd:'Í&ÒT:ÆyDš¥T—gê”ÞšÓv‰æ@$Òài±W7|}¾¤ ~¾‰†Ã G‚YFhÆÐ9Ã1®…Ѭç E‚áþÆZDã•W}¸ÜÕ¯¶I4€ÚG¢a»ßME¼(iÀ%šŠˆÒp$šÕ&ów‰fM4“å»D³2ü™D³Ô(™tMbáVöK¢ia[õ¬‚âŽHÓÞT³‹4ÄÙ3)Ò¬u2•H"Í;vÞ“r‘†}8qi!qK¦á[Ó‘iøU v.Ó,H9V~ ¢ß9-¹ã—©O üèêÓ€Û¾›V2Ý" ׺‘†¡,‘æ}bHœÞÄs´0»#Ø[;'»¸Ë¼í- ³ômH ÇîN² IØWéZ’ˆp^;º|µ›,uÙÂxdˆ)+šº!Ú'S$[øˆ¦yo0="lLoÇQ‹…në|*÷tÐ'ÜR¾'=!1¼¨|΢¹TÍ{0µYh»y[Iðdžà4ΨS°ù¹ n@YÚOÒ?!zêûã=äìÛîs¦îïù€\}¾‡£N¡]ÆG¼Zk÷c9ƒ¶‡>nj)È.Ôk2ŽÛl›·×èÞ‰WPW|™]¨Á;Dû¡Û…Ä­Á´ µTÝ8…óc5«ŽS· 5x¨²ÎÄ8I+ ]¨%Y®·a¨ÁFF-ÃÛÔòdºÚf:†}dm†šÅ ËPC|‘ö„–¡–dÔݧ*¶ûtÃR–«ƒ"ãÝ0´7ÔíBo;|m–[… hcÜ(ÔDŠq£PƒÓ¬mjÉN0gÓÉøÝaäØÝ|uÈæ?“Qh­B1™ÀŒBgweZ+ge…NÓB"£_Ðl7³¾]ݰ/ª´ q„ãh•œƒt"çÑ QwØÍ,ÎCŠ8/s¯Y…Â×H”2 í…–Uèm#È¢Ó=ä²r÷9BVžAJ´ Y¦£|„¬¬ û-d!<¤>¤¬ ͼ)+Ãtt„¨F×¼1—‡–³Ëa<ä|t)1«ÁŶ¤Õàß,ÇttÚ.iˆ$-½à˜mø'q‰ACKGPÂÃ16¯I$Ù46ÛÁ4ç%ŒåžuØû`ßA ÂÕovÈ~b¥Fû P¹„,) =¤©'Û”Å}´všÚVÿª°«Ý£Â@'Bû«ŠÛ‡Î;Ùae£Ã„ö§Õn ‚ ¿áƒ®Ë 1ˆqN±è$mú ¯W;ÒÉøðˆ¶‚°*OËÕTà[x!n‰ yJ¾œvf|=Áx¶½¼r;àÎõ€=ML“¥¹Œ 2)iŒ½ŠÅ"Ç“Èu2ÿò¢cØ}àúNœ…–Uñ)ôÖô¨…¯¶OXµÂ?k¢?ܦãê“V¡V-~êóC_Hä›b`CDuÖ«I‘²\ËòD9¢!Ýð´SaXXÈ;´ÅÜÖÄ1ˆ_‚Ð0Þ3«Úk#"¥ÿÝ\_®2)]‚<¶ƒìb½ÇÑøD`è/}ç…=ø)ºÚ2EH% ÀÈĈuL°Í ¸EÝK¼Ûm~ªøÁ–8i9f.BœàöC\Õ$ñLINÎôìG´ÂíýÕýÄ'D õ€d,ÛˆSÇÂ,gÁÊŸ0˜á@¶"äAèQb›jC,„Ã8?é‡ûvj[ˆ2ýÁm×7W{ïUš“†7Ô"£ó¥W3R€]èÆhXNdÀ ò ãTÖ@Iªyðð‡ª¨ ›éÌú¢Íºù¯¡1ç`'Úëך ›y…6Ò‚nßc˜lÄiX«ÖºaaÀd1ä5t"«·“ Ó‚[èøÞàälßàn‰Ýâ‰Å_¸0ðá‰5È:Ÿ†y7ÝŒ>ÙR®Kié¼ÈÉ÷'‚Kç¹ žÂbcl§)ë.ú; âCl",××—¤«6>€`¿®9mò-g©Øq­tÀkœ8#èßÅ­%­õÒ gšv¬í¢š.ƒ»«=pPß<=FÛˆÝð†I_ é`LÇ—ÁØ!jSñ ŠªÂŸ'’Þ3ËÄì!2‚¦ ‚¹Nó¿Þýá[ûP AÂŽNyUð®,D\ÌMgJ…öa¢ïé ´pU×ÖO–tš×*$Xp~S[Ì‘gó ÕƒÂ% cCß§E …«.1&‰¯…¨§ $^•#€‹¤šÕ¶p›Æp¦ÕîŠão]Æùت) µi=Í…¤[£RdMô_Oâjÿ¾D5yGø<ÕßÏ„(ÆI‘IŒ$$€v!!ÄfÅ™.HQø Ø£è@óP“#žÅŽÓÖiWW°>¡ëT~˜r Àâ×<8ëÔ®Eñà\ †¦5bjÑ4ÖâÏ)L®Ö~hl<íÔ¥NÈzÄ€&kÅ'È)ðĆ*¬‹zBWõ‰CE£OÞ¹» UiÍ.ì'ÑFá~ð~Éð S4ÙÌ©)&åô@vsêå¬.˜ÓŒ¾õ>hÛÆÏÞP¹z|@ÀÉU³ Qy{j5‹Có®Í¤££qÃ;W²è(ÃH¶Z|7ºX,ùÃSP1Î'ž«Íëvb±ý >±Ÿbù&-ûÃÓG$ !enÿƒÙþ0Ñq ‘^*næ%¤k Ò ŒsZÌ:Í ’GÇE³)öEMÒ¢ÝÒ±ß{6A#R–ÃÖJ0i ‘ãB÷ìíÚëȘçÓÖM‘{ï3 À|‚£ªFØ»ñÉ ác¨G£À/¶‰m™i›SlWz¿Xmœ5kHÅÂK ƒåÎ*gí½ï9gïÃÄ—múTΑmú4ÂlÓaªiG¶cš8¹e›Þ%b™hÓ‘ræÈÚ±ûæmé¡5_=2¯ãnñnÿÚoñ¦GÅ»»xÓ£.>¸x³Û[¼Ùoð†’ŽdÑuù’=0 ®I' xˆ‡A0dâ!ßô¦c|÷è çØoIqyç¸ÃÓ¯QL ?4g··„s qØ>NW4ò%á ¦‚¼sK8=MÄ$LTqÉ’p·AÞ¸%œŽÓó8½Ð/¸Å—^é§¾„”yõhÞCNod¢—€¤¡ a"z9ΦÞÛP1Ö[ÀÁSeo¥ÎkNwªtù¦·a"¨ä›¾XK½¤—®ˆý‹P±áR‹»Do°˜Ò²]¼é¸yRL¼Á^ävÄ›·I‘H.¼[ÁÏìƒfØ}¹O@íºû´ ÝL>LfGf¹aèÐjg;1‰ŽÜ$.šed£9ÃîQŒ»Ñ] Új‹ê<ÏW»Û‰Úd&e>Ó™Ìf”iò£HÈ·WÍý^ëb”¶åú‹f½¬köoÚeÞÞîZ}’Æ»µP )-Mwf¸rÔ ƒmV»ÉòBÃÕi¦ij»CŽãm •§6b伉ˆÄÿ¹KÆÖ½#¤è)Ÿ€pã[™ ôÌo! = 86pŒfÜa²,…¥'ÝÊšŒ¿]éi&}7‰]%8õ-ŽnOz’2œÚ1éR„å`â"î%åÓæíN¡(™§oIc°!K¾æõ¾"»Æ+B™¼Ì]•Ï$ÑÌËQÐ#¬Í«IÌ-uz„ªt1‰Îj]]Âã¾t®]Ž¢÷‚izƼÚñ:ìîßÞÙ¿@ήÚC¿ˆß諸+<™i_ ô«(çF·’O§þ\®¹UK·;ÄTé™÷ËöiÖø£.%Þ´Yí¢ ñP*O›7ÄÒ¼.ý¨­UÜš`Ž+UvÍ"k.ƒÑú¸ôÃW½è2Š·[´eÞñmÝÓ`^®¨OfÞÒL¹²ë.i*;œnDòæQc»HßÁŽã )ø5ìÐSï d‡«Ít>qos©†¾á=pA›[d—óº%‡KÔbð.TÆ.îlq½· ´+Ü#dpKRti&¯#YÑÀ)ñNʬå;Êëd 1pÑ®™×©¥a.Ÿ˜Úvå$ï¬4{V&6ËÃÖ¿l±™ÍƒC ò¡„!Ü.ªÞ†s]WTÒƒä†Ä°fæäM HI}aHöK-‘·žI4¼›£;ë «$'ïY¨ÍÖ6Oïáë0¤ øB f9áZÛJvzsÎJw1³·½`D0Äfá±æÇîrue &ò0‹Ý6UVewd¸ç]äeóžµûñŠ2ê]ˆ£sïyVDº§Î+nÜ”ìr F"Vê²ê¨æ–òv—·‹':qö³XSÎ7®­Z¬=Am–Ù°2ÛFAd7ÇEiFP¨5ófïX¿Ð€Ö†8E˲sô$,€#G£ê–°IÒ†_¹c”M‘pÞ&5uA«ªòL¦!73?Ÿ)Gú9sá ÝÚ< $›‰×v¸ÉS»]íôÜ¡4L«™…pÉæºc»Ú&ÔS)À¤1ÝúÌ̈†©§qá2¼ñÂvF†èy-TUÚÂÑ-/–Ž™2ÑÕyÂ3ç°¥Ê)©UÄ(ä·ësk‰wò€Ð¡ö4›EP^Ê™í&5La¤Q¥6¢UƒŒ_¾—NS›„cJò–É$ÿ¿š9$fXì&Ð7Èã %ÖŽc%Ú‚‚X»#é@U„0‡œY±‹ëÃ4­¦Žš©+®$WÂE»ö“’¥W¬’Sc2Å, #»Nw;)Ãá¬W~Š )&©¦,úÎYšx¢®D~,z†úGJ‘VHíPÇ[”_WúMZà´h?"ô*î¦ÂsUt/ÙV½óµËAÎbtÙòDÖíƒá¨«™Z•¾„Y#íÜ×¥›„¨a•<„Õ³q`·KÀéÊÐaGζÈÖ3OÒ‚àƒÙZˆ‚––t¨´bé&IBôvÌw[·\½™¥,áqî~®â“^AòÉaHËÌ_ÌÛ£ì^ÌlégåH–tvŸ¦ƒ¬çô˜Y\-38‰:²„—ì÷ëBÔ¬r5«G»ÈfZ‡h2„/ÂÁ@ ŸÌ:·‹«ÑËnW¦7ýØM]í4~qœº:‚0;6c ðlÔ,H iÄ&kÔÑqŸTæ‚¿:ØzF&ª¢×]ÐÕ­H(ÜYÇ¥ñd)yã¶œè$+–Ý zœpߌÄðØž•|µK°K$â8Í/åpIñöÌo”,ófK$“gÜó”Vùr}¼Yfã@áý’›Ž±fü ͹Yþæl™y™´hQèÔoM‚ŽÂÖEšÙE4^)0t˜à1/4ÆÞ‡‡ØXi¼:TÑj¢4ò†_’žf–ò¥ÜQj‚ÔȢ܊é(?!zäûùk[?î…ÞO¿C.®xž'M4W#ü•¸ßQ²RоCtXGAÆ—ÆÂ;ÚK °œ¢vŽ5å'¼N:º“®‹ËD?èxë3J!~Ù´ Y'ñ Þ$ÝäcݾocŠŽf± tmF%ÔžR¢ÚÌ’"‡0¾ .Î(&R»„Þ]í%E芤·ƒ¥{Ù_`Ü»ìù7@–årC ›v»ª©µð&'~–ŠœKµÆkÒ–]Q¤ÄcòÔÍÏjê·Ø+amÞ,‘~FMpØ¡Ùtb¬+oŠf\CcÈ&^W≯0§‰¶¼^igÔ°; õâ½Ð‘y1¬JêWµj±˜¥&]ë:÷.ä‡q«jÆ 7ˆ2°Ï$*‰QvTù‘úˆÒUE~‡Vº…A•\°wª{«-«ëúIÐn´Û C^ç®ld«I5æ=¦7m³Á ýw¥t\ͪ½K̽ÚfÏ][A×õ¯pïÈÅÌÚ÷F‡¼dÚLÊ( Uu IO X@‰Ñªļ)±èÏ]”Øì„ž¤Äib£³|8¤¸]Þ£i®ºi´Ú&Jåi ”G2)Y׈}Ã+–ÓnѲlH—o uw ÞüÕFà±FÕŒší¡Ûìât&ÝÌ•íW‡lº äælK5ô T:¹:V&ç÷Ý€¨Q¡=$3åc)!چжý H0!ŠRnAB½b . &;šŠDkqAý4Æ„8ùì ÄÝ‚øèxL9xn¢qõ@r)q7óþñ4u¢³;’ôjGÂŽl¤‘¢¬ìvr6HÓ}B*Ó®†(ù,§×’H´ 6 HG¸ä†Æàr ZÜœb…aâ. #±‚Ä/¾S~Ýn¾S˜‡r^=†Yèþ-°£ò4Ý5͆6•"%O^}£}±à0öqR²¹UŠœ ߀•°Xü¹E`ØÇU*Xûh]ÔÁaf“ w3ª˜‡“ëǠȥ˜.¤÷rÁ»UÈP„¸ZºR%SC–áîgÑc“·›ÈH™ÂIEKõkö ¡ìÐ$jÙÚO¨ÚvÄvß#¶˜©S¹zôf…VXÛÍÊn$Mc- À%3A­¿D¹¥‘øJ´òî˜89&V»h˜rL”’L³tÇDEÇD)yÜ2tA"°x;& ±]=Ú°¶®›ÃjoÇDò.ÙÒ®›?NމÓvÇÄÈ1ÁÄ{á8& ,¤wL0—ß<މB{ÂqLX Êí˜(»qY†y[j½™ŠOüb2p—ÌxõHfÕˆvƒ;y™sLpùÃqLœí±›oÈí(ÒäÝ1q rLø}†•5bþ™ ý8& ¼8´½É1±&·ÆÉ›c>±ª0RŽ|õhÁÑno7FoÏD½ˆ^y& ìIõx&NÛ="Ï„Þ^î™Ð'nÏ‘g‚ƒìWØÓØlcOÔ{øBÈ3±WÊ=g)å™8K-ÏÄûfæX1.ÕÕGxãe£1ò//¢‰ f˯dž›Ù•‚%ñV‡ ¬$"Üç•T™uYnótÈnõK ňΈWKœÇÎS·7§}‚ýO“4†jÙ}ŒÅnr¹§GP~1bL+a#ûƒ– òÒdZóÝ£!+¦K¾ía›Ü퉦¤À/ã%à6»Íd8| >¼¾Än¯ït^Â|@|Y˜õØ«.1}…i߯yL3WÛ%Ôiª†%é™E jX f¼¨†¼¡&-y#+b—I a'lw^Dï¯ër†À™Ã´Ä1»fÇd&ò°Ä«Ýšüøâ+cò @~œD·a®›VIixŠ>sBOÍ£X-§1íJaUù¼r—fsfž­¾”÷H’à+iÈË#½¥Ð®o¾ƒb)ûšwºôM¬ÉšxìûR®0£Ï6tw·ƒ‰N²WæÁ`G(ˆ ,uk@?rqš8ò/-O¤ÉÏ8y‘©¦øi]ß(È5Åú38o‰ñ8ÛŒ3`þ0r…‹îaåº@xÞ%[6U‚’Î "›U‚¡_C.=ˆwNÝôî*À‚ ßð²e¦wdV^ ƒ‚âž´ÂHV´›6oW‰Wxš:Wa}õ~3<àòÔÔ€Šüñº3ÚCÐI›D°)H J,Mµ­¸a8³j.•¡uóõìó-Þ2Þ‹FöΦc¹¨fLH¬R|:ͨ=cou&¹:ÄPæû‰n©Sz‚ÄÎCßiæè‚ôŠqð»[|¥í­¾¶øÊxæcTæäÉÉ·LSh¯WÑUå/3°°ÀÌY|G4ûYÅ4‹¤Ähs ™çi·à ì´>ÓÖ«ýf'¶ob?ZpÑ&^ÜÒTñâ%­‡ÛêÈ•ÛT‚ZD°g«©(í“!Ã&šä{×oò¼ï¥‚®d)ÿSÑ‚³¾¬²'kG6/i‰Š)]ª}‘r^†”:aÀ]‡Ð›5.Ȉ¦n!FaýíD6”2A]HÝÇs±Ý]ý‘÷~KwA-uUÔ)°EP7ÊÊÖK„Fmoð¶jLò ƒtÝkÆŠÙ’‡}C¦‰dú5ÃR§¶0Ê£ërá!HŒU¶Ë{ œ­œ0ذޟ@ckg#3Â^ƒ¬W»N…ü^.™Ú/úöÀ‡Ñ¤ÍFÙæ8‹²C58[ºŒ¥RnLSz +ƒ•>Ì —› Ç Ò%dÞþ,]—7Ž`&ÜM¨#4¢÷ˆÅ’m%€„¢ÛÙeˆ«™w×REYD3s¿¡é=­Feˆ›,¾Mo!7GÑyEƒ/m’EpÀÅ’’YSgAÌ+¶¼¦Ñ-ÈAtÚ§…çlJî^Ñ{Œ¾+@,æÙ_Ž»ku׌›‘]9Z>çEBǽyön‘2AùaÖïãi¼-c[{7¤Ëx@O Ú#‰)©zbnBéÌ¥ NÏ–¥D+0ÈÊSC£V1 ªÌhÏ(ËÁˆò•©tô×`L{j%cfW{.ÌE¶Í÷„¦;_Îfƒ «šƒ5ølš~ÂîgÎ R*šJhxuÌ[xÖOÀ==óÄãs/ ‚í:w|n—UÛâs §Õv|na1Ùºãs fÉŠ“Ÿ[ ž¤´ãsW»ïÐÛŸ“ÜÔn[™º9zÈáâÁ¹E:ËŽÍ-V8øÄæò‰´Cs ½yeÞÄkt…æØP8(ïQ‡ªl*4wµÛ׸"sËTÆJFæĘДcõvÛ#s/ÈÞ»ôÿ¹ö³ºÍð°1ï$›‘ŶTÜiºOÔÊœfff ýë@dÿª!k$ª²×øÝþU¹øuÛ¿*2ŽÅsôTÔ ·Ùµ¢ÄeèWž 7U^3tÓ ÝþUÃh’hÿZM3FËþuÚnÿ:Ù¿VÛm“øÞ0†n¶¯ˆ:äeûª¡›$ÛW npuÛךB5ó¸ Í\­Æ›Múˆ 5”‡ Q™®½ÜöUƒW¶vÛWEÑÕyÕpÞ[#Û×ûæá‰4t¸íë@dûªA—-ÜöUIXf1õíœRšeüªÈpx,[gb~|V&ß+WeÙvÛWE’¶n%uõe­pÛ×j[ l_§í¶¯‘í«Z¹X·}én˜Ò.®Ëö¥Aî“ïÌÂÏÆ=Mïà« Ë×Y'7}•”é무L_ï{³±FV:1¹5ÖvÇä®v¼crk,v|ZLî$qzÅäÖ˜ûü]‘‡õ |ÂëÕñêÛ’»ÚÑ4* É­H×]~]û‰ôxÙ¬¡H¹Û’{ATëIé8+…ä®v†äÖ¨û’ËQ$“ Q: \ÊýGJ!£iO É]Ó wHnEINº<$·¢ªg·òÑ…Kc2µBrW»=Br¹ØWHîÚŒz‡är÷!¹‚TÚ÷W¹§i¹ xÜU,Äãq‰ xÜ1ƒñ¸k„C¤eXq Ÿ6ÈõVß8iˆ( ·"¡`1w%6.\qÛf’QŽªxa¡ï€\á‡Å½P¤áþé»Ú¦=[a°¨B‰' wAª)*{ã”逹ӌWH.çq…äró.‹ÌZ‰ü É]Kî\î¦B² WÖ’» Åü…ªÊ[7‹²j÷¡<¯ Ž É­(Ð{…äÖ¸k ÓµUQžWršBr 8!¹lJËãJ^m É=É=…äV”ø½BrÙîÆ¯ž{»CrW»ß!¹«=…ƒ²æixo¢DEy_YaTîå}OHîW»ÐÜr¹ôͨ]\mܹk39E?ìcNŠKU4î†qGã®v}Fã’Ç‹z!SKÑŒ_ŒÆ=Ì¢q‰oW4îj;Zi'¹Ú¢[o*—Ë£} ™fAŒC¨‘̆®hÜÕv÷¹ɘ͈²ÑX‚³÷(Ë¡hÜŠªÇh\2‡+—ìãŠÆ­Ì é>?=0-²@¥ 7CS4îi{4îs'™X)ËŒ[S6"ð`ÜÕ¥Ëp©`ÜÕ¶³ØŽ ü=·DÖgPÌõºIR‘&ržhÜšÂÛ‰Æåæ^A嫟—¸ˆcÞ=ÚLGö'†QnJv×gG䈇àV&L¿B< ÷ý=²uëÓå,¼¿æräó-¢œñ÷{Ù¾_¢Â?Ÿž[sJÀðÜšM¹Ï´lúΩ‡,“á:õ°œøÜЏ|ÇçÖl·«->·"Ð'beâÌ;>·îÐÅçVT²umÿñø\B†…¼ ©9bwâ‰Ï½ÚŸ{ ¾ÄxÈ¿<>÷@Ÿ[‘_Ólá8FqT®øÜŠ$»F¹Tf?S|.—үNJáæd)ò+>—ÜÍ®«‚¸Ñ\O|îA Åçžvs’uÀFÆ󈋸ÝÙ,Ž•á¹5›Í£skö0ŠÎ­ JÂbíFÙ‘‘ªR€PšYvtnŕƾCoWSúØέ¸™Nøn-ª?ëÁ¹µ¸1Óƒsk‰ø¯àÜŠÛ»”µœ[+_'8·–dFqçV–ô5݉ŸLÑ.¹œR,vV±¹E3·"–ë`œMºµó»E‡ZlnE¸R³ë3U„Òš`çVf©µKCán{pîapîjS0œ[¶§Ds®Ú¾)8·ænÊ7ƒs¹Ïò[p.÷Òo@ ÎVos3Œ9ž×¨+ŽKÔ.~»]ž‘³®sïÂ|p:ÖNL¿@Npî(8·¢>¯m64#Ü£¦öç±¹µ$óò)6·¢ÒVÎbs‰. #Í%†ANQlnÅUbP¦bo9í2NlnõØ?ÿ}kVm]—íeÇæ®½°NW ‰ŽÑæ Í}§An]7 ÖBsD¡¹Ü=ÒCs+‚:iG±È\Qa~ydnÍÓÌ"Š»%·¸ÛF†óÄîV\^NBA {K…Ò#s¹ŽŒJï{³˜{Ú˜{ Ìå ú‰à'ÌT#Á¬D#d;>0ƺÀI\1I˜ö´¿ÞcØõhÅåj,„]cÂBÚIP¹y¶Î Ë}ß æ¶†û%¼\? ’•KÑ ß Ò²ÊpOCã6tt_}f ;ç~ª³ÌIÁц²ŽÜç×™ü–e9L˜þÀ}CœdÊNÆ|õ ›¦:‡Ì¤õg=Á2²Ù“€Ók6•™ ù£w[0Hdæ ¾€÷8s)ðѯ/óŒAw‘.šCL;ÜžÄN ×pæóB¤÷ðüt“Ö˜Æ`œj_`Šjm Ó]÷럮ö™…C0ýþ:o(=Ï7ªY÷ö(Tøjr¯ôs/þØîpŸYM2ˆî–a,]^•!©ApâmÈÅ L ŰP·æs*ÌÒd ŸŒ5#}ŒçÁ |Þþj¬&©eœYü±Z62Ëqµ¾³`µYÎQöÈ–Ðß-£àùF²ä8>Ф;âÍñ¼A °¿q-‘b/bñÛ|åõX}o‡›âʉõ³ H‰}Q”6Ñíg>!×CAbÕq¿×ç½HPÉh¤ó–È~h8æ°sýXó¼4ªæÀ/3Z>òÞdâ9´’]}Ÿ4”u˜LÒN–ÖaáP–á¦J &XÒ¥*ðv˜lëIýÚQE%ö oz˜v[Úz ‰0‹×¬zèÌëÌ<“´¹ó{­!‹ÏG:°z·ê;¤°–ÇyA¥kÞ¿PeŸÂ6„*ÓÝ"ðdÏ@H³'¨ßlö¸LÚÊYŸª/¢»÷Sók¯/B<#–ëÚN$(«˜æòsA" ®v²DªP{W³Û é,™û,ïÔƒR˜9ãì°ºçt±Ö»ë¼{Äy§Íì~?LÃc_ã·±©±·AM;`eì1)ý¼Y94†i\”«¨ÛÜCÞltOÊ{ì ³7ìeñ÷ïe³ïïeµá½-<Í ]7˜s!SòBv5f)‹´ä~4ÔÀ²WÔ˜¯R¥‹j¯~Iž—Ûþà­Å’²4tíÊ ääPQC°ßék—/æô]Éédÿ¯É£¤€g*E¼ K$aÒ™Ú¬<Ó Ž« ßeÄ ÉŒ «ˆãÅãÓ'×`>¤B\˜ ´ÈŒcpýbx–._ÅÅ"¢@老:Æ.9ãtgÐ皤«CQÖ;ÄÒ¡5í x‘Â…bùæª^•\Wñ!Zv9>™hRúS×)fpU1¼® YLýM—ºŠeù…1¹ç©ü—E- š,À\YòÂÉÉIå;C&§]âÕ#KEÌû¡˜Ù’ûÉÇÚ5ÆJ©½‡lY܈ú§rbš•Cb.*År% û€e‚–é²{y°ÿ¡I'ùÞ™(‘Ó¼R)V\v£˜0iýXë¦p1`žªXÚÉÀë7×--ÍäÞ>ˆL„וæl'Ü]X¢öa<ý"³ S‰¬É|×§G(7¢U„FÍx#Þ€“¯ð0YJÀ‚æÔµn”†,„ÜÄ&¯ ¤Ôüˆ]S~ÆnvÍQ‚’îV^Xíhůe|Ýí̪|B}f×!÷Ü/Æx?¥h`.]*¼qd<ò”UŸIV?î—ŽÕiFõÂס@ã £çiŽÙ#ä]O›ŒjNKmXd„†DKŠ2—ˆ4S>ï)ܘvÔ²\"ÊZS¢ïq¦sñjÛ…³ 9Kó†Mªû¨2G~äý¨b'A=_aó*&• ô\ÈJ—2ªYHÆœ–#Ÿî• …>yIqãñD¿k8¬f’¨5Èzêh–‰xX\d¥âh©ka4ž yò*Ùn×`Ý­É»ÙV R¹ŸðºniŒmD­ ×Rî5W‰X«f 1± ˜ut«pŸD¾ ܳ’p¡ %?ȸDcØ;, mfB® K ³L!ò˦²9+|”+­4À€ã¾0Ùkf@‘vÎQé"‘ó,É÷8ÓúÝNf9þ­ðEË­X®Õ ˜ôÀ¯1 ±Y˜0TåqÄ×›4fTÎpï1T¦½6[&SÉåÚä2)Å#Hƒ+?<éªíDç¨Ëq#íC ¯\5Ê0C|2)ß¾µi¹U‚Ê‹™Dª‘®¶òX7†¤º3C…†IJøwÞ¨u 'yV7â0TXææ¼zÄ$î×eÁ¥Ÿv¶U•gˆ<6³DlQ©ÆÛŽ,2«Ô±Éì§S!4ÊtŽS<› UY´VUf’ù¢è¥2q/Ú¥ï¥<í<½¢¦CRôâ¹ Cõv¦E9\dž¼‡©Ñ¬bo6]+•¶4rææ`Eßx¸<ç•LÎsV7¦x /Yz!aJ—-½ÞÙÚê©(ž;-ãò$.K=EŸpà éa;`d#¸NÜ%Ï…“ŒÎ²DËöÃ'¯ÎC!&Úeûªc‡iD‹|^χ-ƒ#Ú<("ê´UCÔž„¦oâ®!¯ìÓìCÓ| Œ.Òli°ÝÂMµhßKØâªÎRa¤íIoèâ¤ñœIpV°_‹‰(i;33W˜¬ƒKcÆU”&œüz\¬-Ò rÚ)˜òm7­„1ƒ—/aÉ!ž\¹"<¶Äßžm¹òfˆé¥4ÐuÞY¶åJÏBílË7ö([)Ûrå°#K±‚p;fP<1ƒø÷`]7϶܂¼F'۲ʽæ×ɶÌ2ÄÁ…n¬Ð–]\}H(Õõ{÷1b ½o.ÜÔ¿—Í,z×2pO«U¤UÒ¨“l™ G ž„´Š(0L¶|šžlyC.ª~îà·ÊÚFE\@a‰é6·€Ò›³ (-ÝMÛ Kúªx”ë%¡°¦/óVJBiÁ˜‰I(»- å4%¡¬vÖIBáëˆe.¡°®t[Bád챺Å2 ¥!–çƒ$Ö%f½I( ´4…º„¢‚ÌeK(V‹Û”Õj:±\BáRÓø@ …eªiƒ”„­SÅ“P™[BÙ›kÊÕ6 å‚t•c®§®PÀÎÔþ•€²Ú–@R ‹i÷ƒø,¶=,ÏrÎÕò¼[lF$¡pQXÀÇ%.œ PU$»íDŠò"¸ˆ"ä8z÷·je+÷y4„ –" +FÇz‰( bUž$¢p7©ÆHFYíj9Ú‡WÎ*„f2 ÷¯kÃZŠGe.^¸}/¤4jy’QÖf„]0ÇZÝ «KËA¥…®Ä- 4®§æJCXrÛ\h5ËW½ä¦3ÌÑêRiwÓ¥“ pád$›°Yã–MZPEÊ#›Â’MV{(®d“†Hû1/Ù+ ãþöE!ZŸ.É&Dá±E“w†v㸋&\ø0¶hB,æÀ%š¬­T”Ê–MÈÃúMX“¼Õ-š4ÐÉ=\4!‹£+Ñ„XÆM·pÑda RÅ›hÒ4¶hrÚ.š\"òNv²I4á¨9ºhB,}‹&-˜k‚‰5K4iðÜŠå¦d²šó«¹`BæÀ9Q0á*«º “†˜÷[.!¾'çÒãbh’KNÛå’÷­´ÒáVËÌ­§ ²ä¼n=m!f]Æê#‚Tåïh¹jˆUIB³ž6„7Öm{’(šQ\b4å Š˜S5¹¥¢á<Óht^í8œ²f0‹œ”ñ6ÓC¡ói5Õ[Àâ“xŠÉµªwÊ^]‡U,g±).à‰FwŦW:DB`U¥·ÓCFZòùŠoÌ $¯À²îQ-«X—ÉÄT ¡1!›3yBîJA¼ÞÙM®wæŽfXÅÓµ³ÉáY\&›½2ù0Ùü&¢(W¾„Ì«×q1~â”÷Ø‚=o0D:›EY[SX3Hùñ@¡3‰bC¿Û[öÙ0„’¥›®Ä %e§6´Ö-€i[Æñí9Œ¦öòuÉxÀáÑÅ©"^lÂ@Ôh:S%ÓEÜmEaÜ“ÖH ÄlŸÍ¢¿ªÄÂ(&0yF¶Ò$}J¥Zí$ш¥™¦sÈ©å¢ø»/$ð x’,óoJ¹ e\e¤64 4éy¤.ž£Ƙéc‹-º–)ñõ´iIÀá^Q4oˆâì¿B¶¨³Ÿú„Œ¨Ä%kz¼ÏP@0ù8Ù:ÿ9÷§> fÊ|@“Í6¥™5m]é¥<#yÑLòèáÚó®vÓ¤¤K|‚Áì€hsf±Fß4 ÖùJwZ7ÙÆ)þ†a†u”\(ý-Ê„˜ÓzòTƒL1¹ å]¸0~L®Î5[Z® ž'*x®LÃø9pW¾6dKîû©_ ®NÃd}¢>jr±N¯r¸Yi²ü ÞX*ƒ—Ò,ŽOí×õiš¨ëTK„TÝÉõi£/¡]ú4«¸£P#DOy+Ô©hãѧ3³‚—­OgŠ×cëÓWÛôé‘>Êò’A‹%I_(—:@h,ðÑíÆ;rè¶@3üÕ^OðÚó±‡%¥{vmúl¨kÓï[|o–kÓD馱d¬± m:áªA)—6˜w0mmšþ„Ð7ÃLŸr¹pÛ›ûaΘjëNS,Ôµ^t8ï½ÁÒ¦‘lcPÜ¢6}š~¢H²Ì Iƒ’6/#\›†,ržÔ¦Ó8Ÿc“ó>¤Ú‘ç8Q=Ú4°~ÊÂjê4̸•§Ôé³ÔR§ß7ƒ0œm3£=ù@dOFf™:=™¾™³ÌžŒ<1½:½ÐѶN´É+C©7ýÁvúv23̧—Û“33ü—×±'Sõf¹»}‡L\Ù“OÛíÉ"{2”õÀÕ‘=úè¤QÆíÉH‘1’!¼˜L¡n§âiF´.fPF½¦Âš,2(gÆ—‚Ùß$ÇȸÎÞÌ<ô®[®A‚ù#[…OˆJj/·(Ÿí‘Eù}QFÑônúa]Ó ‘Eæ©ÞÍv”Y}‘E~£2œ-mÚñL'Ìâ ç9s’Ë&Õy¥'q‚ËJ~è-3±‰É:ˆzURB·(璉7ÀJ¹Ž,¹Væd¾^ªŽ™“ñý$âéVtÍç¨K%Üö½‡¯€™“÷m‹òYEY”Ï*Ë¢ü¾Ìš«©Fm bC û ‰­ðØí¼)ê&¶BÛqÖ@ikýÒôg›»õèΪDl@gÍÔ‰M¹Ç&6аã8oNÛ‰í@Dl2²ç µ×Ô/b£{¿ÔMlÔgYïHÄV¨}SL1÷ ªkµK Ü3ßÔÓS©‡‘]&ËÁCjƒ|BÚÙÔVwX㦶½="¶·í[ý‘H¸ßÞ›­±”Ò<Þ”Z…;­•‚[~:Ág/R:ÓrZ+Ì»¨¡f©›ÚX1jÞÕ5ï›Ü°‚1¤Mo§íw ¢8¾Aî’¿á‹ úH£•7Éq”çø:xé·'ê=|ŒâöJmŠ;k)Š;k-Š{ß åâ :‰M&ùµâDåeŸ77燀‹Lë sÿû¯o]1—³/oÂl'C«Òˆ¿@ ®šñvë?®M†A[¶²ê”©`õßž‹ c&]÷>ÿþ¿þa¯úÏ5¬¿g‚x9ÎÆOÈ=Á Û£ÂX ›ï/~>G9oÆçÿQ¯ú{'˜a>럀{z:C‚P1î5ÿxŠÑõm÷þ1/ú{§Ö¢‚?!÷ä6lJîãúâçs ™%óÛÞý£^õŸ÷°¤jþ@€™¨0íŠÂ*?!™Iå:ç·a¬ŸÑ™Ì'Ó@™•Hõ·Ç:éÓé²f÷yÑ^øäSóöžGD½xˆ {f¶Á0ãùØçSEÌq9üšØ?ä=çžñªþrÏlÃöˆ*2û"TÏ¿÷ùXC.‘SûǼsûÛ ±?s1Zñ0=Ìä9ÁªîK_ÅýõúŠAÕÈ ³g çAä8³>IÙ}<yAœvÆŸ°nP“Šñ3)gÈi§dÛ¬vº´B¦—Ù)‹¥ƒ×F€—6ËÍMë9ÈÎòh³¸y5›¦sŸJcËîjó”èPgYÄ« ’Ð+ èÌ(~ˆ:éÁÈ“ý<Õ›J/y7ìçJWy{Þ ¿C²]({{Ëh¨ý~m¤Çü~É;Äúx‹wÚŒX.!°$loÑý6åžÆµ#æûö4½k]ØVi‘ì„‹¥Ê*¸Èø¬6Aó¿ràó&›µûj#Ü:åô€×^mÕåÁ… Õ3«RÕå¡üÅH¿dD$SLíV}&Ä×w^ eÞõ®L>Þx¹ØŠ¶âš+ùØ0XÑ¥µb[4)H7&¾´²¯¸Se~ PÅê*DFÜqÇ=ß–65Ûæ…f­+¨HÛíX»¬¥¤G«Ò0«®ñ ” üjönؽ*oXÇlº-ÚÄ]Ií,ÂÅ¢CDÞïI&‡*l¨£t9…ÂEËH*é)7Ko[ýUîtä7 1mé©g—Ð\¾êÉÅ%ë¸G–±Yç`e®Ò¯©B±Qéü‘nS̪0KXãÅOzZjkk÷l÷æ7D¹àùaÉœ?µ ‚4yƒ1ŠÌâZ‘º9FyT%¤},eêÂ4ÛÜć4¨ƒÛkOCµã~ÿZVé´6‚î®$ܧ9pÖB‹mÊ¡×æh¦%7e•M¦Ê ÂüƦª7VªéLdoˆ… Ø¶@ Ì›ƒßYŒÇ’í¯ÓÛ©ƒÈ-HV:/‹VFŸ€Åa½‚½ªL™Ö ”‰Õ xg,Þ$_£zÃÒ{b¼wñCD®¬÷EÀš("_9ŠÁX¢NîG¢.ÝUæLÚ;±°Æ‹Í¯íØô‰ ßò ¸#ŸN¸z$ˆ¢`®¤}pJÌÃZË 1y‰ “d9Ûõ6)œWçò“â@À?ÀܔӪ-¡9¥IŠœèþËCpÚ<$ÈBÎR`PKy1äµ¥&¿2„‰V>ÖxAM…WŸÈÕ5p„ÉÛŒ,v ™"¶ª˜Z‡|Ò`RÄÔÆº §#…_ØÁ¸`¼¡z5õÅÐð‰¬2& b1]è„1f/!»¦?(­u ¨4l!§xx¤û ù=Y ƒËeJõPô@.•CñXV™”ìy°½cèÁÃFĘeÀYGÔÀê$™×¶s2…D>à×è,fIJwÈáÚï8± 8„TˆU¼~.Hc~n,Fa±(d&]cKU!Éè‹“Æ ½Ãƒu{˦⑶¸gt>p™SâzäfŠuaåäyÕy£l˜oq´`º—3“Æ:-§Ý³8Ãà\á’nQ [ˆ¨ZнÈÇÌy@}V¸ew¼Q) ЇtÑ1¨a´cýQ×`MhÁR•[ ÄZBP’ȉ¾Öƒ>§÷Ý £ -J®ÞÈÞé9Mšû„¸:ÿþž¹8Äîã’ãyÏ;ä¡·÷@:€];'üÝ9o¢Ž+*ú€¸œŠs;$SÉäã¶I²îk‡îfÛ„«ß'mJ.§ 7Æ%§2‹ÏnÉ©¨R!såTÚxUÌäT"“d~ʩ̚ç8³¶æ2­ŽË©€˜4F9í1Ç–SOÛåÔñõdµÊôÀ¤ÔÓ¦ŠfÒE!•º‹×,êœx wÖ…TTCʪZF!•ª^—” BCTˆ‹©¬ööoâ€Ð.rßÁ‰+WÜaR*‹×´åTG“SOÓåÔÙËò†uÀĈümÍü…îy¤1£P¨{ß ’­œjfzõˆÄgùœƒ¸ÓDÿ¬'t7áô@U8{®Ý²¶¹×xf6íêM¢)ŸPåE•¸…Ã@Õ'‡]²Ñ îÂã8*ÆgqÓs·uŸO"A„NA,~è¿BœêÎSŸE{¢ÒmÙ²eÝó”Vú7Èùº?õñBůհ­‚¬HçÄ¥×qÒív ÝŽ _R˜,P¡ÞÌk7%tèU4®0¡÷÷X9ôÐv`E.Dº{X¹L`¾ÞqŒ‘ÛLGuëG,²aÔbt¬‘~‘©Ë ˆFVm*×"ª ©¨E&ȺÑWƒŸhJ“ãÕ£u!¶ô£ÈB_G?ŠA…>\?ŠÈ‡¦AS?:m×DúQDδ·ôÊoH¸5ý…£¨GÃÁ(g¯9 C"ñtNrlžQù8”ól/¿Þβ!í|Ë.æHíè´];º Ԏئà$íHmóMP;¢GYÑè¦-ˆÕèÂ-*VQ±¢Â¸€êödm®1áD6ƒî å]¦Ç7 ª Ûé1½GÑ´Xâå¨FÄ:}¤E$䢜,ÕèAïY™jÄ.½¼¶jD@8ªßI–­›äQå5Žj£n¤¹j™àíœÜîzÛЄ™=OÎj¦q)êËA7+ IÕˆ“˜G5z›”H³DvDd¶<Ò‰9 "ëÆÓ]0„gTË_¨Û+w‚9 blv¬È±ÚÃ*ÍÓ½£j–DŒÃ zá%wé€XmcHfeP×ÏJËáˆÕnRLÝ‘ÿJ¥cIöÙ¯‚˜üàì_nÑ™‰ý2DDޱxD‘u±é8 8ëv÷¨VÓSˆˆzRÌ™´Íl¹\§<5'9 NÛBDDþ»fõêÀÄP™¼ÜˆÈSLÆÉÞ Çq ò@¬v0<%-G$ †…Jͪ°]ˆÈÚÈ/w@eè¬qql´í€ˆˆYyû8ór{ "‹¸Ï«2ÐÎíàb“2Ü£ªa»‚ôW¬%nÚ¿Ñ#ž¨Yç”ò@ì¦<Ü?é¤ÃnŠÔÌ!Z¬/÷@D–O&:‘²hÛm£ÅٮʣÊÁ–Pb®åvƒÄ‹˜ä8m÷@ˆ<|C7[2G9£•5…‘aGyÙ†9oöÉ™^컵@[)ãÐ6¨Ê·î‚8k-Äc+È=qá&[°É*{ 69d«ƒ.Á÷´h¹Uz¡ü•o¹& “®L®I—éhR½…Þ¿©WÝëq™édæ¼eš„Ê;G¤Aš& W"Íno‘fCL¤á Ê)’ ЙCÈãH%âØ¢ˆÜ{åfÈÂs4WæOíz\I\¯`Au²jXr’Œ 5»½…š‘PÃv:B Úõx9 ;\¶PˆÌÂ’kޏbrM’ è’kx#0¹Ƀ.Û2 ÝbM¢#ïê üD[¬á Á|Ë5À–T7¹&M“aM®yÃÏ{b.× KÝæRLtZéz“kðÎp 6Itx 6ÌqU`ƒ,Jó¢;lyî7eâY½:Häp¹K‚ ;·#Ø`}Áæ9+eMJMKáV‡\‡ 2óPžú„„bwgq9Š%‹£Ò”!»Ot3‰eÕq[NTŠ›¢"hfj‰¸‰Ö·“c5U&f@nJÈç¿·jÝ•Éîì8U² VÕ=02†Ø’ ŽY †hù?ËëiíÎúsHãîŒ32yèšS¯(TK‰TŠÒZqøˆëvÕL†§eG‹l—³s±(+&¥‰Ñ¤gäzÙíÞL_ß·W¼ï -Ã)9²×ÏA !H–W:™£7É.êÜï# wÔ^Ÿî½ëCÞ£‹SÞ—Øý¢ŠíÂÅHI• pœ(º…±L~†©éŽ=üX<ìp¿¶/³¹@%ïµn9S·£InÿêA5²0KÈÕ¶Âɱè½oŒPÉEßÉÊDÜÂ"ÜlgóA+¢ÍŸ­^øZ— 3:+;Ö©Z=gH«ôz> =½m ‚\€µ§5AUV»J>ROÀeQ®“É!õ|CÉgõ îö»x]굜°«ê4é‡F{€JÂÇÌ0 HgC Ê[üW»[¦BƒœµD3ñ«'ÀÑòûQ…¼¥H)9È[¼>º¿¶ø 7Vj0hêæB-­`Ì)åP)kî&†¯\C§ƒrÍØÁåøÏ½hµ3kmÆéœ9'K•‡EHFíàÕˆ¹åú#™a»Ú›kí“ôkdMRŸ4›É:ò$ñbòËÒhÁA³XqP-™­9 ÂYg©¦J™i|¥y‰™J¸ŒÙÔ#›xBéÚ‘Nb‹<ä7sÖ4›EôFœ4?¨œHœÊŽBÿX{´‡Ù2èa{Zsá7\ò›f#!#·ð|Rznb­“D„ã:Ù¡/³ P&«h]bŒ1r!ú 𙎠łÂÉ[pã¹æE¤¦›}A‡tY…=º*»©ÜÀàßœŽ#ݬž;^ÌJÓeÄü-2ž…U"H¯›™ ýù‡ñ LMáßa#H—¥¡Ý@‘áQ^" s¸ây¸òc#~1/huï1¦)‰›m·z¼zÔ`ŸœÈf1»³N^Úû-zg37F|íng¯ÁÅ©d„^Å(3÷µ’W`­5œÒ$Á’—Å Š9IÕNDÜóξóÔE;å1î|·Û')Ьᦩmø…¼“I(Ä èäZ'`!)'‘ró^X`EH-ëpcŠ}t7‘6eåÍ…_¹ÛLá'm}Þíd‚7ÁKô"±(®íŒ²*$+>ÅA0.«Pô厼(žcGÜm[!3'ïO’™=Éîšy7·ð U/Ž«G1•·Š2$#qóžÄÓ–üõ{š&`ñÒ×Û©U*Aµñë/‘9s6$ó²þ÷‚d3+~BôÔ÷Ç{äHD§ @ç5o€s”½¿å›cÖEÚ“y5¡º —6X²Í1¶,7` ªE‹ à4§'Y󔋆%àiߣl˜‚Ù±!W¬Yþ{zý‡úùï3YSîø1úÐH$ ž IˆU+0AæÂPàC K*X‚ª_G7C¹zøþÃUÌŸ§ívÓ˜t¹FvÓŠA™)´z NÙQ»ª'pÖ=^=¤°¥p<„ZÌø>u榠LxT` {ÁUš- öˆÝ–ÏO8„éìWÛ‡N¹+Á³¦Ö$c] ÕvoL…¹'‹¸s¶È=hLÏm LJ_*ð³!×f‚Ûp4Õ„:\ѼßàØ±‡m¡5Ñç×nz‹£îpQö (æšêj2Ðqkª)²ªŽ+ª EÆSSMV¡æhª))?¨kª jx:Úú§ÐuÞºªJˆü¾TUÙÖSU=mWUdPqÚÁò qUõ@¤ª² u€BQ¹ùŽªšà"I¬[¸œ.SŠeÂaÒ ·ŠV·˜ZN]ëð(ö.4ؘ{”oÑ{4cKÒT¹½Œ\tMu¡Àç^šêA iª§íšêœ•y¢søt|˜ªšÚNÁANê·Ê0.6Þ½¬sœµ!ä:‰¶|°ZOû4V…Ö÷#j%Z¹%­Ä×ï%K–Œòm£ íN©©ž]b³éPvAƒ–v°ÛuØñ¿!°éàiH˜RÌš0˜—,ê ]à”]ï¼,»Dp\Á¸ÍA)Éßwz@G‰×füò€9ûÆœRomXüj÷ðÄn×!9ü‚è*>Û 3•U›R73áP-ó†| ÒífÎ÷¤ôÔ²E`GKû®&œ±]™ˆ\Ša‘jÔº¹¡—ñ‘KL²Ý<ÆÙ–¢O³Ãšúš˜¯pjK+Ѫ‰Ãä!$zbê=1‘yÊ¡'/¦:L$ëŒûJ¨Ê¤^ŵ°ÐI7¦.\ìcs}4Ê'c¤Ê]?m.N¿’”ªŒCZxX#ŽÅ\¤`¬9Ni|¹ÙLQ G!زgÄ¢wóX£ÓžFÙÒº¦›§Ó‹Ïo$3½HZÅ(‚ŽTS‡ILBr¯9,‹%&Z<{u(y‡a¿°Rõqv²¼Ñ%Íbi£½t„bÁdW2@l…˜I×4{”£dÊ@¹7 ‚&!È¥ä!;áH¿@.Žþ†€ EVÕ‚%auH‘·93ÉÖKw¿1øìJwóõ)Â/ z°ÊÕ&åìø½‰=W)¶Þ¡ÙÃ8~%%™]SÂ)£Ú ÿîI@ƒ™W»c ²8µœ.w%}" g-Ú±x8xó…báØ‰ÆÕå°Žè‚%*;šÍÇÆ„1gMf~Û’0Òg„t«ú²w˜yD⯭ؿ½ç@.æ°û¸¹_ó¸0çí-”‹ æÇ›¹^Ô8ÔÀ%¬"EÂt£áZ5djKÇ­’ŠLkÁŇÓÃ/%­"ë »à¸ãÕ:º¸ZƒEja›™©ïöª$$›Ç«’P!¯JBŠhwÑ%«².Åq«°=ÌË qb··¬º!g…ç”Ôø ٲꆘ¬Šv:n•T”öë’UQ¸ ·JB&êtÜ* )Òšhœ|1$wYµÈtº‘Ÿ Û뢎Ò-TÚ{ Øãµ¥U¤Äy¹´Ê¬)ǯrp¤ÕÝÞÒꆜµyâñÙ«ÉøÈ\:³’7óbªÔjb ¼xN¹ê±Èû¬õM‘tzÚãP]ë= Ò>RÍ'3+2 ¯H$–²H¬OÙ(ÙAëX6ƒílŠ4ÎÙÝ.A±'2ºBd’åU¹›‡â¬û/€”¾Ô¿Ò¬›aà«óÙÏhi?÷WõÌoBËà ÉLªÅ6 \9k²µjŸ³S'ÄDKþ.béAˆµK¢HnŸA†în2–ù5ŽW;!kCž÷éT=bv÷h²†'ż!™5n;»:&µ¨!@-½.µ¨9ªH-BVþfæ@e±Òú¶ZÄ,ü†KÀ¶y°p¯Eר5[(m;!?Ä×VŒ˜âuéEU5/·^T•JuëE»½õ¢ 1½ˆopb¶O$ ܓ΂A”y´™å0kÜã®õfçM‘î§Gö(&{Cñ°3ÿÖ6A`ñ+òooµè@¤±m~B¨Eh{¬¼Ô"(¯K+ªJl´µ¢:eÑs­ˆeN((¹ZÔ,¥¹«E-ØÃ4lh‹7.¢ŒB¸'¬L3§.'¶þúø4i’iºàÁ-[Ĩ©Eo˜zMlkEè¹o­`&`hE-ÛbZ>ü²«01M;¤µ”wˆ>˜6½Ü^µµÃÎëòëj–Sç–«Euz ='€y ‹ÐNãõ6/‘i2,nWDûÿ¬ý9’.¹„‡êw%S¸–¹.á͞Э<…Ûgúçá¯*^ ÝÒ9@áÏLL@ î#[9]®ˆ>"«*¬÷Ý—òåŠèƒÛÀáŠèñâéŠèô®ÓÕp›†x»"”ÿŸ¶+âN%ŠvE(Q¿¸"”zÍ¡®ˆ;Û<]w.¾”.W„r·ûáŠPùÙ®Š_‡'âN‘«žˆ;%JágPžO„:ÝO„p,Æá‰è$Dð×òD´"žˆU^žˆ]cO„ =úá‰èwˆÌu·ëwL^x"ú·‰ðDhºQË–'BÓ99¤(uÓ’-Ù£žç«Íý.žSÙÔØõÃ1w9"\±OJA <ãgÅá‡X5ᇸS±ü·Ïò釸á¦~ˆ;ã_~­ügË¡Uv~Fèn:½ êwýðCô'ž 6J;ü=Ì–Û!À•²ýÚ}¸·âÛnd2®ˆ½˜~ˆU~M` «Ž—]·Iaù!º™À–¢k—m?Ä=í_ÓÇþ3)½Ë¡¹­žä}x"æl‡#b—bV„âÎ-n½ ŸnIƒqÜ%õyíжõýåà ¡æSp>‡BãsOÉœ<Æa¦ 'ÄápB|›äæHá ]ê èõToHŸÏK½9â0B½Q\Wà¥Þ(Cÿ´ú*ð9ìKŠ/<Ü饷vßû®þˆPoî>íMS¿Qô'–€ÐonóÉ-ýf•—~³jB¿á Û÷¾Ã—Ä­{Üwà…v¢¯¼û€>}™ÃAï«…øqÆ~ÀÈÙJÙzÅ()¡Ñ?;«¼ô›]cý†rßú åtê7 )ý4ûdÚ·‚sß3Ó× ŽBJíá› ŽºžúVpBš·BÔ֭|3É·Þh¡¡©3LU=KW¨/SÁ€°oGp‡Ù÷ÛR=;¶µi§~3R„‡~#$ 'ÉX¿kSNýF8º×³õ›qåªÏ6… ðØ¥©ÇøžŠG¨7Š|¶ûqª7îu)þòl¤­Þ|ë–÷©’×¾ó‹+öI3-ý£Ë"!ìoÍO]cë ÑÒŠ£‚\ÇiKwwÖH[†‰{÷êQ±ú…ÎÜà3œä㬅fM¨GZ‰ ja›Â\Ÿ©þöøÝáa?Æ_‡Ôý1|Öa˜÷=ÃyU¨a®¹UõÖdÃ~ qGþØÈö¶ËpÓ¼Dˆózkn˯Ûrm8Y *g1ǵ}Õ,ÆçüÉ„1!™“ŒSwüæñ ͼ‰Î¡÷ÿF‰x5·ÿÙH<²süï')µ÷ך`°õRÁFû÷´jõ;kþÚ5Ù©\í_ýRc<^}cðåÌq%­¨ˆÔÓáÌø]þóŸ‡ëåÑÆ,|~D‘Þ‡;9‡¦#•µã„J7J­Oý[)bo±xêŒ ˜aÖ… @^òE4Näß¿O‹å¬>ð8äYÞ¶Ò’$¼Ò üä(''+îšóžü#BùËÉ´„ÁUG¢`¾Éâ èM­¼Ô·[ê6ð\©~Ì@iýGùý…²5´¥¢†=§aH6¼ïIm‘*ü}š #  Þ2kn‚€D¸R_nˆ†L»@¹®EÈäa˜É‡Èä÷¾c [mQö7[dgG¤†²¥“9½é˜a9Ιa9Z#.¢µ£ }¡fxV˜þñ™8å {¸½ˆXWñ „:D]kߊ"”Z¥•üJIâð%㢬á/PAÍ¥¾bÆÓÞõ*ͤH½“ñ7«(çÉ2q–=:"ÕÌh_¸Øÿþ˜æz­BŸš„ÎCìúšÐQóÙY9 S‚äÙs”ÿô§Í7ápÓaÝá (r m1MȯÂ&:˜°L ®bwÙ’M(Æ«IF$6ÅûÈàN)swðæa!:5 ÔsV„x”€³É“¥=(w/ÜÛÚèƒÚ—,†Ñl.¿r×pl5hܲsjòÜ›û1(N¬4e†õ/ÀÕu»R‚+<:x½‘¹G(ÿ—6ö»+¡éc·”H®W¶Ù8?Ì@"Ÿ5—sÏÕ=R›Àxû¯ÐZ¢x2vx?I46?„Mª X=â7½kïV¹Â•ö–»#µñk´XH…9w9¾Ç¦V„—žËBêyŒt5[(¢“Á¼P—¿-LGÁ2¨¤ $ç¶Ú¥y#áN1X|˜dòÄ´X"ìý\¢·x!=G eèż1b"ÍQÀB¡+V{“)\Æ“m§}ª|òÛàõq”ZåFœƒÉ*iH›]î‘æ3+´Õï…ý“«Øs>󳦲k€ÿ°’©ƒû³fÿ*ù—šýòù«5t¡~Դۘݱ žˆê÷Âõ1*ʹzõ"nd‰¤?§r€uV+b¾6Ï.BÁb?)¯ã`xk"xwµàz¯¢’f¾-°€áðÍ\ç™aÉtÊtut£pد¬¾èË'º)Ð%¼@î.1ÈJÛkPB­}¬R¶á±ŽlL¾fPWt5Ð Í} Ç·€æsr kv–ïg¢ªÌòùLº)~õŠjgA¦7ˆqZRYZø6^F¡wÑÉg-* û ÍAsûÍýù p„Ôã¤ÆU¾‡øóŸ³&þœC:»È¤Ü“ÂùzbÛ¹æ/£øL­Jóx9eJ?勯Kºå6ѾÙk¶€óãëß\_>žŽ˜ ©¯»A©kQVd`¨ÕR ¬“jÌÀ_¶|×ÎÇú<»õ°¨ÿö–u#jþr Ÿ![‘Ÿ‰ªáôBÞ™³U g& `[ìxµ(ŽH å„éî÷¡¾y4ŽÉÑÙŒrŒ¥_Ù"{#ù²B¨¨r¥/¼òBªøÖ/`µáõ92¦Šz©"Ñ ë~f|ò»I…(f‹·ŒI뤈—-2P7³9®(tº{ŠÅ$xüžKOe•¥m^ÜtV‹dž¥ê™¡3õ6• ñm\´ iA¹ÉÒ´S7ÛÄQnÿ£fHß‘B ]´ópô )ïo9òmlÓgÞ€#ئªWÞþ(±»dþà ºIIIÝci‹º ¤ùê×vSÈ‚=W7há¦núA ’Þ1HUÌ̬첈(uG¼ëý@2ÿ lWù¾"Ìâ¨àBODgº½ëtcTš­l´FºTœèM–ƒ®ô™ÔäŒG†ŒOuQæNËE¦ p[ur>!£9év",è·ìè­ŽÌKshá\׷̯K“hPfYz|÷ÔÍ€åÜ~Bæ"pû±÷ ŸT“ï£ô:sÞ( (ÏNö·—F–wgÄ@̓ÆI—“¸¬¼ãØæêæª¸Šë'è[k®ƒ ,û$?€€߯–’Ï3¹ì­¥á×/´¡«?âòE¼ð —}<í¬ÑMOø< y¬ow,Û©$Ž ´“\,"«’‘oYšÿoqGt‰av8ÃqÁ“£§4†ãJö+hiw–öƒ3J2@È“I(Ú Ö”ÍòÜvVa‘êÙ5e0í¼CÆvAr*’Oh ruΞA.ªlÒZüæºÑ~lØa‚oÍjºZì¥w4åÈÕ`È«" ]™a™Ýxy÷‘—ú$ïàþ`…¾/2 Å„G .#SZ, âSvzÞ[\5pÕ)u´Wœ·8æ)á[N¢²œ‹V…£¡9´FçB\›„N{VÑÃ*–ëY3Œ0ûþ¡!ãy1bìŒDBüL²9 dÛWÒû•vßÏn¸íæ¦í‡*pnÕü¡p=’MÓè?jd‹ÔÜð{XTî˜Õ’Àûúi˜˜?’VMNŽ.’%hÀ‰Ôž$òšçÝŽGLB!zˆ¯G×[f/òM4€gìéh <$(ˆ’QÆååÌWE8b«yª#ƒW ^_,†Š›´¨bøe·móÑs†*qU‰D#0eƒ®Åé” ¶z§ÝB>Ä\ýâQÈ!Ò Üªô×’- Þ#¯—¾ãàz8†…‚­x¢Rc};‘oÍp·:¹Ë#°DvÍ›ïk) [ÑÍ9ÛmèV×Ü—Sí•1lG"Ò8‘•W=¯†!¨z)<@3bÙKç~Ü»½¸äw ‰²ÛO(¡_ñwm¬'Œ‹–è¡«–ºÆc—G³Sc×ÜäJ§ä\s¹áKÆl‚+ºªæ"…Ñ/Œþ~(>2[~¤€Í,àïI^€Ûiô”«ßKbpÇã³…²Ò›e€“º= ˆ¨­Vœõ™À¨ÎùºF÷sþ¸á“«LMGƒ^579oyø­ £î®Ö(çt"sßW¾ž”Îxm qwkêt¼•£Å“=r × ˆ”~aŠ¤í„¥ÛŸ€Î~‹óÛH«<¾}×<‹•œs’Nq¨y_þ§QÈY¸­zzØTÞ¥{YÎ}¼zºZÄH܆ñô@ñÏŒãmOÏç'`5?gÂò╽äùª‘ 5â~c ¿_j,;¹µ§Ø1û"\±2†ÒìͼÆNp•7àú ]2· .×#Ÿ›÷q¤;Æ/ƒkP^m~e‰_5Yri,ßu»HyOìk°^zLÉ£ ž“¤Ï¶ZE®ª¯Õ1©ÆéÁiЖg$¾×mäC¡ &Ÿ+9®æò":ŒlH<ô[ö]k•ÇH)«f3ߦQ*S@º-?n¦6g‚J¶+É Ãý­z6râö¾B†uâ9º±Z\BÐnʸü%3Y¨<HérÚó©qŠŽaš æ´–Ð…Ù¾£åÞæ€D $GÞüV³WñüÕÏÛšþrw­Ë´€›ëGsœ©Y/_¿úQC'žÏ£õ©ÌÑHb¦Ì%´Mx.ÙJ¹& =ãqWžÐ¡ã6¥– å¶dH/vJJÍ¿‡zÊR¹åàÁ]-F 8b¿¯2”ÄdzòJâª]„hýRã_ýõã9G J‰9ßmt }<æ{EüæçS`/h¦t=žæF·žß‰Ú¢ÌˆÔÒYDMÄŠ±ÜFŽÅçëûr GLñ¯K…õ¾wEH9ÈX_¬ÓÅa›Qè2 Æ÷ŒÜtÛX"ŒØÝóœc¾¤@“öŠKŽí<Ö¤¬ØåXµò‚ðÝ2}>ö’€»>Jhò£ä‰šžicúfVõ,'.ቹCðÜÍJ7BD¼WÆÜOî{O%=À0„O­-ÿ7>±ØoÈý±–…d‡Ì”èê¶>mÉ|[ûËÑ¢°ZOÈöääéÖŸêc´ØËNfôS€z‡±éB(û±î¯Ç}´jkËB øb¼Âl xü&9àeGšžÄZ èûgŠo¯–Ö×tÃÅ ‰Û%18Y`{ÙåéFß5—ö¼s¥ dgHr²È¼CßÞmwܺٱUæììͤžŽq´(¾kiR_º=Eæòa¸>D‘åkªÇ&¢W¾o5»Zæ/hä2!\³Fê 9–n³Ÿý¨ˆßüõã)»†Œ\ÎçŠvôyŽÇ|¯˜¿ùùIÙ}ŸOŽšý YiÅþKlp%,㊠S@½è¾d=®BðeÇ'ï9—UþóCz-jƒÀîV 3ÁZÁZzi&ñif6%h_‡0,fzÂG- ibÓš.ŸPbFƒ”O¡6v+Ÿ¸íU¨!Sö»ÍÅbFz¯ƒºGª!<ï–5è’ƒh•3fMÿB5{LõábDýY#K×]ûGMÇoNÕ{/,ä€9>þŽž<\vð­Márò`rPWD£®U«$åÏJs$ó/É‚`ͦðì)вLÙàÕB±}I¿Hè¿vˆˆ.ò† ]¦ìB\&LYËçºÐF–be’{°5köªü¶­)%`0冦¤$ÑÛ>YéÒ—n—…#Â7°^M¹™‚b–ÿ˜-I«·¸\XËÑ—ßѬhV1£ßV4Õ[®HCqGvBqMó˜ ïgˆa31YÌåÌۺˢ/ ÕÔ5š·N6:‘ËZÖ?köþ›¿úY£Sãq´ÉE¨ÈÝ Þ¹£fýjŽó/5ëíëW?jèEDÈDàþО.²0mù‹ò»‚t)îtþCŒ".)?Bb]a>¿*”»OØÙœ¦šÉå$êÝQnIDo#­òs_•ûl!oå³üs•9|ʉI]­KpÉ»óJÿŠøÿÿ_âË•J'‚8ÜågÑ zuÀº ÑЭ>ˆpù{Õèn®)áæC¸@!d”d‘ ¡¢ÙÞe.!ï"­¡»•+*ɈߋòÛ>$âjÑéoïú}Á«ñg!‰`­“ï¨À¢P§þ%O/áGàPE æ™4Áª PÞÅ„xMò ßÃÖüDŒÜN‰8õ©­e¤&JÍÎrBUBá¤^øC†Ì!šéAŠ¢V´ˆÞfHÞÙÛ(Šã>›ùg]@¥5Ç0*9!a*q|h¸Å1§hÕGþË9AòÜËÓúmÂ4ü‰‰qlq¹³FÚ¦x%‰ß—Ú°¿[·¯JЦ2Ft6‰@èýg(p¥yPÄ ¸:eB†•uµ_Þ@î0ÉüІ.4ˆ÷} ÏåÞà 4Lo½ÊÀd5R·4<Œ®ê^ ÉÔ!²ì4}Õí8D™`_IÈWV€zˆz]K1Êê¸{ºZÄ@ð9!=R™Ä~CÉG( !†:;œèû\`º¼žç>ü{ÕȸÐá¶Sä1ß?kdèBçœN« Ïу[™˜îØF€l4˜eÒÑB±uÕ[S¦ ÝþŬ·æêPY&ìä&á…<€©EdÔsëÍœ¦9b‰“ÇŽSVÌo„Ú_D¨õm:z‚+ö‰D¬[aw­²ÂÌ5sìl±À»ø£†ˆ|œœ«F$ºÒ´W Ý5/¬À\«2Há!Â)dŽ *¨u˜L’52µ,ì€×5©{á(JXƒŸ’^H‚­mòÎ¥¦È –ólAø®Z46¶¦WÊM'(Ì€~#È×’H¦Òœeå4{ùgÍœo‹c£B&tõÁIvì­P sqx’”ÅeÎoß÷´Tz8À+<(|×;iÂup‰-¥²#÷gùiuñ[-d+-~BƒÓ·f;8Fï2/—.”ˆhõ•Æzü2AÅ‹­<òê,Ž·H€‹ä¯_ifNÉßÑ–Åvnñ<|”F{Ÿ¢rÓëärt\Y-.²TñÍ ™I`¿‘ÂC^¡vhXdÁ*¤¾™6ŠÏU‡¼³¥(KÛLâŒÖò$_ÊbªÙ¯Ð&à*I9 mQ`³H³ý˜uù-ÃZÈå¼8±fçàúT lÈk¶í.Īq´(·ÁÂnäòb=\À$ntÍ’r8 ?äÞ¬ÑÉrµç¬ÑŠaÆh÷LzζÊ9VzœN¶Š.%9pàÄNóöÊjê\fP·q¯AGe&E9 ÄȨëmÃÞ¿‡OS°Ýx 1N\’YC øH5`Ìÿç†Ô/$ ôy‚!W#–¡â<Š©åö7÷#þX®2¨•ösŒ°{YåØl†Ù¢ØÉ¬'`"A¨ù‘ÀPQkøŠkO¹>²Á‹eéfFŸKàŠ=ô_YŒ²«¥1ú…Ûû×_‡míº\¸ïíº\voOíº\&–œÚuIÙ´wK»ª)Þ¬]—ÐU¦î\Œ÷sh×¥«E³E.‡v-ʽ~*×ÂöÔGMåZôtò MåºT2ÄåZ|´íZåñlíšr:µkVÇÖ®K$AÍCXÙS¹V¿%ìVÇ„Nåú-£›-Ýúòj¥¥E´CxF­[¯âÒ­gÍÔ­MÕX§n 3æTH”•ŸH§²nJ`džjÍlŸšµ&slÅZ¨µRy§È¤ö”)‚Õ^ *1NK¯ŽQ=ôêY³E[‰¼5‡^=k¦^]K¾ôjÊw¶õêâê¥W—fžÁ©XkÅà—›ŠµÖ¡@s±úü™Š³º^>4k ~ÛÑâ†jÍX—rèÖïlÝ1uk¶Ÿæ?tëïÛQ︂¬gêÖ«&të¡OS·.)Ù^¶tkvãV­KvxÃTœKŽ˜Ñ¥Zk3Ž|´(ÏÔ@P­ òìЬ‹SÁ–f=·ÒÔ¬gykÖsLÍš'lÅZo v)Ö÷ا‰¾ñ°–Ñ ´Â%dég9Z$¬áK±Ö@õz*Ö å½ë9ÒS±þ>¦E(ÀoüOXŒÕèÁb¬Fÿ c6úŸ°ëIÿ¯°¹:agÃbìšF¨¸pL/Ø ÃssN¦±|EÄeÑ3“EßýÛ¬Íä#*?À{’‹YNG&±NQJØÔ å&/00Ý}øú1i¨ßSÀHˆ3ÿ f¬ˆ®ùv2Á0¿Ú%¾c,4M¬Ôv³|_ñ2kV2ß=úo5º¹gÕô€¿GdtHeç)hû~"s³­¡b°Ù®e̯:í·¦ï$äÛ£äs¾å| ‘ñùÖ÷2ÔËÌè¼*þjcß^Ïã ôe5)ÒÖü Ò|~&ðy¨¦=ò¾Z+è6ÿÛ.GûªÙãXu­¿Õ,$ïkÕøÎá…9Öoó[ßEÍqY¿ú¥fº¼J3Ñ€Öå-l8’‡sÆ ^éŹ>Ä™íÏ0€a]^å°Dºñ°k⹬˫–Ñ<`]Þr#kẼ526®Ë[´1+p]^”ÌÕ ìòÖ½†]Þ²qÇØå(°Ë®1°Ë[ž9ìd†HúþÚÀ.o7º[ØeA<Ïí¯¡*» 3Hµ»Å}ÅåÉ9ºkZ'°Ë÷‰>¦l»ì»¼å¾¶¸ì"Õ¤Ú ×å}íLø·ü©ÎãÞ[eܦêY{©šp·x0ºM`æøÄuYS¸.wrc\—]\—]a\À792†7°&&°‹¶ÇvyË–h‘øÌðCã03£ßÓx¯ŽùŸÀ.Àc§z»€€Þã+Ê9Avù>œˆ­B᳑]Þí6ÂÈ.´Ñ¢ d—·ì…¸-o¹û&8‘]À·†ïg¶h¦p“”àš9Œ&´ €Ìˆ C»€È ‘¡]Þ²¡î´ ˆÌx,œ;ßzÀkÚ8æz@»PÁa´Ë[4`@»Pæv;¡]Þq¨În_Ò®U«×GM7øà‚væ™çÚäp¹¡]Þ²‘ë´Ë[“½¾ íò–«3ùv9¬‚H·|oÄn¿¿¢ëZðQÓߘLÆkè_Ú…·2‡†vá;Ù†3&ž°2Àv¡«€ïÛl³¶ ˜Ùt l&ù ¤Y%´&X}ÛåO¶­Õð³íò}m‹·ÂwÉÊଠp@˜‰20¸KVÄL;$]`Â-é”6’ï£E±zè.ÇiåÖK ñêE(ÜâØ ÀecR,p—·æÈ2À] ÉÜ¿&¸Ë.¸ËªXà)¹§{‰o5{)Ì_ý¬™ð.@†Û~ð.»fÿ*†ù—šýöù«5 Þe×Þ…2¢Äð.Œ¼ÁÁß…š'Fß­t–²ñ]@ñ¸Ÿ¶Ý1ÍÞÅ釮åð¦ó|è8Ý-š«ßåûcÝ)aÒG„ñ]ò]ž…ƾ h»¬"㻀­ûžÍÙÍ à„æXW:Ä•CsÁ€¶öÏ…ú˜3e-ÔǾ^2.qì7ãÚváÄKîÁù/»A‰p¥¯PL$÷Çø†»Q¢“rwyb¼œ5ü9dôófð—xÉdÆß_àÅøÏé+^r÷ØL€°½9+&ÀKV¾~¬YMÏ„òž L9N€ðyós´HqàÅ8Ëék¼°VZhü Öæâ3Ô/ßèÙ­ ðB#ãÀ 5|/<•?øãõÎrà»d% ¶¹å«áŸËÖZ˜êûC‹!Es¼0Riá»0”~cà»0ØwYø.ÌÒ<@`¿u+HoÂÿSe]?.È`.=í¸ tn–ƒ´u}•ÆäYÞäÝÂd¼0Y݆ÿÁhyÜI"½óº!ã¸HuÝIœ Ê'ß•`ïµoÈɬuCÆmuçㆌ÷"6ßå]9 k°jdõ·¬«ï/5ò®Ýõ£æÆb^— '®ÇÎ2}Ž2y¦y]“cë† ºRØ"…[„WÒB‡œdpÜgyÝWƒ¸!ûϺ"óŠ\÷Ù^¥4¯È|¡dK\‘ñ»5®È¤ôµ×ÐmrœU€yì+ò1–q!þ¥&Öæ_?V«¯È‹n S ¬šŽGd|ü¬ñ¯þúñœ£æØ³ÍþÆùœ5ÇW>Ç_=Ⱦ8="c>§ElÏ/5 ¬zjàsÃçÑMÞ¹üVbÉ#Vp E¾Øê:ÿŽ÷Ú^+‘h5¼Ñ¦’™ýøi²ÉvÈŽË`ÿJ/%ó%““Ž"ëL&Y-@—pòÍd›!'‡p†o†(Ç÷›æ4” ·Ç*“ÎñÌ´s ðÝöÝþ¨‘Oõ¬PRP JŸÇI#0Ì”'’HH ùã«\ä:Ã7UÐíÞ4õC7œá~E? VV&'Ý|R§’™WÈ÷~…“í ¿p´ÐÕ«ÇtFµý!ælh£;©Ú·Ý…Är—š›B¹å™×±ÎŒý¡`¤³üÌKSÔdó}üå d¿­Ù»nþêg½ê¹·)ÒµúgÍúÕç_jöÛç¯~Ô¨ÁŸµj )§²Áûph5Â,Ì» &^öÉ8y]n‹)Ûí œ»É™s9o4¢NE sÇKPÇK¿Z Ìö’D·æ»(Sy÷y}ìM¾ÀÿÜÝÇ÷c˜˜¨2Ãy¾Xñ­ß+f<{Eõbê’Z%Ú"Ëv-QÝvƹˆËbڬǢú!W«5ç³Á©ãÝ:/ÞñëY¬£rÖõû’ã"cðoóÂ=9­lÒ{$9òÌBcKvrROÉòO=`3TùAS8>$ø uu(ˆþdóuvùí5”“û†`‰ž ¼«˜©¤¸‘õ‘¢eäeýÌeYVš×³k4oOuÇ yø¿Ô¬M7ô£Bž¶Ô§[¤)?asÔìy”VoŽßü¨¡Ïù&µåÅ£)!}aÒoØv4éÑT£Üe…%Z`g$÷nÄÆEŒÌW/´nç-™«WLn9ý'2]ãhy~þà(Ð{ýú¾¾Ð6`«+Fs˜õß»Fµ!–I—ÁíR ÞÂÞ'«f±å÷#¸7 ²¯=ä<†¦ôIãó>} 40[¶uØÓD¾?pæFwDc&àdF¢g*\ÜdÇ‹N–¿pî†ñá¸ÊŠp´“/j ¸xÏA+ù£FWøpíU#ìÄÙO@ô‚ü³l/²lÜ3t’x ÐBÃ"œ¢ã\¥1CÞ ©íY—ÕÌœ "*+£P6é,ëµ w´ˆ{” OóRñfÌ v; <+»ÎyØÈMpGÆ/؃NR ¶ÍËG1ó¤ãE™pö~Ôœcy;RèGÍ\–ýX¨ÌlÙY÷[ üñú›(»² IgÖ‘¤FVTåÅBöz(Õùºl…7H+È‘©¸Y¨ÓB¤“Žˆ]ÆTlrÄÕbÜŽÁêfC’å—½4ÀRÆ›ìýQ¸:Ï2-i2øñ,ËNg㬑¿c,6âà};0â‚{CûàšáWÎŒ(€ò~J¥•/[«[(ò·†Ë’Àsœ˜f˜²¹±£ÛÇÎ/ÖÙ-|¸à%]®¤]žŠ‚&Ç öš.lëãëûô18j¨1qù¬ص†°ì ü¤þ„ñS16~á'XdÔw*ª·Éì×ÞHêyêG ûoxC9œ¥®7D߆̼ BÆô/a ¦ÞwY>©Ë¿ªÜËÈñ~ŽÓèÕˆ`ŽÁaþˆгùJýgg!{YFO‰‰òV ÆA€w*ŠWXÄPê#8b¨eQàÇ·¹ðý5³´%jŽí­KUë¿ÕÈ\¾¬j‚n#]Üq1.¬-U#‘foºÚíµZ€þ-±Hµb‹Xç3­â½ÓpŸñâƒà™\àЪ£ù.ôÚ;-ÇcŽ?z L¶ÐQ—ÙQ‚h–£ªH—]‚OŸ-óÂYn´³ÏšÇÌC5†£'Œªš f&.pf>¬wAp–œèˆ %¹§eu¥IE³Z¬áÏ{%éÛÓ¹ÖäK‰Z·¨¦±ÌuÞ“‰i .Ò—|G—_KB6t¦Óeù†}‘³æšÏÅçûÝ$bíëJšm ÖÅ}^+RH+GK@GB÷ߥ2z¸¾Üà À‰@褲CÁ_…?eúJ÷"ä›äué«‘{=[4þzÂ= Æ/ÜØç­AšL â+¢»Y/77 ˜À(øã8-þi¦Ùk¨â͆õºž"€í8tß/.çÊ ×É]Ùùâ²K5{ô¥`¤é:¹¬@T[ªD¨> ÄX'Ä,?Æ4ùóŸY£ÕÍñÜ.‡¦ˆ5KÉ!F·àÕþù°é´!±sÀøHè¤.ݵ-Û©å#J›yiM^M§hi²ƒÕ£E‹ŒcÄÌÁÅûæ[Ô¬Ù"®)ág…ŽãrŸæ·áù&>ð¶?Añná'‘^Vœ¼AÐb·î«=‡k¦ÑñðúÙïH´îm¿ 9‚#.¿u⥭ëq wÐl!HhìÆïQQ<ÚÆ¿ãÀf>]îa!³ÿÈv¹ãÎþ±™œ±¾Ã\³j†QØÂPÙ+^@å0«ô©­ý¨Á|PÇñ˜ñ¾“W{v£üÇá›ì‡Ù¢µÀÛFÁbŠŸ®Ó;Óí£ÓGä=çÒtG;ʳyŽ5 ÌK·°Ó]@þ|¤îs×r÷/¤)=ûH‘Ј´<„¨º9&!féh=Z” Ÿ*acÉÊ≎¯Ê3lÝ9ØúJ€Š¾M‡½@Wõ%okÚ?°Þë8é¡jGÍRµua}«Ú ó©jvœ¶ªÝg`Cl<Œœ[SÑ5¥-ž²0X:‘Y'Ûª¶°¼Í&iU;Xë—ªåCÕž5SÕVHIr~€ÐÌé0Um¨ÆRµE¦ R¨Úb’ïr«Ú‘·­kC5¾éèö¡jw‡¦î £ñRµŸ{kÚ{3Y6ÌÙššö·Ùìƒçw+ÚQ1õl¹®²õìÞ&¤ûÔ³15´¥hcD?ÔèÙ«­h¿Ý>þ<šÁ«CË–ë*§–-Û¡d‹ÜCÇÓT²gy+ÙQ³”l= >[É–IüyN%›È[É–ïíÙJõZ{GF/w ÂÒ²c˜-;riÙç©dNƒ5‹–[ÇŽšãt¹«£Î~Öl[öu.¶¡cßmœ:u¾už|ì61º_ÇnÑy9”lqw µ”ìÛ8¶SËž¼çS˾ŸäOXZöýn`bþcsiŽó‰A¾•lUGJ¶˜Ô4o%{–·’5‡Þxd̃ï5‡’½jBÉV9rý9¤nƒéJöý®•È}EÉ‘yÜñ5±Ë‘N%ûVºÃ½•lÿÕöRœèçîpí!þe [ÉÖ÷zjÙwuÀøÔ²ç¢˜Zv”-{Öcó¹üв\Ò§š=Ä$\N5{ˆñokÙCÚä³µìAú¡dYßR²Gµ…mªÐÃQχ’=Zä`ÏÝÆÁ©dndŠ­d‹i»¦õˆeŸބΔà|.+À{1¾¬ïÕ"¼#Øfxë¥˘Þ¸à-GaÞñÝÝ#v|wh +¾Ƨ{Çww“ïüÙñݽ;ÛqpË™Fœô,ßæ?+IËŠÞþY#Íy|TÜ%ì~ðÖ[f>4=™Ì¢+À\ÛÞøÝv4.£Óf®kKÊ;Â;øVV„÷bd™Þ³ÁŒðî>¸V„7¯°‘ËÞúg=›n¨‡‰""¼I‰”æÝ‚m/¢Û¨^«<‚âgÕ챜ñÜ?kEÑ÷åêXéê ²ÅA›k¿ÂR´oMøïLB‹!qR†Ù® ¢Ïf¡%¾îEÓÐÚºyc8pµY–Ùsꓽ "A¨š5gfA*oõ ö6‹Åë€[ø*Ï•²kÐàä[,à†oÙ^ÌÅAë/ˆÅ8Âvlвø"-µ¯MA‹A¼SВ׊ä4-ÃÈÄO Ú\•#>–1Ðj §…)h1 s'4´o/TAC›+óbZí,:ä·úJ䳄8Õ5Ùg1þ^܈)ª'8 Í>KÀšy˜Êœ²Žn䳎j_“|Öo÷×"ŸeQ˜vf ›x!øÅHì.÷Á@öq ©hñ˜wÚä³$+ ‚*sU˜±Ì2Yó”I†#È»DÃzsÝÁXÖâOØ"ƒÚÕ›|–…¹á$ŸõÒ¹¿&ù,yÞš|–¯~bì#!=–RÏÒOÏFóJ¹í¡]´hÿd™-ú¤Œ5¶à$L öÙ·¦£íe$…nûF0Ðå63ÚW£nÙæô=Û3Úë"Ò ô†NXÜd¢E }ÍDë¤y˜Ö‚‰–5w ™hYUf¢Å¿c}%xqì¡…•†ú?–¹hÙ×läà¢e’½í|‰l_\´2Gm"Z à¦6-¶éû+xhWiÒÐîŠìœ‹òŤ¡e½ôúµihYaVg¡¡}Ëq"™†Adn¹2çló¯ICËjI[ÜA¶.…A‚çªG ãL"ZÄŒU{ ždÒ8ˆhqô ‡LDûýPpF~™l˜S×™5‹vÛgz~­™D´N1™b# ÞíØãí.Áî6¥@»Ÿ“›–ìHÍDû–Gìú`¢%!‚g*ZǤ±Ë¡¢%jíÙtŠüÂNksѧOйhWyqÑîšuº*hðƒv×L.ÚU\´„º!dMFëP·øŒ€,¸}S 2ZG*nŠJäÊÊ0a§r´Þñ5¹hI‡7 o€I2#“,Ûfu/Ÿ £Å“RCâ…‹¨>Á˜hµ{ÎrÑîò$£Ý5{p>דÃé"ª‘Ñ®š £%²¿†œ»ºãøï ެòÄ™aȬ¯c}±SÓ¹¾´ÊŸz´¸½cƒŒs5Ÿd´$Pø 0,„NcÀäcZçÀy0™³<ùhwùhy‚CÁ²ûuCĺèhýùkÒÑò‘­ï}ºæÚɳ£«E DÐÑ®¡ZŒ´k0ƒ‘v¶i¿O‡-Ó©žä¦ïš}—#àþµf2Ò’ïmƒnâ #m¾ÃY±ißš’8½¾è\ìCY1ÇsîÔ[¾µã$ Œ´MFZL«ólq–ZôнŠíç)b¬¬Õ‹yôÙ$À¼ôP´xiú˜'}¶iƒ»@ùÚŒ´™@Õ²¤8#a²oã8+&<‡ªîhuèEJ öÎhJÚ]ž”´»f Ôoóˆ@½å´)ió¸ÒCHX{½Ÿ;Œ0Òb¼¿±qU÷·¤ÚÑ`‘>iñ/@›: ißó‚!í[.Q&ÓU&t¥AHûÖ„ŠcBZÊWì_ܳ< iWÍâ{Íw7ã/5{Ï_ý¬™„´ô–M„´»bÿ(Fù—šýòù«5‹ö¨1XžÊ{š–²ÝF´wñm.ÈõÒ—6Ùýp_/÷¼Ù=s ™|hцòÉey#Õr×$Lxåv~|É åjÅÔ¡±­×ß([iòGu®g¿ê¶K\¬CÃ_/ûa‚ù&yQðûŽJVH Þû±íŒE¡%.·OQ›‘ð©÷#×£¬<æSž-n3bñÈw}Ým¾&ï,&{óG%¦ÙL©Ã¶Ð"Ý“©~ùÔ)²7ð Ùwô‹l«»èy†VV6sáêR, #Ïj¤!ôâÑwT0³Š›Á%Ù…ï~†ËÄ^LÙ¢§s:X+£Ù£Ìà¦yµP<åðF÷pîw<žÐ{(V–©;&hxI¼‡âQ̵£¦yÑܶ¸ ÓnòDdEÍd3ÉÖLq½¼†m!£<Ö2Y:’U“’Wï( ×Ôöâ’±*fÌ’ÇÄ ±)ÐØÙìäü˜×”I^ÛJÓ!^÷ÆKZ’Ú¥Þ…wpjj'Wfœ(Èå(p†_ÌÁ”ñxî"†Y2hvO3Ê‹ }뻪aé×í’é§SÃSq_a]˜…ààXDö ^]ásÕ£ÅÝ}15&ߣc&„O4ê‘DÄ,oÞçg…t:vÓ 6þï£æÁ•®½Ð}ùù¥Æ¿úëÇsŽšÛöÖóɸó9?jâW?Ÿó_­AÍÏŽšãI:Y~«o‘/—x «ÈÅËî Ù„Ïö^ò+?‡xÓòÍ5„×­òíã`n NÜxÅ»¬´ë,p‰Œ{Ëd%"»˜‘"yÃiÐn¿BPçÈ2b6Ëh¾KX·ÔôØóm¸…ev„].=â¬Ùc¬¿ö[Î)лw Ñ_”-°±ð!ÿêíûjÆJô·2\Ù’ºq*ÚÞ·»–=ZA»+øÐ °‡¦€¦:D(^øCÈji÷ÇÏÔ/ƒ¹Kj_žÂ`Q0ô¬5Q1ã¬b~|kœÇjü\y¬F-X0$k÷U´ ¸ ÙM«ÑÍÖ]Á¥êCG\଼eÍwïN“.ã1´Ò~õƒÇ$Ædê½{û¹"ÂÓå÷OŠh¯ÙB7¦h*G—³£õ‹ìó_!ö€«­äØ.¢«åÒhã,¿èÑ‚C—òˆâ¹û£uØ5ÿÂŽÉEIê'…qÐH?¸ÏM· ¯G‹1 áÛlÿ7wzTIk‚òh£v˜<³ <<ÖóòYŽõ?‹ïŠÕ¬ÏpíÉIBz%?ÿõº¼›Ðz|Á»:ùÃy>xÎýEã ²î‰oŸšÕ…ê5êõ’-—~¶È—“ìºuÓ9²Ò帎ïš%ážjóþÏ]#ˆ`Û5:UÞÇ–¸³ß\’‹èp±ÄöXxk‚ßÀZE4€˜Ebâ5ƒÍÔø†ôÄ*¹èšá”",‚{}g©»ÌŒ[U£…6 å–<÷c;­ä‚'$¬Ôœv »²£Ý|ß‘LHMÛóßGM²Þ­ID9NW,;ÛG´¨ò³vd܉“G¾ùÞŽU›"ž)þµ%½¢Eêäò„äI6ðܤNZºŽ9Oàdîr Ç]SÈTã笚Šâ)ÇRŽOj¡Èú@Ñ'žjª:Á^Ú2öþè)cŸlÝ—XÔãwø«4”%”ÌaC­8­üõ}2PDçÞÎ]ÿ[jb½ZÄßÌ‹m½n!èVØt¯¯Wwì’»~½åivJT‘»™9jø˜ª"oóqÈ•ºÂ¶5³z»…—fV/;4w‹”CEá^YEëëDÖb SZ yâuÍy ôœÄ¾ªZåܦlž5€q?¡ÅQÆ;((€†OJ9®v¢Jøâï­ËTQ«•SàT12m³Es Öz‚u’óȧùþwäYiåqóYÎÍ:ûQÃ!è2§+p¤”ë°ÚÞ=®Â¿\¹Âv 0ô«¸ŒY¬RªŠì:£ÑfŸšô3ïÖLyAܘ!˜Ëº¬j_Lk1ÿ^ÃüÄ (ê®x5%¿@W/„ŠÄ[n±¥«WÏç=zUðaÿíeÌíÄ5êgsTŒÔÅ¡~¶:0Ê,Ñ1¯þÙ³7¯ötè-ÏÙb“ÖI¥·¶ñ;=4Éh³žÀü'{Öc‚YSÉ£[A)¦#Ö4³Æø[Çlzz†ãîÆ0¼èª)>™ž†Ý›¿ÔÜœü¿úY3Ш?jpLPÖ®SHQçÚùD¹ˆ­Èï ¢Ä¸†Üú`ÿå†&%ÍLñ¾–~·Æ„yHG³<€³ÌÐQ,»±Æ<ÃC!ú^yǶ`b’øâfõR7^U¥VdÒ¼«Ë¹û «‰Ëq1†&u¶HÝÀèL|³Äˆ’cmCºÃg® ë”|Q…;iÔ£p/ xÕÌ™ÐUy<¿Ö¬]¿úQ+ã¯kÅ;“ κ_ÓfŠt•›(gî@5• ƒ"…•ïÁR‹ÒëU_3õx›º‹ä2t+rêr“|Óˆ2w€Èv‹r9Æõ&¼„»Wšg\媳[³RR}ÿ/²¢¬BIó¶4kÿwÃbŠÍŒ"*ƒÏ¦ÅÕÒG{¶˜û€™¯õíJA·ÆÎ¡ öfs#‚–•‰6lšŽr\d›-dìpÜVtdê÷Ü¡ñhäÍŽD¨þžE ´¯ïs§_ |~®¾ËGM„µÈjYb»”ÛLæú±y(" ŠmpïtÊ®ÄÐÜõè˜ËÜ}Ó\-Š¢˜…Ø7ÑÛ¯ð Y”|ƒ47X‡¿1?GY^[kœ³FYº_~@1©™:ÅJPZùaÓ*ÖPôZN õíé27Ùb:57XC _çcŒ{Ï@Ç0*Ü„]Ã\/ ìŸó`¥ P¾ç6AË[´wNW)[w„Éîñõù¹‚óLŽ”˜ërîã÷ŽkP?ÖÓx o°Wœ‚ÉÏ%i7®VìÓ}S%(Ó< R{¬@S÷5ª(Z¢eXöü‹Yêk·=³$Ü0¥ÜS=Ňѱø †6ÜÇ}Qz¿FÎ6k]Î-|Ë—xà 0Áç¥Æ- ûéÑvMèi2½îõ¥¤žäòã{Ùå€õbZ•w2 žÖl^qÛ'#»&;]Ô_7—-yyÛ*L릋ͷ«'M™ 5݆ÿ}ÚsuÅãœRܯÖA÷nš‹W'qþX¼A’¶Z(ä2ù¾14ož†55.pŽÖlæWd˜§˜› uÌi³ýC`$¤Ó©¶€‘óg»€ËnQØ®jF˜î$dˆdÓƒ®¥?aÅqšˆŽ‘¸ÊÆ­QAáˆíðßÍcã1}Øq°<ÒªŽ6Q󀧇զû´»DÀäèäñðÕ¤@ó‚ Ææ v¾J”ÈééÅÛÔ<î6e‡=ih½RJv¯šÓ[fGäQΆ Ú5'á_GMJ¶ ç´/YSᤗn}Ú€§}¼žbw«èùA Q€•|ûˆÕK£x²)m%: ×® É«ñõ!ÍÖ×¶l3O1¦k¸ºCìÇǧq^§ûcŸEÉÙ&‹8ÄÆ}Ûœ€Ï×Z ¤ŠŽ‘Åw}=i‡Œ3Òkï¶~›šM„·ïú%q«<ÊAz±kìià‘)Hï\Ãx¡:åžø&#$ÇÓ½åÀŸç¢n°ýãä||ÛŸ-dÍA”]Ó²e*Â2 ]lÿéþŠ:¼ÂÍz8lCLX­éLA•BB×ûeiJº(;/ûs*Q#Ep~ÇGž\D‰Ž¦2îâ´·nCtâ[v’Øõ³&™zÖ\·O¯;vã c~nȦ˜¹–³VÕí¤Á¢¯Õ"¹ã"t]Œxk¦’hµRÜÆ±’‡í”{­?{7h!^ªï«ÌSÈ¿[Xbm›³|‘Gõý41’ž÷‹©‹[ÚÛ-¹ƒ„Wù÷®Ášßíß*UC‰^\>_a§]ÃiZMآѽ+Ã-û½Š ´c—õ‹NÅnaÛž ÄÉr“¹þ…’wä«V礒àËmÂ8)UÊÿ\eÐ}Cˆ…Ÿ ⌠AüÚí;…X8%Ý[¼ƒ¨n®+8c ë¡8.!6þŽkPn‘Ç£ˆ~³‘¢[­Ž^Î_[2CµänQP}6¡ã¤áPðõ .–÷9;n!fG´Ú½}}Ÿ¿ðI¿›TF{‰fÀ¯G˜ ^ÑJ¨nðB~‚,j5æÇYøÁd|W¸ÜÛAÌhÇŒFY¿0òÚnѹ±é •؈Ž×«û&´W!×"V~øÈê%àrÿÁŽŠ6ÈzôÚ—ªó oY>šˆ¶èä°è´Rr¦¿Q+Y¡i÷"ÊúEôsµˆqÐê(½b„;ßC)…¯ö¯5ÔmRü}2غšl-îØ–ï©v|Ë ðêпÔvg-3cë•&È»å(}õ“µ©t±×ößÛN&7MÂjÑP}T¾ìô%¼cu—i4z;Bý|~2u±.t¸f¤3Kˆ¾26™®,×`Y*3äÐ|‹¦ñt2#j)µÊÂtØÍ¬‰ñÓH8 ô—šæÜÓ£F°¬ø|¾Hõ¨ó§vÄ‹ÁošOE3k¨ùÜ5µò.kjµ6._6*)²š¢ EÊ\`k5É´rås½aÌ9”õH6÷  'T|S®^óF^‹BD«8<¢Ü ëòg/›ch>—Ÿ=ËT2ÃxEzÌ…•0À8”/ø7nn8>dªÉ¸„œ÷„¿cŒé ¬Ÿ^ÃI4¾d% ¡ G9.÷Ñ@º8¿Ï8–+n:½¡ÛóÈñó¾SfLtùÊ Z^HüXÚv_7´˜~¾ñ"eS¨å†ôõû* Y„íÙVòT|ˆÄï •fVf]€ˆrtZ‚oµ¸ Ç®‚þp‘žKì_󎪣M.íÎ<\mhøQÖ¥¨çy'PâÎì ÌtKñðXttÉ©ÚãÌäi¥ܯbIâÝ_ aŠÔòî;‘¥¿¢ ¡4ØÙÚ¶èË^§é.šr¶ÐÐeÎô E)úÏgΆj¶{:ؽ¿ÔÈŽ–úY£#t*»¬Ô 4 æ»´JF8/1¡:ð J_㊯f|d]PáËÆ×a¡½£¤Fð\ßßË‹]"C"3ËŒWãÝâ.îG¯0üÒ$j£Õ‰r1¯¦lgÝ‹àcGr'úm@à»FÔH§ÃKMz—ŒAZÚ‘ïÈ bÌÖâ”.§»$.ò|YºÀáyË2?ÌbÜ·5E«AÁQÆPU%Ò’_Ñõö9žÁ+_“,Dhü‹Q–‡éúXÈæfWIâ&8”4c¡V³;aCÔ:S°<[Š+2N1K7ëÑÂDr<¥j"ñMÑœw÷×û'>és.¬‘Ûf}ë³F8æϼWí¿ßjŽ¿ú¥FBh5úŒ›+ƃ©eç=ñ`yQ¿jø…‰Õy£²¶ ê-ƒãg~øGÏ'ûO©øã ÙA„þÞÓðYƃÇÚ-ì²z@!”7ù&»É“ì¬4…ôcWß_áP}›(3—Ÿ8¤’SænvŽU ¯á»ªwƒ‹`”‡nõ­7LÔ¹²uþÊ © ÷yÒ/2wˆY&ÊÝšs*pf¶û·š5¥ëW?kö!üm±üEÔAÁ”ü¿®kŽ2¨ÇumÕÄu¸¾Ç×µzݘÛ÷u­^ƒþy]«×ƒ›u îš.4·h¯ ò£E¶î×µ*°ý}]×jP„ÎëZE¨v\\×Vy]×VM\×j2’Ǽ®U1'sJÎëÚ[#;μ­½.åËZu³në²öv‚yY{»‰‘q^ÅV·×eíe‰®× lÞÕÞ‘ÅÛºïjïØË2Wµ53qUû>wD.p‰ßWµUWµ÷Ø­çUí-7i„ë¦öV8±ßK^¯N,‰¾º9[ÌaðEmÓº§­qŒ{Ú縧}Ÿ ô*ØA:B|gG(1Yº\m¦Š%´?,2Ž5…¦]-ãÒƒ÷E][Sx>%+nàR8VœàܯcÉ¢üOC§@À„2ÙoŒX„]ïîêKj?bt•G\¸VŒ6ìCof[x&AØ7Hò5™ZÏp‹¯ÐXi‹«×¢g‘ÐH W£-hÃR¹– ^q“|¦¹š¥/rÁ“Fè·5–ØàøC,:aÄtRP.fG^zs÷¥pç §”+´Záš\Ű¾S¸Ëv’?{ú«£±aËè™,®²õý¿ÃFCâF“ºñ@³»—±Nås'g‚í,=@wü*üÄÚ‘å¾À0rÚ[w2¯&{ktëR#}Ûxwg-/\‹EæW«1}e{\¾Á•«0Á'„¹ÎQ¦“P+Ýú3ºÛè!û³ÎQ}TXï<Øê‡ïådú4ýëøxŠužuÀˆò7oSÓ9 ¯ˆe.²µ$ÃrV8ÉÞÄ]ðV çä¸hÚïæØ#ý½BÀ–}ýÐ^ê´ÑíWEP¹ZY+AžBM³©9Z C<”»œB \5RXW³¦˜¿« §M&)ù|% U¾}½é9WH9´¡µhqÛÚñ€Äú–‰˜Ù7Î 3Çyůžä’¾£f³ InIýú.ÙŽÅ®=ºe]ÃR©üëöbÖ— éÏ{Ôç³®JsÖ3Z´â4'`É}ØÁY&Í×¹‡—¸Ó‘¬üÄ›~$ŠnMÈ ÅOs»`éé+u¦à23d|‘Ð#mg–ßAÊx1wMÃlÁFAo ;¨gfÄ-¾+À€%¨ ò¬ÕãÀt úy¤>^¾«ÅVîÞ… °ÙA:‰CÞ²aeÐf$á2§Æ[«‡VçHÚO¬Æ ÌÄöèK‰EïÚ¯&„ÕÏEÃÌ7PUúÎpÍûBŽ;²‰ß6 Ç¢Uø>öõ–áé:άܽWW‹ž\®¨vU<$W,X¯pE·'ô¨›¾¶ê²Âè´uQd³{»,Š›Ý˜V´‹œÝ-…ƒu•mjˆ_”têàYñ ù·š­ËÏ_ý¨á&;î¾ïËׄC³æüUŒóÏšãíñ«Ÿ5êÅ=>jZœj°‚ˆ*epJ´®šW»jzîZz¨•èeâˆ}­í‚´[sÂ:<Áyòß2¾ùcµkIŒq¶À¼2ÀšÏUú€"ú×ÿýÝa¡Çºü÷®©X¡3ü®Éú[ ¯¬ä1Sάù?ÿÓÕÉg·z—7@sà÷bêùíw«Md­½åÿø×õÿ{?ëŸuƒû|ß®Ù]žuû;xÿú»ÕFNµo=þ‡Oú:¬““Àzݪ9:uÇg Qsä_·ÚÈeÞÚ·ÿÃGýó.“GÌÉ=ß·kv—gÝþN¸j{þõw³Ìõ²»}tùŸ>êŸw9;ÿàÜEQqîãfx 5æÍæ®_~µ¶Þcv«o»øŸ3Ó"„â0Ó.+}>º1köbüXx¬E[ƒô` îW6‡×ÝB‡øYã_ýõã9GÍ^æ«ÍZÕë9?jŽéü|_=œÓ¥ ÷Ñ Ö0—5]n‹ˆ:ø&!f$Öäþ‚“ÛÁôÔfAÕ€íDɇ! é<6ˆô½w á(AÓÀî‘S5€’]ѷɬµ!œ¥dò–z”­µÑÞ5Á¬Ò Twý6Z3k'YW¸$»\ð\zÅÈ>Œ ÜâÉžªû4 ø›®lû¾GÇåTOA"DÎÙðéšÅw„;Ti’‚DÎH¶y ¢Ë½‰°Êô®ãþ¤ÙH&bâ+¦&ÏMšõŠ Ÿ¼ú­ý"_ ¢Xñx÷üÈ{²1™Ì ÝÇ–×uÖtް3ˆÄ°_Ä@$ÖvÒ’D¿0²Òjea\äøEÔ Ø¿ý„8Z‘wO±dKÔ'˜xzó¢½./¸8çäì³3pòv‹4¬eý<§àˆ¿ÿ[æ’礽LèŠIecÝ S|ßhØ|BÙlÑ­Ìæ‹Í—d(›Ã³Á7ôàòÈÃ`]±ðh”ê­Ü‚kI q­œ‹N!଀h¡F(׈{ËÉÄŒZbÄwVbGOЕöÇxHLíŒY.|çQc:ŒþÀÒÓ“U6[ÔŒæ¯âÏÝ øÚüăw‚*ëˆÖÏ4ÙC"mµÇt0KÀD¯·€qZÄÑÂxü0Új}êVÁ_ÅØ§F[mÎÖ=¼S>gO¿èæ²,N'ýû¨8•{@̲*Šž©„ÂX4þJ‚‡­Ë6õì(k Î~íUj¦˜ÕB±Þ- ©¹&ó݇Y añ ïBì ²ubîGY3þ+ªsšý€äÍzÕxEòvŽ–B`Î'ŽqHŒ¹$·Äˆn®1 HŒ5J¼À“èO`Wx”õ…u|}Ÿöš€¥Æ>Ãÿ>jÄ@Ãa¬0ef´Aýê3Õƒk湃úl­ª§sÿÞ-z¶”¦À[ 2 8Tž–|Eh,ÇþÔ—®{]íw?—ì|EP$U’G§Ù|vù)fY5Õ9ø<`ª‚’LzEyBüf¿¢‡€Ž% H; ¶{k>"J6´fWFo‹Ë"¿Ú!Ràü:÷ o´ ÝðY©[Ã3 ÏBè'#ûè«úÁcî$}ÅPÊ rügOçÒ­îË)A¿ÔlèÛ²PM+fªÕ€z¡Ìš‘-î‚M,iÕ/o°985öl³0ëO±Cˆ”Î=¬”Üç8i”q›bë¦xúZbQxÝ=±Â½"w79׎²€Îá¹`«á œóNNæp#»¯ê¾ A_ÙŽcý1*ø±µžC5P®ÌÝö­…ܘ;Vž'¹5ß”*@ µvòݾ¾O†vò­€ñØšž;]Ý'þ¥šâßìýÁãÓä=•Š ¿úÏû@u´z ¼Ct+÷Ù‡É}É ¼uSý¨»E½cÛƒþt_F‹óaÒø…R˲“ÑÞù‰(|—±Ûñ‹¨©v+?¡[Q“ƒ\PhÖüš5\¾"®±ü u¾·Ü­Ð|Tǹ)ߎ>qÓö4Ÿ ³å|ƒöJû4ôLè…‘g•éEó/f!\DSOÈe-Ûa4½[¨„oÃH‡Ô°}Ð6o¹{3Ș¢^²¶Ø¥ÍÉIÕªšò®.ghÍÝÅtÖó ½/ƒ’ì÷lúy+eûQïÞMoÍŒ”‚ºª:#€}Ô¹D^ióAPC‹ú¬õóI¦Åº˜„[1å>ã ©d•N­¹y® I’z?»z7žOÍü­Xp·hDYú²¬Ž·+Þy ‘Ñ6;$èžÐOë×÷ޱ?;!¾0€p8áÌi$ú¡ê(O˜'k˜'›'W£TQÿg#Qxäw[éÌPˆöG£&ÂdplS>5EˆÙ<‰"ZE„ÅW*6Řœâû÷–&ØxÏÛ’ˆÖnûRªZTr›'VfÓt=Ñ4›RB ˆš-R LaN“–4MŒ!ízLÅUe|½åpïPGì2Á¥þE]‹ï’ol`õ¼¢À¿åð‰—qß·äbãÚÛ´!»¶&þ~¥!œ†Iøô‹dEØô‹ 5ÑØlÊ‹90€«€æž-êžðßøŒOÚ—U³#ÕÚ—]3ÉYÞh³4áòåCW*%ß’SBºGƒÚ7³Ô;ºÄ^Á,eeJƧ+^QÔ ‡lÅ…Ød‰Bšä,M·V“³4]‹ÊׄÒo¥Ïø¼À¶¥¦ÅoÃ-,¹àfÙåÉͲjö+>ிÕ,n–]cnÊ9øulùHÞ  ¿5Á¢en–&èÏRW§Ÿ [©dV™G†Ó&$Ò±Õ¾V&Î’˜eû³ð_AÎÒJšYAÎÒø7)dÔ‹¹(Ìβ˓žeÕëñsù±$eÀ…Åvò³´ò܆Ÿü,ÔBa~–VŒK9ùYαqð³4|÷6ùYšÌEu‘¯´jßЦgiòAß4[ä;Êг4ìyõ giò\ ‘šž¥ÉÕ†éYÞò0µÊ¤gyk‚—Üô,”ïMÏB¹·ƒž¥É¢Ñ6=Kä±ÉWèÇ|Ž6ú]îÝBÞ`ˆMÏÒÊcN‹EÏÒd‘Ýì,Mö ö™ÙYv9vÀ,𥕠ev–·'w°³´âŒÇÉÎÒ0ímv¦’ÉÎÂdöàmzD“ea¢Sß&O`òš7òlQ°=Lv–5°‹e×,WMÑøKÍbgÙ5°³¼Åëv–V+ÆâÍÎòÖ›8ØYÞröQeCk†ëø¤gaAdz–Vsp™|…γÒ'=K“ë lytKòʸpoz–&Dþ«/z6 ›Òô,ß7¤~ñ‹Â¤gÙ5¦gaM×rya^Fß_ô,Þq ’:Ž·.ò•&ÛMÉ=K#Ò¥-ÄïÕ¿&= ³Ì™3éYÎoÇuLºéYvyÒ³ìÓ³ðs–éYxÁuÒ³ð }ó}ñ‰§^J\Ë)dÃL½¼ßzÏ»öãwmTáR8ÉYö@›œåûT x(óÙgÐo(­™…ú¸ÉŠ)þ:ÉYšbà r29Ëû›h}Ëé¿'7Kk½Æqˆ÷£µ†2:Õ¬fˆ¨Ck¥†æ-¸²›—¥µt7Lð²´Fzî¤eiÍ‘.“–e—'-Ë®1-‹P¿&k¯àØ Ò}@ÜàlÉИoºÍ%kZ3‚îj¡ÜÑ~<á6°üñŽ1õã#&•­í»<¹YŽ@—¡^!Hˆ2¶¬ÉÍòö#‡V³PcCT#o9XLÎò–Ÿ  rú~mr–·ïVÉÂðÐ8ö·Y¢µlÆàøs»ÍýÄ8ôIõ2¯¶Z-hlF¬}ËwìçêÕó¹DÏ^MrÚ”“œå}Љ‚œ…§Z‰ÃCÇ[ïØÄàÀ5…UZU‚œå-µNìQÍy:ÉYÞ‹›q*7Ëû™Ã¯œÜ, öÔè$÷ÕkšøY¿w̶¦G¤²– n 0§SäÝ%³ Â]fNÀq+=üždHm€lh ÊŒ{×mPcÃ$cZýÀøoìÓÑâ¶Å V‰[å+`»oüæíê%£ m¢&‚Ç%Åf™´|ÿ"j k£]¦šO¨½²ÿö€eoÕ<ãMAƬOú:•¸|ÈñïJŸS| ¿œ-úÁs22,Ô÷f Á^ÙY%³…„ç̺È:yÄÝʰ̓À÷b“¨Áœ€ÄÏçb6Ïeg&º!É ÿ—ç&?É—¼M)`ü1*¶2Çç'ÖÀ…ǘ`Ðé Òo³û ãO·YQ³…nÐÕPϲÞfÅ0{ÜÈ …D²÷cÍ®1c Öd `žiÉ|ß›²¦¥îƒ>(kZêæ=^ ÊQÑç’³/q·xž(_aDµ^·(k^¡Áÿ&e ¶óê´£0)kv)k0ªAþbΚ–ƒm‘Ö´l÷Ø$­yËþ„gàAb¤5X¸ ±1iMhÍ!NV··x²ÈU>''i fys¿ÜÓ«Rí¯Òš=9&­ù>}xU¬e-Òš]cÒšœÏøš¤5Mð=ÕëÔ¤5-ù<Ÿ¤5-ky¬ÄÙ³½VQ%»Åœ2f­i)X&'kͲYk Ž öÍZ³Ë“µf×ÀZãÔ¯ÉZã73DÊÓÈ9™ž°QŽ kY.¡1û¹ZÌq0sÍ©É\³ÇÒÌ5{¬a®ù>6•»±ÙªYPõï:̹ò³¦áçVM»BVÛGiÇž ëf³_2ï¡ng†NM¼ >®M%Õ21[Ç6ÍA꽌â]tãnP”x…  Žå#t7ʶ!²‘±±?øsp_*¿<5>¾´Ë„»Ï67ÂQññM:Iã¬8xÚ‡Õ—MAÉïö“ëª3gßZ‰šU†ÔЏb‘w4qå´_*ŠmZgE<³øža¯ªlO†bM|ÑÑzðy‡0R#|‹"‡º†É†Š\|"ö˃r.äâœíc!#掅,é âì]W1K«¡– öŠÏc}2d$_&áÉ»X"¾tVì1™kãgMðü|ÔàM~Ëv…i\ð×8âŒq°IGØBAƒƒ…þ.ÞOÑ/ÀiNî©·&r`W‹Ð”a¤Mq7Ïý_¿ UÏÑMè=w|çÆä§ÌŸ ðvä022R¬Y†ü«4%'“GØe‚˜N¼¥ØÐ™âÌ×¾¬yÒj¤¸•+ ¦ Ÿù¶ä˜fižè2HÝå<óeåí!Z”ðr‰›Å&«¹žišÞÚ±Q™ûQ_%lι ÊV]W×Î_?VÓ¹R2Ö–¿÷ ÛXÐ"ùÃ’SÜ­¾ÊøS¨¯U–¨Í¶ãžŸ*A}Oöq(¸urç\¸Y±:÷9ª|[lš1¶)kƒÍ—me_å2#¿ˆšŠ–à'Äq<ß¼heMà0]K‹ÉV¬)/_>nÌ2GVå+hd°?)èìrÜ;5HÛjëÛè‚ ú66cuÒOvÉŸf¬f?œX–Îåar8‹@·ø3“õ[6ù®P0#µnŽ:Ÿ¾­ú¢‹×Nã¹V[„üXÍ-=A›-âåÅ+ëN¨hè¯vˆ2+ÔW£ŸŒ‡b—5Þij¦Û|Ÿ¸Ò´x>B#Ç©%×ÂL­õy¨!˜Zlè-ºÞ%ô­Ñ¢ãØ|Bq–®wô´Aú‡,úóÎržñB»†û‚ËAÉW’Ë(a¹…Õ³]׉ÍâÕÝDÌ£œƒ•h`Ú«–¯×Œ9jiølØxŒ0ÏqwlŠm8wg+¼wƒšý %5‚Pí®fˆæØ®L:Hdƒô^;ŸËóìX•èo/a:ïuµUKÚܵ–ƒÑÏ>€fÓ;8ìœRI‚Œ²°Hƒ,ö§æüÚå°HÊP ïÊ–@ ΜŽiÍ^œÉ¨ó>Ì’ÿèÕ[˜ï`ìš:½’nSȪ—ŠrƒëÇqÞ"Nc×tO0ï®®(^=€—·f“Š£²‡L>QyOcR¹€ØsØ9*‰o9}arLëeÄY_ÏGMJ«Õµi'iîûœ›'5ù²=¤Ì §/pâØ)ªdççC7ú6”èFztVuUD¨Nê*boCi׈-ÃøßÊ <”Õ-Ä) ˆk& 8ÝþÁ˜á^¦c·©`™2Aó Ód|}ßm6%¾ý6¡NðV~×aÒÀ¯©Î§Ç†þ¨©Ž'lðöŒÉý£0±à/Ê3Ú-›ªF†Àñq{)ô—˹4 ìëG‹ŠU8ÜÜ:¥,zæ² €sxa’M)·ëìQ–íÁîY“+ÈÏÜ3 ô/Dtn™—£æ­%èžy7é¼Î• I¹ŸºNè˜Y‰FZ‘b+ÍåYŠséGœ›5ÂgÍPœrñ¼qàçë;Ê4îqæ[µ¢u¨P0±²g¨^K£„ ôé’òªÚ§ е$…«|œaºcë€X-.´l=’½m²ßÞ+ú©^ò çµ*êM‹U–Fåø¨9ÆæÛê³™«[RØWª6s‘ €ÖæWìÓÛ'¦`-”ã¥åÒRÄ]‰]«…‘WïCo™Z²½Dè¥;m^ÜŠg™K=°?«…l\”³õP ^Q{š6¯TøˆÍ+:" ÔDöv¬Y V_F¿– gJøö¥Kú*#KL„RLD2Ð(=|ôâX|Ñí–7ž\…! †t©•Ú'W–U °$ÔÕ¥µ-b–¡Í‰O×^„ R²¹0;7Aɨüøƒ ADVïφ:{`bªa«(9zL]N…Và~;$‡ºòœ²…(¢¼[hÔš¥Óè÷ÕnÅ5¦aòLÉß*d\¨õ¨ÑÙÙœ˜½D/˜ 0;éV@Œf¦«wªHe(ŽzN”œ¥Z,ïnR(\‹ø+9o¿nÝaf'(Æïfú­Íå0*‰qµx€òa c-:P¢b2HWŒf%¶ÍY‚1àc#ªýݬ˜6h=þÞ5àdtÏ_1n»H7š€1 p-®X‘·ùmÄ d#¢©#¥õ;¼õ^娉c7P–bh!õ «½"âB¥«ÜüØžm•ˆ’43[F¢B~T Í)îJÙ¨ç'#–‚ÉF^'IuÎÔ–8J§t}Ò\õnaG#O`›¾Yïˆb ãLðäy k³Íþs&ÂBˆ¿ó8Ê£~R éZ•oâ—Š½Ôã'?*ÄŸ ⪑%̯såA¤÷BO.ßPËiÀ:&Ô¢v-vò2ž~Y¨Ma5s·´zçÉ=—°Új4ÌËÆ%®d–õ‹qOj7·x’™ÚœTSŸnb7ó `FÄ;ÃW_˜0ª3T º”FQï   n›5ƒ¢ÌKƒía¶pŽù€6²ù³“Iªïäµ|¯ƒù]Þ²ù`d]Åë1Ë%PVÍžÇÃý£â˜ÔøÍšãèý¶Z8z›òÿ¾ž) n¤óz6kæõLÖ¶§­ëYsŽæq=“A/íÛ™ Ї&Øp1â¼ âovƒÇºzÜÍšÌóÿÓÚ™+[ÛHÔ×W´=†¢¸“Ÿ1¶BVOÈzýÿ®*Or{Ëxm—¬ËHyÛfuâž,ÛL¹ìF8¶Ù¢m¶8Ë6#^=ÆYµí1Îêƒ×ð6ΔOÂygecÈnëLYýzÞÖ™®úÒ8¶—{}g8^—Dºõ»ÓÆYÉ$]Æ™†X¯iœ­iYÆÙ—‰ãš”äE—q¶8Ë8ÓÕ7ÝÓ8Ó嬔Àcœ)Mã“q¦«p™€Ëôš³yl3uü¹¬79kÖvl3e;ä/·mF¶Ãql³2ŠÁvl›-òØf‹³l3>Ðm¦¿Pšâm›Ñ†pl3Úxä÷êÄç«—»À…eš­q:¦ÙÉeš­‘^¦Ù—¹@žWuNõO7ÆŠ•ˆ\> ´÷¥yoêZèJ[ÕP£…œrÜ5à”³»–öéæ± nú^uŠÝÏå**©0$tÖÖäT’¦”óF@g¸þ fÃV‹ÐE+Ï€m¬ÍÁoä%‹‘’"&ÌÖ'ªýbkÖ0†u^5Ac«–È͹&³€ˆè5©kf}#àîíþD¾ò™L†=-´ä—ÓŒeüR¹'uJK¬:ĵñî Ú+èãw& ˜ÌA™Õq :­æëÉŒXG¬û5¹:~õ¼é„Ôï3ýºF—jUeãt,0TLe´äÆà™ æEY›s£—(æmÓÕŠðµk1hí.1Ñë+vã¢$¥t>ØÛÃÀçj„ »°»¼šƒu%_¿Î¢¡W´Üù+»†¤ôù*gIþ±Ñ« ¼ËRöS:"ì|쮚|É¡D!z_¯¹øºÂW¡tj¢§6ʘ¾ÎRõ_á>bj3ß.Ñöm„Þ­4›ÕÀO¡ÍÙÌÆ·Ë€a¿4‘[ººŽü¥èó ÷Š!ñF[u$Ö=ÎÁZN²¦q½Æ¿“åT(€q¹ÆqÓ‚gp4Íâľ®¾G·Ä2HEgC“sÏ@æN#C æ¡• ©>mpVŽÎAxýe`ÖÎÊ¿‹*Ý¡¤f°Œ••dXóú"Õ®u® ·œÓÕ§î¤`j«Ý±¯íÙAçÈ/Ñ Vuî•Ln9æ¶U KgF?’®Û´µdËÑ ÓÑ7ìKhà]æv&ƒä…á§ ½ŠuƒXéÕf“e"÷Nð%…>é´ÍR¤ùÇaÃÇç±V²Mñ†tÏca Ybè:(Ügi­Ï}‰_”5ù ‚Ä,Ê’ÊCR[×BHâ±—tÐAEK´PÀÀŸsvc$†i¬-¹¦ÄÖüâ›]¿N&Zeó³°šétæEYLWsüP™îwµ„ï—V6û}µîséý£–ðÿ=%tƒïHq~lÔBÖ¥Ã%ZÄkO”àñ^:›.@ʾ4>èp¾jŽÌ'ÀF§8 ¶D9N|±@°@§âÝ4¶?0¶ö¾ª|cØCŒ„‹èàU=_œ«ÎâoŒëgïé÷~kÝÅš×_ ò3MmÉEÑ–ÉÓ-Ƙwó‘~šQS°AÄÝ’³å©0f ™ÙzÝÕ·œ<Æ{•·<•ï]LfòB~Z]ŸáB Jµ‘¤ÕNjq>G÷Çɹü7O—öV¬D,Dj¶Ÿë \\ëUæ?ÿó×>¥|ñAÙÞÚÝ3sº³9Ww6o·!F‡˜œï¯§[Ú§îü­O©;ÿú¥ƒ}¼jã¿=¿þïJ‡Ÿ$ÇÕÑD†©_Í93²2Iô™è> aE¿ŸpÞ½?‡Ñ‡3,§aÍŸ8®ôñõ+‡!{yÜ_-xÀÝßøÆq¯ßLJX¾¾Ñ9°~âäæ˜µ4t­T†ÈÓü<z©8>èää–™ÎÞˈÜÎ&™+:}" 6ÒÌ‹¯ ‰4¢ü…€»Ÿè,ab/MDG’9c¬è'á —dÀðÒªEbŸfåÌ£M9ØIÎP‰„MVÆ»÷hN kõ¢mZ¨Æä¬ñ¤Ý¯^ó¡xEäßá$Ò¾4A!/3øKg©ô´ÂC¥§u·30T$_yiJÉÑݯÙP=ÎõÉèÇ4çKÈìÏðì˜V‡ŒX‹óÎg÷HdT(æ·G·ûÙ—C˜­ *±ÖDÂeùЉø}VÍY‹÷ʰU+týAÃù#Ð{ ¢”IÀ„ç,÷ô*A‡Yn/MŸ1ôqæñ¿é³ÃÃ'/Š0ÿ°uÜû÷xŒÁíÜ¢O' æ)шÌéêwî‚÷g£¬°8 7{šÒÒ¼6Ÿù…E‡jßÅÃI—VåIîó?"0þ9!Ý[ñØú«V^ÛgT¯¡½¿ÔÍ^O 9I<ùT—D(÷L–Ý =sžH‘èÈï\^rL‹$) ¤f¦„™œñíCð®6G›CÃ~HY!iU3åÃ$+-¢„Ð$èNôuÒýggò¸)Lºÿ¬É“Yû¦\w ÿÑç8è­LäpÐ/Ë%iKò„eÒÏшÂòù¼DïNE<~þxk×L·9ÓMÔeh¹Iç?êã°¬´kTkW­|má#Ö½…;yzN‰ND·pò`Æ=»´;[ä*EQÿE?FqGýõµ_¿Ù ØÔû°Ñº²š4õ4geY© [þÄÑFZšÛìD w5.|«–@oGZÇìÊúÃà$¼Õàº%¨°»;îÑ–MF‡~’÷ÇnƒRåO…õÁÙ}Q™ç:-ùL¼Dˆöñ„A'°BÊÀŸ^²»Î=†Æ©vü%Ž…S]Xפž3æp·ç¸átgo¸l‡,½ .a³¢¥,l-péù$åä8”.9(¿¢2Û¥­¥ü`mXŽz÷’*M¹— Í^óÜ;ñ¢GsðÈæ”‡DüY¢XµNYÂ9¡ø‰ÿÈ>ÿE+ò°L‘t:´-ƒ†;Î=—8„ë¾tñÙæTe/=Xkò˜PÙ—vÇžÁÉø ž·ÎÑ}@XÇU¢Ï£/’Æ—éc§ÅîðwOh¶è”ÐY¬-¡sèèÜ[‡LB/mQX|k•£ó,sèÇÙª©ÍðÆ nuégûG§2¹„´aöó*ám|‘*Ñû4gïwÆÎ´È—&KûŠÉȤnF?*GOÖ¦µ½¤Çu°©#‰XVÿ+4:ÜŒJÎrãH)Sd93uý *²"šB·ZØ&ºz™š¥O)Mß­y*ȪE“×ó”èÁšèãÚ-ÁÜ&)éóäͨ÷8zPv‰ÊÎ |øÝ¸™‚ೕÝ:úÖ¤îÉÑ)WÛàFþ¿ã*7ö'ïQ<´œsèÃæ„0q|GŠÒ[:M5I J—(‚ÞËrµ¯ìå¨4˧¦#`PÒ2)¶è£‰^ôGö>U_Ò²B‚j±Èj¿¾Ê´{‰‡<1Ƶ‘ÆÜì–j‰6«WlÍš¬…ÇɸóŒ€Krsg›«Ær?† –ζ7¥G‰’g/Yþò!eÇöœ¥Fv#ôÌ—N¶lRØn:Û,9döÖÎSyt¶$ö̰ŒìsÁ¢8XaÛY‰Z Fë¡Ù¸Öüv‰öXøÛÙ€ú\<Õ6¢“|ӈԽěU˜ˆøIž*%÷\S¦œNõ’hNth%ãj?L&ǘœ:ØÚO™pˆ‰´Ô .·8Y¾M*z÷Ò*íxÑ5 vòu6‹ŸŸ,»<•yÒ½mOÎÚ²-ÅBrRîƒuá*áD—Vßß•I6‹ÆÊ¤xôn–î^µù°xxp›9t˜IE'â┓-£¾H‘Ò›üLR.„˼’jM¨¿…Ü£ùU!ÇåUN~ìBI ¾­9+ùuðiä ¿¬iBœ§ “àÖÌ –KžÖtZçK!ø9+ýyšÂ?hÐú˜çQñp–[Gï[Øxj8rî¼'KzIâä,`|Òê€\®Ö‰ƒLªä3Ø'3Žªå™§Å,ÁÃéT‹E‚¥ÄH'·2KRgÇÌÊž‡b+ñÐF£Æä8lÉ_˜{£Î¿˜6ˆÕbg§ÉðÐjù3îݹfçì_yž±dW‰Jâ4Œí@ÝMë1Ƶè{¶Pa`§ò6†Üç†f®˜Ô0파–©ú(V޻̑R™§©¾6ŠÜÀZ¿·QŽ—%,7Á:¿ ‹mï–/+nrDo6×xææ³„–‡çJÎ)ó3¯:Á4ÐOôðJ“ÝôhŽÚ-‚d©Òç}ÆWÆVîwcã‡{«¥ã„{ãÔ™ƒügýõªó…¦õõƒÈYHƒ!7 {²0Ožïe‡ôS§š÷ê‘lža¾œÕããdÞ,rdD¼ÖŸæýùt»®ß%ÒÔH_—ÖÛ¿ÖÍèºÏNvœbû(¼sÑÊçßl_õîû«¯œ¤÷„y!¼y~nÁÆ ¤ÚK#…ÿ¯^VƒÜ.#¬Ú¿ô)P§×µ¯°¦c¸P§çãp®ûíÍÛ—ÒŒ‹®(ö…ó÷z©>>îûí¿õ)І¥™^?hç;›sugóv²ÞÛt|îﯗeùòúð·>ø®|YÑ‹rðçâ<¤ú8p|ãá}¼*×£À,ÆC–Ï*÷Öݬ©ÕVp÷ŒÃÉuªr= ŒDtF¦,è±iÕx¾·§DZÿa¨R½–âÿ4Rsö)Z%ä†+n´;â&µ:ó,? ÚKâú»ï.Þ?à}ãÕÍ»Án[âÍêe¼½üµ•ªX0>͹Öb7\6ôOïa¡8V²¾E½©J9v»kWy 1ScÄË\ŸP¼ƒj427E;\t©¶°'wtã±/v¿ÀÕ6T&ljÔäŽü¶š39Ê4>éO›üm(J!i퉘Á¨‡|¡k „¨×aO¾À¡ôõú)R‘ÌÀÉh¨1º=}â§NNy|ïC¡2u;ªT½áVú„ÁÊ?j½á˜×\ujèÔ“%˜ ™„œN ,eÒLÎ!§„œ]üƂ塙¿|ƶ'»Q¡“w/nv¿ÉòÏ9Ì‹AÌ+õ S91-«‘å¥C°f•S¸àqHþ¬%z…iÙ¸^-SeÐKHʋƨÆm‚PÊ&\è^qà`Ýd¾+ôñÈìQKØÀ³s&úp=ÊZ “#'_aL·€Á…3'42½rk XûÚuUû8ö®ê1š1¸“sMzn#¤É*QØ-/mô+6U3üÕXµú‰'š&4¹@½¾ˆ8Ã9R5Äaϧ?' Ç×9Ó?q”º‚¾k}ãÆS>q zAXÕ[VâT¾'¦ç͈•l©Lš AŸ¾|eëæ{¬–MÎÕV• nÙªu81lQÆ’ehóÚs³ÎøÐJÞÊ17ˆ¢qnª&êâ<›$ßp6¯çdvD¾Î®>ˆ~Ù%ºý„9«ºð*;) âXÞQ€(2L£Läχ]Ò_}èÖœ¦îpÎä9åÇœkÐf­8>Ëá´ ¬ÈîÖÒzíauF7m/5“çTEˆêÝ îCöfÕGZ¾·óáæx¼?ÕÈ>诅ƒ|`Û^4ϦŸ*|šô¹x›Œx¬É‡ó훲;ÈÊÏÓíýÿñ_¹;¡endstream endobj 6 0 obj 59493 endobj 4 0 obj <> /Contents 5 0 R >> endobj 3 0 obj << /Type /Pages /Kids [ 4 0 R ] /Count 1 >> endobj 1 0 obj <> endobj 7 0 obj <>endobj 8 0 obj <> endobj 9 0 obj <>stream UnknownApplication Untitled endstream endobj 2 0 obj <>endobj xref 0 10 0000000000 65535 f 0000059789 00000 n 0000061286 00000 n 0000059730 00000 n 0000059599 00000 n 0000000015 00000 n 0000059578 00000 n 0000059853 00000 n 0000059894 00000 n 0000059923 00000 n trailer << /Size 10 /Root 1 0 R /Info 2 0 R /ID [] >> startxref 61409 %%EOF numpy-1.8.2/doc/source/reference/figures/dtype-hierarchy.png0000664000175100017510000004447212370216242025314 0ustar vagrantvagrant00000000000000‰PNG  IHDRõÃlsBITÛáOà IDATxœíÝyx×¹?ðcÉ`lYHŽYà•Äd©Y¡$<Ü…°$¸Pj“xL mRLÁ@¯mBJ @)-ô)¹·¹7O ·¥˜%ÍÃM ¡¡tIãX@%¼I²c˶¼Ë:¿?ίªj-3’F£ùûùKÍœ9ç3óήJ)ð-6Ò€èÃ>¸ö?¤?øˆÁ:þ)"]:¤ ŒëôŽôɨªR€T*€.kU¤ à€T‚‘ÑmE2ª*€ U¤ à€T‚‰ìÝt7oÞÔjµ}š ,--U(f³ùÚµkÇë­·!&“I«Õ¶µµ­_¿¾¬¬ÌϘMMMK—.µZ­<òˆkFk×®Õjµf³ùÒ¥K¯¼òJU€Câ¿;õôôŒ3¦±±‘}=sæL\\\WW—B¡0làÁƒ-ZT__O±Ûí”ÒÚÚÚøøxJ©Ÿ1»ºº(¥õõõJ¥Ò5fKK ³¶¶6ЪÀøk#‰Ùlv8'Nd_³³³ !‹ÅétN›6 t:yyy„¥R©R©!±±±N§Óÿ˜jµÚ}FV«•RšžžÎ¾æçç‹Ð:€è†T‚¡~o‘HMMU(MMM,[466BRRRbbbØæ¾½½}ppÐf³yNÎÌäädBˆÙlfÙâĉÏ<óL@U€p­D¢V«—-[¶mÛ¶¾¾¾ÖÖÖªª*BˆV«]¼xñöíÛûûûÛÛÛ‹ŠŠöîÝëuò€Æ\°`AEEÅààà7\—: hH ž£Göôôètº‡zèÁT*•„êêjv››;iҤݻwûš< 1›››SRR víÚ–ÆŒ&x®ã¯;Ùíök׮͛7eˆS§NmÚ´Éd2‰XÁñ_UG …BQXXøÆoPJ-Ëk¯½öÄODºRÀ Rˆ$!!áÔ©S‡V©TÓ¦M›9s¦¯‹ 58 8ªHÀ©#£+ɨªR€T*€î€á¹Nï¸z—Ô†@@*@ÒØV½ ²p 8 U¤ à€T*€Rp@ªHÀ©8 U¤ à€T*€Rp@ªHÀ©8 U¤ à®ÿÖvýñ=€ìàïÜGÀQpˆ kéQœ™ÙaS70 `ApFÄ+U¤ à€T*€Rp@ªHÀ©8–*bbbü?ºÂ9‚ÄE}£–݆ŸÖöú|l4E9ê°Œ è6þ ùº@ΰÊý QßÀ(€eA@·á„kÀAÈTá?ñFAZŽúF,#º 'US…¯ô5i9ê°Œ è6þá¨8Ÿ*<“p”¥å¨o`À2‚  Ûø£ à–Tដ£2-G}£–ÝÆU‡p¥ –£8-G}£–ÝÆ«XÎ÷œ„©ä@—¢ìHF_OuEÒÕpé)Z¯ð5DîÝ&†R#ä› Â-ˆÚÊ«D†ˆY¬,²¨¤¸V2&‹M°,*éRH‚ŒÞö,£ª©8 U€ŒÉâ O•ô©$AF'seTU¡ U¤ 1YäÉ¢’þ!U€$Èèd®Œª ¤ à€T^&“)ÒUˆf²8È“E%ý 8U †ØØØ çâä¢ñZÏ›7ojµZþ…444L™2EÐzE-ÑNæ†Þ£à¼óè144´hÑ¢„„„çŸ>ÐEÏÖw¯SÉe;& ÑÕÚMž<Ùf³ñ¿§§§··7|õÿŒFã»ï¾k³ÙÆo0š–­ïN­‚<µcÇŽäääÔÔÔ²²2‡ÃAéèè())Ñh4©©©?øÁü ” ¶¶¶•+W²znÞ¼ÙUÏ—_~™5óûßÿþÐÐû®„Íf+..Öh4z½~Ïž=l Õj]±b…V«Õét˜3gÎððpbb¢ÕjLâ…Á`ÈÉÉÙºukRRRVVVMM ù÷=;ƒÁ0nÜ8öáî»ï~饗’““ÓÓÓß~ûííÛ·'''ëtºwÞyÇUàˆ%ë¹4 CFFFaaabbb$Z |ù?È›>}:¥t„ ï¿ÿ¾k çâ>zô¨^¯ïêê"„¬^½º¨¨ˆü{ÑaÜgáuSP%e!˜T1<<\__o4?ýôÓ+W®°è¬Y³†ÒÜÜ|ýúõK—.UUUù(AkÖ¬Q*•¬ž—/_fõ6 F£±®®îã?Þ½{·û$¥¥¥ …Âl6_»víøñão½õ!díÚµZ­Öl6_ºté•W^Ù·oŸR©´Ûíiii‘i˜|pžÌ5™LZ­¶­­mýúõeee~Ƽ}û¶B¡°Z­/¿üòSO=¥V«­VëŽ;ÊËËÙžKÖëÒljjZºt©gš‚óΣÇ_þò¶¸z.îoûÛ<ðÀÎ;Ïž={îܹcÇŽ¹Ħ ¹þǃ§úúzBˆÉdb_Ïž={Ï=÷tvv*І†×ÀÜÜ\¯ëëë•J%ÿÙy ¨¶|&ñUOBÈ;wØÀsçÎÝsÏ=®Êwuu) £ÑÈ~=xðà¢E‹ØÀ––6°¶¶öÊ•+Á56ˆ6Êÿ&³Åa·Û)¥µµµñññl +¼õõõqqq®1;::(¥×¯_W(”ÒºººqãÆ¹Fp_²:Îsi²Ñººº­*HʈN¢T*½®¼”ÒÛ·ok4NwòäI÷ñƒØˆÙ@Ñs­"&&&++‹}ÎÌÌ´X,­­­”ÒŒŒ ×@«Õêu`°-Œ|Õ3&&&33“ ÌÈȰX,®I,‹Óéœ6mûêt:óòò¬V+¥4== ÌÏÏÇYN)•J•JE‰u:þÇdw(•Ê1cÆŒ;–¢P(¨Û_Íx.ÙK“M®V«ÃÕH áuå%„äææÎŸ?ÿÃ?\¸p¡ç,Ú„^I &UPJÍf3Û&šL¦ŒŒŒ””BHSSÓĉ !wîÜÑét^ YwŒ¨§Édbç‹Ü›i4]¹„MÓÐÐÀ6%íí탃ƒì\¹k’'Nàš6A¬H …Âét:N…BÑÑÑмܗ¬^¯7›Í#–¦Ÿûä¾Îr^W^BÈ{ï½÷Ç?þqæÌ™Û·o?xð û$n DmX‚¼¬]^^Þ×××ÜÜüÃþpݺufñâÅååå½½½V«µªªêé§Ÿö:PØÚ ½ž‹¥²²²¤¤„ýÄšÙÔÔ´sçÎuëÖ¹&Ñjµ‹/Þ¾}{{{{QQÑÞ½{µZí‚ ***oܸQVV¦R©œNg___„Zåôz½R©¬©©éïï?räH@Óº/ÙüàžK3Lu†ˆóºòÚíöçž{nß¾}ÇŽ;~üø•+WFLЦ@܉$˜T¡Óét:Ý„ f̘ño|cÓ¦M„êêêþþ~½^?uêÔ¯|å+;wîô5P‚ÜëYPPPQQAÑétz½~âĉ3fÌxòÉ'Y3Ý'a;¹¹¹“&MbWºª««›››SRR víÚU\\»ë®»"]±E&UÔÖÖ&zˆHMø;|øðÊ•+G{òáµ±Òo/€,Èâ1YTÒ?œ€’"ÙU Rd±²È¢’þáp@ª“ÅÞº,*éRH‚ŒNæÊ¨ªB-/!Çê ´Q‘*¢àè¼’ÅcYTÒ¿ÿŸ*°Ó ‘åþ.?‰‘û:}Ü7Ä¡/åC¡J–;Ùç:_ØZŠA·ñ —µ€Rp@ªHÀ©8 U¤ à€T*€Rp@ªHÀ©8 U¤ à€T*€þO`QóÿˆnXõ"(Z×Óðu*U‡ØHW :a‡üˆÖ]ZÙ‰¦õ4Ü GÀ©8 U¤ à€T^ü¯7âr7Hî€ [½ýÜJÁ9D7J):IÄEß"¹EHÂðºT°“îbb¼?ñŠ~"šè[OEkžÖç‚AÁ³“¸Ž6\_ŭѨ}멘-µ €ÈõÎ,Œ6HðŸºe·«á€NqÑ·ÄlRp@ª†¯.Ç]t’ˆ‹¾E Z‹*€R…`<Ó¸|wU LÐI".ú8-BªHBrOærßU0A'‰¸è["´©8 UŒ¥ôèØU0A'‰¸è[ánÞõ¯‡f]QqH˜Jަn ÀŸàk¨Cx¶Hpá(™5 ï€òù7I‘E%£›Ô6Fnž@:d´:»ª*›D–ŒVo8õ%WUq­€¹¬ÛÑGFïU”QU…T oQ¼yé@ªÇš&‹J@´BªàÙ:RdtêOFU R€¼Eñæ ¤©Bkš,* Ñ ©€dëH‘Ñ©?U5PHòÅ›'Tmmmbb¢×Ÿ>ùä“Pº RE¨kšÉdª&~`sD¬Îžäù)S¦Øíöp”ŒTÁáæÍ›Z­Öׯ S¦L³>)^³µÿî!¬QÛÙ8Oý †ØØ0¾ÎŽ䣸,%R‡É“'Ûl6_¿öôôôööŠYÿÝCX¾:[ož$"²«ùæÍ›çúú»ßý.++Ëét¶¶¶._¾\£Ñ¤¤¤|ï{ß$g™ÌfóÂ… xàË—/‡R §Šø_Ó\;,ƒ!''gëÖ­IIIYYY555„9sæ '&&Z­V›ÍV\\¬Ñhôzýž={Øä%%%l’ÊÊÊqãÆB<Ç4 ………¾Î3 Õ^ã„«{oËúèÑ£z½¾««‹²zõꢢ"BˆÑh,,,LNNŽÏÏÏ?þ+o(V­ZõñÇFöõÍ7ß|úé§ Å3Ï<£P(ZZZêêê>úè£ÿøÿðœöÙgŸMJJ²Z­ÿ÷ÿwâĉêAe+¤fóŽ@}}½R©d!»wïv8»wïžÄéÜ#¶v»RZ[[ïþkWW—B¡0lªƒ.Z´¨§§g̘1là™3gâââ¼ŽÉ ïêê _C¤¼-G86£þ»‡×eM)½}û¶F£Ñét'Ožd?F¶µº}ûö‘#GâããÙ´---l„ÚÚÚ+W® UÐFuDd!ÝÝÝ”Òëׯ«T*ö“gT=W´€"ϹòòŒa ¡~ûí·ÙÎÇ‘#G¾üå/³ZBáÚµk±±±ôßS…ç8A,b×$øk£^¬T*U*!$66Öétºÿd±XœNç´iÓØW§Ó™——g6›ÇĉÙÀììl_c²ÂÕjuè•ÿÂFÏîákYçææÎŸ?ÿÃ?\¸p!û©®®®¨¨¨±±1///''ÇétZ­VJizz:!??ß`0„¯Q2:9é52J¥’ÿQ*•‡ƒýäUâ±¢ùàVÞÐ>ÿüóW¯^}óÍ7Ÿ}öYB«Þ;wrssÙW…]t:݈qBªD IF:„ª¿ÿBÜw]ûtõõõìT’k`GGGLLŒkoå‹/¾hiiéêêR*•®£ŠsçÎÅÅÅyÓ½ð *ɇÜwèBŒ€×iýw¯ËšRú‡?ü!55uÁ‚/¼ð¥Ôf³7î½÷Þc£]¾|ÙÕO\û¶o¾ùæ/~ñ _GA7ʽ¹tÿ‘qßkTG¬hF>¸•×S¡~î¹ç.\8vìØ¶¶66ä±Çc§Â,ËÌ™3ËËËé¿UPJ¿þõ¯»Æ™={vóuM"ãËÚR0vìX§ÓÙ××§Õj/^¼}ûöþþþööö¢¢¢½{÷ªÕêeË–mÛ¶­¯¯¯µµµªªŠâuÌH·ÂÂë²¶ÛíÏ=÷ܾ}ûŽ;vüøñ+W® ²ËãŸþyyy¹ÃáÐjµ ,¨¨¨¼qãFYY™J¥bmÄ\è(;ÜôŒÌ˜1cãø‰|WÞÕ«W_¸paÉ’%ÉÉÉlȉ'úúút:Ýý÷ß?{öìÊÊJÏ©ª««[[[SRR žzê©jh’‘qêï·qhhèÑGMHHøôÓO[[[W¬X¡ÑhÆ¿zõê¾¾>Ji{{û²eËÔjuVVÖÆ(¥žc±c(¹/îÐ…¯ÓúïÔÛ²þÎw¾SPPÀ~ݳgÏ}÷Ý×××wèÐ!N§R©fÍšuöìÙ„„„Û·o·´´,]ºT­V§§§ÿüç?wu¶ ›à¿u2ê#"ã+øžQ={öìˆ- È{]ÍÅ9ªˆWUe|œ]•rýívûµk×æÍ›§T* !§NÚ´iS¤û”~¸Â ðCÊÁ‘Ñ…:žU•c‹p*Œ Eaaáo¼A)µX,¯½öÚO<éJA´‘Ñi/¤Š0®i §N:|ø°J¥š6mÚÌ™3ƒ>³‰ÍDlŽƒ< uÈ,‹ƒÁÐ+)å3 â1’í'‚T ÝCL’íKžp JÈe£²†T!5M•€h%§TÁùÂ;¼ÏÂ%l¢,[˨{H¤|Ȩª’ß‹=¼žTâ%"„+ê#ʉï¨E6WWÎNDsdq‰)¸J†#\ò2"t–Kpd±†2üŸ«¡2Ba-’ßQE8¸/`×R”Úˆ,m°¢ŒÔÖD?Cxö9v$ùõ~?›NÙµE—PˆÊT1j»nŽ*&µY€p“厒×]!96D"àÇè Ž*%§›e "d™*<÷°wàÂ…øà²L &¹¦ ÷ìqB¸?à$×T¢‘qªpý™_¤+""à‚þ ü\…øw—GêAë Háf|é<—îŸb%l‹üHC$U$-©‘åsÑ$*Ÿ…AB ”ŒO@@TÂ\‚NQÿn»PõÁáƒgd+U h8ªˆ0ìDƒôáu -QpñF^Çš|¢-pªûæJ£>8|Dß ýeTU“\:Ϭ†P&¯=P*@Zä²?>ªà¨Àà¨á(9G&“)ÒUð ;Ñ }"¥Š›7ojµZÁ‹5 ãÆó_xCCÔ)SŸõ(5×h4Fº £Ep}j$pªðµ4yòd›Í&ì¼xÞÓÓÓÛÛ+Ô¼"{Td\Aî€Z´hQBBÂóÏ?o0bc¸‘ïÎ;®†Oy.W¨çÏŸЄäßûL˜º.ˆ&\G?ýéO'L˜˜˜øµ¯}Íh4ºwÐÎÎÎ’’’¤¤¤¬¬¬ÊÊÊqãÆ †œœœ­[·²555lL›ÍV\\¬Ñhôzýž={ØÀŽŽŽU«V%%%effVWW·Þﵜ9sæ '&&Z­V¯zÖÇë¬ CFFFaaabbb˜‚Æ)j2nˆŒFã»ï¾k6›=è´½½½}}}ìsXãÉŸ”w¢C µ{Ÿ‘H¨!haI­­­¯¾úê_ÿúW›Í–™™¹wï^÷_7lØ@ill¼zõêéÓ§Ù@“ɤÕjÛÚÚÖ¯__VVÆ–––* ³Ù|íÚµãÇ¿õÖ[„uëÖ)Ц¦¦k×®½÷Þ{#fíYΕ+W”J¥ÝnOKKóZ ×úx³©©iéÒ¥V«5”à¸gM¶;O|$9"ÕŒë«Ì@“nÐ1œ>}:¥t„ ï¿ÿ¾k`GGGII‰F£IMMýÁ~àp8!F£ñßøFrrr||ü—¾ô¥sçιÒÜÜìµÉ™™™çÎóÚ¢ +(«ÕºbÅ ­V«Óé8@ikk[¹r%kÝæÍ›‡Á`¸ûî»_zé¥äääôôô·ß~{ûöíÉÉÉ:îwÞ!ÿŒóË/¿œœœœ––¶uëVÏEsôèQ½^ßÕÕEY½zõÔ©S½†Ú³2„£ÑXXXÈBŸŸþüy÷>ÃBí«‹Žˆs\\œH\LLŒ”S{QA±m6ÛøñãwïÞ]__?<çææºµdÉ›Íf±XfÏžÍVIWó=¢ÓéüêW¿ú /ÔÔÔ¤¦¦Z,÷¹&ô¬Œ+ÔCCC¾Bí«‹zí9aôºÌsã)ø¦5|xV5,©‚RzñâÅÇ{,...//ï÷¿ÿ½«Óܺu‹=µÏÔÖÖºo¤¨ÛÖó³Ï>#„hþI­VϘ1Ãÿä¾¶Âl ÿ½ŽÉÊ kª‘䤙q}•É3éºREWWg¬|ñÜuvv*І†6ðìÙ³lsi4‡ÑhüÅ/~ï'UŒh2k‘«Ì3gÎQÕ ° µ´´°¯µµµF£Ñ³u¬Î”Òëׯ+ŠJi]]ݸqã\úüóÏÙTçλ÷Þ{ýï9QJoß¾­Ñht:ÝÉ“'G„ˆ}ðê¡¡¡Û·o9rÄk¨ýÄyDÏ6¤žBÙíã³·}©",ï€êì쌿páBooï믿^ZZúÁ°ŸRSSÙ飉'B}’’’ÓÐРV« !íí탃ƒjµ:66öÎ;YYY„––þµòZ J¥ò¬×1Ã}¦U©TªT*BHll¬Óé$„h4šßþö·{ö쩪ªÊÊÊÚ¿ÿ=÷ÜÃF6›Í‡ƒÕ™’í«‹Åât:§M›ÆFp:yyyV«ÕétzNî§2î¼–éµJžcºÊg±Jkk+¥4##ƒ}ÍÌÌd'Êêëë—/_~çÎI“&åææz¶ÅųɬE®2=£&V«•RšžžÎ¾æççߺuËkë”J%»V¬T*ÇŒ3vìXBˆB¡ nt÷Ýw³Ïîë‹×…HÉÍÍ?þ‡~¸páB¯Õó꺺º¢¢¢ÆÆÆ¼¼¼œœ_¡ög÷ž300xØ"&¬}ñÉ'Ÿ<øàƒCCCÞS ¸°Üe6›¿þõ¯ÿùÏNHHÐjµIII®Ôjõ²e˶mÛÖ×××ÚÚZUUå«(­V»xñâíÛ·÷÷÷···íÝ»W¥R•””lÞ¼¹»»»­­ÍÏä.cÇŽu:}}}^ ôZ¯cº70”à( §ÓÉV’ŽŽ?ã»2n{{ûš5kJKK]?¹2.ûÊ'ãÚl6›Íf4kjjt:˸lœ€2®¯2½VÉsLžó 4Î)))„×Üïܹ£Óé:;;Ÿ|òÉÿøÇV«õã?þîw¿P™¬E®Øú ²àÛˆäädBˆÙlf_Oœ8QWWGÜZg2™ÒÒÒøE)mnnvMÅv°¯ ‘òÞ{ïýñœ9sæöíÛ½–9"ÔæFæ‘ IDAT¬2Ë—/ß·o_kkë•+W6nÜÈ¿½ü;³Dx]ââ_Ãqå)ìÂp@C)¥‡Òëõñññ3fÌøÓŸþä~(ÚÞÞ¾lÙ2µZ••µqãÆ„„¯çd(¥­­­+V¬Ðh4ãÇ_½zu__¥Ôn·¯[·î®»îÒétUUUœ' †††}ôÑ„„„O?ýÔkžõñ:ë'ëƒÖÕÕ{úôé¾¾¾§Ÿ~zÄY2÷š •JuíÚ5JéÏ~ö3÷³”Òo~ó›Ï<óLoo¯Õj}ä‘G|Ç£”.Y²ä»ßýn__ß_|ñ裖••QJŸ}öÙ+Vtuuµ¶¶Î;—3ŒìL]oo¯Ÿ2=«äuÌÐ#éõ$Ò’%KØÕv^þ‡?ü¡ÅbQ(ï¿ÿ>¥ô³Ï>›;w®R©d ééé¡ÞήŒÝ7¿ùÍU«VÙívÖ¢Pêì‡çjøØc=ÿüóƒ!%%å£>rµŽ]ؾ}»¯:8«É¦jnn~衇^ýu÷©<MwwwNNNuuõ?þñÄÄÄ>úÈkˆ<+3"ÔsæÌq…šõ× (_qvï9áÛ.¹„{£\öïß?qâÄøøø &ìÛ·ÏápÄÇÇBT*•J¥úŸÿùŸ¿ýío„ÿüÏÿœ4iÒĉ… ¯Ñ™ÝÝÝ/^t8ìëÉ“'³²²D®CÄësèСääd½^øða?©‚J5ãú*S´¤ë5U´¶¶._¾|üøñ:^¢”þô§?MOOW©T³gÏ>{ölBBÂ7æÍ›—P[[Ë™*X‹³³³7lØJýð\W[ZZ–.]ªV«ÓÓÓþóŸ»·.--mË–-ƒƒƒ|R…R©|ñŵZíĉwïÞít:ݧò\4ßùÎw د{öì¹ï¾ûþö·¿y†È³2”ÒC‡ét:•J5kÖ,ê›7oºúŒÿTáµç„UXS…+a„å_¼x‘Rj³Ùþþ÷¿SJYn`ÙõõÙgŸµÛí®ý¶ÐCÁk4AfÆ®===‰‰‰¿üå/N§Ùlž3gÎÆ…­C@­Op; ¡O;‚Ô2.ÿ*ñí—¸*ÈZÄn( ”¾ýöÛ^G ½ªaj¬PÇÁá‘ÎÜÖ|Ää~’D…[,–ØØØ#Gޏßñá5U¸nF„DS¥ôÝwß6mZ||¼N§ûÞ÷¾ÇNDP@õ‘HªZÆå_%¥ ÷µ´´Ìž=ÛëhR¨ªWrIéÌaJî#Qìÿþïÿ~å+_Q«ÕsæÌùàƒ¨Táú*é¦ Y“Hª Ò˸<«$£TA)=þüÔ©SY‹^|ñE¯ãH¤ªžä’*¨GÏ!¤¡¤ >§›BiÂÀÀÀ®]»t:¥ô“O>‘Hªý@”áSC¹ÃuÄN^ ¢ &“éæÍ›óçÏ3fÌÁƒ÷îÝÛÔÔÔØØ˜™™yãÆÉ“'“ðÜ;˳ªøom€‹‚¿’=Üó„°KÍápüð‡?¬««¾ï¾ûþû¿ÿ›’‘‘±qãÆ/ùË„cÇŽ±„裆T!¾ *xN(£eʳªø¼Àà_ðB„ÁYsßmp ÂFç¦BtçÎx`Ä@»Ý¦Ù |”$£Ã®à„ÒÀ¨<ƒ £Xɨªr!ñËÚ<Ë—K¯ˆÌem×,]Gåáâ.¼\CBYübG"á :€‘•h]@.d“ú<…{¿ Ê \’€D’Ÿk ꃣ Ñð=ЗK{ÇÅű„»ÝN)­­­w³««K¡P´´´°©jkkF£B¡hhh`CΞ=›››ÛÝÝ­T*ÙÀ3gÎÄÅűiF#xðàÁE‹ùj Ÿ&Kè¨@Ö8³ˆ'¥R©R©!±±±N§Óý'«ÕJ)MOOg_óóóoݺE)ÍÈÈ`C233­V«Õju:'Nd³³³ !‹ÅétN›6 t:yyyÁ6‹I€>¯ç—8“„B¡p:N§S¡Ptttð™Qrr2!Äl6³lqâÄ FCijjb‰Ád2¥¥¥étºØØØ;wîdeeBZZZ!)))111 jµšÒÞÞ>88P3GÖ?”‰F9>§¤!z½^©TÖÔÔô÷÷9r„OÉZ­vÁ‚ƒƒƒ7nÜ(++KIIY¼xqyyyoo¯Åb©¬¬,))Q©T%%%›7oîîînkk«ªªbÓ.^¼xûöíýýýíííEEE{÷î ¥™H|¹RðLŒZ­Þ¿ÿÚµk'MšôðÃ󜪺ºº¹¹9%%¥  `×®]sæÌ©®®îïï×ëõS§N-((¨¨¨ „9rD«Õæäääçç?öØc®iÙInnî¤I“vïÞ@;=ÄqrÍgY¡=»#deÂJðª"tü''”ïIî› 3žA޾ž†k|É%© úÕÖÖ>òÈ#AO.Æ ¨Q{ÈP¡ã79ñÿ/Ñ(œ€’Žèëiâ]Öü¥Z£BÇ¢>b¤ ÷”%þúl2™Äœ°":¯$O F ÊDæfÙÐ×g÷7jùÑÐÐ0eÊ”Pf$5aÚFY<Ïæ»944´hÑ¢„„„ « +"]Ö¦nÿâ"©՞žžÞÞÞð•/‚H…Î+ÉÆSü(Æwß}W‚/‹á*|m/§—_~999955õûßÿþÐÐК5kÊÊÊØO---‰‰‰S¦LNLL´Z­Dè·ò NœÐy}2#—x†)J[¶lIJJÊÎξpáb4 “““ãããóóóÏŸ?φ߾}{úôé”Ò &„Þé“ÊÓÚAlò†‡‡ ƒÑh¬««ûøãwïÞ]RRròäIöëÉ“'-ZT[[«T*ív{ZZ!¤´´T¡P˜Íæk×®?~\à6DˆP磢;žœ cxxX­VñÅßýîw7mÚÄ®^½:??¿¥¥¥»»»¸¸xÆ lø¤I“þò—¿°P„½ê O¾öü¤†o{ø¼~–'ÿrV# Ê°—÷Þ¹s‡}=wîÜ=÷Ü344”ššzõêUJé¼yóÞyç÷ÿz¾•7¸fZUžŠ:_/C!ž!†ÎO øôs_Ó²æwwwSJ¯_¿®R©Øp£Ñ800044tûöí#GŽÄÇÇ»"àŠp"P‚¯Ñ.‘†ð’†ÌÌLö9##Ãb±ÄÆÆ®X±â7¿ùMffæßÿþ÷ÇÜývÏ·ò¾ð !V>²‚WÑOžQR*•‰‰‰ìûg1BH]]]QQQccc^^^NNΈwDŒ"¥ ¯‡9!né(¥®×óFö÷’’’µk׿ææ>ñÄñññîã{¾•7”¹‹FðÐùz²¬ãŽÖÙÙ¹|ùò3gÎ|ík_#„|øá‡§N ¥@ùŠÌµ vDz9ååå}}}MMM;wî\·n!dîܹƒƒƒ‡...&„Œ;Öétöõõooå ½â =t~^†5ñ¤ƒ ²[>ÿüóòòr×ÑÀh#Fªpßã*IBt:^¯Ÿ8qâŒ3ž|òIv)2&&fåÊ•--- .$„deeÍ;7%%…ŒñV^AªVᯗ!Ë7žaê`iii¯¿þú·¾õ­ÄÄÄU«VíØ±#..îÿø‡ …ÈK¾êÀŸ~úé/ùËЋòE¨ªºH$:¯„gˆUõžQ }îb ¢ªüã(1®UˆÖwm6Û;wŽ=úÆoˆ3Çp‹ìj/—xbãnRy®Bµµµ³gÏ^¸pa(ïÚÄü ^0D;©ú„O8N@‰6w1áHJ䟫 à9^ @‚ 7¤ ðN.Û_ye5™ŠªkHÀ©8HëZÎ9 ¡ã ‚„R…\®¡IBÇœ€HÀ©`t ìo2!’ºV!¯î+©³ÞO” Þ‘Pª òé¸Üâ tGî´Zí‚ ***oܸQVVöÅ_|ýë_ÿóŸÿœ Õj“’’ü— V«—-[¶mÛ¶¾¾¾ÖÖÖªªªå/^¼xûöíýýýíííEEE#.~€øÄ;…•9hOî! 4I¸TWW777§¤¤ìÚµkíÚµ?úÑ ~õ«_8q‚³„£Göôôètº‡zèÁT*•#ÊgG-¹¹¹“&MÚ½{w•Å×Q¼—åûÉÏ+°¯q¬ &“iÄ©RN‚WU¦¡óÊ£!fe¬VkzzzKKËÐÐÐêÕ«7nÜÈžô©¬¬þÉO~rÿý÷³1üñââb»Ýn6›gÍšµsçN6æ±cÇzzzjkkÙS?¶4ÐI8 -t®Øç¸¸8*búhBBB@³6n4¡KNNÖëõ‡vJœx†:‘åKww÷Å‹ûzòäɬ¬,AJv ¢ªÂ®ÑÂngÂM¨Vƒ/b<­-…§C…%ÚÓÚçäDêííeéSZZjµZ—-[6}úôŸýìg¡—ì¾§µ‚ Æ (–”D˜QôAèx9Px‚ F‘ÞÅsr¹lE;ªˆT}Â'LGâÌ]L8ªI‰üͲ qøk#ðBš/óÇRá†TÞÉeû+¯¬&S8*€RpÖµ œs BÇ ¥ ¹\C“ „Ž' 88*€RÀèô¿ÙÃh&¡kòê¾’:ëÐñ„@¹à…Q ¥ "ŸŽ+Á-BÇE)uŽ„<áÀh'‘SRƒ!6VZ;¯à‚T0êx=ŒHÂiBªˆ*1üøŸÜOùV«uÅŠZ­–ý !¤­­måÊ•&55uóæÍ‡Ã`0Ü}÷Ý/½ôRrrrzzúÛo¿½}ûöäädN÷Î;ïB CFFÆË/¿œœœœ––¶uëV‡Ãá>›ÍV\\¬Ñhôzýž={!GÕëõ]]]„Õ«W .à ©Fò“-Ö®]«ÕjÍfó¥K—^yå•+W®¬Y³F©T677_¿~ýòåËUUU„Û·o+ «ÕúòË/?õÔSjµÚjµîر£¼¼œ•ÓÔÔôÉ'ŸÜ¾}ûúõë—.]úÉO~â>—ÒÒR…Ba6›¯]»vüøñ·ÞzëÛßþö<°sçγgÏž;wîØ±caŒ$àÿt‡X °• +Á«ŠÐñŸò3 ÿ©87 ^‹êêêR(---ìkmm­ÑhT( lÈÙ³gsssëëë !”Òëׯ+ŠJi]]ݸqã(¥l„Ï?ÿœMuîܹ{ï½·¾¾^©Tºæb4Ù¯\´h¥ôöíÛF§ÓŒ3fìØ±„…Bá*?&&æî»ïfŸ322ZZZ\s±X,N§sÚ´iì«ÓéÌËË#„äææÎŸ?ÿÃ?\¸p¡p-^p `Ôñz~‰í<úŸ099™b6›Ù×'NÔÕÕBšššØ“É”––Ƨ”Òææf×TYYY®ŸRRRbbbl6›Íf3555„÷Þ{ïüãÌ™3·oßÎg 1REdï¬0™L‘šuèpS OT(ø$ F«Õ.X° ¢¢bppðÆeee)))‹/.//ïííµX,•••%%%<ç»uëÖÞÞÞ–––ŠŠŠuëÖ¹ÏeñâÅÛ·oïïïooo/**Ú»w¯Ýnî¹çöíÛwìØ±ãÇ_¹r%˜¦B°Ä;ªÓÊ|óæMvœëUCCÔ)SŸ©È°ä ;%|¸‡ˆ’p©®®nnnNII)((صkל9sª««ûûûõzýÔ©S ***ø”£T*SRR&Nœ8kÖ¬'Ÿ|ò…^1³Ùœžžž››;iҤݻw¿ôÒK999Ï>ûlNNÎŽ;JKKûûûª9„"&ÐŽâ¯,ßO~ŽX}#`eƒÁŸŸ?â>¼Ð ^U †n“É”z9!V5¬Zºté¥K—žyæ™M›6Ôs¾ô¥/±[9D x>zÍ´ðu*aWLú?DæZ…€{®'< CNNÎÖ­[“’’²²²ØÉÍ9sæ '&&Z­VÏûÁåg<(£Ñøî»ïšÍæ£G:»žžžÞÞÞ@§Šˆ Ž$DJ¾vñ„Ýê™L&­VÛÖÖ¶~ýú²²2BÈ•+W”J¥ÝnOKKq?¸€ó +qB7yòd›ÍæëWYlCÔôéÓ)¥&Lxÿý÷]=Ÿ/#„ÆÂÂÂäääøøøüüüóçÏ»ï”ÑàP[[›øO„×o¼ ±ÁUÆu/6»SÛn·SJkkkãããÝõ¼<Ä–†2¹×E +&ìs\\ý÷0fggoÙ²E«Õfffž9s†Rš””DQ©T‹Åb±,_¾\£Ñ¤¥¥íß¿?ˆ–:ɈÉè‘aŸüñââb»Ýn6›gÍšµsçNJé¼yó¶mÛ600044´k×®œœ÷iD \ÍŒT"EFU•/©Ü,+È>²R©T©T„ØØX§Óéþ“çýà¡ÏN"?•g$¨@uuu;wnïÞ½*•J§ÓUVVþ×ý!äÍ7߬¨¨`ž%''[,–0Ô@B„O¾’çT‚×Äçýàa]p¤º_|Q©T644¸ïîî>þü+¯¼2nܸ{ï½÷ƒ>|Ö|ˆ¨ÖÖVêíù²ºººÙ³gëõú§žzêòåË#öK¢Oä*ø¬äA;v¬Óéìëëó¼--mË–-ƒƒƒ”ÒC‡ét:•J5kÖ¬³gÏ&$$ܼyóÑGMHHøôÓOCi ϪúšDÀž9š×Gð$Fªà™™d´¼EKa Ý¡C‡’““õzýáÇù¤Š¡¡!×v°¥¥eéÒ¥jµ:==ýç?ÿy@ó ¢ªž“£ù™DØT!#Bµ|ãim)<*,ÑžÖFè<''”ïIþ(ÂCŒ—£ï ¡ãI:ª­­}ä‘GF ´Ûí© €PDzÏÉ¥³Âû'æ; "RŸð ß; D˜»˜pT’ù›e@âð/xàET¾÷‡\ACªï¢lÕÉO48*€RpÖµ œL BÇ ¥Š(»†&&„Ž' 88*€RÀèƒ 6( ]«W÷•ÔYo„Ž'yÊAˆFA@$”*ˆ|:®·8Or ”/¡Rê*$j†ÉdÊÎÎŽt-¢N@Œv¡œ’2 ì¿cC444´hÑ¢„„„çŸ>Ð2¦L™zÀiU€Ü,\"{„a4ß}÷]›Í6~üxƒÁд===½½½aª08ªˆ*1üøŸÜOùV«uÅŠZ­V§Ó8pÀý§¶¶¶•+Wj4šÔÔÔÍ›7;ƒÁ““³uëÖ¤¤¤¬¬¬šš6fgggII XYY3}útJé„ Þÿ}?BŒFcaaarrr|||~~þùóççÌ™3<<œ˜˜JÜÀ?¤ ÉO¶X»v­V«5›Í—.]zå•W®\¹âúiÍš5J¥²¹¹ùúõë—/_®ªª"„˜L&­VÛÖÖ¶~ýú²²26æ† !W¯^=}út\\Ü_þò¥Ri·Û ü¸zõêüüü–––îîîâââ 6\¹r…Mž`!Dп/±@a+V‚W¡ã?ù( ”/B5s³àuF]]] …¢¥¥…}­­­e›iJigg§B¡hhh`PzÍêÚIDAT?={677·¾¾žb·ÛÙÈñññ”Òžžž1cÆ466²1Ïœ9W__ÏÊ¡”²Ï^ ¤”Æ¡¡¡Û·o9r$>>Þ}ZÿM>^£®UÀ¿P¿YÄjµRJÓÓÓÙ×üü|×u…ÖÖVJiFFûš™™iµZ !J¥R¥RBbccN'!Äl6;މ'²1}ݹä«Àººº¢¢¢ÆÆÆ¼¼¼œœV&„N@Œ:^Ï/±Gÿ&''BÌf3ûzâĉ>ø€}NII!„455±¯&“)--Ík!©©© …Â5fcc£×ѼØÙÙ¹|ùò}ûöµ¶¶^¹reãÆþ+ B#UàéР!tÀ=Dü“„KuuusssJJJAAÁ®]»æÌ™ãþS¿^¯Ÿ:ujAAAEE…¯BŽ=ÚÓÓ£Óézè¡|P©Túš×ˆÓÒÒ^ýõo}ë[‰‰‰«V­Ú±cG\\ÜðððܹsÙQ„IL Å_Y¾ï˱ûG¨Ê„ûÑM«ê*H#t|„Þ«¾@ †üü|v;f(>ûì³{ï½×f³577Z Ÿ:„¾¬y>?¾Ne·Û¯]»6oÞ<–!N:µiÓ&§D^M¢Ld®U„¸›|óæM­Vëë×è~tS„#Œèo(Šîç‚8’–B¡(,,|ã7(¥‹åµ×^{â‰'"XàC¤Ták/¸•yòäÉ6›ÍׯQö覰¡ãC¦á0Px> ¬N:uøða•J5mÚ´™3gîÝ»7Ò•.Þxb5øWÆuu}}}vvö–-[´Zmffæ™3g(¥III„•Je±Xl݈– ^ 8¡aÄÍìqqq”wxƒnipº&S \­êùÿÒ`Ÿ¼ïE|F¢‰¾‰I*7˽칯çÚ5óu¯^” ëù(?á ßLÄg Ä|>`öìÙz½þ©§žº|ù2ž)>UøJJœS=Ç_|Q©T644]ˆˆ:>$^ÿ;>œÓò™žðù£ >+¹žûz£Gˆ¡ã#:ÂP ð|€'‘REÐO‡BXC§P(œN'Ë¡A ÏŒäÿˆ> ~ ä3Sþ•ñ¼rHÝ®ÊÞºu+&&¦··7àð&lܨˆ¡¡««+66öôéÓ}}}O?ý´çemÁÃ+xèÜK_ ¼êîî¾xñ¢Ãá`_Ož<™••%`ù^…/€‘š‘h¢¯EbéÅ#Và°Î.++‹íš±»Vd-Ü¡S«Õû÷ï_»ví¤I“~øa>“¸Â+lMB$rc¢þùž}!‘§¼‰ñ´¶¯áž£‰³†‡Nðª"t¡K"¨?üá[¶l¹yóæøñãW®\¹gÏž„„Ë÷$£e ÑD¤{ðœ\.ë€h©"Rõ ŸÈVUFò% šrµÿWQ[[ûÈ#x—ã‘…£Š`à¨"h8ªQ4ä(òÏU€Ä!U¤ à€T*€ƒ´n–Å•ACèxB ‚ ¡T[ƒ†Ðñ„@' €Rp@ªºV!¯ë’:ëÐ@XI(UùlD$¸iFè |p 8 U¤ à€T*€Rp@ªb¤Š˜˜ÜM„¤@¼£ lõ‚†Ð@d‰‘*Ü$ÆV/ HAd®U´Õ3 ±±¼€D¨r"+¸„@(DJ^ßP„Ýd>:ˆ8áSEŒþÇçYx[[ÛÊ•+5MjjêæÍ›‡Á`ÈÉÉÙºukRRRVVVMM ³³³³¤¤„ ¬¬¬7nœ å¾ ûŽ¿Á`Ñp醈©Ü,Ë3[¬Y³F©T677_¿~ýòåËUUU„“ɤÕjÛÚÚÖ¯__VVÆÆÜ°a!¤±±ñêÕ«§OŸS9RèáEdcZ[ B¨X8«á«2õõõJ¥’RÚÙÙ©P(Øð³gÏæææÖ××Bìv;¥´¶¶6>>žRÚÓÓ3fÌ˜ÆÆF6æ™3gâââ)ÇÕ–p„È—€Bçj&ûG¥C‘C‚ˆü%JÊûZ[[)¥ìkff¦Õj%„(•J•JE‰u:„³Ùìp8&NœÈÆÌÎÎG9Ç?t.!È‘H' ¼ž$aÉŠ!)))„¦¦&öÕd2¥¥¥y355U¡P¸Ælll G9â4t …Âét²ÍtGGLj_#C£È\«4I0fñâÅååå½½½‹¥²²²¤¤Äë˜jµzÙ²eÛ¶mëëëkmme§Ñ/'"8C§×ë•JeMMMÿ‘#GFüñÒV ‘^ìáú\’p©®®îïï×ëõS§N-((¨¨¨ð5æÑ£G{zzt:ÝC=ôàƒ*•JAÊ ºæÁ "tjµzÿþýk×®4iÒÃ?ì9BdcÈY"®‡ðœ‘€•éîî¾xñ¢Ãá`_Ož<™••%H9ìƒ8q£‘K˜b(Zè@@"½Øƒ†p$…BQXXøÆoPJ-Ëk¯½öÄORŽàUõOüй„)†‚×D •ç*„•pêԩÇ«TªiӦ͜9sïÞ½‚”#xU%+L1¼ž ‚˜Hí´zЉ‘Peü“ZU¥V?dTUp‰Î£ Rp@ªHÀ©8Dþuîðw=ACè |pç"pøPüF+vÔc*IEND®B`‚numpy-1.8.2/doc/source/reference/figures/threefundamental.pdf0000664000175100017510000000652012370216242025516 0ustar vagrantvagrant00000000000000%PDF-1.4 %Çì¢ 5 0 obj <> stream xœ¥UMO1½ûWøH‘Xì^+U=‘z^mB"´‹J@ªø÷¯C ¨"ÅÏã7ÏãñxöɺÁ[Ç¿6N‹¹¾ÍvÿlÂí#köö§) ,ºb}Îbrö¸3wÆ€M©ØE!3f¶ÇÒí »½†ng¸Ú!ÇäÑû•.p¥cÈÝÎ°Û v;Ã՞͑­ Ìã.Ë„þ¡¹"¡T£L¶P<‘h IxžèN†ÉtUàL0 )È, ´úé„ĘÎ1“þ¬pÝtõåPD’ÁdvÍr‚„oR™n¥'ƒÍç٪ϭzDŽÖ'œšŽ).º¼NÑÑÒ}ާM"Õ„\c†à5-Í»Tv&UDµ ä<£œN1½q• I¡ì4¯¸…М58¤É‘Óú€z\QûD%ë8:'W.'»¼²4“@ Éz ¯¥ÁÌ7ÉÐ`†»£8þº´z1j´„y…w憶ߟ<—÷zº!ÞïrùUÏÃ'R€éâ¡8© ÆèùŠ¡‚[1:Ojévæ÷<øì³./ZÊç?Ñ—dÖ­°|$O ø÷OeI»Vàm ³Â"]IÙVɹpÕÚ ‹­ã¯¬×߹˙Â?º…ŠúL—NþEσ4:§ob9A*̤íK¦R¥ÁÉŒ™Ÿ¸@/B ¹ƒyÛ]½´>§`2>Å x&\Š> /Contents 5 0 R >> endobj 3 0 obj << /Type /Pages /Kids [ 4 0 R ] /Count 1 >> endobj 1 0 obj <> endobj 7 0 obj <>endobj 11 0 obj <> endobj 12 0 obj <> endobj 10 0 obj <> endobj 8 0 obj <> endobj 13 0 obj <> endobj 9 0 obj <> endobj 14 0 obj <>stream UnknownApplication Untitled endstream endobj 2 0 obj <>endobj xref 0 15 0000000000 65535 f 0000001009 00000 n 0000002832 00000 n 0000000950 00000 n 0000000799 00000 n 0000000015 00000 n 0000000780 00000 n 0000001074 00000 n 0000001260 00000 n 0000001403 00000 n 0000001195 00000 n 0000001115 00000 n 0000001145 00000 n 0000001345 00000 n 0000001468 00000 n trailer << /Size 15 /Root 1 0 R /Info 2 0 R /ID [<9CF77C21ED22F00BC8AAEB42A864F6BD><9CF77C21ED22F00BC8AAEB42A864F6BD>] >> startxref 2955 %%EOF numpy-1.8.2/doc/source/reference/figures/dtype-hierarchy.dia0000664000175100017510000001117012370216242025252 0ustar vagrantvagrant00000000000000‹íMsã6†ïó+\ÎÕ‰o ÎLjsØÚÃVía³—\\´Ä‘µ‘EEÏŒ/ûÛiY¤D %ÈíªØ±b2ÞF£ñëo?žfWß²b1Í矯1J®¯²ù(Oç“Ï×ÿùãï?«ëß¾|úu_ÿôÕ}\ßÖ¹]{ÎŽg?§“ì¡ÈÒ¿Ú˜­yôsVl>öé9_LM“òõy«IËsìç•6u«…i4Ÿ|ùéoÉOÕ¯TÿàýYM¿h«‘ò)-&Óù¶óÞ̪7‚ E1o×J'’IüöžnîaXs³aÍÚ›.îŸó¢,Òi¹mò!ÏgY:¯¬–ÅKv¼Å(™!¶«[½ø:-Ë|Ïïÿ5-ºt úñRm‡*wRLÇ»…»Ö¢å)ß§ãòñþÇ®·+A„ÿŽU^Ãø6]LfYS¦óÒû/þöø×~¿ù7r ¹ç˜¨žÖ:IŒUÆ3~ø$1y™Ž³ÅžÁ¶Þ¦åIu³Û}ïúf»®oLõ£)Û™˜¥¯YQ?þ÷÷Éúªþ×ܹJGåôÛÛw+ïIþðßlTÖýw™ÎÇi1¾úùê÷üÇõ»'büéøóõ¿’õ7k³{æa††[ïÖsþ>¤0â7dMmi3ðð°ùüÂô OfÙÒã„Y3 ¡ò3ÄŽo(’Z zœål–=Ýòb¾í3ô×=gÄ‘e»‹+“—L¯|xØz̦“DzݘéÎqOÈ‹qVìëK‚Í OV>ðqöù÷û_µÃDvˆ3g÷‹òu–mZÈæ/O[Ô<äÑãtñ8Ëæ“Ýï&rÏã«V²î ó?²åŠÐq-tì-tbôVæÄ(M(+ïDcTi­´oÁžùl£MÛ(tË€µv+†If2µ,v̲mŽ[>/›ìÙŸ_}MŸ¦³×Ï×i1Mg×WnÜ:–W¯ýG6û–•ÓQº:mþ+l1¤qàJ%Ö>¨ŸÑõÁ×icfÝñرFM?CƹŸÌŸ²æ?æ;[ºZit+SÅ7÷+µcŽöË¡fƒøcÈLÈ"(…*gƒ#3“YgƒWΆDœ…v6<úžxçáiPo‰ÓRàôF F­°1åF׿óùûfŒF|>ó!A= ‚­kñîa†&bãøžuó/¤X›‘øà_ô¬nî­nÒÓˆ‡U¸[Chû¥R¸[C`Œ#ñ  ÷ê]çUÄŠ0°•ƒÊ{V¹ðVyp³j_j\"í4ž ­1ªñËR8cT­˜#Sð½ÈFúÊFVMíó.U£ª-¼!fFZ4’ÃDaÏŠV=Ì%·ú »u‡db&Ãz§ÞÆÖ·“! .kßþAà”~J×ÞJHº0Â^ºYn+?ŠpP‘ûu­‹ÆâDÒ•Ó°·îÏ»1’ÿY9‰¬ñ Ûe΀Û0³Q,Ë~Ù×YöæKÂŽYð³Í!{fç¼gÖF"ïAaFN‚zÂŶ5½Sˆ9·#A"™÷(›Àîý,Ú„@£iäŸ'hsEolF]ÐT"g#mhdƒDWFE.Rž–æÿ> –t²öÁÂ'mFSŒ`¢=Ditx0UF°õ•F4"*ÙçšµÛ†Óà #à#œü39’ÁWq•³ŽÃÜfM$ªZÈEÀ¦oùt<,é|ñáâI ƒx#úÈÕ€G¸æ‘ qÓˆâJ£Ç´HG%D–† *]ÂéìZÊŸ@åUnÜò|ˆBLq{, 1Á1 ¹ÏÎC@Õt-‡M,ÅkÆ8$–zÌå=¤–†Ü¦ÕµB !Ñê¬þ÷0{‡ß‚ êȧmÿDXë¿­as`Wæm†„4óõ •#<úÖ1Vö1—Bì3µw")AŸÉ/¶¦á·¹z4¨¨'°2wh¯ÞÿՌĭ‘ÐðZ\¿‹õãí2¼¿Q¯4ÑÐÌVG¿šQ„U'š½5šÍb¢™:)ÍH$4Ã6Q™±•‚‰NDŒ4ÃôÀ†@3 YD4#'…fÄ|bŒÆ3b‹µÞ½!À `ÌØIaæŸÕ[«N†M£3V¨³Âø6XlK.‰À0kì\{3µ§™Ý0ÈëØìøbY@2 Ù‘$c$;mÄŒ÷pªÓy$aI&Q‚)©@f-J§ôÐ kì[{³=„’.‘¹S#€@lpˆˆÉ“BLDâŽÄ…¬½1ŠuUc#óÆH'Ö½5È¢òÆx`µÜÁåÊMC—$u™à·2ƒ)WK4hYm¸Â  ·­ýSa“(“UcJC…ÁXT”x§MËÊË:szY>˜ Ìà ^†¯ÌµšW̓ækÞ¿’0Cäs¤UØÝ/fdn‹ KTë;,vWh˜ÕÅ,è ïžãEZæ]¤.Ò°—X&ýhÈL1t I$Ôª†4"j ùô4tÑÂýhH#6ÐVu2ð’Îe2~“Œè,Ó fnIG™"Çë¡ò´° ‚3ðäwæ+a²B!QÔÒµ=&…gRãh4ň&Þš¤‹:¿X™Á¢F“½*ÖÆ¿e hú:ËS8â4 šF# )F4‰>¼&w’g“pybÊÁI¢„8³< 6ÙÈ’ãàiÏ©aDŸÎ™O;ïßæþE##°v÷K†Ý«³×ØÚ’òîCš8³Q~l"[·[¸[{¸£)ÛÛ”vn¤µÂ;n7:Çëºw½®ò¾º¸«¼‰ô¸Ë›n\Nû¾Ì{7UìT´÷^2’l/7ŠqS‘Ÿ”Š:v**¤.ÚWTˆí÷7ŠqSQœ’Š"‰œŠ6Õõ’}EÓ?²×WÜjT*ÆMEyR*âØ©H.;®Hp‡¸âV# "P1n*ª“R±‡sõR68"K(«r Í–ÖîhºŸwª.a×µÝ>4êÆv@G ãÉé¨<èÈNºë"hät ¿értÜ¿õ¢ÛŽqÓñ¤»/‚ENÇð›/ç@Çý[0º±Ðè7O» Ãã¦ã›0g@Ç[1º±Ðè7O»#"§#ùqÇ[2º±Ðè7O»+#{8©‡¥’!éQ„‰5báxgLRŒ• :&úØ2PÝÐØÔ»­v‚Îvâ€VÜ|å=·HR.öt…l·‹²@g ó}àLôIá¬b†³BŠ],œbª H7Û» @Œˆ49)uÄ@´U%.Ö[µQË.žåV;"1j âSQúß}¡öŠ6Š’°ÅœÍj]ãÚ’»ÍJ׎¢¾ýÓÚÉMÙþ¦òð¦bï&½Zr»`0yjLjLÊ“F9%¾Lªàû@çƒI¹w7¨Â¤„Ý Àä%aò¤ñFIâǤY`âãMê½éè&5¤£&/“ê¤QHé}V‡¤‰2>y´› %­‘ÄF! C¹‘$x*zSïv´"{³ÆÍïÎ·Û b£Ëƒ÷ñÙNz4F²˜aÄ‚‡þ„ÛŸ«`ÄÎ$>0­Á(ôI”ßó+JÞ(ä}¥’{ ·1¸½ñÖØ±‹F"K8¶+9¢é‘ÊfÙÓý(/æY°ÎÊžai];É“åDZ×ß9[[eø7Œa㎠ÂôûÇqÆòbœû—hNVúfzwœ½Å£Ñ÷C:úkbX8{“°ýˆ~ôCÑ ò¡îë»|8JØò9º{ žËPOË}3Rö çý–²cXS«Ê¥ó#Ew†Î§£|œÁ5Xáï™i‰pÇÌ9ß1Ó2£ûçn»Ð=Š$c»×3:AØÍè2øŒîÙ=˜Ñ/ÚÖý¨G"2ˆ|ŒdU> I=„|Žïèç’õ£’~ô£‡ª¼ñH&…Ë“dîÑá”ã·P© ¹xT¸­Wô/ð\cp·|ÄHàªÎ`ËÇÜï>Ô-¥ C–^¡¬HTâD»›‘B;Á•‰„²³8!ÌY¥*4™çβÙ„MMð#žhx²Õî“É]îΨ㒻êGá0ÁÍîÃri}$’¢½Ô]yçà ›¤ÔcbˆcFµ³s'PâClB\ÈD¸­ní¸i©sC|ô’·K\Ç“wy9pí%C;mÚx14!Wy§Â)d33È©øc?¹üØàjê׎ £„BC@ˆ!B-?Þ‰„˜»½ÌãÓ a#Ž0gÊØaJRu‡%rÂ<èÎïºíœòµ “$ìÎ)’Êå~bs;¨ÅÌÌÌÓ÷nE{Ý7ÈÇéâq?1‘ÃÄddÚçÜÍÑÁµoí˜\p+|Ή³*äù‡fÌhú‘Ž .3@\¦y4Bp&ÞàŒR$­êɰ{í´:­(3|HQM ­AHko¦ßW÷[ &%; ¥×7P¡Xi]à >Å ÄIÃ=º¯—™ç(V20Ö°¨B+BÉ;k¹>:öÓÚÉåih ! S˜Ò°Â#­N &íŸ,‘äÀIºóØï`Òˆ>ȶXk'wó: )€ À4˜ NëÀ`j PiïLkÂuj%H…½ŠoÅÁLßx¢õÛõ|ç§2_Nj\¤óÅ©cTz-êž°à§uÛ$D©â;³«I׋„»"žfe4De–>\ag)1|2~ Ɖ²D¤,èZ„ó‡}¨JÓ¤$Ü(ãHIÔãY+%Ž«¤ÄQç?Õ?¦³¯°~?ªmDÂ\ÎsýF|d9Ù³ö¢°TUù«DàŠ9@1*ìbD&®jòHÃvwo³]v¥š»ÙåJTMôAÌ0=oþ:ï ä0xÈa5ØØ¥Q‡ ªïgékV|ùT}cþ›éÓ—Oÿé”úiá numpy-1.8.2/doc/source/reference/figures/threefundamental.png0000664000175100017510000001275012370216242025533 0ustar vagrantvagrant00000000000000‰PNG  IHDR¶¢òË£] pHYsHHFÉk> vpAg¶¢ã˜¾9IDATxÚíÝ»küÇq1ÇlL¼ / ÆÆU¡v- vvÃ` F[Hl,¡Õ JÆ 1Ym¡YkÐliqͯØj v^~Åg¿ó=g„ÃìÂ<¼_yx˜yØËðá¹Mb<Çã`‚Žáº-î¥Óét:íyžçyÉd2™LºnÜH"êõz½^¯^¯×ëõ¼¡åºu.µZ­V«¥H­ŸF¥R©T*®Û…¨"ø’jµZ­V£¿mý¬¸õ³rÝ"D‡ À¡áp8Ëår¹\ö}ß÷}×-ZÍf³Ùlêq©T*•J®[„(œtÝâ¢Z­V«UzÔÂRpT¤ë¶ :¹nñvÖc¡P( Ùl6›ÍºnûüÍ©õÐ4ÍuÝv,!€CG›û¨ð4)l%‰DÂñä±£µAý²³××zm»ÉÕûE4ÎsÀò£uCˆ`á´ô¤X,‹ÅT*•J¥l?ŸôhX<—Ëår9ÕTy°Ž­i£Y‰™L&“ɨNØÞD`v„HNP+¾ûý~¿ß×°¯žÕzp ‹w»Ýn·«ÁqU_uÚ†=Žk×F=Ë®–XB$ g·ãûj·E;Páo0 •(V*DVàqì&;l¸ƒÅ!D êG´ÖöY•ØY¼·X €cZ׬ÞJõ5ÚmÏõX[ç¨/3¸/£Ž£ ©>H:ù"DàX£Ñh4ZLcË 1µ˜&mèY…EÕÑ0·†¶ufFb‘,ФÝm¹‚ –ÂL:NÍ°å  ¶dúq€yaN$B#D 4B$BcNdìhW0­Â³;„Ç¡éùZõéº-ÀªÑ*iî ƒuCˆŒ]€´•ƒ>òÙ$ǧ¯"Z§©]è41ŸÕšÀ¼°ë‰ ÚBV[3°y,æKaQ]úŠ¢¯+úŠBß$àh˜é˜>Ήˆ†¶QO¤v•S¬tÝ.Àò!D:£AF}„%EIîf8B¤3Z:£¹®Û‚u¤loކéŒ>¼éƒ„[ê•tÝ Àò!D 4VgÚúì É–s˜„ @hZ©Ùí®Û²Xl†IÎÆÐ–‰D"‘Híú¦Í*`eúp‹‰…Ó]RtÇ”EŸËÞ—Åõû°^´ãïxÉq÷ÌŽ‰CêÃËd2™LFýŽår¹\.Oª¯Þ¾T*•J¥T_¯µaQ½˜z¬A[2Ëf×1T¢cª$eØW)nª¦~¶çU%öµÁ>NÍ‹Êår¹\ξ ö_¢§ÿ»‹/^¼xqkkkkkëÉ“'OžÝØØØØØ°W°K—.]ºtéæÍ›7oÞ¼sçÎ;w?~üøñc{M˜ý?"Øc·ÿMÇ_«ñsÀ,XXƒ¶çO¡GIÓÆÕ¯foŽg£•¨7NDZ›WÛHgÖŽ6Ëfg¨JlìÓcõR¨OB%vË÷àŽ‰“~j§îI­rGÕÔ{Ô¹T3Î[ÊF£ÑhÄ,R¬’?~üøñC!RUþ?ÆÙ³gÏž=ûéÓ§OŸ>mooooo?zôèÑ£G¶>€é‘8aC[°N‘È©\±ÏϾmõìGR)ÌMß~ÂÆD{Ìé·œþÓ°?·²aÿ;SŸ?þüù󺛶ë¶Ç¥ÿ¸k×®]»víôéÓ§OŸÖõáܹsçÎÛÜÜÜÜܼÿþýû÷'ý×ó… ˜s"H—ªgÏž={ölÙgÛè"«Çö½è=*êÙúšG¨švÈgºÙ :õ©fŸC©(i{=my°þ¤ŸFÚг aíÂ%ý‡¾yóæÍ›7ûûûûûûŸ?þüùóÎÎÎÎÎÎóçÏŸ?Î}ÂâLWf;Ë\ŠÅb±X´ŸG*×,vE»‹HðÙ°3òuF=kϫdz¬X„È#R¿Ôïß¿ÿþ}ïÞ½{÷î]¾|ùòåË·nݺuëÖrMè¶Jÿ6úÓãé}izwúG ÆMKývÁ:Ó 6}NƤµ„ºØöÛ 7OȵÊ^€t4ÏÐkí¥GïBõ£Y“@ò†ë¶ ]]uÕÕç…ò4iç Û)ü½Ûg5Žd£ú:¾=»^kf¯äö3¿´ g/ï ÂíÛ·oß¾­%#šm£ò?~üøñÅ‹/^¼8uêÔ©S§4GçÊ•+W®\¹qãÆ7\·ýĉÿû7h4FÃöð©\ÃÄvèÖÎbTMÕ±åvÞ¡ÊUS¿eEÃÙ0û{Ñqt…`ELÇÆ¾éÙ¢új¡ jûu|]z'ÕLbç—g Û¹ìÔÐõVŸ¿Áî•ôûý~¿¯}²Ì2#_×]ÛmpT}9ÎóÝ#âzeÏß–q=—Öç^¿~ýúõëö§:ß5€˜¯àŠlû¬•®[þ‹ÕÙ®VgëjŒeÁå’ª,±&=«¸ì>°g±õƒŸz¬°ëúwå^Œz"—‹¾=|øðáÇ.\¸pá‚þ(§OÙ†+v0}úŠl@ôÔç§A;‚¤OÛà.¿Gœ‘¯³hfpJ•žU«ìx)ŸòBˆ<"…wïÞ½{÷Îu[ðß"5À­1ú®ìº]€ShSÔ[ÜÌr{üIsúí ¶fÒ3m±°kÁjh~ŒÝÃÒ²S\·Ö…½­ƒÝg7¸ ïñÏ¢®»LÇž=¸¥ŒÄG‹žHà˜½ïWðÙàØÑô¯ú“žÕYìR›ÙÛ6i ø:£'àZÙAôDüfÒ+>²e[!Xkñ¿1#¸ÂüøéÎvF{¹£ XF„Hg4¯"þ7EĪÒßÞìw<€Õfï¸íº-ËéŒæXЉèi[›h°_&àh‘ŽÙ{wêCÝu‹°Ê´éº6Î%>ˆ}êþ1êÔ½jìÝbD_†u5K*±³½ÕMc)Z43i›ñégÉd2™LÆv©ÿRÏꘪlù*aaM,hÍ—B¤þXµ+·æÃñu ]F£Ñàï @Ü(ØéJ¥/ºúê«ÁuÕR¹Jô¹©ÏJ»…¸­©OUß~y¶›û¾ïû~°=“Îb?¯ƒ›þ(Pês|µ§ "cDûòë±>òíŸ8p4º„é¯kµ/g–â£îeï1cïX£§rm¤ëê—5lïãô*lÔÝco–¨€|•¶L?þýuâSyÃu[ˆ‚ÆIl?_ptN5þ‚AMG°ul_¦Êg‡QMEÆÙ°ñQ˜ bA1Q=y …ê;´ó ã‚}=CTPÇÔ¾³ßöÐ…ëU:£:BO$pLQOs"5 §þ<;Ül£›â¦ú,õ*;'ÒN³Ç·ƒÑ³·Íîh¡ÇÓ—ã¬B$pL¡P³mà³ÏÚÚÇvoÅG=«~JíqúÐ³Ž£POíÎ*“fF®B$ˆ…š1½¦†³F°Ž¢²ƒÏ·9 Þä°dLoϤ³¬6æD 4B$B#D 4B$B#D 4B$Bc‹æ@».û6ÔÓï% X„Hæ``¸n †³=‘„¦û;ïq²8ºM߃+¥n·Ûív• õØ>{8œÝëõz½^§Óét:Š’Êž®s0ÜÈf³ÙlVɰ^¯×ëuWëÙé'jµZ­VsÝ`ÄK£Ñh4år¹\.«ä¤zóù|>Ÿfî#–‹R¢Fª5cò!Òuó_š©ôx8œÍ HL§Y’ê‰üËucX>Z^ e©QžwoooooOý@Ñœ1mDùN„HBS|, …B!ú³¿}ûöíÛ·ÑœK› ±ôAG ‘v+òyF£ÑhG^%ºlµÛív»=¯cê"¨j×ïožvwwwww777777]·…÷µ¾ïKø–UºÚ¨GÐu+¢ íÍWéÓ™«Í¼«'’Ëbôño¬ úêý6õ³â}-‹Õ~_®[«tµÑ€²íÔÕeȦo6›ÍfS%º;ÎjüÖ„«Í¼0œ À¬FDV8¶!˜ä¤ë`ù"!¡"!¡"!¡"!¡"!¡9‘…B¡P($‰D"áúí/SÛ⃞H„æ8D6›Íf³™J¥R©”úÿÔ8‡Ã¡êèq±X,‹ª£úÕjµZ­Ú£õz½^¯g{í1õì¤cÏlg&“Éd2ªŸËår¹œ=¦Ø£©…zìöç 0_¹=}½^¯×ë¥R©T*)u:N§£øÕh4†¢žžõ}ß÷ýÁ`0 lˆ¬ÕjµZM%:B¥R©T*ö,¢#èq«ÕjµZžçyž§šz­m¡JÊår¹\V;UßÄn·ÛívÓét:Ö«ÔZµÓŽF_euUQ‰®HöÊãöUÖã©ø•L&“ɤJÔ“70ãl€SME@]ì"³Ùl6›õ  m/£^« ¢b¥ÊÕ×h/ª©Ç ¦z•+઎­zGý~¿ßï»ý Xvú«k-WI»Ýn·Ûºú¹z€õäx8ÛÆÇ æt ³ƒÔêí³ÑP—6õ2jÈ[ÄIG~«–Ø6ØálÅG•Áù¾àøt• F:Ñ•GWŸÏç5d<4Ô\^£gõ}ÚöZ £ŠŒE#"ƒèöqpÉÌ‹®~Ó¿¦—£|€uë)𳍠œ |Šw¶wP3#õX!ÒÎ’´C窌§êïT¹jê±–øh†¥‚£«m,°8ö¨]Í4Û^÷\½ Àzr0œ=iPXÆãñx<¶%º„Ùå/“”Œé5uÌé-9Ú‘ƒí€ãЗáÙ¯WÑ¿ ÀzZ‚žHÄ !¡"!¡"!¡"!¡"!¡9¸í!«g8‡ÃN§Óét\·åèz½^¯×sÝ ,B$sÐ4\·ˆÂCd>ŸÏçóÕjµZ­º~ ˜ÕûmŽF£ÑhÄûZ«ú¾tµtÝŠxYßòÞÞÞÞÞžëVDagggggg5~kÂÕf^Ž"¹8®†Z­V«Õ\·Àê[¥«Í`0 W¯^½zõªë¶,Ÿø˜„álBK§Óétz•b1«³0õÁëñI}—jµZ­VËuÃ_Ú@ÓNzžçyÞ²oI€EûGˆL&“Éd’þHLR¯×ëõº:Ur8'²R©T*m1ÊWÅGm§oCdb<Çc[U!R2›Íf³Y½@}–®ßEKg:†gØš‘–=„ë7€(̲?è„H ˆ}"!¡"!¡"!¡"!@¬%‰D"Q( …‚ë¶þFˆ@h„H a{«ÕjµZUI&“Éd2Á›©6›Íf³™J¥R©”jêUÁ#÷z½^¯§#' •èYÕ´uìñuöéÏÎrQy±X,‹¶*ѳº­ëß ÌÕÀ^g<Ïó<¯R©T*•¤Óét:­šív»ÝnÛrÕÔc•ëþ­ªoïåZ1칂5u4•t»Ýn·;û³ÓÏbÛiÉd2™Lf³Ùl6ëú·ó÷—ë `•)Bù¾ïû¾JÔ{g{"[­V«ÕÒcÕÔ«Ôr¹\.— Ó3ìцÃáp8 ¶Äy–gg?‹ž­×ëõz]ïE±Ruô¬ëßÌÃÙH½qÓëØ¡Þ`Œ ÖW¹B› Ëår¹\ž~–IG›ôììg±1QÙÆbB$€UEˆà˜¶3'Í#´a®oÌ·U³ŸEqSïBñQï–»þÀü"8fûê´EKj¦oë£Áb-ˆ .j™—ÙÏ¢w¡à«oú ¬6B$Ç´„¥Ñh4 …6 "+„éY;Ü\«Õjµš+ÞÙù‹³  Ï"ìY‚‘‘ `µ%´¾Æu3`hö¤†°µÊÛu‹`QX Çb×›³"Àú DÀ±h1†à5ø^*•J¥’ëvÀb1œ €Ðþ‡úBñÎ¥ tEXtpdf:HiResBoundingBox438x162+0+0ĬÚtEXtpdf:VersionPDF-1.4 G:xIEND®B`‚numpy-1.8.2/doc/source/reference/routines.bitwise.rst0000664000175100017510000000065512370216242024103 0ustar vagrantvagrant00000000000000Binary operations ***************** .. currentmodule:: numpy Elementwise bit operations -------------------------- .. autosummary:: :toctree: generated/ bitwise_and bitwise_or bitwise_xor invert left_shift right_shift Bit packing ----------- .. autosummary:: :toctree: generated/ packbits unpackbits Output formatting ----------------- .. autosummary:: :toctree: generated/ binary_repr numpy-1.8.2/doc/source/reference/arrays.scalars.rst0000664000175100017510000002563412370216242023522 0ustar vagrantvagrant00000000000000.. _arrays.scalars: ******* Scalars ******* .. currentmodule:: numpy Python defines only one type of a particular data class (there is only one integer type, one floating-point type, etc.). This can be convenient in applications that don't need to be concerned with all the ways data can be represented in a computer. For scientific computing, however, more control is often needed. In NumPy, there are 24 new fundamental Python types to describe different types of scalars. These type descriptors are mostly based on the types available in the C language that CPython is written in, with several additional types compatible with Python's types. Array scalars have the same attributes and methods as :class:`ndarrays `. [#]_ This allows one to treat items of an array partly on the same footing as arrays, smoothing out rough edges that result when mixing scalar and array operations. Array scalars live in a hierarchy (see the Figure below) of data types. They can be detected using the hierarchy: For example, ``isinstance(val, np.generic)`` will return :const:`True` if *val* is an array scalar object. Alternatively, what kind of array scalar is present can be determined using other members of the data type hierarchy. Thus, for example ``isinstance(val, np.complexfloating)`` will return :const:`True` if *val* is a complex valued type, while :const:`isinstance(val, np.flexible)` will return true if *val* is one of the flexible itemsize array types (:class:`string`, :class:`unicode`, :class:`void`). .. figure:: figures/dtype-hierarchy.png **Figure:** Hierarchy of type objects representing the array data types. Not shown are the two integer types :class:`intp` and :class:`uintp` which just point to the integer type that holds a pointer for the platform. All the number types can be obtained using bit-width names as well. .. [#] However, array scalars are immutable, so none of the array scalar attributes are settable. .. _arrays.scalars.character-codes: .. _arrays.scalars.built-in: Built-in scalar types ===================== The built-in scalar types are shown below. Along with their (mostly) C-derived names, the integer, float, and complex data-types are also available using a bit-width convention so that an array of the right size can always be ensured (e.g. :class:`int8`, :class:`float64`, :class:`complex128`). Two aliases (:class:`intp` and :class:`uintp`) pointing to the integer type that is sufficiently large to hold a C pointer are also provided. The C-like names are associated with character codes, which are shown in the table. Use of the character codes, however, is discouraged. Some of the scalar types are essentially equivalent to fundamental Python types and therefore inherit from them as well as from the generic array scalar type: ==================== ==================== Array scalar type Related Python type ==================== ==================== :class:`int_` :class:`IntType` (Python 2 only) :class:`float_` :class:`FloatType` :class:`complex_` :class:`ComplexType` :class:`str_` :class:`StringType` :class:`unicode_` :class:`UnicodeType` ==================== ==================== The :class:`bool_` data type is very similar to the Python :class:`BooleanType` but does not inherit from it because Python's :class:`BooleanType` does not allow itself to be inherited from, and on the C-level the size of the actual bool data is not the same as a Python Boolean scalar. .. warning:: The :class:`bool_` type is not a subclass of the :class:`int_` type (the :class:`bool_` is not even a number type). This is different than Python's default implementation of :class:`bool` as a sub-class of int. .. warning:: The :class:`int_` type does **not** inherit from the :class:`int` built-in under Python 3, because type :class:`int` is no longer a fixed-width integer type. .. tip:: The default data type in Numpy is :class:`float_`. In the tables below, ``platform?`` means that the type may not be available on all platforms. Compatibility with different C or Python types is indicated: two types are compatible if their data is of the same size and interpreted in the same way. Booleans: =================== ============================= =============== Type Remarks Character code =================== ============================= =============== :class:`bool_` compatible: Python bool ``'?'`` :class:`bool8` 8 bits =================== ============================= =============== Integers: =================== ============================= =============== :class:`byte` compatible: C char ``'b'`` :class:`short` compatible: C short ``'h'`` :class:`intc` compatible: C int ``'i'`` :class:`int_` compatible: Python int ``'l'`` :class:`longlong` compatible: C long long ``'q'`` :class:`intp` large enough to fit a pointer ``'p'`` :class:`int8` 8 bits :class:`int16` 16 bits :class:`int32` 32 bits :class:`int64` 64 bits =================== ============================= =============== Unsigned integers: =================== ============================= =============== :class:`ubyte` compatible: C unsigned char ``'B'`` :class:`ushort` compatible: C unsigned short ``'H'`` :class:`uintc` compatible: C unsigned int ``'I'`` :class:`uint` compatible: Python int ``'L'`` :class:`ulonglong` compatible: C long long ``'Q'`` :class:`uintp` large enough to fit a pointer ``'P'`` :class:`uint8` 8 bits :class:`uint16` 16 bits :class:`uint32` 32 bits :class:`uint64` 64 bits =================== ============================= =============== Floating-point numbers: =================== ============================= =============== :class:`half` ``'e'`` :class:`single` compatible: C float ``'f'`` :class:`double` compatible: C double :class:`float_` compatible: Python float ``'d'`` :class:`longfloat` compatible: C long float ``'g'`` :class:`float16` 16 bits :class:`float32` 32 bits :class:`float64` 64 bits :class:`float96` 96 bits, platform? :class:`float128` 128 bits, platform? =================== ============================= =============== Complex floating-point numbers: =================== ============================= =============== :class:`csingle` ``'F'`` :class:`complex_` compatible: Python complex ``'D'`` :class:`clongfloat` ``'G'`` :class:`complex64` two 32-bit floats :class:`complex128` two 64-bit floats :class:`complex192` two 96-bit floats, platform? :class:`complex256` two 128-bit floats, platform? =================== ============================= =============== Any Python object: =================== ============================= =============== :class:`object_` any Python object ``'O'`` =================== ============================= =============== .. note:: The data actually stored in :term:`object arrays ` (*i.e.*, arrays having dtype :class:`object_`) are references to Python objects, not the objects themselves. Hence, object arrays behave more like usual Python :class:`lists `, in the sense that their contents need not be of the same Python type. The object type is also special because an array containing :class:`object_` items does not return an :class:`object_` object on item access, but instead returns the actual object that the array item refers to. The following data types are :term:`flexible`. They have no predefined size: the data they describe can be of different length in different arrays. (In the character codes ``#`` is an integer denoting how many elements the data type consists of.) =================== ============================= ======== :class:`str_` compatible: Python str ``'S#'`` :class:`unicode_` compatible: Python unicode ``'U#'`` :class:`void` ``'V#'`` =================== ============================= ======== .. warning:: Numeric Compatibility: If you used old typecode characters in your Numeric code (which was never recommended), you will need to change some of them to the new characters. In particular, the needed changes are ``c -> S1``, ``b -> B``, ``1 -> b``, ``s -> h``, ``w -> H``, and ``u -> I``. These changes make the type character convention more consistent with other Python modules such as the :mod:`struct` module. Attributes ========== The array scalar objects have an :obj:`array priority <__array_priority__>` of :cdata:`NPY_SCALAR_PRIORITY` (-1,000,000.0). They also do not (yet) have a :attr:`ctypes ` attribute. Otherwise, they share the same attributes as arrays: .. autosummary:: :toctree: generated/ generic.flags generic.shape generic.strides generic.ndim generic.data generic.size generic.itemsize generic.base generic.dtype generic.real generic.imag generic.flat generic.T generic.__array_interface__ generic.__array_struct__ generic.__array_priority__ generic.__array_wrap__ Indexing ======== .. seealso:: :ref:`arrays.indexing`, :ref:`arrays.dtypes` Array scalars can be indexed like 0-dimensional arrays: if *x* is an array scalar, - ``x[()]`` returns a 0-dimensional :class:`ndarray` - ``x['field-name']`` returns the array scalar in the field *field-name*. (*x* can have fields, for example, when it corresponds to a record data type.) Methods ======= Array scalars have exactly the same methods as arrays. The default behavior of these methods is to internally convert the scalar to an equivalent 0-dimensional array and to call the corresponding array method. In addition, math operations on array scalars are defined so that the same hardware flags are set and used to interpret the results as for :ref:`ufunc `, so that the error state used for ufuncs also carries over to the math on array scalars. The exceptions to the above rules are given below: .. autosummary:: :toctree: generated/ generic generic.__array__ generic.__array_wrap__ generic.squeeze generic.byteswap generic.__reduce__ generic.__setstate__ generic.setflags Defining new types ================== There are two ways to effectively define a new array scalar type (apart from composing record :ref:`dtypes ` from the built-in scalar types): One way is to simply subclass the :class:`ndarray` and overwrite the methods of interest. This will work to a degree, but internally certain behaviors are fixed by the data type of the array. To fully customize the data type of an array you need to define a new data-type, and register it with NumPy. Such new types can only be defined in C, using the :ref:`Numpy C-API `. numpy-1.8.2/doc/source/reference/maskedarray.baseclass.rst0000664000175100017510000002414012370216243025024 0ustar vagrantvagrant00000000000000.. currentmodule:: numpy.ma .. _numpy.ma.constants: Constants of the :mod:`numpy.ma` module ======================================= In addition to the :class:`MaskedArray` class, the :mod:`numpy.ma` module defines several constants. .. data:: masked The :attr:`masked` constant is a special case of :class:`MaskedArray`, with a float datatype and a null shape. It is used to test whether a specific entry of a masked array is masked, or to mask one or several entries of a masked array:: >>> x = ma.array([1, 2, 3], mask=[0, 1, 0]) >>> x[1] is ma.masked True >>> x[-1] = ma.masked >>> x masked_array(data = [1 -- --], mask = [False True True], fill_value = 999999) .. data:: nomask Value indicating that a masked array has no invalid entry. :attr:`nomask` is used internally to speed up computations when the mask is not needed. .. data:: masked_print_options String used in lieu of missing data when a masked array is printed. By default, this string is ``'--'``. .. _maskedarray.baseclass: The :class:`MaskedArray` class ============================== .. class:: MaskedArray A subclass of :class:`~numpy.ndarray` designed to manipulate numerical arrays with missing data. An instance of :class:`MaskedArray` can be thought as the combination of several elements: * The :attr:`~MaskedArray.data`, as a regular :class:`numpy.ndarray` of any shape or datatype (the data). * A boolean :attr:`~numpy.ma.MaskedArray.mask` with the same shape as the data, where a ``True`` value indicates that the corresponding element of the data is invalid. The special value :const:`nomask` is also acceptable for arrays without named fields, and indicates that no data is invalid. * A :attr:`~numpy.ma.MaskedArray.fill_value`, a value that may be used to replace the invalid entries in order to return a standard :class:`numpy.ndarray`. Attributes and properties of masked arrays ------------------------------------------ .. seealso:: :ref:`Array Attributes ` .. attribute:: MaskedArray.data Returns the underlying data, as a view of the masked array. If the underlying data is a subclass of :class:`numpy.ndarray`, it is returned as such. >>> x = ma.array(np.matrix([[1, 2], [3, 4]]), mask=[[0, 1], [1, 0]]) >>> x.data matrix([[1, 2], [3, 4]]) The type of the data can be accessed through the :attr:`baseclass` attribute. .. attribute:: MaskedArray.mask Returns the underlying mask, as an array with the same shape and structure as the data, but where all fields are atomically booleans. A value of ``True`` indicates an invalid entry. .. attribute:: MaskedArray.recordmask Returns the mask of the array if it has no named fields. For structured arrays, returns a ndarray of booleans where entries are ``True`` if **all** the fields are masked, ``False`` otherwise:: >>> x = ma.array([(1, 1), (2, 2), (3, 3), (4, 4), (5, 5)], ... mask=[(0, 0), (1, 0), (1, 1), (0, 1), (0, 0)], ... dtype=[('a', int), ('b', int)]) >>> x.recordmask array([False, False, True, False, False], dtype=bool) .. attribute:: MaskedArray.fill_value Returns the value used to fill the invalid entries of a masked array. The value is either a scalar (if the masked array has no named fields), or a 0-D ndarray with the same :attr:`dtype` as the masked array if it has named fields. The default filling value depends on the datatype of the array: ======== ======== datatype default ======== ======== bool True int 999999 float 1.e20 complex 1.e20+0j object '?' string 'N/A' ======== ======== .. attribute:: MaskedArray.baseclass Returns the class of the underlying data. >>> x = ma.array(np.matrix([[1, 2], [3, 4]]), mask=[[0, 0], [1, 0]]) >>> x.baseclass .. attribute:: MaskedArray.sharedmask Returns whether the mask of the array is shared between several masked arrays. If this is the case, any modification to the mask of one array will be propagated to the others. .. attribute:: MaskedArray.hardmask Returns whether the mask is hard (``True``) or soft (``False``). When the mask is hard, masked entries cannot be unmasked. As :class:`MaskedArray` is a subclass of :class:`~numpy.ndarray`, a masked array also inherits all the attributes and properties of a :class:`~numpy.ndarray` instance. .. autosummary:: :toctree: generated/ MaskedArray.base MaskedArray.ctypes MaskedArray.dtype MaskedArray.flags MaskedArray.itemsize MaskedArray.nbytes MaskedArray.ndim MaskedArray.shape MaskedArray.size MaskedArray.strides MaskedArray.imag MaskedArray.real MaskedArray.flat MaskedArray.__array_priority__ :class:`MaskedArray` methods ============================ .. seealso:: :ref:`Array methods ` Conversion ---------- .. autosummary:: :toctree: generated/ MaskedArray.__float__ MaskedArray.__hex__ MaskedArray.__int__ MaskedArray.__long__ MaskedArray.__oct__ MaskedArray.view MaskedArray.astype MaskedArray.byteswap MaskedArray.compressed MaskedArray.filled MaskedArray.tofile MaskedArray.toflex MaskedArray.tolist MaskedArray.torecords MaskedArray.tostring Shape manipulation ------------------ For reshape, resize, and transpose, the single tuple argument may be replaced with ``n`` integers which will be interpreted as an n-tuple. .. autosummary:: :toctree: generated/ MaskedArray.flatten MaskedArray.ravel MaskedArray.reshape MaskedArray.resize MaskedArray.squeeze MaskedArray.swapaxes MaskedArray.transpose MaskedArray.T Item selection and manipulation ------------------------------- For array methods that take an *axis* keyword, it defaults to `None`. If axis is *None*, then the array is treated as a 1-D array. Any other value for *axis* represents the dimension along which the operation should proceed. .. autosummary:: :toctree: generated/ MaskedArray.argmax MaskedArray.argmin MaskedArray.argsort MaskedArray.choose MaskedArray.compress MaskedArray.diagonal MaskedArray.fill MaskedArray.item MaskedArray.nonzero MaskedArray.put MaskedArray.repeat MaskedArray.searchsorted MaskedArray.sort MaskedArray.take Pickling and copy ----------------- .. autosummary:: :toctree: generated/ MaskedArray.copy MaskedArray.dump MaskedArray.dumps Calculations ------------ .. autosummary:: :toctree: generated/ MaskedArray.all MaskedArray.anom MaskedArray.any MaskedArray.clip MaskedArray.conj MaskedArray.conjugate MaskedArray.cumprod MaskedArray.cumsum MaskedArray.max MaskedArray.mean MaskedArray.min MaskedArray.prod MaskedArray.product MaskedArray.ptp MaskedArray.round MaskedArray.std MaskedArray.sum MaskedArray.trace MaskedArray.var Arithmetic and comparison operations ------------------------------------ .. index:: comparison, arithmetic, operation, operator Comparison operators: ~~~~~~~~~~~~~~~~~~~~~ .. autosummary:: :toctree: generated/ MaskedArray.__lt__ MaskedArray.__le__ MaskedArray.__gt__ MaskedArray.__ge__ MaskedArray.__eq__ MaskedArray.__ne__ Truth value of an array (:func:`bool()`): ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .. autosummary:: :toctree: generated/ MaskedArray.__nonzero__ Arithmetic: ~~~~~~~~~~~ .. autosummary:: :toctree: generated/ MaskedArray.__abs__ MaskedArray.__add__ MaskedArray.__radd__ MaskedArray.__sub__ MaskedArray.__rsub__ MaskedArray.__mul__ MaskedArray.__rmul__ MaskedArray.__div__ MaskedArray.__rdiv__ MaskedArray.__truediv__ MaskedArray.__rtruediv__ MaskedArray.__floordiv__ MaskedArray.__rfloordiv__ MaskedArray.__mod__ MaskedArray.__rmod__ MaskedArray.__divmod__ MaskedArray.__rdivmod__ MaskedArray.__pow__ MaskedArray.__rpow__ MaskedArray.__lshift__ MaskedArray.__rlshift__ MaskedArray.__rshift__ MaskedArray.__rrshift__ MaskedArray.__and__ MaskedArray.__rand__ MaskedArray.__or__ MaskedArray.__ror__ MaskedArray.__xor__ MaskedArray.__rxor__ Arithmetic, in-place: ~~~~~~~~~~~~~~~~~~~~~ .. autosummary:: :toctree: generated/ MaskedArray.__iadd__ MaskedArray.__isub__ MaskedArray.__imul__ MaskedArray.__idiv__ MaskedArray.__itruediv__ MaskedArray.__ifloordiv__ MaskedArray.__imod__ MaskedArray.__ipow__ MaskedArray.__ilshift__ MaskedArray.__irshift__ MaskedArray.__iand__ MaskedArray.__ior__ MaskedArray.__ixor__ Representation -------------- .. autosummary:: :toctree: generated/ MaskedArray.__repr__ MaskedArray.__str__ MaskedArray.ids MaskedArray.iscontiguous Special methods --------------- For standard library functions: .. autosummary:: :toctree: generated/ MaskedArray.__copy__ MaskedArray.__deepcopy__ MaskedArray.__getstate__ MaskedArray.__reduce__ MaskedArray.__setstate__ Basic customization: .. autosummary:: :toctree: generated/ MaskedArray.__new__ MaskedArray.__array__ MaskedArray.__array_wrap__ Container customization: (see :ref:`Indexing `) .. autosummary:: :toctree: generated/ MaskedArray.__len__ MaskedArray.__getitem__ MaskedArray.__setitem__ MaskedArray.__delitem__ MaskedArray.__getslice__ MaskedArray.__setslice__ MaskedArray.__contains__ Specific methods ---------------- Handling the mask ~~~~~~~~~~~~~~~~~ The following methods can be used to access information about the mask or to manipulate the mask. .. autosummary:: :toctree: generated/ MaskedArray.__setmask__ MaskedArray.harden_mask MaskedArray.soften_mask MaskedArray.unshare_mask MaskedArray.shrink_mask Handling the `fill_value` ~~~~~~~~~~~~~~~~~~~~~~~~~ .. autosummary:: :toctree: generated/ MaskedArray.get_fill_value MaskedArray.set_fill_value Counting the missing elements ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .. autosummary:: :toctree: generated/ MaskedArray.count numpy-1.8.2/doc/source/reference/routines.linalg.rst0000664000175100017510000000360512370216243023702 0ustar vagrantvagrant00000000000000.. _routines.linalg: Linear algebra (:mod:`numpy.linalg`) ************************************ .. currentmodule:: numpy Matrix and vector products -------------------------- .. autosummary:: :toctree: generated/ dot vdot inner outer tensordot einsum linalg.matrix_power kron Decompositions -------------- .. autosummary:: :toctree: generated/ linalg.cholesky linalg.qr linalg.svd Matrix eigenvalues ------------------ .. autosummary:: :toctree: generated/ linalg.eig linalg.eigh linalg.eigvals linalg.eigvalsh Norms and other numbers ----------------------- .. autosummary:: :toctree: generated/ linalg.norm linalg.cond linalg.det linalg.slogdet trace Solving equations and inverting matrices ---------------------------------------- .. autosummary:: :toctree: generated/ linalg.solve linalg.tensorsolve linalg.lstsq linalg.inv linalg.pinv linalg.tensorinv Exceptions ---------- .. autosummary:: :toctree: generated/ linalg.LinAlgError Linear algebra on several matrices at once ------------------------------------------ Several of the linear algebra routines listed above are able to compute results for several matrices at once, if they are stacked into the same array. This is indicated in the documentation via input parameter specifications such as ``a : (..., M, M) array_like``. This means that if for instance given an input array ``a.shape == (N, M, M)``, it is interpreted as a "stack" of N matrices, each of size M-by-M. Similar specification applies to return values, for instance the determinant has ``det : (...)`` and will in this case return an array of shape ``det(a).shape == (N,)``. This generalizes to linear algebra operations on higher-dimensional arrays: the last 1 or 2 dimensions of a multidimensional array are interpreted as vectors or matrices, as appropriate for each operation. numpy-1.8.2/doc/source/reference/ufuncs.rst0000664000175100017510000005272412370216243022076 0ustar vagrantvagrant00000000000000.. sectionauthor:: adapted from "Guide to Numpy" by Travis E. Oliphant .. _ufuncs: ************************************ Universal functions (:class:`ufunc`) ************************************ .. note: XXX: section might need to be made more reference-guideish... .. currentmodule:: numpy .. index: ufunc, universal function, arithmetic, operation A universal function (or :term:`ufunc` for short) is a function that operates on :class:`ndarrays ` in an element-by-element fashion, supporting :ref:`array broadcasting `, :ref:`type casting `, and several other standard features. That is, a ufunc is a ":term:`vectorized`" wrapper for a function that takes a fixed number of scalar inputs and produces a fixed number of scalar outputs. In Numpy, universal functions are instances of the :class:`numpy.ufunc` class. Many of the built-in functions are implemented in compiled C code, but :class:`ufunc` instances can also be produced using the :func:`frompyfunc` factory function. .. _ufuncs.broadcasting: Broadcasting ============ .. index:: broadcasting Each universal function takes array inputs and produces array outputs by performing the core function element-wise on the inputs. Standard broadcasting rules are applied so that inputs not sharing exactly the same shapes can still be usefully operated on. Broadcasting can be understood by four rules: 1. All input arrays with :attr:`ndim ` smaller than the input array of largest :attr:`ndim `, have 1's prepended to their shapes. 2. The size in each dimension of the output shape is the maximum of all the input sizes in that dimension. 3. An input can be used in the calculation if its size in a particular dimension either matches the output size in that dimension, or has value exactly 1. 4. If an input has a dimension size of 1 in its shape, the first data entry in that dimension will be used for all calculations along that dimension. In other words, the stepping machinery of the :term:`ufunc` will simply not step along that dimension (the :term:`stride` will be 0 for that dimension). Broadcasting is used throughout NumPy to decide how to handle disparately shaped arrays; for example, all arithmetic operations (``+``, ``-``, ``*``, ...) between :class:`ndarrays ` broadcast the arrays before operation. .. _arrays.broadcasting.broadcastable: .. index:: broadcastable A set of arrays is called ":term:`broadcastable`" to the same shape if the above rules produce a valid result, *i.e.*, one of the following is true: 1. The arrays all have exactly the same shape. 2. The arrays all have the same number of dimensions and the length of each dimensions is either a common length or 1. 3. The arrays that have too few dimensions can have their shapes prepended with a dimension of length 1 to satisfy property 2. .. admonition:: Example If ``a.shape`` is (5,1), ``b.shape`` is (1,6), ``c.shape`` is (6,) and ``d.shape`` is () so that *d* is a scalar, then *a*, *b*, *c*, and *d* are all broadcastable to dimension (5,6); and - *a* acts like a (5,6) array where ``a[:,0]`` is broadcast to the other columns, - *b* acts like a (5,6) array where ``b[0,:]`` is broadcast to the other rows, - *c* acts like a (1,6) array and therefore like a (5,6) array where ``c[:]`` is broadcast to every row, and finally, - *d* acts like a (5,6) array where the single value is repeated. .. _ufuncs.output-type: Output type determination ========================= The output of the ufunc (and its methods) is not necessarily an :class:`ndarray`, if all input arguments are not :class:`ndarrays `. All output arrays will be passed to the :obj:`__array_prepare__` and :obj:`__array_wrap__` methods of the input (besides :class:`ndarrays `, and scalars) that defines it **and** has the highest :obj:`__array_priority__` of any other input to the universal function. The default :obj:`__array_priority__` of the ndarray is 0.0, and the default :obj:`__array_priority__` of a subtype is 1.0. Matrices have :obj:`__array_priority__` equal to 10.0. All ufuncs can also take output arguments. If necessary, output will be cast to the data-type(s) of the provided output array(s). If a class with an :obj:`__array__` method is used for the output, results will be written to the object returned by :obj:`__array__`. Then, if the class also has an :obj:`__array_prepare__` method, it is called so metadata may be determined based on the context of the ufunc (the context consisting of the ufunc itself, the arguments passed to the ufunc, and the ufunc domain.) The array object returned by :obj:`__array_prepare__` is passed to the ufunc for computation. Finally, if the class also has an :obj:`__array_wrap__` method, the returned :class:`ndarray` result will be passed to that method just before passing control back to the caller. Use of internal buffers ======================= .. index:: buffers Internally, buffers are used for misaligned data, swapped data, and data that has to be converted from one data type to another. The size of internal buffers is settable on a per-thread basis. There can be up to :math:`2 (n_{\mathrm{inputs}} + n_{\mathrm{outputs}})` buffers of the specified size created to handle the data from all the inputs and outputs of a ufunc. The default size of a buffer is 10,000 elements. Whenever buffer-based calculation would be needed, but all input arrays are smaller than the buffer size, those misbehaved or incorrectly-typed arrays will be copied before the calculation proceeds. Adjusting the size of the buffer may therefore alter the speed at which ufunc calculations of various sorts are completed. A simple interface for setting this variable is accessible using the function .. autosummary:: :toctree: generated/ setbufsize Error handling ============== .. index:: error handling Universal functions can trip special floating-point status registers in your hardware (such as divide-by-zero). If available on your platform, these registers will be regularly checked during calculation. Error handling is controlled on a per-thread basis, and can be configured using the functions .. autosummary:: :toctree: generated/ seterr seterrcall .. _ufuncs.casting: Casting Rules ============= .. index:: pair: ufunc; casting rules .. note:: In NumPy 1.6.0, a type promotion API was created to encapsulate the mechansim for determining output types. See the functions :func:`result_type`, :func:`promote_types`, and :func:`min_scalar_type` for more details. At the core of every ufunc is a one-dimensional strided loop that implements the actual function for a specific type combination. When a ufunc is created, it is given a static list of inner loops and a corresponding list of type signatures over which the ufunc operates. The ufunc machinery uses this list to determine which inner loop to use for a particular case. You can inspect the :attr:`.types ` attribute for a particular ufunc to see which type combinations have a defined inner loop and which output type they produce (:ref:`character codes ` are used in said output for brevity). Casting must be done on one or more of the inputs whenever the ufunc does not have a core loop implementation for the input types provided. If an implementation for the input types cannot be found, then the algorithm searches for an implementation with a type signature to which all of the inputs can be cast "safely." The first one it finds in its internal list of loops is selected and performed, after all necessary type casting. Recall that internal copies during ufuncs (even for casting) are limited to the size of an internal buffer (which is user settable). .. note:: Universal functions in NumPy are flexible enough to have mixed type signatures. Thus, for example, a universal function could be defined that works with floating-point and integer values. See :func:`ldexp` for an example. By the above description, the casting rules are essentially implemented by the question of when a data type can be cast "safely" to another data type. The answer to this question can be determined in Python with a function call: :func:`can_cast(fromtype, totype) `. The Figure below shows the results of this call for the 24 internally supported types on the author's 64-bit system. You can generate this table for your system with the code given in the Figure. .. admonition:: Figure Code segment showing the "can cast safely" table for a 32-bit system. >>> def print_table(ntypes): ... print 'X', ... for char in ntypes: print char, ... print ... for row in ntypes: ... print row, ... for col in ntypes: ... print int(np.can_cast(row, col)), ... print >>> print_table(np.typecodes['All']) X ? b h i l q p B H I L Q P e f d g F D G S U V O M m ? 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 b 0 1 1 1 1 1 1 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 0 0 h 0 0 1 1 1 1 1 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 0 0 i 0 0 0 1 1 1 1 0 0 0 0 0 0 0 0 1 1 0 1 1 1 1 1 1 0 0 l 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 1 1 0 1 1 1 1 1 1 0 0 q 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 1 1 0 1 1 1 1 1 1 0 0 p 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 1 1 0 1 1 1 1 1 1 0 0 B 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 H 0 0 0 1 1 1 1 0 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 0 0 I 0 0 0 0 1 1 1 0 0 1 1 1 1 0 0 1 1 0 1 1 1 1 1 1 0 0 L 0 0 0 0 0 0 0 0 0 0 1 1 1 0 0 1 1 0 1 1 1 1 1 1 0 0 Q 0 0 0 0 0 0 0 0 0 0 1 1 1 0 0 1 1 0 1 1 1 1 1 1 0 0 P 0 0 0 0 0 0 0 0 0 0 1 1 1 0 0 1 1 0 1 1 1 1 1 1 0 0 e 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 0 0 f 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 0 0 d 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 1 1 1 1 1 1 0 0 g 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 1 1 1 1 1 0 0 F 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 0 0 D 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 0 0 G 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 0 0 S 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 0 0 U 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 0 0 V 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 O 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 M 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 m 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 You should note that, while included in the table for completeness, the 'S', 'U', and 'V' types cannot be operated on by ufuncs. Also, note that on a 32-bit system the integer types may have different sizes, resulting in a slightly altered table. Mixed scalar-array operations use a different set of casting rules that ensure that a scalar cannot "upcast" an array unless the scalar is of a fundamentally different kind of data (*i.e.*, under a different hierarchy in the data-type hierarchy) than the array. This rule enables you to use scalar constants in your code (which, as Python types, are interpreted accordingly in ufuncs) without worrying about whether the precision of the scalar constant will cause upcasting on your large (small precision) array. :class:`ufunc` ============== Optional keyword arguments -------------------------- All ufuncs take optional keyword arguments. Most of these represent advanced usage and will not typically be used. .. index:: pair: ufunc; keyword arguments *out* .. versionadded:: 1.6 The first output can provided as either a positional or a keyword parameter. *where* .. versionadded:: 1.7 Accepts a boolean array which is broadcast together with the operands. Values of True indicate to calculate the ufunc at that position, values of False indicate to leave the value in the output alone. *casting* .. versionadded:: 1.6 Provides a policy for what kind of casting is permitted. For compatibility with previous versions of NumPy, this defaults to 'unsafe'. May be 'no', 'equiv', 'safe', 'same_kind', or 'unsafe'. See :func:`can_cast` for explanations of the parameter values. In a future version of numpy, this argument will default to 'same_kind'. As part of this transition, starting in version 1.7, ufuncs will produce a DeprecationWarning for calls which are allowed under the 'unsafe' rules, but not under the 'same_kind' rules. *order* .. versionadded:: 1.6 Specifies the calculation iteration order/memory layout of the output array. Defaults to 'K'. 'C' means the output should be C-contiguous, 'F' means F-contiguous, 'A' means F-contiguous if the inputs are F-contiguous and not also not C-contiguous, C-contiguous otherwise, and 'K' means to match the element ordering of the inputs as closely as possible. *dtype* .. versionadded:: 1.6 Overrides the dtype of the calculation and output arrays. Similar to *sig*. *subok* .. versionadded:: 1.6 Defaults to true. If set to false, the output will always be a strict array, not a subtype. *sig* Either a data-type, a tuple of data-types, or a special signature string indicating the input and output types of a ufunc. This argument allows you to provide a specific signature for the 1-d loop to use in the underlying calculation. If the loop specified does not exist for the ufunc, then a TypeError is raised. Normally, a suitable loop is found automatically by comparing the input types with what is available and searching for a loop with data-types to which all inputs can be cast safely. This keyword argument lets you bypass that search and choose a particular loop. A list of available signatures is provided by the **types** attribute of the ufunc object. *extobj* a list of length 1, 2, or 3 specifying the ufunc buffer-size, the error mode integer, and the error call-back function. Normally, these values are looked up in a thread-specific dictionary. Passing them here circumvents that look up and uses the low-level specification provided for the error mode. This may be useful, for example, as an optimization for calculations requiring many ufunc calls on small arrays in a loop. Attributes ---------- There are some informational attributes that universal functions possess. None of the attributes can be set. .. index:: pair: ufunc; attributes ============ ================================================================= **__doc__** A docstring for each ufunc. The first part of the docstring is dynamically generated from the number of outputs, the name, and the number of inputs. The second part of the docstring is provided at creation time and stored with the ufunc. **__name__** The name of the ufunc. ============ ================================================================= .. autosummary:: :toctree: generated/ ufunc.nin ufunc.nout ufunc.nargs ufunc.ntypes ufunc.types ufunc.identity Methods ------- All ufuncs have four methods. However, these methods only make sense on ufuncs that take two input arguments and return one output argument. Attempting to call these methods on other ufuncs will cause a :exc:`ValueError`. The reduce-like methods all take an *axis* keyword and a *dtype* keyword, and the arrays must all have dimension >= 1. The *axis* keyword specifies the axis of the array over which the reduction will take place and may be negative, but must be an integer. The *dtype* keyword allows you to manage a very common problem that arises when naively using :ref:`{op}.reduce `. Sometimes you may have an array of a certain data type and wish to add up all of its elements, but the result does not fit into the data type of the array. This commonly happens if you have an array of single-byte integers. The *dtype* keyword allows you to alter the data type over which the reduction takes place (and therefore the type of the output). Thus, you can ensure that the output is a data type with precision large enough to handle your output. The responsibility of altering the reduce type is mostly up to you. There is one exception: if no *dtype* is given for a reduction on the "add" or "multiply" operations, then if the input type is an integer (or Boolean) data-type and smaller than the size of the :class:`int_` data type, it will be internally upcast to the :class:`int_` (or :class:`uint`) data-type. Ufuncs also have a fifth method that allows in place operations to be performed using fancy indexing. No buffering is used on the dimensions where fancy indexing is used, so the fancy index can list an item more than once and the operation will be performed on the result of the previous operation for that item. .. index:: pair: ufunc; methods .. autosummary:: :toctree: generated/ ufunc.reduce ufunc.accumulate ufunc.reduceat ufunc.outer ufunc.at .. warning:: A reduce-like operation on an array with a data-type that has a range "too small" to handle the result will silently wrap. One should use `dtype` to increase the size of the data-type over which reduction takes place. Available ufuncs ================ There are currently more than 60 universal functions defined in :mod:`numpy` on one or more types, covering a wide variety of operations. Some of these ufuncs are called automatically on arrays when the relevant infix notation is used (*e.g.*, :func:`add(a, b) ` is called internally when ``a + b`` is written and *a* or *b* is an :class:`ndarray`). Nevertheless, you may still want to use the ufunc call in order to use the optional output argument(s) to place the output(s) in an object (or objects) of your choice. Recall that each ufunc operates element-by-element. Therefore, each ufunc will be described as if acting on a set of scalar inputs to return a set of scalar outputs. .. note:: The ufunc still returns its output(s) even if you use the optional output argument(s). Math operations --------------- .. autosummary:: add subtract multiply divide logaddexp logaddexp2 true_divide floor_divide negative power remainder mod fmod absolute rint sign conj exp exp2 log log2 log10 expm1 log1p sqrt square reciprocal ones_like .. tip:: The optional output arguments can be used to help you save memory for large calculations. If your arrays are large, complicated expressions can take longer than absolutely necessary due to the creation and (later) destruction of temporary calculation spaces. For example, the expression ``G = a * b + c`` is equivalent to ``t1 = A * B; G = T1 + C; del t1``. It will be more quickly executed as ``G = A * B; add(G, C, G)`` which is the same as ``G = A * B; G += C``. Trigonometric functions ----------------------- All trigonometric functions use radians when an angle is called for. The ratio of degrees to radians is :math:`180^{\circ}/\pi.` .. autosummary:: sin cos tan arcsin arccos arctan arctan2 hypot sinh cosh tanh arcsinh arccosh arctanh deg2rad rad2deg Bit-twiddling functions ----------------------- These function all require integer arguments and they manipulate the bit-pattern of those arguments. .. autosummary:: bitwise_and bitwise_or bitwise_xor invert left_shift right_shift Comparison functions -------------------- .. autosummary:: greater greater_equal less less_equal not_equal equal .. warning:: Do not use the Python keywords ``and`` and ``or`` to combine logical array expressions. These keywords will test the truth value of the entire array (not element-by-element as you might expect). Use the bitwise operators & and \| instead. .. autosummary:: logical_and logical_or logical_xor logical_not .. warning:: The bit-wise operators & and \| are the proper way to perform element-by-element array comparisons. Be sure you understand the operator precedence: ``(a > 2) & (a < 5)`` is the proper syntax because ``a > 2 & a < 5`` will result in an error due to the fact that ``2 & a`` is evaluated first. .. autosummary:: maximum .. tip:: The Python function ``max()`` will find the maximum over a one-dimensional array, but it will do so using a slower sequence interface. The reduce method of the maximum ufunc is much faster. Also, the ``max()`` method will not give answers you might expect for arrays with greater than one dimension. The reduce method of minimum also allows you to compute a total minimum over an array. .. autosummary:: minimum .. warning:: the behavior of ``maximum(a, b)`` is different than that of ``max(a, b)``. As a ufunc, ``maximum(a, b)`` performs an element-by-element comparison of `a` and `b` and chooses each element of the result according to which element in the two arrays is larger. In contrast, ``max(a, b)`` treats the objects `a` and `b` as a whole, looks at the (total) truth value of ``a > b`` and uses it to return either `a` or `b` (as a whole). A similar difference exists between ``minimum(a, b)`` and ``min(a, b)``. .. autosummary:: fmax fmin Floating functions ------------------ Recall that all of these functions work element-by-element over an array, returning an array output. The description details only a single operation. .. autosummary:: isreal iscomplex isfinite isinf isnan signbit copysign nextafter modf ldexp frexp fmod floor ceil trunc numpy-1.8.2/doc/source/reference/routines.polynomials.poly1d.rst0000664000175100017510000000073112370216242026205 0ustar vagrantvagrant00000000000000Poly1d ====== .. currentmodule:: numpy Basics ------ .. autosummary:: :toctree: generated/ poly1d polyval poly roots Fitting ------- .. autosummary:: :toctree: generated/ polyfit Calculus -------- .. autosummary:: :toctree: generated/ polyder polyint Arithmetic ---------- .. autosummary:: :toctree: generated/ polyadd polydiv polymul polysub Warnings -------- .. autosummary:: :toctree: generated/ RankWarning numpy-1.8.2/doc/source/reference/swig.interface-file.rst0000664000175100017510000011365612370216243024422 0ustar vagrantvagrant00000000000000Numpy.i: a SWIG Interface File for NumPy ======================================== Introduction ------------ The Simple Wrapper and Interface Generator (or `SWIG `_) is a powerful tool for generating wrapper code for interfacing to a wide variety of scripting languages. `SWIG`_ can parse header files, and using only the code prototypes, create an interface to the target language. But `SWIG`_ is not omnipotent. For example, it cannot know from the prototype:: double rms(double* seq, int n); what exactly ``seq`` is. Is it a single value to be altered in-place? Is it an array, and if so what is its length? Is it input-only? Output-only? Input-output? `SWIG`_ cannot determine these details, and does not attempt to do so. If we designed ``rms``, we probably made it a routine that takes an input-only array of length ``n`` of ``double`` values called ``seq`` and returns the root mean square. The default behavior of `SWIG`_, however, will be to create a wrapper function that compiles, but is nearly impossible to use from the scripting language in the way the C routine was intended. For Python, the preferred way of handling contiguous (or technically, *strided*) blocks of homogeneous data is with NumPy, which provides full object-oriented access to multidimensial arrays of data. Therefore, the most logical Python interface for the ``rms`` function would be (including doc string):: def rms(seq): """ rms: return the root mean square of a sequence rms(numpy.ndarray) -> double rms(list) -> double rms(tuple) -> double """ where ``seq`` would be a NumPy array of ``double`` values, and its length ``n`` would be extracted from ``seq`` internally before being passed to the C routine. Even better, since NumPy supports construction of arrays from arbitrary Python sequences, ``seq`` itself could be a nearly arbitrary sequence (so long as each element can be converted to a ``double``) and the wrapper code would internally convert it to a NumPy array before extracting its data and length. `SWIG`_ allows these types of conversions to be defined via a mechanism called *typemaps*. This document provides information on how to use ``numpy.i``, a `SWIG`_ interface file that defines a series of typemaps intended to make the type of array-related conversions described above relatively simple to implement. For example, suppose that the ``rms`` function prototype defined above was in a header file named ``rms.h``. To obtain the Python interface discussed above, your `SWIG`_ interface file would need the following:: %{ #define SWIG_FILE_WITH_INIT #include "rms.h" %} %include "numpy.i" %init %{ import_array(); %} %apply (double* IN_ARRAY1, int DIM1) {(double* seq, int n)}; %include "rms.h" Typemaps are keyed off a list of one or more function arguments, either by type or by type and name. We will refer to such lists as *signatures*. One of the many typemaps defined by ``numpy.i`` is used above and has the signature ``(double* IN_ARRAY1, int DIM1)``. The argument names are intended to suggest that the ``double*`` argument is an input array of one dimension and that the ``int`` represents the size of that dimension. This is precisely the pattern in the ``rms`` prototype. Most likely, no actual prototypes to be wrapped will have the argument names ``IN_ARRAY1`` and ``DIM1``. We use the `SWIG`_ ``%apply`` directive to apply the typemap for one-dimensional input arrays of type ``double`` to the actual prototype used by ``rms``. Using ``numpy.i`` effectively, therefore, requires knowing what typemaps are available and what they do. A `SWIG`_ interface file that includes the `SWIG`_ directives given above will produce wrapper code that looks something like:: 1 PyObject *_wrap_rms(PyObject *args) { 2 PyObject *resultobj = 0; 3 double *arg1 = (double *) 0 ; 4 int arg2 ; 5 double result; 6 PyArrayObject *array1 = NULL ; 7 int is_new_object1 = 0 ; 8 PyObject * obj0 = 0 ; 9 10 if (!PyArg_ParseTuple(args,(char *)"O:rms",&obj0)) SWIG_fail; 11 { 12 array1 = obj_to_array_contiguous_allow_conversion( 13 obj0, NPY_DOUBLE, &is_new_object1); 14 npy_intp size[1] = { 15 -1 16 }; 17 if (!array1 || !require_dimensions(array1, 1) || 18 !require_size(array1, size, 1)) SWIG_fail; 19 arg1 = (double*) array1->data; 20 arg2 = (int) array1->dimensions[0]; 21 } 22 result = (double)rms(arg1,arg2); 23 resultobj = SWIG_From_double((double)(result)); 24 { 25 if (is_new_object1 && array1) Py_DECREF(array1); 26 } 27 return resultobj; 28 fail: 29 { 30 if (is_new_object1 && array1) Py_DECREF(array1); 31 } 32 return NULL; 33 } The typemaps from ``numpy.i`` are responsible for the following lines of code: 12--20, 25 and 30. Line 10 parses the input to the ``rms`` function. From the format string ``"O:rms"``, we can see that the argument list is expected to be a single Python object (specified by the ``O`` before the colon) and whose pointer is stored in ``obj0``. A number of functions, supplied by ``numpy.i``, are called to make and check the (possible) conversion from a generic Python object to a NumPy array. These functions are explained in the section `Helper Functions`_, but hopefully their names are self-explanatory. At line 12 we use ``obj0`` to construct a NumPy array. At line 17, we check the validity of the result: that it is non-null and that it has a single dimension of arbitrary length. Once these states are verified, we extract the data buffer and length in lines 19 and 20 so that we can call the underlying C function at line 22. Line 25 performs memory management for the case where we have created a new array that is no longer needed. This code has a significant amount of error handling. Note the ``SWIG_fail`` is a macro for ``goto fail``, refering to the label at line 28. If the user provides the wrong number of arguments, this will be caught at line 10. If construction of the NumPy array fails or produces an array with the wrong number of dimensions, these errors are caught at line 17. And finally, if an error is detected, memory is still managed correctly at line 30. Note that if the C function signature was in a different order:: double rms(int n, double* seq); that `SWIG`_ would not match the typemap signature given above with the argument list for ``rms``. Fortunately, ``numpy.i`` has a set of typemaps with the data pointer given last:: %apply (int DIM1, double* IN_ARRAY1) {(int n, double* seq)}; This simply has the effect of switching the definitions of ``arg1`` and ``arg2`` in lines 3 and 4 of the generated code above, and their assignments in lines 19 and 20. Using numpy.i ------------- The ``numpy.i`` file is currently located in the ``numpy/docs/swig`` sub-directory under the ``numpy`` installation directory. Typically, you will want to copy it to the directory where you are developing your wrappers. A simple module that only uses a single `SWIG`_ interface file should include the following:: %{ #define SWIG_FILE_WITH_INIT %} %include "numpy.i" %init %{ import_array(); %} Within a compiled Python module, ``import_array()`` should only get called once. This could be in a C/C++ file that you have written and is linked to the module. If this is the case, then none of your interface files should ``#define SWIG_FILE_WITH_INIT`` or call ``import_array()``. Or, this initialization call could be in a wrapper file generated by `SWIG`_ from an interface file that has the ``%init`` block as above. If this is the case, and you have more than one `SWIG`_ interface file, then only one interface file should ``#define SWIG_FILE_WITH_INIT`` and call ``import_array()``. Available Typemaps ------------------ The typemap directives provided by ``numpy.i`` for arrays of different data types, say ``double`` and ``int``, and dimensions of different types, say ``int`` or ``long``, are identical to one another except for the C and NumPy type specifications. The typemaps are therefore implemented (typically behind the scenes) via a macro:: %numpy_typemaps(DATA_TYPE, DATA_TYPECODE, DIM_TYPE) that can be invoked for appropriate ``(DATA_TYPE, DATA_TYPECODE, DIM_TYPE)`` triplets. For example:: %numpy_typemaps(double, NPY_DOUBLE, int) %numpy_typemaps(int, NPY_INT , int) The ``numpy.i`` interface file uses the ``%numpy_typemaps`` macro to implement typemaps for the following C data types and ``int`` dimension types: * ``signed char`` * ``unsigned char`` * ``short`` * ``unsigned short`` * ``int`` * ``unsigned int`` * ``long`` * ``unsigned long`` * ``long long`` * ``unsigned long long`` * ``float`` * ``double`` In the following descriptions, we reference a generic ``DATA_TYPE``, which could be any of the C data types listed above, and ``DIM_TYPE`` which should be one of the many types of integers. The typemap signatures are largely differentiated on the name given to the buffer pointer. Names with ``FARRAY`` are for Fortran-ordered arrays, and names with ``ARRAY`` are for C-ordered (or 1D arrays). Input Arrays ```````````` Input arrays are defined as arrays of data that are passed into a routine but are not altered in-place or returned to the user. The Python input array is therefore allowed to be almost any Python sequence (such as a list) that can be converted to the requested type of array. The input array signatures are 1D: * ``( DATA_TYPE IN_ARRAY1[ANY] )`` * ``( DATA_TYPE* IN_ARRAY1, int DIM1 )`` * ``( int DIM1, DATA_TYPE* IN_ARRAY1 )`` 2D: * ``( DATA_TYPE IN_ARRAY2[ANY][ANY] )`` * ``( DATA_TYPE* IN_ARRAY2, int DIM1, int DIM2 )`` * ``( int DIM1, int DIM2, DATA_TYPE* IN_ARRAY2 )`` * ``( DATA_TYPE* IN_FARRAY2, int DIM1, int DIM2 )`` * ``( int DIM1, int DIM2, DATA_TYPE* IN_FARRAY2 )`` 3D: * ``( DATA_TYPE IN_ARRAY3[ANY][ANY][ANY] )`` * ``( DATA_TYPE* IN_ARRAY3, int DIM1, int DIM2, int DIM3 )`` * ``( int DIM1, int DIM2, int DIM3, DATA_TYPE* IN_ARRAY3 )`` * ``( DATA_TYPE* IN_FARRAY3, int DIM1, int DIM2, int DIM3 )`` * ``( int DIM1, int DIM2, int DIM3, DATA_TYPE* IN_FARRAY3 )`` 4D: * ``(DATA_TYPE IN_ARRAY4[ANY][ANY][ANY][ANY])`` * ``(DATA_TYPE* IN_ARRAY4, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DIM_TYPE DIM4)`` * ``(DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, , DIM_TYPE DIM4, DATA_TYPE* IN_ARRAY4)`` * ``(DATA_TYPE* IN_FARRAY4, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DIM_TYPE DIM4)`` * ``(DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DIM_TYPE DIM4, DATA_TYPE* IN_FARRAY4)`` The first signature listed, ``( DATA_TYPE IN_ARRAY[ANY] )`` is for one-dimensional arrays with hard-coded dimensions. Likewise, ``( DATA_TYPE IN_ARRAY2[ANY][ANY] )`` is for two-dimensional arrays with hard-coded dimensions, and similarly for three-dimensional. In-Place Arrays ``````````````` In-place arrays are defined as arrays that are modified in-place. The input values may or may not be used, but the values at the time the function returns are significant. The provided Python argument must therefore be a NumPy array of the required type. The in-place signatures are 1D: * ``( DATA_TYPE INPLACE_ARRAY1[ANY] )`` * ``( DATA_TYPE* INPLACE_ARRAY1, int DIM1 )`` * ``( int DIM1, DATA_TYPE* INPLACE_ARRAY1 )`` 2D: * ``( DATA_TYPE INPLACE_ARRAY2[ANY][ANY] )`` * ``( DATA_TYPE* INPLACE_ARRAY2, int DIM1, int DIM2 )`` * ``( int DIM1, int DIM2, DATA_TYPE* INPLACE_ARRAY2 )`` * ``( DATA_TYPE* INPLACE_FARRAY2, int DIM1, int DIM2 )`` * ``( int DIM1, int DIM2, DATA_TYPE* INPLACE_FARRAY2 )`` 3D: * ``( DATA_TYPE INPLACE_ARRAY3[ANY][ANY][ANY] )`` * ``( DATA_TYPE* INPLACE_ARRAY3, int DIM1, int DIM2, int DIM3 )`` * ``( int DIM1, int DIM2, int DIM3, DATA_TYPE* INPLACE_ARRAY3 )`` * ``( DATA_TYPE* INPLACE_FARRAY3, int DIM1, int DIM2, int DIM3 )`` * ``( int DIM1, int DIM2, int DIM3, DATA_TYPE* INPLACE_FARRAY3 )`` 4D: * ``(DATA_TYPE INPLACE_ARRAY4[ANY][ANY][ANY][ANY])`` * ``(DATA_TYPE* INPLACE_ARRAY4, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DIM_TYPE DIM4)`` * ``(DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, , DIM_TYPE DIM4, DATA_TYPE* INPLACE_ARRAY4)`` * ``(DATA_TYPE* INPLACE_FARRAY4, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DIM_TYPE DIM4)`` * ``(DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DIM_TYPE DIM4, DATA_TYPE* INPLACE_FARRAY4)`` These typemaps now check to make sure that the ``INPLACE_ARRAY`` arguments use native byte ordering. If not, an exception is raised. Argout Arrays ````````````` Argout arrays are arrays that appear in the input arguments in C, but are in fact output arrays. This pattern occurs often when there is more than one output variable and the single return argument is therefore not sufficient. In Python, the convential way to return multiple arguments is to pack them into a sequence (tuple, list, etc.) and return the sequence. This is what the argout typemaps do. If a wrapped function that uses these argout typemaps has more than one return argument, they are packed into a tuple or list, depending on the version of Python. The Python user does not pass these arrays in, they simply get returned. For the case where a dimension is specified, the python user must provide that dimension as an argument. The argout signatures are 1D: * ``( DATA_TYPE ARGOUT_ARRAY1[ANY] )`` * ``( DATA_TYPE* ARGOUT_ARRAY1, int DIM1 )`` * ``( int DIM1, DATA_TYPE* ARGOUT_ARRAY1 )`` 2D: * ``( DATA_TYPE ARGOUT_ARRAY2[ANY][ANY] )`` 3D: * ``( DATA_TYPE ARGOUT_ARRAY3[ANY][ANY][ANY] )`` 4D: * ``( DATA_TYPE ARGOUT_ARRAY4[ANY][ANY][ANY][ANY] )`` These are typically used in situations where in C/C++, you would allocate a(n) array(s) on the heap, and call the function to fill the array(s) values. In Python, the arrays are allocated for you and returned as new array objects. Note that we support ``DATA_TYPE*`` argout typemaps in 1D, but not 2D or 3D. This is because of a quirk with the `SWIG`_ typemap syntax and cannot be avoided. Note that for these types of 1D typemaps, the Python function will take a single argument representing ``DIM1``. Argout View Arrays `````````````````` Argoutview arrays are for when your C code provides you with a view of its internal data and does not require any memory to be allocated by the user. This can be dangerous. There is almost no way to guarantee that the internal data from the C code will remain in existence for the entire lifetime of the NumPy array that encapsulates it. If the user destroys the object that provides the view of the data before destroying the NumPy array, then using that array may result in bad memory references or segmentation faults. Nevertheless, there are situations, working with large data sets, where you simply have no other choice. The C code to be wrapped for argoutview arrays are characterized by pointers: pointers to the dimensions and double pointers to the data, so that these values can be passed back to the user. The argoutview typemap signatures are therefore 1D: * ``( DATA_TYPE** ARGOUTVIEW_ARRAY1, DIM_TYPE* DIM1 )`` * ``( DIM_TYPE* DIM1, DATA_TYPE** ARGOUTVIEW_ARRAY1 )`` 2D: * ``( DATA_TYPE** ARGOUTVIEW_ARRAY2, DIM_TYPE* DIM1, DIM_TYPE* DIM2 )`` * ``( DIM_TYPE* DIM1, DIM_TYPE* DIM2, DATA_TYPE** ARGOUTVIEW_ARRAY2 )`` * ``( DATA_TYPE** ARGOUTVIEW_FARRAY2, DIM_TYPE* DIM1, DIM_TYPE* DIM2 )`` * ``( DIM_TYPE* DIM1, DIM_TYPE* DIM2, DATA_TYPE** ARGOUTVIEW_FARRAY2 )`` 3D: * ``( DATA_TYPE** ARGOUTVIEW_ARRAY3, DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3)`` * ``( DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DATA_TYPE** ARGOUTVIEW_ARRAY3)`` * ``( DATA_TYPE** ARGOUTVIEW_FARRAY3, DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3)`` * ``( DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DATA_TYPE** ARGOUTVIEW_FARRAY3)`` 4D: * ``(DATA_TYPE** ARGOUTVIEW_ARRAY4, DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DIM_TYPE* DIM4)`` * ``(DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DIM_TYPE* DIM4, DATA_TYPE** ARGOUTVIEW_ARRAY4)`` * ``(DATA_TYPE** ARGOUTVIEW_FARRAY4, DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DIM_TYPE* DIM4)`` * ``(DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DIM_TYPE* DIM4, DATA_TYPE** ARGOUTVIEW_FARRAY4)`` Note that arrays with hard-coded dimensions are not supported. These cannot follow the double pointer signatures of these typemaps. Memory Managed Argout View Arrays ````````````````````````````````` A recent addition to ``numpy.i`` are typemaps that permit argout arrays with views into memory that is managed. See the discussion `here `_. 1D: * ``(DATA_TYPE** ARGOUTVIEWM_ARRAY1, DIM_TYPE* DIM1)`` * ``(DIM_TYPE* DIM1, DATA_TYPE** ARGOUTVIEWM_ARRAY1)`` 2D: * ``(DATA_TYPE** ARGOUTVIEWM_ARRAY2, DIM_TYPE* DIM1, DIM_TYPE* DIM2)`` * ``(DIM_TYPE* DIM1, DIM_TYPE* DIM2, DATA_TYPE** ARGOUTVIEWM_ARRAY2)`` * ``(DATA_TYPE** ARGOUTVIEWM_FARRAY2, DIM_TYPE* DIM1, DIM_TYPE* DIM2)`` * ``(DIM_TYPE* DIM1, DIM_TYPE* DIM2, DATA_TYPE** ARGOUTVIEWM_FARRAY2)`` 3D: * ``(DATA_TYPE** ARGOUTVIEWM_ARRAY3, DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3)`` * ``(DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DATA_TYPE** ARGOUTVIEWM_ARRAY3)`` * ``(DATA_TYPE** ARGOUTVIEWM_FARRAY3, DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3)`` * ``(DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DATA_TYPE** ARGOUTVIEWM_FARRAY3)`` 4D: * ``(DATA_TYPE** ARGOUTVIEWM_ARRAY4, DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DIM_TYPE* DIM4)`` * ``(DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DIM_TYPE* DIM4, DATA_TYPE** ARGOUTVIEWM_ARRAY4)`` * ``(DATA_TYPE** ARGOUTVIEWM_FARRAY4, DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DIM_TYPE* DIM4)`` * ``(DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DIM_TYPE* DIM4, DATA_TYPE** ARGOUTVIEWM_FARRAY4)`` Output Arrays ````````````` The ``numpy.i`` interface file does not support typemaps for output arrays, for several reasons. First, C/C++ return arguments are limited to a single value. This prevents obtaining dimension information in a general way. Second, arrays with hard-coded lengths are not permitted as return arguments. In other words:: double[3] newVector(double x, double y, double z); is not legal C/C++ syntax. Therefore, we cannot provide typemaps of the form:: %typemap(out) (TYPE[ANY]); If you run into a situation where a function or method is returning a pointer to an array, your best bet is to write your own version of the function to be wrapped, either with ``%extend`` for the case of class methods or ``%ignore`` and ``%rename`` for the case of functions. Other Common Types: bool ```````````````````````` Note that C++ type ``bool`` is not supported in the list in the `Available Typemaps`_ section. NumPy bools are a single byte, while the C++ ``bool`` is four bytes (at least on my system). Therefore:: %numpy_typemaps(bool, NPY_BOOL, int) will result in typemaps that will produce code that reference improper data lengths. You can implement the following macro expansion:: %numpy_typemaps(bool, NPY_UINT, int) to fix the data length problem, and `Input Arrays`_ will work fine, but `In-Place Arrays`_ might fail type-checking. Other Common Types: complex ``````````````````````````` Typemap conversions for complex floating-point types is also not supported automatically. This is because Python and NumPy are written in C, which does not have native complex types. Both Python and NumPy implement their own (essentially equivalent) ``struct`` definitions for complex variables:: /* Python */ typedef struct {double real; double imag;} Py_complex; /* NumPy */ typedef struct {float real, imag;} npy_cfloat; typedef struct {double real, imag;} npy_cdouble; We could have implemented:: %numpy_typemaps(Py_complex , NPY_CDOUBLE, int) %numpy_typemaps(npy_cfloat , NPY_CFLOAT , int) %numpy_typemaps(npy_cdouble, NPY_CDOUBLE, int) which would have provided automatic type conversions for arrays of type ``Py_complex``, ``npy_cfloat`` and ``npy_cdouble``. However, it seemed unlikely that there would be any independent (non-Python, non-NumPy) application code that people would be using `SWIG`_ to generate a Python interface to, that also used these definitions for complex types. More likely, these application codes will define their own complex types, or in the case of C++, use ``std::complex``. Assuming these data structures are compatible with Python and NumPy complex types, ``%numpy_typemap`` expansions as above (with the user's complex type substituted for the first argument) should work. NumPy Array Scalars and SWIG ---------------------------- `SWIG`_ has sophisticated type checking for numerical types. For example, if your C/C++ routine expects an integer as input, the code generated by `SWIG`_ will check for both Python integers and Python long integers, and raise an overflow error if the provided Python integer is too big to cast down to a C integer. With the introduction of NumPy scalar arrays into your Python code, you might conceivably extract an integer from a NumPy array and attempt to pass this to a `SWIG`_-wrapped C/C++ function that expects an ``int``, but the `SWIG`_ type checking will not recognize the NumPy array scalar as an integer. (Often, this does in fact work -- it depends on whether NumPy recognizes the integer type you are using as inheriting from the Python integer type on the platform you are using. Sometimes, this means that code that works on a 32-bit machine will fail on a 64-bit machine.) If you get a Python error that looks like the following:: TypeError: in method 'MyClass_MyMethod', argument 2 of type 'int' and the argument you are passing is an integer extracted from a NumPy array, then you have stumbled upon this problem. The solution is to modify the `SWIG`_ type conversion system to accept Numpy array scalars in addition to the standard integer types. Fortunately, this capabilitiy has been provided for you. Simply copy the file:: pyfragments.swg to the working build directory for you project, and this problem will be fixed. It is suggested that you do this anyway, as it only increases the capabilities of your Python interface. Why is There a Second File? ``````````````````````````` The `SWIG`_ type checking and conversion system is a complicated combination of C macros, `SWIG`_ macros, `SWIG`_ typemaps and `SWIG`_ fragments. Fragments are a way to conditionally insert code into your wrapper file if it is needed, and not insert it if not needed. If multiple typemaps require the same fragment, the fragment only gets inserted into your wrapper code once. There is a fragment for converting a Python integer to a C ``long``. There is a different fragment that converts a Python integer to a C ``int``, that calls the rountine defined in the ``long`` fragment. We can make the changes we want here by changing the definition for the ``long`` fragment. `SWIG`_ determines the active definition for a fragment using a "first come, first served" system. That is, we need to define the fragment for ``long`` conversions prior to `SWIG`_ doing it internally. `SWIG`_ allows us to do this by putting our fragment definitions in the file ``pyfragments.swg``. If we were to put the new fragment definitions in ``numpy.i``, they would be ignored. Helper Functions ---------------- The ``numpy.i`` file containes several macros and routines that it uses internally to build its typemaps. However, these functions may be useful elsewhere in your interface file. These macros and routines are implemented as fragments, which are described briefly in the previous section. If you try to use one or more of the following macros or functions, but your compiler complains that it does not recognize the symbol, then you need to force these fragments to appear in your code using:: %fragment("NumPy_Fragments"); in your `SWIG`_ interface file. Macros `````` **is_array(a)** Evaluates as true if ``a`` is non-``NULL`` and can be cast to a ``PyArrayObject*``. **array_type(a)** Evaluates to the integer data type code of ``a``, assuming ``a`` can be cast to a ``PyArrayObject*``. **array_numdims(a)** Evaluates to the integer number of dimensions of ``a``, assuming ``a`` can be cast to a ``PyArrayObject*``. **array_dimensions(a)** Evaluates to an array of type ``npy_intp`` and length ``array_numdims(a)``, giving the lengths of all of the dimensions of ``a``, assuming ``a`` can be cast to a ``PyArrayObject*``. **array_size(a,i)** Evaluates to the ``i``-th dimension size of ``a``, assuming ``a`` can be cast to a ``PyArrayObject*``. **array_strides(a)** Evaluates to an array of type ``npy_intp`` and length ``array_numdims(a)``, giving the stridess of all of the dimensions of ``a``, assuming ``a`` can be cast to a ``PyArrayObject*``. A stride is the distance in bytes between an element and its immediate neighbor along the same axis. **array_stride(a,i)** Evaluates to the ``i``-th stride of ``a``, assuming ``a`` can be cast to a ``PyArrayObject*``. **array_data(a)** Evaluates to a pointer of type ``void*`` that points to the data buffer of ``a``, assuming ``a`` can be cast to a ``PyArrayObject*``. **array_descr(a)** Returns a borrowed reference to the dtype property (``PyArray_Descr*``) of ``a``, assuming ``a`` can be cast to a ``PyArrayObject*``. **array_flags(a)** Returns an integer representing the flags of ``a``, assuming ``a`` can be cast to a ``PyArrayObject*``. **array_enableflags(a,f)** Sets the flag represented by ``f`` of ``a``, assuming ``a`` can be cast to a ``PyArrayObject*``. **array_is_contiguous(a)** Evaluates as true if ``a`` is a contiguous array. Equivalent to ``(PyArray_ISCONTIGUOUS(a))``. **array_is_native(a)** Evaluates as true if the data buffer of ``a`` uses native byte order. Equivalent to ``(PyArray_ISNOTSWAPPED(a))``. **array_is_fortran(a)** Evaluates as true if ``a`` is FORTRAN ordered. Routines ```````` **pytype_string()** Return type: ``const char*`` Arguments: * ``PyObject* py_obj``, a general Python object. Return a string describing the type of ``py_obj``. **typecode_string()** Return type: ``const char*`` Arguments: * ``int typecode``, a NumPy integer typecode. Return a string describing the type corresponding to the NumPy ``typecode``. **type_match()** Return type: ``int`` Arguments: * ``int actual_type``, the NumPy typecode of a NumPy array. * ``int desired_type``, the desired NumPy typecode. Make sure that ``actual_type`` is compatible with ``desired_type``. For example, this allows character and byte types, or int and long types, to match. This is now equivalent to ``PyArray_EquivTypenums()``. **obj_to_array_no_conversion()** Return type: ``PyArrayObject*`` Arguments: * ``PyObject* input``, a general Python object. * ``int typecode``, the desired NumPy typecode. Cast ``input`` to a ``PyArrayObject*`` if legal, and ensure that it is of type ``typecode``. If ``input`` cannot be cast, or the ``typecode`` is wrong, set a Python error and return ``NULL``. **obj_to_array_allow_conversion()** Return type: ``PyArrayObject*`` Arguments: * ``PyObject* input``, a general Python object. * ``int typecode``, the desired NumPy typecode of the resulting array. * ``int* is_new_object``, returns a value of 0 if no conversion performed, else 1. Convert ``input`` to a NumPy array with the given ``typecode``. On success, return a valid ``PyArrayObject*`` with the correct type. On failure, the Python error string will be set and the routine returns ``NULL``. **make_contiguous()** Return type: ``PyArrayObject*`` Arguments: * ``PyArrayObject* ary``, a NumPy array. * ``int* is_new_object``, returns a value of 0 if no conversion performed, else 1. * ``int min_dims``, minimum allowable dimensions. * ``int max_dims``, maximum allowable dimensions. Check to see if ``ary`` is contiguous. If so, return the input pointer and flag it as not a new object. If it is not contiguous, create a new ``PyArrayObject*`` using the original data, flag it as a new object and return the pointer. **make_fortran()** Return type: ``PyArrayObject*`` Arguments * ``PyArrayObject* ary``, a NumPy array. * ``int* is_new_object``, returns a value of 0 if no conversion performed, else 1. Check to see if ``ary`` is Fortran contiguous. If so, return the input pointer and flag it as not a new object. If it is not Fortran contiguous, create a new ``PyArrayObject*`` using the original data, flag it as a new object and return the pointer. **obj_to_array_contiguous_allow_conversion()** Return type: ``PyArrayObject*`` Arguments: * ``PyObject* input``, a general Python object. * ``int typecode``, the desired NumPy typecode of the resulting array. * ``int* is_new_object``, returns a value of 0 if no conversion performed, else 1. Convert ``input`` to a contiguous ``PyArrayObject*`` of the specified type. If the input object is not a contiguous ``PyArrayObject*``, a new one will be created and the new object flag will be set. **obj_to_array_fortran_allow_conversion()** Return type: ``PyArrayObject*`` Arguments: * ``PyObject* input``, a general Python object. * ``int typecode``, the desired NumPy typecode of the resulting array. * ``int* is_new_object``, returns a value of 0 if no conversion performed, else 1. Convert ``input`` to a Fortran contiguous ``PyArrayObject*`` of the specified type. If the input object is not a Fortran contiguous ``PyArrayObject*``, a new one will be created and the new object flag will be set. **require_contiguous()** Return type: ``int`` Arguments: * ``PyArrayObject* ary``, a NumPy array. Test whether ``ary`` is contiguous. If so, return 1. Otherwise, set a Python error and return 0. **require_native()** Return type: ``int`` Arguments: * ``PyArray_Object* ary``, a NumPy array. Require that ``ary`` is not byte-swapped. If the array is not byte-swapped, return 1. Otherwise, set a Python error and return 0. **require_dimensions()** Return type: ``int`` Arguments: * ``PyArrayObject* ary``, a NumPy array. * ``int exact_dimensions``, the desired number of dimensions. Require ``ary`` to have a specified number of dimensions. If the array has the specified number of dimensions, return 1. Otherwise, set a Python error and return 0. **require_dimensions_n()** Return type: ``int`` Arguments: * ``PyArrayObject* ary``, a NumPy array. * ``int* exact_dimensions``, an array of integers representing acceptable numbers of dimensions. * ``int n``, the length of ``exact_dimensions``. Require ``ary`` to have one of a list of specified number of dimensions. If the array has one of the specified number of dimensions, return 1. Otherwise, set the Python error string and return 0. **require_size()** Return type: ``int`` Arguments: * ``PyArrayObject* ary``, a NumPy array. * ``npy_int* size``, an array representing the desired lengths of each dimension. * ``int n``, the length of ``size``. Require ``ary`` to have a specified shape. If the array has the specified shape, return 1. Otherwise, set the Python error string and return 0. **require_fortran()** Return type: ``int`` Arguments: * ``PyArrayObject* ary``, a NumPy array. Require the given ``PyArrayObject`` to to be Fortran ordered. If the the ``PyArrayObject`` is already Fortran ordered, do nothing. Else, set the Fortran ordering flag and recompute the strides. Beyond the Provided Typemaps ---------------------------- There are many C or C++ array/NumPy array situations not covered by a simple ``%include "numpy.i"`` and subsequent ``%apply`` directives. A Common Example ```````````````` Consider a reasonable prototype for a dot product function:: double dot(int len, double* vec1, double* vec2); The Python interface that we want is:: def dot(vec1, vec2): """ dot(PyObject,PyObject) -> double """ The problem here is that there is one dimension argument and two array arguments, and our typemaps are set up for dimensions that apply to a single array (in fact, `SWIG`_ does not provide a mechanism for associating ``len`` with ``vec2`` that takes two Python input arguments). The recommended solution is the following:: %apply (int DIM1, double* IN_ARRAY1) {(int len1, double* vec1), (int len2, double* vec2)} %rename (dot) my_dot; %exception my_dot { $action if (PyErr_Occurred()) SWIG_fail; } %inline %{ double my_dot(int len1, double* vec1, int len2, double* vec2) { if (len1 != len2) { PyErr_Format(PyExc_ValueError, "Arrays of lengths (%d,%d) given", len1, len2); return 0.0; } return dot(len1, vec1, vec2); } %} If the header file that contains the prototype for ``double dot()`` also contains other prototypes that you want to wrap, so that you need to ``%include`` this header file, then you will also need a ``%ignore dot;`` directive, placed after the ``%rename`` and before the ``%include`` directives. Or, if the function in question is a class method, you will want to use ``%extend`` rather than ``%inline`` in addition to ``%ignore``. **A note on error handling:** Note that ``my_dot`` returns a ``double`` but that it can also raise a Python error. The resulting wrapper function will return a Python float representation of 0.0 when the vector lengths do not match. Since this is not ``NULL``, the Python interpreter will not know to check for an error. For this reason, we add the ``%exception`` directive above for ``my_dot`` to get the behavior we want (note that ``$action`` is a macro that gets expanded to a valid call to ``my_dot``). In general, you will probably want to write a `SWIG`_ macro to perform this task. Other Situations ```````````````` There are other wrapping situations in which ``numpy.i`` may be helpful when you encounter them. * In some situations, it is possible that you could use the ``%numpy_typemaps`` macro to implement typemaps for your own types. See the `Other Common Types: bool`_ or `Other Common Types: complex`_ sections for examples. Another situation is if your dimensions are of a type other than ``int`` (say ``long`` for example):: %numpy_typemaps(double, NPY_DOUBLE, long) * You can use the code in ``numpy.i`` to write your own typemaps. For example, if you had a five-dimensional array as a function argument, you could cut-and-paste the appropriate four-dimensional typemaps into your interface file. The modifications for the fourth dimension would be trivial. * Sometimes, the best approach is to use the ``%extend`` directive to define new methods for your classes (or overload existing ones) that take a ``PyObject*`` (that either is or can be converted to a ``PyArrayObject*``) instead of a pointer to a buffer. In this case, the helper routines in ``numpy.i`` can be very useful. * Writing typemaps can be a bit nonintuitive. If you have specific questions about writing `SWIG`_ typemaps for NumPy, the developers of ``numpy.i`` do monitor the `Numpy-discussion `_ and `Swig-user `_ mail lists. A Final Note ```````````` When you use the ``%apply`` directive, as is usually necessary to use ``numpy.i``, it will remain in effect until you tell `SWIG`_ that it shouldn't be. If the arguments to the functions or methods that you are wrapping have common names, such as ``length`` or ``vector``, these typemaps may get applied in situations you do not expect or want. Therefore, it is always a good idea to add a ``%clear`` directive after you are done with a specific typemap:: %apply (double* IN_ARRAY1, int DIM1) {(double* vector, int length)} %include "my_header.h" %clear (double* vector, int length); In general, you should target these typemap signatures specifically where you want them, and then clear them after you are done. Summary ------- Out of the box, ``numpy.i`` provides typemaps that support conversion between NumPy arrays and C arrays: * That can be one of 12 different scalar types: ``signed char``, ``unsigned char``, ``short``, ``unsigned short``, ``int``, ``unsigned int``, ``long``, ``unsigned long``, ``long long``, ``unsigned long long``, ``float`` and ``double``. * That support 74 different argument signatures for each data type, including: + One-dimensional, two-dimensional, three-dimensional and four-dimensional arrays. + Input-only, in-place, argout, argoutview, and memory managed argoutview behavior. + Hard-coded dimensions, data-buffer-then-dimensions specification, and dimensions-then-data-buffer specification. + Both C-ordering ("last dimension fastest") or Fortran-ordering ("first dimension fastest") support for 2D, 3D and 4D arrays. The ``numpy.i`` interface file also provides additional tools for wrapper developers, including: * A `SWIG`_ macro (``%numpy_typemaps``) with three arguments for implementing the 74 argument signatures for the user's choice of (1) C data type, (2) NumPy data type (assuming they match), and (3) dimension type. * Fourteen C macros and fifteen C functions that can be used to write specialized typemaps, extensions, or inlined functions that handle cases not covered by the provided typemaps. Note that the macros and functions are coded specifically to work with the NumPy C/API regardless of NumPy version number, both before and after the deprecation of some aspects of the API after version 1.6. numpy-1.8.2/doc/source/reference/routines.indexing.rst0000664000175100017510000000156412370216242024242 0ustar vagrantvagrant00000000000000.. _routines.indexing: Indexing routines ================= .. seealso:: :ref:`Indexing ` .. currentmodule:: numpy Generating index arrays ----------------------- .. autosummary:: :toctree: generated/ c_ r_ s_ nonzero where indices ix_ ogrid ravel_multi_index unravel_index diag_indices diag_indices_from mask_indices tril_indices tril_indices_from triu_indices triu_indices_from Indexing-like operations ------------------------ .. autosummary:: :toctree: generated/ take choose compress diag diagonal select Inserting data into arrays -------------------------- .. autosummary:: :toctree: generated/ place put putmask fill_diagonal Iterating over arrays --------------------- .. autosummary:: :toctree: generated/ nditer ndenumerate ndindex flatiter numpy-1.8.2/doc/source/reference/distutils.rst0000664000175100017510000002331212370216242022605 0ustar vagrantvagrant00000000000000********************************** Packaging (:mod:`numpy.distutils`) ********************************** .. module:: numpy.distutils NumPy provides enhanced distutils functionality to make it easier to build and install sub-packages, auto-generate code, and extension modules that use Fortran-compiled libraries. To use features of NumPy distutils, use the :func:`setup ` command from :mod:`numpy.distutils.core`. A useful :class:`Configuration ` class is also provided in :mod:`numpy.distutils.misc_util` that can make it easier to construct keyword arguments to pass to the setup function (by passing the dictionary obtained from the todict() method of the class). More information is available in the NumPy Distutils Users Guide in ``/numpy/doc/DISTUTILS.txt``. .. index:: single: distutils Modules in :mod:`numpy.distutils` ================================= misc_util --------- .. module:: numpy.distutils.misc_util .. autosummary:: :toctree: generated/ get_numpy_include_dirs dict_append appendpath allpath dot_join generate_config_py get_cmd terminal_has_colors red_text green_text yellow_text blue_text cyan_text cyg2win32 all_strings has_f_sources has_cxx_sources filter_sources get_dependencies is_local_src_dir get_ext_source_files get_script_files .. class:: Configuration(package_name=None, parent_name=None, top_path=None, package_path=None, **attrs) Construct a configuration instance for the given package name. If *parent_name* is not None, then construct the package as a sub-package of the *parent_name* package. If *top_path* and *package_path* are None then they are assumed equal to the path of the file this instance was created in. The setup.py files in the numpy distribution are good examples of how to use the :class:`Configuration` instance. .. automethod:: todict .. automethod:: get_distribution .. automethod:: get_subpackage .. automethod:: add_subpackage .. automethod:: add_data_files .. automethod:: add_data_dir .. automethod:: add_include_dirs .. automethod:: add_headers .. automethod:: add_extension .. automethod:: add_library .. automethod:: add_scripts .. automethod:: add_installed_library .. automethod:: add_npy_pkg_config .. automethod:: paths .. automethod:: get_config_cmd .. automethod:: get_build_temp_dir .. automethod:: have_f77c .. automethod:: have_f90c .. automethod:: get_version .. automethod:: make_svn_version_py .. automethod:: make_config_py .. automethod:: get_info Other modules ------------- .. currentmodule:: numpy.distutils .. autosummary:: :toctree: generated/ system_info.get_info system_info.get_standard_file cpuinfo.cpu log.set_verbosity exec_command Building Installable C libraries ================================ Conventional C libraries (installed through `add_library`) are not installed, and are just used during the build (they are statically linked). An installable C library is a pure C library, which does not depend on the python C runtime, and is installed such that it may be used by third-party packages. To build and install the C library, you just use the method `add_installed_library` instead of `add_library`, which takes the same arguments except for an additional ``install_dir`` argument:: >>> config.add_installed_library('foo', sources=['foo.c'], install_dir='lib') npy-pkg-config files -------------------- To make the necessary build options available to third parties, you could use the `npy-pkg-config` mechanism implemented in `numpy.distutils`. This mechanism is based on a .ini file which contains all the options. A .ini file is very similar to .pc files as used by the pkg-config unix utility:: [meta] Name: foo Version: 1.0 Description: foo library [variables] prefix = /home/user/local libdir = ${prefix}/lib includedir = ${prefix}/include [default] cflags = -I${includedir} libs = -L${libdir} -lfoo Generally, the file needs to be generated during the build, since it needs some information known at build time only (e.g. prefix). This is mostly automatic if one uses the `Configuration` method `add_npy_pkg_config`. Assuming we have a template file foo.ini.in as follows:: [meta] Name: foo Version: @version@ Description: foo library [variables] prefix = @prefix@ libdir = ${prefix}/lib includedir = ${prefix}/include [default] cflags = -I${includedir} libs = -L${libdir} -lfoo and the following code in setup.py:: >>> config.add_installed_library('foo', sources=['foo.c'], install_dir='lib') >>> subst = {'version': '1.0'} >>> config.add_npy_pkg_config('foo.ini.in', 'lib', subst_dict=subst) This will install the file foo.ini into the directory package_dir/lib, and the foo.ini file will be generated from foo.ini.in, where each ``@version@`` will be replaced by ``subst_dict['version']``. The dictionary has an additional prefix substitution rule automatically added, which contains the install prefix (since this is not easy to get from setup.py). npy-pkg-config files can also be installed at the same location as used for numpy, using the path returned from `get_npy_pkg_dir` function. Reusing a C library from another package ---------------------------------------- Info are easily retrieved from the `get_info` function in `numpy.distutils.misc_util`:: >>> info = get_info('npymath') >>> config.add_extension('foo', sources=['foo.c'], extra_info=**info) An additional list of paths to look for .ini files can be given to `get_info`. Conversion of ``.src`` files ============================ NumPy distutils supports automatic conversion of source files named .src. This facility can be used to maintain very similar code blocks requiring only simple changes between blocks. During the build phase of setup, if a template file named .src is encountered, a new file named is constructed from the template and placed in the build directory to be used instead. Two forms of template conversion are supported. The first form occurs for files named named .ext.src where ext is a recognized Fortran extension (f, f90, f95, f77, for, ftn, pyf). The second form is used for all other cases. .. index:: single: code generation Fortran files ------------- This template converter will replicate all **function** and **subroutine** blocks in the file with names that contain '<...>' according to the rules in '<...>'. The number of comma-separated words in '<...>' determines the number of times the block is repeated. What these words are indicates what that repeat rule, '<...>', should be replaced with in each block. All of the repeat rules in a block must contain the same number of comma-separated words indicating the number of times that block should be repeated. If the word in the repeat rule needs a comma, leftarrow, or rightarrow, then prepend it with a backslash ' \'. If a word in the repeat rule matches ' \\' then it will be replaced with the -th word in the same repeat specification. There are two forms for the repeat rule: named and short. Named repeat rule ^^^^^^^^^^^^^^^^^ A named repeat rule is useful when the same set of repeats must be used several times in a block. It is specified using , where N is the number of times the block should be repeated. On each repeat of the block, the entire expression, '<...>' will be replaced first with item1, and then with item2, and so forth until N repeats are accomplished. Once a named repeat specification has been introduced, the same repeat rule may be used **in the current block** by referring only to the name (i.e. . Short repeat rule ^^^^^^^^^^^^^^^^^ A short repeat rule looks like . The rule specifies that the entire expression, '<...>' should be replaced first with item1, and then with item2, and so forth until N repeats are accomplished. Pre-defined names ^^^^^^^^^^^^^^^^^ The following predefined named repeat rules are available: - - <_c=s,d,c,z> - <_t=real, double precision, complex, double complex> - - - - Other files ----------- Non-Fortran files use a separate syntax for defining template blocks that should be repeated using a variable expansion similar to the named repeat rules of the Fortran-specific repeats. The template rules for these files are: 1. "/\**begin repeat "on a line by itself marks the beginning of a segment that should be repeated. 2. Named variable expansions are defined using #name=item1, item2, item3, ..., itemN# and placed on successive lines. These variables are replaced in each repeat block with corresponding word. All named variables in the same repeat block must define the same number of words. 3. In specifying the repeat rule for a named variable, item*N is short- hand for item, item, ..., item repeated N times. In addition, parenthesis in combination with \*N can be used for grouping several items that should be repeated. Thus, #name=(item1, item2)*4# is equivalent to #name=item1, item2, item1, item2, item1, item2, item1, item2# 4. "\*/ "on a line by itself marks the end of the the variable expansion naming. The next line is the first line that will be repeated using the named rules. 5. Inside the block to be repeated, the variables that should be expanded are specified as @name@. 6. "/\**end repeat**/ "on a line by itself marks the previous line as the last line of the block to be repeated. numpy-1.8.2/doc/source/reference/maskedarray.generic.rst0000664000175100017510000003657412370216242024515 0ustar vagrantvagrant00000000000000.. currentmodule:: numpy.ma .. _maskedarray.generic: The :mod:`numpy.ma` module ========================== Rationale --------- Masked arrays are arrays that may have missing or invalid entries. The :mod:`numpy.ma` module provides a nearly work-alike replacement for numpy that supports data arrays with masks. What is a masked array? ----------------------- In many circumstances, datasets can be incomplete or tainted by the presence of invalid data. For example, a sensor may have failed to record a data, or recorded an invalid value. The :mod:`numpy.ma` module provides a convenient way to address this issue, by introducing masked arrays. A masked array is the combination of a standard :class:`numpy.ndarray` and a mask. A mask is either :attr:`nomask`, indicating that no value of the associated array is invalid, or an array of booleans that determines for each element of the associated array whether the value is valid or not. When an element of the mask is ``False``, the corresponding element of the associated array is valid and is said to be unmasked. When an element of the mask is ``True``, the corresponding element of the associated array is said to be masked (invalid). The package ensures that masked entries are not used in computations. As an illustration, let's consider the following dataset:: >>> import numpy as np >>> import numpy.ma as ma >>> x = np.array([1, 2, 3, -1, 5]) We wish to mark the fourth entry as invalid. The easiest is to create a masked array:: >>> mx = ma.masked_array(x, mask=[0, 0, 0, 1, 0]) We can now compute the mean of the dataset, without taking the invalid data into account:: >>> mx.mean() 2.75 The :mod:`numpy.ma` module -------------------------- The main feature of the :mod:`numpy.ma` module is the :class:`MaskedArray` class, which is a subclass of :class:`numpy.ndarray`. The class, its attributes and methods are described in more details in the :ref:`MaskedArray class ` section. The :mod:`numpy.ma` module can be used as an addition to :mod:`numpy`: :: >>> import numpy as np >>> import numpy.ma as ma To create an array with the second element invalid, we would do:: >>> y = ma.array([1, 2, 3], mask = [0, 1, 0]) To create a masked array where all values close to 1.e20 are invalid, we would do:: >>> z = masked_values([1.0, 1.e20, 3.0, 4.0], 1.e20) For a complete discussion of creation methods for masked arrays please see section :ref:`Constructing masked arrays `. Using numpy.ma ============== .. _maskedarray.generic.constructing: Constructing masked arrays -------------------------- There are several ways to construct a masked array. * A first possibility is to directly invoke the :class:`MaskedArray` class. * A second possibility is to use the two masked array constructors, :func:`array` and :func:`masked_array`. .. autosummary:: :toctree: generated/ array masked_array * A third option is to take the view of an existing array. In that case, the mask of the view is set to :attr:`nomask` if the array has no named fields, or an array of boolean with the same structure as the array otherwise. >>> x = np.array([1, 2, 3]) >>> x.view(ma.MaskedArray) masked_array(data = [1 2 3], mask = False, fill_value = 999999) >>> x = np.array([(1, 1.), (2, 2.)], dtype=[('a',int), ('b', float)]) >>> x.view(ma.MaskedArray) masked_array(data = [(1, 1.0) (2, 2.0)], mask = [(False, False) (False, False)], fill_value = (999999, 1e+20), dtype = [('a', '>> x = ma.array([[1, 2], [3, 4]], mask=[[0, 1], [1, 0]]) >>> x[~x.mask] masked_array(data = [1 4], mask = [False False], fill_value = 999999) Another way to retrieve the valid data is to use the :meth:`compressed` method, which returns a one-dimensional :class:`~numpy.ndarray` (or one of its subclasses, depending on the value of the :attr:`~MaskedArray.baseclass` attribute):: >>> x.compressed() array([1, 4]) Note that the output of :meth:`compressed` is always 1D. Modifying the mask ------------------ Masking an entry ~~~~~~~~~~~~~~~~ The recommended way to mark one or several specific entries of a masked array as invalid is to assign the special value :attr:`masked` to them:: >>> x = ma.array([1, 2, 3]) >>> x[0] = ma.masked >>> x masked_array(data = [-- 2 3], mask = [ True False False], fill_value = 999999) >>> y = ma.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) >>> y[(0, 1, 2), (1, 2, 0)] = ma.masked >>> y masked_array(data = [[1 -- 3] [4 5 --] [-- 8 9]], mask = [[False True False] [False False True] [ True False False]], fill_value = 999999) >>> z = ma.array([1, 2, 3, 4]) >>> z[:-2] = ma.masked >>> z masked_array(data = [-- -- 3 4], mask = [ True True False False], fill_value = 999999) A second possibility is to modify the :attr:`~MaskedArray.mask` directly, but this usage is discouraged. .. note:: When creating a new masked array with a simple, non-structured datatype, the mask is initially set to the special value :attr:`nomask`, that corresponds roughly to the boolean ``False``. Trying to set an element of :attr:`nomask` will fail with a :exc:`TypeError` exception, as a boolean does not support item assignment. All the entries of an array can be masked at once by assigning ``True`` to the mask:: >>> x = ma.array([1, 2, 3], mask=[0, 0, 1]) >>> x.mask = True >>> x masked_array(data = [-- -- --], mask = [ True True True], fill_value = 999999) Finally, specific entries can be masked and/or unmasked by assigning to the mask a sequence of booleans:: >>> x = ma.array([1, 2, 3]) >>> x.mask = [0, 1, 0] >>> x masked_array(data = [1 -- 3], mask = [False True False], fill_value = 999999) Unmasking an entry ~~~~~~~~~~~~~~~~~~ To unmask one or several specific entries, we can just assign one or several new valid values to them:: >>> x = ma.array([1, 2, 3], mask=[0, 0, 1]) >>> x masked_array(data = [1 2 --], mask = [False False True], fill_value = 999999) >>> x[-1] = 5 >>> x masked_array(data = [1 2 5], mask = [False False False], fill_value = 999999) .. note:: Unmasking an entry by direct assignment will silently fail if the masked array has a *hard* mask, as shown by the :attr:`hardmask` attribute. This feature was introduced to prevent overwriting the mask. To force the unmasking of an entry where the array has a hard mask, the mask must first to be softened using the :meth:`soften_mask` method before the allocation. It can be re-hardened with :meth:`harden_mask`:: >>> x = ma.array([1, 2, 3], mask=[0, 0, 1], hard_mask=True) >>> x masked_array(data = [1 2 --], mask = [False False True], fill_value = 999999) >>> x[-1] = 5 >>> x masked_array(data = [1 2 --], mask = [False False True], fill_value = 999999) >>> x.soften_mask() >>> x[-1] = 5 >>> x masked_array(data = [1 2 5], mask = [False False False], fill_value = 999999) >>> x.harden_mask() To unmask all masked entries of a masked array (provided the mask isn't a hard mask), the simplest solution is to assign the constant :attr:`nomask` to the mask:: >>> x = ma.array([1, 2, 3], mask=[0, 0, 1]) >>> x masked_array(data = [1 2 --], mask = [False False True], fill_value = 999999) >>> x.mask = ma.nomask >>> x masked_array(data = [1 2 3], mask = [False False False], fill_value = 999999) Indexing and slicing -------------------- As a :class:`MaskedArray` is a subclass of :class:`numpy.ndarray`, it inherits its mechanisms for indexing and slicing. When accessing a single entry of a masked array with no named fields, the output is either a scalar (if the corresponding entry of the mask is ``False``) or the special value :attr:`masked` (if the corresponding entry of the mask is ``True``):: >>> x = ma.array([1, 2, 3], mask=[0, 0, 1]) >>> x[0] 1 >>> x[-1] masked_array(data = --, mask = True, fill_value = 1e+20) >>> x[-1] is ma.masked True If the masked array has named fields, accessing a single entry returns a :class:`numpy.void` object if none of the fields are masked, or a 0d masked array with the same dtype as the initial array if at least one of the fields is masked. >>> y = ma.masked_array([(1,2), (3, 4)], ... mask=[(0, 0), (0, 1)], ... dtype=[('a', int), ('b', int)]) >>> y[0] (1, 2) >>> y[-1] masked_array(data = (3, --), mask = (False, True), fill_value = (999999, 999999), dtype = [('a', '>> x = ma.array([1, 2, 3, 4, 5], mask=[0, 1, 0, 0, 1]) >>> mx = x[:3] >>> mx masked_array(data = [1 -- 3], mask = [False True False], fill_value = 999999) >>> mx[1] = -1 >>> mx masked_array(data = [1 -1 3], mask = [False True False], fill_value = 999999) >>> x.mask array([False, True, False, False, True], dtype=bool) >>> x.data array([ 1, -1, 3, 4, 5]) Accessing a field of a masked array with structured datatype returns a :class:`MaskedArray`. Operations on masked arrays --------------------------- Arithmetic and comparison operations are supported by masked arrays. As much as possible, invalid entries of a masked array are not processed, meaning that the corresponding :attr:`data` entries *should* be the same before and after the operation. .. warning:: We need to stress that this behavior may not be systematic, that masked data may be affected by the operation in some cases and therefore users should not rely on this data remaining unchanged. The :mod:`numpy.ma` module comes with a specific implementation of most ufuncs. Unary and binary functions that have a validity domain (such as :func:`~numpy.log` or :func:`~numpy.divide`) return the :data:`masked` constant whenever the input is masked or falls outside the validity domain:: >>> ma.log([-1, 0, 1, 2]) masked_array(data = [-- -- 0.0 0.69314718056], mask = [ True True False False], fill_value = 1e+20) Masked arrays also support standard numpy ufuncs. The output is then a masked array. The result of a unary ufunc is masked wherever the input is masked. The result of a binary ufunc is masked wherever any of the input is masked. If the ufunc also returns the optional context output (a 3-element tuple containing the name of the ufunc, its arguments and its domain), the context is processed and entries of the output masked array are masked wherever the corresponding input fall outside the validity domain:: >>> x = ma.array([-1, 1, 0, 2, 3], mask=[0, 0, 0, 0, 1]) >>> np.log(x) masked_array(data = [-- -- 0.0 0.69314718056 --], mask = [ True True False False True], fill_value = 1e+20) Examples ======== Data with a given value representing missing data ------------------------------------------------- Let's consider a list of elements, ``x``, where values of -9999. represent missing data. We wish to compute the average value of the data and the vector of anomalies (deviations from the average):: >>> import numpy.ma as ma >>> x = [0.,1.,-9999.,3.,4.] >>> mx = ma.masked_values (x, -9999.) >>> print mx.mean() 2.0 >>> print mx - mx.mean() [-2.0 -1.0 -- 1.0 2.0] >>> print mx.anom() [-2.0 -1.0 -- 1.0 2.0] Filling in the missing data --------------------------- Suppose now that we wish to print that same data, but with the missing values replaced by the average value. >>> print mx.filled(mx.mean()) [ 0. 1. 2. 3. 4.] Numerical operations -------------------- Numerical operations can be easily performed without worrying about missing values, dividing by zero, square roots of negative numbers, etc.:: >>> import numpy as np, numpy.ma as ma >>> x = ma.array([1., -1., 3., 4., 5., 6.], mask=[0,0,0,0,1,0]) >>> y = ma.array([1., 2., 0., 4., 5., 6.], mask=[0,0,0,0,0,1]) >>> print np.sqrt(x/y) [1.0 -- -- 1.0 -- --] Four values of the output are invalid: the first one comes from taking the square root of a negative number, the second from the division by zero, and the last two where the inputs were masked. Ignoring extreme values ----------------------- Let's consider an array ``d`` of random floats between 0 and 1. We wish to compute the average of the values of ``d`` while ignoring any data outside the range ``[0.1, 0.9]``:: >>> print ma.masked_outside(d, 0.1, 0.9).mean() numpy-1.8.2/doc/source/reference/routines.oldnumeric.rst0000664000175100017510000000033012370216243024565 0ustar vagrantvagrant00000000000000*************************************************** Old Numeric compatibility (:mod:`numpy.oldnumeric`) *************************************************** .. currentmodule:: numpy .. automodule:: numpy.oldnumeric numpy-1.8.2/doc/source/reference/arrays.datetime.rst0000664000175100017510000004276312370216242023670 0ustar vagrantvagrant00000000000000.. currentmodule:: numpy .. _arrays.datetime: ************************ Datetimes and Timedeltas ************************ .. versionadded:: 1.7.0 Starting in NumPy 1.7, there are core array data types which natively support datetime functionality. The data type is called "datetime64", so named because "datetime" is already taken by the datetime library included in Python. .. note:: The datetime API is *experimental* in 1.7.0, and may undergo changes in future versions of NumPy. Basic Datetimes =============== The most basic way to create datetimes is from strings in ISO 8601 date or datetime format. The unit for internal storage is automatically selected from the form of the string, and can be either a :ref:`date unit ` or a :ref:`time unit `. The date units are years ('Y'), months ('M'), weeks ('W'), and days ('D'), while the time units are hours ('h'), minutes ('m'), seconds ('s'), milliseconds ('ms'), and some additional SI-prefix seconds-based units. .. admonition:: Example A simple ISO date: >>> np.datetime64('2005-02-25') numpy.datetime64('2005-02-25') Using months for the unit: >>> np.datetime64('2005-02') numpy.datetime64('2005-02') Specifying just the month, but forcing a 'days' unit: >>> np.datetime64('2005-02', 'D') numpy.datetime64('2005-02-01') Using UTC "Zulu" time: >>> np.datetime64('2005-02-25T03:30Z') numpy.datetime64('2005-02-24T21:30-0600') ISO 8601 specifies to use the local time zone if none is explicitly given: >>> np.datetime64('2005-02-25T03:30') numpy.datetime64('2005-02-25T03:30-0600') When creating an array of datetimes from a string, it is still possible to automatically select the unit from the inputs, by using the datetime type with generic units. .. admonition:: Example >>> np.array(['2007-07-13', '2006-01-13', '2010-08-13'], dtype='datetime64') array(['2007-07-13', '2006-01-13', '2010-08-13'], dtype='datetime64[D]') >>> np.array(['2001-01-01T12:00', '2002-02-03T13:56:03.172'], dtype='datetime64') array(['2001-01-01T12:00:00.000-0600', '2002-02-03T13:56:03.172-0600'], dtype='datetime64[ms]') The datetime type works with many common NumPy functions, for example :func:`arange` can be used to generate ranges of dates. .. admonition:: Example All the dates for one month: >>> np.arange('2005-02', '2005-03', dtype='datetime64[D]') array(['2005-02-01', '2005-02-02', '2005-02-03', '2005-02-04', '2005-02-05', '2005-02-06', '2005-02-07', '2005-02-08', '2005-02-09', '2005-02-10', '2005-02-11', '2005-02-12', '2005-02-13', '2005-02-14', '2005-02-15', '2005-02-16', '2005-02-17', '2005-02-18', '2005-02-19', '2005-02-20', '2005-02-21', '2005-02-22', '2005-02-23', '2005-02-24', '2005-02-25', '2005-02-26', '2005-02-27', '2005-02-28'], dtype='datetime64[D]') The datetime object represents a single moment in time. If two datetimes have different units, they may still be representing the same moment of time, and converting from a bigger unit like months to a smaller unit like days is considered a 'safe' cast because the moment of time is still being represented exactly. .. admonition:: Example >>> np.datetime64('2005') == np.datetime64('2005-01-01') True >>> np.datetime64('2010-03-14T15Z') == np.datetime64('2010-03-14T15:00:00.00Z') True An important exception to this rule is between datetimes with :ref:`date units ` and datetimes with :ref:`time units `. This is because this kind of conversion generally requires a choice of timezone and particular time of day on the given date. .. admonition:: Example >>> np.datetime64('2003-12-25', 's') Traceback (most recent call last): File "", line 1, in TypeError: Cannot parse "2003-12-25" as unit 's' using casting rule 'same_kind' >>> np.datetime64('2003-12-25') == np.datetime64('2003-12-25T00Z') False Datetime and Timedelta Arithmetic ================================= NumPy allows the subtraction of two Datetime values, an operation which produces a number with a time unit. Because NumPy doesn't have a physical quantities system in its core, the timedelta64 data type was created to complement datetime64. Datetimes and Timedeltas work together to provide ways for simple datetime calculations. .. admonition:: Example >>> np.datetime64('2009-01-01') - np.datetime64('2008-01-01') numpy.timedelta64(366,'D') >>> np.datetime64('2009') + np.timedelta64(20, 'D') numpy.datetime64('2009-01-21') >>> np.datetime64('2011-06-15T00:00') + np.timedelta64(12, 'h') numpy.datetime64('2011-06-15T12:00-0500') >>> np.timedelta64(1,'W') / np.timedelta64(1,'D') 7.0 There are two Timedelta units ('Y', years and 'M', months) which are treated specially, because how much time they represent changes depending on when they are used. While a timedelta day unit is equivalent to 24 hours, there is no way to convert a month unit into days, because different months have different numbers of days. .. admonition:: Example >>> a = np.timedelta64(1, 'Y') >>> np.timedelta64(a, 'M') numpy.timedelta64(12,'M') >>> np.timedelta64(a, 'D') Traceback (most recent call last): File "", line 1, in TypeError: Cannot cast NumPy timedelta64 scalar from metadata [Y] to [D] according to the rule 'same_kind' Datetime Units ============== The Datetime and Timedelta data types support a large number of time units, as well as generic units which can be coerced into any of the other units based on input data. Datetimes are always stored based on POSIX time (though having a TAI mode which allows for accounting of leap-seconds is proposed), with a epoch of 1970-01-01T00:00Z. This means the supported dates are always a symmetric interval around the epoch, called "time span" in the table below. The length of the span is the range of a 64-bit integer times the length of the date or unit. For example, the time span for 'W' (week) is exactly 7 times longer than the time span for 'D' (day), and the time span for 'D' (day) is exactly 24 times longer than the time span for 'h' (hour). Here are the date units: .. _arrays.dtypes.dateunits: ======== ================ ======================= ========================== Code Meaning Time span (relative) Time span (absolute) ======== ================ ======================= ========================== Y year +/- 9.2e18 years [9.2e18 BC, 9.2e18 AD] M month +/- 7.6e17 years [7.6e17 BC, 7.6e17 AD] W week +/- 1.7e17 years [1.7e17 BC, 1.7e17 AD] D day +/- 2.5e16 years [2.5e16 BC, 2.5e16 AD] ======== ================ ======================= ========================== And here are the time units: .. _arrays.dtypes.timeunits: ======== ================ ======================= ========================== Code Meaning Time span (relative) Time span (absolute) ======== ================ ======================= ========================== h hour +/- 1.0e15 years [1.0e15 BC, 1.0e15 AD] m minute +/- 1.7e13 years [1.7e13 BC, 1.7e13 AD] s second +/- 2.9e12 years [ 2.9e9 BC, 2.9e9 AD] ms millisecond +/- 2.9e9 years [ 2.9e6 BC, 2.9e6 AD] us microsecond +/- 2.9e6 years [290301 BC, 294241 AD] ns nanosecond +/- 292 years [ 1678 AD, 2262 AD] ps picosecond +/- 106 days [ 1969 AD, 1970 AD] fs femtosecond +/- 2.6 hours [ 1969 AD, 1970 AD] as attosecond +/- 9.2 seconds [ 1969 AD, 1970 AD] ======== ================ ======================= ========================== Business Day Functionality ========================== To allow the datetime to be used in contexts where only certain days of the week are valid, NumPy includes a set of "busday" (business day) functions. The default for busday functions is that the only valid days are Monday through Friday (the usual business days). The implementation is based on a "weekmask" containing 7 Boolean flags to indicate valid days; custom weekmasks are possible that specify other sets of valid days. The "busday" functions can additionally check a list of "holiday" dates, specific dates that are not valid days. The function :func:`busday_offset` allows you to apply offsets specified in business days to datetimes with a unit of 'D' (day). .. admonition:: Example >>> np.busday_offset('2011-06-23', 1) numpy.datetime64('2011-06-24') >>> np.busday_offset('2011-06-23', 2) numpy.datetime64('2011-06-27') When an input date falls on the weekend or a holiday, :func:`busday_offset` first applies a rule to roll the date to a valid business day, then applies the offset. The default rule is 'raise', which simply raises an exception. The rules most typically used are 'forward' and 'backward'. .. admonition:: Example >>> np.busday_offset('2011-06-25', 2) Traceback (most recent call last): File "", line 1, in ValueError: Non-business day date in busday_offset >>> np.busday_offset('2011-06-25', 0, roll='forward') numpy.datetime64('2011-06-27') >>> np.busday_offset('2011-06-25', 2, roll='forward') numpy.datetime64('2011-06-29') >>> np.busday_offset('2011-06-25', 0, roll='backward') numpy.datetime64('2011-06-24') >>> np.busday_offset('2011-06-25', 2, roll='backward') numpy.datetime64('2011-06-28') In some cases, an appropriate use of the roll and the offset is necessary to get a desired answer. .. admonition:: Example The first business day on or after a date: >>> np.busday_offset('2011-03-20', 0, roll='forward') numpy.datetime64('2011-03-21','D') >>> np.busday_offset('2011-03-22', 0, roll='forward') numpy.datetime64('2011-03-22','D') The first business day strictly after a date: >>> np.busday_offset('2011-03-20', 1, roll='backward') numpy.datetime64('2011-03-21','D') >>> np.busday_offset('2011-03-22', 1, roll='backward') numpy.datetime64('2011-03-23','D') The function is also useful for computing some kinds of days like holidays. In Canada and the U.S., Mother's day is on the second Sunday in May, which can be computed with a custom weekmask. .. admonition:: Example >>> np.busday_offset('2012-05', 1, roll='forward', weekmask='Sun') numpy.datetime64('2012-05-13','D') When performance is important for manipulating many business dates with one particular choice of weekmask and holidays, there is an object :class:`busdaycalendar` which stores the data necessary in an optimized form. np.is_busday(): ``````````````` To test a datetime64 value to see if it is a valid day, use :func:`is_busday`. .. admonition:: Example >>> np.is_busday(np.datetime64('2011-07-15')) # a Friday True >>> np.is_busday(np.datetime64('2011-07-16')) # a Saturday False >>> np.is_busday(np.datetime64('2011-07-16'), weekmask="Sat Sun") True >>> a = np.arange(np.datetime64('2011-07-11'), np.datetime64('2011-07-18')) >>> np.is_busday(a) array([ True, True, True, True, True, False, False], dtype='bool') np.busday_count(): `````````````````` To find how many valid days there are in a specified range of datetime64 dates, use :func:`busday_count`: .. admonition:: Example >>> np.busday_count(np.datetime64('2011-07-11'), np.datetime64('2011-07-18')) 5 >>> np.busday_count(np.datetime64('2011-07-18'), np.datetime64('2011-07-11')) -5 If you have an array of datetime64 day values, and you want a count of how many of them are valid dates, you can do this: .. admonition:: Example >>> a = np.arange(np.datetime64('2011-07-11'), np.datetime64('2011-07-18')) >>> np.count_nonzero(np.is_busday(a)) 5 Custom Weekmasks ---------------- Here are several examples of custom weekmask values. These examples specify the "busday" default of Monday through Friday being valid days. Some examples:: # Positional sequences; positions are Monday through Sunday. # Length of the sequence must be exactly 7. weekmask = [1, 1, 1, 1, 1, 0, 0] # list or other sequence; 0 == invalid day, 1 == valid day weekmask = "1111100" # string '0' == invalid day, '1' == valid day # string abbreviations from this list: Mon Tue Wed Thu Fri Sat Sun weekmask = "Mon Tue Wed Thu Fri" # any amount of whitespace is allowed; abbreviations are case-sensitive. weekmask = "MonTue Wed Thu\tFri" Differences Between 1.6 and 1.7 Datetimes ========================================= The NumPy 1.6 release includes a more primitive datetime data type than 1.7. This section documents many of the changes that have taken place. String Parsing `````````````` The datetime string parser in NumPy 1.6 is very liberal in what it accepts, and silently allows invalid input without raising errors. The parser in NumPy 1.7 is quite strict about only accepting ISO 8601 dates, with a few convenience extensions. 1.6 always creates microsecond (us) units by default, whereas 1.7 detects a unit based on the format of the string. Here is a comparison.:: # NumPy 1.6.1 >>> np.datetime64('1979-03-22') 1979-03-22 00:00:00 # NumPy 1.7.0 >>> np.datetime64('1979-03-22') numpy.datetime64('1979-03-22') # NumPy 1.6.1, unit default microseconds >>> np.datetime64('1979-03-22').dtype dtype('datetime64[us]') # NumPy 1.7.0, unit of days detected from string >>> np.datetime64('1979-03-22').dtype dtype('>> np.datetime64('1979-03-2corruptedstring') 1979-03-02 00:00:00 # NumPy 1.7.0, raises error for invalid input >>> np.datetime64('1979-03-2corruptedstring') Traceback (most recent call last): File "", line 1, in ValueError: Error parsing datetime string "1979-03-2corruptedstring" at position 8 # NumPy 1.6.1, 'nat' produces today's date >>> np.datetime64('nat') 2012-04-30 00:00:00 # NumPy 1.7.0, 'nat' produces not-a-time >>> np.datetime64('nat') numpy.datetime64('NaT') # NumPy 1.6.1, 'garbage' produces today's date >>> np.datetime64('garbage') 2012-04-30 00:00:00 # NumPy 1.7.0, 'garbage' raises an exception >>> np.datetime64('garbage') Traceback (most recent call last): File "", line 1, in ValueError: Error parsing datetime string "garbage" at position 0 # NumPy 1.6.1, can't specify unit in scalar constructor >>> np.datetime64('1979-03-22T19:00', 'h') Traceback (most recent call last): File "", line 1, in TypeError: function takes at most 1 argument (2 given) # NumPy 1.7.0, unit in scalar constructor >>> np.datetime64('1979-03-22T19:00', 'h') numpy.datetime64('1979-03-22T19:00-0500','h') # NumPy 1.6.1, reads ISO 8601 strings w/o TZ as UTC >>> np.array(['1979-03-22T19:00'], dtype='M8[h]') array([1979-03-22 19:00:00], dtype=datetime64[h]) # NumPy 1.7.0, reads ISO 8601 strings w/o TZ as local (ISO specifies this) >>> np.array(['1979-03-22T19:00'], dtype='M8[h]') array(['1979-03-22T19-0500'], dtype='datetime64[h]') # NumPy 1.6.1, doesn't parse all ISO 8601 strings correctly >>> np.array(['1979-03-22T12'], dtype='M8[h]') array([1979-03-22 00:00:00], dtype=datetime64[h]) >>> np.array(['1979-03-22T12:00'], dtype='M8[h]') array([1979-03-22 12:00:00], dtype=datetime64[h]) # NumPy 1.7.0, handles this case correctly >>> np.array(['1979-03-22T12'], dtype='M8[h]') array(['1979-03-22T12-0500'], dtype='datetime64[h]') >>> np.array(['1979-03-22T12:00'], dtype='M8[h]') array(['1979-03-22T12-0500'], dtype='datetime64[h]') Unit Conversion ``````````````` The 1.6 implementation of datetime does not convert between units correctly.:: # NumPy 1.6.1, the representation value is untouched >>> np.array(['1979-03-22'], dtype='M8[D]') array([1979-03-22 00:00:00], dtype=datetime64[D]) >>> np.array(['1979-03-22'], dtype='M8[D]').astype('M8[M]') array([2250-08-01 00:00:00], dtype=datetime64[M]) # NumPy 1.7.0, the representation is scaled accordingly >>> np.array(['1979-03-22'], dtype='M8[D]') array(['1979-03-22'], dtype='datetime64[D]') >>> np.array(['1979-03-22'], dtype='M8[D]').astype('M8[M]') array(['1979-03'], dtype='datetime64[M]') Datetime Arithmetic ``````````````````` The 1.6 implementation of datetime only works correctly for a small subset of arithmetic operations. Here we show some simple cases.:: # NumPy 1.6.1, produces invalid results if units are incompatible >>> a = np.array(['1979-03-22T12'], dtype='M8[h]') >>> b = np.array([3*60], dtype='m8[m]') >>> a + b array([1970-01-01 00:00:00.080988], dtype=datetime64[us]) # NumPy 1.7.0, promotes to higher-resolution unit >>> a = np.array(['1979-03-22T12'], dtype='M8[h]') >>> b = np.array([3*60], dtype='m8[m]') >>> a + b array(['1979-03-22T15:00-0500'], dtype='datetime64[m]') # NumPy 1.6.1, arithmetic works if everything is microseconds >>> a = np.array(['1979-03-22T12:00'], dtype='M8[us]') >>> b = np.array([3*60*60*1000000], dtype='m8[us]') >>> a + b array([1979-03-22 15:00:00], dtype=datetime64[us]) # NumPy 1.7.0 >>> a = np.array(['1979-03-22T12:00'], dtype='M8[us]') >>> b = np.array([3*60*60*1000000], dtype='m8[us]') >>> a + b array(['1979-03-22T15:00:00.000000-0500'], dtype='datetime64[us]') numpy-1.8.2/doc/source/reference/swig.rst0000664000175100017510000000022312370216242021526 0ustar vagrantvagrant00000000000000************** Numpy and SWIG ************** .. sectionauthor:: Bill Spotz .. toctree:: :maxdepth: 2 swig.interface-file swig.testing numpy-1.8.2/doc/source/reference/routines.polynomials.laguerre.rst0000664000175100017510000000245512370216242026610 0ustar vagrantvagrant00000000000000Laguerre Module (:mod:`numpy.polynomial.laguerre`) ================================================== .. versionadded:: 1.6.0 .. currentmodule:: numpy.polynomial.laguerre This module provides a number of objects (mostly functions) useful for dealing with Laguerre series, including a `Laguerre` class that encapsulates the usual arithmetic operations. (General information on how this module represents and works with such polynomials is in the docstring for its "parent" sub-package, `numpy.polynomial`). Laguerre Class -------------- .. autosummary:: :toctree: generated/ Laguerre Basics ------ .. autosummary:: :toctree: generated/ lagval lagval2d lagval3d laggrid2d laggrid3d lagroots lagfromroots Fitting ------- .. autosummary:: :toctree: generated/ lagfit lagvander lagvander2d lagvander3d Calculus -------- .. autosummary:: :toctree: generated/ lagder lagint Algebra ------- .. autosummary:: :toctree: generated/ lagadd lagsub lagmul lagmulx lagdiv lagpow Quadrature ---------- .. autosummary:: :toctree: generated/ laggauss lagweight Miscellaneous ------------- .. autosummary:: :toctree: generated/ lagcompanion lagdomain lagzero lagone lagx lagtrim lagline lag2poly poly2lag numpy-1.8.2/doc/source/reference/routines.io.rst0000664000175100017510000000171312370216242023040 0ustar vagrantvagrant00000000000000Input and output **************** .. currentmodule:: numpy NPZ files --------- .. autosummary:: :toctree: generated/ load save savez savez_compressed Text files ---------- .. autosummary:: :toctree: generated/ loadtxt savetxt genfromtxt fromregex fromstring ndarray.tofile ndarray.tolist Raw binary files ---------------- .. autosummary:: fromfile ndarray.tofile String formatting ----------------- .. autosummary:: :toctree: generated/ array_repr array_str Memory mapping files -------------------- .. autosummary:: :toctree: generated/ memmap Text formatting options ----------------------- .. autosummary:: :toctree: generated/ set_printoptions get_printoptions set_string_function Base-n representations ---------------------- .. autosummary:: :toctree: generated/ binary_repr base_repr Data sources ------------ .. autosummary:: :toctree: generated/ DataSource numpy-1.8.2/doc/source/reference/routines.dual.rst0000664000175100017510000000076712370216242023366 0ustar vagrantvagrant00000000000000Optionally Scipy-accelerated routines (:mod:`numpy.dual`) ********************************************************* .. automodule:: numpy.dual Linear algebra -------------- .. currentmodule:: numpy.linalg .. autosummary:: cholesky det eig eigh eigvals eigvalsh inv lstsq norm pinv solve svd FFT --- .. currentmodule:: numpy.fft .. autosummary:: fft fft2 fftn ifft ifft2 ifftn Other ----- .. currentmodule:: numpy .. autosummary:: i0 numpy-1.8.2/doc/source/reference/routines.help.rst0000664000175100017510000000042412370216242023357 0ustar vagrantvagrant00000000000000.. _routines.help: Numpy-specific help functions ============================= .. currentmodule:: numpy Finding help ------------ .. autosummary:: :toctree: generated/ lookfor Reading help ------------ .. autosummary:: :toctree: generated/ info source numpy-1.8.2/doc/source/reference/c-api.config.rst0000664000175100017510000000454512370216242023025 0ustar vagrantvagrant00000000000000System configuration ==================== .. sectionauthor:: Travis E. Oliphant When NumPy is built, information about system configuration is recorded, and is made available for extension modules using Numpy's C API. These are mostly defined in ``numpyconfig.h`` (included in ``ndarrayobject.h``). The public symbols are prefixed by ``NPY_*``. Numpy also offers some functions for querying information about the platform in use. For private use, Numpy also constructs a ``config.h`` in the NumPy include directory, which is not exported by Numpy (that is a python extension which use the numpy C API will not see those symbols), to avoid namespace pollution. Data type sizes --------------- The :cdata:`NPY_SIZEOF_{CTYPE}` constants are defined so that sizeof information is available to the pre-processor. .. cvar:: NPY_SIZEOF_SHORT sizeof(short) .. cvar:: NPY_SIZEOF_INT sizeof(int) .. cvar:: NPY_SIZEOF_LONG sizeof(long) .. cvar:: NPY_SIZEOF_LONGLONG sizeof(longlong) where longlong is defined appropriately on the platform. .. cvar:: NPY_SIZEOF_PY_LONG_LONG .. cvar:: NPY_SIZEOF_FLOAT sizeof(float) .. cvar:: NPY_SIZEOF_DOUBLE sizeof(double) .. cvar:: NPY_SIZEOF_LONG_DOUBLE sizeof(longdouble) (A macro defines **NPY_SIZEOF_LONGDOUBLE** as well.) .. cvar:: NPY_SIZEOF_PY_INTPTR_T Size of a pointer on this platform (sizeof(void \*)) (A macro defines NPY_SIZEOF_INTP as well.) Platform information -------------------- .. cvar:: NPY_CPU_X86 .. cvar:: NPY_CPU_AMD64 .. cvar:: NPY_CPU_IA64 .. cvar:: NPY_CPU_PPC .. cvar:: NPY_CPU_PPC64 .. cvar:: NPY_CPU_SPARC .. cvar:: NPY_CPU_SPARC64 .. cvar:: NPY_CPU_S390 .. cvar:: NPY_CPU_PARISC .. versionadded:: 1.3.0 CPU architecture of the platform; only one of the above is defined. Defined in ``numpy/npy_cpu.h`` .. cvar:: NPY_LITTLE_ENDIAN .. cvar:: NPY_BIG_ENDIAN .. cvar:: NPY_BYTE_ORDER .. versionadded:: 1.3.0 Portable alternatives to the ``endian.h`` macros of GNU Libc. If big endian, :cdata:`NPY_BYTE_ORDER` == :cdata:`NPY_BIG_ENDIAN`, and similarly for little endian architectures. Defined in ``numpy/npy_endian.h``. .. cfunction:: PyArray_GetEndianness() .. versionadded:: 1.3.0 Returns the endianness of the current platform. One of :cdata:`NPY_CPU_BIG`, :cdata:`NPY_CPU_LITTLE`, or :cdata:`NPY_CPU_UNKNOWN_ENDIAN`. numpy-1.8.2/doc/source/reference/routines.polynomials.polynomial.rst0000664000175100017510000000235012370216242027157 0ustar vagrantvagrant00000000000000Polynomial Module (:mod:`numpy.polynomial.polynomial`) ====================================================== .. versionadded:: 1.4.0 .. currentmodule:: numpy.polynomial.polynomial This module provides a number of objects (mostly functions) useful for dealing with Polynomial series, including a `Polynomial` class that encapsulates the usual arithmetic operations. (General information on how this module represents and works with such polynomials is in the docstring for its "parent" sub-package, `numpy.polynomial`). Polynomial Class ---------------- .. autosummary:: :toctree: generated/ Polynomial Basics ------ .. autosummary:: :toctree: generated/ polyval polyval2d polyval3d polygrid2d polygrid3d polyroots polyfromroots Fitting ------- .. autosummary:: :toctree: generated/ polyfit polyvander polyvander2d polyvander3d Calculus -------- .. autosummary:: :toctree: generated/ polyder polyint Algebra ------- .. autosummary:: :toctree: generated/ polyadd polysub polymul polymulx polydiv polypow Miscellaneous ------------- .. autosummary:: :toctree: generated/ polycompanion polydomain polyzero polyone polyx polytrim polyline numpy-1.8.2/doc/source/reference/arrays.rst0000664000175100017510000000306512370216242022065 0ustar vagrantvagrant00000000000000.. _arrays: ************* Array objects ************* .. currentmodule:: numpy NumPy provides an N-dimensional array type, the :ref:`ndarray `, which describes a collection of "items" of the same type. The items can be :ref:`indexed ` using for example N integers. All ndarrays are :term:`homogenous`: every item takes up the same size block of memory, and all blocks are interpreted in exactly the same way. How each item in the array is to be interpreted is specified by a separate :ref:`data-type object `, one of which is associated with every array. In addition to basic types (integers, floats, *etc.*), the data type objects can also represent data structures. An item extracted from an array, *e.g.*, by indexing, is represented by a Python object whose type is one of the :ref:`array scalar types ` built in Numpy. The array scalars allow easy manipulation of also more complicated arrangements of data. .. figure:: figures/threefundamental.png **Figure** Conceptual diagram showing the relationship between the three fundamental objects used to describe the data in an array: 1) the ndarray itself, 2) the data-type object that describes the layout of a single fixed-size element of the array, 3) the array-scalar Python object that is returned when a single element of the array is accessed. .. toctree:: :maxdepth: 2 arrays.ndarray arrays.scalars arrays.dtypes arrays.indexing arrays.nditer arrays.classes maskedarray arrays.interface arrays.datetime numpy-1.8.2/doc/source/reference/routines.rst0000664000175100017510000000207012370216243022430 0ustar vagrantvagrant00000000000000******** Routines ******** In this chapter routine docstrings are presented, grouped by functionality. Many docstrings contain example code, which demonstrates basic usage of the routine. The examples assume that NumPy is imported with:: >>> import numpy as np A convenient way to execute examples is the ``%doctest_mode`` mode of IPython, which allows for pasting of multi-line examples and preserves indentation. .. toctree:: :maxdepth: 2 routines.array-creation routines.array-manipulation routines.bitwise routines.char routines.ctypeslib routines.datetime routines.dtype routines.dual routines.emath routines.err routines.fft routines.financial routines.functional routines.help routines.indexing routines.io routines.linalg routines.logic routines.ma routines.math routines.matlib routines.numarray routines.oldnumeric routines.other routines.padding routines.polynomials routines.random routines.set routines.sort routines.statistics routines.testing routines.window numpy-1.8.2/doc/source/reference/routines.padding.rst0000664000175100017510000000015212370216242024033 0ustar vagrantvagrant00000000000000Padding Arrays ============== .. currentmodule:: numpy .. autosummary:: :toctree: generated/ pad numpy-1.8.2/doc/source/reference/routines.ctypeslib.rst0000664000175100017510000000056112370216242024427 0ustar vagrantvagrant00000000000000*********************************************************** C-Types Foreign Function Interface (:mod:`numpy.ctypeslib`) *********************************************************** .. currentmodule:: numpy.ctypeslib .. autofunction:: as_array .. autofunction:: as_ctypes .. autofunction:: ctypes_load_library .. autofunction:: load_library .. autofunction:: ndpointer numpy-1.8.2/doc/source/reference/c-api.types-and-structures.rst0000664000175100017510000013366212370216243025711 0ustar vagrantvagrant00000000000000***************************** Python Types and C-Structures ***************************** .. sectionauthor:: Travis E. Oliphant Several new types are defined in the C-code. Most of these are accessible from Python, but a few are not exposed due to their limited use. Every new Python type has an associated :ctype:`PyObject *` with an internal structure that includes a pointer to a "method table" that defines how the new object behaves in Python. When you receive a Python object into C code, you always get a pointer to a :ctype:`PyObject` structure. Because a :ctype:`PyObject` structure is very generic and defines only :cmacro:`PyObject_HEAD`, by itself it is not very interesting. However, different objects contain more details after the :cmacro:`PyObject_HEAD` (but you have to cast to the correct type to access them --- or use accessor functions or macros). New Python Types Defined ======================== Python types are the functional equivalent in C of classes in Python. By constructing a new Python type you make available a new object for Python. The ndarray object is an example of a new type defined in C. New types are defined in C by two basic steps: 1. creating a C-structure (usually named :ctype:`Py{Name}Object`) that is binary- compatible with the :ctype:`PyObject` structure itself but holds the additional information needed for that particular object; 2. populating the :ctype:`PyTypeObject` table (pointed to by the ob_type member of the :ctype:`PyObject` structure) with pointers to functions that implement the desired behavior for the type. Instead of special method names which define behavior for Python classes, there are "function tables" which point to functions that implement the desired results. Since Python 2.2, the PyTypeObject itself has become dynamic which allows C types that can be "sub-typed "from other C-types in C, and sub-classed in Python. The children types inherit the attributes and methods from their parent(s). There are two major new types: the ndarray ( :cdata:`PyArray_Type` ) and the ufunc ( :cdata:`PyUFunc_Type` ). Additional types play a supportive role: the :cdata:`PyArrayIter_Type`, the :cdata:`PyArrayMultiIter_Type`, and the :cdata:`PyArrayDescr_Type` . The :cdata:`PyArrayIter_Type` is the type for a flat iterator for an ndarray (the object that is returned when getting the flat attribute). The :cdata:`PyArrayMultiIter_Type` is the type of the object returned when calling ``broadcast`` (). It handles iteration and broadcasting over a collection of nested sequences. Also, the :cdata:`PyArrayDescr_Type` is the data-type-descriptor type whose instances describe the data. Finally, there are 21 new scalar-array types which are new Python scalars corresponding to each of the fundamental data types available for arrays. An additional 10 other types are place holders that allow the array scalars to fit into a hierarchy of actual Python types. PyArray_Type ------------ .. cvar:: PyArray_Type The Python type of the ndarray is :cdata:`PyArray_Type`. In C, every ndarray is a pointer to a :ctype:`PyArrayObject` structure. The ob_type member of this structure contains a pointer to the :cdata:`PyArray_Type` typeobject. .. ctype:: PyArrayObject The :ctype:`PyArrayObject` C-structure contains all of the required information for an array. All instances of an ndarray (and its subclasses) will have this structure. For future compatibility, these structure members should normally be accessed using the provided macros. If you need a shorter name, then you can make use of :ctype:`NPY_AO` which is defined to be equivalent to :ctype:`PyArrayObject`. .. code-block:: c typedef struct PyArrayObject { PyObject_HEAD char *data; int nd; npy_intp *dimensions; npy_intp *strides; PyObject *base; PyArray_Descr *descr; int flags; PyObject *weakreflist; } PyArrayObject; .. cmacro:: PyArrayObject.PyObject_HEAD This is needed by all Python objects. It consists of (at least) a reference count member ( ``ob_refcnt`` ) and a pointer to the typeobject ( ``ob_type`` ). (Other elements may also be present if Python was compiled with special options see Include/object.h in the Python source tree for more information). The ob_type member points to a Python type object. .. cmember:: char *PyArrayObject.data A pointer to the first element of the array. This pointer can (and normally should) be recast to the data type of the array. .. cmember:: int PyArrayObject.nd An integer providing the number of dimensions for this array. When nd is 0, the array is sometimes called a rank-0 array. Such arrays have undefined dimensions and strides and cannot be accessed. :cdata:`NPY_MAXDIMS` is the largest number of dimensions for any array. .. cmember:: npy_intp PyArrayObject.dimensions An array of integers providing the shape in each dimension as long as nd :math:`\geq` 1. The integer is always large enough to hold a pointer on the platform, so the dimension size is only limited by memory. .. cmember:: npy_intp *PyArrayObject.strides An array of integers providing for each dimension the number of bytes that must be skipped to get to the next element in that dimension. .. cmember:: PyObject *PyArrayObject.base This member is used to hold a pointer to another Python object that is related to this array. There are two use cases: 1) If this array does not own its own memory, then base points to the Python object that owns it (perhaps another array object), 2) If this array has the :cdata:`NPY_ARRAY_UPDATEIFCOPY` flag set, then this array is a working copy of a "misbehaved" array. As soon as this array is deleted, the array pointed to by base will be updated with the contents of this array. .. cmember:: PyArray_Descr *PyArrayObject.descr A pointer to a data-type descriptor object (see below). The data-type descriptor object is an instance of a new built-in type which allows a generic description of memory. There is a descriptor structure for each data type supported. This descriptor structure contains useful information about the type as well as a pointer to a table of function pointers to implement specific functionality. .. cmember:: int PyArrayObject.flags Flags indicating how the memory pointed to by data is to be interpreted. Possible flags are :cdata:`NPY_ARRAY_C_CONTIGUOUS`, :cdata:`NPY_ARRAY_F_CONTIGUOUS`, :cdata:`NPY_ARRAY_OWNDATA`, :cdata:`NPY_ARRAY_ALIGNED`, :cdata:`NPY_ARRAY_WRITEABLE`, and :cdata:`NPY_ARRAY_UPDATEIFCOPY`. .. cmember:: PyObject *PyArrayObject.weakreflist This member allows array objects to have weak references (using the weakref module). PyArrayDescr_Type ----------------- .. cvar:: PyArrayDescr_Type The :cdata:`PyArrayDescr_Type` is the built-in type of the data-type-descriptor objects used to describe how the bytes comprising the array are to be interpreted. There are 21 statically-defined :ctype:`PyArray_Descr` objects for the built-in data-types. While these participate in reference counting, their reference count should never reach zero. There is also a dynamic table of user-defined :ctype:`PyArray_Descr` objects that is also maintained. Once a data-type-descriptor object is "registered" it should never be deallocated either. The function :cfunc:`PyArray_DescrFromType` (...) can be used to retrieve a :ctype:`PyArray_Descr` object from an enumerated type-number (either built-in or user- defined). .. ctype:: PyArray_Descr The format of the :ctype:`PyArray_Descr` structure that lies at the heart of the :cdata:`PyArrayDescr_Type` is .. code-block:: c typedef struct { PyObject_HEAD PyTypeObject *typeobj; char kind; char type; char byteorder; char unused; int flags; int type_num; int elsize; int alignment; PyArray_ArrayDescr *subarray; PyObject *fields; PyArray_ArrFuncs *f; } PyArray_Descr; .. cmember:: PyTypeObject *PyArray_Descr.typeobj Pointer to a typeobject that is the corresponding Python type for the elements of this array. For the builtin types, this points to the corresponding array scalar. For user-defined types, this should point to a user-defined typeobject. This typeobject can either inherit from array scalars or not. If it does not inherit from array scalars, then the :cdata:`NPY_USE_GETITEM` and :cdata:`NPY_USE_SETITEM` flags should be set in the ``flags`` member. .. cmember:: char PyArray_Descr.kind A character code indicating the kind of array (using the array interface typestring notation). A 'b' represents Boolean, a 'i' represents signed integer, a 'u' represents unsigned integer, 'f' represents floating point, 'c' represents complex floating point, 'S' represents 8-bit character string, 'U' represents 32-bit/character unicode string, and 'V' repesents arbitrary. .. cmember:: char PyArray_Descr.type A traditional character code indicating the data type. .. cmember:: char PyArray_Descr.byteorder A character indicating the byte-order: '>' (big-endian), '<' (little- endian), '=' (native), '\|' (irrelevant, ignore). All builtin data- types have byteorder '='. .. cmember:: int PyArray_Descr.flags A data-type bit-flag that determines if the data-type exhibits object- array like behavior. Each bit in this member is a flag which are named as: .. cvar:: NPY_ITEM_REFCOUNT .. cvar:: NPY_ITEM_HASOBJECT Indicates that items of this data-type must be reference counted (using :cfunc:`Py_INCREF` and :cfunc:`Py_DECREF` ). .. cvar:: NPY_ITEM_LISTPICKLE Indicates arrays of this data-type must be converted to a list before pickling. .. cvar:: NPY_ITEM_IS_POINTER Indicates the item is a pointer to some other data-type .. cvar:: NPY_NEEDS_INIT Indicates memory for this data-type must be initialized (set to 0) on creation. .. cvar:: NPY_NEEDS_PYAPI Indicates this data-type requires the Python C-API during access (so don't give up the GIL if array access is going to be needed). .. cvar:: NPY_USE_GETITEM On array access use the ``f->getitem`` function pointer instead of the standard conversion to an array scalar. Must use if you don't define an array scalar to go along with the data-type. .. cvar:: NPY_USE_SETITEM When creating a 0-d array from an array scalar use ``f->setitem`` instead of the standard copy from an array scalar. Must use if you don't define an array scalar to go along with the data-type. .. cvar:: NPY_FROM_FIELDS The bits that are inherited for the parent data-type if these bits are set in any field of the data-type. Currently ( :cdata:`NPY_NEEDS_INIT` \| :cdata:`NPY_LIST_PICKLE` \| :cdata:`NPY_ITEM_REFCOUNT` \| :cdata:`NPY_NEEDS_PYAPI` ). .. cvar:: NPY_OBJECT_DTYPE_FLAGS Bits set for the object data-type: ( :cdata:`NPY_LIST_PICKLE` \| :cdata:`NPY_USE_GETITEM` \| :cdata:`NPY_ITEM_IS_POINTER` \| :cdata:`NPY_REFCOUNT` \| :cdata:`NPY_NEEDS_INIT` \| :cdata:`NPY_NEEDS_PYAPI`). .. cfunction:: PyDataType_FLAGCHK(PyArray_Descr *dtype, int flags) Return true if all the given flags are set for the data-type object. .. cfunction:: PyDataType_REFCHK(PyArray_Descr *dtype) Equivalent to :cfunc:`PyDataType_FLAGCHK` (*dtype*, :cdata:`NPY_ITEM_REFCOUNT`). .. cmember:: int PyArray_Descr.type_num A number that uniquely identifies the data type. For new data-types, this number is assigned when the data-type is registered. .. cmember:: int PyArray_Descr.elsize For data types that are always the same size (such as long), this holds the size of the data type. For flexible data types where different arrays can have a different elementsize, this should be 0. .. cmember:: int PyArray_Descr.alignment A number providing alignment information for this data type. Specifically, it shows how far from the start of a 2-element structure (whose first element is a ``char`` ), the compiler places an item of this type: ``offsetof(struct {char c; type v;}, v)`` .. cmember:: PyArray_ArrayDescr *PyArray_Descr.subarray If this is non- ``NULL``, then this data-type descriptor is a C-style contiguous array of another data-type descriptor. In other-words, each element that this descriptor describes is actually an array of some other base descriptor. This is most useful as the data-type descriptor for a field in another data-type descriptor. The fields member should be ``NULL`` if this is non- ``NULL`` (the fields member of the base descriptor can be non- ``NULL`` however). The :ctype:`PyArray_ArrayDescr` structure is defined using .. code-block:: c typedef struct { PyArray_Descr *base; PyObject *shape; } PyArray_ArrayDescr; The elements of this structure are: .. cmember:: PyArray_Descr *PyArray_ArrayDescr.base The data-type-descriptor object of the base-type. .. cmember:: PyObject *PyArray_ArrayDescr.shape The shape (always C-style contiguous) of the sub-array as a Python tuple. .. cmember:: PyObject *PyArray_Descr.fields If this is non-NULL, then this data-type-descriptor has fields described by a Python dictionary whose keys are names (and also titles if given) and whose values are tuples that describe the fields. Recall that a data-type-descriptor always describes a fixed-length set of bytes. A field is a named sub-region of that total, fixed-length collection. A field is described by a tuple composed of another data- type-descriptor and a byte offset. Optionally, the tuple may contain a title which is normally a Python string. These tuples are placed in this dictionary keyed by name (and also title if given). .. cmember:: PyArray_ArrFuncs *PyArray_Descr.f A pointer to a structure containing functions that the type needs to implement internal features. These functions are not the same thing as the universal functions (ufuncs) described later. Their signatures can vary arbitrarily. .. ctype:: PyArray_ArrFuncs Functions implementing internal features. Not all of these function pointers must be defined for a given type. The required members are ``nonzero``, ``copyswap``, ``copyswapn``, ``setitem``, ``getitem``, and ``cast``. These are assumed to be non- ``NULL`` and ``NULL`` entries will cause a program crash. The other functions may be ``NULL`` which will just mean reduced functionality for that data-type. (Also, the nonzero function will be filled in with a default function if it is ``NULL`` when you register a user-defined data-type). .. code-block:: c typedef struct { PyArray_VectorUnaryFunc *cast[NPY_NTYPES]; PyArray_GetItemFunc *getitem; PyArray_SetItemFunc *setitem; PyArray_CopySwapNFunc *copyswapn; PyArray_CopySwapFunc *copyswap; PyArray_CompareFunc *compare; PyArray_ArgFunc *argmax; PyArray_DotFunc *dotfunc; PyArray_ScanFunc *scanfunc; PyArray_FromStrFunc *fromstr; PyArray_NonzeroFunc *nonzero; PyArray_FillFunc *fill; PyArray_FillWithScalarFunc *fillwithscalar; PyArray_SortFunc *sort[NPY_NSORTS]; PyArray_ArgSortFunc *argsort[NPY_NSORTS]; PyObject *castdict; PyArray_ScalarKindFunc *scalarkind; int **cancastscalarkindto; int *cancastto; int listpickle } PyArray_ArrFuncs; The concept of a behaved segment is used in the description of the function pointers. A behaved segment is one that is aligned and in native machine byte-order for the data-type. The ``nonzero``, ``copyswap``, ``copyswapn``, ``getitem``, and ``setitem`` functions can (and must) deal with mis-behaved arrays. The other functions require behaved memory segments. .. cmember:: void cast(void *from, void *to, npy_intp n, void *fromarr, void *toarr) An array of function pointers to cast from the current type to all of the other builtin types. Each function casts a contiguous, aligned, and notswapped buffer pointed at by *from* to a contiguous, aligned, and notswapped buffer pointed at by *to* The number of items to cast is given by *n*, and the arguments *fromarr* and *toarr* are interpreted as PyArrayObjects for flexible arrays to get itemsize information. .. cmember:: PyObject *getitem(void *data, void *arr) A pointer to a function that returns a standard Python object from a single element of the array object *arr* pointed to by *data*. This function must be able to deal with "misbehaved "(misaligned and/or swapped) arrays correctly. .. cmember:: int setitem(PyObject *item, void *data, void *arr) A pointer to a function that sets the Python object *item* into the array, *arr*, at the position pointed to by *data* . This function deals with "misbehaved" arrays. If successful, a zero is returned, otherwise, a negative one is returned (and a Python error set). .. cmember:: void copyswapn(void *dest, npy_intp dstride, void *src, npy_intp sstride, npy_intp n, int swap, void *arr) .. cmember:: void copyswap(void *dest, void *src, int swap, void *arr) These members are both pointers to functions to copy data from *src* to *dest* and *swap* if indicated. The value of arr is only used for flexible ( :cdata:`NPY_STRING`, :cdata:`NPY_UNICODE`, and :cdata:`NPY_VOID` ) arrays (and is obtained from ``arr->descr->elsize`` ). The second function copies a single value, while the first loops over n values with the provided strides. These functions can deal with misbehaved *src* data. If *src* is NULL then no copy is performed. If *swap* is 0, then no byteswapping occurs. It is assumed that *dest* and *src* do not overlap. If they overlap, then use ``memmove`` (...) first followed by ``copyswap(n)`` with NULL valued ``src``. .. cmember:: int compare(const void* d1, const void* d2, void* arr) A pointer to a function that compares two elements of the array, ``arr``, pointed to by ``d1`` and ``d2``. This function requires behaved arrays. The return value is 1 if * ``d1`` > * ``d2``, 0 if * ``d1`` == * ``d2``, and -1 if * ``d1`` < * ``d2``. The array object arr is used to retrieve itemsize and field information for flexible arrays. .. cmember:: int argmax(void* data, npy_intp n, npy_intp* max_ind, void* arr) A pointer to a function that retrieves the index of the largest of ``n`` elements in ``arr`` beginning at the element pointed to by ``data``. This function requires that the memory segment be contiguous and behaved. The return value is always 0. The index of the largest element is returned in ``max_ind``. .. cmember:: void dotfunc(void* ip1, npy_intp is1, void* ip2, npy_intp is2, void* op, npy_intp n, void* arr) A pointer to a function that multiplies two ``n`` -length sequences together, adds them, and places the result in element pointed to by ``op`` of ``arr``. The start of the two sequences are pointed to by ``ip1`` and ``ip2``. To get to the next element in each sequence requires a jump of ``is1`` and ``is2`` *bytes*, respectively. This function requires behaved (though not necessarily contiguous) memory. .. cmember:: int scanfunc(FILE* fd, void* ip , void* sep , void* arr) A pointer to a function that scans (scanf style) one element of the corresponding type from the file descriptor ``fd`` into the array memory pointed to by ``ip``. The array is assumed to be behaved. If ``sep`` is not NULL, then a separator string is also scanned from the file before returning. The last argument ``arr`` is the array to be scanned into. A 0 is returned if the scan is successful. A negative number indicates something went wrong: -1 means the end of file was reached before the separator string could be scanned, -4 means that the end of file was reached before the element could be scanned, and -3 means that the element could not be interpreted from the format string. Requires a behaved array. .. cmember:: int fromstr(char* str, void* ip, char** endptr, void* arr) A pointer to a function that converts the string pointed to by ``str`` to one element of the corresponding type and places it in the memory location pointed to by ``ip``. After the conversion is completed, ``*endptr`` points to the rest of the string. The last argument ``arr`` is the array into which ip points (needed for variable-size data- types). Returns 0 on success or -1 on failure. Requires a behaved array. .. cmember:: Bool nonzero(void* data, void* arr) A pointer to a function that returns TRUE if the item of ``arr`` pointed to by ``data`` is nonzero. This function can deal with misbehaved arrays. .. cmember:: void fill(void* data, npy_intp length, void* arr) A pointer to a function that fills a contiguous array of given length with data. The first two elements of the array must already be filled- in. From these two values, a delta will be computed and the values from item 3 to the end will be computed by repeatedly adding this computed delta. The data buffer must be well-behaved. .. cmember:: void fillwithscalar(void* buffer, npy_intp length, void* value, void* arr) A pointer to a function that fills a contiguous ``buffer`` of the given ``length`` with a single scalar ``value`` whose address is given. The final argument is the array which is needed to get the itemsize for variable-length arrays. .. cmember:: int sort(void* start, npy_intp length, void* arr) An array of function pointers to a particular sorting algorithms. A particular sorting algorithm is obtained using a key (so far :cdata:`NPY_QUICKSORT`, :data`NPY_HEAPSORT`, and :cdata:`NPY_MERGESORT` are defined). These sorts are done in-place assuming contiguous and aligned data. .. cmember:: int argsort(void* start, npy_intp* result, npy_intp length, void \*arr) An array of function pointers to sorting algorithms for this data type. The same sorting algorithms as for sort are available. The indices producing the sort are returned in result (which must be initialized with indices 0 to length-1 inclusive). .. cmember:: PyObject *castdict Either ``NULL`` or a dictionary containing low-level casting functions for user- defined data-types. Each function is wrapped in a :ctype:`PyCObject *` and keyed by the data-type number. .. cmember:: NPY_SCALARKIND scalarkind(PyArrayObject* arr) A function to determine how scalars of this type should be interpreted. The argument is ``NULL`` or a 0-dimensional array containing the data (if that is needed to determine the kind of scalar). The return value must be of type :ctype:`NPY_SCALARKIND`. .. cmember:: int **cancastscalarkindto Either ``NULL`` or an array of :ctype:`NPY_NSCALARKINDS` pointers. These pointers should each be either ``NULL`` or a pointer to an array of integers (terminated by :cdata:`NPY_NOTYPE`) indicating data-types that a scalar of this data-type of the specified kind can be cast to safely (this usually means without losing precision). .. cmember:: int *cancastto Either ``NULL`` or an array of integers (terminated by :cdata:`NPY_NOTYPE` ) indicated data-types that this data-type can be cast to safely (this usually means without losing precision). .. cmember:: int listpickle Unused. The :cdata:`PyArray_Type` typeobject implements many of the features of Python objects including the tp_as_number, tp_as_sequence, tp_as_mapping, and tp_as_buffer interfaces. The rich comparison (tp_richcompare) is also used along with new-style attribute lookup for methods (tp_methods) and properties (tp_getset). The :cdata:`PyArray_Type` can also be sub-typed. .. tip:: The tp_as_number methods use a generic approach to call whatever function has been registered for handling the operation. The function PyNumeric_SetOps(..) can be used to register functions to handle particular mathematical operations (for all arrays). When the umath module is imported, it sets the numeric operations for all arrays to the corresponding ufuncs. The tp_str and tp_repr methods can also be altered using PyString_SetStringFunction(...). PyUFunc_Type ------------ .. cvar:: PyUFunc_Type The ufunc object is implemented by creation of the :cdata:`PyUFunc_Type`. It is a very simple type that implements only basic getattribute behavior, printing behavior, and has call behavior which allows these objects to act like functions. The basic idea behind the ufunc is to hold a reference to fast 1-dimensional (vector) loops for each data type that supports the operation. These one-dimensional loops all have the same signature and are the key to creating a new ufunc. They are called by the generic looping code as appropriate to implement the N-dimensional function. There are also some generic 1-d loops defined for floating and complexfloating arrays that allow you to define a ufunc using a single scalar function (*e.g.* atanh). .. ctype:: PyUFuncObject The core of the ufunc is the :ctype:`PyUFuncObject` which contains all the information needed to call the underlying C-code loops that perform the actual work. It has the following structure: .. code-block:: c typedef struct { PyObject_HEAD int nin; int nout; int nargs; int identity; PyUFuncGenericFunction *functions; void **data; int ntypes; int check_return; char *name; char *types; char *doc; void *ptr; PyObject *obj; PyObject *userloops; npy_uint32 *op_flags; npy_uint32 *iter_flags; } PyUFuncObject; .. cmacro:: PyUFuncObject.PyObject_HEAD required for all Python objects. .. cmember:: int PyUFuncObject.nin The number of input arguments. .. cmember:: int PyUFuncObject.nout The number of output arguments. .. cmember:: int PyUFuncObject.nargs The total number of arguments (*nin* + *nout*). This must be less than :cdata:`NPY_MAXARGS`. .. cmember:: int PyUFuncObject.identity Either :cdata:`PyUFunc_One`, :cdata:`PyUFunc_Zero`, or :cdata:`PyUFunc_None` to indicate the identity for this operation. It is only used for a reduce-like call on an empty array. .. cmember:: void PyUFuncObject.functions(char** args, npy_intp* dims, npy_intp* steps, void* extradata) An array of function pointers --- one for each data type supported by the ufunc. This is the vector loop that is called to implement the underlying function *dims* [0] times. The first argument, *args*, is an array of *nargs* pointers to behaved memory. Pointers to the data for the input arguments are first, followed by the pointers to the data for the output arguments. How many bytes must be skipped to get to the next element in the sequence is specified by the corresponding entry in the *steps* array. The last argument allows the loop to receive extra information. This is commonly used so that a single, generic vector loop can be used for multiple functions. In this case, the actual scalar function to call is passed in as *extradata*. The size of this function pointer array is ntypes. .. cmember:: void **PyUFuncObject.data Extra data to be passed to the 1-d vector loops or ``NULL`` if no extra-data is needed. This C-array must be the same size ( *i.e.* ntypes) as the functions array. ``NULL`` is used if extra_data is not needed. Several C-API calls for UFuncs are just 1-d vector loops that make use of this extra data to receive a pointer to the actual function to call. .. cmember:: int PyUFuncObject.ntypes The number of supported data types for the ufunc. This number specifies how many different 1-d loops (of the builtin data types) are available. .. cmember:: int PyUFuncObject.check_return Obsolete and unused. However, it is set by the corresponding entry in the main ufunc creation routine: :cfunc:`PyUFunc_FromFuncAndData` (...). .. cmember:: char *PyUFuncObject.name A string name for the ufunc. This is used dynamically to build the __doc\__ attribute of ufuncs. .. cmember:: char *PyUFuncObject.types An array of *nargs* :math:`\times` *ntypes* 8-bit type_numbers which contains the type signature for the function for each of the supported (builtin) data types. For each of the *ntypes* functions, the corresponding set of type numbers in this array shows how the *args* argument should be interpreted in the 1-d vector loop. These type numbers do not have to be the same type and mixed-type ufuncs are supported. .. cmember:: char *PyUFuncObject.doc Documentation for the ufunc. Should not contain the function signature as this is generated dynamically when __doc\__ is retrieved. .. cmember:: void *PyUFuncObject.ptr Any dynamically allocated memory. Currently, this is used for dynamic ufuncs created from a python function to store room for the types, data, and name members. .. cmember:: PyObject *PyUFuncObject.obj For ufuncs dynamically created from python functions, this member holds a reference to the underlying Python function. .. cmember:: PyObject *PyUFuncObject.userloops A dictionary of user-defined 1-d vector loops (stored as CObject ptrs) for user-defined types. A loop may be registered by the user for any user-defined type. It is retrieved by type number. User defined type numbers are always larger than :cdata:`NPY_USERDEF`. .. cmember:: npy_uint32 PyUFuncObject.op_flags Override the default operand flags for each ufunc operand. .. cmember:: npy_uint32 PyUFuncObject.iter_flags Override the default nditer flags for the ufunc. PyArrayIter_Type ---------------- .. cvar:: PyArrayIter_Type This is an iterator object that makes it easy to loop over an N-dimensional array. It is the object returned from the flat attribute of an ndarray. It is also used extensively throughout the implementation internals to loop over an N-dimensional array. The tp_as_mapping interface is implemented so that the iterator object can be indexed (using 1-d indexing), and a few methods are implemented through the tp_methods table. This object implements the next method and can be used anywhere an iterator can be used in Python. .. ctype:: PyArrayIterObject The C-structure corresponding to an object of :cdata:`PyArrayIter_Type` is the :ctype:`PyArrayIterObject`. The :ctype:`PyArrayIterObject` is used to keep track of a pointer into an N-dimensional array. It contains associated information used to quickly march through the array. The pointer can be adjusted in three basic ways: 1) advance to the "next" position in the array in a C-style contiguous fashion, 2) advance to an arbitrary N-dimensional coordinate in the array, and 3) advance to an arbitrary one-dimensional index into the array. The members of the :ctype:`PyArrayIterObject` structure are used in these calculations. Iterator objects keep their own dimension and strides information about an array. This can be adjusted as needed for "broadcasting," or to loop over only specific dimensions. .. code-block:: c typedef struct { PyObject_HEAD int nd_m1; npy_intp index; npy_intp size; npy_intp coordinates[NPY_MAXDIMS]; npy_intp dims_m1[NPY_MAXDIMS]; npy_intp strides[NPY_MAXDIMS]; npy_intp backstrides[NPY_MAXDIMS]; npy_intp factors[NPY_MAXDIMS]; PyArrayObject *ao; char *dataptr; Bool contiguous; } PyArrayIterObject; .. cmember:: int PyArrayIterObject.nd_m1 :math:`N-1` where :math:`N` is the number of dimensions in the underlying array. .. cmember:: npy_intp PyArrayIterObject.index The current 1-d index into the array. .. cmember:: npy_intp PyArrayIterObject.size The total size of the underlying array. .. cmember:: npy_intp *PyArrayIterObject.coordinates An :math:`N` -dimensional index into the array. .. cmember:: npy_intp *PyArrayIterObject.dims_m1 The size of the array minus 1 in each dimension. .. cmember:: npy_intp *PyArrayIterObject.strides The strides of the array. How many bytes needed to jump to the next element in each dimension. .. cmember:: npy_intp *PyArrayIterObject.backstrides How many bytes needed to jump from the end of a dimension back to its beginning. Note that *backstrides* [k]= *strides* [k]*d *ims_m1* [k], but it is stored here as an optimization. .. cmember:: npy_intp *PyArrayIterObject.factors This array is used in computing an N-d index from a 1-d index. It contains needed products of the dimensions. .. cmember:: PyArrayObject *PyArrayIterObject.ao A pointer to the underlying ndarray this iterator was created to represent. .. cmember:: char *PyArrayIterObject.dataptr This member points to an element in the ndarray indicated by the index. .. cmember:: Bool PyArrayIterObject.contiguous This flag is true if the underlying array is :cdata:`NPY_ARRAY_C_CONTIGUOUS`. It is used to simplify calculations when possible. How to use an array iterator on a C-level is explained more fully in later sections. Typically, you do not need to concern yourself with the internal structure of the iterator object, and merely interact with it through the use of the macros :cfunc:`PyArray_ITER_NEXT` (it), :cfunc:`PyArray_ITER_GOTO` (it, dest), or :cfunc:`PyArray_ITER_GOTO1D` (it, index). All of these macros require the argument *it* to be a :ctype:`PyArrayIterObject *`. PyArrayMultiIter_Type --------------------- .. cvar:: PyArrayMultiIter_Type This type provides an iterator that encapsulates the concept of broadcasting. It allows :math:`N` arrays to be broadcast together so that the loop progresses in C-style contiguous fashion over the broadcasted array. The corresponding C-structure is the :ctype:`PyArrayMultiIterObject` whose memory layout must begin any object, *obj*, passed in to the :cfunc:`PyArray_Broadcast` (obj) function. Broadcasting is performed by adjusting array iterators so that each iterator represents the broadcasted shape and size, but has its strides adjusted so that the correct element from the array is used at each iteration. .. ctype:: PyArrayMultiIterObject .. code-block:: c typedef struct { PyObject_HEAD int numiter; npy_intp size; npy_intp index; int nd; npy_intp dimensions[NPY_MAXDIMS]; PyArrayIterObject *iters[NPY_MAXDIMS]; } PyArrayMultiIterObject; .. cmacro:: PyArrayMultiIterObject.PyObject_HEAD Needed at the start of every Python object (holds reference count and type identification). .. cmember:: int PyArrayMultiIterObject.numiter The number of arrays that need to be broadcast to the same shape. .. cmember:: npy_intp PyArrayMultiIterObject.size The total broadcasted size. .. cmember:: npy_intp PyArrayMultiIterObject.index The current (1-d) index into the broadcasted result. .. cmember:: int PyArrayMultiIterObject.nd The number of dimensions in the broadcasted result. .. cmember:: npy_intp *PyArrayMultiIterObject.dimensions The shape of the broadcasted result (only ``nd`` slots are used). .. cmember:: PyArrayIterObject **PyArrayMultiIterObject.iters An array of iterator objects that holds the iterators for the arrays to be broadcast together. On return, the iterators are adjusted for broadcasting. PyArrayNeighborhoodIter_Type ---------------------------- .. cvar:: PyArrayNeighborhoodIter_Type This is an iterator object that makes it easy to loop over an N-dimensional neighborhood. .. ctype:: PyArrayNeighborhoodIterObject The C-structure corresponding to an object of :cdata:`PyArrayNeighborhoodIter_Type` is the :ctype:`PyArrayNeighborhoodIterObject`. PyArrayFlags_Type ----------------- .. cvar:: PyArrayFlags_Type When the flags attribute is retrieved from Python, a special builtin object of this type is constructed. This special type makes it easier to work with the different flags by accessing them as attributes or by accessing them as if the object were a dictionary with the flag names as entries. ScalarArrayTypes ---------------- There is a Python type for each of the different built-in data types that can be present in the array Most of these are simple wrappers around the corresponding data type in C. The C-names for these types are :cdata:`Py{TYPE}ArrType_Type` where ``{TYPE}`` can be **Bool**, **Byte**, **Short**, **Int**, **Long**, **LongLong**, **UByte**, **UShort**, **UInt**, **ULong**, **ULongLong**, **Half**, **Float**, **Double**, **LongDouble**, **CFloat**, **CDouble**, **CLongDouble**, **String**, **Unicode**, **Void**, and **Object**. These type names are part of the C-API and can therefore be created in extension C-code. There is also a :cdata:`PyIntpArrType_Type` and a :cdata:`PyUIntpArrType_Type` that are simple substitutes for one of the integer types that can hold a pointer on the platform. The structure of these scalar objects is not exposed to C-code. The function :cfunc:`PyArray_ScalarAsCtype` (..) can be used to extract the C-type value from the array scalar and the function :cfunc:`PyArray_Scalar` (...) can be used to construct an array scalar from a C-value. Other C-Structures ================== A few new C-structures were found to be useful in the development of NumPy. These C-structures are used in at least one C-API call and are therefore documented here. The main reason these structures were defined is to make it easy to use the Python ParseTuple C-API to convert from Python objects to a useful C-Object. PyArray_Dims ------------ .. ctype:: PyArray_Dims This structure is very useful when shape and/or strides information is supposed to be interpreted. The structure is: .. code-block:: c typedef struct { npy_intp *ptr; int len; } PyArray_Dims; The members of this structure are .. cmember:: npy_intp *PyArray_Dims.ptr A pointer to a list of (:ctype:`npy_intp`) integers which usually represent array shape or array strides. .. cmember:: int PyArray_Dims.len The length of the list of integers. It is assumed safe to access *ptr* [0] to *ptr* [len-1]. PyArray_Chunk ------------- .. ctype:: PyArray_Chunk This is equivalent to the buffer object structure in Python up to the ptr member. On 32-bit platforms (*i.e.* if :cdata:`NPY_SIZEOF_INT` == :cdata:`NPY_SIZEOF_INTP` ) or in Python 2.5, the len member also matches an equivalent member of the buffer object. It is useful to represent a generic single- segment chunk of memory. .. code-block:: c typedef struct { PyObject_HEAD PyObject *base; void *ptr; npy_intp len; int flags; } PyArray_Chunk; The members are .. cmacro:: PyArray_Chunk.PyObject_HEAD Necessary for all Python objects. Included here so that the :ctype:`PyArray_Chunk` structure matches that of the buffer object (at least to the len member). .. cmember:: PyObject *PyArray_Chunk.base The Python object this chunk of memory comes from. Needed so that memory can be accounted for properly. .. cmember:: void *PyArray_Chunk.ptr A pointer to the start of the single-segment chunk of memory. .. cmember:: npy_intp PyArray_Chunk.len The length of the segment in bytes. .. cmember:: int PyArray_Chunk.flags Any data flags (*e.g.* :cdata:`NPY_ARRAY_WRITEABLE` ) that should be used to interpret the memory. PyArrayInterface ---------------- .. seealso:: :ref:`arrays.interface` .. ctype:: PyArrayInterface The :ctype:`PyArrayInterface` structure is defined so that NumPy and other extension modules can use the rapid array interface protocol. The :obj:`__array_struct__` method of an object that supports the rapid array interface protocol should return a :ctype:`PyCObject` that contains a pointer to a :ctype:`PyArrayInterface` structure with the relevant details of the array. After the new array is created, the attribute should be ``DECREF``'d which will free the :ctype:`PyArrayInterface` structure. Remember to ``INCREF`` the object (whose :obj:`__array_struct__` attribute was retrieved) and point the base member of the new :ctype:`PyArrayObject` to this same object. In this way the memory for the array will be managed correctly. .. code-block:: c typedef struct { int two; int nd; char typekind; int itemsize; int flags; npy_intp *shape; npy_intp *strides; void *data; PyObject *descr; } PyArrayInterface; .. cmember:: int PyArrayInterface.two the integer 2 as a sanity check. .. cmember:: int PyArrayInterface.nd the number of dimensions in the array. .. cmember:: char PyArrayInterface.typekind A character indicating what kind of array is present according to the typestring convention with 't' -> bitfield, 'b' -> Boolean, 'i' -> signed integer, 'u' -> unsigned integer, 'f' -> floating point, 'c' -> complex floating point, 'O' -> object, 'S' -> string, 'U' -> unicode, 'V' -> void. .. cmember:: int PyArrayInterface.itemsize The number of bytes each item in the array requires. .. cmember:: int PyArrayInterface.flags Any of the bits :cdata:`NPY_ARRAY_C_CONTIGUOUS` (1), :cdata:`NPY_ARRAY_F_CONTIGUOUS` (2), :cdata:`NPY_ARRAY_ALIGNED` (0x100), :cdata:`NPY_ARRAY_NOTSWAPPED` (0x200), or :cdata:`NPY_ARRAY_WRITEABLE` (0x400) to indicate something about the data. The :cdata:`NPY_ARRAY_ALIGNED`, :cdata:`NPY_ARRAY_C_CONTIGUOUS`, and :cdata:`NPY_ARRAY_F_CONTIGUOUS` flags can actually be determined from the other parameters. The flag :cdata:`NPY_ARR_HAS_DESCR` (0x800) can also be set to indicate to objects consuming the version 3 array interface that the descr member of the structure is present (it will be ignored by objects consuming version 2 of the array interface). .. cmember:: npy_intp *PyArrayInterface.shape An array containing the size of the array in each dimension. .. cmember:: npy_intp *PyArrayInterface.strides An array containing the number of bytes to jump to get to the next element in each dimension. .. cmember:: void *PyArrayInterface.data A pointer *to* the first element of the array. .. cmember:: PyObject *PyArrayInterface.descr A Python object describing the data-type in more detail (same as the *descr* key in :obj:`__array_interface__`). This can be ``NULL`` if *typekind* and *itemsize* provide enough information. This field is also ignored unless :cdata:`ARR_HAS_DESCR` flag is on in *flags*. Internally used structures -------------------------- Internally, the code uses some additional Python objects primarily for memory management. These types are not accessible directly from Python, and are not exposed to the C-API. They are included here only for completeness and assistance in understanding the code. .. ctype:: PyUFuncLoopObject A loose wrapper for a C-structure that contains the information needed for looping. This is useful if you are trying to understand the ufunc looping code. The :ctype:`PyUFuncLoopObject` is the associated C-structure. It is defined in the ``ufuncobject.h`` header. .. ctype:: PyUFuncReduceObject A loose wrapper for the C-structure that contains the information needed for reduce-like methods of ufuncs. This is useful if you are trying to understand the reduce, accumulate, and reduce-at code. The :ctype:`PyUFuncReduceObject` is the associated C-structure. It is defined in the ``ufuncobject.h`` header. .. ctype:: PyUFunc_Loop1d A simple linked-list of C-structures containing the information needed to define a 1-d loop for a ufunc for every defined signature of a user-defined data-type. .. cvar:: PyArrayMapIter_Type Advanced indexing is handled with this Python type. It is simply a loose wrapper around the C-structure containing the variables needed for advanced array indexing. The associated C-structure, :ctype:`PyArrayMapIterObject`, is useful if you are trying to understand the advanced-index mapping code. It is defined in the ``arrayobject.h`` header. This type is not exposed to Python and could be replaced with a C-structure. As a Python type it takes advantage of reference- counted memory management. numpy-1.8.2/doc/source/reference/c-api.rst0000664000175100017510000000332512370216242021554 0ustar vagrantvagrant00000000000000.. _c-api: ########### Numpy C-API ########### .. sectionauthor:: Travis E. Oliphant | Beware of the man who won't be bothered with details. | --- *William Feather, Sr.* | The truth is out there. | --- *Chris Carter, The X Files* NumPy provides a C-API to enable users to extend the system and get access to the array object for use in other routines. The best way to truly understand the C-API is to read the source code. If you are unfamiliar with (C) source code, however, this can be a daunting experience at first. Be assured that the task becomes easier with practice, and you may be surprised at how simple the C-code can be to understand. Even if you don't think you can write C-code from scratch, it is much easier to understand and modify already-written source code then create it *de novo*. Python extensions are especially straightforward to understand because they all have a very similar structure. Admittedly, NumPy is not a trivial extension to Python, and may take a little more snooping to grasp. This is especially true because of the code-generation techniques, which simplify maintenance of very similar code, but can make the code a little less readable to beginners. Still, with a little persistence, the code can be opened to your understanding. It is my hope, that this guide to the C-API can assist in the process of becoming familiar with the compiled-level work that can be done with NumPy in order to squeeze that last bit of necessary speed out of your code. .. currentmodule:: numpy-c-api .. toctree:: :maxdepth: 2 c-api.types-and-structures c-api.config c-api.dtype c-api.array c-api.iterator c-api.ufunc c-api.generalized-ufuncs c-api.coremath c-api.deprecations numpy-1.8.2/doc/source/reference/routines.logic.rst0000664000175100017510000000145512370216242023531 0ustar vagrantvagrant00000000000000Logic functions *************** .. currentmodule:: numpy Truth value testing ------------------- .. autosummary:: :toctree: generated/ all any Array contents -------------- .. autosummary:: :toctree: generated/ isfinite isinf isnan isneginf isposinf Array type testing ------------------ .. autosummary:: :toctree: generated/ iscomplex iscomplexobj isfortran isreal isrealobj isscalar Logical operations ------------------ .. autosummary:: :toctree: generated/ logical_and logical_or logical_not logical_xor Comparison ---------- .. autosummary:: :toctree: generated/ allclose isclose array_equal array_equiv .. autosummary:: :toctree: generated/ greater greater_equal less less_equal equal not_equal numpy-1.8.2/doc/source/reference/routines.ma.rst0000664000175100017510000001274012370216243023031 0ustar vagrantvagrant00000000000000.. _routines.ma: Masked array operations *********************** .. currentmodule:: numpy Constants ========= .. autosummary:: :toctree: generated/ ma.MaskType Creation ======== From existing data ~~~~~~~~~~~~~~~~~~ .. autosummary:: :toctree: generated/ ma.masked_array ma.array ma.copy ma.frombuffer ma.fromfunction ma.MaskedArray.copy Ones and zeros ~~~~~~~~~~~~~~ .. autosummary:: :toctree: generated/ ma.empty ma.empty_like ma.masked_all ma.masked_all_like ma.ones ma.zeros _____ Inspecting the array ==================== .. autosummary:: :toctree: generated/ ma.all ma.any ma.count ma.count_masked ma.getmask ma.getmaskarray ma.getdata ma.nonzero ma.shape ma.size ma.MaskedArray.data ma.MaskedArray.mask ma.MaskedArray.recordmask ma.MaskedArray.all ma.MaskedArray.any ma.MaskedArray.count ma.MaskedArray.nonzero ma.shape ma.size _____ Manipulating a MaskedArray ========================== Changing the shape ~~~~~~~~~~~~~~~~~~ .. autosummary:: :toctree: generated/ ma.ravel ma.reshape ma.resize ma.MaskedArray.flatten ma.MaskedArray.ravel ma.MaskedArray.reshape ma.MaskedArray.resize Modifying axes ~~~~~~~~~~~~~~ .. autosummary:: :toctree: generated/ ma.swapaxes ma.transpose ma.MaskedArray.swapaxes ma.MaskedArray.transpose Changing the number of dimensions ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .. autosummary:: :toctree: generated/ ma.atleast_1d ma.atleast_2d ma.atleast_3d ma.expand_dims ma.squeeze ma.MaskedArray.squeeze ma.column_stack ma.concatenate ma.dstack ma.hstack ma.hsplit ma.mr_ ma.row_stack ma.vstack Joining arrays ~~~~~~~~~~~~~~ .. autosummary:: :toctree: generated/ ma.column_stack ma.concatenate ma.dstack ma.hstack ma.vstack _____ Operations on masks =================== Creating a mask ~~~~~~~~~~~~~~~ .. autosummary:: :toctree: generated/ ma.make_mask ma.make_mask_none ma.mask_or ma.make_mask_descr Accessing a mask ~~~~~~~~~~~~~~~~ .. autosummary:: :toctree: generated/ ma.getmask ma.getmaskarray ma.masked_array.mask Finding masked data ~~~~~~~~~~~~~~~~~~~ .. autosummary:: :toctree: generated/ ma.flatnotmasked_contiguous ma.flatnotmasked_edges ma.notmasked_contiguous ma.notmasked_edges Modifying a mask ~~~~~~~~~~~~~~~~ .. autosummary:: :toctree: generated/ ma.mask_cols ma.mask_or ma.mask_rowcols ma.mask_rows ma.harden_mask ma.soften_mask ma.MaskedArray.harden_mask ma.MaskedArray.soften_mask ma.MaskedArray.shrink_mask ma.MaskedArray.unshare_mask _____ Conversion operations ====================== > to a masked array ~~~~~~~~~~~~~~~~~~~ .. autosummary:: :toctree: generated/ ma.asarray ma.asanyarray ma.fix_invalid ma.masked_equal ma.masked_greater ma.masked_greater_equal ma.masked_inside ma.masked_invalid ma.masked_less ma.masked_less_equal ma.masked_not_equal ma.masked_object ma.masked_outside ma.masked_values ma.masked_where > to a ndarray ~~~~~~~~~~~~~~ .. autosummary:: :toctree: generated/ ma.compress_cols ma.compress_rowcols ma.compress_rows ma.compressed ma.filled ma.MaskedArray.compressed ma.MaskedArray.filled > to another object ~~~~~~~~~~~~~~~~~~~ .. autosummary:: :toctree: generated/ ma.MaskedArray.tofile ma.MaskedArray.tolist ma.MaskedArray.torecords ma.MaskedArray.tostring Pickling and unpickling ~~~~~~~~~~~~~~~~~~~~~~~ .. autosummary:: :toctree: generated/ ma.dump ma.dumps ma.load ma.loads Filling a masked array ~~~~~~~~~~~~~~~~~~~~~~ .. autosummary:: :toctree: generated/ ma.common_fill_value ma.default_fill_value ma.maximum_fill_value ma.maximum_fill_value ma.set_fill_value ma.MaskedArray.get_fill_value ma.MaskedArray.set_fill_value ma.MaskedArray.fill_value _____ Masked arrays arithmetics ========================= Arithmetics ~~~~~~~~~~~ .. autosummary:: :toctree: generated/ ma.anom ma.anomalies ma.average ma.conjugate ma.corrcoef ma.cov ma.cumsum ma.cumprod ma.mean ma.median ma.power ma.prod ma.std ma.sum ma.var ma.MaskedArray.anom ma.MaskedArray.cumprod ma.MaskedArray.cumsum ma.MaskedArray.mean ma.MaskedArray.prod ma.MaskedArray.std ma.MaskedArray.sum ma.MaskedArray.var Minimum/maximum ~~~~~~~~~~~~~~~ .. autosummary:: :toctree: generated/ ma.argmax ma.argmin ma.max ma.min ma.ptp ma.MaskedArray.argmax ma.MaskedArray.argmin ma.MaskedArray.max ma.MaskedArray.min ma.MaskedArray.ptp Sorting ~~~~~~~ .. autosummary:: :toctree: generated/ ma.argsort ma.sort ma.MaskedArray.argsort ma.MaskedArray.sort Algebra ~~~~~~~ .. autosummary:: :toctree: generated/ ma.diag ma.dot ma.identity ma.inner ma.innerproduct ma.outer ma.outerproduct ma.trace ma.transpose ma.MaskedArray.trace ma.MaskedArray.transpose Polynomial fit ~~~~~~~~~~~~~~ .. autosummary:: :toctree: generated/ ma.vander ma.polyfit Clipping and rounding ~~~~~~~~~~~~~~~~~~~~~ .. autosummary:: :toctree: generated/ ma.around ma.clip ma.round ma.MaskedArray.clip ma.MaskedArray.round Miscellanea ~~~~~~~~~~~ .. autosummary:: :toctree: generated/ ma.allequal ma.allclose ma.apply_along_axis ma.arange ma.choose ma.ediff1d ma.indices ma.where numpy-1.8.2/doc/source/reference/routines.array-manipulation.rst0000664000175100017510000000272312370216243026250 0ustar vagrantvagrant00000000000000Array manipulation routines *************************** .. currentmodule:: numpy Basic operations ================ .. autosummary:: :toctree: generated/ copyto Changing array shape ==================== .. autosummary:: :toctree: generated/ reshape ravel ndarray.flat ndarray.flatten Transpose-like operations ========================= .. autosummary:: :toctree: generated/ rollaxis swapaxes ndarray.T transpose Changing number of dimensions ============================= .. autosummary:: :toctree: generated/ atleast_1d atleast_2d atleast_3d broadcast broadcast_arrays expand_dims squeeze Changing kind of array ====================== .. autosummary:: :toctree: generated/ asarray asanyarray asmatrix asfarray asfortranarray asscalar require Joining arrays ============== .. autosummary:: :toctree: generated/ column_stack concatenate dstack hstack vstack Splitting arrays ================ .. autosummary:: :toctree: generated/ array_split dsplit hsplit split vsplit Tiling arrays ============= .. autosummary:: :toctree: generated/ tile repeat Adding and removing elements ============================ .. autosummary:: :toctree: generated/ delete insert append resize trim_zeros unique Rearranging elements ==================== .. autosummary:: :toctree: generated/ fliplr flipud reshape roll rot90 numpy-1.8.2/doc/source/reference/swig.testing.rst0000664000175100017510000001446512370216242023217 0ustar vagrantvagrant00000000000000Testing the numpy.i Typemaps ============================ Introduction ------------ Writing tests for the ``numpy.i`` `SWIG `_ interface file is a combinatorial headache. At present, 12 different data types are supported, each with 74 different argument signatures, for a total of 888 typemaps supported "out of the box". Each of these typemaps, in turn, might require several unit tests in order to verify expected behavior for both proper and improper inputs. Currently, this results in 1,427 individual unit tests that are performed when ``make test`` is run in the ``numpy/docs/swig`` subdirectory. To facilitate this many similar unit tests, some high-level programming techniques are employed, including C and `SWIG`_ macros, as well as Python inheritance. The purpose of this document is to describe the testing infrastructure employed to verify that the ``numpy.i`` typemaps are working as expected. Testing Organization -------------------- There are three indepedent testing frameworks supported, for one-, two-, and three-dimensional arrays respectively. For one-dimensional arrays, there are two C++ files, a header and a source, named:: Vector.h Vector.cxx that contain prototypes and code for a variety of functions that have one-dimensional arrays as function arguments. The file:: Vector.i is a `SWIG`_ interface file that defines a python module ``Vector`` that wraps the functions in ``Vector.h`` while utilizing the typemaps in ``numpy.i`` to correctly handle the C arrays. The ``Makefile`` calls ``swig`` to generate ``Vector.py`` and ``Vector_wrap.cxx``, and also executes the ``setup.py`` script that compiles ``Vector_wrap.cxx`` and links together the extension module ``_Vector.so`` or ``_Vector.dylib``, depending on the platform. This extension module and the proxy file ``Vector.py`` are both placed in a subdirectory under the ``build`` directory. The actual testing takes place with a Python script named:: testVector.py that uses the standard Python library module ``unittest``, which performs several tests of each function defined in ``Vector.h`` for each data type supported. Two-dimensional arrays are tested in exactly the same manner. The above description applies, but with ``Matrix`` substituted for ``Vector``. For three-dimensional tests, substitute ``Tensor`` for ``Vector``. For four-dimensional tests, substitute ``SuperTensor`` for ``Vector``. For the descriptions that follow, we will reference the ``Vector`` tests, but the same information applies to ``Matrix``, ``Tensor`` and ``SuperTensor`` tests. The command ``make test`` will ensure that all of the test software is built and then run all three test scripts. Testing Header Files -------------------- ``Vector.h`` is a C++ header file that defines a C macro called ``TEST_FUNC_PROTOS`` that takes two arguments: ``TYPE``, which is a data type name such as ``unsigned int``; and ``SNAME``, which is a short name for the same data type with no spaces, e.g. ``uint``. This macro defines several function prototypes that have the prefix ``SNAME`` and have at least one argument that is an array of type ``TYPE``. Those functions that have return arguments return a ``TYPE`` value. ``TEST_FUNC_PROTOS`` is then implemented for all of the data types supported by ``numpy.i``: * ``signed char`` * ``unsigned char`` * ``short`` * ``unsigned short`` * ``int`` * ``unsigned int`` * ``long`` * ``unsigned long`` * ``long long`` * ``unsigned long long`` * ``float`` * ``double`` Testing Source Files -------------------- ``Vector.cxx`` is a C++ source file that implements compilable code for each of the function prototypes specified in ``Vector.h``. It defines a C macro ``TEST_FUNCS`` that has the same arguments and works in the same way as ``TEST_FUNC_PROTOS`` does in ``Vector.h``. ``TEST_FUNCS`` is implemented for each of the 12 data types as above. Testing SWIG Interface Files ---------------------------- ``Vector.i`` is a `SWIG`_ interface file that defines python module ``Vector``. It follows the conventions for using ``numpy.i`` as described in this chapter. It defines a `SWIG`_ macro ``%apply_numpy_typemaps`` that has a single argument ``TYPE``. It uses the `SWIG`_ directive ``%apply`` to apply the provided typemaps to the argument signatures found in ``Vector.h``. This macro is then implemented for all of the data types supported by ``numpy.i``. It then does a ``%include "Vector.h"`` to wrap all of the function prototypes in ``Vector.h`` using the typemaps in ``numpy.i``. Testing Python Scripts ---------------------- After ``make`` is used to build the testing extension modules, ``testVector.py`` can be run to execute the tests. As with other scripts that use ``unittest`` to facilitate unit testing, ``testVector.py`` defines a class that inherits from ``unittest.TestCase``:: class VectorTestCase(unittest.TestCase): However, this class is not run directly. Rather, it serves as a base class to several other python classes, each one specific to a particular data type. The ``VectorTestCase`` class stores two strings for typing information: **self.typeStr** A string that matches one of the ``SNAME`` prefixes used in ``Vector.h`` and ``Vector.cxx``. For example, ``"double"``. **self.typeCode** A short (typically single-character) string that represents a data type in numpy and corresponds to ``self.typeStr``. For example, if ``self.typeStr`` is ``"double"``, then ``self.typeCode`` should be ``"d"``. Each test defined by the ``VectorTestCase`` class extracts the python function it is trying to test by accessing the ``Vector`` module's dictionary:: length = Vector.__dict__[self.typeStr + "Length"] In the case of double precision tests, this will return the python function ``Vector.doubleLength``. We then define a new test case class for each supported data type with a short definition such as:: class doubleTestCase(VectorTestCase): def __init__(self, methodName="runTest"): VectorTestCase.__init__(self, methodName) self.typeStr = "double" self.typeCode = "d" Each of these 12 classes is collected into a ``unittest.TestSuite``, which is then executed. Errors and failures are summed together and returned as the exit argument. Any non-zero result indicates that at least one test did not pass. numpy-1.8.2/doc/source/reference/internals.code-explanations.rst0000664000175100017510000007613312370216242026205 0ustar vagrantvagrant00000000000000.. currentmodule:: numpy ************************* Numpy C Code Explanations ************************* Fanaticism consists of redoubling your efforts when you have forgotten your aim. --- *George Santayana* An authority is a person who can tell you more about something than you really care to know. --- *Unknown* This Chapter attempts to explain the logic behind some of the new pieces of code. The purpose behind these explanations is to enable somebody to be able to understand the ideas behind the implementation somewhat more easily than just staring at the code. Perhaps in this way, the algorithms can be improved on, borrowed from, and/or optimized. Memory model ============ .. index:: pair: ndarray; memory model One fundamental aspect of the ndarray is that an array is seen as a "chunk" of memory starting at some location. The interpretation of this memory depends on the stride information. For each dimension in an :math:`N` -dimensional array, an integer (stride) dictates how many bytes must be skipped to get to the next element in that dimension. Unless you have a single-segment array, this stride information must be consulted when traversing through an array. It is not difficult to write code that accepts strides, you just have to use (char \*) pointers because strides are in units of bytes. Keep in mind also that strides do not have to be unit-multiples of the element size. Also, remember that if the number of dimensions of the array is 0 (sometimes called a rank-0 array), then the strides and dimensions variables are NULL. Besides the structural information contained in the strides and dimensions members of the :ctype:`PyArrayObject`, the flags contain important information about how the data may be accessed. In particular, the :cdata:`NPY_ARRAY_ALIGNED` flag is set when the memory is on a suitable boundary according to the data-type array. Even if you have a contiguous chunk of memory, you cannot just assume it is safe to dereference a data- type-specific pointer to an element. Only if the :cdata:`NPY_ARRAY_ALIGNED` flag is set is this a safe operation (on some platforms it will work but on others, like Solaris, it will cause a bus error). The :cdata:`NPY_ARRAY_WRITEABLE` should also be ensured if you plan on writing to the memory area of the array. It is also possible to obtain a pointer to an unwriteable memory area. Sometimes, writing to the memory area when the :cdata:`NPY_ARRAY_WRITEABLE` flag is not set will just be rude. Other times it can cause program crashes ( *e.g.* a data-area that is a read-only memory-mapped file). Data-type encapsulation ======================= .. index:: single: dtype The data-type is an important abstraction of the ndarray. Operations will look to the data-type to provide the key functionality that is needed to operate on the array. This functionality is provided in the list of function pointers pointed to by the 'f' member of the :ctype:`PyArray_Descr` structure. In this way, the number of data-types can be extended simply by providing a :ctype:`PyArray_Descr` structure with suitable function pointers in the 'f' member. For built-in types there are some optimizations that by-pass this mechanism, but the point of the data- type abstraction is to allow new data-types to be added. One of the built-in data-types, the void data-type allows for arbitrary records containing 1 or more fields as elements of the array. A field is simply another data-type object along with an offset into the current record. In order to support arbitrarily nested fields, several recursive implementations of data-type access are implemented for the void type. A common idiom is to cycle through the elements of the dictionary and perform a specific operation based on the data-type object stored at the given offset. These offsets can be arbitrary numbers. Therefore, the possibility of encountering mis- aligned data must be recognized and taken into account if necessary. N-D Iterators ============= .. index:: single: array iterator A very common operation in much of NumPy code is the need to iterate over all the elements of a general, strided, N-dimensional array. This operation of a general-purpose N-dimensional loop is abstracted in the notion of an iterator object. To write an N-dimensional loop, you only have to create an iterator object from an ndarray, work with the dataptr member of the iterator object structure and call the macro :cfunc:`PyArray_ITER_NEXT` (it) on the iterator object to move to the next element. The "next" element is always in C-contiguous order. The macro works by first special casing the C-contiguous, 1-D, and 2-D cases which work very simply. For the general case, the iteration works by keeping track of a list of coordinate counters in the iterator object. At each iteration, the last coordinate counter is increased (starting from 0). If this counter is smaller then one less than the size of the array in that dimension (a pre-computed and stored value), then the counter is increased and the dataptr member is increased by the strides in that dimension and the macro ends. If the end of a dimension is reached, the counter for the last dimension is reset to zero and the dataptr is moved back to the beginning of that dimension by subtracting the strides value times one less than the number of elements in that dimension (this is also pre-computed and stored in the backstrides member of the iterator object). In this case, the macro does not end, but a local dimension counter is decremented so that the next-to-last dimension replaces the role that the last dimension played and the previously-described tests are executed again on the next-to-last dimension. In this way, the dataptr is adjusted appropriately for arbitrary striding. The coordinates member of the :ctype:`PyArrayIterObject` structure maintains the current N-d counter unless the underlying array is C-contiguous in which case the coordinate counting is by-passed. The index member of the :ctype:`PyArrayIterObject` keeps track of the current flat index of the iterator. It is updated by the :cfunc:`PyArray_ITER_NEXT` macro. Broadcasting ============ .. index:: single: broadcasting In Numeric, broadcasting was implemented in several lines of code buried deep in ufuncobject.c. In NumPy, the notion of broadcasting has been abstracted so that it can be performed in multiple places. Broadcasting is handled by the function :cfunc:`PyArray_Broadcast`. This function requires a :ctype:`PyArrayMultiIterObject` (or something that is a binary equivalent) to be passed in. The :ctype:`PyArrayMultiIterObject` keeps track of the broadcasted number of dimensions and size in each dimension along with the total size of the broadcasted result. It also keeps track of the number of arrays being broadcast and a pointer to an iterator for each of the arrays being broadcasted. The :cfunc:`PyArray_Broadcast` function takes the iterators that have already been defined and uses them to determine the broadcast shape in each dimension (to create the iterators at the same time that broadcasting occurs then use the :cfunc:`PyMultiIter_New` function). Then, the iterators are adjusted so that each iterator thinks it is iterating over an array with the broadcasted size. This is done by adjusting the iterators number of dimensions, and the shape in each dimension. This works because the iterator strides are also adjusted. Broadcasting only adjusts (or adds) length-1 dimensions. For these dimensions, the strides variable is simply set to 0 so that the data-pointer for the iterator over that array doesn't move as the broadcasting operation operates over the extended dimension. Broadcasting was always implemented in Numeric using 0-valued strides for the extended dimensions. It is done in exactly the same way in NumPy. The big difference is that now the array of strides is kept track of in a :ctype:`PyArrayIterObject`, the iterators involved in a broadcasted result are kept track of in a :ctype:`PyArrayMultiIterObject`, and the :cfunc:`PyArray_BroadCast` call implements the broad-casting rules. Array Scalars ============= .. index:: single: array scalars The array scalars offer a hierarchy of Python types that allow a one- to-one correspondence between the data-type stored in an array and the Python-type that is returned when an element is extracted from the array. An exception to this rule was made with object arrays. Object arrays are heterogeneous collections of arbitrary Python objects. When you select an item from an object array, you get back the original Python object (and not an object array scalar which does exist but is rarely used for practical purposes). The array scalars also offer the same methods and attributes as arrays with the intent that the same code can be used to support arbitrary dimensions (including 0-dimensions). The array scalars are read-only (immutable) with the exception of the void scalar which can also be written to so that record-array field setting works more naturally (a[0]['f1'] = ``value`` ). Advanced ("Fancy") Indexing ============================= .. index:: single: indexing The implementation of advanced indexing represents some of the most difficult code to write and explain. In fact, there are two implementations of advanced indexing. The first works only with 1-D arrays and is implemented to handle expressions involving a.flat[obj]. The second is general-purpose that works for arrays of "arbitrary dimension" (up to a fixed maximum). The one-dimensional indexing approaches were implemented in a rather straightforward fashion, and so it is the general-purpose indexing code that will be the focus of this section. There is a multi-layer approach to indexing because the indexing code can at times return an array scalar and at other times return an array. The functions with "_nice" appended to their name do this special handling while the function without the _nice appendage always return an array (perhaps a 0-dimensional array). Some special-case optimizations (the index being an integer scalar, and the index being a tuple with as many dimensions as the array) are handled in array_subscript_nice function which is what Python calls when presented with the code "a[obj]." These optimizations allow fast single-integer indexing, and also ensure that a 0-dimensional array is not created only to be discarded as the array scalar is returned instead. This provides significant speed-up for code that is selecting many scalars out of an array (such as in a loop). However, it is still not faster than simply using a list to store standard Python scalars, because that is optimized by the Python interpreter itself. After these optimizations, the array_subscript function itself is called. This function first checks for field selection which occurs when a string is passed as the indexing object. Then, 0-D arrays are given special-case consideration. Finally, the code determines whether or not advanced, or fancy, indexing needs to be performed. If fancy indexing is not needed, then standard view-based indexing is performed using code borrowed from Numeric which parses the indexing object and returns the offset into the data-buffer and the dimensions necessary to create a new view of the array. The strides are also changed by multiplying each stride by the step-size requested along the corresponding dimension. Fancy-indexing check -------------------- The fancy_indexing_check routine determines whether or not to use standard view-based indexing or new copy-based indexing. If the indexing object is a tuple, then view-based indexing is assumed by default. Only if the tuple contains an array object or a sequence object is fancy-indexing assumed. If the indexing object is an array, then fancy indexing is automatically assumed. If the indexing object is any other kind of sequence, then fancy-indexing is assumed by default. This is over-ridden to simple indexing if the sequence contains any slice, newaxis, or Ellipsis objects, and no arrays or additional sequences are also contained in the sequence. The purpose of this is to allow the construction of "slicing" sequences which is a common technique for building up code that works in arbitrary numbers of dimensions. Fancy-indexing implementation ----------------------------- The concept of indexing was also abstracted using the idea of an iterator. If fancy indexing is performed, then a :ctype:`PyArrayMapIterObject` is created. This internal object is not exposed to Python. It is created in order to handle the fancy-indexing at a high-level. Both get and set fancy-indexing operations are implemented using this object. Fancy indexing is abstracted into three separate operations: (1) creating the :ctype:`PyArrayMapIterObject` from the indexing object, (2) binding the :ctype:`PyArrayMapIterObject` to the array being indexed, and (3) getting (or setting) the items determined by the indexing object. There is an optimization implemented so that the :ctype:`PyArrayIterObject` (which has it's own less complicated fancy-indexing) is used for indexing when possible. Creating the mapping object ^^^^^^^^^^^^^^^^^^^^^^^^^^^ The first step is to convert the indexing objects into a standard form where iterators are created for all of the index array inputs and all Boolean arrays are converted to equivalent integer index arrays (as if nonzero(arr) had been called). Finally, all integer arrays are replaced with the integer 0 in the indexing object and all of the index-array iterators are "broadcast" to the same shape. Binding the mapping object ^^^^^^^^^^^^^^^^^^^^^^^^^^ When the mapping object is created it does not know which array it will be used with so once the index iterators are constructed during mapping-object creation, the next step is to associate these iterators with a particular ndarray. This process interprets any ellipsis and slice objects so that the index arrays are associated with the appropriate axis (the axis indicated by the iteraxis entry corresponding to the iterator for the integer index array). This information is then used to check the indices to be sure they are within range of the shape of the array being indexed. The presence of ellipsis and/or slice objects implies a sub-space iteration that is accomplished by extracting a sub-space view of the array (using the index object resulting from replacing all the integer index arrays with 0) and storing the information about where this sub-space starts in the mapping object. This is used later during mapping-object iteration to select the correct elements from the underlying array. Getting (or Setting) ^^^^^^^^^^^^^^^^^^^^ After the mapping object is successfully bound to a particular array, the mapping object contains the shape of the resulting item as well as iterator objects that will walk through the currently-bound array and either get or set its elements as needed. The walk is implemented using the :cfunc:`PyArray_MapIterNext` function. This function sets the coordinates of an iterator object into the current array to be the next coordinate location indicated by all of the indexing-object iterators while adjusting, if necessary, for the presence of a sub- space. The result of this function is that the dataptr member of the mapping object structure is pointed to the next position in the array that needs to be copied out or set to some value. When advanced indexing is used to extract an array, an iterator for the new array is constructed and advanced in phase with the mapping object iterator. When advanced indexing is used to place values in an array, a special "broadcasted" iterator is constructed from the object being placed into the array so that it will only work if the values used for setting have a shape that is "broadcastable" to the shape implied by the indexing object. Universal Functions =================== .. index:: single: ufunc Universal functions are callable objects that take :math:`N` inputs and produce :math:`M` outputs by wrapping basic 1-D loops that work element-by-element into full easy-to use functions that seamlessly implement broadcasting, type-checking and buffered coercion, and output-argument handling. New universal functions are normally created in C, although there is a mechanism for creating ufuncs from Python functions (:func:`frompyfunc`). The user must supply a 1-D loop that implements the basic function taking the input scalar values and placing the resulting scalars into the appropriate output slots as explaine n implementation. Setup ----- Every ufunc calculation involves some overhead related to setting up the calculation. The practical significance of this overhead is that even though the actual calculation of the ufunc is very fast, you will be able to write array and type-specific code that will work faster for small arrays than the ufunc. In particular, using ufuncs to perform many calculations on 0-D arrays will be slower than other Python-based solutions (the silently-imported scalarmath module exists precisely to give array scalars the look-and-feel of ufunc-based calculations with significantly reduced overhead). When a ufunc is called, many things must be done. The information collected from these setup operations is stored in a loop-object. This loop object is a C-structure (that could become a Python object but is not initialized as such because it is only used internally). This loop object has the layout needed to be used with PyArray_Broadcast so that the broadcasting can be handled in the same way as it is handled in other sections of code. The first thing done is to look-up in the thread-specific global dictionary the current values for the buffer-size, the error mask, and the associated error object. The state of the error mask controls what happens when an error-condiction is found. It should be noted that checking of the hardware error flags is only performed after each 1-D loop is executed. This means that if the input and output arrays are contiguous and of the correct type so that a single 1-D loop is performed, then the flags may not be checked until all elements of the array have been calcluated. Looking up these values in a thread- specific dictionary takes time which is easily ignored for all but very small arrays. After checking, the thread-specific global variables, the inputs are evaluated to determine how the ufunc should proceed and the input and output arrays are constructed if necessary. Any inputs which are not arrays are converted to arrays (using context if necessary). Which of the inputs are scalars (and therefore converted to 0-D arrays) is noted. Next, an appropriate 1-D loop is selected from the 1-D loops available to the ufunc based on the input array types. This 1-D loop is selected by trying to match the signature of the data-types of the inputs against the available signatures. The signatures corresponding to built-in types are stored in the types member of the ufunc structure. The signatures corresponding to user-defined types are stored in a linked-list of function-information with the head element stored as a ``CObject`` in the userloops dictionary keyed by the data-type number (the first user-defined type in the argument list is used as the key). The signatures are searched until a signature is found to which the input arrays can all be cast safely (ignoring any scalar arguments which are not allowed to determine the type of the result). The implication of this search procedure is that "lesser types" should be placed below "larger types" when the signatures are stored. If no 1-D loop is found, then an error is reported. Otherwise, the argument_list is updated with the stored signature --- in case casting is necessary and to fix the output types assumed by the 1-D loop. If the ufunc has 2 inputs and 1 output and the second input is an Object array then a special-case check is performed so that NotImplemented is returned if the second input is not an ndarray, has the __array_priority\__ attribute, and has an __r{op}\__ special method. In this way, Python is signaled to give the other object a chance to complete the operation instead of using generic object-array calculations. This allows (for example) sparse matrices to override the multiplication operator 1-D loop. For input arrays that are smaller than the specified buffer size, copies are made of all non-contiguous, mis-aligned, or out-of- byteorder arrays to ensure that for small arrays, a single-loop is used. Then, array iterators are created for all the input arrays and the resulting collection of iterators is broadcast to a single shape. The output arguments (if any) are then processed and any missing return arrays are constructed. If any provided output array doesn't have the correct type (or is mis-aligned) and is smaller than the buffer size, then a new output array is constructed with the special UPDATEIFCOPY flag set so that when it is DECREF'd on completion of the function, it's contents will be copied back into the output array. Iterators for the output arguments are then processed. Finally, the decision is made about how to execute the looping mechanism to ensure that all elements of the input arrays are combined to produce the output arrays of the correct type. The options for loop execution are one-loop (for contiguous, aligned, and correct data- type), strided-loop (for non-contiguous but still aligned and correct data-type), and a buffered loop (for mis-aligned or incorrect data- type situations). Depending on which execution method is called for, the loop is then setup and computed. Function call ------------- This section describes how the basic universal function computation loop is setup and executed for each of the three different kinds of execution possibilities. If :cdata:`NPY_ALLOW_THREADS` is defined during compilation, then the Python Global Interpreter Lock (GIL) is released prior to calling all of these loops (as long as they don't involve object arrays). It is re-acquired if necessary to handle error conditions. The hardware error flags are checked only after the 1-D loop is calcluated. One Loop ^^^^^^^^ This is the simplest case of all. The ufunc is executed by calling the underlying 1-D loop exactly once. This is possible only when we have aligned data of the correct type (including byte-order) for both input and output and all arrays have uniform strides (either contiguous, 0-D, or 1-D). In this case, the 1-D computational loop is called once to compute the calculation for the entire array. Note that the hardware error flags are only checked after the entire calculation is complete. Strided Loop ^^^^^^^^^^^^ When the input and output arrays are aligned and of the correct type, but the striding is not uniform (non-contiguous and 2-D or larger), then a second looping structure is employed for the calculation. This approach converts all of the iterators for the input and output arguments to iterate over all but the largest dimension. The inner loop is then handled by the underlying 1-D computational loop. The outer loop is a standard iterator loop on the converted iterators. The hardware error flags are checked after each 1-D loop is completed. Buffered Loop ^^^^^^^^^^^^^ This is the code that handles the situation whenever the input and/or output arrays are either misaligned or of the wrong data-type (including being byte-swapped) from what the underlying 1-D loop expects. The arrays are also assumed to be non-contiguous. The code works very much like the strided loop except for the inner 1-D loop is modified so that pre-processing is performed on the inputs and post- processing is performed on the outputs in bufsize chunks (where bufsize is a user-settable parameter). The underlying 1-D computational loop is called on data that is copied over (if it needs to be). The setup code and the loop code is considerably more complicated in this case because it has to handle: - memory allocation of the temporary buffers - deciding whether or not to use buffers on the input and output data (mis-aligned and/or wrong data-type) - copying and possibly casting data for any inputs or outputs for which buffers are necessary. - special-casing Object arrays so that reference counts are properly handled when copies and/or casts are necessary. - breaking up the inner 1-D loop into bufsize chunks (with a possible remainder). Again, the hardware error flags are checked at the end of each 1-D loop. Final output manipulation ------------------------- Ufuncs allow other array-like classes to be passed seamlessly through the interface in that inputs of a particular class will induce the outputs to be of that same class. The mechanism by which this works is the following. If any of the inputs are not ndarrays and define the :obj:`__array_wrap__` method, then the class with the largest :obj:`__array_priority__` attribute determines the type of all the outputs (with the exception of any output arrays passed in). The :obj:`__array_wrap__` method of the input array will be called with the ndarray being returned from the ufunc as it's input. There are two calling styles of the :obj:`__array_wrap__` function supported. The first takes the ndarray as the first argument and a tuple of "context" as the second argument. The context is (ufunc, arguments, output argument number). This is the first call tried. If a TypeError occurs, then the function is called with just the ndarray as the first argument. Methods ------- Their are three methods of ufuncs that require calculation similar to the general-purpose ufuncs. These are reduce, accumulate, and reduceat. Each of these methods requires a setup command followed by a loop. There are four loop styles possible for the methods corresponding to no-elements, one-element, strided-loop, and buffered- loop. These are the same basic loop styles as implemented for the general purpose function call except for the no-element and one- element cases which are special-cases occurring when the input array objects have 0 and 1 elements respectively. Setup ^^^^^ The setup function for all three methods is ``construct_reduce``. This function creates a reducing loop object and fills it with parameters needed to complete the loop. All of the methods only work on ufuncs that take 2-inputs and return 1 output. Therefore, the underlying 1-D loop is selected assuming a signature of [ ``otype``, ``otype``, ``otype`` ] where ``otype`` is the requested reduction data-type. The buffer size and error handling is then retrieved from (per-thread) global storage. For small arrays that are mis-aligned or have incorrect data-type, a copy is made so that the un-buffered section of code is used. Then, the looping strategy is selected. If there is 1 element or 0 elements in the array, then a simple looping method is selected. If the array is not mis-aligned and has the correct data-type, then strided looping is selected. Otherwise, buffered looping must be performed. Looping parameters are then established, and the return array is constructed. The output array is of a different shape depending on whether the method is reduce, accumulate, or reduceat. If an output array is already provided, then it's shape is checked. If the output array is not C-contiguous, aligned, and of the correct data type, then a temporary copy is made with the UPDATEIFCOPY flag set. In this way, the methods will be able to work with a well-behaved output array but the result will be copied back into the true output array when the method computation is complete. Finally, iterators are set up to loop over the correct axis (depending on the value of axis provided to the method) and the setup routine returns to the actual computation routine. Reduce ^^^^^^ .. index:: triple: ufunc; methods; reduce All of the ufunc methods use the same underlying 1-D computational loops with input and output arguments adjusted so that the appropriate reduction takes place. For example, the key to the functioning of reduce is that the 1-D loop is called with the output and the second input pointing to the same position in memory and both having a step- size of 0. The first input is pointing to the input array with a step- size given by the appropriate stride for the selected axis. In this way, the operation performed is .. math:: :nowrap: \begin{align*} o & = & i[0] \\ o & = & i[k]\textrm{}o\quad k=1\ldots N \end{align*} where :math:`N+1` is the number of elements in the input, :math:`i`, :math:`o` is the output, and :math:`i[k]` is the :math:`k^{\textrm{th}}` element of :math:`i` along the selected axis. This basic operations is repeated for arrays with greater than 1 dimension so that the reduction takes place for every 1-D sub-array along the selected axis. An iterator with the selected dimension removed handles this looping. For buffered loops, care must be taken to copy and cast data before the loop function is called because the underlying loop expects aligned data of the correct data-type (including byte-order). The buffered loop must handle this copying and casting prior to calling the loop function on chunks no greater than the user-specified bufsize. Accumulate ^^^^^^^^^^ .. index:: triple: ufunc; methods; accumulate The accumulate function is very similar to the reduce function in that the output and the second input both point to the output. The difference is that the second input points to memory one stride behind the current output pointer. Thus, the operation performed is .. math:: :nowrap: \begin{align*} o[0] & = & i[0] \\ o[k] & = & i[k]\textrm{}o[k-1]\quad k=1\ldots N. \end{align*} The output has the same shape as the input and each 1-D loop operates over :math:`N` elements when the shape in the selected axis is :math:`N+1`. Again, buffered loops take care to copy and cast the data before calling the underlying 1-D computational loop. Reduceat ^^^^^^^^ .. index:: triple: ufunc; methods; reduceat single: ufunc The reduceat function is a generalization of both the reduce and accumulate functions. It implements a reduce over ranges of the input array specified by indices. The extra indices argument is checked to be sure that every input is not too large for the input array along the selected dimension before the loop calculations take place. The loop implementation is handled using code that is very similar to the reduce code repeated as many times as there are elements in the indices input. In particular: the first input pointer passed to the underlying 1-D computational loop points to the input array at the correct location indicated by the index array. In addition, the output pointer and the second input pointer passed to the underlying 1-D loop point to the same position in memory. The size of the 1-D computational loop is fixed to be the difference between the current index and the next index (when the current index is the last index, then the next index is assumed to be the length of the array along the selected dimension). In this way, the 1-D loop will implement a reduce over the specified indices. Mis-aligned or a loop data-type that does not match the input and/or output data-type is handled using buffered code where-in data is copied to a temporary buffer and cast to the correct data-type if necessary prior to calling the underlying 1-D function. The temporary buffers are created in (element) sizes no bigger than the user settable buffer-size value. Thus, the loop must be flexible enough to call the underlying 1-D computational loop enough times to complete the total calculation in chunks no bigger than the buffer-size. numpy-1.8.2/doc/source/reference/routines.math.rst0000664000175100017510000000331212370216242023357 0ustar vagrantvagrant00000000000000Mathematical functions ********************** .. currentmodule:: numpy Trigonometric functions ----------------------- .. autosummary:: :toctree: generated/ sin cos tan arcsin arccos arctan hypot arctan2 degrees radians unwrap deg2rad rad2deg Hyperbolic functions -------------------- .. autosummary:: :toctree: generated/ sinh cosh tanh arcsinh arccosh arctanh Rounding -------- .. autosummary:: :toctree: generated/ around round_ rint fix floor ceil trunc Sums, products, differences --------------------------- .. autosummary:: :toctree: generated/ prod sum nansum cumprod cumsum diff ediff1d gradient cross trapz Exponents and logarithms ------------------------ .. autosummary:: :toctree: generated/ exp expm1 exp2 log log10 log2 log1p logaddexp logaddexp2 Other special functions ----------------------- .. autosummary:: :toctree: generated/ i0 sinc Floating point routines ----------------------- .. autosummary:: :toctree: generated/ signbit copysign frexp ldexp Arithmetic operations --------------------- .. autosummary:: :toctree: generated/ add reciprocal negative multiply divide power subtract true_divide floor_divide fmod mod modf remainder Handling complex numbers ------------------------ .. autosummary:: :toctree: generated/ angle real imag conj Miscellaneous ------------- .. autosummary:: :toctree: generated/ convolve clip sqrt square absolute fabs sign maximum minimum fmax fmin nan_to_num real_if_close interp numpy-1.8.2/doc/source/reference/index.rst0000664000175100017510000000203512370216242021667 0ustar vagrantvagrant00000000000000.. _reference: ############### NumPy Reference ############### :Release: |version| :Date: |today| .. module:: numpy This reference manual details functions, modules, and objects included in Numpy, describing what they are and what they do. For learning how to use NumPy, see also :ref:`user`. .. toctree:: :maxdepth: 2 arrays ufuncs routines ctypeslib distutils c-api internals swig Acknowledgements ================ Large parts of this manual originate from Travis E. Oliphant's book `Guide to Numpy `__ (which generously entered Public Domain in August 2008). The reference documentation for many of the functions are written by numerous contributors and developers of Numpy, both prior to and during the `Numpy Documentation Marathon `__. Please help to improve NumPy's documentation! Instructions on how to join the ongoing documentation marathon can be found `on the scipy.org website `__ numpy-1.8.2/doc/source/reference/c-api.coremath.rst0000664000175100017510000002731312370216243023361 0ustar vagrantvagrant00000000000000Numpy core libraries ==================== .. sectionauthor:: David Cournapeau .. versionadded:: 1.3.0 Starting from numpy 1.3.0, we are working on separating the pure C, "computational" code from the python dependent code. The goal is twofolds: making the code cleaner, and enabling code reuse by other extensions outside numpy (scipy, etc...). Numpy core math library ----------------------- The numpy core math library ('npymath') is a first step in this direction. This library contains most math-related C99 functionality, which can be used on platforms where C99 is not well supported. The core math functions have the same API as the C99 ones, except for the npy_* prefix. The available functions are defined in - please refer to this header when in doubt. Floating point classification ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .. cvar:: NPY_NAN This macro is defined to a NaN (Not a Number), and is guaranteed to have the signbit unset ('positive' NaN). The corresponding single and extension precision macro are available with the suffix F and L. .. cvar:: NPY_INFINITY This macro is defined to a positive inf. The corresponding single and extension precision macro are available with the suffix F and L. .. cvar:: NPY_PZERO This macro is defined to positive zero. The corresponding single and extension precision macro are available with the suffix F and L. .. cvar:: NPY_NZERO This macro is defined to negative zero (that is with the sign bit set). The corresponding single and extension precision macro are available with the suffix F and L. .. cfunction:: int npy_isnan(x) This is a macro, and is equivalent to C99 isnan: works for single, double and extended precision, and return a non 0 value is x is a NaN. .. cfunction:: int npy_isfinite(x) This is a macro, and is equivalent to C99 isfinite: works for single, double and extended precision, and return a non 0 value is x is neither a NaN nor an infinity. .. cfunction:: int npy_isinf(x) This is a macro, and is equivalent to C99 isinf: works for single, double and extended precision, and return a non 0 value is x is infinite (positive and negative). .. cfunction:: int npy_signbit(x) This is a macro, and is equivalent to C99 signbit: works for single, double and extended precision, and return a non 0 value is x has the signbit set (that is the number is negative). .. cfunction:: double npy_copysign(double x, double y) This is a function equivalent to C99 copysign: return x with the same sign as y. Works for any value, including inf and nan. Single and extended precisions are available with suffix f and l. .. versionadded:: 1.4.0 Useful math constants ~~~~~~~~~~~~~~~~~~~~~ The following math constants are available in npy_math.h. Single and extended precision are also available by adding the F and L suffixes respectively. .. cvar:: NPY_E Base of natural logarithm (:math:`e`) .. cvar:: NPY_LOG2E Logarithm to base 2 of the Euler constant (:math:`\frac{\ln(e)}{\ln(2)}`) .. cvar:: NPY_LOG10E Logarithm to base 10 of the Euler constant (:math:`\frac{\ln(e)}{\ln(10)}`) .. cvar:: NPY_LOGE2 Natural logarithm of 2 (:math:`\ln(2)`) .. cvar:: NPY_LOGE10 Natural logarithm of 10 (:math:`\ln(10)`) .. cvar:: NPY_PI Pi (:math:`\pi`) .. cvar:: NPY_PI_2 Pi divided by 2 (:math:`\frac{\pi}{2}`) .. cvar:: NPY_PI_4 Pi divided by 4 (:math:`\frac{\pi}{4}`) .. cvar:: NPY_1_PI Reciprocal of pi (:math:`\frac{1}{\pi}`) .. cvar:: NPY_2_PI Two times the reciprocal of pi (:math:`\frac{2}{\pi}`) .. cvar:: NPY_EULER The Euler constant :math:`\lim_{n\rightarrow\infty}({\sum_{k=1}^n{\frac{1}{k}}-\ln n})` Low-level floating point manipulation ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Those can be useful for precise floating point comparison. .. cfunction:: double npy_nextafter(double x, double y) This is a function equivalent to C99 nextafter: return next representable floating point value from x in the direction of y. Single and extended precisions are available with suffix f and l. .. versionadded:: 1.4.0 .. cfunction:: double npy_spacing(double x) This is a function equivalent to Fortran intrinsic. Return distance between x and next representable floating point value from x, e.g. spacing(1) == eps. spacing of nan and +/- inf return nan. Single and extended precisions are available with suffix f and l. .. versionadded:: 1.4.0 Complex functions ~~~~~~~~~~~~~~~~~ .. versionadded:: 1.4.0 C99-like complex functions have been added. Those can be used if you wish to implement portable C extensions. Since we still support platforms without C99 complex type, you need to restrict to C90-compatible syntax, e.g.: .. code-block:: c /* a = 1 + 2i \*/ npy_complex a = npy_cpack(1, 2); npy_complex b; b = npy_log(a); Linking against the core math library in an extension ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .. versionadded:: 1.4.0 To use the core math library in your own extension, you need to add the npymath compile and link options to your extension in your setup.py: >>> from numpy.distutils.misc_util import get_info >>> info = get_info('npymath') >>> config.add_extension('foo', sources=['foo.c'], extra_info=info) In other words, the usage of info is exactly the same as when using blas_info and co. Half-precision functions ~~~~~~~~~~~~~~~~~~~~~~~~ .. versionadded:: 2.0.0 The header file provides functions to work with IEEE 754-2008 16-bit floating point values. While this format is not typically used for numerical computations, it is useful for storing values which require floating point but do not need much precision. It can also be used as an educational tool to understand the nature of floating point round-off error. Like for other types, NumPy includes a typedef npy_half for the 16 bit float. Unlike for most of the other types, you cannot use this as a normal type in C, since is is a typedef for npy_uint16. For example, 1.0 looks like 0x3c00 to C, and if you do an equality comparison between the different signed zeros, you will get -0.0 != 0.0 (0x8000 != 0x0000), which is incorrect. For these reasons, NumPy provides an API to work with npy_half values accessible by including and linking to 'npymath'. For functions that are not provided directly, such as the arithmetic operations, the preferred method is to convert to float or double and back again, as in the following example. .. code-block:: c npy_half sum(int n, npy_half *array) { float ret = 0; while(n--) { ret += npy_half_to_float(*array++); } return npy_float_to_half(ret); } External Links: * `754-2008 IEEE Standard for Floating-Point Arithmetic`__ * `Half-precision Float Wikipedia Article`__. * `OpenGL Half Float Pixel Support`__ * `The OpenEXR image format`__. __ http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 __ http://en.wikipedia.org/wiki/Half_precision_floating-point_format __ http://www.opengl.org/registry/specs/ARB/half_float_pixel.txt __ http://www.openexr.com/about.html .. cvar:: NPY_HALF_ZERO This macro is defined to positive zero. .. cvar:: NPY_HALF_PZERO This macro is defined to positive zero. .. cvar:: NPY_HALF_NZERO This macro is defined to negative zero. .. cvar:: NPY_HALF_ONE This macro is defined to 1.0. .. cvar:: NPY_HALF_NEGONE This macro is defined to -1.0. .. cvar:: NPY_HALF_PINF This macro is defined to +inf. .. cvar:: NPY_HALF_NINF This macro is defined to -inf. .. cvar:: NPY_HALF_NAN This macro is defined to a NaN value, guaranteed to have its sign bit unset. .. cfunction:: float npy_half_to_float(npy_half h) Converts a half-precision float to a single-precision float. .. cfunction:: double npy_half_to_double(npy_half h) Converts a half-precision float to a double-precision float. .. cfunction:: npy_half npy_float_to_half(float f) Converts a single-precision float to a half-precision float. The value is rounded to the nearest representable half, with ties going to the nearest even. If the value is too small or too big, the system's floating point underflow or overflow bit will be set. .. cfunction:: npy_half npy_double_to_half(double d) Converts a double-precision float to a half-precision float. The value is rounded to the nearest representable half, with ties going to the nearest even. If the value is too small or too big, the system's floating point underflow or overflow bit will be set. .. cfunction:: int npy_half_eq(npy_half h1, npy_half h2) Compares two half-precision floats (h1 == h2). .. cfunction:: int npy_half_ne(npy_half h1, npy_half h2) Compares two half-precision floats (h1 != h2). .. cfunction:: int npy_half_le(npy_half h1, npy_half h2) Compares two half-precision floats (h1 <= h2). .. cfunction:: int npy_half_lt(npy_half h1, npy_half h2) Compares two half-precision floats (h1 < h2). .. cfunction:: int npy_half_ge(npy_half h1, npy_half h2) Compares two half-precision floats (h1 >= h2). .. cfunction:: int npy_half_gt(npy_half h1, npy_half h2) Compares two half-precision floats (h1 > h2). .. cfunction:: int npy_half_eq_nonan(npy_half h1, npy_half h2) Compares two half-precision floats that are known to not be NaN (h1 == h2). If a value is NaN, the result is undefined. .. cfunction:: int npy_half_lt_nonan(npy_half h1, npy_half h2) Compares two half-precision floats that are known to not be NaN (h1 < h2). If a value is NaN, the result is undefined. .. cfunction:: int npy_half_le_nonan(npy_half h1, npy_half h2) Compares two half-precision floats that are known to not be NaN (h1 <= h2). If a value is NaN, the result is undefined. .. cfunction:: int npy_half_iszero(npy_half h) Tests whether the half-precision float has a value equal to zero. This may be slightly faster than calling npy_half_eq(h, NPY_ZERO). .. cfunction:: int npy_half_isnan(npy_half h) Tests whether the half-precision float is a NaN. .. cfunction:: int npy_half_isinf(npy_half h) Tests whether the half-precision float is plus or minus Inf. .. cfunction:: int npy_half_isfinite(npy_half h) Tests whether the half-precision float is finite (not NaN or Inf). .. cfunction:: int npy_half_signbit(npy_half h) Returns 1 is h is negative, 0 otherwise. .. cfunction:: npy_half npy_half_copysign(npy_half x, npy_half y) Returns the value of x with the sign bit copied from y. Works for any value, including Inf and NaN. .. cfunction:: npy_half npy_half_spacing(npy_half h) This is the same for half-precision float as npy_spacing and npy_spacingf described in the low-level floating point section. .. cfunction:: npy_half npy_half_nextafter(npy_half x, npy_half y) This is the same for half-precision float as npy_nextafter and npy_nextafterf described in the low-level floating point section. .. cfunction:: npy_uint16 npy_floatbits_to_halfbits(npy_uint32 f) Low-level function which converts a 32-bit single-precision float, stored as a uint32, into a 16-bit half-precision float. .. cfunction:: npy_uint16 npy_doublebits_to_halfbits(npy_uint64 d) Low-level function which converts a 64-bit double-precision float, stored as a uint64, into a 16-bit half-precision float. .. cfunction:: npy_uint32 npy_halfbits_to_floatbits(npy_uint16 h) Low-level function which converts a 16-bit half-precision float into a 32-bit single-precision float, stored as a uint32. .. cfunction:: npy_uint64 npy_halfbits_to_doublebits(npy_uint16 h) Low-level function which converts a 16-bit half-precision float into a 64-bit double-precision float, stored as a uint64. numpy-1.8.2/doc/source/reference/routines.emath.rst0000664000175100017510000000051412370216242023525 0ustar vagrantvagrant00000000000000Mathematical functions with automatic domain (:mod:`numpy.emath`) *********************************************************************** .. currentmodule:: numpy .. note:: :mod:`numpy.emath` is a preferred alias for :mod:`numpy.lib.scimath`, available after :mod:`numpy` is imported. .. automodule:: numpy.lib.scimath numpy-1.8.2/doc/source/reference/arrays.dtypes.rst0000664000175100017510000004247012370216243023400 0ustar vagrantvagrant00000000000000.. currentmodule:: numpy .. _arrays.dtypes: ********************************** Data type objects (:class:`dtype`) ********************************** A data type object (an instance of :class:`numpy.dtype` class) describes how the bytes in the fixed-size block of memory corresponding to an array item should be interpreted. It describes the following aspects of the data: 1. Type of the data (integer, float, Python object, etc.) 2. Size of the data (how many bytes is in *e.g.* the integer) 3. Byte order of the data (:term:`little-endian` or :term:`big-endian`) 4. If the data type is a :term:`record`, an aggregate of other data types, (*e.g.*, describing an array item consisting of an integer and a float), 1. what are the names of the ":term:`fields `" of the record, by which they can be :ref:`accessed `, 2. what is the data-type of each :term:`field`, and 3. which part of the memory block each field takes. 5. If the data type is a sub-array, what is its shape and data type. .. index:: pair: dtype; scalar To describe the type of scalar data, there are several :ref:`built-in scalar types ` in Numpy for various precision of integers, floating-point numbers, *etc*. An item extracted from an array, *e.g.*, by indexing, will be a Python object whose type is the scalar type associated with the data type of the array. Note that the scalar types are not :class:`dtype` objects, even though they can be used in place of one whenever a data type specification is needed in Numpy. .. index:: pair: dtype; field pair: dtype; record Struct data types are formed by creating a data type whose :term:`fields` contain other data types. Each field has a name by which it can be :ref:`accessed `. The parent data type should be of sufficient size to contain all its fields; the parent is nearly always based on the :class:`void` type which allows an arbitrary item size. Struct data types may also contain nested struct sub-array data types in their fields. .. index:: pair: dtype; sub-array Finally, a data type can describe items that are themselves arrays of items of another data type. These sub-arrays must, however, be of a fixed size. If an array is created using a data-type describing a sub-array, the dimensions of the sub-array are appended to the shape of the array when the array is created. Sub-arrays in a field of a record behave differently, see :ref:`arrays.indexing.rec`. Sub-arrays always have a C-contiguous memory layout. .. admonition:: Example A simple data type containing a 32-bit big-endian integer: (see :ref:`arrays.dtypes.constructing` for details on construction) >>> dt = np.dtype('>i4') >>> dt.byteorder '>' >>> dt.itemsize 4 >>> dt.name 'int32' >>> dt.type is np.int32 True The corresponding array scalar type is :class:`int32`. .. admonition:: Example A record data type containing a 16-character string (in field 'name') and a sub-array of two 64-bit floating-point number (in field 'grades'): >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))]) >>> dt['name'] dtype('|S16') >>> dt['grades'] dtype(('float64',(2,))) Items of an array of this data type are wrapped in an :ref:`array scalar ` type that also has two fields: >>> x = np.array([('Sarah', (8.0, 7.0)), ('John', (6.0, 7.0))], dtype=dt) >>> x[1] ('John', [6.0, 7.0]) >>> x[1]['grades'] array([ 6., 7.]) >>> type(x[1]) >>> type(x[1]['grades']) .. _arrays.dtypes.constructing: Specifying and constructing data types ====================================== Whenever a data-type is required in a NumPy function or method, either a :class:`dtype` object or something that can be converted to one can be supplied. Such conversions are done by the :class:`dtype` constructor: .. autosummary:: :toctree: generated/ dtype What can be converted to a data-type object is described below: :class:`dtype` object .. index:: triple: dtype; construction; from dtype Used as-is. :const:`None` .. index:: triple: dtype; construction; from None The default data type: :class:`float_`. .. index:: triple: dtype; construction; from type Array-scalar types The 24 built-in :ref:`array scalar type objects ` all convert to an associated data-type object. This is true for their sub-classes as well. Note that not all data-type information can be supplied with a type-object: for example, :term:`flexible` data-types have a default *itemsize* of 0, and require an explicitly given size to be useful. .. admonition:: Example >>> dt = np.dtype(np.int32) # 32-bit integer >>> dt = np.dtype(np.complex128) # 128-bit complex floating-point number Generic types The generic hierarchical type objects convert to corresponding type objects according to the associations: ===================================================== =============== :class:`number`, :class:`inexact`, :class:`floating` :class:`float` :class:`complexfloating` :class:`cfloat` :class:`integer`, :class:`signedinteger` :class:`int\_` :class:`unsignedinteger` :class:`uint` :class:`character` :class:`string` :class:`generic`, :class:`flexible` :class:`void` ===================================================== =============== Built-in Python types Several python types are equivalent to a corresponding array scalar when used to generate a :class:`dtype` object: ================ =============== :class:`int` :class:`int\_` :class:`bool` :class:`bool\_` :class:`float` :class:`float\_` :class:`complex` :class:`cfloat` :class:`str` :class:`string` :class:`unicode` :class:`unicode\_` :class:`buffer` :class:`void` (all others) :class:`object_` ================ =============== .. admonition:: Example >>> dt = np.dtype(float) # Python-compatible floating-point number >>> dt = np.dtype(int) # Python-compatible integer >>> dt = np.dtype(object) # Python object Types with ``.dtype`` Any type object with a ``dtype`` attribute: The attribute will be accessed and used directly. The attribute must return something that is convertible into a dtype object. .. index:: triple: dtype; construction; from string Several kinds of strings can be converted. Recognized strings can be prepended with ``'>'`` (:term:`big-endian`), ``'<'`` (:term:`little-endian`), or ``'='`` (hardware-native, the default), to specify the byte order. One-character strings Each built-in data-type has a character code (the updated Numeric typecodes), that uniquely identifies it. .. admonition:: Example >>> dt = np.dtype('b') # byte, native byte order >>> dt = np.dtype('>H') # big-endian unsigned short >>> dt = np.dtype('>> dt = np.dtype('d') # double-precision floating-point number Array-protocol type strings (see :ref:`arrays.interface`) The first character specifies the kind of data and the remaining characters specify how many bytes of data. The supported kinds are ================ ======================== ``'b'`` Boolean ``'i'`` (signed) integer ``'u'`` unsigned integer ``'f'`` floating-point ``'c'`` complex-floating point ``'S'``, ``'a'`` string ``'U'`` unicode ``'V'`` raw data (:class:`void`) ================ ======================== .. admonition:: Example >>> dt = np.dtype('i4') # 32-bit signed integer >>> dt = np.dtype('f8') # 64-bit floating-point number >>> dt = np.dtype('c16') # 128-bit complex floating-point number >>> dt = np.dtype('a25') # 25-character string String with comma-separated fields Numarray introduced a short-hand notation for specifying the format of a record as a comma-separated string of basic formats. A basic format in this context is an optional shape specifier followed by an array-protocol type string. Parenthesis are required on the shape if it has more than one dimension. NumPy allows a modification on the format in that any string that can uniquely identify the type can be used to specify the data-type in a field. The generated data-type fields are named ``'f0'``, ``'f1'``, ..., ``'f'`` where N (>1) is the number of comma-separated basic formats in the string. If the optional shape specifier is provided, then the data-type for the corresponding field describes a sub-array. .. admonition:: Example - field named ``f0`` containing a 32-bit integer - field named ``f1`` containing a 2 x 3 sub-array of 64-bit floating-point numbers - field named ``f2`` containing a 32-bit floating-point number >>> dt = np.dtype("i4, (2,3)f8, f4") - field named ``f0`` containing a 3-character string - field named ``f1`` containing a sub-array of shape (3,) containing 64-bit unsigned integers - field named ``f2`` containing a 3 x 4 sub-array containing 10-character strings >>> dt = np.dtype("a3, 3u8, (3,4)a10") Type strings Any string in :obj:`numpy.sctypeDict`.keys(): .. admonition:: Example >>> dt = np.dtype('uint32') # 32-bit unsigned integer >>> dt = np.dtype('Float64') # 64-bit floating-point number .. index:: triple: dtype; construction; from tuple ``(flexible_dtype, itemsize)`` The first argument must be an object that is converted to a zero-sized flexible data-type object, the second argument is an integer providing the desired itemsize. .. admonition:: Example >>> dt = np.dtype((void, 10)) # 10-byte wide data block >>> dt = np.dtype((str, 35)) # 35-character string >>> dt = np.dtype(('U', 10)) # 10-character unicode string ``(fixed_dtype, shape)`` .. index:: pair: dtype; sub-array The first argument is any object that can be converted into a fixed-size data-type object. The second argument is the desired shape of this type. If the shape parameter is 1, then the data-type object is equivalent to fixed dtype. If *shape* is a tuple, then the new dtype defines a sub-array of the given shape. .. admonition:: Example >>> dt = np.dtype((np.int32, (2,2))) # 2 x 2 integer sub-array >>> dt = np.dtype(('S10', 1)) # 10-character string >>> dt = np.dtype(('i4, (2,3)f8, f4', (2,3))) # 2 x 3 record sub-array .. index:: triple: dtype; construction; from list ``[(field_name, field_dtype, field_shape), ...]`` *obj* should be a list of fields where each field is described by a tuple of length 2 or 3. (Equivalent to the ``descr`` item in the :obj:`__array_interface__` attribute.) The first element, *field_name*, is the field name (if this is ``''`` then a standard field name, ``'f#'``, is assigned). The field name may also be a 2-tuple of strings where the first string is either a "title" (which may be any string or unicode string) or meta-data for the field which can be any object, and the second string is the "name" which must be a valid Python identifier. The second element, *field_dtype*, can be anything that can be interpreted as a data-type. The optional third element *field_shape* contains the shape if this field represents an array of the data-type in the second element. Note that a 3-tuple with a third argument equal to 1 is equivalent to a 2-tuple. This style does not accept *align* in the :class:`dtype` constructor as it is assumed that all of the memory is accounted for by the array interface description. .. admonition:: Example Data-type with fields ``big`` (big-endian 32-bit integer) and ``little`` (little-endian 32-bit integer): >>> dt = np.dtype([('big', '>i4'), ('little', '>> dt = np.dtype([('R','u1'), ('G','u1'), ('B','u1'), ('A','u1')]) .. index:: triple: dtype; construction; from dict ``{'names': ..., 'formats': ..., 'offsets': ..., 'titles': ..., 'itemsize': ...}`` This style has two required and three optional keys. The *names* and *formats* keys are required. Their respective values are equal-length lists with the field names and the field formats. The field names must be strings and the field formats can be any object accepted by :class:`dtype` constructor. When the optional keys *offsets* and *titles* are provided, their values must each be lists of the same length as the *names* and *formats* lists. The *offsets* value is a list of byte offsets (integers) for each field, while the *titles* value is a list of titles for each field (:const:`None` can be used if no title is desired for that field). The *titles* can be any :class:`string` or :class:`unicode` object and will add another entry to the fields dictionary keyed by the title and referencing the same field tuple which will contain the title as an additional tuple member. The *itemsize* key allows the total size of the dtype to be set, and must be an integer large enough so all the fields are within the dtype. If the dtype being constructed is aligned, the *itemsize* must also be divisible by the struct alignment. .. admonition:: Example Data type with fields ``r``, ``g``, ``b``, ``a``, each being a 8-bit unsigned integer: >>> dt = np.dtype({'names': ['r','g','b','a'], ... 'formats': [uint8, uint8, uint8, uint8]}) Data type with fields ``r`` and ``b`` (with the given titles), both being 8-bit unsigned integers, the first at byte position 0 from the start of the field and the second at position 2: >>> dt = np.dtype({'names': ['r','b'], 'formats': ['u1', 'u1'], ... 'offsets': [0, 2], ... 'titles': ['Red pixel', 'Blue pixel']}) ``{'field1': ..., 'field2': ..., ...}`` This usage is discouraged, because it is ambiguous with the other dict-based construction method. If you have a field called 'names' and a field called 'formats' there will be a conflict. This style allows passing in the :attr:`fields ` attribute of a data-type object. *obj* should contain string or unicode keys that refer to ``(data-type, offset)`` or ``(data-type, offset, title)`` tuples. .. admonition:: Example Data type containing field ``col1`` (10-character string at byte position 0), ``col2`` (32-bit float at byte position 10), and ``col3`` (integers at byte position 14): >>> dt = np.dtype({'col1': ('S10', 0), 'col2': (float32, 10), 'col3': (int, 14)}) ``(base_dtype, new_dtype)`` This usage is discouraged. In NumPy 1.7 and later, it is possible to specify struct dtypes with overlapping fields, functioning like the 'union' type in C. The union mechanism is preferred. Both arguments must be convertible to data-type objects in this case. The *base_dtype* is the data-type object that the new data-type builds on. This is how you could assign named fields to any built-in data-type object. .. admonition:: Example 32-bit integer, whose first two bytes are interpreted as an integer via field ``real``, and the following two bytes via field ``imag``. >>> dt = np.dtype((np.int32,{'real':(np.int16, 0),'imag':(np.int16, 2)}) 32-bit integer, which is interpreted as consisting of a sub-array of shape ``(4,)`` containing 8-bit integers: >>> dt = np.dtype((np.int32, (np.int8, 4))) 32-bit integer, containing fields ``r``, ``g``, ``b``, ``a`` that interpret the 4 bytes in the integer as four unsigned integers: >>> dt = np.dtype(('i4', [('r','u1'),('g','u1'),('b','u1'),('a','u1')])) :class:`dtype` ============== Numpy data type descriptions are instances of the :class:`dtype` class. Attributes ---------- The type of the data is described by the following :class:`dtype` attributes: .. autosummary:: :toctree: generated/ dtype.type dtype.kind dtype.char dtype.num dtype.str Size of the data is in turn described by: .. autosummary:: :toctree: generated/ dtype.name dtype.itemsize Endianness of this data: .. autosummary:: :toctree: generated/ dtype.byteorder Information about sub-data-types in a :term:`record`: .. autosummary:: :toctree: generated/ dtype.fields dtype.names For data types that describe sub-arrays: .. autosummary:: :toctree: generated/ dtype.subdtype dtype.shape Attributes providing additional information: .. autosummary:: :toctree: generated/ dtype.hasobject dtype.flags dtype.isbuiltin dtype.isnative dtype.descr dtype.alignment Methods ------- Data types have the following method for changing the byte order: .. autosummary:: :toctree: generated/ dtype.newbyteorder The following methods implement the pickle protocol: .. autosummary:: :toctree: generated/ dtype.__reduce__ dtype.__setstate__ numpy-1.8.2/doc/source/reference/maskedarray.rst0000664000175100017510000000056712370216242023073 0ustar vagrantvagrant00000000000000.. _maskedarray: ************* Masked arrays ************* Masked arrays are arrays that may have missing or invalid entries. The :mod:`numpy.ma` module provides a nearly work-alike replacement for numpy that supports data arrays with masks. .. index:: single: masked arrays .. toctree:: :maxdepth: 2 maskedarray.generic maskedarray.baseclass routines.ma numpy-1.8.2/doc/source/reference/routines.sort.rst0000664000175100017510000000102612370216242023415 0ustar vagrantvagrant00000000000000Sorting, searching, and counting ================================ .. currentmodule:: numpy Sorting ------- .. autosummary:: :toctree: generated/ sort lexsort argsort ndarray.sort msort sort_complex partition argpartition Searching --------- .. autosummary:: :toctree: generated/ argmax nanargmax argmin nanargmin argwhere nonzero flatnonzero where searchsorted extract Counting -------- .. autosummary:: :toctree: generated/ count_nonzero count_reduce_items numpy-1.8.2/doc/source/reference/routines.testing.rst0000664000175100017510000000167712370216243024120 0ustar vagrantvagrant00000000000000Test Support (:mod:`numpy.testing`) =================================== .. currentmodule:: numpy.testing Common test support for all numpy test scripts. This single module should provide all the common functionality for numpy tests in a single location, so that test scripts can just import it and work right away. Asserts ======= .. autosummary:: :toctree: generated/ assert_almost_equal assert_approx_equal assert_array_almost_equal assert_allclose assert_array_almost_equal_nulp assert_array_max_ulp assert_array_equal assert_array_less assert_equal assert_raises assert_warns assert_string_equal Decorators ---------- .. autosummary:: :toctree: generated/ decorators.deprecated decorators.knownfailureif decorators.setastest decorators.skipif decorators.slow decorate_methods Test Running ------------ .. autosummary:: :toctree: generated/ Tester run_module_suite rundocs numpy-1.8.2/doc/source/reference/routines.random.rst0000664000175100017510000000210112370216242023701 0ustar vagrantvagrant00000000000000.. _routines.random: Random sampling (:mod:`numpy.random`) ************************************* .. currentmodule:: numpy.random Simple random data ================== .. autosummary:: :toctree: generated/ rand randn randint random_integers random_sample random ranf sample choice bytes Permutations ============ .. autosummary:: :toctree: generated/ shuffle permutation Distributions ============= .. autosummary:: :toctree: generated/ beta binomial chisquare dirichlet exponential f gamma geometric gumbel hypergeometric laplace logistic lognormal logseries multinomial multivariate_normal negative_binomial noncentral_chisquare noncentral_f normal pareto poisson power rayleigh standard_cauchy standard_exponential standard_gamma standard_normal standard_t triangular uniform vonmises wald weibull zipf Random generator ================ .. autosummary:: :toctree: generated/ RandomState seed get_state set_state numpy-1.8.2/doc/source/reference/arrays.ndarray.rst0000664000175100017510000004225512370216243023531 0ustar vagrantvagrant00000000000000.. _arrays.ndarray: ****************************************** The N-dimensional array (:class:`ndarray`) ****************************************** .. currentmodule:: numpy An :class:`ndarray` is a (usually fixed-size) multidimensional container of items of the same type and size. The number of dimensions and items in an array is defined by its :attr:`shape `, which is a :class:`tuple` of *N* positive integers that specify the sizes of each dimension. The type of items in the array is specified by a separate :ref:`data-type object (dtype) `, one of which is associated with each ndarray. As with other container objects in Python, the contents of an :class:`ndarray` can be accessed and modified by :ref:`indexing or slicing ` the array (using, for example, *N* integers), and via the methods and attributes of the :class:`ndarray`. .. index:: view, base Different :class:`ndarrays ` can share the same data, so that changes made in one :class:`ndarray` may be visible in another. That is, an ndarray can be a *"view"* to another ndarray, and the data it is referring to is taken care of by the *"base"* ndarray. ndarrays can also be views to memory owned by Python :class:`strings ` or objects implementing the :class:`buffer` or :ref:`array ` interfaces. .. admonition:: Example A 2-dimensional array of size 2 x 3, composed of 4-byte integer elements: >>> x = np.array([[1, 2, 3], [4, 5, 6]], np.int32) >>> type(x) >>> x.shape (2, 3) >>> x.dtype dtype('int32') The array can be indexed using Python container-like syntax: >>> x[1,2] # i.e., the element of x in the *second* row, *third* column, namely, 6. For example :ref:`slicing ` can produce views of the array: >>> y = x[:,1] >>> y array([2, 5]) >>> y[0] = 9 # this also changes the corresponding element in x >>> y array([9, 5]) >>> x array([[1, 9, 3], [4, 5, 6]]) Constructing arrays =================== New arrays can be constructed using the routines detailed in :ref:`routines.array-creation`, and also by using the low-level :class:`ndarray` constructor: .. autosummary:: :toctree: generated/ ndarray .. _arrays.ndarray.indexing: Indexing arrays =============== Arrays can be indexed using an extended Python slicing syntax, ``array[selection]``. Similar syntax is also used for accessing fields in a :ref:`record array `. .. seealso:: :ref:`Array Indexing `. Internal memory layout of an ndarray ==================================== An instance of class :class:`ndarray` consists of a contiguous one-dimensional segment of computer memory (owned by the array, or by some other object), combined with an indexing scheme that maps *N* integers into the location of an item in the block. The ranges in which the indices can vary is specified by the :obj:`shape ` of the array. How many bytes each item takes and how the bytes are interpreted is defined by the :ref:`data-type object ` associated with the array. .. index:: C-order, Fortran-order, row-major, column-major, stride, offset A segment of memory is inherently 1-dimensional, and there are many different schemes for arranging the items of an *N*-dimensional array in a 1-dimensional block. Numpy is flexible, and :class:`ndarray` objects can accommodate any *strided indexing scheme*. In a strided scheme, the N-dimensional index :math:`(n_0, n_1, ..., n_{N-1})` corresponds to the offset (in bytes): .. math:: n_{\mathrm{offset}} = \sum_{k=0}^{N-1} s_k n_k from the beginning of the memory block associated with the array. Here, :math:`s_k` are integers which specify the :obj:`strides ` of the array. The :term:`column-major` order (used, for example, in the Fortran language and in *Matlab*) and :term:`row-major` order (used in C) schemes are just specific kinds of strided scheme, and correspond to memory that can be *addressed* by the strides: .. math:: s_k^{\mathrm{column}} = \prod_{j=0}^{k-1} d_j , \quad s_k^{\mathrm{row}} = \prod_{j=k+1}^{N-1} d_j . .. index:: single-segment, contiguous, non-contiguous where :math:`d_j` `= self.itemsize * self.shape[j]`. Both the C and Fortran orders are :term:`contiguous`, *i.e.,* :term:`single-segment`, memory layouts, in which every part of the memory block can be accessed by some combination of the indices. While a C-style and Fortran-style contiguous array, which has the corresponding flags set, can be addressed with the above strides, the actual strides may be different. This can happen in two cases: 1. If ``self.shape[k] == 1`` then for any legal index ``index[k] == 0``. This means that in the formula for the offset :math:`n_k = 0` and thus :math:`s_k n_k = 0` and the value of :math:`s_k` `= self.strides[k]` is arbitrary. 2. If an array has no elements (``self.size == 0``) there is no legal index and the strides are never used. Any array with no elements may be considered C-style and Fortran-style contiguous. Point 1. means that ``self``and ``self.squeeze()`` always have the same contiguity and :term:`aligned` flags value. This also means that even a high dimensional array could be C-style and Fortran-style contiguous at the same time. .. index:: aligned An array is considered aligned if the memory offsets for all elements and the base offset itself is a multiple of `self.itemsize`. .. note:: Points (1) and (2) are not yet applied by default. Beginning with Numpy 1.8.0, they are applied consistently only if the environment variable ``NPY_RELAXED_STRIDES_CHECKING=1`` was defined when NumPy was built. Eventually this will become the default. You can check whether this option was enabled when your NumPy was built by looking at the value of ``np.ones((10,1), order='C').flags.f_contiguous``. If this is ``True``, then your NumPy has relaxed strides checking enabled. .. warning:: It does *not* generally hold that ``self.strides[-1] == self.itemsize`` for C-style contiguous arrays or ``self.strides[0] == self.itemsize`` for Fortran-style contiguous arrays is true. Data in new :class:`ndarrays ` is in the :term:`row-major` (C) order, unless otherwise specified, but, for example, :ref:`basic array slicing ` often produces :term:`views ` in a different scheme. .. seealso: :ref:`Indexing `_ .. note:: Several algorithms in NumPy work on arbitrarily strided arrays. However, some algorithms require single-segment arrays. When an irregularly strided array is passed in to such algorithms, a copy is automatically made. .. _arrays.ndarray.attributes: Array attributes ================ Array attributes reflect information that is intrinsic to the array itself. Generally, accessing an array through its attributes allows you to get and sometimes set intrinsic properties of the array without creating a new array. The exposed attributes are the core parts of an array and only some of them can be reset meaningfully without creating a new array. Information on each attribute is given below. Memory layout ------------- The following attributes contain information about the memory layout of the array: .. autosummary:: :toctree: generated/ ndarray.flags ndarray.shape ndarray.strides ndarray.ndim ndarray.data ndarray.size ndarray.itemsize ndarray.nbytes ndarray.base Data type --------- .. seealso:: :ref:`Data type objects ` The data type object associated with the array can be found in the :attr:`dtype ` attribute: .. autosummary:: :toctree: generated/ ndarray.dtype Other attributes ---------------- .. autosummary:: :toctree: generated/ ndarray.T ndarray.real ndarray.imag ndarray.flat ndarray.ctypes __array_priority__ .. _arrays.ndarray.array-interface: Array interface --------------- .. seealso:: :ref:`arrays.interface`. ========================== =================================== :obj:`__array_interface__` Python-side of the array interface :obj:`__array_struct__` C-side of the array interface ========================== =================================== :mod:`ctypes` foreign function interface ---------------------------------------- .. autosummary:: :toctree: generated/ ndarray.ctypes .. _array.ndarray.methods: Array methods ============= An :class:`ndarray` object has many methods which operate on or with the array in some fashion, typically returning an array result. These methods are briefly explained below. (Each method's docstring has a more complete description.) For the following methods there are also corresponding functions in :mod:`numpy`: :func:`all`, :func:`any`, :func:`argmax`, :func:`argmin`, :func:`argpartition`, :func:`argsort`, :func:`choose`, :func:`clip`, :func:`compress`, :func:`copy`, :func:`cumprod`, :func:`cumsum`, :func:`diagonal`, :func:`imag`, :func:`max `, :func:`mean`, :func:`min `, :func:`nonzero`, :func:`partition`, :func:`prod`, :func:`ptp`, :func:`put`, :func:`ravel`, :func:`real`, :func:`repeat`, :func:`reshape`, :func:`round `, :func:`searchsorted`, :func:`sort`, :func:`squeeze`, :func:`std`, :func:`sum`, :func:`swapaxes`, :func:`take`, :func:`trace`, :func:`transpose`, :func:`var`. Array conversion ---------------- .. autosummary:: :toctree: generated/ ndarray.item ndarray.tolist ndarray.itemset ndarray.setasflat ndarray.tostring ndarray.tofile ndarray.dump ndarray.dumps ndarray.astype ndarray.byteswap ndarray.copy ndarray.view ndarray.getfield ndarray.setflags ndarray.fill Shape manipulation ------------------ For reshape, resize, and transpose, the single tuple argument may be replaced with ``n`` integers which will be interpreted as an n-tuple. .. autosummary:: :toctree: generated/ ndarray.reshape ndarray.resize ndarray.transpose ndarray.swapaxes ndarray.flatten ndarray.ravel ndarray.squeeze Item selection and manipulation ------------------------------- For array methods that take an *axis* keyword, it defaults to :const:`None`. If axis is *None*, then the array is treated as a 1-D array. Any other value for *axis* represents the dimension along which the operation should proceed. .. autosummary:: :toctree: generated/ ndarray.take ndarray.put ndarray.repeat ndarray.choose ndarray.sort ndarray.argsort ndarray.partition ndarray.argpartition ndarray.searchsorted ndarray.nonzero ndarray.compress ndarray.diagonal Calculation ----------- .. index:: axis Many of these methods take an argument named *axis*. In such cases, - If *axis* is *None* (the default), the array is treated as a 1-D array and the operation is performed over the entire array. This behavior is also the default if self is a 0-dimensional array or array scalar. (An array scalar is an instance of the types/classes float32, float64, etc., whereas a 0-dimensional array is an ndarray instance containing precisely one array scalar.) - If *axis* is an integer, then the operation is done over the given axis (for each 1-D subarray that can be created along the given axis). .. admonition:: Example of the *axis* argument A 3-dimensional array of size 3 x 3 x 3, summed over each of its three axes >>> x array([[[ 0, 1, 2], [ 3, 4, 5], [ 6, 7, 8]], [[ 9, 10, 11], [12, 13, 14], [15, 16, 17]], [[18, 19, 20], [21, 22, 23], [24, 25, 26]]]) >>> x.sum(axis=0) array([[27, 30, 33], [36, 39, 42], [45, 48, 51]]) >>> # for sum, axis is the first keyword, so we may omit it, >>> # specifying only its value >>> x.sum(0), x.sum(1), x.sum(2) (array([[27, 30, 33], [36, 39, 42], [45, 48, 51]]), array([[ 9, 12, 15], [36, 39, 42], [63, 66, 69]]), array([[ 3, 12, 21], [30, 39, 48], [57, 66, 75]])) The parameter *dtype* specifies the data type over which a reduction operation (like summing) should take place. The default reduce data type is the same as the data type of *self*. To avoid overflow, it can be useful to perform the reduction using a larger data type. For several methods, an optional *out* argument can also be provided and the result will be placed into the output array given. The *out* argument must be an :class:`ndarray` and have the same number of elements. It can have a different data type in which case casting will be performed. .. autosummary:: :toctree: generated/ ndarray.argmax ndarray.min ndarray.argmin ndarray.ptp ndarray.clip ndarray.conj ndarray.round ndarray.trace ndarray.sum ndarray.cumsum ndarray.mean ndarray.var ndarray.std ndarray.prod ndarray.cumprod ndarray.all ndarray.any Arithmetic and comparison operations ==================================== .. index:: comparison, arithmetic, operation, operator Arithmetic and comparison operations on :class:`ndarrays ` are defined as element-wise operations, and generally yield :class:`ndarray` objects as results. Each of the arithmetic operations (``+``, ``-``, ``*``, ``/``, ``//``, ``%``, ``divmod()``, ``**`` or ``pow()``, ``<<``, ``>>``, ``&``, ``^``, ``|``, ``~``) and the comparisons (``==``, ``<``, ``>``, ``<=``, ``>=``, ``!=``) is equivalent to the corresponding :term:`universal function` (or :term:`ufunc` for short) in Numpy. For more information, see the section on :ref:`Universal Functions `. Comparison operators: .. autosummary:: :toctree: generated/ ndarray.__lt__ ndarray.__le__ ndarray.__gt__ ndarray.__ge__ ndarray.__eq__ ndarray.__ne__ Truth value of an array (:func:`bool()`): .. autosummary:: :toctree: generated/ ndarray.__nonzero__ .. note:: Truth-value testing of an array invokes :meth:`ndarray.__nonzero__`, which raises an error if the number of elements in the the array is larger than 1, because the truth value of such arrays is ambiguous. Use :meth:`.any() ` and :meth:`.all() ` instead to be clear about what is meant in such cases. (If the number of elements is 0, the array evaluates to ``False``.) Unary operations: .. autosummary:: :toctree: generated/ ndarray.__neg__ ndarray.__pos__ ndarray.__abs__ ndarray.__invert__ Arithmetic: .. autosummary:: :toctree: generated/ ndarray.__add__ ndarray.__sub__ ndarray.__mul__ ndarray.__div__ ndarray.__truediv__ ndarray.__floordiv__ ndarray.__mod__ ndarray.__divmod__ ndarray.__pow__ ndarray.__lshift__ ndarray.__rshift__ ndarray.__and__ ndarray.__or__ ndarray.__xor__ .. note:: - Any third argument to :func:`pow()` is silently ignored, as the underlying :func:`ufunc ` takes only two arguments. - The three division operators are all defined; :obj:`div` is active by default, :obj:`truediv` is active when :obj:`__future__` division is in effect. - Because :class:`ndarray` is a built-in type (written in C), the ``__r{op}__`` special methods are not directly defined. - The functions called to implement many arithmetic special methods for arrays can be modified using :func:`set_numeric_ops`. Arithmetic, in-place: .. autosummary:: :toctree: generated/ ndarray.__iadd__ ndarray.__isub__ ndarray.__imul__ ndarray.__idiv__ ndarray.__itruediv__ ndarray.__ifloordiv__ ndarray.__imod__ ndarray.__ipow__ ndarray.__ilshift__ ndarray.__irshift__ ndarray.__iand__ ndarray.__ior__ ndarray.__ixor__ .. warning:: In place operations will perform the calculation using the precision decided by the data type of the two operands, but will silently downcast the result (if necessary) so it can fit back into the array. Therefore, for mixed precision calculations, ``A {op}= B`` can be different than ``A = A {op} B``. For example, suppose ``a = ones((3,3))``. Then, ``a += 3j`` is different than ``a = a + 3j``: while they both perform the same computation, ``a += 3`` casts the result to fit back in ``a``, whereas ``a = a + 3j`` re-binds the name ``a`` to the result. Special methods =============== For standard library functions: .. autosummary:: :toctree: generated/ ndarray.__copy__ ndarray.__deepcopy__ ndarray.__reduce__ ndarray.__setstate__ Basic customization: .. autosummary:: :toctree: generated/ ndarray.__new__ ndarray.__array__ ndarray.__array_wrap__ Container customization: (see :ref:`Indexing `) .. autosummary:: :toctree: generated/ ndarray.__len__ ndarray.__getitem__ ndarray.__setitem__ ndarray.__getslice__ ndarray.__setslice__ ndarray.__contains__ Conversion; the operations :func:`complex()`, :func:`int()`, :func:`long()`, :func:`float()`, :func:`oct()`, and :func:`hex()`. They work only on arrays that have one element in them and return the appropriate scalar. .. autosummary:: :toctree: generated/ ndarray.__int__ ndarray.__long__ ndarray.__float__ ndarray.__oct__ ndarray.__hex__ String representations: .. autosummary:: :toctree: generated/ ndarray.__str__ ndarray.__repr__ numpy-1.8.2/doc/source/reference/routines.array-creation.rst0000664000175100017510000000311312370216243025346 0ustar vagrantvagrant00000000000000.. _routines.array-creation: Array creation routines ======================= .. seealso:: :ref:`Array creation ` .. currentmodule:: numpy Ones and zeros -------------- .. autosummary:: :toctree: generated/ empty empty_like eye identity ones ones_like zeros zeros_like From existing data ------------------ .. autosummary:: :toctree: generated/ array asarray asanyarray ascontiguousarray asmatrix copy frombuffer fromfile fromfunction fromiter fromstring loadtxt .. _routines.array-creation.rec: Creating record arrays (:mod:`numpy.rec`) ----------------------------------------- .. note:: :mod:`numpy.rec` is the preferred alias for :mod:`numpy.core.records`. .. autosummary:: :toctree: generated/ core.records.array core.records.fromarrays core.records.fromrecords core.records.fromstring core.records.fromfile .. _routines.array-creation.char: Creating character arrays (:mod:`numpy.char`) --------------------------------------------- .. note:: :mod:`numpy.char` is the preferred alias for :mod:`numpy.core.defchararray`. .. autosummary:: :toctree: generated/ core.defchararray.array core.defchararray.asarray Numerical ranges ---------------- .. autosummary:: :toctree: generated/ arange linspace logspace meshgrid mgrid ogrid Building matrices ----------------- .. autosummary:: :toctree: generated/ diag diagflat tri tril triu vander The Matrix class ---------------- .. autosummary:: :toctree: generated/ mat bmat numpy-1.8.2/doc/source/reference/routines.fft.rst0000664000175100017510000000005412370216242023205 0ustar vagrantvagrant00000000000000.. _routines.fft: .. automodule:: numpy.fft numpy-1.8.2/doc/source/reference/routines.set.rst0000664000175100017510000000043312370216242023222 0ustar vagrantvagrant00000000000000Set routines ============ .. currentmodule:: numpy Making proper sets ------------------ .. autosummary:: :toctree: generated/ unique Boolean operations ------------------ .. autosummary:: :toctree: generated/ in1d intersect1d setdiff1d setxor1d union1d numpy-1.8.2/doc/source/reference/routines.financial.rst0000664000175100017510000000035512370216242024356 0ustar vagrantvagrant00000000000000Financial functions ******************* .. currentmodule:: numpy Simple financial functions -------------------------- .. autosummary:: :toctree: generated/ fv pv npv pmt ppmt ipmt irr mirr nper rate numpy-1.8.2/doc/source/reference/routines.window.rst0000664000175100017510000000030012370216242023727 0ustar vagrantvagrant00000000000000Window functions ================ .. currentmodule:: numpy Various windows --------------- .. autosummary:: :toctree: generated/ bartlett blackman hamming hanning kaiser numpy-1.8.2/doc/source/reference/c-api.iterator.rst0000664000175100017510000015430312370216243023410 0ustar vagrantvagrant00000000000000Array Iterator API ================== .. sectionauthor:: Mark Wiebe .. index:: pair: iterator; C-API pair: C-API; iterator .. versionadded:: 1.6 Array Iterator -------------- The array iterator encapsulates many of the key features in ufuncs, allowing user code to support features like output parameters, preservation of memory layouts, and buffering of data with the wrong alignment or type, without requiring difficult coding. This page documents the API for the iterator. The C-API naming convention chosen is based on the one in the numpy-refactor branch, so will integrate naturally into the refactored code base. The iterator is named ``NpyIter`` and functions are named ``NpyIter_*``. There is an :ref:`introductory guide to array iteration ` which may be of interest for those using this C API. In many instances, testing out ideas by creating the iterator in Python is a good idea before writing the C iteration code. Converting from Previous NumPy Iterators ---------------------------------------- The existing iterator API includes functions like PyArrayIter_Check, PyArray_Iter* and PyArray_ITER_*. The multi-iterator array includes PyArray_MultiIter*, PyArray_Broadcast, and PyArray_RemoveSmallest. The new iterator design replaces all of this functionality with a single object and associated API. One goal of the new API is that all uses of the existing iterator should be replaceable with the new iterator without significant effort. In 1.6, the major exception to this is the neighborhood iterator, which does not have corresponding features in this iterator. Here is a conversion table for which functions to use with the new iterator: ===================================== ============================================= *Iterator Functions* :cfunc:`PyArray_IterNew` :cfunc:`NpyIter_New` :cfunc:`PyArray_IterAllButAxis` :cfunc:`NpyIter_New` + ``axes`` parameter **or** Iterator flag :cdata:`NPY_ITER_EXTERNAL_LOOP` :cfunc:`PyArray_BroadcastToShape` **NOT SUPPORTED** (Use the support for multiple operands instead.) :cfunc:`PyArrayIter_Check` Will need to add this in Python exposure :cfunc:`PyArray_ITER_RESET` :cfunc:`NpyIter_Reset` :cfunc:`PyArray_ITER_NEXT` Function pointer from :cfunc:`NpyIter_GetIterNext` :cfunc:`PyArray_ITER_DATA` :cfunc:`NpyIter_GetDataPtrArray` :cfunc:`PyArray_ITER_GOTO` :cfunc:`NpyIter_GotoMultiIndex` :cfunc:`PyArray_ITER_GOTO1D` :cfunc:`NpyIter_GotoIndex` or :cfunc:`NpyIter_GotoIterIndex` :cfunc:`PyArray_ITER_NOTDONE` Return value of ``iternext`` function pointer *Multi-iterator Functions* :cfunc:`PyArray_MultiIterNew` :cfunc:`NpyIter_MultiNew` :cfunc:`PyArray_MultiIter_RESET` :cfunc:`NpyIter_Reset` :cfunc:`PyArray_MultiIter_NEXT` Function pointer from :cfunc:`NpyIter_GetIterNext` :cfunc:`PyArray_MultiIter_DATA` :cfunc:`NpyIter_GetDataPtrArray` :cfunc:`PyArray_MultiIter_NEXTi` **NOT SUPPORTED** (always lock-step iteration) :cfunc:`PyArray_MultiIter_GOTO` :cfunc:`NpyIter_GotoMultiIndex` :cfunc:`PyArray_MultiIter_GOTO1D` :cfunc:`NpyIter_GotoIndex` or :cfunc:`NpyIter_GotoIterIndex` :cfunc:`PyArray_MultiIter_NOTDONE` Return value of ``iternext`` function pointer :cfunc:`PyArray_Broadcast` Handled by :cfunc:`NpyIter_MultiNew` :cfunc:`PyArray_RemoveSmallest` Iterator flag :cdata:`NPY_ITER_EXTERNAL_LOOP` *Other Functions* :cfunc:`PyArray_ConvertToCommonType` Iterator flag :cdata:`NPY_ITER_COMMON_DTYPE` ===================================== ============================================= Simple Iteration Example ------------------------ The best way to become familiar with the iterator is to look at its usage within the NumPy codebase itself. For example, here is a slightly tweaked version of the code for :cfunc:`PyArray_CountNonzero`, which counts the number of non-zero elements in an array. .. code-block:: c npy_intp PyArray_CountNonzero(PyArrayObject* self) { /* Nonzero boolean function */ PyArray_NonzeroFunc* nonzero = PyArray_DESCR(self)->f->nonzero; NpyIter* iter; NpyIter_IterNextFunc *iternext; char** dataptr; npy_intp* strideptr,* innersizeptr; /* Handle zero-sized arrays specially */ if (PyArray_SIZE(self) == 0) { return 0; } /* * Create and use an iterator to count the nonzeros. * flag NPY_ITER_READONLY * - The array is never written to. * flag NPY_ITER_EXTERNAL_LOOP * - Inner loop is done outside the iterator for efficiency. * flag NPY_ITER_NPY_ITER_REFS_OK * - Reference types are acceptable. * order NPY_KEEPORDER * - Visit elements in memory order, regardless of strides. * This is good for performance when the specific order * elements are visited is unimportant. * casting NPY_NO_CASTING * - No casting is required for this operation. */ iter = NpyIter_New(self, NPY_ITER_READONLY| NPY_ITER_EXTERNAL_LOOP| NPY_ITER_REFS_OK, NPY_KEEPORDER, NPY_NO_CASTING, NULL); if (iter == NULL) { return -1; } /* * The iternext function gets stored in a local variable * so it can be called repeatedly in an efficient manner. */ iternext = NpyIter_GetIterNext(iter, NULL); if (iternext == NULL) { NpyIter_Deallocate(iter); return -1; } /* The location of the data pointer which the iterator may update */ dataptr = NpyIter_GetDataPtrArray(iter); /* The location of the stride which the iterator may update */ strideptr = NpyIter_GetInnerStrideArray(iter); /* The location of the inner loop size which the iterator may update */ innersizeptr = NpyIter_GetInnerLoopSizePtr(iter); /* The iteration loop */ do { /* Get the inner loop data/stride/count values */ char* data = *dataptr; npy_intp stride = *strideptr; npy_intp count = *innersizeptr; /* This is a typical inner loop for NPY_ITER_EXTERNAL_LOOP */ while (count--) { if (nonzero(data, self)) { ++nonzero_count; } data += stride; } /* Increment the iterator to the next inner loop */ } while(iternext(iter)); NpyIter_Deallocate(iter); return nonzero_count; } Simple Multi-Iteration Example ------------------------------ Here is a simple copy function using the iterator. The ``order`` parameter is used to control the memory layout of the allocated result, typically :cdata:`NPY_KEEPORDER` is desired. .. code-block:: c PyObject *CopyArray(PyObject *arr, NPY_ORDER order) { NpyIter *iter; NpyIter_IterNextFunc *iternext; PyObject *op[2], *ret; npy_uint32 flags; npy_uint32 op_flags[2]; npy_intp itemsize, *innersizeptr, innerstride; char **dataptrarray; /* * No inner iteration - inner loop is handled by CopyArray code */ flags = NPY_ITER_EXTERNAL_LOOP; /* * Tell the constructor to automatically allocate the output. * The data type of the output will match that of the input. */ op[0] = arr; op[1] = NULL; op_flags[0] = NPY_ITER_READONLY; op_flags[1] = NPY_ITER_WRITEONLY | NPY_ITER_ALLOCATE; /* Construct the iterator */ iter = NpyIter_MultiNew(2, op, flags, order, NPY_NO_CASTING, op_flags, NULL); if (iter == NULL) { return NULL; } /* * Make a copy of the iternext function pointer and * a few other variables the inner loop needs. */ iternext = NpyIter_GetIterNext(iter, NULL); innerstride = NpyIter_GetInnerStrideArray(iter)[0]; itemsize = NpyIter_GetDescrArray(iter)[0]->elsize; /* * The inner loop size and data pointers may change during the * loop, so just cache the addresses. */ innersizeptr = NpyIter_GetInnerLoopSizePtr(iter); dataptrarray = NpyIter_GetDataPtrArray(iter); /* * Note that because the iterator allocated the output, * it matches the iteration order and is packed tightly, * so we don't need to check it like the input. */ if (innerstride == itemsize) { do { memcpy(dataptrarray[1], dataptrarray[0], itemsize * (*innersizeptr)); } while (iternext(iter)); } else { /* For efficiency, should specialize this based on item size... */ npy_intp i; do { npy_intp size = *innersizeptr; char *src = dataaddr[0], *dst = dataaddr[1]; for(i = 0; i < size; i++, src += innerstride, dst += itemsize) { memcpy(dst, src, itemsize); } } while (iternext(iter)); } /* Get the result from the iterator object array */ ret = NpyIter_GetOperandArray(iter)[1]; Py_INCREF(ret); if (NpyIter_Deallocate(iter) != NPY_SUCCEED) { Py_DECREF(ret); return NULL; } return ret; } Iterator Data Types --------------------- The iterator layout is an internal detail, and user code only sees an incomplete struct. .. ctype:: NpyIter This is an opaque pointer type for the iterator. Access to its contents can only be done through the iterator API. .. ctype:: NpyIter_Type This is the type which exposes the iterator to Python. Currently, no API is exposed which provides access to the values of a Python-created iterator. If an iterator is created in Python, it must be used in Python and vice versa. Such an API will likely be created in a future version. .. ctype:: NpyIter_IterNextFunc This is a function pointer for the iteration loop, returned by :cfunc:`NpyIter_GetIterNext`. .. ctype:: NpyIter_GetMultiIndexFunc This is a function pointer for getting the current iterator multi-index, returned by :cfunc:`NpyIter_GetGetMultiIndex`. Construction and Destruction ---------------------------- .. cfunction:: NpyIter* NpyIter_New(PyArrayObject* op, npy_uint32 flags, NPY_ORDER order, NPY_CASTING casting, PyArray_Descr* dtype) Creates an iterator for the given numpy array object ``op``. Flags that may be passed in ``flags`` are any combination of the global and per-operand flags documented in :cfunc:`NpyIter_MultiNew`, except for :cdata:`NPY_ITER_ALLOCATE`. Any of the :ctype:`NPY_ORDER` enum values may be passed to ``order``. For efficient iteration, :ctype:`NPY_KEEPORDER` is the best option, and the other orders enforce the particular iteration pattern. Any of the :ctype:`NPY_CASTING` enum values may be passed to ``casting``. The values include :cdata:`NPY_NO_CASTING`, :cdata:`NPY_EQUIV_CASTING`, :cdata:`NPY_SAFE_CASTING`, :cdata:`NPY_SAME_KIND_CASTING`, and :cdata:`NPY_UNSAFE_CASTING`. To allow the casts to occur, copying or buffering must also be enabled. If ``dtype`` isn't ``NULL``, then it requires that data type. If copying is allowed, it will make a temporary copy if the data is castable. If :cdata:`NPY_ITER_UPDATEIFCOPY` is enabled, it will also copy the data back with another cast upon iterator destruction. Returns NULL if there is an error, otherwise returns the allocated iterator. To make an iterator similar to the old iterator, this should work. .. code-block:: c iter = NpyIter_New(op, NPY_ITER_READWRITE, NPY_CORDER, NPY_NO_CASTING, NULL); If you want to edit an array with aligned ``double`` code, but the order doesn't matter, you would use this. .. code-block:: c dtype = PyArray_DescrFromType(NPY_DOUBLE); iter = NpyIter_New(op, NPY_ITER_READWRITE| NPY_ITER_BUFFERED| NPY_ITER_NBO| NPY_ITER_ALIGNED, NPY_KEEPORDER, NPY_SAME_KIND_CASTING, dtype); Py_DECREF(dtype); .. cfunction:: NpyIter* NpyIter_MultiNew(npy_intp nop, PyArrayObject** op, npy_uint32 flags, NPY_ORDER order, NPY_CASTING casting, npy_uint32* op_flags, PyArray_Descr** op_dtypes) Creates an iterator for broadcasting the ``nop`` array objects provided in ``op``, using regular NumPy broadcasting rules. Any of the :ctype:`NPY_ORDER` enum values may be passed to ``order``. For efficient iteration, :cdata:`NPY_KEEPORDER` is the best option, and the other orders enforce the particular iteration pattern. When using :cdata:`NPY_KEEPORDER`, if you also want to ensure that the iteration is not reversed along an axis, you should pass the flag :cdata:`NPY_ITER_DONT_NEGATE_STRIDES`. Any of the :ctype:`NPY_CASTING` enum values may be passed to ``casting``. The values include :cdata:`NPY_NO_CASTING`, :cdata:`NPY_EQUIV_CASTING`, :cdata:`NPY_SAFE_CASTING`, :cdata:`NPY_SAME_KIND_CASTING`, and :cdata:`NPY_UNSAFE_CASTING`. To allow the casts to occur, copying or buffering must also be enabled. If ``op_dtypes`` isn't ``NULL``, it specifies a data type or ``NULL`` for each ``op[i]``. Returns NULL if there is an error, otherwise returns the allocated iterator. Flags that may be passed in ``flags``, applying to the whole iterator, are: .. cvar:: NPY_ITER_C_INDEX Causes the iterator to track a raveled flat index matching C order. This option cannot be used with :cdata:`NPY_ITER_F_INDEX`. .. cvar:: NPY_ITER_F_INDEX Causes the iterator to track a raveled flat index matching Fortran order. This option cannot be used with :cdata:`NPY_ITER_C_INDEX`. .. cvar:: NPY_ITER_MULTI_INDEX Causes the iterator to track a multi-index. This prevents the iterator from coalescing axes to produce bigger inner loops. .. cvar:: NPY_ITER_EXTERNAL_LOOP Causes the iterator to skip iteration of the innermost loop, requiring the user of the iterator to handle it. This flag is incompatible with :cdata:`NPY_ITER_C_INDEX`, :cdata:`NPY_ITER_F_INDEX`, and :cdata:`NPY_ITER_MULTI_INDEX`. .. cvar:: NPY_ITER_DONT_NEGATE_STRIDES This only affects the iterator when :ctype:`NPY_KEEPORDER` is specified for the order parameter. By default with :ctype:`NPY_KEEPORDER`, the iterator reverses axes which have negative strides, so that memory is traversed in a forward direction. This disables this step. Use this flag if you want to use the underlying memory-ordering of the axes, but don't want an axis reversed. This is the behavior of ``numpy.ravel(a, order='K')``, for instance. .. cvar:: NPY_ITER_COMMON_DTYPE Causes the iterator to convert all the operands to a common data type, calculated based on the ufunc type promotion rules. Copying or buffering must be enabled. If the common data type is known ahead of time, don't use this flag. Instead, set the requested dtype for all the operands. .. cvar:: NPY_ITER_REFS_OK Indicates that arrays with reference types (object arrays or structured arrays containing an object type) may be accepted and used in the iterator. If this flag is enabled, the caller must be sure to check whether :cfunc:`NpyIter_IterationNeedsAPI`(iter) is true, in which case it may not release the GIL during iteration. .. cvar:: NPY_ITER_ZEROSIZE_OK Indicates that arrays with a size of zero should be permitted. Since the typical iteration loop does not naturally work with zero-sized arrays, you must check that the IterSize is non-zero before entering the iteration loop. .. cvar:: NPY_ITER_REDUCE_OK Permits writeable operands with a dimension with zero stride and size greater than one. Note that such operands must be read/write. When buffering is enabled, this also switches to a special buffering mode which reduces the loop length as necessary to not trample on values being reduced. Note that if you want to do a reduction on an automatically allocated output, you must use :cfunc:`NpyIter_GetOperandArray` to get its reference, then set every value to the reduction unit before doing the iteration loop. In the case of a buffered reduction, this means you must also specify the flag :cdata:`NPY_ITER_DELAY_BUFALLOC`, then reset the iterator after initializing the allocated operand to prepare the buffers. .. cvar:: NPY_ITER_RANGED Enables support for iteration of sub-ranges of the full ``iterindex`` range ``[0, NpyIter_IterSize(iter))``. Use the function :cfunc:`NpyIter_ResetToIterIndexRange` to specify a range for iteration. This flag can only be used with :cdata:`NPY_ITER_EXTERNAL_LOOP` when :cdata:`NPY_ITER_BUFFERED` is enabled. This is because without buffering, the inner loop is always the size of the innermost iteration dimension, and allowing it to get cut up would require special handling, effectively making it more like the buffered version. .. cvar:: NPY_ITER_BUFFERED Causes the iterator to store buffering data, and use buffering to satisfy data type, alignment, and byte-order requirements. To buffer an operand, do not specify the :cdata:`NPY_ITER_COPY` or :cdata:`NPY_ITER_UPDATEIFCOPY` flags, because they will override buffering. Buffering is especially useful for Python code using the iterator, allowing for larger chunks of data at once to amortize the Python interpreter overhead. If used with :cdata:`NPY_ITER_EXTERNAL_LOOP`, the inner loop for the caller may get larger chunks than would be possible without buffering, because of how the strides are laid out. Note that if an operand is given the flag :cdata:`NPY_ITER_COPY` or :cdata:`NPY_ITER_UPDATEIFCOPY`, a copy will be made in preference to buffering. Buffering will still occur when the array was broadcast so elements need to be duplicated to get a constant stride. In normal buffering, the size of each inner loop is equal to the buffer size, or possibly larger if :cdata:`NPY_ITER_GROWINNER` is specified. If :cdata:`NPY_ITER_REDUCE_OK` is enabled and a reduction occurs, the inner loops may become smaller depending on the structure of the reduction. .. cvar:: NPY_ITER_GROWINNER When buffering is enabled, this allows the size of the inner loop to grow when buffering isn't necessary. This option is best used if you're doing a straight pass through all the data, rather than anything with small cache-friendly arrays of temporary values for each inner loop. .. cvar:: NPY_ITER_DELAY_BUFALLOC When buffering is enabled, this delays allocation of the buffers until :cfunc:`NpyIter_Reset` or another reset function is called. This flag exists to avoid wasteful copying of buffer data when making multiple copies of a buffered iterator for multi-threaded iteration. Another use of this flag is for setting up reduction operations. After the iterator is created, and a reduction output is allocated automatically by the iterator (be sure to use READWRITE access), its value may be initialized to the reduction unit. Use :cfunc:`NpyIter_GetOperandArray` to get the object. Then, call :cfunc:`NpyIter_Reset` to allocate and fill the buffers with their initial values. Flags that may be passed in ``op_flags[i]``, where ``0 <= i < nop``: .. cvar:: NPY_ITER_READWRITE .. cvar:: NPY_ITER_READONLY .. cvar:: NPY_ITER_WRITEONLY Indicate how the user of the iterator will read or write to ``op[i]``. Exactly one of these flags must be specified per operand. .. cvar:: NPY_ITER_COPY Allow a copy of ``op[i]`` to be made if it does not meet the data type or alignment requirements as specified by the constructor flags and parameters. .. cvar:: NPY_ITER_UPDATEIFCOPY Triggers :cdata:`NPY_ITER_COPY`, and when an array operand is flagged for writing and is copied, causes the data in a copy to be copied back to ``op[i]`` when the iterator is destroyed. If the operand is flagged as write-only and a copy is needed, an uninitialized temporary array will be created and then copied to back to ``op[i]`` on destruction, instead of doing the unecessary copy operation. .. cvar:: NPY_ITER_NBO .. cvar:: NPY_ITER_ALIGNED .. cvar:: NPY_ITER_CONTIG Causes the iterator to provide data for ``op[i]`` that is in native byte order, aligned according to the dtype requirements, contiguous, or any combination. By default, the iterator produces pointers into the arrays provided, which may be aligned or unaligned, and with any byte order. If copying or buffering is not enabled and the operand data doesn't satisfy the constraints, an error will be raised. The contiguous constraint applies only to the inner loop, successive inner loops may have arbitrary pointer changes. If the requested data type is in non-native byte order, the NBO flag overrides it and the requested data type is converted to be in native byte order. .. cvar:: NPY_ITER_ALLOCATE This is for output arrays, and requires that the flag :cdata:`NPY_ITER_WRITEONLY` or :cdata:`NPY_ITER_READWRITE` be set. If ``op[i]`` is NULL, creates a new array with the final broadcast dimensions, and a layout matching the iteration order of the iterator. When ``op[i]`` is NULL, the requested data type ``op_dtypes[i]`` may be NULL as well, in which case it is automatically generated from the dtypes of the arrays which are flagged as readable. The rules for generating the dtype are the same is for UFuncs. Of special note is handling of byte order in the selected dtype. If there is exactly one input, the input's dtype is used as is. Otherwise, if more than one input dtypes are combined together, the output will be in native byte order. After being allocated with this flag, the caller may retrieve the new array by calling :cfunc:`NpyIter_GetOperandArray` and getting the i-th object in the returned C array. The caller must call Py_INCREF on it to claim a reference to the array. .. cvar:: NPY_ITER_NO_SUBTYPE For use with :cdata:`NPY_ITER_ALLOCATE`, this flag disables allocating an array subtype for the output, forcing it to be a straight ndarray. TODO: Maybe it would be better to introduce a function ``NpyIter_GetWrappedOutput`` and remove this flag? .. cvar:: NPY_ITER_NO_BROADCAST Ensures that the input or output matches the iteration dimensions exactly. .. cvar:: NPY_ITER_ARRAYMASK .. versionadded:: 1.7 Indicates that this operand is the mask to use for selecting elements when writing to operands which have the :cdata:`NPY_ITER_WRITEMASKED` flag applied to them. Only one operand may have :cdata:`NPY_ITER_ARRAYMASK` flag applied to it. The data type of an operand with this flag should be either :cdata:`NPY_BOOL`, :cdata:`NPY_MASK`, or a struct dtype whose fields are all valid mask dtypes. In the latter case, it must match up with a struct operand being WRITEMASKED, as it is specifying a mask for each field of that array. This flag only affects writing from the buffer back to the array. This means that if the operand is also :cdata:`NPY_ITER_READWRITE` or :cdata:`NPY_ITER_WRITEONLY`, code doing iteration can write to this operand to control which elements will be untouched and which ones will be modified. This is useful when the mask should be a combination of input masks, for example. Mask values can be created with the :cfunc:`NpyMask_Create` function. .. cvar:: NPY_ITER_WRITEMASKED .. versionadded:: 1.7 Indicates that only elements which the operand with the ARRAYMASK flag indicates are intended to be modified by the iteration. In general, the iterator does not enforce this, it is up to the code doing the iteration to follow that promise. Code can use the :cfunc:`NpyMask_IsExposed` inline function to test whether the mask at a particular element allows writing. When this flag is used, and this operand is buffered, this changes how data is copied from the buffer into the array. A masked copying routine is used, which only copies the elements in the buffer for which :cfunc:`NpyMask_IsExposed` returns true from the corresponding element in the ARRAYMASK operand. .. cfunction:: NpyIter* NpyIter_AdvancedNew(npy_intp nop, PyArrayObject** op, npy_uint32 flags, NPY_ORDER order, NPY_CASTING casting, npy_uint32* op_flags, PyArray_Descr** op_dtypes, int oa_ndim, int** op_axes, npy_intp* itershape, npy_intp buffersize) Extends :cfunc:`NpyIter_MultiNew` with several advanced options providing more control over broadcasting and buffering. If -1/NULL values are passed to ``oa_ndim``, ``op_axes``, ``itershape``, and ``buffersize``, it is equivalent to :cfunc:`NpyIter_MultiNew`. The parameter ``oa_ndim``, when not zero or -1, specifies the number of dimensions that will be iterated with customized broadcasting. If it is provided, ``op_axes`` must and ``itershape`` can also be provided. The ``op_axes`` parameter let you control in detail how the axes of the operand arrays get matched together and iterated. In ``op_axes``, you must provide an array of ``nop`` pointers to ``oa_ndim``-sized arrays of type ``npy_intp``. If an entry in ``op_axes`` is NULL, normal broadcasting rules will apply. In ``op_axes[j][i]`` is stored either a valid axis of ``op[j]``, or -1 which means ``newaxis``. Within each ``op_axes[j]`` array, axes may not be repeated. The following example is how normal broadcasting applies to a 3-D array, a 2-D array, a 1-D array and a scalar. **Note**: Before NumPy 1.8 ``oa_ndim == 0` was used for signalling that that ``op_axes`` and ``itershape`` are unused. This is deprecated and should be replaced with -1. Better backward compatibility may be achieved by using :cfunc:`NpyIter_MultiNew` for this case. .. code-block:: c int oa_ndim = 3; /* # iteration axes */ int op0_axes[] = {0, 1, 2}; /* 3-D operand */ int op1_axes[] = {-1, 0, 1}; /* 2-D operand */ int op2_axes[] = {-1, -1, 0}; /* 1-D operand */ int op3_axes[] = {-1, -1, -1} /* 0-D (scalar) operand */ int* op_axes[] = {op0_axes, op1_axes, op2_axes, op3_axes}; The ``itershape`` parameter allows you to force the iterator to have a specific iteration shape. It is an array of length ``oa_ndim``. When an entry is negative, its value is determined from the operands. This parameter allows automatically allocated outputs to get additional dimensions which don't match up with any dimension of an input. If ``buffersize`` is zero, a default buffer size is used, otherwise it specifies how big of a buffer to use. Buffers which are powers of 2 such as 4096 or 8192 are recommended. Returns NULL if there is an error, otherwise returns the allocated iterator. .. cfunction:: NpyIter* NpyIter_Copy(NpyIter* iter) Makes a copy of the given iterator. This function is provided primarily to enable multi-threaded iteration of the data. *TODO*: Move this to a section about multithreaded iteration. The recommended approach to multithreaded iteration is to first create an iterator with the flags :cdata:`NPY_ITER_EXTERNAL_LOOP`, :cdata:`NPY_ITER_RANGED`, :cdata:`NPY_ITER_BUFFERED`, :cdata:`NPY_ITER_DELAY_BUFALLOC`, and possibly :cdata:`NPY_ITER_GROWINNER`. Create a copy of this iterator for each thread (minus one for the first iterator). Then, take the iteration index range ``[0, NpyIter_GetIterSize(iter))`` and split it up into tasks, for example using a TBB parallel_for loop. When a thread gets a task to execute, it then uses its copy of the iterator by calling :cfunc:`NpyIter_ResetToIterIndexRange` and iterating over the full range. When using the iterator in multi-threaded code or in code not holding the Python GIL, care must be taken to only call functions which are safe in that context. :cfunc:`NpyIter_Copy` cannot be safely called without the Python GIL, because it increments Python references. The ``Reset*`` and some other functions may be safely called by passing in the ``errmsg`` parameter as non-NULL, so that the functions will pass back errors through it instead of setting a Python exception. .. cfunction:: int NpyIter_RemoveAxis(NpyIter* iter, int axis)`` Removes an axis from iteration. This requires that :cdata:`NPY_ITER_MULTI_INDEX` was set for iterator creation, and does not work if buffering is enabled or an index is being tracked. This function also resets the iterator to its initial state. This is useful for setting up an accumulation loop, for example. The iterator can first be created with all the dimensions, including the accumulation axis, so that the output gets created correctly. Then, the accumulation axis can be removed, and the calculation done in a nested fashion. **WARNING**: This function may change the internal memory layout of the iterator. Any cached functions or pointers from the iterator must be retrieved again! Returns ``NPY_SUCCEED`` or ``NPY_FAIL``. .. cfunction:: int NpyIter_RemoveMultiIndex(NpyIter* iter) If the iterator is tracking a multi-index, this strips support for them, and does further iterator optimizations that are possible if multi-indices are not needed. This function also resets the iterator to its initial state. **WARNING**: This function may change the internal memory layout of the iterator. Any cached functions or pointers from the iterator must be retrieved again! After calling this function, :cfunc:`NpyIter_HasMultiIndex`(iter) will return false. Returns ``NPY_SUCCEED`` or ``NPY_FAIL``. .. cfunction:: int NpyIter_EnableExternalLoop(NpyIter* iter) If :cfunc:`NpyIter_RemoveMultiIndex` was called, you may want to enable the flag :cdata:`NPY_ITER_EXTERNAL_LOOP`. This flag is not permitted together with :cdata:`NPY_ITER_MULTI_INDEX`, so this function is provided to enable the feature after :cfunc:`NpyIter_RemoveMultiIndex` is called. This function also resets the iterator to its initial state. **WARNING**: This function changes the internal logic of the iterator. Any cached functions or pointers from the iterator must be retrieved again! Returns ``NPY_SUCCEED`` or ``NPY_FAIL``. .. cfunction:: int NpyIter_Deallocate(NpyIter* iter) Deallocates the iterator object. This additionally frees any copies made, triggering UPDATEIFCOPY behavior where necessary. Returns ``NPY_SUCCEED`` or ``NPY_FAIL``. .. cfunction:: int NpyIter_Reset(NpyIter* iter, char** errmsg) Resets the iterator back to its initial state, at the beginning of the iteration range. Returns ``NPY_SUCCEED`` or ``NPY_FAIL``. If errmsg is non-NULL, no Python exception is set when ``NPY_FAIL`` is returned. Instead, \*errmsg is set to an error message. When errmsg is non-NULL, the function may be safely called without holding the Python GIL. .. cfunction:: int NpyIter_ResetToIterIndexRange(NpyIter* iter, npy_intp istart, npy_intp iend, char** errmsg) Resets the iterator and restricts it to the ``iterindex`` range ``[istart, iend)``. See :cfunc:`NpyIter_Copy` for an explanation of how to use this for multi-threaded iteration. This requires that the flag :cdata:`NPY_ITER_RANGED` was passed to the iterator constructor. If you want to reset both the ``iterindex`` range and the base pointers at the same time, you can do the following to avoid extra buffer copying (be sure to add the return code error checks when you copy this code). .. code-block:: c /* Set to a trivial empty range */ NpyIter_ResetToIterIndexRange(iter, 0, 0); /* Set the base pointers */ NpyIter_ResetBasePointers(iter, baseptrs); /* Set to the desired range */ NpyIter_ResetToIterIndexRange(iter, istart, iend); Returns ``NPY_SUCCEED`` or ``NPY_FAIL``. If errmsg is non-NULL, no Python exception is set when ``NPY_FAIL`` is returned. Instead, \*errmsg is set to an error message. When errmsg is non-NULL, the function may be safely called without holding the Python GIL. .. cfunction:: int NpyIter_ResetBasePointers(NpyIter *iter, char** baseptrs, char** errmsg) Resets the iterator back to its initial state, but using the values in ``baseptrs`` for the data instead of the pointers from the arrays being iterated. This functions is intended to be used, together with the ``op_axes`` parameter, by nested iteration code with two or more iterators. Returns ``NPY_SUCCEED`` or ``NPY_FAIL``. If errmsg is non-NULL, no Python exception is set when ``NPY_FAIL`` is returned. Instead, \*errmsg is set to an error message. When errmsg is non-NULL, the function may be safely called without holding the Python GIL. *TODO*: Move the following into a special section on nested iterators. Creating iterators for nested iteration requires some care. All the iterator operands must match exactly, or the calls to :cfunc:`NpyIter_ResetBasePointers` will be invalid. This means that automatic copies and output allocation should not be used haphazardly. It is possible to still use the automatic data conversion and casting features of the iterator by creating one of the iterators with all the conversion parameters enabled, then grabbing the allocated operands with the :cfunc:`NpyIter_GetOperandArray` function and passing them into the constructors for the rest of the iterators. **WARNING**: When creating iterators for nested iteration, the code must not use a dimension more than once in the different iterators. If this is done, nested iteration will produce out-of-bounds pointers during iteration. **WARNING**: When creating iterators for nested iteration, buffering can only be applied to the innermost iterator. If a buffered iterator is used as the source for ``baseptrs``, it will point into a small buffer instead of the array and the inner iteration will be invalid. The pattern for using nested iterators is as follows. .. code-block:: c NpyIter *iter1, *iter1; NpyIter_IterNextFunc *iternext1, *iternext2; char **dataptrs1; /* * With the exact same operands, no copies allowed, and * no axis in op_axes used both in iter1 and iter2. * Buffering may be enabled for iter2, but not for iter1. */ iter1 = ...; iter2 = ...; iternext1 = NpyIter_GetIterNext(iter1); iternext2 = NpyIter_GetIterNext(iter2); dataptrs1 = NpyIter_GetDataPtrArray(iter1); do { NpyIter_ResetBasePointers(iter2, dataptrs1); do { /* Use the iter2 values */ } while (iternext2(iter2)); } while (iternext1(iter1)); .. cfunction:: int NpyIter_GotoMultiIndex(NpyIter* iter, npy_intp* multi_index) Adjusts the iterator to point to the ``ndim`` indices pointed to by ``multi_index``. Returns an error if a multi-index is not being tracked, the indices are out of bounds, or inner loop iteration is disabled. Returns ``NPY_SUCCEED`` or ``NPY_FAIL``. .. cfunction:: int NpyIter_GotoIndex(NpyIter* iter, npy_intp index) Adjusts the iterator to point to the ``index`` specified. If the iterator was constructed with the flag :cdata:`NPY_ITER_C_INDEX`, ``index`` is the C-order index, and if the iterator was constructed with the flag :cdata:`NPY_ITER_F_INDEX`, ``index`` is the Fortran-order index. Returns an error if there is no index being tracked, the index is out of bounds, or inner loop iteration is disabled. Returns ``NPY_SUCCEED`` or ``NPY_FAIL``. .. cfunction:: npy_intp NpyIter_GetIterSize(NpyIter* iter) Returns the number of elements being iterated. This is the product of all the dimensions in the shape. .. cfunction:: npy_intp NpyIter_GetIterIndex(NpyIter* iter) Gets the ``iterindex`` of the iterator, which is an index matching the iteration order of the iterator. .. cfunction:: void NpyIter_GetIterIndexRange(NpyIter* iter, npy_intp* istart, npy_intp* iend) Gets the ``iterindex`` sub-range that is being iterated. If :cdata:`NPY_ITER_RANGED` was not specified, this always returns the range ``[0, NpyIter_IterSize(iter))``. .. cfunction:: int NpyIter_GotoIterIndex(NpyIter* iter, npy_intp iterindex) Adjusts the iterator to point to the ``iterindex`` specified. The IterIndex is an index matching the iteration order of the iterator. Returns an error if the ``iterindex`` is out of bounds, buffering is enabled, or inner loop iteration is disabled. Returns ``NPY_SUCCEED`` or ``NPY_FAIL``. .. cfunction:: npy_bool NpyIter_HasDelayedBufAlloc(NpyIter* iter) Returns 1 if the flag :cdata:`NPY_ITER_DELAY_BUFALLOC` was passed to the iterator constructor, and no call to one of the Reset functions has been done yet, 0 otherwise. .. cfunction:: npy_bool NpyIter_HasExternalLoop(NpyIter* iter) Returns 1 if the caller needs to handle the inner-most 1-dimensional loop, or 0 if the iterator handles all looping. This is controlled by the constructor flag :cdata:`NPY_ITER_EXTERNAL_LOOP` or :cfunc:`NpyIter_EnableExternalLoop`. .. cfunction:: npy_bool NpyIter_HasMultiIndex(NpyIter* iter) Returns 1 if the iterator was created with the :cdata:`NPY_ITER_MULTI_INDEX` flag, 0 otherwise. .. cfunction:: npy_bool NpyIter_HasIndex(NpyIter* iter) Returns 1 if the iterator was created with the :cdata:`NPY_ITER_C_INDEX` or :cdata:`NPY_ITER_F_INDEX` flag, 0 otherwise. .. cfunction:: npy_bool NpyIter_RequiresBuffering(NpyIter* iter) Returns 1 if the iterator requires buffering, which occurs when an operand needs conversion or alignment and so cannot be used directly. .. cfunction:: npy_bool NpyIter_IsBuffered(NpyIter* iter) Returns 1 if the iterator was created with the :cdata:`NPY_ITER_BUFFERED` flag, 0 otherwise. .. cfunction:: npy_bool NpyIter_IsGrowInner(NpyIter* iter) Returns 1 if the iterator was created with the :cdata:`NPY_ITER_GROWINNER` flag, 0 otherwise. .. cfunction:: npy_intp NpyIter_GetBufferSize(NpyIter* iter) If the iterator is buffered, returns the size of the buffer being used, otherwise returns 0. .. cfunction:: int NpyIter_GetNDim(NpyIter* iter) Returns the number of dimensions being iterated. If a multi-index was not requested in the iterator constructor, this value may be smaller than the number of dimensions in the original objects. .. cfunction:: int NpyIter_GetNOp(NpyIter* iter) Returns the number of operands in the iterator. When :cdata:`NPY_ITER_USE_MASKNA` is used on an operand, a new operand is added to the end of the operand list in the iterator to track that operand's NA mask. Thus, this equals the number of construction operands plus the number of operands for which the flag :cdata:`NPY_ITER_USE_MASKNA` was specified. .. cfunction:: int NpyIter_GetFirstMaskNAOp(NpyIter* iter) .. versionadded:: 1.7 Returns the index of the first NA mask operand in the array. This value is equal to the number of operands passed into the constructor. .. cfunction:: npy_intp* NpyIter_GetAxisStrideArray(NpyIter* iter, int axis) Gets the array of strides for the specified axis. Requires that the iterator be tracking a multi-index, and that buffering not be enabled. This may be used when you want to match up operand axes in some fashion, then remove them with :cfunc:`NpyIter_RemoveAxis` to handle their processing manually. By calling this function before removing the axes, you can get the strides for the manual processing. Returns ``NULL`` on error. .. cfunction:: int NpyIter_GetShape(NpyIter* iter, npy_intp* outshape) Returns the broadcast shape of the iterator in ``outshape``. This can only be called on an iterator which is tracking a multi-index. Returns ``NPY_SUCCEED`` or ``NPY_FAIL``. .. cfunction:: PyArray_Descr** NpyIter_GetDescrArray(NpyIter* iter) This gives back a pointer to the ``nop`` data type Descrs for the objects being iterated. The result points into ``iter``, so the caller does not gain any references to the Descrs. This pointer may be cached before the iteration loop, calling ``iternext`` will not change it. .. cfunction:: PyObject** NpyIter_GetOperandArray(NpyIter* iter) This gives back a pointer to the ``nop`` operand PyObjects that are being iterated. The result points into ``iter``, so the caller does not gain any references to the PyObjects. .. cfunction:: npy_int8* NpyIter_GetMaskNAIndexArray(NpyIter* iter) .. versionadded:: 1.7 This gives back a pointer to the ``nop`` indices which map construction operands with :cdata:`NPY_ITER_USE_MASKNA` flagged to their corresponding NA mask operands and vice versa. For operands which were not flagged with :cdata:`NPY_ITER_USE_MASKNA`, this array contains negative values. .. cfunction:: PyObject* NpyIter_GetIterView(NpyIter* iter, npy_intp i) This gives back a reference to a new ndarray view, which is a view into the i-th object in the array :cfunc:`NpyIter_GetOperandArray`(), whose dimensions and strides match the internal optimized iteration pattern. A C-order iteration of this view is equivalent to the iterator's iteration order. For example, if an iterator was created with a single array as its input, and it was possible to rearrange all its axes and then collapse it into a single strided iteration, this would return a view that is a one-dimensional array. .. cfunction:: void NpyIter_GetReadFlags(NpyIter* iter, char* outreadflags) Fills ``nop`` flags. Sets ``outreadflags[i]`` to 1 if ``op[i]`` can be read from, and to 0 if not. .. cfunction:: void NpyIter_GetWriteFlags(NpyIter* iter, char* outwriteflags) Fills ``nop`` flags. Sets ``outwriteflags[i]`` to 1 if ``op[i]`` can be written to, and to 0 if not. .. cfunction:: int NpyIter_CreateCompatibleStrides(NpyIter* iter, npy_intp itemsize, npy_intp* outstrides) Builds a set of strides which are the same as the strides of an output array created using the :cdata:`NPY_ITER_ALLOCATE` flag, where NULL was passed for op_axes. This is for data packed contiguously, but not necessarily in C or Fortran order. This should be used together with :cfunc:`NpyIter_GetShape` and :cfunc:`NpyIter_GetNDim` with the flag :cdata:`NPY_ITER_MULTI_INDEX` passed into the constructor. A use case for this function is to match the shape and layout of the iterator and tack on one or more dimensions. For example, in order to generate a vector per input value for a numerical gradient, you pass in ndim*itemsize for itemsize, then add another dimension to the end with size ndim and stride itemsize. To do the Hessian matrix, you do the same thing but add two dimensions, or take advantage of the symmetry and pack it into 1 dimension with a particular encoding. This function may only be called if the iterator is tracking a multi-index and if :cdata:`NPY_ITER_DONT_NEGATE_STRIDES` was used to prevent an axis from being iterated in reverse order. If an array is created with this method, simply adding 'itemsize' for each iteration will traverse the new array matching the iterator. Returns ``NPY_SUCCEED`` or ``NPY_FAIL``. .. cfunction:: npy_bool NpyIter_IsFirstVisit(NpyIter* iter, int iop) .. versionadded:: 1.7 Checks to see whether this is the first time the elements of the specified reduction operand which the iterator points at are being seen for the first time. The function returns a reasonable answer for reduction operands and when buffering is disabled. The answer may be incorrect for buffered non-reduction operands. This function is intended to be used in EXTERNAL_LOOP mode only, and will produce some wrong answers when that mode is not enabled. If this function returns true, the caller should also check the inner loop stride of the operand, because if that stride is 0, then only the first element of the innermost external loop is being visited for the first time. *WARNING*: For performance reasons, 'iop' is not bounds-checked, it is not confirmed that 'iop' is actually a reduction operand, and it is not confirmed that EXTERNAL_LOOP mode is enabled. These checks are the responsibility of the caller, and should be done outside of any inner loops. Functions For Iteration ----------------------- .. cfunction:: NpyIter_IterNextFunc* NpyIter_GetIterNext(NpyIter* iter, char** errmsg) Returns a function pointer for iteration. A specialized version of the function pointer may be calculated by this function instead of being stored in the iterator structure. Thus, to get good performance, it is required that the function pointer be saved in a variable rather than retrieved for each loop iteration. Returns NULL if there is an error. If errmsg is non-NULL, no Python exception is set when ``NPY_FAIL`` is returned. Instead, \*errmsg is set to an error message. When errmsg is non-NULL, the function may be safely called without holding the Python GIL. The typical looping construct is as follows. .. code-block:: c NpyIter_IterNextFunc *iternext = NpyIter_GetIterNext(iter, NULL); char** dataptr = NpyIter_GetDataPtrArray(iter); do { /* use the addresses dataptr[0], ... dataptr[nop-1] */ } while(iternext(iter)); When :cdata:`NPY_ITER_EXTERNAL_LOOP` is specified, the typical inner loop construct is as follows. .. code-block:: c NpyIter_IterNextFunc *iternext = NpyIter_GetIterNext(iter, NULL); char** dataptr = NpyIter_GetDataPtrArray(iter); npy_intp* stride = NpyIter_GetInnerStrideArray(iter); npy_intp* size_ptr = NpyIter_GetInnerLoopSizePtr(iter), size; npy_intp iop, nop = NpyIter_GetNOp(iter); do { size = *size_ptr; while (size--) { /* use the addresses dataptr[0], ... dataptr[nop-1] */ for (iop = 0; iop < nop; ++iop) { dataptr[iop] += stride[iop]; } } } while (iternext()); Observe that we are using the dataptr array inside the iterator, not copying the values to a local temporary. This is possible because when ``iternext()`` is called, these pointers will be overwritten with fresh values, not incrementally updated. If a compile-time fixed buffer is being used (both flags :cdata:`NPY_ITER_BUFFERED` and :cdata:`NPY_ITER_EXTERNAL_LOOP`), the inner size may be used as a signal as well. The size is guaranteed to become zero when ``iternext()`` returns false, enabling the following loop construct. Note that if you use this construct, you should not pass :cdata:`NPY_ITER_GROWINNER` as a flag, because it will cause larger sizes under some circumstances. .. code-block:: c /* The constructor should have buffersize passed as this value */ #define FIXED_BUFFER_SIZE 1024 NpyIter_IterNextFunc *iternext = NpyIter_GetIterNext(iter, NULL); char **dataptr = NpyIter_GetDataPtrArray(iter); npy_intp *stride = NpyIter_GetInnerStrideArray(iter); npy_intp *size_ptr = NpyIter_GetInnerLoopSizePtr(iter), size; npy_intp i, iop, nop = NpyIter_GetNOp(iter); /* One loop with a fixed inner size */ size = *size_ptr; while (size == FIXED_BUFFER_SIZE) { /* * This loop could be manually unrolled by a factor * which divides into FIXED_BUFFER_SIZE */ for (i = 0; i < FIXED_BUFFER_SIZE; ++i) { /* use the addresses dataptr[0], ... dataptr[nop-1] */ for (iop = 0; iop < nop; ++iop) { dataptr[iop] += stride[iop]; } } iternext(); size = *size_ptr; } /* Finish-up loop with variable inner size */ if (size > 0) do { size = *size_ptr; while (size--) { /* use the addresses dataptr[0], ... dataptr[nop-1] */ for (iop = 0; iop < nop; ++iop) { dataptr[iop] += stride[iop]; } } } while (iternext()); .. cfunction:: NpyIter_GetMultiIndexFunc *NpyIter_GetGetMultiIndex(NpyIter* iter, char** errmsg) Returns a function pointer for getting the current multi-index of the iterator. Returns NULL if the iterator is not tracking a multi-index. It is recommended that this function pointer be cached in a local variable before the iteration loop. Returns NULL if there is an error. If errmsg is non-NULL, no Python exception is set when ``NPY_FAIL`` is returned. Instead, \*errmsg is set to an error message. When errmsg is non-NULL, the function may be safely called without holding the Python GIL. .. cfunction:: char** NpyIter_GetDataPtrArray(NpyIter* iter) This gives back a pointer to the ``nop`` data pointers. If :cdata:`NPY_ITER_EXTERNAL_LOOP` was not specified, each data pointer points to the current data item of the iterator. If no inner iteration was specified, it points to the first data item of the inner loop. This pointer may be cached before the iteration loop, calling ``iternext`` will not change it. This function may be safely called without holding the Python GIL. .. cfunction:: char** NpyIter_GetInitialDataPtrArray(NpyIter* iter) Gets the array of data pointers directly into the arrays (never into the buffers), corresponding to iteration index 0. These pointers are different from the pointers accepted by ``NpyIter_ResetBasePointers``, because the direction along some axes may have been reversed. This function may be safely called without holding the Python GIL. .. cfunction:: npy_intp* NpyIter_GetIndexPtr(NpyIter* iter) This gives back a pointer to the index being tracked, or NULL if no index is being tracked. It is only useable if one of the flags :cdata:`NPY_ITER_C_INDEX` or :cdata:`NPY_ITER_F_INDEX` were specified during construction. When the flag :cdata:`NPY_ITER_EXTERNAL_LOOP` is used, the code needs to know the parameters for doing the inner loop. These functions provide that information. .. cfunction:: npy_intp* NpyIter_GetInnerStrideArray(NpyIter* iter) Returns a pointer to an array of the ``nop`` strides, one for each iterated object, to be used by the inner loop. This pointer may be cached before the iteration loop, calling ``iternext`` will not change it. This function may be safely called without holding the Python GIL. .. cfunction:: npy_intp* NpyIter_GetInnerLoopSizePtr(NpyIter* iter) Returns a pointer to the number of iterations the inner loop should execute. This address may be cached before the iteration loop, calling ``iternext`` will not change it. The value itself may change during iteration, in particular if buffering is enabled. This function may be safely called without holding the Python GIL. .. cfunction:: void NpyIter_GetInnerFixedStrideArray(NpyIter* iter, npy_intp* out_strides) Gets an array of strides which are fixed, or will not change during the entire iteration. For strides that may change, the value NPY_MAX_INTP is placed in the stride. Once the iterator is prepared for iteration (after a reset if :cdata:`NPY_DELAY_BUFALLOC` was used), call this to get the strides which may be used to select a fast inner loop function. For example, if the stride is 0, that means the inner loop can always load its value into a variable once, then use the variable throughout the loop, or if the stride equals the itemsize, a contiguous version for that operand may be used. This function may be safely called without holding the Python GIL. .. index:: pair: iterator; C-API numpy-1.8.2/doc/source/reference/routines.err.rst0000664000175100017510000000056012370216242023220 0ustar vagrantvagrant00000000000000Floating point error handling ***************************** .. currentmodule:: numpy Setting and getting error handling ---------------------------------- .. autosummary:: :toctree: generated/ seterr geterr seterrcall geterrcall errstate Internal functions ------------------ .. autosummary:: :toctree: generated/ seterrobj geterrobj numpy-1.8.2/doc/source/reference/arrays.interface.rst0000664000175100017510000003274012370216242024026 0ustar vagrantvagrant00000000000000.. index:: pair: array; interface pair: array; protocol .. _arrays.interface: ******************* The Array Interface ******************* .. note:: This page describes the numpy-specific API for accessing the contents of a numpy array from other C extensions. :pep:`3118` -- :cfunc:`The Revised Buffer Protocol ` introduces similar, standardized API to Python 2.6 and 3.0 for any extension module to use. Cython__'s buffer array support uses the :pep:`3118` API; see the `Cython numpy tutorial`__. Cython provides a way to write code that supports the buffer protocol with Python versions older than 2.6 because it has a backward-compatible implementation utilizing the array interface described here. __ http://cython.org/ __ http://wiki.cython.org/tutorials/numpy :version: 3 The array interface (sometimes called array protocol) was created in 2005 as a means for array-like Python objects to re-use each other's data buffers intelligently whenever possible. The homogeneous N-dimensional array interface is a default mechanism for objects to share N-dimensional array memory and information. The interface consists of a Python-side and a C-side using two attributes. Objects wishing to be considered an N-dimensional array in application code should support at least one of these attributes. Objects wishing to support an N-dimensional array in application code should look for at least one of these attributes and use the information provided appropriately. This interface describes homogeneous arrays in the sense that each item of the array has the same "type". This type can be very simple or it can be a quite arbitrary and complicated C-like structure. There are two ways to use the interface: A Python side and a C-side. Both are separate attributes. Python side =========== This approach to the interface consists of the object having an :data:`__array_interface__` attribute. .. data:: __array_interface__ A dictionary of items (3 required and 5 optional). The optional keys in the dictionary have implied defaults if they are not provided. The keys are: **shape** (required) Tuple whose elements are the array size in each dimension. Each entry is an integer (a Python int or long). Note that these integers could be larger than the platform "int" or "long" could hold (a Python int is a C long). It is up to the code using this attribute to handle this appropriately; either by raising an error when overflow is possible, or by using :cdata:`Py_LONG_LONG` as the C type for the shapes. **typestr** (required) A string providing the basic type of the homogenous array The basic string format consists of 3 parts: a character describing the byteorder of the data (``<``: little-endian, ``>``: big-endian, ``|``: not-relevant), a character code giving the basic type of the array, and an integer providing the number of bytes the type uses. The basic type character codes are: ===== ================================================================ ``t`` Bit field (following integer gives the number of bits in the bit field). ``b`` Boolean (integer type where all values are only True or False) ``i`` Integer ``u`` Unsigned integer ``f`` Floating point ``c`` Complex floating point ``O`` Object (i.e. the memory contains a pointer to :ctype:`PyObject`) ``S`` String (fixed-length sequence of char) ``U`` Unicode (fixed-length sequence of :ctype:`Py_UNICODE`) ``V`` Other (void \* -- each item is a fixed-size chunk of memory) ===== ================================================================ **descr** (optional) A list of tuples providing a more detailed description of the memory layout for each item in the homogeneous array. Each tuple in the list has two or three elements. Normally, this attribute would be used when *typestr* is ``V[0-9]+``, but this is not a requirement. The only requirement is that the number of bytes represented in the *typestr* key is the same as the total number of bytes represented here. The idea is to support descriptions of C-like structs (records) that make up array elements. The elements of each tuple in the list are 1. A string providing a name associated with this portion of the record. This could also be a tuple of ``('full name', 'basic_name')`` where basic name would be a valid Python variable name representing the full name of the field. 2. Either a basic-type description string as in *typestr* or another list (for nested records) 3. An optional shape tuple providing how many times this part of the record should be repeated. No repeats are assumed if this is not given. Very complicated structures can be described using this generic interface. Notice, however, that each element of the array is still of the same data-type. Some examples of using this interface are given below. **Default**: ``[('', typestr)]`` **data** (optional) A 2-tuple whose first argument is an integer (a long integer if necessary) that points to the data-area storing the array contents. This pointer must point to the first element of data (in other words any offset is always ignored in this case). The second entry in the tuple is a read-only flag (true means the data area is read-only). This attribute can also be an object exposing the :cfunc:`buffer interface ` which will be used to share the data. If this key is not present (or returns :class:`None`), then memory sharing will be done through the buffer interface of the object itself. In this case, the offset key can be used to indicate the start of the buffer. A reference to the object exposing the array interface must be stored by the new object if the memory area is to be secured. **Default**: :const:`None` **strides** (optional) Either :const:`None` to indicate a C-style contiguous array or a Tuple of strides which provides the number of bytes needed to jump to the next array element in the corresponding dimension. Each entry must be an integer (a Python :const:`int` or :const:`long`). As with shape, the values may be larger than can be represented by a C "int" or "long"; the calling code should handle this appropiately, either by raising an error, or by using :ctype:`Py_LONG_LONG` in C. The default is :const:`None` which implies a C-style contiguous memory buffer. In this model, the last dimension of the array varies the fastest. For example, the default strides tuple for an object whose array entries are 8 bytes long and whose shape is (10,20,30) would be (4800, 240, 8) **Default**: :const:`None` (C-style contiguous) **mask** (optional) :const:`None` or an object exposing the array interface. All elements of the mask array should be interpreted only as true or not true indicating which elements of this array are valid. The shape of this object should be `"broadcastable" ` to the shape of the original array. **Default**: :const:`None` (All array values are valid) **offset** (optional) An integer offset into the array data region. This can only be used when data is :const:`None` or returns a :class:`buffer` object. **Default**: 0. **version** (required) An integer showing the version of the interface (i.e. 3 for this version). Be careful not to use this to invalidate objects exposing future versions of the interface. C-struct access =============== This approach to the array interface allows for faster access to an array using only one attribute lookup and a well-defined C-structure. .. cvar:: __array_struct__ A :ctype:`PyCObject` whose :cdata:`voidptr` member contains a pointer to a filled :ctype:`PyArrayInterface` structure. Memory for the structure is dynamically created and the :ctype:`PyCObject` is also created with an appropriate destructor so the retriever of this attribute simply has to apply :cfunc:`Py_DECREF()` to the object returned by this attribute when it is finished. Also, either the data needs to be copied out, or a reference to the object exposing this attribute must be held to ensure the data is not freed. Objects exposing the :obj:`__array_struct__` interface must also not reallocate their memory if other objects are referencing them. The PyArrayInterface structure is defined in ``numpy/ndarrayobject.h`` as:: typedef struct { int two; /* contains the integer 2 -- simple sanity check */ int nd; /* number of dimensions */ char typekind; /* kind in array --- character code of typestr */ int itemsize; /* size of each element */ int flags; /* flags indicating how the data should be interpreted */ /* must set ARR_HAS_DESCR bit to validate descr */ Py_intptr_t *shape; /* A length-nd array of shape information */ Py_intptr_t *strides; /* A length-nd array of stride information */ void *data; /* A pointer to the first element of the array */ PyObject *descr; /* NULL or data-description (same as descr key of __array_interface__) -- must set ARR_HAS_DESCR flag or this will be ignored. */ } PyArrayInterface; The flags member may consist of 5 bits showing how the data should be interpreted and one bit showing how the Interface should be interpreted. The data-bits are :const:`CONTIGUOUS` (0x1), :const:`FORTRAN` (0x2), :const:`ALIGNED` (0x100), :const:`NOTSWAPPED` (0x200), and :const:`WRITEABLE` (0x400). A final flag :const:`ARR_HAS_DESCR` (0x800) indicates whether or not this structure has the arrdescr field. The field should not be accessed unless this flag is present. .. admonition:: New since June 16, 2006: In the past most implementations used the "desc" member of the :ctype:`PyCObject` itself (do not confuse this with the "descr" member of the :ctype:`PyArrayInterface` structure above --- they are two separate things) to hold the pointer to the object exposing the interface. This is now an explicit part of the interface. Be sure to own a reference to the object when the :ctype:`PyCObject` is created using :ctype:`PyCObject_FromVoidPtrAndDesc`. Type description examples ========================= For clarity it is useful to provide some examples of the type description and corresponding :data:`__array_interface__` 'descr' entries. Thanks to Scott Gilbert for these examples: In every case, the 'descr' key is optional, but of course provides more information which may be important for various applications:: * Float data typestr == '>f4' descr == [('','>f4')] * Complex double typestr == '>c8' descr == [('real','>f4'), ('imag','>f4')] * RGB Pixel data typestr == '|V3' descr == [('r','|u1'), ('g','|u1'), ('b','|u1')] * Mixed endian (weird but could happen). typestr == '|V8' (or '>u8') descr == [('big','>i4'), ('little','i4'), ('data','>f8',(16,4))] * Padded structure struct { int ival; double dval; } typestr == '|V16' descr == [('ival','>i4'),('','|V4'),('dval','>f8')] It should be clear that any record type could be described using this interface. Differences with Array interface (Version 2) ============================================ The version 2 interface was very similar. The differences were largely asthetic. In particular: 1. The PyArrayInterface structure had no descr member at the end (and therefore no flag ARR_HAS_DESCR) 2. The desc member of the PyCObject returned from __array_struct__ was not specified. Usually, it was the object exposing the array (so that a reference to it could be kept and destroyed when the C-object was destroyed). Now it must be a tuple whose first element is a string with "PyArrayInterface Version #" and whose second element is the object exposing the array. 3. The tuple returned from __array_interface__['data'] used to be a hex-string (now it is an integer or a long integer). 4. There was no __array_interface__ attribute instead all of the keys (except for version) in the __array_interface__ dictionary were their own attribute: Thus to obtain the Python-side information you had to access separately the attributes: * __array_data__ * __array_shape__ * __array_strides__ * __array_typestr__ * __array_descr__ * __array_offset__ * __array_mask__ numpy-1.8.2/doc/source/reference/routines.polynomials.rst0000664000175100017510000000174212370216242025001 0ustar vagrantvagrant00000000000000Polynomials *********** Polynomials in NumPy can be *created*, *manipulated*, and even *fitted* using the :doc:`routines.polynomials.classes` of the `numpy.polynomial` package, introduced in NumPy 1.4. Prior to NumPy 1.4, `numpy.poly1d` was the class of choice and it is still available in order to maintain backward compatibility. However, the newer Polynomial package is more complete than `numpy.poly1d` and its convenience classes are better behaved in the numpy environment. Therefore Polynomial is recommended for new coding. Transition notice ----------------- The various routines in the Polynomial package all deal with series whose coefficients go from degree zero upward, which is the *reverse order* of the Poly1d convention. The easy way to remember this is that indexes correspond to degree, i.e., coef[i] is the coefficient of the term of degree i. .. toctree:: :maxdepth: 2 routines.polynomials.package .. toctree:: :maxdepth: 2 routines.polynomials.poly1d numpy-1.8.2/doc/source/reference/c-api.dtype.rst0000664000175100017510000002433712370216242022706 0ustar vagrantvagrant00000000000000Data Type API ============= .. sectionauthor:: Travis E. Oliphant The standard array can have 24 different data types (and has some support for adding your own types). These data types all have an enumerated type, an enumerated type-character, and a corresponding array scalar Python type object (placed in a hierarchy). There are also standard C typedefs to make it easier to manipulate elements of the given data type. For the numeric types, there are also bit-width equivalent C typedefs and named typenumbers that make it easier to select the precision desired. .. warning:: The names for the types in c code follows c naming conventions more closely. The Python names for these types follow Python conventions. Thus, :cdata:`NPY_FLOAT` picks up a 32-bit float in C, but :class:`numpy.float_` in Python corresponds to a 64-bit double. The bit-width names can be used in both Python and C for clarity. Enumerated Types ---------------- There is a list of enumerated types defined providing the basic 24 data types plus some useful generic names. Whenever the code requires a type number, one of these enumerated types is requested. The types are all called :cdata:`NPY_{NAME}`: .. cvar:: NPY_BOOL The enumeration value for the boolean type, stored as one byte. It may only be set to the values 0 and 1. .. cvar:: NPY_BYTE .. cvar:: NPY_INT8 The enumeration value for an 8-bit/1-byte signed integer. .. cvar:: NPY_SHORT .. cvar:: NPY_INT16 The enumeration value for a 16-bit/2-byte signed integer. .. cvar:: NPY_INT .. cvar:: NPY_INT32 The enumeration value for a 32-bit/4-byte signed integer. .. cvar:: NPY_LONG Equivalent to either NPY_INT or NPY_LONGLONG, depending on the platform. .. cvar:: NPY_LONGLONG .. cvar:: NPY_INT64 The enumeration value for a 64-bit/8-byte signed integer. .. cvar:: NPY_UBYTE .. cvar:: NPY_UINT8 The enumeration value for an 8-bit/1-byte unsigned integer. .. cvar:: NPY_USHORT .. cvar:: NPY_UINT16 The enumeration value for a 16-bit/2-byte unsigned integer. .. cvar:: NPY_UINT .. cvar:: NPY_UINT32 The enumeration value for a 32-bit/4-byte unsigned integer. .. cvar:: NPY_ULONG Equivalent to either NPY_UINT or NPY_ULONGLONG, depending on the platform. .. cvar:: NPY_ULONGLONG .. cvar:: NPY_UINT64 The enumeration value for a 64-bit/8-byte unsigned integer. .. cvar:: NPY_HALF .. cvar:: NPY_FLOAT16 The enumeration value for a 16-bit/2-byte IEEE 754-2008 compatible floating point type. .. cvar:: NPY_FLOAT .. cvar:: NPY_FLOAT32 The enumeration value for a 32-bit/4-byte IEEE 754 compatible floating point type. .. cvar:: NPY_DOUBLE .. cvar:: NPY_FLOAT64 The enumeration value for a 64-bit/8-byte IEEE 754 compatible floating point type. .. cvar:: NPY_LONGDOUBLE The enumeration value for a platform-specific floating point type which is at least as large as NPY_DOUBLE, but larger on many platforms. .. cvar:: NPY_CFLOAT .. cvar:: NPY_COMPLEX64 The enumeration value for a 64-bit/8-byte complex type made up of two NPY_FLOAT values. .. cvar:: NPY_CDOUBLE .. cvar:: NPY_COMPLEX128 The enumeration value for a 128-bit/16-byte complex type made up of two NPY_DOUBLE values. .. cvar:: NPY_CLONGDOUBLE The enumeration value for a platform-specific complex floating point type which is made up of two NPY_LONGDOUBLE values. .. cvar:: NPY_DATETIME The enumeration value for a data type which holds dates or datetimes with a precision based on selectable date or time units. .. cvar:: NPY_TIMEDELTA The enumeration value for a data type which holds lengths of times in integers of selectable date or time units. .. cvar:: NPY_STRING The enumeration value for ASCII strings of a selectable size. The strings have a fixed maximum size within a given array. .. cvar:: NPY_UNICODE The enumeration value for UCS4 strings of a selectable size. The strings have a fixed maximum size within a given array. .. cvar:: NPY_OBJECT The enumeration value for references to arbitrary Python objects. .. cvar:: NPY_VOID Primarily used to hold struct dtypes, but can contain arbitrary binary data. Some useful aliases of the above types are .. cvar:: NPY_INTP The enumeration value for a signed integer type which is the same size as a (void \*) pointer. This is the type used by all arrays of indices. .. cvar:: NPY_UINTP The enumeration value for an unsigned integer type which is the same size as a (void \*) pointer. .. cvar:: NPY_MASK The enumeration value of the type used for masks, such as with the :cdata:`NPY_ITER_ARRAYMASK` iterator flag. This is equivalent to :cdata:`NPY_UINT8`. .. cvar:: NPY_DEFAULT_TYPE The default type to use when no dtype is explicitly specified, for example when calling np.zero(shape). This is equivalent to :cdata:`NPY_DOUBLE`. Other useful related constants are .. cvar:: NPY_NTYPES The total number of built-in NumPy types. The enumeration covers the range from 0 to NPY_NTYPES-1. .. cvar:: NPY_NOTYPE A signal value guaranteed not to be a valid type enumeration number. .. cvar:: NPY_USERDEF The start of type numbers used for Custom Data types. The various character codes indicating certain types are also part of an enumerated list. References to type characters (should they be needed at all) should always use these enumerations. The form of them is :cdata:`NPY_{NAME}LTR` where ``{NAME}`` can be **BOOL**, **BYTE**, **UBYTE**, **SHORT**, **USHORT**, **INT**, **UINT**, **LONG**, **ULONG**, **LONGLONG**, **ULONGLONG**, **HALF**, **FLOAT**, **DOUBLE**, **LONGDOUBLE**, **CFLOAT**, **CDOUBLE**, **CLONGDOUBLE**, **DATETIME**, **TIMEDELTA**, **OBJECT**, **STRING**, **VOID** **INTP**, **UINTP** **GENBOOL**, **SIGNED**, **UNSIGNED**, **FLOATING**, **COMPLEX** The latter group of ``{NAME}s`` corresponds to letters used in the array interface typestring specification. Defines ------- Max and min values for integers ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ .. cvar:: NPY_MAX_INT{bits} .. cvar:: NPY_MAX_UINT{bits} .. cvar:: NPY_MIN_INT{bits} These are defined for ``{bits}`` = 8, 16, 32, 64, 128, and 256 and provide the maximum (minimum) value of the corresponding (unsigned) integer type. Note: the actual integer type may not be available on all platforms (i.e. 128-bit and 256-bit integers are rare). .. cvar:: NPY_MIN_{type} This is defined for ``{type}`` = **BYTE**, **SHORT**, **INT**, **LONG**, **LONGLONG**, **INTP** .. cvar:: NPY_MAX_{type} This is defined for all defined for ``{type}`` = **BYTE**, **UBYTE**, **SHORT**, **USHORT**, **INT**, **UINT**, **LONG**, **ULONG**, **LONGLONG**, **ULONGLONG**, **INTP**, **UINTP** Number of bits in data types ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ All :cdata:`NPY_SIZEOF_{CTYPE}` constants have corresponding :cdata:`NPY_BITSOF_{CTYPE}` constants defined. The :cdata:`NPY_BITSOF_{CTYPE}` constants provide the number of bits in the data type. Specifically, the available ``{CTYPE}s`` are **BOOL**, **CHAR**, **SHORT**, **INT**, **LONG**, **LONGLONG**, **FLOAT**, **DOUBLE**, **LONGDOUBLE** Bit-width references to enumerated typenums ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ All of the numeric data types (integer, floating point, and complex) have constants that are defined to be a specific enumerated type number. Exactly which enumerated type a bit-width type refers to is platform dependent. In particular, the constants available are :cdata:`PyArray_{NAME}{BITS}` where ``{NAME}`` is **INT**, **UINT**, **FLOAT**, **COMPLEX** and ``{BITS}`` can be 8, 16, 32, 64, 80, 96, 128, 160, 192, 256, and 512. Obviously not all bit-widths are available on all platforms for all the kinds of numeric types. Commonly 8-, 16-, 32-, 64-bit integers; 32-, 64-bit floats; and 64-, 128-bit complex types are available. Integer that can hold a pointer ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ The constants **NPY_INTP** and **NPY_UINTP** refer to an enumerated integer type that is large enough to hold a pointer on the platform. Index arrays should always be converted to **NPY_INTP** , because the dimension of the array is of type npy_intp. C-type names ------------ There are standard variable types for each of the numeric data types and the bool data type. Some of these are already available in the C-specification. You can create variables in extension code with these types. Boolean ^^^^^^^ .. ctype:: npy_bool unsigned char; The constants :cdata:`NPY_FALSE` and :cdata:`NPY_TRUE` are also defined. (Un)Signed Integer ^^^^^^^^^^^^^^^^^^ Unsigned versions of the integers can be defined by pre-pending a 'u' to the front of the integer name. .. ctype:: npy_(u)byte (unsigned) char .. ctype:: npy_(u)short (unsigned) short .. ctype:: npy_(u)int (unsigned) int .. ctype:: npy_(u)long (unsigned) long int .. ctype:: npy_(u)longlong (unsigned long long int) .. ctype:: npy_(u)intp (unsigned) Py_intptr_t (an integer that is the size of a pointer on the platform). (Complex) Floating point ^^^^^^^^^^^^^^^^^^^^^^^^ .. ctype:: npy_(c)float float .. ctype:: npy_(c)double double .. ctype:: npy_(c)longdouble long double complex types are structures with **.real** and **.imag** members (in that order). Bit-width names ^^^^^^^^^^^^^^^ There are also typedefs for signed integers, unsigned integers, floating point, and complex floating point types of specific bit- widths. The available type names are :ctype:`npy_int{bits}`, :ctype:`npy_uint{bits}`, :ctype:`npy_float{bits}`, and :ctype:`npy_complex{bits}` where ``{bits}`` is the number of bits in the type and can be **8**, **16**, **32**, **64**, 128, and 256 for integer types; 16, **32** , **64**, 80, 96, 128, and 256 for floating-point types; and 32, **64**, **128**, 160, 192, and 512 for complex-valued types. Which bit-widths are available is platform dependent. The bolded bit-widths are usually available on all platforms. Printf Formatting ----------------- For help in printing, the following strings are defined as the correct format specifier in printf and related commands. :cdata:`NPY_LONGLONG_FMT`, :cdata:`NPY_ULONGLONG_FMT`, :cdata:`NPY_INTP_FMT`, :cdata:`NPY_UINTP_FMT`, :cdata:`NPY_LONGDOUBLE_FMT` numpy-1.8.2/doc/source/reference/routines.dtype.rst0000664000175100017510000000131212370216242023551 0ustar vagrantvagrant00000000000000.. _routines.dtype: Data type routines ================== .. currentmodule:: numpy .. autosummary:: :toctree: generated/ can_cast promote_types min_scalar_type result_type common_type obj2sctype Creating data types ------------------- .. autosummary:: :toctree: generated/ dtype format_parser Data type information --------------------- .. autosummary:: :toctree: generated/ finfo iinfo MachAr Data type testing ----------------- .. autosummary:: :toctree: generated/ issctype issubdtype issubsctype issubclass_ find_common_type Miscellaneous ------------- .. autosummary:: :toctree: generated/ typename sctype2char mintypecode numpy-1.8.2/doc/source/reference/arrays.indexing.rst0000664000175100017510000003540312370216243023673 0ustar vagrantvagrant00000000000000.. _arrays.indexing: Indexing ======== .. sectionauthor:: adapted from "Guide to Numpy" by Travis E. Oliphant .. currentmodule:: numpy .. index:: indexing, slicing :class:`ndarrays ` can be indexed using the standard Python ``x[obj]`` syntax, where *x* is the array and *obj* the selection. There are three kinds of indexing available: record access, basic slicing, advanced indexing. Which one occurs depends on *obj*. .. note:: In Python, ``x[(exp1, exp2, ..., expN)]`` is equivalent to ``x[exp1, exp2, ..., expN]``; the latter is just syntactic sugar for the former. Basic Slicing ------------- Basic slicing extends Python's basic concept of slicing to N dimensions. Basic slicing occurs when *obj* is a :class:`slice` object (constructed by ``start:stop:step`` notation inside of brackets), an integer, or a tuple of slice objects and integers. :const:`Ellipsis` and :const:`newaxis` objects can be interspersed with these as well. In order to remain backward compatible with a common usage in Numeric, basic slicing is also initiated if the selection object is any sequence (such as a :class:`list`) containing :class:`slice` objects, the :const:`Ellipsis` object, or the :const:`newaxis` object, but no integer arrays or other embedded sequences. .. index:: triple: ndarray; special methods; getslice triple: ndarray; special methods; setslice single: ellipsis single: newaxis The simplest case of indexing with *N* integers returns an :ref:`array scalar ` representing the corresponding item. As in Python, all indices are zero-based: for the *i*-th index :math:`n_i`, the valid range is :math:`0 \le n_i < d_i` where :math:`d_i` is the *i*-th element of the shape of the array. Negative indices are interpreted as counting from the end of the array (*i.e.*, if *i < 0*, it means :math:`n_i + i`). All arrays generated by basic slicing are always :term:`views ` of the original array. The standard rules of sequence slicing apply to basic slicing on a per-dimension basis (including using a step index). Some useful concepts to remember include: - The basic slice syntax is ``i:j:k`` where *i* is the starting index, *j* is the stopping index, and *k* is the step (:math:`k\neq0`). This selects the *m* elements (in the corresponding dimension) with index values *i*, *i + k*, ..., *i + (m - 1) k* where :math:`m = q + (r\neq0)` and *q* and *r* are the quotient and remainder obtained by dividing *j - i* by *k*: *j - i = q k + r*, so that *i + (m - 1) k < j*. .. admonition:: Example >>> x = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) >>> x[1:7:2] array([1, 3, 5]) - Negative *i* and *j* are interpreted as *n + i* and *n + j* where *n* is the number of elements in the corresponding dimension. Negative *k* makes stepping go towards smaller indices. .. admonition:: Example >>> x[-2:10] array([8, 9]) >>> x[-3:3:-1] array([7, 6, 5, 4]) - Assume *n* is the number of elements in the dimension being sliced. Then, if *i* is not given it defaults to 0 for *k > 0* and *n* for *k < 0* . If *j* is not given it defaults to *n* for *k > 0* and -1 for *k < 0* . If *k* is not given it defaults to 1. Note that ``::`` is the same as ``:`` and means select all indices along this axis. .. admonition:: Example >>> x[5:] array([5, 6, 7, 8, 9]) - If the number of objects in the selection tuple is less than *N* , then ``:`` is assumed for any subsequent dimensions. .. admonition:: Example >>> x = np.array([[[1],[2],[3]], [[4],[5],[6]]]) >>> x.shape (2, 3, 1) >>> x[1:2] array([[[4], [5], [6]]]) - :const:`Ellipsis` expand to the number of ``:`` objects needed to make a selection tuple of the same length as ``x.ndim``. Only the first ellipsis is expanded, any others are interpreted as ``:``. .. admonition:: Example >>> x[...,0] array([[1, 2, 3], [4, 5, 6]]) - Each :const:`newaxis` object in the selection tuple serves to expand the dimensions of the resulting selection by one unit-length dimension. The added dimension is the position of the :const:`newaxis` object in the selection tuple. .. admonition:: Example >>> x[:,np.newaxis,:,:].shape (2, 1, 3, 1) - An integer, *i*, returns the same values as ``i:i+1`` **except** the dimensionality of the returned object is reduced by 1. In particular, a selection tuple with the *p*-th element an integer (and all other entries ``:``) returns the corresponding sub-array with dimension *N - 1*. If *N = 1* then the returned object is an array scalar. These objects are explained in :ref:`arrays.scalars`. - If the selection tuple has all entries ``:`` except the *p*-th entry which is a slice object ``i:j:k``, then the returned array has dimension *N* formed by concatenating the sub-arrays returned by integer indexing of elements *i*, *i+k*, ..., *i + (m - 1) k < j*, - Basic slicing with more than one non-``:`` entry in the slicing tuple, acts like repeated application of slicing using a single non-``:`` entry, where the non-``:`` entries are successively taken (with all other non-``:`` entries replaced by ``:``). Thus, ``x[ind1,...,ind2,:]`` acts like ``x[ind1][...,ind2,:]`` under basic slicing. .. warning:: The above is **not** true for advanced slicing. - You may use slicing to set values in the array, but (unlike lists) you can never grow the array. The size of the value to be set in ``x[obj] = value`` must be (broadcastable) to the same shape as ``x[obj]``. .. index:: pair: ndarray; view .. note:: Remember that a slicing tuple can always be constructed as *obj* and used in the ``x[obj]`` notation. Slice objects can be used in the construction in place of the ``[start:stop:step]`` notation. For example, ``x[1:10:5,::-1]`` can also be implemented as ``obj = (slice(1,10,5), slice(None,None,-1)); x[obj]`` . This can be useful for constructing generic code that works on arrays of arbitrary dimension. .. data:: newaxis The :const:`newaxis` object can be used in all slicing operations as discussed above. :const:`None` can also be used instead of :const:`newaxis`. Advanced indexing ----------------- Advanced indexing is triggered when the selection object, *obj*, is a non-tuple sequence object, an :class:`ndarray` (of data type integer or bool), or a tuple with at least one sequence object or ndarray (of data type integer or bool). There are two types of advanced indexing: integer and Boolean. Advanced indexing always returns a *copy* of the data (contrast with basic slicing that returns a :term:`view`). Integer ^^^^^^^ Integer indexing allows selection of arbitrary items in the array based on their *N*-dimensional index. This kind of selection occurs when advanced indexing is triggered and the selection object is not an array of data type bool. For the discussion below, when the selection object is not a tuple, it will be referred to as if it had been promoted to a 1-tuple, which will be called the selection tuple. The rules of advanced integer-style indexing are: - If the length of the selection tuple is larger than *N* an error is raised. - All sequences and scalars in the selection tuple are converted to :class:`intp` indexing arrays. - All selection tuple objects must be convertible to :class:`intp` arrays, :class:`slice` objects, or the :const:`Ellipsis` object. - The first :const:`Ellipsis` object will be expanded, and any other :const:`Ellipsis` objects will be treated as full slice (``:``) objects. The expanded :const:`Ellipsis` object is replaced with as many full slice (``:``) objects as needed to make the length of the selection tuple :math:`N`. - If the selection tuple is smaller than *N*, then as many ``:`` objects as needed are added to the end of the selection tuple so that the modified selection tuple has length *N*. - All the integer indexing arrays must be :ref:`broadcastable ` to the same shape. - The shape of the output (or the needed shape of the object to be used for setting) is the broadcasted shape. - After expanding any ellipses and filling out any missing ``:`` objects in the selection tuple, then let :math:`N_t` be the number of indexing arrays, and let :math:`N_s = N - N_t` be the number of slice objects. Note that :math:`N_t > 0` (or we wouldn't be doing advanced integer indexing). - If :math:`N_s = 0` then the *M*-dimensional result is constructed by varying the index tuple ``(i_1, ..., i_M)`` over the range of the result shape and for each value of the index tuple ``(ind_1, ..., ind_M)``:: result[i_1, ..., i_M] == x[ind_1[i_1, ..., i_M], ind_2[i_1, ..., i_M], ..., ind_N[i_1, ..., i_M]] .. admonition:: Example Suppose the shape of the broadcasted indexing arrays is 3-dimensional and *N* is 2. Then the result is found by letting *i, j, k* run over the shape found by broadcasting ``ind_1`` and ``ind_2``, and each *i, j, k* yields:: result[i,j,k] = x[ind_1[i,j,k], ind_2[i,j,k]] - If :math:`N_s > 0`, then partial indexing is done. This can be somewhat mind-boggling to understand, but if you think in terms of the shapes of the arrays involved, it can be easier to grasp what happens. In simple cases (*i.e.* one indexing array and *N - 1* slice objects) it does exactly what you would expect (concatenation of repeated application of basic slicing). The rule for partial indexing is that the shape of the result (or the interpreted shape of the object to be used in setting) is the shape of *x* with the indexed subspace replaced with the broadcasted indexing subspace. If the index subspaces are right next to each other, then the broadcasted indexing space directly replaces all of the indexed subspaces in *x*. If the indexing subspaces are separated (by slice objects), then the broadcasted indexing space is first, followed by the sliced subspace of *x*. .. admonition:: Example Suppose ``x.shape`` is (10,20,30) and ``ind`` is a (2,3,4)-shaped indexing :class:`intp` array, then ``result = x[...,ind,:]`` has shape (10,2,3,4,30) because the (20,)-shaped subspace has been replaced with a (2,3,4)-shaped broadcasted indexing subspace. If we let *i, j, k* loop over the (2,3,4)-shaped subspace then ``result[...,i,j,k,:] = x[...,ind[i,j,k],:]``. This example produces the same result as :meth:`x.take(ind, axis=-2) `. .. admonition:: Example Now let ``x.shape`` be (10,20,30,40,50) and suppose ``ind_1`` and ``ind_2`` are broadcastable to the shape (2,3,4). Then ``x[:,ind_1,ind_2]`` has shape (10,2,3,4,40,50) because the (20,30)-shaped subspace from X has been replaced with the (2,3,4) subspace from the indices. However, ``x[:,ind_1,:,ind_2]`` has shape (2,3,4,10,30,50) because there is no unambiguous place to drop in the indexing subspace, thus it is tacked-on to the beginning. It is always possible to use :meth:`.transpose() ` to move the subspace anywhere desired. (Note that this example cannot be replicated using :func:`take`.) Boolean ^^^^^^^ This advanced indexing occurs when obj is an array object of Boolean type (such as may be returned from comparison operators). It is always equivalent to (but faster than) ``x[obj.nonzero()]`` where, as described above, :meth:`obj.nonzero() ` returns a tuple (of length :attr:`obj.ndim `) of integer index arrays showing the :const:`True` elements of *obj*. The special case when ``obj.ndim == x.ndim`` is worth mentioning. In this case ``x[obj]`` returns a 1-dimensional array filled with the elements of *x* corresponding to the :const:`True` values of *obj*. The search order will be C-style (last index varies the fastest). If *obj* has :const:`True` values at entries that are outside of the bounds of *x*, then an index error will be raised. You can also use Boolean arrays as element of the selection tuple. In such instances, they will always be interpreted as :meth:`nonzero(obj) ` and the equivalent integer indexing will be done. .. warning:: The definition of advanced indexing means that ``x[(1,2,3),]`` is fundamentally different than ``x[(1,2,3)]``. The latter is equivalent to ``x[1,2,3]`` which will trigger basic selection while the former will trigger advanced indexing. Be sure to understand why this is occurs. Also recognize that ``x[[1,2,3]]`` will trigger advanced indexing, whereas ``x[[1,2,slice(None)]]`` will trigger basic slicing. .. _arrays.indexing.rec: Record Access ------------- .. seealso:: :ref:`arrays.dtypes`, :ref:`arrays.scalars` If the :class:`ndarray` object is a record array, *i.e.* its data type is a :term:`record` data type, the :term:`fields ` of the array can be accessed by indexing the array with strings, dictionary-like. Indexing ``x['field-name']`` returns a new :term:`view` to the array, which is of the same shape as *x* (except when the field is a sub-array) but of data type ``x.dtype['field-name']`` and contains only the part of the data in the specified field. Also record array scalars can be "indexed" this way. Indexing into a record array can also be done with a list of field names, *e.g.* ``x[['field-name1','field-name2']]``. Currently this returns a new array containing a copy of the values in the fields specified in the list. As of NumPy 1.7, returning a copy is being deprecated in favor of returning a view. A copy will continue to be returned for now, but a FutureWarning will be issued when writing to the copy. If you depend on the current behavior, then we suggest copying the returned array explicitly, i.e. use x[['field-name1','field-name2']].copy(). This will work with both past and future versions of NumPy. If the accessed field is a sub-array, the dimensions of the sub-array are appended to the shape of the result. .. admonition:: Example >>> x = np.zeros((2,2), dtype=[('a', np.int32), ('b', np.float64, (3,3))]) >>> x['a'].shape (2, 2) >>> x['a'].dtype dtype('int32') >>> x['b'].shape (2, 2, 3, 3) >>> x['b'].dtype dtype('float64') Flat Iterator indexing ---------------------- :attr:`x.flat ` returns an iterator that will iterate over the entire array (in C-contiguous style with the last index varying the fastest). This iterator object can also be indexed using basic slicing or advanced indexing as long as the selection object is not a tuple. This should be clear from the fact that :attr:`x.flat ` is a 1-dimensional view. It can be used for integer indexing with 1-dimensional C-style-flat indices. The shape of any returned array is therefore the shape of the integer indexing object. .. index:: single: indexing single: ndarray numpy-1.8.2/doc/source/reference/routines.numarray.rst0000664000175100017510000000025512370216243024270 0ustar vagrantvagrant00000000000000********************************************** Numarray compatibility (:mod:`numpy.numarray`) ********************************************** .. automodule:: numpy.numarray numpy-1.8.2/doc/source/reference/routines.polynomials.hermite.rst0000664000175100017510000000253712370216242026440 0ustar vagrantvagrant00000000000000Hermite Module, "Physicists'" (:mod:`numpy.polynomial.hermite`) =============================================================== .. versionadded:: 1.6.0 .. currentmodule:: numpy.polynomial.hermite This module provides a number of objects (mostly functions) useful for dealing with Hermite series, including a `Hermite` class that encapsulates the usual arithmetic operations. (General information on how this module represents and works with such polynomials is in the docstring for its "parent" sub-package, `numpy.polynomial`). Hermite Class ------------- .. autosummary:: :toctree: generated/ Hermite Basics ------ .. autosummary:: :toctree: generated/ hermval hermval2d hermval3d hermgrid2d hermgrid3d hermroots hermfromroots Fitting ------- .. autosummary:: :toctree: generated/ hermfit hermvander hermvander2d hermvander3d Calculus -------- .. autosummary:: :toctree: generated/ hermder hermint Algebra ------- .. autosummary:: :toctree: generated/ hermadd hermsub hermmul hermmulx hermdiv hermpow Quadrature ---------- .. autosummary:: :toctree: generated/ hermgauss hermweight Miscellaneous ------------- .. autosummary:: :toctree: generated/ hermcompanion hermdomain hermzero hermone hermx hermtrim hermline herm2poly poly2herm numpy-1.8.2/doc/source/reference/routines.polynomials.package.rst0000664000175100017510000000055412370216242026373 0ustar vagrantvagrant00000000000000Polynomial Package ================== .. versionadded:: 1.4.0 .. currentmodule:: numpy.polynomial .. toctree:: :maxdepth: 2 routines.polynomials.classes routines.polynomials.polynomial routines.polynomials.chebyshev routines.polynomials.legendre routines.polynomials.laguerre routines.polynomials.hermite routines.polynomials.hermite_e numpy-1.8.2/doc/source/reference/arrays.nditer.rst0000664000175100017510000006465412370216242023364 0ustar vagrantvagrant00000000000000.. currentmodule:: numpy .. _arrays.nditer: ********************* Iterating Over Arrays ********************* The iterator object :class:`nditer`, introduced in NumPy 1.6, provides many flexible ways to visit all the elements of one or more arrays in a systematic fashion. This page introduces some basic ways to use the object for computations on arrays in Python, then concludes with how one can accelerate the inner loop in Cython. Since the Python exposure of :class:`nditer` is a relatively straightforward mapping of the C array iterator API, these ideas will also provide help working with array iteration from C or C++. Single Array Iteration ====================== The most basic task that can be done with the :class:`nditer` is to visit every element of an array. Each element is provided one by one using the standard Python iterator interface. .. admonition:: Example >>> a = np.arange(6).reshape(2,3) >>> for x in np.nditer(a): ... print x, ... 0 1 2 3 4 5 An important thing to be aware of for this iteration is that the order is chosen to match the memory layout of the array instead of using a standard C or Fortran ordering. This is done for access efficiency, reflecting the idea that by default one simply wants to visit each element without concern for a particular ordering. We can see this by iterating over the transpose of our previous array, compared to taking a copy of that transpose in C order. .. admonition:: Example >>> a = np.arange(6).reshape(2,3) >>> for x in np.nditer(a.T): ... print x, ... 0 1 2 3 4 5 >>> for x in np.nditer(a.T.copy(order='C')): ... print x, ... 0 3 1 4 2 5 The elements of both `a` and `a.T` get traversed in the same order, namely the order they are stored in memory, whereas the elements of `a.T.copy(order='C')` get visited in a different order because they have been put into a different memory layout. Controlling Iteration Order --------------------------- There are times when it is important to visit the elements of an array in a specific order, irrespective of the layout of the elements in memory. The :class:`nditer` object provides an `order` parameter to control this aspect of iteration. The default, having the behavior described above, is order='K' to keep the existing order. This can be overridden with order='C' for C order and order='F' for Fortran order. .. admonition:: Example >>> a = np.arange(6).reshape(2,3) >>> for x in np.nditer(a, order='F'): ... print x, ... 0 3 1 4 2 5 >>> for x in np.nditer(a.T, order='C'): ... print x, ... 0 3 1 4 2 5 Modifying Array Values ---------------------- By default, the :class:`nditer` treats the input array as a read-only object. To modify the array elements, you must specify either read-write or write-only mode. This is controlled with per-operand flags. Regular assignment in Python simply changes a reference in the local or global variable dictionary instead of modifying an existing variable in place. This means that simply assigning to `x` will not place the value into the element of the array, but rather switch `x` from being an array element reference to being a reference to the value you assigned. To actually modify the element of the array, `x` should be indexed with the ellipsis. .. admonition:: Example >>> a = np.arange(6).reshape(2,3) >>> a array([[0, 1, 2], [3, 4, 5]]) >>> for x in np.nditer(a, op_flags=['readwrite']): ... x[...] = 2 * x ... >>> a array([[ 0, 2, 4], [ 6, 8, 10]]) Using an External Loop ---------------------- In all the examples so far, the elements of `a` are provided by the iterator one at a time, because all the looping logic is internal to the iterator. While this is simple and convenient, it is not very efficient. A better approach is to move the one-dimensional innermost loop into your code, external to the iterator. This way, NumPy's vectorized operations can be used on larger chunks of the elements being visited. The :class:`nditer` will try to provide chunks that are as large as possible to the inner loop. By forcing 'C' and 'F' order, we get different external loop sizes. This mode is enabled by specifying an iterator flag. Observe that with the default of keeping native memory order, the iterator is able to provide a single one-dimensional chunk, whereas when forcing Fortran order, it has to provide three chunks of two elements each. .. admonition:: Example >>> a = np.arange(6).reshape(2,3) >>> for x in np.nditer(a, flags=['external_loop']): ... print x, ... [0 1 2 3 4 5] >>> for x in np.nditer(a, flags=['external_loop'], order='F'): ... print x, ... [0 3] [1 4] [2 5] Tracking an Index or Multi-Index -------------------------------- During iteration, you may want to use the index of the current element in a computation. For example, you may want to visit the elements of an array in memory order, but use a C-order, Fortran-order, or multidimensional index to look up values in a different array. The Python iterator protocol doesn't have a natural way to query these additional values from the iterator, so we introduce an alternate syntax for iterating with an :class:`nditer`. This syntax explicitly works with the iterator object itself, so its properties are readily accessible during iteration. With this looping construct, the current value is accessible by indexing into the iterator, and the index being tracked is the property `index` or `multi_index` depending on what was requested. The Python interactive interpreter unfortunately prints out the values of expressions inside the while loop during each iteration of the loop. We have modified the output in the examples using this looping construct in order to be more readable. .. admonition:: Example >>> a = np.arange(6).reshape(2,3) >>> it = np.nditer(a, flags=['f_index']) >>> while not it.finished: ... print "%d <%d>" % (it[0], it.index), ... it.iternext() ... 0 <0> 1 <2> 2 <4> 3 <1> 4 <3> 5 <5> >>> it = np.nditer(a, flags=['multi_index']) >>> while not it.finished: ... print "%d <%s>" % (it[0], it.multi_index), ... it.iternext() ... 0 <(0, 0)> 1 <(0, 1)> 2 <(0, 2)> 3 <(1, 0)> 4 <(1, 1)> 5 <(1, 2)> >>> it = np.nditer(a, flags=['multi_index'], op_flags=['writeonly']) >>> while not it.finished: ... it[0] = it.multi_index[1] - it.multi_index[0] ... it.iternext() ... >>> a array([[ 0, 1, 2], [-1, 0, 1]]) Tracking an index or multi-index is incompatible with using an external loop, because it requires a different index value per element. If you try to combine these flags, the :class:`nditer` object will raise an exception .. admonition:: Example >>> a = np.zeros((2,3)) >>> it = np.nditer(a, flags=['c_index', 'external_loop']) Traceback (most recent call last): File "", line 1, in ValueError: Iterator flag EXTERNAL_LOOP cannot be used if an index or multi-index is being tracked Buffering the Array Elements ---------------------------- When forcing an iteration order, we observed that the external loop option may provide the elements in smaller chunks because the elements can't be visited in the appropriate order with a constant stride. When writing C code, this is generally fine, however in pure Python code this can cause a significant reduction in performance. By enabling buffering mode, the chunks provided by the iterator to the inner loop can be made larger, significantly reducing the overhead of the Python interpreter. In the example forcing Fortran iteration order, the inner loop gets to see all the elements in one go when buffering is enabled. .. admonition:: Example >>> a = np.arange(6).reshape(2,3) >>> for x in np.nditer(a, flags=['external_loop'], order='F'): ... print x, ... [0 3] [1 4] [2 5] >>> for x in np.nditer(a, flags=['external_loop','buffered'], order='F'): ... print x, ... [0 3 1 4 2 5] Iterating as a Specific Data Type --------------------------------- There are times when it is necessary to treat an array as a different data type than it is stored as. For instance, one may want to do all computations on 64-bit floats, even if the arrays being manipulated are 32-bit floats. Except when writing low-level C code, it's generally better to let the iterator handle the copying or buffering instead of casting the data type yourself in the inner loop. There are two mechanisms which allow this to be done, temporary copies and buffering mode. With temporary copies, a copy of the entire array is made with the new data type, then iteration is done in the copy. Write access is permitted through a mode which updates the original array after all the iteration is complete. The major drawback of temporary copies is that the temporary copy may consume a large amount of memory, particularly if the iteration data type has a larger itemsize than the original one. Buffering mode mitigates the memory usage issue and is more cache-friendly than making temporary copies. Except for special cases, where the whole array is needed at once outside the iterator, buffering is recommended over temporary copying. Within NumPy, buffering is used by the ufuncs and other functions to support flexible inputs with minimal memory overhead. In our examples, we will treat the input array with a complex data type, so that we can take square roots of negative numbers. Without enabling copies or buffering mode, the iterator will raise an exception if the data type doesn't match precisely. .. admonition:: Example >>> a = np.arange(6).reshape(2,3) - 3 >>> for x in np.nditer(a, op_dtypes=['complex128']): ... print np.sqrt(x), ... Traceback (most recent call last): File "", line 1, in TypeError: Iterator operand required copying or buffering, but neither copying nor buffering was enabled In copying mode, 'copy' is specified as a per-operand flag. This is done to provide control in a per-operand fashion. Buffering mode is specified as an iterator flag. .. admonition:: Example >>> a = np.arange(6).reshape(2,3) - 3 >>> for x in np.nditer(a, op_flags=['readonly','copy'], ... op_dtypes=['complex128']): ... print np.sqrt(x), ... 1.73205080757j 1.41421356237j 1j 0j (1+0j) (1.41421356237+0j) >>> for x in np.nditer(a, flags=['buffered'], op_dtypes=['complex128']): ... print np.sqrt(x), ... 1.73205080757j 1.41421356237j 1j 0j (1+0j) (1.41421356237+0j) The iterator uses NumPy's casting rules to determine whether a specific conversion is permitted. By default, it enforces 'safe' casting. This means, for example, that it will raise an exception if you try to treat a 64-bit float array as a 32-bit float array. In many cases, the rule 'same_kind' is the most reasonable rule to use, since it will allow conversion from 64 to 32-bit float, but not from float to int or from complex to float. .. admonition:: Example >>> a = np.arange(6.) >>> for x in np.nditer(a, flags=['buffered'], op_dtypes=['float32']): ... print x, ... Traceback (most recent call last): File "", line 1, in TypeError: Iterator operand 0 dtype could not be cast from dtype('float64') to dtype('float32') according to the rule 'safe' >>> for x in np.nditer(a, flags=['buffered'], op_dtypes=['float32'], ... casting='same_kind'): ... print x, ... 0.0 1.0 2.0 3.0 4.0 5.0 >>> for x in np.nditer(a, flags=['buffered'], op_dtypes=['int32'], casting='same_kind'): ... print x, ... Traceback (most recent call last): File "", line 1, in TypeError: Iterator operand 0 dtype could not be cast from dtype('float64') to dtype('int32') according to the rule 'same_kind' One thing to watch out for is conversions back to the original data type when using a read-write or write-only operand. A common case is to implement the inner loop in terms of 64-bit floats, and use 'same_kind' casting to allow the other floating-point types to be processed as well. While in read-only mode, an integer array could be provided, read-write mode will raise an exception because conversion back to the array would violate the casting rule. .. admonition:: Example >>> a = np.arange(6) >>> for x in np.nditer(a, flags=['buffered'], op_flags=['readwrite'], ... op_dtypes=['float64'], casting='same_kind'): ... x[...] = x / 2.0 ... Traceback (most recent call last): File "", line 2, in TypeError: Iterator requested dtype could not be cast from dtype('float64') to dtype('int64'), the operand 0 dtype, according to the rule 'same_kind' Broadcasting Array Iteration ============================ NumPy has a set of rules for dealing with arrays that have differing shapes which are applied whenever functions take multiple operands which combine element-wise. This is called :ref:`broadcasting `. The :class:`nditer` object can apply these rules for you when you need to write such a function. As an example, we print out the result of broadcasting a one and a two dimensional array together. .. admonition:: Example >>> a = np.arange(3) >>> b = np.arange(6).reshape(2,3) >>> for x, y in np.nditer([a,b]): ... print "%d:%d" % (x,y), ... 0:0 1:1 2:2 0:3 1:4 2:5 When a broadcasting error occurs, the iterator raises an exception which includes the input shapes to help diagnose the problem. .. admonition:: Example >>> a = np.arange(2) >>> b = np.arange(6).reshape(2,3) >>> for x, y in np.nditer([a,b]): ... print "%d:%d" % (x,y), ... Traceback (most recent call last): File "", line 1, in ValueError: operands could not be broadcast together with shapes (2) (2,3) Iterator-Allocated Output Arrays -------------------------------- A common case in NumPy functions is to have outputs allocated based on the broadcasting of the input, and additionally have an optional parameter called 'out' where the result will be placed when it is provided. The :class:`nditer` object provides a convenient idiom that makes it very easy to support this mechanism. We'll show how this works by creating a function `square` which squares its input. Let's start with a minimal function definition excluding 'out' parameter support. .. admonition:: Example >>> def square(a): ... it = np.nditer([a, None]) ... for x, y in it: ... y[...] = x*x ... return it.operands[1] ... >>> square([1,2,3]) array([1, 4, 9]) By default, the :class:`nditer` uses the flags 'allocate' and 'writeonly' for operands that are passed in as None. This means we were able to provide just the two operands to the iterator, and it handled the rest. When adding the 'out' parameter, we have to explicitly provide those flags, because if someone passes in an array as 'out', the iterator will default to 'readonly', and our inner loop would fail. The reason 'readonly' is the default for input arrays is to prevent confusion about unintentionally triggering a reduction operation. If the default were 'readwrite', any broadcasting operation would also trigger a reduction, a topic which is covered later in this document. While we're at it, let's also introduce the 'no_broadcast' flag, which will prevent the output from being broadcast. This is important, because we only want one input value for each output. Aggregating more than one input value is a reduction operation which requires special handling. It would already raise an error because reductions must be explicitly enabled in an iterator flag, but the error message that results from disabling broadcasting is much more understandable for end-users. To see how to generalize the square function to a reduction, look at the sum of squares function in the section about Cython. For completeness, we'll also add the 'external_loop' and 'buffered' flags, as these are what you will typically want for performance reasons. .. admonition:: Example >>> def square(a, out=None): ... it = np.nditer([a, out], ... flags = ['external_loop', 'buffered'], ... op_flags = [['readonly'], ... ['writeonly', 'allocate', 'no_broadcast']]) ... for x, y in it: ... y[...] = x*x ... return it.operands[1] ... >>> square([1,2,3]) array([1, 4, 9]) >>> b = np.zeros((3,)) >>> square([1,2,3], out=b) array([ 1., 4., 9.]) >>> b array([ 1., 4., 9.]) >>> square(np.arange(6).reshape(2,3), out=b) Traceback (most recent call last): File "", line 1, in File "", line 4, in square ValueError: non-broadcastable output operand with shape (3) doesn't match the broadcast shape (2,3) Outer Product Iteration ----------------------- Any binary operation can be extended to an array operation in an outer product fashion like in :func:`outer`, and the :class:`nditer` object provides a way to accomplish this by explicitly mapping the axes of the operands. It is also possible to do this with :const:`newaxis` indexing, but we will show you how to directly use the nditer `op_axes` parameter to accomplish this with no intermediate views. We'll do a simple outer product, placing the dimensions of the first operand before the dimensions of the second operand. The `op_axes` parameter needs one list of axes for each operand, and provides a mapping from the iterator's axes to the axes of the operand. Suppose the first operand is one dimensional and the second operand is two dimensional. The iterator will have three dimensions, so `op_axes` will have two 3-element lists. The first list picks out the one axis of the first operand, and is -1 for the rest of the iterator axes, with a final result of [0, -1, -1]. The second list picks out the two axes of the second operand, but shouldn't overlap with the axes picked out in the first operand. Its list is [-1, 0, 1]. The output operand maps onto the iterator axes in the standard manner, so we can provide None instead of constructing another list. The operation in the inner loop is a straightforward multiplication. Everything to do with the outer product is handled by the iterator setup. .. admonition:: Example >>> a = np.arange(3) >>> b = np.arange(8).reshape(2,4) >>> it = np.nditer([a, b, None], flags=['external_loop'], ... op_axes=[[0, -1, -1], [-1, 0, 1], None]) >>> for x, y, z in it: ... z[...] = x*y ... >>> it.operands[2] array([[[ 0, 0, 0, 0], [ 0, 0, 0, 0]], [[ 0, 1, 2, 3], [ 4, 5, 6, 7]], [[ 0, 2, 4, 6], [ 8, 10, 12, 14]]]) Reduction Iteration ------------------- Whenever a writeable operand has fewer elements than the full iteration space, that operand is undergoing a reduction. The :class:`nditer` object requires that any reduction operand be flagged as read-write, and only allows reductions when 'reduce_ok' is provided as an iterator flag. For a simple example, consider taking the sum of all elements in an array. .. admonition:: Example >>> a = np.arange(24).reshape(2,3,4) >>> b = np.array(0) >>> for x, y in np.nditer([a, b], flags=['reduce_ok', 'external_loop'], ... op_flags=[['readonly'], ['readwrite']]): ... y[...] += x ... >>> b array(276) >>> np.sum(a) 276 Things are a little bit more tricky when combining reduction and allocated operands. Before iteration is started, any reduction operand must be initialized to its starting values. Here's how we can do this, taking sums along the last axis of `a`. .. admonition:: Example >>> a = np.arange(24).reshape(2,3,4) >>> it = np.nditer([a, None], flags=['reduce_ok', 'external_loop'], ... op_flags=[['readonly'], ['readwrite', 'allocate']], ... op_axes=[None, [0,1,-1]]) >>> it.operands[1][...] = 0 >>> for x, y in it: ... y[...] += x ... >>> it.operands[1] array([[ 6, 22, 38], [54, 70, 86]]) >>> np.sum(a, axis=2) array([[ 6, 22, 38], [54, 70, 86]]) To do buffered reduction requires yet another adjustment during the setup. Normally the iterator construction involves copying the first buffer of data from the readable arrays into the buffer. Any reduction operand is readable, so it may be read into a buffer. Unfortunately, initialization of the operand after this buffering operation is complete will not be reflected in the buffer that the iteration starts with, and garbage results will be produced. The iterator flag "delay_bufalloc" is there to allow iterator-allocated reduction operands to exist together with buffering. When this flag is set, the iterator will leave its buffers uninitialized until it receives a reset, after which it will be ready for regular iteration. Here's how the previous example looks if we also enable buffering. .. admonition:: Example >>> a = np.arange(24).reshape(2,3,4) >>> it = np.nditer([a, None], flags=['reduce_ok', 'external_loop', ... 'buffered', 'delay_bufalloc'], ... op_flags=[['readonly'], ['readwrite', 'allocate']], ... op_axes=[None, [0,1,-1]]) >>> it.operands[1][...] = 0 >>> it.reset() >>> for x, y in it: ... y[...] += x ... >>> it.operands[1] array([[ 6, 22, 38], [54, 70, 86]]) Putting the Inner Loop in Cython ================================ Those who want really good performance out of their low level operations should strongly consider directly using the iteration API provided in C, but for those who are not comfortable with C or C++, Cython is a good middle ground with reasonable performance tradeoffs. For the :class:`nditer` object, this means letting the iterator take care of broadcasting, dtype conversion, and buffering, while giving the inner loop to Cython. For our example, we'll create a sum of squares function. To start, let's implement this function in straightforward Python. We want to support an 'axis' parameter similar to the numpy :func:`sum` function, so we will need to construct a list for the `op_axes` parameter. Here's how this looks. .. admonition:: Example >>> def axis_to_axeslist(axis, ndim): ... if axis is None: ... return [-1] * ndim ... else: ... if type(axis) is not tuple: ... axis = (axis,) ... axeslist = [1] * ndim ... for i in axis: ... axeslist[i] = -1 ... ax = 0 ... for i in range(ndim): ... if axeslist[i] != -1: ... axeslist[i] = ax ... ax += 1 ... return axeslist ... >>> def sum_squares_py(arr, axis=None, out=None): ... axeslist = axis_to_axeslist(axis, arr.ndim) ... it = np.nditer([arr, out], flags=['reduce_ok', 'external_loop', ... 'buffered', 'delay_bufalloc'], ... op_flags=[['readonly'], ['readwrite', 'allocate']], ... op_axes=[None, axeslist], ... op_dtypes=['float64', 'float64']) ... it.operands[1][...] = 0 ... it.reset() ... for x, y in it: ... y[...] += x*x ... return it.operands[1] ... >>> a = np.arange(6).reshape(2,3) >>> sum_squares_py(a) array(55.0) >>> sum_squares_py(a, axis=-1) array([ 5., 50.]) To Cython-ize this function, we replace the inner loop (y[...] += x*x) with Cython code that's specialized for the float64 dtype. With the 'external_loop' flag enabled, the arrays provided to the inner loop will always be one-dimensional, so very little checking needs to be done. Here's the listing of sum_squares.pyx:: import numpy as np cimport numpy as np cimport cython def axis_to_axeslist(axis, ndim): if axis is None: return [-1] * ndim else: if type(axis) is not tuple: axis = (axis,) axeslist = [1] * ndim for i in axis: axeslist[i] = -1 ax = 0 for i in range(ndim): if axeslist[i] != -1: axeslist[i] = ax ax += 1 return axeslist @cython.boundscheck(False) def sum_squares_cy(arr, axis=None, out=None): cdef np.ndarray[double] x cdef np.ndarray[double] y cdef int size cdef double value axeslist = axis_to_axeslist(axis, arr.ndim) it = np.nditer([arr, out], flags=['reduce_ok', 'external_loop', 'buffered', 'delay_bufalloc'], op_flags=[['readonly'], ['readwrite', 'allocate']], op_axes=[None, axeslist], op_dtypes=['float64', 'float64']) it.operands[1][...] = 0 it.reset() for xarr, yarr in it: x = xarr y = yarr size = x.shape[0] for i in range(size): value = x[i] y[i] = y[i] + value * value return it.operands[1] On this machine, building the .pyx file into a module looked like the following, but you may have to find some Cython tutorials to tell you the specifics for your system configuration.:: $ cython sum_squares.pyx $ gcc -shared -pthread -fPIC -fwrapv -O2 -Wall -I/usr/include/python2.7 -fno-strict-aliasing -o sum_squares.so sum_squares.c Running this from the Python interpreter produces the same answers as our native Python/NumPy code did. .. admonition:: Example >>> from sum_squares import sum_squares_cy >>> a = np.arange(6).reshape(2,3) >>> sum_squares_cy(a) array(55.0) >>> sum_squares_cy(a, axis=-1) array([ 5., 50.]) Doing a little timing in IPython shows that the reduced overhead and memory allocation of the Cython inner loop is providing a very nice speedup over both the straightforward Python code and an expression using NumPy's built-in sum function.:: >>> a = np.random.rand(1000,1000) >>> timeit sum_squares_py(a, axis=-1) 10 loops, best of 3: 37.1 ms per loop >>> timeit np.sum(a*a, axis=-1) 10 loops, best of 3: 20.9 ms per loop >>> timeit sum_squares_cy(a, axis=-1) 100 loops, best of 3: 11.8 ms per loop >>> np.all(sum_squares_cy(a, axis=-1) == np.sum(a*a, axis=-1)) True >>> np.all(sum_squares_py(a, axis=-1) == np.sum(a*a, axis=-1)) True numpy-1.8.2/doc/source/reference/internals.rst0000664000175100017510000000020312370216242022552 0ustar vagrantvagrant00000000000000*************** Numpy internals *************** .. toctree:: internals.code-explanations .. automodule:: numpy.doc.internals numpy-1.8.2/doc/source/reference/routines.char.rst0000664000175100017510000000231112370216242023341 0ustar vagrantvagrant00000000000000String operations ***************** .. currentmodule:: numpy.core.defchararray This module provides a set of vectorized string operations for arrays of type `numpy.string_` or `numpy.unicode_`. All of them are based on the string methods in the Python standard library. String operations ----------------- .. autosummary:: :toctree: generated/ add multiply mod capitalize center decode encode join ljust lower lstrip partition replace rjust rpartition rsplit rstrip split splitlines strip swapcase title translate upper zfill Comparison ---------- Unlike the standard numpy comparison operators, the ones in the `char` module strip trailing whitespace characters before performing the comparison. .. autosummary:: :toctree: generated/ equal not_equal greater_equal less_equal greater less String information ------------------ .. autosummary:: :toctree: generated/ count find index isalpha isdecimal isdigit islower isnumeric isspace istitle isupper rfind rindex startswith Convenience class ----------------- .. autosummary:: :toctree: generated/ chararray numpy-1.8.2/doc/source/reference/routines.statistics.rst0000664000175100017510000000110512370216242024616 0ustar vagrantvagrant00000000000000Statistics ========== .. currentmodule:: numpy Order statistics ---------------- .. autosummary:: :toctree: generated/ amin amax nanmin nanmax ptp percentile Averages and variances ---------------------- .. autosummary:: :toctree: generated/ median average mean std var nanmean nanstd nanvar Correlating ----------- .. autosummary:: :toctree: generated/ corrcoef correlate cov Histograms ---------- .. autosummary:: :toctree: generated/ histogram histogram2d histogramdd bincount digitize numpy-1.8.2/doc/source/reference/routines.polynomials.classes.rst0000664000175100017510000002535012370216243026437 0ustar vagrantvagrant00000000000000Using the Convenience Classes ============================= The convenience classes provided by the polynomial package are: ============ ================ Name Provides ============ ================ Polynomial Power series Chebyshev Chebyshev series Legendre Legendre series Laguerre Laguerre series Hermite Hermite series HermiteE HermiteE series ============ ================ The series in this context are finite sums of the corresponding polynomial basis functions multiplied by coefficients. For instance, a power series looks like .. math:: p(x) = 1 + 2x + 3x^2 and has coefficients :math:`[1, 2, 3]`. The Chebyshev series with the same coefficients looks like .. math:: p(x) = 1 T_0(x) + 2 T_1(x) + 3 T_2(x) and more generally .. math:: p(x) = \sum_{i=0}^n c_i T_i(x) where in this case the :math:`T_n` are the Chebyshev functions of degree :math:`n`, but could just as easily be the basis functions of any of the other classes. The convention for all the classes is that the coefficient :math:`c[i]` goes with the basis function of degree i. All of the classes have the same methods, and especially they implement the Python numeric operators +, -, \*, //, %, divmod, \*\*, ==, and !=. The last two can be a bit problematic due to floating point roundoff errors. We now give a quick demonstration of the various operations using Numpy version 1.7.0. Basics ------ First we need a polynomial class and a polynomial instance to play with. The classes can be imported directly from the polynomial package or from the module of the relevant type. Here we import from the package and use the conventional Polynomial class because of its familiarity:: >>> from numpy.polynomial import Polynomial as P >>> p = P([1,2,3]) >>> p Polynomial([ 1., 2., 3.], [-1., 1.], [-1., 1.]) Note that there are three parts to the long version of the printout. The first is the coefficients, the second is the domain, and the third is the window:: >>> p.coef array([ 1., 2., 3.]) >>> p.domain array([-1., 1.]) >>> p.window array([-1., 1.]) Printing a polynomial yields a shorter form without the domain and window:: >>> print p poly([ 1. 2. 3.]) We will deal with the domain and window when we get to fitting, for the moment we ignore them and run through the basic algebraic and arithmetic operations. Addition and Subtraction:: >>> p + p Polynomial([ 2., 4., 6.], [-1., 1.], [-1., 1.]) >>> p - p Polynomial([ 0.], [-1., 1.], [-1., 1.]) Multiplication:: >>> p * p Polynomial([ 1., 4., 10., 12., 9.], [-1., 1.], [-1., 1.]) Powers:: >>> p**2 Polynomial([ 1., 4., 10., 12., 9.], [-1., 1.], [-1., 1.]) Division: Floor division, '//', is the division operator for the polynomial classes, polynomials are treated like integers in this regard. For Python versions < 3.x the '/' operator maps to '//', as it does for Python, for later versions the '/' will only work for division by scalars. At some point it will be deprecated:: >>> p // P([-1, 1]) Polynomial([ 5., 3.], [-1., 1.], [-1., 1.]) Remainder:: >>> p % P([-1, 1]) Polynomial([ 6.], [-1., 1.], [-1., 1.]) Divmod:: >>> quo, rem = divmod(p, P([-1, 1])) >>> quo Polynomial([ 5., 3.], [-1., 1.], [-1., 1.]) >>> rem Polynomial([ 6.], [-1., 1.], [-1., 1.]) Evaluation:: >>> x = np.arange(5) >>> p(x) array([ 1., 6., 17., 34., 57.]) >>> x = np.arange(6).reshape(3,2) >>> p(x) array([[ 1., 6.], [ 17., 34.], [ 57., 86.]]) Substitution: Substitute a polynomial for x and expand the result. Here we substitute p in itself leading to a new polynomial of degree 4 after expansion. If the polynomials are regarded as functions this is composition of functions:: >>> p(p) Polynomial([ 6., 16., 36., 36., 27.], [-1., 1.], [-1., 1.]) Roots:: >>> p.roots() array([-0.33333333-0.47140452j, -0.33333333+0.47140452j]) It isn't always convenient to explicitly use Polynomial instances, so tuples, lists, arrays, and scalars are automatically cast in the arithmetic operations:: >>> p + [1, 2, 3] Polynomial([ 2., 4., 6.], [-1., 1.], [-1., 1.]) >>> [1, 2, 3] * p Polynomial([ 1., 4., 10., 12., 9.], [-1., 1.], [-1., 1.]) >>> p / 2 Polynomial([ 0.5, 1. , 1.5], [-1., 1.], [-1., 1.]) Polynomials that differ in domain, window, or class can't be mixed in arithmetic:: >>> from numpy.polynomial import Chebyshev as T >>> p + P([1], domain=[0,1]) Traceback (most recent call last): File "", line 1, in File "", line 213, in __add__ TypeError: Domains differ >>> p + P([1], window=[0,1]) Traceback (most recent call last): File "", line 1, in File "", line 215, in __add__ TypeError: Windows differ >>> p + T([1]) Traceback (most recent call last): File "", line 1, in File "", line 211, in __add__ TypeError: Polynomial types differ But different types can be used for substitution. In fact, this is how conversion of Polynomial classes among themselves is done for type, domain, and window casting:: >>> p(T([0, 1])) Chebyshev([ 2.5, 2. , 1.5], [-1., 1.], [-1., 1.]) Which gives the polynomial `p` in Chebyshev form. This works because :math:`T_1(x) = x` and substituting :math:`x` for :math:`x` doesn't change the original polynomial. However, all the multiplications and divisions will be done using Chebyshev series, hence the type of the result. Calculus -------- Polynomial instances can be integrated and differentiated.:: >>> from numpy.polynomial import Polynomial as P >>> p = P([2, 6]) >>> p.integ() Polynomial([ 0., 2., 3.], [-1., 1.], [-1., 1.]) >>> p.integ(2) Polynomial([ 0., 0., 1., 1.], [-1., 1.], [-1., 1.]) The first example integrates `p` once, the second example integrates it twice. By default, the lower bound of the integration and the integration constant are 0, but both can be specified.:: >>> p.integ(lbnd=-1) Polynomial([-1., 2., 3.], [-1., 1.], [-1., 1.]) >>> p.integ(lbnd=-1, k=1) Polynomial([ 0., 2., 3.], [-1., 1.], [-1., 1.]) In the first case the lower bound of the integration is set to -1 and the integration constant is 0. In the second the constant of integration is set to 1 as well. Differentiation is simpler since the only option is the number times the polynomial is differentiated:: >>> p = P([1, 2, 3]) >>> p.deriv(1) Polynomial([ 2., 6.], [-1., 1.], [-1., 1.]) >>> p.deriv(2) Polynomial([ 6.], [-1., 1.], [-1., 1.]) Other Polynomial Constructors ----------------------------- Constructing polynomials by specifying coefficients is just one way of obtaining a polynomial instance, they may also be created by specifying their roots, by conversion from other polynomial types, and by least squares fits. Fitting is discussed in its own section, the other methods are demonstrated below:: >>> from numpy.polynomial import Polynomial as P >>> from numpy.polynomial import Chebyshev as T >>> p = P.fromroots([1, 2, 3]) >>> p Polynomial([ -6., 11., -6., 1.], [-1., 1.], [-1., 1.]) >>> p.convert(kind=T) Chebyshev([ -9. , 11.75, -3. , 0.25], [-1., 1.], [-1., 1.]) The convert method can also convert domain and window:: >>> p.convert(kind=T, domain=[0, 1]) Chebyshev([-2.4375 , 2.96875, -0.5625 , 0.03125], [ 0., 1.], [-1., 1.]) >>> p.convert(kind=P, domain=[0, 1]) Polynomial([-1.875, 2.875, -1.125, 0.125], [ 0., 1.], [-1., 1.]) In numpy versions >= 1.7.0 the `basis` and `cast` class methods are also available. The cast method works like the convert method while the basis method returns the basis polynomial of given degree:: >>> P.basis(3) Polynomial([ 0., 0., 0., 1.], [-1., 1.], [-1., 1.]) >>> T.cast(p) Chebyshev([ -9. , 11.75, -3. , 0.25], [-1., 1.], [-1., 1.]) Conversions between types can be useful, but it is *not* recommended for routine use. The loss of numerical precision in passing from a Chebyshev series of degree 50 to a Polynomial series of the same degree can make the results of numerical evaluation essentially random. Fitting ------- Fitting is the reason that the `domain` and `window` attributes are part of the convenience classes. To illustrate the problem, the values of the Chebyshev polynomials up to degree 5 are plotted below. .. plot:: >>> import matplotlib.pyplot as plt >>> from numpy.polynomial import Chebyshev as T >>> x = np.linspace(-1, 1, 100) >>> for i in range(6): ax = plt.plot(x, T.basis(i)(x), lw=2, label="T_%d"%i) ... >>> plt.legend(loc="upper left") >>> plt.show() In the range -1 <= `x` <= 1 they are nice, equiripple functions lying between +/- 1. The same plots over the range -2 <= `x` <= 2 look very different: .. plot:: >>> import matplotlib.pyplot as plt >>> from numpy.polynomial import Chebyshev as T >>> x = np.linspace(-2, 2, 100) >>> for i in range(6): ax = plt.plot(x, T.basis(i)(x), lw=2, label="T_%d"%i) ... >>> plt.legend(loc="lower right") >>> plt.show() As can be seen, the "good" parts have shrunk to insignificance. In using Chebyshev polynomials for fitting we want to use the region where `x` is between -1 and 1 and that is what the `window` specifies. However, it is unlikely that the data to be fit has all its data points in that interval, so we use `domain` to specify the interval where the data points lie. When the fit is done, the domain is first mapped to the window by a linear transformation and the usual least squares fit is done using the mapped data points. The window and domain of the fit are part of the returned series and are automatically used when computing values, derivatives, and such. If they aren't specified in the call the fitting routine will use the default window and the smallest domain that holds all the data points. This is illustrated below for a fit to a noisy sine curve. .. plot:: >>> import numpy as np >>> import matplotlib.pyplot as plt >>> from numpy.polynomial import Chebyshev as T >>> np.random.seed(11) >>> x = np.linspace(0, 2*np.pi, 20) >>> y = np.sin(x) + np.random.normal(scale=.1, size=x.shape) >>> p = T.fit(x, y, 5) >>> plt.plot(x, y, 'o') [] >>> xx, yy = p.linspace() >>> plt.plot(xx, yy, lw=2) [] >>> p.domain array([ 0. , 6.28318531]) >>> p.window array([-1., 1.]) >>> plt.show() numpy-1.8.2/doc/source/reference/c-api.ufunc.rst0000664000175100017510000004022312370216243022672 0ustar vagrantvagrant00000000000000UFunc API ========= .. sectionauthor:: Travis E. Oliphant .. index:: pair: ufunc; C-API Constants --------- .. cvar:: UFUNC_ERR_{HANDLER} ``{HANDLER}`` can be **IGNORE**, **WARN**, **RAISE**, or **CALL** .. cvar:: UFUNC_{THING}_{ERR} ``{THING}`` can be **MASK**, **SHIFT**, or **FPE**, and ``{ERR}`` can be **DIVIDEBYZERO**, **OVERFLOW**, **UNDERFLOW**, and **INVALID**. .. cvar:: PyUFunc_{VALUE} ``{VALUE}`` can be **One** (1), **Zero** (0), or **None** (-1) Macros ------ .. cmacro:: NPY_LOOP_BEGIN_THREADS Used in universal function code to only release the Python GIL if loop->obj is not true (*i.e.* this is not an OBJECT array loop). Requires use of :cmacro:`NPY_BEGIN_THREADS_DEF` in variable declaration area. .. cmacro:: NPY_LOOP_END_THREADS Used in universal function code to re-acquire the Python GIL if it was released (because loop->obj was not true). .. cfunction:: UFUNC_CHECK_ERROR(loop) A macro used internally to check for errors and goto fail if found. This macro requires a fail label in the current code block. The *loop* variable must have at least members (obj, errormask, and errorobj). If *loop* ->obj is nonzero, then :cfunc:`PyErr_Occurred` () is called (meaning the GIL must be held). If *loop* ->obj is zero, then if *loop* ->errormask is nonzero, :cfunc:`PyUFunc_checkfperr` is called with arguments *loop* ->errormask and *loop* ->errobj. If the result of this check of the IEEE floating point registers is true then the code redirects to the fail label which must be defined. .. cfunction:: UFUNC_CHECK_STATUS(ret) A macro that expands to platform-dependent code. The *ret* variable can can be any integer. The :cdata:`UFUNC_FPE_{ERR}` bits are set in *ret* according to the status of the corresponding error flags of the floating point processor. Functions --------- .. cfunction:: PyObject* PyUFunc_FromFuncAndData(PyUFuncGenericFunction* func, void** data, char* types, int ntypes, int nin, int nout, int identity, char* name, char* doc, int check_return) Create a new broadcasting universal function from required variables. Each ufunc builds around the notion of an element-by-element operation. Each ufunc object contains pointers to 1-d loops implementing the basic functionality for each supported type. .. note:: The *func*, *data*, *types*, *name*, and *doc* arguments are not copied by :cfunc:`PyUFunc_FromFuncAndData`. The caller must ensure that the memory used by these arrays is not freed as long as the ufunc object is alive. :param func: Must to an array of length *ntypes* containing :ctype:`PyUFuncGenericFunction` items. These items are pointers to functions that actually implement the underlying (element-by-element) function :math:`N` times. :param data: Should be ``NULL`` or a pointer to an array of size *ntypes* . This array may contain arbitrary extra-data to be passed to the corresponding 1-d loop function in the func array. :param types: Must be of length (*nin* + *nout*) \* *ntypes*, and it contains the data-types (built-in only) that the corresponding function in the *func* array can deal with. :param ntypes: How many different data-type "signatures" the ufunc has implemented. :param nin: The number of inputs to this operation. :param nout: The number of outputs :param name: The name for the ufunc. Specifying a name of 'add' or 'multiply' enables a special behavior for integer-typed reductions when no dtype is given. If the input type is an integer (or boolean) data type smaller than the size of the int_ data type, it will be internally upcast to the int_ (or uint) data type. :param doc: Allows passing in a documentation string to be stored with the ufunc. The documentation string should not contain the name of the function or the calling signature as that will be dynamically determined from the object and available when accessing the **__doc__** attribute of the ufunc. :param check_return: Unused and present for backwards compatibility of the C-API. A corresponding *check_return* integer does exist in the ufunc structure and it does get set with this value when the ufunc object is created. .. cfunction:: int PyUFunc_RegisterLoopForType(PyUFuncObject* ufunc, int usertype, PyUFuncGenericFunction function, int* arg_types, void* data) This function allows the user to register a 1-d loop with an already- created ufunc to be used whenever the ufunc is called with any of its input arguments as the user-defined data-type. This is needed in order to make ufuncs work with built-in data-types. The data-type must have been previously registered with the numpy system. The loop is passed in as *function*. This loop can take arbitrary data which should be passed in as *data*. The data-types the loop requires are passed in as *arg_types* which must be a pointer to memory at least as large as ufunc->nargs. .. cfunction:: int PyUFunc_RegisterLoopForDescr(PyUFuncObject* ufunc, PyArray_Descr* userdtype, PyUFuncGenericFunction function, PyArray_Descr** arg_dtypes, void* data) This function behaves like PyUFunc_RegisterLoopForType above, except that it allows the user to register a 1-d loop using PyArray_Descr objects instead of dtype type num values. This allows a 1-d loop to be registered for structured array data-dtypes and custom data-types instead of scalar data-types. .. cfunction:: int PyUFunc_ReplaceLoopBySignature(PyUFuncObject* ufunc, PyUFuncGenericFunction newfunc, int* signature, PyUFuncGenericFunction* oldfunc) Replace a 1-d loop matching the given *signature* in the already-created *ufunc* with the new 1-d loop newfunc. Return the old 1-d loop function in *oldfunc*. Return 0 on success and -1 on failure. This function works only with built-in types (use :cfunc:`PyUFunc_RegisterLoopForType` for user-defined types). A signature is an array of data-type numbers indicating the inputs followed by the outputs assumed by the 1-d loop. .. cfunction:: int PyUFunc_GenericFunction(PyUFuncObject* self, PyObject* args, PyObject* kwds, PyArrayObject** mps) A generic ufunc call. The ufunc is passed in as *self*, the arguments to the ufunc as *args* and *kwds*. The *mps* argument is an array of :ctype:`PyArrayObject` pointers whose values are discarded and which receive the converted input arguments as well as the ufunc outputs when success is returned. The user is responsible for managing this array and receives a new reference for each array in *mps*. The total number of arrays in *mps* is given by *self* ->nin + *self* ->nout. Returns 0 on success, -1 on error. .. cfunction:: int PyUFunc_checkfperr(int errmask, PyObject* errobj) A simple interface to the IEEE error-flag checking support. The *errmask* argument is a mask of :cdata:`UFUNC_MASK_{ERR}` bitmasks indicating which errors to check for (and how to check for them). The *errobj* must be a Python tuple with two elements: a string containing the name which will be used in any communication of error and either a callable Python object (call-back function) or :cdata:`Py_None`. The callable object will only be used if :cdata:`UFUNC_ERR_CALL` is set as the desired error checking method. This routine manages the GIL and is safe to call even after releasing the GIL. If an error in the IEEE-compatibile hardware is determined a -1 is returned, otherwise a 0 is returned. .. cfunction:: void PyUFunc_clearfperr() Clear the IEEE error flags. .. cfunction:: void PyUFunc_GetPyValues(char* name, int* bufsize, int* errmask, PyObject** errobj) Get the Python values used for ufunc processing from the thread-local storage area unless the defaults have been set in which case the name lookup is bypassed. The name is placed as a string in the first element of *\*errobj*. The second element is the looked-up function to call on error callback. The value of the looked-up buffer-size to use is passed into *bufsize*, and the value of the error mask is placed into *errmask*. Generic functions ----------------- At the core of every ufunc is a collection of type-specific functions that defines the basic functionality for each of the supported types. These functions must evaluate the underlying function :math:`N\geq1` times. Extra-data may be passed in that may be used during the calculation. This feature allows some general functions to be used as these basic looping functions. The general function has all the code needed to point variables to the right place and set up a function call. The general function assumes that the actual function to call is passed in as the extra data and calls it with the correct values. All of these functions are suitable for placing directly in the array of functions stored in the functions member of the PyUFuncObject structure. .. cfunction:: void PyUFunc_f_f_As_d_d(char** args, npy_intp* dimensions, npy_intp* steps, void* func) .. cfunction:: void PyUFunc_d_d(char** args, npy_intp* dimensions, npy_intp* steps, void* func) .. cfunction:: void PyUFunc_f_f(char** args, npy_intp* dimensions, npy_intp* steps, void* func) .. cfunction:: void PyUFunc_g_g(char** args, npy_intp* dimensions, npy_intp* steps, void* func) .. cfunction:: void PyUFunc_F_F_As_D_D(char** args, npy_intp* dimensions, npy_intp* steps, void* func) .. cfunction:: void PyUFunc_F_F(char** args, npy_intp* dimensions, npy_intp* steps, void* func) .. cfunction:: void PyUFunc_D_D(char** args, npy_intp* dimensions, npy_intp* steps, void* func) .. cfunction:: void PyUFunc_G_G(char** args, npy_intp* dimensions, npy_intp* steps, void* func) .. cfunction:: void PyUFunc_e_e(char** args, npy_intp* dimensions, npy_intp* steps, void* func) .. cfunction:: void PyUFunc_e_e_As_f_f(char** args, npy_intp* dimensions, npy_intp* steps, void* func) .. cfunction:: void PyUFunc_e_e_As_d_d(char** args, npy_intp* dimensions, npy_intp* steps, void* func) Type specific, core 1-d functions for ufuncs where each calculation is obtained by calling a function taking one input argument and returning one output. This function is passed in ``func``. The letters correspond to dtypechar's of the supported data types ( ``e`` - half, ``f`` - float, ``d`` - double, ``g`` - long double, ``F`` - cfloat, ``D`` - cdouble, ``G`` - clongdouble). The argument *func* must support the same signature. The _As_X_X variants assume ndarray's of one data type but cast the values to use an underlying function that takes a different data type. Thus, :cfunc:`PyUFunc_f_f_As_d_d` uses ndarrays of data type :cdata:`NPY_FLOAT` but calls out to a C-function that takes double and returns double. .. cfunction:: void PyUFunc_ff_f_As_dd_d(char** args, npy_intp* dimensions, npy_intp* steps, void* func) .. cfunction:: void PyUFunc_ff_f(char** args, npy_intp* dimensions, npy_intp* steps, void* func) .. cfunction:: void PyUFunc_dd_d(char** args, npy_intp* dimensions, npy_intp* steps, void* func) .. cfunction:: void PyUFunc_gg_g(char** args, npy_intp* dimensions, npy_intp* steps, void* func) .. cfunction:: void PyUFunc_FF_F_As_DD_D(char** args, npy_intp* dimensions, npy_intp* steps, void* func) .. cfunction:: void PyUFunc_DD_D(char** args, npy_intp* dimensions, npy_intp* steps, void* func) .. cfunction:: void PyUFunc_FF_F(char** args, npy_intp* dimensions, npy_intp* steps, void* func) .. cfunction:: void PyUFunc_GG_G(char** args, npy_intp* dimensions, npy_intp* steps, void* func) .. cfunction:: void PyUFunc_ee_e(char** args, npy_intp* dimensions, npy_intp* steps, void* func) .. cfunction:: void PyUFunc_ee_e_As_ff_f(char** args, npy_intp* dimensions, npy_intp* steps, void* func) .. cfunction:: void PyUFunc_ee_e_As_dd_d(char** args, npy_intp* dimensions, npy_intp* steps, void* func) Type specific, core 1-d functions for ufuncs where each calculation is obtained by calling a function taking two input arguments and returning one output. The underlying function to call is passed in as *func*. The letters correspond to dtypechar's of the specific data type supported by the general-purpose function. The argument ``func`` must support the corresponding signature. The ``_As_XX_X`` variants assume ndarrays of one data type but cast the values at each iteration of the loop to use the underlying function that takes a different data type. .. cfunction:: void PyUFunc_O_O(char** args, npy_intp* dimensions, npy_intp* steps, void* func) .. cfunction:: void PyUFunc_OO_O(char** args, npy_intp* dimensions, npy_intp* steps, void* func) One-input, one-output, and two-input, one-output core 1-d functions for the :cdata:`NPY_OBJECT` data type. These functions handle reference count issues and return early on error. The actual function to call is *func* and it must accept calls with the signature ``(PyObject*) (PyObject*)`` for :cfunc:`PyUFunc_O_O` or ``(PyObject*)(PyObject *, PyObject *)`` for :cfunc:`PyUFunc_OO_O`. .. cfunction:: void PyUFunc_O_O_method(char** args, npy_intp* dimensions, npy_intp* steps, void* func) This general purpose 1-d core function assumes that *func* is a string representing a method of the input object. For each iteration of the loop, the Python obejct is extracted from the array and its *func* method is called returning the result to the output array. .. cfunction:: void PyUFunc_OO_O_method(char** args, npy_intp* dimensions, npy_intp* steps, void* func) This general purpose 1-d core function assumes that *func* is a string representing a method of the input object that takes one argument. The first argument in *args* is the method whose function is called, the second argument in *args* is the argument passed to the function. The output of the function is stored in the third entry of *args*. .. cfunction:: void PyUFunc_On_Om(char** args, npy_intp* dimensions, npy_intp* steps, void* func) This is the 1-d core function used by the dynamic ufuncs created by umath.frompyfunc(function, nin, nout). In this case *func* is a pointer to a :ctype:`PyUFunc_PyFuncData` structure which has definition .. ctype:: PyUFunc_PyFuncData .. code-block:: c typedef struct { int nin; int nout; PyObject *callable; } PyUFunc_PyFuncData; At each iteration of the loop, the *nin* input objects are exctracted from their object arrays and placed into an argument tuple, the Python *callable* is called with the input arguments, and the nout outputs are placed into their object arrays. Importing the API ----------------- .. cvar:: PY_UFUNC_UNIQUE_SYMBOL .. cvar:: NO_IMPORT_UFUNC .. cfunction:: void import_ufunc(void) These are the constants and functions for accessing the ufunc C-API from extension modules in precisely the same way as the array C-API can be accessed. The ``import_ufunc`` () function must always be called (in the initialization subroutine of the extension module). If your extension module is in one file then that is all that is required. The other two constants are useful if your extension module makes use of multiple files. In that case, define :cdata:`PY_UFUNC_UNIQUE_SYMBOL` to something unique to your code and then in source files that do not contain the module initialization function but still need access to the UFUNC API, define :cdata:`PY_UFUNC_UNIQUE_SYMBOL` to the same name used previously and also define :cdata:`NO_IMPORT_UFUNC`. The C-API is actually an array of function pointers. This array is created (and pointed to by a global variable) by import_ufunc. The global variable is either statically defined or allowed to be seen by other files depending on the state of :cdata:`Py_UFUNC_UNIQUE_SYMBOL` and :cdata:`NO_IMPORT_UFUNC`. .. index:: pair: ufunc; C-API numpy-1.8.2/doc/source/reference/routines.maskna.rst0000664000175100017510000000022312370216243023677 0ustar vagrantvagrant00000000000000NA-Masked Array Routines ======================== .. currentmodule:: numpy NA Values --------- .. autosummary:: :toctree: generated/ isna numpy-1.8.2/doc/source/reference/routines.functional.rst0000664000175100017510000000030212370216242024564 0ustar vagrantvagrant00000000000000Functional programming ********************** .. currentmodule:: numpy .. autosummary:: :toctree: generated/ apply_along_axis apply_over_axes vectorize frompyfunc piecewise numpy-1.8.2/doc/source/reference/routines.polynomials.hermite_e.rst0000664000175100017510000000261612370216242026742 0ustar vagrantvagrant00000000000000HermiteE Module, "Probabilists'" (:mod:`numpy.polynomial.hermite_e`) ==================================================================== .. versionadded:: 1.6.0 .. currentmodule:: numpy.polynomial.hermite_e This module provides a number of objects (mostly functions) useful for dealing with HermiteE series, including a `HermiteE` class that encapsulates the usual arithmetic operations. (General information on how this module represents and works with such polynomials is in the docstring for its "parent" sub-package, `numpy.polynomial`). HermiteE Class -------------- .. autosummary:: :toctree: generated/ HermiteE Basics ------ .. autosummary:: :toctree: generated/ hermeval hermeval2d hermeval3d hermegrid2d hermegrid3d hermeroots hermefromroots Fitting ------- .. autosummary:: :toctree: generated/ hermefit hermevander hermevander2d hermevander3d Calculus -------- .. autosummary:: :toctree: generated/ hermeder hermeint Algebra ------- .. autosummary:: :toctree: generated/ hermeadd hermesub hermemul hermemulx hermediv hermepow Quadrature ---------- .. autosummary:: :toctree: generated/ hermegauss hermeweight Miscellaneous ------------- .. autosummary:: :toctree: generated/ hermecompanion hermedomain hermezero hermeone hermex hermetrim hermeline herme2poly poly2herme numpy-1.8.2/doc/source/_templates/0000775000175100017510000000000012371375427020241 5ustar vagrantvagrant00000000000000numpy-1.8.2/doc/source/_templates/indexsidebar.html0000664000175100017510000000021312370216242023550 0ustar vagrantvagrant00000000000000

Resources

numpy-1.8.2/doc/source/_templates/autosummary/0000775000175100017510000000000012371375427022627 5ustar vagrantvagrant00000000000000numpy-1.8.2/doc/source/_templates/autosummary/class.rst0000664000175100017510000000153612370216242024457 0ustar vagrantvagrant00000000000000{% extends "!autosummary/class.rst" %} {% block methods %} {% if methods %} .. HACK -- the point here is that we don't want this to appear in the output, but the autosummary should still generate the pages. .. autosummary:: :toctree: {% for item in all_methods %} {%- if not item.startswith('_') or item in ['__call__'] %} {{ name }}.{{ item }} {%- endif -%} {%- endfor %} {% endif %} {% endblock %} {% block attributes %} {% if attributes %} .. HACK -- the point here is that we don't want this to appear in the output, but the autosummary should still generate the pages. .. autosummary:: :toctree: {% for item in all_attributes %} {%- if not item.startswith('_') %} {{ name }}.{{ item }} {%- endif -%} {%- endfor %} {% endif %} {% endblock %} numpy-1.8.2/doc/source/_templates/indexcontent.html0000664000175100017510000000554512370216243023627 0ustar vagrantvagrant00000000000000{% extends "defindex.html" %} {% block tables %}

Parts of the documentation:

Indices and tables:

Meta information:

Acknowledgements

Large parts of this manual originate from Travis E. Oliphant's book "Guide to Numpy" (which generously entered Public Domain in August 2008). The reference documentation for many of the functions are written by numerous contributors and developers of Numpy, both prior to and during the Numpy Documentation Marathon.

The Documentation Marathon is still ongoing. Please help us write better documentation for Numpy by joining it! Instructions on how to join and what to do can be found on the scipy.org website.

{% endblock %} numpy-1.8.2/doc/source/_templates/layout.html0000664000175100017510000000121312370216242022425 0ustar vagrantvagrant00000000000000{% extends "!layout.html" %} {% block rootrellink %} {% if pagename != 'index' %}
  • {{ shorttitle|e }}
  • {% endif %} {% endblock %} {% block sidebarsearch %} {%- if sourcename %} {%- endif %} {{ super() }} {% endblock %} numpy-1.8.2/doc/source/dev/0000775000175100017510000000000012371375427016662 5ustar vagrantvagrant00000000000000numpy-1.8.2/doc/source/dev/gitwash/0000775000175100017510000000000012371375427020330 5ustar vagrantvagrant00000000000000numpy-1.8.2/doc/source/dev/gitwash/forking_button.png0000664000175100017510000003144412370216242024062 0ustar vagrantvagrant00000000000000‰PNG  IHDR]Vl8EÀ pHYs  šœ IDATxí]|TÅöþv7›Ý´M‡„N]&„O ¨Ø ‚Xÿ‚(ú¤("‚}€`@z!Ò!@¨$†’ I6»ÉöÝÿ™{wÓHÅ ™ñ—½w§ÏwÎ|sæÌ,JlÀG€#ÀàÔÒi…7Âàp8œt¹"p8D€“n ‚Í›âp8œt¹p8D€“n ‚Í›âp8œt¹p8DÀ©ÛªSMY­Vܺu jµºN»:ëååH¥åÛ÷;ƇêЦš­£22“ð{ºwG(7oÞ#77·»ÓÀ}Z+»6žŸŸ/®ŸŸ_¹£¼Ÿ1æ8”+ú{2±²2+ß”¸'‡öÏèTnn.\\\þ½‡z)‘HÜ~…ûcŽCEÒ¿÷Ò++3î^¸K²³X,`B`«UC€áÆð«(Üïs*Ò€{/½22ã–î½'7Þ#ŽGà>F€“î},\>´ÒÈËË믾ŠåË— »‘ÒsÝ¿±/^ûã¡vàî…»„;s+p׃[ìîcFºÌ5ÁnGÈd2˜Íæ{VVÕÙ3g°hÑ"A0“'OF»víîٱ߹öÔnÉŠdÆ-ÝÚ•Ðzzz:¶mÛ†9sæì=33³Âžé¯¬C¿~ý0~U¡Õreõ$!nõm…åï,ƒWŽìÀŽ#q(ÏëšgïÛÝëÇõžÝŒX¶l™P844´\K7nÝ'– ã¢USÖ½Ûý__­äÎú\]¥ ÆÎê\²d 222ÊÅ@h[Ÿô/ŽA¿aã±îdrù]3\Ä»TnüJ¦Ÿ„ÃëýÑoüª8äaÓ»%ê&¼‡¾þ5ÎÜ2—_¤VNß«ÒnéV­ªä­„¥«Ñh°aÃ9rþþþ0`€0vïÞM›6 ýé§Ÿ.óÚ™Ù¦z$“ºÂ])‡Fg,°Z¤n.P:Ù 3U¥Ó•È+1áô7s°Bòõo ›±ô‰a³÷MáåMý0V½•9€¬ÆEG¤Óéðí·ßâêÕ«3f úôéS`å–f ùBqŸ¶]ÑÞ_¼ú—w3þ4&k%ÇdƒAG»=ÝÊpS‚„„*­V999˜;w.ŒFc$Ìâÿæ›o0}út¸ººèNANj̈́›B§ãá!@ö<E~‚Ð=«ÑÖ¹Œå—úžGå ‚~ÊÄúõJ¨k6hubC¡}Ÿ@#ºð“S1»ðÞÔöØÿã@H­ŽŽÔ³’ú^¬gÈŒ“n1´jîË•+WŸ"› AAA˜5kؽS6ùû÷ïÏ>û |o¯½öZ¶lYö¤`Ý–Ü>•ö,À´u©hÖ Ø½ë¼õÀÄ™Ÿ¢}Æ&|²ð~4ÚÄ`æ{óa{h¦i‹½_}‚UêΘóå(dí]†Ù³ÃDÕ7ê4ã'¾ãî™X®fm­Àû Z`ÖÝ¿òÍóµzd Þš0Ô¤¶/Ÿðƒ{qÙ«!ÆLœ‰qý‚í)5û(J¸/¼ð‚°À1û+p‹öîÅ©Kð|K+¬ˆÉbÕ§žÆÓ>ƺ³9BÖc>ÃGãúÁS‡ïÞƒôfDNÇþD‹™?À](§€fì[<kÏÝÀƒc¦c\ÍÜÕwviÁ‚prr\*ì”6v†ÉTþêìJÙ%m‡ã¿³ŸƒÔbÅù%/á•åQ8—`„[ÜBLÝjÀ´o?@ eöýw26؆cÞ»EÆ'6Wê  ºáÓù_¢¥ÕB8'áÓŸÁ^m6@m¸²_Ïšƒð˜A‡'|òñ„%=s§}‰]±jô8HGýǦ`â£ÀwgÀð¯iøà©ÐÇíÀ»S¶bÈœy ¯8¹ê|µb7r$*ôù&¦Œ¾ætìøá+ÌÙ|NècçãðÎ;#pí—‹ëûøžP”:ŠÊGJ+Ÿ•ç¬.™2«ƒ. ƒ÷½÷ÞÔ)S••…'Ÿ|RHcï_}õŽ=Zñ6P(Qø¡K¿‚ؘØUïN€œäø|úN¸6®Ø¤l޼Eäqb’ñçÆsÐ!»öœE²S0nlÇ"\íCo૯Bvn>ýlB{áo6IBѽs#˜Î-ÆF¸!#ðæØ¾ˆ=° ï̇D*βăÉèÿþ84ÉIÆêÏ!ÁVóë<³è.#\¶¨iµZÁÊe?`©(l˜÷ ¦6 Ó>üÎÙŽ›š«˜;ä pOøoʼnUŸãå— %/ÇÄàø®Í8. D/8˨÷Øö㻘vÒn¯â­'[ÂUH¨¨õ¿—þÊ+¯‡†ÌwÍÆÊ–-ð_|ñ…@´l1bñŸþ9&Nœ(rY-Ú47{=ÑQ‡±/ò²ÍWå[n4’b¢`vq‡‰=ýb,b®¨¡pu&=©\°Iâp`g8öíÙ‹Í+V!‚JJš@©ÆGc?ExF(>˜1JOâË ï 2/sÿó¡@¸~λváø¹ÄäHàª4ârl.Ó»í-¦,Ĩc‘#U"~ÃT|´bBǽ©zàDØ—˜LrKÙó“@¸Ÿï§ŽÄÙ]+ðÍÖd·)®ïž®ŠJ©¬‘×ü («'÷Y<3nʲ JZL鋿eÖ›E;ì)yèc3Qi²XŠÖÁÊŠ†Yc,^õº¹çAÿç>,Î#Elù ž%âüíÂIœ—_›ÉŽÆ™Hœ£B#ÿý <šñõ$àW»|ú,®S.‰‡ ¡ƒF çšqFõž{¼-.-ø’Rãû…¡—§=ºŸFެ”Š?„zG¿ãzy¢ÃÍãÿs> 2È­¹0ŠÛ.峂d¡ËSrÌ%«b>\fá1—‚ÃÂeÛiggg¼ýöÛå’Œ£®Ü¸hÄç¹Á¦MEžñ(òp†]ŒÏ_î«© ÷ĶC`zµ³PÌç__c÷gA ~±‘œ¢ÂðU%µ€%äã•YtÈ5”îšq´ËžÕÈéÓ!¦kl—Å;HdiLט¿—¹\.ä¾8>˜n±÷Ä0Œy:Ì ¯aPK%þ:`#"ò€³DJ.œ])‹êb‹#P|ÑÀÚcìñ¶l,:¥hŒÕæèÕ‚NB"C^~.n,"NGœÀ.zc2øjb7Xƶň“ % ^æ˜ô.¥ Ôn›Jˆ?DKVfÊƒÆæ,´—´óô/S‡)]·.½Û`ÔëÓñì: ‘2= õ]¢§EªÄX„‚E>Š´H‚ý•“îí˜Üõ˜Ç{ Xºt©`qíܹŒæÏŸ/ûéðž={„~xxxàÍ7ßDûöíoÛ*|êÁ‹Ô]k÷=²&£è‡t’‹¢e“ANñ:³¨àÁÁm¶j>:E–ö”O![ñ¦N>Eµ…à‘üqóÔwøpþJx… Á›ÏöCŸ­§q˜ÍḬûlRRòõåè4TÆ‹¬ òk ¯Ɍr ôÑ‚TºÒ¢£ÛRF0rú,z«©pîÜ9pG%¸ñ4oÞÌo~êÔ)ôîÝû¶®dßžûn Æ…*ˆ XŠæ”D¥4TÈa3ë É'­§XJB%Qù±ê¡Öj`.ðKPžË‹°9êi ªÙM&[°Yp¸Ø{yq,ý¶ÐøY¬\0*9a=ê!Èß°a°ON:`ËÏAB,•l"–®ˆ€m°ÓûW ›—r¢~Å£cçaÇÎÓý¤h|ø4$ê” Ùãï`Bo3‚Ýó±– {Øe 5;¨ÕQ#m.œ™æ“81º0’½I¼ "'S3¼3~Ì^ÐfÈÓ˜ah†#1Ñ8½m²°kSœp`rGZ¨Ø(D}×ÊwÃo¨ôo5+ùÒûp_Æ +9[ÍKùcÖ;9Ÿ1czõê…¤¤$Á­püøq>|ì*OJJŠÆ\ ÂuX*Ž:e> Qì…ë+߯Œµá8²c1>[õ©f(hî^Ì de 7Ò6´éѯ÷û=‚.]Äéaë6íÉ yãê_Bz÷áÏ¡g#3.Ñ7 Í1P-FbM‰&'c3áИz…¹ ¶àô>î5¼<ë( /^Ç K¨’j(ǸO1wÙŸŽ|e=Ù?6”M~A ìßq`—l—Ñ©S'!޹XYJ­ÃN&&“¦<µð©Õ9ÈsoVCÔÒÏñëÁÓ_=똧¨s-? !:bsÓ"Ž“á. ŒÝÛ¿†½Ï›´™´/µÍRô…Š”Ê«ÇQБÇñ=Ë‹s¤ OÒNÇÁüáSÏÞ.€V“‹M>Œ‘tà×°}Ø¿úÁeº"±_^‹ê5^оÁžMNÖ¸.W ø6C'ŠË:Ÿep[Á°È¶)ÚùÈoÁ¢åÛ mÐ]h ——ÎÃúc'°ú›ÿ‚q½Ì&²iI>Û7`ßñ=øáëp!šöxhÞVEφ2€æH°GÃa{T*ŽÏ{ӾߊVC&ãÇï&ˆõ¤iɲv.¦ïÅp)2†’ñb¥rÒ-—»ˈ—Y±ÌçÆükÌâ:þ¼ðÇNÕgÏž &y ƒ@¬L±  ÁW?}@+ÁÖïÈç8w4¤åsщ¬‹…fF‰ 'àÚ²3úS9HF›@O4í)äð¯PZMhÔý1QÌž™£0øÕ p÷¢¼Q!E/GýÀ زö`òsaðò&^~È—ÃfâÝ«ïÁX¾h4|]DÕ7pT‘íö¾”èZµŠŠÂæÍ›…z/^ŒÔÔTÄÇÇ î†ððð²ÿ53û‰‰“ĉ,Ä"{e[C¼³ð}´¥#Æù¼‹™+N!£±vr_b\ \*w2²l%7=úâÓgÛ›„aáÎdaRíƒ.£ÂçŸ^H7n\AŽÒâ ‹¾Þ—Æ$ò ›-‚ ÂLj,´ð::SúžycúÞr67Š'×nApè_A½¸+YåÌ'A˜Ñâ“>Éœáó0|1Þ§WâågÇ`ΆH<öÎ'x*äAüß_ÈþëIS°"ü†PNøðÅkcˆ’¯oÁÇ“f!»“Ø#&Ǿo,Ä‹t(±rêË3i"máã7ÑÚ{è 5¾5 ÏN\Dó"Ñ›R"G½"úž_ÌgRØdUÞø¿2V´ª—ùÍŠœÞ–SÖqIŸ=Û?¶r2’eþ¶ÛȶD]R‰…®ÝØhûe†“w ¼ˆpMyhZ©=¥Ï#«Ïh•ÂÝÓ“&»‰¬6-¬¤P*/wò;Rùì\Ø\=i»&…U¯Zg&ÿœ&‹3|ü=)³LÈ5@mååh`“+ §­‚¼ê =žÙóR¹¼\ÚV;¹ÃÓZËË¡¾PÿŠõ¥Ä J|MKKCHHH‰Øâ_+ƒñ믿^PhõêÕ•©¢Ä³råJ@JúÙ…Ä>K ÆàˆgO©BCž‰–.gºòGþZ¬´-Ld•yz‰ó ÎcW´ qÏ!Üîžp‘Ka1h‘›_þvõïâPtüEû^Öûš5k„ÁmééŠ+d4FAwJd`´i•»ÀÇ®ÅÙÈÖgþ]–7×,ÌÅõ¯ )ÜH/én˜¨§”@í1 ¥¤ÓÒ7Èœ ×ë!wñ†—;¹¬ŒäÖÉÓCF­·Èáïqã{EÆ«ËñûË-É­ÃpµÂÅÇ®÷ÑíZ¤t¸+è¢IFç zèºm³ ŸvAFZX­Ô†…äéAòT’Îh‡“O"”;Ñ÷l Õ\v¨HfœtËÆîo¥T†J6Pé–ÌSæwRr™ýÆ€M¸vSfΪ%õ’Ò’U#Ú …Å‹.,VJ~CÚ4—š·°TåÞ*R\VKe0f÷RÙÙ¯¿þ*,^l×À2FF?üð¹¢qÓædÑÓ_‘_fÞ–­"*’'Ýo¢v(J¶Žž”çHãÏ*VZ`E·Â½<ñˆù^îá?´olëzÿ[wG8 7ÇÒòZ¸ß1æ8”'ý{3­22ã–î]’; aüÿ‘Vu€n ¿ŠÂýŽ1Ç¡" ¸÷Ò+#3~{á.É­xìÓq9ÿ.5s_VëíM¿¢ëvì6Gyá~ǘãPžôïÍ´ÊÈŒ“î½);Þ+ŽGà>E |Sâ>4G€#À¨-8éÖò¼]ŽG N"ÀI·NŠš#À¨-8éÖò¼]ŽG N"ÀI·NŠš#À¨-8éÖò¼]ŽG N"ÀI·NŠš#À¨-8éÖò¼]ŽG N"ÀI·NŠš#À¨-8éÖò¼]ŽG N"ÀI·NŠš#À¨-8éÖò¼]ŽG N"ÀI·NŠš#À¨-8éÖò¼]ŽG N"ÀI·NŠš#À¨-8éÖò¼]ŽG N"ÀI·NŠš#À¨-8éÖò¼]ŽG N"ÀI·NŠš#À¨-œâããk«mÞ.G€#À¨s8yyyÕ¹Aós8ÚB€»j yÞ.G€#P'p²Ùlurà|ÐŽG 6à–nm ÎÛäpê,œtë¬èùÀ9Ú@€»juÞ&G€#Pgà–n=8G€#PpÒ­ Ôy›Ž@E€»ê¬èùÀ9Ú@€[ºµ:o“#À¨³pK·ÎŠžœ#À¨ ¸¥[¨ó69:‹€lÊ”)Ó«:úŒ¸ó¸’fD}$U-\‹ùOîÁé›îhZßÍÞ #òr4ÈÕ›á¢t.èYÆù?p"Í­H¾‚¤»þbѦàÂ…x¤e¦!-­ð/_¢‚—›Ó]o¿x¤DE"QxR5|³ä\ÃÉóiðnàùÔgÌ8]‡ÓÜ¢>döò:­jpv“]9kMž–DŸ‰ÂM‹üT…ú¥MŠÆÅØtȼýQ R›qçÏ!1pËÇùsq°xûÁÔóç ¨çeÉɦK/Ìçìm8æàèöƒ04†sa£yF œíå,YW°cÿuµ DMkYa—Iߢ#ðGøŸˆwgòSp&"Vïúð(‚OaŸªÿ­êîRŽ“a¡ï…Ž_7…Ì`Â?â‡Ä·"°lÇQôk\Nȸr+~Ùƒ[L»ãÍW¡Í^w•þ¼ C¦¡…ÜìÈQ#OCj$6l(µ­=†ã¥íQ8}KÍV}‘6"öàd×ðuSL–ê«›j2dFaÇŽó¨×ís4‡Ö*ծŞ¥p¡Ý‹xÖU¼ìkØ´ügœM3ØkñÅàñ¯¢[ KíÉÓœ‰­[¶@Ûà)Ìx»l&!ÍŸ#¿ýŠc ZʧàÅN0³k¯"lÃVš C§DÒHtòÁ`Û1ü¾å2^êÔ$XŠL6]Â1ÊwVÈ7¢¹ æR~ÒŸtp vGxcʳççÃh+8·f6¶$wÇ'Óž‚‚*•ª<‘vr 66jŽÑ=«(‹* ®ŒÌjì_þ%ŠòS(0hqŠ<Š- úá½×ûóŒ’'Zw#[öDžt@cÂÐŽÏß©³¢²wä^pq§j=]àFÊ^¸vVÔTm¦qlÓ2!žÄ VÞ€1a?ï&Âm€áï|€wžë ¤žÄ°óЀ\šôE?V­9§;BèoŒÕI´3zŽýß~ó ¾¢¿YS' g#%RNüŽÿȨQÌHÖž.np¥…ªºƒ³P§3Ü”.p®"ÎÙçw#ÂàÑà ‹ÖŒÓV„Ûî©×ð“Ç¢nbûâÕH2IkOžò†èhƒ-õ*´D"Â\Ñ'"†—…¤K)P8‹6ºöÆ5¢T kßöðéð/ŒŸ0 ÃÛÕƒRéJ±„‘‹ ä%&›KË' ò¹”f¥éâðÛþ4„ŽxMäRX­ùHMˆÁ¡í+±%žø_啇èeòTKÄl\‡tÙì;؈YßáÌ®ýP÷ÚaÜŠ9„õ€<=4/}Ðkð |’ŽýŽMçåñÚP©[°îDú??|e°¤_ÀÏ«O¡Ë˜á0üq¾íÑHsK<Ðûé1TO=š•$_ªšõÉj³ÂF“ö¾õØq,^ ÷€v2b(ZûŠ“”ÉkÇ–}¸”¦¥r 4n݃†=26…`QÇ`ÓÚmBºG£ÎèÓ*s[ØÈ‚ËÁÉÍ•“'-/@ÙñEtt³ /ã2ŽD¡zð%¼öD;˜õyxña˜¶` "®êÑ,DYKòT¢U«8œk·$褰!ûúawU¯žé1‘H—v„»ÍŒ”¿® ˜µmá}Ú1Øvÿý´0‰–©ˆ‘ ’ÝoÑï×/öw£|„|í}%‚œD¤ÅϨ=›¡•4Æ€^õaÑ唫W¬¥81‚Œíröàa4Þ± ›OÜ›Ý<`p4]´Ò»ñ®>-—È%ÔtÞ®'`Ò!'WÇèÍŽ'çã|tœú5€9ç*Ö¯Ø ß.!H?´ê£1~@S$DìÇîÃg¦!¢¹Ðù¡'0°ok8[2°ç×mÈ h —´œŽ× \òèÈÿàÁ ÷ÌNmÃòØ“ˆºe â­1rÜH´°sIYv§PTѾ¸½Cê!,Ùz ¦ Þ>b0Z+Óq`õ÷8-±œ4‹ú&’5IÈ’*i…ë5f^GVB>ÜT®0§Ã×K6áz ÿ°§ÐÚ%‡6.Áïs…ÌQ¿/·ÓãC1bpO˜’Ná—…{`•0(wÊ•³¤Ð­ðPkŒ:ÔêR6ûÓF£†ÎhBÃÐöd‰ä":Å¡âÒ¤%زy%ÊÛy\ìð]ý4“eBDGÂÊþÌÞiïK$•ÄÚË[ðýÚHUuÂð1#еÞ-#|ÖŸÍ"«Ô„¬ô³HÏw#ëȈˑ‘Èκ†Ë©(ɇ—wаסA#?èS“{h'\¶¢×Ã}¤Ðà(YQŽ™Y0F Îü6‰p}„Q#…,õÖ|¿±4_`IšÅ‰P•è7t8†ô F- ‹×•ií.–Î_ƒ‹i&„öMg±ó@LAí—ÖýPiySãp¤Õ­wmÙõÐ$‘QM»¶†Õ”Ü|rU¸{ òKHÎÜIµ%Ïú-C„1Æ\ˆœtóúÅ˰)ÂèÿW2P… ¬Md¨,øa#âÓT:òQx“ ò9ߦ÷Z\»¬s÷'ÐLfA>[À¥5&MŸoÌ£´W'ïQñ B× ’"¢ q©1't™ÉÂ"Þçñ®‘Q”KºY°Ë·yáßyÀUîD˜š–„C;÷"Ú¤Bƒ OÇ/;Éèóè€áÇ¡gg¬ÅÁd ¤Æ\ÄÄ'!êØœ2´ÁÓÏ<ñÎŽe q1·pU¹zü’ýºbÀCíaÌŠÁª•'iùV¼Ê»#KׯxM¬ 4)7„Öžñ zû[Ñ­[s„ÍÙ@v†)]´BKKS*ì¤åVF6fIÑVbs&å4á莽”!÷È´6öì‚sg üsx¶[¤9ÚlÍ0pð#ð3èÑ¡‘–lÌ€ÖÉ J³¦Àg­äåçAâÑÞR3 F3d„µMâKäd…Yìu¶à‹°‘Xˆ˜lr_´¢­udÒMÈ»!?¿f|»…ý`ýI—ïFÀ©(Ä¥g"W$ êŽ©SŸ‡?YJÝÚ¶€rÞlÞsçt‚ûÖœ§‰Ü³k&R©0É,ábœ»µE<=á;ÍÜ$ˆb²TvÁû_¾€F2+Ô­¬˜¶ô(Òr¥x È¿oo!+a[ŒÁ¿Iƒ[¹Ð.Ðÿ·`öE¦£C/3aªÄ ÷§â‰±ïÊIDATF6õÝ`»ú!vdåÀÙÝI‡÷#:ñÄÛÓñT ZT=„ÝßÍÀ¾$&{Úö¦+-O³^#X…A>¤c Ì01x(˜`6Ø1“Ê ¢\Ìg/‘IkMžòÀ¦"ÝŠJ¬£/.\¢E½K[4iî†@ê_Ä¥,ô훉hZ5T=:À‹d™f?Ê’Ðä47Øn@{óm…FÙïL-\-¸yM4X>'6icâ‰Tr9lthæðåJ¡GN}g†ùr…ÿ¨¢öÞ>\‰Äuó#¨O¬ìˆ/¨÷.¼Ød¢ëŠí':F¸6$ûvgËp&þ7Ú0üeÚ¹Ù;¤j?Ÿ¾B;W*s=ül½ñɇ#ám5ÁÐ¥>þúd þŠ¿…aìF˜ª¦~0 þ”Þ­‰ >Ÿ·‡Ïe"4XP£G^ÇûCÛÂf1‘¼f`ÙÑDä¹=ý²ùÍEf@¾¹ê‰£ý@º6 Ò1X?{2ö6C«mÑuÌkh¤„ÞDi±¥¦i/–Ó( ;›£HÂö•ÿ£#¬¤$·2h)óaQz#°1hfÅãˉ °YK´éØÏOì òi»m,Ð?-’ã(‚ao³Ðak—&©Â*"™‚ÕÑ·ÚH‘IØú+q0<Ó”R ŽŒ5ÿÔÝ$ ! ½…—ëÈ/èÿHw"\4ä~1‘߯u›@9ƒL·GÐAeñ+ÉÐ7KE’ÄÝ{¸àäñKȲú!:Õ†àa¡PØŒ°ɡе®Úì\:1oJÛÝ£`óÞ©ˆ…oÈ¥cu ­ÛÁbÐBG˜z·BWZ¾õÈç $^ˆ!g¢67: Ìc tîÓÎf²É áÑq$&ûÆáÐú_p=ÉIéB-þ4ÍåÎ"ÅÕ{ ›8Wè¶’É#zlB„Z%ÛÖRhEìk5æ!Gk Ã4êí(ÕF'4 ¤ÔÒùͪe}-‰.«­üPuK—VÔÂ`ƒs@|ú^+D=޳ç.àôáxúÛŽ.#ßÂà6½)­E©i* ¥i£ÉÁ,<›ýâÄ¢F¦–ڡÓ)Vjq%|°;-®PhÂþk&v!_ޱ㈊¾„?ãéoSc¼ðþ‹ …¬0HTÒ#â[ Tµc¦v$zÚ¾é-¨O¬ËFd3³[ 7PÑ·²ÚŠŒS.#!ПUq—ƒÃÒeÍ8p›´àÆ4š€è«”F`#¢µ¢èI žŠ÷HØ»Úvöñ“çq6RMdŠÇû×ÉãÛq*Ò—HX‚gÈ÷k1d m°úmT­@R’)[ X“‹ø vŠÁð©çI2!ådý”0Ë’ž¬yÃpÌþvŸ;0¸Úö iÜf" ŽY²i™d±‘ÉâDÓ!ŸY£”Ó¬3®â–§ÝP’gçJÈ“Êå¦Ý{%!r°P]öõPN“!CÚV¦ÚÇÁ:X[ò¤ià¦ìAxx2õÛ«ÈBÏAóvͰoWöf«›:4UÁl$Ý+Š"R„¡gCéoàÚ¦å¸Øñ-4p/ÔH†gQÝacfANDf5Ñ.Äþ]ˆ,ªÛ$ –&æ&ñÓ¡&]¥ 9Ùã BÁ»óÁæ ™™¹°5$Û•úÐí_xùaÜIã6ÎÆ¢ÃÌÕBóõKÈm&ß=é?åß¹«OgQ¼!x¸E=ì ­:Ǹssµ…s…^6'»_“ê3YÌ0ÒùI!6€Œ‰À¾Äa­Kå°Ám|„žTõ£ê¤[0hjŠ:žB‡4»Ršâ¥§GâÑgÆB¦ÅŸ/AT¢}õÛ°!¡I©iCÛ‹+Œ\F“Ž®ÑØlÄÆpJUæw â]»àµqOÒ¤"å¢ týà:¸Y~²,„‡­„®Ó óF‘¯"íø/˜óûĨehE–@Á m“Ò‹:ÊH—Mh{ùøQ}±¸šlDò¡1ë7þR4ep&ÿmqàÙ+C[ÅD/•£Ç]ŽV q[ÕÆÄîxêÃN¦«-lH©7É”¤ *–ñ±©49û€vý0µiú›ÿü{= ÿúîhN¾Ã=ë)BÑ !~2rHÉXX»B=4΂ûägyXó§ý•¢FH¶…§8Ý üE  +À§EÇP Œ›õ_Ð-("Cv|±Ä‹TÎÍšùàØ©KHÒS_ìXf&±­›äY8°vEåäI¹ëµ †íø9h dýP]Êz È:.ž½†'ž¤M;ÅÓDë±-ÛÄ‹cc‹wMË“º ÿæ­¡ìÆ‰„YÃrµÂm¦øŠß‘ï×_ŒÏ*” ++àÌpýèCtJ߉ßîÄÒ° ˜ù,ù³Y{°’U!ÈÏaßöÆÅeÀÒ²^ñ4{F&G»¼ôêã4ÊèÑY\X…ŸÃc Ñi¾GÒ%hØ£TV:@ðk¦ví i׈¬Z6e7Èwع³°Õ2VÁåÚ¤£P߉Ÿ~©äèr“°kÕäÑbøh¯¦’œ‘r\TnÄ]ÄÎ_fcÿ-jÌxùV4hÛŠ&sVü´‹üÅj\?µa„¹$NÐÄ'WRždt;³Ëò$d¥LV;Ü[ GYJG~Âö¨4d%ŸÅšG¨ê&èFÖ£…üøtì]kò”ù#X)‚:‡ÂÕjÜ_Ÿ`´pgxý!$7ØUÞÛ¤yž`X{úARôïØ™@c¿=caŒ‹ù&ůN%È…Å:æ°ãé(h6“WÑŒ€"ÌãH¼[O—æØ¿ éÇE,˜õ3NÅ^'«7—Oí¼ï6‹'[ºKöUèŽDt’ÿ ±‰Ä?gcñŒŸè J™töAÃ`V»>rV»­:»~^O÷_$èÚ™Ü9匉µgѧ—Éo¥áZNuIU·ti ª$3KB;fA4¤“ì.AÄú¥ˆpTëÓ#z5Acót9Eñ¥¤Y¥* ¢<ëŽHóSI_4!4ÕK¬×°Ïh Êþv†ÿ†…ábÅÎ-ŸÄäÑ!3iÑç™Gðךpüöó’‰!¸ç hçE–YqÚãÚ´…äÄ\#It ¾[”Í0vìcX´òüò=³p)>Œ)/Ðé)mõä'd–Û†?Ô>€êb–]y⫨ŽO›M\žÕ1‡±»phðmÕOÓ}ËP/+ù^5h5p4ú©WàÏ]«pa—زO§§ñÖ &ä6È…Yê¡*\»ä‚6Ád½g#¸UàZ,)#a=MpǘèIãÆHO›Íäeߙ²4Èbø+C±fÙlZö½Ð [äz?? =ü¤Èíæû®ãðÚïÁ¤ æèÙÙÇÏ^Àü]1ó©Ç1ö1 VþŽ%ß… åÉ•“š¢ ƒTwôÙWVWNžò€æt…®^MÅ@oZåèñÜ+È\¼ŒÚ_"´o£_ð=ýÑ4w1#—¬ÇÚ’§0Px£EKwDǚѵ]¹ØSŠm3ÙhÚˆò'R¼T*ꀓŒ…ë™ɂ¥µ#Ÿnä…•8ñËtyîœS`ù×QZÑ–ãüᓸ9d˜à2³’»`ã9“¿ä+¸ˆ„ÄLœ>M‡Î¡ áLŸšæëeM„†½ŸÇK®û±vGv‡]+hRÑêQ¼Ñφ—Æ’™é¨UÐO6fÁ•dU¢C¿ž8²ñ8~ž+Îeßö=Ñ9‹Ü×c[§ÿˆ÷©ÆÈKA› !´ô†6w沸tÉõÆ‚Û Ö^ýîÑåBéüf±;„òW5H«^ІáîãC?K4 ëÝ(èNiŒdQ8)T ŸÓ¬FnŽšüå¤YEì©ò†‚¶,t¿H樗ù.éÆŽ]®tp¢"W])ÉÎÖ ÞýrA¯¥ƒ5µ›*Òé`…9Ãɹ^|PZìþf>N·‹ÙÛ"ÏnNH­f:tcë™þü¡ DE÷)æìêYØ~«fÎ|JMr+sjQUôËÈ/QxÀ×CôuÍb¥“Õ|M.ô •ƒ[ГÏÎÉÍÞ´¹"2ÍQ“ÿJ((‹§/ÜäDÔYY‚ËEîæI?vÃX0&)<|}àlÒàV®AlŽäéãK¿”ò éZJד_Ö –|-Œf'¨üÀDbÊË·Yt`&¡ëwV…+|¼UtKÄ‚’•³§'YwZ:H¢ò4™ÙÛ*á ÌJ %åÖÜÊ‚™nTNž@òŸËðóaW¼;û%xÐ1ûpaÎ×ÃLóÈÍ¿¼ÉU¤Sg ò®My::çêåWÚèÔY:ÈÒ”*_ÁwY(²ëÈš÷%pYœÆæFïrZ<²Äb’7ɇ~?M®ôã¢eÅöhªdÂìE{ÐçixÌ×*èµ# ¨hSId‘Î3}ÑÆn÷ëÎcä´oÑK•[95w?]ìÍs¥é€N˜Ó Wï‚9¯Ñ‘žºÓŽˆô„îÑOQÓÙ¡¯žÜ‚Ž2V2Ìrò‰W”‰˜ýá k3øt@ -äê݂ɢƒ³¢X;æ¹ÂÃl :Ú+“ßJÝ™¢\Ú›äúõëÅù©´\•Œs"Ç´”&ž¶·&³}/o/[^š”@¨ù‹[¨Žf%”Î~Æê5Óê[,ÐA™\¸¿GFãm„˲”—fe˜K'\V–d"k®Tðir›¨MÖn©é¬ .MÆ¿;8ãÝÍsu*Â$TV–YéŽØä‹‘poýo kíJ ¢U-Öro~Z p/gRUk×iKJ„f$«ööùÀÒhñ³.kÖj)$\ö]”'åq°0‹t„Jʲ Õ7NGAê^ìÄ„¶ïv}° ôŸ&OÕñ L¿jÓ_DŒÎUXˆÊªÓ’ƒ(c3¼þ|WÚºhkpYI˜™˜Ý®`e )V‰2dÐí¹üèÖ 3YÝB½¥é^Ù5 )åqXE‹%W«¥[¬æ{ò £{Ñ¿ÖDWÒ²4â}À²ºéìá •“·²ézTY™x|­# UªàC·5[ä²:T§åIî/_w˜rÈ­ápM•”„~XäëåL[êìÂ,¥äûÇE1w™¹<õÏûš›$!!sJM ÍÛàp8„@µº8¢ŽG€#P>U¿2V~}<•#ÀàpÊA€[ºå€Ã“8Ž@u#À-ÝêF”×ÇàpÊA€[ºå€Ã“8Ž@u#ÀI·ºåõq8ràî…rÀáIŽG ºød-Ní$Íú„IEND®B`‚numpy-1.8.2/doc/source/dev/gitwash/configure_git.rst0000664000175100017510000000577612370216242023711 0ustar vagrantvagrant00000000000000.. _configure-git: ================= Git configuration ================= .. _git-config-basic: Overview ======== Your personal git_ configurations are saved in the ``.gitconfig`` file in your home directory. Here is an example ``.gitconfig`` file:: [user] name = Your Name email = you@yourdomain.example.com [alias] ci = commit -a co = checkout st = status -a stat = status -a br = branch wdiff = diff --color-words [core] editor = vim [merge] summary = true You can edit this file directly or you can use the ``git config --global`` command:: git config --global user.name "Your Name" git config --global user.email you@yourdomain.example.com git config --global alias.ci "commit -a" git config --global alias.co checkout git config --global alias.st "status -a" git config --global alias.stat "status -a" git config --global alias.br branch git config --global alias.wdiff "diff --color-words" git config --global core.editor vim git config --global merge.summary true To set up on another computer, you can copy your ``~/.gitconfig`` file, or run the commands above. In detail ========= user.name and user.email ------------------------ It is good practice to tell git_ who you are, for labeling any changes you make to the code. The simplest way to do this is from the command line:: git config --global user.name "Your Name" git config --global user.email you@yourdomain.example.com This will write the settings into your git configuration file, which should now contain a user section with your name and email:: [user] name = Your Name email = you@yourdomain.example.com Of course you'll need to replace ``Your Name`` and ``you@yourdomain.example.com`` with your actual name and email address. Aliases ------- You might well benefit from some aliases to common commands. For example, you might well want to be able to shorten ``git checkout`` to ``git co``. Or you may want to alias ``git diff --color-words`` (which gives a nicely formatted output of the diff) to ``git wdiff`` The following ``git config --global`` commands:: git config --global alias.ci "commit -a" git config --global alias.co checkout git config --global alias.st "status -a" git config --global alias.stat "status -a" git config --global alias.br branch git config --global alias.wdiff "diff --color-words" will create an ``alias`` section in your ``.gitconfig`` file with contents like this:: [alias] ci = commit -a co = checkout st = status -a stat = status -a br = branch wdiff = diff --color-words Editor ------ You may also want to make sure that your editor of choice is used :: git config --global core.editor vim Merging ------- To enforce summaries when doing merges (``~/.gitconfig`` file again):: [merge] log = true Or from the command line:: git config --global merge.log true .. include:: git_links.inc numpy-1.8.2/doc/source/dev/gitwash/git_resources.rst0000664000175100017510000000340112370216242023721 0ustar vagrantvagrant00000000000000.. _git-resources: ================ git_ resources ================ Tutorials and summaries ======================= * `github help`_ has an excellent series of how-to guides. * `learn.github`_ has an excellent series of tutorials * The `pro git book`_ is a good in-depth book on git. * A `git cheat sheet`_ is a page giving summaries of common commands. * The `git user manual`_ * The `git tutorial`_ * The `git community book`_ * `git ready`_ - a nice series of tutorials * `git casts`_ - video snippets giving git how-tos. * `git magic`_ - extended introduction with intermediate detail * The `git parable`_ is an easy read explaining the concepts behind git. * Our own `git foundation`_ expands on the `git parable`_. * Fernando Perez' git page - `Fernando's git page`_ - many links and tips * A good but technical page on `git concepts`_ * `git svn crash course`_: git_ for those of us used to subversion_ Advanced git workflow ===================== There are many ways of working with git_; here are some posts on the rules of thumb that other projects have come up with: * Linus Torvalds on `git management`_ * Linus Torvalds on `linux git workflow`_ . Summary; use the git tools to make the history of your edits as clean as possible; merge from upstream edits as little as possible in branches where you are doing active development. Manual pages online =================== You can get these on your own machine with (e.g) ``git help push`` or (same thing) ``git push --help``, but, for convenience, here are the online manual pages for some common commands: * `git add`_ * `git branch`_ * `git checkout`_ * `git clone`_ * `git commit`_ * `git config`_ * `git diff`_ * `git log`_ * `git pull`_ * `git push`_ * `git remote`_ * `git status`_ .. include:: git_links.inc numpy-1.8.2/doc/source/dev/gitwash/development_setup.rst0000664000175100017510000000661512370216242024620 0ustar vagrantvagrant00000000000000==================================== Getting started with Git development ==================================== This section and the next describe in detail how to set up git for working with the NumPy source code. If you have git already set up, skip to :ref:`development-workflow`. Basic Git setup ############### * :ref:`install-git`. * Introduce yourself to Git:: git config --global user.email you@yourdomain.example.com git config --global user.name "Your Name Comes Here" .. _forking: Making your own copy (fork) of NumPy #################################### You need to do this only once. The instructions here are very similar to the instructions at http://help.github.com/forking/ - please see that page for more detail. We're repeating some of it here just to give the specifics for the NumPy_ project, and to suggest some default names. Set up and configure a github_ account ====================================== If you don't have a github_ account, go to the github_ page, and make one. You then need to configure your account to allow write access - see the ``Generating SSH keys`` help on `github help`_. Create your own forked copy of NumPy_ ========================================= #. Log into your github_ account. #. Go to the NumPy_ github home at `NumPy github`_. #. Click on the *fork* button: .. image:: forking_button.png After a short pause, you should find yourself at the home page for your own forked copy of NumPy_. .. include:: git_links.inc .. _set-up-fork: Set up your fork ################ First you follow the instructions for :ref:`forking`. Overview ======== :: git clone git@github.com:your-user-name/numpy.git cd numpy git remote add upstream git://github.com/numpy/numpy.git In detail ========= Clone your fork --------------- #. Clone your fork to the local computer with ``git clone git@github.com:your-user-name/numpy.git`` #. Investigate. Change directory to your new repo: ``cd numpy``. Then ``git branch -a`` to show you all branches. You'll get something like:: * master remotes/origin/master This tells you that you are currently on the ``master`` branch, and that you also have a ``remote`` connection to ``origin/master``. What remote repository is ``remote/origin``? Try ``git remote -v`` to see the URLs for the remote. They will point to your github_ fork. Now you want to connect to the upstream `NumPy github`_ repository, so you can merge in changes from trunk. .. _linking-to-upstream: Linking your repository to the upstream repo -------------------------------------------- :: cd numpy git remote add upstream git://github.com/numpy/numpy.git ``upstream`` here is just the arbitrary name we're using to refer to the main NumPy_ repository at `NumPy github`_. Note that we've used ``git://`` for the URL rather than ``git@``. The ``git://`` URL is read only. This means we that we can't accidentally (or deliberately) write to the upstream repo, and we are only going to use it to merge into our own code. Just for your own satisfaction, show yourself that you now have a new 'remote', with ``git remote -v show``, giving you something like:: upstream git://github.com/numpy/numpy.git (fetch) upstream git://github.com/numpy/numpy.git (push) origin git@github.com:your-user-name/numpy.git (fetch) origin git@github.com:your-user-name/numpy.git (push) .. include:: git_links.inc numpy-1.8.2/doc/source/dev/gitwash/following_latest.rst0000664000175100017510000000211512370216242024421 0ustar vagrantvagrant00000000000000.. _following-latest: ============================= Following the latest source ============================= These are the instructions if you just want to follow the latest *NumPy* source, but you don't need to do any development for now. If you do want to contribute a patch (excellent!) or do more extensive NumPy development, see :ref:`development-workflow`. The steps are: * :ref:`install-git` * get local copy of the git repository from Github_ * update local copy from time to time Get the local copy of the code ============================== From the command line:: git clone git://github.com/numpy/numpy.git You now have a copy of the code tree in the new ``numpy`` directory. If this doesn't work you can try the alternative read-only url:: git clone https://github.com/numpy/numpy.git Updating the code ================= From time to time you may want to pull down the latest code. Do this with:: cd numpy git fetch git merge --ff-only The tree in ``numpy`` will now have the latest changes from the initial repository. .. _Github: https://github.com/numpy numpy-1.8.2/doc/source/dev/gitwash/dot2_dot3.rst0000664000175100017510000000125112370216242022646 0ustar vagrantvagrant00000000000000.. _dot2-dot3: ======================================== Two and three dots in difference specs ======================================== Thanks to Yarik Halchenko for this explanation. Imagine a series of commits A, B, C, D... Imagine that there are two branches, *topic* and *master*. You branched *topic* off *master* when *master* was at commit 'E'. The graph of the commits looks like this:: A---B---C topic / D---E---F---G master Then:: git diff master..topic will output the difference from G to C (i.e. with effects of F and G), while:: git diff master...topic would output just differences in the topic branch (i.e. only A, B, and C). numpy-1.8.2/doc/source/dev/gitwash/branch_list.png0000664000175100017510000003206112370216242023314 0ustar vagrantvagrant00000000000000‰PNG  IHDRyU¬”Ä pHYs  šœ IDATxí]\TÇÖÿ/»ìÒ¢€,ˆlØcLì-£FŸúŒ1ïÅó½˜bÌSS^¢‰‰Qc‹½ FÔhìŠF‰Ø+¢€R¤³KÙÆ~gîî‚ » ˆèÌvïzæΜ9sfî]‘žxàp8§›§²W¼SŽG€# À•<ŽG€#ð#À•üSÌ\Þ5ŽG€#À•<—ŽG€#ð# ±¶o¹¹¹ÈÎΆJ¥ß³µ=žŸ#Àà<^DÖœ®ÉÈÈ€R©„ƒƒD"‘ðÿxÉå­q8Ž€5XlÉ3 ž)xGGG®Ü­A˜çåp8Õˆ€ÅJž¹h˜ÏwÓT#ÇxÓŽGÀ ,Þxe>x8ŽG f!`±’gÖ;óÃóÀàp85‹Ý5¬KÖ¸i4 233QPP`U¹š]IJÙhooWWWØÚÚ–LäwŽG š°JÉ[J#SðÉÉÉðôôD@@¤R©¥Ekl>Öç””áh)Wò5–œpŽÀS‡@•(yfÁ3_¯^½§°ò:Ä;ë¯B¡Sø………åeåñŽGà±!`•’·Ô]Ã\4Ì‚;ÄN"YŠÕ³ˆï3G€#ðø°xãÕ’˜‚{\4ea"‹ùuYÀð8ŽG Z¨K¾Zzò„5Ê-ù'Œ!œŽÀ3Š@•XòÏ(–¼ÛŽGà‰C š-y-bOîÆÖÝH. #šv®yn0^z¾ ìž8¨¬#¨*,ù¬„‹8ô< ô¶ö¨‚ÐÖ Qýg—tHˆ¾€çFòuµ¨Ç”;5&ñÙZø6oÚöæ*qýÌ Hüš# d‚y¦Ç~­L¼ŽëYŽhÛÜb [W?¸ˆýç€ú¶.!ê|%tR'Ø—ªH¯V"5+ÌÅèàê^”þàâA\FKôn]Ç–+/ë÷$$i&-dnÐÌjù2Èfn­fhæãh1¡†±vÆQëáÒ0¡¡KÉŽÅÕUkƇ |5•ª¸ôØ3w > Ï,Ñdľp,ð]¿¾ ï)5ë¦R±‚Ñ¿ýŒ-§“drgˆ9ˆ½~‡´ÆëoG]YuⓇ3›Ãq®ùX|õª”ñ§°,,ƒ¦Ž€oõÏ@d=ä#rófD±‡¶/è0gr[èM‡Ÿòïagx8Ôíkaö°FPkM eã™|z+¶Äøáµ1Pb®(;û_ŽM:·;O·Bë/@¬¢I½Â𔨷l.µ˜€Q2äæÒó)¬Œ.‹¿X¿±30¼© )c"°pí!˜žc×CŽ^£Æ£WóÚprÖâè**8 ¶Ú [®Ì Içv!ü´¢Ì*õm&à«nPite¦—©Wá"ÉæŸ!µðñWU 0ÜØ· N&Õ™ÆÚí„Xœ=&MEW§2›zR#­Rò•Ù‰‚[ÛŠ|Èø0¹{}ÜØˆ¹kŽA¿ÿ „ù#Vf“5¶®ç¶ ^Öà9¼ýúPÔ£Wéi’¼q`~Ú}¿Fv»=} ©XTöèùúôôi ;ò´™HN¿ {79lséHiµÑUÜ]{6.™F‹Ûƒq-ñ¼¯Ä ÉŠ•уÜöt*ÊÁÎj¥Ií—5¿ÒdÞEú]wÔr¶‡:'žÌKZw-‘Ь-u†#)lJ>óâï8­’còˆ`HD¹Ð«Òq+æ6.FD:5ÝÜEG© Qœu‹×‚—5À+SG§àÂ×lÇÑMah<÷mÔóïŽ^'±vÃ|>±*Ô‹Öu푹%[’m;Œ1­]±BËœá UY§ä©5‰œ,q{Uð÷ÁéÍ_·¦¿1õeÂI¹ä‹{±`åïØ¿r)¼f¼‡bºÙ¡' Ñ*%_™Ö©VcLCðÙÛ#áI`´oÛškñep7=Çv,œ¹kgŒé>~>z{€P&vÏ|½óš ~ïôoLÚ¯ÎFØU†¼7ýK ÷wíÑo@+\Z4÷-ÇÒIm‘uó¾þlN'²¶œÑaÄd¼5¹?¼=R±wÉ,X¶¢Zð é†OÏ7±ÌQyX=ÀÁðëDOS¼ýîPÔÕ©¡ÈRBCcµvûþèy W™þõ¡WdáÒ0üv2VÐgN^-0hä4u·….å~Ù߯H?s×3DðjÑ;ºâÄößq#S©[Ƽ6õÉDM:ŽðÛr„6ÊÇþߢ ”¹!¤ï`á&ví;‰ bŸoûáG˜J¡ÅíÓqÏßÎÞwñóš“`/ÀX=g>ºŽ‹6vñعu®$+©24 Œa/U©%lÃû­z£6fnÀcËÃüÙ¸0íEilRчžÌ{Æ·ü¤‹Ø±å €‰L^û Às­¼‘HVüÚ“ ʉϿÍE&yø#ZŠ‘S†À›\! ³-‘Yè5öU´r ˜¯Z…vãÆ¡§®\Þ@€°•ûáÞ.)û‘ÝêUô5v@Ëè£ÿxªû·È8øö­Ùh1¾ýìZO@kGšd³ G«©u[h ã{tCè_j”1ôÿÞB(ydòs]0zL >[y±É"4¬c‡Ž/vÁÑõaˆÖ´GS›<#S]Uù͸!¢±èê)'7I¶pRÍô:½F‰,u!´Y·°{k8Î'/Hž†ôÆ~á*ÖãÁ¹pl¿] Ýüع' Á¯¾%KÒ*†ñ7 [·âB¢úO&Æ ¢éðØëRK|4c$¼„±–IcZñë„7Ǧã›õQ8r1 A]eˆX»·ý`t¨¯PƒúÁ9¬Y{ÞÀïÚ´„Õ=@į»ðÇ•ÈähÖªúõ5ÐÉd)춦Œ5ŒZmžÞ´ñ†`Do¡¾òäÐD¯¥ßÕ·ñªQi Ç”©³±~Ï1ÜLÈÄ ÏâìÙ³Ø>µµdþi¦àYdÄšYè7~=r‰qùÉ'…ˆø\C}"-âÀ™3ÇGKMÓ}D8æÎ˜‹ðxà¶B eôzôý>öEÇ ¯_ÈÌŒ£åî'ðï_Q%6¼ÞŸ0ÏjÕg">j'fŒ=±´yð8C~M7€K÷¨GÊ47Û àÈâéýæ|ûQ8ID8¿i¶“‚wïУGö†8é 6ü°7•4^r’‘‘€“û#Ã;š¹ åʬX†ë6¾èÚ©)ÔÑXµþ4@R¡Êº‹äضçõè‚68³ó¬ÞyòÀ.n艄¨í8Lxˆô:¤^‰Å•T-h€Ê >O//¸¹åaëq%Ã}FŒ@¿OÜ<†•'°fkÐ׈·¦ô&%rë÷ß…-Ó|¥ 2uÒI|µôWRðä¾:Míï!bûRl½œ‰]-¸‘U‘>õêÀÛ]„Œ”óHÉs¤ºÔ¸zî23îà*ù”íˆb¢pO‘OyÝpeówåò†-1’’±g?®kœáãã'£›‹yá"Ö`ÅžóÈôê‰!=ÉVæAƒ;Ô«ö]¡× €”¹}À|:÷,ül \ˆdó vöEËÀžò£€Ü~ùj 2’Ó„,ô½–C {ÿÆp§˜sײ`WÊ—o^WU\ëA2Ÿš¬´Lal²ß±ÈÈÈ…Ž¬ú‚;X¶`-Α7¥ëW0¬{=Ü9³‡¬ì“P?óÒHn£#Œ<œ ®›°?!1{Vý‹çã0)ÝFý†"ÄËR3!Ôç§!‘*qî /k a¬ƒçÔ¸-Ò´’på:t2[dÝIÆ<2l üÐe§¿IãÒ^’ð¯ mt€¾í\p#Šè\w:¢S‡Œ»yptv(¬¾›9"Èí¥x”Z‹yµYòŽ­‡àµ åXMV )Ðùôo íGÍħƒWîI|±,Zˆ~qúÌÛ©G—`è{Ë ž·^B^lî%“™ßPéâ{?ü{î;èØÒ{?Ÿ*Ô+"ÿÿ–ÿ†nï'xå³ýÀÙEˆ¼ Áü3Œ¹~ødãZ i’ ÓGcþ±LÌ_÷'úÏê!”}ÔG¥Yò6b8’’­— P]@g±ÐÚ×A‘™NFÃi„ßP£~Ÿixw` i¥ÔÂÛ/Ü…çR0ÕßP®îsÿÂûCšÒr>÷Þ_ˆûž½1{æÔÒká“>›@,w ‹Ç e½;}ê“7È->ІßÅÛ}êC—{W>Z‰«wr0"Ð…@¦?¹>ê´ÀÈ—R0çç3èÿú84PÝÀaò0°[TíÛ£–ÍRD*9ø /Wó(+'0Ó3…®ÌƒGó¾è»#V"ªÃ<´2³ä W#ê7’Z¯|øýè…Pwn‡ß¾ƒ#/`ÔG/`Pæ5,=Õ ¯~¢Œ3pÒ_ÁÅÛè’Š»IT”Ú¹{9ÒöÍKßpïE$–\W•Ë›–¡Þ8·‰™“»”zÜØ&¥ƒ\:ò Ö¦‰»õ(̘ ™V…¬|5å(ÚƒEëë&%×[iSµ dhhc•h2¬W +[Ï–xiŒä…*r­"áìšDn ýî@tAm컣 £s i° ñE3˜C`r'e"ìëÙ¥Zk‡³‡ óÔ!$ÈC?œç¼l )hƒºÎ«°h÷>\ÊìO£Üv7#È  å-¶±šòb±sénœL¡ÇÄ™ÞÆš<ú…;]1’ùÉ÷£.¸^ma¬©M8Q⎺n"2Õ(d;Ã2¶Ž°ØF$`®—ë¢÷XežÛ‡ó*ú½û5úÖ—A«éf+ðý®ß£ê­¶bÚ×5¬Öé¬>‰¤9ìÐ Z+øa•’/êk%\ˆDÞ˜ºæ \8ˆm;÷ ""q™¢6†Y2z9^pшhÐ}©½pâÆ·ç«øWÐ2üDºÿø‰Û¤ä-ã~X…I¡®$ð©8þÀPnò§ÿDC;‚aè§ØÝæ5äëí!MÞb¬4Û–|‚ZJ]Ž0lgž¿†,ô€eNËi+7'Y/¹$42²®Ê ´¤¤1OFJ–Ü´…/t*%²s)²V„ò½©¡—§ͱ¦A¾$À¹ÈRÚ£geË Rðd“»ÆÞâ8òaR{"0EÒ¾2²öȪÊ3¸×ê7¨Mõ+¥†#µÈ¨’˜½qP¥Ê§O=å#× £œjK<ñÞ>펦ÍÑ*d0^ôyÀ)Å’MEª®’‚ŽZ 1‘ßnÂŽeÇÐê­zdééÉn£ "J0’­†ÝkVSGh0SÓIVDvyd½Ù‘RQAD–²šèV¡Z†§®ÝCAÃ$$ˆ<б“=þYúÙ¤Çö2 ×,Ú;( ´GÃ&Ðqo½ MÞD–(éO¬ú=µkÙ"¯N)î#‡â¥¬Š$Ü')qfõY ‡lzcuZ̶,É^yyš |þTј>´ †áχ`ÌÜp¡¿½àëÛ´g™2ñíäÞÿîëè3ð=*ÁÍ LJßÝ4 Q_bÈ?Æ¥"ËûtB‡ƒ…Äè5Ó0lêtŒèǤè0°¯Ðä¾Es°óÔeÄ‘ew3ŠŽt­:ÄloÚ±o ûz-Ñ€(ŽüùgDÝËB~Nö®ÝF® whꌅQºsTÞê eNŽº€\*›p‰Ü‘¸Ÿœ‚ø›×hƒ=ŸéI²òÉB´ºò¿V Ôp¦JœÐcD¿¢ÊDÌ$W]`°DöáÇð?Éê‹Ãé]+±p矈SÛ‘ –&< ù0h?ãôÍû¤¶i€Öpg¶¨G{!ÎhÜÀŽÝ’¤-ùˆ5x=š7BîÒÌ•%¡Õ–>Ï„ñïìºíHW¬fÙÅRæSáî*C«‡ŠÂ½+ç…,ööäû¥çR¶…mÃÎßèxà#¸mtah³GºSjKGMµl;öñƯ²ºR»IsJ¹‡e?íEj.¹¶bNâ—_I#È» £¿¬h¥SšßŒwzµ=úŽ ʯ»IiíGüï4ð¡£û~š‡GÎ".é½hbQÆãF26ùsè^OF‹_6òH"¶âèÍÚì=‚%»o qìÿ}'a ,û:ˆ½‡;÷ã«o6ãò•TòÓR·±¥ôøõ÷+´Áƒí‹w c™¢)X ‡V çÒÝd-”Øleɹ˜'¸„bMØWxÁÏ ”ñW£‹|òÝ_û ëÞbÚÝ #¿ Ãk=Ø"Ьõˆ3ÂÆˆÈíE,Üý)Ò:ÄwèûøÀ˜ž}•‡“‡P Ô‡„Öý sG1mü3Ï °¥/Óé…&˜·c¾@›žNœD3, zLžŸÇ’Õ‚` N–æ±ñÁÿMŽ†ä ¼ppÖ¬Z…Í¿ŸÚ¹ Æ}0=ëJ‘¯ª…“‡ .ù“]þ¾ùþD¥È:ötò  *ò˳`KŠUÏÞä»e¾'_™wZfȧ'eRtMé6郃©<óÙÒ¤"ì°ò¬rúfÁλ1|éúò¾Õ8œ×#Cü¡ºü;-ø oÄ…LglÝH”-“'Kq*7õÕŽõ“YëfmÚxcL¨@³ŒüÙ,­n×±èßÚ±G6áÇ ±ùh4¤ûbú«­Éz×Á¹®忇°Ÿ– QGÚx¢U3U\ÍêËÉVˆúMü…:CÚ2¥_×#y“—«ÎêKаe”˜xAtÛÔÅHéÅbë¡8aÁ¼¯¶^„ÕæÛIñižÆ®–21¾³o£ øàì>ìÜ{'NàýGFžÀÝ\[áĉ:å®ànjÝҋʰ•!+ÿþIªØé%1¹ËjÏί'ƿرGðÓüoðãÆCPÚ`êôáÓ„X "žPy™©¼QÎe «Ï®Q t†êú6œdÛl¥ú$ñêˆÿ{ãea¬ÅœØƒ5Ë—ã·‹Ä9<Ù1%Åa,ÜzJ• ‡õ¢Ãžt|uÙX¶ýžÔgcÄÆ-¯¿Ü v©‘Xþã,Z³rÖÅØÿ‰zÄßnCÑŽæŽëûÖà{1î”JõÓ¸ÒÓ‘ÍŠäPpé•¢½,¼X¹ÚèÓ‚kñ/=xðÁÁKÙ‚ª¡LMFf3¥${zÃÕ`•(ª¤³½Ø’ÕâSÏó!_nvjªð¨¿«k©£5%jyø†µý@‘[{ª×ûáz³R¡ ?©]-ox:O×TÃÞ§¯TÒ¹ÅJb©ŒN„Ò9æG;Ð;ûÉJ³9ÙÈgç)ˆ¤dýѦŒZ+³§èYhr³¯¥49Ü)BM©9ì¡r»ÈÝÝ S+¦0l¬ÊänKéH]º¶f×,÷CåE2¸¹ÓÎ#mÄfoX]R:ËœžCÇLÉ_)st¢'ëJI›\ªäæé!7ú­²fTŠLÃÃ9Œð*6prs£Í{5ÇË)a™ }–Ù PèÃÁ¶6ZÚЦ>8І&QW@Çùèõ”*¢ О6édb(3ÒèÈ"ml»¸ÃѶî3„#Œ¶Ž.ôm-aýhÞÀˆ¥Ö,¿9/þb’ÑZŽ„'½Ž ƒalî]ŽUÇðÎ!7n’%—W7õ¹¬Àh>¶bv§wÃܹ/ÁÎŒ¦²òWvœ¤OÓ3rטڒО*_ É“··ì”Y–pZæáò9·%9Ïäœ\˜®np c®*Ú¼U°ñT*ˆé‡Ž ssH>IdíŒ2+)@ÔÖõHk1/6°xÀ6Kµ…’ug:JITÐoIˆi£ÏÄwv^"ŸöÀÄ2¸Õ¢ñJ’——eØ0†ˆdŽVØÚ9’Œ9®ÑB:MgOËa)’˽µJÉK~¡D™§’µFÉ—YI ŽdJžýxHÕÄd•ذµ,YXZr<e]æÝápjU¢äY¿™¢ËÍeo.á#Ààpª «”ò²óªoaÞ¬­9ëC4v(; Ô±XøéÏHD±òÓËðê›ãÐÒ£"bÊ©³‚è¼ØpÌ^-§³£<²*¨¢ìä¬óøø«HLûì Ô²Ü?¾ ’îÝÙP߯ÿfýŽqŸOƒŸ1½ìŠ_l^üq|÷Óä˜à—úcÔ¿&¡mE‚ ÊÇÖæ@=þ#ŒiªÃå‹Iðoç²–“¢<ìùt.Ôc?ÁÐrA”wŸÏY[L‡!ÔÆˆÀrdÌ,Ÿu—YØøÑWðzg6zy䬯ˆæƒŸÏ…dÒl¼àW5rh½Oê8!º¾ùtš¿ö ú74Mfz¢¹}Y=Õ!þÒ%ˆZ¡®Ã2Ê"ó1ÄY¥äË_eѨK;%(ønãßËP¥\Šï6à§ß㿃—U¤8Næ‹×'‡1.)jVk&â‹WÊ€FÅa#{Ä+D:(!Ãàiï¢ɈN›ƒ¨­‹±nÙAÌú°å*ac/ô:"L$-K1+ ü«¨M[àÓÿøPŪ¬Dܸv»»„Ú‘6ƈЭX¾ãf¿X~E-%ïSïñxû¹@ÈT)Ø·b6->ˆ&ÿ­{½]_›xÓôw°~ËŒ úÍËÒ‡²†þEbI¹xëðÚ»ïTþÖîÅ¿ÚS¦÷ƒ“F©‡¼Ürª´“›pѧ?F’‚/“WzôÛs~ú¿ 'Ó$øWü»åžÔqBt©uº’<2Óe1ÎmÜ‚üIMñJ9ÿß…¬¦”·JÉ[jÉ«rRˆ!r4ös‡˜ž’u¨ÝãÇtDZ\_ˆ£ö1µO$žX‡ÕWêàßoôsÎ5,ùñ,úOëŽ?ÿ“O`ëã*èð1úÔUbÏÊ8¯êî>fú7ÑC*ÊÁöEß"=)°?ÆL›€–î¤õM¡D@/CÚ. º Z5ñÆ¡ýh©¦øãëM™ã®¢þÄÑ9ûVo‹,>©G+¼2ik©q|Í \9Bƒl‘ ¡#§bpÛ:4]ÆÊ%¯¢fä;éU4"e#RÇÒ…§‘˜¤[ż1¹êPûyñg°båv$’Ë™â'ŒëoÇ<œ_‹-‘qÕ½ÆaBŸ@a’(êFÊ l¿ëMõÔ¦†ôH»]Þ‡‚”ƒ‡ÐGƒ¨7éö<Ô_ïAüfÕoÍç¥#ž:ÐÁ¿.lˆ>ûÚèÿêXäD@yu¾‹pÆ;¯÷‚$ñ¾]vC§OB \= —Á~Ø$Ø?mO`ÿúU k–ììi=³w67`Õ¸Û¼Ú¯!Ä2=Nl_‚è´$?ÝG¿‰þ-ÝMðÑ·-ñL8—湫iW`Ùú#$ hì‰\} ÆhŽèæt‰ÛyϽ1Qÿ”rxåŠ Ñ·ˆˆý«ÛšÂƉÀ(öÁè¢ üô¨ù÷šLAO„ú5€GÚ¬^¶Ý0šcüÔ¡ÈþígD²‚+W£Ã§¢aYÆK‚U>y·%ÿöuÛ¡1r°ò³0߉ÏâGÜ=|*ò,_?Ùñ'q;W„œÛ'§¯Cî®ß¿û6C1¼9)ë€~èØÀQk¿ÇñÌ ¼3óS¼1¸ŽoX8£¨}ºã£™ï¡{Öï½U’FR‚R‘¿®^µ+Öbù’ùøî@†t„œ:£Q¤ |Àð‰xÎû~؉à)bÞ¼™xÞá"6º#Ìm9÷‘ãˆQï„I=ÝpjËd"ë¾ß€Ì6/cæÜ1¤N 6¬üChŸÉŽw牘ùþDÔ¹}ײ W\Æ‚ÅÛá=ôMÌû>ºÚÇÂå'w ›#30îÃy˜ûÞËH>¼Gi0Ç:7õ)&¸ÓDÁâ½»ŽÂ‡ï½‰^Ô ¦è‹òº6G'YÎÇçÇ™ñíú8tøp‰ÿ;wï–™·¨N³òVÅ9øã¹ޝú~±›vÀùž58žµë '.÷ÈgzãóñǘԧÉÇâ.f×"öˆ„¾¨¯•ÍóôH|»ášz“pî‡Ü³Ws%9ñóJO“[ŠÈþdų6ÊåÜѱ.\ˆ+ÿÇÊ«'iœ˜ñJOtÒ= %dOT è ¥N«·!ÆÚ¼ys1¶ém¬]w톎@k*Я?ØüY¢l麞òû*±äa[“>ÿ/oÝĘ›¸y6‘Gw£ӫ˜Þ3„ì~Ä¥5Ã$IC' öeÞôhe‡-ד'½C YûœÛ8v’\.Lô’¯ UL; lYº¡]ÚbÜÛÿOR[f–KÒëµ³8ˆ´`oùT‰)žSxéY´É©ØYÙ°A¤¤¤@«Õ ýµ··‡Ÿ¯o‰¶„„Jù°G·‰³Ð2ñ®ßŒAÌ3´Z9‚Íî]1czg„`'bâR ¿™9­¾b¢ï"Y{ ðj[=.3Í.¦5¡»É…u“Ka1ušŒ6µ™¶+>|«ÔÎ6øƒñgt?ø9RŸ;õ‚lÿ6$åéÁØU:~ž°g˜Ù6CY<¿¸÷Á€ÖÞ´¢òÆð¡A $H=*äU^êâmxKYÆÖËâ%I¤dàd+ËÄÿ±òê 'r)fYy–<Å zBo×z"¤Ý€•ŠÎn>3úÕ…ÔA gï’:Âjª¸ÂgïªJ,ù¸£+±to¼·@Ï~Ã1åƒy˜>²Ò"¯!‡\œÓqh/YÂ~/`Äà–¸vô^•£SKï"½ÆÆ†égJLã„y[صž†XLw,‚‚–¬A/–6f˜gÀ¾é‚MÍÚ·AP›6hݦ†OCΤDß7Xt¬–_K.‘o—oÄ™ûJ¸4i¶¤÷Y–f …9xèÞFl0º¦i@ Cˆ'«—‰¢4¦FY¼Ì‘T½ˆâiJeù%‰ ˆ]÷G¯>àZ»->˜þ:w¬ƒ„¨X¼ð8ŸohËX«‡¡³o!Òì^H§†Qé¼ì^bk S14jÔ"›2ó–UÞš¸¼ø£øö‡ƒ4Q6FÇžý0öõðù†Ñ tIù®hÑɧ÷ï'˽^y¥?D—ŽbÿákìÃÒH¥iþÒ²½ R±ˆÚû°1DSŠ‘?äNÅå3»¦Ë¢PÏ ”¤xìÀ«C&7Ȗؽb^±Êõz[Á5oŸÅ³`Ç®Y(Çî'¯ž¤qR #@"3eÅ39oûò˜:a0¼4÷°cíR|¹øh~/9fËÁ¸DOi«”¼ 1™4Tðïìb‹¸¿àh,-˜)¯N•‰;·ï £S¢·CëŽ>ˆ¿§æðkÒê¤kÈ5GW¹1P9ÖL¦€¬-4£½×‹—c £È”ó0Q2 Æ(èç­Œ4±…éÚøÍª©‘” ef&²2Ópaï^Á¢öw·ÚZ¤:Ô9¨xK¼úò@tnV  d-P5f™Ì®‰,φ´bHÇ•´ ×â†/±hýyº.IÛdÁFêHÔ)áÙ8]»t‡â<ŽœË@õç‹EÑhÚ¥&¾9 ”7=—¦•¢~éáÙ !TWn"ß,®ˆ.¦4*o+#ÖšîK}׫[Ì‚wqq1üL©ôòÊYo/wAzòlŠˆø­ŠV?q ˆÉóoתøkP¸5B}ïFh OÂÕtg„4!_:£IÆoâ¡¶À éŒâÂ%¤Sº.- _~¿Ó‚`â½±d±\Pæ}4¦³¸òxîÔšöiNâJMóªx„m¹H[;¤ŸÛX!¯ì]½H梑¬,£]ÖsZؽ--YJÄ—{\¼ yBÆI ,ˆ0MâÙÉÉÂØMIKFJr ŠXž‰³¿Ä4B¿—'àÝ¥ç@Ëð¤ fËÁöY‰'›Èò`€­âü.ä£~)a¶­øвûaÄ´çA+(xw£ucWÚŒ#˜6Íî¶o!øÈMmHèÂAîÑŸ›°½Ý ô7 —~Ú„Y*l7r¼ÅäÃÙ¢Ør'i°#ÅMYLõ0s߉Ï»ƒ]&ZôÞ4ù_ ãìÅ™,C»º-áG½ÿ›y™ÊËP?ÀŠ?ÁÞ é`ô’)^T/µ+¶m€ñÂñÓ¦†Mò± }Þ¾t0YRÚ;ß#k|Š0wÂ$žÎ)ܵŸÍÙa®0—¡–^… ÷àãÆ!øê"ÌŸyZ¨Ï=x:ùHq¸ þ˜äBÈhö¡“R¥ÅkþžlñÆöLÂú³ í¸êNNðlT!¯D® МÜoÉù:êgñÊî!^QžËæ%ÐbFbÑåcãÕ4N_Š[5ëqm÷rú/Ží8fŒp#Ñ»¢{ß@,ýåKUûþ“Ƽ®uô8µi)Z<Íì‹Ë>kWÿÆkll,ä$äÖ]~.²ò 7Š«Ó_CY­VCLÊÈ0TÔP(éÞÞ fcÇ’,ÈËÜɃTî*´¡Éχ Y½ÅCµŒ*è¡/…ZÂç‘ùŒE. :rubºÆ‹ìô,²@dpõ(«5~=÷ž{BÈÒ-'$ú‹ºáó 4‘>)A—oØ# å*/Ñg+¤ 6µŽ¼Ô€0s§hÄö“‘ð÷ÃÃ<×*bpì²=z·“Üë¿~†uφ5£;]¼ˆK*àƒ.ñf-NÁô¹cÈ<¨iáaÌ*{œXƒˆ.?‹tW¸É¿¤…˜If¬©ïiÊ[%–¼ {G¸Ñ? %ggSŽŠ¿mIÁ³`(/%cÊü¾âòÖçÂŵ¸ )xI¿Ô^Øø­0ŸP¹mãœW\¯ÎîÅC½8ÞXˆ¦ƒÞÿ„™ v!%d ‡MiÆo]6U`ä ã¹ùRÉÕvKÊØÍ½x’¸oP&–²Kd4¡²}Ù¿T×CÍ=Ìs¶kráÈzœ8s nɸJ›ðƒÞð7¶W¯€z½Ç Ñ' ™ÞÙ‘¨‡‚[ŽÒé÷àFi•Ó‡©Âˆ‡1c=²VŽkˆ·±w%]c(QLƒ¶4”‹ï­©ñéÉk•%ïähPØOO÷k^O”éé°q¥óÝeé f1+èPHYGJj^W«b½: ·oÅ#|ë¾A-àãTèå“©S¦C)6·,ÍóêEÌ’»»Z´ú3/ɯ9Ö À•¼5hñ¼ŽG †!P¥îš†'—#ÀàÖxIEND®B`‚numpy-1.8.2/doc/source/dev/gitwash/git_links.inc0000664000175100017510000001036512370216243023000 0ustar vagrantvagrant00000000000000.. This (-*- rst -*-) format file contains commonly used link targets and name substitutions. It may be included in many files, therefore it should only contain link targets and name substitutions. Try grepping for "^\.\. _" to find plausible candidates for this list. .. NOTE: reST targets are __not_case_sensitive__, so only one target definition is needed for nipy, NIPY, Nipy, etc... .. PROJECTNAME placeholders .. _PROJECTNAME: http://neuroimaging.scipy.org .. _`PROJECTNAME github`: http://github.com/nipy .. _`PROJECTNAME mailing list`: http://projects.scipy.org/mailman/listinfo/nipy-devel .. nipy .. _nipy: http://nipy.org/nipy .. _`nipy github`: http://github.com/nipy/nipy .. _`nipy mailing list`: http://mail.scipy.org/mailman/listinfo/nipy-devel .. ipython .. _ipython: http://ipython.scipy.org .. _`ipython github`: http://github.com/ipython/ipython .. _`ipython mailing list`: http://mail.scipy.org/mailman/listinfo/IPython-dev .. dipy .. _dipy: http://nipy.org/dipy .. _`dipy github`: http://github.com/Garyfallidis/dipy .. _`dipy mailing list`: http://mail.scipy.org/mailman/listinfo/nipy-devel .. nibabel .. _nibabel: http://nipy.org/nibabel .. _`nibabel github`: http://github.com/nipy/nibabel .. _`nibabel mailing list`: http://mail.scipy.org/mailman/listinfo/nipy-devel .. marsbar .. _marsbar: http://marsbar.sourceforge.net .. _`marsbar github`: http://github.com/matthew-brett/marsbar .. _`MarsBaR mailing list`: https://lists.sourceforge.net/lists/listinfo/marsbar-users .. git stuff .. _git: http://git-scm.com/ .. _github: http://github.com .. _github help: http://help.github.com .. _msysgit: http://code.google.com/p/msysgit/downloads/list .. _git-osx-installer: http://code.google.com/p/git-osx-installer/downloads/list .. _subversion: http://subversion.tigris.org/ .. _git cheat sheet: http://github.com/guides/git-cheat-sheet .. _pro git book: http://progit.org/ .. _git svn crash course: http://git-scm.com/course/svn.html .. _learn.github: http://learn.github.com/ .. _network graph visualizer: http://github.com/blog/39-say-hello-to-the-network-graph-visualizer .. _git user manual: http://www.kernel.org/pub/software/scm/git/docs/user-manual.html .. _git tutorial: http://www.kernel.org/pub/software/scm/git/docs/gittutorial.html .. _git community book: http://book.git-scm.com/ .. _git ready: http://www.gitready.com/ .. _git casts: http://www.gitcasts.com/ .. _Fernando's git page: http://www.fperez.org/py4science/git.html .. _git magic: http://www-cs-students.stanford.edu/~blynn/gitmagic/index.html .. _git concepts: http://www.eecs.harvard.edu/~cduan/technical/git/ .. _git clone: http://www.kernel.org/pub/software/scm/git/docs/git-clone.html .. _git checkout: http://www.kernel.org/pub/software/scm/git/docs/git-checkout.html .. _git commit: http://www.kernel.org/pub/software/scm/git/docs/git-commit.html .. _git push: http://www.kernel.org/pub/software/scm/git/docs/git-push.html .. _git pull: http://www.kernel.org/pub/software/scm/git/docs/git-pull.html .. _git add: http://www.kernel.org/pub/software/scm/git/docs/git-add.html .. _git status: http://www.kernel.org/pub/software/scm/git/docs/git-status.html .. _git diff: http://www.kernel.org/pub/software/scm/git/docs/git-diff.html .. _git log: http://www.kernel.org/pub/software/scm/git/docs/git-log.html .. _git branch: http://www.kernel.org/pub/software/scm/git/docs/git-branch.html .. _git remote: http://www.kernel.org/pub/software/scm/git/docs/git-remote.html .. _git config: http://www.kernel.org/pub/software/scm/git/docs/git-config.html .. _why the -a flag?: http://www.gitready.com/beginner/2009/01/18/the-staging-area.html .. _git staging area: http://www.gitready.com/beginner/2009/01/18/the-staging-area.html .. _tangled working copy problem: http://tomayko.com/writings/the-thing-about-git .. _git management: http://kerneltrap.org/Linux/Git_Management .. _linux git workflow: http://www.mail-archive.com/dri-devel@lists.sourceforge.net/msg39091.html .. _git parable: http://tom.preston-werner.com/2009/05/19/the-git-parable.html .. _git foundation: http://matthew-brett.github.com/pydagogue/foundation.html .. other stuff .. _python: http://www.python.org .. _NumPy: http://www.numpy.org .. _`NumPy github`: http://github.com/numpy/numpy .. _`NumPy mailing list`: http://scipy.org/Mailing_Lists numpy-1.8.2/doc/source/dev/gitwash/branch_list_compare.png0000664000175100017510000002466712370216242025037 0ustar vagrantvagrant00000000000000‰PNG  IHDRºL‚©4sRGB®ÎébKGDÿÿÿ ½§“ pHYs  šœtIMEÚ0žÞ IDATxÚíÝy|uþøñ×4I“4mz= -Zh©‚ àrÉ!Šº  ¸JUP\WPpñZQù Þ TVXE[ùRŽªP,Š-Ðè‘6MÒóû#éE¹eñý|< Ítæó™¼'™yÏg>óB!„â2¤¨ªªJ„B!ÄåÆOB „B!$ÑB!„â„VB „¸Ö’cX]*SÌ&D!Äÿ^¢kÍ]Áã3WBH^xe á€5÷ Ÿ™ÎÀ‰¯s{’ €’­ ˜2÷; SßOŒï¸—»â%f®ÌC%˜ûg¼L·P –œÅ<9;À[F\/=:‹J…÷ˤÛãd«qɲ³­€>#n§{ôJ ã÷×Bi9qýRx¡¸|ÉÃ3¾"¢çýLº#Á›ÀRBæªÜÚ’Ê2×’?ºÃ—Áž#û!„?Ñí:°¹ßd’úŸ­¼0ÀØàoù™ë(S GÊDVÎ"=w ÙÖÞt08€zt­fÃŽ½T8Bù©Ú÷èÄ®ÌmµeT8ôÍlžÚämÕ±—Ùè7ée†&˜d+ qÉ0Ó©G i+óY0e_†ÇsÅUò7’¢ÌµsÙ]¾K9NWí´êüMd: ¸G #¾enz6™{-ŒJ2ŸvÙ7!„ø5ÎyÔ…ˆN·roßl›>âëÍGj§«”°6c/¨$·iCûö-A)bíuó¨Zw¸ Ŷ‹­Û·RL,]Ú…7(ß®¡Íˆ‹‹#..Ž6ñm0d q©‰:•éFÓ-!{ñ>2Ó—0{ú“¼V¯µöTö¬õöË¿òŠxâÛ·`í·Ûj;@Žì„B\¨snѵ: $޼¶3ÈHÛ\;Ý“¿•Ìr”"æ>ý·ÚéÙ«ÀÚóvÀÛ/¬U" J‹RÓQ#†Ú¸êÈî÷2þ–hÙ*B\²l]ñÙ´ãÞIÏ ßñì?ûÍ,ƒ0Ÿb)Õs€µÊAÌ9SȬÝQl ·²'‰gîp+û!„5ÑUU; qŒÛ)fÕ%´ëh?ä~ÄûÖý{[‹ÖñÓ±[ P«ÑGÓ.r‹ ´} !„¿ß1\F]B!„—%éº „B!$ÑB!„B]!„B!$ÑB!„B]!ÄåÊm¥¸ €ceös_Är˜Ý‡Ê~³U°ì%· J¶…B\´!ÄïeÀ€¤§§7þ£³€/çI¡Ö.;Ñ×ÞÊàg-Óy|ßïkGbËßdK÷n Ãч„¨Ö²Á„B]!„øõoZMat/œˆjÝÍÿIçPÒZêêæ)ß¿‘¯×n§Â¥ÙC®Á¤Ñã:œÅ²Ei«ÔÒ®ç­ôJl‚Û²Ÿ´ÿ®å°ÍEh«kÜ¿&O¿úš…•  ¢ý ƒè‘‚½`;_®ÚD….ÿ*7ÆDl!„¸ H×…óávSisb¯öH,„øM¹(.¨¢Ub4Š)’hl¶úóXùqõÂo¸“Sî Iá~ʯBÑhÀi§MŸ ëÓ’=ë·`¡Œÿ[¼:bì}wvx#_ÿX€ýP;Ž·`DÊŒ¸® »2¶c÷°bÅ& W fÄÀÎÙBq¹Ýstxû>ù²ˆr0E°ì±x~› ¥n ¬Ø€ &fšúK¬ÅŸê¢Â¢ ÑøZRU&­«Ó Ô´®šè~Ç`;Âæ )R!PÝ´Q]éîv3Ò9QÒš| ÞUž½¡åP© C×î æ(G¶ÿHá¡Ã`l‹çøaJÕ6ÜÓ9нÝf¾qÉ&BˆË´èžS.ZÆ[5I. ü–-º¶ž˜·“±©;ùô€Cb-þœ1±Fì6§÷µ«ˆ<—ŽÐ€z]ÜŤñßï<„ÛIl˜·Ûû¥Ô|gˆ7 ÃYUŠ[5âª*åøñRÜÁm¹*.˜â­«ùzõU¸‰lÓ nl6 hõµé´Gz-!„$º.*6_’•ÔŠ¥OþV­¹€QG_ÙAzi`^þF8òý6¬*Ø‹ °H`ý+ÎJŽcfÐðÁ\Ó¡å¥N´šSg¥Ú°(ŒØˆìЃ^½zÐÜžÏ/'lØJOÔaƒ{]K$%¸` Ž÷^ö—X9œoC'_E!„¸,œuw®V[X¸ô‡ÑÑùÊPò³óÕáj4‘r[;nЗðîŠÃl*òÄøÛÛqC”‡o–ïáÊ?n‰Á¤TñÅûØaƒà¨(¿±Ù)jô°qÍnVuѦ} ÚVñæÆR ªš7eÂíñt ©ÉϬùzon© \àúuiÅ}74äT±ø‹}äTCpx¿±[)ï|‘hšÜŠ:™qáõ¯N`WáºþIÜ£k°6®Ç™ÿívú^ÚËùrƒ–½"0œ±~ß6 ‹ÿ»Å¹6Ê…àÝÚErOß"«¼eç©€™™»àhsFwÑñág9R ×ßԞ͵޸¤ïfU± }XSÜœ²]ûyok%ú 37'jXôõ!²tÍY9¡5&åÖMˆKHôuCiwàS>þ`ßExý<ÖF›À V¼ÿ>¨FBÍ {Öo檞'ïÈ´hü¢x] –/~Ÿïˆdè=јòÛP‘±œ÷w€1(\{ØT~-;d“öÙû¬«ùžk¤YWñÛóx<œ8q‚òòr Æ !,, ?¿so§UTUUÏ8‡íþ¿Ýäžkø3뉫)Xü¯ñN™öÈõô WqýßÏ÷Ä®Oæ¾§ju±`Ö&æ[O·ÂÁ,˜–L46Þ™µÏO5_«VÝÉg³6ûÊ å“©í Ù·—A‹yçiÃê±±|¿1k*xêÁë¹)¼aX¹o7CŸ8©‚0–MmÉÇg¬?Cuÿ|5›õ§l¾j¼ÛáþS•ýD8ÿðÅ|ôÈ.<¯oÅÔŒ¥µåà×›ylkuÃø˜š±ô±è³¯›|_ÄàŒÃ‹àÆRVb0dð;åß«,vt&: 8ntºÓ'¥»•J·“ÉP×5ÁnÅæÒc Ô‚Ó‰ÓO‡N.«›&ð4õ !įwüøq<&“I‚qžTU¥ªª ???š6mzÎË}®¥6)Rt&žÞ–q­ê·ŸyjT[îké¦RMÖ'=n¨i­UY·ËÀÝ%¾dUË_:Ÿþâ¿¿]îŸˇ)íêûL¨Š…Ÿ‹¡pëþÚD®[ç8>”̸6¾ëœóYvXÃuW›|õUpЦRWY—±p 8p¨ª6ñìÞ¸©306އGÓÜ·Jýû¶åÃ[QyÖúÝTæÖ&¹=ohË’‰x¤¹7äJu¥ÍâxDóÚ²{öŒçÃÚR/æ§Š‹Š:üµ ð -‚’Dù9¬›—& æ3$›ÌÞ$8c’ àg0a®—äÖL3jk ¨-Kk2K’+„¸¨, F£QqEÁh4b±XÎk¹óê‰Ö¿[njMí,~7r†Þ–ÄMmŒ¸ü+˜ÿQA]‚IOޱØðs ®ëMlÙY (A×`7ß|±¥…`Ðy[jN8M¼ø@Ûº7Є×îˆ!xø¶2Vü§PÉ«pà¿·¢v¾N-ôœ8î¦UK#üâmáÌØeaøUa°ÞŠª¸ØqÄJì‘ú7{Y9x¢’ÝyÞË’›aÊÏçÏ 1š¼G>›ÕÍ-¹Š¡ñfš(pˆnB\¸†5kÎ^ÿˆbygd(¿äY15ƒœ]Åì8^w#›Î_OB›š(G9 ´iF\„œçÿ:¸#w<¬Y|ð¬ë6*:T¾5B!ÄïÈív£( g»˜.NŸìºÝç×Xw^‰n‹&¾þ«AÄ*°hê»Êî>y$3·\éÏúÕ¨Åedò}©·Å´—p Š‹ü}6rë%uŠêá„§nã«z-:_ÿÕ£ý¨.JmuõÍ]±»ÑºW¹Ð†‡1€|ÒììBN÷€)ˆÑ±åTó}v1}õ÷í`Æå8Á>k5Ô»äŸWåO]]§PΩ~?†ïÖìgQ±(8uP•}²sé+häÆ+k <§uB!„¸ÜW¢[›ˆ)õ’3N?ÔVÇnÍ`çÀÊ+ÿâKõŒ N üÿxfÄÕh.“^2‰.Š‘×šøb}]_€Q]›5ÐÕõZ/§ÉíÚw‹¢ù¦ýUTæ.ÞÊÜúÕªZ"½íÄ!±MHàXí¨ɱ&ô££Bíb½®<{Uû…Ôÿ‹·™UUÊ5k3Í+«9Zïý¸ÜNøºg|¾lŸÅÊ”¦Dw‹ þ¯ÆÝNŽ‹ _!ç!þ(χÊwB\îž-•~¨çk̘1(Jãýã /¼ÀÔ©SQ…ûï¿­VKŸ>}NQ‚‹5Ï¥ðZF„uå;Z“þÁ§¬y÷ ,ÿfæVº˜ž×-ÆúSNó¡ÕhO9_B‡ˆÚQ5ˆ~ñgÆm@ÍP¶&ïè'¯jÖB¢˜{kzœ´°ÓÇuẚ.«Æ„×üÑHÇ `¤K ¿Úi½ZŸ¥M_õ«¡ö½Cýí{Æ3 fk5Š?éD°êbÁ÷¥`432¡.&ŠÕ…Scæé[‘P¯Xsx(wÔŒv¡óÆEç»C\Eƒ¶~׆sB!~?¾ÝÓýS…O?ý´Á?€W_}•ââbt:o‚4þ|V¯^ݸŒãy#£¸•Å+æ0~ü$}>0àÇ%›qê5ÏNç±a½éÝ»7½ûŒa^F.ªªb;ÎÄqñü+Ï1¦wo†yž•+yîîaôv7³VîBUUö­œÍƒã&3ã•ÉôîÝ›[|…-…6TUåxv:“ÇôñNó 7@U+I›ñNy…ÙSne\êTÛ>?®vÞMÛuƸÔÿÇy¶èž}Ý_«º”§^ÙE–Í“âùøŽˆß¼ŠòVJªÝ ÑnüÝ›æÏ\¿‡ã'ª°yü ð4+ç²;±« Õh0øû’p·“Â2½–@Ýÿdl„¨¯fÝ›¿•`q™“ÝÆöîÙCdTÔiÿþ׿þ•O?ý»ÝÞ`€ÉdbÊ”)ÄÄÄ`09r$ .l0 5g!CþäRY0þJª*¬¸T@Õ`2¡-[Í'SN"ã§ÝÊÑfðß<¸ë­ŒÒ,cÈÂғ”»<¤þ'€~£GSöÍ"¶”$3÷Û¹¸åáÔ½(¡ÛÏFê’ Àp>]3i}ï'7¤ÏMëÅw/N#­4–¹isÉzt©{%”¡OÏ$þ›û™µ5˜»žyœÍ©¼“vˆ»ßZNÊÁgaaAmÛµ;ç˜_Ä® n2–oçùŸmµ÷Q¼¾éE©)¸‰‰à?ðƒ{æúýhÚäìM¨ZƒŽFsitD6ÑýOÇF!„î£>Â`ð^W¾óÎ;Y°`v»UUÑét' ·å»Bì¯CuU{“\ÅMU•…?m¡ •1sÞæþ®Á8;²á¶©dî(fl7o#Û„^ã¾ä}üôŸL¶&Oà_OŒe¯ù'ÆÌ¿Ñ×µ"–7?™ëCÜ´±ÝÄ3+wQ¢™ÈS¯}/•ì6ªžß<ž±ë‚qí"ˆ“ϬB!Ä9/vr’{ï½÷2þüeÔoÑ­Àð×ÀËÏ0gÃǼ´Á;õ†”×™:(#Œwÿ±“‡_]Ê?&ü€Îw¿Â¤žQ¸¶y“Lo›°†& (zï t#'ÿºyá lPb˜<ï)®h_ÆÈèwXœ6!i‚Z¶™}yÞ–h%@5œqo=OÉߟeZÊ]„ÜøwÔ­ËzÖø¨—ÜÍhBá#7£ ñç!7£5¶{÷n"##Oû÷ûî»Å‹c³Ùj9r$‹/`äÈ‘ 毙·qv§Åã²á¨va jFH ·Ó†Õê}Ì—NqQU­‚.ˆf!ùä“cíž²<Õ‰â§% @â©¢¼ÜƒÇS7_µªA«óCãW¥ÜŽ»æoÕ•”Ö>•¶KÝ ÖrV¨r¡*ǨBƒG—ÕB¹ê¡¦­V‡»ª‚rOýU«.ÅZ.ü´:üüy~:kmñ ¹åzŠ7.gÎô<òú«tÒ èʈQ*ú\3U=Âì¹³™øæ\Ì2†BqIùðà ¸¤×Qߤ­4Z\•¸<—~L]¢ë.fÕ¿?`yVž7Ëï1š±czäg}Áû©i£œÐ‡ñ„õsIW@ÉœÍ{Q“y¨_Ý­jŽ«xésxjÒ LJÝëÉOÞȶo²E‰F—û?Ù‰í6œ‡Rú¸KvðïÙ©dÙIèÑì -|eX·˜9gP¦€!¢)<@;kϾ–‰¢À³o4åÙGÁÁïxoÎrË <¡7÷<8‚³°°náû,ÊÌ%$¦qÕeÚ7ƒ#o Óf¬ôži©ø«¾Çñ:ŠØU¦2`òã Ó ö‹gïƒ3Ùþ‹…êµÉºóYøòG8â[Rø}&ù„3äîÛÐn]ÆòmÅèc{ðäÄ1„W²w?ÜÐ;‰«çðñ¡pZ–n"3· }Bž|t$1j>©/¾O샓écG>ó^Z@ÂØ‘ì{o 0ëoòä¿%A[À—óßã«mE¨!1Ü>z7ulîRÖ-JeQ¦÷ÁÉÉ7cÜ-%ØUyY|4ïc~*²ƒ>œ>w>ÈÈî1l]Á»­¤˜Xz\KѱîšpQ+™‹ßeaÆ>ÚLáþÛºa’æß„ÛZF±Å†14œCókÁ^òÝQ$FCAeìέ¤Mb4õGr¶Î¥ÂÜŠæ³ïl-ØËQ¢/ÒÕ!„øßs.]¬Vë¥ÿ>\NªÿÀž_5¼Xî’Y–UÎð‰“™<á/Û°ˆ%YÅ`Ïáíyé´þÓ§Ž£un3fKèW«ª¨=è“Üp( —½œ¢ÜrÜJÃ×.œîÛKvfΞc™<áfг–ð\êVTÏfMy‡MŽ$R&¤‘—Anm‹2hqÛx¦NÈuúm¼ýö׸ÓÜ7ˆ¡Ÿ+0”fñôŒk;ŒI“ÆÑ"?ƒ×¦-¢7Ys¦ññ†|úÜ3Ž[ÚW²­ô§x‚±>n(sçÎåÍIP•º§™¨ú`ÚêÒæ/bknßÌ[H™C×Ö  Õ^ÉÞü<²ÖüHÇ»Ç1$¾š•©sY^‘Ìøqà ÎÛÀÌ/sp[óÙ¾±à²%?+܈þLH¹ãÞ Þ^šƒêªdoQ1…•n߇±’ÜÂ<òl&®ÜU5pÃÐD,,}v:+sšrÏß'qWr5ËÞÊê%[>cÑ c&MeRJ²¿šËüm–“¿Š|ùÒ<~Ò÷bÒÔ©¤ôoÆšo±Ã UV0}îJô×ÞÄ»®$sm&¹?o瘶/~žk3lÂd&È®´Tžÿ4Gö~¿{ÁVR?þŒU߮⳱½¸áå‡ã»Ö²~O鹿<Æwë÷4šl9œÃÒs;…/Ý»Œ…²a„Büa~U‹n“«ï枎ñôH Æa#ìØSÉ5sè05¿’û^žÌõÅZ‚£Ã¹2t–«®%ñäV_‘Æ×ZûP jòí×èÈäQùç'Ù÷4±W5ðȳãé`‚®Éaì}øUï‚Á‰Œý0]{vÄPm¡mëÖl´â2EÑãšýàÏ bØ¿ôltã™”A„±“ïbÛôEì,èCÎ6;Wßÿ#»…Q?ÈÇéãá:éµB8íÚ«dnËdîLï£ô0tÃdlØ|©øÞºÿ'C;‡ánvÙyìÑ‘$éÁØcï¹­®v£)ÕÔ˜aüsL?4€ÿžÿã=g]YÚ“ÊÖ@b.„.ÚF—>Ñç­ ­ FLO÷Ôö°ï»i¬ûþÚøE¢ÕÓºÛH^ mOY`ãÎÕ÷ÜEǤkIÖRbƒ•‡8´)†3eTw4ÀLC9O¼³G._¬)¥Ûø êÄ1uX/|³ëIÒªû«¸øqÕ´è9’›ÍXs¿âã›h—Ò£vüj>v­æ“£.*ªŒtè?”k[‡€»Œ¬¯¿æ§‚J ¡mè;ôF¢5þp”UËRxÌFh»ž 땈FcÀ_£â*ØÌ²Ìô®ãV@»ž·Ò+± ö‚í|¹jº@ü«Ü¥ŒBÔÐh4x<üüü$Àãñ ÑœßqåW%ºZllœ3™…öº %¤S,·ôH`Á’Ùl[„$0ìÎÑtP\Þd°Úuö²k.ÿû„†7©ý=¬e°C¶Î t!ÚT“ÔEÑÉV@ã§¥dûç<¾èݺBCüѨ`w¶šGãéQÈbÚ¸¬õs@…NAui#¢Cþ!ûÆ +IDATá<®(8¬ u›Bï”éŒê…£ ‹§ÏãÓŒLêÓ`ÞjU!Ðèí`÷=³Oqª WÐê ú;c›Vµ}ŒOžG©×ûØ_©)Ï;ƒÓŠo,yño,©Wn¸ÓEÜM÷ÐmóL̘Æ "¹#ïNnôþl–}¤NYDM¶¢F £Šœme®jQ»~FïIêvaA!R[÷± OL‚eû)ñ€Ir¢ ç>Æ1§‘+b¼]bL­Ð¸P Ô¢H§7Ѥd3KW¯"ú¾QT~ûÛ4×rwJ[ò×.âëe›¹ox8.Õ†¡í`Fu¯dùòïÙ×µ–ã”5qáò¯¢´´NƒïäÚÊ,_¿…N W’¶b†.ƒ]É7Ë×c—-#„µ‚ƒƒ©ªªÂd2I0.@UUÁÁÁ'ÑÕ5šÓÊWo/boÒpž}=Qføò©Çù®â‚PJÕ6ÜÓ9нÝf¾qɦBˆÚÆðp ),”n]"44”ððð‹èªeìû9]@]Behâ}†qËÑD™MlYÊWeâtâ<º–3×2zêëôJ茮8‹ôìjиÁ®b³–`Uix©Ú ™¬Ë¹•›[á½y[ ô&ob¦ûÚ/ȺñIº™Ž²ôã­(É£i©Ö²"=‡Gµå—Õ_‘ ´\NhJTó0(ÞÁâw¡„FàP@ïU±RRå&"®-¬ù­ûÐ/ÁÄÖÅ&½5‰«B!cá z=3’°’ïøxƒCßó®ÆJié9ÜwS[¬3Y[†EŸÓòÕÊù_ËW 4Sàоƒ8:´á‡Ï¡L©—«eÌ+!)¶=ÊÒ3³éx{g¬¹«˜9w9Ý&\I×Í/òöŽ>¼øúH’ºöä@ú2òOα­TÕ@lëæ˜uÖÍÿ7¥¨Ø«¡MûÔ%ÿa]ß©\|”ÔY(Dà hÁ5¡¶ ^So'ʑÒÏòášÁÒmá×2D«Óáð] qÏÇFp£Ñ5êŸLùùk1™œv©h]Jš0Úwm?*c ·+.Ü*hN’N«óîq:\6 hõµ-ù ûó!ÄŸ˜ŸŸÍ›7§yóæŒßÉ9%ºfTV¾?›•õ¦…ô™È½ýÚ³vålÆ­ôñtKaÓ†TöÜþOnŽßÈ¢g‘oþ«†O& 3‰½bIK[ÀÓþa Z’ú20&ƒ•³Ÿd%zòZä“:íQRHf⽽Иaò¨f|2›‡–ƒªPУ!¶ë„|³ˆé ¡slËà•Åy¾{S2xái³ßÃ_÷¾È‚™Sj/áyl z3­ŸHaÿÔyL4×EB„ÿYMµîB±>n0‡ìgöòÙl[î‹[çáŒêvÒBZ̨赚å}[§þýíª±ñ´¯51Ü1¼3–¼Ã£i@H`G¯Õ ‰3ª,{í9ZÌzƒÇ& dÊ;s½ó=R¸·ƒW³"²æ1íaßû&–”±­Ôçw }#WðÉôGùIèD¬~ó¦/aÖóׂÙ,˜ñ$‹€#`oN¨Á̰'Æ‘3uÓ}•ª‘=˜6¦³|-UC ÎÆ÷›óHêÕ’¢ÃÅÚ¦Áðy÷ƒXh‰¹ürªt nFµV¡¸E'z$š±XË6Ñ¥}8Jµó¼VÁß îMì/ëA»+‡ómèd_.„âô«ì°”bui3£ÁÕjÇ`2¡,%EX &sÌõ:`:´zý)ưuSQRŽª®7¿•¥O=Φk&ñ¯aÍ9Qæ¦I˜¹Á²nk '¬Öp,·•’ãô!a˜ôà¶ZqLè5àq8piµøû:5;,¥”¹TƒÃöu[)=aEŽù°u[+8aµÖDxØïÓ/Ça±`EC˜ÙÔ(Æèõ¾7騢¸ÜŽÁÜ`ƒâ‚Ü=a'ǵ^Y–’㸴!„™õà®ÆêÒ`ÏÛȦ£aÜØ+ =P²uSæ„ðúÜ‘¾–[¥Åå8M𙑮¹¿ wÙn>ýt=• ¨„pÓ=#hY¯ƒnÁÆ%¬ØQ7êBd§›¹¥k ìÅ;X²l#6Å{îÛeèh:‡eÑ’ÃÜzwOLØÉœ¿÷¥Õ¾/Ø7ŒîšX¶'ŽQZƒó çOÏ{FÁOŸ‘¶£¬¶ŽÀöƒÝ£î FÍ#€ÓÓÓeƒ !„¸ôÝ‹ÏÊâq±¦Ç#¼?¦ƒl±ÿ–œ<9û;¯Èõ‡Yž–Mü°I<9(A‚sѳ];evŒA!èOsá´[©ÆˆÉP¯c´Û‰ÅZÑdB÷+Ï<\V 6M A†Æ¯%ÑB!‰nÃ#7ù[3)íD·8³l±ÿŹYdnÜÉáR' =naPg¹†-$ÑB!‰®B]!„B]!„B!NEF/B!„’è !„B!‰®B!„’è !„BñÛ:ë“Ñöïß/Q—Ö­[ÿ!õÊ÷I!„øýŽá2ê‚B!„¸,I×!„B!‰®B!„’è !„B!‰®B!„’è !„B!‰®B!„DW!„BIt…B!„¸”ý h«E$IEND®B`‚numpy-1.8.2/doc/source/dev/gitwash/index.rst0000664000175100017510000000030712370216242022155 0ustar vagrantvagrant00000000000000.. _using-git: Working with *NumPy* source code ====================================== Contents: .. toctree:: :maxdepth: 2 git_intro following_latest git_development git_resources numpy-1.8.2/doc/source/dev/gitwash/development_workflow.rst0000664000175100017510000003717212370216243025335 0ustar vagrantvagrant00000000000000.. _development-workflow: ==================== Development workflow ==================== You already have your own forked copy of the NumPy_ repository, by following :ref:`forking`, :ref:`set-up-fork`, you have configured git_ by following :ref:`configure-git`, and have linked the upstream repository as explained in :ref:`linking-to-upstream`. What is described below is a recommended workflow with Git. Basic workflow ############## In short: 1. Update your ``master`` branch if it's not up to date. Then start a new *feature branch* for each set of edits that you do. See :ref:`below `. Avoid putting new commits in your ``master`` branch. 2. Hack away! See :ref:`below ` 3. Avoid merging other branches into your feature branch while you are working. You can optionally rebase if really needed, see :ref:`below `. 4. When finished: - *Contributors*: push your feature branch to your own Github repo, and :ref:`ask for code review or make a pull request `. - *Core developers* (if you want to push changes without further review):: # First, either (i) rebase on upstream -- if you have only few commits git fetch upstream git rebase upstream/master # or, (ii) merge to upstream -- if you have many related commits git fetch upstream git merge --no-ff upstream/master # Recheck that what is there is sensible git log --oneline --graph git log -p upstream/master.. # Finally, push branch to upstream master git push upstream my-new-feature:master See :ref:`below `. .. note:: It's usually a good idea to use the ``-n`` flag to ``git push`` to check first that you're about to push the changes you want to the place you want. This way of working helps to keep work well organized and the history as clear as possible. .. note:: Do not use ``git pull`` --- this avoids common mistakes if you are new to Git. Instead, always do ``git fetch`` followed by ``git rebase``, ``git merge --ff-only`` or ``git merge --no-ff``, depending on what you intend. .. seealso:: See discussions on `linux git workflow`_, and `ipython git workflow `__. .. _making-a-new-feature-branch: Making a new feature branch =========================== To update your master branch, use:: git fetch upstream git merge upstream/master --ff-only To create a new branch and check it out, use:: git checkout -b my-new-feature upstream/master Generally, you will want to keep this branch also on your public github_ fork of NumPy_. To do this, you `git push`_ this new branch up to your github_ repo. Generally (if you followed the instructions in these pages, and by default), git will have a link to your github_ repo, called ``origin``. You push up to your own repo on github_ with:: git push origin my-new-feature In git >= 1.7 you can ensure that the link is correctly set by using the ``--set-upstream`` option:: git push --set-upstream origin my-new-feature From now on git_ will know that ``my-new-feature`` is related to the ``my-new-feature`` branch in your own github_ repo. .. _editing-workflow: The editing workflow ==================== Overview -------- :: # hack hack git add my_new_file git commit -am 'ENH: some message' # push the branch to your own Github repo git push In more detail -------------- #. Make some changes #. See which files have changed with ``git status`` (see `git status`_). You'll see a listing like this one:: # On branch my-new-feature # Changed but not updated: # (use "git add ..." to update what will be committed) # (use "git checkout -- ..." to discard changes in working directory) # # modified: README # # Untracked files: # (use "git add ..." to include in what will be committed) # # INSTALL no changes added to commit (use "git add" and/or "git commit -a") #. Check what the actual changes are with ``git diff`` (`git diff`_). #. Add any new files to version control ``git add new_file_name`` (see `git add`_). #. To commit all modified files into the local copy of your repo,, do ``git commit -am 'A commit message'``. Note the ``-am`` options to ``commit``. The ``m`` flag just signals that you're going to type a message on the command line. If you leave it out, an editor will open in which you can compose your commit message. For non-trivial commits this is often the better choice. The ``a`` flag - you can just take on faith - or see `why the -a flag?`_ - and the helpful use-case description in the `tangled working copy problem`_. The section on :ref:`commit messages ` below might also be useful. #. To push the changes up to your forked repo on github_, do a ``git push`` (see `git push`). .. _writing-the-commit-message: Writing the commit message -------------------------- Commit messages should be clear and follow a few basic rules. Example:: ENH: add functionality X to numpy.. The first line of the commit message starts with a capitalized acronym (options listed below) indicating what type of commit this is. Then a blank line, then more text if needed. Lines shouldn't be longer than 80 characters. If the commit is related to a ticket, indicate that with "See #3456", "See ticket 3456", "Closes #3456" or similar. Describing the motivation for a change, the nature of a bug for bug fixes or some details on what an enhancement does are also good to include in a commit message. Messages should be understandable without looking at the code changes. A commit message like ``MAINT: fixed another one`` is an example of what not to do; the reader has to go look for context elsewhere. Standard acronyms to start the commit message with are:: API: an (incompatible) API change BLD: change related to building numpy BUG: bug fix DEP: deprecate something, or remove a deprecated object DEV: development tool or utility DOC: documentation ENH: enhancement MAINT: maintenance commit (refactoring, typos, etc.) REV: revert an earlier commit STY: style fix (whitespace, PEP8) TST: addition or modification of tests REL: related to releasing numpy .. _rebasing-on-master: Rebasing on master ================== This updates your feature branch with changes from the upstream `NumPy github`_ repo. If you do not absolutely need to do this, try to avoid doing it, except perhaps when you are finished. First, it can be useful to update your master branch:: # go to the master branch git checkout master # pull changes from github git fetch upstream # update the master branch git rebase upstream/master # push it to your Github repo git push Then, the feature branch:: # go to the feature branch git checkout my-new-feature # make a backup in case you mess up git branch tmp my-new-feature # rebase on master git rebase master If you have made changes to files that have changed also upstream, this may generate merge conflicts that you need to resolve. Finally, remove the backup branch once the rebase succeeded:: git branch -D tmp .. _recovering-from-mess-up: Recovering from mess-ups ------------------------ Sometimes, you mess up merges or rebases. Luckily, in Git it is relatively straightforward to recover from such mistakes. If you mess up during a rebase:: git rebase --abort If you notice you messed up after the rebase:: # reset branch back to the saved point git reset --hard tmp If you forgot to make a backup branch:: # look at the reflog of the branch git reflog show my-feature-branch 8630830 my-feature-branch@{0}: commit: BUG: io: close file handles immediately 278dd2a my-feature-branch@{1}: rebase finished: refs/heads/my-feature-branch onto 11ee694744f2552d 26aa21a my-feature-branch@{2}: commit: BUG: lib: make seek_gzip_factory not leak gzip obj ... # reset the branch to where it was before the botched rebase git reset --hard my-feature-branch@{2} If you didn't actually mess up but there are merge conflicts, you need to resolve those. This can be one of the trickier things to get right. For a good description of how to do this, see http://git-scm.com/book/en/Git-Branching-Basic-Branching-and-Merging#Basic-Merge-Conflicts .. _asking-for-merging: Asking for your changes to be merged with the main repo ======================================================= When you feel your work is finished, you can ask for code review, or directly file a pull request. Asking for code review ---------------------- #. Go to your repo URL - e.g. ``http://github.com/your-user-name/numpy``. #. Click on the *Branch list* button: .. image:: branch_list.png #. Click on the *Compare* button for your feature branch - here ``my-new-feature``: .. image:: branch_list_compare.png #. If asked, select the *base* and *comparison* branch names you want to compare. Usually these will be ``master`` and ``my-new-feature`` (where that is your feature branch name). #. At this point you should get a nice summary of the changes. Copy the URL for this, and post it to the `NumPy mailing list`_, asking for review. The URL will look something like: ``http://github.com/your-user-name/numpy/compare/master...my-new-feature``. There's an example at http://github.com/matthew-brett/nipy/compare/master...find-install-data See: http://github.com/blog/612-introducing-github-compare-view for more detail. The generated comparison, is between your feature branch ``my-new-feature``, and the place in ``master`` from which you branched ``my-new-feature``. In other words, you can keep updating ``master`` without interfering with the output from the comparison. More detail? Note the three dots in the URL above (``master...my-new-feature``) and see :ref:`dot2-dot3`. Filing a pull request --------------------- When you are ready to ask for the merge of your code: #. Go to the URL of your forked repo, say ``http://github.com/your-user-name/numpy.git``. #. Click on the 'Pull request' button: .. image:: pull_button.png Enter a message; we suggest you select only ``NumPy`` as the recipient. The message will go to the NumPy core developers. Please feel free to add others from the list as you like. .. _pushing-to-main: Pushing changes to the main repo ================================ When you have a set of "ready" changes in a feature branch ready for Numpy's ``master`` or ``maintenance/1.5.x`` branches, you can push them to ``upstream`` as follows: 1. First, merge or rebase on the target branch. a) Only a few commits: prefer rebasing:: git fetch upstream git rebase upstream/master See :ref:`above `. b) Many related commits: consider creating a merge commit:: git fetch upstream git merge --no-ff upstream/master 2. Check that what you are going to push looks sensible:: git log -p upstream/master.. git log --oneline --graph 3. Push to upstream:: git push upstream my-feature-branch:master .. note:: Avoid using ``git pull`` here. Additional things you might want to do ###################################### .. _rewriting-commit-history: Rewriting commit history ======================== .. note:: Do this only for your own feature branches. There's an embarassing typo in a commit you made? Or perhaps the you made several false starts you would like the posterity not to see. This can be done via *interactive rebasing*. Suppose that the commit history looks like this:: git log --oneline eadc391 Fix some remaining bugs a815645 Modify it so that it works 2dec1ac Fix a few bugs + disable 13d7934 First implementation 6ad92e5 * masked is now an instance of a new object, MaskedConstant 29001ed Add pre-nep for a copule of structured_array_extensions. ... and ``6ad92e5`` is the last commit in the ``master`` branch. Suppose we want to make the following changes: * Rewrite the commit message for ``13d7934`` to something more sensible. * Combine the commits ``2dec1ac``, ``a815645``, ``eadc391`` into a single one. We do as follows:: # make a backup of the current state git branch tmp HEAD # interactive rebase git rebase -i 6ad92e5 This will open an editor with the following text in it:: pick 13d7934 First implementation pick 2dec1ac Fix a few bugs + disable pick a815645 Modify it so that it works pick eadc391 Fix some remaining bugs # Rebase 6ad92e5..eadc391 onto 6ad92e5 # # Commands: # p, pick = use commit # r, reword = use commit, but edit the commit message # e, edit = use commit, but stop for amending # s, squash = use commit, but meld into previous commit # f, fixup = like "squash", but discard this commit's log message # # If you remove a line here THAT COMMIT WILL BE LOST. # However, if you remove everything, the rebase will be aborted. # To achieve what we want, we will make the following changes to it:: r 13d7934 First implementation pick 2dec1ac Fix a few bugs + disable f a815645 Modify it so that it works f eadc391 Fix some remaining bugs This means that (i) we want to edit the commit message for ``13d7934``, and (ii) collapse the last three commits into one. Now we save and quit the editor. Git will then immediately bring up an editor for editing the commit message. After revising it, we get the output:: [detached HEAD 721fc64] FOO: First implementation 2 files changed, 199 insertions(+), 66 deletions(-) [detached HEAD 0f22701] Fix a few bugs + disable 1 files changed, 79 insertions(+), 61 deletions(-) Successfully rebased and updated refs/heads/my-feature-branch. and the history looks now like this:: 0f22701 Fix a few bugs + disable 721fc64 ENH: Sophisticated feature 6ad92e5 * masked is now an instance of a new object, MaskedConstant If it went wrong, recovery is again possible as explained :ref:`above `. Deleting a branch on github_ ============================ :: git checkout master # delete branch locally git branch -D my-unwanted-branch # delete branch on github git push origin :my-unwanted-branch (Note the colon ``:`` before ``test-branch``. See also: http://github.com/guides/remove-a-remote-branch Several people sharing a single repository ========================================== If you want to work on some stuff with other people, where you are all committing into the same repository, or even the same branch, then just share it via github_. First fork NumPy into your account, as from :ref:`forking`. Then, go to your forked repository github page, say ``http://github.com/your-user-name/numpy`` Click on the 'Admin' button, and add anyone else to the repo as a collaborator: .. image:: pull_button.png Now all those people can do:: git clone git@githhub.com:your-user-name/numpy.git Remember that links starting with ``git@`` use the ssh protocol and are read-write; links starting with ``git://`` are read-only. Your collaborators can then commit directly into that repo with the usual:: git commit -am 'ENH - much better code' git push origin master # pushes directly into your repo Exploring your repository ========================= To see a graphical representation of the repository branches and commits:: gitk --all To see a linear list of commits for this branch:: git log You can also look at the `network graph visualizer`_ for your github_ repo. .. include:: git_links.inc numpy-1.8.2/doc/source/dev/gitwash/pull_button.png0000664000175100017510000003113512370216242023374 0ustar vagrantvagrant00000000000000‰PNG  IHDR~\iÉÞu pHYs  šœ IDATxí]|TÅÖÿoß”MHH€ ¡„–P¤KTôå,€¢"ÊS, Oð‰øÀ§‚}€%"]zï„HR’@©›dûîwæÞ½ÉfIBB$a&¿Ý{ïÔ3ÿsæÌ™3s72ðÀàp8÷ òû¦§¼£ŽG€# À?ŽG€#pŸ!Àÿ}ÆpÞ]ŽG€#À?—ŽG€#pŸ!Àÿ}ÆpÞ]ŽG€#À?—ŽG€#pŸ! ¬ýµÛíHKKCVVVuèN¹ûP£F øûûC./y>çx•bpŒËÝßU’óìVäeÕáÿÍ›7Á”™——×­=¼ObØëyyy‚Ò(±×¯á)6‘c\,4÷lçYѬ)Ù4,ºÌ=› {Ž®Ê$H&“ 0,n8^·C¨ètŽqѸÜ˱œgEs§Z¸zl6ƒÙì~?†Ãâvãu;„ŠOçͽšÂyv+gª…Åk·x G€#Àà‡À}¯ø÷ìÙƒ©S§âÔ©Sª¡8 xyò$¾ûî;¶wß}­Zµ*—ø¸.6.O[ÑB$É´ÜÓ r)›ÉÄ»›BñúèÕ? Z}|?¢·ÌìÐøê©à¢qu'ò.=ËIXHéG.AŸÖ0[ŠäráÖïgcÇŽN,Y²Dx_è³Ï>ãŸkðññøÆ®£GÆ ËÏŒÌüàù¡SÿNð3^Ƕ½QXöÙ+PmÀˆæÞùY+ô†úïÊëê¡øË³\ÙK_,?~\ø°û‘#GB¡PN$,þÌÆÕì"†¸EØŸø úùAÉÇ~ǧ³¾GLVs<ÒYʘ¯ìÀÄ™›àR7ï†>øŒÙ'—,Æîo<5ú#¼3( fèa0¨`¡9—·ÍÃÌUI ¶l>‚õº`ÂŒOлaå½£páÂ0e‚Œ™3g‚ýgxôéÓŸ~ú©°Zb>é1cÆ iÓ¦E*(O§¥_€ˆË)óÞ…ä:á8·G|ÐåÙ ˜<Ì ó'þêg>Ää!AŸ>; Ýñù¬Ðoœ‡©áÉxýËéMÛ9³gáH¼¾Áí0tÌÛèaÙ‚.I FøpìÌŸ3W6bά¯Ä|Íû`ü„ñx´Àh‹üs &îÞ‡ýĶ?×ÞEëKÂ+î–½X4þ|aµÉdŽ#,0œÙÉ+‹åöVC‹ÁSðùȦ°Ù³ñÓоøþÚÄÛÿqÿ‡?ð$¾ú`¼ —0oÂt˜žœŠñ$WR spÒ-ÍÐ.÷Ëð‘µй³þv›Žøõxè3‘šk§‡Ñ;~ÂŒO– –òÖëú>ú`4Â|•H>ŽOg, ±ŒO5Eâ… ô›4}±ïLZ'æÌÅ &^ø‹xùÙz`ê¼ h‚«Xñål,ÙCãÙÉbM8Ö´³øvæ—XIÅù:Æ?ÿ–½? ‚ öã$̯?c{Õ+èÇ]º“ŒD•J___Lš4 ÿú׿hÜ„5 &Ož ö ËË^¢d Ÿåg|tUþ"¶¯â?Ÿ¿5ñyâÉŸ0pÜwXº&£¦<ŒÄÓ[ñ¯?G›W¨ßÃirToV|ô)ö{<†¯¦Á•å3ðïmÀÛßLA»Œmxsâ <ôág>ü6'Õ@Ù9l>œ€à.#0}ÚH4tÅ…x-w}¾_î™Ò_·nÀ Æ ºuë¢~ýú1búöí{‹Ò‡õÖ®#…Ò`4–|ó†ÓêÍÑÐ(è6yžÿà{Äf¶ÀðÑmñ×^g°“][lè?¼2ãwaÎgs xøqt”'`ýœoqѪ‚!!§îC¦McÊÄÆÁ–¨ZxçþÈL8‚Ϧm‚E)*©î»ueî/f…JÖÌàÁƒ¥ÿÞ{ï žžžŽÇ{LhžÝÏž=ÌWZ¥§Ë€ó±8¼y3ÿñ6ž Αðéø3ÝŸ”L¶¬‚Ù‡?wÇ öè$ZM¸°s¼Ñ¬^ ¦ŒŸ…£ú¾˜þÕ tɉÀ’)Ÿ"­NKtoï+Щw+ÚNàµ7æÒo‡ÑG@³ŸŸ‡2§Ø_Û ¿>òÛÞtÅ‚Ê@™Yƒ¯½öš``0…À”<›\™"aJ‚)Ï¬Ê &ùŠÃ57íâ®"êÈ&¢IÐ! €¯R´s±ˆ=o€‡§°Ö±ñ8Ÿ)ƒ— ´ÅÕV8Þ‘xk÷ìÂÖmâÇe…ÄÐ:žäÎü #Hé§ôxÓ§Œ‡âp8Æ¿ú²Rh,¼·@ #Þ膣kw òŸ)Ó@åÈ¤É ™r-­„e0gœG|ì)Ø<ìXõáH,ÙŒ?™Žñýåø}ÖXr.»æLÀÚÓzŒý|¦<«Ãæ%Ÿ`ãU Â:·Ù\@‹‡Ñ¾Q <5•g¿JtPPÞxCÔŒvß°aÃ|Ý!R~–§p0ÁHÖ?[áiµB[&xÑI0fÁh’íÈÌ0Œ›2OÇcÅg¯ÔÖÆàâ®H¶çàÌÖ]H }r6Ñ€äÓ[“†Íë#=æ("ŽlATà“÷D ÄYŽi\„«úÝ܇ÊC¬p¯+ô‰Ù*ÐÅUÌÒÙ úæ›oŸí‘GÁ+¯¼’ÿÌfköq¡³NlÇaj¤A¯6 “!”ÔCÔ¢õ¸1jò"÷ e‡/øïtòÅ íôñJ!ŽšÂøÿ}‰W[^BäŠ8Õr<>o$b}"1b P³ÏddpyC#WÀ.”©Ë?E'ï\÷lÇ‚\´Zزó\m4±r·og“n±…Yžâðr·2®yÙ^ˆû» /&à욟×*ºS¤–Y|!ÚœàÔi¦è„ÜÖ&¬µrEž|¦v¯9‡#' ¢eçÈÀ™ˆH\Ž|‡=‰Æ0iö;Ø‘†øÓû@F%!¨ƒ_ËAÚm62bøKý ?þ ( #¾ùãºù`H».ˆÍÒ¢¦‡ƒ þ#æãÓ‘Ýõ`6Ö¿¾”¬fO‡¤ôŸ< ͨOˆÔzÒde Ÿ³ðð/m È„<@Π¶soÿΛXy³É’ÉÅÃîKŠcéî¡Ás30oáO›IºZõèM}5§ R”-AnÉJÀiz$äÊHlY3°"òç÷1jî^ì8‡ÎýƒÆA:¨ ëG߃î¶Z¨‘µE¬_EøÆrr¸•ŠV $ñ1Wéú€,PêßT?M†!ý1v\wø¶¨'Ÿÿ¦_w :þþ\½—db5n¨þÀ»íM°Q^&SZ š,™®h×® K˜nq7’„Îû¥m±P?€´ÈÃüÚ…Á3ïPBK2}’G“6I©jwêMFç:,ú`*üLÑŠ©³§à<¥†Žì-ð‰¼r$PjZaY Ï4çlþ/,y&qò-[$e]Ôuß¾}'AB¾ÒW«Õ‚Òg§yÃL&“ ¸˜•%1/¿®ÌHüÆÌ}ÿ§0—üÞ è3wòSJ¿­;ŽFÎc ß~1{NìÄ¿?\ê‚ 8ø\"à`‡}H`œãÒ5‰%zf40>Š•-‰|ÚŠy–Jw-©<ëË–-1}úttëÖ ñññ‚‹çðáÃØ¿?ØqÃ7niÌÍ#)}÷‰Ó¡¨ƒúd:Ò—á­¿âصøhÚ¤níá)öU8ûäì‡D¯_«NâÒ—"Âzö@—vMÅ$Y/ô ­Œkgß²ßCC0¨[mÄŸev= ÚLgÁ!KÄ©£±ÐÖ®#_<*Jz¦Pp•.– ÕËŒA"Ó©á)(5§K—Òñ@Ë0±Mm´ëÐ×þŽÅ?_@­‡ºñ‹æ~‡}'v £¶áçU8´k ¾ßÍ~Z„(ò®¾t—n@–ÐPuáß/Áù›7ðí 1øfÃM |ó_˜7®£P>1Ý/…°fÀù³G›n, »˜ñ õK¨ „/)_QW©KcAÊÃt³òÙ‡ÝKñÅå—°EÔVÌûþG,]0Ã>\!dùD6±]4}.öœ>Žå_ÌF¥¶ «MX5G¯fNY {Ý;·’šÁÀG›Àa1 ¢ÉZ*,×RæÀf-ª¿ÅÏN¡°súlff–*ÛÈe0ÌÒgJŸ1Œ)»âÂ#Ûà3½Ú6€fKG³¡èûÅzìܰ W&}Ž9£cÒâp¼ÿNA-ê‚[²ŠXP¢&ɹÌ[´‚¶¤u.lNwÎËÂ}áM=Ù]ÚègTÌšg¾h†Sú§OŸ„ºgÏž`&Ûôeùؤ) |áº4xnÎwH{ó ü±n>X'¦öŸ¸¯µõ†5Ý!¸È‹Q(0¬Mз³"d ]H001ß¿þýÐ\kƒ©a/<¼á[§`0->BƒkGà8.ÆТVU‹o߯[Â1㥓˜²l&¾IUÐFÙû˾B[ßËð"^°¶.®Wž"ê.=¼øâ‹øá‡„REÅIi®W¥ÒiM“b–¬6WW/ŒŸ§.Ç×ïMDýv¡T”~¹ÖkÉg ÷Ž;DY½(4(ª«såy#îjŽ™¯¤á“Ÿ¦â¹e”‰pðÝh´n£Ã—/Ä?ÿWx,°j¼[ ÀˆÐŸ±|ë\LÜŒ°údÅ1¹¯‹qßÌ@ê„)˜2j8ËŠ}'`ìã‘£|›§ü†‰Ãv ñ¨ÿ(Æ j™Æ:/Ø}ßâÅZaØ;¾,¢TÌw¿î(¶ÌíæpDá÷ÅQBU2Z‹}°d.†µ­s^_|÷~Þø÷j¼?^4í‡IÁaÌAç'Á¯v¡Wûø>‹®T×aÇSèâ ‹Iô)¸ê Ö–4Æ$^+ƒ0ÃËÍܹ£^ý=…™´NѺs§ ""]ºt–ÓÌg:eÊa3—Y«Lé»ûNÝ˳g¥‡/tZ9llvž4À”ðñÓAAslnf6L4‰ØÔ¾¬Á–²b°äf"^ðõ¢}ºÏ±¨áSà »™Y9P{ù“].ýœ´Ã£¼Õäž {µ'Å›írxÓ)ªŽ‘帬¤V _“’’ßcáØÂO%áU8§ècîæ“\Ld˜Ò—VHîe =S9SnLé¨H'?læ<èsi¥M?_Âæ\dåš!W{`Ež_hi=lÒ3=à§ÓÀa3"+›|º$ÐVr—yøÀ›üòÌW*'¶9' ¹VòijiQ«€ð4ši#Í*‡Ž,cò„=YÈ#^ßvÑ–’Ô¯;Åøõ×_—ª*Õõ—_~;^ëd*/ÔðVÃîÄÏ==«•¦m–§¸|,¾:ñ«Z(þÒ cóë—ÄàÒÖÅóq8¥@€,‹Óo]ŠÜÈÒâUÙôW…ö8ÆUK…iä<+Œ{ª?ûí öÿfïçÿ¹Ë˜É0`XÜ.p¼n‡Pñéãâ±¹WS8ÏnåLµ8ÎÉftv\+£à¨Â­=½büüü„c­ìNIãU:%§qŒKÆç^Lå<»•+ÕBñßÚ-Ãàp8Å!P²iX\)Ïàp8U®ø«,ë8áŽG |pÅ_>Üx)ŽG€#PeàŠ¿Ê²ŽÎàpʇWüå×âp8U®ø«,ë8áŽG |pÅ_>Üx)ŽG€#PeàŠ¿Ê²ŽÎàpʇWüå×âp8U®ø«,ë8áŽG |pÅ_>Üx)ŽG€#PeàŠ¿Ê²ŽÎàpʇWüå×âp8U®ø«,ë8áŽG |pÅ_>Üx)ŽG€#PeàŠ¿Ê²ŽÎàpʇWüå×âp8U®ø«,ë8áŽG |pÅ_>Üx)ŽG€#PeàŠ¿Ê²ŽÎàpʇWüå×âp8U®ø«,ë8áŽG |pÅ_>Üx)ŽG€#PeàŠ¿Ê²ŽÎàpʇ€òòåËå+ÉKq8Ž@•D@Y£F*I8'š#Ààpʇwõ”7^Š#ÀàTY”‡£ÊÏ çp8²#À-þ²cÆKp8*WüUš}œxŽG€#Pv¸«§ì˜ñŽG J#À-þ*Í>NP{@)#mé°qç57 Bå"hC<á›jE@ O>ŒÇ§ÏÆ"ÓªC€:¿Ÿ9ñш¸˜ /1g.Áæ%§O_…¦V´Îþä0$ãt¤3ŸÔÙüDé&ÿÜ S݆ðWT`3k–A-•sprëNdÕl€íßg³˜Ó.áÀÎ8x"g¢/!Eoƒ.0žƒ¥nUØÕ†+§áZ®jûU¼ŒW™¼¢*ƒ@¹\=¦ÄSXµþX‘¬Ûe(^ت¢Èlé0áTø:íø2¾hä“ÅVquSM¦Ô(lÜxµ:}†Æ0Á^¦Ús°uÑ*œiõ žóÔ 7ã Ö,ùI&g-51xìkèä¹/’Žþ‚Õõcxß2¶S&¢Ü2[qyïZìHòAÍ©¢‘Âö#É‘›°z[Pw¦¿Ù õœïß~Æ!} _lH2pmýÂ0Øq¬;WÛ¶q6—_1\=Dù"„|Ã+`-â'Bâ÷þ‚-Çü0é9Tyy0ÛÅ "™…u ñÑÔAЕj¡Î>€Ÿ—{`Æ„‡ápmÈ­Wwë1þÐX¼õ¬X½Z˜Mˆ9½0t´ö§¸Š$ãQ«6âh§@<ÔÜFsÅÊxE“Ëë»÷(ŸÙ¤mÒ®/}„ÿ|ù%fÓgæ”7еž7ŽüÿIAÝv÷APz¾^ðÔT¼­¬êTÃKëuÑÊ8½ÇL: Ú,{+N¬Z*(ýVƒÆàãw_BnâÏ+o¡ŠAxbPSĬþÉŠò¬-Ê‹³¡B‰_zÄeÊ úhÆ• qB…Žë—ªÐŠü´$㲞¢Cz¢eÇgðæø‰Úª´ZOŠ$Œ<< rc¼GÓû†˜ÏÃŚϧÖp ¿íLBËaÏ J»=‰Wc°ïÏeXG¿îðñ†Î ô­{ÚÔØô—±ReŒÑk¸ºUTú>íñÆg_bþúÌ›‹F>-ñråOG`‘V'ù¬˜%­°|<|à¡®x¯ y-U rYü’ѦòöÝf†Éd…LYǾÓÌy8¹™–ã€ÎdAZÌ>¬\µ If‚Eínƒ‡¡ÿƒA°$Ãâ_N¡Í³/£[°liQøyÅNxvyC;Sæì[¶×>ÞÚSX÷—ݰmç1ä˜d¨Óêq¼<ô!x1Ì>d4Ùvº:ŠmS`Œ- ‡þ܈½—É6tµ›¡çÀAx¨¡¯˜œƒ5¿nÀ¹¤èêµCÏfy9ØòÚA–¬7NnÃÊ­‡Î kjã‘aÏâá&5…²…¿R°nõhÛ¼‚6^6䦜Çh3|zc´‚Õ˜‹WÞ‚©ó×á)±0;ôBý‹±öHÆwÒÁäb9®»bŸj…4§ c›ˆuɰ¿ŽÓñhjÁtó/œ¿nF¿šè“®!‰ÔmH›¦PÝèÐH‹¤s›°ä`"änfVÔÚbÛl8µâl#¥ß Ç@ {º/|3c±éG²º™wÛ|‹¾þg“,hÙç42G`Ó®˜|lÌ7öaáúC°wÇÐaƒÑ\›Œ]T߉ 7"¨„9ñ®’ìÔ=ŒÜ$Fèãã‘Nñm:6‡Ý’‡ì!ócÊ)Ìÿv5.“ëè©gûBgNÈϧV¸ã”ƒ+çõPw€… yF+àѧÍÂæÏD_š‹ÉËáëÒäã ®˜ÈEæ–z×ÍqˆL’Á§ËhåI´fë¥/¶ç@“ã1û«ÐÊ[Ix˜˜}›¶!Ú⃺uëB•¼?m"ƒA÷ †‚®ÁVDìú{lÂÊÅ”yñçcÛ¡tôxúèbÁ¹]?céa6ÕJZI˜bvb×y-z=ÞÁ=¬\Œ£Šd­ôry×ðáW)Êiñ‹ˆhƒ‰Š_êµ_½:Àñ(\JNEÞæS€OgL™ò"VtjÑÚ¹³°k†uëI¾mvŸ½ûúH¼tU¨B–…e_h¯^¬šî¡µà¸&*ÁoÍÂãM6ìèhG§N>g WÃCaBžU²|A½žè× Ø_ ‹I+,Nˆ,°šœ˜É‰~Ê•F)2…\°ju~þ]8…kÖGP›´^AÎâwåˆÍÔˆŽ9›Ê‡‘u–Úm†Ðú¡ %ÅìÌO6B\tiâÖ­-‡%IT¹2ꃊÌr¶*ÒÇÆÜïÖC¯m·§½Ž&¤ o^ fù”2f¹»ì’˜“p™»F¥‚ƒ6r%ß¾œìÝÌtzf›¥dQ ’ÅOQ‡2™“ hZÛ£K•wV©“&™v¢Õ@t™aaø ²ÞiZ­†™Vµž~ Ýj‰œOëaødt’®íNƒC×}ð,üì˜ÚׯÅââå4<R›úÄdL‹§ßÿ'úÔSÃÔ¥9äs>Ç¡­Çaî÷,¬Jm{|øÅ˨CLN]3>^| évÔM.½\Þ5|xÅU wn’s¢I,ü®—!ð‘Τô-ÐgèIõ©Ñ<4öÅ Åþš·n€ÝÛ£È Ô±1f4èÒÉGOâJ¢~ÉÒöéŽF¾\¶©ÎVèDÊØœ“A®<Éç)¬€IaæR$1tX¦¤6{y Î_À¯?îÀ•¸x$§çÒ ¤;6¤\K€CÓ=;Û!k¶e×ÖØ–pMhBT—®1X9ë]l A³&-ÐqÄ4 ÖžÃ|Yj:/;›êõõ°· ©PÓüÍ‚bdÙ±IΛLMþöÜÊQjÔbƒÍ ‹=‡«)7‘M´7„@ÂÄÖ ˆ>‹™GÚ'´5jÑ4–êîa‘¥bùwáTm |Š”¾9™Ù 9î¶¡!mÊ»@ äwÜ+ð¨Û€VJû…h-7Œ¥iĽ’²>;ûëë©$ \¤V&×·¦/Ô>:¤Ÿ=C+:ŒjoxÒF‡™²´ëÙj«ÙèÚ<‹wk^¾•?áêµHˆO“˜@²”4ñF‡LÓ ëi`Ô§#Ï¢B•ƒ©‘j9¹Ótº“Ò·BŸN.1ÿ`x32hû×£›ÒÉ%eä#€;²ø~¢¥" [®_O"ó• ¢œ”©ƒÄÙF’‘‚˜G<3Âî¨Û´%°}3NDDâM CûõÇ%Rü‘'N!à¢=ÛÂÓn†…&hàEBϹƒ,G)L!¸X‚p(©å*®ÍT¬¢M¹3TTÐ-º¢í¶6S)#n¤éd¹)iHæ±v¨«ÁL \<©¡®ÓŸ¼× ÇFDäœØ™>¢ý³obp¨¿Hó;;é¦x'#%n£ºÈ‹Á‚J¡$̆‡9‰În°YŒÅÉi™íoP.á™e«ŒàÓ 1Y¦çpr÷>Ü̦ oHê¼ ^B¡sœÃᇑ@„´jßr«¹Ðé)’ßl¼Ž+k–àl›7QWèSæg]ú-uÈÙ9°[¬…ÓˆÇÁ‰…á Õ‘ó¾°üIîÂU.d+)ö/«'Ъ j‡—Fwƒ—¶«›ñþüí$@20–HŸ•V~$‹ÔÏË›þ‹'Ò)^‡æ­ÂЫI-lß}V ”z'ü‰&hÖ`åűÂbi…Ã.›¸2b¸Ñ JÚ+Wõ"¹lR*¹dÕðÀ ›f$Heº bÉ”)D—²ú‹{±å2E=Ð uä ù¼yS/ ,ÖoÂeÚ@tø6G‘† ¥Úý+·ÑFk 4©UÍZë°{-"i·kÛÈÇK¾pq ‚ÏŽ u9yG; býôí ÁYR›µ²ÿ”~«¦àßS&Òæð@tmļìÔ€ÂMBHygŸC¼‘ju¶“/.£Yž„£kñ¿íÉèòس˜4cæ|:(>*Ž6mµŠBÖjÚ&¨lèM4X©.m­º‚…v6‚\[lSœ)ùªà÷oÙ"ˆjûeÒg±ÙGì“Ô×ʸú4@¨¸|ä²d:tjH.*š½‚ÑŠ Цx=Å·j ù4$eÏ%òˆz FNþÿ÷8ÑŸ‚EágD׎ÐñKê·( Ô_§kìÒ¥šÈ©F÷~JeYý.iÖÌ7!Ù%Þ5O…ß«ê¡cmò'lŶ¿ò„N³6ìæ¡ñÜ”‚lö$ôÉŠfD9Âh¬Pº3°;©oÒæÿõÃkJ-—RY~uê‘Ê’Ÿ{¬?‰$Z¥¿žÜ¶;÷ìÀöíÛ±yÕøú×$Â:¼úÚ£¤ê¢K;àÌrü¸;zCbw¯ÄdèÒ >v¬v„†Q š6at܆šÍBDÈ—Ü*XM¾ÓTcKþVÔG×ÚôÓªˆ. >ö,âoü…“;~Ág¿ž&MÖ~¼»ƒ)­¥?lFRv®_ðÓä;r›1ñgÖbKÔ5$’_5::×É«àEËuZs»…ZG)&rЊMñn‚.Á@êðgTÒ"ðËÒT¢:5òÍ,öÓJV¶C‚`—ÁîRí]¼õEhi~ 2ß¶hìk'Ÿ5£É!Íh߆Åk[¢‰¿&„¢xBû4äúvÀÖ>EÿMW©ïBÉb¾<ìÔiîø±R+ÒUªÅ–—)ÜÖ$K»ò‚ì'ÈÏ®…3±þp­S‘ðÿÎÁ’ëbƒŒö7Ø\ž‡Ø8’›ˆýX0ý: ©Ž<;+Kò#;‡Yóv#^ð;¿û7ÁˆòéÒ†ÜZtˆBZáш՘Xj¹,¢8º(§«G0S³[ ½ÒîŒgèbI©äÒÙ ¿ÜçÈâââ¤ñT&(dt ¦¦îV‹Ën³ OŸ £tÂ…NA£Fòá*½üQÇÏ“ü¹tj#+Ç)ÌäeÑÐ&¨Ž âLdȾSxÀßÏ 2K.Ò² ]?tj ÒÓôÎrrèjúCmÑ#-Ûâ¼Ï¡{Ú.±M9d¤Ô,deù8_³7æ¤Ã,÷‚mÄfÜÌ$ëŠÒi3Oã(lÎÚI ÉIñëÓÒɆ×л ¹‚5¬$ºëÐÏP‡™E§R C˜°g1~Üï‰wf½ ß)kžVºzÖƒŸÆÏ¥7csb7à?¿ŸÆ³Sÿƒn>yHËÌ«TÅÏèSh‰ÞjØé$R:;oî ¿.<‘Ѫ¦¦fÚŒÔ;¼è^EaÉpiàWSGJ›6#³íÐÑÏ>°|Ùn±¶ôã˜õÝVô7•Þ Õ„Ô p•ÃÇŸxL{.é´¡)ÀkKÀ³~„bÐ$|ðèÈ&ž°ÔÊ rµ'ísÐÆ;% 'É*û© ;mÊæA¥ó†õÓ¬‚?õßêÒgš…¬ÆÓ~„›Ý’ƒÌ<|}=pé)øþLW|>}LI©°R½T/ù’‘M}t•wI–4mP{¥•ËÊÄŠ·uo" »víZ¥ …’,7:tï`J×ê¦!ï6%µ)§ E¶ g³²e4é)ZŽËÙF,{  £MX%£×FtÎ8W2•Ô¹ÐõÇýˆ‹3§- ¿Î^ y/·òpQP2ZúSyÊf·°Rº¡ŸCØ1.Ž6ŽÿŒêˆ¼Œä²Ùá>ÖÍÁªøî˜öÏî´™^²l$þïÔཹo¡ž9‹Ü"ìlÌß$Crrã±#ª6’R $’3•’6§iXiEG’ â•­_cYd;Ìš=Ú“3×!Õk-N¶Šér©ä²˜²<úþAàŽ|üeÉfµ•L't*Ié3ÚJjÓN ßB«I§;È…!)}V–)|‹…ÎÜKX¤K°æ÷§¥Ïò*êà‰ºãú‰(ȽE׈X¹. †‡´0²eÄ Ê‚×_ìHÇ9rî¥ÏðLoÿÏ"Æ@–´P1ß9ˆŽÊDç—^@}­$rÿ>¥ÏdFƒ #¥Uú¬É™PFPúB„xêKI+\;ÑÅ&{’&{eTú¬¶RÉ%ËÈÃ}@¥Yü÷3ÊrrŸøÓ)¦|wE1`Èhð׬¡&—RF¥ý\C1¤T~4¹†jÔô†%3&½’lgzéÍß²¼ dÑQÉê´ºšäÎ4#-ßYzÇûr/! »zõjI£ì^¢•ÓÂàp8€@É+ë h€WÁàp8÷å:ÎyouSÃàp8eA€[üeA‹çåp8ÕnñW&ò.p8² À-þ² Åór8j€WüÕ€‰¼ ŽG ,pWOYÐây9Ž@5@€[üÕ€‰¼ ŽG ,ü?‡V#ú9}nýIEND®B`‚numpy-1.8.2/doc/source/dev/gitwash/git_development.rst0000664000175100017510000000027712370216242024241 0ustar vagrantvagrant00000000000000.. _git-development: ===================== Git for development ===================== Contents: .. toctree:: :maxdepth: 2 development_setup configure_git development_workflow numpy-1.8.2/doc/source/dev/gitwash/git_intro.rst0000664000175100017510000000207412370216242023047 0ustar vagrantvagrant00000000000000============ Introduction ============ These pages describe a git_ and github_ workflow for the NumPy_ project. There are several different workflows here, for different ways of working with *NumPy*. This is not a comprehensive git_ reference, it's just a workflow for our own project. It's tailored to the github_ hosting service. You may well find better or quicker ways of getting stuff done with git_, but these should get you started. For general resources for learning git_ see :ref:`git-resources`. .. _install-git: Install git =========== Overview -------- ================ ============= Debian / Ubuntu ``sudo apt-get install git-core`` Fedora ``sudo yum install git-core`` Windows Download and install msysGit_ OS X Use the git-osx-installer_ ================ ============= In detail --------- See the git_ page for the most recent information. Have a look at the github_ install help pages available from `github help`_ There are good instructions here: http://book.git-scm.com/2_installing_git.html .. include:: git_links.inc numpy-1.8.2/doc/source/dev/index.rst0000664000175100017510000000025112370216242020505 0ustar vagrantvagrant00000000000000##################### Contributing to Numpy ##################### .. toctree:: :maxdepth: 3 gitwash/index For core developers: see :ref:`development-workflow`. numpy-1.8.2/doc/source/dev/gitwash_links.txt0000664000175100017510000000021312370216242022251 0ustar vagrantvagrant00000000000000.. _NumPy: http://www.numpy.org .. _`NumPy github`: http://github.com/numpy/numpy .. _`NumPy mailing list`: http://scipy.org/Mailing_Lists numpy-1.8.2/doc/source/contents.rst0000664000175100017510000000026212370216243020460 0ustar vagrantvagrant00000000000000##################### Numpy manual contents ##################### .. toctree:: user/index reference/index dev/index release about bugs license glossary numpy-1.8.2/doc/source/glossary.rst0000664000175100017510000000017612370216242020471 0ustar vagrantvagrant00000000000000******** Glossary ******** .. toctree:: .. automodule:: numpy.doc.glossary Jargon ------ .. automodule:: numpy.doc.jargon numpy-1.8.2/doc/source/bugs.rst0000664000175100017510000000120512370216242017560 0ustar vagrantvagrant00000000000000************** Reporting bugs ************** File bug reports or feature requests, and make contributions (e.g. code patches), by opening a "new issue" on GitHub: - Numpy Issues: http://github.com/numpy/numpy/issues Please give as much information as you can in the ticket. It is extremely useful if you can supply a small self-contained code snippet that reproduces the problem. Also specify the component, the version you are referring to and the milestone. Report bugs to the appropriate GitHub project (there is one for NumPy and a different one for SciPy). More information can be found on the http://scipy.org/Developer_Zone website. numpy-1.8.2/doc/source/about.rst0000664000175100017510000000452112370216242017736 0ustar vagrantvagrant00000000000000About NumPy =========== `NumPy `__ is the fundamental package needed for scientific computing with Python. This package contains: - a powerful N-dimensional :ref:`array object ` - sophisticated :ref:`(broadcasting) functions ` - basic :ref:`linear algebra functions ` - basic :ref:`Fourier transforms ` - sophisticated :ref:`random number capabilities ` - tools for integrating Fortran code - tools for integrating C/C++ code Besides its obvious scientific uses, *NumPy* can also be used as an efficient multi-dimensional container of generic data. Arbitrary data types can be defined. This allows *NumPy* to seamlessly and speedily integrate with a wide variety of databases. NumPy is a successor for two earlier scientific Python libraries: NumPy derives from the old *Numeric* code base and can be used as a replacement for *Numeric*. It also adds the features introduced by *Numarray* and can also be used to replace *Numarray*. NumPy community --------------- Numpy is a distributed, volunteer, open-source project. *You* can help us make it better; if you believe something should be improved either in functionality or in documentation, don't hesitate to contact us --- or even better, contact us and participate in fixing the problem. Our main means of communication are: - `scipy.org website `__ - `Mailing lists `__ - `Numpy Issues `__ (bug reports go here) - `Old Numpy Trac `__ (no longer used) More information about the development of Numpy can be found at http://scipy.org/Developer_Zone If you want to fix issues in this documentation, the easiest way is to participate in `our ongoing documentation marathon `__. About this documentation ======================== Conventions ----------- Names of classes, objects, constants, etc. are given in **boldface** font. Often they are also links to a more detailed documentation of the referred object. This manual contains many examples of use, usually prefixed with the Python prompt ``>>>`` (which is not a part of the example code). The examples assume that you have first entered:: >>> import numpy as np before running the examples. numpy-1.8.2/doc/source/license.rst0000664000175100017510000000300312370216242020240 0ustar vagrantvagrant00000000000000************* Numpy License ************* Copyright (c) 2005, NumPy Developers All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the NumPy Developers nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. numpy-1.8.2/doc/source/conf.py0000664000175100017510000002306512370216242017375 0ustar vagrantvagrant00000000000000# -*- coding: utf-8 -*- from __future__ import division, absolute_import, print_function import sys, os, re # Check Sphinx version import sphinx if sphinx.__version__ < "1.0.1": raise RuntimeError("Sphinx 1.0.1 or newer required") needs_sphinx = '1.0' # ----------------------------------------------------------------------------- # General configuration # ----------------------------------------------------------------------------- # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. sys.path.insert(0, os.path.abspath('../sphinxext')) extensions = ['sphinx.ext.autodoc', 'sphinx.ext.pngmath', 'numpydoc', 'sphinx.ext.intersphinx', 'sphinx.ext.coverage', 'sphinx.ext.doctest', 'sphinx.ext.autosummary', 'matplotlib.sphinxext.plot_directive'] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # General substitutions. project = 'NumPy' copyright = '2008-2009, The Scipy community' # The default replacements for |version| and |release|, also used in various # other places throughout the built documents. # import numpy # The short X.Y version (including .devXXXX, rcX, b1 suffixes if present) version = re.sub(r'(\d+\.\d+)\.\d+(.*)', r'\1\2', numpy.__version__) version = re.sub(r'(\.dev\d+).*?$', r'\1', version) # The full version, including alpha/beta/rc tags. release = numpy.__version__ print("%s %s" % (version, release)) # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. today_fmt = '%B %d, %Y' # List of documents that shouldn't be included in the build. #unused_docs = [] # The reST default role (used for this markup: `text`) to use for all documents. default_role = "autolink" # List of directories, relative to source directories, that shouldn't be searched # for source files. exclude_dirs = [] # If true, '()' will be appended to :func: etc. cross-reference text. add_function_parentheses = False # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # ----------------------------------------------------------------------------- # HTML output # ----------------------------------------------------------------------------- themedir = os.path.join(os.pardir, 'scipy-sphinx-theme', '_theme') if not os.path.isdir(themedir): raise RuntimeError("Get the scipy-sphinx-theme first, " "via git submodule init && git submodule update") html_theme = 'scipy' html_theme_path = [themedir] if 'scipyorg' in tags: # Build for the scipy.org website html_theme_options = { "edit_link": True, "sidebar": "right", "scipy_org_logo": True, "rootlinks": [("http://scipy.org/", "Scipy.org"), ("http://docs.scipy.org/", "Docs")] } else: # Default build html_theme_options = { "edit_link": False, "sidebar": "left", "scipy_org_logo": False, "rootlinks": [] } html_sidebars = {'index': 'indexsidebar.html'} html_additional_pages = { 'index': 'indexcontent.html', } html_title = "%s v%s Manual" % (project, version) html_static_path = ['_static'] html_last_updated_fmt = '%b %d, %Y' html_use_modindex = True html_copy_source = False html_domain_indices = False html_file_suffix = '.html' htmlhelp_basename = 'numpy' pngmath_use_preview = True pngmath_dvipng_args = ['-gamma', '1.5', '-D', '96', '-bg', 'Transparent'] # ----------------------------------------------------------------------------- # LaTeX output # ----------------------------------------------------------------------------- # The paper size ('letter' or 'a4'). #latex_paper_size = 'letter' # The font size ('10pt', '11pt' or '12pt'). #latex_font_size = '10pt' # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, document class [howto/manual]). _stdauthor = 'Written by the NumPy community' latex_documents = [ ('reference/index', 'numpy-ref.tex', 'NumPy Reference', _stdauthor, 'manual'), ('user/index', 'numpy-user.tex', 'NumPy User Guide', _stdauthor, 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # Additional stuff for the LaTeX preamble. latex_preamble = r''' \usepackage{amsmath} \DeclareUnicodeCharacter{00A0}{\nobreakspace} % In the parameters section, place a newline after the Parameters % header \usepackage{expdlist} \let\latexdescription=\description \def\description{\latexdescription{}{} \breaklabel} % Make Examples/etc section headers smaller and more compact \makeatletter \titleformat{\paragraph}{\normalsize\py@HeaderFamily}% {\py@TitleColor}{0em}{\py@TitleColor}{\py@NormalColor} \titlespacing*{\paragraph}{0pt}{1ex}{0pt} \makeatother % Fix footer/header \renewcommand{\chaptermark}[1]{\markboth{\MakeUppercase{\thechapter.\ #1}}{}} \renewcommand{\sectionmark}[1]{\markright{\MakeUppercase{\thesection.\ #1}}} ''' # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. latex_use_modindex = False # ----------------------------------------------------------------------------- # Texinfo output # ----------------------------------------------------------------------------- texinfo_documents = [ ("contents", 'numpy', 'Numpy Documentation', _stdauthor, 'Numpy', "NumPy: array processing for numbers, strings, records, and objects.", 'Programming', 1), ] # ----------------------------------------------------------------------------- # Intersphinx configuration # ----------------------------------------------------------------------------- intersphinx_mapping = {'http://docs.python.org/dev': None} # ----------------------------------------------------------------------------- # Numpy extensions # ----------------------------------------------------------------------------- # If we want to do a phantom import from an XML file for all autodocs phantom_import_file = 'dump.xml' # Make numpydoc to generate plots for example sections numpydoc_use_plots = True # ----------------------------------------------------------------------------- # Autosummary # ----------------------------------------------------------------------------- import glob autosummary_generate = glob.glob("reference/*.rst") # ----------------------------------------------------------------------------- # Coverage checker # ----------------------------------------------------------------------------- coverage_ignore_modules = r""" """.split() coverage_ignore_functions = r""" test($|_) (some|all)true bitwise_not cumproduct pkgload generic\. """.split() coverage_ignore_classes = r""" """.split() coverage_c_path = [] coverage_c_regexes = {} coverage_ignore_c_items = {} # ----------------------------------------------------------------------------- # Plots # ----------------------------------------------------------------------------- plot_pre_code = """ import numpy as np np.random.seed(0) """ plot_include_source = True plot_formats = [('png', 100), 'pdf'] import math phi = (math.sqrt(5) + 1)/2 plot_rcparams = { 'font.size': 8, 'axes.titlesize': 8, 'axes.labelsize': 8, 'xtick.labelsize': 8, 'ytick.labelsize': 8, 'legend.fontsize': 8, 'figure.figsize': (3*phi, 3), 'figure.subplot.bottom': 0.2, 'figure.subplot.left': 0.2, 'figure.subplot.right': 0.9, 'figure.subplot.top': 0.85, 'figure.subplot.wspace': 0.4, 'text.usetex': False, } # ----------------------------------------------------------------------------- # Source code links # ----------------------------------------------------------------------------- import inspect from os.path import relpath, dirname for name in ['sphinx.ext.linkcode', 'numpydoc.linkcode']: try: __import__(name) extensions.append(name) break except ImportError: pass else: print("NOTE: linkcode extension not found -- no links to source generated") def linkcode_resolve(domain, info): """ Determine the URL corresponding to Python object """ if domain != 'py': return None modname = info['module'] fullname = info['fullname'] submod = sys.modules.get(modname) if submod is None: return None obj = submod for part in fullname.split('.'): try: obj = getattr(obj, part) except: return None try: fn = inspect.getsourcefile(obj) except: fn = None if not fn: return None try: source, lineno = inspect.findsource(obj) except: lineno = None if lineno: linespec = "#L%d" % (lineno + 1) else: linespec = "" fn = relpath(fn, start=dirname(numpy.__file__)) if 'dev' in numpy.__version__: return "http://github.com/numpy/numpy/blob/master/numpy/%s%s" % ( fn, linespec) else: return "http://github.com/numpy/numpy/blob/v%s/numpy/%s%s" % ( numpy.__version__, fn, linespec) numpy-1.8.2/doc/pyrex/0000775000175100017510000000000012371375427015753 5ustar vagrantvagrant00000000000000numpy-1.8.2/doc/pyrex/README.txt0000664000175100017510000000025712370216243017442 0ustar vagrantvagrant00000000000000WARNING: this code is deprecated and slated for removal soon. See the doc/cython directory for the replacement, which uses Cython (the actively maintained version of Pyrex). numpy-1.8.2/doc/pyrex/numpyx.c0000664000175100017510000013761712370216243017463 0ustar vagrantvagrant00000000000000/* Generated by Pyrex 0.9.5.1 on Wed Jan 31 11:57:10 2007 */ #include "Python.h" #include "structmember.h" #ifndef PY_LONG_LONG #define PY_LONG_LONG LONG_LONG #endif #ifdef __cplusplus #define __PYX_EXTERN_C extern "C" #else #define __PYX_EXTERN_C extern #endif __PYX_EXTERN_C double pow(double, double); #include "stdlib.h" #include "numpy/arrayobject.h" typedef struct {PyObject **p; char *s;} __Pyx_InternTabEntry; /*proto*/ typedef struct {PyObject **p; char *s; long n;} __Pyx_StringTabEntry; /*proto*/ static PyObject *__pyx_m; static PyObject *__pyx_b; static int __pyx_lineno; static char *__pyx_filename; static char **__pyx_f; static int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed, char *name); /*proto*/ static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list); /*proto*/ static int __Pyx_PrintItem(PyObject *); /*proto*/ static int __Pyx_PrintNewline(void); /*proto*/ static PyObject *__Pyx_GetName(PyObject *dict, PyObject *name); /*proto*/ static int __Pyx_InternStrings(__Pyx_InternTabEntry *t); /*proto*/ static int __Pyx_InitStrings(__Pyx_StringTabEntry *t); /*proto*/ static PyTypeObject *__Pyx_ImportType(char *module_name, char *class_name, long size); /*proto*/ static void __Pyx_AddTraceback(char *funcname); /*proto*/ /* Declarations from c_python */ /* Declarations from c_numpy */ static PyTypeObject *__pyx_ptype_7c_numpy_dtype = 0; static PyTypeObject *__pyx_ptype_7c_numpy_ndarray = 0; static PyTypeObject *__pyx_ptype_7c_numpy_flatiter = 0; static PyTypeObject *__pyx_ptype_7c_numpy_broadcast = 0; /* Declarations from numpyx */ static PyObject *(__pyx_f_6numpyx_print_elements(char (*),Py_intptr_t (*),Py_intptr_t (*),int ,int ,PyObject *)); /*proto*/ /* Implementation of numpyx */ static PyObject *__pyx_n_c_python; static PyObject *__pyx_n_c_numpy; static PyObject *__pyx_n_numpy; static PyObject *__pyx_n_print_array_info; static PyObject *__pyx_n_test_methods; static PyObject *__pyx_n_test; static PyObject *__pyx_n_dtype; static PyObject *__pyx_k2p; static PyObject *__pyx_k3p; static PyObject *__pyx_k4p; static PyObject *__pyx_k5p; static PyObject *__pyx_k6p; static PyObject *__pyx_k7p; static PyObject *__pyx_k8p; static PyObject *__pyx_k9p; static char (__pyx_k2[]) = "-="; static char (__pyx_k3[]) = "printing array info for ndarray at 0x%0lx"; static char (__pyx_k4[]) = "print number of dimensions:"; static char (__pyx_k5[]) = "address of strides: 0x%0lx"; static char (__pyx_k6[]) = "strides:"; static char (__pyx_k7[]) = " stride %d:"; static char (__pyx_k8[]) = "memory dump:"; static char (__pyx_k9[]) = "-="; static PyObject *__pyx_f_6numpyx_print_array_info(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static PyObject *__pyx_f_6numpyx_print_array_info(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { PyArrayObject *__pyx_v_arr = 0; int __pyx_v_i; PyObject *__pyx_r; PyObject *__pyx_1 = 0; PyObject *__pyx_2 = 0; int __pyx_3; static char *__pyx_argnames[] = {"arr",0}; if (!PyArg_ParseTupleAndKeywords(__pyx_args, __pyx_kwds, "O", __pyx_argnames, &__pyx_v_arr)) return 0; Py_INCREF(__pyx_v_arr); if (!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_arr), __pyx_ptype_7c_numpy_ndarray, 1, "arr")) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 10; goto __pyx_L1;} /* "/Users/rkern/svn/numpy/numpy/doc/pyrex/numpyx.pyx":13 */ __pyx_1 = PyInt_FromLong(10); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 13; goto __pyx_L1;} __pyx_2 = PyNumber_Multiply(__pyx_k2p, __pyx_1); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 13; goto __pyx_L1;} Py_DECREF(__pyx_1); __pyx_1 = 0; if (__Pyx_PrintItem(__pyx_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 13; goto __pyx_L1;} Py_DECREF(__pyx_2); __pyx_2 = 0; if (__Pyx_PrintNewline() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 13; goto __pyx_L1;} /* "/Users/rkern/svn/numpy/numpy/doc/pyrex/numpyx.pyx":14 */ __pyx_1 = PyInt_FromLong(((int )__pyx_v_arr)); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; goto __pyx_L1;} __pyx_2 = PyTuple_New(1); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; goto __pyx_L1;} PyTuple_SET_ITEM(__pyx_2, 0, __pyx_1); __pyx_1 = 0; __pyx_1 = PyNumber_Remainder(__pyx_k3p, __pyx_2); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; goto __pyx_L1;} Py_DECREF(__pyx_2); __pyx_2 = 0; if (__Pyx_PrintItem(__pyx_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; goto __pyx_L1;} Py_DECREF(__pyx_1); __pyx_1 = 0; if (__Pyx_PrintNewline() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; goto __pyx_L1;} /* "/Users/rkern/svn/numpy/numpy/doc/pyrex/numpyx.pyx":15 */ if (__Pyx_PrintItem(__pyx_k4p) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 15; goto __pyx_L1;} __pyx_2 = PyInt_FromLong(__pyx_v_arr->nd); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 15; goto __pyx_L1;} if (__Pyx_PrintItem(__pyx_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 15; goto __pyx_L1;} Py_DECREF(__pyx_2); __pyx_2 = 0; if (__Pyx_PrintNewline() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 15; goto __pyx_L1;} /* "/Users/rkern/svn/numpy/numpy/doc/pyrex/numpyx.pyx":16 */ __pyx_1 = PyInt_FromLong(((int )__pyx_v_arr->strides)); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 16; goto __pyx_L1;} __pyx_2 = PyTuple_New(1); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 16; goto __pyx_L1;} PyTuple_SET_ITEM(__pyx_2, 0, __pyx_1); __pyx_1 = 0; __pyx_1 = PyNumber_Remainder(__pyx_k5p, __pyx_2); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 16; goto __pyx_L1;} Py_DECREF(__pyx_2); __pyx_2 = 0; if (__Pyx_PrintItem(__pyx_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 16; goto __pyx_L1;} Py_DECREF(__pyx_1); __pyx_1 = 0; if (__Pyx_PrintNewline() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 16; goto __pyx_L1;} /* "/Users/rkern/svn/numpy/numpy/doc/pyrex/numpyx.pyx":17 */ if (__Pyx_PrintItem(__pyx_k6p) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 17; goto __pyx_L1;} if (__Pyx_PrintNewline() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 17; goto __pyx_L1;} /* "/Users/rkern/svn/numpy/numpy/doc/pyrex/numpyx.pyx":18 */ __pyx_3 = __pyx_v_arr->nd; for (__pyx_v_i = 0; __pyx_v_i < __pyx_3; ++__pyx_v_i) { /* "/Users/rkern/svn/numpy/numpy/doc/pyrex/numpyx.pyx":20 */ __pyx_2 = PyInt_FromLong(__pyx_v_i); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 20; goto __pyx_L1;} __pyx_1 = PyNumber_Remainder(__pyx_k7p, __pyx_2); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 20; goto __pyx_L1;} Py_DECREF(__pyx_2); __pyx_2 = 0; if (__Pyx_PrintItem(__pyx_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 20; goto __pyx_L1;} Py_DECREF(__pyx_1); __pyx_1 = 0; __pyx_2 = PyInt_FromLong(((int )(__pyx_v_arr->strides[__pyx_v_i]))); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 20; goto __pyx_L1;} if (__Pyx_PrintItem(__pyx_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 20; goto __pyx_L1;} Py_DECREF(__pyx_2); __pyx_2 = 0; if (__Pyx_PrintNewline() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 20; goto __pyx_L1;} } /* "/Users/rkern/svn/numpy/numpy/doc/pyrex/numpyx.pyx":21 */ if (__Pyx_PrintItem(__pyx_k8p) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; goto __pyx_L1;} if (__Pyx_PrintNewline() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; goto __pyx_L1;} /* "/Users/rkern/svn/numpy/numpy/doc/pyrex/numpyx.pyx":22 */ __pyx_1 = PyObject_GetAttr(((PyObject *)__pyx_v_arr), __pyx_n_dtype); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 23; goto __pyx_L1;} __pyx_2 = __pyx_f_6numpyx_print_elements(__pyx_v_arr->data,__pyx_v_arr->strides,__pyx_v_arr->dimensions,__pyx_v_arr->nd,(sizeof(double )),__pyx_1); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 22; goto __pyx_L1;} Py_DECREF(__pyx_1); __pyx_1 = 0; Py_DECREF(__pyx_2); __pyx_2 = 0; /* "/Users/rkern/svn/numpy/numpy/doc/pyrex/numpyx.pyx":24 */ __pyx_1 = PyInt_FromLong(10); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 24; goto __pyx_L1;} __pyx_2 = PyNumber_Multiply(__pyx_k9p, __pyx_1); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 24; goto __pyx_L1;} Py_DECREF(__pyx_1); __pyx_1 = 0; if (__Pyx_PrintItem(__pyx_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 24; goto __pyx_L1;} Py_DECREF(__pyx_2); __pyx_2 = 0; if (__Pyx_PrintNewline() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 24; goto __pyx_L1;} /* "/Users/rkern/svn/numpy/numpy/doc/pyrex/numpyx.pyx":25 */ if (__Pyx_PrintNewline() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 25; goto __pyx_L1;} __pyx_r = Py_None; Py_INCREF(Py_None); goto __pyx_L0; __pyx_L1:; Py_XDECREF(__pyx_1); Py_XDECREF(__pyx_2); __Pyx_AddTraceback("numpyx.print_array_info"); __pyx_r = 0; __pyx_L0:; Py_DECREF(__pyx_v_arr); return __pyx_r; } static PyObject *__pyx_n_object_; static PyObject *__pyx_n_float64; static PyObject *__pyx_n_name; static PyObject *__pyx_k10p; static PyObject *__pyx_k11p; static PyObject *__pyx_k12p; static PyObject *__pyx_k13p; static PyObject *__pyx_k14p; static char (__pyx_k10[]) = " print_elements() not (yet) implemented for dtype %s"; static char (__pyx_k11[]) = " "; static char (__pyx_k12[]) = " "; static char (__pyx_k13[]) = " "; static char (__pyx_k14[]) = " "; static PyObject *__pyx_f_6numpyx_print_elements(char (*__pyx_v_data),Py_intptr_t (*__pyx_v_strides),Py_intptr_t (*__pyx_v_dimensions),int __pyx_v_nd,int __pyx_v_elsize,PyObject *__pyx_v_dtype) { Py_intptr_t __pyx_v_i; void (*__pyx_v_elptr); PyObject *__pyx_r; PyObject *__pyx_1 = 0; PyObject *__pyx_2 = 0; PyObject *__pyx_3 = 0; PyObject *__pyx_4 = 0; int __pyx_5; Py_intptr_t __pyx_6; Py_INCREF(__pyx_v_dtype); /* "/Users/rkern/svn/numpy/numpy/doc/pyrex/numpyx.pyx":36 */ __pyx_1 = __Pyx_GetName(__pyx_m, __pyx_n_numpy); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 36; goto __pyx_L1;} __pyx_2 = PyObject_GetAttr(__pyx_1, __pyx_n_dtype); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 36; goto __pyx_L1;} Py_DECREF(__pyx_1); __pyx_1 = 0; __pyx_1 = __Pyx_GetName(__pyx_m, __pyx_n_numpy); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 36; goto __pyx_L1;} __pyx_3 = PyObject_GetAttr(__pyx_1, __pyx_n_object_); if (!__pyx_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 36; goto __pyx_L1;} Py_DECREF(__pyx_1); __pyx_1 = 0; __pyx_1 = PyTuple_New(1); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 36; goto __pyx_L1;} PyTuple_SET_ITEM(__pyx_1, 0, __pyx_3); __pyx_3 = 0; __pyx_3 = PyObject_CallObject(__pyx_2, __pyx_1); if (!__pyx_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 36; goto __pyx_L1;} Py_DECREF(__pyx_2); __pyx_2 = 0; Py_DECREF(__pyx_1); __pyx_1 = 0; __pyx_2 = __Pyx_GetName(__pyx_m, __pyx_n_numpy); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 37; goto __pyx_L1;} __pyx_1 = PyObject_GetAttr(__pyx_2, __pyx_n_dtype); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 37; goto __pyx_L1;} Py_DECREF(__pyx_2); __pyx_2 = 0; __pyx_2 = __Pyx_GetName(__pyx_m, __pyx_n_numpy); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 37; goto __pyx_L1;} __pyx_4 = PyObject_GetAttr(__pyx_2, __pyx_n_float64); if (!__pyx_4) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 37; goto __pyx_L1;} Py_DECREF(__pyx_2); __pyx_2 = 0; __pyx_2 = PyTuple_New(1); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 37; goto __pyx_L1;} PyTuple_SET_ITEM(__pyx_2, 0, __pyx_4); __pyx_4 = 0; __pyx_4 = PyObject_CallObject(__pyx_1, __pyx_2); if (!__pyx_4) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 37; goto __pyx_L1;} Py_DECREF(__pyx_1); __pyx_1 = 0; Py_DECREF(__pyx_2); __pyx_2 = 0; __pyx_1 = PyList_New(2); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 36; goto __pyx_L1;} PyList_SET_ITEM(__pyx_1, 0, __pyx_3); PyList_SET_ITEM(__pyx_1, 1, __pyx_4); __pyx_3 = 0; __pyx_4 = 0; __pyx_5 = PySequence_Contains(__pyx_1, __pyx_v_dtype); if (__pyx_5 < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 36; goto __pyx_L1;} __pyx_5 = !__pyx_5; Py_DECREF(__pyx_1); __pyx_1 = 0; if (__pyx_5) { /* "/Users/rkern/svn/numpy/numpy/doc/pyrex/numpyx.pyx":38 */ __pyx_2 = PyObject_GetAttr(__pyx_v_dtype, __pyx_n_name); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 38; goto __pyx_L1;} __pyx_3 = PyNumber_Remainder(__pyx_k10p, __pyx_2); if (!__pyx_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 38; goto __pyx_L1;} Py_DECREF(__pyx_2); __pyx_2 = 0; if (__Pyx_PrintItem(__pyx_3) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 38; goto __pyx_L1;} Py_DECREF(__pyx_3); __pyx_3 = 0; if (__Pyx_PrintNewline() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 38; goto __pyx_L1;} /* "/Users/rkern/svn/numpy/numpy/doc/pyrex/numpyx.pyx":39 */ __pyx_r = Py_None; Py_INCREF(Py_None); goto __pyx_L0; goto __pyx_L2; } __pyx_L2:; /* "/Users/rkern/svn/numpy/numpy/doc/pyrex/numpyx.pyx":41 */ __pyx_5 = (__pyx_v_nd == 0); if (__pyx_5) { /* "/Users/rkern/svn/numpy/numpy/doc/pyrex/numpyx.pyx":42 */ __pyx_4 = __Pyx_GetName(__pyx_m, __pyx_n_numpy); if (!__pyx_4) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 42; goto __pyx_L1;} __pyx_1 = PyObject_GetAttr(__pyx_4, __pyx_n_dtype); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 42; goto __pyx_L1;} Py_DECREF(__pyx_4); __pyx_4 = 0; __pyx_2 = __Pyx_GetName(__pyx_m, __pyx_n_numpy); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 42; goto __pyx_L1;} __pyx_3 = PyObject_GetAttr(__pyx_2, __pyx_n_object_); if (!__pyx_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 42; goto __pyx_L1;} Py_DECREF(__pyx_2); __pyx_2 = 0; __pyx_4 = PyTuple_New(1); if (!__pyx_4) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 42; goto __pyx_L1;} PyTuple_SET_ITEM(__pyx_4, 0, __pyx_3); __pyx_3 = 0; __pyx_2 = PyObject_CallObject(__pyx_1, __pyx_4); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 42; goto __pyx_L1;} Py_DECREF(__pyx_1); __pyx_1 = 0; Py_DECREF(__pyx_4); __pyx_4 = 0; if (PyObject_Cmp(__pyx_v_dtype, __pyx_2, &__pyx_5) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 42; goto __pyx_L1;} __pyx_5 = __pyx_5 == 0; Py_DECREF(__pyx_2); __pyx_2 = 0; if (__pyx_5) { /* "/Users/rkern/svn/numpy/numpy/doc/pyrex/numpyx.pyx":43 */ __pyx_v_elptr = (((void (*(*)))__pyx_v_data)[0]); /* "/Users/rkern/svn/numpy/numpy/doc/pyrex/numpyx.pyx":44 */ if (__Pyx_PrintItem(__pyx_k11p) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 44; goto __pyx_L1;} __pyx_3 = (PyObject *)__pyx_v_elptr; Py_INCREF(__pyx_3); if (__Pyx_PrintItem(__pyx_3) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 44; goto __pyx_L1;} Py_DECREF(__pyx_3); __pyx_3 = 0; if (__Pyx_PrintNewline() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 44; goto __pyx_L1;} goto __pyx_L4; } __pyx_1 = __Pyx_GetName(__pyx_m, __pyx_n_numpy); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 45; goto __pyx_L1;} __pyx_4 = PyObject_GetAttr(__pyx_1, __pyx_n_dtype); if (!__pyx_4) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 45; goto __pyx_L1;} Py_DECREF(__pyx_1); __pyx_1 = 0; __pyx_2 = __Pyx_GetName(__pyx_m, __pyx_n_numpy); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 45; goto __pyx_L1;} __pyx_3 = PyObject_GetAttr(__pyx_2, __pyx_n_float64); if (!__pyx_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 45; goto __pyx_L1;} Py_DECREF(__pyx_2); __pyx_2 = 0; __pyx_1 = PyTuple_New(1); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 45; goto __pyx_L1;} PyTuple_SET_ITEM(__pyx_1, 0, __pyx_3); __pyx_3 = 0; __pyx_2 = PyObject_CallObject(__pyx_4, __pyx_1); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 45; goto __pyx_L1;} Py_DECREF(__pyx_4); __pyx_4 = 0; Py_DECREF(__pyx_1); __pyx_1 = 0; if (PyObject_Cmp(__pyx_v_dtype, __pyx_2, &__pyx_5) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 45; goto __pyx_L1;} __pyx_5 = __pyx_5 == 0; Py_DECREF(__pyx_2); __pyx_2 = 0; if (__pyx_5) { /* "/Users/rkern/svn/numpy/numpy/doc/pyrex/numpyx.pyx":46 */ if (__Pyx_PrintItem(__pyx_k12p) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 46; goto __pyx_L1;} __pyx_3 = PyFloat_FromDouble((((double (*))__pyx_v_data)[0])); if (!__pyx_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 46; goto __pyx_L1;} if (__Pyx_PrintItem(__pyx_3) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 46; goto __pyx_L1;} Py_DECREF(__pyx_3); __pyx_3 = 0; if (__Pyx_PrintNewline() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 46; goto __pyx_L1;} goto __pyx_L4; } __pyx_L4:; goto __pyx_L3; } __pyx_5 = (__pyx_v_nd == 1); if (__pyx_5) { /* "/Users/rkern/svn/numpy/numpy/doc/pyrex/numpyx.pyx":48 */ __pyx_6 = (__pyx_v_dimensions[0]); for (__pyx_v_i = 0; __pyx_v_i < __pyx_6; ++__pyx_v_i) { /* "/Users/rkern/svn/numpy/numpy/doc/pyrex/numpyx.pyx":49 */ __pyx_4 = __Pyx_GetName(__pyx_m, __pyx_n_numpy); if (!__pyx_4) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 49; goto __pyx_L1;} __pyx_1 = PyObject_GetAttr(__pyx_4, __pyx_n_dtype); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 49; goto __pyx_L1;} Py_DECREF(__pyx_4); __pyx_4 = 0; __pyx_2 = __Pyx_GetName(__pyx_m, __pyx_n_numpy); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 49; goto __pyx_L1;} __pyx_3 = PyObject_GetAttr(__pyx_2, __pyx_n_object_); if (!__pyx_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 49; goto __pyx_L1;} Py_DECREF(__pyx_2); __pyx_2 = 0; __pyx_4 = PyTuple_New(1); if (!__pyx_4) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 49; goto __pyx_L1;} PyTuple_SET_ITEM(__pyx_4, 0, __pyx_3); __pyx_3 = 0; __pyx_2 = PyObject_CallObject(__pyx_1, __pyx_4); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 49; goto __pyx_L1;} Py_DECREF(__pyx_1); __pyx_1 = 0; Py_DECREF(__pyx_4); __pyx_4 = 0; if (PyObject_Cmp(__pyx_v_dtype, __pyx_2, &__pyx_5) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 49; goto __pyx_L1;} __pyx_5 = __pyx_5 == 0; Py_DECREF(__pyx_2); __pyx_2 = 0; if (__pyx_5) { /* "/Users/rkern/svn/numpy/numpy/doc/pyrex/numpyx.pyx":50 */ __pyx_v_elptr = (((void (*(*)))__pyx_v_data)[0]); /* "/Users/rkern/svn/numpy/numpy/doc/pyrex/numpyx.pyx":51 */ if (__Pyx_PrintItem(__pyx_k13p) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 51; goto __pyx_L1;} __pyx_3 = (PyObject *)__pyx_v_elptr; Py_INCREF(__pyx_3); if (__Pyx_PrintItem(__pyx_3) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 51; goto __pyx_L1;} Py_DECREF(__pyx_3); __pyx_3 = 0; if (__Pyx_PrintNewline() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 51; goto __pyx_L1;} goto __pyx_L7; } __pyx_1 = __Pyx_GetName(__pyx_m, __pyx_n_numpy); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 52; goto __pyx_L1;} __pyx_4 = PyObject_GetAttr(__pyx_1, __pyx_n_dtype); if (!__pyx_4) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 52; goto __pyx_L1;} Py_DECREF(__pyx_1); __pyx_1 = 0; __pyx_2 = __Pyx_GetName(__pyx_m, __pyx_n_numpy); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 52; goto __pyx_L1;} __pyx_3 = PyObject_GetAttr(__pyx_2, __pyx_n_float64); if (!__pyx_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 52; goto __pyx_L1;} Py_DECREF(__pyx_2); __pyx_2 = 0; __pyx_1 = PyTuple_New(1); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 52; goto __pyx_L1;} PyTuple_SET_ITEM(__pyx_1, 0, __pyx_3); __pyx_3 = 0; __pyx_2 = PyObject_CallObject(__pyx_4, __pyx_1); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 52; goto __pyx_L1;} Py_DECREF(__pyx_4); __pyx_4 = 0; Py_DECREF(__pyx_1); __pyx_1 = 0; if (PyObject_Cmp(__pyx_v_dtype, __pyx_2, &__pyx_5) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 52; goto __pyx_L1;} __pyx_5 = __pyx_5 == 0; Py_DECREF(__pyx_2); __pyx_2 = 0; if (__pyx_5) { /* "/Users/rkern/svn/numpy/numpy/doc/pyrex/numpyx.pyx":53 */ if (__Pyx_PrintItem(__pyx_k14p) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; goto __pyx_L1;} __pyx_3 = PyFloat_FromDouble((((double (*))__pyx_v_data)[0])); if (!__pyx_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; goto __pyx_L1;} if (__Pyx_PrintItem(__pyx_3) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; goto __pyx_L1;} Py_DECREF(__pyx_3); __pyx_3 = 0; if (__Pyx_PrintNewline() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; goto __pyx_L1;} goto __pyx_L7; } __pyx_L7:; /* "/Users/rkern/svn/numpy/numpy/doc/pyrex/numpyx.pyx":54 */ __pyx_v_data = (__pyx_v_data + (__pyx_v_strides[0])); } goto __pyx_L3; } /*else*/ { /* "/Users/rkern/svn/numpy/numpy/doc/pyrex/numpyx.pyx":56 */ __pyx_6 = (__pyx_v_dimensions[0]); for (__pyx_v_i = 0; __pyx_v_i < __pyx_6; ++__pyx_v_i) { /* "/Users/rkern/svn/numpy/numpy/doc/pyrex/numpyx.pyx":57 */ __pyx_4 = __pyx_f_6numpyx_print_elements(__pyx_v_data,(__pyx_v_strides + 1),(__pyx_v_dimensions + 1),(__pyx_v_nd - 1),__pyx_v_elsize,__pyx_v_dtype); if (!__pyx_4) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 57; goto __pyx_L1;} Py_DECREF(__pyx_4); __pyx_4 = 0; /* "/Users/rkern/svn/numpy/numpy/doc/pyrex/numpyx.pyx":58 */ __pyx_v_data = (__pyx_v_data + (__pyx_v_strides[0])); } } __pyx_L3:; __pyx_r = Py_None; Py_INCREF(Py_None); goto __pyx_L0; __pyx_L1:; Py_XDECREF(__pyx_1); Py_XDECREF(__pyx_2); Py_XDECREF(__pyx_3); Py_XDECREF(__pyx_4); __Pyx_AddTraceback("numpyx.print_elements"); __pyx_r = 0; __pyx_L0:; Py_DECREF(__pyx_v_dtype); return __pyx_r; } static PyObject *__pyx_n_any; static PyObject *__pyx_k15p; static PyObject *__pyx_k16p; static PyObject *__pyx_k17p; static char (__pyx_k15[]) = "arr.any() :"; static char (__pyx_k16[]) = "arr.nd :"; static char (__pyx_k17[]) = "arr.flags :"; static PyObject *__pyx_f_6numpyx_test_methods(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static char __pyx_doc_6numpyx_test_methods[] = "Test a few attribute accesses for an array.\n \n This illustrates how the pyrex-visible object is in practice a strange\n hybrid of the C PyArrayObject struct and the python object. Some\n properties (like .nd) are visible here but not in python, while others\n like flags behave very differently: in python flags appears as a separate,\n object while here we see the raw int holding the bit pattern.\n\n This makes sense when we think of how pyrex resolves arr.foo: if foo is\n listed as a field in the c_numpy.ndarray struct description, it will be\n directly accessed as a C variable without going through Python at all.\n This is why for arr.flags, we see the actual int which holds all the flags\n as bit fields. However, for any other attribute not listed in the struct,\n it simply forwards the attribute lookup to python at runtime, just like\n python would (which means that AttributeError can be raised for\n non-existent attributes, for example)."; static PyObject *__pyx_f_6numpyx_test_methods(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { PyArrayObject *__pyx_v_arr = 0; PyObject *__pyx_r; PyObject *__pyx_1 = 0; PyObject *__pyx_2 = 0; static char *__pyx_argnames[] = {"arr",0}; if (!PyArg_ParseTupleAndKeywords(__pyx_args, __pyx_kwds, "O", __pyx_argnames, &__pyx_v_arr)) return 0; Py_INCREF(__pyx_v_arr); if (!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_arr), __pyx_ptype_7c_numpy_ndarray, 1, "arr")) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 60; goto __pyx_L1;} /* "/Users/rkern/svn/numpy/numpy/doc/pyrex/numpyx.pyx":78 */ if (__Pyx_PrintItem(__pyx_k15p) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 78; goto __pyx_L1;} __pyx_1 = PyObject_GetAttr(((PyObject *)__pyx_v_arr), __pyx_n_any); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 78; goto __pyx_L1;} __pyx_2 = PyObject_CallObject(__pyx_1, 0); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 78; goto __pyx_L1;} Py_DECREF(__pyx_1); __pyx_1 = 0; if (__Pyx_PrintItem(__pyx_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 78; goto __pyx_L1;} Py_DECREF(__pyx_2); __pyx_2 = 0; if (__Pyx_PrintNewline() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 78; goto __pyx_L1;} /* "/Users/rkern/svn/numpy/numpy/doc/pyrex/numpyx.pyx":79 */ if (__Pyx_PrintItem(__pyx_k16p) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 79; goto __pyx_L1;} __pyx_1 = PyInt_FromLong(__pyx_v_arr->nd); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 79; goto __pyx_L1;} if (__Pyx_PrintItem(__pyx_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 79; goto __pyx_L1;} Py_DECREF(__pyx_1); __pyx_1 = 0; if (__Pyx_PrintNewline() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 79; goto __pyx_L1;} /* "/Users/rkern/svn/numpy/numpy/doc/pyrex/numpyx.pyx":80 */ if (__Pyx_PrintItem(__pyx_k17p) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 80; goto __pyx_L1;} __pyx_2 = PyInt_FromLong(__pyx_v_arr->flags); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 80; goto __pyx_L1;} if (__Pyx_PrintItem(__pyx_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 80; goto __pyx_L1;} Py_DECREF(__pyx_2); __pyx_2 = 0; if (__Pyx_PrintNewline() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 80; goto __pyx_L1;} __pyx_r = Py_None; Py_INCREF(Py_None); goto __pyx_L0; __pyx_L1:; Py_XDECREF(__pyx_1); Py_XDECREF(__pyx_2); __Pyx_AddTraceback("numpyx.test_methods"); __pyx_r = 0; __pyx_L0:; Py_DECREF(__pyx_v_arr); return __pyx_r; } static PyObject *__pyx_n_array; static PyObject *__pyx_n_arange; static PyObject *__pyx_n_shape; static PyObject *__pyx_n_one; static PyObject *__pyx_n_two; static PyObject *__pyx_f_6numpyx_test(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static char __pyx_doc_6numpyx_test[] = "this function is pure Python"; static PyObject *__pyx_f_6numpyx_test(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { PyObject *__pyx_v_arr1; PyObject *__pyx_v_arr2; PyObject *__pyx_v_arr3; PyObject *__pyx_v_four; PyObject *__pyx_v_arr4; PyObject *__pyx_v_arr5; PyObject *__pyx_v_arr; PyObject *__pyx_r; PyObject *__pyx_1 = 0; PyObject *__pyx_2 = 0; PyObject *__pyx_3 = 0; PyObject *__pyx_4 = 0; PyObject *__pyx_5 = 0; static char *__pyx_argnames[] = {0}; if (!PyArg_ParseTupleAndKeywords(__pyx_args, __pyx_kwds, "", __pyx_argnames)) return 0; __pyx_v_arr1 = Py_None; Py_INCREF(Py_None); __pyx_v_arr2 = Py_None; Py_INCREF(Py_None); __pyx_v_arr3 = Py_None; Py_INCREF(Py_None); __pyx_v_four = Py_None; Py_INCREF(Py_None); __pyx_v_arr4 = Py_None; Py_INCREF(Py_None); __pyx_v_arr5 = Py_None; Py_INCREF(Py_None); __pyx_v_arr = Py_None; Py_INCREF(Py_None); /* "/Users/rkern/svn/numpy/numpy/doc/pyrex/numpyx.pyx":84 */ __pyx_1 = __Pyx_GetName(__pyx_m, __pyx_n_numpy); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 84; goto __pyx_L1;} __pyx_2 = PyObject_GetAttr(__pyx_1, __pyx_n_array); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 84; goto __pyx_L1;} Py_DECREF(__pyx_1); __pyx_1 = 0; __pyx_1 = PyFloat_FromDouble((-1e-30)); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 84; goto __pyx_L1;} __pyx_3 = PyTuple_New(1); if (!__pyx_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 84; goto __pyx_L1;} PyTuple_SET_ITEM(__pyx_3, 0, __pyx_1); __pyx_1 = 0; __pyx_1 = PyDict_New(); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 84; goto __pyx_L1;} __pyx_4 = __Pyx_GetName(__pyx_m, __pyx_n_numpy); if (!__pyx_4) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 84; goto __pyx_L1;} __pyx_5 = PyObject_GetAttr(__pyx_4, __pyx_n_float64); if (!__pyx_5) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 84; goto __pyx_L1;} Py_DECREF(__pyx_4); __pyx_4 = 0; if (PyDict_SetItem(__pyx_1, __pyx_n_dtype, __pyx_5) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 84; goto __pyx_L1;} Py_DECREF(__pyx_5); __pyx_5 = 0; __pyx_4 = PyEval_CallObjectWithKeywords(__pyx_2, __pyx_3, __pyx_1); if (!__pyx_4) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 84; goto __pyx_L1;} Py_DECREF(__pyx_2); __pyx_2 = 0; Py_DECREF(__pyx_3); __pyx_3 = 0; Py_DECREF(__pyx_1); __pyx_1 = 0; Py_DECREF(__pyx_v_arr1); __pyx_v_arr1 = __pyx_4; __pyx_4 = 0; /* "/Users/rkern/svn/numpy/numpy/doc/pyrex/numpyx.pyx":85 */ __pyx_5 = __Pyx_GetName(__pyx_m, __pyx_n_numpy); if (!__pyx_5) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 85; goto __pyx_L1;} __pyx_2 = PyObject_GetAttr(__pyx_5, __pyx_n_array); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 85; goto __pyx_L1;} Py_DECREF(__pyx_5); __pyx_5 = 0; __pyx_3 = PyFloat_FromDouble(1.0); if (!__pyx_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 85; goto __pyx_L1;} __pyx_1 = PyFloat_FromDouble(2.0); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 85; goto __pyx_L1;} __pyx_4 = PyFloat_FromDouble(3.0); if (!__pyx_4) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 85; goto __pyx_L1;} __pyx_5 = PyList_New(3); if (!__pyx_5) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 85; goto __pyx_L1;} PyList_SET_ITEM(__pyx_5, 0, __pyx_3); PyList_SET_ITEM(__pyx_5, 1, __pyx_1); PyList_SET_ITEM(__pyx_5, 2, __pyx_4); __pyx_3 = 0; __pyx_1 = 0; __pyx_4 = 0; __pyx_3 = PyTuple_New(1); if (!__pyx_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 85; goto __pyx_L1;} PyTuple_SET_ITEM(__pyx_3, 0, __pyx_5); __pyx_5 = 0; __pyx_1 = PyDict_New(); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 85; goto __pyx_L1;} __pyx_4 = __Pyx_GetName(__pyx_m, __pyx_n_numpy); if (!__pyx_4) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 85; goto __pyx_L1;} __pyx_5 = PyObject_GetAttr(__pyx_4, __pyx_n_float64); if (!__pyx_5) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 85; goto __pyx_L1;} Py_DECREF(__pyx_4); __pyx_4 = 0; if (PyDict_SetItem(__pyx_1, __pyx_n_dtype, __pyx_5) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 85; goto __pyx_L1;} Py_DECREF(__pyx_5); __pyx_5 = 0; __pyx_4 = PyEval_CallObjectWithKeywords(__pyx_2, __pyx_3, __pyx_1); if (!__pyx_4) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 85; goto __pyx_L1;} Py_DECREF(__pyx_2); __pyx_2 = 0; Py_DECREF(__pyx_3); __pyx_3 = 0; Py_DECREF(__pyx_1); __pyx_1 = 0; Py_DECREF(__pyx_v_arr2); __pyx_v_arr2 = __pyx_4; __pyx_4 = 0; /* "/Users/rkern/svn/numpy/numpy/doc/pyrex/numpyx.pyx":87 */ __pyx_5 = __Pyx_GetName(__pyx_m, __pyx_n_numpy); if (!__pyx_5) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 87; goto __pyx_L1;} __pyx_2 = PyObject_GetAttr(__pyx_5, __pyx_n_arange); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 87; goto __pyx_L1;} Py_DECREF(__pyx_5); __pyx_5 = 0; __pyx_3 = PyInt_FromLong(9); if (!__pyx_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 87; goto __pyx_L1;} __pyx_1 = PyTuple_New(1); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 87; goto __pyx_L1;} PyTuple_SET_ITEM(__pyx_1, 0, __pyx_3); __pyx_3 = 0; __pyx_4 = PyDict_New(); if (!__pyx_4) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 87; goto __pyx_L1;} __pyx_5 = __Pyx_GetName(__pyx_m, __pyx_n_numpy); if (!__pyx_5) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 87; goto __pyx_L1;} __pyx_3 = PyObject_GetAttr(__pyx_5, __pyx_n_float64); if (!__pyx_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 87; goto __pyx_L1;} Py_DECREF(__pyx_5); __pyx_5 = 0; if (PyDict_SetItem(__pyx_4, __pyx_n_dtype, __pyx_3) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 87; goto __pyx_L1;} Py_DECREF(__pyx_3); __pyx_3 = 0; __pyx_5 = PyEval_CallObjectWithKeywords(__pyx_2, __pyx_1, __pyx_4); if (!__pyx_5) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 87; goto __pyx_L1;} Py_DECREF(__pyx_2); __pyx_2 = 0; Py_DECREF(__pyx_1); __pyx_1 = 0; Py_DECREF(__pyx_4); __pyx_4 = 0; Py_DECREF(__pyx_v_arr3); __pyx_v_arr3 = __pyx_5; __pyx_5 = 0; /* "/Users/rkern/svn/numpy/numpy/doc/pyrex/numpyx.pyx":88 */ __pyx_3 = PyInt_FromLong(3); if (!__pyx_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 88; goto __pyx_L1;} __pyx_2 = PyInt_FromLong(3); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 88; goto __pyx_L1;} __pyx_1 = PyTuple_New(2); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 88; goto __pyx_L1;} PyTuple_SET_ITEM(__pyx_1, 0, __pyx_3); PyTuple_SET_ITEM(__pyx_1, 1, __pyx_2); __pyx_3 = 0; __pyx_2 = 0; if (PyObject_SetAttr(__pyx_v_arr3, __pyx_n_shape, __pyx_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 88; goto __pyx_L1;} Py_DECREF(__pyx_1); __pyx_1 = 0; /* "/Users/rkern/svn/numpy/numpy/doc/pyrex/numpyx.pyx":90 */ __pyx_4 = PyInt_FromLong(4); if (!__pyx_4) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 90; goto __pyx_L1;} Py_DECREF(__pyx_v_four); __pyx_v_four = __pyx_4; __pyx_4 = 0; /* "/Users/rkern/svn/numpy/numpy/doc/pyrex/numpyx.pyx":91 */ __pyx_5 = __Pyx_GetName(__pyx_m, __pyx_n_numpy); if (!__pyx_5) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 91; goto __pyx_L1;} __pyx_3 = PyObject_GetAttr(__pyx_5, __pyx_n_array); if (!__pyx_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 91; goto __pyx_L1;} Py_DECREF(__pyx_5); __pyx_5 = 0; __pyx_2 = PyInt_FromLong(3); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 91; goto __pyx_L1;} __pyx_1 = PyList_New(4); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 91; goto __pyx_L1;} Py_INCREF(__pyx_n_one); PyList_SET_ITEM(__pyx_1, 0, __pyx_n_one); Py_INCREF(__pyx_n_two); PyList_SET_ITEM(__pyx_1, 1, __pyx_n_two); PyList_SET_ITEM(__pyx_1, 2, __pyx_2); Py_INCREF(__pyx_v_four); PyList_SET_ITEM(__pyx_1, 3, __pyx_v_four); __pyx_2 = 0; __pyx_4 = PyTuple_New(1); if (!__pyx_4) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 91; goto __pyx_L1;} PyTuple_SET_ITEM(__pyx_4, 0, __pyx_1); __pyx_1 = 0; __pyx_5 = PyDict_New(); if (!__pyx_5) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 91; goto __pyx_L1;} __pyx_2 = __Pyx_GetName(__pyx_m, __pyx_n_numpy); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 91; goto __pyx_L1;} __pyx_1 = PyObject_GetAttr(__pyx_2, __pyx_n_object_); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 91; goto __pyx_L1;} Py_DECREF(__pyx_2); __pyx_2 = 0; if (PyDict_SetItem(__pyx_5, __pyx_n_dtype, __pyx_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 91; goto __pyx_L1;} Py_DECREF(__pyx_1); __pyx_1 = 0; __pyx_2 = PyEval_CallObjectWithKeywords(__pyx_3, __pyx_4, __pyx_5); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 91; goto __pyx_L1;} Py_DECREF(__pyx_3); __pyx_3 = 0; Py_DECREF(__pyx_4); __pyx_4 = 0; Py_DECREF(__pyx_5); __pyx_5 = 0; Py_DECREF(__pyx_v_arr4); __pyx_v_arr4 = __pyx_2; __pyx_2 = 0; /* "/Users/rkern/svn/numpy/numpy/doc/pyrex/numpyx.pyx":93 */ __pyx_1 = __Pyx_GetName(__pyx_m, __pyx_n_numpy); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 93; goto __pyx_L1;} __pyx_3 = PyObject_GetAttr(__pyx_1, __pyx_n_array); if (!__pyx_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 93; goto __pyx_L1;} Py_DECREF(__pyx_1); __pyx_1 = 0; __pyx_4 = PyInt_FromLong(1); if (!__pyx_4) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 93; goto __pyx_L1;} __pyx_5 = PyInt_FromLong(2); if (!__pyx_5) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 93; goto __pyx_L1;} __pyx_2 = PyInt_FromLong(3); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 93; goto __pyx_L1;} __pyx_1 = PyList_New(3); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 93; goto __pyx_L1;} PyList_SET_ITEM(__pyx_1, 0, __pyx_4); PyList_SET_ITEM(__pyx_1, 1, __pyx_5); PyList_SET_ITEM(__pyx_1, 2, __pyx_2); __pyx_4 = 0; __pyx_5 = 0; __pyx_2 = 0; __pyx_4 = PyTuple_New(1); if (!__pyx_4) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 93; goto __pyx_L1;} PyTuple_SET_ITEM(__pyx_4, 0, __pyx_1); __pyx_1 = 0; __pyx_5 = PyObject_CallObject(__pyx_3, __pyx_4); if (!__pyx_5) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 93; goto __pyx_L1;} Py_DECREF(__pyx_3); __pyx_3 = 0; Py_DECREF(__pyx_4); __pyx_4 = 0; Py_DECREF(__pyx_v_arr5); __pyx_v_arr5 = __pyx_5; __pyx_5 = 0; /* "/Users/rkern/svn/numpy/numpy/doc/pyrex/numpyx.pyx":95 */ __pyx_2 = PyList_New(5); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 95; goto __pyx_L1;} Py_INCREF(__pyx_v_arr1); PyList_SET_ITEM(__pyx_2, 0, __pyx_v_arr1); Py_INCREF(__pyx_v_arr2); PyList_SET_ITEM(__pyx_2, 1, __pyx_v_arr2); Py_INCREF(__pyx_v_arr3); PyList_SET_ITEM(__pyx_2, 2, __pyx_v_arr3); Py_INCREF(__pyx_v_arr4); PyList_SET_ITEM(__pyx_2, 3, __pyx_v_arr4); Py_INCREF(__pyx_v_arr5); PyList_SET_ITEM(__pyx_2, 4, __pyx_v_arr5); __pyx_1 = PyObject_GetIter(__pyx_2); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 95; goto __pyx_L1;} Py_DECREF(__pyx_2); __pyx_2 = 0; for (;;) { __pyx_3 = PyIter_Next(__pyx_1); if (!__pyx_3) { if (PyErr_Occurred()) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 95; goto __pyx_L1;} break; } Py_DECREF(__pyx_v_arr); __pyx_v_arr = __pyx_3; __pyx_3 = 0; /* "/Users/rkern/svn/numpy/numpy/doc/pyrex/numpyx.pyx":96 */ __pyx_4 = __Pyx_GetName(__pyx_m, __pyx_n_print_array_info); if (!__pyx_4) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 96; goto __pyx_L1;} __pyx_5 = PyTuple_New(1); if (!__pyx_5) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 96; goto __pyx_L1;} Py_INCREF(__pyx_v_arr); PyTuple_SET_ITEM(__pyx_5, 0, __pyx_v_arr); __pyx_2 = PyObject_CallObject(__pyx_4, __pyx_5); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 96; goto __pyx_L1;} Py_DECREF(__pyx_4); __pyx_4 = 0; Py_DECREF(__pyx_5); __pyx_5 = 0; Py_DECREF(__pyx_2); __pyx_2 = 0; } Py_DECREF(__pyx_1); __pyx_1 = 0; __pyx_r = Py_None; Py_INCREF(Py_None); goto __pyx_L0; __pyx_L1:; Py_XDECREF(__pyx_1); Py_XDECREF(__pyx_2); Py_XDECREF(__pyx_3); Py_XDECREF(__pyx_4); Py_XDECREF(__pyx_5); __Pyx_AddTraceback("numpyx.test"); __pyx_r = 0; __pyx_L0:; Py_DECREF(__pyx_v_arr1); Py_DECREF(__pyx_v_arr2); Py_DECREF(__pyx_v_arr3); Py_DECREF(__pyx_v_four); Py_DECREF(__pyx_v_arr4); Py_DECREF(__pyx_v_arr5); Py_DECREF(__pyx_v_arr); return __pyx_r; } static __Pyx_InternTabEntry __pyx_intern_tab[] = { {&__pyx_n_any, "any"}, {&__pyx_n_arange, "arange"}, {&__pyx_n_array, "array"}, {&__pyx_n_c_numpy, "c_numpy"}, {&__pyx_n_c_python, "c_python"}, {&__pyx_n_dtype, "dtype"}, {&__pyx_n_float64, "float64"}, {&__pyx_n_name, "name"}, {&__pyx_n_numpy, "numpy"}, {&__pyx_n_object_, "object_"}, {&__pyx_n_one, "one"}, {&__pyx_n_print_array_info, "print_array_info"}, {&__pyx_n_shape, "shape"}, {&__pyx_n_test, "test"}, {&__pyx_n_test_methods, "test_methods"}, {&__pyx_n_two, "two"}, {0, 0} }; static __Pyx_StringTabEntry __pyx_string_tab[] = { {&__pyx_k2p, __pyx_k2, sizeof(__pyx_k2)}, {&__pyx_k3p, __pyx_k3, sizeof(__pyx_k3)}, {&__pyx_k4p, __pyx_k4, sizeof(__pyx_k4)}, {&__pyx_k5p, __pyx_k5, sizeof(__pyx_k5)}, {&__pyx_k6p, __pyx_k6, sizeof(__pyx_k6)}, {&__pyx_k7p, __pyx_k7, sizeof(__pyx_k7)}, {&__pyx_k8p, __pyx_k8, sizeof(__pyx_k8)}, {&__pyx_k9p, __pyx_k9, sizeof(__pyx_k9)}, {&__pyx_k10p, __pyx_k10, sizeof(__pyx_k10)}, {&__pyx_k11p, __pyx_k11, sizeof(__pyx_k11)}, {&__pyx_k12p, __pyx_k12, sizeof(__pyx_k12)}, {&__pyx_k13p, __pyx_k13, sizeof(__pyx_k13)}, {&__pyx_k14p, __pyx_k14, sizeof(__pyx_k14)}, {&__pyx_k15p, __pyx_k15, sizeof(__pyx_k15)}, {&__pyx_k16p, __pyx_k16, sizeof(__pyx_k16)}, {&__pyx_k17p, __pyx_k17, sizeof(__pyx_k17)}, {0, 0, 0} }; static struct PyMethodDef __pyx_methods[] = { {"print_array_info", (PyCFunction)__pyx_f_6numpyx_print_array_info, METH_VARARGS|METH_KEYWORDS, 0}, {"test_methods", (PyCFunction)__pyx_f_6numpyx_test_methods, METH_VARARGS|METH_KEYWORDS, __pyx_doc_6numpyx_test_methods}, {"test", (PyCFunction)__pyx_f_6numpyx_test, METH_VARARGS|METH_KEYWORDS, __pyx_doc_6numpyx_test}, {0, 0, 0, 0} }; static void __pyx_init_filenames(void); /*proto*/ PyMODINIT_FUNC initnumpyx(void); /*proto*/ PyMODINIT_FUNC initnumpyx(void) { PyObject *__pyx_1 = 0; __pyx_init_filenames(); __pyx_m = Py_InitModule4("numpyx", __pyx_methods, 0, 0, PYTHON_API_VERSION); if (!__pyx_m) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3; goto __pyx_L1;}; __pyx_b = PyImport_AddModule("__builtin__"); if (!__pyx_b) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3; goto __pyx_L1;}; if (PyObject_SetAttrString(__pyx_m, "__builtins__", __pyx_b) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3; goto __pyx_L1;}; if (__Pyx_InternStrings(__pyx_intern_tab) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3; goto __pyx_L1;}; if (__Pyx_InitStrings(__pyx_string_tab) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3; goto __pyx_L1;}; __pyx_ptype_7c_numpy_dtype = __Pyx_ImportType("numpy", "dtype", sizeof(PyArray_Descr)); if (!__pyx_ptype_7c_numpy_dtype) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 76; goto __pyx_L1;} __pyx_ptype_7c_numpy_ndarray = __Pyx_ImportType("numpy", "ndarray", sizeof(PyArrayObject)); if (!__pyx_ptype_7c_numpy_ndarray) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 81; goto __pyx_L1;} __pyx_ptype_7c_numpy_flatiter = __Pyx_ImportType("numpy", "flatiter", sizeof(PyArrayIterObject)); if (!__pyx_ptype_7c_numpy_flatiter) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 90; goto __pyx_L1;} __pyx_ptype_7c_numpy_broadcast = __Pyx_ImportType("numpy", "broadcast", sizeof(PyArrayMultiIterObject)); if (!__pyx_ptype_7c_numpy_broadcast) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 96; goto __pyx_L1;} /* "/Users/rkern/svn/numpy/numpy/doc/pyrex/numpyx.pyx":5 */ __pyx_1 = __Pyx_Import(__pyx_n_numpy, 0); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 5; goto __pyx_L1;} if (PyObject_SetAttr(__pyx_m, __pyx_n_numpy, __pyx_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 5; goto __pyx_L1;} Py_DECREF(__pyx_1); __pyx_1 = 0; /* "/Users/rkern/svn/numpy/numpy/doc/pyrex/numpyx.pyx":8 */ import_array(); /* "/Users/rkern/svn/numpy/numpy/doc/pyrex/numpyx.pyx":82 */ return; __pyx_L1:; Py_XDECREF(__pyx_1); __Pyx_AddTraceback("numpyx"); } static char *__pyx_filenames[] = { "numpyx.pyx", "c_numpy.pxd", }; /* Runtime support code */ static void __pyx_init_filenames(void) { __pyx_f = __pyx_filenames; } static int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed, char *name) { if (!type) { PyErr_Format(PyExc_SystemError, "Missing type object"); return 0; } if ((none_allowed && obj == Py_None) || PyObject_TypeCheck(obj, type)) return 1; PyErr_Format(PyExc_TypeError, "Argument '%s' has incorrect type (expected %s, got %s)", name, type->tp_name, obj->ob_type->tp_name); return 0; } static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list) { PyObject *__import__ = 0; PyObject *empty_list = 0; PyObject *module = 0; PyObject *global_dict = 0; PyObject *empty_dict = 0; PyObject *list; __import__ = PyObject_GetAttrString(__pyx_b, "__import__"); if (!__import__) goto bad; 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; module = PyObject_CallFunction(__import__, "OOOO", name, global_dict, empty_dict, list); bad: Py_XDECREF(empty_list); Py_XDECREF(__import__); Py_XDECREF(empty_dict); return module; } static PyObject *__Pyx_GetStdout(void) { PyObject *f = PySys_GetObject("stdout"); if (!f) { PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout"); } return f; } static int __Pyx_PrintItem(PyObject *v) { PyObject *f; if (!(f = __Pyx_GetStdout())) return -1; if (PyFile_SoftSpace(f, 1)) { if (PyFile_WriteString(" ", f) < 0) return -1; } if (PyFile_WriteObject(v, f, Py_PRINT_RAW) < 0) return -1; if (PyString_Check(v)) { char *s = PyString_AsString(v); int len = PyString_Size(v); if (len > 0 && isspace(Py_CHARMASK(s[len-1])) && s[len-1] != ' ') PyFile_SoftSpace(f, 0); } return 0; } static int __Pyx_PrintNewline(void) { PyObject *f; if (!(f = __Pyx_GetStdout())) return -1; if (PyFile_WriteString("\n", f) < 0) return -1; PyFile_SoftSpace(f, 0); return 0; } static PyObject *__Pyx_GetName(PyObject *dict, PyObject *name) { PyObject *result; result = PyObject_GetAttr(dict, name); if (!result) PyErr_SetObject(PyExc_NameError, name); return result; } static int __Pyx_InternStrings(__Pyx_InternTabEntry *t) { while (t->p) { *t->p = PyString_InternFromString(t->s); if (!*t->p) return -1; ++t; } return 0; } static int __Pyx_InitStrings(__Pyx_StringTabEntry *t) { while (t->p) { *t->p = PyString_FromStringAndSize(t->s, t->n - 1); if (!*t->p) return -1; ++t; } return 0; } static PyTypeObject *__Pyx_ImportType(char *module_name, char *class_name, long size) { PyObject *py_module_name = 0; PyObject *py_class_name = 0; PyObject *py_name_list = 0; PyObject *py_module = 0; PyObject *result = 0; py_module_name = PyString_FromString(module_name); if (!py_module_name) goto bad; py_class_name = PyString_FromString(class_name); if (!py_class_name) goto bad; py_name_list = PyList_New(1); if (!py_name_list) goto bad; Py_INCREF(py_class_name); if (PyList_SetItem(py_name_list, 0, py_class_name) < 0) goto bad; py_module = __Pyx_Import(py_module_name, py_name_list); if (!py_module) goto bad; result = PyObject_GetAttr(py_module, py_class_name); 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; } if (((PyTypeObject *)result)->tp_basicsize != size) { PyErr_Format(PyExc_ValueError, "%s.%s does not appear to be the correct type object", module_name, class_name); goto bad; } goto done; bad: Py_XDECREF(result); result = 0; done: Py_XDECREF(py_module_name); Py_XDECREF(py_class_name); Py_XDECREF(py_name_list); return (PyTypeObject *)result; } #include "compile.h" #include "frameobject.h" #include "traceback.h" static void __Pyx_AddTraceback(char *funcname) { PyObject *py_srcfile = 0; PyObject *py_funcname = 0; PyObject *py_globals = 0; PyObject *empty_tuple = 0; PyObject *empty_string = 0; PyCodeObject *py_code = 0; PyFrameObject *py_frame = 0; py_srcfile = PyString_FromString(__pyx_filename); if (!py_srcfile) goto bad; py_funcname = PyString_FromString(funcname); if (!py_funcname) goto bad; py_globals = PyModule_GetDict(__pyx_m); if (!py_globals) goto bad; empty_tuple = PyTuple_New(0); if (!empty_tuple) goto bad; empty_string = PyString_FromString(""); if (!empty_string) goto bad; py_code = PyCode_New( 0, /*int argcount,*/ 0, /*int nlocals,*/ 0, /*int stacksize,*/ 0, /*int flags,*/ empty_string, /*PyObject *code,*/ empty_tuple, /*PyObject *consts,*/ empty_tuple, /*PyObject *names,*/ empty_tuple, /*PyObject *varnames,*/ empty_tuple, /*PyObject *freevars,*/ empty_tuple, /*PyObject *cellvars,*/ py_srcfile, /*PyObject *filename,*/ py_funcname, /*PyObject *name,*/ __pyx_lineno, /*int firstlineno,*/ empty_string /*PyObject *lnotab*/ ); if (!py_code) 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 = __pyx_lineno; PyTraceBack_Here(py_frame); bad: Py_XDECREF(py_srcfile); Py_XDECREF(py_funcname); Py_XDECREF(empty_tuple); Py_XDECREF(empty_string); Py_XDECREF(py_code); Py_XDECREF(py_frame); } numpy-1.8.2/doc/pyrex/setup.py0000664000175100017510000000257312370216243017461 0ustar vagrantvagrant00000000000000#!/usr/bin/env python """ WARNING: this code is deprecated and slated for removal soon. See the doc/cython directory for the replacement, which uses Cython (the actively maintained version of Pyrex). Install file for example on how to use Pyrex with Numpy. For more details, see: http://www.scipy.org/Cookbook/Pyrex_and_NumPy http://www.scipy.org/Cookbook/ArrayStruct_and_Pyrex """ from __future__ import division, print_function from distutils.core import setup from distutils.extension import Extension # Make this usable by people who don't have pyrex installed (I've committed # the generated C sources to SVN). try: from Pyrex.Distutils import build_ext has_pyrex = True except ImportError: has_pyrex = False import numpy # Define a pyrex-based extension module, using the generated sources if pyrex # is not available. if has_pyrex: pyx_sources = ['numpyx.pyx'] cmdclass = {'build_ext': build_ext} else: pyx_sources = ['numpyx.c'] cmdclass = {} pyx_ext = Extension('numpyx', pyx_sources, include_dirs = [numpy.get_include()]) # Call the routine which does the real work setup(name = 'numpyx', description = 'Small example on using Pyrex to write a Numpy extension', url = 'http://www.scipy.org/Cookbook/Pyrex_and_NumPy', ext_modules = [pyx_ext], cmdclass = cmdclass, ) numpy-1.8.2/doc/pyrex/run_test.py0000775000175100017510000000016712370216243020164 0ustar vagrantvagrant00000000000000#!/usr/bin/env python from __future__ import division, absolute_import, print_function from numpyx import test test() numpy-1.8.2/doc/pyrex/numpyx.pyx0000664000175100017510000000730112370216243020043 0ustar vagrantvagrant00000000000000# -*- Mode: Python -*- Not really, but close enough """WARNING: this code is deprecated and slated for removal soon. See the doc/cython directory for the replacement, which uses Cython (the actively maintained version of Pyrex). """ cimport c_python cimport c_numpy import numpy # Numpy must be initialized c_numpy.import_array() def print_array_info(c_numpy.ndarray arr): cdef int i print '-='*10 print 'printing array info for ndarray at 0x%0lx'%(arr,) print 'print number of dimensions:',arr.nd print 'address of strides: 0x%0lx'%(arr.strides,) print 'strides:' for i from 0<=iarr.strides[i] print 'memory dump:' print_elements( arr.data, arr.strides, arr.dimensions, arr.nd, sizeof(double), arr.dtype ) print '-='*10 print cdef print_elements(char *data, c_python.Py_intptr_t* strides, c_python.Py_intptr_t* dimensions, int nd, int elsize, object dtype): cdef c_python.Py_intptr_t i,j cdef void* elptr if dtype not in [numpy.dtype(numpy.object_), numpy.dtype(numpy.float64)]: print ' print_elements() not (yet) implemented for dtype %s'%dtype.name return if nd ==0: if dtype==numpy.dtype(numpy.object_): elptr = (data)[0] #[0] dereferences pointer in Pyrex print ' ',elptr elif dtype==numpy.dtype(numpy.float64): print ' ',(data)[0] elif nd == 1: for i from 0<=idata)[0] print ' ',elptr elif dtype==numpy.dtype(numpy.float64): print ' ',(data)[0] data = data + strides[0] else: for i from 0<=i`__ theme for `Scipy `__. Theme options ------------- The theme takes the followin options in the `html_options` configuration variable: - ``edit_link`` ``True`` or ``False``. Determines if an "edit this page" link is displayed in the left sidebar. - ``rootlinks`` List of tuples ``(url, link_name)`` to show in the beginning of the breadcrumb list on the top left. You can override it by defining an `edit_link` block in ``searchbox.html``. - ``sidebar`` One of ``"left"``, ``"right"``, ``"none"``. Defines where the sidebar should appear. - ``scipy_org_logo`` ``True`` or ``False``. Whether to plaster the scipy.org logo on top. You can use your own logo by overriding the :attr:`layout.html:header` block. - ``navigation_links`` ``True`` or ``False``. Whether to display "next", "prev", "index", etc. links. The following blocks are defined: - ``layout.html:header`` Block at the top of the page, for logo etc. - ``searchbox.html:edit_link`` Edit link HTML code to paste in the left sidebar, if `edit_link` is enabled. numpy-1.8.2/doc/scipy-sphinx-theme/.git0000664000175100017510000000010612370216243021110 0ustar vagrantvagrant00000000000000gitdir: /home/vagrant/repos/numpy/.git/modules/doc/scipy-sphinx-theme numpy-1.8.2/doc/scipy-sphinx-theme/.gitignore0000664000175100017510000000011212370216245022313 0ustar vagrantvagrant00000000000000*.pyc *.swp *.pyd *.so *.o *.lo *.la *~ *.bak *.swp .\#* .deps .libs .tox numpy-1.8.2/doc/scipy-sphinx-theme/test_autodoc.rst0000664000175100017510000000012212370216246023554 0ustar vagrantvagrant00000000000000scipy.odr.Model =============== .. currentmodule:: scipy.odr .. autoclass:: ODR numpy-1.8.2/doc/scipy-sphinx-theme/_static/0000775000175100017510000000000012371375427021770 5ustar vagrantvagrant00000000000000numpy-1.8.2/doc/scipy-sphinx-theme/_static/scipyshiny_small.png0000664000175100017510000004505712370216245026072 0ustar vagrantvagrant00000000000000‰PNG  IHDRÈ» îÑñsRGB®ÎébKGDÿÿÿ ½§“ pHYs  šœtIMEØ 9«!¬‚ IDATxÚí}w˜$U¹þ{ª:wOOÎ3»3³³9/`,Y‚Œ(W¹¨øS¯ŠâE¯¢&¸Š  JÎ, ,lÎyggÓìä<Ó9T8¿?ºz¦ººªºzfzvú{žzº+W:ïùòw€,e)KYÊR–²”¥,e)KYÊR–²”¥,e)KYÊR–²”¥,e)KYÊR–²”¥,e)KYÊR–²”¥,e)KYÊR–&‘ld€*¢¬¤Ð^\Xà>v²ÙJ©XT^Z\Éq|a ² z|&µÓv›XXuØl^¯ßßÑÝ;Ð>Ö´ˆÛåô¿¿u—OlÛM³›ÈYE•‹.sŠ”Ö{}þ™‚ ÌdYv:ÇñõÏX̦Žã"¥#jgB¬KTÅ>JiWŽËÑ Göä †ÂûæÌ¨?µaË®.´ïÉ~ˆ,@Î<Õw5Ãq|iÿ g• ˆ+zn”ãëš+Š”Ïga¡ $àtØ;EQÜh2±[§ÖNÚÌqüᢂír:Q[]þkÿÌäCNÎú‹Ã‘è=¢(^J)MÒœ-3¦M©ÅÜ™ÓPX§T<>@Õð‘H ÇOaßÁx}þ„}6«å Ëé¸Ûj1½Ð¶{˜ȇŒJç]\Ö7à¹GÅ)¥Vå~›Õй³¦cöŒ©p:ì:-q¶7M¹™ãyi<]û&pBˆh·Y7æå~»º¢dßæW§Y€œõzÆ +Ï‹·D8îg¢(*÷[­VÌž9ógÏ„Ýfý4‘ñ>‰F±ÿ`ön@$•+óQ§ÃþÛåøŸ¶Ýodr¶‚cÚªÙ¡pø!žV ½›$&±,‹Së°pÞl¸Î µ9óžŽþÚ^Ûwíʼn¦fP™2o1›O¸]Îoæ¹,¯ß¶–fr–PތՖp„»=Êqw‹¢èRêå¥%8wÉ"È^˜d äL`c´ ¡Š5ŠÖöNlÙ¾ ƒï.Cáí6ë?ªÊŠ¿Ý¸é¥Á,@&>ר G¢áxþBå>‡ÝŽ%‹ ~JÌ¡GFßTµÕèX°’Äó8ŽÇ®=ûq¤ñAs““N‡í–®¶÷Ñw, G%³‰ÅáºFÄ? ¢X¢|¥šÉÕX¶xœ‡Á·'™o22¢>š1cèX§´wvaóÖíðú|rÝ$dµ˜f53¿lØÈg2A¨xî…?xÇñߢ”šå¯aµZ±lÉ"ÔNž¬BFÓ dbµ"-HhZ§†#lÙ¶§›[åS‹ÙüRQ~î—Ú÷¼Ù—È&GýòRž‹rÜåÊÇ/).ÆŠó–!'''Í·'cÛld¼1RÖCÓ>RGŽ6bï¾àùa¦ab™#v›õs¾Æöer¦À1eÅìÇý[ÄÙòW „`æŒi˜7w.L,«ïÓ cÑ$d [Ž` LOñÁ|ô(£Æ¸KGW6mÞŠp8$¹ú­ó¡›^ÏdÜ9ÇŠóCáèÓ”Òù£›L&,Yrj´Dª¡7%£l£ Èt“Ò4¡£à44åa^¯7mÁàààÐ9„°Íbþ¦ÛÎ>Üu胳Þ<ñ£ðÜ•ÄQ=ÿúP8ú,¥È‹uÀX't:X½zÊËÊûž±…ÈþK U.*Ǩ—p ;Wõ<’úü1Ytî7Ðô®IJir%›x]‹ÅŠI“ªÑ?0€@ ÿ.&A?ÆS˜Ý%ðžšH¦¨°žØ *o G¸¿RŠ„ô¼ü<¬Zµ nw®6T?¶¬s íKÕ¹û©Æöq_d`¡:Ï«u^àUÞ1aQÃ2¨¬ª„ßç‡×ë’¶Q<ŒÉ-ÚòÞF û¬ÉıòëˆÉ]ò5A¯ K/.)Á²óÎ…ÕbÕˆ±×6dÑJe S¿ClV3j*ŠPYR€²Â\å»afØm@(Âãô úÐÑ;ˆŽžA4µ÷"‰@G`‰2lÕ¢:«4{ ¯‹‚€½{÷âÔÉ“ '˜XöA*D¿-´íæ²CÎarÞ&ˆô÷”JÕB¤'-¯¨Äâ%K¥pôTÖ$b앉^SÃà°˜M˜RU‚%³k1§¾µÅ`ÙôRoEJqº½‡N´aÇ¡“hlîB$ʉj§ièjÊ95tQq`ß^œ/îøÝ hëñ¤0ÍRû¨†IWÇZ¦c‡vmw°_¾=L¨xmݱ9 !ÖQÀZÊf>åøOÈÙ“‹Ù‹WHŽ@-ó«Žò=i_Çå°â¡;¯GýÅ*_0‚÷öœÀÚíGq´¹Áˆ1²ÃfÆŒêb\¾l:.XX—Ý:¢ûkéÁm¿y^RÜ©¾2­éOQÆ€¥‹j(ó²ë„‚~ܱ<•ï<ĈÜ*±m÷„«˜r&D,b­^ô¥(ÇßëÑ’Þa6cêÜ%0Û©Å'Cúƒ½CEY' ƒß|)Ϩ0c~úØz¬Ûuí½~DyÑpða”ÑÞçÃûû›ðòÆ#G9L«*JÛ Y˜ëDy¡ïî= QŒIUÚN-XW<£ÉbUÒv¢¸Nlk¶Àlµb ·K>0•€°"òo" i€8¦,¯òô) 8†F} º~6r ËÔuªòaÕ¶%E±Ê­V©À;÷ú æâ —.JËZE)ÅÚíøZ‹œF(ÊÇž [O޾ EyìjlÇÛQèv`JEAZÏTWQ€_Ou©XêÔ¢ž@u¬XÐHHÒOu›ÓpÀ‡pÐ/É9ÄæÞ oû©,@ò'Í2‡‰ýaAÉE"wA *êfipÐêà©Ì»Dña•#iâùÕ¥yøù—/‡Íb¼‚{ ÅÏþñ~m|á¨FÇOgI|V˜Ã»{›ÐÙïÃÒU†=÷„,œZ‰mGZÐ5Lm¢D=@S™'ÀÓ1˸ŒÓîˆb¼R a@˜¥°ç?Ž@wô£Âϸ6Âñw!–'+‰VÔÎ^ÖdVí‰öˆ¯åÿPã*Dïz±u0wßt¦O*1üBí}>ü×^ÇÆƒ-uýúÜ"Õ±"¥hhéÃŽ£mX=o2Vc6›X,ž^‰W¶4 ‰ú¦Yª‘ fÄÜKu,Œç3¬¬Ùo_—¤.(kè~Ô€å·rñJ¸+~ wwy+|ѳ yõKóBóœH‘?¤Låµ3áÌ+LÙ©žOÍÄKÔíójÀ"D5±èÜYÕ¸ýºå†ß§­×‹¯>ð [’Àf é%Fu°­¡.¬3 ’\§ “JòðÖ®“”YMÜ¢)D/šŠ£Põ$5“°Í‘ƒ Ïƒh8(7²,„³äøÚ»S¾œ»ò'¾à³©¯ýù³ òkÿ;Ê‹ÃV+ÂÀáÎGiÍL`(»hȶ:\ƒ}P£ØFƒŸé”«†â „qÛï^DZ¶)»dŒ)üݾ“]¸lñX Š[µåùð£Ø{¢31›0刯‘©Hõ|(Šï¦MØlÎ\ ö´›‡ ±‚0e}Ÿ6©\’ àA€Ä Ÿý/|íÏF€WýyS¡¶x8 aTL]Öj×P¦µi­Jô9ªW9¶íÜ™UøÊUK )Á¼ âû¬Ç–†vÙ5™Ô:!0h2Wlï  ÏÄš“ =3!‹¦–cûÑv´õÔµÁGs›R Ó Õ8gøzŒÙ ‘çò{ä<×fxÛNêpëÜ(Ð ;àkŒýÈžiÖaËa£”ýoQ¤yòX+wq%,Î\ˆ¢þ ù6å:‰­#~,I\¤õ¹‹æ@|æý#xsW“t’xoù³&Ü i¼§bâ¹¥û=·±ϾÄðw°[Íøå—/FžË–øÜšm3ÜF)¿AÂ{ëíX·Gì>yu0YlCM€0`˜ŸÁ]¡.GV-% ø‚ÌuõÚvx2Ñ3=É­Y0Ëoƒƒ1YW1¢¨ðÝQåºJ¦ Uø ©ÂCN5‹ñ²' }y ËgóytpßsÛ!ȦI§”B8¼Q Ò" ~èìW”Šˆ±QT>ÿ943.š!76—:FšWaY°¬ kk2á®ÇÞÅœš"Ìšl̰P]œ‹ÿ¹é|ãÁuÒlRƒ ½Ul“56Õrþ‘DïyÂyòë(÷;# kEny úN7 ë"”Y wÕUð¶¿ âáœóc'CÅ?3Õ3 6Àá»"…mX1'È-«c²@¤*½ž*<â PYOÑñ¾K òÒ\´°N›ÅÐËÜ÷ä;8~ü8x. žã ð|ÌLIi̦Døˆ+7"Ùã­æð¹ôcßîD^ŽÃЕ.9g n½|>þüúÞd/º¼sS=°Èö =Ñ~N9©zú®«¨ž®ðáÀ°\ȰßC~í8RÈŒ×pJ mÁ–Ì)Ï™äÓVLçú)Ù‹µ8à,ª†@ˆýR"­Ù6$þï§€@©ì<’xø>ùµ ;wh{LX³ Æ˜Õªg?»Þ>ý>D#‚ éN̰x°°Ò¢µ]kÑ8ž‘ï‹qäý':ð­ß> ^0KpǵK±lzÅP; µŸj;)Úoè;Èåw¢Pÿ&”h|c JX¸Kk‡ß-få\ WÉ• #Lõ¹3|yØêEÞHÆ¢3©¤›HAÝ=œ .›tî²:Xs vv ¯ÚºªoCî8TîKT A@$DÐ7&À¯n»ÊóíÏ/|€W7ê˜H…´aTö+Fc{Âï$:ûb²º’v”æbñÌIÆ> Ëà¼åxìù·Ñ×ßžçAÀ€0ædƒÕÉ™¡>ª0ùjFY'^Ïds‚‰D†¦?!žDéìÈ­þ5€ûR!Cü×À]™wE¼íýc:ÊgŒ{Ô/«õ –Ý‚(æÆ?&k¶¢xæy`X3ƒI¢„D1ÈÐ1 ûȰ~ÀG ú Á…à£QPJBpñÒYxë¡; X®,»õ>ì>Ú’|ySj¥-?”,àËãYÔ÷KºÝjÆûÝa$ðֶøúÛ*+IJ,,v,v¬vX‹5f%Ò?(†ƒ©â¹”ë"X†ÀÌ20³,œ6 sì(/ÊAI®ù96”æç ¼È\§E¹NTåÁbbpøX¾þãû±e÷ÁX™`€Å ”MÓîËt(žð<€f´í  &ûÔÕ? qâÝC—¸Ê¦ÀUZ›¬$uv@®Ô§ÞG†šJˆFÀ…ý(¸hâh,ûýÞM—ã—߸>åË4¶tcîç1¦ž-À¨¶r:Mžª\Ob§œ6©ÿï繌]÷<ú*îþË˱A#¾H5[b`qæÂbw‰—[¢Ú`ɱ›ñµ«ÏÁòÙ“àvX벡(×™vÀå¡cM˜ÿ±[ ¼Â@)@w‚Òg¬° î$°Rô˜…¶½MI'9•Ór”Ü(aYØ *P0P³°¹Ü"Et¬U\ЇhÀƒhÐ £Ž+úZâŠô\³ê* ½ÐÖƒ§hâµT9Ñà&£hòiÊTjÆ–>Üvß³xê§7Â̦ ¾ûÅ˰åà)¬Ý| 4¶Hx!o?BÞ>ÂÀls–“‹3/Š$ ×ß° ·\¾pÔhVýd\²r ÖnØS1bœä˜ˆ…õhÙEõ¹¿Pà Ÿ!çƒRS¬ýéfPôŽz¤Ï„âO]eqqŠ|t·æ–¬u Jph"8¢ ‚ zõ ôIm'£Â1†þËîu•Æò=v7¶ÉÎSB¥„ˆQ ¤ÈÕP¥xþýƒøÝÓà;Ÿ»ÀлÙ,füí®›°ìÖ{ÑÜÑ?̈( 4bÌJG)¢!¢A/ša¶»`É)€Å‘ †e‡Ìè+æL›Q–ÜñŸÄ›ïoGlz{áOè;vüÝÓ’´l€V£zÙ_T‚OƒÒÏäq´mŸf^3'2_Äaуa`É«€8d$ ‹(nùJ@©>äCÄ×.è‰ù”ŸhC}ŸÑlÁãm}‰Ö-€’Ç :œ”êp!G¡‰ÉL?|äM,™9 ç/¨3ô~e…n<þã›ñ±o=ˆp$šèǤPÌ!ÿ¸, ‹#–œB˜ì.ì=Ñ…iU…cÒ‘Öœ»ógÕcï¡caÖ€µØøTnÙF%°Üª¥÷•…v¬Í¼LAÝÂ2^À%r¿ksƒ±åhx¼ežf${ÆùhÁÞxN€¯ã¢þ~IÉf’Èþ3:fV&ök$½U¤=ž`¢É•ab&ס{0¦YÙý6q¤ØÏ0÷PšcçFyŠ›ù :ú¼†?Üù §âÇ·^Âh¼£þ~T¤ˆøàë8o˼öþ®1ëLV‹_ûü'âƒÚ4äTœk¨Ï¶nZ·‹ lÄ”{­@©M>z›Ý%‰a P ‘†RpA/üíGám>€ð`'D“€¨wÆ„ÎĦüÈFDÉÁ&Q³Ét ÈM@©tÀ„ó4|-º©Óƒÿ¸÷yD8Þ H|熋ðÉ j€UWf˜; \!ïØfÍ~îê‹P\˜‚µ\B2•)€Ž’k†EX2®"8Tâ€âq9¢ˆ¨¯þÖÃtôÊÄ'Ž• V¥ó²ÉÜð›è”0à$dƒàкŠ3D¬kwÃ/þ¹Á¸llbñ·}ŸX5_—k$¿7 ›ÍŠ«V/ÂϾñé1í N‡ V«5îCº¹“ÜÇZ c©ƒ‚ú%“=" ƒŒ-Äd¥rëM ûÀû{Á v@ä ë“¬K$üg´õ„ÿL¢"O8^H=‚‚·S:_ib†Š?'…å*Âs1«’ª‰7~_•‚ CçQüüŸïcùœÉ¸tq½±i³à©ÿ¹ w?úø×{àx^fÙcí û_”ëį8_ºf5fÔ”ya½WÖoAGwüûVÁU²ƒ§ß˜Lì8¾1q&ç!J]qp€0`…©Â2EÈÐ1ì7Ð1Jö@'@Å{ -0‘$sÂ/z=AC>ƒI¥ù2€A§ô?Hº^*¢a¼R8æˆl@äEŠ/þòylù×Q[žoè¶v«¿üÏã³/Â/þñ6Ömo€×Œ%ùQ “‰ ¦¼_»v¾rÍ*ä8méœoïhÀ—øyT«ÉzµdîÏ&€Hâ{É•EêPÄ–7<¸Å?8(?Ø !0 „€á0:–-鷭׋™"ag×”$r¥ïÃhux-+ôüòãUìâ„èr€ k0ˆ[~ý^ûß f §Uáé{nFŸ7€ƒ';ÐÑãÍjF]E!fÕ–Åfν¸ñ0¾tß‹è÷…¥¶c 'ì%Ìøñà"cœ²Ú¼0%KcÎ&©1,`qÅ|C„Bô÷€l†LµLb‡Vã ¡>@1kXL:ÖÚ‹ÏIýrKgV)ü *ŽA£>#"ˆüJSÊ,D„RlØßŒþõ®ë(øþÓ8cà+Œ – VÅ¢ÂjXZäçÄþ8ÕeèåfO.FYaŽ‚Ë±ê«„ÿj¦h’Þ¢©Ä§¸'”A” ~ÿÂüß+;1Q‰RŠ?¿º·Þÿ‚‘Xé$b¶+¼,,®ó1É~c S„XV&¼HÌs.e¨ ¡Að‡@#¾dÀh™MS™j‰Š……¨›Kå瀄Åö£†^.×iÅùójtD=&Ùœ›²ƒb‰BP³ž)vèy)!¸óá·ñï÷O@p÷?½·?ø¢‚8d夌9Y2ü­ä–: €µÌðn"sÀ᨜ùé0OÎKî°júC*Ρ&J©Ä\RfñB*œ'PWž‡ÅÓÊR³Jƒš’\<³é¸T·@‡{¤e©"#¿×Rˆ\Pã*± M]ümÝ~D8skŠá°™Óê¼ bË¡&|ç/áë¿yöƒ7Ú¿ÿX æÕWbfm9ÀŠà3ßû#ž}{;4“‚ˆ øj©À š^Èaäð¹57ŠÄ43¥OƒÑ ¼S±iul·˜À‘:Jk¯·\:ט1µ"-½~ì9Ù“¢“ËwºçBý:É"žP×KlØßŒÇÖ@G¿y.+Šsšm"RŠSxjý^|û¯àžÇÖáЩÎárBò)Ön>o „C'Úðûÿ…÷v‘q>Y¤‘;A•œS.jQþ®' r¡L„ŒÀÊ\ó®~Óægkv|¤ÒH²“Ñ ÆSaªp“¤_(: Á+?¹W-5–?á FqÙ_ÄÖ£ãÜÜ*"–Öv¥è¥š;.ËïZ‰ô,T81¿®Ó« Pä¶ÃÄ2èópº{ûŽ·£©½ÁpD:G:—ÆÅäuHëbü¿òxšx\Â6Ù:( è:´¾öÓˆG™±“u™ráFLi²•%M`¨ê"z ôBN´b°¼.5Ãüºbìøí 0TV{¶o÷‰Üpþt¸ìÆ”T‡Õ„«—ÖâóLCžË†cíøBœþÇÏÔ¢¼\J”T IJ-Öëë¬RhçïÃHp¦ÊýDn3<­»'*!ìkñÁâ¾nä PèºzL ‰žù˜¨‡cÈ:•/Ì£s0ˆk–Õ¥å<ËuZqÁœJ|ýʹ˜=¹tc9ø#µlŠ‹(£¢2Ò=#U ´AbHœÔ˜­˜¦šUK:Oäwc°yS&-Y£ˆ£ vî!j¹8Iï`Ë•|´gõc±`”±z¬Ba4|#‰`9ÔÜiy˜[“~áË`ÎäBÜrÑL\² œœìôÆÄ/Œ£È%ÑŠ’›P •QhO½M©¤Ô ×ЪþB~ç G0xzýDÀ实uQ€cV$v`V{Äg˜qU)ü$ó¯Fô,T8ˆ2~*¡ãÄŸxg.]Xòü‘ÍYNAu‘ מ[‹×LÃâú”ç;áôzÚéú^rƒqZI²œ‚c¨q UýƒhHL*uÀRqC…óˆú¦¡ÜD…“8õ:€ðDô¤¬ Êâ¯I-ZÉ£PßDJë—N’T<ßC%{0¡àÑ‘— ¢¸â§¯ãÕ»®ÀâúâQ5pU¡ 7¬žŠVO•®Áæ†.l<ÜM 8xº©ê¨m’Dź¥ð¬Ç«µÇGbyFb’¸#߯ ׈–ÿ‡¼b¾ä‡,‚"žè4Q!_—}C**ÄPÙ6ªRf‰R€°ni×QdÎa䆕Âd_d¼0«ÒùYƒf`eR”JxJØ”2N¢6Ê/—¶5a^M!êËsǬÁm¦Väâ¢ùU¸å¢øÊe³på9“0½26 ‹0/Ââ¥>7†Q¿zV-hX°Ôô-ÅÝP-b£¢–ò¢bÉ@ùôŸ|@p"„‹¼Ék`q.L­Ø‘Wó0ŽT•Ð|! ` #Dx<»ù$B°lZ)Xfìýv‹ “‹s°rfnX=_½t¾¸f–N-FQ®þ‹ N7¨Qëݒ̧‰é Ú QÙ—Êâ”0#1Ëö‹b?úOü€?SÍ7¨FíwÁYtszåkF #NA¥Üj„Ó§eÓJð»[W`éÔŒwtx{oíkÅÚ=­xï`ºC)D2­Jð©*²S…‡]ñ;äP=ïJ§ ª—\Lv(ŠbâoÜËžä@T<ë"ÀGö qí'tdÊÔ;b‹üš `qÎO°Z©åjJr2öNTcª”οDó/4Ì­ÆÒ`Ûú‚øû{Çp¢Ó‡i•y(vÛÆ 9v3Ôâ“çÕâ¶ËfaÕ¬2Ø-&tzBð…y…]+p*•óÿUå1R2€¥5»Cº¢–¬®ù)³ûäÀ½„h˜t–.(2ìÀ¨ç£$q—‘/PiÄßß;†GÞ>Š^"EAŽ ‹iÜD0«™ÅœIù¸iÍT\³¬ƒ(ŽwzÁ TÝl¬¦hê%Jg Ae\@äÛÐwlÂr€<¶¨~55Ë8£¦ ³ê# @Ââµ¢x“uF,ü i’/Äaçñ^ükãI<¼®ïhG7 §Õ„Â[F{5*˳ãúójñ±…Õhëâx—WE’Q™×D¯JäçP±x%€…ª(ê$ùXUCŒ°u¸ãè;þïDå ¹5³W„¨u¡ºx¥­ØÔ‰QŒN–nˆ»PäoÆ`þFàœ"œ€“]>¬ÛÛ†G×7âŽãHë ‘¢¢À «™Í(H€Š>³²³«ò°éh7üa^$*BjU‡$Z#<Ôu­§Uó½( &‡¡P%@^žÐ"VnåŒ%~j]’ 6µNbÔ‚¥•¡¨É5•íDÅËLt4ÌTÇès#‘(vèÅ¿6Äý/À›{Ûp¸uþ0—Í »Å”Âٓòqê)8ÚîEc‡7} ‹Ÿ–>"à ™y©ŠÅÍ Â>$놢ÿÄÚ‰ ·µ jNˆÉY©]_£È[J]z³G)ó>´"\•)Á0ºø(AZzØr´Oo>…×ÁÓ›Oaë±nôxÂ0± rÃù(F­_ŸZ^‹pTÄÖÆžDÓ°V¨º2§] D¥£5‹4@ -‰%…•èIZÑÀ œzg¢ŠX €œ0ì“᮸T•{0¬ŠÓMÏbLb˜‰J%÷Ô¢RÏx5†$ˆ½Þ0öŸÀ«»ZðèúF<¼î(Þ;Ô‰®Á0VJsí£VøY†à¢¹p;,xç`D‘jìD%¶*¡ÐÕ u§†'ÔkNȈwOo’…Èhb±(±ÀeyM&‘À¨×ÇeÔËÒ€è{À5sÛãu™d'`Bí]=ÉÎ3åt€Ê<‰™+ÁÄ "ºwZ úýl;Ö“ZGÐ ‹O‹SÐÌŽblàk{þîC˜ ±X€#ðä±ó¯ ëH.&ÍŽ"ä„èsµÔÖ¤ì9#ØÀœ)/3`Ñ9Ÿþ(Þ?Ü…GÖ7âX‡Ó+rÓöæ\0»›v¡©Û§`ª6IÐ;”À¡ .“¦.bÈêK)zŽü _S&2@iÔa&ƒÚѶŒ†^ªj¹Þ*aíª³IiX›´:§f^E:8 Xˆá]ÁÇß;ùßy_ú¿Mh¦õÑìúê ä9­* Ð©¦C/i0ÒiN颤vS1°È×EÑ‹ˆß‹X>ú„±À  uK“sr²Ks°ê‡Œ^­L燚ÂÎ@=¢•I!V¥ê¨$­?=Í”Œ`7(Rì9Õ§6žDYžsªó § æØÀ‹ïhOÍE4ý!TGV3õRç)tC¢ÁE(1Ò†®OƒÒn‘Ld´6E@ÔÎp]ÉUc:´¤šUU@äÛTÁ•Ä($[²Ôb®49†bô3Ò‘G ’Ñ ~!ÜôÇ𵇷@_ë›WÍÆ¤b—üê¥Áj•SRÆxÉW^[uNzÙ=øH;D!Œ Ï45z ˆÐ@oÑ "TDֹͪÒÉñH²T©XÄäÀHseD?Sd–‘â/o7â¶4@â²™ñÝkæ«idfjŠ]ÀHѵ*,ñõÁ&ÄrÑ…L¶íh9 Ì÷:E5Ó\‰FŒôÊpjYHø@ŒBÉÖËÍŽ-« n»9«zNª’ 4Ð4w©ÿèúF<ôfƒá»~~u=Jóì*zH 1+ݶI`:DÝ8’âuw€ü¡þ’h5¡«»‹"þÎ>‡ ƒA$™^¸£?=3Ôu7г¿ˆÅÄ`Åôb\:¯K§¢¾Ô…[¬¾'ˆhëá@ó Þ?Ò…×w·¢£?˜2NµªoД›ÒÉèÀ'RŠ=µ kæ”aNuêJíyN >·r ~ûêÁÔƒR?’­UqßUXéæ–Ë§'ŠÆTá.”†áï:-D˜È¤‡ ˆ· æÂMo·–>’$‹jp5‡`8b¿En+¾zñT|õâzTjOkPì¶aAM>n\] ŽñêîVüæ•ÃØr´'6ñ¨nO£DÕò!$®â røæ_·aÝ]—1çuÃê)øã‡Á â¼ ITˆÌ©'?9É©IC²^#p}ðwuJ"VF'ЭˆE¥‡ `ïqUÑ*•Ȥ¥ CÅ4¬[c—€en½p öÜû1üì3ótÁ¡$³‰ÁµK'á½»/Ãÿµ•]$SDGp&†àŽ+fà­®ÁÔ²œ1o‡Õ„Gn[ŽËæWàl£'àÕ-†Ž]PS¨ÈK1›¥v¸ž˜¥á!ÐÉ58 î„¿«Mˆév €ˆB<Œ§ù0IÉÔ²öä\Ñ­G§b· OkøâB8­™›2ÛnañØ7Vbj¹{”WùëÆæŸRæN#RXÍ ¬a.OªfIÔu$ޤå-möD,ÿ#|6$ ÀÃu54°Cê%?•Ȩ˚ÊQ±…¯žYŠí?¿ ×.­—)ŒËòìxü+q‚è!p¨eÁHêrQ&–`R‘KÛ(aDÌRu&‹Ãºâ·^|V|½ÿän©Ïѳ qEÝñtw˜£MªåK…=œèªIÛÌ&ß¹zÞøÁÔ”8ǵ³7½?»aQ†¹ÈØ¢«Ë‚'h¬ðyE’aC%Ò@MÌ"D_ÜR›p‡¤â"$l„|¸žæˆ%Hqg @ =¬@?úNH-^é˜nÕ&u!¥yv<ûíUøÕçÂaYŒ%/ˆèõEÐë‹$—Æ1@·l&®?wr†@2ö¬'à 3ôä:,ƒhlÓËñ×øîzn­IJå÷ñwé‘ú?ãX 4õGNoßg®^þ ÄšÔ€)”0$5:!Àš9exìë+ÒòkÈ©c0„_¼xÏnkAÇ` Uv\·¬ßÿøL”çÛ ]‡eþô•óp°yа…H ixÏÉÈîcDÄR?•¨Ì±…#2Ï9•š¦2Ï8Mô¬&VJ4a›Òó®Ö7D½; Œ—‚>–„J2á  v1¾¶£‰úƒw 6s鯙eðƒëæáµï_8bp¼}  çþh=þðæ±8$jíâ÷oÅò»ÖaoÓ€áë¹mxüö•pÙÆblɼÂ2*³7Q©€ Qõ‰šÓQô‰\„0@4Ð…SG "½AÏ6€D%ëB騻“!„ª‡?k¬+³,ß—¾·÷|fl#©xâ§ÏÂU¿Þˆæ>í¤¢¦ž®¿ÿt{ŒÏÁ²lj1î½qñøéãddÇ3„ Àe1tŠ U ÛHmcŒn½2¢mþUr‘ÁÓ{ ò=R‹žmÄòüz#‡MQow’eCË"û²„\¾°Ûq%>¶°rD‘­ý!\ù«p÷s‡áRsâ“]>|éÏÛÒÒKn»t>»²î ‚#E^<ò]Ã’öxÃÚ)Z š¡:eMÑ×ZÖ*åB…(ÚvmÐ+õ1a¼Æ¦±H\Ìê§×IzŽìUWæÅ(9G±˜Üý™…xñ»¢ºhdVªuû»°â'ï`Ý®´Î{uw+xíHZÒÇn]†YUygHiuª.r&*ß:ÔÒ„¦7\ $J‘I-ŠÙ¿ ¨™¬±­¿·ý0žýãeÞÍ@âbV—pzË3øU'ŽT1 V¹ðê.Á]ŸZ0¢œ â§ÏÆÕ÷é‹TšOŸ>³º ŸS˜cÅã·¯‚Óf{`´Q“´ÿÜiņ*7zC:CÉS-lD$D­( ´-.ˆ¤}÷݈ù?¢g+@äbVl%= “‘¨\±h¶þòã¸d~åˆäúæÞ ®üÕFÜýÜ!iFÙ‘Q Âã–7§¥,žR„n^–~nшú?1|B®XTmèè†ÖApªí¦1ùP’¨”ÂR™” ª‘–«†DÝMt é¨q¯2!1 @‡pâÝí,„¨ÖǵYXüü KðÂ÷/QqT£7÷ubÅÝïà­4E*-:ÞéÅ×þ²5­üî[/šŠϯÏ0×Hu¥¹vœ?»ÌбێõJ1ãZz7a”Ä]ÔŠ"Ùª¥6+˜Œ{ cÏVP±S&^‰g3@€˜Ç Sð÷ž6÷6RSÆ'—¸±öÇWâû×/„Å”þcDxw?{¿o#ZG R ÉUIø^ÜÞŒ×O]eÁïnY†y“óG2Ø×H¤ÏŸ·Aýƒz¿Vø¹\äRIRÎ4Ä'F}vbiaB½m´óàARŸâ0Δ €PÄ9=ÚøÆu[YÊEä¬ÿê¥5Ø~ßõ8NÅÈEª{ßÇOS‰TT¯ÔŒ6X(~ðäl>Úcø™òœüýöÕ ôh€1rpäØÍøÖU³ ;à`SC7ôëkÔ¼J ’EÆD-F(PÚ¼u3¨Ø&‰WÁñ晇˜C§÷u7±Ý€Ýj½7¯À³ßÿJrí#ºðë{;°ü'ocýÁ®Ü`tÓG6¡×g¼äÒüš®Êyœ29£ •®ï‚·²ø¢Y/þøzËgVOÑœaNÀ]OÀ7ßÁ¤ø"ň6F`éó‡qºÇOž;ÙpÔðüš4÷°·©?Sšz²ùU¶,ª+ÄÃ_[aHlqÊ]hh÷˜mK¥ôÑ›GD^ \¤¨5ñçðvB©H޾ü öíÐ(qÎ1GDB~«hZÂmyÙôÒõÜ“Ý~\þ¿ïáÞ—§¶Riè‰û?Æ3[šÒ×GþcO)÷Y˜cÅß¾n< æx§k÷¶kË~ª³æêä'(æ °ëÍ×®à"¤ÿøQ±çx€V}gßÇx’¼è—¬æ§žzêÈ»ï¾Ûœ.Ê^ÞÙŠU?~ w¥82íÆ‰²»“+¢ëÛnÆ¿¾u&e8$_Ö­&OüתDCA úýëGæmË•ï¹ײPAÏß»#DÂôØ[[Ú‚Øüç¾ñ6íŽ@âŽÃ~-Zî¼óÎm>ŸÏP‚B˜ðýîÆ'ïÿ@Q ™jˆPtà0F¾‡›þ¸¨ás¦”å`í.aD€Ág—Ú!ÇnÆw¬Æå * ßáT·}ç8Œ„#ÚŽÁ!î¡Á”yèjä¤ë³í;÷P× Íˆ…–œ1î‘iDÎIkWW—Ãívç¬X±¢BO¦?Ñéçï߀'76ÅfDR«5’ -9°ÒÔSú|´ôpí²I†õ‘b· ×-›ŒíÇ{ÑÒHSÍ0vš’<÷5iC¤ßxt;öœJWOR©1Ò¯eŰM¡Þ~Ï?ׂÒÃ’îÑ# ²ø°DŒ+ì[·n%W^yeuYY™êÐúÒöf\wß{8ÔâI…”¬~D¡Ü#Œ¶  <ß‘–~‘ç´à3+ê RŠÇ{“#ôBð©å5xöÎ5˜]^<Øë{Úð“ïƒ8bc†¨½ÑžK„PA`>ý¶èï9àˆÄA26µÚDÅð4YŽãœ{öì?ÿùÏO1›ÍC"^(ÊãGOî·ßoÓfÇ£å"šœ…â*wá’ùiyþ-&Ï«ÀÕ‹'¡c „“]¾äÎi( !X6­Þ¶ßýÄ\¸æ´^µÇÆu¿~}þˆ!«˜îœ*Dã¿Úêzƒ¡°vì8=ùÁV‡—Ä+g˜Øqº•¶¶¶6!ĺfÍšrB9Þéŧ~½Om<Q„J¥Œž‹Œ‘é7ÊÇfŒýìŠZØ-é)–åÛñ¹•uøø’I°˜YôxÃð†¸ÄGS\'(Ï·ãÚe“ñ››–àgŸ[ˆúrwÚ+xâ¦?nÄ–ÆÞ”J¿±}DeŠ:$›~U'ûæ&æ`g¿û‰õTäHÜ£ ±J9â™ÈxÖà0È0 À9f³yþK/¿|i$Fõ×þ´]ž°Æ|!H¬ã«fFLÕQ”uÕuªm"V× «êð÷ÛWjžóPTÀ±vïÅ‘VZûð£àŠ|—ùL-w㜺BÌž”o8tDk„úŸgöá§OïMU÷ :󚫵‘¼=ãÿ©(;^ŒýýïÁ ‘(Ùöàk|óN;šºÇ™`P `6€ÅÎ’É ¹åw^…Õbxª5Í"£œZ¸É„ໟ˜ƒÿ½áCE¢Ï$Q¼Ýˆÿ|d›T¤Z &üÑ •Õ …´ˆ¢l»‘Z½²5|týF»ì“,ž›sp¢ŠXòoÅé#ra¥³ª†¾V!c5ӘŘŒ¶4vƒe¬˜Q:f%O3A®oÄׇÀ€m]DS¬RlSÕETEGßá}/lèI÷hE¬æ®8QÚîLDÄðÄ‹V:pŒ³ÐMs'%†.hȱº Qûø4#ºHüRuÂâpñ¼Š ‘RüöµÃøöc;bùz\B“;C}€2’Ð¥5%4¡°‡:{#[Þ@î¨$VB,~O˜HmÈž{ƹHÜ…k£Ý‡9¶dz)µæès Q`4æÞT¡'Tß ClmìÁ¡–\<¯"mÅ=Sˆð¸ã¯ÛñË çÚk$å £q,IÅET9JaAaóƒï ÁÁF qŸÇ¸U+™ÈÄEâ a@Eí:"es+`ͱkr-%Ý(Ph:@Hï;iõà•ÍXP[˜ù“t¨e×Þû^ÞÙ¢°ˆ‘Á†õ¾'Z«ÀŽ3ïytc¸çTƒŽ#ˆEìN«ÕDˆ$<øˆ•ô 3UçTSVš'M‹‹¤Ò?”f. EN½ÞžÚx ¾0‡%õE°™Ç·yƒQ¿zñn}hNvû+â©Ä+=$™y©¦˜e"‚`9ô驪%`FÌ!èÃ8UJ<›Ÿ%—“~YD|f2p*ŒŠ…U`ͦD@¤ ’T¢•ñjÄ "65tãÉ'á¶›1«:&–ÉhCFx/n;ÏÜÿžÙÒ$•:Ò™áW ÄXµ] i`!”æœ|mŸ0ßj —IDATïðÛûp@Ò;0‚ )ìñé|M4ØÏOKå *ÁšÙdÙVÅùd(4=ñŠRã×R¬z‚Q¼¼£Oo:Q¤¨)Î1\£Ê(õù"øû†øòC›ðàÚ#èKJî"£Ñ !Æ&–¡´ cÑþÏípLGÜ[>áôŒ`ØÍô3X¨0À,”/˜ƒ%_:&»9µG}a'rî‘6@h Ü%Ÿ—ç´à¢y¸þܬ™S޲<ûˆ«ßÁ†CxnkÖím|Óýšd„18ШùdNB–¡´´wccdžÇwR*CÌ×q±Pö3’F{¶$þVE¦J ™òù³°äËú IW†ÖôªgJ²šY̬ÌÅâúbÌ›œú27* ÈsZ‘+ÅVùB<Á(Úúƒ8ÑéÃÓýØy¢›Šò:b<’ $±ÿ,DZÞ·éhÛ†¿í¥”—À!÷w˜à4‘ ÷Œ’bÄÂQæ˜Ò9ÓÉ’//¥—M}rOƒš„¯šQpŒË'$idDàH ¢˜ßööÑÞ-Oî“týçhÈJùDÓA”-.JúHdȺèé? eóÊÀZÍɲ¯Šc0ÉAeÔY8rcäà c0^‘3íc¬ sO½r°odz‡4aØœ‡€³„Ø öŒQŠ\A $>Iþå@EоãA4oé†ÉJS抙„IæAéÄÉ(bf@K¸æ~vçÃ{¶?{"ôõH\#ž"Û€X¢Óâæ÷)‘Ñ{˜8‹®P  @€¸Ê 0ãŠ:T.‘òLä§ŽQÇ>Ëbb ¸¶zø¥“ý[{AðIJw«¤ŒŸÂð„6¡+×ø0$þ. b¹%n%ªL–~ËäÃYœ‡WÕ¢bQŰŠi€˜J ¢m¤á•SÝ [{(’ÂÝ!)ß§%ôJœšû0s+@äïd`C¬’c)€* (•ˆ…ÓçÁ–çÆ” «Q½¬ŽBÇG ÃÛ¬À;z„£o´ 4è—t‰A] š¥ßnI Ï2Kñ!ò!~7FŠ@¾ (U’ØU &›  KP³² …õ… ,™ #E0nѰtìè6¼ÝèïôK:Ü „6 ñÉ31Áð‘ÆG r X$ äI¢W…´”K% N8‹rP³²ç”ÁUìaµ…‰é‡!N‰šûzÄSïwxšöPQŒÈ8F·$NµJ¿= `ˆøˆù½'#)òŽ P$q• I?)’ä`CAm*Î)Aéì"¸Ê\‰ŠýÄK«à Y<'hÛ®îPóžþh8ióKè‘ÑXxH¯$J?êÀø¨Dþ¾q‹—@bÅ"Š%”J@É—}c…³È‰ÒÙ(žU€üÚ<Øås,O‡¡ÆÛ2H{Žˆí{û¹¾f¿À…ãšA©ó÷KÀè’@Ñ#Y¥|YŽ‘ˆRôb˃wJ\%–øR %G”„1ÃYâ@ÉŒ<ÔåÂ]™g‰& ›$’5H$€0BT°ÓP”ë?íeO{Ùž`{ƒŠ"H¬HÀp¡½8 â—qNᕸ lñJâS@ !+Fe2º +uv« 0.iÉ‘-.g±%p—aÀ°C QŸ˜\6ÓÌÐħ‚ ây1ñ°ÿxˆM~i JÇD1\(|ìk­f’%™ÆJÞ"]Ž]¶Ød‹EVZ” ‰‹:qPð2`D0\Ä"¤Xâ@ˆçîÇÁgŧ,@Î4`‡0+‹ì¿I%'Qã¼l‰*¸'[ä`õMkYÊäÌ‹eŒ@Œ (hÏ”)*À"¨8& „,@>”mm´}YÊR–²”¥,e)KYÊR–²”¥,e)KYÊR–²”¥,e)KYÊR–²”¥,eiÑÿI$kÚG{,IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/test_autodoc_4.rst0000664000175100017510000000021112370216246023776 0ustar vagrantvagrant00000000000000scipy.sparse.linalg.eigsh ========================= .. currentmodule:: scipy.sparse.linalg .. autofunction:: scipy.sparse.linalg.eigsh numpy-1.8.2/doc/scipy-sphinx-theme/test_optimize.rst0000664000175100017510000007227212370216246023775 0ustar vagrantvagrant00000000000000Optimization (:mod:`scipy.optimize`) ==================================== .. sectionauthor:: Travis E. Oliphant .. sectionauthor:: Pauli Virtanen .. sectionauthor:: Denis Laxalde .. currentmodule:: scipy.optimize The :mod:`scipy.optimize` package provides several commonly used optimization algorithms. A detailed listing is available: :mod:`scipy.optimize` (can also be found by ``help(scipy.optimize)``). The module contains: 1. Unconstrained and constrained minimization of multivariate scalar functions (:func:`minimize`) using a variety of algorithms (e.g. BFGS, Nelder-Mead simplex, Newton Conjugate Gradient, COBYLA or SLSQP) 2. Global (brute-force) optimization routines (e.g., :func:`anneal`, :func:`basinhopping`) 3. Least-squares minimization (:func:`leastsq`) and curve fitting (:func:`curve_fit`) algorithms 4. Scalar univariate functions minimizers (:func:`minimize_scalar`) and root finders (:func:`newton`) 5. Multivariate equation system solvers (:func:`root`) using a variety of algorithms (e.g. hybrid Powell, Levenberg-Marquardt or large-scale methods such as Newton-Krylov). Below, several examples demonstrate their basic usage. Unconstrained minimization of multivariate scalar functions (:func:`minimize`) ------------------------------------------------------------------------------ The :func:`minimize` function provides a common interface to unconstrained and constrained minimization algorithms for multivariate scalar functions in `scipy.optimize`. To demonstrate the minimization function consider the problem of minimizing the Rosenbrock function of :math:`N` variables: .. math:: :nowrap: \[ f\left(\mathbf{x}\right)=\sum_{i=1}^{N-1}100\left(x_{i}-x_{i-1}^{2}\right)^{2}+\left(1-x_{i-1}\right)^{2}.\] The minimum value of this function is 0 which is achieved when :math:`x_{i}=1.` Note that the Rosenbrock function and its derivatives are included in `scipy.optimize`. The implementations shown in the following sections provide examples of how to define an objective function as well as its jacobian and hessian functions. Nelder-Mead Simplex algorithm (``method='Nelder-Mead'``) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ In the example below, the :func:`minimize` routine is used with the *Nelder-Mead* simplex algorithm (selected through the ``method`` parameter): >>> import numpy as np >>> from scipy.optimize import minimize >>> def rosen(x): ... """The Rosenbrock function""" ... return sum(100.0*(x[1:]-x[:-1]**2.0)**2.0 + (1-x[:-1])**2.0) >>> x0 = np.array([1.3, 0.7, 0.8, 1.9, 1.2]) >>> res = minimize(rosen, x0, method='nelder-mead', ... options={'xtol': 1e-8, 'disp': True}) Optimization terminated successfully. Current function value: 0.000000 Iterations: 339 Function evaluations: 571 >>> print(res.x) [ 1. 1. 1. 1. 1.] The simplex algorithm is probably the simplest way to minimize a fairly well-behaved function. It requires only function evaluations and is a good choice for simple minimization problems. However, because it does not use any gradient evaluations, it may take longer to find the minimum. Another optimization algorithm that needs only function calls to find the minimum is *Powell*'s method available by setting ``method='powell'`` in :func:`minimize`. Broyden-Fletcher-Goldfarb-Shanno algorithm (``method='BFGS'``) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ In order to converge more quickly to the solution, this routine uses the gradient of the objective function. If the gradient is not given by the user, then it is estimated using first-differences. The Broyden-Fletcher-Goldfarb-Shanno (BFGS) method typically requires fewer function calls than the simplex algorithm even when the gradient must be estimated. To demonstrate this algorithm, the Rosenbrock function is again used. The gradient of the Rosenbrock function is the vector: .. math:: :nowrap: \begin{eqnarray*} \frac{\partial f}{\partial x_{j}} & = & \sum_{i=1}^{N}200\left(x_{i}-x_{i-1}^{2}\right)\left(\delta_{i,j}-2x_{i-1}\delta_{i-1,j}\right)-2\left(1-x_{i-1}\right)\delta_{i-1,j}.\\ & = & 200\left(x_{j}-x_{j-1}^{2}\right)-400x_{j}\left(x_{j+1}-x_{j}^{2}\right)-2\left(1-x_{j}\right).\end{eqnarray*} This expression is valid for the interior derivatives. Special cases are .. math:: :nowrap: \begin{eqnarray*} \frac{\partial f}{\partial x_{0}} & = & -400x_{0}\left(x_{1}-x_{0}^{2}\right)-2\left(1-x_{0}\right),\\ \frac{\partial f}{\partial x_{N-1}} & = & 200\left(x_{N-1}-x_{N-2}^{2}\right).\end{eqnarray*} A Python function which computes this gradient is constructed by the code-segment: >>> def rosen_der(x): ... xm = x[1:-1] ... xm_m1 = x[:-2] ... xm_p1 = x[2:] ... der = np.zeros_like(x) ... der[1:-1] = 200*(xm-xm_m1**2) - 400*(xm_p1 - xm**2)*xm - 2*(1-xm) ... der[0] = -400*x[0]*(x[1]-x[0]**2) - 2*(1-x[0]) ... der[-1] = 200*(x[-1]-x[-2]**2) ... return der This gradient information is specified in the :func:`minimize` function through the ``jac`` parameter as illustrated below. >>> res = minimize(rosen, x0, method='BFGS', jac=rosen_der, ... options={'disp': True}) Optimization terminated successfully. Current function value: 0.000000 Iterations: 51 Function evaluations: 63 Gradient evaluations: 63 >>> print(res.x) [ 1. 1. 1. 1. 1.] Newton-Conjugate-Gradient algorithm (``method='Newton-CG'``) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ The method which requires the fewest function calls and is therefore often the fastest method to minimize functions of many variables uses the Newton-Conjugate Gradient algorithm. This method is a modified Newton's method and uses a conjugate gradient algorithm to (approximately) invert the local Hessian. Newton's method is based on fitting the function locally to a quadratic form: .. math:: :nowrap: \[ f\left(\mathbf{x}\right)\approx f\left(\mathbf{x}_{0}\right)+\nabla f\left(\mathbf{x}_{0}\right)\cdot\left(\mathbf{x}-\mathbf{x}_{0}\right)+\frac{1}{2}\left(\mathbf{x}-\mathbf{x}_{0}\right)^{T}\mathbf{H}\left(\mathbf{x}_{0}\right)\left(\mathbf{x}-\mathbf{x}_{0}\right).\] where :math:`\mathbf{H}\left(\mathbf{x}_{0}\right)` is a matrix of second-derivatives (the Hessian). If the Hessian is positive definite then the local minimum of this function can be found by setting the gradient of the quadratic form to zero, resulting in .. math:: :nowrap: \[ \mathbf{x}_{\textrm{opt}}=\mathbf{x}_{0}-\mathbf{H}^{-1}\nabla f.\] The inverse of the Hessian is evaluated using the conjugate-gradient method. An example of employing this method to minimizing the Rosenbrock function is given below. To take full advantage of the Newton-CG method, a function which computes the Hessian must be provided. The Hessian matrix itself does not need to be constructed, only a vector which is the product of the Hessian with an arbitrary vector needs to be available to the minimization routine. As a result, the user can provide either a function to compute the Hessian matrix, or a function to compute the product of the Hessian with an arbitrary vector. Full Hessian example: """"""""""""""""""""" The Hessian of the Rosenbrock function is .. math:: :nowrap: \begin{eqnarray*} H_{ij}=\frac{\partial^{2}f}{\partial x_{i}\partial x_{j}} & = & 200\left(\delta_{i,j}-2x_{i-1}\delta_{i-1,j}\right)-400x_{i}\left(\delta_{i+1,j}-2x_{i}\delta_{i,j}\right)-400\delta_{i,j}\left(x_{i+1}-x_{i}^{2}\right)+2\delta_{i,j},\\ & = & \left(202+1200x_{i}^{2}-400x_{i+1}\right)\delta_{i,j}-400x_{i}\delta_{i+1,j}-400x_{i-1}\delta_{i-1,j},\end{eqnarray*} if :math:`i,j\in\left[1,N-2\right]` with :math:`i,j\in\left[0,N-1\right]` defining the :math:`N\times N` matrix. Other non-zero entries of the matrix are .. math:: :nowrap: \begin{eqnarray*} \frac{\partial^{2}f}{\partial x_{0}^{2}} & = & 1200x_{0}^{2}-400x_{1}+2,\\ \frac{\partial^{2}f}{\partial x_{0}\partial x_{1}}=\frac{\partial^{2}f}{\partial x_{1}\partial x_{0}} & = & -400x_{0},\\ \frac{\partial^{2}f}{\partial x_{N-1}\partial x_{N-2}}=\frac{\partial^{2}f}{\partial x_{N-2}\partial x_{N-1}} & = & -400x_{N-2},\\ \frac{\partial^{2}f}{\partial x_{N-1}^{2}} & = & 200.\end{eqnarray*} For example, the Hessian when :math:`N=5` is .. math:: :nowrap: \[ \mathbf{H}=\left[\begin{array}{ccccc} 1200x_{0}^{2}-400x_{1}+2 & -400x_{0} & 0 & 0 & 0\\ -400x_{0} & 202+1200x_{1}^{2}-400x_{2} & -400x_{1} & 0 & 0\\ 0 & -400x_{1} & 202+1200x_{2}^{2}-400x_{3} & -400x_{2} & 0\\ 0 & & -400x_{2} & 202+1200x_{3}^{2}-400x_{4} & -400x_{3}\\ 0 & 0 & 0 & -400x_{3} & 200\end{array}\right].\] The code which computes this Hessian along with the code to minimize the function using Newton-CG method is shown in the following example: >>> def rosen_hess(x): ... x = np.asarray(x) ... H = np.diag(-400*x[:-1],1) - np.diag(400*x[:-1],-1) ... diagonal = np.zeros_like(x) ... diagonal[0] = 1200*x[0]**2-400*x[1]+2 ... diagonal[-1] = 200 ... diagonal[1:-1] = 202 + 1200*x[1:-1]**2 - 400*x[2:] ... H = H + np.diag(diagonal) ... return H >>> res = minimize(rosen, x0, method='Newton-CG', ... jac=rosen_der, hess=rosen_hess, ... options={'avextol': 1e-8, 'disp': True}) Optimization terminated successfully. Current function value: 0.000000 Iterations: 19 Function evaluations: 22 Gradient evaluations: 19 Hessian evaluations: 19 >>> print(res.x) [ 1. 1. 1. 1. 1.] Hessian product example: """""""""""""""""""""""" For larger minimization problems, storing the entire Hessian matrix can consume considerable time and memory. The Newton-CG algorithm only needs the product of the Hessian times an arbitrary vector. As a result, the user can supply code to compute this product rather than the full Hessian by giving a ``hess`` function which take the minimization vector as the first argument and the arbitrary vector as the second argument (along with extra arguments passed to the function to be minimized). If possible, using Newton-CG with the Hessian product option is probably the fastest way to minimize the function. In this case, the product of the Rosenbrock Hessian with an arbitrary vector is not difficult to compute. If :math:`\mathbf{p}` is the arbitrary vector, then :math:`\mathbf{H}\left(\mathbf{x}\right)\mathbf{p}` has elements: .. math:: :nowrap: \[ \mathbf{H}\left(\mathbf{x}\right)\mathbf{p}=\left[\begin{array}{c} \left(1200x_{0}^{2}-400x_{1}+2\right)p_{0}-400x_{0}p_{1}\\ \vdots\\ -400x_{i-1}p_{i-1}+\left(202+1200x_{i}^{2}-400x_{i+1}\right)p_{i}-400x_{i}p_{i+1}\\ \vdots\\ -400x_{N-2}p_{N-2}+200p_{N-1}\end{array}\right].\] Code which makes use of this Hessian product to minimize the Rosenbrock function using :func:`minimize` follows: >>> def rosen_hess_p(x,p): ... x = np.asarray(x) ... Hp = np.zeros_like(x) ... Hp[0] = (1200*x[0]**2 - 400*x[1] + 2)*p[0] - 400*x[0]*p[1] ... Hp[1:-1] = -400*x[:-2]*p[:-2]+(202+1200*x[1:-1]**2-400*x[2:])*p[1:-1] \ ... -400*x[1:-1]*p[2:] ... Hp[-1] = -400*x[-2]*p[-2] + 200*p[-1] ... return Hp >>> res = minimize(rosen, x0, method='Newton-CG', ... jac=rosen_der, hess=rosen_hess_p, ... options={'avextol': 1e-8, 'disp': True}) Optimization terminated successfully. Current function value: 0.000000 Iterations: 20 Function evaluations: 23 Gradient evaluations: 20 Hessian evaluations: 44 >>> print(res.x) [ 1. 1. 1. 1. 1.] .. _tutorial-sqlsp: Constrained minimization of multivariate scalar functions (:func:`minimize`) ---------------------------------------------------------------------------- The :func:`minimize` function also provides an interface to several constrained minimization algorithm. As an example, the Sequential Least SQuares Programming optimization algorithm (SLSQP) will be considered here. This algorithm allows to deal with constrained minimization problems of the form: .. math:: :nowrap: \begin{eqnarray*} \min F(x) \\ \text{subject to } & C_j(X) = 0 , &j = 1,...,\text{MEQ}\\ & C_j(x) \geq 0 , &j = \text{MEQ}+1,...,M\\ & XL \leq x \leq XU , &I = 1,...,N. \end{eqnarray*} As an example, let us consider the problem of maximizing the function: .. math:: :nowrap: \[ f(x, y) = 2 x y + 2 x - x^2 - 2 y^2 \] subject to an equality and an inequality constraints defined as: .. math:: :nowrap: \[ x^3 - y = 0 \] \[ y - 1 \geq 0 \] The objective function and its derivative are defined as follows. >>> def func(x, sign=1.0): ... """ Objective function """ ... return sign*(2*x[0]*x[1] + 2*x[0] - x[0]**2 - 2*x[1]**2) >>> def func_deriv(x, sign=1.0): ... """ Derivative of objective function """ ... dfdx0 = sign*(-2*x[0] + 2*x[1] + 2) ... dfdx1 = sign*(2*x[0] - 4*x[1]) ... return np.array([ dfdx0, dfdx1 ]) Note that since :func:`minimize` only minimizes functions, the ``sign`` parameter is introduced to multiply the objective function (and its derivative by -1) in order to perform a maximization. Then constraints are defined as a sequence of dictionaries, with keys ``type``, ``fun`` and ``jac``. >>> cons = ({'type': 'eq', ... 'fun' : lambda x: np.array([x[0]**3 - x[1]]), ... 'jac' : lambda x: np.array([3.0*(x[0]**2.0), -1.0])}, ... {'type': 'ineq', ... 'fun' : lambda x: np.array([x[1] - 1]), ... 'jac' : lambda x: np.array([0.0, 1.0])}) Now an unconstrained optimization can be performed as: >>> res = minimize(func, [-1.0,1.0], args=(-1.0,), jac=func_deriv, ... method='SLSQP', options={'disp': True}) Optimization terminated successfully. (Exit mode 0) Current function value: -2.0 Iterations: 4 Function evaluations: 5 Gradient evaluations: 4 >>> print(res.x) [ 2. 1.] and a constrained optimization as: >>> res = minimize(func, [-1.0,1.0], args=(-1.0,), jac=func_deriv, ... constraints=cons, method='SLSQP', options={'disp': True}) Optimization terminated successfully. (Exit mode 0) Current function value: -1.00000018311 Iterations: 9 Function evaluations: 14 Gradient evaluations: 9 >>> print(res.x) [ 1.00000009 1. ] Least-square fitting (:func:`leastsq`) -------------------------------------- All of the previously-explained minimization procedures can be used to solve a least-squares problem provided the appropriate objective function is constructed. For example, suppose it is desired to fit a set of data :math:`\left\{\mathbf{x}_{i}, \mathbf{y}_{i}\right\}` to a known model, :math:`\mathbf{y}=\mathbf{f}\left(\mathbf{x},\mathbf{p}\right)` where :math:`\mathbf{p}` is a vector of parameters for the model that need to be found. A common method for determining which parameter vector gives the best fit to the data is to minimize the sum of squares of the residuals. The residual is usually defined for each observed data-point as .. math:: :nowrap: \[ e_{i}\left(\mathbf{p},\mathbf{y}_{i},\mathbf{x}_{i}\right)=\left\Vert \mathbf{y}_{i}-\mathbf{f}\left(\mathbf{x}_{i},\mathbf{p}\right)\right\Vert .\] An objective function to pass to any of the previous minization algorithms to obtain a least-squares fit is. .. math:: :nowrap: \[ J\left(\mathbf{p}\right)=\sum_{i=0}^{N-1}e_{i}^{2}\left(\mathbf{p}\right).\] The :obj:`leastsq` algorithm performs this squaring and summing of the residuals automatically. It takes as an input argument the vector function :math:`\mathbf{e}\left(\mathbf{p}\right)` and returns the value of :math:`\mathbf{p}` which minimizes :math:`J\left(\mathbf{p}\right)=\mathbf{e}^{T}\mathbf{e}` directly. The user is also encouraged to provide the Jacobian matrix of the function (with derivatives down the columns or across the rows). If the Jacobian is not provided, it is estimated. An example should clarify the usage. Suppose it is believed some measured data follow a sinusoidal pattern .. math:: :nowrap: \[ y_{i}=A\sin\left(2\pi kx_{i}+\theta\right)\] where the parameters :math:`A,` :math:`k` , and :math:`\theta` are unknown. The residual vector is .. math:: :nowrap: \[ e_{i}=\left|y_{i}-A\sin\left(2\pi kx_{i}+\theta\right)\right|.\] By defining a function to compute the residuals and (selecting an appropriate starting position), the least-squares fit routine can be used to find the best-fit parameters :math:`\hat{A},\,\hat{k},\,\hat{\theta}`. This is shown in the following example: .. plot:: >>> from numpy import * >>> x = arange(0,6e-2,6e-2/30) >>> A,k,theta = 10, 1.0/3e-2, pi/6 >>> y_true = A*sin(2*pi*k*x+theta) >>> y_meas = y_true + 2*random.randn(len(x)) >>> def residuals(p, y, x): ... A,k,theta = p ... err = y-A*sin(2*pi*k*x+theta) ... return err >>> def peval(x, p): ... return p[0]*sin(2*pi*p[1]*x+p[2]) >>> p0 = [8, 1/2.3e-2, pi/3] >>> print(array(p0)) [ 8. 43.4783 1.0472] >>> from scipy.optimize import leastsq >>> plsq = leastsq(residuals, p0, args=(y_meas, x)) >>> print(plsq[0]) [ 10.9437 33.3605 0.5834] >>> print(array([A, k, theta])) [ 10. 33.3333 0.5236] >>> import matplotlib.pyplot as plt >>> plt.plot(x,peval(x,plsq[0]),x,y_meas,'o',x,y_true) >>> plt.title('Least-squares fit to noisy data') >>> plt.legend(['Fit', 'Noisy', 'True']) >>> plt.show() .. :caption: Least-square fitting to noisy data using .. :obj:`scipy.optimize.leastsq` Univariate function minimizers (:func:`minimize_scalar`) -------------------------------------------------------- Often only the minimum of an univariate function (i.e. a function that takes a scalar as input) is needed. In these circumstances, other optimization techniques have been developed that can work faster. These are accessible from the :func:`minimize_scalar` function which proposes several algorithms. Unconstrained minimization (``method='brent'``) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ There are actually two methods that can be used to minimize an univariate function: `brent` and `golden`, but `golden` is included only for academic purposes and should rarely be used. These can be respectively selected through the `method` parameter in :func:`minimize_scalar`. The `brent` method uses Brent's algorithm for locating a minimum. Optimally a bracket (the `bs` parameter) should be given which contains the minimum desired. A bracket is a triple :math:`\left( a, b, c \right)` such that :math:`f \left( a \right) > f \left( b \right) < f \left( c \right)` and :math:`a < b < c` . If this is not given, then alternatively two starting points can be chosen and a bracket will be found from these points using a simple marching algorithm. If these two starting points are not provided `0` and `1` will be used (this may not be the right choice for your function and result in an unexpected minimum being returned). Here is an example: >>> from scipy.optimize import minimize_scalar >>> f = lambda x: (x - 2) * (x + 1)**2 >>> res = minimize_scalar(f, method='brent') >>> print(res.x) 1.0 Bounded minimization (``method='bounded'``) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Very often, there are constraints that can be placed on the solution space before minimization occurs. The `bounded` method in :func:`minimize_scalar` is an example of a constrained minimization procedure that provides a rudimentary interval constraint for scalar functions. The interval constraint allows the minimization to occur only between two fixed endpoints, specified using the mandatory `bs` parameter. For example, to find the minimum of :math:`J_{1}\left( x \right)` near :math:`x=5` , :func:`minimize_scalar` can be called using the interval :math:`\left[ 4, 7 \right]` as a constraint. The result is :math:`x_{\textrm{min}}=5.3314` : >>> from scipy.special import j1 >>> res = minimize_scalar(j1, bs=(4, 7), method='bounded') >>> print(res.x) 5.33144184241 Root finding ------------ Scalar functions ^^^^^^^^^^^^^^^^ If one has a single-variable equation, there are four different root finding algorithms that can be tried. Each of these algorithms requires the endpoints of an interval in which a root is expected (because the function changes signs). In general :obj:`brentq` is the best choice, but the other methods may be useful in certain circumstances or for academic purposes. Fixed-point solving ^^^^^^^^^^^^^^^^^^^ A problem closely related to finding the zeros of a function is the problem of finding a fixed-point of a function. A fixed point of a function is the point at which evaluation of the function returns the point: :math:`g\left(x\right)=x.` Clearly the fixed point of :math:`g` is the root of :math:`f\left(x\right)=g\left(x\right)-x.` Equivalently, the root of :math:`f` is the fixed_point of :math:`g\left(x\right)=f\left(x\right)+x.` The routine :obj:`fixed_point` provides a simple iterative method using Aitkens sequence acceleration to estimate the fixed point of :math:`g` given a starting point. Sets of equations ^^^^^^^^^^^^^^^^^ Finding a root of a set of non-linear equations can be achieve using the :func:`root` function. Several methods are available, amongst which ``hybr`` (the default) and ``lm`` which respectively use the hybrid method of Powell and the Levenberg-Marquardt method from MINPACK. The following example considers the single-variable transcendental equation .. math:: :nowrap: \[ x+2\cos\left(x\right)=0,\] a root of which can be found as follows:: >>> import numpy as np >>> from scipy.optimize import root >>> def func(x): ... return x + 2 * np.cos(x) >>> sol = root(func, 0.3) >>> sol.x array([-1.02986653]) >>> sol.fun array([ -6.66133815e-16]) Consider now a set of non-linear equations .. math:: :nowrap: \begin{eqnarray*} x_{0}\cos\left(x_{1}\right) & = & 4,\\ x_{0}x_{1}-x_{1} & = & 5. \end{eqnarray*} We define the objective function so that it also returns the Jacobian and indicate this by setting the ``jac`` parameter to ``True``. Also, the Levenberg-Marquardt solver is used here. :: >>> def func2(x): ... f = [x[0] * np.cos(x[1]) - 4, ... x[1]*x[0] - x[1] - 5] ... df = np.array([[np.cos(x[1]), -x[0] * np.sin(x[1])], ... [x[1], x[0] - 1]]) ... return f, df >>> sol = root(func2, [1, 1], jac=True, method='lm') >>> sol.x array([ 6.50409711, 0.90841421]) Root finding for large problems ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Methods ``hybr`` and ``lm`` in :func:`root` cannot deal with a very large number of variables (*N*), as they need to calculate and invert a dense *N x N* Jacobian matrix on every Newton step. This becomes rather inefficient when *N* grows. Consider for instance the following problem: we need to solve the following integrodifferential equation on the square :math:`[0,1]\times[0,1]`: .. math:: (\partial_x^2 + \partial_y^2) P + 5 \left(\int_0^1\int_0^1\cosh(P)\,dx\,dy\right)^2 = 0 with the boundary condition :math:`P(x,1) = 1` on the upper edge and :math:`P=0` elsewhere on the boundary of the square. This can be done by approximating the continuous function *P* by its values on a grid, :math:`P_{n,m}\approx{}P(n h, m h)`, with a small grid spacing *h*. The derivatives and integrals can then be approximated; for instance :math:`\partial_x^2 P(x,y)\approx{}(P(x+h,y) - 2 P(x,y) + P(x-h,y))/h^2`. The problem is then equivalent to finding the root of some function ``residual(P)``, where ``P`` is a vector of length :math:`N_x N_y`. Now, because :math:`N_x N_y` can be large, methods ``hybr`` or ``lm`` in :func:`root` will take a long time to solve this problem. The solution can however be found using one of the large-scale solvers, for example ``krylov``, ``broyden2``, or ``anderson``. These use what is known as the inexact Newton method, which instead of computing the Jacobian matrix exactly, forms an approximation for it. The problem we have can now be solved as follows: .. plot:: import numpy as np from scipy.optimize import root from numpy import cosh, zeros_like, mgrid, zeros # parameters nx, ny = 75, 75 hx, hy = 1./(nx-1), 1./(ny-1) P_left, P_right = 0, 0 P_top, P_bottom = 1, 0 def residual(P): d2x = zeros_like(P) d2y = zeros_like(P) d2x[1:-1] = (P[2:] - 2*P[1:-1] + P[:-2]) / hx/hx d2x[0] = (P[1] - 2*P[0] + P_left)/hx/hx d2x[-1] = (P_right - 2*P[-1] + P[-2])/hx/hx d2y[:,1:-1] = (P[:,2:] - 2*P[:,1:-1] + P[:,:-2])/hy/hy d2y[:,0] = (P[:,1] - 2*P[:,0] + P_bottom)/hy/hy d2y[:,-1] = (P_top - 2*P[:,-1] + P[:,-2])/hy/hy return d2x + d2y + 5*cosh(P).mean()**2 # solve guess = zeros((nx, ny), float) sol = root(residual, guess, method='krylov', options={'disp': True}) #sol = root(residual, guess, method='broyden2', options={'disp': True, 'max_rank': 50}) #sol = root(residual, guess, method='anderson', options={'disp': True, 'M': 10}) print('Residual: %g' % abs(residual(sol.x)).max()) # visualize import matplotlib.pyplot as plt x, y = mgrid[0:1:(nx*1j), 0:1:(ny*1j)] plt.pcolor(x, y, sol.x) plt.colorbar() plt.show() Still too slow? Preconditioning. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ When looking for the zero of the functions :math:`f_i({\bf x}) = 0`, *i = 1, 2, ..., N*, the ``krylov`` solver spends most of its time inverting the Jacobian matrix, .. math:: J_{ij} = \frac{\partial f_i}{\partial x_j} . If you have an approximation for the inverse matrix :math:`M\approx{}J^{-1}`, you can use it for *preconditioning* the linear inversion problem. The idea is that instead of solving :math:`J{\bf s}={\bf y}` one solves :math:`MJ{\bf s}=M{\bf y}`: since matrix :math:`MJ` is "closer" to the identity matrix than :math:`J` is, the equation should be easier for the Krylov method to deal with. The matrix *M* can be passed to :func:`root` with method ``krylov`` as an option ``options['jac_options']['inner_M']``. It can be a (sparse) matrix or a :obj:`scipy.sparse.linalg.LinearOperator` instance. For the problem in the previous section, we note that the function to solve consists of two parts: the first one is application of the Laplace operator, :math:`[\partial_x^2 + \partial_y^2] P`, and the second is the integral. We can actually easily compute the Jacobian corresponding to the Laplace operator part: we know that in one dimension .. math:: \partial_x^2 \approx \frac{1}{h_x^2} \begin{pmatrix} -2 & 1 & 0 & 0 \cdots \\ 1 & -2 & 1 & 0 \cdots \\ 0 & 1 & -2 & 1 \cdots \\ \ldots \end{pmatrix} = h_x^{-2} L so that the whole 2-D operator is represented by .. math:: J_1 = \partial_x^2 + \partial_y^2 \simeq h_x^{-2} L \otimes I + h_y^{-2} I \otimes L The matrix :math:`J_2` of the Jacobian corresponding to the integral is more difficult to calculate, and since *all* of it entries are nonzero, it will be difficult to invert. :math:`J_1` on the other hand is a relatively simple matrix, and can be inverted by :obj:`scipy.sparse.linalg.splu` (or the inverse can be approximated by :obj:`scipy.sparse.linalg.spilu`). So we are content to take :math:`M\approx{}J_1^{-1}` and hope for the best. In the example below, we use the preconditioner :math:`M=J_1^{-1}`. .. literalinclude:: examples/newton_krylov_preconditioning.py Resulting run, first without preconditioning:: 0: |F(x)| = 803.614; step 1; tol 0.000257947 1: |F(x)| = 345.912; step 1; tol 0.166755 2: |F(x)| = 139.159; step 1; tol 0.145657 3: |F(x)| = 27.3682; step 1; tol 0.0348109 4: |F(x)| = 1.03303; step 1; tol 0.00128227 5: |F(x)| = 0.0406634; step 1; tol 0.00139451 6: |F(x)| = 0.00344341; step 1; tol 0.00645373 7: |F(x)| = 0.000153671; step 1; tol 0.00179246 8: |F(x)| = 6.7424e-06; step 1; tol 0.00173256 Residual 3.57078908664e-07 Evaluations 317 and then with preconditioning:: 0: |F(x)| = 136.993; step 1; tol 7.49599e-06 1: |F(x)| = 4.80983; step 1; tol 0.00110945 2: |F(x)| = 0.195942; step 1; tol 0.00149362 3: |F(x)| = 0.000563597; step 1; tol 7.44604e-06 4: |F(x)| = 1.00698e-09; step 1; tol 2.87308e-12 Residual 9.29603061195e-11 Evaluations 77 Using a preconditioner reduced the number of evaluations of the ``residual`` function by a factor of *4*. For problems where the residual is expensive to compute, good preconditioning can be crucial --- it can even decide whether the problem is solvable in practice or not. Preconditioning is an art, science, and industry. Here, we were lucky in making a simple choice that worked reasonably well, but there is a lot more depth to this topic than is shown here. .. rubric:: References Some further reading and related software: .. [KK] D.A. Knoll and D.E. Keyes, "Jacobian-free Newton-Krylov methods", J. Comp. Phys. 193, 357 (2003). .. [PP] PETSc http://www.mcs.anl.gov/petsc/ and its Python bindings http://code.google.com/p/petsc4py/ .. [AMG] PyAMG (algebraic multigrid preconditioners/solvers) http://code.google.com/p/pyamg/ numpy-1.8.2/doc/scipy-sphinx-theme/index.rst0000664000175100017510000000116412370216246022175 0ustar vagrantvagrant00000000000000.. scipy-sphinx-theme documentation master file, created by sphinx-quickstart on Sun Apr 21 11:22:24 2013. You can adapt this file completely to your liking, but it should at least contain the root `toctree` directive. Welcome to scipy-sphinx-theme's documentation! ============================================== The theme is under `_theme`, this document contains various test pages. Contents: .. toctree:: :maxdepth: 2 README test_optimize test_autodoc test_autodoc_2 test_autodoc_3 test_autodoc_4 Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search` numpy-1.8.2/doc/scipy-sphinx-theme/test_autodoc_3.rst0000664000175100017510000000014612370216246024004 0ustar vagrantvagrant00000000000000scipy.odr.ODR.run ================= .. currentmodule:: scipy.odr .. automethod:: scipy.odr.ODR.run numpy-1.8.2/doc/scipy-sphinx-theme/test_autodoc_2.rst0000664000175100017510000000021212370216246023775 0ustar vagrantvagrant00000000000000scipy.interpolate.griddata ========================== .. currentmodule:: scipy.interpolate .. autofunction:: scipy.interpolate.griddata numpy-1.8.2/doc/scipy-sphinx-theme/_theme/0000775000175100017510000000000012371375427021603 5ustar vagrantvagrant00000000000000numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/0000775000175100017510000000000012371375427022732 5ustar vagrantvagrant00000000000000numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/theme.conf0000664000175100017510000000025512370216246024675 0ustar vagrantvagrant00000000000000[theme] inherit = basic stylesheet = scipy.css pygments_style = friendly [options] edit_link = false rootlinks = [] sidebar = left scipy_org_logo = navigation_links = true numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/0000775000175100017510000000000012371375427024221 5ustar vagrantvagrant00000000000000numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/css/0000775000175100017510000000000012371375427025011 5ustar vagrantvagrant00000000000000numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/css/spc-extend.css0000664000175100017510000000351112370216245027564 0ustar vagrantvagrant00000000000000body { background-color: #f9faf5; } .container { width: 80%; } .main { background-color: white; padding: 18px; -moz-box-shadow: 0 0 3px #888; -webkit-box-shadow: 0 0 3px #888; box-shadow: 0 0 3px #888; } .underline { border-bottom: 1.5px solid #eeeeee; } .header { margin-top: 15px; margin-bottom: 15px; margin-left: 0px; margin-right: 0px; } .spc-navbar { margin-top: 15px; margin-bottom: 5px; margin-left: 0px; margin-right: 0px; } .spc-navbar .nav-pills { margin-bottom: 0px; font-size: 12px; } .spc-navbar .nav-pills > li > a { padding-top: 2.5px; padding-bottom: 2.5px; } .underline { border-bottom: 1.5px solid #eeeeee; } .spc-page-title h1, .spc-page-title h2, .spc-page-title h3, .spc-page-title h4 { font-weight: normal; border-bottom: 1.5px solid #eeeeee; } .tags .btn { border: none; font-size: 9.5px; font-weight: bold; } .spc-search-result-title h1, .spc-search-result-title h2, .spc-search-result-title h3, .spc-search-result-title h4 { font-weight: normal; } .spc-snippet-header { margin-bottom: 5px; } .spc-snippet-info { padding-top: 10px; } .spc-snippet-info .dl-horizontal { margin: 5px; } .spc-snippet-info .dl-horizontal dt { font-weight: normal; } .spc-snippet-body { padding: 10px; } .spc-snippet-body .accordion-group { border: none; } .spc-snippet-body .accordion-heading { text-transform: uppercase; font-size: 14px; border-bottom: 1px solid #e5e5e5; } .spc-snippet-body .accordion-heading .accordion-toggle { padding-top: 10px; padding-bottom: 5px; } .spc-rightsidebar { color: #555555; } .spc-rightsidebar .navigation { padding: 2px 10px; font-size: 11.9px; } .spc-rightsidebar .navigation .nav-title { font-weight: bold; text-transform: uppercase; } .spc-rightsidebar .navigation li { margin: 5px; } .footer { padding: 5px; font-size: small; } numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/css/spc-bootstrap.css0000664000175100017510000053513412370216245030325 0ustar vagrantvagrant00000000000000@import url(http://fonts.googleapis.com/css?family=Open+Sans); /*! * Bootstrap v2.3.1 * * Copyright 2012 Twitter, Inc * Licensed under the Apache License v2.0 * http://www.apache.org/licenses/LICENSE-2.0 * * Designed and built with all the love in the world @twitter by @mdo and @fat. */ .clearfix { *zoom: 1; } .clearfix:before, .clearfix:after { display: table; content: ""; line-height: 0; } .clearfix:after { clear: both; } .hide-text { font: 0/0 a; color: transparent; text-shadow: none; background-color: transparent; border: 0; } .input-block-level { display: block; width: 100%; min-height: 29px; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } article, aside, details, figcaption, figure, footer, header, hgroup, nav, section { display: block; } audio, canvas, video { display: inline-block; *display: inline; *zoom: 1; } audio:not([controls]) { display: none; } html { font-size: 100%; -webkit-text-size-adjust: 100%; -ms-text-size-adjust: 100%; } a:focus { outline: thin dotted #333; outline: 5px auto -webkit-focus-ring-color; outline-offset: -2px; } a:hover, a:active { outline: 0; } sub, sup { position: relative; font-size: 75%; line-height: 0; vertical-align: baseline; } sup { top: -0.5em; } sub { bottom: -0.25em; } img { /* Responsive images (ensure images don't scale beyond their parents) */ max-width: 100%; /* Part 1: Set a maxium relative to the parent */ width: auto\9; /* IE7-8 need help adjusting responsive images */ height: auto; /* Part 2: Scale the height according to the width, otherwise you get stretching */ vertical-align: middle; border: 0; -ms-interpolation-mode: bicubic; } #map_canvas img, .google-maps img { max-width: none; } button, input, select, textarea { margin: 0; font-size: 100%; vertical-align: middle; } button, input { *overflow: visible; line-height: normal; } button::-moz-focus-inner, input::-moz-focus-inner { padding: 0; border: 0; } button, html input[type="button"], input[type="reset"], input[type="submit"] { -webkit-appearance: button; cursor: pointer; } label, select, button, input[type="button"], input[type="reset"], input[type="submit"], input[type="radio"], input[type="checkbox"] { cursor: pointer; } input[type="search"] { -webkit-box-sizing: content-box; -moz-box-sizing: content-box; box-sizing: content-box; -webkit-appearance: textfield; } input[type="search"]::-webkit-search-decoration, input[type="search"]::-webkit-search-cancel-button { -webkit-appearance: none; } textarea { overflow: auto; vertical-align: top; } @media print { * { text-shadow: none !important; color: #000 !important; background: transparent !important; box-shadow: none !important; } a, a:visited { text-decoration: underline; } a[href]:after { content: " (" attr(href) ")"; } abbr[title]:after { content: " (" attr(title) ")"; } .ir a:after, a[href^="javascript:"]:after, a[href^="#"]:after { content: ""; } pre, blockquote { border: 1px solid #999; page-break-inside: avoid; } thead { display: table-header-group; } tr, img { page-break-inside: avoid; } img { max-width: 100% !important; } @page { margin: 0.5cm; } p, h2, h3 { orphans: 3; widows: 3; } h2, h3 { page-break-after: avoid; } } body { margin: 0; font-family: 'Open Sans', sans-serif; font-size: 13px; line-height: 19px; color: #333333; background-color: #ffffff; } a { color: #0088cc; text-decoration: none; } a:hover, a:focus { color: #005580; text-decoration: underline; } .img-rounded { -webkit-border-radius: 6px; -moz-border-radius: 6px; border-radius: 6px; } .img-polaroid { padding: 4px; background-color: #fff; border: 1px solid #ccc; border: 1px solid rgba(0, 0, 0, 0.2); -webkit-box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1); -moz-box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1); box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1); } .img-circle { -webkit-border-radius: 500px; -moz-border-radius: 500px; border-radius: 500px; } .row { margin-left: -20px; *zoom: 1; } .row:before, .row:after { display: table; content: ""; line-height: 0; } .row:after { clear: both; } .row:before, .row:after { display: table; content: ""; line-height: 0; } .row:after { clear: both; } [class*="span"] { float: left; min-height: 1px; margin-left: 20px; } .container, .navbar-static-top .container, .navbar-fixed-top .container, .navbar-fixed-bottom .container { width: 940px; } .span12 { width: 940px; } .span11 { width: 860px; } .span10 { width: 780px; } .span9 { width: 700px; } .span8 { width: 620px; } .span7 { width: 540px; } .span6 { width: 460px; } .span5 { width: 380px; } .span4 { width: 300px; } .span3 { width: 220px; } .span2 { width: 140px; } .span1 { width: 60px; } .offset12 { margin-left: 980px; } .offset11 { margin-left: 900px; } .offset10 { margin-left: 820px; } .offset9 { margin-left: 740px; } .offset8 { margin-left: 660px; } .offset7 { margin-left: 580px; } .offset6 { margin-left: 500px; } .offset5 { margin-left: 420px; } .offset4 { margin-left: 340px; } .offset3 { margin-left: 260px; } .offset2 { margin-left: 180px; } .offset1 { margin-left: 100px; } .row { margin-left: -20px; *zoom: 1; } .row:before, .row:after { display: table; content: ""; line-height: 0; } .row:after { clear: both; } .row:before, .row:after { display: table; content: ""; line-height: 0; } .row:after { clear: both; } [class*="span"] { float: left; min-height: 1px; margin-left: 20px; } .container, .navbar-static-top .container, .navbar-fixed-top .container, .navbar-fixed-bottom .container { width: 940px; } .span12 { width: 940px; } .span11 { width: 860px; } .span10 { width: 780px; } .span9 { width: 700px; } .span8 { width: 620px; } .span7 { width: 540px; } .span6 { width: 460px; } .span5 { width: 380px; } .span4 { width: 300px; } .span3 { width: 220px; } .span2 { width: 140px; } .span1 { width: 60px; } .offset12 { margin-left: 980px; } .offset11 { margin-left: 900px; } .offset10 { margin-left: 820px; } .offset9 { margin-left: 740px; } .offset8 { margin-left: 660px; } .offset7 { margin-left: 580px; } .offset6 { margin-left: 500px; } .offset5 { margin-left: 420px; } .offset4 { margin-left: 340px; } .offset3 { margin-left: 260px; } .offset2 { margin-left: 180px; } .offset1 { margin-left: 100px; } .row-fluid { width: 100%; *zoom: 1; } .row-fluid:before, .row-fluid:after { display: table; content: ""; line-height: 0; } .row-fluid:after { clear: both; } .row-fluid:before, .row-fluid:after { display: table; content: ""; line-height: 0; } .row-fluid:after { clear: both; } .row-fluid [class*="span"] { display: block; width: 100%; min-height: 29px; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; float: left; margin-left: 2.127659574468085%; *margin-left: 2.074468085106383%; } .row-fluid [class*="span"]:first-child { margin-left: 0; } .row-fluid .controls-row [class*="span"] + [class*="span"] { margin-left: 2.127659574468085%; } .row-fluid .span12 { width: 100%; *width: 99.94680851063829%; } .row-fluid .span11 { width: 91.48936170212765%; *width: 91.43617021276594%; } .row-fluid .span10 { width: 82.97872340425532%; *width: 82.92553191489361%; } .row-fluid .span9 { width: 74.46808510638297%; *width: 74.41489361702126%; } .row-fluid .span8 { width: 65.95744680851064%; *width: 65.90425531914893%; } .row-fluid .span7 { width: 57.44680851063829%; *width: 57.39361702127659%; } .row-fluid .span6 { width: 48.93617021276595%; *width: 48.88297872340425%; } .row-fluid .span5 { width: 40.42553191489362%; *width: 40.37234042553192%; } .row-fluid .span4 { width: 31.914893617021278%; *width: 31.861702127659576%; } .row-fluid .span3 { width: 23.404255319148934%; *width: 23.351063829787233%; } .row-fluid .span2 { width: 14.893617021276595%; *width: 14.840425531914894%; } .row-fluid .span1 { width: 6.382978723404255%; *width: 6.329787234042553%; } .row-fluid .offset12 { margin-left: 104.25531914893617%; *margin-left: 104.14893617021275%; } .row-fluid .offset12:first-child { margin-left: 102.12765957446808%; *margin-left: 102.02127659574467%; } .row-fluid .offset11 { margin-left: 95.74468085106382%; *margin-left: 95.6382978723404%; } .row-fluid .offset11:first-child { margin-left: 93.61702127659574%; *margin-left: 93.51063829787232%; } .row-fluid .offset10 { margin-left: 87.23404255319149%; *margin-left: 87.12765957446807%; } .row-fluid .offset10:first-child { margin-left: 85.1063829787234%; *margin-left: 84.99999999999999%; } .row-fluid .offset9 { margin-left: 78.72340425531914%; *margin-left: 78.61702127659572%; } .row-fluid .offset9:first-child { margin-left: 76.59574468085106%; *margin-left: 76.48936170212764%; } .row-fluid .offset8 { margin-left: 70.2127659574468%; *margin-left: 70.10638297872339%; } .row-fluid .offset8:first-child { margin-left: 68.08510638297872%; *margin-left: 67.9787234042553%; } .row-fluid .offset7 { margin-left: 61.70212765957446%; *margin-left: 61.59574468085106%; } .row-fluid .offset7:first-child { margin-left: 59.574468085106375%; *margin-left: 59.46808510638297%; } .row-fluid .offset6 { margin-left: 53.191489361702125%; *margin-left: 53.085106382978715%; } .row-fluid .offset6:first-child { margin-left: 51.063829787234035%; *margin-left: 50.95744680851063%; } .row-fluid .offset5 { margin-left: 44.68085106382979%; *margin-left: 44.57446808510638%; } .row-fluid .offset5:first-child { margin-left: 42.5531914893617%; *margin-left: 42.4468085106383%; } .row-fluid .offset4 { margin-left: 36.170212765957444%; *margin-left: 36.06382978723405%; } .row-fluid .offset4:first-child { margin-left: 34.04255319148936%; *margin-left: 33.93617021276596%; } .row-fluid .offset3 { margin-left: 27.659574468085104%; *margin-left: 27.5531914893617%; } .row-fluid .offset3:first-child { margin-left: 25.53191489361702%; *margin-left: 25.425531914893618%; } .row-fluid .offset2 { margin-left: 19.148936170212764%; *margin-left: 19.04255319148936%; } .row-fluid .offset2:first-child { margin-left: 17.02127659574468%; *margin-left: 16.914893617021278%; } .row-fluid .offset1 { margin-left: 10.638297872340425%; *margin-left: 10.53191489361702%; } .row-fluid .offset1:first-child { margin-left: 8.51063829787234%; *margin-left: 8.404255319148938%; } .row-fluid { width: 100%; *zoom: 1; } .row-fluid:before, .row-fluid:after { display: table; content: ""; line-height: 0; } .row-fluid:after { clear: both; } .row-fluid:before, .row-fluid:after { display: table; content: ""; line-height: 0; } .row-fluid:after { clear: both; } .row-fluid [class*="span"] { display: block; width: 100%; min-height: 29px; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; float: left; margin-left: 2.127659574468085%; *margin-left: 2.074468085106383%; } .row-fluid [class*="span"]:first-child { margin-left: 0; } .row-fluid .controls-row [class*="span"] + [class*="span"] { margin-left: 2.127659574468085%; } .row-fluid .span12 { width: 100%; *width: 99.94680851063829%; } .row-fluid .span11 { width: 91.48936170212765%; *width: 91.43617021276594%; } .row-fluid .span10 { width: 82.97872340425532%; *width: 82.92553191489361%; } .row-fluid .span9 { width: 74.46808510638297%; *width: 74.41489361702126%; } .row-fluid .span8 { width: 65.95744680851064%; *width: 65.90425531914893%; } .row-fluid .span7 { width: 57.44680851063829%; *width: 57.39361702127659%; } .row-fluid .span6 { width: 48.93617021276595%; *width: 48.88297872340425%; } .row-fluid .span5 { width: 40.42553191489362%; *width: 40.37234042553192%; } .row-fluid .span4 { width: 31.914893617021278%; *width: 31.861702127659576%; } .row-fluid .span3 { width: 23.404255319148934%; *width: 23.351063829787233%; } .row-fluid .span2 { width: 14.893617021276595%; *width: 14.840425531914894%; } .row-fluid .span1 { width: 6.382978723404255%; *width: 6.329787234042553%; } .row-fluid .offset12 { margin-left: 104.25531914893617%; *margin-left: 104.14893617021275%; } .row-fluid .offset12:first-child { margin-left: 102.12765957446808%; *margin-left: 102.02127659574467%; } .row-fluid .offset11 { margin-left: 95.74468085106382%; *margin-left: 95.6382978723404%; } .row-fluid .offset11:first-child { margin-left: 93.61702127659574%; *margin-left: 93.51063829787232%; } .row-fluid .offset10 { margin-left: 87.23404255319149%; *margin-left: 87.12765957446807%; } .row-fluid .offset10:first-child { margin-left: 85.1063829787234%; *margin-left: 84.99999999999999%; } .row-fluid .offset9 { margin-left: 78.72340425531914%; *margin-left: 78.61702127659572%; } .row-fluid .offset9:first-child { margin-left: 76.59574468085106%; *margin-left: 76.48936170212764%; } .row-fluid .offset8 { margin-left: 70.2127659574468%; *margin-left: 70.10638297872339%; } .row-fluid .offset8:first-child { margin-left: 68.08510638297872%; *margin-left: 67.9787234042553%; } .row-fluid .offset7 { margin-left: 61.70212765957446%; *margin-left: 61.59574468085106%; } .row-fluid .offset7:first-child { margin-left: 59.574468085106375%; *margin-left: 59.46808510638297%; } .row-fluid .offset6 { margin-left: 53.191489361702125%; *margin-left: 53.085106382978715%; } .row-fluid .offset6:first-child { margin-left: 51.063829787234035%; *margin-left: 50.95744680851063%; } .row-fluid .offset5 { margin-left: 44.68085106382979%; *margin-left: 44.57446808510638%; } .row-fluid .offset5:first-child { margin-left: 42.5531914893617%; *margin-left: 42.4468085106383%; } .row-fluid .offset4 { margin-left: 36.170212765957444%; *margin-left: 36.06382978723405%; } .row-fluid .offset4:first-child { margin-left: 34.04255319148936%; *margin-left: 33.93617021276596%; } .row-fluid .offset3 { margin-left: 27.659574468085104%; *margin-left: 27.5531914893617%; } .row-fluid .offset3:first-child { margin-left: 25.53191489361702%; *margin-left: 25.425531914893618%; } .row-fluid .offset2 { margin-left: 19.148936170212764%; *margin-left: 19.04255319148936%; } .row-fluid .offset2:first-child { margin-left: 17.02127659574468%; *margin-left: 16.914893617021278%; } .row-fluid .offset1 { margin-left: 10.638297872340425%; *margin-left: 10.53191489361702%; } .row-fluid .offset1:first-child { margin-left: 8.51063829787234%; *margin-left: 8.404255319148938%; } [class*="span"].hide, .row-fluid [class*="span"].hide { display: none; } [class*="span"].pull-right, .row-fluid [class*="span"].pull-right { float: right; } .container { margin-right: auto; margin-left: auto; *zoom: 1; } .container:before, .container:after { display: table; content: ""; line-height: 0; } .container:after { clear: both; } .container:before, .container:after { display: table; content: ""; line-height: 0; } .container:after { clear: both; } .container:before, .container:after { display: table; content: ""; line-height: 0; } .container:after { clear: both; } .container:before, .container:after { display: table; content: ""; line-height: 0; } .container:after { clear: both; } .container-fluid { padding-right: 20px; padding-left: 20px; *zoom: 1; } .container-fluid:before, .container-fluid:after { display: table; content: ""; line-height: 0; } .container-fluid:after { clear: both; } .container-fluid:before, .container-fluid:after { display: table; content: ""; line-height: 0; } .container-fluid:after { clear: both; } p { margin: 0 0 9.5px; } .lead { margin-bottom: 19px; font-size: 19.5px; font-weight: 200; line-height: 28.5px; } small { font-size: 85%; } strong { font-weight: bold; } em { font-style: italic; } cite { font-style: normal; } .muted { color: #999999; } a.muted:hover, a.muted:focus { color: #808080; } .text-warning { color: #c09853; } a.text-warning:hover, a.text-warning:focus { color: #a47e3c; } .text-error { color: #b94a48; } a.text-error:hover, a.text-error:focus { color: #953b39; } .text-info { color: #3a87ad; } a.text-info:hover, a.text-info:focus { color: #2d6987; } .text-success { color: #468847; } a.text-success:hover, a.text-success:focus { color: #356635; } .text-left { text-align: left; } .text-right { text-align: right; } .text-center { text-align: center; } h1, h2, h3, h4, h5, h6 { margin: 9.5px 0; font-family: inherit; font-weight: bold; line-height: 19px; color: inherit; text-rendering: optimizelegibility; } h1 small, h2 small, h3 small, h4 small, h5 small, h6 small { font-weight: normal; line-height: 1; color: #999999; } h1, h2, h3 { line-height: 38px; } h1 { font-size: 35.75px; } h2 { font-size: 29.25px; } h3 { font-size: 22.75px; } h4 { font-size: 16.25px; } h5 { font-size: 13px; } h6 { font-size: 11.049999999999999px; } h1 small { font-size: 22.75px; } h2 small { font-size: 16.25px; } h3 small { font-size: 13px; } h4 small { font-size: 13px; } .page-header { padding-bottom: 8.5px; margin: 19px 0 28.5px; border-bottom: 1px solid #eeeeee; } ul, ol { padding: 0; margin: 0 0 9.5px 25px; } ul ul, ul ol, ol ol, ol ul { margin-bottom: 0; } li { line-height: 19px; } ul.unstyled, ol.unstyled { margin-left: 0; list-style: none; } ul.inline, ol.inline { margin-left: 0; list-style: none; } ul.inline > li, ol.inline > li { display: inline-block; *display: inline; /* IE7 inline-block hack */ *zoom: 1; padding-left: 5px; padding-right: 5px; } dl { margin-bottom: 19px; } dt, dd { line-height: 19px; } dt { font-weight: bold; } dd { margin-left: 9.5px; } .dl-horizontal { *zoom: 1; } .dl-horizontal:before, .dl-horizontal:after { display: table; content: ""; line-height: 0; } .dl-horizontal:after { clear: both; } .dl-horizontal:before, .dl-horizontal:after { display: table; content: ""; line-height: 0; } .dl-horizontal:after { clear: both; } .dl-horizontal dt { float: left; width: 160px; clear: left; text-align: right; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .dl-horizontal dd { margin-left: 180px; } hr { margin: 19px 0; border: 0; border-top: 1px solid #eeeeee; border-bottom: 1px solid #ffffff; } abbr[title], abbr[data-original-title] { cursor: help; border-bottom: 1px dotted #999999; } abbr.initialism { font-size: 90%; text-transform: uppercase; } blockquote { padding: 0 0 0 15px; margin: 0 0 19px; border-left: 5px solid #eeeeee; } blockquote p { margin-bottom: 0; font-size: 16.25px; font-weight: 300; line-height: 1.25; } blockquote small { display: block; line-height: 19px; color: #999999; } blockquote small:before { content: '\2014 \00A0'; } blockquote.pull-right { float: right; padding-right: 15px; padding-left: 0; border-right: 5px solid #eeeeee; border-left: 0; } blockquote.pull-right p, blockquote.pull-right small { text-align: right; } blockquote.pull-right small:before { content: ''; } blockquote.pull-right small:after { content: '\00A0 \2014'; } q:before, q:after, blockquote:before, blockquote:after { content: ""; } address { display: block; margin-bottom: 19px; font-style: normal; line-height: 19px; } code, pre { padding: 0 3px 2px; font-family: Monaco, Menlo, Consolas, "Courier New", monospace; font-size: 11px; color: #333333; -webkit-border-radius: 3px; -moz-border-radius: 3px; border-radius: 3px; } code { padding: 2px 4px; color: #d14; background-color: #f7f7f9; border: 1px solid #e1e1e8; white-space: nowrap; } pre { display: block; padding: 9px; margin: 0 0 9.5px; font-size: 12px; line-height: 19px; word-break: break-all; word-wrap: break-word; white-space: pre; white-space: pre-wrap; background-color: #f5f5f5; border: 1px solid #ccc; border: 1px solid rgba(0, 0, 0, 0.15); -webkit-border-radius: 4px; -moz-border-radius: 4px; border-radius: 4px; } pre.prettyprint { margin-bottom: 19px; } pre code { padding: 0; color: inherit; white-space: pre; white-space: pre-wrap; background-color: transparent; border: 0; } .pre-scrollable { max-height: 340px; overflow-y: scroll; } form { margin: 0 0 19px; } fieldset { padding: 0; margin: 0; border: 0; } legend { display: block; width: 100%; padding: 0; margin-bottom: 19px; font-size: 19.5px; line-height: 38px; color: #333333; border: 0; border-bottom: 1px solid #e5e5e5; } legend small { font-size: 14.25px; color: #999999; } label, input, button, select, textarea { font-size: 13px; font-weight: normal; line-height: 19px; } input, button, select, textarea { font-family: 'Open Sans', sans-serif; } label { display: block; margin-bottom: 5px; } select, textarea, input[type="text"], input[type="password"], input[type="datetime"], input[type="datetime-local"], input[type="date"], input[type="month"], input[type="time"], input[type="week"], input[type="number"], input[type="email"], input[type="url"], input[type="search"], input[type="tel"], input[type="color"], .uneditable-input { display: inline-block; height: 19px; padding: 4px 6px; margin-bottom: 9.5px; font-size: 13px; line-height: 19px; color: #555555; -webkit-border-radius: 4px; -moz-border-radius: 4px; border-radius: 4px; vertical-align: middle; } input, textarea, .uneditable-input { width: 206px; } textarea { height: auto; } textarea, input[type="text"], input[type="password"], input[type="datetime"], input[type="datetime-local"], input[type="date"], input[type="month"], input[type="time"], input[type="week"], input[type="number"], input[type="email"], input[type="url"], input[type="search"], input[type="tel"], input[type="color"], .uneditable-input { background-color: #ffffff; border: 1px solid #cccccc; -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); -webkit-transition: border linear .2s, box-shadow linear .2s; -moz-transition: border linear .2s, box-shadow linear .2s; -o-transition: border linear .2s, box-shadow linear .2s; transition: border linear .2s, box-shadow linear .2s; } textarea:focus, input[type="text"]:focus, input[type="password"]:focus, input[type="datetime"]:focus, input[type="datetime-local"]:focus, input[type="date"]:focus, input[type="month"]:focus, input[type="time"]:focus, input[type="week"]:focus, input[type="number"]:focus, input[type="email"]:focus, input[type="url"]:focus, input[type="search"]:focus, input[type="tel"]:focus, input[type="color"]:focus, .uneditable-input:focus { border-color: rgba(82, 168, 236, 0.8); outline: 0; outline: thin dotted \9; /* IE6-9 */ -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(82,168,236,.6); -moz-box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(82,168,236,.6); box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(82,168,236,.6); } input[type="radio"], input[type="checkbox"] { margin: 4px 0 0; *margin-top: 0; /* IE7 */ margin-top: 1px \9; /* IE8-9 */ line-height: normal; } input[type="file"], input[type="image"], input[type="submit"], input[type="reset"], input[type="button"], input[type="radio"], input[type="checkbox"] { width: auto; } select, input[type="file"] { height: 29px; /* In IE7, the height of the select element cannot be changed by height, only font-size */ *margin-top: 4px; /* For IE7, add top margin to align select with labels */ line-height: 29px; } select { width: 220px; border: 1px solid #cccccc; background-color: #ffffff; } select[multiple], select[size] { height: auto; } select:focus, input[type="file"]:focus, input[type="radio"]:focus, input[type="checkbox"]:focus { outline: thin dotted #333; outline: 5px auto -webkit-focus-ring-color; outline-offset: -2px; } .uneditable-input, .uneditable-textarea { color: #999999; background-color: #fcfcfc; border-color: #cccccc; -webkit-box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.025); -moz-box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.025); box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.025); cursor: not-allowed; } .uneditable-input { overflow: hidden; white-space: nowrap; } .uneditable-textarea { width: auto; height: auto; } input:-moz-placeholder, textarea:-moz-placeholder { color: #999999; } input:-ms-input-placeholder, textarea:-ms-input-placeholder { color: #999999; } input::-webkit-input-placeholder, textarea::-webkit-input-placeholder { color: #999999; } input:-moz-placeholder, textarea:-moz-placeholder { color: #999999; } input:-ms-input-placeholder, textarea:-ms-input-placeholder { color: #999999; } input::-webkit-input-placeholder, textarea::-webkit-input-placeholder { color: #999999; } .radio, .checkbox { min-height: 19px; padding-left: 20px; } .radio input[type="radio"], .checkbox input[type="checkbox"] { float: left; margin-left: -20px; } .controls > .radio:first-child, .controls > .checkbox:first-child { padding-top: 5px; } .radio.inline, .checkbox.inline { display: inline-block; padding-top: 5px; margin-bottom: 0; vertical-align: middle; } .radio.inline + .radio.inline, .checkbox.inline + .checkbox.inline { margin-left: 10px; } .input-mini { width: 60px; } .input-small { width: 90px; } .input-medium { width: 150px; } .input-large { width: 210px; } .input-xlarge { width: 270px; } .input-xxlarge { width: 530px; } input[class*="span"], select[class*="span"], textarea[class*="span"], .uneditable-input[class*="span"], .row-fluid input[class*="span"], .row-fluid select[class*="span"], .row-fluid textarea[class*="span"], .row-fluid .uneditable-input[class*="span"] { float: none; margin-left: 0; } .input-append input[class*="span"], .input-append .uneditable-input[class*="span"], .input-prepend input[class*="span"], .input-prepend .uneditable-input[class*="span"], .row-fluid input[class*="span"], .row-fluid select[class*="span"], .row-fluid textarea[class*="span"], .row-fluid .uneditable-input[class*="span"], .row-fluid .input-prepend [class*="span"], .row-fluid .input-append [class*="span"] { display: inline-block; } input, textarea, .uneditable-input { margin-left: 0; } .controls-row [class*="span"] + [class*="span"] { margin-left: 20px; } input.span12, textarea.span12, .uneditable-input.span12 { width: 926px; } input.span11, textarea.span11, .uneditable-input.span11 { width: 846px; } input.span10, textarea.span10, .uneditable-input.span10 { width: 766px; } input.span9, textarea.span9, .uneditable-input.span9 { width: 686px; } input.span8, textarea.span8, .uneditable-input.span8 { width: 606px; } input.span7, textarea.span7, .uneditable-input.span7 { width: 526px; } input.span6, textarea.span6, .uneditable-input.span6 { width: 446px; } input.span5, textarea.span5, .uneditable-input.span5 { width: 366px; } input.span4, textarea.span4, .uneditable-input.span4 { width: 286px; } input.span3, textarea.span3, .uneditable-input.span3 { width: 206px; } input.span2, textarea.span2, .uneditable-input.span2 { width: 126px; } input.span1, textarea.span1, .uneditable-input.span1 { width: 46px; } input, textarea, .uneditable-input { margin-left: 0; } .controls-row [class*="span"] + [class*="span"] { margin-left: 20px; } input.span12, textarea.span12, .uneditable-input.span12 { width: 926px; } input.span11, textarea.span11, .uneditable-input.span11 { width: 846px; } input.span10, textarea.span10, .uneditable-input.span10 { width: 766px; } input.span9, textarea.span9, .uneditable-input.span9 { width: 686px; } input.span8, textarea.span8, .uneditable-input.span8 { width: 606px; } input.span7, textarea.span7, .uneditable-input.span7 { width: 526px; } input.span6, textarea.span6, .uneditable-input.span6 { width: 446px; } input.span5, textarea.span5, .uneditable-input.span5 { width: 366px; } input.span4, textarea.span4, .uneditable-input.span4 { width: 286px; } input.span3, textarea.span3, .uneditable-input.span3 { width: 206px; } input.span2, textarea.span2, .uneditable-input.span2 { width: 126px; } input.span1, textarea.span1, .uneditable-input.span1 { width: 46px; } .controls-row { *zoom: 1; } .controls-row:before, .controls-row:after { display: table; content: ""; line-height: 0; } .controls-row:after { clear: both; } .controls-row:before, .controls-row:after { display: table; content: ""; line-height: 0; } .controls-row:after { clear: both; } .controls-row [class*="span"], .row-fluid .controls-row [class*="span"] { float: left; } .controls-row .checkbox[class*="span"], .controls-row .radio[class*="span"] { padding-top: 5px; } input[disabled], select[disabled], textarea[disabled], input[readonly], select[readonly], textarea[readonly] { cursor: not-allowed; background-color: #eeeeee; } input[type="radio"][disabled], input[type="checkbox"][disabled], input[type="radio"][readonly], input[type="checkbox"][readonly] { background-color: transparent; } .control-group.warning .control-label, .control-group.warning .help-block, .control-group.warning .help-inline { color: #c09853; } .control-group.warning .checkbox, .control-group.warning .radio, .control-group.warning input, .control-group.warning select, .control-group.warning textarea { color: #c09853; } .control-group.warning input, .control-group.warning select, .control-group.warning textarea { border-color: #c09853; -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); } .control-group.warning input:focus, .control-group.warning select:focus, .control-group.warning textarea:focus { border-color: #a47e3c; -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #dbc59e; -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #dbc59e; box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #dbc59e; } .control-group.warning .input-prepend .add-on, .control-group.warning .input-append .add-on { color: #c09853; background-color: #fcf8e3; border-color: #c09853; } .control-group.warning .control-label, .control-group.warning .help-block, .control-group.warning .help-inline { color: #c09853; } .control-group.warning .checkbox, .control-group.warning .radio, .control-group.warning input, .control-group.warning select, .control-group.warning textarea { color: #c09853; } .control-group.warning input, .control-group.warning select, .control-group.warning textarea { border-color: #c09853; -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); } .control-group.warning input:focus, .control-group.warning select:focus, .control-group.warning textarea:focus { border-color: #a47e3c; -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #dbc59e; -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #dbc59e; box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #dbc59e; } .control-group.warning .input-prepend .add-on, .control-group.warning .input-append .add-on { color: #c09853; background-color: #fcf8e3; border-color: #c09853; } .control-group.error .control-label, .control-group.error .help-block, .control-group.error .help-inline { color: #b94a48; } .control-group.error .checkbox, .control-group.error .radio, .control-group.error input, .control-group.error select, .control-group.error textarea { color: #b94a48; } .control-group.error input, .control-group.error select, .control-group.error textarea { border-color: #b94a48; -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); } .control-group.error input:focus, .control-group.error select:focus, .control-group.error textarea:focus { border-color: #953b39; -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #d59392; -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #d59392; box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #d59392; } .control-group.error .input-prepend .add-on, .control-group.error .input-append .add-on { color: #b94a48; background-color: #f2dede; border-color: #b94a48; } .control-group.error .control-label, .control-group.error .help-block, .control-group.error .help-inline { color: #b94a48; } .control-group.error .checkbox, .control-group.error .radio, .control-group.error input, .control-group.error select, .control-group.error textarea { color: #b94a48; } .control-group.error input, .control-group.error select, .control-group.error textarea { border-color: #b94a48; -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); } .control-group.error input:focus, .control-group.error select:focus, .control-group.error textarea:focus { border-color: #953b39; -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #d59392; -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #d59392; box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #d59392; } .control-group.error .input-prepend .add-on, .control-group.error .input-append .add-on { color: #b94a48; background-color: #f2dede; border-color: #b94a48; } .control-group.success .control-label, .control-group.success .help-block, .control-group.success .help-inline { color: #468847; } .control-group.success .checkbox, .control-group.success .radio, .control-group.success input, .control-group.success select, .control-group.success textarea { color: #468847; } .control-group.success input, .control-group.success select, .control-group.success textarea { border-color: #468847; -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); } .control-group.success input:focus, .control-group.success select:focus, .control-group.success textarea:focus { border-color: #356635; -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #7aba7b; -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #7aba7b; box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #7aba7b; } .control-group.success .input-prepend .add-on, .control-group.success .input-append .add-on { color: #468847; background-color: #dff0d8; border-color: #468847; } .control-group.success .control-label, .control-group.success .help-block, .control-group.success .help-inline { color: #468847; } .control-group.success .checkbox, .control-group.success .radio, .control-group.success input, .control-group.success select, .control-group.success textarea { color: #468847; } .control-group.success input, .control-group.success select, .control-group.success textarea { border-color: #468847; -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); } .control-group.success input:focus, .control-group.success select:focus, .control-group.success textarea:focus { border-color: #356635; -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #7aba7b; -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #7aba7b; box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #7aba7b; } .control-group.success .input-prepend .add-on, .control-group.success .input-append .add-on { color: #468847; background-color: #dff0d8; border-color: #468847; } .control-group.info .control-label, .control-group.info .help-block, .control-group.info .help-inline { color: #3a87ad; } .control-group.info .checkbox, .control-group.info .radio, .control-group.info input, .control-group.info select, .control-group.info textarea { color: #3a87ad; } .control-group.info input, .control-group.info select, .control-group.info textarea { border-color: #3a87ad; -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); } .control-group.info input:focus, .control-group.info select:focus, .control-group.info textarea:focus { border-color: #2d6987; -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #7ab5d3; -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #7ab5d3; box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #7ab5d3; } .control-group.info .input-prepend .add-on, .control-group.info .input-append .add-on { color: #3a87ad; background-color: #d9edf7; border-color: #3a87ad; } .control-group.info .control-label, .control-group.info .help-block, .control-group.info .help-inline { color: #3a87ad; } .control-group.info .checkbox, .control-group.info .radio, .control-group.info input, .control-group.info select, .control-group.info textarea { color: #3a87ad; } .control-group.info input, .control-group.info select, .control-group.info textarea { border-color: #3a87ad; -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); } .control-group.info input:focus, .control-group.info select:focus, .control-group.info textarea:focus { border-color: #2d6987; -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #7ab5d3; -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #7ab5d3; box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #7ab5d3; } .control-group.info .input-prepend .add-on, .control-group.info .input-append .add-on { color: #3a87ad; background-color: #d9edf7; border-color: #3a87ad; } input:focus:invalid, textarea:focus:invalid, select:focus:invalid { color: #b94a48; border-color: #ee5f5b; } input:focus:invalid:focus, textarea:focus:invalid:focus, select:focus:invalid:focus { border-color: #e9322d; -webkit-box-shadow: 0 0 6px #f8b9b7; -moz-box-shadow: 0 0 6px #f8b9b7; box-shadow: 0 0 6px #f8b9b7; } .form-actions { padding: 18px 20px 19px; margin-top: 19px; margin-bottom: 19px; background-color: #f5f5f5; border-top: 1px solid #e5e5e5; *zoom: 1; } .form-actions:before, .form-actions:after { display: table; content: ""; line-height: 0; } .form-actions:after { clear: both; } .form-actions:before, .form-actions:after { display: table; content: ""; line-height: 0; } .form-actions:after { clear: both; } .help-block, .help-inline { color: #595959; } .help-block { display: block; margin-bottom: 9.5px; } .help-inline { display: inline-block; *display: inline; /* IE7 inline-block hack */ *zoom: 1; vertical-align: middle; padding-left: 5px; } .input-append, .input-prepend { display: inline-block; margin-bottom: 9.5px; vertical-align: middle; font-size: 0; white-space: nowrap; } .input-append input, .input-prepend input, .input-append select, .input-prepend select, .input-append .uneditable-input, .input-prepend .uneditable-input, .input-append .dropdown-menu, .input-prepend .dropdown-menu, .input-append .popover, .input-prepend .popover { font-size: 13px; } .input-append input, .input-prepend input, .input-append select, .input-prepend select, .input-append .uneditable-input, .input-prepend .uneditable-input { position: relative; margin-bottom: 0; *margin-left: 0; vertical-align: top; -webkit-border-radius: 0 4px 4px 0; -moz-border-radius: 0 4px 4px 0; border-radius: 0 4px 4px 0; } .input-append input:focus, .input-prepend input:focus, .input-append select:focus, .input-prepend select:focus, .input-append .uneditable-input:focus, .input-prepend .uneditable-input:focus { z-index: 2; } .input-append .add-on, .input-prepend .add-on { display: inline-block; width: auto; height: 19px; min-width: 16px; padding: 4px 5px; font-size: 13px; font-weight: normal; line-height: 19px; text-align: center; text-shadow: 0 1px 0 #ffffff; background-color: #eeeeee; border: 1px solid #ccc; } .input-append .add-on, .input-prepend .add-on, .input-append .btn, .input-prepend .btn, .input-append .btn-group > .dropdown-toggle, .input-prepend .btn-group > .dropdown-toggle { vertical-align: top; -webkit-border-radius: 0; -moz-border-radius: 0; border-radius: 0; } .input-append .active, .input-prepend .active { background-color: #a9dba9; border-color: #46a546; } .input-prepend .add-on, .input-prepend .btn { margin-right: -1px; } .input-prepend .add-on:first-child, .input-prepend .btn:first-child { -webkit-border-radius: 4px 0 0 4px; -moz-border-radius: 4px 0 0 4px; border-radius: 4px 0 0 4px; } .input-append input, .input-append select, .input-append .uneditable-input { -webkit-border-radius: 4px 0 0 4px; -moz-border-radius: 4px 0 0 4px; border-radius: 4px 0 0 4px; } .input-append input + .btn-group .btn:last-child, .input-append select + .btn-group .btn:last-child, .input-append .uneditable-input + .btn-group .btn:last-child { -webkit-border-radius: 0 4px 4px 0; -moz-border-radius: 0 4px 4px 0; border-radius: 0 4px 4px 0; } .input-append .add-on, .input-append .btn, .input-append .btn-group { margin-left: -1px; } .input-append .add-on:last-child, .input-append .btn:last-child, .input-append .btn-group:last-child > .dropdown-toggle { -webkit-border-radius: 0 4px 4px 0; -moz-border-radius: 0 4px 4px 0; border-radius: 0 4px 4px 0; } .input-prepend.input-append input, .input-prepend.input-append select, .input-prepend.input-append .uneditable-input { -webkit-border-radius: 0; -moz-border-radius: 0; border-radius: 0; } .input-prepend.input-append input + .btn-group .btn, .input-prepend.input-append select + .btn-group .btn, .input-prepend.input-append .uneditable-input + .btn-group .btn { -webkit-border-radius: 0 4px 4px 0; -moz-border-radius: 0 4px 4px 0; border-radius: 0 4px 4px 0; } .input-prepend.input-append .add-on:first-child, .input-prepend.input-append .btn:first-child { margin-right: -1px; -webkit-border-radius: 4px 0 0 4px; -moz-border-radius: 4px 0 0 4px; border-radius: 4px 0 0 4px; } .input-prepend.input-append .add-on:last-child, .input-prepend.input-append .btn:last-child { margin-left: -1px; -webkit-border-radius: 0 4px 4px 0; -moz-border-radius: 0 4px 4px 0; border-radius: 0 4px 4px 0; } .input-prepend.input-append .btn-group:first-child { margin-left: 0; } input.search-query { padding-right: 14px; padding-right: 4px \9; padding-left: 14px; padding-left: 4px \9; /* IE7-8 doesn't have border-radius, so don't indent the padding */ margin-bottom: 0; -webkit-border-radius: 15px; -moz-border-radius: 15px; border-radius: 15px; } /* Allow for input prepend/append in search forms */ .form-search .input-append .search-query, .form-search .input-prepend .search-query { -webkit-border-radius: 0; -moz-border-radius: 0; border-radius: 0; } .form-search .input-append .search-query { -webkit-border-radius: 14px 0 0 14px; -moz-border-radius: 14px 0 0 14px; border-radius: 14px 0 0 14px; } .form-search .input-append .btn { -webkit-border-radius: 0 14px 14px 0; -moz-border-radius: 0 14px 14px 0; border-radius: 0 14px 14px 0; } .form-search .input-prepend .search-query { -webkit-border-radius: 0 14px 14px 0; -moz-border-radius: 0 14px 14px 0; border-radius: 0 14px 14px 0; } .form-search .input-prepend .btn { -webkit-border-radius: 14px 0 0 14px; -moz-border-radius: 14px 0 0 14px; border-radius: 14px 0 0 14px; } .form-search input, .form-inline input, .form-horizontal input, .form-search textarea, .form-inline textarea, .form-horizontal textarea, .form-search select, .form-inline select, .form-horizontal select, .form-search .help-inline, .form-inline .help-inline, .form-horizontal .help-inline, .form-search .uneditable-input, .form-inline .uneditable-input, .form-horizontal .uneditable-input, .form-search .input-prepend, .form-inline .input-prepend, .form-horizontal .input-prepend, .form-search .input-append, .form-inline .input-append, .form-horizontal .input-append { display: inline-block; *display: inline; /* IE7 inline-block hack */ *zoom: 1; margin-bottom: 0; vertical-align: middle; } .form-search .hide, .form-inline .hide, .form-horizontal .hide { display: none; } .form-search label, .form-inline label, .form-search .btn-group, .form-inline .btn-group { display: inline-block; } .form-search .input-append, .form-inline .input-append, .form-search .input-prepend, .form-inline .input-prepend { margin-bottom: 0; } .form-search .radio, .form-search .checkbox, .form-inline .radio, .form-inline .checkbox { padding-left: 0; margin-bottom: 0; vertical-align: middle; } .form-search .radio input[type="radio"], .form-search .checkbox input[type="checkbox"], .form-inline .radio input[type="radio"], .form-inline .checkbox input[type="checkbox"] { float: left; margin-right: 3px; margin-left: 0; } .control-group { margin-bottom: 9.5px; } legend + .control-group { margin-top: 19px; -webkit-margin-top-collapse: separate; } .form-horizontal .control-group { margin-bottom: 19px; *zoom: 1; } .form-horizontal .control-group:before, .form-horizontal .control-group:after { display: table; content: ""; line-height: 0; } .form-horizontal .control-group:after { clear: both; } .form-horizontal .control-group:before, .form-horizontal .control-group:after { display: table; content: ""; line-height: 0; } .form-horizontal .control-group:after { clear: both; } .form-horizontal .control-label { float: left; width: 160px; padding-top: 5px; text-align: right; } .form-horizontal .controls { *display: inline-block; *padding-left: 20px; margin-left: 180px; *margin-left: 0; } .form-horizontal .controls:first-child { *padding-left: 180px; } .form-horizontal .help-block { margin-bottom: 0; } .form-horizontal input + .help-block, .form-horizontal select + .help-block, .form-horizontal textarea + .help-block, .form-horizontal .uneditable-input + .help-block, .form-horizontal .input-prepend + .help-block, .form-horizontal .input-append + .help-block { margin-top: 9.5px; } .form-horizontal .form-actions { padding-left: 180px; } table { max-width: 100%; background-color: transparent; border-collapse: collapse; border-spacing: 0; } .table { width: 100%; margin-bottom: 19px; } .table th, .table td { padding: 8px; line-height: 19px; text-align: left; vertical-align: top; border-top: 1px solid #dddddd; } .table th { font-weight: bold; } .table thead th { vertical-align: bottom; } .table caption + thead tr:first-child th, .table caption + thead tr:first-child td, .table colgroup + thead tr:first-child th, .table colgroup + thead tr:first-child td, .table thead:first-child tr:first-child th, .table thead:first-child tr:first-child td { border-top: 0; } .table tbody + tbody { border-top: 2px solid #dddddd; } .table .table { background-color: #ffffff; } .table-condensed th, .table-condensed td { padding: 4px 5px; } .table-bordered { border: 1px solid #dddddd; border-collapse: separate; *border-collapse: collapse; border-left: 0; -webkit-border-radius: 4px; -moz-border-radius: 4px; border-radius: 4px; } .table-bordered th, .table-bordered td { border-left: 1px solid #dddddd; } .table-bordered caption + thead tr:first-child th, .table-bordered caption + tbody tr:first-child th, .table-bordered caption + tbody tr:first-child td, .table-bordered colgroup + thead tr:first-child th, .table-bordered colgroup + tbody tr:first-child th, .table-bordered colgroup + tbody tr:first-child td, .table-bordered thead:first-child tr:first-child th, .table-bordered tbody:first-child tr:first-child th, .table-bordered tbody:first-child tr:first-child td { border-top: 0; } .table-bordered thead:first-child tr:first-child > th:first-child, .table-bordered tbody:first-child tr:first-child > td:first-child, .table-bordered tbody:first-child tr:first-child > th:first-child { -webkit-border-top-left-radius: 4px; -moz-border-radius-topleft: 4px; border-top-left-radius: 4px; } .table-bordered thead:first-child tr:first-child > th:last-child, .table-bordered tbody:first-child tr:first-child > td:last-child, .table-bordered tbody:first-child tr:first-child > th:last-child { -webkit-border-top-right-radius: 4px; -moz-border-radius-topright: 4px; border-top-right-radius: 4px; } .table-bordered thead:last-child tr:last-child > th:first-child, .table-bordered tbody:last-child tr:last-child > td:first-child, .table-bordered tbody:last-child tr:last-child > th:first-child, .table-bordered tfoot:last-child tr:last-child > td:first-child, .table-bordered tfoot:last-child tr:last-child > th:first-child { -webkit-border-bottom-left-radius: 4px; -moz-border-radius-bottomleft: 4px; border-bottom-left-radius: 4px; } .table-bordered thead:last-child tr:last-child > th:last-child, .table-bordered tbody:last-child tr:last-child > td:last-child, .table-bordered tbody:last-child tr:last-child > th:last-child, .table-bordered tfoot:last-child tr:last-child > td:last-child, .table-bordered tfoot:last-child tr:last-child > th:last-child { -webkit-border-bottom-right-radius: 4px; -moz-border-radius-bottomright: 4px; border-bottom-right-radius: 4px; } .table-bordered tfoot + tbody:last-child tr:last-child td:first-child { -webkit-border-bottom-left-radius: 0; -moz-border-radius-bottomleft: 0; border-bottom-left-radius: 0; } .table-bordered tfoot + tbody:last-child tr:last-child td:last-child { -webkit-border-bottom-right-radius: 0; -moz-border-radius-bottomright: 0; border-bottom-right-radius: 0; } .table-bordered caption + thead tr:first-child th:first-child, .table-bordered caption + tbody tr:first-child td:first-child, .table-bordered colgroup + thead tr:first-child th:first-child, .table-bordered colgroup + tbody tr:first-child td:first-child { -webkit-border-top-left-radius: 4px; -moz-border-radius-topleft: 4px; border-top-left-radius: 4px; } .table-bordered caption + thead tr:first-child th:last-child, .table-bordered caption + tbody tr:first-child td:last-child, .table-bordered colgroup + thead tr:first-child th:last-child, .table-bordered colgroup + tbody tr:first-child td:last-child { -webkit-border-top-right-radius: 4px; -moz-border-radius-topright: 4px; border-top-right-radius: 4px; } .table-striped tbody > tr:nth-child(odd) > td, .table-striped tbody > tr:nth-child(odd) > th { background-color: #f9f9f9; } .table-hover tbody tr:hover > td, .table-hover tbody tr:hover > th { background-color: #f5f5f5; } table td[class*="span"], table th[class*="span"], .row-fluid table td[class*="span"], .row-fluid table th[class*="span"] { display: table-cell; float: none; margin-left: 0; } .table td.span1, .table th.span1 { float: none; width: 44px; margin-left: 0; } .table td.span2, .table th.span2 { float: none; width: 124px; margin-left: 0; } .table td.span3, .table th.span3 { float: none; width: 204px; margin-left: 0; } .table td.span4, .table th.span4 { float: none; width: 284px; margin-left: 0; } .table td.span5, .table th.span5 { float: none; width: 364px; margin-left: 0; } .table td.span6, .table th.span6 { float: none; width: 444px; margin-left: 0; } .table td.span7, .table th.span7 { float: none; width: 524px; margin-left: 0; } .table td.span8, .table th.span8 { float: none; width: 604px; margin-left: 0; } .table td.span9, .table th.span9 { float: none; width: 684px; margin-left: 0; } .table td.span10, .table th.span10 { float: none; width: 764px; margin-left: 0; } .table td.span11, .table th.span11 { float: none; width: 844px; margin-left: 0; } .table td.span12, .table th.span12 { float: none; width: 924px; margin-left: 0; } .table tbody tr.success > td { background-color: #dff0d8; } .table tbody tr.error > td { background-color: #f2dede; } .table tbody tr.warning > td { background-color: #fcf8e3; } .table tbody tr.info > td { background-color: #d9edf7; } .table-hover tbody tr.success:hover > td { background-color: #d0e9c6; } .table-hover tbody tr.error:hover > td { background-color: #ebcccc; } .table-hover tbody tr.warning:hover > td { background-color: #faf2cc; } .table-hover tbody tr.info:hover > td { background-color: #c4e3f3; } [class^="icon-"], [class*=" icon-"] { display: inline-block; width: 14px; height: 14px; *margin-right: .3em; line-height: 14px; vertical-align: text-top; background-image: url("../../img/glyphicons-halflings.png"); background-position: 14px 14px; background-repeat: no-repeat; margin-top: 1px; } /* White icons with optional class, or on hover/focus/active states of certain elements */ .icon-white, .nav-pills > .active > a > [class^="icon-"], .nav-pills > .active > a > [class*=" icon-"], .nav-list > .active > a > [class^="icon-"], .nav-list > .active > a > [class*=" icon-"], .navbar-inverse .nav > .active > a > [class^="icon-"], .navbar-inverse .nav > .active > a > [class*=" icon-"], .dropdown-menu > li > a:hover > [class^="icon-"], .dropdown-menu > li > a:focus > [class^="icon-"], .dropdown-menu > li > a:hover > [class*=" icon-"], .dropdown-menu > li > a:focus > [class*=" icon-"], .dropdown-menu > .active > a > [class^="icon-"], .dropdown-menu > .active > a > [class*=" icon-"], .dropdown-submenu:hover > a > [class^="icon-"], .dropdown-submenu:focus > a > [class^="icon-"], .dropdown-submenu:hover > a > [class*=" icon-"], .dropdown-submenu:focus > a > [class*=" icon-"] { background-image: url("../../img/glyphicons-halflings-white.png"); } .icon-glass { background-position: 0 0; } .icon-music { background-position: -24px 0; } .icon-search { background-position: -48px 0; } .icon-envelope { background-position: -72px 0; } .icon-heart { background-position: -96px 0; } .icon-star { background-position: -120px 0; } .icon-star-empty { background-position: -144px 0; } .icon-user { background-position: -168px 0; } .icon-film { background-position: -192px 0; } .icon-th-large { background-position: -216px 0; } .icon-th { background-position: -240px 0; } .icon-th-list { background-position: -264px 0; } .icon-ok { background-position: -288px 0; } .icon-remove { background-position: -312px 0; } .icon-zoom-in { background-position: -336px 0; } .icon-zoom-out { background-position: -360px 0; } .icon-off { background-position: -384px 0; } .icon-signal { background-position: -408px 0; } .icon-cog { background-position: -432px 0; } .icon-trash { background-position: -456px 0; } .icon-home { background-position: 0 -24px; } .icon-file { background-position: -24px -24px; } .icon-time { background-position: -48px -24px; } .icon-road { background-position: -72px -24px; } .icon-download-alt { background-position: -96px -24px; } .icon-download { background-position: -120px -24px; } .icon-upload { background-position: -144px -24px; } .icon-inbox { background-position: -168px -24px; } .icon-play-circle { background-position: -192px -24px; } .icon-repeat { background-position: -216px -24px; } .icon-refresh { background-position: -240px -24px; } .icon-list-alt { background-position: -264px -24px; } .icon-lock { background-position: -287px -24px; } .icon-flag { background-position: -312px -24px; } .icon-headphones { background-position: -336px -24px; } .icon-volume-off { background-position: -360px -24px; } .icon-volume-down { background-position: -384px -24px; } .icon-volume-up { background-position: -408px -24px; } .icon-qrcode { background-position: -432px -24px; } .icon-barcode { background-position: -456px -24px; } .icon-tag { background-position: 0 -48px; } .icon-tags { background-position: -25px -48px; } .icon-book { background-position: -48px -48px; } .icon-bookmark { background-position: -72px -48px; } .icon-print { background-position: -96px -48px; } .icon-camera { background-position: -120px -48px; } .icon-font { background-position: -144px -48px; } .icon-bold { background-position: -167px -48px; } .icon-italic { background-position: -192px -48px; } .icon-text-height { background-position: -216px -48px; } .icon-text-width { background-position: -240px -48px; } .icon-align-left { background-position: -264px -48px; } .icon-align-center { background-position: -288px -48px; } .icon-align-right { background-position: -312px -48px; } .icon-align-justify { background-position: -336px -48px; } .icon-list { background-position: -360px -48px; } .icon-indent-left { background-position: -384px -48px; } .icon-indent-right { background-position: -408px -48px; } .icon-facetime-video { background-position: -432px -48px; } .icon-picture { background-position: -456px -48px; } .icon-pencil { background-position: 0 -72px; } .icon-map-marker { background-position: -24px -72px; } .icon-adjust { background-position: -48px -72px; } .icon-tint { background-position: -72px -72px; } .icon-edit { background-position: -96px -72px; } .icon-share { background-position: -120px -72px; } .icon-check { background-position: -144px -72px; } .icon-move { background-position: -168px -72px; } .icon-step-backward { background-position: -192px -72px; } .icon-fast-backward { background-position: -216px -72px; } .icon-backward { background-position: -240px -72px; } .icon-play { background-position: -264px -72px; } .icon-pause { background-position: -288px -72px; } .icon-stop { background-position: -312px -72px; } .icon-forward { background-position: -336px -72px; } .icon-fast-forward { background-position: -360px -72px; } .icon-step-forward { background-position: -384px -72px; } .icon-eject { background-position: -408px -72px; } .icon-chevron-left { background-position: -432px -72px; } .icon-chevron-right { background-position: -456px -72px; } .icon-plus-sign { background-position: 0 -96px; } .icon-minus-sign { background-position: -24px -96px; } .icon-remove-sign { background-position: -48px -96px; } .icon-ok-sign { background-position: -72px -96px; } .icon-question-sign { background-position: -96px -96px; } .icon-info-sign { background-position: -120px -96px; } .icon-screenshot { background-position: -144px -96px; } .icon-remove-circle { background-position: -168px -96px; } .icon-ok-circle { background-position: -192px -96px; } .icon-ban-circle { background-position: -216px -96px; } .icon-arrow-left { background-position: -240px -96px; } .icon-arrow-right { background-position: -264px -96px; } .icon-arrow-up { background-position: -289px -96px; } .icon-arrow-down { background-position: -312px -96px; } .icon-share-alt { background-position: -336px -96px; } .icon-resize-full { background-position: -360px -96px; } .icon-resize-small { background-position: -384px -96px; } .icon-plus { background-position: -408px -96px; } .icon-minus { background-position: -433px -96px; } .icon-asterisk { background-position: -456px -96px; } .icon-exclamation-sign { background-position: 0 -120px; } .icon-gift { background-position: -24px -120px; } .icon-leaf { background-position: -48px -120px; } .icon-fire { background-position: -72px -120px; } .icon-eye-open { background-position: -96px -120px; } .icon-eye-close { background-position: -120px -120px; } .icon-warning-sign { background-position: -144px -120px; } .icon-plane { background-position: -168px -120px; } .icon-calendar { background-position: -192px -120px; } .icon-random { background-position: -216px -120px; width: 16px; } .icon-comment { background-position: -240px -120px; } .icon-magnet { background-position: -264px -120px; } .icon-chevron-up { background-position: -288px -120px; } .icon-chevron-down { background-position: -313px -119px; } .icon-retweet { background-position: -336px -120px; } .icon-shopping-cart { background-position: -360px -120px; } .icon-folder-close { background-position: -384px -120px; width: 16px; } .icon-folder-open { background-position: -408px -120px; width: 16px; } .icon-resize-vertical { background-position: -432px -119px; } .icon-resize-horizontal { background-position: -456px -118px; } .icon-hdd { background-position: 0 -144px; } .icon-bullhorn { background-position: -24px -144px; } .icon-bell { background-position: -48px -144px; } .icon-certificate { background-position: -72px -144px; } .icon-thumbs-up { background-position: -96px -144px; } .icon-thumbs-down { background-position: -120px -144px; } .icon-hand-right { background-position: -144px -144px; } .icon-hand-left { background-position: -168px -144px; } .icon-hand-up { background-position: -192px -144px; } .icon-hand-down { background-position: -216px -144px; } .icon-circle-arrow-right { background-position: -240px -144px; } .icon-circle-arrow-left { background-position: -264px -144px; } .icon-circle-arrow-up { background-position: -288px -144px; } .icon-circle-arrow-down { background-position: -312px -144px; } .icon-globe { background-position: -336px -144px; } .icon-wrench { background-position: -360px -144px; } .icon-tasks { background-position: -384px -144px; } .icon-filter { background-position: -408px -144px; } .icon-briefcase { background-position: -432px -144px; } .icon-fullscreen { background-position: -456px -144px; } .dropup, .dropdown { position: relative; } .dropdown-toggle { *margin-bottom: -3px; } .dropdown-toggle:active, .open .dropdown-toggle { outline: 0; } .caret { display: inline-block; width: 0; height: 0; vertical-align: top; border-top: 4px solid #000000; border-right: 4px solid transparent; border-left: 4px solid transparent; content: ""; } .dropdown .caret { margin-top: 8px; margin-left: 2px; } .dropdown-menu { position: absolute; top: 100%; left: 0; z-index: 1000; display: none; float: left; min-width: 160px; padding: 5px 0; margin: 2px 0 0; list-style: none; background-color: #ffffff; border: 1px solid #ccc; border: 1px solid rgba(0, 0, 0, 0.2); *border-right-width: 2px; *border-bottom-width: 2px; -webkit-border-radius: 6px; -moz-border-radius: 6px; border-radius: 6px; -webkit-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2); -moz-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2); box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2); -webkit-background-clip: padding-box; -moz-background-clip: padding; background-clip: padding-box; } .dropdown-menu.pull-right { right: 0; left: auto; } .dropdown-menu .divider { *width: 100%; height: 1px; margin: 8.5px 1px; *margin: -5px 0 5px; overflow: hidden; background-color: #e5e5e5; border-bottom: 1px solid #ffffff; } .dropdown-menu > li > a { display: block; padding: 3px 20px; clear: both; font-weight: normal; line-height: 19px; color: #333333; white-space: nowrap; } .dropdown-menu > li > a:hover, .dropdown-menu > li > a:focus, .dropdown-submenu:hover > a, .dropdown-submenu:focus > a { text-decoration: none; color: #ffffff; background-color: #0081c2; background-image: -moz-linear-gradient(top, #0088cc, #0077b3); background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#0088cc), to(#0077b3)); background-image: -webkit-linear-gradient(top, #0088cc, #0077b3); background-image: -o-linear-gradient(top, #0088cc, #0077b3); background-image: linear-gradient(to bottom, #0088cc, #0077b3); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff0088cc', endColorstr='#ff0077b3', GradientType=0); } .dropdown-menu > .active > a, .dropdown-menu > .active > a:hover, .dropdown-menu > .active > a:focus { color: #ffffff; text-decoration: none; outline: 0; background-color: #0081c2; background-image: -moz-linear-gradient(top, #0088cc, #0077b3); background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#0088cc), to(#0077b3)); background-image: -webkit-linear-gradient(top, #0088cc, #0077b3); background-image: -o-linear-gradient(top, #0088cc, #0077b3); background-image: linear-gradient(to bottom, #0088cc, #0077b3); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff0088cc', endColorstr='#ff0077b3', GradientType=0); } .dropdown-menu > .disabled > a, .dropdown-menu > .disabled > a:hover, .dropdown-menu > .disabled > a:focus { color: #999999; } .dropdown-menu > .disabled > a:hover, .dropdown-menu > .disabled > a:focus { text-decoration: none; background-color: transparent; background-image: none; filter: progid:DXImageTransform.Microsoft.gradient(enabled = false); cursor: default; } .open { *z-index: 1000; } .open > .dropdown-menu { display: block; } .pull-right > .dropdown-menu { right: 0; left: auto; } .dropup .caret, .navbar-fixed-bottom .dropdown .caret { border-top: 0; border-bottom: 4px solid #000000; content: ""; } .dropup .dropdown-menu, .navbar-fixed-bottom .dropdown .dropdown-menu { top: auto; bottom: 100%; margin-bottom: 1px; } .dropdown-submenu { position: relative; } .dropdown-submenu > .dropdown-menu { top: 0; left: 100%; margin-top: -6px; margin-left: -1px; -webkit-border-radius: 0 6px 6px 6px; -moz-border-radius: 0 6px 6px 6px; border-radius: 0 6px 6px 6px; } .dropdown-submenu:hover > .dropdown-menu { display: block; } .dropup .dropdown-submenu > .dropdown-menu { top: auto; bottom: 0; margin-top: 0; margin-bottom: -2px; -webkit-border-radius: 5px 5px 5px 0; -moz-border-radius: 5px 5px 5px 0; border-radius: 5px 5px 5px 0; } .dropdown-submenu > a:after { display: block; content: " "; float: right; width: 0; height: 0; border-color: transparent; border-style: solid; border-width: 5px 0 5px 5px; border-left-color: #cccccc; margin-top: 5px; margin-right: -10px; } .dropdown-submenu:hover > a:after { border-left-color: #ffffff; } .dropdown-submenu.pull-left { float: none; } .dropdown-submenu.pull-left > .dropdown-menu { left: -100%; margin-left: 10px; -webkit-border-radius: 6px 0 6px 6px; -moz-border-radius: 6px 0 6px 6px; border-radius: 6px 0 6px 6px; } .dropdown .dropdown-menu .nav-header { padding-left: 20px; padding-right: 20px; } .typeahead { z-index: 1051; margin-top: 2px; -webkit-border-radius: 4px; -moz-border-radius: 4px; border-radius: 4px; } .well { min-height: 20px; padding: 19px; margin-bottom: 20px; background-color: #f5f5f5; border: 1px solid #e3e3e3; -webkit-border-radius: 4px; -moz-border-radius: 4px; border-radius: 4px; -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.05); -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.05); box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.05); } .well blockquote { border-color: #ddd; border-color: rgba(0, 0, 0, 0.15); } .well-large { padding: 24px; -webkit-border-radius: 6px; -moz-border-radius: 6px; border-radius: 6px; } .well-small { padding: 9px; -webkit-border-radius: 3px; -moz-border-radius: 3px; border-radius: 3px; } .fade { opacity: 0; -webkit-transition: opacity 0.15s linear; -moz-transition: opacity 0.15s linear; -o-transition: opacity 0.15s linear; transition: opacity 0.15s linear; } .fade.in { opacity: 1; } .collapse { position: relative; height: 0; overflow: hidden; -webkit-transition: height 0.35s ease; -moz-transition: height 0.35s ease; -o-transition: height 0.35s ease; transition: height 0.35s ease; } .collapse.in { height: auto; } .close { float: right; font-size: 20px; font-weight: bold; line-height: 19px; color: #000000; text-shadow: 0 1px 0 #ffffff; opacity: 0.2; filter: alpha(opacity=20); } .close:hover, .close:focus { color: #000000; text-decoration: none; cursor: pointer; opacity: 0.4; filter: alpha(opacity=40); } button.close { padding: 0; cursor: pointer; background: transparent; border: 0; -webkit-appearance: none; } .btn { display: inline-block; *display: inline; /* IE7 inline-block hack */ *zoom: 1; padding: 4px 12px; margin-bottom: 0; font-size: 13px; line-height: 19px; text-align: center; vertical-align: middle; cursor: pointer; color: #333333; text-shadow: 0 1px 1px rgba(255, 255, 255, 0.75); background-color: #f5f5f5; background-image: -moz-linear-gradient(top, #ffffff, #e6e6e6); background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#ffffff), to(#e6e6e6)); background-image: -webkit-linear-gradient(top, #ffffff, #e6e6e6); background-image: -o-linear-gradient(top, #ffffff, #e6e6e6); background-image: linear-gradient(to bottom, #ffffff, #e6e6e6); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff', endColorstr='#ffe6e6e6', GradientType=0); border-color: #e6e6e6 #e6e6e6 #bfbfbf; border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); *background-color: #e6e6e6; /* Darken IE7 buttons by default so they stand out more given they won't have borders */ filter: progid:DXImageTransform.Microsoft.gradient(enabled = false); border: 1px solid #cccccc; *border: 0; border-bottom-color: #b3b3b3; -webkit-border-radius: 4px; -moz-border-radius: 4px; border-radius: 4px; *margin-left: .3em; -webkit-box-shadow: inset 0 1px 0 rgba(255,255,255,.2), 0 1px 2px rgba(0,0,0,.05); -moz-box-shadow: inset 0 1px 0 rgba(255,255,255,.2), 0 1px 2px rgba(0,0,0,.05); box-shadow: inset 0 1px 0 rgba(255,255,255,.2), 0 1px 2px rgba(0,0,0,.05); } .btn:hover, .btn:focus, .btn:active, .btn.active, .btn.disabled, .btn[disabled] { color: #333333; background-color: #e6e6e6; *background-color: #d9d9d9; } .btn:active, .btn.active { background-color: #cccccc \9; } .btn:hover, .btn:focus, .btn:active, .btn.active, .btn.disabled, .btn[disabled] { color: #333333; background-color: #e6e6e6; *background-color: #d9d9d9; } .btn:active, .btn.active { background-color: #cccccc \9; } .btn:first-child { *margin-left: 0; } .btn:first-child { *margin-left: 0; } .btn:hover, .btn:focus { color: #333333; text-decoration: none; background-position: 0 -15px; -webkit-transition: background-position 0.1s linear; -moz-transition: background-position 0.1s linear; -o-transition: background-position 0.1s linear; transition: background-position 0.1s linear; } .btn:focus { outline: thin dotted #333; outline: 5px auto -webkit-focus-ring-color; outline-offset: -2px; } .btn.active, .btn:active { background-image: none; outline: 0; -webkit-box-shadow: inset 0 2px 4px rgba(0,0,0,.15), 0 1px 2px rgba(0,0,0,.05); -moz-box-shadow: inset 0 2px 4px rgba(0,0,0,.15), 0 1px 2px rgba(0,0,0,.05); box-shadow: inset 0 2px 4px rgba(0,0,0,.15), 0 1px 2px rgba(0,0,0,.05); } .btn.disabled, .btn[disabled] { cursor: default; background-image: none; opacity: 0.65; filter: alpha(opacity=65); -webkit-box-shadow: none; -moz-box-shadow: none; box-shadow: none; } .btn-large { padding: 11px 19px; font-size: 16.25px; -webkit-border-radius: 6px; -moz-border-radius: 6px; border-radius: 6px; } .btn-large [class^="icon-"], .btn-large [class*=" icon-"] { margin-top: 4px; } .btn-small { padding: 2px 10px; font-size: 11.049999999999999px; -webkit-border-radius: 3px; -moz-border-radius: 3px; border-radius: 3px; } .btn-small [class^="icon-"], .btn-small [class*=" icon-"] { margin-top: 0; } .btn-mini [class^="icon-"], .btn-mini [class*=" icon-"] { margin-top: -1px; } .btn-mini { padding: 0 6px; font-size: 9.75px; -webkit-border-radius: 3px; -moz-border-radius: 3px; border-radius: 3px; } .btn-block { display: block; width: 100%; padding-left: 0; padding-right: 0; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } .btn-block + .btn-block { margin-top: 5px; } input[type="submit"].btn-block, input[type="reset"].btn-block, input[type="button"].btn-block { width: 100%; } .btn-primary.active, .btn-warning.active, .btn-danger.active, .btn-success.active, .btn-info.active, .btn-inverse.active { color: rgba(255, 255, 255, 0.75); } .btn-primary { color: #ffffff; text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); background-color: #006dcc; background-image: -moz-linear-gradient(top, #0088cc, #0044cc); background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#0088cc), to(#0044cc)); background-image: -webkit-linear-gradient(top, #0088cc, #0044cc); background-image: -o-linear-gradient(top, #0088cc, #0044cc); background-image: linear-gradient(to bottom, #0088cc, #0044cc); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff0088cc', endColorstr='#ff0044cc', GradientType=0); border-color: #0044cc #0044cc #002a80; border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); *background-color: #0044cc; /* Darken IE7 buttons by default so they stand out more given they won't have borders */ filter: progid:DXImageTransform.Microsoft.gradient(enabled = false); } .btn-primary:hover, .btn-primary:focus, .btn-primary:active, .btn-primary.active, .btn-primary.disabled, .btn-primary[disabled] { color: #ffffff; background-color: #0044cc; *background-color: #003bb3; } .btn-primary:active, .btn-primary.active { background-color: #003399 \9; } .btn-primary:hover, .btn-primary:focus, .btn-primary:active, .btn-primary.active, .btn-primary.disabled, .btn-primary[disabled] { color: #ffffff; background-color: #0044cc; *background-color: #003bb3; } .btn-primary:active, .btn-primary.active { background-color: #003399 \9; } .btn-warning { color: #ffffff; text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); background-color: #faa732; background-image: -moz-linear-gradient(top, #fbb450, #f89406); background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#fbb450), to(#f89406)); background-image: -webkit-linear-gradient(top, #fbb450, #f89406); background-image: -o-linear-gradient(top, #fbb450, #f89406); background-image: linear-gradient(to bottom, #fbb450, #f89406); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffbb450', endColorstr='#fff89406', GradientType=0); border-color: #f89406 #f89406 #ad6704; border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); *background-color: #f89406; /* Darken IE7 buttons by default so they stand out more given they won't have borders */ filter: progid:DXImageTransform.Microsoft.gradient(enabled = false); } .btn-warning:hover, .btn-warning:focus, .btn-warning:active, .btn-warning.active, .btn-warning.disabled, .btn-warning[disabled] { color: #ffffff; background-color: #f89406; *background-color: #df8505; } .btn-warning:active, .btn-warning.active { background-color: #c67605 \9; } .btn-warning:hover, .btn-warning:focus, .btn-warning:active, .btn-warning.active, .btn-warning.disabled, .btn-warning[disabled] { color: #ffffff; background-color: #f89406; *background-color: #df8505; } .btn-warning:active, .btn-warning.active { background-color: #c67605 \9; } .btn-danger { color: #ffffff; text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); background-color: #da4f49; background-image: -moz-linear-gradient(top, #ee5f5b, #bd362f); background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#ee5f5b), to(#bd362f)); background-image: -webkit-linear-gradient(top, #ee5f5b, #bd362f); background-image: -o-linear-gradient(top, #ee5f5b, #bd362f); background-image: linear-gradient(to bottom, #ee5f5b, #bd362f); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffee5f5b', endColorstr='#ffbd362f', GradientType=0); border-color: #bd362f #bd362f #802420; border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); *background-color: #bd362f; /* Darken IE7 buttons by default so they stand out more given they won't have borders */ filter: progid:DXImageTransform.Microsoft.gradient(enabled = false); } .btn-danger:hover, .btn-danger:focus, .btn-danger:active, .btn-danger.active, .btn-danger.disabled, .btn-danger[disabled] { color: #ffffff; background-color: #bd362f; *background-color: #a9302a; } .btn-danger:active, .btn-danger.active { background-color: #942a25 \9; } .btn-danger:hover, .btn-danger:focus, .btn-danger:active, .btn-danger.active, .btn-danger.disabled, .btn-danger[disabled] { color: #ffffff; background-color: #bd362f; *background-color: #a9302a; } .btn-danger:active, .btn-danger.active { background-color: #942a25 \9; } .btn-success { color: #ffffff; text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); background-color: #5bb75b; background-image: -moz-linear-gradient(top, #62c462, #51a351); background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#62c462), to(#51a351)); background-image: -webkit-linear-gradient(top, #62c462, #51a351); background-image: -o-linear-gradient(top, #62c462, #51a351); background-image: linear-gradient(to bottom, #62c462, #51a351); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff62c462', endColorstr='#ff51a351', GradientType=0); border-color: #51a351 #51a351 #387038; border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); *background-color: #51a351; /* Darken IE7 buttons by default so they stand out more given they won't have borders */ filter: progid:DXImageTransform.Microsoft.gradient(enabled = false); } .btn-success:hover, .btn-success:focus, .btn-success:active, .btn-success.active, .btn-success.disabled, .btn-success[disabled] { color: #ffffff; background-color: #51a351; *background-color: #499249; } .btn-success:active, .btn-success.active { background-color: #408140 \9; } .btn-success:hover, .btn-success:focus, .btn-success:active, .btn-success.active, .btn-success.disabled, .btn-success[disabled] { color: #ffffff; background-color: #51a351; *background-color: #499249; } .btn-success:active, .btn-success.active { background-color: #408140 \9; } .btn-info { color: #ffffff; text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); background-color: #49afcd; background-image: -moz-linear-gradient(top, #5bc0de, #2f96b4); background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#5bc0de), to(#2f96b4)); background-image: -webkit-linear-gradient(top, #5bc0de, #2f96b4); background-image: -o-linear-gradient(top, #5bc0de, #2f96b4); background-image: linear-gradient(to bottom, #5bc0de, #2f96b4); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5bc0de', endColorstr='#ff2f96b4', GradientType=0); border-color: #2f96b4 #2f96b4 #1f6377; border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); *background-color: #2f96b4; /* Darken IE7 buttons by default so they stand out more given they won't have borders */ filter: progid:DXImageTransform.Microsoft.gradient(enabled = false); } .btn-info:hover, .btn-info:focus, .btn-info:active, .btn-info.active, .btn-info.disabled, .btn-info[disabled] { color: #ffffff; background-color: #2f96b4; *background-color: #2a85a0; } .btn-info:active, .btn-info.active { background-color: #24748c \9; } .btn-info:hover, .btn-info:focus, .btn-info:active, .btn-info.active, .btn-info.disabled, .btn-info[disabled] { color: #ffffff; background-color: #2f96b4; *background-color: #2a85a0; } .btn-info:active, .btn-info.active { background-color: #24748c \9; } .btn-inverse { color: #ffffff; text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); background-color: #363636; background-image: -moz-linear-gradient(top, #444444, #222222); background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#444444), to(#222222)); background-image: -webkit-linear-gradient(top, #444444, #222222); background-image: -o-linear-gradient(top, #444444, #222222); background-image: linear-gradient(to bottom, #444444, #222222); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff444444', endColorstr='#ff222222', GradientType=0); border-color: #222222 #222222 #000000; border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); *background-color: #222222; /* Darken IE7 buttons by default so they stand out more given they won't have borders */ filter: progid:DXImageTransform.Microsoft.gradient(enabled = false); } .btn-inverse:hover, .btn-inverse:focus, .btn-inverse:active, .btn-inverse.active, .btn-inverse.disabled, .btn-inverse[disabled] { color: #ffffff; background-color: #222222; *background-color: #151515; } .btn-inverse:active, .btn-inverse.active { background-color: #080808 \9; } .btn-inverse:hover, .btn-inverse:focus, .btn-inverse:active, .btn-inverse.active, .btn-inverse.disabled, .btn-inverse[disabled] { color: #ffffff; background-color: #222222; *background-color: #151515; } .btn-inverse:active, .btn-inverse.active { background-color: #080808 \9; } button.btn, input[type="submit"].btn { *padding-top: 3px; *padding-bottom: 3px; } button.btn::-moz-focus-inner, input[type="submit"].btn::-moz-focus-inner { padding: 0; border: 0; } button.btn.btn-large, input[type="submit"].btn.btn-large { *padding-top: 7px; *padding-bottom: 7px; } button.btn.btn-small, input[type="submit"].btn.btn-small { *padding-top: 3px; *padding-bottom: 3px; } button.btn.btn-mini, input[type="submit"].btn.btn-mini { *padding-top: 1px; *padding-bottom: 1px; } .btn-link, .btn-link:active, .btn-link[disabled] { background-color: transparent; background-image: none; -webkit-box-shadow: none; -moz-box-shadow: none; box-shadow: none; } .btn-link { border-color: transparent; cursor: pointer; color: #0088cc; -webkit-border-radius: 0; -moz-border-radius: 0; border-radius: 0; } .btn-link:hover, .btn-link:focus { color: #005580; text-decoration: underline; background-color: transparent; } .btn-link[disabled]:hover, .btn-link[disabled]:focus { color: #333333; text-decoration: none; } .btn-group { position: relative; display: inline-block; *display: inline; /* IE7 inline-block hack */ *zoom: 1; font-size: 0; vertical-align: middle; white-space: nowrap; *margin-left: .3em; } .btn-group:first-child { *margin-left: 0; } .btn-group:first-child { *margin-left: 0; } .btn-group + .btn-group { margin-left: 5px; } .btn-toolbar { font-size: 0; margin-top: 9.5px; margin-bottom: 9.5px; } .btn-toolbar > .btn + .btn, .btn-toolbar > .btn-group + .btn, .btn-toolbar > .btn + .btn-group { margin-left: 5px; } .btn-group > .btn { position: relative; -webkit-border-radius: 0; -moz-border-radius: 0; border-radius: 0; } .btn-group > .btn + .btn { margin-left: -1px; } .btn-group > .btn, .btn-group > .dropdown-menu, .btn-group > .popover { font-size: 13px; } .btn-group > .btn-mini { font-size: 9.75px; } .btn-group > .btn-small { font-size: 11.049999999999999px; } .btn-group > .btn-large { font-size: 16.25px; } .btn-group > .btn:first-child { margin-left: 0; -webkit-border-top-left-radius: 4px; -moz-border-radius-topleft: 4px; border-top-left-radius: 4px; -webkit-border-bottom-left-radius: 4px; -moz-border-radius-bottomleft: 4px; border-bottom-left-radius: 4px; } .btn-group > .btn:last-child, .btn-group > .dropdown-toggle { -webkit-border-top-right-radius: 4px; -moz-border-radius-topright: 4px; border-top-right-radius: 4px; -webkit-border-bottom-right-radius: 4px; -moz-border-radius-bottomright: 4px; border-bottom-right-radius: 4px; } .btn-group > .btn.large:first-child { margin-left: 0; -webkit-border-top-left-radius: 6px; -moz-border-radius-topleft: 6px; border-top-left-radius: 6px; -webkit-border-bottom-left-radius: 6px; -moz-border-radius-bottomleft: 6px; border-bottom-left-radius: 6px; } .btn-group > .btn.large:last-child, .btn-group > .large.dropdown-toggle { -webkit-border-top-right-radius: 6px; -moz-border-radius-topright: 6px; border-top-right-radius: 6px; -webkit-border-bottom-right-radius: 6px; -moz-border-radius-bottomright: 6px; border-bottom-right-radius: 6px; } .btn-group > .btn:hover, .btn-group > .btn:focus, .btn-group > .btn:active, .btn-group > .btn.active { z-index: 2; } .btn-group .dropdown-toggle:active, .btn-group.open .dropdown-toggle { outline: 0; } .btn-group > .btn + .dropdown-toggle { padding-left: 8px; padding-right: 8px; -webkit-box-shadow: inset 1px 0 0 rgba(255,255,255,.125), inset 0 1px 0 rgba(255,255,255,.2), 0 1px 2px rgba(0,0,0,.05); -moz-box-shadow: inset 1px 0 0 rgba(255,255,255,.125), inset 0 1px 0 rgba(255,255,255,.2), 0 1px 2px rgba(0,0,0,.05); box-shadow: inset 1px 0 0 rgba(255,255,255,.125), inset 0 1px 0 rgba(255,255,255,.2), 0 1px 2px rgba(0,0,0,.05); *padding-top: 5px; *padding-bottom: 5px; } .btn-group > .btn-mini + .dropdown-toggle { padding-left: 5px; padding-right: 5px; *padding-top: 2px; *padding-bottom: 2px; } .btn-group > .btn-small + .dropdown-toggle { *padding-top: 5px; *padding-bottom: 4px; } .btn-group > .btn-large + .dropdown-toggle { padding-left: 12px; padding-right: 12px; *padding-top: 7px; *padding-bottom: 7px; } .btn-group.open .dropdown-toggle { background-image: none; -webkit-box-shadow: inset 0 2px 4px rgba(0,0,0,.15), 0 1px 2px rgba(0,0,0,.05); -moz-box-shadow: inset 0 2px 4px rgba(0,0,0,.15), 0 1px 2px rgba(0,0,0,.05); box-shadow: inset 0 2px 4px rgba(0,0,0,.15), 0 1px 2px rgba(0,0,0,.05); } .btn-group.open .btn.dropdown-toggle { background-color: #e6e6e6; } .btn-group.open .btn-primary.dropdown-toggle { background-color: #0044cc; } .btn-group.open .btn-warning.dropdown-toggle { background-color: #f89406; } .btn-group.open .btn-danger.dropdown-toggle { background-color: #bd362f; } .btn-group.open .btn-success.dropdown-toggle { background-color: #51a351; } .btn-group.open .btn-info.dropdown-toggle { background-color: #2f96b4; } .btn-group.open .btn-inverse.dropdown-toggle { background-color: #222222; } .btn .caret { margin-top: 8px; margin-left: 0; } .btn-large .caret { margin-top: 6px; } .btn-large .caret { border-left-width: 5px; border-right-width: 5px; border-top-width: 5px; } .btn-mini .caret, .btn-small .caret { margin-top: 8px; } .dropup .btn-large .caret { border-bottom-width: 5px; } .btn-primary .caret, .btn-warning .caret, .btn-danger .caret, .btn-info .caret, .btn-success .caret, .btn-inverse .caret { border-top-color: #ffffff; border-bottom-color: #ffffff; } .btn-group-vertical { display: inline-block; *display: inline; /* IE7 inline-block hack */ *zoom: 1; } .btn-group-vertical > .btn { display: block; float: none; max-width: 100%; -webkit-border-radius: 0; -moz-border-radius: 0; border-radius: 0; } .btn-group-vertical > .btn + .btn { margin-left: 0; margin-top: -1px; } .btn-group-vertical > .btn:first-child { -webkit-border-radius: 4px 4px 0 0; -moz-border-radius: 4px 4px 0 0; border-radius: 4px 4px 0 0; } .btn-group-vertical > .btn:last-child { -webkit-border-radius: 0 0 4px 4px; -moz-border-radius: 0 0 4px 4px; border-radius: 0 0 4px 4px; } .btn-group-vertical > .btn-large:first-child { -webkit-border-radius: 6px 6px 0 0; -moz-border-radius: 6px 6px 0 0; border-radius: 6px 6px 0 0; } .btn-group-vertical > .btn-large:last-child { -webkit-border-radius: 0 0 6px 6px; -moz-border-radius: 0 0 6px 6px; border-radius: 0 0 6px 6px; } .alert { padding: 8px 35px 8px 14px; margin-bottom: 19px; text-shadow: 0 1px 0 rgba(255, 255, 255, 0.5); background-color: #fcf8e3; border: 1px solid #fbeed5; -webkit-border-radius: 4px; -moz-border-radius: 4px; border-radius: 4px; } .alert, .alert h4 { color: #c09853; } .alert h4 { margin: 0; } .alert .close { position: relative; top: -2px; right: -21px; line-height: 19px; } .alert-success { background-color: #dff0d8; border-color: #d6e9c6; color: #468847; } .alert-success h4 { color: #468847; } .alert-danger, .alert-error { background-color: #f2dede; border-color: #eed3d7; color: #b94a48; } .alert-danger h4, .alert-error h4 { color: #b94a48; } .alert-info { background-color: #d9edf7; border-color: #bce8f1; color: #3a87ad; } .alert-info h4 { color: #3a87ad; } .alert-block { padding-top: 14px; padding-bottom: 14px; } .alert-block > p, .alert-block > ul { margin-bottom: 0; } .alert-block p + p { margin-top: 5px; } .nav { margin-left: 0; margin-bottom: 19px; list-style: none; } .nav > li > a { display: block; } .nav > li > a:hover, .nav > li > a:focus { text-decoration: none; background-color: #eeeeee; } .nav > li > a > img { max-width: none; } .nav > .pull-right { float: right; } .nav-header { display: block; padding: 3px 15px; font-size: 11px; font-weight: bold; line-height: 19px; color: #999999; text-shadow: 0 1px 0 rgba(255, 255, 255, 0.5); text-transform: uppercase; } .nav li + .nav-header { margin-top: 9px; } .nav-list { padding-left: 15px; padding-right: 15px; margin-bottom: 0; } .nav-list > li > a, .nav-list .nav-header { margin-left: -15px; margin-right: -15px; text-shadow: 0 1px 0 rgba(255, 255, 255, 0.5); } .nav-list > li > a { padding: 3px 15px; } .nav-list > .active > a, .nav-list > .active > a:hover, .nav-list > .active > a:focus { color: #ffffff; text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.2); background-color: #0088cc; } .nav-list [class^="icon-"], .nav-list [class*=" icon-"] { margin-right: 2px; } .nav-list .divider { *width: 100%; height: 1px; margin: 8.5px 1px; *margin: -5px 0 5px; overflow: hidden; background-color: #e5e5e5; border-bottom: 1px solid #ffffff; } .nav-tabs, .nav-pills { *zoom: 1; } .nav-tabs:before, .nav-pills:before, .nav-tabs:after, .nav-pills:after { display: table; content: ""; line-height: 0; } .nav-tabs:after, .nav-pills:after { clear: both; } .nav-tabs:before, .nav-pills:before, .nav-tabs:after, .nav-pills:after { display: table; content: ""; line-height: 0; } .nav-tabs:after, .nav-pills:after { clear: both; } .nav-tabs > li, .nav-pills > li { float: left; } .nav-tabs > li > a, .nav-pills > li > a { padding-right: 12px; padding-left: 12px; margin-right: 2px; line-height: 14px; } .nav-tabs { border-bottom: 1px solid #ddd; } .nav-tabs > li { margin-bottom: -1px; } .nav-tabs > li > a { padding-top: 8px; padding-bottom: 8px; line-height: 19px; border: 1px solid transparent; -webkit-border-radius: 4px 4px 0 0; -moz-border-radius: 4px 4px 0 0; border-radius: 4px 4px 0 0; } .nav-tabs > li > a:hover, .nav-tabs > li > a:focus { border-color: #eeeeee #eeeeee #dddddd; } .nav-tabs > .active > a, .nav-tabs > .active > a:hover, .nav-tabs > .active > a:focus { color: #555555; background-color: #ffffff; border: 1px solid #ddd; border-bottom-color: transparent; cursor: default; } .nav-pills > li > a { padding-top: 8px; padding-bottom: 8px; margin-top: 2px; margin-bottom: 2px; -webkit-border-radius: 5px; -moz-border-radius: 5px; border-radius: 5px; } .nav-pills > .active > a, .nav-pills > .active > a:hover, .nav-pills > .active > a:focus { color: #ffffff; background-color: #0088cc; } .nav-stacked > li { float: none; } .nav-stacked > li > a { margin-right: 0; } .nav-tabs.nav-stacked { border-bottom: 0; } .nav-tabs.nav-stacked > li > a { border: 1px solid #ddd; -webkit-border-radius: 0; -moz-border-radius: 0; border-radius: 0; } .nav-tabs.nav-stacked > li:first-child > a { -webkit-border-top-right-radius: 4px; -moz-border-radius-topright: 4px; border-top-right-radius: 4px; -webkit-border-top-left-radius: 4px; -moz-border-radius-topleft: 4px; border-top-left-radius: 4px; } .nav-tabs.nav-stacked > li:last-child > a { -webkit-border-bottom-right-radius: 4px; -moz-border-radius-bottomright: 4px; border-bottom-right-radius: 4px; -webkit-border-bottom-left-radius: 4px; -moz-border-radius-bottomleft: 4px; border-bottom-left-radius: 4px; } .nav-tabs.nav-stacked > li > a:hover, .nav-tabs.nav-stacked > li > a:focus { border-color: #ddd; z-index: 2; } .nav-pills.nav-stacked > li > a { margin-bottom: 3px; } .nav-pills.nav-stacked > li:last-child > a { margin-bottom: 1px; } .nav-tabs .dropdown-menu { -webkit-border-radius: 0 0 6px 6px; -moz-border-radius: 0 0 6px 6px; border-radius: 0 0 6px 6px; } .nav-pills .dropdown-menu { -webkit-border-radius: 6px; -moz-border-radius: 6px; border-radius: 6px; } .nav .dropdown-toggle .caret { border-top-color: #0088cc; border-bottom-color: #0088cc; margin-top: 6px; } .nav .dropdown-toggle:hover .caret, .nav .dropdown-toggle:focus .caret { border-top-color: #005580; border-bottom-color: #005580; } /* move down carets for tabs */ .nav-tabs .dropdown-toggle .caret { margin-top: 8px; } .nav .active .dropdown-toggle .caret { border-top-color: #fff; border-bottom-color: #fff; } .nav-tabs .active .dropdown-toggle .caret { border-top-color: #555555; border-bottom-color: #555555; } .nav > .dropdown.active > a:hover, .nav > .dropdown.active > a:focus { cursor: pointer; } .nav-tabs .open .dropdown-toggle, .nav-pills .open .dropdown-toggle, .nav > li.dropdown.open.active > a:hover, .nav > li.dropdown.open.active > a:focus { color: #ffffff; background-color: #999999; border-color: #999999; } .nav li.dropdown.open .caret, .nav li.dropdown.open.active .caret, .nav li.dropdown.open a:hover .caret, .nav li.dropdown.open a:focus .caret { border-top-color: #ffffff; border-bottom-color: #ffffff; opacity: 1; filter: alpha(opacity=100); } .tabs-stacked .open > a:hover, .tabs-stacked .open > a:focus { border-color: #999999; } .tabbable { *zoom: 1; } .tabbable:before, .tabbable:after { display: table; content: ""; line-height: 0; } .tabbable:after { clear: both; } .tabbable:before, .tabbable:after { display: table; content: ""; line-height: 0; } .tabbable:after { clear: both; } .tab-content { overflow: auto; } .tabs-below > .nav-tabs, .tabs-right > .nav-tabs, .tabs-left > .nav-tabs { border-bottom: 0; } .tab-content > .tab-pane, .pill-content > .pill-pane { display: none; } .tab-content > .active, .pill-content > .active { display: block; } .tabs-below > .nav-tabs { border-top: 1px solid #ddd; } .tabs-below > .nav-tabs > li { margin-top: -1px; margin-bottom: 0; } .tabs-below > .nav-tabs > li > a { -webkit-border-radius: 0 0 4px 4px; -moz-border-radius: 0 0 4px 4px; border-radius: 0 0 4px 4px; } .tabs-below > .nav-tabs > li > a:hover, .tabs-below > .nav-tabs > li > a:focus { border-bottom-color: transparent; border-top-color: #ddd; } .tabs-below > .nav-tabs > .active > a, .tabs-below > .nav-tabs > .active > a:hover, .tabs-below > .nav-tabs > .active > a:focus { border-color: transparent #ddd #ddd #ddd; } .tabs-left > .nav-tabs > li, .tabs-right > .nav-tabs > li { float: none; } .tabs-left > .nav-tabs > li > a, .tabs-right > .nav-tabs > li > a { min-width: 74px; margin-right: 0; margin-bottom: 3px; } .tabs-left > .nav-tabs { float: left; margin-right: 19px; border-right: 1px solid #ddd; } .tabs-left > .nav-tabs > li > a { margin-right: -1px; -webkit-border-radius: 4px 0 0 4px; -moz-border-radius: 4px 0 0 4px; border-radius: 4px 0 0 4px; } .tabs-left > .nav-tabs > li > a:hover, .tabs-left > .nav-tabs > li > a:focus { border-color: #eeeeee #dddddd #eeeeee #eeeeee; } .tabs-left > .nav-tabs .active > a, .tabs-left > .nav-tabs .active > a:hover, .tabs-left > .nav-tabs .active > a:focus { border-color: #ddd transparent #ddd #ddd; *border-right-color: #ffffff; } .tabs-right > .nav-tabs { float: right; margin-left: 19px; border-left: 1px solid #ddd; } .tabs-right > .nav-tabs > li > a { margin-left: -1px; -webkit-border-radius: 0 4px 4px 0; -moz-border-radius: 0 4px 4px 0; border-radius: 0 4px 4px 0; } .tabs-right > .nav-tabs > li > a:hover, .tabs-right > .nav-tabs > li > a:focus { border-color: #eeeeee #eeeeee #eeeeee #dddddd; } .tabs-right > .nav-tabs .active > a, .tabs-right > .nav-tabs .active > a:hover, .tabs-right > .nav-tabs .active > a:focus { border-color: #ddd #ddd #ddd transparent; *border-left-color: #ffffff; } .nav > .disabled > a { color: #999999; } .nav > .disabled > a:hover, .nav > .disabled > a:focus { text-decoration: none; background-color: transparent; cursor: default; } .navbar { overflow: visible; margin-bottom: 19px; *position: relative; *z-index: 2; } .navbar-inner { min-height: 40px; padding-left: 20px; padding-right: 20px; background-color: #fafafa; background-image: -moz-linear-gradient(top, #ffffff, #f2f2f2); background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#ffffff), to(#f2f2f2)); background-image: -webkit-linear-gradient(top, #ffffff, #f2f2f2); background-image: -o-linear-gradient(top, #ffffff, #f2f2f2); background-image: linear-gradient(to bottom, #ffffff, #f2f2f2); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff', endColorstr='#fff2f2f2', GradientType=0); border: 1px solid #d4d4d4; -webkit-border-radius: 4px; -moz-border-radius: 4px; border-radius: 4px; -webkit-box-shadow: 0 1px 4px rgba(0, 0, 0, 0.065); -moz-box-shadow: 0 1px 4px rgba(0, 0, 0, 0.065); box-shadow: 0 1px 4px rgba(0, 0, 0, 0.065); *zoom: 1; } .navbar-inner:before, .navbar-inner:after { display: table; content: ""; line-height: 0; } .navbar-inner:after { clear: both; } .navbar-inner:before, .navbar-inner:after { display: table; content: ""; line-height: 0; } .navbar-inner:after { clear: both; } .navbar .container { width: auto; } .nav-collapse.collapse { height: auto; overflow: visible; } .navbar .brand { float: left; display: block; padding: 10.5px 20px 10.5px; margin-left: -20px; font-size: 20px; font-weight: 200; color: #777777; text-shadow: 0 1px 0 #ffffff; } .navbar .brand:hover, .navbar .brand:focus { text-decoration: none; } .navbar-text { margin-bottom: 0; line-height: 40px; color: #777777; } .navbar-link { color: #777777; } .navbar-link:hover, .navbar-link:focus { color: #333333; } .navbar .divider-vertical { height: 40px; margin: 0 9px; border-left: 1px solid #f2f2f2; border-right: 1px solid #ffffff; } .navbar .btn, .navbar .btn-group { margin-top: 5px; } .navbar .btn-group .btn, .navbar .input-prepend .btn, .navbar .input-append .btn, .navbar .input-prepend .btn-group, .navbar .input-append .btn-group { margin-top: 0; } .navbar-form { margin-bottom: 0; *zoom: 1; } .navbar-form:before, .navbar-form:after { display: table; content: ""; line-height: 0; } .navbar-form:after { clear: both; } .navbar-form:before, .navbar-form:after { display: table; content: ""; line-height: 0; } .navbar-form:after { clear: both; } .navbar-form input, .navbar-form select, .navbar-form .radio, .navbar-form .checkbox { margin-top: 5px; } .navbar-form input, .navbar-form select, .navbar-form .btn { display: inline-block; margin-bottom: 0; } .navbar-form input[type="image"], .navbar-form input[type="checkbox"], .navbar-form input[type="radio"] { margin-top: 3px; } .navbar-form .input-append, .navbar-form .input-prepend { margin-top: 5px; white-space: nowrap; } .navbar-form .input-append input, .navbar-form .input-prepend input { margin-top: 0; } .navbar-search { position: relative; float: left; margin-top: 5px; margin-bottom: 0; } .navbar-search .search-query { margin-bottom: 0; padding: 4px 14px; font-family: 'Open Sans', sans-serif; font-size: 13px; font-weight: normal; line-height: 1; -webkit-border-radius: 15px; -moz-border-radius: 15px; border-radius: 15px; } .navbar-static-top { position: static; margin-bottom: 0; } .navbar-static-top .navbar-inner { -webkit-border-radius: 0; -moz-border-radius: 0; border-radius: 0; } .navbar-fixed-top, .navbar-fixed-bottom { position: fixed; right: 0; left: 0; z-index: 1030; margin-bottom: 0; } .navbar-fixed-top .navbar-inner, .navbar-static-top .navbar-inner { border-width: 0 0 1px; } .navbar-fixed-bottom .navbar-inner { border-width: 1px 0 0; } .navbar-fixed-top .navbar-inner, .navbar-fixed-bottom .navbar-inner { padding-left: 0; padding-right: 0; -webkit-border-radius: 0; -moz-border-radius: 0; border-radius: 0; } .navbar-static-top .container, .navbar-fixed-top .container, .navbar-fixed-bottom .container { width: 940px; } .navbar-fixed-top { top: 0; } .navbar-fixed-top .navbar-inner, .navbar-static-top .navbar-inner { -webkit-box-shadow: 0 1px 10px rgba(0,0,0,.1); -moz-box-shadow: 0 1px 10px rgba(0,0,0,.1); box-shadow: 0 1px 10px rgba(0,0,0,.1); } .navbar-fixed-bottom { bottom: 0; } .navbar-fixed-bottom .navbar-inner { -webkit-box-shadow: 0 -1px 10px rgba(0,0,0,.1); -moz-box-shadow: 0 -1px 10px rgba(0,0,0,.1); box-shadow: 0 -1px 10px rgba(0,0,0,.1); } .navbar .nav { position: relative; left: 0; display: block; float: left; margin: 0 10px 0 0; } .navbar .nav.pull-right { float: right; margin-right: 0; } .navbar .nav > li { float: left; } .navbar .nav > li > a { float: none; padding: 10.5px 15px 10.5px; color: #777777; text-decoration: none; text-shadow: 0 1px 0 #ffffff; } .navbar .nav .dropdown-toggle .caret { margin-top: 8px; } .navbar .nav > li > a:focus, .navbar .nav > li > a:hover { background-color: transparent; color: #333333; text-decoration: none; } .navbar .nav > .active > a, .navbar .nav > .active > a:hover, .navbar .nav > .active > a:focus { color: #555555; text-decoration: none; background-color: #e5e5e5; -webkit-box-shadow: inset 0 3px 8px rgba(0, 0, 0, 0.125); -moz-box-shadow: inset 0 3px 8px rgba(0, 0, 0, 0.125); box-shadow: inset 0 3px 8px rgba(0, 0, 0, 0.125); } .navbar .btn-navbar { display: none; float: right; padding: 7px 10px; margin-left: 5px; margin-right: 5px; color: #ffffff; text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); background-color: #ededed; background-image: -moz-linear-gradient(top, #f2f2f2, #e5e5e5); background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#f2f2f2), to(#e5e5e5)); background-image: -webkit-linear-gradient(top, #f2f2f2, #e5e5e5); background-image: -o-linear-gradient(top, #f2f2f2, #e5e5e5); background-image: linear-gradient(to bottom, #f2f2f2, #e5e5e5); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff2f2f2', endColorstr='#ffe5e5e5', GradientType=0); border-color: #e5e5e5 #e5e5e5 #bfbfbf; border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); *background-color: #e5e5e5; /* Darken IE7 buttons by default so they stand out more given they won't have borders */ filter: progid:DXImageTransform.Microsoft.gradient(enabled = false); -webkit-box-shadow: inset 0 1px 0 rgba(255,255,255,.1), 0 1px 0 rgba(255,255,255,.075); -moz-box-shadow: inset 0 1px 0 rgba(255,255,255,.1), 0 1px 0 rgba(255,255,255,.075); box-shadow: inset 0 1px 0 rgba(255,255,255,.1), 0 1px 0 rgba(255,255,255,.075); } .navbar .btn-navbar:hover, .navbar .btn-navbar:focus, .navbar .btn-navbar:active, .navbar .btn-navbar.active, .navbar .btn-navbar.disabled, .navbar .btn-navbar[disabled] { color: #ffffff; background-color: #e5e5e5; *background-color: #d9d9d9; } .navbar .btn-navbar:active, .navbar .btn-navbar.active { background-color: #cccccc \9; } .navbar .btn-navbar:hover, .navbar .btn-navbar:focus, .navbar .btn-navbar:active, .navbar .btn-navbar.active, .navbar .btn-navbar.disabled, .navbar .btn-navbar[disabled] { color: #ffffff; background-color: #e5e5e5; *background-color: #d9d9d9; } .navbar .btn-navbar:active, .navbar .btn-navbar.active { background-color: #cccccc \9; } .navbar .btn-navbar .icon-bar { display: block; width: 18px; height: 2px; background-color: #f5f5f5; -webkit-border-radius: 1px; -moz-border-radius: 1px; border-radius: 1px; -webkit-box-shadow: 0 1px 0 rgba(0, 0, 0, 0.25); -moz-box-shadow: 0 1px 0 rgba(0, 0, 0, 0.25); box-shadow: 0 1px 0 rgba(0, 0, 0, 0.25); } .btn-navbar .icon-bar + .icon-bar { margin-top: 3px; } .navbar .nav > li > .dropdown-menu:before { content: ''; display: inline-block; border-left: 7px solid transparent; border-right: 7px solid transparent; border-bottom: 7px solid #ccc; border-bottom-color: rgba(0, 0, 0, 0.2); position: absolute; top: -7px; left: 9px; } .navbar .nav > li > .dropdown-menu:after { content: ''; display: inline-block; border-left: 6px solid transparent; border-right: 6px solid transparent; border-bottom: 6px solid #ffffff; position: absolute; top: -6px; left: 10px; } .navbar-fixed-bottom .nav > li > .dropdown-menu:before { border-top: 7px solid #ccc; border-top-color: rgba(0, 0, 0, 0.2); border-bottom: 0; bottom: -7px; top: auto; } .navbar-fixed-bottom .nav > li > .dropdown-menu:after { border-top: 6px solid #ffffff; border-bottom: 0; bottom: -6px; top: auto; } .navbar .nav li.dropdown > a:hover .caret, .navbar .nav li.dropdown > a:focus .caret { border-top-color: #333333; border-bottom-color: #333333; } .navbar .nav li.dropdown.open > .dropdown-toggle, .navbar .nav li.dropdown.active > .dropdown-toggle, .navbar .nav li.dropdown.open.active > .dropdown-toggle { background-color: #e5e5e5; color: #555555; } .navbar .nav li.dropdown > .dropdown-toggle .caret { border-top-color: #777777; border-bottom-color: #777777; } .navbar .nav li.dropdown.open > .dropdown-toggle .caret, .navbar .nav li.dropdown.active > .dropdown-toggle .caret, .navbar .nav li.dropdown.open.active > .dropdown-toggle .caret { border-top-color: #555555; border-bottom-color: #555555; } .navbar .pull-right > li > .dropdown-menu, .navbar .nav > li > .dropdown-menu.pull-right { left: auto; right: 0; } .navbar .pull-right > li > .dropdown-menu:before, .navbar .nav > li > .dropdown-menu.pull-right:before { left: auto; right: 12px; } .navbar .pull-right > li > .dropdown-menu:after, .navbar .nav > li > .dropdown-menu.pull-right:after { left: auto; right: 13px; } .navbar .pull-right > li > .dropdown-menu .dropdown-menu, .navbar .nav > li > .dropdown-menu.pull-right .dropdown-menu { left: auto; right: 100%; margin-left: 0; margin-right: -1px; -webkit-border-radius: 6px 0 6px 6px; -moz-border-radius: 6px 0 6px 6px; border-radius: 6px 0 6px 6px; } .navbar-inverse .navbar-inner { background-color: #1b1b1b; background-image: -moz-linear-gradient(top, #222222, #111111); background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#222222), to(#111111)); background-image: -webkit-linear-gradient(top, #222222, #111111); background-image: -o-linear-gradient(top, #222222, #111111); background-image: linear-gradient(to bottom, #222222, #111111); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff222222', endColorstr='#ff111111', GradientType=0); border-color: #252525; } .navbar-inverse .brand, .navbar-inverse .nav > li > a { color: #999999; text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); } .navbar-inverse .brand:hover, .navbar-inverse .nav > li > a:hover, .navbar-inverse .brand:focus, .navbar-inverse .nav > li > a:focus { color: #ffffff; } .navbar-inverse .brand { color: #999999; } .navbar-inverse .navbar-text { color: #999999; } .navbar-inverse .nav > li > a:focus, .navbar-inverse .nav > li > a:hover { background-color: transparent; color: #ffffff; } .navbar-inverse .nav .active > a, .navbar-inverse .nav .active > a:hover, .navbar-inverse .nav .active > a:focus { color: #ffffff; background-color: #111111; } .navbar-inverse .navbar-link { color: #999999; } .navbar-inverse .navbar-link:hover, .navbar-inverse .navbar-link:focus { color: #ffffff; } .navbar-inverse .divider-vertical { border-left-color: #111111; border-right-color: #222222; } .navbar-inverse .nav li.dropdown.open > .dropdown-toggle, .navbar-inverse .nav li.dropdown.active > .dropdown-toggle, .navbar-inverse .nav li.dropdown.open.active > .dropdown-toggle { background-color: #111111; color: #ffffff; } .navbar-inverse .nav li.dropdown > a:hover .caret, .navbar-inverse .nav li.dropdown > a:focus .caret { border-top-color: #ffffff; border-bottom-color: #ffffff; } .navbar-inverse .nav li.dropdown > .dropdown-toggle .caret { border-top-color: #999999; border-bottom-color: #999999; } .navbar-inverse .nav li.dropdown.open > .dropdown-toggle .caret, .navbar-inverse .nav li.dropdown.active > .dropdown-toggle .caret, .navbar-inverse .nav li.dropdown.open.active > .dropdown-toggle .caret { border-top-color: #ffffff; border-bottom-color: #ffffff; } .navbar-inverse .navbar-search .search-query { color: #ffffff; background-color: #515151; border-color: #111111; -webkit-box-shadow: inset 0 1px 2px rgba(0,0,0,.1), 0 1px 0 rgba(255,255,255,.15); -moz-box-shadow: inset 0 1px 2px rgba(0,0,0,.1), 0 1px 0 rgba(255,255,255,.15); box-shadow: inset 0 1px 2px rgba(0,0,0,.1), 0 1px 0 rgba(255,255,255,.15); -webkit-transition: none; -moz-transition: none; -o-transition: none; transition: none; } .navbar-inverse .navbar-search .search-query:-moz-placeholder { color: #cccccc; } .navbar-inverse .navbar-search .search-query:-ms-input-placeholder { color: #cccccc; } .navbar-inverse .navbar-search .search-query::-webkit-input-placeholder { color: #cccccc; } .navbar-inverse .navbar-search .search-query:-moz-placeholder { color: #cccccc; } .navbar-inverse .navbar-search .search-query:-ms-input-placeholder { color: #cccccc; } .navbar-inverse .navbar-search .search-query::-webkit-input-placeholder { color: #cccccc; } .navbar-inverse .navbar-search .search-query:focus, .navbar-inverse .navbar-search .search-query.focused { padding: 5px 15px; color: #333333; text-shadow: 0 1px 0 #ffffff; background-color: #ffffff; border: 0; -webkit-box-shadow: 0 0 3px rgba(0, 0, 0, 0.15); -moz-box-shadow: 0 0 3px rgba(0, 0, 0, 0.15); box-shadow: 0 0 3px rgba(0, 0, 0, 0.15); outline: 0; } .navbar-inverse .btn-navbar { color: #ffffff; text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); background-color: #0e0e0e; background-image: -moz-linear-gradient(top, #151515, #040404); background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#151515), to(#040404)); background-image: -webkit-linear-gradient(top, #151515, #040404); background-image: -o-linear-gradient(top, #151515, #040404); background-image: linear-gradient(to bottom, #151515, #040404); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff151515', endColorstr='#ff040404', GradientType=0); border-color: #040404 #040404 #000000; border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); *background-color: #040404; /* Darken IE7 buttons by default so they stand out more given they won't have borders */ filter: progid:DXImageTransform.Microsoft.gradient(enabled = false); } .navbar-inverse .btn-navbar:hover, .navbar-inverse .btn-navbar:focus, .navbar-inverse .btn-navbar:active, .navbar-inverse .btn-navbar.active, .navbar-inverse .btn-navbar.disabled, .navbar-inverse .btn-navbar[disabled] { color: #ffffff; background-color: #040404; *background-color: #000000; } .navbar-inverse .btn-navbar:active, .navbar-inverse .btn-navbar.active { background-color: #000000 \9; } .navbar-inverse .btn-navbar:hover, .navbar-inverse .btn-navbar:focus, .navbar-inverse .btn-navbar:active, .navbar-inverse .btn-navbar.active, .navbar-inverse .btn-navbar.disabled, .navbar-inverse .btn-navbar[disabled] { color: #ffffff; background-color: #040404; *background-color: #000000; } .navbar-inverse .btn-navbar:active, .navbar-inverse .btn-navbar.active { background-color: #000000 \9; } .breadcrumb { padding: 8px 15px; margin: 0 0 19px; list-style: none; background-color: #f5f5f5; -webkit-border-radius: 4px; -moz-border-radius: 4px; border-radius: 4px; } .breadcrumb > li { display: inline-block; *display: inline; /* IE7 inline-block hack */ *zoom: 1; text-shadow: 0 1px 0 #ffffff; } .breadcrumb > li > .divider { padding: 0 5px; color: #ccc; } .breadcrumb > .active { color: #999999; } .pagination { margin: 19px 0; } .pagination ul { display: inline-block; *display: inline; /* IE7 inline-block hack */ *zoom: 1; margin-left: 0; margin-bottom: 0; -webkit-border-radius: 4px; -moz-border-radius: 4px; border-radius: 4px; -webkit-box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05); -moz-box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05); box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05); } .pagination ul > li { display: inline; } .pagination ul > li > a, .pagination ul > li > span { float: left; padding: 4px 12px; line-height: 19px; text-decoration: none; background-color: #ffffff; border: 1px solid #dddddd; border-left-width: 0; } .pagination ul > li > a:hover, .pagination ul > li > a:focus, .pagination ul > .active > a, .pagination ul > .active > span { background-color: #f5f5f5; } .pagination ul > .active > a, .pagination ul > .active > span { color: #999999; cursor: default; } .pagination ul > .disabled > span, .pagination ul > .disabled > a, .pagination ul > .disabled > a:hover, .pagination ul > .disabled > a:focus { color: #999999; background-color: transparent; cursor: default; } .pagination ul > li:first-child > a, .pagination ul > li:first-child > span { border-left-width: 1px; -webkit-border-top-left-radius: 4px; -moz-border-radius-topleft: 4px; border-top-left-radius: 4px; -webkit-border-bottom-left-radius: 4px; -moz-border-radius-bottomleft: 4px; border-bottom-left-radius: 4px; } .pagination ul > li:last-child > a, .pagination ul > li:last-child > span { -webkit-border-top-right-radius: 4px; -moz-border-radius-topright: 4px; border-top-right-radius: 4px; -webkit-border-bottom-right-radius: 4px; -moz-border-radius-bottomright: 4px; border-bottom-right-radius: 4px; } .pagination-centered { text-align: center; } .pagination-right { text-align: right; } .pagination-large ul > li > a, .pagination-large ul > li > span { padding: 11px 19px; font-size: 16.25px; } .pagination-large ul > li:first-child > a, .pagination-large ul > li:first-child > span { -webkit-border-top-left-radius: 6px; -moz-border-radius-topleft: 6px; border-top-left-radius: 6px; -webkit-border-bottom-left-radius: 6px; -moz-border-radius-bottomleft: 6px; border-bottom-left-radius: 6px; } .pagination-large ul > li:last-child > a, .pagination-large ul > li:last-child > span { -webkit-border-top-right-radius: 6px; -moz-border-radius-topright: 6px; border-top-right-radius: 6px; -webkit-border-bottom-right-radius: 6px; -moz-border-radius-bottomright: 6px; border-bottom-right-radius: 6px; } .pagination-mini ul > li:first-child > a, .pagination-small ul > li:first-child > a, .pagination-mini ul > li:first-child > span, .pagination-small ul > li:first-child > span { -webkit-border-top-left-radius: 3px; -moz-border-radius-topleft: 3px; border-top-left-radius: 3px; -webkit-border-bottom-left-radius: 3px; -moz-border-radius-bottomleft: 3px; border-bottom-left-radius: 3px; } .pagination-mini ul > li:last-child > a, .pagination-small ul > li:last-child > a, .pagination-mini ul > li:last-child > span, .pagination-small ul > li:last-child > span { -webkit-border-top-right-radius: 3px; -moz-border-radius-topright: 3px; border-top-right-radius: 3px; -webkit-border-bottom-right-radius: 3px; -moz-border-radius-bottomright: 3px; border-bottom-right-radius: 3px; } .pagination-small ul > li > a, .pagination-small ul > li > span { padding: 2px 10px; font-size: 11.049999999999999px; } .pagination-mini ul > li > a, .pagination-mini ul > li > span { padding: 0 6px; font-size: 9.75px; } .pager { margin: 19px 0; list-style: none; text-align: center; *zoom: 1; } .pager:before, .pager:after { display: table; content: ""; line-height: 0; } .pager:after { clear: both; } .pager:before, .pager:after { display: table; content: ""; line-height: 0; } .pager:after { clear: both; } .pager li { display: inline; } .pager li > a, .pager li > span { display: inline-block; padding: 5px 14px; background-color: #fff; border: 1px solid #ddd; -webkit-border-radius: 15px; -moz-border-radius: 15px; border-radius: 15px; } .pager li > a:hover, .pager li > a:focus { text-decoration: none; background-color: #f5f5f5; } .pager .next > a, .pager .next > span { float: right; } .pager .previous > a, .pager .previous > span { float: left; } .pager .disabled > a, .pager .disabled > a:hover, .pager .disabled > a:focus, .pager .disabled > span { color: #999999; background-color: #fff; cursor: default; } .modal-backdrop { position: fixed; top: 0; right: 0; bottom: 0; left: 0; z-index: 1040; background-color: #000000; } .modal-backdrop.fade { opacity: 0; } .modal-backdrop, .modal-backdrop.fade.in { opacity: 0.8; filter: alpha(opacity=80); } .modal { position: fixed; top: 10%; left: 50%; z-index: 1050; width: 560px; margin-left: -280px; background-color: #ffffff; border: 1px solid #999; border: 1px solid rgba(0, 0, 0, 0.3); *border: 1px solid #999; /* IE6-7 */ -webkit-border-radius: 6px; -moz-border-radius: 6px; border-radius: 6px; -webkit-box-shadow: 0 3px 7px rgba(0, 0, 0, 0.3); -moz-box-shadow: 0 3px 7px rgba(0, 0, 0, 0.3); box-shadow: 0 3px 7px rgba(0, 0, 0, 0.3); -webkit-background-clip: padding-box; -moz-background-clip: padding-box; background-clip: padding-box; outline: none; } .modal.fade { -webkit-transition: opacity .3s linear, top .3s ease-out; -moz-transition: opacity .3s linear, top .3s ease-out; -o-transition: opacity .3s linear, top .3s ease-out; transition: opacity .3s linear, top .3s ease-out; top: -25%; } .modal.fade.in { top: 10%; } .modal-header { padding: 9px 15px; border-bottom: 1px solid #eee; } .modal-header .close { margin-top: 2px; } .modal-header h3 { margin: 0; line-height: 30px; } .modal-body { position: relative; overflow-y: auto; max-height: 400px; padding: 15px; } .modal-form { margin-bottom: 0; } .modal-footer { padding: 14px 15px 15px; margin-bottom: 0; text-align: right; background-color: #f5f5f5; border-top: 1px solid #ddd; -webkit-border-radius: 0 0 6px 6px; -moz-border-radius: 0 0 6px 6px; border-radius: 0 0 6px 6px; -webkit-box-shadow: inset 0 1px 0 #ffffff; -moz-box-shadow: inset 0 1px 0 #ffffff; box-shadow: inset 0 1px 0 #ffffff; *zoom: 1; } .modal-footer:before, .modal-footer:after { display: table; content: ""; line-height: 0; } .modal-footer:after { clear: both; } .modal-footer:before, .modal-footer:after { display: table; content: ""; line-height: 0; } .modal-footer:after { clear: both; } .modal-footer .btn + .btn { margin-left: 5px; margin-bottom: 0; } .modal-footer .btn-group .btn + .btn { margin-left: -1px; } .modal-footer .btn-block + .btn-block { margin-left: 0; } .tooltip { position: absolute; z-index: 1030; display: block; visibility: visible; font-size: 11px; line-height: 1.4; opacity: 0; filter: alpha(opacity=0); } .tooltip.in { opacity: 0.8; filter: alpha(opacity=80); } .tooltip.top { margin-top: -3px; padding: 5px 0; } .tooltip.right { margin-left: 3px; padding: 0 5px; } .tooltip.bottom { margin-top: 3px; padding: 5px 0; } .tooltip.left { margin-left: -3px; padding: 0 5px; } .tooltip-inner { max-width: 200px; padding: 8px; color: #ffffff; text-align: center; text-decoration: none; background-color: #000000; -webkit-border-radius: 4px; -moz-border-radius: 4px; border-radius: 4px; } .tooltip-arrow { position: absolute; width: 0; height: 0; border-color: transparent; border-style: solid; } .tooltip.top .tooltip-arrow { bottom: 0; left: 50%; margin-left: -5px; border-width: 5px 5px 0; border-top-color: #000000; } .tooltip.right .tooltip-arrow { top: 50%; left: 0; margin-top: -5px; border-width: 5px 5px 5px 0; border-right-color: #000000; } .tooltip.left .tooltip-arrow { top: 50%; right: 0; margin-top: -5px; border-width: 5px 0 5px 5px; border-left-color: #000000; } .tooltip.bottom .tooltip-arrow { top: 0; left: 50%; margin-left: -5px; border-width: 0 5px 5px; border-bottom-color: #000000; } .popover { position: absolute; top: 0; left: 0; z-index: 1010; display: none; max-width: 276px; padding: 1px; text-align: left; background-color: #ffffff; -webkit-background-clip: padding-box; -moz-background-clip: padding; background-clip: padding-box; border: 1px solid #ccc; border: 1px solid rgba(0, 0, 0, 0.2); -webkit-border-radius: 6px; -moz-border-radius: 6px; border-radius: 6px; -webkit-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2); -moz-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2); box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2); white-space: normal; } .popover.top { margin-top: -10px; } .popover.right { margin-left: 10px; } .popover.bottom { margin-top: 10px; } .popover.left { margin-left: -10px; } .popover-title { margin: 0; padding: 8px 14px; font-size: 14px; font-weight: normal; line-height: 18px; background-color: #f7f7f7; border-bottom: 1px solid #ebebeb; -webkit-border-radius: 5px 5px 0 0; -moz-border-radius: 5px 5px 0 0; border-radius: 5px 5px 0 0; } .popover-title:empty { display: none; } .popover-content { padding: 9px 14px; } .popover .arrow, .popover .arrow:after { position: absolute; display: block; width: 0; height: 0; border-color: transparent; border-style: solid; } .popover .arrow { border-width: 11px; } .popover .arrow:after { border-width: 10px; content: ""; } .popover.top .arrow { left: 50%; margin-left: -11px; border-bottom-width: 0; border-top-color: #999; border-top-color: rgba(0, 0, 0, 0.25); bottom: -11px; } .popover.top .arrow:after { bottom: 1px; margin-left: -10px; border-bottom-width: 0; border-top-color: #ffffff; } .popover.right .arrow { top: 50%; left: -11px; margin-top: -11px; border-left-width: 0; border-right-color: #999; border-right-color: rgba(0, 0, 0, 0.25); } .popover.right .arrow:after { left: 1px; bottom: -10px; border-left-width: 0; border-right-color: #ffffff; } .popover.bottom .arrow { left: 50%; margin-left: -11px; border-top-width: 0; border-bottom-color: #999; border-bottom-color: rgba(0, 0, 0, 0.25); top: -11px; } .popover.bottom .arrow:after { top: 1px; margin-left: -10px; border-top-width: 0; border-bottom-color: #ffffff; } .popover.left .arrow { top: 50%; right: -11px; margin-top: -11px; border-right-width: 0; border-left-color: #999; border-left-color: rgba(0, 0, 0, 0.25); } .popover.left .arrow:after { right: 1px; border-right-width: 0; border-left-color: #ffffff; bottom: -10px; } .thumbnails { margin-left: -20px; list-style: none; *zoom: 1; } .thumbnails:before, .thumbnails:after { display: table; content: ""; line-height: 0; } .thumbnails:after { clear: both; } .thumbnails:before, .thumbnails:after { display: table; content: ""; line-height: 0; } .thumbnails:after { clear: both; } .row-fluid .thumbnails { margin-left: 0; } .thumbnails > li { float: left; margin-bottom: 19px; margin-left: 20px; } .thumbnail { display: block; padding: 4px; line-height: 19px; border: 1px solid #ddd; -webkit-border-radius: 4px; -moz-border-radius: 4px; border-radius: 4px; -webkit-box-shadow: 0 1px 3px rgba(0, 0, 0, 0.055); -moz-box-shadow: 0 1px 3px rgba(0, 0, 0, 0.055); box-shadow: 0 1px 3px rgba(0, 0, 0, 0.055); -webkit-transition: all 0.2s ease-in-out; -moz-transition: all 0.2s ease-in-out; -o-transition: all 0.2s ease-in-out; transition: all 0.2s ease-in-out; } a.thumbnail:hover, a.thumbnail:focus { border-color: #0088cc; -webkit-box-shadow: 0 1px 4px rgba(0, 105, 214, 0.25); -moz-box-shadow: 0 1px 4px rgba(0, 105, 214, 0.25); box-shadow: 0 1px 4px rgba(0, 105, 214, 0.25); } .thumbnail > img { display: block; max-width: 100%; margin-left: auto; margin-right: auto; } .thumbnail .caption { padding: 9px; color: #555555; } .media, .media-body { overflow: hidden; *overflow: visible; zoom: 1; } .media, .media .media { margin-top: 15px; } .media:first-child { margin-top: 0; } .media-object { display: block; } .media-heading { margin: 0 0 5px; } .media > .pull-left { margin-right: 10px; } .media > .pull-right { margin-left: 10px; } .media-list { margin-left: 0; list-style: none; } .label, .badge { display: inline-block; padding: 2px 4px; font-size: 10.998px; font-weight: bold; line-height: 14px; color: #ffffff; vertical-align: baseline; white-space: nowrap; text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); background-color: #999999; } .label { -webkit-border-radius: 3px; -moz-border-radius: 3px; border-radius: 3px; } .badge { padding-left: 9px; padding-right: 9px; -webkit-border-radius: 9px; -moz-border-radius: 9px; border-radius: 9px; } .label:empty, .badge:empty { display: none; } a.label:hover, a.label:focus, a.badge:hover, a.badge:focus { color: #ffffff; text-decoration: none; cursor: pointer; } .label-important, .badge-important { background-color: #b94a48; } .label-important[href], .badge-important[href] { background-color: #953b39; } .label-warning, .badge-warning { background-color: #f89406; } .label-warning[href], .badge-warning[href] { background-color: #c67605; } .label-success, .badge-success { background-color: #468847; } .label-success[href], .badge-success[href] { background-color: #356635; } .label-info, .badge-info { background-color: #3a87ad; } .label-info[href], .badge-info[href] { background-color: #2d6987; } .label-inverse, .badge-inverse { background-color: #333333; } .label-inverse[href], .badge-inverse[href] { background-color: #1a1a1a; } .btn .label, .btn .badge { position: relative; top: -1px; } .btn-mini .label, .btn-mini .badge { top: 0; } @-webkit-keyframes progress-bar-stripes { from { background-position: 40px 0; } to { background-position: 0 0; } } @-moz-keyframes progress-bar-stripes { from { background-position: 40px 0; } to { background-position: 0 0; } } @-ms-keyframes progress-bar-stripes { from { background-position: 40px 0; } to { background-position: 0 0; } } @-o-keyframes progress-bar-stripes { from { background-position: 0 0; } to { background-position: 40px 0; } } @keyframes progress-bar-stripes { from { background-position: 40px 0; } to { background-position: 0 0; } } .progress { overflow: hidden; height: 19px; margin-bottom: 19px; background-color: #f7f7f7; background-image: -moz-linear-gradient(top, #f5f5f5, #f9f9f9); background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#f5f5f5), to(#f9f9f9)); background-image: -webkit-linear-gradient(top, #f5f5f5, #f9f9f9); background-image: -o-linear-gradient(top, #f5f5f5, #f9f9f9); background-image: linear-gradient(to bottom, #f5f5f5, #f9f9f9); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff5f5f5', endColorstr='#fff9f9f9', GradientType=0); -webkit-box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1); -moz-box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1); box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1); -webkit-border-radius: 4px; -moz-border-radius: 4px; border-radius: 4px; } .progress .bar { width: 0%; height: 100%; color: #ffffff; float: left; font-size: 12px; text-align: center; text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); background-color: #0e90d2; background-image: -moz-linear-gradient(top, #149bdf, #0480be); background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#149bdf), to(#0480be)); background-image: -webkit-linear-gradient(top, #149bdf, #0480be); background-image: -o-linear-gradient(top, #149bdf, #0480be); background-image: linear-gradient(to bottom, #149bdf, #0480be); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff149bdf', endColorstr='#ff0480be', GradientType=0); -webkit-box-shadow: inset 0 -1px 0 rgba(0, 0, 0, 0.15); -moz-box-shadow: inset 0 -1px 0 rgba(0, 0, 0, 0.15); box-shadow: inset 0 -1px 0 rgba(0, 0, 0, 0.15); -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; -webkit-transition: width 0.6s ease; -moz-transition: width 0.6s ease; -o-transition: width 0.6s ease; transition: width 0.6s ease; } .progress .bar + .bar { -webkit-box-shadow: inset 1px 0 0 rgba(0,0,0,.15), inset 0 -1px 0 rgba(0,0,0,.15); -moz-box-shadow: inset 1px 0 0 rgba(0,0,0,.15), inset 0 -1px 0 rgba(0,0,0,.15); box-shadow: inset 1px 0 0 rgba(0,0,0,.15), inset 0 -1px 0 rgba(0,0,0,.15); } .progress-striped .bar { background-color: #149bdf; background-image: -webkit-gradient(linear, 0 100%, 100% 0, color-stop(0.25, rgba(255, 255, 255, 0.15)), color-stop(0.25, transparent), color-stop(0.5, transparent), color-stop(0.5, rgba(255, 255, 255, 0.15)), color-stop(0.75, rgba(255, 255, 255, 0.15)), color-stop(0.75, transparent), to(transparent)); background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); background-image: -moz-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); -webkit-background-size: 40px 40px; -moz-background-size: 40px 40px; -o-background-size: 40px 40px; background-size: 40px 40px; } .progress.active .bar { -webkit-animation: progress-bar-stripes 2s linear infinite; -moz-animation: progress-bar-stripes 2s linear infinite; -ms-animation: progress-bar-stripes 2s linear infinite; -o-animation: progress-bar-stripes 2s linear infinite; animation: progress-bar-stripes 2s linear infinite; } .progress-danger .bar, .progress .bar-danger { background-color: #dd514c; background-image: -moz-linear-gradient(top, #ee5f5b, #c43c35); background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#ee5f5b), to(#c43c35)); background-image: -webkit-linear-gradient(top, #ee5f5b, #c43c35); background-image: -o-linear-gradient(top, #ee5f5b, #c43c35); background-image: linear-gradient(to bottom, #ee5f5b, #c43c35); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffee5f5b', endColorstr='#ffc43c35', GradientType=0); } .progress-danger.progress-striped .bar, .progress-striped .bar-danger { background-color: #ee5f5b; background-image: -webkit-gradient(linear, 0 100%, 100% 0, color-stop(0.25, rgba(255, 255, 255, 0.15)), color-stop(0.25, transparent), color-stop(0.5, transparent), color-stop(0.5, rgba(255, 255, 255, 0.15)), color-stop(0.75, rgba(255, 255, 255, 0.15)), color-stop(0.75, transparent), to(transparent)); background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); background-image: -moz-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); } .progress-success .bar, .progress .bar-success { background-color: #5eb95e; background-image: -moz-linear-gradient(top, #62c462, #57a957); background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#62c462), to(#57a957)); background-image: -webkit-linear-gradient(top, #62c462, #57a957); background-image: -o-linear-gradient(top, #62c462, #57a957); background-image: linear-gradient(to bottom, #62c462, #57a957); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff62c462', endColorstr='#ff57a957', GradientType=0); } .progress-success.progress-striped .bar, .progress-striped .bar-success { background-color: #62c462; background-image: -webkit-gradient(linear, 0 100%, 100% 0, color-stop(0.25, rgba(255, 255, 255, 0.15)), color-stop(0.25, transparent), color-stop(0.5, transparent), color-stop(0.5, rgba(255, 255, 255, 0.15)), color-stop(0.75, rgba(255, 255, 255, 0.15)), color-stop(0.75, transparent), to(transparent)); background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); background-image: -moz-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); } .progress-info .bar, .progress .bar-info { background-color: #4bb1cf; background-image: -moz-linear-gradient(top, #5bc0de, #339bb9); background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#5bc0de), to(#339bb9)); background-image: -webkit-linear-gradient(top, #5bc0de, #339bb9); background-image: -o-linear-gradient(top, #5bc0de, #339bb9); background-image: linear-gradient(to bottom, #5bc0de, #339bb9); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5bc0de', endColorstr='#ff339bb9', GradientType=0); } .progress-info.progress-striped .bar, .progress-striped .bar-info { background-color: #5bc0de; background-image: -webkit-gradient(linear, 0 100%, 100% 0, color-stop(0.25, rgba(255, 255, 255, 0.15)), color-stop(0.25, transparent), color-stop(0.5, transparent), color-stop(0.5, rgba(255, 255, 255, 0.15)), color-stop(0.75, rgba(255, 255, 255, 0.15)), color-stop(0.75, transparent), to(transparent)); background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); background-image: -moz-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); } .progress-warning .bar, .progress .bar-warning { background-color: #faa732; background-image: -moz-linear-gradient(top, #fbb450, #f89406); background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#fbb450), to(#f89406)); background-image: -webkit-linear-gradient(top, #fbb450, #f89406); background-image: -o-linear-gradient(top, #fbb450, #f89406); background-image: linear-gradient(to bottom, #fbb450, #f89406); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffbb450', endColorstr='#fff89406', GradientType=0); } .progress-warning.progress-striped .bar, .progress-striped .bar-warning { background-color: #fbb450; background-image: -webkit-gradient(linear, 0 100%, 100% 0, color-stop(0.25, rgba(255, 255, 255, 0.15)), color-stop(0.25, transparent), color-stop(0.5, transparent), color-stop(0.5, rgba(255, 255, 255, 0.15)), color-stop(0.75, rgba(255, 255, 255, 0.15)), color-stop(0.75, transparent), to(transparent)); background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); background-image: -moz-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); } .accordion { margin-bottom: 19px; } .accordion-group { margin-bottom: 2px; border: 1px solid #e5e5e5; -webkit-border-radius: 4px; -moz-border-radius: 4px; border-radius: 4px; } .accordion-heading { border-bottom: 0; } .accordion-heading .accordion-toggle { display: block; padding: 8px 15px; } .accordion-toggle { cursor: pointer; } .accordion-inner { padding: 9px 15px; border-top: 1px solid #e5e5e5; } .carousel { position: relative; margin-bottom: 19px; line-height: 1; } .carousel-inner { overflow: hidden; width: 100%; position: relative; } .carousel-inner > .item { display: none; position: relative; -webkit-transition: 0.6s ease-in-out left; -moz-transition: 0.6s ease-in-out left; -o-transition: 0.6s ease-in-out left; transition: 0.6s ease-in-out left; } .carousel-inner > .item > img, .carousel-inner > .item > a > img { display: block; line-height: 1; } .carousel-inner > .active, .carousel-inner > .next, .carousel-inner > .prev { display: block; } .carousel-inner > .active { left: 0; } .carousel-inner > .next, .carousel-inner > .prev { position: absolute; top: 0; width: 100%; } .carousel-inner > .next { left: 100%; } .carousel-inner > .prev { left: -100%; } .carousel-inner > .next.left, .carousel-inner > .prev.right { left: 0; } .carousel-inner > .active.left { left: -100%; } .carousel-inner > .active.right { left: 100%; } .carousel-control { position: absolute; top: 40%; left: 15px; width: 40px; height: 40px; margin-top: -20px; font-size: 60px; font-weight: 100; line-height: 30px; color: #ffffff; text-align: center; background: #222222; border: 3px solid #ffffff; -webkit-border-radius: 23px; -moz-border-radius: 23px; border-radius: 23px; opacity: 0.5; filter: alpha(opacity=50); } .carousel-control.right { left: auto; right: 15px; } .carousel-control:hover, .carousel-control:focus { color: #ffffff; text-decoration: none; opacity: 0.9; filter: alpha(opacity=90); } .carousel-indicators { position: absolute; top: 15px; right: 15px; z-index: 5; margin: 0; list-style: none; } .carousel-indicators li { display: block; float: left; width: 10px; height: 10px; margin-left: 5px; text-indent: -999px; background-color: #ccc; background-color: rgba(255, 255, 255, 0.25); border-radius: 5px; } .carousel-indicators .active { background-color: #fff; } .carousel-caption { position: absolute; left: 0; right: 0; bottom: 0; padding: 15px; background: #333333; background: rgba(0, 0, 0, 0.75); } .carousel-caption h4, .carousel-caption p { color: #ffffff; line-height: 19px; } .carousel-caption h4 { margin: 0 0 5px; } .carousel-caption p { margin-bottom: 0; } .hero-unit { padding: 60px; margin-bottom: 30px; font-size: 18px; font-weight: 200; line-height: 28.5px; color: inherit; background-color: #eeeeee; -webkit-border-radius: 6px; -moz-border-radius: 6px; border-radius: 6px; } .hero-unit h1 { margin-bottom: 0; font-size: 60px; line-height: 1; color: inherit; letter-spacing: -1px; } .hero-unit li { line-height: 28.5px; } .pull-right { float: right; } .pull-left { float: left; } .hide { display: none; } .show { display: block; } .invisible { visibility: hidden; } .affix { position: fixed; } /*! * Bootstrap Responsive v2.3.1 * * Copyright 2012 Twitter, Inc * Licensed under the Apache License v2.0 * http://www.apache.org/licenses/LICENSE-2.0 * * Designed and built with all the love in the world @twitter by @mdo and @fat. */ .clearfix { *zoom: 1; } .clearfix:before, .clearfix:after { display: table; content: ""; line-height: 0; } .clearfix:after { clear: both; } .hide-text { font: 0/0 a; color: transparent; text-shadow: none; background-color: transparent; border: 0; } .input-block-level { display: block; width: 100%; min-height: 29px; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } @-ms-viewport { width: device-width; } .hidden { display: none; visibility: hidden; } .visible-phone { display: none !important; } .visible-tablet { display: none !important; } .hidden-desktop { display: none !important; } .visible-desktop { display: inherit !important; } @media (min-width: 768px) and (max-width: 979px) { .hidden-desktop { display: inherit !important; } .visible-desktop { display: none !important ; } .visible-tablet { display: inherit !important; } .hidden-tablet { display: none !important; } } @media (max-width: 767px) { .hidden-desktop { display: inherit !important; } .visible-desktop { display: none !important; } .visible-phone { display: inherit !important; } .hidden-phone { display: none !important; } } .visible-print { display: none !important; } @media print { .visible-print { display: inherit !important; } .hidden-print { display: none !important; } } @media (min-width: 1200px) { .row { margin-left: -30px; *zoom: 1; } .row:before, .row:after { display: table; content: ""; line-height: 0; } .row:after { clear: both; } .row:before, .row:after { display: table; content: ""; line-height: 0; } .row:after { clear: both; } [class*="span"] { float: left; min-height: 1px; margin-left: 30px; } .container, .navbar-static-top .container, .navbar-fixed-top .container, .navbar-fixed-bottom .container { width: 1170px; } .span12 { width: 1170px; } .span11 { width: 1070px; } .span10 { width: 970px; } .span9 { width: 870px; } .span8 { width: 770px; } .span7 { width: 670px; } .span6 { width: 570px; } .span5 { width: 470px; } .span4 { width: 370px; } .span3 { width: 270px; } .span2 { width: 170px; } .span1 { width: 70px; } .offset12 { margin-left: 1230px; } .offset11 { margin-left: 1130px; } .offset10 { margin-left: 1030px; } .offset9 { margin-left: 930px; } .offset8 { margin-left: 830px; } .offset7 { margin-left: 730px; } .offset6 { margin-left: 630px; } .offset5 { margin-left: 530px; } .offset4 { margin-left: 430px; } .offset3 { margin-left: 330px; } .offset2 { margin-left: 230px; } .offset1 { margin-left: 130px; } .row { margin-left: -30px; *zoom: 1; } .row:before, .row:after { display: table; content: ""; line-height: 0; } .row:after { clear: both; } .row:before, .row:after { display: table; content: ""; line-height: 0; } .row:after { clear: both; } [class*="span"] { float: left; min-height: 1px; margin-left: 30px; } .container, .navbar-static-top .container, .navbar-fixed-top .container, .navbar-fixed-bottom .container { width: 1170px; } .span12 { width: 1170px; } .span11 { width: 1070px; } .span10 { width: 970px; } .span9 { width: 870px; } .span8 { width: 770px; } .span7 { width: 670px; } .span6 { width: 570px; } .span5 { width: 470px; } .span4 { width: 370px; } .span3 { width: 270px; } .span2 { width: 170px; } .span1 { width: 70px; } .offset12 { margin-left: 1230px; } .offset11 { margin-left: 1130px; } .offset10 { margin-left: 1030px; } .offset9 { margin-left: 930px; } .offset8 { margin-left: 830px; } .offset7 { margin-left: 730px; } .offset6 { margin-left: 630px; } .offset5 { margin-left: 530px; } .offset4 { margin-left: 430px; } .offset3 { margin-left: 330px; } .offset2 { margin-left: 230px; } .offset1 { margin-left: 130px; } .row-fluid { width: 100%; *zoom: 1; } .row-fluid:before, .row-fluid:after { display: table; content: ""; line-height: 0; } .row-fluid:after { clear: both; } .row-fluid:before, .row-fluid:after { display: table; content: ""; line-height: 0; } .row-fluid:after { clear: both; } .row-fluid [class*="span"] { display: block; width: 100%; min-height: 29px; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; float: left; margin-left: 2.564102564102564%; *margin-left: 2.5109110747408616%; } .row-fluid [class*="span"]:first-child { margin-left: 0; } .row-fluid .controls-row [class*="span"] + [class*="span"] { margin-left: 2.564102564102564%; } .row-fluid .span12 { width: 100%; *width: 99.94680851063829%; } .row-fluid .span11 { width: 91.45299145299145%; *width: 91.39979996362975%; } .row-fluid .span10 { width: 82.90598290598291%; *width: 82.8527914166212%; } .row-fluid .span9 { width: 74.35897435897436%; *width: 74.30578286961266%; } .row-fluid .span8 { width: 65.81196581196582%; *width: 65.75877432260411%; } .row-fluid .span7 { width: 57.26495726495726%; *width: 57.21176577559556%; } .row-fluid .span6 { width: 48.717948717948715%; *width: 48.664757228587014%; } .row-fluid .span5 { width: 40.17094017094017%; *width: 40.11774868157847%; } .row-fluid .span4 { width: 31.623931623931625%; *width: 31.570740134569924%; } .row-fluid .span3 { width: 23.076923076923077%; *width: 23.023731587561375%; } .row-fluid .span2 { width: 14.52991452991453%; *width: 14.476723040552828%; } .row-fluid .span1 { width: 5.982905982905983%; *width: 5.929714493544281%; } .row-fluid .offset12 { margin-left: 105.12820512820512%; *margin-left: 105.02182214948171%; } .row-fluid .offset12:first-child { margin-left: 102.56410256410257%; *margin-left: 102.45771958537915%; } .row-fluid .offset11 { margin-left: 96.58119658119658%; *margin-left: 96.47481360247316%; } .row-fluid .offset11:first-child { margin-left: 94.01709401709402%; *margin-left: 93.91071103837061%; } .row-fluid .offset10 { margin-left: 88.03418803418803%; *margin-left: 87.92780505546462%; } .row-fluid .offset10:first-child { margin-left: 85.47008547008548%; *margin-left: 85.36370249136206%; } .row-fluid .offset9 { margin-left: 79.48717948717949%; *margin-left: 79.38079650845607%; } .row-fluid .offset9:first-child { margin-left: 76.92307692307693%; *margin-left: 76.81669394435352%; } .row-fluid .offset8 { margin-left: 70.94017094017094%; *margin-left: 70.83378796144753%; } .row-fluid .offset8:first-child { margin-left: 68.37606837606839%; *margin-left: 68.26968539734497%; } .row-fluid .offset7 { margin-left: 62.393162393162385%; *margin-left: 62.28677941443899%; } .row-fluid .offset7:first-child { margin-left: 59.82905982905982%; *margin-left: 59.72267685033642%; } .row-fluid .offset6 { margin-left: 53.84615384615384%; *margin-left: 53.739770867430444%; } .row-fluid .offset6:first-child { margin-left: 51.28205128205128%; *margin-left: 51.175668303327875%; } .row-fluid .offset5 { margin-left: 45.299145299145295%; *margin-left: 45.1927623204219%; } .row-fluid .offset5:first-child { margin-left: 42.73504273504273%; *margin-left: 42.62865975631933%; } .row-fluid .offset4 { margin-left: 36.75213675213675%; *margin-left: 36.645753773413354%; } .row-fluid .offset4:first-child { margin-left: 34.18803418803419%; *margin-left: 34.081651209310785%; } .row-fluid .offset3 { margin-left: 28.205128205128204%; *margin-left: 28.0987452264048%; } .row-fluid .offset3:first-child { margin-left: 25.641025641025642%; *margin-left: 25.53464266230224%; } .row-fluid .offset2 { margin-left: 19.65811965811966%; *margin-left: 19.551736679396257%; } .row-fluid .offset2:first-child { margin-left: 17.094017094017094%; *margin-left: 16.98763411529369%; } .row-fluid .offset1 { margin-left: 11.11111111111111%; *margin-left: 11.004728132387708%; } .row-fluid .offset1:first-child { margin-left: 8.547008547008547%; *margin-left: 8.440625568285142%; } .row-fluid { width: 100%; *zoom: 1; } .row-fluid:before, .row-fluid:after { display: table; content: ""; line-height: 0; } .row-fluid:after { clear: both; } .row-fluid:before, .row-fluid:after { display: table; content: ""; line-height: 0; } .row-fluid:after { clear: both; } .row-fluid [class*="span"] { display: block; width: 100%; min-height: 29px; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; float: left; margin-left: 2.564102564102564%; *margin-left: 2.5109110747408616%; } .row-fluid [class*="span"]:first-child { margin-left: 0; } .row-fluid .controls-row [class*="span"] + [class*="span"] { margin-left: 2.564102564102564%; } .row-fluid .span12 { width: 100%; *width: 99.94680851063829%; } .row-fluid .span11 { width: 91.45299145299145%; *width: 91.39979996362975%; } .row-fluid .span10 { width: 82.90598290598291%; *width: 82.8527914166212%; } .row-fluid .span9 { width: 74.35897435897436%; *width: 74.30578286961266%; } .row-fluid .span8 { width: 65.81196581196582%; *width: 65.75877432260411%; } .row-fluid .span7 { width: 57.26495726495726%; *width: 57.21176577559556%; } .row-fluid .span6 { width: 48.717948717948715%; *width: 48.664757228587014%; } .row-fluid .span5 { width: 40.17094017094017%; *width: 40.11774868157847%; } .row-fluid .span4 { width: 31.623931623931625%; *width: 31.570740134569924%; } .row-fluid .span3 { width: 23.076923076923077%; *width: 23.023731587561375%; } .row-fluid .span2 { width: 14.52991452991453%; *width: 14.476723040552828%; } .row-fluid .span1 { width: 5.982905982905983%; *width: 5.929714493544281%; } .row-fluid .offset12 { margin-left: 105.12820512820512%; *margin-left: 105.02182214948171%; } .row-fluid .offset12:first-child { margin-left: 102.56410256410257%; *margin-left: 102.45771958537915%; } .row-fluid .offset11 { margin-left: 96.58119658119658%; *margin-left: 96.47481360247316%; } .row-fluid .offset11:first-child { margin-left: 94.01709401709402%; *margin-left: 93.91071103837061%; } .row-fluid .offset10 { margin-left: 88.03418803418803%; *margin-left: 87.92780505546462%; } .row-fluid .offset10:first-child { margin-left: 85.47008547008548%; *margin-left: 85.36370249136206%; } .row-fluid .offset9 { margin-left: 79.48717948717949%; *margin-left: 79.38079650845607%; } .row-fluid .offset9:first-child { margin-left: 76.92307692307693%; *margin-left: 76.81669394435352%; } .row-fluid .offset8 { margin-left: 70.94017094017094%; *margin-left: 70.83378796144753%; } .row-fluid .offset8:first-child { margin-left: 68.37606837606839%; *margin-left: 68.26968539734497%; } .row-fluid .offset7 { margin-left: 62.393162393162385%; *margin-left: 62.28677941443899%; } .row-fluid .offset7:first-child { margin-left: 59.82905982905982%; *margin-left: 59.72267685033642%; } .row-fluid .offset6 { margin-left: 53.84615384615384%; *margin-left: 53.739770867430444%; } .row-fluid .offset6:first-child { margin-left: 51.28205128205128%; *margin-left: 51.175668303327875%; } .row-fluid .offset5 { margin-left: 45.299145299145295%; *margin-left: 45.1927623204219%; } .row-fluid .offset5:first-child { margin-left: 42.73504273504273%; *margin-left: 42.62865975631933%; } .row-fluid .offset4 { margin-left: 36.75213675213675%; *margin-left: 36.645753773413354%; } .row-fluid .offset4:first-child { margin-left: 34.18803418803419%; *margin-left: 34.081651209310785%; } .row-fluid .offset3 { margin-left: 28.205128205128204%; *margin-left: 28.0987452264048%; } .row-fluid .offset3:first-child { margin-left: 25.641025641025642%; *margin-left: 25.53464266230224%; } .row-fluid .offset2 { margin-left: 19.65811965811966%; *margin-left: 19.551736679396257%; } .row-fluid .offset2:first-child { margin-left: 17.094017094017094%; *margin-left: 16.98763411529369%; } .row-fluid .offset1 { margin-left: 11.11111111111111%; *margin-left: 11.004728132387708%; } .row-fluid .offset1:first-child { margin-left: 8.547008547008547%; *margin-left: 8.440625568285142%; } input, textarea, .uneditable-input { margin-left: 0; } .controls-row [class*="span"] + [class*="span"] { margin-left: 30px; } input.span12, textarea.span12, .uneditable-input.span12 { width: 1156px; } input.span11, textarea.span11, .uneditable-input.span11 { width: 1056px; } input.span10, textarea.span10, .uneditable-input.span10 { width: 956px; } input.span9, textarea.span9, .uneditable-input.span9 { width: 856px; } input.span8, textarea.span8, .uneditable-input.span8 { width: 756px; } input.span7, textarea.span7, .uneditable-input.span7 { width: 656px; } input.span6, textarea.span6, .uneditable-input.span6 { width: 556px; } input.span5, textarea.span5, .uneditable-input.span5 { width: 456px; } input.span4, textarea.span4, .uneditable-input.span4 { width: 356px; } input.span3, textarea.span3, .uneditable-input.span3 { width: 256px; } input.span2, textarea.span2, .uneditable-input.span2 { width: 156px; } input.span1, textarea.span1, .uneditable-input.span1 { width: 56px; } input, textarea, .uneditable-input { margin-left: 0; } .controls-row [class*="span"] + [class*="span"] { margin-left: 30px; } input.span12, textarea.span12, .uneditable-input.span12 { width: 1156px; } input.span11, textarea.span11, .uneditable-input.span11 { width: 1056px; } input.span10, textarea.span10, .uneditable-input.span10 { width: 956px; } input.span9, textarea.span9, .uneditable-input.span9 { width: 856px; } input.span8, textarea.span8, .uneditable-input.span8 { width: 756px; } input.span7, textarea.span7, .uneditable-input.span7 { width: 656px; } input.span6, textarea.span6, .uneditable-input.span6 { width: 556px; } input.span5, textarea.span5, .uneditable-input.span5 { width: 456px; } input.span4, textarea.span4, .uneditable-input.span4 { width: 356px; } input.span3, textarea.span3, .uneditable-input.span3 { width: 256px; } input.span2, textarea.span2, .uneditable-input.span2 { width: 156px; } input.span1, textarea.span1, .uneditable-input.span1 { width: 56px; } .thumbnails { margin-left: -30px; } .thumbnails > li { margin-left: 30px; } .row-fluid .thumbnails { margin-left: 0; } } @media (min-width: 768px) and (max-width: 979px) { .row { margin-left: -20px; *zoom: 1; } .row:before, .row:after { display: table; content: ""; line-height: 0; } .row:after { clear: both; } .row:before, .row:after { display: table; content: ""; line-height: 0; } .row:after { clear: both; } [class*="span"] { float: left; min-height: 1px; margin-left: 20px; } .container, .navbar-static-top .container, .navbar-fixed-top .container, .navbar-fixed-bottom .container { width: 724px; } .span12 { width: 724px; } .span11 { width: 662px; } .span10 { width: 600px; } .span9 { width: 538px; } .span8 { width: 476px; } .span7 { width: 414px; } .span6 { width: 352px; } .span5 { width: 290px; } .span4 { width: 228px; } .span3 { width: 166px; } .span2 { width: 104px; } .span1 { width: 42px; } .offset12 { margin-left: 764px; } .offset11 { margin-left: 702px; } .offset10 { margin-left: 640px; } .offset9 { margin-left: 578px; } .offset8 { margin-left: 516px; } .offset7 { margin-left: 454px; } .offset6 { margin-left: 392px; } .offset5 { margin-left: 330px; } .offset4 { margin-left: 268px; } .offset3 { margin-left: 206px; } .offset2 { margin-left: 144px; } .offset1 { margin-left: 82px; } .row { margin-left: -20px; *zoom: 1; } .row:before, .row:after { display: table; content: ""; line-height: 0; } .row:after { clear: both; } .row:before, .row:after { display: table; content: ""; line-height: 0; } .row:after { clear: both; } [class*="span"] { float: left; min-height: 1px; margin-left: 20px; } .container, .navbar-static-top .container, .navbar-fixed-top .container, .navbar-fixed-bottom .container { width: 724px; } .span12 { width: 724px; } .span11 { width: 662px; } .span10 { width: 600px; } .span9 { width: 538px; } .span8 { width: 476px; } .span7 { width: 414px; } .span6 { width: 352px; } .span5 { width: 290px; } .span4 { width: 228px; } .span3 { width: 166px; } .span2 { width: 104px; } .span1 { width: 42px; } .offset12 { margin-left: 764px; } .offset11 { margin-left: 702px; } .offset10 { margin-left: 640px; } .offset9 { margin-left: 578px; } .offset8 { margin-left: 516px; } .offset7 { margin-left: 454px; } .offset6 { margin-left: 392px; } .offset5 { margin-left: 330px; } .offset4 { margin-left: 268px; } .offset3 { margin-left: 206px; } .offset2 { margin-left: 144px; } .offset1 { margin-left: 82px; } .row-fluid { width: 100%; *zoom: 1; } .row-fluid:before, .row-fluid:after { display: table; content: ""; line-height: 0; } .row-fluid:after { clear: both; } .row-fluid:before, .row-fluid:after { display: table; content: ""; line-height: 0; } .row-fluid:after { clear: both; } .row-fluid [class*="span"] { display: block; width: 100%; min-height: 29px; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; float: left; margin-left: 2.7624309392265194%; *margin-left: 2.709239449864817%; } .row-fluid [class*="span"]:first-child { margin-left: 0; } .row-fluid .controls-row [class*="span"] + [class*="span"] { margin-left: 2.7624309392265194%; } .row-fluid .span12 { width: 100%; *width: 99.94680851063829%; } .row-fluid .span11 { width: 91.43646408839778%; *width: 91.38327259903608%; } .row-fluid .span10 { width: 82.87292817679558%; *width: 82.81973668743387%; } .row-fluid .span9 { width: 74.30939226519337%; *width: 74.25620077583166%; } .row-fluid .span8 { width: 65.74585635359117%; *width: 65.69266486422946%; } .row-fluid .span7 { width: 57.18232044198895%; *width: 57.12912895262725%; } .row-fluid .span6 { width: 48.61878453038674%; *width: 48.56559304102504%; } .row-fluid .span5 { width: 40.05524861878453%; *width: 40.00205712942283%; } .row-fluid .span4 { width: 31.491712707182323%; *width: 31.43852121782062%; } .row-fluid .span3 { width: 22.92817679558011%; *width: 22.87498530621841%; } .row-fluid .span2 { width: 14.3646408839779%; *width: 14.311449394616199%; } .row-fluid .span1 { width: 5.801104972375691%; *width: 5.747913483013988%; } .row-fluid .offset12 { margin-left: 105.52486187845304%; *margin-left: 105.41847889972962%; } .row-fluid .offset12:first-child { margin-left: 102.76243093922652%; *margin-left: 102.6560479605031%; } .row-fluid .offset11 { margin-left: 96.96132596685082%; *margin-left: 96.8549429881274%; } .row-fluid .offset11:first-child { margin-left: 94.1988950276243%; *margin-left: 94.09251204890089%; } .row-fluid .offset10 { margin-left: 88.39779005524862%; *margin-left: 88.2914070765252%; } .row-fluid .offset10:first-child { margin-left: 85.6353591160221%; *margin-left: 85.52897613729868%; } .row-fluid .offset9 { margin-left: 79.8342541436464%; *margin-left: 79.72787116492299%; } .row-fluid .offset9:first-child { margin-left: 77.07182320441989%; *margin-left: 76.96544022569647%; } .row-fluid .offset8 { margin-left: 71.2707182320442%; *margin-left: 71.16433525332079%; } .row-fluid .offset8:first-child { margin-left: 68.50828729281768%; *margin-left: 68.40190431409427%; } .row-fluid .offset7 { margin-left: 62.70718232044199%; *margin-left: 62.600799341718584%; } .row-fluid .offset7:first-child { margin-left: 59.94475138121547%; *margin-left: 59.838368402492065%; } .row-fluid .offset6 { margin-left: 54.14364640883978%; *margin-left: 54.037263430116376%; } .row-fluid .offset6:first-child { margin-left: 51.38121546961326%; *margin-left: 51.27483249088986%; } .row-fluid .offset5 { margin-left: 45.58011049723757%; *margin-left: 45.47372751851417%; } .row-fluid .offset5:first-child { margin-left: 42.81767955801105%; *margin-left: 42.71129657928765%; } .row-fluid .offset4 { margin-left: 37.01657458563536%; *margin-left: 36.91019160691196%; } .row-fluid .offset4:first-child { margin-left: 34.25414364640884%; *margin-left: 34.14776066768544%; } .row-fluid .offset3 { margin-left: 28.45303867403315%; *margin-left: 28.346655695309746%; } .row-fluid .offset3:first-child { margin-left: 25.69060773480663%; *margin-left: 25.584224756083227%; } .row-fluid .offset2 { margin-left: 19.88950276243094%; *margin-left: 19.783119783707537%; } .row-fluid .offset2:first-child { margin-left: 17.12707182320442%; *margin-left: 17.02068884448102%; } .row-fluid .offset1 { margin-left: 11.32596685082873%; *margin-left: 11.219583872105325%; } .row-fluid .offset1:first-child { margin-left: 8.56353591160221%; *margin-left: 8.457152932878806%; } .row-fluid { width: 100%; *zoom: 1; } .row-fluid:before, .row-fluid:after { display: table; content: ""; line-height: 0; } .row-fluid:after { clear: both; } .row-fluid:before, .row-fluid:after { display: table; content: ""; line-height: 0; } .row-fluid:after { clear: both; } .row-fluid [class*="span"] { display: block; width: 100%; min-height: 29px; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; float: left; margin-left: 2.7624309392265194%; *margin-left: 2.709239449864817%; } .row-fluid [class*="span"]:first-child { margin-left: 0; } .row-fluid .controls-row [class*="span"] + [class*="span"] { margin-left: 2.7624309392265194%; } .row-fluid .span12 { width: 100%; *width: 99.94680851063829%; } .row-fluid .span11 { width: 91.43646408839778%; *width: 91.38327259903608%; } .row-fluid .span10 { width: 82.87292817679558%; *width: 82.81973668743387%; } .row-fluid .span9 { width: 74.30939226519337%; *width: 74.25620077583166%; } .row-fluid .span8 { width: 65.74585635359117%; *width: 65.69266486422946%; } .row-fluid .span7 { width: 57.18232044198895%; *width: 57.12912895262725%; } .row-fluid .span6 { width: 48.61878453038674%; *width: 48.56559304102504%; } .row-fluid .span5 { width: 40.05524861878453%; *width: 40.00205712942283%; } .row-fluid .span4 { width: 31.491712707182323%; *width: 31.43852121782062%; } .row-fluid .span3 { width: 22.92817679558011%; *width: 22.87498530621841%; } .row-fluid .span2 { width: 14.3646408839779%; *width: 14.311449394616199%; } .row-fluid .span1 { width: 5.801104972375691%; *width: 5.747913483013988%; } .row-fluid .offset12 { margin-left: 105.52486187845304%; *margin-left: 105.41847889972962%; } .row-fluid .offset12:first-child { margin-left: 102.76243093922652%; *margin-left: 102.6560479605031%; } .row-fluid .offset11 { margin-left: 96.96132596685082%; *margin-left: 96.8549429881274%; } .row-fluid .offset11:first-child { margin-left: 94.1988950276243%; *margin-left: 94.09251204890089%; } .row-fluid .offset10 { margin-left: 88.39779005524862%; *margin-left: 88.2914070765252%; } .row-fluid .offset10:first-child { margin-left: 85.6353591160221%; *margin-left: 85.52897613729868%; } .row-fluid .offset9 { margin-left: 79.8342541436464%; *margin-left: 79.72787116492299%; } .row-fluid .offset9:first-child { margin-left: 77.07182320441989%; *margin-left: 76.96544022569647%; } .row-fluid .offset8 { margin-left: 71.2707182320442%; *margin-left: 71.16433525332079%; } .row-fluid .offset8:first-child { margin-left: 68.50828729281768%; *margin-left: 68.40190431409427%; } .row-fluid .offset7 { margin-left: 62.70718232044199%; *margin-left: 62.600799341718584%; } .row-fluid .offset7:first-child { margin-left: 59.94475138121547%; *margin-left: 59.838368402492065%; } .row-fluid .offset6 { margin-left: 54.14364640883978%; *margin-left: 54.037263430116376%; } .row-fluid .offset6:first-child { margin-left: 51.38121546961326%; *margin-left: 51.27483249088986%; } .row-fluid .offset5 { margin-left: 45.58011049723757%; *margin-left: 45.47372751851417%; } .row-fluid .offset5:first-child { margin-left: 42.81767955801105%; *margin-left: 42.71129657928765%; } .row-fluid .offset4 { margin-left: 37.01657458563536%; *margin-left: 36.91019160691196%; } .row-fluid .offset4:first-child { margin-left: 34.25414364640884%; *margin-left: 34.14776066768544%; } .row-fluid .offset3 { margin-left: 28.45303867403315%; *margin-left: 28.346655695309746%; } .row-fluid .offset3:first-child { margin-left: 25.69060773480663%; *margin-left: 25.584224756083227%; } .row-fluid .offset2 { margin-left: 19.88950276243094%; *margin-left: 19.783119783707537%; } .row-fluid .offset2:first-child { margin-left: 17.12707182320442%; *margin-left: 17.02068884448102%; } .row-fluid .offset1 { margin-left: 11.32596685082873%; *margin-left: 11.219583872105325%; } .row-fluid .offset1:first-child { margin-left: 8.56353591160221%; *margin-left: 8.457152932878806%; } input, textarea, .uneditable-input { margin-left: 0; } .controls-row [class*="span"] + [class*="span"] { margin-left: 20px; } input.span12, textarea.span12, .uneditable-input.span12 { width: 710px; } input.span11, textarea.span11, .uneditable-input.span11 { width: 648px; } input.span10, textarea.span10, .uneditable-input.span10 { width: 586px; } input.span9, textarea.span9, .uneditable-input.span9 { width: 524px; } input.span8, textarea.span8, .uneditable-input.span8 { width: 462px; } input.span7, textarea.span7, .uneditable-input.span7 { width: 400px; } input.span6, textarea.span6, .uneditable-input.span6 { width: 338px; } input.span5, textarea.span5, .uneditable-input.span5 { width: 276px; } input.span4, textarea.span4, .uneditable-input.span4 { width: 214px; } input.span3, textarea.span3, .uneditable-input.span3 { width: 152px; } input.span2, textarea.span2, .uneditable-input.span2 { width: 90px; } input.span1, textarea.span1, .uneditable-input.span1 { width: 28px; } input, textarea, .uneditable-input { margin-left: 0; } .controls-row [class*="span"] + [class*="span"] { margin-left: 20px; } input.span12, textarea.span12, .uneditable-input.span12 { width: 710px; } input.span11, textarea.span11, .uneditable-input.span11 { width: 648px; } input.span10, textarea.span10, .uneditable-input.span10 { width: 586px; } input.span9, textarea.span9, .uneditable-input.span9 { width: 524px; } input.span8, textarea.span8, .uneditable-input.span8 { width: 462px; } input.span7, textarea.span7, .uneditable-input.span7 { width: 400px; } input.span6, textarea.span6, .uneditable-input.span6 { width: 338px; } input.span5, textarea.span5, .uneditable-input.span5 { width: 276px; } input.span4, textarea.span4, .uneditable-input.span4 { width: 214px; } input.span3, textarea.span3, .uneditable-input.span3 { width: 152px; } input.span2, textarea.span2, .uneditable-input.span2 { width: 90px; } input.span1, textarea.span1, .uneditable-input.span1 { width: 28px; } } @media (max-width: 767px) { body { padding-left: 20px; padding-right: 20px; } .navbar-fixed-top, .navbar-fixed-bottom, .navbar-static-top { margin-left: -20px; margin-right: -20px; } .container-fluid { padding: 0; } .dl-horizontal dt { float: none; clear: none; width: auto; text-align: left; } .dl-horizontal dd { margin-left: 0; } .container { width: auto; } .row-fluid { width: 100%; } .row, .thumbnails { margin-left: 0; } .thumbnails > li { float: none; margin-left: 0; } [class*="span"], .uneditable-input[class*="span"], .row-fluid [class*="span"] { float: none; display: block; width: 100%; margin-left: 0; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } .span12, .row-fluid .span12 { width: 100%; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } .row-fluid [class*="offset"]:first-child { margin-left: 0; } .input-large, .input-xlarge, .input-xxlarge, input[class*="span"], select[class*="span"], textarea[class*="span"], .uneditable-input { display: block; width: 100%; min-height: 29px; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } .input-prepend input, .input-append input, .input-prepend input[class*="span"], .input-append input[class*="span"] { display: inline-block; width: auto; } .controls-row [class*="span"] + [class*="span"] { margin-left: 0; } .modal { position: fixed; top: 20px; left: 20px; right: 20px; width: auto; margin: 0; } .modal.fade { top: -100px; } .modal.fade.in { top: 20px; } } @media (max-width: 480px) { .nav-collapse { -webkit-transform: translate3d(0, 0, 0); } .page-header h1 small { display: block; line-height: 19px; } input[type="checkbox"], input[type="radio"] { border: 1px solid #ccc; } .form-horizontal .control-label { float: none; width: auto; padding-top: 0; text-align: left; } .form-horizontal .controls { margin-left: 0; } .form-horizontal .control-list { padding-top: 0; } .form-horizontal .form-actions { padding-left: 10px; padding-right: 10px; } .media .pull-left, .media .pull-right { float: none; display: block; margin-bottom: 10px; } .media-object { margin-right: 0; margin-left: 0; } .modal { top: 10px; left: 10px; right: 10px; } .modal-header .close { padding: 10px; margin: -10px; } .carousel-caption { position: static; } } @media (max-width: 979px) { body { padding-top: 0; } .navbar-fixed-top, .navbar-fixed-bottom { position: static; } .navbar-fixed-top { margin-bottom: 19px; } .navbar-fixed-bottom { margin-top: 19px; } .navbar-fixed-top .navbar-inner, .navbar-fixed-bottom .navbar-inner { padding: 5px; } .navbar .container { width: auto; padding: 0; } .navbar .brand { padding-left: 10px; padding-right: 10px; margin: 0 0 0 -5px; } .nav-collapse { clear: both; } .nav-collapse .nav { float: none; margin: 0 0 9.5px; } .nav-collapse .nav > li { float: none; } .nav-collapse .nav > li > a { margin-bottom: 2px; } .nav-collapse .nav > .divider-vertical { display: none; } .nav-collapse .nav .nav-header { color: #777777; text-shadow: none; } .nav-collapse .nav > li > a, .nav-collapse .dropdown-menu a { padding: 9px 15px; font-weight: bold; color: #777777; -webkit-border-radius: 3px; -moz-border-radius: 3px; border-radius: 3px; } .nav-collapse .btn { padding: 4px 10px 4px; font-weight: normal; -webkit-border-radius: 4px; -moz-border-radius: 4px; border-radius: 4px; } .nav-collapse .dropdown-menu li + li a { margin-bottom: 2px; } .nav-collapse .nav > li > a:hover, .nav-collapse .nav > li > a:focus, .nav-collapse .dropdown-menu a:hover, .nav-collapse .dropdown-menu a:focus { background-color: #f2f2f2; } .navbar-inverse .nav-collapse .nav > li > a, .navbar-inverse .nav-collapse .dropdown-menu a { color: #999999; } .navbar-inverse .nav-collapse .nav > li > a:hover, .navbar-inverse .nav-collapse .nav > li > a:focus, .navbar-inverse .nav-collapse .dropdown-menu a:hover, .navbar-inverse .nav-collapse .dropdown-menu a:focus { background-color: #111111; } .nav-collapse.in .btn-group { margin-top: 5px; padding: 0; } .nav-collapse .dropdown-menu { position: static; top: auto; left: auto; float: none; display: none; max-width: none; margin: 0 15px; padding: 0; background-color: transparent; border: none; -webkit-border-radius: 0; -moz-border-radius: 0; border-radius: 0; -webkit-box-shadow: none; -moz-box-shadow: none; box-shadow: none; } .nav-collapse .open > .dropdown-menu { display: block; } .nav-collapse .dropdown-menu:before, .nav-collapse .dropdown-menu:after { display: none; } .nav-collapse .dropdown-menu .divider { display: none; } .nav-collapse .nav > li > .dropdown-menu:before, .nav-collapse .nav > li > .dropdown-menu:after { display: none; } .nav-collapse .navbar-form, .nav-collapse .navbar-search { float: none; padding: 9.5px 15px; margin: 9.5px 0; border-top: 1px solid #f2f2f2; border-bottom: 1px solid #f2f2f2; -webkit-box-shadow: inset 0 1px 0 rgba(255,255,255,.1), 0 1px 0 rgba(255,255,255,.1); -moz-box-shadow: inset 0 1px 0 rgba(255,255,255,.1), 0 1px 0 rgba(255,255,255,.1); box-shadow: inset 0 1px 0 rgba(255,255,255,.1), 0 1px 0 rgba(255,255,255,.1); } .navbar-inverse .nav-collapse .navbar-form, .navbar-inverse .nav-collapse .navbar-search { border-top-color: #111111; border-bottom-color: #111111; } .navbar .nav-collapse .nav.pull-right { float: none; margin-left: 0; } .nav-collapse, .nav-collapse.collapse { overflow: hidden; height: 0; } .navbar .btn-navbar { display: block; } .navbar-static .navbar-inner { padding-left: 10px; padding-right: 10px; } } @media (min-width: 980px) { .nav-collapse.collapse { height: auto !important; overflow: visible !important; } } numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/css/pygments.css0000664000175100017510000000751412370216245027367 0ustar vagrantvagrant00000000000000/* Styling for the source code listings: (mostly from pygments)*/ .highlight pre{ overflow: auto; padding: 5px; background-color: #ffffff; color: #333333; border: 1px solid #ac9; border-left: none; border-right: none; } /* Styling for pre elements: from http://perishablepress.com/press/2009/11/09/perfect-pre-tags/ */ /* no vertical scrollbars for IE 6 */ * html pre { padding-bottom:25px; overflow-y:hidden; overflow:visible; overflow-x:auto } /* no vertical scrollbars for IE 7 */ *:first-child+html pre { padding-bottom:25px; overflow-y:hidden; overflow:visible; overflow-x:auto } div#spc-section-body td.linenos pre { padding: 5px 0px; border: 0; background-color: transparent; color: #aaa; } .highlight .hll { background-color: #ffffcc } .highlight { background: #ffffff; } .highlight .c { color: #008000 } /* Comment */ .highlight .k { color: #000080; font-weight: bold } /* Keyword */ .highlight .n { color: #000000 } /* Name */ .highlight .o { color: #000000 } /* Operator */ .highlight .cm { color: #008000 } /* Comment.Multiline */ .highlight .cp { color: #008000 } /* Comment.Preproc */ .highlight .c1 { color: #008000 } /* Comment.Single */ .highlight .cs { color: #008000 } /* Comment.Special */ .highlight .kc { color: #000080; font-weight: bold } /* Keyword.Constant */ .highlight .kd { color: #000080; font-weight: bold } /* Keyword.Declaration */ .highlight .kn { color: #000080; font-weight: bold } /* Keyword.Namespace */ .highlight .kp { color: #000080; font-weight: bold } /* Keyword.Pseudo */ .highlight .kr { color: #000080; font-weight: bold } /* Keyword.Reserved */ .highlight .kt { color: #000080; font-weight: bold } /* Keyword.Type */ .highlight .m { color: #008080 } /* Literal.Number */ .highlight .s { color: #800080 } /* Literal.String */ .highlight .na { color: #000000 } /* Name.Attribute */ .highlight .nb { color: #407090 } /* Name.Builtin */ .highlight .nc { color: #0000F0; font-weight: bold } /* Name.Class */ .highlight .no { color: #000000 } /* Name.Constant */ .highlight .nd { color: #000000 } /* Name.Decorator */ .highlight .ni { color: #000000 } /* Name.Entity */ .highlight .ne { color: #000000 } /* Name.Exception */ .highlight .nf { color: #008080; font-weight: bold } /* Name.Function */ .highlight .nl { color: #000000 } /* Name.Label */ .highlight .nn { color: #000000 } /* Name.Namespace */ .highlight .nx { color: #000000 } /* Name.Other */ .highlight .py { color: #000000 } /* Name.Property */ .highlight .nt { color: #000000 } /* Name.Tag */ .highlight .nv { color: #000000 } /* Name.Variable */ .highlight .ow { color: #AA22FF; font-weight: bold } /* Operator.Word */ .highlight .mf { color: #008080 } /* Literal.Number.Float */ .highlight .mh { color: #008080 } /* Literal.Number.Hex */ .highlight .mi { color: #008080 } /* Literal.Number.Integer */ .highlight .mo { color: #008080 } /* Literal.Number.Oct */ .highlight .sb { color: #800080 } /* Literal.String.Backtick */ .highlight .sc { color: #800080 } /* Literal.String.Char */ .highlight .sd { color: #800000 } /* Literal.String.Doc */ .highlight .s2 { color: #800080 } /* Literal.String.Double */ .highlight .se { color: #800080 } /* Literal.String.Escape */ .highlight .sh { color: #800080 } /* Literal.String.Heredoc */ .highlight .si { color: #800080 } /* Literal.String.Interpol */ .highlight .sx { color: #800080 } /* Literal.String.Other */ .highlight .sr { color: #800080 } /* Literal.String.Regex */ .highlight .s1 { color: #800080 } /* Literal.String.Single */ .highlight .ss { color: #800080 } /* Literal.String.Symbol */ .highlight .bp { color: #407090 } /* Name.Builtin.Pseudo */ .highlight .vc { color: #000000 } /* Name.Variable.Class */ .highlight .vg { color: #000000 } /* Name.Variable.Global */ .highlight .vi { color: #000000 } /* Name.Variable.Instance */ .highlight .il { color: #008080 } /* Literal.Number.Integer.Long */ numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/css/extend.css0000664000175100017510000000366712370216245027015 0ustar vagrantvagrant00000000000000.container { width: 80%; } .navbar1 { padding-bottom: 10px; } .navbar1 .nav-pills { margin-bottom: 0px; font-size: 12px; } .navbar1 .nav-pills > li > a { padding-top: 2.5px; padding-bottom: 2.5px; } .navbar1 .dropdown.dropdown-menu { padding: 0px; } .header { padding-top: 30px; padding-bottom: 18px; } .SearchBar .form-search { margin-bottom: 0px; } .SearchBar .input-append input { height: 12px; } body { font-family: Segoe UI; background-color: #f9faf7; } .main { background-color: white; padding: 18px; -moz-box-shadow: 0 0 3px #888; -webkit-box-shadow: 0 0 3px #888; box-shadow: 0 0 3px #888; } .MainHeader h1 { font-weight: normal; } .content .contentTitle h4 { font-size: 18px; font-weight: normal; } .content .meta { font-size: small; } .tags .btn { border: none; font-size: 10px; font-weight: bold; } .navigation { font-size: 12px; padding-bottom: 12px; } .navigation .nav-title { color: #333333; font-family: "Segoe UI semibold"; font-size: 16px; text-transform: uppercase; } .navigation li { margin: 5px; } .snippetHeader { margin-bottom: 5px; } .snippetHeader .snippetTitle { font-size: 21px; line-height: 40px; border-bottom: 1px solid #e5e5e5; display: block; color: #333333; } .snippetInfo { padding-top: 10px; } .snippetInfo .dl-horizontal { margin: 5px; } .snippet-body { padding: 10px; } .snippet-body .accordion-group { border: none; } .snippet-body .accordion-heading { text-transform: uppercase; font-size: 14px; border-bottom: 1px solid #e5e5e5; } .snippet-body .accordion-heading .accordion-toggle { padding-top: 10px; padding-bottom: 5px; } .SearchResult { padding: 10px; padding-top: 0px; } .SearchResult .PageTitle { font-size: 21px; line-height: 40px; border-bottom: 1px solid #e5e5e5; padding-bottom: 5px; display: block; color: #333333; } .footer { padding: 10px; } .footer-inside { border-top: 1px solid #e5e5e5; padding: 10px; } numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/css/scipy-central.css0000664000175100017510000003763512370216245030305 0ustar vagrantvagrant00000000000000/* Styling to add still -------------------- div: spc-notice (general notices: e.g. submission requested is invalid) */ /* -------------------------------------------------------------------------*/ /* Basic layout of the document: no styling - that is applied further down. */ /* -------------------------------------------------------------------------*/ body { /* From: http://matthewjamestaylor.com/blog/perfect-3-column.htm */ margin:0; padding:0; border:0; /* This removes the border around the viewport in old versions of IE */ width:100%; background:#ffffff; min-width:600px; /* Minimum width of layout - remove line if not required */ /* The min-width property does not work in old versions of Internet Explorer */ } #spc-document-container{ position: relative; min-width: 50em; max-width: 90em; } #spc-header { clear: both; float: left; width: 100%; display: block; } .spc-header-row{ float: left; width: 100%; clear: both; } .spc-header-left{ float: left; position: relative; left: +1% } .spc-header-right{ float: right; position: relative; left: -1% } #spc-contentwrap{ display: block; overflow: hidden; } #spc-content-main{ float: left; width: 100%; } #spc-navigation-bottom{ clear: both; } #spc-footer{ clear: both; } /* -------------------------------------------- */ /* Now we will begin styling the various blocks */ /* -------------------------------------------- */ /* Document container */ #spc-document-container { font: 13px/1.5 'Lucida Grande','Lucida Sans Unicode','Geneva','Verdana',sans-serif; background: #FFFFFF; margin: auto; /* display container in the center of the page */ padding-top: 12px; } #spc-document-container img{ border: 0 } #spc-document-container a:visited { /* for IE6 */ color: purple; } /* Header block styling */ .spc-header-row{ text-align: center; } .spc-header-right{ float: right; text-align: right; } #spc-site-notice{ /*display: none;*/ color: #aaf; font-weight: bold; padding: 6px 0px; border-bottom: 1px dashed #aaf; background: #eee; /*display: none; Uncomment to remove the site notice*/ } #spc-site-title{ border-bottom: 1px solid #aaa; margin-top: -2em; } #spc-top-menu{ padding-top: 0.25em; } #spc-header h1 a { color: black; text-decoration: none; text-align: center; font: 36px/1.0 'Inconsolata','Lucida Grande','Lucida Sans Unicode','Geneva','Verdana',sans-serif; font-weight: bold; } #spc-top-menu a { text-decoration: none; font-weight: bold; font: 20px 'Inconsolata','Lucida Grande','Lucida Sans Unicode','Geneva','Verdana',sans-serif; } #spc-top-menu a:hover{ text-decoration: underline; } /* contentwrap block: applies to everything in the bulk of the page */ #spc-contentwrap { } /* The major chunk of content (left side); the sidebar comes later */ #spc-content-main{ background: #FFFFFF; } /* Border */ #spc-border { margin-left: 0px; background: white; padding-top: 0em; /* Don't remove top and bottom padding: leads to */ padding-bottom: 0em; /* unwanted horizontal borders around the document.*/ padding-left: 2em; padding-right: 2em; } /* spc-section-body: the current section of the document. The Sphinx generated HTML is inserted inside this DIV element. Specific formatting for the HTML should go here */ /* ----------------------- */ #spc-section-body { margin-bottom: 1em; } /* Styling for the headers */ div#spc-section-body h1, h2, h3, h4, h5, h6{ color: #20435C; font-family: 'Trebuchet MS', sans-serif; font-weight: normal; border-bottom: 0px solid #ccc; margin-bottom: 0.5em; } div#spc-section-body h1 { font-size: 200%; font-weight: bold;} div#spc-section-body h2 { font-size: 160%; font-weight: bold; color: #101074;} div#spc-section-body h3 { font-size: 140%; color: #362A13;} div#spc-section-body h4 { font-size: 120%; } div#spc-section-body h5 { font-size: 110%; } div#spc-section-body h6 { font-size: 100%; } .spc-title-in-span{font-size: 160%; font-weight: bold; color: #101074; float: left;} /* Styling for forms */ input, select, textarea{ border:solid 1px #aacfe4; padding: 4px 2px; margin-bottom: 1em; } /* Styling for hyperlinks */ div#spc-section-body a{ text-decoration: none; } div#spc-section-body a:hover{ text-decoration: underline; } /* Styling for images and figures: images are inline, figures are centered */ div#spc-section-body .align-center{ text-align: center; } /* Styling for elements */ tt { background-color:#EEE; color:#000; font: 16px/1.0 'Inconsolata', Monaco, Lucida Console, Liberation Mono, DejaVu Sans Mono, Bitstream Vera Sans Mono, Courier New, monospace, serif; } /* Main page */ #spc-site-statement{ width: 90%; margin: auto; text-align: center; padding-top: 1em; } #spc-search{ clear: both; float: none; display: block; margin: 0 auto; width: 700px; } #spc-search-form{ margin-top: 10pt; } #spc-search-input { cursor: auto; display: inline; height: 31px; float: left; width: 580px; border: 2px solid #3e5d34; padding: 0; padding-left: 0.5em; margin: 0; margin-right: 20px; color: #555; font-family: 'Inconsolata', 'Lucida Grande'; font-size: 24px; text-indent: 0px; text-shadow: none; text-transform: none; word-spacing: 0px; background: none; } #spc-search-button{ border: 1px outset #B6A792; vertical-align:middle; border:none; cursor:pointer; padding: 0; display: block; float: left; width: 80px; height: 35px; margin: 0; background: #ddd; display: inline-block; overflow: hidden; } #spc-search-results{ width: 75%; } #spc-search-results li{ margin: 0 auto; list-style-type: none; padding: 0.5em 0; float: left; } /* Submission buttons */ .spc-button-container { float: left; width: 100%; clear: both; margin-bottom:1em; } #spc-buttonlist { margin: 0 auto; list-style-type: none; padding: 0; padding-top: 2em; float: left; position: relative; left: 50%; } #spc-buttonlist li { float: left; position: relative; right: 50%; padding: 0em 1em; } #spc-buttonlist a { text-decoration: none; margin: 0 auto; display: block; } .spc-button{ background-position: 0px 0px; background-color: #DDDDDD; border: 1px outset #B6A792; cursor: auto; display: inline-block; vertical-align: middle; overflow: hidden; padding: 0; margin: 0; } /* Portals */ .spc-portal-container{ width: 65%; clear: both; padding: 0px; position: relative; display: block; margin: 0 auto; } .spc-portal-row-container { clear:both; float:left; width:100%; /* width of whole page */ overflow:hidden; /* This chops off any overhanging divs */ } .spc-portal-row { float:left; width:100%; position:relative; right:50%; /* right column width */ background:#fff; /* left column background colour */ } .spc-portal-left, .spc-portal-right{ float:left; position:relative; padding:0 0 1em 0; overflow:hidden; } .spc-portal-left { width:46%; /* left column content width (column width minus left and right padding) */ left:52%; /* right column width plus left column left padding */ } .spc-portal-right { width:46%; /* right column content width (column width minus left and right padding) */ left:56%; /* (right column width) plus (left column left and right padding) plus (right column left padding) */ } .spc-portal-container h3{ font: 14px/1.0 'Inconsolata', Monaco, Lucida Console, Sans Mono, Courier New, monospace, serif; text-align: center; border-bottom: 1px solid; } .spc-portal-container a{ text-decoration: none; font-weight: bold; font: 14px sans-serif; } .spc-portal-container a:hover{ text-decoration: underline; } .spc-portal-container ul{ list-style-type: square; } .spc-portal-container li{ margin-left: -1em; } /* Submission forms */ #spc-form-error-message{ margin-bottom: 1em; text-align: center; border-bottom:solid 1px #000; } .errorlist{ list-style-type: none; float: left; padding: 0; } .errorlist li{ font-style: italic; } .spc-field-error{ background: #ee8888; padding: 4px; } .spc-form-button{ padding: 5px; } /* column container */ /* http://matthewjamestaylor.com/blog/perfect-3-column.htm */ .colmask { position:relative; /* This fixes the IE7 overflow hidden bug */ clear:both; float:left; width:100%; /* width of whole page */ overflow:hidden; /* This chops off any overhanging divs */ padding-bottom: 1em; } /* common column settings */ .colright, .colmid, .colleft { float:left; width:100%; /* width of page */ position:relative; } .col1, .col2, .col3 { float:left; position:relative; padding:0; /* no left and right padding on columns */ overflow:hidden; } /* 3 Column settings */ .threecol { background:#fff; /* right column background colour */ } .threecol .colmid { right:25%; /* width of the right column */ background:#fff; /* center column background colour */ } .threecol .colleft { right:60%; /* width of the middle column */ background:#fff; /* left column background colour */ } .threecol .col1 { width:58%; /* width of center column content (column width minus padding on either side) */ left:101%; /* 100% plus left padding of center column */ } .threecol .col2 { width:13%; /* Width of left column content (column width minus padding on either side) */ left:28%; /* width of (right column) plus (center column left and right padding) plus (left column left padding) */ } .threecol .col3 { width:23%; /* Width of right column content (column width minus padding on either side) */ left:90%; /* Please make note of the brackets here: (100% - left column width) plus (center column left and right padding) plus (left column left and right padding) plus (right column left padding) (100-15)+(1+1)+(1+1)+(1)*/ } .form-field input, select, textarea{ width: 98%; max-width:1000px; min-width:500px; } .form-field-auto-width{ width: auto; } .spc-code-description{ height: 15em; } span.spc-helptext ul{ margin: 0; padding-left: 20px; } .spc-odd{ background: #DDF; } .spc-even{ background: #CCF; } li.spc-odd tt{ background-color: #DDF; } li.spc-even tt { background-color: #CCF; } /* Image upload */ #spc-item-upload { } #spc-item-upload-button{ padding: 0.5em; text-align: center; } .spc-item-upload-success{ background: #ffa; padding: 4px; } /* Tagging */ .ui-autocomplete { max-height: 150px; overflow-y: auto; overflow-x: hidden; /* prevent horizontal scrollbar */ padding-right: 20px; /* add padding to account for vertical scrollbar */ } /* IE 6 doesn't support max-height * we use height instead, but this forces the menu to always be this tall */ * html .ui-autocomplete { height: 100px; } .spc-tag{ background-color: #E0EAF1; color: #3E6D8E; border-bottom: 1px solid #37607D; border-right: 1px solid #37607D; text-decoration: none; padding: 4px 4px 3px 4px; margin: 2px 5px 2px 0px; font-size: 90%; line-height: 1.4; white-space: nowrap; cursor: pointer; float:left; } .spc-tag:hover{ background-color: #3E6D8E; color: #E0EAF1; } .spc-tag-cloud{ background-color: #FFF; color: #3E6D8E; border-bottom: 0px solid #37607D; border-right: 0px solid #37607D; text-decoration: none; padding: 0px 4px 0px 4px; margin: 2px 5px 2px 0px; font-size: 90%; white-space: nowrap; cursor: pointer; } .spc-tag-cloud:hover{ background-color: #FFF; color: #1E4D6E; } #spc-preview-edit-submit{ clear: both; } #spc-preview-edit-submit form input{ display: inline; padding: 5px; } #spc-item-submit{ margin-left:8em; font-weight: bold; } #spc-item-preview{ width:auto; min-width:0; padding: 0.5em; text-align:center; } #spc-item-header{ clear: both; padding: 0px; float: left; width: 102%; position: relative; display: block; margin: 0 auto; left: -1%; top: -20px; } #spc-item-header-left{ float: left; text-align: left; } #spc-item-header-right{ float: right; text-align: right; } div.spc-item-row { clear: both; padding-top: 10px; } div.spc-item-row span.spc-item-label { float: left; width: 200px; text-align: left; padding-right: 20px; padding-bottom: 4px; font-weight: bold; } div.spc-item-row span.spc-item-entry { float: left; min-width: 500px; max-width: 1000px; text-align: left; } div.spc-item-row span.spc-item-entry ul{ padding: 0; margin: 0; list-style-type: none; } div.spc-item-row span.spc-50-50{ float: left; width: 49%; text-align: left; } .spc-help-section a{ color: #0069CC; margin-top: 1em; } .spc-entries-list ul{ padding: 0; margin: 0; list-style-type: none; } /* Unstyle certain elements in the code/link description fields */ .spc-item-description p{ margin: 0; margin-bottom: 1em; } .spc-item-row pre{ border: 0px solid #FFF; overflow: auto; padding: 5px; background-color: #EEE; border: none; margin: 0; font: 16px/1.0 'Inconsolata', Monaco, Lucida Console, Liberation Mono, DejaVu Sans Mono, Bitstream Vera Sans Mono, Courier New, monospace, serif; } /* Item display*/ #spc-itemdisp-container{ clear: both; padding: 0; padding-top: 1em; margin: 0 auto; width: 85%; } .spc-itemdisp-row-container { clear:both; float:left; width:100%; margin: 0 0 1em 0; } .spc-itemdisp-row { float:left; width:100%; } .spc-itemdisp-td{ float: left; padding-right: 1%; } .spc-itemdisp-description{ width: 50%; } .spc-itemdisp-link{ float: right; font-size: 80%; } div .spc-itemdisp-mainlink{ text-decoration: underline; float: left; width: 100%; } .spc-itemdisp-revinfo{ float: right; font-size: 80%; } .spc-itemdisp-created{ width: 23%; } .spc-itemdisp-tags{ width: 23%; } .spc-itemdisp-odd{ background: #fff8f1; } .spc-itemdisp-even{ background: #fff; } .spc-itemdisp-header{ background: #f1c79d; padding: 0.4em 0 0.4em 0; font-weight: bold; } #spc-itemdisp-pageheader{ text-align: center; font: 24px/1.0 'Inconsolata','Lucida Grande','Lucida Sans Unicode','Geneva','Verdana',sans-serif; font-weight: bold; } .spc-itemdisp-pagination{ float: left; } div#spc-itemdisp-container h1, h2, h3, h4, h5, h6{ font-weight: normal; border-bottom: 1px solid #ccc;} div#spc-itemdisp-container h1 { font-size: 130%; font-weight: bold;} div#spc-itemdisp-container h2 { font-size: 120%; font-weight: bold;} div#spc-itemdisp-container h3 { font-size: 110%;} div#spc-itemdisp-container h4 { font-size: 100%; } div#spc-itemdisp-container h5 { font-size: 100%; } div#spc-itemdisp-container h6 { font-size: 100%; } /* Permalinks and other minor info*/ .spc-minor-info { font-size: 80%; float: left; border-top: 1px solid #ddd; } .spc-minor-info p{ margin: 0; } .spc-minor-info a{ text-decoration: none; } .spc-minor-info a:hover{ text-decoration: underline; } /* User profile pages */ #spc-profile-user-options ul{ margin: 0 auto; padding: 0 0; } #spc-profile-user-options li{ margin: 0 auto; list-style-type: none; padding: 0 5px 0 5px; float: left; border-right: 1px solid; } #spc-profile-user-options li:first-child{ padding-left: 0px; } #spc-profile-user-options li:last-child{ border-right: none; } /* Styling for certain static pages */ #spc-static-centering{ display: block; margin: 0 auto; min-width: 30em; max-width: 50em; } /* spc-footer: http://www.alistapart.com/articles/practicalcss/ */ #spc-footer { clear: both; font-size: 90%; padding: 0px; float: left; width: 100%; position: relative; display: block; margin: 0 auto; border-top: 1px solid #aaa; } #spc-footer a{ text-decoration: none; font-weight: bold; font: 15px sans-serif; } #spc-footer a:hover{ text-decoration: underline; } .spc-footer-left{ float: left; text-align: left; } .spc-footer-right{ float: right; text-align: right; } .spc-footer-left ul{ margin: 0; padding: 0; } .spc-footer-left li{ display: inline; padding-left: 3px; padding-right: 7px; border-right: 0px solid #aaa; } .spc-indent{ margin-left: 15px; } .spc-flag{ padding-left: 1em; vertical-align: middle; } /* ---------------- */ /* Form styling */ /* ---------------- */ .spc-form{ padding-top: 2em; } .spc-form-label{ display: block; font-size: 14px; color: #444; } .spc-centering-div-container{ clear: both; margin: 0 auto; border: 1px; padding: 1em; float: left; } /* ---------------------- */ /* Miscellaneous elements */ /* ---------------------- */ numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/scipy.css_t0000664000175100017510000001014712370216246026400 0ustar vagrantvagrant00000000000000/* -*- css -*- * * sphinxdoc.css_t * ~~~~~~~~~~~~~~~ * * Sphinx stylesheet -- sphinxdoc theme. Originally created by * Armin Ronacher for Werkzeug. * * :copyright: Copyright 2007-2011 by the Sphinx team, see AUTHORS. * :license: BSD, see LICENSE for details. * */ @import url("basic.css"); @import url("css/scipy-central.css"); /* * General tweaks */ div.container-navbar-bottom { margin-top: 0; } div.container-navbar-bottom div.spc-navbar { margin-top: 0; } div.spc-navbar { margin: 0; } tt { color: inherit; font: inherit; } tt.literal { font-family: monospace; padding-left: 2px; background-color: rgb(242, 242, 242); } a tt.literal { border-bottom: none; background-color: inherit; } tt.xref { font-family: inherit; border-bottom: none; background-color: inherit; font-weight: normal; padding-left: 0px; } tt.descname { font-size: 16px; } dl.class > dt > em { font-weight: normal; } dl.function > dt > em { font-weight: normal; } dl.method > dt > em { font-weight: normal; } pre { border-radius: 0; border: none; font-family: monospace; } /* * Field lists */ table.field-list { border-collapse: collapse; border-spacing: 5px; margin-left: 1px; border-left: 5px solid rgb(238, 238, 238) !important; } table.field-list th.field-name { display: inline-block; padding: 1px 8px 1px 5px; white-space: nowrap; background-color: rgb(238, 238, 238); } table.field-list td.field-body { border-left: none !important; } table.field-list td.field-body > p { font-style: italic; } table.field-list td.field-body > p > strong { font-style: normal; } td.field-body blockquote { border-left: none; margin: 0; padding-left: 30px; } td.field-body blockquote p, dl.class blockquote p, dl.function blockquote p, dl.method blockquote p { font-family: inherit; font-size: inherit; font-weight: inherit; line-height: inherit; } /* * Sidebars and top logo */ div.sphinxsidebarwrapper { overflow: hidden; } div.spc-rightsidebar h3 { font-size: 120%; line-height: inherit; border-bottom: none; } div.spc-rightsidebar h4 { font-size: 120%; line-height: inherit; border-bottom: none; } div.top-scipy-org-logo-header { text-align: left; background-color: rgb(140, 170, 230); border-bottom: 8px solid rgb(0, 51, 153); margin-top: 10px; padding: 5px; box-shadow: 0px 0px 3px rgb(136, 136, 136); } /* * Headers */ h1 a { color: rgb(85, 85, 85); } h2 a { color: rgb(85, 85, 85); } h3 a { color: rgb(85, 85, 85); } h4 a { color: rgb(85, 85, 85); } h5 a { color: rgb(85, 85, 85); } h6 a { color: rgb(85, 85, 85); } h1 tt { font: inherit; border-bottom: none; } h2 tt { font: inherit; border-bottom: none; } h3 tt { font: inherit; border-bottom: none; } h4 tt { font: inherit; border-bottom: none; } h5 tt { font: inherit; border-bottom: none; } h6 tt { font: inherit; border-bottom: none; } div#spc-section-body h1 { color: rgb(85, 85, 85); } div#spc-section-body h2 { color: rgb(85, 85, 85); } div#spc-section-body h3 { color: rgb(85, 85, 85); } div#spc-section-body h4 { color: rgb(85, 85, 85); border-bottom: none; } div#spc-section-body h5 { color: rgb(85, 85, 85); border-bottom: none; } div#spc-section-body h6 { color: rgb(85, 85, 85); border-bottom: none; } p.rubric { color: rgb(85, 85, 85); font-size: 120%; font-weight: normal; border-bottom: 1px solid rgb(204, 204, 204); } /* * Tables */ table.citation { border: none; } table.docutils td, table.docutils th { border: none; } table.docutils { margin-bottom: 9.5px; } /* * Admonitions */ p.admonition-title { display: inline; } p.admonition-title:after { content: ":"; } div.seealso { background-color: #ffc; border: 1px solid #ff6; } div.seealso dt { float: left; clear: left; min-width: 4em; padding-right: 1em; } div.seealso dd { margin-top: 0; margin-bottom: 0; } div.warning { background-color: #ffe4e4; border: 1px solid #f66; } div.note { background-color: #eee; border: 1px solid #ccc; } numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/0000775000175100017510000000000012371375427024775 5ustar vagrantvagrant00000000000000numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/single-file-list-icon.png0000664000175100017510000001536412370216246031601 0ustar vagrantvagrant00000000000000‰PNG  IHDR  ‹Ïg-sBIT|dˆ pHYs.#.#x¥?vtEXtSoftwarewww.inkscape.org›î<tEXtAuthorAndreas Nilsson+ïä£tEXtCreation Time2005-10-15 ”W+IDATxœí{”UÇ¿UÕÕÓÓ™éÌ$“É“!/y’,ÊÃ%¼=F]% >ÖˆÖUˆI:p\²Btq=«Èñ± 𳂠 ®ˆá!²¸Èy’“d^=ž~UuÕÝ?zª»Þ]]]ÕÕ5SßsúôtÕýݺSõéßïÞß½UMB(W¢½n@ ‰­À@ž*0§ ä©yª“•ݳu `5€'ë T7ðâ†õ·;–:¡œHÃܳuK3€/ø€³ª®0P=ë€Ü¿aýíéj+sÊÞ àÕ¨¾µÀ·ˆî«¶²ª=à=[·„œ0½ÚÆò•8·Úp센 2øÚÚÚ°dñ2Ðå@ÕêE¢(b÷ÞÝ’6-ðNÿWM½N—8ùJ¬ZuÕª7ñù<^úë‹òMq£²Våx†¢Ï7^寵 ò€<•£y@=‰¢€|^pû0\P(M»ë£\0ŸÉT. 䣇î#Á ð€¾–ŸÁ“èC97ºõ>/è3¯'W OTkð©M>°îL&“H§ÇçzA– ¡µµÕ´ŒávB%¢Ë)•Jahh¨|A*‰˜è…׫µêÀ‰¨ú¯64Ö™ì®Xñ#|@`Ýh"y=¹=–¯À žŒ0¾ä+ø\Rà=P ¼Ê.þxORÝÇF½n†#R{¼PÈÚé¯fÃ.|Á“ƉD‰D¼nFÕòK¸­u.°îô»ðÌè’êg ­~á]ÑøðzÁLˆïäðŒm+oCµ t@ã'Ü3!¾“_¼^½'©îL$õºÕxÍÍMˆÇËÿbj½Âø@ŽãN××oÍÕËŠ•ÆFóü¨]ð‚©uªzðzn†Û`AjÊ/àÛ–¯#HDשüŸßÀ“h ¼Ú(P%/î»­Oø´ËÅÜ`6P¦ÀëY;¾“ª{ÛÚÚO®Á‘üÃ0–ì­‡Û`&D#–eÁ²îÔ=¦Ðìz½àÉ.+·úöÁ‚T—åðŒmË×áø€  ]ðJ¶ÅO6í¬ÛOð$MýâõÜÏé©Ò*u ×úÏ<ÜšyAÊЪ‚pk\‡áÖŠ'‹Ôà ‚PÁ]oš­6Ži½;ð…Ãa_z=+Ð yˆ.~Pø ì”ö•Û•··ûM§i ,°XÚ}ðëÞNýnÖtR5Ê*>Ù´³n_)x„ý™<²y‚)!DBnŸxo¼^Uý?Ê` ,(÷Á;<Èá¯Ý)Ŷxƒ5ó›5uäðøáì8•FoŠG^V}K :¢x׬.= ,m¹éE=õV9ÍöÅSpåY“ªoÇé ž<2¢ØÛf°áSØ ·fï„?OÅÕÆë½ÑŸÅw+ÃùÜxkæ7?âpïŽ^ìï×Â!i8'bûñQl?>Š“øüŠV\6g’ÕâEüë_{5Ûo¿°WTX MzðõAõg+0J6š gõLɨÚ`XÌ)ðÌ )á³.åèöÂéQM @åöòãQn˜×`¸§lºB»-ÊÒ¶½žÜ®#¦Ÿ2MdÔO¡]¿¨E3üò™  reÁxäÍA…]sƒ5 â†ÀTnåûåÝ)éÚJgˆ"ÈšžJ rebtÜõzú,Oþëƒ'©µQ»°PzÀri•ÖƒÌÓΠüâõAS0ú2þ¬Jˆ_sn+Y¦j/gô"„@E"–þ –œL¨÷Ûî‡Û±Ž¼Îó>šÒ^:¦žÚtV¶À('ÀÌÛK’.ì'—jÃðÃoayìÀUýk—NqÌ˩ˊ¢¨€¯ð.bxdXy¥((§dlÈå4L¹‹o?Ü–ìÍ r‚ù ÁÌëÉÕÖ°9LW”L¾pF ‹Úe³~wxD·`ÉZ·zÈh׆hJ Õ°×ÜÀàšs´‰ée^Ð(ü^qv3¦O2ÏýYÒÈ뉢Žãpô­#Øö«mØþìŸtኡú+;‹Z¹òhm‡ÜN:ÆØ¶x’œˆ$' )LWl+oÃî^mwgé”°´½ÅžŸY>¾¦„kÛë Üyé,„™B/ŸNáè r¾xe¨þËiÐ4 š¦@Ó ¦0fhMƒah04–e …Š/–eÁ0 šÍ0 @!I!•N!N#™Lâíî·qúÌ)+÷j ,aWtuäüz@Í®|ÒV×°§7‹KfjÉVŽ/ïOÇ´Ý‹fFËŽ2ö-ŸŪŽ(^•õï2yÍŽ¯>Þw^é‡z,ÓÒÀà]³J«íôÇ®YÔŠ–å æ…ãIÊáùãIô¥•ýΕ¡ž þêfÃhŠ5£½u"áòB^¾›Ð¢ø˜Çq¡¨¼€r€{ú2h†pNkƒj\u}=€€2X2þ?o%ñf"‡s[t÷[®c¾ §»lê¦%“Ë VÚÿ“ÞCnX2?xµð_{úpzT _;Æl&‰ó¢¹©‚(BDˆ¤ðlQ!ˆc‹„¼AÌ#Ÿò ¢q,©,Žý BÀ0!0L¨¸¢š ±³…ó$=·gdT¹„<²aÃ×÷˜œL˪A°p“v׋gðàkƒÅÝ3'±¸ïʸ|Žv•I5‹ôÄ _~æžüH'X©9£YŒîQkÿ¶Æû… ë–·Y‚¬\™Ïžß®ÚÛ4¯¬ nrÇ'cÚTë¿'¥Sòùüœóù<8ŽÏóày¾›TFú;“M#/(¾ ‚|ÃrÊÈ…™)ÕQ Áÿ¼½?—Á.î ¿;}}ÊðX |f³¾»{³øàoŽã”³èO¡OIâÿ=¡*_ÐÍ+¦ ck+ý¡~3¥—ÎQÎ÷¥y¤d÷Ó XÁ-òù|ñ%‹çyär9är9pWÜ/½ä6©ŒjðEð³;¾vÇK° fB”ewO OÑ-Ë‹[ÿÖ'³³|XÍé± )ÒïìÉàŠ_½…oíèʼnNc'`ûñQ¼çácø§?vãĈ¾åíØtQ».dv\·²Ýô¿Ï ¡™â mÔÌFh%y8½W.—C6›E.—S€§†P¤³)¢øœÂ]eP\ÁÊ«º·Ç|ÕðΞL…àé€þr¬©!|áüVÜñ—B˜Ì ¸ï•üÇ«˜ÓÌ¢³9ŒIaG†8â3™;žað£÷ÎF˜¡« »ê÷Û†öØqô¦ôoˆ_Å–B´ är9ð<_<®bùTqE )z>¹Ç“‡ZuøÍq9¤³Ê,Kˆ ýxýW7h&„«‘kψ–¼`{Œ5. ãuvÆ5W>*þì²VœáñÀžRZC$À±adžõ/ºZ3&±øõ‡ÏÆüÖÂmšNôÿ¤÷0Má“ËÛqïKÝšã6…€E!Y»Uã8$“Iµ™B€fÀ)B°G*«¬“5Ú9{²!×î ‘ôÎ1݇ôHzïÙM†ûÆ*„ÕpKéö í¹ë’v|û²Äl;áÖÌö³+;@ë4ÿŠ¢Èý©g(ô’ïŠÿžÓ0«×ÿM¨ûÆÂŒÙ³¾tíµ×öUxêÊÊõ{Bâß½r†îS¡.˜Å-+õï8³³b¥\{Öždz×5óšŠShfšÕÄâ‡WÏÆS×ÍǬæ°.\v^z¶“#¸z¾v­àûg)¿¼¢P‚QÑIê š§Þ–ÎŽB$Ê:›››ï¾ñú·C{y«–K}@%8ï›Û„箟‹v'ðZSCX=;†O/kÕ½éÛ.xeœà¬f?¾z&Y¿>8Œ]=áñv’GKƒ“X,™Ášù-…5w°Þ—³Óÿ“¿'ÒŠd/ΛÅ’Ö<ž—mE¡Ø·Á0…$­VCo†K#/*ÛÐÐа틟»å~˜-eªB.-FPm#À‚É øöåÓ-X—lìÝ\ÒŸ áæÖryÒ»¨¬–ýß“IìèVö»nZц9¥Ø&Œy59@jY…Nþ9ËeÀç9E=4M¿xÓ Ÿú€<ü v*Íj›€¯Ü\±CžÊ ›»_8¡h+CQøÄÒ6ô=£Ø.ŠÄÀr^NÂL.^Ð ÆŽ.>gé mmm" g×ñ‰hç= ©:À ð$;£ìµw+WÇ“xúˆò®·«çÇ1-B¯ª›.Š‚@©(Ë•@˜Î¥ ¨Â.€ÐôÖ¬YÓ€E >ÿy@+åªÏLjW%e9àÖ?Ñ´ûæUÓ Š"ø¼6M¤P>Òµ ¡ŸH4!¼‡bÄ÷müêæý  ¿ŽèÊLˆ…R–×Úë&¢M&㜩VbÛŸÉ㡽}eË~oG7 (—z-l‹àª³›!Š"8NÙ/#Š™ 5\ÖR-­s¨—Ižzÿ¦Må¹>¥Ðë8|@ < !Jïmw}_¹›¾è&r­'“¶©ßò¯÷eðÓ]=èMñ¸âçûð߯õWÔð"°ãí|pÛ>|é÷‡5Ûx÷Ü|ü¼Ö"`<¯ Á²{9*ñzÒÜn†Ké9ˆ§X*|ù¦M›Ô‰f9€®¨¦}@·¼ž„Ñ(¤R¯WG€ÛþôVñFò3£Ö>vŸzü Îj‰àäp9A0ÙÜÀà?¯ž£¸)œã”Ò4m)­"߯ó¼Q ðP[óÔϬ[·ÎÚœ¤Ãrm= üÑlnƒ'½Ó&Jïn*vÅ3Gµ XyàpÂøÖ€i1|t.¦Ç˜â¢QB8^?[tdsdù,tC@צÛ6ÿ›ÞÎZÉ•{BjŸQh4+kf[.ÜZ±]9£ ÛoZ†ù­ÚgéÒ9Mxæ °|jDq®4•¦V¹P+ø<ÑLY> _‹—lZ¿y‹vgmåÚT\­¼žü=¢15Zú—(f<œ·åê¸rîdìýÂ*Üý <º¿‡²Šg»PæMŽ`ù´F||q+ÞÝ9I¶tJzPaù<Ï«GÁD8ùÊçt6ŽÏéÞ F?Í¥ò_îêêªú©NÈqEÕ ƒ¦i„ÃÚ§‹*e!Ds‘%É·_57ŽÃŸ?[±1Ú_<½º¤¿ !ÓÀ«g£ëÒYÈæìïKã¾4f6±XÞÞˆ[Z»'…[å«°Wy@) £;—›M#KƒÝ>f‚Öm\¿ùQ£óì…\„Hà0Œñr,5|z)ùE7Àì3EQ–!–Þ¥ò•¨…¨R˜.¬¤^6µa̳‘â{é TZE‘`tTë¨Ô^/“Í •Ij«Êô¬›¿²Y»àÐcy6§¼eS¿¼tQÕvzý=³ÏFðA%m3ƒO ž”Õ%š€'ÿ,=Ÿ… —Ë!•*­J¦)4Eûxét ™\Z}ˤ\Ç(`ãÆõ›†Ç}=#9‚ Ö§édEFÞO•üs9ïf¶Ý,ìÊÛ«õzbñ‹'©¼—u,Ùö(Ór¡‹t&…ÑTY.kv‡ ¡înjlúÞ-·Übý§A=*~ ÷À7N§ôG¤Š+:'¯¸ŸdkTa¥´“¦Þ × (S› ê»Ï˜R[S@¡›5ö´P‚R‡ŸÈîbé?•¶ËN‚tonɶX„ $”OFàøúÚß –I…ûÃTþ®[oíªúÁAµ>à€9ÍeqèðAªè"•¬}â<*r×ë»e²¢œøMØ{¶n¹ÀÝÕ7'$ÑZ—íMò>$ü²ë+]‰òÅëONõ¿ `Àç,u¨Î +“ßêgX "нcý\&€H{¬°¶©iÍþ±~¨ ÑÊŒc‘´ûYÎüú±~¦aJ €µ^…HVÂËŒ#ñùV8*àÇú™FXöC$„µ ¡k¬èT“ c‘‚uø€‹سy}«•GŽÇ'ž\7r¼9Èñ¸àÎqÂã‚Ëí„Ûí„Ói8Á`¡`Á€ô †ð ap0€€?„` ˆX,‘í¢Hx À<ÑÔ´&4 ÅÊËŒ‘ø|«—¸Àµ ‡s-ŽŠK 0ezê'W£º¶ååE()ÎE®× gú;Ë?9‘vˆ.]Ü–Ò‰”DÚúý!tvöãĉn´¶tâØ‘V4lAwg/²P¥üþ‘ ^kjZ3QIGH&`E â]øS‡r ‹…ÃìyÓ°dù\ÔOªDYi> ós`·Y :0ËßÄHrºìj^Vºš¦ÞK&“h4Žî?Ú;úp¬ù¶nÚ…}»!‘†ZlGÜàÞ¦¦5{Fðç9%e‚FX|¾ÕVðiËpéœÇóØíV„ÃQLkl€oåÌ™7 “jKawHÝ7(`*Bkl*ã8X,€…ã`áÄoÞ¢¦qŽ&Š ˆÅù ”µ@¤´Å@$Ë@ÎB”tùôH$†ÃGÚ±{çalÛ´ ‡öÅëÝf𦳕5‘±ûU?82A#$>ßj'€Oø&ÄÎ8Iåì³`޼ɨ®.F}CJKóFŒ p»ìl°ƒ‚¹tœ`å9Xy ¬윅Ku$‰ÆE"E¢Æ×XPH€¶ÌH€hDÜ#8|øví8ˆm›v£¥¹5ÓâmðKnjZÑò.eñùV{ÜàëÊÓ9çc;_úÒDMMKo_?xGŽáúg³X«…ƒ·€ç3{2Q¬‚H,aPÜì2A5Ÿ1]%„îžlzgÖ¿ø:Úº3yÄn¿°¦©iM_–^û”’ È’ø|«ó¬p+€¢tÎ)(ðâŽÿ÷I,[2y\øˆ%‡Ó¥haŽÏ[DMo1A|6Û‡;#8Ü€•çàqYáuZá‘>2o1Á®±Ôt}<GŽvàí7¶¢ií&„‚i÷2öø#€_75­éÈÚKŸ2Aßou)€¯ø€Üdy'MªÀå—û0Á4ÔÖ”Âá`ÅG"ƒC „ÀîpÁ›—§€ž×!~´~CAðÿÖ<‚ÂÚY°Ú D´@·ƒÉ@"¯Û†"Ž3ßÄ*P K`×îf4­{[7î„ ¤D AŒü¢©iͱQ)”“\&`ˆ"÷¾àûÓ˜Êܹ“pÓM`ñâ_–x"P0„@0ˆD"ÎÂÃîp““‡§4ìØý^o¾õ¾üõ;ðÑÏÝâªIˆÆDã!d+€&°pмv”æ9QšçD¡ÇŽÓ’€>`(ž¯!ð†°yÓ¼ðØ«èïñ§ó¨a?p×D°0¹LÀÄç[½À=f'Ë·`Á|þ —cÖÌ:&ðc±¢±Âá"‘(8ŽƒÍn‡ÝáoµA €Ç1~Fló;ßÇîýGñ¥;~@h,‘À`8@8Ž@8ŽXBСˆ·XP’ç@Yž¥y.ä娔ë(V!¤D:Æ@‹Å±iãn<ÿ¿WÑÝÙ›Î#𥦦5/ŽuÙW™ € Äç[]àç>‰Íy眷ÿ÷ƒO€ÇáD4µ¤Å o…Ín‡Íæ€?’@kovÞ‚™Uî±~eEzzzqɇ?† ®¼KV]`ôß% ‡¢" †ãFâ(t„à°ñ¨-q£¡Ôƒ]k* (éâ=ãñ¶¼¿Ï?ò*N´v¦óøÿðÕ‰±F™ €4Äç[Íø,D³² YÞ©ÓkñÙ/~§Í­Ï‰x V+žç‘H$Ð×?B§Û ž·Áb± p¢/ŠÖ¾úCb[+Ï¡ÖÂÜ©Ucýú€{ïþû½øÖOî†Ó£ñÙéVÚA0’@ Ã`8†PTP¬#…\· ¥9¨/õÀåàUàëî!Ç‚€íÛá…ÇÖ¢åpʦÄA?ðÛ¦¦5ñ±.Ïñ"B|¾Õ šûg$Ë7yZ-nýúµ˜5½RÑú‰D‰x ‰DB"AÀq¸=^p舡µ/ŠîÁ³ûl8DÛ®7pý•磨hX½…‡-¹îFVÔã£7}Iõõ eæë{š˜€´=Ž£ÛA WÒ]Ü€‚²<'ʼ¨.qÃjátV€ñž„ìÞ}Ï<ø"ZšÛR½Ê_hjZóƘè8‘ 0)Èw'€Ûdb ‡Ó†[oû8Î;g¾!:Ï’p4æî(Zû¢ˆ º²×tßUwZ÷¿ÆJ7V.[:&eñþ–møü—¿Ž›¿òÿ0iÚL­IÎ$ë¸L @(G÷@þP,©‹`±p¨/õ`Vmrœ6Í}@ÝG±86¼±Ï<ð""‘hª×ºÀ×Oõ á0Äç[]àA¾dùοxV¯¾9n»¼r·[@,!Eé £­? ÷fd!æçãàáuñ°Z8 ôáÀ– ¸úò áñ$mtȺüàλ°yËÜöÃßšì $`hî38‰ è£?… PÖ€Î:€ºfÕå#ÏmS¯-°­‚ ž|øU¼·aKªW{ÀG›šÖÕG2A:ñùV_àßH2B¯º¶ ßþÞM˜9µVž!ñ„Îb·€Žû8Ò‚~ä£} ¦väIr '¶©{¼hQh~‚-ß@c})ž¶`TÊÃ?8ˆK®¼ç\r5Vw©¡Ý^ zûiÁ«§‘0dÍKèõGÐ3EBPI@tnjŠÝ˜]W€¯]|@9<Ђÿýût$ú|¦©iÍC£R ãL&@Ÿoµ ÀÏ|Í,oµà _¹—^´6^Tñ6 ð@N§V^…7!Ͼð2êf.‚`q Ž Ç¦ÏïuŠÀ7íÙ‘<º:ÛqlÏf\͇MûdKþ÷Ø“øíÝÂ?ý#r¼y¢F¦À,­¹ŸŽK ‚ßêzˆ&¿&ÐWT”‹êê´´tbú¬IøÚm×¢(ߥ9ׯs°p"‘ìv;8ŽKÙYG6[zc8ÔoáPÃÃa5kó'†óA+àù‘÷ó“7ßgn ®ÿìW™`(ÐóˆàlP5¼zþ`8†¶žbñ„üíN”¸±¬±%yN †ãª€ªµÒÛãÇãÿ}»·$Q¼ ¢K°wD uÉ)O>ßê+ü@¾þØêÕWâÚkÏ úõ @?¬·@ þeZ–áHºÿYœ{ÁEZ­/«zèÒ ¦B0³Â…‘2âñ8žyþEüüW¿ÃÍ·~ÓfΡšæô=ö´vŠ4 ºä>0b!ˆ'ÚzC𣆘@±×Žš7j‹Ý¨-r"?Çžça±ðèÆÐˆa (öAÐ7¬ß‚gx!Y×âAŸojZsßÈ”ìø’Sv]©mÿ.ß`·Ùx\tÑ›·p°pD ì%ïß?0€¼Ü¤Càt8P–# è€7/O=À)•ö91MîyŒ˜éßÕÕ'ŸyO>õº{z0}Ö|L›9WzB=žŸ œX5^™p„pÊyœúèò€SÚ:èmqÏjªŠ\èsXÑÑBÇŽsæ–¡¾Ô —‡ H]¥ïD"D"\—;bñúƒq" #q# Ä`Ùªù¨›T…ûîy½]}¬"ðøÏ·zÄæÂØˆô8‘SÒüýBœ¨ƒ)_ºõj\wÍ*æ±ÿ œ.7¢qQ‹yªéîÄ/~s7^zuæÎ™…sV-Ç9g®Dq1{€`0Ÿþý0.¼òc¥ ðlqÛ-¨-´e­L¶mßGŸx ë_ßÎbÁÂ¥«°ì¬ PVYc4í¥GÔøçzk@§é‰Ò‡>Çù×»Á´Ê\,˜T GöüÍqœÁA4& ‘Aï@Ý÷ÞzíÝdÅò<€«›šÖ³VÐãLN9ðùVç@ìz³@8_ûÖ ¸ò’…°0´,!½}}è ZP^˜¯SõÁ7n~wþìWèêéÅÙ}+ο ‡öìÄŽ÷6 ¡<_øÌp»]†k6=ÎUˆ±AHúsˆÝv ªòmH£ÛAR‰D"x镵xô‰§pàà!—aÙYàŒgÁåÊ1Fî¡%Øõ$ÀêèCŸ#Ѐ—†Ëû¹.–N/FQ®C){=øY Ûl6X­Vå\ý· xð©wñï{Oæ¼ à’¦¦5MTp²È)E>ßê"ϤWߌÆ:üè'ŸAyI®i§žX,Žþäçøî·o‡Ã&jþH$‚»ÿü<òØ“(*«Ä5ŸºÕ STS™ˆÇÑM˜7µ óçÎa_;‡?LÐâ öïâ¶[P™g2øAÀ{ïoÅ+k×aýë0`ÚÌ9XyÎE˜5ït@¾«ù46‚]P¥‹ÚÈ€Õ: ë#@]³ÐcǹsËaa }Nz}Çqp:Š5@Àæ÷·£¥õ‚OÜÿH<†þ~æC»œÿAb|Ê€Ô¹ç%3ôÇ®¸bn¹å2俦|³wß„#Ì=SIûÜê¯aëö]Xræ¸øêOÀæp*æ<ljŸ—6žCWÇ Ûû.®¼ô"8ÆÀßÛ²¯5½ß™BQq ç™+‡šÛ»vïÁ+k_ÃÚ×Ö£§§¥e8}É œvÆr”VTivÓžÕjAE¾-ÝaDãD¹§³Xaˆô§ BPUèÆò™%ÌwIøô÷‘£- ò7äDGŽ=OQ%š2¨&š^zu¾tËÍJú–m;°uû.\uÃçqÆÊó@(§Äî*ò¬¨Èå1!°T”£¤ì"<úÜ:,h¬Gã u6 —_]‹»~ù”•WaåyjŸ‰â‚8ÆÊ§7DøHóQ¼ºî5¼ºvZŽ·¡ ¨ —ž‰ÓÏXŽšº-ÈåÀÄûòós¬ 'Pâµ£²À.ZF?vµátçJqA)f!…òDÎ’¶•¾LR P:ÆIç"Qs¥#²F¿÷Gqï·d!¾û­J @Îùyøâ·~Œ’Òr\tî Øx@NAr‹«ÁqÀôª\8¬~ô£ðíoÿíí†îÕÞðùV_ÜÔ´æí,UÍ1—¼àó­^ à0zö]qÅ2|ãפþH$‚ïüàÇX¼ð4|ôÃW(Ǿõÿ~„-;÷â[?û,uâℜSKm(öðJµG¢Ä,è­Ç[Ð~x'.»ø|<öø“øó_ÿ)ÓgâËßø.\îCk !@ž#É'N&ïlÜ„oÞñ=xsópú˰pÉrLš2]4ñ‰Œ7³>üª©½°!—iq¼½é}°Ú슕Ôô”6|:Ž  ~yíX4¥^—y“‚ßßó7üþÏÿFÕ”yXó³ï`zM¡Á"÷{zû°æéݰy‹pæœJäºíJ`rJ¹ ¹.^¹î‰í¸ýö¿°H‚>ÒԴ湬¶£&hðùV¯ðƒmùå>|ó›×¦þÁ@ßøö÷±gß<ÿÔ#pÚÅŠy¼µ ½þS¸ðêObÕù—KJPÕayVÔXÁRØO½¸“gŸ»Ý×_yÜûÌ]°Ÿ[ý XívU[Bm '®ß]é˜îƒ,áH7~ús°»<¸ý‡?oá)ó€Îl—R”özÙ °óæÔ'$=pðîüÙ/Á»òðÉ/|C˜£1ý`7ö  ú €€ç8̪ÉÔŠäcà§¿üzô L™»¾ ¯Ã—/™žÔ ]ݸû¹ýˆYópÆôL®ÈE}‰Eybõ™:;»qÛm÷ £ƒIq—55­y>Ûuv´åëø|«çx ð_vYjðËÀèííí·Ý‡à–¯Þ®ðÞ+/#Äæ÷¶ÀfwbÉÊó”ùš¹. ظ»ÖP7-¢§AÑ›˜¿,ω p;’÷lŒÇãøÎ~‚^Y‡Ó—Ÿeç_ÅS 5f?Ë à8¥ÅEøÌ¹1üé¥f¼¹3ªн¹šß[Î[RR„_ÿæ ¸íë÷àÄ Ã*eVÿóùVŸs²»Hºö¾Fï¾+®X†o|óÚ¤ž¦¬ž{ñÜý§¿c`0€¾ø-ÔÎ8 ïîkÃóëÞ‘eÃEWß—;Ç¡8Ç‚ž ƒ‡Ó*VíÒò*ô÷ºñßGžÀ™ËÎP𥢱(J ¬¼JÕúÔ GÊ^ Æ#7ƒSgB°oÿ<òØã8ç‚KQ;i²äFHmð‘h€Ï©qFÅ—n*‚ÃA<öØc˜?k þò÷cÿþƒ8mÉr\vÍpçx ÀQ‰@íÞ#Q‚ôDóÞV+‡Ù5¹¨-Noö£þç¼øÊ:,;ïJ,\u8p˜Q'=:‘FbZ4}hB¨ª(çΊckKójÜp»ÝÔó«dPXP€_ÿú‹¸í¶{ÐÚjhpxÖç[½¼©iÍîªÊ#.8@š¶kKo]uÕ ÜvÛG“žOÁž½ûñËßÞ»v£aÚ,\~Ýͨ¨®—‚z"b8ÉÔ—+M™—Çäb+úƒLØŽËšõú+/àñ‡ïC<.v.ûÔ-·âô3’Ž8–ŸJ׋ðÚ”xµ nùÒWÐÕÓ‡þâpØTDŠ/!è:óh;÷H£étÍ{»¶oÁ‹O=Œs.ºsOל+PùÔˆ¿¶¿!…^Nk(PšSSI__?.þðu¨6ç_ýi‘«8àg5¤Õ`öÍqrrr˜M…„ôøñÍoÞƒcG™’°ìdm"ü@€´(ÇkN×»ìòeøÖí×&=``øÓßñôs/À›_„‹®þ$æ-Z&‚]½¸-k1ާïš_iƒçBèè@˜ËA\ê_BñÛú0sGt¿<†…ÊrððÿÃÿôW|ù›ßÜù§+ùÕ c¿tý0_m3 4íôf£ü”éº`Þæ¯ÚëÂܺ<¤+[¶íÀ§>ÿÜøµŸ 7¿gþäÙ“ A?ý~ªoðx<+€þôøñõ¯ß¶Vf§ÀÝ–75­éÉF=M?SÎS¤e¶ü—\²·'?!O?÷"®üØxöÅW±êÂãë?Zƒy‹–Kàç4àç8NZcOL¯Ê³Ânµhb ¥…¹¨Êå@""¶-P®#wà,ÔGM†Ä/Š…¡9⾃Qñ~~?þðÇ?ã/û'-]޹ JÏ"~ÄëˆÏÅ£®+“|mu_¶vdâbîSþ‰²¯0¾A£Î·{SÎÚ£‘ùsgcÖì9È/,–¯(~KÒÛ×÷¶lÇËëÞ@<×þvŒ|®¬ùHh—=—çåzq×]Ÿƒ×Ë|´FˆîÀø™Å5Mù@X>ßj €ìû /\Œï~÷S;0àÇ×¾ýÿ°mû.Ìœ¿ôF•”kÀ®jã¾ÓfÁ¼JóÎ9ÿ÷㟡¡qVœ%õPœîT«„íÑ!èi=ˆï}÷;†Â8÷ÂËpéÕ×ÂépRÚ]ÕÈÒij ´“lj†ë‚ݱ‡èÜ¥i²ÌÆèGæBð¡ye°YÓ×Cû×}è·W£¸¼Fi±(Îuâ—ÿïKèííÊåKñ½o} ùy¹Y´%àv»5]ˆi·àHó1|yõ‘H0›(Ÿ‡Ø:pÒL:úA±~ øO;m*¾ó›‚sÇ®=¸øª¡­³7Ýú=Üð…ÛQT\®Óôêê¹,-RWÀ›^¶mÛŽx<Ï¡ÀÅ!×%jA ­ñY¨š_%ñš2 àà)®Å¼…Kpç¯ïÆ5×ß—Óº’<O¶Ôëpjÿ¨×U45TΉ—Q5.u ôõ¨}Mšæúô‡¾ v°]0B{‡ù >ÕU•Øùn“ò@G«.ûþõŸûñ»Ÿÿ…ùkŒ¥õõß´%088ˆhTkÈyëj«ñÃ}„$Xw!Ä¡å'œôàó­þ$Ä5ù4RSS‚_üòX,æ¯ø¯ûÀòó¯Â—¿÷L›9O ~¹bX”ºÄv¾Ë‚·ùõ{zzqÚ‚¸ò³Q•Ë!ÏÉÁÃ'°þ¹ùX†í^@qÔ0|Ìf·ãÓ_ø*ÊË«†PÀÇqCœÓ£A J €ÒœG±ê2¨Ï¦Ù–[5ò8sf!ΜY—Ýj´zˆäTص{/®»ñsøü—¿þf™>ûâ+èîhÕ”AIž_¿éR,˜VÉ4ïYû©H!($ o.ž?w¾üÕóAsÑ >ßê[3ªÄc('5ø|«!ÎîªÇ…»ÿø¸œæe!XºxJÊ+aåy–Õ˜ùþkò“·YàŽo݆|¯êÚlV Üþ~­ßLùÎ2)XhÀs4fDM%Wc J^ù(ߟãÔ¾Ô%”mNzõ\*—v“º'%oáо÷-t´µhbòuzÅ ?þußøÔ-_†?ÁªË?‰×··föíîéEÓ[›0cÞb¥O8gL-BžÛ–R˳¾“D<®µæåcç½ ù˜!Ü$ËÏ}¾Õ‹pÈIK>ßj€‡hºªñ¼kþðe™OÆ!ûsË–.ÆÞí猪 €e‘µœÁÿW?ivÉ7È—]‚Wž*e>¹{˜¦íŠâ–ö5A>ùZðÕʯ5ßU³_5¹€j ¡…@ÇÒÎ?çL¼·a- éß(ž×ˆá©õÛñ‡?ý óã3·ý5 Óµ¸ðò¦ðªíïÏ¿ô*, ¦Í^¨yº|Ú+*-ŸÊZ¿ß/®ÕH“ßð±K±òìI¬ŸÎà!iÅèq-'-ø=kó}÷ÿÝ€éÓªMO¢ƒže¥%˜ÙP G ß_~UƒÅÓZ°Ö(^¯ïmÜ¿ e^©€ Ðn  h|èÍJS®f¯ÜQNe1·b>å|…(w¡k0нGNrrܨ+ÏEhЯ5t$‚#WÝð\qÃçQS–†2‘ÓÃ/þùÔ[xä±§‘H$ðôs/bʬÓàâX4¥ÈÐ ÐYÇÌ,³Öùø­_¼S¦°~ºœñ€“’|¾Õ׸YŸþ‘¬ÄùZhz«ÅãË·|gÔÚÑPd…ËnQ›É”?6ø ÝØyC‘ææ£8vìN´OûB}XD@ï}¥WóiͱΡq¸å<Êic J/Cê™Oíèë;Ï|äÊ˰yëÐPŽta›Í†¹ }XÐe3ŠÁÅCxwÃ+8TÔMÇ »·ÿx ö8„Y§‹§ìV Ξ[ŽÙuùšrJeêgbÈ"úûû™“†Øl6|ï»7ÂË68¯ôùVyH•d”ä¤#ŸoõTҧϞ݀[o½Úô¼dÍ.§µ…v,¬q`z ‡Â^xqÛÆs¨ðZ0»ÜІ lCœ÷xk+ŠŠK0yêô!¯ZªFVµ¼Byx­>xÙj C”o¯×†ª¯ Aå—R,‡ü+¦”¹ÄY’$ò°;ÅøGEy¬ñ$„¸H_€€B³Ù¶ñ ´;¬< Û“‹…g]‰OÜúÔOËŠ N«@u»Ù=YðÞ×”O·PI@ÈËõâG?ºÇì×ð Ÿoµ¹Vc9©Àç[í€è÷kºc¸\üìgŸ5Ì#Kº}8ŽCI®e6Ì-ççâÚjá0§ÜŠª< ܉۷t ¸÷ï(vö,ÌêmðÇ©¸…r” ;Û¸ƒ–¦JSù’‰‘¨*p`Vµåù$ZqôÀ>ùW]v!¶o~Ë0”ïs¬Kìe×8c*æÌ˜"®½ <3‡²ŠZ”¸qáiUÈÏ1ð¦àËä½Öc?£ úºÜüÙ3‘HæµxØç[~—ÇQ”“m0ÐoÌ×'Þñ£°0{ËeqËŽŽw߯1?s ÄcrÐ%V«VV.†}G;‘_R9¼g–Bt„8©³õA"…%ÔrœÜ9H²"ifN¬\]Ë Ê$âÒg²ÌœR‡{øj'k‡cÌ™5“Î à-¼v«4–€ ?(Fܾ‹N_B€þ`]þ(º"°ñL*`ÎÕÈú é@úo}šþ\ý1y;‹iÑÇ.ºàl¼ùæ{ؽÓ0„XŽ|8{5(;rÒX>ßês|^Ÿ¾jÕ\œsöÓó2íéH³û¤ú¼þòÓb¿{ÏÈ•ÝfÃŒºR´=8ü‹ÉZ•S£öú¦9z›PÛâi:k@1,¨Qƒ`ŠªA2·Û…Ê"/ƒ~ð:°^qÉùp‡ÅØÇŒ*/–7aecVÍ,Æ’iÚ9[8ÈϱcJ¹K¦áôÉ…i_=?sS?¸@ @,cÞï[·¼•9hè*Ÿoµ¹:FrR€ÔÏßÐÞ_XèÅ~x“éyÃíæ\S]…ÞŽ6ç ÝßOG¬V+þó÷?a׎mÎkÏi·µÍ~¬é·8õ‹Ó¥)»jÇ"u¶"ñ¿¸Ü™ØeöÕuëñþ֭ؾis¤ßŠ3æCèÙšbã ÉÙ’d¦>+ŸYÐ,_?sÞ\¯wÜq=âqæD"¿•¬9)À7LÓ'þê7_„ÃÎöb†~Ö?¹¡%®!¶÷¥)½½}عkB!Ѧ›þ2~é¿6rOGì¨#šöz¾>êZrÓa܇ ´öEñéÏߊïþðÇ8;¦7æ_<ÿâ+¨*ÉGúº|ˆeaêt|³ã²B4AAZÌŸ .ndªðƒ~íŒd܀Ϸz€;ôé×^{¦O­ÊÚ}8Óò–›o„Ë12¡’`(„W×¾†;zx«³æÎ×§›þ2{yCÝQZ @÷ P³É…p”! 79ª™@±u?黹+Œ‚²:|ê‹·cõ?ÅôiÎÆ³/¼„ÍïmÁ¼9³F¤LÙå14-¯Ï§O‹F£˜ÓˆãÓ7~ÞÜëЭÒlUãBÆýh@Ÿoõ³.¢ÓjjJqÿ¿c:;n¶´ÿHH0Â[o½ƒõ¯¿›ßE<ÇŒYs±â¬sá[yvúÏ›FÓ‘~†‘Ò¢›0Žþӯߧ,¿Mè1ÿT@Z܃ ¦Ø‰úbBá0öîÛw6¾‹ÍïmÁÝ¿ýìöì­jd&É&Ig;Ýsòóóa³Ù”z'Ûµg?¾}û¿aµš+7XÑÔ´fÌÁ7®[¤…;/Ò§ÿð‡7Žkð÷õõá©gĵõhéêêÆ»ï½x<ŽÆYópݟÙ«V“ƒP ´cRÒyKeÅ=YƒSà‰ºKÔ Uà b&Å #â {'j.§öÑ'zü1¬[ÿ&þú‡_@€Ùsæá·¿øÉ¨€ºgNv,ÝÖ³óûûûQTTd¸æÌSñ¡ó§cí«Gõ?ì27B\žnLeÜZÒ^»ÔÐéË—ÏÁÏþYæ9c þ¶'ðÐ#á…—^‡ågž‹Âbíâ¹yù8mÑx¥®cV Pák‡=·Lv–‹è47h­ ¢Y¸Cù‡¯ñW' ¡gÒM .=ráp“&MÆÒÆr¸²Ññ!Ã÷OGË%Þv8ÈËËSöå{‡Ba|ö³?D0h˜I¤ Àô±žEh<[߃üV+oçãC¼ÜÈÉ¡C‡ñ߇Áº×^‡Ûƒ .ý0λèräÉ$.ˆà™TS†ƒGŽ‚Ï­ÏóZ?,2íARò$?Ÿhµ6‚Ô¿ßÀ£”ÊW¯E¯ç+^S ª‘ãàáuð˜^1^—5ål¿#-©´|*¯¿Žþšáp.— 6›M“Çétà›·ß€ï~ç~X­šqkÅ~à³)o:’å2-Ÿoõ ÛhlÅ›nºŸùÌÅÌsÆJûkiÁÆMïÂát¢¾a ªjë`å¼:bŒÆ@™GìxçOîBkg/¾õýŸ¦~¶tè|{j¢Nƒ–×Ìï­_¯™#ÏÏÏavMÜ£¬í™¯Ÿb~ÀáÆèm‹Å‚ââbÃ|‚‚ à®»îÆæÍà8ëJœÑÔ´fÓX•Ïxmø.tàÏËËÁ7]0ÄËœÔTWãÃW^ŽK.<³gLFÛ ¯šÏ@O~ð~k>l8Ÿˆ&€m;vaíkë1sö¼ôˆ‰¤ùѧ#Ž‘f8ØŸz¥ šÒ<šðö®8Ú’þ`§‘’TÍz™(d-€ØU˜Õ*ÀqnúÔ54LÌøþX–ϸ#Ÿoõd†<¿õíÃfek”ñhÅȇñÍo›Þz•ìaÊá8°aóvÔÔOÂÅW~4Ã;¤#\Ò]%ME´ÇÓL'μ„²r 4„cs¹±·#æc-#T²–@ ð¦ÛCÐìZ²øý~æ¨ÁÒ’b\xñ鬩Ä.öùVÏ«rwàv¤××—aåŠÙÌÌCÿh5ûýõÿ‰í¸ù‹_…ÕÆŽ~c@EU->óů—®Ng ûJÿ ƒè¾X(ìótéÄä&ÚF —'‚cfªÆÊuåùXÇo¸þjøýLB¼c$ãŠ|¾ÕÕ>©OÿÞ÷o5ÀfS¶nÛŽÇŸ|]vµ¸0g9mñRÔÖg—IiÕ§!ò9DDàL¬z&bbrMŽaJÊŠĈSl!’I¿t¬³¼¡P‘HÄpŸÎ;eKÆ… ÍžÚ @ÓsfÍnÅé§Maž3œçΆà÷ûñ©Ï~v§?¸k ìvÊsIãò£Mr4_³j mÿ×ô¤Wþ¡ÖúÓ¶ý¸ìL.qÂeÏÜ›üÓßþ‰Ý÷ &M›š†i¨n˜†Ššð6; >g§ÏÑÆNÞx{3òÐw|?®Æã×ÝôyôùØÛÀŒéÓQ^ªª›‰¤ ¦³FFa·Û5ÏPS]‰ªj;‚ÆÞÃ7¸?㇂Œ© ÍvÆq®»îfþÑÖþ[·ïÀ•×\þäçè Fñé/~¿ùËýøø§nA~A¡!ZÚ{˜j>Ó>ê­ˆöto Æ=ä 9hÏOOŽ·¶aãæ÷°êü+P;i:ð´¹!§A™ÐÄNYä…—×"cÖÂeè–Ö”% £³«WÞô Ì_q)^ÞÖÁœÀ3™Œ„«0`²ØéWP¨WŸ|®Ï·º"ëÁ±v> ÝÚ~K–4¢ ?gˆ—Ë®<øðc°;rðŸþßø¿ß`ù™ç~ IߣP€k?1ºº<ÌÇÌ๟|ú9ØíNÌ[¸Ìüùl#ÿo(ËÛaűãmxð£~Úäx ‰&ðÆÎÊYò¤Ü"±ù¸/<ÿö¾Ñ)à$‰D4D$“ÖŠeKà÷™<€ëFã¹Æš æÿ'o<Ÿ™q´µGg'šÞÞˆUºÕub]!ÃGÈÛÃíï›Æåé-ÚϧMp­_OÀ2ä@]º!Áx<ާŸ{sù`wÈcdBJv ¢äŒÄ±æÁµ¸ôêãhk;Nó«äÙ×ÄKonk9·'OlM®p¸—ÃÆí²_¨Š~¤ Çqðzr°èŒ©¬`à'Ò¾ð0dÌÀç[] à,:­¾¾sf7ŒÕ#iäÉgžoµbéªó”´Ä0Íö!”-RÍi}µ£ïÿ/ﳂ‚râ@(×6íÂO~þktuun;0àÇïîþ3zz{±hùyâ¬DÔ5ô¯f #INô„ÑÛ?ˆñ»¸å;¿Eí”™šG4½+v&Ê-(6¼ú¦£q´´u ³‡'Á`Pû\R^rɹl×gŸëó­ž;ÒÏ4–AÀë¡‹iwÞéãbШ±^ÀéKVÂéVÝ‘L-½Ð§é-³7÷EµÏ2éÙ¦>IвH0–€?n…ÅS'×nÄu—ž—ˉ?xäQ<ü¿'ŠDà;ëBTT×IŒ¨š]{{b|jcÒŒyJ‡%åÔÿvì;Ò…Ü‚ÕÂÎŽ&¼¼£“7Ãí´#/׋¼\/¼žÑ›¦?‘H ‰ÀáphÒO›?ñø= nÿ'Ü6’Ï4–`0q>tþ"fÆÑ6ÿ_³ ==½XqÞÅJ…ä8 !@7Pyè2l2âÝ Z]þh"D“OCú@ ŠŠË±üÜ‹B°y_;öoÝ€û|áp§-=+Ï¿ùùEGà¶ñpÚ,ÊÇåà᲋‰‚‘:ú#8ÑA¯?".¦£#Íý¡}@ý‚sa+اy)ù9ûBÚÑ/Þhh‘P‰XE…øÌ'?†\~‘”Ÿ*/“í¡J 0€Ýnùç-ÆÆwúÀóšÓu>ßêÛ›šÖŒØhª1!iµTMÏŠŠBTVñŠÙB}âiÔ6LEmÃT©yOü/iÞ»4·¤}OÝ~¶¯MOìIßOžÎ[€'ÒAM<€u¾æ[ê:ìÈ—_Ù§-Ùç_Žªª2¸m(ôØPcMº´WŽÃŠ’\fÕ‘˜H›ö ´eD1’ê2ˆVÅ£ªa†Ò•™fŒx‚Àá-²¯Ä®ÍB"H8€uGüxëÇÆ-מ‡) u©Ë5 ’`mƒAäçç®wÁgá•—ïFAA=\ÑM~%‹UB#ce"}gž9ÌÍÿH$Š;ïú¶lÛæ+â „Zv;.6jÎΑxb–žú}tTÖðD«E-Ô9ß_=Yë¿‹{¾EóqÉ™ ‘ŸcƒÚ“;l#õnZ#Q‰’„cZWZã"øÐ‚2L¯ù `8F"¡{B°pá|ô÷úÌ÷ùV˜o<.€€¦–ø|³`±Œù¿výøÑO ‡+_úöOPÛ0U­L†)´Äqß²À’‘t 2S?ßý'jd_!7-ôM´» G¾ÛŠie#7†erC-ÀÅëûüïÒôB¨.r#ßc‡×i…ÛiEgûŽ Wê&L †cš&Nzƒã€,­Æâ)ùYœÃq B¡rr´Þ&OªC,Ö«Ïjp&€ÇF¢\Ç‚ &Í9çœÆÌ8ÒÑÿÞû_üõŸ÷¢ªn2>}ëwWP¤˜ŒòÄx´•—ÚŠ l$EùèFù™…§s(­(—@£íi A! B›ÿrT*¸í4Vº1Ò!œÉõµ ¤ë÷V'¦Vzqæl­õ8¹Ü‹%ÓKÐÞÀìiéCkW€%°[-¸~U-¦Wz4cöé÷Ìt;kÐ §Ûl6ÌŸ?mmQ}kÀÙø €ÍÆcñâÑ1‘Hà?þ^~uæ-^Žk?õeØ âòÔØR•ç8ié<©5@âD*¼4§ðO3kVD]øCvaT3^ûLDzðZ·š^" Ê™`ã9̪Ê5 þ~:2¥¡ ÍX¿Ïª’B¬œUjš·¬ e9ðÍ(Á±Žl ‘'ì D@CY*òÌ©¼å² ‡ÃÌkû–-ƽÿ~¹¹•tòˆÅF•|¾Õ^šÆþ ¦Ân]:v¼/½ººìZœwÙ5š\„£Á/Ïw/ºôôY±«©ú‘lîSî¡1÷U“^ÕèªögFòå÷%´µ }z9Ac¥'£iÀ²!S&Õ硪ª,i³"-UÅTå˜Îà3Ú"b±¬º€ãüùspÏÓ@£Ï·º¢©iM[¶Ÿc´ƒ€+¡#+æŒzó_OO/r<^œ}éGi”HEÏÛq Ί&gP—Hæ§$¿žFC«ñp}÷ZÅϧI~o%¯Îm ~ÀÔr7r]c3l»¡®ö ‡Œ§cº§:žÎvºç…B!Ã3VWU€çìÇ+`´]ÃK¬Z5Ÿ™1SV‚\ÿiÔTWbޜ٘7g&f5N7ôº€žÞ^äxó$sWZÐAùÏIzž6Üå=íÂØ‘8oã̧ÐÊ€×ÌÞ6í%é¦>èˆ :ÓEѵmèº>šnÀêµk (ñŽÎ2ßÕl÷æK%­':P^Zœ2_8†×«®LÅbÁKæaïžìvMðlŒÀ£mhÿTW— ¨È;Ôkidמ½8rô*g­Àñ }ø%\{óWð©[nÕL'==}ðxó(Iw$ÑmË>´Æ2·M$—OÒùÈϽ¥Bà×¶ ¨@½Ù¯ "RyJ¼6Ô92~—±ð3ÕòÉΣåõ·6ãá§_5=.K$a_ºt!ÃÀ¥“Ûæþ›I§M™R5¤k=vß}_£7¾û>ró‹0u¶8 hîâ•à8 ‹âÍ]­¸¢¸H™FZ¶Ô¨¶º¢…Úì'µpT«€˜´%s°r.ÅD#ÐhzñF4I©íá„ʯ•6u:â¯s ¤\ ¼.SÊÒŸ‡o¬%S¿@\×ÏëÉIy­TÇŸxs?*ªk±tNCRr‰F£°é–Œ›:u2NhFÆÖû|«‹ššÖt#‹2š.@=ÄYO©­b‚&YA¿ðò:Üyׯ!p<ª¦SëÞq8㬋Õ6|ˆ€´Ù°WLÂÆýÝX9§ ŽCwDºˆ6÷ rB›þ§!@$8mR:Ç¥‡ía‚Ü£Úæ©Ž9zð›ôh—n Z­/ç#€Ã*6÷Q—¬Šžâñ8nýÖÿ€Ã=¿ü!¬V>¥_ov-@3òô>r]-hœTiúáp6›Msò²R„Ãý¬ìÓ4!‹2š`XoÚ´ôæt€h,†_üæn<òøÓ¨¬›ŠËnøò ŠÁqâ¢8pN£­ep‚œw4cÉœz1XT9“í‡v[¹TÀkEL‹%8ð+Ï#Q \³8q²øÐjwÚô(b ›÷X¦>ÃEPºK×°Z8̪rÃ:ÖSÈ AÒ1ë9ŽÃþƒÍ¨9ý"üý…øÌÅ©‡â›“€ø<´EÀ Ö6p$ãmíhi=Ö¶\ò¡U¨©*G$ÑÄqt`ii!‹EÑL¯IëÄ£-Çñ;þ{÷Àé+/ÄÊ‹®•ç%¸r’B&R[½® œÔ„GЃ|ìØ×Œîž^LmÇ–‹@eXDMÀÁB“€dÈ)„c€›ƒ¨¥ãô@"`V?ÑnjÆâS{£é9·®/€®…ƒ:N·°ˆõ¥ââãaM†ŒŠÐðôq@ì‹¿øô¹ˆTOÅþ^;|y®=wÎc2CGàOopèõÿ  Àá·='GÛŒ/\µ“ëª çB0uúd4„Ó™O?nòf‡ cF^¯ÅE¹)OzeÝëøÞ?G\àpÙ'¾‚ɳÀÂqj穰Ŷ|HîÝ™G.XÑ4oåÃ[RƒOõƒ1Ì}Ù· * p °(yµß8„ãN«˜@8)¢@` ù®fBôÿ™š_άÓîŠE #æ§‚„Ô=Õm5€hµp(ñÚNJð§sLÞ^ºhÛ|¥“æas›¹vâ‚¥ùþpÞ™K±÷D²ÏÛì˜zö§ /ÅDˆ÷¿=ˆë„”——®U]]‰}{ö8Œ¦A7ÞI7øÓ_­ANA9®[ýhhœ¯ñyAU_¥âÚíµA±x‚༫nBEí¤”mýD,yy,i9}]AL%¢q1]^‚K^fKžÜB-õA ‹qAÚ ÌI@?—&Á¯iÐßÐ@·|ˆÏ\žg£GDœ”’Ž&_²hzZö),¸ö‡÷v7Î×_S¼ /wÜ|1V4°H^,[«…C ü÷œèìÑ\«½³‡G,f9 Y–Ñ$ {MššÁ :;»qî•7Á[P$è,«ÚS³ Þf…7¯jê“Íd]]s]ý1ẨDâEF2Pƒt*àYã *¡è‰æ:¬kA;Ǿþyaôïé÷6HDPžŸz&äñ*é˜î²TU”Á%øª°î@Bs­t®ˆ.Å%‹ªññ…6Ø­œ¢µæÖºpÅÂB’@ ¬Û5€ž^qÚð¾~?^k3 KÊô“ƒÀŸouV{^ Hóÿk?eJeÊ€#ÍÇÈ-*ÕTL`0cõaXíãRNÊdÖhF=ÐÁ&­5 7—ú4@U+Z\Ð~Aͧ6ÅA8eÈJy~¨ä¡<»x\м— ø© Ðcƒ}”úùg[Òé¡§?¶pî4 ö´)×ñÞv6÷2ë'ëzúkÎj(ÃUq@ˆ ˜TâÀ§bf• \Û; è ı­5Ž–¶N¬ß°‚ÀaòœåúA`‡Øš–5- À`ºLšº ùh rr Á[í ÐPš[ß±%‰)OUz3M/è}iÕæ3hs„c‚H:7~.ÐZÐ D°B^ zðJý{j­õ>t™1Ê@ç>€y'Go?½¤jºc#„àš+/F¤§™Š/ëö ˜^/‚™;½j 4—ǵK‹À[ÄxÔe«æ ÐÝ‚þÁÄ‚½Ä-.ÔÌD~q¡Y¿’¬ÆF‹4Íó44”§<épóQä•Aké­˜€ÐVnÀn º|*ðõé*øéípŒ WA íFŒ7 šëÊD¢îk¯'À˜‡éâtÝ4‰Àeç‘ï«Ç MXM ¨¯­Â—?≇”ò;Ô¡66 °®­X¹h>{f œ6‹r¿y³g ?Ú 0"þ œùUàí9°X­Èñ2çW8) @³Îw]]l¶Ô+ !2ÿ Zž2‚ªRÕn³@Ì:(@ Û2ÈF0cb Y“ƒa9P¦ºy'Z_о·âN¤|£U qg æÑƒŸ‚Êü“Sû‹u }ðÓçÀüYÓpñtIu X·ÇŸô\ý5Xc·Y çÌ™Z‰ã‡w믂\v+Ù¤l–Óh@>½“Žùùyp8ÝÄ¡…{Fæ>´ P¬ “À’€•a È 5x§@T@,ùš@}t ÕÆè ”k„"ú½AŒà‡îýek‰·p(Í=9 ]?!œµt–”öŠÁìn àx—ßô^©HÅì998qxeÑ ¢|ÙÌñÙ,«Ñ"ÍDkS¦T¦uRqa!BÁÁ¤Ú­"ߎÍ-ÆysŠ1½Â)hÒ‘„ßràOOúóBƒFŘ€ÖtOã#è@¯i&¤ŸIµ$è8‚æAåÂ°Š”æÚÁŸÄ}~Y8•ù¯ÿ¾â¼¥èÚµN´Ž@°~o mÀgfÑXB%jIlv&guÒÂÑ"M_Ç-[¦uRaa>B?åÃËæ½XiÝv+‹P–ç@Yž{Þ߀M¯?O™üÚàÁ×O‹TÑA>½¿O_S?¥Í Ž º "ËTgœO »§Y\@Kt „`8.• Äó#ñ[‹bD…öté¿­V³« öÞ;âGw(m+"]ÂâtyKfŸ•í&ggø¬$cB6ìÀ¡æ)O*+-A84¨iÚƒ¤Å8p8kv‘f6šmï¿‹€¿ßèצC ?šnæ çB<=PU²ÐV¼HLÀ`$¸Àz&hÜùO€þ™%ð*n«#ØGY j:;OG o¼»;åo4%Ÿ?Ýcœ³]‡·*å½~;0ÔxÃÑq’Ÿ˜BDùo³@ 6m=šÔ?€Ó¦à÷wÞŽò|§(ŽƒoZJsµ>ÒñÖ6äk´ݣ͌XÑ}ˆ¥ÕeDM<@wùZ‰ ÇÌg0žÇr=¡z‚ý^† +0h°‚¤k¸+ŽDG©ŠdGÌb6ò1ýwªc3§O#,‚”ØxÐ@,P³žE¿M§½°öM¼öæFØ]¹ˆÆªš“b3£aŒVá¡Cá8úä{’Ï#ß8m2ì:Ò‰íÇ£¨-qa^}Üvc‡¨ãm'0ÝW"ùQ†á½œ˜¦:ZT~Nõ£¢Sg ÒT¾ Ž#J‡ŽèªÂG bN§bKt[š:FÕ(ïG¤ŒÊ·L „hóS`—Ï׃_¾Î”rœŽ“§`:Á?=)$Ë+oŸµx6š:Ã_‰hœ`í®\zZÑM~B6¾·ÿ~à x‹ëP:õ ÑPÊžŒš0fàp:ÐLÀãJÀʧîÝ8³¾3ëÍC!ôöõ#·@þadjGû©hd€É·xyªüÚmiD"§½ ‚

    Æ¡:ÕæÆ©®QŸê{¸’ŽF×§ë BpîòÓÑßvHÜÚ&àHK{J+Bá0þüï‡ñÓßþ1‹õ‹¯€ÕîV¬2±@ ü0‹X|¾ÕYcç·|¾ÕÃÛí6I[qÆyì=|‰H³g­§cKkró‹¥ !ËfEH^ Ž£-]L€PÚž©ÿµÑR ÍyýüœÞ Ý9Ä@ÝY:ÑÐ×[®,âˆBqȨÝÊQíñjLAÖöê¹´FWn¡1ûé€|?:V@ˆ¸ÐGuaö×÷IIǬOLgÿÜU><ðÊŸà-Ÿ¬–#1 #ìDM’ó`×Þƒøý_ïCGgJ¦,FÉ”Åà8 ÄNFâ/Ó­:K̃€€h ÀFLç-j%æ88½…Øz"‚ß¹7_s¦OœÑMÎ\¾Ë}>”––À%ï]Lü,…8evmPOžÄC-è9¬TôàWÝ• `0ýé{˜»<â5£ ‚hà9‘¬¼:‘òR­H• ̬’HŒ w0ŠÏÉü£øHGûë¿S¹ ‡gL+Æþp»8)ªÃfÁ¼:éucñ8î{øi<õÂZØÜy˜ä»®ü2©ÐUð€ $¨û‹ß¼ù$³YûqFÜÎkjZ`hK Gbª“´ONŽÅ3ÏÅŸŸÝ_ßó/øýƒiß§ª²uÕå øàîï}ý½ÝZÓŸ6“ .€ù¾2:OoÒ®­ºšæ8Am¶£û°?r¯KD&‰kï+7CA{ɯºHÆ>ÍÝá´Ë}¬% _:ý9ò>ý}ùg¡ëлŠ%5¿V#QŸ·¥µ_ÿ?ǓϯEA݃Ԝ‹ÇÍ^;}`¤Ñ úÑ ‘pTÒRjtœçÅ‘ReµÓ%wüî!œ3¿—\pŽa ¥tD Ú¨oiž.˜Fý9B$k€€ZìR7 dˆ.À„c[ÔÙŠFNµ’Ö0 "þ„ /hå+Ï)CK©Ë3*°xT:uk }·öF0µ4‚×øn0±Þî·ü©ª(E­;€ pXXŸÃÌ{ìø |çÎßa Eý’ÃS\ÍÌ.Ú_ `Õ̶*Yј٫û‘%3…e£@ŠŸ±B+ ±p¨½ ÛüxàÖ¡ÈÅÒ3N‡ïŒ…˜ÜPŸÖMÕ ˜>êo’_¸çÔÑ´{@ûöÍy] €DÕí2H)@¦žP»Kh""DŒð¼EŒˆñ‚À—ß…r 4y‚–¾8¦s†îÿÅ:€‹ÏYŠ¿¾ºyÕ3ñÎA?ª 4÷kimÇw~ü;øÃ14ø> §·X1÷u¿€æÛÊË®ª?~<Æ´ÂMMkLMƒLe´À`²„CP„€p¬Ú/åt{±èC×!`㑽x|ÝßhÇœ“à;c!–.>E…ìR6»MçÛ%oãçÀÁí°`Uc MûûŠiƒ}ÔT£Úx€lHUéøCoSO‘‚‹ CÊóW”ˆ|¯X‚(£ Ñw´ò1PÏ¡´ È7`‘€Ô7 ¹3ˆ)e.ð–ñÙ “~(VÀ§ÍÁßÿ·¤ªï ÀëÂ…gL–ÀwÜù[øC14ø®Ã[dðõYæ?—\ªëx,ÊÄyÖÌ`t-„CQIcªP´òeþÒ-ðvgêOCÃÌÓaá8ø{;ðÌÛ»ñçžÇ×n¾g­Xj¸éJß$ Õ@w’A/+ȱáÌ™JáœÆ\¼½· a;ÕÇœŒ4#¯O YòâBíh{Êq5A²irR)ãÄω½9pªBˆ¦;##„hé ¢®4«ÍÎY“T€Ï¶5@—õ¹‹§c]k;œ¹¥Xßì@¾ë0êK=øÕÿ…â’R,]|!ró à¶+‡7v÷©æ¨ö×SÞÇÊ[ i&.@ÖÌ`  cå-TçÖ*=jO8oA)•bæâ3±7Àaj[ª+´kÅ_|Á¹xäµÈ+*ÕDúY]}+ œX1£6ª7žËéÄYóª±uß1p ž­¹71GëcDþiÓßlý ¢G8t»”)¯òQê–bÆSÑ}YÓGåó)²Ð´è¬í-qI™hþT`δ…€‚ Ï]ކÃí(,)ƒÛ¸lì<ðëÝnX~<Oà‰çס v®T?ä6凃€¼E3Þ„˜¹Y%€Ñ²ïŒ@0,UFµÃŠè¨Á)¥¸hUÅ–*¶@ðÊ.?Aír˾3âÄ¡Ú(7#ê=¹Ì³fiÀO˼i5ðÕYáµkíȳÙ­¸yTäÙ!ƒQ3Hˆ°Z̦Sã†I‚úîú¡Æj~º5‚µ­ëEK—1!'zÃhïͪÅ9l1µ ºtŸ©æ§Ï·Ë…ù3jQShC›‡ÃÊ™ÞOhÛ±NœñU1ù©o9¨³`æ|0,€`0LiQ±Žè¨Z_Šîœ#°ÎŸÏn<Ьš¦t°áy ëàïï7¯@¹.­^ç×ça~}êJÊK q^A{[úàõzà¶ópÛ-pÚyÍ@ž'Öï@ÄV›Í®1Áå{˽ôc€t@J!„ÚV-™äèÎBŠõIm«Ö+@YÇB(+V@¦à6;'k@ߢª¿~?Ñí8º_XýæiëWJ `Ì,€P0¬VB©°ÄH(]Œmù‡ ÚŠJ@p"Àã±u[¥ î[_û._XŽÆ*/ìVNÑœ–M/L ü²X­V̪/Fm‘Å^ÜÞ°P¦GèÁî÷ßÑNÔ!èÚÞ IÚ@›Ì>Æ9Ô|J I?\™»EgÖ~hàÅ·vR5I.#ÙOf9è­Ösé÷_k8‹Ô7…ü“-oQÝ0)-þ"ƒ Òe¢|;¬* €¤&AGÇCüò_Ï¢ùh 12?¥®+‹pÊ\¹¸ËgazE¦”»3x…ôdÕrïÚ¬{>(z’wb¸ ‚¸š9t&:ÿ+¯½…¼ò)Ts@o X,Ïk-S‚ø(¸£Em†„£í@Ëf¬×m£Ànôÿõ$@WpAº†§j6þ³v?ž}ù5íËZ8”ä:ÐXåÁŠÆ"XRõÈ‚ØlVÌœ\þÞnÝdÉAf¬Ø&½ø#ˆÙƒ’ô^w]+¶B»;{rðÞŽ}£T]´’ŽŸŸ©æOàú¼ô>ë:úÏöÝûÑÖÑ…ÂÚ9ò›hƒà=n»Ò„,+> 貊£ Y”Ñ"€½ú„®Î^ÅT§IÀë²*qÒTÓwÓ$ 'oI ö ã×yƒ± C¡0n† é?ùäÒ ?„›ßÔÌ ¬¶™5@3¾—ðšõÝ>Ñ–fäŸ`,+Vùé]ƒ„ à­fû¥*µn$?'9¡¦&t®%çI§·áKë6Àé)„» ’ü“ÊÖëvRér6þ>f6«,â'Š ÆnÜ‹,ÊhÀQ!.:±³³eeù8¥Ý\$¹¤–f~Àœ´dP>å4œU\‹P(€ü¢R8]9hîj…@H²WÃ’UK õèA”×L[¤Ç¥;7%õ„u„P$¡=èJ+f0ŸJ§€/Ÿ£'9O˜ðx|Ó ||¥y¹C›œÆ?Àá#G1wvcò†6ª5 -»Ì,úÜW_ „³ ¯r†ìSÍ{Ú ðºêï)Ytþ>ÓѾY%€QqššÖûõé'ºÕJ&Õ^¯Ëª3ùY3ûRòëýZä䣤²v‡„œ6{êˆvs½øüsqdÏfi´ãbô_»¦³€5‰ Û×mëã š²RÇ*‚ ;\¿‘¨ù„¡»÷îÇö{ éϽ´ç_ñqÜðÙ¯b瞦çgÌfÇéëËÛò÷PÈA¿O$ðêëï ¯rº¸®¥˜Ãð-S¸×íP®#ìg@GSÓš¾lÖÓÑ\øm/€¹tB[K§TxP:È{œ6¥o­ÑIwZ¨®¼-*Ÿi6¹'L¯ÊêÔj)..Â~ø cèôÇÐ墣?о` ‚ò¾&Bô›Z€v ”j¤Kà¬ZÓ+Óô.Ãè»ñß—¶â“-„E׺þÍ·ñ•o}ù…¥¸ïÏ¿BUE)Ž·žÀ÷ò+¬ómUÖcùÅŸÅ#ïöc]Óƒùû4ï{þ9+1»qúÍýLŽëOçÑ–_ú÷~÷ýèéëÇä™RÚ†¦?ùÛãv¨çK 3øû™þVµ?0ú ‘Öæ6"wé‘z×s^§ ýAY»°gþüšoÆÜ~ò7AŽÃŠÚbWê'΂äºmÈuÛ0¹Llr „cxbSâIza$*•P,@Å”¤cFÐËétCº‰Ù/W^½µÕõàá—7ãÚó)Ïõ߇Ç?ÿ¼EXtÉgð`S+òB¯ã÷wÿq8휠aîr@(Fp R‰}Û÷@º-Þkã§ðóÛ®GMeYF&*mŸ©ë0TkàÅךàÊ+…+¯„Šö«>?ÝàrX53>É“àŒŽŠŽSF‚^·}(U`F  äè¦öbž 0½Ò3"M€éHŽÓ†ýëÁW/‚ÍžÞÔ[DÃ*à©/èéóT€ÓÚ|}¥Ö’&]:÷ßg׿‡ WÌÇÏ{þyßC¨h˜…e—ݫ݉þAK>Ê&ÍŜ嗙“§Y²Ìætc¦ïëCÁ?Ö×.t  ?×”fÛõ#¸õif÷kkïÄŽÝûQ9ûì´´¿7Ǩý`°ÙÜŸuͱž†‡Ã Š]‚¹"ÈuÛu>¿1X¥=¦ûè&ÝÔ«Óïý7ríUaׯרZ‡›µÇ øýú±ô;zVÓ :0î£)gzQí÷ûívÜ~×ßñÏû”ù+°êßƒÕæP®—“WŒÅ\‡üÆßQÝîsøó {‰D3u6ú ÅU „àùWÞ€…·!¯bšôk›kÑÿ·ë¬ K 8Èœ•餶˜í—}¨÷¸(%NP’ë,xZ³S’ÂÄ×»ʰ]”æ9P’;¶]äçcr‰ ápv‡‰+"W,v²r„¶hß^ÐÄhÓ^gîÓV‚Ñ0i ž†3°âJ'ª¦Ì£Ü •84@üú•œBÄ ÞÊgÌ™€]S®)ò7m|/®Û€¢ºy°XøäÚ_ú¥Šò<ºß‚`p@]„T''¯ÐÔ´¦@»>ýàþcT¥˧$שŒûÑV4Ö k-Hv€™5c«ýe¹áš+±óµÚŽAšNBìND´Ö6jyöøº=¢P¾¦aAhÊ4uë…ø[Ñà'šóRƒŸH?>ÝâÓX+hèšæá€ÝÌUعçîþÇpå—£lºOú•“h©ÐŠó¥ ³åÊ‚®öV• 8”íz8ÚÓ½4évmÙ¯)p±Ën±×Á&k¬\©ºÙÒƒ,fޱù/K~~fT8’KºÀtkX+C7>@GI€O[¬ABf®AÚ®1¿BÜyϬÎ ¨#eæÕ8v¼ ¿¼ûŸà^Ô~©4å·\ŸÍµnŽv»U"µþwµu³ªÌ[Ùœ L–Ñ&€µú„ƒ»"i*”å»4Cïw²+”L‘+<¡|ÛeÅÈqަד\nþÄÇPïö‹sêÈŒ=›/až"@Ï !6ð5‹—ÆØú>†ÕS]û[°ŽÑÏbå9L­ð¤‘l% ³ÒzzûñÓßü‘‡ºE—ƒ·Éî%1|ëµI4¥8í/]mL `-F@F †—ˆÅ8z¬ “*Ä‚‘üû²|§D–´Ïý(*]€ãPQèÄ’iÅ£üºÉÅårâ²sÎ@0ÁÖæìh WÇ)Æ+ª½è2ª>¼”“ŠöËÇå2¥%m Ïaiyj`]ŸßœôVÞ´ /x ˜ Lølµ(P~¾æèéDý’Ãîʃ<û¯©ö§~$Åü§Ê| ×h„9 xD`T-€¦¦5»œÐ§ØÝ¬T\¹yà•‚’h{E+é*"® r骔Óq•¸,^‚ë|˜WëÏqŒè¿q@¬­ée½Ì©³¦‹ ¯€*K:Î@k}hËY?"“m°ã5¬ßmr™;-ð7.0œ<›·ìÄ¡#GQ9÷Cpå–*Ñ|’LûKÇåçè´?A'[ûØ8uo,¦|]§OؽmŸ&JM¤Î<%yÓ $W2¶K Ž×eCñGþÓ‘—ËKqݲrÌ«õÂbÖ,§âZsž175ˆÞUPÊ)Å„!ìØKê®ÂÚîÄÒom@„uhüýÖîèDWï@Fà鸠­_O>·ÎÜäUL nè4?Û ÈÍqÁ&­uA_ßÄÿc$ü`lÀ`ÊÞ׌H89B$FÔÄÀ6 üé¬îö¶ôŽÁ«M¼9.¬˜UŠë—U`n­Î8†_ß @ûíÚáÁZ0§ž0$ àAip\¶U ž§#3K@_ Š?=¿þÁ€f¢Ílƒ=“Vú³{ß!ì;xÅ“j@Nåç+ê ʶl ”ä@5‰'Ðsbôü`œ@"! ¹¹]WQÄ@ ÀÐ ¢ö2¯tzÒÏŸà_º’ëqãÌÙe¸~Yæè‰€1-˜iS †س VpV@PÛDhÖ $âÏ:5OOĆ??»ÑX,%(GŠ 0ÓŸ|þUØÜyÈU´? ±d‹ÖÄ()𪱱€Ñß3 .žf²%£NMMkhÖ§ØsD°T(…;À”hÍ݇ddMk<ÃoöoGˆ¸rnº éV‚îÞ>lxç}5Ìg±€n×7ýHy$5…Ô¦?€ 0@OG_ZXɦŒ< Æ’áï¾³ƒ*O±À€ãʼn>‰lúÃ`òk ¹nòrœP,陎:Áú‰ €'G² 45­éð´>}Óú÷¤µüd-!þð e^c¡{«ÁØç\®¨åùNxœ¼¡|¤¼8ßyíÇhšõô 7Œ`FÿSttM“ 20 ÐêI!elâ6oáЛx¨þ|&Ö¤ç±:sÀóÒ*PšþþúX€®u€ÔT¨« C®‡8~¨•õÓ®kjZsl$ëÎX.ýz¯>aÐÀþ}Ç • ®T¿oZ‰>ªœÇë²1+ÏìÛƒ®¶f†F×úñ3_ÐK|C\@"^&h’Yk&V‚Ñ}PÓx.I (Í&Ât{¦C*¢˜™ü ,1Ÿl pAuYR¯ebèéìEÀbý¬ÿéz3–ð<€N}âæ ÛÄB£\Ï¡ºØmRÁLLQ©2ïiéGs[¯¦²|‰ õD;rr 5óã&®Iøf#å<´Ö×uÒÒ42€ž5F€j&ä-X jPp8d@ƒœ0MÊì§[AI¾›’ÿ£¼wËa¦ùðèH×›1#€¦¦51èÓ·mÜŽ`0J™\bÑŠn€yw_õ¿¼£Çz3"8É £³».O¾Vë3@Ok{ÀÉ5>«›°êj°-= µœ¤× “Ç$s†¢ù‡öÒ7ýå@Ÿü£Ì)& $´² à‰¦¦5Y]ˆ%ci 7 ‘°sÛC§ Ê¸ìÚÉ!’𣻷<1ˆíO*]©ôË:ŸLDÐÞÑ!!À[¨kÐ^tV‡ ½ÆO¶® ^‹+V˜ ?®·Ö(âÎõH€£]!Â1$þHXÌÚ{Ç<â/fÐX6žGyqžBòõÚw™­<âæ?0ÆÐÔ´æ];õé›Þx_çR€fÖæk5®’ Œ ”\×î@"‘HªýOV« õD;x›ViÊsMÇ ÖøšRMÂ" Æ EÉâ0ɾ™­€æ¡¨€u;{’’v6ÀŸ.L|:êO§SŸ†ê"iòOÕôLƒ'¼<ug¬-€aÞ{]]}[ª$0­*6«~a3m¢­Œ'zÃxgw›© '³ã㑞|æEääÌuv×`vo@=Ø“ b »%&ý€ üz¢Ø°½Á”絉0×AJÓ3,ÕôþœT]¢ž/†Ñqœ9øç¿MMkp?¤9Aiyã•M [,kòµ•ö)5“e+ëk{úŽD™`g¹éÂXÊ«¯½‰‡{US盎PËɬ«0Ë0?ź‚É´={¨pªoÕìŽÆ Öí ¨Ùh"Ì$¶`:âOß@J¯¯,‚ÍÊkȇö…ÀžþÞôkÀðdÌ  ©iÍq/éÓ7¯ßŒþþAI£©-3ªó43è¬øÕíþ`oìì`‚=È“Y fZg4¤«»ßþá]((¯EãÒjy†¦7)C¦ |}PÏ\ëMþL» ¿s0€®¾@JÀ'³²aÐà&º@ þcá€É5%‰A¾F,ÇѽÇY?ëæ¦¦5[G cN’Ü¥OH$¼¹î]Õ_’ÊÔÊ[0­:/©ÖHÖž½a?úü”Úß äÉÒÌŽ™›‘CBnÿÞOÐïbñ…Ÿ¡&Ñûé©@O/-NèsuÀ×›ýDCFв{êcéZñ„”K~½l"Ôšðøu€W܉j+ áæý#²¶'‡÷E<δò<šÀÐÔ´æ50& }ûÕwðŲ¥ÚŠ« ¤î¡ìqò,"ó…£ % ¤×©bɬd„`xÎç?>†×Þ|óμî¼bà g‚žÝ*`ZžDÛùJ¯Ášºkh›ͬu Œª í¨)´›~¸M„éäQÌ|†¶×[“kK5¤@ˆ€X,Ž#{[XP؉îú«—qA’üDŸÅñÖë[ÔÁ.:lL­Ìct2'µÒïÀ‰®þ´@œÊEHµ °ë?ûÆ]¿ù#*'ÏAݬ%†™‚4ÍhB2ÐÃhÀ”†Èe VK eÏr X‹H’säc˧z‘ °CµÒÍSZ\¤®KA‚ÁªÊòávØJyG÷7kúû©´î¨É¸!€¦¦5Ï‚1î¹éå· Ft˜YW ôcc7Ó`„Ä^Ý=T“§Òþ™B:ñ†t>rþïýøW€Õg_íô[ZÀ35?TcYiI@{Ž |Ó Ct宀—1— k I Ìuñ˜YéL ê¡X™]NJò] Bf~?@`á¦Ô•‰ï$¨C<ÇáÝÌîý<8Ú¸7 ‰Á ˆ„#ØØ´]Sù!pÛ­˜S_`höJErÚÎc~héN l3“?SÓ?UåLWóËùC¡欺 VgãÝ)Ò’ƒž©í5=¡^I& aM¦éiÈöï &¿é "‚ù5nqݧ4A®50”XÁäº*„ú;”ö~ÚÄ—I¡¡º9.»Æï'„ å`"aæ²êwVÓ-ãcù£ /¼‰H$FU`±Â̬-D®Û¦Óô0%º² ÁCïtcÇÞÃiùt‚‡™D¦Ÿ¢ÂB&ØÍo½ ·`£Y´?Ù¼Ú¼ª ¼ù/y3¡~N€L5=+ÏPÀ/ òìm3m˜5¥ ô$ƒ=ÌN@%…T”æiü~B"¡öm;̪ïþ2V`w Ínè‹Åñü£k¡ŸŸM-Ï[¨Êe$‚dcä ÇcSOþùØ:Ä¥ IÒiH¦íGÂô—?…yZ ÀðF€³ÓXå"ûäàÃø xÁ2œ|ú6%?eòë‰ÀjIO»'#‰áX‚  áOÿ|]=¨œ±\ ~BÀqÀì©ÕJy:Ï–ƒˆÅ˜‘ÿß45­ ŽÞÆHòW;ô‰{¶ìÅÁ½G¥ ¥öt:xÌk(bŽ`ÓøªúŠ­©¼ÀÁXÖ<ð*B¡pƦ27 UeÌÄ‚ „  ?‘€_"SÃëµ¼ÙÜúIAZÚK`÷´$Yˆ÷×ií$Z?•k`µ°;ebÎÕ›ÞÛŽÿûÅq¸ù8*¦/GNA%hߟ“kJ‘ã´tÓ €ÞÎ>?ÜΪç‡üv,6. @²¾À:öÜC/"‹QM|ä娵•1öÝð­#ƒN¾¿~hzûú“õÒn2àÇÈÏÏEXrŒ¦7ðz köue–Ý Cؽ™® =NçÑ[Ã%ØtI¡½£ ¿ÿËð¯GÜâFÃÂËW>šîÀ„Àí°aJm)ô~¿H`ç¦}ÌzNˆpkSÓšÆPÆ%@SÓš7ÀÑÛÕ‡¦uïæ à,i,SzŽ)ZH_ùuV‹ ŽjÜ·vŸ©YofúØCÀv3À3 FгF ißX¦É‚véi}úZÖ4ƒ€™Zɬuo¼ƒ;unEÅôe¨?í8=Ì®¿³¦V)ýRhÓ¿yßqøû>!ä™·ßþã Çñ7v«VŽ[à8Ž‹F¿ OìÍçßDOW¿fê)‚Ò<—è ˜³`° ÌÈ -’‡uïI[ã§2û³¡ùåOGg"!?»ù/ àÍ4½Yó_2+*­yh ›X$Mà-É5}&äš*O"‘Àÿ÷ ~ây8ó*1eɇ‘_9 ÌŽ? ¨«,BYQ®üá`û·aUïàà`û7$üYXÆŠÆ%H…Á¿û!ö}ýñDBÀK½ª±XQæ6¢¬À¥«ˆ„cçýµ^?˜À±¶®¤@jô81€}¼Í©óÉó²üý¡ŒÐÂ& 1ÓúôóÂHf2¨lI– ÏÔŠJ–g0ÄïÿrÞxk3Šjæ vÎy°ØŒrsœ˜5¥Ò~€`Ïû™~‰è/vìø_ žþp7êxw /=›eûöGþAyOŸïÀ΃ؽýXà 5 ‡•³+à´ñº¨8Ã*Ød oGâžØâG,O ȆîçPó1¼µé}ÔÌòi@G»0,Àëýò¤–€É„!zkÊLãë; @-°ÉÕPÛñÞ“8Si÷t\-ùø‰öNüü÷ǾGP9cʦ,áŒÁoµp8}V=D}E¨™~:[»ÑvÔ0ç-!û÷î}þPÚZK`T19®@zyÍ'ìA0Øýu0& yþçÐ×ë7ü N;³+µ‰Vû±É€nJkëc_K¿¡"±Àž®0’xð¢ö/Ÿz:ìlß[`úþi€>ˆ°¦ `$ Uó ¢¦%[†’–w&–€Ùï’„"qÔ-¸ùÓŒ}@”ç!˜3­n)ê/—D‚l‡ø »¾Õß,­ö37À¿\@Û¶=¸5‘ˆºJ†CýJæÀæöŠï!h Ú†~L3º¯ï.LL´=«k°ÞR µ?«›0ÌÊ̦5õ#ÁŽ–PÚÚ¨!³¦ÕaN‰Ÿ ~ÞÂá´Yõ°XÄ9AôL ÐÝÞ‡;›™õ|p°óö––]P5~º$0¢­cJÒËÉ/›’vìxôhtð7¬k={ß3èïó+ƒˆä8m<ΜW Ç™4wéÈ€¡=y.½S*³?­ŸH$pððQ<ñÜ+¸ó—wãc7=¨ž¹ÜÐaFv­†gÒb£K ÕözR4ÝfŸº–Þò ®j}Â4½tEÐ7I«¥%²N ô ýà& !qN›YÛa$Ŷ·öˆ¬“X,øŸíÛ~1Uýf|8Œ0 p„õÄ£$DZ˜O¶ÏóvÛé§ßt/ÏÛ–é¯WQ_‰Ýr5,<N¼¾rìXç Önm!jºøÅSžGÚ§Š›pÛE•ð8,ò3ÓÏÏÜNṳ,þÁ~üë{°mç^ ‚°;s[Roi-òJëWV¯906µOäÿDÍB+Ÿ>Ñæ•åL4r½-å§óÈ™²­îTô\|ñ‚²}öŒ,žäB:~(Ö@"!à‰g^ƆwÞƒ§¸U«ÀIÏ2oF ªË à'Á»ë·£‹aú B|ÇÖ­\÷G ²ˆV¬ û$’íBFd®ëH\4‘ü–ùŸt?‘ˆ’ææ7¿Þаê޳Ó×l;ÒŠ×_z«.ð€¢€»º8KËÑ´S\!HžÕ‰ãÄz(6äHßÒ†˜ÆçÔ\%N ½m¶ŸFy~sÏ¿ðöæm˜²ô2ä•5À•[$fP%îhh; ØésÔm5/ÍÿZÐSûR"–ä<™€ØMIÛ;Z‚XXïP®%W¹çL~ù‰DñŸŸÀ®½QP5e“OWî;cRü ‡ve‚Ÿ2ØÒ²éëápªµM`´¼õi†}Žã,„CKØpeL€á÷³öMI ½}gO~~Ým……“þ¡/ÌÍk7¢¢¦Sg6H%©‚ojEB‘8ÞÛß)SÉ@Þ— A‚•Íc=è©÷Ñ|ëó°¬,=)B°¾i^ym^ V>@QZP³€.^G=žÊÐjsê,¢½|œy,ðåë*y)p«J¢õ©ãÒwG ýym)ŸÉgÀ?ˆ¿ýû´´@éä…(¬š¡1»Y…Ë4øÎ»[a±ê–¾Ò|(eÈp S„%|²±¬Øˆ!ˆˆ 4¾ÉgtôIih]™zãiiýT$Ñ?àÇ?•\ƒ³êÅNc:ð`ë[{ÐÛ5À¬ß}}ͿݿÿÅ7G°Žˆ0šÍ\ÙØ6|öî}n]ËÖÍ[Å‹¿ŒXeòëâ‚^û«Ç{ü±”­+¬Ï‹¯¾‰ý‡šñ‘݈ÉS¦CTÒ‘ï E°éµm&C{h4°eûö‡CDÆN]ͬ¼Ã’±°’½l¶òr‚ÀöíÜnd=L_wÿÛÿÐÝÞ­h-h¹n;.9£S*ó!‚ê<>iÛÿP#ÿ]=½ØôþNQûÂ$$ ÀÍt»¼ì ÏÔòIôF“ß|¶[`|ºŽÞjÐ[êñÞ1Öïõö¦­8|ô8®þèu¨®Ÿ.ùûÔóƒ àâµÛ0Ð`VäX,¸{çÎÇîŠÇ# ¸CÍË:>d•Ñ€ò$Ÿ0Žîcm§:žI^Þb±ZçνæË.WÁ¹¬g³;l¸àã— ²¶\,SC±r8ØÖ_e6 ’Žúc훥ÉòÈS/á¡§^Á¬K¾ Þî4/D¢n“c„N Ðå#škˆ_Ôʶþ˜|ž6]5•åcÔ¶òMÔ'&DwMõ¢ëï¯ä£Ì}õ˜z~‘‡Ç‹ò”g§‰àÀ¡ftv÷*ç„Baô1kîTL£Î”k÷÷úñîë;Z”‘ÈÀæ;ýU4C;bµêx&y™ÇÉ0˜ ïÍ)¤$9s®¾Ñã)¿Šõ|´$  b§ƒzx\±(_üþ?žz~¶ïÚgN>ìî\€ KÍGa^<%u‚ÑÄÒÕч-v!c¼ »×mßþÈŸ!Ày(LJKc6x”…Û¾ýÿ™1ã’¾‚‚ú› Ãx"!à•ŸÇ¢s—`Þ’¹â E¼+¬V+*++ÑÝÝÓ‘š›šX„ìÙ¯¾ñººz1yöåê´Ri¿ ù,0Ë@K–Gw\wŒè4:SÛ‹/fåǰëIFz21þ omz/½ºÑ„€²É QX1 PYš9Óª¥Î=”U!_K h>І}[IÇ20pü‰;Œ~&'³œŒ.À°ŽOž|öÊÒÒÆ/“üª§Öâ¬Ë΂3G5ǧ—ÙPêå•ý@ €®®.$ ùýôïË,‡#ÇZñæÆ-hÚ¸ݽýpx PP;¥3V¤(Ab²ËÒý„}<àuÇͨ?O“®s ˜cúåsõ ŒZ]ºŠ‰¹¯Zê1Þx¬QÝú‚¡0zû[\‹²É aµ9a³ZÐ8¹5å…JŸxku‚‘X$†›÷£½Å0œD) îîƒ÷íÛ÷üó[­?"ÀXÀˆùû鯭]:¿²rÁ×9ÎÂtºÝ7Îúð¹R\XXç€ÓÆÑïƒD"a°Ì€ÏqÞ~w~û—ûasä ¯z&òkfÁ]P™Q9 (µG´›Äx<…@ @gœ§K' 46hà›[ÄôxrW€Býí °ð68=ù!¨*/@㤠8lVT‘&—¾žl}k/B0»¼ ‰··ïøËáÃë›0¾üP¯E† àÑ$€ó·¼|Î人åß²Xø\“gÆ‚U qÚ²yX>Õeö^‡ÃèììD$IJw­ùöŸbÒŠëÓš!ÈT’h¦ï¯|Mºðôqsÿ_=njÐ÷Hâ$õóåge¸`€⌽³§Ö 0/Ñšü i4ïožm‡MM~B„pK˦5--›¶#õ”]£ôÓo—F;@Û$ãCÍkv9qbûáHÄÿ½É“ϹÕfs5”¼÷Ú&´iEõçÏGm‰‹9‹ÝnGUUÐÝÝ­t#T‹ §·ÛvíGåü ÄàCÆ¿™™æg$š‚]dî@: —‰Ã3PH"ðµûDGz’ Ô1ÞÂaZ}9ªKÀ ˜&4ÅŽÍûÑqœÝ­âñðñC‡ÖßÓݽ¿EWÈÔ‹hö…Î>žI^¤™wX2j“‚ê–üÊD«gã<Óm«Õáhl¼ô:§ü<³gwº]¸ò£ pö²¹ày^sŒ&…x<Ž®®. *i±X¿ýËýعï0/ø",VÇÐ ‘iÞ« @gž“ÚH zú\ Œ†¼ —úV„dÀ§ÏMb‚Š’<ÌœR§Ý3­ôv`Û[{ ²†òŠtnؽû©ûc±PéMØ™M“?£óH& mGJŸ¿¯IDATÈp³EÊ~}ýòEåås>Íq¼Ûì&Í,ÀÇ?²õµUIß5£§§}ýýøý_þ‹{ jî‡PX?™õßPíÏDL²¦áû.F(Hnþ³Ò +Ã= f¤²ÉÊO[ sݘZ_ŽârŒè‹cÿÎ#8vàÌê;!B´£c×ý‡½&ûûf¨³Jà £Kú8@Öµù¶5ûùùueS¦œó›Í]oþ"1œyî\~ñ*x=9¦Ù‚€§_X‹ÇŸ}aïtÖÍ£®‘¢°HÊí±dùõ¿/Ýù'%Ðémôútú<´ò=2>ÌÜ/)ð`J]™èçKifZÿxs;öm=ŒH˜Ý±b±Pë¡CëþÚÓsè8Rƒs4 `Dý` €~€1z²cŸ¦5}½Ÿ›[Y¿¯5óåü @i¡Õe(-ÎÏqKeîàıNÜyƒÌI:éwúû¿qàÀ+ÏF£ƒtó^¦0\È IdKûc@€!0ÒZ=]ðóãóÉ–næ êËëëW^ëtæNOõž9¹9˜}ÆLžY‹UËÉŠ=KàX{Úºüèè OÀ\ók ¾;ó†Ä˜Çx:ph$5“6iæëÒ¬<‡Â<J ½¨,Í‡ÝÆ«÷3¾x BB@ksï>†€ß0¼A"ÿ‘ææ¦G¤N=é‚|¸$0bDM팆ŽA# ìL´*‚„Ë–•ͺšçm¹©ÞÕ•ã¬ų0eö$ðV+Ò ð‰" w „ŽÞA´÷ ¢«7€xB0¹ÆÐ|:a7sX¾=`° x‹…¹nxP”ïAž×%-ÎJ»ò5M€püH;í:†PÝw_SnB<Ðѱû™#G^GŠ˜§ø¡ÀH€a?[‘ZÆ’Òu2 Ü¥‘/UzÚy¯{òä³/ÌÍ­ZÁqc[ NN;êgNBÃŒ:–€¤Õ)H jA 袣g½ƒè !+Y3 ¨éãzë€A¬f>Ø­Väz(Êó ¨Àƒ¯  §€<ðÅMÕÏì àø‘v´iOÚ–¯>*‰ûý­ï<¸îùp¸o™ƒ 9Qd›Ò&‚lšþ²ŒLW Ûš> gBÌËUà­¯_~vnnõJ‹…O2­*y…¹h˜5 õÓjáò°i-tóß)‹Ãˆ` †???B •FÂé[Ì-íqsóžã8ä8mð¸ÒÇ ÛÛ »•×þØÀ§ãZàGB´íÀñC'0З<°§–h}ûèѦµƒƒ}ÈLÓlj8KûgÕô—eL HÚ7 Û`6ÐS}ŽÜœúúå«òókWY,Vón‚Ú÷GYMëQÕP«Í||³¯¿æÑìB0Œ ‰!ž‹Ç ˆ'ˆÅâw\@<G<&*?+o•çaå9ðVñÛÆóàyNJ·Ài·"Çm‡êrê*WHA:êyÔÉN´1øBB@ûñ.´:νH·^’÷õµ4=ºa}0ØãÇÐN>ØÓ%†¬X #~`ÀŒŒØÓÍÇ¥™Ï€³ÙÜÎúú+ êÏây›7Ýr°ZyTO­AUC%J+Š`w1/ƒ†7Ï«jaéDåKÜ’´ÐçÒ¤Ööò5(k„ˆ“qôtö¡ãx7Ní@,­fPQ!ìëk~ãÈ‘ oF"˜ƒ9ÀgÓ øM `$ÁŒ Ý„³ ôliþT$`8nµ:íõõË}……“Îáy{~¦e’_”‡ÒÚ2”V• ¤¬6‡Í´33âLÁJ&å‹Ð)Z¢ ýz@Œ3=}¢é¤£u!bÑ8z»úÑÝÞƒî}èL[ÓË’HÄü½½‡×77ox+ ÐMzz@§øP `8Ä‘µ0A?½Œ†L£fâƒM©Ò8‹…·VV.˜YX8e‘Û]8›ã,¶!” òKòQVSŠ’Ê—€—šÏda[Z°3ó锌6¯¨A;m3¡Æä—H$ÐÓÕžö^tŸèA_·?cÀK×K„B½{zz½ÛÚúÞŽD"ƒ àTÀg=Ûàb‰ Ÿ^ÆII`4žøSŸµípx]••§-((¨[äpäNÂçw·X8äxsà-ô"7ß O¾Þ<T"ª50‹!#’ ³Ÿ–qI@ÚM„#éÓ§kòsÈøÔ·²]ZÚX_R2c‘Û]4Ãju–ŒfY[,xžÇñx"y7äx<Ò õìëêÚ÷n{ûŽCRà‹t*HEÃu FÊe•¦¾d2n 0%Ñ €L€Ÿ à Àg¥y‹ ŸüüºÒÜÜÊ*—+¿Ìn÷–ÚíîR«ÕUj±ð&] GGI„c±pg,ìŒDüáp_ûÀ@kkoï‘v˜>Ù'øYÛC%‚LÜ‚Lˆ iÞ±?p`JÙ æð“Ý ôfé0Ks»‹sss+KÝî¢2§3·Ôn÷”Y­Ž‹…wpïä8ÞÁqܦ‚'„$I„ ¢‚ÇãáÞh4Ð÷wƒÝ~[G Ð)Ï¿Ew&`Û,]H3=™%0ZD0¬àáX™üz9©`ºwÐÁØ?m“?’¤Á$ 8ž·ñv{ŽÃfs»l6—Ãju:yÞá°Z\" ÇãáH<‰Äb¡p,ŒD£p"¥Æ$&ÛzpÓÛÉ€Ÿ®;‰+0^ˆÀp|¬µ>-'(.ZCÿXHæ>Ò' 0ÙNWF›†c Œ ™Ƌ֧å¤]X.LŽãÌ*Š \³´dûòv¶5ÿP´?Ò<“4€M¬ý¤En²oF©È RR¤k"À—夵4/¡ºÙÒøãÍäOz°¾õÛ¬}–$ûúít¬z{$¬€qCãÉÜgÉ‚”—ÑÆÆ#ð‡kö'3ý“=•韌HŠ´lYúãF†’=kD0Þ/ËŠ”—JŸFø™Fù3 ø¥c$Ûfí³$ @ÿ°Ò†Lô#F' ðeù@€òræD0À®¯?\­?T0K“%] €Þ΄ôûÙr2u †E'ðeù@€ò’ÆÁh?f: O×`íg*C%:m¸à©Ø@FDp²_–S‚4/¬v& ð‡ëë§CH30sÒ‰Ði£íd•NvàËrÊ€òâæVA¶?f¿™¹Ÿ®ÀÚOGÒ‰èÓÒq FÂHüÁô´œ² )m§¢lùFÂìOÇßÏ„ÌÒ’I&ì{,Ýtƒ„ʱ"ðe™ J$«`¨ÀM³(Î~2!iî…èílºCv >È §e‚L$ 2.èÓ%`èli¤ìV}z¦–ÀX»LðŸ* §e‚ÒŠ F:ÒŸ®Ö)ߟ>–¬b ×Kwà”1ïÓ‘ ‚˜X™ZHóXªmÖ·Yk(’M ÓFÜ8Õ¯— È‚èZ²mö³@>\Ó8$øéíl+-­Ïxˆ3d‚F@.C¶›ü²áûg£PŸ6\ ·‡þ Ÿ™LÀ(ˆD@öšü²eú§€•FéÃ!ý¾áØà‡'0†¢³€ì@²m¤‘NËP[èíaÀÐGF&` Ãb’š Xû©Že«%@ŸfJ@]™ €“Tt$ÁúÖo'KŠ ¥%`àãL&àŠ8†, þàÈLÈ„œÂbë˜ ™±“ ˜ 9…åÿb‚lè íetEXtAuthorJakub Steineræû÷/%tEXtdate:create2010-02-20T23:26:19-07:00Á›6õ%tEXtdate:modify2010-01-11T08:56:55-07:00‚Èö2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏtEXtSoftwarewww.inkscape.org›î<tEXtSourceTango Icon LibraryTÏí‚:tEXtSource_URLhttp://tango.freedesktop.org/Tango_Icon_Library¼È­Ö tEXtTitleGlobeN‡b]IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/multiple-file-list-icon.png0000664000175100017510000001541412370216246032147 0ustar vagrantvagrant00000000000000‰PNG  IHDR  ‹Ïg-sBIT|dˆ pHYs.#.#x¥?vtEXtSoftwarewww.inkscape.org›î<tEXtAuthorAndreas Nilsson+ïä£tEXtCreation Time2005-10-15 ”WCIDATxœí]{U™ÿõãÞ;s3ï™LBf&ÈKC0¼Ôˆµ>@APy¬”tÑ’ÕÝÕ]—ADZVS"‚¸[eQ®EYìúØ¥Œˆ®¨VyT$„˜„B2™dÈÌdž÷ݳôíÛÛïÛ·»çNÿªnÝ~|çô¹ßýõ÷ï;çtS„Ĉè°cq#&`ŒP0F¨ˆ #TÄŒ*bÆ1c„Š˜€1BELÀ¡‚u"t÷ÝwwQŒøv[¤êÛ¤æ Æ ŸgéÔË·ß~;vkü€-·oßN5¥ÛtО– ½E]%b;€]a·Æغàd:¹1ù¢†-Û·ooˆî“­¤!®(Àù[.XúŽ·o]EQuoW xžÇ¸¯´Gµ473΄Ú(`K@Š¢(yÂL[{{"N·Ô»Q1ì!0LC˜†0ã1.EÁF „ä9Ž{ÃÏÆÄЂ¦©&–Mœv;ê‰ZÈñ<7îgcbhÁ0LK£0vÁ1BELÀ¡"&`ŒP0F¨ˆ ¸`И«c.4&ù€˜€‘!€´f»qÉÔ´B±XŒ‰]F*•Ý–YL ¨ GGG›Ahˆ±ÊZ@Q4Ö­[›u*/ñnñ¨c¸Ãb$žŒØU†ŒÅL> ¶€¡Á ñ¹K0¸ 2™|@LÀ@áÖê5:ù€:°¿¿¿Pzí0:z¢÷/ö_”Éf–†q}#ì}agÑ4Å$“©VÕ¡Õ•s"ùà=÷ÞÅ•q“°óKƒ_±ýéu! —ÜW­xò©?¼ãà¡ úº£Cµ½:¬F8Àu~à#v‚ ‹¢H}ãè;ÃnG ®ºçÞ»ÖÚ 5Dðر7–‹…N i¿qh† »Y‹xò©Ý8>r–R^ àß­Š4yA¨°-‘H ¯¯?Ìæ,jô¬” I;ù†pÁ1.µ€ù|žÉçó¾“>—ÍšþŽãÕà~H$ <>­ PÎÏÏ3333 ßëÍdLë, EÁïKÆPeÛ<0vÁ1BELÀ¡"&`ŒP0F¨4¡i Ãø’Ò4‡¹QË"Pöôô”zzzJ~×+ˆB(“bÔŽØǨ µ¦Xb(.Fððk)Á¢%àìì,fggÃn†ïhkkCGG‡½` ðsË¢%`©TB.— »¾£©©©nu×cÕ¢%` w¨×xz œ™™IÌÍÍù~Í©©©øå9uB½—JÀR©D ß#oŽãâhÞgx'ž»2± ŽQ… —.Z677×=Z étÚsÙ0Ë/Z¶´´ ¥%~çàÞÝ*ä‹ó€1j„7wë_P(›››EAx?ë$˜‰§<»„ww»€ó€­­­|kk«/T+0“ó}‚C£"Lwk„é‚û#ͼ"*VOEÀ ˆ'ÑôèŒÇÅöõ$Þ¢Iõ´²X,â7¢ùÆ7º’¯§»]4i˜ØÝzC”­žPEG H])P$‹þè2‚%ÞËŽ',Lw››Ÿ¯ß¤„zåôêA<‘rÁQŒÒ"eõ¢¼(É QËM-d4h0ì¡ =‰úû£ÿx·¨¸Û›†‰ª»¥i:Ò“¢ânl&v·Þwëw:6P¶µµóÉdÒÑÌÝüÐB±ÐÐcÁÑv·µ12Êwo*•S)kzqÍMMÑ;«Ñw·Ï.„¡ ("*îÖXÞÙuœ¢n\(CAzˆ¢ˆL&S¿ Ø ^zÓ묵µÅò©¦õ&ž ß ·áÇáÔ©S¾×k‡ õ¶nÝ:ÃÙ5nÜ­†ÀWF¥³¼Ð½¹±z‘JÃ8½{‹Å"],–TkxýQb¡XXo¥‰Š·Úê©QÝv–ggçØééé„ß œ™žµ}!J”°‰g-ï5Z@·J$¶e‚ çnµÿ©Û¿Ã#£|÷F ÑêÙë8è< '%.,â¥R)lذÁ·ú¢’ÓÓË*)¯VÏ©¬5ꔆ‚sþÃë[ô „@ªÊ¾>ù·Q”ü#ístJ3­Ë¢–Õ—1®ÛäÊ.dÁ7ÆîVÁbp·LÃv ìîîæºººu¯™¯]M _µ¼t ˆª»µ+´ÕSÇ4LeÏV–¢hâÛП |V‹{x¤YYèO†'.·QÄîÖuå¸&`ð9=/w¯wð<‰‰ [¹¨¸[cùê2 à···VXì٣γa4G\Èš—©·ÕÁöõ AÍXñž¨>Á² ,]ÚkU›ÃºÍä‰áq;¸$`”;ËõGìnµedYuÿ×íT§4 Vg¹^hÌ!4§²ÕeŒä !õï!*wo=[=m3Yù ´•ÜT=x• #üœž5ñ¤sD½ã¤Ò ¼”¯Ct‡Ì „ê6ܦiWOš_î`Yeʤî¶úúÁX@¢ºÑ|6ʪ§²ÆeêA>B–e100àHVµçRÞºLøz³·zæEëhµ$'ÄýÝM«»[mw:& „c‰D:Rv¿Æb¹[©Þð‰g,o^&èèÖ¬Œ¡l]û€¤Ò÷“IèàºÑu·NïרÝêÛ¡¿N@°\½¨Þ‰†ÛpkÅ·zÑЛy©Œß©1—.X„DÆm8‡Wwk…Eën}€K\ö¾rO°ZÀ¸ˆu¥.å•2N•âÆê‹%?~ÜYÅÆW³i‡³2Aê­¯¯ÍÍͦeÌê6š9î–¨®- qí»×m_ÏÉÛÄÂÌ鹇µÞŒ=ƒ=ñ(Š2 a=ƒ‘Èÿ¦ê_ âîõB<çÞÝ— šxfe¬dÕ¤3& ;¸µ€@%1ÎF#7å Q‰n­å½Â‹ÞÜY=CÖÓ— Qí(g"áncaäô¼À«Õ3¶#^]®Žp;RŽB¤Ýò1»Rú:œ\É…¬;DÅêÕ'ªt¯7)‡g|ΊtfV¸|gk ¨ Bl²AÏüî­’t`õœM]wŠ`ƒ3¯î6™Ô>ZÇ é Btä3¹RpÑ­»4Œö:f i]†m³®[Û6àE‚£3%ŒÌs˜ÎóxKw6t¥ÀÒFV"z3"šžlVt{ßz !¦‰µ`îÞ°Çoó<Á{<¢9öókV£¿5€`,Ãá¿^™ÂƒfðfV›Òib)l^ÚŒëÖ·ãÖÍ]奧Öz›*øë_ƒ :¾¶#_5àIoŸ|ì$^8¯ÿÌyøü…=®-Ÿš|•ãõ B¤!¿2û´³õrNjs!«”qïe£m!Ჟ'ŠG¦‹šã¼( øÕksøâîS˜-?7½Àž±­û“›;5û{Ær˜/Ù½ñ¢ZoOf5äÛЕ¹K›5îÖí§xîVýu!¸ÛŠ<ü§º^ã¶9‘5Rú#Gæp÷žq@GƒmoíÄ{–`e[àèL¿>2‡_Ö.ùœÌ ¸å·'°ó†5ØÔcöÒO‚ËVµ ¿5ÑyéÉ&yžàáóøä¹Æ%Lô¶{$«Ù¿nChš®ü®Z/dtgËcÁòP«g„ª;ÐÅïvcõÌ[õÁ;Ÿ= B€®nÅŸ?±_»dÞ»²gw$ñÖî>|N+^¿[zµã®EàÓ;GQôõ*m£Ü²IK¶ŸüeưmVzû½k±~4MkH鶋䊀R"ÑN‚µ,¡&žS+é$7åÖ øãn¥2FW pùšVüäÃ+ÑšÔ«U©ìⳚñȵ«qñr- _Ÿ)aÇÁ•|µÞ>þ–v$åêû' xi<_)c§·CS%œÊ(φºhy«Û“5°ÖD´ ¨ 6®ñ#E`uçÙЭ»u3’!£%Iã;ï[m†Å¸ÜÄRøÑUÕDý—Δ‡ÛÛ±4Íâʳ[5Ç$+èLo»ŽkßrýF{ë§×³ )Š\&¢]P”‚_B,mŸ¿A†Se˜Öì“ÕÓ¶©Zêý+[°|‰Ü¥¶Îzš|îünͱ£3%¼<^°Ô›¾Ï÷Ë׿1FŒôöèÑùÊy†¦ðÑõ†º5Ó³ŒòÛ뫯œ»õ…ùcõÌdßշİŒ•nÝÜ}Nú™“Ycaù:+ÒXשŒ\d9¿|mN#c¤£‘y{ßÌUd.]ÕŠe-µ»_µþÿ \¦aÔ#!ÕyÀz¹[W$$¨tPI%Vòd“Ï oéNjÊ8ÑEgsu‘ïs's&ÒJÛ>aŒXéçáWµËMçvùB>÷†@ wAˆ¤QÙú‘ Ü­í¶*,pÚ ·ÄSË©:  eM®^¹ÎÖÚEð'æ9y©Œ¬·6´¡™UZñòDû'‹–ºzèBÀ®fWžÓá³ë•þ?Qõã È%všp«û€òˆˆsòùán ï¼ªŽ¿Ñ¶Ü†ÚÝ­Ò,í:JTýF S…ê$¶^oí)׬kÓÈü÷Sýì›(à5ÕÈÍõ;‘b­ƒ 'Á‡>#Š"@Äò¯$ ÀYvÚð;KÃT :Îéùaþ¬mº_îÖHž¶uAÒuôíèHiß26­E1×›>yøð, ‚±>:4­‘½ys¯z'D„(Šåo"“`û"q×yÀ²4BÌJØ[='nÀÒ%ؼҠwë¤ Í|±+cTo{“–€å¿ÔVoç/KkÚó%¿<<[¥+ ¿Põÿ6-mÆùË—8N¯X}DQ„( éÊ$œ˜œPkȬ?Qç…éE±Éd²&>Ï U£Ù§Ê/Ä(ßE•mý~ùZ’2 !*PE(Š›` –tYM\pkñ´eŒèÎо\äµ'»šÛVÞþÛÍ]øÂ®“•ó?Þ?…›7wkdžÍ`L•|V[?£:ÕÛêcê}BA¨X<Š’¼Î¡Waìô˜ºÉ>[@¢MÁÐ4ÍR•(ÊÛ`°ªcúCÓ4CÓ4KÓ4SÞ¯lËŸò>­:F«dhÕ9š¢(ZÛN…|ÚûÀ«»µn9¡ú:NúgòÚéZMÕ/þ4³@×mìD»Ê…ï}3‡ƒgŠ™Ÿœªœgi 7nrî~’ý¢(Bˆ¢PùEÀÎß=¦oú”þ€žú€eˆDÉs¨rÔš‘Õy²ÅÒœSï—Ï‹ò1Y^'#ªŽK7ƒí ÚÝ­ZÖ¨»Wˆ¦ŒÓþñéœÖKõ·$4ûVI'hÜøVm_ð‡¯œ©œ/ ¿:¬¸ß+Îé@ï’DMîVK>§ÆNâgïÀ£? AÐPxÙî÷;qÁ•ðéè±£E6ÁÎÈÿ‹öïQ®ªÕ=!T¥gƒŠÿ¢Ê»„èþPŠ’(U®E¾ó*17UÝ㛚šÒ˜z»èÈ»u&ž*`ëŠfé(©OžÐæý¶öIi§nòÖózpÿ‹“•ò;LáÎ÷ô#dðø‘iÌ©‚š·Ñ'ñû'G@Ó hšEÓ )4-}†˲åO –Ã0 i C£TâÍeÍf05=…‘‘äò–yËgít`K@‘§_¡ñ}¨ùù9þ…?ïµ_µ<,Úä†Lî‰'ã¥ñHÜsï]“fç2%Øñ:O)7ã÷^œÄc7¬ÁšvePß ñdèñÕ§O£¿5KúÒš2úºŸ9™Ã7ž×[šf±mS§c׫ÞN%h|â¼Üûœ’¹ïù7+Û+˜ ΢³X¾l=úì?Ìqxž—ˆYþ”J%”J%‹E‚P9/ÏçæÕUüqhpx§í…à~2‚€z2Âw÷ŽkÈgò¾öôi•¼mPG·Fò Ma®(à†GFð•?žÆî‘ ²%A#ûÊDÛ~;Šë~5‚’*mCQÀ}—õ¡%ÉxŠP)ŠÂ§¶ôVͬ‘q#‘ÖkHDQÇqâñb±žç«>¹|Vÿ@§!;ʨ۫º¢‚UËÕøÓXÎõØ­ £ÿù—ôâkÏœ'<°o ì›B‚¡pAoŠÂë³%œÎÇJƒoïÅÖHc»^, EQXÕÑ„+ÎéÄ£G´Ãn,E°%!P JD,ß ryµ5“·yžG±XD©Tª²xòw‰+!WPº4M?þ¥zƉfF$ Š(„ ´% ÅV›7ªÈ Qßݿ߻¬Ÿß} …òè'ì3¾iVÊ}—õኳÛ,ÉevN/sÛEË«xakiQ"¾¨²€ÇarR鹨ë !¡ñxž/ðÈäæ *‘¯ØÙÙõu{m)h8L ÜÝð¹ º‘bªmÖ/ÅÜÝu !¸zm+žø›5ØÒk§m]‘Æ“_‹Ón8òàvLœ¢(\~N'Vµ§4×¹´W Ô‰b}?–RN6‹ày¾Ò´údróD¥Î¶¶öï|æÖÛl“Ïj4žÔ M¯ëLáÑÖà›ÏŽãÐT­ |á¢\¶ªÅ´¬›üŸk;’ØyýjìËᧇæ°o¢€Ñyé —5ãâ³Ò¸è¬4.^žËОܭÙ6Cí)Ÿ•ú¼ËZ’¸¨SÄ¡r<"“EË5‚Ú[}ç Yð‚2Š“J¥þûÛþá»0JX  ¨#OB€Í=MøéÕ+-å+[>¥ÊÞ¹b ¶öI$÷ƒ\N¶_ËàéezþÍo[†¤pFùmåq\Ù‚éá„x<Ï£P* Ä+Ã0ºáÚý3¤Ù/v«å5hHº#‘{«çd±|PÛêc_ÿȦ-·œ·£û”^–PŽre«þ=N-_¾˜ÓÀ±óßvþ¶þ, × Y£A èD^¬žóÝêcAlï<2Ç^S†ÞÞÑ׊Ý)œÒê¾ôÛIUôkö/æÀ šdó,€àÒË夣<ñÄ1.±‡}NϨŒ~‚¨>q›·sûùãÈœé9^¾øøQM{þîÂe©¡& p8ùd =ùƼghpø/Æ}¹òÇ•lhšÍ‰õk‹~,ð1’}ºˆüô žx£zÆóTžÇÇ:ˆW'•Y)gw6áÚE¥’BB8Ž«$›ã8d óDMŸñU[‡‡åˆ—ƒB¸h5Û7w í­^O{ÇÇçD|tÇA\³±×lìÁ²–$ž>>ƒïïÃØ¼B2šî¿r5ÊȆZ/úQ£oy»Ä‘/åôú|ÀG†‡Ï¨Žyž!ÕTà~‚¨ñ€ê„­Ñq?·w›ÅoK}»"/bÇþ ìØ?aØ6–¦ðÍ÷öá+Ò•™Ê%N!'EÑŽ 9Í¢ 6à7 ›g×]¢!]°zUœwë&ÈГ°^}¿õÝi\µ®Ë¸Q*¬ëJa×MðÙ z43]ô}@+w+O:˜ÏÍêÉ'ø€ký$ÐÐÐÍÓTÝ¿cSw ¢jT¸‰¥«djÙ–¿Wu4á7Û6ãç&ð½='±ïtSåu$í)[–§ñ®þüÓÅËÐÄ(£ò‚!ŽW°ñš «åó9¹‚~…à 7 ?éT›nÐT÷Y¤)忆ÞèÕ£2ÌOݼÑPÆ®¬yBD|tC®YßQ&(Jõ’Hy8­²>—ˆà9¥{FL˜Ëg‘/æÔcº2~à¶¡Áa£ú‚†$  BXÖì'ê®k‰Wë¶¹œ—%”»f$3' /ðÈæ´“^ÕÌrÈä3FïÆ›ðCƒÃ?2QžohHZ%¢+oÙ±ñÏ2ôÛò¾~ÛŒHúcò¾¼L(s‚©÷ÕßBeffJ3æKS J¥2¹ ò…,øjâ‰þÀ¿ éOÖBÀ ;AÀÄä8X&¡?¥"Ÿöxù™”æ°¼§œÐŸ'•m€¥¬ö“I¥Jܨ H©ˆìVË–ˆ"DA"¤H$’)rR¤¥žFOˆˆã'F4m<33‰B1ovóý€Û‡‡_1:Y/4 _0  GE<ôóa·'u7_¾`¸„r€;†‡ª]jP.ž0iÜsï]÷¸#ìvDRÔô¿-xÀ÷‡‡÷Ö(4Š€í^ðY›BnKØ ˆ<å›Èx’~ð?CƒÃNÖ‘Ö cc(øÖ½ß\ À‰¡Áá9;ù00F¨hÈ¡¸ 1c„Š˜€1BELÀ¡"&`ŒP0F¨ˆ #TÄŒ*þnÄ S­ckÓIEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/important-icon.png0000664000175100017510000004150212370216246030440 0ustar vagrantvagrant00000000000000‰PNG  IHDR\r¨fbKGDùC» pHYsIÒIÒ¨EŠø vpAg²gÜŠAIDATxÚí½yœ$ÙUßû½‘kíKWoÕÝÕûô63=êY5³jfPiIH d °…M!–‡±ì†ÂÆÆ@!„áÙ ¤‡l6am%i43Ò ³4ûÒ=ÝÓkuuמµåqß‘™™™‘™U¿Ï§?qâÆÑu~÷œsï=WH)ñ±±0:,Ún +÷Û$%`1÷»<2æÿq¬wŸÖ>F‡EØ×›Ñ<¯äùßN à Z ,c&…üïtTº§»;ÊÐÐvíd˶:»ºÁ0(a÷”¼hY¤–ÖIAMé‘MÍd‰-Ä™¸²ÀøDŒ‰‰Rå­… ð à ÀWGÆdªÙ¯¶Þá@ƒ0:,®~ø0X®lG{˜»63´w;†éìé%ÔìW¨R"Õdâ]l)%Ó3KŒOĸ|9Æ•«‹d²j©bÀߟ“O4ûuÖ+|ð£ÃbðQtÅ¿¡T¹h$ÈΛÚ»“Á¡Azû7A A}MCj*¨ºÿ€€‚P÷- ©!³‰Ä!›@Ó$“S‹Œ_Ž1>ãêä"šfû÷xøÿ€/ŒŒÉ3Þ˜Ÿ\FnLþCÀ¿î£Ä˜{@ìÝ·£×bçÞ!”P[ý—™N!SIý7UMÕ•]UW•^Ór¾} ÈJ`õX @D¢ˆpDÿ …kh«ŠÌÄ!½™e@’Hfxó̧ޜdzf¹ÔOŸG'ƒÿë6$|p £Ã"„î×ÿú¸¼-¶mëåØõÙwÍ"Ý5=Kf3ÈÔª¢“Nêç™ty¥ö ŠR ”H‰ ÂQPXRE¦u2È&˜›sêÍIN™beÅ60üð™‘1¹Øø—^ð  NŒ‹(ðÓÀ¿vÙ•éêŒrìº\sì ÝýU›×2“A‹/#W–ôéµ3éN´µ#:ºP::QÚ;+‚š^%-”0>1Ï©7§8{nÆ.f>üáȘœmöû®5øP#F‡Eð à—mÖëBâØõ‡Ù¶k'(AÇuK5‹\YF[YB./é½üz€(mÐщÒÑ…ÒÞ¢ô¨§Ì&t"H/€ÔÈdTΞ›áå×&˜š^²_þ;ðû#còj³_u­À'€*1:,z€Ÿ> l²^(‚c×ïçÄ-7ÐÙ·Éq½Z<޶8¯÷ðÉD³_³1P”öDg7Jw"Tb¤CªÈÔ<$ç@êÀ¥ñy¾ÿâ%.OĬ¥“Àÿ~odL^jö+¶:|pˆ\ÿkèÊßc½ *\ÃAn¸ù8íÝ}Žê”é4ÚÂZlnýôòu@éìBôôèêÕŽVHM'‚Ôhú|‚«“‹|ï…‹\¸8g-þ øõ‘1y¥ÙïÖªð ÀF‡Å€?ÂÆÇ‡ƒ¼íÆÃ\ãõD:º*W¦ª¨‹óÈØ)Ñ–õÞ~iQs÷á"BôôèíGDÛÍ¥D¦rD Fçcq¾ÿâ%NŸ™²Î)xøÄȘ|ºÙïÔJð À£Ã"ü*ð) j¼P7Ýr„·ÝvÁH…±{UCŸA›Bf3Í~­5¥½e`J—Õ“ÈÔ$¦ 1‚ØB‚Çž8Ã¥ñysA=>ðk#crÎÙS×7|°`tXÜü pÐzmh÷fîºïtoÚZ¾UEB›Ö'âøp"ÚF`óVk¬ES‘‰)HÇ ¢3g§yü©³Ö¹3èö¹Ñ³ùÃè°DŸXò뵎ö0w¾ëö>¬Ï„+™Í¢ÎN¡ÍOëÓk}x Ž lÞF §Ï'Ùį‚ª¯FÌdTžýþ^~õ²Õ-xÝ-x¹ÙïÒ,øŒ‹Ÿ@ïõMQùæ$O>s–D—ùðÑ6‰hÃÀè°8 üp­Q‰¹óî\sÝõúê¸PçfP§&|¿!ÚÚ nß…h[5™ˆOæ¤ÒYž~ö<¯¾>a¼uøØÈ˜|¸Ùïаoµ `tXü8ú´Q“]¿mk?øþ»èìßVò^™ˆ“½r ™ˆ7û5|T€Ò?@pË rD®©ÈøDnõ¡Ž çxè»§H& Ö€ü?Àom—`C@ÎäÿcôÅ;&œ8±ŸÛîzGée¹ªJvjmn¦Ù¯á£ ˆ@eÛ½ý™LÎBb}T–—S|ëá7¸:iZTøº5°®]‚ C9“ÿoëŒòh$È}ユÝ×-¹JOÍ¡M^Ff«J~飅 ´wؾÕ ^fã°r¹àhšä™çÎóüK¦å“èqGšÝ~¯°!`tXü(ú³É¿­‡w¿ïn:úíÇõe*‰:qÉŸ²»^ Jÿf‚[¶ëË’»¿92&«ÙÍ÷䓬w¿ü–l»7Ýx€[î¼½¤É¯ÆæP¯\ò‡õÖ!D$Jp×^= Ž]‚Ï?32&ו¸n `tXtÅÿ£< qÿ73t蘽ɯid¯\B‹ù3E×5…Àö]…Ø€ÌÆay¼0•¸„Kð5à##crݬ×^—0:,‚ÀÿDOÑU@Ow?ô¡;èÞ²»ôû2•${é2å(Ÿ½u¥·Ÿàö]ºK ¦‘Ë + Þ:;÷¿suufç“À{GÆä|-Ïk5¬;Èí|ûwXVðmèäý¼‡¶¾í¶÷ù&ÿÆ…îìADÚô‰CËõý r¸<cìÁ×H§ s>^“—›Ýöºß}=Àè°è¾Üf”ïÜÑË{~ø^BÅ7ù&¿Ð]‚m; ômÒ3-ëéËs˜žYækßx•x¢ñ": œlvÓëÁº!€Ña± øpÄ(?° ÷½÷Ñ¢$>¾Éï£JOÁÁ!¹r2«¹|eì /³À{FÆä3Ínw­X0:,Ž¢+ÿN£üºkwrÇýw!BÅ y´ø Ù‹oùSy}Aiï 8´ 2~R±Âµx"ÍWÇ^ef¶0t¸üÈȘüf³Û] Ö<Œ‹ÀÀ£üÖ[ösóï„@´èmi‘ìø9ßß÷Q"%¸{?"F&¦!¹:4V{ð5cBÒ4º%ðP³Û]õ{®eÈm½õ°¯ðBîºãÇn¾ Å;Ö¨±9Ô‰‹þê=!Ba"ÑÜ\©Â5UÕxð‘“œ=W †%àî‘1ùýf·»ªw\«0:,ºÇ€ãFù}÷åÐ 7C°¸çWg§P¯®ùÀ­B‚†ö¡´w ã“zF⤔|ó¡7Œ$0¼sdLžnv»¢ö–®¹œ}_Æ¢üï¼ý×?a«üÙÉ˾òû¨RÍ’½pmyѾ«Ád!÷ßs˜ƒ½yÑà[£Ãb{ j ÖŒ ø"p—Q~â†]¿õæâ€Ÿ”d/_@›™rü >LÐ4²Ï¢ÆæíÛÁð7( ߌMyÑ^๠dZkŽ€Ï4 _³•·ßu"lÙlSJ²—Îùcü>ꇔ¨—/ ÎÏ :vBpu I8à}Ã×ÒÝ]°<_ÎíÙÒXS0:,~ø—FÙî¡~î¹ÿvD¤¿¨|vüÚÒ‚Óê}ø¨õÊ8êB ѱËdno óþáëho+ÈÛ.¾e±f`tXüðëFÙ¶­Ý¼û=·£tl)*Ÿ½r mq]L×öÑbP'.¢ÅWC¦M_{ºÛxﻯ%.èüÐ-Ö–Åš €Ñaqz&ŸúzÛyïûn#Ø=XT>;uÅÏÜãÃ;ä]ËdZ'êÒÍ ßŒÀêÞ†?;:,~¡ÙM.…–'€ÜXÿmíèˆðþ÷ž Ú?„uUŸ:76½®³8ùhhêųȬ„vsÐÇ`/÷Ý}Ø(ú½Ñaqs³›l‡–&€\Äÿ¯BÊE¼ûþctmÝW´I‡¶8ze¼ÙÍö±A ¾" ó.Eû÷ pâxa/Ù0ð7­82ÐÒ€îóßcÜ~ë>¶í7Ea´•E²ãšÝ^ 2“&{á-Dx hÚù­7ïaÛÖÂÈÔ^à/šÝ^+Z–F‡Å½èÛ:°w÷&ŽŸ8Œˆš#þ2'{éœ?½×GS ¯*=«Ï0ÄEðÀ½GˆFCyÑG‡Å¿iv{hIÈùýml_Wg”{ï¹Ñaö·¤š%{鬿Ÿ¦B‹¯½zµ(ÐÙá]w2Š~tXÜØìöæÑr`˜égòûx×Q¢ý»‹ü~uü2ão½í£ùÐæÑV2Eñ€ÝCývñ€îjë÷-GÀow·ßº­»‹ý~ufmy±šº}øðêÕqPº+Åö£§©o:ZŠF‡ÅÝÀ0Êt¿ÿP‘߯ÅWP§®4»É>|˜¡idÇ/ Ú·UŠ|xtX|¢ÙÍmÈ­ðû3¬~ÿÝGôàŠªŠ:~ÞúùhIÈT’ìäDÍ9(mâÿ%—Ê®ih~8h¼ëîCDz¶›¦[d'. 3éjêöᣡÐbshI 1ÉwõsíÑÂìÕà›ÙΖ €Ña±ø”QvèàVwnAX*êì4Ú¢¿ÀÇGëC½2JñÜŸÛnÙC[›ihðÝÍjcKú<ÿBÔ$rûm{¡}›žã+™ˆ£NúI=|¬hÙ«Sì2‰#á ·ßºÏ(úL³–믢>Œ‹`ÙÄãÖ›÷ÐÞ³l_æ{ø~1D[Á[?hë­«ma¼°[nU÷ù6Ú̚ɂÕPÈTu©@{ °íè9,Þ8y•‰«  ç´üwè#` ESsŽ‹à  Ù<Ðɇ?x3JÏ~PVÇüÕ™IÔɉ¦µµ•ºýÜðѦ=_ÆçIýÕ»}r.!nFHóõÜÜ ó¥çÑ4 ®kt>Áf»¿ŽAù…€;ßyѾ٤ü2FõWø•„Ø|¸þJêy~{¢ský­WH‰6¿R47 ¿¿ƒë¯Ý‘?ŸitÓšF£Ãâð‹FÙÑÃÛÙ:hø›÷sø—Cf¥Ù-€t¼þ:Ö1´ø Z:T$¿åÆÝttF înd»ši|(|‘h4ÄÛoÙ‹h3÷$Úâ‚õ¯™lò÷‘2½\=ëÚÌ<:M²P(À;ßn þÁè°èªªâ:Ðïî0Ên¿u/‘Îót_MÓ{eÑl©%¾…V RÍ¢.Ï_9°o3»v¬ÞÀH£ÚÔ, àßO6träж¢™SÙé«È´?á§"RM^Ñìç¯!h‹‹Èl±ÚÝñŽ(JaÈû“¹¹çh8äòû½Ý(»éÄn¶›†ýd*‰6ëçòw‚¦[ÍvAÖÔ¹D‘¬·§ƒ Ém°d¿ö ͰL‹}úû;Ø·gD7™?Ò•qXÉ!š®€Í~þƒÌJÔ…âÀí7ì2Î{û•ÜúOÑP·cYê{ÓÛ† E„Vƒ#ÚÊ"ÚÊRµÕo\øÀšƒ\V‹â&}½íìÛ[pƒ·?íu;m˜zÿÞž6ìÛ\äûkS“ nÖG³°ÙÏ_ƒ"ŒºP|Ä«ç7Êø†-|ÚÛÃú¸¸Ç(Fñ}ÿZÑT%ô  vˆZ¬xK‹ðïG‡…p\gðœF‡ÅfÀ4¿ùm×ï$PáÕd 2•D[ŒyÝœu ŸÖ*j¬Ø ص³-› ±±cè» »ŽFX?ŠaÎ  pôð6}ʯa{eµ_h¢ú.@íh±Ù"ñõÇLßz l|Üx²oÏ&Âá`Îü×!Ó)¿÷¯ÉæÅNdŸ½.jGž.ïÛ;@(Xˆÿ}xtX´UU¯xJ£Ãâp“QvèàV@ B«Á?u~ÖŸõW'šÖ 79¹^ µÒ2ü Œƒº€vû¹^[¦Þ¿½-ÌЮ>uš~,ÌW]±3š5ç›ÿî@´o² ‚ºf‹ñôãŽ+tÏ ·Å×ÇŒ²ƒ6#„0™ÿÚÊ’ŸâÛ4K}p 0r9Ud ïì3& ¹/·o¦kðÒ¸ Cº/Ð!"æyÿ±9›°Ð,Eô À5ÈpOQ,L8´ºJ0¸šüÑK0™+ýý lê„p÷jªoMC[ŠÕPµ+šÖûàD[êlq0ðÐ5¦,Y®ºžÀè°h>d”>˜{‰aÞÿÒ‚¿­·[ð]€µ¡ PU“¸¿¯Í«ùøè°¸Þ­Gze|(´XÁ¡ƒ[0¤üòÍ÷àÇÖ B]¨ó3Eb‹àÚœ¯àÇ';wôÒÞÖ'ÿävL•Ù¬¿æßMø°. ¢Ý¶™°®9°Å˜2ì£nM vF‡EË´Å}{r+þ‚«iδ…yìßEÈôrssú+ÝE0ж¼\” ³-bÛÖÂÜ™AàZ7ç…p`š±´kG.ãih5矶à›ÿ®BjzvÞF?Ö·\‡ˆt£Í[;{§w;­¯¼ €{Œ'zztÓ_t^j™ð7’pÍÈÎëOv‘nÝB¶`çŽ^ãé=N«+/ÀÄLÖ ¶†ÿ䊟ñÇ 4¥7ö-×!¢Ýú™ÅEÞº¥Û¸6àÎÜd»ºà*ä+Üf”XËòÛþy„&(£Ÿ È" „Š’ã(Š`û¶B x[½rÛx6 ò€0} À4Üéo â D¤Ûv…ì³PwÀm0ù%=ÝmtvF@ ¨ïŒ*³dÊ_=æ L2½ìoÚê"ÝH°ëޏM&FÚQðÿW·Eö{ïÐp À÷ÿ=ƒˆtê.€fž¸y ‹H8˜?ýÑa¬ºr\#€Üަ¦µÿÿ_YÝàÄOùííûC€"Ú’ÙÅ «i;›ëyŒ›À&6Ú•'Cê/¹ì½‚o¬3£¶q7ç¸I¦í¾{{ÛˆFs©d&L§<øR>€ÆÇ|ð¢R†ƒÞñÖ 7 àˆñ¤¯wuØOt@‹¯TW£êà[ë ¡(re©(ÐÛÓn<=RU¸I‡Œ'}ùF Ý3ÉDÕ•úpŽF÷Ⱦà1r+g­z *tuëCõ$ u…rî7Êz{smR ÓÒþðŸ—htv^€·ù¡s›ió}=è»Õ·,€}X€ÀLúà)²I=Koƒà[#¤€fc9]làšZá² ú @nPJ?ùgÐP¥ô§{ €@™,¶zÍpÈq¸E‡'ÑHH$7³d:í¯ÿoJ¾à9D° ™°³LnkYFvù!@úocÐ@¥ô]€ ±µúZÌ0@ò)ÀüñÿÆÀ'€õ%šV¤?íía}‹=­e˜Ø©@¾Ð4L)Õ4düa]ϑ׻‘€U7 /· wÕ¨›F‡Å&`À(ëµ!| !hø‚6¹-ôìæÐôº0à†P4Ùß³ºú¯À`)ßhG¾ù߈<[ÝQãiMsÜ €~« Éù&†ŒERÍz÷‘|¬¢QCs>4ù4“)º Œ§ýÎ*4à è² B! ø»ÿ4 ë™}h ò»h[Ö„C&èvTŸµzšØiò‰ óì¥ù½ÃÐ ßÜÏØˆœ `Ý. Š ËQ…Ô•MÄîÁ¡`€Õ=Krüâ§jZ- e ›Fª)ȦAM阥ì?!P}AŒâÆŸé…’ëDm\èPØô]j²Ü'£_’g/Ÿ††õÌ^Aæ×!dS ¦‘¹ßZw+2Í „¡6}c™P{î¸ }Ì:ǰL.€©Q¾ ÐpÈÔ¢>åÚ­ãJ?'v9}²1[’©i¤š.Žýý‚QD¨Âˆ¶¾\­u†2j0[æFåï[ ƒ¦!ÓˈHMÎ3{¦¹Ë¥„L™I@|»¨[mý:„j^"ßZÈo¦cç¸tÂ&¿D7ä¤ï4Éð˜d|¶ÙoYŒL™‰#Çuë ­O'ƒpgýu7 yëJÊÕØIápkX¦¯kb¥|ãm†0|x™\@ôìôö!­HFd“È¥+È¥+z ¡­ѹŔ¢~MÀà^IUE jÁ `ØŽTŸŠŒ´¤P j¹|¹|íEtn…hOýõ6Ò ;ª ÁPá4TB õeö­‹ @úy Ï'I‰L¬ÍíÝe2†LÆt¡s¢cÓj ­a °Út¤Á B&£B ÀôõT“¿¯o€ÁšÖ‚Ç S kß­Ë&‘±óÈÅKˆö͈®­­9Š`Ô'¥xÞž¶`¯I—Ý ÓV?™´á#Ï^ <‘£ ðÜXKæ%hªî¬L":¶ ºw´ÔÄ#i´fKEÕ$ªV°®kÚqÇ75=8gŽäZŸk¼âö„>ÊÁëá9_›æù—’ÈåId|Ñ5¨Ç D üÝ@X “6 ÖDn¼¡ÉHg,ã•RCZàCn¨iäü9O±¦€ÕBS‘ —Ю¾ŒŒÏ4»5« Äê L-ÔÄúÞZùPZ8Ȳ. ‘‰¬L#“1DÇ@Ý5–}Úz&€<Ô4rî,ré*JïDje«ùY´6:”6ëZk¸é´…´ŒO^!›D®Lë=•ºº^ÜsÝG&Ž6}R>ìÙÕø†Y=“–Õü‡"]kX\3H5…PZ0ººV‘‚[™.éë{M°¾s2¦O°ê@tï„@¨þJ<7“ËdC³»Ý¢.€š„`{5õù°ƒšB.O!W¦WÍÂð À³7ÏY\³ˆ®íˆ®íÞ s‰W…ÍHZKºRJTU#ü©IDÄwjF2¦+~2æüžôо,7èåµq ÿ4äâeäÊ¢{'¢£¦„¼•‘M†Òí,€ d3Yù=Õ”? X-´¬ÞÓ¬LéŠ\d|Ñ=èMû6:ä¡fóçË“ž æ?Ø@«XËVA&£ɯ¹Z.¨ø‰A*!½¬÷ö‰Ùº·Qó’6¼`E>PØÖ‹èroÁ‘aß; Ó"AÀ"Ócy9Eg×j´TªID8b›Û|ÃCjÈø,ry2ñúëËWë¡’ú`™È ·êä[׌Biš‡ ¢Å£ñ„i³Ýš¦ºAE³NfæãlÛÞ»*PSˆpÔ'#²ÉÂÌ3OæÕûÐH©O-ŽÏ ºwèKkX #ã³&÷ÏŽb1“>Õ4ûË ¸$€B çcEÏ,Addh© ™˜‡å)ï§ëzµZOMCz¹þzÖ;´¬ž6myÑ;„ˆöVq³D.N˜$"Z<’63YŒoÖÒ̺£s#cRZ‹YLY5…¢l`ÿ_M#/£]y Ù TZ^õÒër€—È&‘3o"gN:&N¹2S˜€E@&£²¼R°RÀ…ZšçÖ²§SÀñüÉü‚©¿ÍÿÔb.¨7%Ï­÷ðŒ|ó¿Èä"2ùºž‡ c3¢}äGÊVKé/±‹&©ˆD‹’¼ÆÌ:vfd¬¶Ì¬n@ËËI4UC1,"]”Ól]BM#Wfñ隇ðÜ€gŠê@}È&‘ — ãz6c%˜Û A SKº‹eÿo1ÿOQ#=²}"ÒíÂŒA é¸>ï>½„L-·ÜX½å t÷É,êó#c²®žÓmøð3ùM“\½ºÀŽæqÑÝ‹œ›.ºYÆgõ½Þ…‚ˆö@´WÿÍO—´ƒ–Õ£õÙ”ž}(›†l\Wx¿g÷±†a´Àwê}†`¹KóE t÷ Ù@RÓMóļ9/zf¡üfŽjƼ{ªë¢»xãË.úÿàî<FÆäUà2 ÖjcÚ8‚Tu¥Ï&s }å÷±>‘w•˜ÅY‰ e€Çë}ŽKóL¬43»B&•1Ѓþ^>|”‚]'iéLŸ“uOGõ‚ŠÜ€‰+Åq ¥ßÛí«|øXËPú‹S»íÿƒ7ð],ÓçÎ^,Î"Ø´ÕƒGûð±ö!¢m(]&™¦I×ýð€ró’_2ÊÞ:;ƒfI .::mW9ùð±Ñ(î/\œ#™* c'€§Üx–Wéyþ—ñ$•Îrñbñz»õÑ@£ˆþý({Þ‰2ôvDïî†íyç£4”MÅÓãOžž4žþŸ‘1™t\ax5ÿö¯ßÅ@0¯œdϳ_£lÚ—¼ÝËÞ‡Á(Á›~ŠÀ±Ø{gñìLõôƒ¨¯ýÙÿÚŸKÑ`(]=z@’©,.˜:ÐÏ»öú÷Í~“u¥¯,{ÆLN™¶ýsÍü 7Iá²é™e–,s”>N€W?ði”Áu×8öA‚·ül³_g]Ãnhü”¹÷udL¾èæ3½îz‹ØêÕ“6V€ïxeïoÿ¤kõ…‡_ÏÝàÃuˆP¥·8Yî)sôßÕÞ¼'€‡±$ =yz iÙúZééÓÓ…ùpáN"?ò9w}÷p'‘ùK?àÛv}×Ë1–– t5ôÑ5Wá)ä¶+25:O3q¹xf`p°ó®]„ÞñIOzkeïŽ}¨Ù¯·¾ ز½HüúÉ«ÆÓ‡GÆä„ã:¢Ñ·/XO}ïRqCúü™."pìk²îˆàÖ0h“œ~Ë´dþ UUêžÀȘ|xÎ(›œZdêj¬øCøV€+]Û\ ü•BàÐp³_qý  °uG‘øù—.]åyàK^<¾QãoŸ¶ žüÞÅ¢BJÿfD¤ÍQ…>JÃë@ˆö"ÚjÌéàÄÀ–A=U¾++)Nž2™ÿ£n,ýµC£àË€)¡ü剳3‹æRBÜÙ &­_ˆîÁuñŒuEу¼ðò¸qæßðGž5¡ï92&%ð;VùSÏ[m~²ÍÛ!óâ«d2Ãko\1Š>;2&ç½jC#§àý-–]L.\šca~Ù\J[VôárÑõ`qSž±®!íÅç/¾r™l¶°+ü7/›Ñ0È þ'«üI;+`Ëö¢ýÐ|8‡œ÷v…¥LÆô¤­>jF`s±¥›Ngyå5±þ¿#crªªŠ«D£'á¸`œ=?Ã’u#QE!8´¯ÁM[?KWÑ&ž÷¬~õÔX³_qm#$°sO‘ø•×&H§ I?ÒÀïyÝ”†ÀȘÌÿÙ*úû6#›¶øK…ë€úÚ?Ö_IêÞîÜ[”ñ7›Õxñ•ËFÑçrËê=E3–áý–éÁ§ßšf!V<ÊÜsПvZ#2Oü¡'®€vîQÔ×þ¡Ù¯·f!:ºlgý}ÿ…‹$“…|YlÜe/Ðp“)à¿eRJzôtñÇŠ¶ؾ«ÑM\H/“úûŸéâöæéeRÿ/Ü­sƒ!´§8ÁJl!Á /™fÇ~qdL6$UV³âÿ9+àêä"o¾yµ¨`pp¨(E’gÐÎ=FöÉ?t­¾ôØ/{`\Ïl´]ôöØgŒãþil†Ì½BS 7«é­òzúÙ´eOE!¸û@3š¹.þÖ§\ ª¯}‰ì³Þì×Y³¡Á]{ŠägÎNsiÜ4¢òû#còM§õÖ‹¦¥â“‹%·Y2™áñgŠ{¥·ßOR+²I’úv2þ'ÐjÈ$•‰“þê©/þH³ßdM#°k_Q¶ŸLFåñ'ß2Š.¿ÝÈv5;׿RFÁko\anf©¨`p÷þÚRZù5Mæ[ÿŽä¿mê Ç·iŸ$1zÙ§þØ÷ûë€ÒÕc›ôæ™ï7îõ022&ãŽ+v£mÍü0#cò46c=vº(iˆGlM(Ρ?Kò3'Hå_£¾õ°¾µº™êë_&ýw'ùg?€œ=]ýƒ|¬BQî-üÍέX'ý|udL~¥ÑͲÉÌ>:,¢Àk€iæÏ]ïÜϱ£ÅË$3§_C›ŸuX»²FÝ;ÝÛAS‘‹È¥ }f® ¸ïmïÿ¥¯¼È•«…Åp àèȘ<ßèö5Û ·ÃÉÏ[åO>{t2]T>´÷?*à²IäÜ[hçG»ø2vÁW~Øj«ü'ßœ4*?Ào7Cù¡`dLŽaÉ œNgyð»6ÁÐ`àþÃþ!- ÑÖ®Od³`i9ÉãO™§°Ì‹i$Z‚rø,û\¸8Ç˯Œ7º³›àN?;­…¢:p´h¿ M“|ë¡“¤R¦ØËÏŒÉtUõ»ÙÔf=ØŠ‘1y øM«ü‰gÎ1;½XT>°}§me>šàžƒ¶ù-Ÿzö“S¦¿åÏŒIW¶ù®-C9ü>ðQ i’¯û 2éâˆupß!?yˆ–B)¿ÿüÅ9^|Ùd;‰> ÞT´är| 0¥DYZNñíïœ**/‚!‚Žøñ-R~ÿòrЇ¿sÒ(J“ËNëö -E¹LÓÖÎ]˜å•WKÄüÜ>š`ÐÁ~ÿÃo4ûýŸ“/5»ÉЂ02&¿‹M<àñ§Ï17[ñgϧNá¡C×í¼âÃG=Pz7Ü{M‘\Jxè‘“Œ_ŽÅç“‹ÎjoÂû4»N‘[5ø~àeëµo=rŠ+WŠ7ªÑ6BGnð-®@é߬õÛL<{ì‰3œ9kÚÎ{x`dL¶ôJk†FÆäðƒèÌZ€¦I¾úÍ×™·™# “Àq?&à£.¶ *1ëô¹ç/ðêë&=_†™Û¯V¬)“W€ûÝf2*ÿøõWYYJÝ#ÂÂGŽû£>jB`Çn‚{ìÓ¾öÆžýži³« ð¡‘1ù\³ÛíkŽ Jli H$3üÃW_aÙ† ¾ÞŸ'à£*÷ ¸c·íµ7ÏLñè㦔iøç#còÁf·Û)šž¬Œ‹û€¯¦DÛ¢!~ø=×Ò¿©«ø&)Éž?:}ÕÙC|lLAhÿa”þͶ—_zå²5±èsüÿ¨ÙM¯ê5×2Œ‹¾˜œ³P(Àû8ÊöÁ>Ûû²—Ρ^¹äà >6B¢tÛÿí<õì9ž±èoçwGÆä§šÝôj±¦ @èñ?ÈÏ(‚?ÅâÒ(Šà{±oßÛûÕÉËd/žõS^û(@„ÄCt[š&ùÎcoròÍI“\Âg>ù ~A?D®%Z“ tÍÏ÷øà¿>À‡B ŸŠ2„ÜùŽý\{l‡m]Úò"Ù3o Ó)|ll(=ý÷*Ú¹ôÝ{¿ùÐë\¸8g’«’ÿøKßäwЕãïZ`‚5Cù޳⛎?}/wv„ù{ (ÜÓÛvqëÍöye6Cöì)´Ø>6 „ ¸sOÉ%åÉT–¯óUë²^5­òóÿ׃ü¹ž3 ˜Ž[UÏZžÊ(¾íù¯ßÉñþv¾, h•Æ‘C[¹ûŽkòuA½2Nvüœïl ˆp„`™dËË)¾2ö ó1Ó†=É•4?ù©‡ù ÅJ_ö¼Õô­e À¢øvÊ^ÒøÅ·³ww_‚¢.÷P??xïa‚¡ ísµåE²oD¦’Íþ><†Ò·‰ÐÞC´ÿ[˜œZâß~•“{¸8›à#¿õ]Ï—íùKÉZEïZŽêQ|ãùOgë‰íüƒ"¸ÞúŒ®®(ï¹ï›ºì‘Í’9wÊßh½B‚»öض£d‘—^¹Ì“ÏœE[ݶ W/.ð¡ÿö$¯â ·¯p­%ˆ e ‚©ïDñ‹®ß»®÷ä¯ wXŸ§(‚wܺ—ë¯+^Ò™‡:y™ìøyPkØU×GKB´µÚwÈ6ÊJeyø»§8wÁLþšäì«S|ð>Ϫïñí®·„kÐ`Õ/ëçS1ÜDøgoäOÂ>h÷ì½»7qß݇…íÍ@™N‘½øÚÜL³?“z îÒ×ð—ˆMN-ñ­‡Þ`iÙìþ©ßôýòIf©^Ñ+]oê¨AS ÀÆÜwÚûWM ¿u7?Ýå7±ÌèêŒðîûްyséµÚÂ<Ù gÉ>Ö”¾‚»÷—ÝCÂÎäHdøó?~–ߺ¼H‡½y‰2Nîk¸5Ð4¨Ðë;µª"‚u×àϛࠢn¿u/Ç˸H uâÙ+—@ÓšòÝ|8‡ˆ´ܳ¥§ôR¥L~)Y¸²Ì'ÿóã|“*|ú:e ·Nuöúõ”7Òýácü—H÷Ùµo÷P?÷Ýu ‘h˜R©$Ù güy­ E!°}Áí»Šòô1qe‡¾sªÈäÏj<ÿÄE~îKop zøjÊz­Ÿ %{ýªËþ‡;ùñv~CØÌ ‡ƒ¼ýæÝ;:Xr΀6?CöÂ[þ,‚ÒÓOpÏ~D¤­d™x"Í“OŸãÔéIë%¹”æŒ>ÍïN­Å…®å~/Y aà@ù=Ux;ùÇsä†müi@a]›7trÏ(5\º[0=‰zå’?w ‰Pzú ¡tõ”,#%¼úúÏøšÈòÜ£çùô7Ns÷zk×zózÊÔ«¿^@-JêTéÝ.çøÚÇ®çÆ¶ñoÖ{ÿƒ½ÜzãÛ·÷:þfreuvmnfCÎ)]6mAÙ´ÅñNNªªñÆ©«<ÿâxÑDžB©·æù£?y–oàÉ^Iy«-ç”4\‹¸J.™þµ–sÃU([G@ üÔ î<ØÏOG‚)÷-¶néææ»ÚÕ_v2‘2™@[œG[\@.ÆÙŒã{× D[;Jw/Jw/¢«Ç6W)¤ÓY^?y•^'OÛ–Éj\¹¸Àç¾ð_Kæð{©ÈÕÔáDÉ«ª·v›ªU\¯¬/\Ós?~œÛná§Ú‚ÅùŒhosèÀŽÚêhäÀ _A[Š¡-ÆÐ– ›­ºŽfCDÛt…ïêEt÷ Báªî×4É¥ñyNžäìùYTÕ>šV¹x.Æ_}î¾Ϙfò‹ çA¹ºˆ¤pôþP½ò6CÙ« @þ³k¹éøVþyG˜›+}£Í:¸•÷‰Ö¶i©\YF[^@&Èd\ÿ—N×T—ëiC´µ!¢íˆö”®ž²«ðÊazf™S§'9}fšx¢ô;¦TΜžåóŸ{G2y†t#WµIîàŸ'åkÕãF@­ »&¬Š:̱›ùÉ®·WúVŠ"ÚÙÇák¶²wÏ&Á®²PUdR'-/Ëd4÷“™ˆ`mC´µëŠž?ŽD¡ wÇ+ñ4ožžâäéIÛh¾‰,'ߘ毾ðk²0ÙÆkÅôªÞº¬V €F*¶“…j{óZË›Hä\óö]|´7ÂAE[7²ßC;ûÙ¹£‡HÄåíÌ¥Ô BÍ꿚 ùcUÕ³©Y¤”E@D ûÕÏQ Ç.#K0>1ÏÙó³Œ_ŽQáoR[JóýW'ù›ÿý*ÏRŸ©íT1֥ΆE­&€WPòÔ£x­fMÊïê¡ë½×p÷®îïq­¡ž²ØÔÁŽÁ^vîècçö‚!÷®ÙXZNqy"Æøåã1kÒM[$³œXâÁ‡ÏòЫSÌÒ‚½põWCD¶ÓŠ[‰êéy«éÙ_¨ËZ¹yÛ~`ˆû¶wq_8@éL”(Š`ó@;wô²k°—mÛº ÖÞ~®‰D†ñœÂ_žˆ±°èl±TVcnj…Gž»Ìƒœ#¿_µ æ¥â×SÞUÂð  … Àø-†räø6Þµ¹» å—°Y( lê ·§ÞÞ6úzÚéëm£§§­%ˆ!™Ì0K[ˆ‹%˜_ˆ3ÓB“¤æ<ñú4}åϧU4Ê/¦ñ  Å,ô†ãV"/ë¯øœÎ0¡÷â–}}ÜÞåx(€ý6´Ž¾=tvFéëi£·W'…Þžv:;#DÂB¡ Á`}!%d2*éL–t*Kl1I,–Sð…±Xœdª¶!JUci!Å+—xúkoòøÔ qš¯Ðt1Ö• Q®VTüšÛsã ƒoÛÆñí]ïr]P¡Ï•ÿ˜ÕÿB¡áP€p8; ……lV%QuEOgs ¯’I«d²î&¨’øRŠ×®.óÒÓ¼üØÎZ¢øÐŠÚ¨òu“T+x¯,­0 ZÇi;L×oÛÉÐõ[¹~[×÷D¸6X¥»ÐJÐ$É¥''WxùÔ /?z3µªõ÷NªW¨ü=Õ”o˜b;mO«€—ŠævùjʹE$ùkU-QVÊ;†Ø³¯}ým v…ÙÑb0d»"pyܰvHPSY¦&–ÒLÄ’\¾´À…ºÀéD¶d޽RJ’—Õ»r®VES­‰–˜ ÔÄA»òN¹šzÝ(Wé]ÊË– ((G7³y_;¶t0Øe°S'‡í¡ý¢DR“:!3‹‰ W–Ó\^H11½ÂÄÅ&^™äJ2kêÙ¡²²”’UÊ¢ãÖj;·ËUSW5VBÉò­DàîŠ=¯zk'õÕ[U^£Ž2Ø\§7J´¯ho„ŽÎÑŽmm!Ú¢AÚ¢AÚâ‘mA…HV’ɨ$RY)•D"C"™%±’!±œ"±˜"1— >Ÿ$•ó×Áüǘÿ­Eñí®WRŒr×ê½îŒgVEË,‚†X^”s[ÉË=uPåqþœçXdØ\Ï£Ô„´¹.Kœ—Sp'ǵX n*«Z® ÿå¬çæ°6Hä¢B9iùu³\)”»^îšõ}¬÷iØ+—õ{›ëÂÁ1“Ýo¹c'Ž+Yå®9U|p®8P¾·-%wƒ8¬ßÍ­r¶ßÄ´`®€”Ò¸þ½’â•*gT¼jÊÕ¢Èå®WRòr÷Ø)ºZËË–S|pÖÛWR~'€SÈWCÕ’ÎkUäZî©æ^\.çJrI/,¤”Ò0*`|¡Rp£·®t½ÚÞ¼”ò—SèR2»2¥®[ôòÕ*¾S+@:<¯æ·V«*+]¥:jUäZîqƒ(UÎ-×Ý04܈F˜ìå®WRh§²jÊÚÝg׫;Uv7Ìýz\;Y9‹ Ôq5=¿ñ¸¢¨†<ªuJ•uÓª°~3WÓ‚{F9WÀNÉ5V‡ðjé­Ë]/§¤J…:­u8•UkÊWòã8'»ózP­òçݶ ª=w˲h9”¼æöÆ ^Zõ@©ÞºÜõr÷Ô”+W¦Ro½VŠ j5÷+ɬÇvçÕ ’âZùßj  Ô±[Äà¤L=Š\Ë=žl æ)@E°S¸üu7{x§JŒÃ2¥zôZ†ðp Ãæ:8Wv·,€RŠ_îš,q­V(u½ZwÁz^©|­ ]­5âúdŸrðœ , 8QØr2£ÜØÃ[T8¬·œY_M_éÊ+»—QþR²RÿÕÊœXµZÆknYµ(¾“2®Y^nÞ@ i"ltP®Ö¡97zx'Êí¤··#¨Låä• ÈKYÍv J×KNÉ£pe÷Ÿrhä‘"tK¡©²¬[=|©råzøZ2'r·QùïTæÄJ¨•(m!T{ŸfSÖså‡&غn[^ôð¥¼TP¯T:¯—ì®Ù¡R'}ÕXF¹Sk ×Ák+ÀzÍ-«¡Hî¥Éo…§Ûƒ;j@é½E¹“ûê9¯tL…:*ý:1ï«íñË•u ²Â¹QæÔ-¨Ç*°»VA¸¡ø•ÎKÊ­M'€BCJg²ž{­Øn‘uü–’U*K‰²NåV8ñýKÉ’€¬šßFZåÊÕJÐ sß-CPd «UL'ÄQ鸖²Ök¥Ê–*‡Y©2T•“WB5DP­[P-!4Ã*0W'°+Ûsß-E…FU&¨]±½ 7~+ɬǕ®áðZ5¯9u ªQþüq½Ö—VA¹û[JñóhI(4®4ÝPv'Ï¡D½åê³û-U'ÊÛ;½^ò—WóGáTñK—»^¯›P+TS¶ªóVQü˜W+Ö5½ìêRD¯ˆÀ©¬”òºåó{¥øV8Uz«ÜI0ÐNÞˆ`a‘É¿žudC€éÅí­ƒR¿n éÕê89¯$¯tÍ d ×*¹õ˜ÿNe•Ü„ ¥ðVlX°¢JB0þZï+U¦¹Ýs(sN…ûÝ€“?§Šn•Õj䫵Œ‘{—?ÓÚ€O%`Ikî–+àDnw­Ry”wÕÎpcŽ@)yU¦¾ÿ7¿ Ÿª€CR¨t­TY'ת‘•|*_»š?7'•»æ”|e¯€ÿ4Åb®æ%tEXtdate:create2010-02-20T23:26:23-07:00ëdnX%tEXtdate:modify2010-01-11T08:57:03-07:00F昖2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏtEXtSoftwarewww.inkscape.org›î<tEXtSourceTango Icon LibraryTÏí‚:tEXtSource_URLhttp://tango.freedesktop.org/Tango_Icon_Library¼È­ÖIEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/scipy-logo.png0000664000175100017510000000130312370216246027555 0ustar vagrantvagrant00000000000000‰PNG  IHDR6x-ýsRGB®ÎébKGDÿÿÿ ½§“ pHYs  šœtIMEÝ0+ZùßÁiTXtCommentCreated with GIMPd.eIDATHÇí×Ohqð—š,j³Lc»˜.R24¹¹Qäà 'w9Ȯ܉ËKÙA“¶‰+2E-;ààÏÖ‹ý\>O}{zöì÷c¿†|ê¹¼?ï÷÷ûy÷ùþ{øo´âžã+¦1†ÞÍRœÀ0>â&0‚ ¯’û”ä¦ðgÑ”ð†"ÿ)æ-Š®à eÀ¼-˜¤¨,¶a´DSùEcé÷ ÍÁÛ•àÇf©)3ß•} c+–`¶ãfÁ[1šÇ8„v,ÆJìÇÀ,Ì7…~,ðž$7Ø“jºã¶U±dñ&øWÂL5Q­±,öþ*Áv'ü9þ`¾[b_TÐYEÇ“N5Ô°‡k5Öø·~?ðë ¶³¨[p#O±iŽ‚{¸ÆÃ©VcËÿœÃ÷>ÕeÝ‚¼Žä ú ZŇàµ×ÙØÑÀ r"wº¬[Y´àrË&ëÅŠï{äêd¬5–{¶=hº#7Š;³u+q-1ð2NºüAÓ2ÏÆŠ¾‹%ã=LxCµ²Bx5ÁG뮓±‰XjGæoo¢éª±!ü’`ç»Uç=ö;cÎm!O° ñtªàäŸnìnßkãPhÄÜ aŽ&´/.ÎæÐvà@hÜXÙ~‡u9þ¢x0ÏÌã[±.ÆNÅ}ñ>–Ùd=XU¢ÛŒKqN%·ãZpcÿ\üÌ· ÿJ6÷IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/scipycentral_logo.png0000664000175100017510000000652212370216246031220 0ustar vagrantvagrant00000000000000‰PNG  IHDR!Œ´]sRGB®ÎébKGDÿÿÿ ½§“ pHYs  šœtIMEÝ)$ðÙiTXtCommentCreated with GIMPd.e ©IDATxÚíyTÅÇ?»,‡ á 5 ñV‰G@¼‚е#jÅ"jÚ3DÄ3e¢AÚMaÅ$bX‚rVTTˆåˆš GD@E›?ú7™žá½÷fgwvfç[õªÞô;úõ¯»ý»ú7PB %”PB %”Ph(+‘ H ÌÀÙÀñÀáÀ~ÀžÒÇ[/€ÕÀ?€ÀL¬þWÀ{jêôV—Åx砫ߎÙÖšŒu×µQÛ½ž­À×ÀZà}``±zmú~pHÈÕÀ¾±ë‰B㨨¥‚VÀÀ  p Ш6«€€—„P[² L08è t:-¤ŽõÀR`.0«—dѹ}±zaŒçvÈd\ü˜„Õ/‡|ÿ«Àä×:à¬þ& :Ü Ü#¿faõi1žŒÖrמrì\ÞH˜ ài”éƒÕÿ-ò% •€ÀPà!”y‰Õ²d.}ka.Í<’F—NzenVUÀp™üdâ·:G€b¥%ÊüXü œ|ØCˆò-a8ƒ€»Å(3«}' 7p5P2 Pæ°€{G{ç€+² €‘ò«¸9âsQfP¹4v ÜÞDåÎf2fæ£Ì~Y¾ãâ÷ ÍWËÓm`ð[àÛ1ÞÓ%Æ„ê'’ϯ}b~ï)y¢S`¡¬¾¸ø 0Ç+¹I¤²8ø•0S€?aõ;hØxøQ‘L´[Q¦WVp»U(Ssqj&‹|&ô: Æ}ìs@ïú"Áôöš ãé &‹J• —É„ìæ•®ÆƒEÔk/’RàûÀÏE_ ÖÇîjQâÚÂ*”ÿž6ÀAÀEÀlï¾6ÀT”ùV-RÌò\Tz\)¿¶EZÉ•é¼&Ò^± ¡*5oÂLæQeâ` Ð9â½æ«c}1*!!ì®Äê§žÙ Çb`‚ˆvc#LŒaÀïÓÞ3x«·<±VŽy¢«%ROýÂÙ’>–ãY”¹ÆÓ_»7wy÷ÏF™×¥d$Ê<ƒÕQìC÷{}0«WdT‹`†0á ìþ Lº­¶í€®À±ÀùÞ·Æ¡K}ÛkŽnîÌQ?–e eM½¶3ÕàÜøÐ¸QÎ œLŒQË%eˤ®öjÒýùd0¾ý`\s "äJ`H†Î<ï•,z1Âëyg nXX=NÔº„d¢RLRŠ©–ó#€s€)hr¼G·/{#|ÍøZ$—·€áXý~ÀµÏäx ‹2Ý©ª4%’šXHpìÕÀ_P¦J3CTñ¨Òoëy÷°¿,&©¶.eŽÀêòeƒ9Â;Ÿš³œ7ê1h,NˆÅ\ò'½óî(Ó6m½,êd£"¼ÓŸà÷aõçèxr-6—É@ÿæ4à—`õ!›‹T\¼ª’Õ;_†\íãMƒqžÁt¼š6Ó¥òÅ`üI“Ë‚ëq.nD\‚Õ lX¼a ø¶˜JaaÌ✻œ·nl„o¸µ–o»«·M7àÂÒÑ«–¶ –Ô¢âFE˜÷è9…Æg0«½óSs$½T×y%6´ˆ–#l XiÓW¦jàÍŒRŒ[ïóJîÈÈ”9€pWôð¬boòÂÚ·‰Í­XÑ6¤|UÄyÕ1Ä\°PLoàbÈÒq0ÊTæ‹ÁÌðÎoA]ÑŸ¤+z{#Õû£ s€Mƒ RÌ)(sLÀ=Wã¼T }ù™ˆâpª#xÉ+Ú§1eŸ³Wé¼ò9Q—îÀEÎ©Ê 5ljcP“|ó°IÎ[³PæÚؾùTø\vnN¢óƒÞù¬^¢_Ï"Õ¥>*måi ÜᕌÄê(bq˜×ajO²æÒöaÀ7MFURæH’QÛéx*â[. )¯ 9OeNu›Ó±PáMŽ•(3T>¬Q;Ž2wU]¯>|«øË: Z]ûb†'F3å|ÊŠÕË<†“`œÕ3#~E÷ò×Ñú>º›·™Ü¿en~¢*Uaõ{ÎTZ7­îz«çGxW×g)V/õ~Ï!ݼn{Ë+ -Á€Õ/Š®¿Æ+í L– ÌObFªäÿ³Æ^¸àÃÄß‘Qͳú%ܦ}GÊ»öǼö‡›c|I˜kzuO;Ÿ=œAUª(À±SóÿÃIhïã¼GAÌåmQ£ ,srÚ8ÜLÏ·šT0Aæà\ÖãÚáÀÓÀra4QÄ,»Áúå(ÓeúÊÄ€s½;îÂê(ŒrtŠ8«L\Y+)›ˆÕ‹b|Ù^!å_…ÚàT¥ËCT¥Þ·Wi pr ÏêÅÔ£LjÒy eß*éðX}­0• ¤nè*ŒfÑn{svG ï|K#íàÞJ³ç:/z²/9ŒÇê1'ÌL\P[b\*¿·ã"Vã`gHy뢙fŽq‡1’ÛeÿU±`nÊ ¬‚ÕÑ ezËœLÇÊcÿtoéè@­–gèô°z˜è·_&^À\”¹¾–7ø\¹}†u8Wð•1Ÿó¥˜ëH>–Eá†b1`,ÁAb…«*ã+`I[]TÄ‘^À꯷}6ˆš­ÃÜ™kPæ^Ñ#¯g+€‡Q¦ V…º¯n ñ¢óÝùë€E¸TÎ*ÎÄê(3¨Lc¸c²ø¦õï<¯$nªŒì%Œ²¨cÊ\¼ -’à‘èš0ƒi‡3j2—Fò$:“ÄÐX &y-(jû”iU§œ3˜äX\…2O⌟ #îÝ(ó&V¿¶›è–L†ÓOԭƆ¾õK2ZVªÈ2±ÐR\Þ”tœ<[T2ŒÕ¢Ì(àw!ªÒ$‘¤[7òv”¡Lp(Ξ90D"ùçYÊ„„§7yeâ~a\Äçò§"…o‘0Œ„¨_ÆîÁ¥Hàš¬N·âg›0kvHù…(³wRÎZ¥©Þ¹ÿkÄu|&Á^2€(sVÔ£ºà¢ú&Ayˆ··õ<Q¦]Ú]ÕÞyW”9›²AuHyKà¡"dÌ5¸¼ ñý$`ïkÏ6a›Bî¿ÛÚTõ¨áÑ¿uÁs¶‘0˜„h–D°oÚõ·pI¦¸³ˆ u 9@?Âå>Â%P­Û|KµgỨ÷¦ötg‘Ìz˜K´¨'Æ•3“nøÛ˜FÔ]¤†E]”+nÃà®Z®A™§P&š§N™cQ¦ºÚ<.MÍ.Õ/l³ïUµlD¼¸¿©^½Iu•&ÎðÎ7ÿ ¸g"ð3’áÍ× Ì&ඈûpJpÌz.Êüd&Ǩ¹*„Á$þÖdlNÇŒ_‚ B™eœ'«à Q} ¿»ãÒ Ãmˆ²~O-•­ï‹$ãaNÞE™é¸ˆÃ7p.»/p.ÈĪÛ—G¶GIŠÑß§ŠºÙTð¨Ø I{Fà ·‡§G(7M†ùûXà]ëSdLf5.i÷Ä&Ã^’^¥MEÒž•„uÛH2ï6Ȇ%h!Pc¯s+©9Ÿ|'»´ë•Álùl n£VŸÐ>ܽ‘ŸˆDòSà“˜õ­$5;^S–d¶`õPܶûÙY¼¡†B3žZýoâí@oìxð(ìÁ(s®He9P|5) õ’NÓW‘öÁÃU‡áòèv&™Þïkœw).hh*V˜Å@Ù<)ÆÈEU:Aì3„ƒoÉi™H<Óq «v–¸K -çQæ{Òw'ã"§;ÊQ‹%ùRúrQ}«eÂUi`ôÝ6”¹ðü¹šÍÀÇf² Úœ&‚DMç"RS¹–PB %”PB %4Qü«»µì&´Ë„IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/person-list-icon.png0000664000175100017510000002607012370216246030705 0ustar vagrantvagrant00000000000000‰PNG  IHDR  ‹Ïg-sBIT|dˆ pHYs.#.#x¥?vtEXtSoftwarewww.inkscape.org›î<tEXtAuthorAndreas Nilsson+ïä£tEXtCreation Time2005-10-15 ”W IDATxœí{$[^×?çdfUwõs¦»§{^}3s_ûrAX]CØÞ]è\wqYY Âå%!8† ®±òÒ :PCp ž†ˆ3¢ô*.°ˆ {÷rïÝ;sg¦{ºgúYÏÌ<Ç?NfVfVVeNÏtW×ÜúNäT>~™y2óÛ¿Ç9¿sŽÐZ3Äý‚ìw†xccHÀ!úŠ!‡è+†¢¯pˆ¾bHÀ!úŠ!‡è+†¢¯pˆ¾bHÀ!úŠ!‡è+†¢¯°û]€AÁÕ•Êià—ãØñ†#àÕ•Ê8ð·ïÆû\œ8|à_ß·z­v§ß…9.¼axu¥"o¾8ÓçâôB XþÑêµZµß…9j¼!xu¥2 üð®>åAððþÕkµ?îwAŽ}EôÕ•Ê[€ße°ÈpøäÕ•ÊWô» G‰ÇZ^]©|øÒדÒÂ.`Ûå’C¹\¢\*Q*—pl Ïóh6[4]V³E³ÙÂó=ÜVå{û  ü“‡½ÐIÄcKÀ«+•?ˆÃœoÙ¥‘ ³§¦™™fjb„²4iµFüjPZƒÖ4=Ÿýj‹Ý}¶·÷h4jø^ëaégoZ½Vk<ÌEN;Ê? |èAÏB0Z™`~þ ³§&959Šm'½ü’ h É_W­žRT[ìÔØº¿Km­Õaï·•ÕkµÃœ|ñ8ð'€o|ÐóÊ£ã\¼pž'ÏÏ0R²ÈÐ:` IÙÚDTÁ/h¥PJ£´Bi…çj¶vªÜ¹»I£ºÏ!Þÿ'€/]½VsôÄ“ˆÇ*áêJå;x@ò9¥QÎ;ËÓ‹g-#BÖ¿"fÁ5ÚlE$ M0hK ´F*Ö¡ ’‰e4©í(ægƘžaóþw7ïѬaL±0B 2n~Ñ1-¨B2*˜me´  ~µ ×J©h»ÞòXßÚgksãA–o_½Vû±9á$â± àÕ•Êeàw€SEä¥esñâ¼pùŽm#¤ˆ(0QK\ ˆ‚ý?Úæ7åó©Ð‡¤K“0"¢Ùö•bs»ÆíÛwðÜfÑÇö1þà-þ¦Nž€WW*“çü¹"òNi„+—/qéâ,RJ„”Èx‘ 4a¨ÿ"Bèÿ¡“&¸x´}>­uD²6 UD:hJ_Ù݃7n­?ˆIÞÞ±z­öRávÂð8TDœ‚ä©Lð¶7?ÏåÅ9¤e!- K¤HKû$–%±¤e~-+X7Û2Øž/- )…¹NHh)±bKiöËèR"„D ‰”!Íý¦ÆK\~òÿmÏ335f>zH!,“f8Ô€1'P+…ï5QÊG+ß÷ÑÊ7¦F,!-ó×­Z‚D€&‘‰@ûÁý¤Dt´lqiqž—_ÓT÷ Õ¶¼ ø›À@VT¬ ¾ºRÀïoÏ“µìo{Ë \˜ŸFÄ´“ÑFm2Š !FDí{(¿‰ï6оÛé÷fVÇ|:¥ZH„,UFXv☯T‡)VÊÇ÷Ûuƒõ¦ÏK¯¾N«Q(axzõZmûpo³dü! OJ‹Ë—ŸŽÈ7…R cNS™0Ÿ(üæ~cíÖ(c²e`ž¥YäS‹Ð ß­áÖîѪÞCû­HÃJ! ®qEÌÿ 0Z¶X¼pÛ)d]§úMö©¯®TJÀg€§zÉ !8a‘·=ÿv诅OÆ5ŸŒùbݪá{õd4 Q¥q¢Å#^Ý¢T‡¦SJáûæËÁ.M …4Q°ß–IÈÅpw»Æë7o¢TnW’ðÌêµÚÍ}ŸýÄ jÀ¿Nù&§gxÓ•‹XÒ2Ú ‰”&4Z í£êÛh¿a4]¨ñÂÀIJZ.Kób·ƒ jW!Ð^‹Fuå5ÿ2!föSÍ/s§*œž-”¾8‚iû( ¯®T&€åÉY¶Ãå§.PrìÂD Ѩöš¨Æ.B#œ Ì®E¿‰cYí(7ªâ‰‘P­ê}ÜæAÌÇÍpò9°0;E©\)òz¾þêJåM‡x­}ÃÀø0›'tzfŽ…™‰dd+CÒÅ´”h¯Žjí·}˜— ]´ßJ‘N$"êlÑvŒháº×Ø£UÛ4ÁDX žÄHI2;7Û¡3 ï8Ä;í‘€9OÀvÊ\~âœÑt1¿]ÕBdþ´ßBµª ¿Ð’2ª´dP_hY1­˜­ýD¤c/l´#lߪãÖ÷£m +ÉæNU(JküÊ ûÁ@`` QO¶?›'7?¿Àé©Ñv• mó–ˆDµ‰tCÂDd²d톚¯Óß³bþ^Zãe›Ö6ñˆ™[·±‡×j¶¦ŸŽ%™ŸŸAˆÜO6Wä ¿@N™ÒO]œ>b"± •dà7v(ôc$³b­!Á’³Ãçë ^œp©?‚¨‚ÛoÕ¶ÑJEeë†Ó“£ŒT iÁ÷: 4~ O`rrЉ±2¤>|ôÁíã»5´VIßL¶}¹¶¦³Z0Ô|¹ø:1bÅ}>SL­­ú^Lf?›%ÓSSä= ¯®T*À{óäæfO%?`¨ cž ’8ž€0Ïq3‘ßi¼”oG[ãÅ5\<½+..úõ[U´ç¥öwbb|iå¶ ^¹ºRy>Oè$``|)0ÚKÀ)pjʘ¨ˆlá†Y~³ŠÐº­"mÙ&T¨Ýâ~`9§Í{¤Íhß&üéJ¥¸L°Þ¬íæö`±ŠVÉ „$þù<ÑÊ“•RbŸH­hÀwë ˆ("¹3$¤e™ŠìÐf&‘<9Ò¸$É”[ƒ¾ÛÈí¸dIÁÄD!?ðÝE„úA"àÓy³3Óݨ ÅQyÍ(±4~¨£A2ÖñÈ÷UÐçÃÐÑÿ± ‡¿QÒjöýóà»ùÞ&'*E¢á+ÅîØ_ Ï÷:(¥ÅTJ3„†Ú„Ó(·ID¢ ­>`["É4žÁì+?Êb›¬üð:d,Ìšî…èü^³ÞU6ÄhÉ.’¤p6÷B'-'èB™ø¨©Lfß­'Óë3ºS¢µ |?FB•êz™î\3Ö$¹Ÿöþ¸ö µªïµÐªwßÛ¦H RFu=Ñ^]©XÀ|/)-ÛŠ©Ý6£aå™\½°CQšDš/ÈPñM®^˜­¢Â|¾Ä¹íë¡c÷LiáH–¤æ‹,8à¹y~ ‰Î àÄkÁ †|={» iáØ2ô¶ûp(å'ûr$ˆ§b)Um²ù¾oˆhÀxú”!j\kv’1ê?’Q.ˆ2æä¤^ À± %³Ÿ+"ÔO JJ~Oó `Û6–mí.#2ÊGi¤¿+”ˆ £¹Š˜|<):¨ª ‘¥%uœŒ:‹ŒI-™èÔžòA£Nù¹E xâ5à 0÷/¹\v¢*²ºL‚é¿#‘é<ž†0dˆ¥O…Ýââ×TQßßd7L˜ø1ƒŒ:ˆ^e 5uœR¡A]‡|DȡޒVÌ”%?¨Ö-Jyy%S¨5D™È-@èt»- âD}@t»«¥Ò1¿0ÞY½ñfÐP`Ü) T,ndÿcÅ ð^ž@Ëu¢Ñ"ÃI³‰D)… ÚÖÖ 0µZ ¤ Mo¼é,ÔhŒ™ ÷UàªÐ«$Ùº.Qð¢?›ß+4ÛCî{ë7…€·òš­–!„0~¡™E¡•@ F¦7éï šÐ÷ËN‡Œj`t2JŽû…AÏ¹îæ¹}m!ò Ør ãqâÇš~l¨•¢åy”¥}d©4Ê­«& 1¢³$ "ŸOÆ}¿t[rµ’ò-£NIiMØÿÅTý´‡çhŸŸ4Ï*¸‡´ °Uhp¬ÛE„ú‰¨†Y½VÛzvU¾OËS‘æ µMÛLj@d%꽦|Sí«÷óãU1¾YW¾oz´Åö'®©c&8"§NFÊ*;R†|¬´Æ÷ ™à¡|„¸<Óí Ržë£F4Rk”¡”1´Âh:!$H¥;{Õ¶O¦cæ/Fa—«`à·#Üvdë·£àø’>[”ò„L'/tTVÇL¯¥Ñ‰Ü÷P­·ðò“V[˜áŠO<†€~9O`{wÏ7õ~IMhH褴F&‚ÁüØ'bºZÆ,*F>¥üh ÏÊÐ†í¡ØÚ‘pˆre’"yû;{‰óºà7V¯Õ Ùé~ã±#`³Veg¯ÙQ¬"Rh|¥ÒA8£f_lñU›\i 'gú¸ŠÕvh>?®ù:Ég9eœòXîÃ×›>û{ä= Rð›À} k¦¯R>wîn11~ )@IÓ'E0R©øBâŒLÒô\|¿ë«Ûîd„Á´ƒnU2ª]ÝNZh0N>)mF'f(¢ýÖ·vq[¹æWÿ)÷b'¥W¯Õ| 8×Õý]¶w>—nk)øNe¥I¶z¤Z9­"¡YV19?¹žl]I%±ÆÍ§ŒNÎjû=¨{ìlß/òš>µz­vâ›àB |!-*“sH+?¯Oëw·‹Î5÷ÓE„N Ž€«×jŸ~#O®QÛgkÇô0ëå‹ù¾B#)Ï ¬R2?]EiF¿C.î ¶G>mÿÄ!m‡±©y,»Øàö»-öö ÿ| 3ëúÀ`Ð|Àß™˜¦«ã¤µfcý.•EÆF,´ÖøZ#bù~‰Ñ³”*§i5vqƒy:²ºÇ[CÚiôYù}ÉŽN¹ÂÈøé^EO å*nß¹[t¥ïY½VËï×y‚0p`õZíSÚÌ€Þn«Îk¯¯ÓtÛHk¡±Ú½à¬òåñY°œîQ°ÊȆ‰zÏ…~`’|Òvœcd¼XÀà+Ík··¨U E¾üT¡ Ÿ $<Ÿ¹-òµƒ]nÜÞÂOBÇ['bæVû ¤Myl†ÒØ Xv»ž0JÃJú‰¡© g<ŠCZ£3ŒM-`hf‹Ê¼¾±ÇÞNá¤æAÚ@aPM0ŸnkQ[÷N ¹'»·s[å2¦z¶íB{Ì!@Xå±Y´òñÜ^«Žï6"Ÿ.³BX,»„]Å)U ¥×gaã^•{›ëE*~kõZm`ª^âH.-;‚ßRþ©)KæN©µfëî:Žm±0;ÞÓ†\‡ÎËÅrFƒca5Ž™)I‰´ì`â›Ã.Ž{» îܹCÁœ?vµZ}è›ö 5OÈÒ²S~øv0$™Ò’§ ¤°ƒ=afn ó“¦ñ ƒB³¾Uccýv‘|?6´bøðÚu77aã¤a`¸´ì<ü"±Ù‘tЛòœ°X(6TB&§gX<7KÙ99.°ç+^ߨåÞæF”‡]­yU{Q‡>Ì÷Úgð‹%)|×Úu÷Ÿ>’B=Bœ.-;àS@¡ VBò¿X!¬‡öü}óëÞ\GßÙ:ºÂÄôö¥ X¶™­É¶$Ò63z¶šš[7÷yíÆ¦àÛÖ®»ÿâ(Ëü 895±ð#&_™gRä"³h¿Ò2ëÎÅä¥ `?|3Ù±@ÄùyìË‘¶…´D´XÒŒÚPœ½0ÁâÅçÅÛ›tiÙùâ£,úƒâDhÀ¥eç}ìÇ`È÷<ç.VVl²«`ÅWæóL¶‹ç™NHn³ÉÖæ œû ÆjÑÿÇ΄šÇ>9Z ¦†Ø–Ä’Ë6¿aÑ5P¯)nßÜãÆÍ‹ú„7€·®]wwì!}×€KËÎ<³xKN™+W^è _‘ö³…™çÍ4›»lmÿ  jÓšÍ9E-Œc…ž´¹{Z±1z@S×°ímɶ6OŠ*€ÑŠäÜùI.^xY,,^~ìáPè;1}<æò„l»Äå+/pþÂ(i‹“®³,‰-ÅÎî vwo€PXV0´mI°?­¹;«iËŠ?2XSc_pší_H¡ÙÙ»ÉîÞm¤ þ ,e·g×LctLröüÎ?Sd%€/-;|Är(ôÕ/-;ßüx¾¤àÊ•çyò©i„Õ&\ÚüÆ'¡t[u–Û 2žƒvc Ú7¿a Štaµ¨¸]+UbÄš-SZÁ9]Âó<^þãM„Ät•fgaþŽS281Û7Ãaê¾æõ[ܺý'Eб1ůÁ#F߸´ì<‡@'×.Ì_àMo[Ä Ín]¯ÁÆÝÏàz®!AtR¥„ÙÖývÛD¼øô,Òo³‰º×Dï»±bÌÆš-cÏ`OÚAPa4Üæú[ëÆ­ˆPHA¹4¹³ÏaYN.Ñp°§y鳯°½s·H±þð%ýl®ëKSÜÒ²c?GòU*“\yöB;ÚÍiªuÝ:ë›/¢|)ƒ$Ì@”  ú¥›,Ã1£-¡^m0=3Ž5f£+¨¦Â¿ßBW=»MTÓÃRKÌødZ€'À—àK/Á³ QÒœ»2ÎÈx7«–!ÙþNi…¤ ´ eL®¯ÜÙø gçŸÃ’Ý»pŠàþã“‚ÅÅ'¨Õ÷iæÏ;÷à*¦¢/èW[ð·Ÿ—'dY6Ï<{™‘J1WÕuë¬ß}_¹O¥Œp*Lôk¦a šŽA+“ ]Ýo0{fm-©, {d”F½Å=¿Šk÷~ d@D! }4Œ® t¤±ïmì35= °€Ú~ß÷ÿÔ”QJ°$mî6Xßx‘…ùg{’0Äô¬ÍÅê%^~åŠTˆÿàÒ²s}íºûG…^ò#Ʊ!öû®"²‹‹—˜Kuäéb,Z!ùüÎLb¹ >¼lo[‘)TÊcw»Še lG`¿{õ@VD‹tº$ðË¿$Nû˜ec‹hÝs]šV⺖„õ[»‘ö3õ|š±óùˆße"ÃxK™…qæÏ\,òšË@ßZHú ÚyOŸžgñÉÓí¡? ´ÜëŸÁK“/.,B²é zÃ|äðƒK –-ØÝ9@+Û–8މ>›¦!I@X;\Hf¿Òn“Ú²t›ÜAåx½Ö4 Hxë·åe0e ýÀ¬m¹uîlt'a##‚óÎ2>>+ |ÙÒ²ó§‹>jôƒ€'O@J‹K—)•Dn Ñln½l>JÂ3ïX áDH [ÄcŽI[ww–* |ÏEU8!ñ"¢IçÛq­Ó–!9ëÕ†¹®-P¾ÇæÆ^P< ¨t—hµj¬ß})˜8¬ëK`bJpñâ%¬ü©]þ~¡Gc%àÒ²óeÀ[òäÎ.0}*éët{Ý÷·oÒluŽÚ!‹¥Ô†DDPÙkÙD$hÖšÜßÜÃqZûɦ0[DͲEŒ@¢ƒÔ2AH3•„íÿðÕ?ÙB@¤‰»Õ!wQC£yÀÎîí,©„€™Y‡ÙÙB“f¾oiÙy[ÁG‰ãÖ€ß' ¥ÅOæL޼ïjm‡½ý¬C™UÑzð_h‚¥MÔ†šÍûûìÜ«-'cf7$Vhvƒm;ò'u‡f”¶B#…æsŸÝÀkyѱHëehðŽç °½}‡zã ïá”.,àäLý€q•?–'ô¨ql\Zv¾ÈmŸ?³Àؘ|á©£ßwÙº÷j[¤—ùíABDXí.&“‚­õvwk ÿ/$£Ûg$”¶Ž­‡dmkLi >÷ÙMš 7ÊhΪ†íf~ÓRw·^Fù~"ÉÂø„ÅÜ™BZð«––Š>*§Ì|¥”,>ë{”z©ñÍÍÍWð•—ø€{i¿øº6¡?%EL#Ú†<Íz+–]Ó&j’ˆKjÓn#pÕÆYë2uGÞPÇ3ž×b3öGØí çÎÏSrrÛ]  —–)àýyr3³ ŒMt1¡öÓP¯ïRk´ìÉüxI˜&bšŒvÌ”ÚV[“™d‡  “ì0š–X•ŠH—+¶žõGÔ+ŠÿU«÷9¨ÞKîØ¨ŒIΜ)ÔÃáƒA—ˆcÁqiÀ/rkPŒY ¶»™–ã€ç~Ì8 Sëm⥉hNLÌß&4BjãÃÉPÛéÈ šx5Š€ö³ô*Ùûzjó˜”îß¿•)ßÎÎR*å$å =*ß'066ÎäT9û%Æ#ÀÆõfÛùÎý:ù10MÄØ¾Ä’µ?$uœÄ“3¶»/ï‡ôj¼Ì<¯Éî~FÆ·NüP“œ>}¦S®ï+"ô(pb8wæTPél^W¯ØÎÑ~‰õH ‹LmwjÂîKšŒ]‰/_r§÷Åšm•;ö…Ú/Ü·³};˜”»}¯˜¨„ùù à ƒ<Í#Ç‘piÙ™Þœ'wzf:ö×$aø¢Í}êý­f´„È4½t!^J &ö÷X2ɘ§»ü¡¤Ë=7s¹Ý§áƒXåý_öÚhgiA¿Åî~,&¥ýÂñÉ2££ãä@_‘'ô(pp‰œ˲™˜ ^JÆË 7îGëñ©üÎ*â¥5`üú)2ƸҴæÓ©ûÒ÷Î(WǺ†•wÿ=þÒWüÉ;>ÿüðì ïø¼óÕïÿ¤°‰·‚ÄßÅÎÎäYê=i¡9uª<3|Ù0¹æwúÔ4VŠ¢3ž³ŽÍXY«ïš8÷B›¾ç2l; Hf „/=]ÑÛQñÈ H|½n$L–3[0í›v¾Ëzyd‚§Ÿ|'–t(—§xæé/ŠÄ|ë ï£ìŒñóÿáoຠ¥¬]ßwi4ö™È,CˆÙ¹ÓܾýZÞ£}ÉÒ²S^»î锯ǡ¿(Oàôé)³ÒáÀèè¹n×k&>¸çÊX«Èä‘\‡l-ÔS >ÀBÎu3·“—XöÒ{X(¥xöÒ»ÂNL3qåÒ»ø†þJå FûÇßÉA5f%b÷Œcl¬ÌèHîÌLcëu¤8^ʘ¯$>Dø«c+‘öÓá_;(öÄMMó×k_‡ùŒ1c cIDATê¸ ~ûD»W|ýù+Ë“&—Å ŸÏGþêÏ2V9mºøí2T·;ßG NIPËõ¡€òxX)—–1 ·rdÔTv#¡FS¯ï·]- ž«æ9®" ˜"b® ïù€š¯ëõÒûÒ$Osì1ž~â¹TJ1?÷,ùÚŸgzò,*èã‚6f¸^ïÞFbr²’+\)"ô08j xªˆí´ë¨³Hˆ×oF_«Õ2ûd”L›¬qâÑI–BZðKæµbÏ’» \¹ô®“Ûk95½È7~ÝÏqêÔSø^û¾µúnT–n›(Ô/õ©"Bƒ¾PZ)eÒgéXÏmÓëj|_ƒaܑЌáO{‘1K«å¢Ó‘ub_Ö¶†gŸ~oçÙ9ËøØúÊΙÙç Gèh¹õžä-"à“E_ÅaqÔQpn:®j¿àCÄ2èT ¢AxZ®Ž5u‰(#‡Ž™åXfqC‚hñ^vécÝåÔ¬ý)ØöçÞB½¾W¸¡”m;|ù{¾kk?ÀÆÝOÓjæV*;Hiå¦0³´ìL¬]wlîá£&`®tÇTĪFÒYÁ¾ç¢µÆuÍNaæ]E=‹tØM3NÄàYÄ‹j|2GVåe!jt!]âüÔ¶ë6øÑŸ|O‡&OkìÌuµšŽ:;Ñjû΄e J¥2Fg2o Oÿ/Oè°è¿ +üc- i¡µ <Ân•"’k۱ЊvõãûÂóuçñ:cÉèILJç‡ûÛí¹‡³È=Cj=|Wá;ñ=P¾Æ÷4-7gfMv±Ášž,"tXµ̽¾ç¶ÚZ/0·‘é%è¨-$®kðˆF§ˆi9 &cE·dšã@>~z¸‘ÖL ¹šØ¡;öéŽûöÔ€=ä¤Ï þ8…Fùmëvó]¤Uèa e/GMÀØÖh0Fv°xÚhÄ\·ï2Áƒ«|.O`kë~æþfÓ¦B0ÿ&&ç:5 t%^®, è2Ïé!ßqNÖõŠì #µÝ RšÑJ¥‰„ö µa|÷ƒê~ÑëéP¾ÇAÀOç Ôª.ÕjRÓû¾F)Œ—'R051‹m´_œÎø@yZ0MÊØñ¬¥—¦KªÔ2¦ŽÅµY"ÅÔÔ4–å$µŸoüh/¦ñöw )¶pëÁKQÇAÀkE„îm%»6^›|¢]8sÊt-ì¦)ºjÁ.¤ëêþÐt]Mqù,Òej»C/ÄÜœ™PTé6ñ|ÏÑÍ]¸³»×íqüöQϺyä\»îþ6›~{÷î=â_ÏuU›|R ƒæ±±SŒUÚMÌY²CsÅöw÷÷2¾{M—y¸ÉéYþCbjržÉÉÉ(¨WáŒ13ìyŠf«ÆÁ^îà•¿ùð¥êãê÷ïójÕÛÛF ¶Z~¤õBò‰Øñg枦ätöoÍÔ‚éýiM]MnÞÒ“˜Y²ÇÊ¥ 3§/"¥À)µ›ØB3šd×UÜݸÓ”tÁÿ|t%ÌÆ‰! À«/ßÀ$(„Ñ&_¼EIJ‹…ù+fÜänÈ"LìØ‘C3~«.ÇFÊãœ;û\ÔìV*%ÛxãU2µjõb³FùÀÿzä…MáX¸vÝýðJžÜÁA“Í»ëø¾JYÍ™Ž3Â…s/P*Ÿð£ÁzŸ˜¸ãc§8wöÙÄlIé– x¾™DqssƒêA¡ê—ß êqÇ98Ñ¿-"ôÊ˯£´JÙmc¶]âüÙ癚œïÙèž‹4½ÇM²,8v™…3—™?s¹cnÇéü¬ZkšÍ&ëw¶ŠNóúS¤ 98Nþ8&¬ï‰ZÍãÖÍ›FóÅ‚nÒbvf‘‹çßÌ©és•Õ¤´™œ8Ãùsϳxñ­Œeg»ÙÍ­×o$ê{`“c"à±Î²´ì|?ð=½dZAëÐs/<ÅÂü,[æÍ Þßw©Õw©Õvi4ðáô©Ç!–å`[¶3ÂøØiÆF§(ú2^¿±O<b{û.wnÝe´Rèüc›_ø¸§iøaà›…®Ú$¼òÒ瘜¬099ùÀ7±,‡‰ñY&Ægc×ÕøÊG)¥ü`lÁ>ØÎBbÙ¶Uz03aYÏ7ÏW¯U¹sk“‘ÑBä«QhöªGƒcŸ)iiÙù&à_u;öîF+%Þþö7Séó„nˆ;·ðtÍŠÜÝl6ù¿¿ÿÜÛ:ÓÛ´†»÷¹yã5*M±YPÀ×­]ww޶tIôs²ÂoþeQy!çÎ=ÁÅÅJ凨ryœ¡a¿É«/¿ÊÖ½mìóðhíºûÑ#*YWô{ºÖŸÄhÃÂãü…'9uj‚ò¨(jZkxž¦QÓܹ³ÁÆÆÍ¢3§Çñ»ÀŸ[»îiÿ,ô›€eà_ø çNMÍ2sú,ì’À±Á.=þ„4SÎj|ZMÍÁAí{ììnán$µÏïZ»îÞyÄE-„¾`iÙ9 |xæ0ç—J#ŒO3>6M¥2´I Á,Df T‘­~ ”é·¡ý ¿oP•éy.{û÷ÙÛÝ¢Þ¨>Ì-þ3_pnïÅ£Bß °´ìÌ¿ ¼óa®#¥ÅXe’ññ)*•I»„p•¨”ÂóZxžK³Ycÿ`‡jµøð=ð»ÀÊÚu7;ý˜p"°´ìŒ`šþÊ£¼®iQ°‘Ò²l³H iÙ×~|ÐÏ÷ð<7"Ý!ü¹"øUàkŽrÌ—¢81XZvð2XÖrP° |çÚu÷ãý.HˆEÀKËÎ;Uà ú]–Ç¿|ÇÚuw½ß‰ãD"møõÀgsćèŽO?°vÝýµ~$ '–€!‚a~¿øk˜od<à1íºŸìwazáÄ0Ž¥eçí­ø5ôʨycÂÃh»_~fíº{³Ïå)„"`ˆÀœ×‹”×infÆÈ½O¦»Ìî«b¡œNö½ô~N³Þ>Â! ­?F¸žõŒÕ?âaá¤æÄ†=5ôø`·©ø5Â_M'¢TqÙ. ñ˜®ýVòJ‚p8Êda€sZHO×Lnøº‡}&ׯâwVQáygÞÔÝïEÚ¯0  š HPEa˜°P@†<14²r?#«“{2u$j»tbD±A{6Ü=·Q¤Ý<þ("q”Cµ’üAþ*¯ÉOåyùË\°ØV÷”­›šºòà;Å噹×ÓÈãsM^|•Ôv“WG–¬yz¼šì?ìW—1æ‚5Äs°ûñ-_•Ì—)ŒÅãUóêK„uZ17ߟl;=â.Ï.µÖs­‰‹7V›—gýjHû“æUùO^õñügÍÄcâ)1&vŠç!‰—Å.ñ’ØK« â`mÇ•†)Òm‘ú$Õ``š¼õ/]?[x½F õQ”ÌÒT‰÷Â*d4¹oúÛÇüä÷ŠçŸ(/làÈ™ºmSqï¡e¥ns®¿Ñ}ð¶nk£~8üX<«­R5Ÿ ¼v‡zè)˜Ó––Í9R‡,Ÿ“ºéÊbRÌPÛCRR×%×eK³™UbévØ™Ón¡9B÷ħJe“ú¯ñ°ý°Rùù¬RÙ~NÖ—úoÀ¼ýEÀx‹‰ pHYsIÒIÒ¨EŠø›IDATxí[ ”U~ÿ}÷ôÜ3Àp #Ž‚\+Þ +®Qw­¬UÄ2›MR1q+1¨»›Ôº[eʪ˜Úd7»1¥ñˆ¢  Â*:#0܇0€0ÌÙsõ}_ùýÞׯ§g쓸úúûú}ïúýþç{=ÉdR¾ÉÅòMOì¿'à÷ð gÀ– ¿òÄOÙÞý_ª[½z5=üi½¼ñÿ= P˜À8* Y5`ÕªUöòò‚IGuŒÅbgÐçÿ*ŰÙlI¿ßoÇû|ÀÞy:†ðꫯZW¬X/*öü<–Hü°¹µ5hX kVt£r:ôbè)ëgPNö6$1BƒO¶èaaŸD"ép8.—³ýÑGž¼j°,3Ž$@@€ øýÕ×\}­Ì™}¹3[PL†áSϺ€át=ŸuùlB,´É|ÖíñB=ò3Ý&cìt»Ó<¼¼4·œ’Wÿû¥Š›Î v‡>X·$â&hçû‘„é¾™õê9-õÑÁÓ1s ¯½öš”ÁaÏ™3G€"ßC~ú{V” S*ÄÁH™ ÏZ]]-Èóv» À¨¾o…ÍZ%…”zã)i³?‹ZžGSiÝÎlœÑž}2ú™D[”VnܸQ˜£\ýõ ¼žGÁ9‘GʲôQÐC˜ áP,$áŠ+®P&°víZ±#ãŠÆ™®xL )a¨µÂlÏ>ià^ «Óõ#Û¦€s UÐOiÆÎËË“úúz9yò¤,Y²D­êVjìô—1Ù¶m›Üu×]оcá¼øTÏcýÈJvÚ f‚1MH “ënº ÊþŸ!ñ°‹ÛaU¦ÙÞ\Ùkd}úÝhà³ÔÉ¡C‡T¸[¶l™ØívåXi¢Cãk"ÆFAV@dÚ  œ:×@(.ýA¬¡bê´éòÁïêäà¾]R\\¬fÔÒÐÓgö×Ï£¾ÓÒKg;öᘿ±±QÞ|óMY¹r¥Šý´ÿLðº½_—þžå!+èˆqêÀ„‹à×Þ°töÓé‰ "ÒÕ’ùófËöO·ª}CIi‰ZVW X'4z~]ŸyWï2¤Îï —lSRR"GU±~ùòåRXX¨"S&ø/Œ¥';Ã=;8°èûBr¢= $ßÓ?Ì ¥­[¦N,—¥wÜ)ï¬[' ;¤4ƒÃþ6ä¼c›®îÙ;²Žà à>,/¾ø¢PíòÌ4×S÷Ós™ß3œá1+˜òV $Ahûì¤Yƒ]úý!€Š„0p`?YTX$Ëî¾[Ö„O?ݦÉ8ÍøÏÒÒѧrN)2פð® û±?Á3·饗Ô9sF"f•Ãû 'ölaV¸ª< ¥ßÜÑ/¾(e•Žn?&7¤«' V#!N0@¢TZZ*wƒ„ 6ÈæÍ›…‹#„/›>i”5ïò†$ì9šÊtFÈ;͆w‚gºÍþØÖªDgå=+ÕÆLeyXO&xóù쟉ÌüÌz`Z¼Ù ‚¤æÀç½âÌÉÃIQ€ÔØí„?J©Ç ?TU..??_–.]*ï®Wúûúeñ­‹±'/·Ó!?ù¯}„æ<¸ü*¥ 4eÃt8)m#‚gýÚµoc¶Oî½÷^E†–­ÿTZ±=½céì˃²ôŠÉ²yg»ôúÞ—?}ðZáà@iUš…jßÜÜ,o¿ý6r‹ˆ<ðÀ*ÝÕ6Ï6§?ôÞ\½ùÉÚÑKV2w­ÞØÙsh74eû†Òíí•çÿóyùpOXjç.å·]*¿~¹NÞº÷iYyS)œ£ Š+Ó©A$!¯0Oì›k:*Ó&Õ¨ºX<†e YìHÉëï™{èMV (¡éZ;!çxRIÝŒ"&ADHr=.ùh[rpÕUeÒíë•ú=up¯ÔÖ\*eÅeRRX*ÕS'ÉÁS;ÅÀÊå–U÷_/¯¿Ó ¯m9&?ýˤ¬4¤ÆÄ… 77Œ÷Ô¢C¥n×'rªí”\uùÕ˜/Wij°†þ®ïº~,÷!J‡µJ…i”~0 µÇÅ´·ñ߉ñäèƒOŽIo¼_ÿ>ìÝ%‹-–в µIaÚìp8”©Ž]¾ œjï—{î¼R.¹l†<õ\=6O™4q<öñ…Êþ™ÜД.¯++–Ü£¶¶ïlY+Þ®8QÇ —mÚýP„9-ȪÜ%k "á E°%F(¤í3*Pí»‘ \^;Ižk@œ’뮘.“ÇOÇ"íQ.góâÉqK0 Ÿ0dבNh‘!·ßº@Þs;ä{?Z#¿zêv™6uœøb­ TEy…Üw×ýRßP'ïÕ½'ókçËÅSg(ÿ@à™×ÏÃÀƒõ3l3ŒŠ#¦ IA:ªl:¢l? 裱¤´v ˆÞ}þ¥åWkºÐ°Dòr] MÀX< ðf5Ì•ü;b?]R©(Œ_4‰0è—Æ2}úùÖ¼‹å~ø†¬¯ì†d­ blOu4–öÌÜH¡Zï‘m{›eîåÉ÷¿³Hîûûw¥n{#ÌÀ¥6U”(~ÞRQÁðKå¸Jy`Ùw•™|¸} Æ Š›0’À¢ë;jTý™>²€®i _ž+õ‡Û¡!¶¨8yav8ijí—3§ÊƒKÈÃÏm—Çþalùøtö *‡é@¢Ä*Š M(ŽªJ7õÊÖ†“R3­Jþæ¡›eÕÏ?”M[pøšО$@o‡Wººº”VÝtÍͲ`öBi8¸C:èp&‘MÎ\¿Ïî`œœeòÄ-‡¤©¹[lN—¹ J†Cò¶.¿ *Šä‘å‹äø‰Vyê?öJ®e§L)wËÄrlÝÙ,Ók§#|F!9ú‹IŽÝ*§`J±†ò­¹“å‰Gn“Çÿm“ ÊÜù‡ó\™\K¿š›®iSj 㥮áŒé—)¦`¬)_fÔÌ„Ÿ‰b]ƒŠµ~ˆÓëíÌ6?ñ¥±jl¼«J¼g¸Ìëéé)üÌsªj LÍñB2©²\þxùÙóÆqZ*ÜAK”™0'`˜dÂÔÇÇû Äê&”–dƒTìÀsH%5rJ0¸a~’mH^ÝÞVø•¨<òà-ÒvÊã¿xG™ûëDIíáˆ*mTá²»j‘·@ÌÕ'îî^þ8Xxüøñ<ÌÇ5¼ØR•nTçðʱ:°î8¸ùw—Õ^(òÈCÕrü”_žyçˆÜ¼p–ƒêswgÅ¢S³)‰2­ ™³+i³/ê»ùÛ¡H¡TíТ„gŠn'Î]vHÚ*ïi–«.› Ý£¼ùv½¬~f£<ûã?JNžB_GšòQÃáˆLJN††X$„Ý)¹CÄ• ßÀxIïŽH™Œê~t‚é öbïìo7ð³²³³³“¬Z¢±¨• ‹[ñí™ò»{¥µ©%9nâééõ~89JF 4UJorÃØÌØÏoX»ª¤±.UmvÀLæ1³}ï)YzmÜpÃ¼äº Û’?xüËO]¬NŸ©IjafÏô'çâ!m+ÌÆL ˜¨Ý6h  T‰w\_Æá@Ô³''·íãO>ªÝ°iš"Ãþy§Ü±Ð“\»½ÓF–K++ãˆóÖ¾þ€ÂŒOLÕ*ÐÕe[¾ÙŒ®vD†ªøãFòƒ­ŒÝûšŒœdsügOoSædšv$I$I6ìCzººà1Á3|FgF/SKQáÂ…M˜;ö™3kŠª«k&Ì` 1¸yc m.{_üdwÍ”ŽXÕßVŽŸW>~ö©6K_ŸßBmà¸_Ð*ŸžŒxñŽ’­pÿAÍîG¶8£ªH®ZP÷¶¶Yß\¿S:ZOþ˲…ŸoŒÇ !„"Ó@¿8R*n3l1ÃH$zzúzð£ns‰Ûíæ‰ µq…iºgúÏä`ôüüêâÂf„jÂ%óN±òÒ¦ÂvÑÒêëkys~ìÉ/™S1¾Tò‹Šp:bXüþ°%"˜û3Î3æ³(b€Ž!/ OÒ~NM™\vIUìØ‘ã¶—7í’‚x×_{ýöåVso“:…QÃŽüàd¼¨ÑTó8ð$AX7)ñE—4é œt °akkÃoîøS³¸ì~#öhÔ[´ùcÅŽþÎãQ—Íséªï‰-÷áÂÂÒ’’ÒBÉ+ÈüyVœ&øÝЈë36Ɖˆa“b’`ªÁó;Såy³*eÚ䲨}Glë¶î TÚû¿Þûï›zŠk ÊmþÖƒƒ&À/hi›¯Þ'ñ7q¬;†CU(0·`ÙËÈÖ ÚA  äyQ¬99UÎ@î:Øê/œzM•á¹ôž„á¼f43/¿Pr‘-záîìîÞQ]=á–]oü¹Ï˜¿ÊžÜÿËÛ}å¼0 DçA6\vü†ÁéîêqãÌá-ß®§ïD»¤qÓ¶äŽ_ÒŒ¾¶rÎ>àlVlÇžÊ×Óä¾¾g{w=}ú&¡ÖäæÕJCÎf¬óÝö«Õ€²Ê`®d¤ÿgÞÿø˜é#ž@¶š~ãë/ôa_õ5nÁcÕœ&ŸÞ/ÀœccÌ©ð—•a< s{ë2™ø²ã¯þ„‚‡Êå1ý\H¹ œËÂ.TŸ .˜s™çN1Þ)½XkIEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/multiple-file-list-icon-tiny.png0000664000175100017510000000351612370216246033130 0ustar vagrantvagrant00000000000000‰PNG  IHDR((Œþ¸msBIT|dˆ pHYs ‰ ‰7ÉË­tEXtSoftwarewww.inkscape.org›î<tEXtAuthorAndreas Nilsson+ïä£tEXtCreation Time2005-10-15 ”W…IDATX…í˜[ŒÕÇÿç2¾ï:öf“lv³d© ¤i¸´*´ ny‡J‘Ѝ”z…  -Z5OP5/¥B*^¸ hR[^!‰€¡¨¤Ù6!—e×aí=¾ÎÌùNÆÏxlï:Yý$Kg>ûœó;ÿï|ß9¦µÆ×ÙøW °”ÉVcß¾}ñ¸ñÍ/k"¥”S,VìÝ»·>H?pÕªÔÛ·ï¸jåÑ\[\,”ÿ¶ÿÍ(€¿ÒÏ4¢Q1<œ†eÕ¬8ÀGFF/‰p!—þiÐ:;ÖÚZ!(¿ó^ﺢb±( û¼hÍšÕÞB‰Î}œ®€¦Y–ÕjEœû°.àù€µ¬+àÄÄxÏLûøãÃ›ŽŸøì–X,Ö·€?q<ðÌ—Ù‘‘_zå…F¿~š4ÏçÞúùOï½£' 3M3¤â©Ó'·Ü¶}GÂ0"ýæéeÑ¥~ ¥ÀSO?¹Í{îˆ\.вÕjÀÊŸBÉd*ðÜPJ©'''kþ™ÿU+N°à¢®K~+•J˜ŸŸ¸ßÔÔ Ãù»Ý z:ŽÃNž<ïô[–ííK)%’ÉäÀ€œ+˜¬“±¯‚£££¡¢mÌH¯x$ $‰{ƒ   ”Rg2»õܪiBÈPu›ŸŸ‡eõ?€¢Ñ(Ö®]‚óƒu»ùõ ñ±cÇ~8¨7ê¡>D¥úç5 ªÖ]A?gß§RÃŽo €à"´Îõë×÷…kôV-Üî Hp.õºuë~8"@FHª|>Û¶;Ý>¸°jZ©T©TÊZ½t’´Âé8›=óûÀ²¬Ðébš&êõðéØ3„Ͷ”¢Y˜Ã`=›˜œsíªÙù]Ð6nÜØ†éÝÖ—èp.õøø†z§ÿÓ#Ÿ„Blš&§åîÎÎL ÖÐe+H=în½ü®åóyÔjíSq9 &I$“‰˜ÖÚýø¼@¢ÎøõkÙØØˆh‰šôsκ&AûæôµÖšˆT ¬ Ü×Ú!Ô^kCèÙé¶•lÛ†aD „ðÆqÇl¯Î$"pÎ凹­ÈÜÜjµÚ¡í¾¸ññqo/ !À tðgšˆT78êâôÞlvJ9pÈUGr†BÝA&ÚªH¶ÒÐ ÞžßVaDÀ9çB÷"ÁX÷R­5]PT* ­ßÌáDÉB®â WuŽpüöšµ¸j,7þSÄ3ÿ\Ä_n½ÀSðæW?Ã#×Åñý éÁqÎõ³óŸ›·‰ÂpRJ0Æ;Ôp>SÇs?˜Ä;»¿mÉà'ûgáÆÍSC8vÖÂiÓ‚Ö…¡P'\=™†”RJ†á*èÛ ² Zk§çÜ` E˜?!4€k'ˆK7CwmN£PW8U²`pà‡—¤ñÜ¿ŠRâ¯Ç+¸}sF¬5¾J9Æ£=:Tk­µ‘H$+¥ÌH)WE"‘t,ŽF£Cñxþ¬ÛyqÙ˜ÄÛŸWñÈ ãøÞxʃãœã¦‹²Š \™*£R©À4MT«U”J%|‘Ï‘”üÙ=¿¸ÿ£ót”¶ÉÖ5©}šœ3ÜyéjÜÕ¬k-°™E ›F“xìÀiìÜ<¹`Á4M”Ëe”JE,,.hGY/=pÿôÝðåñ9½ "ïzÏÜÊ7Ó³ñ²qÃÛôþøó¿ ØúÄ?0{¶Š=W¤@¤]Õ¾À™|αû¿ypz7€ÀÍw`•RµÙÏg)›Érjž­Â¿sÒÎåæÁãÍ/4°kÌÆm£1Øv§gN¡R-£\.“RÎ[«ë¦šžé6ßÀ€Z™¿>pð‚"ðr&x©õ?ø/n[*Gi(ç÷¿zhúÓ~ó±ÿ¿å?Oûn•bÓW~/IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/scipyshiny_small.png0000664000175100017510000004505712370216246031100 0ustar vagrantvagrant00000000000000‰PNG  IHDRÈ» îÑñsRGB®ÎébKGDÿÿÿ ½§“ pHYs  šœtIMEØ 9«!¬‚ IDATxÚí}w˜$U¹þ{ª:wOOÎ3»3³³9/`,Y‚Œ(W¹¨øS¯ŠâE¯¢&¸Š  JÎ, ,lÎyggÓìä<Ó9T8¿?ºz¦ººªºzfzvú{žzº+W:ïùòw€,e)KYÊR–²”¥,e)KYÊR–²”¥,e)KYÊR–²”¥,e)KYÊR–²”¥,e)KYÊR–²”¥,e)KYÊR–&‘ld€*¢¬¤Ð^\Xà>v²ÙJ©XT^Z\Éq|a ² z|&µÓv›XXuØl^¯ßßÑÝ;Ð>Ö´ˆÛåô¿¿u—OlÛM³›ÈYE•‹.sŠ”Ö{}þ™‚ ÌdYv:ÇñõÏX̦Žã"¥#jgB¬KTÅ>JiWŽËÑ Göä †ÂûæÌ¨?µaË®.´ïÉ~ˆ,@Î<Õw5Ãq|iÿ g• ˆ+zn”ãëš+Š”Ïga¡ $àtØ;EQÜh2±[§ÖNÚÌqüᢂír:Q[]þkÿÌäCNÎú‹Ã‘è=¢(^J)MÒœ-3¦M©ÅÜ™ÓPX§T<>@Õð‘H ÇOaßÁx}þ„}6«å Ëé¸Ûj1½Ð¶{˜ȇŒJç]\Ö7à¹GÅ)¥Vå~›Õй³¦cöŒ©p:ì:-q¶7M¹™ãyi<]û&pBˆh·Y7æå~»º¢dßæW§Y€œõzÆ +Ï‹·D8îg¢(*÷[­VÌž9ógÏ„Ýfý4‘ñ>‰F±ÿ`ön@$•+óQ§ÃþÛåøŸ¶Ýodr¶‚cÚªÙ¡pø!žV ½›$&±,‹Së°pÞl¸Î µ9óžŽþÚ^Ûwíʼn¦fP™2o1›O¸]Îoæ¹,¯ß¶–fr–PތՖp„»=Êqw‹¢èRêå¥%8wÉ"È^˜d äL`c´ ¡Š5ŠÖöNlÙ¾ ƒï.Cáí6ë?ªÊŠ¿Ý¸é¥Á,@&>ר G¢áxþBå>‡ÝŽ%‹ ~JÌ¡GFßTµÕèX°’Äó8ŽÇ®=ûq¤ñAs““N‡í–®¶÷Ñw, G%³‰ÅáºFÄ? ¢X¢|¥šÉÕX¶xœ‡Á·'™o22¢>š1cèX§´wvaóÖíðú|rÝ$dµ˜f53¿lØÈg2A¨xî…?xÇñߢ”šå¯aµZ±lÉ"ÔNž¬BFÓ dbµ"-HhZ§†#lÙ¶§›[åS‹ÙüRQ~î—Ú÷¼Ù—È&GýòRž‹rÜåÊÇ/).ÆŠó–!'''Í·'cÛld¼1RÖCÓ>RGŽ6bï¾àùa¦ab™#v›õs¾Æöer¦À1eÅìÇý[ÄÙòW „`æŒi˜7w.L,«ïÓ cÑ$d [Ž` LOñÁ|ô(£Æ¸KGW6mÞŠp8$¹ú­ó¡›^ÏdÜ9ÇŠóCáèÓ”Òù£›L&,Yrj´Dª¡7%£l£ Èt“Ò4¡£à44åa^¯7mÁàààÐ9„°Íbþ¦ÛÎ>Üu胳Þ<ñ£ðÜ•ÄQ=ÿúP8ú,¥È‹uÀX't:X½zÊËÊûž±…ÈþK U.*Ǩ—p ;Wõ<’úü1Ytî7Ðô®IJir%›x]‹ÅŠI“ªÑ?0€@ ÿ.&A?ÆS˜Ý%ðžšH¦¨°žØ *o G¸¿RŠ„ô¼ü<¬Zµ nw®6T?¶¬s íKÕ¹û©Æöq_d`¡:Ï«u^àUÞ1aQÃ2¨¬ª„ßç‡×ë’¶Q<ŒÉ-ÚòÞF û¬ÉıòëˆÉ]ò5A¯ K/.)Á²óÎ…ÕbÕˆ±×6dÑJe S¿ClV3j*ŠPYR€²Â\å»afØm@(Âãô úÐÑ;ˆŽžA4µ÷"‰@G`‰2lÕ¢:«4{ ¯‹‚€½{÷âÔÉ“ '˜XöA*D¿-´íæ²CÎarÞ&ˆô÷”JÕB¤'-¯¨Äâ%K¥pôTÖ$b앉^SÃà°˜M˜RU‚%³k1§¾µÅ`ÙôRoEJqº½‡N´aÇ¡“hlîB$ʉj§ièjÊ95tQq`ß^œ/îøÝ hëñ¤0ÍRû¨†IWÇZ¦c‡vmw°_¾=L¨xmݱ9 !ÖQÀZÊf>åøOÈÙ“‹Ù‹WHŽ@-ó«Žò=i_Çå°â¡;¯GýÅ*_0‚÷öœÀÚíGq´¹Áˆ1²ÃfÆŒêb\¾l:.XX—Ý:¢ûkéÁm¿y^RÜ©¾2­éOQÆ€¥‹j(ó²ë„‚~ܱ<•ï<ĈÜ*±m÷„«˜r&D,b­^ô¥(ÇßëÑ’Þa6cêÜ%0Û©Å'Cúƒ½CEY' ƒß|)Ϩ0c~úØz¬Ûuí½~DyÑpða”ÑÞçÃûû›ðòÆ#G9L«*JÛ Y˜ëDy¡ïî= QŒIUÚN-XW<£ÉbUÒv¢¸Nlk¶Àlµb ·K>0•€°"òo" i€8¦,¯òô) 8†F} º~6r ËÔuªòaÕ¶%E±Ê­V©À;÷ú æâ —.JËZE)ÅÚíøZ‹œF(ÊÇž [O޾ EyìjlÇÛQèv`JEAZÏTWQ€_Ou©XêÔ¢ž@u¬XÐHHÒOu›ÓpÀ‡pÐ/É9ÄæÞ oû©,@ò'Í2‡‰ýaAÉE"wA *êfipÐêà©Ì»Dña•#iâùÕ¥yøù—/‡Íb¼‚{ ÅÏþñ~m|á¨FÇOgI|V˜Ã»{›ÐÙïÃÒU†=÷„,œZ‰mGZÐ5Lm¢D=@S™'ÀÓ1˸ŒÓîˆb¼R a@˜¥°ç?Ž@wô£Âϸ6Âñw!–'+‰VÔÎ^ÖdVí‰öˆ¯åÿPã*Dïz±u0wßt¦O*1üBí}>ü×^ÇÆƒ-uýúÜ"Õ±"¥hhéÃŽ£mX=o2Vc6›X,ž^‰W¶4 ‰ú¦Yª‘ fÄÜKu,Œç3¬¬Ùo_—¤.(kè~Ô€å·rñJ¸+~ wwy+|ѳ yõKóBóœH‘?¤Låµ3áÌ+LÙ©žOÍÄKÔíójÀ"D5±èÜYÕ¸ýºå†ß§­×‹¯>ð [’Àf é%Fu°­¡.¬3 ’\§ “JòðÖ®“”YMÜ¢)D/šŠ£Põ$5“°Í‘ƒ Ïƒh8(7²,„³äøÚ»S¾œ»ò'¾à³©¯ýù³ òkÿ;Ê‹ÃV+ÂÀáÎGiÍL`(»hȶ:\ƒ}P£ØFƒŸé”«†â „qÛï^DZ¶)»dŒ)üݾ“]¸lñX Š[µåùð£Ø{¢31›0刯‘©Hõ|(Šï¦MØlÎ\ ö´›‡ ±‚0e}Ÿ6©\’ àA€Ä Ÿý/|íÏF€WýyS¡¶x8 aTL]Öj×P¦µi­Jô9ªW9¶íÜ™UøÊUK )Á¼ âû¬Ç–†vÙ5™Ô:!0h2Wlï  ÏÄš“ =3!‹¦–cûÑv´õÔµÁGs›R Ó Õ8gøzŒÙ ‘çò{ä<×fxÛNêpëÜ(Ð ;àkŒýÈžiÖaËa£”ýoQ¤yòX+wq%,Î\ˆ¢þ ù6å:‰­#~,I\¤õ¹‹æ@|æý#xsW“t’xoù³&Ü i¼§bâ¹¥û=·±ϾÄðw°[Íøå—/FžË–øÜšm3ÜF)¿AÂ{ëíX·Gì>yu0YlCM€0`˜ŸÁ]¡.GV-% ø‚ÌuõÚvx2Ñ3=É­Y0Ëoƒƒ1YW1¢¨ðÝQåºJ¦ Uø ©ÂCN5‹ñ²' }y ËgóytpßsÛ!ȦI§”B8¼Q Ò" ~èìW”Šˆ±QT>ÿ943.š!76—:FšWaY°¬ kk2á®ÇÞÅœš"Ìšl̰P]œ‹ÿ¹é|ãÁuÒlRƒ ½Ul“56Õrþ‘DïyÂyòë(÷;# kEny úN7 ë"”Y wÕUð¶¿ âáœóc'CÅ?3Õ3 6Àá»"…mX1'È-«c²@¤*½ž*<â PYOÑñ¾K òÒ\´°N›ÅÐËÜ÷ä;8~ü8x. žã ð|ÌLIi̦Døˆ+7"Ùã­æð¹ôcßîD^ŽÃЕ.9g n½|>þüúÞd/º¼sS=°Èö =Ñ~N9©zú®«¨ž®ðáÀ°\ȰßC~í8RÈŒ×pJ mÁ–Ì)Ï™äÓVLçú)Ù‹µ8à,ª†@ˆýR"­Ù6$þï§€@©ì<’xø>ùµ ;wh{LX³ Æ˜Õªg?»Þ>ý>D#‚ éN̰x°°Ò¢µ]kÑ8ž‘ï‹qäý':ð­ß> ^0KpǵK±lzÅP; µŸj;)Úoè;Èåw¢Pÿ&”h|c JX¸Kk‡ß-få\ WÉ• #Lõ¹3|yØêEÞHÆ¢3©¤›HAÝ=œ .›tî²:Xs vv ¯ÚºªoCî8TîKT A@$DÐ7&À¯n»ÊóíÏ/|€W7ê˜H…´aTö+Fc{Âï$:ûb²º’v”æbñÌIÆ> Ëà¼åxìù·Ñ×ßžçAÀ€0ædƒÕÉ™¡>ª0ùjFY'^Ïds‚‰D†¦?!žDéìÈ­þ5€ûR!Cü×À]™wE¼íýc:ÊgŒ{Ô/«õ –Ý‚(æÆ?&k¶¢xæy`X3ƒI¢„D1ÈÐ1 ûȰ~ÀG ú Á…à£QPJBpñÒYxë¡; X®,»õ>ì>Ú’|ySj¥-?”,àËãYÔ÷KºÝjÆûÝa$ðֶøúÛ*+IJ,,v,v¬vX‹5f%Ò?(†ƒ©â¹”ë"X†ÀÌ20³,œ6 sì(/ÊAI®ù96”æç ¼È\§E¹NTåÁbbpøX¾þãû±e÷ÁX™`€Å ”MÓîËt(žð<€f´í  &ûÔÕ? qâÝC—¸Ê¦ÀUZ›¬$uv@®Ô§ÞG†šJˆFÀ…ý(¸hâh,ûýÞM—ã—߸>åË4¶tcîç1¦ž-À¨¶r:Mžª\Ob§œ6©ÿï繌]÷<ú*îþË˱A#¾H5[b`qæÂbw‰—[¢Ú`ɱ›ñµ«ÏÁòÙ“àvX벡(×™vÀå¡cM˜ÿ±[ ¼Â@)@w‚Òg¬° î$°Rô˜…¶½MI'9•Ór”Ü(aYØ *P0P³°¹Ü"Et¬U\ЇhÀƒhÐ £Ž+úZâŠô\³ê* ½ÐÖƒ§hâµT9Ñà&£hòiÊTjÆ–>Üvß³xê§7Â̦ ¾ûÅ˰åà)¬Ý| 4¶Hx!o?BÞ>ÂÀls–“‹3/Š$ ×ß° ·\¾pÔhVýd\²r ÖnØS1bœä˜ˆ…õhÙEõ¹¿Pà Ÿ!çƒRS¬ýéfPôŽz¤Ï„âO]eqqŠ|t·æ–¬u Jph"8¢ ‚ zõ ôIm'£Â1†þËîu•Æò=v7¶ÉÎSB¥„ˆQ ¤ÈÕP¥xþýƒøÝÓà;Ÿ»ÀлÙ,füí®›°ìÖ{ÑÜÑ?̈( 4bÌJG)¢!¢A/ša¶»`É)€Å‘ †e‡Ìè+æL›Q–ÜñŸÄ›ïoGlz{áOè;vüÝÓ’´l€V£zÙ_T‚OƒÒÏäq´mŸf^3'2_Äaуa`É«€8d$ ‹(nùJ@©>äCÄ×.è‰ù”ŸhC}ŸÑlÁãm}‰Ö-€’Ç :œ”êp!G¡‰ÉL?|äM,™9 ç/¨3ô~e…n<þã›ñ±o=ˆp$šèǤPÌ!ÿ¸, ‹#–œB˜ì.ì=Ñ…iU…cÒ‘Öœ»ógÕcï¡caÖ€µØøTnÙF%°Üª¥÷•…v¬Í¼LAÝÂ2^À%r¿ksƒ±åhx¼ežf${ÆùhÁÞxN€¯ã¢þ~IÉf’Èþ3:fV&ök$½U¤=ž`¢É•ab&ס{0¦YÙý6q¤ØÏ0÷PšcçFyŠ›ù :ú¼†?Üù §âÇ·^Âh¼£þ~T¤ˆøàë8o˼öþ®1ëLV‹_ûü'âƒÚ4äTœk¨Ï¶nZ·‹ lÄ”{­@©M>z›Ý%‰a P ‘†RpA/üíGám>€ð`'D“€¨wÆ„ÎĦüÈFDÉÁ&Q³Ét ÈM@©tÀ„ó4|-º©Óƒÿ¸÷yD8Þ H|熋ðÉ j€UWf˜; \!ïØfÍ~îê‹P\˜‚µ\B2•)€Ž’k†EX2®"8Tâ€âq9¢ˆ¨¯þÖÃtôÊÄ'Ž• V¥ó²ÉÜð›è”0à$dƒàкŠ3D¬kwÃ/þ¹Á¸llbñ·}ŸX5_—k$¿7 ›ÍŠ«V/ÂϾñé1í N‡ V«5îCº¹“ÜÇZ c©ƒ‚ú%“=" ƒŒ-Äd¥rëM ûÀû{Á v@ä ë“¬K$üg´õ„ÿL¢"O8^H=‚‚·S:_ib†Š?'…å*Âs1«’ª‰7~_•‚ CçQüüŸïcùœÉ¸tq½±i³à©ÿ¹ w?úø×{àx^fÙcí û_”ëį8_ºf5fÔ”ya½WÖoAGwüûVÁU²ƒ§ß˜Lì8¾1q&ç!J]qp€0`…©Â2EÈÐ1ì7Ð1Jö@'@Å{ -0‘$sÂ/z=AC>ƒI¥ù2€A§ô?Hº^*¢a¼R8æˆl@äEŠ/þòylù×Q[žoè¶v«¿üÏã³/Â/þñ6Ömo€×Œ%ùQ “‰ ¦¼_»v¾rÍ*ä8méœoïhÀ—øyT«ÉzµdîÏ&€Hâ{É•EêPÄ–7<¸Å?8(?Ø !0 „€á0:–-鷭׋™"ag×”$r¥ïÃhux-+ôüòãUìâ„èr€ k0ˆ[~ý^ûß f §Uáé{nFŸ7€ƒ';ÐÑãÍjF]E!fÕ–Åfν¸ñ0¾tß‹è÷…¥¶c 'ì%Ìøñà"cœ²Ú¼0%KcÎ&©1,`qÅ|C„Bô÷€l†LµLb‡Vã ¡>@1kXL:ÖÚ‹ÏIýrKgV)ü *ŽA£>#"ˆüJSÊ,D„RlØßŒþõ®ë(øþÓ8cà+Œ – VÅ¢ÂjXZäçÄþ8ÕeèåfO.FYaŽ‚Ë±ê«„ÿj¦h’Þ¢©Ä§¸'”A” ~ÿÂüß+;1Q‰RŠ?¿º·Þÿ‚‘Xé$b¶+¼,,®ó1É~c S„XV&¼HÌs.e¨ ¡Að‡@#¾dÀh™MS™j‰Š……¨›Kå瀄Åö£†^.×iÅùójtD=&Ùœ›²ƒb‰BP³ž)vèy)!¸óá·ñï÷O@p÷?½·?ø¢‚8d夌9Y2ü­ä–: €µÌðn"sÀ᨜ùé0OÎKî°júC*Ρ&J©Ä\RfñB*œ'PWž‡ÅÓÊR³Jƒš’\<³é¸T·@‡{¤e©"#¿×Rˆ\Pã*± M]ümÝ~D8skŠá°™Óê¼ bË¡&|ç/áë¿yöƒ7Ú¿ÿX æÕWbfm9ÀŠà3ßû#ž}{;4“‚ˆ øj©À š^Èaäð¹57ŠÄ43¥OƒÑ ¼S±iul·˜À‘:Jk¯·\:ט1µ"-½~ì9Ù“¢“ËwºçBý:É"žP×KlØßŒÇÖ@G¿y.+Šsšm"RŠSxjý^|û¯àžÇÖáЩÎárBò)Ön>o „C'Úðûÿ…÷v‘q>Y¤‘;A•œS.jQþ®' r¡L„ŒÀÊ\ó®~Óægkv|¤ÒH²“Ñ ÆSaªp“¤_(: Á+?¹W-5–?á FqÙ_ÄÖ£ãÜÜ*"–Öv¥è¥š;.ËïZ‰ô,T81¿®Ó« Pä¶ÃÄ2èópº{ûŽ·£©½ÁpD:G:—ÆÅäuHëbü¿òxšx\Â6Ù:( è:´¾öÓˆG™±“u™ráFLi²•%M`¨ê"z ôBN´b°¼.5Ãüºbìøí 0TV{¶o÷‰Üpþt¸ìÆ”T‡Õ„«—ÖâóLCžË†cíøBœþÇÏÔ¢¼\J”T IJ-Öëë¬RhçïÃHp¦ÊýDn3<­»'*!ìkñÁâ¾nä PèºzL ‰žù˜¨‡cÈ:•/Ì£s0ˆk–Õ¥å<ËuZqÁœJ|ýʹ˜=¹tc9ø#µlŠ‹(£¢2Ò=#U ´AbHœÔ˜­˜¦šUK:Oäwc°yS&-Y£ˆ£ vî!j¹8Iï`Ë•|´gõc±`”±z¬Ba4|#‰`9ÔÜiy˜[“~áË`ÎäBÜrÑL\² œœìôÆÄ/Œ£È%ÑŠ’›P •QhO½M©¤Ô ×ЪþB~ç G0xzýDÀ实uQ€cV$v`V{Äg˜qU)ü$ó¯Fô,T8ˆ2~*¡ãÄŸxg.]Xòü‘ÍYNAu‘ מ[‹×LÃâú”ç;áôzÚéú^rƒqZI²œ‚c¨q UýƒhHL*uÀRqC…óˆú¦¡ÜD…“8õ:€ðDô¤¬ Êâ¯I-ZÉ£PßDJë—N’T<ßC%{0¡àÑ‘— ¢¸â§¯ãÕ»®ÀâúâQ5pU¡ 7¬žŠVO•®Áæ†.l<ÜM 8xº©ê¨m’Dź¥ð¬Ç«µÇGbyFb’¸#߯ ׈–ÿ‡¼b¾ä‡,‚"žè4Q!_—}C**ÄPÙ6ªRf‰R€°ni×QdÎa䆕Âd_d¼0«ÒùYƒf`eR”JxJØ”2N¢6Ê/—¶5a^M!êËsǬÁm¦Väâ¢ùU¸å¢øÊe³på9“0½26 ‹0/Ââ¥>7†Q¿zV-hX°Ôô-ÅÝP-b£¢–ò¢bÉ@ùôŸ|@p"„‹¼Ék`q.L­Ø‘Wó0ŽT•Ð|! ` #Dx<»ù$B°lZ)Xfìýv‹ “‹s°rfnX=_½t¾¸f–N-FQ®þ‹ N7¨Qëݒ̧‰é Ú QÙ—Êâ”0#1Ëö‹b?úOü€?SÍ7¨FíwÁYtszåkF #NA¥Üj„Ó§eÓJð»[W`éÔŒwtx{oíkÅÚ=­xï`ºC)D2­Jð©*²S…‡]ñ;äP=ïJ§ ª—\Lv(ŠbâoÜËžä@T<ë"ÀGö qí'tdÊÔ;b‹üš `qÎO°Z©åjJr2öNTcª”οDó/4Ì­ÆÒ`Ûú‚øû{Çp¢Ó‡i•y(vÛÆ 9v3Ôâ“çÕâ¶ËfaÕ¬2Ø-&tzBð…y…]+p*•óÿUå1R2€¥5»Cº¢–¬®ù)³ûäÀ½„h˜t–.(2ìÀ¨ç£$q—‘/PiÄßß;†GÞ>Š^"EAŽ ‹iÜD0«™ÅœIù¸iÍT\³¬ƒ(ŽwzÁ TÝl¬¦hê%Jg Ae\@äÛÐwlÂr€<¶¨~55Ë8£¦ ³ê# @Ââµ¢x“uF,ü i’/Äaçñ^ükãI<¼®ïhG7 §Õ„Â[F{5*˳ãúójñ±…Õhëâx—WE’Q™×D¯JäçP±x%€…ª(ê$ùXUCŒ°u¸ãè;þïDå ¹5³W„¨u¡ºx¥­ØÔ‰QŒN–nˆ»PäoÆ`þFàœ"œ€“]>¬ÛÛ†G×7âŽãHë ‘¢¢À «™Í(H€Š>³²³«ò°éh7üa^$*BjU‡$Z#<Ôu­§Uó½( &‡¡P%@^žÐ"VnåŒ%~j]’ 6µNbÔ‚¥•¡¨É5•íDÅËLt4ÌTÇès#‘(vèÅ¿6Äý/À›{Ûp¸uþ0—Í »Å”Âٓòqê)8ÚîEc‡7} ‹Ÿ–>"à ™y©ŠÅÍ Â>$놢ÿÄÚ‰ ·µ jNˆÉY©]_£È[J]z³G)ó>´"\•)Á0ºø(AZzØr´Oo>…×ÁÓ›Oaë±nôxÂ0± rÃù(F­_ŸZ^‹pTÄÖÆžDÓ°V¨º2§] D¥£5‹4@ -‰%…•èIZÑÀ œzg¢ŠX €œ0ì“᮸T•{0¬ŠÓMÏbLb˜‰J%÷Ô¢RÏx5†$ˆ½Þ0öŸÀ«»ZðèúF<¼î(Þ;Ô‰®Á0VJsí£VøY†à¢¹p;,xç`D‘jìD%¶*¡ÐÕ u§†'ÔkNȈwOo’…Èhb±(±ÀeyM&‘À¨×ÇeÔËÒ€è{À5sÛãu™d'`Bí]=ÉÎ3åt€Ê<‰™+ÁÄ "ºwZ úýl;Ö“ZGÐ ‹O‹SÐÌŽblàk{þîC˜ ±X€#ðä±ó¯ ëH.&ÍŽ"ä„èsµÔÖ¤ì9#ØÀœ)/3`Ñ9Ÿþ(Þ?Ü…GÖ7âX‡Ó+rÓöæ\0»›v¡©Û§`ª6IÐ;”À¡ .“¦.bÈêK)zŽü _S&2@iÔa&ƒÚѶŒ†^ªj¹Þ*aíª³IiX›´:§f^E:8 Xˆá]ÁÇß;ùßy_ú¿Mh¦õÑìúê ä9­* Ð©¦C/i0ÒiN颤vS1°È×EÑ‹ˆß‹X>ú„±À  uK“sr²Ks°ê‡Œ^­L燚ÂÎ@=¢•I!V¥ê¨$­?=Í”Œ`7(Rì9Õ§6žDYžsªó § æØÀ‹ïhOÍE4ý!TGV3õRç)tC¢ÁE(1Ò†®OƒÒn‘Ld´6E@ÔÎp]ÉUc:´¤šUU@äÛTÁ•Ä($[²Ôb®49†bô3Ò‘G ’Ñ ~!ÜôÇ𵇷@_ë›WÍÆ¤b—üê¥Áj•SRÆxÉW^[uNzÙ=øH;D!Œ Ï45z ˆÐ@oÑ "TDֹͪÒÉñH²T©XÄäÀHseD?Sd–‘â/o7â¶4@â²™ñÝkæ«idfjŠ]ÀHѵ*,ñõÁ&ÄrÑ…L¶íh9 Ì÷:E5Ó\‰FŒôÊpjYHø@ŒBÉÖËÍŽ-« n»9«zNª’ 4Ð4w©ÿèúF<ôfƒá»~~u=Jóì*zH 1+ݶI`:DÝ8’âuw€ü¡þ’h5¡«»‹"þÎ>‡ ƒA$™^¸£?=3Ôu7г¿ˆÅÄ`Åôb\:¯K§¢¾Ô…[¬¾'ˆhëá@ó Þ?Ò…×w·¢£?˜2NµªoД›ÒÉèÀ'RŠ=µ kæ”aNuêJíyN >·r ~ûêÁÔƒR?’­UqßUXéæ–Ë§'ŠÆTá.”†áï:-D˜È¤‡ ˆ· æÂMo·–>’$‹jp5‡`8b¿En+¾zñT|õâzTjOkPì¶aAM>n\] ŽñêîVüæ•ÃØr´'6ñ¨nO£DÕò!$®â røæ_·aÝ]—1çuÃê)øã‡Á â¼ ITˆÌ©'?9É©IC²^#p}ðwuJ"VF'ЭˆE¥‡ `ïqUÑ*•Ȥ¥ CÅ4¬[c—€en½p öÜû1üì3ótÁ¡$³‰ÁµK'á½»/Ãÿµ•]$SDGp&†àŽ+fà­®ÁÔ²œ1o‡Õ„Gn[ŽËæWàl£'àÕ-†Ž]PS¨ÈK1›¥v¸ž˜¥á!ÐÉ58 î„¿«Mˆév €ˆB<Œ§ù0IÉÔ²öä\Ñ­G§b· OkøâB8­™›2ÛnañØ7Vbj¹{”WùëÆæŸRæN#RXÍ ¬a.OªfIÔu$ޤå-möD,ÿ#|6$ ÀÃu54°Cê%?•Ȩ˚ÊQ±…¯žYŠí?¿ ×.­—)ŒËòìxü+q‚è!p¨eÁHêrQ&–`R‘KÛ(aDÌRu&‹Ãºâ·^|V|½ÿän©Ïѳ qEÝñtw˜£MªåK…=œèªIÛÌ&ß¹zÞøÁÔ”8ǵ³7½?»aQ†¹ÈØ¢«Ë‚'h¬ðyE’aC%Ò@MÌ"D_ÜR›p‡¤â"$l„|¸žæˆ%Hqg @ =¬@?úNH-^é˜nÕ&u!¥yv<ûíUøÕçÂaYŒ%/ˆèõEÐë‹$—Æ1@·l&®?wr†@2ö¬'à 3ôä:,ƒhlÓËñ×øîzn­IJå÷ñwé‘ú?ãX 4õGNoßg®^þ ÄšÔ€)”0$5:!Àš9exìë+ÒòkÈ©c0„_¼xÏnkAÇ` Uv\·¬ßÿøL”çÛ ]‡eþô•óp°yа…H ixÏÉÈîcDÄR?•¨Ì±…#2Ï9•š¦2Ï8Mô¬&VJ4a›Òó®Ö7D½; Œ—‚>–„J2á  v1¾¶£‰úƒw 6s鯙eðƒëæáµï_8bp¼}  çþh=þðæ±8$jíâ÷oÅò»ÖaoÓ€áë¹mxüö•pÙÆblɼÂ2*³7Q©€ Qõ‰šÓQô‰\„0@4Ð…SG "½AÏ6€D%ëB騻“!„ª‡?k¬+³,ß—¾·÷|fl#©xâ§ÏÂU¿Þˆæ>í¤¢¦ž®¿ÿt{ŒÏÁ²lj1î½qñøéãddÇ3„ Àe1tŠ U ÛHmcŒn½2¢mþUr‘ÁÓ{ ò=R‹žmÄòüz#‡MQow’eCË"û²„\¾°Ûq%>¶°rD‘­ý!\ù«p÷s‡áRsâ“]>|éÏÛÒÒKn»t>»²î ‚#E^<ò]Ã’öxÃÚ)Z š¡:eMÑ×ZÖ*åB…(ÚvmÐ+õ1a¼Æ¦±H\Ìê§×IzŽìUWæÅ(9G±˜Üý™…xñ»¢ºhdVªuû»°â'ï`Ý®´Î{uw+xíHZÒÇn]†YUygHiuª.r&*ß:ÔÒ„¦7\ $J‘I-ŠÙ¿ ¨™¬±­¿·ý0žýãeÞÍ@âbV—pzË3øU'ŽT1 V¹ðê.Á]ŸZ0¢œ â§ÏÆÕ÷é‹TšOŸ>³º ŸS˜cÅã·¯‚Óf{`´Q“´ÿÜiņ*7zC:CÉS-lD$D­( ´-.ˆ¤}÷݈ù?¢g+@äbVl%= “‘¨\±h¶þòã¸d~åˆäúæÞ ®üÕFÜýÜ!iFÙ‘Q Âã–7§¥,žR„n^–~nшú?1|B®XTmèè†ÖApªí¦1ùP’¨”ÂR™” ª‘–«†DÝMt é¨q¯2!1 @‡pâÝí,„¨ÖǵYXüü KðÂ÷/QqT£7÷ubÅÝïà­4E*-:ÞéÅ×þ²5­üî[/šŠϯÏ0×Hu¥¹vœ?»ÌбێõJ1ãZz7a”Ä]ÔŠ"Ùª¥6+˜Œ{ cÏVP±S&^‰g3@€˜Ç Sð÷ž6÷6RSÆ'—¸±öÇWâû×/„Å”þcDxw?{¿o#ZG R ÉUIø^ÜÞŒ×O]eÁïnY†y“óG2Ø×H¤ÏŸ·Aýƒz¿Vø¹\äRIRÎ4Ä'F}vbiaB½m´óàARŸâ0Δ €PÄ9=ÚøÆu[YÊEä¬ÿê¥5Ø~ßõ8NÅÈEª{ßÇOS‰TT¯ÔŒ6X(~ðäl>Úcø™òœüýöÕ ôh€1rpäØÍøÖU³ ;à`SC7ôëkÔ¼J ’EÆD-F(PÚ¼u3¨Ø&‰WÁñ晇˜C§÷u7±Ý€Ýj½7¯À³ßÿJrí#ºðë{;°ü'ocýÁ®Ü`tÓG6¡×g¼äÒüš®Êyœ29£ •®ï‚·²ø¢Y/þøzËgVOÑœaNÀ]OÀ7ßÁ¤ø"ň6F`éó‡qºÇOž;ÙpÔðüš4÷°·©?Sšz²ùU¶,ª+ÄÃ_[aHlqÊ]hh÷˜mK¥ôÑ›GD^ \¤¨5ñçðvB©H޾ü öíÐ(qÎ1GDB~«hZÂmyÙôÒõÜ“Ý~\þ¿ïáÞ—§¶Riè‰û?Æ3[šÒ×GþcO)÷Y˜cÅß¾n< æx§k÷¶kË~ª³æêä'(æ °ëÍ×®à"¤ÿøQ±çx€V}gßÇx’¼è—¬æ§žzêÈ»ï¾Ûœ.Ê^ÞÙŠU?~ w¥82íÆ‰²»“+¢ëÛnÆ¿¾u&e8$_Ö­&OüתDCA úýëGæmË•ï¹ײPAÏß»#DÂôØ[[Ú‚Øüç¾ñ6íŽ@âŽÃ~-Zî¼óÎm>ŸÏP‚B˜ðýîÆ'ïÿ@Q ™jˆPtà0F¾‡›þ¸¨ás¦”å`í.aD€Ág—Ú!ÇnÆw¬Æå * ßáT·}ç8Œ„#ÚŽÁ!î¡Á”yèjä¤ë³í;÷P× Íˆ…–œ1î‘iDÎIkWW—Ãívç¬X±¢BO¦?Ñéçï߀'76ÅfDR«5’ -9°ÒÔSú|´ôpí²I†õ‘b· ×-›ŒíÇ{ÑÒHSÍ0vš’<÷5iC¤ßxt;öœJWOR©1Ò¯eŰM¡Þ~Ï?ׂÒÃ’îÑ# ²ø°DŒ+ì[·n%W^yeuYY™êÐúÒöf\wß{8ÔâI…”¬~D¡Ü#Œ¶  <ß‘–~‘ç´à3+ê RŠÇ{“#ôBð©å5xöÎ5˜]^<Øë{Úð“ïƒ8bc†¨½ÑžK„PA`>ý¶èï9àˆÄA26µÚDÅð4YŽãœ{öì?ÿùÏO1›ÍC"^(ÊãGOî·ßoÓfÇ£å"šœ…â*wá’ùiyþ-&Ï«ÀÕ‹'¡c „“]¾äÎi( !X6­Þ¶ßýÄ\¸æ´^µÇÆu¿~}þˆ!«˜îœ*Dã¿Úêzƒ¡°vì8=ùÁV‡—Ä+g˜Øqº•¶¶¶6!ĺfÍšrB9Þéŧ~½Om<Q„J¥Œž‹Œ‘é7ÊÇfŒýìŠZØ-é)–åÛñ¹•uøø’I°˜YôxÃð†¸ÄGS\'(Ï·ãÚe“ñ››–àgŸ[ˆúrwÚ+xâ¦?nÄ–ÆÞ”J¿±}DeŠ:$›~U'ûæ&æ`g¿û‰õTäHÜ£ ±J9â™ÈxÖà0È0 À9f³yþK/¿|i$Fõ×þ´]ž°Æ|!H¬ã«fFLÕQ”uÕuªm"V× «êð÷ÛWjžóPTÀ±vïÅ‘VZûð£àŠ|—ùL-w㜺BÌž”o8tDk„úŸgöá§OïMU÷ :󚫵‘¼=ãÿ©(;^ŒýýïÁ ‘(Ùöàk|óN;šºÇ™`P `6€ÅÎ’É ¹åw^…Õbxª5Í"£œZ¸É„ໟ˜ƒÿ½áCE¢Ï$Q¼Ýˆÿ|d›T¤Z &üÑ •Õ …´ˆ¢l»‘Z½²5|týF»ì“,ž›sp¢ŠXòoÅé#ra¥³ª†¾V!c5ӘŘŒ¶4vƒe¬˜Q:f%O3A®oÄׇÀ€m]DS¬RlSÕETEGßá}/lèI÷hE¬æ®8QÚîLDÄðÄ‹V:pŒ³ÐMs'%†.hȱº Qûø4#ºHüRuÂâpñ¼Š ‘RüöµÃøöc;bùz\B“;C}€2’Ð¥5%4¡°‡:{#[Þ@î¨$VB,~O˜HmÈž{ƹHÜ…k£Ý‡9¶dz)µæès Q`4æÞT¡'Tß ClmìÁ¡–\<¯"mÅ=Sˆð¸ã¯ÛñË çÚk$å £q,IÅET9JaAaóƒï ÁÁF qŸÇ¸U+™ÈÄEâ a@Eí:"es+`ͱkr-%Ý(Ph:@Hï;iõà•ÍXP[˜ù“t¨e×Þû^ÞÙ¢°ˆ‘Á†õ¾'Z«ÀŽ3ïytc¸çTƒŽ#ˆEìN«ÕDˆ$<øˆ•ô 3UçTSVš'M‹‹¤Ò?”f. EN½ÞžÚx ¾0‡%õE°™Ç·yƒQ¿zñn}hNvû+â©Ä+=$™y©¦˜e"‚`9ô驪%`FÌ!èÃ8UJ<›Ÿ%—“~YD|f2p*ŒŠ…U`ͦD@¤ ’T¢•ñjÄ "65tãÉ'á¶›1«:&–ÉhCFx/n;ÏÜÿžÙÒ$•:Ò™áW ÄXµ] i`!”æœ|mŸ0ßj —IDATïðÛûp@Ò;0‚ )ìñé|M4ØÏOKå *ÁšÙdÙVÅùd(4=ñŠRã×R¬z‚Q¼¼£Oo:Q¤¨)Î1\£Ê(õù"øû†øòC›ðàÚ#èKJî"£Ñ !Æ&–¡´ cÑþÏípLGÜ[>áôŒ`ØÍô3X¨0À,”/˜ƒ%_:&»9µG}a'rî‘6@h Ü%Ÿ—ç´à¢y¸þܬ™S޲<ûˆ«ßÁ†CxnkÖím|Óýšd„18ШùdNB–¡´´wccdžÇwR*CÌ×q±Pö3’F{¶$þVE¦J ™òù³°äËú IW†ÖôªgJ²šY̬ÌÅâúbÌ›œú27* ÈsZ‘+ÅVùB<Á(Úúƒ8ÑéÃÓýØy¢›Šò:b<’ $±ÿ,DZÞ·éhÛ†¿í¥”—À!÷w˜à4‘ ÷Œ’bÄÂQæ˜Ò9ÓÉ’//¥—M}rOƒš„¯šQpŒË'$idDàH ¢˜ßööÑÞ-Oî“týçhÈJùDÓA”-.JúHdȺèé? eóÊÀZÍɲ¯Šc0ÉAeÔY8rcäà c0^‘3íc¬ sO½r°odz‡4aØœ‡€³„Ø öŒQŠ\A $>Iþå@EоãA4oé†ÉJS抙„IæAéÄÉ(bf@K¸æ~vçÃ{¶?{"ôõH\#ž"Û€X¢Óâæ÷)‘Ñ{˜8‹®P  @€¸Ê 0ãŠ:T.‘òLä§ŽQÇ>Ëbb ¸¶zø¥“ý[{AðIJw«¤ŒŸÂð„6¡+×ø0$þ. b¹%n%ªL–~ËäÃYœ‡WÕ¢bQŰŠi€˜J ¢m¤á•SÝ [{(’ÂÝ!)ß§%ôJœšû0s+@äïd`C¬’c)€* (•ˆ…ÓçÁ–çÆ” «Q½¬ŽBÇG ÃÛ¬À;z„£o´ 4è—t‰A] š¥ßnI Ï2Kñ!ò!~7FŠ@¾ (U’ØU &›  KP³² …õ… ,™ #E0nѰtìè6¼ÝèïôK:Ü „6 ñÉ31Áð‘ÆG r X$ äI¢W…´”K% N8‹rP³²ç”ÁUìaµ…‰é‡!N‰šûzÄSïwxšöPQŒÈ8F·$NµJ¿= `ˆøˆù½'#)òŽ P$q• I?)’ä`CAm*Î)Aéì"¸Ê\‰ŠýÄK«à Y<'hÛ®îPóžþh8ióKè‘ÑXxH¯$J?êÀø¨Dþ¾q‹—@bÅ"Š%”J@É—}c…³È‰ÒÙ(žU€üÚ<Øås,O‡¡ÆÛ2H{Žˆí{û¹¾f¿À…ãšA©ó÷KÀè’@Ñ#Y¥|YŽ‘ˆRôb˃wJ\%–øR %G”„1ÃYâ@ÉŒ<ÔåÂ]™g‰& ›$’5H$€0BT°ÓP”ë?íeO{Ùž`{ƒŠ"H¬HÀp¡½8 â—qNᕸ lñJâS@ !+Fe2º +uv« 0.iÉ‘-.g±%p—aÀ°C QŸ˜\6ÓÌÐħ‚ ây1ñ°ÿxˆM~i JÇD1\(|ìk­f’%™ÆJÞ"]Ž]¶Ød‹EVZ” ‰‹:qPð2`D0\Ä"¤Xâ@ˆçîÇÁgŧ,@Î4`‡0+‹ì¿I%'Qã¼l‰*¸'[ä`õMkYÊäÌ‹eŒ@Œ (hÏ”)*À"¨8& „,@>”mm´}YÊR–²”¥,e)KYÊR–²”¥,e)KYÊR–²”¥,e)KYÊR–²”¥,eiÑÿI$kÚG{,IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/single-file-icon.png0000664000175100017510000003601212370216246030621 0ustar vagrantvagrant00000000000000‰PNG  IHDRÝ ÐÐÄsBIT|dˆ pHYs.#.#x¥?vtEXtSoftwarewww.inkscape.org›î<tEXtAuthorAndreas Nilsson+ïä£tEXtCreation Time2005-10-15 ”W IDATxœíÝyœeµÿñÏ™™Lö„@kØEADÜAQ‘ÍT¹¨×¢„èÕßUQÀ ‚÷zõº²)‚‚(nÈ&  "‚"»„%lBöÙûüþxª§—©ª®êéîéÉ|߯מ®§–iº«O=užó˜»#"""""ÍÓ1Ö """"²¡SÐ-""""Òd ºEDDDDšLA·ˆˆˆˆH“)èi2Ý"""""M¦ [DDDD¤Ét‹ˆˆˆˆ4™‚n‘&SÐ-""""Òd ºEDDDDšLA·ˆˆˆˆH“)èi2Ý"""""M¦ [DDDD¤Ét‹ˆˆˆˆ4™‚n‘&ëjÖ†O?ó´-€¯¬Yû‘ܾõ™E§Þ:Ö""""2Q˜»7|£§ŸyÚÛ€ŸÑÄ ^Fí;ŸYtêÆú DDDD&‚f¥—œ„îvwìégž¶éX„ˆˆˆÈDÐðÀøô3O[@H)`¿W¼’9mÜèÝH >Ä5×\M_@7ðà¿Çö¨DDDD6|Íèž^þËÞ/Û‡îîÉMØÔãŽ;îà‰'/þ:c,EDDDd¢Põ‘&kiÞu3mJmf*#"""2–Zt÷÷÷ÓÛÛÓÊ]Nx̘1s¬CDDDdBSz‰ˆˆˆˆH“)èi2Ý"""""M¦ [DDDD¤Ét‹ˆˆˆˆ4™‚n‘&SÐ-""""Òd º7`îšHDDD¤´triÛ""""í£m‚î¥K—Ò××?Ö‡Ñ2Ûm·-ÝÝÝ ßnˆµp‹ˆˆˆ´“¶ ºCÏìÄ Ý­`[DDD¤}µMÐ-õËÀ+,i=Ýã˜z·EDDDÆÝã‚m‘ñE%Ç™¼·Š˜ˆˆˆˆŒ½¶ééž6mzSªy´«ŽŽ|×; ¶EDDDƯ¶ º7ÛlÓ±>„¶4º`{bU„iWmtËHõÜ ´EDDDÚ‰‚î64úÞmi' ºÛL®šÛ ¶EDDDÆÝmB©$"""".Ýc¬Ù©$ªb""""2öÚ>èdùòåc}u™5k3fÌH\ÞÌTÛ""""í£íƒî¡¡!V¯^=Ö‡Q—É“'ÇÝÍN%QÀ-"""Ò^Ú>èÞ´>•DÑ·ˆˆˆH;PÐÝ"yRIBûáG9ÚV<›k""""Ò< º›L½Û""""¢ »IÜ‹½Ûõäa+ØÙ(èn‚Ö”TÀ-"""ÒÎÚ>èžÖ± ¶‰‹ˆˆˆ´Ú¸ºÛY»¥’¨w;™í¼Ø˜ýl «€•À¿€Û€?¹ûct¨u1³©À«?çîiåñ´;3Û˜³ÈÝýw­>™xÌl;`Ç„Åwºû“­<©™½Ø(añÕî>ØÊã‘ö¤ »Nã'•DQxˆ~8Ø&Ã*¯NˆÖ½ø.ðmw_Ó¬cl Íß$,»x} e<ø>°0æù!ê8?šÙ^À“îþÄhL&Œw_LXö^ࢋÔï`ï„e³ñ9Ëß,:_?ÑÊ ÛŽVíhC’·*Ieïvíà9OÀß>Û¾&3;¸ø<Ùîj;gwF½¢"#˜Ù|3û.ðg`Ó±>‰Wu¾žßÊ}+èΡT0{ûèõ÷n§Ü Kjîk"0³€Ÿ[7`sÛ×›ÙQ Ø–l Ìl’™} ¸ø7tNiKeçë£óuÛ§— Ö­[7¦ÇÐÊT’®®.¦N’cûùö5Q˜Ù¡À·¼Ùà|3[¡|_1³7g;õ±ˆˆH23;ˆp¾ÓrxmtòøãÙþëëÙ†z§oŸ>} ,ÈÜ>m_É©'63›|èlÂæ»€ï˜Ù.î>¶Wƒ2fÌì `ÑX‡ˆˆ¤3³¯'õq€n…&ï©$1Ø.ó~`ã”å½Àw€#WRGvÞD¤–ÕØþàS£?LÇâ_ŠˆHûi›óuÛ÷t·Úx¯J2Áƒí¢¤,ûð~w_³ì.àwfv.pVíGrÅ?^Bü}’D$דS¹»*—  »B3kn'WÉÓ>yÛATp»„ÅOïr÷Þ´m¸{¿™HÈÕM*±·™í9ÞêxK¥qRRDÚœ»¯ëcö§ôÊSIê-X»}Õ3©ë56àžpÑøö$O z{­€»È݇¨Ý“½Kž‘‰kB÷t·c*IžñÚ½Û.à˜–²ì…ffž=Yÿ&àYÂŒ•ÕÍ’V4³ý€—%,þµ»ß_kçföÂŒ™q¾]ÔÍÌö!䵿ؘIø{—&عÄÝïα½£ˆ¯Q}›»ßTÖn„ ‡òé7ž'Làów¿'a“·G»òë{£uήÌúÚ˜Ù±Àœ˜Ew?·ªí1”Æ ¤å¾ÛÌÊg]íîßÏrÂ{ñѱ¬$ܽ†ð¼%Ǿ$ù;á›q¯w4èÿ„„u~æî•µÝø°°á¼µX ü’p¾~4Çñ¾Š^Wíw¿¨¬]á½|,á¼·€Ê÷óO ßiY÷p<Û‡>«Û¾KŠïÝg(½w¯ËòÞ­:_oŸÒô=föÚ²ßW¹ûrÿY£Ï½§ŸyÚ΄ÉHøä‰'ÑÝ=€¾¾>z{{rm¯P(°vmãïÚ´ëôí]]]L›VŒGlwuu±ÑF¥˜âü È“OŸÃfÑ©_­µµñÄ̶ } äéÀ©î^ȸ½Ý€n—ÁðO­½™}•0 fœ#Ýý'ö}aºú8Sܽ/fíÓØÇ¹ÖÝ_}ñ}8¢Æ!8aÆÆÅîþL†ãý+ñ'ñ3ÝýÓfÖ œ |¦ùZ´ßáÀ$ dHíIŽË’úcf0#¥»wUµ½›úîn<êî¨_~,„Á¼§’<õt’¥À‡Ýý·<¦4QyÅ/ÿþHrð1wÿgû[@ýÒU—{ø,!xÉýÅhf“€OŸ#’iþœàî1³Ï’2#ey”²ï-€/ÇíöÃÀ"wÿi†¶£sÎ'_U©!ÂŒœ§d™5ÐÌ>|;fQ¿»OŽÚlJ('{h†ýÿ†ðL:§–ïûO¤ÌH—×½O“å7¸û5f¶Qt¼ï$ù..À¡$Þ³¤º˜ÙÙÀ'bÝéî{FmÞH˜‘yË›»ð:ý¾Ö~cŽã„÷ÿqd{ï> |ºÖw¨™ÝK}åv÷mëX/“¶ïéîèè`Ö¬Y Û^;ön',ÉÙ>~ ˜ëý$¡÷*©Çá3À[Íì?ŸÖ ¾Ýý®ߘ2³=ß‘m.#L p ™½1©÷9ã~7~¼"ã*'»˜ÙÁîîfv !hËrRÞ¸ÉÌ«çK ÝE=Æß!ôÒÕc[à7fö5wojÙÃ(ý_Âû(¯×·›ÙñYϲ}\Ì͹¿…ÀÅÀ‡Íì ƒ­“ö9“0×ë2®ò"à3;>ç1Æíû5À@ž/Êm€KÍìràÝYÓîêafû>ûqw”jé$\Hìgf¯-ïù­óX^ü„ì›Íìõcñ]`f{þßf¹hŸ|8ÈÌt÷§F¹ï/.êÓý¢€«ÌìTwÿJŽ}ìO(n§ã`+àâèNð»Ü=_Oî›P9Ý­¾½vÞvžéÛk×Ü®\8QktGAôÏj4Û•pâ]nf?6³c£Þ Ýö„ÞüÓÞ. ±õæ°Ï&úY‹¢€û+ä;_MÎ3³Ù9÷9|úîr'G·`›Â̦þ¿×pu˜Ù»3îó‹„/oÀ]îUÀmÑj–}N%|®²ÜE„;7ïȹ^ù¾&¤ÆÔÛ3u!XšYï1¤1³_S_À]n{àf¶Õ(Žå•„/ï{c>áeR½û®Ó„×.ï]²ÝÍ,)5±&3; XB¶€»Üifö÷qpùïÔ \=ÞÎñ"蛚ÛyÚ'¯—-Ø.5˜¨Áv•s€,ùŠs 9Í?ž4³ÛÍì+föê18Á¶ÂÖÔ‚Ûøq”S×ûI¾íZËi„€»›Ÿ¯sݶYoà&—4p[ÕÎ%ôV–&¤J½UlfÇÒCò qîl‘¡íÙÀ^uîǽÞùW 9¾ò¡Gcà¿G¹$ÿGísÎaLG-ÛgÖy]„‹±´1?iv&¤?´Ò¹„\óz,$LWí3ê\à f–zjfÛî*ÕJ3¬åÀ7G¹–jûô’ÑØ°SIF®§`;p÷Ìì,à”«ðâèç`™] ü¸l´ƒDÚÐáŽÀ­„\Ö] tÞš²Î„ôœÿ̹¯ò ¨øpcôøUÀÛIάÎÿ|Š®paÞÀ»RöýV6¬‰ŒÒîG¯Í}„Ai›¾@?Hò—÷Žf¶c–½y˜ÙÛ [I „Þá¿rÌ·&ÜÙØ5¡ý4B pHÂþÆ)¤q½¿Á}ˆ$]´ð33{UÒŽhÖkì÷vBoômÑþ^JxÏgÍ5Ûo'p)aðs’Ÿ#>HßB4ç3»Ìݯ¨÷˜bŽñÅÀ«ÿ‰0¾æZw_µŸB\ù)’{ÿ0³í³äXWé ònÀS„<é.Z >Më>ŠÖÕ*Õ=¸÷ÞC4½?éã[6³cÜýüœû­ÐCøž¸…ð¹Ý—ìNMXßwwˆK[2³Âæ´»3¿®'|^w"ü¿I äßmf—·j|Âhm°Aw«§oomÍmÛ|–pµÿö:ןIø‚?xÚ̾ œ›'ϳ=CÌymÙs¿0³£ ½SI=6³¯ÖYùààw ì¹Ë£×ö¶”}ý8ÂÝ×—=÷}3»‹äh;˜Ù&îþlÇ[mOJw¼-¡ÝË;Ë~oÈ'4ª¶W™Ââq¨,LYÿWà… ëîGøBo¤Ï¥,{’G|}ù“fv*á¢îË ë½ÍÌöp÷;c–OúàÅ«c«+aD9¾’<dBPÐÇ D+waÐWy5ï˜Ùé„\ÝÝj¬Ÿäp’Y¯Žw÷ò4»+Íì¿¢ãýñw¹¿S£”ðüzÂçøñò'£íVàѱÆ],wR«>;Šãú!a qy.ðEf¶5á"0)&©U³ ’~­üÉèÂë«„ñ/IN&|6êup¸»ß[µï uIwŸ¶¤t¹Ú!$ßZC˜¼®|ä•À™ÙÇ Ÿ§¸¸_"TQ)÷"JïóKé(qö! l.ÊTd¡^\zÉxž¾]©$}ɽ‡ÆôLlJ¸ —™Åö´#àuU÷0w¿€0p)ɦdõ·ß·VÜÅ}þ“p2M³8´*à.ú/BoL’zoÑVp÷~w´’„Ãí¢ŸUfê4…Êp5ðtÙóB@[± :ÞÓR¶[oÊQ¬(MJ™^YpCøÌºûi„»KIŽÙß˽oINÞWzÎݯ!\Lý%eý%J3Vïwéw†Îv÷“âÊWºûC„Þ§G®–É'S–-ª ¸‹ûtw?›ÐÃg73«7M&NRjN/¡ TšÏJÒý¸}’ÐÓ9×ÝGpÿŒpA2â|áî>þ`Æý9¢:à†áÏË"ÒƒîÝ-”¬ÇÀÞÕw´ï{ )ƒ#–•IšÑ9íBuqRU%\“Ò v²P·¼}ùù:-î«:_7µ”fÛ÷t÷÷÷óÐCK3¶n}*ÉäÉSØf›‘ãÚ£w»:HÏ>tC}x>`f¿ ä×Û«T4ø¹™}ÅÝOõŽ‹2ŒÂÿ!E!©ãõ„žƒ<.«±ß´ à«IÁ«»÷˜ÙÍ$Ï:®Ú$q÷Û © D¥v6Ž»˜©ò`ʲF¿>‡¥,ûQp¦ùáV>„/Ë =QþÓ>-Pº ø\Z•"w:*5÷Wâ;¢6%¤;œWõüþ í!•©cÜ}™}½V»jÑ`¤‹Œ»©ËûYBü¸‹­÷^‡FHªC¾1a`âéÀ5q壠8K>}BP—üíì~¹™­%ù®Éê¿PªÇÕR~¾œH‡ç„ýy’VzÐÝWGN.LhòÒ껌JG&]ÜG|¹ÇrÿM|jÖÑ„´¥¶Öö=Ý¥@1ùǽýxÍŸB!ü„ßk¯WÙ¾|½Òï•ÇÛŒª$y{·Kë{þóôþohÜýJ­ØC ·OG›Ÿ½ØÌFS‘a,%ݺ(i=Ïi½ŠIþPcy­R`±=óeÒÒ~6ˆ »š»?ãî×ÖÊeŒrewOiÒè×'­gíœ ëß O¸í;ÓÝwr÷w¸û«ïÐDÛ‘)ÛZœpy¨éž<@Èù­––nð]ÏPÛž0lM†våÒ^ß«ãzÖ˹ûó$Öy+ ¥I›¨å ÀïGÌì{fön3Kœl¬A–f¸8…ü%IÊcn–š½úQçRÚÀÇzþŸÞìÙêø_LúýË«~O{ï^ã5&ŒòPëüÏ ‹ùÞmš¶ºÓŒçT’ôöñûÊÞ»œOÐØÛÝ î~…»JÈß<ŠpÛ2ólgUþw%ôÆJ/ÙswÓz vÃä—‡[.­NðZ’'ü)Z•²¬»Æº3›ffû™Ù'Ììg„ÝÒÒ¬öú˜Ù,Òï(¥ÝŽ†Ó ~àîNH'*·3É Ë£ î¬Òzˆã]Èü-Ë£ "󬯑W¦,K €Ê%M8´{”+Ü¿ÈÐfáë"B©»ÌìL3{…™)ëëœ6þc´•bòè§öÀ¢´N‰<RÝT»ÉpgZ/zuºÒþ)m³ŽMzïî:ªŽµ}zIU%I_'®}ñâd‚ÆÜÜ}á ýb3ەГua´ýô ›™|øX“³K»µZåñ”e„@'K™¯¢çj,O ºŸÌpÜiA÷Í̶$|™íOèíÙ|³þ5ràЦ$—ì[™!ˆÎk»”eYТ´/ýÍÌljU.pZõ‘ÌÓq“þY‹“–vqL”S_KÜ,¬zrw¤lVézy¨"u9ééFÕv~NV™ÙïUZ~–ãÜ•$ëÄ:iãCQŽ2«Ç²Ü¥)¶MY6ËÌ&'¥ç%x$GÛ´}WÏ ‘6¾æÝóÏ“¦tï&Ìü÷„åmaÜÝí4}{{Û¥õ’ÚWž«vWó0ïŸÀ×ͬ›¸Cˆ™Ö xŒ™âîµUËzânt¯Jæ©»?kf})Ç7è®l¥ ^©9¥1é78fø|/¡’C==Yåt§¢Ë¸Ÿ¢´éšó–•{H{ÏoJ˜>½(--'OÐ’7èNøúÒèg4æÓ€ ;òAÂûsäÀ§Úf¦>'ðW3;ÙcàæuæÂv™á0Ïùz™­"ù=9—|wuÎÑ6í³ú|öÞÝ‹úëÝÕ=!P«Œ›ô’R*Iöà9OÀ]ÏŒ’ Kr¶ßWÞ’YÚOä¼î¬¢Ï×»ûñ„«æ´[’³¨ï$‘µ²ÑAwÞà*mÀPÞI FÓÙ7çuƒMsaÕhnhlЈ¦ækÖ)­L`®`6êIM{ÏW iwÄòü­yæ5{ŒÂh',嵿œ§?{×™Ùh&BÉ:Õ}£ª VÞãHCö9í¾ÓÒqª÷Ûì÷n«sîskûžn³¦OÏr·?hu*Iww±#´}RIFCY£¦V [Ñ@œf"¬þ¹ÑÝ3MO[äî™ÙG“x$©§'ëç®ÑAwÞrWi½–«snk4W»| Ž93{/pAÆæËX¯'vI9¶<+¤] 5c \ZïÝæy6dfFúgdEÕïkRÚoBö“´ zâd ëÕÐÀÅÝŸ2³WæL8‘P¾^2³?¹{u%™,²ö`·KïTÞê-i½¼+›¸ï´÷ouÚ_³Ïå ºGÃ&MêbË-“&«Ù>z”³}¶õòV%©±÷œí+׫·Óº]Î&Mr8ð? Ëv0³Ïבx¡Ç,é$TOÐ=V=Ý™ƒî(}!­wdÂæP3Û ønJ“àr ªë½lÖ¾hÝ$ º«Óró̬³VuœÒz³“r?“lNúg®ºBNZ “'Þ&G[Hÿì}Ÿì¹ËI²TøÈ%:ï^J(¸-¡ã›ƒBó~û3û•çŸðj¼u9e|Íl*é½ÈyR!y†à8iyÚÕcyÒ>3ç‘/­%NÍÚc­-ƒî { d=zåzyÂÆ‘å7è°ûŽ”e[nÅçªAëî3{’ä`=kj~î¢QØ ´„ôÌH«½Z&©æ+Àº:òØ'’f ¶ú4ÉAáo€÷Fƒ„ã¤Ýµhd0’–*ÑIè{ªÖFÌì5ÑûjWiAwÒ`Á$iùáûÈ)­Ónççé)Ü&G[Hý®q÷åÜ^K¹ûRB‰»3Ìlaðúþ„rr{Q»šÎô¨Ýïšyœm`®™M‰yßÅI |W¸{Þ2¹yÞ¿iw”ªÏiïÝë꼃1Z­Û~9Ý£ËÛ®<ç(ÙøšÛyÚWî+ß ”²6÷ßIPwbÞ F3Ñí™Ò$©W(-(ÍÒ ¶=ù*PdÑIzMãriµ¸okÀ±ŒwijÃËŠ™Ùdà] ‹ŸÞžpCH•¤aA·»¯$½§4®Þuœÿ#¤u=cfO›Ù5fvŽ™½¿jvÈ‘|Ëz³Œ•<ŠŽNYvUÌsiŸƒ·eÙa”—·ôèí)ËÆUSw_ëî¿r÷SÜý„ކwf]MûKšñtCóÎŒíÒÎ×YË–;$:çŒvßÕŸ‘´RšÍ|ï¦Å ÃEÛÝã¹ævs&¸)í«ž`»ºýD˜ 'êÁMëý8Ú̎ϹÙ3Hï™Nª{V"o› ûmätÌåÞ_«ATƒ;mjá¶Ÿõ«Ò.ªš‘W¸É=€7d(Å—–ZÔèï´¿Ÿªµ²™íìPöÔ|Âà'ÌÞ8dGŸù_¦lîô(W»Ö>wNHi7QHÚàÀ7G)ZµœDþ‹´¤ÉAªõ÷šY·™]lf§E“Òì‘#ÀÊÌÌæ˜ÙËÍì3û’™]bfwšYâ{ÀÝ{Üýw?€ä)¿!ý®Ä†dI­ºéÑÿïϤ4©gë¤ÏôZÜ÷',vF~W¤½wßTkþ3›df?ŽÞ»ï1³=£ ²jI;_O¬ »«’Œ}îv¾ª$åëÕ ¶7ì°€ók,ÿo3{_†÷d3ûÀGRš=ü#aYÚ-ñ7D·U“ö=ø|ÚñÂÞföámޤ2è©öëÏxÕê {Nʲ,¹úïKYÖè %Ò&EÙÓÌŽ¨±þ™)Ë~“žö™ß‹–“( Ž¿Eò¥GŸÇ<#ÉG» ¢¤IûÝøPÚ±%¸…äAš{&›Is¡7y1aRš;€ufvŸ™¥M¢”Y4}Et¬çKyÜ/>˜qr­ëS–¥Í@»!Ù‘0Dš#HŸ*ÏQåN1³ÄsKt16cæMî^=þàÏÀÒ„ö{P»SèÂ÷Ób ²ÖFïÝ溺×êóu¢1 º7üT’¼½Û£K%É›¾ú9ðPÊò©„ÁFw˜Ùqf¶™mbff¶ÀÌözbjU;ùzJ®\Ú1lK(÷6‚™Í~EzÐ;Zç˜ÙÇö<ðƒ”uÿátŸÒòâ_W|`A#zåÒ¦¦~…™%Öf6³Ó½SÖoôŒ¿ =Åä'fvJu¬™MŽõà”uÿ/æ¹ß’žKþU3ûi\ÏsôºÝNúôÔ_Œ¦Ú®àîk³Ú&y+pIÜ,yföJB’½4Wi¿Ò?£g˜Ùâ˜Ù ˆ¿¨é$xi)Jy\Nò-ý³3l#mR\csƹsÍ쌸 3ûáÂ)ɟܽÞtÀ„úè/‹Ùï5iðs3{Ÿ»ÿ¾ødt _¦ìK%AZ¾wnÑàã/“vÒD>nf·.(¾ÀÓpýÑÝÿ³¿èbñJ’?ÃG›Ù„×€}¨=ØòÆ”¿àà$§ˆB™´¿_›Ù™¤§’t‚”ZJÑ2ÂÕÄóîþ/3û,飛ʙž°|=á\æsPtöI ©R‰fƒü`Öm§¸{ÍÊ29|Ž0 4)EáÍÑfö áÂeV†ížZG5Ž Áä»z©»_Ö€ýv@g]ŽKúÜD³gž\’°¾¾»ó|/q÷´JFyÏ×Ó2Œ“©K‹ÓKš3Pr|¦’”ޱ‘©$Å@»øÓÑQù¿xKYîß ½¸Íðw«fPísd›Â<ÎÝdt–Ó‡€'ë\÷ÒšM4¿$ß,›yêÞ&YDíY7'Lp'åÁî‘6Æ`N ½ZAV|ÌÝïªÑn ɽky=äîYr‡Ï¢þqƒ„üêÜdÜýÇÀ©uî·Ú÷Ýý´-ÜýiÂ…F–Iiæ‘-àþ1ð½Ñ×8r?ù¦n/÷ õ(º~ë~>îŽT9w¿”p>k„óÝýÜm® ûäHИóu¬1HY­ž’UϤ®7§o/m;{°ÔËm~N70œ÷øÂq£zEž ôp§åS–ÃĘy'ùa∼Ôò0pùïû€ýÜ 6®EU3Ò VK«{žuŸ+€ãÈ õऊ4ÓHÏŸ­‹»¯&ÜÏó:UëþÍÝkðs÷Aw?œÐCVïÅ.„Š {gò‹û-^¿¤ž»$}Àñî^ï@7Üý+„Ál£™ñõ\òõˆgæî7Rj],fñ}àè:&8¯%¤\¥Šsá|VA«–Ó •uò:ÕÝ¿”¥¡» 8…Ñ}?“ UVê8_oøA÷èJ6¾*Éx©¹pOÔô’"wr÷Ó=‚z¬#Ü>ÞÉÝs}±ºûù„ü·,k!omowí¬rIÇs'!Ÿ=ËmÇ¡ªÃË›u<ãÜGÉ^Ž«!'qw¿špá”6p°Ü5„÷Ó÷9ÏI_pi5ªë¥ÔKþÙæ®öÈz‘[¶Ïï*!œOz.gµe„‹“ýò^`F-"\dg™rûv`¯F¤k¹û— eÛnȹêCÀ!î~bZ ÍhEù^|•|w‡Šîs÷‹©\³A‹&Ú›ôÁ’EC„|éW4¢ƒÄÝÏ"œk’*å”[ ¼%ºÌ³Ó ó`\—óðw÷äxï~”ìånGÝI’¤-f¤›’­ÌÛ.­×¬’qyÜ=è.r÷¿GE#®# ÔÙ›0ˆªºFçzÂÈ' '‚ßpÕ°ãî×›Ùv„üÖã€] ·S0(èB*Ì…UœÜ ü¿„Í&hžOYç‘èxžŽ0³½ÁЛy½Ý„ “‡ U`.ÈÚÛù6É3£Õºµ·*å¸ÿ•ð|¹kH(ïIYï\âÍÔìMv÷ç¢8Gr÷÷Ši=„tŽ[=,¿ªµ½¬Üýªh„ý1„|è—Súú _’¿.q÷ËÖ{ÞÌ>Fü¦A3ëˆzm*Úæùfv1¥<Þ×Þ+ʼnnœðÞ½ƒðÅx¡»ß=Š}>•Ç<‚ð¹ßŽPï¼8Nb ¡özBzÈï=ÛìIû,ß4³K ï‡w>ë3ï§'5Ì\]õZÿ'ñ`ϸﻀW›Ù®À¡„×xÂy¦8`s€ðYø3á¢û÷Í ¶«Žo5°8`{p áµYHe*”.ZóµRªü•äóÈ ÏW»‚ä@3­óá;„™aã$MàTSt¾~¯™}‹PúóM„÷Ñv—ÒªÎw÷†Nƒîî¿5³Ý皣³ÅsÜ ÂgõbBþxžôò}Ü ¼ÎÌ^Hxo¼…ðÞOå{÷^ èË€«òæõ»û³ÑùúHâÏ×O:Qz¾®f¾Ssú™§íLÙ—Ü'O<‰îî0°»¯¯—žžÒÿ—ñ5P2¾7¼¶úJÖêÙ.þ›ô¸øogg'S¦”âÊ .:gžNS\ü™E§~5ûQmx,ÔÑM¸]áîuŸsîw2ÐÕ€Áu •£šåaFA©“™M:ÒÙ6i¿Ý„A²+ÇÓíw ³KNV·ª3Ê_ª7H¨c3¾Ñ\¸bßF¸Èèo—sM5 õžg:ÖŒ§÷ïh™Ù’ü«=L·^0c4çk3;›P%&ÎAî[!&z?÷7û»²ì½;¥‡4c3qpËÎ×cX2pø7–.]Jü9©Ýª’l²É<6Þ¸V°ÆW%ô@;­×;î¸dø¶ð3c°ß>FÑûÑhQ¯›îQ«À&z·<¨­¨B@Sª¤ì³)_à)ûkéXÕ¾‹wÚVt±Õ¨úàBt‡bLÎ×­z?·â½ÛêsŒIÉÀáG#ž»Àmt*Éúgéª~žX;Àê¾!vØx2;Í™Lwg#Ó0Æ6•$)èVª‰ˆˆˆÈØhiÐ=úª$ɾxóÓÜñténá+·œÎ'^:ox½»ŸíãòVqí#kéªÜV§Ávu³ÿ–38z·9teŒM/»_º¥²¢ÔÞ›Oå[nQW*É“ëyã¥Wü¥§¿z3Þ²ÝÌÜAwr€­À[DDD¤Õšt7sÐcyûç{‡xj]iLÈó½C€3P€oÿíY~rïªÄ­ 9<ð|?<¿‚›–­åóûmÆV³jOö†mfòÉkŸ¤g°4fÿ-§ç¬JRúíÚGÖ²|}éo˜Üi¼fÁŒ•HF€Oœl9‘öÑ6%!)@ÏVs;®ÿ¶ÈùØÕsqJÀ]íþçû9þ7qŃ«j¶ÕÝÁ;VÖó¿qÙ: rÄãjn_ýHe:èÛÎdæäΚ%ó• TÔ-"""ÒjmV2pø™œíã}ù–åÜõL¨5µËxÓ¶³ØmÞd6Ÿ1‰U½–®êçÚGÖðàÊÊñG}CÎ×þü,“ÌxóöI“d…ƒ8v·9\xwi<ò5\÷èZ^¿uÒoñ¹Ûç†e•A÷;ή+;nùðó G%""""Í3¦Awyð9mÚ4&MšDÖžíª%tM™Ý¥·<ë¬(@÷TÝa6'ï=Ÿé“FöúþûÞpå¿Vó?[ÁÓë*Ë>~ý®õ¼lë¹l3»»âùI“º†çEó¦°çü©Ü±¼”O~áÝ+c‚îô’z²‡u¥4•Ù“;9pÛY¹ÒG2åw+êi¹1 º«ÐM7Ÿ«}Ù¦l<kJÕ_Š5¨NÞ{ŸÙ§zÛ•ûÐxϾþÙÃÜý\in„àuó½]·¬X¯z6ÉcwÛˆ;®-ÝW=r³çOë"KU™ZrðÂYLîêhHÐ]ñ—+»DDDD¤åưdàð39Û'¬Óƒ»×fSY´wzÀ]ÜþÌî~tð^õ£±º¿Ôãü«­æ‘Õýl ¬Œ;žÃv˜Åþ¸œU}an‡Á‚óã{Vrâ^s¿:(¾ú‘Êr‘oßyNìÊâ¿õÝá±¢n‘6ða–É8O4yß?"ÌüçMÞ÷„Õâ’Õ_}©$Yô²yt Çœµ§oÁŒIüû‹çrÆŸJs¥.º{%‹÷™—¸Ÿ©]¼sçÙ|çÎR}ÿ ï^ÉÇ^276›£:(~hU?>_š'eÓ铨ÁLÌê¯T’\Ÿ[ù%"""c-šê‡c´ï¿¦U—£ê%Ù«’Œ\/[ûƒ½7Ÿ»¯´‹î1—)U…ºoZV{’¹cwݨâ÷GWpÃc•ë%U¹ìþÕíÞ¹óFtvÄ·íèèÈ\µ¤Ø¶|ÿ""""ÒzMºCiÉÌncßL«xîÎå½aPfŠætóŠ-*×» ¬ªIZpüÓ{+gs}ÏnsG]&°º÷»ø»rºEDDDZ¯Å=Ýy{·kÛI6žÒ™«}ùñ½fAeå‘‚sߊ¾¸(¯¹]ÝÛý»¥ky®w(µwúŽå=ükeiÛ/Þt»l25WOv¾žîÒ áøžY^–ôt§/Ï7 eâÀĪßgtw¤¶¹¯Re’ÝçMÑâÙÞ¡˜c©¬Lòæíf2oZ)M~ àüäÞÕ©ò¥)½ÜyRI²ôz …Ò߉ã°0Ë«#""""£Ó‚žîêô’èÙQ¤’d1½«#CûÊ`»Ø¾¼—¼èÙ²éÙ‹SµIÆQ;Ï®xî‚> p¸ì¾RÐ=¹Óxç 7nX ]J)qÜ ¸ÀKµAå¬@""""Ò-èéù8Ï@ÉÚÁv!«Ç¦g`—ö·ý91A÷ª¾ÐK7}{‘™qÌnsÊ*¦ÀÒUýÜüøúØ€ø†ÇÖ±¼,˜óÂØxꤺ‚ë¸^ñB¡Põãôö÷…>î )gFDDDD¨%=Ý¿åìÝγírCIË*{·ãLŸ4òe™Ùm©ÁvñgëÙ“y]Õl”çݵ"6P¾ôÞç+Ú½w÷MêÎß®îÝŠíð¯»óÈ£³fíšò]ª§[DDD¤ZÒÓ—^-e4½Ûåí« âj‚'÷n—[Ù72{îÔø’æqAïñ»Ï­hs僫XÑ;TѦwÈù嫆Ûl6cl7»!yÛÅ@»pXþÌr~qåÕ‡ßSý„ˆˆˆˆ4^KRVÞ ¶K%+ Fî+k^xeþvPçü°í,¶œ9i¸mÿsñ=ÏW´ùÍ¿V³¶¿Ü¹ë\ºF1pÒ½0h‡^îðÓ?ÐÏ-º™ýä"úú+³Iî©ýjˆˆˆˆÈhµlFÊZuºó¦’Ôj¿¦¿T©#ÛöKY]™uaÀºÃc«=;d§Áq»ÏåK7?5¼óþñÙfÃm/þç³ûxçN³èë룳³“Ž£££“ÎÎÎ=ÙÕÝ= °}8ðîïïgÙãñè²ÇxàÁûY³¦"¥¤ÜíÙ_©WÓƒîZã4:Ø.ºû¹^ NgõËûr‡k©œIr繓™3¥35ø­~îèÝçrú­O÷¸?°¢›_Ç+ÌäùÞA®^Zš…rËÎ5\Ù÷¹>á¨:;;éì褳«“®Î.ºººèìꢫ³“ÎÎ.:;;qwÖ­_˺uëéëëÍúßµ¡ˆˆˆˆÔ¯e=Ýqj§’äi_©wйç¹>vÛddÍíøc ïr~ÿÈÚŠeûm1½fsõs›Íèæ­;lÄå÷•KþàÎgÙ«Y\vïó –ý-{u-O=¶¡¡2Â@¦?%V÷¤n†¢Ô“Ȳŋ–<]ÿEDDD$«åt{Unw¾€;K.v\‡ö­O¬Ïr„Çöí;Wð|ÕD8o[8«®<ëöœW±+îž•}CüäîÃÏuQàE]Ïd8Îü:;»˜>mϞˌi³Ên€ ›²S¡ùé%”êZƒçkYËU¯a¨¯Ûzm7s¸uź™{¶ãžuÛ³¶ÃlæNYwFÖÛ¾oEçüõ¹Šçöœ?•}·˜ÄçoÇ=.þûê­g±ÃÆSx`EH÷è,ðÕ›Ÿà–e¥ë]ºV0Õy徯€¡ŠºÚC •G†bhpÁÁA† CQ·SðV¼†2º:»è°Žá^òçVVö뀯¥¾¤""""Ò0ÍO/©Šlÿ㦧øß¿•ÛÞµ‚÷îºg¿îi«%mîéía`°"7åÌÅ‹–<—´i¬–ÖéþËk+î¢ ÿ¹’ë[WÖ¾æV©.X]Rüýæ'ÖsÀ%K¹âÕ FÜ®à#W?Á—<ÌÓU¥ßq6oÛatµ³Þ}¦vſ̳¬Ÿ…aøÂPúšCCC 0õr ÐßßOOO===ôõõ /+þïu=ÕKžÎJÝ™ˆˆˆˆ4TKÒKŠn{r]b»[_Ï«·œži‹P;0ßoËétüá±u<¶f€\õ8OéäEó¦°åÌI¬ìbéª~î_Ñ_UÓ;X8g2g½~ËØ”ų<ž3uoá\.øûȼíOZNÇðßS:†b°ÜÑ‚õò©ÜË{±‹=Üå½ÚÕ×õ¬e¨PÊåîìì<ãÓŸ:%±† ˆˆˆˆ4^ ÒK¢ÜÙdÚ¤Äfó§Õ:”ôšÛÕ=ÝÝÆwÞ´ï¸âQn:L¼¸¢wh¸G=Íó§rÉ¡Û0krHIÉSµ$îñ÷Ú,>è.«ZR÷öö²jÕª틊ÁwR ]ü½·¯‡ÞþÒ¤“O,Ü~‡oÖ|DDDD¤¡šŸ^RVä€mg²ùŒ‘ÁõÆS:yëö3G<_ÜBÞ%‹ëMï2®8l+>üâGåq:Í8a¹\ùŽí™7mR¦ô‘Ž ³Hî½ÅLöܬ²ÿ%›Na~G©ºŠÇô¶Ç) #ÒGªÒ×ßÇú¾Ò†™õì°pÇ÷~È™‹x‹ˆˆˆHc4=è.uP;³'wrñÁ[±kYíìæLæGoż؞îìÁvÒ8“:ŒÿØw>×¹-'¼hNÅ€J€Ù“;yíV38yïùÜðž…œñÚ-˜ÑÝ™)à®îÑNû9pû9û=ê…•¿¢žî0…{|~wu`ôÓ?ÐÏú¾ŠZã>o“y'~È£ÖèSi¸• ,Åy»ÌÂuGnÇk(8l93.夾éÛÓì2w _Þ3N{Õæ<Ó3Ä#«û™3¥‹…s&Ó‘³`ÞåCî\|W)½dJWïØe.?úKéø†¢ìá‰pª¤¥“”?`}ßÚŠ×|úôégüÛqï¿‚òÛ""""Ò2-™¾ô¸ôü f42ØNo\o:}›NŸÔ° ºVÛ‹ÿñ ®ê>ž·í4—9S+_úbE’ê ÛÝkÚ¥ðÖ÷­£à¥žr3»øãþęы”^"EDDDDš¢%uº‹w\}ì²†Åæy6žÚ¾™tÖ¶ë œzÍÃÇuÜžó¨ú9880t†Ò…Å€;Kwÿ@?=ýëª_ã?o½Õ6'þ?PO·ˆˆˆÈ˜hAOwÍ9ÚV®—Þ>[p<Ú ºoÈ™ÒÕ‘¸ü´ãñÕ¥^î6žÂë¶™ÅÚ5•Uû††J$ãʦõp÷ôÓÛ¿¾¢<#ðàУÞùî` êé3ÍH™Ú±Z_U’0ÙNå³qã(³VÉS‰¤üçîg{øèoJÜÖmO¬å¬›«8¦½tS CCôöõT<_(†'¿©L©U¥¤7ôpW¾Î—o\¼hÉÊèEˆ~QO·ˆˆˆH˵¤§{dZI}½Ûié)ÅÞåÒÍO%Yôû‡¹ú¡•l1s2ŸzÅ–Ì®Cnœsë2>sÕRú‡JǼûüi¼ïE›P( Ñ××_q¸…¡!†:†Fôb§õp÷ô­g`¨r;À¹À'/ZRìÕvl‹ˆˆˆŒ©æçtWÄz•5·ól£VîvÜ4ðÍ ºýÀó\ýP˜Âý+7=Æ™7/cÿ­g3µ«ƒ[—­fEOå”ò“:Œo¿ykº¬ÀÐÓ×WY.Û¬£f°]|\¬PR>`’ðž²xÑ’3b_@3-íéΗF™‚íbwuO7ñµ´‹ãžËÓöœ?=Q±·Á‚sÝÒ•±Ç¹`V7ßyË6ì¶Éäá|íþþ¾Š6…B¡æÀÉ¡¡!zz×Ó;ÐS½‹uÀ/ZrQò«%""""c¥ù3Rzy–Cžõ’îØëÒ'­m®÷åGîÊG÷~5¦ºü/ÃÿÜÁ a›î¥=ô†{ôGÿíëëãÙçžÞÅÚõkX³nuü« w'-^´ä·I DDDD¤½Y¶Áùœ~æiW4|ÃOìÿ¯pp6pÞâEKF䙈ˆˆˆÈøÑ¬ô’¯¯&7iûãViz X=À€ÿ^¼hÉ-:$i²¦ôtœ~æió€ÁwjÖ†ð—.vz V8ÜÜÜ ü~ñ¢%#æu‘ñ­iA·ˆˆˆˆˆMŸ‘RDDDDd¢SÐ-""""Òd ºEDDDDšLA·ˆˆˆˆH“)èi2Ý"""""M¦ [DDDD¤Ét‹ˆˆˆˆ4™‚n‘&SÐ-""""Òd ºEDDDDšLA·ˆˆˆˆH“)èi2Ý"""""M¦ [DDDD¤Ét‹ˆˆˆˆ4™‚n‘&ûÿöòæ#dk~IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/external-link-list-icon-tiniest.png0000664000175100017510000000273712370216245033634 0ustar vagrantvagrant00000000000000‰PNG  IHDRëŠZîiCCPICC Profilex…TÏkAþ6n©Ð"Zk²x"IY«hEÔ6ýbk Û¶Ed3IÖn6ëî&µ¥ˆäâÑ*ÞEí¡ÿ€zðd/J…ZE(Þ«(b¡-ñÍnL¶¥êÀÎ~óÞ7ï}ovß rÒ4õ€ä ÇR¢il|BjüˆŽ¢ A4%UÛìN$Aƒsù{çØz[VÃ{ûw²w­šÒ¶š„ý@àGšÙ*°ïq Yˆ<ß¡)ÇtßãØòì9NyxÁµ+=ÄY"|@5-ÎM¸SÍ%Ó@ƒH8”õqR>œ×‹”×infÆÈ½O¦»Ìî«b¡œNö½ô~N³Þ>Â! ­?F¸žõŒÕ?âaá¤æÄ†=5ôø`·©ø5Â_M'¢TqÙ. ñ˜®ýVòJ‚p8Êda€sZHO×Lnøº‡}&ׯâwVQáygÞÔÝïEÚ¯0  š HPEa˜°P@†<14²r?#«“{2u$j»tbD±A{6Ü=·Q¤Ý<þ("q”Cµ’üAþ*¯ÉOåyùË\°ØV÷”­›šºòà;Å噹×ÓÈãsM^|•Ôv“WG–¬yz¼šì?ìW—1æ‚5Äs°ûñ-_•Ì—)ŒÅãUóêK„uZ17ߟl;=â.Ï.µÖs­‰‹7V›—gýjHû“æUùO^õñügÍÄcâ)1&vŠç!‰—Å.ñ’ØK« â`mÇ•†)Òm‘ú$Õ``š¼õ/]?[x½F õQ”ÌÒT‰÷Â*d4¹oúÛÇüä÷ŠçŸ(/làÈ™ºmSqï¡e¥ns®¿Ñ}ð¶nk£~8üX<«­R5Ÿ ¼v‡zè)˜Ó––Í9R‡,Ÿ“ºéÊbRÌPÛCRR×%×eK³™UbévØ™Ón¡9B÷ħJe“ú¯ñ°ý°Rùù¬RÙ~NÖ—úoÀ¼ýEÀx‹‰ pHYs.#.#x¥?v—IDAT8•SMoÓ@ݯخë4 m)åCÜh‹„Á\7Μ8ó8ÂOá‚è‰^8€!J+ Vj ‘´MLìú#¶w—Y;)E­ª2‡]{<ïÍ›·^,¥DÁ‚1ìÿ$árËwR|À 4ÈóÃÜ`'^”.ïõS Û‹Ÿ¯t;^üì³ ¯©n”/V¡Ô­·/âN_á•i ÿt¢×kH˜ÓÖÛ¾©SȬlø‹ß~駪†©Q :VÒû‰p‚D1A`D¸@5K»~¶J0*ìÜtqvÊš™…N'«#7æj+­íÒ;S3±V,ô‚X2,"BHÅ$•N/¤”› !‘e0h‚5  £@rSÔŒh lh¤b²/­m¿ÏÝë,ùÚ¢DÌ·šN´Ù‹ÇÇ4?æ•Q-ãT ÎT~¨)TCG‘å†C™;QdF“ì!J%ùÄCðÓî¨KR¤Ì5˜üý TµÙ´»AÙºv³Y_èÿZåœ+äŽÌ—ZOÝ©›Ó—ogäò ðиÐaÚZzL(< òÊ-uf‡·ÓÔÂO—Åa:äZ¥Üg„þ~¢‰‹crIEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/multiple-file-icon.svg0000664000175100017510000004351312370216246031212 0ustar vagrantvagrant00000000000000 copy edit Open Clip Art Library, Source: Tango Icon Library (modified by Kevin Dunn for SciPy-Central website) Andreas Nilsson Andreas Nilsson 2005-10-15 image/svg+xml en .py Submit a libraryof files numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/multiple-file-icon-shrunk.png0000664000175100017510000001636112370216246032510 0ustar vagrantvagrant00000000000000‰PNG  IHDR·(¼^k îiCCPICC Profilex…TÏkAþ6n©Ð"Zk²x"IY«hEÔ6ýbk Û¶Ed3IÖn6ëî&µ¥ˆäâÑ*ÞEí¡ÿ€zðd/J…ZE(Þ«(b¡-ñÍnL¶¥êÀÎ~óÞ7ï}ovß rÒ4õ€ä ÇR¢il|BjüˆŽ¢ A4%UÛìN$Aƒsù{çØz[VÃ{ûw²w­šÒ¶š„ý@àGšÙ*°ïq Yˆ<ß¡)ÇtßãØòì9NyxÁµ+=ÄY"|@5-ÎM¸SÍ%Ó@ƒH8”õqR>œ×‹”×infÆÈ½O¦»Ìî«b¡œNö½ô~N³Þ>Â! ­?F¸žõŒÕ?âaá¤æÄ†=5ôø`·©ø5Â_M'¢TqÙ. ñ˜®ýVòJ‚p8Êda€sZHO×Lnøº‡}&ׯâwVQáygÞÔÝïEÚ¯0  š HPEa˜°P@†<14²r?#«“{2u$j»tbD±A{6Ü=·Q¤Ý<þ("q”Cµ’üAþ*¯ÉOåyùË\°ØV÷”­›šºòà;Å噹×ÓÈãsM^|•Ôv“WG–¬yz¼šì?ìW—1æ‚5Äs°ûñ-_•Ì—)ŒÅãUóêK„uZ17ߟl;=â.Ï.µÖs­‰‹7V›—gýjHû“æUùO^õñügÍÄcâ)1&vŠç!‰—Å.ñ’ØK« â`mÇ•†)Òm‘ú$Õ``š¼õ/]?[x½F õQ”ÌÒT‰÷Â*d4¹oúÛÇüä÷ŠçŸ(/làÈ™ºmSqï¡e¥ns®¿Ñ}ð¶nk£~8üX<«­R5Ÿ ¼v‡zè)˜Ó––Í9R‡,Ÿ“ºéÊbRÌPÛCRR×%×eK³™UbévØ™Ón¡9B÷ħJe“ú¯ñ°ý°Rùù¬RÙ~NÖ—úoÀ¼ýEÀx‹‰ pHYs.#.#x¥?v©IDATx휀\Õy…ïôÝíª—U 5hÆ2 ¶caâ0C0\`Ç EŽ‘dãØ"”`ÀŠƒƒ)vD0N¨¢èÝXBhUY´«¶u¶Mñwî{w43i´"¬¼¿tæö~îÿþwß{Èf³¦Oúf`Oœp©AÍŸ??øæ›/ŽùýÃ$L³Iûy¥ò~Ä8í¨à‘Çš:ùÄ3Ö^xá…í±ž¾b}3°Ã(&·œ]ºô±ágœñïÌ™3R0Je²ÈfÈ.«ù „AjÌFÖ®]³å±GßDÔËê¡m ïR¢©è“˜¹}bÙ*/~&ôÃ+®ª˜9s&dÏÖvv¦ƒJÍ.‘;ál0LG"¡!‰Då÷ÝíqôUÑ7ÛÍ@ŽÜ(LךƒF“J¥²--Íõkñ†Âá %f&“±yòk‚¬]’^åü²ºtÆãñLggçð`tׯù}éó÷Í€›¹ó5w«R™@ÉdBÑÖÖ–H*»‰=Ò’{¤÷â3&-ËÄb‘l*…ú˜0{)ØAÛ‡… FÎ?ÿ|ƒ½¿]555‘#GfçÍ›—ö7¡ëÿnsu¡¢rA¢>eºÛ6eC*ƒÈ ûÈ¢5¡°÷]­+¿þذ4³i¿ õ×Î-aùÕyw¯•_´Wùsä.Ýë`¶³3eª««cÉd2Y,͵·fL@ §ãñ~í¸ÙL&U¤Õ½¼˜#fذa£FUµCvˆ’Mƒ‘$åeáØµ ±;K÷a[ìܹs?»\‹ï“©€œyñÛ:•çQ('Ùeb¸º¨ÞÖ¥0~Á6×ì‡öRAn\ªŒ R®‚»ÜwW×ÿ·[’Üåy½‚Цªªª#ÀeT­—È$@ìhjëÖ͕Ͽ°ôS ñP8”FÇ\*ϘX,šIÄû¥3š»¬É”ÇÉ–æò†æÆKÎ:çôÕlŽˆ‘Q^tÓÊf .-+/_;|Ȩ[i·1oáózºë^W/mdð¡Æ#@°gîn=Ååv%\’ÜÖ,¡ÖL&ÍMd0;tèP´jP;Ú’[¦†4u4ië­×÷?~ÂÑx°Á†Öà4ùvvòYž%FÃvq"­ä+_9eJ(R*!—j“¼ºð–••™'ŸzÂÜ~篵À÷ûmtkÒ½šºþ¥Ï9Òâ?w•z’øÓh»·Àì ¬Žk.uõ σ£€D7äõ4&~©•±¦áS€°#ï‘ä¹Ü. þÜóÀUàm¿Õk²ˆÓœy¡úmWâú'ÿuàÓ`8ü¸\ îZëÉ@TPßµŠÓÚZõFØ. á‚vüt vgù•îÊ«>‚¥7…Úü¨R’ÜÅ•‰ÌMM áuëÖG]Ÿ0Çac0²þýõe³ffFŒ¨2mm­i¬6„ ªÑ¸·‰}3e@;Èܱþ\fÍ™6›(‰DËܱ¹a‹ÝÈeëIí,í¥R‘ç}ðyP®g€9àbúm¿Ûm2[¢EkÖÜR„ËOV»Û…Uš—«4ÍŽÓÊÏâÿðü˜ .UQ}ºš¸>8BEˆWrõâW½Nšñ4€ ð88,¡š®Ò’”·:×ÕiÛ œë;ù,+q\·)só²ƒü¹¾§«Îž’n“Eš:eC¡áf9ÎÓ1 7‰)Û455“­-Aìó`k«ÐR€dRiÀæQZ2BÉds¤¹¹)ÜÔÔ˜Cc£çÇ܉pbc:::±z¬‚멱羽 ‚ ‚Éß¾Ž_$»háæ€Á$Ò¤5Ïo‚ƒI9D¬±„o­ài°Yu™?<~Þ!ßû¸Î›Á*ð5â%ãÁ·À¡Ä†û9 YLø3Ô'b‹P–,øU6ew8Óæö~ò5&RÐó àb SJýîƒ(»4×À±j÷8ð(¸Tƒÿ•à_€6K îóà(?ÿ9ø•ÿðxhìsÉkÿåà% SIsÛc‹Ü-rKƒ&‰ôÔ©S“Ó§OMzîô–3öoÁdÑdOÇPYM¦¡¡4‚†.ÐhêëL#e˜ ê› &Š úœ_v?ƒ.ÔCjt7ýXOµ7™ÏÑî&ðüëH{ W2 ˆ Ò|’½À~  Hã‰li¹à "háú£ÁYàN Íðï@$–¹0\O^ÿ+ï @vw5Ø$ÒäÎo#È4Õó*Ðæ(7¿7®¤ÔZkí4ÎÃÁ4Ƨ°>Œ?jûnêÑMã9h3hžƒSÁp+°÷ é”ÿ\ ~Ý ƒ‹©/ ¤D¾ †wAJ·ÌÍK[[[pÓ¦-äÏÈ\D£Q0„Äá1Lˆv5+W¾gÚÛÛ-1 ¯„¥ú-Ó#Í1aÌLž<ÙTTDL:­ùƒÈðC„÷à— •ª£gâhGÇb!¹`>þg¨ù;àH (íüMÒâO‰½ãйê|¼IÞ³pµ1E”óÀ¡À•½’tivøRðÂÒÈSð‹0"“ˆ/i#MWЧñŸ¾KX›Nëçú þªŒ6Å^@äiD¦U ”¨¯®ïÚ”õg#ø*m誣Mñcp,X $·“¦9ÑØDÐû€òiël9ñê‡6Šä‡ä_ ñÚ¼óÀ,ÐÆ€‘.­¯:D€MN—Âè´7l¨‰J‹Ó ÓŸ€Lí@kG"3aÂiA½xº jcÄb1êP~ÝŒâÚ¢¹»SOÍì4Yãa0|$™/>™°¶ÔI@ZGši!p„ÐbHD'ŠSï?p¸ë|¿nàTŸÄ‘\$´xN®.o2¼HW¿´±êiE^Aa\Ä–æù«Á@кWw¾[G!G2™9ia××õ6Æû™Œs˜ ÞÚµ@âò¯ñ‚ö÷!~ÿ|lÚ÷‰½‡ð¼»þÛ-rcSd–LŸ>Ý.€4·os·×n¬i›!¦DÐ 0@ä·d/\óâÎz§*ÞfålM£{m ‰Ïo©nãvç}v7eSig¦<‚quà¾@¸ D€ÄiKGrif‰¡4a2å´XŠ$ÀHëÛ¶c]]ŽL®¼ŸÍ:þ¬ØúSĸ›Unð³Ò~’Áˆ{ˆ¶oÄ>p}Ä›×OE¸º«ü{ƒ!@Äž$5 ¸¯Šÿ9®¢Ý ´»ÿ0üš77&§ÁI²&Õƒ¸çÙé“÷e\‰Ëï…vñ·[ävmðtÑîn:ÉH†Él “F}û{ÞsÓ¦fõê5–ä Ùó¿5{ÊLyKæáÇ™1cÆÚ°âœ8¿\½-ÉeéQ—vt³$ªÅ{üœts÷GÜc€æêV ©ös é/â?×ë­|ÒXã€nž¤au3úͼJøü·Qâ^Ж“·ÂO“Fvë“P²H3ÞI=—PŸ#…Òáÿ–4Ùвe%ƒ=Ç­’ Uò+Í®•sý(³)^›êÓ¨ç]ÜÓÁJðøhœNÔ'É¥ä/Çý4ø¿Úpù4âƒ.÷"ýï žtºØ4œŸÜ:)áæ0´|ùŠ2ÙÈ¢sÄš%ÙH]]mtâÄIêŸ/YkC{\Q>ó]²uEî¬)//Ï›Aû9œëm/ÞÅTÒ£Ú‘Ib5-îyTþ&œ–€[Ès®äW  èÒ*²‰HZø€6È]`9IDü;À?É ðX£òqê@žÒtI°ÜÔÉÍ`VU»"…;~»àp ÒhÂ.ÇN"ïäa<Ú Š«‹Î͵Á¥Uÿˆ´ƒ{ÁåŒ]'=Ú@÷üMuamBÍÕÝàpPßëZ Qý𵝹R9ù­ÐF.´.Ŷb:îüÙøèÀèûøœgT‘Ju.ãÙd(•êmÝZ¯Îé¦/ c@Št<½ä™Cö›¾ßìf û[ýÃdñN;”Wµ—¤7 ºb{æˆrJ<Ò+N"—“4%ôÜÒgÓW-˜ÿåÅ÷>©ÉVwµ1zt2Ô&õ:SBÁí¤«ôí äEPÖÞ°º¨âº;ÓÈeɹ¥Ò\œss™‹<]¥e/¤Žâ¾Ûeíî¨T,2ë !¥ðàw”ÿ®]ÐîÖ¥üÝ5Ö Ñ‹OÑLUÕí:ÞÔiIXgÞíýú¥<ÛºÏã,{ ¸q£*ÞŽ©ƒ%½8Ý”z[À#vee¥á q"¿ò8بÝþC›ÒPê”6²v™: AýÑIŠKWœÒ”×IÁG?Òå¡hîE%•U^Õ%¿êpem¸(¯Êº¼~µvo«nëñûlë%J®[¯ ÈumµQоŸG}·ýɯ ¿æ*×nQÝÎIGW¢Ï€Õà§@ý)Ø8Šë é¹õ¾©©%¼zíjiè¿}üÎ"jkc{íµ·×¦"ÀÓÉŽŽ³u+7ÂpDdߦ_}šÜþªø>Ý€ŠÜižHF ·]0-š-»­|O ¹ë:´räÊ¿ŒÛMíJúéq.M.é;KSݹtòz—)¿‚üpq;ùi~öœS”7W.Cž'¿ž¢rê{AòŠ)­ ïJ+Ê_ЮËy]º”©#óI§Q:ÎÔÕª i="%ÉíŒ4 EB¥¡Ödg£>0t2¢Í–͆ŠÞåÖ9õàÁƒÌ àTšGÎí}Ž?öƒ4ig ¸EPXæ“eËâÝ-šñì‡ú£ü~ŸÔokâ}˜:>lÞ“;¯&io½Ê-­ªô¥ŽNLL&ÖéžMµæ[ÝW¬X!«Ä†=Žzso½qzäµ…³ªÏÚÚ'NÄ´á{6«Å!=5«=Í ·©y½Ú³½Ì£½¹,&¦‹w.³PLÜœZ*.ûI˜±³O¥É-»SZñ‚7%ÎÍŸ m³èÅŠˆ* ›Â)S¦ä²Š˜ûëü^À‹Ç¯<‘HØÛ ÛË-3ŃgªØì{܈ʠœÖ´ŠØvzI:‘ð@;[o$>Cœ=þÃÕq ŽâNƒgÁÁ•à=p5XE™ŸãjnÕ†¯Š¼XÅKü4¥kò ®JïR’ÜåòU&—WXeoÛyÎODÙôrS@DÙÍ‘hÄôô'©Ðζ|VëñÒøõt7q,T°W’öÉ' þ£ØoA•?Àf⾌ÿ- ­­‡Ÿ¯$s´¿äà"ë3FïKÃÿ>Ö>¼ b€ ·Še*Î}`o…‘”™M}ïâÎ!ücP½ øEÒžÀµš¯[ŸV '_8±·‰BWzôÕ=žüö_>£U.7l™%Ó/Qa¦ì;Ñ >ÖÜõvÔ<\]fáþócY³è°6r¬™6e¢y{K¥yz]¹?~¼™GÃ*·9t&Â5‘Ó‘1- ÉExÝTâ5åä§nsȤ湕IóØÛæýÍMfÿ¡ æ76˜@(J}e”ï0ïñéÚsÏ?—=fìfª´"’8/tmßÂZæTöîí`UÞ8.ôÓ¦'%‘—&¢9qšÛiv®¹V´®ÒÔ\ÍpêJÑÎåøejȯ͠si5ZWü?Âý6®ÊªÍëür½’Øôß³ßäa öòƒcößÿÐ /½öÊ<¶x ûÞj7{º» ò1Ñ/‘YúòKÉYÌ蘱ÿŒÏ¾¼R¾·1{ÂÌ7ƒ2uüW×’6¿Qo&ŒŒ›æÖ”¹mI™1*nF ŽsÓ4c†õ3‡Œ¯4gÿa9u@©K4˜ºuÓÆw˜|)Ïçm-v1Ó¼z*‹¾¢¾ò'×üõ)§¥Õ«„9ÖñŸµeñßw ø+ ;ø!â–ùZ‹û%Pç‡åäkñ»¯Ï*ù x ¼t#y­õ}”v&øqÚ÷÷ŽŸvi:™9ÈDz4]U¬àD»4'nG¨KS—ò½‹Îª ß +ÍOž¬ËÎÚ·ÂT–CnæCU6›ÛÒæûw¬2/Öv˜ÙãæœÏŽ6e±¨Ñ‡=qnÜ„™ôèZ3"Öd¦O™ŽvgeZ’¦±¡!½eë–ð–úM&” Þpý•×è†g7×JqÖ0¨›ÜÀ‡_YqïU–±w[ã+ ·"œ 5ðÈ“Á¹sŸæÌÔ·µÇôTñ¬£G˜Ù$LœezÄ0;Dî6È™‡ 1#–™Vt¨!qáh[RÓ¿"fBá¨iéh73G”™ C¦¶nöu'>4¦ô·KZÚšøš¾õ—?½òj{ƒ£~õf­]<¡pGZ\síæ[„²W%Ÿ”Ž€W*‘.¯œ{ÏÜÕSêÅ©üüêF®¨KfнJ§)½7Êɽ3ÍŸ?Ocµ“ÍÑ NUìQ^<œ ÈÆÖ…yѪ“øå[1/Ú³¦jP9h°qÐÖ:I¢Ío{°š¸¬Y²¢Éœ4£¿ nšÍ[0Öü‘žhsk£ijn¼öê½ö{jpO#¶Æ$ñÉ\@^?^ZÚÝ,*ª@ŠË•”-NϯŒ´‚¼ùi½Õ¿Crïl@óHœëgà$Åþ%¨XŒ{›@0Ź¡47A3Ž#½§&Ìô±¦,^ŽAÉV ^ꡜsƒ÷M›W–m4sþzo3º{vÑ]ͼ.› s|ý`cM 7²ß½æg×ýJõzê©¡E‹íq  ±õÉî™Hîy¹Þ”—'ZªWUc^„õÇxt6Ë%ÎþZ‚…̺jý™R®»¼L¢+0—@žµ&ÌãR¦uËfé²Í†¿øªOÔ:9c¿3mÚæ]ó³›Vëҿ盾¾M›=ž•£PäÂØŸ?÷Û A÷#?ê&X)ï[k]ø«»|ÌhY*•cæÝ%Ë¥$Ir[‚eXE-SUŒ±e-B×ë­òʱ´(`$r †¡/…«`”RGÀZJÜ¢€>Ÿ¦¹¼X$Ä^±Šáªq. ØÚÚº4ª fãX–‹-‹Åb`¬¾ºC),Ëe0åpËTв™™™º]M)…,ËTsn/P–庳™RW;XÝ€õÄbmî\hWƒ­PQ”𬦥dÙçÊ+jY3àììlÕ,¯iN .— ²ì³)zG’¤¹9PEÁÚ’€ZÙÝÜÙÉ5†BA;VÙisgQûŽ)F .æNB€@ `ƒ+VÞ^&àÜÜLÓ¬I5Bš›ÅAyÅð©0)è ¶`Ĭè’-ÅJ]Vßâåm§YàÒ’ ~PkÇq:¥U,^ìîRJA)ÍÁ:ÚK~!0??ÆXÅÅMÎ@‹îL †aróT”Rˆ¢˜ï·VT07CQd³z,–axáØ¿xs¨ ‡Çœ¹‘„[ ØÙëÇ3=~PB0©{°ûøŽn_‹Õ^Wá~£c Ž\‰ãèÓå¬Ë4 GŽEbƒ0Í…S:"DÁû›xc¨ ½"¾ºLJ¿ÍcM‡„m]^tù%ˆ”àØD{úÕ¾H`°ÝSP®øÓ¬p‚täœb+÷vZî-}*Ý–î÷7”€Ý׈+JŒçæ?×#ãz\ǯ‘ DQıkz‚úÚ› A€(Š… àЙa{á¸v0˲¦•,¹ñ·ƒqùzltaÛzŸ]ŒB|9®àù¾–(Ëņ¡ãÔ§`¦\Îâèâ`ñ®hDÓKêä¥h«½.4 n{±?„§_Å~EÇé©8vÉ“8~âŠíëå…†ÖÈXpcøè6ˆ Ú½n¸%7(¡H§2ˆF£PÜ Tàœãš|ët?Okxb·¤TX ~IÀÐçWÑæqîfƒíxms{ÁmVvîhÇÞï&°[¾–P?Òé4t]‡(è0²(â‰(g³™¤>Z gxwKÆçÓy8û£Ñp¯¯„ðËÍö¶bk§ ¢PH)Ew¨mM ØèÖ ë:4MƒišÐ4 ªª"»L6{°o`K8¶mÈ΀&CWó*¬“E”nì¼Ð¦„ 'äFo[“­dL%ttø$dL‚''ñò@è8‡S`98MÓ,8ÕÝ l ‡ÃÓN,]œÛÀ‹Ð,0š [!gÅ`–zœ›Â‘æ fMlJxi“_ŒéH¥RȤ3H$PQnšúœ×‹”×infÆÈ½O¦»Ìî«b¡œNö½ô~N³Þ>Â! ­?F¸žõŒÕ?âaá¤æÄ†=5ôø`·©ø5Â_M'¢TqÙ. ñ˜®ýVòJ‚p8Êda€sZHO×Lnøº‡}&ׯâwVQáygÞÔÝïEÚ¯0  š HPEa˜°P@†<14²r?#«“{2u$j»tbD±A{6Ü=·Q¤Ý<þ("q”Cµ’üAþ*¯ÉOåyùË\°ØV÷”­›šºòà;Å噹×ÓÈãsM^|•Ôv“WG–¬yz¼šì?ìW—1æ‚5Äs°ûñ-_•Ì—)ŒÅãUóêK„uZ17ߟl;=â.Ï.µÖs­‰‹7V›—gýjHû“æUùO^õñügÍÄcâ)1&vŠç!‰—Å.ñ’ØK« â`mÇ•†)Òm‘ú$Õ``š¼õ/]?[x½F õQ”ÌÒT‰÷Â*d4¹oúÛÇüä÷ŠçŸ(/làÈ™ºmSqï¡e¥ns®¿Ñ}ð¶nk£~8üX<«­R5Ÿ ¼v‡zè)˜Ó––Í9R‡,Ÿ“ºéÊbRÌPÛCRR×%×eK³™UbévØ™Ón¡9B÷ħJe“ú¯ñ°ý°Rùù¬RÙ~NÖ—úoÀ¼ýEÀx‹‰ pHYsIÒIÒ¨EŠø IDATxíZ{l”ו?ßÌxÆž1¶Çolð ®m é‚x$Ý¢¨4D¢f m’*]¢„¨Úü‘Õ®Ð’%¡I!Ýj©”î–ªQ»‰HTœRÊjÉ£¼RÆÆæe¿=öx^ß·¿ßýæzfü*]‘VÞäÂû>÷žß9÷Üsïgò,™ùÁp‡4D—ô‰Cüb"EŒˆXL§ ÆÌÀðʈdKLfí 1Äè 1 ƒy— †!ñÉ €N†Â ÀHkyyÍ˳À¸ € $Ð -àq€y‡ô¢tS>Bº&U#f Fº H d]  À\.˜ÏFÞÆ=ˆ°oâ7„ºrhïA¼‰xCÒÅ kmàÞ™AÁpƒ­R°9J^&‹°ø|0és™È{:QC~éÊ}" å Ä4Ô’n\×¶a`8$(…X~ )ssgƒ¹"¤¹!i:ÊNÄú @ìA=µ# } ¤1´„Äk|¬ö9™€ `ÜL€ |”)a§bÑžÜ,…`œ`ÃHœy ÌÓ‚´C$0C€ô e¢*O,ØQZÀÔ 1ò!aà`EŸ…>T}7 `kqu@0ˆR¯dÃS`@6xè… ¸hZÖÙ˜û}LÌf3–aðÖ”ž)Ç@ ¹„mp>y (æ·oßþwáÀö‚üoFFì¤%†q{øç¦äÿ?-€˜€î4‰Z… _‘hN« JÒ`Ú&ü W6ŠÔYµ–aÍ-bš7ÅŒe‰ÍCÚ,¡QÉé¼)¥¡°”ÕΗ¤y±S\ ­öH·z½Þ]÷ÝwŸÔ××GÓÒÒ”†Ü.È8A€Ž¦``ƒŒ¶)À1ŒV0ø:üÁp8Ѭ D†–݈Ågpï„°8Xv`G¤áŠ€Íà…,=Vó¥ÂêßsnY»öÌw 0¸ç:”¶‘ùeË–qÏ$kŠŸN˜ì.’¨#"Ë‚a££Sú<¼î€oû4ëCÚ‰~P £)O¸.äQoá€@Eöf—ó«çF;:Â5G:ÿjÕ½'ßwÑÚoذ!öÁ4ä"ÔÕÕ‘y'ö½`ÿs(Ç«`/ÇPÛ²°Ua—©%vdWJ²F»f&5ºmb?®Á‰¦áwxÂtýYËY ã*šé"Ð ã̉{ÕÀ:¶ —WÖˆK¼Y¥â÷ÈÅ&£n•X¡1)ŒŒdøý~h o• ìÐjªÓ8[ f@å ê5.pñdš&cjæí¶qCÇŠ‘tìTWÓ‘£»Ÿ &sæ"ƒA8s”4ü9ÂúÌóBBÚ -¹ ZƒöZà7ÅÌø@ðši2(ÆàT}æ1ƒÍ±*Ø? ­i9wJšÎž‘¡^É/*•Ú†%RR^­:š„›ŒH’p-ï¿ÿ> Ȥ¿¿_ÚÛÛåÍ7ß”?þX‚Á j?|ø°ŒŽŽJzzºœ:uJž¾^Ù±ãÇ0f•r¸ñºœ89"nO½4]ôÉù ™bK%j®„ª/WiÔZŒ´ÚUX…XÊÁåÐÈEŠ×2„?ª¶:bÏôuKã>+«×UI†söxT²ó|2[‚—10Ø-n‡Ô}Y¤ñ—oÈŠ/ LãZékM ‘íèè}û~"………²gÏ)))‘¾¾>ùéOßåËWÈ[o½¥´ ‰Èºuë”-X¶ìnY¿~½œ8qB~ô¯¿–‚‚"¹p!$mmW¤µw›Ñ lØX&Õóæ©íÅ'Â7 †Ï´ò¯•`™v‚Á¶G·žS:?‘aØÿêY†*:•”yZ8!m ,¡`@ò |rõÒ)è—¬œ\¨fDµ“IJ¶¢¢Bº»»eéÒ¥rþüyéìì”xj~\®\¹"+W®ŸÏ'ׯ_Wˤm p âóù|24”ËWcrõZ“¬ZõEÔ͇j»Á(%Ëû0C/À& _Œc³Me$ÔAz ¡ÔT%Ip4ËkÉh8ŠA™{*,1|HÝ4£ª¿2BP·Û­*--•n”K-—äÝwß•‡zHíuxŸ I:w.ö*Œå¢E‹`°”}xøáGÐjÉÏþ )-]Æ7Ëo{sÄë«4®ÊÔÝÈû°ø ú)lc° ,sT؉!ÛŸ+i8…º{±ïsñ¢0ÔÆ<@6&CÃC€Qžå÷J_G·äÝ%ÞÌYh³Oîç… *fhètžõ Ü"sæÌÁBéGØ‘õ4˜¬ß¼y3‹ ,¶?úè#ØÇ1؉|å+_Uã¹ mæyŠAn?úIu§=RG?+ÆÂ4pïÚÆj\8{®Ü³ñi9~p—䬆!‰¸%2Ô&Ç Ã|Lá‘¶s"[v?*é>±3”7)Jš4rTe2N+OÃH†&KÙN-à8–¨ ,öû¦ÝFÉ8[ $gJú‰9تÔy%Ò<ÂÚ.7˱3Çek9ßÒ%e¥^qyfÃgމÏë’ш)m—z¥§^ù0¼/H•ªfÅA¤Ö‘yªz*Ãz‘Áà˜ñ}5Öë<µÈ6¶6-Γ{êõ¢ôB§J1j‚4É8ý›ÜdcY§ëõ\L§„ˆn8<*Û¶Oð -«W7HO_«Ë!M¨~ûаŒ\Ç£—2/N©ªtËÃ[æÉ7ùŽÌ›W#w4,ÊV ÚÒŒ÷- %ÇEè…%§Ôvªmr»]J­ÓŒQKçÏŸ¯–LGW M€­“É”ãyª>­ñïŽ5ʾÿJî¹§Azû®I<>/N¼J£¦¥ -CD]?öã…¦‹RXì•Õ+Eö¼þö;÷:Ol 0dïU{½x;µ]àÄâ ÀÄE¯#=IU·'§œW—홿“j;3Ј4¾÷Ž,‡sãp†¥« ÷kÚ!4›°=Ìæä°˜‡¾êîoBcD®´úEõò?û¥<Þ|Nêj—ÀÙ®í<8+4j‰9ô\©©=j]ò H÷a=ÕŸ¶Å¶q†çªÛŸU”.ëÅ–ÓR\„ûUp·m¼MD±.ªh²šÒÖ5Ôþµdzså_|À"8 žZ³,ª¿S-Œ’âb¹Èdf4#·šR3³²ø¨k3Ê”45(ÉõÉóè<Ûu˜\€;ó™‹„ñ°ŽãÎ…“†Œ+ñ«V[ÒPÿß|†GbZ¦df–A*° 86ôqÊEÒ â{eüD ½0ÆÉªD×1ÕÛ‡7MºÐÅÅÅêÖ9UÖ'Oî§ó)6@w&ߜċ³ü 5K¤µ>ÉÎr á£ü¸ß)‘õ$æÆ{J†ß1ú 雄?39qòžÕ Kãše—m0¯™ë‡ÌØzãy=Çtiòxæ'Õ6pÿóSûýëÖË??·[êkGážÖaÏÂÆFO¬ÝU fЭåÃåÑ#§e>\5,Z »€šx¨¬äµ7ú 4#Jãât5zœnc=µ‡÷ªüØXD˜®¬Û4M¦“`wĆkñwË¿ïß#›7m‘%ËEÊañá#@çU Ü99¸·"òÉ ‘?Àô¡Ïk/’üübh | Ã-@C•“ãÇ"Àÿñôàt\ãx;¢™›.Õm¤£Ã¤°‘¹èÒ7nxX,¨—÷~sH._i†ûÑ÷ôÀM‚‚Ç]eélùê½urï=÷Á¯TŸtôäzáºüMõǧÓªçâ&€ug¦ôÝßq—Š¡P[Ö‚Cƒ=©ú… ðÀÁ=÷‡d¬¯cÓ‹HmK¢«é߆”sØ+Ô³Ú鏯/ŠÌ°ŽÒtâU•kÒ}œuÜßGq{¢úê>©©Ý7µNÓ³Û&[ûë1º}ª²®OISq' e¸U&ñc««¨+Å8Î_¦¶c ¨GÉ„!Ò@8ñE†ãHC«?ó‰²=Ûu°Ë‰ƒIÕ}8^¯GÓÒÏ÷Éôm:6ÉcÙg|˜ ì ‰‘Q^Gi¸Hˆ¶±Ì‰„Õ›€z ‰{f|üàöãöqÁypÒc_Ö“·‰î7U™ô8F÷£9~<# 8ç&-–YÏ2S „"”ô“€;^ÉÁüÇ\à /¼ —/_Vïv;vì|?TOW|áݹóy5ÙáÆÃªþõ×_Wå·ß~[I㥗^‚óÓ¢^…ÈÈË/¿¬^‡ùºsçNùüÅòóÏ?¯"ó¬{å•W ¾½óÎ;j…»wï–k×®©·Å_|QÑkkkSôÉìþýûe×®]rôèQÕïÞ½jý’¼4€I¯€À¾ÜÒ)¢ô˜O–6&Ø/„—™ÞÞ^u6³L©ëñìÃñ <9XÖç7鱟vaYf`™‘c2=PPuÉã© z<×È'ÒÑš@º‚&Àóœ Õ p]æ$Ì'×érrÎëÔÏR‚–7Yj÷·íF"?ùX¶ëuiZœ‡¨×¯Êü&ÀÔ^‰ñY›ÒÔ†ˆenHø®Šü{$Û䂲³³ÕÔôx‰Ñ{’m¤;žž®ËÁU“RKÏÀ¥˜“çÐã9?Ç2r #=DŽãšôœj!SüL €È”ÒäççËSO=¥&áÕ“‹xâ‰'òkÖ¬‘+V¨ Ù—e¶ó•vË–-jÒxqQÃ…²ý™gžQ€rRM·nݪêÙåÇ{L}2[½jµCPŸ|òI5'™~üñÇÕœ\·inÚ´ @ìg< ‹%œÏ:M 1)lÖ ¨}ÏEÒØÐpzŸ-^¼X¤®›]xäW\û{ëêêR‹"-Ž»q£Cî¼s©2¨´´™™™ª\[[«l_‹øÌE̲²2hQ–œI‘J¬ªªJEÀÉ óÜÿ¶á´Ácâ‡.BÓdžªÍH ²i3Õõ)e®…´*++@Ç6lì«ç 0Œìú²²¹ªËœ÷þûïW´©9Ü ¬GThð/D!ÂÁÃü|” .B_dRv¢85¡Î³óÉ)ódP×év]¯Ë:_¯Çéz¦ às%À°k'þÞD9€ÏóÜ–VwúŒ®þvÆ…?†tB‚™øÕ¼víÚ ÇŽ«Á·º0$dÃ5‘!ÀÁüðÃ]ü4Á¼‡ºY®³gÏ:«««ÝgΜ‰b¿ü#>_Ä>wó>­k²tnçöbl Þz·Jƒ[FÜ >¹÷¼öÚk'Àw6aáóF ™---Q|‡»;7/÷{P™z7  z)sÝn`Rˆ Ú;`?¼úê«oÐhB ‚ä,@à{s¶ÃlXs8?…5ýYHBxŒ/þjÔ 766vÁ¦ Âhºñ‰>·98ö§²èÈÁ]SS“Ξ¦¦&.Œ3òÒ4Q P9-3ÝÒN% Ge —ËÈ?%“ð(¨ Ȭ³¢¢Â çÂ…K…êcèï6#HžÒ·pü™ð/Lü1$j8·ƒ:²&0ggFifrZžâ@L×çÿuÕý3>à3-~0ÿ¹|®Ÿq>ó[à|·)ù0IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/person-list-icon-tiny.png0000664000175100017510000000651012370216246031663 0ustar vagrantvagrant00000000000000‰PNG  IHDR((Œþ¸mîiCCPICC Profilex…TÏkAþ6n©Ð"Zk²x"IY«hEÔ6ýbk Û¶Ed3IÖn6ëî&µ¥ˆäâÑ*ÞEí¡ÿ€zðd/J…ZE(Þ«(b¡-ñÍnL¶¥êÀÎ~óÞ7ï}ovß rÒ4õ€ä ÇR¢il|BjüˆŽ¢ A4%UÛìN$Aƒsù{çØz[VÃ{ûw²w­šÒ¶š„ý@àGšÙ*°ïq Yˆ<ß¡)ÇtßãØòì9NyxÁµ+=ÄY"|@5-ÎM¸SÍ%Ó@ƒH8”õqR>œ×‹”×infÆÈ½O¦»Ìî«b¡œNö½ô~N³Þ>Â! ­?F¸žõŒÕ?âaá¤æÄ†=5ôø`·©ø5Â_M'¢TqÙ. ñ˜®ýVòJ‚p8Êda€sZHO×Lnøº‡}&ׯâwVQáygÞÔÝïEÚ¯0  š HPEa˜°P@†<14²r?#«“{2u$j»tbD±A{6Ü=·Q¤Ý<þ("q”Cµ’üAþ*¯ÉOåyùË\°ØV÷”­›šºòà;Å噹×ÓÈãsM^|•Ôv“WG–¬yz¼šì?ìW—1æ‚5Äs°ûñ-_•Ì—)ŒÅãUóêK„uZ17ߟl;=â.Ï.µÖs­‰‹7V›—gýjHû“æUùO^õñügÍÄcâ)1&vŠç!‰—Å.ñ’ØK« â`mÇ•†)Òm‘ú$Õ``š¼õ/]?[x½F õQ”ÌÒT‰÷Â*d4¹oúÛÇüä÷ŠçŸ(/làÈ™ºmSqï¡e¥ns®¿Ñ}ð¶nk£~8üX<«­R5Ÿ ¼v‡zè)˜Ó––Í9R‡,Ÿ“ºéÊbRÌPÛCRR×%×eK³™UbévØ™Ón¡9B÷ħJe“ú¯ñ°ý°Rùù¬RÙ~NÖ—úoÀ¼ýEÀx‹‰ pHYs.#.#x¥?v IDATX ÍX[l\W]ç>æi{<~ÅIœ&!1Ò*%I_Î ñ‚!”H¨ˆ/ $„ P ¾Šà ñ@J‘ZñÓªR+!¡&1U)­ˆ¡QhãÔMìÆÎxìÏÌ}Ö>ãìø1v'¹¾wΜÇ:kïµ÷¾£´ÖønÎ N±;kÿ4Ô¹ÅÅFx—ç‘sˆOióñî›0x7wT##pZÍ•1OV«qk}W ?®l.døÕ£*øxÄŽð¬PHñ>7"?žÕïqŽUÎÙ³:”çÍ4%È7ÓÜ3Ïp8ñQõ¸RxÜRØn¼hLË"eDÌÏ5®þ´á¿yEOÝ ÈMLÀ@õ§<ÏëPepSˆº‹m:ŸM™³ÖfçÐhÀɱ+Шò_<óýÒfAnàéÓÊ:uJÇ'T}$ýu[a«çÃÿàûû=–€#›£ž ²àajºª¯^Ÿ énʼŸ}ú¢~~3 7P”JW0¾@³^´- Ó¿üG>2˜Ú¹µƒæ´iÎa #^±¹<ß'“u¼yu2ªTas^kì?3ª¯$nå^ô–ÖJ¤GA|îëià 2÷𡽩÷ tÂq\¸Š+ærÂ9ÀŸEìWÍÂÂì¾]ýv6ƒ€¬»ôϧ䋱1Êi­%@aOÔwZ)‹&üvµ|`OŸs™ƒ²®†´Õ@´å3ÈfÓH»6TTEX¿Å#Mgݵ½ÇõÄÔ§¾2¬†DhâÓ­0¶(AXyû0Žà±æîí–E™Z‘Ç@è¡=ŸC¡=‡\FÀ9p®›¦Œ=õ2ͯQhK¡ÐXÑQÈâçdÍiw¹¯×Z” a°0†‘ÎB:Îg]ãsQP#‰d‹ÈÅÁÈ1Y•áriqã›ò}G{‡¢‹J;,z{9¨EÛL  ȦÓÈGà(HXñƒ}¼ÂQ!âà˜æå#´ò‘J§NÙ§÷ ®$ž®‡±%ƒç’ÙÊàâw ‚ †“ÁU˜¯ÖQ­5Ö7aF†¼à"O&Ô‚f6÷déõî-Ž,Î&!“’!„­½=`¼k0°-Ô¨Xe¡fÖêê b<@hÙ4AzA¤›qK–݈HZšx,ñ“oH°©,øj¾êÁ¦ïéØW-#•ÊJbR%&ö ¬áÕQ¯“-Ê‘TÃ8Y©Ö4E&ŒþMnD$->û¬H˜ q¾`áf¢orºçÒ¶¥D¡C03DÖTEa Íï1«pf¾£—R˜«ú(Ï…]¾Æs²æFDÒÒÄ’A>9¨ÒϽªk¶Æ“n015ßš«Q„v;¼¸@3×é‡bj1;YâÊùBsÙcÚ¹vc:bô±Xf¼xæ¼þ³ÄÕˆ¤%ƒ&o^ÑÞ½÷ªT¦Ò—ìÖåñ›Ø·{ ´å¶‘Á 4EÁ: )úœdaŽn‡MÌb¾Íl‚ —„½±cþ“B¥oµ¶n.Nª—TÞÍá¼¶qÀi äÞ1£ŒÃ wn+¢»#ÃÀÌ8hb ·á!¤h¨Ô|\›œÁ<³ŸKu\—sÖæ.ŒvwíÄ,M=;[2–(veT±èòuôL’ÁFrVàYÖ!æ•à)ÊåÄ!PìʲPU, š©K˜pÉ%cä’·ºewŽtÌ<øÚ‰ßãûßzŸùØw1qc>S‰Ã¨ÝÝ[°„Y¶OÈŸsçšYKž“¶ ;r‹Eo{¤8H§]ú¤øZƒ sO>p‹ ’ç\\À±Ž@ï0¶ôìA/QGþ=üJ³o›Z1ß–²dÿ>ôj—°&$%àä¾B$Òé)dɻӪ ¨ÀW˜Hp&”,.u{Éæf²„™C‘aæÖ~öË/°ôZ`¥ÝIWÉÀròôá®ÀbW(bÁÍhÊ Œ†$®Ôlw4_D6æøEl¤}ú ‚sxê&{2H°Ý¶ôÌ‹KËA¤ÕV2Ü—Ÿ5JðÈj{¾‹¢iú€ŒãtM ‹3šó’¿‚ÿv#ÅfÐ¥ ºÄIWå‹j¥û~ÌP‘£¹Y‰ˆ™¹¶ar‰/&ÂILœÜe aR”/•xŽª·”Ëu#–cž± –Ñ7Û2 ËÊ÷¤Í8Ðäõr\c©”á{HoÏ€Q¨TûT.yµ›çÅûí~~'ì‹ä.·ö÷3fPžõqãÝéˆÅŽöõKguUboBRë*>˜(‰úÿ•£ño•ïN”âÝ×oeYŽìØÍ“×ÈçéC..¦âÎw6Ó%dð…Ê’ê&ÅWÒ2¾pQÚׯ+¨ÌC ÿk™¾Z»nªûð°ú ÌŸKªÛ¾£ÝºgWaye ¦-³Æbßj·æxyý”xúÎxYR]oC:ððÂ_Gõ§)^SœÜ9{U€2(™04¬žâá¿É0(>uuu¾-kh±Þ[¼;7‘ßÂä%«ÆJ¶T*)¦O;ËôG×x9máã.èz²ßsר4âàau’¿œfÇ.‰wÒŒ‚7†Ïª)¿¦XÈû4?ÿⵋú'f­uêÂ56AÆ|KdQ)â™óð(ô@¬ÐÏ ÐÉMX²šð`#sÖhFäMn’ÿ^QøÓ›/k‰y·-µÆ¬Q¼¿®·îŸýSû¾§ºúœnŸSõV§;1K½G‰ÛösêÔ©ó>Uo½ÇõTU•1cÆ–YuÖ¼ÅìcÞùa&÷£Â#C,pؚĸ>kÚº Ÿ¶ú–UƒLW -sÆnÇ3Vq¼ë~Nšþ£ïoÖücèÇøI»~LÅ£{ÿà- ÆúñH8%_èïM²Â£wöB¿â²6EW²Õ,Ä¢p†¼‚¬ÅYþ2+­(Y³ë°ð@ ï±&áóA»/š¶¤޵3kXãhàߨ-a荒×AÀÔè<>Pø•Œ'\Á£›JË;(ø}†#›Qz„–ÿ”€‡:4Ãý%m?nf¢ntK*À¯²ælË9JÉØÚ+¡DÞîI§ýYu1Y‘¨¬Z^œ (]YYE­¾f@ìÀâО®lXáîz]‡U×t¥ ¨u¹ ¾&á5-Pš¤íW€}ƒþ@tð‘|Ý#Lõ˜Y’=û´sðŸÈÜ‚¬Æù,w#+¾Rñ”+?‘Æ‹aÖxÑÿ Xé0ø"ea)týGÝ*Ô¡wV®wëV^ªÂrf%xB(qÖ¼¼4>šüWÕG¶#ÝñŽlWU<ÐÌøÑ»XJVѶ·“l÷‹¬Á¾RýÄî$kýDVrÓI¯®£é¤7:ðX%Xà1¾N²ŽEzùºw–Ч;yÒî9ïzÀ9øOÔ%~–ã—~¥áu©ÊÉ—*ú=±ªªÄçIÑx‘cáy}®öY(þ£ëoÖ•u ±N$«^¬jŸþ î®»ÿe\õ‰iXíñœ¬]Ùã;Y-¥r‡ö×ã¬ѲŠ&¾>º!¥zlYÉaVHVNÔ°Ï9=‡‹]Š=‡ý˜°ÇmR¯ÌMÞýŽd»¯OUC ©JUiT}rñW¾¨W'ŸÚ¹uª¸)Ê¢„é÷ËF"YUþ#ðüPã×¾Ÿ„çê&Ü‘íÐ…ÏèÌRåOÀª‹ØwyzÛém$«ª»O²Ñßþs? +^FTÛÁêÝßIEáq÷%¹ó&™›¬‚¨~ç >îMÕÁÇ}]±áÔ–â»wî»A†ï™? [Ëú÷Nteexnî(åæŽª•Ÿ«BºdÏMTÙªpÊ¥šnqÿqîSé?šøØbW–û¼èXmW6ñÎx*{V_ã»øû©!VÃjΧðsã»VL^jï‘Â… XkÏQj©Uôÿ®Ð6œ×ësk”õÌ©n~ý[üqòǸþ-ÿ¦` ØO‘ É:G¦ôÈë”Ý7â‡ßlµƒ"k¸™ýÇãísRùeŠ2ª®vòQÕ=ÎQƼJÏU­X`¡gžQy~ ÄîKƒ·È°Ü°E°]Ôþ#ðüPã»ç:—t¦Ùd¶\T½/uÇñ÷›Úøãç;þسù:¨JËc-%'¦ eçÿ q“Õ ?j¼"/yh†…¬4ެ8¢Zišñ¿ÂùÔÒ1ò|JUÿ§ïuð>¢¾_ÄÿÍNëÌÝ;hxw¿NU ÓJ²QU7\é¹jó©„Ì®bT¢:£¯˜³ÊBá?6ñþ£ëo½J°Â1Ί%ˆóI UY-IƒïÙi4{„=ŸrǤ7ˆª@)HˆKçJ+†f˜4ÏXþ8C×dÃ?'j؃1ôÅü ’•NÑò×<› 3Ú9üŸ’ÕE<Œw߬†€V‡÷z—E}àý^_e檴 p¥çªtë¶¾3úŠ9«,ãªë?ºø±g’lÍY÷OÖÀ¸<öŒÎxªxÕ|†º’aØŽùªUe—…ªðFõ²Óë‡ ó1Ú;“{ EFÓ0`ÿÆãDÅR‘¦ü+’UÖYiDåÙßÑ4ë?ŠY`|B‡¾s2ÈÜyip›Iÿqã»>WÕoý §Vœ¹áTùüGÛßzg#ø %–‹ÏD0#Ü 3žª˜[t¦i™Ø¢º( U×,Ä]Î125Ù|îøNÅÌ­fwØ7w³ æšíÆ ø¿u+¾ÂŠÙÂ]¨Dµb]ßÂK¦ œÙxbWê Õ›7|ã•Ð’ú‡Xã•›•®ü{UÝÖljcù™G•ÏôñX‡k¬þ|‹(ÿh)IUÌa)ÿlp 3ùlúîÔuPUü]D’ð—)©/7~4W‰¸t5å¼J}±ûV¿éù Xõ0«§†zæ ËVM©ÃÆ;>¾GÔ™Õ^è ¯|ø¸gF:Îä£jaZé»ö^)74C#jîwr,еSõlõüGuØ;1éÌvÏm><Ñ)¿}ªò«<½ëðVZ ueÛ DçŸ+jÕy‡–믫J6V{j ý±’K­>´†Z÷ÕáQÕ–ïý·&þmZ:ž–¾1ïU¡MBå~¢åò ÆaíÀƒ:ä/᜗:KÿWžWOÒ &…­ŸªºY´ª®2fìùñ7cÆŒ3f̘1cÆŒ3f̘1cÆŒ3f̘1cÆŒ3f̘±åg¥È*3fìF5ÝLb´‘¥NŽÁ2#Tf=Cé`!–üZG¯Ue꣇‡e‚Å2VéÏ<œ1mkS¤ÉåÅ4iÏ—*.š{Nü8X™aj~ŽéïÚ€ânAšx,ÿ—×%fE:Ã|éY˜DV÷j žë¬Â¢Úlg6Â(:«k~Œ¥÷MöMâ×5?¦4 ]WO·>ºøè¯‹W¥È£—Z”iGü|˜QËGüJe´çK[YcÕµ¹pmjE\f/¾ÇŽ8&¼OQÿ3Í ‹âœöý.3t¹êt2'½-Và8ßùá…pƒXµS°rÇY#J!«ûñQð¸ê ƒ"¤,ub×@F­³úKß:¾uÜ^íùiy©ª[]<.Cw¯‹ƒ¯+W\)¿ïb¼ª k¯r-¡åƒî.M¢t¤Ú€ÔM¨‘qÆÊ„õÀ²þÓÛ°§·¦#$^X$žÑ"œ§‰½»ñV`•TŠ4™máÒ~÷w%Pµp1·š|…+&UxÔY‰Š8«Å*Âr²8:£ìæ¬ôàk7QЃҀTªºëâ“Êú¸ð“Ö$ˆÛÐŽõÎÆ™¿ S>~§Sü®õµ„jÌsá­:5Þq.w°&_Z.ôX=•ª‰ü:Þˆbwë`”ÁÒ _àkd‚{'¢Ê0Û:ØdÇÜsÔþ#ð«q«¾i!224Óö•ünq‰\’9„-‘ªKUTäsSU½ìuVo•@;¼U®³zÛ>^ú¡=¼—N²Ûö•ªîúp¼¼>oõ…PÁ¿O…ÇÚ  @Iûêú@à£×'G“j5©o¯*U®>îä^«*‘e›w‹ä>ͫʧ‡×á« Q°†”5 Í„¯Êç†<$ç#ž5¶JÒÙ»ñ¨jÒö6eî)ðÛ_ ýîùûd]±Ó2‚°–B:À‡ª^ò(*²:8JÊÁÑYÕS鬆®òÒïKÝ—“è ]U4_Ærj¤{Üõá5’ׇãaÇ‘/íyó—Vÿ?“ìG¿tÿäG¿¬Ôõ‰b@xPUŸä7O3§|ªéª ÿI°òQ5ÎÝQü³GwÄ *(;³w¢f·0*×PðUU<Y¤Æ”ˆÿñ¶v†²¼þb¡ÎtÂö5{2!ë,}©Š½ìÒ¦–”:)·Îj2Ok™Îª’' ÖŠ0I.q\(Ä%ojQ˦âÄ–Õ‡ãa<ê¶ëÔ‹”exÜAgt‹û'£[d;׸Ûù«ªú`rÈcd»ìž¦–j ŠP¹FUÝ$”UeJ½I6ÙTü³É&Z}ªªîz¿Þõ(•z÷ vfu¨zÏ ¿›{}Û¿ßÑåÝžlx“ÎUõZï謊Ç.×Y岟bÌÎç%»†Ž—¨nwÀ·@×Ç©¿¸S9ÞÖ|źs%Ú>Ë_õo#§üž9Ø\¤EU~ÿ/ÝÚ÷t(r[½QµªZu™ûOo;°ŸËèÛ!MrU»]ÛÎ0TÓêcpDÅ‘Õ?.¬õÚcÎêPuí±Íç¬F€²€™û²;œ¼ªŠL_¹©ª«³ŠùSÞÓb}¸R/ŒJ_Ëç+ßÔh¥2$õaµ£i ­UÕÇ©¿¸S9>¿Ð„}7ª6rÊ©µzuùÞíùà~国4­ýoĨ 1Jœ­€Ñ µŒ^±Ì˜ãÀ~££iCÞ¸5Àÿ5G×¹]úg…þõwö¼sùn zTuO=Š?/“ÓÛýzƲc>ÚþΟb¶#7Ö»cg’æk¿þÞ›TU—j÷©*-T=]Ýúèãuu}¯£>ݨÚNЭ Ùø[ ]â”:%/_› ®ëS÷z]6D.Ôm®‡ƒ¬ÄìD7UÆŒ3f̘1cÆŒ3f̘1cÆŒ3f̘1cÆŒ3f̘1cÆŒ3f̘1cæú£ì´>ÞJ4hëPP…®+«§A›;'G_®XK¡ÚmL«…˜5I.},wFFu§Þm$S–-¥E-;Õ C3I-`ÏBëßRÕx1¾ˆÒ“T±JÝ•;hΊœ8£ DêYøªJ‚o;´çÀþÞÙYš5ŒM²ÍçäK·¬É°Mµ;šª¾%Pº”Žd9Kîh”ø€nç´D[z¯ÅgVhè,®¥'Cº p!^MÖ(³WK2ªX¥>UQ‚Ä%âö°^ƒ›p8 ˽Ö^#Ζ؄+.@—ÔñgêCêz%É”-Pr –‚¸K¿Xÿˆ ¼…‚¦nÓÁ·>½»×=‹Õ”ÞѨðÅeSvR—×£’L—zªò½Ö5%9UQS ¢¡\ŒW‘Õ«ÙÊKÕö'Üh™p)ô J·”r˜h¡ß žîM0ÊF ¢Î(f_¤R5ñ/É//§Gïä+óª‹õþ£±¶x 1"è¿þ³¨eSðú 5… ­Ö:Tõöf¾ð=+Š7ÉQɧ§\Œ—“µ²TE¢¡ §sü༬ïrÆßÞY®s8ú•&†kíìùû¶ÿ­ª#pSÕŠ5Mà³Tªb«ªDÜŠ[Ng¡5QÒ\sÇí5PB@[ñ8ɨ‘V1ªª¢¤¯¬&ö¦4Wsy[šÇ¾ ŸwÒU€½ñ2²V–ª¶îì7ÁÂ7”€jïÄÔÐÔÐÞ‰d^~Yf·íC©«_‚Àh;a.ÌÇê&†M® i §ÂU–ªººªWpzs`>÷/Ö"¤Ô'OòIöáÚÛ²ç‹y‰Š›€¬:ÏBzdõÃû“µòTôŸq£ï=Ð¹Š­b:…‚°"ü½ºùm«/¾Ñ-/PÜ÷WÁDQóÇ´Íâÿ5Éîþ7Ÿªºúªúmå`ôHý¥%AÚóVµÒ!ÉH¼Ô›×¿¥µ÷@"Q£¶zãÅÞ‹|ëß’TÖ¿þ-ï³*OUý^ºûÒ¦6üº©­û!Èî‹Cw„kÑ|h¢&Hd5ŽLEYày‘Ž'ÙÆ£7Ÿª%½*Ó{èü=)­°ÆZ¯%Ù¿§P »Œú*GÕæÜ]ëÀ•È/—¸8LÔÍwº$?8üñM¹)\į«ä£µ/#ª7U‡fd7'6´\h1ï vI’f”EIr˜˜Ç=½1øwöÜ\òWKÖžVZÄHKüœgþZ‰ƒÍ¡$m¤äx·‹ÉÒ %œË Ý`j}ÔTuTöQJZ¯è*H>*QÝxkLFT¿ÀïÞy†“UÕÅ¡-†)‘ôb¾®iA¨Ùó|q`Á¿F­'ÁŸÔ+ ˜áç4^Q¶y ´x‹ÎH)’î#Ät^­•?@]^`AÕRêSŠªq¨jgžB:ÅrK÷Û·l<2ï-4¿YŠçKâhgQ°®öLÓÄxœV§wÞP¶ì~ÑÉM õΦ¾‘¸0l 3šÆ…ÖaÅŠITˆÈ€hwJ¬m¼¨¬èÁ¨­™xIM¤Õ¹¥¸|«U7xˆS½³~2ß•?ŠkW1k¥ü½C3]Ùã;Y­•nSÞ—ºÒ‘AíeºXÊYzø8,'‚x‰< k7Kx‘ƒÞÂ]Öù$³¥x¾$Žvë´g˜T#wû“;oðÉýòÂ@ Èz¡_VÐÚ÷mán|¢HÖµïËhåØZg-^TAn«¯-‡ )ƒà–¯@4[*Ô9xKãÅÆ‹çÖÁ²²j>Å!,¬VtË:eù°Ô—Âqn8%oh²ÊéS„(2è\Q‡Ë^éaigéáñí¸F—¸3€³v³TUDV¸l’QÈê…§¬W¥cÝí%’UàåªeŽq©4ŸÒº/í¾U¾ ¥$†_æŸQ!Âä´>¼µøÉÕt×|é ×,È›G<tßC÷¥Á[ÔxTXmf|ì·<©ÄOÚ¡¯MTÙ|(w:ÌÜã_XÚ¤Óþj7w°´³tñ¼å » AXßͦªpÙ$‰^xZ«R±îö¤‘ÕÁëj¬x”îæÖ`ð3=â^±ñll±+Ë—e»QâÙ8g8V ‡‘+þ9MËïë/£ªÀž–oè14snb› ¡ëtXÙÜÛsŠýÉü×vEÀl+@\Œ’e¸,å,·cÑ®â<§(†ÂiõHVYªr—¥Qà O7£aÝíI©‘>Q%dÕ#jUÕ†³|; H¯Ø[bÈÂÁî¹Î¬Ç#ÊÊÆá¡«ó,Wés7NT1~ÝÔém&Ç»²{' \­–㟾· ’bíBKJ¾o8å%·!˜…€$•ªQ—›¨Ïj:©‡/¦RX)$SyªÞ³ ä§ëR°…DUg_Dûƒè»¦ÆJÏ\Ñý굪jßN®¨Ö–SU;~·?¶÷O‰¼h˜ssýdáõÆ£}“6Î(T <ÍÕ_ž4ÉïÜb5øõÔÖ £^N ªöøNŒ%8QejF¼7toç¤îMyÛÓ©ê`)g[§‡/¦ÒÐÌÇ÷Ü|ªºïÁ?òÆÓ©JÁæåuÜG§ºýãLï啎Þ/=£CTÜ hdÊifHºÔøcÇžùæÙâG4öŒ,¼îøóáõ޲`’DÕžÃ{'xý£ÊG_p/5øâ‰@m +×$jVÔH¨¼Š3Õa"…*Å©,å,¡ûH¿JÒµ¯ȸ…T^Qyª¢o&IÉžJUVwW§ýÃLçeM¸ø~ñ×3t¢¢½“²»A©ã6ôÎÚÁrÌÝwɤÊ6œ²Õ¿í¿ Ðò\0HÀL%LªX5ê’c¨¡Æç“@ HHÃZ‹º|NVÜË+7WM«Ã{ü­¦¨cigéâ…à*¼Îê¤È¸UšªÜ7iÉž«Ð±zŠˆúdõ *Ì ?¯gtäÇXõ‘í8îõÌO©°XÍî°:ïô]2üÉ]Ùp^°¸++òÇ>Áø¸A”èÛVÚ›Eí{âæá “´DB.È&¨/ÅÒÎÒÃã56Ÿƒ©AãrxY#Ü•÷yá)ô£cKQtȪó²¦à~­Îð¶ÿ­êõŒÇÅ! ì™;¶C}ʃîÈtf{æ6Ÿƒ$N§üVsj þ¹wup˜Z)zÅý|ú-”wìg+nÞMVjÆ/d+U½°”³Ê~ͯÄÛêŲi—ó:_ixš£ wµêhqŸƒr>©é§ƒ-Íx«ë¼¬)ºßÝ·ÚyÐÆR=! ì–ÓÈì:øŠJ/lÌÊIk‡ÔÃV@¹nåÝ7ï475ãç8«ZõØ KÑJæ(þœUxšzñ1w)^ê \ŸÔ£žözȪ󲦨c‚¨©2fÌØèvª+‡6f̘1cÆŒ3f̘1cÆŒ3f̘1cÆŒ3f̘1cÆŒ3f̘±2›®Nï÷ oŸC–\žõ¯¸ F1Ö´Ø ¨UZ÷JVÌš\®4ÍéôÆM§÷û†gq1z{&³YúT £,ðHX~D­ uÁ\Ágô÷}xþ>½+Y±ÀèdNÞÌ®†ïo‘l ¸Z´X+F¥Ó[ž/jÃÿ+S~2/jVîò¹8óJ»r^­Ûïè³Ô‰]J}JÅï é*Û<£í2Ô°&£JÝ£ë¥jOµöM@âѯ#0àà¥Oß[‰úS‰Ê÷·°‡†XÓB^ uzùe…\§×Á»]…ïýd®ßüd.°¥—/„ ÔxXE ¢f'vÑëO»_´¦“‹HŠ${è%;•kçt7Þßm¼ƒÅ‘|òúd{a¡Þе^£Ô…Ç›¢ÚŽE§†5Ê‹¦ÑBr]W·ú¬=¨_¹šÑÃSA¼»†f(ø0 …ÙoU×5Çq ,ë_\×lÿuz˪uz¼û㻲¸ö×oâš=Yiå÷Î~|§ˆ 0+¬=VŒÕòµö”ò…¨J—ت ³Ý/²›Þ½ÔzMÖÐ\÷zCåLÃÿ±Ã[Uõ:|k*^8"¶\WÙš\ .¨ïXTjX5 ÎSk½F‹u\”1çƒ ­ž—q'Žöm¿Ä£/ñQ¿”UØ•£*«AɽDNZ×®?_¨[#Œ Ë4þ:½^j|Â5LÊGù­ ||©­ÂøÂBW{6[uQF©¿¸µ.1Š´$qFÈí9´Ç‡IHg)\÷˜ÕÍàž5°ê>CÃ#ÇÃuöXÜZ¡é$Ÿ#*<Èß«sRÉv¹1Tj>J¸ºm>*§«ãÆ#‰¢(®é Éé[F¦hÄsשõ5õÕ*jQʼ–&š†è&×ý&Pêˆã»çŠ›L®Ó[ÞQ”áª1*üÔ«‡ ¯š;¤Ÿ´X}ÓI•ΰÀ[Q„?Þq¨Q½Z Hèóûä÷Ý™•ÕñÖžV¶ŠEsB’¼CÔZ9¾éJTK¶Ë «¢—ÛtuŠp¡«Ë·ºê /©Oïì±´,.k¡Ud‰sƒOHMg4=-)ï+Ø¿èý“h2Á¹N¯ƒw÷/r|WÖQn=·GIUù;“˜'ª„j,¬ÔvðîfñdzþÏí™p¿e¬¨ú$õàºÇV GTYñsBZÄO‡1pçj:ü˜›¨rü±Ž"n©TUSCgœœr Çve§†¤AìÛ˜±™Â˜FèC+Õ–#‹[J–¸òTeý'v9-Ô3 Dîm¨Ó»Ôuýuz¼û㶘?ÎÝ0»• ”oËÿ÷ ¢ÒêãhÕxð«u‰YõÐ &“·î§‹»_”54×=fµÐÀ07‡ÿkלUÕð0‡·]D:Ôøæ‚ä‡Ïj±dwÐ/+žÚP¨¡GUVóäSŽç<ù”\2¨u¦»at´cÕ^zYÜR²Ä…mCÔ+ÔÒ7´¼þ¼#‹ã,|ú:½Åi™N¯ƒw÷º*|^sàÜmå|”X>Ъ^ýÝ1\—#ÁÓ͹” &˜¤%§{,2À¸Uˆª>ˆÝŽ.c05zØ#ª oëg…öNà£×O+©©QÊì“­’ï ‚®•¢óÅ,ÎÌË—Å-%K\ù´Òî[S_`ýyŠ«+›úb÷­¹_9Šë4ÞÒð"£U©ò+‡çÎŽap’}²I­¸èè[óM,Bª.ÞNtñœàÇwªH—Ûj”漬…ü¬E‰ ºïœú…žLÒÍ߀ 0DX(©kÚµ§¶¸” …NoU§÷{†gquz RèwkÕ§Rx'ÖuZà[šóÙÞ3'Ÿ¥zÝyy²¸×“%®ûsŸ½¦ÿ Æ•úàü3jYF\ÙÚs¸â÷=m1ª&ÔúŒVÙ•ÂAɼ?k\+]Æ6yïモ¾»1ŠÃêgtÝOIW7öaïl|1«ì­É è©õÎÆ>$]e 7ÈÚØ¿W¯I¼e?Þ¦ÑL#•àÿ>|Çÿ½ó íÒ­±´]ÚÒ p±M5M­UdIú² 61íýÔ ûeǼY½Gððþî»híO n‡Ô3çÕ­R:^×k_'Yuuq#ìáçpõ# âJ¿‡Ÿ‹¨2Öx¥™ñël>×ÿOjª®ÙÌõØcY²é¦ƒ¬!•Ú¡+ðsZ/üíìÞ× D‘}Ïá2ž AƒY m™”®ˆp®c#Æ<'x»ÏSKx–Ÿ`å¦*W[,e|‘6â·BÿH)㶤kj•ÈÙp™»D¾U(2qzx‡¨9éÕÒÉ*tqa™/,ê Z[¿¯ 0Ï>ýìÓ¨§ÖœóŒ…xN)fïăûÃ@qÕ¨‡ÍÑþFUÕ¿—w(·¸a;Ë‹ð>Ò|T†c|Ôw2 Æ÷µeiT]*æ!_\•WG{ §è]¬^ÐÛÝ…ßÉZ5ÌÔí¸t|‘6ÎoYHÈÎÈëßa齿¬ÛþþO@¿=í«„¸Ä my^ak俺¸ñEü.¾¨ÒÅuô‹îzà®]#Ù¥¹ hWvü(ëî:Ô,•ã6ÉõA“ë߉JçÂïFaœâÞ\ â‚w©øW×ô¦ex>v¡<çë?|ý‡¶Ô&i_¾q†zë Ïð”É] e²R_Ä7©|& c*kÖ€4fÔñÈ,J «U—øÜ_Äh“ø\1A¤„îîèù•¿ùµ¥÷ºu\·ý-‰L\Ïœ^çê~ÔP¹hrÃÉ*tqa0¯ƒfTêâ:ßMUùÅ;qÔ>µet‹u¹MÙÏYÃÖA>†Ž€á«þ).,ù ;ɦïCÚbwÛjE)øÔW°â¾ÅÏ …ÆFÓ«@þs4¢e¢6^äµQ9oI}4Èx<û“Õ.ÕB?¢–BÕÂß«ë#ˆš$‘åHxì.x9,•Ìa!®RTèpgd5ºÿ‰¥÷úxB·ýeŠŽü².L7@¥*ïž AsduttSëâVUaà‹RU|–I xG¶߃$T®üÃëýñ­Ÿ¬›Âë#_œùIF÷MÂŒö_Xõ@fõo÷ÙÂQ°IDÍúI²¾I?|÷%Ž¿÷¥$Ûrê ¥ž¹{œŸ‰ôÌEÔÛNĸÜwÞ•ó²qqé?ÕíéâDؽ}­}o•/`Ó£ªCT±i ¬ñÈ/§ywãOº §rD 9©ï—YUD]êà˜ Î‰Ãú¤¢@sÊåè]ÙÁ¿+'UaL}Ûû hƒšrÌU±Ýßç'7º:ººsU|k)Hú€@§ôáˆñhßN¾qž#è›ÏµÁ8Œïy­Ë­àX²ÇÏű#ö¶wýÙ ´1!•í‰ÆR'7âçfÈuãד»²0Šù¾¿Ýp¤!WˆºÃ–W+NmÙp¶\£ª š-‡ioD$Ï£ãògúÙ Ë…%%ï¼ÃømÊíV€]”̱œ™ráw*²ÊZÞ}¿ùy›+L» N¾äoçu©jÚ}Îxt‡ô•“¢ƒ)lSŸïtuqõ¨Úx±ûÒém NyKÌUª OnDbƒhf}ëk¼>Î6ÞuÀfTï%þøÃÀ{‡ö¦ <ñ®¸’úÛmj¼¤FÍcÂmU¾ï«ì¡ùcßò;°wŠí8ž‚@dG¹FUAµü&©‚ ÉçêÑË=nðqÕ5]iP¼ˆù}§zê:¹kâ¼¶‘Ý-¼ÄÊ“» Κl*'U›zãax«W…µÔFÖdZº¸zTí¾NR“s+’ˆ#«ùø wÎÀzgi:·°MB„Àqø¿žtúMÐ ül#¨^Ö'G™ß£Œ*^ÚtÛ{œØÕ=§rEý¹êR“ºnQù$adJlÄ02%Ÿ®TÚŠ^Š„ÔÝ<Ó~g§?ÖOóf*U×^óÆ?üœ:¬½N¢Šž”®+›o¶[àP¾UÒs’|çQ“»R']çVó-L)H K¿äž mYËÕnµ\±¿4}Y©ëVÓD½ ÎhÉÍøRð©ºê;g¢Õ-©û'…3aסæM¨ D­h£}´1cÆŒ3f̘1cÆŒ3f̘1cÆŒ3f̘1cÆŒ3f̘1cÆŒýÿk¸*Èš4í`Læ$bÙ ªòœÖUêì²ë4\dtœ×Ö'žÿ®>…HÈ„|Õ.–Ü+Y+/‡GçyšÎó2ÅOCWvþÓò¹3v,«'kiaåÏÊØÈ ­ô¥W³¿‰Œ O6߯Eô=Hv $L°l¹xI¾èº/†˜}Š^]èÚøÑÓxŒ™\3Ôè æÉ®5¯ç °¤ÿQÑT&Gç9AÔy^Žø¶¯úÿiä•}OÜó[5Þ±Æwq¥4,s JJ×ÖI.myEÔ^ë%ˆÍ–'VñB~½dׯ‰Î}ã*þj÷­*‡ ~™ÈuÁTå®k†õ¡\f†KЬÌ*¶®Y]›ÀóÙ_v'IÙÖ˨æºáëöé‘©6ÒXš—oÿç'Ÿj&uÍìɧnÿgúèT]oíò„ÚŒþÆ9”«©ó\*¾wVHÓ–¿|Ì Å>Œþ:ò5EFø'J ¿‰ËýÉ`î¶Ä©!ëòA¦¯˜ØÃê® É ÄÙçe~ÀÇ_;ªÌð5çױϊ©ûŒà¸é•‹m_&þO÷¿Æ«ViÚÅÝë<}"«éºð°hW9ÖX±6öÐKPÆ£ G…"ëÆ­£?¹ó/Á÷”åO¯^Ø÷ëhC¦HáØÐLû¬cß«¬iÂÌP¥ªjßãÿ)}ûûÐQQÕ¦‰#tM§g¾°9ÿ ÆÔxGw—‚ïÊÙ~d;_åJ+ßRỲ¸<üõë;¶e¢ŒÛ ÞÂ5/Qs¥/5º²N[òÉ!´a+„N‰PÏb+üѺ’éIÆ}´ûÒà-ƒ·t_âq“U=–MKÜÊžÙYÇÜþ5nožá*ÊÇÚîv—Þv·bŽÊŠ{]¸â¤|” ~ Z¨{-èÿˆú¾¸ë‡^ˆý›ÿFVviϵ3™YaÙÒü˜ô«=6nŒ­ødS;œ-ŸÍ´^;°uꪪ^ þ|ð¿=úó_Èw+°ú"‹ŽøÊàiÝ&4¡ól“#´w‚“iíûr|W–ô‡œ3Uø$Ûý"Jì~‘ŠçO@]~tÎâRJV³©MH¿w:̦“¼ìÕ@?ÿþ>ëO¥Ëé?èvdrº²tS§*$í&~1>‰ÚÀ¨«äÖÝZ}^ùnÍL(ôÆ]Âf*ª&ž*èQž’aßIÊÇðÐê„|”Œ3Ô*°—‹÷O¢ê?ª¬úç‘Áÿrÿ?¶*ñ¶³4ˆGyz[äk/täk—‚Q–ÏÏ–µÏöWC¿CÙKºk/Ýúx§¼5×|ùäSÎ*`’ÏϹγ˜Q±ÜÂâ¦E¾w”›œy’ o ‘ØK«YqTøbªúãß$ÙÎóÏ-/PtªsZNî›KÎÛQ¾¹*>§‰Ý¢ì‰ÝåU™@»Ð"JQ;¢ÄϹ&¼ ŠLxÒ;+Tã /+¿ôÚOÝ赟ÊÃ>è» (T²›þ?Ä·D^N*©'Âpöï·öþ$I¤¶õWÖõÔW~Ó =üæJ|ÐÔ_‰óUTeÁÄ7Ö°P`ÿ;CYjkà=ßsßU[«åmß™-¼úÆ;°};³2|÷¥w¶€o«1ƒp‘0‚Æ~>†ð0Ûßõm·õ @JïrÇŸócÙ·4¢ÍœØâ?qÅ÷\ÕUUéIV?2…åL©‚/Æ+Шꄾ< ½Ü‡^TõÛÛ ¥?t©j\ÐJr£¸ÜҀܧ˜B*Á˜³þŽ=kÿmü¨ ¿þXï,n}a¿Þ©¬Õ’¹Iaù¡dìp×·öãlñl{\ïú6v8”¤Rµªê…Ÿº·­²Ò²™ä¹f¥1¹ÝF|ÕÂ;äeó=\DÂß ,D¥:ψ¢rñ˜xQTâ—Ž’*|{n¶‰S 9~à=ü}Ó•¾ÉG~%jû:D…©j­<Óáž«:£ªjO%Œþð ï$T8!jÿìÓÛvmÛå|'O¤‰Ð—‡Á¹➱z\vsIv`ÿÈ”¨Ê¨jµ-¡^›$-€Î^¬ èG Q¯¡{ÛmŸ¥¾`ÒTûš#Ûc‹Öž­ã¸Ÿ|nâ.ߪNŽ$Þ÷O ÇÖÄûÉ«šJUV¿áìʼ›t,ßéÝýâjÆg¶-÷…þûmï­ðNV¶£ó „zÌþ:ÏŸÀ—(ÓΙ*|1UÕx=Y±Ök*üƒûùt« ÎM³þÏ÷NÈåNÝDUÏhK™«ò ØžX(刄Rvñ!±#B_—«c¿xï€R§·ʉŒªo¶E5Dg>?úf›¤©XQ‡¨QéË”|@‹"ÓÕ¡M‘—£ìÈveC×>ôÒm×O$HãÞ#]Y”µ ®I=ÜÁŽ)_Àëë`©‡ƒkø©¦* ’:aØ>!X³çË!›ªWÖ^Ýô†wÒ’œ¶l'è<;øvwgIÀÓt¤_Û?Jh”Ÿ`ƒ#E:fdx=¢–6Wu<ƒ†ÒÒöÌÛÓ‹âd2¦di¾×ŸË‚Œc#h¬c4íßûÔ?<´çÐHº¤à»FYo´ûVp¿Nñž;„Ý·J\ûÀ ö¶‰Ïÿ>„` (Šˆét¸3{Û>⦊Áã;;q†ºF±‰‡xÝ4Yc«ã‰µS¿$w¿. ½……—dÝÐa*k£«ó|£ðQÕ,¿í+xñ’¹ýs^¨Kß«ÒæªüP^Üéîn€OÖ®L5m­IÛwl?-.ʲÓÛÒ÷J8 §FÔÃê…Õ ýB.-:2…ÀÈ”Ý!ÐÎêÌ/AÊ#bÕÛ_m%ÌIÄ(œ”â$|¼PZ[¯÷¥ 1½G¬{^ç#µ®òòÄo>×3×õmèw?'Çcx¬£·[ü^•:W•k/—`'=ÿ°Ð~Ö¥ÆêúWÒ(õgQ¶ªbfv7UŽzÉèMþ3µ‘©Æ+Ø‘Kç:ÏÑ4|GñCtªùAË+Kôÿʨú{@©ÊÐÆ– ±[0ø5íðý±ÿE›|yn4MIEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/external-link-icon.svg0000664000175100017510000021101412370216245031207 0ustar vagrantvagrant00000000000000 e-mail mail MUA Open Clip Art Library, Public domain (modified by Kevin Dunn for SciPy-Central website) Jakub Steiner Jakub Steiner image/svg+xml en http:// Submit a link numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/external-link-list-icon.png0000664000175100017510000002126212370216245032151 0ustar vagrantvagrant00000000000000‰PNG  IHDR  ‹Ïg-sBIT|dˆ pHYs.#.#x¥?vtEXtSoftwarewww.inkscape.org›î<tEXtAuthorAndreas Nilsson+ïä£tEXtCreation Time2005-10-15 ”W IDATxœíy”Å翿Ȭ£«ªoI-µNÐè@B$¤’Œ9½¾Ç0f$! ìøÙ^÷ÙÞõŒ_¹<ïyvÌŒ3ž™]°@¯ÁÀbÄT€¹Íк[­–úîº+3~ûGfugWWw×Õ*ñéW¯+£22£ª>WFD3C¡¨¢Ú PœÛ(UE ¨¨*J@EUQ*ªŠPQU”€Šª¢TT% ¢ª(UE ¨¨*J@EUÑÇÛB‘ËLwãpð•‰K’â\b\,p©cû-J@EEPE°¢ª’V E> `’#è_-0®ÀÍ9Ás8x¼RéS”Çi/ €…f9¶{$ €9aJÀÓ„3A@E… PäóÖØ›÷s8øVqÀ÷ÔÈø[3•J“ðÜb€€ÝÆ™  Å~¾¯’òªrÎ@¡È,Möæ^“F]æx>nŽY,JÀs§Hoïû¿ðnå’c¡:¬/h®}ÎZºauó¼Îá`4Ïù«A¹Å/¼]¡´ £,í/r€kL-`ÿ=~ÅáàáQviðq³#ûö~`'€øä8ñoÌöXâdqçIG@;…"€ë¬ã<F¡È[~Çáà‰qÒ4Ñ-…"MÊ Žr8ØYñT¡ )i° ÀÌ"¢]àP(ò0‡ƒ;K=wµ°sù-æ°»뇲Ä~¿,â½Lƒ5’f)¬bÍÉ)y›ÃÁ”#¬Àã9û­PïØþÀ9û´ÿïÁp <®ÎÙ÷%]9a ŒÏ ¿&-¼àÚ84ízáX-ˉ=…"]¾PÀ¹*IÑ"Q(ÀP¸‹ÃÁ#O•M)NÏÙÞ àçË ï°oÙÍùo`¸´µ–À`·Î† H¡ÈÅ.à~s%ÍÆßk§'·#|‘ÃÁ}ùßÚ˜8勨Êáà°‚ÝùÀ‡Š,p+¯c—/Q(²¯ˆb°,ìÁØ›½õb •ŽVüåwÃ<ÌáàòÈ7 ÛüŸžü‡ƒ¹ssã} Àüœà]þ~”(Î9Å "­Zë7Ë™öçlÏ¥P¤¡À¸1XÖ,ϳ2B1_γ:Ã0(Yk:¥ó\&€_pŽVXãicì_Êàƒ MXJ¢ÈוâLðhζÀ×(Yh{…"Þìs'öèåÜå@.°ÙÙ¢µëiãñ^ž4ÜdOV„B‘V E6¸#‹Þ‡*½J‚=‡ã"{3‘.5I °FL5Ò»Rœ EðÁ±œ%Ç~à÷öy]°&¾Œ‹½bÂv«r1¬‘>Xƒ<{`6õXî¢Pä»°¦Cζã¬N'¬åD ÂþA](Rê™d½ï;-Göï™ÖÞvh¦iÙÅ}@ÀΘ×wÿ—ÿýDÕV89§Ìò㯑«6æ¿ÀM°oÖÜ4ez[ðº›^©oš”¤)uHCƒ4uÀÐb}Þ·_}aÖý{ff2{’70ÿíÖ{㯴PI<·ßÍU›d^ J@Ûn«A‚¿¶îdéöú’«¯úÜsçÍ_Øiêi#M )u©%¢ý®ž}rnÛÑ£ÙåÞ$ˆ²qklç©Nÿý›wä3Õú”‚êt°é¾£þþØßÁZQ‹Óɸ÷ům?¼¯`h:8ÄÚ“)H†æ©©¡«®ÿÌáU+WîÑu-@€éöí›ý¹+£N8L»}K`é©>w©(søâÃll¼7úÝ@f2ï3=¸¦ûÄá èµ^¸j<ˆµ'‘èLR€I,X¼<~Ãõ×îñzÜ)XÇ-÷oö»žt%ð€ñÍm·rF?-QŽÂÆŸ ¼Ê„»p&“ö=ý›Ÿ­Šöu»hp7ÔHÍíB¦ÏD¬=™­aò ºîêà~¯Ç†%á¦m·ùæy¢‰A#ÂW¶m©½¶ ç. %àlÚ}„Ÿ@"™¬<ùÈ…`CH@ƒ·ÉÉF ˆIÀL‚ZýäYúuëWpéšÉ€F$¾zÏMroàÑÐ\^€ˆyã¶-µv*Ï],JÀqظ5ú$€'àäÉŽÖƒ{ß €Yƒp{ û=`C@¦ ±¶$!0‹ú–ó<+—-È®M=Åm¦·œÊ4·Î˜íiiébþÂöÍþÛÂa*÷ö‚°´LìºàµŸ_`¹5~€ AFˆ¶%¬Æ is/Zй³Z¬¥Ó«ïßì_ªÒëu ZÙ|ïÌ9óìÅ+éêÙGü_}äF:í.½* à–8EÀC‹ÇêÞ}ý…f€„K‡æqƒ¥™#ʈK‚!@º¾zõêd]À›møé_Õ–{ÇÍ ‚Ç%híòó¼ó,ô0VÇjýßüé­4Ú"êUA X î¾ð^Ø·ûÝV°!hp×{I²K BªÇ@êDiî׺ÕË£𘒿zϤy¢ @ º ¬Z2Ó³pÉR?‘€‹M—ÿïØP—{ãĪ¡,¢%íG<Ä$È]ë…ÂêŽ1¤ˆO#= ÁSf¸.]<;{wôÙžLà ŸNA " MV\8ͽlùŠZ¡é`ž©Ëïmý+_Ó¸Ç9(‹@KÇ^‡½ú‡{ßo±h.ÛÉ–„Vn=˜A\¸èb1µ9`Ý¿ƒøÓÛ7ùçŽuž²!$ÀFÜädW†HÐÅó&»V®\U't70]7Eø¾Íu¹÷O9å(‹À® þ Ž>Ò†  ¹]ƒ9`VB3Mè?dÕ…K_³êvéÄ h,请o"×D¥Ó.‚­Vo÷ûQŽ·§A f5ék®¼²^w×&iß»o³ÿü±6±(‹†^€x<êêííõРyܦóP1Ì,î29Ñ‘ jj›Ü«–Í“@Àt"ÿ—DYE1èù ƇaÎÔ:mýºµõîšZZ øîý[‹Ç?èÄ ,M—{³Ï;OvÔ, ¼.@ÂʳE1 D'aÄqÞÜžófL¶Æ[>9a×líúß°@õí‹sß¾ˆ¨µÙ¯]ýñµ ¾Ú&A^f|ëþ͵—OHZÆA X$yw¬@tvvÔ€! {]`€A`S€%AšÄ,LC woÒ "ÒV®Xæ ¬+_`‹N¥Ó˜m#·ï¹ÿ@’»ß€Iõ5âê¯m¨ožêàbð׫qíZ Xþº;»<4 Íʭƃ¤@&ÆèÙKò¸uíãW,÷¹ÝnbW2}»âýƒDV.8Â@Ñ£)î|³`n¸é뮨ož:Ë€´eûfÿg+š–qP–í€þ¾3k ¸¼.H»"í–°4‡&éɽ&Àµ^mýËBh0%¿¢Å±UÃîûIüxš;^雨qÑUÁÕõÓfÍ·§&ÐMÛ7nµžx”€%À’@:ãh·Ýc½,HZuB¶¥Œ78z(4uRƒ¾þŠå]àã[Û¶ø?÷㯕ß:¶fäÔsIve¸ý½iYãÖ°îÊËêfÏ_’½oòõÛoóÿu8<ñæJÀ`ÒŽK“cÑ€½Æmµ‚¥xHº¬ŒÙþÁþ)NœLƒ͘6Å}Ã'®¨óûjAL7ÖÆü?Ú¾%°¦¬ˆìÒŸÄØÇH÷|ìù éÖ®\¹4°`ñeµ¶¸kföÿ÷Gn¤±n…[6JÀ0ô²îŒþ¾ ÄZ 0Ä`î—+Þà6€ÞÝ1[B46Ô럼fMýìS²9ß$0¾¼ý6ÿ¿l߸¹¤Nël+¸‡3Q“Ûvv#=`èBÐÊK.ò/Y±¦Þöÿ’x­ï;Û75NØp25'¤D¶oü3€Ö…¯0/»ìÒ4Œ$ÐþBKC›ºÕhè`©Yÿ mPÀ,uç×Pý\_¶¨<Ñq<ýÚïÆ:ûâ2çt'쨃Àljd;2z‡Ã' ‘ÿë ,_¸tuÝeKæx‘î3¸íÙ‚î  á&j]Ûo³›AØõáÑä/?Û+MƒÖuþ» ¢œvÃsÎˆŽ¹µ¿¯×ªç ]cZ¶8”ë™Âê#”#³£þý ÎDMjZ€æS¦N÷ÜpýTwû±¶ÔG&µu¦¥âdëÁ`Àjhë€Ä!í´¡à0‹L3·=ÛM­kÈ7Í»hþ,¯Çs]ÓËÏ=Ýc©Y†!Â÷oløÁ†í½EVc Šàap;ôõõ[—ät¿;§ø%Gћ߆ĉ4·?ßÇ@Â%ZgÌ©Y³v}ã—>}ãÕk–ùÍŸåiih½@¡ˆlùЬF²É|ì¹D$@DófOó¯þT³îö €§°f„ïÛ˜]ÜAÇIª*‚KcÛmuD¸Ch.ºñæ[¥Gq÷®e¬âÖÔ M»ø5 kMºj5ÔŸï#_«B·úñIœIExÊäxÒ€išÌÒdºGîÕHóoW4ùuBº7ÃGžî*þÝÐry=5,ðDÇ»ŒO?Þ™Š÷›ââÎÛúwÜA¤„F.ÒÒ`È´d3-a¦ìGR"5‘8‘.ëô ýÔry#ˆÐMËgžþ}]ÇÒ˜’pϦ­ÑçÊzwJÀÒ¹sà› ,ŸÖÚŠk®¹Þ 65îx¹ñ9˜ ¢ÈÜït¤~n M[Û K¼ó;:;íOÂzs?Ûpoô‰R­!eÀÀnè8ÞŽd*eu@fúíV0ò@ßG >ú‡N°É~¯›®ºæ†É­ç-ô þrûæÀ—J=´° 4]¾€¥d<°Ï È×⃻Ö=¢Ï¯Øù`PîCæyäÛÏyœŠ=œäÿ?™–^·Në>~õ¤ó.¼´Ö~õÓÛ7näÆÑ.>ް n¹;Þ ÂÛðþ»ogXšC ñÂ:ŒÒâ,ŸLRBH Q¨lùöËc´sd%-šøñ4|üŒ„éÒ5\±&ØtÁ²5õö«ë£µ¯{-[ X&,ù%qìÐîÀ‚¼“½¨Ÿ[Œ”mP²|ÙÒŒ*VÎ9O¾så>/XÊdW†üæ8Ò†¦ \¾reÃÒÕ×5|Y æÿö}›'׌ %`™žÖ¥2¼ôê;ét*&DÜ´¤NÖLõpF‘AH€$œa\ôc˜¼Ö±Fä„c‰èLߨo:ÝoòþG;ìN ´téÅu—­ûìd°H ñÝm·ÕÖòù©Vp¸ï¶À"| š;½A»bÝ5Íni°y,Òd¯éü”ypuôìÅ5v‘íø:† 0Ö·”Ç”¡ƒÒð0rv%†a0E4oØkymÔÜ‚æ|f ü­^´ÿàáÄw<Ò!Í h7ÉüÁæ­‰Î1’®,¢Áë]´uƒo# º®\:Ó}þ’µ AÌ&Ë“opßÁ$0(9E|:(e±×Ðò¤-{´!ÙÏâ”rhâá:¥SFÒˆ.¸¥žF7ìýèP⥧~–]§ÛíÑ¿uóôÆFK§*‚K€,¬ë¿€@<ñAü’¹ƒôü[G2»ß}}€r j¹¼ZVÔKÁl×ÿ0v‘‹1ßå×´¹ŸŸ‚š)^ب-ñòÓ??n¤@§&èÝò“¶qÒk[ 8>ãÈ7"ìcó<57¯Ô¾êÒè"+:°è¹ÞE‹—8Ÿùr´ÁøùD´åXûx›]ڼϷÀ]çb&ÞõÁîèÏ=zÒ”@⇷E ¸ª‡œb7W¶Q·g×Ãõåk}Ÿ¬÷Òµ<  ÆÒ‹Î÷οhYÀS;Ùíll°4YÆ:ÒràhÊ8’âtL:¾™B%C Ϲ†½Fyäƒ3Gz}˜„¢v–[œÿ驤y…!?½öJïž×íÑ6„·^ß]ÅÞ'E 8vc£$ е‹õ¦«º?ðÐj{®0ЬY3Üsç_äk™6Ãër{³³ˆ²6 ““ý†Lõœê6ÍdÁɃ3ÉáÃõ‡µr)§…‹":‹ÓÁx9ÂåË EóbŸ6ûšÉ RÆKÏ=uâðîW@J<³ãµØ½ì‚ÉE ¥ƒ"r¿q_»åcî—ÌÔ?ïuc¡£¡AD„Y3[=sæÌñLj™íõÕ5º¬Q¨LÎö†-'±‘”œ0ØvÅ0’&›)iýOJI #iÂLH6’’ìZåhŽV7tHÈZëÇêEë•MB4‘‘Ïíx´ãä‘Ýq"pÆä‡ÿëñßZoR XAƨû%ŸsûšÅzÓªó\—6øéRŽìðöl½¼þZ­¥u–»¹¹ÙÝØÐ¬×54º|~¿.È!ãÐ`T"8<%Bv›@‰“éÔî‡;œ9¡³8v悹E1 ! Ï¾¶YLZRGDÜÝ3Ÿ}â¡öhw[ #–ä­ÿí¡øóp^âfÎP5ög¬ 8æöº µI«ç¹.™ËÝšÕjvÖû²R꺛'Mv×74ëµ ÍzMM@óÖÔ×+<¯p{¼šËå‚K'[&@,'Ó©~Þ1L¶Bnèó?7EÔÍñÚ;ºÒ;ÿi{*Þk8ÞÃ]ß|$¾ €„pb(µRÊö-ºoå7Ípkh ²õÂ1’Êš¦“î©~_€]º¶~þ¼95œèL¥v=Ø‘/÷³Þ߈"Ø’ÏÐ\ nj!ßd@¼ÿà¡Ä‹O=xÜÌ$%]‡{ä?ýýïG‘#J(‚Õ´Ì1`f¦Á¹Ã:AÆÛFÛ÷tñ=Æ>Úa˜€kí|×ôYÍbF½¦¹tªs ÔºtÔjBÔ âìª,¥ÁéÄ€Ì$H&M"¶&ÇÝÞ"ù¦¸\ó¿8•@ XÌ,Ç€Q yyž;ÿc”íÁ¤$’ˆX€$‘÷J‡} †¤ŸÿéÉ¢yIÐÓÍ<ûØÇú»ÚÒi¾ïoL ëfÁð"·¨o>”€EâÈ ss>å³eå~  ²r@UÛrŒ <˜æ!×7M¥Ú95 àøñ©g~·íX&Þ—8Ñÿ~û‘ø{¨`}/JÀqˆ˜·Ñ…+&×+$A¤ °D D¶v¶„AžzM¿à/ZQ3ÙÜ{á‰ÚMë2_÷É~ÜùGã‡ǯ¸xY”€e’'G,F¸Br½‚s@aÁLB0 Á ÁV±[±‰ˆˆÈ”£‰”"1¬µ½8*kÓ#%´] ÌÍ<ìž©`×DDDdŠQÐ-ïe@"s“·µì*¡í‰Y÷Ÿð¶–tåº%"""S‚n‘x'dÝ/z”»mEDDdšQÐ-’‡µ¶WÇem*%µdQe€ðd»&"""S&R™®‘èCNÐçm->¹½:°¬µ½˜C”®±ÇÛZÊ)qx Ôdîïò¶–M%´Íå~ÚÛZú+×-™ŠtOkm_ ¼8ž¨–vmÎ!ÖÚ¾x¸ÇÛZºÆ8ßéÀêœÍssW[kûÅyšÿ¯·µtXkû+=r °(÷R1çø…·µlÏéÓ+\|×ÛZú²ŽY œI”ßܘÓ~Ø Ü Ü¦J-‘ŠQÐ]AÖÚ¾xѼBjˆ‚èÕÀ›¬µýgÀ¯¼­%nqšÃ€ÓÇ8g2æ˜_À!EœÃb޹ Øž³mEžcôYk{p1чŽ8UÀªÌíÖÚ~Qp?é ôXk{@ô¡iØ£%´m&zN¼<çm-eöADDD¦M¤¬km¿(hÌ÷z:Ñícåp¿ ø£ wí@[|ˆüwŠh´|+0Óþࣙ‘òbœ›ç¶¸„säÊNy¬ÄÑw¥–ˆˆˆÈ~4Ò=~ç¥d ‰r• íʤ,4G§¥–XN»W[kûo¼­eCÎöm9Û^—9ß°!àGyú·'óóѬûÃÎæg=và{yα#϶|®r¶= Ü<™=yÔZÛ.`ÿTœùÀ‡¬µýKÞÖ2Täu+­¬ÀÙZÛë)s1™Þt_nÀ½ø¶·µlÎÞ˜-íîî±ÖöWå=gŽçToÈiû 9+f&WŽ º½­å×qô¶–uä¤IXkû‰äÝ…ÎQ„ìþ8Ñ$Î_Äôç9àß3ÏãÝDi6Ã%J¹¹q})KÎJ’ÀïJhþ2ö½Ÿ[¼­¥Ø+"""2Í)½¤rœ(ØþBnÀ÷à¶–ûÈT•gÛTôý¸€;›·µÜ|ƒýÓoÎÉT9вW’|ªÄÑöì¶EO¾‘éOAwåüÔÛZÚKlóPžm¥L@«Ù—Ó<]BÛìQîMÞÖ²«b½‘iGA·TÒaX²ýèœÇCä_0§²s²Ÿô¶–T mµ ŽˆˆˆMA·TRQÍë²dª,ÎÙüÜD,«žYIòY›JI-iŽ,§­ˆˆˆÌL º¥ÒÎGÛWçÙöà8ÎWÈ*ö­$™ž(¡íËÙ÷»³ËÛZ6U°_"""2 )è–J;ÊZÛ(µ‘µ¶7-9›ÓÀÃéÕþ²ÓCžñ¶–RöÑ‚8"""R’ädw@*¦ÊZÛ­Ä’w¹ÌZÛ“%æ6çs‘µ¶®Äó¼“}õ²‡=àm-=…e*ä[P'5ÆkQVNv&gý˜rÚŠˆˆÈÌ¥ {ú¨æ;Çq#Ê©oºÄJ¢ úÛE]´µýlàÔœÍÀŠh~ð¶<Û¯î¹Þö­$é”VcûX¢× X_B[™¡”^2uå«]›žq ΧÅZÛ߉Že­íïʳë—ÞÖ²§B}É•=Êý‚·µì-¡mvjÉc1ÉSDDD¦tO]›½° ÀùÖÚžÚíÞÖâÖÚ>×ÛZâ—ÉWŠïLkm¸ØVÄ9²=œ’õø,àPkm¿xÄÛZ¬µ=ITðõ@¾üïÇ›Š¸^¹ÊÊÉμ¶ÙÕY”Z""""EQÐ=u½³ýÜÌ-m­í=DùÎÿ'æØ1ÛÏÌÜBkmï&Z@æÏ‹èÓD•A†­.°Öö. f¥²Äõéê‰Aά$¹2kS)óQ@]æþð»JõKDDD¦7¥—L]ÏØŸ pp‹·µüŽhT9N9G±ÿNRÀŸçÜ4èÓCÀ¿y[Ë@‘×+Gö(÷6oky©„¶Ùi)Oy[ËP…ú$"""Óœ‚î)*S™ã`Ç8OµØ:îex[K'ð%¢ô”bG«;oz[ËU%–î+G¹UK¬Ü¶""""J/)ÍFà§9ÛÆ°ÞLT‹:™¹å+——·µìµÖöO¯!J™Ôfv÷»€çÇ8Gµ¶ 8ƒ({>Q: D)»ˆOe‰;gø®µ¶ß”éÛÉ™ó—t¢@{3pQ¾wº”kdYÏþï äÉWϬ$™C^Jà|Ѩ?D& }C """2駬³l¬µ½O­mkm¯Ò…Ò'¬µýBàœÍ“éŽkÓDôÁbïdTý°Öö¥D J…ùa±uÍ­µýöM¢ìð¶–›' ‹"""2M)è–²”t‹ˆˆˆÌTÊé™` ºEDDDD&˜&RŠˆDÌ, BTó~Ñ$ä°Ø ¬s÷-“×C)‡‚n‘Iffó€7oÎ'ªg_èø­À}À·¹ûà„w²Ììà;1»ïq÷ÈþìÌìGÀâ<»úÝýì2Ïi>Ã's™Ùธݯu÷ž˜v7‘ÿw³ÃÝ/¨Tÿ*ÅÌþ“Ñ¥n³½ÞÝ÷Èþˆ‚n‘Icf àCÀ§#ÐαxKæ¶ÓÌ>áîߘ€.VZðª˜}²#SĉŒ^AwXÉë˜Ù‘À¿<5Î~MuǧÆì+T¶÷•ÀÜ<ÛÇ»^ÆD9Žøß7Å“@9Ý""“ÀÌ_¥´€;×|à?ÍìçfÖT‘ÎÉ´afMfö9à à“Ý‘™LA·ˆÈff³€_ÿÕo9.~bfu<§LQ¹ø=ð1ö-N&"“DA·ˆÈ÷*pk¾2ç•)ÄÌN%Êù¿–ü9á"2 ”Ó#"r™Ùk€×qX X¼lš€eÀj`Îm¯0³«ÜýñöU¦¬Và”ÉŒ¦ [ÊÕ<Ÿ³-=™bþ¶À¾àëÀWÜ}SîN3«®þ‘¨œ`>F4Yîãì§L¾5䟸7%ªÕLCÿ 4äÙÞ} ;"S“–9@2ÕJzÉŸ_;œçîwqžW¿jcéºûA ˜ÙÑÀïbvÿò`,»6™ÙψÊOæsœ»Ïèê%fvñÕKšÝ½ó@ög¢˜Ùo€×Äì^àî;dD9Ý""Ò â'´ÝSLÀ àîŸ,pH¡Ò|""2 ”^""ràR`_©µ—¿ |¦ÌkM f¶€h¤nÐì6íî^r­ê®[•¹î*`°Ø ÜUÌ‚"för¢ÉËþLŸïîONTŸff¶Œèõ8Œè}¬%úÆgOæ¶x`"ßÓ©"ëßÞ ¢züÀvà~w_7™}“ñSÐ-Sʵ—5놻áAÑ}ssÀ¬×w;zªêv~èß·÷OvŸE² ØÎ4³#ÝýÙbNäîÍìZ¢:Ý=ynOĵ5³þ,f÷{Ýý§c]ßÌÙ=g<«šÙÉÀ§sÉ¿XI™ýø„»çÎ-‰;çÝÀ±yv}ÁÝÿ9sÌ\¢|ù÷½®¹úÍìÀßææÜ›™$z]ó]3{øª»_WdŸ' ¾rõ¹û’œc šy˜/ïxؽff=^ïî'ÓŸRdÊbþ%ðGįþ˜­ÏÌn%ªìó̓qÕL3{Žü9ö;Ýýˆ˜6+ÇbNùFw¿+sÜBàïˆÿ·‡™=|¸a"_3{ðMâ³!ºˆú÷¼$†‚n™R¯ ÝN0·h» ÿ÷ãŽcvêÓ½¬½¼±ØaÆæw÷Ç/[Ó£•ïd²lœh²c®zà&3ûðƒbþ¨ºûeeö£ŽøyªŠ<Ǭç(K&pýW¢ºÒ…VlÞ ¼ÍÌþÁÝ¿TÄé›ÈßßÚ̵ÿøÑÈvœÚÌuÏ7³‹ÜýöLÛÀõÀÙcôá$`­™¼ßÝÇš÷çKQ*öýÈ]@©â *™ÙiÀÿ?Ù7Ÿ:¢Å{Þ\if—„#»Íä ½ALÈÄ`fö¢ Ôyƒí,Ç×U(zóD,ãžùÀû]â?¸ oWÀ]Ý2¥¸ûê|ÛÍŒ(DÙ/NiÝ9Ôà5†±ö²ÆMð˜¹=ü¾5]3òë^™îÞaf÷gÄr(ð=àq3»ŠhraQ#ßÓ@’(p}o mj/šÙ!À_•;úgf—W“ÿÃP> €›Ù‰DU›Ú)-çâL»ËKéçT`f¯ Zøiö8Ns&p‹™ìî»*Ó³ƒ“™}øb‰ÍÎ~if¯v÷ŠU 3³UÀO‰¸SÀ»ÜýוºæL£ [¦ ¾J¾ãD²þ@šCKVºnÕÇlèÞÓÑÐÕ½·¾¯·«¡¯·§q ¿·±¿¯·ÏŒ‹ËÝYîø®½¼ñ…ûñ +»ïkm=ø¾Î”iéâƒîa/#Z~ø+í_¿ns÷ž‰íÞ¤y-޹þ’(çúse´}Ñb©×žE4"8—òòç/3³oºûme´=(™ÙràWŒ/àvÑBO¥|›j® üç÷*¢T¦¯V¢#™Ôª_¿˜’—¹û+q½™J%eJºö²¦åf~!Ñ„“‘¯¡›fÏÛ~æyo½káÒå=ÑßPÃ:÷î©}þ÷/ݺqýÒŽ[ ô÷å–ZÛfðË×tU=B¤\f–$Êñ<¦ŒæƒÀÀMÀMîþh™}øð‘˜Ýos÷qާˆA¾Qç1Jæ³xŽ(w¼~Œc‡€ÓÜýá|;3ùÑÇqÍ¡Ì5)/ï!Zz}ÑDÊB~áîq¥ý0³ ÀÊ<»úܽ>çØõDKõlÜ7ˆ¥2³Ï]à=À¢Ià ˆ& z_»€ùE¤á”¤Ü’f¶‹ü9Ý;Ü}aL›U쿦Eœ4ÑëÓIôÁ»PŠD“sŠÛYlÉ@3«n)p,À_¸ûׯèŒAA·LiW_Y?7o°hÂU@"Y•:öÄ3î?ùŒóžºqÂTÂa*±yãú9O=úÀ¡[^|a™{¸o²ˆóð`UðŸïÿFg×d='™þ2ËtßJá oÅx’(ô†Rj O û&àÃDA…gꛟ \CáIyÿëîÓßb‚îomî¾5ÓfÑÄÊÑç>¢‰pßp÷þLû〟?¾˜çîa¾%Ýæe¾8<æškˆª… Ûéî_ˆ9¶hfVOT¥%ߊ©CD¯ášì:ÓæO‰&ÆMÚ;ßÝooÿrúz0Ý_þÅÝ7gÚÍ&Êo¿šøzü«ãRЊ º3ó(¾CáÅ´>áîÿ2Ö±)è–iá†÷5ÍJWùŸ'F[Œ…KWn<ëõ|có¬!ÒaO'¢[xcéÄžŽ] ÞwÇŠ /<·, ÃáQ…=_¿xM÷¤N¹æò†9AØÛ}ɵ>4™ý‰af¯%šl6Ön1ºÏŸ.&Çó º¿@Td¿@ÔÌš€?ˆiGä«hRDÐÝæîŸÌÓ. ÜE|Q®ëëò¥Šdrœ)Ðv•»oÈ·£” ;§Ý_ÇÌÞ |+f÷•î~u¶_þ"f÷î¾f¼ý˹ÞÁt;Ñs¼&¦ýÿ(ÐþMqՆРº¿|´Àù¿àî+°_J ÅqdZø“ë»:/YÓý9Ì®ÁÙ¾eÃÊŸ~ûkoØñÒ‹M@€`¤zC‚Ð-1»yöà™ç¿iÃ…o}ÇÃÍͳ†ÿ£íðñµW4?‰O‰Àl¥õÿ°öÒ9•Êä “™ŒôJà·8]#ð)àN3+'Åà`ñ,ðwq#¿îÞE42šŠiPxÄ.Î:àŸc®™"šàYÈuq¹Ù™ ¼AuF%òŸ'»ÿ7Ñ(÷™À‡ˆFnï$ú÷}íÍo.°¯¢rB7ÆÜîþuàÁíó•”,Š™}˜Â÷Õ ¸+KA·L+—\Ýus"°¿wx ¿¯»þ×?¼¾¥³c{ pK`A‚®­ý v¦B,ž˜=oaúMo½è™Õ‡ú¢ —ts¿líåMq#j„cGaCm×_\ŸotE¦8wÿQÚÄ»Ç+pÊÓˆª>ŒUzì`Õš rc¹û Dãœ^Æu¿9ÆuŸ£ýUcì/ôÞN› ÒÝ÷¸ûîþuwÿ»Ÿéî'ñíËæû¦Í룘‰yç)dÔ•yÝ·…Jm~ø@™ç– ºeÚù“«º67võü£cô÷õ4Ýôý5gôwï­Â< Q[MÍÜz†vѽ¹ô@Éêà´–ówvʉë͆+û%“xc,“AÛõdìƒeªñÈ·ÝýåD#ß_&šˆW®CïgV¶›JB¢Ô‘bZ\æ´2®=Ö· { ìK¿øI1í+^'{*°È+ÌìŸ(<>Ý_ŸbÒ ¥§”tÿ;ñ1àF¢E²ò~ã$åSÐ-ÓÒ;¿ë) »¿‚ó@OoÏÜŸïÚS†úTÕׄɯZ|º·ö3Ðâ$° qäñ'¼ú”㟠‚‘Àûâë®h*§ÒD%ÍÓá'¯½¬áб•©ÊÝr÷d*F”Jñ ¯d™ÏYD“馒-crg)”®±83ñ²c-ÂRheÛ >öòå…‚îrË$N)f¶ØÌÞffŸ6³[€¢\÷6àå“Û»I³%“25–BeBË-ý\èwd%Ñÿ!Ra ºeÚºäZ ­î dF :÷î™ÿ››n< pOP=§6 ´SFß¶~w$?æÄô'¬þÃn¸ÿùš+š'ç™$ ˜efÿxýåMÅ,©,Sœ»?ïîßp÷·­TwQ%;ˆF…Çò§Ù?Æ.gVªBt®BéPzJÂXµÏ Ý…êa½%ôeZ0³¤™ý¡™]cfÏ[ï'ªÉ^ì{4G[‹­84Ö‡º‰ðå2>¼ÊtË´vÙš}ƒÉàÓ˜¿°qã†Ã¶ox¦&4 ’ÔÌ©%$€0 oç  íMx€%‡{bxÄ! v8Ì <|ÿd<3cåÇ7‰*êBüo¯¿¼þ”Éè‹LwO»û}îþÏîÞ¬ÖŽÑì¬Lå„Rûw¡¦ŒsòR±º{7…–Rƒî±‚âBŸÊ‹fÉÛÿ@ôÁèGÀ¥Àã8åtº‹ ¦'#è>ž‰ÿà>ã(è–iïýßèì2·hv¸»Ý}×-« S†Y‚ªæzŒ$îQàݽm€ÁÞ4F@P<ý´Ó{šk£š»ø)×^69MŽZ1;ñªWžØ˜¨ª €ªà¯®»¼áœÉè‹T†™5™Ùj3k1³cKiëîëÝýRà3c»pFÅ~]]é ;_}çB •Ò,µÌf¡‘ì±L×BKff {‰*Áä-¡—Ç&¢U,ã(èŽæ L†63+õ÷R PÐ-3ÂÅkºžX¹§cïüg»·˜'¨n®!L†§z6ö“#Ô̪9÷ÌWíI&‚ÀÌß{Ýû›ÆZe®ò,°#—7%^sÚÉÉêú{ÿÚ+ß|Àû"e1³?2³;ÌìY3©}¸ø·2Oû5¢j;qÊYž¼Ø¯” -ØQŽEÅhfuì[&ŸRsàdz`Åt ‹–YÕð‡DÕx y¸¸8ÜÝWSàøéüúVt¥Í2u_²qQνTˆ‚n™1‚tâ2#`ýö¡U„i3ª›jÁÂtNC׆^<4ÀfÍ_ZuÚ‰G çmV“ö¿\{é­ af˜¬ZÔœóšSšjêgE‘óÇ×]Öø¢UÅäàfD5Œ`ÿ•(ÏÎ,üR’Ìêu…*o”Sñ¦Ø‘îr«&Ä):è¦ðòêéLú‰XΈÙ×|šhᢕîþ>w¿ÆÝŸËì/4_f:Ý“­‡h¥‹‰ÿÆæƒ¥~'ñtËŒqñÚ=/™ùí}}} /my®H`5ÕÔ$! võG7`‡¯>ÖV-Óà°‚ á]´ó€†™-W¼öÌSšfÍM¸qáÚË>pãE¦ßçƒ[¡U «‰_A0Vf çU‰›pXèëê1G°Íl•O/™gfc-Ó>¬PŸñ”[œ *>`ùwø—1»SD«œþ½»¯9¦Ð· º'F?ðfw¿ËÝ·Ÿ9.IùßÄIý‘–ÅÍ3|ÝÓOÎ1<Ý®iªÅ 3Í»Cú^ŒV²L&Î8íäT}Mb8XyÃÚKg}àze¿à¡cÆ‚æšà¼³Nijž·¸:s@KwSãGô¼”ä`[ý_4³%ž³…üËR{6f{G6ù–ϵºˆcÊqE‘Ç]R`ß}èÇTW(G½ÒiAˈÿ t§»ÊÙ†ÂA÷xR$Þ»ÜýÖ¬Ç_¶Äû:3{ÓèÓ´§ [f”K®ê}l;À‹7Îõ0˜[‚d]žŽ&S†¡áaé€îmƒ õ„˜ÉÚæêלzÜpžøÿãÏNİý™æý»†¼kc?³’vÞ™'5Î_¼²&êŸLÐðwÿõ¹Z6þ ”Yhâ¿ ² øo3+*½ÃÌVÿSà4DuêóØY ]1“/ßSÄ1åxŸ™-.t@f™û‹ rWe»4%šÜYé´ (üAíÅ"ÚŸT`_¹u¨¥°»³¸{QIÒ8_4³êû¥ ºe&º`pp°zóæMn5ÕxDyÜ™Ÿîé€Îç{£üo‚ÅË«:öЙ<|a}ßDû˜™E©%€Açs}¾w]/µI;÷Õ¯h\zÈ‘ÃH©NþÓÕW6N÷¥“§ªk)xõ•õ…òjÇod¤;ëW¶gë ï|´ œêdÂ^}ò꺣Ž?¹ÉÌp8Î8IDATlq:L´­½´qÅ„öKÊñ·Àî"Ž; ¸øsàŸˆF—Ï!Zr,ßv÷‡âvf&N=V ýràwfv™}ÇÌî ª§ü)Ì×ýG?ºÍlÑHêÍN}ÙMTZ <Ü<|¸r¼s÷ðdC> ÜjfWšÙÍì#fv3p+cx<ð%Zg0w¿øyÌîYÀ¿ÀîL; ºeÆimuÖtìÞU‹[n$k“#vZTFÐwîï}®Ï‡úÜ܃¹óæU½òÇ í9;ŸØ\ê‘€{ôhQßöAßñ`'žödÂ8õe‡Öwâé³2ËÆÏ&à“×]1«œRd‚¸ûv¢J%UÖîNŠKÿ¸jŒýÑÒó•:Ì.iRù4ŽŸæÙVK”/\Líðe>LÜT±ufVh"c± }³p6ð_Dïó—ˆR©Š1Q“v%ÞLj¯pt©™ÊÁ—tË eëú{»éìê©ÅI¨«ÆÓ£òºLðía€Oõº§À-8æÈ•5G¶j¸lÚŠêÔàGo¼h‚&šdÊ’¯wÿî!é¾½„CÆIG/¯9éÔ3›3ËÆ×»‡·öÒ†&¤_Rw¿x#°½Â§~øCwûª?Û™ßP†¿¾WfÛ8ÿL”•ããîþJvf*s÷‰¯\“ϸG“3¯ÿ7Ëlþ8ð­˜}ǘÙ1ežWÊàîOWÇ숾!‘2(è–™ÉÂõazÈ;;÷VGÙÚõÕ@`Úa0ˆ{îsv=Ùƒ§Í xÕ‰«ë–-]4\¦ï¸ž¦†ONDª‰EÕKÈè1¸7åÛîÞCª?´Àìø#WŸöšsç$ªj Æûëë.o|M¥û%ås÷;€ã‰Ò(Æk/ðaàTw/&ue8óíD9µÅÚ¼ÅÝÿ_é],ʉRiREß\éþLeÿJñåö*•†ög”^=濉òø¿^à˜÷–Ý#)×?]1ûÎ4³»VÅ4¡ [f¤Ð#õH÷vìN⬮" Ü Í=Œ¢\÷M®ô0`¨Ó½ãé>ð vÖ«^Þ°`Þœá<×C“að/×_^dE;lA´zf¡•'‡zÒ¾õΆºS`¹r^ò¬sΟSUÛ˜pH8|èºËš^_Ñ~ɸ¸ûw;pðU ×ñÎ5D´„üß«Ýý«î^hÑ›|×ßœOôuò Ý|8ÞÝ\Ê5JìOèîŸ^M”W÷|ˆÊ%ëîq#r3š»¯Þ¬ãЧ‰–¯Ä5;‰ÒHþ†øšÏ½¯7g¸û{2åêî!þßÿ{òMÄ”‰“ù¿á3ùœ™i’k‰Ì]uçeæik³Ä!®«;)uúi¯êÆÃÛïÛÃPx*ážN¦x:v§“ÑãTt¿aY­5QJ‡ÜóÀc=ÏmÜ:\ÇÛ͸+°ôrU_Y)k¯h|ÎÇ-HØëßø–ù g%ðîûÙùHÜèC$¨2[òêÙÔÌ­ÆŒ­»zÃöÛoíèÙ“0·^|M×wËé“L<3;8•h"esæ–$š(¸+ós3pW%—;Ï5-À±D#Ÿ ¢@ü =3Yî€ÊÔì~-Ñk1x xø…ª”ÇÌࢼüáI‹Û‰^˻ݽ”4”R®›$ª¿ý*` йæ À¯Ü½P­x‘iIA·ÌXk/oü"°tñòCý^ÿú.Ât‚ÝwÑ·=ía˜ÀÓ H'H§£û&S™ûéhbWó‘õÖ¸¢ÇxòwÏö=ôØ3}Y—I™û¯Óf·]¶¦{CIý˺/|Û‚…³¼ëÅ>vþ¶pÐ ` ³Åg4S¿¨°{ÂÛÛoëèÙ³c(sÀ-Vv_“™T*"""Lé%2s™mèÜ»'“’õQÙÀáœî0«nwv ïa{ŸíõÎõ½`˜vü±GÕ¿ùZš—,I7IºÙð™µW4|yíåï¾îŠYG•\éd¸\`±ß°zÚ}Û{¼gs?0v]pÞy¯›Û<Yfâ§ŸwÈÆ†¿¼ñ¢âV?‘ñÑH·ÌX×^ÑønsÞ$ªì|qmu`ôlî÷ÝOõâé$¤Òéd4² ‡ÓLÂýË—Õ-¨²y/kªF°Ù¼iCÿ¿ý]ßÞîþ0¦ àÛpÛæo Â Ï 7ðÐñ€p™›ý »àÍï\° )À»6ö±ã¡±GºG,;Ñ€¶ªTbFÁ‰”y9l°ÓÓƒ¡Í=¾©±.°sÏ9{ÎoîªÙ»õ…§z1^Vßßû‰ë/žõ™÷]×9Qu£EDDf<Ý2cy˜ØbÁ{÷î æÏnrKÖ%<ÍÞw ³îãñAoª/dÇÃ]^·pÀæÛ@²!‰ÁÜKjæ.XRs‰ƒáž=C;ww¤övt¤::v¥ötõ‡½S×ËHTÕÉš†c• ˮǺ= mÁɳ몳Ïzõì{jë/<ýPpx:~òÚËê?}é5½»Ê»€ˆˆˆ¢ [f¬0°-‰L´ÛÙÑ‘`Õò * ¨Nö‚gòºÉŒzgçrÒ·}зì¤ai +j­v~5˜‘¬MÌž¿41{þÒÌ8a:íC)ÃÐ Ó¸–¨ j‚L·ÕTYf°{U³:žîõô ÛâÓçT'öêÓNžUSS<óè]{ _†mk/õ¯—\ÛY¨Ô—ˆˆˆ”A)eƺüê½ÝÀV€íÛ·N€{@ÍÜš}µ¹‡SJbÒJâxÝ›ØvÏ^ßôëݾ÷Ù;‡p'J ¢TKX¬êê MɆYs’M³«êë µ k¨ ¬¡6A2ýºŽ³Vmçs}¾åŽ]xèÉDÀ)'½¬ñe¯:onTUŒy„Ÿ\{iÃá㺆ˆˆˆìG)eF[{yãûs‚D•ýÑ»ßT%,ðÞmCl {¤4`˜U"p¼Ì º9IÍÜ*jf'IÔfI#H– ’QP==’ CÒý!©Á=C v–´J^õ‹«mùkçT<õìÆþ‡ïúå®0rÃû1ûâÅWw?1î눈ˆ  [f¸k¯h<Ëœ¼î‚ KÍO¦ßø«Ý„ƒÁHàír¹§ªÚyU¶âuóIÖ'l݆m÷Ýþ“é¡H¹Û×.½¦ë¾ÉˆÈt ô™Ù<ýôðÝ­›7:X€%–Ö/?-n€þ]C¾áç;Hõ¤ÍŽ\µ´æ¬×½ca²¦!$ÍüÃ×]ÞðÚÉˆÈt  [f´K×ôm¶<ûûg=2ðÀškÂ29Þãäq7Çö»Å;a÷¦üùÿÝÎÀž!,°•ËTŸûÆw-ªn˜̱+®»¬á­Ù‘™@A·ˆq @ŸozaÝ`$êªi\ÙP°D`FnæÜF¶‡£nyŽÍ=&îœaž@½l©Þ´¿ðãíômÀŒ% f'Ï¿ð]‹šV¸ÙEk/o|_é5ÂEDDd˜‚n‘tU;0ðä¦ ¬ùÈFµ#¿#Ù#Ô¹ÁoÞ ;.H.á–œç îã—ˆ§Cá'ÛéÞÜfóg7&Ï»ð¢ÅÍóWd–炵—5|°­Í*3¡TDDd†QÐ-3Þ%×vôÜ °££‡Ï==˜'k,:}Ž“rƒÛ±ß<r‚ºÅŒ`ç9.ïˆw1ÁwIAx˜rßð³t>׃ÌnªKœwá;Í_¶º.sÄ™‡llø?7^dÕù~ˆˆˆLG ºE?îºÿѾ®iǯSå OiŽ ¸Gîgä}û<û¸»¹»…aÖÍcn™ýÃm°g(ÜõdOºsc?î£R4<>ð.¶Þõè¼lòäcGw²ƒð‘ ;&øÎxŸÃfY¬º`!V8°nýó=÷ýúÆ—ÂÔ C†}íâ5]÷ÙÉPÐ-3Bf„{Ì`›¬ ü¢S«fŸ½ºê£‰À–g¶³|éüª“O>¹±yÞòáQoÃÀ»Óa熾tצAïÝ93¹2š€™õ`ÿŽŽº;êˆ}Aó¨mûÎÃg/%ø6ÀÜ,k™f¡›?þØcÝý“xè@·{ðùK¯éü}Ük,"""ñtË´—“RR(ðÞoßé‡T׿ã´Ä[j‚³‰rÀ àðåó’¯8ñ¤¦Æù‡ÔBfäÛ2Avz0 »·†]›úÓ]›†<5¨ºè‘î¬ÑìQAxn>Vð]8ð6ËÏ™,<©ƒ¡tníÑG/ÞQ•`ÅèZÝfK–,®:ì°Cë–-[YSÛ4·jd<†ó½£ØÃ´ã]!éTÚÓý¡§úCR}iOõ…yÞà{tà=*ßw•‘À;ªI²ÎªŽ|ûBkXZÐÕ;¾ýßÛÖ±m}€;ÝùBÏ×ÖÞÎÑùCý!""RÝ2meMž,5àη}d[58·æ¸s'7ÔpF]öeÝ¡iVSréòCk.YQ3köÜªÆÆYÉšª Ú?2Øœ5v=Uß5Ì< =I…¤Âôžu½©ívgÞùRMÆíjæ$G¾sQP;» Œ]©Û~ö­­½{^H»ßüoé½nófB¢€;ª*¨ÿ0DDDÊ¢ [¦­1‚îb·Ü>¿žäE§×»rNpRC½,0êF*›ŒêJššçUÍ_0/9oÞüªæÙs“uM³«jêf%«ÉD4&o6< ]" ’‡Ÿ‰yz÷3=ƒ/ܼ{'9{vÍj¨±¦Újšj4V%¬)™¤±* )Ð5ŒŒ`Xf—R2ò$÷ ¸äÊóæ&½²ƒT¸ûöÝ¿ÿím¸³sý6ÿÂgoêÝBþn'Ý2­¹ûpžt¡à1$©.d¿ ºˆùîßýlz'¤wfménö?pvõq/_ž¼Ò ·ÀÜ0Ì,¾L`tgtÀHZÕáo™ÌYÝXÿP:¼ó–ŸlßüìÃ]„!Ïßó|êKk3°—ü·r¹EDD*@A·L{Yw!¹Aõpî”hg?Î÷³ 3dôHwt³ÿÈvÎI£‘ðd}P}Ô»YÃÒ: º{úÓ·ýü¶íÞ²¾73âýèîïù÷›Ÿ¡Ÿ<“&QÀ-""R1 ºeFpwÏÞÙu!ÙAøÈi(>ঈŸ»œÍ2UG, 03 ´3‚Ú¹‰äѼÔj¢’€»;:‡nýßë¶ôì}iƒ¡·}ö'=×mØKp‹ˆˆL8Ý2cdâG7³rREòb3²`çÛù‚ï‘ 7î›0i™<3Ê=‘rødQ î¦5É#/ZL²>i[¶¾ÔûO®Ý2Ø×•|`Èoüóoõþ„Ávôr)Þ©Ý2ãäŒz—l—3²/ÈŽÍéN&,mf¡™YöHwVjÉȪó™Ì;®!yØ›T™c¬[÷lÏ=7}s[˜L¤ºýª¿úïÞ»=IReEDD&˜‚n™‘²F½ã‚oŠÜNÎ}(l•Ï P“$mM Îç6#°QÁòHÙÀ`É͉¯]€ºñÄcîyäölwïÙÓÇWþú;½O¡‘m‘NA·ÌhÃÁ7Q^L`7Â]J ]TNwU‚ô¾œns³³ÀÍ£“ s‰UÌ2 •Ƽû–χs¨K °Ç ¶K ¼ *a£'RQ“ »K´Ä‘-¶Ù«›0óÁ”ßuó¶½øû»¢çÄ }áç>þ½¾=(Й4 ºEòÈ ÀaìÀ›<ÛÊáQ=’^B”ÏE8€U5$‚£Þ»Ô–Öt÷ö§oÿé ›wm~¶Ï¢Î?ºÍk¿ü‰ïìêS-""2¹Š)&2£¹{T;Ï=ÌÜÒ@ HgÝœÇùn¹m Þêªl8½Äƒ`_^w`xP7?™8þ+¬qYY@ÇžÎÁ›nüú†Ý[žíÍ´¹õÅCz>÷kw*à9h¤[¤ Ù¹àÙÛm_ ¿b+–Ä^¢¦j_nˆò¹1ƒY«j‚Õï^N². ÆÖ­[úoÿÑU/öu¦3Mo¼dMÏJV"""2Qt‹TPÖ¨²çü,ÙÚ+C<³"eD‰æËëlîñ³’Ï­¦ûݒN „@Úà¿.^ÓsÇ8Ÿ†ˆˆˆT˜‚n‘)Á€jÔ„O=zÇ÷}ç¥L ßgÆ—.¾ºû‰Ií¦ˆˆˆä¥ [d*ÈJHI¥‡îþÕö§¸iwf×nùÌÅ×v¿8YÝ‘Ât‹L!ƒC~×Íßßòâ3÷we6m´TøÙ‹¯ëÝ]°¡ˆˆˆL*Ý"SDOooúöŸ\¿içæß÷à<^5Xóoïù殾IˆˆŒAA·È°{×îÁoZ³©gÏKƒ™MíƒU=W]rMwzR;&"""EQÐ-ró0åwÿø«†ú£Û;éÕ]ß›ì~‰ˆˆHñt‹äÜ¡þî´AÚͯ¾ôêîÛ'»O"""RÝ"SCðåK®îyl²;""""¥SÐ-rðë ä³_Û½a²;""""åQÐ-r036¤,üÜkTPDDd* &»"’Ÿ‡á¦ÞšúO^q•n‘©Î2KH‹ˆˆˆˆÈÑH·ˆˆˆˆÈSÐ-""""2Át‹ˆˆˆˆL0Ý"""""LA·ˆˆˆˆÈSÐ-""""2Át‹ˆˆˆˆL0Ý"""""ìÿµõC=@[©IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/multiple-file-icon.png0000664000175100017510000004020612370216246031173 0ustar vagrantvagrant00000000000000‰PNG  IHDRÝ ÐÐÄsBIT|dˆ pHYs.#.#x¥?vtEXtSoftwarewww.inkscape.org›î<tEXtAuthorAndreas Nilsson+ïä£tEXtCreation Time2005-10-15 ”W IDATxœíwœ\uÕÿßgf{* ¤ÑR¥AEPQ+*–Ç‚Øò㉱<è#ˆˆ½€)Ò”*¨4‘ÞBH ´M²}Êùýñ½³Óî½sïìÌìÌîy¿^“ÌÜoÝ;³³Ÿ{î)¢ª†a†a†Q?ã½Ã0 Ã0 Øè˜è6 Ã0 Ã0Œ:c¢Û0 Ã0 Ã0ꌉnÃ0 Ã0 è3&º Ã0 Ã0 £Î´5b‘ÓO?½½³§m'”îF¬gT&‘HdRÉìÓK¾°dÓxïÅ0 Ã0 c¢#õNø­oŸq˜u]ȨžHJÇïO=õÔÔxoÆ0 Ã0 c¢RW÷’3¿{ælÅw³"À.iÙc¼7b†a†1‘©«{I"Í~ˆ·P[[bÆômˆÔsI#"ýÙÁÁÁ4€ÀþÀ¿ÆyK†a†a–úút‹ÎÊ==ðÕÍ;àU¯Þ©®ë‘yá…«.»âÒǽ—³B;†a†ac¢aÙK’mÉF-eD ‘°Ä5†a†a”—a†a†aÔ™†¤ ,G3ÃÃ#ÿŸµ'/íÛ‹$¦÷> Ã0 Ã0&ã$ºÑL&Ý;NkOZTÛÒÇj†a†Ñx̽Ä0 Ã0 Ã0ꌉnÃ0 Ã0 è3&º Ã0 Ã0 £Î˜è6 Ã0 Ã0Œ:c¢Û0 Ã0 Ã0ꌉîI‰Ž÷ Ã0 Ã0&&º' ªîa‚Û0 Ã0 £ñŒWžn£¨šÐ6 Ã0 ÃOšNtoذ¡mݺuã½fcÊ”)é9sæŒÄc–mÃ0 Ã0Œæ éDw&“‘T*euKÈd2‘ω‰mÃ0 Ã0Œæ¢éD·16Ì•Ä0 Ã0 £ù0Ñ=AˆkÝ6in†a†Ñ8Lt·8±Å¶©mÃ0 Ã0Œ†c)[óÝ6 Ã0 Ãh šÎÒL&µ½½}\•d&›I vçJI $ÒëÖ­k‡œÌŽoÝž:ujW2‘ìèëëë¦z]:Î:ûŒyµÛm]X}Ú¢/eÆ{†a†aÕÐt¢{ÆŒé3f¤Çcíµk×Lûçýÿ<`ÅŠû¦Ó©)㱇qäKã½ ,;ëì3ÎÎ;mÑ—Ö÷fŒê‘ÀaÀÖÀÞc° جîWÕÞqÚfÕˆHÁß«#ªšmä~šIAéaÓª:.Z 3 9£ª©€qaïGJU}"ÒAÀ]sUª°]ØT4èOn¿ã¶£Ö¬]³ëxïÃðe[à `ð¹qÞ‹™œ  D´ï‘€ó‹[H€ÿ÷³úqpc÷Òì \Ðvð?q'‘ùªºrL»j}î hû ð¡€¶÷´}ø¿€¶{}üDd–ª®g“óéöX»ní´µëÖî<Þû0*rÒYgŸ1ÙîB´,"ò.àqàlàuD¿Ð`_àÇÀR9±>;4&"2OD..faa–ngŸ}f[UM$“I>ùñSH$욤æ¼_ü,÷r°?ð—ñÛ‘ùð_5˜j&p‘ˆü—¹h9<׆Ïá,±Ó€?ïŽ Ã0‚1ÑíC[[S§N­ÜÑhÝÝ]¥‡¬bi“#"gPÁ]ȇa‚Ý7ŒI„ˆ¼ø°ãxïÅ0 # fÊ5 £¦ˆÈÑÀâ:MÿIyGæ6Z™&"7×a‚Û0Œ¢¥,Ý6lhK¥Ru¹P <étŠLÆîh7’d2I[[K}<PDöÂ?Ë͈ªV¼U."S ¾€X­ª/Tš#ÂÛïvà2³¬þ \ãY£Î¶ß‡ «;ŠH7p,î®ÄV@ð"ðp™ª. YG€×â ýl Ì^^À¹'üIU5âž§Û4¿TX䦤ïV!ÓN‘½KŽ­PÕ5Qöï|€s©z%Îß¼gÐÚôzgÂÎíx#"›O±RU_ªÁûo¶Ã«MÀËÀÀõªº!Æ\aŸùGr•7Ed\&¥\Žg€û«Tu¤Â €Ãݼ=OÁý¾ô“o×·÷Uí ˜»ôsšcY® ÷ž|—&wððp)N¿Í˜£_UŸŠ±ö$83XÑwˆQ=&º è%«BÚN‘kUu â\—àþô<¸ð‹ÓX+A_‰[Ú~ |&¾ˆÈ¶ÀOp~éAüPD®¾ ªÏE˜öUÀmms—½œÖ_>‹ËwïÇ·Däjàcªº®dßG?À‰?ωÈbUý]„=¿žè)Áe+©ÄÀ%Ç>ƒ{Ïj†ˆtŸ>lcÜÃÀwUõ‚Zî§FEu)+""¯ÎÅ ;?NFDä'ÀÿªêÆÓ†}æ·ž‘SpUbýîꯑªê >û= 8÷¹‹š¢v­ˆ\|¹ôwÇgþåŸÓ~ëÅÇ\‡«SPÊ·qß ˜£ODæ¨ê`´­‡V1}Žà‹c#&æ^b4=ÑìfF“ðDHÛ^À"ò~ \ΡªËUõ[ªú#U=_U/SÕëTõvUýG+É‘ã€GÜàþÐ <&"ï®Áº»ÿ‰§ Á[÷xà~ÏBˆˆ´‰ÈÏ?,¸s,.‘oŒuÏÍŠˆLÃYõÏ&†àöØ8_DþìY1'<"ò5œ%;Hpçè¾€ûÌû–•¹îɸ‹­ 3g¥.÷ÿp–ëׯ&ÄlÜÅÃc"rD¼Ý–íáUÀŸðÜݸïÚ ;'SqQQ9!¤í¢¨w¯ŒÊ´”¥{Þ¼yÃõzï×­_z›É0ŒH\|?¤}'à·Àéž%÷&௓$ýßû€÷âo¢ 'bg©êÏ*öög'àr‚oEû±¸LD.ÞsÍ/‹È£ªziÌqMçšóG‚Ýž¢òàby[+^<Æà»À‡bŽYÜ᛿U¹îÞ¸ÂIa<¥ªEq#"òIÜ]–±0¸RD^­ªW1~Î}¤'¤Ogéž |5 Oœ`ó0Ñ}aÄ9Œ´”¥»££#ÛÙÙY—G2ÙfWr†1F<ŸÕ›"tÝgÕºX'"׋ÈgEd§ºnp|y?ñw~äÝ¢¯†?OpçØç?Wpçø¾ˆYêZ•Ÿ‡Öh®·àü›'2ªrÜtà ™SåøŸú\\øBDŽ¿µ`:Τ¾ ¼¢BŸ¿xq%¿‚´Ë[EdJ¥Å-åÓmL<Üwa+k(#U=g鹿Óuá£nõr6·*KÂr{¹¿2~ÿ*ý\¿”ªÑ³|?2v`Qî¶{a™RZ Uý°ªns×yN ž‹{Oƒ!½üÆ4wxé'*#À¢01Uý'áÕJ™~‚xX\z‘®ªkJ(UõJUݘ¸.èùLàLU}°Â:aíÕ~þ‡qwŠ\STuDUo-9Ö\0OptÈ:a®%¿²Q#-eé©ÛEB&“©æ6¸Q%fÝžxP÷÷Rå‚ËÚ0–ßµ7¿‘£[Ð×û>U½6B¿ó¯ìký Ê<92„ cp./AÅ:îòJ¶ñ\HÛ„Ý9Tµø›÷ˆJ˜â `¢fïùE¡;Sß&Ø_~;™Wá3èÇyq3ÃxuöQ3ï„Õ ¨öóUÌbD h{7åþë9Þp|-.¦Æ¨1-%ºW­ZÕ944Tá½aÆÒ[JF0±=9QÕ««EdÜý›pAfÕXùÞ‚+ÔQê»Ûìü%J'U‘Ûq¾§~ìO<Ñýx„”ŒaÂáßƆU K{6a‘Ù¸´‚oÂå[r‚‰}ŽîˆÒIU‘å®Úø"°.nFžŸþž¸»ÇLYí{kïªz§ˆ<ìèÓü&™^ZpHD^‰«†ëÇïr=ÚÒR¢Ûhmâ¸â¶´×®ˆgõúð=ï¶ú!ÀÀ‘„—!.å³"ò­8e£›€8%ÀÃÊÌosÝ('a¢üÙ c7⮤'åÝBiÃù¿WÉôUT."TÈDÎÓ÷3$ºã~æGpÁ‡cÆ3‚»Ãtî{*jvjßÛgªók\Ðn)¸‹ƒÒXËZ2˜è6êN\ë¶ îÉg}½Å{ü?ÏWù8Î(h*¤8 W⹌%ø3ˆ(·Ùs„‰î¸¹¯}}¹KKCè„•CUUDR„¿_ ï‚ñXà¸;6ó!‡0‘E÷x}æ—Ž¥è—»úÃ8èÒ´™qh¤è¾øþ±zï"ºè~¢Ôçݨ&ºÇ€ˆ°`Á‚ñÞF]éè¨þïèØÄ¶)ïɆª¾Œó=¼DDNÅEä‡åè=žø¢;jqšzäÉŒc• ~Y ˆ’'8ì.TtO6Däý¸ª«³k4åDÝãõ™1fDd\LÅ!ÕŒ÷¡š÷6ÓŸU]!"·à\šJ9RD6SÕõ^²=¦2+w1Ñ=F¦OoåD õ#nV·|wÛ­ŒˆLÃåQ.}œ¥ªk£Î£ª+Eä\ñ˜ýºÅ¹…ŸcED>^zPDöþŒ»ÃÆdÈ;û¹UDŽ‘Dd?ù4.Pú¸q©êíuÞÛc»t,.‘"?hÙLDÎ~Uaîqyo½šaî~¥\!ÎŨÚÒm®$µ¡úòíÑĶÏÑÈëÍ…ª‰ÈÉÀõDˉ=Ï{Äa%á.7ßi-p¿ˆ àJ ÏòéSÏÒæ¯~sÌÿ¨j˜ÛÌdbÁÖу)ö‰¿»ëÝÒ&Ày"òQÜE[;°®$|¶!Øw"q8áVáR2À'ê´—QT5-"ìvqð˜Wxæ%œ«Ð!„g-É1–j–cåà˜ˆ}͵¤A´”è^µjUçÐÐPEë|5Ó7Nd¿ºªh¼+‰‰í‰€ªÞ,"Æùd×Z´öo­”KVUÿ#"Ä¥* £ÿܼ—ãR˜½¦ª]–s?®â^Ô?‚¥ÜŒ«Ði8~OpnäRÂRÑEBU‘ó,ÜÂ.àö$žU²U¸—}(ÌŸ=Œ3T5,n£–|Wè&ÈP0w‡*ˆ ÷wÏ1îk,\˾²E…~ªê°ƒs/I¥R222’{ 'FF¢=†‡ót:]/‹VËÑxWË$3ÑPÕßï¡¶9¥—G«êû’à,&aÜ |Ú¦rËàÎÇUŒ½8^ãú„Ml.Ñ7¬èJ¾HxÆœ zqÖÒíï«zGÍÍàÍ„—wâU À¬%ªzpf•ÃŒóŸöc'/QÃQÕѪKZnîÒR¢;Œ¼PŒÞß{† ¾<ÏJbç~¢¢ª—ãR­]‰«ÖW-ÃÀÀ.!*üÖgyŒ*ÒqÂê¨Ò ÇZ ªƒ¸Ûëß!Ú?|w¡–&oÒ¡ª÷=ÀnÌ–noÍàm@«àŸTõ&à}ö‘ñ´ˆÖ U}Wˆå‡l>¥ªaÙLêÅéÀbô_ |@U?ƒ«fD˜…¼Þe1É‘.nÄF GK¹—øÑ¬•ÛÛÛ™:5(íèøÓÙYœÎÖ\IŒzàUè{§ˆ,ÀåÜ~#î–s¥_޵¸hú›‰–+7hýgEä à$àcøÛyø5ðKU]^püü/ž Yò)ÜmêRõö3,‘+p–øp9Ì Ùˆ+çü]UZ¤7`]€Ç#Œ:düºãÿЦ†CƬ Y³b^fUý”ˆü —éfÊoïgqzWWš+*ªú”ˆ€û,ç>PºîîsûsOlç¸Ø-`ê}€‡j´ÍT÷Yx)dܲq÷{k–ò€—%è9ø(Îú]ª=^ÀWŸ­ªQÓ~õ3_„ª¦Ïz¿›_ŽÄU¼-å_Àæ²/©ê}"r-þ•lç,´÷jî øâ¹Ù=Hp&§[Tõ¥Z­gTFêyÇò¬³Ïxž?ס‡¾~Á~ûì¿“kÑôÀÀ@ì۬˗/ïõ¹ªe€ßsË–îòܲ¥GtvvòùÏæÝúI¥jZ ³i¨÷EK\±ëßÕÕÅ”)îû.›Írö9ß*ìöúÓ}鎊‹M‰W g'`.i:ÎʼÖ{¬VyY*j½ö<\pÓ|o­ç€ÆËuÃK)÷ \P`'RŸTÕ¡ñØO«""óqŸ©ÙÀœ€\R±´VëÎvÁùÍŽÿ‚²«Lz¼b9¯Àýn³'šÍ}Ê˧¿.л÷™Zã¢`Üñ~†pßµ~œ¨ª—4pK“ž–´t[ÙñÚÐLÖíæúº5ê‰'¦§ kT Ö^…Ë|Ñxn,z£J¼;!UÝ ãºë¨Mv”Iƒ—óú¢»} žåûßÄ/AßLI°àîÃÝQ3HK‰îD"©Éd2²<‹c•M$&Œ{{EšÕºm†aÆØñªúx\m±"§eD·*,X0?rpS\«ìÚukk8Õl´ŽØ¶àVÃ0 èÏmígÀî!Ý~Þ í4½èn¼Pœ˜4“+‰ÿèk†a†1ZŠ~—’²Üû~‚ƒ'þ¬ªÕ¤/5ÆHÓŠîf³Ê¶*Ívíۆa†aÄàCÀ¡1Ç|­û0"Д¢»Ù¬²Õ000@oooÍçC#Ë·÷ôt3s¦_¶$ÿþ•Öš,w Ã0 c „VçõáF¯14•èn6«ìXH¥RlÜè—º´þŒÇEK"\Ð3Žà6±m†a‘‰#ºN¬×FŒÊ4èn¤Uv¢º24ÛE‹Y· Ã0 £®DÝwÇ©êúznÆgÜEw¡¸aƶt:ã™TkëJ244”ômh{Ñ>ÎĶa†a4„'qÅfù´­n¾¯ª–O¾ 7Ñ]U¶·wCûÐÐP¢VÙÁq¿©†fó7Ám†aAUïf‹H°5®Úîjà¹\™z£y¡G(–[ek›Š®UE_3º’Ä9÷­zÞ Ã0 £Ùð Ý<á=Œ&eDw+Xe››8®$®ÿè³}‹ŽÆì<¦òÖ[ôM1 Ã0 áq¢{LÖí8ý+i„Øž>}:Ó§O¯éœÛ•ÄĶa†a—¦òc¿¿Ú#œB/.9±í¦¬BÕX·µ¨¯ªÆÎKn†a†Ñl4èneëvZÕÄ\ý\IÊ·a†aÆD ¢;®èß¿zѪ®$•ûû‹ëJâ×ßÄ·a†a­NSXº›É*[OZÙ•¤ÑbÛÜJ Ã0 ØH4IÊÀÑ#1û‡kÁÝÊ®$áýËÇTëJÚÓÄ·a†a-θˆngÅ,;Ò?°%fÿqõÒtæJ>Æ·a~ˆˆ³€Àz Wôe "À\ ¬UÕ¡F¬kÆÄ§Ñ¢[Kþ§–B±YÄ6@WW7 ÌÜlyËÃÇÕKlwvvFì_<.jÿÜßXÞ†1ñ‘yÀIÀ‰À.@{AsFDžîîΫ¥‘7xkl^ÒÖüÛ[÷rU½_D¶N ˜î~U½"`½€÷Œû“ªÞVÍþ Ãh &ºÕ)®‚G+Xe㓳nwt´ÓÑÑ^©{‹Y·«¹Ð)WÍy7Ñm9ø%βíGØÎ{¦ªçÖhÝéÀ/€w…t›ä=^îæ§ô¿ðÝÀn!ãúSƒ;`±IDAT݆1iœ¥[GÿU Ø­ÅÅv¼þ£¯bö¯<¦9Îcµb[-Ò0& "òv‚EªÖh]®‹1ìZ¬mÆä¤–nUïv`îQÞ§)¬²ñi@ÉF_´Äs%ɱ”†1y‘༘Ãj%|?D<Á 5ü†aLNméö,Ü%vÞ¦°ÊÆgb[·ëJâ'¬MlÆ„çÕ¸ Å8ÔJø³ÿ2U]_£µ Ø„4ÔÒMI eóˆíøâ®±9·'º+‰ÏQ܆1xMHÛð5àÏ8ƒÍ¶À6¸€ÆZpPHÛ½À7€g-¼uÓ5Z×0ŒIÊxøtî®ÛÜVÙÖp%ñ× ®$9œ»¥ÿ¾ Ø0lÒö}UýNÁë×xíÙÇG€ãUu¥÷úqŸ>!ûy~¬3 cbÒà2ð£Ižül›þ£šÄ*Wl÷ön`ÕªUeë…Ï_t$fÿðqtÉI$ì°ÃÁ+…L^,¶Ç¾Ã0šši!mw×kQ™‚ˈâÇÒÁ틪> ì]ó†1¡ihÊ@Õ¢´ù¿þMd•ÍÇFé[ø<0I‹oÿ‚£1û©` ¿h Õ•­Û9Ñí'¾ ØpL i{¹ŽëN i[]Çu ØÄ4ÎÒ5(Øæv%‰K±+ÉøZ·ëg®Ÿ+‰‰nÃhND$‰ËM½%0 ¬V«êðX§iËŒqîf\·æx©7æ¯à¹WM³¦ ¼l3Ûà.–¦âüܽ5WhK“aLbÆ¥8Žû"h”Ïq#ÅvñzÑúWÓ Öí°qAýMlFó""ŽP‘{‹Tµ¢/³ˆ‹KÕ—c¿îçˆÈ†’cßRÕ{+­°öÀfÞËή»‹È5%Ç^VÕ̵#pvÀøÛTõ‡Õì1"òàƒ¸,, |º¬‘€ß«êưÎθ÷ìH`w # ëˆ<ü¸XUŸ®vMب4ا›l.–²¨¥‰\Iâ0v±>n¢Šm(Ú¥¢ÛÄ·aŒ"ò.àëÀκ¶¯õ_‘ŸßTÕµ!cvÞq+‡ù»0âX?Þ Ì‹Ðo6å{\Vòz3Ÿ>9J/jŠˆlœW¡ë¸Òö'‰È=ÀçTõŸ1Ö™ |ß›# ]¸‹¨ý€¯ˆÈ/€Ïªj*Ꚇ1ÑI4j!çÏ]^§~ÖíF ’´†àV?˜u;ÊÃ0ŒÆ"""òcà2* îR:/ŠÈþ5ßœ€wnÿNeÁ]Êk€»Eä×™ÜCtÁ]Jø$p¥ç’b ¶t{”d1 í_ôª®®$ÕJ†ioogêÔ©MàJR»¬$•qÖíD¢üZÎÏ’öÜ„·a4™ ܼjŒSmüUDÞ§ª¥.Æ‘WáÞ£°àÓ0ڀ߈HªV‘p-°K•ër pÑïnÆ„¦q>ÝùÌ%¨lÑHW’pˆ²ÞEÖípzzzèîî)[¯òÜe-£Ï² /ö¥JgÙnF'‰P]Ú<ç1Š+‰‰nÃW~ÄØwŽnàb9HUk[{Râ¹z\Nõ‚{t*à"r——öÐÿ ™ãE`).˜¶W´(ìÎÈ1"r¸ªþ¹š ÆD¢Ñ>Ýeî%>}ò¯êlÝŽ“£;ŽàŽcÝþÆÝ/±ª/ïòvÄÂi¼}Ç£ãz‡3\ùø.}¬—ÇÖ1’qsMíH°÷œnöÛÍ1;Lg¯9Ýk•îçÊ'6ð—åýEÇöŸ×ÅI»o°ÿ`T•ç7¦øæ½ÅY¶>»ïlvߢ ¨Ntç0ñmõÅóáþP…nÿÁU‚ü'®lû«×ã²eøÑ\#"{ªê¦‚ãK› ^ï‰ËŠâÇ=ÀÆ’c/UØg·³¼ç¸ýû±øG ×­?†´ÿ ¸x÷3œ‰Ä¥tŠÈþÙF>°ÆàÀ_JïU‹ÈžÀCÆž†«,j“š†Zº5ŸðºDÖ5§ØZ/°G®$7<³‘'×å³nÍéiçí;Nà¢GÖ󥿮b Uþ½Ø7’åÎýܹ¢ŸŸ>°–SØ‚Ïï¿9Éôsn=½Ëï-:¶Õ´Í«>7-ÝĵOçÿ6NiOðÃÃDr% j·Š”†QD¤87¤Ëpšª~ßgìÖ8ÿï Rî q~Þ_ÏPÕ++ æ¸x_ÀøO«ê¿ÂöU]GD櫺>¤ªo®ÕºcÅ;ÏAç( ¼WU//8¶xFDn~ÿÅÅ>À€[KÖê‚|ò¿¡ªwø5¨êC"òœ¿ùn%Í/{sÏTÕÞ²Á†1‰hX ¥G–"Ñ]®¿ãî¸~ªa‚{lÕZún§³ÊÇnZÁçÿü¢¯à.%U¾uïËsÕs,ߘªx^^=¿‡ggÌzb]Ôt»Zvo]Vl5ËöÓènOD ˜L$Âû†QWÞI>^)Yàp?Á  ªË×áRÄñß"4¿S6_"¸Gñî‡qy´ýð ’Ü"d{†´¡ªýÀ—q÷ÓpÙbæ«ê\U=Ò·a4RtX¹ýòtGÐÕf%ÑÀ*‰yg¾‚™Ëö]9+Ia¿e¿ò·U\ýd>ëÔÞsº9i÷ÍXòš9|tÏY¼åÚ|ºÿ±r€7üîYžßX)C“òá=ŠÿÞ¼´5ƒéðQ>-ý©,÷¼8Ptì„gFÕÑ͉oè i»XUï ¬ªiàó8‹¸Ó± º±ò¶€ãYà+aUuð³€æãE¤½äX©;O!‘ëEäXÏ"î·Þ5ªz¢ª~[UoVÕ » †1)i`qœœO÷¨o·;Þ$~q…]írnóÇg6²´×ýý:hË)œþÚ¹ì=ê¯çéõÃ|ýî—¸ñÙMEÇ{‡3|ì¦\wÂBÚË„y~'ì4ƒ¯ßýò¨%=•U~÷Ø>½ïlߟ+hÿ[1@*›oœÝÝÆaÛL-ÐQ³–ø=7 £öˆÈ¶8Kµ#Tt9TõYùð¹€.G¿Ž½AÙxe@󊈢6(7w°+ðPn‘—qÕ-˶å=EäNœŸömÀýVÒ0*ÓÀ<Ý£6ÞQ[o=sn‡¹’ø[Wã̼ÇhýóãJ×Í î÷½r3®:v[ÁíÖÚa³.|ëÖüî˜mèHOòÀ˃\ðŸõ>ãò–öi Ž÷|Çs\ôhoéý‡ŠçñÖe}EÇÞ¾ãtÚ“ÕY·-Þ¦» £‰9€G=+iT®i ®3*sÁ߀Q+>>Ò¶·Ï±K"ÌÙ»˜ú.ètµˆ\,"ï5w"æ¡>ÝšÓpÁÞ…½©Îw;|ò`qWYÙÕ•$ê¸Ý6ïâœ×Ï÷q!)wÉyÃ6Sùááå€Ï}p-élqÜjé^rÙJr,Ý0Â]+rþÙÑ.Zn{¾ØŸû»lVµÿv {‰ÅQF=Ø>¤í™˜s- i›/v˪Z6i;DDz+=pYg‚ØÃçØÙÀº˜ûœ… ö¼'Àÿ*"ÇÇœÃ0&< ¶t£äƒ)Ãz{câ‹í0¡.ú*íßA}«Û9¾þÚy%‚»x\éüÇï4ƒC¶šR4ÇŠM)n^º)t?{nÑÅ>s‹-é¿}´7ò]‚G×óbAºÃm¦wpÀ‚)5  ÌØñ÷ñ6 £lÒÕŠšãy¬¿Ð†+­nÄgfH[;.ec¥Çô  ðIù¨ª/'åÝ#‘ÄÝݸJDî‘°œß†1©hœèÆ‹ Ì‹ï ^îY]]IÊE_t†ê]I|÷Wòº3)¸ WT'\l²è€ò óÛŸï¯xOÚ­ø;ýúg6±n(S¾OŸsxõSÅ17'ì2“D Kvl‹·aµ$Ì·Ô?-U!8K8w#>S*w]~Uõ&à0 ¨€NTî‘£Ç8aL™½ò*²D 6Ö•$Ž¥;ï S[W’ þ{Ïíö|´Ë]IÂ8pAszŠãbïy±? wžãvœÁÌÎäèëTV¹ìñ|æ”@1,ÂïŸ(Îuân³#Ÿï(®&¹õ è /„´…YÁˑل ÄÕ!mF0}•»Œ‰À‹!Uý'°ppžÞ*œ_‹Ë7n“šf/u-ɹšä[¨}V’ÜÿQžûn6â†âZ¶Ëû¯¿`j[ÑØ8 ‡n=…+žÈ æ§Ö°a8ÃŒQ]:¦3 ïÚe?ÿwÞ…ï¢G{9yïY¡çìÞúY¾)ïZrà‚)ì0Ë¿¥ß±°÷"èÿ:¢žÃ0 ݯˆ9×¶ª:s>ñ!¤í:àœ1ο&¬ÑËHrÎUd6.÷ö›#ñÏpÄ,àV·MØ4® |ÞÒíý_°tCÃ\IrÿÇ}…Â.êvÆ.¸Ë™ÚžÈq+s0¿»Ht¼<à/º /*>øÊ™E¢û™Þî]9ÈA[N e`-%ÇêÊP´Û¢ç宵p%qû.~=µ#QU¡ UØ¢»üjmYÁ›r—œ6ëàà-{ŠŽ]ôhoà¹J+\ûTÞµ¤»-Á;B²–Tûp?[–l6ïzšu?³åƒ5Œ±ó‚ƒå¶‘wF™Ä`_ érSÜ£ü‹`;Ю؀ˆ´‰È–…Ǽ?åªê¹ªz"°ðVÂ!»ŠHã }†Ñ„Œ‹Ow´”£«ÛAmß>%ê7ŸÛÐïÇ(ßc\±Wòó„u/W:ÿf]åí|Pdøy,MøÇ§7Ò;œõ=W~në ‚-Þq&Ó;ÛÆtÑSÚ7›Íz‚[ÉÕ\ÈæÏ—Ýª6Œ1¢ª}ÀÕ!]¾Q$½Ø?¤ýºX3FQÕMß)˜/"GUšCD®‘GDä2ùªˆ¼CDv‘dI¿¤ˆ*"‘³EäZywaö¬8÷’ }fUõà8‚«ZvÓ*í×0&2 ´tkÎØ%²¥rlb;–è«´“Pë¶ÿ°Ÿ+h\auǰq~óÏôÝI‰tÑòÖWLg‹‚@ÌáŒrÅþÖîË/ üÀž›×ì½PU2™ ªYT•l6ËÈÈp¡à9I†aDç·!m;ç‹HOPyðý9nTÕW»9€ CÚ¾/"1."²=p,®Ò»€Ó+Ç€~)t#Êâ*‡þ88çfÔŽ‹£ùD¥ªêÁA³ª++ŽaL4èÓ ª£ªQ:::¶È·örÿy"±T*ªªæšBQZµsc ¬Ý…ý‹úŠÉd[§ß¦k+¶ËÇ•ŠýTÆo‚hþï}#å×2³}„øèÚw:ÂûwÛŒïý3ÿ}ù›ÿ¬çä}çõíÉrÓ3yî­§wpض3p7 ªóÙΉíl6;jáΑÍf¹ñO7–n=,5™aѹx '°ýø°Ÿˆ|¸ÇUˆ+!ðU\^f?”ˆ¥äP~ |ÿì0;7‹ÈUuyaƒˆÌ~Oðûó/U}"÷BUUD~|- ÿ×EäaUýCÐFEäÝáÞ4Î0& Ë^’Ü H$ÚÝñ¢K/³‰ä¼=ÊyNpûˆíѾí£B½ðyn¾DBЬþÁþ/µÛAýÓe–îèÙ]Ö”ùoÃìîòïÛ !|Ò³ùÁ}«Émá‰uCü}å¼ùãÓ½ ¦ó¢ø}»oN21¶ I'´uTpç\{Òé4·Þ~+Ëž/‹%ZYùl†Q U͈È{€»q·ÿýx%Nœ§EäQ`®÷¨Ä7UõþÚìtò¢ª«Eä›À]‘«€ûpÕ$wNÊ 8xÓ§ùÿp þ•0“Àµ"r=îB`.Ÿû|`[ÜÚá!?Ê/CÚ cRÐèì%¹”P&¨Ë¬Û¾‚»ôxq]ÁÒ#wJíw©¥{8SþãGõ_Õ_,ºÛÂÜ—‘Jâw›é±p:7/Í»ä]øŸµ´Õ´Ñ>—?V|wðý{lÛª{îçJ’;öäÓOrçÝ£¯¯Ö¯_ϲåËX¾b9ÃánÛ/Æ93†a„£ª?‘Y8ׂ±þ]¸8Iƒo1QÕy3pÑ/|‚¸ø|ÈZWŠÈ—€3ǸNއ÷×h.Ãhiê*ºUõ1A^ °zõË#·Þö§‘z®7FR…/Âþ^ÔRlK‰-ᱵà ¦”®¶èeéUa$£ÜQ"º_³ '¶ËÇÛÍ`ëé,ßèÞªÁt–Ë]Ç'öÃU¯§Ðûe‡'¹ã¯/EÜgÍx~ñ¢%k½¨aLtTõÿDä&œëÀ.UL1‚søº îÚ£ªëE䜛FµeÕ|ZUC«Kªê·Dd)p.Ί^-7â.ÀB‹ðÆd¡®ÙKfÍØâQ`S=ר?q­Õñ­Û…¤³ÊC«£fÄËg%9ÿáõô§Š)X8-zö–\@iBøð^Åî|ü{ "Âeæµn;Yöh«ï÷h2™dúÔ…Á²¬ë¢†1‰QÕûpELNî‰8,…ê;«êé&¸ë‡ª¾¬ªÇàD÷1†Þ¼QU?¡ª©Š½ÝZ—á‚"Ï¡BåJþ|@URÕ l&†1騫¥ûãÿxöÌ3ÏÎÞ3¬mÄVþø›ªÖó½3Œ–EÌ(á8ëì3Þ\ ÐÑÑÁ§?õ¹Ñ¶~vßK|í®UŒxŽ›u%ùé[ñÆ…ÅYœâýxãeK}-Û_;hŸÚ§´Ay¾í5ƒŽ»fO­/öÜùÅ›·âØgÄnÌ=?éÏrÕãùÒðSÚE–ôv?Ì>3³¼îàÃò»-(”Oÿ—ÉdÈf³¤ÓiÒé©tšl6C:!N“ɤ]Oàg2¹ãFR#¬í-2’üvñ¢% >§†a†aÍIã*R¶(ªÊ?^ìcÉßVŽ n€õC>qórV¤ úFš‘(’§ßý2_¼}eAåÇbÁ=œQ~úà:^{ɳe‚û §rìN3}ÝG¢ºš|ÌËÏ£PpÏ”a¶Oö’É»³äæO&“´··ÓÙÙIOO]]]twwÓÓ3…©S¦2¥g*=Ý=tvt’L´‘ÄhŠÀÂǦþ"ãYšàü±†a†aMMãR¶…wþ´t~…"7ŽdùÛŠ~ŽÛqFÔY½¹óGJÃ%ZÐãk‡éÎpñ£½\ñÄŽÚ~{nÞÅü©m¬Hóì†7?·‰•}å±0s§´ñ“#¶"QeÎìÜóC·Áγ»ybmyš}Û_F€L:4gÔÒ]h½Îd2ŒŒŒŒ>rÇJû 1’*òø9oñ¢%‘o¿†a†a4&ºýˆ“¹;¦ïv¥þ;lÖÉâçpµËÎ(#åš§6rÍS•]&·šÖΕÇmÇæ=íUª)|þñ}çòß·úûû`pp¡¡!GwÎ…¤ôy*¢o`cQ)øiÓ¦ýxñ¢%aÁI†a†aM‰n_Š3p° ‡¯<—¶D^!OïHð“#¶dNOÐÍ‚p±¾6ì¾y·¼s;–¸ g´ûöœÖ‘àЭ§ò«£¶á'lÏ‚iUùoõݬ»£wžU´æÛæ/4-SI®Êd©Ï¶ß£°L63:¶³£ó†O|ô“?ˆs Ã0 Ã0š s/ %/(OÙw6Gm?»_ «M8d«)lá+¸ã—o¢«MøÌ¾³ùÌ~›óï—y¦7ÅŠM)æNicÿùSØiV ‰—•$N{Fážåy7)IÞ²°›??á^g Ê·ç²””ä×íçZ28<@:“O!›L&:îíïøt[[{¸ó¸a†aF“c¢;€B nÎZ½pF g¹|ÔNl’ÄûÌíaßyÕ éjD÷¬fùÆ|0ã;vÝœiya³`¤Óé2«wNpûùm—>`$_K÷Ù{ßl·p»> ƒa†aF c¢»&TNè7&¼<|m…tܾƒé,_¾mYÑž>¸×$]\ö=•r–éœxÎdѲp§2Ei¦M›öŽ#ÞpärÜÉ-7¡†a†a´&ºˆV4¨:ëváÜåq”Å~Õ0>üì»V°¬7_´gçÍ»9d›©<ûl‰èN§@)r/©dÕ.|>0ÔG:[ä=’ÞÊ'?ó/\eµ,&º Ã0 Ãhq,²**g% WIÌ‹P$ºkYøxrÝÿgM`ûÒÞa¾}×ò¢}}jÿyd½Û…d3. `*•ò-pã÷Èe)éÚT*¸û·/^´äjœÐNáD¸ùt†a†ÑÒ˜¥;\[W’œ…¹ôX=-ݧÝú÷®ØÄžó¦°÷¼©Eí·<ÛËÿ8ƒ(w˜ÕÅö˜E6›-*X“L$GEtPÀ¤ßót:ÅÀp?Y-2`¯Þ¶xÑ’x¯³8±%VætÃ0 Ã0ŒæÃDwÅ”y˶{k¦X‚;Ƚ¤VüÖ¥¸á©õð‹yÍÖÓ9zçÙ¤2ÊÝË7rÓSëŠnB༣Ò!Íf.vLÈheW’L&ÃÐðéA´XG? ¼yñ¢%O3·Ã0 Ã0& &º+RìJg\¥@I+·¿¥»\E·ä+©gîz~#w=ï_í²§=Á÷ŽØ†æ÷Í:kv¡{I"‘ŒláNgÒ •Lܼuñ¢%/•6†a†aĻ;€| óønrãü(ó¿.Óݵ©&éëë-Âwß´=ÛoÖUñgØ{nw´ ï}åfd³™Q’TªPt'"ùp¤FèØè'¸f‚Û0 Ã0Œ‰ŽYºC ·VÇédÞuvZÃdÛÅU% ûú=¯Ô^Ú÷ˆWÌâáS^Å·þö<·<³ŽGV°qØ¥úÛzz{Ìéáà­¦rò~›“Ĺ”¨fÉfÕ,##ùâ5 ‘P w*•bpx€áT> ŠÇà”Å‹–\çì†a†a´*&º(ôéN$Âo”û&”xä6En&qEuá¸J}sÏ;“ÊWÝŠ/²%ªYžß0LOÌìLŒŠëlVɪ ngéN­Y˜‘¤Pt õ38<àw>þ |pñ¢%ËJ Ã0 Ã0&*&º+ ª´µŸ¦RQY”ƒÛG—>÷kTÕ×ï;LtWã¹’í £BZUÙrj[¸Î¥5t5iÜó,ªnÜàÐ`Á܉‚Œ$îÿÁ¡úûÈdËŠH¦€¯ß^¼h‰H†a†1©0Ñ@¥|Ú•¬ÛAÄâAâÙo¾0!žÛªy¡í^g‹,ÛZfÙÎýŸm[¿~ÝèümÉ6Òé4©TŠþ>‡Hg|SjßœºxÑ’G"Ÿ(Ã0 Ã0Œ „‰n4«d2’ÉdþX ‘fÉνÎÍQØösñë+"b;Xp‹ðâcCCÃlêë]/I³fÝË •¦ÌñðÅÅ‹–ü)ô„†a†aLpLtçy"÷$IóË_‡”§izœ–¯a-eTPg5[tÁÑ׿)hÔàKÀù‹-)ó31 Ã0 ØlH׈‰ÎYgŸq°ßxï£YÉVó?~·xÑ’þúïÈ0 Ã0 £50Kw1§ßöï4î#ýÀeÀ9‹-y´q;2 Ã0 ÃhÌÒíÃYgŸq °Ëxï£YP˜­èÛÖá\GS¸ xnñ¢%ëÇy{†a†aM‰nÃ0 Ã0 è3VÞ0 Ã0 Ã0ꌉnÃ0 Ã0 è3&º Ã0 Ã0 £Î˜è6 Ã0 Ã0Œ:c¢Û0 Ã0 Ã0êÌÿBݾ?í£îIEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/all-icons.svg0000664000175100017510000035074112370216245027400 0ustar vagrantvagrant00000000000000 copy edit Source: Tango Icon Library: public domain (modified by Kevin Dunn for SciPy-Central website) Andreas Nilsson Andreas Nilsson 2005-10-15 image/svg+xml en .py .py http:// Put icon inside page boundary. Align center/center.Export "Page" option (icon will be 160 x 160 at 300dpi)Open PNG exported icon in Mac Preview. Save at 25% of the size (40x40 px) for the ....-tiny.png icons (keep alpha). numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/ui-anim_basic_16x16.gif0000664000175100017510000000266312370216246031030 0ustar vagrantvagrant00000000000000GIF89aó»»»™™™333ÝÝÝwwwUUUfffªªªˆˆˆîîîDDD"""!ÿ NETSCAPE2.0!ù,@pðÉ·(:uJÅzÐÓ"ŠL¡,…sCÖJÃð ƒ"SÚP4 G¡µ -‚¢$RÊÅ œdÏÀœ ­Âד)LÂXwVrP5Ò g¥*"€aýš :1 o!Y3 !ù,]ðÉù ’‹N&›D¢IÂÒ8CS£4DPpÓ/„`E–I‡‚`0[´Ö#0XÊGà€@@£ŸÀè7I0ÛÁOÁH,‰ú(Ö óUcÐÆ%sL s•j#!ù,ZðÉù‚¢X"ÉÚZB&9ÇÒ-‡¸TEÒ%ÓH†€Œ¢Å = ! ³ ±R.€.0È|® ƒVÄ}Àº„¢Ù  úª’(ðÅ€Œ Ìà9÷‹ÏS"!ù,]ðÉ)½Ò¬uØ>öZ· Ø2@è2H 2,ŒL±‚êa Ý&€†ˆxÀn @ ‘!h˜]…°€jÎòDveÞå0º¶³M[âÕï'~!ù,FɉŒ¡XY ÏÜÖ!(ÐEI€‚åU£VlXWF0Ž /f¹d¾›d€Q1ÀªŠàš|/ œš&!ù,lÐÉé Ø­´–21d‹Á)Š×ŒÙ€ è@( ^`Â4 ‰OXLƒCAÀ’ ˜#Ðé ®FLàp`(®ØL Ñ (ÙÉ@ˆ^)ÏB!(ÄU;„B²@HgPQ $m~!ù,_ðÉùÆ X‚µBàA&Ã’|#JŠI2 fq `ˆÄäÒ`g³¸` Ž’#J ‡–²É «É!¹Èj DWd@4 DA°"¬O´ptGÁ∭c!ù,ZÐɱ5É-AÇÂq 0 ž³¨Ûà‰± ‡RÍëhƘsŠÔh05ÃMèPKJ¨álð4 ½Q¡ P0 EÄ6îp° A2QÀ¼g aksHF!ù,`ðÉùÖ¢XÚ5†WæqÞ„G.Êm0HJ¥bßXàò˜bœ È™Ð`Z”£PØM…ÆQ @ÁXIÀIUÉÒX¸Ïái$ à|glt¤ý¢½ © o3:}æìC~ÀÏ8p/ÏŸë&aßëŸ5àüáØèÈë÷údmÚ8µàm@§ÏœÍ8 àxèNŽÅ¸žîÏt‚g:ïèC6_B*•‚a¤`t##eÀÐ8‚-lË‚eY°- ¦Ù„e™¨U˨,ÍA4–!š+•»¯ø7ÆÆFGÛ}ïw;µ`éô™³~À ³û3=­0„LÇ0:zö ØÙ…R±ˆBFC!«¡Ñ kÌÝ– ‚OŽyë•í0ÆàÂjÝvÿjVʬ,/`qn õ¥ 8•iݼŸ? à_øÜØèÈÊv?‹ÝJmØ:}æì \¦ÿ¥îÇ´”ËðûÑ»çúûûÑS2Й7\Æ2±÷)'­#0o  ,²½K‹«&¦—똜šÃÔ+! 8› ”ü€56:2½ÝÏf·Q¶NŸ9Ûàð_HodÆ è‡Ñ³ïaìÝw½¥: :¸Ç‘Œ¹Ï/*ÍãLî1 Âì£{©Û{ÇÎw{°Pnbz±ŽËW¯aúÚë°—ÆAbÀ&€ßð«c£# Ûý¬v µ` èô™³Àßð¿è^wÆ¡—ö¡´çAì;x†zs(dµ5˜ZcðÀ¡… Œ¹¬ËXh&øÛÈ ¯ž‡%J|–«&.O–qáÜ9,Mœƒ]¾ØÈíZðOü۱ё íЦۧ6Üc:}æìûü€Ç×Û–éäžûÞ…¡þº †;crW‚»Ò_ý”™]Pkب›lGÀv¶#` Ç[tÃÐ ÁÐ8 ÃÐ8òŬú¤k@#cSƒ×2½ÔÀ¥‰Eœ{íTo½²7äû{ À56:ò½í~†;™Úpèô™³þ7ªé#ž*¢0ü9ñ(öõç\ï|Lr“'})fÓ+U åšjÃB¥a£R·Po: tvŠ|¢År8Æä3:J¹J9¥œîB½¥ 8gÉ õxc¦MxëÆ^~ñ,¿ Ѭ¬w Àïø‡c£#3Ûù‰cú‘1xÜ›.©ú–#pc¶†[ u4í$¦_‹ñ[|²š­Æ6C¡vKë8¾·îïF6­«ZT¿AµaãÙ×nàµï~öÊÄZ'hÂõ üßwx¡»žÚptúÌÙ,Üb—Ï´Ú†9ôøN?ŽÎ‚›{U…ÝEBß­ãÖB‚n‡ñ×gzÆiCóþ˜û©s8D°lþ9îŸi ú"dZûÕ‰˜œãøp9ÔƒbÖW‡LѦkøú÷^ÃW¾ ²êkä/üÜØèÈšµ©5µà6ÉKêynin"qü=§ppOGLʇ’Pm8Ÿ­az©"ÙŽO¶6ãgÒú:RèÈ¥18Ò)Ž´Á=†çHéëG>{“+™Ë5åš…rͤ•š…Õº!(ª+Da‚©¯g G÷tà±Ã½è.f”´cÙqH<aßüò_ÀZ¾¹Ö¥~À©vòÐíQnƒNŸ9{À—ÑÊÞg:=‰‡{:òzB*. Tý+SUL-4¼p] ¦GÂïiƒ£¯#þ®4ú;2(å¢]ÞâÏ—±p˜ZêûÈBžÔ5D„•ª‰ÙåÍ,×±°Ú$AÄ"‡ðá*t3’/èN wá}÷ —Öx˜>œ\¬áé¯<ƒ¹ ßYË7pÀŽŽ\»7O|çR6Iž³ïK“ÖóL'ö=úwpâÈ^¯Ú.îä#“ \®…Ž=…ùe¯¾:–Òú:RèïÌ ¿3޼Ë<ë9ñ$>¾!­gõSâkâB„Ë«–#0·Ò éå:Í,ÕÑ0my;ß§©XÚÐðÄ}ƒxhw$¯ ô 4-¯|ÿ^æ r«‹œðé¶spsÔ€MÐé3gŸðg›i*”î>†“ïûìíÉÅcà®T-\ºUE¥a#YºËRß}6ºÈáà`]y#¢h·vèµ`úÖÜ á„’w¢„ƒJï0·Ò ›óUšZ¬ÁäIþà¨2 0è.d؇ÂpO!žYè9 ^»º€¯<ýÿ¢>µÕ/Xð“c£#ÿñ.>öMmØ >sö€ÿ-:)ç‡Çãïÿ$Š9]‘baZ.áòd S‹ ¨ ÞZêgÓdž 8²'Cš×ë2~0ÈZûë¨ÕR’R@‘5QPáÂ;!³É…š¸1_ÅâjÓÍY@ž¹@’6€=°¯›=ù€«=ÉàŸ^®ãOþì XµÕ£²üøØèÈÓwò¼w µ`túÌÙøk™¤õ‡?‚ÇÞýdÓžÊhxËÁ[7*¨5e©Ÿ ñ€º :ް¯/›à}Of|YÚË&>‹léƒ4žüPÒ:UÊ+£è1þnŒ"'˜_iÐ÷/Î A‚r ¬«f?øøÖ[Êz¿M ™.WMüÉø¦Þüv«GÖðCc£#ß¼ó§¿³© ëÐé3gßàHRû™†¾“?„G~†Î#¶¾»0¹ØÄÕ©*EUûøßPoLJ èëðÓ Ö²ëÃ2`À/ ˆ08)â9~TJò"D¶Ž½)Þ»£¦QxªèD`×fVÅ[7–ýøó‚! b01öÁû‡Ø£{™jN¹ßj¦Ïù»¸úü—[U®øØØèÈ‹wúìdjÀtúÌÙ¾  7ºŽi) =òzluL# œ4reÊX¸h¯\]p&käk>P¨E0õ—øSîg™”ó ØŽÀ_|ó¼ù­¿9‰}æ<96:rþn¾;‰ÚЂNŸ9{À³†c+¹ŽƒïùOpüèþ@"É1þ†%ðÆxõ¦ƒ8óûÒŠPÈhxâD'z;RX¿RoŒï f&ñ,ÉLïW%ó!´„«‹ø¤SJc¦à8ß;?k—k–/_ÀezE+ bù4û±÷Ñ:ò)ï'†>ð¥ï¾‰ïÿõ"1L8àCc£#ãwñõØ1Ô€:}ælÀsNÆV2Ž}ÿN?ÎX,Æ_©;xóF–’Â+3¿»|dO)B÷sºÔʱ§¨ûë1¾Äj²#Iä%Ûø.8¦pª|Ò¤·#þÊP+Ÿ‘—áq0²Zæµ,Ûq/@‘þ`R€ ›ÒØ>qXì̱h5ðßx/ÿÍç[™ç<16:²nýñn£öä Éô[Hb~0ìyèGpâ¾cAi®L‹«^»e~0Ÿù³iŽ?ÔwÝ×á5ÚˆFTæ÷þ…rœy#·#ˆ›¦Ãb®¬$&å»—ínĘ»ÎÏ1— •‹a Î ÆÜ?—õ(¾ÞÝQ@ºeåÒ=Ô­q÷cŒà}g‚1FþXÝtÄŸ}ïŠ}m¶,˜ücÀÀ9Ã}ì1Üÿ¡Sñ‡âÒIï™¶)Bm B§Ïœý¯üë¤u}'>…G}šÆb­°f–M\™ªy6¯Ìüáò,?R‚a´’úˆGBz”$ñ Ôm’ o7æHC !Pýó£j~äHúCu>Ù.Þ*;×fVПB워Ü1Æch¯öÐ^m[f;¿÷¾‰+Ï}¥ÕãýÿŽŽüÚí¿;Ú Ñé3gŸ€ëôKE×uy½ûC04ŸñC˜Y6qy²†˜°d®ÔO ᆵ{{2-êõ“¿+ØÈÎ_hÅøk0ýÚ˾ËPûIJA8Ïß# ;zÚŽ ï¼5k6--˜^s}D`ŸxdŸþЮ1š¦ƒßþ³¿ÆÍ×C„&\§às·÷†ìs¶ÀŸ"ù3½Çððã zãùÄÌ—­Ìï~öw¦ðƒïîÛ ó+* Ž³è†nó?’Uý„AOM—ÄU§Ãuáñ£ã™ îcžyeû0ŒXøÌC=¦þ ^ “ÏI 3Û[Ò\3 Tù“Ì€Àda_í¦uirYøÏ!xV)ÿég>…ÒÐѤǜð§Þ³nÚ ˜‡ï÷0Owà¡÷ýÒFx«|©³T±pñVÉÌ/0Е“v¹ûnˆùƒì_g–Uò|äÛk1>ó"p¾½Î¢ÌèëÚ3DÀAùA³á# áƒ‹g÷KרýA.° ŒÑž®,ï̧azÁÁ„ç# ÏO ˜F_~yÜŸ[þó]ƒ¥\ ?õS?-˜±}ÀïyÏ|×S\ú>å:޾÷'ÑY”&âõ^›ÕšóQ›_eþ=Ðåælù½o²tlä©ûLq¬A¾€ í—E™!&•Èz2/S¤{  øcŠFx9½KŽkŒÉÇ ÄÓ`è¾áƒ1&$éOô÷ÁwºÚ€âé篚SKU!×]À‘=øäÿÀ5$Ч½g¾ëi×€×½÷Ÿ%­<ù)ìß;,û"£n:8w³ !’ÕþÁ®ž| {ÓÌñÔeYz¯ÁøoªûD¶‹ü)^~& ÕtD´Y[€Ë²ú˜‘„€=ˆPGÎ`C]YÍÓB MæE.¤e[ýåß^1—«MU#ÃG=Œ>Çuþ™÷ìw5íz0 3:XØó0Žßÿ’äBoÕÜžú Ì¿§;…=Ø Î±!æÛnH K‘eOÿ–lë`…ñ©5㇌Ëaâh¨OI`𥼘—Áœȳx@B¾:„ýë“L€1:²§¤ë#îj9ž9àG ’Y  š¶ ¿zþši»ˆ89cø‰O}=‡LzîÞ³ßÕ´«àô™³Ÿ€;·BSZúD¨‚Ë üפ`LÞ§•³/ÉþGè =²?XLr2† “64 t帟à$ýÑJsåºó×&,D®­Öñ³Ÿýqhé|Ò+ð³Þ;°ki×Àé3gÓ>—´îࣟF)ïï9»bbv9’Ûïý õ¤7Àüã~Åæ–bû“¹/;bÌqì¹›FÔy00Ÿñ ^B[Ü÷îûj9¹ž:/É)ˆD¥;âNB)9Hõ1¨æ€BöøÉHƒ-*ýY(ý)²¬8 ߸±`¿ycÑñ| ðîöõñáú $úœ÷.ìJÚµà8ÌõǃGbך®MבäñèJá÷w&3?ùL©0†¤$梈‡]„¨·ß› ,Ù9lçÙÛã{a´ˆ¦@"Ùáçf’/Ý•ó( ¯† Y,4h~#cÔ‘Oi™”ßÑÇs™<Œ%D9Üñ¿yífs~µcöO¼÷Ö³ÿxÒ{pÌ{v%íJ8}æl?€_‰Ž3nàøãŸ fèÂ\óK·j߆ï}&Åð¾ Ìï3}²&wèIª¿ô9þ_5Hag|øŒ¤ý†R1jx&@’“ÔAÜÁè…òäë¡È5ùáAüîà¼L$b8cÔߙոt>T³À;7‡ ŽôWÏ_k:ÂG[×ë‘24üØg>CLKìçò+Þ;±ëhW\æÏEO| Ý]nìXßZh¢nFfâñ4ç÷èDÚ¼ý¾Ä÷·ƒìùR˜rßTï$ò2sÿÉlø$Æoáä ìîã°D½ùžŸ@Í€ï$ ®Ù7+|À`!@ElÿСÈB_À@GFOö Ëô÷AA0ÆÄb¥é<yÆb¡†8¹¯—=ú¡L2rH»vœ>s¶À/DÇõ\/Žœ|Ìó ‡ì_7&¤6^R~ÿÉýyôwz‰ƒ ŸÖ$µßý"Û~¨-ÂÔÌ;"b’3”˜,¢ê³h†Œ…öü¸>“¨*ñÝm%­@^ñÈŒîû7B¯¿ K–ƒõù¬Îò1€xÿ—²eµ_ÕÜ} ¾aÚ\ª„¡Aÿ‰žúÄíèM_ðÞ]E»üwb.áý~TÉöóéÚt]íæ tu *¿*Å AY€2£‡@!T“#bn¨ ÁàšA… ëñ\N R}Iàk‚H|íÕ›Mï÷Ô‘K³>u* òÞ»±«hWÀé3g{üRt\Ïõbø@øø žíèI_òÞ‘]C» ÐJú?ð·ÊÏ#À„ñYYõ…Ô¡Á,º F°½ïå÷;o©¦@̹%V­¿÷zôGÂnª@R™Ê¬ÆG$©'<†/µ™¢‚#`~—Ñd[Å ¸W^AÀeBH×^!Ð’®KÑn(mh¬UöŸ¯ös•ñýqâaT€¾ùæDôï^»W—Kéhk.í8}æl‰¶O ýeûz):¯ûgè *•ø¤„öBÆÇ<ß âíl{Ú aè/¢Ê«þ¤¬@™qZ1>dGcÆPļœß™è‡#Ò_JÊ‘Õ{!)Cªß@®”B^òˆƒš{í)ƒC–þ‘ì?Ï7 3¾¯x@ä}o˜¶xùÚœ}îzü$k¡ü‚÷®ì Ú5àÇ”¢ƒûîÿŒHÆŸ#ÓKþ;:ÚÂýûóHé\²ù|R¢O蜋lêZå±Ð_ Þ‡ÌÈ6;1Åy„ö:ÖbüC+%¾BÙ×ýû8,÷ð_îWÀH2 ’µÙ ÈÔÜ Ȥ4æ;¨#ð3ÿà3¾d„ ’AàÅ+³MÓVÓ„si}ä©IêVòÞ•]A» ~>: gJØw – „™%S•þŸ¤t†Cƒ¹`Ü•¡!¿ù¦€7÷ž¼sÀÕîé"Òݵ%¤VÞ’„dQÀëJ|Wò*ó%Äü#y¾ “\Æv™P- ü ¡S`¸Ç‚”ÞLq &DÆÐ¤3ÕÀÁDÔ$A€Kß›¦ã¼’ <ùøý<“ïHÒ~»„vx~?<ün躚õ#ajÉuGÿ f¡kÞ’ÿÏKŠ˜A=¢<Æðjþ¼äõWâç>Ó0Ymö‹€ÂcÆWbõêu°äëÊØj…¢ï6”#LaòÀ,PT~EÓ ø9Ãß+RÍ€˜/ ã“â,ŒÂ‹—gë–#$fgÈg öÄ“O€{ïÌŽ§]þÔÜÀà°ï§¿rf9*ý_øʇŒÓ#ØŸÿÖÈ$ç_hû³PB«!?¹ù&‹+Ð4‚¬:¹D7î$T#,ÈæèHµá5L-‚cD®!rÝpSŒC3Á7i|€bJÄ@Ò8ÈdG`XôÃd_S?¸FdhX¶xõÚ\S~ÖðžÇNz_˜÷ÎìxÚñàu~ùùèx¾çŠ¥’:õfdé/9ã‡{3ȦÜfžaœ_IH·ý½68FB`*õbRX J‘ƒ˜ù 3>’?‰aY r‡BÈ”ƒMfxÿ˜ Q5µ8ðG¸æÈ/Í¥úPÊè ÂŽ ”Ò5¸ê¾ÊøœÅ$~ô{ À˜xùê\#*î÷õuðÁÇ’|?¿ºíxð$€ÃÑÁ=‡©+5¦Iùõþö÷g¡$ø@ïj÷\9.L^fòaˆ˜¯=D³¥pŸ{ µÇeš0Á’Ÿ¢•‚±R܈ʣtî ͉9Uéï3³”:,'Éê½týLöDú ÈÛFÓ~5 BµŸÖÕ†eßœ_M!ôþ}8É 8ì½;;švœŠ0®c`o¤â1̯H¥¾’ô×5†¾?åaÜß3(Xº"e^È/(”Q¶Wƒr…ŸçGH•y6ß4Pkùã3ÊÔ¡IÌ 1&¤$£ì tF ‚$ó!ôD“‹d Æ['ˆ‚HƒœöËÆ—3¥~‚q Л7n™tøè»ÿ(çÉEB§°Ãi7ÀDº‡@*&ò0ŽCXªDký€0Ðg›xxãþ’¢Ii·¤zìeAuþ!Rƒp‹˜òÅù …LÚ>ð DßKÓ Ãgúˆó.djæªÍJ!P¤‡‚Q`2ø¤ØýR&!”,¾±e Ç/<pÀQcüˆ3¾’dFA Ð".M®4›n;§€J¹4;ñØ{“æÛñÍBv4xiFÇû‡ï ¶úZX5Ãr_Es' u§TÅL þâ 8æþdz阬îŠoÕ¥d †á4!;ßZ0><Æ L/§îJÒ_‘ÌJV“͆Ð,<ïžÑ dÀðödû¡¯!âAŽ9Ecüa% f—ÍTÿ1Æ„#„¸4¹Ôˆ¾ïzü±¤W葞¼£nè/æÈéêŠ Î—=ç_¬R•0Ðé6Œ!‰Ï}S2£„LŒHo9˜¿¼Ÿ|ð83ç’£R‚Q4²@^Ú˜ßJ™QªªC$>cÉËð>p*‰A¡F2°£WîOdÎ4HNOŠ™‚Èæ Õ~ ~dP}Áïyóæb ŽØ›Ä áãD;bê®c錚éi B¥n#¦þ3B>£Aט×dßg|@õú‡“UN;oìxóµ‹à¥§@YP» _µ‡»Qä8‰žø ÙÇe:"Sšu0I[Îvý ™‘€`¿°¶ ’,¤Hɧ ø ¤^~¶b$âà3ßQ(| ¦a:–¤ö+•€J@Kˆ˜ÞØäBÅlXŽâù/åÒlpßÁ¤hÀ`ÓN€˜ ×=¤fþ1åšçN(ª+åtø€)òA¨j…€Ä“Ý„á1™?ôÌE…‡g×+^pY‰'ïD4 %~4tÇB¦gÓ³ÐI0Yª ²cÍAÉég2xx¹ùA"“”Üq: ܈ÈiÚÂVÕþ¤´_F-A@6 ÃÄüj,3ðäƒ&ÀŽöìX8}æìA$„ÿºúPíÿrÕo&«ªþ¡#¯Kbî7YõGÐ3O"‚ÜHSQÍ•˜)jp`?GípU²ËŽAj,i5]Xf|! ù Œ|•áw•Ù a²×ßs²°Š ì 1¸R+À”è‡oªˆ†åX\Œ")Ás3ŠhaÝ@(ýeÀ ó•¿ïhRÜÿ°÷.íHÒïüo[z_|ˆ¡³gQf]©ÙIŽx@GÎƃ.sL>¢ûŸ‘ÔòÁÑ0õŽyö5X Ït ‰IÝý|Gš{1ƪ YxÑX 1„Nß[ïg8‡wª+áÆÞ}ð’ÏB¾Í ÷·¹•,´¢ü}#·31k˜Žå‚ øý„1¸Wl!¾ €¸kúwï ã `ŒÃkø¹r‘â°ƒCýœy›'¼K×ïÁ;ºí´c5'¢Å޽РuîϦ-дü>ÿ@”ó-ÖÔ‡$?Åmò¨ƒQ®º ×{v³÷‡ÛÙ‡"Zy¶w¤+p˜m‡˜Ô—n,h8Ù «ÐJØO>vdÔ—HÒ (¢îËæ0¨)¿²³Qþ|ï=õ¦ÝÜ@ÚoÂ÷s ˆ`ø>FËÕ¦µZ·”Ð_&¥³G'™'°CiW@©k²Ì@nÇŸÒ èz Ûö˜EòôIGUb>£‡Û̳³ûM3ba¦ˆ»˜ ({þC¯=¹ŒÏdÆ4æ'ä@Þêü~Q¼T µ•$@‚ #®Tfª™Ã‚¨D¨å„a@€Êu«!gÿ1ÁU¾HˆO@ÞÎ?–7vk±ÒŒ¾#ÞU°“M€ØCË•z¨*|½é{ÿ¸öN04¯M¬ƒû Ë(¨Ñ‡§b“Ô{ßó¨ûߢiÂðnîú(£»¨`¨ç±ŽÁc‘Br|žk0Rùgà „ìü) ò1½–‡äÿtWûg#晌\a!¼ºw Ôš¶)Ù ÌïfÎÆÝÛ _Âï²9@’¡×ñêšä±ÀA …rÝÄÞ.%$480¸¡wi§ÐŽÔ¼"Žû¢ã¹b·’‚uKžæ ™Ÿs¸ýþ½·œ$&&_âW%x$;^Šç‡9òJ®˜ L²ëµÚ·Óé ¨Í<@»ðö+üd-A.ÃõÚy 5B"ôü‡EAr~@Þ“0lØ!…ü\†ÒuSЇ*¾[ê¼Z·jªôw¥6÷S}ÃICäŒ?¥ü7Œ„Ó‰K‘b ´XiÄêúúz’^©ûvjaÐNÕÈF³…Îà»—˜çi€*ýÝeC³s˜º§4À<•;ê­÷$œÐ“¼Ôþ!§¡êGˆf$Áù’@ff&íë;"_ æ;å@cÐ0‘…(¸É¢üÈ?±ÿÛBÉøÒ=ØÑ‡3ÿ’Ãe*×̺g¯ûxÅ ™8RMÉ " bZA$)¹È½²ðe毋b+eó‘+™üBð:%yÑ#/K‘ÜVÞ0¨Ú°›–Ccˆ1>q¦2~ø5@Ü=•a'#€¯Ö,ÛrVG>Ã5M‡ãÄš ŸÀ€i8È•zÁ8—ø’Ð0%õ?Áü¶~ÝHøÒ“ÂßaI¢+!?Oºª3øFœ|á AÌ—©L¹()ä—h„í¸"NÁ°ÊÎ/ì ®Si×ÅdmÅÿàÏ+N îÇßÉï ¬œ;œ0/?Òö $›®z¾°Ú\MÌþƒ;áG,ß?9íW1O¢ Ð)è›(+Õ¦b0Æ0¸w_’#ð v íTèˆä rÈ×}7ÑðŸÿ)ñXÍ5”¿›©&©ø S«Ù~Á_(•!yË>D¨Ç‘¥|òS¥¿Çüî5J¶;“_JMýjöS[w‡Y†I  ûbNÎ`Þ ˜ Tö;È×è‚`ÓfµaוÉ@C&n]ô£0¹â €'‰ˆ?`¹ÚŒ™ýƒƒqÇgÂ;µh§šÅ耞ÊBÒfÆ`Ú^8ÁÜö?¦M¥œ?C²KH•ò¾‡0ÜV0É€ö®#è¥2·Êü¾]ÎäÌ?5è7» µ…°{p8®&)ßCo}ðûd½†¢vw ÐÖw¡y.Ù7àÙöÁ7çÇó=ÀsÝ3¶Ti–½¢¯öÃË–dq"&¼BB5Ù'Áp}Ï7à¥C¹WB¨Ö´ceÀù|! ŠØ´k@Óý)àÃwßíá‡Ô]3Á íy*½gÂJ1~2£tNæ‡å&¡íußðUsìU‚©cîEú~~ä€Bæö# !ã{&‹3¾ dãQ¾IÞ: 8ýu¡åãs0|ƒŸäú¾jòtáe󹿚yÙŒ`YÂ^©™UD6˜o­pÏæ Ä(pú!1ã<`^¨Ï½~Å@æé81Èf2mx‡S¬ÿ¿n¤Cûßã!…aðɨnÚc+Ì­JÓÀÞ‡„"Ĉ¸Ìоó/¨ü“Ö)Õ€ ¨¸ã.ËÏ]k xÝÃÊ<µê”#L¨)¼®6ÊöG„Š c :xg „¼¼ŠùÙ͸¿|v¥¾‚Ù7u( _¸> î: Á™Ÿ)8Z=§` a""²íxÞo& %¾S;v*ÄM€H 0c ŽˆøÔ‚èW ÁSà ºÇ¸[ò0‰“’„,Ø'’&«T瓘ß/þqk B ¤GRŒaMÆ~¬-ð¯[N6’…á»`e ñž“ç}gD®Úïþso]µi×+ »ÆXރǨ~3¼kq3Œ¤Úî‚€0à‚o $i™LfCïÔN ]š‘F”/&áE}~rKÝtüÈ|é Hêw´\7ôÎËL åà•¬äø‡ê~ô¸.Òø•ƒÂóD" R5a$/-Æ÷Žj9®p·Âô¤âD(ç™Ëu®C¾Ä\µŸÈERš[i,x¿A´(úa¾}/ƒcļa´èÇ3L0É ›–Ý€H…ØÕe Àå…D@øI  rÕMKð´¡I|à§þ1 ŒØp4ê”m#³Pl}o, "—áLšân¨˜>ø¦tÎ"? ¦S  ¶=¯ò½¥jÄÀR*ƒ þªýÏ"¶±ÿ9»Twä}CC7t‹áû¸ê¶¬¾‡Þh|¦ôj$¡ïÀOá’OÁ?ŸWùÖ€…Ù}AÚn8oA¸Ÿ D’ú¹ƒp¨Ò{&€WÇ/¥>˦E.¬¤3±\5* «ÉÜ[«å·¬ÊÇû2¥ÉHdN€¸)É$04m£°#5€ É&@`ï€[îë’¢Á+Uuð$ãôr=,ðóÊ¢ó(þ35£È“’’ó-ÈÔ Â‹ÖSAÌŸÈ›„C¶ùå‰>åNÂñ–âã3wÂN™)år_¹{dÓGúÿQ×ú‚&,¼F¹ìÙÓ:–kæÂb¹¹(u÷õòü7ö+" à§E«©Î‘y•?Æ„®óì& `ט¶å6‘{nhŒÅœ²tÿjMGTê–(fSJV]˾dK„1y‰ùÉO¬ñ³=[\Î=ý]Îd;>áÓÿaAÏ?ßñ&ÍTä:?$i¯D¢¿IŽñÉæ@J•’ÂĽtœ0Þ媹´¸Ú\fA 2ò¢aÚ¯—åǰvÚo¨Q…Õ‚$ù@ šî$Š~§$"hF‚À4c‚€¶ðŽ¢˜ ì8ª‡U IÎ?JjoüÚôª fw­ÿ ºï½Zè3‚ç6ˆ:äÂÖ\RUœ|n0ÉÛ®øÔ£ˆ#æ¿Ü¡šî6 Š*­»ÔÖ_2ø…•~Ujÿ˜J»sI€±ü'²±\5+ÍߌˆLø!øÆ[~Gæt?ýû`„¦€o}S‰1CKК»vª°°ê+3BÊ›î[œh‹ÓYª˜¬«˜æ­«Úü¾C,Ø€žºÄú½ ?Ùà3°Ý>C*H TiE(É´¦ Å$¾ì`ôÇT[FùäüÊ«ä$ pÁù¹S+Us~©Ò\æA^2üDŸ@²ÿ¸›RKûuÁ‡Ü^šÉNAŒ)¸Wú&€{>2L€z­š$W¶ìíÝBÚ©ÀÅè@½V9–ô²YCƒêùWRc%Oz8QÇÕ©²éKlÉìãü²÷<"Ù QFb2ò¥j:ì}gú!dÔ~aÄ!>Û“&ódŠÍîi A›ñ°XÊ}TU$?smîp>i6_÷+UkniÕ\µ©I§ß×_îõŸÔÞK2Ç ®ä(Düaì_vÊ÷Š1*dŒX©çÂìl_\ßî—ú^Ðî€z°ëÊX&å'|ÄÔÿp9¢ TMÇ™^ªY~kùL{¾/)Ö¯ôûƒþó,쪾:qXÁ,>.È0¹Ÿ·}è “µ÷w¨Œ8Í"MBdÄÿS|#ªF";ûh¥fÎ-Wš !ãF}d¿uËïÖ&€÷»•^j4BM’4;»B&¥‰˜_˜EЀwŽÌX–ÇlÛ†ÙðÍ8×–288wýPªäpi¤0’ô Ÿ­4‡ù®¯ :à±³ït#I·ñÑF•æRU œ°d½IZF õƒ¡bÏ‹ ä ó±`êíPÚË¡¾€‰¤Ž?`Ò2”?_«P"D‚g©bN-WÍÌ2:W¤wb›ïõ}†Þ}¨þ¨Ò?Œ ¨>€`»|ƈåý..Ä,H¸¶Ýïõ½  Å´€Ze9– äš­½ê‘q0²‰ó•¦TÎëPµùÕœ€Hž€?Ï($Ó@9†´O(ÂŽ=’óËÿ Ê„C§œ“u‘¬A `XL .Ú%H’ü¾:oÚT^¬_«Ô­%Ù„ˆ<á‡à²Ó0þ=îóróD‘üóK` k ¾/ÄÐ8ËšbÔêMÇŠg®ŒŽ,o÷ }/hwÀ꒲̸Ù}2*NÀ L|zÛM/Öš¯§˜ï'€šeæ×£È˜œÚ:"[ŸH’}áÄ ð %$MBž(T•ø¾Øò²]I Ts?~ïNúékœ•ª93³\·…hI=,—ØóÑ6ßÉ ñð+=þb6¿¬5ÅL‚ ¨”KÇÔÿ¥r9©àŽ”þÀ΀sÑÊâ|^õUŽ| ’”P{îI½ô¢áA£ +UÛ"ðl›…ó~³PÊzB?R!¨F k ¾´'Éã/KyEcL–X`¤8CÆÀN–îA@)óOI0‚Ä–ãT§—ê×Ê5k! HÒ9QúK˲IX¸á±¥,Ä~¨CPjÚUHÇê~ qº¾Ý/ó½¢€g¢K sV šÔ°#—Š«ùQõ_© I¦íˆK“åêýû:ó\Võܯð’}Âã1»°CP˜Ù'©æQ&«´—¢̯ð³ù”0¤l^^ŠpYRÈ&Mô[¸ã‡¨\³æVªæ¢´›·èfûøO~^—zEK½þå6ßꄞ~¸Oó’zü† ˜FC|rÔ„¤ß/g`4Б‹•øNÞº™T øÖv¿Ì÷Šv2|nòFÞ¨T*°ªË!“Ò‘64X¶Õ(ê?âµ>#•«¦us¾ZÛß—Ï„…ê¼Ü$”ìî²2]WØ.,^ ÊæCØŽ[xÂâýñcJÑŒXoxtJÙƒåˆúB¹9iÚ¢ÉXÌà¥B¾O‚›á'µâƒ_ôã31BåÇ<«¯€ÌØ~‰‘×Ö‹Ém¾‚ŽJ~ÇX`0ÞSÌÆš|\¾x1 ¾³Ý/ó½¢kŒŽXHxpK³·„ ®Œ:óiLßZý5ƒ°¯<À@S‹µúRÅlBòÞ²^š[$µ“lv 4= \ƒÂСºö ޝ˜(j>€§Î†ì ”Š~|o`FÈ¡ÅÀd°ª.U̳K«–C yâM®ÖòËa¾pLYɹÿmFq J¦‹âSC¬-¿œ³R.¥h‚ˆÆo܈¾2à{Ûý>ß+ÚÉ|ÀSòÀâô8ö€PÝíȧ1_®¯‘ h‘(ûymzµ’KëÅlJ㾊M\S >ã/Á›`Ô·­ÉOÔó%¹”ŠÌ ™Š´Wç ŒT *וú’Ä&ÉaH¬a9«•ºµÐ0·(†…Ò#Hut}æ#„wLÍk³×> 1g˜ -]û¾Í´”é•*Èùþ€×RJGŸH›o0áYa›¯pæŸ@Ú£…Ðß•+p5­³s ŽišQžxkltd ;”v(´´¸Ñ(CËá×®ô3ìú w3ôdï?’Ôÿ0+P‡H\ž*—÷÷å³¹”Á¸'홤NûñޱɓÈŬ^Ø×›ß§q®[¶cΗk³ËU{ŒYø"¶½ŸJ„ã\ï)Ž.Ï)&ÿ† ÛP ƘŸÑ0í¥Õšµ`9d~Ÿ|?g`#xJ>s½n?V]™ï_™¼ð³ÅB¾Ô?0€••L_üþ#ûïÿÝt¾g^Jûý0É@`Û+þ€É©µêO’–D væ;¢ïÆÕkW“Þ¡«þ;^0 ×¨V«¨.L¢4|"Èýר·”åsåšXSýÖD@¡a:ÎåÉòJZ×ÐÛ‘Iõ”Ò©lJ—Ó %ær»Xd -}x°tˆyœ¥i<½··´¯·d÷ϯÔfÊugœ[¾ÏÁWß!Ûòr\™+€ YòË>IfG58‚¬ZÃY¨4¬EAäøãq’⾌zó/M];Qž½þ“<ü°qâĉ@^ýumüÆÍϤ =¿ÉÔÜábžëœR›oJrô1ÅÑ'€ ÷ˆÕña¨»Ðý5ν•Ä;v¬ÆFG¿uí<@¶WÇ@g–)žw$¨ÿ-éϱf2„Ù„–ÎÌr½zîæòü¥É•ù¥J³êr$UÝ1Ü›ßÃ"ª(c ™´‘ÞÛWÚh ÿ`1!¶îíªF—|~åÉÌÏBYÍâDd6-±¼\1oÌ,ÕÏ—ëæ,Yr2OÂ_ ärϳõ箿ñáÕÙñÏ~ô#1Nž<©hGŽÁjy¹ƒo ãOÊÈ”€Ô°  ~ÃÔ0ƒ è)fò…Œ‘—ï¹m;tîÜùè«BHÐ"wít ~À-ÌLMá¾ê´RŸ—ÀPÊ¥KéhØöÞÏ? $ )Í&åec¨6l³Þ¬6&æ«"Ÿ1´Î¼‘*fS©\Z7üV« gŒ!›Igö¦S sp¹R›¯4ìA¼Â¹nIUƒ¤h$’¹ Iý°ùˆÈ6mQ5m§Ò0EÅrDCÚ~L„@à‡£Ò´ÏÌ2k…Ù«¯ÿ#ûا?ýCz±ï¨]­Va†ÃÂö^Á¬¾A Ë‘°ž»æ™†°‘j ÈfÁÁþŽþèõœ¿p1Éþvltdb›ßß{J;ÆFG^:}æìôÇÍ&æo]eC¥¾0åÀþþ"¿4¹l·öþËörbª0ÉÒGÍ&ÕMÛlZNcv¥!R:G)—J•òF¶˜5:Öú Œ1d³ét&“ÚkÛÎP¥ÖX^­7çÍ‚ëuƹ¯Ö‹óÎ@"rLGTMK¬6,§bZN=H¢a2p „Ì)["r„>3~îÕåÙOìÛ·O{÷»Þ¥§âµ6°mÏ=÷ŠÝ/ƒÁ-nbŒS0¯Ÿ¯Áóú‘gg$6öðöñ·¦÷™>š 0Ô•Œ^Ó÷¿ÿ·I¼ðÇÛùîníxðèwüKy`rü Ïu¸Zcè+e´é¥«6LòýJ^€¤þC9UXq"Êþ5P¥{‚ú¨© 'Ê É*4mÇ\XmÎô–2{À ·M=ã|m÷Œ¦iÈçr©\6;Ôl6‡jõz}aiuvµÖ˜*׫‚éU=/kšæ(%´^û=ª¨L/ec>ÕV—z–gn>jÖWŸÈdÒ…÷>ñžìððpËkžžžÆ³Ï>‹ãÇÓÞƒ÷ýíù‰áæñ0îÎÀh[/)J~‡_ß PL‚@;~<Ñ×8c8¾·ûXôº^{íõ¤Và_™Ýò7u‹iWÀØèÈÔé3gÇüŒˆpñ­WÙ{‡3-_ &é(æR¼¿”ÕæWëòdrˆ«ý¬QLä:Ꙟ˜¯Þì)¦<1E‚Žc3Î眳õ´‚L&ƒL&“íîê:`šæF£ñÞ¥•Õùå•òl­áÜhÚ˜ãUM7jF:[çzª¹ÉfÈøjRà·˜Ízª¾º4P¯¬ ³öp¬ýÃ{÷f÷í{Dïîî^ó\¸p¯¾ú*ÞÿþØÃÃÃtqråuÆbJ?€ñ@Õ§@õ÷çíz¦Æø}_@hÿ»Àpt°s8›Òçák_ûjÚîxõØ%àÑ?p’0?¿€™ñ |øþ÷8€ËL Àþ¢±Ti˜UZË*e õ?©˜(®¨æ]Ÿ­L>x Ëfî` %XŽC ‹•‰ÎBfO&¥4M[÷G¦R)¤R)V*•úöí}õzý˲¨VoT«ÕZ¥Z[ª›u»æ,Ù‚æâsœkM!8g¾t%Û¶2¶²$ìÑIŽ=èØV_±XÔìéÉwvÑûúú°Þ5U«U¼ôÒKXXX¤O>õT£££–#—+æcˆ¦ý“þ~ÿ%*&ù}€T_Ò‚ø¿Æ;2Ø“þ/¿òª3==ýsþh»_Ø­ ]c£#7OŸ9û[~Q?ÿúËl`ÿž)õm¿Ó†Æ†z ÆäbÅQÕÿ@]{@ 9 =gZ¬ aH™–°V›S=Åô y^nçÓ+ß|}êO‡:Óû»²ÇºK¹}†¡kë™À9G>ŸÖÙ‰¼ùílÛ†išh6›h6›N£Ñ¬ÛŽ!"AÂq¦#•J¥ ]纮#“É X,b#çõÏqîÜ9:þ<öíßo~ê°™J¥_­[o¸ áÔÞ}”yýHŠ€ù¦A4¯ŸÅ’~ ¤\ƒÑ}CÝSº¦ØþBzúé§“ì_ŽÔ7ôCßá´kÀ£à¿t©T*¸öæ‹Ú‰÷|Üa^{8ÆöõŒ¹r­á8n~+¨ô¾ªïBˆH1Q - ?Þ=¹X»Ù]H÷S Õ܉ » é!®iÏO¯:—gWËW2z9¿§3}¼¿+,—Iu†±¦ã0‰t]‡®ëÈår€6»«_Þ¸q/¿ür³ÔÑüÕήNz0N-”›oÈ©Èá«~e9…™TS@Rý-€¢•~¾)æ¦뺦è+^ç÷¾ÿœ³´´å2€_¿›÷ãíL;:(J^L÷_GÇ/_¼À*s7t¯ 6@ÓŽ tfþSƒŠ÷?Aý€¨óOùèæ\uÊd‘ "‡‚BãÌèÈöº@¡Ù¦Ð–Æíï½piþ_¹4ýùK×§žŸž[˜¬Vk²¶oþÊz½Ž‹/Š¿þò—«/½üÊÄÁ£'žyòÉÏwtv4‰`ÁàØŽ˜Y­›³­züE{´,ìQ ”¤ŸhîêºO׸´,[|é‹_L€ŸYÙ¶¹Å´Û4ø|ÀÀ4M\~óíáŽ-]ì²| ß[Êèu³¾µX­ÅÂ,d|@~éïØlQSA Z¶°+Í©îBzܤ¯Hˆ¨¯3»w®Ü˜B`B0ÁôT£æ°ëµUº6¹RÕ5¬ä;²üp!£ïï(æ‡rÙL1•J­k£ß Y–…¹¹9Œß¨Ì/,45#ýZ¡{Ï‹ûö,þ ž åFæˆ@•†ý& T~ÅNî´á^»t¹½w¤¤—\ ‰ñCNú!0ê)d:÷öï‹^û׿ñuT«±Vÿ«þ¯­y ß´ë`lt¤zúÌÙ_ðEyüúø8†÷]2ú<äðLÎñ•êý}¥tÝt¬åj³Ùþ—<ÿJ‘PÔûïR<<‹€¦—ê]…Ô‘Ú§#—ÚÙïûRûÜqÆÓR ÆÒµŠÀÌêªóÜ­¥¥lN§½ w¦ÓF!“JÓéTQ×u¦ë: ÃØ88Žƒz½ŽÕÕU,//×çk«««Žf¤®§²ÅçÞÿž º‘²‰€ŒÁ‹†ÆûØäj™ÜÿýK•æ[¡j˜^’çÁwll”H`$Æ/›PÆÐŒGö}3¦üÐZ­.¾þõo$i¿ÿãnýÉ´ëÆFG¾túÌÙ?ðÓþ˜o¼ñ:{¢PHwî;^‡noÎjvßPgî Vò%%8Œ‹û…P¥»´ ‹„•lB÷sr¡6}ßPÉâœ14ÎôÞŽtïB¹1-Gg£w^M×MÝ(4Æj ¯’mk¢aÂ.§œœg@çèc$zu²ÙLN×4ÃM¥eÌK©e¶mÛõzÃj4V£Ù–e €•ØuÍH_Ï—úfzöŸ˜Õ¸nÃëd÷ưŽBú('¨ÞsE¸°Z¬6ìyÆÀvô l|£OJî‰Wõ)I?‘äwÎ=4ðÁ”®å£Ïÿ¯¿ü×¼ŸýçMÿÏv¿›[M»<úeT…-..âÜ›oð‡R™tÇБ8#]cìÄpwáñù%á¶þ ²æ‚ðŸlï'$ÿ$«ÿj6¡-„³\5§: ©&€ûÙ[Ì -”›S~òN`È1‘¦ LpÝpt#Õà,¿âí{ÅK &«YÏÔëͬ°› ‡ƒ$¸Ë?L©tç²ÍŽÎL-“ÍÕçjÃ̰Á€c`Ù”v˜ÜL:Jn€×šö9/çJÆŸ— Oò ÏHø‰á>Èå¾  “ý”²©=ч~áÂE<ûlbß/ŽØØe´k`ltdæô™³Ÿð5ù>Œ£T*êGÓÙL¡o8åRºv|oWñüÄâ’—;Í ¼ú;HŒ–꿚M8³\Ÿèȧúš€(æŒ~ÍM›H©J.ðœ·p¤IÍ59c¤çò °*uã‰T¦ÿTbÁÏ÷SîXÚÐ ºÆ{Xp½þ¾ ÀWªæyÆýøŒ‚4`¯­—Ïè­kûË}‰h_Oiÿ`gþ¡èå.--ÑïþÞ﹞•þýØèÈ·¶ûÜÚUQ€(yý—£ão¾ù¦o\N5WS@È…Lêð`Ga ûßgŠpLJþ‰G âÙ„3KõY7/àF8ƒÖ]J÷D¥¿W. ©5–<5…m¹‚æ£AÇ^( !ÏÚãõêsÛ|µþóÖ‡í‹9ã\é¯üÙŽ˜©7íÅX[/È`Å &µø½’´å~væÓ‡;ŸŒ>SÛ¶é·þÝKpü½à—¶û]Ü.ÚÕc£#Ÿð[ò˜/½ô2&®dìfUó›ìÊç t×±ÿ#Ῠ&HÛ)Ù„‘³R5§Ôp 9Dpº ©•!-À¯î¥&¶ÆS}æ‡\Ãï×õ³pû°õ¶Ïäò¼áw©}xÆÐ€È‘ ø«›Îy˜‚ó ‹ÿEfû‰]yù¥lªøÀ¾¾âŒÅæûûã?ùvëÖ­èð"€ÏŒŽÔ¶û=Ü.ÚõàÑ/ø®<Ðl6ñâ‹/²¥‰+y»Y×d5OW>°¿TZÃþ†ÿÆ¢/¯Ül4_nLàxÂûs £Ï- Hª7|dÆB„¡dæûõS¨„“~úÌͽÆaó—y½Y(ch³Nò˜ž| 8åºyIîõXÌ?Yú¯¥È`[̦JìëûQ]ã1§ß·žy/¼ðbtXø™±Ñ‘Ä>`»…Ú`ltÄð±¼¼ŒW^y‰/ݺRț ¡îBá`©$ Ûÿ!ÅŠ‰¤~}@4šFóåÆ\$)È!"ÁxW!Õ ‰©£ùaÇà`z¬Èä›ò¤ò$©tïå¡y Ìäù"]! c\•ß@°m!¦›¦X‘¤ÄLQ|d@‹jI˜ÅLºtÿpïßIbþ+W®à _øIýùÛýîm7µÀ£±Ñ‘iŸÐÇ''§ðòK/²…‰K%Ûl¸ñdOŸßÓ•/èëèœf@kû_r¦1U+P‹‰àrÊ5sÚó8Rf Ó‘OõE=ÿJ ®ú‡v¨Dgà 'ä„'á§¡ˆØÿp5‚pJ/F)ƒÃuþ)êÃt.ËçLhë¥Ìümë•N˜MÅlªãÄÞž×5Kgž¸u ÿnì·á•XËôù±Ñ‘ÿm»ß¹·µ@¢±Ñ‘çü§p¥X@·nÝÂË/½Ä'®t8V3hòÉ uç;ö÷;¥N»@‚ý ÿ€Mð“ŽdÐX,7§%õ_+M\Zïñ „£j²R„„¸ê/Ï©eþˆÝ¯ÎèË•¾|¾Y Jÿ´Ásg%ïÞÉàTöe?IJÊfŒš»gB1"U˜ò}*¤S¥ûöôüDóߺu ŸûÜo V‹™÷oøÏ·û]{»P"46:òçþ." 011—_~‰/ܼÜi›¦§ ¸}¯÷ö;÷÷;¼Mƒø? Kýà3 ÿµ²ih±Ò\pÑt¥?Ù¾9€uäC3 RW©ã:#®Ïôˆh2óûßsÊ“zÈ€âK‘Kë{á2¼I °͘¶³W=¿j øÍJ"IN±nÌŒQ!c”Ž uÿ”®ñXÃÁ[““øÜoü›$æð#c£#±PÀn¥6$ÐØèÈÁ•ŠîèV¹½Ä&.w Û”Û}coO¡{_o±$¯? Æÿå~Á¾J³!ˆ VëÖlt‚œbÖèQێų ×µ­“µ™ñÝ|HW`®Ìîj)ï$i¦å\m¥~‹„Ù—•0fÄlʧÒÑÁîŸÑ9/EŸÝää$>÷¹ßHÊóðѱёñí~¿ÞNÔ€46:ò{Î ’3>>ŽW^zI›»y¹Ë±L%Ç|¸§Ð3샀Āj'¡û_j°©„ —«æ,¼H€ë '›Ò:9ãÌWû#Î4Ĥ?S„Ѫ»hKîã{j?cÄç ¤€‰”Ásœ³<\æw`¹@PkÚ×á·ì–€DÉdTr"€ÑlòéTéÈ@×Ïi Ì?55…_Ofþp™ÿúv¿Wo7jÀ46:2àkׯ㕗_Òæ'®t;–¥±q1ÜSìÛÛ]èt—ÂòbHÌ& ©öàøòœËÕæ’ã)ExuszG(Õ£ê~’ K—ƒR?þˆ ‡eµ1}PZ×Jþ@pš±ª„@¢ªøÉ~ŒØõÃß&cè…CýW㼚žžn3ÿmPÖ¡±Ñ‘ßDd^¸zõ^~é%möæånÛ¶4„}ô1ÜS(åRµTØ zrèÏg Ð<3€Q¥aÍûfÈu‘Ȧ´néœQ†‹‡Í’ÌY-NÐ)%øZ€’˜äì±m›HxÉ?äú,Û¹Á’΋ZHæ‘zÝòoþÞÎÏ$3ÿ ~í×?‡J¥]å3ÿµí~Þ®Ô€ ÐØèȯ8¿rå ^}ùe}îæ•ǶÂ<èÜ«{5¼ÞæÁ:¨Þl L B4½u¥jÍ‘C€#ˆÈ±²l:]ÜU0¤Pb–›p%ÿ®ÎòÛµ`46:ò¿øÿEÇ/\¸€×®¥–ç§ÇTw1ÓÝ[Ìu@µËˆPŽÿûþ_Š*5sɶmضM¶còm8¶ 9þ¤§IIEÆŠçÓG„±]<’I<ŒAXfsÈ—þ>X–E¦íLÊ¡FÄ@(Ѐp…9œ1>ÐYü Æ Cb~Û¶ñÛ¿ýÛIÌ?Wò·™Ô€MÒØèÈÿàŸFÇ_|é%ÌMMµŠWAèþíï+îÕƒVº,Tû% ¿=$€öªÔíEÇqàÛ†eÙ€cv¹þ8É~öŽ£d"¶È¥;• AÉ?¿P(øcŒ ÛlÍf³`Y&Y–ŸùmÛ"ÛÁ-T’Lx_Äx¸¡¯#ÿ„¡ñ½ÑûýWõELOÏD‡'àJþ+Ûýž¼S¨ ·Ac£#¿ àÿÇšÍ&žþ,LÝì&á ¯k\ï+e»b€ð·„ª‰lZ³DÙ´,ËqìlÛ&Û²9'³,¹è(ž(Ä’£‘ì¼Hz°ïðS2ÿ8ƒ¨UV‡<ÉÛ¶<-À„í8 `¬®3€$fW}B3)ŸN½;zÿ/_¾Œo=óLtxmæß4µàöé!RA833ƒóçÏë ÓB‡=Ål8mN$|2 ÂP¡û½a‰EÛ²a[žà¸¬÷ùˆt(+ï’Âk1G‚Ì¿0+‡j¼ê¨V­ [– Ë´„ez&€e›ˆ‚KÜ ~¿¯¥Ä:)åÒFŸÎ¹ÜÕ‡Ù¶?üÃ?BBS3mæß<µà6iltÄ›2¬¸ŸÏŸ?Jy9ߨUÓ€ËÎÙ´Q0tM“^úx w‰¹ý@M‹–mÁvlOÕv}–Ùè"ÚF;'ÍOK n¡ÈfÃjy¥Ôh6ò®cÒbž#–e =•™”ÉZ@´Y¬V‚ ™´ÜËŸÀ[çÎaqi)ú8~gltäéí~'Þ‰Ô€; ÏѤtj4˜ŸŸÇêò‚\ B¹”ž¤[>±Øa) (lÒ˶íX>ó»w ¶eq»±Ú-J•ø#0L´IH³ ’i¦/.ÌíµL“LÓ$Ó²„e™°-‹Ñ‚nuµg¡bçCú]r7¥àZý»¤sÞ#ß!"Âo¼½_HèêÔ¦Qî¼lAEú¬–WQ¯¬æH8žcH§´4b9r"âPÈg›Ø¢m¹ª¿ì hÖVý‚¡ ÂŽªTMòD4°‘ˆ—!È•~.¬,/ Ûžçß2M˜–%LË‚n¤n"1Ư‚QD[ û) Œ€hœw)÷1,.,FoÏ/í¦‰<î6µàîп”ªµ V«¬sÑ¥tÍŸ™†Z$äý„²a‚§æm7@>X¶ÅêÕJ9¶îÙ J€²>ô9„aÀ0i(ìèjJƒÙ™©ŽF£Q0- ¦éJ~Û²`™–(utNÄ%<þ Ù’¢$ ¯¼Ø¿ –W^ŸðWÛýðßÉÔ€»@c£#߆›|À—Á2›A·átrqJª?$g˜¿Ó3eÛ¦mÛ°- –›x˲Xee¡Ç—œ5 ‰¡|f„‡'ãD{ò IÈ Þš˜Øï«ÿ^ÒLÓãl6•Î4b•‰‡¤ü»ýó×c±:ÿHÜÿ‹c£#±nmÚ8µàîÑ›þ—ZÍ-HqlK÷ßwC€(±ß·ÔŒÛ¶˜e²m «Ë ýÞÝ…©ù@T%OHÊñSÍôjæ÷™^ÈϲL²< Èfó7×*æòµ2IÆKZK,ËBdBvšïÒ®àPyV­º(·H(¥i©VI@ˆúd©-mÄÒÓ…ùZyq€„€#p¦ivÛ–©§R)¿‘‰[` 9²Ä´d58 cÐÕ®\¾ÔS«Õr\ãÐ5Bp4‡4¡ÓÀž=îo‹LÕåMþ埇üzo2`ÿ·atÎ3,ò~&dýÅÚü¶isÔÖî]÷¿4 !`[¶î3°¡ótÂ>a€µE ÕS¹BÙdZ¶í…ÝlæúL>?3Ù+yÕåý¢êv4çr·P‡ŽA/ˆ®^½¼ß4›®÷ß4©i6a™Óu}&Ÿ+4¤(¤szç ú­Ì ÿܺ¦ÂC¸”±TÀ6mŽÚp÷膼P­UaÛ¦ŒqƸ¡qE¢­©ú·ÀHçæ-Ë‚c;p³ð\s`qnz é jnd3@IÆ‘&ß  1;3»ß4½|Ó$Ë´È´L*utÜðjbZå:´"èš2§€ÕÕXÅß®šÈó^PîË µj $ˆ9¶t êȧKIqÿð+‹,+ëƒa¶Ø5o{‰7^þ=,Û¦òòBO³ÙÐÑBõou<éìJ6¡¯ø¯½újoµZÉ»Rß„ï´,[:|Ä ÿ!è•({ü¥KH(v—åP`JÓú¡¶p÷© w˜_˜c€m™Ôï.dû÷\G$FýùRW™Àš~€eYÌÿ›¿ÚêR¨ÉÇŽ• KãJ6ß[o½¹ß4Ma™¦h6›0Í&3-©TjºXìh*¡K5´,ǵ<@ÚÐGÇæçç£Cm à©í¼{4 À€ññxèÁaY¦–APȤ: ëŽpÛzEöW–Y Æð)[蘫ÍÜÚ+„Äp›‘˜º5>tàèÑ)Wx3á%ôgŒƒ‘à`œ»É>ãpànäp`ÜË4k眧R†­qNS““…Ð4 𦑮Lb½½½ã,ðâÅzqЬˆoÇ Ÿ@û.\¸ /.{º´é¨ w‰ÆFGèô™³7\uuaq½ý)5ÀåÈÞR®wf¹z[Þk‚;ä0ArÅRyêæ•CÂqHAŽã!5êõþÅ…™b6“mr@€‘ã…n>9Ì[¹½ÉapÛ3òz ‚ã\ºp¹»\^éÖ4Nš¦‘a¤à8é†á<øÐÃ7[]sŒ·[‚BHùtj˜1¦´û^]]Å­ÉIy¨­þßjÀÝ¥+ðp;ïÚ›íîXöǺò™¾Í€c[ºå45Û6¹›žK(•NÛDd›–™Bpæ86„Úõˇ=v 1—É €#¸Lá‘C—齩Ȅ "!„#!.^ºt̲š†m3hšÛ±™®é¬#Uœ¹víÍ®l6ïä N._²s¹’S þ€hýßœ5R÷GÇÎ_¸­œÞ¨ w—¾ à)a|üì±”ÙhéLÖ@Ù”^̧\Ý´V[ıM½i7²ŽÝÔA$˜:w1WŠk™|¡\©”Çp!„CŽ#hêÖ¡½û†ç<¦ ò>áJu"‡<)/„Ïôä1> G‚„p„°1;3{X‘✓ãhЄÃÍfù|ß|¹¼˜[]]ælnš3Æ8ÓtžÉä­b±ËìîÙÓH¥³¶_{1¥k'¥EçÏÞ¦ç¶ûaïjÀÝ¥?‚[ n>ÀôÌ :{ú éL6¨aÝ×[:rqráÕ`/ÀÀÛ4jõrI8–Θ¯®“€û©¹É8¤yË¢Ôѱ:uóú^ÇqH‡»š€ Å…ùžÕòR!“É4ABÀ",ûŸÂñ>} "ránâpèÖÄTg½^+1ÎgŒ4MgBpnPGg~¹^«d×8cœs®q0ΛZ~eyžOL\E±ÔÝèë.—:ûL™×ÝïjNT.•Ú«q~‘*À /FïõW¶ûaïjÀ]¤±Ñ‘éÓgÎþ $-àÊ•«Ø·o®§0€\ZïìïÈ Ì—ë“ Ákµ•’Ù¬e¸g§ƒ“`äMù á0òËs}i‘Éem0æX¶e@Ø:‘£ÙÈÑ''^ÿÐÞ½Ý&ÈNƒ¬ `gAN°³$ì òDŽÆL"2AhQ“€&5"¾àþés33·JŽcfáhã ®Ï#›KÏ a¦ÃcŒs]cŒ1 c LÓÌùÉüâÂt_*³zúö.÷÷ï[eš}0(fÒ?Šˆóo||<Úõ· àÛÛý¼wµàîÓïA€7n`fzZïÎdsù<Á7ØY8¼TmÎ6ëU­^Yè$w²A ÄÂUÙÝpœÐ"tÎ}ç_Àð_úÒ—’Ò¤Úöÿ]¢6Üú÷^}õUvüøñ®£'˜&fš@ì¾ýû¼véâx½^o0&€à0óœ–f§+“ƒ2~7Œ.Âe€¡ÔYB¥bBG0¸=éé&zû:"84C×¹—ÌppNÐÀ4‚ÆÝô\" –ÙÀ«¯Î@Ó Ç-˜0N(Ó…õ „Ƙ½pöj¼ñ^‚1éˆü¶“×À„ÃmÀ€1]7J¥lîSˆØþ7nÜo;ÍV½46:ry»ðN¡6ÜùÚé3g¿àþ˜mÛxöÙgÓ}ƒ¥|±`’s‹^؃GŽìåü¹›¦Õ$ «ûA·†Öcx)»V×Ò`Zʓƌq î)aj² Μ æ2|³a¡T*!“I9÷ÜMóKð¹÷ÉŒ…¥Â:ç˜_XB&Ó‰Bž{M€p#<øÐI¬¬, V)Ã|$`~g3&À˜5ÄYyˆk•š#2…(\ô&<Ÿ„`œëÚûÞýñeÒÙ"1©Mû«/~1IúÿÚv?ßDm¸wô‹^”߸qo¾þZÇ#ïz|UÓ4òÃ)ÃH?tì¾ý¯{6ç8Ôã@7²Ð´8ãà\c‡Ï°„b©€L&j¥êüàú LÞšÁá#û@`àÑz ©fWiHA„«W'Ðh˜àÜÕ8gÐ8ÇоA ìÃààX¶…fÃDµVÃÊòšÍÇ„m›.€¹…„9°ú£o>L”ºåˆÜ%éÆ8{â]{¨³³§ß¿1†K—/‹‹/E¥ÿM¿¹Ýv'Q»èÑØèÈ%ÿ":þÌ3Ïð›ã7²D‚ FDŒˆX:¥uœ8ü@Ð<&f0R%¤3ÝÐ8K{ÕÄ^Årܾþ^8ŽGxÍBw¡›7o!hâïÌüý#Þ˜knŒOÂq܆#î\lÇÁÐP_PJ˜2R(•ŠØ³gGŽÜ‡Ã‡ïÃðð1ô÷Dw÷0JC(Íö@Ósœ1Ú§ñòÇ8*'ï;úðá}ÃGyÞˆà·Ôêuó÷ÿ÷“ÞÍÿelt¤‰6Ý5jÀ½¥@±WMÓÄÓ_øBja~A'€ƒˆ „•.ä;püðCH¥JÈf»¡i€in®ŒRa#×Òºýƒ}ÞœŽ;iˆ-àÙÙyÔëÍHE!w+ÃÎ@a_¯›çôÔjµ†7‰n³¡¡¡~uG0hÈd tvu`hh}ýý(;PÈfQÌgQÌçÐQìB©Ô‡Ba€ >ñðƒï}Èû1A§á8ô›¿ùoµ••rô^^0¶Ýt§Qî!yÒê£ãõzŸÿã?É­,/k® 4¿·§{¹ÿ=Èe ñl"ôz_ …_‡Ž@*eŒïÓà ¯²{r_Þ„¶@ñc‡°oÿP¨50àÁ‡ŽchÏ@°_¨Q„> ÆÃCsãðÁ£xüÝŸA_ßak¤ópáâ9ë _øb‹¾‰øeo*¶6Ýeb “,¶éÐé3gÃÍ_uìÚ;$~ò§~ù\Ž¡Nìó‰m™¸~ë2*•e/„GaÏûä^8oqqßü›oÃqR)ï}ÿ»°ÿP$ä‡ äç¦å¸×áÏ3Œ1†óç.cnnýýÝxàc^è`œ{ÇôtνcJÀÀ8ãÈdö P8Æ47û˜HÒ]¼ôVó·~ëw3¶¨áÿã±Ñ‘6ÝjÀÒé3gðMÅ躎Ž}ög~’õõö…6z(ÜÁC¥º‚™¹ ¬VC à`#…‰MÓÄòò2:;JÈåÒA¸0`z¨ùÞÜá1¸'×}ÀP˜à.:¸ŸÌõ“k:²™!äòÃÐ" ‘ýWNAÏ|û«Õ§ŸþZž'EÃïŽüÝí~n;™Ú°…têÔIžÎ }¡ØñÐ3Æc/<çŸúô'ñè#€3ß»ø*¸/5ë fæ&P.Ï´ö˜’†hn:‘"í=ãÏ?Ox &i C+ƒ'åƒuêç:ò¹aäóÃ`܈ö%†ïSh4ªøã?ùƒúk¯]Ê"™þÀGÛa¿{KmØB:uêäàŸ¦3ƒ™R磽­º?y~ø‡ÙlVr¬EM†¦YÇÜü–Vf\—\Àô20SÍàŒ">²­"队1 8܃¤REd3Èç‡À˜Ž0÷ î¬\^™Á¯îßÚós+­Ñnxblt¤ÝõçS¶ˆN:Yð€Èd‡SÅŽ‡ò­¶/–Šø‰Ïþ†‡öúxÑGبV—Q­­ Z[B³YSí{Eò3,âfÏøÁgDòû€À9ƒ¦eÍö “îF:Ý Mó£@˜È@ LO]Ưýúï Vk)Ø«žyy»ŸÙn 6l:uòWüòX67Ì‹êDÉšc O¼ÿq¼÷½O £ØHÔ$ôȦ‚íX¨Ö–Q«-£Z]‚m×Cfö÷Sþ˜ú¾¶À išž†¡g ëidÒÈdz`>vIY†-€H R›Æ³Ï~_ûê‹¢Õ;GKû;Þd«mÚjÀÑ©S'Çì—Çîà(Êã­ó}¨TŒ–ûf²i<úîñîÇGwWoX´ã'õDLJöñúu;†Pþa¹ŸdDÐõ4t=0»¦¥ÝÜ%8’¹0{| $°Z™Ä³ßyÏ~û Ôë­{x8Ný†¦eß?6:2‰6mµ` èÔ©“ÁUÿÒu ?ð‰ÇÐÙ±ÃÈãâå>\»žYó8FJǃœÀûÞûô÷‚1.€œïÏß`>„¨!iñí£>f×`#©úä`uõ¾õÌ·ñ½ïC£a­ù»êµë¨®^øK"ñÙ§Ÿ>×ÎöÛBjWn ÅÚ\Ÿ8y¥ç>\ÁÐŽç_LÁl!(-ÓÆËÏ¿×^z Çï?‚~à½èï@:¥:Ò£ gÑè¶‘1¶á-ƒoŽÓ„i­`yyßûÞóxî¹K0͵y™ÈÁêÊëh6¦àÇà–úþƒ{÷Ú¥6l ítvfÀ˜ÛÜíÃGØ7lcÏ`ßþÃ̬hy0ÇxëõK8÷Æe õ`ÿ=8zô0úûP,t"eDêb6zâÊDb-V r`6—Q­-â굫¸pþ:ÆÇ籸XÁFȱ+XY~Ž­lÿÿ9uêä<ýô¹¶`‹¨ [CCÑTJÎÂ[uåó„S?œÁ¹ /¿ÒD­Ö:–ˆ0ukS·æñýホL&…¾N:´‡B_o?ò¹èº΃9Jõ_K DZàÂ1á ¦UÅ­‰ œ?ããó˜ž^ÁfÌÈ”!Ð×ÛD­6ƒÅùD°ø?<± ÏhWRÛ°têÔÉà?ó—>ùÔcèê\F ™L>øK¥²Herд ηðüóËX^¶6}Þ\.þNärid2)ä YäsYär9d³d³d2¤Ói蚆z£ŽZµŠÕÕ Êå2–—˨Tê¨ÕLT« T«&jµ&GlúZ2iÂÐ@%7"áŽóoàæÍ‰¤Íï{úés—¶û¹íjk[CJB P­:èêô—C €ÈkFM{´ˆw=Þ‹ êøÎwg0;[ßðIkµ&®_ÛØzŒ±MIòR>ì²ÑÝiÁqløéþèk?  [@mغ˜™YÁðÞ 3d|¢Hç^w[·êÄ£àòåU<óí[_¹«x7™Ÿ1 ³Ä°ÐÓíÀ±¶ bÍò†ËŠi7C¾ÛÞ¼Z~7)Ÿ×0Ч£¯—£»‹À™p[“ÙÒü4bÿ÷p躞ýÛúcvµ` èé§ÏMœ:uòo|Ò³mÏ|ëe|ôc¡·g@h ¸stˆp~¤ l¾o¸„ýû»ð©Oi°mÂøø .]šÇ¥Ks_Z#ÛîîP*Å1´'ƒ=ƒ) öÈfÇöúÚŽHA$Eš¦ƒz=ѤYE›¶„Ú°uô+^„7q(X–…o|ý%|àƒbïÞ,ÒiÇ«—÷¥9y¥³a[pHÚÏR†¡áر>?>h6\¹2K—æ±°PE­fzj5ͦ…õ4þLFC¡F±` —בÏéÈå82 ÅGW§áµs¼†¡rƒ‚ Ôá˜ûÕÕÊå:VË~4¶ûaíjÀÑÓOŸ{õÔ©“#p Û¶ñÌ·^@¡PÀ>ø0ö gN³P:)ÜçätZljý8z´–iô,¬®ÖP.WPY­ÁŽ-¼J>wò1Æ4ttäQ(Èçup/]XHLníÆÇvg.dNýG$Qé™)óóó­n׫Ûý¼v µ`kékrQ©TðÝニS§>‡²h4 4›·ÁØ*«Á0R0ôt#…T* Æ586Á¶,Oí6MW'AÐuÃБÉÈfSس§™ýHe ºËv  ¦s?Ýïn¨ONù’bMÅ’Ô}¿qX³iáÖ­E€‘ÎáÆ›I÷h À÷¶ûAíjÀÒÓOŸ§Nü+$ÀÐÞA<õÔ»18 !•vΤa)hZÖ+ÌIÁ0òH¥ºF ªÛ›FÃ%H7twê/Í·2¸RäDî|žfaÛ i"åzâ€j¥_TÂ˳ …-Ãb¥å•*ff–á8]Ýx«u˜ôé§Ïm¯GsQ¶N:y ½íûð±=ˆÎŽ€\µß審T }½B:Õ+íE0­4ÌËÞ4\¾=Íà¹;o¸}°¨X l f÷ÖCîø+oWóÃíÝ1A„©©e¬¬¸Y¹|ã7oae%1Œ9 àßÖ‡´Ë¨ [Kÿ'¤i௯O~øŠ… €|hû{þ¾\vC{>Æ´È¡RÆ ½Õú+ÌuNí¶ ¿JË@¼ÊrÏ@¦ŽEæÏ &7&nÞœG£á^ç:fçæ1ykªÕEþ£§Ÿ>Wݦg³+©Ý|‹èÔ©“Ÿðwä±T:…÷½ÿ8ò¹%9½üš–Â@ÿG˜?$ÆRȤï»Í«ŠÖù'­‹.²ˆà—J=UA03»Œ7æaÙ~tÀÀRy·Z]Ìž~úÜïmųhSHm `ëèGü$rÙ9™H€+þ»:‚®ç×=°®uBãpÄzÙQ- a wéß“"‚åÕ:&'æÑlšnÎŽÐ0~ó:V–—׺¸¿¼G÷½MkP[Ø:uêä€Êc]]à\ï»’ ìÕd3ƒ>‡Æ‹ £ëûbÝ~€¸0h%&7‰ø,ËÆÍó¸us>Lâ]Ý]س§„cÇ£«»k­«ùÍS§N>µÏ£M!µ`kèýˆÜëc÷íC:½ì-…Ù~ðŒ"‚‘êØð ËltË„oñmâ}þÔ#ø`à8³3K¸ty «•Z ”Îå°w¨Ý Y{Šx÷ã÷ãÝï~ ¹|¢V“ð§Nì¼GÏ M Ô€­¡“ÑL&¼õaöŸ'±IDh6ç7z|±qßY,vß‚ÙYâF®ôw™™%\¸0ÙÙî¤Z }ý]ÞSB&¥¦§t ·+Ç{ÅbÂä§@/€_½W¡MqjÀÖÐè@:-€ð>½w ÕêÄØ¢¼¡íZôVSw¥-å IÀ!ff–qîÜx×A ¥Ž"èAg)%å„ÎAÿ8…,ã>ˆ|²&pæÔ©“¹{û8ÚäS¶†–£N¤4Ö-þÁÜyD„Å¥7Ðl.®{pËž†­[q…6|0²æ¶HØÎ¶ÌÎ,ã­·®czjŽAU_±£€Ã‡ú±g°]c±ãËy>å3À‘#‡’.!àGîÅChSœÚQ€­¡XWŽÅÅúz]W¼ðÔg@5HؘšþþQèZ²PtœUÔ›—½Œ>ßµ¯2µôú‡"ÂòÒ*ææ–±´Tvk„p³ ‰¡«»ˆîî<8ŽãÀ–k!ç$N±˜kÕˆä1º=jwQ¶†¾¸ryû÷G6ãKø0ûÏõÆÆo|}D.7 Î]gŸu4­[hš7Üöàl³Ê\kD¨×›˜]ÄÜÜ2,Ó‚ Ç0M ºÎ10Ð…î®l4/ ¬TûdÒ:rù<ª•˜ö²ñðG›îˆÚ°ôôÓç¾êÔÉëúc««¼òò${|¹lØXSí ¸Bó‹ß…¶’B:Ur§èæÆ5¯ÙçFjÿÀ¨Å¦„J¥Ž••UÌÍ-¡Z­ƒ¼â ÛqÀ¡³«€ÞžR)T:ä78KŒ´28l[ ‘Ü µ½Ol÷P¶Žþ€#ܸ1"àñwD&ÓPJ€aË.[Ô¡1Œ5,ywûÄþþžµ\E¹\E¹¼ŠÕÕš[î+#h:ƒa¤‘Ë¥ÑÙQ@:¥ÃŽÖýGÔ:iRùÄÙ¶ƒzC¨ÚCH-ÓÛtw© [G£þ>€ÇåÁ›7§0=3÷¼ç:”G_šGêTP€ü@˜COà!"X– Ó´ÐlZX-W±R^EµR‡ †lÖ@wW©”#¥C×u†Ƥ~¶qè³ä¡T7Ö„;úf@µÚ@­f¡é´Ô\^Øî‡µ[¨Ý| éÔ©“û< `_ÒúTÊÀ©ý8öíëC:­q‚®3¸8­{%ÁÞ_* ]7pض€m9°lá61]¦wMã0R2™²Ãí 6ʸsþ9¶€®óÑïà8ŽÒ#@îúã8vhHã~+0'h fGÆlX–ƒÙ¹e¬¬TÑÝÓç_x%©  `èé§Ï-l÷óÚ ÔÖ¶ž~úÜS§Nþ<€¿‰®ÓuŸ|êƒ8p bÑA*çypî3½ŽLººÞÆgY bH¥\ÉjHý¸¦Aã<м‰Üü"!!(è9è:æäŠƒbÅ@ñ CãÓ†&€m&'Q©ÖÑÕUÄôì|óÀµ™ë¨ [H§Näþç踦iøôGHNÀœšfC×uäsÝèë}†¡¦[öÍ ³¤(ìqA,L.$q.ºÎ4¬ŒÆëfòVD¾ûê~hÔê&nÝZ@Ó4‘ÍfдkW¯'Ý" ®¯¤M[DíD ­¥¿àò€¦q|â©÷cï"'Ö´?ˆ={~8Æü`è=(äžc9È ¾Éf]´z/)í7©Sföû$7Q£þDÀüB·n-Âq蚎®ž>Œ_¿Ñj˜#ܦ{CmØ":uêd À?Žø#ïž*ˆL)%ؕԺ–E߇פŒéȦoîbغñ±„Ê`¹9HmèC³iáæÄ<V½ëÔÐ?ØîŽG=‰¡={’®,àOO:Ù-¢6lý#}òÀ±cÑÛS`I™€a «ëAhÚúU~/Aã›»š5$þ;Ä?#À@ÌÍ­àúø êu`€¦Ø»o݈€b–ãĉCØ`Ò‰øoïÝch“LmØ:uê¤à´<¦iŽíçU©ý·” B&3°ás$÷ˆÒR­€a{ÿµ{V* \¹2………²×r 0R<8ˆŽbJªsÒáà!¤Ó‘©Ì]úïN:™¸¢Mw—Ú°5ô! 7?ðàt”–@qÎùL"FiÃ'`,‰_Öñ&KüXG â–ecbb7n̲Üz¦qtõtá¾£Èf¸ÿÔéÎriàþN$]V ÀïÝãh“Oí(ÀÖÐýÑb1 ÀÍN ê7i4æI÷nèÎÕ€*¹5rƒà¤°_XœàèóÆmÛÁôÔ"ææ–‚Œ>C&—G__¹ ‡eÙA]ƒl2• ÉADøcìár;aå^P¶†b^:¹@˜ú+·¨Vo¢³ãä†Nàl²@$ز5xRu°e9˜šœÇÜÜ’; ‰Ç×\Kah „®ÎŒ›äÇù)PB Ç#®ºaÀ2c]÷@ÒPY8|ÓÜ/mp¸mj›÷€XHœ¹úX[_]“‚D§w5€¥å7ÐhÌ®{>Óš\·#ÐFú$…½ß·xgrrçÎc~a%ìdÄ8zz»pÿÉaô÷\ßÌTžúÏE žh†áÝ7 î{êFÿ‚ûìý1ÖÚ“Ù¦µ5€»@,©³¦ä;#¢¹è;Y^µÑåõÈT˜ßo N®Sprú«Ø·÷TK€í,¡i]AØ Þ`ƒ¿Âû-ñ±r¹Š¹ÙE,,”aÛH„ã ö¡¯·@x)¿2ˆI­Î)¢á÷¡†f³»!è-¸ .ÿ VZ€üéÎz Þpï–¶5…(µà6ˆÅ§ÝT!«| A㚦n~kbûöu‚³º*%)dÐl.âæÄŸ£·÷½Èe÷A×]f³ Lk¦u Œià|e.Vþߺc †‰¹¹%ÌÍ-¢Ù´¼š¦é Öq`¸Ýy©> YÒËš@0³±÷Ù´8._¾šx –%^ƒª¡F™}£cI ÐÚ°Ú,ÃGÇææª_,6®ú‰‰)LN`ï^"[ÑäÉAÀ—^@yõ5èzš—ëϹ¶æ¤!±ËmÙÀ%Ç!é—°Z®À!˜M·)HWg÷ #—Möm8¶ DÔzÙÖÓýNÇ!óW„K—¯be%Ñw1ùê«SÏ#€ÍjQ5(i]Ѐ–”Àô2“¯ÉðÑí^xáÖê§?}üÏ9g?ëoLDøîw^Á?ô(ö ›j€Âb¹e8 È#NšT¼‰÷VüŽ#P.WP.W±²\Fyµá8n5 4 ( è;Ú‰R)TÿÙã‡> ­Ì“Â}´GË×_+©À²œß˜›«:ˆû¨ZJwÄb½mÖÔv ´@¢L¿ž”O†ØúùùêÿÜß_ø €¬¿’ˆðg_ÁƒÃÑ£ÝH3ÕFö˜>|_CÑJA(/¹@RCËrP.¯be¹‚òJÕíüC`C×P,f`:²Ùòù,²ÙŒW¬N^¢F, ÚøPͬј_ªaòÖ nÞ¼ÙªD¸~þüÜï@•þþg’“#Qºcm@@‹õÁEí0Øõý6 éoW ˆ­ê©c/•ÒþuÒupÎñÈ#'püÄ>tueP*Hg2Èdr0Œ ÒišpÃýÓ p®»íÁ˜« 8`™LËí `YvРÑl¢Ù0a2Ù²†î~O¥SàLƒ¦i ûÈ}éï÷ð4DZsÀí`¹½ ,«•:+(¯VqýÚ Ìϯ;ϵ´Tÿáï|gü%oy£ê~«mZùZí¿Ö¾;ÒLص°†´o%ñ×búVZ@ìŸúÔ±lÚ¯¬um8yÿQìÝÛžžKyèºáýéиM×Á5B¸’Ýq†n@Ó84Mƒ¦3èº]çH:Ò™4²Ù„T÷ú¸Œ2¼ÌüÂqæ÷ßÛ²Q¯7±¼RÁÒr+Ë«XZ.câæ-”Ëelð«­®6Ï|ë[×¾æ-Ó:Ÿ­Ö%Âí‚AËu;v$„ëÖ“ök1öF×!ºþ©§ŽýJ*¥ý÷ˆ› ‰d¤ tu–pßñÃxôÑ“@!ŸC&†nÐ º¦ƒq nR—.ƒ+—ªîQæ*Ã{€mÛh6›¨×›¨Vj^K±jÕ:*ÕðsaaK‹K¨Õjeø€ˆ07?_ý{ßÿþÍWü¡È'Æ×„µ~3ë¨Åzïv¾³hWÀm2þÝ‹Ø6O>yðÉR)ó¯Ãðü. 9ttÑÙYÂÀ`úû{Q,惦þOç^no0¥·W¹gYžên9°ä¿žoWØàѽbþ;ÑüOŽ1ü†ÀÁ¶íE`LcypFÇ¿…B™Lét†a¸IAš¶ööç frgí±‚˜¿išh6›h6›h4h4¨×ë¨×ë°í*³b±~˲–á¾Oë1høãhÝíÇÿžt_ZÝ·V ¹Ö³NzŽwò¬±Î¶oKzG€G­hÒvëm»PØè¶I/äZfÇÚ/to¾ùæËDT‹žpbbâžßl3Þ»DT?þü›ˆ3y+ænÅäk£|ÿZúKžM«g·Ñíîæû…·[»²2mqo‡Ñ7{Ìõü ­ÆÖJ¥bU«ÕoEO¾²²‚ñññ{vskµZÐýW¦r¹ü½Z­fa}&_Ë,Úè½Ùèý¼ç¸ÉÞê¸ëmƒ l·å´ÓÀ§{u£o÷¸q0ndÿ`Ÿ‰‰‰¯$møÖ[o¡\ÞX‡àÍiš-{ãÆobsL¼Ö½Ü Pnô¾môo†îÕq·”v*ìxzíµ×Þ¬×ë·, ßúÖ·P©ltž€õÉ4MLMM%:ÿªÕê‹çλ€¸Óëv))µ÷Nµôv¸†–´S`37}£ÛÒ&·•÷t(«ÔIDAT¡uƒγÞ>ôâ‹/þ?I¾€z½Ž¯|å+˜™™¹ãY©TpýúõDÕ_Qþùç ¡—ž¾oè·DîÅZÉ5½Ñc­G›y¾›9îf·ÝRÚI°‘—áN¶ÝÈúV/htYÛ(³Älrrrvzzúß&]T­V×¾ô%<ÿüó‰m·×#Û¶1>>Ž‹/¶ôüONNþîììì¬tM¶ôÝÏŒ~_ë÷Þ xܰ®÷L7»ízô¶Ë |ǧ·ÈØhh³Ûb“ÇX/\µÙ€Äm>ùÉOžîêêú¹V÷È0 <øàƒ8vìz{Ý©ÆZ%ÍÍÍa||ããã‰Rß§ùùù?ûú׿þØxZïZß“@.)ý·Õ8%k=`Z3úz@l ”bßÛp·ÀÆÊ~×rDmdÝf!o4ã¯U‚ÐZÞò`ùSŸúÔ/vtt|v½ûU(0<<Œ|>L&!jµVWW155…z½¾î=_ZZú˯~õ«ÿÉ/úz€Ð Zm³Ã'c=FÅ·»« ðvc~`€Í–ÿÞ-‰Û8vbfZ3|Òw üÀüÀÏöôôü¸wžöÜÜÜï~ãßø÷lüíÌüÀ`ÃŽÁŽw°Áuë1|tý†œžGÝsàÀæóùwiš6¨iZç¼Çk¾à8μã8Ó•JåÅëׯïêÕ«S ·–¾oFúÊcbåµþZ3‰á“Ö¯·Ï]ÑÞîŒïÓŽ€àÇmÜ$Ç6ÀÆÁc#û%íßRÂop H¾–¤kkE´Áå;Ñ’ØÐltÝF¿Õµ®9þNa~`‡€µº%}—ÇnGß躵®-ŽÃ#ÛnæÚ׺ŽÛ%ZçÓÿ¾Qs`½ã´ÚXŸ£çÝè~›ÒÞIŒïÓŽ€à‡®?ñç½Pç‘p̮օÍj­Æb·Ëûlõr¬Å¤þ÷Jè¤ó¬Çð9ÇzçºkfÃ;‘ñ}Ú5üàÁ®KÚf£ëƒB«c¯µÏzË­¨ÃGÇèöYOØÈ6›ñ$í³ãß§]Á_º°®KOb°µy³Àzû·üÙ÷àV®÷­wî¦ÙÐrÝN`|Ÿv-(7aóZAÒ6]ßjÝzÀZÛbc¬7v'D[o›Í˜ëm·ŸDô;°6`ì(¦—© jþçF¤?°¾t¿Sf_OÀûn­wÃ$ØèvÑZ­ß±L/SÖ uÀÀÿ¼SgÞFx3N¼µÖo‡ÐjÝÝ4 ¢ã·e6즗© ¤Ÿüýn8óîTåß ³ß-X/J°ÑåèØzÎĤmnÇy¸ë>Jm¸MÚ $}®·]Ò¶k­ßŒ6€ÛܶmæÅ¹›&A«±¤ñ6ïCm¸KÔäåÛ çm”É·Zبš¿Þ¶òúÃFˆm†_‡Úp)Á¬jñ ܞʿöþFi³&Àí$ÅÆÚ̾yjÀ6у<¶Ñ<€–§¹ÃõI´‘f3¹Ñåu%›ÑïµàmH‘Ùc¶"æ;™€›ÝfÃŽÀ6ƒoµàN‹u³mn÷Ei3õÛ˜ÚЦ6íbúÿÏÎ#|¥‰^‹%tEXtdate:create2010-02-20T23:26:24-07:00.ÃPÖ%tEXtdate:modify2010-01-11T08:57:17-07:00~¼2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏtEXtSoftwarewww.inkscape.org›î<tEXtSourceTango Icon LibraryTÏí‚:tEXtSource_URLhttp://tango.freedesktop.org/Tango_Icon_Library¼È­ÖIEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/external-link-list-icon-tiny.png0000664000175100017510000000353412370216245033134 0ustar vagrantvagrant00000000000000‰PNG  IHDR((Œþ¸msBIT|dˆ pHYs ‰ ‰7ÉË­tEXtSoftwarewww.inkscape.org›î<tEXtAuthorAndreas Nilsson+ïä£tEXtCreation Time2005-10-15 ”W“IDATX…í—klTÇÇÿgî݇YïÃàGÍ &Jp°!Æ ±ë¨jƒËAXmÔ|j£PBEÒ¦ Q£x}K"…ªRiª*M¢Fj«Õ‰ZÚ",›5Vb”»4NBlÃÚ»ë]ïÞ;súaý€Í¼*õ/tÏ3g~3sçÌ\bfÜÌ_4Àtúß$#x7ý¸ÍõEÂdÒä *nD®Ý=•#‚Éèð† æý[Èèp^kÇdt8É88wÒ>PveÀi¥– )©ç@¼®ÙÚµ¨%)8(ëÞLNzší$#Ø)K i§ODN(Uô ˆlдÈè BÊÕ á‹ÒÓ…Å€|PTÁöq nhûQ/ðÖÊáÉñÒrˆØk+¸ÿÎxù ²ø.GÀ¼Š‹à°­Ç Hu hÝ€6ˆãcã{V( `>”xR”AÉ6(J@Ñ“ŸÀÈÈ7‹|k¼zù¨ €Îûb©0jt½kz@Åc£¶·Õ÷B$÷‚èvnm’¨ëXA&{8PÓíî Çó>ooˆŒ. M½ÊÛê{Ù¨Ý Ði@Ô¤ª¬·¡Ô¾‰~úÂK!¸ˆˆ PÄšþL€—/±Æÿ™xN ]Q¦FÅ|’uÖ¤-{ ©À;¼­¾÷ò~´pˆÝ€–öR@;=UØ,æAN¦A˜ÙÓ½È0$ûø©»B¥­€ÅÇo (¹ÌTT ÎÖïž[@jrFY.ijµ§¦Œzõ¤`ׯò¤`„†=“Õ<Ÿšƒw‡ AªI: ÔÜ^IÍ*RUÀîìšôÃ_áB05 =‡R6SXl&££Žæ“°©Qó;Sõø;ë¨e¿6ŸñüÜÚORµJU56??½ælê½U)—7—ùª ÂóG¼hi×™`NÙM­Z‚hîx€™'¸ÁLc´°@KÛÜ û'Áb4µjWê—²qÝ"£³JµoÍ8XšÒO’k“RÃtõ)és(+3x=uÓßg´Ä¿Ä·UhT4Ë9ë|ÒJš–”Gƒ¡4µ¦%íhF3˜34üs½Cv‡mÝúMŸVU×­Òçù›w>êËx·€76æ¾¼q¶÷†6µ²üö‹ÿ204øR°íµòò[Eî¿ÝPþìüM;Î+ÍÔ&2:âñêØþ‡MîÂë8®G^ F.†Þîþ Ç¯Ç¸þ®Up{ßûÕrdò_¾d‰onañOw>œ“qY€“sC‡>é;eƒætë±3²¶æŽâR-ϦÝ®¡vùœâÒòÅϼþ}÷²°ŠGCqèÂsÄæ2Ϫ5+—U½µ%#)tácÕ‹œùå‹nßúÇG½ÕSÅÍN¢“•ˆ÷Ž*¿]Å™=òzuÅ×ö<Õ}ÛhÄ{ÌdyN 6@Q¸7^9¯Ì““³ê±77çz6ü:Úv]G-«ëÂpì+_²Y¦aÊ"îæo¬^XCnyÂT0•@®k–†A„€ÃÅ—Î)uÚï¼gã®Ç|¾Æ_µ^3«'Éž-äð”Tí¨YhÍáHŸüVefwvÿÙwúôžÝû8.뀗€*f6™y”™cÌeæ3GV–jQ›ÓÉ1ƒwÿž]ûú{¶~ç·‘©beu_­ÎôöŒ\8u|_ÃŽþß`šMpÃoÔB‘úøÄÁß5üâÓ§ƒþÿO2sÝô€ÿ!n,%þ¼flIEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/0000775000175100017510000000000012371375427026071 5ustar vagrantvagrant00000000000000numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-cw.png0000664000175100017510000000155712370216245030116 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœmIDATXÃí”»/Q‡¿{çšÙõ&h¶ÐXNB¢Ø„D¡Óøt¢R¯F¯Ðø”*B¢SQ؈U²“õš}ÌC±!”3§ñëî½ÅùîwrüG8ŠBIÀ}Ò;Ò+ŸKkÂ(J@(¥êu™Ê32ÃÒ*]§Ãbqnœ­õ"Ëóܬ qŠÍVÀCõë;Gïßo¢4èL( ¥XÝÛ""¼gŸ±|?9›³«{¢mhÛ®½Ö!ŽÉd:˜™Ê³¼0IO–½ƒsŽO+xµ:$ Ä|÷¡ƒ7kSœe°Ïåèä†F3L¤øO „”+û‡Wd‹Ëòï~+1E¡ô£Ã]9Ûh‚0ÂXšjÍOl(Ìo—/o ˆc¾¾à0˜?_T:ËȨ”Ο«K¢êùvXÔi–¨³¶='  ˜Ø”mÂc E«Ó^DÂ-€]i€ i€WI€ÿˆçƦf+RÌ»%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:49-07:00ä[å%tEXtdate:modify2010-01-11T09:46:49-07:00•¤Y2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-sl.png0000664000175100017510000000120212370216245030106 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœ€IDATXÃíÓ±@P„á}æÈ5 ¥¨ƒT ‘)@*“kC¢‘1ï”ñ nØonö¤œÔl- 0I5 ˜h@G ²<¿XU”NÒr® p÷LLR"ø`ovô mÜ/ô ’õ{7£ýü`’ØJšiÀ@nÁóÏGØq–U%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:49-07:00ä[å%tEXtdate:modify2010-01-11T09:46:49-07:00•¤Y2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-bm.png0000664000175100017510000000304212370216245030072 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœ IDATXÃí”ËoTuÇ?¿;w^m‡ÞÎ;´ôÉ#RmhŒµIKkÄÈ#!eEâIÜøè®\é’£q,hŒQCÁšÁ””Rú 0SÚNg†i;s§3÷ñs1íô©©Vö›ÜŽ9÷œÏï{ÎùÁ–¶ô—˜øô4Ê[Çøêòg¿¼J$œ@8œ<ÒÀGs¿ð…ï0çEÚ’ªŠbÞ¥ˆ“;â”Uø‰ww“yjU«ÛÙø$XEßP?‘ð4 ‘Ò±&PJ@ZŒ'r ¤4ô™4l‡mnʵïúàw•xy¯½;ÕÂå+C$:ÈåÕAAYiíuNNìLØ÷qg™«×›8Ýc7¾éãõ&?Ÿ¼YMgó~ø#Ì6Íé|jŸÏMç‹>ŽÖI:›xêjùqÚMèÒmŽGST±’÷?”×ó¨ø3N:f£¼S[Îáöv1Ô³&x·-€go–Ú]AæköðÛíiî „)2t<êfÎâvçA)„À¥€j›(^/Ò4ÐC}x÷íC8·Ã’dç €®cݽzz±Sdý~Š‚©ëX†ËçËW‹FqÇb+Z¦þ´%BUóųYdÎX¢t9n7v&ƒ4MP¬Óy[‡Qþ<õçΑ;r”øþýÏœa×… ¨]]ØŠ²²Ÿ—b[i1­-5lÞŽçÑG&™/¯Dûþkÿàcü;ÊñGîãæ”JoÄÄç˜2J€ta\eeh{ö‰FÉ `D¨.'ÚîÝLúýäÄJpuÆé£µ1HS±NøÒU®ôÅùi ^nòð¡p‚€o/Ž0»ÏñŽjÚ*MsˆgôOÄ™ÏZkœx8%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:45-07:00#ûv‘%tEXtdate:modify2010-01-11T09:46:45-07:00R¦Î-2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-kh.png0000664000175100017510000000223612370216245030102 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœœIDATXÃí–ÏOAÇ?3³»RZZ!mXä„’ šh¼M<Ï\4ñ¿ñ‚ÿg=˜˜xò¢‰áˆ?À”?Ú¦lwwÆÃ"C $ëwš|çíÌç½·ófàÚ6ë‰8@!i€×IÎPŽâËHÏå`cÓ:ê Pg ãdzê6âáîÑÎ6 QM‹qŽ*Åÿ‹µDÇAåòÈGOiÝ¢õùKç ?f­c+P…<îÍ2Hyò7 ¥NæmuÖŒ!ØùE´·ßÞtéE0§®'Ðäíœô¾Ñþ>(ç-ÖKë¼Gòï®âR¿$@¢ïrëƒIg ‘$Àµ%n¿ç‹ô\~ð/%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:47-07:00´dg¸%tEXtdate:modify2010-01-11T09:46:47-07:00Å9ß2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-sd.png0000664000175100017510000000165212370216245030107 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœ¨IDATXÃí•ÁNQ@ÏyÐ ´6±‰$5Dj5QCBhø|€ÊBYêÖµ >ÿèÞ…;Ù€ Œ((j $4Ú¡hgæº 1€ Igº gwß[¼óî½ï]èÒå¦#o'1³iH¶퀀)Ô¬búDð,Pé€@¹à• Å ȳ`Þç½b­Oyñµ‡ñ=›^?ÚLØÞTf~g@YÏ0rd‘ð£3°)eæœø™D#¹#!}* áÄœœ¸R.´ØJ¼\ëeÂI1±Cí‹ (4-X¾íSíoé\òaðüÁ´'S¨j("æ²EØðd¡ï—ÙºÇëÒ3 Ù<–Xmø×—á6]¾ìnð³ºÍX6On0‹ÐÞmÿ•®‰¹rG`èVšÙ'3¼*=e,{·í·¿Z@Á>ôtôOÊ¿SIèÇw‹,é‡P2 ¼¹¯ç"ð*Çȧ:ñƒ è!Êgèúð½«Zoâ‚å†xøEzVØhœ‰D„Á  âÂJ *ÇàG; ?~ã³Õ“èg1 äEvîôÿxœ†XÇÿ£.]n0¶Ë7˜i¾%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:48-07:00B,Q%tEXtdate:modify2010-01-11T09:46:48-07:003q¯í2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-mq.png0000664000175100017510000000363712370216245030123 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœIDATXÃí—Ûo\WÆkïsÎxf_Æ—±cÇ‘Mí¸‰«S¢ªÑ>4¨R…„P"žxà¡UÿŠ„Ä ©AÅ/ˆ–$€‡”`|‰Ç3ã±ç~|n›‡¹dŽ=mM…à¥K:Ò™sÎ^û[k}k¯oàKû?›Ìûݾ/Œ1O‰¿³´âÇ?x‘ï¿v€÷ÞÈO}‡ ŒNøƒA9é¤ã >ù0Š ®`ŒÁÒÇÖ§@`02Ò¾7€9éÇB¼ D‰°5Z«¾b)0´VdDZ”¢áz{á©Ì9¶Rã£) àØ*¢^L;¤“aQkxD‘é à‡]¯É„Íìô/õ"ƒi‡B©Îïþø ¹B5–FQ"Ž­;÷ôn®µâ\Úáúåi®,f £ˆßçöñƒˆÞd*h•¨sÙ–Ï d{¯,JD®_>/™´ÿ®Ÿ:—Rˆ¥•J ÉÔefrHV—§ÄÖZ8á'Vc R?fk¯Â¹Á s£ÜYßa/_A©þ$êg¾Q(5Ø?¨±²4‰ë|ð—-‚0:Å%ÕÏ1†½|•üA«KYn÷榇1æ,Û?cAÓ øçö!Z o¼²Ìw¾¹H§l½8±9Œ$ÉŒ$ñýˆó“CLdÒœK'ÚeþüL–¥¸05„8–f&;Dá°V û°-Mf8É›¯_åW–Ù+T)–êäŠ5’–Vág§ADH%-ž_˜à­Û7˜È¤ØÞ+“+Ô¨Ö=Òi‡Æ±ß Cõ¢vlÍüì(cÃIMŸÂARÙå¹¹1^º>‡m랪ä™á$ FÑJ(W]r…Ü\»ÈüÌḢeõÇ~ÈGöx²{ÈÊR– SÃh-|ü¸ÀýG9ÂÈ`ÛËR¨6),뙟ýƒ:ïÿþ<Ü̳²˜eøÜ~²“«°¹U±žñ@~ö›»ñL»¡ h-ƒ1t¬DøúµV—§¸ÿ(ÇÝõ]¢žÈŒi‘Y)A‹`€0jõ`/$ £ÿˆÛ½µîêlöEL}¡UÿE³~þÞŸâOÚ(õ,ý'»ï,%謉¥¿O[ïþ⃞´‚ei²ciÖ®ÎN9<ÍWùó_ŸrTu»,Kñöí\»Ôpw}—ŸüêC‚ ê‚OØ<ÿ• .ÍãùoøÛã©dõÎpH%ŽE2#)V'ɪäKu´’n«õFCDøA ¥IX(%(+KY&2i6žq½ ÞA±ì¨ÔŽÙÜ*QkúdÇÒÜ”cg¿ÒMŸ|ÆA(Òª”„ìël|Rd|$…ç…Ü[ßÅóÂSÂä 1DaGÅ@vlWo,0™IŸyQµ[W°´â…ËÓ¬]›Å:!JT¿Å‰„¦Tnð¯Ý2óF¹us‰™©¡¶ð9›)QضfãÉ~òÒõ9n~í" GǼÄfVB*ióú·.ñ½[WpCŽ*Mnæiº>Z©8Ó?ÅlK3w~˜½¹ÆÒÅ ¥r“½B•ÇÛ%´R§I×R6W—²¼¸:ËøHŠƒÃ:ûÅ—æÇyíåE Ÿ3 ”Óƒ|cu–+ÏM`€\?ˆ¸us‘å…ñø, GJÕ]ŸyŽî±vm†©ñA ÕçwÖwð‚ˆžá”LiuD®Xã·xÌv®Âêr–„Mlì³õô(Æd øeçGÊU—£J“Í­ƒ)­…¦ÐtýÖ®­µb"£&ËE­[–] ¥FW˜X}Q¹/‘lnXéóçi‘¶o1z‚I8N›’³ëÊ/ífÿ™­c!b,%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:48-07:00B,Q%tEXtdate:modify2010-01-11T09:46:48-07:003q¯í2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-bz.png0000664000175100017510000000321212370216245030106 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœˆIDATXÃí–Ík\UÆç~Ìܹsg&c&“L“´Óæ«ÖB-4Új%Šu#TT(‚àJè!îôp£‚ Ñ®D¥ÅÄÚÚZ„.SKZÓ´“¤™4™$w>îÌÜ™{‹”ºêd…l|6œóþÎÃË{ø_;,q#>º£š@Æw@E~ºÝÃRn¬Bü €«‘Áw·ZTŠ)íIbË0¢ç…eçÕ!’NÅì&ÕQ„BÑn0³¸JfirµñèæÈëáŽ*:Gö'ykbˆáAAOD§Ö,aè¦eÑvÈ<|{y†ë·—i¸ÍŽ(ËMjc…tN½2 $ (ÒÇS%>º¢£HC3q½$?\Îsæçi*µæ¦ *éµ+nTÞ91Ʃע”jw&5½FÞ]äÁÚ]2«wX÷×Huï¦æÖPåÙ±>ÓsZžßBÙÌ¢#c}¼zÔ îfÙ¦—8™™I¦ç¯ãçkÈüMžãâ¯_cÕM<]¥ZŸç͉Æ÷§6^Áv$X¡¯¤¿KbÂìÕ(·~á`]c(0Š_¬P)—0C]„¦VXùéÃáê~ƒ@ ÇÛCX¡@[†6HÒ}QÆöh,Ù Ä…åó_`Õ®2š´ w©hš†ééM>MpÅcöÂ9¦Î|Cw3€]É“ðH§ºÚº µ³g_qKR®GHŽ «K”skÔ ‡S#ˆgÆqk×qê5nÇ´B=Ävíc 5B!w“¸%Ø·+Æ­û¹mAwÔ@ÈB¢©AÉ÷ÙÑ*%d6‹„ÂaêeŸ¾Óïcv “Ü‹¯ ¦×fp\›§¢FÛQÙÖ@M¿…ç{(ºE$™F5+x­¶W§©† +w±½Dz÷¢ ÏAVÀBPjÛ„O’ܺCPKVC4ZuÂjDª;ÒG¶Ø€Æc»ÍŠP<¯…‚ °îlÌï'¸ÐÖûY›õª†Ó,‘)Ü#§Í“³çX¶ù}Î’š‰­ó\å"»âi Œ³ä,Ól6¨ “Ù¬½MÌ­Øü9[ååÃCÜËÞF6iÔ×(T 4D+¢“†ãæ’Î|ñ.ž€J$œàêTž…›v“¨M‚SwùþJ†‘=#$C=  ¬ÈQúTÉh-TÆÐMJ«*-iéVPD™eû!–~ˆóצ¨ÖݶMØ~ A~½Š"C<0MÉY¢é:xšKHí%jô¢ªQ\_C3òå9$‰ÈA>?;˥ɼMþZMä6}¾»2CËoqúäa‚Æ2޳FÅ¿G±Ü á»$Åê éÄÙU¯.Üãìo÷q›þ¦Ÿ‘`Ⓨò€¦)îåäñ4Ç$A+bê-Ù"n$™/V¹qÇæÇkóü1»B«åwr-¢ÿØ)Á êô÷DH§¢$»L@P°kdÚ,æJ8æ–R‘ørà¥ÎPS€”r#–‰À „è8 =vv¼òð³­ùo%&ã£ÖNh*; ð¿v\4Õ+wÀr3%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:46-07:00l %tEXtdate:modify2010-01-11T09:46:46-07:00cNÔ°2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-cl.png0000664000175100017510000000160512370216245030075 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœƒIDATXÃí–»JA†¿³;ñnT¯ˆ—Î hccaa'–‚o`í3øŠa©¡… ^  "(¨$Fa7ºs,Œ"F’ ³.B~˜á0æÿvæœa¡¡„%ƒK{5“TaeqˆÍõiÒ)§Æ÷$[ÕPUDÞÃòppW·j –¬Uˆœ~>`‚’]­•$ ‘U×öàU,Sé$1˜WXe ÓÂÂl†æ”çø¶–ùZ›}¦Æ:Yœëe~&C¶ëŠÃ³¹ëg¬ÚøT•áþVÖ–G˜ï¤ôj9½|B5ÞcøBËÁIžãÜ#Aqt^à좈*HÕ÷Þ+}{7Ç}¾DOº ßϸ@àö!äæ>ÀZð=ÁRn½¯Á|mîÈ–I"-Ç€"(‚ˆ÷ê“zY5áã%ìË¿ðr*mÆi{ÊþìDÛ)éöÙî&Pt pê@ša#u}œK§Ëÿ€Oê4øÁþÞÔjRED­ž‘ÉËë·ñn…$Šøzî¢ ¥ê¥0DÄâùµŠg:Dô/¯yëö–‚ÏùƒC‚pÙÀ8„3U’Î#÷w·\Œcn Ðo=wž˜©¹ V-Ðxi¼ÉdJ:R» øÆÄ"”×kl×w(÷ÚxÓ1•jòfœEd0÷PQ’÷!q« ÁVÒêÊoLŽN®Œ[€€:÷\d¾ÚÂa÷ÜμÉ'gQÞÊù_øÀ™k€c×#—™2ý–6_2œ!¯W%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:48-07:00B,Q%tEXtdate:modify2010-01-11T09:46:48-07:003q¯í2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-mt.png0000664000175100017510000000145212370216245030117 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœ(IDATXÃíÕËJÄ0†á7iÒÎ`›ÎIÐRÐ[rç¸ñNÜxg"Žˆ8ƒ¦2­µNZêB7JaÚM¾U$yò“¸tQ×uãÁÅÕ”Û“SŠË¢Ñ vYœTo%å2Cú>~h¶£&€c€2Ï™_O cÃöV‚Ъ@½¶TeIž¾°(V¼‹“eøQˆÔzã•P«‡Gžgsž–)ÓÙƒ(Æ®-ãÁIr€× 6 uUa­åó.ÖÖb¿ú ù ùwÂÝúÃæ~†Q¯Ç~’ƒlv÷Jh…Ò!ÑdÌh‘C4jï~7‚8fïèék„òZYü@úš`Üþ›$[_ÑÀÀ~EÑÆ§ÿà¢kÀY×€×..ç PéeþÙ%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:48-07:00B,Q%tEXtdate:modify2010-01-11T09:46:48-07:003q¯í2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-id.png0000664000175100017510000000115312370216245030071 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœiIDATXÃíÔ± €@ Á{ä‘|D]$4E HTA€8ÊØä¶dËR‚kgŸQ@Iê4`§ Èá€$•?³€q]^Оëf¶ÑàG@”$ô”¤ƒ4Û ç'¾Úë(×~5%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:47-07:00´dg¸%tEXtdate:modify2010-01-11T09:46:47-07:00Å9ß2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-bf.png0000664000175100017510000000144712370216245030072 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœ%IDATXÃíÕ1NÃ0Æñ¿G„†´àE]+±³s$$&ŽÂÂÈÊÀÌÊ '€ "†––T$$~ aa´«(ßèÅ¿÷l?CÏQ³ý‰W€¾¾'¾Ê' ð¹yX€J *5Çá¸ù]sˆIJêXPY © Êvñ3€¥Br|Ù½jý4Œì‰!šÖìNW w*>ö„×Ç„ïvMÕÇGÛömÛN£œ³wn¢W£ŒúÐ~¦égË$¡Dq;oÿ±ÅË–¦èÙ_)刕á~™r™gLz+be(Äàyr·èSKÛò·Eߥw@#Ϻ÷ÿl½'aø×\{ŒŠæÜ+  ˜ùtñž¾˜N$ï?h%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:45-07:00#ûv‘%tEXtdate:modify2010-01-11T09:46:45-07:00R¦Î-2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-to.png0000664000175100017510000000154312370216246030123 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœaIDATXÃ픿NÂP‡¿[J!†ˆe`€¨,,l°FžÀ^6˜û0ñ†‡ ,$e"Jb ˆaàO¬­ Š5& …Á~ã¹í¹ßýõô‚‹ËGX–e+Z¦ ¦ B <ž5c6ã±Pà¹VƒoÞý-2°YIHÒQÛ¯Å×ñ˜U¿7‹m„°%0oµhj6ËU©„ðùØbL&¬‡CºÎB×ñ†Ã¼´Û(Ñ(J$âH;§÷¹OÕ*–a0o6yÈçV*X«•# gÒ~`ç\d2œÅãŒëušÆy:Íu¹Œ"ü~çdUEVU½TŠ@2I ™D(Êö!IˆC ,;[Ñ qY,â Yv»Ã'o‹ÆtzK@Ü%öNBl6µ¬Í­øÓd=m$!ЀÃåœü/p\èìÝeO›S œ4—w^iºc[BC%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:49-07:00ä[å%tEXtdate:modify2010-01-11T09:46:49-07:00•¤Y2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-dk.png0000664000175100017510000000160012370216245030070 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœ~IDATXÃí—ÁJ[A…¿33Ü©ÉF*B+u!}ߢ«¸*-]Õ[_ÃMß ë. í"]†@I !©i,%ͽanؘÝaþøÏÌÀÿ.ÕV^¤›œ¥rôŠò»*r–þ×sêG ëßAŠpÀ6`³Àâ=x!„<:à€`5½¼ÀZa å °¬grG¶{œ àsßuJ€¹j°péÓÆO|¿)2 M©V9‹Üai *P© j¿ÿЕ'š$Š{Ï)î>‰Q»CïÓ’^?º Þ·Ðd€YÊÌ"^§‘ë~üÌä6$±üô …­ Hnn|»Ä~}g›ûM òÏòd-åÃ*ko^"kÔ.h¼=fØh¡ÈAv£öu:¥³øÁÝÔhDÒé’\urxdÙ`œGzXš{.†Ø$‰”šÀÏ ^ýu/çö, ,¥:C‰‰àóý˜œfrJ¿>$šóö¸t¢Ma=«¬0­%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:46-07:00l %tEXtdate:modify2010-01-11T09:46:46-07:00cNÔ°2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-sg.png0000664000175100017510000000172412370216245030112 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœÒIDATXÃí–;kTA†ŸoÎ9Y“½Ä5ÙõBT$‚ 4"6j¡6‚…iýA6þ ›ØØ A !EˆÑBQ”Õ5`6›ìžëg1ÆÄ"Â9œæ¼03S¼Ï¼s…B9K6g®ä àõ½ª¶“9ÀãæIŽã€& Ù<Øo.圩ILcŒøóWâ!@$€A¾ªH}”#ï3ühS?ŠvwpN41g&ÀH&I˜=s<¡[7(ݹI¸´Œ¿øœ¤õ sö4îôây๩¸{füCׯ‘´Ú„K¯q/Ì¢}Ÿhí%<‡i6_­€ï§H­Š#i·ÑŸ[hÏ·¥ÓE;ÛÐ÷a·78©h¯îì"Õ*¸Ñú[´ÛEj¤\FÃЦYÚþA¸¼j×üâyddo~gâæxïê%¤RN=÷@¯ÿôæd“Ò½Ûh­m´¾C¾xIÒÙNý8Êæô¼’ÚÊ4¸—ç0£5¢õ ¢wïmìªÖu@PB.™þøð$OQÕJÞyúÊ_¿Ð‚±¥q×ê%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:48-07:00B,Q%tEXtdate:modify2010-01-11T09:46:48-07:003q¯í2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-fm.png0000664000175100017510000000150712370216245030102 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœEIDATXÃíÔMNƒ@Æñ?¯L ÝP¯PÎA¯äÊÄ#¸õ*¡=Þ bÂØ¼ã¢Z»Aé´JbxV,æã<30fÌÀ‰îžŠA1 ¸ð04à:d¢D0KbJÛ >”›Äg)«¢b]»¿xÀ©âZ…gOX›ƒPï”eQ`¥“ÇoÙ¨çuÛ~;æb‰öÿÜ©R£q±DL'‚ac]¯bJÀ,‰É³”|ž’˜î)‰òyJž¥‡rÀo¦³´ «¢Â©bv޳NY=WJÛ\ Öµû±`zª·–ˆ¶Ï²ýŸ9Þ<–èÐ뾊yêq ꀦa‘¥,²”éD¼‰Ã/"#‚¹ÚûÈIŸýlÀÆ:–E лp]€mÈDõðR‡o| ¸?{•3CB ïÇï=þï’¯GŽòY&ǘ(ü!˜÷uxzR4)þpnµ7¾5§tˆÀk‡H”?k"¾ '™7òÏ!v.ý?Õ)þæc—pß¶„ã: õâë1OfÚášv8…nlxËý´EÍ[fT@^éƒ$Г¹ŠÉ}’Ò¸§q Z Ó}Øð–[íMJ.æZ¶ÀGADæ€-ÞB0åÈ_ˆq-Á<¶>9@vd²KXîjI¸_K¢w-cgS‚7<¹SÌ„',:tí?>é_‰€U½å^ÚdÃ;¦UÀä –(‹–±SÆæ-ùO‚£“ó„o;¢%YS´é¾ "Œ <ÉÖkQš)e؃á!šµLÕdòÂvà`Ê¡‚®ãóÔ6Ø­Þ* ˜™™aqq‘ù…~XYæ§êZKDÃè™”‘Ó[Sà!È{PàØ !­*D ñÐ?U=†RJQ,1Æ µ¦dc¾i®óØÆ\ÉæyGgÀÃÖR@óWƒw»ÕÈsøD¨ÞÎÐü]w¤ý­0°q³¼¼Ì;w(—Ë$IB Ïo¶Íª‹)ˆaJ ª%¤›‚Ý’gšdMHk‚䙢ú]‰·}î3¿{GCDð¾¿ñÂ0¤Çà'u†ËÙ<3ãLˆÞ½D@…žÑR2Ç›ßg™K ÞtTog¶—SW1:ÐZ3==ÍÜÜ[[[Äq¼ªX,réÒ%c¨T*¯Æáš2J¤M>™ÂÕt2=AAÙá˜A?îô ©31'Èå]Æ3çò,Q@ Ç•ü|ËÛ”Ròëøu˜ÎJ¤Z,ˆñêõRª9Ü¡~‹"qíOúãZ¸–öš!@qá®]lª Ѷ#‰vã&ÑÑ,gâ.¿ÇsŒÏÙ ¼&¨ðkTù£+rŽÄ•^"!Í‚p@ñõ˜†e/–ÃxjŠÐøݽ3|û—ÍO“.]-&­·eëé‹Ñ=˜ ³¥–Çwo¥cg†íâßXŸh ÛËBS©bO0ÇçN€qgQf¥¤7³ÛYêC p±?Î@ÊàǸÃd&RŠÁ±4_eJtÒŒM¤øâlŠ —Kél ÓQs7¦Ã'@CIEÔÒI8fí垟° ˜0ØðšRšFNy›¯¥¡ Lå)` Ç] BÓ˜(I.ï" õØ*`Xh Ô’Vr\…³°ñ¯ B ”ÂÊٞኟA¢o®fôΟQ…%*žÀ`êMe^â«) »ÐX+~C°7h³J° |–kF ——œMÖ…`ÿÁÃ…‘—ŠXêΡ àÄZ©°ÀËëM ³ž6°uÇ?¶2žÿ8­žö%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:48-07:00B,Q%tEXtdate:modify2010-01-11T09:46:48-07:003q¯í2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-pf.png0000664000175100017510000000205212370216245030101 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœ(IDATXÃí–MkQ†Ÿ3™‰IÚ´i&ö+ BÛT…*®DEܸÄ•âÆ¥À_âÆ Ò•èΡƒ-M¢Á4mL3cÒ6™Ì\ЏÌM ÓEßõ=ç<÷=—s.+dI~"*€ L„ ð8l€{aa?&J -‚ê9Ì̃»C†*¯ ËDD`ñÛ½0À^^y…Í-¹,ö¬‡d.BlD¯«¦1’к5¨Ò2½¯œ.æÍsЫ ;ï‘Åû^dàŒz¸ô‹ÏhŠôºjËÁyµŠ[‡Ÿ«‚âSØÛÖJ©  YÀolЪF ˆaNÚ( º½$Îæ~s šŸõZ0ðÉ *âïx6nâ,rç2}·…õ1ü<†×„Ý*($rÈÀ¾Œ³ÕŸa§#ì–<[At«æïD‰ûYÒ*I\1ð3À0Ùˆ\çeË&Û~Mªò‰µÅ+X~—ùõë“ ¼q®rË:OÎìöšv:…˰2u‰ñØ)JÁ –lÏÆ¨'§™OœÄ¶S:¦"JcŒ)àK¹ÅówßXÿîÒõ|”R†pa.Ííg˜Ë&õúŽ«5ˆ”§Óãíjrí‚Üé1®-M1–°tFÀ€òÃGÚTDðü€n×Gñ̈ µV$ŸZz“ˆÈ_W°ŒMÏþÓ¿²ÈqþC-ÑÃx&€ä'r£a;ÐàX¡ë7ÔhÌìàf_ %tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:48-07:00B,Q%tEXtdate:modify2010-01-11T09:46:48-07:003q¯í2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-lv.png0000664000175100017510000000115612370216245030121 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœlIDATXÃíÒ± €0 DÑ †¡¢B¢a ÖC¢ R˜'ìBfŒ_à¿@ž.–¢èï¥mœQ€Ih@¡è ùx$ÉÚ¾C©æâ(ÀÝQ×q¢€´O úöÞº~0I•¬4] Š¢Ì– 9p&%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:48-07:00B,Q%tEXtdate:modify2010-01-11T09:46:48-07:003q¯í2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-cr.png0000664000175100017510000000124012370216245030076 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœžIDATXÃc`#02hרXØÚíí€üuÀ¦u@z˜É@ÚÏÀøíû¯ÿê€ÿÿÿ¨X>í=<ö30^Ö°Øøýü倆 Ó€æÂ- !ðïßÀ:€ETx@Àøaëî^ýüõg íg`©ìß3 `dÒ®Ø(ØLiÍh´¾¤FÁ(Üe&zyG%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:46-07:00l %tEXtdate:modify2010-01-11T09:46:46-07:00cNÔ°2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-bt.png0000664000175100017510000000273412370216245030110 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœÚIDATXÃí–]oTU†Ÿu¾f¦3™J["*´(”4HÁ@4cü &þ.o¼ð^õB£ÁDŠDˆÚÒJmI -3†¶óÑ™söÞË‹‚ÐL)…"õ‚÷ê$gç}Þµö:{x¦–ÜþòÕ"ƒ++гp Œ>m8€-)ÉøZ>xªps>ê03Žàɹë‚®/P|M%™p$®¬ <‰Š#Eâï†}„ºB, ® (êe0‘¹EÌxŒ™rhë^¾mpa/I4Hœ=†äqââ¸ú5¤v /µ ­í¡=v,]לíp’&N¿»Þ!U<‚Ÿîà "V—Ií^Dë+Ø«ØVü*žm¯óØVEÉBÒ»I’&Z.ìÃOD`VÚtîš&ì* Ã'1½û ¾Œx>A¾ˆîÞƒI§¡¶ "@›9ˆÝó>^?ÐÆU'±¥%¼Ø ]Š›žD®Ãj÷ǯ¬fsè­ Ü®vÀ­¢ÝG pmUÑò$ôà÷Œ °­vüwìOgvYYÂþ»Ùïö(.z×s»ÚDÏ~Ž»0 °/ìƒýCÈ©ÓkUžÇ»µ…4Aâö¦ÎÁÃÀwå¢>4ꇆAÒÇû1g¿Ãýò=nv)>…" &:Œ÷òñßÂåÑÇ  ’B½QÅ„½$=ï¢6 DGOuhû>í¹kÈÍðÉǰw8@êí÷ˆ^Ú‹¨Òžž„Õ뎿­°~›íƤp¥½ð nÿAì¥L³ÎÏ‚µˆ5Pž‡Ò<2q‰¤+K/àwuÜ»§¶À…y(ƒÌ›˜ZïfÎ|¿aÝEÌ蘛gïL·¬A5â¯>]{¿²Íú†Ó¿qçBŒ;Œ”q#?`§ÿFWP)!™,™\ŽÔoÑlÖ°•2²²Ô ¸} W­¬={›ŸuÁýpm@<fvÊWÐjÏÙ{KD²9ÄÜ_—¡QÛ¸:‘M«î àÀ.(ñ¸ÃLhÍÚiÔ¬ýæ·s05X»eÐh5SŽxÜáõ¾ÙÀX{q{÷Ïg›p€ ¹h?JÆ·¬p5éV>T2{úPN )ø©ü— ¼œÔÑ?ÓÿBÿbÏÍÅr`3%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:45-07:00#ûv‘%tEXtdate:modify2010-01-11T09:46:45-07:00R¦Î-2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-gf.png0000664000175100017510000000132412370216245030071 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœÒIDATXÃíÖ½mAÄñÿ[n qDL ¤4àpn€˜*e‰&ˆ¨‰ [;øÈŽ]§MÞH—=~šK<•cãé*{$ÁûÛ˜ÅÇ„á "©¥ÍÐñÌy¹â{½³lwÓ 6Ê„X¤tµPpÿò€íîòY²Àþ7H¯Cì%bmÕf¨‰"„¤"Àé’fù?2ÔDˆýç·±W4ýP²SyÝíZEëþQÛIŠ]Åp€àT4>»|ÕÌk5žêùº99ˆt ÚŽ%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:46-07:00l %tEXtdate:modify2010-01-11T09:46:46-07:00cNÔ°2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-cx.png0000664000175100017510000000301012370216245030101 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœIDATXÃí–½oWÅ÷͛ٯÁÞ±1–×&à¸&‚‰&J¢|)P$"ÒQDù7"þT)“åKJ¥ˆRD(b ‚‘Œã]c°½ÆagwfÞ¼—b×xY¯‘ˆ"ŠO5z_÷Üsï;oàø¿CÏJiv?Ú'û¯þ»ù=PP‚±»žãœ ƒ±ÕY¿\G´Á½d¯`ûp}Æ¡a ·¨žI«ÐùS_¹4 x|¯ÔèÚéxVô¥&Ž©Àa¬¦O¯pâÐÉÊĬÙ,“Ô*„Ów)Tj¨b³M _¶ÏHÌ£åõ²åû5Ŧ¦‘®LÕ#ðÂâ›Næ;Üà\§îÒ_þcEÇkÃOàa*¼3b¹+þh "íþнz•‡|Î9ÁüÂÕ_**5Âé •^?  û6s!±»I<208Îå<6BäÃxàžjÖ¶]ÆF ¼ÿæ8+« ÕªÁÔ#’• òͨ-kØ" >™ÌywÄrÈs,%Ò%mM+ÜŽë™ðjÙòrÉҴ–6 ¤Vz4š9¿ÝÞbù~cVx¶@k­LRDm qa¦ÎÇ3[œ,YZVXN„²†Å–¸%HÜk ‘vœ=ìÔY˜k(â¼SÙck)xJxë•# òùúÇIR¼?É,óü°î±š·ŠQßñF”smKQK¤;B/†–!íø¬ª¹¾¥¸ õ¬­–ÖžpîL„ÖÂÕëd])8ÀäcºªæœâdÉ›vÆçÇrT{Û˜ïô@|i—<Ç·5÷Z^Øö$­”p|r€B ¸~sƒÌ9D`rCõDSUôá-Ú¶üŒ"ëäàõtªÎŒå»ŸV É:­,0|8@y°´ãìN2£øâêK(q¼}zÃç·¦øò×YÖRE½R¥6½@±RC:·FØÃ%áÄ•{ÑÕ ž×®‘±}œÏA -Q©…Çz£H’é'.é…1A¥ÆÀô…‰*ÜÃYtt»—CVjI3˾p]Œ¥g\*lR˜Øí#ÝØåG¢—.¼€µŽåûÍý ýõí㬦ã#½Îª{ÏL3ËR-æÑŸÿîèF—ˆfh-o;ë] U¼°‰pâÊ\/yO ÖµŸÐç¯Ô x|‘™ßÑÀ‡Ý“m3ê\Öö´?œoÏÂ¥>˜ßµHžGäí³hƒ.× Æ<¿88Àý¾ØÆ( 5%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:46-07:00l %tEXtdate:modify2010-01-11T09:46:46-07:00cNÔ°2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-bd.png0000664000175100017510000000200212370216245030054 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœIDATXÃí•=‹Q†Ÿ3÷&C’%_ë‚‹(¢˜ÂR …UÁÆÂÂ? ø±¶ÕÊÆÎRð?ˆ,b³±ÓFÄeT–X¬‰Yv¢™¹s,6‰…:™Ù¸La^¸00÷žyî{Μsýïn^ËÀ~Þò¸7€—é„úoR«ê”SẢRqJÏ eÍ’0ðäà¬Â™ÇõNÈå®ci¨XU†žðÉž/Zž.ð¡ìe6g*€\ìEÜÛrvÇQˆAG—-ÇJ#RZÁVsÿ¸ÏÛ…lº»ÄÜýr¾ï° ±ì•ÀxÅ€¯pu;âÖç!Ka6 £ÀçúnòÁ?IGiº²±Òsd©†D€z¤\è:*N§æVC¡²ò-¢§w! )Ë?âÔ¿§pä»RvÖ†DIgßgúFèø^ꈱÀ–/†ô®%½ì„vݤ`àkAxU³šR"@(ðlÑòºjý;„xѰ¬ÕM¦f4µ¼/{<p‘Je^–U¨çÑã@ VUÕØüš<Ú%€i¼‰0ÅþÐ} ñ"sć2+̰õŸˆ0 z­œÒÑ>Á(h¡Û6knë&Ôºè×BAfúÂ#£^ á|ûÅ—à¹úfÇŠ³4¯WˆZ-Û?ð1·€·VÇ Åw:g=Ûºç%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:46-07:00l %tEXtdate:modify2010-01-11T09:46:46-07:00cNÔ°2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-pt.png0000664000175100017510000000223312370216245030120 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœ™IDATXÃí–KkQ†Ÿs™¤¹´iÚÚ´©Z¨¨TÁ îÄ•¿Ap#èÒµ{·îÝtåðˆn/"–‘Þ”Òv’´IšÌœÌMè*m')‚/Îbæ;ïs¾sûà¿ÎX‚G·¢üÍݲÏóRI/$ƒh –ÐÀ‹ˆ1Áa.q<ˆÓî˜Çy ö°‹GýÍ"6ûÃ%ˆ`*ŽÌ»ý€'áTOŠYŸ…|KJÕí‰p5¢%‚8À–ãM®æ}Fr~¨­œ¦Å¶ˆ9gÙA¹ýïÇc”°Ü)îs¿Ð,¥i®%™œPx¿ÁIcÑ02µOú­Æqu_™è `a*ãóxÑe¡š¢á¦™¼píiMª¨Ñë´vоbñ®µÐï3ˆ :Aos# `ë0*fÈ=|B©ž 5–!ÿñ Þ«%TËCŽ× ³!ªª"g¡'€Ä2“ñøUÑT* fϵXÝØeKMáÖkì4«8EŸÑÑ6¶`ºuìî±€ÛtØ)‘ÛÒh?DPRÙ³äj’ÂȾ'g D°V"©-9!90UæÔ&ÁÐ4I”Y%œ6¤ç}Z+ µ}öÇüÜKrïb…ü¨a%™!ýú%³êa{ŸÝÌW²·kˆK ô— ²!û:Š›Åg½>6Û ?ÌŽà:ŠRYaÝMrå-i9\#ø®PïÒ¨>ŽÍ@|ØÎR3Š…ñÌlìeùuC¢iŸôrµ}÷Ÿ °‚oå4›õ…¬a̘u+²ÛRŠŠB˜¿|wUõ4Uß¡PÖ¡-!µß)É|ŒN‰ @ØN㨠¨þ^‘Œ»ÒD,/:Þ±UEXŠ{Qú4bŒ%ÆEÐ@=®ÁþëŸÔ• èMγ!À%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:48-07:00B,Q%tEXtdate:modify2010-01-11T09:46:48-07:003q¯í2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-fo.png0000664000175100017510000000201312370216245030075 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœ IDATXÃí—»kQÆçÞ;³™5ñµ…ÁB‘øÀ`1`!Zh•ÆBR‰Ö"‚µÿ€`ic"(vZKšT*b$¤ÈÖÍjâ¾gî±I`!q62#QÜ·ûf¾ï~ç1gà¿UM=Oç¿rúþ[ž]¹Aõì9æ.Lqñö ÷^-Ñê&}ŸïwPL(Ίø0¤= Xg0"š‡xØÇ!ét½ØfSŠ?Ö$ôÝN¢‰Wdá€[;II‚MbŒñ^³3o„Ù h“Lr"ým2þ~"ÛŸÁHö²t Õö¯É•õ.‰êµFÌBµE`³™ènÎ|JTê1ÍN‚HÏÔQåõûU>.¯“Õ7ñf6 þ͑f°¯Ûdzù‹µÏ ÙÇ‘TÎLìà-ŠUEPÁ‹ 9¥]ï÷àøÕt‹6Rp­<ljú Õp„磓,F¥\Ràæ/O§*õ˜µr…Éo_8U/ó=ˆ˜=|ž¥£ãÛd/Â'×O¦Ü^~¨ñèÅ*ª=ó@„©ñƒÜ½t({Ž• ©€Ñ‘+²åó{ è+ Ølô•¯ºýÖáUñ9ÔÀ®wÁ@À¿!`³ÎóZD{Ãûñ‹ˆ`­$Ö‰7cDr[Ëïôa' Œ$QDcx/hAh±&¿“F@QâD1…VgÚ$±Ïe à'вþ Äí®W%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:46-07:00l %tEXtdate:modify2010-01-11T09:46:46-07:00cNÔ°2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-lb.png0000664000175100017510000000207512370216245030076 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœ;IDATXÃí–MKTQÇgî™·;jS I 4›È °E m£UDà¢oЦ¯ÐªТ>CÔ*ˆ6AB‚¡)!‚6Žè8wÞ¼/sϽ÷´0Û´hŽ)×…ÿÕYœç9¿çå<çÀ™R–hVª©Hà|ÚÏÓÍJU§ IóðS ÑG¯@F4 ÿÇÌ?š56@¬5[¾Ã°,p!?üBcŠ"’}×_À÷îÏVÞ0^(s¿r››å+2Yó ˆ’mlÔQ¯ö™ë­v ÞOžÞ˜efìºqS7aGy¼ÝúÂÇ%JVÛÊáG}꾃J”q0FøÑ­óaçÛA‹ Jb‚8äõæ<óU"Ÿ€lz ê¾ÃnÐÁÊdè'ŠM¯Ábkwõ¯4‚îÉl¸ >5Vp£>A…ø‘B IIèF.NØ3º ôEÍk²×ï±áîb[9F²6±Ž±„4=Póš¨dð2ÈA7î«€mßa¢4ʃ‰i–ÛÌí.3”µy81MÑÊR´ò´B—Vèr±pîxÊù!fÆ'™Šª”³%^¬½gÁY£ sÜ­ÜâÎØ$A²´Aˆ3 ’v{ð‚iðÅR·Æj·F”D|vÖ˜½Æ½KS”¥ýg4 8™ÿè=~b4 ½¨ŒH›\FÒV.aS´rŒd‹&®š—¯âÃÀ4 8hÀ£>GÒ¤^‡Ò­Í}êü8röŽ àeš¢Y©¥ý4Δº~âñï[Ⱦõ%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:47-07:00´dg¸%tEXtdate:modify2010-01-11T09:46:47-07:00Å9ß2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-nl.png0000664000175100017510000000121512370216245030105 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœ‹IDATXÃíÖA ƒP„áYxÀ8TBmÔ·&\H0NPPí­·6éãUÆÙ1°_&sX)'öaDVÛv( ^Ï;ÛÀ÷seªä}5èõHrc£€xÌ ºÂ¨¥À€ZQ>Âød' /Û¢¿Lhþ•ma,ø%²¤•ÜhÀ›dðüBtEš‹.š%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:48-07:00B,Q%tEXtdate:modify2010-01-11T09:46:48-07:003q¯í2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-mw.png0000664000175100017510000000166412370216245030127 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœ²IDATXÃí–ÍjA…¿[Õé™– ˆ(hÀEÔU²¢ !oG >‹àÊ¥¸7®Œd!øb…i§ÓÓÕu]ÌÄ™šÈÐ ç¬jqïå»§NAÁJÿ»t ðì2M‰)€ÏX½$@pŸc¹mnÚ„B&Cõ|nÇ|ðc~øv!`€aÓ¦ìÄ9We¤J©€¾r¾û–7Íˆã¶Æb`+ZãqÜçÏ{WsŠ’‹0R%C¸¥¤^5%G®Â- 6æaÜ£Äsä*îÙ”GqŸëfÒþÕ;^7%‡®b+ZãAÜãD_Úæßb„m›‘!¼s÷£œýtu±gÖÝ2 ›6åyý“·®b'ÊÙ¶ßZG3Çà(Úx‘(ÄPˆå¸­«²a>ù†œßN€ ›œe ËcªGfÈ“üÚLDôÄÐ0yfö¯Ò"Sç~©Ÿ›9Ü™Bnøçmöó6%ÂΜӴûKh÷•X\~¦cˆmYçx7õ%·®ù&Êh§ŠV@a€L\ŽÔåžÂ©ŽÓá/EJñäZ˜émìÏ>Ì‹¾±õ¸¤™ˆTc Ã6LEj'5LqJÏ®¼ŠM‰à‹º évúfã 3, f«B§0å6{s›¨UZXu¾‡à÷àëÕÀ QŒ¡‚%ÓHHîNòO’ïì%Y ²%óîN. Uq°ë†T O·°=û, îã”Ýl#z:ÊH‡ŠžÖE ZªÄõ¼ŽxÉžެäóîw'ñaù'hŠŽ"%×|e|ìyŸÎÑbt©>68I ±)ã ûVcËÈhG.ªÄý힨Z±K’Êu¬¯Yé(ª¢eìõ)üÑtÖ1l †Óq¨a†"ét ˆKmnêt»s›©M¬ú¥‡ñ³’`¯†Ô§‚ìù:®W`ps>-F-G½õt­™°ª1*Ü.?ØÀ±»õ¥xÙö;yÎ><£E¦ìöM³{Ò’&qUëD_Må´{ _ô7ðëp%¡¸Ä´S`Qb´ûKøºÞ±’´UiWgÎþ ìVì’¤2Û+××?Í!g®oåÏpÆÔXH| $€cƬE$î©B§0yšÝv‡{Õ9vÛruœÛƒÕy4Ê:NôÖâ ¬M3ëHÿÝ):3E“tC%ÝnÞîäÍ:ñš¾K{™¯öpyøêŽU?à±v§_a_–y»;‹6rØ·›o¯×0I[ðèÎX´ÝuxÇÖÎ{lçX*»Í.mrÃfw%‡üo?ÒnÓšˆ³.åöæ6ÎÿîVÀ–7i÷:NÜÞ…w´à‘v›8Pø%µÉ§(¿yÕ¼Ý÷÷pyh~»Í.qç³§¤<&xA%îSα»2aw¿9»MtåËØ°‚ŒO#Àž7iw^Âî¾'³Ûô¢3íÖ&ìŽ-ÒnÓ³í¶î°rcžw÷’¬ùI5‚¡ê]œìÞ…7°8»M¸ªuk§¤­`{ßãÜýÆÿjÕ3ÜoÆvËçœ4ýö­w·'BþûZ:€Gõ8ÖÆ(vÝ"Ç9À½PÖò¥ÿ¿€¿‡8²Uó½%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:45-07:00#ûv‘%tEXtdate:modify2010-01-11T09:46:45-07:00R¦Î-2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-ad.png0000664000175100017510000000217512370216245030066 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœ{IDATXÃí–ÍnÓ@…¿ùñOœ¿Æ‰@*mAH ±¨@ij±€'`ÛWèCð,XU©¥¨´4¥¡©“8ñØ­ØÔãÒ!8’7öõ̹gνwà_‡èÞse€µ‚ÕS¶^oó|óeY±¢û!ļÜÀî +ëQä áš’ .Ÿ hàA%çÝkÃj` XqIl 0x ô«"—$‚‘@•­ÀbkŠà_:™p™ø=ŽN¿ úº?&$Ï}”Z ýÅò ØR1¯“Üøœ a­ 3ØA{3”2´ãCD Uj°ä¦ÁøË ²Ï-”<£,(ßb&kLéQ¶øÑ[BÌ “5ȾOi½‡Þf“ùèáŸàO&ƒ”Ó¨I¶h”…3GZŠÜçäà1ç§ëøq@cÃÇË[xÙ?Kðò“Þetø “ùǪu>! ´7AFÓW$;‚, Ž)§Óë€Ô(=Aʹi8H™ÓŽw9®£'Çx_a­…Ä8E7g†´ãèIŽq¬Oç>`­`–ô)òÊæè"E1G«²ÈeAa"fIkÝËÀ½ „@ØEÑãÄ»ÇüV¢«,ö΂©¹øfË+öpíÜî $êÑìIu›´;Ñ€1ävŠö7š¯ˆi‰k‹t#p™LkeõpDžE$£ FGOBÓ»ýŽî`/˜4ÄÌ_ÂB–„ÑÑã7ÎðÂ!XI;>"Œf?E·5ææµfµà)ƒÕ½_Þ]°¬·Ö_>ŽoÑDí©ï/4WÚ¶î}¬2 ¼Âå¬_‰BÛhsàÂKR÷?ÜðÿHæË4šd%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:44-07:00…Œ}%%tEXtdate:modify2010-01-11T09:46:44-07:00ôÑÅ™2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-mg.png0000664000175100017510000000130212370216245030074 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœÀIDATXÃíÖ± Â0…áÿS $$Æ`%ö`6 Š!(è˜„Žš"‰)5¶tÁ_ý$’ï,CI戙EÇë;Ÿ ë@Ä €uATPoÀ!êüqT«+¥mÝÛ¨¦¼z×+дzܼLðO@v@HÒî› xx,•·(âüþŽ·ì7¦ŸPÍŒûê ®€¤!Ô¯Æ1Ù·  ; 0Å7'pÌ Øå49%Ùó‰+Ðã¶ %tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:47-07:00´dg¸%tEXtdate:modify2010-01-11T09:46:47-07:00Å9ß2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-es.png0000664000175100017510000000170612370216245030110 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœÄIDATXÃí–ÏnÓ@‡¿Y¯óÏnPÚ@U¤– ¡–S/<RŸ ÏÕ ¯Á+$Þ …ª-4&Jê8vìÝåÐJª";²„ò;®F3ßþvvva­Š%gÁ^¥èT pZ5ÀI•ªÊâk½}=*P·É?ªóŠÜέà)‡\‰$ÚkØf‰ÇøN3Š|‚º¡ÓÎZ¥Ê¡ÐË|uî~×?¾ûô¾Ô™Æ‚ï)váõK³á)°¸ âDè]x˜¹ánjDQ{ÝÝæràÓ•Ó¿zñöÁJ‹˜}Ì·ŸŒ~Â'‡twßb6.™ºÏ4ÝÐ_‘À|\#»zÊðªÁ6×6d–´HÇ›¤×]ÒAˆ5«r@ÀæVÑ|žÑ‰r¾NoÙ:O7 [Mlê•r-—·þK…ê;:ƒ˜£èœ0Î`’S{u„UBj–$É<Ë0°³iÙ9h0É^ÐN†l=»áFnñ½”€óA²‹/ôÜhâ¬NS§à‰ ñ]JMψMOY?-ì€ôŽ»Ë&Á‚è¿—‹Ÿþý©U8I!€2¦YUÿ³šWöŸÞU gÁ^Xµû­õ¿êȼž”y.$—%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:46-07:00l %tEXtdate:modify2010-01-11T09:46:46-07:00cNÔ°2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-mx.png0000664000175100017510000000214112370216245030117 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœ_IDATXÃí–¿NQ‡¿;3ˬðì€cEm(Œ‰VÆRâXàØÚ[ŸÀw°Òh£…6†ÂP(b! *–Y`w™;îµX7Ò°3"ýÕçžóÍ=çÜùÁýëc÷n©¨kÖšÙKWxpkŽŠãvM¶¬Þˆÿø R¬åÕO %hÝ€Ú™s‘žPATói½_ÌtV¥EA.€|-Њíf~ §Œž¸Š#çiõôpáüE´h•gµs˜–MÑ)QvwX’Ãlo6áì$Åq쪃ÛWƲlòlE.CT«£²Åt¼A°z) { xž7Ž!Õáµ@–Udxh ×]£Q:H½•2ýýÇ1Í’ qx™–Mµ2B¥Ü¾ê¼“`€ŽR¸£?á_°ÿwüWÈ20VŒ,Vë‡×HO)Ú½1D6Cb sí î–Ì4ÌL¦) ÛÎfÉüúÚó,¦´4³ h;cùõKz,`ÏdË=·L&Oª5¯‚35ÉQ»­ÿú;ôYJïe&Ù|>%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:48-07:00B,Q%tEXtdate:modify2010-01-11T09:46:48-07:003q¯í2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-ru.png0000664000175100017510000000116612370216245030127 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœtIDATXÃíÔÁ ƒ@ DÑ¿hŽ\R'P@zHôˆÂRÄGЧ}òŽ 9£ªT@€—=ͨ0™7à€ì;j Dzԡ .‹^Â$œêfå­nÁø÷î%ÔKØ€ w ÀÇŒ‚Ùtþ;7vo= ‡"`%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:49-07:00ä[å%tEXtdate:modify2010-01-11T09:46:49-07:00•¤Y2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-uy.png0000664000175100017510000000204212370216246030131 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœ IDATXÃí–;oAFÏÌά½^?HŒ‚Å[IA$!h%€ÿ@ÿƒQ * ¢J• ¥ @!(HDZ½^{3€ *M“¯›ê™¹÷Â~GXk( áÚÀ׿÷ÁZ‹1†,Ï„”(¥Bü7€<ω¢»¯äyF2Ž µfPZ#¥d³3bñM›xlþ±ìŸ £>kŸ^2h/bƘ<¥Ú<ÏhØ£ud–Z­ÁÒ—>·ï¾æÛöèvAqÑÙZ&î¼ ÞœG¤ë€¤;|Ï(îãy’ r­$“uŸ4³u+ KSv¶ÞwžÃø3ÕÐç0-a†Ç\ÁÃéé:÷ï\"ÍL±Œµh¿ŠÊ%‹µÏ_[ò|LuI’”jXåÌLƒ"[‡(•´.#ýƒ$q…$°^rp¥|´V,¯x¼°B/J‹½Ï“µãès$ƒ· 4ºrŠ 9GëèY´Ò¬~ïqïéG6ÚñO€L(­}šS'(5ÚS vW  !ÍÖ9*aéyLÖ}®^œ¢ÓK {ÂîÖæôºÛ¤i‚_ª ¥ Ö‘Ò Í ;ý„¼¸6€XÛþU¤‚½ÃJ ïŠâÚÍgNÇ¡—Ÿ8P·n̺¬HRãÖÀ«;n œ¼>ïÖ@{wìÖÀ£…·ßpïJæ" xèÚ€óµÜeýý¸Ï>æB¢8ί%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:49-07:00ä[å%tEXtdate:modify2010-01-11T09:46:49-07:00•¤Y2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-bj.png0000664000175100017510000000132112370216245030065 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœÏIDATXÃí–1 1EßìFÄF°Ú[x[ïá¼€Xx/ÅÞÊjÁlÆÂ,Íî°Qȇ)ù™7B²KØ,¿ß­Â¢º²ŸŸ¨Æ‚öpÀ,å 8`éi(¬V‘ß&7èrˆ¶a"“*2@økí PmC„ZÔŸGÞ—h@ñGG}˜ÊäÞH蟿C î"Í¥,šexµþ=•üd€ ÀÑmº1›Š°‹ô˜¥ëƒ(6¿Ð@å0Kõ#zû-QÏH¢9%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:45-07:00#ûv‘%tEXtdate:modify2010-01-11T09:46:45-07:00R¦Î-2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-me.png0000664000175100017510000000177512370216245030110 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœûIDATXÃí–MoA †{lÓ¦¡BêP‰@Ꟁ8ó+áΑÿ€ª@ET Z¡mª|Îî˜ÃÄÝJMä•æâ™µßym¯Xà‡½~†3¬ ¹`4å@Û ø¬¢§X>q,~¯Ê/L·ô5sç Á±äá¯õ/Lk%xÔH¶“c¯WG¿cY-æ A·¿Œ°®È=MöžÂUD6”x!TWDëÈ&!;Ì‘®¡]ÂcG»†<´´×‘ZÝT€€¬)ºo4Ÿä„‘rÙYá²Ó& •æÓ}`ÈšÖª¥Z)pM”u׸¸ZåÓÒ&ýÐäñÖ9ÝÝ>Å0âeR«*‰ê Œ!þ(‰ê öZŒMYia߈ ñs‰_”µ\VWÀÁFÊwø-²q¿ÇÙRA¦%í0dt#6¹•0ˆ©€;Ë}·'àBël°—Ñ¿Ûbý´ Å-(FªùP°¶m€Þ4™tt[)˜¦á´-aE(N ð³¹ˆØ ~å6u\¹wGžˆ œòí(Ù†þ‡`Õ‹LÏ AV5µÃM‡Q£îIȆ`ÙŽçÏ—ç3Žw ÓM}™mçó{0ñãxçö$[`~ƒgÏ;z[¢>%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:47-07:00´dg¸%tEXtdate:modify2010-01-11T09:46:47-07:00Å9ß2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-tk.png0000664000175100017510000000273512370216246030123 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœÛIDATXÃí–ÛoTUÆëœÓé\Ú¡L(URÓ6B)ÒT’JA jh,Qã%¢Ñøæ?ࣀƿÀ„'Ÿ"Ƙ@¼…¤2B/Ô{¦í´ÌíìåÙNgèEª¼û%“ÙgßÖ·¾o½l`ÿwˆe]¬èP‘¿±1BdS–c‡î1™òóãT—oì»+ ( O€„Er¦†Á‘uá –€«Ëg9À7åUU6Æh‘Èú¡ а©&CûÞ ŽHÐw-ŠkVΨ¤€*„Ã~::šˆÇŒM#ëA5B0P`ÿ³Óœ;6Â‰Ž»ôEøòr+FKtExÉzY/µ,AD0æï•PªCkK’ÞÜíºCËŽ\Wøêr+‰éàŠÁKÂájD„¹¹,W® "bÑÖÖH:%O¬)7[#éîåS·9¸k ¿Ï”©AG7㺂e­BÀ²„öö&|>‡¾¾ù¼‹mC6ë’Ï»k÷Uï™àBwœÓclgAÅóC ý°Šé™jXÃIGâñ¶maŒ–d¸ËjuhŒ—õ¹ã#\xã&{›àØ š1‚ëZkÚç¨*ããI€Š¢[)¸*ض²¯%ɇoÆèî%R—ñ¯0?P] 6”/)²j ”^0è#›-,“ߨô8Ù1ÎG½¼¸ÿO|ŽY–õ„pMž iDVU ¤*D"!z{_`×®§*ÎUˆnç“óý|ñé5޶Ý÷‚¯õ‚(„yíž$à/¬j§SþÉž$•ZUÁ¶ ûv&ùø|?g:ïPW›ó í1à8†#4mŸe`(‚¬vx6@:áêÕßKƒáPŽ×;ǸÔãðžIl[;¸§‚ð\s’³Gï04&›³—ñβ5E’ÍÑYÞ;s‹wOß"Z?_’u]P ¼õê×û·òÝÏÛ×¶@U‡rt¶ÝçROŒ—Þ'à/,½Ûÿ;ŸIñÙû7H/øø)V_1&–uQ JãÓiÞ>u›žW†iÚ>‡ (OànF)¸ßÿºÏ¿~ž_nÖcŒw78¶­læ¨ æØÛ’DDùö‡FÌz¼~LªBst–©”Ÿ™¹jfç«ãí§c¯ùƒm[mó>´|i¹MåR9öÈ䥦”Ö‰xw'Bô]â|Ðï9÷ò(¾Ì"–Ú”õ•~‚Q¨I¨Yº’M1 –æxÿ¦ØàÁ\55Îoƒõƒ»S4lY@‹GjE&‹´\â¦x‹ÄJê•qE]#ʽÉñ±º'ló6ð_Ä_¥2ÃT„t1%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:49-07:00ä[å%tEXtdate:modify2010-01-11T09:46:49-07:00•¤Y2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-ie.png0000664000175100017510000000130312370216245030067 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœÁIDATXÃí–¡ AE߇@Ђ¨ Ì)Z¡IHúÀ!Ž“œÛý—pŠùɈM~þ¼3 ¡Ð¿+qÞ 6ã°ÚrÚt,狲õõ„ÛîHõäX×)ÁÀÒð,¹ Lð ×úü 7høVÉ!eÏþÍ|²·7¯Mf@fJj£˜\ÙÕ…e5t À$ €€€1Ê!Â=rn <4«õHç˜ì%Ÿã½2Ò”’êl€P6¥ö…B|Ž3'¬ô¬à%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:47-07:00´dg¸%tEXtdate:modify2010-01-11T09:46:47-07:00Å9ß2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-va.png0000664000175100017510000000206412370216246030106 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœ2IDATXÃíÕËjÔPÇño29I&™Î¤-&N/«z+‚¢Xèµ ñ|0ŸAô|ƒê¤i;½Ø2—Nf’˜ëq!(E‹RÜÌsV?Îçp¿£È=$Wq^ýX¯8ê•“Í0L¥d"³ðÿ¤”Dþ)±Š”—wVÎÉSzGÛ ·@Q˜»ö€ùö]õ÷í ä‰Oˆ¿ùŒN?â¼ ¢£†f:Ö<š&Ê„~ýÝMtÝ ò{H™‚„prFÿè=Y2Ľþ”šÓþ™)ì ¤iJß“œ-Æ“dIN–J ÷w0½×(£Mò4(àû>Ýð‹TÚ˜fÛœE•!ZÔAÈ!a÷éd¯ø+°, ×u9<ãb6cB/ ‹"æï?¤bÌ”ò¨ºNkc —n^*À¨×ÿ-ð/3LSÀw{›ÜÊÒºhó%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:49-07:00ä[å%tEXtdate:modify2010-01-11T09:46:49-07:00•¤Y2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-tj.png0000664000175100017510000000143112370216246030112 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœIDATXÃí•ÍJ1…¿›Lý©Ð"7â ø>¾‚»Ò×|W.\¨KwÒ ÕÎLI“ë"Sww"8ÂÀpÏ™/'Aƒþ»ä¾0@\•¸+ P´Wòã¹ç´(Àù|z»u›ŸrØ;BbÓD³+ÕWû@ÁŸ‚;±¨ªítqDØ[EŸŒöK¸û àgP?äåg ;ˆæ8€FÐÜ4ç¥ Ü1h›g ªLÓâ@FÐ>Ax…øÞµò—0ºÈ3€6´ÉÖÂÂ3Ô/ GÝ»%ÈTS[Ûž· › ­!®sÐ݉ ¸‰9Jܳ5ðmýYM¯”*‘¤—ó—ôþðXàº4@Ñ ô©Uá"ç€3%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:49-07:00ä[å%tEXtdate:modify2010-01-11T09:46:49-07:00•¤Y2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-is.png0000664000175100017510000000201012370216245030101 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœIDATXÃí•¿kQÇ?³ïÝíåÂE“˱TH’6–Ú ++ƒÖÖ"¨ ÉÂÂNS©M$ÁH°›Äc4GrÙÛÛ7ñâ/v£¾ƒ-Ì´3»ï3ß™ï{ð¿‡0}?=딉Ó#Ü›=KõÁ<;Ï_PžšbçòUfç^³ü¦xX ˜Uàœò©Ù[¬ׯ¤Ó/ÛΩöB ÜÊ*0Fdt¨d«­MÓ|¿&ý'kZ.'ÆÀÂ7² ()¸&Ú•bÒ&±ŠøÞ0‡ (òMuüÿCÿòQOZ÷èeØÌ*¤¹]u?ï»¶/L7&JX0ˆü¼ô" ¥Ð ¾7áÝëÓé 'ªejCeâï¢0X ¹viœó§OCÚ+¥wÙ-A—vÙYßâFYzÆ…Júü )oëõÃÿ¢ŠFš$ˆ1HâÝzW1`í(Aà=û¶/f( û Øj±µ°ÀÞÊ ¥ñqŽÏÌ ¨óÛMM:UF‡û¹89Hñéö^)¶V#™:Ç£µ]Ö?6sÈ_Üœ{™Þ¢Lœar¬Î`W2àóvÄüÃU–W?øÛ0Š]zÖ)qâÐ_n#⎣ÝqÞËh3V!5}p®ç.æþä`NÞ·ó¸“7@®#8НŽ`¥‰!¦ék%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:47-07:00´dg¸%tEXtdate:modify2010-01-11T09:46:47-07:00Å9ß2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-tn.png0000664000175100017510000000202212370216246030113 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœIDATXÃí–?hSAÇ?ïÞ{¶>MR»-ˆ‰µ "Hº93\º("Rp„Ò¥“ºˆ¸w—b¥!©m-mŒL*Á¦æ½w×!þ_¼†”sèw¾?Ÿûþ¾÷»ƒ–U&fÀöš¸kÀ*“¦°L“›ÿp )@òË<õý,[7³%à$ú=qä»Áܲ²¶ÍÂÂHãe38ý)P”þÌ+ê÷âOÏ‚TÚKZebz£-peÏí õǓȫ8½‡pÒGpOô#W>P»6Šÿb¦Y•ö9 ‘^6¢v}‚ïÊeœt€ëâžÀËf¨½y‹¬TÑÉ„æ-8‰>œc)ê& —–ñ®Ó9tž ðš`~U]Ûa×à)ìý4CªQUÍJý \Ëc÷tã&4¦ž³>ñ€ÚÈM‚\K¬Xû`\ëô[Ø>ig@¾/5'¤’|{ò?_¤óÂ9¼áKˆ]Øñn””¨Ï•º)ÔÅ‚—9v_"ÈX›€Àÿ#„„gS„s‹ÚæÚ#x·þ=ÌBml ?­Òqæ4g‘•*þô,²TF5|Äþ.Ââ<_ïŒ.-£›ý>†ÑïÑ}mkÅ-ŒšÙ­MýKÿEh¡í¸oÀ*3þ-ÿb`GƵ öÑÈt“NE0%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:49-07:00ä[å%tEXtdate:modify2010-01-11T09:46:49-07:00•¤Y2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-pe.png0000664000175100017510000000126312370216245030103 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœ±IDATXÃíÖ= 1Åñÿäc‹eeQ;ï%‚Ç`eeãÄy+eËŒ…ZºI³¤™éS,•#÷Å*ßRe¶Y³<ì¶Õ?k‚ã‰çõ"ÙéÌˬ*¤ôy#RÒ¯PKVp.:•÷Îõ½s]7 H1ªxŸ€T Ø–]@‘¦o…äOÿ‹+nNÀ0€ `€ê€@áçqJÀ¥6`_𪠰TφÎ%­]ÅÍÒ%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:48-07:00B,Q%tEXtdate:modify2010-01-11T09:46:48-07:003q¯í2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-nf.png0000664000175100017510000000207412370216245030103 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœ:IDATXÃí”ÏNQÆ÷δ”ÒBÕЉ&¦,ܹШ[ŸÀ—0>/áݸÑÄ(M4"HD@Ê¡ÓvÚNçÒ™ëB$©Ì0IÙÐo9s¾{~ùNήº:é<9¼BûÜåñØr©Lû/­ÿ<"DÛ÷r³Æý§x63Bú¼ Â(5:˜þŸÆQ÷ ̈u>Ð6LÛµyµð†L2ÍÙì éDo¨'H¡4Úçcq–ñ…·Œ/¾ãgy=v±J /¾½f¥²ÅZu›%km#Ž`¹\dî× B˜Ô•ËËù)­Õãp[ŠOës”œ ¦¬U-žbbñÊÛí<@c·ÉÌæŪEÅuP^‹’Sczã;e§Úyå)²==ä3(ϧ/™âToNË¡âÚ°œ ¶[Ãv›Ô•”’„!)5,ŠÕÍÈðȨ©:ïW¿0»µÂVÝÆ×>;Õ¦C]5™ß^¦¡šáç/^‚ {‡ÉåiÖí2RH@`Hƒ\ªŸ\*‹åT¨©:.ð¾¢^B@s®;WF(ä‡Â`òÇgΤ%ŸÉ‘0Lr©,N+ú6DÐ@:ÑËíË×¹¥5RJ¤$ “›—®µÕv`TI#±¤)ä/âù¾ö÷Fì ˜@Û`‚®¢µjè9à^x÷àÕú›ÆQ<±GZ¬øž®º:™ú ?½å×ûE¼å%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:48-07:00B,Q%tEXtdate:modify2010-01-11T09:46:48-07:003q¯í2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-tw.png0000664000175100017510000000171612370216246030135 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœÌIDATXÃí•?OÛ@‡Ÿ‹Ü4J‰"p»Ðˆ¬lñIúuúºuêÖolØ*DX"þȱl’`.Éù®ƒ;¤Pj[Šªæ'ÝpïÙ÷{ü¾ïa¥%K|às® ‚ øÊwv¹Åä°-´› ‚6Û;¸£ñåiƒLª2s Il ¨"¶¤ú)¬ˆÔñc ' é÷Î!)¬çx_ðTðm½J»ýަë…./‡ŒÇ³ç²$È©€fÓaggÃCííWW#ÖÖ®¹¸¸'Š&y½^P«Yìímpp°Åþþ&Ýî-3úý1QTª?•ù‰e <¯Žë:t:.­VV«F§ã⺞WDzrgûÏÐÚàûı"$Ó© $q¬ðýG´.tê^0¤Lèõ†õ $ggz½!R&˜rý{ $Ýî JiÎÏCÂpÂééQ4ýíÙ2Šag·IˆîÇ'×4UF£J’dÞV`J@°w¹YŒª_#­™eAz·ñqH ˆl殪CÂ{BT~SðgR´'í’›ú¯U)¾Å `ðØ?Ê…¾-@hX_6ÀJÿ·~¬§T0È%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:49-07:00ä[å%tEXtdate:modify2010-01-11T09:46:49-07:00•¤Y2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-li.png0000664000175100017510000000145512370216245030106 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœ+IDATXÃí–MJAF_Í 3uü!šE\ˆÜdé%¼‰Çð‚ÞD^ÀUÀu¢ˆA'É$Óév!D³SbÓ çíjSß«¢ þ;BãÜ©@D®N] œ¸ð¾J#2`!è’ª Ú„ ÚªÀ”ÈïS.uåÄ §vée^GUrmçT¦‚á |ÃÑöù8§Ÿj’ÄCIÂuû˜VïÄØ<µ•Göj/>(QépHó©K«÷÷áß Ÿ÷ÉÕ%V3†Ä%ÃÝó©ªXÛ<š÷uÎ.'ȤÏ8J‘a ×iww?ó- 4.fÇÒfvPO¬…ûYÇÞûÉnãMåTÀظ¬_àÍߢ( ù§¿R1»((pÊI\^Z˜ó%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:47-07:00´dg¸%tEXtdate:modify2010-01-11T09:46:47-07:00Å9ß2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-sh.png0000664000175100017510000000271712370216245030116 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœÍIDATXÃí•ÍO\U‡ŸsïF(0—A(Š­`h€ÚRµ‘¶¢qa­5š¸¬Ô»­ ÿãFumâÎmÔ…¤ÖšØÑ6Uì”ÒÌ ff˜áÎ0÷㸠€‚Ò°gyϹïýçœó^Øe—ÿ;bêã‹x^}…Îë1.~ö3ƒ¡i„ªÐqæ¬[ضÃ'<ËW—êž.åýã:¯Î2©WsîËQ£ @l)€VT]YoîÝËHˆpx 0‘Ò³¾ )M"3CÙ í 2=‚â8Û2 …û"_WhݼõB€…³ÇùñÊSÓóH)W&9R¢¨ þb^®+䔞¥¸¦žµœÜ/7¶à£^£¾m2ȉNVÑÚÔÆ÷×FÑýbF€”•ú8u$Àk5nšëuÜûžäJB囟ÂLÅ2[Ö ù* ¹Üèæc¼˜JðF…ÎK¶’šI¡}Þ"$mOPpP£r_9Öþ®cƒQTÃÀ­ rÛ0 ‚§Û¥” TŠm¡x‘–…ÑøêjAQ^¶¹¬‰@YP¹pS#š^WEM“ À2KGE®  ­n´ƒð¸Q<2·ŽR‚àr!4 ÇÈ!UÄÒÜ`Eª*hj28v,¯@¡  Ç\R£§'@_ŸÛ^û–ö©8„^^Dë‰ZËP"&‡§É?^‰ï»KH)Ét¼‹¿²”Âá!’“ nÆnŒ óÄå8_)èóAû;#´wüA$TAvÑæ™ºM„B ¤°¥Éâ=9\EƒÛ`âr7=ý1º¢& Î)*¶íðÅ¥~&$ožÜÏóþé¿HYqîÆÈçíµòX¢ŠxÖˬ©ÍJF-–RPĺmÐÎõã»ËÕîyº†r\5˜Mçqï!ì€cC4§«wŒÞî!Z[j9Óò‡Žcåîq;"¹¿*3ý¿•PRú E8R2.£b˺ Økn¨ÓÏKËr˜u\$L¤ã‚’":9¤„R™< Bà× è>òÉ ã1ƒü?z‘¦ÂéÃ4·Ì3W{Í[ ™ ý¿Îñ÷·00¦…Ë–—±”.™^$¹’tuLJHÄÓ$âi6ºÿ–-ˆÌ–R=7Mxèwòv¦'ûÓe®ïš[b³Æ# ßàÈ5×’öºÈG<ÄÆg×t×mØœlN#ØçeOÞÀQm2wÒ˜ÙÿÞ“ÿ±þÃ{K§^nò…Gb`)ÿ}mÊ£ ð0hÀÀNx{§ì¨]vÙåo?’¦µcòþã%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:49-07:00ä[å%tEXtdate:modify2010-01-11T09:46:49-07:00•¤Y2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-sb.png0000664000175100017510000000242612370216245030105 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœIDATXÃí•ÍoE†ŸÙo{ãBMKJª‰%HzCBBB‚ɉ[Ü*!NpàoáÂQ©$š‚%!Hj>BB©qÒ:‰ã.¶“˜ýðÎS%d;ô‚ßãog÷}ŸÝwf¡«®þïŒOb'컞«G M!8aKªµ@éæ¼miAª·Æ›Ï|Çû/|F¿]F™Hiîm cÏEƒR¥í¢ûæ(2qª)r…óT½gq>IÚ’¡ë¿ùÊ>‘À‡û,žz,ÎʦKq'@ëÎèûŽÕxnp™K¾ådÂay½i‘=—ä×çË>üz×W˜¦àù¡ã¼õÒW§Š|úýAµl Ð yt±Ì,/?‘Ã2&~–ÜXéC*­)×ꬖ\Š•€z!„Jãì†ä‹¥í€Pµnž°|FúWycx–l:‡‰Ãt>Ƶ¥>¶,ܺ@0>©{-ƒ^Ë$TÓ€ôé8«%×WĤAFÔ<Å¿~&±ÏHÿƇor1#f8L­H®/Å™ÿÓx¯RÀ "\?B‚W/¤xûµA&f¶øøÆ;n@su»Ä‹IJßÿ8Ù¸¹1Ô‘f«ðC~‡õ²_B4Ê'7ýgâãMbÄáI %$™A›‚ã1g—ÅBHC*i14çö¦ËF¥±;:%>À‚ÑsIÞ;Ë9‡®ßeÇUH)¸8šâò+gøè› ®LmÕé˜ø@¥4›Ÿ™Å Ëë5êaãÄSJs×ñ˜^¨p»è† ñ~ Æ'µ% ,S ´Æ«GͧGš˜† Çôy:•glø&Ù¿i5¢½“ZaDPßW4-0q9µÊØð,Ù'†øÐ{ïâHZÝ~€#juë´±G¼ö@ˆxñüÙôOdÓ·0…ÃôJŒkKI~ýˆ÷KÌ}5úË©ø=¦ó&s6· ¿FÛ­n9€^´3Ë›w??ÉÌÚ1,Sc™üø[“ ÝļÝϞȗ%UÏx`æ]uÕÀPYÁÂ9=%ê%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:48-07:00B,Q%tEXtdate:modify2010-01-11T09:46:48-07:003q¯í2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-sj.png0000664000175100017510000000175512370216245030121 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœëIDATXÃí–¿kaÇ?Ï{×&m¬IŒÙ"Ñ:–Nvq(âhv¡89tPÁU»‰P°‹‹â¢ÿ€: Eüº‰)BZ©šjL.÷<.Q¹Kôn0Ïú}ß÷>Ï÷îûÜ ÿ{ÉöÌl´ªJ®q‚öâÎ.ßçá“×L¨²rñ$G^=åëµ,@äŸ| 0²×•‚ƒòĘÇ/誖†>°<`ÓÉ‚Ûîã6?}#_R‚ü¤ây h‹úϧ§Ð ”n¨˜çÙþKw»!ß“¤]#€Ì|4&Iª˜Eèf˜*¨&DÞÁz¤hj¸jÜïF ®¸¯^‡~$ÒÏ--Å.rÍç0Û  0?Onú0X²`úW_lŰÅÎN‡·-pŽí·ï>ãQm*3AÆgÎ <Ç€P 5Cß¹´!¾ q’á~E@`˜}C9påÆƒXhépçÞsÖÖßSÙ7ÅBcŽCµj*¯À??[ŠVÍp• ­B‰Ç/×Y{óŽâž s­Mnl&ÿ»—.Ç<ß?~ 9uúgÖe7u««toÞ‚~@’úa³­ª¢­ü9¬ ýÜ&l6!ñÈÅOc% Îa.ÙÝ óÁ`à׳¸5@'K€Q}C¦Ã7U+ã%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:49-07:00ä[å%tEXtdate:modify2010-01-11T09:46:49-07:00•¤Y2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-ps.png0000664000175100017510000000156212370216245030123 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœpIDATXÃí–=/Q†Ÿsï]³³X3–ž†d7‹D%Q)…F|D¢VøGj ñ*?A§# ‘vlHv—™«`7¢ß;…}º{š÷='÷Í9Сÿg¦«‡.‘ÔôÍMÜ(6¬MÍ€løûõˆ§ä3 ,xùb‚e»Qµ±{1¬z»µˆŠcÊyÑ,{+Ù€¼h·°@(º5‰©Û÷Œ¶.²!çáH+D6áº4ëåùÄ„´9!æ÷Ã(¦^õ`MtavSÛj@ý-Xàã¥ÂãæÏ[û$µº[®1 bÁ„ëkÖQYϱùŠ«é¡X&ûsw· ßß³=´R ªž°3–ãx¢Ï¾ug¬8ئ)^É*öÊ>Ûã9ª™X¨:Y‘¦Ùù^Ùg·œ£ê©ï(8ZÑæ9§8(ýtÞwˆ9*ú—‡¥tÄÌéhvé©GC’ÎQb†+ñå}¯¦¡Ò;Ë:tøß|G¥tç¾ks%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:48-07:00B,Q%tEXtdate:modify2010-01-11T09:46:48-07:003q¯í2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-cy.png0000664000175100017510000000204112370216245030105 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœIDATXÃí–MkQ†Ÿ;™ÌäcZ:$5ÚÒÆº¨ø±©;ÁŸàFÜŠ¿Ä? ‚ÿ…;ÖRª ‘&–D›¦m’&e2™¹s\Å3¥uæ]Þ{yÏsîÇ9&úߥD$Uȧ½ÓˆÒ0•&€qfΡzôï$ðЭ׈ßûëzódQ"@@€$8&êí6Þ@èc.ÝBåܳÐíOµu”U@ÙSˆ×%ln Ã.Ùêm¬KwPÅs±¼âH„îÔa—ðÛK¼W@`ZúHèa¯=Àº|•›‰m @¼C‚ú:þæ3¢ö¢}dx"0”Be¢Nh°KæÔF}ü÷O ¶_@¤Çƒ<ÞŒ{ûúC ç<Ê´c  ŠÌÅ„ÍwãÌT&²§1J+ØWîa]»² ‰‚øÆêFQÿ;á—çèÖ&zÐÂp—1o’)]Ę©&Î<9°ÔÁóú”MM!?…*”Ï{Áˆ½£yË¢ìLc¨x6Á+ê‡|lÔYž­°:7ì߇ö ÇÖ&Ûû-®Î/Qv¦cÛÆ0”bÁ-Ñì°sÐf¯×emi€·õ¯ŒÂ€²3Å‚[Š}¢# s<àónƒÎñ€êl€ív ·è°:7[tu·D¿hÍ0a›Yü0 —µÈf2I­Npš2ïlªOÒP"’ú§4ÍøMÄOè†ç•=¢kÃ%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:46-07:00l %tEXtdate:modify2010-01-11T09:46:46-07:00cNÔ°2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-ag.png0000664000175100017510000000304412370216245030065 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœ"IDATXÃí–OoeƳ»Þul'¶cABÚ¤P µ( ÚŠr‰„ •Ê…&…påˆÄ'àp@ª¸å„ÚŠFB"¢ŠK”@*@‰Ô‡´”¶¡uì¤uŒw×»ÃÁNšP;vr :Òjí}çÏóÎóÎ;Oä1‹~öE Kð„XeÓH‹ Æ<Ê"X}+÷?ŸõK{p¢Z}‹ìÞÖŽEbX§5úþMlà¶d¸LœHõOÙ×mß[‘çL‡ÓVã¤gÄI’³5äôt™D¡¯Ç ¯Ç ê=]&f‹<&ÅdÄIrÒŠc9"œ²Û¹x|í­á6Ø‚iB"&”]eð°EÉUº2Õˆ=Ý!1G¸›ˆÇ„bI pºï”ÝŽ#‚¥@‡˜Œ8)þ}füuêBPx±ß"“2èHg‡ŒZÞCU¾›òxó5‡•ÕõëÓ¼bÅqRtˆ‰VÍ7‡L›¢iî„>K·uDHÄ…ÜjÈ»ÃQž?hòÒ ‰X@±¤t& ~»pîb‰T‡Aq]qýí[é­Å8dÚ››4?jË|º®Ë°„ùJ™ò–<´E…×m†ŽÙôõ ·éL8ÁŽñ˜ðtÆàö½€LÊ$b 7ÿ ð¶$"%&F;yÃN`ò°l6òc×Ò+@ÙUæ²>arâˆE{¢5+Å¥½ N±ƒ¹¬OÙÕÍ0öÞ#È6Š­ÑLJLF£Ü|ª—Ùô3 B*²o¿ÁrÆäÛåéRýÂ/ÜW–3>ûNü}+dµh€*Ç w}pŸT÷mçâ§ôÀ#gN€ºøìÕ÷XLïÇ2BœU k]¤ú„!¸>TBƒþÂ->¹r‘Ë u·E¼·Ä™ì4_¼ükV¯¢5hÍnššŽ!$ýuÎd§¼·ÔP»îÕ¡€x /Î0¼8ƒ]ñ¶¬4“ªŽ]yhï^CK«±!é½z™;©n~>x´¥ð9¼1ÏèÕË$Ý"ºC³°vr¤"ô­Þæãß'É¿}{ ¿ùe/‚·°Hç÷“ô®ÞÞ1xS¢JÿõyŽÿ2I÷[˜éõƒ|åK“ä®Ïª6m•ÍÛ‡¡ë‘Ÿ iu½†ªêzä/MŸ t½–útkýK„ÊJÜØyŠÓWêÓ Jqú ¹±óTV - ­B"”–¸{nŒòµì#ËåkÙêÚÂÒ®&”]Nbʃ©Yrc¨Ö6¿V käÆ.ð`j–ÖJu¯DP×%?>Aa¼zÔõ(ŒWyW×Ýõ|Ö´ êj;vú»@PXÛÓph‰c¹k Þ?Éõ Pým8º‡áT接wo˜ñÁz 1[›)É€AaO–ª±¶*€â:ìe°"ÿù £ÓZêæ%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:44-07:00…Œ}%%tEXtdate:modify2010-01-11T09:46:44-07:00ôÑÅ™2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-mr.png0000664000175100017510000000211712370216245030114 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœMIDATXÃ핽OqÇ?¿»ËQ¯ô zB‚@ ÆA¥Žî&nƸ1H\\ü#\]š¸c]d%AˆlÚ…TŒ)åZ°w½ë½8´TéÐë‹ñÓÜp¿Ëó<Ÿû>¿çyàÂ"6Áêr¤ ŠàEÔ£QHÃ8«R€*ÿ@´ž¥1‹¥1«ý>ˆ)ƒ8é1—;z‡ÓoŠ>–âÖûê!‹E p<‰3±]_p#cqª @¡cãÇè9…TÙÇõ^Ð]›Ð¤T¹„,~×Ú°evÊ›¥8›¥8;e ÖÏAÏ%lRª7¤Œ*>7Ç-¾ÕTNÍ$BÀ^MåùÖd[!h+¤µ|NdŽët½ ¡%p|‰…´Åîɇqà_*1üVF©uv½®³¶ø°Ÿ U { TlÛ—X™/3¡5Ú¿é·¾Ó‘|Bk°2_Æö%*¶Ú¡w î Ö÷ät“µÅfN3æŸí4óÌ$ÖÈé&ëû ê~xsöÔ7ÛGïŠiž^/1›tx½›aëHÃpšîÕ%—5y4kp{Üäågí#­—н˜žD¾E•ž\+q÷Ê){?GÚ}9æ25jcºù‚N¾Åôz›q‚ÕåžgiJõ¸7yƒiƒ[ã&éV›U™Oe·Å ï¿'©:r¯!ûh:@fÄåjÜA¿äP²¾ÖT [¡ßÍÐ÷ì €c[á¸sì¸ ÚÃ$ì´¡Öñ @ß÷毼ŠàYÔÕ(.,rû»Å¾¸n¦x%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:48-07:00B,Q%tEXtdate:modify2010-01-11T09:46:48-07:003q¯í2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-bo.png0000664000175100017510000000147012370216245030077 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœ6IDATXÃ핽JA…¿›Ìn~%$Jl‚­Øøú¾…¥UÁÖÆ§ð9D´Q0&(Š1D#1ÙݰÙk¡±ŸE¸{ªiæÌ7gs¡±¤× Lа8³^'PK€’åáÀ¿p`ZB×8®¥ù¶*"?+\.=¶2ïMÀÛ´ÌëX˜Ï”ö¦²½åmóêEާ¾ãâ²É4QŽ?h¬%Ts„é]BUat—1¸Yììîîó|Uat›¡êÿ Þ"Je“&e¢z•H‡KÂa„ˆŸ?-aýþæ Ï2]²NÛ%DV…ôð›=ø—p1Æ/JœŠP«d4ÛÖ½ÀÞø¬’ø½n,è$ ˆëØ~DiŽæþ¥ÌgAàÀxçÖ'ÖŸ–…ÌõþAa*ཎu%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:45-07:00#ûv‘%tEXtdate:modify2010-01-11T09:46:45-07:00R¦Î-2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-pw.png0000664000175100017510000000166112370216245030127 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœ¯IDATXÃí–¿NÂP‡¿Û6ðBcb"80é¢ lÔÝÝ„GÐ'ÒG 1¾ƒl” \\ ˜¸ ÓÛëÐø/&•°ü¶öÞœóÝsz~½°Õ¦Kœß=¤ `'iܦ zI#¾= ôÿh L Í19Ó`¦$¾* ´… \/Àa扚ݢ"]öwžxy= ç;t¼:ÃEy}ǹ>â5Õ¼KÖ˜òÞ…£lŸjÞ¥"]š£+g§‰Œ¸EA)3 Q¼Á±ï£äÑï­ÏSûžFñ†Rf€Ž™ À5»E5ßŽí± ¤šoS³[˜"X €F Í1é~ž0¢=:¸·$Å)xXÍðs*Jƒ–4L“Ý2Ùß"™Ö¾a7Ø;ä&+-qOªJà!˜Ì¨²JñÑ4ºâäék·ROœëw”‘1Û•MCD4རOT+:­åBÖÜ‹džýlÐ}¨ç—_ÏàK‚^J¾ª§Š °YMÓi%hSââûÑY.|ápuÔÃvä‚ç|Ÿj Å(õCHž ¸t[q¶Ä08lóÉ%—»dðýåß+øÌÏ´YMÓn%èPf¿es¶ßadÌ#±hêù¨ l )…ø@@Hž $9iMSKðõÍ"×Kb• š÷èœh7 Ø”uÝ®ÎýÁæí‡+7–ºž"`Ûc*'hkÙH$ظv€\×Ç­8õ±8ƒÃ³ÿéÚ*Ü¥sæ˜Å†[ùÔéâËèó«XÉõ·c+L­ÀÖ:•×:MZ_ñKå~Þ<ʨ݀'Õâºi·Îé—Ë 7l§Çé o¼‰h*ôïÊ«(Äu{K˜ÛûxgòEnÚ;HJ=g?W8†År}Ñéb`ü ‘T8[¼z @Á®»LZ›»Ö—/ P×;·Ó3»ØužÅõÄò®ó,q=•uýUq]ç¨ÓR.·Kî:_ÄÕ±ÇehÊæòÿpÝ?ÛA_,×õÚ£M_›âÃË.WFKë:ïÔ„ùç„O&늬ë7²®{.b¹® ‹È·J®ë–æ·+÷óQ®×`• í1xý%‹ ÛøÜ9" u/š¢0íûTC®k“ãmf,°!|óì_'¢ý±CØ~9s¿›E0tq1éÉS–)‚v¼y¬Ìß÷´~'X!.ÜuË.}<Ñ9)¥&PÜ¢—hºÆ[êÔÚîVóè+‡Íx}­:$TΧS܈¥+½ãïtI®ÀÜ7  «>°·Q«ªB|'¡7é5´ì²ñ~ÉÊç²ÆàN:œöä„"p¥,}ñ€ôOsH™=ëUðâ#(;$þ—%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:49-07:00ä[å%tEXtdate:modify2010-01-11T09:46:49-07:00•¤Y2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-kz.png0000664000175100017510000000214712370216245030125 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœeIDATXÃí•ÏKTQ€¿sï}ãhc“óCR ³P¢©(èh×¢¿²E›6-ZH!TH2ˆ 65ˆãŒ3êŒïÝ-L Z̉iÑ|»ïœûÝóÎ;† ùßž¯¡hñDXº!ƒG&`€%ƃ7ð àÙ¨t—cŽBö_ÈRY5Y6›¬ÆËx& F‰)É2Àƒ«$hš!‡;õI…9é0©d$¡ésÔ}žø4eh<Ÿ:°¨ZÜ*Ü3ŸÉË›n†·É-6ì\_@ÈJŒŸêók< z‡Ç™w<yMNŽùbg æ |÷%Òö‘°hš>Gz›G8.I—«ªÁ²ÙdJÕ—‹f›ySeBµÉÊ *¥€1XʪAIô RV¢¯U‹CÝç±h Žv£és¥Åbf›7Émj¾Ð³¦ ymàCïsú‹z›Wñ /㻂j±nçù`opMïò(ó‰u{…4=H‚¡ÆzþÍûä&M‚á£] êËd%fßçØy¦Õ«ñT·0YN˜P‡˜àȈíØrÓ!`Äa¼Ã¡‰ƒ!ư믰åfh‡±tC'dè„\轄,Š-7E„cLºÌD{XžkÑy=jÚÚÍ ¯‘¥;ãËòÖèÀñÛNß¡Ä(»ƒ|´¯…½|u-N0 B@Pç÷p ÓÏK-‚z‚x;Z9ŸÓùò§YæRÅGÚ/E±Q\ÛU‘ÿ P‹´E¸çÓY:ÏçR¼ÑÔÀáwHÏgÑ'@p䩌›M›#˜›¸8œfèî5•>UP~胊¸R û ÔÕ%—ü$ÍiË rY„X±WüúÊ1)©ZìQ@uË´mÌ¡QŒîmE¯Û•”Ë6É„¥óÁL„‰²Ž®9ôw-`‹w±y²3C­ô3«!Q”„"I²K:Kù¤«VXÉY"4 Å£AÙ×]K×@ÓpÍ2RU«–KVåîÓm¶´&‰;ü)°ÏÃöŽ–½„7æ`WŽmÝ“œ¿UOÉ4°Kµ $Ú‰Æg  öílåPo#6ÍôT3ÜHèÜY@’¼tÕô´,àu ÂF=š/Ç™ËQRÝ-eêÊ!|§¿ßÜ®ø:fs#a“7m‚¡Zî–t¦ãy¾½çêíöõ·ñêž6ž¢9ŒÍ;Äm]6p’[yºwˆ¾‹ÌPRä.Dpœl6ÃÙŸÃLNnÆ,kÒÛw—Ç%áê,–kt"¶ @R3È+Ü/‡@À 9Tƒ½¸Äl¶DÙ¨ŠÃáý#ìí›ãbú Ór//·^b8ßÃP*Ê–Â9*…4”ëíz BÍËå{l/Kª>rÅ ¹ûgÔª,¯Uóùù¼YݼüNãIÈŽ Æl?í[2ô´zPyƳMDk ºòLÏù}¨ÖT`bõ p+ßÄžÝ)ÔBžæšQŠ…9tÛ¡] N),.Üë d­D =6ù¿ˆ*.ù1sa¢ÄpŠÃÌg“dË µe³K!“Md<Üòʺ YƒK7ÛÈ' )/BQ¨X ‚N?X™v\{õnýX¶!³èö b#½hÒK*ÄÌD …ÊT,/¬š]˵‘=ŠhªKÅQÐt ×Q(èªKÉÒø+™ ­§W ,»Z4Ë÷`bÛytÚðÚz Xÿ6wÝØÀ6ð¸ø}Ü JTòz%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:48-07:00B,Q%tEXtdate:modify2010-01-11T09:46:48-07:003q¯í2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-ms.png0000664000175100017510000000274012370216245030117 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœÞIDATXÃí”ËO\e‡Ÿïœ37fÊp) ,¡±¡4Ðblc«‰é® ¯‰I£@»p×®îktÙ1ÆÄ¨µ—ØPê­jm)7¡P`¹Î€3ÌÌ™™s¾Ï…„K‡¦ 6]ȳþÎû>ù½ï{`‡þïˆé³gÐ^x™®ÎrîÃkDÂ1„®óú‹õœJ\àƒ¢cœÿf %Uå^Þx¶€7+ˆ•7pò“C£Q@lIÀ(©«n^ UÑ;ÒO$<(”Òó*(›©X–Áå’&Ñ2ch²p[ ½?ýþi%^ë,G.·qµ{„X,j}wBà÷ÐYçàDu’`Ó3ÜqT‘ºÖ¿=3×eóó‘^žk ðî‘Ýtí=È=aŠKtHþkQ‘‹®§‹x©NÑÕRŠ»®–¯æ|~y‚é¹å-Ç`kBŒ» i‡âs¼RäXg'±éŒsxµ£÷“jB˜5|{kžÁÁI r)Üdòö€vù¢âV×a¥„À©!-4eåHÝîÀÓÔ„Ðu„ËEÎVdÌš€±”“S!ÆRNVJàõ{púÝ(M äŠˆhJaFÓ¤–Ì ¬ +…p:Ðt*“AÙöš¥Ó0Èt¥ ‰•­Üˆ&%íÕd4M,ášÇ0 ÌÊ:n/ž/‡0{&ë>5Þ/ ªÍ¢¤bi1ÉÅKüpcœPY!VÜ&fÞWPZf“ø­yÊ—z¹“$SüEÎtiç xûA7óTÞYišÆ¾Nöï Sœ›b"¾ÈwU& V™¾ÿ5Dßí jÝ,ŒÙu£û}H©HFÒ<ág·=€Ó£ÑghÞ#° HÌòö@‡}g·.‘OÂÔɸËútüºE~D®™+£õ MiH¹Ñ`#x0†C§f— q—‰Tón"s¶-7Ëñ¿X-®i€Zû#n&û¨š()úÆ¥Ä?8ñ¸k;ì°Ã_ID˜ovt%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:48-07:00B,Q%tEXtdate:modify2010-01-11T09:46:48-07:003q¯í2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-it.png0000664000175100017510000000127112370216245030112 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœ·IDATXÃc` &¹¡ì?C²–C¿]&/+'^•¿|axÒÖËðvã6FFF‚&³000ðéØÿpGSGÜ}C ê9(› ÉljÿAå™Ñ„Ó‰D†À_¨åÄ„À?$ ¢‚Š´(øO¬¹LDZN30ê€QŒ:`Ô£uÀ¨FÀÂ@ Í†`-bÔ3k. Ã|"-¦Y£´ˆÈ Y³ü#‘Ãê[%sìëX%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:47-07:00´dg¸%tEXtdate:modify2010-01-11T09:46:47-07:00Å9ß2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-in.png0000664000175100017510000000154412370216245030107 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœbIDATXÃí•»JQ†¿ »Z¬kDI`5¦Ñ¶ú&¾¯àc¤ÐÚÊÂ>y +›€ )²lsW¢YαXmìF„#˜NsàŸùæK9–ØË#§Pv pîàÔ5€¸(¹L¾ð(yVí@k «ˆ€µ „Ø»ë7­i‘z½ ýþ€ííz}ßÓT¬5F•|a¸½ÍˆïŸ ÖVx™½Ó8Øâø8Â÷u%Ѽ$™H¤R d8šËp4—J58H’LT±@D…k-dÙ” ðIÓ)íV‡v«CšY6Å*ûàLB"E!Ý“C h§§W¢(D”{Õ3Ö¨ŠV«…ìíoÇÊ«<<Îh46©ÕBŒUõ4rqÓTaž’Þ˜~6+*­±[/ãýd «Í@‡üeü¶ˆ¬¶û>åå&_^Ãÿ àñ£ö»W®Î\Œ],å\Ò9y¥o™Mê%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:47-07:00´dg¸%tEXtdate:modify2010-01-11T09:46:47-07:00Å9ß2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-er.png0000664000175100017510000000263612370216245030112 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœœIDATXÃí–íO\UÆsîÝ{wní–îÊÂÕ"&‚¶šc¢ŸüLüGõƒ~µ‰Æë[#BKk‘ņY–Ý{füp·ËòVŠø­<ÉMÎ=gÎÌ3ÏÌ99p‰K¼ê¯gîðÍmÏwï¥<©[EÃ8Ñlìÿ±SæO°9º>Ów~˜N¹?©l gµ…Èwíð9ñœ4Áçë¿Ïþþ`LùeÊ3?¡<QÖKÆnÞPÉ {Î ãhÒ?4hÅF31êãñ¨2?¡,Ö”•в9h´"Pw@äÿ Ó#pÔ© ´"ØLŒz%#²0¡<ª)õ²Ñ¼bìÅ™BrAezúá®Á¨‡TuÆöÓ€fêåÑhFhqL©—•Íä¿+t˜@áÍ”Ü-O0ìÑ8®+s¤÷CtCP×§P9#²0‘;¯B ‚1¥ðY ÿW@º›IÑ ‡6…胾áh}c»™gé6¨ ìÅYàzÙÎ¥PØÏ&|Ã#y£}/$œôoz$1ÚßǸ!%þ¸CûÛ¿›õ²ÉÁ +¶„=¡¶ ³sÁ RšWŒV †õÀ•ÝtèºÃjše·ê°]Á? °Ù÷šâë&Ù÷ù6T×…‘õ€;ó­Èh&Ù©zXƒßÞ ™»‘ï0À¢á† I²±í hFN † Šçiyë*$8Ë¥ ƒ{®o0²6γÂp—€€©àŽp&%¼é ªŠ ))nH §=x° wb(1CºáTí\ÄvqµR…åJ¥ê8+åQÖJe¶Š í(ƾ¤Ðù)$÷vJüi›ý¯â¬À9ˆ?êÝê°÷ELºô®3±nÿŠÐŠólÖ®UX)°4<Áre”µk¶ ƒ´s*°îɰl|è ÃJn¶ƒ4‚š¢ë‚í~Å‘Þ ±g îŒ ös1&rˆèÙ÷@· ¨z¢wSü²£³ÒÒ<[ k¥n†Õ—Éðlô]ÅÇk¸S¤qJ ÷£—Ëð,„½Fy¶¥2+åQ–†Ç©Wj4JevŠ'gx‘À=ëW‡æ–_çÁØ$KÕü]®ÒL®ÒŠò˜H¦J7N þÂøyêöçwßÿ„…ñ)v ˆ*‘蠟Ú+ §$+Gìø¼ô/zÀáØj}núÏ?ðAÀÓ¡*»ù"ê\ÏÊèÞ·§¼µ é9ëfvxCÏæÔ7Û%.ñªâ_ÇÃéºdG%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:46-07:00l %tEXtdate:modify2010-01-11T09:46:46-07:00cNÔ°2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-hk.png0000664000175100017510000000220412370216245030075 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœ‚IDATXÃí–;LQ†¿;w–ëÎâºDLð‰D jˆ …ñQB¥–¶–+[{Z-l°°ð‘C @1’Õðy‹û`–Ý™¹›ˆ62»§á/o2óç?gîØUÀ“MV : àAÐ7‚Ђ4ß>€RàyÁÈX£µY+Àü7FS {ïÞ'Ú{ͪ.@÷oºi í‰¾v£ýÞU´på:%AÐü×å@“Ȉ…·žFemôºzŒ“íx«Ë(×-´¢ùÂ0qæ¿á./ò7>šaPÕ}ͪÆý>‹›\+œWT‘}ÿ†Š®K”9’ü×iRý±GÁuw&¥&—Cè:Êõ0ZN#c5d^êÃÀ[[õ=ˆòÖ>óÞÖ!T.K.1J~"Ðu„Ô);t -A?؈ÙÚ²3d‡Pùœ¯êý'ð»62^‹ÙÞ‰Þƒ0Lì‘!d$Š»¼ˆÑ܆ŒïÇK'þ?Xz}•»‘5µ8³_°_â,Ì¡YQ…ü×StBC¯©EmØ8Óãä§ÆI?ëgãÃ[œù9¬ÞÛ8s³¸K ¾«‡Â‘ï;Tè!´ˆ…0L¼äÏBÔJ”˜mgñRIrŸÇŠJ (`sû ñ÷ iZI›±ˆ!üÃè_`ž®¤§vP:PÚÝA€¾ Äd“Uté v¸~‘ã®\£ŸB%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:46-07:00l %tEXtdate:modify2010-01-11T09:46:46-07:00cNÔ°2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-st.png0000664000175100017510000000173512370216245030131 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœÛIDATXÃí–½nAFÏìNXGËÄÖË ¢H‰$ˆl (!ð4<¼/A²E4(PAtéÒB… †ÄÎذ㊃AØ‘v ö«æÞbîÑwïü@¡Bÿ»ÄÕ;³¼ší“¸ roêf&>²ŸòÂKù`¹¡ùP±›À•grÆ8ðp>!òÉB=¸¾*h75]•­Ò P»°ø4…hÍ'D¾›ÍHJHkU"XZ•ÔÜ„íË;¸ s²l~^ðBíÂÅ'”•%Xúˆ«þ !Ä{éºä³mr `{’O­£xÂR]Øê„1}µõ4>{T gt÷V©~÷W³ç¿žÄñ,“§>#ÜA‚ø+Ï÷îûÜ ÿ{ÉöÌl´ªJ®q‚öâÎ.ßçá“×L¨²rñ$G^=åëµ,@äŸ| 0²×•‚ƒòĘÇ/誖†>°<`ÓÉ‚Ûîã6?}#_R‚ü¤ây h‹úϧ§Ð ”n¨˜çÙþKw»!ß“¤]#€Ì|4&Iª˜Eèf˜*¨&DÞÁz¤hj¸jÜïF ®¸¯^‡~$ÒÏ--Å.rÍç0Û  0?Onú0X²`úW_lŰÅÎN‡·-pŽí·ï>ãQm*3AÆgÎ <Ç€P 5Cß¹´!¾ q’á~E@`˜}C9påÆƒXhépçÞsÖÖßSÙ7ÅBcŽCµj*¯À??[ŠVÍp• ­B‰Ç/×Y{óŽâž s­Mnl&ÿ»—.Ç<ß?~ 9uúgÖe7u««toÞ‚~@’úa³­ª¢­ü9¬ ýÜ&l6!ñÈÅOc% Îa.ÙÝ óÁ`à׳¸5@'K€Q}C¦Ã7U+ã%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:48-07:00B,Q%tEXtdate:modify2010-01-11T09:46:48-07:003q¯í2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-gw.png0000664000175100017510000000151512370216245030114 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœKIDATXÃí–±JA†¿ÙÝÜ%Ä„Dìì,Dħ°RÄFð9|(Kñ¬­Ä*Ø¥³°Š¨¹˜lv,.9ï`„Ü_ÜóÍ¿s;µjmºä¡¿ÿ·KaûlÊîU†44€Kz—e%f¸)éõ FÀÄ(›Àœ¼xÔªtˆzúÕV¢ÿ`€LÏa†ù°‘[>x” ü„GŸqštÙ1–¶ØDƒF̱èt¦ÊýlÌíç+Ãù”—à¹H{9 ÀÈ;Þ³ÿ"B–\ŠæiôcÏ&EÇwo®‡=&©ÄX¦"7¶8itHÄ`¿½Í-O“&Yˆ;€}qœ']R1Œ5Ð)†QYQ©B^´-ëùBT‰~ÕUX·ªD_DÏÀ ¤×/ ¢¯ãËRN]ÝI¹Ö±jÕÚH}ýžU[¥Î@¦%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:46-07:00l %tEXtdate:modify2010-01-11T09:46:46-07:00cNÔ°2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-vi.png0000664000175100017510000000355012370216246030117 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœfIDATXÃí–Ý]UÆkíµ¿Îמ9uf3S¡Ði‡ -BGZI•iLLQbüŠW˜ÆÄ M$Fo/ˆú/Œ(1@0C Œ%£…ò5 t mgÚ™N™ÃÌœÓsfŸ}öÚkyÑ2mA$ÈÅñ‚çj¯dí÷ýe½k?ûÕg km_õû~ÕoÓOˆRÀ~ÄêêE/>NΡÜ*Ò«à¨"BüçòÖfÄ­“d³x…Oánzß½Æd˜´E–®`ô^þF7-@Ü|…ÞâOQnî@„S¸…ÛpÃú%©6›´×çhÌ!ÔOc¶Ü‡3þÊ‹®4“bÒ&Iç4Yg¿ˆ‰çвNéú_¾ÀËÑ•Uz­§§Ñæwà‘&ÁVÕñ£ýx…íé㻆’Û KfHâ%”a²„nótûD¶ˆîœ Ó<‰b ac¬(¢ªûPÞÀ{G·cÆFç\ ÛzI‹tcÇÅKqwaG¡K)¼€— 6tƒ¤õAáFâõãè¥"{¯ú ­v†ípÁˆ2ní0¥ë@y¥+½,£›eŽƒ*ÝŠ~ÌJdçID¶ÆF ¡¯Éù]N.-òìÑ¿ygPkœZÞE)Ôl~†5QÁM_âÞoSÍÇèÌ' înùÛ#‡±^uóò*€ùV›‡—ßæ Õ´1<½ñ•êOäìúcèîx„\!â_ÆùÅofiu4p7Í8ÀWšœo‰“çØ{s}Û¶SÉÏÓlõЦ„?ƒ_û…¡ü¹ÑEÛeÕ‡ð•s  øœL3¢‹1™5œN ~Pã¯Êx½/²§²‹ÕöŸ€UÊjšÑT²€(X ˜À0Q™'/žg­™Òè^Ïrî~N„ùlq‚¡`Wº tŒáËØ+#¨ú·ó¼Üj“bÙYXz™ÇŽ?‚#òw|ÛË%Z­?P+¤üà6‡ÐV¬Ö¥@Òn9®ISM"obÆÿ&OlìÃÊ»µ&î%()‘Äe÷PŽ”ì‰ò<º²†#SEòξ0·6Ë3oc×=‡©Äž?FÉ;OÍup”Âö$ÂsBÒaNX"W?Â[Î$<_`.I¨Ðæë™ˆ ð.¯ï<ÜúÔŸ‘Àgkè3Rerø”ã2Û8ÎëËgÉU?O±¶›`ë›$ncÀÆBª5ºr†üÐ¥¡/á–§è%–HXÆò9öÔÊ}ŸÌŒ1Ø«GPpî-xB“×-0µm/3óÏq6>Åã/=BhW¹Áþ–âÐ ZzÛ¨â›K¦ÓV ÎX ×y’æÂVÞ¾C#Õæþ±aF‹2c™ôzJ .Ça/c-]!€@9!XlœåçOáïçžb4èòÕñ€©z‰pp?‰žd騳xaš¨mã·Þ‰^Ý;ËóÝ;iòõ[î¢ø—ÝÑ’dÖ^é±yRrî5¾Äp¹Î÷|Ÿý‹Ÿ#ì%‰Oa¯ûA®BgîG¨Ò mal—@ZZë.§£™>w”ÁÎ?9ôI½Ù@A ®íqíê]’R²sìfvŽNÇ8~æE¦ÎðéŸ@䈊)#[VÐt{yš=‡‡ß²ü>ÙÃ]ÅÝÜ7¸óÃý ßWBæÊܱ}?…ð5ŠùA¢âiÎ[|3cs¨Ú7¨Ô¿ËÐBJÐYg<ÚÂ@îƒÃÖæø°²&c£õ:ÝÕ¿ T…|í ʯñêJƒé•U&"î®Gü÷´ð?¼#c4BH„Øü¢É² „À‘òßÿ¿ˆd¿î'€°Öö=–÷³ÿÇê¿þ r?$²N²¥%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:49-07:00ä[å%tEXtdate:modify2010-01-11T09:46:49-07:00•¤Y2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-pl.png0000664000175100017510000000114212370216245030106 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœ`IDATXÃíÔ± €0 DÑŸÈÓ0{P17Q!ÆHÆøw øél’¿§Í9U@‹ÝÀaÔtsxPã~T@{×]}D5.·¢7 aè€N°Ùµ$ù˸W_¬É%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:48-07:00B,Q%tEXtdate:modify2010-01-11T09:46:48-07:003q¯í2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-rw.png0000664000175100017510000000164712370216245030135 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœ¥IDATXÃíÖÏNSAÇñï™;m±…¶hAºÑàßÄèÞµ¯à+°ö |7>/ÁŠh+”ÄEm A ´… z½sç°hŠ!!’a6üVw5ç3gνwà:‘#¼ý`É«ØçiôÀ»ðÅ ( aF€×!KW$§™¤L˜úE}_%W{Z|¾²É‹ê÷Ê=œZ>g³¬=¤—߯i`P¦í/kk¼ª¯Ð²T…c],žý´Æ®k`‚ÄÓ²Cßè0m÷˜JúÜ´CÚ¥uh˜®‚RGYò“g£Š ”MŽ•!à jØu ºY›¹òÆ)Š0(Æédm†Å8 ð¶Ý-–ŸãîW¾á4áÓ¯y>>¥_ÔÑ€#_aýç]v\“V2À#|w-~¸I2-`Q¹d™ó£EÔWé2ŒŽæÏ/£}Öì¸]8ÅŒrv»òeõɕ΋üÞ˜ÒË/óÿ±J¸¸ÀÄ­ígÖG,®.QK_¨/A¸ßñÅ;pö–ð>6àMl@pè9ýÓŒU…-ÎV%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:49-07:00ä[å%tEXtdate:modify2010-01-11T09:46:49-07:00•¤Y2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-la.png0000664000175100017510000000172112370216245030072 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœÏIDATXÃí–?O“Q‡Ÿ+Q*ÂK_•ZÞJšP¿€©qpeÂGd€ø\ü°°‚q1‘Ä„™ b &Ž’H­­5¶¯H†ByC•¤!$=MÉuà7Üáþ;Ï=÷wO.\ȱ̆—q `Ï5Àœk€§..¹ þ_XãàÍÕ¤z‘"ÒÔgŒ¡Ã˜Þ»ÏD³@D¸ÒÓÍ蛤S>_ò6¿þd¿vˆ1: [5 Üðû˜~ò€ÉGY‚¡F ùöc›WïÞ³ðvr¸‹&VCÛsÙ2õø>ÏgƈÄNúû{¾5†D³K«Ôë-ïÙúñEH>ãÙ¦àÿˆ11ž%ø ­ßªF’q‚ÄÙ•;HxŒ$ã —vˆ"9åþæ$ Q¤ò´ÀÀV¡B®ž9%WÙ*TT&TrÅÅåuJåSÃ¥ò‹ËëäŠ!(žbþ½­N>:6óeÂß{xý1¬íb·ZãÓç"³K«¼^ùÀ^õ@•s=3£»4k-©„Gêö ùï¿È—¶©×먢æeâ¡à¯ÉEN^›1¦­RüÑUtRVÚâîœÜÿPÕ­ó˜w `6¼Ì5×øãàBÎu ”æŒ#ÔzÎ%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:47-07:00´dg¸%tEXtdate:modify2010-01-11T09:46:47-07:00Å9ß2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-mk.png0000664000175100017510000000270212370216245030105 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœÀIDATXÃí–KˆeÇÝýÍûÑ“™dg}’¸Á$‚ÖœTL@6 A=”€7oŠ ÞÔ£âMö¤Q ®¢õ¢‰ÆC‚J$‰‰daggÓ3;žé‡‡úBï¼VrуSÐPÝ]]_Uý«þÕ0‘‰üßÅX|ŠG 9à-CåMXÿÂî˜L½;ž—ûê;°ü6„Þû8l{Ê/šBè\€µyPé}ìIÌi Á¸Áï‚9.lÌÚÀL°…±ør/ŠoÊ@ 3Þjmžý È? ±iPe(< ^Ü¿$Úaà×¢Œýš<>¤îŸª,v½KPÿœÏ@5O³Ç½ ÍS`?™¡ðXX}Z¿ —6  ·AGî{‹òlTéû trAІƷà|)çy+ ðÁ«€sš?@fìCy»`õC¨/ˆqt¯êÌ}°Rj;äç ô ¨"4¾çs}ðjd¯6;õVÀY€æOR {N¢OÝ«@ç< 3íU¦ëúæþHî†Ò³ž÷<,/@ó¤Nb Pã×Ñ(ƒª™ý?FL2h|/Ídæaúe1]z‚:˜Y)µ}ÂÔO@óÇþŒ‡Žù-F:³£Pâ@íhR÷@÷ 4NæöœØ9 2¹¿Úgt©«‘Áä0åcùB¿þ:øøu¹‚ iš aB” ɽòqîÈõ¯¥¹ ó;xI0“`¦¤:V^_6XÛD7ÂEÂЗ’…]\[ào@ÐÐAÕ¤Œ^º×ÀÌÀô«2¶½%Xz‚&Äo•Š©’L’eƒ™+ FZóG\ 5¬-éãßU}W—ý ð{Pÿª¿&8Ço‚ÿº UØSbÿ0†‰]b´e kŸDc˜?¸Å†€¯«:ê`µ="¢Änh&"U„ÔÝ‘ÞÕ°9_€û§ÑÔ àÎirCDªïàR?{k²†¨ˆ•šëz÷Š~@稼QñͯAóçqTléŒg£ed&¥Ôã–Äo“1Ñ›§û³óV`}^¨¸tr‹ïæÉe”¹ŸsöãÑ:ÚPûVÞ¿Ž b·H  ºa ¦}MìÉ^ñ*2%…ÃkúÞMë¸x„§ìÃBtĸv Ú—· K²74€VAžü'ÅWíd÷C|'ÄvBñ&!'Õ:˹äÞè—ÌÌBâNhÿKF S7dàFÍ92Þ¸ø4³º¢-p/@ë,™ÈDøäòÏŽVA$Ä%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:48-07:00B,Q%tEXtdate:modify2010-01-11T09:46:48-07:003q¯í2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-tc.png0000664000175100017510000000266412370216245030113 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœ²IDATXÃí”ËOœUÆç›on 0\†0„±M­` õ‚m€b¬‘jbºëÂkÒ¤Ñ? MtW×F÷5ºÄ…1ÆÄD)ÔHh‰Uz±ŽÜ)˜¡t`f˜û0|—ã‚R:Bƒ4,ä·;ÉÉó>ïó¾çÀ{üßóŸ^@yý-¾ê qñË+Q„ÅÂ{oìç\²€/ŠNÒyi iJª+]¼ÿBT…‰Vàì·QF'#€Ø–µÄWÓ°ä­Æ?1D0°H¤´l¸(% æ¢+Œ¤JHÇÓ(¹)³pG ¨þ?ƾۇ“w[+1SÍôöMf@>Z„”º hõY9]“ÆSÿ[«É\Ú™ ýfëA?¯4–ñÉkOÑ~¤¯(.±@z5Ö¢";íÏñ¦OÒÞXŽÃWÇO‹6~¸<ÃüBjÛñ¨žZ/Ó•²¬•ã‰Þ®óp²µ•è|õ¢Þi)ÇñLŽº^–kòëíEFFf)Ð28TÈí q»ý„”B`S@5u§©kdþòଯGX,»Íä–5S熽Lely¢Š¢€XOERJLÓܘÀÚŒ‘a³¢X¬È\ië6+Bµbf³HEE<ØÊ¸‹U:Ú$Õže&†!‘RZrÒÓ¯Oèù>/ì Øíâhs-'ŽTà˜`fò>Ëž}”|ÿ5Hˆœ9OY•‡²à(‘{an„Tþ j²D”y`å¡`i1œé¸Ë±Ê ¢ N8"V™ÉbÀˆxâ_ $­…kðÒäʼÜGŸ?B×´àp£„ :¾ÃxxœSÇkh)¯¤)9K,ep~…å\~GBHl"‹=ëÀÐrˆL =¡¢ÚÓNeÝÀÙ7ö¹!z~OÐuÇàÖœN"«ã.O2™±Äø¥?Èõ»m®ãTÛ~^n)G5†Ü×Ö•5] )–ªQ&n¨¤4+UOë„—º¾‰óŸ]eE3 ë6’Yãálûn…4½D”ҔĖÒt÷ sm`oE!z ºœ/OJ¦î¹y¾1Ag±‹N>®I13VB<¹qoÔ±€äÛ‹§Vˆ³¶Ýk3^í4Ë’ˆeœósM¥Mº~óRÛäãviŒœÅÂͨK×¼¤Ò{ÛbóÏGJIïu®Š—hëG*‚oºÒ;à@Jc3•åV¥¶ƒ«@áÅëÒ7錹é½'f ?¥Ç—ØÁþ [÷¦?¡üEÓh£”fÐéq|v6™i0 ÿ±b¦±-}‹œ>ĺ §ˆJw‰e$v€ósôòîÙ» ¤,p. ŠZ(ímæ·O³j ¼~odTý‰ Ê?8^lù)ø,¨ pà&4À*$@­Z_ˆñuúʉ(%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:48-07:00B,Q%tEXtdate:modify2010-01-11T09:46:48-07:003q¯í2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-nu.png0000664000175100017510000000234512370216245030123 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœãIDATXÃí”ËkTgÆ߹̙Lg&—Ñ™3FgJÍÅŠAZD$]ˆ›¶›tÑ(¥Ë.D¸rëBhé®Ðm)ñ²oXŠx£¨QC3™Ü›Ì%ד¹œ×ÅhZ]œ ¡tž?à}~ßû<ß 5Õô—š8õ#êÐ~¾3ÂO¿Ý`d"‹ÒtŽîo¥oò§cüòÇsD„‘ ½môì=!B;Ï dPžŒ†D|k6#õW?#™¿Añë¸Î?C \a¤àðÄQ,º héÚvñæ]Hõ¿8³A³øª³×ÙÃÕÛÏÉæ|¶»b¯”¢±!À~;@ODhú°éVݽI¾ €“æ¶œ~@wË:NìŠÓµÅæìÝ4 õ>,³ v,º’ ±}t·Dñ'6p®·R α9 ®xX·1Êß ±ì£«ãËX‡¿ífl2Oê÷j>ïj書A2e)‘äÊÀ$O‡ š–®áÑ» Ð7vŒœ`Ù.ùk`*? ‹ÁM£ Ð~é<õó…°#Yfw¦Âö ¿=O¤â  `ˆè‚ÒqëLÜB‘Š®#¯ž&ºÍrq—” Ê\EëÞ8mï °·#ÉÁ-1ÂmiÒé)‚룴\¾á/z(E‰d†˜™Êò§ér'èŒóþ”fæ=oÁ(˜>ù(Î6½Dæò-®½˜ââÄ2ÛÚ+/ðÃõžæ‹|¶+ɾP³ãLÏçœËâ”Ê(ðÜãû#þчô?Ësat‘û3…J‰ U€´aƆÓüšK1Ø‘äÓ ¾þ8J!“Á¶*¸ÍTñF»K.ÓèÌ9eA)×ùˆ”f ?³KEÄDA}(@¬)ˆáÌ"Z¥{GPåÔzê!ýwŠ+¹ª7X)¨×¼Áë;*¼=GA­ê¯¿KÚ{š[øïÀãµèYk€5Ý@M5Õô¿~Ûz›%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:48-07:00B,Q%tEXtdate:modify2010-01-11T09:46:48-07:003q¯í2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-gi.png0000664000175100017510000000210712370216245030074 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœEIDATXÃí–OOAƳڡ€ÒEj"ÑŒFýoÆÏàÕÄOcâÕ£/&ž$ÖÀAÅšhH Eú‡Òì¶ìμ¼îV ûœß™ùÍ33ϼ0ÔPÿ»”ˆ+€\9n> 2PD8pO)…Rj`€Ìg`SC¯ÝÂî'4Ö7è~Z`ìÒ“s³8].ã¸î¿èïuùøè1•U˜>Cýù PpúÞ]¨}çÄõy.?|@q|,3€“Ç.OkŠq Õ‚ r‘Råª+ãOë\G@¬ÅD5“:BXÚb%„Ž¥f &ŠkÀ¤)›áÛ¯Bl³Ec!¤ÒÚ¥ÒÚ¥¹°„m¶Ù~¹Èfø“¦Ù]ÍZèú>Z0SÛâl'b¹ÊM~Ýüd¹Êkñk[h­q}ÿè”RŒ–'(ùº%+|Æ € 8BÉ/0ZžÈõ$3è †}nãó„€ûø,’p ùœóe:õ:}´Öô,L[Œ@ÜuÑŽKßN½ÎI‘Ì.¨½§Ï2å€1)?Þ®Òy÷ž¨ÙÂìlóm²‡A˜iŒàžªP Êœ¸v•©ó¸n¶½©/Átæ ú¼` ±—òõbŠB8¿áQ4>Êu!O({¦ÙÊQ~ÈMÁ !`Áo'ˆòÿ¬^Î0üã†×¯Êì9ÿ‡4Øê@·"´g[t†CXd ›(ܶ â¿PëŒ ÔXº£‚×W”zÇà@¢!®ÀÈŽ@o°fd¨¡†ø O]ó²sϤÍ%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:46-07:00l %tEXtdate:modify2010-01-11T09:46:46-07:00cNÔ°2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-br.png0000664000175100017510000000277112370216245030107 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœ÷IDATXÃí—MlTU†ŸsîüÜ™;ÓNgÚa†–R PE~DD¢ F !&MŒ„„ [·n]®HŒ %$†…Qƒ $†°@Q‰?±å·:ÖH™v:3íLïüÞsŽ ±Z¥tú.ïÉýòä½ï÷}÷À]‚CÛÛ Ûí€ØÝn€wÚ n7À¢äHÅf§À·nW[ÿ€¬ VÙ—˜àù®I>(%9ZXÂÏ0êŸè°Ou9Ø}­N…€1¼’¼Æ§Ìá©¥œ,Ç)«…»!8´ÝÜ–RÖ‡\ö'r쉩O:ŒŒ¦¹:Ù@_²Ì†¡,vÒåølœ÷ )ÎÕ<#îÖA¯Éîλ³ ‰§Ï òÑ©udÆÔ~ì`‹Áeö>yž·eØ®px*͉™y/˜;°…fSx–ƒÝYvuè4ŠãŸÝÏ[ïoc¢àÜ,jBàÖü ¦Éæ£`ώˬêã±È ‡§Ò|_P7óÏ<‹]¯ýñáR“ý‰¯¦®ðD´DÔRL5–súʳ¨®Õô Å舋‡1„íi*®ŸR9ÌÆû²ô'fYtyЩ†ñ¦MežN™ã€#5F¦9ȱ3Z¤ÃR@iÁXn%åÖ ¶A éZ¡c}š¦l¡êšÑï²dF&É\I0<šf°¿€% C³¬HÕxÄ)s¤â‹Ù®–ˆû<$²¼”È2¬!}óÌÓ’oÎzœ:‘¡^WH Ò’‚>â)‡µ=¬ÞšbÙú8—Î\%Wˆá)Ï2 j)ž‰åÙšåÝBš#…4EÏ·ÞŠ"xž¢ÙôB ¤@yšºjq}lšk™ѸÍЖ4[w²&vÁí;`NjZ2R‹r±&$ }þ¶¼‘^!!›q.³C­4JiB!?>¿E«åQ­4™ºæâS ßt™Þ؃*ÊâÓr7oLôsl:9gNÌqÀÕ’“å8çjžëšd_|‚l¿eذ&KoOŽK¿,Ãù©º7 „H)°‚~‚vý'¢ê¤Ð´´àBÝáhq –’\oÖm1\0\‹â—†¥þ©h)#?öPqhmPžÆÚ‚¡‰Î2{w~É–u¿RÔ>>žîáõÜr>™IPRóíy<ã-›¯ÜÆ›6é`ƒ‡úó$;]òE›²@i Æà÷5XӟㅧϲãáQÎ{aÞœèçí|/£ ïoòpFñ †r‹Å ¸¥¿ZFM!øÚ.jÝÑ6,+‹c¥†«Î=[ÇwäÀïÕ¶’[rµÅç•Øb_Ÿ½ë*w ðr»N´ í7£ÿõöÀ=9¯Tq%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:45-07:00#ûv‘%tEXtdate:modify2010-01-11T09:46:45-07:00R¦Î-2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-jm.png0000664000175100017510000000213512370216245030104 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœ[IDATXÃí–ËkQÆw2™IÒ4¶I¦±„ú€""Mµb¥Š #èÊ…—.ü¯êÂ¥PÝ(XWZT|4 U¤Z”PÚ<ªi›d&ëâ&±¶Õ¶Å|Ë3çžó}ß½sï6Úøß!ì€]Ñxœ p{&Ì×U‰Š7õZ}~‡GÒ\Šæ0]U$ Çœª`6g2·bPª<ºlªÒBY0·b0›3¹Ð+0]*® Á8€W¯æX+¹x±ØAªènŠ õüÑ5âÑ^½ BÅŃ1äàDÂjAªà&‘ññ$à]ÆÇ²í b—Ld­s·YáD(ÏÅhŽX(å-°˜†©iû-䙌^‘!èíQÌ2E©ôO"Y[ß‘#õœ Yn4 ç yÊH`a &_ÃøCx™P¹RåÀÙ“ŠÈ¹!è «©¢N"íc"¹¯áˆ” m`R­¹TW~'ÎcÕ/¥áY­ñó·Ê)kÖ²B0r ®]®9b©Â¿s„?)–°RŠï>‚É7ÊüJ|P wâÈûŒ€ã¡ÂŽoêµíÈØ:ÓYE` X d–íïš@Ý+¨ܼçOƒá^·R€S‚§¯àÖE •ÝZñFhÛ§ì-þÎ-hé!lÉoØÒ‹¨åWqË#ç3ÊUÁ§oîÏwïÉslyJ GÖ¸zh™£]EtM ]JFP(kL$Ü›ïj $͘ˆê§ü˪ÁBÁM‡»ÂA¿C§»Ò˜ˆ>š¤?`s¸ÓiŒdÍ„W—ôùú6†Öìêm´ñ/ãó@¨Ú’}*r%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:47-07:00´dg¸%tEXtdate:modify2010-01-11T09:46:47-07:00Å9ß2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-gu.png0000664000175100017510000000204112370216245030105 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœIDATXÃí–ÏjSQÆsrîM›4µ1iDŒuQb Vpam„‚àJܺöħ|×>à ‚ˆ *êB»€ôÉÍÿäÞ;.RÒnÏ…^öÛ8‹3ß™of¾süïÝúƒJÀYEд~== <3ĘÔÂO#(‚ž™<‡fr;ë (¥¸C1îaÌÛì*/ów‰0©Èó¸û‘Gým¬"´LŽ=["$“ KDËä¦LÔPq««1¡¸eNT‘ãš³I1«cÖgðTù4,Ó?a6À×B“Ú͉É|Þç}»Â@<ç·Uݲ×fiÅð¥°}ñêªeÅ \LF ¯#Ö*1rí2!'>ñR•‹y†àØÊŽó2¢\ô™Ó, Q… JÞ‚¢Ç|cD‡™³$ªÐiGyfÃ.ƒ^õGxadÁõ9wm²ìýh`d‡æxL«}ÀÕ ×´îª€+¥+û¶Â¦÷ޑק^kpÝËò¼±IWKKÔ?©²õëwJ!·ËÂ›Ý‡ì —ÑV’h ±|èßâ·ˆ­ï!¯Ög€{&œ„J_|^ýÙ@€±˜DÁ§AEp­ P’™—ŠL­ß JA\ ›Dަ’)è`² pð•µq#Õ•¬ ^,Æm.ÅAJá'8½’=U„0¥mè$ 'û@ÿôÅ9Α6þ½!¹¢ZƒÕ%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:46-07:00l %tEXtdate:modify2010-01-11T09:46:46-07:00cNÔ°2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-pk.png0000664000175100017510000000227612370216245030116 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœ¼IDATXÃí—¿KaÇ?ïÝ&æÔ¢é`:¸HªÒÖÚ¡: .*8ÔAè :8UðÏè"NE(ŽñP :”¬"Q ¢Xm¢¢!Ö©grw,V[sjêéâ³߇çý¼_žçå9¸aÛvVq~mž®÷],m-!„p@N ’$ Y’…›o³‰6¶ØNm+ë;ëB’k¯t‘6Ó¦ÁPp­ôÅÂ_¯ ÀERðø‘%ùúJ‹JiºßDÍݤ¥IH`Ÿ_#7J¼%t?ë¦ñ^#Ë[ˤÍô±¬È u•uT—WSá¯pt''Y’i}ÐJÛ£6&&ØØÙ8ne!Z@£ói'ý¯úi58:qyôöÇí¤˜[›; 'd‚ÅA4U#T"Ppt@Éۦ¶²–Éo“¤S§´Œ•azušÁñA¼/3ßgýòtU§(¿_¾‚¼‚R Ó`|aœŒ•ÁH޹O UeUT—WŸ)ïîcdŒsŸ¹œz ¶cÏØ#Ò\ߌZ¨^hä®Ìh<ÊLlERh{ØFÇ“üþ#ˆ“ 6xdªWE’Î>*§ˆ%c &¬… ‚ô½ì£"PAäK„ÅÍEŒŒ")hªF]e‹›‹L­N]`Z&#S#hªFÏótU§÷E/-õ-ÌÆgIì'ðåû(ö36?Æèü(–eÙ9 ù3ÉÀ‡âÛqÚÛ©Õk •…Ý ±{°K4eøó0‘©ÉT2k3æð;’©$C‡ý:JX £«:pÔ¤Ñx”X2†i™Wüüå„i›¬$VXI¬ü9Èþ£Ÿ7†ÿpÄñû§ v}[R€wNyržâÉ󸺔¾É~}Z¨Š`qÐÕµü‡S‚eY˜–éÚÉmÜxü†sÖí§N%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:48-07:00B,Q%tEXtdate:modify2010-01-11T09:46:48-07:003q¯í2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-ci.png0000664000175100017510000000127712370216245030077 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœ½IDATXÃíÖ½ Â@ †á×—“è¨h=˜‰Q(˜€‚‰“d zhP¤$äÇtÐÅI]ã¯;ɲŸó5žÄ‘ê¼Q¦„ÍŽ¸=!‹å`å»)9æ7îAÌÎÉVÖpPÑÿaøR"H ˆ&"jù¼˜ÚºíÌ])Ô]›½ê" ö"mµ7÷„@oÎþ¥ÓžOß #ž Œî:¢ÙôÊI€yâ8Àp€±?™³®©‡Ô€"%À“<_ÇJ0ÿ‚R¡%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:45-07:00#ûv‘%tEXtdate:modify2010-01-11T09:46:45-07:00R¦Î-2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-dj.png0000664000175100017510000000222712370216245030075 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœ•IDATXÃí–ÍNQ†Ÿ3´1Ô#+W,½6^Âu¸ç Ô!þ4B "FP ¨ü¥ †Zf(Ò¡ôgf:3çs1vÑX -.|w'g¾ó=ç=ïÌø¯K–ºûÚÆ,êrbeO_w|MoܸµªÞ{›®‰u B×!TÅ e·àË»=‡¯¹:U_ÓM%""@Ñ Ù<ôø`¹˜%?THÔ¯þhÃJÀÇŒËjÆÅ®„BGih¨ ß‹>Ë–ÃÆ¡GÙÓi ÐPÍ×lÛuV”' ‡ø+€y'díÀeeßÅ*ùš Ëlj …?ÊËûŸ<ŽjúòÑ AkˆÇ›ò!Uðyo:$í(¨öAšDÀq ™„l†‡¡¿zz~+¬Ô£|¼7k¤ n›ùhÐ Ë‚ÑQ¾¾–Å"«i–3efR&9·vf€XÓÈ0`p0J˜ @oï‹M‹=ÇR8‹–Îé@¡[[‘·nÁÐPËœW`>»Äxz’åü• ÚÆ´h •Š £iºTYɯ3žžd>»„íæQ T›1<õkèë€/å]žšSLeæHUM´è¶7;éf¿vÀTæÏÌ—l·©ë:†2ÎÝüDŠõcìw<Ú{Á¢½B9¨\HÓpB—Õü:OÌ)fÈzGm~GM¡h¾•SLîÏ0aM³[IèÕÁ‹A @2Î!³?Þ0ž~Îz1‰ºÑ9wøV+ÔK$rŸäaz’E;AÁ>&†2ιô)&¬éûRe³´ƒˆt­qCêöË;דÇ߸¿Jê9ÿŠguàæ•¥L<Ûõÿ×?£ŸÌê™Þ*žìí%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:46-07:00l %tEXtdate:modify2010-01-11T09:46:46-07:00cNÔ°2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-mn.png0000664000175100017510000000157712370216245030121 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœ}IDATXÃí“ËJ\A†¿êîã9ŽW¼2*JÀU@¢îuåJˆyƒy¨¼Aâ#èZWº Yˆ›¸6 ÞpÆsª\èLLzfáùM4UýU %%9›ž{ÿ‘G›üøZã>« fo¾3²û;v¿cýpy7w>÷ÒìõZ@›’€¤†Þ X‡Yÿׄ¥²•ㆬ7døiEúâ%@H— ²µ‚ä“vY€‚ôaÖ“F¨*x¢!<µþd½0~ ÒçÑ+ÁzÔ#; ¶swrìZÐKAúa¤Ö ]Ò¨.¸æ™,¤+~Ü0…0¯¤«9n2î.„ÖÍ1|ÕÌÐ?€Ò¥xF23Š6tL×iÚØ-ÔO8; ^dñrvž]ä÷ë ØŸE£™¯ég…¼bñ"‹ø¥Ë úÝv鿉?Ÿ#¯f˜ Ež°^^Ó¡:†ì»ÄþªÐZULñè'ß&sJªZNÿëxÅ‘93˜duæ³xZ'€èwÛaÝ'0¬à\µë/š®F<< %tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:49-07:00ä[å%tEXtdate:modify2010-01-11T09:46:49-07:00•¤Y2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-do.png0000664000175100017510000000164212370216245030102 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœ IDATXÃí–¿kAÇ?on²çe³ çÏC¨e®‰"˜J!hR¤ò?°°Lom›ÚN,•€ "HP‰Q¹Ë%JØM.wçER¾#°DïÛÍÀ{ó™ï¼73Ð×ÿ.áöc[„*³wk,<šf8,Æ çùõü%81¥ó@-O<ð,o€\py.~²4W9<ìYžÌ¸U4S:.?»û(B˜¦ç33Ž¿smÔL=z.äÕê{:û{DY›¡SWª—ˆnM€ØäûVl²@€fƒ§‹¯qÛ»Œ·š|˜º7Íêesmø‹g†Ì|ÙùJ;mPK $Á o»MÆÜ•óæ\Þ8W@ã&…ú. !ëQÌ`Pì%¾[ß4U[“•«øÒ#â *T]™Û‰9—|¾?g:6U¥tó:§Ì¢QˆCh%mž¼øÀòZÃÜ’>^yc‹È” g)•˸è ~~;|ª',½[7wg½‹9Zíªˆ“ƒ¿€àøÞ‚ïæ“ûý3XË`&o€\諯?†{̦}~%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:46-07:00l %tEXtdate:modify2010-01-11T09:46:46-07:00cNÔ°2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-ua.png0000664000175100017510000000116312370216246030104 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœqIDATXÃíÔ±@@@ÑæB‰t U€Rô¡‰~ä*@’SÆOö7°ovö"¹4-» È@cV0›€Ê€ —’\ÀÐÞ* ÝÇXTÀwu*@¿ý : î?l& ½g_ÛxL@¤÷ƒÿG_| %tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:49-07:00ä[å%tEXtdate:modify2010-01-11T09:46:49-07:00•¤Y2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-gs.png0000664000175100017510000000317112370216245030110 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœwIDATXÃí–Ëo”UÆç»Ì}:ÓÎÐz‚ö"á+¦…5‚&†aá51!øàÂþºÇè’1ÆÄD1…"ÚÒ––Ò™é”vfÚÎ}æ»@›¡­‰ac»“œ÷¼ÏyÞç;ù`“Mþïˆäç'QÞx›¯/>äÔW—‰Ç2Uåƒ7·q"w€/ý‡9}viKš#^>Üëᣭ)2‘íû6Ã݉4 6$@ v´t/D›"›$Rª«6J H‹D¦ÊH>Ha©€R™D±}ëÝíIå? ücô»&ܼßÁÎ÷rñÒ8™L±¶N‚‚ú€‡þ£-Â]=ÜÖ›)^ZÝZHtÍFQ$¦©`Z뻣¼bw¿äàÎ>{½•Ýûùñ·uA ý~'~Þê ì áêhç§y?œ@r.¿Ê~M•loYÂã2®'_ÐÖn‹2åÒh(éÈÎñn{˜Ãýýd’)´S&x¯/„ëù íÛ£”Ûvpáæ<##ÓxŒ". *Oj˜»X¢Ñ™$­Ù”Dk±ˆ›¯IùÈ7 h¶‰âv#Mƒâ­AÜ]]UE8–¤R6PLœŽ2Yt,èó9ˆFý”fèò^§b9˜²^BsI&s”ËV­Ë9‘áÐQTY© ­•¡#4»TB*(âq*WE•pØÃ¡CÝŒÜñC¡ˆ¨*ôD;Ñ]©ÔØj_øQ𲯷×voÁ5=΃‰YÊá&‚ßÒJÃÖ0 ñ»¤gR\{¨q#n›+‘V’@u9ù33YΞ›ÅëigG{šBÉÁøD„Bþ–™Cgv-§ûx¥;Ê.o‘øùK\LsfJðâN'Ÿ œþùc©1Žh¡/aWnšÅJ†;É*åŠYs£@PÐE‘6º;WWx¦hðÜ"¡JJ³ÏÕ„V;ÖÀ™â—ß³œ¹gñWÂ$[2 „rLub±E~½çÏ«÷Ù×ÛΑýÛx¹/„f 3·˜5Vôû¡1’£XYÀjU²§©™T¢ÛײÐWÆûB踬6)ÓA®d-Ï6às²ó¤Kù*O‡º ‡èf6G|¾DÕ~$@Ó{{UÂáY\¡MÝCU²8ùw¯]àæQŒj?àZq`4  µV.å«,ñ$Ý+3È.–È.¯WnïñZ4F,¼ºGWQänT[x`àtˆDڈǔ5¾‚ ±úu3 “…¹®ºŒršiG'õìkÆÈÎ4qQ XM¥¬’™6il-0g褊#¤¬ê{ðåâ2 öAúOX¶F9íaWÏ"Å:±Ùzªw¦)…F‰º—¨Ît#e[M²Á^ë’n †Ž^V¸:¼ƒË×{Èe7pžó~?çÀ€ÿ;âñ…(·õ0f] % ú+ åu#?ÚTpÛôþ' =ùÖxj$¹ƒ .‘ASÃ!!¯6yX°˜ò äx{útªç³ôa×cuÏeø¬Bîjˆ°©àÛ ]z.¢KHøR÷YyïÒˆän†Hä5þžD¶{'r ÐÁÙ—¼Úpyó©Mê¼ÆxÑ œQѳDT`IA,Ã4Mœ–ËçºÁòšƒ:ù+Ñ‹zâ ®ow7‘à …óóóLLL'x±¼ÁóÕ_ë>Ù¬NâœÎp^ÅH)ÑI¤Ý%˲(•J,..R,©T*¬¬Tqö}^¿sÙøèq&cJi„’sRÁH‚&|ßí¼˜DQ…T*E2™¤ÕjaÛ6étš“ñøÑÛû  u]'R.—ÙÜܤZ­²½½ƒ&mf§#ÜŸ±˜ÌHZëÍJ@k=À·Öý¡@' 2™ Û;;4 ò§ ÌXÌMG°Pqjþ/…éÚ%<øIHܘ2y4{‚ëãC°—Â=ø!ˆY*sÓnYd gÙÇ©u·ã? riƒri”;éÌ·â pf±#qw,²v/!×:¦qüìr<©Âmv’~oD5¯] ë˜^g%0`@Ÿù óÑõ ÷V%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:49-07:00ä[å%tEXtdate:modify2010-01-11T09:46:49-07:00•¤Y2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-ke.png0000664000175100017510000000206712370216245030101 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœ5IDATXÃí”1OAÇ3»K.w»Äev9¹Æ„‹&pÉs‚Pp…)-­-øÆŽ¯€4müDâR¢WØiÌåàHö\Oðv-ÎÂÆd§ Ûð/ß¼7óËÞ{p¥Œ%J¥R¦¦an¦är¹—™I–2Ëǵ\×E)õßs¥®«×RZAÐh4Pž‡ ÌÛ6ó¶ (Ï£ÑhÁå´Ûm<ßg©^gÁ²Ø¬ÕجÕX°,–êu<ß§Ýnk˜Ö×µ lÇa¥Zåw³ÉÙYbV«|—’•ÕU=€çkkZ±”œ6›D€Q(0 ä;–yT.kÝ'Þ‹©ÇP½$á ßg.޹µ±À—ím¤dζq…Кkspt”:Ù¾»@É0¸Ñjp2°;2†€¡€Ð2 Bà“„1ÏÅ’dûÇ©´Ê|™º{ئGλÝQLˆQìoŽV䦊©“0 ,÷CÔ0&_© >î³lH¦m‡1]€âÖ -&…ÀßûÀÏWo1qlÇæÞÃû¨ú]d¢ç©ùììVÁD~‚k创~L1ŠøìÇ|-÷9ûµÇitªðfÿuêd)%• B25Óãzg4†;3=Žw±{­N‹8ŽSß)x’þË,iáÍ`{Y\)sý8š¥ ŠÕ%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:47-07:00´dg¸%tEXtdate:modify2010-01-11T09:46:47-07:00Å9ß2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-ls.png0000664000175100017510000000163012370216245030113 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœ–IDATXÃ핱NA†¿Ù[!Ȱ‚"…,(’}ƒ”Q” RRæò <¢rå"UäÂä-,ùz:""@Ø—;9 Ÿ‡šDì¦ØÆ³[ìüûifgŠ,i½ûÀ&‰¬Eøu9=Œ ðç®þÀļ|`Qýpy\Ã=ìþn;(PU©ª €4Í ²An&·Þøœÿ<§ßïcŒaoï›Ay°«%ï ù|N1¾ ú} @1¾À½ÙBÄÿIÙ°Ä=äáêꚺ®P%¨ AÆ’$!ÏsêºFD0&¬¡‚ʲd00QUz½Î9†¿™zª( ív»Ún·•‡þÓV«¥NG'“‰¯zç-ÏsŽ¿“eÎ9Ü[G³Ùäôä”Ñhä_‚ñ]ùìä¯^ò~÷#[ggTe‰IÒ4eg{›l}?ÙÿqàÙ¾Âl6£*K¦Ó)ˆ°²²LšfXkñŠÂÑÿù!ÿnô¯ÅG6x†>E`ý7\ØådékT€×/Ö¾D¨u~`¡èº€àËx«²Ù%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:47-07:00´dg¸%tEXtdate:modify2010-01-11T09:46:47-07:00Å9ß2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-gb.png0000664000175100017510000000375512370216245030077 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœëIDATXÃí–ÙO\çÆß™Ãlàañ°Ì`V/qÇ€í:ÆÆÛ8±'N¤(±¥¨z•TªS¹ýµ²Ò¨7­zÑ‹FUSÉ­”¬ÄË 'ij˜Õ“aéŒáÌ ÌÌ× L¶Ü¦µT5ïÅÑ9:çÝž÷y¿óÀwöÿnBJùðAˆ§’tuNåQ/žFòeÊc÷=C£>íüï?á‡wðÍAk½I2ëy÷Üjºë™úÃû¤½~†Ë;ª8{þ3þ¬E2*±&x¹ªÙæ)ýéŒÀ65<í=¯¦X­qIÀ•[cÓ>ÏŒ@Šî?Óv8ŠoÊOç¸&OïOom?&ô't‰ŸúÕ/~sÀrðûŠy_YqÊËkoüðYÿŸ¬FZ;Çðk €€—1´-V#åEi¼œ¯½ð7ó¤Çm3n/Ö'VWDÕÑH¼’r¡C‹ÞRµ?ç¥rŽ’tê¹xµî ‚ÁÅoÂúøA`0êÙ–kåxž‘ƒ™7ZI¿¡¬B¥PUWàUT•Ö¾):‡¼TïË#?Õ„.AÏ\} ¡:MvFã2¸ü…Fψ— ¶À2°êÌlƒ!žgŠm8«Kp."×(‰´}ÊÄÇ×Ѧ0ž–Mcê>ìö36u—·s3(ZE, Ý÷òËß6òç¿wðâÑ­œD¢Y¿®pB …ië£÷Þuõý8”à<ìÀ^æ ©­³«™ÌÉQ*7gÓ·‰†Ñ ê{¿:Eº.LøV;Þúfü“>ܳiJßÂGC=#nZh…Øû' ±tÑ‹|v{”Ž>\éå…£%œ¬t`/Ý…åÖmLõÍdMÜäxf&jæOtÖu]Ñîô‡Ò3'šŠJüи9àfÎZxRÅ+$ s³kŒ¾{“4´|Ák/9x±ºÒœ¾·Ôæ¿Ñ¦76}U•¤ÄO,GXÍ{.¹ã’®üñ–éÖ#E@ü·$K”Ç?¤ÞÕÇŒO“Ê6§&f§Ûpªæ„¹bOÕÛsÎÅ>ï™}ç=mg–‰Á43¾™À·K¾Út Öô$JwnZ>–n!ÄE55ùëªx™LÿM[›ïkªøiÈò§%ý¿³ÿû'xRxÃW¿!§%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:46-07:00l %tEXtdate:modify2010-01-11T09:46:46-07:00cNÔ°2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-ao.png0000664000175100017510000000203112370216245030070 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœIDATXÃ픽kSQÆçÜ››4mZRoÓšjP,.¢Ø¡è¤â ÒÁª8‰ºº¹:tñ_\+89ˆ.ê`œ\‚ B)ØÖ&­‚•bóÑÜ›óáÐÎöÞh¸"yàp–ÃóþÎó¾¼ÐSÂåüÑD\ Ÿ4Àƒ¤®' “,þŸXÀìÞI¸#†ìIEªh:‚pÿäçÂì Íð倠"ùùÒ£µè`Ñý„ ^I£~6g ·[¤'t¬$:™Ðø7ò—BÔ¦`c.CX‘ä§CRû£·CŠ¿xÇ€Ù88д×$µytÉà„æå.è Þï- úàû°ô”‚ö÷mÙËä¶ek<äó{Õ{Û¹wë_ãÕ·–É#.wf²<}0_Ñf'ïRà0«úxÖxÑPØÝ~ °j¸@XÕ|i¤¸zËe]†¼y§hµ,Ç RYˇJ›UÝŽäå÷âw$( C9ÉùÓ¹~‰µpc&CeÝðêmH­m 1×Ç1‡kÓ,W5+kš©ã)ÎL¥¨7-ý}‚ûsMÊŸTd¿Ø‹¨¹mÙ——LŸõh¶@ØØ4,.k†r‚1ßap@³UïRÅ‚¤X>¸Ã¿°¤¨~ÓŒú’s§å»E²ß²VˆÊR„a }é:dá´Ó#FMC+;ñ⇟•±·l ¢!Z£Azí*IÑÁìuÏ6ÈZûhµ¶JzkÓQ1žSÈ7ÇЮÓM®1 Èßë›ä.úBôÆ*±WÁäó-ò„eÃÍU’ÅEÄg_>TËseÖÞs± í'Í.'aLÕ³y©ÂbÙäx˜ð¸Ùcïh€iè¬.yܪ—xÚ°±Û#N2gK¬Õ=flƒ½“˜õÝíÞrÑävÝçJµH”d<~Õçåá ⛿¨ý>Ûû}’4gÎ/²Z÷ñ‹ý΀Íf—^0¢hK®.x,Ï»DqʳÝ.{í€ÅªÃ%Ë”¼<è³ÕêS<§ÀõºO­R¢Dl4»vC ©±RsiÔ\Äßý¤ê³eæ+%tMÐc^ôé FÌy6Kó.¶)‰ÓŒV; Ù° ÉÊ‚‹ïXtƒˆíVŸ(I©Wª¦ÔÆ)»}{C¼Råy·h’劃΀æÑ âó¯¿Wí^È0Î&*¨º6NѤ{Ñ "4!ȕ± f½"q’qØ I³ñÐK]cÎ/b:G½`˜¼ö©8~Ù"cÚý!J)`›:U¯ˆüèÃ+”,ƒaœ’¦9Žm§QœR²LŠA”`$R׆ †.° ƒ(û’lœdšåD£”’e  ¢Ë”˜R'ÆH©a›’A” jŸ|«ê³·U,S²Ýê±ÑìD1Çævc†…ªÃqÈÓcö»L]çê¢Çõ¥ ›»¶özÄYFÍ/q«1ÃŒkÓj<Ù9¦ q,“Õz…•(Ny²Ó¦y ¸ÿÕúk¡@ŒâtÍ©ˆLÖo¨â™H©3á9¯ÙïâšÄ”ñé™jšø+‰x#ع£³õ[~ÁÿÄ%N¥¿•ôï‚]ÿ&×%.ñŸÆŸ¸Ïù°¦"ó.%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:47-07:00´dg¸%tEXtdate:modify2010-01-11T09:46:47-07:00Å9ß2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-td.png0000664000175100017510000000130212370216245030100 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœÀIDATXÃí–1 A Eß즰±¬í¼ˆÇ°«=€çÄÆ£Ø{O`i¥•:±pDDP!†)òù¼¤úêX‰qc»æ“=ËÙŽ~ïú6|®9¬F·CRR3Z€A—`íôހ걧u/2P{¦N€k¨ _.O<¡VØëf_÷~ð@@@@¾ö¢O¿åoç»?"ÀÆ Ðz:¡â+°°p^K=Å¡ ¶·œœ~ÌÐ?éµï&PHlÇ%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:49-07:00ä[å%tEXtdate:modify2010-01-11T09:46:49-07:00•¤Y2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-at.png0000664000175100017510000000120212370216245030074 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœ€IDATXÃíÕ½ Â@ †á×ȇRÐd“—>TYë"T´áãmü-àGþ‘¡"'Fo* Õl& FoÓ\ÌâHPW€Œë¢â³oj bΟ H³¾HÎÓχ ˆ÷}qÏpÊ#З°‰üx™€½Ýì|M@EÏ›B bn%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:45-07:00#ûv‘%tEXtdate:modify2010-01-11T09:46:45-07:00R¦Î-2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-vu.png0000664000175100017510000000246212370216246030134 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœ0IDATXÃí•ÏoTUÇ?÷Ý{ßéüzó ¾FAqêŽö£)Sú[dj…‰[×þ&¸re qaܹ2Á‰!ÄІ(‚ÓÚ«m(±q¡$*¨¥Ó™yïºj@6š™Ž ûMîâ,nÎ÷|Î9÷¶þïo&rL*#¢ÿÀ€:fºLÞ1\ ׸m#D» ×o7;íÓ*„¶Sƒ«Ðû5Á;Ò):h£yòõèz熘¾±*Ê7×E á -:„#¶øHNz`b4¢âW8{ýænU¡ ë(âÂÙÒ¹€Ý‘ÏÂáQH&à‹9˜¹  ~IqÈñ)èžØ­0°<…ñAxabÎÏÀüW.]OS’>:AZHl üe@Ið3®éXF –É!p$|^†…K.üž¡¤²ôª©;DZb nGÆ4Ã{1Wðý!§>ÝÀhKiîƒ0‚sKe—î›JÊç Cá4ÅC¶Ø§xõeÃìb(‚狚s—j¼ÿñ»‚F[Æ¡R…é ‚åo\üÕbÂižÀÑç4ùœâò•:ÖB>'ÙÝåpâÝun­5ª“vðÒ8:7VaajuM¬‰Xù9â™<$â‚jÝ’T²zÛÝEÖFP¡Zk$Œkèp¡Ö€WÃÀ“оnÉþÅSÝ’“TøpªŠе¡Tl\8[L/~3 "-›z'îYÃþÇ%¯½cn©Î©©*qc™Ø“CàjølF0µhøÉ÷‰ ìJ‚jÁ lÆx)t"ö÷Ë#ŒÃù9ødÁðc:KX çABÝéMs-Pwɸ¥Øg9< Ù|9g.V’Y±º3Ô-I|/Ãpd¬ñ^üÎÌk®š,µ½<æAÊý¯86Žlìzù;8=ërEe¨õГ…´ÛÒŠï3ðÑ[ØÙE8=£X"C¥/€<³%ßg ß«íŠLSé ïC¶=‰7¥“ï1ò ìIƒ´ô«û'xç`œ\®­ÁFؾ̛øúÚ:¡Óšïu[Ûú·ú&Îè íœÛ%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:49-07:00ä[å%tEXtdate:modify2010-01-11T09:46:49-07:00•¤Y2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-cf.png0000664000175100017510000000223512370216245030067 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœ›IDATXÃí–ÍKTQ‡Ÿ÷Üs¯3:‰†dB–5ABX‹6µ Ú´r×"HZôÔ¶]´é_h´¬Àö¶0¬UD–™_3£3:sÏÛbt'æH1_¸pïùâù½_ç¡5Ù„¡'µ£* ºï†”+ñ`yŠë³håx×ÚóÎsäŒõ°@ç®'à°¥úЈ8E¶”-âíÇ àyµò0ŒI†2…–º›"uAG\4ÕˆÔ9 ö îˆ@hbú»–9bž÷ŸÈ"JÎÔl2(nWŒŸð]åq üdäÊNÎr¦{‰—ùºÐY³Iöˬ"¯è s«mïÈrº{‰[b!ÓæÑx :ÙWÖ¼žHóöÓi¾-t²Q´eeUkÊJ÷£*§¤xÛ{w.V> & .³Q²¤»Kôž qNªü+„›Òc³0ù½œ8ª¤ûº¹6D1Jàã6ûôáõ=CRÿ4›cqþ#ÙÉjí0<ØÃÍûW‘#)P€Tkäå2WŠX j+ƶd„I†^ç¯Õ€þEz(?0€ˆP¯Eü‹ÑNýž*5¼Z€lWX6{áW Ë.³øÅ±™ô*];úf´al4QP¹=“—á]^ÆgÆåÕØ¤¢•K¢€éÌtà@rrÅ"áN+È×äGv1Èoúõë7#R·1ˆ|Àúä­*8Ýîy{æòœo'lb×0€@2"ÑšRˆDµÝÆZõ Áãþ¹†ïp0ù€ŽÔ±@5¬ÄB†Ryí;õ+vÉØàVW¶ñÖ%àÖf,í™êMlšKG³Æ´Å~eè{Ý–ÿ¹öÏÝYаywÂmÖ÷ÿ¼h6À£fäš phM·?«ê|W N%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:45-07:00#ûv‘%tEXtdate:modify2010-01-11T09:46:45-07:00R¦Î-2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-ht.png0000664000175100017510000000156512370216245030117 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœsIDATXÃíÔMKQÆñÿÉLÐf"”b[ÔÔ¡+]¸Üø1\tçÒ~ ¡[—‚_B)¨E0K¡(«¢(šD3IhÆ{\DÜ sQ¹ çYçü˜óp!É{_r ð® ®s®âr¹<@»Ö@DÇú(Šª¢oPøØÝÉÌÔ‚@9¾8AòŸúCauýŒËë¦U­}«¯ò¹7Ãü÷1²Ù2Ë¿Öavz’»ZŽý¿e.¯šàÅŸé™›øûÒ¯i¢ê…Ý?ŒDŠ…"ù¡1úõŽª¹!%€Ÿµ•ø0†\}sÚÅÖö£õ")cØ Îèô™¯oR ‘Tünûƒ@ŒÒ¨–Ø9^#ê> ÕU¢ž ÿҌߖè1eÔâ¬RÌMÄ.¯(TøýÕ£tàÝ·Ež!þçÛÑ=¹Ô¢VV€§S<7Ìv/x^+Î_Âàà·ð*ÒñÃ) £­†K@’$•”)¹´ V%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:47-07:00´dg¸%tEXtdate:modify2010-01-11T09:46:47-07:00Å9ß2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-af.png0000664000175100017510000000212112370216245030057 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœOIDATXÃí–MOQ†Ÿ;ÜN Qb°RüXiBÔàΘ˜ÃÊ?à_ð§ãï`­Ä…éF Á iÒè´sçº]Xï4ÅÙð®n2÷œû̹gÞ3p¢”%L7>ž Û$ÛËÀ‹i˜4Ëëý¦„nÀïÏô¿ó<7ÙhðÀò!þVX€í3xbZë0 € ˆ£…€ezøÑÝV"€ãPêN§Â¶ŽƒV ­höï€ËáÓ30€ª×‰Ã°\&ÚØ#€8ƒ^á –“Ad$®ç¡UD¦0Jím 6×¥LÔ¶ŸÃt÷Ò­Êî™SØýyßVˆ³1½÷obçsÆ&”¬–@G‘#£ÔÞ¼Ã+8ýø!èU«~]%?u YAXŸ1¥0®ƒ71†¦qnË÷¨~(¡vëßEÊaäÐE¼«—z t«ÛW °3½8}yˆ4ÍjçÂY”P46ÖAX¸A€“͓IJŒ+ ›-öi^ÃÊJz‚ó¸Ù€¾â D â¨Aøsý…Eô`뀡«V¬5ûsK¨õ þ½;Ø=’úì{öJŸpýê6ê{…½¹EtlÞ…‰>Ãhs‡í™×øÓ‚ìµ Ôq#Äh”¿P™y…ÚÚI44’ù@³ûqžÖv•¾É5,)AkâùˆZ©Dsy-eìÀ 5„ËešåÕƒ¹+詃O82;žZ©NCÿPêÓ0u€vXÿ àeÚÏÒ¨§ p¢Ôõ œZÀäÞ4v•%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:44-07:00…Œ}%%tEXtdate:modify2010-01-11T09:46:44-07:00ôÑÅ™2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-cd.png0000664000175100017510000000165012370216245030065 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœ¦IDATXÃ픽NÛP†ŸïØ!ˆ¥-ˆP`«Ô±Tbk¯¢bccdà`ãH¯  WP¤ä&  ¤M”ÄØñÇÈ'vœ“ÀÀ;Ûç}ŸGdž÷¼r„“mw§),æ…£uŸ­BÜ¿™¸ÖÁ .‰ê‘Òê¨tT¤ïOÐiƒ»°ùÉÈׯ[È‹± 8ˆiþùütQ,ÀƬ°»lX™0ögµ£4Ë îßâ?¾;t6f„ƒÏ?æ=rjY©‘Ò*5øW¬^øNÈg„Ã5ïiÊÏëÔN«„•Ì€}VòTå¥F·ü2èyÏl`Xò§d60,ùS6àŠ<³É‹/“l y±JxôýÐSÈD^ ÿ2‰FEžÚÀ¨È Œš<ÑÀ¨É­ÆEn50.ògÆMþÌÀ¸É{R“ã–¼7àKAØ_é–ûIåewä½;KÞ¯í9C¬Ð¶´‹@tJíìδÿ†7î|›3{Íj‘ÚÏ4]ÝÓº‰DçsˆqÔøõHï&t/ƒ-š¼ CÜŽA5uÁ{Þ|å0COF±%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:45-07:00#ûv‘%tEXtdate:modify2010-01-11T09:46:45-07:00R¦Î-2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-mz.png0000664000175100017510000000240512370216245030124 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœIDATXÃí–ËoU…¿;sg<ã;~ä!pÓ´¥A¨¥4€+¤uSQª–E…„ú€X±ç¿@¬xHHD uUDYx©*A(¡©°c§vbÓyÝËÂ(lí ‹žåHs¿3çwï¹÷´Ï /¿ÄF1‡Ðûc@ŽO¤I.Qûc`éúo¯_~p‚ͼ…¡AdmàÌrý|n7âÒC“lø6YOÂ|Õœzmn«ÏýÝfÞfÓ³Ð"»¤œT±¸ÞfºòÎüŸÎ”èÙ&YÄaÀ€#€¹Û}^ùæ¿«3D™$ n”»ë; }ipí`‰wç§ø~ó87fÊ4U<‚4(`9hø§Ou ®–Y¾™£dšL·vÈ_¾†MÀgq“µ;ÔiH³²*Þë7˜=¢¹ÚéÓñSª³Ej–OnÛ$½ O§9*i™·ÃˆÏ“mî Ɇ4¼”hz‡…C9ª“5¾øÅä䉃,^¨S¼¹Jçƒ*IÛB‚£À„iófhñQØ"‚ ™4mŽÆãlù𝓍}ïÀ Ë×9üq½b€ús‘V„Z m 2N5_6B~my,žà¾‰1¼RŸ®Übõƒ#ñjÅWI—·Â:ߦ=†µ¥BãHÁs'ZÌÊ+ì|8‰¬M¹ÖeÍ« v}b×â3àý¨ÏºëPÀ~ïº)…'ºÄ¿Û„?»˜•˜üñ€Ý]„]Dž{„•ÃU::¼44üž„¡Ñ±¬®Àpù“]*/nã=™Çpm„~%šPVÿ€RЧÚT.lâÌöÁަï®b öLHù|“±3[ÈJ< ŽðV”{`ajÜcÕ‹ ¼§¶1\•Éu,Ñ`ø)ÅÅ•8sý¿}’öP=»Eé\ k2yäÿ1P~¾õFél³š@šxO"Y¾QШ^öp7­žefóûuOÿKýß#1"*"ÛÆ%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:48-07:00B,Q%tEXtdate:modify2010-01-11T09:46:48-07:003q¯í2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-lc.png0000664000175100017510000000203212370216245030070 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœIDATXÃí•MKQ†Ÿ{ïL!ƒ CŒ¨ciBV‚JiÁ•qÑnÝ»õï¸î/èÎU$F UG±YÔP”¢e£ÎéÂâ®83´ua^¸›ËópÞó}õõÔ¥œ…µG°€Úc||l€L ì ðí,DeÐY“ÛF3?Se~¦Šm4ò_D({øÅ¿RöɆ`e¢VšzÕe¯õ €zõ=ïáïÚüã Ptrø¥íæ:íæ:~©GÑÉe²!½SeÎ ‚}‚`Îïþ2¤ g•<{;M.Ãs.Ãsövš4*yr¶IÍ F‡Š»ì¶YœË±8—ã`·ÍPÜetx‰Ó!¤ÐZQ«8t¶hLž²ºì²ºìÒ˜<¥{´E­â uº@JnÿYD>ÚdeÉbjÌ05fXY²ÈG›øÏ"Jn4™j ý—ñ€ñצëö}¢éºÍÏ«Çá¼`ë"ú»"wÍ÷ö¥æÝó£…Ëè{ËhÞ4"Æ£õŠÏdžÞõ-*‰,ª³øÞ6…<  ¸{òà{ÛÌNlPõHlC2 ”ÂV´‚‚¯5DÔ„×'ت Ê!ÉbPÎÂÚ—D¤:Æ67‰x¯o-nâdým’^Ýž=[›j£†÷¸Ñ˜(MëW™¦¸Ñ¸Ü¿YLÀ«’ÿøŒ¨Ô#3\@ïÍ{âþ j,3¢4%>yŽ$IuÛjE~û¿\V’@žÝ°øôÍnjÍ*p†¸7“ Ç;k)I‚;†×ŽcÄ%”§© c”ؼoŒhç)ZµÓ‡«DÐðN< ˜®ÐÙû•ïÍ„¦+B,$4’=ÃÞ«·5Ãé|ÆâËGt:iÃ`0ÕòU 4" <åür‰N',¯¯££­µlDt«‰³n2¡ÁC‰¢²ø6{ðDSð¤ H@iŒÚ}h7‰àUÑl^ê¼9’es¼jëÁTÚþu;”²Žh6§³±¼¬%ú5ìžnÂ{úЮ‹ªT õÝKýÚ4ÊkŸõ,ûœùxT{òFè@AÚhšNyåj¥÷Ñ-!VOB4ªTA+’Ož!:ذ,d4BËñ£˜ÉÙ‡rÜ•¯hvÕ¹'[ Öf|¥eï¾ Ñž£7¬Ø kÌzÆñ‘€‚±ïn½¾Pz?Ýœ™ÆîM=0ˆŒ5!¤Dû>ºR¥ðÇ¿R|õ5´[!ÖL%°t@Wà~g.WÎ@EÚ‡sF(ì¡ëˆpí±ä–s›«\M·–³Ô.^¦vy vgê ù¿Ÿgî¿&wîox•JJ”IKmMºÎwAîrSŽäŒÐýe!*@p×B˜42!JeŠyòëo ,‹÷D3ÿ´º©DŒ¨önþö&&–d¢Ì¨ªèñðKà½%l° ,…žëÒbj ‘]ü6>0_‘öK=µÀM‰µ& ppm¹¼ÀZ ‰ Ê¹q´œ÷7g­øYb}WjË[qsð PÏZ,7ªQð“!˜&V¢on”v8“ŸˆèÑ—ãý:[z÷iCûSÁ­…XÜ@Ú@)d,Flø Â0h:ôÊç/ü×ßXˆÑ³ñýd­øPÞ`[Ï·†f*ÝwÈ`?F¼™Ö“Q¹0Ž¿˜£ëÚ4§sã}êåøY3ö´©ý)øyxóÛ·°1 Kï§»Ò :¿÷$±ÏÆîîBF#˜í­XI̶V*—ÏÏÑçeMG˜{§í–ŽŠÙô:ÈÝîe$×Õ´FØöÒb©$fGûze’ Ìdf{+XI¿Â™Üxä‘Âä©v¯øC„±ÛDÃðóÛ°L¬î.dKóÆÑŒ¶V¬®N0 ‚„_åñÜDèDar´Ý/=åK{'ZÁÐsÛ]©R¿ˆ—™C{ÞºníÖñ>¸NmâzÍ]p'JlT@,¹¢ðêkTÇßF9îÒ=Ps¨üû¿ÿq~9¼WCïN”h𠹚ŽÏgp¯M#Â6Î¥wPÕù?ü™ê[“d_ü=þB¶ád1UgW}Ñò„±ÿ+ÞQ3—LTVõœØtc6 C­5A¹BöW¿iÞׇóö;`H´ë¬{¦­µµJl8'†žkxNlú$ÓBUk¨ZúLUsPÕÚ¦‹o®D˲AV¥¿ºA‰ {@j…¡5…Ëy௯ß" 4^™ÓÙñÐ#…ÉÑ”W|ÊÆ}5zvsT¥Åd8EQ†Ðâãœï[›Ôš~g.r9œ<µ`F„2"?ý.kî„UøZÍó?OÎØ*PÛY°‘  h„„†aÐ?Ê+ýÿ :!øª‰%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:48-07:00B,Q%tEXtdate:modify2010-01-11T09:46:48-07:003q¯í2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-gn.png0000664000175100017510000000132012370216245030075 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœÎIDATXÃí—1 Â@Eß$i¬DKÁÖÆ£x /ƒxÁy{[±Ñb3îJÂŒ 2¿Ù@†?/›ýXr˜,ì)…éêÆ¬½RtÀ ¸¤šö¸dšƒ¨iÝc'lq“Í=¶VJùLT f€€tùÓë A€µ/Iy¹™€B×0pEÅ{W ^ßʹük €€€€h0:[O¥áxæÅëÛ;ßbMùÙ(¥tòxï.¥gš­Œ®§åÇÁ]ËÏN€Ðêé,7ïyÄ%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:46-07:00l %tEXtdate:modify2010-01-11T09:46:46-07:00cNÔ°2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-tv.png0000664000175100017510000000325212370216246030131 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœ¨IDATXÃí–ÛoTUÆ{ŸsfÎLg¦3)½H˵¥\JH5  Bbàc>ŠÆÄ?ÀŸ%þÄø¢¾/ñ’ P”X )VèýF/3ÓËœ33çìíÔ2Dnoô{:ÉÞg­o}ë[{oXÄ"žtˆ›‡Ý;ø¨c‚ãŸ_bpt!%Gv4ðÎHÖµóÙÏh­Yš óZsˆ×#Óˆ¶õ|S³ñ<ˆIŠ@#0+jÖMÖTóGO7ƒiÐmîøIxŠÁL‘«N”œvˆö`T¯ŒªÚÓR( óòï½_ÖAoI¡ÜVN_êc*ã uYr Bq›çj-^M¨Z¾Šáå«ÉiùÀ²WYéÔE_1®Mf\¿ä!¨ ›$=€IÓ&›óЪ”)µ©­ ƒã’U_ó•+„P¥/-)§e &ÐÞÔÇ »ÍœKĜаcå}„ ¥>©HÙšÖL:>`!ämá+Ì k#¿-.ázn+¾.¹#dÌÐ\q¢²Î7q!ó Ž¥¨C˜ S|S—Ëz¯µ[;"Fš¦p#ù&úœ ÒDަp®ŠÐç´ò×Ü3 ÷ÉcÄT±ž3S‡qU_[$­! QdÎOp.}«"”]…€)Š¥ …-søÚÂ’.›+ ÊæÔäQ†òkeã÷X4Õ>BWéwÖcÉ<Û_0ì6Ó‘}™a·‰Y/A^…‘¨»Æxd–{i‹þD^…éu6Ò9½—/IÎÑ5·‰‡§ƒÿ­põa“kÃn3çõAnæ™õ’tÍnGi‰Æ4êÞ &pàQ˜*Ö3VX%ò€ÆÓnó÷ƒGR4¶œ#"ÓxÊšw¸zøp‹Xĉ="û1×%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:49-07:00ä[å%tEXtdate:modify2010-01-11T09:46:49-07:00•¤Y2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-bb.png0000664000175100017510000000207312370216245030062 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœ9IDATXÃí•ÁjQ†¿sçŽI&‰m][ˆ4P\X©TAÁBÐp£ >‚;· >ƒ—ö JAwR[\jºè¢P*B(HK“t’›{\L‰ ¶™IZ‚Ðfwî?ßùÏ™;p®K˜}Ñ¿JáÉÝž?øJ1çP=ÆL [^.ϱôñ Hk L¤!U¯ˆ÷ˆ×;Q¼¢ šIð*U¡ñf¢Ø1å|GNJࡪ5Þ>-Àã~Erô„Ö“ ýñ½ :ß«OICù#¥’jøÙÎFÿÀßÁ¶b¥ë‰5§ (ÐvJ×+H²â«MV7šÉº t½Òvz´)éPlzVåËVÌ·zƒû7#¬–Þí0?›Ã9åý§&•ËER^YPŒc¥€•õ–×ÄmÅ+x…¸­,¯5XY?`¬`$í“aTaf:¤¶±¹Ó&*ªS–ê”%*6wÚÔ"f¦Ãc¯ê¡¬ç ´bÏîžCŒ FØÝs´bÏâ|k³­a†HR­L†Œ—¶ëŽŽKZÝ®;ÆË•É0Ëø³¨*¥H( oÞþ¢þðõ½Ã\5G)ân6‚Ì „P»Q X>|npûZž[Wó„»³L0F¨-Dܹžçç~€§ÆÉ…c2O cG Ø@¸t1HL!ðRk„‡÷ʉ‰‘¬?Á!#03ö€ÕÀþ¸×ÈðÃÉžNü5À³QŒà\#×oUZ¸Osm=ñ%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:45-07:00#ûv‘%tEXtdate:modify2010-01-11T09:46:45-07:00R¦Î-2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-kw.png0000664000175100017510000000154412370216245030122 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœbIDATXÃí“?NA‡¿Ù™e]X܉BâJb($¶Ô@.`<†×ð^ÁÒÒÎÆN ŽaAâÙ±@b0Blf)ܯ›™â}ó{ïAJÊGÐ?€ÝÈgAëÄ¥bÀƒX/Hàúî€JR&.!°•&\…Vð’m…ÆÕ=;Ž×7Bm*5óe _Äa±¬j•º±æg+¦ÇÐ\sÿˆš÷¨gPŠÃ'ývy5z¸hSSøëúBÒµ=zn@-»KËBŠ`J@!Ø–GŽO7㉱ýû)IÇöè/ùT¥ƒù „®*‡žãÓ±¿~@á ªñ'ŽO¤\TB¿žJà<Ö÷TŽšQÂÅÔàãuP–+B. |JJ |¢ÒX°ï!r¾%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:47-07:00´dg¸%tEXtdate:modify2010-01-11T09:46:47-07:00Å9ß2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-th.png0000664000175100017510000000124312370216246030111 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœ¡IDATXÃíÖ± 1DÑÙ» @2’  ЉˆN® (€œ„R(G@ c™2~€§yÚµ¬•ZàX ¸¤% 8“K!Vv¥ýòÙ°E–ïtVkeßÀûó%ûåÓéŠÌÖGvh»¤îo¹wÆãXÎåÏ¿â|Kd¿ì¹Û³+H‹|õ= .$ÀRˆsz/Ђçm½)XnYÑ‚%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:49-07:00ä[å%tEXtdate:modify2010-01-11T09:46:49-07:00•¤Y2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-sy.png0000664000175100017510000000157212370216245030135 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœxIDATXÃ핽JA…¿;;I »(C*!¥ ïá3¥ì±³ñ„TiE;“BA±‚Id%‰»;×&–;QAÆb Ûœ9óÝX¨Xr»{ÀbÌvP€âuzÀ-?C˜WÿÀJ½@^NÏu­iõ]kü…_Ô9õE)Ê[6'±DƬRµÔ@ái¾`³ÖD/ŠA„²³pé„‹Ç+FÓgÒ|‰ ¥~Hó%£é3W<¤.Ã÷†w Çógwކ—úÜÏÆk«ÜÏÆú /9»0žÏ¼#ðtš[´ 5‰ˆm¸µjiÙ„¸ElëÔ$¢ÕHè4·Öì€jiI™ÜLžxÏ—DbØowIì†70Í\Ož(ÔÛ{í.5‰Ê²,ó.k¡ŠC¡_ý_CU%C®ŽHü7l¯×ó·hêßåßßkíwsÿD?)ìOü_PXï€NC„¨Tépˆ ý­4ö%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:49-07:00ä[å%tEXtdate:modify2010-01-11T09:46:49-07:00•¤Y2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-im.png0000664000175100017510000000165012370216245030104 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœ¦IDATXÃí”AkA†Ÿovv7&©±)¨hˆÑ¢`±ô"ôäÉ“'OÞü]þ¯‚'o âÕK@¡Ô¶RÓ’6ÍšÌîÎx‰Ôã÷a3ÌûðÎ0PQñ¿#¿V7KÐÀFÙ¯Ê(µUfx~÷wv`ãŸ5qî|OFtæl%˜0@›‚€Yg GJcïlŠ© Hˆg,:N.@áäÖtnt{DwZÔ´GíÅäðу›Ì¯vXéïqåçå²U‘ù Tj©'Ì1|Ù¥þ¶O£w—t{ë‡èÛ[´¦ÂåÁ8sx®¨'èw}‚H0ò;¡žlá‚€¤wæçoèy^ö§•ëªjg‚¹×Cž?E Á©C?ÞÆFÇÈ`"yŽÌÑÀ«„ézÑ|ù÷¯Ý¢=‹ðÇg .X@9h~üNt½‹¹¿ŽìåÒþ|«r‡CÁ(ž°òú=ÉtÂh³‹ Tîê 7€Þøù´Ck2Cbù«ÇxqR4{9q/}.°³ô)K <+[ Ô***þm­‡Ö&Y%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:47-07:00´dg¸%tEXtdate:modify2010-01-11T09:46:47-07:00Å9ß2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-gd.png0000664000175100017510000000350312370216245030070 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœAIDATXÃí–Ëo\WÇ?¿sïÏË3qÆãGlœ;ˆw…"!P‘*D!T”€T©¨› ©ìÙÁ†€ v¬ ”%¢R!„ ”¤ÐRñ¨š{b=ñÌØž÷½÷üXÜñ<üJº&¿Ý9¿ó;ç{¾¿'<”ÿw‘[ù•ÓO(˜”b[rt?®Ø®À!µI*¶ytÿ°¸@ü´á¾Ð®;x(nÎ.ÔÚu€X:D¼!° nðkḆ8Y½/€žvÀ›±¤|ü²!Ø5Cêâ}¤@·ä€=P@b) 3cé®;G™;Àw+;®T﬒{ÜgïÁ[4ÚwâJæR€¿e[‚H ¾hÉ~Ö§zÝйÓßóÏ8Ä7«Ä\‹öGÁd”`_ pg‡a/ºÙVŒ?¤Z& ØLFñæ"·I?z!ØÜnt^nåW…¿_Ȱö…8O,Ýc9Ý$f,Ve`|èØŸbî°¥g ï6R¼²z–ÅßvùÄí}ˆ(ÅâüÈ|€ëÝW ežšÛæBº…g,ªÂé¡tTQ|k¸ÝHrucšwf¸m’¼û/Ÿdí» ‚©Ðö ÞÎñN5͵õ_[ØâɹmSm\ш‘#J ÂZ3ɵi~±^äfm’Fà’öƒ>“ È€!jDi¿ßžâfm’—KÓ|c±Ìg+œ›èàEõ˜üÖèÇ¡ÖZÜØ,ð³µþRÍÑð]Ñ#fãD¥ÿ@äwÛS¼Y›äêÝi¾¾X扙{]šÐYuH,…89¥ÜNðJù,?_›áõ{yj~ÿz9ÙîðÂb²Ã‡fܪfYm$±Uë¹\ß,ðúNŽÇ 5žÍoð©×ö‘­¾mn>žá§µ9þPÉSëy ßWFÀùt‹ï_|—·«¾÷¯‹ÜnNŒøj=_mLÓý›Ãrå?œ¿ÜàÎ?ymÓSÃLy°p–ºÖ¡]vÈÝ ˜r{'…=!ØÄq!Ø•AMx¿2ïì¦ùÁÆÙÙ‰ñO“?©õ>]¨óÍ• ¦Þè±s5j#SéñÜ¥fÏò§JŽ=ß}`e¯çrµ:ÆŠNÖ ¹4UçÊB™Ë³æ“좡õï(“Cž9³Ác­*¿Þ,ðâú oìäØ œ÷ÇŒ¤¨ I7äÑü.WÊ<9Wa)ÕÆí&3eÉ~ÆŽ.¦Ú<¡Äç‹;\Ûˆ€¼Y›¤8'f‚{ôq!é„|<·ÇÓç¶øÊ¹-ΧÚxýÒ¬Åè˜ûTG”åL“ï,·ùò\…—KE^*y«ž¥:ĞY ÷,Ëgwyz~‹¯Îo±œmïÿØrÿáâ@,‚ë(+“M^Ȭry¾Â/ïyén‘µÊ£Õ>#Ì=¾%%¾”©ða$6-ÝM‡N”+‡Ž2ÞŒŽk¹ýùe‰ßfÏejüæ^Ù ÇAMŒº!ÐKœ3J £.ÖÄ=£$?ÐyÏ¡w× ö%©†4ÿá ½!ˆØ¼%ñHHëm— :dN:¾CXb;î‚XÇB ü‘iA±$&-Ý–C°j†ûIÅ}4º$,¹Ãˆç#›fMðWÍØ@â 8f .ðã1ÚFD‚ªP5Fo[z4ðk ÈHÆu× õWcUA §ÆŽÜʯLœ¬Û…nÓàyŠ›‰a…n=BV‚†àûBz”ŽoNø¼CcÜ(Š‚²,±mûÀ=c ÆI²ÐxµB*,KÝwVk €RêÀ{„1Fâÿõ ø.0wgÁCÇ$I‚ëºÌÌÌ Ä=~:KˆF]*NxÔEç1ö)&iŸj­ƒSm|â‚$Iˆ¢Çq˜™™AJyc¾hŒAÁp8dssc ËËË!Ðù˜Ñ`×m2IöYûû¯©7WˆF7§&ÉÞî~…fûa’x?8„ãÖèõz¤iÊáÇi·ÛÓ§!ÊãŽF#/I|ßçúõëôû}<ÏãNyhríý× ˆ©V ®~ð6ó³>É8#NÆèè}6º{ï°³>K”¤œ;ÿý»²,' C666°,‹²,˜EEQd¶··I’Û¶ ù¹9¢pƒ[Û»ÌÔžÅqëxÁïýág,/ØL&i*Ð…¡,“qL–ÂÞUvz ‹'^À(Ë‚ý[—I¢æç¡×Ûgssónô¶m£ƒa2¨T*(eáW÷úû» ³óßf~ñ,®7Oïâ»!Jl…]b+ƒ­ yQ KÅÃç–ÍpÿL¢W j`ÛgBÐï÷)Š‚Z­F¿ßG ‡C¡µ&MS‚  Z­’zó<“$gØ#Z4_ Ù>J¸³C3ð©TÕF‹‰+rZÉ&Ϩ¸Mš³Gö?¤·óÈÓg)Œ‹mÛ!èõz8ŽCǨ(ŠÐZS–%J)<Ï#Ï3d­ÉLã"yv†þàƒñ„Jûœ²ƒ±2Æä2@X’x<Á &ZR÷Wèj¨ò µÚ 8î Šáp@µZ%Ë2ʲ¤( ’$A)¥LQ¸®‹eY(¥(Š­5ž äQ<–øù›7÷ê¸êq®\?‚Ö%µÖð݈lQae~‡F-#[ xåÅÇp=‰ã¸ÄqŒ1¥ZkÇÁ²,„ÈN§C½^§Z­EÑ]Œã˜ñx ŠRQè+­×ydñuвG”iN/¿ËãÇÿ„#ÂqΉùßñðÂ/‘f¼°ow@FÇäyŽ‚0 ±m›z½>í‚¥¥%Â0$MSz½Ýn—ååe‚ À²,Œ1EÁX Ê²Š”²Ò¡06Ѹ‚’Y颱‰&ÊrI3­s@bŒ¹û¯n·ËÞÞív›¹¹9Z­J)…R Çqh·ÛÄqLE4 *• Zk&éû÷ÙÞ:kÉû”Éx/9‰k§d½169‰ãÚ‡(í˜ô‚F.F)­5I’¦)ÍfÏóPJM;îNëµÛmlÛÆ²,¶m“ç­52Ûã™~‚zwy[• ) —–(]—™µulc¦Ã…ü!÷;? ׇ0F ¥ ^¯†!žçÑh4ð<ï®ã8A°±±Á7hµZ”eI8êRõêønʱɇÌí}„0L—[gŠ  såoTŒaÐlaW(UoâûóÛÛÛø¾ÏÒÒÒ' ”eI·Û¥ÛíÞ‚4¡'—†¼pé¹È•k'h„()„E8\ Lfš°ƒ ƒ¤,$ÁéCœ¨ZÄ÷(&}Rëë3ƒmÛôz=ÖÖÖ‚`ª„Ãá­­-lÛfuu¥“IÎÜÂ3äù.J5¹öòE~Uü•ºzwZÚáúàYá±òÄe<;"+»ñ.>ó$_=™£ó8³úCÃxœpêÔ)®^½Êîî.»»»,..Þ«ÕÕUªÕ*A°¾ög¤° ç#œ9eX9Ùa}£M„¤†¡Õ!CÑ&¦…¦ µÔæ‰ÇZ4š X N®1쯳rêi:aâûþ½ø¾wÁ3¾¦(ö™Lú(Uòlg߸p’¯¦»SàUFT¬1JÖHò€ZUñÃçN™ºŸ²Ôh¢äÍúäv·MƒüW?ðI‹T½9F½Kìl¾Guæ[ÌvGJ‹§ÎÙ|ï›ðê~OÇÿc œÌ³•¾È‹yé)§2 d4Ø ìÿÌ6^ý%¤°tD÷¡œDçÏ®â8³H9ýЭÀË_³i×^ûí£|tý(¹9Tá•çg¹øå Ú½@·A(ç©8Ç©7¾„ø”bÚ¶æmàÉOo”åt@I©(Ë’ñxLÇXR"¥âÚ–à7—Kâ1<ý˜Å£ÇÁ’yžã¸.¾çM•´,°”}P¬ŸMàâ8f†DaH)%~­FQh²Ü ¥Â±§®7 CÆiJ½Ù¤ÕjQ­Vi4<’8â²,Ù¹y“øÖ-’7è¿õùæ&JM-¸ë(*ö4ßR)Ê~Ÿý7ß$^_'"v¶¶È²ìPú@ư×í²ýÎ;,;ÆÜÙ³tVV˜_Y¹KðŽ™•RÒpTYRZW.]¢²°ÀC++T*•ø)ðúùêòüyŽ­®R›Å’ë€bh-.RëtÈÒåû”JÝgêë³Ò óîÈå‰Éd‚ã8ÿ6ŸAO°Ýíb».Vëö úÏ0ˆ"†ûû,ÌÏÿô?ø'F­¸!Âv%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:45-07:00#ûv‘%tEXtdate:modify2010-01-11T09:46:45-07:00R¦Î-2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-ir.png0000664000175100017510000000172512370216245030114 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœÓIDATXÃí•1oA„¿Ù;GV\D"X(5'ÁÀ55âoEüþMR∂ÂX‚D ðí{)v}ø’ÅE ¿j4·;oöíÜlë/={û²¨úÝì}YOî?z^ÔÀÏå团Ìí°¤P²9@íîe <`îH‚Œ+ Ü €ã™OxÅkk:Þ ` ‹ anHB$\¿zü‚ZîŽaIÈÇ©TõD7”Ec D‹(7h=R) DôHÈxŧ¦>A}»üî’ÀÁ­ÏG$ò:¼]¿|M†Æc4ä%y’xR”Ò$A D Ò$|ƒØÅËSÚùçt4 aÿÞí3°Ip~ŸñëôíîОžàA ÷ŸÞ0¥Æó9ÕÞ^ÇÝZk“Mƒ¦a8™`‹¶X0œL4ÍFÔžŸ§ ˜A)!îž\ÒÎfàN}t„vvrè §î6ësM¯þq| U…[zÅzBÀcLß b„ªJ:fh…Û6a Úöæ÷¤“ùî°úxpà7¬pÞܹ6ËðŒu'ÆNÜÍúæ3ßáд÷vß}ÿ7PŸJx]Ò€¦%»ód`[Ûº oöûÍ Z%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:47-07:00´dg¸%tEXtdate:modify2010-01-11T09:46:47-07:00Å9ß2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-sz.png0000664000175100017510000000262312370216245030134 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœ‘IDATXÃí•ËoU‡¿;s=NâØÍ£y@¢&RR“@+RÄ&¢%*eÄ2]ðÐ5¬ûTElØVª¬ BH@Q² -(ˆš'ÆÍÛ4±ãGfœ!bˆZ¸[’RÞÿðógÙÿÌ&³…ÓaÆGZB‡«ðYØ… P ๅnÿÚ+‚ì÷_<%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:49-07:00ä[å%tEXtdate:modify2010-01-11T09:46:49-07:00•¤Y2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-iq.png0000664000175100017510000000171412370216245030111 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœÊIDATXÃí–Ën1†?{&™IÒmÔR$6°éŽÄ ñ ,«ˆ-kVl*—JÐ iÓÒJÒI3I&ñŒ‹*­L$$³È¿ôåøóñïcÃJŽ¥^oî:ð[®»xä@¹Ð.ÿ/|±Ö-@íáYjÆÌ1ËÍú{¸ô¸U8 °" ÕïÞ´Ò€æS"Rx/9ÂaÜf3¨r·²ñKŸKw’˜”z°F½\-s)ž&]>öÛdyÆÉ°ÃqÒaÆomÎQ|γÖ[ž}ÏÐLþ-@<ñªÓ¤Ôxñã3{_ö9ê·®ìÐL:¼éžÐÇ\œ1ÈÒBqý… OG|ºüλ^‹Ã¸MT˜”™p¯¶…±}3¦Ñܧ•ô¨øe¬' LÊN%B-¨ssøŸó´ù’Ð+±®cEØ#n‡0ʧ\š”q6EêA¨Ta­ðmÜçþú6¾š0ׄáàâŒÓaÝh‡;•›‡ÓÓW§WõÊ€b”M°…V ­4¡^˜`T£Ñ0ó2‹%‹§4%¥ÿ8fåA]·¾†QÍ­ u·øí.®dGrþ­|{Àž¸P8þ–¯´ÒOhš¿»Û ±%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:47-07:00´dg¸%tEXtdate:modify2010-01-11T09:46:47-07:00Å9ß2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-my.png0000664000175100017510000000221612370216245030123 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœŒIDATXÃí”ËOSAÅÓ{ñRZKy?£&Ø`(! âcáÚ…îdëÆÆ•KMܹ0Jb4eQP)”W4&ò2-ܾç~. Þ’taO2‹™Ì™s¾3ß ”PÂÿEïã?WŲ·Crãêi½ÊÝØ}BzA¹2`ÅdMÐÌÌßÙŽƒ$HÆÆÁãÚÀ£u)¡ªr“@y‚”Åf܇–ÃW–ű¶–Qs ”š‹¡Yηͱ¼UMd¥……õ&b /‚"«=¿¢ÁSSKåÐílMƒGq¥™¯¸ÒæÖ¥— ¿ëgl¦‹´6©;¥«õ ŠÅµ&V¢Ud\"Ú¶uüÕ¤mûZpA΀(Þ8׺߲´ÞÈÓ©^âi‹*ß—ÛÃÜì›àáëA†'ûøaû0LÃ(«©ŒÒ„ø­$ÁM¦>#ž¶@ oœž“K\E˜[mfl¶3o@&žÊ 2ª希 o ‘¶Ø²}47(34m`§Ê™_kfæ[+(˜_kÆNYy²“L’ŽDHVØ=CPÂV¢‚ç{êçjÇ&æÏOYŒNwóu£˜^>A4áË“=~ÞAüõŠš0çÜFÃg)34¡9ê1"«-|þ^ÏH¸Gim"» ˆRdc1ìÑ7ÄÊcˆ¸L NÙ©½‰¤ãï;™™?…¿<Áv²#îÁ¯õîŽ û^!µAK‚7®K°áâ6;Γƒ_Ù‚œ’ ~/lŸ/jˆïY¥õšÖÿjûÁ=Ç5§é¸½ü½2ј»Ë;"˜zc£˜ú˜VgWq Ø/FŠj@¥ÂE5 "…S˜bê—PB üC{ =«OvB%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:48-07:00B,Q%tEXtdate:modify2010-01-11T09:46:48-07:003q¯í2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-hr.png0000664000175100017510000000203512370216245030106 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœIDATXÃí”MOQ†ŸsgÚé'(•©&H‚UHJ.LüØ×¥~„Ä ?À-+’nܸ11qabWCLm„0"lëÌ\5†å½„¤ û,oNNžóæœ C†üïÈçÉÉ ¸@yÐ냰J@´"¥Ð¢AЈAƒ±0&R‡ù¿:¿Íá¼ÆŸUfË“¼}¶É÷?u>ÖvéôºcÛä@y<`º4Á—æ7za$ÿÌäÚ±[ÙÁ1_ìõµÓõv‹õÙeŠ…; :¾Mnš¶ö¶™)O²¹ø’ XBr®.ó&R·KŒòùpæù ó•iîÝ h÷»hZ%üFD¡B¹i›H5äèçúD„’Æ)ç…b8ôNP?‚ýˆ§Ç sm¨GÍ´?íY©VÖF¸$ýãóIÌ–ÆÐ Šë×ø¸êb °eà½m€s›·²®¿`“̽Gø›%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:48-07:00B,Q%tEXtdate:modify2010-01-11T09:46:48-07:003q¯í2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-de.png0000664000175100017510000000116712370216245030072 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœuIDATXÃíÖ± €@DÑY™DLÅ‚,Q ¬ÄÌlF×2þ; Ü㘽=©R’z°Ò€$ èÈà Iža@p =Á7`ôP%ÄöÈâZØ)ˆ<á1dwa%Äf 9_m$ žý”ÚƒnP©ü{â§½ ÌÊ%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:46-07:00l %tEXtdate:modify2010-01-11T09:46:46-07:00cNÔ°2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-ck.png0000664000175100017510000000326212370216245030075 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœ°IDATXÃí”KlTe†Ÿÿ\f¦×éL§wZ ´@QîD´£ ÆDcÄK êF7FMÜhÜ·lÝ‚ cCH4 ¢à­j¡@ -mi Ó–N™Ó¹õrærÎù]Ì”RЉÖîì»9É9ÿÉû|ï÷ý,iIÿw‰Ð‡‡»wq䃵1J …šky'ü•=ÄÑŸ†R²,Ï‹kóxÙ#R¹ŒC§b\ Æ@ˆh%u•ë"åtô14)‘×¼ƒÀrŽfèž.fZ™FIQí`aæZÇ…Á/«…›p’ëùñÏŒÇL¤œë.„Àçóðp•γå&þúF.{ʘºÒ—Ã[`ï_²×í÷°«Ñ˻۫hnÚ‰s!¼Å*‚¢Í+ x¼Jðèj/îÚj¾Žë´´Ž0:>='~EÜ. ÔT02–@©´3§2Ð5®{4üiGâã<_áã±×¶‹¡÷Û€àÀ&yµu˘µuüСëÚ(ù™$Uº”ÄïËçé}MŒS¬^Y @ïà8ZNvcD¦æ‹Ž'JI6b—ªm£ä¹‘–…ÙÕ@^ã*„¢€Û…åHR) ¤?­óÖp€þ”†Û¥²©© Ÿ×ÚUú#Œ†'¨*+¢q¥Ÿž~ƒhÜäbwˆTÚwÐ MCqiJƒãÌæ¤k i8f ©ªÙ $³}—àqk4o[A2•áØ‰NâIÒ€+ú-Ú:Gxî‰ûñ¸5®¤Ò ~"½Åyl__Íî&?yCA‚7 ÌÒ2üÇ¿$ñC¯â¯(¡txc,ÊÏöp†áˆÉ™Ëal ;·ÖávitôŒqW«êªJذ¦‚TÚâ×ö SfeÒUÀ} ålt'¹yæŸ}ÛË›§Ç9v1Š­(ØBåèÙ¼~¤/¦JJÙè6©7 bc1RiGgÇæZ ó] ‡âóÌs3ŠS˜ïbÇæZòÜ:HÐ^ÙP„g´ŸSç'ùfÈ¢=l‘0-¼þB®%u‚¡ߟÑvi˜íjØ¿µ†m[¼hv?½c6¦íÐÖ9Â@0ŠãÜÃ='Ç‘\è%>™Ä²³-ÖÞþôÛ!ìèL$í,ª€³]W¬ì!‰$–0ùî—k´vŒPéÏÇš°ˆ¤aUM{w6Ð2ÙÅÕãoW‚”Pæ+`ï·bÄI´ž„Ì] +׬ì#>!>3£éÌl#D"I"af AȘàtk?©Œ…®«d,ûžº®’ÊXœní'dL€eA Lä`rÿÆI¤„ý{š¨ änÈÝåCe €ý{š2û€Š× @˜Ç£i Ò’bŠ"ˆÅ“·¿©Bи¢”µõeDãIz¯‘éì üWó\qt÷…‰ÆLÞxéAªË‹X^í%š«ÒWì¡®º„ú:?‡?ÿPx)fàÞ“ ·ž+—®²¢¦—¦òÔ¾&ÆŒI*…?ÙMÚ²¹>»½ -¥36½ª¦o™Ý„.]åæ­ lËeîÐi@×bB lG24š˜û^0Ï|à™E¸ÓðhñXÒ’–ô/õ ši„…þ%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:45-07:00#ûv‘%tEXtdate:modify2010-01-11T09:46:45-07:00R¦Î-2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-ma.png0000664000175100017510000000165212370216245030076 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœ¨IDATXÃ픿K[QÇ?ç¼—¬A#‘ íÖAhqï$®"ÅÍÁÍÁ?Ä?¡úÜ+G;ì`‚y$¡OcÎqxŠîMm/‚ßér﹜Ïù /J,9X^I ó©öR줔šÒùó` °tÇ ç¸áÿ@€稥-*¿ñ©;9à>NqP‡nîœÕ³šÓÍõê ° QjØÇ8i8ƒA NëFÀýyåíØ0殌w¥Ð Œ-@î /jðµ#ÜL ;±Âáœq˜gd™°ù ò²ú’‰ š(ëC§uîì/À…ÂÇK‡OX*>Œ”$¸ Á%h¸°:FLøÒ¾5®Ö X á<ÀÃé×…š;?g«ËšC¿®ñ{=j (~4…ÙLÙî Û½ê|Ò Ÿëè ôÔx=t¶FÊû2àÍñýÕ„ž mË¢ä`y%j•]bLÚþ8Ö®™<~Se*ò‡e³äÕ|÷šj{àÝ?xJåÿdŸSì¦(R¼(¹nÈäˆÔlm«%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:47-07:00´dg¸%tEXtdate:modify2010-01-11T09:46:47-07:00Å9ß2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-ba.png0000664000175100017510000000176212370216245030065 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœðIDATXÃí–½OaÇ?ÏÝÙ‚Z-@€JBŒ ÚÁ‚ à[B˜ˆ3Nnêê⿉qWG‰!á-1i”…¥èâ Ð#Ø0`MiS°×ëwW^ ÑÒ«Þ1h¿Û/—{îó|îyùA=õüï¾àøaaYe®^nãá½kÌ„U"Ÿâ \Ryúà-Û·Á5 nX‚±É[<›ºŽUá]¸rP”Y‘èøQ‰T:Çù3Û´6e÷ŸÖ`' ðæ d´Óa•|Á` ÔIBËY^e8Cvá1 „`ã»Æë¹Ï öx|¿Ÿù…s¼˜ÝÂ×P ¿'Žä0À/ãwL~hE¾%2¬ÄRhºÉ¦ÞËóù–¢,· I‚µõ-&^}Ä0-ž<ºI£ÿ6c“C|ˆv8 QÑhqÇDˉ'2¬|M¢éÉ\ÈqNÊDÕ5嶉ªn›°½«Ü2aÀ-5Ÿ+N›¨À¶ aïîøã“µª‰²`ïs  ª µcÂ%€ßšXûibbn„HôBÅ>àp"¾àø—¿…ðzd¼^…}Fïy·¸Š– ã‘uf#=˜Ç4$wÈå 2Ù§O14Ø…Kóò}mþ4Ç53 °ì€$ <ò^Ë’Jç(• :[tšÏê¬'šœøD=õü£ÙòÝAͬe*%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:45-07:00#ûv‘%tEXtdate:modify2010-01-11T09:46:45-07:00R¦Î-2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-ar.png0000664000175100017510000000143612370216245030103 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœIDATXÃí•=NÃ@…¿±w¤ÄEÄ))(ÝÓp nÀ ¸ 7€67 K¥ -•ñ§Ç^ ‰v×H#Ÿ´ÍJ3ûí›·Zè¥,¹¼¹Sˆ´0À¹6À•6À¾&€zz€ŽÒ®p™³“ƒ BçWµ1È!Ÿ»ÚyWÕåû»· à0ã;:„(öwÀƾèŽòã‘â~A‘¯¦öè›Lñ‰ñ%vuEùš³ÍWDO ¶À`rŒMȯ¥7@ãAsKißDÑ’AÅ ’”½YFÑî g6I‘€ t af< ¡Ì—› ï~ëšÛõsXesò7Np‡ þð¡[9ÿ/øxѸиÖPÏ@/u}ÙH8?o¿'%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:45-07:00#ûv‘%tEXtdate:modify2010-01-11T09:46:45-07:00R¦Î-2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-lu.png0000664000175100017510000000120512370216245030113 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœƒIDATXÃíÓÑ A „ቸbŽ-à¬ÂV¬Â쮟|Ø'QиWÆ¿`¦ù)óï±¶à’fp!Ö–ô$-à tr?®`QëôÞ; ÀG˜¼ãGì´±_à·ûsB2²~€&À%]iÀ™¼H@&³¡ìŒû%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:47-07:00´dg¸%tEXtdate:modify2010-01-11T09:46:47-07:00Å9ß2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-fi.png0000664000175100017510000000162212370216245030074 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœIDATXÃí•¿/aÆ?ßó¶ÕV¥ 1VCc!›`»‰XL£X VYlVƒ°I°Zü¤"4î´\{÷êW¥½£wÉIôn¸<ïû<ï÷û|ßZøï­µ'áàä’å=®ò 4Í$ÙZff|(°ty I'cÒ™nô†L*Žaàúg2Þ¶½®«yx,©Û{‹w劃ãêÊ› j`Ò‹ © Ú¶FU«\vÐÏþVá_¯I¸y!ãïz9“@Ñû„z0KŬ¢ëÖ6^Vɦ`>£†Bæ×vî "äï-ŽÎ®±ŠåB$bmŒ ÷ÑÛ < ÂȺÿõêÒª¦›R"Ÿ%~•”úw@(—’ZšË5ÖáæÎdÿøóÉþ a\1‘ëg 'x ÔæJã§@€Ã³kNÏó˜ÖKµïÒí1gsL.‚ʤ➄TBa| œÉ„¢ÃgíOàBýå[ó?²×0d´ (`7j Q(Di …^SvãIŸÔ%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:46-07:00l %tEXtdate:modify2010-01-11T09:46:46-07:00cNÔ°2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-gg.png0000664000175100017510000000215212370216245030072 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœhIDATXÃí–±kAÆof/¹w^r… „tÚå/°´±·lE€ BDDÛ€•½¥¥U:mCÒy F¸Üš=s·ó,f—ܚܑE-òààvggÞ÷ÞûÞ›N훨jÐÝËȽâÇ»÷ R¾Tæ¯]¥õà6r¶t^t "‚µ2 E‹¦ð<,ˆæC[|ùj&h>t(„H€›aþA†µ¨s(¨Dd tˆbÒñÁj_@”˜³’`çeÌò˜ôÖ>ùÆB`âÍDí*÷ÙBªªÿ_„'2>À¸DL!ãˆLx’k'àö² ÈuðFã£k£1nùQÀ‡dpÿéL‡(¾¾Up££ÍO¾á*G*Œ6?’­¿€F£|X= ,~Y1œ÷Zmj›[4¶wQýš‰Y*ã4Ûˆ1&‚N³Y*Ó©™þØ{ûX•ª'‡V¥Š½·ï@·Þd`ó{Úÿ‡}L·Þô@ˆ?kþˆ¡O±œ&Œº}¼šLËþÈåÒýÚ –9ÏÜ•KDSIDh²vö!Ñðv¸§ ð$H¡”òÞ²S2þLÁë'V…·ÆN€±%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:47-07:00´dg¸%tEXtdate:modify2010-01-11T09:46:47-07:00Å9ß2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-gm.png0000664000175100017510000000123112370216245030075 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœ—IDATXÃíÕ± ƒ0„á³õä&i@L@‘‚˜${P0 tˆ)c¤O‘1¨SYÂ0Ɵ·Àû|ö“¥8îSBI èhÀäà¹æe븑T%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:46-07:00l %tEXtdate:modify2010-01-11T09:46:46-07:00cNÔ°2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-lk.png0000664000175100017510000000250712370216245030107 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœEIDATXÃí–[o#E…¿êé{Æv.Nœ¬,BBHh…iÿŽwø< !¤<¢ ´Eɲ$q|Yßf<ÓÅÃØÎš(+眷‘ªªO:Ý5p{üß!ºÈœÑ:Ž•[äÜ—׳ÀÎÜÝ8ÎÞEë@ Vá«~bHœÌˆpÐÙ$aÔõ@Douæ•’‚ç;la™Ùùòh‰Ý³«ìŸK‡'ôfB; ùëdž­€~+¸Ý¹ 6p”k1Kõ¯|‰Mœ°{òÅ+r„(1䉌 hÞ=¤ÃŽOܳ|W#M¼©¢“ЛW…µí.¥Ú9Ó,5XÐiç/@ä_Ùc8'œìU ª`Œb¬#åß2ö“ˆb‹Í„46  ­€ƒo7xðA‘—ì$r3ûY¡wQ ×0Fñ£Œp5!éZ¢jÂòk}œP¡\2lû´N"º’®¥ßôé7Öß{üG?‹è”pPJ).(oļõIƒ¨“ ýøâC>ÛëÀQ„·"¤µœ[1_n¬1A^:4§l$œ=Ή+´Á# žøâ¢±^$ÉŤqUׄQÉ¡ˆ}â€>™(¨:õw[œV2ÜÉ>•Ç;1Ó"‚BpÁ¿4ÓrNP±¦Sð{&,-orÛp§!¨&%®/59ìŸà¼#1½ñç¯FH=Ûh£.i{-5 %ë0® Í™ú Á(Eb"n4V¨%)ïmÞäöÚg çQ €‰ø çƒ<»‚ðÿêÅ WôŒã$1DâØòPäzæPá=½ñðœø|Ûi&†Î*:NÑnš×*d+q`’éý%27ø¬”öÔ•Çö¡ÆHîXË…?"·ˆkà9€ÖžFâ©÷]kI¬$§n1è¢÷ýSÊÕM†ã içi¼ØNÿÍ;EÑUˆÉÈï‘”Ú襹¼Á¢\h€¯.šà…Q7A¯OXYí£cÏà8¥H ÈbL`€Ï/‘@6Œè<ªaRF'1áæ‚2xN`ðì¥ÚxD„€‰="‹‹áëzåõ7;ssžkHò”%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:49-07:00ä[å%tEXtdate:modify2010-01-11T09:46:49-07:00•¤Y2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-al.png0000664000175100017510000000217312370216245030074 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœyIDATXÃí—ÍjAÇÕݳ;³›˜,*(ŠqA“ƒÉÉCÀƒoáSø>¯ Ü…œb Ê¢!æ‹M²»3Ó]f6 ‘Éf`ú?õ@Uϯú_5ð¯KÖ;Ý©8ÀLàÍ4d½Ó=™ö $Ó¨ä¿\X› ‰ãk¹$窸R)ZÞ@8VÏzš:ư<#óbi‹EQUÀ¨ðÕØ 9Om̆²šáQ^ÇÞ ÷±¯3,Ú˜Ï~Èmãxfã›HYÉ–Oé…œ>ã–±ô|Êû´À‰Ø³¿BÎ@÷LQ¿^±åg@z>c5ë³åGtm“µôˆµôˆ®m²åG¬f}z>#TÝ´ªÁ"«²‘Ùö;!àCÚgG= ‚Ø2§FpªÅ‘4ð]Ïêü2b±¨‚“¸Š*[£(`äòÊŒZÆVU%'B$B¥…‹ü5ó±-Š˜H'5Zà(,ˆ1Kܧ±l¸š4H NfÉýé­»>Åž¥b›lêK”-›W'Zì^ð±ž-°º¶Ë˜iƒ†­ƒŽ=õ§¢¼>Ù¦Ô sëHoZ=û€âÅëtWApØÔ;pÎ(r%!˜ +ÚÅL)ÐZ£W'xm¢ÅqµÍ ß?°±ûh…}µâ¶ ßíIêVˆëç*Œ4Ž)a#„€¨¬“°¶¹w0ÊÍl„Ÿ,·Ÿû$Ðr?dQ. ‹9§Îˆ8U(Sóñmj˜´!×xT}ÂÜï7ØÖ°Q츣Ì)Áp³ƒ‹ kÉ5"§?à€3‰xg°°¤ug: @©GƒÈ`ÃÈÀ ü¡‚4ñÊIŒ?ÃÎð7·E†&~¨®%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:48-07:00B,Q%tEXtdate:modify2010-01-11T09:46:48-07:003q¯í2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-qa.png0000664000175100017510000000151212370216245030075 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœHIDATXÃí–¿.Q‡çεþíŠ µ¨•ÞÂxÏÀC Q*Ð ‰šn …†béØÁffDzfîO1£œ1›œ5Í|í=™ùî¹çœ{ŠŠŠ’‘ã­ìE¾ýóS\Ý\bµ±„¹úê Å>Ö:8ÃÑÎ^!"jö3øXËÖ@¢}{_4›®Ûy‡Þ¯SÑÉñݼ’¨ÏLsj~–^­&@¨+ F¹ŽpQ„ø;èÒ´èaŠ9G¸(FÑzQbP,¾b"…\‡!@I1*¶ÿ Ã¥ØH2Õ‡@1‚Ž ]YHŽžŽ@YmhŒÀXOõøÅÒ1ÈÝ=c-½ËdšÅ`¿ÂÞzæjzuß:±ÿôêâ~_?c‰Ã¿‚W–·žÑ¾¾C/U›Ážlng'à$¥óÆ’€×©Nr%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:48-07:00B,Q%tEXtdate:modify2010-01-11T09:46:48-07:003q¯í2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-mf.png0000664000175100017510000000132412370216245030077 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœÒIDATXÃíÖ½mAÄñÿ[n qDL ¤4àpn€˜*e‰&ˆ¨‰ [;øÈŽ]§MÞH—=~šK<•cãé*{$ÁûÛ˜ÅÇ„á "©¥ÍÐñÌy¹â{½³lwÓ 6Ê„X¤tµPpÿò€íîòY²Àþ7H¯Cì%bmÕf¨‰"„¤"Àé’fù?2ÔDˆýç·±W4ýP²SyÝíZEëþQÛIŠ]Åp€àT4>»|ÕÌk5žêùº99ˆt ÚŽ%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:47-07:00´dg¸%tEXtdate:modify2010-01-11T09:46:47-07:00Å9ß2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-vc.png0000664000175100017510000000205612370216246030111 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœ,IDATXÃí•»NQ†¿Ù+‘Ùh¹-¸ @H‘ò4@¤(/@•&u*Ê(y šä h!- ¢¥‹‚Ä%8öcbv×gR°DŠÆ»rÃ_Ξ3óí?stàIC–ða÷î/*¼ ø²´Î|PèJl¡|Kžññäß“½sŸŒÝ—D1*ÒUKŒ ý"( (F-$‡¹ï¬¬ßk ÏÝßö¤ÿK ; PWÕª4ºvO€w½¹V†o§%Z®‘!$X¹/wï{$Ý6âaÐ¡ê  €ô¹ö(]:£œg’>Ï<:£t Þ”ÂÊYæ±V›c;Ž0a;ŽX«Íq–yXÎýa§5ÁæÅ Í*ljÏqâ³Ñ¬²y1ÃNkS°}ÐÌ\¶âiê©Ç~;d÷rœÝËqöÛ!õÔc+ž¦™¹…œB´®(ˆb‹’æ=·ó5W«àô퀡²Ö¨º×,TbZÆ¡e*1U÷š•°Fh§…¦ ‚²4x;öƒ·Ã×8àuð“yÿŠå  =Þ¾€›!œrV£ClQöÚ!{í[”Õè)')<„…¸%žõ:œ¦#Ä]€Ót„Y¯ÓãÍûOðŰXi¹ ‘›°Xiâ‹)\¼”ps%_ ÞuÈc)ñ÷¥ 0é$¼Ÿ<‚<6e•¸ua)hüËÊ¡œsØåþðyà,|6Àå0ž4tý¡b‹ÂE¦&%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:49-07:00ä[å%tEXtdate:modify2010-01-11T09:46:49-07:00•¤Y2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-ky.png0000664000175100017510000000302712370216245030122 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœIDATXÃí”ËoTUÇ?çÞsçÙi§)--´ ˆÐ )bm¡(*`4ÄѨ¨1!¸qcpáÿMܘ`tÉBCŒÄDQ "…¯ V ”> Ì”B;3vÞû8. ´ã”` †…ýìnrÏ9Ÿß÷wÎæ™çÿŽ{ÚSÏòéÑkìýä8ÑH¡ëìØº„Ýéïø0°…}ß £EsƒŸ×Öøx}aŒDÃRv~‘àüPsÁ¶E56Ó;p–hdP(¥Wü¨ lF%ú2A²É,ZqÍ©º£dïÏýû›ðòjwNf-G Hä@Í<„ÔÖøèn3ؾ(K¸ýþ4šÉ?{g{N:G{Ù¸ªŽ÷žXLÏêõ|}"BuP‡ìõX7=+<ݦèYÂÓÖÊ7.¾:<ÂØxæ6ñ Ê«ù‡@¸¥‘KI]Þ`Cjœ—[Ãléî&1Cîµ@À+]!<÷i]ÚH¡e?œž ¯ï2>3‡GBq–„ݬ\á,Μ·•f×;ݳI)!pi  ÍëEY&¹?zð¶·#távcÚŠbÁD0œs±û\#Ã9WÙ¦ndûs^vlDj:¾”Ó(åT&0Õc”B¸ 4Ý@‹(Ûž¶tiàäó(M‚&nÜÊÙñt®È8ý8€_÷3’\€¸ÅùAÕfªkü¬[Û¦Õõx.02t•B¸‰à—Ÿ‚ø›ïR·0L]ô<ñ+1~»&ù=jÏׯ€éx5MÒd… "üáX Ó°ˆz5Ƴ³¤*éh¤ÓŸ#zøÇzã¼$X¹ÊÍ[B‚€}ßr!vmÑj 3}™Éb‚3c% E«<~ žôñ¼5„,Ì’"…A¡ú!å1È]5¸GÏrè§mNZ¤ò5¡4C9€Hd’#'£üúËEÖ­meÛú%<ÜBÚ縵¹jN¿¡kx›â¯Ï tŸ)-\ñZ³*ËC»TÉtˆY.Òyû¦aM•‹“ ®U‘Ì”n>§ê Æú*¬TšèDž’3% p{\¼ôÆ]C¸êqÌ,–e³ÿ@šGú+[ÐЀr»d¦D’©Û=Õãë¥&ó¤&s7¾§«—R££Á¤EŽÓWô ‘Ʋ Jc ×ë\‰9¨mИ3•ç³Iã lî¼HKý2&'ض›å ~^Ü8ÈÛÏÔå Ì] Gƒ‚/@ÄTxâ§»øÉ¢’×uØ.¶S>¶ìRs<¯)ÁjImP£ý¾"‹K4aÐ?ýƒŠdÊ&™²ÊZpWf¢ë[ ” Pppn1¸îj fbÛŠlîöµIàÜ%ñoÀö{-pO˜gžyþ\D£û-$×%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:47-07:00´dg¸%tEXtdate:modify2010-01-11T09:46:47-07:00Å9ß2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-ai.png0000664000175100017510000000275412370216245030076 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœêIDATXÃí”MLuÆÿ™agwùZز,´@m ÑZMU5Æx¨£Ñ¤Õ˜èÁ“WŒoÆcc<´êÁ&Z?ŒJ…bÊBË–] » û ÌÎÌÎìßôZMkÓƒ<·Ùyç}yÞç]ØÒ–þïéw?@<~ÎÌóáçC\NŠÊáGzycñ,ïw plh)%áŽô…8ÒhRèØÎkß§˜JåP„¸)-Ôå#Î%ÆH¤–AJt¿ºi±í¸$K&çMÁŠD©ÕnÉm|ìâŠÃû¶#¬ûùñÌrE)åµ")%R¢¡ Eƒ<–´ÞÕÇD #~öÖÞù³{4wŽƒ{Úxs_”Á½Q¾MÒÔ䃌gkc½ÎÁÍ<Õ®3¸§ ½»“oÊ’×Èä×nÚ~mÛŽI]c©ãár‘ç#-<ñÊ Ålmz¼po§JOw³»›â¦.&©¯ZèªÀ®"xÆyî]õðo<Áõ¬büÐKÞ7BàSªë üHÇ¡2 л¡ûpj˪"€DUá­´NÂV^ Â- ô:j5ÉŽÎ0HÉübET,›\a•uÛE[·h„¦¡ø4¤eÃúpÕiM£V1‘ªæMZßežŒqô™¨5›y„æ#cqUOŽÿÊg_ o\Á{Ñûhn ²ÿžnÛÛŽ?•dn.‹¹­–ã'Iþè‹„"-„Ssä²F .g—+Ìç òK €}ÍþPcý±N´ÔïØ‰Q´Ž>v¶µRîäËï‚7pk«¾îŽÒï«rù§aNÏ,q2cëuyU(;=ÍtÉæé}ÝhÑ¿–¦`˜È®aV® [^B.LC}ê˜ñ_ Ù<„/÷·á_˜ãÔH‰“óc9“b¥JSK³¶×:•)rj4ÉÈø%èïáÐ@ûšÑÜ8²+¤6@Ȫ‰ÒЊSLã–³ˆ:·¼´9ÀÛŸÆv\rRcÅr &Q M-2éèä—Q”Êßþ|žßÆçho©ÇY5(ØrØV!„ª¡¨ª¿µ}•ÆL+”l¸-^v®üà%ûj·’aSÂ[¶}%åÞËr¹B©l n8+ÉØLšOÿ(l ¦®"3+¨Fc¶ÄØLúÊq®;Lÿݯoç›”ªëè±N×.jŠ÷—®H-9‹59‰kYWð_p-‹J<Ž´]œöNoHfjâòºá·@bz_fÁ{.‘UgÓÚÛ «ryùë”Ûðo¥“wà¹; pGØÒ–¶ôH©­sªÈæL%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:44-07:00…Œ}%%tEXtdate:modify2010-01-11T09:46:44-07:00ôÑÅ™2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-md.png0000664000175100017510000000167712370216245030110 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœ½IDATXÃ핽nA…¿ïή½11A8ü¥£" %EºAB‚šáè‘xJÒ€xD‡H(ŠDÉ'ëYïÎ\ ;8Îøt#ÍÜûÝ3g40×\ÿ»<­µíþÝ<|ð˜n–#r|5É‡ÚØgÔß+GÀõ&ˆ€'M4ê€n²ù?(Þƒµ ç&kU#pRz@û[ÀÛw)Ëç=ËÆ( ×ó³P l[ÏÛ$t3Ü^¾ŠH3ÇíQðDa@Q(>2t?.&%¢`o”’^Q9KxaÀ ¾*ò"¦•.R­ q•¦ú˜·JŠ1´ãYÄ‘0ôïú úgä]òopË|!j…5`¡ g»%Æn“‹J:½´$Š€À¿c„õ5Ëîö˜7;ŽÌ8V¯îÓ_ñ´´ .,a¤ ܼQ²{Y3’’ijºVrnIФœ±ZÕKž;›C´ž@µ~¿8RÖáø¯¹î0Óž¶ù‘¯§/3À½¦~: ² )%l Ào¹õÅ$^§œÀ ×sàW àNeô¹æú¡ï¬RˆT‘IÌ%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:47-07:00´dg¸%tEXtdate:modify2010-01-11T09:46:47-07:00Å9ß2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-bh.png0000664000175100017510000000213512370216245030067 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœ[IDATXÃí•MOQ†Ÿ;Ú¢àGŒJ ÆÄ­ W®táŸñøCÜ»@] qabŒ1,- `ø0„Jùn±ítf:mgzg® Üv@sÃFÞí¹“ûœ÷¼wœé—PJu-FmŸÊó7T†^#«Â4Aè0TW€f ;óE¸ó3¢÷æmÌkÀèqàI·¢’¡hLN›ÕW£¢‘ŸEZ6BúlJ©0®5<Ú…"Ü,îDo~‘вµ˜€wÀè;Ϲ»wè¹~óÊed¥FÓ²µÁŒ­FŠ`{7;“™¤µðà ¬5±* iolbÇËÏ!k(ÀЛØv”ï”i}[ÆÉäp2Y:¥ÃS R)’7@†ÈZæÒÊ€&“ˆÖê:ö‡Ï8c9Ú뺣5±/@EаîàïìÓ9(¹D‘¶Ëá жCûÇn&‹õî#þæ–6ŒcOH˜ÉD2‰HÿÉß(þ†!ÞìÖÈ{Ü/S;û¨ Ð ÛŽ@`¤S$.õ“èïÃH%µî8I8úøÅ]ܱIªÃ£´V×O/ªÓAV-üŸEÚ…"¡íhu >Râfg¨¾¡‘ÿŠüU;ê\ãb„aº5Hßý{D¾O{yN¹‚’RÀ‰2€Rûe܉<•¡aš‹+Ò.ˆ¼&þÖ©yÜñÁöžöuü´kãaˆ7·@õÅîIJZûã›ÞuÜÛ­Öm SzûŒ$i’fB»­®té4>À_Z£³WBBëåg:ÀoLåL„š. 5%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:45-07:00#ûv‘%tEXtdate:modify2010-01-11T09:46:45-07:00R¦Î-2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-sr.png0000664000175100017510000000163512370216245030126 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœ›IDATXÃí–±NÛP†¿s}cHB¢P"D)+C¶.l<+R #oÁ°S•n]Ù ­ØP@¡ŠqÛ¹‡¡2ú& »ð–}ÎwŸóÛð®À:kA,0`?4ÀvH²9€5ˆØÝÜÉCH6.ÆA}/&~úy‚ÜüþøebfWÒËÚä¸dè±  ê@b¥þù€ä| Í1O·@ù¹¶ˆ”oo•ÊâSuØæ˜ÆF€áŸ:EßâÒˆü6F‹ò5­—_F©®imu™YQig,w®ý¡wÒ&ïVžm(WÒ§¿f†ûÓ&½“680U‡™uà ÷cûÓ&šùe›wº$"9›#ïÆ¸¡Á¥†¼3øÕÀ%‘o9,ê„*Ä+)šÃÍá2Ì­÷‰?¥w|ÀF­¦ß‹"UÿãÉE€ìz€©¢5Ðòï@úß~z‘DŠŽåÿaåÅ5ßZIžN‘cÓK¾íMů@g-èç8ü ¾{ó¡vC<„xWp=l…zÈj—Š%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:49-07:00ä[å%tEXtdate:modify2010-01-11T09:46:49-07:00•¤Y2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-jo.png0000664000175100017510000000201412370216245030102 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœ IDATXÃ핽OSQÆ﹇ÞÞ¶|ôÁÄȈÁFRGâ‚›þþ5ŽŽ.®$°0šB 1¨1&ãBª`[½÷ž×¡¥P0Ѥ—2Øg¼Ãy~ïsŸ÷h ÿ^O3Ìz)äŠü훨9ÿ)Ñ«xè¾Dذ碾ƒH5?§‡.b3j°S ëÔ4îˆlåçÔ¨iL5¬·@¢:îòAd+?×ñ@³ÕYëC"]çANY ÙÑ_Ú |ÅÐäp.œ.Òùê"ÞÖ…woǹÊìxDÀ¹žl7Žà çÀâïGh¦d,ã¡1öõG“›`tù&Ù¥E†J0&¹LÚ§øx32Ìþ³çÄߎZ“žMG[,»W¦ôä¹J±^ ¨‚*®Ñ@<¿µ.©›óBLÚ1¸f³ÓQ¼bž\¥ÌØò²K‹Øñ"Òã/°ç?¸F³vZÂýŒáÝôˆûy!ÎV°%_^ÁçÞ·áÏk¨ µÀPL±6ã³}=­a_It »è¬]ư9Õ2®N¦¨„°)IßHÀ(8ÃöÄë3>Õ©9õÓ6bÂï¶uÒžøŒq-mГ8.YvûZjwu6ÍÆtн¬wnâ>¼œVVo¤ ‡"í›qàÖ^¸û¶dùP°I–{ úgýSq×[}}÷ö%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:47-07:00´dg¸%tEXtdate:modify2010-01-11T09:46:47-07:00Å9ß2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-cm.png0000664000175100017510000000153612370216245030101 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœ\IDATXÃí–±JA†¿¹[BRßE°³Ÿ@ð  ÂWð¬ìÓYÚ )lÒ(BԠə۱¸K4Å‘Ù#1(÷Ç,ÌÍ|;³» TÚ°„ó#“ãáý#g74J“BÔTvN>hï' Ëã: e„…“ùÍ.–V)û¤¹Q¼7< ±.+æÉ-ð@l­€©T„µ@­q#còµ©øã‚ý¯ ¿hµ®§ÖõùÍ/à‚ ÄM%ÞR¶÷†½雎$$ `öSGéLhí~fë¶ò|]ÏÞ…d1îLjq0îÇ$ƒrÝ «@¾Aõ0}ž®ê@f«_ôYÀ÷;Çè6Ë5´ôm(àa:”yR?‘Òåß)° `Eª6à°?ž³£fñk\\ ¥|Ï„K‡ÒS ©ŽåÖ§É/ÇJÿV_W:`9%bµ%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:45-07:00#ûv‘%tEXtdate:modify2010-01-11T09:46:45-07:00R¦Î-2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-gr.png0000664000175100017510000000205512370216245030107 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœ+IDATXÃí–¿KAÇ?3;s§^â²Ü%¨ Fäz ¤Kåu6’?Áë˜ÂF$µÝ56!¥’FPÒØL!rÈ%E0ÅÅã\I²âî¤X]÷.Á d—m|0żYö}ßç½7»po)›€•ÈV3??Åêê3...©VwØßÿÈÄ(àQ·Óó´ô<­4¼‰:¤Ò¶³ª¯ÏÐBð“ð²Ë'LSbš!ö. ñBQ€èñLxžÏ÷3;û„LÆŒS@4#Ö·{¶A°&'-ÖÖžS,Ä'`||¨#`¡Ða”’”JƒŒŽ!¥Dkmgi·]”Šo*ÄÁÁ×0e­Á²26öÏÓ4-ÎÏ]„ªP¯§VûH»ý‹Þ•ûGår¡Ã!¥Ä0†VX!Žãr|ÜäôÔ Eý7åå÷š™™•Ê®ë±µõ‰““RÁLÓ —{îc åJ¤ 5•ÊS66^à8—,.¾coïóu¶š¹¹q67+”J蘦Qù]×Ì틃‰Vq³ùƒÝÝ–•‰ÀcèûÑ1„££&KK;F|S FFr‘ì},+ƒ”ÃØv–ááBÈësúÛÛõŽ&,™žÎsuåsxø³³Ÿ±uü_ø¾þ㮿ñq“  Ö×?$ 'Ó|ø7ÿNår)]F+UÂqÜt,,¼MW¼JôŸ¯—)µ”PM[@;M÷–ºý9ãÄÿ£WÝ%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:46-07:00l %tEXtdate:modify2010-01-11T09:46:46-07:00cNÔ°2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-ca.png0000664000175100017510000000167012370216245030064 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœ¶IDATXÃ픽NQ…?6kø 1TÒP`áÖØQ;BgâKø<!44šPÑZðT«…i„ ŽÅ×DvÁPÀI&»wîüœ{næÂì=d™YbÛˆˆ?³m­±¤‡ X»ÀîvMÀ¿Ž£ßTÊw ÃWÖû;ŒFP«©Fêó©€wt»ÐnC³éúŠEÈåþ™€ˆžt8„z^_Õ_¯ÃÅÌf`šl™ÀÛ<>ê·ß‡d  t?‘ÀÛ[H§!†óó-`:…jîïa2|æs7f>‡F:… P€Je-%ÖSàèHOØëéºÕ‚w¿×Se¦S]_^jÎÖ®`<Öû µÉ¢Ñ³™û êz<^«ôê1“(—áú¢Ñ¿c£Q)—5Gd5ѰßͲDl[¾à8"77"‘ÈÏØHD÷Ç·m­±¤‡·1<=…R žž~ß/•4Ƽ?DÙ¬ND(ÏÏêËdt:âqÏ弈ÅÔ^^tÔ’IÏeüøÃPÛ&ðà;ûìÌÓ³û+ßÙÇÇ5ß\Åœo¨Âì7>-#û èºF¤%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:45-07:00#ûv‘%tEXtdate:modify2010-01-11T09:46:45-07:00R¦Î-2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-mo.png0000664000175100017510000000215412370216245030112 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœjIDATXÃíÔËNSAÇñh©ô¦RB¹)1‚x!¬Ä…qåŠ Æ·Ð•Wn}£&n4‘D5V®¥–ÒÓrÚùôrÆ F7l­1ü6“L2™Ïüÿ™?§ÍÜ»ÝV€ DÛ xØnÀL;J;/ÿ'êQú„älÈà« .ÅßÄ;*ø…Ĭ©ÜìÝàñJ’Z£*º«µ0ÜeÓí¯ñ:áÅv€JÆâ&¥ªÚ:@P­ת¤ÊA>b=\ ¶ºÌ»¢Y§?è WüX5_s1­ÊdÌàe6 J·&®1se €ÁH”¯žg03x[7°mkÌê=hþšª1‰Ó×½?D"qBšF¥fV×(8^ó[Ђ\îa²oˆ‚mâ?~°O(LN „˜ßZcn3EÕuš’ó§z¹cšñD³âR­×Sƒç¸~f”ÖÁR6ÍݧOx³¹â÷_³á ä-“ CçRo?ýážôЭ=†¢q¡`8†NÞ2›Ü!(ÚO?¿§îIFâ§©xu–²›Œ'úÑ)=Çó/‹m«¡×ª(96 ™5–s[”]›ÕÂþ ú˜Ëp¢#€[«Rrl3ì: ™u|ŠÂPô$!­“ ‰$ ·Ve­˜g!³Î®c5àIÉ·²ÁÜFвëp1‘$Ž6 ,fÓ|ØN³³g"‘ÍH$9³D~ïó[«„´NÌŠƒéºxÒk¸÷G ’’ëPr샽ŸÖ–~ÁüiT8DÃZxÔnÀvŸ›Çùó3ÿòÚ=”\Ç%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:48-07:00B,Q%tEXtdate:modify2010-01-11T09:46:48-07:003q¯í2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-lt.png0000664000175100017510000000121512370216245030113 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœ‹IDATXÃíÔ± Â0…ágsR ¢pÏ Ù' ¤`‰,À"ž‚Ž H•Ä‚XŒñ[²ß÷éN烙ÚãöP€I:Ñ€‰¸=†LoÀ‘O/`=€d÷÷™ xmÆØ–Ðzú‰e×çÂú9±€\{ À~ÝPÀÚiDǯ>$ ¥åJ½SG%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:47-07:00´dg¸%tEXtdate:modify2010-01-11T09:46:47-07:00Å9ß2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-dz.png0000664000175100017510000000222412370216245030112 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœ’IDATXÃí–»kSaÆß¹%±—$­iz³—D”V…Úª EœDÝç. \\Šÿn.âà$è"è .m‡@-j‘.ö’^Ò¦mšœ|¯ƒ­ ÓÉwêeè³8Ï÷þxÞ÷|ç…}ýc©Î‡ŒŒ"B¦ùOnŒÑ—Î8¶e'M,e apæ×óMŒZ„d¬Aü0N©R¾eä¡Rõ>˜«©LO±ÌŒkîAêG ÂÄKŠÞU›¡ü¼~ÏfÿÞ‘œ¦xÍ@5(àø¢Åõi—¡9‹H´Œ]ž¤0“'’í¢nxÈán°ƒw60Ànñ{ãÇmÞwTÈkäþÈmZÚ2ø…utq“jq;Þ°Ç KŠëÓ.'l&Z«<:U&ҭЩ8vsíû8ÉF¬X´¦Î*SPœùf³åo²>3IA¶+lMLQ|ûŽå§¯ð–Qž[@à´-’%X‰ 3 ,×ÁŸË3ÿì••ʱHܼ„×ÕV°a qì'0W¯Y‰BSI‘YµÈµTѧõ é#lä>¿z¯§ãÏÌÄ…ñ¶*×>9\þâKù¨´Kìô êÓY"ƒ}Xž‹”+5ÍA0µˆðòh…ž‚b`Þæî¤G.&X‹ªÎ*zc ~ ¯»»›³©± //Ö _’GÇ–lf5‰Ï ø¿¢×ŠDz;q[S°¦ìÁTJ3ÛX¦w†ì£çOï?ñw®â]¢B.­ÙNǽ2Ì–ŒÉ1€ég(€¨Ÿb¨,Ì=®ð®BlD¿ôÚ|%‹ºÞs£Áµ!ìRšn8xÇÄ("$bqQa×òª®®˜hÑajïëÿÐwŠÞu™I¼%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:46-07:00l %tEXtdate:modify2010-01-11T09:46:46-07:00cNÔ°2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-gl.png0000664000175100017510000000221512370216245030077 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœ‹IDATXÃí–=LSQÇ÷õõ,b• 1‘ÉÄÂà,NŒnή2;8šg Atñ#1PEZ•€!6´¥Ú÷úñz¯CJ(ôµ`ÞÂ?9Û}çüιïÞƒ39,¡”r@êžÀ ÓÒIN”•Êå°"q¬È&ÒÌ Õúp7_ÄÕx¡ÛJQ%€RdWH¼'96M.¼†LgÑj|x®µR××Íùþ^|†15¿{²D‡J¦áïí¢õñ¾”D¶"q¢/F0 …V¯ %©ñbC£ä;§`|’š€”å="ʲØy?I:´|reå1gƒä"›…Ëò¡dÃë˜ó?+Ð3ß‹¨ÈLkkoG{E‰„¦aE6I—.qð…=î¹Pçý£ „ÇMÃÝ~ênß*\½D”%I¼úÀÖè;”´¿\õLèWñ€î"ŸHâíhG¸\¶IÃÄŠÄH/,íRÛÛ š`?4ÈKŒÙ V$^ÑäÂë˜ó‹…âšÆÁ¼GGI˜³E.°¡‚ >‘-U¼}>‚øVpÂqÊKR3Ć_’O$+pÝ÷\yTâO”ìÊ*îÖô–F„ûðgC¦L¶ßN²ñdóËŠ ówÓ¢À{ý*õý=ø{ºp·]FóyfšÌr˜äØ4Û¯ÇÈþ^«ª¸ @)„[Goj@oj@ÔxQFšÜz”|,²¬ª¿„öv!ö⟽ ´ÿÎèØY5Bœ¨ËrCÿ%sN$œ8“ãú /,à¬#¯¼%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:46-07:00l %tEXtdate:modify2010-01-11T09:46:46-07:00cNÔ°2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-pr.png0000664000175100017510000000225712370216245030124 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœ­IDATXÃí—ËOQ‡¿{gÚÊËÚXQ0b$)1hˆh>âBàÂÄhØøßø˜ˆ ……Wn „¸!h”ˆ‰&Ф<¤ò(•Giçq]L)Ô”„i7œÕ̽ÉÜïœó»çœ+°‰¡#õ„—ǰQÐË“ó~?Š¿€Uˆt†Ÿ½x2Ù¥êâãv¾·'Õ¥ÅÕyMÓÂ{©%€¼%DÐWE(1ËÍh?"=„ãc²6ò Aë²ã¬h¶IÍêZgÞÒ6ÓÇéõ tÛ@!ò°m©ÈJpaù#÷aîT¯Pp” yÉà,¼&×ëàQ³—æóþ2âØ/–¶L Á‰ ¤­QçáU/õ§$^Ýåø‹Å>˜‹)ÇS<¨­ÒèhöÐÖ衺R¢ÉýPÎa×Â:5!ÉË)[û¥E‚Ƴ/ÛÜ8¡<µÞÚ›P3Á,ò j*%GK÷®èœ9¦]RüŽÙüŒÚ,®*°šP Œ™|þfÐ’ˆÐé¦!6J™¹²'ˆ €jKžÞòÒP­áó ‚~AϰÁÔ`ʉŽ`SŸ,$=ôÒÈhyˆ»É^:'žJÎíZœ™,®§ï>˜ô2‘|:|Ÿ¶y5”b.¦p«déÙ°– ƒ_LV6 e( +}ÿ7ÒÏAŸAKb”öùnÖG) JU»æÌa‰šju~EmbkŠ‹5ãS6Só¶à‚³¤M‚a:ïšæœkšî]ìØ lk+Ü–R NV¸WˆvøTºû¶—b…¿$ `ì_)Îð_3ò¬PñGÀXs¡mìÔŽG 6\lÇ:ŠÐútÎÄqÚ½ùH1rdùš õ¶é¾®‚¥_‹ªüç3Ëõy_y<”˜-ØÉÜþÎ 6ˆ+Õ%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:48-07:00B,Q%tEXtdate:modify2010-01-11T09:46:48-07:003q¯í2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-na.png0000664000175100017510000000276612370216245030106 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœôIDATXÃí•ML\U†Ÿsïf˜; 0üthi D@¥¦5 -Ô"MšZITb•ؤkWî—®tcBD›ÔDSµ%šÔRLÓ–R£F(ªS° ÂÀ\îü–9Ç?Ãc¡e¢‹~»›ùîyŸï>çËÀ£úKP2{§K…×Ã;oäˆßAèí÷Hþ6 š¶P˜5€9‰5#Šä™‡C(MC,¨€÷³5½#×Á¡ÆšËÜšÖÝ£34,t+Œ©68¶éáJQâ3y¾¡šŽ:¥Ý_cŸë…©„Ri­ÆÊw MâÐ%W+êdNj$¥Xw°¡ë¬E×›Pâ'ï…X=µæqc6ì!r´‰¯¶Xt.=”ëLe ­ø“‚œŠ­¸^ne¨©’Îp?ú =¤ëÌðÁòÉõ/¾W۸ݶ‹w‡>ãâëH)Ah›¼à­¥')qV•“ßq„Þàe.ܺºtGVÂìÔ£@Å$'‚ä¡cºò 'ç²þ¨þõ§3^0vâ%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:48-07:00B,Q%tEXtdate:modify2010-01-11T09:46:48-07:003q¯í2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-cz.png0000664000175100017510000000205112370216245030107 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœ'IDATXÃí–MoQ…ŸËÌ´¢@ú‰M°tatc\hÒÀ¦ Óׯ¸ôW~ƒ ·®º÷wFbšh+ ’HmZ´Ìh‡ t˜ë‚B0fš–2à¢gwW÷yÏ9÷Í…SXâÓ» bÑ 8RŽ@ÆÃʘ‚´š#PŸ¿þüìѽ[\™B:#X}µñ°\mòøþmnÄfÐTe¨JköN:[Üe½PBQ|\žá׆à%ÓŽ”ìèÞ~Ü¢dT˜ ˜ P|b‰´„X}²_wy_(1¦*\œ röŒ·n(þX"Ý9!hIII¯É~c»l29ÏDèŠÏç=@ÇZ}Ÿlñë…ïžvã€^7 ;z…Œ‡Ýpèu£Ó…Ú€»q(@¯­ƒ—ÒÛÈÜáŧÇZRJTUáæµ(O¯³Ÿ@;„z|d´m¬µ5Êo^²­ýFóA¿KüXAȶX07Ié9æjŽÓ¢Ñ÷üG€*æ,ƒzžs“m!pÂýp(@ÛVA°U'±WdÅÈ3_ÓQ¥l_>¹´§–Ä­2+zž¤Y$h×ÑwÞGhg]ïf· Té ljW€NÖqë')=÷WÖ^}Uºò ëä^‘e²vèd=o•Yö0kW€ˆmq×Ü’^gí °d|y‘ÒsòR³‚3¤©{%2ÓWƒÑF•ªª uò®¿4¿´#¹üTÿ…þ8•+;×ð%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:46-07:00l %tEXtdate:modify2010-01-11T09:46:46-07:00cNÔ°2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-kr.png0000664000175100017510000000324512370216245030115 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœ£IDATXÃí–ËOTgÆgÎáÌ…Ë Œ038ŒXK›‘qJê D¢… êPÒ¤«n»hšÿ“®º°¦]›Iƒ1.&¨AÍ`P êLqÊEæÂœ¹]­„áÒ.:]ø,Nr¾Ûó|ïû~ïûÂ{”’¢¬À\n üXnŽ&·Ý#IÒ¿:ü0û äl¡PàÁƒȲL[[ƒá‘§Ói¦¦¦( tvv"ËòžJbff†7n`4 ‡Ãtwwãp8Ðétû‹E LLL iuuu¸Ýî’ëKž–H$!™L‰D¸uë~¿Ÿl6{àͳÙ,~¿Ÿ±±1Ðëõ<}ú”T*u8 äóyn߾ͳgÏ$ UUÉçóx<ôzýæš·1´Ù92o–@€ÞiÃøñq”Z3z½ÇÃää$•••är9ÆÇÇQU•þþ~EÙ_Àêê*>DQr¹BzzzhooG’“!–~%>$¿¶ŽPaµPs¾Û•KT}z’3gÎH$„ÃaEabb‚³gÏb³ÙvðÉCCCC;d™††b±ñx»ÝÎàà µµµ$?çõ7×Xû%@nù-"E¤3äV×I…fI¿˜ÇtòÆ&f‹…{wï’Édp»Ý ÐÔÔDEEÅ’(‘ ‹Å"Ñh”@ @KK >Ÿìz‚ùï¾gíçQ(aëiI€„!@'SÿùE\W¿B¶Ô yùò%ÝÝÝØíö’\RÀ6r¹Š¢ I³ÁY~ûò[,Ïg`ëIIÀ†NáwÕ„¦Sp¤“¸ŽÛhùá*Õm!Èçó»n½o ¼‹íx±²ÁtJâ¼N‡Ì¦æ˜¬2bqq§Æ¦“ù(cpc…co–6JÒ¾ä øËL@J'ã·8k븳 R:™;5F,.â² @´Ú@½dà3‚õ0$à]8mVm®%ó4Ò¤¶L¿¡S¶l´ùýÃÞH¾©qóÿ.(™ˆŠÅ"‘H„ááa‚Á BÜÍõœ÷}Àª±’Ǧ:f æ-ò-ež7Ö]!ƒ ‰D(K—œ]Ð4ééiÆÆÆ˜åÈ‘#=z”ÆÆF¾hçÅëîMÍS(ÿ®"[ä]mÍ\¹ØÙRÉòò27oÞ$‡éë룵µ£Ñ¸ƒoWX[[ãúõë„ÃaTUEÓ4’É$^¯§½Ï ; Hld0é+h²›¹ÔÓÊ×Wºñµ:ÉårÜ¿Ÿ••âñ8‹‹‹,,,púôiªªªö·€Õj¥££ƒùùyš››I&“ŒãõzéêꢽÕÉ g¿Î/³°Ài3ãn®§ÎlBÁ£GÅåráõz™››£³³«uwhî ( .\`zzšW¯^‘N§Ñëõ„B!|>ƒ:³‰®OŽ•ôi&“! ¡iOž<ÁårqîÜ9z{{wÕ=ƒ°ººšË—/£( ôööÒßߪª„í¢Ó×ׇÝn'‹qêÔ)L&SÉõ{fÂÿª!){Kö¿hJËÞ–—“ÿ=Ê?=JqÉâ%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:47-07:00´dg¸%tEXtdate:modify2010-01-11T09:46:47-07:00Å9ß2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-sm.png0000664000175100017510000000207312370216245030116 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœ9IDATXÃíÖÍOAÇñïì}a+--–@ÄH ñâ™ãÉÿ@þKÏœŒ &¾]Ô‚˜4”vK_è²mw§38袕ç<óÌg~»3øßKcHà~Ò l' HôXI.~¸6@CÆã09@ÛÛ¡Ýܹ@^eR8:£Õtùîn‚DJ0S^$•vþ  zLÝÝ@]ÂȰ¿ã“N?¡T®ü^€ÒŠƒV,=:fÐÝbœ|–ȲøPße!?Kq2»gì‹ÈÍžwÈ‹Úk*¶‡÷u/”¤¤¡`ÃTeg€GË«<^Y%%Sñ¨zÁÅJ!€ê:m„¨ñÎ_᣿„a)³ÇZã“þ2^ªwBJÆKA®?­Å¨Õ½nòÈÅY€ƒÁ"ÚIÙжõ3—çn‹fã%rËÈÄ9d±ª‹ž ´¢9Ò„ú-GAž¬Q”¬‡í€ýö õQu–1ÄÅ€cÎY‰Bö‹ì ˜ºsHOwFcÒ*ÅûVè#Å)cá`„\ü{Å<Ð ææË&îÙ™Â'2¶¤dÍÓ*æÈúÚ‘‰×6>ŒUBM<Ä¿•gî®Ãâ¸Ax0Mi2ÇÔô5?‡µ£ƒk÷— ”ȱÛ7t¾ YŠ£Îmr=ì>G‚¡žq¹çÅ%oÂóæ^(8ÑLvÁ FˆØ»¾àgiKþBºzýÝï jÒ€õ¤‰&pS?è¶üèuÐ>%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:49-07:00ä[å%tEXtdate:modify2010-01-11T09:46:49-07:00•¤Y2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-ro.png0000664000175100017510000000131712370216245030117 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœÍIDATXÃí–Á ÂPDß&Q,Ä*¬D´°Å lÃ,Â<‹/B²9DÍŒŠ ;‡Ã°ó2¹ ¸~,a¼L»æ“ëéžaÿŠª´]£¼ÇÍ€Ó®’>€‘V›˜ø«dKõ£ú=‹B^yK@ryj˜™¾_(ná–J ·6`ªŠn¿@­w3cø×äàààHl¶H÷…cñ‹õn¶¦`¥ Ã(¥Ù„ÉQº°j½tã&ÞXA:Ìò³Åèú[Uƒ+IÖp%%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:48-07:00B,Q%tEXtdate:modify2010-01-11T09:46:48-07:003q¯í2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-et.png0000664000175100017510000000173112370216245030107 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœ×IDATXÃí•ÏkA†ŸÙÝi6»IHIª !Tm<BQâ½H=ëÝ?É‹wõâ](Eð*Òi%±5?6k6³ã¡µˆx˜Ýöà¾0‡ù˜yç™o¾™\¹þw ÞÊÀ.g ð$k€Ì3Rú¯¾H  SÌ€]Y:êGcP!i¼œJA%XUã0õšÄõ,”ÎšÙø+VÿÅ`‹ùÉX#×GÏ›‰¸_¯ò,|Þ2ÜoXh>…gÑAM÷1×Kï“eàþÚ3R¡*Ÿ7{ë”Y^øLÓÝCRÌøbŸÁª®swå-{‚Öf5á˜n_hèGUÚAƒ%9 åí2R>W¼]”´§ úQ•Š51.Ë4U¿ µôfu†ÊÇ&ÆF1œûô¢¥“]'9S ¦­&iù~R`¢Š8B!…b{Lã-¿CMû!À _Œi%Š`‹¶Õà£X!Îqƒ-dW1Å5öÝ;«‰nA„ûÚ%ž6oÓ©Ÿ Ñï²¹ó‚kƒHæIìû7/&~>„ÐŒ¤Ç[`1RŽãÊÿSNšT#(GåYpLtKã•ú/H»à¿¶Oos:€{Ydš\¹rýSÿ˜¤?Ëm%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:46-07:00l %tEXtdate:modify2010-01-11T09:46:46-07:00cNÔ°2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-fk.png0000664000175100017510000000305212370216245030075 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœ(IDATXÃí”ÛoeÆsÚí¶ÛÓnéni¡ÄÒ€("-Ô€QÔîÐxLLˆþpá^½Çè%7Ä£‰"‡@ $ÊA(…¶´…RÚm·ÛíN·{˜ÙÓç…PX¶^X0\ØßÝ̼ó=Ï<ïû,±Äÿ)þåAä×ßá»3 }{–Ø¸Ž¤(|ôæjögðMõnÿ6‚ðÍ‘*>Þ\É'M3è‘5ì;¢sóv e@­kkY?m¦w¸Øx¡” — Ýb WG~.\Aö‚•€Ú{að‡åø°3‚—Û™îatÝñ°:H’D}m%m{[ò4¬{žëZ3ÆÙ¾Ç3pð¼·~g¬—WÛC|ñÚ º6mççsãÔÔ)ÿ;Öêj?]ÏUóV› «=LE[+¿$}üxò.ñéÜñ‹+o“Ú°2Êh…JÈÔØ‘™æýÖvwv¢ÇgP9 Áa*ž-Òº&JaåZN÷$£Ò6¨P¡øÐ¾ `(Š‚@m’’ã€5 +àêdºÉŽU5¸ž ÎÇå… «Y-È+ë£l¬2ˆì¦»7űQ‰ í~>—Tà𯷚bÏŽ:Â6fÇHunÄ- E§´§’DÑu9úçu.ôåÈZ6~,»I*Ou_G-þ‰>Nü‘áØ-—+Ó¡6œå¶¡0>žæÔù—.Þaë–Völ_ÍËaT·Ÿ¡˜Ë”}¿§‚P@á½#(Æäô Žê êײ±¥‰#§úH JgàÀWç°lÇGÖtç{Û}%Á / @JN M¹ÃR:ŒH—ˆ8Òß¾ô'ˆÒúAÿͤ밴Xfsm€j­I½Ñ"zɺ7xýr¤™™`{kƒýU¦¦/¹;>§£Y¸ˆtµ^ARñ‹Ì•ǨøE¼‚|ÏÎvé7 !è…TkMüI YAÐ “ì¬W:ÐU!§g7\Ý>Po´éª0óðÁ@¬5÷mÅCG%¥äó|\æüY`7ÿ˜_6`±Xþ‚7}Oéº/¢%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:48-07:00B,Q%tEXtdate:modify2010-01-11T09:46:48-07:003q¯í2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-pa.png0000664000175100017510000000200512370216245030072 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœIDATXÃí–;oA…¿Ù‡ëW'æá(J@ *¤TéhiàPÐ":J: øˆŠ‚žP"E$) 4Nd ó0²-¯wçRl$ð:ñ 69Íj¥½÷|÷ìì̱þ±”ˆ>|¤yï!á§&(eÔÃ*V8ŽÂu•²xbì.¨è[Ç‹[m%Ž9Àm›d£ÃÐê¤VÆ:¹ºÎ¡IŒé2^c[ïîõØÝëYt´þP»ñ~¿Çó·_¸uõ$—N¼‰šÄZxÕèðìÍgNªùÙ%0_òY[*r±š`m©À|ÉŸ€¨Íù<ºY ŸqІ_Ú䎂+µ÷À1Ö2óTï7G/Å]ˆ€ÖòA¥¼Û+P{®FŒ7"uùÁÖä§‘J_®¸<^X®˜Mo—€ çÏ]È™˜n¡ ’ÔÇ纛 çÒ÷óì 9F:kdÑÝܦ»¹ £ƒ…:*)hØjóãåk¾¿ØHî›-J××ñOÿåRä–‹È ¤¿Ó ¿Ó@!n¹8»œBžìjÊkdWë©ë`*ˆY©S½ÅÉb±WL@)2gŽô¨À¯Œ­½œï<5)Ô¾«ˆ¬ªeÿ®I¡ˆ0ø¢,̼XËW3ÐÚÊûXÿ‡~°Ôœ>̨ip%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:48-07:00B,Q%tEXtdate:modify2010-01-11T09:46:48-07:003q¯í2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-ge.png0000664000175100017510000000230212370216245030065 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœÀIDATXÃí–¿K#AÇ?³Ù‚à/V ÆTba#ÆF,´QHge!ˆˆ€Í‰ØY؉äþ…D°öÚHÀ"•)‰L$$1;W¼ËÝå2³zÜ]á–Ý™÷}ß÷æíÛOükh­ý_——èxÊËØ;¸l ß·j¥ Pض Ð(¥ß“øêÛÊu-ŠÅ…‚ú.H㺠À}€M'r·,c¨×¡Z•·zýÇŽúäÁTÛU«)ÎÎçç ×U†5^h]çºÂqv&œ_vÅÓÜÞÂÑ Àð0LL@o¯¿Ü¾¼@>''P.C$““ÐßZríyÉçáà²Y8?‡dîïý9±I&…#›Î|¾mY{b1ØØúú`m Ç¿ÇÛJžŸ…3ëBÀÈ$P(ˆ€¥%°ín\¶bpPlE@"áp@nnÊ÷nr®Twc¶ ++ 5„BFW6——æš„Z·çr??Aç\Î{½i¼9­£Qÿ¬Z…R  y$åQv‚Ò¦æña}œâc°‰Fý[ýÑ-¸¸ð¨Ž7ŠpŠEsØÛƒéißEh³°à¥RÐÓcžÿ5ÚPHœÏÏ·¯«Õ:~†æ¨T •‚ÓSx}mŸ7Ec{}ŽTJ8øpu™Œt¡!˜•=öƒRIþ™ŒtÂHææ¤Óvpwé4ÜÜH' ‡a|Ü¿€bŽáúZ2‘NÃØX&&`wåw¼µ££þœƒØloK •˰³#ÜonA?ÌÌÀúºœ¦¦EšTvú" -Ó„;‚¤ò` £á6°ÊÜ©ÿýøÿabý÷.®Û*ŒúK¦ç7ŒûKÊ*§˜M˜W9ˆz$À8¤ 0 ÔƒŸG€½HPiW¨ [4ª‚óí.£Írid5©±|­œÔX†Y€÷"’Çûg‡ÔXŽ;¯ À›5,Ö]k¼÷‡#'€ÂDÿöaË*wŠþ2‚¤˜MÚ›!¼:½eÕ,Ö].ïÎxYõü¯áÜå€ 4Ö|gÞXÃóªÇÓ¯œãȈ~~î |#@p€(C¡‚:+ÖZCZÇäeá%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:48-07:00B,Q%tEXtdate:modify2010-01-11T09:46:48-07:003q¯í2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-zw.png0000664000175100017510000000207212370216246030137 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœ8IDATXÃí–ÍOA‡ŸÙÝn›ÒŠbL+(„#îü 4!1xñæÕƒ^Œ‰‰‰7!AÔh"~ÐĈ†" ù¦E¡6hìBÛíîŽb‚oíz°ÏmNóÌ;¿÷"EþwÄÅ«4zpÂ)„P\Ðf—&ëRá$MÛý h-§ÛõN刧&Qü® cÛï'†¹;|“¨ýoiÖÕ«r¢‹Qú‡ÚQd7µå ¼:H·~/6Öט½‡šî¢áh”}Â+ìVÀ±Èmc‰cLÿd¹ªŒÄâmª¾¿%d™(¢p¹Òq¤ceÈÄ;0G»ØRÚvÕeÌ<è¤äÅc*-|ªB!*rËq™Â\}…^õ;f’K4á 5³}¸’ù•’}=8Ÿ£ì¹­¼¡ ŽL`Îã­Î¢5dl„täû_¢¹õÿýSþ(NƒRhC£€Ê®ùø·yï³w¸>6Ê_÷g $lÜ‚¸ÕAo÷~¯BÞ¾C®}ô¿N+¥„¼}—kc£L~áâ¾ ÷£X´zíÿF„0 ž<Ý EP­²òÕ7Ì^g׃¦4PvWÉÛ3ô÷ éÊ1QÇÀ@›”RŠ%²COù»U'e;xA±1 ª~•/nßàpzˆWúÎq«0Á²cS«»ˆükG{E84ãsb¼Nî^@´¢n™föüžËËŽÍÒêßôvï'Û•Ãó=b:ÆRyåÖØ7pöÛ/ýä±g1@‚R‚¢ åÔ•£²1’ñ¹®^\ßa¦x§!3ÛÉ‘©€ÝÅCÖ¬h¦î„‚°Xšg±4’v¤ÖÎ0óº‡â@sƒ>E©g a¤6aœJˆµ@~q ÕcˆŸÌu(ZzSÒˆwqN õH”VÁˆ;ô8'¿gýÕ&߈ÂÒ¥·%H¢Ì…M •5V¥öcûlßÝ… ¤ 8£\à¿ÛÕhöÓ?»3 Sýï’íÊÕLŽÂ΢ÏýÕ“|?áZð‡³YRµé€ç§<É à»‡xŽr-+€X?¼¿mæ–N¡qLrp"¿÷P•? « žKéÖI£EølŒ‚;,~à–‹] yǾÞbå4n¥LéöuÒÖÒz“4l3Ø«’Ö[\(·y¸ö ­$–PÀ§xs•¹;7ðW–P“â/Ÿ¡ùt¸ºÅ\¹ùo!¶0ôR ®Pô‚ÞÇ/Hà#3>ÝÍ4¿"©5†A¿JeQGî€b¢ÚÐ~»‰ä<4Ž1QT„(qùÜš…œíŒä– ´ßmÑÙØF‚òW.áó˜n„ˆ²xðþ2Y9âýáóט¨@üõ𦠂(tb—ÝFZßµp$‘FƒárôöM§7‚cÔdÌôrç{™E•¹ù”‹ õÀ±æ€t_™Sõ]á0-ݱ?`Æ‘½žúò¶jåÉÜ}“íGtl{­üd°ÿ´Ç€IÜ›4@u’SMõž»1´—w%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:49-07:00ä[å%tEXtdate:modify2010-01-11T09:46:49-07:00•¤Y2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-au.png0000664000175100017510000000302512370216245030102 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœIDATXÃí•MLeÇ3;³; »,„~$±‘Û¤ •UKmìÅC£iÒ´‡r0^ªñÒ‹‰1QO¼[/zé…›ôB µ¡h¥ Xš¶» K)°ŸììÎÌÎëa·t »BkâE~§IÞç}žÿû<ÿw^Øa‡ÿ;’ýåÄß}ŸÞß .ý0I(‡LÏ{»ø.q€Ï¼gøñ—e°õ{5>~Ýà|íó{›ù ÏÅÝû @z!ŠÔTצ×40qï6¡` äÍ‘‚Ъ`"YÓ)ËÌá°›_¸8€òpôQÿ.®Óã߇”lá·?B¬¬¦Bä«’û–$ª}*G›2œ«àimaJÝOrèÉ¿òéê¶¡t óUw#ïjáÊpo¥…´–;™×ëäX‹ƒ“M Žt#7µqùI%ý×VYXJM,Ëuu’ض(. ªq7ÓšL…žåx<ÌG/¥9á?@,ÁuÉ z:U|¯Ø4¼ÜH¤±™Á‰ÓÓKxÍ$š"ÈI\V¦pæL½½ã$“fQR¬«;'M’qËÕ6Áí˄ۓ¹¨ÖVpÈàÒ0³ §-¥<œ½û3)Ïú¸žât:8r¤€‘‘0†‘ÍÇlô‹Rh0œ 8Ȥ!kdSAQA×AVA–rñÿ€adå=ª*ãñ¨¬­™ƳÜÊ'ž³ø|‡÷püPUY‚÷Wˆíª§õçïAÀô¹ÏñÕVÑš"¶aðq7C-™„å`!I i¹ó¤ÓBjìß_ÅéÓ­\½:ÇØØâ3Qµ‚7Û¼t”¯¹6Nÿ¤Î•‡^^=hòµ¤€? ,ñçò*'ß®åXµFG"@2“f*ì"7€Û­pêT }}3¤RÖ†Ž˜f–h4EÁÎw |óã\1¸2§1:ï!ªgñVë̤Ê“üz#ÊØMWïáä[x£ó1jö>3!ó¦Zr²,¡i @œ‹'Èd6 T# S°h•×íõ¾UzÔØ1eÑäSAE¥›šÝ"ž ðÄ$cËH¸\¹d2Özû½^•ööZîÜYfiim“ %ø¶¤›Ê=NÖ’F‘ÕÍŽ.†ªÊÔÔ”³¼¬£ëÖ¦u¥Ø&E‘in®¢««€¡¡³³,«àfló÷kš6Á`¼d|Q² ~ÿ>.\h ›Ü»ÙVÁ íÍ×¢´Ø¢ÜnMs¬ÏQÓ¸Ý*†‘a»82uŒŽ.l¸û[ H$2 <À²r ’Hl¿xN€¿·n=.) ¤ UUFQrϲeÙ˜¦Íó°íǸ[lÁ4Ÿ¿h!¶-…âÏÎYøð…«lÉÖ7¥dvØa‡ÿŠ¿9°mÎÝg!« \™= à¸¬îÎÑÓý{+¡4·æv©ºf{£H¹íã06|ïI©Óîæ¸V¬°¾_ )u|ÏÂm;Àáäµ"[_óhßBÙý!]äõÆUÓw~˜N¹?©l gµ…Èwíð9ñœ4Áçë¿Ïþþ`LùeÊ3?¡<QÖKÆnÞPÉ {Î ãhÒ?4hÅF31êãñ¨2?¡,Ö”•в9h´"Pw@äÿ Ó#pÔ© ´"ØLŒz%#²0¡<ª)õ²Ñ¼bìÅ™BrAezúá®Á¨‡TuÆöÓ€fêåÑhFhqL©—•Íä¿+t˜@áÍ”Ü-O0ìÑ8®+s¤÷CtCP×§P9#²0‘;¯B ‚1¥ðY ÿW@º›IÑ ‡6…胾áh}c»™gé6¨ ìÅYàzÙÎ¥PØÏ&|Ã#y£}/$œôoz$1ÚßǸ!%þ¸CûÛ¿›õ²ÉÁ +¶„=¡¶ ³sÁ RšWŒV †õÀ•ÝtèºÃjše·ê°]Á? °Ù÷šâë&Ù÷ù6T×…‘õ€;ó­Èh&Ù©zXƒßÞ ™»‘ï0À¢á† I²±í hFN † Šçiyë*$8Ë¥ ƒ{®o0²6γÂp—€€©àŽp&%¼é ªŠ ))nH §=x° wb(1CºáTí\ÄvqµR…åJ¥ê8+åQÖJe¶Š í(ƾ¤Ðù)$÷vJüi›ý¯â¬À9ˆ?êÝê°÷ELºô®3±nÿŠÐŠólÖ®UX)°4<Áre”µk¶ ƒ´s*°îɰl|è ÃJn¶ƒ4‚š¢ë‚í~Å‘Þ ±g îŒ ös1&rˆèÙ÷@· ¨z¢wSü²£³ÒÒ<[ k¥n†Õ—Éðlô]ÅÇk¸S¤qJ ÷£—Ëð,„½Fy¶¥2+åQ–†Ç©Wj4JevŠ'gx‘À=ëW‡æ–_çÁØ$KÕü]®ÒL®ÒŠò˜H¦J7N þÂøyêöçwßÿ„…ñ)v ˆ*‘蠟Ú+ §$+Gìø¼ô/zÀáØj}núÏ?ðAÀÓ¡*»ù"ê\ÏÊèÞ·§¼µ é9ëfvxCÏæÔ7Û%.ñªâ_ÇÃéºdG%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:49-07:00ä[å%tEXtdate:modify2010-01-11T09:46:49-07:00•¤Y2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-kn.png0000664000175100017510000000303312370216245030104 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœIDATXÃí”]lSe‡Ÿ÷|ôœÓVšm-0A5cz10Ê,KœÃ"B‚d“] pɵ7\x+jD ÄxŒ TBb¼Ùbb “Hœû*0j?¶ö´ëúñzÁ-[ ›#zÁïòäüßÿsÞ§¿ÂÃüÇZ÷`N–‚Íe>YàÆPšÝǸ|5"9h€çdU¢YUW„ǣݡ€" ˜øôAì_î¶Ù1?$Œ‘¤ÖÖžýW0š+;ær±!$«Ü6-AžŠ†ÅÁÓ6­cD#YÈM}_cÊ¥Ì> ô Må]A‚—FøèÛ?u¥±“²èŒ6‹Bò‚Ûæ½Š Õ±0­q޶Ñw=WrN׿`¡žfsy”-®›„zâ|ý‹—ïVŽÂ’%>†‡oJ¥¦Ì=ñ˜Êúcöù®«caN}çXgЧWøÙ³o-vw`÷h“_Ÿin»~·"HõhˆÎ“6GOÑw­t¯–`M­>­ëü¯. ï:r%ÁWçñÝÙ$#q¾ùó‡Bd³S¯Ù"•æ &ÛÖXx‡L" ]Ë$Àt½nû!K틯Ӳséô8½½½œ8q¢à€‚^{MÆ4¸1ë’ÅzÃbãÂ…ìÝ»‡±±1öïß”ròÜ‚^ßÃuQ€µžQšËÂ< ôZQ5êêžcåÊ•(Š‚ßï§««›Àà4Ôê´¼iQç½?×Å"~½¸Xö_²ùò¸]ÐkEQ(//§²²’]»v14àÌ™Ób˜Wj£lm˜p}òþ\Ø·Í’íÆé*Þk¿5vì&•ž>>xËß[¼×3Ð5d:SâàÉ¥&ÛÖë4ÖøL"3w]êü¢ÿ*.KÜr}»×çMÂçôY¹ž€"àñE*Ío˜l}ÙÂ;dÊp»Aâ_¸.Í8v÷Ãòy ;79ٱєÚoFæÚS¦”[‹çp9€æUµ=È;—“ðì"wœx3ª¼ÚávŠæ–s¾@ËB$ÿAHe$áX© <"Q]”¹_þ0ÿ‹üxçÖÒ%JGa%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:47-07:00´dg¸%tEXtdate:modify2010-01-11T09:46:47-07:00Å9ß2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-bs.png0000664000175100017510000000204412370216245030101 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs Ð Ðw1t vpAg ‡úœ"IDATXÃÅ—ÍkA‡ŸÙ²IZ±&±›Ï6{ƒ(X¬BD$Å“‚PêEEðØÿGz÷®7ñ/P(ñ³Õ”¦Q›Ú&;F¨¢isؾ0—Ýaö™÷}ç÷Üy,¹r"# %ºÃàù3xý¼¾ö˜|Û\bõ=¤²p" Bh€%:mh· ; G€¾£PHh­Á¦!:ª¬}TOó§!ähè÷àSBaÈMekØù ŸßA|Ò0LÍ[ßaõ$'`<} ØøŠÈ•±8)±ï²¦ItvŽK‹×IŸŠ"è”Ö¾oû}ú¯^-6yú DZ˜çù a4a{k—åå&SIÁâíc?çÀÑÝöx³Ò%yÒaz2Š!>Œ¡ÚoWº” QÜ´ƒðéΠµ¾Ã—õ].œ=Âñ¸íËímø² ]gJ#<ºë’Ï„ñ<͹‰0Oîe˜»Ã4üÓ –!@¥wHHkWöÙäËûü¾ç}¾ëZ×ÿ]bôÔI”×Þä‹‹ãœþü‘p¡ª¼ûzǧÏð™÷0g~DÚ’šJ7ï5—ò~U”xåŽ}çÎ@ +ÐÊëk§‚5ôôß"ž$RªËJ H‹ñ·Óåd’”ü ŠíYUZÏw¿®¦„wÚ*±Ó-\ìì'7@.t!ÊJi«wp´6C`ÇóÜpÔ`\ºµ:€“WìÆ‘^iªàãW7Ó±»ï/‡ñ•«™‰ÕëuÒ±ÝËõ’Ž&?®ú?Lê|{a˜Ñ‰ôŠãÐuA†\YûS¼ p¸­øhí´ ÞnõãÚ–'´%H®îY~ížäöíJ‹. òO¿L>þDwÇA)„@W@³M”’¤YÄø§€’;ªŠp:)Z’|®ˆ"`ÐÐ9ÞdÐÐçzÊTÜ~[ØH BÚH…\\#3e-BÑæà¤DèÕÌç‘–5O©;š;›E*(âQ+—ÜF¼5B{î’u¥)š>*-I’$R/eâïFŒ„Ž”ö<À§žCøÊÜìk©ãàî¸Fú#¨¦ü›/ABìƒTT¨ˆÜ!ö0Ê_ã]‘"á‰,1e(Ì ´M¢»¦©õ?GKÅf®ö}G’R1Aè‹¶¡M;<¼Ôd—Û r¡“Ξg‡;›œ|$4pæÇ{ôEû8²¿–V%»¦GHäãÜ-Ë›‹RH$àQì©ÛIspýá_ˆf ¤˪ k-Ãùà篦8{Ïâú“TÖ¤Ì?Í€á Nðó•^»Ï¾–GÚØÛêG³zé‹XŒÅˆÙÏHØàr5’$s1ã-÷Q;ñÉe E›¨©3µævÛy}œ›v€˜2Ž´%‰© çÎ÷òûµ!‚=˜)‹xny³ml¥@¹¯Uõ¦â°Í™ÙK¸P€ÅQ&Ó’̶{vÇ37M%²¤Æ£ï·— Ú*UšER 2ÂÃÞÚ­lòŸ˜@ .{Œ*¼xŠiùÏÇçC/gØRgòÐSqS,f»Gƒ·„§›¡!Ù©i+3¯KÏ©¹ŠÜ  œ ¶g¿ª Nq:^ZD0fR]Á‰h2ÁL¡“›µ@rybÎÇ9%¼H£dˆ‹§€K ÁìNßP¯æ¸Ý\#ð ±u(pxÜãgw„êx“FíqÍËÁF%ËýV…­zGÛ„£˜½ƒ32¾áýÞ áÈ.Zçßž'4ëÖ‹»;M´*¾P.eyùö;Zž¯ßú©L{)žg¨–sdCa­ãV£Èz)C>ë#7Ûðר*áÈr>Œñ<Ãf5Oi-K·ÑëGÄ6•=÷—¦#°NéüiÔò¼ùÐfÆDÖñîc‡þ ¢}2DS9x¸KFrÚøô¥ËE¬|>êa­Ã9eÿ¨Ëù(™œ¹±ùÌ<Œ§¢xm!:ó ’(I”°5²lº‰ŠpÇvðI yµóx¾±:AgëËož(£–²bRð"¿™œ^ÕëRéŒÁOsž‹(=O]¬”¼X6ÀÓe.`¥•–®_NÃfå&%%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:48-07:00B,Q%tEXtdate:modify2010-01-11T09:46:48-07:003q¯í2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-ec.png0000664000175100017510000000171112370216245030064 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœÇIDATXÃí”ËjA…¿ªît÷ cg’0ñ £p.¼ ‚àÎ…®óB¾„ø ‚Ïà2…02‚¢Bi5™ôômjº«\¸R7Sã¥öZÔâ?|uŠÿ@£Fÿ»D¹¿Y+€ êxV7@í ,%!~¼ó²™`2u <1š|&Y5íÀžÂ @…’ì [¼xå³Ñm‘9Ÿ¿d<¸ ÷o*ZžÆCÚh$Éü~°ÊÕí”ãt•nwÛמ¿F¢Îcì,q¥°á5PΉ8ˆ¶¨:}OsMYñ3¤ñøî·¸§;÷¬ˆõ¼¢P-¦§Âþ=†Q‰>ÜÚ~ɧ‰"J6ìØ}º»øûµàBóhg„Èé×÷8qI§0N.òdoÀø4DH‹ÞØ$`'‰ÇÃk’K]Ňo93+ÙôÊ^{Dqß*°ð‘†¼ Ø?ꑯ8Ù N9¥ÚªŽ{¥Ò,î'@\¹ñØjyÛ+†À-ðœœø-%ï:—QU€ª|2%­ÖP[r¤EJ\¥ Š¡ŒBAC„Dêô(dñó«Š3t:£ØZV dJÿ0+„·Î4Wô÷À`ã– Øz-ëF·§õÖ`~"…³‰×®%¶r9áÉÙ»™ãDõqÎöb4¶`4~ƒwé2Jn‹ç#ûÇŸƒßžÍA¯y½f5‘ü<…ÆM¿ÊÒqœÁ­ XmˆP`XÒ—heKÉÜXKÆÒ…i9ª’ò?ÇdôPÑit ‰úê2Œ–6¼¾Ë(Sÿ ÆÂòbâuÁtÁ¶Ô7;ÿ¨†0éÖ®%¶j9áÉ“î!z s†ž‡óë…# ZûÌ]#š™á$­öq{ˆ†®cîi±b‘ Ú}¯72cYñósÇ´âzŒRE*Ñ=Çé`Ü縿¤Fºç. ¢Q2J‹R:HˆÈ=‰´mÔ禡¸Ýç·¢*R+[šöI–„C+_FxR·„æÞƒÂí>/Ä¥YåšÐu²?þ€È¢y¼ðXpŽdà÷ƒ£ÔO–p\¬öNÔÙ3Ò¾ŒÓ…4-¬öNü7‘Žó¯|ðcü·ñ'Ž+gòÙÏЬ%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:47-07:00´dg¸%tEXtdate:modify2010-01-11T09:46:47-07:00Å9ß2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-sc.png0000664000175100017510000000260112370216245030101 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœIDATXÃí”OoÛdÆ®í¦íÚ®¡é&Ô®LJ3‰ Ѹ\¸”Nœ@‚i=p䂸ˆOÁ€Ãv¢Ôˆ Hݸ@Ú4i\'þ;‰ßÄ~98iÓ-ÿª‰}$ß^ùy~Ÿ×p­kýߥ°ûÍØC³zÌ×{%¾zßbJ‘#Ï¿y˜ß–i—CPÆЀÍq‡Zb ÓÕ‰bPUAIM1½–B]Pi—˜8À÷#OH¸}³Í;wèªjŽSàýdÓ>Œ~¢tUòá[;÷|ÐwD1Äݯâ=uˆêÑ•Œ¤7Ö›<ºoqk¡Cü¢»RH‡>ö“3šÏd[Nl>:€„åùˆÏw,¶ÖšÈæQ=¢þÔÁÙ¯"Ž[—yåº&Ù3.º&_ ŽZ8ûUêW¬Û©’™ï«^Ù–4ŸÔžœÑ<ô‘b‚Ê¥¼0žFM§IårÌln !3ßá‹]‹íõƹ‘Q?°“Ê‹áøÊ{¦ºŽ–É0Í2gÌæó¤r9Ô¥¥—èªäAÞåAÞEë»v¢&•ØDÞÊ‘nl0kÌÓÙ,Z&ƒ¢ëC6Ð]ý—»+ób&\ù8Òtú’i¿´~óóÕßi"±ò¤³†Ajé0è­~oÛEW%á‹+ï¥ì#Me³‰é¤±”„/š¸­Ó·1» ·ú÷ª¼–jüP{Ü]y˜|ï~Ò¹~Ò•д>£uh´C¼–OÅ·)y§Â‘sÊ‘kR®[˜¾ƒ× ÐÎWßbkÉÃÞ·q~°ÅE×ÑWo“Êf™3¶™5.HcM#ŒvËÇuÌ FÙ«qìV(8 Î)%ÏÂômÜ0 !Zˆ¸CGI‘Ýiº&ùxËåƒô)Þwê?7Pô4‹;9fòyR[oÃÝuÄÍÌXPñ-JýIÁîU(׫˜¾ƒÛªã‹aÔ&ŽcΔ¾ûªL]±öîjO—OPn}ƒèá=Ä›9Нg0µ˜b㔣Ã?(ÔÊ”¼3*¾ƒ4õL”ä™à÷¨}´ê>­üxç Žo-r¤w8®þÊÉßµÀÅ š‘õ®Á¢«J[L+Ÿ<¾±È/ºÍ?'‡¸5D˜¨ZòL©‰Ñ MiÆÏ·4‰2—!½¬SPg°|‡@´ˆe÷§£¼âµ®u­1ú[{ûı´ƒ%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:48-07:00B,Q%tEXtdate:modify2010-01-11T09:46:48-07:003q¯í2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-gy.png0000664000175100017510000000323112370216245030113 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœ—IDATXÃí–ÉsTU‡¿û¦&ÒÁ MÂ&!˜ˆJDHàÁ@Y¥¥UnÜXåŸ`•+·lýCÜX%ÑÁTH´$Ý{zÝýºûM×E:T‚@À ÙÈ©º»wÏùÎïœwÎ…Wö7qˆ5ëL¦çð|mW´ŠsG·–oCd ‚MPZ (€ÜN}Ù}£¾»]ÎWä˜ME0mk=¸€xùçB~Ù{oÊŽÞP›ÊÏF™H,µâäÜRúë âåÀ¨7dðûü켸?~_Ôa‹/ÚB¢7Ü&:*›EUIµP]8¾' ¾#¤ôâÍŽ1 K[J&Ý}j§]ãJo=]´¡haÞ1ié &ã ǘ5£Äò&¶gïH©ÄH0,7\¤|'Ë@¹IÝŸëWÐy²†=‡È­¬ŠCLç+NeJ,2ŠÍ®‘qsH)‹/#F‚áGí.ˆx·ü4ÕYtv >¹`Ð  ê{‘Z'ÐLL ó·[ÅhÆc(±Âh|޹ì*¦ÁóÝ¢ÃíÕÙ°a P’i·ÀMÕ¤ÐZ࣫:]§5ª‚P¢¡Wãa²Æ1ü–ÆD‚±d”3ÂZ.EÞ³7Á<'Àf!“¾Ç k1°7MíiŸO{œjÓ( €ïoø6Ú4aé-¬ˆ&î^cÄ´Œ-0•аhűžðW=`3ˆ\‡>?ßuYÞ½ ÐÛàpƒŠªPübý¡£¨ 7àa’Ú1¸• §=†«Œ'æy˜Y&agñ|o{€Í ¶”L»y~RL¬ãy¾þ¼„‹g ´Moùè–PJZ5~ ™ŒÑFD9Ád®ŒÛ+3ô/O ¼HÇ*€Ž‚âƒãH\Wn3°%àtÒFÅÅPuŠŽ*T¶Ý<½°è9Üv³LÕd9y®_.'ܨ¡©—@C(å½7&¥µ0ç½ÎXF2´c4Þǃôq;í{Ï@Ú÷¹ëZô—¥ÙÊãÛ«í:å¥é¯+ „†Pƒ`¤`´°¦fÆ>ÀX²Àx”‰äïÌg×È:¾ô¶4áÀ‘’׿ab+ÐÝ£rñý=ÔVŠ¢,£ß8BÎha‘F¦r{\6I,r/5Êr.å`ó[«®=ž±¢žKŸ—á^M–“]’kÝ­‡hz9R«Ç %©†yèÕ2n) -­2›äAf…„mâz.[Æô3™¶xCî!Ç¢¿$Åþ³ßô”qö*J÷¤`´²¢eÖ2’,0˜Xb29À|vÓ¶ð¥¿)Ëçßš(Ê}ßÍsKÉ~.]mäÒ…ã”U·°@#S¹R†–SÜE˜N ³šO’wóE½ŠÿãºÖ"®Ío~©Ð>N\>͇=”„êù9'œ‹1ŸæAf‰XÁÄñ6Íøz°ˆ®Úèl§ãÚyJš÷1‘[d<¾ðÔ®ÝioÖõãÁKo±¸¯ÀŒ!žO³«O²+7¿+ùÕúkr Êj t?•Ýz”j™þ‡¹–ãuLԸ؞SÌ|w‚¿²Wð#Y3T£€6%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:47-07:00´dg¸%tEXtdate:modify2010-01-11T09:46:47-07:00Å9ß2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-fj.png0000664000175100017510000000300512370216245030072 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœIDATXÃí•ËO\UÇ?çÞ33wf`†^3”W)B[B©Á¤¶¥â+í¢+cR«vá¸4®L\»Ð? wj"©ÑÃN­•…bi5 -¯á5¼f(3Ìܹs ^C©UIIòÝÜÅýåü>çû{ØÓžþïÑwÞ‡Žã|Ð3Ê¥O¿'2½ˆÐt.œx„7§zx/ÜÂÇ݃(¥(/ÌãåºB^ñZdZ¹TÕLıC鯞/-â×á"ãs Êз*+K$¾BJ‘´“£´òF@ÿ¯y7~»1t9¬K.­ÀN=Æ•kƒ,Ä’(¥Ö²®fB(ððD(‚:ÁêZFjT;ν ðvßÂá'çoÒ^[Â[­û8u0Ì—¿ŒàÏw"¦Wƒò½.NV8rÓ^[Š«"ÌWK_ÿÿ €¹‹ ”R46ÎüÌ×b×gÄœiilA]ƒ€Ï¤ÌÇÌb+Èj–×DêÙmàrÉaðxM˜f©˜¸ÒÃÕ¡(]ÓIêËxMh|tu€¸É¹ÖjŽû4/O³¸ç;3¦…sÃ…é5ljb!³C½s¸Ünn´ø¥õhÞ"”R[€åO7âŽLòc_Œ®É;\ŸËOi”ëN¢bbèüt{–?fïÐÖP͹£yªv?•ÃQºœ:Kjm)º$œ_LÈtâ)4K§PË#e9Am_Wò²]€Yâc®X#qÈ¢^Ù!H¹tZ-¤¤AÛ‘V”­ˆ øBxø!˜‡òT²¢tĺ¯B@Ò¤ {ˆý±yÌñ@ðh,Á@ õl¢dëÈÊ Äê ü9d6Å·1L>_N³)˜JÛ 9·Ø)P$òò™9sŠc¥>Ô']{™•Ž"&²Õ¬øüÛö…ln¼»;÷ðûýË%³ /ý¾4W‹ƒÄ£ô¹ãÜt”aº<›nmÃ'!#¦‹ÎÛ š„A¨¦Wœ ꨼gü°…ÆŸ¶—‘c§ LïoŸË]Xw"“¿ÖU÷y'v àŸçôï*Ä¿xþaCE–™|ë¥;!Ðe‡xÃf¸yœ˜¶ŽW8¸„·é¡IÂ÷ú"œ=ÞŠßðp{f‹kcë,% /‡4¥N<g08ILK  ©é(ZçûhÑê„Ý+ÓÝ䳡8Ãíh™þX »J®Xa{§BÍuÿ‘Ü-º}I.‡& NÕ6P¥*BoÁéG_BïDô#éM(B€O÷ÐöÑÓàDWˆp@ ·³™¾£Íü¹–Ãuód‹ªUwOǺbÓíK2ãB`’£ZÕ#!¢x;ÎbÁûæž`È*µš‹âº`Vª¤se’Û&›™ñö&Yb{§¾·•1)”ljµ§É}²EoÑp¸CO£(­çÐbƒèñ!ÔÈ[HZ€²U%•.2·’ez!SÀ©ÖÈËL/móãµE̲ƒÏðp}2É­é$[Y“Š]}ÌqƒbÑë_g¤åwΦˆúóhÁV¼#èñaôŽ3È6\IÅ,;l¬í0µáúT’»³)f—³¤s&‚3Wÿ¶¥©2­¡޵ðf—²¬l(š®[~¥LŸ?ÁhËç›gèlv1Z{к†Ñº.¢Fz©y|äŠË;ŒÍ§¹5³É™ ëyr…2΃-Äã×°lUYI(–l M!‘ÚÅ©ºà‚O±èó¯ñqè7Î…‰2ðGG0ºGQÛÞ¥j&kºÌÏæ¸;·ÈÉ$“ V’ò%ë~|¢>¤‡cVy"Tª5—\±B¡dã8.M“ãþU>zc’ G6‰v¶á‰Ânì"Q™›ÝáæÔ8·g6™Z̰•11+öÃ÷DˆúÚÊÓ[ÛqÑ•ï4¯òÉá9>Œšt½Õ‹û‚JË)VÊMŒÍæ¹55ÍÙ-î%vHçL¬çäá¿xOžPvy;àÓh‚Á•¶îKTÂÌY‡»gqã‡UÆþ¸Ër2OaצZ­=Nú‚Pp\‚j™S¡Wâ9Îöñ¹ÂJ-ÊOËîüœejá&é] ¦ îÞy¾ ”ˆQæDd—¡¸Í±ö0õ4ߥýܼQf~mt¶„e9¸ä¥œ>SÀç˜ Fˆy³‘·Q$“OãTÉó?º|®€ÅRø«ñ¹K©N¥r¿­Ò¾º|"pB£Ðj5°öû3ò,ÍßÂ! |žWÚêà‹¿k?È£Õà¢0%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:47-07:00´dg¸%tEXtdate:modify2010-01-11T09:46:47-07:00Å9ß2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-bi.png0000664000175100017510000000340512370216245030071 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœIDATXÃí–[lTU†¿=眡[§ÓvfJ[b…Br‘«‚7$å")!ãƒhLÔxàÁ_0ñEcb¢1–‹%TH BE°¡ÐÊ PÚít:·væ\¶ HZ…˜(ÿÉIöÊ>û¬ïµöŸâÿa$’ ~ìW®¾÷>éæBUH2iŒ¨(§ôƒM¸çÌBª™HåÚ€dãY¢ ‡±“êó”÷y«3'Úp˜üÆ8'WaªÝçÝ"üê…2sîMÝ{ÙÛ6Ûý%`šhÁEKד_½P(>¯PÑ•î–ùZ"£“:{^F¶ÕÝ÷=úµöæÃ;÷þ“ÔFñ.yßÚÆ i×èÖ{P+´Í6a#à â*)®ÙÓENåaõö #Ü)d:-BwÿJ)[xž™'‚ïn…ëW û#e"F‡®ãÓ‹µ(/›ë>Cg:BÝK¡'€£b4ÎY¡ 1˜‘n0Ì›§aYÙec™o™šJîÄqmxÿÆWqNŸ‚9Bá÷Ø>¿TÇg¡4DÏ Fí›#-i¡Ù4ƹeeI5‹‚ó)É-F©3MDvì¦gÏwd²eÑ‚r'Ub/ @æÊ5z›ÐÛ;° ’·ìy|/.ÇQU‰TUZ{Û8Ð~„­û9¿ˆn騄­ŸÀ@¹xT³}SYS¶ŒÇ ¦áV˜±8ñÃ?Ù^–Ä÷R ŽS1JJ'uò‘­õ`øÖÔà^ðŠÇMÜHòKWÛ¯ìáxä1#àf_ÝFà €â?‹óYYZM¥§;*z8 –D úIõ%hÙ]À˜å«pä¸ÐÛÃ`h~? šbÍ켺ŸGhë ÷'äö¦¾Cqn|ÐÖ¦öò74DÏPS²ˆÅÁ§ üËõt/É -crÝhÅdví·í‡¨o=À¹X º4îH<([‰èÒàtô$.Ó™îæÑ/ãT¸<Œ}}ÃÀøRFŠ/ÿÜÅ—v’0’!M>$$„$Í=z@¦4Ql ²lÙÀ&ŠPzô8I3…Mü³˜Ý•ÜI‘k—hÚ½ƒp¨ ™}¡&švï ríò.ukH‰%-œŠƒ<ÍD µÐQ[G×ÙF,$’®³tÔÖ µ ‘äinœŠKZM=”¼ue›K® •ª¼q¼V¾š•¥‹ñÙ½¨öÊÑø'N!×éA мyŒ˜8–¢ñU¸^F»FQ”ã£[ï!’‰bb Ú÷t •b?¶¿ýÐBb¶ ó%DÑÛ„hÎSP¿nu¿)U\Ž^8'MÀ;méæÐýOž-…âvã­˜ŒsÒl.Ã,îCüGð¸€ÊF©9%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:45-07:00#ûv‘%tEXtdate:modify2010-01-11T09:46:45-07:00R¦Î-2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-ga.png0000664000175100017510000000117412370216245030067 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœzIDATXÃíÔ± @…á÷ä K(”ì£ÐÙÅj‰Iô¢¶‚D1~‰»îË˽“þ>Ö4 €ÔÒ€…  äò|’Y@S^(ÀÛZ?h-œ@Üð à-H@Øh ÇY¡÷ãÌþ:üð$„¤t4M çR¹ž&á¹%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:46-07:00l %tEXtdate:modify2010-01-11T09:46:46-07:00cNÔ°2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-mu.png0000664000175100017510000000124412370216245030117 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœ¢IDATXÃí–± ÂP DïÀ@DÚˆ"B©’õèh +d€¬’’2b‚4HPþgŒ×äð³}:[ZËSY¡!© :ÀSY%z&6dqI ´}I1š/ àc{ÿ¡øxú ¬LÖWäÌÚ0ÚËŒø1Öèœæ ‰öž„ïeË^ÃÛØ°I8<Ï;Àf“ÿ$ö„¤ž¸Ò/`®? xFf%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:48-07:00B,Q%tEXtdate:modify2010-01-11T09:46:48-07:003q¯í2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-hm.png0000664000175100017510000000302512370216245030101 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœIDATXÃí•MLeÇ3;³; »,„~$±‘Û¤ •UKmìÅC£iÒ´‡r0^ªñÒ‹‰1QO¼[/zé…›ôB µ¡h¥ Xš¶» K)°ŸììÎÌÎëa·t »BkâE~§IÞç}žÿû<ÿw^Øa‡ÿ;’ýåÄß}ŸÞß .ý0I(‡LÏ{»ø.q€Ï¼gøñ—e°õ{5>~Ýà|íó{›ù ÏÅÝû @z!ŠÔTצ×40qï6¡` äÍ‘‚Ъ`"YÓ)ËÌá°›_¸8€òpôQÿ.®Óã߇”lá·?B¬¬¦Bä«’û–$ª}*G›2œ«àimaJÝOrèÉ¿òéê¶¡t óUw#ïjáÊpo¥…´–;™×ëäX‹ƒ“M Žt#7µqùI%ý×VYXJM,Ëuu’ض(. ªq7ÓšL…žåx<ÌG/¥9á?@,ÁuÉ z:U|¯Ø4¼ÜH¤±™Á‰ÓÓKxÍ$š"ÈI\V¦pæL½½ã$“fQR¬«;'M’qËÕ6Áí˄ۓ¹¨ÖVpÈàÒ0³ §-¥<œ½û3)Ïú¸žât:8r¤€‘‘0†‘ÍÇlô‹Rh0œ 8Ȥ!kdSAQA×AVA–rñÿ€adå=ª*ãñ¨¬­™ƳÜÊ'ž³ø|‡÷püPUY‚÷Wˆíª§õçïAÀô¹ÏñÕVÑš"¶aðq7C-™„å`!I i¹ó¤ÓBjìß_ÅéÓ­\½:ÇØØâ3Qµ‚7Û¼t”¯¹6Nÿ¤Î•‡^^=hòµ¤€? ,ñçò*'ß®åXµFG"@2“f*ì"7€Û­pêT }}3¤RÖ†Ž˜f–h4EÁÎw |óã\1¸2§1:ï!ªgñVë̤Ê“üz#ÊØMWïáä[x£ó1jö>3!ó¦Zr²,¡i @œ‹'Èd6 T# S°h•×íõ¾UzÔØ1eÑäSAE¥›šÝ"ž ðÄ$cËH¸\¹d2Özû½^•ööZîÜYfiim“ %ø¶¤›Ê=NÖ’F‘ÕÍŽ.†ªÊÔÔ”³¼¬£ëÖ¦u¥Ø&E‘in®¢««€¡¡³³,«àfló÷kš6Á`¼d|Q² ~ÿ>.\h ›Ü»ÙVÁ íÍ×¢´Ø¢ÜnMs¬ÏQÓ¸Ý*†‘a»82uŒŽ.l¸û[ H$2 <À²r ’Hl¿xN€¿·n=.) ¤ UUFQrϲeÙ˜¦Íó°íǸ[lÁ4Ÿ¿h!¶-…âÏÎYøð…«lÉÖ7¥dvØa‡ÿŠ¿9°f)© †±Ï–ím"·/@)8„™ £rv; <À²¥Qh07S˜ãEäXZX* ¶ƒ8R¶©À‚uå¯KM#±IeJîѹÅÈ…`§„އÑßËÔƒïT/«²«{T€ÅèåæÙ£Q-ff{ õwh ¬ "Å”9Êc¼ÿPà­Là¥Rïgüçq­Aô£“I sˆ|RçÇ)§jè™it4Úðãè§)¼Ø¯–E-§rí:¦ ËÐV?Õdg "‘©—heЀ0MT8„ÛÛCwW„à ³±×@P÷0-*ð+'aÛ°•Âý¶ † Áqp¾.ã¦wÐå²§àªÙVm´@RÙÉ{ýmgqÝ(ö4"·JÑìÃ)J„ŒxÚÌêÁüls‹Œí®ànÇÎqã ÔÆ:‘3§°îΣâñ£Gn `_n¾@mm×¶1bæÈ"ò¼m€ã”÷ßÄ£”×Mæ R*?ó@¬Yíñµ†22~œÈwýã•óojq•ä%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:49-07:00ä[å%tEXtdate:modify2010-01-11T09:46:49-07:00•¤Y2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-cc.png0000664000175100017510000000224112370216245030061 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœŸIDATXÃíÕÁk\Uðß{ó§Sk’Ò­%­Š ¢(bQ¡¸QèÒ‚ˆâ ¸q/.Õ… .üDQAp¡…n¡ tJµ †i1MBÒ‰™y™Ì¼qq'Ì›t¦M„qã|pçÝûî¹ßwιç1ÄÿwD>Ø5ÓêZ8ÌtÍdm ÿ oó‚ÇŠLØlp{»; @1æìƒœ?ÁÑ"¿W¸x“Ÿ—¨gûwGLöÍY%ñÎãÜq>|Ž3“Ä1¥„÷Ÿæ•©öGûD©ÀÛ§Â(Ý%• LÜÇ›'ËÏæ¹¼ÊHÌ»3¼v‚Kˬ¤º‹²­(Šz§©žñË­ŽÝŸ@‹Ã£+…¼Ÿgq´Î^œ WÒΦ‘ˆÇÇybŒjƒ¹uÊÕî0×3~Zêp‰¹¿][yB T›Ôœ}ˆéC<’2>©éP ÕF÷áçŽñÎinlòc™ ID¡«´ÍGæÑxkšïùu5O b9å‡2Ïáá"Ïf§PäÓù°. ã½'©Ôùh6D©…bÂÓÁé× Ý¤a;c½~g:¨7ùòÅçÓ*±”qá7¾YèÞ43ÁÉC|<ËÕJNe^rNz…¶ø7Ÿ_a«¥|2Çw†šXÙbq3„s/¨5ùj!Ø[¹=ž?Âì·jîè®Iþ%mre=7Ñ£ϯq}ƒW§¸x£“‚Lo²i“«·ÙhôöWðò®¿A”»…<.§¼0ÉS$1 T¶{7›¬Ö}®bbŸØnq¡ÌµÎ5¬5hö8|GÃÝÚù¾ ì˜[ £_#9s4Ø—–û7£E /¯ŸºÑ˜—&ƒ}yuîj“/®wì~H0?Y‹ò潿Kðú ¢° ,C 1Ä^ñÅéð‡’Í#¥%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:45-07:00#ûv‘%tEXtdate:modify2010-01-11T09:46:45-07:00R¦Î-2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-lr.png0000664000175100017510000000167512370216245030123 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœ»IDATXÃí”MKTQÇgî¹sgRƒA ¢rpÕÂL2|YŠ ?@DЦ/Ð2èC´ìm"(ÚdA1˜8¢Œ×Pd´ëÜ;÷<-&ÍEÖb8œÍüWç9çð<¿ótÔ‘c©Á›/=¼wZãÉÑ1ÖtÁ4õ@Î#A]ܰ°™ízvˆ´Ôïx¨qlÒ¸™ŠIíÄ*óü,ð<…i=:ÓÛM¾xCrMÐZ^Fq{ø?ê„{5 Ð3q‡Ò£ òXbÐÝ…ÓwK<œ£ºsÈ›e–+!ÉAãå5ŒïÙˆ“”Á¾&Go±¹}•·ŸV0Æp²¶Îv¥L±Ö Æ|û¾ÃË× œD ¶vk˜Tè¡ôà>]¶`|­„”W«hí') $Gu¢õ*Ê÷þ¨6ªý ` x¥µÎÎg5ôF•ðÅ1ÖP>¯\š»Ï$\7 2¶~  ÇwÿyAØC –†g­ŽÚÿì¿›w  •¯ÛÏÒŽ‹®[°÷ê½Ûdû‹.룇f~:u ÚŸ:u`¡Üe}t³9è¨#çú¬ð¡àíJ`%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:47-07:00´dg¸%tEXtdate:modify2010-01-11T09:46:47-07:00Å9ß2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-sn.png0000664000175100017510000000157112370216245030121 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœwIDATXÃí–=JAÇowYÄoZ)Šˆ‚XxƒT¶zÚÆFðvÞ w0–)$ˆh„8Ïbv#²o×Ä(ä³Åìã½ß¼a`¦)K¨š Ow…‹ƒ€r ªßzÃõ/õ.ýÛH¶ßXšf"àÒhûdŸKQZNŒÃ Ȱs.ñ©,g_Of¨éÈÖ¨<Ñ à´û~ý@ÒÛ€4ZJ£¥ˆø½"2ÍêH¯xxVÚ}¸yôDs1¬•`gY(O@Üuàú^iv=ÀSÎö„í—z®(0CmK¨V`èüªVüÞBœã*’4  Ô6}áC)Þ͹Ž7„ýÐì(÷K ,Æp´.DI篖!ú‹e@?G. A(RºÀ˜5ˆ°5¯&_5اÿ†Ž‰€+#@ê0ûMèA-X"àÜ^Q1»Z‚§o&—c¿™þŒ>íA[¿66“%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:49-07:00ä[å%tEXtdate:modify2010-01-11T09:46:49-07:00•¤Y2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-as.png0000664000175100017510000000253212370216245030102 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœXIDATXÃí–Koe†Ÿof_fìø’Æ×z_Æ—š¤"A±T «Jˆ¬º@Ù±â°á_ !HH¬X A!A©Z@B UURµIj§‘í8¶gÛÓE ô512y¥oûç}uŽÎèÿ.Ë+%°ÑDŸ»<­l󬧉”&`#Ó²T({BÍ ðé¿ï|ˆ‹§å9O…°D!^wâÀë}¼ôˆJ&s.‹|@KxÉ ¢gRòs¨ze\áº0Mˆl¢»zäƒ#¡‘1RDËiü…9”Ù]±G£^¥&uÉeõQw“LR.‹|²qL^'^N*eñ¤“ Ü õ{·©\ÿ…Íïb³ræV•ù×Þ$wîüñŽtXš#T6P3:S‘YdUEÁì´¸úÁûܸô µjË4Ù³%BÆYJç/àÖ|ŒæPM'÷ z}ÇÃ_ ú}Ö~üŠß¿ýŒÎÝ[HZ4ÉâëoãOt»Ý}¸ÅŸè‘ºèÎêDKiBåj&õÃ'iÐßÃV\D^|ƒÎ—£UWqË`[ êµMn¯¯ Í èR›¼²CIn Œ%ƒÓçæ™Y( ¦S8§½B9~»Ø¶ÍNsU/2¯ØT>ÿi{§æ#¬çø¨Ò8¦àÑâV{‹Öæw`Ýa6á…‹ï’å-†²U/a,=OR× ƒÈMû¹÷V^~¹Òör¹²Ëµnrãë«l|s™Ýk?Ó«¬B³‘ ’¢€t8» t†[—°Z`KNdÑÃl­Ñ·{åé7(T]¶^Ï’˜)Ð;Ì„“c6z –‹ÝÈüʦûuo}±´êRù¼ˆúá·b-Šz>å©9– ïAA+Õm_¨î”`m8O9ÙÏYÓ™=¨›P¤½‡D-êûˆHè&¬·¡*êzˆ(Æ÷°2¤.œ ½ ÿ˜‚²!1¾dúàÒÉ‘ÓX7¾Z míÿ(ö#)ž'ŽÖ—‘o Xõ〗±îùÇÎñ¿Ö±‚Ù}ÿÀCgèæ‹xßþ$CÞêü»hgí$kª©¦¯Ÿ£8Ð Ôjì%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:46-07:00l %tEXtdate:modify2010-01-11T09:46:46-07:00cNÔ°2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-us.png0000664000175100017510000000217312370216246030130 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœyIDATXÃí”;‹UWÇûqöãœûž اˆ‚…à7°?‚ù~ S¤ÖB‹4ébª@‚ˆ¯ñŒã½çµÏÙ'Åá"$Å0N3ÿæÏÚÅ^¿½ÖÚ Žu¬%Î]¼M1‚’‚#RIÚ6¢\JBŒ|ŸtÜõ5SÑÑõ É cÄš„¢¨q©åk^2y¾|Í™M2v¿¬˜MRòeš9TêP²'€êÄö}€¼ip[ Ë@¶½ÅûUÉx1çݲdr~ÎΪ [,Xî}fïùËNÇ–ˆ8:€Ní™·4M‹1[RoÐÎ0ÎÒ¦c´ £ÌaSÉìâ ¶Œ$öP½Ìkz‹÷†ªnEY3{Š20{ʺa\— n£ö La!‹tV‚ûwXYm±Àn±°°UŠMe ¤ÑÞ4‚FELbÄÊ^žyc¡ˆlµóbv =Í4sçÎ{æ¼u)¥V&àêVà»V÷Pk Ìo¿ŽuæG8s[zðƒP«fâƒ9X<­ÝH(¶v[‘ãÛÁc¨m‰¨G dD' %ü©\°œI`Dä`ªlî„’N(ÀÁé-¿Ku&F]>¹H Ïô)°QR v~G¡ÜÀoKªµkNêw|ég2=ˆc òó)Ò^op,ƒýÃjç· ¹&_r£ÊMJ{—¤=—•C©J»S1›\&Ž„ä³IV—ºTk×lÏ€ÇK8;=Œc TU© þnǬ¯ÿŸ6|‰×2"ýVœXÜŽLà5#óâÊï"¼{˜Ž¥× ÄןGZ'"íC©þ±\J©ýc¢3ÿ;x³…©zÕ/×ò%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:47-07:00´dg¸%tEXtdate:modify2010-01-11T09:46:47-07:00Å9ß2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-by.png0000664000175100017510000000152712370216245030114 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœUIDATXÃí”KNAEO}hšÂÏDI$1qªîÀ}¸.݇K`&$ÆL b ¨Ä†V›ªêrÀ̼‰}6pOÝwSÐÐðßQ›áº,!F>··¤ª°¶×»HÞƒ÷èNG¼û3ß…÷wW+PJV ¼½]TÓ)ƹÝ)„ÑÊ”µ 5#.`ÍÁfãªÕ’Ë%~>'dÉ{yíË ?“ Ú9HI~„Ùé)¤„Îs¾Çㄤ€év1{{¨V Ýn‹†hñÄ¿ IJ$n6è<'UJöØílÆ×ã#Ú9žN÷WŠXB[´Y¿O]ÐÎx¸\ps–ðA°{|L¶^£ºŽÐY±iƒ·‚±(Å<ú]ó‚;Ð)Fꚣh8€µGG#…")ÐÝgX äçç×l=uôØ ¼ ÿ„a±ÕeIŠ‘šoÙç744¿˜O“uòÐ%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:46-07:00l %tEXtdate:modify2010-01-11T09:46:46-07:00cNÔ°2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-ph.png0000664000175100017510000000213612370216245030106 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœ\IDATXÃí”ßKSaÇ?ïñ¸M ,ÄêF0"-¡›êªK/ºï&èú?ú;¼(I±XÉ’DeB.tQöÃå&ÊÜæšnâ67w¶íì<]LÌHºq[í/¼ïÕóáû<ïmÚüï¨'£kŒz¶ˆ&  TËôÏ¡Ìp4Qèüî_}©;4æü»ä Zì *FX¢ñîåóLz÷øÉaUmÐZc¢Äø TbTºîˆØŒÍDñøÄv l¡é‰(±Ë‚X u¹B•÷«û<ްð)E:oÖ-š$¢DD~=¬$ Hæz˜YNòìm„¡ F©Ö‰#3‚XûPÒQ®kXªÍT/î…8óÛllbÕì†~×c1üHöT¢õÈh@÷ÌŠÍÊzšñÙ-<¾‰ýr}>€ Õ$”7 AŒ¥º™RH9„rôãt\âîPŽ}{ŒÜdl2L`%ÊoÝ;‹@9:„t|ë©•9 ÒŸšåÇN±åÌc¡¨ÎˈkJk( cåºúEĬPü–#û"@næÉ=®ˆÝœ2„ë :À5ªs[8ðÌ’uOc†£Hµ šÖâ'N´ÁJPÍtŸ_$3ñšâ—¶QjÊvÔ““‹¨V<‡á_!=èÇÊdëß®I«Y§´ŠTcà¡´¾KfrŠüŒ3ž[÷i(ÛØsë+¹¹²S^ʡ͆÷ù¯ .%‚éç>ò^v¾PºEÅTøáãáƒ7sˆm£9-+|œ@÷­›Áb D%¾ÓòâmÚ´ø Èß@oäòö%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:48-07:00B,Q%tEXtdate:modify2010-01-11T09:46:48-07:003q¯í2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-za.png0000664000175100017510000000303212370216246030106 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœIDATXÃí—]L›Uǧ}ßÒR …µò16ãp°€Ld€Â`§˜è…n!²L ‰£1ñNLôJã‰fèüHÆÐ ½Z–áÈtš°ø±l2dº1¾ [KË×ÛÒ÷=^Ц‰†RbböOÎÅ“œ÷œßóüŸ“÷¸«ÿXB¼þ8RJ’{Ý9tïŠÜ­Ìÿÿ;o"5 L¦ PG,PM .{rqÁÐý>)TaIÚ8)å{ÑZ0˜æÈϧx±ºE¸Ê+umÏcÆâÙïA×7¬ p(Ì…4>?×ÇâRˆçvÔQØö<¦Ô4ûÏ` DÂÌéu…ša€DP›ǯŠ+7ÇDš§@l©iÉî,ñN#àH)beþz‡ùð¡Pç¼®0¶‘„ ¢ëüÿú äï¬åž²JD$‚î@†B «†ùÆÙÎ=Y3$«’‘ ®FÙ³Úçdž˜%=3›«°»²Ð§½è~?H¹nó¹a:„yºh†òŒynE,LÞ^ Cçh5|BRTYKfY%bi Ý;‰ iË+Å b÷ÑùãxoÔdÍÓ’À®\×lueÙ*!j \f`zŒ4O![jIvg¡OMbÌÏ!La2­}Àl‚mèh†¦‡. 7]yüÌ@3¢GPJr›h-ÛM[éÃùèƒÈ¥P´¯Ö¦€˜2Ra_t<*H˵Ó}ËCÏt6£!ëê$)±©vÓVÞ@Óý×eâ0 Øží{¡©JáWáâÉÎ,æN«d‹5ŽÜÿ &‡ž¬‚WŸ˜]v>Ïç3¯‡¹ˆ(H|É/'ÿ§‰QB,°[¬kØò_ÖÚ„Ëw“çÌŒµ{×1Ìul¢µ¼žý%õ,LÚ8ÙÖãjDÈôhyÚ›iž¾ðåÒíÍf4|gÖVÕBmÁýtT6Sê(¦÷´—z†øíZÈóVlE>[Í».G½î¦³Ë:Úå¹Ê¡µ´àD]G‡8ñí(¾@x5•x.¼/$vŽù=ôLe3²­zó:¿˜ªö±Ýq½}S|üåC~ #þcR.Ùs8:’s›×òo^(©'0fåíO®p¼ïþ`xõ¾N)/_-ÆQïðÚ¦Z¨‰z]âØÆ7§¦è:v‘Ááºa$ôf¤ø#êJ÷¹Nϔ֊Ö rvÂÊ[G8ñÝ(¾™ðÊ=!‘R€OcAJ’•ƒ4ðRõbꆔïþÅ8yfŒHÄ@UP„¯ÄÞy7í;÷â¶;øê§Ù{úÕLjêÆ¾ ±`Ɉps!HAz&É6…tg‹š¾ÜíwõÕŸœºi ‘%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:49-07:00ä[å%tEXtdate:modify2010-01-11T09:46:49-07:00•¤Y2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-ee.png0000664000175100017510000000117412370216245030071 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœzIDATXÃíÓ±@@…á·œÀ ¹X5*¹äšP€.c$†ÈÎ*㙹ýx_° x¹'í0S@ÇŒl@ÃÌqü¶e¢¤¬j£Pôp@ˆ1R’Râ~ªrfæo˜7 ¼¯žL€¬ûÑS×ý0÷=w²RÖ%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:46-07:00l %tEXtdate:modify2010-01-11T09:46:46-07:00cNÔ°2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-nc.png0000664000175100017510000000132412370216245030075 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœÒIDATXÃíÖ½mAÄñÿ[n qDL ¤4àpn€˜*e‰&ˆ¨‰ [;øÈŽ]§MÞH—=~šK<•cãé*{$ÁûÛ˜ÅÇ„á "©¥ÍÐñÌy¹â{½³lwÓ 6Ê„X¤tµPpÿò€íîòY²Àþ7H¯Cì%bmÕf¨‰"„¤"Àé’fù?2ÔDˆýç·±W4ýP²SyÝíZEëþQÛIŠ]Åp€àT4>»|ÕÌk5žêùº99ˆt ÚŽ%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:48-07:00B,Q%tEXtdate:modify2010-01-11T09:46:48-07:003q¯í2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-pm.png0000664000175100017510000000515112370216245030113 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœgIDATXÃí—YlWÇgÎ,w|¯ï½¶¯}íØIlÇ7M'RÒ@K J[ TTà%‚‚XÄò„ªè }A­(Aˆ'Pº@Y„ªÒÐ…6¡é'N½Ä‰÷뻯3sÎáá†$-…J Š—þ_fÎÌ9s¾ómú ¼«ÿ³Ä|ûÃóÀÒ;kÀÐ]‡ùâ‰G%ƒ·ßA´²ÂâOîáî Ýå“÷îq@yokì'cÇ"“ÛQt²ía¢È‘"SÔh)´í7qƒw+àæm).^~ G›7/hØøý΄ŸÁìw=¹¶91ìë'F»,?OùvùlÃ8 ¤ßrC `F!ŒÆÖhEàtƒ°À€Ð!’ˆHÆÞluÙ¾í…Ò¾?Ntñó ¾“vÉ«?»¦[…|ýxñ½ƒ¹ù´Ì¥X*À£M"Ü@·š”â£l+g_÷,¾®ð÷Úf“×2Ð8ÃD| ¯]àTc9ó¾ñ„ýåýŸ4‡\ñ|®öÎq¢öׯ?à g+äzÚÜŸH]±@`EMrùÇ8œz^ÖùSíeÑKDTÊ!ÑÊ ÚN"­<éÆ#rY\fF%ðìEÂî,Zº— H¿ÿ°Øç[$²q2‰>â~7GF²³«EE*q®Öǃk%îÞ#NR,+Ê:I¥göÔÞ‡·&¶ªx|Q4“=¢73`>pú®Ú?N~ 5Ñ:VéÏ«(¦m°È²ÌÍ#¯0>¬yôôVN×FøÆäãÜ:±ŠíÀr%ÎâÒ;Ë¡ÝJÁ^ÞCIôrûÐÙ›ZäÁÓWqoý« ö×|ÊËdMao<¶ï“ýì繺·!ÄèJy6:>«ì&tH²¾@»Tæ¹S^ÞŘwž#Ãgq/æÕR=Mè¦Ø7´‰”°^ñxfeeºx|s?KyÉ‹Á^ªÝcÈô÷‹é3§Åää$år™ÙÙY¦¦¦XXX FGGqÎ/Òl…ص JÃ/N^Mw{•9;ÉÍ{×Étµ.%i-ôpŠôù-t+K­ ‚Ç7'˜­¦{£,ÐØZk¤”h­B`Û6J©Î3)MFâÔÖ@E”Ý!tK2Ù»†©ÆH[);/Š@5$Ú+DaÄéeÁ«ë.}чõ#dE™§åuT½ìå*X[[c÷îÝ,--áû>¹\ŽÙÙY†††pl)æ¦V “? ñêÄ¡+7N#¹œg½¾…§_ï¡TVHQ š"Á‹ó>¿{)ˉð ;Å)Œ,°¦˜“S2~Ù€b±H.—£R­ЗÉP(Èfq…C©XM;éŸdáFý5úS6ãÛ$Ùþu~y¼›{Ÿ›âB˜¥Iöx34Ý+£,±‘LÀ§G—Øž’ühნQ×c„u)dòûwÞyG¥\&Ûßë8ÔªUF†‡QaHÐn³á¦Õ‘U“IQqHRæz÷ÆÒRŠYÆjK(IÝé£[år7¹n`Ž£{O±w¸ÊÓë;¸¿öòîö+[qË®Ýw_”ßÜÙþ~m*ժܒ5¥BYè(2á–} —Ä’ü%¢XJÁ+¿âÐÖ p$·ÆMÎ%ÉjÉfl0·#66 ª /ž†¹uí4;Éb4X¾bçï¹Ë¶&….°,ƒlBi „K ÏcjcGLìæ¯DZ±Œ¦ìtsʾŽÖ xòQ®lR‰â ÊM|W è£Ö0ºÍ\cU¨±¥{ƒñ>Ÿùب÷‘°uÛ§!}a‹ ±!‡Ò§hpú Íih6®0rL¶DOD‚þæ:¾#)|„ßÖùÛ:¬Ú#¨=‹¯›<ÁMô–6f™âÊi1Í0ÃnVÝc–¦í§H(EÌT¥mBAc^Ï(¢¢ Q±ñ“aA€ §‹9 '“´I‹×–”Å“õmh¶ã°ê¤×Q¼Ts µaGBb¤ÍfK1Ýš¢Ü„ ëYCC5PÄ„Æ&¢ËœiDÓ RÝ4è5NÚ‘Á5éD ˶0€ºd|‡ñ¤G¨]JöôY¸Rj(´B’®EÂñpZqGÒíHZ& ÐŽ´ÀüA×lœØh¾­VC\KÐÓeSk+fË-réý¾Ã€ïàJ‹Pê¡b®Ü¶Ûº=<Ù)µ¤'Áº‹fd8SjR æb!ּؘ…ß«‹‚zEâwE„eq©X¤%Ì€ï°+C”f¡Ò„j¨Iº’mI—ñT ¤=›f¤‰I‹´+Yª,Õª¦iôhh c~jæ­eƒi´†úÅ­…Ñ#t;ÒbºÐ[ã6¾m±Ò)µ‘Ö Êj›ŠÁ.‡¸cq®Òf(îP çªm»\KtNþF&lÛÀ·DË [Ú‘è‹“ "ú'†@;T¼¾tF¶ÒºDÀ@†r5mÀÌo˜? 8ŸotæÛÖ›áÞØ@í߂󕲸Öeô¾òCB€¤Ó\ŒéŒ/cdç^ðÎüY¼«ÿUÿÐó 3lï%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:48-07:00B,Q%tEXtdate:modify2010-01-11T09:46:48-07:003q¯í2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-kp.png0000664000175100017510000000166312370216245030115 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœ±IDATXÃí”OKTQÆçÜsgp¥ Ëѱ?ƒ$‘„"–´„((³UôÚ´ëC´é¸ "qeZ A#JCJ*ÑÉV:çÞ󺸴óÚ ¸‹î³=/çù÷¼ï¹rýïRÁÄt¦¸”5À‹LDël;ð¨¿Ð\¥Ê?€úvç¾k*”cÀ9ˆcPÚŒÚ-÷¥$OÖå«#¨ŽvÄZâOUâõψµ ØIêg. BP©Ðöä1fd»°ˆDıÿì9×K ÒšÛÒiæªX$»Žî-UW9x5‹}» áÍèÓ§¼˜T€Žv‚‹ýØ7ïhÌÍo~Åmí~ÙHÎÅ}ÿqâoÐéG‚.•(ÜGwv‚µ€Þ¾…¼ŒÒºi“Ö; ²÷‡¨ºJ¡§„êî¢8õ©×ˆ76‰·¶½ a:Àþ—3 Å»ã˜+øíì‡ØÅ%ÜÏ_~¶àŸkØ]"¼6Š®œG~ï­¼'ªÕ ŠðÇ€“Ä'’©÷DæéÀƒæ*ÿbzŽc3]kø½±UåÜZ¦ÀdÖ™v W®\‡·<”ºèõ %tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:47-07:00´dg¸%tEXtdate:modify2010-01-11T09:46:47-07:00Å9ß2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-zm.png0000664000175100017510000000156312370216246030131 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœqIDATXÃíÕ¿ŠÔ@ðÏìfs{¹•cåÄ9ÁJ+;_âÀÇð%¬µð |K ÁFQlô\T´8nÿÀþKÆ"9V+›,iò…&æ÷aø C›†nG+FÅEˆŠäþí Û§úÔlZ@ h- ±½¼lð´iÀ¬I@›Æóîùuæû –%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:50-07:00½iY¨%tEXtdate:modify2010-01-11T09:46:50-07:00Ì4á2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-io.png0000664000175100017510000000501212370216245030102 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœIDATXÃíÖÙo\Çñï]|g÷ŒgìñÌx›Øqìdœxm›¥i6P i Šò@›¢ÒB< !úÂBTð€x@¥ª@å¡ê‚€6i”(I›¤iJÇñnÇöx™ÍãY=sg»s/mù@"ŸçstŽôÓ‘<ðÀÿ;!þëßÃã¼~+ÍëïÜb3‘GDNéàÕÈe~ÛvŒ¿^ßÄ0 n+/ö(¼hÝÆwtçsßB2+hu“›\½½Æð^?GG:±Y Ã`æ~’³W—\?ÔÛi \Ñí­ûÒ­­L…—ÙÜÌÈ |µ¥‚( ×t";sUźJÃÆ:’Y@–Dz½‚@o—›Uù²W ·ËÃQµB ¥ñ?ÃÌ&yvjí]Ÿü9/ {ÐË!.ßZ#+c†ñE¡®èºÛ¡p¤E䔫@Kpë{úa1IkK#Ù2áÚí5z½<ûD?ý»š)W5Î^YâƒË ´y<÷d?ƒ}>”‰p4‹pâÙ׌c­G»ý>>-˜øÇ8ý.‘/žà»3½¸Å7½:ã»XºÚù¬ pnz›µŠ¿ÅNQ­QP+x\V’iI6q°µUgieËL©¬³S¨â÷Ú1+ ¬Ç²È.¿›³Œ«.s4Ÿæ´ßÃ×0B&žFž×縱4ºÚÝ”»º¸¼˜eú~Ÿ=¢©"mÁF뢹ɌfÔ˜]ÞæÊê‡h’¡Gl vûém ±²‘áæL”|¡Ì‘‘N„ɧO_­ˆ ëuD³ £¦¡ÎÌ`éÛ Š (h†A¥¢a :ÝÄŸ9ISoLNåÌ'KÄ3Û„FóŒôïbrãI5J,V¥kÇoëex÷.öÁÊfáÞ‰ÓÆWY›L2² @µŠ¡ë”î` õ!44 —+h¢DUÁ0ˆ‰Vþ`ÚKT°Ð ‰ìß㣷ÇÂôöUÖJÔ…"UCÅ%w°¯u€¦ú>ý,O*W@Ótä×ÚÆq:Ì<2àXoæµUÂiJÍ^<ï¿ $_únŸ›æÍURñ4·ó2·¶jÈV ß=ÔGEÓ±YìV…ɵiD šÖs1l&;#´I‡¸Ú8ºßB|»@Q­ât˜‘‹&;‡zÜì—TÖ/-ry)ËG >™Ÿ"o]]c>»Ês#>Ž8š(ÄÉó\‰HT3{|„#Y®M¬³SR1¹$ ¹¤®•˜X s#›¥’ Òîö3òc³6péÆ*ÂÊ…ÏŒúÒ2w£E.¥D&Ó:ùrÃ^ž_¿N]7x»óg'·ht(< ðÔ>}Z–åÙ”˜M–q;-<ýøúºÝlîÌ31»ÅÖj G[œÞqöõ´ Ij©ÆÙ«‘ =nFCEBÓt¦Ì­$iqÛ8<Ôͪ éŠÿü Âò Q ü¶§ޤXÙˆe¹=#W¨ÐÞê@øé/Ïwç㈂ÀH(À‘áN\f¦|tu‰B±B¨×ËccA^áH–?^ ºµCO‡›ñ‡ƒìjo"-qæÊ"ó+Ûš-<˜#茠pwÝÉù½Ø6íd¸ßI‘YZO!<ÿê»Æ#ƒÔ´:7&7G²èºÇeeüá N»™›SæV’hõ/ÎíÈp'Á6S &æc”+JƒÄh(À=­¬l¤Y^‹±ËšQFpuÓÝå'‘R¹~wdFÅÐ Ã@¸xcÙG²È’H‡ßÉN±J¾PÁí²Í•)Wjt\Ô´:©¬ŠÓa¦RÕHçÊtø‘e‘­T«¥I‰%wð5ÛqØÍäç® J rç‘D—ÃL‹ÇÆvF¥Xªâ°šŽ¿ügC-Õ¨ëc¡­;“óqV·Ñu“©¡½>ºÛšXÞHsg.†¦éˆ¢@h·—½Ý-$3E>ŸÜ¤T®a=zb”kpiÃE&§bð:ÙçÇfU˜^ÚBøÅï.Ì?܃V×9wu‰³W–HeU¶óÊÉQÜN ŸÜ ó÷‹s¬E³ôíjᇧFé z¸5å½ó3Ì.'iõØyùä0‡‡:YXÝæ½ó³$Ë4(2>~ã{H¤ŠüíÂ,×n¯±S¬â÷:öÒáS-MVB=-”«uÎ][âÔ7B|ûÉ~†öúE7Þ¿ÃSöð½gE‡ö·a³)¼öæ§»|ÕÌk5žêùº99ˆt ÚŽ%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:46-07:00l %tEXtdate:modify2010-01-11T09:46:46-07:00cNÔ°2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-dm.png0000664000175100017510000000203212370216245030072 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœIDATXÃí•=hSQÇçå¾—/ˆiR1¶~,¢ñé¢Uqp\up¨à (Buts¨]uv‡BV)ÖV µ–|ˆ$BÒ$}Mr“ë ]œÞ{Ì.ÜáœÃ9ÿsù_2äG¸u6X†\ªÍ““EfW±ÓW¹qwšë/ò©¼ "Ê)àÐ PÀ«A70P¬Ð™fëpï+c@ožÕ¨Úħªç^ö-¿îô°¬B«¯Ù¾Ù¢”Ú Õd6¡¯2èmôœˆï5Hþó¼?½hy¬Ï¼€wy\Ó§ÞîN­ÆZç&IÞœ‚d¿[?˜ò½0Œ­páÃÒ-MÂÖÔ£Ðóë1Åë㣬íO{„ åÕáð% ú˜Í=Ï£²Ô'j’žÌqŸo¼·èr3P= ùãd>¡´œ+ æ²%ò÷áܾFiïÚ V ‘pN(&nøiwqÉÒŽÃÿfËpÌoo‰CgÿpiÐ T!C†üÜɳ!°ÕÖ´%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:46-07:00l %tEXtdate:modify2010-01-11T09:46:46-07:00cNÔ°2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-co.png0000664000175100017510000000121712370216245030077 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœIDATXÃíÔ± ÂP EÑëä—é75LÃD´¬@Ã2È4Tˆ–é'0Æmüð‘ýdÈȉ6 * ÕœM@´iø™€Îž€$ t¡¾Êí¹i& ¶‡“ (wíUv \Àzþ.*àøg÷ºSKP¹þ+Ü׺_Ùø˜€Œž?äBlWc›%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:46-07:00l %tEXtdate:modify2010-01-11T09:46:46-07:00cNÔ°2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-bn.png0000664000175100017510000000300312370216245030070 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœIDATXÃí•Ën[U…¿½Ï±'vìÜì(%NÒÄ&TT¢Bj!ʈ#F è#0åx€ŒP%$&q)RiÕÖI|‹siÒ\ìããËÞûg`GzáR$È’öèH¿¾³ÖÚÿ†3éÿ.–& ¨Áyºò‘Έ€Šü+øÊŸÿD\$ܱ1OÍ e‚ë‚ÙÀõî!¦„Øb÷AÞê$Ðß ¦DDÀtÀ!vgªH¯ˆ˜5Ä”» v‘Ä(LG?ú—%‹¸Üb·SAzëˆ) ¶Ø»}H¸ÙfúŠÅ‹É §þ¸KþÍ›?111I*•&£”|òPzô(ÊÏAìrÿ聾È&XãÁh”Êd^ž!:´3Ûˆ=iöDdò¯]»ÆÌÌ ù¥%ò…ù|ž\nŽ©© ‰‘‘h¥”³#´÷:4oG~ÁÓË„µ7ñ i¢©ŠÒ[ÅõVSCÜ}pH÷P 5­5±XŒT*Éôt–……òù<Ï Ì/œç\zœÉñ "Ãq*J뛘êx¹gH¼ú‹ï¼M/h =ËðäâvS…Þ®WDl1up{ôo^5WÒé Æ>lçi‰Òé1^LóÆÜ,Ÿg¼’¸ø±µéôÙ«+„·ï1öÂEÊŸÁôk+Ì\]91Ék!Ò/¹˜¾Kb*¨?•RÕroÝR©Y¶vGŽV(8÷눊wc㨸&’ŠðUdˆ×ݳ óØW.qiwßDð»ŠÅ÷ßc²°ˆÖÞêgú„¥¬ôŒÐh »{ŽÚ¦c½b¹»j(–,åšeg×4…·$ÅÄÇüœæÛz›™ JOÁ~RX97B}GŸœfëÊó–—É/-1¿°@&3Íèè(Ñh ­õo0TXÊŠRp|p:]¡÷÷• KqÕâý¥RwŒ‹Çeo{¨qJPÃŽÏ4¹µÝE‹âKàE£$“ ²™)rs9 ù<ùBÅÅ%fggÉLeH$“}€Ç.‰c(ÀZhnAé†P¿î“iGÒšN(¶ß=hsý¨A)ì²Û³ü~¨ÖŠøpœ±Tšìt–ùù9r¹Ü“&‚fE±ûµ¦Wר–Ɔ I‡>ç(';|_iS\·”ª–ÍmÇþ#h=ºäZëSwÚ€ 6èGæ%ÀOžÆ@³åØÛê[–õ²¥X²Ü]³”«†ÍÇQChwú%ÿSôŸäx?É`™È ¶A|¨~Ÿº=!hÁÞ¾£ºaY+[–²?Ÿàô¼}è°s¶…£† ÂRöÂ? ð‚ˆ:¢ð[Oú·Ê¹Ó§¦3ý÷ô jÆß{ÿ%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:45-07:00#ûv‘%tEXtdate:modify2010-01-11T09:46:45-07:00R¦Î-2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-kg.png0000664000175100017510000000177412370216245030107 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœúIDATXÃí–ÍnÓ@…¿;3§$"%‚j Ýu×ygàeXR$^€6$~D¨JK«:±cÏ\Nì& È z$Ë æ|sîÜ+íþwÉl°ß*€²¶ž· ³Á~h;Ó&Àææ²ykJ7"ÛéEй!^Z´0 ÿÀ€V¸½÷¤Ä k@‰ßõIF=íOÄôXǪ̀Â?Íñ“;.·:nêžåaÍò°OüÖIN"@º·[â'9n\RO3ð+—Âàö D@ÏË+‹ÎÓ®W2€¹p»v\¾v_:Ôï3ˆ‚ÛY"½€}Tb÷ ÌIF˜û¿œ@?bF5(è [ŠéÇæÛ€‚¤§Mw$”! @þ|×ÇZ²gW`•òå]â¹Ãî” Ú<©É&­ÒU«90ййÁ<¨°«&‘í€8%œ94OoÇäÄ–ð.#|Ìð“kðJõ¦×lò¸ÄÌ Ÿ=aš/Ò›+y¥. ÕQ3¬£USñJøäY¾îQuÑEú€MGUˆ§Žå«>ñÜáv‹æRñl5ˆÞv ³Ää]ל„A³ñÒRgȪ 47Ä ‹ÎíZæëÄÆ0äþWw¬9ÿ7ø]ߨÕ›^´ ³ÁþVÛ ,Ú¸Õ­~ãÉüXXÞ³%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:47-07:00´dg¸%tEXtdate:modify2010-01-11T09:46:47-07:00Å9ß2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-tf.png0000664000175100017510000000262712370216245030115 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœ•IDATXÃí–ÝOUÆï™Y–XX H¡´-%!MCbµÆ¯h¢ÖöÊÄ ¯ü¼ðèwMLŒASÓ¤jH‹‰X+1˜¦‚¶i‹J[Xvgwfç/f»EvÁÔÝDcú$g&93ç¼ÏyÞsž÷ÀcüËcLQ§1†B·€)=x‡þG%üí´(U2ˆ#O¿åa[e°?¿8ñêèøµZíkËc÷vªwÞ|ÖjŒÔa¼…%ÖFÎ+oqYÁoŠZ#iµ¬ªB‹Zëò ||áÛáKW®¿DÐÚ¬­ÊÛ¯?#Õá0é´8—ÇŹq%‚ÓÒ"¿´tûÚ¯ìè€Î¸Õ9_Ç€¾Æ×APâåÀuA\?—«Dl @‚Eü»ÒP•ŸòÿM ò9°ƒw¼m5ü?R´Ê&‹FªbÑz1ŒÑÔÕ„I;Y6Ó qs8 õdc1”Ù†|µƒ™Âc›p;+g{9µ9Z/ýî.ÅùàÌU!ü´ƒ«šÐ]µàYSI÷¡j…BUÈÂVÁÁ2€äSæù>nÎ/Mà‹o&ïxhiÆ095³ujØnÇÛSa –¥xqx€CýX–B|­q2Y.ŒM29=SR ¥ó+/´Bâ´|À­m›ºMO‹FXޝ³OЭçäKCt´ÅHn:$6R´Æ‰ÔÕ)Pö1´-‹Ž pêåcÜ™[äÃO.rþÒ^.Æ'o°™Êðî©ç9rè@Ñx‹æƒÃÀq üäOÍÊê:O6ÕóÚ‰#„«Bô슧fèl‹ñûü2kÉó‹qÖ’©¿. \´1Lßž#Öáý÷Nrôp7+«ë„l‹¾ít´ÅHl¤9{n ×+®!sÂþÞNÚ[›™ûc…Þ}ìî «}wfìëbok3¥.?å§€ Y×ã§é._ý™šê0]{÷p棯8{nŒë7gYŠ'ȸŠ”¬gå~’ž}ÔÖ„ùtô ·f˜¸v‹ç†úùufžD2UÒ*B P”¥PJXXZeå~m ÊRµïà†#àùš±¦Á¾ý?zˆÏF¿gäËïðw©!6ä/>• ‘óÁ≠nþv”“ vþ.µ@è9ýp¨¥d%yt<¸ÎœuØÀ×ÀU*XìÖÁ‘õ·³Ú€“o•Ã.›î1þsøQ€9ykñ#%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:49-07:00ä[å%tEXtdate:modify2010-01-11T09:46:49-07:00•¤Y2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-cn.png0000664000175100017510000000163512370216245030102 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœ›IDATXÃíÖKOAÀñõƒÁÍ.¢áŽ"“ Bá0º¦099I÷½{(e%¢ÅaÅX„¦¢Š¬’9}ÖÓ¶Šóz2Eæ‹eeålpt2eèxÑT€t:ÓédÜÐY{¸“Š’2žfFžs'¬§måçc:MºÏE¹%-]‡0‹‹ðx<¤ÓiEáA?áÄöýÔ¬¨CñѧRsBdB`ª*…I‰MXT[ÀËE*•ÀÐuü>ž¡0õ»·óFK3š/„6‘xiÄ߀M'ã ’ÿ0ÂÆÝ;©ZÛÌ ßO<Ë" ƒp(„ÓãfiÛßÛ £QÔÈ#0s7ûÒ€Ç@Å °ævÞܺ…ÁPh$2³-ÒãtRÜÔ@óž]äÅ(ÃÁ0fÕž(5:†Úï¡¡±‘æý{ˆŒÇÂ0 ‰Ý÷ïcT–Óê°cÓt”`xV1}&!ÐI2}.j««YèCbéi~?Z.¦’$ÑÓÓƒ´ Ÿ‡R› Ù|á„<C)‰LŸ‹Ê6Úºh p»ÝȲ €,Ë8NF¤$Í;U˪‘ÒôsÏ䦬qy)’UÚÙÉ_º·Çƒ$IhšÆ ×‹t”ú½;YÑØ€ê¡OL>ñb€ÇMCöúy-csÇ>–45àöxH$@6!@€>¯‡åï¿Ë[í›1Â#¨cñyä&rx¦eÛV–·mÄ Fg¶EFGéè§tMÍ»¶c‹¡ŒD²Sôݘfr®ŽFѼ¬^×Êê];G#<™IH<£ûÞ=òëjXcï `:ƒM 1{ÀÝÐ&(ܬ¨­c­}?RS ] •Jq¿§‡Ì¢…´î¤Èš—MˆªÎ ^CèÉéÞª/¦íðA$‹Àçó¡( d=½½Œ© Í;•Ⱦ †”!æÈ!LY&=à¥T7ÙÜuKÙb\.×Ì ÓT—ÛM(6FÓ}¼¾r%Š7€>•ÂzÚV~nN€ÇE%ãö±01EûŠW®¯—d2‰]Óðù| ÔmßFýúVô‡È¾3à1BÓHÞü…òŠ2Ž:f …Bâû‹—Ðõì_ÓºïÞå•+¼ýõ9*Ž;LÑ]ºÊ6/€BŸ’0ó~¾ÎÝéIŽŸø„É\„€L:ÃDb‚+W¯ò‘ÃAž7€ib±P¸®)ßÂown'#gr¯7Ðu†ÆFj–T"ýþç¼ýªþ»õzM†[n¯™ä%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:49-07:00ä[å%tEXtdate:modify2010-01-11T09:46:49-07:00•¤Y2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-ws.png0000664000175100017510000000160312370216246030127 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœIDATXÃí“»JA†¿Ù «1„xA¼ (ÁÂÆÊN¬ŸÇðMD_ÀJlDlL¡Xˆ‚x!1“l2;ÇB+ên$ˆûÁ;g8óÍ?³ðßQäÖ>)@6íp_ö‘ºÄza—q]BP‘`&¬ Åûêó‡m±ÿ·6 ¶­˜àèôȯH„' ‚B1Ô—àøìǶÐÚ`D~¸Å×o6†LÚcj¬—³Ë";ç€Ðédan„½Ã ®ïÊ Z…ÕttR.¹É2]ÕZz#@D¸-<â7Z}ïPŠÛB…Íí<5_ƒ@_6Eo6ÅþÑ%Ú´þ8Í1t“Ö¼£„`0çÀXÎbnÒű Jµ”b˜²Qj 4ƒ° 0H>œ?Êü©®m'ŠÕ­˜oÿem§Î­õˆ0ÎúR¥-€¦}Ò¼öï=‚'½õ©1É‹ÇF(VS¾Y,rs­ÆÍ"vª ™Òt³ŽePÈ™lWSÒLïE¡5rgžmqÞŒÔwM|×äã×& ë7VC>ÿnƒ?þ»*Ñò'­Á± Þ:ðúóF]¥Ù}43ÃL »Fd›‚±œÅËÇ}NN¹= ¢E! ¬glV>xe‚ó'|._/²¶SgrLòΙ€ñQ»wbW 掺8– ‘vNäJóË2çæFy÷¥qNá~9a&L$¶Ù_Bà{B´ÖÓp@a¬øúF‘‰¼äÕçòœœòúrÚ’N ï™<=î°º“v(F£Ýb¦5¿ÿ²°\!ÉÔÀΛœ›óùôíifÇ:†¶hÈ9§¦sHË`Xó¤Á3.9Çx I¿(xÁˆÕqc¿&Mïšk -€°]MøâÊ+›ñcdJÓ­µjuÅ·Ëüt»ŒÒÃÉ ”æç;–Ökƒ4U¨§Š+VX¼W#Nc¿<Å0å·•*¥(ëÿîWâÚJ…í¯Οð9>é¡”&Œ3žÊÛ̾g2HŒ}2¥ùþV‰…»•®Í°çmXO5KëË1Ò 4+×6È{o¼Pà“7§ÉÉV7Kë—¯)VÓ®wAO±›¥5QCïESI3©¦0b!éŽJÃýRƒ/¶X¼ö¼’šľi ʵŒ–ÊøžI1LÙ,'üº\áÚÝJÇî×ò›ù‹W‡ku»@ŽmàÚž4ˆЍ¡¨§ªãLÑNφÐ@ÔP„õ‡Ps>ìw,³€ Ã4šÃN¤»ÕÇxbÿ{ûÿá56¸ÈÍö%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:45-07:00#ûv‘%tEXtdate:modify2010-01-11T09:46:45-07:00R¦Î-2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-uz.png0000664000175100017510000000152512370216246030137 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœSIDATXÃ픽JAFÏ7;&&æÅN°Š…biékøp‚……µ…•oa-"("þ@Lvv®Å† …HÂÈ îéfŠ™oνw ¦æ¿#Ž/æ‹þŠ'sâuˆfh:‡0AˆF0KÀ{˜ñ6™Òô›]`À{gI ’ðÀ9ÀªÏôÚ¼L÷ãwÌÀ 6šÒ€Ê»‡yÁ8é ì¯wÙé·¹¼{"8 /á(ÌÈ$¤²© ý6£Pð<ÉÁ ÛÈhû †ÈTêWòH·ã Û½ÆÊ¼Öù¬×¢Q3‚D9üÖhf<ÞŒèôÖØÍsB4òh¥nAa¥%ñ©™ð'ƒÍ/N­ù|Gº!YRž·D€Ÿžûˤžª…ñ„Xm€««ÓJèàì°ÒðýtÿúRœ¥ýZåL\Wà¨ê•¨©©ù¿@{±Á*%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:49-07:00ä[å%tEXtdate:modify2010-01-11T09:46:49-07:00•¤Y2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-gq.png0000664000175100017510000000223212370216245030103 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœ˜IDATXÃí–ÏKaÆ?ßwfwÚMsµÔ•,Á@IêaP&R‡‚‚]:EÝúq–èOˆ cÑ¥sAB—ŽXöC)‰Z]ÝuÝuÆ]wæí0ºj¬?Öd·ƒÏa†÷…™çó<3ï;[ª°äȃ(–«€iªt­h]!€xº÷~}õ åTàWòâ%%õÕýˆÌ•@e²mŒN^a"s­å°sûø1qxúTÙ!”ò°s-óMô”B-øM\-kæòábJ\v¼ÑJòü½BeÉqQš¬d³Ø¤ÛËèä } ±Ç=Ónx–±¬(´vñò<×ök4B(³cs@3“m–÷?[óQã\{ –)…Í*Ÿ“š";碬€¢fç~Û6 À/th<+}¯ÆÈ{…Ζé׮̱L/¿ö3žçlÛiº¢DÔº´úŸÆg¹×ãõ·t¡QAl×c:™À™J“Õ ‘`Éæ«6P`°L!8Ÿ^kãØÔZŽÖ&—uhíÁqÂÛÈȚ¦ëo8¸;L_oÇöVá´4‰D‚™ŒíW¤afÆ&9•Doà‹¶bt6õÝ“»tokˆ€7‡výùp0@ M]}ËP„ƒA$Ÿ/y)® t¤¿sËþàu=dz ÅÒ;hš\DZB¡JL—œ¿€í©an>æxü1빪X*AXxÜŽÞØ&T@hO sóãºÇÞbhMñ·J£Ù°k1€…äwÑ=6€é›ÿ»ÃR‹ÉGæ“`j¯,æf¥’%>ëë_ž–=yàòȳ‡Ý±LÏE—¸‹m†äwK}•Ò9UþÿA3nÕfêr©Š˜oé¿ÐKî©bÖ%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:46-07:00l %tEXtdate:modify2010-01-11T09:46:46-07:00cNÔ°2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-re.png0000664000175100017510000000132412370216245030103 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœÒIDATXÃíÖ½mAÄñÿ[n qDL ¤4àpn€˜*e‰&ˆ¨‰ [;øÈŽ]§MÞH—=~šK<•cãé*{$ÁûÛ˜ÅÇ„á "©¥ÍÐñÌy¹â{½³lwÓ 6Ê„X¤tµPpÿò€íîòY²Àþ7H¯Cì%bmÕf¨‰"„¤"Àé’fù?2ÔDˆýç·±W4ýP²SyÝíZEëþQÛIŠ]Åp€àT4>»|ÕÌk5žêùº99ˆt ÚŽ%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:48-07:00B,Q%tEXtdate:modify2010-01-11T09:46:48-07:003q¯í2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-sk.png0000664000175100017510000000211212370216245030106 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœHIDATXÃí•ÍKTQÆï½gæŠÎ‡3i‘(ÍØB¡ ¥6B.Œ+¡MA«þv-ú \A Õ"¨D„ڥÒB4ÉÅh4£Î·÷ž×Ó(¸Å šguι‹÷wŸó¼ï†|–h­}P@Ìoû àë~o€ÛÇ«T‚ pÃp×Z»ûh"ïÕª}8„²ÿáí;1܇BZ[ahææ “@'fïú ­Mb¬îÜ›Þûñв”\˽7ú¦¦ šš •r!*X^†µ,«íI=¾Ñmçwm-â`ôáì¡kÐ"‹ ÝëÒ'ýý02‰ ƒeÁÓ'|ÍíÈø³ysés ÓC’Ôé2DP8`!„…ˆÇaqÑu!B96¦xù÷ýZGNÄ͘€[<‘€ÎNˆµBG$“ #h¼—ÿIÔmÍ®aA¹ ccØ'Ú(¤oÑ2ùki›ÒÙA*•cìûåªÍGâ¬Ä|ÉäÉÚxùfl”ÞZ§¢–ClfmÏÊäð[ 5èZéÍfê©´L8¶k[ 3© ŸàJo3ÙjŒâNQ+´'¹»z¤ µÖ4YŠ®¾nyì1&>Ù”ËuÌ€ÉÀ‹›áU½53ïvªxÍ¡ÔÅ8~Œh–f2/ó(~‰×[·«Ü®Í’šy…ä×½ý«9fÙNö°ÚuŽ“ùÚ—>@±è½òo|—2Á¶=]oIÿÄsì« õ@4„ühèÿÖ7¬ÉÎ`Ù%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:49-07:00ä[å%tEXtdate:modify2010-01-11T09:46:49-07:00•¤Y2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-ae.png0000664000175100017510000000134712370216245030067 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœåIDATXÃí’±ŠÂ@EÏ‹ƒ"芅ÄnAÅÂn¿DK¿`[;ñ‹$¿’rKµ²”vÕ̳²3lšÉΩæwçB ðîHÚŸ¾¾P8ÄWÖ«ûø êFÀ3Ÿ `ç[Àk‘ÏáÏJQ@Ñç¡~†DtL×~4 ¤nE‰Û±n¾¾íßh ¨ƒòTé5{²øœ›Ödìf}*”P]}~U×x(ï€Y–i’$ÅïÐ] %íO_¾,ÀQïl‹³=R µ'XkÉó<ºØ›£ñÿt@W»W¨üøXúðš@ x0@”Õä!ÿ%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:44-07:00…Œ}%%tEXtdate:modify2010-01-11T09:46:44-07:00ôÑÅ™2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-ml.png0000664000175100017510000000127412370216245030111 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœºIDATXÃí–Á B1D_â"¨¬ÆR´K°Á‹…6äMAošõò?ˆ Aù ;rÈ0y»§PÇJÓݬjr`1:³fÇߦA¹&ë§}RÀ€I—0`#zï@¦>—Å¡',æÚÿé)ƒçб4Ç”ÔZØëd_÷~ð@@@@Z{ñ§»æoß B/6`+´J't´‹Kq[®6ÍÛ\D€Ðêü®%BßeC.%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:48-07:00B,Q%tEXtdate:modify2010-01-11T09:46:48-07:003q¯í2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-be.png0000664000175100017510000000126012370216245030062 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœ®IDATXÃíס BA„áS$H †R¨,`ž¦ ,EP @‚E¼{’¼9›u—Lv¿“(p<¬9[VËù;Ç3áô€ëk|ÏL6³÷ǃ‰´=[Ë\¨}ø aq’|€… ØI¿ê Šxœ¶4…ܦð—1À 0À 0ÀzJ)¡e佸‰Y½E_5Û‹€ µœf_9½KKCëeSV/Ó±!|jìóD%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:45-07:00#ûv‘%tEXtdate:modify2010-01-11T09:46:45-07:00R¦Î-2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-sa.png0000664000175100017510000000226212370216245030102 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœ°IDATXÃí–ÍNÛX€¿s}Ç& $4  UÕH#u…f×E×]ÌÌ{ôMÊ¢Ï1P©Û.Gh­S*TÊ@ 8!Ž}ïé‚BÍÈ,8 ßkëøœïüÜcÔ,ÂÆz©h– ð¦l€ßË0e:¿ö.ôÆ ‚¼zEFzy•ÙŒksK<®-Ûˆýô'±1Õ B«:O3jðϠ÷ó¡_ øyþ iÞç ÄÇÓ=r_Ì $6æåʯ¼úé^•ß69èñ¸¶L+j–V´€luv©‡ [~{ú’î°Çæñ'¾¤³€•€fTg!jæ}æÂBcqxÔåg§8ïM@î [¥“u±¹!6°ß^Š M(ôŠuvøóè#N=ë~au® €÷Êr²ÈjÒ&÷ͨA¡Ž^qÎI–bMH+šÇJ0±&ž‚@ ^=NÝa­Î^=QPa­Öf5Y©§ïì¥X XNö{‡Ô+5ŒÌÜ„J-LhUˆL…“A—½³¯¬ÔÚ¾àÝ—,VØ>ýŒóŽ•äiÞ'Ãç³M’0F€~žM6ÖõV:0gcjaLî nHÅXD 'Y—Š qê±& ±Unˆª2píj‹Ì 9κ(:À8WÇy< Æûk:7Ì¢zí™Jpܸ͘ÿ7KÑþŽÚÿBl#B :žqWQçç.£ðÂöTF„çÍgÙåðücÌ(âëñ]ä£5xZ_½˜|z÷wà"»w6á•“Ë\O2(‚ øéŒN—1ë4¥0UíÇr/þ~øx[6Àë²Ò2¤tùÁ+ôÄ(9ú%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:48-07:00B,Q%tEXtdate:modify2010-01-11T09:46:48-07:003q¯í2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-az.png0000664000175100017510000000144112370216245030107 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœIDATXÃí”±JA†¿¹¬ЈE ˆ•¶Zim¡Uû€©|_ÁÂð ,¬|ÅÚÖÂ&DÐFÅ Ià ·;¹ôîXÁýaË™ù柙…¨¨ÿ.áò>(€¶C\‡ê@²øÔ‘°<÷R@Dà—ür±wª¾AIs³¹ŽË†½øš€T›¦ôÙõpÔZ)nû‘‘ß>àÞ2ÔZt0B­w/$:sô‡oag‹dcñÍ“§gêGû,ŸuÕ&ŠzåRþÀH_|F ÔZ)K'm\9ûžAaqƒ8çp~pè¿„i¹„ŸCŠÞk¹„ÕÎA¯ºþ›£: P¹ðLf\¯’`~Ÿ—Á¿ÿ¹*øà14Àqh€ DEE}›çnKεŸ'%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:45-07:00#ûv‘%tEXtdate:modify2010-01-11T09:46:45-07:00R¦Î-2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-wf.png0000664000175100017510000000213112370216246030107 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs‹‹uËû vpAg ‡úœWIDATXÃí•ÏKTQÇ?÷¾÷fÆIÂ,"臿&Á•„‘L¥µp C›íZÖ²¿¡@wé&\‰ mQ»¨°B ZõßeéHŽäÌó½wO‹ 7 ósàÀýŹŸó=—s-€@Ýხ’¹–€ÀP|D¾ÿ!âù -¬æd-‡Y^¥Ø¯é}G¨Tªÿ;€yDc@Jæ ЕóÜ zHBFa¦ ¬–F¨I*_9‚™9ðýp¥Jè´µ“V+DkPº¸®J+¤Rvlb½=8=WPZ#ž‡;ü3¿ˆT¸}ÖßJ.Y§–g ¦óF`#Ýx1Jk¨­EVVwI$ècGQõux¯Þât¥Ñ©&¼7“xSÓèæÌÜò{£\µ…®Ûº*HÄ,l[oA‰ïæ·µ/~€¬¯ƒlG V[+ñLîèSœÎâ™>òCH.‡Ó}‰ÂÐ0f%[öÙÉå¥]ÉÁĽËÖ8íày¸#cŸ¿b¾ý æÞÔ¡dÅ÷¥E)J½XëWªÜÃL€xœXoúôI¼‰Iì çpºÒßUØ¢ë p]6_¼ÆÌ/â¤Ïã¿{÷r¢X•‹HÞÔ4îøsœî‹$ïßÅJ5á>%ø4S±tÑh…dWqGÆÐõGˆß¼ŽÕš"~+ƒY[dž ¡Ñ(…É®b–~â\î„x ³ø}â8NG;æËlhPÙ¶´ìñºÊÿÒŠ£º@ ü÷ñEazoU=ð>P¨Tà µàœ4e,\%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:49-07:00ä[å%tEXtdate:modify2010-01-11T09:46:49-07:00•¤Y2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-ng.png0000664000175100017510000000116312370216245030102 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœqIDATXÃc`£`¤F†ö@"ýgHÔufèsIbàgç«öãÏo E{æ1Ì¿¼—á?#A³Y´2XV´4˜ÒòQŒ:`Ô£uÀ¨ µáµv@è@;`@C`Œ‚Qɬ Ù €%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:48-07:00B,Q%tEXtdate:modify2010-01-11T09:46:48-07:003q¯í2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-ve.png0000664000175100017510000000216212370216246030111 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœpIDATXÃí–MOAÇÏÌt·-¢P"*15àŒñ„G¿‚7^ g?ƒ_Á“'<›ÈÁ )‰Òvé¶³3ÊK4Г¶žÛîþgæ÷¼îÀµuÙäxuøüA<ÞKG ÐÊat ›¤Hœê(À;ˆ“€_å›ô†eRº†÷ãÕaW®x66³ì–ÆÊ˜¼U¤/Ý™(˜rŒ,® ñb…Øo±þ ‚Gx|Ó€R ßw5éê%7Fq‡(Üäþ%4ÐîLX‹=“ØàöhÓ»…`Ûï>`r!Lå,?ì2I¸N@…‰Œ#­¡í!0ÆhÝŠe,Y£˜ž´ÖTá_²ÿ›2ÿöµÇ qlM0Æ„õ¡t‘÷þä¨0P8W§ÄUwöíJjö£9÷Ê#îQJèïK¡•ð|6ÏQ©@®7Åç•=ç9,Öp®uãþŠèå‹E_áå‹;~FTªžJ\§ ÏÓ©îŽdùði‹Ã¢Å·X<ÂI™xòðƒý!ÇqÂö^…Íí2îd\*ÆG{ͧɄšýØåo¿q-0´4îŒVŒ fÈ,­°Q(Rµ›xlâ©ZÇF¡ÈÒÚ¹€‘Á F·6I›ªRF17“Ç:Ï—¢8¹8SQœ°ðeëIòaQ€]ûý‰üµ.h.CWøGH7àõúFÖ=îè lºUì ³¯ þõ¼CË¥|¢€bÿl$ ùE–_Uvþ%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:45-07:00#ûv‘%tEXtdate:modify2010-01-11T09:46:45-07:00R¦Î-2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-gh.png0000664000175100017510000000156512370216245030102 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœsIDATXÃ픽K1†ŸäR®Ø^¡`»´‹'øA7G—nNÅÅÕÁUÿg77ÝÁÝIp "8U(--µU+­‰CýÜš³‡¾K฼÷üÞË˱Äe:t  €´k€=×k.¤Ëþ€ u³ƒÕDv5½ñÒº¹ÖÔ “–ч藧´íÔR€6ptÚ`u%þõÌ6 ˆa_6@«mxìhÚφ“³WgÁ„ •”¤’bxÀá§*Õ7»\\õ¹¾íP©–ë¥8óI+Kû„9RÑÇ“Ðh-ƒ'¡Tô sž­]~LPù¬äfrÀŸÏJ ¡Â ´íÐØÕÐ÷uMHv·ÎË=îëš™„gÝi±s0g]ÃZSÓ~2䳃î4ABIÛßkBm.Gê°ßÑ °ŽþSªolJóC¸ý~ 2›1@t)Fö7£ì»Ør Ðq 0–s½ðb%êGL?%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:46-07:00l %tEXtdate:modify2010-01-11T09:46:46-07:00cNÔ°2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/flags/flag-eg.png0000664000175100017510000000147112370216245030073 0ustar vagrantvagrant00000000000000‰PNG  IHDR szzôbKGDùC» pHYs × ×B(›x vpAg ‡úœ7IDATXÃí–=N1…¿ÙÍ*$„‰2Hj¸ 7 æ{NBMAÇ@"¡H”µ=ègA2žf%Kãùü¼Ï6 Ê,y>¸È  À ™ú›Mn€[ Èr5þÑ@EKë]mò«™žÞß%€µ? œŒ¿çóN”$…ðn…m:€°„rŠ1H”n•²\QÄVO— ‡ÐKdz£¹ÛJõV`[¿`«Gdzƒm^!.(êsÄÐ#– }vÖë>R`fÝXùÀ@gÈä â ªc .{§AÍÌpý¾L®¡}ƒöŠdt£yç„s5Ò4ÍïV¤5]Š)¢G þH]×ùÙ.`ûí}E¢Û¿Óp(ð@ÆG©ùYž©ï ¤/N¾_†[ìát%tEXtcreate-date2009-12-08T12:09:45-07:00Ò Ëè%tEXtdate:create2010-01-11T09:46:46-07:00l %tEXtdate:modify2010-01-11T09:46:46-07:00cNÔ°2tEXtLicensehttp://en.wikipedia.org/wiki/Public_domain?ýêÏ%tEXtmodify-date2009-12-08T12:09:45-07:00‘½ÜtEXtSoftwarewww.inkscape.org›î<tEXtSourceWikimedia CommonsÒÂSš6tEXtSource_URLhttp://commons.wikimedia.org/wiki/Main_Pageü-IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/glyphicons-halflings-white.png0000664000175100017510000002111112370216246032731 0ustar vagrantvagrant00000000000000‰PNG  IHDRÕŸ˜Ó³{ÙPLTEÿÿÿùùùÿÿÿÿÿÿýýýmmmÿÿÿÿÿÿÿÿÿÿÿÿðððþþþöööüüüÿÿÿÿÿÿÚÚÚÂÂÂôôôÿÿÿÿÿÿôôô÷÷÷ÿÿÿ³³³ýýýâââ°°°ÿÿÿÿÿÿûûûçççþþþÿÿÿíííÏÏÏýýýöööíííûûûçççúúúááá’’’þþþþþþÁÁÁ˜˜˜tttáááÐÐÐóóó»»»¡¡¡€€€ýýýÔÔÔbbbÿÿÿÕÕÕøøøÜÜÜúúúûûûéééûûûýýýýýýÑÑÑòòòüüüøøøëëëüüü¶¶¶ÆÆÆåååîîîõõõýýýeeegggððð¶¶¶ààà÷÷÷úúúéééåååúúúøøøËËËÿÿÿ„„„ñññxxx÷÷÷ÝÝÝùùùÈÈÈÒÒÒìììúúúÞÞÞâââæææóóó›››¨¨¨¥¥¥ÜÜÜîîîÿÿÿñññÉÉÉðððÿÿÿÿÿÿÞÞÞÆÆÆ¼¼¼ëëëÖÖÖÐÐÐâââùùùôôôâââìììõõõ´´´ÿÿÿýýýûûûüüüúúúæææäääüüü÷÷÷°°°™™™ýýýìììüüüÁÁÁéééÿÿÿÚÚÚððððððõõõñññþþþøøøþþþŽŽŽâââûûûùùùÜÜÜÿÿÿòòòúúúŸŸŸííí÷÷÷öööèèèóóóúúúõõõõõõ¦¦¦ËËËúúúøøøÓÓÓëëëúúúëë몪ªóóóííí¢¢¢ÏÏÏÚÚÚÖÖÖ¢¢¢ëëëâââùùùUUUÍÍÍÿÿÿÖÖÖãããáááêêêüüüÿÿÿöööûûûóóóôôôÌÌÌÿÿÿÿÿÿùùùõõõÿÿÿòòòýýýÙÙÙüüüûûûüüüééé¿¿¿ûûûêêêéééþþþÿÿÿørOæòtRNSÔÏñ#ïŸ_ /©ðÆâ¿oS·ß?†ÅCá kD¯ÂÀOS_ ¥š²ŒÓ6Ðà>4!~a §@1Ñ_'oÄn¢Ò‹‘€M†¡“3±BQj™¶p&%!lµÃ"Xqr;€— A[‚<`‰am}4…3/0Iˆ¨PCM!6(*gK&YQ¦GDP,å`’{VP¤-êxÁ)hÝ7‡e1]ôˆßW¿³$—‡1ƒbÄzSÜ•cOÙÍ]ÀŠ–U;Zié»'yÜ"€âÐÐ‘ÝØ†‰K 64ÖYœ*.vè@²¸îŽc.};‡ïŸtN%¨DIª˜ÊÐ !Z¶Ð5LñH£2Ú6 ŒƒÉ¯ŽÖ"Š Ô-b±E,,)ÊÀ BŒ·¦>m¹ªÃãúnøö6pmŸRöO wm@°ÝÌVÝ#?É'C…È‘Z#©Žqž‡ìÀbÒÓ|$½:Ü)‰Â/E¾%÷ânR¹q—CàhnµÉ%õiÓÌ“­º¶¶ß}lƒm ?iÿdâdÃ"€,Ø­Ç`¬Hñ"r.z¡¼‹ŽÁ~ýìü(bðQÜU&ê½—)–5õêX#•§ òé™EMªæÜR<Í*p[€[%.©OÉÌ£˜¥k7“lIo°ý¨ý“¶ßJ°F  ¥lV!̡ăuH‚`Ƽ™€—›ç‚&¢,Çz´ÉRk$¤ò¨|$ölŠ»¼Xbü¢âéÇjߪÈdU±û?Σ$Hµî¸©W±¾$Uû'…ÆÅHÜE3*Õ­º€µµU\}ê­ý†(Ò ¤zhVk}gÇu«Rk$¤ò%¨|‰T¨|Úêck¦ç³"ãžä±Dç”ý«ƒ_W+‹®”Ê.QòÒÅ)Õ@«ý“ƽ€H¢À›Íbµs¸ÔlžŽT´©·Dÿô­RÄ2Xm£#a Ýêº3lYÃÎzÌj¹ŽÔã’š#!Þ 4þJ´Ä8Ñ(Œòcµv™‰¾t]­a·˜T™Çàø Ò÷D Î…à¼áQ?^-‹Õ_^$:\ÿìÞV  $«•N|ì=(vˆZ'q6¹Zð׆‡×üB5VìÌî!y†´¼3äßKœÿ㱿bàv4Œñxðëê£âR]al—í!ÔþIÛo‡P‰@Åt¥äVy”ºîàLïÿÙªmlµÚ¿I¨Ub|[*°¶lke'*¾WdîÀÝdà³ðïD·Ó}\W›ƒ_Wß´ù¶¤rÐNÚ?™øÛvÞ«ÁÛ²X%§Ž0u‡öoui*„üJV·€Æ¦‡b%†}ôãˆi5I¥YlNŸE-wÐÏ‚ûf_W3mþIåà…Äý“…—-ŒmƒÊ¬²Q)“S µÖk´«TC7êím¤<"ÄôÜŒ‡b‹T|ìÆ'¦Õ$µÒ˜Ÿ£óóÖR&>¥êO pœõºš¾ù…ê6ݬÒöçú½t±¨î¥S­ŽN\©×¯LŒîmÕø\ÈÎÑÊÄr@¦3žuT b7úÓt.5.q©ôÈ3²r0ü=™8T¿ªi­J©\ëÈ6uF ”²R¸32^÷íñ'ŪŠóÀí±xˆâI« ïÒF„8O{%8­žkJšÓMSÈ´dâBEdæÑè ïW‚CYÃ÷O:/OŒN/—I‹ê_=½€xFE”Ñ! Í=¥æi:oÁ~’¡· yþ?¶š'·š'·š[Í“[Í“[Í“[Í“[Í­–è».¹U>±$÷P–ƦŠc%†] Û\c©´:é| ý,e¯SœZ,‘oš¿XríäÎËXº!ëRæ”ÇÆò@áZøv‚ ‡0Ôç>?Á*ç® Ô<ðþÕ|ø«¼N6þ0ú¹;{¯ažd³ê2Ôév+Däó^tààúÑ[q!òÛžV}Èøf«œÛ¨ÏŽÎ×Yÿêeॗ€Ë)Vyl|" f÷UDzqˆ@ëˆÇ¼˜4Y-˜³YýÍ-!¶6a“žŠB:o%ñJ¤ÛI±´—UQ|£UÆK¨O `¢®=\ ý´­ò:ë0¾°Àx …±Paó‰Ìuˆ@œ»!ç»K†âPÏdÕxhw1>×$jγ“vöZdàè™xñ«ÕSšUAÅ&[URßd•ý7ðøÂz·ký«/˜œðr¢U^¬Žä £ó—w:I.àVÇ®ëôÿc>qí.!·zSÛr&«³Õ2…)Wgù ¾…R -ÎiãQ 8¿çØûPa\О×U%•iÝ¡¦þUï_=àÃpÊø ›Lu ê(îžN¹?†Ÿ 0?Æ:]½Î¬ä†ÔÏt¬B%“U|™úù²¡NsorNÿ¹f¶ú ø,»P !­v" Y¬6¼hLï_­@@…bé·s¯c¶¬£qg˜v4|Â|0lÏŸÐëÔ$SŒõ9ŽîòbʱšÑj#ŽŸ£~žƒÁÒÏ?o²÷}‘‘ƒð}7sAPm:IV¹=n•÷¯ !ôþÕ{±›{ÍÝh¼ÎEࢪ£8¤sèu€ÍoL®ëÈTð$ñ„õ;VÝú¹­sõöcqìD¦3ðø¸ñ üÛ༂3.D«Bˆ«éý«³B4Ì&ìV'ØÜ TÅ `õà½Dï6ÿ™žšÏ·óqýyùjû8V‰Õæ*ëÖíX%ý³›@s«\ÞjrNµ$à|ö=5þΆ 'ìmU«iý«Kýi€%C™ÉIð:ssaÆ…`*`óµ=úl½÷)>ÈuÕ˜MeuSš›·¨Iò_ÎO÷ˆLü£_©}o&©íÀjzÿêÝpèºþ{¨¤ÖáÜlu:OñÁ®«ÆÌ)«s¤%Q@ãÍ$Þ<]f› € xO%…÷PCbhr2£ÕôþÕ¼ŸèýPK·Êëpžf5½Në3^o«ù©ú¼]êe²JÊêÁ¤iÐB˜œ464†€^tï‡uÙ²þUÖŒ:G4'¿ò22YêpÎëˆÌu¦G'/PyÙ4?¡þè.ÕæSB„P_>‘ÑëšI 1t3Γ÷BäÉ­æÉ­æÉ­æÉ­æVóäVóäVóäVóäVs«æÃ]î³!×67(ªÇg ¯¤¥‹Šyƒ°@†” 4>QÚò ßÕV«F­}^XׇìÚ¼ˆ’Õjµ¦e÷26 Lž³Ð%žòY´Gâh û³šl‰C­}­)Óâ< ˆ!ÚE ôðÇE½PçZWZ™½ŒV+þ@†ÏR 5{@ou—Ɇ4²‚²&…„˜´H…Ѭ6÷eµy V‹ˆÝ€˜VÅ¥ÖÁ¬¾ácqZ„Þ’©rìÓJÆçyBêæyžÓˆFzÑõFN¢$¢HbÈÈÕ³*+jÕqòÑÎÀ Ú«˜kÝ¿UàX„¯lºe·ìÄö¾Ä1“ÕÊÚdà0d^õ-‘B%‰ƒ}ê œø¸{Yõ¡™%rÇ*Òj5Ak5¦u«³"Ì,·:~éÒ¸áY¾Ü~ h™÷ûÄSA~¿­6ì ¼fuÁlÕ‡fµŠ{ȵQtATHÐZˆkÀªŠÆ­/_°¸ÕSŸî¼náû¹ ±u']bù]|m`«B…ñÄÁÏÀ¡J,O$íÁdu]·Zs® ÀFLß:©Äùúú›aõø‹À‹Ç™ÕÂÌT4Ïoà~by?wpÇj滥ÖAœ…Ø(€xù]„†¦ú…ªfÕí¶~anÖ§/ž©¸¿^ÈdÕÚ²öcØÚú˜Õ‡,!ÄÐ1©øi&–xi_VK@ip«Íƒ9¯ÐÞVi%a; Õ¯L?‰0J“*¹’šÅª5ܶ¸UÑ·Š“'Á¬ºx^î²6âV[¥^ à{öeU™ÈÒ|—:0ø=0‡»ÈdÛ«o‡¨ç*J“q%•[­ÆõYÃN¸˜.sQ„L‹udš[2×ð9þIýó:WÁn—ÔÈÿÐÙŽÊm™Xl¥Úƒ¾6×!lNl‡ÙVÙÕ§KU¼¤¤jVã\J%©UߊßB°ŽLcKfáb×ö>a“=Òb›~¹R]aG%[ú÷×js@«/9ðMطݘU×>yɲXÇ@}³ ” ëëF¢´tÜg^‚ÛvO\°žÓ¸wv‚p•ϯz3›K5i¤!$P>”ÄÅ€¹'Ò”VÆ›¬”¢Lž2r´ú@¤UMÃÉKÃúZ¯õ‰¹å6Ö×ÀtwŒë§ŸÂ¦bä„mß1âh|ô|É]}~¹0øÀMjA¢À´Ò(JâŠÝÁ­JP68ÌC&yrÈÌ׉e}­jŽ_cËJ½?êI0¬¯kêÛ>š«W™‹áø Æû‹™¯é|¡B¾Þá."TEXd Ô8”Ä!cwµ*E(ÎJ)ÊåÉ!Î[W"­j_ÔÃáТeX_×ÐXB;¤÷¯o°†O0~?¬:P½Cã (.²í¶±[·Ž‘‘ò!Wq£%ßÔ*leÃÀY)E™<^ˆKåZ¹T•60Ö.ðõ#«µøA\ý¤Á5;RmÆtkdÂ/8§)5~‚¿ ¬^0Ú #åCkg–¦¶eÍÌy)²—±Í¶¿‘ÔºÒ°6Ä¥ª<€(?Æ×&ÉõõuîA„áVŸ’õm0^h.—tÌxR*ô×aô©'ö:,¥H§|èÅ–ªÏ l5z„;8+e¦#b'#|û}2Æw(|Kc–J½ Èl6 뀶¾®wù‹^‚ÕŒo×—iúœ3HÓ êR –ŽÌ”9Š,Y“gP«Ö°:N œ[5SÃöû‰R‡!¢§ä[)•ç]€úœi}`úúºm¬’¸N±4Ð¥¹²ãvÑ`|;f¬(®´Fïlt©„¢LÔ8”Ä÷Z#½Aï–¤O%ÕÀY)N¹U®5YêÑeœ¼d–JÎE3dZذ’þÇ<Èx·ÇñØÉñä¶e •@ùPÚ§ÏþÎFúTR œ•2S¡Â·ßüΦ/uˆZ°~ðšCæ3ÇÔXÊz¼ÍÓU¨žâxõ\2s«ñä¶e •DùD.çÉåfBO&enÝ'iÈåR%™?Fy¸VsS~$uˆ®mœw()Á´r”ºo³0*Dí˜Õi!3½:On[Bµ!sʇBäp>Ý£HTÙ1òè ;ö8M×jnʤ‘Ó¤ï¼äqpÞ 1hò^ˆ<¹Õ<¹Õ<¹ÕÜjžÜjžÜjžÜjžÜjnÕÜßû–qÕ(qpõOkª’Ô}¸ßøI?TY8H«®mhyK¸Ìu5ÍÏÂÎIœt÷eÕnQBÞ—`µRÄÂ`¯·EÀPË ­Ú¦ö˜½¹xû™«ž½>¹>€â‘¡yt¾{?|œ×'j)”ÉÆ€µ}YUÛÏäUùÛÜ{ç@Vå‡/€J1ìF+€¬¿7䀉[OW«O[æù ø¹‘‰y³ÇUY«ª•ˆõ!?BôÈD%D™Wj¼>-Ai6x£z)»ÕÎU R½ùª±’7 dõÙŠ@µg‡ˆëï•\†soØ)œaÏ4ßzfŒ[«W+•±>¹¸« œÿPô>ä |•ÛqLãÑG8vâ¸âêÈ£„˜l´j©µ2ZíÆtÜß+åŒV¥ÔA¬6g<„/ŽæQ ‚H­çSrΣ“ÑçÖd}ØùYqàÔg]€sY]ç;]FëCª@5¼YÓÕ–5ÎC©3å8oÙ)kš1'ûüd6«>T *Ëʆ’§Uz(¥m)ûâ®CD `‡ÖHe/¾.ñ:ç—zN¥È9pgo &NC¦×ƒŒÞ‡¼>¶WÓøÕ°_’ñHj ñ)¤Xe6F„ 7p’m¾-è`'Öc†»Ü.Õ«‹ÂAZ=³þ^Ée8÷ÂF×;<ËûÄJ1{óãŠ+8'€Éª'„Ö‡\Aµ*¿Òø[² ‹ñR$UãY)V¹ óAyɃŒw)ŽEc#<ÕT‡ƒ”»\vW•{R­®«ÉëÉýºtÛn(–ÏzÏ!S×7o ×ï€×Ie®Žî™wõ3]ÔçbÜ—üäÇ8¹5|Æi·Ï æêRÛÚJkʱZ‘RO+ê8£U&µ:]•Z‰ieR‰’¬¢‰(üóJËMŠÞ—7—³«ÒZ@Œ²5Ýa^äº\G˜z™¯sª¾éÏU‚Ò*¥rMÏe³zT¬^Ê:ɬ‚õͦX=>Ü$ bi>³U&X¬Qoybb¹GÄøkøÍ8¯ – ÅÒ˜óýÿn).Õ¤òœÙðoã ¥À^Mmád³ZƒÊóië$s«ªo–oÞê*{»4ììÑeLb¤LÙ³""mx: `:mÉkž[ØgeTˆÑ‡Þ¬)Á„'0*T˜›Bá€{!úîIÞ ‘'·š'·š'·š'·š[Í“[Í“[Í“[Í“[]˜ZˆƒÜj QŠ.e '/¸®y÷vQ¤71ø(Z&†óÒX‘õ?(_œšZ”œÇº”){tÄÚ€m˜ZíÿÀWÑÏ)­«-C“ŠÓò´¶ jqání,Ì‹Ÿ"áIv‹¦½ULØ!h¢™Ù꛿îñ©¯Ýsçk’óAcrN‚ôþ佚ф€…VE4ö0úy˜XÜÒ~å4zʸVã³°%·ñ,é¹ßû)føÃÀqtÃp˜u¦~ã  Þø©ŽÑ*ý“©^æÖ0:åýÏéܲö3ÿ3…ÃÏJÎâOô(¦·ö£›ZB?K™^ Àv]’un ŸlçúÿôWþÀ‚¶i0´p6­ˆ[ì°©àC_5Xý#ú[¿öwX3ábñÎ廫ÄR½{ùÎâ¢NKðAîÏÿŒée S«èÓeª|Ýã¹wñ¢ÇxâºÊÞsôño>ÖP\å„”Ô•6Ò;nVÛm¯fëI$àø‰ÇûVÍ“J-ÛJ%ÖŒ¼Ž0¯óUwûYÐŽÉSõóó×n‘uÿÒmÿè—®Æù«xzµÒË—VŸÆ«ÚIµvnôWÿÚ_ÿqLZØÇòé"_—X®z‡Ã÷Æ 8Ç]Ap—‰ƒˆÍ?†¶CÍ‹Ž‘ž5È4ˆ·3ñŽzw(Ü{7e²*Ȳ`Û°¬!AÔQ“:ñKUnõ•¿Âÿzë]ú1y†V„ø›Ga°úCÿêm0îPY ÙšUx6TT&·hVï9V§ þîßÓ¬žzÑ  1[÷X®z‡ZœËÕî„Ð9ªe¢r›qóJ¸³¸NDß/ù¬¹g·þX¦ë*9o—ðíN6«DÃÃ` Ë{à÷ªIï%ËM´z9—ãTûQŽŸà–ˆþþ7fö\"jþÃ_3ÙþÖç~xBá'€ŸùÜ·ˆˆY›]*KÐŒãî“«%"úÔç5«"ðÈqxq~ü’Æ•=·‘¨j¼´ºSá>j¤Vç·&~]2 xzÀF¸ÕíŸ1X•§_yÞùDÀÎ<#N’ÕîïRB÷Ô}KôÏÿÅ/ói‰Šy†ù¿õË !V^¢ñË¿e²JŸ‰‡}/FkïñAßú7Ÿû· âëS©È×+.–(ec—ˆJ:˜zðƒªóW“ZšŠ°ëª–wïÒÙQ™þáðÅž~aÛÒê„ØÍ„öpç6,e5í¯,¬+¢–”Á,ýûÿð­óñ÷ÿt±võ%O^OøüO}ãן -Oüú7>e²ÚkC¦6£waô_þëC ¢‹|½â›9‘‘×*•šÎ‡ØWÆñ¸Aª)×U¶Jgê8<ýZ€´šx^?„ÿ¾2²u¶­Yýí³õè*^?ûÛÚ‡KC­Z¤[‚ÿ©ÿù0.’–àCµ¯@m¾çÓçß$-ßÄ/~ž|Y¥å[eþwƒeQýŸÙ×¶&cëÊOž4s|‰œc’§JåûŸwsïûXÍ8/ñš¼Î6Ï/ Ú¼;ç'F¯LN^8]ÛeadëZ 1'®Ü°ž÷^†Úü™û¼‡L³‘sBdü%Ó+M¢·`ÝãSKö8פ²÷«ìº*ƒª)gl#Ž3"Ä’gÑŠ˜S Ç㋎©qtcxxƒš|H>–¬Æø=ðŒ:³ÅçýÎmÊjÕå¬ßÿìÕUßòÁóv£qìys©Ü’žLglþC6+[FÍSWg…ö“9õ˜ƒwV3¼1µA ë N”ßD¾<Íû«ËÂ$5eÿ(s„ú¡ ÿ[Ð Û¨bú—³‡žaF.”¨]±K¡îÇIEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/single-file-icon.svg0000664000175100017510000003362712370216246030645 0ustar vagrantvagrant00000000000000 copy edit Source: Tango Icon Library: public domain (modified by Kevin Dunn for SciPy-Central website) Andreas Nilsson Andreas Nilsson 2005-10-15 image/svg+xml en .py Submit a code snippet numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/transparent-pixel.gif0000664000175100017510000000005312370216246031132 0ustar vagrantvagrant00000000000000GIF89aðÀÀÀ!ù,D;numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/single-file-icon-shrunk.png0000664000175100017510000001416612370216246032137 0ustar vagrantvagrant00000000000000‰PNG  IHDR·(¼^k îiCCPICC Profilex…TÏkAþ6n©Ð"Zk²x"IY«hEÔ6ýbk Û¶Ed3IÖn6ëî&µ¥ˆäâÑ*ÞEí¡ÿ€zðd/J…ZE(Þ«(b¡-ñÍnL¶¥êÀÎ~óÞ7ï}ovß rÒ4õ€ä ÇR¢il|BjüˆŽ¢ A4%UÛìN$Aƒsù{çØz[VÃ{ûw²w­šÒ¶š„ý@àGšÙ*°ïq Yˆ<ß¡)ÇtßãØòì9NyxÁµ+=ÄY"|@5-ÎM¸SÍ%Ó@ƒH8”õqR>œ×‹”×infÆÈ½O¦»Ìî«b¡œNö½ô~N³Þ>Â! ­?F¸žõŒÕ?âaá¤æÄ†=5ôø`·©ø5Â_M'¢TqÙ. ñ˜®ýVòJ‚p8Êda€sZHO×Lnøº‡}&ׯâwVQáygÞÔÝïEÚ¯0  š HPEa˜°P@†<14²r?#«“{2u$j»tbD±A{6Ü=·Q¤Ý<þ("q”Cµ’üAþ*¯ÉOåyùË\°ØV÷”­›šºòà;Å噹×ÓÈãsM^|•Ôv“WG–¬yz¼šì?ìW—1æ‚5Äs°ûñ-_•Ì—)ŒÅãUóêK„uZ17ߟl;=â.Ï.µÖs­‰‹7V›—gýjHû“æUùO^õñügÍÄcâ)1&vŠç!‰—Å.ñ’ØK« â`mÇ•†)Òm‘ú$Õ``š¼õ/]?[x½F õQ”ÌÒT‰÷Â*d4¹oúÛÇüä÷ŠçŸ(/làÈ™ºmSqï¡e¥ns®¿Ñ}ð¶nk£~8üX<«­R5Ÿ ¼v‡zè)˜Ó––Í9R‡,Ÿ“ºéÊbRÌPÛCRR×%×eK³™UbévØ™Ón¡9B÷ħJe“ú¯ñ°ý°Rùù¬RÙ~NÖ—úoÀ¼ýEÀx‹‰ pHYs.#.#x¥?v.IDATxíœ œÝEuÇgwï¾²ÉnB’% ĤòP ‚¢µ*Ô¢ ÅF¥V­bý¨¥% ¶Z­VQD* ÖŠHñQ? ¤*RFPHBÈ&y°Ù$l’}Þ½ý~ççîÝÝ»KK>ŸÒ{>ùÝ33gæÌÌ™3ç?ÿG¶¦P(„*U-ðl´@í³qRÕ9U- r•̰|ùr~8þÐÒ¥K‡*¡ZVµÀÓµ@ÍècI DÙ~;«ìïþž®ÁªíÿïX ¹““éØ|ø‚ãvvm}e___uµùÚB¨™¬) Õ„BÈÕ566†™3fÿ’îVª;õ?YýTõT-Prî³Î:ËcH'«ûÔgþþsºà¯Nill ƒ¡¦vÒ|;† ¡¾¾>ôöõ†ïÝxÝôw >°lÙ2;ÙoWŒêÒ?û-PæÜ¥ÉæZ§µ,Xêsõ}8¡Qµ$ݧD mG6À¹ DíþúÖimž·ëÁÀÈZÕ\ÕOß%ç.SU( …~Ž${vïÎy4©««ÃE÷=¨‘ÑÚCMòqò…¦¦&u’v»ïŠË[MV-0ž*9w¬[S[0ŸÏ‡ÞÞ½ÇÓQ¡¼ôÛ†††ý×¼QœÛÕP‹n/µ£ÃzMÕ¢ªžª*:7®#­NØÙÙ6lØPrÈ$«Ô¡!˜ƒŽlÄ <'ÌŸ??‹ÞÑÁ• E¹í«Ï+Y±Z6Y¨èÜÑAéAGœ>½è»8FZmv’¿ûTGŸ2eJtlÛdí²>~몤jɳ@EçÎÔëˆ8hKKhmm-9çÞví±ÃóöÐP~Ć0ò«WÚo‰öv¼ÕzÏ> LàÜ!˜0?ýýM:ÂÎOÄsøDfðŒÞÚ:#ÉÂX7säì¨Û£xæÞišXÆæ©£†÷©ªŠœ¾ò·Ê¤Å¶n²½ª?žNôدã@U¦«X Æk·?Ë‹sõÅÜàþè—þÒÛí¼Fy&û|2[OàÜÃÃBI¼1LO92I¥q×ð~&ŸcësÎÍèíM¤T($'¯Ô6Óúd¿NH£Ac3ÉÆÓ‘äåmSÙxmÆ+/kÆÿ3jûqLÌ-:RšëèqNàÜ:eæŒÞX‰ky™“Ü2†Ê¢¶ØSìÌ‚a§¶oÛäóé&29y±á>2ÆS‹Îd¸Óiþ60¬W#ûÜq§El)'B„%9H²‘ôG€ƒùÈ—ûÀÚ ¢°>†&pîÌ±íŸÆaóæM¡§§‡IÇ~Æ(²N"ÓÛ¨íÆ˜5kVðu»OP²zÔ-«ŸÚMÄGMêÃÔýgÐKuÎEÿw@Ü”ÅE"ïà¢ó›€ ®1¿“NŸ oÝ4™ÄÕãæˆW‹b]›ê4ïßWRþ&ø¥` Øbx\,Òög_¥±™·œ²R?Ų´€¥«Õb™Ç¼-:7uq+Ön5n*.“˜BóÀf°}F£W‘¾œ¾C¾~øò]ä§’^Ü{;èÍÈ\ŒÝÔ{®a§Ãfõ@¶[¼ÙѤ[ÀÝÀ¶Î)`ÎóÑÛ¹ú9C$ÒËÈÓÙ¶#~¼²”É£!³î±°iàwÈ·©‹äs)wœ«)S—ý¥>'ëœ;ÀŠéäøŽé8ÊšÁ½4ÙC>m&ûLNšú?zSo ܱÚÎ+–W&îEàQäëàÒ `X­.ø!ÀÈꆳßÔÝWÿ0íÝ´›övL=È’ƒ»Þǃà>`»6Ø™`1p|÷ƒhkÚF¯üÉ«ɱYW~è¡‹b:“d¿ezвìŒmÄNÒ®r¹:Ž&<5±”Ÿòvåúö2­Sjœ#ÁeŒíßà¿Ý.¤óÁ§ÀÁÀëÁõàýôýUÚðEXlÿK¸Îí—![Nò:Wyør÷]@R§º]Ÿ‚kÿ'ü-@º–|úþ…´ÑÆ+Cé+ÁÛA¢SîÕf'¼ÖBÒwÔ{ 8É2È ìØ¿w1¯§*€\Ô!û¼ÒÂbî˜g‚¸™‘i£›Àk´²·Òö×pûס«Ng§7ïÛj~ˆÌ¼cs®]À@¡ãÙï{;¿7ƒ/ƒÓÀàÚüyÀ ruÕ¯ƒ^ îêq#¯B~òá'“×釔@Þ^aôÊΤþà9Pº‘ÍêTúM¾Â¶ã*_Å÷÷÷Gî7'ýý}ÅtâñÒØ˜½™ÌÞPÖÇÍ÷Sö;Ö\©ßŠe.zŠ*ScXnF :Hõ+YÓ<ÓeLjbDøXîËPÿ¸‹æÑ¥œ¾^-âGðÓ©ëBy™oFŸ‚€ô×àÚ˜Þp É™.d!ìÿ  ¼H^V‡²dܘ'‘^ŽÛÀ{éÓ ² èØŽ+Áç !ýyð{°Ør0Ôýw@Ç~0ê€Ëi—úNý;.ùÆTÿKà•Ãyî­à( ¾WÉ:RÒáX{kr8¸ —¢k|+pÙ~%8<| ¹kèš*÷Jø:ðg`)ø:¸Ø×»F*9¶™´Ø¦Ç¾H'D“¡°~ýú°mÛ¶…­82{Ó8ˆ,?üˆÐÖÖZv¾v‡"Y;ÎÞDw~Çô9^FvÇë¤&W‘7ziåç¹àOF­DÉðløºŒ|_#m”Õøt2/­÷eÙpù‡ÉßK^çh@n:õ¬%-ý‚üäuŒ´)××±Þÿ ÜqÚÖT"d:£›É£È¿* ìhÒÝp7‡s½‡ü§‹²‹à·~…eÐ7‘?DýÒ:Êlð`Ÿ/:”iéX MãxáÎÃH{1:tòŸDçòÚØE½üÍä]“Á f,Fke:¹gï+-§¾¶þ[p P.yóy²H_Ïk€ó݃W,éTê^DÝÕ¤_~NÞcL¼‰¶B¢ ;ž˜¢Ö„¹s熙3 óŠîêOÑ=q^œÕy65¥ÇX-«Yòáá3w R¥òT·2gà±S&¡£,¤Örp7ù/Á¿O™ x8™´FHÎzÈS6š\ç¯Ì…”\Ül‚1‡“15‘Í’£¦…¶—zÿÒ7£ÐàNà%v4©?Ž‹6é*ÍCGQ¶«¬QO1í8•K‹óÑnDÛ¥ù½˜´uÃu`;tv£ÇÓ÷Ñ$?ÜÈÚ{)e'ÀÚ(9±ºÓøHް_²eò4^Ç“äi}ŸWíhR¯ú_WL_ ÷å\ËådGŒÁ|içÄÌØß2:ßB| ßÞ~`˜={ví‘·›ŸÕÚÛÍÏ"z×ǧ$¶É¢´Z‡:æÄ''Q·%Æv’i—÷“>xi3 j“À¡ÀEêɘ:ºôòŒ•D[ÿÕÅr'=ÒBÅ…&Ÿ ?:Ÿê¹È©Nù‚SœEtN²xÆþü1 ¥•ÚKõð<`d’naž¿‡ÛÖMü ¸ô¶Œ…_ÁWÓ¯-rÛ{5ÒaŒ€öi?ç3†3áwƒ'ÀF SÇy û4²ËÁ¥”µÃ? ´ÿKö·^²‡Ü|l[Vn?–i“—¢óx¸ôúŒÅceZ'm#¬·Ül¿…1¼~6p}½yÕfêwL:¿”Ö#Ëñ›¦TPJàOFWÅ9º.:ªéÍb^^|ví3ìT>8˜Ïœ6¶USæÔ¶a@%¨sxÓ–z|²DŒ.â[À:ðm ià÷Qº¸@·é;@îÞP¾¸Òµ ,w€1&Ÿ¸8"kÁÏÀ‰`pÌ.ŽN`ú¿HEò Óü”²[áÊîDæÜÕ³x¾ÿx¢óHüÝü®ñŸOÿ®¨×9Ï7SöS¸ŽÍŠ”§ùòeù·Çñ]àæyŒrÇãÕBg”úÀc*ûù Ì w;h:ûÍ`x#X…žëàÒ \ þN×"_w®_ ?íx°eÚ^ú2Ø ÚÀÿÉ9ª/’CQÊóõ“×õ!‡ƒÖñBfUGwؼ³?~‹ý³5Ýafc]8ûÅ3ÂaóZBÍÔyá—ëkÂki ‡،ޚðð–=ág¿ÝÎ<¡=Ì9 ‰¨Ïêãܾ¦ßߎcLg\žcu/–ÞròÙð /¹"Ñ5)A[=ÑE)A{ϸ“Îß~4f4h1y‘è[&в^’_KÊÜŒÌ8ÊM{©‰R?iÓ¦ºöÛA¥Låê“!Ó±¾bY¢¢L‡pþßNåEû¤ŽóÓ‰>[.·m±],&kÿ]d.UÏö…hËb;¯œ%{"_C^8ÞC`SÁtÊWÀE9ÅùPàSŽÀEš§Iç3¢cËŠãøJë_K´_lÈOEç¶GÉã†/`-Z#p}®6Üß¹%\º¢3|ýôyáì×´„Ÿß×>}WW¸úÜ9áЃg„ïÞ½9ܹšGsun¶iÇî°ig>ÌlkŽçq?3ѹ ûö´$*+þ0a£¸“×u×–&W”×Y^”[7ÖAf¹d;Ór lôT_l7ªååýÆÇNT׆ˆF´UG¬d…b¿qq(t\¥1eµ²_ª–÷£.Çû#ž¥¹«§±ÊÆÇ€L®óúš:]JmËôR-#ÊF÷Ÿì[nª•ÎèÑžæ‹ý7’v£÷`©¹(k@f–¶‡WPå°8Nóeê.ÙŒ¶q‹ºb¿È“mlR¢ŠÎ­%ѹ[ZšCËÔ©ñø‘ã›Mmˇ÷ßÞð²…aZs.ÌŸw`x`{GXýxC8ᘖpÚóÛÂ7ïØÞt¬ÐÔ lê ¯>zzhmi œVBŸôhâKþ?Nxi@{›(N2N´R› òR]d\6JT*·™ i4Š4ZO…|yÝm“ŽÄik¿ãöêÉG÷³²'ƒó1çrÝ)=^ÿ”ÑOQiNE¹Ží6ÁN)ÓiÛäØÊ¿G^D"_’••¶Yª;f©Mâã:7¡ç.„A=[ühŠ¿ËàóìæFØÏš2'7Ò³saöžÐÓ7ž{p ¡+¬ßÚڧׄþB.œxÔ¼ÐÌwá\âK¢½PÓÓ·§…´»Õ³k•ª˜T ”œûÔz‡"ãq¿!"omÈâ ƒn. ¦øñFRòÿAöq39³7×0kzsxõ­á×kv…í|Û]³+ìèÜzžh µ|—â‘dÇÎí5÷®º'<¶yS÷’eK¼Y«RÕ“n’s'Ƕ‡ü´§?îßÐZ†ÂÁ³š¼„àØ<í ‚ßöðîð¶ýáÈù-áÞuO„›Wï KO;È?×…“™>~]GøÑýá•­kÿâÕ=¾¯·/ôôîêíé­S[}.÷‹«—^/a“>³ªÂÿ÷(Æß‘vh& oÞÎYùëÃM+;9JdÄgÚž»¹» _½usxß×׆3¾ÙÎ>ö€ð’çÎ䮯?×P9hz8yñôp׺GÂÑ Û±ÏQ8Ⱓ¢C‡ùsœ=׿™m.Ÿ,ø· ù£<ÙåaäPª¹ªž²J‘ûÎ%gÃw÷žÁ0§­>ÜûEDñ<çî¼'Ž"Q†Â©‹[¹'6>ÞÞÿ'Má°ƒ§q<áQ!7ŠS¦x„Î…¶©á]/à9ÿ`WØ´ekØÖµƒ¿ƒ²k`×î]õÛ·¶Íh½ðS½xƒ#çaÄSžEµaÕ,PrîrY¿/\8s/˜Ýöðúø.›hí™{WÏöB{[S8t^+ÎnËÚx–~à‘]áQ>®êîɇÛ~ßþœˆÞ¹ñäÝC½{öäuìÇ»¶ô„Âà[.úèÅ>ÓŒOt8òT[3ViR-PɹkâɃ³s}có`3qybÿ\`ŽçÜ/:²6,^8¦µNçTQr>ÚËN7í³êÃ+ÖâêCá’³…ÞÖ¬Ú]¨«ßÝÓ]»¹sóoyÜúÎ/|ö2¿s¯x–¯:ö¤.iUY²@%çìÞÕ]³¾ãa¢qC½ßqý0òöúº0‡G|kÖvÅ|v牵7›Ü&¾ã…ƒcî-†Õ­ãñàž°£»«³o ÿ‹®ßôO×_}?glû­øà= ¬Ê«xºðÍUÔa$MQôƒyß±;ºv¾Â¿È÷<ϸc”õÝyün„õÅ[ÑøôÞ©(äø’çå^oyêr³gÍœÒÜÒ´®÷‰Ÿ\~ùå¾¶ :6çëÒ‹˪TµÀ3a’s'ååNžÊ&ƒÚ½P=†L†A«:žÔcœÛ>šƒU|Lø¤+T RWº‚]ªEϬ*:÷3ÛeU{ÕûÇ“÷Ïp«½T-°÷ø_¸¦;(ׯIEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/single-file-list-icon-tiniest.png0000664000175100017510000000304412370216246033246 0ustar vagrantvagrant00000000000000‰PNG  IHDRëŠZîiCCPICC Profilex…TÏkAþ6n©Ð"Zk²x"IY«hEÔ6ýbk Û¶Ed3IÖn6ëî&µ¥ˆäâÑ*ÞEí¡ÿ€zðd/J…ZE(Þ«(b¡-ñÍnL¶¥êÀÎ~óÞ7ï}ovß rÒ4õ€ä ÇR¢il|BjüˆŽ¢ A4%UÛìN$Aƒsù{çØz[VÃ{ûw²w­šÒ¶š„ý@àGšÙ*°ïq Yˆ<ß¡)ÇtßãØòì9NyxÁµ+=ÄY"|@5-ÎM¸SÍ%Ó@ƒH8”õqR>œ×‹”×infÆÈ½O¦»Ìî«b¡œNö½ô~N³Þ>Â! ­?F¸žõŒÕ?âaá¤æÄ†=5ôø`·©ø5Â_M'¢TqÙ. ñ˜®ýVòJ‚p8Êda€sZHO×Lnøº‡}&ׯâwVQáygÞÔÝïEÚ¯0  š HPEa˜°P@†<14²r?#«“{2u$j»tbD±A{6Ü=·Q¤Ý<þ("q”Cµ’üAþ*¯ÉOåyùË\°ØV÷”­›šºòà;Å噹×ÓÈãsM^|•Ôv“WG–¬yz¼šì?ìW—1æ‚5Äs°ûñ-_•Ì—)ŒÅãUóêK„uZ17ߟl;=â.Ï.µÖs­‰‹7V›—gýjHû“æUùO^õñügÍÄcâ)1&vŠç!‰—Å.ñ’ØK« â`mÇ•†)Òm‘ú$Õ``š¼õ/]?[x½F õQ”ÌÒT‰÷Â*d4¹oúÛÇüä÷ŠçŸ(/làÈ™ºmSqï¡e¥ns®¿Ñ}ð¶nk£~8üX<«­R5Ÿ ¼v‡zè)˜Ó––Í9R‡,Ÿ“ºéÊbRÌPÛCRR×%×eK³™UbévØ™Ón¡9B÷ħJe“ú¯ñ°ý°Rùù¬RÙ~NÖ—úoÀ¼ýEÀx‹‰ pHYs.#.#x¥?vÜIDAT8}T]OÓ`íÛ·íè>ºÖŽM2è†1MH¸1†xoc¼1ò¼áÏñ c¼7¯P  ƒnëc¥í[ÏÛŽFy³4í“sžsžót%Œ1BHý¸Þr²$‡a(üÿéù^ÎÌò E<ƒ¿¶¶ªkºïBHþýˆ Àgºf¬®þD 2¾ï›f®XœÒõ.¥¨ü-7Œ@Ó´,l‚"Ë2'GÕÀuëëëG˸_!˜eY¢HÑ"‘H—˜!8Q ã®y$N@Æ3ªãBˆÈ‹ \‘Q4 £Z­zž‡û‘¬$AvбÑD}F}¯‘†+]Ï„lFd4‚ ùAL¾ÊäJhôl·O  hä+v'ÔjµHߺM™Ü9 rÙPˆ¡AÀs޹ ¼ã8ñÌ1N¤´Äs1 ö4œúr—7l£ˆ™±-øô<S€Æí<6DÖ®§ 4tݠѲ˜çs¤çLy„—¿Xù®“ÛÚÞYpä¸3¯Ññf-ÕÌ»b7ûöàÌe3SiEQÀÇA/‘{‰ŒåÌ\Ù*þ<’™l<›þ\!™túËJ ¬ìt=FÓ©$ÈHž5RÆ( EÔ4-¥JÅqãÉÃììtæÛ–蜥®ìô©¬ÌÝ7©¬‚ÓrZ7ßmÆ*»§IñBUHïÜÛ>쩊Ðìº)Už”ûð©jIÕlã" §v§ÛyþìÏ(öŒ5|ßh÷<"E6kýËö›ù‚¡%ïYùñd˜NJÒ®Û»{{¯^¾ŽXápUHøÝ´Ýp¨$¥Tuá±ù ¤ªµ_Ï–2Ä÷«õƒÃ½Å·‹åRX '#€f«YÙØìu»ø÷͘¬ÛTú6ê}×´š“z¸|p011¹ô~©¿3AäŸäÞhØM§!Q ïþ˜L=ß?÷|ÁÔ±PKgNzn6kàÓˆ‰û?w¨¼Ó~AvIEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/external-link-icon-shrunk.png0000664000175100017510000001300312370216245032502 0ustar vagrantvagrant00000000000000‰PNG  IHDR·(¼^k îiCCPICC Profilex…TÏkAþ6n©Ð"Zk²x"IY«hEÔ6ýbk Û¶Ed3IÖn6ëî&µ¥ˆäâÑ*ÞEí¡ÿ€zðd/J…ZE(Þ«(b¡-ñÍnL¶¥êÀÎ~óÞ7ï}ovß rÒ4õ€ä ÇR¢il|BjüˆŽ¢ A4%UÛìN$Aƒsù{çØz[VÃ{ûw²w­šÒ¶š„ý@àGšÙ*°ïq Yˆ<ß¡)ÇtßãØòì9NyxÁµ+=ÄY"|@5-ÎM¸SÍ%Ó@ƒH8”õqR>œ×‹”×infÆÈ½O¦»Ìî«b¡œNö½ô~N³Þ>Â! ­?F¸žõŒÕ?âaá¤æÄ†=5ôø`·©ø5Â_M'¢TqÙ. ñ˜®ýVòJ‚p8Êda€sZHO×Lnøº‡}&ׯâwVQáygÞÔÝïEÚ¯0  š HPEa˜°P@†<14²r?#«“{2u$j»tbD±A{6Ü=·Q¤Ý<þ("q”Cµ’üAþ*¯ÉOåyùË\°ØV÷”­›šºòà;Å噹×ÓÈãsM^|•Ôv“WG–¬yz¼šì?ìW—1æ‚5Äs°ûñ-_•Ì—)ŒÅãUóêK„uZ17ߟl;=â.Ï.µÖs­‰‹7V›—gýjHû“æUùO^õñügÍÄcâ)1&vŠç!‰—Å.ñ’ØK« â`mÇ•†)Òm‘ú$Õ``š¼õ/]?[x½F õQ”ÌÒT‰÷Â*d4¹oúÛÇüä÷ŠçŸ(/làÈ™ºmSqï¡e¥ns®¿Ñ}ð¶nk£~8üX<«­R5Ÿ ¼v‡zè)˜Ó––Í9R‡,Ÿ“ºéÊbRÌPÛCRR×%×eK³™UbévØ™Ón¡9B÷ħJe“ú¯ñ°ý°Rùù¬RÙ~NÖ—úoÀ¼ýEÀx‹‰ pHYs.#.#x¥?v»IDATxí[ ˜TÅ•®{owO?f††p†‡fèó}§«NªSuÏýëܪº· )¥Èsçš²¢ÂÉ”½¬¬ºâ³+Û¶í Ø†'€ng”EJÖåÙ4ëLxÀÈTä6~°,Grâ{äýÓ¢ ŽÀÆC#õØ0@KJî¬}VŸõ@gèRÔ$ Rv’ë=À0å¬@ÔÛ—²1s™Å(­õ,ó÷åá¡YËǰ;çå~ÁÙ+ÏâÄ °U$wí©¶ª=J€ŒYïxõSA=! A³l•ì.û ¿Hkm×e²ª<¡–)•Ið³Ü4ÌÑÒ4'ë-m«T‰KD´Ø¢ž€×ÑœmôéK™6†í‚ÿþJÿ€Y{©Õõnxå ¿µ"u¤ô –,Éþ ðdì"ã SiÅããßþœ´G$ Y#—Lû˜}ÜðF¡a˜ùR:žàõ/–E‘š‘_H;!Ù2Ƽz“â z"fíO84Ü>IX¶îëßÛ¸¼¨`±V—Bm^¥×7Ø´ã-²â|U/ Ï:öAÆ®-k¨[z àæªA×9¶ #á³þ%h4iJË¥¡Ù+Þi®©_,È/,s ã¨!s.5û>–†Æ%Ò1¾îÑÒ Œè€¨cL Œˆ…Á=°áîŠÅƒsV<*UTßZ „ÄÅBZÛåâóޢǹ ‰RÛëÙ@9´wb‰0b9M†oeFmý4 œ¥cÇX–¸{ÀX4·ƒsšÃrAxñÔ;°P¹_âÔœ>yÃÂ]ð<@¶ ‹§,nZ<õ5 ïix—×´yð‚ml‹úC0Y>aûðƒSÿg)ÕX˜\æƒ ¸P2‹ÌÝ%X¬b9¡m,sìØ Œ¨^.šÔD¹u˪¤ìÏ1ä €;é-™ca'넌UÉßL ³ÔŸ{ GÔxŸªÅÚ™‰µ¼0Ó'¤Qð:¯êj†i¿l:23{åÉrÉôæfY4/r öY­†žõrÁYUfˆ˜0Û[õ©\6sŒy cà 3bÂãKØ :¢3ö‘Nª¬Cÿb}‚È~ ¦(Ьë…=Øg6™ÒV§0rÉØ¸YnS¯6š à¶·QΟõbSÈ<¯UrvIB¯»”9p'}€·’ ´êC»”±¦Öv<7Ùµ¥UVF3õyÄ(Äje$÷ÀéE¦åÉÍq¼Ÿ°×„ðtL³©îWÕªQ´Ó»*ÏþÈÀ†²3?qÅÑŠU,]Ô$Õ K×›„!Ê…#‹ ‚ÃCÐ×±N°Æè%<2ϲ<{(óˆ‘)ɱ­€|¸fÉùõ”qÌ8H»šyEì6 p×Ç^rh튀Óôæ§‚Àµ!;YްŠeJ UÇQo%ý‰DBsCCý²hsôÂT¯œŽ]dcã¢ó?dÔνþ¿–3kÅ¥wÌþ¨¿ƒù¢ï½’oJ§ÀŒÇ?¥¬_1Ÿ¥cәܶidx±,‘Q[–šD¦“øHšÖy¡ëWTX–õ@³åÝHÄEÜ#oÏõò£Â²¢†4?ÂéG¿Ðìå?Dý0×,Œøc4Û«O0?æ8X¦ù–1gõ?‚ÂékyoR×5‡arØ‘‡/Qžo„¾ „IƉ›>é¼—:ÈO‡'ÚòþðWêiu¸º•s¢CÏq¤l¹eª £¶é`C]ŒÚi}tz}iuSã騟£Õu)rsdÀBQ´¦n»åøEìmŸéÁ4Öî«õØâp4ç#–5=|Á)¢ó Ç~º1‰ð¸Îiúy¿{‚ŸZŽ!Îï‹7e¡eʧ i?3ò»šœ¾“íë÷77x<á;"РŠ˜ Ç^Ýxÿ´}ÔIӻǰíUÌ+R÷S _|ÊH‚ƒ`;ñ¼2:ô;ÛqÄn›.vHC‚¶AØÁ$‰ÂÑz‡öÀjsïšc¼¾ÃÚ¤.­®ÏÑößY;vÔYŒèõó´A¸ý·®ŠC³_»ÊšO¹O×a Oáx»µ^ºNé]‡µÍ·­÷EÉÁ£¢3òg£ß¯ƒñ6VlWA÷‰ö䃢'Ê-èyÓƒP] æ±ê“´‡²”]”¹K/¬AÓúT2ÊP¤ôÇ!øˆË‘²m’È ”Û’¶‰ršH»g­c@‹ ?ü8|-ø¯¨¾Êm¯#ŸšÌÐñ:ÊPïàõWºu9fˆ­}AîÑV¦cS“%Ý^Û2tfˆÊJÞ$Õ¯(¯âÍTùàìåÓ³—ߤۈr™Òé:Li£6*'Uz ¹”ëýCûOo÷Eäq7Z¯Mˆë!äF7åIÎ9mÇ‚²ƒ|¹˜›j>õÒmê¥@ÒiíPIù yò—œ`Ão]™“m-ø,WNÙDm¤úsõ§ëgáe™[þÊi—“çŸÝü­w뤮 zÕéd·îãéu3WƒÌ´Ñ£µWpí3¡^ê×^{8€>ØéºÞáʵž)Û§ËŸWýh@ ¿\ .pÇpò #1Á—[…`݆_2¹:¾íý¼Ê•K‘Wv\™û‘<7Ϩ9˜yWfÛ²4™z¼ÔÕW!ϨI†TiÊGÈ÷Ÿî£í¸mÕXÝüï ç“åWf8ÁR×–‡<Ÿ HÔDU}»òx”ÅÀ‹(»esêútyWÒ¯¸Û½×á•å"÷îâ–û.¿úõu½ðÀ•â;•“ÄåØgºÎaÄIÝœŽlµ«sÜUÆ J@­óîÞ àŽóxä5ȰiV}‚«»2¿¬¼Ìe£önð`Úaô¿Ú­û-ä©{Ì}õƒïtó”ïq랆üvðíà™`êÈQÊnŸ›r‚-põºÞBÈꉀTÕsë>™ãeä> ||[šndNmçnWÇIÀ²Ÿºò[È×€'ºòAO– §ÖB0ü¥×à@(AÚJîÕVTÉ&Û%lñF(¯wñ´Wø.ýÆùcgÌ)ý¯¹ ‚C‘^ëµbé¿þÕsqò€sÓÖéu2˜WkmtÅo[惹!¼¼cÛ‚tt»’Ý9 ÁIA°B¾àòäuðùàð#°Ó)NÝð7ÁÏ xFEÖ]¾Ù­Ë(9\ ¦-‚‰ôsðÿ©^¸é(¤—€ïóÚ+àïƒÇIߟ¤Ì¶<âe´ï&1rðçdðvð­îxøšcêù·HÏ߈k^™ö ü.ÓW Üj‚îÂpÑ?|Z¸éYù?kÿ´õÉuoP|êè²ê«gŒÙyö„¡WÍ;×8Þ€ƒÔËu’rPm£úöZqã7 #¿še3ÕV—מt¯6~Ô!ÿ „‘{˜›¯…Û"¤$˜¤o¦Öxo˜-°ócðJäA¹!Ðt®q—CÖ ½×­»e¤^`FWTr?R>QH¿¼}qB©“ ÈÔqÂpìW‡9N‚µ=ÒãHÝ­Ä Kß›«‘¾&q°œüm0'æ#¨ó{¤$>}µÍdÉQþ~¥ÀÝá5à‚gº üÅ:¹~Ãû›_}å†S…±'Ž)Úúe—}g€ÁýªŽ.* ðÖFO=¹hò¥7æUàFæ—WÉÄçpØV„¡àǃ‚᜙˃¯!?¼<º|¤p:¥ßTF0RòëÆd¾>™(€k½AOâ“‚DÀŽ8iH|rØ/— ôáZðð0—º/d!­Ó©®@™“‚Ëœ¶Ä1r¼6¸<ýrCJÊ&3f(9®Ï÷·  œ;7y¬4¥X»wý¾Ú½-e>»:2îÄüй¯†“<Ò©œ¤^Z¨mÞ)äà~Áðä*9«ê{EóP§äó8Á‘vsBÈÿüú­’Œ¢Œ€u¬¨9Ò­ÇócêŽSÑž‘”tv2Ÿº)mƒ@!i°k9}ÂèºLYO×á>Aë®A9×è¢ì2¤3 s,m‰mROW™Þ?ué2«° qÇÉ·<̧}ÅG‹~jQìu+p§_)œmhjþ¤¶)Þ[´ìö™†O?¥d 6W±^Å*¼\X=Éb¾ ,ÏÁçæ½ÅÇ{¦ŒÊ=å¹ÛÝyŽa "À& ÀÓ6ê°Y—ãÛ·‚¡ßCŸ1s½zÞä `ÒÓЯBúm%aÍ ™€Òkð  ùJðKhû6R‚¤'í’r’‰ê—Y‚Hùi! @ÛÀ¼÷¯Ãn9}‰Tcᔓ¸¶é÷•”|ê¸ÙTÂÈÏþ5X©ÐË.?ÈÚ.ý@âxt4çæ”>!È/E×"%!Ûõ{ÂŽºUTâZ‘rcCýî–¨íþ‚¼D}Ü¿h€+\a„nþ£x Ž«aÍ­›Ãæ9%fÛ±‚øöÝçžÐ2p5˜íik˜vI€ ¼Rð?À$5Á1¦e'Çô.˜›Î‰à]`’ŽöÌ/s ÃM#íÜ ^&=”> ™ãy‡ Ð|ð>0#=ý¢ÖÿÌw…ÔÑYW |ÑmáxŒ™½Jyûã¤K§ºeLñžDüÀ^ n÷{ …3¬`ó®DÍžÍ[jë«£f~þ¤ÓJÎÜàĈ°ñ0Ò{Ôqk«ÍºÇXÿ“GwªMTò¬žÍÄ5qœÉQj¯#Ý‘ôö<–cäWÔŽ¬&—Ö§§¨{ˆN—!íp3—®OϧÛg¾­ò!}ê6е½–Ç ÛIÚíÀ­.Šÿ†Ç¿ã'FñóOª8³S«¶:–p°6t„ããv)¯(¡˜ãõËãøX³Y·%Œ=ºƒãÒçN´dt¿w?óGŸüÝ_~¶pü“² o3t‰óޤoê¥/{`ý``ºzöI6ÁŒúÜ”òɪǢmp=ÎëÑ6eÖÕ2¿ï ž:–éHK[´«£"õ$ÕW2›üuÛ²¿ô¾[6¹Nf}ö¡Ç£®›:Z=‚ñ¤ÆÇú™ n nn*¹i¤ªnx˔ѹS ë?Üó†»~þUlY`ø/ôê0ŶÆñY"‘(Ûwýþ\cÙ×üâ®UòUåTÖÂ]É„ƒ³6¾<tKp{©G×Íg§•_%÷aÞ ŠòÔ5©×Î`=/tY6í^è–‘›.J-lÅ}½F[7îspÄpÚ%×—Ÿ2¼ÿè¾…þü ¦­OÄlË‰Úø‡Ž-£õÑDÃÎ(¡ü?4ã"ê[è«í=~À›÷ýõòyoU`ÎìQ–lN îu+³£mën n\Œ·¸oáÝØ<Ì5[yÆ;øº3ÅÉC† z\q¯² ß›óOX˜_ܰ®!V³+âIˆxÞ á¡=Á‘Ç­þÛ§+®]ðÞ]Àrݲ™3­òªªÔ)D[geåîåî n®¸#çÒÊ;2_x}%¹Ö^O/gçæ0ZÇr‚ÝÆÛ‘¯Þ;å¶‘¾-–³{û¾àðqE;ÌAů­yïÉÿxx+_¨Dù:^½ÔAƒ,õ ð¨¨[— 3EÁ‘ "üîÖ¦p`ïÎø¨uÆéeB~÷â±ÔÕ_sшz¿Ï²V¸%tòø>[åñ½ž~~Í/ç<ô÷ŸÁF”§/Y`wKt8èn n}U â9AвÈÖÑôþѰv§¨/;¤å-‘›Ã¡P®í:½lS¸ùÄÒeóþó©½ÒFú±¢¶™M{†øèî1D ãbÒ7‚\ºˆ¡…"‘¾Üw¶5×+Áy9³Ô#=Ðí#÷áî NS’¯ÓQ!Ô×—ûç×^ÜôìƒU7Øsù†ú,°罞QÞm7”¹Ÿàv#¹¸ë2£(V+¼øRð³ìQ_gžë9ú îönQv}ÝžWznÙ1nÅy“kòž{7³Wvþê¨òmH@1@IEND®B`‚numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/img/scipy_org_logo.gif0000664000175100017510000000556512370216246030505 0ustar vagrantvagrant00000000000000GIF89an>Õ©ØÃÏ꨻áÞäóôöûÒÒÒµÅ墷ߜ²ÜíðùÑÙïåéö¯ÀãÊÔìØßñ¼Êçäº]ËµŠ¯¯±¶±¨ ³Õ°½Ôظv¡¬ÃÞ¹jij”Ò·½²žð¾=ÁÇÓ¨®»ê¼Nö¿*–­Ú˜«Ìœ±Öÿ¨¸ÕÎÐÒµÀÔñðï¹ÂÔÊÍÓ½ÅÔ¤µÕ´ÃâÖ×Ö÷ööÜÜÛ·ÂÖïîí±ÀßÜáïÅÊÒÿÿÿŒªæ!ù,n>ÿÀ›pH,ȤrÉl:ŸÐ¨tJ­Z¯Ø¬vËíz¿à°xL.›Ïè´zÍn»ßð¸|N¯Ûïø¼~Ïß" ‚}‡ˆ‰Šf6‘’“ †‹˜™š›F“ ¡‘ œ¦§¨u ¢­¡¥©²³´`Ÿ®¹  µ¾¿ÀN® ÇĹÁÍÎÀ ¹ Fѹ —ÏÛÜ™×¢ÚGÊàâÝèéw߯ÔKå¯çêôõkì¡Nº öÿÍfä€îˆÐ5  Ã‡[à¹òWÄÁ$FXåŠu€Ä ™àjõ HƒP‰HÌEíAÊ0cÞ˜Kß­ àŠÀ€ÿRzí{ÐàXƒó¨,DäÏÒ§LeJ£ÑU‘­t’´ ÀÁ" @QVßöœñüTöª\¹CŽ$jÅ‹µÒÿÉõÏÄÈ{¼‘X pU7’‰ ØTÕx‡ÿ|a˜JZBèŠöV˜`(ß@‚g?ÈÁ`'AupŽÁuËÁ‹ÓfˆÁÙ f0›3/H±,/’áº.„äˆÁõfAR]ôN’Hêù¼ ‰ß ÄØp$¼ÌÈD 2.Cšp¨D } v¯¨XÄva:«C'Ê€ˆ.Ý \(×2€¸ pKnDðà‹„0 Íp)áÐV†õ±¯ ›“Üä” 8&lFsÎö'Åü„9 8‹G¾Á)¾è Å1•]®Hôp­¦šQ~¨@È`¦[ßÏ ›Ñ!B&졃VÀNIÿ¬ñC‚Æ IÝ`–ŠÄÜÁD…IîŠ\ó£$œD® `i€l"½Š€*úi0Wë P¼xH Î$ô„âÁ7„Ø7Æù1 P€s@áÔå±wæIÚ+‰ Œ! J ¥2ÕHlr)‚åÏTUùÂ&9=~ŠbJ €4§I!P`E¨æé ò•DåIè9Àrα¤!ü,‚xÀiÂy n~“ D[eÑ \ “»” 5oN’ …ôaÖP1L §3~4B0‰4LIF¢lÊ0€}P55-,³(È«gNz”“½'±)„ @·ÂÑæ¥\C/ÿ<éW§4ªÞe¥nÅ-õ¿d܆qwôÌð‰ä8! …|Wnp®öñ_Kk¨!oú¹× 2P³¨GCú¤÷Ñ® E'M@R“a!xIŽM> †`!n‰)ÖžD^ ¡(6õË1ðb:%ä"•z@PAEIÉ9µ)K˜QCŒÚ¤Ž UAÀ`,Èþ1”s¥*zö:0\”«Q«ZV“P€H“¤C(À L ‚’žt®’ÐR¢¡~X²> 1„\ç%„“…'xŠ1ø:…Y>¬ ƒ¥ê¹rÁ˜àb ó;Ý?UÂq8–_PÀä4²Æª‚ñ_Î!&fð¾¬õõ Ÿ%ÿX2ÎÛQv eAjp³Âv‰¢ÐÇ@@$àúS¦7àÌ1ÝꔸRÀ§Ï’PÄQ˜§'JøF_©R“„|ìSÙÛ”¬Ib´äÊ¿BÉ©(4¤PÀ165†ôj¡´§…oFK Zûò6¶O¡­?@$œôb·½µ1`Î\ ¸Âvõ‰’Äêâ4Æmrz&Á˜ya© ~—œYÁ¸=B‰dI)&@Š£\Ì#¬G€ó `‚×Þx‰j Aï„`´ª@‘P'úà‰^•ìå,K‚£F¬^uâgm´¨²pÚSØÎV˜ËSm´ÿ2-èªrù´ÏJ4ýT4ç/vï ›àÍŠ´Èu®K 8ß œ<«%“ç™Ø€Gá'«Qjz:÷ÔE?¿¦èÍ2š Å,ÂH¿È !ÊUcÂ~F镃4g”D¨ )oéÎi¸ËQX® ÄAšÏ,wü@؆hbcæÂ'ŒÌÂEUÀë&xj¼Dè€ÂÞ¡B ÞKO¡/p§ 8à ÐHWŠà‰ ‚òt¿k«pØ%ô¨b+9‡‚—º¯œ<¹Gq*F€f`Rœd_…â‡sƒ”éçw’À°o0o—{qW(À;Èý— p%GÀPÈt$€VÀ3ðPàu¯€ ¥Q~²ÐMt š·Õ%ƒˆ PòÔ΄Fø …7„Ft„L¨¶¢„ÇׄR˜íBƒ;S˜…õ@`Çç§…b8†dX†fx†h˜†j¸†l؆nø†p‡rèA;numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/less/0000775000175100017510000000000012371375427025167 5ustar vagrantvagrant00000000000000numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/less/spc-rightsidebar.less0000664000175100017510000000040312370216246031276 0ustar vagrantvagrant00000000000000@import "bootstrap/variables.less"; .spc-rightsidebar { color: @gray; .navigation { padding: @paddingSmall; font-size: @fontSizeSmall; } .navigation .nav-title { font-weight: bold; text-transform: uppercase; } .navigation li { margin: 5px; } } numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/less/spc-footer.less0000664000175100017510000000023212370216246030125 0ustar vagrantvagrant00000000000000@import "bootstrap/variables.less"; //footer-outside .footer { padding: 5px; font-size: small; } //footer inside yet to be done (may be not required).numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/less/spc-bootstrap.less0000664000175100017510000000070112370216246030645 0ustar vagrantvagrant00000000000000// spc bootstrap settings @import "bootstrap/bootstrap.less"; @import "bootstrap/responsive.less"; // google webfont @import url(http://fonts.googleapis.com/css?family=Open+Sans); //Typography @sansFontFamily: 'Open Sans', sans-serif !important; @baseFontSize: 13px; @baseLineHeight: 19px; //Colors @blue: #12567D; //Sprites @iconSpritePath: '../../img/glyphicons-halflings.png'; @iconWhiteSpritePath: '../../img/glyphicons-halflings-white.png';numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/less/spc-extend.less0000664000175100017510000000055512370216246030126 0ustar vagrantvagrant00000000000000//spc extend settings body { background-color: rgb(249,250,245); } .container { width: 80%; } .main { background-color: white; padding: 18px; -moz-box-shadow: 0 0 3px #888; -webkit-box-shadow: 0 0 3px #888; box-shadow: 0 0 3px #888; } @import "spc-header.less"; @import "spc-content.less"; @import "spc-rightsidebar.less"; @import "spc-footer.less";numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/less/spc-content.less0000664000175100017510000000150012370216246030300 0ustar vagrantvagrant00000000000000@import "spc-utils.less"; @import "bootstrap/variables.less"; .spc-page-title { h1, h2, h3, h4 { font-weight: normal; .underline; } } //tags -- depricated // need to design .tags .btn { border: none; font-size: 9.5px; font-weight: bold; } // search item specific settings .spc-search-result { &-title { h1, h2, h3, h4 { font-weight: normal; } } } // snippet specific settings .spc-snippet-header { margin-bottom: 5px; } .spc-snippet-info { padding-top: 10px; .dl-horizontal { margin: 5px; dt { font-weight: normal; } } } .spc-snippet-body { padding: 10px; .accordion-group { border: none; } .accordion-heading { text-transform: uppercase; font-size: 14px; border-bottom: 1px solid #e5e5e5; } .accordion-heading .accordion-toggle { padding-top: 10px; padding-bottom: 5px; } } numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/less/spc-utils.less0000664000175100017510000000065112370216246027774 0ustar vagrantvagrant00000000000000// LESS Utilities for spc @import "bootstrap/variables.less"; .padding (@top: 0px, @bottom: 0px, @left: 0px, @right: 0px) { padding-top: @top; padding-bottom: @bottom; padding-left: @left; padding-right: @right; } .margin (@top: 0px, @bottom: 0px, @left: 0px, @right: 0px) { margin-top: @top; margin-bottom: @bottom; margin-left: @left; margin-right:@right; } .underline { border-bottom: 1.5px solid @hrBorder; } numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/less/bootstrap/0000775000175100017510000000000012371375427027204 5ustar vagrantvagrant00000000000000numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/less/bootstrap/mixins.less0000664000175100017510000005500212370216246031375 0ustar vagrantvagrant00000000000000// // Mixins // -------------------------------------------------- // UTILITY MIXINS // -------------------------------------------------- // Clearfix // -------- // For clearing floats like a boss h5bp.com/q .clearfix { *zoom: 1; &:before, &:after { display: table; content: ""; // Fixes Opera/contenteditable bug: // http://nicolasgallagher.com/micro-clearfix-hack/#comment-36952 line-height: 0; } &:after { clear: both; } } // Webkit-style focus // ------------------ .tab-focus() { // Default outline: thin dotted #333; // Webkit outline: 5px auto -webkit-focus-ring-color; outline-offset: -2px; } // Center-align a block level element // ---------------------------------- .center-block() { display: block; margin-left: auto; margin-right: auto; } // IE7 inline-block // ---------------- .ie7-inline-block() { *display: inline; /* IE7 inline-block hack */ *zoom: 1; } // IE7 likes to collapse whitespace on either side of the inline-block elements. // Ems because we're attempting to match the width of a space character. Left // version is for form buttons, which typically come after other elements, and // right version is for icons, which come before. Applying both is ok, but it will // mean that space between those elements will be .6em (~2 space characters) in IE7, // instead of the 1 space in other browsers. .ie7-restore-left-whitespace() { *margin-left: .3em; &:first-child { *margin-left: 0; } } .ie7-restore-right-whitespace() { *margin-right: .3em; } // Sizing shortcuts // ------------------------- .size(@height, @width) { width: @width; height: @height; } .square(@size) { .size(@size, @size); } // Placeholder text // ------------------------- .placeholder(@color: @placeholderText) { &:-moz-placeholder { color: @color; } &:-ms-input-placeholder { color: @color; } &::-webkit-input-placeholder { color: @color; } } // Text overflow // ------------------------- // Requires inline-block or block for proper styling .text-overflow() { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } // CSS image replacement // ------------------------- // Source: https://github.com/h5bp/html5-boilerplate/commit/aa0396eae757 .hide-text { font: 0/0 a; color: transparent; text-shadow: none; background-color: transparent; border: 0; } // FONTS // -------------------------------------------------- #font { #family { .serif() { font-family: @serifFontFamily; } .sans-serif() { font-family: @sansFontFamily; } .monospace() { font-family: @monoFontFamily; } } .shorthand(@size: @baseFontSize, @weight: normal, @lineHeight: @baseLineHeight) { font-size: @size; font-weight: @weight; line-height: @lineHeight; } .serif(@size: @baseFontSize, @weight: normal, @lineHeight: @baseLineHeight) { #font > #family > .serif; #font > .shorthand(@size, @weight, @lineHeight); } .sans-serif(@size: @baseFontSize, @weight: normal, @lineHeight: @baseLineHeight) { #font > #family > .sans-serif; #font > .shorthand(@size, @weight, @lineHeight); } .monospace(@size: @baseFontSize, @weight: normal, @lineHeight: @baseLineHeight) { #font > #family > .monospace; #font > .shorthand(@size, @weight, @lineHeight); } } // FORMS // -------------------------------------------------- // Block level inputs .input-block-level { display: block; width: 100%; min-height: @inputHeight; // Make inputs at least the height of their button counterpart (base line-height + padding + border) .box-sizing(border-box); // Makes inputs behave like true block-level elements } // Mixin for form field states .formFieldState(@textColor: #555, @borderColor: #ccc, @backgroundColor: #f5f5f5) { // Set the text color .control-label, .help-block, .help-inline { color: @textColor; } // Style inputs accordingly .checkbox, .radio, input, select, textarea { color: @textColor; } input, select, textarea { border-color: @borderColor; .box-shadow(inset 0 1px 1px rgba(0,0,0,.075)); // Redeclare so transitions work &:focus { border-color: darken(@borderColor, 10%); @shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 6px lighten(@borderColor, 20%); .box-shadow(@shadow); } } // Give a small background color for input-prepend/-append .input-prepend .add-on, .input-append .add-on { color: @textColor; background-color: @backgroundColor; border-color: @textColor; } } // CSS3 PROPERTIES // -------------------------------------------------- // Border Radius .border-radius(@radius) { -webkit-border-radius: @radius; -moz-border-radius: @radius; border-radius: @radius; } // Single Corner Border Radius .border-top-left-radius(@radius) { -webkit-border-top-left-radius: @radius; -moz-border-radius-topleft: @radius; border-top-left-radius: @radius; } .border-top-right-radius(@radius) { -webkit-border-top-right-radius: @radius; -moz-border-radius-topright: @radius; border-top-right-radius: @radius; } .border-bottom-right-radius(@radius) { -webkit-border-bottom-right-radius: @radius; -moz-border-radius-bottomright: @radius; border-bottom-right-radius: @radius; } .border-bottom-left-radius(@radius) { -webkit-border-bottom-left-radius: @radius; -moz-border-radius-bottomleft: @radius; border-bottom-left-radius: @radius; } // Single Side Border Radius .border-top-radius(@radius) { .border-top-right-radius(@radius); .border-top-left-radius(@radius); } .border-right-radius(@radius) { .border-top-right-radius(@radius); .border-bottom-right-radius(@radius); } .border-bottom-radius(@radius) { .border-bottom-right-radius(@radius); .border-bottom-left-radius(@radius); } .border-left-radius(@radius) { .border-top-left-radius(@radius); .border-bottom-left-radius(@radius); } // Drop shadows .box-shadow(@shadow) { -webkit-box-shadow: @shadow; -moz-box-shadow: @shadow; box-shadow: @shadow; } // Transitions .transition(@transition) { -webkit-transition: @transition; -moz-transition: @transition; -o-transition: @transition; transition: @transition; } .transition-delay(@transition-delay) { -webkit-transition-delay: @transition-delay; -moz-transition-delay: @transition-delay; -o-transition-delay: @transition-delay; transition-delay: @transition-delay; } .transition-duration(@transition-duration) { -webkit-transition-duration: @transition-duration; -moz-transition-duration: @transition-duration; -o-transition-duration: @transition-duration; transition-duration: @transition-duration; } // Transformations .rotate(@degrees) { -webkit-transform: rotate(@degrees); -moz-transform: rotate(@degrees); -ms-transform: rotate(@degrees); -o-transform: rotate(@degrees); transform: rotate(@degrees); } .scale(@ratio) { -webkit-transform: scale(@ratio); -moz-transform: scale(@ratio); -ms-transform: scale(@ratio); -o-transform: scale(@ratio); transform: scale(@ratio); } .translate(@x, @y) { -webkit-transform: translate(@x, @y); -moz-transform: translate(@x, @y); -ms-transform: translate(@x, @y); -o-transform: translate(@x, @y); transform: translate(@x, @y); } .skew(@x, @y) { -webkit-transform: skew(@x, @y); -moz-transform: skew(@x, @y); -ms-transform: skewX(@x) skewY(@y); // See https://github.com/twitter/bootstrap/issues/4885 -o-transform: skew(@x, @y); transform: skew(@x, @y); -webkit-backface-visibility: hidden; // See https://github.com/twitter/bootstrap/issues/5319 } .translate3d(@x, @y, @z) { -webkit-transform: translate3d(@x, @y, @z); -moz-transform: translate3d(@x, @y, @z); -o-transform: translate3d(@x, @y, @z); transform: translate3d(@x, @y, @z); } // Backface visibility // Prevent browsers from flickering when using CSS 3D transforms. // Default value is `visible`, but can be changed to `hidden // See git pull https://github.com/dannykeane/bootstrap.git backface-visibility for examples .backface-visibility(@visibility){ -webkit-backface-visibility: @visibility; -moz-backface-visibility: @visibility; backface-visibility: @visibility; } // Background clipping // Heads up: FF 3.6 and under need "padding" instead of "padding-box" .background-clip(@clip) { -webkit-background-clip: @clip; -moz-background-clip: @clip; background-clip: @clip; } // Background sizing .background-size(@size) { -webkit-background-size: @size; -moz-background-size: @size; -o-background-size: @size; background-size: @size; } // Box sizing .box-sizing(@boxmodel) { -webkit-box-sizing: @boxmodel; -moz-box-sizing: @boxmodel; box-sizing: @boxmodel; } // User select // For selecting text on the page .user-select(@select) { -webkit-user-select: @select; -moz-user-select: @select; -ms-user-select: @select; -o-user-select: @select; user-select: @select; } // Resize anything .resizable(@direction) { resize: @direction; // Options: horizontal, vertical, both overflow: auto; // Safari fix } // CSS3 Content Columns .content-columns(@columnCount, @columnGap: @gridGutterWidth) { -webkit-column-count: @columnCount; -moz-column-count: @columnCount; column-count: @columnCount; -webkit-column-gap: @columnGap; -moz-column-gap: @columnGap; column-gap: @columnGap; } // Optional hyphenation .hyphens(@mode: auto) { word-wrap: break-word; -webkit-hyphens: @mode; -moz-hyphens: @mode; -ms-hyphens: @mode; -o-hyphens: @mode; hyphens: @mode; } // Opacity .opacity(@opacity) { opacity: @opacity / 100; filter: ~"alpha(opacity=@{opacity})"; } // BACKGROUNDS // -------------------------------------------------- // Add an alphatransparency value to any background or border color (via Elyse Holladay) #translucent { .background(@color: @white, @alpha: 1) { background-color: hsla(hue(@color), saturation(@color), lightness(@color), @alpha); } .border(@color: @white, @alpha: 1) { border-color: hsla(hue(@color), saturation(@color), lightness(@color), @alpha); .background-clip(padding-box); } } // Gradient Bar Colors for buttons and alerts .gradientBar(@primaryColor, @secondaryColor, @textColor: #fff, @textShadow: 0 -1px 0 rgba(0,0,0,.25)) { color: @textColor; text-shadow: @textShadow; #gradient > .vertical(@primaryColor, @secondaryColor); border-color: @secondaryColor @secondaryColor darken(@secondaryColor, 15%); border-color: rgba(0,0,0,.1) rgba(0,0,0,.1) fadein(rgba(0,0,0,.1), 15%); } // Gradients #gradient { .horizontal(@startColor: #555, @endColor: #333) { background-color: @endColor; background-image: -moz-linear-gradient(left, @startColor, @endColor); // FF 3.6+ background-image: -webkit-gradient(linear, 0 0, 100% 0, from(@startColor), to(@endColor)); // Safari 4+, Chrome 2+ background-image: -webkit-linear-gradient(left, @startColor, @endColor); // Safari 5.1+, Chrome 10+ background-image: -o-linear-gradient(left, @startColor, @endColor); // Opera 11.10 background-image: linear-gradient(to right, @startColor, @endColor); // Standard, IE10 background-repeat: repeat-x; filter: e(%("progid:DXImageTransform.Microsoft.gradient(startColorstr='%d', endColorstr='%d', GradientType=1)",argb(@startColor),argb(@endColor))); // IE9 and down } .vertical(@startColor: #555, @endColor: #333) { background-color: mix(@startColor, @endColor, 60%); background-image: -moz-linear-gradient(top, @startColor, @endColor); // FF 3.6+ background-image: -webkit-gradient(linear, 0 0, 0 100%, from(@startColor), to(@endColor)); // Safari 4+, Chrome 2+ background-image: -webkit-linear-gradient(top, @startColor, @endColor); // Safari 5.1+, Chrome 10+ background-image: -o-linear-gradient(top, @startColor, @endColor); // Opera 11.10 background-image: linear-gradient(to bottom, @startColor, @endColor); // Standard, IE10 background-repeat: repeat-x; filter: e(%("progid:DXImageTransform.Microsoft.gradient(startColorstr='%d', endColorstr='%d', GradientType=0)",argb(@startColor),argb(@endColor))); // IE9 and down } .directional(@startColor: #555, @endColor: #333, @deg: 45deg) { background-color: @endColor; background-repeat: repeat-x; background-image: -moz-linear-gradient(@deg, @startColor, @endColor); // FF 3.6+ background-image: -webkit-linear-gradient(@deg, @startColor, @endColor); // Safari 5.1+, Chrome 10+ background-image: -o-linear-gradient(@deg, @startColor, @endColor); // Opera 11.10 background-image: linear-gradient(@deg, @startColor, @endColor); // Standard, IE10 } .horizontal-three-colors(@startColor: #00b3ee, @midColor: #7a43b6, @colorStop: 50%, @endColor: #c3325f) { background-color: mix(@midColor, @endColor, 80%); background-image: -webkit-gradient(left, linear, 0 0, 0 100%, from(@startColor), color-stop(@colorStop, @midColor), to(@endColor)); background-image: -webkit-linear-gradient(left, @startColor, @midColor @colorStop, @endColor); background-image: -moz-linear-gradient(left, @startColor, @midColor @colorStop, @endColor); background-image: -o-linear-gradient(left, @startColor, @midColor @colorStop, @endColor); background-image: linear-gradient(to right, @startColor, @midColor @colorStop, @endColor); background-repeat: no-repeat; filter: e(%("progid:DXImageTransform.Microsoft.gradient(startColorstr='%d', endColorstr='%d', GradientType=0)",argb(@startColor),argb(@endColor))); // IE9 and down, gets no color-stop at all for proper fallback } .vertical-three-colors(@startColor: #00b3ee, @midColor: #7a43b6, @colorStop: 50%, @endColor: #c3325f) { background-color: mix(@midColor, @endColor, 80%); background-image: -webkit-gradient(linear, 0 0, 0 100%, from(@startColor), color-stop(@colorStop, @midColor), to(@endColor)); background-image: -webkit-linear-gradient(@startColor, @midColor @colorStop, @endColor); background-image: -moz-linear-gradient(top, @startColor, @midColor @colorStop, @endColor); background-image: -o-linear-gradient(@startColor, @midColor @colorStop, @endColor); background-image: linear-gradient(@startColor, @midColor @colorStop, @endColor); background-repeat: no-repeat; filter: e(%("progid:DXImageTransform.Microsoft.gradient(startColorstr='%d', endColorstr='%d', GradientType=0)",argb(@startColor),argb(@endColor))); // IE9 and down, gets no color-stop at all for proper fallback } .radial(@innerColor: #555, @outerColor: #333) { background-color: @outerColor; background-image: -webkit-gradient(radial, center center, 0, center center, 460, from(@innerColor), to(@outerColor)); background-image: -webkit-radial-gradient(circle, @innerColor, @outerColor); background-image: -moz-radial-gradient(circle, @innerColor, @outerColor); background-image: -o-radial-gradient(circle, @innerColor, @outerColor); background-repeat: no-repeat; } .striped(@color: #555, @angle: 45deg) { background-color: @color; background-image: -webkit-gradient(linear, 0 100%, 100% 0, color-stop(.25, rgba(255,255,255,.15)), color-stop(.25, transparent), color-stop(.5, transparent), color-stop(.5, rgba(255,255,255,.15)), color-stop(.75, rgba(255,255,255,.15)), color-stop(.75, transparent), to(transparent)); background-image: -webkit-linear-gradient(@angle, rgba(255,255,255,.15) 25%, transparent 25%, transparent 50%, rgba(255,255,255,.15) 50%, rgba(255,255,255,.15) 75%, transparent 75%, transparent); background-image: -moz-linear-gradient(@angle, rgba(255,255,255,.15) 25%, transparent 25%, transparent 50%, rgba(255,255,255,.15) 50%, rgba(255,255,255,.15) 75%, transparent 75%, transparent); background-image: -o-linear-gradient(@angle, rgba(255,255,255,.15) 25%, transparent 25%, transparent 50%, rgba(255,255,255,.15) 50%, rgba(255,255,255,.15) 75%, transparent 75%, transparent); background-image: linear-gradient(@angle, rgba(255,255,255,.15) 25%, transparent 25%, transparent 50%, rgba(255,255,255,.15) 50%, rgba(255,255,255,.15) 75%, transparent 75%, transparent); } } // Reset filters for IE .reset-filter() { filter: e(%("progid:DXImageTransform.Microsoft.gradient(enabled = false)")); } // COMPONENT MIXINS // -------------------------------------------------- // Horizontal dividers // ------------------------- // Dividers (basically an hr) within dropdowns and nav lists .nav-divider(@top: #e5e5e5, @bottom: @white) { // IE7 needs a set width since we gave a height. Restricting just // to IE7 to keep the 1px left/right space in other browsers. // It is unclear where IE is getting the extra space that we need // to negative-margin away, but so it goes. *width: 100%; height: 1px; margin: ((@baseLineHeight / 2) - 1) 1px; // 8px 1px *margin: -5px 0 5px; overflow: hidden; background-color: @top; border-bottom: 1px solid @bottom; } // Button backgrounds // ------------------ .buttonBackground(@startColor, @endColor, @textColor: #fff, @textShadow: 0 -1px 0 rgba(0,0,0,.25)) { // gradientBar will set the background to a pleasing blend of these, to support IE<=9 .gradientBar(@startColor, @endColor, @textColor, @textShadow); *background-color: @endColor; /* Darken IE7 buttons by default so they stand out more given they won't have borders */ .reset-filter(); // in these cases the gradient won't cover the background, so we override &:hover, &:focus, &:active, &.active, &.disabled, &[disabled] { color: @textColor; background-color: @endColor; *background-color: darken(@endColor, 5%); } // IE 7 + 8 can't handle box-shadow to show active, so we darken a bit ourselves &:active, &.active { background-color: darken(@endColor, 10%) e("\9"); } } // Navbar vertical align // ------------------------- // Vertically center elements in the navbar. // Example: an element has a height of 30px, so write out `.navbarVerticalAlign(30px);` to calculate the appropriate top margin. .navbarVerticalAlign(@elementHeight) { margin-top: (@navbarHeight - @elementHeight) / 2; } // Grid System // ----------- // Centered container element .container-fixed() { margin-right: auto; margin-left: auto; .clearfix(); } // Table columns .tableColumns(@columnSpan: 1) { float: none; // undo default grid column styles width: ((@gridColumnWidth) * @columnSpan) + (@gridGutterWidth * (@columnSpan - 1)) - 16; // 16 is total padding on left and right of table cells margin-left: 0; // undo default grid column styles } // Make a Grid // Use .makeRow and .makeColumn to assign semantic layouts grid system behavior .makeRow() { margin-left: @gridGutterWidth * -1; .clearfix(); } .makeColumn(@columns: 1, @offset: 0) { float: left; margin-left: (@gridColumnWidth * @offset) + (@gridGutterWidth * (@offset - 1)) + (@gridGutterWidth * 2); width: (@gridColumnWidth * @columns) + (@gridGutterWidth * (@columns - 1)); } // The Grid #grid { .core (@gridColumnWidth, @gridGutterWidth) { .spanX (@index) when (@index > 0) { .span@{index} { .span(@index); } .spanX(@index - 1); } .spanX (0) {} .offsetX (@index) when (@index > 0) { .offset@{index} { .offset(@index); } .offsetX(@index - 1); } .offsetX (0) {} .offset (@columns) { margin-left: (@gridColumnWidth * @columns) + (@gridGutterWidth * (@columns + 1)); } .span (@columns) { width: (@gridColumnWidth * @columns) + (@gridGutterWidth * (@columns - 1)); } .row { margin-left: @gridGutterWidth * -1; .clearfix(); } [class*="span"] { float: left; min-height: 1px; // prevent collapsing columns margin-left: @gridGutterWidth; } // Set the container width, and override it for fixed navbars in media queries .container, .navbar-static-top .container, .navbar-fixed-top .container, .navbar-fixed-bottom .container { .span(@gridColumns); } // generate .spanX and .offsetX .spanX (@gridColumns); .offsetX (@gridColumns); } .fluid (@fluidGridColumnWidth, @fluidGridGutterWidth) { .spanX (@index) when (@index > 0) { .span@{index} { .span(@index); } .spanX(@index - 1); } .spanX (0) {} .offsetX (@index) when (@index > 0) { .offset@{index} { .offset(@index); } .offset@{index}:first-child { .offsetFirstChild(@index); } .offsetX(@index - 1); } .offsetX (0) {} .offset (@columns) { margin-left: (@fluidGridColumnWidth * @columns) + (@fluidGridGutterWidth * (@columns - 1)) + (@fluidGridGutterWidth*2); *margin-left: (@fluidGridColumnWidth * @columns) + (@fluidGridGutterWidth * (@columns - 1)) - (.5 / @gridRowWidth * 100 * 1%) + (@fluidGridGutterWidth*2) - (.5 / @gridRowWidth * 100 * 1%); } .offsetFirstChild (@columns) { margin-left: (@fluidGridColumnWidth * @columns) + (@fluidGridGutterWidth * (@columns - 1)) + (@fluidGridGutterWidth); *margin-left: (@fluidGridColumnWidth * @columns) + (@fluidGridGutterWidth * (@columns - 1)) - (.5 / @gridRowWidth * 100 * 1%) + @fluidGridGutterWidth - (.5 / @gridRowWidth * 100 * 1%); } .span (@columns) { width: (@fluidGridColumnWidth * @columns) + (@fluidGridGutterWidth * (@columns - 1)); *width: (@fluidGridColumnWidth * @columns) + (@fluidGridGutterWidth * (@columns - 1)) - (.5 / @gridRowWidth * 100 * 1%); } .row-fluid { width: 100%; .clearfix(); [class*="span"] { .input-block-level(); float: left; margin-left: @fluidGridGutterWidth; *margin-left: @fluidGridGutterWidth - (.5 / @gridRowWidth * 100 * 1%); } [class*="span"]:first-child { margin-left: 0; } // Space grid-sized controls properly if multiple per line .controls-row [class*="span"] + [class*="span"] { margin-left: @fluidGridGutterWidth; } // generate .spanX and .offsetX .spanX (@gridColumns); .offsetX (@gridColumns); } } .input(@gridColumnWidth, @gridGutterWidth) { .spanX (@index) when (@index > 0) { input.span@{index}, textarea.span@{index}, .uneditable-input.span@{index} { .span(@index); } .spanX(@index - 1); } .spanX (0) {} .span(@columns) { width: ((@gridColumnWidth) * @columns) + (@gridGutterWidth * (@columns - 1)) - 14; } input, textarea, .uneditable-input { margin-left: 0; // override margin-left from core grid system } // Space grid-sized controls properly if multiple per line .controls-row [class*="span"] + [class*="span"] { margin-left: @gridGutterWidth; } // generate .spanX .spanX (@gridColumns); } } numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/less/bootstrap/labels-badges.less0000664000175100017510000000353412370216246032556 0ustar vagrantvagrant00000000000000// // Labels and badges // -------------------------------------------------- // Base classes .label, .badge { display: inline-block; padding: 2px 4px; font-size: @baseFontSize * .846; font-weight: bold; line-height: 14px; // ensure proper line-height if floated color: @white; vertical-align: baseline; white-space: nowrap; text-shadow: 0 -1px 0 rgba(0,0,0,.25); background-color: @grayLight; } // Set unique padding and border-radii .label { .border-radius(3px); } .badge { padding-left: 9px; padding-right: 9px; .border-radius(9px); } // Empty labels/badges collapse .label, .badge { &:empty { display: none; } } // Hover/focus state, but only for links a { &.label:hover, &.label:focus, &.badge:hover, &.badge:focus { color: @white; text-decoration: none; cursor: pointer; } } // Colors // Only give background-color difference to links (and to simplify, we don't qualifty with `a` but [href] attribute) .label, .badge { // Important (red) &-important { background-color: @errorText; } &-important[href] { background-color: darken(@errorText, 10%); } // Warnings (orange) &-warning { background-color: @orange; } &-warning[href] { background-color: darken(@orange, 10%); } // Success (green) &-success { background-color: @successText; } &-success[href] { background-color: darken(@successText, 10%); } // Info (turquoise) &-info { background-color: @infoText; } &-info[href] { background-color: darken(@infoText, 10%); } // Inverse (black) &-inverse { background-color: @grayDark; } &-inverse[href] { background-color: darken(@grayDark, 10%); } } // Quick fix for labels/badges in buttons .btn { .label, .badge { position: relative; top: -1px; } } .btn-mini { .label, .badge { top: 0; } } numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/less/bootstrap/responsive-1200px-min.less0000664000175100017510000000106512370216246033774 0ustar vagrantvagrant00000000000000// // Responsive: Large desktop and up // -------------------------------------------------- @media (min-width: 1200px) { // Fixed grid #grid > .core(@gridColumnWidth1200, @gridGutterWidth1200); // Fluid grid #grid > .fluid(@fluidGridColumnWidth1200, @fluidGridGutterWidth1200); // Input grid #grid > .input(@gridColumnWidth1200, @gridGutterWidth1200); // Thumbnails .thumbnails { margin-left: -@gridGutterWidth1200; } .thumbnails > li { margin-left: @gridGutterWidth1200; } .row-fluid .thumbnails { margin-left: 0; } } numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/less/bootstrap/media.less0000664000175100017510000000153412370216246031146 0ustar vagrantvagrant00000000000000// Media objects // Source: http://stubbornella.org/content/?p=497 // -------------------------------------------------- // Common styles // ------------------------- // Clear the floats .media, .media-body { overflow: hidden; *overflow: visible; zoom: 1; } // Proper spacing between instances of .media .media, .media .media { margin-top: 15px; } .media:first-child { margin-top: 0; } // For images and videos, set to block .media-object { display: block; } // Reset margins on headings for tighter default spacing .media-heading { margin: 0 0 5px; } // Media image alignment // ------------------------- .media > .pull-left { margin-right: 10px; } .media > .pull-right { margin-left: 10px; } // Media list variation // ------------------------- // Undo default ul/ol styles .media-list { margin-left: 0; list-style: none; } numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/less/bootstrap/popovers.less0000664000175100017510000000600512370216246031742 0ustar vagrantvagrant00000000000000// // Popovers // -------------------------------------------------- .popover { position: absolute; top: 0; left: 0; z-index: @zindexPopover; display: none; max-width: 276px; padding: 1px; text-align: left; // Reset given new insertion method background-color: @popoverBackground; -webkit-background-clip: padding-box; -moz-background-clip: padding; background-clip: padding-box; border: 1px solid #ccc; border: 1px solid rgba(0,0,0,.2); .border-radius(6px); .box-shadow(0 5px 10px rgba(0,0,0,.2)); // Overrides for proper insertion white-space: normal; // Offset the popover to account for the popover arrow &.top { margin-top: -10px; } &.right { margin-left: 10px; } &.bottom { margin-top: 10px; } &.left { margin-left: -10px; } } .popover-title { margin: 0; // reset heading margin padding: 8px 14px; font-size: 14px; font-weight: normal; line-height: 18px; background-color: @popoverTitleBackground; border-bottom: 1px solid darken(@popoverTitleBackground, 5%); .border-radius(5px 5px 0 0); &:empty { display: none; } } .popover-content { padding: 9px 14px; } // Arrows // // .arrow is outer, .arrow:after is inner .popover .arrow, .popover .arrow:after { position: absolute; display: block; width: 0; height: 0; border-color: transparent; border-style: solid; } .popover .arrow { border-width: @popoverArrowOuterWidth; } .popover .arrow:after { border-width: @popoverArrowWidth; content: ""; } .popover { &.top .arrow { left: 50%; margin-left: -@popoverArrowOuterWidth; border-bottom-width: 0; border-top-color: #999; // IE8 fallback border-top-color: @popoverArrowOuterColor; bottom: -@popoverArrowOuterWidth; &:after { bottom: 1px; margin-left: -@popoverArrowWidth; border-bottom-width: 0; border-top-color: @popoverArrowColor; } } &.right .arrow { top: 50%; left: -@popoverArrowOuterWidth; margin-top: -@popoverArrowOuterWidth; border-left-width: 0; border-right-color: #999; // IE8 fallback border-right-color: @popoverArrowOuterColor; &:after { left: 1px; bottom: -@popoverArrowWidth; border-left-width: 0; border-right-color: @popoverArrowColor; } } &.bottom .arrow { left: 50%; margin-left: -@popoverArrowOuterWidth; border-top-width: 0; border-bottom-color: #999; // IE8 fallback border-bottom-color: @popoverArrowOuterColor; top: -@popoverArrowOuterWidth; &:after { top: 1px; margin-left: -@popoverArrowWidth; border-top-width: 0; border-bottom-color: @popoverArrowColor; } } &.left .arrow { top: 50%; right: -@popoverArrowOuterWidth; margin-top: -@popoverArrowOuterWidth; border-right-width: 0; border-left-color: #999; // IE8 fallback border-left-color: @popoverArrowOuterColor; &:after { right: 1px; border-right-width: 0; border-left-color: @popoverArrowColor; bottom: -@popoverArrowWidth; } } } numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/less/bootstrap/utilities.less0000664000175100017510000000051712370216246032102 0ustar vagrantvagrant00000000000000// // Utility classes // -------------------------------------------------- // Quick floats .pull-right { float: right; } .pull-left { float: left; } // Toggling content .hide { display: none; } .show { display: block; } // Visibility .invisible { visibility: hidden; } // For Affix plugin .affix { position: fixed; } numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/less/bootstrap/pager.less0000664000175100017510000000137012370216246031163 0ustar vagrantvagrant00000000000000// // Pager pagination // -------------------------------------------------- .pager { margin: @baseLineHeight 0; list-style: none; text-align: center; .clearfix(); } .pager li { display: inline; } .pager li > a, .pager li > span { display: inline-block; padding: 5px 14px; background-color: #fff; border: 1px solid #ddd; .border-radius(15px); } .pager li > a:hover, .pager li > a:focus { text-decoration: none; background-color: #f5f5f5; } .pager .next > a, .pager .next > span { float: right; } .pager .previous > a, .pager .previous > span { float: left; } .pager .disabled > a, .pager .disabled > a:hover, .pager .disabled > a:focus, .pager .disabled > span { color: @grayLight; background-color: #fff; cursor: default; }numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/less/bootstrap/code.less0000664000175100017510000000240212370216246030774 0ustar vagrantvagrant00000000000000// // Code (inline and blocK) // -------------------------------------------------- // Inline and block code styles code, pre { padding: 0 3px 2px; #font > #family > .monospace; font-size: @baseFontSize - 2; color: @grayDark; .border-radius(3px); } // Inline code code { padding: 2px 4px; color: #d14; background-color: #f7f7f9; border: 1px solid #e1e1e8; white-space: nowrap; } // Blocks of code pre { display: block; padding: (@baseLineHeight - 1) / 2; margin: 0 0 @baseLineHeight / 2; font-size: @baseFontSize - 1; // 14px to 13px line-height: @baseLineHeight; word-break: break-all; word-wrap: break-word; white-space: pre; white-space: pre-wrap; background-color: #f5f5f5; border: 1px solid #ccc; // fallback for IE7-8 border: 1px solid rgba(0,0,0,.15); .border-radius(@baseBorderRadius); // Make prettyprint styles more spaced out for readability &.prettyprint { margin-bottom: @baseLineHeight; } // Account for some code outputs that place code tags in pre tags code { padding: 0; color: inherit; white-space: pre; white-space: pre-wrap; background-color: transparent; border: 0; } } // Enable scrollable blocks of code .pre-scrollable { max-height: 340px; overflow-y: scroll; }numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/less/bootstrap/component-animations.less0000664000175100017510000000046212370216246034230 0ustar vagrantvagrant00000000000000// // Component animations // -------------------------------------------------- .fade { opacity: 0; .transition(opacity .15s linear); &.in { opacity: 1; } } .collapse { position: relative; height: 0; overflow: hidden; .transition(height .35s ease); &.in { height: auto; } } numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/less/bootstrap/responsive-768px-979px.less0000664000175100017510000000071712370216246034056 0ustar vagrantvagrant00000000000000// // Responsive: Tablet to desktop // -------------------------------------------------- @media (min-width: 768px) and (max-width: 979px) { // Fixed grid #grid > .core(@gridColumnWidth768, @gridGutterWidth768); // Fluid grid #grid > .fluid(@fluidGridColumnWidth768, @fluidGridGutterWidth768); // Input grid #grid > .input(@gridColumnWidth768, @gridGutterWidth768); // No need to reset .thumbnails here since it's the same @gridGutterWidth } numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/less/bootstrap/pagination.less0000664000175100017510000000516612370216246032225 0ustar vagrantvagrant00000000000000// // Pagination (multiple pages) // -------------------------------------------------- // Space out pagination from surrounding content .pagination { margin: @baseLineHeight 0; } .pagination ul { // Allow for text-based alignment display: inline-block; .ie7-inline-block(); // Reset default ul styles margin-left: 0; margin-bottom: 0; // Visuals .border-radius(@baseBorderRadius); .box-shadow(0 1px 2px rgba(0,0,0,.05)); } .pagination ul > li { display: inline; // Remove list-style and block-level defaults } .pagination ul > li > a, .pagination ul > li > span { float: left; // Collapse white-space padding: 4px 12px; line-height: @baseLineHeight; text-decoration: none; background-color: @paginationBackground; border: 1px solid @paginationBorder; border-left-width: 0; } .pagination ul > li > a:hover, .pagination ul > li > a:focus, .pagination ul > .active > a, .pagination ul > .active > span { background-color: @paginationActiveBackground; } .pagination ul > .active > a, .pagination ul > .active > span { color: @grayLight; cursor: default; } .pagination ul > .disabled > span, .pagination ul > .disabled > a, .pagination ul > .disabled > a:hover, .pagination ul > .disabled > a:focus { color: @grayLight; background-color: transparent; cursor: default; } .pagination ul > li:first-child > a, .pagination ul > li:first-child > span { border-left-width: 1px; .border-left-radius(@baseBorderRadius); } .pagination ul > li:last-child > a, .pagination ul > li:last-child > span { .border-right-radius(@baseBorderRadius); } // Alignment // -------------------------------------------------- .pagination-centered { text-align: center; } .pagination-right { text-align: right; } // Sizing // -------------------------------------------------- // Large .pagination-large { ul > li > a, ul > li > span { padding: @paddingLarge; font-size: @fontSizeLarge; } ul > li:first-child > a, ul > li:first-child > span { .border-left-radius(@borderRadiusLarge); } ul > li:last-child > a, ul > li:last-child > span { .border-right-radius(@borderRadiusLarge); } } // Small and mini .pagination-mini, .pagination-small { ul > li:first-child > a, ul > li:first-child > span { .border-left-radius(@borderRadiusSmall); } ul > li:last-child > a, ul > li:last-child > span { .border-right-radius(@borderRadiusSmall); } } // Small .pagination-small { ul > li > a, ul > li > span { padding: @paddingSmall; font-size: @fontSizeSmall; } } // Mini .pagination-mini { ul > li > a, ul > li > span { padding: @paddingMini; font-size: @fontSizeMini; } } numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/less/bootstrap/breadcrumbs.less0000664000175100017510000000065712370216246032365 0ustar vagrantvagrant00000000000000// // Breadcrumbs // -------------------------------------------------- .breadcrumb { padding: 8px 15px; margin: 0 0 @baseLineHeight; list-style: none; background-color: #f5f5f5; .border-radius(@baseBorderRadius); > li { display: inline-block; .ie7-inline-block(); text-shadow: 0 1px 0 @white; > .divider { padding: 0 5px; color: #ccc; } } > .active { color: @grayLight; } } numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/less/bootstrap/accordion.less0000664000175100017510000000117412370216246032030 0ustar vagrantvagrant00000000000000// // Accordion // -------------------------------------------------- // Parent container .accordion { margin-bottom: @baseLineHeight; } // Group == heading + body .accordion-group { margin-bottom: 2px; border: 1px solid #e5e5e5; .border-radius(@baseBorderRadius); } .accordion-heading { border-bottom: 0; } .accordion-heading .accordion-toggle { display: block; padding: 8px 15px; } // General toggle styles .accordion-toggle { cursor: pointer; } // Inner needs the styles because you can't animate properly with any styles on the element .accordion-inner { padding: 9px 15px; border-top: 1px solid #e5e5e5; } numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/less/bootstrap/dropdowns.less0000664000175100017510000001256512370216246032114 0ustar vagrantvagrant00000000000000// // Dropdown menus // -------------------------------------------------- // Use the .menu class on any

  • element within the topbar or ul.tabs and you'll get some superfancy dropdowns .dropup, .dropdown { position: relative; } .dropdown-toggle { // The caret makes the toggle a bit too tall in IE7 *margin-bottom: -3px; } .dropdown-toggle:active, .open .dropdown-toggle { outline: 0; } // Dropdown arrow/caret // -------------------- .caret { display: inline-block; width: 0; height: 0; vertical-align: top; border-top: 4px solid @black; border-right: 4px solid transparent; border-left: 4px solid transparent; content: ""; } // Place the caret .dropdown .caret { margin-top: 8px; margin-left: 2px; } // The dropdown menu (ul) // ---------------------- .dropdown-menu { position: absolute; top: 100%; left: 0; z-index: @zindexDropdown; display: none; // none by default, but block on "open" of the menu float: left; min-width: 160px; padding: 5px 0; margin: 2px 0 0; // override default ul list-style: none; background-color: @dropdownBackground; border: 1px solid #ccc; // Fallback for IE7-8 border: 1px solid @dropdownBorder; *border-right-width: 2px; *border-bottom-width: 2px; .border-radius(6px); .box-shadow(0 5px 10px rgba(0,0,0,.2)); -webkit-background-clip: padding-box; -moz-background-clip: padding; background-clip: padding-box; // Aligns the dropdown menu to right &.pull-right { right: 0; left: auto; } // Dividers (basically an hr) within the dropdown .divider { .nav-divider(@dropdownDividerTop, @dropdownDividerBottom); } // Links within the dropdown menu > li > a { display: block; padding: 3px 20px; clear: both; font-weight: normal; line-height: @baseLineHeight; color: @dropdownLinkColor; white-space: nowrap; } } // Hover/Focus state // ----------- .dropdown-menu > li > a:hover, .dropdown-menu > li > a:focus, .dropdown-submenu:hover > a, .dropdown-submenu:focus > a { text-decoration: none; color: @dropdownLinkColorHover; #gradient > .vertical(@dropdownLinkBackgroundHover, darken(@dropdownLinkBackgroundHover, 5%)); } // Active state // ------------ .dropdown-menu > .active > a, .dropdown-menu > .active > a:hover, .dropdown-menu > .active > a:focus { color: @dropdownLinkColorActive; text-decoration: none; outline: 0; #gradient > .vertical(@dropdownLinkBackgroundActive, darken(@dropdownLinkBackgroundActive, 5%)); } // Disabled state // -------------- // Gray out text and ensure the hover/focus state remains gray .dropdown-menu > .disabled > a, .dropdown-menu > .disabled > a:hover, .dropdown-menu > .disabled > a:focus { color: @grayLight; } // Nuke hover/focus effects .dropdown-menu > .disabled > a:hover, .dropdown-menu > .disabled > a:focus { text-decoration: none; background-color: transparent; background-image: none; // Remove CSS gradient .reset-filter(); cursor: default; } // Open state for the dropdown // --------------------------- .open { // IE7's z-index only goes to the nearest positioned ancestor, which would // make the menu appear below buttons that appeared later on the page *z-index: @zindexDropdown; & > .dropdown-menu { display: block; } } // Right aligned dropdowns // --------------------------- .pull-right > .dropdown-menu { right: 0; left: auto; } // Allow for dropdowns to go bottom up (aka, dropup-menu) // ------------------------------------------------------ // Just add .dropup after the standard .dropdown class and you're set, bro. // TODO: abstract this so that the navbar fixed styles are not placed here? .dropup, .navbar-fixed-bottom .dropdown { // Reverse the caret .caret { border-top: 0; border-bottom: 4px solid @black; content: ""; } // Different positioning for bottom up menu .dropdown-menu { top: auto; bottom: 100%; margin-bottom: 1px; } } // Sub menus // --------------------------- .dropdown-submenu { position: relative; } // Default dropdowns .dropdown-submenu > .dropdown-menu { top: 0; left: 100%; margin-top: -6px; margin-left: -1px; .border-radius(0 6px 6px 6px); } .dropdown-submenu:hover > .dropdown-menu { display: block; } // Dropups .dropup .dropdown-submenu > .dropdown-menu { top: auto; bottom: 0; margin-top: 0; margin-bottom: -2px; .border-radius(5px 5px 5px 0); } // Caret to indicate there is a submenu .dropdown-submenu > a:after { display: block; content: " "; float: right; width: 0; height: 0; border-color: transparent; border-style: solid; border-width: 5px 0 5px 5px; border-left-color: darken(@dropdownBackground, 20%); margin-top: 5px; margin-right: -10px; } .dropdown-submenu:hover > a:after { border-left-color: @dropdownLinkColorHover; } // Left aligned submenus .dropdown-submenu.pull-left { // Undo the float // Yes, this is awkward since .pull-left adds a float, but it sticks to our conventions elsewhere. float: none; // Positioning the submenu > .dropdown-menu { left: -100%; margin-left: 10px; .border-radius(6px 0 6px 6px); } } // Tweak nav headers // ----------------- // Increase padding from 15px to 20px on sides .dropdown .dropdown-menu .nav-header { padding-left: 20px; padding-right: 20px; } // Typeahead // --------- .typeahead { z-index: 1051; margin-top: 2px; // give it some space to breathe .border-radius(@baseBorderRadius); } numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/less/bootstrap/type.less0000664000175100017510000001137112370216246031050 0ustar vagrantvagrant00000000000000// // Typography // -------------------------------------------------- // Body text // ------------------------- p { margin: 0 0 @baseLineHeight / 2; } .lead { margin-bottom: @baseLineHeight; font-size: @baseFontSize * 1.5; font-weight: 200; line-height: @baseLineHeight * 1.5; } // Emphasis & misc // ------------------------- // Ex: 14px base font * 85% = about 12px small { font-size: 85%; } strong { font-weight: bold; } em { font-style: italic; } cite { font-style: normal; } // Utility classes .muted { color: @grayLight; } a.muted:hover, a.muted:focus { color: darken(@grayLight, 10%); } .text-warning { color: @warningText; } a.text-warning:hover, a.text-warning:focus { color: darken(@warningText, 10%); } .text-error { color: @errorText; } a.text-error:hover, a.text-error:focus { color: darken(@errorText, 10%); } .text-info { color: @infoText; } a.text-info:hover, a.text-info:focus { color: darken(@infoText, 10%); } .text-success { color: @successText; } a.text-success:hover, a.text-success:focus { color: darken(@successText, 10%); } .text-left { text-align: left; } .text-right { text-align: right; } .text-center { text-align: center; } // Headings // ------------------------- h1, h2, h3, h4, h5, h6 { margin: (@baseLineHeight / 2) 0; font-family: @headingsFontFamily; font-weight: @headingsFontWeight; line-height: @baseLineHeight; color: @headingsColor; text-rendering: optimizelegibility; // Fix the character spacing for headings small { font-weight: normal; line-height: 1; color: @grayLight; } } h1, h2, h3 { line-height: @baseLineHeight * 2; } h1 { font-size: @baseFontSize * 2.75; } // ~38px h2 { font-size: @baseFontSize * 2.25; } // ~32px h3 { font-size: @baseFontSize * 1.75; } // ~24px h4 { font-size: @baseFontSize * 1.25; } // ~18px h5 { font-size: @baseFontSize; } h6 { font-size: @baseFontSize * 0.85; } // ~12px h1 small { font-size: @baseFontSize * 1.75; } // ~24px h2 small { font-size: @baseFontSize * 1.25; } // ~18px h3 small { font-size: @baseFontSize; } h4 small { font-size: @baseFontSize; } // Page header // ------------------------- .page-header { padding-bottom: (@baseLineHeight / 2) - 1; margin: @baseLineHeight 0 (@baseLineHeight * 1.5); border-bottom: 1px solid @grayLighter; } // Lists // -------------------------------------------------- // Unordered and Ordered lists ul, ol { padding: 0; margin: 0 0 @baseLineHeight / 2 25px; } ul ul, ul ol, ol ol, ol ul { margin-bottom: 0; } li { line-height: @baseLineHeight; } // Remove default list styles ul.unstyled, ol.unstyled { margin-left: 0; list-style: none; } // Single-line list items ul.inline, ol.inline { margin-left: 0; list-style: none; > li { display: inline-block; .ie7-inline-block(); padding-left: 5px; padding-right: 5px; } } // Description Lists dl { margin-bottom: @baseLineHeight; } dt, dd { line-height: @baseLineHeight; } dt { font-weight: bold; } dd { margin-left: @baseLineHeight / 2; } // Horizontal layout (like forms) .dl-horizontal { .clearfix(); // Ensure dl clears floats if empty dd elements present dt { float: left; width: @horizontalComponentOffset - 20; clear: left; text-align: right; .text-overflow(); } dd { margin-left: @horizontalComponentOffset; } } // MISC // ---- // Horizontal rules hr { margin: @baseLineHeight 0; border: 0; border-top: 1px solid @hrBorder; border-bottom: 1px solid @white; } // Abbreviations and acronyms abbr[title], // Added data-* attribute to help out our tooltip plugin, per https://github.com/twitter/bootstrap/issues/5257 abbr[data-original-title] { cursor: help; border-bottom: 1px dotted @grayLight; } abbr.initialism { font-size: 90%; text-transform: uppercase; } // Blockquotes blockquote { padding: 0 0 0 15px; margin: 0 0 @baseLineHeight; border-left: 5px solid @grayLighter; p { margin-bottom: 0; font-size: @baseFontSize * 1.25; font-weight: 300; line-height: 1.25; } small { display: block; line-height: @baseLineHeight; color: @grayLight; &:before { content: '\2014 \00A0'; } } // Float right with text-align: right &.pull-right { float: right; padding-right: 15px; padding-left: 0; border-right: 5px solid @grayLighter; border-left: 0; p, small { text-align: right; } small { &:before { content: ''; } &:after { content: '\00A0 \2014'; } } } } // Quotes q:before, q:after, blockquote:before, blockquote:after { content: ""; } // Addresses address { display: block; margin-bottom: @baseLineHeight; font-style: normal; line-height: @baseLineHeight; } numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/less/bootstrap/thumbnails.less0000664000175100017510000000225012370216246032231 0ustar vagrantvagrant00000000000000// // Thumbnails // -------------------------------------------------- // Note: `.thumbnails` and `.thumbnails > li` are overriden in responsive files // Make wrapper ul behave like the grid .thumbnails { margin-left: -@gridGutterWidth; list-style: none; .clearfix(); } // Fluid rows have no left margin .row-fluid .thumbnails { margin-left: 0; } // Float li to make thumbnails appear in a row .thumbnails > li { float: left; // Explicity set the float since we don't require .span* classes margin-bottom: @baseLineHeight; margin-left: @gridGutterWidth; } // The actual thumbnail (can be `a` or `div`) .thumbnail { display: block; padding: 4px; line-height: @baseLineHeight; border: 1px solid #ddd; .border-radius(@baseBorderRadius); .box-shadow(0 1px 3px rgba(0,0,0,.055)); .transition(all .2s ease-in-out); } // Add a hover/focus state for linked versions only a.thumbnail:hover, a.thumbnail:focus { border-color: @linkColor; .box-shadow(0 1px 4px rgba(0,105,214,.25)); } // Images and captions .thumbnail > img { display: block; max-width: 100%; margin-left: auto; margin-right: auto; } .thumbnail .caption { padding: 9px; color: @gray; } numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/less/bootstrap/responsive-767px-max.less0000664000175100017510000000752012370216246033741 0ustar vagrantvagrant00000000000000// // Responsive: Landscape phone to desktop/tablet // -------------------------------------------------- @media (max-width: 767px) { // Padding to set content in a bit body { padding-left: 20px; padding-right: 20px; } // Negative indent the now static "fixed" navbar .navbar-fixed-top, .navbar-fixed-bottom, .navbar-static-top { margin-left: -20px; margin-right: -20px; } // Remove padding on container given explicit padding set on body .container-fluid { padding: 0; } // TYPOGRAPHY // ---------- // Reset horizontal dl .dl-horizontal { dt { float: none; clear: none; width: auto; text-align: left; } dd { margin-left: 0; } } // GRID & CONTAINERS // ----------------- // Remove width from containers .container { width: auto; } // Fluid rows .row-fluid { width: 100%; } // Undo negative margin on rows and thumbnails .row, .thumbnails { margin-left: 0; } .thumbnails > li { float: none; margin-left: 0; // Reset the default margin for all li elements when no .span* classes are present } // Make all grid-sized elements block level again [class*="span"], .uneditable-input[class*="span"], // Makes uneditable inputs full-width when using grid sizing .row-fluid [class*="span"] { float: none; display: block; width: 100%; margin-left: 0; .box-sizing(border-box); } .span12, .row-fluid .span12 { width: 100%; .box-sizing(border-box); } .row-fluid [class*="offset"]:first-child { margin-left: 0; } // FORM FIELDS // ----------- // Make span* classes full width .input-large, .input-xlarge, .input-xxlarge, input[class*="span"], select[class*="span"], textarea[class*="span"], .uneditable-input { .input-block-level(); } // But don't let it screw up prepend/append inputs .input-prepend input, .input-append input, .input-prepend input[class*="span"], .input-append input[class*="span"] { display: inline-block; // redeclare so they don't wrap to new lines width: auto; } .controls-row [class*="span"] + [class*="span"] { margin-left: 0; } // Modals .modal { position: fixed; top: 20px; left: 20px; right: 20px; width: auto; margin: 0; &.fade { top: -100px; } &.fade.in { top: 20px; } } } // UP TO LANDSCAPE PHONE // --------------------- @media (max-width: 480px) { // Smooth out the collapsing/expanding nav .nav-collapse { -webkit-transform: translate3d(0, 0, 0); // activate the GPU } // Block level the page header small tag for readability .page-header h1 small { display: block; line-height: @baseLineHeight; } // Update checkboxes for iOS input[type="checkbox"], input[type="radio"] { border: 1px solid #ccc; } // Remove the horizontal form styles .form-horizontal { .control-label { float: none; width: auto; padding-top: 0; text-align: left; } // Move over all input controls and content .controls { margin-left: 0; } // Move the options list down to align with labels .control-list { padding-top: 0; // has to be padding because margin collaspes } // Move over buttons in .form-actions to align with .controls .form-actions { padding-left: 10px; padding-right: 10px; } } // Medias // Reset float and spacing to stack .media .pull-left, .media .pull-right { float: none; display: block; margin-bottom: 10px; } // Remove side margins since we stack instead of indent .media-object { margin-right: 0; margin-left: 0; } // Modals .modal { top: 10px; left: 10px; right: 10px; } .modal-header .close { padding: 10px; margin: -10px; } // Carousel .carousel-caption { position: static; } } numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/less/bootstrap/forms.less0000664000175100017510000003677212370216246031231 0ustar vagrantvagrant00000000000000// // Forms // -------------------------------------------------- // GENERAL STYLES // -------------- // Make all forms have space below them form { margin: 0 0 @baseLineHeight; } fieldset { padding: 0; margin: 0; border: 0; } // Groups of fields with labels on top (legends) legend { display: block; width: 100%; padding: 0; margin-bottom: @baseLineHeight; font-size: @baseFontSize * 1.5; line-height: @baseLineHeight * 2; color: @grayDark; border: 0; border-bottom: 1px solid #e5e5e5; // Small small { font-size: @baseLineHeight * .75; color: @grayLight; } } // Set font for forms label, input, button, select, textarea { #font > .shorthand(@baseFontSize,normal,@baseLineHeight); // Set size, weight, line-height here } input, button, select, textarea { font-family: @baseFontFamily; // And only set font-family here for those that need it (note the missing label element) } // Identify controls by their labels label { display: block; margin-bottom: 5px; } // Form controls // ------------------------- // Shared size and type resets select, textarea, input[type="text"], input[type="password"], input[type="datetime"], input[type="datetime-local"], input[type="date"], input[type="month"], input[type="time"], input[type="week"], input[type="number"], input[type="email"], input[type="url"], input[type="search"], input[type="tel"], input[type="color"], .uneditable-input { display: inline-block; height: @baseLineHeight; padding: 4px 6px; margin-bottom: @baseLineHeight / 2; font-size: @baseFontSize; line-height: @baseLineHeight; color: @gray; .border-radius(@inputBorderRadius); vertical-align: middle; } // Reset appearance properties for textual inputs and textarea // Declare width for legacy (can't be on input[type=*] selectors or it's too specific) input, textarea, .uneditable-input { width: 206px; // plus 12px padding and 2px border } // Reset height since textareas have rows textarea { height: auto; } // Everything else textarea, input[type="text"], input[type="password"], input[type="datetime"], input[type="datetime-local"], input[type="date"], input[type="month"], input[type="time"], input[type="week"], input[type="number"], input[type="email"], input[type="url"], input[type="search"], input[type="tel"], input[type="color"], .uneditable-input { background-color: @inputBackground; border: 1px solid @inputBorder; .box-shadow(inset 0 1px 1px rgba(0,0,0,.075)); .transition(~"border linear .2s, box-shadow linear .2s"); // Focus state &:focus { border-color: rgba(82,168,236,.8); outline: 0; outline: thin dotted \9; /* IE6-9 */ .box-shadow(~"inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(82,168,236,.6)"); } } // Position radios and checkboxes better input[type="radio"], input[type="checkbox"] { margin: 4px 0 0; *margin-top: 0; /* IE7 */ margin-top: 1px \9; /* IE8-9 */ line-height: normal; } // Reset width of input images, buttons, radios, checkboxes input[type="file"], input[type="image"], input[type="submit"], input[type="reset"], input[type="button"], input[type="radio"], input[type="checkbox"] { width: auto; // Override of generic input selector } // Set the height of select and file controls to match text inputs select, input[type="file"] { height: @inputHeight; /* In IE7, the height of the select element cannot be changed by height, only font-size */ *margin-top: 4px; /* For IE7, add top margin to align select with labels */ line-height: @inputHeight; } // Make select elements obey height by applying a border select { width: 220px; // default input width + 10px of padding that doesn't get applied border: 1px solid @inputBorder; background-color: @inputBackground; // Chrome on Linux and Mobile Safari need background-color } // Make multiple select elements height not fixed select[multiple], select[size] { height: auto; } // Focus for select, file, radio, and checkbox select:focus, input[type="file"]:focus, input[type="radio"]:focus, input[type="checkbox"]:focus { .tab-focus(); } // Uneditable inputs // ------------------------- // Make uneditable inputs look inactive .uneditable-input, .uneditable-textarea { color: @grayLight; background-color: darken(@inputBackground, 1%); border-color: @inputBorder; .box-shadow(inset 0 1px 2px rgba(0,0,0,.025)); cursor: not-allowed; } // For text that needs to appear as an input but should not be an input .uneditable-input { overflow: hidden; // prevent text from wrapping, but still cut it off like an input does white-space: nowrap; } // Make uneditable textareas behave like a textarea .uneditable-textarea { width: auto; height: auto; } // Placeholder // ------------------------- // Placeholder text gets special styles because when browsers invalidate entire lines if it doesn't understand a selector input, textarea { .placeholder(); } // CHECKBOXES & RADIOS // ------------------- // Indent the labels to position radios/checkboxes as hanging .radio, .checkbox { min-height: @baseLineHeight; // clear the floating input if there is no label text padding-left: 20px; } .radio input[type="radio"], .checkbox input[type="checkbox"] { float: left; margin-left: -20px; } // Move the options list down to align with labels .controls > .radio:first-child, .controls > .checkbox:first-child { padding-top: 5px; // has to be padding because margin collaspes } // Radios and checkboxes on same line // TODO v3: Convert .inline to .control-inline .radio.inline, .checkbox.inline { display: inline-block; padding-top: 5px; margin-bottom: 0; vertical-align: middle; } .radio.inline + .radio.inline, .checkbox.inline + .checkbox.inline { margin-left: 10px; // space out consecutive inline controls } // INPUT SIZES // ----------- // General classes for quick sizes .input-mini { width: 60px; } .input-small { width: 90px; } .input-medium { width: 150px; } .input-large { width: 210px; } .input-xlarge { width: 270px; } .input-xxlarge { width: 530px; } // Grid style input sizes input[class*="span"], select[class*="span"], textarea[class*="span"], .uneditable-input[class*="span"], // Redeclare since the fluid row class is more specific .row-fluid input[class*="span"], .row-fluid select[class*="span"], .row-fluid textarea[class*="span"], .row-fluid .uneditable-input[class*="span"] { float: none; margin-left: 0; } // Ensure input-prepend/append never wraps .input-append input[class*="span"], .input-append .uneditable-input[class*="span"], .input-prepend input[class*="span"], .input-prepend .uneditable-input[class*="span"], .row-fluid input[class*="span"], .row-fluid select[class*="span"], .row-fluid textarea[class*="span"], .row-fluid .uneditable-input[class*="span"], .row-fluid .input-prepend [class*="span"], .row-fluid .input-append [class*="span"] { display: inline-block; } // GRID SIZING FOR INPUTS // ---------------------- // Grid sizes #grid > .input(@gridColumnWidth, @gridGutterWidth); // Control row for multiple inputs per line .controls-row { .clearfix(); // Clear the float from controls } // Float to collapse white-space for proper grid alignment .controls-row [class*="span"], // Redeclare the fluid grid collapse since we undo the float for inputs .row-fluid .controls-row [class*="span"] { float: left; } // Explicity set top padding on all checkboxes/radios, not just first-child .controls-row .checkbox[class*="span"], .controls-row .radio[class*="span"] { padding-top: 5px; } // DISABLED STATE // -------------- // Disabled and read-only inputs input[disabled], select[disabled], textarea[disabled], input[readonly], select[readonly], textarea[readonly] { cursor: not-allowed; background-color: @inputDisabledBackground; } // Explicitly reset the colors here input[type="radio"][disabled], input[type="checkbox"][disabled], input[type="radio"][readonly], input[type="checkbox"][readonly] { background-color: transparent; } // FORM FIELD FEEDBACK STATES // -------------------------- // Warning .control-group.warning { .formFieldState(@warningText, @warningText, @warningBackground); } // Error .control-group.error { .formFieldState(@errorText, @errorText, @errorBackground); } // Success .control-group.success { .formFieldState(@successText, @successText, @successBackground); } // Success .control-group.info { .formFieldState(@infoText, @infoText, @infoBackground); } // HTML5 invalid states // Shares styles with the .control-group.error above input:focus:invalid, textarea:focus:invalid, select:focus:invalid { color: #b94a48; border-color: #ee5f5b; &:focus { border-color: darken(#ee5f5b, 10%); @shadow: 0 0 6px lighten(#ee5f5b, 20%); .box-shadow(@shadow); } } // FORM ACTIONS // ------------ .form-actions { padding: (@baseLineHeight - 1) 20px @baseLineHeight; margin-top: @baseLineHeight; margin-bottom: @baseLineHeight; background-color: @formActionsBackground; border-top: 1px solid #e5e5e5; .clearfix(); // Adding clearfix to allow for .pull-right button containers } // HELP TEXT // --------- .help-block, .help-inline { color: lighten(@textColor, 15%); // lighten the text some for contrast } .help-block { display: block; // account for any element using help-block margin-bottom: @baseLineHeight / 2; } .help-inline { display: inline-block; .ie7-inline-block(); vertical-align: middle; padding-left: 5px; } // INPUT GROUPS // ------------ // Allow us to put symbols and text within the input field for a cleaner look .input-append, .input-prepend { display: inline-block; margin-bottom: @baseLineHeight / 2; vertical-align: middle; font-size: 0; // white space collapse hack white-space: nowrap; // Prevent span and input from separating // Reset the white space collapse hack input, select, .uneditable-input, .dropdown-menu, .popover { font-size: @baseFontSize; } input, select, .uneditable-input { position: relative; // placed here by default so that on :focus we can place the input above the .add-on for full border and box-shadow goodness margin-bottom: 0; // prevent bottom margin from screwing up alignment in stacked forms *margin-left: 0; vertical-align: top; .border-radius(0 @inputBorderRadius @inputBorderRadius 0); // Make input on top when focused so blue border and shadow always show &:focus { z-index: 2; } } .add-on { display: inline-block; width: auto; height: @baseLineHeight; min-width: 16px; padding: 4px 5px; font-size: @baseFontSize; font-weight: normal; line-height: @baseLineHeight; text-align: center; text-shadow: 0 1px 0 @white; background-color: @grayLighter; border: 1px solid #ccc; } .add-on, .btn, .btn-group > .dropdown-toggle { vertical-align: top; .border-radius(0); } .active { background-color: lighten(@green, 30); border-color: @green; } } .input-prepend { .add-on, .btn { margin-right: -1px; } .add-on:first-child, .btn:first-child { // FYI, `.btn:first-child` accounts for a button group that's prepended .border-radius(@inputBorderRadius 0 0 @inputBorderRadius); } } .input-append { input, select, .uneditable-input { .border-radius(@inputBorderRadius 0 0 @inputBorderRadius); + .btn-group .btn:last-child { .border-radius(0 @inputBorderRadius @inputBorderRadius 0); } } .add-on, .btn, .btn-group { margin-left: -1px; } .add-on:last-child, .btn:last-child, .btn-group:last-child > .dropdown-toggle { .border-radius(0 @inputBorderRadius @inputBorderRadius 0); } } // Remove all border-radius for inputs with both prepend and append .input-prepend.input-append { input, select, .uneditable-input { .border-radius(0); + .btn-group .btn { .border-radius(0 @inputBorderRadius @inputBorderRadius 0); } } .add-on:first-child, .btn:first-child { margin-right: -1px; .border-radius(@inputBorderRadius 0 0 @inputBorderRadius); } .add-on:last-child, .btn:last-child { margin-left: -1px; .border-radius(0 @inputBorderRadius @inputBorderRadius 0); } .btn-group:first-child { margin-left: 0; } } // SEARCH FORM // ----------- input.search-query { padding-right: 14px; padding-right: 4px \9; padding-left: 14px; padding-left: 4px \9; /* IE7-8 doesn't have border-radius, so don't indent the padding */ margin-bottom: 0; // Remove the default margin on all inputs .border-radius(15px); } /* Allow for input prepend/append in search forms */ .form-search .input-append .search-query, .form-search .input-prepend .search-query { .border-radius(0); // Override due to specificity } .form-search .input-append .search-query { .border-radius(14px 0 0 14px); } .form-search .input-append .btn { .border-radius(0 14px 14px 0); } .form-search .input-prepend .search-query { .border-radius(0 14px 14px 0); } .form-search .input-prepend .btn { .border-radius(14px 0 0 14px); } // HORIZONTAL & VERTICAL FORMS // --------------------------- // Common properties // ----------------- .form-search, .form-inline, .form-horizontal { input, textarea, select, .help-inline, .uneditable-input, .input-prepend, .input-append { display: inline-block; .ie7-inline-block(); margin-bottom: 0; vertical-align: middle; } // Re-hide hidden elements due to specifity .hide { display: none; } } .form-search label, .form-inline label, .form-search .btn-group, .form-inline .btn-group { display: inline-block; } // Remove margin for input-prepend/-append .form-search .input-append, .form-inline .input-append, .form-search .input-prepend, .form-inline .input-prepend { margin-bottom: 0; } // Inline checkbox/radio labels (remove padding on left) .form-search .radio, .form-search .checkbox, .form-inline .radio, .form-inline .checkbox { padding-left: 0; margin-bottom: 0; vertical-align: middle; } // Remove float and margin, set to inline-block .form-search .radio input[type="radio"], .form-search .checkbox input[type="checkbox"], .form-inline .radio input[type="radio"], .form-inline .checkbox input[type="checkbox"] { float: left; margin-right: 3px; margin-left: 0; } // Margin to space out fieldsets .control-group { margin-bottom: @baseLineHeight / 2; } // Legend collapses margin, so next element is responsible for spacing legend + .control-group { margin-top: @baseLineHeight; -webkit-margin-top-collapse: separate; } // Horizontal-specific styles // -------------------------- .form-horizontal { // Increase spacing between groups .control-group { margin-bottom: @baseLineHeight; .clearfix(); } // Float the labels left .control-label { float: left; width: @horizontalComponentOffset - 20; padding-top: 5px; text-align: right; } // Move over all input controls and content .controls { // Super jank IE7 fix to ensure the inputs in .input-append and input-prepend // don't inherit the margin of the parent, in this case .controls *display: inline-block; *padding-left: 20px; margin-left: @horizontalComponentOffset; *margin-left: 0; &:first-child { *padding-left: @horizontalComponentOffset; } } // Remove bottom margin on block level help text since that's accounted for on .control-group .help-block { margin-bottom: 0; } // And apply it only to .help-block instances that follow a form control input, select, textarea, .uneditable-input, .input-prepend, .input-append { + .help-block { margin-top: @baseLineHeight / 2; } } // Move over buttons in .form-actions to align with .controls .form-actions { padding-left: @horizontalComponentOffset; } } numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/less/bootstrap/bootstrap.less0000664000175100017510000000272112370216246032103 0ustar vagrantvagrant00000000000000/*! * Bootstrap v2.3.1 * * Copyright 2012 Twitter, Inc * Licensed under the Apache License v2.0 * http://www.apache.org/licenses/LICENSE-2.0 * * Designed and built with all the love in the world @twitter by @mdo and @fat. */ // Core variables and mixins @import "variables.less"; // Modify this for custom colors, font-sizes, etc @import "mixins.less"; // CSS Reset @import "reset.less"; // Grid system and page structure @import "scaffolding.less"; @import "grid.less"; @import "layouts.less"; // Base CSS @import "type.less"; @import "code.less"; @import "forms.less"; @import "tables.less"; // Components: common @import "sprites.less"; @import "dropdowns.less"; @import "wells.less"; @import "component-animations.less"; @import "close.less"; // Components: Buttons & Alerts @import "buttons.less"; @import "button-groups.less"; @import "alerts.less"; // Note: alerts share common CSS with buttons and thus have styles in buttons.less // Components: Nav @import "navs.less"; @import "navbar.less"; @import "breadcrumbs.less"; @import "pagination.less"; @import "pager.less"; // Components: Popovers @import "modals.less"; @import "tooltip.less"; @import "popovers.less"; // Components: Misc @import "thumbnails.less"; @import "media.less"; @import "labels-badges.less"; @import "progress-bars.less"; @import "accordion.less"; @import "carousel.less"; @import "hero-unit.less"; // Utility classes @import "utilities.less"; // Has to be last to override when necessary numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/less/bootstrap/responsive-utilities.less0000664000175100017510000000310212370216246034266 0ustar vagrantvagrant00000000000000// // Responsive: Utility classes // -------------------------------------------------- // IE10 Metro responsive // Required for Windows 8 Metro split-screen snapping with IE10 // Source: http://timkadlec.com/2012/10/ie10-snap-mode-and-responsive-design/ @-ms-viewport{ width: device-width; } // Hide from screenreaders and browsers // Credit: HTML5 Boilerplate .hidden { display: none; visibility: hidden; } // Visibility utilities // For desktops .visible-phone { display: none !important; } .visible-tablet { display: none !important; } .hidden-phone { } .hidden-tablet { } .hidden-desktop { display: none !important; } .visible-desktop { display: inherit !important; } // Tablets & small desktops only @media (min-width: 768px) and (max-width: 979px) { // Hide everything else .hidden-desktop { display: inherit !important; } .visible-desktop { display: none !important ; } // Show .visible-tablet { display: inherit !important; } // Hide .hidden-tablet { display: none !important; } } // Phones only @media (max-width: 767px) { // Hide everything else .hidden-desktop { display: inherit !important; } .visible-desktop { display: none !important; } // Show .visible-phone { display: inherit !important; } // Use inherit to restore previous behavior // Hide .hidden-phone { display: none !important; } } // Print utilities .visible-print { display: none !important; } .hidden-print { } @media print { .visible-print { display: inherit !important; } .hidden-print { display: none !important; } } numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/less/bootstrap/modals.less0000664000175100017510000000367212370216246031353 0ustar vagrantvagrant00000000000000// // Modals // -------------------------------------------------- // Background .modal-backdrop { position: fixed; top: 0; right: 0; bottom: 0; left: 0; z-index: @zindexModalBackdrop; background-color: @black; // Fade for backdrop &.fade { opacity: 0; } } .modal-backdrop, .modal-backdrop.fade.in { .opacity(80); } // Base modal .modal { position: fixed; top: 10%; left: 50%; z-index: @zindexModal; width: 560px; margin-left: -280px; background-color: @white; border: 1px solid #999; border: 1px solid rgba(0,0,0,.3); *border: 1px solid #999; /* IE6-7 */ .border-radius(6px); .box-shadow(0 3px 7px rgba(0,0,0,0.3)); .background-clip(padding-box); // Remove focus outline from opened modal outline: none; &.fade { .transition(e('opacity .3s linear, top .3s ease-out')); top: -25%; } &.fade.in { top: 10%; } } .modal-header { padding: 9px 15px; border-bottom: 1px solid #eee; // Close icon .close { margin-top: 2px; } // Heading h3 { margin: 0; line-height: 30px; } } // Body (where all modal content resides) .modal-body { position: relative; overflow-y: auto; max-height: 400px; padding: 15px; } // Remove bottom margin if need be .modal-form { margin-bottom: 0; } // Footer (for actions) .modal-footer { padding: 14px 15px 15px; margin-bottom: 0; text-align: right; // right align buttons background-color: #f5f5f5; border-top: 1px solid #ddd; .border-radius(0 0 6px 6px); .box-shadow(inset 0 1px 0 @white); .clearfix(); // clear it in case folks use .pull-* classes on buttons // Properly space out buttons .btn + .btn { margin-left: 5px; margin-bottom: 0; // account for input[type="submit"] which gets the bottom margin like all other inputs } // but override that for button groups .btn-group .btn + .btn { margin-left: -1px; } // and override it for block buttons as well .btn-block + .btn-block { margin-left: 0; } } numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/less/bootstrap/grid.less0000664000175100017510000000065512370216246031017 0ustar vagrantvagrant00000000000000// // Grid system // -------------------------------------------------- // Fixed (940px) #grid > .core(@gridColumnWidth, @gridGutterWidth); // Fluid (940px) #grid > .fluid(@fluidGridColumnWidth, @fluidGridGutterWidth); // Reset utility classes due to specificity [class*="span"].hide, .row-fluid [class*="span"].hide { display: none; } [class*="span"].pull-right, .row-fluid [class*="span"].pull-right { float: right; } numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/less/bootstrap/variables.less0000664000175100017510000002166612370216246032047 0ustar vagrantvagrant00000000000000// // Variables // -------------------------------------------------- // Global values // -------------------------------------------------- // Grays // ------------------------- @black: #000; @grayDarker: #222; @grayDark: #333; @gray: #555; @grayLight: #999; @grayLighter: #eee; @white: #fff; // Accent colors // ------------------------- @blue: #049cdb; @blueDark: #0064cd; @green: #46a546; @red: #9d261d; @yellow: #ffc40d; @orange: #f89406; @pink: #c3325f; @purple: #7a43b6; // Scaffolding // ------------------------- @bodyBackground: @white; @textColor: @grayDark; // Links // ------------------------- @linkColor: #08c; @linkColorHover: darken(@linkColor, 15%); // Typography // ------------------------- @sansFontFamily: "Helvetica Neue", Helvetica, Arial, sans-serif; @serifFontFamily: Georgia, "Times New Roman", Times, serif; @monoFontFamily: Monaco, Menlo, Consolas, "Courier New", monospace; @baseFontSize: 14px; @baseFontFamily: @sansFontFamily; @baseLineHeight: 20px; @altFontFamily: @serifFontFamily; @headingsFontFamily: inherit; // empty to use BS default, @baseFontFamily @headingsFontWeight: bold; // instead of browser default, bold @headingsColor: inherit; // empty to use BS default, @textColor // Component sizing // ------------------------- // Based on 14px font-size and 20px line-height @fontSizeLarge: @baseFontSize * 1.25; // ~18px @fontSizeSmall: @baseFontSize * 0.85; // ~12px @fontSizeMini: @baseFontSize * 0.75; // ~11px @paddingLarge: 11px 19px; // 44px @paddingSmall: 2px 10px; // 26px @paddingMini: 0 6px; // 22px @baseBorderRadius: 4px; @borderRadiusLarge: 6px; @borderRadiusSmall: 3px; // Tables // ------------------------- @tableBackground: transparent; // overall background-color @tableBackgroundAccent: #f9f9f9; // for striping @tableBackgroundHover: #f5f5f5; // for hover @tableBorder: #ddd; // table and cell border // Buttons // ------------------------- @btnBackground: @white; @btnBackgroundHighlight: darken(@white, 10%); @btnBorder: #ccc; @btnPrimaryBackground: @linkColor; @btnPrimaryBackgroundHighlight: spin(@btnPrimaryBackground, 20%); @btnInfoBackground: #5bc0de; @btnInfoBackgroundHighlight: #2f96b4; @btnSuccessBackground: #62c462; @btnSuccessBackgroundHighlight: #51a351; @btnWarningBackground: lighten(@orange, 15%); @btnWarningBackgroundHighlight: @orange; @btnDangerBackground: #ee5f5b; @btnDangerBackgroundHighlight: #bd362f; @btnInverseBackground: #444; @btnInverseBackgroundHighlight: @grayDarker; // Forms // ------------------------- @inputBackground: @white; @inputBorder: #ccc; @inputBorderRadius: @baseBorderRadius; @inputDisabledBackground: @grayLighter; @formActionsBackground: #f5f5f5; @inputHeight: @baseLineHeight + 10px; // base line-height + 8px vertical padding + 2px top/bottom border // Dropdowns // ------------------------- @dropdownBackground: @white; @dropdownBorder: rgba(0,0,0,.2); @dropdownDividerTop: #e5e5e5; @dropdownDividerBottom: @white; @dropdownLinkColor: @grayDark; @dropdownLinkColorHover: @white; @dropdownLinkColorActive: @white; @dropdownLinkBackgroundActive: @linkColor; @dropdownLinkBackgroundHover: @dropdownLinkBackgroundActive; // COMPONENT VARIABLES // -------------------------------------------------- // Z-index master list // ------------------------- // Used for a bird's eye view of components dependent on the z-axis // Try to avoid customizing these :) @zindexDropdown: 1000; @zindexPopover: 1010; @zindexTooltip: 1030; @zindexFixedNavbar: 1030; @zindexModalBackdrop: 1040; @zindexModal: 1050; // Sprite icons path // ------------------------- @iconSpritePath: "../img/glyphicons-halflings.png"; @iconWhiteSpritePath: "../img/glyphicons-halflings-white.png"; // Input placeholder text color // ------------------------- @placeholderText: @grayLight; // Hr border color // ------------------------- @hrBorder: @grayLighter; // Horizontal forms & lists // ------------------------- @horizontalComponentOffset: 180px; // Wells // ------------------------- @wellBackground: #f5f5f5; // Navbar // ------------------------- @navbarCollapseWidth: 979px; @navbarCollapseDesktopWidth: @navbarCollapseWidth + 1; @navbarHeight: 40px; @navbarBackgroundHighlight: #ffffff; @navbarBackground: darken(@navbarBackgroundHighlight, 5%); @navbarBorder: darken(@navbarBackground, 12%); @navbarText: #777; @navbarLinkColor: #777; @navbarLinkColorHover: @grayDark; @navbarLinkColorActive: @gray; @navbarLinkBackgroundHover: transparent; @navbarLinkBackgroundActive: darken(@navbarBackground, 5%); @navbarBrandColor: @navbarLinkColor; // Inverted navbar @navbarInverseBackground: #111111; @navbarInverseBackgroundHighlight: #222222; @navbarInverseBorder: #252525; @navbarInverseText: @grayLight; @navbarInverseLinkColor: @grayLight; @navbarInverseLinkColorHover: @white; @navbarInverseLinkColorActive: @navbarInverseLinkColorHover; @navbarInverseLinkBackgroundHover: transparent; @navbarInverseLinkBackgroundActive: @navbarInverseBackground; @navbarInverseSearchBackground: lighten(@navbarInverseBackground, 25%); @navbarInverseSearchBackgroundFocus: @white; @navbarInverseSearchBorder: @navbarInverseBackground; @navbarInverseSearchPlaceholderColor: #ccc; @navbarInverseBrandColor: @navbarInverseLinkColor; // Pagination // ------------------------- @paginationBackground: #fff; @paginationBorder: #ddd; @paginationActiveBackground: #f5f5f5; // Hero unit // ------------------------- @heroUnitBackground: @grayLighter; @heroUnitHeadingColor: inherit; @heroUnitLeadColor: inherit; // Form states and alerts // ------------------------- @warningText: #c09853; @warningBackground: #fcf8e3; @warningBorder: darken(spin(@warningBackground, -10), 3%); @errorText: #b94a48; @errorBackground: #f2dede; @errorBorder: darken(spin(@errorBackground, -10), 3%); @successText: #468847; @successBackground: #dff0d8; @successBorder: darken(spin(@successBackground, -10), 5%); @infoText: #3a87ad; @infoBackground: #d9edf7; @infoBorder: darken(spin(@infoBackground, -10), 7%); // Tooltips and popovers // ------------------------- @tooltipColor: #fff; @tooltipBackground: #000; @tooltipArrowWidth: 5px; @tooltipArrowColor: @tooltipBackground; @popoverBackground: #fff; @popoverArrowWidth: 10px; @popoverArrowColor: #fff; @popoverTitleBackground: darken(@popoverBackground, 3%); // Special enhancement for popovers @popoverArrowOuterWidth: @popoverArrowWidth + 1; @popoverArrowOuterColor: rgba(0,0,0,.25); // GRID // -------------------------------------------------- // Default 940px grid // ------------------------- @gridColumns: 12; @gridColumnWidth: 60px; @gridGutterWidth: 20px; @gridRowWidth: (@gridColumns * @gridColumnWidth) + (@gridGutterWidth * (@gridColumns - 1)); // 1200px min @gridColumnWidth1200: 70px; @gridGutterWidth1200: 30px; @gridRowWidth1200: (@gridColumns * @gridColumnWidth1200) + (@gridGutterWidth1200 * (@gridColumns - 1)); // 768px-979px @gridColumnWidth768: 42px; @gridGutterWidth768: 20px; @gridRowWidth768: (@gridColumns * @gridColumnWidth768) + (@gridGutterWidth768 * (@gridColumns - 1)); // Fluid grid // ------------------------- @fluidGridColumnWidth: percentage(@gridColumnWidth/@gridRowWidth); @fluidGridGutterWidth: percentage(@gridGutterWidth/@gridRowWidth); // 1200px min @fluidGridColumnWidth1200: percentage(@gridColumnWidth1200/@gridRowWidth1200); @fluidGridGutterWidth1200: percentage(@gridGutterWidth1200/@gridRowWidth1200); // 768px-979px @fluidGridColumnWidth768: percentage(@gridColumnWidth768/@gridRowWidth768); @fluidGridGutterWidth768: percentage(@gridGutterWidth768/@gridRowWidth768); numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/less/bootstrap/responsive.less0000664000175100017510000000205512370216246032263 0ustar vagrantvagrant00000000000000/*! * Bootstrap Responsive v2.3.1 * * Copyright 2012 Twitter, Inc * Licensed under the Apache License v2.0 * http://www.apache.org/licenses/LICENSE-2.0 * * Designed and built with all the love in the world @twitter by @mdo and @fat. */ // Responsive.less // For phone and tablet devices // ------------------------------------------------------------- // REPEAT VARIABLES & MIXINS // ------------------------- // Required since we compile the responsive stuff separately @import "variables.less"; // Modify this for custom colors, font-sizes, etc @import "mixins.less"; // RESPONSIVE CLASSES // ------------------ @import "responsive-utilities.less"; // MEDIA QUERIES // ------------------ // Large desktops @import "responsive-1200px-min.less"; // Tablets to regular desktops @import "responsive-768px-979px.less"; // Phones to portrait tablets and narrow desktops @import "responsive-767px-max.less"; // RESPONSIVE NAVBAR // ------------------ // From 979px and below, show a button to toggle navbar contents @import "responsive-navbar.less"; numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/less/bootstrap/navs.less0000664000175100017510000001774312370216246031047 0ustar vagrantvagrant00000000000000// // Navs // -------------------------------------------------- // BASE CLASS // ---------- .nav { margin-left: 0; margin-bottom: @baseLineHeight; list-style: none; } // Make links block level .nav > li > a { display: block; } .nav > li > a:hover, .nav > li > a:focus { text-decoration: none; background-color: @grayLighter; } // Prevent IE8 from misplacing imgs // See https://github.com/h5bp/html5-boilerplate/issues/984#issuecomment-3985989 .nav > li > a > img { max-width: none; } // Redeclare pull classes because of specifity .nav > .pull-right { float: right; } // Nav headers (for dropdowns and lists) .nav-header { display: block; padding: 3px 15px; font-size: 11px; font-weight: bold; line-height: @baseLineHeight; color: @grayLight; text-shadow: 0 1px 0 rgba(255,255,255,.5); text-transform: uppercase; } // Space them out when they follow another list item (link) .nav li + .nav-header { margin-top: 9px; } // NAV LIST // -------- .nav-list { padding-left: 15px; padding-right: 15px; margin-bottom: 0; } .nav-list > li > a, .nav-list .nav-header { margin-left: -15px; margin-right: -15px; text-shadow: 0 1px 0 rgba(255,255,255,.5); } .nav-list > li > a { padding: 3px 15px; } .nav-list > .active > a, .nav-list > .active > a:hover, .nav-list > .active > a:focus { color: @white; text-shadow: 0 -1px 0 rgba(0,0,0,.2); background-color: @linkColor; } .nav-list [class^="icon-"], .nav-list [class*=" icon-"] { margin-right: 2px; } // Dividers (basically an hr) within the dropdown .nav-list .divider { .nav-divider(); } // TABS AND PILLS // ------------- // Common styles .nav-tabs, .nav-pills { .clearfix(); } .nav-tabs > li, .nav-pills > li { float: left; } .nav-tabs > li > a, .nav-pills > li > a { padding-right: 12px; padding-left: 12px; margin-right: 2px; line-height: 14px; // keeps the overall height an even number } // TABS // ---- // Give the tabs something to sit on .nav-tabs { border-bottom: 1px solid #ddd; } // Make the list-items overlay the bottom border .nav-tabs > li { margin-bottom: -1px; } // Actual tabs (as links) .nav-tabs > li > a { padding-top: 8px; padding-bottom: 8px; line-height: @baseLineHeight; border: 1px solid transparent; .border-radius(4px 4px 0 0); &:hover, &:focus { border-color: @grayLighter @grayLighter #ddd; } } // Active state, and it's :hover/:focus to override normal :hover/:focus .nav-tabs > .active > a, .nav-tabs > .active > a:hover, .nav-tabs > .active > a:focus { color: @gray; background-color: @bodyBackground; border: 1px solid #ddd; border-bottom-color: transparent; cursor: default; } // PILLS // ----- // Links rendered as pills .nav-pills > li > a { padding-top: 8px; padding-bottom: 8px; margin-top: 2px; margin-bottom: 2px; .border-radius(5px); } // Active state .nav-pills > .active > a, .nav-pills > .active > a:hover, .nav-pills > .active > a:focus { color: @white; background-color: @linkColor; } // STACKED NAV // ----------- // Stacked tabs and pills .nav-stacked > li { float: none; } .nav-stacked > li > a { margin-right: 0; // no need for the gap between nav items } // Tabs .nav-tabs.nav-stacked { border-bottom: 0; } .nav-tabs.nav-stacked > li > a { border: 1px solid #ddd; .border-radius(0); } .nav-tabs.nav-stacked > li:first-child > a { .border-top-radius(4px); } .nav-tabs.nav-stacked > li:last-child > a { .border-bottom-radius(4px); } .nav-tabs.nav-stacked > li > a:hover, .nav-tabs.nav-stacked > li > a:focus { border-color: #ddd; z-index: 2; } // Pills .nav-pills.nav-stacked > li > a { margin-bottom: 3px; } .nav-pills.nav-stacked > li:last-child > a { margin-bottom: 1px; // decrease margin to match sizing of stacked tabs } // DROPDOWNS // --------- .nav-tabs .dropdown-menu { .border-radius(0 0 6px 6px); // remove the top rounded corners here since there is a hard edge above the menu } .nav-pills .dropdown-menu { .border-radius(6px); // make rounded corners match the pills } // Default dropdown links // ------------------------- // Make carets use linkColor to start .nav .dropdown-toggle .caret { border-top-color: @linkColor; border-bottom-color: @linkColor; margin-top: 6px; } .nav .dropdown-toggle:hover .caret, .nav .dropdown-toggle:focus .caret { border-top-color: @linkColorHover; border-bottom-color: @linkColorHover; } /* move down carets for tabs */ .nav-tabs .dropdown-toggle .caret { margin-top: 8px; } // Active dropdown links // ------------------------- .nav .active .dropdown-toggle .caret { border-top-color: #fff; border-bottom-color: #fff; } .nav-tabs .active .dropdown-toggle .caret { border-top-color: @gray; border-bottom-color: @gray; } // Active:hover/:focus dropdown links // ------------------------- .nav > .dropdown.active > a:hover, .nav > .dropdown.active > a:focus { cursor: pointer; } // Open dropdowns // ------------------------- .nav-tabs .open .dropdown-toggle, .nav-pills .open .dropdown-toggle, .nav > li.dropdown.open.active > a:hover, .nav > li.dropdown.open.active > a:focus { color: @white; background-color: @grayLight; border-color: @grayLight; } .nav li.dropdown.open .caret, .nav li.dropdown.open.active .caret, .nav li.dropdown.open a:hover .caret, .nav li.dropdown.open a:focus .caret { border-top-color: @white; border-bottom-color: @white; .opacity(100); } // Dropdowns in stacked tabs .tabs-stacked .open > a:hover, .tabs-stacked .open > a:focus { border-color: @grayLight; } // TABBABLE // -------- // COMMON STYLES // ------------- // Clear any floats .tabbable { .clearfix(); } .tab-content { overflow: auto; // prevent content from running below tabs } // Remove border on bottom, left, right .tabs-below > .nav-tabs, .tabs-right > .nav-tabs, .tabs-left > .nav-tabs { border-bottom: 0; } // Show/hide tabbable areas .tab-content > .tab-pane, .pill-content > .pill-pane { display: none; } .tab-content > .active, .pill-content > .active { display: block; } // BOTTOM // ------ .tabs-below > .nav-tabs { border-top: 1px solid #ddd; } .tabs-below > .nav-tabs > li { margin-top: -1px; margin-bottom: 0; } .tabs-below > .nav-tabs > li > a { .border-radius(0 0 4px 4px); &:hover, &:focus { border-bottom-color: transparent; border-top-color: #ddd; } } .tabs-below > .nav-tabs > .active > a, .tabs-below > .nav-tabs > .active > a:hover, .tabs-below > .nav-tabs > .active > a:focus { border-color: transparent #ddd #ddd #ddd; } // LEFT & RIGHT // ------------ // Common styles .tabs-left > .nav-tabs > li, .tabs-right > .nav-tabs > li { float: none; } .tabs-left > .nav-tabs > li > a, .tabs-right > .nav-tabs > li > a { min-width: 74px; margin-right: 0; margin-bottom: 3px; } // Tabs on the left .tabs-left > .nav-tabs { float: left; margin-right: 19px; border-right: 1px solid #ddd; } .tabs-left > .nav-tabs > li > a { margin-right: -1px; .border-radius(4px 0 0 4px); } .tabs-left > .nav-tabs > li > a:hover, .tabs-left > .nav-tabs > li > a:focus { border-color: @grayLighter #ddd @grayLighter @grayLighter; } .tabs-left > .nav-tabs .active > a, .tabs-left > .nav-tabs .active > a:hover, .tabs-left > .nav-tabs .active > a:focus { border-color: #ddd transparent #ddd #ddd; *border-right-color: @white; } // Tabs on the right .tabs-right > .nav-tabs { float: right; margin-left: 19px; border-left: 1px solid #ddd; } .tabs-right > .nav-tabs > li > a { margin-left: -1px; .border-radius(0 4px 4px 0); } .tabs-right > .nav-tabs > li > a:hover, .tabs-right > .nav-tabs > li > a:focus { border-color: @grayLighter @grayLighter @grayLighter #ddd; } .tabs-right > .nav-tabs .active > a, .tabs-right > .nav-tabs .active > a:hover, .tabs-right > .nav-tabs .active > a:focus { border-color: #ddd #ddd #ddd transparent; *border-left-color: @white; } // DISABLED STATES // --------------- // Gray out text .nav > .disabled > a { color: @grayLight; } // Nuke hover/focus effects .nav > .disabled > a:hover, .nav > .disabled > a:focus { text-decoration: none; background-color: transparent; cursor: default; } numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/less/bootstrap/layouts.less0000664000175100017510000000051112370216246031561 0ustar vagrantvagrant00000000000000// // Layouts // -------------------------------------------------- // Container (centered, fixed-width layouts) .container { .container-fixed(); } // Fluid layouts (left aligned, with sidebar, min- & max-width content) .container-fluid { padding-right: @gridGutterWidth; padding-left: @gridGutterWidth; .clearfix(); }numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/less/bootstrap/button-groups.less0000664000175100017510000001311512370216246032715 0ustar vagrantvagrant00000000000000// // Button groups // -------------------------------------------------- // Make the div behave like a button .btn-group { position: relative; display: inline-block; .ie7-inline-block(); font-size: 0; // remove as part 1 of font-size inline-block hack vertical-align: middle; // match .btn alignment given font-size hack above white-space: nowrap; // prevent buttons from wrapping when in tight spaces (e.g., the table on the tests page) .ie7-restore-left-whitespace(); } // Space out series of button groups .btn-group + .btn-group { margin-left: 5px; } // Optional: Group multiple button groups together for a toolbar .btn-toolbar { font-size: 0; // Hack to remove whitespace that results from using inline-block margin-top: @baseLineHeight / 2; margin-bottom: @baseLineHeight / 2; > .btn + .btn, > .btn-group + .btn, > .btn + .btn-group { margin-left: 5px; } } // Float them, remove border radius, then re-add to first and last elements .btn-group > .btn { position: relative; .border-radius(0); } .btn-group > .btn + .btn { margin-left: -1px; } .btn-group > .btn, .btn-group > .dropdown-menu, .btn-group > .popover { font-size: @baseFontSize; // redeclare as part 2 of font-size inline-block hack } // Reset fonts for other sizes .btn-group > .btn-mini { font-size: @fontSizeMini; } .btn-group > .btn-small { font-size: @fontSizeSmall; } .btn-group > .btn-large { font-size: @fontSizeLarge; } // Set corners individual because sometimes a single button can be in a .btn-group and we need :first-child and :last-child to both match .btn-group > .btn:first-child { margin-left: 0; .border-top-left-radius(@baseBorderRadius); .border-bottom-left-radius(@baseBorderRadius); } // Need .dropdown-toggle since :last-child doesn't apply given a .dropdown-menu immediately after it .btn-group > .btn:last-child, .btn-group > .dropdown-toggle { .border-top-right-radius(@baseBorderRadius); .border-bottom-right-radius(@baseBorderRadius); } // Reset corners for large buttons .btn-group > .btn.large:first-child { margin-left: 0; .border-top-left-radius(@borderRadiusLarge); .border-bottom-left-radius(@borderRadiusLarge); } .btn-group > .btn.large:last-child, .btn-group > .large.dropdown-toggle { .border-top-right-radius(@borderRadiusLarge); .border-bottom-right-radius(@borderRadiusLarge); } // On hover/focus/active, bring the proper btn to front .btn-group > .btn:hover, .btn-group > .btn:focus, .btn-group > .btn:active, .btn-group > .btn.active { z-index: 2; } // On active and open, don't show outline .btn-group .dropdown-toggle:active, .btn-group.open .dropdown-toggle { outline: 0; } // Split button dropdowns // ---------------------- // Give the line between buttons some depth .btn-group > .btn + .dropdown-toggle { padding-left: 8px; padding-right: 8px; .box-shadow(~"inset 1px 0 0 rgba(255,255,255,.125), inset 0 1px 0 rgba(255,255,255,.2), 0 1px 2px rgba(0,0,0,.05)"); *padding-top: 5px; *padding-bottom: 5px; } .btn-group > .btn-mini + .dropdown-toggle { padding-left: 5px; padding-right: 5px; *padding-top: 2px; *padding-bottom: 2px; } .btn-group > .btn-small + .dropdown-toggle { *padding-top: 5px; *padding-bottom: 4px; } .btn-group > .btn-large + .dropdown-toggle { padding-left: 12px; padding-right: 12px; *padding-top: 7px; *padding-bottom: 7px; } .btn-group.open { // The clickable button for toggling the menu // Remove the gradient and set the same inset shadow as the :active state .dropdown-toggle { background-image: none; .box-shadow(~"inset 0 2px 4px rgba(0,0,0,.15), 0 1px 2px rgba(0,0,0,.05)"); } // Keep the hover's background when dropdown is open .btn.dropdown-toggle { background-color: @btnBackgroundHighlight; } .btn-primary.dropdown-toggle { background-color: @btnPrimaryBackgroundHighlight; } .btn-warning.dropdown-toggle { background-color: @btnWarningBackgroundHighlight; } .btn-danger.dropdown-toggle { background-color: @btnDangerBackgroundHighlight; } .btn-success.dropdown-toggle { background-color: @btnSuccessBackgroundHighlight; } .btn-info.dropdown-toggle { background-color: @btnInfoBackgroundHighlight; } .btn-inverse.dropdown-toggle { background-color: @btnInverseBackgroundHighlight; } } // Reposition the caret .btn .caret { margin-top: 8px; margin-left: 0; } // Carets in other button sizes .btn-large .caret { margin-top: 6px; } .btn-large .caret { border-left-width: 5px; border-right-width: 5px; border-top-width: 5px; } .btn-mini .caret, .btn-small .caret { margin-top: 8px; } // Upside down carets for .dropup .dropup .btn-large .caret { border-bottom-width: 5px; } // Account for other colors .btn-primary, .btn-warning, .btn-danger, .btn-info, .btn-success, .btn-inverse { .caret { border-top-color: @white; border-bottom-color: @white; } } // Vertical button groups // ---------------------- .btn-group-vertical { display: inline-block; // makes buttons only take up the width they need .ie7-inline-block(); } .btn-group-vertical > .btn { display: block; float: none; max-width: 100%; .border-radius(0); } .btn-group-vertical > .btn + .btn { margin-left: 0; margin-top: -1px; } .btn-group-vertical > .btn:first-child { .border-radius(@baseBorderRadius @baseBorderRadius 0 0); } .btn-group-vertical > .btn:last-child { .border-radius(0 0 @baseBorderRadius @baseBorderRadius); } .btn-group-vertical > .btn-large:first-child { .border-radius(@borderRadiusLarge @borderRadiusLarge 0 0); } .btn-group-vertical > .btn-large:last-child { .border-radius(0 0 @borderRadiusLarge @borderRadiusLarge); } numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/less/bootstrap/navbar.less0000664000175100017510000002734212370216246031345 0ustar vagrantvagrant00000000000000// // Navbars (Redux) // -------------------------------------------------- // COMMON STYLES // ------------- // Base class and wrapper .navbar { overflow: visible; margin-bottom: @baseLineHeight; // Fix for IE7's bad z-indexing so dropdowns don't appear below content that follows the navbar *position: relative; *z-index: 2; } // Inner for background effects // Gradient is applied to its own element because overflow visible is not honored by IE when filter is present .navbar-inner { min-height: @navbarHeight; padding-left: 20px; padding-right: 20px; #gradient > .vertical(@navbarBackgroundHighlight, @navbarBackground); border: 1px solid @navbarBorder; .border-radius(@baseBorderRadius); .box-shadow(0 1px 4px rgba(0,0,0,.065)); // Prevent floats from breaking the navbar .clearfix(); } // Set width to auto for default container // We then reset it for fixed navbars in the #gridSystem mixin .navbar .container { width: auto; } // Override the default collapsed state .nav-collapse.collapse { height: auto; overflow: visible; } // Brand: website or project name // ------------------------- .navbar .brand { float: left; display: block; // Vertically center the text given @navbarHeight padding: ((@navbarHeight - @baseLineHeight) / 2) 20px ((@navbarHeight - @baseLineHeight) / 2); margin-left: -20px; // negative indent to left-align the text down the page font-size: 20px; font-weight: 200; color: @navbarBrandColor; text-shadow: 0 1px 0 @navbarBackgroundHighlight; &:hover, &:focus { text-decoration: none; } } // Plain text in topbar // ------------------------- .navbar-text { margin-bottom: 0; line-height: @navbarHeight; color: @navbarText; } // Janky solution for now to account for links outside the .nav // ------------------------- .navbar-link { color: @navbarLinkColor; &:hover, &:focus { color: @navbarLinkColorHover; } } // Dividers in navbar // ------------------------- .navbar .divider-vertical { height: @navbarHeight; margin: 0 9px; border-left: 1px solid @navbarBackground; border-right: 1px solid @navbarBackgroundHighlight; } // Buttons in navbar // ------------------------- .navbar .btn, .navbar .btn-group { .navbarVerticalAlign(30px); // Vertically center in navbar } .navbar .btn-group .btn, .navbar .input-prepend .btn, .navbar .input-append .btn, .navbar .input-prepend .btn-group, .navbar .input-append .btn-group { margin-top: 0; // then undo the margin here so we don't accidentally double it } // Navbar forms // ------------------------- .navbar-form { margin-bottom: 0; // remove default bottom margin .clearfix(); input, select, .radio, .checkbox { .navbarVerticalAlign(30px); // Vertically center in navbar } input, select, .btn { display: inline-block; margin-bottom: 0; } input[type="image"], input[type="checkbox"], input[type="radio"] { margin-top: 3px; } .input-append, .input-prepend { margin-top: 5px; white-space: nowrap; // preven two items from separating within a .navbar-form that has .pull-left input { margin-top: 0; // remove the margin on top since it's on the parent } } } // Navbar search // ------------------------- .navbar-search { position: relative; float: left; .navbarVerticalAlign(30px); // Vertically center in navbar margin-bottom: 0; .search-query { margin-bottom: 0; padding: 4px 14px; #font > .sans-serif(13px, normal, 1); .border-radius(15px); // redeclare because of specificity of the type attribute } } // Static navbar // ------------------------- .navbar-static-top { position: static; margin-bottom: 0; // remove 18px margin for default navbar .navbar-inner { .border-radius(0); } } // Fixed navbar // ------------------------- // Shared (top/bottom) styles .navbar-fixed-top, .navbar-fixed-bottom { position: fixed; right: 0; left: 0; z-index: @zindexFixedNavbar; margin-bottom: 0; // remove 18px margin for default navbar } .navbar-fixed-top .navbar-inner, .navbar-static-top .navbar-inner { border-width: 0 0 1px; } .navbar-fixed-bottom .navbar-inner { border-width: 1px 0 0; } .navbar-fixed-top .navbar-inner, .navbar-fixed-bottom .navbar-inner { padding-left: 0; padding-right: 0; .border-radius(0); } // Reset container width // Required here as we reset the width earlier on and the grid mixins don't override early enough .navbar-static-top .container, .navbar-fixed-top .container, .navbar-fixed-bottom .container { #grid > .core > .span(@gridColumns); } // Fixed to top .navbar-fixed-top { top: 0; } .navbar-fixed-top, .navbar-static-top { .navbar-inner { .box-shadow(~"0 1px 10px rgba(0,0,0,.1)"); } } // Fixed to bottom .navbar-fixed-bottom { bottom: 0; .navbar-inner { .box-shadow(~"0 -1px 10px rgba(0,0,0,.1)"); } } // NAVIGATION // ---------- .navbar .nav { position: relative; left: 0; display: block; float: left; margin: 0 10px 0 0; } .navbar .nav.pull-right { float: right; // redeclare due to specificity margin-right: 0; // remove margin on float right nav } .navbar .nav > li { float: left; } // Links .navbar .nav > li > a { float: none; // Vertically center the text given @navbarHeight padding: ((@navbarHeight - @baseLineHeight) / 2) 15px ((@navbarHeight - @baseLineHeight) / 2); color: @navbarLinkColor; text-decoration: none; text-shadow: 0 1px 0 @navbarBackgroundHighlight; } .navbar .nav .dropdown-toggle .caret { margin-top: 8px; } // Hover/focus .navbar .nav > li > a:focus, .navbar .nav > li > a:hover { background-color: @navbarLinkBackgroundHover; // "transparent" is default to differentiate :hover/:focus from .active color: @navbarLinkColorHover; text-decoration: none; } // Active nav items .navbar .nav > .active > a, .navbar .nav > .active > a:hover, .navbar .nav > .active > a:focus { color: @navbarLinkColorActive; text-decoration: none; background-color: @navbarLinkBackgroundActive; .box-shadow(inset 0 3px 8px rgba(0,0,0,.125)); } // Navbar button for toggling navbar items in responsive layouts // These definitions need to come after '.navbar .btn' .navbar .btn-navbar { display: none; float: right; padding: 7px 10px; margin-left: 5px; margin-right: 5px; .buttonBackground(darken(@navbarBackgroundHighlight, 5%), darken(@navbarBackground, 5%)); .box-shadow(~"inset 0 1px 0 rgba(255,255,255,.1), 0 1px 0 rgba(255,255,255,.075)"); } .navbar .btn-navbar .icon-bar { display: block; width: 18px; height: 2px; background-color: #f5f5f5; .border-radius(1px); .box-shadow(0 1px 0 rgba(0,0,0,.25)); } .btn-navbar .icon-bar + .icon-bar { margin-top: 3px; } // Dropdown menus // -------------- // Menu position and menu carets .navbar .nav > li > .dropdown-menu { &:before { content: ''; display: inline-block; border-left: 7px solid transparent; border-right: 7px solid transparent; border-bottom: 7px solid #ccc; border-bottom-color: @dropdownBorder; position: absolute; top: -7px; left: 9px; } &:after { content: ''; display: inline-block; border-left: 6px solid transparent; border-right: 6px solid transparent; border-bottom: 6px solid @dropdownBackground; position: absolute; top: -6px; left: 10px; } } // Menu position and menu caret support for dropups via extra dropup class .navbar-fixed-bottom .nav > li > .dropdown-menu { &:before { border-top: 7px solid #ccc; border-top-color: @dropdownBorder; border-bottom: 0; bottom: -7px; top: auto; } &:after { border-top: 6px solid @dropdownBackground; border-bottom: 0; bottom: -6px; top: auto; } } // Caret should match text color on hover/focus .navbar .nav li.dropdown > a:hover .caret, .navbar .nav li.dropdown > a:focus .caret { border-top-color: @navbarLinkColorHover; border-bottom-color: @navbarLinkColorHover; } // Remove background color from open dropdown .navbar .nav li.dropdown.open > .dropdown-toggle, .navbar .nav li.dropdown.active > .dropdown-toggle, .navbar .nav li.dropdown.open.active > .dropdown-toggle { background-color: @navbarLinkBackgroundActive; color: @navbarLinkColorActive; } .navbar .nav li.dropdown > .dropdown-toggle .caret { border-top-color: @navbarLinkColor; border-bottom-color: @navbarLinkColor; } .navbar .nav li.dropdown.open > .dropdown-toggle .caret, .navbar .nav li.dropdown.active > .dropdown-toggle .caret, .navbar .nav li.dropdown.open.active > .dropdown-toggle .caret { border-top-color: @navbarLinkColorActive; border-bottom-color: @navbarLinkColorActive; } // Right aligned menus need alt position .navbar .pull-right > li > .dropdown-menu, .navbar .nav > li > .dropdown-menu.pull-right { left: auto; right: 0; &:before { left: auto; right: 12px; } &:after { left: auto; right: 13px; } .dropdown-menu { left: auto; right: 100%; margin-left: 0; margin-right: -1px; .border-radius(6px 0 6px 6px); } } // Inverted navbar // ------------------------- .navbar-inverse { .navbar-inner { #gradient > .vertical(@navbarInverseBackgroundHighlight, @navbarInverseBackground); border-color: @navbarInverseBorder; } .brand, .nav > li > a { color: @navbarInverseLinkColor; text-shadow: 0 -1px 0 rgba(0,0,0,.25); &:hover, &:focus { color: @navbarInverseLinkColorHover; } } .brand { color: @navbarInverseBrandColor; } .navbar-text { color: @navbarInverseText; } .nav > li > a:focus, .nav > li > a:hover { background-color: @navbarInverseLinkBackgroundHover; color: @navbarInverseLinkColorHover; } .nav .active > a, .nav .active > a:hover, .nav .active > a:focus { color: @navbarInverseLinkColorActive; background-color: @navbarInverseLinkBackgroundActive; } // Inline text links .navbar-link { color: @navbarInverseLinkColor; &:hover, &:focus { color: @navbarInverseLinkColorHover; } } // Dividers in navbar .divider-vertical { border-left-color: @navbarInverseBackground; border-right-color: @navbarInverseBackgroundHighlight; } // Dropdowns .nav li.dropdown.open > .dropdown-toggle, .nav li.dropdown.active > .dropdown-toggle, .nav li.dropdown.open.active > .dropdown-toggle { background-color: @navbarInverseLinkBackgroundActive; color: @navbarInverseLinkColorActive; } .nav li.dropdown > a:hover .caret, .nav li.dropdown > a:focus .caret { border-top-color: @navbarInverseLinkColorActive; border-bottom-color: @navbarInverseLinkColorActive; } .nav li.dropdown > .dropdown-toggle .caret { border-top-color: @navbarInverseLinkColor; border-bottom-color: @navbarInverseLinkColor; } .nav li.dropdown.open > .dropdown-toggle .caret, .nav li.dropdown.active > .dropdown-toggle .caret, .nav li.dropdown.open.active > .dropdown-toggle .caret { border-top-color: @navbarInverseLinkColorActive; border-bottom-color: @navbarInverseLinkColorActive; } // Navbar search .navbar-search { .search-query { color: @white; background-color: @navbarInverseSearchBackground; border-color: @navbarInverseSearchBorder; .box-shadow(~"inset 0 1px 2px rgba(0,0,0,.1), 0 1px 0 rgba(255,255,255,.15)"); .transition(none); .placeholder(@navbarInverseSearchPlaceholderColor); // Focus states (we use .focused since IE7-8 and down doesn't support :focus) &:focus, &.focused { padding: 5px 15px; color: @grayDark; text-shadow: 0 1px 0 @white; background-color: @navbarInverseSearchBackgroundFocus; border: 0; .box-shadow(0 0 3px rgba(0,0,0,.15)); outline: 0; } } } // Navbar collapse button .btn-navbar { .buttonBackground(darken(@navbarInverseBackgroundHighlight, 5%), darken(@navbarInverseBackground, 5%)); } } numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/less/bootstrap/close.less0000664000175100017510000000120412370216246031166 0ustar vagrantvagrant00000000000000// // Close icons // -------------------------------------------------- .close { float: right; font-size: 20px; font-weight: bold; line-height: @baseLineHeight; color: @black; text-shadow: 0 1px 0 rgba(255,255,255,1); .opacity(20); &:hover, &:focus { color: @black; text-decoration: none; cursor: pointer; .opacity(40); } } // Additional properties for button version // iOS requires the button element instead of an anchor tag. // If you want the anchor version, it requires `href="#"`. button.close { padding: 0; cursor: pointer; background: transparent; border: 0; -webkit-appearance: none; }numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/less/bootstrap/progress-bars.less0000664000175100017510000000545212370216246032663 0ustar vagrantvagrant00000000000000// // Progress bars // -------------------------------------------------- // ANIMATIONS // ---------- // Webkit @-webkit-keyframes progress-bar-stripes { from { background-position: 40px 0; } to { background-position: 0 0; } } // Firefox @-moz-keyframes progress-bar-stripes { from { background-position: 40px 0; } to { background-position: 0 0; } } // IE9 @-ms-keyframes progress-bar-stripes { from { background-position: 40px 0; } to { background-position: 0 0; } } // Opera @-o-keyframes progress-bar-stripes { from { background-position: 0 0; } to { background-position: 40px 0; } } // Spec @keyframes progress-bar-stripes { from { background-position: 40px 0; } to { background-position: 0 0; } } // THE BARS // -------- // Outer container .progress { overflow: hidden; height: @baseLineHeight; margin-bottom: @baseLineHeight; #gradient > .vertical(#f5f5f5, #f9f9f9); .box-shadow(inset 0 1px 2px rgba(0,0,0,.1)); .border-radius(@baseBorderRadius); } // Bar of progress .progress .bar { width: 0%; height: 100%; color: @white; float: left; font-size: 12px; text-align: center; text-shadow: 0 -1px 0 rgba(0,0,0,.25); #gradient > .vertical(#149bdf, #0480be); .box-shadow(inset 0 -1px 0 rgba(0,0,0,.15)); .box-sizing(border-box); .transition(width .6s ease); } .progress .bar + .bar { .box-shadow(~"inset 1px 0 0 rgba(0,0,0,.15), inset 0 -1px 0 rgba(0,0,0,.15)"); } // Striped bars .progress-striped .bar { #gradient > .striped(#149bdf); .background-size(40px 40px); } // Call animation for the active one .progress.active .bar { -webkit-animation: progress-bar-stripes 2s linear infinite; -moz-animation: progress-bar-stripes 2s linear infinite; -ms-animation: progress-bar-stripes 2s linear infinite; -o-animation: progress-bar-stripes 2s linear infinite; animation: progress-bar-stripes 2s linear infinite; } // COLORS // ------ // Danger (red) .progress-danger .bar, .progress .bar-danger { #gradient > .vertical(#ee5f5b, #c43c35); } .progress-danger.progress-striped .bar, .progress-striped .bar-danger { #gradient > .striped(#ee5f5b); } // Success (green) .progress-success .bar, .progress .bar-success { #gradient > .vertical(#62c462, #57a957); } .progress-success.progress-striped .bar, .progress-striped .bar-success { #gradient > .striped(#62c462); } // Info (teal) .progress-info .bar, .progress .bar-info { #gradient > .vertical(#5bc0de, #339bb9); } .progress-info.progress-striped .bar, .progress-striped .bar-info { #gradient > .striped(#5bc0de); } // Warning (orange) .progress-warning .bar, .progress .bar-warning { #gradient > .vertical(lighten(@orange, 15%), @orange); } .progress-warning.progress-striped .bar, .progress-striped .bar-warning { #gradient > .striped(lighten(@orange, 15%)); } numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/less/bootstrap/carousel.less0000664000175100017510000000466212370216246031711 0ustar vagrantvagrant00000000000000// // Carousel // -------------------------------------------------- .carousel { position: relative; margin-bottom: @baseLineHeight; line-height: 1; } .carousel-inner { overflow: hidden; width: 100%; position: relative; } .carousel-inner { > .item { display: none; position: relative; .transition(.6s ease-in-out left); // Account for jankitude on images > img, > a > img { display: block; line-height: 1; } } > .active, > .next, > .prev { display: block; } > .active { left: 0; } > .next, > .prev { position: absolute; top: 0; width: 100%; } > .next { left: 100%; } > .prev { left: -100%; } > .next.left, > .prev.right { left: 0; } > .active.left { left: -100%; } > .active.right { left: 100%; } } // Left/right controls for nav // --------------------------- .carousel-control { position: absolute; top: 40%; left: 15px; width: 40px; height: 40px; margin-top: -20px; font-size: 60px; font-weight: 100; line-height: 30px; color: @white; text-align: center; background: @grayDarker; border: 3px solid @white; .border-radius(23px); .opacity(50); // we can't have this transition here // because webkit cancels the carousel // animation if you trip this while // in the middle of another animation // ;_; // .transition(opacity .2s linear); // Reposition the right one &.right { left: auto; right: 15px; } // Hover/focus state &:hover, &:focus { color: @white; text-decoration: none; .opacity(90); } } // Carousel indicator pips // ----------------------------- .carousel-indicators { position: absolute; top: 15px; right: 15px; z-index: 5; margin: 0; list-style: none; li { display: block; float: left; width: 10px; height: 10px; margin-left: 5px; text-indent: -999px; background-color: #ccc; background-color: rgba(255,255,255,.25); border-radius: 5px; } .active { background-color: #fff; } } // Caption for text below images // ----------------------------- .carousel-caption { position: absolute; left: 0; right: 0; bottom: 0; padding: 15px; background: @grayDark; background: rgba(0,0,0,.75); } .carousel-caption h4, .carousel-caption p { color: @white; line-height: @baseLineHeight; } .carousel-caption h4 { margin: 0 0 5px; } .carousel-caption p { margin-bottom: 0; } numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/less/bootstrap/hero-unit.less0000664000175100017510000000101112370216246031767 0ustar vagrantvagrant00000000000000// // Hero unit // -------------------------------------------------- .hero-unit { padding: 60px; margin-bottom: 30px; font-size: 18px; font-weight: 200; line-height: @baseLineHeight * 1.5; color: @heroUnitLeadColor; background-color: @heroUnitBackground; .border-radius(6px); h1 { margin-bottom: 0; font-size: 60px; line-height: 1; color: @heroUnitHeadingColor; letter-spacing: -1px; } li { line-height: @baseLineHeight * 1.5; // Reset since we specify in type.less } } numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/less/bootstrap/responsive-navbar.less0000664000175100017510000001035012370216246033527 0ustar vagrantvagrant00000000000000// // Responsive: Navbar // -------------------------------------------------- // TABLETS AND BELOW // ----------------- @media (max-width: @navbarCollapseWidth) { // UNFIX THE TOPBAR // ---------------- // Remove any padding from the body body { padding-top: 0; } // Unfix the navbars .navbar-fixed-top, .navbar-fixed-bottom { position: static; } .navbar-fixed-top { margin-bottom: @baseLineHeight; } .navbar-fixed-bottom { margin-top: @baseLineHeight; } .navbar-fixed-top .navbar-inner, .navbar-fixed-bottom .navbar-inner { padding: 5px; } .navbar .container { width: auto; padding: 0; } // Account for brand name .navbar .brand { padding-left: 10px; padding-right: 10px; margin: 0 0 0 -5px; } // COLLAPSIBLE NAVBAR // ------------------ // Nav collapse clears brand .nav-collapse { clear: both; } // Block-level the nav .nav-collapse .nav { float: none; margin: 0 0 (@baseLineHeight / 2); } .nav-collapse .nav > li { float: none; } .nav-collapse .nav > li > a { margin-bottom: 2px; } .nav-collapse .nav > .divider-vertical { display: none; } .nav-collapse .nav .nav-header { color: @navbarText; text-shadow: none; } // Nav and dropdown links in navbar .nav-collapse .nav > li > a, .nav-collapse .dropdown-menu a { padding: 9px 15px; font-weight: bold; color: @navbarLinkColor; .border-radius(3px); } // Buttons .nav-collapse .btn { padding: 4px 10px 4px; font-weight: normal; .border-radius(@baseBorderRadius); } .nav-collapse .dropdown-menu li + li a { margin-bottom: 2px; } .nav-collapse .nav > li > a:hover, .nav-collapse .nav > li > a:focus, .nav-collapse .dropdown-menu a:hover, .nav-collapse .dropdown-menu a:focus { background-color: @navbarBackground; } .navbar-inverse .nav-collapse .nav > li > a, .navbar-inverse .nav-collapse .dropdown-menu a { color: @navbarInverseLinkColor; } .navbar-inverse .nav-collapse .nav > li > a:hover, .navbar-inverse .nav-collapse .nav > li > a:focus, .navbar-inverse .nav-collapse .dropdown-menu a:hover, .navbar-inverse .nav-collapse .dropdown-menu a:focus { background-color: @navbarInverseBackground; } // Buttons in the navbar .nav-collapse.in .btn-group { margin-top: 5px; padding: 0; } // Dropdowns in the navbar .nav-collapse .dropdown-menu { position: static; top: auto; left: auto; float: none; display: none; max-width: none; margin: 0 15px; padding: 0; background-color: transparent; border: none; .border-radius(0); .box-shadow(none); } .nav-collapse .open > .dropdown-menu { display: block; } .nav-collapse .dropdown-menu:before, .nav-collapse .dropdown-menu:after { display: none; } .nav-collapse .dropdown-menu .divider { display: none; } .nav-collapse .nav > li > .dropdown-menu { &:before, &:after { display: none; } } // Forms in navbar .nav-collapse .navbar-form, .nav-collapse .navbar-search { float: none; padding: (@baseLineHeight / 2) 15px; margin: (@baseLineHeight / 2) 0; border-top: 1px solid @navbarBackground; border-bottom: 1px solid @navbarBackground; .box-shadow(~"inset 0 1px 0 rgba(255,255,255,.1), 0 1px 0 rgba(255,255,255,.1)"); } .navbar-inverse .nav-collapse .navbar-form, .navbar-inverse .nav-collapse .navbar-search { border-top-color: @navbarInverseBackground; border-bottom-color: @navbarInverseBackground; } // Pull right (secondary) nav content .navbar .nav-collapse .nav.pull-right { float: none; margin-left: 0; } // Hide everything in the navbar save .brand and toggle button */ .nav-collapse, .nav-collapse.collapse { overflow: hidden; height: 0; } // Navbar button .navbar .btn-navbar { display: block; } // STATIC NAVBAR // ------------- .navbar-static .navbar-inner { padding-left: 10px; padding-right: 10px; } } // DEFAULT DESKTOP // --------------- @media (min-width: @navbarCollapseDesktopWidth) { // Required to make the collapsing navbar work on regular desktops .nav-collapse.collapse { height: auto !important; overflow: visible !important; } } numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/less/bootstrap/reset.less0000664000175100017510000001015112370216246031204 0ustar vagrantvagrant00000000000000// // Reset CSS // Adapted from http://github.com/necolas/normalize.css // -------------------------------------------------- // Display in IE6-9 and FF3 // ------------------------- article, aside, details, figcaption, figure, footer, header, hgroup, nav, section { display: block; } // Display block in IE6-9 and FF3 // ------------------------- audio, canvas, video { display: inline-block; *display: inline; *zoom: 1; } // Prevents modern browsers from displaying 'audio' without controls // ------------------------- audio:not([controls]) { display: none; } // Base settings // ------------------------- html { font-size: 100%; -webkit-text-size-adjust: 100%; -ms-text-size-adjust: 100%; } // Focus states a:focus { .tab-focus(); } // Hover & Active a:hover, a:active { outline: 0; } // Prevents sub and sup affecting line-height in all browsers // ------------------------- sub, sup { position: relative; font-size: 75%; line-height: 0; vertical-align: baseline; } sup { top: -0.5em; } sub { bottom: -0.25em; } // Img border in a's and image quality // ------------------------- img { /* Responsive images (ensure images don't scale beyond their parents) */ max-width: 100%; /* Part 1: Set a maxium relative to the parent */ width: auto\9; /* IE7-8 need help adjusting responsive images */ height: auto; /* Part 2: Scale the height according to the width, otherwise you get stretching */ vertical-align: middle; border: 0; -ms-interpolation-mode: bicubic; } // Prevent max-width from affecting Google Maps #map_canvas img, .google-maps img { max-width: none; } // Forms // ------------------------- // Font size in all browsers, margin changes, misc consistency button, input, select, textarea { margin: 0; font-size: 100%; vertical-align: middle; } button, input { *overflow: visible; // Inner spacing ie IE6/7 line-height: normal; // FF3/4 have !important on line-height in UA stylesheet } button::-moz-focus-inner, input::-moz-focus-inner { // Inner padding and border oddities in FF3/4 padding: 0; border: 0; } button, html input[type="button"], // Avoid the WebKit bug in Android 4.0.* where (2) destroys native `audio` and `video` controls. input[type="reset"], input[type="submit"] { -webkit-appearance: button; // Corrects inability to style clickable `input` types in iOS. cursor: pointer; // Improves usability and consistency of cursor style between image-type `input` and others. } label, select, button, input[type="button"], input[type="reset"], input[type="submit"], input[type="radio"], input[type="checkbox"] { cursor: pointer; // Improves usability and consistency of cursor style between image-type `input` and others. } input[type="search"] { // Appearance in Safari/Chrome .box-sizing(content-box); -webkit-appearance: textfield; } input[type="search"]::-webkit-search-decoration, input[type="search"]::-webkit-search-cancel-button { -webkit-appearance: none; // Inner-padding issues in Chrome OSX, Safari 5 } textarea { overflow: auto; // Remove vertical scrollbar in IE6-9 vertical-align: top; // Readability and alignment cross-browser } // Printing // ------------------------- // Source: https://github.com/h5bp/html5-boilerplate/blob/master/css/main.css @media print { * { text-shadow: none !important; color: #000 !important; // Black prints faster: h5bp.com/s background: transparent !important; box-shadow: none !important; } a, a:visited { text-decoration: underline; } a[href]:after { content: " (" attr(href) ")"; } abbr[title]:after { content: " (" attr(title) ")"; } // Don't show links for images, or javascript/internal links .ir a:after, a[href^="javascript:"]:after, a[href^="#"]:after { content: ""; } pre, blockquote { border: 1px solid #999; page-break-inside: avoid; } thead { display: table-header-group; // h5bp.com/t } tr, img { page-break-inside: avoid; } img { max-width: 100% !important; } @page { margin: 0.5cm; } p, h2, h3 { orphans: 3; widows: 3; } h2, h3 { page-break-after: avoid; } } numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/less/bootstrap/wells.less0000664000175100017510000000105012370216246031206 0ustar vagrantvagrant00000000000000// // Wells // -------------------------------------------------- // Base class .well { min-height: 20px; padding: 19px; margin-bottom: 20px; background-color: @wellBackground; border: 1px solid darken(@wellBackground, 7%); .border-radius(@baseBorderRadius); .box-shadow(inset 0 1px 1px rgba(0,0,0,.05)); blockquote { border-color: #ddd; border-color: rgba(0,0,0,.15); } } // Sizes .well-large { padding: 24px; .border-radius(@borderRadiusLarge); } .well-small { padding: 9px; .border-radius(@borderRadiusSmall); } numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/less/bootstrap/scaffolding.less0000664000175100017510000000156512370216246032352 0ustar vagrantvagrant00000000000000// // Scaffolding // -------------------------------------------------- // Body reset // ------------------------- body { margin: 0; font-family: @baseFontFamily; font-size: @baseFontSize; line-height: @baseLineHeight; color: @textColor; background-color: @bodyBackground; } // Links // ------------------------- a { color: @linkColor; text-decoration: none; } a:hover, a:focus { color: @linkColorHover; text-decoration: underline; } // Images // ------------------------- // Rounded corners .img-rounded { .border-radius(6px); } // Add polaroid-esque trim .img-polaroid { padding: 4px; background-color: #fff; border: 1px solid #ccc; border: 1px solid rgba(0,0,0,.2); .box-shadow(0 1px 3px rgba(0,0,0,.1)); } // Perfect circle .img-circle { .border-radius(500px); // crank the border-radius so it works with most reasonably sized images } numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/less/bootstrap/buttons.less0000664000175100017510000001123612370216246031565 0ustar vagrantvagrant00000000000000// // Buttons // -------------------------------------------------- // Base styles // -------------------------------------------------- // Core .btn { display: inline-block; .ie7-inline-block(); padding: 4px 12px; margin-bottom: 0; // For input.btn font-size: @baseFontSize; line-height: @baseLineHeight; text-align: center; vertical-align: middle; cursor: pointer; .buttonBackground(@btnBackground, @btnBackgroundHighlight, @grayDark, 0 1px 1px rgba(255,255,255,.75)); border: 1px solid @btnBorder; *border: 0; // Remove the border to prevent IE7's black border on input:focus border-bottom-color: darken(@btnBorder, 10%); .border-radius(@baseBorderRadius); .ie7-restore-left-whitespace(); // Give IE7 some love .box-shadow(~"inset 0 1px 0 rgba(255,255,255,.2), 0 1px 2px rgba(0,0,0,.05)"); // Hover/focus state &:hover, &:focus { color: @grayDark; text-decoration: none; background-position: 0 -15px; // transition is only when going to hover/focus, otherwise the background // behind the gradient (there for IE<=9 fallback) gets mismatched .transition(background-position .1s linear); } // Focus state for keyboard and accessibility &:focus { .tab-focus(); } // Active state &.active, &:active { background-image: none; outline: 0; .box-shadow(~"inset 0 2px 4px rgba(0,0,0,.15), 0 1px 2px rgba(0,0,0,.05)"); } // Disabled state &.disabled, &[disabled] { cursor: default; background-image: none; .opacity(65); .box-shadow(none); } } // Button Sizes // -------------------------------------------------- // Large .btn-large { padding: @paddingLarge; font-size: @fontSizeLarge; .border-radius(@borderRadiusLarge); } .btn-large [class^="icon-"], .btn-large [class*=" icon-"] { margin-top: 4px; } // Small .btn-small { padding: @paddingSmall; font-size: @fontSizeSmall; .border-radius(@borderRadiusSmall); } .btn-small [class^="icon-"], .btn-small [class*=" icon-"] { margin-top: 0; } .btn-mini [class^="icon-"], .btn-mini [class*=" icon-"] { margin-top: -1px; } // Mini .btn-mini { padding: @paddingMini; font-size: @fontSizeMini; .border-radius(@borderRadiusSmall); } // Block button // ------------------------- .btn-block { display: block; width: 100%; padding-left: 0; padding-right: 0; .box-sizing(border-box); } // Vertically space out multiple block buttons .btn-block + .btn-block { margin-top: 5px; } // Specificity overrides input[type="submit"], input[type="reset"], input[type="button"] { &.btn-block { width: 100%; } } // Alternate buttons // -------------------------------------------------- // Provide *some* extra contrast for those who can get it .btn-primary.active, .btn-warning.active, .btn-danger.active, .btn-success.active, .btn-info.active, .btn-inverse.active { color: rgba(255,255,255,.75); } // Set the backgrounds // ------------------------- .btn-primary { .buttonBackground(@btnPrimaryBackground, @btnPrimaryBackgroundHighlight); } // Warning appears are orange .btn-warning { .buttonBackground(@btnWarningBackground, @btnWarningBackgroundHighlight); } // Danger and error appear as red .btn-danger { .buttonBackground(@btnDangerBackground, @btnDangerBackgroundHighlight); } // Success appears as green .btn-success { .buttonBackground(@btnSuccessBackground, @btnSuccessBackgroundHighlight); } // Info appears as a neutral blue .btn-info { .buttonBackground(@btnInfoBackground, @btnInfoBackgroundHighlight); } // Inverse appears as dark gray .btn-inverse { .buttonBackground(@btnInverseBackground, @btnInverseBackgroundHighlight); } // Cross-browser Jank // -------------------------------------------------- button.btn, input[type="submit"].btn { // Firefox 3.6 only I believe &::-moz-focus-inner { padding: 0; border: 0; } // IE7 has some default padding on button controls *padding-top: 3px; *padding-bottom: 3px; &.btn-large { *padding-top: 7px; *padding-bottom: 7px; } &.btn-small { *padding-top: 3px; *padding-bottom: 3px; } &.btn-mini { *padding-top: 1px; *padding-bottom: 1px; } } // Link buttons // -------------------------------------------------- // Make a button look and behave like a link .btn-link, .btn-link:active, .btn-link[disabled] { background-color: transparent; background-image: none; .box-shadow(none); } .btn-link { border-color: transparent; cursor: pointer; color: @linkColor; .border-radius(0); } .btn-link:hover, .btn-link:focus { color: @linkColorHover; text-decoration: underline; background-color: transparent; } .btn-link[disabled]:hover, .btn-link[disabled]:focus { color: @grayDark; text-decoration: none; } numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/less/bootstrap/sprites.less0000664000175100017510000002513112370216246031557 0ustar vagrantvagrant00000000000000// // Sprites // -------------------------------------------------- // ICONS // ----- // All icons receive the styles of the tag with a base class // of .i and are then given a unique class to add width, height, // and background-position. Your resulting HTML will look like // . // For the white version of the icons, just add the .icon-white class: // [class^="icon-"], [class*=" icon-"] { display: inline-block; width: 14px; height: 14px; .ie7-restore-right-whitespace(); line-height: 14px; vertical-align: text-top; background-image: url("@{iconSpritePath}"); background-position: 14px 14px; background-repeat: no-repeat; margin-top: 1px; } /* White icons with optional class, or on hover/focus/active states of certain elements */ .icon-white, .nav-pills > .active > a > [class^="icon-"], .nav-pills > .active > a > [class*=" icon-"], .nav-list > .active > a > [class^="icon-"], .nav-list > .active > a > [class*=" icon-"], .navbar-inverse .nav > .active > a > [class^="icon-"], .navbar-inverse .nav > .active > a > [class*=" icon-"], .dropdown-menu > li > a:hover > [class^="icon-"], .dropdown-menu > li > a:focus > [class^="icon-"], .dropdown-menu > li > a:hover > [class*=" icon-"], .dropdown-menu > li > a:focus > [class*=" icon-"], .dropdown-menu > .active > a > [class^="icon-"], .dropdown-menu > .active > a > [class*=" icon-"], .dropdown-submenu:hover > a > [class^="icon-"], .dropdown-submenu:focus > a > [class^="icon-"], .dropdown-submenu:hover > a > [class*=" icon-"], .dropdown-submenu:focus > a > [class*=" icon-"] { background-image: url("@{iconWhiteSpritePath}"); } .icon-glass { background-position: 0 0; } .icon-music { background-position: -24px 0; } .icon-search { background-position: -48px 0; } .icon-envelope { background-position: -72px 0; } .icon-heart { background-position: -96px 0; } .icon-star { background-position: -120px 0; } .icon-star-empty { background-position: -144px 0; } .icon-user { background-position: -168px 0; } .icon-film { background-position: -192px 0; } .icon-th-large { background-position: -216px 0; } .icon-th { background-position: -240px 0; } .icon-th-list { background-position: -264px 0; } .icon-ok { background-position: -288px 0; } .icon-remove { background-position: -312px 0; } .icon-zoom-in { background-position: -336px 0; } .icon-zoom-out { background-position: -360px 0; } .icon-off { background-position: -384px 0; } .icon-signal { background-position: -408px 0; } .icon-cog { background-position: -432px 0; } .icon-trash { background-position: -456px 0; } .icon-home { background-position: 0 -24px; } .icon-file { background-position: -24px -24px; } .icon-time { background-position: -48px -24px; } .icon-road { background-position: -72px -24px; } .icon-download-alt { background-position: -96px -24px; } .icon-download { background-position: -120px -24px; } .icon-upload { background-position: -144px -24px; } .icon-inbox { background-position: -168px -24px; } .icon-play-circle { background-position: -192px -24px; } .icon-repeat { background-position: -216px -24px; } .icon-refresh { background-position: -240px -24px; } .icon-list-alt { background-position: -264px -24px; } .icon-lock { background-position: -287px -24px; } // 1px off .icon-flag { background-position: -312px -24px; } .icon-headphones { background-position: -336px -24px; } .icon-volume-off { background-position: -360px -24px; } .icon-volume-down { background-position: -384px -24px; } .icon-volume-up { background-position: -408px -24px; } .icon-qrcode { background-position: -432px -24px; } .icon-barcode { background-position: -456px -24px; } .icon-tag { background-position: 0 -48px; } .icon-tags { background-position: -25px -48px; } // 1px off .icon-book { background-position: -48px -48px; } .icon-bookmark { background-position: -72px -48px; } .icon-print { background-position: -96px -48px; } .icon-camera { background-position: -120px -48px; } .icon-font { background-position: -144px -48px; } .icon-bold { background-position: -167px -48px; } // 1px off .icon-italic { background-position: -192px -48px; } .icon-text-height { background-position: -216px -48px; } .icon-text-width { background-position: -240px -48px; } .icon-align-left { background-position: -264px -48px; } .icon-align-center { background-position: -288px -48px; } .icon-align-right { background-position: -312px -48px; } .icon-align-justify { background-position: -336px -48px; } .icon-list { background-position: -360px -48px; } .icon-indent-left { background-position: -384px -48px; } .icon-indent-right { background-position: -408px -48px; } .icon-facetime-video { background-position: -432px -48px; } .icon-picture { background-position: -456px -48px; } .icon-pencil { background-position: 0 -72px; } .icon-map-marker { background-position: -24px -72px; } .icon-adjust { background-position: -48px -72px; } .icon-tint { background-position: -72px -72px; } .icon-edit { background-position: -96px -72px; } .icon-share { background-position: -120px -72px; } .icon-check { background-position: -144px -72px; } .icon-move { background-position: -168px -72px; } .icon-step-backward { background-position: -192px -72px; } .icon-fast-backward { background-position: -216px -72px; } .icon-backward { background-position: -240px -72px; } .icon-play { background-position: -264px -72px; } .icon-pause { background-position: -288px -72px; } .icon-stop { background-position: -312px -72px; } .icon-forward { background-position: -336px -72px; } .icon-fast-forward { background-position: -360px -72px; } .icon-step-forward { background-position: -384px -72px; } .icon-eject { background-position: -408px -72px; } .icon-chevron-left { background-position: -432px -72px; } .icon-chevron-right { background-position: -456px -72px; } .icon-plus-sign { background-position: 0 -96px; } .icon-minus-sign { background-position: -24px -96px; } .icon-remove-sign { background-position: -48px -96px; } .icon-ok-sign { background-position: -72px -96px; } .icon-question-sign { background-position: -96px -96px; } .icon-info-sign { background-position: -120px -96px; } .icon-screenshot { background-position: -144px -96px; } .icon-remove-circle { background-position: -168px -96px; } .icon-ok-circle { background-position: -192px -96px; } .icon-ban-circle { background-position: -216px -96px; } .icon-arrow-left { background-position: -240px -96px; } .icon-arrow-right { background-position: -264px -96px; } .icon-arrow-up { background-position: -289px -96px; } // 1px off .icon-arrow-down { background-position: -312px -96px; } .icon-share-alt { background-position: -336px -96px; } .icon-resize-full { background-position: -360px -96px; } .icon-resize-small { background-position: -384px -96px; } .icon-plus { background-position: -408px -96px; } .icon-minus { background-position: -433px -96px; } .icon-asterisk { background-position: -456px -96px; } .icon-exclamation-sign { background-position: 0 -120px; } .icon-gift { background-position: -24px -120px; } .icon-leaf { background-position: -48px -120px; } .icon-fire { background-position: -72px -120px; } .icon-eye-open { background-position: -96px -120px; } .icon-eye-close { background-position: -120px -120px; } .icon-warning-sign { background-position: -144px -120px; } .icon-plane { background-position: -168px -120px; } .icon-calendar { background-position: -192px -120px; } .icon-random { background-position: -216px -120px; width: 16px; } .icon-comment { background-position: -240px -120px; } .icon-magnet { background-position: -264px -120px; } .icon-chevron-up { background-position: -288px -120px; } .icon-chevron-down { background-position: -313px -119px; } // 1px, 1px off .icon-retweet { background-position: -336px -120px; } .icon-shopping-cart { background-position: -360px -120px; } .icon-folder-close { background-position: -384px -120px; width: 16px; } .icon-folder-open { background-position: -408px -120px; width: 16px; } .icon-resize-vertical { background-position: -432px -119px; } // 1px, 1px off .icon-resize-horizontal { background-position: -456px -118px; } // 1px, 2px off .icon-hdd { background-position: 0 -144px; } .icon-bullhorn { background-position: -24px -144px; } .icon-bell { background-position: -48px -144px; } .icon-certificate { background-position: -72px -144px; } .icon-thumbs-up { background-position: -96px -144px; } .icon-thumbs-down { background-position: -120px -144px; } .icon-hand-right { background-position: -144px -144px; } .icon-hand-left { background-position: -168px -144px; } .icon-hand-up { background-position: -192px -144px; } .icon-hand-down { background-position: -216px -144px; } .icon-circle-arrow-right { background-position: -240px -144px; } .icon-circle-arrow-left { background-position: -264px -144px; } .icon-circle-arrow-up { background-position: -288px -144px; } .icon-circle-arrow-down { background-position: -312px -144px; } .icon-globe { background-position: -336px -144px; } .icon-wrench { background-position: -360px -144px; } .icon-tasks { background-position: -384px -144px; } .icon-filter { background-position: -408px -144px; } .icon-briefcase { background-position: -432px -144px; } .icon-fullscreen { background-position: -456px -144px; } numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/less/bootstrap/alerts.less0000664000175100017510000000253112370216246031357 0ustar vagrantvagrant00000000000000// // Alerts // -------------------------------------------------- // Base styles // ------------------------- .alert { padding: 8px 35px 8px 14px; margin-bottom: @baseLineHeight; text-shadow: 0 1px 0 rgba(255,255,255,.5); background-color: @warningBackground; border: 1px solid @warningBorder; .border-radius(@baseBorderRadius); } .alert, .alert h4 { // Specified for the h4 to prevent conflicts of changing @headingsColor color: @warningText; } .alert h4 { margin: 0; } // Adjust close link position .alert .close { position: relative; top: -2px; right: -21px; line-height: @baseLineHeight; } // Alternate styles // ------------------------- .alert-success { background-color: @successBackground; border-color: @successBorder; color: @successText; } .alert-success h4 { color: @successText; } .alert-danger, .alert-error { background-color: @errorBackground; border-color: @errorBorder; color: @errorText; } .alert-danger h4, .alert-error h4 { color: @errorText; } .alert-info { background-color: @infoBackground; border-color: @infoBorder; color: @infoText; } .alert-info h4 { color: @infoText; } // Block alerts // ------------------------- .alert-block { padding-top: 14px; padding-bottom: 14px; } .alert-block > p, .alert-block > ul { margin-bottom: 0; } .alert-block p + p { margin-top: 5px; } numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/less/bootstrap/tooltip.less0000664000175100017510000000322412370216246031557 0ustar vagrantvagrant00000000000000// // Tooltips // -------------------------------------------------- // Base class .tooltip { position: absolute; z-index: @zindexTooltip; display: block; visibility: visible; font-size: 11px; line-height: 1.4; .opacity(0); &.in { .opacity(80); } &.top { margin-top: -3px; padding: 5px 0; } &.right { margin-left: 3px; padding: 0 5px; } &.bottom { margin-top: 3px; padding: 5px 0; } &.left { margin-left: -3px; padding: 0 5px; } } // Wrapper for the tooltip content .tooltip-inner { max-width: 200px; padding: 8px; color: @tooltipColor; text-align: center; text-decoration: none; background-color: @tooltipBackground; .border-radius(@baseBorderRadius); } // Arrows .tooltip-arrow { position: absolute; width: 0; height: 0; border-color: transparent; border-style: solid; } .tooltip { &.top .tooltip-arrow { bottom: 0; left: 50%; margin-left: -@tooltipArrowWidth; border-width: @tooltipArrowWidth @tooltipArrowWidth 0; border-top-color: @tooltipArrowColor; } &.right .tooltip-arrow { top: 50%; left: 0; margin-top: -@tooltipArrowWidth; border-width: @tooltipArrowWidth @tooltipArrowWidth @tooltipArrowWidth 0; border-right-color: @tooltipArrowColor; } &.left .tooltip-arrow { top: 50%; right: 0; margin-top: -@tooltipArrowWidth; border-width: @tooltipArrowWidth 0 @tooltipArrowWidth @tooltipArrowWidth; border-left-color: @tooltipArrowColor; } &.bottom .tooltip-arrow { top: 0; left: 50%; margin-left: -@tooltipArrowWidth; border-width: 0 @tooltipArrowWidth @tooltipArrowWidth; border-bottom-color: @tooltipArrowColor; } } numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/less/bootstrap/tables.less0000664000175100017510000001415712370216246031346 0ustar vagrantvagrant00000000000000// // Tables // -------------------------------------------------- // BASE TABLES // ----------------- table { max-width: 100%; background-color: @tableBackground; border-collapse: collapse; border-spacing: 0; } // BASELINE STYLES // --------------- .table { width: 100%; margin-bottom: @baseLineHeight; // Cells th, td { padding: 8px; line-height: @baseLineHeight; text-align: left; vertical-align: top; border-top: 1px solid @tableBorder; } th { font-weight: bold; } // Bottom align for column headings thead th { vertical-align: bottom; } // Remove top border from thead by default caption + thead tr:first-child th, caption + thead tr:first-child td, colgroup + thead tr:first-child th, colgroup + thead tr:first-child td, thead:first-child tr:first-child th, thead:first-child tr:first-child td { border-top: 0; } // Account for multiple tbody instances tbody + tbody { border-top: 2px solid @tableBorder; } // Nesting .table { background-color: @bodyBackground; } } // CONDENSED TABLE W/ HALF PADDING // ------------------------------- .table-condensed { th, td { padding: 4px 5px; } } // BORDERED VERSION // ---------------- .table-bordered { border: 1px solid @tableBorder; border-collapse: separate; // Done so we can round those corners! *border-collapse: collapse; // IE7 can't round corners anyway border-left: 0; .border-radius(@baseBorderRadius); th, td { border-left: 1px solid @tableBorder; } // Prevent a double border caption + thead tr:first-child th, caption + tbody tr:first-child th, caption + tbody tr:first-child td, colgroup + thead tr:first-child th, colgroup + tbody tr:first-child th, colgroup + tbody tr:first-child td, thead:first-child tr:first-child th, tbody:first-child tr:first-child th, tbody:first-child tr:first-child td { border-top: 0; } // For first th/td in the first row in the first thead or tbody thead:first-child tr:first-child > th:first-child, tbody:first-child tr:first-child > td:first-child, tbody:first-child tr:first-child > th:first-child { .border-top-left-radius(@baseBorderRadius); } // For last th/td in the first row in the first thead or tbody thead:first-child tr:first-child > th:last-child, tbody:first-child tr:first-child > td:last-child, tbody:first-child tr:first-child > th:last-child { .border-top-right-radius(@baseBorderRadius); } // For first th/td (can be either) in the last row in the last thead, tbody, and tfoot thead:last-child tr:last-child > th:first-child, tbody:last-child tr:last-child > td:first-child, tbody:last-child tr:last-child > th:first-child, tfoot:last-child tr:last-child > td:first-child, tfoot:last-child tr:last-child > th:first-child { .border-bottom-left-radius(@baseBorderRadius); } // For last th/td (can be either) in the last row in the last thead, tbody, and tfoot thead:last-child tr:last-child > th:last-child, tbody:last-child tr:last-child > td:last-child, tbody:last-child tr:last-child > th:last-child, tfoot:last-child tr:last-child > td:last-child, tfoot:last-child tr:last-child > th:last-child { .border-bottom-right-radius(@baseBorderRadius); } // Clear border-radius for first and last td in the last row in the last tbody for table with tfoot tfoot + tbody:last-child tr:last-child td:first-child { .border-bottom-left-radius(0); } tfoot + tbody:last-child tr:last-child td:last-child { .border-bottom-right-radius(0); } // Special fixes to round the left border on the first td/th caption + thead tr:first-child th:first-child, caption + tbody tr:first-child td:first-child, colgroup + thead tr:first-child th:first-child, colgroup + tbody tr:first-child td:first-child { .border-top-left-radius(@baseBorderRadius); } caption + thead tr:first-child th:last-child, caption + tbody tr:first-child td:last-child, colgroup + thead tr:first-child th:last-child, colgroup + tbody tr:first-child td:last-child { .border-top-right-radius(@baseBorderRadius); } } // ZEBRA-STRIPING // -------------- // Default zebra-stripe styles (alternating gray and transparent backgrounds) .table-striped { tbody { > tr:nth-child(odd) > td, > tr:nth-child(odd) > th { background-color: @tableBackgroundAccent; } } } // HOVER EFFECT // ------------ // Placed here since it has to come after the potential zebra striping .table-hover { tbody { tr:hover > td, tr:hover > th { background-color: @tableBackgroundHover; } } } // TABLE CELL SIZING // ----------------- // Reset default grid behavior table td[class*="span"], table th[class*="span"], .row-fluid table td[class*="span"], .row-fluid table th[class*="span"] { display: table-cell; float: none; // undo default grid column styles margin-left: 0; // undo default grid column styles } // Change the column widths to account for td/th padding .table td, .table th { &.span1 { .tableColumns(1); } &.span2 { .tableColumns(2); } &.span3 { .tableColumns(3); } &.span4 { .tableColumns(4); } &.span5 { .tableColumns(5); } &.span6 { .tableColumns(6); } &.span7 { .tableColumns(7); } &.span8 { .tableColumns(8); } &.span9 { .tableColumns(9); } &.span10 { .tableColumns(10); } &.span11 { .tableColumns(11); } &.span12 { .tableColumns(12); } } // TABLE BACKGROUNDS // ----------------- // Exact selectors below required to override .table-striped .table tbody tr { &.success > td { background-color: @successBackground; } &.error > td { background-color: @errorBackground; } &.warning > td { background-color: @warningBackground; } &.info > td { background-color: @infoBackground; } } // Hover states for .table-hover .table-hover tbody tr { &.success:hover > td { background-color: darken(@successBackground, 5%); } &.error:hover > td { background-color: darken(@errorBackground, 5%); } &.warning:hover > td { background-color: darken(@warningBackground, 5%); } &.info:hover > td { background-color: darken(@infoBackground, 5%); } } numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/less/spc-header.less0000664000175100017510000000067112370216246030066 0ustar vagrantvagrant00000000000000// settings for // 1) .header // header block is found on the top of the website // spc-navbar, spc-header-searchbar found inside .header // 2) .spc-navbar // 3) .spc-header-searchbar @import "spc-utils.less"; .header { .margin(@top: 15px, @bottom: 15px); } .spc-navbar { .margin (@top: 15px, @bottom: 5px); .nav-pills { margin-bottom: 0px; font-size: 12px; >li >a { padding-top: 2.5px; padding-bottom: 2.5px; } } }numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/js/0000775000175100017510000000000012371375427024635 5ustar vagrantvagrant00000000000000numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/static/js/copybutton.js0000664000175100017510000000516412370216246027377 0ustar vagrantvagrant00000000000000// Copyright 2014 PSF. Licensed under the PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2 // File originates from the cpython source found in Doc/tools/sphinxext/static/copybutton.js $(document).ready(function() { /* Add a [>>>] button on the top-right corner of code samples to hide * the >>> and ... prompts and the output and thus make the code * copyable. */ var div = $('.highlight-python .highlight,' + '.highlight-python3 .highlight') var pre = div.find('pre'); // get the styles from the current theme pre.parent().parent().css('position', 'relative'); var hide_text = 'Hide the prompts and output'; var show_text = 'Show the prompts and output'; var border_width = pre.css('border-top-width'); var border_style = pre.css('border-top-style'); var border_color = pre.css('border-top-color'); var button_styles = { 'cursor':'pointer', 'position': 'absolute', 'top': '0', 'right': '0', 'border-color': border_color, 'border-style': border_style, 'border-width': border_width, 'color': border_color, 'text-size': '75%', 'font-family': 'monospace', 'padding-left': '0.2em', 'padding-right': '0.2em', 'border-radius': '0 3px 0 0' } // create and add the button to all the code blocks that contain >>> div.each(function(index) { var jthis = $(this); if (jthis.find('.gp').length > 0) { var button = $('>>>'); button.css(button_styles) button.attr('title', hide_text); jthis.prepend(button); } // tracebacks (.gt) contain bare text elements that need to be // wrapped in a span to work with .nextUntil() (see later) jthis.find('pre:has(.gt)').contents().filter(function() { return ((this.nodeType == 3) && (this.data.trim().length > 0)); }).wrap(''); }); // define the behavior of the button when it's clicked $('.copybutton').toggle( function() { var button = $(this); button.parent().find('.go, .gp, .gt').hide(); button.next('pre').find('.gt').nextUntil('.gp, .go').css('visibility', 'hidden'); button.css('text-decoration', 'line-through'); button.attr('title', show_text); }, function() { var button = $(this); button.parent().find('.go, .gp, .gt').show(); button.next('pre').find('.gt').nextUntil('.gp, .go').css('visibility', 'visible'); button.css('text-decoration', 'none'); button.attr('title', hide_text); }); }); numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/searchbox.html0000664000175100017510000000065112370216245025567 0ustar vagrantvagrant00000000000000{%- if theme_edit_link -%} {% block edit_link %} {%- if sourcename %}
    {%- if 'generated/' in sourcename %} {{_('Edit page')}} {%- else %} {{_('Edit page')}} {%- endif %}
    {%- endif %} {% endblock %} {%- endif -%} numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/sourcelink.html0000664000175100017510000000034012370216245025762 0ustar vagrantvagrant00000000000000{%- if show_source and has_source and sourcename %}

    {{ _('This Page') }}

    {%- endif %} numpy-1.8.2/doc/scipy-sphinx-theme/_theme/scipy/layout.html0000664000175100017510000002070312370216245025126 0ustar vagrantvagrant00000000000000{# scipy/layout.html ~~~~~~~~~~~~~~~~~ Master layout template for Sphinx themes. :copyright: Copyright 2007-2011 by the Sphinx team, see AUTHORS. :license: BSD, see LICENSE for details. #} {%- block doctype -%} {%- endblock %} {%- set url_root = pathto('', 1) %} {%- if url_root == '#' %}{% set url_root = '' %}{% endif %} {%- if not embedded and docstitle %} {%- set titlesuffix = " — "|safe + docstitle|e %} {%- else %} {%- set titlesuffix = "" %} {%- endif %} {%- macro relbar_top() %} {%- endmacro %} {%- macro relbar_top_right() %} {%- endmacro %} {%- macro relbar_bottom() %} {%- endmacro %} {%- macro sidebar() %}
    {%- block sidebarlogo %} {%- if logo %} {%- endif %} {%- endblock %} {%- if sidebars != None %} {#- new style sidebar: explicitly include/exclude templates #} {%- for sidebartemplate in sidebars %} {%- include sidebartemplate %} {%- endfor %} {%- else %} {#- old style sidebars: using blocks -- should be deprecated #} {%- block sidebartoc %} {%- include "localtoc.html" %} {%- endblock %} {%- block sidebarrel %} {%- include "relations.html" %} {%- endblock %} {%- block sidebarsourcelink %} {%- include "sourcelink.html" %} {%- endblock %} {%- if customsidebar %} {%- include customsidebar %} {%- endif %} {%- block sidebarsearch %} {%- include "searchbox.html" %} {%- endblock %} {%- endif %}
    {%- endmacro %} {%- macro script() %} {%- for scriptfile in script_files %} {%- endfor %} {%- endmacro %} {%- macro css() %} {%- for cssfile in css_files %} {%- endfor %} {%- endmacro %} {{ metatags }} {%- block htmltitle %} {{ title|striptags|e }}{{ titlesuffix }} {%- endblock %} {{ css() }} {%- if not embedded %} {{ script() }} {%- if use_opensearch %} {%- endif %} {%- if favicon %} {%- endif %} {%- endif %} {%- block linktags %} {%- if hasdoc('about') %} {%- endif %} {%- if hasdoc('genindex') %} {%- endif %} {%- if hasdoc('search') %} {%- endif %} {%- if hasdoc('copyright') %} {%- endif %} {%- if parents %} {%- endif %} {%- if next %} {%- endif %} {%- if prev %} {%- endif %} {%- endblock %} {%- block extrahead %} {% endblock %} {%- block header %} {% if theme_scipy_org_logo %} {% else %}
    {% endif %} {% endblock %} {%- block content %}
    {%- block navbar %} {% if theme_navigation_links or sidebar == 'left' %}
    {{ relbar_top() }} {% if theme_navigation_links %} {{ relbar_top_right() }} {% endif %}
    {% endif %} {% endblock %}
    {%- if theme_sidebar == 'left' -%} {{ sidebar() }} {%- endif %} {%- if theme_sidebar == 'none' -%}
    {% else %}
    {%- endif %} {% if not theme_navigation_links and sidebar != 'left' %}
    {{ relbar_top() }}
    {% endif %} {%- block document %}
    {% block body %} {% endblock %}
    {%- endblock %}
    {%- if theme_sidebar == 'right' -%} {{ sidebar() }} {%- elif theme_sidebar == 'none' -%}
    {%- endif %}
    {%- endblock %}
    {{ relbar_bottom() }}
    {%- block footer %}
    {%- endblock %} numpy-1.8.2/doc/scipy-sphinx-theme/conf.py0000664000175100017510000000366412370216246021642 0ustar vagrantvagrant00000000000000needs_sphinx = '1.1' extensions = ['sphinx.ext.autodoc', 'sphinx.ext.pngmath', 'numpydoc', 'sphinx.ext.intersphinx', 'sphinx.ext.coverage', 'sphinx.ext.autosummary', 'matplotlib.sphinxext.plot_directive'] templates_path = ['_templates'] source_suffix = '.rst' master_doc = 'index' project = u'scipy-sphinx-theme' copyright = u'2013, Surya Kasturi and Pauli Virtanen' version = '0.1' release = '0.1' exclude_patterns = ['_build'] pygments_style = 'sphinx' # -- Options for HTML output --------------------------------------------------- html_theme = 'scipy' html_theme_path = ['_theme'] #html_logo = '_static/scipyshiny_small.png' html_static_path = ['_static'] html_theme_options = { "edit_link": "true", "sidebar": "right", "scipy_org_logo": "true", "rootlinks": [("http://scipy.org/", "Scipy.org"), ("http://docs.scipy.org/", "Docs")] } pngmath_latex_preamble = r""" \usepackage{color} \definecolor{textgray}{RGB}{51,51,51} \color{textgray} """ pngmath_use_preview = True pngmath_dvipng_args = ['-gamma 1.5', '-D 96', '-bg Transparent'] #------------------------------------------------------------------------------ # Plot style #------------------------------------------------------------------------------ plot_pre_code = """ import numpy as np import scipy as sp np.random.seed(123) """ plot_include_source = True plot_formats = [('png', 96), 'pdf'] plot_html_show_formats = False import math phi = (math.sqrt(5) + 1)/2 font_size = 13*72/96.0 # 13 px plot_rcparams = { 'font.size': font_size, 'axes.titlesize': font_size, 'axes.labelsize': font_size, 'xtick.labelsize': font_size, 'ytick.labelsize': font_size, 'legend.fontsize': font_size, 'figure.figsize': (3*phi, 3), 'figure.subplot.bottom': 0.2, 'figure.subplot.left': 0.2, 'figure.subplot.right': 0.9, 'figure.subplot.top': 0.85, 'figure.subplot.wspace': 0.4, 'text.usetex': False, } numpy-1.8.2/doc/scipy-sphinx-theme/Makefile0000664000175100017510000000417012370216245021773 0ustar vagrantvagrant00000000000000# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = _build # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . # the i18n builder cannot share the environment and doctrees with the others I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext all css all: html css: $(wildcard _theme/scipy/static/css/*.css) _theme/scipy/static/css/%.css: _theme/scipy/static/less/%.less lessc $^ > $@.new mv -f $@.new $@ help: @echo "Please use \`make ' where is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " singlehtml to make a single large HTML file" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " devhelp to make HTML files and a Devhelp project" @echo " epub to make an epub" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " latexpdf to make LaTeX files and run them through pdflatex" @echo " text to make text files" @echo " man to make manual pages" @echo " texinfo to make Texinfo files" @echo " info to make Texinfo files and run them through makeinfo" @echo " gettext to make PO message catalogs" @echo " changes to make an overview of all changed/added/deprecated items" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" clean: -rm -rf $(BUILDDIR)/* html: $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." numpy-1.8.2/doc/swig/0000775000175100017510000000000012371375427015555 5ustar vagrantvagrant00000000000000numpy-1.8.2/doc/swig/test/0000775000175100017510000000000012371375427016534 5ustar vagrantvagrant00000000000000numpy-1.8.2/doc/swig/test/SuperTensor.cxx0000664000175100017510000001251512370216243021542 0ustar vagrantvagrant00000000000000#include #include #include #include "SuperTensor.h" // The following macro defines a family of functions that work with 3D // arrays with the forms // // TYPE SNAMENorm( TYPE supertensor[2][2][2][2]); // TYPE SNAMEMax( TYPE * supertensor, int cubes, int slices, int rows, int cols); // TYPE SNAMEMin( int cubes, int slices, int rows, int cols, TYPE * supertensor); // void SNAMEScale( TYPE supertensor[3][3][3][3]); // void SNAMEFloor( TYPE * array, int cubes, int slices, int rows, int cols, TYPE floor); // void SNAMECeil( int slices, int cubes, int slices, int rows, int cols, TYPE * array, TYPE ceil); // void SNAMELUSplit(TYPE in[2][2][2][2], TYPE lower[2][2][2][2], TYPE upper[2][2][2][2]); // // for any specified type TYPE (for example: short, unsigned int, long // long, etc.) with given short name SNAME (for example: short, uint, // longLong, etc.). The macro is then expanded for the given // TYPE/SNAME pairs. The resulting functions are for testing numpy // interfaces, respectively, for: // // * 4D input arrays, hard-coded length // * 4D input arrays // * 4D input arrays, data last // * 4D in-place arrays, hard-coded lengths // * 4D in-place arrays // * 4D in-place arrays, data last // * 4D argout arrays, hard-coded length // #define TEST_FUNCS(TYPE, SNAME) \ \ TYPE SNAME ## Norm(TYPE supertensor[2][2][2][2]) { \ double result = 0; \ for (int l=0; l<2; ++l) \ for (int k=0; k<2; ++k) \ for (int j=0; j<2; ++j) \ for (int i=0; i<2; ++i) \ result += supertensor[l][k][j][i] * supertensor[l][k][j][i]; \ return (TYPE)sqrt(result/16); \ } \ \ TYPE SNAME ## Max(TYPE * supertensor, int cubes, int slices, int rows, int cols) { \ int i, j, k, l, index; \ TYPE result = supertensor[0]; \ for (l=0; l result) result = supertensor[index]; \ } \ } \ } \ } \ return result; \ } \ \ TYPE SNAME ## Min(int cubes, int slices, int rows, int cols, TYPE * supertensor) { \ int i, j, k, l, index; \ TYPE result = supertensor[0]; \ for (l=0; l ceil) array[index] = ceil; \ } \ } \ } \ } \ } \ \ void SNAME ## LUSplit(TYPE supertensor[2][2][2][2], TYPE lower[2][2][2][2], \ TYPE upper[2][2][2][2]) { \ int sum; \ for (int l=0; l<2; ++l) { \ for (int k=0; k<2; ++k) { \ for (int j=0; j<2; ++j) { \ for (int i=0; i<2; ++i) { \ sum = i + j + k + l; \ if (sum < 2) { \ lower[l][k][j][i] = supertensor[l][k][j][i]; \ upper[l][k][j][i] = 0; \ } else { \ upper[l][k][j][i] = supertensor[l][k][j][i]; \ lower[l][k][j][i] = 0; \ } \ } \ } \ } \ } \ } TEST_FUNCS(signed char , schar ) TEST_FUNCS(unsigned char , uchar ) TEST_FUNCS(short , short ) TEST_FUNCS(unsigned short , ushort ) TEST_FUNCS(int , int ) TEST_FUNCS(unsigned int , uint ) TEST_FUNCS(long , long ) TEST_FUNCS(unsigned long , ulong ) TEST_FUNCS(long long , longLong ) TEST_FUNCS(unsigned long long, ulongLong) TEST_FUNCS(float , float ) TEST_FUNCS(double , double ) numpy-1.8.2/doc/swig/test/Farray.i0000664000175100017510000000242312370216243020120 0ustar vagrantvagrant00000000000000// -*- c++ -*- %module Farray %{ #define SWIG_FILE_WITH_INIT #include "Farray.h" %} // Get the NumPy typemaps %include "../numpy.i" // Get the STL typemaps %include "stl.i" // Handle standard exceptions %include "exception.i" %exception { try { $action } catch (const std::invalid_argument& e) { SWIG_exception(SWIG_ValueError, e.what()); } catch (const std::out_of_range& e) { SWIG_exception(SWIG_IndexError, e.what()); } } %init %{ import_array(); %} // Global ignores %ignore *::operator=; %ignore *::operator(); // Apply the 2D NumPy typemaps %apply (int* DIM1 , int* DIM2 , long** ARGOUTVIEW_FARRAY2) {(int* nrows, int* ncols, long** data )}; // Farray support %include "Farray.h" %extend Farray { PyObject * __setitem__(PyObject* index, long v) { int i, j; if (!PyArg_ParseTuple(index, "ii:Farray___setitem__",&i,&j)) return NULL; self->operator()(i,j) = v; return Py_BuildValue(""); } PyObject * __getitem__(PyObject * index) { int i, j; if (!PyArg_ParseTuple(index, "ii:Farray___getitem__",&i,&j)) return NULL; return SWIG_From_long(self->operator()(i,j)); } int __len__() { return self->nrows() * self->ncols(); } std::string __str__() { return self->asString(); } } numpy-1.8.2/doc/swig/test/Matrix.i0000664000175100017510000000257212370216243020145 0ustar vagrantvagrant00000000000000// -*- c++ -*- %module Matrix %{ #define SWIG_FILE_WITH_INIT #include "Matrix.h" %} // Get the NumPy typemaps %include "../numpy.i" %init %{ import_array(); %} %define %apply_numpy_typemaps(TYPE) %apply (TYPE IN_ARRAY2[ANY][ANY]) {(TYPE matrix[ANY][ANY])}; %apply (TYPE* IN_ARRAY2, int DIM1, int DIM2) {(TYPE* matrix, int rows, int cols)}; %apply (int DIM1, int DIM2, TYPE* IN_ARRAY2) {(int rows, int cols, TYPE* matrix)}; %apply (TYPE INPLACE_ARRAY2[ANY][ANY]) {(TYPE array[3][3])}; %apply (TYPE* INPLACE_ARRAY2, int DIM1, int DIM2) {(TYPE* array, int rows, int cols)}; %apply (int DIM1, int DIM2, TYPE* INPLACE_ARRAY2) {(int rows, int cols, TYPE* array)}; %apply (TYPE ARGOUT_ARRAY2[ANY][ANY]) {(TYPE lower[3][3])}; %apply (TYPE ARGOUT_ARRAY2[ANY][ANY]) {(TYPE upper[3][3])}; %enddef /* %apply_numpy_typemaps() macro */ %apply_numpy_typemaps(signed char ) %apply_numpy_typemaps(unsigned char ) %apply_numpy_typemaps(short ) %apply_numpy_typemaps(unsigned short ) %apply_numpy_typemaps(int ) %apply_numpy_typemaps(unsigned int ) %apply_numpy_typemaps(long ) %apply_numpy_typemaps(unsigned long ) %apply_numpy_typemaps(long long ) %apply_numpy_typemaps(unsigned long long) %apply_numpy_typemaps(float ) %apply_numpy_typemaps(double ) // Include the header file to be wrapped %include "Matrix.h" numpy-1.8.2/doc/swig/test/Farray.h0000664000175100017510000000161212370216243020116 0ustar vagrantvagrant00000000000000#ifndef FARRAY_H #define FARRAY_H #include #include class Farray { public: // Size constructor Farray(int nrows, int ncols); // Copy constructor Farray(const Farray & source); // Destructor ~Farray(); // Assignment operator Farray & operator=(const Farray & source); // Equals operator bool operator==(const Farray & other) const; // Length accessors int nrows() const; int ncols() const; // Set item accessor long & operator()(int i, int j); // Get item accessor const long & operator()(int i, int j) const; // String output std::string asString() const; // Get view void view(int* nrows, int* ncols, long** data) const; private: // Members int _nrows; int _ncols; long * _buffer; // Default constructor: not implemented Farray(); // Methods void allocateMemory(); int offset(int i, int j) const; }; #endif numpy-1.8.2/doc/swig/test/testSuperTensor.py0000664000175100017510000004016012370216243022265 0ustar vagrantvagrant00000000000000#! /usr/bin/env python from __future__ import division # System imports from distutils.util import get_platform from math import sqrt import os import sys import unittest # Import NumPy import numpy as np major, minor = [ int(d) for d in np.__version__.split(".")[:2] ] if major == 0: BadListError = TypeError else: BadListError = ValueError import SuperTensor ###################################################################### class SuperTensorTestCase(unittest.TestCase): def __init__(self, methodName="runTests"): unittest.TestCase.__init__(self, methodName) self.typeStr = "double" self.typeCode = "d" # Test (type IN_ARRAY3[ANY][ANY][ANY]) typemap def testNorm(self): "Test norm function" print >>sys.stderr, self.typeStr, "... ", norm = SuperTensor.__dict__[self.typeStr + "Norm"] supertensor = np.arange(2*2*2*2, dtype=self.typeCode).reshape((2, 2, 2, 2)) #Note: cludge to get an answer of the same type as supertensor. #Answer is simply sqrt(sum(supertensor*supertensor)/16) answer = np.array([np.sqrt(np.sum(supertensor.astype('d')*supertensor)/16.)], dtype=self.typeCode)[0] self.assertAlmostEqual(norm(supertensor), answer, 6) # Test (type IN_ARRAY3[ANY][ANY][ANY]) typemap def testNormBadList(self): "Test norm function with bad list" print >>sys.stderr, self.typeStr, "... ", norm = SuperTensor.__dict__[self.typeStr + "Norm"] supertensor = [[[[0, "one"], [2, 3]], [[3, "two"], [1, 0]]], [[[0, "one"], [2, 3]], [[3, "two"], [1, 0]]]] self.assertRaises(BadListError, norm, supertensor) # Test (type IN_ARRAY3[ANY][ANY][ANY]) typemap def testNormWrongDim(self): "Test norm function with wrong dimensions" print >>sys.stderr, self.typeStr, "... ", norm = SuperTensor.__dict__[self.typeStr + "Norm"] supertensor = np.arange(2*2*2, dtype=self.typeCode).reshape((2, 2, 2)) self.assertRaises(TypeError, norm, supertensor) # Test (type IN_ARRAY3[ANY][ANY][ANY]) typemap def testNormWrongSize(self): "Test norm function with wrong size" print >>sys.stderr, self.typeStr, "... ", norm = SuperTensor.__dict__[self.typeStr + "Norm"] supertensor = np.arange(3*2*2, dtype=self.typeCode).reshape((3, 2, 2)) self.assertRaises(TypeError, norm, supertensor) # Test (type IN_ARRAY3[ANY][ANY][ANY]) typemap def testNormNonContainer(self): "Test norm function with non-container" print >>sys.stderr, self.typeStr, "... ", norm = SuperTensor.__dict__[self.typeStr + "Norm"] self.assertRaises(TypeError, norm, None) # Test (type* IN_ARRAY3, int DIM1, int DIM2, int DIM3) typemap def testMax(self): "Test max function" print >>sys.stderr, self.typeStr, "... ", max = SuperTensor.__dict__[self.typeStr + "Max"] supertensor = [[[[1, 2], [3, 4]], [[5, 6], [7, 8]]], [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]] self.assertEquals(max(supertensor), 8) # Test (type* IN_ARRAY3, int DIM1, int DIM2, int DIM3) typemap def testMaxBadList(self): "Test max function with bad list" print >>sys.stderr, self.typeStr, "... ", max = SuperTensor.__dict__[self.typeStr + "Max"] supertensor = [[[[1, "two"], [3, 4]], [[5, "six"], [7, 8]]], [[[1, "two"], [3, 4]], [[5, "six"], [7, 8]]]] self.assertRaises(BadListError, max, supertensor) # Test (type* IN_ARRAY3, int DIM1, int DIM2, int DIM3) typemap def testMaxNonContainer(self): "Test max function with non-container" print >>sys.stderr, self.typeStr, "... ", max = SuperTensor.__dict__[self.typeStr + "Max"] self.assertRaises(TypeError, max, None) # Test (type* IN_ARRAY3, int DIM1, int DIM2, int DIM3) typemap def testMaxWrongDim(self): "Test max function with wrong dimensions" print >>sys.stderr, self.typeStr, "... ", max = SuperTensor.__dict__[self.typeStr + "Max"] self.assertRaises(TypeError, max, [0, -1, 2, -3]) # Test (int DIM1, int DIM2, int DIM3, type* IN_ARRAY3) typemap def testMin(self): "Test min function" print >>sys.stderr, self.typeStr, "... ", min = SuperTensor.__dict__[self.typeStr + "Min"] supertensor = [[[[9, 8], [7, 6]], [[5, 4], [3, 2]]], [[[9, 8], [7, 6]], [[5, 4], [3, 2]]]] self.assertEquals(min(supertensor), 2) # Test (int DIM1, int DIM2, int DIM3, type* IN_ARRAY3) typemap def testMinBadList(self): "Test min function with bad list" print >>sys.stderr, self.typeStr, "... ", min = SuperTensor.__dict__[self.typeStr + "Min"] supertensor = [[[["nine", 8], [7, 6]], [["five", 4], [3, 2]]], [[["nine", 8], [7, 6]], [["five", 4], [3, 2]]]] self.assertRaises(BadListError, min, supertensor) # Test (int DIM1, int DIM2, int DIM3, type* IN_ARRAY3) typemap def testMinNonContainer(self): "Test min function with non-container" print >>sys.stderr, self.typeStr, "... ", min = SuperTensor.__dict__[self.typeStr + "Min"] self.assertRaises(TypeError, min, True) # Test (int DIM1, int DIM2, int DIM3, type* IN_ARRAY3) typemap def testMinWrongDim(self): "Test min function with wrong dimensions" print >>sys.stderr, self.typeStr, "... ", min = SuperTensor.__dict__[self.typeStr + "Min"] self.assertRaises(TypeError, min, [[1, 3], [5, 7]]) # Test (type INPLACE_ARRAY3[ANY][ANY][ANY]) typemap def testScale(self): "Test scale function" print >>sys.stderr, self.typeStr, "... ", scale = SuperTensor.__dict__[self.typeStr + "Scale"] supertensor = np.arange(3*3*3*3, dtype=self.typeCode).reshape((3, 3, 3, 3)) answer = supertensor.copy()*4 scale(supertensor, 4) self.assertEquals((supertensor == answer).all(), True) # Test (type INPLACE_ARRAY3[ANY][ANY][ANY]) typemap def testScaleWrongType(self): "Test scale function with wrong type" print >>sys.stderr, self.typeStr, "... ", scale = SuperTensor.__dict__[self.typeStr + "Scale"] supertensor = np.array([[[1, 0, 1], [0, 1, 0], [1, 0, 1]], [[0, 1, 0], [1, 0, 1], [0, 1, 0]], [[1, 0, 1], [0, 1, 0], [1, 0, 1]]], 'c') self.assertRaises(TypeError, scale, supertensor) # Test (type INPLACE_ARRAY3[ANY][ANY][ANY]) typemap def testScaleWrongDim(self): "Test scale function with wrong dimensions" print >>sys.stderr, self.typeStr, "... ", scale = SuperTensor.__dict__[self.typeStr + "Scale"] supertensor = np.array([[1, 0, 1], [0, 1, 0], [1, 0, 1], [0, 1, 0], [1, 0, 1], [0, 1, 0]], self.typeCode) self.assertRaises(TypeError, scale, supertensor) # Test (type INPLACE_ARRAY3[ANY][ANY][ANY]) typemap def testScaleWrongSize(self): "Test scale function with wrong size" print >>sys.stderr, self.typeStr, "... ", scale = SuperTensor.__dict__[self.typeStr + "Scale"] supertensor = np.array([[[1, 0], [0, 1], [1, 0]], [[0, 1], [1, 0], [0, 1]], [[1, 0], [0, 1], [1, 0]]], self.typeCode) self.assertRaises(TypeError, scale, supertensor) # Test (type INPLACE_ARRAY3[ANY][ANY][ANY]) typemap def testScaleNonArray(self): "Test scale function with non-array" print >>sys.stderr, self.typeStr, "... ", scale = SuperTensor.__dict__[self.typeStr + "Scale"] self.assertRaises(TypeError, scale, True) # Test (type* INPLACE_ARRAY3, int DIM1, int DIM2, int DIM3) typemap def testFloor(self): "Test floor function" print >>sys.stderr, self.typeStr, "... ", supertensor = np.arange(2*2*2*2, dtype=self.typeCode).reshape((2, 2, 2, 2)) answer = supertensor.copy() answer[answer < 4] = 4 floor = SuperTensor.__dict__[self.typeStr + "Floor"] floor(supertensor, 4) np.testing.assert_array_equal(supertensor, answer) # Test (type* INPLACE_ARRAY3, int DIM1, int DIM2, int DIM3) typemap def testFloorWrongType(self): "Test floor function with wrong type" print >>sys.stderr, self.typeStr, "... ", floor = SuperTensor.__dict__[self.typeStr + "Floor"] supertensor = np.ones(2*2*2*2, dtype='c').reshape((2, 2, 2, 2)) self.assertRaises(TypeError, floor, supertensor) # Test (type* INPLACE_ARRAY3, int DIM1, int DIM2, int DIM3) typemap def testFloorWrongDim(self): "Test floor function with wrong type" print >>sys.stderr, self.typeStr, "... ", floor = SuperTensor.__dict__[self.typeStr + "Floor"] supertensor = np.arange(2*2*2, dtype=self.typeCode).reshape((2, 2, 2)) self.assertRaises(TypeError, floor, supertensor) # Test (type* INPLACE_ARRAY3, int DIM1, int DIM2, int DIM3) typemap def testFloorNonArray(self): "Test floor function with non-array" print >>sys.stderr, self.typeStr, "... ", floor = SuperTensor.__dict__[self.typeStr + "Floor"] self.assertRaises(TypeError, floor, object) # Test (int DIM1, int DIM2, int DIM3, type* INPLACE_ARRAY3) typemap def testCeil(self): "Test ceil function" print >>sys.stderr, self.typeStr, "... ", supertensor = np.arange(2*2*2*2, dtype=self.typeCode).reshape((2, 2, 2, 2)) answer = supertensor.copy() answer[answer > 5] = 5 ceil = SuperTensor.__dict__[self.typeStr + "Ceil"] ceil(supertensor, 5) np.testing.assert_array_equal(supertensor, answer) # Test (int DIM1, int DIM2, int DIM3, type* INPLACE_ARRAY3) typemap def testCeilWrongType(self): "Test ceil function with wrong type" print >>sys.stderr, self.typeStr, "... ", ceil = SuperTensor.__dict__[self.typeStr + "Ceil"] supertensor = np.ones(2*2*2*2, 'c').reshape((2, 2, 2, 2)) self.assertRaises(TypeError, ceil, supertensor) # Test (int DIM1, int DIM2, int DIM3, type* INPLACE_ARRAY3) typemap def testCeilWrongDim(self): "Test ceil function with wrong dimensions" print >>sys.stderr, self.typeStr, "... ", ceil = SuperTensor.__dict__[self.typeStr + "Ceil"] supertensor = np.arange(2*2*2, dtype=self.typeCode).reshape((2, 2, 2)) self.assertRaises(TypeError, ceil, supertensor) # Test (int DIM1, int DIM2, int DIM3, type* INPLACE_ARRAY3) typemap def testCeilNonArray(self): "Test ceil function with non-array" print >>sys.stderr, self.typeStr, "... ", ceil = SuperTensor.__dict__[self.typeStr + "Ceil"] supertensor = np.arange(2*2*2*2, dtype=self.typeCode).reshape((2, 2, 2, 2)).tolist() self.assertRaises(TypeError, ceil, supertensor) # Test (type ARGOUT_ARRAY3[ANY][ANY][ANY]) typemap def testLUSplit(self): "Test luSplit function" print >>sys.stderr, self.typeStr, "... ", luSplit = SuperTensor.__dict__[self.typeStr + "LUSplit"] supertensor = np.ones(2*2*2*2, dtype=self.typeCode).reshape((2, 2, 2, 2)) answer_upper = [[[[0, 0], [0, 1]], [[0, 1], [1, 1]]], [[[0, 1], [1, 1]], [[1, 1], [1, 1]]]] answer_lower = [[[[1, 1], [1, 0]], [[1, 0], [0, 0]]], [[[1, 0], [0, 0]], [[0, 0], [0, 0]]]] lower, upper = luSplit(supertensor) self.assertEquals((lower == answer_lower).all(), True) self.assertEquals((upper == answer_upper).all(), True) ###################################################################### class scharTestCase(SuperTensorTestCase): def __init__(self, methodName="runTest"): SuperTensorTestCase.__init__(self, methodName) self.typeStr = "schar" self.typeCode = "b" #self.result = int(self.result) ###################################################################### class ucharTestCase(SuperTensorTestCase): def __init__(self, methodName="runTest"): SuperTensorTestCase.__init__(self, methodName) self.typeStr = "uchar" self.typeCode = "B" #self.result = int(self.result) ###################################################################### class shortTestCase(SuperTensorTestCase): def __init__(self, methodName="runTest"): SuperTensorTestCase.__init__(self, methodName) self.typeStr = "short" self.typeCode = "h" #self.result = int(self.result) ###################################################################### class ushortTestCase(SuperTensorTestCase): def __init__(self, methodName="runTest"): SuperTensorTestCase.__init__(self, methodName) self.typeStr = "ushort" self.typeCode = "H" #self.result = int(self.result) ###################################################################### class intTestCase(SuperTensorTestCase): def __init__(self, methodName="runTest"): SuperTensorTestCase.__init__(self, methodName) self.typeStr = "int" self.typeCode = "i" #self.result = int(self.result) ###################################################################### class uintTestCase(SuperTensorTestCase): def __init__(self, methodName="runTest"): SuperTensorTestCase.__init__(self, methodName) self.typeStr = "uint" self.typeCode = "I" #self.result = int(self.result) ###################################################################### class longTestCase(SuperTensorTestCase): def __init__(self, methodName="runTest"): SuperTensorTestCase.__init__(self, methodName) self.typeStr = "long" self.typeCode = "l" #self.result = int(self.result) ###################################################################### class ulongTestCase(SuperTensorTestCase): def __init__(self, methodName="runTest"): SuperTensorTestCase.__init__(self, methodName) self.typeStr = "ulong" self.typeCode = "L" #self.result = int(self.result) ###################################################################### class longLongTestCase(SuperTensorTestCase): def __init__(self, methodName="runTest"): SuperTensorTestCase.__init__(self, methodName) self.typeStr = "longLong" self.typeCode = "q" #self.result = int(self.result) ###################################################################### class ulongLongTestCase(SuperTensorTestCase): def __init__(self, methodName="runTest"): SuperTensorTestCase.__init__(self, methodName) self.typeStr = "ulongLong" self.typeCode = "Q" #self.result = int(self.result) ###################################################################### class floatTestCase(SuperTensorTestCase): def __init__(self, methodName="runTest"): SuperTensorTestCase.__init__(self, methodName) self.typeStr = "float" self.typeCode = "f" ###################################################################### class doubleTestCase(SuperTensorTestCase): def __init__(self, methodName="runTest"): SuperTensorTestCase.__init__(self, methodName) self.typeStr = "double" self.typeCode = "d" ###################################################################### if __name__ == "__main__": # Build the test suite suite = unittest.TestSuite() suite.addTest(unittest.makeSuite( scharTestCase)) suite.addTest(unittest.makeSuite( ucharTestCase)) suite.addTest(unittest.makeSuite( shortTestCase)) suite.addTest(unittest.makeSuite( ushortTestCase)) suite.addTest(unittest.makeSuite( intTestCase)) suite.addTest(unittest.makeSuite( uintTestCase)) suite.addTest(unittest.makeSuite( longTestCase)) suite.addTest(unittest.makeSuite( ulongTestCase)) suite.addTest(unittest.makeSuite( longLongTestCase)) suite.addTest(unittest.makeSuite(ulongLongTestCase)) suite.addTest(unittest.makeSuite( floatTestCase)) suite.addTest(unittest.makeSuite( doubleTestCase)) # Execute the test suite print "Testing 4D Functions of Module SuperTensor" print "NumPy version", np.__version__ print result = unittest.TextTestRunner(verbosity=2).run(suite) sys.exit(len(result.errors) + len(result.failures)) numpy-1.8.2/doc/swig/test/testMatrix.py0000775000175100017510000003375112370216243021253 0ustar vagrantvagrant00000000000000#! /usr/bin/env python from __future__ import division, absolute_import, print_function # System imports from distutils.util import get_platform import os import sys import unittest # Import NumPy import numpy as np major, minor = [ int(d) for d in np.__version__.split(".")[:2] ] if major == 0: BadListError = TypeError else: BadListError = ValueError import Matrix ###################################################################### class MatrixTestCase(unittest.TestCase): def __init__(self, methodName="runTests"): unittest.TestCase.__init__(self, methodName) self.typeStr = "double" self.typeCode = "d" # Test (type IN_ARRAY2[ANY][ANY]) typemap def testDet(self): "Test det function" print(self.typeStr, "... ", end=' ', file=sys.stderr) det = Matrix.__dict__[self.typeStr + "Det"] matrix = [[8, 7], [6, 9]] self.assertEquals(det(matrix), 30) # Test (type IN_ARRAY2[ANY][ANY]) typemap def testDetBadList(self): "Test det function with bad list" print(self.typeStr, "... ", end=' ', file=sys.stderr) det = Matrix.__dict__[self.typeStr + "Det"] matrix = [[8, 7], ["e", "pi"]] self.assertRaises(BadListError, det, matrix) # Test (type IN_ARRAY2[ANY][ANY]) typemap def testDetWrongDim(self): "Test det function with wrong dimensions" print(self.typeStr, "... ", end=' ', file=sys.stderr) det = Matrix.__dict__[self.typeStr + "Det"] matrix = [8, 7] self.assertRaises(TypeError, det, matrix) # Test (type IN_ARRAY2[ANY][ANY]) typemap def testDetWrongSize(self): "Test det function with wrong size" print(self.typeStr, "... ", end=' ', file=sys.stderr) det = Matrix.__dict__[self.typeStr + "Det"] matrix = [[8, 7, 6], [5, 4, 3], [2, 1, 0]] self.assertRaises(TypeError, det, matrix) # Test (type IN_ARRAY2[ANY][ANY]) typemap def testDetNonContainer(self): "Test det function with non-container" print(self.typeStr, "... ", end=' ', file=sys.stderr) det = Matrix.__dict__[self.typeStr + "Det"] self.assertRaises(TypeError, det, None) # Test (type* IN_ARRAY2, int DIM1, int DIM2) typemap def testMax(self): "Test max function" print(self.typeStr, "... ", end=' ', file=sys.stderr) max = Matrix.__dict__[self.typeStr + "Max"] matrix = [[6, 5, 4], [3, 2, 1]] self.assertEquals(max(matrix), 6) # Test (type* IN_ARRAY2, int DIM1, int DIM2) typemap def testMaxBadList(self): "Test max function with bad list" print(self.typeStr, "... ", end=' ', file=sys.stderr) max = Matrix.__dict__[self.typeStr + "Max"] matrix = [[6, "five", 4], ["three", 2, "one"]] self.assertRaises(BadListError, max, matrix) # Test (type* IN_ARRAY2, int DIM1, int DIM2) typemap def testMaxNonContainer(self): "Test max function with non-container" print(self.typeStr, "... ", end=' ', file=sys.stderr) max = Matrix.__dict__[self.typeStr + "Max"] self.assertRaises(TypeError, max, None) # Test (type* IN_ARRAY2, int DIM1, int DIM2) typemap def testMaxWrongDim(self): "Test max function with wrong dimensions" print(self.typeStr, "... ", end=' ', file=sys.stderr) max = Matrix.__dict__[self.typeStr + "Max"] self.assertRaises(TypeError, max, [0, 1, 2, 3]) # Test (int DIM1, int DIM2, type* IN_ARRAY2) typemap def testMin(self): "Test min function" print(self.typeStr, "... ", end=' ', file=sys.stderr) min = Matrix.__dict__[self.typeStr + "Min"] matrix = [[9, 8], [7, 6], [5, 4]] self.assertEquals(min(matrix), 4) # Test (int DIM1, int DIM2, type* IN_ARRAY2) typemap def testMinBadList(self): "Test min function with bad list" print(self.typeStr, "... ", end=' ', file=sys.stderr) min = Matrix.__dict__[self.typeStr + "Min"] matrix = [["nine", "eight"], ["seven", "six"]] self.assertRaises(BadListError, min, matrix) # Test (int DIM1, int DIM2, type* IN_ARRAY2) typemap def testMinWrongDim(self): "Test min function with wrong dimensions" print(self.typeStr, "... ", end=' ', file=sys.stderr) min = Matrix.__dict__[self.typeStr + "Min"] self.assertRaises(TypeError, min, [1, 3, 5, 7, 9]) # Test (int DIM1, int DIM2, type* IN_ARRAY2) typemap def testMinNonContainer(self): "Test min function with non-container" print(self.typeStr, "... ", end=' ', file=sys.stderr) min = Matrix.__dict__[self.typeStr + "Min"] self.assertRaises(TypeError, min, False) # Test (type INPLACE_ARRAY2[ANY][ANY]) typemap def testScale(self): "Test scale function" print(self.typeStr, "... ", end=' ', file=sys.stderr) scale = Matrix.__dict__[self.typeStr + "Scale"] matrix = np.array([[1, 2, 3], [2, 1, 2], [3, 2, 1]], self.typeCode) scale(matrix, 4) self.assertEquals((matrix == [[4, 8, 12], [8, 4, 8], [12, 8, 4]]).all(), True) # Test (type INPLACE_ARRAY2[ANY][ANY]) typemap def testScaleWrongDim(self): "Test scale function with wrong dimensions" print(self.typeStr, "... ", end=' ', file=sys.stderr) scale = Matrix.__dict__[self.typeStr + "Scale"] matrix = np.array([1, 2, 2, 1], self.typeCode) self.assertRaises(TypeError, scale, matrix) # Test (type INPLACE_ARRAY2[ANY][ANY]) typemap def testScaleWrongSize(self): "Test scale function with wrong size" print(self.typeStr, "... ", end=' ', file=sys.stderr) scale = Matrix.__dict__[self.typeStr + "Scale"] matrix = np.array([[1, 2], [2, 1]], self.typeCode) self.assertRaises(TypeError, scale, matrix) # Test (type INPLACE_ARRAY2[ANY][ANY]) typemap def testScaleWrongType(self): "Test scale function with wrong type" print(self.typeStr, "... ", end=' ', file=sys.stderr) scale = Matrix.__dict__[self.typeStr + "Scale"] matrix = np.array([[1, 2, 3], [2, 1, 2], [3, 2, 1]], 'c') self.assertRaises(TypeError, scale, matrix) # Test (type INPLACE_ARRAY2[ANY][ANY]) typemap def testScaleNonArray(self): "Test scale function with non-array" print(self.typeStr, "... ", end=' ', file=sys.stderr) scale = Matrix.__dict__[self.typeStr + "Scale"] matrix = [[1, 2, 3], [2, 1, 2], [3, 2, 1]] self.assertRaises(TypeError, scale, matrix) # Test (type* INPLACE_ARRAY2, int DIM1, int DIM2) typemap def testFloor(self): "Test floor function" print(self.typeStr, "... ", end=' ', file=sys.stderr) floor = Matrix.__dict__[self.typeStr + "Floor"] matrix = np.array([[6, 7], [8, 9]], self.typeCode) floor(matrix, 7) np.testing.assert_array_equal(matrix, np.array([[7, 7], [8, 9]])) # Test (type* INPLACE_ARRAY2, int DIM1, int DIM2) typemap def testFloorWrongDim(self): "Test floor function with wrong dimensions" print(self.typeStr, "... ", end=' ', file=sys.stderr) floor = Matrix.__dict__[self.typeStr + "Floor"] matrix = np.array([6, 7, 8, 9], self.typeCode) self.assertRaises(TypeError, floor, matrix) # Test (type* INPLACE_ARRAY2, int DIM1, int DIM2) typemap def testFloorWrongType(self): "Test floor function with wrong type" print(self.typeStr, "... ", end=' ', file=sys.stderr) floor = Matrix.__dict__[self.typeStr + "Floor"] matrix = np.array([[6, 7], [8, 9]], 'c') self.assertRaises(TypeError, floor, matrix) # Test (type* INPLACE_ARRAY2, int DIM1, int DIM2) typemap def testFloorNonArray(self): "Test floor function with non-array" print(self.typeStr, "... ", end=' ', file=sys.stderr) floor = Matrix.__dict__[self.typeStr + "Floor"] matrix = [[6, 7], [8, 9]] self.assertRaises(TypeError, floor, matrix) # Test (int DIM1, int DIM2, type* INPLACE_ARRAY2) typemap def testCeil(self): "Test ceil function" print(self.typeStr, "... ", end=' ', file=sys.stderr) ceil = Matrix.__dict__[self.typeStr + "Ceil"] matrix = np.array([[1, 2], [3, 4]], self.typeCode) ceil(matrix, 3) np.testing.assert_array_equal(matrix, np.array([[1, 2], [3, 3]])) # Test (int DIM1, int DIM2, type* INPLACE_ARRAY2) typemap def testCeilWrongDim(self): "Test ceil function with wrong dimensions" print(self.typeStr, "... ", end=' ', file=sys.stderr) ceil = Matrix.__dict__[self.typeStr + "Ceil"] matrix = np.array([1, 2, 3, 4], self.typeCode) self.assertRaises(TypeError, ceil, matrix) # Test (int DIM1, int DIM2, type* INPLACE_ARRAY2) typemap def testCeilWrongType(self): "Test ceil function with wrong dimensions" print(self.typeStr, "... ", end=' ', file=sys.stderr) ceil = Matrix.__dict__[self.typeStr + "Ceil"] matrix = np.array([[1, 2], [3, 4]], 'c') self.assertRaises(TypeError, ceil, matrix) # Test (int DIM1, int DIM2, type* INPLACE_ARRAY2) typemap def testCeilNonArray(self): "Test ceil function with non-array" print(self.typeStr, "... ", end=' ', file=sys.stderr) ceil = Matrix.__dict__[self.typeStr + "Ceil"] matrix = [[1, 2], [3, 4]] self.assertRaises(TypeError, ceil, matrix) # Test (type ARGOUT_ARRAY2[ANY][ANY]) typemap def testLUSplit(self): "Test luSplit function" print(self.typeStr, "... ", end=' ', file=sys.stderr) luSplit = Matrix.__dict__[self.typeStr + "LUSplit"] lower, upper = luSplit([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) self.assertEquals((lower == [[1, 0, 0], [4, 5, 0], [7, 8, 9]]).all(), True) self.assertEquals((upper == [[0, 2, 3], [0, 0, 6], [0, 0, 0]]).all(), True) ###################################################################### class scharTestCase(MatrixTestCase): def __init__(self, methodName="runTest"): MatrixTestCase.__init__(self, methodName) self.typeStr = "schar" self.typeCode = "b" ###################################################################### class ucharTestCase(MatrixTestCase): def __init__(self, methodName="runTest"): MatrixTestCase.__init__(self, methodName) self.typeStr = "uchar" self.typeCode = "B" ###################################################################### class shortTestCase(MatrixTestCase): def __init__(self, methodName="runTest"): MatrixTestCase.__init__(self, methodName) self.typeStr = "short" self.typeCode = "h" ###################################################################### class ushortTestCase(MatrixTestCase): def __init__(self, methodName="runTest"): MatrixTestCase.__init__(self, methodName) self.typeStr = "ushort" self.typeCode = "H" ###################################################################### class intTestCase(MatrixTestCase): def __init__(self, methodName="runTest"): MatrixTestCase.__init__(self, methodName) self.typeStr = "int" self.typeCode = "i" ###################################################################### class uintTestCase(MatrixTestCase): def __init__(self, methodName="runTest"): MatrixTestCase.__init__(self, methodName) self.typeStr = "uint" self.typeCode = "I" ###################################################################### class longTestCase(MatrixTestCase): def __init__(self, methodName="runTest"): MatrixTestCase.__init__(self, methodName) self.typeStr = "long" self.typeCode = "l" ###################################################################### class ulongTestCase(MatrixTestCase): def __init__(self, methodName="runTest"): MatrixTestCase.__init__(self, methodName) self.typeStr = "ulong" self.typeCode = "L" ###################################################################### class longLongTestCase(MatrixTestCase): def __init__(self, methodName="runTest"): MatrixTestCase.__init__(self, methodName) self.typeStr = "longLong" self.typeCode = "q" ###################################################################### class ulongLongTestCase(MatrixTestCase): def __init__(self, methodName="runTest"): MatrixTestCase.__init__(self, methodName) self.typeStr = "ulongLong" self.typeCode = "Q" ###################################################################### class floatTestCase(MatrixTestCase): def __init__(self, methodName="runTest"): MatrixTestCase.__init__(self, methodName) self.typeStr = "float" self.typeCode = "f" ###################################################################### class doubleTestCase(MatrixTestCase): def __init__(self, methodName="runTest"): MatrixTestCase.__init__(self, methodName) self.typeStr = "double" self.typeCode = "d" ###################################################################### if __name__ == "__main__": # Build the test suite suite = unittest.TestSuite() suite.addTest(unittest.makeSuite( scharTestCase)) suite.addTest(unittest.makeSuite( ucharTestCase)) suite.addTest(unittest.makeSuite( shortTestCase)) suite.addTest(unittest.makeSuite( ushortTestCase)) suite.addTest(unittest.makeSuite( intTestCase)) suite.addTest(unittest.makeSuite( uintTestCase)) suite.addTest(unittest.makeSuite( longTestCase)) suite.addTest(unittest.makeSuite( ulongTestCase)) suite.addTest(unittest.makeSuite( longLongTestCase)) suite.addTest(unittest.makeSuite(ulongLongTestCase)) suite.addTest(unittest.makeSuite( floatTestCase)) suite.addTest(unittest.makeSuite( doubleTestCase)) # Execute the test suite print("Testing 2D Functions of Module Matrix") print("NumPy version", np.__version__) print() result = unittest.TextTestRunner(verbosity=2).run(suite) sys.exit(len(result.errors) + len(result.failures)) numpy-1.8.2/doc/swig/test/testTensor.py0000775000175100017510000004010112370216243021244 0ustar vagrantvagrant00000000000000#! /usr/bin/env python from __future__ import division, absolute_import, print_function # System imports from distutils.util import get_platform from math import sqrt import os import sys import unittest # Import NumPy import numpy as np major, minor = [ int(d) for d in np.__version__.split(".")[:2] ] if major == 0: BadListError = TypeError else: BadListError = ValueError import Tensor ###################################################################### class TensorTestCase(unittest.TestCase): def __init__(self, methodName="runTests"): unittest.TestCase.__init__(self, methodName) self.typeStr = "double" self.typeCode = "d" self.result = sqrt(28.0/8) # Test (type IN_ARRAY3[ANY][ANY][ANY]) typemap def testNorm(self): "Test norm function" print(self.typeStr, "... ", end=' ', file=sys.stderr) norm = Tensor.__dict__[self.typeStr + "Norm"] tensor = [[[0, 1], [2, 3]], [[3, 2], [1, 0]]] if isinstance(self.result, int): self.assertEquals(norm(tensor), self.result) else: self.assertAlmostEqual(norm(tensor), self.result, 6) # Test (type IN_ARRAY3[ANY][ANY][ANY]) typemap def testNormBadList(self): "Test norm function with bad list" print(self.typeStr, "... ", end=' ', file=sys.stderr) norm = Tensor.__dict__[self.typeStr + "Norm"] tensor = [[[0, "one"], [2, 3]], [[3, "two"], [1, 0]]] self.assertRaises(BadListError, norm, tensor) # Test (type IN_ARRAY3[ANY][ANY][ANY]) typemap def testNormWrongDim(self): "Test norm function with wrong dimensions" print(self.typeStr, "... ", end=' ', file=sys.stderr) norm = Tensor.__dict__[self.typeStr + "Norm"] tensor = [[0, 1, 2, 3], [3, 2, 1, 0]] self.assertRaises(TypeError, norm, tensor) # Test (type IN_ARRAY3[ANY][ANY][ANY]) typemap def testNormWrongSize(self): "Test norm function with wrong size" print(self.typeStr, "... ", end=' ', file=sys.stderr) norm = Tensor.__dict__[self.typeStr + "Norm"] tensor = [[[0, 1, 0], [2, 3, 2]], [[3, 2, 3], [1, 0, 1]]] self.assertRaises(TypeError, norm, tensor) # Test (type IN_ARRAY3[ANY][ANY][ANY]) typemap def testNormNonContainer(self): "Test norm function with non-container" print(self.typeStr, "... ", end=' ', file=sys.stderr) norm = Tensor.__dict__[self.typeStr + "Norm"] self.assertRaises(TypeError, norm, None) # Test (type* IN_ARRAY3, int DIM1, int DIM2, int DIM3) typemap def testMax(self): "Test max function" print(self.typeStr, "... ", end=' ', file=sys.stderr) max = Tensor.__dict__[self.typeStr + "Max"] tensor = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]] self.assertEquals(max(tensor), 8) # Test (type* IN_ARRAY3, int DIM1, int DIM2, int DIM3) typemap def testMaxBadList(self): "Test max function with bad list" print(self.typeStr, "... ", end=' ', file=sys.stderr) max = Tensor.__dict__[self.typeStr + "Max"] tensor = [[[1, "two"], [3, 4]], [[5, "six"], [7, 8]]] self.assertRaises(BadListError, max, tensor) # Test (type* IN_ARRAY3, int DIM1, int DIM2, int DIM3) typemap def testMaxNonContainer(self): "Test max function with non-container" print(self.typeStr, "... ", end=' ', file=sys.stderr) max = Tensor.__dict__[self.typeStr + "Max"] self.assertRaises(TypeError, max, None) # Test (type* IN_ARRAY3, int DIM1, int DIM2, int DIM3) typemap def testMaxWrongDim(self): "Test max function with wrong dimensions" print(self.typeStr, "... ", end=' ', file=sys.stderr) max = Tensor.__dict__[self.typeStr + "Max"] self.assertRaises(TypeError, max, [0, -1, 2, -3]) # Test (int DIM1, int DIM2, int DIM3, type* IN_ARRAY3) typemap def testMin(self): "Test min function" print(self.typeStr, "... ", end=' ', file=sys.stderr) min = Tensor.__dict__[self.typeStr + "Min"] tensor = [[[9, 8], [7, 6]], [[5, 4], [3, 2]]] self.assertEquals(min(tensor), 2) # Test (int DIM1, int DIM2, int DIM3, type* IN_ARRAY3) typemap def testMinBadList(self): "Test min function with bad list" print(self.typeStr, "... ", end=' ', file=sys.stderr) min = Tensor.__dict__[self.typeStr + "Min"] tensor = [[["nine", 8], [7, 6]], [["five", 4], [3, 2]]] self.assertRaises(BadListError, min, tensor) # Test (int DIM1, int DIM2, int DIM3, type* IN_ARRAY3) typemap def testMinNonContainer(self): "Test min function with non-container" print(self.typeStr, "... ", end=' ', file=sys.stderr) min = Tensor.__dict__[self.typeStr + "Min"] self.assertRaises(TypeError, min, True) # Test (int DIM1, int DIM2, int DIM3, type* IN_ARRAY3) typemap def testMinWrongDim(self): "Test min function with wrong dimensions" print(self.typeStr, "... ", end=' ', file=sys.stderr) min = Tensor.__dict__[self.typeStr + "Min"] self.assertRaises(TypeError, min, [[1, 3], [5, 7]]) # Test (type INPLACE_ARRAY3[ANY][ANY][ANY]) typemap def testScale(self): "Test scale function" print(self.typeStr, "... ", end=' ', file=sys.stderr) scale = Tensor.__dict__[self.typeStr + "Scale"] tensor = np.array([[[1, 0, 1], [0, 1, 0], [1, 0, 1]], [[0, 1, 0], [1, 0, 1], [0, 1, 0]], [[1, 0, 1], [0, 1, 0], [1, 0, 1]]], self.typeCode) scale(tensor, 4) self.assertEquals((tensor == [[[4, 0, 4], [0, 4, 0], [4, 0, 4]], [[0, 4, 0], [4, 0, 4], [0, 4, 0]], [[4, 0, 4], [0, 4, 0], [4, 0, 4]]]).all(), True) # Test (type INPLACE_ARRAY3[ANY][ANY][ANY]) typemap def testScaleWrongType(self): "Test scale function with wrong type" print(self.typeStr, "... ", end=' ', file=sys.stderr) scale = Tensor.__dict__[self.typeStr + "Scale"] tensor = np.array([[[1, 0, 1], [0, 1, 0], [1, 0, 1]], [[0, 1, 0], [1, 0, 1], [0, 1, 0]], [[1, 0, 1], [0, 1, 0], [1, 0, 1]]], 'c') self.assertRaises(TypeError, scale, tensor) # Test (type INPLACE_ARRAY3[ANY][ANY][ANY]) typemap def testScaleWrongDim(self): "Test scale function with wrong dimensions" print(self.typeStr, "... ", end=' ', file=sys.stderr) scale = Tensor.__dict__[self.typeStr + "Scale"] tensor = np.array([[1, 0, 1], [0, 1, 0], [1, 0, 1], [0, 1, 0], [1, 0, 1], [0, 1, 0]], self.typeCode) self.assertRaises(TypeError, scale, tensor) # Test (type INPLACE_ARRAY3[ANY][ANY][ANY]) typemap def testScaleWrongSize(self): "Test scale function with wrong size" print(self.typeStr, "... ", end=' ', file=sys.stderr) scale = Tensor.__dict__[self.typeStr + "Scale"] tensor = np.array([[[1, 0], [0, 1], [1, 0]], [[0, 1], [1, 0], [0, 1]], [[1, 0], [0, 1], [1, 0]]], self.typeCode) self.assertRaises(TypeError, scale, tensor) # Test (type INPLACE_ARRAY3[ANY][ANY][ANY]) typemap def testScaleNonArray(self): "Test scale function with non-array" print(self.typeStr, "... ", end=' ', file=sys.stderr) scale = Tensor.__dict__[self.typeStr + "Scale"] self.assertRaises(TypeError, scale, True) # Test (type* INPLACE_ARRAY3, int DIM1, int DIM2, int DIM3) typemap def testFloor(self): "Test floor function" print(self.typeStr, "... ", end=' ', file=sys.stderr) floor = Tensor.__dict__[self.typeStr + "Floor"] tensor = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]], self.typeCode) floor(tensor, 4) np.testing.assert_array_equal(tensor, np.array([[[4, 4], [4, 4]], [[5, 6], [7, 8]]])) # Test (type* INPLACE_ARRAY3, int DIM1, int DIM2, int DIM3) typemap def testFloorWrongType(self): "Test floor function with wrong type" print(self.typeStr, "... ", end=' ', file=sys.stderr) floor = Tensor.__dict__[self.typeStr + "Floor"] tensor = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]], 'c') self.assertRaises(TypeError, floor, tensor) # Test (type* INPLACE_ARRAY3, int DIM1, int DIM2, int DIM3) typemap def testFloorWrongDim(self): "Test floor function with wrong type" print(self.typeStr, "... ", end=' ', file=sys.stderr) floor = Tensor.__dict__[self.typeStr + "Floor"] tensor = np.array([[1, 2], [3, 4], [5, 6], [7, 8]], self.typeCode) self.assertRaises(TypeError, floor, tensor) # Test (type* INPLACE_ARRAY3, int DIM1, int DIM2, int DIM3) typemap def testFloorNonArray(self): "Test floor function with non-array" print(self.typeStr, "... ", end=' ', file=sys.stderr) floor = Tensor.__dict__[self.typeStr + "Floor"] self.assertRaises(TypeError, floor, object) # Test (int DIM1, int DIM2, int DIM3, type* INPLACE_ARRAY3) typemap def testCeil(self): "Test ceil function" print(self.typeStr, "... ", end=' ', file=sys.stderr) ceil = Tensor.__dict__[self.typeStr + "Ceil"] tensor = np.array([[[9, 8], [7, 6]], [[5, 4], [3, 2]]], self.typeCode) ceil(tensor, 5) np.testing.assert_array_equal(tensor, np.array([[[5, 5], [5, 5]], [[5, 4], [3, 2]]])) # Test (int DIM1, int DIM2, int DIM3, type* INPLACE_ARRAY3) typemap def testCeilWrongType(self): "Test ceil function with wrong type" print(self.typeStr, "... ", end=' ', file=sys.stderr) ceil = Tensor.__dict__[self.typeStr + "Ceil"] tensor = np.array([[[9, 8], [7, 6]], [[5, 4], [3, 2]]], 'c') self.assertRaises(TypeError, ceil, tensor) # Test (int DIM1, int DIM2, int DIM3, type* INPLACE_ARRAY3) typemap def testCeilWrongDim(self): "Test ceil function with wrong dimensions" print(self.typeStr, "... ", end=' ', file=sys.stderr) ceil = Tensor.__dict__[self.typeStr + "Ceil"] tensor = np.array([[9, 8], [7, 6], [5, 4], [3, 2]], self.typeCode) self.assertRaises(TypeError, ceil, tensor) # Test (int DIM1, int DIM2, int DIM3, type* INPLACE_ARRAY3) typemap def testCeilNonArray(self): "Test ceil function with non-array" print(self.typeStr, "... ", end=' ', file=sys.stderr) ceil = Tensor.__dict__[self.typeStr + "Ceil"] tensor = [[[9, 8], [7, 6]], [[5, 4], [3, 2]]] self.assertRaises(TypeError, ceil, tensor) # Test (type ARGOUT_ARRAY3[ANY][ANY][ANY]) typemap def testLUSplit(self): "Test luSplit function" print(self.typeStr, "... ", end=' ', file=sys.stderr) luSplit = Tensor.__dict__[self.typeStr + "LUSplit"] lower, upper = luSplit([[[1, 1], [1, 1]], [[1, 1], [1, 1]]]) self.assertEquals((lower == [[[1, 1], [1, 0]], [[1, 0], [0, 0]]]).all(), True) self.assertEquals((upper == [[[0, 0], [0, 1]], [[0, 1], [1, 1]]]).all(), True) ###################################################################### class scharTestCase(TensorTestCase): def __init__(self, methodName="runTest"): TensorTestCase.__init__(self, methodName) self.typeStr = "schar" self.typeCode = "b" self.result = int(self.result) ###################################################################### class ucharTestCase(TensorTestCase): def __init__(self, methodName="runTest"): TensorTestCase.__init__(self, methodName) self.typeStr = "uchar" self.typeCode = "B" self.result = int(self.result) ###################################################################### class shortTestCase(TensorTestCase): def __init__(self, methodName="runTest"): TensorTestCase.__init__(self, methodName) self.typeStr = "short" self.typeCode = "h" self.result = int(self.result) ###################################################################### class ushortTestCase(TensorTestCase): def __init__(self, methodName="runTest"): TensorTestCase.__init__(self, methodName) self.typeStr = "ushort" self.typeCode = "H" self.result = int(self.result) ###################################################################### class intTestCase(TensorTestCase): def __init__(self, methodName="runTest"): TensorTestCase.__init__(self, methodName) self.typeStr = "int" self.typeCode = "i" self.result = int(self.result) ###################################################################### class uintTestCase(TensorTestCase): def __init__(self, methodName="runTest"): TensorTestCase.__init__(self, methodName) self.typeStr = "uint" self.typeCode = "I" self.result = int(self.result) ###################################################################### class longTestCase(TensorTestCase): def __init__(self, methodName="runTest"): TensorTestCase.__init__(self, methodName) self.typeStr = "long" self.typeCode = "l" self.result = int(self.result) ###################################################################### class ulongTestCase(TensorTestCase): def __init__(self, methodName="runTest"): TensorTestCase.__init__(self, methodName) self.typeStr = "ulong" self.typeCode = "L" self.result = int(self.result) ###################################################################### class longLongTestCase(TensorTestCase): def __init__(self, methodName="runTest"): TensorTestCase.__init__(self, methodName) self.typeStr = "longLong" self.typeCode = "q" self.result = int(self.result) ###################################################################### class ulongLongTestCase(TensorTestCase): def __init__(self, methodName="runTest"): TensorTestCase.__init__(self, methodName) self.typeStr = "ulongLong" self.typeCode = "Q" self.result = int(self.result) ###################################################################### class floatTestCase(TensorTestCase): def __init__(self, methodName="runTest"): TensorTestCase.__init__(self, methodName) self.typeStr = "float" self.typeCode = "f" ###################################################################### class doubleTestCase(TensorTestCase): def __init__(self, methodName="runTest"): TensorTestCase.__init__(self, methodName) self.typeStr = "double" self.typeCode = "d" ###################################################################### if __name__ == "__main__": # Build the test suite suite = unittest.TestSuite() suite.addTest(unittest.makeSuite( scharTestCase)) suite.addTest(unittest.makeSuite( ucharTestCase)) suite.addTest(unittest.makeSuite( shortTestCase)) suite.addTest(unittest.makeSuite( ushortTestCase)) suite.addTest(unittest.makeSuite( intTestCase)) suite.addTest(unittest.makeSuite( uintTestCase)) suite.addTest(unittest.makeSuite( longTestCase)) suite.addTest(unittest.makeSuite( ulongTestCase)) suite.addTest(unittest.makeSuite( longLongTestCase)) suite.addTest(unittest.makeSuite(ulongLongTestCase)) suite.addTest(unittest.makeSuite( floatTestCase)) suite.addTest(unittest.makeSuite( doubleTestCase)) # Execute the test suite print("Testing 3D Functions of Module Tensor") print("NumPy version", np.__version__) print() result = unittest.TextTestRunner(verbosity=2).run(suite) sys.exit(len(result.errors) + len(result.failures)) numpy-1.8.2/doc/swig/test/Vector.i0000664000175100017510000000261412370216243020140 0ustar vagrantvagrant00000000000000// -*- c++ -*- %module Vector %{ #define SWIG_FILE_WITH_INIT #include "Vector.h" %} // Get the NumPy typemaps %include "../numpy.i" %init %{ import_array(); %} %define %apply_numpy_typemaps(TYPE) %apply (TYPE IN_ARRAY1[ANY]) {(TYPE vector[3])}; %apply (TYPE* IN_ARRAY1, int DIM1) {(TYPE* series, int size)}; %apply (int DIM1, TYPE* IN_ARRAY1) {(int size, TYPE* series)}; %apply (TYPE INPLACE_ARRAY1[ANY]) {(TYPE array[3])}; %apply (TYPE* INPLACE_ARRAY1, int DIM1) {(TYPE* array, int size)}; %apply (int DIM1, TYPE* INPLACE_ARRAY1) {(int size, TYPE* array)}; %apply (TYPE ARGOUT_ARRAY1[ANY]) {(TYPE even[3])}; %apply (TYPE ARGOUT_ARRAY1[ANY]) {(TYPE odd[ 3])}; %apply (TYPE* ARGOUT_ARRAY1, int DIM1) {(TYPE* twoVec, int size)}; %apply (int DIM1, TYPE* ARGOUT_ARRAY1) {(int size, TYPE* threeVec)}; %enddef /* %apply_numpy_typemaps() macro */ %apply_numpy_typemaps(signed char ) %apply_numpy_typemaps(unsigned char ) %apply_numpy_typemaps(short ) %apply_numpy_typemaps(unsigned short ) %apply_numpy_typemaps(int ) %apply_numpy_typemaps(unsigned int ) %apply_numpy_typemaps(long ) %apply_numpy_typemaps(unsigned long ) %apply_numpy_typemaps(long long ) %apply_numpy_typemaps(unsigned long long) %apply_numpy_typemaps(float ) %apply_numpy_typemaps(double ) // Include the header file to be wrapped %include "Vector.h" numpy-1.8.2/doc/swig/test/Vector.h0000664000175100017510000000437712370216243020147 0ustar vagrantvagrant00000000000000#ifndef VECTOR_H #define VECTOR_H // The following macro defines the prototypes for a family of // functions that work with 1D arrays with the forms // // TYPE SNAMELength( TYPE vector[3]); // TYPE SNAMEProd( TYPE * series, int size); // TYPE SNAMESum( int size, TYPE * series); // void SNAMEReverse(TYPE array[3]); // void SNAMEOnes( TYPE * array, int size); // void SNAMEZeros( int size, TYPE * array); // void SNAMEEOSplit(TYPE vector[3], TYPE even[3], TYPE odd[3]); // void SNAMETwos( TYPE * twoVec, int size); // void SNAMEThrees( int size, TYPE * threeVec); // // for any specified type TYPE (for example: short, unsigned int, long // long, etc.) with given short name SNAME (for example: short, uint, // longLong, etc.). The macro is then expanded for the given // TYPE/SNAME pairs. The resulting functions are for testing numpy // interfaces, respectively, for: // // * 1D input arrays, hard-coded length // * 1D input arrays // * 1D input arrays, data last // * 1D in-place arrays, hard-coded length // * 1D in-place arrays // * 1D in-place arrays, data last // * 1D argout arrays, hard-coded length // * 1D argout arrays // * 1D argout arrays, data last // #define TEST_FUNC_PROTOS(TYPE, SNAME) \ \ TYPE SNAME ## Length( TYPE vector[3]); \ TYPE SNAME ## Prod( TYPE * series, int size); \ TYPE SNAME ## Sum( int size, TYPE * series); \ void SNAME ## Reverse(TYPE array[3]); \ void SNAME ## Ones( TYPE * array, int size); \ void SNAME ## Zeros( int size, TYPE * array); \ void SNAME ## EOSplit(TYPE vector[3], TYPE even[3], TYPE odd[3]); \ void SNAME ## Twos( TYPE * twoVec, int size); \ void SNAME ## Threes( int size, TYPE * threeVec); \ TEST_FUNC_PROTOS(signed char , schar ) TEST_FUNC_PROTOS(unsigned char , uchar ) TEST_FUNC_PROTOS(short , short ) TEST_FUNC_PROTOS(unsigned short , ushort ) TEST_FUNC_PROTOS(int , int ) TEST_FUNC_PROTOS(unsigned int , uint ) TEST_FUNC_PROTOS(long , long ) TEST_FUNC_PROTOS(unsigned long , ulong ) TEST_FUNC_PROTOS(long long , longLong ) TEST_FUNC_PROTOS(unsigned long long, ulongLong) TEST_FUNC_PROTOS(float , float ) TEST_FUNC_PROTOS(double , double ) #endif numpy-1.8.2/doc/swig/test/Tensor.h0000664000175100017510000000444012370216243020146 0ustar vagrantvagrant00000000000000#ifndef TENSOR_H #define TENSOR_H // The following macro defines the prototypes for a family of // functions that work with 3D arrays with the forms // // TYPE SNAMENorm( TYPE tensor[2][2][2]); // TYPE SNAMEMax( TYPE * tensor, int slices, int rows, int cols); // TYPE SNAMEMin( int slices, int rows, int cols, TYPE * tensor); // void SNAMEScale( TYPE array[3][3][3]); // void SNAMEFloor( TYPE * array, int slices, int rows, int cols, TYPE floor); // void SNAMECeil( int slices, int rows, int cols, TYPE * array, TYPE ceil ); // void SNAMELUSplit(TYPE in[3][3][3], TYPE lower[3][3][3], TYPE upper[3][3][3]); // // for any specified type TYPE (for example: short, unsigned int, long // long, etc.) with given short name SNAME (for example: short, uint, // longLong, etc.). The macro is then expanded for the given // TYPE/SNAME pairs. The resulting functions are for testing numpy // interfaces, respectively, for: // // * 3D input arrays, hard-coded lengths // * 3D input arrays // * 3D input arrays, data last // * 3D in-place arrays, hard-coded lengths // * 3D in-place arrays // * 3D in-place arrays, data last // * 3D argout arrays, hard-coded length // #define TEST_FUNC_PROTOS(TYPE, SNAME) \ \ TYPE SNAME ## Norm( TYPE tensor[2][2][2]); \ TYPE SNAME ## Max( TYPE * tensor, int slices, int rows, int cols); \ TYPE SNAME ## Min( int slices, int rows, int cols, TYPE * tensor); \ void SNAME ## Scale( TYPE array[3][3][3], TYPE val); \ void SNAME ## Floor( TYPE * array, int slices, int rows, int cols, TYPE floor); \ void SNAME ## Ceil( int slices, int rows, int cols, TYPE * array, TYPE ceil ); \ void SNAME ## LUSplit(TYPE tensor[2][2][2], TYPE lower[2][2][2], TYPE upper[2][2][2]); TEST_FUNC_PROTOS(signed char , schar ) TEST_FUNC_PROTOS(unsigned char , uchar ) TEST_FUNC_PROTOS(short , short ) TEST_FUNC_PROTOS(unsigned short , ushort ) TEST_FUNC_PROTOS(int , int ) TEST_FUNC_PROTOS(unsigned int , uint ) TEST_FUNC_PROTOS(long , long ) TEST_FUNC_PROTOS(unsigned long , ulong ) TEST_FUNC_PROTOS(long long , longLong ) TEST_FUNC_PROTOS(unsigned long long, ulongLong) TEST_FUNC_PROTOS(float , float ) TEST_FUNC_PROTOS(double , double ) #endif numpy-1.8.2/doc/swig/test/Tensor.i0000664000175100017510000000301412370216243020143 0ustar vagrantvagrant00000000000000// -*- c++ -*- %module Tensor %{ #define SWIG_FILE_WITH_INIT #include "Tensor.h" %} // Get the NumPy typemaps %include "../numpy.i" %init %{ import_array(); %} %define %apply_numpy_typemaps(TYPE) %apply (TYPE IN_ARRAY3[ANY][ANY][ANY]) {(TYPE tensor[ANY][ANY][ANY])}; %apply (TYPE* IN_ARRAY3, int DIM1, int DIM2, int DIM3) {(TYPE* tensor, int slices, int rows, int cols)}; %apply (int DIM1, int DIM2, int DIM3, TYPE* IN_ARRAY3) {(int slices, int rows, int cols, TYPE* tensor)}; %apply (TYPE INPLACE_ARRAY3[ANY][ANY][ANY]) {(TYPE array[3][3][3])}; %apply (TYPE* INPLACE_ARRAY3, int DIM1, int DIM2, int DIM3) {(TYPE* array, int slices, int rows, int cols)}; %apply (int DIM1, int DIM2, int DIM3, TYPE* INPLACE_ARRAY3) {(int slices, int rows, int cols, TYPE* array)}; %apply (TYPE ARGOUT_ARRAY3[ANY][ANY][ANY]) {(TYPE lower[2][2][2])}; %apply (TYPE ARGOUT_ARRAY3[ANY][ANY][ANY]) {(TYPE upper[2][2][2])}; %enddef /* %apply_numpy_typemaps() macro */ %apply_numpy_typemaps(signed char ) %apply_numpy_typemaps(unsigned char ) %apply_numpy_typemaps(short ) %apply_numpy_typemaps(unsigned short ) %apply_numpy_typemaps(int ) %apply_numpy_typemaps(unsigned int ) %apply_numpy_typemaps(long ) %apply_numpy_typemaps(unsigned long ) %apply_numpy_typemaps(long long ) %apply_numpy_typemaps(unsigned long long) %apply_numpy_typemaps(float ) %apply_numpy_typemaps(double ) // Include the header file to be wrapped %include "Tensor.h" numpy-1.8.2/doc/swig/test/Array2.cxx0000664000175100017510000000616412370216243020414 0ustar vagrantvagrant00000000000000#include "Array2.h" #include // Default constructor Array2::Array2() : _ownData(false), _nrows(0), _ncols(), _buffer(0), _rows(0) { } // Size/array constructor Array2::Array2(int nrows, int ncols, long* data) : _ownData(false), _nrows(0), _ncols(), _buffer(0), _rows(0) { resize(nrows, ncols, data); } // Copy constructor Array2::Array2(const Array2 & source) : _nrows(source._nrows), _ncols(source._ncols) { _ownData = true; allocateMemory(); *this = source; } // Destructor Array2::~Array2() { deallocateMemory(); } // Assignment operator Array2 & Array2::operator=(const Array2 & source) { int nrows = _nrows < source._nrows ? _nrows : source._nrows; int ncols = _ncols < source._ncols ? _ncols : source._ncols; for (int i=0; i < nrows; ++i) { for (int j=0; j < ncols; ++j) { (*this)[i][j] = source[i][j]; } } return *this; } // Equals operator bool Array2::operator==(const Array2 & other) const { if (_nrows != other._nrows) return false; if (_ncols != other._ncols) return false; for (int i=0; i < _nrows; ++i) { for (int j=0; j < _ncols; ++j) { if ((*this)[i][j] != other[i][j]) return false; } } return true; } // Length accessors int Array2::nrows() const { return _nrows; } int Array2::ncols() const { return _ncols; } // Resize array void Array2::resize(int nrows, int ncols, long* data) { if (nrows < 0) throw std::invalid_argument("Array2 nrows less than 0"); if (ncols < 0) throw std::invalid_argument("Array2 ncols less than 0"); if (nrows == _nrows && ncols == _ncols) return; deallocateMemory(); _nrows = nrows; _ncols = ncols; if (!data) { allocateMemory(); } else { _ownData = false; _buffer = data; allocateRows(); } } // Set item accessor Array1 & Array2::operator[](int i) { if (i < 0 || i > _nrows) throw std::out_of_range("Array2 row index out of range"); return _rows[i]; } // Get item accessor const Array1 & Array2::operator[](int i) const { if (i < 0 || i > _nrows) throw std::out_of_range("Array2 row index out of range"); return _rows[i]; } // String output std::string Array2::asString() const { std::stringstream result; result << "[ "; for (int i=0; i < _nrows; ++i) { if (i > 0) result << " "; result << (*this)[i].asString(); if (i < _nrows-1) result << "," << std::endl; } result << " ]" << std::endl; return result.str(); } // Get view void Array2::view(int* nrows, int* ncols, long** data) const { *nrows = _nrows; *ncols = _ncols; *data = _buffer; } // Private methods void Array2::allocateMemory() { if (_nrows * _ncols == 0) { _ownData = false; _buffer = 0; _rows = 0; } else { _ownData = true; _buffer = new long[_nrows*_ncols]; allocateRows(); } } void Array2::allocateRows() { _rows = new Array1[_nrows]; for (int i=0; i < _nrows; ++i) { _rows[i].resize(_ncols, &_buffer[i*_ncols]); } } void Array2::deallocateMemory() { if (_ownData && _nrows*_ncols && _buffer) { delete [] _rows; delete [] _buffer; } _ownData = false; _nrows = 0; _ncols = 0; _buffer = 0; _rows = 0; } numpy-1.8.2/doc/swig/test/Fortran.i0000664000175100017510000000161112370216243020305 0ustar vagrantvagrant00000000000000// -*- c++ -*- %module Fortran %{ #define SWIG_FILE_WITH_INIT #include "Fortran.h" %} // Get the NumPy typemaps %include "../numpy.i" %init %{ import_array(); %} %define %apply_numpy_typemaps(TYPE) %apply (TYPE* IN_FARRAY2, int DIM1, int DIM2) {(TYPE* matrix, int rows, int cols)}; %enddef /* %apply_numpy_typemaps() macro */ %apply_numpy_typemaps(signed char ) %apply_numpy_typemaps(unsigned char ) %apply_numpy_typemaps(short ) %apply_numpy_typemaps(unsigned short ) %apply_numpy_typemaps(int ) %apply_numpy_typemaps(unsigned int ) %apply_numpy_typemaps(long ) %apply_numpy_typemaps(unsigned long ) %apply_numpy_typemaps(long long ) %apply_numpy_typemaps(unsigned long long) %apply_numpy_typemaps(float ) %apply_numpy_typemaps(double ) // Include the header file to be wrapped %include "Fortran.h" numpy-1.8.2/doc/swig/test/setup.py0000775000175100017510000000357612370216243020251 0ustar vagrantvagrant00000000000000#! /usr/bin/env python from __future__ import division, print_function # System imports from distutils.core import * from distutils import sysconfig # Third-party modules - we depend on numpy for everything import numpy # Obtain the numpy include directory. numpy_include = numpy.get_include() # Array extension module _Array = Extension("_Array", ["Array_wrap.cxx", "Array1.cxx", "Array2.cxx"], include_dirs = [numpy_include], ) # Farray extension module _Farray = Extension("_Farray", ["Farray_wrap.cxx", "Farray.cxx"], include_dirs = [numpy_include], ) # _Vector extension module _Vector = Extension("_Vector", ["Vector_wrap.cxx", "Vector.cxx"], include_dirs = [numpy_include], ) # _Matrix extension module _Matrix = Extension("_Matrix", ["Matrix_wrap.cxx", "Matrix.cxx"], include_dirs = [numpy_include], ) # _Tensor extension module _Tensor = Extension("_Tensor", ["Tensor_wrap.cxx", "Tensor.cxx"], include_dirs = [numpy_include], ) _Fortran = Extension("_Fortran", ["Fortran_wrap.cxx", "Fortran.cxx"], include_dirs = [numpy_include], ) # NumyTypemapTests setup setup(name = "NumpyTypemapTests", description = "Functions that work on arrays", author = "Bill Spotz", py_modules = ["Array", "Farray", "Vector", "Matrix", "Tensor", "Fortran"], ext_modules = [_Array, _Farray, _Vector, _Matrix, _Tensor, _Fortran] ) numpy-1.8.2/doc/swig/test/Array2.h0000664000175100017510000000201712370216243020032 0ustar vagrantvagrant00000000000000#ifndef ARRAY2_H #define ARRAY2_H #include "Array1.h" #include #include class Array2 { public: // Default constructor Array2(); // Size/array constructor Array2(int nrows, int ncols, long* data=0); // Copy constructor Array2(const Array2 & source); // Destructor ~Array2(); // Assignment operator Array2 & operator=(const Array2 & source); // Equals operator bool operator==(const Array2 & other) const; // Length accessors int nrows() const; int ncols() const; // Resize array void resize(int nrows, int ncols, long* data=0); // Set item accessor Array1 & operator[](int i); // Get item accessor const Array1 & operator[](int i) const; // String output std::string asString() const; // Get view void view(int* nrows, int* ncols, long** data) const; private: // Members bool _ownData; int _nrows; int _ncols; long * _buffer; Array1 * _rows; // Methods void allocateMemory(); void allocateRows(); void deallocateMemory(); }; #endif numpy-1.8.2/doc/swig/test/Farray.cxx0000664000175100017510000000502312370216243020471 0ustar vagrantvagrant00000000000000#include "Farray.h" #include // Size constructor Farray::Farray(int nrows, int ncols) : _nrows(nrows), _ncols(ncols), _buffer(0) { allocateMemory(); } // Copy constructor Farray::Farray(const Farray & source) : _nrows(source._nrows), _ncols(source._ncols) { allocateMemory(); *this = source; } // Destructor Farray::~Farray() { delete [] _buffer; } // Assignment operator Farray & Farray::operator=(const Farray & source) { int nrows = _nrows < source._nrows ? _nrows : source._nrows; int ncols = _ncols < source._ncols ? _ncols : source._ncols; for (int i=0; i < nrows; ++i) { for (int j=0; j < ncols; ++j) { (*this)(i,j) = source(i,j); } } return *this; } // Equals operator bool Farray::operator==(const Farray & other) const { if (_nrows != other._nrows) return false; if (_ncols != other._ncols) return false; for (int i=0; i < _nrows; ++i) { for (int j=0; j < _ncols; ++j) { if ((*this)(i,j) != other(i,j)) return false; } } return true; } // Length accessors int Farray::nrows() const { return _nrows; } int Farray::ncols() const { return _ncols; } // Set item accessor long & Farray::operator()(int i, int j) { if (i < 0 || i > _nrows) throw std::out_of_range("Farray row index out of range"); if (j < 0 || j > _ncols) throw std::out_of_range("Farray col index out of range"); return _buffer[offset(i,j)]; } // Get item accessor const long & Farray::operator()(int i, int j) const { if (i < 0 || i > _nrows) throw std::out_of_range("Farray row index out of range"); if (j < 0 || j > _ncols) throw std::out_of_range("Farray col index out of range"); return _buffer[offset(i,j)]; } // String output std::string Farray::asString() const { std::stringstream result; result << "[ "; for (int i=0; i < _nrows; ++i) { if (i > 0) result << " "; result << "["; for (int j=0; j < _ncols; ++j) { result << " " << (*this)(i,j); if (j < _ncols-1) result << ","; } result << " ]"; if (i < _nrows-1) result << "," << std::endl; } result << " ]" << std::endl; return result.str(); } // Get view void Farray::view(int* nrows, int* ncols, long** data) const { *nrows = _nrows; *ncols = _ncols; *data = _buffer; } // Private methods void Farray::allocateMemory() { if (_nrows <= 0) throw std::invalid_argument("Farray nrows <= 0"); if (_ncols <= 0) throw std::invalid_argument("Farray ncols <= 0"); _buffer = new long[_nrows*_ncols]; } inline int Farray::offset(int i, int j) const { return i + j * _nrows; } numpy-1.8.2/doc/swig/test/SuperTensor.i0000664000175100017510000000324112370216243021164 0ustar vagrantvagrant00000000000000// -*- c++ -*- %module SuperTensor %{ #define SWIG_FILE_WITH_INIT #include "SuperTensor.h" %} // Get the NumPy typemaps %include "../numpy.i" %init %{ import_array(); %} %define %apply_numpy_typemaps(TYPE) %apply (TYPE IN_ARRAY4[ANY][ANY][ANY][ANY]) {(TYPE supertensor[ANY][ANY][ANY][ANY])}; %apply (TYPE* IN_ARRAY4, int DIM1, int DIM2, int DIM3, int DIM4) {(TYPE* supertensor, int cubes, int slices, int rows, int cols)}; %apply (int DIM1, int DIM2, int DIM3, int DIM4, TYPE* IN_ARRAY4) {(int cubes, int slices, int rows, int cols, TYPE* supertensor)}; %apply (TYPE INPLACE_ARRAY4[ANY][ANY][ANY][ANY]) {(TYPE array[3][3][3][3])}; %apply (TYPE* INPLACE_ARRAY4, int DIM1, int DIM2, int DIM3, int DIM4) {(TYPE* array, int cubes, int slices, int rows, int cols)}; %apply (int DIM1, int DIM2, int DIM3, int DIM4, TYPE* INPLACE_ARRAY4) {(int cubes, int slices, int rows, int cols, TYPE* array)}; %apply (TYPE ARGOUT_ARRAY4[ANY][ANY][ANY][ANY]) {(TYPE lower[2][2][2][2])}; %apply (TYPE ARGOUT_ARRAY4[ANY][ANY][ANY][ANY]) {(TYPE upper[2][2][2][2])}; %enddef /* %apply_numpy_typemaps() macro */ %apply_numpy_typemaps(signed char ) %apply_numpy_typemaps(unsigned char ) %apply_numpy_typemaps(short ) %apply_numpy_typemaps(unsigned short ) %apply_numpy_typemaps(int ) %apply_numpy_typemaps(unsigned int ) %apply_numpy_typemaps(long ) %apply_numpy_typemaps(unsigned long ) %apply_numpy_typemaps(long long ) %apply_numpy_typemaps(unsigned long long) %apply_numpy_typemaps(float ) %apply_numpy_typemaps(double ) // Include the header file to be wrapped %include "SuperTensor.h" numpy-1.8.2/doc/swig/test/Array1.cxx0000664000175100017510000000440512370216243020407 0ustar vagrantvagrant00000000000000#include "Array1.h" #include #include // Default/length/array constructor Array1::Array1(int length, long* data) : _ownData(false), _length(0), _buffer(0) { resize(length, data); } // Copy constructor Array1::Array1(const Array1 & source) : _length(source._length) { allocateMemory(); *this = source; } // Destructor Array1::~Array1() { deallocateMemory(); } // Assignment operator Array1 & Array1::operator=(const Array1 & source) { int len = _length < source._length ? _length : source._length; for (int i=0; i < len; ++i) { (*this)[i] = source[i]; } return *this; } // Equals operator bool Array1::operator==(const Array1 & other) const { if (_length != other._length) return false; for (int i=0; i < _length; ++i) { if ((*this)[i] != other[i]) return false; } return true; } // Length accessor int Array1::length() const { return _length; } // Resize array void Array1::resize(int length, long* data) { if (length < 0) throw std::invalid_argument("Array1 length less than 0"); if (length == _length) return; deallocateMemory(); _length = length; if (!data) { allocateMemory(); } else { _ownData = false; _buffer = data; } } // Set item accessor long & Array1::operator[](int i) { if (i < 0 || i >= _length) throw std::out_of_range("Array1 index out of range"); return _buffer[i]; } // Get item accessor const long & Array1::operator[](int i) const { if (i < 0 || i >= _length) throw std::out_of_range("Array1 index out of range"); return _buffer[i]; } // String output std::string Array1::asString() const { std::stringstream result; result << "["; for (int i=0; i < _length; ++i) { result << " " << _buffer[i]; if (i < _length-1) result << ","; } result << " ]"; return result.str(); } // Get view void Array1::view(long** data, int* length) const { *data = _buffer; *length = _length; } // Private methods void Array1::allocateMemory() { if (_length == 0) { _ownData = false; _buffer = 0; } else { _ownData = true; _buffer = new long[_length]; } } void Array1::deallocateMemory() { if (_ownData && _length && _buffer) { delete [] _buffer; } _ownData = false; _length = 0; _buffer = 0; } numpy-1.8.2/doc/swig/test/Array.i0000664000175100017510000000322712370216243017755 0ustar vagrantvagrant00000000000000// -*- c++ -*- %module Array %{ #define SWIG_FILE_WITH_INIT #include "Array1.h" #include "Array2.h" %} // Get the NumPy typemaps %include "../numpy.i" // Get the STL typemaps %include "stl.i" // Handle standard exceptions %include "exception.i" %exception { try { $action } catch (const std::invalid_argument& e) { SWIG_exception(SWIG_ValueError, e.what()); } catch (const std::out_of_range& e) { SWIG_exception(SWIG_IndexError, e.what()); } } %init %{ import_array(); %} // Global ignores %ignore *::operator=; %ignore *::operator[]; // Apply the 1D NumPy typemaps %apply (int DIM1 , long* INPLACE_ARRAY1) {(int length, long* data )}; %apply (long** ARGOUTVIEW_ARRAY1, int* DIM1 ) {(long** data , int* length)}; // Apply the 2D NumPy typemaps %apply (int DIM1 , int DIM2 , long* INPLACE_ARRAY2) {(int nrows, int ncols, long* data )}; %apply (int* DIM1 , int* DIM2 , long** ARGOUTVIEW_ARRAY2) {(int* nrows, int* ncols, long** data )}; // Array1 support %include "Array1.h" %extend Array1 { void __setitem__(int i, long v) { self->operator[](i) = v; } long __getitem__(int i) { return self->operator[](i); } int __len__() { return self->length(); } std::string __str__() { return self->asString(); } } // Array2 support %include "Array2.h" %extend Array2 { void __setitem__(int i, Array1 & v) { self->operator[](i) = v; } Array1 & __getitem__(int i) { return self->operator[](i); } int __len__() { return self->nrows() * self->ncols(); } std::string __str__() { return self->asString(); } } numpy-1.8.2/doc/swig/test/Tensor.cxx0000664000175100017510000001073112370216243020521 0ustar vagrantvagrant00000000000000#include #include #include #include "Tensor.h" // The following macro defines a family of functions that work with 3D // arrays with the forms // // TYPE SNAMENorm( TYPE tensor[2][2][2]); // TYPE SNAMEMax( TYPE * tensor, int slices, int rows, int cols); // TYPE SNAMEMin( int slices, int rows, int cols TYPE * tensor); // void SNAMEScale( TYPE tensor[3][3][3]); // void SNAMEFloor( TYPE * array, int slices, int rows, int cols, TYPE floor); // void SNAMECeil( int slices, int rows, int cols, TYPE * array, TYPE ceil); // void SNAMELUSplit(TYPE in[2][2][2], TYPE lower[2][2][2], TYPE upper[2][2][2]); // // for any specified type TYPE (for example: short, unsigned int, long // long, etc.) with given short name SNAME (for example: short, uint, // longLong, etc.). The macro is then expanded for the given // TYPE/SNAME pairs. The resulting functions are for testing numpy // interfaces, respectively, for: // // * 3D input arrays, hard-coded length // * 3D input arrays // * 3D input arrays, data last // * 3D in-place arrays, hard-coded lengths // * 3D in-place arrays // * 3D in-place arrays, data last // * 3D argout arrays, hard-coded length // #define TEST_FUNCS(TYPE, SNAME) \ \ TYPE SNAME ## Norm(TYPE tensor[2][2][2]) { \ double result = 0; \ for (int k=0; k<2; ++k) \ for (int j=0; j<2; ++j) \ for (int i=0; i<2; ++i) \ result += tensor[k][j][i] * tensor[k][j][i]; \ return (TYPE)sqrt(result/8); \ } \ \ TYPE SNAME ## Max(TYPE * tensor, int slices, int rows, int cols) { \ int i, j, k, index; \ TYPE result = tensor[0]; \ for (k=0; k result) result = tensor[index]; \ } \ } \ } \ return result; \ } \ \ TYPE SNAME ## Min(int slices, int rows, int cols, TYPE * tensor) { \ int i, j, k, index; \ TYPE result = tensor[0]; \ for (k=0; k ceil) array[index] = ceil; \ } \ } \ } \ } \ \ void SNAME ## LUSplit(TYPE tensor[2][2][2], TYPE lower[2][2][2], \ TYPE upper[2][2][2]) { \ int sum; \ for (int k=0; k<2; ++k) { \ for (int j=0; j<2; ++j) { \ for (int i=0; i<2; ++i) { \ sum = i + j + k; \ if (sum < 2) { \ lower[k][j][i] = tensor[k][j][i]; \ upper[k][j][i] = 0; \ } else { \ upper[k][j][i] = tensor[k][j][i]; \ lower[k][j][i] = 0; \ } \ } \ } \ } \ } TEST_FUNCS(signed char , schar ) TEST_FUNCS(unsigned char , uchar ) TEST_FUNCS(short , short ) TEST_FUNCS(unsigned short , ushort ) TEST_FUNCS(int , int ) TEST_FUNCS(unsigned int , uint ) TEST_FUNCS(long , long ) TEST_FUNCS(unsigned long , ulong ) TEST_FUNCS(long long , longLong ) TEST_FUNCS(unsigned long long, ulongLong) TEST_FUNCS(float , float ) TEST_FUNCS(double , double ) numpy-1.8.2/doc/swig/test/Fortran.cxx0000664000175100017510000000154612370216243020666 0ustar vagrantvagrant00000000000000#include #include #include #include "Fortran.h" #define TEST_FUNCS(TYPE, SNAME) \ \ TYPE SNAME ## SecondElement(TYPE * matrix, int rows, int cols) { \ TYPE result = matrix[1]; \ return result; \ } \ TEST_FUNCS(signed char , schar ) TEST_FUNCS(unsigned char , uchar ) TEST_FUNCS(short , short ) TEST_FUNCS(unsigned short , ushort ) TEST_FUNCS(int , int ) TEST_FUNCS(unsigned int , uint ) TEST_FUNCS(long , long ) TEST_FUNCS(unsigned long , ulong ) TEST_FUNCS(long long , longLong ) TEST_FUNCS(unsigned long long, ulongLong) TEST_FUNCS(float , float ) TEST_FUNCS(double , double ) numpy-1.8.2/doc/swig/test/testFortran.py0000664000175100017510000001432512370216243021413 0ustar vagrantvagrant00000000000000#! /usr/bin/env python from __future__ import division, absolute_import, print_function # System imports from distutils.util import get_platform import os import sys import unittest # Import NumPy import numpy as np major, minor = [ int(d) for d in np.__version__.split(".")[:2] ] if major == 0: BadListError = TypeError else: BadListError = ValueError import Fortran ###################################################################### class FortranTestCase(unittest.TestCase): def __init__(self, methodName="runTests"): unittest.TestCase.__init__(self, methodName) self.typeStr = "double" self.typeCode = "d" # This test used to work before the update to avoid deprecated code. Now it # doesn't work. As best I can tell, it never should have worked, so I am # commenting it out. --WFS # def testSecondElementContiguous(self): # "Test Fortran matrix initialized from reshaped default array" # print >>sys.stderr, self.typeStr, "... ", # second = Fortran.__dict__[self.typeStr + "SecondElement"] # matrix = np.arange(9).reshape(3, 3).astype(self.typeCode) # self.assertEquals(second(matrix), 3) # Test (type* IN_FARRAY2, int DIM1, int DIM2) typemap def testSecondElementFortran(self): "Test Fortran matrix initialized from reshaped NumPy fortranarray" print(self.typeStr, "... ", end=' ', file=sys.stderr) second = Fortran.__dict__[self.typeStr + "SecondElement"] matrix = np.asfortranarray(np.arange(9).reshape(3, 3), self.typeCode) self.assertEquals(second(matrix), 3) def testSecondElementObject(self): "Test Fortran matrix initialized from nested list fortranarray" print(self.typeStr, "... ", end=' ', file=sys.stderr) second = Fortran.__dict__[self.typeStr + "SecondElement"] matrix = np.asfortranarray([[0, 1, 2], [3, 4, 5], [6, 7, 8]], self.typeCode) self.assertEquals(second(matrix), 3) ###################################################################### class scharTestCase(FortranTestCase): def __init__(self, methodName="runTest"): FortranTestCase.__init__(self, methodName) self.typeStr = "schar" self.typeCode = "b" ###################################################################### class ucharTestCase(FortranTestCase): def __init__(self, methodName="runTest"): FortranTestCase.__init__(self, methodName) self.typeStr = "uchar" self.typeCode = "B" ###################################################################### class shortTestCase(FortranTestCase): def __init__(self, methodName="runTest"): FortranTestCase.__init__(self, methodName) self.typeStr = "short" self.typeCode = "h" ###################################################################### class ushortTestCase(FortranTestCase): def __init__(self, methodName="runTest"): FortranTestCase.__init__(self, methodName) self.typeStr = "ushort" self.typeCode = "H" ###################################################################### class intTestCase(FortranTestCase): def __init__(self, methodName="runTest"): FortranTestCase.__init__(self, methodName) self.typeStr = "int" self.typeCode = "i" ###################################################################### class uintTestCase(FortranTestCase): def __init__(self, methodName="runTest"): FortranTestCase.__init__(self, methodName) self.typeStr = "uint" self.typeCode = "I" ###################################################################### class longTestCase(FortranTestCase): def __init__(self, methodName="runTest"): FortranTestCase.__init__(self, methodName) self.typeStr = "long" self.typeCode = "l" ###################################################################### class ulongTestCase(FortranTestCase): def __init__(self, methodName="runTest"): FortranTestCase.__init__(self, methodName) self.typeStr = "ulong" self.typeCode = "L" ###################################################################### class longLongTestCase(FortranTestCase): def __init__(self, methodName="runTest"): FortranTestCase.__init__(self, methodName) self.typeStr = "longLong" self.typeCode = "q" ###################################################################### class ulongLongTestCase(FortranTestCase): def __init__(self, methodName="runTest"): FortranTestCase.__init__(self, methodName) self.typeStr = "ulongLong" self.typeCode = "Q" ###################################################################### class floatTestCase(FortranTestCase): def __init__(self, methodName="runTest"): FortranTestCase.__init__(self, methodName) self.typeStr = "float" self.typeCode = "f" ###################################################################### class doubleTestCase(FortranTestCase): def __init__(self, methodName="runTest"): FortranTestCase.__init__(self, methodName) self.typeStr = "double" self.typeCode = "d" ###################################################################### if __name__ == "__main__": # Build the test suite suite = unittest.TestSuite() suite.addTest(unittest.makeSuite( scharTestCase)) suite.addTest(unittest.makeSuite( ucharTestCase)) suite.addTest(unittest.makeSuite( shortTestCase)) suite.addTest(unittest.makeSuite( ushortTestCase)) suite.addTest(unittest.makeSuite( intTestCase)) suite.addTest(unittest.makeSuite( uintTestCase)) suite.addTest(unittest.makeSuite( longTestCase)) suite.addTest(unittest.makeSuite( ulongTestCase)) suite.addTest(unittest.makeSuite( longLongTestCase)) suite.addTest(unittest.makeSuite(ulongLongTestCase)) suite.addTest(unittest.makeSuite( floatTestCase)) suite.addTest(unittest.makeSuite( doubleTestCase)) # Execute the test suite print("Testing 2D Functions of Module Matrix") print("NumPy version", np.__version__) print() result = unittest.TextTestRunner(verbosity=2).run(suite) sys.exit(len(result.errors) + len(result.failures)) numpy-1.8.2/doc/swig/test/Fortran.h0000664000175100017510000000133612370216243020310 0ustar vagrantvagrant00000000000000#ifndef FORTRAN_H #define FORTRAN_H #define TEST_FUNC_PROTOS(TYPE, SNAME) \ \ TYPE SNAME ## SecondElement( TYPE * matrix, int rows, int cols); \ TEST_FUNC_PROTOS(signed char , schar ) TEST_FUNC_PROTOS(unsigned char , uchar ) TEST_FUNC_PROTOS(short , short ) TEST_FUNC_PROTOS(unsigned short , ushort ) TEST_FUNC_PROTOS(int , int ) TEST_FUNC_PROTOS(unsigned int , uint ) TEST_FUNC_PROTOS(long , long ) TEST_FUNC_PROTOS(unsigned long , ulong ) TEST_FUNC_PROTOS(long long , longLong ) TEST_FUNC_PROTOS(unsigned long long, ulongLong) TEST_FUNC_PROTOS(float , float ) TEST_FUNC_PROTOS(double , double ) #endif numpy-1.8.2/doc/swig/test/testArray.py0000775000175100017510000002204212370216243021054 0ustar vagrantvagrant00000000000000#! /usr/bin/env python from __future__ import division, absolute_import, print_function # System imports from distutils.util import get_platform import os import sys import unittest # Import NumPy import numpy as np major, minor = [ int(d) for d in np.__version__.split(".")[:2] ] if major == 0: BadListError = TypeError else: BadListError = ValueError import Array ###################################################################### class Array1TestCase(unittest.TestCase): def setUp(self): self.length = 5 self.array1 = Array.Array1(self.length) def testConstructor0(self): "Test Array1 default constructor" a = Array.Array1() self.failUnless(isinstance(a, Array.Array1)) self.failUnless(len(a) == 0) def testConstructor1(self): "Test Array1 length constructor" self.failUnless(isinstance(self.array1, Array.Array1)) def testConstructor2(self): "Test Array1 array constructor" na = np.arange(self.length) aa = Array.Array1(na) self.failUnless(isinstance(aa, Array.Array1)) def testConstructor3(self): "Test Array1 copy constructor" for i in range(self.array1.length()): self.array1[i] = i arrayCopy = Array.Array1(self.array1) self.failUnless(arrayCopy == self.array1) def testConstructorBad(self): "Test Array1 length constructor, negative" self.assertRaises(ValueError, Array.Array1, -4) def testLength(self): "Test Array1 length method" self.failUnless(self.array1.length() == self.length) def testLen(self): "Test Array1 __len__ method" self.failUnless(len(self.array1) == self.length) def testResize0(self): "Test Array1 resize method, length" newLen = 2 * self.length self.array1.resize(newLen) self.failUnless(len(self.array1) == newLen) def testResize1(self): "Test Array1 resize method, array" a = np.zeros((2*self.length,), dtype='l') self.array1.resize(a) self.failUnless(len(self.array1) == a.size) def testResizeBad(self): "Test Array1 resize method, negative length" self.assertRaises(ValueError, self.array1.resize, -5) def testSetGet(self): "Test Array1 __setitem__, __getitem__ methods" n = self.length for i in range(n): self.array1[i] = i*i for i in range(n): self.failUnless(self.array1[i] == i*i) def testSetBad1(self): "Test Array1 __setitem__ method, negative index" self.assertRaises(IndexError, self.array1.__setitem__, -1, 0) def testSetBad2(self): "Test Array1 __setitem__ method, out-of-range index" self.assertRaises(IndexError, self.array1.__setitem__, self.length+1, 0) def testGetBad1(self): "Test Array1 __getitem__ method, negative index" self.assertRaises(IndexError, self.array1.__getitem__, -1) def testGetBad2(self): "Test Array1 __getitem__ method, out-of-range index" self.assertRaises(IndexError, self.array1.__getitem__, self.length+1) def testAsString(self): "Test Array1 asString method" for i in range(self.array1.length()): self.array1[i] = i+1 self.failUnless(self.array1.asString() == "[ 1, 2, 3, 4, 5 ]") def testStr(self): "Test Array1 __str__ method" for i in range(self.array1.length()): self.array1[i] = i-2 self.failUnless(str(self.array1) == "[ -2, -1, 0, 1, 2 ]") def testView(self): "Test Array1 view method" for i in range(self.array1.length()): self.array1[i] = i+1 a = self.array1.view() self.failUnless(isinstance(a, np.ndarray)) self.failUnless(len(a) == self.length) self.failUnless((a == [1, 2, 3, 4, 5]).all()) ###################################################################### class Array2TestCase(unittest.TestCase): def setUp(self): self.nrows = 5 self.ncols = 4 self.array2 = Array.Array2(self.nrows, self.ncols) def testConstructor0(self): "Test Array2 default constructor" a = Array.Array2() self.failUnless(isinstance(a, Array.Array2)) self.failUnless(len(a) == 0) def testConstructor1(self): "Test Array2 nrows, ncols constructor" self.failUnless(isinstance(self.array2, Array.Array2)) def testConstructor2(self): "Test Array2 array constructor" na = np.zeros((3, 4), dtype="l") aa = Array.Array2(na) self.failUnless(isinstance(aa, Array.Array2)) def testConstructor3(self): "Test Array2 copy constructor" for i in range(self.nrows): for j in range(self.ncols): self.array2[i][j] = i * j arrayCopy = Array.Array2(self.array2) self.failUnless(arrayCopy == self.array2) def testConstructorBad1(self): "Test Array2 nrows, ncols constructor, negative nrows" self.assertRaises(ValueError, Array.Array2, -4, 4) def testConstructorBad2(self): "Test Array2 nrows, ncols constructor, negative ncols" self.assertRaises(ValueError, Array.Array2, 4, -4) def testNrows(self): "Test Array2 nrows method" self.failUnless(self.array2.nrows() == self.nrows) def testNcols(self): "Test Array2 ncols method" self.failUnless(self.array2.ncols() == self.ncols) def testLen(self): "Test Array2 __len__ method" self.failUnless(len(self.array2) == self.nrows*self.ncols) def testResize0(self): "Test Array2 resize method, size" newRows = 2 * self.nrows newCols = 2 * self.ncols self.array2.resize(newRows, newCols) self.failUnless(len(self.array2) == newRows * newCols) def testResize1(self): "Test Array2 resize method, array" a = np.zeros((2*self.nrows, 2*self.ncols), dtype='l') self.array2.resize(a) self.failUnless(len(self.array2) == a.size) def testResizeBad1(self): "Test Array2 resize method, negative nrows" self.assertRaises(ValueError, self.array2.resize, -5, 5) def testResizeBad2(self): "Test Array2 resize method, negative ncols" self.assertRaises(ValueError, self.array2.resize, 5, -5) def testSetGet1(self): "Test Array2 __setitem__, __getitem__ methods" m = self.nrows n = self.ncols array1 = [ ] a = np.arange(n, dtype="l") for i in range(m): array1.append(Array.Array1(i*a)) for i in range(m): self.array2[i] = array1[i] for i in range(m): self.failUnless(self.array2[i] == array1[i]) def testSetGet2(self): "Test Array2 chained __setitem__, __getitem__ methods" m = self.nrows n = self.ncols for i in range(m): for j in range(n): self.array2[i][j] = i*j for i in range(m): for j in range(n): self.failUnless(self.array2[i][j] == i*j) def testSetBad1(self): "Test Array2 __setitem__ method, negative index" a = Array.Array1(self.ncols) self.assertRaises(IndexError, self.array2.__setitem__, -1, a) def testSetBad2(self): "Test Array2 __setitem__ method, out-of-range index" a = Array.Array1(self.ncols) self.assertRaises(IndexError, self.array2.__setitem__, self.nrows+1, a) def testGetBad1(self): "Test Array2 __getitem__ method, negative index" self.assertRaises(IndexError, self.array2.__getitem__, -1) def testGetBad2(self): "Test Array2 __getitem__ method, out-of-range index" self.assertRaises(IndexError, self.array2.__getitem__, self.nrows+1) def testAsString(self): "Test Array2 asString method" result = """\ [ [ 0, 1, 2, 3 ], [ 1, 2, 3, 4 ], [ 2, 3, 4, 5 ], [ 3, 4, 5, 6 ], [ 4, 5, 6, 7 ] ] """ for i in range(self.nrows): for j in range(self.ncols): self.array2[i][j] = i+j self.failUnless(self.array2.asString() == result) def testStr(self): "Test Array2 __str__ method" result = """\ [ [ 0, -1, -2, -3 ], [ 1, 0, -1, -2 ], [ 2, 1, 0, -1 ], [ 3, 2, 1, 0 ], [ 4, 3, 2, 1 ] ] """ for i in range(self.nrows): for j in range(self.ncols): self.array2[i][j] = i-j self.failUnless(str(self.array2) == result) def testView(self): "Test Array2 view method" a = self.array2.view() self.failUnless(isinstance(a, np.ndarray)) self.failUnless(len(a) == self.nrows) ###################################################################### if __name__ == "__main__": # Build the test suite suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(Array1TestCase)) suite.addTest(unittest.makeSuite(Array2TestCase)) # Execute the test suite print("Testing Classes of Module Array") print("NumPy version", np.__version__) print() result = unittest.TextTestRunner(verbosity=2).run(suite) sys.exit(len(result.errors) + len(result.failures)) numpy-1.8.2/doc/swig/test/Matrix.h0000664000175100017510000000424212370216243020140 0ustar vagrantvagrant00000000000000#ifndef MATRIX_H #define MATRIX_H // The following macro defines the prototypes for a family of // functions that work with 2D arrays with the forms // // TYPE SNAMEDet( TYPE matrix[2][2]); // TYPE SNAMEMax( TYPE * matrix, int rows, int cols); // TYPE SNAMEMin( int rows, int cols, TYPE * matrix); // void SNAMEScale( TYPE array[3][3]); // void SNAMEFloor( TYPE * array, int rows, int cols, TYPE floor); // void SNAMECeil( int rows, int cols, TYPE * array, TYPE ceil ); // void SNAMELUSplit(TYPE in[3][3], TYPE lower[3][3], TYPE upper[3][3]); // // for any specified type TYPE (for example: short, unsigned int, long // long, etc.) with given short name SNAME (for example: short, uint, // longLong, etc.). The macro is then expanded for the given // TYPE/SNAME pairs. The resulting functions are for testing numpy // interfaces, respectively, for: // // * 2D input arrays, hard-coded lengths // * 2D input arrays // * 2D input arrays, data last // * 2D in-place arrays, hard-coded lengths // * 2D in-place arrays // * 2D in-place arrays, data last // * 2D argout arrays, hard-coded length // #define TEST_FUNC_PROTOS(TYPE, SNAME) \ \ TYPE SNAME ## Det( TYPE matrix[2][2]); \ TYPE SNAME ## Max( TYPE * matrix, int rows, int cols); \ TYPE SNAME ## Min( int rows, int cols, TYPE * matrix); \ void SNAME ## Scale( TYPE array[3][3], TYPE val); \ void SNAME ## Floor( TYPE * array, int rows, int cols, TYPE floor); \ void SNAME ## Ceil( int rows, int cols, TYPE * array, TYPE ceil ); \ void SNAME ## LUSplit(TYPE matrix[3][3], TYPE lower[3][3], TYPE upper[3][3]); TEST_FUNC_PROTOS(signed char , schar ) TEST_FUNC_PROTOS(unsigned char , uchar ) TEST_FUNC_PROTOS(short , short ) TEST_FUNC_PROTOS(unsigned short , ushort ) TEST_FUNC_PROTOS(int , int ) TEST_FUNC_PROTOS(unsigned int , uint ) TEST_FUNC_PROTOS(long , long ) TEST_FUNC_PROTOS(unsigned long , ulong ) TEST_FUNC_PROTOS(long long , longLong ) TEST_FUNC_PROTOS(unsigned long long, ulongLong) TEST_FUNC_PROTOS(float , float ) TEST_FUNC_PROTOS(double , double ) #endif numpy-1.8.2/doc/swig/test/Vector.cxx0000664000175100017510000000706412370216243020516 0ustar vagrantvagrant00000000000000#include #include #include #include "Vector.h" // The following macro defines a family of functions that work with 1D // arrays with the forms // // TYPE SNAMELength( TYPE vector[3]); // TYPE SNAMEProd( TYPE * series, int size); // TYPE SNAMESum( int size, TYPE * series); // void SNAMEReverse(TYPE array[3]); // void SNAMEOnes( TYPE * array, int size); // void SNAMEZeros( int size, TYPE * array); // void SNAMEEOSplit(TYPE vector[3], TYPE even[3], odd[3]); // void SNAMETwos( TYPE * twoVec, int size); // void SNAMEThrees( int size, TYPE * threeVec); // // for any specified type TYPE (for example: short, unsigned int, long // long, etc.) with given short name SNAME (for example: short, uint, // longLong, etc.). The macro is then expanded for the given // TYPE/SNAME pairs. The resulting functions are for testing numpy // interfaces, respectively, for: // // * 1D input arrays, hard-coded length // * 1D input arrays // * 1D input arrays, data last // * 1D in-place arrays, hard-coded length // * 1D in-place arrays // * 1D in-place arrays, data last // * 1D argout arrays, hard-coded length // * 1D argout arrays // * 1D argout arrays, data last // #define TEST_FUNCS(TYPE, SNAME) \ \ TYPE SNAME ## Length(TYPE vector[3]) { \ double result = 0; \ for (int i=0; i<3; ++i) result += vector[i]*vector[i]; \ return (TYPE)sqrt(result); \ } \ \ TYPE SNAME ## Prod(TYPE * series, int size) { \ TYPE result = 1; \ for (int i=0; i #include class Array1 { public: // Default/length/array constructor Array1(int length = 0, long* data = 0); // Copy constructor Array1(const Array1 & source); // Destructor ~Array1(); // Assignment operator Array1 & operator=(const Array1 & source); // Equals operator bool operator==(const Array1 & other) const; // Length accessor int length() const; // Resize array void resize(int length, long* data = 0); // Set item accessor long & operator[](int i); // Get item accessor const long & operator[](int i) const; // String output std::string asString() const; // Get view void view(long** data, int* length) const; private: // Members bool _ownData; int _length; long * _buffer; // Methods void allocateMemory(); void deallocateMemory(); }; #endif numpy-1.8.2/doc/swig/test/Matrix.cxx0000664000175100017510000001203112370216243020506 0ustar vagrantvagrant00000000000000#include #include #include #include "Matrix.h" // The following macro defines a family of functions that work with 2D // arrays with the forms // // TYPE SNAMEDet( TYPE matrix[2][2]); // TYPE SNAMEMax( TYPE * matrix, int rows, int cols); // TYPE SNAMEMin( int rows, int cols, TYPE * matrix); // void SNAMEScale( TYPE matrix[3][3]); // void SNAMEFloor( TYPE * array, int rows, int cols, TYPE floor); // void SNAMECeil( int rows, int cols, TYPE * array, TYPE ceil); // void SNAMELUSplit(TYPE in[3][3], TYPE lower[3][3], TYPE upper[3][3]); // // for any specified type TYPE (for example: short, unsigned int, long // long, etc.) with given short name SNAME (for example: short, uint, // longLong, etc.). The macro is then expanded for the given // TYPE/SNAME pairs. The resulting functions are for testing numpy // interfaces, respectively, for: // // * 2D input arrays, hard-coded length // * 2D input arrays // * 2D input arrays, data last // * 2D in-place arrays, hard-coded lengths // * 2D in-place arrays // * 2D in-place arrays, data last // * 2D argout arrays, hard-coded length // #define TEST_FUNCS(TYPE, SNAME) \ \ TYPE SNAME ## Det(TYPE matrix[2][2]) { \ return matrix[0][0]*matrix[1][1] - matrix[0][1]*matrix[1][0]; \ } \ \ TYPE SNAME ## Max(TYPE * matrix, int rows, int cols) { \ int i, j, index; \ TYPE result = matrix[0]; \ for (j=0; j result) result = matrix[index]; \ } \ } \ return result; \ } \ \ TYPE SNAME ## Min(int rows, int cols, TYPE * matrix) { \ int i, j, index; \ TYPE result = matrix[0]; \ for (j=0; j ceil) array[index] = ceil; \ } \ } \ } \ \ void SNAME ## LUSplit(TYPE matrix[3][3], TYPE lower[3][3], TYPE upper[3][3]) { \ for (int i=0; i<3; ++i) { \ for (int j=0; j<3; ++j) { \ if (i >= j) { \ lower[i][j] = matrix[i][j]; \ upper[i][j] = 0; \ } else { \ lower[i][j] = 0; \ upper[i][j] = matrix[i][j]; \ } \ } \ } \ } TEST_FUNCS(signed char , schar ) TEST_FUNCS(unsigned char , uchar ) TEST_FUNCS(short , short ) TEST_FUNCS(unsigned short , ushort ) TEST_FUNCS(int , int ) TEST_FUNCS(unsigned int , uint ) TEST_FUNCS(long , long ) TEST_FUNCS(unsigned long , ulong ) TEST_FUNCS(long long , longLong ) TEST_FUNCS(unsigned long long, ulongLong) TEST_FUNCS(float , float ) TEST_FUNCS(double , double ) numpy-1.8.2/doc/swig/test/SuperTensor.h0000664000175100017510000000470412370216243021170 0ustar vagrantvagrant00000000000000#ifndef SUPERTENSOR_H #define SUPERTENSOR_H // The following macro defines the prototypes for a family of // functions that work with 4D arrays with the forms // // TYPE SNAMENorm( TYPE supertensor[2][2][2][2]); // TYPE SNAMEMax( TYPE * supertensor, int cubes, int slices, int rows, int cols); // TYPE SNAMEMin( int cubes, int slices, int rows, int cols, TYPE * supertensor); // void SNAMEScale( TYPE array[3][3][3][3]); // void SNAMEFloor( TYPE * array, int cubes, int slices, int rows, int cols, TYPE floor); // void SNAMECeil( int cubes, int slices, int rows, int cols, TYPE * array, TYPE ceil ); // void SNAMELUSplit(TYPE in[3][3][3][3], TYPE lower[3][3][3][3], TYPE upper[3][3][3][3]); // // for any specified type TYPE (for example: short, unsigned int, long // long, etc.) with given short name SNAME (for example: short, uint, // longLong, etc.). The macro is then expanded for the given // TYPE/SNAME pairs. The resulting functions are for testing numpy // interfaces, respectively, for: // // * 4D input arrays, hard-coded lengths // * 4D input arrays // * 4D input arrays, data last // * 4D in-place arrays, hard-coded lengths // * 4D in-place arrays // * 4D in-place arrays, data last // * 4D argout arrays, hard-coded length // #define TEST_FUNC_PROTOS(TYPE, SNAME) \ \ TYPE SNAME ## Norm( TYPE supertensor[2][2][2][2]); \ TYPE SNAME ## Max( TYPE * supertensor, int cubes, int slices, int rows, int cols); \ TYPE SNAME ## Min( int cubes, int slices, int rows, int cols, TYPE * supertensor); \ void SNAME ## Scale( TYPE array[3][3][3][3], TYPE val); \ void SNAME ## Floor( TYPE * array, int cubes, int slices, int rows, int cols, TYPE floor); \ void SNAME ## Ceil( int cubes, int slices, int rows, int cols, TYPE * array, TYPE ceil ); \ void SNAME ## LUSplit(TYPE supertensor[2][2][2][2], TYPE lower[2][2][2][2], TYPE upper[2][2][2][2]); TEST_FUNC_PROTOS(signed char , schar ) TEST_FUNC_PROTOS(unsigned char , uchar ) TEST_FUNC_PROTOS(short , short ) TEST_FUNC_PROTOS(unsigned short , ushort ) TEST_FUNC_PROTOS(int , int ) TEST_FUNC_PROTOS(unsigned int , uint ) TEST_FUNC_PROTOS(long , long ) TEST_FUNC_PROTOS(unsigned long , ulong ) TEST_FUNC_PROTOS(long long , longLong ) TEST_FUNC_PROTOS(unsigned long long, ulongLong) TEST_FUNC_PROTOS(float , float ) TEST_FUNC_PROTOS(double , double ) #endif numpy-1.8.2/doc/swig/test/testFarray.py0000775000175100017510000001205012370216243021220 0ustar vagrantvagrant00000000000000#! /usr/bin/env python from __future__ import division, absolute_import, print_function # System imports from distutils.util import get_platform import os import sys import unittest # Import NumPy import numpy as np major, minor = [ int(d) for d in np.__version__.split(".")[:2] ] if major == 0: BadListError = TypeError else: BadListError = ValueError # Add the distutils-generated build directory to the python search path and then # import the extension module libDir = "lib.%s-%s" % (get_platform(), sys.version[:3]) sys.path.insert(0, os.path.join("build", libDir)) import Farray ###################################################################### class FarrayTestCase(unittest.TestCase): def setUp(self): self.nrows = 5 self.ncols = 4 self.array = Farray.Farray(self.nrows, self.ncols) def testConstructor1(self): "Test Farray size constructor" self.failUnless(isinstance(self.array, Farray.Farray)) def testConstructor2(self): "Test Farray copy constructor" for i in range(self.nrows): for j in range(self.ncols): self.array[i, j] = i + j arrayCopy = Farray.Farray(self.array) self.failUnless(arrayCopy == self.array) def testConstructorBad1(self): "Test Farray size constructor, negative nrows" self.assertRaises(ValueError, Farray.Farray, -4, 4) def testConstructorBad2(self): "Test Farray size constructor, negative ncols" self.assertRaises(ValueError, Farray.Farray, 4, -4) def testNrows(self): "Test Farray nrows method" self.failUnless(self.array.nrows() == self.nrows) def testNcols(self): "Test Farray ncols method" self.failUnless(self.array.ncols() == self.ncols) def testLen(self): "Test Farray __len__ method" self.failUnless(len(self.array) == self.nrows*self.ncols) def testSetGet(self): "Test Farray __setitem__, __getitem__ methods" m = self.nrows n = self.ncols for i in range(m): for j in range(n): self.array[i, j] = i*j for i in range(m): for j in range(n): self.failUnless(self.array[i, j] == i*j) def testSetBad1(self): "Test Farray __setitem__ method, negative row" self.assertRaises(IndexError, self.array.__setitem__, (-1, 3), 0) def testSetBad2(self): "Test Farray __setitem__ method, negative col" self.assertRaises(IndexError, self.array.__setitem__, (1, -3), 0) def testSetBad3(self): "Test Farray __setitem__ method, out-of-range row" self.assertRaises(IndexError, self.array.__setitem__, (self.nrows+1, 0), 0) def testSetBad4(self): "Test Farray __setitem__ method, out-of-range col" self.assertRaises(IndexError, self.array.__setitem__, (0, self.ncols+1), 0) def testGetBad1(self): "Test Farray __getitem__ method, negative row" self.assertRaises(IndexError, self.array.__getitem__, (-1, 3)) def testGetBad2(self): "Test Farray __getitem__ method, negative col" self.assertRaises(IndexError, self.array.__getitem__, (1, -3)) def testGetBad3(self): "Test Farray __getitem__ method, out-of-range row" self.assertRaises(IndexError, self.array.__getitem__, (self.nrows+1, 0)) def testGetBad4(self): "Test Farray __getitem__ method, out-of-range col" self.assertRaises(IndexError, self.array.__getitem__, (0, self.ncols+1)) def testAsString(self): "Test Farray asString method" result = """\ [ [ 0, 1, 2, 3 ], [ 1, 2, 3, 4 ], [ 2, 3, 4, 5 ], [ 3, 4, 5, 6 ], [ 4, 5, 6, 7 ] ] """ for i in range(self.nrows): for j in range(self.ncols): self.array[i, j] = i+j self.failUnless(self.array.asString() == result) def testStr(self): "Test Farray __str__ method" result = """\ [ [ 0, -1, -2, -3 ], [ 1, 0, -1, -2 ], [ 2, 1, 0, -1 ], [ 3, 2, 1, 0 ], [ 4, 3, 2, 1 ] ] """ for i in range(self.nrows): for j in range(self.ncols): self.array[i, j] = i-j self.failUnless(str(self.array) == result) def testView(self): "Test Farray view method" for i in range(self.nrows): for j in range(self.ncols): self.array[i, j] = i+j a = self.array.view() self.failUnless(isinstance(a, np.ndarray)) self.failUnless(a.flags.f_contiguous) for i in range(self.nrows): for j in range(self.ncols): self.failUnless(a[i, j] == i+j) ###################################################################### if __name__ == "__main__": # Build the test suite suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(FarrayTestCase)) # Execute the test suite print("Testing Classes of Module Farray") print("NumPy version", np.__version__) print() result = unittest.TextTestRunner(verbosity=2).run(suite) sys.exit(len(result.errors) + len(result.failures)) numpy-1.8.2/doc/swig/test/Makefile0000664000175100017510000000143512370216243020164 0ustar vagrantvagrant00000000000000# SWIG INTERFACES = Array.i Farray.i Vector.i Matrix.i Tensor.i Fortran.i WRAPPERS = $(INTERFACES:.i=_wrap.cxx) PROXIES = $(INTERFACES:.i=.py ) # Default target: build the tests .PHONY : all all: $(WRAPPERS) Array1.cxx Array1.h Farray.cxx Farray.h Vector.cxx Vector.h \ Matrix.cxx Matrix.h Tensor.cxx Tensor.h Fortran.h Fortran.cxx ./setup.py build_ext -i # Test target: run the tests .PHONY : test test: all python testVector.py python testMatrix.py python testTensor.py python testArray.py python testFarray.py python testFortran.py # Rule: %.i -> %_wrap.cxx %_wrap.cxx: %.i %.h ../numpy.i swig -c++ -python $< %_wrap.cxx: %.i %1.h %2.h ../numpy.i swig -c++ -python $< # Clean target .PHONY : clean clean: $(RM) -r build $(RM) *.so $(RM) $(WRAPPERS) $(RM) $(PROXIES) numpy-1.8.2/doc/swig/test/testVector.py0000775000175100017510000003525612370216243021253 0ustar vagrantvagrant00000000000000#! /usr/bin/env python from __future__ import division, absolute_import, print_function # System imports from distutils.util import get_platform import os import sys import unittest # Import NumPy import numpy as np major, minor = [ int(d) for d in np.__version__.split(".")[:2] ] if major == 0: BadListError = TypeError else: BadListError = ValueError import Vector ###################################################################### class VectorTestCase(unittest.TestCase): def __init__(self, methodName="runTest"): unittest.TestCase.__init__(self, methodName) self.typeStr = "double" self.typeCode = "d" # Test the (type IN_ARRAY1[ANY]) typemap def testLength(self): "Test length function" print(self.typeStr, "... ", end=' ', file=sys.stderr) length = Vector.__dict__[self.typeStr + "Length"] self.assertEquals(length([5, 12, 0]), 13) # Test the (type IN_ARRAY1[ANY]) typemap def testLengthBadList(self): "Test length function with bad list" print(self.typeStr, "... ", end=' ', file=sys.stderr) length = Vector.__dict__[self.typeStr + "Length"] self.assertRaises(BadListError, length, [5, "twelve", 0]) # Test the (type IN_ARRAY1[ANY]) typemap def testLengthWrongSize(self): "Test length function with wrong size" print(self.typeStr, "... ", end=' ', file=sys.stderr) length = Vector.__dict__[self.typeStr + "Length"] self.assertRaises(TypeError, length, [5, 12]) # Test the (type IN_ARRAY1[ANY]) typemap def testLengthWrongDim(self): "Test length function with wrong dimensions" print(self.typeStr, "... ", end=' ', file=sys.stderr) length = Vector.__dict__[self.typeStr + "Length"] self.assertRaises(TypeError, length, [[1, 2], [3, 4]]) # Test the (type IN_ARRAY1[ANY]) typemap def testLengthNonContainer(self): "Test length function with non-container" print(self.typeStr, "... ", end=' ', file=sys.stderr) length = Vector.__dict__[self.typeStr + "Length"] self.assertRaises(TypeError, length, None) # Test the (type* IN_ARRAY1, int DIM1) typemap def testProd(self): "Test prod function" print(self.typeStr, "... ", end=' ', file=sys.stderr) prod = Vector.__dict__[self.typeStr + "Prod"] self.assertEquals(prod([1, 2, 3, 4]), 24) # Test the (type* IN_ARRAY1, int DIM1) typemap def testProdBadList(self): "Test prod function with bad list" print(self.typeStr, "... ", end=' ', file=sys.stderr) prod = Vector.__dict__[self.typeStr + "Prod"] self.assertRaises(BadListError, prod, [[1, "two"], ["e", "pi"]]) # Test the (type* IN_ARRAY1, int DIM1) typemap def testProdWrongDim(self): "Test prod function with wrong dimensions" print(self.typeStr, "... ", end=' ', file=sys.stderr) prod = Vector.__dict__[self.typeStr + "Prod"] self.assertRaises(TypeError, prod, [[1, 2], [8, 9]]) # Test the (type* IN_ARRAY1, int DIM1) typemap def testProdNonContainer(self): "Test prod function with non-container" print(self.typeStr, "... ", end=' ', file=sys.stderr) prod = Vector.__dict__[self.typeStr + "Prod"] self.assertRaises(TypeError, prod, None) # Test the (int DIM1, type* IN_ARRAY1) typemap def testSum(self): "Test sum function" print(self.typeStr, "... ", end=' ', file=sys.stderr) sum = Vector.__dict__[self.typeStr + "Sum"] self.assertEquals(sum([5, 6, 7, 8]), 26) # Test the (int DIM1, type* IN_ARRAY1) typemap def testSumBadList(self): "Test sum function with bad list" print(self.typeStr, "... ", end=' ', file=sys.stderr) sum = Vector.__dict__[self.typeStr + "Sum"] self.assertRaises(BadListError, sum, [3, 4, 5, "pi"]) # Test the (int DIM1, type* IN_ARRAY1) typemap def testSumWrongDim(self): "Test sum function with wrong dimensions" print(self.typeStr, "... ", end=' ', file=sys.stderr) sum = Vector.__dict__[self.typeStr + "Sum"] self.assertRaises(TypeError, sum, [[3, 4], [5, 6]]) # Test the (int DIM1, type* IN_ARRAY1) typemap def testSumNonContainer(self): "Test sum function with non-container" print(self.typeStr, "... ", end=' ', file=sys.stderr) sum = Vector.__dict__[self.typeStr + "Sum"] self.assertRaises(TypeError, sum, True) # Test the (type INPLACE_ARRAY1[ANY]) typemap def testReverse(self): "Test reverse function" print(self.typeStr, "... ", end=' ', file=sys.stderr) reverse = Vector.__dict__[self.typeStr + "Reverse"] vector = np.array([1, 2, 4], self.typeCode) reverse(vector) self.assertEquals((vector == [4, 2, 1]).all(), True) # Test the (type INPLACE_ARRAY1[ANY]) typemap def testReverseWrongDim(self): "Test reverse function with wrong dimensions" print(self.typeStr, "... ", end=' ', file=sys.stderr) reverse = Vector.__dict__[self.typeStr + "Reverse"] vector = np.array([[1, 2], [3, 4]], self.typeCode) self.assertRaises(TypeError, reverse, vector) # Test the (type INPLACE_ARRAY1[ANY]) typemap def testReverseWrongSize(self): "Test reverse function with wrong size" print(self.typeStr, "... ", end=' ', file=sys.stderr) reverse = Vector.__dict__[self.typeStr + "Reverse"] vector = np.array([9, 8, 7, 6, 5, 4], self.typeCode) self.assertRaises(TypeError, reverse, vector) # Test the (type INPLACE_ARRAY1[ANY]) typemap def testReverseWrongType(self): "Test reverse function with wrong type" print(self.typeStr, "... ", end=' ', file=sys.stderr) reverse = Vector.__dict__[self.typeStr + "Reverse"] vector = np.array([1, 2, 4], 'c') self.assertRaises(TypeError, reverse, vector) # Test the (type INPLACE_ARRAY1[ANY]) typemap def testReverseNonArray(self): "Test reverse function with non-array" print(self.typeStr, "... ", end=' ', file=sys.stderr) reverse = Vector.__dict__[self.typeStr + "Reverse"] self.assertRaises(TypeError, reverse, [2, 4, 6]) # Test the (type* INPLACE_ARRAY1, int DIM1) typemap def testOnes(self): "Test ones function" print(self.typeStr, "... ", end=' ', file=sys.stderr) ones = Vector.__dict__[self.typeStr + "Ones"] vector = np.zeros(5, self.typeCode) ones(vector) np.testing.assert_array_equal(vector, np.array([1, 1, 1, 1, 1])) # Test the (type* INPLACE_ARRAY1, int DIM1) typemap def testOnesWrongDim(self): "Test ones function with wrong dimensions" print(self.typeStr, "... ", end=' ', file=sys.stderr) ones = Vector.__dict__[self.typeStr + "Ones"] vector = np.zeros((5, 5), self.typeCode) self.assertRaises(TypeError, ones, vector) # Test the (type* INPLACE_ARRAY1, int DIM1) typemap def testOnesWrongType(self): "Test ones function with wrong type" print(self.typeStr, "... ", end=' ', file=sys.stderr) ones = Vector.__dict__[self.typeStr + "Ones"] vector = np.zeros((5, 5), 'c') self.assertRaises(TypeError, ones, vector) # Test the (type* INPLACE_ARRAY1, int DIM1) typemap def testOnesNonArray(self): "Test ones function with non-array" print(self.typeStr, "... ", end=' ', file=sys.stderr) ones = Vector.__dict__[self.typeStr + "Ones"] self.assertRaises(TypeError, ones, [2, 4, 6, 8]) # Test the (int DIM1, type* INPLACE_ARRAY1) typemap def testZeros(self): "Test zeros function" print(self.typeStr, "... ", end=' ', file=sys.stderr) zeros = Vector.__dict__[self.typeStr + "Zeros"] vector = np.ones(5, self.typeCode) zeros(vector) np.testing.assert_array_equal(vector, np.array([0, 0, 0, 0, 0])) # Test the (int DIM1, type* INPLACE_ARRAY1) typemap def testZerosWrongDim(self): "Test zeros function with wrong dimensions" print(self.typeStr, "... ", end=' ', file=sys.stderr) zeros = Vector.__dict__[self.typeStr + "Zeros"] vector = np.ones((5, 5), self.typeCode) self.assertRaises(TypeError, zeros, vector) # Test the (int DIM1, type* INPLACE_ARRAY1) typemap def testZerosWrongType(self): "Test zeros function with wrong type" print(self.typeStr, "... ", end=' ', file=sys.stderr) zeros = Vector.__dict__[self.typeStr + "Zeros"] vector = np.ones(6, 'c') self.assertRaises(TypeError, zeros, vector) # Test the (int DIM1, type* INPLACE_ARRAY1) typemap def testZerosNonArray(self): "Test zeros function with non-array" print(self.typeStr, "... ", end=' ', file=sys.stderr) zeros = Vector.__dict__[self.typeStr + "Zeros"] self.assertRaises(TypeError, zeros, [1, 3, 5, 7, 9]) # Test the (type ARGOUT_ARRAY1[ANY]) typemap def testEOSplit(self): "Test eoSplit function" print(self.typeStr, "... ", end=' ', file=sys.stderr) eoSplit = Vector.__dict__[self.typeStr + "EOSplit"] even, odd = eoSplit([1, 2, 3]) self.assertEquals((even == [1, 0, 3]).all(), True) self.assertEquals((odd == [0, 2, 0]).all(), True) # Test the (type* ARGOUT_ARRAY1, int DIM1) typemap def testTwos(self): "Test twos function" print(self.typeStr, "... ", end=' ', file=sys.stderr) twos = Vector.__dict__[self.typeStr + "Twos"] vector = twos(5) self.assertEquals((vector == [2, 2, 2, 2, 2]).all(), True) # Test the (type* ARGOUT_ARRAY1, int DIM1) typemap def testTwosNonInt(self): "Test twos function with non-integer dimension" print(self.typeStr, "... ", end=' ', file=sys.stderr) twos = Vector.__dict__[self.typeStr + "Twos"] self.assertRaises(TypeError, twos, 5.0) # Test the (int DIM1, type* ARGOUT_ARRAY1) typemap def testThrees(self): "Test threes function" print(self.typeStr, "... ", end=' ', file=sys.stderr) threes = Vector.__dict__[self.typeStr + "Threes"] vector = threes(6) self.assertEquals((vector == [3, 3, 3, 3, 3, 3]).all(), True) # Test the (type* ARGOUT_ARRAY1, int DIM1) typemap def testThreesNonInt(self): "Test threes function with non-integer dimension" print(self.typeStr, "... ", end=' ', file=sys.stderr) threes = Vector.__dict__[self.typeStr + "Threes"] self.assertRaises(TypeError, threes, "threes") ###################################################################### class scharTestCase(VectorTestCase): def __init__(self, methodName="runTest"): VectorTestCase.__init__(self, methodName) self.typeStr = "schar" self.typeCode = "b" ###################################################################### class ucharTestCase(VectorTestCase): def __init__(self, methodName="runTest"): VectorTestCase.__init__(self, methodName) self.typeStr = "uchar" self.typeCode = "B" ###################################################################### class shortTestCase(VectorTestCase): def __init__(self, methodName="runTest"): VectorTestCase.__init__(self, methodName) self.typeStr = "short" self.typeCode = "h" ###################################################################### class ushortTestCase(VectorTestCase): def __init__(self, methodName="runTest"): VectorTestCase.__init__(self, methodName) self.typeStr = "ushort" self.typeCode = "H" ###################################################################### class intTestCase(VectorTestCase): def __init__(self, methodName="runTest"): VectorTestCase.__init__(self, methodName) self.typeStr = "int" self.typeCode = "i" ###################################################################### class uintTestCase(VectorTestCase): def __init__(self, methodName="runTest"): VectorTestCase.__init__(self, methodName) self.typeStr = "uint" self.typeCode = "I" ###################################################################### class longTestCase(VectorTestCase): def __init__(self, methodName="runTest"): VectorTestCase.__init__(self, methodName) self.typeStr = "long" self.typeCode = "l" ###################################################################### class ulongTestCase(VectorTestCase): def __init__(self, methodName="runTest"): VectorTestCase.__init__(self, methodName) self.typeStr = "ulong" self.typeCode = "L" ###################################################################### class longLongTestCase(VectorTestCase): def __init__(self, methodName="runTest"): VectorTestCase.__init__(self, methodName) self.typeStr = "longLong" self.typeCode = "q" ###################################################################### class ulongLongTestCase(VectorTestCase): def __init__(self, methodName="runTest"): VectorTestCase.__init__(self, methodName) self.typeStr = "ulongLong" self.typeCode = "Q" ###################################################################### class floatTestCase(VectorTestCase): def __init__(self, methodName="runTest"): VectorTestCase.__init__(self, methodName) self.typeStr = "float" self.typeCode = "f" ###################################################################### class doubleTestCase(VectorTestCase): def __init__(self, methodName="runTest"): VectorTestCase.__init__(self, methodName) self.typeStr = "double" self.typeCode = "d" ###################################################################### if __name__ == "__main__": # Build the test suite suite = unittest.TestSuite() suite.addTest(unittest.makeSuite( scharTestCase)) suite.addTest(unittest.makeSuite( ucharTestCase)) suite.addTest(unittest.makeSuite( shortTestCase)) suite.addTest(unittest.makeSuite( ushortTestCase)) suite.addTest(unittest.makeSuite( intTestCase)) suite.addTest(unittest.makeSuite( uintTestCase)) suite.addTest(unittest.makeSuite( longTestCase)) suite.addTest(unittest.makeSuite( ulongTestCase)) suite.addTest(unittest.makeSuite( longLongTestCase)) suite.addTest(unittest.makeSuite(ulongLongTestCase)) suite.addTest(unittest.makeSuite( floatTestCase)) suite.addTest(unittest.makeSuite( doubleTestCase)) # Execute the test suite print("Testing 1D Functions of Module Vector") print("NumPy version", np.__version__) print() result = unittest.TextTestRunner(verbosity=2).run(suite) sys.exit(len(result.errors) + len(result.failures)) numpy-1.8.2/doc/swig/numpy.i0000664000175100017510000031577212370216243017103 0ustar vagrantvagrant00000000000000/* -*- C -*- (not really, but good for syntax highlighting) */ #ifdef SWIGPYTHON %{ #ifndef SWIG_FILE_WITH_INIT #define NO_IMPORT_ARRAY #endif #include "stdio.h" #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION #include %} /**********************************************************************/ %fragment("NumPy_Backward_Compatibility", "header") { %#if NPY_API_VERSION < 0x00000007 %#define NPY_ARRAY_DEFAULT NPY_DEFAULT %#define NPY_ARRAY_FARRAY NPY_FARRAY %#define NPY_FORTRANORDER NPY_FORTRAN %#endif } /**********************************************************************/ /* The following code originally appeared in * enthought/kiva/agg/src/numeric.i written by Eric Jones. It was * translated from C++ to C by John Hunter. Bill Spotz has modified * it to fix some minor bugs, upgrade from Numeric to numpy (all * versions), add some comments and functionality, and convert from * direct code insertion to SWIG fragments. */ %fragment("NumPy_Macros", "header") { /* Macros to extract array attributes. */ %#if NPY_API_VERSION < 0x00000007 %#define is_array(a) ((a) && PyArray_Check((PyArrayObject*)a)) %#define array_type(a) (int)(PyArray_TYPE((PyArrayObject*)a)) %#define array_numdims(a) (((PyArrayObject*)a)->nd) %#define array_dimensions(a) (((PyArrayObject*)a)->dimensions) %#define array_size(a,i) (((PyArrayObject*)a)->dimensions[i]) %#define array_strides(a) (((PyArrayObject*)a)->strides) %#define array_stride(a,i) (((PyArrayObject*)a)->strides[i]) %#define array_data(a) (((PyArrayObject*)a)->data) %#define array_descr(a) (((PyArrayObject*)a)->descr) %#define array_flags(a) (((PyArrayObject*)a)->flags) %#define array_enableflags(a,f) (((PyArrayObject*)a)->flags) = f %#else %#define is_array(a) ((a) && PyArray_Check(a)) %#define array_type(a) PyArray_TYPE((PyArrayObject*)a) %#define array_numdims(a) PyArray_NDIM((PyArrayObject*)a) %#define array_dimensions(a) PyArray_DIMS((PyArrayObject*)a) %#define array_strides(a) PyArray_STRIDES((PyArrayObject*)a) %#define array_stride(a,i) PyArray_STRIDE((PyArrayObject*)a,i) %#define array_size(a,i) PyArray_DIM((PyArrayObject*)a,i) %#define array_data(a) PyArray_DATA((PyArrayObject*)a) %#define array_descr(a) PyArray_DESCR((PyArrayObject*)a) %#define array_flags(a) PyArray_FLAGS((PyArrayObject*)a) %#define array_enableflags(a,f) PyArray_ENABLEFLAGS((PyArrayObject*)a,f) %#endif %#define array_is_contiguous(a) (PyArray_ISCONTIGUOUS((PyArrayObject*)a)) %#define array_is_native(a) (PyArray_ISNOTSWAPPED((PyArrayObject*)a)) %#define array_is_fortran(a) (PyArray_ISFORTRAN((PyArrayObject*)a)) } /**********************************************************************/ %fragment("NumPy_Utilities", "header") { /* Given a PyObject, return a string describing its type. */ const char* pytype_string(PyObject* py_obj) { if (py_obj == NULL ) return "C NULL value"; if (py_obj == Py_None ) return "Python None" ; if (PyCallable_Check(py_obj)) return "callable" ; if (PyString_Check( py_obj)) return "string" ; if (PyInt_Check( py_obj)) return "int" ; if (PyFloat_Check( py_obj)) return "float" ; if (PyDict_Check( py_obj)) return "dict" ; if (PyList_Check( py_obj)) return "list" ; if (PyTuple_Check( py_obj)) return "tuple" ; %#if PY_MAJOR_VERSION < 3 if (PyFile_Check( py_obj)) return "file" ; if (PyModule_Check( py_obj)) return "module" ; if (PyInstance_Check(py_obj)) return "instance" ; %#endif return "unkown type"; } /* Given a NumPy typecode, return a string describing the type. */ const char* typecode_string(int typecode) { static const char* type_names[25] = {"bool", "byte", "unsigned byte", "short", "unsigned short", "int", "unsigned int", "long", "unsigned long", "long long", "unsigned long long", "float", "double", "long double", "complex float", "complex double", "complex long double", "object", "string", "unicode", "void", "ntypes", "notype", "char", "unknown"}; return typecode < 24 ? type_names[typecode] : type_names[24]; } /* Make sure input has correct numpy type. This now just calls PyArray_EquivTypenums(). */ int type_match(int actual_type, int desired_type) { return PyArray_EquivTypenums(actual_type, desired_type); } %#ifdef SWIGPY_USE_CAPSULE void free_cap(PyObject * cap) { void* array = (void*) PyCapsule_GetPointer(cap,SWIGPY_CAPSULE_NAME); if (array != NULL) free(array); } %#endif } /**********************************************************************/ %fragment("NumPy_Object_to_Array", "header", fragment="NumPy_Backward_Compatibility", fragment="NumPy_Macros", fragment="NumPy_Utilities") { /* Given a PyObject pointer, cast it to a PyArrayObject pointer if * legal. If not, set the python error string appropriately and * return NULL. */ PyArrayObject* obj_to_array_no_conversion(PyObject* input, int typecode) { PyArrayObject* ary = NULL; if (is_array(input) && (typecode == NPY_NOTYPE || PyArray_EquivTypenums(array_type(input), typecode))) { ary = (PyArrayObject*) input; } else if is_array(input) { const char* desired_type = typecode_string(typecode); const char* actual_type = typecode_string(array_type(input)); PyErr_Format(PyExc_TypeError, "Array of type '%s' required. Array of type '%s' given", desired_type, actual_type); ary = NULL; } else { const char* desired_type = typecode_string(typecode); const char* actual_type = pytype_string(input); PyErr_Format(PyExc_TypeError, "Array of type '%s' required. A '%s' was given", desired_type, actual_type); ary = NULL; } return ary; } /* Convert the given PyObject to a NumPy array with the given * typecode. On success, return a valid PyArrayObject* with the * correct type. On failure, the python error string will be set and * the routine returns NULL. */ PyArrayObject* obj_to_array_allow_conversion(PyObject* input, int typecode, int* is_new_object) { PyArrayObject* ary = NULL; PyObject* py_obj; if (is_array(input) && (typecode == NPY_NOTYPE || PyArray_EquivTypenums(array_type(input),typecode))) { ary = (PyArrayObject*) input; *is_new_object = 0; } else { py_obj = PyArray_FROMANY(input, typecode, 0, 0, NPY_ARRAY_DEFAULT); /* If NULL, PyArray_FromObject will have set python error value.*/ ary = (PyArrayObject*) py_obj; *is_new_object = 1; } return ary; } /* Given a PyArrayObject, check to see if it is contiguous. If so, * return the input pointer and flag it as not a new object. If it is * not contiguous, create a new PyArrayObject using the original data, * flag it as a new object and return the pointer. */ PyArrayObject* make_contiguous(PyArrayObject* ary, int* is_new_object, int min_dims, int max_dims) { PyArrayObject* result; if (array_is_contiguous(ary)) { result = ary; *is_new_object = 0; } else { result = (PyArrayObject*) PyArray_ContiguousFromObject((PyObject*)ary, array_type(ary), min_dims, max_dims); *is_new_object = 1; } return result; } /* Given a PyArrayObject, check to see if it is Fortran-contiguous. * If so, return the input pointer, but do not flag it as not a new * object. If it is not Fortran-contiguous, create a new * PyArrayObject using the original data, flag it as a new object * and return the pointer. */ PyArrayObject* make_fortran(PyArrayObject* ary, int* is_new_object) { PyArrayObject* result; if (array_is_fortran(ary)) { result = ary; *is_new_object = 0; } else { Py_INCREF(array_descr(ary)); result = (PyArrayObject*) PyArray_FromArray(ary, array_descr(ary), NPY_FORTRANORDER); *is_new_object = 1; } return result; } /* Convert a given PyObject to a contiguous PyArrayObject of the * specified type. If the input object is not a contiguous * PyArrayObject, a new one will be created and the new object flag * will be set. */ PyArrayObject* obj_to_array_contiguous_allow_conversion(PyObject* input, int typecode, int* is_new_object) { int is_new1 = 0; int is_new2 = 0; PyArrayObject* ary2; PyArrayObject* ary1 = obj_to_array_allow_conversion(input, typecode, &is_new1); if (ary1) { ary2 = make_contiguous(ary1, &is_new2, 0, 0); if ( is_new1 && is_new2) { Py_DECREF(ary1); } ary1 = ary2; } *is_new_object = is_new1 || is_new2; return ary1; } /* Convert a given PyObject to a Fortran-ordered PyArrayObject of the * specified type. If the input object is not a Fortran-ordered * PyArrayObject, a new one will be created and the new object flag * will be set. */ PyArrayObject* obj_to_array_fortran_allow_conversion(PyObject* input, int typecode, int* is_new_object) { int is_new1 = 0; int is_new2 = 0; PyArrayObject* ary2; PyArrayObject* ary1 = obj_to_array_allow_conversion(input, typecode, &is_new1); if (ary1) { ary2 = make_fortran(ary1, &is_new2); if (is_new1 && is_new2) { Py_DECREF(ary1); } ary1 = ary2; } *is_new_object = is_new1 || is_new2; return ary1; } } /* end fragment */ /**********************************************************************/ %fragment("NumPy_Array_Requirements", "header", fragment="NumPy_Backward_Compatibility", fragment="NumPy_Macros") { /* Test whether a python object is contiguous. If array is * contiguous, return 1. Otherwise, set the python error string and * return 0. */ int require_contiguous(PyArrayObject* ary) { int contiguous = 1; if (!array_is_contiguous(ary)) { PyErr_SetString(PyExc_TypeError, "Array must be contiguous. A non-contiguous array was given"); contiguous = 0; } return contiguous; } /* Require that a numpy array is not byte-swapped. If the array is * not byte-swapped, return 1. Otherwise, set the python error string * and return 0. */ int require_native(PyArrayObject* ary) { int native = 1; if (!array_is_native(ary)) { PyErr_SetString(PyExc_TypeError, "Array must have native byteorder. " "A byte-swapped array was given"); native = 0; } return native; } /* Require the given PyArrayObject to have a specified number of * dimensions. If the array has the specified number of dimensions, * return 1. Otherwise, set the python error string and return 0. */ int require_dimensions(PyArrayObject* ary, int exact_dimensions) { int success = 1; if (array_numdims(ary) != exact_dimensions) { PyErr_Format(PyExc_TypeError, "Array must have %d dimensions. Given array has %d dimensions", exact_dimensions, array_numdims(ary)); success = 0; } return success; } /* Require the given PyArrayObject to have one of a list of specified * number of dimensions. If the array has one of the specified number * of dimensions, return 1. Otherwise, set the python error string * and return 0. */ int require_dimensions_n(PyArrayObject* ary, int* exact_dimensions, int n) { int success = 0; int i; char dims_str[255] = ""; char s[255]; for (i = 0; i < n && !success; i++) { if (array_numdims(ary) == exact_dimensions[i]) { success = 1; } } if (!success) { for (i = 0; i < n-1; i++) { sprintf(s, "%d, ", exact_dimensions[i]); strcat(dims_str,s); } sprintf(s, " or %d", exact_dimensions[n-1]); strcat(dims_str,s); PyErr_Format(PyExc_TypeError, "Array must have %s dimensions. Given array has %d dimensions", dims_str, array_numdims(ary)); } return success; } /* Require the given PyArrayObject to have a specified shape. If the * array has the specified shape, return 1. Otherwise, set the python * error string and return 0. */ int require_size(PyArrayObject* ary, npy_intp* size, int n) { int i; int success = 1; int len; char desired_dims[255] = "["; char s[255]; char actual_dims[255] = "["; for(i=0; i < n;i++) { if (size[i] != -1 && size[i] != array_size(ary,i)) { success = 0; } } if (!success) { for (i = 0; i < n; i++) { if (size[i] == -1) { sprintf(s, "*,"); } else { sprintf(s, "%ld,", (long int)size[i]); } strcat(desired_dims,s); } len = strlen(desired_dims); desired_dims[len-1] = ']'; for (i = 0; i < n; i++) { sprintf(s, "%ld,", (long int)array_size(ary,i)); strcat(actual_dims,s); } len = strlen(actual_dims); actual_dims[len-1] = ']'; PyErr_Format(PyExc_TypeError, "Array must have shape of %s. Given array has shape of %s", desired_dims, actual_dims); } return success; } /* Require the given PyArrayObject to to be Fortran ordered. If the * the PyArrayObject is already Fortran ordered, do nothing. Else, * set the Fortran ordering flag and recompute the strides. */ int require_fortran(PyArrayObject* ary) { int success = 1; int nd = array_numdims(ary); int i; npy_intp * strides = array_strides(ary); if (array_is_fortran(ary)) return success; /* Set the Fortran ordered flag */ array_enableflags(ary,NPY_ARRAY_FARRAY); /* Recompute the strides */ strides[0] = strides[nd-1]; for (i=1; i < nd; ++i) strides[i] = strides[i-1] * array_size(ary,i-1); return success; } } /* Combine all NumPy fragments into one for convenience */ %fragment("NumPy_Fragments", "header", fragment="NumPy_Backward_Compatibility", fragment="NumPy_Macros", fragment="NumPy_Utilities", fragment="NumPy_Object_to_Array", fragment="NumPy_Array_Requirements") { } /* End John Hunter translation (with modifications by Bill Spotz) */ /* %numpy_typemaps() macro * * This macro defines a family of 74 typemaps that allow C arguments * of the form * * 1. (DATA_TYPE IN_ARRAY1[ANY]) * 2. (DATA_TYPE* IN_ARRAY1, DIM_TYPE DIM1) * 3. (DIM_TYPE DIM1, DATA_TYPE* IN_ARRAY1) * * 4. (DATA_TYPE IN_ARRAY2[ANY][ANY]) * 5. (DATA_TYPE* IN_ARRAY2, DIM_TYPE DIM1, DIM_TYPE DIM2) * 6. (DIM_TYPE DIM1, DIM_TYPE DIM2, DATA_TYPE* IN_ARRAY2) * 7. (DATA_TYPE* IN_FARRAY2, DIM_TYPE DIM1, DIM_TYPE DIM2) * 8. (DIM_TYPE DIM1, DIM_TYPE DIM2, DATA_TYPE* IN_FARRAY2) * * 9. (DATA_TYPE IN_ARRAY3[ANY][ANY][ANY]) * 10. (DATA_TYPE* IN_ARRAY3, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3) * 11. (DATA_TYPE** IN_ARRAY3, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3) * 12. (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DATA_TYPE* IN_ARRAY3) * 13. (DATA_TYPE* IN_FARRAY3, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3) * 14. (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DATA_TYPE* IN_FARRAY3) * * 15. (DATA_TYPE IN_ARRAY4[ANY][ANY][ANY][ANY]) * 16. (DATA_TYPE* IN_ARRAY4, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DIM_TYPE DIM4) * 17. (DATA_TYPE** IN_ARRAY4, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DIM_TYPE DIM4) * 18. (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, , DIM_TYPE DIM4, DATA_TYPE* IN_ARRAY4) * 19. (DATA_TYPE* IN_FARRAY4, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DIM_TYPE DIM4) * 20. (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DIM_TYPE DIM4, DATA_TYPE* IN_FARRAY4) * * 21. (DATA_TYPE INPLACE_ARRAY1[ANY]) * 22. (DATA_TYPE* INPLACE_ARRAY1, DIM_TYPE DIM1) * 23. (DIM_TYPE DIM1, DATA_TYPE* INPLACE_ARRAY1) * * 24. (DATA_TYPE INPLACE_ARRAY2[ANY][ANY]) * 25. (DATA_TYPE* INPLACE_ARRAY2, DIM_TYPE DIM1, DIM_TYPE DIM2) * 26. (DIM_TYPE DIM1, DIM_TYPE DIM2, DATA_TYPE* INPLACE_ARRAY2) * 27. (DATA_TYPE* INPLACE_FARRAY2, DIM_TYPE DIM1, DIM_TYPE DIM2) * 28. (DIM_TYPE DIM1, DIM_TYPE DIM2, DATA_TYPE* INPLACE_FARRAY2) * * 29. (DATA_TYPE INPLACE_ARRAY3[ANY][ANY][ANY]) * 30. (DATA_TYPE* INPLACE_ARRAY3, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3) * 31. (DATA_TYPE** INPLACE_ARRAY3, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3) * 32. (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DATA_TYPE* INPLACE_ARRAY3) * 33. (DATA_TYPE* INPLACE_FARRAY3, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3) * 34. (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DATA_TYPE* INPLACE_FARRAY3) * * 35. (DATA_TYPE INPLACE_ARRAY4[ANY][ANY][ANY][ANY]) * 36. (DATA_TYPE* INPLACE_ARRAY4, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DIM_TYPE DIM4) * 37. (DATA_TYPE** INPLACE_ARRAY4, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DIM_TYPE DIM4) * 38. (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DIM_TYPE DIM4, DATA_TYPE* INPLACE_ARRAY4) * 39. (DATA_TYPE* INPLACE_FARRAY4, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DIM_TYPE DIM4) * 40. (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DIM_TYPE DIM4, DATA_TYPE* INPLACE_FARRAY4) * * 41. (DATA_TYPE ARGOUT_ARRAY1[ANY]) * 42. (DATA_TYPE* ARGOUT_ARRAY1, DIM_TYPE DIM1) * 43. (DIM_TYPE DIM1, DATA_TYPE* ARGOUT_ARRAY1) * * 44. (DATA_TYPE ARGOUT_ARRAY2[ANY][ANY]) * * 45. (DATA_TYPE ARGOUT_ARRAY3[ANY][ANY][ANY]) * * 46. (DATA_TYPE ARGOUT_ARRAY4[ANY][ANY][ANY][ANY]) * * 47. (DATA_TYPE** ARGOUTVIEW_ARRAY1, DIM_TYPE* DIM1) * 48. (DIM_TYPE* DIM1, DATA_TYPE** ARGOUTVIEW_ARRAY1) * * 49. (DATA_TYPE** ARGOUTVIEW_ARRAY2, DIM_TYPE* DIM1, DIM_TYPE* DIM2) * 50. (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DATA_TYPE** ARGOUTVIEW_ARRAY2) * 51. (DATA_TYPE** ARGOUTVIEW_FARRAY2, DIM_TYPE* DIM1, DIM_TYPE* DIM2) * 52. (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DATA_TYPE** ARGOUTVIEW_FARRAY2) * * 53. (DATA_TYPE** ARGOUTVIEW_ARRAY3, DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3) * 54. (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DATA_TYPE** ARGOUTVIEW_ARRAY3) * 55. (DATA_TYPE** ARGOUTVIEW_FARRAY3, DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3) * 56. (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DATA_TYPE** ARGOUTVIEW_FARRAY3) * * 57. (DATA_TYPE** ARGOUTVIEW_ARRAY4, DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DIM_TYPE* DIM4) * 58. (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DIM_TYPE* DIM4, DATA_TYPE** ARGOUTVIEW_ARRAY4) * 59. (DATA_TYPE** ARGOUTVIEW_FARRAY4, DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DIM_TYPE* DIM4) * 60. (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DIM_TYPE* DIM4, DATA_TYPE** ARGOUTVIEW_FARRAY4) * * 61. (DATA_TYPE** ARGOUTVIEWM_ARRAY1, DIM_TYPE* DIM1) * 62. (DIM_TYPE* DIM1, DATA_TYPE** ARGOUTVIEWM_ARRAY1) * * 63. (DATA_TYPE** ARGOUTVIEWM_ARRAY2, DIM_TYPE* DIM1, DIM_TYPE* DIM2) * 64. (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DATA_TYPE** ARGOUTVIEWM_ARRAY2) * 65. (DATA_TYPE** ARGOUTVIEWM_FARRAY2, DIM_TYPE* DIM1, DIM_TYPE* DIM2) * 66. (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DATA_TYPE** ARGOUTVIEWM_FARRAY2) * * 67. (DATA_TYPE** ARGOUTVIEWM_ARRAY3, DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3) * 68. (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DATA_TYPE** ARGOUTVIEWM_ARRAY3) * 69. (DATA_TYPE** ARGOUTVIEWM_FARRAY3, DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3) * 70. (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DATA_TYPE** ARGOUTVIEWM_FARRAY3) * * 71. (DATA_TYPE** ARGOUTVIEWM_ARRAY4, DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DIM_TYPE* DIM4) * 72. (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DIM_TYPE* DIM4, DATA_TYPE** ARGOUTVIEWM_ARRAY4) * 73. (DATA_TYPE** ARGOUTVIEWM_FARRAY4, DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DIM_TYPE* DIM4) * 74. (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DIM_TYPE* DIM4, DATA_TYPE** ARGOUTVIEWM_FARRAY4) * * where "DATA_TYPE" is any type supported by the NumPy module, and * "DIM_TYPE" is any int-like type suitable for specifying dimensions. * The difference between "ARRAY" typemaps and "FARRAY" typemaps is * that the "FARRAY" typemaps expect Fortran ordering of * multidimensional arrays. In python, the dimensions will not need * to be specified (except for the "DATA_TYPE* ARGOUT_ARRAY1" * typemaps). The IN_ARRAYs can be a numpy array or any sequence that * can be converted to a numpy array of the specified type. The * INPLACE_ARRAYs must be numpy arrays of the appropriate type. The * ARGOUT_ARRAYs will be returned as new numpy arrays of the * appropriate type. * * These typemaps can be applied to existing functions using the * %apply directive. For example: * * %apply (double* IN_ARRAY1, int DIM1) {(double* series, int length)}; * double prod(double* series, int length); * * %apply (int DIM1, int DIM2, double* INPLACE_ARRAY2) * {(int rows, int cols, double* matrix )}; * void floor(int rows, int cols, double* matrix, double f); * * %apply (double IN_ARRAY3[ANY][ANY][ANY]) * {(double tensor[2][2][2] )}; * %apply (double ARGOUT_ARRAY3[ANY][ANY][ANY]) * {(double low[2][2][2] )}; * %apply (double ARGOUT_ARRAY3[ANY][ANY][ANY]) * {(double upp[2][2][2] )}; * void luSplit(double tensor[2][2][2], * double low[2][2][2], * double upp[2][2][2] ); * * or directly with * * double prod(double* IN_ARRAY1, int DIM1); * * void floor(int DIM1, int DIM2, double* INPLACE_ARRAY2, double f); * * void luSplit(double IN_ARRAY3[ANY][ANY][ANY], * double ARGOUT_ARRAY3[ANY][ANY][ANY], * double ARGOUT_ARRAY3[ANY][ANY][ANY]); */ %define %numpy_typemaps(DATA_TYPE, DATA_TYPECODE, DIM_TYPE) /************************/ /* Input Array Typemaps */ /************************/ /* Typemap suite for (DATA_TYPE IN_ARRAY1[ANY]) */ %typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, fragment="NumPy_Macros") (DATA_TYPE IN_ARRAY1[ANY]) { $1 = is_array($input) || PySequence_Check($input); } %typemap(in, fragment="NumPy_Fragments") (DATA_TYPE IN_ARRAY1[ANY]) (PyArrayObject* array=NULL, int is_new_object=0) { npy_intp size[1] = { $1_dim0 }; array = obj_to_array_contiguous_allow_conversion($input, DATA_TYPECODE, &is_new_object); if (!array || !require_dimensions(array, 1) || !require_size(array, size, 1)) SWIG_fail; $1 = ($1_ltype) array_data(array); } %typemap(freearg) (DATA_TYPE IN_ARRAY1[ANY]) { if (is_new_object$argnum && array$argnum) { Py_DECREF(array$argnum); } } /* Typemap suite for (DATA_TYPE* IN_ARRAY1, DIM_TYPE DIM1) */ %typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, fragment="NumPy_Macros") (DATA_TYPE* IN_ARRAY1, DIM_TYPE DIM1) { $1 = is_array($input) || PySequence_Check($input); } %typemap(in, fragment="NumPy_Fragments") (DATA_TYPE* IN_ARRAY1, DIM_TYPE DIM1) (PyArrayObject* array=NULL, int is_new_object=0) { npy_intp size[1] = { -1 }; array = obj_to_array_contiguous_allow_conversion($input, DATA_TYPECODE, &is_new_object); if (!array || !require_dimensions(array, 1) || !require_size(array, size, 1)) SWIG_fail; $1 = (DATA_TYPE*) array_data(array); $2 = (DIM_TYPE) array_size(array,0); } %typemap(freearg) (DATA_TYPE* IN_ARRAY1, DIM_TYPE DIM1) { if (is_new_object$argnum && array$argnum) { Py_DECREF(array$argnum); } } /* Typemap suite for (DIM_TYPE DIM1, DATA_TYPE* IN_ARRAY1) */ %typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, fragment="NumPy_Macros") (DIM_TYPE DIM1, DATA_TYPE* IN_ARRAY1) { $1 = is_array($input) || PySequence_Check($input); } %typemap(in, fragment="NumPy_Fragments") (DIM_TYPE DIM1, DATA_TYPE* IN_ARRAY1) (PyArrayObject* array=NULL, int is_new_object=0) { npy_intp size[1] = {-1}; array = obj_to_array_contiguous_allow_conversion($input, DATA_TYPECODE, &is_new_object); if (!array || !require_dimensions(array, 1) || !require_size(array, size, 1)) SWIG_fail; $1 = (DIM_TYPE) array_size(array,0); $2 = (DATA_TYPE*) array_data(array); } %typemap(freearg) (DIM_TYPE DIM1, DATA_TYPE* IN_ARRAY1) { if (is_new_object$argnum && array$argnum) { Py_DECREF(array$argnum); } } /* Typemap suite for (DATA_TYPE IN_ARRAY2[ANY][ANY]) */ %typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, fragment="NumPy_Macros") (DATA_TYPE IN_ARRAY2[ANY][ANY]) { $1 = is_array($input) || PySequence_Check($input); } %typemap(in, fragment="NumPy_Fragments") (DATA_TYPE IN_ARRAY2[ANY][ANY]) (PyArrayObject* array=NULL, int is_new_object=0) { npy_intp size[2] = { $1_dim0, $1_dim1 }; array = obj_to_array_contiguous_allow_conversion($input, DATA_TYPECODE, &is_new_object); if (!array || !require_dimensions(array, 2) || !require_size(array, size, 2)) SWIG_fail; $1 = ($1_ltype) array_data(array); } %typemap(freearg) (DATA_TYPE IN_ARRAY2[ANY][ANY]) { if (is_new_object$argnum && array$argnum) { Py_DECREF(array$argnum); } } /* Typemap suite for (DATA_TYPE* IN_ARRAY2, DIM_TYPE DIM1, DIM_TYPE DIM2) */ %typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, fragment="NumPy_Macros") (DATA_TYPE* IN_ARRAY2, DIM_TYPE DIM1, DIM_TYPE DIM2) { $1 = is_array($input) || PySequence_Check($input); } %typemap(in, fragment="NumPy_Fragments") (DATA_TYPE* IN_ARRAY2, DIM_TYPE DIM1, DIM_TYPE DIM2) (PyArrayObject* array=NULL, int is_new_object=0) { npy_intp size[2] = { -1, -1 }; array = obj_to_array_contiguous_allow_conversion($input, DATA_TYPECODE, &is_new_object); if (!array || !require_dimensions(array, 2) || !require_size(array, size, 2)) SWIG_fail; $1 = (DATA_TYPE*) array_data(array); $2 = (DIM_TYPE) array_size(array,0); $3 = (DIM_TYPE) array_size(array,1); } %typemap(freearg) (DATA_TYPE* IN_ARRAY2, DIM_TYPE DIM1, DIM_TYPE DIM2) { if (is_new_object$argnum && array$argnum) { Py_DECREF(array$argnum); } } /* Typemap suite for (DIM_TYPE DIM1, DIM_TYPE DIM2, DATA_TYPE* IN_ARRAY2) */ %typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, fragment="NumPy_Macros") (DIM_TYPE DIM1, DIM_TYPE DIM2, DATA_TYPE* IN_ARRAY2) { $1 = is_array($input) || PySequence_Check($input); } %typemap(in, fragment="NumPy_Fragments") (DIM_TYPE DIM1, DIM_TYPE DIM2, DATA_TYPE* IN_ARRAY2) (PyArrayObject* array=NULL, int is_new_object=0) { npy_intp size[2] = { -1, -1 }; array = obj_to_array_contiguous_allow_conversion($input, DATA_TYPECODE, &is_new_object); if (!array || !require_dimensions(array, 2) || !require_size(array, size, 2)) SWIG_fail; $1 = (DIM_TYPE) array_size(array,0); $2 = (DIM_TYPE) array_size(array,1); $3 = (DATA_TYPE*) array_data(array); } %typemap(freearg) (DIM_TYPE DIM1, DIM_TYPE DIM2, DATA_TYPE* IN_ARRAY2) { if (is_new_object$argnum && array$argnum) { Py_DECREF(array$argnum); } } /* Typemap suite for (DATA_TYPE* IN_FARRAY2, DIM_TYPE DIM1, DIM_TYPE DIM2) */ %typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, fragment="NumPy_Macros") (DATA_TYPE* IN_FARRAY2, DIM_TYPE DIM1, DIM_TYPE DIM2) { $1 = is_array($input) || PySequence_Check($input); } %typemap(in, fragment="NumPy_Fragments") (DATA_TYPE* IN_FARRAY2, DIM_TYPE DIM1, DIM_TYPE DIM2) (PyArrayObject* array=NULL, int is_new_object=0) { npy_intp size[2] = { -1, -1 }; array = obj_to_array_fortran_allow_conversion($input, DATA_TYPECODE, &is_new_object); if (!array || !require_dimensions(array, 2) || !require_size(array, size, 2) || !require_fortran(array)) SWIG_fail; $1 = (DATA_TYPE*) array_data(array); $2 = (DIM_TYPE) array_size(array,0); $3 = (DIM_TYPE) array_size(array,1); } %typemap(freearg) (DATA_TYPE* IN_FARRAY2, DIM_TYPE DIM1, DIM_TYPE DIM2) { if (is_new_object$argnum && array$argnum) { Py_DECREF(array$argnum); } } /* Typemap suite for (DIM_TYPE DIM1, DIM_TYPE DIM2, DATA_TYPE* IN_FARRAY2) */ %typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, fragment="NumPy_Macros") (DIM_TYPE DIM1, DIM_TYPE DIM2, DATA_TYPE* IN_FARRAY2) { $1 = is_array($input) || PySequence_Check($input); } %typemap(in, fragment="NumPy_Fragments") (DIM_TYPE DIM1, DIM_TYPE DIM2, DATA_TYPE* IN_FARRAY2) (PyArrayObject* array=NULL, int is_new_object=0) { npy_intp size[2] = { -1, -1 }; array = obj_to_array_contiguous_allow_conversion($input, DATA_TYPECODE, &is_new_object); if (!array || !require_dimensions(array, 2) || !require_size(array, size, 2) || !require_fortran(array)) SWIG_fail; $1 = (DIM_TYPE) array_size(array,0); $2 = (DIM_TYPE) array_size(array,1); $3 = (DATA_TYPE*) array_data(array); } %typemap(freearg) (DIM_TYPE DIM1, DIM_TYPE DIM2, DATA_TYPE* IN_FARRAY2) { if (is_new_object$argnum && array$argnum) { Py_DECREF(array$argnum); } } /* Typemap suite for (DATA_TYPE IN_ARRAY3[ANY][ANY][ANY]) */ %typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, fragment="NumPy_Macros") (DATA_TYPE IN_ARRAY3[ANY][ANY][ANY]) { $1 = is_array($input) || PySequence_Check($input); } %typemap(in, fragment="NumPy_Fragments") (DATA_TYPE IN_ARRAY3[ANY][ANY][ANY]) (PyArrayObject* array=NULL, int is_new_object=0) { npy_intp size[3] = { $1_dim0, $1_dim1, $1_dim2 }; array = obj_to_array_contiguous_allow_conversion($input, DATA_TYPECODE, &is_new_object); if (!array || !require_dimensions(array, 3) || !require_size(array, size, 3)) SWIG_fail; $1 = ($1_ltype) array_data(array); } %typemap(freearg) (DATA_TYPE IN_ARRAY3[ANY][ANY][ANY]) { if (is_new_object$argnum && array$argnum) { Py_DECREF(array$argnum); } } /* Typemap suite for (DATA_TYPE* IN_ARRAY3, DIM_TYPE DIM1, DIM_TYPE DIM2, * DIM_TYPE DIM3) */ %typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, fragment="NumPy_Macros") (DATA_TYPE* IN_ARRAY3, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3) { $1 = is_array($input) || PySequence_Check($input); } %typemap(in, fragment="NumPy_Fragments") (DATA_TYPE* IN_ARRAY3, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3) (PyArrayObject* array=NULL, int is_new_object=0) { npy_intp size[3] = { -1, -1, -1 }; array = obj_to_array_contiguous_allow_conversion($input, DATA_TYPECODE, &is_new_object); if (!array || !require_dimensions(array, 3) || !require_size(array, size, 3)) SWIG_fail; $1 = (DATA_TYPE*) array_data(array); $2 = (DIM_TYPE) array_size(array,0); $3 = (DIM_TYPE) array_size(array,1); $4 = (DIM_TYPE) array_size(array,2); } %typemap(freearg) (DATA_TYPE* IN_ARRAY3, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3) { if (is_new_object$argnum && array$argnum) { Py_DECREF(array$argnum); } } /* Typemap suite for (DATA_TYPE** IN_ARRAY3, DIM_TYPE DIM1, DIM_TYPE DIM2, * DIM_TYPE DIM3) */ %typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, fragment="NumPy_Macros") (DATA_TYPE** IN_ARRAY3, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3) { /* for now, only concerned with lists */ $1 = PySequence_Check($input); } %typemap(in, fragment="NumPy_Fragments") (DATA_TYPE** IN_ARRAY3, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3) (DATA_TYPE** array=NULL, PyArrayObject** object_array=NULL, int* is_new_object_array=NULL) { npy_intp size[2] = { -1, -1 }; PyArrayObject* temp_array; Py_ssize_t i; int is_new_object; /* length of the list */ $2 = PyList_Size($input); /* the arrays */ array = (DATA_TYPE **)malloc($2*sizeof(DATA_TYPE *)); object_array = (PyArrayObject **)calloc($2,sizeof(PyArrayObject *)); is_new_object_array = (int *)calloc($2,sizeof(int)); if (array == NULL || object_array == NULL || is_new_object_array == NULL) { SWIG_fail; } for (i=0; i<$2; i++) { temp_array = obj_to_array_contiguous_allow_conversion(PySequence_GetItem($input,i), DATA_TYPECODE, &is_new_object); /* the new array must be stored so that it can be destroyed in freearg */ object_array[i] = temp_array; is_new_object_array[i] = is_new_object; if (!temp_array || !require_dimensions(temp_array, 2)) SWIG_fail; /* store the size of the first array in the list, then use that for comparison. */ if (i == 0) { size[0] = array_size(temp_array,0); size[1] = array_size(temp_array,1); } if (!require_size(temp_array, size, 2)) SWIG_fail; array[i] = (DATA_TYPE*) array_data(temp_array); } $1 = (DATA_TYPE**) array; $3 = (DIM_TYPE) size[0]; $4 = (DIM_TYPE) size[1]; } %typemap(freearg) (DATA_TYPE** IN_ARRAY3, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3) { Py_ssize_t i; if (array$argnum!=NULL) free(array$argnum); /*freeing the individual arrays if needed */ if (object_array$argnum!=NULL) { if (is_new_object_array$argnum!=NULL) { for (i=0; i<$2; i++) { if (object_array$argnum[i] != NULL && is_new_object_array$argnum[i]) { Py_DECREF(object_array$argnum[i]); } } free(is_new_object_array$argnum); } free(object_array$argnum); } } /* Typemap suite for (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, * DATA_TYPE* IN_ARRAY3) */ %typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, fragment="NumPy_Macros") (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DATA_TYPE* IN_ARRAY3) { $1 = is_array($input) || PySequence_Check($input); } %typemap(in, fragment="NumPy_Fragments") (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DATA_TYPE* IN_ARRAY3) (PyArrayObject* array=NULL, int is_new_object=0) { npy_intp size[3] = { -1, -1, -1 }; array = obj_to_array_contiguous_allow_conversion($input, DATA_TYPECODE, &is_new_object); if (!array || !require_dimensions(array, 3) || !require_size(array, size, 3)) SWIG_fail; $1 = (DIM_TYPE) array_size(array,0); $2 = (DIM_TYPE) array_size(array,1); $3 = (DIM_TYPE) array_size(array,2); $4 = (DATA_TYPE*) array_data(array); } %typemap(freearg) (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DATA_TYPE* IN_ARRAY3) { if (is_new_object$argnum && array$argnum) { Py_DECREF(array$argnum); } } /* Typemap suite for (DATA_TYPE* IN_FARRAY3, DIM_TYPE DIM1, DIM_TYPE DIM2, * DIM_TYPE DIM3) */ %typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, fragment="NumPy_Macros") (DATA_TYPE* IN_FARRAY3, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3) { $1 = is_array($input) || PySequence_Check($input); } %typemap(in, fragment="NumPy_Fragments") (DATA_TYPE* IN_FARRAY3, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3) (PyArrayObject* array=NULL, int is_new_object=0) { npy_intp size[3] = { -1, -1, -1 }; array = obj_to_array_fortran_allow_conversion($input, DATA_TYPECODE, &is_new_object); if (!array || !require_dimensions(array, 3) || !require_size(array, size, 3) | !require_fortran(array)) SWIG_fail; $1 = (DATA_TYPE*) array_data(array); $2 = (DIM_TYPE) array_size(array,0); $3 = (DIM_TYPE) array_size(array,1); $4 = (DIM_TYPE) array_size(array,2); } %typemap(freearg) (DATA_TYPE* IN_FARRAY3, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3) { if (is_new_object$argnum && array$argnum) { Py_DECREF(array$argnum); } } /* Typemap suite for (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, * DATA_TYPE* IN_FARRAY3) */ %typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, fragment="NumPy_Macros") (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DATA_TYPE* IN_FARRAY3) { $1 = is_array($input) || PySequence_Check($input); } %typemap(in, fragment="NumPy_Fragments") (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DATA_TYPE* IN_FARRAY3) (PyArrayObject* array=NULL, int is_new_object=0) { npy_intp size[3] = { -1, -1, -1 }; array = obj_to_array_contiguous_allow_conversion($input, DATA_TYPECODE, &is_new_object); if (!array || !require_dimensions(array, 3) || !require_size(array, size, 3) || !require_fortran(array)) SWIG_fail; $1 = (DIM_TYPE) array_size(array,0); $2 = (DIM_TYPE) array_size(array,1); $3 = (DIM_TYPE) array_size(array,2); $4 = (DATA_TYPE*) array_data(array); } %typemap(freearg) (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DATA_TYPE* IN_FARRAY3) { if (is_new_object$argnum && array$argnum) { Py_DECREF(array$argnum); } } /* Typemap suite for (DATA_TYPE IN_ARRAY4[ANY][ANY][ANY][ANY]) */ %typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, fragment="NumPy_Macros") (DATA_TYPE IN_ARRAY4[ANY][ANY][ANY][ANY]) { $1 = is_array($input) || PySequence_Check($input); } %typemap(in, fragment="NumPy_Fragments") (DATA_TYPE IN_ARRAY4[ANY][ANY][ANY][ANY]) (PyArrayObject* array=NULL, int is_new_object=0) { npy_intp size[4] = { $1_dim0, $1_dim1, $1_dim2 , $1_dim3}; array = obj_to_array_contiguous_allow_conversion($input, DATA_TYPECODE, &is_new_object); if (!array || !require_dimensions(array, 4) || !require_size(array, size, 4)) SWIG_fail; $1 = ($1_ltype) array_data(array); } %typemap(freearg) (DATA_TYPE IN_ARRAY4[ANY][ANY][ANY][ANY]) { if (is_new_object$argnum && array$argnum) { Py_DECREF(array$argnum); } } /* Typemap suite for (DATA_TYPE* IN_ARRAY4, DIM_TYPE DIM1, DIM_TYPE DIM2, * DIM_TYPE DIM3, DIM_TYPE DIM4) */ %typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, fragment="NumPy_Macros") (DATA_TYPE* IN_ARRAY4, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DIM_TYPE DIM4) { $1 = is_array($input) || PySequence_Check($input); } %typemap(in, fragment="NumPy_Fragments") (DATA_TYPE* IN_ARRAY4, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DIM_TYPE DIM4) (PyArrayObject* array=NULL, int is_new_object=0) { npy_intp size[4] = { -1, -1, -1, -1 }; array = obj_to_array_contiguous_allow_conversion($input, DATA_TYPECODE, &is_new_object); if (!array || !require_dimensions(array, 4) || !require_size(array, size, 4)) SWIG_fail; $1 = (DATA_TYPE*) array_data(array); $2 = (DIM_TYPE) array_size(array,0); $3 = (DIM_TYPE) array_size(array,1); $4 = (DIM_TYPE) array_size(array,2); $5 = (DIM_TYPE) array_size(array,3); } %typemap(freearg) (DATA_TYPE* IN_ARRAY4, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DIM_TYPE DIM4) { if (is_new_object$argnum && array$argnum) { Py_DECREF(array$argnum); } } /* Typemap suite for (DATA_TYPE** IN_ARRAY4, DIM_TYPE DIM1, DIM_TYPE DIM2, * DIM_TYPE DIM3, DIM_TYPE DIM4) */ %typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, fragment="NumPy_Macros") (DATA_TYPE** IN_ARRAY4, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DIM_TYPE DIM4) { /* for now, only concerned with lists */ $1 = PySequence_Check($input); } %typemap(in, fragment="NumPy_Fragments") (DATA_TYPE** IN_ARRAY4, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DIM_TYPE DIM4) (DATA_TYPE** array=NULL, PyArrayObject** object_array=NULL, int* is_new_object_array=NULL) { npy_intp size[3] = { -1, -1, -1 }; PyArrayObject* temp_array; Py_ssize_t i; int is_new_object; /* length of the list */ $2 = PyList_Size($input); /* the arrays */ array = (DATA_TYPE **)malloc($2*sizeof(DATA_TYPE *)); object_array = (PyArrayObject **)calloc($2,sizeof(PyArrayObject *)); is_new_object_array = (int *)calloc($2,sizeof(int)); if (array == NULL || object_array == NULL || is_new_object_array == NULL) { SWIG_fail; } for (i=0; i<$2; i++) { temp_array = obj_to_array_contiguous_allow_conversion(PySequence_GetItem($input,i), DATA_TYPECODE, &is_new_object); /* the new array must be stored so that it can be destroyed in freearg */ object_array[i] = temp_array; is_new_object_array[i] = is_new_object; if (!temp_array || !require_dimensions(temp_array, 3)) SWIG_fail; /* store the size of the first array in the list, then use that for comparison. */ if (i == 0) { size[0] = array_size(temp_array,0); size[1] = array_size(temp_array,1); size[2] = array_size(temp_array,2); } if (!require_size(temp_array, size, 3)) SWIG_fail; array[i] = (DATA_TYPE*) array_data(temp_array); } $1 = (DATA_TYPE**) array; $3 = (DIM_TYPE) size[0]; $4 = (DIM_TYPE) size[1]; $5 = (DIM_TYPE) size[2]; } %typemap(freearg) (DATA_TYPE** IN_ARRAY4, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DIM_TYPE DIM4) { Py_ssize_t i; if (array$argnum!=NULL) free(array$argnum); /*freeing the individual arrays if needed */ if (object_array$argnum!=NULL) { if (is_new_object_array$argnum!=NULL) { for (i=0; i<$2; i++) { if (object_array$argnum[i] != NULL && is_new_object_array$argnum[i]) { Py_DECREF(object_array$argnum[i]); } } free(is_new_object_array$argnum); } free(object_array$argnum); } } /* Typemap suite for (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DIM_TYPE DIM4, * DATA_TYPE* IN_ARRAY4) */ %typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, fragment="NumPy_Macros") (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DIM_TYPE DIM4, DATA_TYPE* IN_ARRAY4) { $1 = is_array($input) || PySequence_Check($input); } %typemap(in, fragment="NumPy_Fragments") (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DIM_TYPE DIM4, DATA_TYPE* IN_ARRAY4) (PyArrayObject* array=NULL, int is_new_object=0) { npy_intp size[4] = { -1, -1, -1 , -1}; array = obj_to_array_contiguous_allow_conversion($input, DATA_TYPECODE, &is_new_object); if (!array || !require_dimensions(array, 4) || !require_size(array, size, 4)) SWIG_fail; $1 = (DIM_TYPE) array_size(array,0); $2 = (DIM_TYPE) array_size(array,1); $3 = (DIM_TYPE) array_size(array,2); $4 = (DIM_TYPE) array_size(array,3); $5 = (DATA_TYPE*) array_data(array); } %typemap(freearg) (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DIM_TYPE DIM4, DATA_TYPE* IN_ARRAY4) { if (is_new_object$argnum && array$argnum) { Py_DECREF(array$argnum); } } /* Typemap suite for (DATA_TYPE* IN_FARRAY4, DIM_TYPE DIM1, DIM_TYPE DIM2, * DIM_TYPE DIM3, DIM_TYPE DIM4) */ %typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, fragment="NumPy_Macros") (DATA_TYPE* IN_FARRAY4, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DIM_TYPE DIM4) { $1 = is_array($input) || PySequence_Check($input); } %typemap(in, fragment="NumPy_Fragments") (DATA_TYPE* IN_FARRAY4, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DIM_TYPE DIM4) (PyArrayObject* array=NULL, int is_new_object=0) { npy_intp size[4] = { -1, -1, -1, -1 }; array = obj_to_array_fortran_allow_conversion($input, DATA_TYPECODE, &is_new_object); if (!array || !require_dimensions(array, 4) || !require_size(array, size, 4) | !require_fortran(array)) SWIG_fail; $1 = (DATA_TYPE*) array_data(array); $2 = (DIM_TYPE) array_size(array,0); $3 = (DIM_TYPE) array_size(array,1); $4 = (DIM_TYPE) array_size(array,2); $5 = (DIM_TYPE) array_size(array,3); } %typemap(freearg) (DATA_TYPE* IN_FARRAY4, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DIM_TYPE DIM4) { if (is_new_object$argnum && array$argnum) { Py_DECREF(array$argnum); } } /* Typemap suite for (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DIM_TYPE DIM4, * DATA_TYPE* IN_FARRAY4) */ %typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, fragment="NumPy_Macros") (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DIM_TYPE DIM4, DATA_TYPE* IN_FARRAY4) { $1 = is_array($input) || PySequence_Check($input); } %typemap(in, fragment="NumPy_Fragments") (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DIM_TYPE DIM4, DATA_TYPE* IN_FARRAY4) (PyArrayObject* array=NULL, int is_new_object=0) { npy_intp size[4] = { -1, -1, -1 , -1 }; array = obj_to_array_contiguous_allow_conversion($input, DATA_TYPECODE, &is_new_object); if (!array || !require_dimensions(array, 4) || !require_size(array, size, 4) || !require_fortran(array)) SWIG_fail; $1 = (DIM_TYPE) array_size(array,0); $2 = (DIM_TYPE) array_size(array,1); $3 = (DIM_TYPE) array_size(array,2); $4 = (DIM_TYPE) array_size(array,3); $5 = (DATA_TYPE*) array_data(array); } %typemap(freearg) (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DIM_TYPE DIM4, DATA_TYPE* IN_FARRAY4) { if (is_new_object$argnum && array$argnum) { Py_DECREF(array$argnum); } } /***************************/ /* In-Place Array Typemaps */ /***************************/ /* Typemap suite for (DATA_TYPE INPLACE_ARRAY1[ANY]) */ %typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, fragment="NumPy_Macros") (DATA_TYPE INPLACE_ARRAY1[ANY]) { $1 = is_array($input) && PyArray_EquivTypenums(array_type($input), DATA_TYPECODE); } %typemap(in, fragment="NumPy_Fragments") (DATA_TYPE INPLACE_ARRAY1[ANY]) (PyArrayObject* array=NULL) { npy_intp size[1] = { $1_dim0 }; array = obj_to_array_no_conversion($input, DATA_TYPECODE); if (!array || !require_dimensions(array,1) || !require_size(array, size, 1) || !require_contiguous(array) || !require_native(array)) SWIG_fail; $1 = ($1_ltype) array_data(array); } /* Typemap suite for (DATA_TYPE* INPLACE_ARRAY1, DIM_TYPE DIM1) */ %typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, fragment="NumPy_Macros") (DATA_TYPE* INPLACE_ARRAY1, DIM_TYPE DIM1) { $1 = is_array($input) && PyArray_EquivTypenums(array_type($input), DATA_TYPECODE); } %typemap(in, fragment="NumPy_Fragments") (DATA_TYPE* INPLACE_ARRAY1, DIM_TYPE DIM1) (PyArrayObject* array=NULL, int i=1) { array = obj_to_array_no_conversion($input, DATA_TYPECODE); if (!array || !require_dimensions(array,1) || !require_contiguous(array) || !require_native(array)) SWIG_fail; $1 = (DATA_TYPE*) array_data(array); $2 = 1; for (i=0; i < array_numdims(array); ++i) $2 *= array_size(array,i); } /* Typemap suite for (DIM_TYPE DIM1, DATA_TYPE* INPLACE_ARRAY1) */ %typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, fragment="NumPy_Macros") (DIM_TYPE DIM1, DATA_TYPE* INPLACE_ARRAY1) { $1 = is_array($input) && PyArray_EquivTypenums(array_type($input), DATA_TYPECODE); } %typemap(in, fragment="NumPy_Fragments") (DIM_TYPE DIM1, DATA_TYPE* INPLACE_ARRAY1) (PyArrayObject* array=NULL, int i=0) { array = obj_to_array_no_conversion($input, DATA_TYPECODE); if (!array || !require_dimensions(array,1) || !require_contiguous(array) || !require_native(array)) SWIG_fail; $1 = 1; for (i=0; i < array_numdims(array); ++i) $1 *= array_size(array,i); $2 = (DATA_TYPE*) array_data(array); } /* Typemap suite for (DATA_TYPE INPLACE_ARRAY2[ANY][ANY]) */ %typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, fragment="NumPy_Macros") (DATA_TYPE INPLACE_ARRAY2[ANY][ANY]) { $1 = is_array($input) && PyArray_EquivTypenums(array_type($input), DATA_TYPECODE); } %typemap(in, fragment="NumPy_Fragments") (DATA_TYPE INPLACE_ARRAY2[ANY][ANY]) (PyArrayObject* array=NULL) { npy_intp size[2] = { $1_dim0, $1_dim1 }; array = obj_to_array_no_conversion($input, DATA_TYPECODE); if (!array || !require_dimensions(array,2) || !require_size(array, size, 2) || !require_contiguous(array) || !require_native(array)) SWIG_fail; $1 = ($1_ltype) array_data(array); } /* Typemap suite for (DATA_TYPE* INPLACE_ARRAY2, DIM_TYPE DIM1, DIM_TYPE DIM2) */ %typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, fragment="NumPy_Macros") (DATA_TYPE* INPLACE_ARRAY2, DIM_TYPE DIM1, DIM_TYPE DIM2) { $1 = is_array($input) && PyArray_EquivTypenums(array_type($input), DATA_TYPECODE); } %typemap(in, fragment="NumPy_Fragments") (DATA_TYPE* INPLACE_ARRAY2, DIM_TYPE DIM1, DIM_TYPE DIM2) (PyArrayObject* array=NULL) { array = obj_to_array_no_conversion($input, DATA_TYPECODE); if (!array || !require_dimensions(array,2) || !require_contiguous(array) || !require_native(array)) SWIG_fail; $1 = (DATA_TYPE*) array_data(array); $2 = (DIM_TYPE) array_size(array,0); $3 = (DIM_TYPE) array_size(array,1); } /* Typemap suite for (DIM_TYPE DIM1, DIM_TYPE DIM2, DATA_TYPE* INPLACE_ARRAY2) */ %typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, fragment="NumPy_Macros") (DIM_TYPE DIM1, DIM_TYPE DIM2, DATA_TYPE* INPLACE_ARRAY2) { $1 = is_array($input) && PyArray_EquivTypenums(array_type($input), DATA_TYPECODE); } %typemap(in, fragment="NumPy_Fragments") (DIM_TYPE DIM1, DIM_TYPE DIM2, DATA_TYPE* INPLACE_ARRAY2) (PyArrayObject* array=NULL) { array = obj_to_array_no_conversion($input, DATA_TYPECODE); if (!array || !require_dimensions(array,2) || !require_contiguous(array) || !require_native(array)) SWIG_fail; $1 = (DIM_TYPE) array_size(array,0); $2 = (DIM_TYPE) array_size(array,1); $3 = (DATA_TYPE*) array_data(array); } /* Typemap suite for (DATA_TYPE* INPLACE_FARRAY2, DIM_TYPE DIM1, DIM_TYPE DIM2) */ %typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, fragment="NumPy_Macros") (DATA_TYPE* INPLACE_FARRAY2, DIM_TYPE DIM1, DIM_TYPE DIM2) { $1 = is_array($input) && PyArray_EquivTypenums(array_type($input), DATA_TYPECODE); } %typemap(in, fragment="NumPy_Fragments") (DATA_TYPE* INPLACE_FARRAY2, DIM_TYPE DIM1, DIM_TYPE DIM2) (PyArrayObject* array=NULL) { array = obj_to_array_no_conversion($input, DATA_TYPECODE); if (!array || !require_dimensions(array,2) || !require_contiguous(array) || !require_native(array) || !require_fortran(array)) SWIG_fail; $1 = (DATA_TYPE*) array_data(array); $2 = (DIM_TYPE) array_size(array,0); $3 = (DIM_TYPE) array_size(array,1); } /* Typemap suite for (DIM_TYPE DIM1, DIM_TYPE DIM2, DATA_TYPE* INPLACE_FARRAY2) */ %typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, fragment="NumPy_Macros") (DIM_TYPE DIM1, DIM_TYPE DIM2, DATA_TYPE* INPLACE_FARRAY2) { $1 = is_array($input) && PyArray_EquivTypenums(array_type($input), DATA_TYPECODE); } %typemap(in, fragment="NumPy_Fragments") (DIM_TYPE DIM1, DIM_TYPE DIM2, DATA_TYPE* INPLACE_FARRAY2) (PyArrayObject* array=NULL) { array = obj_to_array_no_conversion($input, DATA_TYPECODE); if (!array || !require_dimensions(array,2) || !require_contiguous(array) || !require_native(array) || !require_fortran(array)) SWIG_fail; $1 = (DIM_TYPE) array_size(array,0); $2 = (DIM_TYPE) array_size(array,1); $3 = (DATA_TYPE*) array_data(array); } /* Typemap suite for (DATA_TYPE INPLACE_ARRAY3[ANY][ANY][ANY]) */ %typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, fragment="NumPy_Macros") (DATA_TYPE INPLACE_ARRAY3[ANY][ANY][ANY]) { $1 = is_array($input) && PyArray_EquivTypenums(array_type($input), DATA_TYPECODE); } %typemap(in, fragment="NumPy_Fragments") (DATA_TYPE INPLACE_ARRAY3[ANY][ANY][ANY]) (PyArrayObject* array=NULL) { npy_intp size[3] = { $1_dim0, $1_dim1, $1_dim2 }; array = obj_to_array_no_conversion($input, DATA_TYPECODE); if (!array || !require_dimensions(array,3) || !require_size(array, size, 3) || !require_contiguous(array) || !require_native(array)) SWIG_fail; $1 = ($1_ltype) array_data(array); } /* Typemap suite for (DATA_TYPE* INPLACE_ARRAY3, DIM_TYPE DIM1, DIM_TYPE DIM2, * DIM_TYPE DIM3) */ %typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, fragment="NumPy_Macros") (DATA_TYPE* INPLACE_ARRAY3, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3) { $1 = is_array($input) && PyArray_EquivTypenums(array_type($input), DATA_TYPECODE); } %typemap(in, fragment="NumPy_Fragments") (DATA_TYPE* INPLACE_ARRAY3, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3) (PyArrayObject* array=NULL) { array = obj_to_array_no_conversion($input, DATA_TYPECODE); if (!array || !require_dimensions(array,3) || !require_contiguous(array) || !require_native(array)) SWIG_fail; $1 = (DATA_TYPE*) array_data(array); $2 = (DIM_TYPE) array_size(array,0); $3 = (DIM_TYPE) array_size(array,1); $4 = (DIM_TYPE) array_size(array,2); } /* Typemap suite for (DATA_TYPE** INPLACE_ARRAY3, DIM_TYPE DIM1, DIM_TYPE DIM2, * DIM_TYPE DIM3) */ %typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, fragment="NumPy_Macros") (DATA_TYPE** INPLACE_ARRAY3, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3) { $1 = PySequence_Check($input); } %typemap(in, fragment="NumPy_Fragments") (DATA_TYPE** INPLACE_ARRAY3, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3) (DATA_TYPE** array=NULL, PyArrayObject** object_array=NULL) { npy_intp size[2] = { -1, -1 }; PyArrayObject* temp_array; Py_ssize_t i; /* length of the list */ $2 = PyList_Size($input); /* the arrays */ array = (DATA_TYPE **)malloc($2*sizeof(DATA_TYPE *)); object_array = (PyArrayObject **)calloc($2,sizeof(PyArrayObject *)); if (array == NULL || object_array == NULL) { SWIG_fail; } for (i=0; i<$2; i++) { temp_array = obj_to_array_no_conversion(PySequence_GetItem($input,i), DATA_TYPECODE); /* the new array must be stored so that it can be destroyed in freearg */ object_array[i] = temp_array; if ( !temp_array || !require_dimensions(temp_array, 2) || !require_contiguous(temp_array) || !require_native(temp_array) || !PyArray_EquivTypenums(array_type(temp_array), DATA_TYPECODE) ) SWIG_fail; /* store the size of the first array in the list, then use that for comparison. */ if (i == 0) { size[0] = array_size(temp_array,0); size[1] = array_size(temp_array,1); } if (!require_size(temp_array, size, 2)) SWIG_fail; array[i] = (DATA_TYPE*) array_data(temp_array); } $1 = (DATA_TYPE**) array; $3 = (DIM_TYPE) size[0]; $4 = (DIM_TYPE) size[1]; } %typemap(freearg) (DATA_TYPE** INPLACE_ARRAY3, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3) { if (array$argnum!=NULL) free(array$argnum); if (object_array$argnum!=NULL) free(object_array$argnum); } /* Typemap suite for (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, * DATA_TYPE* INPLACE_ARRAY3) */ %typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, fragment="NumPy_Macros") (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DATA_TYPE* INPLACE_ARRAY3) { $1 = is_array($input) && PyArray_EquivTypenums(array_type($input), DATA_TYPECODE); } %typemap(in, fragment="NumPy_Fragments") (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DATA_TYPE* INPLACE_ARRAY3) (PyArrayObject* array=NULL) { array = obj_to_array_no_conversion($input, DATA_TYPECODE); if (!array || !require_dimensions(array,3) || !require_contiguous(array) || !require_native(array)) SWIG_fail; $1 = (DIM_TYPE) array_size(array,0); $2 = (DIM_TYPE) array_size(array,1); $3 = (DIM_TYPE) array_size(array,2); $4 = (DATA_TYPE*) array_data(array); } /* Typemap suite for (DATA_TYPE* INPLACE_FARRAY3, DIM_TYPE DIM1, DIM_TYPE DIM2, * DIM_TYPE DIM3) */ %typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, fragment="NumPy_Macros") (DATA_TYPE* INPLACE_FARRAY3, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3) { $1 = is_array($input) && PyArray_EquivTypenums(array_type($input), DATA_TYPECODE); } %typemap(in, fragment="NumPy_Fragments") (DATA_TYPE* INPLACE_FARRAY3, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3) (PyArrayObject* array=NULL) { array = obj_to_array_no_conversion($input, DATA_TYPECODE); if (!array || !require_dimensions(array,3) || !require_contiguous(array) || !require_native(array) || !require_fortran(array)) SWIG_fail; $1 = (DATA_TYPE*) array_data(array); $2 = (DIM_TYPE) array_size(array,0); $3 = (DIM_TYPE) array_size(array,1); $4 = (DIM_TYPE) array_size(array,2); } /* Typemap suite for (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, * DATA_TYPE* INPLACE_FARRAY3) */ %typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, fragment="NumPy_Macros") (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DATA_TYPE* INPLACE_FARRAY3) { $1 = is_array($input) && PyArray_EquivTypenums(array_type($input), DATA_TYPECODE); } %typemap(in, fragment="NumPy_Fragments") (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DATA_TYPE* INPLACE_FARRAY3) (PyArrayObject* array=NULL) { array = obj_to_array_no_conversion($input, DATA_TYPECODE); if (!array || !require_dimensions(array,3) || !require_contiguous(array) || !require_native(array) || !require_fortran(array)) SWIG_fail; $1 = (DIM_TYPE) array_size(array,0); $2 = (DIM_TYPE) array_size(array,1); $3 = (DIM_TYPE) array_size(array,2); $4 = (DATA_TYPE*) array_data(array); } /* Typemap suite for (DATA_TYPE INPLACE_ARRAY4[ANY][ANY][ANY][ANY]) */ %typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, fragment="NumPy_Macros") (DATA_TYPE INPLACE_ARRAY4[ANY][ANY][ANY][ANY]) { $1 = is_array($input) && PyArray_EquivTypenums(array_type($input), DATA_TYPECODE); } %typemap(in, fragment="NumPy_Fragments") (DATA_TYPE INPLACE_ARRAY4[ANY][ANY][ANY][ANY]) (PyArrayObject* array=NULL) { npy_intp size[4] = { $1_dim0, $1_dim1, $1_dim2 , $1_dim3 }; array = obj_to_array_no_conversion($input, DATA_TYPECODE); if (!array || !require_dimensions(array,4) || !require_size(array, size, 4) || !require_contiguous(array) || !require_native(array)) SWIG_fail; $1 = ($1_ltype) array_data(array); } /* Typemap suite for (DATA_TYPE* INPLACE_ARRAY4, DIM_TYPE DIM1, DIM_TYPE DIM2, * DIM_TYPE DIM3, DIM_TYPE DIM4) */ %typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, fragment="NumPy_Macros") (DATA_TYPE* INPLACE_ARRAY4, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DIM_TYPE DIM4) { $1 = is_array($input) && PyArray_EquivTypenums(array_type($input), DATA_TYPECODE); } %typemap(in, fragment="NumPy_Fragments") (DATA_TYPE* INPLACE_ARRAY4, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DIM_TYPE DIM4) (PyArrayObject* array=NULL) { array = obj_to_array_no_conversion($input, DATA_TYPECODE); if (!array || !require_dimensions(array,4) || !require_contiguous(array) || !require_native(array)) SWIG_fail; $1 = (DATA_TYPE*) array_data(array); $2 = (DIM_TYPE) array_size(array,0); $3 = (DIM_TYPE) array_size(array,1); $4 = (DIM_TYPE) array_size(array,2); $5 = (DIM_TYPE) array_size(array,3); } /* Typemap suite for (DATA_TYPE** INPLACE_ARRAY4, DIM_TYPE DIM1, DIM_TYPE DIM2, * DIM_TYPE DIM3, DIM_TYPE DIM4) */ %typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, fragment="NumPy_Macros") (DATA_TYPE** INPLACE_ARRAY4, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DIM_TYPE DIM4) { $1 = PySequence_Check($input); } %typemap(in, fragment="NumPy_Fragments") (DATA_TYPE** INPLACE_ARRAY4, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DIM_TYPE DIM4) (DATA_TYPE** array=NULL, PyArrayObject** object_array=NULL) { npy_intp size[3] = { -1, -1, -1 }; PyArrayObject* temp_array; Py_ssize_t i; /* length of the list */ $2 = PyList_Size($input); /* the arrays */ array = (DATA_TYPE **)malloc($2*sizeof(DATA_TYPE *)); object_array = (PyArrayObject **)calloc($2,sizeof(PyArrayObject *)); if (array == NULL || object_array == NULL) { SWIG_fail; } for (i=0; i<$2; i++) { temp_array = obj_to_array_no_conversion(PySequence_GetItem($input,i), DATA_TYPECODE); /* the new array must be stored so that it can be destroyed in freearg */ object_array[i] = temp_array; if ( !temp_array || !require_dimensions(temp_array, 3) || !require_contiguous(temp_array) || !require_native(temp_array) || !PyArray_EquivTypenums(array_type(temp_array), DATA_TYPECODE) ) SWIG_fail; /* store the size of the first array in the list, then use that for comparison. */ if (i == 0) { size[0] = array_size(temp_array,0); size[1] = array_size(temp_array,1); size[2] = array_size(temp_array,2); } if (!require_size(temp_array, size, 3)) SWIG_fail; array[i] = (DATA_TYPE*) array_data(temp_array); } $1 = (DATA_TYPE**) array; $3 = (DIM_TYPE) size[0]; $4 = (DIM_TYPE) size[1]; $5 = (DIM_TYPE) size[2]; } %typemap(freearg) (DATA_TYPE** INPLACE_ARRAY4, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DIM_TYPE DIM4) { if (array$argnum!=NULL) free(array$argnum); if (object_array$argnum!=NULL) free(object_array$argnum); } /* Typemap suite for (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DIM_TYPE DIM4, * DATA_TYPE* INPLACE_ARRAY4) */ %typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, fragment="NumPy_Macros") (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DIM_TYPE DIM4, DATA_TYPE* INPLACE_ARRAY4) { $1 = is_array($input) && PyArray_EquivTypenums(array_type($input), DATA_TYPECODE); } %typemap(in, fragment="NumPy_Fragments") (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DIM_TYPE DIM4, DATA_TYPE* INPLACE_ARRAY4) (PyArrayObject* array=NULL) { array = obj_to_array_no_conversion($input, DATA_TYPECODE); if (!array || !require_dimensions(array,4) || !require_contiguous(array) || !require_native(array)) SWIG_fail; $1 = (DIM_TYPE) array_size(array,0); $2 = (DIM_TYPE) array_size(array,1); $3 = (DIM_TYPE) array_size(array,2); $4 = (DIM_TYPE) array_size(array,3); $5 = (DATA_TYPE*) array_data(array); } /* Typemap suite for (DATA_TYPE* INPLACE_FARRAY4, DIM_TYPE DIM1, DIM_TYPE DIM2, * DIM_TYPE DIM3, DIM_TYPE DIM4) */ %typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, fragment="NumPy_Macros") (DATA_TYPE* INPLACE_FARRAY4, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DIM_TYPE DIM4) { $1 = is_array($input) && PyArray_EquivTypenums(array_type($input), DATA_TYPECODE); } %typemap(in, fragment="NumPy_Fragments") (DATA_TYPE* INPLACE_FARRAY4, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DIM_TYPE DIM4) (PyArrayObject* array=NULL) { array = obj_to_array_no_conversion($input, DATA_TYPECODE); if (!array || !require_dimensions(array,4) || !require_contiguous(array) || !require_native(array) || !require_fortran(array)) SWIG_fail; $1 = (DATA_TYPE*) array_data(array); $2 = (DIM_TYPE) array_size(array,0); $3 = (DIM_TYPE) array_size(array,1); $4 = (DIM_TYPE) array_size(array,2); $5 = (DIM_TYPE) array_size(array,3); } /* Typemap suite for (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, * DATA_TYPE* INPLACE_FARRAY4) */ %typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, fragment="NumPy_Macros") (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DIM_TYPE DIM4, DATA_TYPE* INPLACE_FARRAY4) { $1 = is_array($input) && PyArray_EquivTypenums(array_type($input), DATA_TYPECODE); } %typemap(in, fragment="NumPy_Fragments") (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DIM_TYPE DIM4, DATA_TYPE* INPLACE_FARRAY4) (PyArrayObject* array=NULL) { array = obj_to_array_no_conversion($input, DATA_TYPECODE); if (!array || !require_dimensions(array,4) || !require_contiguous(array) || !require_native(array) || !require_fortran(array)) SWIG_fail; $1 = (DIM_TYPE) array_size(array,0); $2 = (DIM_TYPE) array_size(array,1); $3 = (DIM_TYPE) array_size(array,2); $4 = (DIM_TYPE) array_size(array,3); $5 = (DATA_TYPE*) array_data(array); } /*************************/ /* Argout Array Typemaps */ /*************************/ /* Typemap suite for (DATA_TYPE ARGOUT_ARRAY1[ANY]) */ %typemap(in,numinputs=0, fragment="NumPy_Backward_Compatibility,NumPy_Macros") (DATA_TYPE ARGOUT_ARRAY1[ANY]) (PyObject* array = NULL) { npy_intp dims[1] = { $1_dim0 }; array = PyArray_SimpleNew(1, dims, DATA_TYPECODE); if (!array) SWIG_fail; $1 = ($1_ltype) array_data(array); } %typemap(argout) (DATA_TYPE ARGOUT_ARRAY1[ANY]) { $result = SWIG_Python_AppendOutput($result,(PyObject*)array$argnum); } /* Typemap suite for (DATA_TYPE* ARGOUT_ARRAY1, DIM_TYPE DIM1) */ %typemap(in,numinputs=1, fragment="NumPy_Fragments") (DATA_TYPE* ARGOUT_ARRAY1, DIM_TYPE DIM1) (PyObject* array = NULL) { npy_intp dims[1]; if (!PyInt_Check($input)) { const char* typestring = pytype_string($input); PyErr_Format(PyExc_TypeError, "Int dimension expected. '%s' given.", typestring); SWIG_fail; } $2 = (DIM_TYPE) PyInt_AsLong($input); dims[0] = (npy_intp) $2; array = PyArray_SimpleNew(1, dims, DATA_TYPECODE); if (!array) SWIG_fail; $1 = (DATA_TYPE*) array_data(array); } %typemap(argout) (DATA_TYPE* ARGOUT_ARRAY1, DIM_TYPE DIM1) { $result = SWIG_Python_AppendOutput($result,(PyObject*)array$argnum); } /* Typemap suite for (DIM_TYPE DIM1, DATA_TYPE* ARGOUT_ARRAY1) */ %typemap(in,numinputs=1, fragment="NumPy_Fragments") (DIM_TYPE DIM1, DATA_TYPE* ARGOUT_ARRAY1) (PyObject* array = NULL) { npy_intp dims[1]; if (!PyInt_Check($input)) { const char* typestring = pytype_string($input); PyErr_Format(PyExc_TypeError, "Int dimension expected. '%s' given.", typestring); SWIG_fail; } $1 = (DIM_TYPE) PyInt_AsLong($input); dims[0] = (npy_intp) $1; array = PyArray_SimpleNew(1, dims, DATA_TYPECODE); if (!array) SWIG_fail; $2 = (DATA_TYPE*) array_data(array); } %typemap(argout) (DIM_TYPE DIM1, DATA_TYPE* ARGOUT_ARRAY1) { $result = SWIG_Python_AppendOutput($result,(PyObject*)array$argnum); } /* Typemap suite for (DATA_TYPE ARGOUT_ARRAY2[ANY][ANY]) */ %typemap(in,numinputs=0, fragment="NumPy_Backward_Compatibility,NumPy_Macros") (DATA_TYPE ARGOUT_ARRAY2[ANY][ANY]) (PyObject* array = NULL) { npy_intp dims[2] = { $1_dim0, $1_dim1 }; array = PyArray_SimpleNew(2, dims, DATA_TYPECODE); if (!array) SWIG_fail; $1 = ($1_ltype) array_data(array); } %typemap(argout) (DATA_TYPE ARGOUT_ARRAY2[ANY][ANY]) { $result = SWIG_Python_AppendOutput($result,(PyObject*)array$argnum); } /* Typemap suite for (DATA_TYPE ARGOUT_ARRAY3[ANY][ANY][ANY]) */ %typemap(in,numinputs=0, fragment="NumPy_Backward_Compatibility,NumPy_Macros") (DATA_TYPE ARGOUT_ARRAY3[ANY][ANY][ANY]) (PyObject* array = NULL) { npy_intp dims[3] = { $1_dim0, $1_dim1, $1_dim2 }; array = PyArray_SimpleNew(3, dims, DATA_TYPECODE); if (!array) SWIG_fail; $1 = ($1_ltype) array_data(array); } %typemap(argout) (DATA_TYPE ARGOUT_ARRAY3[ANY][ANY][ANY]) { $result = SWIG_Python_AppendOutput($result,(PyObject*)array$argnum); } /* Typemap suite for (DATA_TYPE ARGOUT_ARRAY4[ANY][ANY][ANY][ANY]) */ %typemap(in,numinputs=0, fragment="NumPy_Backward_Compatibility,NumPy_Macros") (DATA_TYPE ARGOUT_ARRAY4[ANY][ANY][ANY][ANY]) (PyObject* array = NULL) { npy_intp dims[4] = { $1_dim0, $1_dim1, $1_dim2, $1_dim3 }; array = PyArray_SimpleNew(4, dims, DATA_TYPECODE); if (!array) SWIG_fail; $1 = ($1_ltype) array_data(array); } %typemap(argout) (DATA_TYPE ARGOUT_ARRAY4[ANY][ANY][ANY][ANY]) { $result = SWIG_Python_AppendOutput($result,(PyObject*)array$argnum); } /*****************************/ /* Argoutview Array Typemaps */ /*****************************/ /* Typemap suite for (DATA_TYPE** ARGOUTVIEW_ARRAY1, DIM_TYPE* DIM1) */ %typemap(in,numinputs=0) (DATA_TYPE** ARGOUTVIEW_ARRAY1, DIM_TYPE* DIM1 ) (DATA_TYPE* data_temp = NULL , DIM_TYPE dim_temp) { $1 = &data_temp; $2 = &dim_temp; } %typemap(argout, fragment="NumPy_Backward_Compatibility") (DATA_TYPE** ARGOUTVIEW_ARRAY1, DIM_TYPE* DIM1) { npy_intp dims[1] = { *$2 }; PyObject* obj = PyArray_SimpleNewFromData(1, dims, DATA_TYPECODE, (void*)(*$1)); PyArrayObject* array = (PyArrayObject*) obj; if (!array) SWIG_fail; $result = SWIG_Python_AppendOutput($result,obj); } /* Typemap suite for (DIM_TYPE* DIM1, DATA_TYPE** ARGOUTVIEW_ARRAY1) */ %typemap(in,numinputs=0) (DIM_TYPE* DIM1 , DATA_TYPE** ARGOUTVIEW_ARRAY1) (DIM_TYPE dim_temp, DATA_TYPE* data_temp = NULL ) { $1 = &dim_temp; $2 = &data_temp; } %typemap(argout, fragment="NumPy_Backward_Compatibility") (DIM_TYPE* DIM1, DATA_TYPE** ARGOUTVIEW_ARRAY1) { npy_intp dims[1] = { *$1 }; PyObject* obj = PyArray_SimpleNewFromData(1, dims, DATA_TYPECODE, (void*)(*$2)); PyArrayObject* array = (PyArrayObject*) obj; if (!array) SWIG_fail; $result = SWIG_Python_AppendOutput($result,obj); } /* Typemap suite for (DATA_TYPE** ARGOUTVIEW_ARRAY2, DIM_TYPE* DIM1, DIM_TYPE* DIM2) */ %typemap(in,numinputs=0) (DATA_TYPE** ARGOUTVIEW_ARRAY2, DIM_TYPE* DIM1 , DIM_TYPE* DIM2 ) (DATA_TYPE* data_temp = NULL , DIM_TYPE dim1_temp, DIM_TYPE dim2_temp) { $1 = &data_temp; $2 = &dim1_temp; $3 = &dim2_temp; } %typemap(argout, fragment="NumPy_Backward_Compatibility") (DATA_TYPE** ARGOUTVIEW_ARRAY2, DIM_TYPE* DIM1, DIM_TYPE* DIM2) { npy_intp dims[2] = { *$2, *$3 }; PyObject* obj = PyArray_SimpleNewFromData(2, dims, DATA_TYPECODE, (void*)(*$1)); PyArrayObject* array = (PyArrayObject*) obj; if (!array) SWIG_fail; $result = SWIG_Python_AppendOutput($result,obj); } /* Typemap suite for (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DATA_TYPE** ARGOUTVIEW_ARRAY2) */ %typemap(in,numinputs=0) (DIM_TYPE* DIM1 , DIM_TYPE* DIM2 , DATA_TYPE** ARGOUTVIEW_ARRAY2) (DIM_TYPE dim1_temp, DIM_TYPE dim2_temp, DATA_TYPE* data_temp = NULL ) { $1 = &dim1_temp; $2 = &dim2_temp; $3 = &data_temp; } %typemap(argout, fragment="NumPy_Backward_Compatibility") (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DATA_TYPE** ARGOUTVIEW_ARRAY2) { npy_intp dims[2] = { *$1, *$2 }; PyObject* obj = PyArray_SimpleNewFromData(2, dims, DATA_TYPECODE, (void*)(*$3)); PyArrayObject* array = (PyArrayObject*) obj; if (!array) SWIG_fail; $result = SWIG_Python_AppendOutput($result,obj); } /* Typemap suite for (DATA_TYPE** ARGOUTVIEW_FARRAY2, DIM_TYPE* DIM1, DIM_TYPE* DIM2) */ %typemap(in,numinputs=0) (DATA_TYPE** ARGOUTVIEW_FARRAY2, DIM_TYPE* DIM1 , DIM_TYPE* DIM2 ) (DATA_TYPE* data_temp = NULL , DIM_TYPE dim1_temp, DIM_TYPE dim2_temp) { $1 = &data_temp; $2 = &dim1_temp; $3 = &dim2_temp; } %typemap(argout, fragment="NumPy_Backward_Compatibility,NumPy_Array_Requirements") (DATA_TYPE** ARGOUTVIEW_FARRAY2, DIM_TYPE* DIM1, DIM_TYPE* DIM2) { npy_intp dims[2] = { *$2, *$3 }; PyObject* obj = PyArray_SimpleNewFromData(2, dims, DATA_TYPECODE, (void*)(*$1)); PyArrayObject* array = (PyArrayObject*) obj; if (!array || !require_fortran(array)) SWIG_fail; $result = SWIG_Python_AppendOutput($result,obj); } /* Typemap suite for (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DATA_TYPE** ARGOUTVIEW_FARRAY2) */ %typemap(in,numinputs=0) (DIM_TYPE* DIM1 , DIM_TYPE* DIM2 , DATA_TYPE** ARGOUTVIEW_FARRAY2) (DIM_TYPE dim1_temp, DIM_TYPE dim2_temp, DATA_TYPE* data_temp = NULL ) { $1 = &dim1_temp; $2 = &dim2_temp; $3 = &data_temp; } %typemap(argout, fragment="NumPy_Backward_Compatibility,NumPy_Array_Requirements") (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DATA_TYPE** ARGOUTVIEW_FARRAY2) { npy_intp dims[2] = { *$1, *$2 }; PyObject* obj = PyArray_SimpleNewFromData(2, dims, DATA_TYPECODE, (void*)(*$3)); PyArrayObject* array = (PyArrayObject*) obj; if (!array || !require_fortran(array)) SWIG_fail; $result = SWIG_Python_AppendOutput($result,obj); } /* Typemap suite for (DATA_TYPE** ARGOUTVIEW_ARRAY3, DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3) */ %typemap(in,numinputs=0) (DATA_TYPE** ARGOUTVIEW_ARRAY3, DIM_TYPE* DIM1 , DIM_TYPE* DIM2 , DIM_TYPE* DIM3 ) (DATA_TYPE* data_temp = NULL , DIM_TYPE dim1_temp, DIM_TYPE dim2_temp, DIM_TYPE dim3_temp) { $1 = &data_temp; $2 = &dim1_temp; $3 = &dim2_temp; $4 = &dim3_temp; } %typemap(argout, fragment="NumPy_Backward_Compatibility") (DATA_TYPE** ARGOUTVIEW_ARRAY3, DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3) { npy_intp dims[3] = { *$2, *$3, *$4 }; PyObject* obj = PyArray_SimpleNewFromData(3, dims, DATA_TYPECODE, (void*)(*$1)); PyArrayObject* array = (PyArrayObject*) obj; if (!array) SWIG_fail; $result = SWIG_Python_AppendOutput($result,obj); } /* Typemap suite for (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DATA_TYPE** ARGOUTVIEW_ARRAY3) */ %typemap(in,numinputs=0) (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DATA_TYPE** ARGOUTVIEW_ARRAY3) (DIM_TYPE dim1_temp, DIM_TYPE dim2_temp, DIM_TYPE dim3_temp, DATA_TYPE* data_temp = NULL) { $1 = &dim1_temp; $2 = &dim2_temp; $3 = &dim3_temp; $4 = &data_temp; } %typemap(argout, fragment="NumPy_Backward_Compatibility") (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DATA_TYPE** ARGOUTVIEW_ARRAY3) { npy_intp dims[3] = { *$1, *$2, *$3 }; PyObject* obj = PyArray_SimpleNewFromData(3, dims, DATA_TYPECODE, (void*)(*$4)); PyArrayObject* array = (PyArrayObject*) obj; if (!array) SWIG_fail; $result = SWIG_Python_AppendOutput($result,obj); } /* Typemap suite for (DATA_TYPE** ARGOUTVIEW_FARRAY3, DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3) */ %typemap(in,numinputs=0) (DATA_TYPE** ARGOUTVIEW_FARRAY3, DIM_TYPE* DIM1 , DIM_TYPE* DIM2 , DIM_TYPE* DIM3 ) (DATA_TYPE* data_temp = NULL , DIM_TYPE dim1_temp, DIM_TYPE dim2_temp, DIM_TYPE dim3_temp) { $1 = &data_temp; $2 = &dim1_temp; $3 = &dim2_temp; $4 = &dim3_temp; } %typemap(argout, fragment="NumPy_Backward_Compatibility,NumPy_Array_Requirements") (DATA_TYPE** ARGOUTVIEW_FARRAY3, DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3) { npy_intp dims[3] = { *$2, *$3, *$4 }; PyObject* obj = PyArray_SimpleNewFromData(3, dims, DATA_TYPECODE, (void*)(*$1)); PyArrayObject* array = (PyArrayObject*) obj; if (!array || require_fortran(array)) SWIG_fail; $result = SWIG_Python_AppendOutput($result,obj); } /* Typemap suite for (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DATA_TYPE** ARGOUTVIEW_FARRAY3) */ %typemap(in,numinputs=0) (DIM_TYPE* DIM1 , DIM_TYPE* DIM2 , DIM_TYPE* DIM3 , DATA_TYPE** ARGOUTVIEW_FARRAY3) (DIM_TYPE dim1_temp, DIM_TYPE dim2_temp, DIM_TYPE dim3_temp, DATA_TYPE* data_temp = NULL ) { $1 = &dim1_temp; $2 = &dim2_temp; $3 = &dim3_temp; $4 = &data_temp; } %typemap(argout, fragment="NumPy_Backward_Compatibility,NumPy_Array_Requirements") (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DATA_TYPE** ARGOUTVIEW_FARRAY3) { npy_intp dims[3] = { *$1, *$2, *$3 }; PyObject* obj = PyArray_SimpleNewFromData(3, dims, DATA_TYPECODE, (void*)(*$4)); PyArrayObject* array = (PyArrayObject*) obj; if (!array || require_fortran(array)) SWIG_fail; $result = SWIG_Python_AppendOutput($result,obj); } /* Typemap suite for (DATA_TYPE** ARGOUTVIEW_ARRAY4, DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DIM_TYPE* DIM4) */ %typemap(in,numinputs=0) (DATA_TYPE** ARGOUTVIEW_ARRAY4, DIM_TYPE* DIM1 , DIM_TYPE* DIM2 , DIM_TYPE* DIM3 , DIM_TYPE* DIM4 ) (DATA_TYPE* data_temp = NULL , DIM_TYPE dim1_temp, DIM_TYPE dim2_temp, DIM_TYPE dim3_temp, DIM_TYPE dim4_temp) { $1 = &data_temp; $2 = &dim1_temp; $3 = &dim2_temp; $4 = &dim3_temp; $5 = &dim4_temp; } %typemap(argout, fragment="NumPy_Backward_Compatibility") (DATA_TYPE** ARGOUTVIEW_ARRAY4, DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DIM_TYPE* DIM4) { npy_intp dims[4] = { *$2, *$3, *$4 , *$5 }; PyObject* obj = PyArray_SimpleNewFromData(4, dims, DATA_TYPECODE, (void*)(*$1)); PyArrayObject* array = (PyArrayObject*) obj; if (!array) SWIG_fail; $result = SWIG_Python_AppendOutput($result,obj); } /* Typemap suite for (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DIM_TYPE* DIM4, DATA_TYPE** ARGOUTVIEW_ARRAY4) */ %typemap(in,numinputs=0) (DIM_TYPE* DIM1 , DIM_TYPE* DIM2 , DIM_TYPE* DIM3 , DIM_TYPE* DIM4 , DATA_TYPE** ARGOUTVIEW_ARRAY4) (DIM_TYPE dim1_temp, DIM_TYPE dim2_temp, DIM_TYPE dim3_temp, DIM_TYPE dim4_temp, DATA_TYPE* data_temp = NULL ) { $1 = &dim1_temp; $2 = &dim2_temp; $3 = &dim3_temp; $4 = &dim4_temp; $5 = &data_temp; } %typemap(argout, fragment="NumPy_Backward_Compatibility") (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DIM_TYPE* DIM4, DATA_TYPE** ARGOUTVIEW_ARRAY4) { npy_intp dims[4] = { *$1, *$2, *$3 , *$4 }; PyObject* obj = PyArray_SimpleNewFromData(4, dims, DATA_TYPECODE, (void*)(*$5)); PyArrayObject* array = (PyArrayObject*) obj; if (!array) SWIG_fail; $result = SWIG_Python_AppendOutput($result,obj); } /* Typemap suite for (DATA_TYPE** ARGOUTVIEW_FARRAY4, DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DIM_TYPE* DIM4) */ %typemap(in,numinputs=0) (DATA_TYPE** ARGOUTVIEW_FARRAY4, DIM_TYPE* DIM1 , DIM_TYPE* DIM2 , DIM_TYPE* DIM3 , DIM_TYPE* DIM4 ) (DATA_TYPE* data_temp = NULL , DIM_TYPE dim1_temp, DIM_TYPE dim2_temp, DIM_TYPE dim3_temp, DIM_TYPE dim4_temp) { $1 = &data_temp; $2 = &dim1_temp; $3 = &dim2_temp; $4 = &dim3_temp; $5 = &dim4_temp; } %typemap(argout, fragment="NumPy_Backward_Compatibility,NumPy_Array_Requirements") (DATA_TYPE** ARGOUTVIEW_FARRAY4, DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DIM_TYPE* DIM4) { npy_intp dims[4] = { *$2, *$3, *$4 , *$5 }; PyObject* obj = PyArray_SimpleNewFromData(4, dims, DATA_TYPECODE, (void*)(*$1)); PyArrayObject* array = (PyArrayObject*) obj; if (!array || require_fortran(array)) SWIG_fail; $result = SWIG_Python_AppendOutput($result,obj); } /* Typemap suite for (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DIM_TYPE* DIM4, DATA_TYPE** ARGOUTVIEW_FARRAY4) */ %typemap(in,numinputs=0) (DIM_TYPE* DIM1 , DIM_TYPE* DIM2 , DIM_TYPE* DIM3 , DIM_TYPE* DIM4 , DATA_TYPE** ARGOUTVIEW_FARRAY4) (DIM_TYPE dim1_temp, DIM_TYPE dim2_temp, DIM_TYPE dim3_temp, DIM_TYPE dim4_temp, DATA_TYPE* data_temp = NULL ) { $1 = &dim1_temp; $2 = &dim2_temp; $3 = &dim3_temp; $4 = &dim4_temp; $5 = &data_temp; } %typemap(argout, fragment="NumPy_Backward_Compatibility,NumPy_Array_Requirements") (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DIM_TYPE* DIM4, DATA_TYPE** ARGOUTVIEW_FARRAY4) { npy_intp dims[4] = { *$1, *$2, *$3 , *$4 }; PyObject* obj = PyArray_SimpleNewFromData(4, dims, DATA_TYPECODE, (void*)(*$5)); PyArrayObject* array = (PyArrayObject*) obj; if (!array || require_fortran(array)) SWIG_fail; $result = SWIG_Python_AppendOutput($result,obj); } /*************************************/ /* Managed Argoutview Array Typemaps */ /*************************************/ /* Typemap suite for (DATA_TYPE** ARGOUTVIEWM_ARRAY1, DIM_TYPE* DIM1) */ %typemap(in,numinputs=0) (DATA_TYPE** ARGOUTVIEWM_ARRAY1, DIM_TYPE* DIM1 ) (DATA_TYPE* data_temp = NULL , DIM_TYPE dim_temp) { $1 = &data_temp; $2 = &dim_temp; } %typemap(argout, fragment="NumPy_Backward_Compatibility") (DATA_TYPE** ARGOUTVIEWM_ARRAY1, DIM_TYPE* DIM1) { npy_intp dims[1] = { *$2 }; PyObject* obj = PyArray_SimpleNewFromData(1, dims, DATA_TYPECODE, (void*)(*$1)); PyArrayObject* array = (PyArrayObject*) obj; if (!array) SWIG_fail; %#ifdef SWIGPY_USE_CAPSULE PyObject* cap = PyCapsule_New((void*)(*$1), SWIGPY_CAPSULE_NAME, free_cap); %#else PyObject* cap = PyCObject_FromVoidPtr((void*)(*$1), free); %#endif %#if NPY_API_VERSION < 0x00000007 PyArray_BASE(array) = cap; %#else PyArray_SetBaseObject(array,cap); %#endif $result = SWIG_Python_AppendOutput($result,obj); } /* Typemap suite for (DIM_TYPE* DIM1, DATA_TYPE** ARGOUTVIEWM_ARRAY1) */ %typemap(in,numinputs=0) (DIM_TYPE* DIM1 , DATA_TYPE** ARGOUTVIEWM_ARRAY1) (DIM_TYPE dim_temp, DATA_TYPE* data_temp = NULL ) { $1 = &dim_temp; $2 = &data_temp; } %typemap(argout, fragment="NumPy_Backward_Compatibility") (DIM_TYPE* DIM1, DATA_TYPE** ARGOUTVIEWM_ARRAY1) { npy_intp dims[1] = { *$1 }; PyObject* obj = PyArray_SimpleNewFromData(1, dims, DATA_TYPECODE, (void*)(*$2)); PyArrayObject* array = (PyArrayObject*) obj; if (!array) SWIG_fail; %#ifdef SWIGPY_USE_CAPSULE PyObject* cap = PyCapsule_New((void*)(*$1), SWIGPY_CAPSULE_NAME, free_cap); %#else PyObject* cap = PyCObject_FromVoidPtr((void*)(*$1), free); %#endif %#if NPY_API_VERSION < 0x00000007 PyArray_BASE(array) = cap; %#else PyArray_SetBaseObject(array,cap); %#endif $result = SWIG_Python_AppendOutput($result,obj); } /* Typemap suite for (DATA_TYPE** ARGOUTVIEWM_ARRAY2, DIM_TYPE* DIM1, DIM_TYPE* DIM2) */ %typemap(in,numinputs=0) (DATA_TYPE** ARGOUTVIEWM_ARRAY2, DIM_TYPE* DIM1 , DIM_TYPE* DIM2 ) (DATA_TYPE* data_temp = NULL , DIM_TYPE dim1_temp, DIM_TYPE dim2_temp) { $1 = &data_temp; $2 = &dim1_temp; $3 = &dim2_temp; } %typemap(argout, fragment="NumPy_Backward_Compatibility") (DATA_TYPE** ARGOUTVIEWM_ARRAY2, DIM_TYPE* DIM1, DIM_TYPE* DIM2) { npy_intp dims[2] = { *$2, *$3 }; PyObject* obj = PyArray_SimpleNewFromData(2, dims, DATA_TYPECODE, (void*)(*$1)); PyArrayObject* array = (PyArrayObject*) obj; if (!array) SWIG_fail; %#ifdef SWIGPY_USE_CAPSULE PyObject* cap = PyCapsule_New((void*)(*$1), SWIGPY_CAPSULE_NAME, free_cap); %#else PyObject* cap = PyCObject_FromVoidPtr((void*)(*$1), free); %#endif %#if NPY_API_VERSION < 0x00000007 PyArray_BASE(array) = cap; %#else PyArray_SetBaseObject(array,cap); %#endif $result = SWIG_Python_AppendOutput($result,obj); } /* Typemap suite for (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DATA_TYPE** ARGOUTVIEWM_ARRAY2) */ %typemap(in,numinputs=0) (DIM_TYPE* DIM1 , DIM_TYPE* DIM2 , DATA_TYPE** ARGOUTVIEWM_ARRAY2) (DIM_TYPE dim1_temp, DIM_TYPE dim2_temp, DATA_TYPE* data_temp = NULL ) { $1 = &dim1_temp; $2 = &dim2_temp; $3 = &data_temp; } %typemap(argout, fragment="NumPy_Backward_Compatibility") (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DATA_TYPE** ARGOUTVIEWM_ARRAY2) { npy_intp dims[2] = { *$1, *$2 }; PyObject* obj = PyArray_SimpleNewFromData(2, dims, DATA_TYPECODE, (void*)(*$3)); PyArrayObject* array = (PyArrayObject*) obj; if (!array) SWIG_fail; %#ifdef SWIGPY_USE_CAPSULE PyObject* cap = PyCapsule_New((void*)(*$1), SWIGPY_CAPSULE_NAME, free_cap); %#else PyObject* cap = PyCObject_FromVoidPtr((void*)(*$1), free); %#endif %#if NPY_API_VERSION < 0x00000007 PyArray_BASE(array) = cap; %#else PyArray_SetBaseObject(array,cap); %#endif $result = SWIG_Python_AppendOutput($result,obj); } /* Typemap suite for (DATA_TYPE** ARGOUTVIEWM_FARRAY2, DIM_TYPE* DIM1, DIM_TYPE* DIM2) */ %typemap(in,numinputs=0) (DATA_TYPE** ARGOUTVIEWM_FARRAY2, DIM_TYPE* DIM1 , DIM_TYPE* DIM2 ) (DATA_TYPE* data_temp = NULL , DIM_TYPE dim1_temp, DIM_TYPE dim2_temp) { $1 = &data_temp; $2 = &dim1_temp; $3 = &dim2_temp; } %typemap(argout, fragment="NumPy_Backward_Compatibility,NumPy_Array_Requirements") (DATA_TYPE** ARGOUTVIEWM_FARRAY2, DIM_TYPE* DIM1, DIM_TYPE* DIM2) { npy_intp dims[2] = { *$2, *$3 }; PyObject* obj = PyArray_SimpleNewFromData(2, dims, DATA_TYPECODE, (void*)(*$1)); PyArrayObject* array = (PyArrayObject*) obj; if (!array || !require_fortran(array)) SWIG_fail; %#ifdef SWIGPY_USE_CAPSULE PyObject* cap = PyCapsule_New((void*)(*$1), SWIGPY_CAPSULE_NAME, free_cap); %#else PyObject* cap = PyCObject_FromVoidPtr((void*)(*$1), free); %#endif %#if NPY_API_VERSION < 0x00000007 PyArray_BASE(array) = cap; %#else PyArray_SetBaseObject(array,cap); %#endif $result = SWIG_Python_AppendOutput($result,obj); } /* Typemap suite for (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DATA_TYPE** ARGOUTVIEWM_FARRAY2) */ %typemap(in,numinputs=0) (DIM_TYPE* DIM1 , DIM_TYPE* DIM2 , DATA_TYPE** ARGOUTVIEWM_FARRAY2) (DIM_TYPE dim1_temp, DIM_TYPE dim2_temp, DATA_TYPE* data_temp = NULL ) { $1 = &dim1_temp; $2 = &dim2_temp; $3 = &data_temp; } %typemap(argout, fragment="NumPy_Backward_Compatibility,NumPy_Array_Requirements") (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DATA_TYPE** ARGOUTVIEWM_FARRAY2) { npy_intp dims[2] = { *$1, *$2 }; PyObject* obj = PyArray_SimpleNewFromData(2, dims, DATA_TYPECODE, (void*)(*$3)); PyArrayObject* array = (PyArrayObject*) obj; if (!array || !require_fortran(array)) SWIG_fail; %#ifdef SWIGPY_USE_CAPSULE PyObject* cap = PyCapsule_New((void*)(*$1), SWIGPY_CAPSULE_NAME, free_cap); %#else PyObject* cap = PyCObject_FromVoidPtr((void*)(*$1), free); %#endif %#if NPY_API_VERSION < 0x00000007 PyArray_BASE(array) = cap; %#else PyArray_SetBaseObject(array,cap); %#endif $result = SWIG_Python_AppendOutput($result,obj); } /* Typemap suite for (DATA_TYPE** ARGOUTVIEWM_ARRAY3, DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3) */ %typemap(in,numinputs=0) (DATA_TYPE** ARGOUTVIEWM_ARRAY3, DIM_TYPE* DIM1 , DIM_TYPE* DIM2 , DIM_TYPE* DIM3 ) (DATA_TYPE* data_temp = NULL , DIM_TYPE dim1_temp, DIM_TYPE dim2_temp, DIM_TYPE dim3_temp) { $1 = &data_temp; $2 = &dim1_temp; $3 = &dim2_temp; $4 = &dim3_temp; } %typemap(argout, fragment="NumPy_Backward_Compatibility") (DATA_TYPE** ARGOUTVIEWM_ARRAY3, DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3) { npy_intp dims[3] = { *$2, *$3, *$4 }; PyObject* obj = PyArray_SimpleNewFromData(3, dims, DATA_TYPECODE, (void*)(*$1)); PyArrayObject* array = (PyArrayObject*) obj; if (!array) SWIG_fail; %#ifdef SWIGPY_USE_CAPSULE PyObject* cap = PyCapsule_New((void*)(*$1), SWIGPY_CAPSULE_NAME, free_cap); %#else PyObject* cap = PyCObject_FromVoidPtr((void*)(*$1), free); %#endif %#if NPY_API_VERSION < 0x00000007 PyArray_BASE(array) = cap; %#else PyArray_SetBaseObject(array,cap); %#endif $result = SWIG_Python_AppendOutput($result,obj); } /* Typemap suite for (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DATA_TYPE** ARGOUTVIEWM_ARRAY3) */ %typemap(in,numinputs=0) (DIM_TYPE* DIM1 , DIM_TYPE* DIM2 , DIM_TYPE* DIM3 , DATA_TYPE** ARGOUTVIEWM_ARRAY3) (DIM_TYPE dim1_temp, DIM_TYPE dim2_temp, DIM_TYPE dim3_temp, DATA_TYPE* data_temp = NULL ) { $1 = &dim1_temp; $2 = &dim2_temp; $3 = &dim3_temp; $4 = &data_temp; } %typemap(argout, fragment="NumPy_Backward_Compatibility") (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DATA_TYPE** ARGOUTVIEWM_ARRAY3) { npy_intp dims[3] = { *$1, *$2, *$3 }; PyObject* obj= PyArray_SimpleNewFromData(3, dims, DATA_TYPECODE, (void*)(*$4)); PyArrayObject* array = (PyArrayObject*) obj; if (!array) SWIG_fail; %#ifdef SWIGPY_USE_CAPSULE PyObject* cap = PyCapsule_New((void*)(*$1), SWIGPY_CAPSULE_NAME, free_cap); %#else PyObject* cap = PyCObject_FromVoidPtr((void*)(*$1), free); %#endif %#if NPY_API_VERSION < 0x00000007 PyArray_BASE(array) = cap; %#else PyArray_SetBaseObject(array,cap); %#endif $result = SWIG_Python_AppendOutput($result,obj); } /* Typemap suite for (DATA_TYPE** ARGOUTVIEWM_FARRAY3, DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3) */ %typemap(in,numinputs=0) (DATA_TYPE** ARGOUTVIEWM_FARRAY3, DIM_TYPE* DIM1 , DIM_TYPE* DIM2 , DIM_TYPE* DIM3 ) (DATA_TYPE* data_temp = NULL , DIM_TYPE dim1_temp, DIM_TYPE dim2_temp, DIM_TYPE dim3_temp) { $1 = &data_temp; $2 = &dim1_temp; $3 = &dim2_temp; $4 = &dim3_temp; } %typemap(argout, fragment="NumPy_Backward_Compatibility,NumPy_Array_Requirements") (DATA_TYPE** ARGOUTVIEWM_FARRAY3, DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3) { npy_intp dims[3] = { *$2, *$3, *$4 }; PyObject* obj = PyArray_SimpleNewFromData(3, dims, DATA_TYPECODE, (void*)(*$1)); PyArrayObject* array = (PyArrayObject*) obj; if (!array || require_fortran(array)) SWIG_fail; %#ifdef SWIGPY_USE_CAPSULE PyObject* cap = PyCapsule_New((void*)(*$1), SWIGPY_CAPSULE_NAME, free_cap); %#else PyObject* cap = PyCObject_FromVoidPtr((void*)(*$1), free); %#endif %#if NPY_API_VERSION < 0x00000007 PyArray_BASE(array) = cap; %#else PyArray_SetBaseObject(array,cap); %#endif $result = SWIG_Python_AppendOutput($result,obj); } /* Typemap suite for (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DATA_TYPE** ARGOUTVIEWM_FARRAY3) */ %typemap(in,numinputs=0) (DIM_TYPE* DIM1 , DIM_TYPE* DIM2 , DIM_TYPE* DIM3 , DATA_TYPE** ARGOUTVIEWM_FARRAY3) (DIM_TYPE dim1_temp, DIM_TYPE dim2_temp, DIM_TYPE dim3_temp, DATA_TYPE* data_temp = NULL ) { $1 = &dim1_temp; $2 = &dim2_temp; $3 = &dim3_temp; $4 = &data_temp; } %typemap(argout, fragment="NumPy_Backward_Compatibility,NumPy_Array_Requirements") (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DATA_TYPE** ARGOUTVIEWM_FARRAY3) { npy_intp dims[3] = { *$1, *$2, *$3 }; PyObject* obj = PyArray_SimpleNewFromData(3, dims, DATA_TYPECODE, (void*)(*$4)); PyArrayObject* array = (PyArrayObject*) obj; if (!array || require_fortran(array)) SWIG_fail; %#ifdef SWIGPY_USE_CAPSULE PyObject* cap = PyCapsule_New((void*)(*$1), SWIGPY_CAPSULE_NAME, free_cap); %#else PyObject* cap = PyCObject_FromVoidPtr((void*)(*$1), free); %#endif %#if NPY_API_VERSION < 0x00000007 PyArray_BASE(array) = cap; %#else PyArray_SetBaseObject(array,cap); %#endif $result = SWIG_Python_AppendOutput($result,obj); } /* Typemap suite for (DATA_TYPE** ARGOUTVIEWM_ARRAY4, DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DIM_TYPE* DIM4) */ %typemap(in,numinputs=0) (DATA_TYPE** ARGOUTVIEWM_ARRAY4, DIM_TYPE* DIM1 , DIM_TYPE* DIM2 , DIM_TYPE* DIM3 , DIM_TYPE* DIM4 ) (DATA_TYPE* data_temp = NULL , DIM_TYPE dim1_temp, DIM_TYPE dim2_temp, DIM_TYPE dim3_temp, DIM_TYPE dim4_temp) { $1 = &data_temp; $2 = &dim1_temp; $3 = &dim2_temp; $4 = &dim3_temp; $5 = &dim4_temp; } %typemap(argout, fragment="NumPy_Backward_Compatibility") (DATA_TYPE** ARGOUTVIEWM_ARRAY4, DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DIM_TYPE* DIM4) { npy_intp dims[4] = { *$2, *$3, *$4 , *$5 }; PyObject* obj = PyArray_SimpleNewFromData(4, dims, DATA_TYPECODE, (void*)(*$1)); PyArrayObject* array = (PyArrayObject*) obj; if (!array) SWIG_fail; %#ifdef SWIGPY_USE_CAPSULE PyObject* cap = PyCapsule_New((void*)(*$1), SWIGPY_CAPSULE_NAME, free_cap); %#else PyObject* cap = PyCObject_FromVoidPtr((void*)(*$1), free); %#endif %#if NPY_API_VERSION < 0x00000007 PyArray_BASE(array) = cap; %#else PyArray_SetBaseObject(array,cap); %#endif $result = SWIG_Python_AppendOutput($result,obj); } /* Typemap suite for (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DIM_TYPE* DIM4, DATA_TYPE** ARGOUTVIEWM_ARRAY4) */ %typemap(in,numinputs=0) (DIM_TYPE* DIM1 , DIM_TYPE* DIM2 , DIM_TYPE* DIM3 , DIM_TYPE* DIM4 , DATA_TYPE** ARGOUTVIEWM_ARRAY4) (DIM_TYPE dim1_temp, DIM_TYPE dim2_temp, DIM_TYPE dim3_temp, DIM_TYPE dim4_temp, DATA_TYPE* data_temp = NULL ) { $1 = &dim1_temp; $2 = &dim2_temp; $3 = &dim3_temp; $4 = &dim4_temp; $5 = &data_temp; } %typemap(argout, fragment="NumPy_Backward_Compatibility") (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DIM_TYPE* DIM4, DATA_TYPE** ARGOUTVIEWM_ARRAY4) { npy_intp dims[4] = { *$1, *$2, *$3 , *$4 }; PyObject* obj = PyArray_SimpleNewFromData(4, dims, DATA_TYPECODE, (void*)(*$5)); PyArrayObject* array = (PyArrayObject*) obj; if (!array) SWIG_fail; %#ifdef SWIGPY_USE_CAPSULE PyObject* cap = PyCapsule_New((void*)(*$1), SWIGPY_CAPSULE_NAME, free_cap); %#else PyObject* cap = PyCObject_FromVoidPtr((void*)(*$1), free); %#endif %#if NPY_API_VERSION < 0x00000007 PyArray_BASE(array) = cap; %#else PyArray_SetBaseObject(array,cap); %#endif $result = SWIG_Python_AppendOutput($result,obj); } /* Typemap suite for (DATA_TYPE** ARGOUTVIEWM_FARRAY4, DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DIM_TYPE* DIM4) */ %typemap(in,numinputs=0) (DATA_TYPE** ARGOUTVIEWM_FARRAY4, DIM_TYPE* DIM1 , DIM_TYPE* DIM2 , DIM_TYPE* DIM3 , DIM_TYPE* DIM4 ) (DATA_TYPE* data_temp = NULL , DIM_TYPE dim1_temp, DIM_TYPE dim2_temp, DIM_TYPE dim3_temp, DIM_TYPE dim4_temp) { $1 = &data_temp; $2 = &dim1_temp; $3 = &dim2_temp; $4 = &dim3_temp; $5 = &dim4_temp; } %typemap(argout, fragment="NumPy_Backward_Compatibility,NumPy_Array_Requirements") (DATA_TYPE** ARGOUTVIEWM_FARRAY4, DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3) { npy_intp dims[4] = { *$2, *$3, *$4 , *$5 }; PyObject* obj = PyArray_SimpleNewFromData(4, dims, DATA_TYPECODE, (void*)(*$1)); PyArrayObject* array = (PyArrayObject*) obj; if (!array || require_fortran(array)) SWIG_fail; %#ifdef SWIGPY_USE_CAPSULE PyObject* cap = PyCapsule_New((void*)(*$1), SWIGPY_CAPSULE_NAME, free_cap); %#else PyObject* cap = PyCObject_FromVoidPtr((void*)(*$1), free); %#endif %#if NPY_API_VERSION < 0x00000007 PyArray_BASE(array) = cap; %#else PyArray_SetBaseObject(array,cap); %#endif $result = SWIG_Python_AppendOutput($result,obj); } /* Typemap suite for (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DIM_TYPE* DIM4, DATA_TYPE** ARGOUTVIEWM_FARRAY4) */ %typemap(in,numinputs=0) (DIM_TYPE* DIM1 , DIM_TYPE* DIM2 , DIM_TYPE* DIM3 , DIM_TYPE* DIM4 , DATA_TYPE** ARGOUTVIEWM_FARRAY4) (DIM_TYPE dim1_temp, DIM_TYPE dim2_temp, DIM_TYPE dim3_temp, DIM_TYPE dim4_temp, DATA_TYPE* data_temp = NULL ) { $1 = &dim1_temp; $2 = &dim2_temp; $3 = &dim3_temp; $4 = &dim4_temp; $5 = &data_temp; } %typemap(argout, fragment="NumPy_Backward_Compatibility,NumPy_Array_Requirements") (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DIM_TYPE* DIM4, DATA_TYPE** ARGOUTVIEWM_FARRAY4) { npy_intp dims[4] = { *$1, *$2, *$3 , *$4 }; PyObject* obj = PyArray_SimpleNewFromData(4, dims, DATA_TYPECODE, (void*)(*$5)); PyArrayObject* array = (PyArrayObject*) obj; if (!array || require_fortran(array)) SWIG_fail; %#ifdef SWIGPY_USE_CAPSULE PyObject* cap = PyCapsule_New((void*)(*$1), SWIGPY_CAPSULE_NAME, free_cap); %#else PyObject* cap = PyCObject_FromVoidPtr((void*)(*$1), free); %#endif %#if NPY_API_VERSION < 0x00000007 PyArray_BASE(array) = cap; %#else PyArray_SetBaseObject(array,cap); %#endif $result = SWIG_Python_AppendOutput($result,obj); } /* Typemap suite for (DATA_TYPE** ARGOUTVIEWM_ARRAY4, DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DIM_TYPE* DIM4) */ %typemap(in,numinputs=0) (DATA_TYPE** ARGOUTVIEWM_ARRAY4, DIM_TYPE* DIM1 , DIM_TYPE* DIM2 , DIM_TYPE* DIM3 , DIM_TYPE* DIM4 ) (DATA_TYPE* data_temp = NULL , DIM_TYPE dim1_temp, DIM_TYPE dim2_temp, DIM_TYPE dim3_temp, DIM_TYPE dim4_temp) { $1 = &data_temp; $2 = &dim1_temp; $3 = &dim2_temp; $4 = &dim3_temp; $5 = &dim4_temp; } %typemap(argout, fragment="NumPy_Backward_Compatibility") (DATA_TYPE** ARGOUTVIEWM_ARRAY4, DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DIM_TYPE* DIM4) { npy_intp dims[4] = { *$2, *$3, *$4 , *$5 }; PyObject* obj = PyArray_SimpleNewFromData(4, dims, DATA_TYPECODE, (void*)(*$1)); PyArrayObject* array = (PyArrayObject*) obj; if (!array) SWIG_fail; %#ifdef SWIGPY_USE_CAPSULE PyObject* cap = PyCapsule_New((void*)(*$1), SWIGPY_CAPSULE_NAME, free_cap); %#else PyObject* cap = PyCObject_FromVoidPtr((void*)(*$1), free); %#endif %#if NPY_API_VERSION < 0x00000007 PyArray_BASE(array) = cap; %#else PyArray_SetBaseObject(array,cap); %#endif $result = SWIG_Python_AppendOutput($result,obj); } /* Typemap suite for (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DIM_TYPE* DIM4, DATA_TYPE** ARGOUTVIEWM_ARRAY4) */ %typemap(in,numinputs=0) (DIM_TYPE* DIM1 , DIM_TYPE* DIM2 , DIM_TYPE* DIM3 , DIM_TYPE* DIM4 , DATA_TYPE** ARGOUTVIEWM_ARRAY4) (DIM_TYPE dim1_temp, DIM_TYPE dim2_temp, DIM_TYPE dim3_temp, DIM_TYPE dim4_temp, DATA_TYPE* data_temp = NULL ) { $1 = &dim1_temp; $2 = &dim2_temp; $3 = &dim3_temp; $4 = &dim4_temp; $5 = &data_temp; } %typemap(argout, fragment="NumPy_Backward_Compatibility") (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DIM_TYPE* DIM4, DATA_TYPE** ARGOUTVIEWM_ARRAY4) { npy_intp dims[4] = { *$1, *$2, *$3 , *$4 }; PyObject* obj = PyArray_SimpleNewFromData(4, dims, DATA_TYPECODE, (void*)(*$5)); PyArrayObject* array = (PyArrayObject*) obj; if (!array) SWIG_fail; %#ifdef SWIGPY_USE_CAPSULE PyObject* cap = PyCapsule_New((void*)(*$1), SWIGPY_CAPSULE_NAME, free_cap); %#else PyObject* cap = PyCObject_FromVoidPtr((void*)(*$1), free); %#endif %#if NPY_API_VERSION < 0x00000007 PyArray_BASE(array) = cap; %#else PyArray_SetBaseObject(array,cap); %#endif $result = SWIG_Python_AppendOutput($result,obj); } /* Typemap suite for (DATA_TYPE** ARGOUTVIEWM_FARRAY4, DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DIM_TYPE* DIM4) */ %typemap(in,numinputs=0) (DATA_TYPE** ARGOUTVIEWM_FARRAY4, DIM_TYPE* DIM1 , DIM_TYPE* DIM2 , DIM_TYPE* DIM3 , DIM_TYPE* DIM4 ) (DATA_TYPE* data_temp = NULL , DIM_TYPE dim1_temp, DIM_TYPE dim2_temp, DIM_TYPE dim3_temp, DIM_TYPE dim4_temp) { $1 = &data_temp; $2 = &dim1_temp; $3 = &dim2_temp; $4 = &dim3_temp; $5 = &dim4_temp; } %typemap(argout, fragment="NumPy_Backward_Compatibility,NumPy_Array_Requirements") (DATA_TYPE** ARGOUTVIEWM_FARRAY4, DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DIM_TYPE* DIM4) { npy_intp dims[4] = { *$2, *$3, *$4 , *$5 }; PyObject* obj = PyArray_SimpleNewFromData(4, dims, DATA_TYPECODE, (void*)(*$1)); PyArrayObject* array = (PyArrayObject*) obj; if (!array || require_fortran(array)) SWIG_fail; %#ifdef SWIGPY_USE_CAPSULE PyObject* cap = PyCapsule_New((void*)(*$1), SWIGPY_CAPSULE_NAME, free_cap); %#else PyObject* cap = PyCObject_FromVoidPtr((void*)(*$1), free); %#endif %#if NPY_API_VERSION < 0x00000007 PyArray_BASE(array) = cap; %#else PyArray_SetBaseObject(array,cap); %#endif $result = SWIG_Python_AppendOutput($result,obj); } /* Typemap suite for (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DIM_TYPE* DIM4, DATA_TYPE** ARGOUTVIEWM_FARRAY4) */ %typemap(in,numinputs=0) (DIM_TYPE* DIM1 , DIM_TYPE* DIM2 , DIM_TYPE* DIM3 , DIM_TYPE* DIM4 , DATA_TYPE** ARGOUTVIEWM_FARRAY4) (DIM_TYPE dim1_temp, DIM_TYPE dim2_temp, DIM_TYPE dim3_temp, DIM_TYPE dim4_temp, DATA_TYPE* data_temp = NULL ) { $1 = &dim1_temp; $2 = &dim2_temp; $3 = &dim3_temp; $4 = &dim4_temp; $5 = &data_temp; } %typemap(argout, fragment="NumPy_Backward_Compatibility,NumPy_Array_Requirements") (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DIM_TYPE* DIM4, DATA_TYPE** ARGOUTVIEWM_FARRAY4) { npy_intp dims[4] = { *$1, *$2, *$3 , *$4 }; PyObject* obj = PyArray_SimpleNewFromData(4, dims, DATA_TYPECODE, (void*)(*$5)); PyArrayObject* array = (PyArrayObject*) obj; if (!array || require_fortran(array)) SWIG_fail; %#ifdef SWIGPY_USE_CAPSULE PyObject* cap = PyCapsule_New((void*)(*$1), SWIGPY_CAPSULE_NAME, free_cap); %#else PyObject* cap = PyCObject_FromVoidPtr((void*)(*$1), free); %#endif %#if NPY_API_VERSION < 0x00000007 PyArray_BASE(array) = cap; %#else PyArray_SetBaseObject(array,cap); %#endif $result = SWIG_Python_AppendOutput($result,obj); } %enddef /* %numpy_typemaps() macro */ /* *************************************************************** */ /* Concrete instances of the %numpy_typemaps() macro: Each invocation * below applies all of the typemaps above to the specified data type. */ %numpy_typemaps(signed char , NPY_BYTE , int) %numpy_typemaps(unsigned char , NPY_UBYTE , int) %numpy_typemaps(short , NPY_SHORT , int) %numpy_typemaps(unsigned short , NPY_USHORT , int) %numpy_typemaps(int , NPY_INT , int) %numpy_typemaps(unsigned int , NPY_UINT , int) %numpy_typemaps(long , NPY_LONG , int) %numpy_typemaps(unsigned long , NPY_ULONG , int) %numpy_typemaps(long long , NPY_LONGLONG , int) %numpy_typemaps(unsigned long long, NPY_ULONGLONG, int) %numpy_typemaps(float , NPY_FLOAT , int) %numpy_typemaps(double , NPY_DOUBLE , int) /* *************************************************************** * The follow macro expansion does not work, because C++ bool is 4 * bytes and NPY_BOOL is 1 byte * * %numpy_typemaps(bool, NPY_BOOL, int) */ /* *************************************************************** * On my Mac, I get the following warning for this macro expansion: * 'swig/python detected a memory leak of type 'long double *', no destructor found.' * * %numpy_typemaps(long double, NPY_LONGDOUBLE, int) */ /* *************************************************************** * Swig complains about a syntax error for the following macro * expansions: * * %numpy_typemaps(complex float, NPY_CFLOAT , int) * * %numpy_typemaps(complex double, NPY_CDOUBLE, int) * * %numpy_typemaps(complex long double, NPY_CLONGDOUBLE, int) */ #endif /* SWIGPYTHON */ numpy-1.8.2/doc/swig/README0000664000175100017510000001120112370216243016415 0ustar vagrantvagrant00000000000000Notes for the numpy/doc/swig directory ====================================== This set of files is for developing and testing file numpy.i, which is intended to be a set of typemaps for helping SWIG interface between C and C++ code that uses C arrays and the python module NumPy. It is ultimately hoped that numpy.i will be included as part of the SWIG distribution. Documentation ------------- Documentation for how to use numpy.i, as well as for the testing system used here, can be found in the NumPy reference guide. Testing ------- The tests are a good example of what we are trying to do with numpy.i. The files related to testing are are in the test subdirectory:: Vector.h Vector.cxx Vector.i testVector.py Matrix.h Matrix.cxx Matrix.i testMatrix.py Tensor.h Tensor.cxx Tensor.i testTensor.py SuperTensor.h SuperTensor.cxx SuperTensor.i testSuperTensor.py The header files contain prototypes for functions that illustrate the wrapping issues we wish to address. Right now, this consists of functions with argument signatures of the following forms. Vector.h:: (type IN_ARRAY1[ANY]) (type* IN_ARRAY1, int DIM1) (int DIM1, type* IN_ARRAY1) (type INPLACE_ARRAY1[ANY]) (type* INPLACE_ARRAY1, int DIM1) (int DIM1, type* INPLACE_ARRAY1) (type ARGOUT_ARRAY1[ANY]) (type* ARGOUT_ARRAY1, int DIM1) (int DIM1, type* ARGOUT_ARRAY1) Matrix.h:: (type IN_ARRAY2[ANY][ANY]) (type* IN_ARRAY2, int DIM1, int DIM2) (int DIM1, int DIM2, type* IN_ARRAY2) (type INPLACE_ARRAY2[ANY][ANY]) (type* INPLACE_ARRAY2, int DIM1, int DIM2) (int DIM1, int DIM2, type* INPLACE_ARRAY2) (type ARGOUT_ARRAY2[ANY][ANY]) Tensor.h:: (type IN_ARRAY3[ANY][ANY][ANY]) (type* IN_ARRAY3, int DIM1, int DIM2, int DIM3) (int DIM1, int DIM2, int DIM3, type* IN_ARRAY3) (type INPLACE_ARRAY3[ANY][ANY][ANY]) (type* INPLACE_ARRAY3, int DIM1, int DIM2, int DIM3) (int DIM1, int DIM2, int DIM3, type* INPLACE_ARRAY3) (type ARGOUT_ARRAY3[ANY][ANY][ANY]) SuperTensor.h:: (type IN_ARRAY4[ANY][ANY][ANY][ANY]) (type* IN_ARRAY4, int DIM1, int DIM2, int DIM3, int DIM4) (int DIM1, int DIM2, int DIM3, int DIM4, type* IN_ARRAY4) (type INPLACE_ARRAY4[ANY][ANY][ANY][ANY]) (type* INPLACE_ARRAY4, int DIM1, int DIM2, int DIM3, int DIM4) (int DIM1, int DIM2, int DIM3, int DIM4, type* INPLACE_ARRAY4) (type ARGOUT_ARRAY4[ANY][ANY][ANY][ANY]) These function signatures take a pointer to an array of type "type", whose length is specified by the integer(s) DIM1 (and DIM2, and DIM3, and DIM4). The objective for the IN_ARRAY signatures is for SWIG to generate python wrappers that take a container that constitutes a valid argument to the numpy array constructor, and can be used to build an array of type "type". Currently, types "signed char", "unsigned char", "short", "unsigned short", "int", "unsigned int", "long", "unsigned long", "long long", "unsigned long long", "float", and "double" are supported and tested. The objective for the INPLACE_ARRAY signatures is for SWIG to generate python wrappers that accept a numpy array of any of the above-listed types. The source files Vector.cxx, Matrix.cxx Tensor.cxx and SuperTensor.cxx contain the actual implementations of the functions described in Vector.h, Matrix.h Tensor.h and SuperTensor.h. The python scripts testVector.py, testMatrix.py testTensor.py and testSuperTensor.py test the resulting python wrappers using the unittest module. The SWIG interface files Vector.i, Matrix.i Tensor.i and SuperTensor.i are used to generate the wrapper code. The SWIG_FILE_WITH_INIT macro allows numpy.i to be used with multiple python modules. If it is specified, then the %init block found in Vector.i, Matrix.i Tensor.i and SuperTensor.i are required. The other things done in Vector.i, Matrix.i Tensor.i and SuperTensor.i are the inclusion of the appropriate header file and numpy.i file, and the "%apply" directives to force the functions to use the typemaps. The setup.py script is a standard python distutils script. It defines _Vector, _Matrix _Tensor and _SuperTensor extension modules and Vector , Matrix, Tensor and SuperTensor python modules. The Makefile automates everything, setting up the dependencies, calling swig to generate the wrappers, and calling setup.py to compile the wrapper code and generate the shared objects. Targets "all" (default), "test", "doc" and "clean" are supported. The "doc" target creates HTML documentation (with make target "html"), and PDF documentation (with make targets "tex" and "pdf"). To build and run the test code, simply execute from the shell:: $ make test numpy-1.8.2/doc/swig/pyfragments.swg0000664000175100017510000000617612370216243020635 0ustar vagrantvagrant00000000000000/*-*- C -*-*/ /**********************************************************************/ /* For numpy versions prior to 1.0, the names of certain data types * are different than in later versions. This fragment provides macro * substitutions that allow us to support old and new versions of * numpy. */ /**********************************************************************/ /* Override the SWIG_AsVal_frag(long) fragment so that it also checks * for numpy scalar array types. The code through the %#endif is * essentially cut-and-paste from pyprimtype.swg */ %fragment(SWIG_AsVal_frag(long), "header", fragment="SWIG_CanCastAsInteger", fragment="NumPy_Backward_Compatibility") { SWIGINTERN int SWIG_AsVal_dec(long)(PyObject * obj, long * val) { PyArray_Descr * longDescr = PyArray_DescrNewFromType(NPY_LONG); if (PyInt_Check(obj)) { if (val) *val = PyInt_AsLong(obj); return SWIG_OK; } else if (PyLong_Check(obj)) { long v = PyLong_AsLong(obj); if (!PyErr_Occurred()) { if (val) *val = v; return SWIG_OK; } else { PyErr_Clear(); } } %#ifdef SWIG_PYTHON_CAST_MODE { int dispatch = 0; long v = PyInt_AsLong(obj); if (!PyErr_Occurred()) { if (val) *val = v; return SWIG_AddCast(SWIG_OK); } else { PyErr_Clear(); } if (!dispatch) { double d; int res = SWIG_AddCast(SWIG_AsVal(double)(obj,&d)); if (SWIG_IsOK(res) && SWIG_CanCastAsInteger(&d, LONG_MIN, LONG_MAX)) { if (val) *val = (long)(d); return res; } } } %#endif if (!PyArray_IsScalar(obj,Integer)) return SWIG_TypeError; PyArray_CastScalarToCtype(obj, (void*)val, longDescr); return SWIG_OK; } } /* Override the SWIG_AsVal_frag(unsigned long) fragment so that it * also checks for numpy scalar array types. The code through the * %#endif is essentially cut-and-paste from pyprimtype.swg */ %fragment(SWIG_AsVal_frag(unsigned long),"header", fragment="SWIG_CanCastAsInteger", fragment="NumPy_Backward_Compatibility") { SWIGINTERN int SWIG_AsVal_dec(unsigned long)(PyObject *obj, unsigned long *val) { PyArray_Descr * ulongDescr = PyArray_DescrNewFromType(NPY_ULONG); if (PyInt_Check(obj)) { long v = PyInt_AsLong(obj); if (v >= 0) { if (val) *val = v; return SWIG_OK; } else { return SWIG_OverflowError; } } else if (PyLong_Check(obj)) { unsigned long v = PyLong_AsUnsignedLong(obj); if (!PyErr_Occurred()) { if (val) *val = v; return SWIG_OK; } else { PyErr_Clear(); } } %#ifdef SWIG_PYTHON_CAST_MODE { int dispatch = 0; unsigned long v = PyLong_AsUnsignedLong(obj); if (!PyErr_Occurred()) { if (val) *val = v; return SWIG_AddCast(SWIG_OK); } else { PyErr_Clear(); } if (!dispatch) { double d; int res = SWIG_AddCast(SWIG_AsVal(double)(obj,&d)); if (SWIG_IsOK(res) && SWIG_CanCastAsInteger(&d, 0, ULONG_MAX)) { if (val) *val = (unsigned long)(d); return res; } } } %#endif if (!PyArray_IsScalar(obj,Integer)) return SWIG_TypeError; PyArray_CastScalarToCtype(obj, (void*)val, ulongDescr); return SWIG_OK; } } numpy-1.8.2/doc/swig/Makefile0000664000175100017510000000145012370216243017202 0ustar vagrantvagrant00000000000000# List all of the subdirectories here for recursive make SUBDIRS = test # Default target .PHONY : default default: @echo "There is no default make target for this Makefile" @echo "Valid make targets are:" @echo " test - Compile and run tests of numpy.i" @echo " doc - Generate numpy.i documentation" @echo " all - make test + doc" @echo " clean - Remove generated files recursively" # Target all .PHONY : all all: $(SUBDIRS) # Target test .PHONY : test test: cd $@ && make $@ # Target clean .PHONY : clean clean: @for dir in $(SUBDIRS); do \ echo ; \ echo Running \'make clean\' in $$dir; \ cd $$dir && make clean && cd ..; \ done; \ echo numpy-1.8.2/doc/Makefile0000664000175100017510000001424612370216242016237 0ustar vagrantvagrant00000000000000# Makefile for Sphinx documentation # PYVER = 2.7 PYTHON = python$(PYVER) # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = LANG=C sphinx-build PAPER = FILES= # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d build/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source .PHONY: help clean html web pickle htmlhelp latex changes linkcheck \ dist dist-build gitwash-update #------------------------------------------------------------------------------ help: @echo "Please use \`make ' where is one of" @echo " html to make standalone HTML files" @echo " html-scipyorg to make standalone HTML files with scipy.org theming" @echo " pickle to make pickle files (usable by e.g. sphinx-web)" @echo " htmlhelp to make HTML files and a HTML help project" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " changes to make an overview over all changed/added/deprecated items" @echo " linkcheck to check all external links for integrity" @echo " dist PYVER=... to make a distribution-ready tree" @echo " gitwash-update GITWASH=path/to/gitwash update gitwash developer docs" clean: -rm -rf build/* source/reference/generated gitwash-update: rm -rf source/dev/gitwash install -d source/dev/gitwash python $(GITWASH)/gitwash_dumper.py source/dev NumPy \ --repo-name=numpy \ --github-user=numpy cat source/dev/gitwash_links.txt >> source/dev/gitwash/git_links.inc #------------------------------------------------------------------------------ # Automated generation of all documents #------------------------------------------------------------------------------ # Build the current numpy version, and extract docs from it. # We have to be careful of some issues: # # - Everything must be done using the same Python version # - We must use eggs (otherwise they might override PYTHONPATH on import). # - Different versions of easy_install install to different directories (!) # INSTALL_DIR = $(CURDIR)/build/inst-dist/ INSTALL_PPH = $(INSTALL_DIR)/lib/python$(PYVER)/site-packages:$(INSTALL_DIR)/local/lib/python$(PYVER)/site-packages:$(INSTALL_DIR)/lib/python$(PYVER)/dist-packages:$(INSTALL_DIR)/local/lib/python$(PYVER)/dist-packages DIST_VARS=SPHINXBUILD="LANG=C PYTHONPATH=$(INSTALL_PPH) python$(PYVER) `which sphinx-build`" PYTHON="PYTHONPATH=$(INSTALL_PPH) python$(PYVER)" SPHINXOPTS="$(SPHINXOPTS)" dist: make $(DIST_VARS) real-dist real-dist: dist-build html html-scipyorg test -d build/latex || make latex make -C build/latex all-pdf -test -d build/htmlhelp || make htmlhelp-build -rm -rf build/dist cp -r build/html-scipyorg build/dist cd build/html && zip -9r ../dist/numpy-html.zip . cp build/latex/numpy-*.pdf build/dist -zip build/dist/numpy-chm.zip build/htmlhelp/numpy.chm cd build/dist && tar czf ../dist.tar.gz * chmod ug=rwX,o=rX -R build/dist find build/dist -type d -print0 | xargs -0r chmod g+s dist-build: rm -f ../dist/*.egg cd .. && $(PYTHON) setupegg.py bdist_egg install -d $(subst :, ,$(INSTALL_PPH)) $(PYTHON) `which easy_install` --prefix=$(INSTALL_DIR) ../dist/*.egg #------------------------------------------------------------------------------ # Basic Sphinx generation rules for different formats #------------------------------------------------------------------------------ generate: build/generate-stamp build/generate-stamp: $(wildcard source/reference/*.rst) mkdir -p build touch build/generate-stamp html: generate mkdir -p build/html build/doctrees $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) build/html $(FILES) $(PYTHON) postprocess.py html build/html/*.html @echo @echo "Build finished. The HTML pages are in build/html." html-scipyorg: mkdir -p build/html build/doctrees $(SPHINXBUILD) -t scipyorg -b html $(ALLSPHINXOPTS) build/html-scipyorg $(FILES) @echo @echo "Build finished. The HTML pages are in build/html." pickle: generate mkdir -p build/pickle build/doctrees $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) build/pickle $(FILES) @echo @echo "Build finished; now you can process the pickle files or run" @echo " sphinx-web build/pickle" @echo "to start the sphinx-web server." web: pickle htmlhelp: generate mkdir -p build/htmlhelp build/doctrees $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) build/htmlhelp $(FILES) @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in build/htmlhelp." htmlhelp-build: htmlhelp build/htmlhelp/numpy.chm %.chm: %.hhp -hhc.exe $^ qthelp: generate mkdir -p build/qthelp build/doctrees $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) build/qthelp $(FILES) latex: generate mkdir -p build/latex build/doctrees $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) build/latex $(FILES) $(PYTHON) postprocess.py tex build/latex/*.tex perl -pi -e 's/\t(latex.*|pdflatex) (.*)/\t-$$1 -interaction batchmode $$2/' build/latex/Makefile @echo @echo "Build finished; the LaTeX files are in build/latex." @echo "Run \`make all-pdf' or \`make all-ps' in that directory to" \ "run these through (pdf)latex." coverage: build mkdir -p build/coverage build/doctrees $(SPHINXBUILD) -b coverage $(ALLSPHINXOPTS) build/coverage $(FILES) @echo "Coverage finished; see c.txt and python.txt in build/coverage" changes: generate mkdir -p build/changes build/doctrees $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) build/changes $(FILES) @echo @echo "The overview file is in build/changes." linkcheck: generate mkdir -p build/linkcheck build/doctrees $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) build/linkcheck $(FILES) @echo @echo "Link check complete; look for any errors in the above output " \ "or in build/linkcheck/output.txt." texinfo: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) build/texinfo @echo @echo "Build finished. The Texinfo files are in build/texinfo." @echo "Run \`make' in that directory to run these through makeinfo" \ "(use \`make info' here to do that automatically)." info: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) build/texinfo @echo "Running Texinfo files through makeinfo..." make -C build/texinfo info @echo "makeinfo finished; the Info files are in build/texinfo." numpy-1.8.2/PKG-INFO0000664000175100017510000000314712371375430015133 0ustar vagrantvagrant00000000000000Metadata-Version: 1.1 Name: numpy Version: 1.8.2 Summary: NumPy: array processing for numbers, strings, records, and objects. Home-page: http://www.numpy.org Author: NumPy Developers Author-email: numpy-discussion@scipy.org License: BSD Download-URL: http://sourceforge.net/projects/numpy/files/NumPy/ Description: NumPy is a general-purpose array-processing package designed to efficiently manipulate large multi-dimensional arrays of arbitrary records without sacrificing too much speed for small multi-dimensional arrays. NumPy is built on the Numeric code base and adds features introduced by numarray as well as an extended C-API and the ability to create arrays of arbitrary type which also makes NumPy suitable for interfacing with general-purpose data-base applications. There are also basic facilities for discrete fourier transform, basic linear algebra and random number generation. Platform: Windows Platform: Linux Platform: Solaris Platform: Mac OS-X Platform: Unix Classifier: Development Status :: 5 - Production/Stable Classifier: Intended Audience :: Science/Research Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved Classifier: Programming Language :: C Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 3 Classifier: Topic :: Software Development Classifier: Topic :: Scientific/Engineering Classifier: Operating System :: Microsoft :: Windows Classifier: Operating System :: POSIX Classifier: Operating System :: Unix Classifier: Operating System :: MacOS numpy-1.8.2/BENTO_BUILD.txt0000664000175100017510000000105012370216242016346 0ustar vagrantvagrant00000000000000No-frill version: * Clone bento:: git clone git://github.com/cournape/Bento.git bento-git * Bootstrap bento:: cd bento-git && python bootstrap.py * Download waf >= 1.6.5 from a release (or from git):: git clone https://code.google.com/p/waf/ * Build numpy with bento: export WAFDIR=ROOT_OF_WAF_CHECKOUT # WAFDIR should be such as $WAFDIR/waflib exists $BENTO_ROOT/bentomaker build -j 4 # 4 threads in parallel # or with progress bar $BENTO_ROOT/bentomaker build -p # or with verbose output $BENTO_ROOT/bentomaker build -v numpy-1.8.2/setupegg.py0000775000175100017510000000124612370216242016226 0ustar vagrantvagrant00000000000000#!/usr/bin/env python """ A setup.py script to use setuptools, which gives egg goodness, etc. This is used to build installers for OS X through bdist_mpkg. Notes ----- Using ``python setupegg.py install`` directly results in file permissions being set wrong, with nose refusing to run any tests. To run the tests anyway, use:: >>> np.test(extra_argv=['--exe']) """ from __future__ import division, absolute_import, print_function import sys from setuptools import setup if sys.version_info[0] >= 3: import imp setupfile = imp.load_source('setupfile', 'setup.py') setupfile.setup_package() else: exec(compile(open('setup.py').read(), 'setup.py', 'exec')) numpy-1.8.2/numpy/0000775000175100017510000000000012371375427015207 5ustar vagrantvagrant00000000000000numpy-1.8.2/numpy/ctypeslib.py0000664000175100017510000003266312370216242017555 0ustar vagrantvagrant00000000000000""" ============================ ``ctypes`` Utility Functions ============================ See Also --------- load_library : Load a C library. ndpointer : Array restype/argtype with verification. as_ctypes : Create a ctypes array from an ndarray. as_array : Create an ndarray from a ctypes array. References ---------- .. [1] "SciPy Cookbook: ctypes", http://www.scipy.org/Cookbook/Ctypes Examples -------- Load the C library: >>> _lib = np.ctypeslib.load_library('libmystuff', '.') #doctest: +SKIP Our result type, an ndarray that must be of type double, be 1-dimensional and is C-contiguous in memory: >>> array_1d_double = np.ctypeslib.ndpointer( ... dtype=np.double, ... ndim=1, flags='CONTIGUOUS') #doctest: +SKIP Our C-function typically takes an array and updates its values in-place. For example:: void foo_func(double* x, int length) { int i; for (i = 0; i < length; i++) { x[i] = i*i; } } We wrap it using: >>> _lib.foo_func.restype = None #doctest: +SKIP >>> _lib.foo_func.argtypes = [array_1d_double, c_int] #doctest: +SKIP Then, we're ready to call ``foo_func``: >>> out = np.empty(15, dtype=np.double) >>> _lib.foo_func(out, len(out)) #doctest: +SKIP """ from __future__ import division, absolute_import, print_function __all__ = ['load_library', 'ndpointer', 'test', 'ctypes_load_library', 'c_intp', 'as_ctypes', 'as_array'] import sys, os from numpy import integer, ndarray, dtype as _dtype, deprecate, array from numpy.core.multiarray import _flagdict, flagsobj try: import ctypes except ImportError: ctypes = None if ctypes is None: def _dummy(*args, **kwds): """ Dummy object that raises an ImportError if ctypes is not available. Raises ------ ImportError If ctypes is not available. """ raise ImportError("ctypes is not available.") ctypes_load_library = _dummy load_library = _dummy as_ctypes = _dummy as_array = _dummy from numpy import intp as c_intp _ndptr_base = object else: import numpy.core._internal as nic c_intp = nic._getintp_ctype() del nic _ndptr_base = ctypes.c_void_p # Adapted from Albert Strasheim def load_library(libname, loader_path): if ctypes.__version__ < '1.0.1': import warnings warnings.warn("All features of ctypes interface may not work " \ "with ctypes < 1.0.1") ext = os.path.splitext(libname)[1] if not ext: # Try to load library with platform-specific name, otherwise # default to libname.[so|pyd]. Sometimes, these files are built # erroneously on non-linux platforms. from numpy.distutils.misc_util import get_shared_lib_extension so_ext = get_shared_lib_extension() libname_ext = [libname + so_ext] # mac, windows and linux >= py3.2 shared library and loadable # module have different extensions so try both so_ext2 = get_shared_lib_extension(is_python_ext=True) if not so_ext2 == so_ext: libname_ext.insert(0, libname + so_ext2) else: libname_ext = [libname] loader_path = os.path.abspath(loader_path) if not os.path.isdir(loader_path): libdir = os.path.dirname(loader_path) else: libdir = loader_path for ln in libname_ext: libpath = os.path.join(libdir, ln) if os.path.exists(libpath): try: return ctypes.cdll[libpath] except OSError: ## defective lib file raise ## if no successful return in the libname_ext loop: raise OSError("no file with expected extension") ctypes_load_library = deprecate(load_library, 'ctypes_load_library', 'load_library') def _num_fromflags(flaglist): num = 0 for val in flaglist: num += _flagdict[val] return num _flagnames = ['C_CONTIGUOUS', 'F_CONTIGUOUS', 'ALIGNED', 'WRITEABLE', 'OWNDATA', 'UPDATEIFCOPY'] def _flags_fromnum(num): res = [] for key in _flagnames: value = _flagdict[key] if (num & value): res.append(key) return res class _ndptr(_ndptr_base): def _check_retval_(self): """This method is called when this class is used as the .restype asttribute for a shared-library function. It constructs a numpy array from a void pointer.""" return array(self) @property def __array_interface__(self): return {'descr': self._dtype_.descr, '__ref': self, 'strides': None, 'shape': self._shape_, 'version': 3, 'typestr': self._dtype_.descr[0][1], 'data': (self.value, False), } @classmethod def from_param(cls, obj): if not isinstance(obj, ndarray): raise TypeError("argument must be an ndarray") if cls._dtype_ is not None \ and obj.dtype != cls._dtype_: raise TypeError("array must have data type %s" % cls._dtype_) if cls._ndim_ is not None \ and obj.ndim != cls._ndim_: raise TypeError("array must have %d dimension(s)" % cls._ndim_) if cls._shape_ is not None \ and obj.shape != cls._shape_: raise TypeError("array must have shape %s" % str(cls._shape_)) if cls._flags_ is not None \ and ((obj.flags.num & cls._flags_) != cls._flags_): raise TypeError("array must have flags %s" % _flags_fromnum(cls._flags_)) return obj.ctypes # Factory for an array-checking class with from_param defined for # use with ctypes argtypes mechanism _pointer_type_cache = {} def ndpointer(dtype=None, ndim=None, shape=None, flags=None): """ Array-checking restype/argtypes. An ndpointer instance is used to describe an ndarray in restypes and argtypes specifications. This approach is more flexible than using, for example, ``POINTER(c_double)``, since several restrictions can be specified, which are verified upon calling the ctypes function. These include data type, number of dimensions, shape and flags. If a given array does not satisfy the specified restrictions, a ``TypeError`` is raised. Parameters ---------- dtype : data-type, optional Array data-type. ndim : int, optional Number of array dimensions. shape : tuple of ints, optional Array shape. flags : str or tuple of str Array flags; may be one or more of: - C_CONTIGUOUS / C / CONTIGUOUS - F_CONTIGUOUS / F / FORTRAN - OWNDATA / O - WRITEABLE / W - ALIGNED / A - UPDATEIFCOPY / U Returns ------- klass : ndpointer type object A type object, which is an ``_ndtpr`` instance containing dtype, ndim, shape and flags information. Raises ------ TypeError If a given array does not satisfy the specified restrictions. Examples -------- >>> clib.somefunc.argtypes = [np.ctypeslib.ndpointer(dtype=np.float64, ... ndim=1, ... flags='C_CONTIGUOUS')] ... #doctest: +SKIP >>> clib.somefunc(np.array([1, 2, 3], dtype=np.float64)) ... #doctest: +SKIP """ if dtype is not None: dtype = _dtype(dtype) num = None if flags is not None: if isinstance(flags, str): flags = flags.split(',') elif isinstance(flags, (int, integer)): num = flags flags = _flags_fromnum(num) elif isinstance(flags, flagsobj): num = flags.num flags = _flags_fromnum(num) if num is None: try: flags = [x.strip().upper() for x in flags] except: raise TypeError("invalid flags specification") num = _num_fromflags(flags) try: return _pointer_type_cache[(dtype, ndim, shape, num)] except KeyError: pass if dtype is None: name = 'any' elif dtype.names: name = str(id(dtype)) else: name = dtype.str if ndim is not None: name += "_%dd" % ndim if shape is not None: try: strshape = [str(x) for x in shape] except TypeError: strshape = [str(shape)] shape = (shape,) shape = tuple(shape) name += "_"+"x".join(strshape) if flags is not None: name += "_"+"_".join(flags) else: flags = [] klass = type("ndpointer_%s"%name, (_ndptr,), {"_dtype_": dtype, "_shape_" : shape, "_ndim_" : ndim, "_flags_" : num}) _pointer_type_cache[dtype] = klass return klass if ctypes is not None: ct = ctypes ################################################################ # simple types # maps the numpy typecodes like '>> from numpy.polynomial.laguerre import poly2lag >>> poly2lag(np.arange(4)) array([ 23., -63., 58., -18.]) """ [pol] = pu.as_series([pol]) deg = len(pol) - 1 res = 0 for i in range(deg, -1, -1) : res = lagadd(lagmulx(res), pol[i]) return res def lag2poly(c) : """ Convert a Laguerre series to a polynomial. Convert an array representing the coefficients of a Laguerre series, ordered from lowest degree to highest, to an array of the coefficients of the equivalent polynomial (relative to the "standard" basis) ordered from lowest to highest degree. Parameters ---------- c : array_like 1-D array containing the Laguerre series coefficients, ordered from lowest order term to highest. Returns ------- pol : ndarray 1-D array containing the coefficients of the equivalent polynomial (relative to the "standard" basis) ordered from lowest order term to highest. See Also -------- poly2lag Notes ----- The easy way to do conversions between polynomial basis sets is to use the convert method of a class instance. Examples -------- >>> from numpy.polynomial.laguerre import lag2poly >>> lag2poly([ 23., -63., 58., -18.]) array([ 0., 1., 2., 3.]) """ from .polynomial import polyadd, polysub, polymulx [c] = pu.as_series([c]) n = len(c) if n == 1: return c else: c0 = c[-2] c1 = c[-1] # i is the current degree of c1 for i in range(n - 1, 1, -1): tmp = c0 c0 = polysub(c[i - 2], (c1*(i - 1))/i) c1 = polyadd(tmp, polysub((2*i - 1)*c1, polymulx(c1))/i) return polyadd(c0, polysub(c1, polymulx(c1))) # # These are constant arrays are of integer type so as to be compatible # with the widest range of other types, such as Decimal. # # Laguerre lagdomain = np.array([0, 1]) # Laguerre coefficients representing zero. lagzero = np.array([0]) # Laguerre coefficients representing one. lagone = np.array([1]) # Laguerre coefficients representing the identity x. lagx = np.array([1, -1]) def lagline(off, scl) : """ Laguerre series whose graph is a straight line. Parameters ---------- off, scl : scalars The specified line is given by ``off + scl*x``. Returns ------- y : ndarray This module's representation of the Laguerre series for ``off + scl*x``. See Also -------- polyline, chebline Examples -------- >>> from numpy.polynomial.laguerre import lagline, lagval >>> lagval(0,lagline(3, 2)) 3.0 >>> lagval(1,lagline(3, 2)) 5.0 """ if scl != 0 : return np.array([off + scl, -scl]) else : return np.array([off]) def lagfromroots(roots) : """ Generate a Laguerre series with given roots. The function returns the coefficients of the polynomial .. math:: p(x) = (x - r_0) * (x - r_1) * ... * (x - r_n), in Laguerre form, where the `r_n` are the roots specified in `roots`. If a zero has multiplicity n, then it must appear in `roots` n times. For instance, if 2 is a root of multiplicity three and 3 is a root of multiplicity 2, then `roots` looks something like [2, 2, 2, 3, 3]. The roots can appear in any order. If the returned coefficients are `c`, then .. math:: p(x) = c_0 + c_1 * L_1(x) + ... + c_n * L_n(x) The coefficient of the last term is not generally 1 for monic polynomials in Laguerre form. Parameters ---------- roots : array_like Sequence containing the roots. Returns ------- out : ndarray 1-D array of coefficients. If all roots are real then `out` is a real array, if some of the roots are complex, then `out` is complex even if all the coefficients in the result are real (see Examples below). See Also -------- polyfromroots, legfromroots, chebfromroots, hermfromroots, hermefromroots. Examples -------- >>> from numpy.polynomial.laguerre import lagfromroots, lagval >>> coef = lagfromroots((-1, 0, 1)) >>> lagval((-1, 0, 1), coef) array([ 0., 0., 0.]) >>> coef = lagfromroots((-1j, 1j)) >>> lagval((-1j, 1j), coef) array([ 0.+0.j, 0.+0.j]) """ if len(roots) == 0 : return np.ones(1) else : [roots] = pu.as_series([roots], trim=False) roots.sort() p = [lagline(-r, 1) for r in roots] n = len(p) while n > 1: m, r = divmod(n, 2) tmp = [lagmul(p[i], p[i+m]) for i in range(m)] if r: tmp[0] = lagmul(tmp[0], p[-1]) p = tmp n = m return p[0] def lagadd(c1, c2): """ Add one Laguerre series to another. Returns the sum of two Laguerre series `c1` + `c2`. The arguments are sequences of coefficients ordered from lowest order term to highest, i.e., [1,2,3] represents the series ``P_0 + 2*P_1 + 3*P_2``. Parameters ---------- c1, c2 : array_like 1-D arrays of Laguerre series coefficients ordered from low to high. Returns ------- out : ndarray Array representing the Laguerre series of their sum. See Also -------- lagsub, lagmul, lagdiv, lagpow Notes ----- Unlike multiplication, division, etc., the sum of two Laguerre series is a Laguerre series (without having to "reproject" the result onto the basis set) so addition, just like that of "standard" polynomials, is simply "component-wise." Examples -------- >>> from numpy.polynomial.laguerre import lagadd >>> lagadd([1, 2, 3], [1, 2, 3, 4]) array([ 2., 4., 6., 4.]) """ # c1, c2 are trimmed copies [c1, c2] = pu.as_series([c1, c2]) if len(c1) > len(c2) : c1[:c2.size] += c2 ret = c1 else : c2[:c1.size] += c1 ret = c2 return pu.trimseq(ret) def lagsub(c1, c2): """ Subtract one Laguerre series from another. Returns the difference of two Laguerre series `c1` - `c2`. The sequences of coefficients are from lowest order term to highest, i.e., [1,2,3] represents the series ``P_0 + 2*P_1 + 3*P_2``. Parameters ---------- c1, c2 : array_like 1-D arrays of Laguerre series coefficients ordered from low to high. Returns ------- out : ndarray Of Laguerre series coefficients representing their difference. See Also -------- lagadd, lagmul, lagdiv, lagpow Notes ----- Unlike multiplication, division, etc., the difference of two Laguerre series is a Laguerre series (without having to "reproject" the result onto the basis set) so subtraction, just like that of "standard" polynomials, is simply "component-wise." Examples -------- >>> from numpy.polynomial.laguerre import lagsub >>> lagsub([1, 2, 3, 4], [1, 2, 3]) array([ 0., 0., 0., 4.]) """ # c1, c2 are trimmed copies [c1, c2] = pu.as_series([c1, c2]) if len(c1) > len(c2) : c1[:c2.size] -= c2 ret = c1 else : c2 = -c2 c2[:c1.size] += c1 ret = c2 return pu.trimseq(ret) def lagmulx(c): """Multiply a Laguerre series by x. Multiply the Laguerre series `c` by x, where x is the independent variable. Parameters ---------- c : array_like 1-D array of Laguerre series coefficients ordered from low to high. Returns ------- out : ndarray Array representing the result of the multiplication. Notes ----- The multiplication uses the recursion relationship for Laguerre polynomials in the form .. math:: xP_i(x) = (-(i + 1)*P_{i + 1}(x) + (2i + 1)P_{i}(x) - iP_{i - 1}(x)) Examples -------- >>> from numpy.polynomial.laguerre import lagmulx >>> lagmulx([1, 2, 3]) array([ -1., -1., 11., -9.]) """ # c is a trimmed copy [c] = pu.as_series([c]) # The zero series needs special treatment if len(c) == 1 and c[0] == 0: return c prd = np.empty(len(c) + 1, dtype=c.dtype) prd[0] = c[0] prd[1] = -c[0] for i in range(1, len(c)): prd[i + 1] = -c[i]*(i + 1) prd[i] += c[i]*(2*i + 1) prd[i - 1] -= c[i]*i return prd def lagmul(c1, c2): """ Multiply one Laguerre series by another. Returns the product of two Laguerre series `c1` * `c2`. The arguments are sequences of coefficients, from lowest order "term" to highest, e.g., [1,2,3] represents the series ``P_0 + 2*P_1 + 3*P_2``. Parameters ---------- c1, c2 : array_like 1-D arrays of Laguerre series coefficients ordered from low to high. Returns ------- out : ndarray Of Laguerre series coefficients representing their product. See Also -------- lagadd, lagsub, lagdiv, lagpow Notes ----- In general, the (polynomial) product of two C-series results in terms that are not in the Laguerre polynomial basis set. Thus, to express the product as a Laguerre series, it is necessary to "reproject" the product onto said basis set, which may produce "unintuitive" (but correct) results; see Examples section below. Examples -------- >>> from numpy.polynomial.laguerre import lagmul >>> lagmul([1, 2, 3], [0, 1, 2]) array([ 8., -13., 38., -51., 36.]) """ # s1, s2 are trimmed copies [c1, c2] = pu.as_series([c1, c2]) if len(c1) > len(c2): c = c2 xs = c1 else: c = c1 xs = c2 if len(c) == 1: c0 = c[0]*xs c1 = 0 elif len(c) == 2: c0 = c[0]*xs c1 = c[1]*xs else : nd = len(c) c0 = c[-2]*xs c1 = c[-1]*xs for i in range(3, len(c) + 1) : tmp = c0 nd = nd - 1 c0 = lagsub(c[-i]*xs, (c1*(nd - 1))/nd) c1 = lagadd(tmp, lagsub((2*nd - 1)*c1, lagmulx(c1))/nd) return lagadd(c0, lagsub(c1, lagmulx(c1))) def lagdiv(c1, c2): """ Divide one Laguerre series by another. Returns the quotient-with-remainder of two Laguerre series `c1` / `c2`. The arguments are sequences of coefficients from lowest order "term" to highest, e.g., [1,2,3] represents the series ``P_0 + 2*P_1 + 3*P_2``. Parameters ---------- c1, c2 : array_like 1-D arrays of Laguerre series coefficients ordered from low to high. Returns ------- [quo, rem] : ndarrays Of Laguerre series coefficients representing the quotient and remainder. See Also -------- lagadd, lagsub, lagmul, lagpow Notes ----- In general, the (polynomial) division of one Laguerre series by another results in quotient and remainder terms that are not in the Laguerre polynomial basis set. Thus, to express these results as a Laguerre series, it is necessary to "reproject" the results onto the Laguerre basis set, which may produce "unintuitive" (but correct) results; see Examples section below. Examples -------- >>> from numpy.polynomial.laguerre import lagdiv >>> lagdiv([ 8., -13., 38., -51., 36.], [0, 1, 2]) (array([ 1., 2., 3.]), array([ 0.])) >>> lagdiv([ 9., -12., 38., -51., 36.], [0, 1, 2]) (array([ 1., 2., 3.]), array([ 1., 1.])) """ # c1, c2 are trimmed copies [c1, c2] = pu.as_series([c1, c2]) if c2[-1] == 0 : raise ZeroDivisionError() lc1 = len(c1) lc2 = len(c2) if lc1 < lc2 : return c1[:1]*0, c1 elif lc2 == 1 : return c1/c2[-1], c1[:1]*0 else : quo = np.empty(lc1 - lc2 + 1, dtype=c1.dtype) rem = c1 for i in range(lc1 - lc2, - 1, -1): p = lagmul([0]*i + [1], c2) q = rem[-1]/p[-1] rem = rem[:-1] - q*p[:-1] quo[i] = q return quo, pu.trimseq(rem) def lagpow(c, pow, maxpower=16) : """Raise a Laguerre series to a power. Returns the Laguerre series `c` raised to the power `pow`. The argument `c` is a sequence of coefficients ordered from low to high. i.e., [1,2,3] is the series ``P_0 + 2*P_1 + 3*P_2.`` Parameters ---------- c : array_like 1-D array of Laguerre series coefficients ordered from low to high. pow : integer Power to which the series will be raised maxpower : integer, optional Maximum power allowed. This is mainly to limit growth of the series to unmanageable size. Default is 16 Returns ------- coef : ndarray Laguerre series of power. See Also -------- lagadd, lagsub, lagmul, lagdiv Examples -------- >>> from numpy.polynomial.laguerre import lagpow >>> lagpow([1, 2, 3], 2) array([ 14., -16., 56., -72., 54.]) """ # c is a trimmed copy [c] = pu.as_series([c]) power = int(pow) if power != pow or power < 0 : raise ValueError("Power must be a non-negative integer.") elif maxpower is not None and power > maxpower : raise ValueError("Power is too large") elif power == 0 : return np.array([1], dtype=c.dtype) elif power == 1 : return c else : # This can be made more efficient by using powers of two # in the usual way. prd = c for i in range(2, power + 1) : prd = lagmul(prd, c) return prd def lagder(c, m=1, scl=1, axis=0) : """ Differentiate a Laguerre series. Returns the Laguerre series coefficients `c` differentiated `m` times along `axis`. At each iteration the result is multiplied by `scl` (the scaling factor is for use in a linear change of variable). The argument `c` is an array of coefficients from low to high degree along each axis, e.g., [1,2,3] represents the series ``1*L_0 + 2*L_1 + 3*L_2`` while [[1,2],[1,2]] represents ``1*L_0(x)*L_0(y) + 1*L_1(x)*L_0(y) + 2*L_0(x)*L_1(y) + 2*L_1(x)*L_1(y)`` if axis=0 is ``x`` and axis=1 is ``y``. Parameters ---------- c : array_like Array of Laguerre series coefficients. If `c` is multidimensional the different axis correspond to different variables with the degree in each axis given by the corresponding index. m : int, optional Number of derivatives taken, must be non-negative. (Default: 1) scl : scalar, optional Each differentiation is multiplied by `scl`. The end result is multiplication by ``scl**m``. This is for use in a linear change of variable. (Default: 1) axis : int, optional Axis over which the derivative is taken. (Default: 0). .. versionadded:: 1.7.0 Returns ------- der : ndarray Laguerre series of the derivative. See Also -------- lagint Notes ----- In general, the result of differentiating a Laguerre series does not resemble the same operation on a power series. Thus the result of this function may be "unintuitive," albeit correct; see Examples section below. Examples -------- >>> from numpy.polynomial.laguerre import lagder >>> lagder([ 1., 1., 1., -3.]) array([ 1., 2., 3.]) >>> lagder([ 1., 0., 0., -4., 3.], m=2) array([ 1., 2., 3.]) """ c = np.array(c, ndmin=1, copy=1) if c.dtype.char in '?bBhHiIlLqQpP': c = c.astype(np.double) cnt, iaxis = [int(t) for t in [m, axis]] if cnt != m: raise ValueError("The order of derivation must be integer") if cnt < 0: raise ValueError("The order of derivation must be non-negative") if iaxis != axis: raise ValueError("The axis must be integer") if not -c.ndim <= iaxis < c.ndim: raise ValueError("The axis is out of range") if iaxis < 0: iaxis += c.ndim if cnt == 0: return c c = np.rollaxis(c, iaxis) n = len(c) if cnt >= n: c = c[:1]*0 else : for i in range(cnt): n = n - 1 c *= scl der = np.empty((n,) + c.shape[1:], dtype=c.dtype) for j in range(n, 1, -1): der[j - 1] = -c[j] c[j - 1] += c[j] der[0] = -c[1] c = der c = np.rollaxis(c, 0, iaxis + 1) return c def lagint(c, m=1, k=[], lbnd=0, scl=1, axis=0): """ Integrate a Laguerre series. Returns the Laguerre series coefficients `c` integrated `m` times from `lbnd` along `axis`. At each iteration the resulting series is **multiplied** by `scl` and an integration constant, `k`, is added. The scaling factor is for use in a linear change of variable. ("Buyer beware": note that, depending on what one is doing, one may want `scl` to be the reciprocal of what one might expect; for more information, see the Notes section below.) The argument `c` is an array of coefficients from low to high degree along each axis, e.g., [1,2,3] represents the series ``L_0 + 2*L_1 + 3*L_2`` while [[1,2],[1,2]] represents ``1*L_0(x)*L_0(y) + 1*L_1(x)*L_0(y) + 2*L_0(x)*L_1(y) + 2*L_1(x)*L_1(y)`` if axis=0 is ``x`` and axis=1 is ``y``. Parameters ---------- c : array_like Array of Laguerre series coefficients. If `c` is multidimensional the different axis correspond to different variables with the degree in each axis given by the corresponding index. m : int, optional Order of integration, must be positive. (Default: 1) k : {[], list, scalar}, optional Integration constant(s). The value of the first integral at ``lbnd`` is the first value in the list, the value of the second integral at ``lbnd`` is the second value, etc. If ``k == []`` (the default), all constants are set to zero. If ``m == 1``, a single scalar can be given instead of a list. lbnd : scalar, optional The lower bound of the integral. (Default: 0) scl : scalar, optional Following each integration the result is *multiplied* by `scl` before the integration constant is added. (Default: 1) axis : int, optional Axis over which the integral is taken. (Default: 0). .. versionadded:: 1.7.0 Returns ------- S : ndarray Laguerre series coefficients of the integral. Raises ------ ValueError If ``m < 0``, ``len(k) > m``, ``np.isscalar(lbnd) == False``, or ``np.isscalar(scl) == False``. See Also -------- lagder Notes ----- Note that the result of each integration is *multiplied* by `scl`. Why is this important to note? Say one is making a linear change of variable :math:`u = ax + b` in an integral relative to `x`. Then .. math::`dx = du/a`, so one will need to set `scl` equal to :math:`1/a` - perhaps not what one would have first thought. Also note that, in general, the result of integrating a C-series needs to be "reprojected" onto the C-series basis set. Thus, typically, the result of this function is "unintuitive," albeit correct; see Examples section below. Examples -------- >>> from numpy.polynomial.laguerre import lagint >>> lagint([1,2,3]) array([ 1., 1., 1., -3.]) >>> lagint([1,2,3], m=2) array([ 1., 0., 0., -4., 3.]) >>> lagint([1,2,3], k=1) array([ 2., 1., 1., -3.]) >>> lagint([1,2,3], lbnd=-1) array([ 11.5, 1. , 1. , -3. ]) >>> lagint([1,2], m=2, k=[1,2], lbnd=-1) array([ 11.16666667, -5. , -3. , 2. ]) """ c = np.array(c, ndmin=1, copy=1) if c.dtype.char in '?bBhHiIlLqQpP': c = c.astype(np.double) if not np.iterable(k): k = [k] cnt, iaxis = [int(t) for t in [m, axis]] if cnt != m: raise ValueError("The order of integration must be integer") if cnt < 0 : raise ValueError("The order of integration must be non-negative") if len(k) > cnt : raise ValueError("Too many integration constants") if iaxis != axis: raise ValueError("The axis must be integer") if not -c.ndim <= iaxis < c.ndim: raise ValueError("The axis is out of range") if iaxis < 0: iaxis += c.ndim if cnt == 0: return c c = np.rollaxis(c, iaxis) k = list(k) + [0]*(cnt - len(k)) for i in range(cnt) : n = len(c) c *= scl if n == 1 and np.all(c[0] == 0): c[0] += k[i] else: tmp = np.empty((n + 1,) + c.shape[1:], dtype=c.dtype) tmp[0] = c[0] tmp[1] = -c[0] for j in range(1, n): tmp[j] += c[j] tmp[j + 1] = -c[j] tmp[0] += k[i] - lagval(lbnd, tmp) c = tmp c = np.rollaxis(c, 0, iaxis + 1) return c def lagval(x, c, tensor=True): """ Evaluate a Laguerre series at points x. If `c` is of length `n + 1`, this function returns the value: .. math:: p(x) = c_0 * L_0(x) + c_1 * L_1(x) + ... + c_n * L_n(x) The parameter `x` is converted to an array only if it is a tuple or a list, otherwise it is treated as a scalar. In either case, either `x` or its elements must support multiplication and addition both with themselves and with the elements of `c`. If `c` is a 1-D array, then `p(x)` will have the same shape as `x`. If `c` is multidimensional, then the shape of the result depends on the value of `tensor`. If `tensor` is true the shape will be c.shape[1:] + x.shape. If `tensor` is false the shape will be c.shape[1:]. Note that scalars have shape (,). Trailing zeros in the coefficients will be used in the evaluation, so they should be avoided if efficiency is a concern. Parameters ---------- x : array_like, compatible object If `x` is a list or tuple, it is converted to an ndarray, otherwise it is left unchanged and treated as a scalar. In either case, `x` or its elements must support addition and multiplication with with themselves and with the elements of `c`. c : array_like Array of coefficients ordered so that the coefficients for terms of degree n are contained in c[n]. If `c` is multidimensional the remaining indices enumerate multiple polynomials. In the two dimensional case the coefficients may be thought of as stored in the columns of `c`. tensor : boolean, optional If True, the shape of the coefficient array is extended with ones on the right, one for each dimension of `x`. Scalars have dimension 0 for this action. The result is that every column of coefficients in `c` is evaluated for every element of `x`. If False, `x` is broadcast over the columns of `c` for the evaluation. This keyword is useful when `c` is multidimensional. The default value is True. .. versionadded:: 1.7.0 Returns ------- values : ndarray, algebra_like The shape of the return value is described above. See Also -------- lagval2d, laggrid2d, lagval3d, laggrid3d Notes ----- The evaluation uses Clenshaw recursion, aka synthetic division. Examples -------- >>> from numpy.polynomial.laguerre import lagval >>> coef = [1,2,3] >>> lagval(1, coef) -0.5 >>> lagval([[1,2],[3,4]], coef) array([[-0.5, -4. ], [-4.5, -2. ]]) """ c = np.array(c, ndmin=1, copy=0) if c.dtype.char in '?bBhHiIlLqQpP': c = c.astype(np.double) if isinstance(x, (tuple, list)): x = np.asarray(x) if isinstance(x, np.ndarray) and tensor: c = c.reshape(c.shape + (1,)*x.ndim) if len(c) == 1 : c0 = c[0] c1 = 0 elif len(c) == 2 : c0 = c[0] c1 = c[1] else : nd = len(c) c0 = c[-2] c1 = c[-1] for i in range(3, len(c) + 1) : tmp = c0 nd = nd - 1 c0 = c[-i] - (c1*(nd - 1))/nd c1 = tmp + (c1*((2*nd - 1) - x))/nd return c0 + c1*(1 - x) def lagval2d(x, y, c): """ Evaluate a 2-D Laguerre series at points (x, y). This function returns the values: .. math:: p(x,y) = \\sum_{i,j} c_{i,j} * L_i(x) * L_j(y) The parameters `x` and `y` are converted to arrays only if they are tuples or a lists, otherwise they are treated as a scalars and they must have the same shape after conversion. In either case, either `x` and `y` or their elements must support multiplication and addition both with themselves and with the elements of `c`. If `c` is a 1-D array a one is implicitly appended to its shape to make it 2-D. The shape of the result will be c.shape[2:] + x.shape. Parameters ---------- x, y : array_like, compatible objects The two dimensional series is evaluated at the points `(x, y)`, where `x` and `y` must have the same shape. If `x` or `y` is a list or tuple, it is first converted to an ndarray, otherwise it is left unchanged and if it isn't an ndarray it is treated as a scalar. c : array_like Array of coefficients ordered so that the coefficient of the term of multi-degree i,j is contained in ``c[i,j]``. If `c` has dimension greater than two the remaining indices enumerate multiple sets of coefficients. Returns ------- values : ndarray, compatible object The values of the two dimensional polynomial at points formed with pairs of corresponding values from `x` and `y`. See Also -------- lagval, laggrid2d, lagval3d, laggrid3d Notes ----- .. versionadded::1.7.0 """ try: x, y = np.array((x, y), copy=0) except: raise ValueError('x, y are incompatible') c = lagval(x, c) c = lagval(y, c, tensor=False) return c def laggrid2d(x, y, c): """ Evaluate a 2-D Laguerre series on the Cartesian product of x and y. This function returns the values: .. math:: p(a,b) = \sum_{i,j} c_{i,j} * L_i(a) * L_j(b) where the points `(a, b)` consist of all pairs formed by taking `a` from `x` and `b` from `y`. The resulting points form a grid with `x` in the first dimension and `y` in the second. The parameters `x` and `y` are converted to arrays only if they are tuples or a lists, otherwise they are treated as a scalars. In either case, either `x` and `y` or their elements must support multiplication and addition both with themselves and with the elements of `c`. If `c` has fewer than two dimensions, ones are implicitly appended to its shape to make it 2-D. The shape of the result will be c.shape[2:] + x.shape + y.shape. Parameters ---------- x, y : array_like, compatible objects The two dimensional series is evaluated at the points in the Cartesian product of `x` and `y`. If `x` or `y` is a list or tuple, it is first converted to an ndarray, otherwise it is left unchanged and, if it isn't an ndarray, it is treated as a scalar. c : array_like Array of coefficients ordered so that the coefficient of the term of multi-degree i,j is contained in `c[i,j]`. If `c` has dimension greater than two the remaining indices enumerate multiple sets of coefficients. Returns ------- values : ndarray, compatible object The values of the two dimensional Chebyshev series at points in the Cartesian product of `x` and `y`. See Also -------- lagval, lagval2d, lagval3d, laggrid3d Notes ----- .. versionadded::1.7.0 """ c = lagval(x, c) c = lagval(y, c) return c def lagval3d(x, y, z, c): """ Evaluate a 3-D Laguerre series at points (x, y, z). This function returns the values: .. math:: p(x,y,z) = \\sum_{i,j,k} c_{i,j,k} * L_i(x) * L_j(y) * L_k(z) The parameters `x`, `y`, and `z` are converted to arrays only if they are tuples or a lists, otherwise they are treated as a scalars and they must have the same shape after conversion. In either case, either `x`, `y`, and `z` or their elements must support multiplication and addition both with themselves and with the elements of `c`. If `c` has fewer than 3 dimensions, ones are implicitly appended to its shape to make it 3-D. The shape of the result will be c.shape[3:] + x.shape. Parameters ---------- x, y, z : array_like, compatible object The three dimensional series is evaluated at the points `(x, y, z)`, where `x`, `y`, and `z` must have the same shape. If any of `x`, `y`, or `z` is a list or tuple, it is first converted to an ndarray, otherwise it is left unchanged and if it isn't an ndarray it is treated as a scalar. c : array_like Array of coefficients ordered so that the coefficient of the term of multi-degree i,j,k is contained in ``c[i,j,k]``. If `c` has dimension greater than 3 the remaining indices enumerate multiple sets of coefficients. Returns ------- values : ndarray, compatible object The values of the multidimension polynomial on points formed with triples of corresponding values from `x`, `y`, and `z`. See Also -------- lagval, lagval2d, laggrid2d, laggrid3d Notes ----- .. versionadded::1.7.0 """ try: x, y, z = np.array((x, y, z), copy=0) except: raise ValueError('x, y, z are incompatible') c = lagval(x, c) c = lagval(y, c, tensor=False) c = lagval(z, c, tensor=False) return c def laggrid3d(x, y, z, c): """ Evaluate a 3-D Laguerre series on the Cartesian product of x, y, and z. This function returns the values: .. math:: p(a,b,c) = \\sum_{i,j,k} c_{i,j,k} * L_i(a) * L_j(b) * L_k(c) where the points `(a, b, c)` consist of all triples formed by taking `a` from `x`, `b` from `y`, and `c` from `z`. The resulting points form a grid with `x` in the first dimension, `y` in the second, and `z` in the third. The parameters `x`, `y`, and `z` are converted to arrays only if they are tuples or a lists, otherwise they are treated as a scalars. In either case, either `x`, `y`, and `z` or their elements must support multiplication and addition both with themselves and with the elements of `c`. If `c` has fewer than three dimensions, ones are implicitly appended to its shape to make it 3-D. The shape of the result will be c.shape[3:] + x.shape + y.shape + z.shape. Parameters ---------- x, y, z : array_like, compatible objects The three dimensional series is evaluated at the points in the Cartesian product of `x`, `y`, and `z`. If `x`,`y`, or `z` is a list or tuple, it is first converted to an ndarray, otherwise it is left unchanged and, if it isn't an ndarray, it is treated as a scalar. c : array_like Array of coefficients ordered so that the coefficients for terms of degree i,j are contained in ``c[i,j]``. If `c` has dimension greater than two the remaining indices enumerate multiple sets of coefficients. Returns ------- values : ndarray, compatible object The values of the two dimensional polynomial at points in the Cartesian product of `x` and `y`. See Also -------- lagval, lagval2d, laggrid2d, lagval3d Notes ----- .. versionadded::1.7.0 """ c = lagval(x, c) c = lagval(y, c) c = lagval(z, c) return c def lagvander(x, deg) : """Pseudo-Vandermonde matrix of given degree. Returns the pseudo-Vandermonde matrix of degree `deg` and sample points `x`. The pseudo-Vandermonde matrix is defined by .. math:: V[..., i] = L_i(x) where `0 <= i <= deg`. The leading indices of `V` index the elements of `x` and the last index is the degree of the Laguerre polynomial. If `c` is a 1-D array of coefficients of length `n + 1` and `V` is the array ``V = lagvander(x, n)``, then ``np.dot(V, c)`` and ``lagval(x, c)`` are the same up to roundoff. This equivalence is useful both for least squares fitting and for the evaluation of a large number of Laguerre series of the same degree and sample points. Parameters ---------- x : array_like Array of points. The dtype is converted to float64 or complex128 depending on whether any of the elements are complex. If `x` is scalar it is converted to a 1-D array. deg : int Degree of the resulting matrix. Returns ------- vander : ndarray The pseudo-Vandermonde matrix. The shape of the returned matrix is ``x.shape + (deg + 1,)``, where The last index is the degree of the corresponding Laguerre polynomial. The dtype will be the same as the converted `x`. Examples -------- >>> from numpy.polynomial.laguerre import lagvander >>> x = np.array([0, 1, 2]) >>> lagvander(x, 3) array([[ 1. , 1. , 1. , 1. ], [ 1. , 0. , -0.5 , -0.66666667], [ 1. , -1. , -1. , -0.33333333]]) """ ideg = int(deg) if ideg != deg: raise ValueError("deg must be integer") if ideg < 0: raise ValueError("deg must be non-negative") x = np.array(x, copy=0, ndmin=1) + 0.0 dims = (ideg + 1,) + x.shape dtyp = x.dtype v = np.empty(dims, dtype=dtyp) v[0] = x*0 + 1 if ideg > 0 : v[1] = 1 - x for i in range(2, ideg + 1) : v[i] = (v[i-1]*(2*i - 1 - x) - v[i-2]*(i - 1))/i return np.rollaxis(v, 0, v.ndim) def lagvander2d(x, y, deg) : """Pseudo-Vandermonde matrix of given degrees. Returns the pseudo-Vandermonde matrix of degrees `deg` and sample points `(x, y)`. The pseudo-Vandermonde matrix is defined by .. math:: V[..., deg[1]*i + j] = L_i(x) * L_j(y), where `0 <= i <= deg[0]` and `0 <= j <= deg[1]`. The leading indices of `V` index the points `(x, y)` and the last index encodes the degrees of the Laguerre polynomials. If ``V = lagvander2d(x, y, [xdeg, ydeg])``, then the columns of `V` correspond to the elements of a 2-D coefficient array `c` of shape (xdeg + 1, ydeg + 1) in the order .. math:: c_{00}, c_{01}, c_{02} ... , c_{10}, c_{11}, c_{12} ... and ``np.dot(V, c.flat)`` and ``lagval2d(x, y, c)`` will be the same up to roundoff. This equivalence is useful both for least squares fitting and for the evaluation of a large number of 2-D Laguerre series of the same degrees and sample points. Parameters ---------- x, y : array_like Arrays of point coordinates, all of the same shape. The dtypes will be converted to either float64 or complex128 depending on whether any of the elements are complex. Scalars are converted to 1-D arrays. deg : list of ints List of maximum degrees of the form [x_deg, y_deg]. Returns ------- vander2d : ndarray The shape of the returned matrix is ``x.shape + (order,)``, where :math:`order = (deg[0]+1)*(deg([1]+1)`. The dtype will be the same as the converted `x` and `y`. See Also -------- lagvander, lagvander3d. lagval2d, lagval3d Notes ----- .. versionadded::1.7.0 """ ideg = [int(d) for d in deg] is_valid = [id == d and id >= 0 for id, d in zip(ideg, deg)] if is_valid != [1, 1]: raise ValueError("degrees must be non-negative integers") degx, degy = ideg x, y = np.array((x, y), copy=0) + 0.0 vx = lagvander(x, degx) vy = lagvander(y, degy) v = vx[..., None]*vy[..., None,:] return v.reshape(v.shape[:-2] + (-1,)) def lagvander3d(x, y, z, deg) : """Pseudo-Vandermonde matrix of given degrees. Returns the pseudo-Vandermonde matrix of degrees `deg` and sample points `(x, y, z)`. If `l, m, n` are the given degrees in `x, y, z`, then The pseudo-Vandermonde matrix is defined by .. math:: V[..., (m+1)(n+1)i + (n+1)j + k] = L_i(x)*L_j(y)*L_k(z), where `0 <= i <= l`, `0 <= j <= m`, and `0 <= j <= n`. The leading indices of `V` index the points `(x, y, z)` and the last index encodes the degrees of the Laguerre polynomials. If ``V = lagvander3d(x, y, z, [xdeg, ydeg, zdeg])``, then the columns of `V` correspond to the elements of a 3-D coefficient array `c` of shape (xdeg + 1, ydeg + 1, zdeg + 1) in the order .. math:: c_{000}, c_{001}, c_{002},... , c_{010}, c_{011}, c_{012},... and ``np.dot(V, c.flat)`` and ``lagval3d(x, y, z, c)`` will be the same up to roundoff. This equivalence is useful both for least squares fitting and for the evaluation of a large number of 3-D Laguerre series of the same degrees and sample points. Parameters ---------- x, y, z : array_like Arrays of point coordinates, all of the same shape. The dtypes will be converted to either float64 or complex128 depending on whether any of the elements are complex. Scalars are converted to 1-D arrays. deg : list of ints List of maximum degrees of the form [x_deg, y_deg, z_deg]. Returns ------- vander3d : ndarray The shape of the returned matrix is ``x.shape + (order,)``, where :math:`order = (deg[0]+1)*(deg([1]+1)*(deg[2]+1)`. The dtype will be the same as the converted `x`, `y`, and `z`. See Also -------- lagvander, lagvander3d. lagval2d, lagval3d Notes ----- .. versionadded::1.7.0 """ ideg = [int(d) for d in deg] is_valid = [id == d and id >= 0 for id, d in zip(ideg, deg)] if is_valid != [1, 1, 1]: raise ValueError("degrees must be non-negative integers") degx, degy, degz = ideg x, y, z = np.array((x, y, z), copy=0) + 0.0 vx = lagvander(x, degx) vy = lagvander(y, degy) vz = lagvander(z, degz) v = vx[..., None, None]*vy[..., None,:, None]*vz[..., None, None,:] return v.reshape(v.shape[:-3] + (-1,)) def lagfit(x, y, deg, rcond=None, full=False, w=None): """ Least squares fit of Laguerre series to data. Return the coefficients of a Laguerre series of degree `deg` that is the least squares fit to the data values `y` given at points `x`. If `y` is 1-D the returned coefficients will also be 1-D. If `y` is 2-D multiple fits are done, one for each column of `y`, and the resulting coefficients are stored in the corresponding columns of a 2-D return. The fitted polynomial(s) are in the form .. math:: p(x) = c_0 + c_1 * L_1(x) + ... + c_n * L_n(x), 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,) 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 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. Returns ------- coef : ndarray, shape (M,) or (M, K) Laguerre coefficients ordered from low to high. If `y` was 2-D, 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`. Warns ----- RankWarning The rank of the coefficient matrix in the least-squares fit is deficient. The warning is only raised if `full` = False. The warnings can be turned off by >>> import warnings >>> warnings.simplefilter('ignore', RankWarning) See Also -------- chebfit, legfit, polyfit, hermfit, hermefit lagval : Evaluates a Laguerre series. lagvander : pseudo Vandermonde matrix of Laguerre series. lagweight : Laguerre weight function. linalg.lstsq : Computes a least-squares fit from the matrix. scipy.interpolate.UnivariateSpline : Computes spline fits. Notes ----- The solution is the coefficients of the Laguerre series `p` that minimizes the sum of the weighted squared errors .. math:: E = \\sum_j w_j^2 * |y_j - p(x_j)|^2, where the :math:`w_j` are the weights. This problem is solved by setting up as the (typically) overdetermined matrix equation .. math:: V(x) * c = w * y, where `V` is the weighted pseudo Vandermonde matrix of `x`, `c` are the coefficients to be solved for, `w` are the weights, and `y` are the observed values. This equation is then solved using the singular value decomposition of `V`. If some of the singular values of `V` are so small that they are neglected, then a `RankWarning` will be issued. This means that the coefficient values may be poorly determined. Using a lower order fit will usually get rid of the warning. The `rcond` parameter can also be set to a value smaller than its default, but the resulting fit may be spurious and have large contributions from roundoff error. Fits using Laguerre series are probably most useful when the data can be approximated by ``sqrt(w(x)) * p(x)``, where `w(x)` is the Laguerre weight. In that case the weight ``sqrt(w(x[i])`` should be used together with data values ``y[i]/sqrt(w(x[i])``. The weight function is available as `lagweight`. References ---------- .. [1] Wikipedia, "Curve fitting", http://en.wikipedia.org/wiki/Curve_fitting Examples -------- >>> from numpy.polynomial.laguerre import lagfit, lagval >>> x = np.linspace(0, 10) >>> err = np.random.randn(len(x))/10 >>> y = lagval(x, [1, 2, 3]) + err >>> lagfit(x, y, 2) array([ 0.96971004, 2.00193749, 3.00288744]) """ order = int(deg) + 1 x = np.asarray(x) + 0.0 y = np.asarray(y) + 0.0 # check arguments. if deg < 0 : raise ValueError("expected deg >= 0") if x.ndim != 1: raise TypeError("expected 1D vector for x") if x.size == 0: raise TypeError("expected non-empty vector for x") if y.ndim < 1 or y.ndim > 2 : raise TypeError("expected 1D or 2D array for y") if len(x) != len(y): raise TypeError("expected x and y to have same length") # set up the least squares matrices in transposed form lhs = lagvander(x, deg).T rhs = y.T if w is not None: w = np.asarray(w) + 0.0 if w.ndim != 1: raise TypeError("expected 1D vector for w") if len(x) != len(w): raise TypeError("expected x and w to have same length") # apply weights. Don't use inplace operations as they # can cause problems with NA. lhs = lhs * w rhs = rhs * w # set rcond if rcond is None : rcond = len(x)*np.finfo(x.dtype).eps # Determine the norms of the design matrix columns. if issubclass(lhs.dtype.type, np.complexfloating): scl = np.sqrt((np.square(lhs.real) + np.square(lhs.imag)).sum(1)) else: scl = np.sqrt(np.square(lhs).sum(1)) scl[scl == 0] = 1 # Solve the least squares problem. c, resids, rank, s = la.lstsq(lhs.T/scl, rhs.T, rcond) c = (c.T/scl).T # warn on rank reduction if rank != order and not full: msg = "The fit may be poorly conditioned" warnings.warn(msg, pu.RankWarning) if full : return c, [resids, rank, s, rcond] else : return c def lagcompanion(c): """ Return the companion matrix of c. The usual companion matrix of the Laguerre polynomials is already symmetric when `c` is a basis Laguerre polynomial, so no scaling is applied. Parameters ---------- c : array_like 1-D array of Laguerre series coefficients ordered from low to high degree. Returns ------- mat : ndarray Companion matrix of dimensions (deg, deg). Notes ----- .. versionadded::1.7.0 """ accprod = np.multiply.accumulate # c is a trimmed copy [c] = pu.as_series([c]) if len(c) < 2: raise ValueError('Series must have maximum degree of at least 1.') if len(c) == 2: return np.array([[1 + c[0]/c[1]]]) n = len(c) - 1 mat = np.zeros((n, n), dtype=c.dtype) top = mat.reshape(-1)[1::n+1] mid = mat.reshape(-1)[0::n+1] bot = mat.reshape(-1)[n::n+1] top[...] = -np.arange(1, n) mid[...] = 2.*np.arange(n) + 1. bot[...] = top mat[:, -1] += (c[:-1]/c[-1])*n return mat def lagroots(c): """ Compute the roots of a Laguerre series. Return the roots (a.k.a. "zeros") of the polynomial .. math:: p(x) = \\sum_i c[i] * L_i(x). Parameters ---------- c : 1-D array_like 1-D array of coefficients. Returns ------- out : ndarray Array of the roots of the series. If all the roots are real, then `out` is also real, otherwise it is complex. See Also -------- polyroots, legroots, chebroots, hermroots, hermeroots Notes ----- The root estimates are obtained as the eigenvalues of the companion matrix, Roots far from the origin of the complex plane may have large errors due to the numerical instability of the series for such values. Roots with multiplicity greater than 1 will also show larger errors as the value of the series near such points is relatively insensitive to errors in the roots. Isolated roots near the origin can be improved by a few iterations of Newton's method. The Laguerre series basis polynomials aren't powers of `x` so the results of this function may seem unintuitive. Examples -------- >>> from numpy.polynomial.laguerre import lagroots, lagfromroots >>> coef = lagfromroots([0, 1, 2]) >>> coef array([ 2., -8., 12., -6.]) >>> lagroots(coef) array([ -4.44089210e-16, 1.00000000e+00, 2.00000000e+00]) """ # c is a trimmed copy [c] = pu.as_series([c]) if len(c) <= 1 : return np.array([], dtype=c.dtype) if len(c) == 2 : return np.array([1 + c[0]/c[1]]) m = lagcompanion(c) r = la.eigvals(m) r.sort() return r def laggauss(deg): """ Gauss-Laguerre quadrature. Computes the sample points and weights for Gauss-Laguerre quadrature. These sample points and weights will correctly integrate polynomials of degree :math:`2*deg - 1` or less over the interval :math:`[0, \inf]` with the weight function :math:`f(x) = \exp(-x)`. Parameters ---------- deg : int Number of sample points and weights. It must be >= 1. Returns ------- x : ndarray 1-D ndarray containing the sample points. y : ndarray 1-D ndarray containing the weights. Notes ----- .. versionadded::1.7.0 The results have only been tested up to degree 100 higher degrees may be problematic. The weights are determined by using the fact that .. math:: w_k = c / (L'_n(x_k) * L_{n-1}(x_k)) where :math:`c` is a constant independent of :math:`k` and :math:`x_k` is the k'th root of :math:`L_n`, and then scaling the results to get the right value when integrating 1. """ ideg = int(deg) if ideg != deg or ideg < 1: raise ValueError("deg must be a non-negative integer") # first approximation of roots. We use the fact that the companion # matrix is symmetric in this case in order to obtain better zeros. c = np.array([0]*deg + [1]) m = lagcompanion(c) x = la.eigvals(m) x.sort() # improve roots by one application of Newton dy = lagval(x, c) df = lagval(x, lagder(c)) x -= dy/df # compute the weights. We scale the factor to avoid possible numerical # overflow. fm = lagval(x, c[1:]) fm /= np.abs(fm).max() df /= np.abs(df).max() w = 1/(fm * df) # scale w to get the right value, 1 in this case w /= w.sum() return x, w def lagweight(x): """Weight function of the Laguerre polynomials. The weight function is :math:`exp(-x)` and the interval of integration is :math:`[0, \inf]`. The Laguerre polynomials are orthogonal, but not normalized, with respect to this weight function. Parameters ---------- x : array_like Values at which the weight function will be computed. Returns ------- w : ndarray The weight function at `x`. Notes ----- .. versionadded::1.7.0 """ w = np.exp(-x) return w # # Laguerre series class # exec(polytemplate.substitute(name='Laguerre', nick='lag', domain='[-1,1]')) numpy-1.8.2/numpy/polynomial/polynomial.py0000664000175100017510000013377712370216243022136 0ustar vagrantvagrant00000000000000""" Objects for dealing with polynomials. This module provides a number of objects (mostly functions) useful for dealing with polynomials, including a `Polynomial` class that encapsulates the usual arithmetic operations. (General information on how this module represents and works with polynomial objects is in the docstring for its "parent" sub-package, `numpy.polynomial`). Constants --------- - `polydomain` -- Polynomial default domain, [-1,1]. - `polyzero` -- (Coefficients of the) "zero polynomial." - `polyone` -- (Coefficients of the) constant polynomial 1. - `polyx` -- (Coefficients of the) identity map polynomial, ``f(x) = x``. Arithmetic ---------- - `polyadd` -- add two polynomials. - `polysub` -- subtract one polynomial from another. - `polymul` -- multiply two polynomials. - `polydiv` -- divide one polynomial by another. - `polypow` -- raise a polynomial to an positive integer power - `polyval` -- evaluate a polynomial at given points. - `polyval2d` -- evaluate a 2D polynomial at given points. - `polyval3d` -- evaluate a 3D polynomial at given points. - `polygrid2d` -- evaluate a 2D polynomial on a Cartesian product. - `polygrid3d` -- evaluate a 3D polynomial on a Cartesian product. Calculus -------- - `polyder` -- differentiate a polynomial. - `polyint` -- integrate a polynomial. Misc Functions -------------- - `polyfromroots` -- create a polynomial with specified roots. - `polyroots` -- find the roots of a polynomial. - `polyvander` -- Vandermonde-like matrix for powers. - `polyvander2d` -- Vandermonde-like matrix for 2D power series. - `polyvander3d` -- Vandermonde-like matrix for 3D power series. - `polycompanion` -- companion matrix in power series form. - `polyfit` -- least-squares fit returning a polynomial. - `polytrim` -- trim leading coefficients from a polynomial. - `polyline` -- polynomial representing given straight line. Classes ------- - `Polynomial` -- polynomial class. See also -------- `numpy.polynomial` """ from __future__ import division, absolute_import, print_function __all__ = ['polyzero', 'polyone', 'polyx', 'polydomain', 'polyline', 'polyadd', 'polysub', 'polymulx', 'polymul', 'polydiv', 'polypow', 'polyval', 'polyder', 'polyint', 'polyfromroots', 'polyvander', 'polyfit', 'polytrim', 'polyroots', 'Polynomial', 'polyval2d', 'polyval3d', 'polygrid2d', 'polygrid3d', 'polyvander2d', 'polyvander3d'] import numpy as np import numpy.linalg as la from . import polyutils as pu import warnings from .polytemplate import polytemplate polytrim = pu.trimcoef # # These are constant arrays are of integer type so as to be compatible # with the widest range of other types, such as Decimal. # # Polynomial default domain. polydomain = np.array([-1, 1]) # Polynomial coefficients representing zero. polyzero = np.array([0]) # Polynomial coefficients representing one. polyone = np.array([1]) # Polynomial coefficients representing the identity x. polyx = np.array([0, 1]) # # Polynomial series functions # def polyline(off, scl) : """ Returns an array representing a linear polynomial. Parameters ---------- off, scl : scalars The "y-intercept" and "slope" of the line, respectively. Returns ------- y : ndarray This module's representation of the linear polynomial ``off + scl*x``. See Also -------- chebline Examples -------- >>> from numpy import polynomial as P >>> P.polyline(1,-1) array([ 1, -1]) >>> P.polyval(1, P.polyline(1,-1)) # should be 0 0.0 """ if scl != 0 : return np.array([off, scl]) else : return np.array([off]) def polyfromroots(roots) : """ Generate a monic polynomial with given roots. Return the coefficients of the polynomial .. math:: p(x) = (x - r_0) * (x - r_1) * ... * (x - r_n), where the `r_n` are the roots specified in `roots`. If a zero has multiplicity n, then it must appear in `roots` n times. For instance, if 2 is a root of multiplicity three and 3 is a root of multiplicity 2, then `roots` looks something like [2, 2, 2, 3, 3]. The roots can appear in any order. If the returned coefficients are `c`, then .. math:: p(x) = c_0 + c_1 * x + ... + x^n The coefficient of the last term is 1 for monic polynomials in this form. Parameters ---------- roots : array_like Sequence containing the roots. Returns ------- out : ndarray 1-D array of the polynomial's coefficients If all the roots are real, then `out` is also real, otherwise it is complex. (see Examples below). See Also -------- chebfromroots, legfromroots, lagfromroots, hermfromroots hermefromroots Notes ----- The coefficients are determined by multiplying together linear factors of the form `(x - r_i)`, i.e. .. math:: p(x) = (x - r_0) (x - r_1) ... (x - r_n) where ``n == len(roots) - 1``; note that this implies that `1` is always returned for :math:`a_n`. Examples -------- >>> import numpy.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) >>> P.polyfromroots((-j,j)) # complex returned, though values are real array([ 1.+0.j, 0.+0.j, 1.+0.j]) """ if len(roots) == 0 : return np.ones(1) else : [roots] = pu.as_series([roots], trim=False) roots.sort() p = [polyline(-r, 1) for r in roots] n = len(p) while n > 1: m, r = divmod(n, 2) tmp = [polymul(p[i], p[i+m]) for i in range(m)] if r: tmp[0] = polymul(tmp[0], p[-1]) p = tmp n = m return p[0] def polyadd(c1, c2): """ Add one polynomial to another. Returns the sum of two polynomials `c1` + `c2`. The arguments are sequences of coefficients from lowest order term to highest, i.e., [1,2,3] represents the polynomial ``1 + 2*x + 3*x**2``. Parameters ---------- c1, c2 : array_like 1-D arrays of polynomial coefficients ordered from low to high. Returns ------- out : ndarray The coefficient array representing their sum. See Also -------- polysub, polymul, polydiv, polypow Examples -------- >>> from numpy import polynomial as P >>> c1 = (1,2,3) >>> c2 = (3,2,1) >>> sum = P.polyadd(c1,c2); sum array([ 4., 4., 4.]) >>> P.polyval(2, sum) # 4 + 4(2) + 4(2**2) 28.0 """ # c1, c2 are trimmed copies [c1, c2] = pu.as_series([c1, c2]) if len(c1) > len(c2) : c1[:c2.size] += c2 ret = c1 else : c2[:c1.size] += c1 ret = c2 return pu.trimseq(ret) def polysub(c1, c2): """ Subtract one polynomial from another. Returns the difference of two polynomials `c1` - `c2`. The arguments are sequences of coefficients from lowest order term to highest, i.e., [1,2,3] represents the polynomial ``1 + 2*x + 3*x**2``. Parameters ---------- c1, c2 : array_like 1-D arrays of polynomial coefficients ordered from low to high. Returns ------- out : ndarray Of coefficients representing their difference. See Also -------- polyadd, polymul, polydiv, polypow Examples -------- >>> from numpy import polynomial as P >>> c1 = (1,2,3) >>> c2 = (3,2,1) >>> P.polysub(c1,c2) array([-2., 0., 2.]) >>> P.polysub(c2,c1) # -P.polysub(c1,c2) array([ 2., 0., -2.]) """ # c1, c2 are trimmed copies [c1, c2] = pu.as_series([c1, c2]) if len(c1) > len(c2) : c1[:c2.size] -= c2 ret = c1 else : c2 = -c2 c2[:c1.size] += c1 ret = c2 return pu.trimseq(ret) def polymulx(c): """Multiply a polynomial by x. Multiply the polynomial `c` by x, where x is the independent variable. Parameters ---------- c : array_like 1-D array of polynomial coefficients ordered from low to high. Returns ------- out : ndarray Array representing the result of the multiplication. Notes ----- .. versionadded:: 1.5.0 """ # c is a trimmed copy [c] = pu.as_series([c]) # The zero series needs special treatment if len(c) == 1 and c[0] == 0: return c prd = np.empty(len(c) + 1, dtype=c.dtype) prd[0] = c[0]*0 prd[1:] = c return prd def polymul(c1, c2): """ Multiply one polynomial by another. Returns the product of two polynomials `c1` * `c2`. The arguments are sequences of coefficients, from lowest order term to highest, e.g., [1,2,3] represents the polynomial ``1 + 2*x + 3*x**2.`` Parameters ---------- c1, c2 : array_like 1-D arrays of coefficients representing a polynomial, relative to the "standard" basis, and ordered from lowest order term to highest. Returns ------- out : ndarray Of the coefficients of their product. See Also -------- polyadd, polysub, polydiv, polypow Examples -------- >>> import numpy.polynomial as P >>> c1 = (1,2,3) >>> c2 = (3,2,1) >>> P.polymul(c1,c2) array([ 3., 8., 14., 8., 3.]) """ # c1, c2 are trimmed copies [c1, c2] = pu.as_series([c1, c2]) ret = np.convolve(c1, c2) return pu.trimseq(ret) def polydiv(c1, c2): """ Divide one polynomial by another. Returns the quotient-with-remainder of two polynomials `c1` / `c2`. The arguments are sequences of coefficients, from lowest order term to highest, e.g., [1,2,3] represents ``1 + 2*x + 3*x**2``. Parameters ---------- c1, c2 : array_like 1-D arrays of polynomial coefficients ordered from low to high. Returns ------- [quo, rem] : ndarrays Of coefficient series representing the quotient and remainder. See Also -------- polyadd, polysub, polymul, polypow Examples -------- >>> import numpy.polynomial as P >>> c1 = (1,2,3) >>> c2 = (3,2,1) >>> P.polydiv(c1,c2) (array([ 3.]), array([-8., -4.])) >>> P.polydiv(c2,c1) (array([ 0.33333333]), array([ 2.66666667, 1.33333333])) """ # c1, c2 are trimmed copies [c1, c2] = pu.as_series([c1, c2]) if c2[-1] == 0 : raise ZeroDivisionError() len1 = len(c1) len2 = len(c2) if len2 == 1 : return c1/c2[-1], c1[:1]*0 elif len1 < len2 : return c1[:1]*0, c1 else : dlen = len1 - len2 scl = c2[-1] c2 = c2[:-1]/scl i = dlen j = len1 - 1 while i >= 0 : c1[i:j] -= c2*c1[j] i -= 1 j -= 1 return c1[j+1:]/scl, pu.trimseq(c1[:j+1]) def polypow(c, pow, maxpower=None) : """Raise a polynomial to a power. Returns the polynomial `c` raised to the power `pow`. The argument `c` is a sequence of coefficients ordered from low to high. i.e., [1,2,3] is the series ``1 + 2*x + 3*x**2.`` Parameters ---------- c : array_like 1-D array of array of series coefficients ordered from low to high degree. pow : integer Power to which the series will be raised maxpower : integer, optional Maximum power allowed. This is mainly to limit growth of the series to unmanageable size. Default is 16 Returns ------- coef : ndarray Power series of power. See Also -------- polyadd, polysub, polymul, polydiv Examples -------- """ # c is a trimmed copy [c] = pu.as_series([c]) power = int(pow) if power != pow or power < 0 : raise ValueError("Power must be a non-negative integer.") elif maxpower is not None and power > maxpower : raise ValueError("Power is too large") elif power == 0 : return np.array([1], dtype=c.dtype) elif power == 1 : return c else : # This can be made more efficient by using powers of two # in the usual way. prd = c for i in range(2, power + 1) : prd = np.convolve(prd, c) return prd def polyder(c, m=1, scl=1, axis=0): """ Differentiate a polynomial. Returns the polynomial coefficients `c` differentiated `m` times along `axis`. At each iteration the result is multiplied by `scl` (the scaling factor is for use in a linear change of variable). The argument `c` is an array of coefficients from low to high degree along each axis, e.g., [1,2,3] represents the polynomial ``1 + 2*x + 3*x**2`` while [[1,2],[1,2]] represents ``1 + 1*x + 2*y + 2*x*y`` if axis=0 is ``x`` and axis=1 is ``y``. Parameters ---------- c : array_like Array of polynomial coefficients. If c is multidimensional the different axis correspond to different variables with the degree in each axis given by the corresponding index. m : int, optional Number of derivatives taken, must be non-negative. (Default: 1) scl : scalar, optional Each differentiation is multiplied by `scl`. The end result is multiplication by ``scl**m``. This is for use in a linear change of variable. (Default: 1) axis : int, optional Axis over which the derivative is taken. (Default: 0). .. versionadded:: 1.7.0 Returns ------- der : ndarray Polynomial coefficients of the derivative. See Also -------- polyint Examples -------- >>> from numpy 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.]) >>> P.polyder(c,3) # (d**3/dx**3)(c) = 24 array([ 24.]) >>> P.polyder(c,scl=-1) # (d/d(-x))(c) = -2 - 6x - 12x**2 array([ -2., -6., -12.]) >>> P.polyder(c,2,-1) # (d**2/d(-x)**2)(c) = 6 + 24x array([ 6., 24.]) """ c = np.array(c, ndmin=1, copy=1) if c.dtype.char in '?bBhHiIlLqQpP': # astype fails with NA c = c + 0.0 cdt = c.dtype cnt, iaxis = [int(t) for t in [m, axis]] if cnt != m: raise ValueError("The order of derivation must be integer") if cnt < 0: raise ValueError("The order of derivation must be non-negative") if iaxis != axis: raise ValueError("The axis must be integer") if not -c.ndim <= iaxis < c.ndim: raise ValueError("The axis is out of range") if iaxis < 0: iaxis += c.ndim if cnt == 0: return c c = np.rollaxis(c, iaxis) n = len(c) if cnt >= n: c = c[:1]*0 else : for i in range(cnt): n = n - 1 c *= scl der = np.empty((n,) + c.shape[1:], dtype=cdt) for j in range(n, 0, -1): der[j - 1] = j*c[j] c = der c = np.rollaxis(c, 0, iaxis + 1) return c def polyint(c, m=1, k=[], lbnd=0, scl=1, axis=0): """ Integrate a polynomial. Returns the polynomial coefficients `c` integrated `m` times from `lbnd` along `axis`. At each iteration the resulting series is **multiplied** by `scl` and an integration constant, `k`, is added. The scaling factor is for use in a linear change of variable. ("Buyer beware": note that, depending on what one is doing, one may want `scl` to be the reciprocal of what one might expect; for more information, see the Notes section below.) The argument `c` is an array of coefficients, from low to high degree along each axis, e.g., [1,2,3] represents the polynomial ``1 + 2*x + 3*x**2`` while [[1,2],[1,2]] represents ``1 + 1*x + 2*y + 2*x*y`` if axis=0 is ``x`` and axis=1 is ``y``. Parameters ---------- c : array_like 1-D array of polynomial coefficients, ordered from low to high. m : int, optional Order of integration, must be positive. (Default: 1) k : {[], list, scalar}, optional Integration constant(s). The value of the first integral at zero is the first value in the list, the value of the second integral at zero is the second value, etc. If ``k == []`` (the default), all constants are set to zero. If ``m == 1``, a single scalar can be given instead of a list. lbnd : scalar, optional The lower bound of the integral. (Default: 0) scl : scalar, optional Following each integration the result is *multiplied* by `scl` before the integration constant is added. (Default: 1) axis : int, optional Axis over which the integral is taken. (Default: 0). .. versionadded:: 1.7.0 Returns ------- S : ndarray Coefficient array of the integral. Raises ------ ValueError If ``m < 1``, ``len(k) > m``. See Also -------- polyder Notes ----- Note that the result of each integration is *multiplied* by `scl`. Why is this important to note? Say one is making a linear change of variable :math:`u = ax + b` in an integral relative to `x`. Then .. math::`dx = du/a`, so one will need to set `scl` equal to :math:`1/a` - perhaps not what one would have first thought. Examples -------- >>> from numpy import polynomial as P >>> c = (1,2,3) >>> P.polyint(c) # should return array([0, 1, 1, 1]) array([ 0., 1., 1., 1.]) >>> P.polyint(c,3) # should return array([0, 0, 0, 1/6, 1/12, 1/20]) array([ 0. , 0. , 0. , 0.16666667, 0.08333333, 0.05 ]) >>> P.polyint(c,k=3) # should return array([3, 1, 1, 1]) array([ 3., 1., 1., 1.]) >>> P.polyint(c,lbnd=-2) # should return array([6, 1, 1, 1]) array([ 6., 1., 1., 1.]) >>> P.polyint(c,scl=-2) # should return array([0, -2, -2, -2]) array([ 0., -2., -2., -2.]) """ c = np.array(c, ndmin=1, copy=1) if c.dtype.char in '?bBhHiIlLqQpP': # astype doesn't preserve mask attribute. c = c + 0.0 cdt = c.dtype if not np.iterable(k): k = [k] cnt, iaxis = [int(t) for t in [m, axis]] if cnt != m: raise ValueError("The order of integration must be integer") if cnt < 0 : raise ValueError("The order of integration must be non-negative") if len(k) > cnt : raise ValueError("Too many integration constants") if iaxis != axis: raise ValueError("The axis must be integer") if not -c.ndim <= iaxis < c.ndim: raise ValueError("The axis is out of range") if iaxis < 0: iaxis += c.ndim if cnt == 0: return c k = list(k) + [0]*(cnt - len(k)) c = np.rollaxis(c, iaxis) for i in range(cnt): n = len(c) c *= scl if n == 1 and np.all(c[0] == 0): c[0] += k[i] else: tmp = np.empty((n + 1,) + c.shape[1:], dtype=cdt) tmp[0] = c[0]*0 tmp[1] = c[0] for j in range(1, n): tmp[j + 1] = c[j]/(j + 1) tmp[0] += k[i] - polyval(lbnd, tmp) c = tmp c = np.rollaxis(c, 0, iaxis + 1) return c def polyval(x, c, tensor=True): """ Evaluate a polynomial at points x. If `c` is of length `n + 1`, this function returns the value .. math:: p(x) = c_0 + c_1 * x + ... + c_n * x^n The parameter `x` is converted to an array only if it is a tuple or a list, otherwise it is treated as a scalar. In either case, either `x` or its elements must support multiplication and addition both with themselves and with the elements of `c`. If `c` is a 1-D array, then `p(x)` will have the same shape as `x`. If `c` is multidimensional, then the shape of the result depends on the value of `tensor`. If `tensor` is true the shape will be c.shape[1:] + x.shape. If `tensor` is false the shape will be c.shape[1:]. Note that scalars have shape (,). Trailing zeros in the coefficients will be used in the evaluation, so they should be avoided if efficiency is a concern. Parameters ---------- x : array_like, compatible object If `x` is a list or tuple, it is converted to an ndarray, otherwise it is left unchanged and treated as a scalar. In either case, `x` or its elements must support addition and multiplication with with themselves and with the elements of `c`. c : array_like Array of coefficients ordered so that the coefficients for terms of degree n are contained in c[n]. If `c` is multidimensional the remaining indices enumerate multiple polynomials. In the two dimensional case the coefficients may be thought of as stored in the columns of `c`. tensor : boolean, optional If True, the shape of the coefficient array is extended with ones on the right, one for each dimension of `x`. Scalars have dimension 0 for this action. The result is that every column of coefficients in `c` is evaluated for every element of `x`. If False, `x` is broadcast over the columns of `c` for the evaluation. This keyword is useful when `c` is multidimensional. The default value is True. .. versionadded:: 1.7.0 Returns ------- values : ndarray, compatible object The shape of the returned array is described above. See Also -------- polyval2d, polygrid2d, polyval3d, polygrid3d Notes ----- The evaluation uses Horner's method. Examples -------- >>> from numpy.polynomial.polynomial import polyval >>> polyval(1, [1,2,3]) 6.0 >>> a = np.arange(4).reshape(2,2) >>> a array([[0, 1], [2, 3]]) >>> polyval(a, [1,2,3]) array([[ 1., 6.], [ 17., 34.]]) >>> coef = np.arange(4).reshape(2,2) # multidimensional coefficients >>> coef array([[0, 1], [2, 3]]) >>> polyval([1,2], coef, tensor=True) array([[ 2., 4.], [ 4., 7.]]) >>> polyval([1,2], coef, tensor=False) array([ 2., 7.]) """ c = np.array(c, ndmin=1, copy=0) if c.dtype.char in '?bBhHiIlLqQpP': # astype fails with NA c = c + 0.0 if isinstance(x, (tuple, list)): x = np.asarray(x) if isinstance(x, np.ndarray) and tensor: c = c.reshape(c.shape + (1,)*x.ndim) c0 = c[-1] + x*0 for i in range(2, len(c) + 1) : c0 = c[-i] + c0*x return c0 def polyval2d(x, y, c): """ Evaluate a 2-D polynomial at points (x, y). This function returns the value .. math:: p(x,y) = \\sum_{i,j} c_{i,j} * x^i * y^j The parameters `x` and `y` are converted to arrays only if they are tuples or a lists, otherwise they are treated as a scalars and they must have the same shape after conversion. In either case, either `x` and `y` or their elements must support multiplication and addition both with themselves and with the elements of `c`. If `c` has fewer than two dimensions, ones are implicitly appended to its shape to make it 2-D. The shape of the result will be c.shape[2:] + x.shape. Parameters ---------- x, y : array_like, compatible objects The two dimensional series is evaluated at the points `(x, y)`, where `x` and `y` must have the same shape. If `x` or `y` is a list or tuple, it is first converted to an ndarray, otherwise it is left unchanged and, if it isn't an ndarray, it is treated as a scalar. c : array_like Array of coefficients ordered so that the coefficient of the term of multi-degree i,j is contained in `c[i,j]`. If `c` has dimension greater than two the remaining indices enumerate multiple sets of coefficients. Returns ------- values : ndarray, compatible object The values of the two dimensional polynomial at points formed with pairs of corresponding values from `x` and `y`. See Also -------- polyval, polygrid2d, polyval3d, polygrid3d Notes ----- .. versionadded::1.7.0 """ try: x, y = np.array((x, y), copy=0) except: raise ValueError('x, y are incompatible') c = polyval(x, c) c = polyval(y, c, tensor=False) return c def polygrid2d(x, y, c): """ Evaluate a 2-D polynomial on the Cartesian product of x and y. This function returns the values: .. math:: p(a,b) = \\sum_{i,j} c_{i,j} * a^i * b^j where the points `(a, b)` consist of all pairs formed by taking `a` from `x` and `b` from `y`. The resulting points form a grid with `x` in the first dimension and `y` in the second. The parameters `x` and `y` are converted to arrays only if they are tuples or a lists, otherwise they are treated as a scalars. In either case, either `x` and `y` or their elements must support multiplication and addition both with themselves and with the elements of `c`. If `c` has fewer than two dimensions, ones are implicitly appended to its shape to make it 2-D. The shape of the result will be c.shape[2:] + x.shape + y.shape. Parameters ---------- x, y : array_like, compatible objects The two dimensional series is evaluated at the points in the Cartesian product of `x` and `y`. If `x` or `y` is a list or tuple, it is first converted to an ndarray, otherwise it is left unchanged and, if it isn't an ndarray, it is treated as a scalar. c : array_like Array of coefficients ordered so that the coefficients for terms of degree i,j are contained in ``c[i,j]``. If `c` has dimension greater than two the remaining indices enumerate multiple sets of coefficients. Returns ------- values : ndarray, compatible object The values of the two dimensional polynomial at points in the Cartesian product of `x` and `y`. See Also -------- polyval, polyval2d, polyval3d, polygrid3d Notes ----- .. versionadded::1.7.0 """ c = polyval(x, c) c = polyval(y, c) return c def polyval3d(x, y, z, c): """ Evaluate a 3-D polynomial at points (x, y, z). This function returns the values: .. math:: p(x,y,z) = \\sum_{i,j,k} c_{i,j,k} * x^i * y^j * z^k The parameters `x`, `y`, and `z` are converted to arrays only if they are tuples or a lists, otherwise they are treated as a scalars and they must have the same shape after conversion. In either case, either `x`, `y`, and `z` or their elements must support multiplication and addition both with themselves and with the elements of `c`. If `c` has fewer than 3 dimensions, ones are implicitly appended to its shape to make it 3-D. The shape of the result will be c.shape[3:] + x.shape. Parameters ---------- x, y, z : array_like, compatible object The three dimensional series is evaluated at the points `(x, y, z)`, where `x`, `y`, and `z` must have the same shape. If any of `x`, `y`, or `z` is a list or tuple, it is first converted to an ndarray, otherwise it is left unchanged and if it isn't an ndarray it is treated as a scalar. c : array_like Array of coefficients ordered so that the coefficient of the term of multi-degree i,j,k is contained in ``c[i,j,k]``. If `c` has dimension greater than 3 the remaining indices enumerate multiple sets of coefficients. Returns ------- values : ndarray, compatible object The values of the multidimensional polynomial on points formed with triples of corresponding values from `x`, `y`, and `z`. See Also -------- polyval, polyval2d, polygrid2d, polygrid3d Notes ----- .. versionadded::1.7.0 """ try: x, y, z = np.array((x, y, z), copy=0) except: raise ValueError('x, y, z are incompatible') c = polyval(x, c) c = polyval(y, c, tensor=False) c = polyval(z, c, tensor=False) return c def polygrid3d(x, y, z, c): """ Evaluate a 3-D polynomial on the Cartesian product of x, y and z. This function returns the values: .. math:: p(a,b,c) = \\sum_{i,j,k} c_{i,j,k} * a^i * b^j * c^k where the points `(a, b, c)` consist of all triples formed by taking `a` from `x`, `b` from `y`, and `c` from `z`. The resulting points form a grid with `x` in the first dimension, `y` in the second, and `z` in the third. The parameters `x`, `y`, and `z` are converted to arrays only if they are tuples or a lists, otherwise they are treated as a scalars. In either case, either `x`, `y`, and `z` or their elements must support multiplication and addition both with themselves and with the elements of `c`. If `c` has fewer than three dimensions, ones are implicitly appended to its shape to make it 3-D. The shape of the result will be c.shape[3:] + x.shape + y.shape + z.shape. Parameters ---------- x, y, z : array_like, compatible objects The three dimensional series is evaluated at the points in the Cartesian product of `x`, `y`, and `z`. If `x`,`y`, or `z` is a list or tuple, it is first converted to an ndarray, otherwise it is left unchanged and, if it isn't an ndarray, it is treated as a scalar. c : array_like Array of coefficients ordered so that the coefficients for terms of degree i,j are contained in ``c[i,j]``. If `c` has dimension greater than two the remaining indices enumerate multiple sets of coefficients. Returns ------- values : ndarray, compatible object The values of the two dimensional polynomial at points in the Cartesian product of `x` and `y`. See Also -------- polyval, polyval2d, polygrid2d, polyval3d Notes ----- .. versionadded::1.7.0 """ c = polyval(x, c) c = polyval(y, c) c = polyval(z, c) return c def polyvander(x, deg) : """Vandermonde matrix of given degree. Returns the Vandermonde matrix of degree `deg` and sample points `x`. The Vandermonde matrix is defined by .. math:: V[..., i] = x^i, where `0 <= i <= deg`. The leading indices of `V` index the elements of `x` and the last index is the power of `x`. If `c` is a 1-D array of coefficients of length `n + 1` and `V` is the matrix ``V = polyvander(x, n)``, then ``np.dot(V, c)`` and ``polyval(x, c)`` are the same up to roundoff. This equivalence is useful both for least squares fitting and for the evaluation of a large number of polynomials of the same degree and sample points. Parameters ---------- x : array_like Array of points. The dtype is converted to float64 or complex128 depending on whether any of the elements are complex. If `x` is scalar it is converted to a 1-D array. deg : int Degree of the resulting matrix. Returns ------- vander : ndarray. The Vandermonde matrix. The shape of the returned matrix is ``x.shape + (deg + 1,)``, where the last index is the power of `x`. The dtype will be the same as the converted `x`. See Also -------- polyvander2d, polyvander3d """ ideg = int(deg) if ideg != deg: raise ValueError("deg must be integer") if ideg < 0: raise ValueError("deg must be non-negative") x = np.array(x, copy=0, ndmin=1) + 0.0 dims = (ideg + 1,) + x.shape dtyp = x.dtype v = np.empty(dims, dtype=dtyp) v[0] = x*0 + 1 if ideg > 0 : v[1] = x for i in range(2, ideg + 1) : v[i] = v[i-1]*x return np.rollaxis(v, 0, v.ndim) def polyvander2d(x, y, deg) : """Pseudo-Vandermonde matrix of given degrees. Returns the pseudo-Vandermonde matrix of degrees `deg` and sample points `(x, y)`. The pseudo-Vandermonde matrix is defined by .. math:: V[..., deg[1]*i + j] = x^i * y^j, where `0 <= i <= deg[0]` and `0 <= j <= deg[1]`. The leading indices of `V` index the points `(x, y)` and the last index encodes the powers of `x` and `y`. If ``V = polyvander2d(x, y, [xdeg, ydeg])``, then the columns of `V` correspond to the elements of a 2-D coefficient array `c` of shape (xdeg + 1, ydeg + 1) in the order .. math:: c_{00}, c_{01}, c_{02} ... , c_{10}, c_{11}, c_{12} ... and ``np.dot(V, c.flat)`` and ``polyval2d(x, y, c)`` will be the same up to roundoff. This equivalence is useful both for least squares fitting and for the evaluation of a large number of 2-D polynomials of the same degrees and sample points. Parameters ---------- x, y : array_like Arrays of point coordinates, all of the same shape. The dtypes will be converted to either float64 or complex128 depending on whether any of the elements are complex. Scalars are converted to 1-D arrays. deg : list of ints List of maximum degrees of the form [x_deg, y_deg]. Returns ------- vander2d : ndarray The shape of the returned matrix is ``x.shape + (order,)``, where :math:`order = (deg[0]+1)*(deg([1]+1)`. The dtype will be the same as the converted `x` and `y`. See Also -------- polyvander, polyvander3d. polyval2d, polyval3d """ ideg = [int(d) for d in deg] is_valid = [id == d and id >= 0 for id, d in zip(ideg, deg)] if is_valid != [1, 1]: raise ValueError("degrees must be non-negative integers") degx, degy = ideg x, y = np.array((x, y), copy=0) + 0.0 vx = polyvander(x, degx) vy = polyvander(y, degy) v = vx[..., None]*vy[..., None,:] # einsum bug #v = np.einsum("...i,...j->...ij", vx, vy) return v.reshape(v.shape[:-2] + (-1,)) def polyvander3d(x, y, z, deg) : """Pseudo-Vandermonde matrix of given degrees. Returns the pseudo-Vandermonde matrix of degrees `deg` and sample points `(x, y, z)`. If `l, m, n` are the given degrees in `x, y, z`, then The pseudo-Vandermonde matrix is defined by .. math:: V[..., (m+1)(n+1)i + (n+1)j + k] = x^i * y^j * z^k, where `0 <= i <= l`, `0 <= j <= m`, and `0 <= j <= n`. The leading indices of `V` index the points `(x, y, z)` and the last index encodes the powers of `x`, `y`, and `z`. If ``V = polyvander3d(x, y, z, [xdeg, ydeg, zdeg])``, then the columns of `V` correspond to the elements of a 3-D coefficient array `c` of shape (xdeg + 1, ydeg + 1, zdeg + 1) in the order .. math:: c_{000}, c_{001}, c_{002},... , c_{010}, c_{011}, c_{012},... and ``np.dot(V, c.flat)`` and ``polyval3d(x, y, z, c)`` will be the same up to roundoff. This equivalence is useful both for least squares fitting and for the evaluation of a large number of 3-D polynomials of the same degrees and sample points. Parameters ---------- x, y, z : array_like Arrays of point coordinates, all of the same shape. The dtypes will be converted to either float64 or complex128 depending on whether any of the elements are complex. Scalars are converted to 1-D arrays. deg : list of ints List of maximum degrees of the form [x_deg, y_deg, z_deg]. Returns ------- vander3d : ndarray The shape of the returned matrix is ``x.shape + (order,)``, where :math:`order = (deg[0]+1)*(deg([1]+1)*(deg[2]+1)`. The dtype will be the same as the converted `x`, `y`, and `z`. See Also -------- polyvander, polyvander3d. polyval2d, polyval3d Notes ----- .. versionadded::1.7.0 """ ideg = [int(d) for d in deg] is_valid = [id == d and id >= 0 for id, d in zip(ideg, deg)] if is_valid != [1, 1, 1]: raise ValueError("degrees must be non-negative integers") degx, degy, degz = ideg x, y, z = np.array((x, y, z), copy=0) + 0.0 vx = polyvander(x, degx) vy = polyvander(y, degy) vz = polyvander(z, degz) v = vx[..., None, None]*vy[..., None,:, None]*vz[..., None, None,:] # einsum bug #v = np.einsum("...i, ...j, ...k->...ijk", vx, vy, vz) return v.reshape(v.shape[:-3] + (-1,)) def polyfit(x, y, deg, rcond=None, full=False, w=None): """ Least-squares fit of a polynomial to data. Return the coefficients of a polynomial of degree `deg` that is the least squares fit to the data values `y` given at points `x`. If `y` is 1-D the returned coefficients will also be 1-D. If `y` is 2-D multiple fits are done, one for each column of `y`, and the resulting coefficients are stored in the corresponding columns of a 2-D return. The fitted polynomial(s) are in the form .. math:: p(x) = c_0 + c_1 * x + ... + c_n * x^n, 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`,) x-coordinates of the `M` sample (data) points ``(x[i], y[i])``. y : array_like, shape (`M`,) or (`M`, `K`) y-coordinates of the sample points. Several sets of sample points sharing the same x-coordinates can be (independently) fit with one call to `polyfit` by passing in for `y` a 2-D array that contains one data set per column. deg : int Degree of the polynomial(s) to be fit. rcond : float, optional Relative condition number of the fit. Singular values smaller than `rcond`, relative to the largest singular value, will be ignored. The default value is ``len(x)*eps``, where `eps` is the relative precision of the platform's float type, about 2e-16 in most cases. full : bool, optional Switch determining the nature of the return value. When ``False`` (the default) just the coefficients are returned; when ``True``, diagnostic information from the singular value decomposition (used to solve the fit's matrix equation) 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 Returns ------- coef : ndarray, shape (`deg` + 1,) or (`deg` + 1, `K`) Polynomial coefficients ordered from low to high. If `y` was 2-D, 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`. Raises ------ RankWarning Raised if the matrix in the least-squares fit is rank deficient. The warning is only raised if `full` == False. The warnings can be turned off by: >>> import warnings >>> warnings.simplefilter('ignore', RankWarning) See Also -------- chebfit, legfit, lagfit, hermfit, hermefit polyval : Evaluates a polynomial. polyvander : Vandermonde matrix for powers. linalg.lstsq : Computes a least-squares fit from the matrix. scipy.interpolate.UnivariateSpline : Computes spline fits. Notes ----- The solution is the coefficients of the polynomial `p` that minimizes the sum of the weighted squared errors .. math :: E = \\sum_j w_j^2 * |y_j - p(x_j)|^2, where the :math:`w_j` are the weights. This problem is solved by setting up the (typically) over-determined matrix equation: .. math :: V(x) * c = w * y, where `V` is the weighted pseudo Vandermonde matrix of `x`, `c` are the coefficients to be solved for, `w` are the weights, and `y` are the observed values. This equation is then solved using the singular value decomposition of `V`. If some of the singular values of `V` are so small that they are neglected (and `full` == ``False``), a `RankWarning` will be raised. This means that the coefficient values may be poorly determined. Fitting to a lower order polynomial will usually get rid of the warning (but may not be what you want, of course; if you have independent reason(s) for choosing the degree which isn't working, you may have to: a) reconsider those reasons, and/or b) reconsider the quality of your data). The `rcond` parameter can also be set to a value smaller than its default, but the resulting fit may be spurious and have large contributions from roundoff error. Polynomial fits using double precision tend to "fail" at about (polynomial) degree 20. Fits using Chebyshev or Legendre series are generally better conditioned, but much can still depend on the distribution of the sample points and the smoothness of the data. If the quality of the fit is inadequate, splines may be a good alternative. Examples -------- >>> from numpy 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) >>> c # c[0], c[2] should be approx. 0, c[1] approx. -1, c[3] approx. 1 array([ 0.01909725, -1.30598256, -0.00577963, 1.02644286]) >>> stats # note the large SSR, explaining the rather poor results [array([ 38.06116253]), 4, array([ 1.38446749, 1.32119158, 0.50443316, 0.28853036]), 1.1324274851176597e-014] Same thing without the added noise >>> y = x**3 - x >>> c, stats = P.polyfit(x,y,3,full=True) >>> c # c[0], c[2] should be "very close to 0", c[1] ~= -1, c[3] ~= 1 array([ -1.73362882e-17, -1.00000000e+00, -2.67471909e-16, 1.00000000e+00]) >>> stats # note the minuscule SSR [array([ 7.46346754e-31]), 4, array([ 1.38446749, 1.32119158, 0.50443316, 0.28853036]), 1.1324274851176597e-014] """ order = int(deg) + 1 x = np.asarray(x) + 0.0 y = np.asarray(y) + 0.0 # check arguments. if deg < 0 : raise ValueError("expected deg >= 0") if x.ndim != 1: raise TypeError("expected 1D vector for x") if x.size == 0: raise TypeError("expected non-empty vector for x") if y.ndim < 1 or y.ndim > 2 : raise TypeError("expected 1D or 2D array for y") if len(x) != len(y): raise TypeError("expected x and y to have same length") # set up the least squares matrices in transposed form lhs = polyvander(x, deg).T rhs = y.T if w is not None: w = np.asarray(w) + 0.0 if w.ndim != 1: raise TypeError("expected 1D vector for w") if len(x) != len(w): raise TypeError("expected x and w to have same length") # apply weights. Don't use inplace operations as they # can cause problems with NA. lhs = lhs * w rhs = rhs * w # set rcond if rcond is None : rcond = len(x)*np.finfo(x.dtype).eps # Determine the norms of the design matrix columns. if issubclass(lhs.dtype.type, np.complexfloating): scl = np.sqrt((np.square(lhs.real) + np.square(lhs.imag)).sum(1)) else: scl = np.sqrt(np.square(lhs).sum(1)) scl[scl == 0] = 1 # Solve the least squares problem. c, resids, rank, s = la.lstsq(lhs.T/scl, rhs.T, rcond) c = (c.T/scl).T # warn on rank reduction if rank != order and not full: msg = "The fit may be poorly conditioned" warnings.warn(msg, pu.RankWarning) if full : return c, [resids, rank, s, rcond] else : return c def polycompanion(c): """ Return the companion matrix of c. The companion matrix for power series cannot be made symmetric by scaling the basis, so this function differs from those for the orthogonal polynomials. Parameters ---------- c : array_like 1-D array of polynomial coefficients ordered from low to high degree. Returns ------- mat : ndarray Companion matrix of dimensions (deg, deg). Notes ----- .. versionadded:: 1.7.0 """ # c is a trimmed copy [c] = pu.as_series([c]) if len(c) < 2 : raise ValueError('Series must have maximum degree of at least 1.') if len(c) == 2: return np.array([[-c[0]/c[1]]]) n = len(c) - 1 mat = np.zeros((n, n), dtype=c.dtype) bot = mat.reshape(-1)[n::n+1] bot[...] = 1 mat[:, -1] -= c[:-1]/c[-1] return mat def polyroots(c): """ Compute the roots of a polynomial. Return the roots (a.k.a. "zeros") of the polynomial .. math:: p(x) = \\sum_i c[i] * x^i. Parameters ---------- c : 1-D array_like 1-D array of polynomial coefficients. Returns ------- out : ndarray Array of the roots of the polynomial. If all the roots are real, then `out` is also real, otherwise it is complex. See Also -------- chebroots Notes ----- The root estimates are obtained as the eigenvalues of the companion matrix, Roots far from the origin of the complex plane may have large errors due to the numerical instability of the power series for such values. Roots with multiplicity greater than 1 will also show larger errors as the value of the series near such points is relatively insensitive to errors in the roots. Isolated roots near the origin can be improved by a few iterations of Newton's method. Examples -------- >>> import numpy.polynomial.polynomial as poly >>> poly.polyroots(poly.polyfromroots((-1,0,1))) array([-1., 0., 1.]) >>> poly.polyroots(poly.polyfromroots((-1,0,1))).dtype dtype('float64') >>> j = complex(0,1) >>> poly.polyroots(poly.polyfromroots((-j,0,j))) array([ 0.00000000e+00+0.j, 0.00000000e+00+1.j, 2.77555756e-17-1.j]) """ # c is a trimmed copy [c] = pu.as_series([c]) if len(c) < 2: return np.array([], dtype=c.dtype) if len(c) == 2: return np.array([-c[0]/c[1]]) m = polycompanion(c) r = la.eigvals(m) r.sort() return r # # polynomial class # exec(polytemplate.substitute(name='Polynomial', nick='poly', domain='[-1,1]')) numpy-1.8.2/numpy/polynomial/polyutils.py0000664000175100017510000002526012370216243022002 0ustar vagrantvagrant00000000000000""" Utililty objects 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." Warning objects --------------- - `RankWarning` -- raised by a least-squares fit when a rank-deficient matrix is encountered. Base class ---------- - `PolyBase` -- The base class for the `Polynomial` and `Chebyshev` classes. 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. """ from __future__ import division, absolute_import, print_function __all__ = ['RankWarning', 'PolyError', 'PolyDomainError', 'PolyBase', 'as_series', 'trimseq', 'trimcoef', 'getdomain', 'mapdomain', 'mapparms'] import warnings import numpy as np import sys # # Warnings and Exceptions # class RankWarning(UserWarning) : """Issued by chebfit when the design matrix is rank deficient.""" pass class PolyError(Exception) : """Base class for errors in this module.""" pass class PolyDomainError(PolyError) : """Issued by the generic Poly class when two domains don't match. This is raised when an binary operation is passed Poly objects with different domains. """ pass # # Base class for all polynomial types # class PolyBase(object) : pass # # Helper functions to convert inputs to 1-D arrays # def trimseq(seq) : """Remove small Poly series coefficients. Parameters ---------- seq : sequence Sequence of Poly series coefficients. This routine fails for empty sequences. Returns ------- series : sequence Subsequence with trailing zeros removed. If the resulting sequence would be empty, return the first element. The returned sequence may or may not be a view. Notes ----- Do not lose the type info if the sequence contains unknown objects. """ if len(seq) == 0 : return seq else : for i in range(len(seq) - 1, -1, -1) : if seq[i] != 0 : break return seq[:i+1] def as_series(alist, trim=True) : """ Return argument as a list of 1-d arrays. The returned list contains array(s) of dtype double, complex double, or object. A 1-d argument of shape ``(N,)`` is parsed into ``N`` arrays of size one; a 2-d argument of shape ``(M,N)`` is parsed into ``M`` arrays of size ``N`` (i.e., is "parsed by row"); and a higher dimensional array raises a Value Error if it is not first reshaped into either a 1-d or 2-d array. Parameters ---------- a : array_like A 1- or 2-d array_like trim : boolean, optional When True, trailing zeros are removed from the inputs. When False, the inputs are passed through intact. Returns ------- [a1, a2,...] : list of 1-D arrays A copy of the input data as a list of 1-d arrays. Raises ------ ValueError Raised when `as_series` cannot convert its input to 1-d arrays, or at least one of the resulting arrays is empty. Examples -------- >>> from numpy import polynomial as P >>> a = np.arange(4) >>> P.as_series(a) [array([ 0.]), array([ 1.]), array([ 2.]), array([ 3.])] >>> b = np.arange(6).reshape((2,3)) >>> P.as_series(b) [array([ 0., 1., 2.]), array([ 3., 4., 5.])] """ arrays = [np.array(a, ndmin=1, copy=0) for a in alist] if min([a.size for a in arrays]) == 0 : raise ValueError("Coefficient array is empty") if any([a.ndim != 1 for a in arrays]) : raise ValueError("Coefficient array is not 1-d") if trim : arrays = [trimseq(a) for a in arrays] if any([a.dtype == np.dtype(object) for a in arrays]) : ret = [] for a in arrays : if a.dtype != np.dtype(object) : tmp = np.empty(len(a), dtype=np.dtype(object)) tmp[:] = a[:] ret.append(tmp) else : ret.append(a.copy()) else : try : dtype = np.common_type(*arrays) except : raise ValueError("Coefficient arrays have no common type") ret = [np.array(a, copy=1, dtype=dtype) for a in arrays] return ret def trimcoef(c, tol=0) : """ Remove "small" "trailing" coefficients from a polynomial. "Small" means "small in absolute value" and is controlled by the parameter `tol`; "trailing" means highest order coefficient(s), e.g., in ``[0, 1, 1, 0, 0]`` (which represents ``0 + x + x**2 + 0*x**3 + 0*x**4``) both the 3-rd and 4-th order coefficients would be "trimmed." Parameters ---------- c : array_like 1-d array of coefficients, ordered from lowest order to highest. tol : number, optional Trailing (i.e., highest order) elements with absolute value less than or equal to `tol` (default value is zero) are removed. Returns ------- trimmed : ndarray 1-d array with trailing zeros removed. If the resulting series would be empty, a series containing a single zero is returned. Raises ------ ValueError If `tol` < 0 See Also -------- trimseq Examples -------- >>> from numpy import polynomial as P >>> P.trimcoef((0,0,3,0,5,0,0)) array([ 0., 0., 3., 0., 5.]) >>> P.trimcoef((0,0,1e-3,0,1e-5,0,0),1e-3) # item == tol is trimmed array([ 0.]) >>> i = complex(0,1) # works for complex >>> P.trimcoef((3e-4,1e-3*(1-i),5e-4,2e-5*(1+i)), 1e-3) array([ 0.0003+0.j , 0.0010-0.001j]) """ if tol < 0 : raise ValueError("tol must be non-negative") [c] = as_series([c]) [ind] = np.where(np.abs(c) > tol) if len(ind) == 0 : return c[:1]*0 else : return c[:ind[-1] + 1].copy() def getdomain(x) : """ Return a domain suitable for given abscissae. Find a domain suitable for a polynomial or Chebyshev series defined at the values supplied. Parameters ---------- x : array_like 1-d array of abscissae whose domain will be determined. Returns ------- domain : ndarray 1-d array containing two values. If the inputs are complex, then the two returned points are the lower left and upper right corners of the smallest rectangle (aligned with the axes) in the complex plane containing the points `x`. If the inputs are real, then the two points are the ends of the smallest interval containing the points `x`. See Also -------- mapparms, mapdomain Examples -------- >>> from numpy.polynomial import polyutils as pu >>> points = np.arange(4)**2 - 5; points array([-5, -4, -1, 4]) >>> pu.getdomain(points) array([-5., 4.]) >>> c = np.exp(complex(0,1)*np.pi*np.arange(12)/6) # unit circle >>> pu.getdomain(c) array([-1.-1.j, 1.+1.j]) """ [x] = as_series([x], trim=False) if x.dtype.char in np.typecodes['Complex'] : rmin, rmax = x.real.min(), x.real.max() imin, imax = x.imag.min(), x.imag.max() return np.array((complex(rmin, imin), complex(rmax, imax))) else : return np.array((x.min(), x.max())) def mapparms(old, new) : """ Linear map parameters between domains. Return the parameters of the linear map ``offset + scale*x`` that maps `old` to `new` such that ``old[i] -> new[i]``, ``i = 0, 1``. Parameters ---------- old, new : array_like Domains. Each domain must (successfully) convert to a 1-d array containing precisely two values. Returns ------- offset, scale : scalars The map ``L(x) = offset + scale*x`` maps the first domain to the second. See Also -------- getdomain, mapdomain Notes ----- Also works for complex numbers, and thus can be used to calculate the parameters required to map any line in the complex plane to any other line therein. Examples -------- >>> from numpy import polynomial as P >>> P.mapparms((-1,1),(-1,1)) (0.0, 1.0) >>> P.mapparms((1,-1),(-1,1)) (0.0, -1.0) >>> i = complex(0,1) >>> P.mapparms((-i,-1),(1,i)) ((1+1j), (1+0j)) """ oldlen = old[1] - old[0] newlen = new[1] - new[0] off = (old[1]*new[0] - old[0]*new[1])/oldlen scl = newlen/oldlen return off, scl def mapdomain(x, old, new) : """ Apply linear map to input points. The linear map ``offset + scale*x`` that maps the domain `old` to the domain `new` is applied to the points `x`. Parameters ---------- x : array_like Points to be mapped. If `x` is a subtype of ndarray the subtype will be preserved. old, new : array_like The two domains that determine the map. Each must (successfully) convert to 1-d arrays containing precisely two values. Returns ------- x_out : ndarray Array of points of the same shape as `x`, after application of the linear map between the two domains. See Also -------- getdomain, mapparms Notes ----- Effectively, this implements: .. math :: x\\_out = new[0] + m(x - old[0]) where .. math :: m = \\frac{new[1]-new[0]}{old[1]-old[0]} Examples -------- >>> from numpy import polynomial as P >>> old_domain = (-1,1) >>> new_domain = (0,2*np.pi) >>> x = np.linspace(-1,1,6); x array([-1. , -0.6, -0.2, 0.2, 0.6, 1. ]) >>> x_out = P.mapdomain(x, old_domain, new_domain); x_out array([ 0. , 1.25663706, 2.51327412, 3.76991118, 5.02654825, 6.28318531]) >>> x - P.mapdomain(x_out, new_domain, old_domain) array([ 0., 0., 0., 0., 0., 0.]) Also works for complex numbers (and thus can be used to map any line in the complex plane to any other line therein). >>> i = complex(0,1) >>> old = (-1 - i, 1 + i) >>> new = (-1 + i, 1 - i) >>> z = np.linspace(old[0], old[1], 6); z array([-1.0-1.j , -0.6-0.6j, -0.2-0.2j, 0.2+0.2j, 0.6+0.6j, 1.0+1.j ]) >>> new_z = P.mapdomain(z, old, new); new_z array([-1.0+1.j , -0.6+0.6j, -0.2+0.2j, 0.2-0.2j, 0.6-0.6j, 1.0-1.j ]) """ x = np.asanyarray(x) off, scl = mapparms(old, new) return off + scl*x numpy-1.8.2/numpy/polynomial/hermite_e.py0000664000175100017510000015332512370216243021703 0ustar vagrantvagrant00000000000000""" Objects for dealing with Hermite_e series. This module provides a number of objects (mostly functions) useful for dealing with Hermite_e series, including a `HermiteE` class that encapsulates the usual arithmetic operations. (General information on how this module represents and works with such polynomials is in the docstring for its "parent" sub-package, `numpy.polynomial`). Constants --------- - `hermedomain` -- Hermite_e series default domain, [-1,1]. - `hermezero` -- Hermite_e series that evaluates identically to 0. - `hermeone` -- Hermite_e series that evaluates identically to 1. - `hermex` -- Hermite_e series for the identity map, ``f(x) = x``. Arithmetic ---------- - `hermemulx` -- multiply a Hermite_e series in ``P_i(x)`` by ``x``. - `hermeadd` -- add two Hermite_e series. - `hermesub` -- subtract one Hermite_e series from another. - `hermemul` -- multiply two Hermite_e series. - `hermediv` -- divide one Hermite_e series by another. - `hermeval` -- evaluate a Hermite_e series at given points. - `hermeval2d` -- evaluate a 2D Hermite_e series at given points. - `hermeval3d` -- evaluate a 3D Hermite_e series at given points. - `hermegrid2d` -- evaluate a 2D Hermite_e series on a Cartesian product. - `hermegrid3d` -- evaluate a 3D Hermite_e series on a Cartesian product. Calculus -------- - `hermeder` -- differentiate a Hermite_e series. - `hermeint` -- integrate a Hermite_e series. Misc Functions -------------- - `hermefromroots` -- create a Hermite_e series with specified roots. - `hermeroots` -- find the roots of a Hermite_e series. - `hermevander` -- Vandermonde-like matrix for Hermite_e polynomials. - `hermevander2d` -- Vandermonde-like matrix for 2D power series. - `hermevander3d` -- Vandermonde-like matrix for 3D power series. - `hermegauss` -- Gauss-Hermite_e quadrature, points and weights. - `hermeweight` -- Hermite_e weight function. - `hermecompanion` -- symmetrized companion matrix in Hermite_e form. - `hermefit` -- least-squares fit returning a Hermite_e series. - `hermetrim` -- trim leading coefficients from a Hermite_e series. - `hermeline` -- Hermite_e series of given straight line. - `herme2poly` -- convert a Hermite_e series to a polynomial. - `poly2herme` -- convert a polynomial to a Hermite_e series. Classes ------- - `HermiteE` -- A Hermite_e series class. See also -------- `numpy.polynomial` """ from __future__ import division, absolute_import, print_function import numpy as np import numpy.linalg as la from . import polyutils as pu import warnings from .polytemplate import polytemplate __all__ = ['hermezero', 'hermeone', 'hermex', 'hermedomain', 'hermeline', 'hermeadd', 'hermesub', 'hermemulx', 'hermemul', 'hermediv', 'hermpow', 'hermeval', 'hermeder', 'hermeint', 'herme2poly', 'poly2herme', 'hermefromroots', 'hermevander', 'hermefit', 'hermetrim', 'hermeroots', 'HermiteE', 'hermeval2d', 'hermeval3d', 'hermegrid2d', 'hermegrid3d', 'hermevander2d', 'hermevander3d', 'hermecompanion', 'hermegauss', 'hermeweight'] hermetrim = pu.trimcoef def poly2herme(pol) : """ poly2herme(pol) Convert a polynomial to a Hermite series. Convert an array representing the coefficients of a polynomial (relative to the "standard" basis) ordered from lowest degree to highest, to an array of the coefficients of the equivalent Hermite series, ordered from lowest to highest degree. Parameters ---------- pol : array_like 1-D array containing the polynomial coefficients Returns ------- c : ndarray 1-D array containing the coefficients of the equivalent Hermite series. See Also -------- herme2poly Notes ----- The easy way to do conversions between polynomial basis sets is to use the convert method of a class instance. Examples -------- >>> from numpy.polynomial.hermite_e import poly2herme >>> poly2herme(np.arange(4)) array([ 2., 10., 2., 3.]) """ [pol] = pu.as_series([pol]) deg = len(pol) - 1 res = 0 for i in range(deg, -1, -1) : res = hermeadd(hermemulx(res), pol[i]) return res def herme2poly(c) : """ Convert a Hermite series to a polynomial. Convert an array representing the coefficients of a Hermite series, ordered from lowest degree to highest, to an array of the coefficients of the equivalent polynomial (relative to the "standard" basis) ordered from lowest to highest degree. Parameters ---------- c : array_like 1-D array containing the Hermite series coefficients, ordered from lowest order term to highest. Returns ------- pol : ndarray 1-D array containing the coefficients of the equivalent polynomial (relative to the "standard" basis) ordered from lowest order term to highest. See Also -------- poly2herme Notes ----- The easy way to do conversions between polynomial basis sets is to use the convert method of a class instance. Examples -------- >>> from numpy.polynomial.hermite_e import herme2poly >>> herme2poly([ 2., 10., 2., 3.]) array([ 0., 1., 2., 3.]) """ from .polynomial import polyadd, polysub, polymulx [c] = pu.as_series([c]) n = len(c) if n == 1: return c if n == 2: return c else: c0 = c[-2] c1 = c[-1] # i is the current degree of c1 for i in range(n - 1, 1, -1) : tmp = c0 c0 = polysub(c[i - 2], c1*(i - 1)) c1 = polyadd(tmp, polymulx(c1)) return polyadd(c0, polymulx(c1)) # # These are constant arrays are of integer type so as to be compatible # with the widest range of other types, such as Decimal. # # Hermite hermedomain = np.array([-1, 1]) # Hermite coefficients representing zero. hermezero = np.array([0]) # Hermite coefficients representing one. hermeone = np.array([1]) # Hermite coefficients representing the identity x. hermex = np.array([0, 1]) def hermeline(off, scl) : """ Hermite series whose graph is a straight line. Parameters ---------- off, scl : scalars The specified line is given by ``off + scl*x``. Returns ------- y : ndarray This module's representation of the Hermite series for ``off + scl*x``. See Also -------- polyline, chebline Examples -------- >>> from numpy.polynomial.hermite_e import hermeline >>> from numpy.polynomial.hermite_e import hermeline, hermeval >>> hermeval(0,hermeline(3, 2)) 3.0 >>> hermeval(1,hermeline(3, 2)) 5.0 """ if scl != 0 : return np.array([off, scl]) else : return np.array([off]) def hermefromroots(roots) : """ Generate a HermiteE series with given roots. The function returns the coefficients of the polynomial .. math:: p(x) = (x - r_0) * (x - r_1) * ... * (x - r_n), in HermiteE form, where the `r_n` are the roots specified in `roots`. If a zero has multiplicity n, then it must appear in `roots` n times. For instance, if 2 is a root of multiplicity three and 3 is a root of multiplicity 2, then `roots` looks something like [2, 2, 2, 3, 3]. The roots can appear in any order. If the returned coefficients are `c`, then .. math:: p(x) = c_0 + c_1 * He_1(x) + ... + c_n * He_n(x) The coefficient of the last term is not generally 1 for monic polynomials in HermiteE form. Parameters ---------- roots : array_like Sequence containing the roots. Returns ------- out : ndarray 1-D array of coefficients. If all roots are real then `out` is a real array, if some of the roots are complex, then `out` is complex even if all the coefficients in the result are real (see Examples below). See Also -------- polyfromroots, legfromroots, lagfromroots, hermfromroots, chebfromroots. Examples -------- >>> from numpy.polynomial.hermite_e import hermefromroots, hermeval >>> coef = hermefromroots((-1, 0, 1)) >>> hermeval((-1, 0, 1), coef) array([ 0., 0., 0.]) >>> coef = hermefromroots((-1j, 1j)) >>> hermeval((-1j, 1j), coef) array([ 0.+0.j, 0.+0.j]) """ if len(roots) == 0 : return np.ones(1) else : [roots] = pu.as_series([roots], trim=False) roots.sort() p = [hermeline(-r, 1) for r in roots] n = len(p) while n > 1: m, r = divmod(n, 2) tmp = [hermemul(p[i], p[i+m]) for i in range(m)] if r: tmp[0] = hermemul(tmp[0], p[-1]) p = tmp n = m return p[0] def hermeadd(c1, c2): """ Add one Hermite series to another. Returns the sum of two Hermite series `c1` + `c2`. The arguments are sequences of coefficients ordered from lowest order term to highest, i.e., [1,2,3] represents the series ``P_0 + 2*P_1 + 3*P_2``. Parameters ---------- c1, c2 : array_like 1-D arrays of Hermite series coefficients ordered from low to high. Returns ------- out : ndarray Array representing the Hermite series of their sum. See Also -------- hermesub, hermemul, hermediv, hermepow Notes ----- Unlike multiplication, division, etc., the sum of two Hermite series is a Hermite series (without having to "reproject" the result onto the basis set) so addition, just like that of "standard" polynomials, is simply "component-wise." Examples -------- >>> from numpy.polynomial.hermite_e import hermeadd >>> hermeadd([1, 2, 3], [1, 2, 3, 4]) array([ 2., 4., 6., 4.]) """ # c1, c2 are trimmed copies [c1, c2] = pu.as_series([c1, c2]) if len(c1) > len(c2) : c1[:c2.size] += c2 ret = c1 else : c2[:c1.size] += c1 ret = c2 return pu.trimseq(ret) def hermesub(c1, c2): """ Subtract one Hermite series from another. Returns the difference of two Hermite series `c1` - `c2`. The sequences of coefficients are from lowest order term to highest, i.e., [1,2,3] represents the series ``P_0 + 2*P_1 + 3*P_2``. Parameters ---------- c1, c2 : array_like 1-D arrays of Hermite series coefficients ordered from low to high. Returns ------- out : ndarray Of Hermite series coefficients representing their difference. See Also -------- hermeadd, hermemul, hermediv, hermepow Notes ----- Unlike multiplication, division, etc., the difference of two Hermite series is a Hermite series (without having to "reproject" the result onto the basis set) so subtraction, just like that of "standard" polynomials, is simply "component-wise." Examples -------- >>> from numpy.polynomial.hermite_e import hermesub >>> hermesub([1, 2, 3, 4], [1, 2, 3]) array([ 0., 0., 0., 4.]) """ # c1, c2 are trimmed copies [c1, c2] = pu.as_series([c1, c2]) if len(c1) > len(c2) : c1[:c2.size] -= c2 ret = c1 else : c2 = -c2 c2[:c1.size] += c1 ret = c2 return pu.trimseq(ret) def hermemulx(c): """Multiply a Hermite series by x. Multiply the Hermite series `c` by x, where x is the independent variable. Parameters ---------- c : array_like 1-D array of Hermite series coefficients ordered from low to high. Returns ------- out : ndarray Array representing the result of the multiplication. Notes ----- The multiplication uses the recursion relationship for Hermite polynomials in the form .. math:: xP_i(x) = (P_{i + 1}(x) + iP_{i - 1}(x))) Examples -------- >>> from numpy.polynomial.hermite_e import hermemulx >>> hermemulx([1, 2, 3]) array([ 2., 7., 2., 3.]) """ # c is a trimmed copy [c] = pu.as_series([c]) # The zero series needs special treatment if len(c) == 1 and c[0] == 0: return c prd = np.empty(len(c) + 1, dtype=c.dtype) prd[0] = c[0]*0 prd[1] = c[0] for i in range(1, len(c)): prd[i + 1] = c[i] prd[i - 1] += c[i]*i return prd def hermemul(c1, c2): """ Multiply one Hermite series by another. Returns the product of two Hermite series `c1` * `c2`. The arguments are sequences of coefficients, from lowest order "term" to highest, e.g., [1,2,3] represents the series ``P_0 + 2*P_1 + 3*P_2``. Parameters ---------- c1, c2 : array_like 1-D arrays of Hermite series coefficients ordered from low to high. Returns ------- out : ndarray Of Hermite series coefficients representing their product. See Also -------- hermeadd, hermesub, hermediv, hermepow Notes ----- In general, the (polynomial) product of two C-series results in terms that are not in the Hermite polynomial basis set. Thus, to express the product as a Hermite series, it is necessary to "reproject" the product onto said basis set, which may produce "unintuitive" (but correct) results; see Examples section below. Examples -------- >>> from numpy.polynomial.hermite_e import hermemul >>> hermemul([1, 2, 3], [0, 1, 2]) array([ 14., 15., 28., 7., 6.]) """ # s1, s2 are trimmed copies [c1, c2] = pu.as_series([c1, c2]) if len(c1) > len(c2): c = c2 xs = c1 else: c = c1 xs = c2 if len(c) == 1: c0 = c[0]*xs c1 = 0 elif len(c) == 2: c0 = c[0]*xs c1 = c[1]*xs else : nd = len(c) c0 = c[-2]*xs c1 = c[-1]*xs for i in range(3, len(c) + 1) : tmp = c0 nd = nd - 1 c0 = hermesub(c[-i]*xs, c1*(nd - 1)) c1 = hermeadd(tmp, hermemulx(c1)) return hermeadd(c0, hermemulx(c1)) def hermediv(c1, c2): """ Divide one Hermite series by another. Returns the quotient-with-remainder of two Hermite series `c1` / `c2`. The arguments are sequences of coefficients from lowest order "term" to highest, e.g., [1,2,3] represents the series ``P_0 + 2*P_1 + 3*P_2``. Parameters ---------- c1, c2 : array_like 1-D arrays of Hermite series coefficients ordered from low to high. Returns ------- [quo, rem] : ndarrays Of Hermite series coefficients representing the quotient and remainder. See Also -------- hermeadd, hermesub, hermemul, hermepow Notes ----- In general, the (polynomial) division of one Hermite series by another results in quotient and remainder terms that are not in the Hermite polynomial basis set. Thus, to express these results as a Hermite series, it is necessary to "reproject" the results onto the Hermite basis set, which may produce "unintuitive" (but correct) results; see Examples section below. Examples -------- >>> from numpy.polynomial.hermite_e import hermediv >>> hermediv([ 14., 15., 28., 7., 6.], [0, 1, 2]) (array([ 1., 2., 3.]), array([ 0.])) >>> hermediv([ 15., 17., 28., 7., 6.], [0, 1, 2]) (array([ 1., 2., 3.]), array([ 1., 2.])) """ # c1, c2 are trimmed copies [c1, c2] = pu.as_series([c1, c2]) if c2[-1] == 0 : raise ZeroDivisionError() lc1 = len(c1) lc2 = len(c2) if lc1 < lc2 : return c1[:1]*0, c1 elif lc2 == 1 : return c1/c2[-1], c1[:1]*0 else : quo = np.empty(lc1 - lc2 + 1, dtype=c1.dtype) rem = c1 for i in range(lc1 - lc2, - 1, -1): p = hermemul([0]*i + [1], c2) q = rem[-1]/p[-1] rem = rem[:-1] - q*p[:-1] quo[i] = q return quo, pu.trimseq(rem) def hermepow(c, pow, maxpower=16) : """Raise a Hermite series to a power. Returns the Hermite series `c` raised to the power `pow`. The argument `c` is a sequence of coefficients ordered from low to high. i.e., [1,2,3] is the series ``P_0 + 2*P_1 + 3*P_2.`` Parameters ---------- c : array_like 1-D array of Hermite series coefficients ordered from low to high. pow : integer Power to which the series will be raised maxpower : integer, optional Maximum power allowed. This is mainly to limit growth of the series to unmanageable size. Default is 16 Returns ------- coef : ndarray Hermite series of power. See Also -------- hermeadd, hermesub, hermemul, hermediv Examples -------- >>> from numpy.polynomial.hermite_e import hermepow >>> hermepow([1, 2, 3], 2) array([ 23., 28., 46., 12., 9.]) """ # c is a trimmed copy [c] = pu.as_series([c]) power = int(pow) if power != pow or power < 0 : raise ValueError("Power must be a non-negative integer.") elif maxpower is not None and power > maxpower : raise ValueError("Power is too large") elif power == 0 : return np.array([1], dtype=c.dtype) elif power == 1 : return c else : # This can be made more efficient by using powers of two # in the usual way. prd = c for i in range(2, power + 1) : prd = hermemul(prd, c) return prd def hermeder(c, m=1, scl=1, axis=0) : """ Differentiate a Hermite_e series. Returns the series coefficients `c` differentiated `m` times along `axis`. At each iteration the result is multiplied by `scl` (the scaling factor is for use in a linear change of variable). The argument `c` is an array of coefficients from low to high degree along each axis, e.g., [1,2,3] represents the series ``1*He_0 + 2*He_1 + 3*He_2`` while [[1,2],[1,2]] represents ``1*He_0(x)*He_0(y) + 1*He_1(x)*He_0(y) + 2*He_0(x)*He_1(y) + 2*He_1(x)*He_1(y)`` if axis=0 is ``x`` and axis=1 is ``y``. Parameters ---------- c : array_like Array of Hermite_e series coefficients. If `c` is multidimensional the different axis correspond to different variables with the degree in each axis given by the corresponding index. m : int, optional Number of derivatives taken, must be non-negative. (Default: 1) scl : scalar, optional Each differentiation is multiplied by `scl`. The end result is multiplication by ``scl**m``. This is for use in a linear change of variable. (Default: 1) axis : int, optional Axis over which the derivative is taken. (Default: 0). .. versionadded:: 1.7.0 Returns ------- der : ndarray Hermite series of the derivative. See Also -------- hermeint Notes ----- In general, the result of differentiating a Hermite series does not resemble the same operation on a power series. Thus the result of this function may be "unintuitive," albeit correct; see Examples section below. Examples -------- >>> from numpy.polynomial.hermite_e import hermeder >>> hermeder([ 1., 1., 1., 1.]) array([ 1., 2., 3.]) >>> hermeder([-0.25, 1., 1./2., 1./3., 1./4 ], m=2) array([ 1., 2., 3.]) """ c = np.array(c, ndmin=1, copy=1) if c.dtype.char in '?bBhHiIlLqQpP': c = c.astype(np.double) cnt, iaxis = [int(t) for t in [m, axis]] if cnt != m: raise ValueError("The order of derivation must be integer") if cnt < 0: raise ValueError("The order of derivation must be non-negative") if iaxis != axis: raise ValueError("The axis must be integer") if not -c.ndim <= iaxis < c.ndim: raise ValueError("The axis is out of range") if iaxis < 0: iaxis += c.ndim if cnt == 0: return c c = np.rollaxis(c, iaxis) n = len(c) if cnt >= n: return c[:1]*0 else : for i in range(cnt): n = n - 1 c *= scl der = np.empty((n,) + c.shape[1:], dtype=c.dtype) for j in range(n, 0, -1): der[j - 1] = j*c[j] c = der c = np.rollaxis(c, 0, iaxis + 1) return c def hermeint(c, m=1, k=[], lbnd=0, scl=1, axis=0): """ Integrate a Hermite_e series. Returns the Hermite_e series coefficients `c` integrated `m` times from `lbnd` along `axis`. At each iteration the resulting series is **multiplied** by `scl` and an integration constant, `k`, is added. The scaling factor is for use in a linear change of variable. ("Buyer beware": note that, depending on what one is doing, one may want `scl` to be the reciprocal of what one might expect; for more information, see the Notes section below.) The argument `c` is an array of coefficients from low to high degree along each axis, e.g., [1,2,3] represents the series ``H_0 + 2*H_1 + 3*H_2`` while [[1,2],[1,2]] represents ``1*H_0(x)*H_0(y) + 1*H_1(x)*H_0(y) + 2*H_0(x)*H_1(y) + 2*H_1(x)*H_1(y)`` if axis=0 is ``x`` and axis=1 is ``y``. Parameters ---------- c : array_like Array of Hermite_e series coefficients. If c is multidimensional the different axis correspond to different variables with the degree in each axis given by the corresponding index. m : int, optional Order of integration, must be positive. (Default: 1) k : {[], list, scalar}, optional Integration constant(s). The value of the first integral at ``lbnd`` is the first value in the list, the value of the second integral at ``lbnd`` is the second value, etc. If ``k == []`` (the default), all constants are set to zero. If ``m == 1``, a single scalar can be given instead of a list. lbnd : scalar, optional The lower bound of the integral. (Default: 0) scl : scalar, optional Following each integration the result is *multiplied* by `scl` before the integration constant is added. (Default: 1) axis : int, optional Axis over which the integral is taken. (Default: 0). .. versionadded:: 1.7.0 Returns ------- S : ndarray Hermite_e series coefficients of the integral. Raises ------ ValueError If ``m < 0``, ``len(k) > m``, ``np.isscalar(lbnd) == False``, or ``np.isscalar(scl) == False``. See Also -------- hermeder Notes ----- Note that the result of each integration is *multiplied* by `scl`. Why is this important to note? Say one is making a linear change of variable :math:`u = ax + b` in an integral relative to `x`. Then .. math::`dx = du/a`, so one will need to set `scl` equal to :math:`1/a` - perhaps not what one would have first thought. Also note that, in general, the result of integrating a C-series needs to be "reprojected" onto the C-series basis set. Thus, typically, the result of this function is "unintuitive," albeit correct; see Examples section below. Examples -------- >>> from numpy.polynomial.hermite_e import hermeint >>> hermeint([1, 2, 3]) # integrate once, value 0 at 0. array([ 1., 1., 1., 1.]) >>> hermeint([1, 2, 3], m=2) # integrate twice, value & deriv 0 at 0 array([-0.25 , 1. , 0.5 , 0.33333333, 0.25 ]) >>> hermeint([1, 2, 3], k=1) # integrate once, value 1 at 0. array([ 2., 1., 1., 1.]) >>> hermeint([1, 2, 3], lbnd=-1) # integrate once, value 0 at -1 array([-1., 1., 1., 1.]) >>> hermeint([1, 2, 3], m=2, k=[1, 2], lbnd=-1) array([ 1.83333333, 0. , 0.5 , 0.33333333, 0.25 ]) """ c = np.array(c, ndmin=1, copy=1) if c.dtype.char in '?bBhHiIlLqQpP': c = c.astype(np.double) if not np.iterable(k): k = [k] cnt, iaxis = [int(t) for t in [m, axis]] if cnt != m: raise ValueError("The order of integration must be integer") if cnt < 0 : raise ValueError("The order of integration must be non-negative") if len(k) > cnt : raise ValueError("Too many integration constants") if iaxis != axis: raise ValueError("The axis must be integer") if not -c.ndim <= iaxis < c.ndim: raise ValueError("The axis is out of range") if iaxis < 0: iaxis += c.ndim if cnt == 0: return c c = np.rollaxis(c, iaxis) k = list(k) + [0]*(cnt - len(k)) for i in range(cnt) : n = len(c) c *= scl if n == 1 and np.all(c[0] == 0): c[0] += k[i] else: tmp = np.empty((n + 1,) + c.shape[1:], dtype=c.dtype) tmp[0] = c[0]*0 tmp[1] = c[0] for j in range(1, n): tmp[j + 1] = c[j]/(j + 1) tmp[0] += k[i] - hermeval(lbnd, tmp) c = tmp c = np.rollaxis(c, 0, iaxis + 1) return c def hermeval(x, c, tensor=True): """ Evaluate an HermiteE series at points x. If `c` is of length `n + 1`, this function returns the value: .. math:: p(x) = c_0 * He_0(x) + c_1 * He_1(x) + ... + c_n * He_n(x) The parameter `x` is converted to an array only if it is a tuple or a list, otherwise it is treated as a scalar. In either case, either `x` or its elements must support multiplication and addition both with themselves and with the elements of `c`. If `c` is a 1-D array, then `p(x)` will have the same shape as `x`. If `c` is multidimensional, then the shape of the result depends on the value of `tensor`. If `tensor` is true the shape will be c.shape[1:] + x.shape. If `tensor` is false the shape will be c.shape[1:]. Note that scalars have shape (,). Trailing zeros in the coefficients will be used in the evaluation, so they should be avoided if efficiency is a concern. Parameters ---------- x : array_like, compatible object If `x` is a list or tuple, it is converted to an ndarray, otherwise it is left unchanged and treated as a scalar. In either case, `x` or its elements must support addition and multiplication with with themselves and with the elements of `c`. c : array_like Array of coefficients ordered so that the coefficients for terms of degree n are contained in c[n]. If `c` is multidimensional the remaining indices enumerate multiple polynomials. In the two dimensional case the coefficients may be thought of as stored in the columns of `c`. tensor : boolean, optional If True, the shape of the coefficient array is extended with ones on the right, one for each dimension of `x`. Scalars have dimension 0 for this action. The result is that every column of coefficients in `c` is evaluated for every element of `x`. If False, `x` is broadcast over the columns of `c` for the evaluation. This keyword is useful when `c` is multidimensional. The default value is True. .. versionadded:: 1.7.0 Returns ------- values : ndarray, algebra_like The shape of the return value is described above. See Also -------- hermeval2d, hermegrid2d, hermeval3d, hermegrid3d Notes ----- The evaluation uses Clenshaw recursion, aka synthetic division. Examples -------- >>> from numpy.polynomial.hermite_e import hermeval >>> coef = [1,2,3] >>> hermeval(1, coef) 3.0 >>> hermeval([[1,2],[3,4]], coef) array([[ 3., 14.], [ 31., 54.]]) """ c = np.array(c, ndmin=1, copy=0) if c.dtype.char in '?bBhHiIlLqQpP': c = c.astype(np.double) if isinstance(x, (tuple, list)): x = np.asarray(x) if isinstance(x, np.ndarray) and tensor: c = c.reshape(c.shape + (1,)*x.ndim) if len(c) == 1 : c0 = c[0] c1 = 0 elif len(c) == 2 : c0 = c[0] c1 = c[1] else : nd = len(c) c0 = c[-2] c1 = c[-1] for i in range(3, len(c) + 1) : tmp = c0 nd = nd - 1 c0 = c[-i] - c1*(nd - 1) c1 = tmp + c1*x return c0 + c1*x def hermeval2d(x, y, c): """ Evaluate a 2-D HermiteE series at points (x, y). This function returns the values: .. math:: p(x,y) = \\sum_{i,j} c_{i,j} * He_i(x) * He_j(y) The parameters `x` and `y` are converted to arrays only if they are tuples or a lists, otherwise they are treated as a scalars and they must have the same shape after conversion. In either case, either `x` and `y` or their elements must support multiplication and addition both with themselves and with the elements of `c`. If `c` is a 1-D array a one is implicitly appended to its shape to make it 2-D. The shape of the result will be c.shape[2:] + x.shape. Parameters ---------- x, y : array_like, compatible objects The two dimensional series is evaluated at the points `(x, y)`, where `x` and `y` must have the same shape. If `x` or `y` is a list or tuple, it is first converted to an ndarray, otherwise it is left unchanged and if it isn't an ndarray it is treated as a scalar. c : array_like Array of coefficients ordered so that the coefficient of the term of multi-degree i,j is contained in ``c[i,j]``. If `c` has dimension greater than two the remaining indices enumerate multiple sets of coefficients. Returns ------- values : ndarray, compatible object The values of the two dimensional polynomial at points formed with pairs of corresponding values from `x` and `y`. See Also -------- hermeval, hermegrid2d, hermeval3d, hermegrid3d Notes ----- .. versionadded::1.7.0 """ try: x, y = np.array((x, y), copy=0) except: raise ValueError('x, y are incompatible') c = hermeval(x, c) c = hermeval(y, c, tensor=False) return c def hermegrid2d(x, y, c): """ Evaluate a 2-D HermiteE series on the Cartesian product of x and y. This function returns the values: .. math:: p(a,b) = \sum_{i,j} c_{i,j} * H_i(a) * H_j(b) where the points `(a, b)` consist of all pairs formed by taking `a` from `x` and `b` from `y`. The resulting points form a grid with `x` in the first dimension and `y` in the second. The parameters `x` and `y` are converted to arrays only if they are tuples or a lists, otherwise they are treated as a scalars. In either case, either `x` and `y` or their elements must support multiplication and addition both with themselves and with the elements of `c`. If `c` has fewer than two dimensions, ones are implicitly appended to its shape to make it 2-D. The shape of the result will be c.shape[2:] + x.shape. Parameters ---------- x, y : array_like, compatible objects The two dimensional series is evaluated at the points in the Cartesian product of `x` and `y`. If `x` or `y` is a list or tuple, it is first converted to an ndarray, otherwise it is left unchanged and, if it isn't an ndarray, it is treated as a scalar. c : array_like Array of coefficients ordered so that the coefficients for terms of degree i,j are contained in ``c[i,j]``. If `c` has dimension greater than two the remaining indices enumerate multiple sets of coefficients. Returns ------- values : ndarray, compatible object The values of the two dimensional polynomial at points in the Cartesian product of `x` and `y`. See Also -------- hermeval, hermeval2d, hermeval3d, hermegrid3d Notes ----- .. versionadded::1.7.0 """ c = hermeval(x, c) c = hermeval(y, c) return c def hermeval3d(x, y, z, c): """ Evaluate a 3-D Hermite_e series at points (x, y, z). This function returns the values: .. math:: p(x,y,z) = \\sum_{i,j,k} c_{i,j,k} * He_i(x) * He_j(y) * He_k(z) The parameters `x`, `y`, and `z` are converted to arrays only if they are tuples or a lists, otherwise they are treated as a scalars and they must have the same shape after conversion. In either case, either `x`, `y`, and `z` or their elements must support multiplication and addition both with themselves and with the elements of `c`. If `c` has fewer than 3 dimensions, ones are implicitly appended to its shape to make it 3-D. The shape of the result will be c.shape[3:] + x.shape. Parameters ---------- x, y, z : array_like, compatible object The three dimensional series is evaluated at the points `(x, y, z)`, where `x`, `y`, and `z` must have the same shape. If any of `x`, `y`, or `z` is a list or tuple, it is first converted to an ndarray, otherwise it is left unchanged and if it isn't an ndarray it is treated as a scalar. c : array_like Array of coefficients ordered so that the coefficient of the term of multi-degree i,j,k is contained in ``c[i,j,k]``. If `c` has dimension greater than 3 the remaining indices enumerate multiple sets of coefficients. Returns ------- values : ndarray, compatible object The values of the multidimensional polynomial on points formed with triples of corresponding values from `x`, `y`, and `z`. See Also -------- hermeval, hermeval2d, hermegrid2d, hermegrid3d Notes ----- .. versionadded::1.7.0 """ try: x, y, z = np.array((x, y, z), copy=0) except: raise ValueError('x, y, z are incompatible') c = hermeval(x, c) c = hermeval(y, c, tensor=False) c = hermeval(z, c, tensor=False) return c def hermegrid3d(x, y, z, c): """ Evaluate a 3-D HermiteE series on the Cartesian product of x, y, and z. This function returns the values: .. math:: p(a,b,c) = \\sum_{i,j,k} c_{i,j,k} * He_i(a) * He_j(b) * He_k(c) where the points `(a, b, c)` consist of all triples formed by taking `a` from `x`, `b` from `y`, and `c` from `z`. The resulting points form a grid with `x` in the first dimension, `y` in the second, and `z` in the third. The parameters `x`, `y`, and `z` are converted to arrays only if they are tuples or a lists, otherwise they are treated as a scalars. In either case, either `x`, `y`, and `z` or their elements must support multiplication and addition both with themselves and with the elements of `c`. If `c` has fewer than three dimensions, ones are implicitly appended to its shape to make it 3-D. The shape of the result will be c.shape[3:] + x.shape + y.shape + z.shape. Parameters ---------- x, y, z : array_like, compatible objects The three dimensional series is evaluated at the points in the Cartesian product of `x`, `y`, and `z`. If `x`,`y`, or `z` is a list or tuple, it is first converted to an ndarray, otherwise it is left unchanged and, if it isn't an ndarray, it is treated as a scalar. c : array_like Array of coefficients ordered so that the coefficients for terms of degree i,j are contained in ``c[i,j]``. If `c` has dimension greater than two the remaining indices enumerate multiple sets of coefficients. Returns ------- values : ndarray, compatible object The values of the two dimensional polynomial at points in the Cartesian product of `x` and `y`. See Also -------- hermeval, hermeval2d, hermegrid2d, hermeval3d Notes ----- .. versionadded::1.7.0 """ c = hermeval(x, c) c = hermeval(y, c) c = hermeval(z, c) return c def hermevander(x, deg) : """Pseudo-Vandermonde matrix of given degree. Returns the pseudo-Vandermonde matrix of degree `deg` and sample points `x`. The pseudo-Vandermonde matrix is defined by .. math:: V[..., i] = He_i(x), where `0 <= i <= deg`. The leading indices of `V` index the elements of `x` and the last index is the degree of the HermiteE polynomial. If `c` is a 1-D array of coefficients of length `n + 1` and `V` is the array ``V = hermevander(x, n)``, then ``np.dot(V, c)`` and ``hermeval(x, c)`` are the same up to roundoff. This equivalence is useful both for least squares fitting and for the evaluation of a large number of HermiteE series of the same degree and sample points. Parameters ---------- x : array_like Array of points. The dtype is converted to float64 or complex128 depending on whether any of the elements are complex. If `x` is scalar it is converted to a 1-D array. deg : int Degree of the resulting matrix. Returns ------- vander : ndarray The pseudo-Vandermonde matrix. The shape of the returned matrix is ``x.shape + (deg + 1,)``, where The last index is the degree of the corresponding HermiteE polynomial. The dtype will be the same as the converted `x`. Examples -------- >>> from numpy.polynomial.hermite_e import hermevander >>> x = np.array([-1, 0, 1]) >>> hermevander(x, 3) array([[ 1., -1., 0., 2.], [ 1., 0., -1., -0.], [ 1., 1., 0., -2.]]) """ ideg = int(deg) if ideg != deg: raise ValueError("deg must be integer") if ideg < 0: raise ValueError("deg must be non-negative") x = np.array(x, copy=0, ndmin=1) + 0.0 dims = (ideg + 1,) + x.shape dtyp = x.dtype v = np.empty(dims, dtype=dtyp) v[0] = x*0 + 1 if ideg > 0 : v[1] = x for i in range(2, ideg + 1) : v[i] = (v[i-1]*x - v[i-2]*(i - 1)) return np.rollaxis(v, 0, v.ndim) def hermevander2d(x, y, deg) : """Pseudo-Vandermonde matrix of given degrees. Returns the pseudo-Vandermonde matrix of degrees `deg` and sample points `(x, y)`. The pseudo-Vandermonde matrix is defined by .. math:: V[..., deg[1]*i + j] = He_i(x) * He_j(y), where `0 <= i <= deg[0]` and `0 <= j <= deg[1]`. The leading indices of `V` index the points `(x, y)` and the last index encodes the degrees of the HermiteE polynomials. If ``V = hermevander2d(x, y, [xdeg, ydeg])``, then the columns of `V` correspond to the elements of a 2-D coefficient array `c` of shape (xdeg + 1, ydeg + 1) in the order .. math:: c_{00}, c_{01}, c_{02} ... , c_{10}, c_{11}, c_{12} ... and ``np.dot(V, c.flat)`` and ``hermeval2d(x, y, c)`` will be the same up to roundoff. This equivalence is useful both for least squares fitting and for the evaluation of a large number of 2-D HermiteE series of the same degrees and sample points. Parameters ---------- x, y : array_like Arrays of point coordinates, all of the same shape. The dtypes will be converted to either float64 or complex128 depending on whether any of the elements are complex. Scalars are converted to 1-D arrays. deg : list of ints List of maximum degrees of the form [x_deg, y_deg]. Returns ------- vander2d : ndarray The shape of the returned matrix is ``x.shape + (order,)``, where :math:`order = (deg[0]+1)*(deg([1]+1)`. The dtype will be the same as the converted `x` and `y`. See Also -------- hermevander, hermevander3d. hermeval2d, hermeval3d Notes ----- .. versionadded::1.7.0 """ ideg = [int(d) for d in deg] is_valid = [id == d and id >= 0 for id, d in zip(ideg, deg)] if is_valid != [1, 1]: raise ValueError("degrees must be non-negative integers") degx, degy = ideg x, y = np.array((x, y), copy=0) + 0.0 vx = hermevander(x, degx) vy = hermevander(y, degy) v = vx[..., None]*vy[..., None,:] return v.reshape(v.shape[:-2] + (-1,)) def hermevander3d(x, y, z, deg) : """Pseudo-Vandermonde matrix of given degrees. Returns the pseudo-Vandermonde matrix of degrees `deg` and sample points `(x, y, z)`. If `l, m, n` are the given degrees in `x, y, z`, then Hehe pseudo-Vandermonde matrix is defined by .. math:: V[..., (m+1)(n+1)i + (n+1)j + k] = He_i(x)*He_j(y)*He_k(z), where `0 <= i <= l`, `0 <= j <= m`, and `0 <= j <= n`. The leading indices of `V` index the points `(x, y, z)` and the last index encodes the degrees of the HermiteE polynomials. If ``V = hermevander3d(x, y, z, [xdeg, ydeg, zdeg])``, then the columns of `V` correspond to the elements of a 3-D coefficient array `c` of shape (xdeg + 1, ydeg + 1, zdeg + 1) in the order .. math:: c_{000}, c_{001}, c_{002},... , c_{010}, c_{011}, c_{012},... and ``np.dot(V, c.flat)`` and ``hermeval3d(x, y, z, c)`` will be the same up to roundoff. This equivalence is useful both for least squares fitting and for the evaluation of a large number of 3-D HermiteE series of the same degrees and sample points. Parameters ---------- x, y, z : array_like Arrays of point coordinates, all of the same shape. The dtypes will be converted to either float64 or complex128 depending on whether any of the elements are complex. Scalars are converted to 1-D arrays. deg : list of ints List of maximum degrees of the form [x_deg, y_deg, z_deg]. Returns ------- vander3d : ndarray The shape of the returned matrix is ``x.shape + (order,)``, where :math:`order = (deg[0]+1)*(deg([1]+1)*(deg[2]+1)`. The dtype will be the same as the converted `x`, `y`, and `z`. See Also -------- hermevander, hermevander3d. hermeval2d, hermeval3d Notes ----- .. versionadded::1.7.0 """ ideg = [int(d) for d in deg] is_valid = [id == d and id >= 0 for id, d in zip(ideg, deg)] if is_valid != [1, 1, 1]: raise ValueError("degrees must be non-negative integers") degx, degy, degz = ideg x, y, z = np.array((x, y, z), copy=0) + 0.0 vx = hermevander(x, degx) vy = hermevander(y, degy) vz = hermevander(z, degz) v = vx[..., None, None]*vy[..., None,:, None]*vz[..., None, None,:] return v.reshape(v.shape[:-3] + (-1,)) def hermefit(x, y, deg, rcond=None, full=False, w=None): """ Least squares fit of Hermite series to data. Return the coefficients of a HermiteE series of degree `deg` that is the least squares fit to the data values `y` given at points `x`. If `y` is 1-D the returned coefficients will also be 1-D. If `y` is 2-D multiple fits are done, one for each column of `y`, and the resulting coefficients are stored in the corresponding columns of a 2-D return. The fitted polynomial(s) are in the form .. math:: p(x) = c_0 + c_1 * He_1(x) + ... + c_n * He_n(x), 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,) 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 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. Returns ------- coef : ndarray, shape (M,) or (M, K) Hermite coefficients ordered from low to high. If `y` was 2-D, 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`. Warns ----- RankWarning The rank of the coefficient matrix in the least-squares fit is deficient. The warning is only raised if `full` = False. The warnings can be turned off by >>> import warnings >>> warnings.simplefilter('ignore', RankWarning) See Also -------- chebfit, legfit, polyfit, hermfit, polyfit hermeval : Evaluates a Hermite series. hermevander : pseudo Vandermonde matrix of Hermite series. hermeweight : HermiteE weight function. linalg.lstsq : Computes a least-squares fit from the matrix. scipy.interpolate.UnivariateSpline : Computes spline fits. Notes ----- The solution is the coefficients of the HermiteE series `p` that minimizes the sum of the weighted squared errors .. math:: E = \\sum_j w_j^2 * |y_j - p(x_j)|^2, where the :math:`w_j` are the weights. This problem is solved by setting up the (typically) overdetermined matrix equation .. math:: V(x) * c = w * y, where `V` is the pseudo Vandermonde matrix of `x`, the elements of `c` are the coefficients to be solved for, and the elements of `y` are the observed values. This equation is then solved using the singular value decomposition of `V`. If some of the singular values of `V` are so small that they are neglected, then a `RankWarning` will be issued. This means that the coefficient values may be poorly determined. Using a lower order fit will usually get rid of the warning. The `rcond` parameter can also be set to a value smaller than its default, but the resulting fit may be spurious and have large contributions from roundoff error. Fits using HermiteE series are probably most useful when the data can be approximated by ``sqrt(w(x)) * p(x)``, where `w(x)` is the HermiteE weight. In that case the weight ``sqrt(w(x[i])`` should be used together with data values ``y[i]/sqrt(w(x[i])``. The weight function is available as `hermeweight`. References ---------- .. [1] Wikipedia, "Curve fitting", http://en.wikipedia.org/wiki/Curve_fitting Examples -------- >>> from numpy.polynomial.hermite_e import hermefik, hermeval >>> x = np.linspace(-10, 10) >>> err = np.random.randn(len(x))/10 >>> y = hermeval(x, [1, 2, 3]) + err >>> hermefit(x, y, 2) array([ 1.01690445, 1.99951418, 2.99948696]) """ order = int(deg) + 1 x = np.asarray(x) + 0.0 y = np.asarray(y) + 0.0 # check arguments. if deg < 0 : raise ValueError("expected deg >= 0") if x.ndim != 1: raise TypeError("expected 1D vector for x") if x.size == 0: raise TypeError("expected non-empty vector for x") if y.ndim < 1 or y.ndim > 2 : raise TypeError("expected 1D or 2D array for y") if len(x) != len(y): raise TypeError("expected x and y to have same length") # set up the least squares matrices in transposed form lhs = hermevander(x, deg).T rhs = y.T if w is not None: w = np.asarray(w) + 0.0 if w.ndim != 1: raise TypeError("expected 1D vector for w") if len(x) != len(w): raise TypeError("expected x and w to have same length") # apply weights. Don't use inplace operations as they # can cause problems with NA. lhs = lhs * w rhs = rhs * w # set rcond if rcond is None : rcond = len(x)*np.finfo(x.dtype).eps # Determine the norms of the design matrix columns. if issubclass(lhs.dtype.type, np.complexfloating): scl = np.sqrt((np.square(lhs.real) + np.square(lhs.imag)).sum(1)) else: scl = np.sqrt(np.square(lhs).sum(1)) scl[scl == 0] = 1 # Solve the least squares problem. c, resids, rank, s = la.lstsq(lhs.T/scl, rhs.T, rcond) c = (c.T/scl).T # warn on rank reduction if rank != order and not full: msg = "The fit may be poorly conditioned" warnings.warn(msg, pu.RankWarning) if full : return c, [resids, rank, s, rcond] else : return c def hermecompanion(c): """ Return the scaled companion matrix of c. The basis polynomials are scaled so that the companion matrix is symmetric when `c` is an HermiteE basis polynomial. This provides better eigenvalue estimates than the unscaled case and for basis polynomials the eigenvalues are guaranteed to be real if `numpy.linalg.eigvalsh` is used to obtain them. Parameters ---------- c : array_like 1-D array of HermiteE series coefficients ordered from low to high degree. Returns ------- mat : ndarray Scaled companion matrix of dimensions (deg, deg). Notes ----- .. versionadded::1.7.0 """ accprod = np.multiply.accumulate # c is a trimmed copy [c] = pu.as_series([c]) if len(c) < 2: raise ValueError('Series must have maximum degree of at least 1.') if len(c) == 2: return np.array([[-c[0]/c[1]]]) n = len(c) - 1 mat = np.zeros((n, n), dtype=c.dtype) scl = np.hstack((1., np.sqrt(np.arange(1, n)))) scl = np.multiply.accumulate(scl) top = mat.reshape(-1)[1::n+1] bot = mat.reshape(-1)[n::n+1] top[...] = np.sqrt(np.arange(1, n)) bot[...] = top mat[:, -1] -= (c[:-1]/c[-1])*(scl/scl[-1]) return mat def hermeroots(c): """ Compute the roots of a HermiteE series. Return the roots (a.k.a. "zeros") of the polynomial .. math:: p(x) = \\sum_i c[i] * He_i(x). Parameters ---------- c : 1-D array_like 1-D array of coefficients. Returns ------- out : ndarray Array of the roots of the series. If all the roots are real, then `out` is also real, otherwise it is complex. See Also -------- polyroots, legroots, lagroots, hermroots, chebroots Notes ----- The root estimates are obtained as the eigenvalues of the companion matrix, Roots far from the origin of the complex plane may have large errors due to the numerical instability of the series for such values. Roots with multiplicity greater than 1 will also show larger errors as the value of the series near such points is relatively insensitive to errors in the roots. Isolated roots near the origin can be improved by a few iterations of Newton's method. The HermiteE series basis polynomials aren't powers of `x` so the results of this function may seem unintuitive. Examples -------- >>> from numpy.polynomial.hermite_e import hermeroots, hermefromroots >>> coef = hermefromroots([-1, 0, 1]) >>> coef array([ 0., 2., 0., 1.]) >>> hermeroots(coef) array([-1., 0., 1.]) """ # c is a trimmed copy [c] = pu.as_series([c]) if len(c) <= 1 : return np.array([], dtype=c.dtype) if len(c) == 2 : return np.array([-c[0]/c[1]]) m = hermecompanion(c) r = la.eigvals(m) r.sort() return r def hermegauss(deg): """ Gauss-HermiteE quadrature. Computes the sample points and weights for Gauss-HermiteE quadrature. These sample points and weights will correctly integrate polynomials of degree :math:`2*deg - 1` or less over the interval :math:`[-\inf, \inf]` with the weight function :math:`f(x) = \exp(-x^2/2)`. Parameters ---------- deg : int Number of sample points and weights. It must be >= 1. Returns ------- x : ndarray 1-D ndarray containing the sample points. y : ndarray 1-D ndarray containing the weights. Notes ----- .. versionadded::1.7.0 The results have only been tested up to degree 100, higher degrees may be problematic. The weights are determined by using the fact that .. math:: w_k = c / (He'_n(x_k) * He_{n-1}(x_k)) where :math:`c` is a constant independent of :math:`k` and :math:`x_k` is the k'th root of :math:`He_n`, and then scaling the results to get the right value when integrating 1. """ ideg = int(deg) if ideg != deg or ideg < 1: raise ValueError("deg must be a non-negative integer") # first approximation of roots. We use the fact that the companion # matrix is symmetric in this case in order to obtain better zeros. c = np.array([0]*deg + [1]) m = hermecompanion(c) x = la.eigvals(m) x.sort() # improve roots by one application of Newton dy = hermeval(x, c) df = hermeval(x, hermeder(c)) x -= dy/df # compute the weights. We scale the factor to avoid possible numerical # overflow. fm = hermeval(x, c[1:]) fm /= np.abs(fm).max() df /= np.abs(df).max() w = 1/(fm * df) # for Hermite_e we can also symmetrize w = (w + w[::-1])/2 x = (x - x[::-1])/2 # scale w to get the right value w *= np.sqrt(2*np.pi) / w.sum() return x, w def hermeweight(x): """Weight function of the Hermite_e polynomials. The weight function is :math:`\exp(-x^2/2)` and the interval of integration is :math:`[-\inf, \inf]`. the HermiteE polynomials are orthogonal, but not normalized, with respect to this weight function. Parameters ---------- x : array_like Values at which the weight function will be computed. Returns ------- w : ndarray The weight function at `x`. Notes ----- .. versionadded::1.7.0 """ w = np.exp(-.5*x**2) return w # # HermiteE series class # exec(polytemplate.substitute(name='HermiteE', nick='herme', domain='[-1,1]')) numpy-1.8.2/numpy/polynomial/legendre.py0000664000175100017510000015361612370216243021532 0ustar vagrantvagrant00000000000000""" Legendre Series (:mod: `numpy.polynomial.legendre`) =================================================== .. currentmodule:: numpy.polynomial.polynomial This module provides a number of objects (mostly functions) useful for dealing with Legendre series, including a `Legendre` class that encapsulates the usual arithmetic operations. (General information on how this module represents and works with such polynomials is in the docstring for its "parent" sub-package, `numpy.polynomial`). Constants --------- .. autosummary:: :toctree: generated/ legdomain Legendre series default domain, [-1,1]. legzero Legendre series that evaluates identically to 0. legone Legendre series that evaluates identically to 1. legx Legendre series for the identity map, ``f(x) = x``. Arithmetic ---------- .. autosummary:: :toctree: generated/ legmulx multiply a Legendre series in P_i(x) by x. legadd add two Legendre series. legsub subtract one Legendre series from another. legmul multiply two Legendre series. legdiv divide one Legendre series by another. legpow raise a Legendre series to an positive integer power legval evaluate a Legendre series at given points. legval2d evaluate a 2D Legendre series at given points. legval3d evaluate a 3D Legendre series at given points. leggrid2d evaluate a 2D Legendre series on a Cartesian product. leggrid3d evaluate a 3D Legendre series on a Cartesian product. Calculus -------- .. autosummary:: :toctree: generated/ legder differentiate a Legendre series. legint integrate a Legendre series. Misc Functions -------------- .. autosummary:: :toctree: generated/ legfromroots create a Legendre series with specified roots. legroots find the roots of a Legendre series. legvander Vandermonde-like matrix for Legendre polynomials. legvander2d Vandermonde-like matrix for 2D power series. legvander3d Vandermonde-like matrix for 3D power series. leggauss Gauss-Legendre quadrature, points and weights. legweight Legendre weight function. legcompanion symmetrized companion matrix in Legendre form. legfit least-squares fit returning a Legendre series. legtrim trim leading coefficients from a Legendre series. legline Legendre series representing given straight line. leg2poly convert a Legendre series to a polynomial. poly2leg convert a polynomial to a Legendre series. Classes ------- Legendre A Legendre series class. See also -------- numpy.polynomial.polynomial numpy.polynomial.chebyshev numpy.polynomial.laguerre numpy.polynomial.hermite numpy.polynomial.hermite_e """ from __future__ import division, absolute_import, print_function import numpy as np import numpy.linalg as la from . import polyutils as pu import warnings from .polytemplate import polytemplate __all__ = ['legzero', 'legone', 'legx', 'legdomain', 'legline', 'legadd', 'legsub', 'legmulx', 'legmul', 'legdiv', 'legpow', 'legval', 'legder', 'legint', 'leg2poly', 'poly2leg', 'legfromroots', 'legvander', 'legfit', 'legtrim', 'legroots', 'Legendre', 'legval2d', 'legval3d', 'leggrid2d', 'leggrid3d', 'legvander2d', 'legvander3d', 'legcompanion', 'leggauss', 'legweight'] legtrim = pu.trimcoef def poly2leg(pol) : """ Convert a polynomial to a Legendre series. Convert an array representing the coefficients of a polynomial (relative to the "standard" basis) ordered from lowest degree to highest, to an array of the coefficients of the equivalent Legendre series, ordered from lowest to highest degree. Parameters ---------- pol : array_like 1-D array containing the polynomial coefficients Returns ------- c : ndarray 1-D array containing the coefficients of the equivalent Legendre series. See Also -------- leg2poly Notes ----- The easy way to do conversions between polynomial basis sets is to use the convert method of a class instance. Examples -------- >>> from numpy import polynomial as P >>> p = P.Polynomial(np.arange(4)) >>> p Polynomial([ 0., 1., 2., 3.], [-1., 1.]) >>> c = P.Legendre(P.poly2leg(p.coef)) >>> c Legendre([ 1. , 3.25, 1. , 0.75], [-1., 1.]) """ [pol] = pu.as_series([pol]) deg = len(pol) - 1 res = 0 for i in range(deg, -1, -1) : res = legadd(legmulx(res), pol[i]) return res def leg2poly(c) : """ Convert a Legendre series to a polynomial. Convert an array representing the coefficients of a Legendre series, ordered from lowest degree to highest, to an array of the coefficients of the equivalent polynomial (relative to the "standard" basis) ordered from lowest to highest degree. Parameters ---------- c : array_like 1-D array containing the Legendre series coefficients, ordered from lowest order term to highest. Returns ------- pol : ndarray 1-D array containing the coefficients of the equivalent polynomial (relative to the "standard" basis) ordered from lowest order term to highest. See Also -------- poly2leg Notes ----- The easy way to do conversions between polynomial basis sets is to use the convert method of a class instance. Examples -------- >>> c = P.Legendre(range(4)) >>> c Legendre([ 0., 1., 2., 3.], [-1., 1.]) >>> p = c.convert(kind=P.Polynomial) >>> p Polynomial([-1. , -3.5, 3. , 7.5], [-1., 1.]) >>> P.leg2poly(range(4)) array([-1. , -3.5, 3. , 7.5]) """ from .polynomial import polyadd, polysub, polymulx [c] = pu.as_series([c]) n = len(c) if n < 3: return c else: c0 = c[-2] c1 = c[-1] # i is the current degree of c1 for i in range(n - 1, 1, -1) : tmp = c0 c0 = polysub(c[i - 2], (c1*(i - 1))/i) c1 = polyadd(tmp, (polymulx(c1)*(2*i - 1))/i) return polyadd(c0, polymulx(c1)) # # These are constant arrays are of integer type so as to be compatible # with the widest range of other types, such as Decimal. # # Legendre legdomain = np.array([-1, 1]) # Legendre coefficients representing zero. legzero = np.array([0]) # Legendre coefficients representing one. legone = np.array([1]) # Legendre coefficients representing the identity x. legx = np.array([0, 1]) def legline(off, scl) : """ Legendre series whose graph is a straight line. Parameters ---------- off, scl : scalars The specified line is given by ``off + scl*x``. Returns ------- y : ndarray This module's representation of the Legendre series for ``off + scl*x``. See Also -------- polyline, chebline Examples -------- >>> import numpy.polynomial.legendre as L >>> L.legline(3,2) array([3, 2]) >>> L.legval(-3, L.legline(3,2)) # should be -3 -3.0 """ if scl != 0 : return np.array([off, scl]) else : return np.array([off]) def legfromroots(roots) : """ Generate a Legendre series with given roots. The function returns the coefficients of the polynomial .. math:: p(x) = (x - r_0) * (x - r_1) * ... * (x - r_n), in Legendre form, where the `r_n` are the roots specified in `roots`. If a zero has multiplicity n, then it must appear in `roots` n times. For instance, if 2 is a root of multiplicity three and 3 is a root of multiplicity 2, then `roots` looks something like [2, 2, 2, 3, 3]. The roots can appear in any order. If the returned coefficients are `c`, then .. math:: p(x) = c_0 + c_1 * L_1(x) + ... + c_n * L_n(x) The coefficient of the last term is not generally 1 for monic polynomials in Legendre form. Parameters ---------- roots : array_like Sequence containing the roots. Returns ------- out : ndarray 1-D array of coefficients. If all roots are real then `out` is a real array, if some of the roots are complex, then `out` is complex even if all the coefficients in the result are real (see Examples below). See Also -------- polyfromroots, chebfromroots, lagfromroots, hermfromroots, hermefromroots. Examples -------- >>> import numpy.polynomial.legendre as L >>> L.legfromroots((-1,0,1)) # x^3 - x relative to the standard basis array([ 0. , -0.4, 0. , 0.4]) >>> j = complex(0,1) >>> L.legfromroots((-j,j)) # x^2 + 1 relative to the standard basis array([ 1.33333333+0.j, 0.00000000+0.j, 0.66666667+0.j]) """ if len(roots) == 0 : return np.ones(1) else : [roots] = pu.as_series([roots], trim=False) roots.sort() p = [legline(-r, 1) for r in roots] n = len(p) while n > 1: m, r = divmod(n, 2) tmp = [legmul(p[i], p[i+m]) for i in range(m)] if r: tmp[0] = legmul(tmp[0], p[-1]) p = tmp n = m return p[0] def legadd(c1, c2): """ Add one Legendre series to another. Returns the sum of two Legendre series `c1` + `c2`. The arguments are sequences of coefficients ordered from lowest order term to highest, i.e., [1,2,3] represents the series ``P_0 + 2*P_1 + 3*P_2``. Parameters ---------- c1, c2 : array_like 1-D arrays of Legendre series coefficients ordered from low to high. Returns ------- out : ndarray Array representing the Legendre series of their sum. See Also -------- legsub, legmul, legdiv, legpow Notes ----- Unlike multiplication, division, etc., the sum of two Legendre series is a Legendre series (without having to "reproject" the result onto the basis set) so addition, just like that of "standard" polynomials, is simply "component-wise." Examples -------- >>> from numpy.polynomial import legendre as L >>> c1 = (1,2,3) >>> c2 = (3,2,1) >>> L.legadd(c1,c2) array([ 4., 4., 4.]) """ # c1, c2 are trimmed copies [c1, c2] = pu.as_series([c1, c2]) if len(c1) > len(c2) : c1[:c2.size] += c2 ret = c1 else : c2[:c1.size] += c1 ret = c2 return pu.trimseq(ret) def legsub(c1, c2): """ Subtract one Legendre series from another. Returns the difference of two Legendre series `c1` - `c2`. The sequences of coefficients are from lowest order term to highest, i.e., [1,2,3] represents the series ``P_0 + 2*P_1 + 3*P_2``. Parameters ---------- c1, c2 : array_like 1-D arrays of Legendre series coefficients ordered from low to high. Returns ------- out : ndarray Of Legendre series coefficients representing their difference. See Also -------- legadd, legmul, legdiv, legpow Notes ----- Unlike multiplication, division, etc., the difference of two Legendre series is a Legendre series (without having to "reproject" the result onto the basis set) so subtraction, just like that of "standard" polynomials, is simply "component-wise." Examples -------- >>> from numpy.polynomial import legendre as L >>> c1 = (1,2,3) >>> c2 = (3,2,1) >>> L.legsub(c1,c2) array([-2., 0., 2.]) >>> L.legsub(c2,c1) # -C.legsub(c1,c2) array([ 2., 0., -2.]) """ # c1, c2 are trimmed copies [c1, c2] = pu.as_series([c1, c2]) if len(c1) > len(c2) : c1[:c2.size] -= c2 ret = c1 else : c2 = -c2 c2[:c1.size] += c1 ret = c2 return pu.trimseq(ret) def legmulx(c): """Multiply a Legendre series by x. Multiply the Legendre series `c` by x, where x is the independent variable. Parameters ---------- c : array_like 1-D array of Legendre series coefficients ordered from low to high. Returns ------- out : ndarray Array representing the result of the multiplication. Notes ----- The multiplication uses the recursion relationship for Legendre polynomials in the form .. math:: xP_i(x) = ((i + 1)*P_{i + 1}(x) + i*P_{i - 1}(x))/(2i + 1) """ # c is a trimmed copy [c] = pu.as_series([c]) # The zero series needs special treatment if len(c) == 1 and c[0] == 0: return c prd = np.empty(len(c) + 1, dtype=c.dtype) prd[0] = c[0]*0 prd[1] = c[0] for i in range(1, len(c)): j = i + 1 k = i - 1 s = i + j prd[j] = (c[i]*j)/s prd[k] += (c[i]*i)/s return prd def legmul(c1, c2): """ Multiply one Legendre series by another. Returns the product of two Legendre series `c1` * `c2`. The arguments are sequences of coefficients, from lowest order "term" to highest, e.g., [1,2,3] represents the series ``P_0 + 2*P_1 + 3*P_2``. Parameters ---------- c1, c2 : array_like 1-D arrays of Legendre series coefficients ordered from low to high. Returns ------- out : ndarray Of Legendre series coefficients representing their product. See Also -------- legadd, legsub, legdiv, legpow Notes ----- In general, the (polynomial) product of two C-series results in terms that are not in the Legendre polynomial basis set. Thus, to express the product as a Legendre series, it is necessary to "reproject" the product onto said basis set, which may produce "unintuitive" (but correct) results; see Examples section below. Examples -------- >>> from numpy.polynomial import legendre as L >>> c1 = (1,2,3) >>> c2 = (3,2) >>> P.legmul(c1,c2) # multiplication requires "reprojection" array([ 4.33333333, 10.4 , 11.66666667, 3.6 ]) """ # s1, s2 are trimmed copies [c1, c2] = pu.as_series([c1, c2]) if len(c1) > len(c2): c = c2 xs = c1 else: c = c1 xs = c2 if len(c) == 1: c0 = c[0]*xs c1 = 0 elif len(c) == 2: c0 = c[0]*xs c1 = c[1]*xs else : nd = len(c) c0 = c[-2]*xs c1 = c[-1]*xs for i in range(3, len(c) + 1) : tmp = c0 nd = nd - 1 c0 = legsub(c[-i]*xs, (c1*(nd - 1))/nd) c1 = legadd(tmp, (legmulx(c1)*(2*nd - 1))/nd) return legadd(c0, legmulx(c1)) def legdiv(c1, c2): """ Divide one Legendre series by another. Returns the quotient-with-remainder of two Legendre series `c1` / `c2`. The arguments are sequences of coefficients from lowest order "term" to highest, e.g., [1,2,3] represents the series ``P_0 + 2*P_1 + 3*P_2``. Parameters ---------- c1, c2 : array_like 1-D arrays of Legendre series coefficients ordered from low to high. Returns ------- quo, rem : ndarrays Of Legendre series coefficients representing the quotient and remainder. See Also -------- legadd, legsub, legmul, legpow Notes ----- In general, the (polynomial) division of one Legendre series by another results in quotient and remainder terms that are not in the Legendre polynomial basis set. Thus, to express these results as a Legendre series, it is necessary to "reproject" the results onto the Legendre basis set, which may produce "unintuitive" (but correct) results; see Examples section below. Examples -------- >>> from numpy.polynomial import legendre as L >>> c1 = (1,2,3) >>> c2 = (3,2,1) >>> L.legdiv(c1,c2) # quotient "intuitive," remainder not (array([ 3.]), array([-8., -4.])) >>> c2 = (0,1,2,3) >>> L.legdiv(c2,c1) # neither "intuitive" (array([-0.07407407, 1.66666667]), array([-1.03703704, -2.51851852])) """ # c1, c2 are trimmed copies [c1, c2] = pu.as_series([c1, c2]) if c2[-1] == 0 : raise ZeroDivisionError() lc1 = len(c1) lc2 = len(c2) if lc1 < lc2 : return c1[:1]*0, c1 elif lc2 == 1 : return c1/c2[-1], c1[:1]*0 else : quo = np.empty(lc1 - lc2 + 1, dtype=c1.dtype) rem = c1 for i in range(lc1 - lc2, - 1, -1): p = legmul([0]*i + [1], c2) q = rem[-1]/p[-1] rem = rem[:-1] - q*p[:-1] quo[i] = q return quo, pu.trimseq(rem) def legpow(c, pow, maxpower=16) : """Raise a Legendre series to a power. Returns the Legendre series `c` raised to the power `pow`. The arguement `c` is a sequence of coefficients ordered from low to high. i.e., [1,2,3] is the series ``P_0 + 2*P_1 + 3*P_2.`` Parameters ---------- c : array_like 1-D array of Legendre series coefficients ordered from low to high. pow : integer Power to which the series will be raised maxpower : integer, optional Maximum power allowed. This is mainly to limit growth of the series to unmanageable size. Default is 16 Returns ------- coef : ndarray Legendre series of power. See Also -------- legadd, legsub, legmul, legdiv Examples -------- """ # c is a trimmed copy [c] = pu.as_series([c]) power = int(pow) if power != pow or power < 0 : raise ValueError("Power must be a non-negative integer.") elif maxpower is not None and power > maxpower : raise ValueError("Power is too large") elif power == 0 : return np.array([1], dtype=c.dtype) elif power == 1 : return c else : # This can be made more efficient by using powers of two # in the usual way. prd = c for i in range(2, power + 1) : prd = legmul(prd, c) return prd def legder(c, m=1, scl=1, axis=0) : """ Differentiate a Legendre series. Returns the Legendre series coefficients `c` differentiated `m` times along `axis`. At each iteration the result is multiplied by `scl` (the scaling factor is for use in a linear change of variable). The argument `c` is an array of coefficients from low to high degree along each axis, e.g., [1,2,3] represents the series ``1*L_0 + 2*L_1 + 3*L_2`` while [[1,2],[1,2]] represents ``1*L_0(x)*L_0(y) + 1*L_1(x)*L_0(y) + 2*L_0(x)*L_1(y) + 2*L_1(x)*L_1(y)`` if axis=0 is ``x`` and axis=1 is ``y``. Parameters ---------- c : array_like Array of Legendre series coefficients. If c is multidimensional the different axis correspond to different variables with the degree in each axis given by the corresponding index. m : int, optional Number of derivatives taken, must be non-negative. (Default: 1) scl : scalar, optional Each differentiation is multiplied by `scl`. The end result is multiplication by ``scl**m``. This is for use in a linear change of variable. (Default: 1) axis : int, optional Axis over which the derivative is taken. (Default: 0). .. versionadded:: 1.7.0 Returns ------- der : ndarray Legendre series of the derivative. See Also -------- legint Notes ----- In general, the result of differentiating a Legendre series does not resemble the same operation on a power series. Thus the result of this function may be "unintuitive," albeit correct; see Examples section below. Examples -------- >>> from numpy.polynomial import legendre as L >>> c = (1,2,3,4) >>> L.legder(c) array([ 6., 9., 20.]) >>> L.legder(c, 3) array([ 60.]) >>> L.legder(c, scl=-1) array([ -6., -9., -20.]) >>> L.legder(c, 2,-1) array([ 9., 60.]) """ c = np.array(c, ndmin=1, copy=1) if c.dtype.char in '?bBhHiIlLqQpP': c = c.astype(np.double) cnt, iaxis = [int(t) for t in [m, axis]] if cnt != m: raise ValueError("The order of derivation must be integer") if cnt < 0: raise ValueError("The order of derivation must be non-negative") if iaxis != axis: raise ValueError("The axis must be integer") if not -c.ndim <= iaxis < c.ndim: raise ValueError("The axis is out of range") if iaxis < 0: iaxis += c.ndim if cnt == 0: return c c = np.rollaxis(c, iaxis) n = len(c) if cnt >= n: c = c[:1]*0 else : for i in range(cnt): n = n - 1 c *= scl der = np.empty((n,) + c.shape[1:], dtype=c.dtype) for j in range(n, 2, -1): der[j - 1] = (2*j - 1)*c[j] c[j - 2] += c[j] if n > 1: der[1] = 3*c[2] der[0] = c[1] c = der c = np.rollaxis(c, 0, iaxis + 1) return c def legint(c, m=1, k=[], lbnd=0, scl=1, axis=0): """ Integrate a Legendre series. Returns the Legendre series coefficients `c` integrated `m` times from `lbnd` along `axis`. At each iteration the resulting series is **multiplied** by `scl` and an integration constant, `k`, is added. The scaling factor is for use in a linear change of variable. ("Buyer beware": note that, depending on what one is doing, one may want `scl` to be the reciprocal of what one might expect; for more information, see the Notes section below.) The argument `c` is an array of coefficients from low to high degree along each axis, e.g., [1,2,3] represents the series ``L_0 + 2*L_1 + 3*L_2`` while [[1,2],[1,2]] represents ``1*L_0(x)*L_0(y) + 1*L_1(x)*L_0(y) + 2*L_0(x)*L_1(y) + 2*L_1(x)*L_1(y)`` if axis=0 is ``x`` and axis=1 is ``y``. Parameters ---------- c : array_like Array of Legendre series coefficients. If c is multidimensional the different axis correspond to different variables with the degree in each axis given by the corresponding index. m : int, optional Order of integration, must be positive. (Default: 1) k : {[], list, scalar}, optional Integration constant(s). The value of the first integral at ``lbnd`` is the first value in the list, the value of the second integral at ``lbnd`` is the second value, etc. If ``k == []`` (the default), all constants are set to zero. If ``m == 1``, a single scalar can be given instead of a list. lbnd : scalar, optional The lower bound of the integral. (Default: 0) scl : scalar, optional Following each integration the result is *multiplied* by `scl` before the integration constant is added. (Default: 1) axis : int, optional Axis over which the integral is taken. (Default: 0). .. versionadded:: 1.7.0 Returns ------- S : ndarray Legendre series coefficient array of the integral. Raises ------ ValueError If ``m < 0``, ``len(k) > m``, ``np.isscalar(lbnd) == False``, or ``np.isscalar(scl) == False``. See Also -------- legder Notes ----- Note that the result of each integration is *multiplied* by `scl`. Why is this important to note? Say one is making a linear change of variable :math:`u = ax + b` in an integral relative to `x`. Then .. math::`dx = du/a`, so one will need to set `scl` equal to :math:`1/a` - perhaps not what one would have first thought. Also note that, in general, the result of integrating a C-series needs to be "reprojected" onto the C-series basis set. Thus, typically, the result of this function is "unintuitive," albeit correct; see Examples section below. Examples -------- >>> from numpy.polynomial import legendre as L >>> c = (1,2,3) >>> L.legint(c) array([ 0.33333333, 0.4 , 0.66666667, 0.6 ]) >>> L.legint(c, 3) array([ 1.66666667e-02, -1.78571429e-02, 4.76190476e-02, -1.73472348e-18, 1.90476190e-02, 9.52380952e-03]) >>> L.legint(c, k=3) array([ 3.33333333, 0.4 , 0.66666667, 0.6 ]) >>> L.legint(c, lbnd=-2) array([ 7.33333333, 0.4 , 0.66666667, 0.6 ]) >>> L.legint(c, scl=2) array([ 0.66666667, 0.8 , 1.33333333, 1.2 ]) """ c = np.array(c, ndmin=1, copy=1) if c.dtype.char in '?bBhHiIlLqQpP': c = c.astype(np.double) if not np.iterable(k): k = [k] cnt, iaxis = [int(t) for t in [m, axis]] if cnt != m: raise ValueError("The order of integration must be integer") if cnt < 0 : raise ValueError("The order of integration must be non-negative") if len(k) > cnt : raise ValueError("Too many integration constants") if iaxis != axis: raise ValueError("The axis must be integer") if not -c.ndim <= iaxis < c.ndim: raise ValueError("The axis is out of range") if iaxis < 0: iaxis += c.ndim if cnt == 0: return c c = np.rollaxis(c, iaxis) k = list(k) + [0]*(cnt - len(k)) for i in range(cnt) : n = len(c) c *= scl if n == 1 and np.all(c[0] == 0): c[0] += k[i] else: tmp = np.empty((n + 1,) + c.shape[1:], dtype=c.dtype) tmp[0] = c[0]*0 tmp[1] = c[0] if n > 1: tmp[2] = c[1]/3 for j in range(2, n): t = c[j]/(2*j + 1) tmp[j + 1] = t tmp[j - 1] -= t tmp[0] += k[i] - legval(lbnd, tmp) c = tmp c = np.rollaxis(c, 0, iaxis + 1) return c def legval(x, c, tensor=True): """ Evaluate a Legendre series at points x. If `c` is of length `n + 1`, this function returns the value: .. math:: p(x) = c_0 * L_0(x) + c_1 * L_1(x) + ... + c_n * L_n(x) The parameter `x` is converted to an array only if it is a tuple or a list, otherwise it is treated as a scalar. In either case, either `x` or its elements must support multiplication and addition both with themselves and with the elements of `c`. If `c` is a 1-D array, then `p(x)` will have the same shape as `x`. If `c` is multidimensional, then the shape of the result depends on the value of `tensor`. If `tensor` is true the shape will be c.shape[1:] + x.shape. If `tensor` is false the shape will be c.shape[1:]. Note that scalars have shape (,). Trailing zeros in the coefficients will be used in the evaluation, so they should be avoided if efficiency is a concern. Parameters ---------- x : array_like, compatible object If `x` is a list or tuple, it is converted to an ndarray, otherwise it is left unchanged and treated as a scalar. In either case, `x` or its elements must support addition and multiplication with with themselves and with the elements of `c`. c : array_like Array of coefficients ordered so that the coefficients for terms of degree n are contained in c[n]. If `c` is multidimensional the remaining indices enumerate multiple polynomials. In the two dimensional case the coefficients may be thought of as stored in the columns of `c`. tensor : boolean, optional If True, the shape of the coefficient array is extended with ones on the right, one for each dimension of `x`. Scalars have dimension 0 for this action. The result is that every column of coefficients in `c` is evaluated for every element of `x`. If False, `x` is broadcast over the columns of `c` for the evaluation. This keyword is useful when `c` is multidimensional. The default value is True. .. versionadded:: 1.7.0 Returns ------- values : ndarray, algebra_like The shape of the return value is described above. See Also -------- legval2d, leggrid2d, legval3d, leggrid3d Notes ----- The evaluation uses Clenshaw recursion, aka synthetic division. Examples -------- """ c = np.array(c, ndmin=1, copy=0) if c.dtype.char in '?bBhHiIlLqQpP': c = c.astype(np.double) if isinstance(x, (tuple, list)): x = np.asarray(x) if isinstance(x, np.ndarray) and tensor: c = c.reshape(c.shape + (1,)*x.ndim) if len(c) == 1 : c0 = c[0] c1 = 0 elif len(c) == 2 : c0 = c[0] c1 = c[1] else : nd = len(c) c0 = c[-2] c1 = c[-1] for i in range(3, len(c) + 1) : tmp = c0 nd = nd - 1 c0 = c[-i] - (c1*(nd - 1))/nd c1 = tmp + (c1*x*(2*nd - 1))/nd return c0 + c1*x def legval2d(x, y, c): """ Evaluate a 2-D Legendre series at points (x, y). This function returns the values: .. math:: p(x,y) = \\sum_{i,j} c_{i,j} * L_i(x) * L_j(y) The parameters `x` and `y` are converted to arrays only if they are tuples or a lists, otherwise they are treated as a scalars and they must have the same shape after conversion. In either case, either `x` and `y` or their elements must support multiplication and addition both with themselves and with the elements of `c`. If `c` is a 1-D array a one is implicitly appended to its shape to make it 2-D. The shape of the result will be c.shape[2:] + x.shape. Parameters ---------- x, y : array_like, compatible objects The two dimensional series is evaluated at the points `(x, y)`, where `x` and `y` must have the same shape. If `x` or `y` is a list or tuple, it is first converted to an ndarray, otherwise it is left unchanged and if it isn't an ndarray it is treated as a scalar. c : array_like Array of coefficients ordered so that the coefficient of the term of multi-degree i,j is contained in ``c[i,j]``. If `c` has dimension greater than two the remaining indices enumerate multiple sets of coefficients. Returns ------- values : ndarray, compatible object The values of the two dimensional Legendre series at points formed from pairs of corresponding values from `x` and `y`. See Also -------- legval, leggrid2d, legval3d, leggrid3d Notes ----- .. versionadded::1.7.0 """ try: x, y = np.array((x, y), copy=0) except: raise ValueError('x, y are incompatible') c = legval(x, c) c = legval(y, c, tensor=False) return c def leggrid2d(x, y, c): """ Evaluate a 2-D Legendre series on the Cartesian product of x and y. This function returns the values: .. math:: p(a,b) = \sum_{i,j} c_{i,j} * L_i(a) * L_j(b) where the points `(a, b)` consist of all pairs formed by taking `a` from `x` and `b` from `y`. The resulting points form a grid with `x` in the first dimension and `y` in the second. The parameters `x` and `y` are converted to arrays only if they are tuples or a lists, otherwise they are treated as a scalars. In either case, either `x` and `y` or their elements must support multiplication and addition both with themselves and with the elements of `c`. If `c` has fewer than two dimensions, ones are implicitly appended to its shape to make it 2-D. The shape of the result will be c.shape[2:] + x.shape + y.shape. Parameters ---------- x, y : array_like, compatible objects The two dimensional series is evaluated at the points in the Cartesian product of `x` and `y`. If `x` or `y` is a list or tuple, it is first converted to an ndarray, otherwise it is left unchanged and, if it isn't an ndarray, it is treated as a scalar. c : array_like Array of coefficients ordered so that the coefficient of the term of multi-degree i,j is contained in `c[i,j]`. If `c` has dimension greater than two the remaining indices enumerate multiple sets of coefficients. Returns ------- values : ndarray, compatible object The values of the two dimensional Chebyshev series at points in the Cartesian product of `x` and `y`. See Also -------- legval, legval2d, legval3d, leggrid3d Notes ----- .. versionadded::1.7.0 """ c = legval(x, c) c = legval(y, c) return c def legval3d(x, y, z, c): """ Evaluate a 3-D Legendre series at points (x, y, z). This function returns the values: .. math:: p(x,y,z) = \\sum_{i,j,k} c_{i,j,k} * L_i(x) * L_j(y) * L_k(z) The parameters `x`, `y`, and `z` are converted to arrays only if they are tuples or a lists, otherwise they are treated as a scalars and they must have the same shape after conversion. In either case, either `x`, `y`, and `z` or their elements must support multiplication and addition both with themselves and with the elements of `c`. If `c` has fewer than 3 dimensions, ones are implicitly appended to its shape to make it 3-D. The shape of the result will be c.shape[3:] + x.shape. Parameters ---------- x, y, z : array_like, compatible object The three dimensional series is evaluated at the points `(x, y, z)`, where `x`, `y`, and `z` must have the same shape. If any of `x`, `y`, or `z` is a list or tuple, it is first converted to an ndarray, otherwise it is left unchanged and if it isn't an ndarray it is treated as a scalar. c : array_like Array of coefficients ordered so that the coefficient of the term of multi-degree i,j,k is contained in ``c[i,j,k]``. If `c` has dimension greater than 3 the remaining indices enumerate multiple sets of coefficients. Returns ------- values : ndarray, compatible object The values of the multidimensional polynomial on points formed with triples of corresponding values from `x`, `y`, and `z`. See Also -------- legval, legval2d, leggrid2d, leggrid3d Notes ----- .. versionadded::1.7.0 """ try: x, y, z = np.array((x, y, z), copy=0) except: raise ValueError('x, y, z are incompatible') c = legval(x, c) c = legval(y, c, tensor=False) c = legval(z, c, tensor=False) return c def leggrid3d(x, y, z, c): """ Evaluate a 3-D Legendre series on the Cartesian product of x, y, and z. This function returns the values: .. math:: p(a,b,c) = \\sum_{i,j,k} c_{i,j,k} * L_i(a) * L_j(b) * L_k(c) where the points `(a, b, c)` consist of all triples formed by taking `a` from `x`, `b` from `y`, and `c` from `z`. The resulting points form a grid with `x` in the first dimension, `y` in the second, and `z` in the third. The parameters `x`, `y`, and `z` are converted to arrays only if they are tuples or a lists, otherwise they are treated as a scalars. In either case, either `x`, `y`, and `z` or their elements must support multiplication and addition both with themselves and with the elements of `c`. If `c` has fewer than three dimensions, ones are implicitly appended to its shape to make it 3-D. The shape of the result will be c.shape[3:] + x.shape + y.shape + z.shape. Parameters ---------- x, y, z : array_like, compatible objects The three dimensional series is evaluated at the points in the Cartesian product of `x`, `y`, and `z`. If `x`,`y`, or `z` is a list or tuple, it is first converted to an ndarray, otherwise it is left unchanged and, if it isn't an ndarray, it is treated as a scalar. c : array_like Array of coefficients ordered so that the coefficients for terms of degree i,j are contained in ``c[i,j]``. If `c` has dimension greater than two the remaining indices enumerate multiple sets of coefficients. Returns ------- values : ndarray, compatible object The values of the two dimensional polynomial at points in the Cartesian product of `x` and `y`. See Also -------- legval, legval2d, leggrid2d, legval3d Notes ----- .. versionadded::1.7.0 """ c = legval(x, c) c = legval(y, c) c = legval(z, c) return c def legvander(x, deg) : """Pseudo-Vandermonde matrix of given degree. Returns the pseudo-Vandermonde matrix of degree `deg` and sample points `x`. The pseudo-Vandermonde matrix is defined by .. math:: V[..., i] = L_i(x) where `0 <= i <= deg`. The leading indices of `V` index the elements of `x` and the last index is the degree of the Legendre polynomial. If `c` is a 1-D array of coefficients of length `n + 1` and `V` is the array ``V = legvander(x, n)``, then ``np.dot(V, c)`` and ``legval(x, c)`` are the same up to roundoff. This equivalence is useful both for least squares fitting and for the evaluation of a large number of Legendre series of the same degree and sample points. Parameters ---------- x : array_like Array of points. The dtype is converted to float64 or complex128 depending on whether any of the elements are complex. If `x` is scalar it is converted to a 1-D array. deg : int Degree of the resulting matrix. Returns ------- vander : ndarray The pseudo-Vandermonde matrix. The shape of the returned matrix is ``x.shape + (deg + 1,)``, where The last index is the degree of the corresponding Legendre polynomial. The dtype will be the same as the converted `x`. """ ideg = int(deg) if ideg != deg: raise ValueError("deg must be integer") if ideg < 0: raise ValueError("deg must be non-negative") x = np.array(x, copy=0, ndmin=1) + 0.0 dims = (ideg + 1,) + x.shape dtyp = x.dtype v = np.empty(dims, dtype=dtyp) # Use forward recursion to generate the entries. This is not as accurate # as reverse recursion in this application but it is more efficient. v[0] = x*0 + 1 if ideg > 0 : v[1] = x for i in range(2, ideg + 1) : v[i] = (v[i-1]*x*(2*i - 1) - v[i-2]*(i - 1))/i return np.rollaxis(v, 0, v.ndim) def legvander2d(x, y, deg) : """Pseudo-Vandermonde matrix of given degrees. Returns the pseudo-Vandermonde matrix of degrees `deg` and sample points `(x, y)`. The pseudo-Vandermonde matrix is defined by .. math:: V[..., deg[1]*i + j] = L_i(x) * L_j(y), where `0 <= i <= deg[0]` and `0 <= j <= deg[1]`. The leading indices of `V` index the points `(x, y)` and the last index encodes the degrees of the Legendre polynomials. If ``V = legvander2d(x, y, [xdeg, ydeg])``, then the columns of `V` correspond to the elements of a 2-D coefficient array `c` of shape (xdeg + 1, ydeg + 1) in the order .. math:: c_{00}, c_{01}, c_{02} ... , c_{10}, c_{11}, c_{12} ... and ``np.dot(V, c.flat)`` and ``legval2d(x, y, c)`` will be the same up to roundoff. This equivalence is useful both for least squares fitting and for the evaluation of a large number of 2-D Legendre series of the same degrees and sample points. Parameters ---------- x, y : array_like Arrays of point coordinates, all of the same shape. The dtypes will be converted to either float64 or complex128 depending on whether any of the elements are complex. Scalars are converted to 1-D arrays. deg : list of ints List of maximum degrees of the form [x_deg, y_deg]. Returns ------- vander2d : ndarray The shape of the returned matrix is ``x.shape + (order,)``, where :math:`order = (deg[0]+1)*(deg([1]+1)`. The dtype will be the same as the converted `x` and `y`. See Also -------- legvander, legvander3d. legval2d, legval3d Notes ----- .. versionadded::1.7.0 """ ideg = [int(d) for d in deg] is_valid = [id == d and id >= 0 for id, d in zip(ideg, deg)] if is_valid != [1, 1]: raise ValueError("degrees must be non-negative integers") degx, degy = ideg x, y = np.array((x, y), copy=0) + 0.0 vx = legvander(x, degx) vy = legvander(y, degy) v = vx[..., None]*vy[..., None,:] return v.reshape(v.shape[:-2] + (-1,)) def legvander3d(x, y, z, deg) : """Pseudo-Vandermonde matrix of given degrees. Returns the pseudo-Vandermonde matrix of degrees `deg` and sample points `(x, y, z)`. If `l, m, n` are the given degrees in `x, y, z`, then The pseudo-Vandermonde matrix is defined by .. math:: V[..., (m+1)(n+1)i + (n+1)j + k] = L_i(x)*L_j(y)*L_k(z), where `0 <= i <= l`, `0 <= j <= m`, and `0 <= j <= n`. The leading indices of `V` index the points `(x, y, z)` and the last index encodes the degrees of the Legendre polynomials. If ``V = legvander3d(x, y, z, [xdeg, ydeg, zdeg])``, then the columns of `V` correspond to the elements of a 3-D coefficient array `c` of shape (xdeg + 1, ydeg + 1, zdeg + 1) in the order .. math:: c_{000}, c_{001}, c_{002},... , c_{010}, c_{011}, c_{012},... and ``np.dot(V, c.flat)`` and ``legval3d(x, y, z, c)`` will be the same up to roundoff. This equivalence is useful both for least squares fitting and for the evaluation of a large number of 3-D Legendre series of the same degrees and sample points. Parameters ---------- x, y, z : array_like Arrays of point coordinates, all of the same shape. The dtypes will be converted to either float64 or complex128 depending on whether any of the elements are complex. Scalars are converted to 1-D arrays. deg : list of ints List of maximum degrees of the form [x_deg, y_deg, z_deg]. Returns ------- vander3d : ndarray The shape of the returned matrix is ``x.shape + (order,)``, where :math:`order = (deg[0]+1)*(deg([1]+1)*(deg[2]+1)`. The dtype will be the same as the converted `x`, `y`, and `z`. See Also -------- legvander, legvander3d. legval2d, legval3d Notes ----- .. versionadded::1.7.0 """ ideg = [int(d) for d in deg] is_valid = [id == d and id >= 0 for id, d in zip(ideg, deg)] if is_valid != [1, 1, 1]: raise ValueError("degrees must be non-negative integers") degx, degy, degz = ideg x, y, z = np.array((x, y, z), copy=0) + 0.0 vx = legvander(x, degx) vy = legvander(y, degy) vz = legvander(z, degz) v = vx[..., None, None]*vy[..., None,:, None]*vz[..., None, None,:] return v.reshape(v.shape[:-3] + (-1,)) def legfit(x, y, deg, rcond=None, full=False, w=None): """ Least squares fit of Legendre series to data. Return the coefficients of a Legendre series of degree `deg` that is the least squares fit to the data values `y` given at points `x`. If `y` is 1-D the returned coefficients will also be 1-D. If `y` is 2-D multiple fits are done, one for each column of `y`, and the resulting coefficients are stored in the corresponding columns of a 2-D return. The fitted polynomial(s) are in the form .. math:: p(x) = c_0 + c_1 * L_1(x) + ... + c_n * L_n(x), 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,) 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 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 Returns ------- coef : ndarray, shape (M,) or (M, K) Legendre coefficients ordered from low to high. If `y` was 2-D, 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`. Warns ----- RankWarning The rank of the coefficient matrix in the least-squares fit is deficient. The warning is only raised if `full` = False. The warnings can be turned off by >>> import warnings >>> warnings.simplefilter('ignore', RankWarning) See Also -------- chebfit, polyfit, lagfit, hermfit, hermefit legval : Evaluates a Legendre series. legvander : Vandermonde matrix of Legendre series. legweight : Legendre weight function (= 1). linalg.lstsq : Computes a least-squares fit from the matrix. scipy.interpolate.UnivariateSpline : Computes spline fits. Notes ----- The solution is the coefficients of the Legendre series `p` that minimizes the sum of the weighted squared errors .. math:: E = \\sum_j w_j^2 * |y_j - p(x_j)|^2, where :math:`w_j` are the weights. This problem is solved by setting up as the (typically) overdetermined matrix equation .. math:: V(x) * c = w * y, where `V` is the weighted pseudo Vandermonde matrix of `x`, `c` are the coefficients to be solved for, `w` are the weights, and `y` are the observed values. This equation is then solved using the singular value decomposition of `V`. If some of the singular values of `V` are so small that they are neglected, then a `RankWarning` will be issued. This means that the coefficient values may be poorly determined. Using a lower order fit will usually get rid of the warning. The `rcond` parameter can also be set to a value smaller than its default, but the resulting fit may be spurious and have large contributions from roundoff error. Fits using Legendre series are usually better conditioned than fits using power series, but much can depend on the distribution of the sample points and the smoothness of the data. If the quality of the fit is inadequate splines may be a good alternative. References ---------- .. [1] Wikipedia, "Curve fitting", http://en.wikipedia.org/wiki/Curve_fitting Examples -------- """ order = int(deg) + 1 x = np.asarray(x) + 0.0 y = np.asarray(y) + 0.0 # check arguments. if deg < 0 : raise ValueError("expected deg >= 0") if x.ndim != 1: raise TypeError("expected 1D vector for x") if x.size == 0: raise TypeError("expected non-empty vector for x") if y.ndim < 1 or y.ndim > 2 : raise TypeError("expected 1D or 2D array for y") if len(x) != len(y): raise TypeError("expected x and y to have same length") # set up the least squares matrices in transposed form lhs = legvander(x, deg).T rhs = y.T if w is not None: w = np.asarray(w) + 0.0 if w.ndim != 1: raise TypeError("expected 1D vector for w") if len(x) != len(w): raise TypeError("expected x and w to have same length") # apply weights. Don't use inplace operations as they # can cause problems with NA. lhs = lhs * w rhs = rhs * w # set rcond if rcond is None : rcond = len(x)*np.finfo(x.dtype).eps # Determine the norms of the design matrix columns. if issubclass(lhs.dtype.type, np.complexfloating): scl = np.sqrt((np.square(lhs.real) + np.square(lhs.imag)).sum(1)) else: scl = np.sqrt(np.square(lhs).sum(1)) scl[scl == 0] = 1 # Solve the least squares problem. c, resids, rank, s = la.lstsq(lhs.T/scl, rhs.T, rcond) c = (c.T/scl).T # warn on rank reduction if rank != order and not full: msg = "The fit may be poorly conditioned" warnings.warn(msg, pu.RankWarning) if full : return c, [resids, rank, s, rcond] else : return c def legcompanion(c): """Return the scaled companion matrix of c. The basis polynomials are scaled so that the companion matrix is symmetric when `c` is an Legendre basis polynomial. This provides better eigenvalue estimates than the unscaled case and for basis polynomials the eigenvalues are guaranteed to be real if `numpy.linalg.eigvalsh` is used to obtain them. Parameters ---------- c : array_like 1-D array of Legendre series coefficients ordered from low to high degree. Returns ------- mat : ndarray Scaled companion matrix of dimensions (deg, deg). Notes ----- .. versionadded::1.7.0 """ # c is a trimmed copy [c] = pu.as_series([c]) if len(c) < 2: raise ValueError('Series must have maximum degree of at least 1.') if len(c) == 2: return np.array([[-c[0]/c[1]]]) n = len(c) - 1 mat = np.zeros((n, n), dtype=c.dtype) scl = 1./np.sqrt(2*np.arange(n) + 1) top = mat.reshape(-1)[1::n+1] bot = mat.reshape(-1)[n::n+1] top[...] = np.arange(1, n)*scl[:n-1]*scl[1:n] bot[...] = top mat[:, -1] -= (c[:-1]/c[-1])*(scl/scl[-1])*(n/(2*n - 1)) return mat def legroots(c): """ Compute the roots of a Legendre series. Return the roots (a.k.a. "zeros") of the polynomial .. math:: p(x) = \\sum_i c[i] * L_i(x). Parameters ---------- c : 1-D array_like 1-D array of coefficients. Returns ------- out : ndarray Array of the roots of the series. If all the roots are real, then `out` is also real, otherwise it is complex. See Also -------- polyroots, chebroots, lagroots, hermroots, hermeroots Notes ----- The root estimates are obtained as the eigenvalues of the companion matrix, Roots far from the origin of the complex plane may have large errors due to the numerical instability of the series for such values. Roots with multiplicity greater than 1 will also show larger errors as the value of the series near such points is relatively insensitive to errors in the roots. Isolated roots near the origin can be improved by a few iterations of Newton's method. The Legendre series basis polynomials aren't powers of ``x`` so the results of this function may seem unintuitive. Examples -------- >>> import numpy.polynomial.legendre as leg >>> leg.legroots((1, 2, 3, 4)) # 4L_3 + 3L_2 + 2L_1 + 1L_0 has only real roots array([-0.85099543, -0.11407192, 0.51506735]) """ # c is a trimmed copy [c] = pu.as_series([c]) if len(c) < 2: return np.array([], dtype=c.dtype) if len(c) == 2: return np.array([-c[0]/c[1]]) m = legcompanion(c) r = la.eigvals(m) r.sort() return r def leggauss(deg): """ Gauss-Legendre quadrature. Computes the sample points and weights for Gauss-Legendre quadrature. These sample points and weights will correctly integrate polynomials of degree :math:`2*deg - 1` or less over the interval :math:`[-1, 1]` with the weight function :math:`f(x) = 1`. Parameters ---------- deg : int Number of sample points and weights. It must be >= 1. Returns ------- x : ndarray 1-D ndarray containing the sample points. y : ndarray 1-D ndarray containing the weights. Notes ----- .. versionadded::1.7.0 The results have only been tested up to degree 100, higher degrees may be problematic. The weights are determined by using the fact that .. math:: w_k = c / (L'_n(x_k) * L_{n-1}(x_k)) where :math:`c` is a constant independent of :math:`k` and :math:`x_k` is the k'th root of :math:`L_n`, and then scaling the results to get the right value when integrating 1. """ ideg = int(deg) if ideg != deg or ideg < 1: raise ValueError("deg must be a non-negative integer") # first approximation of roots. We use the fact that the companion # matrix is symmetric in this case in order to obtain better zeros. c = np.array([0]*deg + [1]) m = legcompanion(c) x = la.eigvals(m) x.sort() # improve roots by one application of Newton dy = legval(x, c) df = legval(x, legder(c)) x -= dy/df # compute the weights. We scale the factor to avoid possible numerical # overflow. fm = legval(x, c[1:]) fm /= np.abs(fm).max() df /= np.abs(df).max() w = 1/(fm * df) # for Legendre we can also symmetrize w = (w + w[::-1])/2 x = (x - x[::-1])/2 # scale w to get the right value w *= 2. / w.sum() return x, w def legweight(x): """ Weight function of the Legendre polynomials. The weight function is :math:`1` and the interval of integration is :math:`[-1, 1]`. The Legendre polynomials are orthogonal, but not normalized, with respect to this weight function. Parameters ---------- x : array_like Values at which the weight function will be computed. Returns ------- w : ndarray The weight function at `x`. Notes ----- .. versionadded::1.7.0 """ w = x*0.0 + 1.0 return w # # Legendre series class # exec(polytemplate.substitute(name='Legendre', nick='leg', domain='[-1,1]')) numpy-1.8.2/numpy/polynomial/chebyshev.py0000664000175100017510000016677512370216243021737 0ustar vagrantvagrant00000000000000""" Objects for dealing with Chebyshev series. This module provides a number of objects (mostly functions) useful for dealing with Chebyshev series, including a `Chebyshev` class that encapsulates the usual arithmetic operations. (General information on how this module represents and works with such polynomials is in the docstring for its "parent" sub-package, `numpy.polynomial`). Constants --------- - `chebdomain` -- Chebyshev series default domain, [-1,1]. - `chebzero` -- (Coefficients of the) Chebyshev series that evaluates identically to 0. - `chebone` -- (Coefficients of the) Chebyshev series that evaluates identically to 1. - `chebx` -- (Coefficients of the) Chebyshev series for the identity map, ``f(x) = x``. Arithmetic ---------- - `chebadd` -- add two Chebyshev series. - `chebsub` -- subtract one Chebyshev series from another. - `chebmul` -- multiply two Chebyshev series. - `chebdiv` -- divide one Chebyshev series by another. - `chebpow` -- raise a Chebyshev series to an positive integer power - `chebval` -- evaluate a Chebyshev series at given points. - `chebval2d` -- evaluate a 2D Chebyshev series at given points. - `chebval3d` -- evaluate a 3D Chebyshev series at given points. - `chebgrid2d` -- evaluate a 2D Chebyshev series on a Cartesian product. - `chebgrid3d` -- evaluate a 3D Chebyshev series on a Cartesian product. Calculus -------- - `chebder` -- differentiate a Chebyshev series. - `chebint` -- integrate a Chebyshev series. Misc Functions -------------- - `chebfromroots` -- create a Chebyshev series with specified roots. - `chebroots` -- find the roots of a Chebyshev series. - `chebvander` -- Vandermonde-like matrix for Chebyshev polynomials. - `chebvander2d` -- Vandermonde-like matrix for 2D power series. - `chebvander3d` -- Vandermonde-like matrix for 3D power series. - `chebgauss` -- Gauss-Chebyshev quadrature, points and weights. - `chebweight` -- Chebyshev weight function. - `chebcompanion` -- symmetrized companion matrix in Chebyshev form. - `chebfit` -- least-squares fit returning a Chebyshev series. - `chebpts1` -- Chebyshev points of the first kind. - `chebpts2` -- Chebyshev points of the second kind. - `chebtrim` -- trim leading coefficients from a Chebyshev series. - `chebline` -- Chebyshev series representing given straight line. - `cheb2poly` -- convert a Chebyshev series to a polynomial. - `poly2cheb` -- convert a polynomial to a Chebyshev series. Classes ------- - `Chebyshev` -- A Chebyshev series class. See also -------- `numpy.polynomial` Notes ----- The implementations of multiplication, division, integration, and differentiation use the algebraic identities [1]_: .. math :: T_n(x) = \\frac{z^n + z^{-n}}{2} \\\\ z\\frac{dx}{dz} = \\frac{z - z^{-1}}{2}. where .. math :: x = \\frac{z + z^{-1}}{2}. These identities allow a Chebyshev series to be expressed as a finite, symmetric Laurent series. In this module, this sort of Laurent series is referred to as a "z-series." References ---------- .. [1] A. T. Benjamin, et al., "Combinatorial Trigonometry with Chebyshev Polynomials," *Journal of Statistical Planning and Inference 14*, 2008 (preprint: http://www.math.hmc.edu/~benjamin/papers/CombTrig.pdf, pg. 4) """ from __future__ import division, absolute_import, print_function import numpy as np import numpy.linalg as la from . import polyutils as pu import warnings from .polytemplate import polytemplate __all__ = ['chebzero', 'chebone', 'chebx', 'chebdomain', 'chebline', 'chebadd', 'chebsub', 'chebmulx', 'chebmul', 'chebdiv', 'chebpow', 'chebval', 'chebder', 'chebint', 'cheb2poly', 'poly2cheb', 'chebfromroots', 'chebvander', 'chebfit', 'chebtrim', 'chebroots', 'chebpts1', 'chebpts2', 'Chebyshev', 'chebval2d', 'chebval3d', 'chebgrid2d', 'chebgrid3d', 'chebvander2d', 'chebvander3d', 'chebcompanion', 'chebgauss', 'chebweight'] chebtrim = pu.trimcoef # # A collection of functions for manipulating z-series. These are private # functions and do minimal error checking. # def _cseries_to_zseries(c) : """Covert Chebyshev series to z-series. Covert a Chebyshev series to the equivalent z-series. The result is never an empty array. The dtype of the return is the same as that of the input. No checks are run on the arguments as this routine is for internal use. Parameters ---------- c : 1-D ndarray Chebyshev coefficients, ordered from low to high Returns ------- zs : 1-D ndarray Odd length symmetric z-series, ordered from low to high. """ n = c.size zs = np.zeros(2*n-1, dtype=c.dtype) zs[n-1:] = c/2 return zs + zs[::-1] def _zseries_to_cseries(zs) : """Covert z-series to a Chebyshev series. Covert a z series to the equivalent Chebyshev series. The result is never an empty array. The dtype of the return is the same as that of the input. No checks are run on the arguments as this routine is for internal use. Parameters ---------- zs : 1-D ndarray Odd length symmetric z-series, ordered from low to high. Returns ------- c : 1-D ndarray Chebyshev coefficients, ordered from low to high. """ n = (zs.size + 1)//2 c = zs[n-1:].copy() c[1:n] *= 2 return c def _zseries_mul(z1, z2) : """Multiply two z-series. Multiply two z-series to produce a z-series. Parameters ---------- z1, z2 : 1-D ndarray The arrays must be 1-D but this is not checked. Returns ------- product : 1-D ndarray The product z-series. Notes ----- This is simply convolution. If symmetric/anti-symmetric z-series are denoted by S/A then the following rules apply: S*S, A*A -> S S*A, A*S -> A """ return np.convolve(z1, z2) def _zseries_div(z1, z2) : """Divide the first z-series by the second. Divide `z1` by `z2` and return the quotient and remainder as z-series. Warning: this implementation only applies when both z1 and z2 have the same symmetry, which is sufficient for present purposes. Parameters ---------- z1, z2 : 1-D ndarray The arrays must be 1-D and have the same symmetry, but this is not checked. Returns ------- (quotient, remainder) : 1-D ndarrays Quotient and remainder as z-series. Notes ----- This is not the same as polynomial division on account of the desired form of the remainder. If symmetric/anti-symmetric z-series are denoted by S/A then the following rules apply: S/S -> S,S A/A -> S,A The restriction to types of the same symmetry could be fixed but seems like unneeded generality. There is no natural form for the remainder in the case where there is no symmetry. """ z1 = z1.copy() z2 = z2.copy() len1 = len(z1) len2 = len(z2) if len2 == 1 : z1 /= z2 return z1, z1[:1]*0 elif len1 < len2 : return z1[:1]*0, z1 else : dlen = len1 - len2 scl = z2[0] z2 /= scl quo = np.empty(dlen + 1, dtype=z1.dtype) i = 0 j = dlen while i < j : r = z1[i] quo[i] = z1[i] quo[dlen - i] = r tmp = r*z2 z1[i:i+len2] -= tmp z1[j:j+len2] -= tmp i += 1 j -= 1 r = z1[i] quo[i] = r tmp = r*z2 z1[i:i+len2] -= tmp quo /= scl rem = z1[i+1:i-1+len2].copy() return quo, rem def _zseries_der(zs) : """Differentiate a z-series. The derivative is with respect to x, not z. This is achieved using the chain rule and the value of dx/dz given in the module notes. Parameters ---------- zs : z-series The z-series to differentiate. Returns ------- derivative : z-series The derivative Notes ----- The zseries for x (ns) has been multiplied by two in order to avoid using floats that are incompatible with Decimal and likely other specialized scalar types. This scaling has been compensated by multiplying the value of zs by two also so that the two cancels in the division. """ n = len(zs)//2 ns = np.array([-1, 0, 1], dtype=zs.dtype) zs *= np.arange(-n, n+1)*2 d, r = _zseries_div(zs, ns) return d def _zseries_int(zs) : """Integrate a z-series. The integral is with respect to x, not z. This is achieved by a change of variable using dx/dz given in the module notes. Parameters ---------- zs : z-series The z-series to integrate Returns ------- integral : z-series The indefinite integral Notes ----- The zseries for x (ns) has been multiplied by two in order to avoid using floats that are incompatible with Decimal and likely other specialized scalar types. This scaling has been compensated by dividing the resulting zs by two. """ n = 1 + len(zs)//2 ns = np.array([-1, 0, 1], dtype=zs.dtype) zs = _zseries_mul(zs, ns) div = np.arange(-n, n+1)*2 zs[:n] /= div[:n] zs[n+1:] /= div[n+1:] zs[n] = 0 return zs # # Chebyshev series functions # def poly2cheb(pol) : """ Convert a polynomial to a Chebyshev series. Convert an array representing the coefficients of a polynomial (relative to the "standard" basis) ordered from lowest degree to highest, to an array of the coefficients of the equivalent Chebyshev series, ordered from lowest to highest degree. Parameters ---------- pol : array_like 1-D array containing the polynomial coefficients Returns ------- c : ndarray 1-D array containing the coefficients of the equivalent Chebyshev series. See Also -------- cheb2poly Notes ----- The easy way to do conversions between polynomial basis sets is to use the convert method of a class instance. Examples -------- >>> from numpy import polynomial as P >>> p = P.Polynomial(range(4)) >>> p Polynomial([ 0., 1., 2., 3.], [-1., 1.]) >>> c = p.convert(kind=P.Chebyshev) >>> c Chebyshev([ 1. , 3.25, 1. , 0.75], [-1., 1.]) >>> P.poly2cheb(range(4)) array([ 1. , 3.25, 1. , 0.75]) """ [pol] = pu.as_series([pol]) deg = len(pol) - 1 res = 0 for i in range(deg, -1, -1) : res = chebadd(chebmulx(res), pol[i]) return res def cheb2poly(c) : """ Convert a Chebyshev series to a polynomial. Convert an array representing the coefficients of a Chebyshev series, ordered from lowest degree to highest, to an array of the coefficients of the equivalent polynomial (relative to the "standard" basis) ordered from lowest to highest degree. Parameters ---------- c : array_like 1-D array containing the Chebyshev series coefficients, ordered from lowest order term to highest. Returns ------- pol : ndarray 1-D array containing the coefficients of the equivalent polynomial (relative to the "standard" basis) ordered from lowest order term to highest. See Also -------- poly2cheb Notes ----- The easy way to do conversions between polynomial basis sets is to use the convert method of a class instance. Examples -------- >>> from numpy import polynomial as P >>> c = P.Chebyshev(range(4)) >>> c Chebyshev([ 0., 1., 2., 3.], [-1., 1.]) >>> p = c.convert(kind=P.Polynomial) >>> p Polynomial([ -2., -8., 4., 12.], [-1., 1.]) >>> P.cheb2poly(range(4)) array([ -2., -8., 4., 12.]) """ from .polynomial import polyadd, polysub, polymulx [c] = pu.as_series([c]) n = len(c) if n < 3: return c else: c0 = c[-2] c1 = c[-1] # i is the current degree of c1 for i in range(n - 1, 1, -1) : tmp = c0 c0 = polysub(c[i - 2], c1) c1 = polyadd(tmp, polymulx(c1)*2) return polyadd(c0, polymulx(c1)) # # These are constant arrays are of integer type so as to be compatible # with the widest range of other types, such as Decimal. # # Chebyshev default domain. chebdomain = np.array([-1, 1]) # Chebyshev coefficients representing zero. chebzero = np.array([0]) # Chebyshev coefficients representing one. chebone = np.array([1]) # Chebyshev coefficients representing the identity x. chebx = np.array([0, 1]) def chebline(off, scl) : """ Chebyshev series whose graph is a straight line. Parameters ---------- off, scl : scalars The specified line is given by ``off + scl*x``. Returns ------- y : ndarray This module's representation of the Chebyshev series for ``off + scl*x``. See Also -------- polyline Examples -------- >>> import numpy.polynomial.chebyshev as C >>> C.chebline(3,2) array([3, 2]) >>> C.chebval(-3, C.chebline(3,2)) # should be -3 -3.0 """ if scl != 0 : return np.array([off, scl]) else : return np.array([off]) def chebfromroots(roots) : """ Generate a Chebyshev series with given roots. The function returns the coefficients of the polynomial .. math:: p(x) = (x - r_0) * (x - r_1) * ... * (x - r_n), in Chebyshev form, where the `r_n` are the roots specified in `roots`. If a zero has multiplicity n, then it must appear in `roots` n times. For instance, if 2 is a root of multiplicity three and 3 is a root of multiplicity 2, then `roots` looks something like [2, 2, 2, 3, 3]. The roots can appear in any order. If the returned coefficients are `c`, then .. math:: p(x) = c_0 + c_1 * T_1(x) + ... + c_n * T_n(x) The coefficient of the last term is not generally 1 for monic polynomials in Chebyshev form. Parameters ---------- roots : array_like Sequence containing the roots. Returns ------- out : ndarray 1-D array of coefficients. If all roots are real then `out` is a real array, if some of the roots are complex, then `out` is complex even if all the coefficients in the result are real (see Examples below). See Also -------- polyfromroots, legfromroots, lagfromroots, hermfromroots, hermefromroots. Examples -------- >>> import numpy.polynomial.chebyshev as C >>> C.chebfromroots((-1,0,1)) # x^3 - x relative to the standard basis array([ 0. , -0.25, 0. , 0.25]) >>> j = complex(0,1) >>> C.chebfromroots((-j,j)) # x^2 + 1 relative to the standard basis array([ 1.5+0.j, 0.0+0.j, 0.5+0.j]) """ if len(roots) == 0 : return np.ones(1) else : [roots] = pu.as_series([roots], trim=False) roots.sort() p = [chebline(-r, 1) for r in roots] n = len(p) while n > 1: m, r = divmod(n, 2) tmp = [chebmul(p[i], p[i+m]) for i in range(m)] if r: tmp[0] = chebmul(tmp[0], p[-1]) p = tmp n = m return p[0] def chebadd(c1, c2): """ Add one Chebyshev series to another. Returns the sum of two Chebyshev series `c1` + `c2`. The arguments are sequences of coefficients ordered from lowest order term to highest, i.e., [1,2,3] represents the series ``T_0 + 2*T_1 + 3*T_2``. Parameters ---------- c1, c2 : array_like 1-D arrays of Chebyshev series coefficients ordered from low to high. Returns ------- out : ndarray Array representing the Chebyshev series of their sum. See Also -------- chebsub, chebmul, chebdiv, chebpow Notes ----- Unlike multiplication, division, etc., the sum of two Chebyshev series is a Chebyshev series (without having to "reproject" the result onto the basis set) so addition, just like that of "standard" polynomials, is simply "component-wise." Examples -------- >>> from numpy.polynomial import chebyshev as C >>> c1 = (1,2,3) >>> c2 = (3,2,1) >>> C.chebadd(c1,c2) array([ 4., 4., 4.]) """ # c1, c2 are trimmed copies [c1, c2] = pu.as_series([c1, c2]) if len(c1) > len(c2) : c1[:c2.size] += c2 ret = c1 else : c2[:c1.size] += c1 ret = c2 return pu.trimseq(ret) def chebsub(c1, c2): """ Subtract one Chebyshev series from another. Returns the difference of two Chebyshev series `c1` - `c2`. The sequences of coefficients are from lowest order term to highest, i.e., [1,2,3] represents the series ``T_0 + 2*T_1 + 3*T_2``. Parameters ---------- c1, c2 : array_like 1-D arrays of Chebyshev series coefficients ordered from low to high. Returns ------- out : ndarray Of Chebyshev series coefficients representing their difference. See Also -------- chebadd, chebmul, chebdiv, chebpow Notes ----- Unlike multiplication, division, etc., the difference of two Chebyshev series is a Chebyshev series (without having to "reproject" the result onto the basis set) so subtraction, just like that of "standard" polynomials, is simply "component-wise." Examples -------- >>> from numpy.polynomial import chebyshev as C >>> c1 = (1,2,3) >>> c2 = (3,2,1) >>> C.chebsub(c1,c2) array([-2., 0., 2.]) >>> C.chebsub(c2,c1) # -C.chebsub(c1,c2) array([ 2., 0., -2.]) """ # c1, c2 are trimmed copies [c1, c2] = pu.as_series([c1, c2]) if len(c1) > len(c2) : c1[:c2.size] -= c2 ret = c1 else : c2 = -c2 c2[:c1.size] += c1 ret = c2 return pu.trimseq(ret) def chebmulx(c): """Multiply a Chebyshev series by x. Multiply the polynomial `c` by x, where x is the independent variable. Parameters ---------- c : array_like 1-D array of Chebyshev series coefficients ordered from low to high. Returns ------- out : ndarray Array representing the result of the multiplication. Notes ----- .. versionadded:: 1.5.0 """ # c is a trimmed copy [c] = pu.as_series([c]) # The zero series needs special treatment if len(c) == 1 and c[0] == 0: return c prd = np.empty(len(c) + 1, dtype=c.dtype) prd[0] = c[0]*0 prd[1] = c[0] if len(c) > 1: tmp = c[1:]/2 prd[2:] = tmp prd[0:-2] += tmp return prd def chebmul(c1, c2): """ Multiply one Chebyshev series by another. Returns the product of two Chebyshev series `c1` * `c2`. The arguments are sequences of coefficients, from lowest order "term" to highest, e.g., [1,2,3] represents the series ``T_0 + 2*T_1 + 3*T_2``. Parameters ---------- c1, c2 : array_like 1-D arrays of Chebyshev series coefficients ordered from low to high. Returns ------- out : ndarray Of Chebyshev series coefficients representing their product. See Also -------- chebadd, chebsub, chebdiv, chebpow Notes ----- In general, the (polynomial) product of two C-series results in terms that are not in the Chebyshev polynomial basis set. Thus, to express the product as a C-series, it is typically necessary to "reproject" the product onto said basis set, which typically produces "unintuitive live" (but correct) results; see Examples section below. Examples -------- >>> from numpy.polynomial import chebyshev as C >>> c1 = (1,2,3) >>> c2 = (3,2,1) >>> C.chebmul(c1,c2) # multiplication requires "reprojection" array([ 6.5, 12. , 12. , 4. , 1.5]) """ # c1, c2 are trimmed copies [c1, c2] = pu.as_series([c1, c2]) z1 = _cseries_to_zseries(c1) z2 = _cseries_to_zseries(c2) prd = _zseries_mul(z1, z2) ret = _zseries_to_cseries(prd) return pu.trimseq(ret) def chebdiv(c1, c2): """ Divide one Chebyshev series by another. Returns the quotient-with-remainder of two Chebyshev series `c1` / `c2`. The arguments are sequences of coefficients from lowest order "term" to highest, e.g., [1,2,3] represents the series ``T_0 + 2*T_1 + 3*T_2``. Parameters ---------- c1, c2 : array_like 1-D arrays of Chebyshev series coefficients ordered from low to high. Returns ------- [quo, rem] : ndarrays Of Chebyshev series coefficients representing the quotient and remainder. See Also -------- chebadd, chebsub, chebmul, chebpow Notes ----- In general, the (polynomial) division of one C-series by another results in quotient and remainder terms that are not in the Chebyshev polynomial basis set. Thus, to express these results as C-series, it is typically necessary to "reproject" the results onto said basis set, which typically produces "unintuitive" (but correct) results; see Examples section below. Examples -------- >>> from numpy.polynomial import chebyshev as C >>> c1 = (1,2,3) >>> c2 = (3,2,1) >>> C.chebdiv(c1,c2) # quotient "intuitive," remainder not (array([ 3.]), array([-8., -4.])) >>> c2 = (0,1,2,3) >>> C.chebdiv(c2,c1) # neither "intuitive" (array([ 0., 2.]), array([-2., -4.])) """ # c1, c2 are trimmed copies [c1, c2] = pu.as_series([c1, c2]) if c2[-1] == 0 : raise ZeroDivisionError() lc1 = len(c1) lc2 = len(c2) if lc1 < lc2 : return c1[:1]*0, c1 elif lc2 == 1 : return c1/c2[-1], c1[:1]*0 else : z1 = _cseries_to_zseries(c1) z2 = _cseries_to_zseries(c2) quo, rem = _zseries_div(z1, z2) quo = pu.trimseq(_zseries_to_cseries(quo)) rem = pu.trimseq(_zseries_to_cseries(rem)) return quo, rem def chebpow(c, pow, maxpower=16) : """Raise a Chebyshev series to a power. Returns the Chebyshev series `c` raised to the power `pow`. The argument `c` is a sequence of coefficients ordered from low to high. i.e., [1,2,3] is the series ``T_0 + 2*T_1 + 3*T_2.`` Parameters ---------- c : array_like 1-D array of Chebyshev series coefficients ordered from low to high. pow : integer Power to which the series will be raised maxpower : integer, optional Maximum power allowed. This is mainly to limit growth of the series to unmanageable size. Default is 16 Returns ------- coef : ndarray Chebyshev series of power. See Also -------- chebadd, chebsub, chebmul, chebdiv Examples -------- """ # c is a trimmed copy [c] = pu.as_series([c]) power = int(pow) if power != pow or power < 0 : raise ValueError("Power must be a non-negative integer.") elif maxpower is not None and power > maxpower : raise ValueError("Power is too large") elif power == 0 : return np.array([1], dtype=c.dtype) elif power == 1 : return c else : # This can be made more efficient by using powers of two # in the usual way. zs = _cseries_to_zseries(c) prd = zs for i in range(2, power + 1) : prd = np.convolve(prd, zs) return _zseries_to_cseries(prd) def chebder(c, m=1, scl=1, axis=0) : """ Differentiate a Chebyshev series. Returns the Chebyshev series coefficients `c` differentiated `m` times along `axis`. At each iteration the result is multiplied by `scl` (the scaling factor is for use in a linear change of variable). The argument `c` is an array of coefficients from low to high degree along each axis, e.g., [1,2,3] represents the series ``1*T_0 + 2*T_1 + 3*T_2`` while [[1,2],[1,2]] represents ``1*T_0(x)*T_0(y) + 1*T_1(x)*T_0(y) + 2*T_0(x)*T_1(y) + 2*T_1(x)*T_1(y)`` if axis=0 is ``x`` and axis=1 is ``y``. Parameters ---------- c : array_like Array of Chebyshev series coefficients. If c is multidimensional the different axis correspond to different variables with the degree in each axis given by the corresponding index. m : int, optional Number of derivatives taken, must be non-negative. (Default: 1) scl : scalar, optional Each differentiation is multiplied by `scl`. The end result is multiplication by ``scl**m``. This is for use in a linear change of variable. (Default: 1) axis : int, optional Axis over which the derivative is taken. (Default: 0). .. versionadded:: 1.7.0 Returns ------- der : ndarray Chebyshev series of the derivative. See Also -------- chebint Notes ----- In general, the result of differentiating a C-series needs to be "reprojected" onto the C-series basis set. Thus, typically, the result of this function is "unintuitive," albeit correct; see Examples section below. Examples -------- >>> from numpy.polynomial import chebyshev as C >>> c = (1,2,3,4) >>> C.chebder(c) array([ 14., 12., 24.]) >>> C.chebder(c,3) array([ 96.]) >>> C.chebder(c,scl=-1) array([-14., -12., -24.]) >>> C.chebder(c,2,-1) array([ 12., 96.]) """ c = np.array(c, ndmin=1, copy=1) if c.dtype.char in '?bBhHiIlLqQpP': c = c.astype(np.double) cnt, iaxis = [int(t) for t in [m, axis]] if cnt != m: raise ValueError("The order of derivation must be integer") if cnt < 0: raise ValueError("The order of derivation must be non-negative") if iaxis != axis: raise ValueError("The axis must be integer") if not -c.ndim <= iaxis < c.ndim: raise ValueError("The axis is out of range") if iaxis < 0: iaxis += c.ndim if cnt == 0: return c c = np.rollaxis(c, iaxis) n = len(c) if cnt >= n: c = c[:1]*0 else: for i in range(cnt): n = n - 1 c *= scl der = np.empty((n,) + c.shape[1:], dtype=c.dtype) for j in range(n, 2, -1): der[j - 1] = (2*j)*c[j] c[j - 2] += (j*c[j])/(j - 2) if n > 1: der[1] = 4*c[2] der[0] = c[1] c = der c = np.rollaxis(c, 0, iaxis + 1) return c def chebint(c, m=1, k=[], lbnd=0, scl=1, axis=0): """ Integrate a Chebyshev series. Returns the Chebyshev series coefficients `c` integrated `m` times from `lbnd` along `axis`. At each iteration the resulting series is **multiplied** by `scl` and an integration constant, `k`, is added. The scaling factor is for use in a linear change of variable. ("Buyer beware": note that, depending on what one is doing, one may want `scl` to be the reciprocal of what one might expect; for more information, see the Notes section below.) The argument `c` is an array of coefficients from low to high degree along each axis, e.g., [1,2,3] represents the series ``T_0 + 2*T_1 + 3*T_2`` while [[1,2],[1,2]] represents ``1*T_0(x)*T_0(y) + 1*T_1(x)*T_0(y) + 2*T_0(x)*T_1(y) + 2*T_1(x)*T_1(y)`` if axis=0 is ``x`` and axis=1 is ``y``. Parameters ---------- c : array_like Array of Chebyshev series coefficients. If c is multidimensional the different axis correspond to different variables with the degree in each axis given by the corresponding index. m : int, optional Order of integration, must be positive. (Default: 1) k : {[], list, scalar}, optional Integration constant(s). The value of the first integral at zero is the first value in the list, the value of the second integral at zero is the second value, etc. If ``k == []`` (the default), all constants are set to zero. If ``m == 1``, a single scalar can be given instead of a list. lbnd : scalar, optional The lower bound of the integral. (Default: 0) scl : scalar, optional Following each integration the result is *multiplied* by `scl` before the integration constant is added. (Default: 1) axis : int, optional Axis over which the integral is taken. (Default: 0). .. versionadded:: 1.7.0 Returns ------- S : ndarray C-series coefficients of the integral. Raises ------ ValueError If ``m < 1``, ``len(k) > m``, ``np.isscalar(lbnd) == False``, or ``np.isscalar(scl) == False``. See Also -------- chebder Notes ----- Note that the result of each integration is *multiplied* by `scl`. Why is this important to note? Say one is making a linear change of variable :math:`u = ax + b` in an integral relative to `x`. Then .. math::`dx = du/a`, so one will need to set `scl` equal to :math:`1/a`- perhaps not what one would have first thought. Also note that, in general, the result of integrating a C-series needs to be "reprojected" onto the C-series basis set. Thus, typically, the result of this function is "unintuitive," albeit correct; see Examples section below. Examples -------- >>> from numpy.polynomial import chebyshev as C >>> c = (1,2,3) >>> C.chebint(c) array([ 0.5, -0.5, 0.5, 0.5]) >>> C.chebint(c,3) array([ 0.03125 , -0.1875 , 0.04166667, -0.05208333, 0.01041667, 0.00625 ]) >>> C.chebint(c, k=3) array([ 3.5, -0.5, 0.5, 0.5]) >>> C.chebint(c,lbnd=-2) array([ 8.5, -0.5, 0.5, 0.5]) >>> C.chebint(c,scl=-2) array([-1., 1., -1., -1.]) """ c = np.array(c, ndmin=1, copy=1) if c.dtype.char in '?bBhHiIlLqQpP': c = c.astype(np.double) if not np.iterable(k): k = [k] cnt, iaxis = [int(t) for t in [m, axis]] if cnt != m: raise ValueError("The order of integration must be integer") if cnt < 0 : raise ValueError("The order of integration must be non-negative") if len(k) > cnt : raise ValueError("Too many integration constants") if iaxis != axis: raise ValueError("The axis must be integer") if not -c.ndim <= iaxis < c.ndim: raise ValueError("The axis is out of range") if iaxis < 0: iaxis += c.ndim if cnt == 0: return c c = np.rollaxis(c, iaxis) k = list(k) + [0]*(cnt - len(k)) for i in range(cnt) : n = len(c) c *= scl if n == 1 and np.all(c[0] == 0): c[0] += k[i] else: tmp = np.empty((n + 1,) + c.shape[1:], dtype=c.dtype) tmp[0] = c[0]*0 tmp[1] = c[0] if n > 1: tmp[2] = c[1]/4 for j in range(2, n): t = c[j]/(2*j + 1) tmp[j + 1] = c[j]/(2*(j + 1)) tmp[j - 1] -= c[j]/(2*(j - 1)) tmp[0] += k[i] - chebval(lbnd, tmp) c = tmp c = np.rollaxis(c, 0, iaxis + 1) return c def chebval(x, c, tensor=True): """ Evaluate a Chebyshev series at points x. If `c` is of length `n + 1`, this function returns the value: .. math:: p(x) = c_0 * T_0(x) + c_1 * T_1(x) + ... + c_n * T_n(x) The parameter `x` is converted to an array only if it is a tuple or a list, otherwise it is treated as a scalar. In either case, either `x` or its elements must support multiplication and addition both with themselves and with the elements of `c`. If `c` is a 1-D array, then `p(x)` will have the same shape as `x`. If `c` is multidimensional, then the shape of the result depends on the value of `tensor`. If `tensor` is true the shape will be c.shape[1:] + x.shape. If `tensor` is false the shape will be c.shape[1:]. Note that scalars have shape (,). Trailing zeros in the coefficients will be used in the evaluation, so they should be avoided if efficiency is a concern. Parameters ---------- x : array_like, compatible object If `x` is a list or tuple, it is converted to an ndarray, otherwise it is left unchanged and treated as a scalar. In either case, `x` or its elements must support addition and multiplication with with themselves and with the elements of `c`. c : array_like Array of coefficients ordered so that the coefficients for terms of degree n are contained in c[n]. If `c` is multidimensional the remaining indices enumerate multiple polynomials. In the two dimensional case the coefficients may be thought of as stored in the columns of `c`. tensor : boolean, optional If True, the shape of the coefficient array is extended with ones on the right, one for each dimension of `x`. Scalars have dimension 0 for this action. The result is that every column of coefficients in `c` is evaluated for every element of `x`. If False, `x` is broadcast over the columns of `c` for the evaluation. This keyword is useful when `c` is multidimensional. The default value is True. .. versionadded:: 1.7.0 Returns ------- values : ndarray, algebra_like The shape of the return value is described above. See Also -------- chebval2d, chebgrid2d, chebval3d, chebgrid3d Notes ----- The evaluation uses Clenshaw recursion, aka synthetic division. Examples -------- """ c = np.array(c, ndmin=1, copy=1) if c.dtype.char in '?bBhHiIlLqQpP': c = c.astype(np.double) if isinstance(x, (tuple, list)): x = np.asarray(x) if isinstance(x, np.ndarray) and tensor: c = c.reshape(c.shape + (1,)*x.ndim) if len(c) == 1 : c0 = c[0] c1 = 0 elif len(c) == 2 : c0 = c[0] c1 = c[1] else : x2 = 2*x c0 = c[-2] c1 = c[-1] for i in range(3, len(c) + 1) : tmp = c0 c0 = c[-i] - c1 c1 = tmp + c1*x2 return c0 + c1*x def chebval2d(x, y, c): """ Evaluate a 2-D Chebyshev series at points (x, y). This function returns the values: .. math:: p(x,y) = \\sum_{i,j} c_{i,j} * T_i(x) * T_j(y) The parameters `x` and `y` are converted to arrays only if they are tuples or a lists, otherwise they are treated as a scalars and they must have the same shape after conversion. In either case, either `x` and `y` or their elements must support multiplication and addition both with themselves and with the elements of `c`. If `c` is a 1-D array a one is implicitly appended to its shape to make it 2-D. The shape of the result will be c.shape[2:] + x.shape. Parameters ---------- x, y : array_like, compatible objects The two dimensional series is evaluated at the points `(x, y)`, where `x` and `y` must have the same shape. If `x` or `y` is a list or tuple, it is first converted to an ndarray, otherwise it is left unchanged and if it isn't an ndarray it is treated as a scalar. c : array_like Array of coefficients ordered so that the coefficient of the term of multi-degree i,j is contained in ``c[i,j]``. If `c` has dimension greater than 2 the remaining indices enumerate multiple sets of coefficients. Returns ------- values : ndarray, compatible object The values of the two dimensional Chebyshev series at points formed from pairs of corresponding values from `x` and `y`. See Also -------- chebval, chebgrid2d, chebval3d, chebgrid3d Notes ----- .. versionadded::1.7.0 """ try: x, y = np.array((x, y), copy=0) except: raise ValueError('x, y are incompatible') c = chebval(x, c) c = chebval(y, c, tensor=False) return c def chebgrid2d(x, y, c): """ Evaluate a 2-D Chebyshev series on the Cartesian product of x and y. This function returns the values: .. math:: p(a,b) = \sum_{i,j} c_{i,j} * T_i(a) * T_j(b), where the points `(a, b)` consist of all pairs formed by taking `a` from `x` and `b` from `y`. The resulting points form a grid with `x` in the first dimension and `y` in the second. The parameters `x` and `y` are converted to arrays only if they are tuples or a lists, otherwise they are treated as a scalars. In either case, either `x` and `y` or their elements must support multiplication and addition both with themselves and with the elements of `c`. If `c` has fewer than two dimensions, ones are implicitly appended to its shape to make it 2-D. The shape of the result will be c.shape[2:] + x.shape + y.shape. Parameters ---------- x, y : array_like, compatible objects The two dimensional series is evaluated at the points in the Cartesian product of `x` and `y`. If `x` or `y` is a list or tuple, it is first converted to an ndarray, otherwise it is left unchanged and, if it isn't an ndarray, it is treated as a scalar. c : array_like Array of coefficients ordered so that the coefficient of the term of multi-degree i,j is contained in `c[i,j]`. If `c` has dimension greater than two the remaining indices enumerate multiple sets of coefficients. Returns ------- values : ndarray, compatible object The values of the two dimensional Chebyshev series at points in the Cartesian product of `x` and `y`. See Also -------- chebval, chebval2d, chebval3d, chebgrid3d Notes ----- .. versionadded::1.7.0 """ c = chebval(x, c) c = chebval(y, c) return c def chebval3d(x, y, z, c): """ Evaluate a 3-D Chebyshev series at points (x, y, z). This function returns the values: .. math:: p(x,y,z) = \\sum_{i,j,k} c_{i,j,k} * T_i(x) * T_j(y) * T_k(z) The parameters `x`, `y`, and `z` are converted to arrays only if they are tuples or a lists, otherwise they are treated as a scalars and they must have the same shape after conversion. In either case, either `x`, `y`, and `z` or their elements must support multiplication and addition both with themselves and with the elements of `c`. If `c` has fewer than 3 dimensions, ones are implicitly appended to its shape to make it 3-D. The shape of the result will be c.shape[3:] + x.shape. Parameters ---------- x, y, z : array_like, compatible object The three dimensional series is evaluated at the points `(x, y, z)`, where `x`, `y`, and `z` must have the same shape. If any of `x`, `y`, or `z` is a list or tuple, it is first converted to an ndarray, otherwise it is left unchanged and if it isn't an ndarray it is treated as a scalar. c : array_like Array of coefficients ordered so that the coefficient of the term of multi-degree i,j,k is contained in ``c[i,j,k]``. If `c` has dimension greater than 3 the remaining indices enumerate multiple sets of coefficients. Returns ------- values : ndarray, compatible object The values of the multidimensional polynomial on points formed with triples of corresponding values from `x`, `y`, and `z`. See Also -------- chebval, chebval2d, chebgrid2d, chebgrid3d Notes ----- .. versionadded::1.7.0 """ try: x, y, z = np.array((x, y, z), copy=0) except: raise ValueError('x, y, z are incompatible') c = chebval(x, c) c = chebval(y, c, tensor=False) c = chebval(z, c, tensor=False) return c def chebgrid3d(x, y, z, c): """ Evaluate a 3-D Chebyshev series on the Cartesian product of x, y, and z. This function returns the values: .. math:: p(a,b,c) = \\sum_{i,j,k} c_{i,j,k} * T_i(a) * T_j(b) * T_k(c) where the points `(a, b, c)` consist of all triples formed by taking `a` from `x`, `b` from `y`, and `c` from `z`. The resulting points form a grid with `x` in the first dimension, `y` in the second, and `z` in the third. The parameters `x`, `y`, and `z` are converted to arrays only if they are tuples or a lists, otherwise they are treated as a scalars. In either case, either `x`, `y`, and `z` or their elements must support multiplication and addition both with themselves and with the elements of `c`. If `c` has fewer than three dimensions, ones are implicitly appended to its shape to make it 3-D. The shape of the result will be c.shape[3:] + x.shape + y.shape + z.shape. Parameters ---------- x, y, z : array_like, compatible objects The three dimensional series is evaluated at the points in the Cartesian product of `x`, `y`, and `z`. If `x`,`y`, or `z` is a list or tuple, it is first converted to an ndarray, otherwise it is left unchanged and, if it isn't an ndarray, it is treated as a scalar. c : array_like Array of coefficients ordered so that the coefficients for terms of degree i,j are contained in ``c[i,j]``. If `c` has dimension greater than two the remaining indices enumerate multiple sets of coefficients. Returns ------- values : ndarray, compatible object The values of the two dimensional polynomial at points in the Cartesian product of `x` and `y`. See Also -------- chebval, chebval2d, chebgrid2d, chebval3d Notes ----- .. versionadded::1.7.0 """ c = chebval(x, c) c = chebval(y, c) c = chebval(z, c) return c def chebvander(x, deg) : """Pseudo-Vandermonde matrix of given degree. Returns the pseudo-Vandermonde matrix of degree `deg` and sample points `x`. The pseudo-Vandermonde matrix is defined by .. math:: V[..., i] = T_i(x), where `0 <= i <= deg`. The leading indices of `V` index the elements of `x` and the last index is the degree of the Chebyshev polynomial. If `c` is a 1-D array of coefficients of length `n + 1` and `V` is the matrix ``V = chebvander(x, n)``, then ``np.dot(V, c)`` and ``chebval(x, c)`` are the same up to roundoff. This equivalence is useful both for least squares fitting and for the evaluation of a large number of Chebyshev series of the same degree and sample points. Parameters ---------- x : array_like Array of points. The dtype is converted to float64 or complex128 depending on whether any of the elements are complex. If `x` is scalar it is converted to a 1-D array. deg : int Degree of the resulting matrix. Returns ------- vander : ndarray The pseudo Vandermonde matrix. The shape of the returned matrix is ``x.shape + (deg + 1,)``, where The last index is the degree of the corresponding Chebyshev polynomial. The dtype will be the same as the converted `x`. """ ideg = int(deg) if ideg != deg: raise ValueError("deg must be integer") if ideg < 0: raise ValueError("deg must be non-negative") x = np.array(x, copy=0, ndmin=1) + 0.0 dims = (ideg + 1,) + x.shape dtyp = x.dtype v = np.empty(dims, dtype=dtyp) # Use forward recursion to generate the entries. v[0] = x*0 + 1 if ideg > 0 : x2 = 2*x v[1] = x for i in range(2, ideg + 1) : v[i] = v[i-1]*x2 - v[i-2] return np.rollaxis(v, 0, v.ndim) def chebvander2d(x, y, deg) : """Pseudo-Vandermonde matrix of given degrees. Returns the pseudo-Vandermonde matrix of degrees `deg` and sample points `(x, y)`. The pseudo-Vandermonde matrix is defined by .. math:: V[..., deg[1]*i + j] = T_i(x) * T_j(y), where `0 <= i <= deg[0]` and `0 <= j <= deg[1]`. The leading indices of `V` index the points `(x, y)` and the last index encodes the degrees of the Chebyshev polynomials. If ``V = chebvander2d(x, y, [xdeg, ydeg])``, then the columns of `V` correspond to the elements of a 2-D coefficient array `c` of shape (xdeg + 1, ydeg + 1) in the order .. math:: c_{00}, c_{01}, c_{02} ... , c_{10}, c_{11}, c_{12} ... and ``np.dot(V, c.flat)`` and ``chebval2d(x, y, c)`` will be the same up to roundoff. This equivalence is useful both for least squares fitting and for the evaluation of a large number of 2-D Chebyshev series of the same degrees and sample points. Parameters ---------- x, y : array_like Arrays of point coordinates, all of the same shape. The dtypes will be converted to either float64 or complex128 depending on whether any of the elements are complex. Scalars are converted to 1-D arrays. deg : list of ints List of maximum degrees of the form [x_deg, y_deg]. Returns ------- vander2d : ndarray The shape of the returned matrix is ``x.shape + (order,)``, where :math:`order = (deg[0]+1)*(deg([1]+1)`. The dtype will be the same as the converted `x` and `y`. See Also -------- chebvander, chebvander3d. chebval2d, chebval3d Notes ----- .. versionadded::1.7.0 """ ideg = [int(d) for d in deg] is_valid = [id == d and id >= 0 for id, d in zip(ideg, deg)] if is_valid != [1, 1]: raise ValueError("degrees must be non-negative integers") degx, degy = ideg x, y = np.array((x, y), copy=0) + 0.0 vx = chebvander(x, degx) vy = chebvander(y, degy) v = vx[..., None]*vy[..., None,:] return v.reshape(v.shape[:-2] + (-1,)) def chebvander3d(x, y, z, deg) : """Pseudo-Vandermonde matrix of given degrees. Returns the pseudo-Vandermonde matrix of degrees `deg` and sample points `(x, y, z)`. If `l, m, n` are the given degrees in `x, y, z`, then The pseudo-Vandermonde matrix is defined by .. math:: V[..., (m+1)(n+1)i + (n+1)j + k] = T_i(x)*T_j(y)*T_k(z), where `0 <= i <= l`, `0 <= j <= m`, and `0 <= j <= n`. The leading indices of `V` index the points `(x, y, z)` and the last index encodes the degrees of the Chebyshev polynomials. If ``V = chebvander3d(x, y, z, [xdeg, ydeg, zdeg])``, then the columns of `V` correspond to the elements of a 3-D coefficient array `c` of shape (xdeg + 1, ydeg + 1, zdeg + 1) in the order .. math:: c_{000}, c_{001}, c_{002},... , c_{010}, c_{011}, c_{012},... and ``np.dot(V, c.flat)`` and ``chebval3d(x, y, z, c)`` will be the same up to roundoff. This equivalence is useful both for least squares fitting and for the evaluation of a large number of 3-D Chebyshev series of the same degrees and sample points. Parameters ---------- x, y, z : array_like Arrays of point coordinates, all of the same shape. The dtypes will be converted to either float64 or complex128 depending on whether any of the elements are complex. Scalars are converted to 1-D arrays. deg : list of ints List of maximum degrees of the form [x_deg, y_deg, z_deg]. Returns ------- vander3d : ndarray The shape of the returned matrix is ``x.shape + (order,)``, where :math:`order = (deg[0]+1)*(deg([1]+1)*(deg[2]+1)`. The dtype will be the same as the converted `x`, `y`, and `z`. See Also -------- chebvander, chebvander3d. chebval2d, chebval3d Notes ----- .. versionadded::1.7.0 """ ideg = [int(d) for d in deg] is_valid = [id == d and id >= 0 for id, d in zip(ideg, deg)] if is_valid != [1, 1, 1]: raise ValueError("degrees must be non-negative integers") degx, degy, degz = ideg x, y, z = np.array((x, y, z), copy=0) + 0.0 vx = chebvander(x, degx) vy = chebvander(y, degy) vz = chebvander(z, degz) v = vx[..., None, None]*vy[..., None,:, None]*vz[..., None, None,:] return v.reshape(v.shape[:-3] + (-1,)) def chebfit(x, y, deg, rcond=None, full=False, w=None): """ Least squares fit of Chebyshev series to data. Return the coefficients of a Legendre series of degree `deg` that is the least squares fit to the data values `y` given at points `x`. If `y` is 1-D the returned coefficients will also be 1-D. If `y` is 2-D multiple fits are done, one for each column of `y`, and the resulting coefficients are stored in the corresponding columns of a 2-D return. The fitted polynomial(s) are in the form .. math:: p(x) = c_0 + c_1 * T_1(x) + ... + c_n * T_n(x), 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,) 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 series 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 Returns ------- coef : ndarray, shape (M,) or (M, K) Chebyshev coefficients ordered from low to high. If `y` was 2-D, 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`. Warns ----- RankWarning The rank of the coefficient matrix in the least-squares fit is deficient. The warning is only raised if `full` = False. The warnings can be turned off by >>> import warnings >>> warnings.simplefilter('ignore', RankWarning) See Also -------- polyfit, legfit, lagfit, hermfit, hermefit chebval : Evaluates a Chebyshev series. chebvander : Vandermonde matrix of Chebyshev series. chebweight : Chebyshev weight function. linalg.lstsq : Computes a least-squares fit from the matrix. scipy.interpolate.UnivariateSpline : Computes spline fits. Notes ----- The solution is the coefficients of the Chebyshev series `p` that minimizes the sum of the weighted squared errors .. math:: E = \\sum_j w_j^2 * |y_j - p(x_j)|^2, where :math:`w_j` are the weights. This problem is solved by setting up as the (typically) overdetermined matrix equation .. math:: V(x) * c = w * y, where `V` is the weighted pseudo Vandermonde matrix of `x`, `c` are the coefficients to be solved for, `w` are the weights, and `y` are the observed values. This equation is then solved using the singular value decomposition of `V`. If some of the singular values of `V` are so small that they are neglected, then a `RankWarning` will be issued. This means that the coefficient values may be poorly determined. Using a lower order fit will usually get rid of the warning. The `rcond` parameter can also be set to a value smaller than its default, but the resulting fit may be spurious and have large contributions from roundoff error. Fits using Chebyshev series are usually better conditioned than fits using power series, but much can depend on the distribution of the sample points and the smoothness of the data. If the quality of the fit is inadequate splines may be a good alternative. References ---------- .. [1] Wikipedia, "Curve fitting", http://en.wikipedia.org/wiki/Curve_fitting Examples -------- """ order = int(deg) + 1 x = np.asarray(x) + 0.0 y = np.asarray(y) + 0.0 # check arguments. if deg < 0 : raise ValueError("expected deg >= 0") if x.ndim != 1: raise TypeError("expected 1D vector for x") if x.size == 0: raise TypeError("expected non-empty vector for x") if y.ndim < 1 or y.ndim > 2 : raise TypeError("expected 1D or 2D array for y") if len(x) != len(y): raise TypeError("expected x and y to have same length") # set up the least squares matrices in transposed form lhs = chebvander(x, deg).T rhs = y.T if w is not None: w = np.asarray(w) + 0.0 if w.ndim != 1: raise TypeError("expected 1D vector for w") if len(x) != len(w): raise TypeError("expected x and w to have same length") # apply weights. Don't use inplace operations as they # can cause problems with NA. lhs = lhs * w rhs = rhs * w # set rcond if rcond is None : rcond = len(x)*np.finfo(x.dtype).eps # Determine the norms of the design matrix columns. if issubclass(lhs.dtype.type, np.complexfloating): scl = np.sqrt((np.square(lhs.real) + np.square(lhs.imag)).sum(1)) else: scl = np.sqrt(np.square(lhs).sum(1)) scl[scl == 0] = 1 # Solve the least squares problem. c, resids, rank, s = la.lstsq(lhs.T/scl, rhs.T, rcond) c = (c.T/scl).T # warn on rank reduction if rank != order and not full: msg = "The fit may be poorly conditioned" warnings.warn(msg, pu.RankWarning) if full : return c, [resids, rank, s, rcond] else : return c def chebcompanion(c): """Return the scaled companion matrix of c. The basis polynomials are scaled so that the companion matrix is symmetric when `c` is aa Chebyshev basis polynomial. This provides better eigenvalue estimates than the unscaled case and for basis polynomials the eigenvalues are guaranteed to be real if `numpy.linalg.eigvalsh` is used to obtain them. Parameters ---------- c : array_like 1-D array of Chebyshev series coefficients ordered from low to high degree. Returns ------- mat : ndarray Scaled companion matrix of dimensions (deg, deg). Notes ----- .. versionadded::1.7.0 """ # c is a trimmed copy [c] = pu.as_series([c]) if len(c) < 2: raise ValueError('Series must have maximum degree of at least 1.') if len(c) == 2: return np.array([[-c[0]/c[1]]]) n = len(c) - 1 mat = np.zeros((n, n), dtype=c.dtype) scl = np.array([1.] + [np.sqrt(.5)]*(n-1)) top = mat.reshape(-1)[1::n+1] bot = mat.reshape(-1)[n::n+1] top[0] = np.sqrt(.5) top[1:] = 1/2 bot[...] = top mat[:, -1] -= (c[:-1]/c[-1])*(scl/scl[-1])*.5 return mat def chebroots(c): """ Compute the roots of a Chebyshev series. Return the roots (a.k.a. "zeros") of the polynomial .. math:: p(x) = \\sum_i c[i] * T_i(x). Parameters ---------- c : 1-D array_like 1-D array of coefficients. Returns ------- out : ndarray Array of the roots of the series. If all the roots are real, then `out` is also real, otherwise it is complex. See Also -------- polyroots, legroots, lagroots, hermroots, hermeroots Notes ----- The root estimates are obtained as the eigenvalues of the companion matrix, Roots far from the origin of the complex plane may have large errors due to the numerical instability of the series for such values. Roots with multiplicity greater than 1 will also show larger errors as the value of the series near such points is relatively insensitive to errors in the roots. Isolated roots near the origin can be improved by a few iterations of Newton's method. The Chebyshev series basis polynomials aren't powers of `x` so the results of this function may seem unintuitive. Examples -------- >>> import numpy.polynomial.chebyshev as cheb >>> cheb.chebroots((-1, 1,-1, 1)) # T3 - T2 + T1 - T0 has real roots array([ -5.00000000e-01, 2.60860684e-17, 1.00000000e+00]) """ # c is a trimmed copy [c] = pu.as_series([c]) if len(c) < 2: return np.array([], dtype=c.dtype) if len(c) == 2: return np.array([-c[0]/c[1]]) m = chebcompanion(c) r = la.eigvals(m) r.sort() return r def chebgauss(deg): """ Gauss-Chebyshev quadrature. Computes the sample points and weights for Gauss-Chebyshev quadrature. These sample points and weights will correctly integrate polynomials of degree :math:`2*deg - 1` or less over the interval :math:`[-1, 1]` with the weight function :math:`f(x) = 1/\sqrt{1 - x^2}`. Parameters ---------- deg : int Number of sample points and weights. It must be >= 1. Returns ------- x : ndarray 1-D ndarray containing the sample points. y : ndarray 1-D ndarray containing the weights. Notes ----- .. versionadded:: 1.7.0 The results have only been tested up to degree 100, higher degrees may be problematic. For Gauss-Chebyshev there are closed form solutions for the sample points and weights. If n = `deg`, then .. math:: x_i = \cos(\pi (2 i - 1) / (2 n)) .. math:: w_i = \pi / n """ ideg = int(deg) if ideg != deg or ideg < 1: raise ValueError("deg must be a non-negative integer") x = np.cos(np.pi * np.arange(1, 2*ideg, 2) / (2.0*ideg)) w = np.ones(ideg)*(np.pi/ideg) return x, w def chebweight(x): """ The weight function of the Chebyshev polynomials. The weight function is :math:`1/\sqrt{1 - x^2}` and the interval of integration is :math:`[-1, 1]`. The Chebyshev polynomials are orthogonal, but not normalized, with respect to this weight function. Parameters ---------- x : array_like Values at which the weight function will be computed. Returns ------- w : ndarray The weight function at `x`. Notes ----- .. versionadded:: 1.7.0 """ w = 1./(np.sqrt(1. + x) * np.sqrt(1. - x)) return w def chebpts1(npts): """ Chebyshev points of the first kind. The Chebyshev points of the first kind are the points ``cos(x)``, where ``x = [pi*(k + .5)/npts for k in range(npts)]``. Parameters ---------- npts : int Number of sample points desired. Returns ------- pts : ndarray The Chebyshev points of the first kind. See Also -------- chebpts2 Notes ----- .. versionadded:: 1.5.0 """ _npts = int(npts) if _npts != npts: raise ValueError("npts must be integer") if _npts < 1: raise ValueError("npts must be >= 1") x = np.linspace(-np.pi, 0, _npts, endpoint=False) + np.pi/(2*_npts) return np.cos(x) def chebpts2(npts): """ Chebyshev points of the second kind. The Chebyshev points of the second kind are the points ``cos(x)``, where ``x = [pi*k/(npts - 1) for k in range(npts)]``. Parameters ---------- npts : int Number of sample points desired. Returns ------- pts : ndarray The Chebyshev points of the second kind. Notes ----- .. versionadded:: 1.5.0 """ _npts = int(npts) if _npts != npts: raise ValueError("npts must be integer") if _npts < 2: raise ValueError("npts must be >= 2") x = np.linspace(-np.pi, 0, _npts) return np.cos(x) # # Chebyshev series class # exec(polytemplate.substitute(name='Chebyshev', nick='cheb', domain='[-1,1]')) numpy-1.8.2/numpy/polynomial/setup.py0000664000175100017510000000060112370216242021065 0ustar vagrantvagrant00000000000000from __future__ import division, print_function def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('polynomial', parent_package, top_path) config.add_data_dir('tests') return config if __name__ == '__main__': from numpy.distutils.core import setup setup(configuration=configuration) numpy-1.8.2/numpy/polynomial/tests/0000775000175100017510000000000012371375430020526 5ustar vagrantvagrant00000000000000numpy-1.8.2/numpy/polynomial/tests/test_printing.py0000664000175100017510000000373512370216243023774 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function import numpy.polynomial as poly from numpy.testing import TestCase, run_module_suite, assert_ class test_str(TestCase): def test_polynomial_str(self): res = str(poly.Polynomial([0, 1])) tgt = 'poly([0., 1.])' assert_(res, tgt) def test_chebyshev_str(self): res = str(poly.Chebyshev([0, 1])) tgt = 'leg([0., 1.])' assert_(res, tgt) def test_legendre_str(self): res = str(poly.Legendre([0, 1])) tgt = 'leg([0., 1.])' assert_(res, tgt) def test_hermite_str(self): res = str(poly.Hermite([0, 1])) tgt = 'herm([0., 1.])' assert_(res, tgt) def test_hermiteE_str(self): res = str(poly.HermiteE([0, 1])) tgt = 'herme([0., 1.])' assert_(res, tgt) def test_laguerre_str(self): res = str(poly.Laguerre([0, 1])) tgt = 'lag([0., 1.])' assert_(res, tgt) class test_repr(TestCase): def test_polynomial_str(self): res = repr(poly.Polynomial([0, 1])) tgt = 'Polynomial([0., 1.])' assert_(res, tgt) def test_chebyshev_str(self): res = repr(poly.Chebyshev([0, 1])) tgt = 'Chebyshev([0., 1.], [-1., 1.], [-1., 1.])' assert_(res, tgt) def test_legendre_repr(self): res = repr(poly.Legendre([0, 1])) tgt = 'Legendre([0., 1.], [-1., 1.], [-1., 1.])' assert_(res, tgt) def test_hermite_repr(self): res = repr(poly.Hermite([0, 1])) tgt = 'Hermite([0., 1.], [-1., 1.], [-1., 1.])' assert_(res, tgt) def test_hermiteE_repr(self): res = repr(poly.HermiteE([0, 1])) tgt = 'HermiteE([0., 1.], [-1., 1.], [-1., 1.])' assert_(res, tgt) def test_laguerre_repr(self): res = repr(poly.Laguerre([0, 1])) tgt = 'Laguerre([0., 1.], [0., 1.], [0., 1.])' assert_(res, tgt) # if __name__ == "__main__": run_module_suite() numpy-1.8.2/numpy/polynomial/tests/test_classes.py0000664000175100017510000003742412370216243023601 0ustar vagrantvagrant00000000000000"""Test inter-conversion of different polynomial classes. This tests the convert and cast methods of all the polynomial classes. """ from __future__ import division, absolute_import, print_function import numpy as np from numpy.polynomial import ( Polynomial, Legendre, Chebyshev, Laguerre, Hermite, HermiteE) from numpy.testing import ( TestCase, assert_almost_equal, assert_raises, assert_equal, assert_, run_module_suite, dec) from numpy.testing.noseclasses import KnownFailure classes = ( Polynomial, Legendre, Chebyshev, Laguerre, Hermite, HermiteE) def test_class_methods(): for Poly1 in classes: for Poly2 in classes: yield check_conversion, Poly1, Poly2 yield check_cast, Poly1, Poly2 for Poly in classes: yield check_call, Poly yield check_identity, Poly yield check_basis, Poly yield check_fromroots, Poly yield check_fit, Poly yield check_equal, Poly yield check_not_equal, Poly yield check_add, Poly yield check_sub, Poly yield check_mul, Poly yield check_floordiv, Poly yield check_mod, Poly yield check_divmod, Poly yield check_pow, Poly yield check_integ, Poly yield check_deriv, Poly yield check_roots, Poly yield check_linspace, Poly yield check_mapparms, Poly yield check_degree, Poly yield check_copy, Poly yield check_cutdeg, Poly yield check_truncate, Poly yield check_trim, Poly # # helper functions # random = np.random.random def assert_poly_almost_equal(p1, p2, msg=""): try: assert_(np.all(p1.domain == p2.domain)) assert_(np.all(p1.window == p2.window)) assert_almost_equal(p1.coef, p2.coef) except AssertionError: msg = "Result: %s\nTarget: %s", (p1, p2) raise AssertionError(msg) # # conversion methods that depend on two classes # def check_conversion(Poly1, Poly2): x = np.linspace(0, 1, 10) coef = random((3,)) d1 = Poly1.domain + random((2,))*.25 w1 = Poly1.window + random((2,))*.25 p1 = Poly1(coef, domain=d1, window=w1) d2 = Poly2.domain + random((2,))*.25 w2 = Poly2.window + random((2,))*.25 p2 = p1.convert(kind=Poly2, domain=d2, window=w2) assert_almost_equal(p2.domain, d2) assert_almost_equal(p2.window, w2) assert_almost_equal(p2(x), p1(x)) def check_cast(Poly1, Poly2): x = np.linspace(0, 1, 10) coef = random((3,)) d1 = Poly1.domain + random((2,))*.25 w1 = Poly1.window + random((2,))*.25 p1 = Poly1(coef, domain=d1, window=w1) d2 = Poly2.domain + random((2,))*.25 w2 = Poly2.window + random((2,))*.25 p2 = Poly2.cast(p1, domain=d2, window=w2) assert_almost_equal(p2.domain, d2) assert_almost_equal(p2.window, w2) assert_almost_equal(p2(x), p1(x)) # # methods that depend on one class # def check_identity(Poly) : d = Poly.domain + random((2,))*.25 w = Poly.window + random((2,))*.25 x = np.linspace(d[0], d[1], 11) p = Poly.identity(domain=d, window=w) assert_equal(p.domain, d) assert_equal(p.window, w) assert_almost_equal(p(x), x) def check_basis(Poly): d = Poly.domain + random((2,))*.25 w = Poly.window + random((2,))*.25 p = Poly.basis(5, domain=d, window=w) assert_equal(p.domain, d) assert_equal(p.window, w) assert_equal(p.coef, [0]*5 + [1]) def check_fromroots(Poly): # check that requested roots are zeros of a polynomial # of correct degree, domain, and window. d = Poly.domain + random((2,))*.25 w = Poly.window + random((2,))*.25 r = random((5,)) p1 = Poly.fromroots(r, domain=d, window=w) assert_equal(p1.degree(), len(r)) assert_equal(p1.domain, d) assert_equal(p1.window, w) assert_almost_equal(p1(r), 0) # check that polynomial is monic pdom = Polynomial.domain pwin = Polynomial.window p2 = Polynomial.cast(p1, domain=pdom, window=pwin) assert_almost_equal(p2.coef[-1], 1) def check_fit(Poly) : def f(x) : return x*(x - 1)*(x - 2) x = np.linspace(0, 3) y = f(x) # check default value of domain and window p = Poly.fit(x, y, 3) assert_almost_equal(p.domain, [0, 3]) assert_almost_equal(p(x), y) assert_equal(p.degree(), 3) # check with given domains and window d = Poly.domain + random((2,))*.25 w = Poly.window + random((2,))*.25 p = Poly.fit(x, y, 3, domain=d, window=w) assert_almost_equal(p(x), y) assert_almost_equal(p.domain, d) assert_almost_equal(p.window, w) # check with class domain default p = Poly.fit(x, y, 3, []) assert_equal(p.domain, Poly.domain) assert_equal(p.window, Poly.window) # check that fit accepts weights. w = np.zeros_like(x) z = y + random(y.shape)*.25 w[::2] = 1 p1 = Poly.fit(x[::2], z[::2], 3) p2 = Poly.fit(x, z, 3, w=w) assert_almost_equal(p1(x), p2(x)) def check_equal(Poly) : p1 = Poly([1, 2, 3], domain=[0, 1], window=[2, 3]) p2 = Poly([1, 1, 1], domain=[0, 1], window=[2, 3]) p3 = Poly([1, 2, 3], domain=[1, 2], window=[2, 3]) p4 = Poly([1, 2, 3], domain=[0, 1], window=[1, 2]) assert_(p1 == p1) assert_(not p1 == p2) assert_(not p1 == p3) assert_(not p1 == p4) def check_not_equal(Poly) : p1 = Poly([1, 2, 3], domain=[0, 1], window=[2, 3]) p2 = Poly([1, 1, 1], domain=[0, 1], window=[2, 3]) p3 = Poly([1, 2, 3], domain=[1, 2], window=[2, 3]) p4 = Poly([1, 2, 3], domain=[0, 1], window=[1, 2]) assert_(not p1 != p1) assert_(p1 != p2) assert_(p1 != p3) assert_(p1 != p4) def check_add(Poly) : # This checks commutation, not numerical correctness c1 = list(random((4,)) + .5) c2 = list(random((3,)) + .5) p1 = Poly(c1) p2 = Poly(c2) p3 = p1 + p2 assert_poly_almost_equal(p2 + p1, p3) assert_poly_almost_equal(p1 + c2, p3) assert_poly_almost_equal(c2 + p1, p3) assert_poly_almost_equal(p1 + tuple(c2), p3) 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)) if Poly is Polynomial: assert_raises(TypeError, p1.__add__, Chebyshev([0])) else: assert_raises(TypeError, p1.__add__, Polynomial([0])) def check_sub(Poly) : # This checks commutation, not numerical correctness c1 = list(random((4,)) + .5) c2 = list(random((3,)) + .5) p1 = Poly(c1) p2 = Poly(c2) p3 = p1 - p2 assert_poly_almost_equal(p2 - p1, -p3) assert_poly_almost_equal(p1 - c2, p3) assert_poly_almost_equal(c2 - p1, -p3) assert_poly_almost_equal(p1 - tuple(c2), p3) 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)) if Poly is Polynomial: assert_raises(TypeError, p1.__sub__, Chebyshev([0])) else: assert_raises(TypeError, p1.__sub__, Polynomial([0])) def check_mul(Poly) : c1 = list(random((4,)) + .5) c2 = list(random((3,)) + .5) p1 = Poly(c1) p2 = Poly(c2) p3 = p1 * p2 assert_poly_almost_equal(p2 * p1, p3) assert_poly_almost_equal(p1 * c2, p3) assert_poly_almost_equal(c2 * p1, p3) assert_poly_almost_equal(p1 * tuple(c2), p3) 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_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)) if Poly is Polynomial: assert_raises(TypeError, p1.__mul__, Chebyshev([0])) else: assert_raises(TypeError, p1.__mul__, Polynomial([0])) def check_floordiv(Poly) : c1 = list(random((4,)) + .5) c2 = list(random((3,)) + .5) c3 = list(random((2,)) + .5) p1 = Poly(c1) p2 = Poly(c2) p3 = Poly(c3) p4 = p1 * p2 + p3 c4 = list(p4.coef) assert_poly_almost_equal(p4 // p2, p1) assert_poly_almost_equal(p4 // c2, p1) assert_poly_almost_equal(c4 // p2, p1) assert_poly_almost_equal(p4 // tuple(c2), p1) assert_poly_almost_equal(tuple(c4) // p2, p1) assert_poly_almost_equal(p4 // np.array(c2), p1) assert_poly_almost_equal(np.array(c4) // p2, p1) 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)) assert_raises(TypeError, p1.__floordiv__, Poly([0], window=Poly.window + 1)) if Poly is Polynomial: assert_raises(TypeError, p1.__floordiv__, Chebyshev([0])) else: assert_raises(TypeError, p1.__floordiv__, Polynomial([0])) def check_mod(Poly) : # This checks commutation, not numerical correctness c1 = list(random((4,)) + .5) c2 = list(random((3,)) + .5) c3 = list(random((2,)) + .5) p1 = Poly(c1) p2 = Poly(c2) p3 = Poly(c3) p4 = p1 * p2 + p3 c4 = list(p4.coef) assert_poly_almost_equal(p4 % p2, p3) assert_poly_almost_equal(p4 % c2, p3) assert_poly_almost_equal(c4 % p2, p3) assert_poly_almost_equal(p4 % tuple(c2), p3) assert_poly_almost_equal(tuple(c4) % p2, p3) assert_poly_almost_equal(p4 % np.array(c2), p3) 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)) if Poly is Polynomial: assert_raises(TypeError, p1.__mod__, Chebyshev([0])) else: assert_raises(TypeError, p1.__mod__, Polynomial([0])) def check_divmod(Poly) : # This checks commutation, not numerical correctness c1 = list(random((4,)) + .5) c2 = list(random((3,)) + .5) c3 = list(random((2,)) + .5) p1 = Poly(c1) p2 = Poly(c2) p3 = Poly(c3) p4 = p1 * p2 + p3 c4 = list(p4.coef) quo, rem = divmod(p4, p2) assert_poly_almost_equal(quo, p1) assert_poly_almost_equal(rem, p3) quo, rem = divmod(p4, c2) assert_poly_almost_equal(quo, p1) assert_poly_almost_equal(rem, p3) quo, rem = divmod(c4, p2) assert_poly_almost_equal(quo, p1) assert_poly_almost_equal(rem, p3) quo, rem = divmod(p4, tuple(c2)) assert_poly_almost_equal(quo, p1) assert_poly_almost_equal(rem, p3) quo, rem = divmod(tuple(c4), p2) assert_poly_almost_equal(quo, p1) assert_poly_almost_equal(rem, p3) quo, rem = divmod(p4, np.array(c2)) assert_poly_almost_equal(quo, p1) assert_poly_almost_equal(rem, p3) quo, rem = divmod(np.array(c4), p2) assert_poly_almost_equal(quo, p1) assert_poly_almost_equal(rem, p3) quo, rem = divmod(p2, 2) assert_poly_almost_equal(quo, 0.5*p2) assert_poly_almost_equal(rem, Poly([0])) quo, rem = divmod(2, p2) assert_poly_almost_equal(quo, Poly([0])) assert_poly_almost_equal(rem, Poly([2])) assert_raises(TypeError, divmod, p1, Poly([0], domain=Poly.domain + 1)) assert_raises(TypeError, divmod, p1, Poly([0], window=Poly.window + 1)) if Poly is Polynomial: assert_raises(TypeError, divmod, p1, Chebyshev([0])) else: assert_raises(TypeError, divmod, p1, Polynomial([0])) def check_roots(Poly): d = Poly.domain + random((2,))*.25 w = Poly.window + random((2,))*.25 tgt = np.sort(random((5,))) res = np.sort(Poly.fromroots(tgt).roots()) assert_almost_equal(res, tgt) def check_degree(Poly): p = Poly.basis(5) assert_equal(p.degree(), 5) def check_copy(Poly): p1 = Poly.basis(5) p2 = p1.copy() assert_(p1 == p2) assert_(p1 is not p2) assert_(p1.coef is not p2.coef) assert_(p1.domain is not p2.domain) assert_(p1.window is not p2.window) def check_integ(Poly) : P = Polynomial # Check defaults p0 = Poly.cast(P([1*2, 2*3, 3*4])) p1 = P.cast(p0.integ()) p2 = P.cast(p0.integ(2)) assert_poly_almost_equal(p1, P([0, 2, 3, 4])) assert_poly_almost_equal(p2, P([0, 0, 1, 1, 1])) # Check with k p0 = Poly.cast(P([1*2, 2*3, 3*4])) p1 = P.cast(p0.integ(k=1)) p2 = P.cast(p0.integ(2, k=[1, 1])) assert_poly_almost_equal(p1, P([1, 2, 3, 4])) assert_poly_almost_equal(p2, P([1, 1, 1, 1, 1])) # Check with lbnd p0 = Poly.cast(P([1*2, 2*3, 3*4])) p1 = P.cast(p0.integ(lbnd=1)) p2 = P.cast(p0.integ(2, lbnd=1)) assert_poly_almost_equal(p1, P([-9, 2, 3, 4])) assert_poly_almost_equal(p2, P([6, -9, 1, 1, 1])) # Check scaling d = 2*Poly.domain p0 = Poly.cast(P([1*2, 2*3, 3*4]), domain=d) p1 = P.cast(p0.integ()) p2 = P.cast(p0.integ(2)) assert_poly_almost_equal(p1, P([0, 2, 3, 4])) assert_poly_almost_equal(p2, P([0, 0, 1, 1, 1])) def check_deriv(Poly): # Check that the derivative is the inverse of integration. It is # assumes that the integration has been checked elsewhere. d = Poly.domain + random((2,))*.25 w = Poly.window + random((2,))*.25 p1 = Poly([1, 2, 3], domain=d, window=w) p2 = p1.integ(2, k=[1, 2]) p3 = p1.integ(1, k=[1]) assert_almost_equal(p2.deriv(1).coef, p3.coef) assert_almost_equal(p2.deriv(2).coef, p1.coef) def check_linspace(Poly): d = Poly.domain + random((2,))*.25 w = Poly.window + random((2,))*.25 p = Poly([1, 2, 3], domain=d, window=w) # check default domain xtgt = np.linspace(d[0], d[1], 20) ytgt = p(xtgt) xres, yres = p.linspace(20) assert_almost_equal(xres, xtgt) assert_almost_equal(yres, ytgt) # check specified domain xtgt = np.linspace(0, 2, 20) ytgt = p(xtgt) xres, yres = p.linspace(20, domain=[0, 2]) assert_almost_equal(xres, xtgt) assert_almost_equal(yres, ytgt) def check_pow(Poly) : d = Poly.domain + random((2,))*.25 w = Poly.window + random((2,))*.25 tgt = Poly([1], domain=d, window=d) tst = Poly([1, 2, 3], domain=d, window=d) 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) def check_call(Poly) : P = Polynomial d = Poly.domain x = np.linspace(d[0], d[1], 11) # Check defaults p = Poly.cast(P([1, 2, 3])) tgt = 1 + x*(2 + 3*x) res = p(x) assert_almost_equal(res, tgt) def check_cutdeg(Poly) : p = Poly([1, 2, 3]) assert_raises(ValueError, p.cutdeg, .5) assert_raises(ValueError, p.cutdeg, -1) assert_equal(len(p.cutdeg(3)), 3) assert_equal(len(p.cutdeg(2)), 3) assert_equal(len(p.cutdeg(1)), 2) assert_equal(len(p.cutdeg(0)), 1) def check_truncate(Poly) : p = Poly([1, 2, 3]) assert_raises(ValueError, p.truncate, .5) assert_raises(ValueError, p.truncate, 0) assert_equal(len(p.truncate(4)), 3) assert_equal(len(p.truncate(3)), 3) assert_equal(len(p.truncate(2)), 2) assert_equal(len(p.truncate(1)), 1) def check_trim(Poly) : c = [1, 1e-6, 1e-12, 0] p = Poly(c) assert_equal(p.trim().coef, c[:3]) assert_equal(p.trim(1e-10).coef, c[:2]) assert_equal(p.trim(1e-5).coef, c[:1]) def check_mapparms(Poly) : # check with defaults. Should be identity. d = Poly.domain w = Poly.window p = Poly([1], domain=d, window=w) assert_almost_equal([0, 1], p.mapparms()) # w = 2*d + 1 p = Poly([1], domain=d, window=w) assert_almost_equal([1, 2], p.mapparms()) if __name__ == "__main__": run_module_suite() numpy-1.8.2/numpy/polynomial/tests/test_polynomial.py0000664000175100017510000003623612370216243024327 0ustar vagrantvagrant00000000000000"""Tests for polynomial module. """ from __future__ import division, absolute_import, print_function import numpy as np import numpy.polynomial.polynomial as poly from numpy.testing import ( TestCase, assert_almost_equal, assert_raises, assert_equal, assert_, run_module_suite) def trim(x) : return poly.polytrim(x, tol=1e-6) T0 = [ 1] T1 = [ 0, 1] T2 = [-1, 0, 2] T3 = [ 0, -3, 0, 4] T4 = [ 1, 0, -8, 0, 8] T5 = [ 0, 5, 0, -20, 0, 16] T6 = [-1, 0, 18, 0, -48, 0, 32] T7 = [ 0, -7, 0, 56, 0, -112, 0, 64] T8 = [ 1, 0, -32, 0, 160, 0, -256, 0, 128] T9 = [ 0, 9, 0, -120, 0, 432, 0, -576, 0, 256] Tlist = [T0, T1, T2, T3, T4, T5, T6, T7, T8, T9] class TestConstants(TestCase) : def test_polydomain(self) : assert_equal(poly.polydomain, [-1, 1]) def test_polyzero(self) : assert_equal(poly.polyzero, [0]) def test_polyone(self) : assert_equal(poly.polyone, [1]) def test_polyx(self) : assert_equal(poly.polyx, [0, 1]) class TestArithmetic(TestCase) : def test_polyadd(self) : for i in range(5) : for j in range(5) : msg = "At i=%d, j=%d" % (i, j) tgt = np.zeros(max(i, j) + 1) tgt[i] += 1 tgt[j] += 1 res = poly.polyadd([0]*i + [1], [0]*j + [1]) assert_equal(trim(res), trim(tgt), err_msg=msg) def test_polysub(self) : for i in range(5) : for j in range(5) : msg = "At i=%d, j=%d" % (i, j) tgt = np.zeros(max(i, j) + 1) tgt[i] += 1 tgt[j] -= 1 res = poly.polysub([0]*i + [1], [0]*j + [1]) assert_equal(trim(res), trim(tgt), err_msg=msg) def test_polymulx(self): assert_equal(poly.polymulx([0]), [0]) assert_equal(poly.polymulx([1]), [0, 1]) for i in range(1, 5): ser = [0]*i + [1] tgt = [0]*(i + 1) + [1] assert_equal(poly.polymulx(ser), tgt) def test_polymul(self) : for i in range(5) : for j in range(5) : msg = "At i=%d, j=%d" % (i, j) tgt = np.zeros(i + j + 1) tgt[i + j] += 1 res = poly.polymul([0]*i + [1], [0]*j + [1]) assert_equal(trim(res), trim(tgt), err_msg=msg) def test_polydiv(self) : # check zero division assert_raises(ZeroDivisionError, poly.polydiv, [1], [0]) # check scalar division quo, rem = poly.polydiv([2], [2]) assert_equal((quo, rem), (1, 0)) quo, rem = poly.polydiv([2, 2], [2]) assert_equal((quo, rem), ((1, 1), 0)) # check rest. for i in range(5) : for j in range(5) : msg = "At i=%d, j=%d" % (i, j) ci = [0]*i + [1, 2] cj = [0]*j + [1, 2] tgt = poly.polyadd(ci, cj) quo, rem = poly.polydiv(tgt, ci) res = poly.polyadd(poly.polymul(quo, ci), rem) assert_equal(res, tgt, err_msg=msg) class TestEvaluation(TestCase): # coefficients of 1 + 2*x + 3*x**2 c1d = np.array([1., 2., 3.]) c2d = np.einsum('i,j->ij', c1d, c1d) c3d = np.einsum('i,j,k->ijk', c1d, c1d, c1d) # some random values in [-1, 1) x = np.random.random((3, 5))*2 - 1 y = poly.polyval(x, [1., 2., 3.]) def test_polyval(self) : #check empty input assert_equal(poly.polyval([], [1]).size, 0) #check normal input) x = np.linspace(-1, 1) y = [x**i for i in range(5)] for i in range(5) : tgt = y[i] res = poly.polyval(x, [0]*i + [1]) assert_almost_equal(res, tgt) tgt = x*(x**2 - 1) res = poly.polyval(x, [0, -1, 0, 1]) assert_almost_equal(res, tgt) #check that shape is preserved for i in range(3) : dims = [2]*i x = np.zeros(dims) assert_equal(poly.polyval(x, [1]).shape, dims) assert_equal(poly.polyval(x, [1, 0]).shape, dims) assert_equal(poly.polyval(x, [1, 0, 0]).shape, dims) def test_polyval2d(self): x1, x2, x3 = self.x y1, y2, y3 = self.y #test exceptions assert_raises(ValueError, poly.polyval2d, x1, x2[:2], self.c2d) #test values tgt = y1*y2 res = poly.polyval2d(x1, x2, self.c2d) assert_almost_equal(res, tgt) #test shape z = np.ones((2, 3)) res = poly.polyval2d(z, z, self.c2d) assert_(res.shape == (2, 3)) def test_polyval3d(self): x1, x2, x3 = self.x y1, y2, y3 = self.y #test exceptions assert_raises(ValueError, poly.polyval3d, x1, x2, x3[:2], self.c3d) #test values tgt = y1*y2*y3 res = poly.polyval3d(x1, x2, x3, self.c3d) assert_almost_equal(res, tgt) #test shape z = np.ones((2, 3)) res = poly.polyval3d(z, z, z, self.c3d) assert_(res.shape == (2, 3)) def test_polygrid2d(self): x1, x2, x3 = self.x y1, y2, y3 = self.y #test values tgt = np.einsum('i,j->ij', y1, y2) res = poly.polygrid2d(x1, x2, self.c2d) assert_almost_equal(res, tgt) #test shape z = np.ones((2, 3)) res = poly.polygrid2d(z, z, self.c2d) assert_(res.shape == (2, 3)*2) def test_polygrid3d(self): x1, x2, x3 = self.x y1, y2, y3 = self.y #test values tgt = np.einsum('i,j,k->ijk', y1, y2, y3) res = poly.polygrid3d(x1, x2, x3, self.c3d) assert_almost_equal(res, tgt) #test shape z = np.ones((2, 3)) res = poly.polygrid3d(z, z, z, self.c3d) assert_(res.shape == (2, 3)*3) class TestIntegral(TestCase): def test_polyint(self) : # check exceptions assert_raises(ValueError, poly.polyint, [0], .5) assert_raises(ValueError, poly.polyint, [0], -1) assert_raises(ValueError, poly.polyint, [0], 1, [0, 0]) # test integration of zero polynomial for i in range(2, 5): k = [0]*(i - 2) + [1] res = poly.polyint([0], m=i, k=k) assert_almost_equal(res, [0, 1]) # check single integration with integration constant for i in range(5) : scl = i + 1 pol = [0]*i + [1] tgt = [i] + [0]*i + [1/scl] res = poly.polyint(pol, m=1, k=[i]) assert_almost_equal(trim(res), trim(tgt)) # check single integration with integration constant and lbnd for i in range(5) : scl = i + 1 pol = [0]*i + [1] res = poly.polyint(pol, m=1, k=[i], lbnd=-1) assert_almost_equal(poly.polyval(-1, res), i) # check single integration with integration constant and scaling for i in range(5) : scl = i + 1 pol = [0]*i + [1] tgt = [i] + [0]*i + [2/scl] res = poly.polyint(pol, m=1, k=[i], scl=2) assert_almost_equal(trim(res), trim(tgt)) # check multiple integrations with default k for i in range(5) : for j in range(2, 5) : pol = [0]*i + [1] tgt = pol[:] for k in range(j) : tgt = poly.polyint(tgt, m=1) res = poly.polyint(pol, m=j) assert_almost_equal(trim(res), trim(tgt)) # check multiple integrations with defined k for i in range(5) : for j in range(2, 5) : pol = [0]*i + [1] tgt = pol[:] for k in range(j) : tgt = poly.polyint(tgt, m=1, k=[k]) res = poly.polyint(pol, m=j, k=list(range(j))) assert_almost_equal(trim(res), trim(tgt)) # check multiple integrations with lbnd for i in range(5) : for j in range(2, 5) : pol = [0]*i + [1] tgt = pol[:] for k in range(j) : tgt = poly.polyint(tgt, m=1, k=[k], lbnd=-1) res = poly.polyint(pol, m=j, k=list(range(j)), lbnd=-1) assert_almost_equal(trim(res), trim(tgt)) # check multiple integrations with scaling for i in range(5) : for j in range(2, 5) : pol = [0]*i + [1] tgt = pol[:] for k in range(j) : tgt = poly.polyint(tgt, m=1, k=[k], scl=2) res = poly.polyint(pol, m=j, k=list(range(j)), scl=2) assert_almost_equal(trim(res), trim(tgt)) def test_polyint_axis(self): # check that axis keyword works c2d = np.random.random((3, 4)) tgt = np.vstack([poly.polyint(c) for c in c2d.T]).T res = poly.polyint(c2d, axis=0) assert_almost_equal(res, tgt) tgt = np.vstack([poly.polyint(c) for c in c2d]) res = poly.polyint(c2d, axis=1) assert_almost_equal(res, tgt) tgt = np.vstack([poly.polyint(c, k=3) for c in c2d]) res = poly.polyint(c2d, k=3, axis=1) assert_almost_equal(res, tgt) class TestDerivative(TestCase) : def test_polyder(self) : # check exceptions assert_raises(ValueError, poly.polyder, [0], .5) assert_raises(ValueError, poly.polyder, [0], -1) # check that zeroth deriviative does nothing for i in range(5) : tgt = [0]*i + [1] res = poly.polyder(tgt, m=0) assert_equal(trim(res), trim(tgt)) # check that derivation is the inverse of integration for i in range(5) : for j in range(2, 5) : tgt = [0]*i + [1] res = poly.polyder(poly.polyint(tgt, m=j), m=j) assert_almost_equal(trim(res), trim(tgt)) # check derivation with scaling for i in range(5) : for j in range(2, 5) : tgt = [0]*i + [1] res = poly.polyder(poly.polyint(tgt, m=j, scl=2), m=j, scl=.5) assert_almost_equal(trim(res), trim(tgt)) def test_polyder_axis(self): # check that axis keyword works c2d = np.random.random((3, 4)) tgt = np.vstack([poly.polyder(c) for c in c2d.T]).T res = poly.polyder(c2d, axis=0) assert_almost_equal(res, tgt) tgt = np.vstack([poly.polyder(c) for c in c2d]) res = poly.polyder(c2d, axis=1) assert_almost_equal(res, tgt) class TestVander(TestCase): # some random values in [-1, 1) x = np.random.random((3, 5))*2 - 1 def test_polyvander(self) : # check for 1d x x = np.arange(3) v = poly.polyvander(x, 3) assert_(v.shape == (3, 4)) for i in range(4) : coef = [0]*i + [1] assert_almost_equal(v[..., i], poly.polyval(x, coef)) # check for 2d x x = np.array([[1, 2], [3, 4], [5, 6]]) v = poly.polyvander(x, 3) assert_(v.shape == (3, 2, 4)) for i in range(4) : coef = [0]*i + [1] assert_almost_equal(v[..., i], poly.polyval(x, coef)) def test_polyvander2d(self) : # also tests polyval2d for non-square coefficient array x1, x2, x3 = self.x c = np.random.random((2, 3)) van = poly.polyvander2d(x1, x2, [1, 2]) tgt = poly.polyval2d(x1, x2, c) res = np.dot(van, c.flat) assert_almost_equal(res, tgt) # check shape van = poly.polyvander2d([x1], [x2], [1, 2]) assert_(van.shape == (1, 5, 6)) def test_polyvander3d(self) : # also tests polyval3d for non-square coefficient array x1, x2, x3 = self.x c = np.random.random((2, 3, 4)) van = poly.polyvander3d(x1, x2, x3, [1, 2, 3]) tgt = poly.polyval3d(x1, x2, x3, c) res = np.dot(van, c.flat) assert_almost_equal(res, tgt) # check shape van = poly.polyvander3d([x1], [x2], [x3], [1, 2, 3]) assert_(van.shape == (1, 5, 24)) class TestCompanion(TestCase): def test_raises(self): assert_raises(ValueError, poly.polycompanion, []) assert_raises(ValueError, poly.polycompanion, [1]) def test_dimensions(self): for i in range(1, 5): coef = [0]*i + [1] assert_(poly.polycompanion(coef).shape == (i, i)) def test_linear_root(self): assert_(poly.polycompanion([1, 2])[0, 0] == -.5) class TestMisc(TestCase) : def test_polyfromroots(self) : res = poly.polyfromroots([]) assert_almost_equal(trim(res), [1]) for i in range(1, 5) : roots = np.cos(np.linspace(-np.pi, 0, 2*i + 1)[1::2]) tgt = Tlist[i] res = poly.polyfromroots(roots)*2**(i-1) assert_almost_equal(trim(res), trim(tgt)) def test_polyroots(self) : assert_almost_equal(poly.polyroots([1]), []) assert_almost_equal(poly.polyroots([1, 2]), [-.5]) for i in range(2, 5) : tgt = np.linspace(-1, 1, i) res = poly.polyroots(poly.polyfromroots(tgt)) assert_almost_equal(trim(res), trim(tgt)) def test_polyfit(self) : def f(x) : return x*(x - 1)*(x - 2) # Test exceptions assert_raises(ValueError, poly.polyfit, [1], [1], -1) assert_raises(TypeError, poly.polyfit, [[1]], [1], 0) assert_raises(TypeError, poly.polyfit, [], [1], 0) assert_raises(TypeError, poly.polyfit, [1], [[[1]]], 0) assert_raises(TypeError, poly.polyfit, [1, 2], [1], 0) assert_raises(TypeError, poly.polyfit, [1], [1, 2], 0) assert_raises(TypeError, poly.polyfit, [1], [1], 0, w=[[1]]) assert_raises(TypeError, poly.polyfit, [1], [1], 0, w=[1, 1]) # Test fit x = np.linspace(0, 2) y = f(x) # coef3 = poly.polyfit(x, y, 3) assert_equal(len(coef3), 4) assert_almost_equal(poly.polyval(x, coef3), y) # coef4 = poly.polyfit(x, y, 4) assert_equal(len(coef4), 5) assert_almost_equal(poly.polyval(x, coef4), y) # coef2d = poly.polyfit(x, np.array([y, y]).T, 3) assert_almost_equal(coef2d, np.array([coef3, coef3]).T) # test weighting w = np.zeros_like(x) yw = y.copy() w[1::2] = 1 yw[0::2] = 0 wcoef3 = poly.polyfit(x, yw, 3, w=w) assert_almost_equal(wcoef3, coef3) # wcoef2d = poly.polyfit(x, np.array([yw, yw]).T, 3, w=w) assert_almost_equal(wcoef2d, np.array([coef3, coef3]).T) # test scaling with complex values x points whose square # is zero when summed. x = [1, 1j, -1, -1j] assert_almost_equal(poly.polyfit(x, x, 1), [0, 1]) def test_polytrim(self) : coef = [2, -1, 1, 0] # Test exceptions assert_raises(ValueError, poly.polytrim, coef, -1) # Test results assert_equal(poly.polytrim(coef), coef[:-1]) assert_equal(poly.polytrim(coef, 1), coef[:-3]) assert_equal(poly.polytrim(coef, 2), [0]) def test_polyline(self) : assert_equal(poly.polyline(3, 4), [3, 4]) if __name__ == "__main__": run_module_suite() numpy-1.8.2/numpy/polynomial/tests/test_chebyshev.py0000664000175100017510000004347312370216243024125 0ustar vagrantvagrant00000000000000"""Tests for chebyshev module. """ from __future__ import division, absolute_import, print_function import numpy as np import numpy.polynomial.chebyshev as cheb from numpy.polynomial.polynomial import polyval from numpy.testing import ( TestCase, assert_almost_equal, assert_raises, assert_equal, assert_, run_module_suite) def trim(x) : return cheb.chebtrim(x, tol=1e-6) T0 = [ 1] T1 = [ 0, 1] T2 = [-1, 0, 2] T3 = [ 0, -3, 0, 4] T4 = [ 1, 0, -8, 0, 8] T5 = [ 0, 5, 0, -20, 0, 16] T6 = [-1, 0, 18, 0, -48, 0, 32] T7 = [ 0, -7, 0, 56, 0, -112, 0, 64] T8 = [ 1, 0, -32, 0, 160, 0, -256, 0, 128] T9 = [ 0, 9, 0, -120, 0, 432, 0, -576, 0, 256] Tlist = [T0, T1, T2, T3, T4, T5, T6, T7, T8, T9] class TestPrivate(TestCase) : def test__cseries_to_zseries(self) : for i in range(5) : inp = np.array([2] + [1]*i, np.double) tgt = np.array([.5]*i + [2] + [.5]*i, np.double) res = cheb._cseries_to_zseries(inp) assert_equal(res, tgt) def test__zseries_to_cseries(self) : for i in range(5) : inp = np.array([.5]*i + [2] + [.5]*i, np.double) tgt = np.array([2] + [1]*i, np.double) res = cheb._zseries_to_cseries(inp) assert_equal(res, tgt) class TestConstants(TestCase) : def test_chebdomain(self) : assert_equal(cheb.chebdomain, [-1, 1]) def test_chebzero(self) : assert_equal(cheb.chebzero, [0]) def test_chebone(self) : assert_equal(cheb.chebone, [1]) def test_chebx(self) : assert_equal(cheb.chebx, [0, 1]) class TestArithmetic(TestCase) : def test_chebadd(self) : for i in range(5) : for j in range(5) : msg = "At i=%d, j=%d" % (i, j) tgt = np.zeros(max(i, j) + 1) tgt[i] += 1 tgt[j] += 1 res = cheb.chebadd([0]*i + [1], [0]*j + [1]) assert_equal(trim(res), trim(tgt), err_msg=msg) def test_chebsub(self) : for i in range(5) : for j in range(5) : msg = "At i=%d, j=%d" % (i, j) tgt = np.zeros(max(i, j) + 1) tgt[i] += 1 tgt[j] -= 1 res = cheb.chebsub([0]*i + [1], [0]*j + [1]) assert_equal(trim(res), trim(tgt), err_msg=msg) def test_chebmulx(self): assert_equal(cheb.chebmulx([0]), [0]) assert_equal(cheb.chebmulx([1]), [0, 1]) for i in range(1, 5): ser = [0]*i + [1] tgt = [0]*(i - 1) + [.5, 0, .5] assert_equal(cheb.chebmulx(ser), tgt) def test_chebmul(self) : for i in range(5) : for j in range(5) : msg = "At i=%d, j=%d" % (i, j) tgt = np.zeros(i + j + 1) tgt[i + j] += .5 tgt[abs(i - j)] += .5 res = cheb.chebmul([0]*i + [1], [0]*j + [1]) assert_equal(trim(res), trim(tgt), err_msg=msg) def test_chebdiv(self) : for i in range(5) : for j in range(5) : msg = "At i=%d, j=%d" % (i, j) ci = [0]*i + [1] cj = [0]*j + [1] tgt = cheb.chebadd(ci, cj) quo, rem = cheb.chebdiv(tgt, ci) res = cheb.chebadd(cheb.chebmul(quo, ci), rem) assert_equal(trim(res), trim(tgt), err_msg=msg) class TestEvaluation(TestCase): # coefficients of 1 + 2*x + 3*x**2 c1d = np.array([2.5, 2., 1.5]) c2d = np.einsum('i,j->ij', c1d, c1d) c3d = np.einsum('i,j,k->ijk', c1d, c1d, c1d) # some random values in [-1, 1) x = np.random.random((3, 5))*2 - 1 y = polyval(x, [1., 2., 3.]) def test_chebval(self) : #check empty input assert_equal(cheb.chebval([], [1]).size, 0) #check normal input) x = np.linspace(-1, 1) y = [polyval(x, c) for c in Tlist] for i in range(10) : msg = "At i=%d" % i tgt = y[i] res = cheb.chebval(x, [0]*i + [1]) assert_almost_equal(res, tgt, err_msg=msg) #check that shape is preserved for i in range(3) : dims = [2]*i x = np.zeros(dims) assert_equal(cheb.chebval(x, [1]).shape, dims) assert_equal(cheb.chebval(x, [1, 0]).shape, dims) assert_equal(cheb.chebval(x, [1, 0, 0]).shape, dims) def test_chebval2d(self): x1, x2, x3 = self.x y1, y2, y3 = self.y #test exceptions assert_raises(ValueError, cheb.chebval2d, x1, x2[:2], self.c2d) #test values tgt = y1*y2 res = cheb.chebval2d(x1, x2, self.c2d) assert_almost_equal(res, tgt) #test shape z = np.ones((2, 3)) res = cheb.chebval2d(z, z, self.c2d) assert_(res.shape == (2, 3)) def test_chebval3d(self): x1, x2, x3 = self.x y1, y2, y3 = self.y #test exceptions assert_raises(ValueError, cheb.chebval3d, x1, x2, x3[:2], self.c3d) #test values tgt = y1*y2*y3 res = cheb.chebval3d(x1, x2, x3, self.c3d) assert_almost_equal(res, tgt) #test shape z = np.ones((2, 3)) res = cheb.chebval3d(z, z, z, self.c3d) assert_(res.shape == (2, 3)) def test_chebgrid2d(self): x1, x2, x3 = self.x y1, y2, y3 = self.y #test values tgt = np.einsum('i,j->ij', y1, y2) res = cheb.chebgrid2d(x1, x2, self.c2d) assert_almost_equal(res, tgt) #test shape z = np.ones((2, 3)) res = cheb.chebgrid2d(z, z, self.c2d) assert_(res.shape == (2, 3)*2) def test_chebgrid3d(self): x1, x2, x3 = self.x y1, y2, y3 = self.y #test values tgt = np.einsum('i,j,k->ijk', y1, y2, y3) res = cheb.chebgrid3d(x1, x2, x3, self.c3d) assert_almost_equal(res, tgt) #test shape z = np.ones((2, 3)) res = cheb.chebgrid3d(z, z, z, self.c3d) assert_(res.shape == (2, 3)*3) class TestIntegral(TestCase) : def test_chebint(self) : # check exceptions assert_raises(ValueError, cheb.chebint, [0], .5) assert_raises(ValueError, cheb.chebint, [0], -1) assert_raises(ValueError, cheb.chebint, [0], 1, [0, 0]) # test integration of zero polynomial for i in range(2, 5): k = [0]*(i - 2) + [1] res = cheb.chebint([0], m=i, k=k) assert_almost_equal(res, [0, 1]) # check single integration with integration constant for i in range(5) : scl = i + 1 pol = [0]*i + [1] tgt = [i] + [0]*i + [1/scl] chebpol = cheb.poly2cheb(pol) chebint = cheb.chebint(chebpol, m=1, k=[i]) res = cheb.cheb2poly(chebint) assert_almost_equal(trim(res), trim(tgt)) # check single integration with integration constant and lbnd for i in range(5) : scl = i + 1 pol = [0]*i + [1] chebpol = cheb.poly2cheb(pol) chebint = cheb.chebint(chebpol, m=1, k=[i], lbnd=-1) assert_almost_equal(cheb.chebval(-1, chebint), i) # check single integration with integration constant and scaling for i in range(5) : scl = i + 1 pol = [0]*i + [1] tgt = [i] + [0]*i + [2/scl] chebpol = cheb.poly2cheb(pol) chebint = cheb.chebint(chebpol, m=1, k=[i], scl=2) res = cheb.cheb2poly(chebint) assert_almost_equal(trim(res), trim(tgt)) # check multiple integrations with default k for i in range(5) : for j in range(2, 5) : pol = [0]*i + [1] tgt = pol[:] for k in range(j) : tgt = cheb.chebint(tgt, m=1) res = cheb.chebint(pol, m=j) assert_almost_equal(trim(res), trim(tgt)) # check multiple integrations with defined k for i in range(5) : for j in range(2, 5) : pol = [0]*i + [1] tgt = pol[:] for k in range(j) : tgt = cheb.chebint(tgt, m=1, k=[k]) res = cheb.chebint(pol, m=j, k=list(range(j))) assert_almost_equal(trim(res), trim(tgt)) # check multiple integrations with lbnd for i in range(5) : for j in range(2, 5) : pol = [0]*i + [1] tgt = pol[:] for k in range(j) : tgt = cheb.chebint(tgt, m=1, k=[k], lbnd=-1) res = cheb.chebint(pol, m=j, k=list(range(j)), lbnd=-1) assert_almost_equal(trim(res), trim(tgt)) # check multiple integrations with scaling for i in range(5) : for j in range(2, 5) : pol = [0]*i + [1] tgt = pol[:] for k in range(j) : tgt = cheb.chebint(tgt, m=1, k=[k], scl=2) res = cheb.chebint(pol, m=j, k=list(range(j)), scl=2) assert_almost_equal(trim(res), trim(tgt)) def test_chebint_axis(self): # check that axis keyword works c2d = np.random.random((3, 4)) tgt = np.vstack([cheb.chebint(c) for c in c2d.T]).T res = cheb.chebint(c2d, axis=0) assert_almost_equal(res, tgt) tgt = np.vstack([cheb.chebint(c) for c in c2d]) res = cheb.chebint(c2d, axis=1) assert_almost_equal(res, tgt) tgt = np.vstack([cheb.chebint(c, k=3) for c in c2d]) res = cheb.chebint(c2d, k=3, axis=1) assert_almost_equal(res, tgt) class TestDerivative(TestCase) : def test_chebder(self) : # check exceptions assert_raises(ValueError, cheb.chebder, [0], .5) assert_raises(ValueError, cheb.chebder, [0], -1) # check that zeroth deriviative does nothing for i in range(5) : tgt = [0]*i + [1] res = cheb.chebder(tgt, m=0) assert_equal(trim(res), trim(tgt)) # check that derivation is the inverse of integration for i in range(5) : for j in range(2, 5) : tgt = [0]*i + [1] res = cheb.chebder(cheb.chebint(tgt, m=j), m=j) assert_almost_equal(trim(res), trim(tgt)) # check derivation with scaling for i in range(5) : for j in range(2, 5) : tgt = [0]*i + [1] res = cheb.chebder(cheb.chebint(tgt, m=j, scl=2), m=j, scl=.5) assert_almost_equal(trim(res), trim(tgt)) def test_chebder_axis(self): # check that axis keyword works c2d = np.random.random((3, 4)) tgt = np.vstack([cheb.chebder(c) for c in c2d.T]).T res = cheb.chebder(c2d, axis=0) assert_almost_equal(res, tgt) tgt = np.vstack([cheb.chebder(c) for c in c2d]) res = cheb.chebder(c2d, axis=1) assert_almost_equal(res, tgt) class TestVander(TestCase): # some random values in [-1, 1) x = np.random.random((3, 5))*2 - 1 def test_chebvander(self) : # check for 1d x x = np.arange(3) v = cheb.chebvander(x, 3) assert_(v.shape == (3, 4)) for i in range(4) : coef = [0]*i + [1] assert_almost_equal(v[..., i], cheb.chebval(x, coef)) # check for 2d x x = np.array([[1, 2], [3, 4], [5, 6]]) v = cheb.chebvander(x, 3) assert_(v.shape == (3, 2, 4)) for i in range(4) : coef = [0]*i + [1] assert_almost_equal(v[..., i], cheb.chebval(x, coef)) def test_chebvander2d(self) : # also tests chebval2d for non-square coefficient array x1, x2, x3 = self.x c = np.random.random((2, 3)) van = cheb.chebvander2d(x1, x2, [1, 2]) tgt = cheb.chebval2d(x1, x2, c) res = np.dot(van, c.flat) assert_almost_equal(res, tgt) # check shape van = cheb.chebvander2d([x1], [x2], [1, 2]) assert_(van.shape == (1, 5, 6)) def test_chebvander3d(self) : # also tests chebval3d for non-square coefficient array x1, x2, x3 = self.x c = np.random.random((2, 3, 4)) van = cheb.chebvander3d(x1, x2, x3, [1, 2, 3]) tgt = cheb.chebval3d(x1, x2, x3, c) res = np.dot(van, c.flat) assert_almost_equal(res, tgt) # check shape van = cheb.chebvander3d([x1], [x2], [x3], [1, 2, 3]) assert_(van.shape == (1, 5, 24)) class TestFitting(TestCase): def test_chebfit(self) : def f(x) : return x*(x - 1)*(x - 2) # Test exceptions assert_raises(ValueError, cheb.chebfit, [1], [1], -1) assert_raises(TypeError, cheb.chebfit, [[1]], [1], 0) assert_raises(TypeError, cheb.chebfit, [], [1], 0) assert_raises(TypeError, cheb.chebfit, [1], [[[1]]], 0) assert_raises(TypeError, cheb.chebfit, [1, 2], [1], 0) assert_raises(TypeError, cheb.chebfit, [1], [1, 2], 0) assert_raises(TypeError, cheb.chebfit, [1], [1], 0, w=[[1]]) assert_raises(TypeError, cheb.chebfit, [1], [1], 0, w=[1, 1]) # Test fit x = np.linspace(0, 2) y = f(x) # coef3 = cheb.chebfit(x, y, 3) assert_equal(len(coef3), 4) assert_almost_equal(cheb.chebval(x, coef3), y) # coef4 = cheb.chebfit(x, y, 4) assert_equal(len(coef4), 5) assert_almost_equal(cheb.chebval(x, coef4), y) # coef2d = cheb.chebfit(x, np.array([y, y]).T, 3) assert_almost_equal(coef2d, np.array([coef3, coef3]).T) # test weighting w = np.zeros_like(x) yw = y.copy() w[1::2] = 1 y[0::2] = 0 wcoef3 = cheb.chebfit(x, yw, 3, w=w) assert_almost_equal(wcoef3, coef3) # wcoef2d = cheb.chebfit(x, np.array([yw, yw]).T, 3, w=w) assert_almost_equal(wcoef2d, np.array([coef3, coef3]).T) # test scaling with complex values x points whose square # is zero when summed. x = [1, 1j, -1, -1j] assert_almost_equal(cheb.chebfit(x, x, 1), [0, 1]) class TestCompanion(TestCase): def test_raises(self): assert_raises(ValueError, cheb.chebcompanion, []) assert_raises(ValueError, cheb.chebcompanion, [1]) def test_dimensions(self): for i in range(1, 5): coef = [0]*i + [1] assert_(cheb.chebcompanion(coef).shape == (i, i)) def test_linear_root(self): assert_(cheb.chebcompanion([1, 2])[0, 0] == -.5) class TestGauss(TestCase): def test_100(self): x, w = cheb.chebgauss(100) # test orthogonality. Note that the results need to be normalized, # otherwise the huge values that can arise from fast growing # functions like Laguerre can be very confusing. v = cheb.chebvander(x, 99) vv = np.dot(v.T * w, v) vd = 1/np.sqrt(vv.diagonal()) vv = vd[:, None] * vv * vd assert_almost_equal(vv, np.eye(100)) # check that the integral of 1 is correct tgt = np.pi assert_almost_equal(w.sum(), tgt) class TestMisc(TestCase) : def test_chebfromroots(self) : res = cheb.chebfromroots([]) assert_almost_equal(trim(res), [1]) for i in range(1, 5) : roots = np.cos(np.linspace(-np.pi, 0, 2*i + 1)[1::2]) tgt = [0]*i + [1] res = cheb.chebfromroots(roots)*2**(i-1) assert_almost_equal(trim(res), trim(tgt)) def test_chebroots(self) : assert_almost_equal(cheb.chebroots([1]), []) assert_almost_equal(cheb.chebroots([1, 2]), [-.5]) for i in range(2, 5) : tgt = np.linspace(-1, 1, i) res = cheb.chebroots(cheb.chebfromroots(tgt)) assert_almost_equal(trim(res), trim(tgt)) def test_chebtrim(self) : coef = [2, -1, 1, 0] # Test exceptions assert_raises(ValueError, cheb.chebtrim, coef, -1) # Test results assert_equal(cheb.chebtrim(coef), coef[:-1]) assert_equal(cheb.chebtrim(coef, 1), coef[:-3]) assert_equal(cheb.chebtrim(coef, 2), [0]) def test_chebline(self) : assert_equal(cheb.chebline(3, 4), [3, 4]) def test_cheb2poly(self) : for i in range(10) : assert_almost_equal(cheb.cheb2poly([0]*i + [1]), Tlist[i]) def test_poly2cheb(self) : for i in range(10) : assert_almost_equal(cheb.poly2cheb(Tlist[i]), [0]*i + [1]) def test_weight(self): x = np.linspace(-1, 1, 11)[1:-1] tgt = 1./(np.sqrt(1 + x) * np.sqrt(1 - x)) res = cheb.chebweight(x) assert_almost_equal(res, tgt) def test_chebpts1(self): #test exceptions assert_raises(ValueError, cheb.chebpts1, 1.5) assert_raises(ValueError, cheb.chebpts1, 0) #test points tgt = [0] assert_almost_equal(cheb.chebpts1(1), tgt) tgt = [-0.70710678118654746, 0.70710678118654746] assert_almost_equal(cheb.chebpts1(2), tgt) tgt = [-0.86602540378443871, 0, 0.86602540378443871] assert_almost_equal(cheb.chebpts1(3), tgt) tgt = [-0.9238795325, -0.3826834323, 0.3826834323, 0.9238795325] assert_almost_equal(cheb.chebpts1(4), tgt) def test_chebpts2(self): #test exceptions assert_raises(ValueError, cheb.chebpts2, 1.5) assert_raises(ValueError, cheb.chebpts2, 1) #test points tgt = [-1, 1] assert_almost_equal(cheb.chebpts2(2), tgt) tgt = [-1, 0, 1] assert_almost_equal(cheb.chebpts2(3), tgt) tgt = [-1, -0.5, .5, 1] assert_almost_equal(cheb.chebpts2(4), tgt) tgt = [-1.0, -0.707106781187, 0, 0.707106781187, 1.0] assert_almost_equal(cheb.chebpts2(5), tgt) if __name__ == "__main__": run_module_suite() numpy-1.8.2/numpy/polynomial/tests/test_hermite.py0000664000175100017510000004112512370216243023572 0ustar vagrantvagrant00000000000000"""Tests for hermite module. """ from __future__ import division, absolute_import, print_function import numpy as np import numpy.polynomial.hermite as herm from numpy.polynomial.polynomial import polyval from numpy.testing import ( TestCase, assert_almost_equal, assert_raises, assert_equal, assert_, run_module_suite) H0 = np.array([ 1]) H1 = np.array([0, 2]) H2 = np.array([ -2, 0, 4]) H3 = np.array([0, -12, 0, 8]) H4 = np.array([ 12, 0, -48, 0, 16]) H5 = np.array([0, 120, 0, -160, 0, 32]) H6 = np.array([-120, 0, 720, 0, -480, 0, 64]) H7 = np.array([0, -1680, 0, 3360, 0, -1344, 0, 128]) H8 = np.array([1680, 0, -13440, 0, 13440, 0, -3584, 0, 256]) H9 = np.array([0, 30240, 0, -80640, 0, 48384, 0, -9216, 0, 512]) Hlist = [H0, H1, H2, H3, H4, H5, H6, H7, H8, H9] def trim(x) : return herm.hermtrim(x, tol=1e-6) class TestConstants(TestCase) : def test_hermdomain(self) : assert_equal(herm.hermdomain, [-1, 1]) def test_hermzero(self) : assert_equal(herm.hermzero, [0]) def test_hermone(self) : assert_equal(herm.hermone, [1]) def test_hermx(self) : assert_equal(herm.hermx, [0, .5]) class TestArithmetic(TestCase) : x = np.linspace(-3, 3, 100) def test_hermadd(self) : for i in range(5) : for j in range(5) : msg = "At i=%d, j=%d" % (i, j) tgt = np.zeros(max(i, j) + 1) tgt[i] += 1 tgt[j] += 1 res = herm.hermadd([0]*i + [1], [0]*j + [1]) assert_equal(trim(res), trim(tgt), err_msg=msg) def test_hermsub(self) : for i in range(5) : for j in range(5) : msg = "At i=%d, j=%d" % (i, j) tgt = np.zeros(max(i, j) + 1) tgt[i] += 1 tgt[j] -= 1 res = herm.hermsub([0]*i + [1], [0]*j + [1]) assert_equal(trim(res), trim(tgt), err_msg=msg) def test_hermmulx(self): assert_equal(herm.hermmulx([0]), [0]) assert_equal(herm.hermmulx([1]), [0, .5]) for i in range(1, 5): ser = [0]*i + [1] tgt = [0]*(i - 1) + [i, 0, .5] assert_equal(herm.hermmulx(ser), tgt) def test_hermmul(self) : # check values of result for i in range(5) : pol1 = [0]*i + [1] val1 = herm.hermval(self.x, pol1) for j in range(5) : msg = "At i=%d, j=%d" % (i, j) pol2 = [0]*j + [1] val2 = herm.hermval(self.x, pol2) pol3 = herm.hermmul(pol1, pol2) val3 = herm.hermval(self.x, pol3) assert_(len(pol3) == i + j + 1, msg) assert_almost_equal(val3, val1*val2, err_msg=msg) def test_hermdiv(self) : for i in range(5) : for j in range(5) : msg = "At i=%d, j=%d" % (i, j) ci = [0]*i + [1] cj = [0]*j + [1] tgt = herm.hermadd(ci, cj) quo, rem = herm.hermdiv(tgt, ci) res = herm.hermadd(herm.hermmul(quo, ci), rem) assert_equal(trim(res), trim(tgt), err_msg=msg) class TestEvaluation(TestCase) : # coefficients of 1 + 2*x + 3*x**2 c1d = np.array([2.5, 1., .75]) c2d = np.einsum('i,j->ij', c1d, c1d) c3d = np.einsum('i,j,k->ijk', c1d, c1d, c1d) # some random values in [-1, 1) x = np.random.random((3, 5))*2 - 1 y = polyval(x, [1., 2., 3.]) def test_hermval(self) : #check empty input assert_equal(herm.hermval([], [1]).size, 0) #check normal input) x = np.linspace(-1, 1) y = [polyval(x, c) for c in Hlist] for i in range(10) : msg = "At i=%d" % i ser = np.zeros tgt = y[i] res = herm.hermval(x, [0]*i + [1]) assert_almost_equal(res, tgt, err_msg=msg) #check that shape is preserved for i in range(3) : dims = [2]*i x = np.zeros(dims) assert_equal(herm.hermval(x, [1]).shape, dims) assert_equal(herm.hermval(x, [1, 0]).shape, dims) assert_equal(herm.hermval(x, [1, 0, 0]).shape, dims) def test_hermval2d(self): x1, x2, x3 = self.x y1, y2, y3 = self.y #test exceptions assert_raises(ValueError, herm.hermval2d, x1, x2[:2], self.c2d) #test values tgt = y1*y2 res = herm.hermval2d(x1, x2, self.c2d) assert_almost_equal(res, tgt) #test shape z = np.ones((2, 3)) res = herm.hermval2d(z, z, self.c2d) assert_(res.shape == (2, 3)) def test_hermval3d(self): x1, x2, x3 = self.x y1, y2, y3 = self.y #test exceptions assert_raises(ValueError, herm.hermval3d, x1, x2, x3[:2], self.c3d) #test values tgt = y1*y2*y3 res = herm.hermval3d(x1, x2, x3, self.c3d) assert_almost_equal(res, tgt) #test shape z = np.ones((2, 3)) res = herm.hermval3d(z, z, z, self.c3d) assert_(res.shape == (2, 3)) def test_hermgrid2d(self): x1, x2, x3 = self.x y1, y2, y3 = self.y #test values tgt = np.einsum('i,j->ij', y1, y2) res = herm.hermgrid2d(x1, x2, self.c2d) assert_almost_equal(res, tgt) #test shape z = np.ones((2, 3)) res = herm.hermgrid2d(z, z, self.c2d) assert_(res.shape == (2, 3)*2) def test_hermgrid3d(self): x1, x2, x3 = self.x y1, y2, y3 = self.y #test values tgt = np.einsum('i,j,k->ijk', y1, y2, y3) res = herm.hermgrid3d(x1, x2, x3, self.c3d) assert_almost_equal(res, tgt) #test shape z = np.ones((2, 3)) res = herm.hermgrid3d(z, z, z, self.c3d) assert_(res.shape == (2, 3)*3) class TestIntegral(TestCase) : def test_hermint(self) : # check exceptions assert_raises(ValueError, herm.hermint, [0], .5) assert_raises(ValueError, herm.hermint, [0], -1) assert_raises(ValueError, herm.hermint, [0], 1, [0, 0]) # test integration of zero polynomial for i in range(2, 5): k = [0]*(i - 2) + [1] res = herm.hermint([0], m=i, k=k) assert_almost_equal(res, [0, .5]) # check single integration with integration constant for i in range(5) : scl = i + 1 pol = [0]*i + [1] tgt = [i] + [0]*i + [1/scl] hermpol = herm.poly2herm(pol) hermint = herm.hermint(hermpol, m=1, k=[i]) res = herm.herm2poly(hermint) assert_almost_equal(trim(res), trim(tgt)) # check single integration with integration constant and lbnd for i in range(5) : scl = i + 1 pol = [0]*i + [1] hermpol = herm.poly2herm(pol) hermint = herm.hermint(hermpol, m=1, k=[i], lbnd=-1) assert_almost_equal(herm.hermval(-1, hermint), i) # check single integration with integration constant and scaling for i in range(5) : scl = i + 1 pol = [0]*i + [1] tgt = [i] + [0]*i + [2/scl] hermpol = herm.poly2herm(pol) hermint = herm.hermint(hermpol, m=1, k=[i], scl=2) res = herm.herm2poly(hermint) assert_almost_equal(trim(res), trim(tgt)) # check multiple integrations with default k for i in range(5) : for j in range(2, 5) : pol = [0]*i + [1] tgt = pol[:] for k in range(j) : tgt = herm.hermint(tgt, m=1) res = herm.hermint(pol, m=j) assert_almost_equal(trim(res), trim(tgt)) # check multiple integrations with defined k for i in range(5) : for j in range(2, 5) : pol = [0]*i + [1] tgt = pol[:] for k in range(j) : tgt = herm.hermint(tgt, m=1, k=[k]) res = herm.hermint(pol, m=j, k=list(range(j))) assert_almost_equal(trim(res), trim(tgt)) # check multiple integrations with lbnd for i in range(5) : for j in range(2, 5) : pol = [0]*i + [1] tgt = pol[:] for k in range(j) : tgt = herm.hermint(tgt, m=1, k=[k], lbnd=-1) res = herm.hermint(pol, m=j, k=list(range(j)), lbnd=-1) assert_almost_equal(trim(res), trim(tgt)) # check multiple integrations with scaling for i in range(5) : for j in range(2, 5) : pol = [0]*i + [1] tgt = pol[:] for k in range(j) : tgt = herm.hermint(tgt, m=1, k=[k], scl=2) res = herm.hermint(pol, m=j, k=list(range(j)), scl=2) assert_almost_equal(trim(res), trim(tgt)) def test_hermint_axis(self): # check that axis keyword works c2d = np.random.random((3, 4)) tgt = np.vstack([herm.hermint(c) for c in c2d.T]).T res = herm.hermint(c2d, axis=0) assert_almost_equal(res, tgt) tgt = np.vstack([herm.hermint(c) for c in c2d]) res = herm.hermint(c2d, axis=1) assert_almost_equal(res, tgt) tgt = np.vstack([herm.hermint(c, k=3) for c in c2d]) res = herm.hermint(c2d, k=3, axis=1) assert_almost_equal(res, tgt) class TestDerivative(TestCase) : def test_hermder(self) : # check exceptions assert_raises(ValueError, herm.hermder, [0], .5) assert_raises(ValueError, herm.hermder, [0], -1) # check that zeroth deriviative does nothing for i in range(5) : tgt = [0]*i + [1] res = herm.hermder(tgt, m=0) assert_equal(trim(res), trim(tgt)) # check that derivation is the inverse of integration for i in range(5) : for j in range(2, 5) : tgt = [0]*i + [1] res = herm.hermder(herm.hermint(tgt, m=j), m=j) assert_almost_equal(trim(res), trim(tgt)) # check derivation with scaling for i in range(5) : for j in range(2, 5) : tgt = [0]*i + [1] res = herm.hermder(herm.hermint(tgt, m=j, scl=2), m=j, scl=.5) assert_almost_equal(trim(res), trim(tgt)) def test_hermder_axis(self): # check that axis keyword works c2d = np.random.random((3, 4)) tgt = np.vstack([herm.hermder(c) for c in c2d.T]).T res = herm.hermder(c2d, axis=0) assert_almost_equal(res, tgt) tgt = np.vstack([herm.hermder(c) for c in c2d]) res = herm.hermder(c2d, axis=1) assert_almost_equal(res, tgt) class TestVander(TestCase): # some random values in [-1, 1) x = np.random.random((3, 5))*2 - 1 def test_hermvander(self) : # check for 1d x x = np.arange(3) v = herm.hermvander(x, 3) assert_(v.shape == (3, 4)) for i in range(4) : coef = [0]*i + [1] assert_almost_equal(v[..., i], herm.hermval(x, coef)) # check for 2d x x = np.array([[1, 2], [3, 4], [5, 6]]) v = herm.hermvander(x, 3) assert_(v.shape == (3, 2, 4)) for i in range(4) : coef = [0]*i + [1] assert_almost_equal(v[..., i], herm.hermval(x, coef)) def test_hermvander2d(self) : # also tests hermval2d for non-square coefficient array x1, x2, x3 = self.x c = np.random.random((2, 3)) van = herm.hermvander2d(x1, x2, [1, 2]) tgt = herm.hermval2d(x1, x2, c) res = np.dot(van, c.flat) assert_almost_equal(res, tgt) # check shape van = herm.hermvander2d([x1], [x2], [1, 2]) assert_(van.shape == (1, 5, 6)) def test_hermvander3d(self) : # also tests hermval3d for non-square coefficient array x1, x2, x3 = self.x c = np.random.random((2, 3, 4)) van = herm.hermvander3d(x1, x2, x3, [1, 2, 3]) tgt = herm.hermval3d(x1, x2, x3, c) res = np.dot(van, c.flat) assert_almost_equal(res, tgt) # check shape van = herm.hermvander3d([x1], [x2], [x3], [1, 2, 3]) assert_(van.shape == (1, 5, 24)) class TestFitting(TestCase): def test_hermfit(self) : def f(x) : return x*(x - 1)*(x - 2) # Test exceptions assert_raises(ValueError, herm.hermfit, [1], [1], -1) assert_raises(TypeError, herm.hermfit, [[1]], [1], 0) assert_raises(TypeError, herm.hermfit, [], [1], 0) assert_raises(TypeError, herm.hermfit, [1], [[[1]]], 0) assert_raises(TypeError, herm.hermfit, [1, 2], [1], 0) assert_raises(TypeError, herm.hermfit, [1], [1, 2], 0) assert_raises(TypeError, herm.hermfit, [1], [1], 0, w=[[1]]) assert_raises(TypeError, herm.hermfit, [1], [1], 0, w=[1, 1]) # Test fit x = np.linspace(0, 2) y = f(x) # coef3 = herm.hermfit(x, y, 3) assert_equal(len(coef3), 4) assert_almost_equal(herm.hermval(x, coef3), y) # coef4 = herm.hermfit(x, y, 4) assert_equal(len(coef4), 5) assert_almost_equal(herm.hermval(x, coef4), y) # coef2d = herm.hermfit(x, np.array([y, y]).T, 3) assert_almost_equal(coef2d, np.array([coef3, coef3]).T) # test weighting w = np.zeros_like(x) yw = y.copy() w[1::2] = 1 y[0::2] = 0 wcoef3 = herm.hermfit(x, yw, 3, w=w) assert_almost_equal(wcoef3, coef3) # wcoef2d = herm.hermfit(x, np.array([yw, yw]).T, 3, w=w) assert_almost_equal(wcoef2d, np.array([coef3, coef3]).T) # test scaling with complex values x points whose square # is zero when summed. x = [1, 1j, -1, -1j] assert_almost_equal(herm.hermfit(x, x, 1), [0, .5]) class TestCompanion(TestCase): def test_raises(self): assert_raises(ValueError, herm.hermcompanion, []) assert_raises(ValueError, herm.hermcompanion, [1]) def test_dimensions(self): for i in range(1, 5): coef = [0]*i + [1] assert_(herm.hermcompanion(coef).shape == (i, i)) def test_linear_root(self): assert_(herm.hermcompanion([1, 2])[0, 0] == -.25) class TestGauss(TestCase): def test_100(self): x, w = herm.hermgauss(100) # test orthogonality. Note that the results need to be normalized, # otherwise the huge values that can arise from fast growing # functions like Laguerre can be very confusing. v = herm.hermvander(x, 99) vv = np.dot(v.T * w, v) vd = 1/np.sqrt(vv.diagonal()) vv = vd[:, None] * vv * vd assert_almost_equal(vv, np.eye(100)) # check that the integral of 1 is correct tgt = np.sqrt(np.pi) assert_almost_equal(w.sum(), tgt) class TestMisc(TestCase) : def test_hermfromroots(self) : res = herm.hermfromroots([]) assert_almost_equal(trim(res), [1]) for i in range(1, 5) : roots = np.cos(np.linspace(-np.pi, 0, 2*i + 1)[1::2]) pol = herm.hermfromroots(roots) res = herm.hermval(roots, pol) tgt = 0 assert_(len(pol) == i + 1) assert_almost_equal(herm.herm2poly(pol)[-1], 1) assert_almost_equal(res, tgt) def test_hermroots(self) : assert_almost_equal(herm.hermroots([1]), []) assert_almost_equal(herm.hermroots([1, 1]), [-.5]) for i in range(2, 5) : tgt = np.linspace(-1, 1, i) res = herm.hermroots(herm.hermfromroots(tgt)) assert_almost_equal(trim(res), trim(tgt)) def test_hermtrim(self) : coef = [2, -1, 1, 0] # Test exceptions assert_raises(ValueError, herm.hermtrim, coef, -1) # Test results assert_equal(herm.hermtrim(coef), coef[:-1]) assert_equal(herm.hermtrim(coef, 1), coef[:-3]) assert_equal(herm.hermtrim(coef, 2), [0]) def test_hermline(self) : assert_equal(herm.hermline(3, 4), [3, 2]) def test_herm2poly(self) : for i in range(10) : assert_almost_equal(herm.herm2poly([0]*i + [1]), Hlist[i]) def test_poly2herm(self) : for i in range(10) : assert_almost_equal(herm.poly2herm(Hlist[i]), [0]*i + [1]) def test_weight(self): x = np.linspace(-5, 5, 11) tgt = np.exp(-x**2) res = herm.hermweight(x) assert_almost_equal(res, tgt) if __name__ == "__main__": run_module_suite() numpy-1.8.2/numpy/polynomial/tests/test_hermite_e.py0000664000175100017510000004133712370216243024103 0ustar vagrantvagrant00000000000000"""Tests for hermite_e module. """ from __future__ import division, absolute_import, print_function import numpy as np import numpy.polynomial.hermite_e as herme from numpy.polynomial.polynomial import polyval from numpy.testing import * He0 = np.array([ 1 ]) He1 = np.array([ 0, 1 ]) He2 = np.array([ -1, 0, 1 ]) He3 = np.array([ 0, -3, 0, 1 ]) He4 = np.array([ 3, 0, -6, 0, 1 ]) He5 = np.array([ 0, 15, 0, -10, 0, 1 ]) He6 = np.array([ -15, 0, 45, 0, -15, 0, 1 ]) He7 = np.array([ 0, -105, 0, 105, 0, -21, 0, 1 ]) He8 = np.array([ 105, 0, -420, 0, 210, 0, -28, 0, 1 ]) He9 = np.array([ 0, 945, 0, -1260, 0, 378, 0, -36, 0, 1 ]) Helist = [He0, He1, He2, He3, He4, He5, He6, He7, He8, He9] def trim(x) : return herme.hermetrim(x, tol=1e-6) class TestConstants(TestCase) : def test_hermedomain(self) : assert_equal(herme.hermedomain, [-1, 1]) def test_hermezero(self) : assert_equal(herme.hermezero, [0]) def test_hermeone(self) : assert_equal(herme.hermeone, [1]) def test_hermex(self) : assert_equal(herme.hermex, [0, 1]) class TestArithmetic(TestCase) : x = np.linspace(-3, 3, 100) def test_hermeadd(self) : for i in range(5) : for j in range(5) : msg = "At i=%d, j=%d" % (i, j) tgt = np.zeros(max(i, j) + 1) tgt[i] += 1 tgt[j] += 1 res = herme.hermeadd([0]*i + [1], [0]*j + [1]) assert_equal(trim(res), trim(tgt), err_msg=msg) def test_hermesub(self) : for i in range(5) : for j in range(5) : msg = "At i=%d, j=%d" % (i, j) tgt = np.zeros(max(i, j) + 1) tgt[i] += 1 tgt[j] -= 1 res = herme.hermesub([0]*i + [1], [0]*j + [1]) assert_equal(trim(res), trim(tgt), err_msg=msg) def test_hermemulx(self): assert_equal(herme.hermemulx([0]), [0]) assert_equal(herme.hermemulx([1]), [0, 1]) for i in range(1, 5): ser = [0]*i + [1] tgt = [0]*(i - 1) + [i, 0, 1] assert_equal(herme.hermemulx(ser), tgt) def test_hermemul(self) : # check values of result for i in range(5) : pol1 = [0]*i + [1] val1 = herme.hermeval(self.x, pol1) for j in range(5) : msg = "At i=%d, j=%d" % (i, j) pol2 = [0]*j + [1] val2 = herme.hermeval(self.x, pol2) pol3 = herme.hermemul(pol1, pol2) val3 = herme.hermeval(self.x, pol3) assert_(len(pol3) == i + j + 1, msg) assert_almost_equal(val3, val1*val2, err_msg=msg) def test_hermediv(self) : for i in range(5) : for j in range(5) : msg = "At i=%d, j=%d" % (i, j) ci = [0]*i + [1] cj = [0]*j + [1] tgt = herme.hermeadd(ci, cj) quo, rem = herme.hermediv(tgt, ci) res = herme.hermeadd(herme.hermemul(quo, ci), rem) assert_equal(trim(res), trim(tgt), err_msg=msg) class TestEvaluation(TestCase) : # coefficients of 1 + 2*x + 3*x**2 c1d = np.array([4., 2., 3.]) c2d = np.einsum('i,j->ij', c1d, c1d) c3d = np.einsum('i,j,k->ijk', c1d, c1d, c1d) # some random values in [-1, 1) x = np.random.random((3, 5))*2 - 1 y = polyval(x, [1., 2., 3.]) def test_hermeval(self) : #check empty input assert_equal(herme.hermeval([], [1]).size, 0) #check normal input) x = np.linspace(-1, 1) y = [polyval(x, c) for c in Helist] for i in range(10) : msg = "At i=%d" % i ser = np.zeros tgt = y[i] res = herme.hermeval(x, [0]*i + [1]) assert_almost_equal(res, tgt, err_msg=msg) #check that shape is preserved for i in range(3) : dims = [2]*i x = np.zeros(dims) assert_equal(herme.hermeval(x, [1]).shape, dims) assert_equal(herme.hermeval(x, [1, 0]).shape, dims) assert_equal(herme.hermeval(x, [1, 0, 0]).shape, dims) def test_hermeval2d(self): x1, x2, x3 = self.x y1, y2, y3 = self.y #test exceptions assert_raises(ValueError, herme.hermeval2d, x1, x2[:2], self.c2d) #test values tgt = y1*y2 res = herme.hermeval2d(x1, x2, self.c2d) assert_almost_equal(res, tgt) #test shape z = np.ones((2, 3)) res = herme.hermeval2d(z, z, self.c2d) assert_(res.shape == (2, 3)) def test_hermeval3d(self): x1, x2, x3 = self.x y1, y2, y3 = self.y #test exceptions assert_raises(ValueError, herme.hermeval3d, x1, x2, x3[:2], self.c3d) #test values tgt = y1*y2*y3 res = herme.hermeval3d(x1, x2, x3, self.c3d) assert_almost_equal(res, tgt) #test shape z = np.ones((2, 3)) res = herme.hermeval3d(z, z, z, self.c3d) assert_(res.shape == (2, 3)) def test_hermegrid2d(self): x1, x2, x3 = self.x y1, y2, y3 = self.y #test values tgt = np.einsum('i,j->ij', y1, y2) res = herme.hermegrid2d(x1, x2, self.c2d) assert_almost_equal(res, tgt) #test shape z = np.ones((2, 3)) res = herme.hermegrid2d(z, z, self.c2d) assert_(res.shape == (2, 3)*2) def test_hermegrid3d(self): x1, x2, x3 = self.x y1, y2, y3 = self.y #test values tgt = np.einsum('i,j,k->ijk', y1, y2, y3) res = herme.hermegrid3d(x1, x2, x3, self.c3d) assert_almost_equal(res, tgt) #test shape z = np.ones((2, 3)) res = herme.hermegrid3d(z, z, z, self.c3d) assert_(res.shape == (2, 3)*3) class TestIntegral(TestCase): def test_hermeint(self) : # check exceptions assert_raises(ValueError, herme.hermeint, [0], .5) assert_raises(ValueError, herme.hermeint, [0], -1) assert_raises(ValueError, herme.hermeint, [0], 1, [0, 0]) # test integration of zero polynomial for i in range(2, 5): k = [0]*(i - 2) + [1] res = herme.hermeint([0], m=i, k=k) assert_almost_equal(res, [0, 1]) # check single integration with integration constant for i in range(5) : scl = i + 1 pol = [0]*i + [1] tgt = [i] + [0]*i + [1/scl] hermepol = herme.poly2herme(pol) hermeint = herme.hermeint(hermepol, m=1, k=[i]) res = herme.herme2poly(hermeint) assert_almost_equal(trim(res), trim(tgt)) # check single integration with integration constant and lbnd for i in range(5) : scl = i + 1 pol = [0]*i + [1] hermepol = herme.poly2herme(pol) hermeint = herme.hermeint(hermepol, m=1, k=[i], lbnd=-1) assert_almost_equal(herme.hermeval(-1, hermeint), i) # check single integration with integration constant and scaling for i in range(5) : scl = i + 1 pol = [0]*i + [1] tgt = [i] + [0]*i + [2/scl] hermepol = herme.poly2herme(pol) hermeint = herme.hermeint(hermepol, m=1, k=[i], scl=2) res = herme.herme2poly(hermeint) assert_almost_equal(trim(res), trim(tgt)) # check multiple integrations with default k for i in range(5) : for j in range(2, 5) : pol = [0]*i + [1] tgt = pol[:] for k in range(j) : tgt = herme.hermeint(tgt, m=1) res = herme.hermeint(pol, m=j) assert_almost_equal(trim(res), trim(tgt)) # check multiple integrations with defined k for i in range(5) : for j in range(2, 5) : pol = [0]*i + [1] tgt = pol[:] for k in range(j) : tgt = herme.hermeint(tgt, m=1, k=[k]) res = herme.hermeint(pol, m=j, k=list(range(j))) assert_almost_equal(trim(res), trim(tgt)) # check multiple integrations with lbnd for i in range(5) : for j in range(2, 5) : pol = [0]*i + [1] tgt = pol[:] for k in range(j) : tgt = herme.hermeint(tgt, m=1, k=[k], lbnd=-1) res = herme.hermeint(pol, m=j, k=list(range(j)), lbnd=-1) assert_almost_equal(trim(res), trim(tgt)) # check multiple integrations with scaling for i in range(5) : for j in range(2, 5) : pol = [0]*i + [1] tgt = pol[:] for k in range(j) : tgt = herme.hermeint(tgt, m=1, k=[k], scl=2) res = herme.hermeint(pol, m=j, k=list(range(j)), scl=2) assert_almost_equal(trim(res), trim(tgt)) def test_hermeint_axis(self): # check that axis keyword works c2d = np.random.random((3, 4)) tgt = np.vstack([herme.hermeint(c) for c in c2d.T]).T res = herme.hermeint(c2d, axis=0) assert_almost_equal(res, tgt) tgt = np.vstack([herme.hermeint(c) for c in c2d]) res = herme.hermeint(c2d, axis=1) assert_almost_equal(res, tgt) tgt = np.vstack([herme.hermeint(c, k=3) for c in c2d]) res = herme.hermeint(c2d, k=3, axis=1) assert_almost_equal(res, tgt) class TestDerivative(TestCase) : def test_hermeder(self) : # check exceptions assert_raises(ValueError, herme.hermeder, [0], .5) assert_raises(ValueError, herme.hermeder, [0], -1) # check that zeroth deriviative does nothing for i in range(5) : tgt = [0]*i + [1] res = herme.hermeder(tgt, m=0) assert_equal(trim(res), trim(tgt)) # check that derivation is the inverse of integration for i in range(5) : for j in range(2, 5) : tgt = [0]*i + [1] res = herme.hermeder(herme.hermeint(tgt, m=j), m=j) assert_almost_equal(trim(res), trim(tgt)) # check derivation with scaling for i in range(5) : for j in range(2, 5) : tgt = [0]*i + [1] res = herme.hermeder(herme.hermeint(tgt, m=j, scl=2), m=j, scl=.5) assert_almost_equal(trim(res), trim(tgt)) def test_hermeder_axis(self): # check that axis keyword works c2d = np.random.random((3, 4)) tgt = np.vstack([herme.hermeder(c) for c in c2d.T]).T res = herme.hermeder(c2d, axis=0) assert_almost_equal(res, tgt) tgt = np.vstack([herme.hermeder(c) for c in c2d]) res = herme.hermeder(c2d, axis=1) assert_almost_equal(res, tgt) class TestVander(TestCase): # some random values in [-1, 1) x = np.random.random((3, 5))*2 - 1 def test_hermevander(self) : # check for 1d x x = np.arange(3) v = herme.hermevander(x, 3) assert_(v.shape == (3, 4)) for i in range(4) : coef = [0]*i + [1] assert_almost_equal(v[..., i], herme.hermeval(x, coef)) # check for 2d x x = np.array([[1, 2], [3, 4], [5, 6]]) v = herme.hermevander(x, 3) assert_(v.shape == (3, 2, 4)) for i in range(4) : coef = [0]*i + [1] assert_almost_equal(v[..., i], herme.hermeval(x, coef)) def test_hermevander2d(self) : # also tests hermeval2d for non-square coefficient array x1, x2, x3 = self.x c = np.random.random((2, 3)) van = herme.hermevander2d(x1, x2, [1, 2]) tgt = herme.hermeval2d(x1, x2, c) res = np.dot(van, c.flat) assert_almost_equal(res, tgt) # check shape van = herme.hermevander2d([x1], [x2], [1, 2]) assert_(van.shape == (1, 5, 6)) def test_hermevander3d(self) : # also tests hermeval3d for non-square coefficient array x1, x2, x3 = self.x c = np.random.random((2, 3, 4)) van = herme.hermevander3d(x1, x2, x3, [1, 2, 3]) tgt = herme.hermeval3d(x1, x2, x3, c) res = np.dot(van, c.flat) assert_almost_equal(res, tgt) # check shape van = herme.hermevander3d([x1], [x2], [x3], [1, 2, 3]) assert_(van.shape == (1, 5, 24)) class TestFitting(TestCase): def test_hermefit(self) : def f(x) : return x*(x - 1)*(x - 2) # Test exceptions assert_raises(ValueError, herme.hermefit, [1], [1], -1) assert_raises(TypeError, herme.hermefit, [[1]], [1], 0) assert_raises(TypeError, herme.hermefit, [], [1], 0) assert_raises(TypeError, herme.hermefit, [1], [[[1]]], 0) assert_raises(TypeError, herme.hermefit, [1, 2], [1], 0) assert_raises(TypeError, herme.hermefit, [1], [1, 2], 0) assert_raises(TypeError, herme.hermefit, [1], [1], 0, w=[[1]]) assert_raises(TypeError, herme.hermefit, [1], [1], 0, w=[1, 1]) # Test fit x = np.linspace(0, 2) y = f(x) # coef3 = herme.hermefit(x, y, 3) assert_equal(len(coef3), 4) assert_almost_equal(herme.hermeval(x, coef3), y) # coef4 = herme.hermefit(x, y, 4) assert_equal(len(coef4), 5) assert_almost_equal(herme.hermeval(x, coef4), y) # coef2d = herme.hermefit(x, np.array([y, y]).T, 3) assert_almost_equal(coef2d, np.array([coef3, coef3]).T) # test weighting w = np.zeros_like(x) yw = y.copy() w[1::2] = 1 y[0::2] = 0 wcoef3 = herme.hermefit(x, yw, 3, w=w) assert_almost_equal(wcoef3, coef3) # wcoef2d = herme.hermefit(x, np.array([yw, yw]).T, 3, w=w) assert_almost_equal(wcoef2d, np.array([coef3, coef3]).T) # test scaling with complex values x points whose square # is zero when summed. x = [1, 1j, -1, -1j] assert_almost_equal(herme.hermefit(x, x, 1), [0, 1]) class TestCompanion(TestCase): def test_raises(self): assert_raises(ValueError, herme.hermecompanion, []) assert_raises(ValueError, herme.hermecompanion, [1]) def test_dimensions(self): for i in range(1, 5): coef = [0]*i + [1] assert_(herme.hermecompanion(coef).shape == (i, i)) def test_linear_root(self): assert_(herme.hermecompanion([1, 2])[0, 0] == -.5) class TestGauss(TestCase): def test_100(self): x, w = herme.hermegauss(100) # test orthogonality. Note that the results need to be normalized, # otherwise the huge values that can arise from fast growing # functions like Laguerre can be very confusing. v = herme.hermevander(x, 99) vv = np.dot(v.T * w, v) vd = 1/np.sqrt(vv.diagonal()) vv = vd[:, None] * vv * vd assert_almost_equal(vv, np.eye(100)) # check that the integral of 1 is correct tgt = np.sqrt(2*np.pi) assert_almost_equal(w.sum(), tgt) class TestMisc(TestCase) : def test_hermefromroots(self) : res = herme.hermefromroots([]) assert_almost_equal(trim(res), [1]) for i in range(1, 5) : roots = np.cos(np.linspace(-np.pi, 0, 2*i + 1)[1::2]) pol = herme.hermefromroots(roots) res = herme.hermeval(roots, pol) tgt = 0 assert_(len(pol) == i + 1) assert_almost_equal(herme.herme2poly(pol)[-1], 1) assert_almost_equal(res, tgt) def test_hermeroots(self) : assert_almost_equal(herme.hermeroots([1]), []) assert_almost_equal(herme.hermeroots([1, 1]), [-1]) for i in range(2, 5) : tgt = np.linspace(-1, 1, i) res = herme.hermeroots(herme.hermefromroots(tgt)) assert_almost_equal(trim(res), trim(tgt)) def test_hermetrim(self) : coef = [2, -1, 1, 0] # Test exceptions assert_raises(ValueError, herme.hermetrim, coef, -1) # Test results assert_equal(herme.hermetrim(coef), coef[:-1]) assert_equal(herme.hermetrim(coef, 1), coef[:-3]) assert_equal(herme.hermetrim(coef, 2), [0]) def test_hermeline(self) : assert_equal(herme.hermeline(3, 4), [3, 4]) def test_herme2poly(self) : for i in range(10) : assert_almost_equal(herme.herme2poly([0]*i + [1]), Helist[i]) def test_poly2herme(self) : for i in range(10) : assert_almost_equal(herme.poly2herme(Helist[i]), [0]*i + [1]) def test_weight(self): x = np.linspace(-5, 5, 11) tgt = np.exp(-.5*x**2) res = herme.hermeweight(x) assert_almost_equal(res, tgt) if __name__ == "__main__": run_module_suite() numpy-1.8.2/numpy/polynomial/tests/test_polyutils.py0000664000175100017510000000561612370216243024206 0ustar vagrantvagrant00000000000000"""Tests for polyutils module. """ from __future__ import division, absolute_import, print_function import numpy as np import numpy.polynomial.polyutils as pu from numpy.testing import * class TestMisc(TestCase) : def test_trimseq(self) : for i in range(5) : tgt = [1] res = pu.trimseq([1] + [0]*5) assert_equal(res, tgt) def test_as_series(self) : # check exceptions assert_raises(ValueError, pu.as_series, [[]]) assert_raises(ValueError, pu.as_series, [[[1, 2]]]) assert_raises(ValueError, pu.as_series, [[1], ['a']]) # check common types types = ['i', 'd', 'O'] for i in range(len(types)) : for j in range(i) : ci = np.ones(1, types[i]) cj = np.ones(1, types[j]) [resi, resj] = pu.as_series([ci, cj]) assert_(resi.dtype.char == resj.dtype.char) assert_(resj.dtype.char == types[i]) def test_trimcoef(self) : coef = [2, -1, 1, 0] # Test exceptions assert_raises(ValueError, pu.trimcoef, coef, -1) # Test results assert_equal(pu.trimcoef(coef), coef[:-1]) assert_equal(pu.trimcoef(coef, 1), coef[:-3]) assert_equal(pu.trimcoef(coef, 2), [0]) class TestDomain(TestCase) : def test_getdomain(self) : # test for real values x = [1, 10, 3, -1] tgt = [-1, 10] res = pu.getdomain(x) assert_almost_equal(res, tgt) # test for complex values x = [1 + 1j, 1 - 1j, 0, 2] tgt = [-1j, 2 + 1j] res = pu.getdomain(x) assert_almost_equal(res, tgt) def test_mapdomain(self) : # test for real values dom1 = [0, 4] dom2 = [1, 3] tgt = dom2 res = pu. mapdomain(dom1, dom1, dom2) assert_almost_equal(res, tgt) # test for complex values dom1 = [0 - 1j, 2 + 1j] dom2 = [-2, 2] tgt = dom2 x = dom1 res = pu.mapdomain(x, dom1, dom2) assert_almost_equal(res, tgt) # test for multidimensional arrays dom1 = [0, 4] dom2 = [1, 3] tgt = np.array([dom2, dom2]) x = np.array([dom1, dom1]) res = pu.mapdomain(x, dom1, dom2) assert_almost_equal(res, tgt) # test that subtypes are preserved. dom1 = [0, 4] dom2 = [1, 3] x = np.matrix([dom1, dom1]) res = pu.mapdomain(x, dom1, dom2) assert_(isinstance(res, np.matrix)) def test_mapparms(self) : # test for real values dom1 = [0, 4] dom2 = [1, 3] tgt = [1, .5] res = pu. mapparms(dom1, dom2) assert_almost_equal(res, tgt) # test for complex values dom1 = [0 - 1j, 2 + 1j] dom2 = [-2, 2] tgt = [-1 + 1j, 1 - 1j] res = pu.mapparms(dom1, dom2) assert_almost_equal(res, tgt) numpy-1.8.2/numpy/polynomial/tests/test_legendre.py0000664000175100017510000004055712370216243023732 0ustar vagrantvagrant00000000000000"""Tests for legendre module. """ from __future__ import division, absolute_import, print_function import numpy as np import numpy.polynomial.legendre as leg from numpy.polynomial.polynomial import polyval from numpy.testing import ( TestCase, assert_almost_equal, assert_raises, assert_equal, assert_, run_module_suite) L0 = np.array([ 1]) L1 = np.array([ 0, 1]) L2 = np.array([-1, 0, 3])/2 L3 = np.array([ 0, -3, 0, 5])/2 L4 = np.array([ 3, 0, -30, 0, 35])/8 L5 = np.array([ 0, 15, 0, -70, 0, 63])/8 L6 = np.array([-5, 0, 105, 0, -315, 0, 231])/16 L7 = np.array([ 0, -35, 0, 315, 0, -693, 0, 429])/16 L8 = np.array([35, 0, -1260, 0, 6930, 0, -12012, 0, 6435])/128 L9 = np.array([ 0, 315, 0, -4620, 0, 18018, 0, -25740, 0, 12155])/128 Llist = [L0, L1, L2, L3, L4, L5, L6, L7, L8, L9] def trim(x) : return leg.legtrim(x, tol=1e-6) class TestConstants(TestCase) : def test_legdomain(self) : assert_equal(leg.legdomain, [-1, 1]) def test_legzero(self) : assert_equal(leg.legzero, [0]) def test_legone(self) : assert_equal(leg.legone, [1]) def test_legx(self) : assert_equal(leg.legx, [0, 1]) class TestArithmetic(TestCase) : x = np.linspace(-1, 1, 100) def test_legadd(self) : for i in range(5) : for j in range(5) : msg = "At i=%d, j=%d" % (i, j) tgt = np.zeros(max(i, j) + 1) tgt[i] += 1 tgt[j] += 1 res = leg.legadd([0]*i + [1], [0]*j + [1]) assert_equal(trim(res), trim(tgt), err_msg=msg) def test_legsub(self) : for i in range(5) : for j in range(5) : msg = "At i=%d, j=%d" % (i, j) tgt = np.zeros(max(i, j) + 1) tgt[i] += 1 tgt[j] -= 1 res = leg.legsub([0]*i + [1], [0]*j + [1]) assert_equal(trim(res), trim(tgt), err_msg=msg) def test_legmulx(self): assert_equal(leg.legmulx([0]), [0]) assert_equal(leg.legmulx([1]), [0, 1]) for i in range(1, 5): tmp = 2*i + 1 ser = [0]*i + [1] tgt = [0]*(i - 1) + [i/tmp, 0, (i + 1)/tmp] assert_equal(leg.legmulx(ser), tgt) def test_legmul(self) : # check values of result for i in range(5) : pol1 = [0]*i + [1] val1 = leg.legval(self.x, pol1) for j in range(5) : msg = "At i=%d, j=%d" % (i, j) pol2 = [0]*j + [1] val2 = leg.legval(self.x, pol2) pol3 = leg.legmul(pol1, pol2) val3 = leg.legval(self.x, pol3) assert_(len(pol3) == i + j + 1, msg) assert_almost_equal(val3, val1*val2, err_msg=msg) def test_legdiv(self) : for i in range(5) : for j in range(5) : msg = "At i=%d, j=%d" % (i, j) ci = [0]*i + [1] cj = [0]*j + [1] tgt = leg.legadd(ci, cj) quo, rem = leg.legdiv(tgt, ci) res = leg.legadd(leg.legmul(quo, ci), rem) assert_equal(trim(res), trim(tgt), err_msg=msg) class TestEvaluation(TestCase) : # coefficients of 1 + 2*x + 3*x**2 c1d = np.array([2., 2., 2.]) c2d = np.einsum('i,j->ij', c1d, c1d) c3d = np.einsum('i,j,k->ijk', c1d, c1d, c1d) # some random values in [-1, 1) x = np.random.random((3, 5))*2 - 1 y = polyval(x, [1., 2., 3.]) def test_legval(self) : #check empty input assert_equal(leg.legval([], [1]).size, 0) #check normal input) x = np.linspace(-1, 1) y = [polyval(x, c) for c in Llist] for i in range(10) : msg = "At i=%d" % i ser = np.zeros tgt = y[i] res = leg.legval(x, [0]*i + [1]) assert_almost_equal(res, tgt, err_msg=msg) #check that shape is preserved for i in range(3) : dims = [2]*i x = np.zeros(dims) assert_equal(leg.legval(x, [1]).shape, dims) assert_equal(leg.legval(x, [1, 0]).shape, dims) assert_equal(leg.legval(x, [1, 0, 0]).shape, dims) def test_legval2d(self): x1, x2, x3 = self.x y1, y2, y3 = self.y #test exceptions assert_raises(ValueError, leg.legval2d, x1, x2[:2], self.c2d) #test values tgt = y1*y2 res = leg.legval2d(x1, x2, self.c2d) assert_almost_equal(res, tgt) #test shape z = np.ones((2, 3)) res = leg.legval2d(z, z, self.c2d) assert_(res.shape == (2, 3)) def test_legval3d(self): x1, x2, x3 = self.x y1, y2, y3 = self.y #test exceptions assert_raises(ValueError, leg.legval3d, x1, x2, x3[:2], self.c3d) #test values tgt = y1*y2*y3 res = leg.legval3d(x1, x2, x3, self.c3d) assert_almost_equal(res, tgt) #test shape z = np.ones((2, 3)) res = leg.legval3d(z, z, z, self.c3d) assert_(res.shape == (2, 3)) def test_leggrid2d(self): x1, x2, x3 = self.x y1, y2, y3 = self.y #test values tgt = np.einsum('i,j->ij', y1, y2) res = leg.leggrid2d(x1, x2, self.c2d) assert_almost_equal(res, tgt) #test shape z = np.ones((2, 3)) res = leg.leggrid2d(z, z, self.c2d) assert_(res.shape == (2, 3)*2) def test_leggrid3d(self): x1, x2, x3 = self.x y1, y2, y3 = self.y #test values tgt = np.einsum('i,j,k->ijk', y1, y2, y3) res = leg.leggrid3d(x1, x2, x3, self.c3d) assert_almost_equal(res, tgt) #test shape z = np.ones((2, 3)) res = leg.leggrid3d(z, z, z, self.c3d) assert_(res.shape == (2, 3)*3) class TestIntegral(TestCase) : def test_legint(self) : # check exceptions assert_raises(ValueError, leg.legint, [0], .5) assert_raises(ValueError, leg.legint, [0], -1) assert_raises(ValueError, leg.legint, [0], 1, [0, 0]) # test integration of zero polynomial for i in range(2, 5): k = [0]*(i - 2) + [1] res = leg.legint([0], m=i, k=k) assert_almost_equal(res, [0, 1]) # check single integration with integration constant for i in range(5) : scl = i + 1 pol = [0]*i + [1] tgt = [i] + [0]*i + [1/scl] legpol = leg.poly2leg(pol) legint = leg.legint(legpol, m=1, k=[i]) res = leg.leg2poly(legint) assert_almost_equal(trim(res), trim(tgt)) # check single integration with integration constant and lbnd for i in range(5) : scl = i + 1 pol = [0]*i + [1] legpol = leg.poly2leg(pol) legint = leg.legint(legpol, m=1, k=[i], lbnd=-1) assert_almost_equal(leg.legval(-1, legint), i) # check single integration with integration constant and scaling for i in range(5) : scl = i + 1 pol = [0]*i + [1] tgt = [i] + [0]*i + [2/scl] legpol = leg.poly2leg(pol) legint = leg.legint(legpol, m=1, k=[i], scl=2) res = leg.leg2poly(legint) assert_almost_equal(trim(res), trim(tgt)) # check multiple integrations with default k for i in range(5) : for j in range(2, 5) : pol = [0]*i + [1] tgt = pol[:] for k in range(j) : tgt = leg.legint(tgt, m=1) res = leg.legint(pol, m=j) assert_almost_equal(trim(res), trim(tgt)) # check multiple integrations with defined k for i in range(5) : for j in range(2, 5) : pol = [0]*i + [1] tgt = pol[:] for k in range(j) : tgt = leg.legint(tgt, m=1, k=[k]) res = leg.legint(pol, m=j, k=list(range(j))) assert_almost_equal(trim(res), trim(tgt)) # check multiple integrations with lbnd for i in range(5) : for j in range(2, 5) : pol = [0]*i + [1] tgt = pol[:] for k in range(j) : tgt = leg.legint(tgt, m=1, k=[k], lbnd=-1) res = leg.legint(pol, m=j, k=list(range(j)), lbnd=-1) assert_almost_equal(trim(res), trim(tgt)) # check multiple integrations with scaling for i in range(5) : for j in range(2, 5) : pol = [0]*i + [1] tgt = pol[:] for k in range(j) : tgt = leg.legint(tgt, m=1, k=[k], scl=2) res = leg.legint(pol, m=j, k=list(range(j)), scl=2) assert_almost_equal(trim(res), trim(tgt)) def test_legint_axis(self): # check that axis keyword works c2d = np.random.random((3, 4)) tgt = np.vstack([leg.legint(c) for c in c2d.T]).T res = leg.legint(c2d, axis=0) assert_almost_equal(res, tgt) tgt = np.vstack([leg.legint(c) for c in c2d]) res = leg.legint(c2d, axis=1) assert_almost_equal(res, tgt) tgt = np.vstack([leg.legint(c, k=3) for c in c2d]) res = leg.legint(c2d, k=3, axis=1) assert_almost_equal(res, tgt) class TestDerivative(TestCase) : def test_legder(self) : # check exceptions assert_raises(ValueError, leg.legder, [0], .5) assert_raises(ValueError, leg.legder, [0], -1) # check that zeroth deriviative does nothing for i in range(5) : tgt = [0]*i + [1] res = leg.legder(tgt, m=0) assert_equal(trim(res), trim(tgt)) # check that derivation is the inverse of integration for i in range(5) : for j in range(2, 5) : tgt = [0]*i + [1] res = leg.legder(leg.legint(tgt, m=j), m=j) assert_almost_equal(trim(res), trim(tgt)) # check derivation with scaling for i in range(5) : for j in range(2, 5) : tgt = [0]*i + [1] res = leg.legder(leg.legint(tgt, m=j, scl=2), m=j, scl=.5) assert_almost_equal(trim(res), trim(tgt)) def test_legder_axis(self): # check that axis keyword works c2d = np.random.random((3, 4)) tgt = np.vstack([leg.legder(c) for c in c2d.T]).T res = leg.legder(c2d, axis=0) assert_almost_equal(res, tgt) tgt = np.vstack([leg.legder(c) for c in c2d]) res = leg.legder(c2d, axis=1) assert_almost_equal(res, tgt) class TestVander(TestCase): # some random values in [-1, 1) x = np.random.random((3, 5))*2 - 1 def test_legvander(self) : # check for 1d x x = np.arange(3) v = leg.legvander(x, 3) assert_(v.shape == (3, 4)) for i in range(4) : coef = [0]*i + [1] assert_almost_equal(v[..., i], leg.legval(x, coef)) # check for 2d x x = np.array([[1, 2], [3, 4], [5, 6]]) v = leg.legvander(x, 3) assert_(v.shape == (3, 2, 4)) for i in range(4) : coef = [0]*i + [1] assert_almost_equal(v[..., i], leg.legval(x, coef)) def test_legvander2d(self) : # also tests polyval2d for non-square coefficient array x1, x2, x3 = self.x c = np.random.random((2, 3)) van = leg.legvander2d(x1, x2, [1, 2]) tgt = leg.legval2d(x1, x2, c) res = np.dot(van, c.flat) assert_almost_equal(res, tgt) # check shape van = leg.legvander2d([x1], [x2], [1, 2]) assert_(van.shape == (1, 5, 6)) def test_legvander3d(self) : # also tests polyval3d for non-square coefficient array x1, x2, x3 = self.x c = np.random.random((2, 3, 4)) van = leg.legvander3d(x1, x2, x3, [1, 2, 3]) tgt = leg.legval3d(x1, x2, x3, c) res = np.dot(van, c.flat) assert_almost_equal(res, tgt) # check shape van = leg.legvander3d([x1], [x2], [x3], [1, 2, 3]) assert_(van.shape == (1, 5, 24)) class TestFitting(TestCase): def test_legfit(self) : def f(x) : return x*(x - 1)*(x - 2) # Test exceptions assert_raises(ValueError, leg.legfit, [1], [1], -1) assert_raises(TypeError, leg.legfit, [[1]], [1], 0) assert_raises(TypeError, leg.legfit, [], [1], 0) assert_raises(TypeError, leg.legfit, [1], [[[1]]], 0) assert_raises(TypeError, leg.legfit, [1, 2], [1], 0) assert_raises(TypeError, leg.legfit, [1], [1, 2], 0) assert_raises(TypeError, leg.legfit, [1], [1], 0, w=[[1]]) assert_raises(TypeError, leg.legfit, [1], [1], 0, w=[1, 1]) # Test fit x = np.linspace(0, 2) y = f(x) # coef3 = leg.legfit(x, y, 3) assert_equal(len(coef3), 4) assert_almost_equal(leg.legval(x, coef3), y) # coef4 = leg.legfit(x, y, 4) assert_equal(len(coef4), 5) assert_almost_equal(leg.legval(x, coef4), y) # coef2d = leg.legfit(x, np.array([y, y]).T, 3) assert_almost_equal(coef2d, np.array([coef3, coef3]).T) # test weighting w = np.zeros_like(x) yw = y.copy() w[1::2] = 1 y[0::2] = 0 wcoef3 = leg.legfit(x, yw, 3, w=w) assert_almost_equal(wcoef3, coef3) # wcoef2d = leg.legfit(x, np.array([yw, yw]).T, 3, w=w) assert_almost_equal(wcoef2d, np.array([coef3, coef3]).T) # test scaling with complex values x points whose square # is zero when summed. x = [1, 1j, -1, -1j] assert_almost_equal(leg.legfit(x, x, 1), [0, 1]) class TestCompanion(TestCase): def test_raises(self): assert_raises(ValueError, leg.legcompanion, []) assert_raises(ValueError, leg.legcompanion, [1]) def test_dimensions(self): for i in range(1, 5): coef = [0]*i + [1] assert_(leg.legcompanion(coef).shape == (i, i)) def test_linear_root(self): assert_(leg.legcompanion([1, 2])[0, 0] == -.5) class TestGauss(TestCase): def test_100(self): x, w = leg.leggauss(100) # test orthogonality. Note that the results need to be normalized, # otherwise the huge values that can arise from fast growing # functions like Laguerre can be very confusing. v = leg.legvander(x, 99) vv = np.dot(v.T * w, v) vd = 1/np.sqrt(vv.diagonal()) vv = vd[:, None] * vv * vd assert_almost_equal(vv, np.eye(100)) # check that the integral of 1 is correct tgt = 2.0 assert_almost_equal(w.sum(), tgt) class TestMisc(TestCase) : def test_legfromroots(self) : res = leg.legfromroots([]) assert_almost_equal(trim(res), [1]) for i in range(1, 5) : roots = np.cos(np.linspace(-np.pi, 0, 2*i + 1)[1::2]) pol = leg.legfromroots(roots) res = leg.legval(roots, pol) tgt = 0 assert_(len(pol) == i + 1) assert_almost_equal(leg.leg2poly(pol)[-1], 1) assert_almost_equal(res, tgt) def test_legroots(self) : assert_almost_equal(leg.legroots([1]), []) assert_almost_equal(leg.legroots([1, 2]), [-.5]) for i in range(2, 5) : tgt = np.linspace(-1, 1, i) res = leg.legroots(leg.legfromroots(tgt)) assert_almost_equal(trim(res), trim(tgt)) def test_legtrim(self) : coef = [2, -1, 1, 0] # Test exceptions assert_raises(ValueError, leg.legtrim, coef, -1) # Test results assert_equal(leg.legtrim(coef), coef[:-1]) assert_equal(leg.legtrim(coef, 1), coef[:-3]) assert_equal(leg.legtrim(coef, 2), [0]) def test_legline(self) : assert_equal(leg.legline(3, 4), [3, 4]) def test_leg2poly(self) : for i in range(10) : assert_almost_equal(leg.leg2poly([0]*i + [1]), Llist[i]) def test_poly2leg(self) : for i in range(10) : assert_almost_equal(leg.poly2leg(Llist[i]), [0]*i + [1]) def test_weight(self): x = np.linspace(-1, 1, 11) tgt = 1. res = leg.legweight(x) assert_almost_equal(res, tgt) if __name__ == "__main__": run_module_suite() numpy-1.8.2/numpy/polynomial/tests/test_laguerre.py0000664000175100017510000004020012370216243023734 0ustar vagrantvagrant00000000000000"""Tests for laguerre module. """ from __future__ import division, absolute_import, print_function import numpy as np import numpy.polynomial.laguerre as lag from numpy.polynomial.polynomial import polyval from numpy.testing import ( TestCase, assert_almost_equal, assert_raises, assert_equal, assert_, run_module_suite) L0 = np.array([1 ])/1 L1 = np.array([1, -1 ])/1 L2 = np.array([2, -4, 1 ])/2 L3 = np.array([6, -18, 9, -1 ])/6 L4 = np.array([24, -96, 72, -16, 1 ])/24 L5 = np.array([120, -600, 600, -200, 25, -1 ])/120 L6 = np.array([720, -4320, 5400, -2400, 450, -36, 1 ])/720 Llist = [L0, L1, L2, L3, L4, L5, L6] def trim(x) : return lag.lagtrim(x, tol=1e-6) class TestConstants(TestCase) : def test_lagdomain(self) : assert_equal(lag.lagdomain, [0, 1]) def test_lagzero(self) : assert_equal(lag.lagzero, [0]) def test_lagone(self) : assert_equal(lag.lagone, [1]) def test_lagx(self) : assert_equal(lag.lagx, [1, -1]) class TestArithmetic(TestCase) : x = np.linspace(-3, 3, 100) def test_lagadd(self) : for i in range(5) : for j in range(5) : msg = "At i=%d, j=%d" % (i, j) tgt = np.zeros(max(i, j) + 1) tgt[i] += 1 tgt[j] += 1 res = lag.lagadd([0]*i + [1], [0]*j + [1]) assert_equal(trim(res), trim(tgt), err_msg=msg) def test_lagsub(self) : for i in range(5) : for j in range(5) : msg = "At i=%d, j=%d" % (i, j) tgt = np.zeros(max(i, j) + 1) tgt[i] += 1 tgt[j] -= 1 res = lag.lagsub([0]*i + [1], [0]*j + [1]) assert_equal(trim(res), trim(tgt), err_msg=msg) def test_lagmulx(self): assert_equal(lag.lagmulx([0]), [0]) assert_equal(lag.lagmulx([1]), [1, -1]) for i in range(1, 5): ser = [0]*i + [1] tgt = [0]*(i - 1) + [-i, 2*i + 1, -(i + 1)] assert_almost_equal(lag.lagmulx(ser), tgt) def test_lagmul(self) : # check values of result for i in range(5) : pol1 = [0]*i + [1] val1 = lag.lagval(self.x, pol1) for j in range(5) : msg = "At i=%d, j=%d" % (i, j) pol2 = [0]*j + [1] val2 = lag.lagval(self.x, pol2) pol3 = lag.lagmul(pol1, pol2) val3 = lag.lagval(self.x, pol3) assert_(len(pol3) == i + j + 1, msg) assert_almost_equal(val3, val1*val2, err_msg=msg) def test_lagdiv(self) : for i in range(5) : for j in range(5) : msg = "At i=%d, j=%d" % (i, j) ci = [0]*i + [1] cj = [0]*j + [1] tgt = lag.lagadd(ci, cj) quo, rem = lag.lagdiv(tgt, ci) res = lag.lagadd(lag.lagmul(quo, ci), rem) assert_almost_equal(trim(res), trim(tgt), err_msg=msg) class TestEvaluation(TestCase) : # coefficients of 1 + 2*x + 3*x**2 c1d = np.array([9., -14., 6.]) c2d = np.einsum('i,j->ij', c1d, c1d) c3d = np.einsum('i,j,k->ijk', c1d, c1d, c1d) # some random values in [-1, 1) x = np.random.random((3, 5))*2 - 1 y = polyval(x, [1., 2., 3.]) def test_lagval(self) : #check empty input assert_equal(lag.lagval([], [1]).size, 0) #check normal input) x = np.linspace(-1, 1) y = [polyval(x, c) for c in Llist] for i in range(7) : msg = "At i=%d" % i ser = np.zeros tgt = y[i] res = lag.lagval(x, [0]*i + [1]) assert_almost_equal(res, tgt, err_msg=msg) #check that shape is preserved for i in range(3) : dims = [2]*i x = np.zeros(dims) assert_equal(lag.lagval(x, [1]).shape, dims) assert_equal(lag.lagval(x, [1, 0]).shape, dims) assert_equal(lag.lagval(x, [1, 0, 0]).shape, dims) def test_lagval2d(self): x1, x2, x3 = self.x y1, y2, y3 = self.y #test exceptions assert_raises(ValueError, lag.lagval2d, x1, x2[:2], self.c2d) #test values tgt = y1*y2 res = lag.lagval2d(x1, x2, self.c2d) assert_almost_equal(res, tgt) #test shape z = np.ones((2, 3)) res = lag.lagval2d(z, z, self.c2d) assert_(res.shape == (2, 3)) def test_lagval3d(self): x1, x2, x3 = self.x y1, y2, y3 = self.y #test exceptions assert_raises(ValueError, lag.lagval3d, x1, x2, x3[:2], self.c3d) #test values tgt = y1*y2*y3 res = lag.lagval3d(x1, x2, x3, self.c3d) assert_almost_equal(res, tgt) #test shape z = np.ones((2, 3)) res = lag.lagval3d(z, z, z, self.c3d) assert_(res.shape == (2, 3)) def test_laggrid2d(self): x1, x2, x3 = self.x y1, y2, y3 = self.y #test values tgt = np.einsum('i,j->ij', y1, y2) res = lag.laggrid2d(x1, x2, self.c2d) assert_almost_equal(res, tgt) #test shape z = np.ones((2, 3)) res = lag.laggrid2d(z, z, self.c2d) assert_(res.shape == (2, 3)*2) def test_laggrid3d(self): x1, x2, x3 = self.x y1, y2, y3 = self.y #test values tgt = np.einsum('i,j,k->ijk', y1, y2, y3) res = lag.laggrid3d(x1, x2, x3, self.c3d) assert_almost_equal(res, tgt) #test shape z = np.ones((2, 3)) res = lag.laggrid3d(z, z, z, self.c3d) assert_(res.shape == (2, 3)*3) class TestIntegral(TestCase) : def test_lagint(self) : # check exceptions assert_raises(ValueError, lag.lagint, [0], .5) assert_raises(ValueError, lag.lagint, [0], -1) assert_raises(ValueError, lag.lagint, [0], 1, [0, 0]) # test integration of zero polynomial for i in range(2, 5): k = [0]*(i - 2) + [1] res = lag.lagint([0], m=i, k=k) assert_almost_equal(res, [1, -1]) # check single integration with integration constant for i in range(5) : scl = i + 1 pol = [0]*i + [1] tgt = [i] + [0]*i + [1/scl] lagpol = lag.poly2lag(pol) lagint = lag.lagint(lagpol, m=1, k=[i]) res = lag.lag2poly(lagint) assert_almost_equal(trim(res), trim(tgt)) # check single integration with integration constant and lbnd for i in range(5) : scl = i + 1 pol = [0]*i + [1] lagpol = lag.poly2lag(pol) lagint = lag.lagint(lagpol, m=1, k=[i], lbnd=-1) assert_almost_equal(lag.lagval(-1, lagint), i) # check single integration with integration constant and scaling for i in range(5) : scl = i + 1 pol = [0]*i + [1] tgt = [i] + [0]*i + [2/scl] lagpol = lag.poly2lag(pol) lagint = lag.lagint(lagpol, m=1, k=[i], scl=2) res = lag.lag2poly(lagint) assert_almost_equal(trim(res), trim(tgt)) # check multiple integrations with default k for i in range(5) : for j in range(2, 5) : pol = [0]*i + [1] tgt = pol[:] for k in range(j) : tgt = lag.lagint(tgt, m=1) res = lag.lagint(pol, m=j) assert_almost_equal(trim(res), trim(tgt)) # check multiple integrations with defined k for i in range(5) : for j in range(2, 5) : pol = [0]*i + [1] tgt = pol[:] for k in range(j) : tgt = lag.lagint(tgt, m=1, k=[k]) res = lag.lagint(pol, m=j, k=list(range(j))) assert_almost_equal(trim(res), trim(tgt)) # check multiple integrations with lbnd for i in range(5) : for j in range(2, 5) : pol = [0]*i + [1] tgt = pol[:] for k in range(j) : tgt = lag.lagint(tgt, m=1, k=[k], lbnd=-1) res = lag.lagint(pol, m=j, k=list(range(j)), lbnd=-1) assert_almost_equal(trim(res), trim(tgt)) # check multiple integrations with scaling for i in range(5) : for j in range(2, 5) : pol = [0]*i + [1] tgt = pol[:] for k in range(j) : tgt = lag.lagint(tgt, m=1, k=[k], scl=2) res = lag.lagint(pol, m=j, k=list(range(j)), scl=2) assert_almost_equal(trim(res), trim(tgt)) def test_lagint_axis(self): # check that axis keyword works c2d = np.random.random((3, 4)) tgt = np.vstack([lag.lagint(c) for c in c2d.T]).T res = lag.lagint(c2d, axis=0) assert_almost_equal(res, tgt) tgt = np.vstack([lag.lagint(c) for c in c2d]) res = lag.lagint(c2d, axis=1) assert_almost_equal(res, tgt) tgt = np.vstack([lag.lagint(c, k=3) for c in c2d]) res = lag.lagint(c2d, k=3, axis=1) assert_almost_equal(res, tgt) class TestDerivative(TestCase) : def test_lagder(self) : # check exceptions assert_raises(ValueError, lag.lagder, [0], .5) assert_raises(ValueError, lag.lagder, [0], -1) # check that zeroth deriviative does nothing for i in range(5) : tgt = [0]*i + [1] res = lag.lagder(tgt, m=0) assert_equal(trim(res), trim(tgt)) # check that derivation is the inverse of integration for i in range(5) : for j in range(2, 5) : tgt = [0]*i + [1] res = lag.lagder(lag.lagint(tgt, m=j), m=j) assert_almost_equal(trim(res), trim(tgt)) # check derivation with scaling for i in range(5) : for j in range(2, 5) : tgt = [0]*i + [1] res = lag.lagder(lag.lagint(tgt, m=j, scl=2), m=j, scl=.5) assert_almost_equal(trim(res), trim(tgt)) def test_lagder_axis(self): # check that axis keyword works c2d = np.random.random((3, 4)) tgt = np.vstack([lag.lagder(c) for c in c2d.T]).T res = lag.lagder(c2d, axis=0) assert_almost_equal(res, tgt) tgt = np.vstack([lag.lagder(c) for c in c2d]) res = lag.lagder(c2d, axis=1) assert_almost_equal(res, tgt) class TestVander(TestCase): # some random values in [-1, 1) x = np.random.random((3, 5))*2 - 1 def test_lagvander(self) : # check for 1d x x = np.arange(3) v = lag.lagvander(x, 3) assert_(v.shape == (3, 4)) for i in range(4) : coef = [0]*i + [1] assert_almost_equal(v[..., i], lag.lagval(x, coef)) # check for 2d x x = np.array([[1, 2], [3, 4], [5, 6]]) v = lag.lagvander(x, 3) assert_(v.shape == (3, 2, 4)) for i in range(4) : coef = [0]*i + [1] assert_almost_equal(v[..., i], lag.lagval(x, coef)) def test_lagvander2d(self) : # also tests lagval2d for non-square coefficient array x1, x2, x3 = self.x c = np.random.random((2, 3)) van = lag.lagvander2d(x1, x2, [1, 2]) tgt = lag.lagval2d(x1, x2, c) res = np.dot(van, c.flat) assert_almost_equal(res, tgt) # check shape van = lag.lagvander2d([x1], [x2], [1, 2]) assert_(van.shape == (1, 5, 6)) def test_lagvander3d(self) : # also tests lagval3d for non-square coefficient array x1, x2, x3 = self.x c = np.random.random((2, 3, 4)) van = lag.lagvander3d(x1, x2, x3, [1, 2, 3]) tgt = lag.lagval3d(x1, x2, x3, c) res = np.dot(van, c.flat) assert_almost_equal(res, tgt) # check shape van = lag.lagvander3d([x1], [x2], [x3], [1, 2, 3]) assert_(van.shape == (1, 5, 24)) class TestFitting(TestCase): def test_lagfit(self) : def f(x) : return x*(x - 1)*(x - 2) # Test exceptions assert_raises(ValueError, lag.lagfit, [1], [1], -1) assert_raises(TypeError, lag.lagfit, [[1]], [1], 0) assert_raises(TypeError, lag.lagfit, [], [1], 0) assert_raises(TypeError, lag.lagfit, [1], [[[1]]], 0) assert_raises(TypeError, lag.lagfit, [1, 2], [1], 0) assert_raises(TypeError, lag.lagfit, [1], [1, 2], 0) assert_raises(TypeError, lag.lagfit, [1], [1], 0, w=[[1]]) assert_raises(TypeError, lag.lagfit, [1], [1], 0, w=[1, 1]) # Test fit x = np.linspace(0, 2) y = f(x) # coef3 = lag.lagfit(x, y, 3) assert_equal(len(coef3), 4) assert_almost_equal(lag.lagval(x, coef3), y) # coef4 = lag.lagfit(x, y, 4) assert_equal(len(coef4), 5) assert_almost_equal(lag.lagval(x, coef4), y) # coef2d = lag.lagfit(x, np.array([y, y]).T, 3) assert_almost_equal(coef2d, np.array([coef3, coef3]).T) # test weighting w = np.zeros_like(x) yw = y.copy() w[1::2] = 1 y[0::2] = 0 wcoef3 = lag.lagfit(x, yw, 3, w=w) assert_almost_equal(wcoef3, coef3) # wcoef2d = lag.lagfit(x, np.array([yw, yw]).T, 3, w=w) assert_almost_equal(wcoef2d, np.array([coef3, coef3]).T) # test scaling with complex values x points whose square # is zero when summed. x = [1, 1j, -1, -1j] assert_almost_equal(lag.lagfit(x, x, 1), [1, -1]) class TestCompanion(TestCase): def test_raises(self): assert_raises(ValueError, lag.lagcompanion, []) assert_raises(ValueError, lag.lagcompanion, [1]) def test_dimensions(self): for i in range(1, 5): coef = [0]*i + [1] assert_(lag.lagcompanion(coef).shape == (i, i)) def test_linear_root(self): assert_(lag.lagcompanion([1, 2])[0, 0] == 1.5) class TestGauss(TestCase): def test_100(self): x, w = lag.laggauss(100) # test orthogonality. Note that the results need to be normalized, # otherwise the huge values that can arise from fast growing # functions like Laguerre can be very confusing. v = lag.lagvander(x, 99) vv = np.dot(v.T * w, v) vd = 1/np.sqrt(vv.diagonal()) vv = vd[:, None] * vv * vd assert_almost_equal(vv, np.eye(100)) # check that the integral of 1 is correct tgt = 1.0 assert_almost_equal(w.sum(), tgt) class TestMisc(TestCase) : def test_lagfromroots(self) : res = lag.lagfromroots([]) assert_almost_equal(trim(res), [1]) for i in range(1, 5) : roots = np.cos(np.linspace(-np.pi, 0, 2*i + 1)[1::2]) pol = lag.lagfromroots(roots) res = lag.lagval(roots, pol) tgt = 0 assert_(len(pol) == i + 1) assert_almost_equal(lag.lag2poly(pol)[-1], 1) assert_almost_equal(res, tgt) def test_lagroots(self) : assert_almost_equal(lag.lagroots([1]), []) assert_almost_equal(lag.lagroots([0, 1]), [1]) for i in range(2, 5) : tgt = np.linspace(0, 3, i) res = lag.lagroots(lag.lagfromroots(tgt)) assert_almost_equal(trim(res), trim(tgt)) def test_lagtrim(self) : coef = [2, -1, 1, 0] # Test exceptions assert_raises(ValueError, lag.lagtrim, coef, -1) # Test results assert_equal(lag.lagtrim(coef), coef[:-1]) assert_equal(lag.lagtrim(coef, 1), coef[:-3]) assert_equal(lag.lagtrim(coef, 2), [0]) def test_lagline(self) : assert_equal(lag.lagline(3, 4), [7, -4]) def test_lag2poly(self) : for i in range(7) : assert_almost_equal(lag.lag2poly([0]*i + [1]), Llist[i]) def test_poly2lag(self) : for i in range(7) : assert_almost_equal(lag.poly2lag(Llist[i]), [0]*i + [1]) def test_weight(self): x = np.linspace(0, 10, 11) tgt = np.exp(-x) res = lag.lagweight(x) assert_almost_equal(res, tgt) if __name__ == "__main__": run_module_suite() numpy-1.8.2/numpy/polynomial/polytemplate.py0000664000175100017510000007313212370216243022456 0ustar vagrantvagrant00000000000000""" Template for the Chebyshev and Polynomial classes. This module houses a Python string module Template object (see, e.g., http://docs.python.org/library/string.html#template-strings) used by the `polynomial` and `chebyshev` modules to implement their respective `Polynomial` and `Chebyshev` classes. It provides a mechanism for easily creating additional specific polynomial classes (e.g., Legendre, Jacobi, etc.) in the future, such that all these classes will have a common API. """ from __future__ import division, absolute_import, print_function import string import sys polytemplate = string.Template(''' from __future__ import division, absolute_import, print_function import numpy as np import warnings from . import polyutils as pu class $name(pu.PolyBase) : """A $name series class. $name instances provide the standard Python numerical methods '+', '-', '*', '//', '%', 'divmod', '**', and '()' as well as the listed methods. Parameters ---------- coef : array_like $name coefficients, in increasing order. For example, ``(1, 2, 3)`` implies ``P_0 + 2P_1 + 3P_2`` where the ``P_i`` are a graded polynomial basis. 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 $domain. window : (2,) array_like, optional Window, see ``domain`` for its use. The default value is $domain. .. versionadded:: 1.6.0 Attributes ---------- coef : (N,) ndarray $name coefficients, from low to high. 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. Notes ----- It is important to specify the domain in many cases, for instance in fitting data, because many of the important properties of the polynomial basis only hold in a specified interval and consequently the data must be mapped into that interval in order to benefit. Examples -------- """ # Limit runaway size. T_n^m has degree n*2^m maxpower = 16 # Default domain domain = np.array($domain) # Default window window = np.array($domain) # Don't let participate in array operations. Value doesn't matter. __array_priority__ = 1000 # Not hashable __hash__ = None def has_samecoef(self, other): """Check if coefficients match. Parameters ---------- other : class instance The other class must have the ``coef`` attribute. Returns ------- bool : boolean True if the coefficients are the same, False otherwise. Notes ----- .. versionadded:: 1.6.0 """ 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. Parameters ---------- other : class instance The other class must have the ``domain`` attribute. Returns ------- bool : boolean True if the domains are the same, False otherwise. Notes ----- .. versionadded:: 1.6.0 """ return np.all(self.domain == other.domain) def has_samewindow(self, other): """Check if windows match. Parameters ---------- other : class instance The other class must have the ``window`` attribute. Returns ------- bool : boolean True if the windows are the same, False otherwise. Notes ----- .. versionadded:: 1.6.0 """ return np.all(self.window == other.window) def has_sametype(self, other): """Check if types match. Parameters ---------- other : object Class instance. Returns ------- bool : boolean True if other is same class as self Notes ----- .. versionadded:: 1.7.0 """ return isinstance(other, self.__class__) def __init__(self, coef, domain=$domain, window=$domain) : [coef, dom, win] = pu.as_series([coef, domain, window], trim=False) if len(dom) != 2 : raise ValueError("Domain has wrong number of elements.") if len(win) != 2 : raise ValueError("Window has wrong number of elements.") self.coef = coef self.domain = dom self.window = win 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] return format % ('$name', coef, domain, window) def __str__(self) : format = "%s(%s)" coef = str(self.coef) return format % ('$nick', 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 ${nick}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) : """Returns sum""" if isinstance(other, pu.PolyBase): if not self.has_sametype(other): raise TypeError("Polynomial types differ") elif not self.has_samedomain(other): raise TypeError("Domains differ") elif not self.has_samewindow(other): raise TypeError("Windows differ") else: coef = ${nick}add(self.coef, other.coef) else : try : coef = ${nick}add(self.coef, other) except : return NotImplemented return self.__class__(coef, self.domain, self.window) def __sub__(self, other) : """Returns difference""" if isinstance(other, pu.PolyBase): if not self.has_sametype(other): raise TypeError("Polynomial types differ") elif not self.has_samedomain(other): raise TypeError("Domains differ") elif not self.has_samewindow(other): raise TypeError("Windows differ") else: coef = ${nick}sub(self.coef, other.coef) else : try : coef = ${nick}sub(self.coef, other) except : return NotImplemented return self.__class__(coef, self.domain, self.window) def __mul__(self, other) : """Returns product""" if isinstance(other, pu.PolyBase): if not self.has_sametype(other): raise TypeError("Polynomial types differ") elif not self.has_samedomain(other): raise TypeError("Domains differ") elif not self.has_samewindow(other): raise TypeError("Windows differ") else: coef = ${nick}mul(self.coef, other.coef) else : try : coef = ${nick}mul(self.coef, other) 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 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 np.isscalar(other) : # this might be overly restrictive coef = self.coef/other return self.__class__(coef, self.domain, self.window) else : return NotImplemented def __floordiv__(self, other) : """Returns the quotient.""" if isinstance(other, pu.PolyBase): if not self.has_sametype(other): raise TypeError("Polynomial types differ") elif not self.has_samedomain(other): raise TypeError("Domains differ") elif not self.has_samewindow(other): raise TypeError("Windows differ") else: quo, rem = ${nick}div(self.coef, other.coef) else : try : quo, rem = ${nick}div(self.coef, other) except : return NotImplemented return self.__class__(quo, self.domain, self.window) def __mod__(self, other) : """Returns the remainder.""" if isinstance(other, pu.PolyBase): if not self.has_sametype(other): raise TypeError("Polynomial types differ") elif not self.has_samedomain(other): raise TypeError("Domains differ") elif not self.has_samewindow(other): raise TypeError("Windows differ") else: quo, rem = ${nick}div(self.coef, other.coef) else : try : quo, rem = ${nick}div(self.coef, other) except : return NotImplemented return self.__class__(rem, self.domain, self.window) def __divmod__(self, other) : """Returns quo, remainder""" if isinstance(other, self.__class__) : if not self.has_samedomain(other): raise TypeError("Domains are not equal") elif not self.has_samewindow(other): raise TypeError("Windows are not equal") else: quo, rem = ${nick}div(self.coef, other.coef) else : try : quo, rem = ${nick}div(self.coef, other) 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) : try : coef = ${nick}pow(self.coef, other, maxpower = self.maxpower) except : raise return self.__class__(coef, self.domain, self.window) def __radd__(self, other) : try : coef = ${nick}add(other, self.coef) except : return NotImplemented return self.__class__(coef, self.domain, self.window) def __rsub__(self, other): try : coef = ${nick}sub(other, self.coef) except : return NotImplemented return self.__class__(coef, self.domain, self.window) def __rmul__(self, other) : try : coef = ${nick}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) : # 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) def __rfloordiv__(self, other) : try : quo, rem = ${nick}div(other, self.coef) except : return NotImplemented return self.__class__(quo, self.domain, self.window) def __rmod__(self, other) : try : quo, rem = ${nick}div(other, self.coef) except : return NotImplemented return self.__class__(rem, self.domain, self.window) def __rdivmod__(self, other) : try : quo, rem = ${nick}div(other, self.coef) 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 self.has_samecoef(other) \ and self.has_samedomain(other) \ and self.has_samewindow(other) return res def __ne__(self, other) : return not self.__eq__(other) # # Extra methods. # def copy(self) : """Return a copy. Return a copy of the current $name instance. Returns ------- new_instance : $name Copy of current instance. """ return self.__class__(self.coef, self.domain, self.window) def degree(self) : """The degree of the series. Notes ----- .. versionadded:: 1.5.0 """ return len(self) - 1 def cutdeg(self, deg) : """Truncate series to the given degree. Reduce the degree of the $name 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. 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_instance : $name New instance of $name with reduced degree. Notes ----- .. versionadded:: 1.5.0 """ return self.truncate(deg + 1) def trim(self, tol=0) : """Remove small leading coefficients Remove leading 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 $name 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_instance : $name 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 $name 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_instance : $name New instance of $name 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 to different class and/or domain. 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_instance : `kind` The returned class can be of different type than the current instance and/or have a different domain. Notes ----- Conversion between domains and class types can result in numerically ill defined series. Examples -------- """ if kind is None: kind = $name 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 ``$name`` 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 : floats or complex The mapping function is defined by ``off + scl*x``. Notes ----- If the current domain is the interval ``[l_1, r_1]`` and the window is ``[l_2, r_2]``, then the linear mapping function ``L`` is defined by the equations:: L(l_1) = l_2 L(r_1) = r_2 """ return pu.mapparms(self.domain, self.window) def integ(self, m=1, k=[], lbnd=None) : """Integrate. Return an instance of $name that is the definite integral of the current series. Refer to `${nick}int` for full documentation. 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 ------- integral : $name The integral of the series using the same domain. See Also -------- ${nick}int : similar function. ${nick}der : similar function for derivative. """ off, scl = self.mapparms() if lbnd is None : lbnd = 0 else : lbnd = off + scl*lbnd coef = ${nick}int(self.coef, m, k, lbnd, 1./scl) return self.__class__(coef, self.domain, self.window) def deriv(self, m=1): """Differentiate. Return an instance of $name that is the derivative of the current series. Refer to `${nick}der` for full documentation. Parameters ---------- m : non-negative int The number of integrations to perform. Returns ------- derivative : $name The derivative of the series using the same domain. See Also -------- ${nick}der : similar function. ${nick}int : similar function for integration. """ off, scl = self.mapparms() coef = ${nick}der(self.coef, m, scl) return self.__class__(coef, self.domain, self.window) def roots(self) : """Return list of roots. Return ndarray of roots for this series. See `${nick}roots` for full documentation. Note that the accuracy of the roots is likely to decrease the further outside the domain they lie. See Also -------- ${nick}roots : similar function ${nick}fromroots : function to go generate series from roots. """ roots = ${nick}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 x, y values at `n` linearly spaced points across domain. Here y is the value of the polynomial at the points x. By default the domain is the same as that of the $name instance. This method is intended mostly as a plotting aid. Parameters ---------- n : int, optional Number of point pairs to return. The default value is 100. domain : {None, array_like} 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. Returns ------- x, y : ndarrays ``x`` is equal to linspace(self.domain[0], self.domain[1], n) ``y`` is the polynomial evaluated at ``x``. .. versionadded:: 1.5.0 """ if domain is None: domain = self.domain x = np.linspace(domain[0], domain[1], n) y = self(x) return x, y @staticmethod def fit(x, y, deg, domain=None, rcond=None, full=False, w=None, window=$domain): """Least squares fit to data. Return a `$name` instance that is the least squares fit to the data `y` sampled at `x`. Unlike `${nick}fit`, the domain of the returned instance can be specified and this will often result in a superior fit with less chance of ill conditioning. Support for NA was added in version 1.7.0. See `${nick}fit` for full documentation of the implementation. 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 $name instance. If ``None``, 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. 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 $name instance. The default value is ``$domain`` .. versionadded:: 1.6.0 Returns ------- least_squares_fit : instance of $name The $name instance is the least squares fit to the data and has the domain specified in the call. [residuals, rank, singular_values, rcond] : only if `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`. See Also -------- ${nick}fit : similar function """ if domain is None: domain = pu.getdomain(x) elif domain == []: domain = $domain if window == []: window = $domain xnew = pu.mapdomain(x, domain, window) res = ${nick}fit(xnew, y, deg, w=w, rcond=rcond, full=full) if full : [coef, status] = res return $name(coef, domain=domain, window=window), status else : coef = res return $name(coef, domain=domain, window=window) @staticmethod def fromroots(roots, domain=$domain, window=$domain) : """Return $name instance with specified roots. Returns an instance of $name representing the product ``(x - r[0])*(x - r[1])*...*(x - r[n-1])``, where ``r`` is the list of roots. Parameters ---------- roots : array_like List of roots. domain : {array_like, None}, optional Domain for the resulting instance of $name. If none the domain is the interval from the smallest root to the largest. The default is $domain. window : array_like, optional Window for the resulting instance of $name. The default value is $domain. Returns ------- object : $name instance Series with the specified roots. See Also -------- ${nick}fromroots : equivalent function """ [roots] = pu.as_series([roots], trim=False) if domain is None : domain = pu.getdomain(roots) deg = len(roots) off, scl = pu.mapparms(domain, window) rnew = off + scl*roots coef = ${nick}fromroots(rnew) / scl**deg return $name(coef, domain=domain, window=window) @staticmethod def identity(domain=$domain, window=$domain) : """Identity function. If ``p`` is the returned $name object, then ``p(x) == x`` for all values of x. Parameters ---------- domain : array_like The resulting array must be of the form ``[beg, end]``, where ``beg`` and ``end`` are the endpoints of the domain. window : array_like The resulting array must be if the form ``[beg, end]``, where ``beg`` and ``end`` are the endpoints of the window. Returns ------- identity : $name instance """ off, scl = pu.mapparms(window, domain) coef = ${nick}line(off, scl) return $name(coef, domain, window) @staticmethod def basis(deg, domain=$domain, window=$domain): """$name polynomial of degree `deg`. Returns an instance of the $name polynomial of degree `d`. Parameters ---------- deg : int Degree of the $name polynomial. Must be >= 0. domain : array_like The resulting array must be of the form ``[beg, end]``, where ``beg`` and ``end`` are the endpoints of the domain. window : array_like The resulting array must be if the form ``[beg, end]``, where ``beg`` and ``end`` are the endpoints of the window. Returns p : $name instance Notes ----- .. versionadded:: 1.7.0 """ ideg = int(deg) if ideg != deg or ideg < 0: raise ValueError("deg must be non-negative integer") return $name([0]*ideg + [1], domain, window) @staticmethod def cast(series, domain=$domain, window=$domain): """Convert instance to equivalent $name series. 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. Parameters ---------- series : series The instance series to be converted. domain : array_like The resulting array must be of the form ``[beg, end]``, where ``beg`` and ``end`` are the endpoints of the domain. window : array_like The resulting array must be if the form ``[beg, end]``, where ``beg`` and ``end`` are the endpoints of the window. Returns p : $name instance A $name series equal to the `poly` series. See Also -------- convert -- similar instance method Notes ----- .. versionadded:: 1.7.0 """ return series.convert(domain, $name, window) ''') numpy-1.8.2/numpy/polynomial/__init__.py0000664000175100017510000000216012370216243021467 0ustar vagrantvagrant00000000000000""" A sub-package for efficiently dealing with polynomials. Within the documentation for this sub-package, a "finite power series," i.e., a polynomial (also referred to simply as a "series") is represented by a 1-D numpy array of the polynomial's coefficients, ordered from lowest order term to highest. For example, array([1,2,3]) represents ``P_0 + 2*P_1 + 3*P_2``, where P_n is the n-th order basis polynomial applicable to the specific module in question, e.g., `polynomial` (which "wraps" the "standard" basis) or `chebyshev`. For optimal performance, all operations on polynomials, including evaluation at an argument, are implemented as operations on the coefficients. Additional (module-specific) information can be found in the docstring for the module of interest. """ from __future__ import division, absolute_import, print_function import warnings from .polynomial import Polynomial from .chebyshev import Chebyshev from .legendre import Legendre from .hermite import Hermite from .hermite_e import HermiteE from .laguerre import Laguerre from numpy.testing import Tester test = Tester().test bench = Tester().bench numpy-1.8.2/numpy/polynomial/hermite.py0000664000175100017510000015303512370216243021375 0ustar vagrantvagrant00000000000000""" Objects for dealing with Hermite series. This module provides a number of objects (mostly functions) useful for dealing with Hermite series, including a `Hermite` class that encapsulates the usual arithmetic operations. (General information on how this module represents and works with such polynomials is in the docstring for its "parent" sub-package, `numpy.polynomial`). Constants --------- - `hermdomain` -- Hermite series default domain, [-1,1]. - `hermzero` -- Hermite series that evaluates identically to 0. - `hermone` -- Hermite series that evaluates identically to 1. - `hermx` -- Hermite series for the identity map, ``f(x) = x``. Arithmetic ---------- - `hermmulx` -- multiply a Hermite series in ``P_i(x)`` by ``x``. - `hermadd` -- add two Hermite series. - `hermsub` -- subtract one Hermite series from another. - `hermmul` -- multiply two Hermite series. - `hermdiv` -- divide one Hermite series by another. - `hermval` -- evaluate a Hermite series at given points. - `hermval2d` -- evaluate a 2D Hermite series at given points. - `hermval3d` -- evaluate a 3D Hermite series at given points. - `hermgrid2d` -- evaluate a 2D Hermite series on a Cartesian product. - `hermgrid3d` -- evaluate a 3D Hermite series on a Cartesian product. Calculus -------- - `hermder` -- differentiate a Hermite series. - `hermint` -- integrate a Hermite series. Misc Functions -------------- - `hermfromroots` -- create a Hermite series with specified roots. - `hermroots` -- find the roots of a Hermite series. - `hermvander` -- Vandermonde-like matrix for Hermite polynomials. - `hermvander2d` -- Vandermonde-like matrix for 2D power series. - `hermvander3d` -- Vandermonde-like matrix for 3D power series. - `hermgauss` -- Gauss-Hermite quadrature, points and weights. - `hermweight` -- Hermite weight function. - `hermcompanion` -- symmetrized companion matrix in Hermite form. - `hermfit` -- least-squares fit returning a Hermite series. - `hermtrim` -- trim leading coefficients from a Hermite series. - `hermline` -- Hermite series of given straight line. - `herm2poly` -- convert a Hermite series to a polynomial. - `poly2herm` -- convert a polynomial to a Hermite series. Classes ------- - `Hermite` -- A Hermite series class. See also -------- `numpy.polynomial` """ from __future__ import division, absolute_import, print_function import numpy as np import numpy.linalg as la from . import polyutils as pu import warnings from .polytemplate import polytemplate __all__ = ['hermzero', 'hermone', 'hermx', 'hermdomain', 'hermline', 'hermadd', 'hermsub', 'hermmulx', 'hermmul', 'hermdiv', 'hermpow', 'hermval', 'hermder', 'hermint', 'herm2poly', 'poly2herm', 'hermfromroots', 'hermvander', 'hermfit', 'hermtrim', 'hermroots', 'Hermite', 'hermval2d', 'hermval3d', 'hermgrid2d', 'hermgrid3d', 'hermvander2d', 'hermvander3d', 'hermcompanion', 'hermgauss', 'hermweight'] hermtrim = pu.trimcoef def poly2herm(pol) : """ poly2herm(pol) Convert a polynomial to a Hermite series. Convert an array representing the coefficients of a polynomial (relative to the "standard" basis) ordered from lowest degree to highest, to an array of the coefficients of the equivalent Hermite series, ordered from lowest to highest degree. Parameters ---------- pol : array_like 1-D array containing the polynomial coefficients Returns ------- c : ndarray 1-D array containing the coefficients of the equivalent Hermite series. See Also -------- herm2poly Notes ----- The easy way to do conversions between polynomial basis sets is to use the convert method of a class instance. Examples -------- >>> from numpy.polynomial.hermite_e import poly2herme >>> poly2herm(np.arange(4)) array([ 1. , 2.75 , 0.5 , 0.375]) """ [pol] = pu.as_series([pol]) deg = len(pol) - 1 res = 0 for i in range(deg, -1, -1) : res = hermadd(hermmulx(res), pol[i]) return res def herm2poly(c) : """ Convert a Hermite series to a polynomial. Convert an array representing the coefficients of a Hermite series, ordered from lowest degree to highest, to an array of the coefficients of the equivalent polynomial (relative to the "standard" basis) ordered from lowest to highest degree. Parameters ---------- c : array_like 1-D array containing the Hermite series coefficients, ordered from lowest order term to highest. Returns ------- pol : ndarray 1-D array containing the coefficients of the equivalent polynomial (relative to the "standard" basis) ordered from lowest order term to highest. See Also -------- poly2herm Notes ----- The easy way to do conversions between polynomial basis sets is to use the convert method of a class instance. Examples -------- >>> from numpy.polynomial.hermite import herm2poly >>> herm2poly([ 1. , 2.75 , 0.5 , 0.375]) array([ 0., 1., 2., 3.]) """ from .polynomial import polyadd, polysub, polymulx [c] = pu.as_series([c]) n = len(c) if n == 1: return c if n == 2: c[1] *= 2 return c else: c0 = c[-2] c1 = c[-1] # i is the current degree of c1 for i in range(n - 1, 1, -1) : tmp = c0 c0 = polysub(c[i - 2], c1*(2*(i - 1))) c1 = polyadd(tmp, polymulx(c1)*2) return polyadd(c0, polymulx(c1)*2) # # These are constant arrays are of integer type so as to be compatible # with the widest range of other types, such as Decimal. # # Hermite hermdomain = np.array([-1, 1]) # Hermite coefficients representing zero. hermzero = np.array([0]) # Hermite coefficients representing one. hermone = np.array([1]) # Hermite coefficients representing the identity x. hermx = np.array([0, 1/2]) def hermline(off, scl) : """ Hermite series whose graph is a straight line. Parameters ---------- off, scl : scalars The specified line is given by ``off + scl*x``. Returns ------- y : ndarray This module's representation of the Hermite series for ``off + scl*x``. See Also -------- polyline, chebline Examples -------- >>> from numpy.polynomial.hermite import hermline, hermval >>> hermval(0,hermline(3, 2)) 3.0 >>> hermval(1,hermline(3, 2)) 5.0 """ if scl != 0 : return np.array([off, scl/2]) else : return np.array([off]) def hermfromroots(roots) : """ Generate a Hermite series with given roots. The function returns the coefficients of the polynomial .. math:: p(x) = (x - r_0) * (x - r_1) * ... * (x - r_n), in Hermite form, where the `r_n` are the roots specified in `roots`. If a zero has multiplicity n, then it must appear in `roots` n times. For instance, if 2 is a root of multiplicity three and 3 is a root of multiplicity 2, then `roots` looks something like [2, 2, 2, 3, 3]. The roots can appear in any order. If the returned coefficients are `c`, then .. math:: p(x) = c_0 + c_1 * H_1(x) + ... + c_n * H_n(x) The coefficient of the last term is not generally 1 for monic polynomials in Hermite form. Parameters ---------- roots : array_like Sequence containing the roots. Returns ------- out : ndarray 1-D array of coefficients. If all roots are real then `out` is a real array, if some of the roots are complex, then `out` is complex even if all the coefficients in the result are real (see Examples below). See Also -------- polyfromroots, legfromroots, lagfromroots, chebfromroots, hermefromroots. Examples -------- >>> from numpy.polynomial.hermite import hermfromroots, hermval >>> coef = hermfromroots((-1, 0, 1)) >>> hermval((-1, 0, 1), coef) array([ 0., 0., 0.]) >>> coef = hermfromroots((-1j, 1j)) >>> hermval((-1j, 1j), coef) array([ 0.+0.j, 0.+0.j]) """ if len(roots) == 0 : return np.ones(1) else : [roots] = pu.as_series([roots], trim=False) roots.sort() p = [hermline(-r, 1) for r in roots] n = len(p) while n > 1: m, r = divmod(n, 2) tmp = [hermmul(p[i], p[i+m]) for i in range(m)] if r: tmp[0] = hermmul(tmp[0], p[-1]) p = tmp n = m return p[0] def hermadd(c1, c2): """ Add one Hermite series to another. Returns the sum of two Hermite series `c1` + `c2`. The arguments are sequences of coefficients ordered from lowest order term to highest, i.e., [1,2,3] represents the series ``P_0 + 2*P_1 + 3*P_2``. Parameters ---------- c1, c2 : array_like 1-D arrays of Hermite series coefficients ordered from low to high. Returns ------- out : ndarray Array representing the Hermite series of their sum. See Also -------- hermsub, hermmul, hermdiv, hermpow Notes ----- Unlike multiplication, division, etc., the sum of two Hermite series is a Hermite series (without having to "reproject" the result onto the basis set) so addition, just like that of "standard" polynomials, is simply "component-wise." Examples -------- >>> from numpy.polynomial.hermite import hermadd >>> hermadd([1, 2, 3], [1, 2, 3, 4]) array([ 2., 4., 6., 4.]) """ # c1, c2 are trimmed copies [c1, c2] = pu.as_series([c1, c2]) if len(c1) > len(c2) : c1[:c2.size] += c2 ret = c1 else : c2[:c1.size] += c1 ret = c2 return pu.trimseq(ret) def hermsub(c1, c2): """ Subtract one Hermite series from another. Returns the difference of two Hermite series `c1` - `c2`. The sequences of coefficients are from lowest order term to highest, i.e., [1,2,3] represents the series ``P_0 + 2*P_1 + 3*P_2``. Parameters ---------- c1, c2 : array_like 1-D arrays of Hermite series coefficients ordered from low to high. Returns ------- out : ndarray Of Hermite series coefficients representing their difference. See Also -------- hermadd, hermmul, hermdiv, hermpow Notes ----- Unlike multiplication, division, etc., the difference of two Hermite series is a Hermite series (without having to "reproject" the result onto the basis set) so subtraction, just like that of "standard" polynomials, is simply "component-wise." Examples -------- >>> from numpy.polynomial.hermite import hermsub >>> hermsub([1, 2, 3, 4], [1, 2, 3]) array([ 0., 0., 0., 4.]) """ # c1, c2 are trimmed copies [c1, c2] = pu.as_series([c1, c2]) if len(c1) > len(c2) : c1[:c2.size] -= c2 ret = c1 else : c2 = -c2 c2[:c1.size] += c1 ret = c2 return pu.trimseq(ret) def hermmulx(c): """Multiply a Hermite series by x. Multiply the Hermite series `c` by x, where x is the independent variable. Parameters ---------- c : array_like 1-D array of Hermite series coefficients ordered from low to high. Returns ------- out : ndarray Array representing the result of the multiplication. Notes ----- The multiplication uses the recursion relationship for Hermite polynomials in the form .. math:: xP_i(x) = (P_{i + 1}(x)/2 + i*P_{i - 1}(x)) Examples -------- >>> from numpy.polynomial.hermite import hermmulx >>> hermmulx([1, 2, 3]) array([ 2. , 6.5, 1. , 1.5]) """ # c is a trimmed copy [c] = pu.as_series([c]) # The zero series needs special treatment if len(c) == 1 and c[0] == 0: return c prd = np.empty(len(c) + 1, dtype=c.dtype) prd[0] = c[0]*0 prd[1] = c[0]/2 for i in range(1, len(c)): prd[i + 1] = c[i]/2 prd[i - 1] += c[i]*i return prd def hermmul(c1, c2): """ Multiply one Hermite series by another. Returns the product of two Hermite series `c1` * `c2`. The arguments are sequences of coefficients, from lowest order "term" to highest, e.g., [1,2,3] represents the series ``P_0 + 2*P_1 + 3*P_2``. Parameters ---------- c1, c2 : array_like 1-D arrays of Hermite series coefficients ordered from low to high. Returns ------- out : ndarray Of Hermite series coefficients representing their product. See Also -------- hermadd, hermsub, hermdiv, hermpow Notes ----- In general, the (polynomial) product of two C-series results in terms that are not in the Hermite polynomial basis set. Thus, to express the product as a Hermite series, it is necessary to "reproject" the product onto said basis set, which may produce "unintuitive" (but correct) results; see Examples section below. Examples -------- >>> from numpy.polynomial.hermite import hermmul >>> hermmul([1, 2, 3], [0, 1, 2]) array([ 52., 29., 52., 7., 6.]) """ # s1, s2 are trimmed copies [c1, c2] = pu.as_series([c1, c2]) if len(c1) > len(c2): c = c2 xs = c1 else: c = c1 xs = c2 if len(c) == 1: c0 = c[0]*xs c1 = 0 elif len(c) == 2: c0 = c[0]*xs c1 = c[1]*xs else : nd = len(c) c0 = c[-2]*xs c1 = c[-1]*xs for i in range(3, len(c) + 1) : tmp = c0 nd = nd - 1 c0 = hermsub(c[-i]*xs, c1*(2*(nd - 1))) c1 = hermadd(tmp, hermmulx(c1)*2) return hermadd(c0, hermmulx(c1)*2) def hermdiv(c1, c2): """ Divide one Hermite series by another. Returns the quotient-with-remainder of two Hermite series `c1` / `c2`. The arguments are sequences of coefficients from lowest order "term" to highest, e.g., [1,2,3] represents the series ``P_0 + 2*P_1 + 3*P_2``. Parameters ---------- c1, c2 : array_like 1-D arrays of Hermite series coefficients ordered from low to high. Returns ------- [quo, rem] : ndarrays Of Hermite series coefficients representing the quotient and remainder. See Also -------- hermadd, hermsub, hermmul, hermpow Notes ----- In general, the (polynomial) division of one Hermite series by another results in quotient and remainder terms that are not in the Hermite polynomial basis set. Thus, to express these results as a Hermite series, it is necessary to "reproject" the results onto the Hermite basis set, which may produce "unintuitive" (but correct) results; see Examples section below. Examples -------- >>> from numpy.polynomial.hermite import hermdiv >>> hermdiv([ 52., 29., 52., 7., 6.], [0, 1, 2]) (array([ 1., 2., 3.]), array([ 0.])) >>> hermdiv([ 54., 31., 52., 7., 6.], [0, 1, 2]) (array([ 1., 2., 3.]), array([ 2., 2.])) >>> hermdiv([ 53., 30., 52., 7., 6.], [0, 1, 2]) (array([ 1., 2., 3.]), array([ 1., 1.])) """ # c1, c2 are trimmed copies [c1, c2] = pu.as_series([c1, c2]) if c2[-1] == 0 : raise ZeroDivisionError() lc1 = len(c1) lc2 = len(c2) if lc1 < lc2 : return c1[:1]*0, c1 elif lc2 == 1 : return c1/c2[-1], c1[:1]*0 else : quo = np.empty(lc1 - lc2 + 1, dtype=c1.dtype) rem = c1 for i in range(lc1 - lc2, - 1, -1): p = hermmul([0]*i + [1], c2) q = rem[-1]/p[-1] rem = rem[:-1] - q*p[:-1] quo[i] = q return quo, pu.trimseq(rem) def hermpow(c, pow, maxpower=16) : """Raise a Hermite series to a power. Returns the Hermite series `c` raised to the power `pow`. The argument `c` is a sequence of coefficients ordered from low to high. i.e., [1,2,3] is the series ``P_0 + 2*P_1 + 3*P_2.`` Parameters ---------- c : array_like 1-D array of Hermite series coefficients ordered from low to high. pow : integer Power to which the series will be raised maxpower : integer, optional Maximum power allowed. This is mainly to limit growth of the series to unmanageable size. Default is 16 Returns ------- coef : ndarray Hermite series of power. See Also -------- hermadd, hermsub, hermmul, hermdiv Examples -------- >>> from numpy.polynomial.hermite import hermpow >>> hermpow([1, 2, 3], 2) array([ 81., 52., 82., 12., 9.]) """ # c is a trimmed copy [c] = pu.as_series([c]) power = int(pow) if power != pow or power < 0 : raise ValueError("Power must be a non-negative integer.") elif maxpower is not None and power > maxpower : raise ValueError("Power is too large") elif power == 0 : return np.array([1], dtype=c.dtype) elif power == 1 : return c else : # This can be made more efficient by using powers of two # in the usual way. prd = c for i in range(2, power + 1) : prd = hermmul(prd, c) return prd def hermder(c, m=1, scl=1, axis=0) : """ Differentiate a Hermite series. Returns the Hermite series coefficients `c` differentiated `m` times along `axis`. At each iteration the result is multiplied by `scl` (the scaling factor is for use in a linear change of variable). The argument `c` is an array of coefficients from low to high degree along each axis, e.g., [1,2,3] represents the series ``1*H_0 + 2*H_1 + 3*H_2`` while [[1,2],[1,2]] represents ``1*H_0(x)*H_0(y) + 1*H_1(x)*H_0(y) + 2*H_0(x)*H_1(y) + 2*H_1(x)*H_1(y)`` if axis=0 is ``x`` and axis=1 is ``y``. Parameters ---------- c : array_like Array of Hermite series coefficients. If `c` is multidimensional the different axis correspond to different variables with the degree in each axis given by the corresponding index. m : int, optional Number of derivatives taken, must be non-negative. (Default: 1) scl : scalar, optional Each differentiation is multiplied by `scl`. The end result is multiplication by ``scl**m``. This is for use in a linear change of variable. (Default: 1) axis : int, optional Axis over which the derivative is taken. (Default: 0). .. versionadded:: 1.7.0 Returns ------- der : ndarray Hermite series of the derivative. See Also -------- hermint Notes ----- In general, the result of differentiating a Hermite series does not resemble the same operation on a power series. Thus the result of this function may be "unintuitive," albeit correct; see Examples section below. Examples -------- >>> from numpy.polynomial.hermite import hermder >>> hermder([ 1. , 0.5, 0.5, 0.5]) array([ 1., 2., 3.]) >>> hermder([-0.5, 1./2., 1./8., 1./12., 1./16.], m=2) array([ 1., 2., 3.]) """ c = np.array(c, ndmin=1, copy=1) if c.dtype.char in '?bBhHiIlLqQpP': c = c.astype(np.double) cnt, iaxis = [int(t) for t in [m, axis]] if cnt != m: raise ValueError("The order of derivation must be integer") if cnt < 0: raise ValueError("The order of derivation must be non-negative") if iaxis != axis: raise ValueError("The axis must be integer") if not -c.ndim <= iaxis < c.ndim: raise ValueError("The axis is out of range") if iaxis < 0: iaxis += c.ndim if cnt == 0: return c c = np.rollaxis(c, iaxis) n = len(c) if cnt >= n: c = c[:1]*0 else : for i in range(cnt): n = n - 1 c *= scl der = np.empty((n,) + c.shape[1:], dtype=c.dtype) for j in range(n, 0, -1): der[j - 1] = (2*j)*c[j] c = der c = np.rollaxis(c, 0, iaxis + 1) return c def hermint(c, m=1, k=[], lbnd=0, scl=1, axis=0): """ Integrate a Hermite series. Returns the Hermite series coefficients `c` integrated `m` times from `lbnd` along `axis`. At each iteration the resulting series is **multiplied** by `scl` and an integration constant, `k`, is added. The scaling factor is for use in a linear change of variable. ("Buyer beware": note that, depending on what one is doing, one may want `scl` to be the reciprocal of what one might expect; for more information, see the Notes section below.) The argument `c` is an array of coefficients from low to high degree along each axis, e.g., [1,2,3] represents the series ``H_0 + 2*H_1 + 3*H_2`` while [[1,2],[1,2]] represents ``1*H_0(x)*H_0(y) + 1*H_1(x)*H_0(y) + 2*H_0(x)*H_1(y) + 2*H_1(x)*H_1(y)`` if axis=0 is ``x`` and axis=1 is ``y``. Parameters ---------- c : array_like Array of Hermite series coefficients. If c is multidimensional the different axis correspond to different variables with the degree in each axis given by the corresponding index. m : int, optional Order of integration, must be positive. (Default: 1) k : {[], list, scalar}, optional Integration constant(s). The value of the first integral at ``lbnd`` is the first value in the list, the value of the second integral at ``lbnd`` is the second value, etc. If ``k == []`` (the default), all constants are set to zero. If ``m == 1``, a single scalar can be given instead of a list. lbnd : scalar, optional The lower bound of the integral. (Default: 0) scl : scalar, optional Following each integration the result is *multiplied* by `scl` before the integration constant is added. (Default: 1) axis : int, optional Axis over which the integral is taken. (Default: 0). .. versionadded:: 1.7.0 Returns ------- S : ndarray Hermite series coefficients of the integral. Raises ------ ValueError If ``m < 0``, ``len(k) > m``, ``np.isscalar(lbnd) == False``, or ``np.isscalar(scl) == False``. See Also -------- hermder Notes ----- Note that the result of each integration is *multiplied* by `scl`. Why is this important to note? Say one is making a linear change of variable :math:`u = ax + b` in an integral relative to `x`. Then .. math::`dx = du/a`, so one will need to set `scl` equal to :math:`1/a` - perhaps not what one would have first thought. Also note that, in general, the result of integrating a C-series needs to be "reprojected" onto the C-series basis set. Thus, typically, the result of this function is "unintuitive," albeit correct; see Examples section below. Examples -------- >>> from numpy.polynomial.hermite import hermint >>> hermint([1,2,3]) # integrate once, value 0 at 0. array([ 1. , 0.5, 0.5, 0.5]) >>> hermint([1,2,3], m=2) # integrate twice, value & deriv 0 at 0 array([-0.5 , 0.5 , 0.125 , 0.08333333, 0.0625 ]) >>> hermint([1,2,3], k=1) # integrate once, value 1 at 0. array([ 2. , 0.5, 0.5, 0.5]) >>> hermint([1,2,3], lbnd=-1) # integrate once, value 0 at -1 array([-2. , 0.5, 0.5, 0.5]) >>> hermint([1,2,3], m=2, k=[1,2], lbnd=-1) array([ 1.66666667, -0.5 , 0.125 , 0.08333333, 0.0625 ]) """ c = np.array(c, ndmin=1, copy=1) if c.dtype.char in '?bBhHiIlLqQpP': c = c.astype(np.double) if not np.iterable(k): k = [k] cnt, iaxis = [int(t) for t in [m, axis]] if cnt != m: raise ValueError("The order of integration must be integer") if cnt < 0 : raise ValueError("The order of integration must be non-negative") if len(k) > cnt : raise ValueError("Too many integration constants") if iaxis != axis: raise ValueError("The axis must be integer") if not -c.ndim <= iaxis < c.ndim: raise ValueError("The axis is out of range") if iaxis < 0: iaxis += c.ndim if cnt == 0: return c c = np.rollaxis(c, iaxis) k = list(k) + [0]*(cnt - len(k)) for i in range(cnt) : n = len(c) c *= scl if n == 1 and np.all(c[0] == 0): c[0] += k[i] else: tmp = np.empty((n + 1,) + c.shape[1:], dtype=c.dtype) tmp[0] = c[0]*0 tmp[1] = c[0]/2 for j in range(1, n): tmp[j + 1] = c[j]/(2*(j + 1)) tmp[0] += k[i] - hermval(lbnd, tmp) c = tmp c = np.rollaxis(c, 0, iaxis + 1) return c def hermval(x, c, tensor=True): """ Evaluate an Hermite series at points x. If `c` is of length `n + 1`, this function returns the value: .. math:: p(x) = c_0 * H_0(x) + c_1 * H_1(x) + ... + c_n * H_n(x) The parameter `x` is converted to an array only if it is a tuple or a list, otherwise it is treated as a scalar. In either case, either `x` or its elements must support multiplication and addition both with themselves and with the elements of `c`. If `c` is a 1-D array, then `p(x)` will have the same shape as `x`. If `c` is multidimensional, then the shape of the result depends on the value of `tensor`. If `tensor` is true the shape will be c.shape[1:] + x.shape. If `tensor` is false the shape will be c.shape[1:]. Note that scalars have shape (,). Trailing zeros in the coefficients will be used in the evaluation, so they should be avoided if efficiency is a concern. Parameters ---------- x : array_like, compatible object If `x` is a list or tuple, it is converted to an ndarray, otherwise it is left unchanged and treated as a scalar. In either case, `x` or its elements must support addition and multiplication with with themselves and with the elements of `c`. c : array_like Array of coefficients ordered so that the coefficients for terms of degree n are contained in c[n]. If `c` is multidimensional the remaining indices enumerate multiple polynomials. In the two dimensional case the coefficients may be thought of as stored in the columns of `c`. tensor : boolean, optional If True, the shape of the coefficient array is extended with ones on the right, one for each dimension of `x`. Scalars have dimension 0 for this action. The result is that every column of coefficients in `c` is evaluated for every element of `x`. If False, `x` is broadcast over the columns of `c` for the evaluation. This keyword is useful when `c` is multidimensional. The default value is True. .. versionadded:: 1.7.0 Returns ------- values : ndarray, algebra_like The shape of the return value is described above. See Also -------- hermval2d, hermgrid2d, hermval3d, hermgrid3d Notes ----- The evaluation uses Clenshaw recursion, aka synthetic division. Examples -------- >>> from numpy.polynomial.hermite import hermval >>> coef = [1,2,3] >>> hermval(1, coef) 11.0 >>> hermval([[1,2],[3,4]], coef) array([[ 11., 51.], [ 115., 203.]]) """ c = np.array(c, ndmin=1, copy=0) if c.dtype.char in '?bBhHiIlLqQpP': c = c.astype(np.double) if isinstance(x, (tuple, list)): x = np.asarray(x) if isinstance(x, np.ndarray) and tensor: c = c.reshape(c.shape + (1,)*x.ndim) x2 = x*2 if len(c) == 1 : c0 = c[0] c1 = 0 elif len(c) == 2 : c0 = c[0] c1 = c[1] else : nd = len(c) c0 = c[-2] c1 = c[-1] for i in range(3, len(c) + 1) : tmp = c0 nd = nd - 1 c0 = c[-i] - c1*(2*(nd - 1)) c1 = tmp + c1*x2 return c0 + c1*x2 def hermval2d(x, y, c): """ Evaluate a 2-D Hermite series at points (x, y). This function returns the values: .. math:: p(x,y) = \\sum_{i,j} c_{i,j} * H_i(x) * H_j(y) The parameters `x` and `y` are converted to arrays only if they are tuples or a lists, otherwise they are treated as a scalars and they must have the same shape after conversion. In either case, either `x` and `y` or their elements must support multiplication and addition both with themselves and with the elements of `c`. If `c` is a 1-D array a one is implicitly appended to its shape to make it 2-D. The shape of the result will be c.shape[2:] + x.shape. Parameters ---------- x, y : array_like, compatible objects The two dimensional series is evaluated at the points `(x, y)`, where `x` and `y` must have the same shape. If `x` or `y` is a list or tuple, it is first converted to an ndarray, otherwise it is left unchanged and if it isn't an ndarray it is treated as a scalar. c : array_like Array of coefficients ordered so that the coefficient of the term of multi-degree i,j is contained in ``c[i,j]``. If `c` has dimension greater than two the remaining indices enumerate multiple sets of coefficients. Returns ------- values : ndarray, compatible object The values of the two dimensional polynomial at points formed with pairs of corresponding values from `x` and `y`. See Also -------- hermval, hermgrid2d, hermval3d, hermgrid3d Notes ----- .. versionadded::1.7.0 """ try: x, y = np.array((x, y), copy=0) except: raise ValueError('x, y are incompatible') c = hermval(x, c) c = hermval(y, c, tensor=False) return c def hermgrid2d(x, y, c): """ Evaluate a 2-D Hermite series on the Cartesian product of x and y. This function returns the values: .. math:: p(a,b) = \sum_{i,j} c_{i,j} * H_i(a) * H_j(b) where the points `(a, b)` consist of all pairs formed by taking `a` from `x` and `b` from `y`. The resulting points form a grid with `x` in the first dimension and `y` in the second. The parameters `x` and `y` are converted to arrays only if they are tuples or a lists, otherwise they are treated as a scalars. In either case, either `x` and `y` or their elements must support multiplication and addition both with themselves and with the elements of `c`. If `c` has fewer than two dimensions, ones are implicitly appended to its shape to make it 2-D. The shape of the result will be c.shape[2:] + x.shape. Parameters ---------- x, y : array_like, compatible objects The two dimensional series is evaluated at the points in the Cartesian product of `x` and `y`. If `x` or `y` is a list or tuple, it is first converted to an ndarray, otherwise it is left unchanged and, if it isn't an ndarray, it is treated as a scalar. c : array_like Array of coefficients ordered so that the coefficients for terms of degree i,j are contained in ``c[i,j]``. If `c` has dimension greater than two the remaining indices enumerate multiple sets of coefficients. Returns ------- values : ndarray, compatible object The values of the two dimensional polynomial at points in the Cartesian product of `x` and `y`. See Also -------- hermval, hermval2d, hermval3d, hermgrid3d Notes ----- .. versionadded::1.7.0 """ c = hermval(x, c) c = hermval(y, c) return c def hermval3d(x, y, z, c): """ Evaluate a 3-D Hermite series at points (x, y, z). This function returns the values: .. math:: p(x,y,z) = \\sum_{i,j,k} c_{i,j,k} * H_i(x) * H_j(y) * H_k(z) The parameters `x`, `y`, and `z` are converted to arrays only if they are tuples or a lists, otherwise they are treated as a scalars and they must have the same shape after conversion. In either case, either `x`, `y`, and `z` or their elements must support multiplication and addition both with themselves and with the elements of `c`. If `c` has fewer than 3 dimensions, ones are implicitly appended to its shape to make it 3-D. The shape of the result will be c.shape[3:] + x.shape. Parameters ---------- x, y, z : array_like, compatible object The three dimensional series is evaluated at the points `(x, y, z)`, where `x`, `y`, and `z` must have the same shape. If any of `x`, `y`, or `z` is a list or tuple, it is first converted to an ndarray, otherwise it is left unchanged and if it isn't an ndarray it is treated as a scalar. c : array_like Array of coefficients ordered so that the coefficient of the term of multi-degree i,j,k is contained in ``c[i,j,k]``. If `c` has dimension greater than 3 the remaining indices enumerate multiple sets of coefficients. Returns ------- values : ndarray, compatible object The values of the multidimensional polynomial on points formed with triples of corresponding values from `x`, `y`, and `z`. See Also -------- hermval, hermval2d, hermgrid2d, hermgrid3d Notes ----- .. versionadded::1.7.0 """ try: x, y, z = np.array((x, y, z), copy=0) except: raise ValueError('x, y, z are incompatible') c = hermval(x, c) c = hermval(y, c, tensor=False) c = hermval(z, c, tensor=False) return c def hermgrid3d(x, y, z, c): """ Evaluate a 3-D Hermite series on the Cartesian product of x, y, and z. This function returns the values: .. math:: p(a,b,c) = \\sum_{i,j,k} c_{i,j,k} * H_i(a) * H_j(b) * H_k(c) where the points `(a, b, c)` consist of all triples formed by taking `a` from `x`, `b` from `y`, and `c` from `z`. The resulting points form a grid with `x` in the first dimension, `y` in the second, and `z` in the third. The parameters `x`, `y`, and `z` are converted to arrays only if they are tuples or a lists, otherwise they are treated as a scalars. In either case, either `x`, `y`, and `z` or their elements must support multiplication and addition both with themselves and with the elements of `c`. If `c` has fewer than three dimensions, ones are implicitly appended to its shape to make it 3-D. The shape of the result will be c.shape[3:] + x.shape + y.shape + z.shape. Parameters ---------- x, y, z : array_like, compatible objects The three dimensional series is evaluated at the points in the Cartesian product of `x`, `y`, and `z`. If `x`,`y`, or `z` is a list or tuple, it is first converted to an ndarray, otherwise it is left unchanged and, if it isn't an ndarray, it is treated as a scalar. c : array_like Array of coefficients ordered so that the coefficients for terms of degree i,j are contained in ``c[i,j]``. If `c` has dimension greater than two the remaining indices enumerate multiple sets of coefficients. Returns ------- values : ndarray, compatible object The values of the two dimensional polynomial at points in the Cartesian product of `x` and `y`. See Also -------- hermval, hermval2d, hermgrid2d, hermval3d Notes ----- .. versionadded::1.7.0 """ c = hermval(x, c) c = hermval(y, c) c = hermval(z, c) return c def hermvander(x, deg) : """Pseudo-Vandermonde matrix of given degree. Returns the pseudo-Vandermonde matrix of degree `deg` and sample points `x`. The pseudo-Vandermonde matrix is defined by .. math:: V[..., i] = H_i(x), where `0 <= i <= deg`. The leading indices of `V` index the elements of `x` and the last index is the degree of the Hermite polynomial. If `c` is a 1-D array of coefficients of length `n + 1` and `V` is the array ``V = hermvander(x, n)``, then ``np.dot(V, c)`` and ``hermval(x, c)`` are the same up to roundoff. This equivalence is useful both for least squares fitting and for the evaluation of a large number of Hermite series of the same degree and sample points. Parameters ---------- x : array_like Array of points. The dtype is converted to float64 or complex128 depending on whether any of the elements are complex. If `x` is scalar it is converted to a 1-D array. deg : int Degree of the resulting matrix. Returns ------- vander : ndarray The pseudo-Vandermonde matrix. The shape of the returned matrix is ``x.shape + (deg + 1,)``, where The last index is the degree of the corresponding Hermite polynomial. The dtype will be the same as the converted `x`. Examples -------- >>> from numpy.polynomial.hermite import hermvander >>> x = np.array([-1, 0, 1]) >>> hermvander(x, 3) array([[ 1., -2., 2., 4.], [ 1., 0., -2., -0.], [ 1., 2., 2., -4.]]) """ ideg = int(deg) if ideg != deg: raise ValueError("deg must be integer") if ideg < 0: raise ValueError("deg must be non-negative") x = np.array(x, copy=0, ndmin=1) + 0.0 dims = (ideg + 1,) + x.shape dtyp = x.dtype v = np.empty(dims, dtype=dtyp) v[0] = x*0 + 1 if ideg > 0 : x2 = x*2 v[1] = x2 for i in range(2, ideg + 1) : v[i] = (v[i-1]*x2 - v[i-2]*(2*(i - 1))) return np.rollaxis(v, 0, v.ndim) def hermvander2d(x, y, deg) : """Pseudo-Vandermonde matrix of given degrees. Returns the pseudo-Vandermonde matrix of degrees `deg` and sample points `(x, y)`. The pseudo-Vandermonde matrix is defined by .. math:: V[..., deg[1]*i + j] = H_i(x) * H_j(y), where `0 <= i <= deg[0]` and `0 <= j <= deg[1]`. The leading indices of `V` index the points `(x, y)` and the last index encodes the degrees of the Hermite polynomials. If ``V = hermvander2d(x, y, [xdeg, ydeg])``, then the columns of `V` correspond to the elements of a 2-D coefficient array `c` of shape (xdeg + 1, ydeg + 1) in the order .. math:: c_{00}, c_{01}, c_{02} ... , c_{10}, c_{11}, c_{12} ... and ``np.dot(V, c.flat)`` and ``hermval2d(x, y, c)`` will be the same up to roundoff. This equivalence is useful both for least squares fitting and for the evaluation of a large number of 2-D Hermite series of the same degrees and sample points. Parameters ---------- x, y : array_like Arrays of point coordinates, all of the same shape. The dtypes will be converted to either float64 or complex128 depending on whether any of the elements are complex. Scalars are converted to 1-D arrays. deg : list of ints List of maximum degrees of the form [x_deg, y_deg]. Returns ------- vander2d : ndarray The shape of the returned matrix is ``x.shape + (order,)``, where :math:`order = (deg[0]+1)*(deg([1]+1)`. The dtype will be the same as the converted `x` and `y`. See Also -------- hermvander, hermvander3d. hermval2d, hermval3d Notes ----- .. versionadded::1.7.0 """ ideg = [int(d) for d in deg] is_valid = [id == d and id >= 0 for id, d in zip(ideg, deg)] if is_valid != [1, 1]: raise ValueError("degrees must be non-negative integers") degx, degy = ideg x, y = np.array((x, y), copy=0) + 0.0 vx = hermvander(x, degx) vy = hermvander(y, degy) v = vx[..., None]*vy[..., None,:] return v.reshape(v.shape[:-2] + (-1,)) def hermvander3d(x, y, z, deg) : """Pseudo-Vandermonde matrix of given degrees. Returns the pseudo-Vandermonde matrix of degrees `deg` and sample points `(x, y, z)`. If `l, m, n` are the given degrees in `x, y, z`, then The pseudo-Vandermonde matrix is defined by .. math:: V[..., (m+1)(n+1)i + (n+1)j + k] = H_i(x)*H_j(y)*H_k(z), where `0 <= i <= l`, `0 <= j <= m`, and `0 <= j <= n`. The leading indices of `V` index the points `(x, y, z)` and the last index encodes the degrees of the Hermite polynomials. If ``V = hermvander3d(x, y, z, [xdeg, ydeg, zdeg])``, then the columns of `V` correspond to the elements of a 3-D coefficient array `c` of shape (xdeg + 1, ydeg + 1, zdeg + 1) in the order .. math:: c_{000}, c_{001}, c_{002},... , c_{010}, c_{011}, c_{012},... and ``np.dot(V, c.flat)`` and ``hermval3d(x, y, z, c)`` will be the same up to roundoff. This equivalence is useful both for least squares fitting and for the evaluation of a large number of 3-D Hermite series of the same degrees and sample points. Parameters ---------- x, y, z : array_like Arrays of point coordinates, all of the same shape. The dtypes will be converted to either float64 or complex128 depending on whether any of the elements are complex. Scalars are converted to 1-D arrays. deg : list of ints List of maximum degrees of the form [x_deg, y_deg, z_deg]. Returns ------- vander3d : ndarray The shape of the returned matrix is ``x.shape + (order,)``, where :math:`order = (deg[0]+1)*(deg([1]+1)*(deg[2]+1)`. The dtype will be the same as the converted `x`, `y`, and `z`. See Also -------- hermvander, hermvander3d. hermval2d, hermval3d Notes ----- .. versionadded::1.7.0 """ ideg = [int(d) for d in deg] is_valid = [id == d and id >= 0 for id, d in zip(ideg, deg)] if is_valid != [1, 1, 1]: raise ValueError("degrees must be non-negative integers") degx, degy, degz = ideg x, y, z = np.array((x, y, z), copy=0) + 0.0 vx = hermvander(x, degx) vy = hermvander(y, degy) vz = hermvander(z, degz) v = vx[..., None, None]*vy[..., None,:, None]*vz[..., None, None,:] return v.reshape(v.shape[:-3] + (-1,)) def hermfit(x, y, deg, rcond=None, full=False, w=None): """ Least squares fit of Hermite series to data. Return the coefficients of a Hermite series of degree `deg` that is the least squares fit to the data values `y` given at points `x`. If `y` is 1-D the returned coefficients will also be 1-D. If `y` is 2-D multiple fits are done, one for each column of `y`, and the resulting coefficients are stored in the corresponding columns of a 2-D return. The fitted polynomial(s) are in the form .. math:: p(x) = c_0 + c_1 * H_1(x) + ... + c_n * H_n(x), 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,) 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 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. Returns ------- coef : ndarray, shape (M,) or (M, K) Hermite coefficients ordered from low to high. If `y` was 2-D, 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`. Warns ----- RankWarning The rank of the coefficient matrix in the least-squares fit is deficient. The warning is only raised if `full` = False. The warnings can be turned off by >>> import warnings >>> warnings.simplefilter('ignore', RankWarning) See Also -------- chebfit, legfit, lagfit, polyfit, hermefit hermval : Evaluates a Hermite series. hermvander : Vandermonde matrix of Hermite series. hermweight : Hermite weight function linalg.lstsq : Computes a least-squares fit from the matrix. scipy.interpolate.UnivariateSpline : Computes spline fits. Notes ----- The solution is the coefficients of the Hermite series `p` that minimizes the sum of the weighted squared errors .. math:: E = \\sum_j w_j^2 * |y_j - p(x_j)|^2, where the :math:`w_j` are the weights. This problem is solved by setting up the (typically) overdetermined matrix equation .. math:: V(x) * c = w * y, where `V` is the weighted pseudo Vandermonde matrix of `x`, `c` are the coefficients to be solved for, `w` are the weights, `y` are the observed values. This equation is then solved using the singular value decomposition of `V`. If some of the singular values of `V` are so small that they are neglected, then a `RankWarning` will be issued. This means that the coefficient values may be poorly determined. Using a lower order fit will usually get rid of the warning. The `rcond` parameter can also be set to a value smaller than its default, but the resulting fit may be spurious and have large contributions from roundoff error. Fits using Hermite series are probably most useful when the data can be approximated by ``sqrt(w(x)) * p(x)``, where `w(x)` is the Hermite weight. In that case the weight ``sqrt(w(x[i])`` should be used together with data values ``y[i]/sqrt(w(x[i])``. The weight function is available as `hermweight`. References ---------- .. [1] Wikipedia, "Curve fitting", http://en.wikipedia.org/wiki/Curve_fitting Examples -------- >>> from numpy.polynomial.hermite import hermfit, hermval >>> x = np.linspace(-10, 10) >>> err = np.random.randn(len(x))/10 >>> y = hermval(x, [1, 2, 3]) + err >>> hermfit(x, y, 2) array([ 0.97902637, 1.99849131, 3.00006 ]) """ order = int(deg) + 1 x = np.asarray(x) + 0.0 y = np.asarray(y) + 0.0 # check arguments. if deg < 0 : raise ValueError("expected deg >= 0") if x.ndim != 1: raise TypeError("expected 1D vector for x") if x.size == 0: raise TypeError("expected non-empty vector for x") if y.ndim < 1 or y.ndim > 2 : raise TypeError("expected 1D or 2D array for y") if len(x) != len(y): raise TypeError("expected x and y to have same length") # set up the least squares matrices in transposed form lhs = hermvander(x, deg).T rhs = y.T if w is not None: w = np.asarray(w) + 0.0 if w.ndim != 1: raise TypeError("expected 1D vector for w") if len(x) != len(w): raise TypeError("expected x and w to have same length") # apply weights. Don't use inplace operations as they # can cause problems with NA. lhs = lhs * w rhs = rhs * w # set rcond if rcond is None : rcond = len(x)*np.finfo(x.dtype).eps # Determine the norms of the design matrix columns. if issubclass(lhs.dtype.type, np.complexfloating): scl = np.sqrt((np.square(lhs.real) + np.square(lhs.imag)).sum(1)) else: scl = np.sqrt(np.square(lhs).sum(1)) scl[scl == 0] = 1 # Solve the least squares problem. c, resids, rank, s = la.lstsq(lhs.T/scl, rhs.T, rcond) c = (c.T/scl).T # warn on rank reduction if rank != order and not full: msg = "The fit may be poorly conditioned" warnings.warn(msg, pu.RankWarning) if full : return c, [resids, rank, s, rcond] else : return c def hermcompanion(c): """Return the scaled companion matrix of c. The basis polynomials are scaled so that the companion matrix is symmetric when `c` is an Hermite basis polynomial. This provides better eigenvalue estimates than the unscaled case and for basis polynomials the eigenvalues are guaranteed to be real if `numpy.linalg.eigvalsh` is used to obtain them. Parameters ---------- c : array_like 1-D array of Hermite series coefficients ordered from low to high degree. Returns ------- mat : ndarray Scaled companion matrix of dimensions (deg, deg). Notes ----- .. versionadded::1.7.0 """ accprod = np.multiply.accumulate # c is a trimmed copy [c] = pu.as_series([c]) if len(c) < 2: raise ValueError('Series must have maximum degree of at least 1.') if len(c) == 2: return np.array([[-.5*c[0]/c[1]]]) n = len(c) - 1 mat = np.zeros((n, n), dtype=c.dtype) scl = np.hstack((1., np.sqrt(2.*np.arange(1, n)))) scl = np.multiply.accumulate(scl) top = mat.reshape(-1)[1::n+1] bot = mat.reshape(-1)[n::n+1] top[...] = np.sqrt(.5*np.arange(1, n)) bot[...] = top mat[:, -1] -= (c[:-1]/c[-1])*(scl/scl[-1])*.5 return mat def hermroots(c): """ Compute the roots of a Hermite series. Return the roots (a.k.a. "zeros") of the polynomial .. math:: p(x) = \\sum_i c[i] * H_i(x). Parameters ---------- c : 1-D array_like 1-D array of coefficients. Returns ------- out : ndarray Array of the roots of the series. If all the roots are real, then `out` is also real, otherwise it is complex. See Also -------- polyroots, legroots, lagroots, chebroots, hermeroots Notes ----- The root estimates are obtained as the eigenvalues of the companion matrix, Roots far from the origin of the complex plane may have large errors due to the numerical instability of the series for such values. Roots with multiplicity greater than 1 will also show larger errors as the value of the series near such points is relatively insensitive to errors in the roots. Isolated roots near the origin can be improved by a few iterations of Newton's method. The Hermite series basis polynomials aren't powers of `x` so the results of this function may seem unintuitive. Examples -------- >>> from numpy.polynomial.hermite import hermroots, hermfromroots >>> coef = hermfromroots([-1, 0, 1]) >>> coef array([ 0. , 0.25 , 0. , 0.125]) >>> hermroots(coef) array([ -1.00000000e+00, -1.38777878e-17, 1.00000000e+00]) """ # c is a trimmed copy [c] = pu.as_series([c]) if len(c) <= 1 : return np.array([], dtype=c.dtype) if len(c) == 2 : return np.array([-.5*c[0]/c[1]]) m = hermcompanion(c) r = la.eigvals(m) r.sort() return r def hermgauss(deg): """ Gauss-Hermite quadrature. Computes the sample points and weights for Gauss-Hermite quadrature. These sample points and weights will correctly integrate polynomials of degree :math:`2*deg - 1` or less over the interval :math:`[-\inf, \inf]` with the weight function :math:`f(x) = \exp(-x^2)`. Parameters ---------- deg : int Number of sample points and weights. It must be >= 1. Returns ------- x : ndarray 1-D ndarray containing the sample points. y : ndarray 1-D ndarray containing the weights. Notes ----- .. versionadded::1.7.0 The results have only been tested up to degree 100, higher degrees may be problematic. The weights are determined by using the fact that .. math:: w_k = c / (H'_n(x_k) * H_{n-1}(x_k)) where :math:`c` is a constant independent of :math:`k` and :math:`x_k` is the k'th root of :math:`H_n`, and then scaling the results to get the right value when integrating 1. """ ideg = int(deg) if ideg != deg or ideg < 1: raise ValueError("deg must be a non-negative integer") # first approximation of roots. We use the fact that the companion # matrix is symmetric in this case in order to obtain better zeros. c = np.array([0]*deg + [1]) m = hermcompanion(c) x = la.eigvals(m) x.sort() # improve roots by one application of Newton dy = hermval(x, c) df = hermval(x, hermder(c)) x -= dy/df # compute the weights. We scale the factor to avoid possible numerical # overflow. fm = hermval(x, c[1:]) fm /= np.abs(fm).max() df /= np.abs(df).max() w = 1/(fm * df) # for Hermite we can also symmetrize w = (w + w[::-1])/2 x = (x - x[::-1])/2 # scale w to get the right value w *= np.sqrt(np.pi) / w.sum() return x, w def hermweight(x): """ Weight function of the Hermite polynomials. The weight function is :math:`\exp(-x^2)` and the interval of integration is :math:`[-\inf, \inf]`. the Hermite polynomials are orthogonal, but not normalized, with respect to this weight function. Parameters ---------- x : array_like Values at which the weight function will be computed. Returns ------- w : ndarray The weight function at `x`. Notes ----- .. versionadded::1.7.0 """ w = np.exp(-x**2) return w # # Hermite series class # exec(polytemplate.substitute(name='Hermite', nick='herm', domain='[-1,1]')) numpy-1.8.2/numpy/add_newdocs.py0000664000175100017510000064714612370216243020042 0ustar vagrantvagrant00000000000000""" This is only meant to add docs to objects defined in C-extension modules. The purpose is to allow easier editing of the docstrings without requiring a re-compile. NOTE: Many of the methods of ndarray have corresponding functions. If you update these docstrings, please keep also the ones in core/fromnumeric.py, core/defmatrix.py up-to-date. """ from __future__ import division, absolute_import, print_function from numpy.lib import add_newdoc ############################################################################### # # flatiter # # flatiter needs a toplevel description # ############################################################################### add_newdoc('numpy.core', 'flatiter', """ Flat iterator object to iterate over arrays. A `flatiter` iterator is returned by ``x.flat`` for any array `x`. It allows iterating over the array as if it were a 1-D array, either in a for-loop or by calling its `next` method. Iteration is done in C-contiguous style, with the last index varying the fastest. The iterator can also be indexed using basic slicing or advanced indexing. See Also -------- ndarray.flat : Return a flat iterator over an array. ndarray.flatten : Returns a flattened copy of an array. Notes ----- A `flatiter` iterator can not be constructed directly from Python code by calling the `flatiter` constructor. Examples -------- >>> x = np.arange(6).reshape(2, 3) >>> fl = x.flat >>> type(fl) >>> for item in fl: ... print item ... 0 1 2 3 4 5 >>> fl[2:4] array([2, 3]) """) # flatiter attributes add_newdoc('numpy.core', 'flatiter', ('base', """ A reference to the array that is iterated over. Examples -------- >>> x = np.arange(5) >>> fl = x.flat >>> fl.base is x True """)) add_newdoc('numpy.core', 'flatiter', ('coords', """ An N-dimensional tuple of current coordinates. Examples -------- >>> x = np.arange(6).reshape(2, 3) >>> fl = x.flat >>> fl.coords (0, 0) >>> fl.next() 0 >>> fl.coords (0, 1) """)) add_newdoc('numpy.core', 'flatiter', ('index', """ Current flat index into the array. Examples -------- >>> x = np.arange(6).reshape(2, 3) >>> fl = x.flat >>> fl.index 0 >>> fl.next() 0 >>> fl.index 1 """)) # flatiter functions add_newdoc('numpy.core', 'flatiter', ('__array__', """__array__(type=None) Get array from iterator """)) add_newdoc('numpy.core', 'flatiter', ('copy', """ copy() Get a copy of the iterator as a 1-D array. Examples -------- >>> x = np.arange(6).reshape(2, 3) >>> x array([[0, 1, 2], [3, 4, 5]]) >>> fl = x.flat >>> fl.copy() array([0, 1, 2, 3, 4, 5]) """)) ############################################################################### # # nditer # ############################################################################### add_newdoc('numpy.core', 'nditer', """ Efficient multi-dimensional iterator object to iterate over arrays. To get started using this object, see the :ref:`introductory guide to array iteration `. Parameters ---------- op : ndarray or sequence of array_like The array(s) to iterate over. flags : sequence of str, optional Flags to control the behavior of the iterator. * "buffered" enables buffering when required. * "c_index" causes a C-order index to be tracked. * "f_index" causes a Fortran-order index to be tracked. * "multi_index" causes a multi-index, or a tuple of indices with one per iteration dimension, to be tracked. * "common_dtype" causes all the operands to be converted to a common data type, with copying or buffering as necessary. * "delay_bufalloc" delays allocation of the buffers until a reset() call is made. Allows "allocate" operands to be initialized before their values are copied into the buffers. * "external_loop" causes the `values` given to be one-dimensional arrays with multiple values instead of zero-dimensional arrays. * "grow_inner" allows the `value` array sizes to be made larger than the buffer size when both "buffered" and "external_loop" is used. * "ranged" allows the iterator to be restricted to a sub-range of the iterindex values. * "refs_ok" enables iteration of reference types, such as object arrays. * "reduce_ok" enables iteration of "readwrite" operands which are broadcasted, also known as reduction operands. * "zerosize_ok" allows `itersize` to be zero. op_flags : list of list of str, optional This is a list of flags for each operand. At minimum, one of "readonly", "readwrite", or "writeonly" must be specified. * "readonly" indicates the operand will only be read from. * "readwrite" indicates the operand will be read from and written to. * "writeonly" indicates the operand will only be written to. * "no_broadcast" prevents the operand from being broadcasted. * "contig" forces the operand data to be contiguous. * "aligned" forces the operand data to be aligned. * "nbo" forces the operand data to be in native byte order. * "copy" allows a temporary read-only copy if required. * "updateifcopy" allows a temporary read-write copy if required. * "allocate" causes the array to be allocated if it is None in the `op` parameter. * "no_subtype" prevents an "allocate" operand from using a subtype. * "arraymask" indicates that this operand is the mask to use for selecting elements when writing to operands with the 'writemasked' flag set. The iterator does not enforce this, but when writing from a buffer back to the array, it only copies those elements indicated by this mask. * 'writemasked' indicates that only elements where the chosen 'arraymask' operand is True will be written to. op_dtypes : dtype or tuple of dtype(s), optional The required data type(s) of the operands. If copying or buffering is enabled, the data will be converted to/from their original types. order : {'C', 'F', 'A', 'K'}, optional Controls the iteration order. 'C' means C order, 'F' means Fortran order, 'A' means 'F' order if all the arrays are Fortran contiguous, 'C' order otherwise, and 'K' means as close to the order the array elements appear in memory as possible. This also affects the element memory order of "allocate" operands, as they are allocated to be compatible with iteration order. Default is 'K'. casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional Controls what kind of data casting may occur when making a copy or buffering. Setting this to 'unsafe' is not recommended, as it can adversely affect accumulations. * 'no' means the data types should not be cast at all. * 'equiv' means only byte-order changes are allowed. * 'safe' means only casts which can preserve values are allowed. * 'same_kind' means only safe casts or casts within a kind, like float64 to float32, are allowed. * 'unsafe' means any data conversions may be done. op_axes : list of list of ints, optional If provided, is a list of ints or None for each operands. The list of axes for an operand is a mapping from the dimensions of the iterator to the dimensions of the operand. A value of -1 can be placed for entries, causing that dimension to be treated as "newaxis". itershape : tuple of ints, optional The desired shape of the iterator. This allows "allocate" operands with a dimension mapped by op_axes not corresponding to a dimension of a different operand to get a value not equal to 1 for that dimension. buffersize : int, optional When buffering is enabled, controls the size of the temporary buffers. Set to 0 for the default value. Attributes ---------- dtypes : tuple of dtype(s) The data types of the values provided in `value`. This may be different from the operand data types if buffering is enabled. finished : bool Whether the iteration over the operands is finished or not. has_delayed_bufalloc : bool If True, the iterator was created with the "delay_bufalloc" flag, and no reset() function was called on it yet. has_index : bool If True, the iterator was created with either the "c_index" or the "f_index" flag, and the property `index` can be used to retrieve it. has_multi_index : bool If True, the iterator was created with the "multi_index" flag, and the property `multi_index` can be used to retrieve it. index : When the "c_index" or "f_index" flag was used, this property provides access to the index. Raises a ValueError if accessed and `has_index` is False. iterationneedsapi : bool Whether iteration requires access to the Python API, for example if one of the operands is an object array. iterindex : int An index which matches the order of iteration. itersize : int Size of the iterator. itviews : Structured view(s) of `operands` in memory, matching the reordered and optimized iterator access pattern. multi_index : When the "multi_index" flag was used, this property provides access to the index. Raises a ValueError if accessed accessed and `has_multi_index` is False. ndim : int The iterator's dimension. nop : int The number of iterator operands. operands : tuple of operand(s) The array(s) to be iterated over. shape : tuple of ints Shape tuple, the shape of the iterator. value : Value of `operands` at current iteration. Normally, this is a tuple of array scalars, but if the flag "external_loop" is used, it is a tuple of one dimensional arrays. Notes ----- `nditer` supersedes `flatiter`. The iterator implementation behind `nditer` is also exposed by the Numpy C API. The Python exposure supplies two iteration interfaces, one which follows the Python iterator protocol, and another which mirrors the C-style do-while pattern. The native Python approach is better in most cases, but if you need the iterator's coordinates or index, use the C-style pattern. Examples -------- Here is how we might write an ``iter_add`` function, using the Python iterator protocol:: def iter_add_py(x, y, out=None): addop = np.add it = np.nditer([x, y, out], [], [['readonly'], ['readonly'], ['writeonly','allocate']]) for (a, b, c) in it: addop(a, b, out=c) return it.operands[2] Here is the same function, but following the C-style pattern:: def iter_add(x, y, out=None): addop = np.add it = np.nditer([x, y, out], [], [['readonly'], ['readonly'], ['writeonly','allocate']]) while not it.finished: addop(it[0], it[1], out=it[2]) it.iternext() return it.operands[2] Here is an example outer product function:: def outer_it(x, y, out=None): mulop = np.multiply it = np.nditer([x, y, out], ['external_loop'], [['readonly'], ['readonly'], ['writeonly', 'allocate']], op_axes=[range(x.ndim)+[-1]*y.ndim, [-1]*x.ndim+range(y.ndim), None]) for (a, b, c) in it: mulop(a, b, out=c) return it.operands[2] >>> a = np.arange(2)+1 >>> b = np.arange(3)+1 >>> outer_it(a,b) array([[1, 2, 3], [2, 4, 6]]) Here is an example function which operates like a "lambda" ufunc:: def luf(lamdaexpr, *args, **kwargs): "luf(lambdaexpr, op1, ..., opn, out=None, order='K', casting='safe', buffersize=0)" nargs = len(args) op = (kwargs.get('out',None),) + args it = np.nditer(op, ['buffered','external_loop'], [['writeonly','allocate','no_broadcast']] + [['readonly','nbo','aligned']]*nargs, order=kwargs.get('order','K'), casting=kwargs.get('casting','safe'), buffersize=kwargs.get('buffersize',0)) while not it.finished: it[0] = lamdaexpr(*it[1:]) it.iternext() return it.operands[0] >>> a = np.arange(5) >>> b = np.ones(5) >>> luf(lambda i,j:i*i + j/2, a, b) array([ 0.5, 1.5, 4.5, 9.5, 16.5]) """) # nditer methods add_newdoc('numpy.core', 'nditer', ('copy', """ copy() Get a copy of the iterator in its current state. Examples -------- >>> x = np.arange(10) >>> y = x + 1 >>> it = np.nditer([x, y]) >>> it.next() (array(0), array(1)) >>> it2 = it.copy() >>> it2.next() (array(1), array(2)) """)) add_newdoc('numpy.core', 'nditer', ('debug_print', """ debug_print() Print the current state of the `nditer` instance and debug info to stdout. """)) add_newdoc('numpy.core', 'nditer', ('enable_external_loop', """ enable_external_loop() When the "external_loop" was not used during construction, but is desired, this modifies the iterator to behave as if the flag was specified. """)) add_newdoc('numpy.core', 'nditer', ('iternext', """ iternext() Check whether iterations are left, and perform a single internal iteration without returning the result. Used in the C-style pattern do-while pattern. For an example, see `nditer`. Returns ------- iternext : bool Whether or not there are iterations left. """)) add_newdoc('numpy.core', 'nditer', ('remove_axis', """ remove_axis(i) Removes axis `i` from the iterator. Requires that the flag "multi_index" be enabled. """)) add_newdoc('numpy.core', 'nditer', ('remove_multi_index', """ remove_multi_index() When the "multi_index" flag was specified, this removes it, allowing the internal iteration structure to be optimized further. """)) add_newdoc('numpy.core', 'nditer', ('reset', """ reset() Reset the iterator to its initial state. """)) ############################################################################### # # broadcast # ############################################################################### add_newdoc('numpy.core', 'broadcast', """ Produce an object that mimics broadcasting. Parameters ---------- in1, in2, ... : array_like Input parameters. Returns ------- b : broadcast object Broadcast the input parameters against one another, and return an object that encapsulates the result. Amongst others, it has ``shape`` and ``nd`` properties, and may be used as an iterator. Examples -------- Manually adding two vectors, using broadcasting: >>> x = np.array([[1], [2], [3]]) >>> y = np.array([4, 5, 6]) >>> b = np.broadcast(x, y) >>> out = np.empty(b.shape) >>> out.flat = [u+v for (u,v) in b] >>> out array([[ 5., 6., 7.], [ 6., 7., 8.], [ 7., 8., 9.]]) Compare against built-in broadcasting: >>> x + y array([[5, 6, 7], [6, 7, 8], [7, 8, 9]]) """) # attributes add_newdoc('numpy.core', 'broadcast', ('index', """ current index in broadcasted result Examples -------- >>> x = np.array([[1], [2], [3]]) >>> y = np.array([4, 5, 6]) >>> b = np.broadcast(x, y) >>> b.index 0 >>> b.next(), b.next(), b.next() ((1, 4), (1, 5), (1, 6)) >>> b.index 3 """)) add_newdoc('numpy.core', 'broadcast', ('iters', """ tuple of iterators along ``self``'s "components." Returns a tuple of `numpy.flatiter` objects, one for each "component" of ``self``. See Also -------- numpy.flatiter Examples -------- >>> x = np.array([1, 2, 3]) >>> y = np.array([[4], [5], [6]]) >>> b = np.broadcast(x, y) >>> row, col = b.iters >>> row.next(), col.next() (1, 4) """)) add_newdoc('numpy.core', 'broadcast', ('nd', """ Number of dimensions of broadcasted result. Examples -------- >>> x = np.array([1, 2, 3]) >>> y = np.array([[4], [5], [6]]) >>> b = np.broadcast(x, y) >>> b.nd 2 """)) add_newdoc('numpy.core', 'broadcast', ('numiter', """ Number of iterators possessed by the broadcasted result. Examples -------- >>> x = np.array([1, 2, 3]) >>> y = np.array([[4], [5], [6]]) >>> b = np.broadcast(x, y) >>> b.numiter 2 """)) add_newdoc('numpy.core', 'broadcast', ('shape', """ Shape of broadcasted result. Examples -------- >>> x = np.array([1, 2, 3]) >>> y = np.array([[4], [5], [6]]) >>> b = np.broadcast(x, y) >>> b.shape (3, 3) """)) add_newdoc('numpy.core', 'broadcast', ('size', """ Total size of broadcasted result. Examples -------- >>> x = np.array([1, 2, 3]) >>> y = np.array([[4], [5], [6]]) >>> b = np.broadcast(x, y) >>> b.size 9 """)) add_newdoc('numpy.core', 'broadcast', ('reset', """ reset() Reset the broadcasted result's iterator(s). Parameters ---------- None Returns ------- None Examples -------- >>> x = np.array([1, 2, 3]) >>> y = np.array([[4], [5], [6]] >>> b = np.broadcast(x, y) >>> b.index 0 >>> b.next(), b.next(), b.next() ((1, 4), (2, 4), (3, 4)) >>> b.index 3 >>> b.reset() >>> b.index 0 """)) ############################################################################### # # numpy functions # ############################################################################### add_newdoc('numpy.core.multiarray', 'array', """ array(object, dtype=None, copy=True, order=None, subok=False, ndmin=0) Create an array. Parameters ---------- object : array_like An array, any object exposing the array interface, an object whose __array__ method returns an array, or any (nested) sequence. dtype : data-type, optional The desired data-type for the array. If not given, then the type will be determined as the minimum type required to hold the objects in the sequence. This argument can only be used to 'upcast' the array. For downcasting, use the .astype(t) method. copy : bool, optional If true (default), then the object is copied. Otherwise, a copy will only be made if __array__ returns a copy, if obj is a nested sequence, or if a copy is needed to satisfy any of the other requirements (`dtype`, `order`, etc.). order : {'C', 'F', 'A'}, optional Specify the order of the array. If order is 'C' (default), then the array will be in C-contiguous order (last-index varies the fastest). If order is 'F', then the returned array will be in Fortran-contiguous order (first-index varies the fastest). If order is 'A', then the returned array may be in any order (either C-, Fortran-contiguous, or even discontiguous). subok : bool, optional If True, then sub-classes will be passed-through, otherwise the returned array will be forced to be a base-class array (default). ndmin : int, optional Specifies the minimum number of dimensions that the resulting array should have. Ones will be pre-pended to the shape as needed to meet this requirement. Returns ------- out : ndarray An array object satisfying the specified requirements. See Also -------- empty, empty_like, zeros, zeros_like, ones, ones_like, fill Examples -------- >>> np.array([1, 2, 3]) array([1, 2, 3]) Upcasting: >>> np.array([1, 2, 3.0]) array([ 1., 2., 3.]) More than one dimension: >>> np.array([[1, 2], [3, 4]]) array([[1, 2], [3, 4]]) Minimum dimensions 2: >>> np.array([1, 2, 3], ndmin=2) array([[1, 2, 3]]) Type provided: >>> np.array([1, 2, 3], dtype=complex) array([ 1.+0.j, 2.+0.j, 3.+0.j]) Data-type consisting of more than one element: >>> x = np.array([(1,2),(3,4)],dtype=[('a','>> x['a'] array([1, 3]) Creating an array from sub-classes: >>> np.array(np.mat('1 2; 3 4')) array([[1, 2], [3, 4]]) >>> np.array(np.mat('1 2; 3 4'), subok=True) matrix([[1, 2], [3, 4]]) """) add_newdoc('numpy.core.multiarray', 'empty', """ empty(shape, dtype=float, order='C') Return a new array of given shape and type, without initializing entries. Parameters ---------- shape : int or tuple of int Shape of the empty array dtype : data-type, optional Desired output data-type. order : {'C', 'F'}, optional Whether to store multi-dimensional data in C (row-major) or Fortran (column-major) order in memory. See Also -------- empty_like, zeros, ones Notes ----- `empty`, unlike `zeros`, does not set the array values to zero, and may therefore be marginally faster. On the other hand, it requires the user to manually set all the values in the array, and should be used with caution. Examples -------- >>> np.empty([2, 2]) array([[ -9.74499359e+001, 6.69583040e-309], [ 2.13182611e-314, 3.06959433e-309]]) #random >>> np.empty([2, 2], dtype=int) array([[-1073741821, -1067949133], [ 496041986, 19249760]]) #random """) add_newdoc('numpy.core.multiarray', 'empty_like', """ empty_like(a, dtype=None, order='K', subok=True) Return a new array with the same shape and type as a given array. Parameters ---------- a : array_like The shape and data-type of `a` define these same attributes of the returned array. dtype : data-type, optional .. versionadded:: 1.6.0 Overrides the data type of the result. order : {'C', 'F', 'A', or 'K'}, optional .. versionadded:: 1.6.0 Overrides the memory layout of the result. 'C' means C-order, 'F' means F-order, 'A' means 'F' if ``a`` is Fortran contiguous, 'C' otherwise. 'K' means match the layout of ``a`` as closely as possible. subok : bool, optional. If True, then the newly created array will use the sub-class type of 'a', otherwise it will be a base-class array. Defaults to True. Returns ------- out : ndarray Array of uninitialized (arbitrary) data with the same shape and type as `a`. See Also -------- ones_like : Return an array of ones with shape and type of input. zeros_like : Return an array of zeros with shape and type of input. empty : Return a new uninitialized array. ones : Return a new array setting values to one. zeros : Return a new array setting values to zero. Notes ----- This function does *not* initialize the returned array; to do that use `zeros_like` or `ones_like` instead. It may be marginally faster than the functions that do set the array values. Examples -------- >>> a = ([1,2,3], [4,5,6]) # a is array-like >>> np.empty_like(a) array([[-1073741821, -1073741821, 3], #random [ 0, 0, -1073741821]]) >>> a = np.array([[1., 2., 3.],[4.,5.,6.]]) >>> np.empty_like(a) array([[ -2.00000715e+000, 1.48219694e-323, -2.00000572e+000],#random [ 4.38791518e-305, -2.00000715e+000, 4.17269252e-309]]) """) add_newdoc('numpy.core.multiarray', 'scalar', """ scalar(dtype, obj) Return a new scalar array of the given type initialized with obj. This function is meant mainly for pickle support. `dtype` must be a valid data-type descriptor. If `dtype` corresponds to an object descriptor, then `obj` can be any object, otherwise `obj` must be a string. If `obj` is not given, it will be interpreted as None for object type and as zeros for all other types. """) add_newdoc('numpy.core.multiarray', 'zeros', """ zeros(shape, dtype=float, order='C') Return a new array of given shape and type, filled with zeros. Parameters ---------- shape : int or sequence of ints Shape of the new array, e.g., ``(2, 3)`` or ``2``. dtype : data-type, optional The desired data-type for the array, e.g., `numpy.int8`. Default is `numpy.float64`. order : {'C', 'F'}, optional Whether to store multidimensional data in C- or Fortran-contiguous (row- or column-wise) order in memory. Returns ------- out : ndarray Array of zeros with the given shape, dtype, and order. See Also -------- zeros_like : Return an array of zeros with shape and type of input. ones_like : Return an array of ones with shape and type of input. empty_like : Return an empty array with shape and type of input. ones : Return a new array setting values to one. empty : Return a new uninitialized array. Examples -------- >>> np.zeros(5) array([ 0., 0., 0., 0., 0.]) >>> np.zeros((5,), dtype=numpy.int) array([0, 0, 0, 0, 0]) >>> np.zeros((2, 1)) array([[ 0.], [ 0.]]) >>> s = (2,2) >>> np.zeros(s) array([[ 0., 0.], [ 0., 0.]]) >>> np.zeros((2,), dtype=[('x', 'i4'), ('y', 'i4')]) # custom dtype array([(0, 0), (0, 0)], dtype=[('x', '>> np.count_nonzero(np.eye(4)) 4 >>> np.count_nonzero([[0,1,7,0,0],[3,0,0,2,19]]) 5 """) add_newdoc('numpy.core.multiarray', 'set_typeDict', """set_typeDict(dict) Set the internal dictionary that can look up an array type using a registered code. """) add_newdoc('numpy.core.multiarray', 'fromstring', """ fromstring(string, dtype=float, count=-1, sep='') A new 1-D array initialized from raw binary or text data in a string. Parameters ---------- string : str A string containing the data. dtype : data-type, optional The data type of the array; default: float. For binary input data, the data must be in exactly this format. count : int, optional Read this number of `dtype` elements from the data. If this is negative (the default), the count will be determined from the length of the data. sep : str, optional If not provided or, equivalently, the empty string, the data will be interpreted as binary data; otherwise, as ASCII text with decimal numbers. Also in this latter case, this argument is interpreted as the string separating numbers in the data; extra whitespace between elements is also ignored. Returns ------- arr : ndarray The constructed array. Raises ------ ValueError If the string is not the correct size to satisfy the requested `dtype` and `count`. See Also -------- frombuffer, fromfile, fromiter Examples -------- >>> np.fromstring('\\x01\\x02', dtype=np.uint8) array([1, 2], dtype=uint8) >>> np.fromstring('1 2', dtype=int, sep=' ') array([1, 2]) >>> np.fromstring('1, 2', dtype=int, sep=',') array([1, 2]) >>> np.fromstring('\\x01\\x02\\x03\\x04\\x05', dtype=np.uint8, count=3) array([1, 2, 3], dtype=uint8) """) add_newdoc('numpy.core.multiarray', 'fromiter', """ fromiter(iterable, dtype, count=-1) Create a new 1-dimensional array from an iterable object. Parameters ---------- iterable : iterable object An iterable object providing data for the array. dtype : data-type The data-type of the returned array. count : int, optional The number of items to read from *iterable*. The default is -1, which means all data is read. Returns ------- out : ndarray The output array. Notes ----- Specify `count` to improve performance. It allows ``fromiter`` to pre-allocate the output array, instead of resizing it on demand. Examples -------- >>> iterable = (x*x for x in range(5)) >>> np.fromiter(iterable, np.float) array([ 0., 1., 4., 9., 16.]) """) add_newdoc('numpy.core.multiarray', 'fromfile', """ fromfile(file, dtype=float, count=-1, sep='') Construct an array from data in a text or binary file. A highly efficient way of reading binary data with a known data-type, as well as parsing simply formatted text files. Data written using the `tofile` method can be read using this function. Parameters ---------- file : file or str Open file object or filename. dtype : data-type Data type of the returned array. For binary files, it is used to determine the size and byte-order of the items in the file. count : int Number of items to read. ``-1`` means all items (i.e., the complete file). sep : str Separator between items if file is a text file. Empty ("") separator means the file should be treated as binary. Spaces (" ") in the separator match zero or more whitespace characters. A separator consisting only of spaces must match at least one whitespace. See also -------- load, save ndarray.tofile loadtxt : More flexible way of loading data from a text file. Notes ----- Do not rely on the combination of `tofile` and `fromfile` for data storage, as the binary files generated are are not platform independent. In particular, no byte-order or data-type information is saved. Data can be stored in the platform independent ``.npy`` format using `save` and `load` instead. Examples -------- Construct an ndarray: >>> dt = np.dtype([('time', [('min', int), ('sec', int)]), ... ('temp', float)]) >>> x = np.zeros((1,), dtype=dt) >>> x['time']['min'] = 10; x['temp'] = 98.25 >>> x array([((10, 0), 98.25)], dtype=[('time', [('min', '>> import os >>> fname = os.tmpnam() >>> x.tofile(fname) Read the raw data from disk: >>> np.fromfile(fname, dtype=dt) array([((10, 0), 98.25)], dtype=[('time', [('min', '>> np.save(fname, x) >>> np.load(fname + '.npy') array([((10, 0), 98.25)], dtype=[('time', [('min', '>> dt = np.dtype(int) >>> dt = dt.newbyteorder('>') >>> np.frombuffer(buf, dtype=dt) The data of the resulting array will not be byteswapped, but will be interpreted correctly. Examples -------- >>> s = 'hello world' >>> np.frombuffer(s, dtype='S1', count=5, offset=6) array(['w', 'o', 'r', 'l', 'd'], dtype='|S1') """) add_newdoc('numpy.core.multiarray', 'concatenate', """ concatenate((a1, a2, ...), axis=0) Join a sequence of arrays together. Parameters ---------- a1, a2, ... : sequence of array_like The arrays must have the same shape, except in the dimension corresponding to `axis` (the first, by default). axis : int, optional The axis along which the arrays will be joined. Default is 0. Returns ------- res : ndarray The concatenated array. See Also -------- ma.concatenate : Concatenate function that preserves input masks. array_split : Split an array into multiple sub-arrays of equal or near-equal size. split : Split array into a list of multiple sub-arrays of equal size. hsplit : Split array into multiple sub-arrays horizontally (column wise) vsplit : Split array into multiple sub-arrays vertically (row wise) dsplit : Split array into multiple sub-arrays along the 3rd axis (depth). hstack : Stack arrays in sequence horizontally (column wise) vstack : Stack arrays in sequence vertically (row wise) dstack : Stack arrays in sequence depth wise (along third dimension) Notes ----- When one or more of the arrays to be concatenated is a MaskedArray, this function will return a MaskedArray object instead of an ndarray, but the input masks are *not* preserved. In cases where a MaskedArray is expected as input, use the ma.concatenate function from the masked array module instead. Examples -------- >>> a = np.array([[1, 2], [3, 4]]) >>> b = np.array([[5, 6]]) >>> np.concatenate((a, b), axis=0) array([[1, 2], [3, 4], [5, 6]]) >>> np.concatenate((a, b.T), axis=1) array([[1, 2, 5], [3, 4, 6]]) This function will not preserve masking of MaskedArray inputs. >>> a = np.ma.arange(3) >>> a[1] = np.ma.masked >>> b = np.arange(2, 5) >>> a masked_array(data = [0 -- 2], mask = [False True False], fill_value = 999999) >>> b array([2, 3, 4]) >>> np.concatenate([a, b]) masked_array(data = [0 1 2 2 3 4], mask = False, fill_value = 999999) >>> np.ma.concatenate([a, b]) masked_array(data = [0 -- 2 2 3 4], mask = [False True False False False False], fill_value = 999999) """) add_newdoc('numpy.core', 'inner', """ inner(a, b) Inner product of two arrays. Ordinary inner product of vectors for 1-D arrays (without complex conjugation), in higher dimensions a sum product over the last axes. Parameters ---------- a, b : array_like If `a` and `b` are nonscalar, their last dimensions of must match. Returns ------- out : ndarray `out.shape = a.shape[:-1] + b.shape[:-1]` Raises ------ ValueError If the last dimension of `a` and `b` has different size. See Also -------- tensordot : Sum products over arbitrary axes. dot : Generalised matrix product, using second last dimension of `b`. einsum : Einstein summation convention. Notes ----- For vectors (1-D arrays) it computes the ordinary inner-product:: np.inner(a, b) = sum(a[:]*b[:]) More generally, if `ndim(a) = r > 0` and `ndim(b) = s > 0`:: np.inner(a, b) = np.tensordot(a, b, axes=(-1,-1)) or explicitly:: np.inner(a, b)[i0,...,ir-1,j0,...,js-1] = sum(a[i0,...,ir-1,:]*b[j0,...,js-1,:]) In addition `a` or `b` may be scalars, in which case:: np.inner(a,b) = a*b Examples -------- Ordinary inner product for vectors: >>> a = np.array([1,2,3]) >>> b = np.array([0,1,0]) >>> np.inner(a, b) 2 A multidimensional example: >>> a = np.arange(24).reshape((2,3,4)) >>> b = np.arange(4) >>> np.inner(a, b) array([[ 14, 38, 62], [ 86, 110, 134]]) An example where `b` is a scalar: >>> np.inner(np.eye(2), 7) array([[ 7., 0.], [ 0., 7.]]) """) add_newdoc('numpy.core', 'fastCopyAndTranspose', """_fastCopyAndTranspose(a)""") add_newdoc('numpy.core.multiarray', 'correlate', """cross_correlate(a,v, mode=0)""") add_newdoc('numpy.core.multiarray', 'arange', """ arange([start,] stop[, step,], dtype=None) Return evenly spaced values within a given interval. Values are generated within the half-open interval ``[start, stop)`` (in other words, the interval including `start` but excluding `stop`). For integer arguments the function is equivalent to the Python built-in `range `_ function, but returns an ndarray rather than a list. When using a non-integer step, such as 0.1, the results will often not be consistent. It is better to use ``linspace`` for these cases. Parameters ---------- start : number, optional Start of interval. The interval includes this value. The default start value is 0. stop : number End of interval. The interval does not include this value, except in some cases where `step` is not an integer and floating point round-off affects the length of `out`. step : number, optional Spacing between values. For any output `out`, this is the distance between two adjacent values, ``out[i+1] - out[i]``. The default step size is 1. If `step` is specified, `start` must also be given. dtype : dtype The type of the output array. If `dtype` is not given, infer the data type from the other input arguments. Returns ------- arange : ndarray Array of evenly spaced values. For floating point arguments, the length of the result is ``ceil((stop - start)/step)``. Because of floating point overflow, this rule may result in the last element of `out` being greater than `stop`. See Also -------- linspace : Evenly spaced numbers with careful handling of endpoints. ogrid: Arrays of evenly spaced numbers in N-dimensions. mgrid: Grid-shaped arrays of evenly spaced numbers in N-dimensions. Examples -------- >>> np.arange(3) array([0, 1, 2]) >>> np.arange(3.0) array([ 0., 1., 2.]) >>> np.arange(3,7) array([3, 4, 5, 6]) >>> np.arange(3,7,2) array([3, 5]) """) add_newdoc('numpy.core.multiarray', '_get_ndarray_c_version', """_get_ndarray_c_version() Return the compile time NDARRAY_VERSION number. """) add_newdoc('numpy.core.multiarray', '_reconstruct', """_reconstruct(subtype, shape, dtype) Construct an empty array. Used by Pickles. """) add_newdoc('numpy.core.multiarray', 'set_string_function', """ set_string_function(f, repr=1) Internal method to set a function to be used when pretty printing arrays. """) add_newdoc('numpy.core.multiarray', 'set_numeric_ops', """ set_numeric_ops(op1=func1, op2=func2, ...) Set numerical operators for array objects. Parameters ---------- op1, op2, ... : callable Each ``op = func`` pair describes an operator to be replaced. For example, ``add = lambda x, y: np.add(x, y) % 5`` would replace addition by modulus 5 addition. Returns ------- saved_ops : list of callables A list of all operators, stored before making replacements. Notes ----- .. WARNING:: Use with care! Incorrect usage may lead to memory errors. A function replacing an operator cannot make use of that operator. For example, when replacing add, you may not use ``+``. Instead, directly call ufuncs. Examples -------- >>> def add_mod5(x, y): ... return np.add(x, y) % 5 ... >>> old_funcs = np.set_numeric_ops(add=add_mod5) >>> x = np.arange(12).reshape((3, 4)) >>> x + x array([[0, 2, 4, 1], [3, 0, 2, 4], [1, 3, 0, 2]]) >>> ignore = np.set_numeric_ops(**old_funcs) # restore operators """) add_newdoc('numpy.core.multiarray', 'where', """ where(condition, [x, y]) Return elements, either from `x` or `y`, depending on `condition`. If only `condition` is given, return ``condition.nonzero()``. Parameters ---------- condition : array_like, bool When True, yield `x`, otherwise yield `y`. x, y : array_like, optional Values from which to choose. `x` and `y` need to have the same shape as `condition`. Returns ------- out : ndarray or tuple of ndarrays If both `x` and `y` are specified, the output array contains elements of `x` where `condition` is True, and elements from `y` elsewhere. If only `condition` is given, return the tuple ``condition.nonzero()``, the indices where `condition` is True. See Also -------- nonzero, choose Notes ----- If `x` and `y` are given and input arrays are 1-D, `where` is equivalent to:: [xv if c else yv for (c,xv,yv) in zip(condition,x,y)] Examples -------- >>> np.where([[True, False], [True, True]], ... [[1, 2], [3, 4]], ... [[9, 8], [7, 6]]) array([[1, 8], [3, 4]]) >>> np.where([[0, 1], [1, 0]]) (array([0, 1]), array([1, 0])) >>> x = np.arange(9.).reshape(3, 3) >>> np.where( x > 5 ) (array([2, 2, 2]), array([0, 1, 2])) >>> x[np.where( x > 3.0 )] # Note: result is 1D. array([ 4., 5., 6., 7., 8.]) >>> np.where(x < 5, x, -1) # Note: broadcasting. array([[ 0., 1., 2.], [ 3., 4., -1.], [-1., -1., -1.]]) Find the indices of elements of `x` that are in `goodvalues`. >>> goodvalues = [3, 4, 7] >>> ix = np.in1d(x.ravel(), goodvalues).reshape(x.shape) >>> ix array([[False, False, False], [ True, True, False], [False, True, False]], dtype=bool) >>> np.where(ix) (array([1, 1, 2]), array([0, 1, 1])) """) add_newdoc('numpy.core.multiarray', 'lexsort', """ lexsort(keys, axis=-1) Perform an indirect sort using a sequence of keys. Given multiple sorting keys, which can be interpreted as columns in a spreadsheet, lexsort returns an array of integer indices that describes the sort order by multiple columns. The last key in the sequence is used for the primary sort order, the second-to-last key for the secondary sort order, and so on. The keys argument must be a sequence of objects that can be converted to arrays of the same shape. If a 2D array is provided for the keys argument, it's rows are interpreted as the sorting keys and sorting is according to the last row, second last row etc. Parameters ---------- keys : (k, N) array or tuple containing k (N,)-shaped sequences The `k` different "columns" to be sorted. The last column (or row if `keys` is a 2D array) is the primary sort key. axis : int, optional Axis to be indirectly sorted. By default, sort over the last axis. Returns ------- indices : (N,) ndarray of ints Array of indices that sort the keys along the specified axis. See Also -------- argsort : Indirect sort. ndarray.sort : In-place sort. sort : Return a sorted copy of an array. Examples -------- Sort names: first by surname, then by name. >>> surnames = ('Hertz', 'Galilei', 'Hertz') >>> first_names = ('Heinrich', 'Galileo', 'Gustav') >>> ind = np.lexsort((first_names, surnames)) >>> ind array([1, 2, 0]) >>> [surnames[i] + ", " + first_names[i] for i in ind] ['Galilei, Galileo', 'Hertz, Gustav', 'Hertz, Heinrich'] Sort two columns of numbers: >>> a = [1,5,1,4,3,4,4] # First column >>> b = [9,4,0,4,0,2,1] # Second column >>> ind = np.lexsort((b,a)) # Sort by a, then by b >>> print ind [2 0 4 6 5 3 1] >>> [(a[i],b[i]) for i in ind] [(1, 0), (1, 9), (3, 0), (4, 1), (4, 2), (4, 4), (5, 4)] Note that sorting is first according to the elements of ``a``. Secondary sorting is according to the elements of ``b``. A normal ``argsort`` would have yielded: >>> [(a[i],b[i]) for i in np.argsort(a)] [(1, 9), (1, 0), (3, 0), (4, 4), (4, 2), (4, 1), (5, 4)] Structured arrays are sorted lexically by ``argsort``: >>> x = np.array([(1,9), (5,4), (1,0), (4,4), (3,0), (4,2), (4,1)], ... dtype=np.dtype([('x', int), ('y', int)])) >>> np.argsort(x) # or np.argsort(x, order=('x', 'y')) array([2, 0, 4, 6, 5, 3, 1]) """) add_newdoc('numpy.core.multiarray', 'can_cast', """ can_cast(from, totype, casting = 'safe') Returns True if cast between data types can occur according to the casting rule. If from is a scalar or array scalar, also returns True if the scalar value can be cast without overflow or truncation to an integer. Parameters ---------- from : dtype, dtype specifier, scalar, or array Data type, scalar, or array to cast from. totype : dtype or dtype specifier Data type to cast to. casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional Controls what kind of data casting may occur. * 'no' means the data types should not be cast at all. * 'equiv' means only byte-order changes are allowed. * 'safe' means only casts which can preserve values are allowed. * 'same_kind' means only safe casts or casts within a kind, like float64 to float32, are allowed. * 'unsafe' means any data conversions may be done. Returns ------- out : bool True if cast can occur according to the casting rule. See also -------- dtype, result_type Examples -------- Basic examples >>> np.can_cast(np.int32, np.int64) True >>> np.can_cast(np.float64, np.complex) True >>> np.can_cast(np.complex, np.float) False >>> np.can_cast('i8', 'f8') True >>> np.can_cast('i8', 'f4') False >>> np.can_cast('i4', 'S4') True Casting scalars >>> np.can_cast(100, 'i1') True >>> np.can_cast(150, 'i1') False >>> np.can_cast(150, 'u1') True >>> np.can_cast(3.5e100, np.float32) False >>> np.can_cast(1000.0, np.float32) True Array scalar checks the value, array does not >>> np.can_cast(np.array(1000.0), np.float32) True >>> np.can_cast(np.array([1000.0]), np.float32) False Using the casting rules >>> np.can_cast('i8', 'i8', 'no') True >>> np.can_cast('i8', 'no') False >>> np.can_cast('i8', 'equiv') True >>> np.can_cast('i8', 'equiv') False >>> np.can_cast('i8', 'safe') True >>> np.can_cast('i4', 'safe') False >>> np.can_cast('i4', 'same_kind') True >>> np.can_cast('u4', 'same_kind') False >>> np.can_cast('u4', 'unsafe') True """) add_newdoc('numpy.core.multiarray', 'promote_types', """ promote_types(type1, type2) Returns the data type with the smallest size and smallest scalar kind to which both ``type1`` and ``type2`` may be safely cast. The returned data type is always in native byte order. This function is symmetric and associative. Parameters ---------- type1 : dtype or dtype specifier First data type. type2 : dtype or dtype specifier Second data type. Returns ------- out : dtype The promoted data type. Notes ----- .. versionadded:: 1.6.0 See Also -------- result_type, dtype, can_cast Examples -------- >>> np.promote_types('f4', 'f8') dtype('float64') >>> np.promote_types('i8', 'f4') dtype('float64') >>> np.promote_types('>i8', '>> np.promote_types('i1', 'S8') Traceback (most recent call last): File "", line 1, in TypeError: invalid type promotion """) add_newdoc('numpy.core.multiarray', 'min_scalar_type', """ min_scalar_type(a) For scalar ``a``, returns the data type with the smallest size and smallest scalar kind which can hold its value. For non-scalar array ``a``, returns the vector's dtype unmodified. Floating point values are not demoted to integers, and complex values are not demoted to floats. Parameters ---------- a : scalar or array_like The value whose minimal data type is to be found. Returns ------- out : dtype The minimal data type. Notes ----- .. versionadded:: 1.6.0 See Also -------- result_type, promote_types, dtype, can_cast Examples -------- >>> np.min_scalar_type(10) dtype('uint8') >>> np.min_scalar_type(-260) dtype('int16') >>> np.min_scalar_type(3.1) dtype('float16') >>> np.min_scalar_type(1e50) dtype('float64') >>> np.min_scalar_type(np.arange(4,dtype='f8')) dtype('float64') """) add_newdoc('numpy.core.multiarray', 'result_type', """ result_type(*arrays_and_dtypes) Returns the type that results from applying the NumPy type promotion rules to the arguments. Type promotion in NumPy works similarly to the rules in languages like C++, with some slight differences. When both scalars and arrays are used, the array's type takes precedence and the actual value of the scalar is taken into account. For example, calculating 3*a, where a is an array of 32-bit floats, intuitively should result in a 32-bit float output. If the 3 is a 32-bit integer, the NumPy rules indicate it can't convert losslessly into a 32-bit float, so a 64-bit float should be the result type. By examining the value of the constant, '3', we see that it fits in an 8-bit integer, which can be cast losslessly into the 32-bit float. Parameters ---------- arrays_and_dtypes : list of arrays and dtypes The operands of some operation whose result type is needed. Returns ------- out : dtype The result type. See also -------- dtype, promote_types, min_scalar_type, can_cast Notes ----- .. versionadded:: 1.6.0 The specific algorithm used is as follows. Categories are determined by first checking which of boolean, integer (int/uint), or floating point (float/complex) the maximum kind of all the arrays and the scalars are. If there are only scalars or the maximum category of the scalars is higher than the maximum category of the arrays, the data types are combined with :func:`promote_types` to produce the return value. Otherwise, `min_scalar_type` is called on each array, and the resulting data types are all combined with :func:`promote_types` to produce the return value. The set of int values is not a subset of the uint values for types with the same number of bits, something not reflected in :func:`min_scalar_type`, but handled as a special case in `result_type`. Examples -------- >>> np.result_type(3, np.arange(7, dtype='i1')) dtype('int8') >>> np.result_type('i4', 'c8') dtype('complex128') >>> np.result_type(3.0, -2) dtype('float64') """) add_newdoc('numpy.core.multiarray', 'newbuffer', """ newbuffer(size) Return a new uninitialized buffer object. Parameters ---------- size : int Size in bytes of returned buffer object. Returns ------- newbuffer : buffer object Returned, uninitialized buffer object of `size` bytes. """) add_newdoc('numpy.core.multiarray', 'getbuffer', """ getbuffer(obj [,offset[, size]]) Create a buffer object from the given object referencing a slice of length size starting at offset. Default is the entire buffer. A read-write buffer is attempted followed by a read-only buffer. Parameters ---------- obj : object offset : int, optional size : int, optional Returns ------- buffer_obj : buffer Examples -------- >>> buf = np.getbuffer(np.ones(5), 1, 3) >>> len(buf) 3 >>> buf[0] '\\x00' >>> buf """) add_newdoc('numpy.core', 'dot', """ dot(a, b, out=None) Dot product of two arrays. For 2-D arrays it is equivalent to matrix multiplication, and for 1-D arrays to inner product of vectors (without complex conjugation). For N dimensions it is a sum product over the last axis of `a` and the second-to-last of `b`:: dot(a, b)[i,j,k,m] = sum(a[i,j,:] * b[k,:,m]) Parameters ---------- a : array_like First argument. b : array_like Second argument. out : ndarray, optional Output argument. This must have the exact kind that would be returned if it was not used. In particular, it must have the right type, must be C-contiguous, and its dtype must be the dtype that would be returned for `dot(a,b)`. This is a performance feature. Therefore, if these conditions are not met, an exception is raised, instead of attempting to be flexible. Returns ------- output : ndarray Returns the dot product of `a` and `b`. If `a` and `b` are both scalars or both 1-D arrays then a scalar is returned; otherwise an array is returned. If `out` is given, then it is returned. Raises ------ ValueError If the last dimension of `a` is not the same size as the second-to-last dimension of `b`. See Also -------- vdot : Complex-conjugating dot product. tensordot : Sum products over arbitrary axes. einsum : Einstein summation convention. Examples -------- >>> np.dot(3, 4) 12 Neither argument is complex-conjugated: >>> np.dot([2j, 3j], [2j, 3j]) (-13+0j) For 2-D arrays it's the matrix product: >>> a = [[1, 0], [0, 1]] >>> b = [[4, 1], [2, 2]] >>> np.dot(a, b) array([[4, 1], [2, 2]]) >>> a = np.arange(3*4*5*6).reshape((3,4,5,6)) >>> b = np.arange(3*4*5*6)[::-1].reshape((5,4,6,3)) >>> np.dot(a, b)[2,3,2,1,2,2] 499128 >>> sum(a[2,3,2,:] * b[1,2,:,2]) 499128 """) add_newdoc('numpy.core', 'einsum', """ einsum(subscripts, *operands, out=None, dtype=None, order='K', casting='safe') Evaluates the Einstein summation convention on the operands. Using the Einstein summation convention, many common multi-dimensional array operations can be represented in a simple fashion. This function provides a way compute such summations. The best way to understand this function is to try the examples below, which show how many common NumPy functions can be implemented as calls to `einsum`. Parameters ---------- subscripts : str Specifies the subscripts for summation. operands : list of array_like These are the arrays for the operation. out : ndarray, optional If provided, the calculation is done into this array. dtype : data-type, optional If provided, forces the calculation to use the data type specified. Note that you may have to also give a more liberal `casting` parameter to allow the conversions. order : {'C', 'F', 'A', 'K'}, optional Controls the memory layout of the output. 'C' means it should be C contiguous. 'F' means it should be Fortran contiguous, 'A' means it should be 'F' if the inputs are all 'F', 'C' otherwise. 'K' means it should be as close to the layout as the inputs as is possible, including arbitrarily permuted axes. Default is 'K'. casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional Controls what kind of data casting may occur. Setting this to 'unsafe' is not recommended, as it can adversely affect accumulations. * 'no' means the data types should not be cast at all. * 'equiv' means only byte-order changes are allowed. * 'safe' means only casts which can preserve values are allowed. * 'same_kind' means only safe casts or casts within a kind, like float64 to float32, are allowed. * 'unsafe' means any data conversions may be done. Returns ------- output : ndarray The calculation based on the Einstein summation convention. See Also -------- dot, inner, outer, tensordot Notes ----- .. versionadded:: 1.6.0 The subscripts string is a comma-separated list of subscript labels, where each label refers to a dimension of the corresponding operand. Repeated subscripts labels in one operand take the diagonal. For example, ``np.einsum('ii', a)`` is equivalent to ``np.trace(a)``. Whenever a label is repeated, it is summed, so ``np.einsum('i,i', a, b)`` is equivalent to ``np.inner(a,b)``. If a label appears only once, it is not summed, so ``np.einsum('i', a)`` produces a view of ``a`` with no changes. The order of labels in the output is by default alphabetical. This means that ``np.einsum('ij', a)`` doesn't affect a 2D array, while ``np.einsum('ji', a)`` takes its transpose. The output can be controlled by specifying output subscript labels as well. This specifies the label order, and allows summing to be disallowed or forced when desired. The call ``np.einsum('i->', a)`` is like ``np.sum(a, axis=-1)``, and ``np.einsum('ii->i', a)`` is like ``np.diag(a)``. The difference is that `einsum` does not allow broadcasting by default. To enable and control broadcasting, use an ellipsis. Default NumPy-style broadcasting is done by adding an ellipsis to the left of each term, like ``np.einsum('...ii->...i', a)``. To take the trace along the first and last axes, you can do ``np.einsum('i...i', a)``, or to do a matrix-matrix product with the left-most indices instead of rightmost, you can do ``np.einsum('ij...,jk...->ik...', a, b)``. When there is only one operand, no axes are summed, and no output parameter is provided, a view into the operand is returned instead of a new array. Thus, taking the diagonal as ``np.einsum('ii->i', a)`` produces a view. An alternative way to provide the subscripts and operands is as ``einsum(op0, sublist0, op1, sublist1, ..., [sublistout])``. The examples below have corresponding `einsum` calls with the two parameter methods. Examples -------- >>> a = np.arange(25).reshape(5,5) >>> b = np.arange(5) >>> c = np.arange(6).reshape(2,3) >>> np.einsum('ii', a) 60 >>> np.einsum(a, [0,0]) 60 >>> np.trace(a) 60 >>> np.einsum('ii->i', a) array([ 0, 6, 12, 18, 24]) >>> np.einsum(a, [0,0], [0]) array([ 0, 6, 12, 18, 24]) >>> np.diag(a) array([ 0, 6, 12, 18, 24]) >>> np.einsum('ij,j', a, b) array([ 30, 80, 130, 180, 230]) >>> np.einsum(a, [0,1], b, [1]) array([ 30, 80, 130, 180, 230]) >>> np.dot(a, b) array([ 30, 80, 130, 180, 230]) >>> np.einsum('ji', c) array([[0, 3], [1, 4], [2, 5]]) >>> np.einsum(c, [1,0]) array([[0, 3], [1, 4], [2, 5]]) >>> c.T array([[0, 3], [1, 4], [2, 5]]) >>> np.einsum('..., ...', 3, c) array([[ 0, 3, 6], [ 9, 12, 15]]) >>> np.einsum(3, [Ellipsis], c, [Ellipsis]) array([[ 0, 3, 6], [ 9, 12, 15]]) >>> np.multiply(3, c) array([[ 0, 3, 6], [ 9, 12, 15]]) >>> np.einsum('i,i', b, b) 30 >>> np.einsum(b, [0], b, [0]) 30 >>> np.inner(b,b) 30 >>> np.einsum('i,j', np.arange(2)+1, b) array([[0, 1, 2, 3, 4], [0, 2, 4, 6, 8]]) >>> np.einsum(np.arange(2)+1, [0], b, [1]) array([[0, 1, 2, 3, 4], [0, 2, 4, 6, 8]]) >>> np.outer(np.arange(2)+1, b) array([[0, 1, 2, 3, 4], [0, 2, 4, 6, 8]]) >>> np.einsum('i...->...', a) array([50, 55, 60, 65, 70]) >>> np.einsum(a, [0,Ellipsis], [Ellipsis]) array([50, 55, 60, 65, 70]) >>> np.sum(a, axis=0) array([50, 55, 60, 65, 70]) >>> a = np.arange(60.).reshape(3,4,5) >>> b = np.arange(24.).reshape(4,3,2) >>> np.einsum('ijk,jil->kl', a, b) array([[ 4400., 4730.], [ 4532., 4874.], [ 4664., 5018.], [ 4796., 5162.], [ 4928., 5306.]]) >>> np.einsum(a, [0,1,2], b, [1,0,3], [2,3]) array([[ 4400., 4730.], [ 4532., 4874.], [ 4664., 5018.], [ 4796., 5162.], [ 4928., 5306.]]) >>> np.tensordot(a,b, axes=([1,0],[0,1])) array([[ 4400., 4730.], [ 4532., 4874.], [ 4664., 5018.], [ 4796., 5162.], [ 4928., 5306.]]) """) add_newdoc('numpy.core', 'alterdot', """ Change `dot`, `vdot`, and `inner` to use accelerated BLAS functions. Typically, as a user of Numpy, you do not explicitly call this function. If Numpy is built with an accelerated BLAS, this function is automatically called when Numpy is imported. When Numpy is built with an accelerated BLAS like ATLAS, these functions are replaced to make use of the faster implementations. The faster implementations only affect float32, float64, complex64, and complex128 arrays. Furthermore, the BLAS API only includes matrix-matrix, matrix-vector, and vector-vector products. Products of arrays with larger dimensionalities use the built in functions and are not accelerated. See Also -------- restoredot : `restoredot` undoes the effects of `alterdot`. """) add_newdoc('numpy.core', 'restoredot', """ Restore `dot`, `vdot`, and `innerproduct` to the default non-BLAS implementations. Typically, the user will only need to call this when troubleshooting and installation problem, reproducing the conditions of a build without an accelerated BLAS, or when being very careful about benchmarking linear algebra operations. See Also -------- alterdot : `restoredot` undoes the effects of `alterdot`. """) add_newdoc('numpy.core', 'vdot', """ vdot(a, b) Return the dot product of two vectors. The vdot(`a`, `b`) function handles complex numbers differently than dot(`a`, `b`). If the first argument is complex the complex conjugate of the first argument is used for the calculation of the dot product. Note that `vdot` handles multidimensional arrays differently than `dot`: it does *not* perform a matrix product, but flattens input arguments to 1-D vectors first. Consequently, it should only be used for vectors. Parameters ---------- a : array_like If `a` is complex the complex conjugate is taken before calculation of the dot product. b : array_like Second argument to the dot product. Returns ------- output : ndarray Dot product of `a` and `b`. Can be an int, float, or complex depending on the types of `a` and `b`. See Also -------- dot : Return the dot product without using the complex conjugate of the first argument. Examples -------- >>> a = np.array([1+2j,3+4j]) >>> b = np.array([5+6j,7+8j]) >>> np.vdot(a, b) (70-8j) >>> np.vdot(b, a) (70+8j) Note that higher-dimensional arrays are flattened! >>> a = np.array([[1, 4], [5, 6]]) >>> b = np.array([[4, 1], [2, 2]]) >>> np.vdot(a, b) 30 >>> np.vdot(b, a) 30 >>> 1*4 + 4*1 + 5*2 + 6*2 30 """) ############################################################################## # # Documentation for ndarray attributes and methods # ############################################################################## ############################################################################## # # ndarray object # ############################################################################## add_newdoc('numpy.core.multiarray', 'ndarray', """ ndarray(shape, dtype=float, buffer=None, offset=0, strides=None, order=None) An array object represents a multidimensional, homogeneous array of fixed-size items. An associated data-type object describes the format of each element in the array (its byte-order, how many bytes it occupies in memory, whether it is an integer, a floating point number, or something else, etc.) Arrays should be constructed using `array`, `zeros` or `empty` (refer to the See Also section below). The parameters given here refer to a low-level method (`ndarray(...)`) for instantiating an array. For more information, refer to the `numpy` module and examine the the methods and attributes of an array. Parameters ---------- (for the __new__ method; see Notes below) shape : tuple of ints Shape of created array. dtype : data-type, optional Any object that can be interpreted as a numpy data type. buffer : object exposing buffer interface, optional Used to fill the array with data. offset : int, optional Offset of array data in buffer. strides : tuple of ints, optional Strides of data in memory. order : {'C', 'F'}, optional Row-major or column-major order. Attributes ---------- T : ndarray Transpose of the array. data : buffer The array's elements, in memory. dtype : dtype object Describes the format of the elements in the array. flags : dict Dictionary containing information related to memory use, e.g., 'C_CONTIGUOUS', 'OWNDATA', 'WRITEABLE', etc. flat : numpy.flatiter object Flattened version of the array as an iterator. The iterator allows assignments, e.g., ``x.flat = 3`` (See `ndarray.flat` for assignment examples; TODO). imag : ndarray Imaginary part of the array. real : ndarray Real part of the array. size : int Number of elements in the array. itemsize : int The memory use of each array element in bytes. nbytes : int The total number of bytes required to store the array data, i.e., ``itemsize * size``. ndim : int The array's number of dimensions. shape : tuple of ints Shape of the array. strides : tuple of ints The step-size required to move from one element to the next in memory. For example, a contiguous ``(3, 4)`` array of type ``int16`` in C-order has strides ``(8, 2)``. This implies that to move from element to element in memory requires jumps of 2 bytes. To move from row-to-row, one needs to jump 8 bytes at a time (``2 * 4``). ctypes : ctypes object Class containing properties of the array needed for interaction with ctypes. base : ndarray If the array is a view into another array, that array is its `base` (unless that array is also a view). The `base` array is where the array data is actually stored. See Also -------- array : Construct an array. zeros : Create an array, each element of which is zero. empty : Create an array, but leave its allocated memory unchanged (i.e., it contains "garbage"). dtype : Create a data-type. Notes ----- There are two modes of creating an array using ``__new__``: 1. If `buffer` is None, then only `shape`, `dtype`, and `order` are used. 2. If `buffer` is an object exposing the buffer interface, then all keywords are interpreted. No ``__init__`` method is needed because the array is fully initialized after the ``__new__`` method. Examples -------- These examples illustrate the low-level `ndarray` constructor. Refer to the `See Also` section above for easier ways of constructing an ndarray. First mode, `buffer` is None: >>> np.ndarray(shape=(2,2), dtype=float, order='F') array([[ -1.13698227e+002, 4.25087011e-303], [ 2.88528414e-306, 3.27025015e-309]]) #random Second mode: >>> np.ndarray((2,), buffer=np.array([1,2,3]), ... offset=np.int_().itemsize, ... dtype=int) # offset = 1*itemsize, i.e. skip first element array([2, 3]) """) ############################################################################## # # ndarray attributes # ############################################################################## add_newdoc('numpy.core.multiarray', 'ndarray', ('__array_interface__', """Array protocol: Python side.""")) add_newdoc('numpy.core.multiarray', 'ndarray', ('__array_finalize__', """None.""")) add_newdoc('numpy.core.multiarray', 'ndarray', ('__array_priority__', """Array priority.""")) add_newdoc('numpy.core.multiarray', 'ndarray', ('__array_struct__', """Array protocol: C-struct side.""")) add_newdoc('numpy.core.multiarray', 'ndarray', ('_as_parameter_', """Allow the array to be interpreted as a ctypes object by returning the data-memory location as an integer """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('base', """ Base object if memory is from some other object. Examples -------- The base of an array that owns its memory is None: >>> x = np.array([1,2,3,4]) >>> x.base is None True Slicing creates a view, whose memory is shared with x: >>> y = x[2:] >>> y.base is x True """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('ctypes', """ An object to simplify the interaction of the array with the ctypes module. This attribute creates an object that makes it easier to use arrays when calling shared libraries with the ctypes module. The returned object has, among others, data, shape, and strides attributes (see Notes below) which themselves return ctypes objects that can be used as arguments to a shared library. Parameters ---------- None Returns ------- c : Python object Possessing attributes data, shape, strides, etc. See Also -------- numpy.ctypeslib Notes ----- Below are the public attributes of this object which were documented in "Guide to NumPy" (we have omitted undocumented public attributes, as well as documented private attributes): * data: A pointer to the memory area of the array as a Python integer. This memory area may contain data that is not aligned, or not in correct byte-order. The memory area may not even be writeable. The array flags and data-type of this array should be respected when passing this attribute to arbitrary C-code to avoid trouble that can include Python crashing. User Beware! The value of this attribute is exactly the same as self._array_interface_['data'][0]. * shape (c_intp*self.ndim): A ctypes array of length self.ndim where the basetype is the C-integer corresponding to dtype('p') on this platform. This base-type could be c_int, c_long, or c_longlong depending on the platform. The c_intp type is defined accordingly in numpy.ctypeslib. The ctypes array contains the shape of the underlying array. * strides (c_intp*self.ndim): A ctypes array of length self.ndim where the basetype is the same as for the shape attribute. This ctypes array contains the strides information from the underlying array. This strides information is important for showing how many bytes must be jumped to get to the next element in the array. * data_as(obj): Return the data pointer cast to a particular c-types object. For example, calling self._as_parameter_ is equivalent to self.data_as(ctypes.c_void_p). Perhaps you want to use the data as a pointer to a ctypes array of floating-point data: self.data_as(ctypes.POINTER(ctypes.c_double)). * shape_as(obj): Return the shape tuple as an array of some other c-types type. For example: self.shape_as(ctypes.c_short). * strides_as(obj): Return the strides tuple as an array of some other c-types type. For example: self.strides_as(ctypes.c_longlong). Be careful using the ctypes attribute - especially on temporary arrays or arrays constructed on the fly. For example, calling ``(a+b).ctypes.data_as(ctypes.c_void_p)`` returns a pointer to memory that is invalid because the array created as (a+b) is deallocated before the next Python statement. You can avoid this problem using either ``c=a+b`` or ``ct=(a+b).ctypes``. In the latter case, ct will hold a reference to the array until ct is deleted or re-assigned. If the ctypes module is not available, then the ctypes attribute of array objects still returns something useful, but ctypes objects are not returned and errors may be raised instead. In particular, the object will still have the as parameter attribute which will return an integer equal to the data attribute. Examples -------- >>> import ctypes >>> x array([[0, 1], [2, 3]]) >>> x.ctypes.data 30439712 >>> x.ctypes.data_as(ctypes.POINTER(ctypes.c_long)) >>> x.ctypes.data_as(ctypes.POINTER(ctypes.c_long)).contents c_long(0) >>> x.ctypes.data_as(ctypes.POINTER(ctypes.c_longlong)).contents c_longlong(4294967296L) >>> x.ctypes.shape >>> x.ctypes.shape_as(ctypes.c_long) >>> x.ctypes.strides >>> x.ctypes.strides_as(ctypes.c_longlong) """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('data', """Python buffer object pointing to the start of the array's data.""")) add_newdoc('numpy.core.multiarray', 'ndarray', ('dtype', """ Data-type of the array's elements. Parameters ---------- None Returns ------- d : numpy dtype object See Also -------- numpy.dtype Examples -------- >>> x array([[0, 1], [2, 3]]) >>> x.dtype dtype('int32') >>> type(x.dtype) """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('imag', """ The imaginary part of the array. Examples -------- >>> x = np.sqrt([1+0j, 0+1j]) >>> x.imag array([ 0. , 0.70710678]) >>> x.imag.dtype dtype('float64') """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('itemsize', """ Length of one array element in bytes. Examples -------- >>> x = np.array([1,2,3], dtype=np.float64) >>> x.itemsize 8 >>> x = np.array([1,2,3], dtype=np.complex128) >>> x.itemsize 16 """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('flags', """ Information about the memory layout of the array. Attributes ---------- C_CONTIGUOUS (C) The data is in a single, C-style contiguous segment. F_CONTIGUOUS (F) The data is in a single, Fortran-style contiguous segment. OWNDATA (O) The array owns the memory it uses or borrows it from another object. WRITEABLE (W) The data area can be written to. Setting this to False locks the data, making it read-only. A view (slice, etc.) inherits WRITEABLE from its base array at creation time, but a view of a writeable array may be subsequently locked while the base array remains writeable. (The opposite is not true, in that a view of a locked array may not be made writeable. However, currently, locking a base object does not lock any views that already reference it, so under that circumstance it is possible to alter the contents of a locked array via a previously created writeable view onto it.) Attempting to change a non-writeable array raises a RuntimeError exception. ALIGNED (A) The data and all elements are aligned appropriately for the hardware. UPDATEIFCOPY (U) This array is a copy of some other array. When this array is deallocated, the base array will be updated with the contents of this array. FNC F_CONTIGUOUS and not C_CONTIGUOUS. FORC F_CONTIGUOUS or C_CONTIGUOUS (one-segment test). BEHAVED (B) ALIGNED and WRITEABLE. CARRAY (CA) BEHAVED and C_CONTIGUOUS. FARRAY (FA) BEHAVED and F_CONTIGUOUS and not C_CONTIGUOUS. Notes ----- The `flags` object can be accessed dictionary-like (as in ``a.flags['WRITEABLE']``), or by using lowercased attribute names (as in ``a.flags.writeable``). Short flag names are only supported in dictionary access. Only the UPDATEIFCOPY, WRITEABLE, and ALIGNED flags can be changed by the user, via direct assignment to the attribute or dictionary entry, or by calling `ndarray.setflags`. The array flags cannot be set arbitrarily: - UPDATEIFCOPY can only be set ``False``. - ALIGNED can only be set ``True`` if the data is truly aligned. - WRITEABLE can only be set ``True`` if the array owns its own memory or the ultimate owner of the memory exposes a writeable buffer interface or is a string. Arrays can be both C-style and Fortran-style contiguous simultaneously. This is clear for 1-dimensional arrays, but can also be true for higher dimensional arrays. Even for contiguous arrays a stride for a given dimension ``arr.strides[dim]`` may be *arbitrary* if ``arr.shape[dim] == 1`` or the array has no elements. It does *not* generally hold that ``self.strides[-1] == self.itemsize`` for C-style contiguous arrays or ``self.strides[0] == self.itemsize`` for Fortran-style contiguous arrays is true. """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('flat', """ A 1-D iterator over the array. This is a `numpy.flatiter` instance, which acts similarly to, but is not a subclass of, Python's built-in iterator object. See Also -------- flatten : Return a copy of the array collapsed into one dimension. flatiter Examples -------- >>> x = np.arange(1, 7).reshape(2, 3) >>> x array([[1, 2, 3], [4, 5, 6]]) >>> x.flat[3] 4 >>> x.T array([[1, 4], [2, 5], [3, 6]]) >>> x.T.flat[3] 5 >>> type(x.flat) An assignment example: >>> x.flat = 3; x array([[3, 3, 3], [3, 3, 3]]) >>> x.flat[[1,4]] = 1; x array([[3, 1, 3], [3, 1, 3]]) """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('nbytes', """ Total bytes consumed by the elements of the array. Notes ----- Does not include memory consumed by non-element attributes of the array object. Examples -------- >>> x = np.zeros((3,5,2), dtype=np.complex128) >>> x.nbytes 480 >>> np.prod(x.shape) * x.itemsize 480 """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('ndim', """ Number of array dimensions. Examples -------- >>> x = np.array([1, 2, 3]) >>> x.ndim 1 >>> y = np.zeros((2, 3, 4)) >>> y.ndim 3 """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('real', """ The real part of the array. Examples -------- >>> x = np.sqrt([1+0j, 0+1j]) >>> x.real array([ 1. , 0.70710678]) >>> x.real.dtype dtype('float64') See Also -------- numpy.real : equivalent function """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('shape', """ Tuple of array dimensions. Notes ----- May be used to "reshape" the array, as long as this would not require a change in the total number of elements Examples -------- >>> x = np.array([1, 2, 3, 4]) >>> x.shape (4,) >>> y = np.zeros((2, 3, 4)) >>> y.shape (2, 3, 4) >>> y.shape = (3, 8) >>> y array([[ 0., 0., 0., 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0., 0., 0., 0.]]) >>> y.shape = (3, 6) Traceback (most recent call last): File "", line 1, in ValueError: total size of new array must be unchanged """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('size', """ Number of elements in the array. Equivalent to ``np.prod(a.shape)``, i.e., the product of the array's dimensions. Examples -------- >>> x = np.zeros((3, 5, 2), dtype=np.complex128) >>> x.size 30 >>> np.prod(x.shape) 30 """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('strides', """ Tuple of bytes to step in each dimension when traversing an array. The byte offset of element ``(i[0], i[1], ..., i[n])`` in an array `a` is:: offset = sum(np.array(i) * a.strides) A more detailed explanation of strides can be found in the "ndarray.rst" file in the NumPy reference guide. Notes ----- Imagine an array of 32-bit integers (each 4 bytes):: x = np.array([[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]], dtype=np.int32) This array is stored in memory as 40 bytes, one after the other (known as a contiguous block of memory). The strides of an array tell us how many bytes we have to skip in memory to move to the next position along a certain axis. For example, we have to skip 4 bytes (1 value) to move to the next column, but 20 bytes (5 values) to get to the same position in the next row. As such, the strides for the array `x` will be ``(20, 4)``. See Also -------- numpy.lib.stride_tricks.as_strided Examples -------- >>> y = np.reshape(np.arange(2*3*4), (2,3,4)) >>> y array([[[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]], [[12, 13, 14, 15], [16, 17, 18, 19], [20, 21, 22, 23]]]) >>> y.strides (48, 16, 4) >>> y[1,1,1] 17 >>> offset=sum(y.strides * np.array((1,1,1))) >>> offset/y.itemsize 17 >>> x = np.reshape(np.arange(5*6*7*8), (5,6,7,8)).transpose(2,3,1,0) >>> x.strides (32, 4, 224, 1344) >>> i = np.array([3,5,2,2]) >>> offset = sum(i * x.strides) >>> x[3,5,2,2] 813 >>> offset / x.itemsize 813 """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('T', """ Same as self.transpose(), except that self is returned if self.ndim < 2. Examples -------- >>> x = np.array([[1.,2.],[3.,4.]]) >>> x array([[ 1., 2.], [ 3., 4.]]) >>> x.T array([[ 1., 3.], [ 2., 4.]]) >>> x = np.array([1.,2.,3.,4.]) >>> x array([ 1., 2., 3., 4.]) >>> x.T array([ 1., 2., 3., 4.]) """)) ############################################################################## # # ndarray methods # ############################################################################## add_newdoc('numpy.core.multiarray', 'ndarray', ('__array__', """ a.__array__(|dtype) -> reference if type unchanged, copy otherwise. Returns either a new reference to self if dtype is not given or a new array of provided data type if dtype is different from the current dtype of the array. """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('__array_prepare__', """a.__array_prepare__(obj) -> Object of same type as ndarray object obj. """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('__array_wrap__', """a.__array_wrap__(obj) -> Object of same type as ndarray object a. """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('__copy__', """a.__copy__([order]) Return a copy of the array. Parameters ---------- order : {'C', 'F', 'A'}, optional If order is 'C' (False) then the result is contiguous (default). If order is 'Fortran' (True) then the result has fortran order. If order is 'Any' (None) then the result has fortran order only if the array already is in fortran order. """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('__deepcopy__', """a.__deepcopy__() -> Deep copy of array. Used if copy.deepcopy is called on an array. """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('__reduce__', """a.__reduce__() For pickling. """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('__setstate__', """a.__setstate__(version, shape, dtype, isfortran, rawdata) For unpickling. Parameters ---------- version : int optional pickle version. If omitted defaults to 0. shape : tuple dtype : data-type isFortran : bool rawdata : string or list a binary string with the data (or a list if 'a' is an object array) """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('all', """ a.all(axis=None, out=None) Returns True if all elements evaluate to True. Refer to `numpy.all` for full documentation. See Also -------- numpy.all : equivalent function """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('any', """ a.any(axis=None, out=None) Returns True if any of the elements of `a` evaluate to True. Refer to `numpy.any` for full documentation. See Also -------- numpy.any : equivalent function """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('argmax', """ a.argmax(axis=None, out=None) Return indices of the maximum values along the given axis. Refer to `numpy.argmax` for full documentation. See Also -------- numpy.argmax : equivalent function """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('argmin', """ a.argmin(axis=None, out=None) Return indices of the minimum values along the given axis of `a`. Refer to `numpy.argmin` for detailed documentation. See Also -------- numpy.argmin : equivalent function """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('argsort', """ a.argsort(axis=-1, kind='quicksort', order=None) Returns the indices that would sort this array. Refer to `numpy.argsort` for full documentation. See Also -------- numpy.argsort : equivalent function """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('argpartition', """ a.argpartition(kth, axis=-1, kind='introselect', order=None) Returns the indices that would partition this array. Refer to `numpy.argpartition` for full documentation. .. versionadded:: 1.8.0 See Also -------- numpy.argpartition : equivalent function """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('astype', """ a.astype(dtype, order='K', casting='unsafe', subok=True, copy=True) Copy of the array, cast to a specified type. Parameters ---------- dtype : str or dtype Typecode or data-type to which the array is cast. order : {'C', 'F', 'A', 'K'}, optional Controls the memory layout order of the result. 'C' means C order, 'F' means Fortran order, 'A' means 'F' order if all the arrays are Fortran contiguous, 'C' order otherwise, and 'K' means as close to the order the array elements appear in memory as possible. Default is 'K'. casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional Controls what kind of data casting may occur. Defaults to 'unsafe' for backwards compatibility. * 'no' means the data types should not be cast at all. * 'equiv' means only byte-order changes are allowed. * 'safe' means only casts which can preserve values are allowed. * 'same_kind' means only safe casts or casts within a kind, like float64 to float32, are allowed. * 'unsafe' means any data conversions may be done. subok : bool, optional If True, then sub-classes will be passed-through (default), otherwise the returned array will be forced to be a base-class array. copy : bool, optional By default, astype always returns a newly allocated array. If this is set to false, and the `dtype`, `order`, and `subok` requirements are satisfied, the input array is returned instead of a copy. Returns ------- arr_t : ndarray Unless `copy` is False and the other conditions for returning the input array are satisfied (see description for `copy` input paramter), `arr_t` is a new array of the same shape as the input array, with dtype, order given by `dtype`, `order`. Raises ------ ComplexWarning When casting from complex to float or int. To avoid this, one should use ``a.real.astype(t)``. Examples -------- >>> x = np.array([1, 2, 2.5]) >>> x array([ 1. , 2. , 2.5]) >>> x.astype(int) array([1, 2, 2]) """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('byteswap', """ a.byteswap(inplace) Swap the bytes of the array elements Toggle between low-endian and big-endian data representation by returning a byteswapped array, optionally swapped in-place. Parameters ---------- inplace : bool, optional If ``True``, swap bytes in-place, default is ``False``. Returns ------- out : ndarray The byteswapped array. If `inplace` is ``True``, this is a view to self. Examples -------- >>> A = np.array([1, 256, 8755], dtype=np.int16) >>> map(hex, A) ['0x1', '0x100', '0x2233'] >>> A.byteswap(True) array([ 256, 1, 13090], dtype=int16) >>> map(hex, A) ['0x100', '0x1', '0x3322'] Arrays of strings are not swapped >>> A = np.array(['ceg', 'fac']) >>> A.byteswap() array(['ceg', 'fac'], dtype='|S3') """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('choose', """ a.choose(choices, out=None, mode='raise') Use an index array to construct a new array from a set of choices. Refer to `numpy.choose` for full documentation. See Also -------- numpy.choose : equivalent function """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('clip', """ a.clip(a_min, a_max, out=None) Return an array whose values are limited to ``[a_min, a_max]``. Refer to `numpy.clip` for full documentation. See Also -------- numpy.clip : equivalent function """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('compress', """ a.compress(condition, axis=None, out=None) Return selected slices of this array along given axis. Refer to `numpy.compress` for full documentation. See Also -------- numpy.compress : equivalent function """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('conj', """ a.conj() Complex-conjugate all elements. Refer to `numpy.conjugate` for full documentation. See Also -------- numpy.conjugate : equivalent function """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('conjugate', """ a.conjugate() Return the complex conjugate, element-wise. Refer to `numpy.conjugate` for full documentation. See Also -------- numpy.conjugate : equivalent function """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('copy', """ a.copy(order='C') Return a copy of the array. Parameters ---------- order : {'C', 'F', 'A', 'K'}, optional Controls the memory layout of the copy. 'C' means C-order, 'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous, 'C' otherwise. 'K' means match the layout of `a` as closely as possible. (Note that this function and :func:numpy.copy are very similar, but have different default values for their order= arguments.) See also -------- numpy.copy numpy.copyto Examples -------- >>> x = np.array([[1,2,3],[4,5,6]], order='F') >>> y = x.copy() >>> x.fill(0) >>> x array([[0, 0, 0], [0, 0, 0]]) >>> y array([[1, 2, 3], [4, 5, 6]]) >>> y.flags['C_CONTIGUOUS'] True """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('cumprod', """ a.cumprod(axis=None, dtype=None, out=None) Return the cumulative product of the elements along the given axis. Refer to `numpy.cumprod` for full documentation. See Also -------- numpy.cumprod : equivalent function """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('cumsum', """ a.cumsum(axis=None, dtype=None, out=None) Return the cumulative sum of the elements along the given axis. Refer to `numpy.cumsum` for full documentation. See Also -------- numpy.cumsum : equivalent function """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('diagonal', """ a.diagonal(offset=0, axis1=0, axis2=1) Return specified diagonals. Refer to :func:`numpy.diagonal` for full documentation. See Also -------- numpy.diagonal : equivalent function """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('dot', """ a.dot(b, out=None) Dot product of two arrays. Refer to `numpy.dot` for full documentation. See Also -------- numpy.dot : equivalent function Examples -------- >>> a = np.eye(2) >>> b = np.ones((2, 2)) * 2 >>> a.dot(b) array([[ 2., 2.], [ 2., 2.]]) This array method can be conveniently chained: >>> a.dot(b).dot(b) array([[ 8., 8.], [ 8., 8.]]) """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('dump', """a.dump(file) Dump a pickle of the array to the specified file. The array can be read back with pickle.load or numpy.load. Parameters ---------- file : str A string naming the dump file. """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('dumps', """ a.dumps() Returns the pickle of the array as a string. pickle.loads or numpy.loads will convert the string back to an array. Parameters ---------- None """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('fill', """ a.fill(value) Fill the array with a scalar value. Parameters ---------- value : scalar All elements of `a` will be assigned this value. Examples -------- >>> a = np.array([1, 2]) >>> a.fill(0) >>> a array([0, 0]) >>> a = np.empty(2) >>> a.fill(1) >>> a array([ 1., 1.]) """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('flatten', """ a.flatten(order='C') Return a copy of the array collapsed into one dimension. Parameters ---------- order : {'C', 'F', 'A'}, optional Whether to flatten in C (row-major), Fortran (column-major) order, or preserve the C/Fortran ordering from `a`. The default is 'C'. Returns ------- y : ndarray A copy of the input array, flattened to one dimension. See Also -------- ravel : Return a flattened array. flat : A 1-D flat iterator over the array. Examples -------- >>> a = np.array([[1,2], [3,4]]) >>> a.flatten() array([1, 2, 3, 4]) >>> a.flatten('F') array([1, 3, 2, 4]) """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('getfield', """ a.getfield(dtype, offset=0) Returns a field of the given array as a certain type. A field is a view of the array data with a given data-type. The values in the view are determined by the given type and the offset into the current array in bytes. The offset needs to be such that the view dtype fits in the array dtype; for example an array of dtype complex128 has 16-byte elements. If taking a view with a 32-bit integer (4 bytes), the offset needs to be between 0 and 12 bytes. Parameters ---------- dtype : str or dtype The data type of the view. The dtype size of the view can not be larger than that of the array itself. offset : int Number of bytes to skip before beginning the element view. Examples -------- >>> x = np.diag([1.+1.j]*2) >>> x[1, 1] = 2 + 4.j >>> x array([[ 1.+1.j, 0.+0.j], [ 0.+0.j, 2.+4.j]]) >>> x.getfield(np.float64) array([[ 1., 0.], [ 0., 2.]]) By choosing an offset of 8 bytes we can select the complex part of the array for our view: >>> x.getfield(np.float64, offset=8) array([[ 1., 0.], [ 0., 4.]]) """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('item', """ a.item(*args) Copy an element of an array to a standard Python scalar and return it. Parameters ---------- \\*args : Arguments (variable number and type) * none: in this case, the method only works for arrays with one element (`a.size == 1`), which element is copied into a standard Python scalar object and returned. * int_type: this argument is interpreted as a flat index into the array, specifying which element to copy and return. * tuple of int_types: functions as does a single int_type argument, except that the argument is interpreted as an nd-index into the array. Returns ------- z : Standard Python scalar object A copy of the specified element of the array as a suitable Python scalar Notes ----- When the data type of `a` is longdouble or clongdouble, item() returns a scalar array object because there is no available Python scalar that would not lose information. Void arrays return a buffer object for item(), unless fields are defined, in which case a tuple is returned. `item` is very similar to a[args], except, instead of an array scalar, a standard Python scalar is returned. This can be useful for speeding up access to elements of the array and doing arithmetic on elements of the array using Python's optimized math. Examples -------- >>> x = np.random.randint(9, size=(3, 3)) >>> x array([[3, 1, 7], [2, 8, 3], [8, 5, 3]]) >>> x.item(3) 2 >>> x.item(7) 5 >>> x.item((0, 1)) 1 >>> x.item((2, 2)) 3 """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('itemset', """ a.itemset(*args) Insert scalar into an array (scalar is cast to array's dtype, if possible) There must be at least 1 argument, and define the last argument as *item*. Then, ``a.itemset(*args)`` is equivalent to but faster than ``a[args] = item``. The item should be a scalar value and `args` must select a single item in the array `a`. Parameters ---------- \*args : Arguments If one argument: a scalar, only used in case `a` is of size 1. If two arguments: the last argument is the value to be set and must be a scalar, the first argument specifies a single array element location. It is either an int or a tuple. Notes ----- Compared to indexing syntax, `itemset` provides some speed increase for placing a scalar into a particular location in an `ndarray`, if you must do this. However, generally this is discouraged: among other problems, it complicates the appearance of the code. Also, when using `itemset` (and `item`) inside a loop, be sure to assign the methods to a local variable to avoid the attribute look-up at each loop iteration. Examples -------- >>> x = np.random.randint(9, size=(3, 3)) >>> x array([[3, 1, 7], [2, 8, 3], [8, 5, 3]]) >>> x.itemset(4, 0) >>> x.itemset((2, 2), 9) >>> x array([[3, 1, 7], [2, 0, 3], [8, 5, 9]]) """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('setasflat', """ a.setasflat(arr) Equivalent to a.flat = arr.flat, but is generally more efficient. This function does not check for overlap, so if ``arr`` and ``a`` are viewing the same data with different strides, the results will be unpredictable. Parameters ---------- arr : array_like The array to copy into a. Examples -------- >>> a = np.arange(2*4).reshape(2,4)[:,:-1]; a array([[0, 1, 2], [4, 5, 6]]) >>> b = np.arange(3*3, dtype='f4').reshape(3,3).T[::-1,:-1]; b array([[ 2., 5.], [ 1., 4.], [ 0., 3.]], dtype=float32) >>> a.setasflat(b) >>> a array([[2, 5, 1], [4, 0, 3]]) """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('max', """ a.max(axis=None, out=None) Return the maximum along a given axis. Refer to `numpy.amax` for full documentation. See Also -------- numpy.amax : equivalent function """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('mean', """ a.mean(axis=None, dtype=None, out=None) Returns the average of the array elements along given axis. Refer to `numpy.mean` for full documentation. See Also -------- numpy.mean : equivalent function """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('min', """ a.min(axis=None, out=None) Return the minimum along a given axis. Refer to `numpy.amin` for full documentation. See Also -------- numpy.amin : equivalent function """)) add_newdoc('numpy.core.multiarray', 'may_share_memory', """ Determine if two arrays can share memory The memory-bounds of a and b are computed. If they overlap then this function returns True. Otherwise, it returns False. A return of True does not necessarily mean that the two arrays share any element. It just means that they *might*. Parameters ---------- a, b : ndarray Returns ------- out : bool Examples -------- >>> np.may_share_memory(np.array([1,2]), np.array([5,8,9])) False """) add_newdoc('numpy.core.multiarray', 'ndarray', ('newbyteorder', """ arr.newbyteorder(new_order='S') Return the array with the same data viewed with a different byte order. Equivalent to:: arr.view(arr.dtype.newbytorder(new_order)) Changes are also made in all fields and sub-arrays of the array data type. Parameters ---------- new_order : string, optional Byte order to force; a value from the byte order specifications above. `new_order` codes can be any of:: * 'S' - swap dtype from current to opposite endian * {'<', 'L'} - little endian * {'>', 'B'} - big endian * {'=', 'N'} - native order * {'|', 'I'} - ignore (no change to byte order) The default value ('S') results in swapping the current byte order. The code does a case-insensitive check on the first letter of `new_order` for the alternatives above. For example, any of 'B' or 'b' or 'biggish' are valid to specify big-endian. Returns ------- new_arr : array New array object with the dtype reflecting given change to the byte order. """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('nonzero', """ a.nonzero() Return the indices of the elements that are non-zero. Refer to `numpy.nonzero` for full documentation. See Also -------- numpy.nonzero : equivalent function """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('prod', """ a.prod(axis=None, dtype=None, out=None) Return the product of the array elements over the given axis Refer to `numpy.prod` for full documentation. See Also -------- numpy.prod : equivalent function """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('ptp', """ a.ptp(axis=None, out=None) Peak to peak (maximum - minimum) value along a given axis. Refer to `numpy.ptp` for full documentation. See Also -------- numpy.ptp : equivalent function """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('put', """ a.put(indices, values, mode='raise') Set ``a.flat[n] = values[n]`` for all `n` in indices. Refer to `numpy.put` for full documentation. See Also -------- numpy.put : equivalent function """)) add_newdoc('numpy.core.multiarray', 'copyto', """ copyto(dst, src, casting='same_kind', where=None, preservena=False) Copies values from one array to another, broadcasting as necessary. Raises a TypeError if the `casting` rule is violated, and if `where` is provided, it selects which elements to copy. .. versionadded:: 1.7.0 Parameters ---------- dst : ndarray The array into which values are copied. src : array_like The array from which values are copied. casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional Controls what kind of data casting may occur when copying. * 'no' means the data types should not be cast at all. * 'equiv' means only byte-order changes are allowed. * 'safe' means only casts which can preserve values are allowed. * 'same_kind' means only safe casts or casts within a kind, like float64 to float32, are allowed. * 'unsafe' means any data conversions may be done. where : array_like of bool, optional A boolean array which is broadcasted to match the dimensions of `dst`, and selects elements to copy from `src` to `dst` wherever it contains the value True. preservena : bool, optional If set to True, leaves any NA values in `dst` untouched. This is similar to the "hard mask" feature in numpy.ma. """) add_newdoc('numpy.core.multiarray', 'putmask', """ putmask(a, mask, values) Changes elements of an array based on conditional and input values. Sets ``a.flat[n] = values[n]`` for each n where ``mask.flat[n]==True``. If `values` is not the same size as `a` and `mask` then it will repeat. This gives behavior different from ``a[mask] = values``. .. note:: The `putmask` functionality is also provided by `copyto`, which can be significantly faster and in addition is NA-aware (`preservena` keyword). Replacing `putmask` with ``np.copyto(a, values, where=mask)`` is recommended. Parameters ---------- a : array_like Target array. mask : array_like Boolean mask array. It has to be the same shape as `a`. values : array_like Values to put into `a` where `mask` is True. If `values` is smaller than `a` it will be repeated. See Also -------- place, put, take, copyto Examples -------- >>> x = np.arange(6).reshape(2, 3) >>> np.putmask(x, x>2, x**2) >>> x array([[ 0, 1, 2], [ 9, 16, 25]]) If `values` is smaller than `a` it is repeated: >>> x = np.arange(5) >>> np.putmask(x, x>1, [-33, -44]) >>> x array([ 0, 1, -33, -44, -33]) """) add_newdoc('numpy.core.multiarray', 'ndarray', ('ravel', """ a.ravel([order]) Return a flattened array. Refer to `numpy.ravel` for full documentation. See Also -------- numpy.ravel : equivalent function ndarray.flat : a flat iterator on the array. """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('repeat', """ a.repeat(repeats, axis=None) Repeat elements of an array. Refer to `numpy.repeat` for full documentation. See Also -------- numpy.repeat : equivalent function """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('reshape', """ a.reshape(shape, order='C') Returns an array containing the same data with a new shape. Refer to `numpy.reshape` for full documentation. See Also -------- numpy.reshape : equivalent function """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('resize', """ a.resize(new_shape, refcheck=True) Change shape and size of array in-place. Parameters ---------- new_shape : tuple of ints, or `n` ints Shape of resized array. refcheck : bool, optional If False, reference count will not be checked. Default is True. Returns ------- None Raises ------ ValueError If `a` does not own its own data or references or views to it exist, and the data memory must be changed. SystemError If the `order` keyword argument is specified. This behaviour is a bug in NumPy. See Also -------- resize : Return a new array with the specified shape. Notes ----- This reallocates space for the data area if necessary. Only contiguous arrays (data elements consecutive in memory) can be resized. The purpose of the reference count check is to make sure you do not use this array as a buffer for another Python object and then reallocate the memory. However, reference counts can increase in other ways so if you are sure that you have not shared the memory for this array with another Python object, then you may safely set `refcheck` to False. Examples -------- Shrinking an array: array is flattened (in the order that the data are stored in memory), resized, and reshaped: >>> a = np.array([[0, 1], [2, 3]], order='C') >>> a.resize((2, 1)) >>> a array([[0], [1]]) >>> a = np.array([[0, 1], [2, 3]], order='F') >>> a.resize((2, 1)) >>> a array([[0], [2]]) Enlarging an array: as above, but missing entries are filled with zeros: >>> b = np.array([[0, 1], [2, 3]]) >>> b.resize(2, 3) # new_shape parameter doesn't have to be a tuple >>> b array([[0, 1, 2], [3, 0, 0]]) Referencing an array prevents resizing... >>> c = a >>> a.resize((1, 1)) Traceback (most recent call last): ... ValueError: cannot resize an array that has been referenced ... Unless `refcheck` is False: >>> a.resize((1, 1), refcheck=False) >>> a array([[0]]) >>> c array([[0]]) """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('round', """ a.round(decimals=0, out=None) Return `a` with each element rounded to the given number of decimals. Refer to `numpy.around` for full documentation. See Also -------- numpy.around : equivalent function """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('searchsorted', """ a.searchsorted(v, side='left', sorter=None) Find indices where elements of v should be inserted in a to maintain order. For full documentation, see `numpy.searchsorted` See Also -------- numpy.searchsorted : equivalent function """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('setfield', """ a.setfield(val, dtype, offset=0) Put a value into a specified place in a field defined by a data-type. Place `val` into `a`'s field defined by `dtype` and beginning `offset` bytes into the field. Parameters ---------- val : object Value to be placed in field. dtype : dtype object Data-type of the field in which to place `val`. offset : int, optional The number of bytes into the field at which to place `val`. Returns ------- None See Also -------- getfield Examples -------- >>> x = np.eye(3) >>> x.getfield(np.float64) array([[ 1., 0., 0.], [ 0., 1., 0.], [ 0., 0., 1.]]) >>> x.setfield(3, np.int32) >>> x.getfield(np.int32) array([[3, 3, 3], [3, 3, 3], [3, 3, 3]]) >>> x array([[ 1.00000000e+000, 1.48219694e-323, 1.48219694e-323], [ 1.48219694e-323, 1.00000000e+000, 1.48219694e-323], [ 1.48219694e-323, 1.48219694e-323, 1.00000000e+000]]) >>> x.setfield(np.eye(3), np.int32) >>> x array([[ 1., 0., 0.], [ 0., 1., 0.], [ 0., 0., 1.]]) """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('setflags', """ a.setflags(write=None, align=None, uic=None) Set array flags WRITEABLE, ALIGNED, and UPDATEIFCOPY, respectively. These Boolean-valued flags affect how numpy interprets the memory area used by `a` (see Notes below). The ALIGNED flag can only be set to True if the data is actually aligned according to the type. The UPDATEIFCOPY flag can never be set to True. The flag WRITEABLE can only be set to True if the array owns its own memory, or the ultimate owner of the memory exposes a writeable buffer interface, or is a string. (The exception for string is made so that unpickling can be done without copying memory.) Parameters ---------- write : bool, optional Describes whether or not `a` can be written to. align : bool, optional Describes whether or not `a` is aligned properly for its type. uic : bool, optional Describes whether or not `a` is a copy of another "base" array. Notes ----- Array flags provide information about how the memory area used for the array is to be interpreted. There are 6 Boolean flags in use, only three of which can be changed by the user: UPDATEIFCOPY, WRITEABLE, and ALIGNED. WRITEABLE (W) the data area can be written to; ALIGNED (A) the data and strides are aligned appropriately for the hardware (as determined by the compiler); UPDATEIFCOPY (U) this array is a copy of some other array (referenced by .base). When this array is deallocated, the base array will be updated with the contents of this array. All flags can be accessed using their first (upper case) letter as well as the full name. Examples -------- >>> y array([[3, 1, 7], [2, 0, 0], [8, 5, 9]]) >>> y.flags C_CONTIGUOUS : True F_CONTIGUOUS : False OWNDATA : True WRITEABLE : True ALIGNED : True UPDATEIFCOPY : False >>> y.setflags(write=0, align=0) >>> y.flags C_CONTIGUOUS : True F_CONTIGUOUS : False OWNDATA : True WRITEABLE : False ALIGNED : False UPDATEIFCOPY : False >>> y.setflags(uic=1) Traceback (most recent call last): File "", line 1, in ValueError: cannot set UPDATEIFCOPY flag to True """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('sort', """ a.sort(axis=-1, kind='quicksort', order=None) Sort an array, in-place. Parameters ---------- axis : int, optional Axis along which to sort. Default is -1, which means sort along the last axis. kind : {'quicksort', 'mergesort', 'heapsort'}, optional Sorting algorithm. Default is 'quicksort'. order : list, optional When `a` is an array with fields defined, this argument specifies which fields to compare first, second, etc. Not all fields need be specified. See Also -------- numpy.sort : Return a sorted copy of an array. argsort : Indirect sort. lexsort : Indirect stable sort on multiple keys. searchsorted : Find elements in sorted array. partition: Partial sort. Notes ----- See ``sort`` for notes on the different sorting algorithms. Examples -------- >>> a = np.array([[1,4], [3,1]]) >>> a.sort(axis=1) >>> a array([[1, 4], [1, 3]]) >>> a.sort(axis=0) >>> a array([[1, 3], [1, 4]]) Use the `order` keyword to specify a field to use when sorting a structured array: >>> a = np.array([('a', 2), ('c', 1)], dtype=[('x', 'S1'), ('y', int)]) >>> a.sort(order='y') >>> a array([('c', 1), ('a', 2)], dtype=[('x', '|S1'), ('y', '>> a = np.array([3, 4, 2, 1]) >>> a.partition(a, 3) >>> a array([2, 1, 3, 4]) >>> a.partition((1, 3)) array([1, 2, 3, 4]) """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('squeeze', """ a.squeeze(axis=None) Remove single-dimensional entries from the shape of `a`. Refer to `numpy.squeeze` for full documentation. See Also -------- numpy.squeeze : equivalent function """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('std', """ a.std(axis=None, dtype=None, out=None, ddof=0) Returns the standard deviation of the array elements along given axis. Refer to `numpy.std` for full documentation. See Also -------- numpy.std : equivalent function """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('sum', """ a.sum(axis=None, dtype=None, out=None) Return the sum of the array elements over the given axis. Refer to `numpy.sum` for full documentation. See Also -------- numpy.sum : equivalent function """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('swapaxes', """ a.swapaxes(axis1, axis2) Return a view of the array with `axis1` and `axis2` interchanged. Refer to `numpy.swapaxes` for full documentation. See Also -------- numpy.swapaxes : equivalent function """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('take', """ a.take(indices, axis=None, out=None, mode='raise') Return an array formed from the elements of `a` at the given indices. Refer to `numpy.take` for full documentation. See Also -------- numpy.take : equivalent function """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('tofile', """ a.tofile(fid, sep="", format="%s") Write array to a file as text or binary (default). Data is always written in 'C' order, independent of the order of `a`. The data produced by this method can be recovered using the function fromfile(). Parameters ---------- fid : file or str An open file object, or a string containing a filename. sep : str Separator between array items for text output. If "" (empty), a binary file is written, equivalent to ``file.write(a.tostring())``. format : str Format string for text file output. Each entry in the array is formatted to text by first converting it to the closest Python type, and then using "format" % item. Notes ----- This is a convenience function for quick storage of array data. Information on endianness and precision is lost, so this method is not a good choice for files intended to archive data or transport data between machines with different endianness. Some of these problems can be overcome by outputting the data as text files, at the expense of speed and file size. """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('tolist', """ a.tolist() Return the array as a (possibly nested) list. Return a copy of the array data as a (nested) Python list. Data items are converted to the nearest compatible Python type. Parameters ---------- none Returns ------- y : list The possibly nested list of array elements. Notes ----- The array may be recreated, ``a = np.array(a.tolist())``. Examples -------- >>> a = np.array([1, 2]) >>> a.tolist() [1, 2] >>> a = np.array([[1, 2], [3, 4]]) >>> list(a) [array([1, 2]), array([3, 4])] >>> a.tolist() [[1, 2], [3, 4]] """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('tostring', """ a.tostring(order='C') Construct a Python string containing the raw data bytes in the array. Constructs a Python string showing a copy of the raw contents of data memory. The string can be produced in either 'C' or 'Fortran', or 'Any' order (the default is 'C'-order). 'Any' order means C-order unless the F_CONTIGUOUS flag in the array is set, in which case it means 'Fortran' order. Parameters ---------- order : {'C', 'F', None}, optional Order of the data for multidimensional arrays: C, Fortran, or the same as for the original array. Returns ------- s : str A Python string exhibiting a copy of `a`'s raw data. Examples -------- >>> x = np.array([[0, 1], [2, 3]]) >>> x.tostring() '\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x02\\x00\\x00\\x00\\x03\\x00\\x00\\x00' >>> x.tostring('C') == x.tostring() True >>> x.tostring('F') '\\x00\\x00\\x00\\x00\\x02\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x03\\x00\\x00\\x00' """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('trace', """ a.trace(offset=0, axis1=0, axis2=1, dtype=None, out=None) Return the sum along diagonals of the array. Refer to `numpy.trace` for full documentation. See Also -------- numpy.trace : equivalent function """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('transpose', """ a.transpose(*axes) Returns a view of the array with axes transposed. For a 1-D array, this has no effect. (To change between column and row vectors, first cast the 1-D array into a matrix object.) For a 2-D array, this is the usual matrix transpose. For an n-D array, if axes are given, their order indicates how the axes are permuted (see Examples). If axes are not provided and ``a.shape = (i[0], i[1], ... i[n-2], i[n-1])``, then ``a.transpose().shape = (i[n-1], i[n-2], ... i[1], i[0])``. Parameters ---------- axes : None, tuple of ints, or `n` ints * None or no argument: reverses the order of the axes. * tuple of ints: `i` in the `j`-th place in the tuple means `a`'s `i`-th axis becomes `a.transpose()`'s `j`-th axis. * `n` ints: same as an n-tuple of the same ints (this form is intended simply as a "convenience" alternative to the tuple form) Returns ------- out : ndarray View of `a`, with axes suitably permuted. See Also -------- ndarray.T : Array property returning the array transposed. Examples -------- >>> a = np.array([[1, 2], [3, 4]]) >>> a array([[1, 2], [3, 4]]) >>> a.transpose() array([[1, 3], [2, 4]]) >>> a.transpose((1, 0)) array([[1, 3], [2, 4]]) >>> a.transpose(1, 0) array([[1, 3], [2, 4]]) """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('var', """ a.var(axis=None, dtype=None, out=None, ddof=0) Returns the variance of the array elements, along given axis. Refer to `numpy.var` for full documentation. See Also -------- numpy.var : equivalent function """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('view', """ a.view(dtype=None, type=None) New view of array with the same data. Parameters ---------- dtype : data-type or ndarray sub-class, optional Data-type descriptor of the returned view, e.g., float32 or int16. The default, None, results in the view having the same data-type as `a`. This argument can also be specified as an ndarray sub-class, which then specifies the type of the returned object (this is equivalent to setting the ``type`` parameter). type : Python type, optional Type of the returned view, e.g., ndarray or matrix. Again, the default None results in type preservation. Notes ----- ``a.view()`` is used two different ways: ``a.view(some_dtype)`` or ``a.view(dtype=some_dtype)`` constructs a view of the array's memory with a different data-type. This can cause a reinterpretation of the bytes of memory. ``a.view(ndarray_subclass)`` or ``a.view(type=ndarray_subclass)`` just returns an instance of `ndarray_subclass` that looks at the same array (same shape, dtype, etc.) This does not cause a reinterpretation of the memory. For ``a.view(some_dtype)``, if ``some_dtype`` has a different number of bytes per entry than the previous dtype (for example, converting a regular array to a structured array), then the behavior of the view cannot be predicted just from the superficial appearance of ``a`` (shown by ``print(a)``). It also depends on exactly how ``a`` is stored in memory. Therefore if ``a`` is C-ordered versus fortran-ordered, versus defined as a slice or transpose, etc., the view may give different results. Examples -------- >>> x = np.array([(1, 2)], dtype=[('a', np.int8), ('b', np.int8)]) Viewing array data using a different type and dtype: >>> y = x.view(dtype=np.int16, type=np.matrix) >>> y matrix([[513]], dtype=int16) >>> print type(y) Creating a view on a structured array so it can be used in calculations >>> x = np.array([(1, 2),(3,4)], dtype=[('a', np.int8), ('b', np.int8)]) >>> xv = x.view(dtype=np.int8).reshape(-1,2) >>> xv array([[1, 2], [3, 4]], dtype=int8) >>> xv.mean(0) array([ 2., 3.]) Making changes to the view changes the underlying array >>> xv[0,1] = 20 >>> print x [(1, 20) (3, 4)] Using a view to convert an array to a record array: >>> z = x.view(np.recarray) >>> z.a array([1], dtype=int8) Views share data: >>> x[0] = (9, 10) >>> z[0] (9, 10) Views that change the dtype size (bytes per entry) should normally be avoided on arrays defined by slices, transposes, fortran-ordering, etc.: >>> x = np.array([[1,2,3],[4,5,6]], dtype=np.int16) >>> y = x[:, 0:2] >>> y array([[1, 2], [4, 5]], dtype=int16) >>> y.view(dtype=[('width', np.int16), ('length', np.int16)]) Traceback (most recent call last): File "", line 1, in ValueError: new type not compatible with array. >>> z = y.copy() >>> z.view(dtype=[('width', np.int16), ('length', np.int16)]) array([[(1, 2)], [(4, 5)]], dtype=[('width', '>> oct_array = np.frompyfunc(oct, 1, 1) >>> oct_array(np.array((10, 30, 100))) array([012, 036, 0144], dtype=object) >>> np.array((oct(10), oct(30), oct(100))) # for comparison array(['012', '036', '0144'], dtype='|S4') """) add_newdoc('numpy.core.umath', 'geterrobj', """ geterrobj() Return the current object that defines floating-point error handling. The error object contains all information that defines the error handling behavior in Numpy. `geterrobj` is used internally by the other functions that get and set error handling behavior (`geterr`, `seterr`, `geterrcall`, `seterrcall`). Returns ------- errobj : list The error object, a list containing three elements: [internal numpy buffer size, error mask, error callback function]. The error mask is a single integer that holds the treatment information on all four floating point errors. The information for each error type is contained in three bits of the integer. If we print it in base 8, we can see what treatment is set for "invalid", "under", "over", and "divide" (in that order). The printed string can be interpreted with * 0 : 'ignore' * 1 : 'warn' * 2 : 'raise' * 3 : 'call' * 4 : 'print' * 5 : 'log' See Also -------- seterrobj, seterr, geterr, seterrcall, geterrcall getbufsize, setbufsize Notes ----- For complete documentation of the types of floating-point exceptions and treatment options, see `seterr`. Examples -------- >>> np.geterrobj() # first get the defaults [10000, 0, None] >>> def err_handler(type, flag): ... print "Floating point error (%s), with flag %s" % (type, flag) ... >>> old_bufsize = np.setbufsize(20000) >>> old_err = np.seterr(divide='raise') >>> old_handler = np.seterrcall(err_handler) >>> np.geterrobj() [20000, 2, ] >>> old_err = np.seterr(all='ignore') >>> np.base_repr(np.geterrobj()[1], 8) '0' >>> old_err = np.seterr(divide='warn', over='log', under='call', invalid='print') >>> np.base_repr(np.geterrobj()[1], 8) '4351' """) add_newdoc('numpy.core.umath', 'seterrobj', """ seterrobj(errobj) Set the object that defines floating-point error handling. The error object contains all information that defines the error handling behavior in Numpy. `seterrobj` is used internally by the other functions that set error handling behavior (`seterr`, `seterrcall`). Parameters ---------- errobj : list The error object, a list containing three elements: [internal numpy buffer size, error mask, error callback function]. The error mask is a single integer that holds the treatment information on all four floating point errors. The information for each error type is contained in three bits of the integer. If we print it in base 8, we can see what treatment is set for "invalid", "under", "over", and "divide" (in that order). The printed string can be interpreted with * 0 : 'ignore' * 1 : 'warn' * 2 : 'raise' * 3 : 'call' * 4 : 'print' * 5 : 'log' See Also -------- geterrobj, seterr, geterr, seterrcall, geterrcall getbufsize, setbufsize Notes ----- For complete documentation of the types of floating-point exceptions and treatment options, see `seterr`. Examples -------- >>> old_errobj = np.geterrobj() # first get the defaults >>> old_errobj [10000, 0, None] >>> def err_handler(type, flag): ... print "Floating point error (%s), with flag %s" % (type, flag) ... >>> new_errobj = [20000, 12, err_handler] >>> np.seterrobj(new_errobj) >>> np.base_repr(12, 8) # int for divide=4 ('print') and over=1 ('warn') '14' >>> np.geterr() {'over': 'warn', 'divide': 'print', 'invalid': 'ignore', 'under': 'ignore'} >>> np.geterrcall() is err_handler True """) ############################################################################## # # lib._compiled_base functions # ############################################################################## add_newdoc('numpy.lib._compiled_base', 'digitize', """ digitize(x, bins, right=False) Return the indices of the bins to which each value in input array belongs. Each index ``i`` returned is such that ``bins[i-1] <= x < bins[i]`` if `bins` is monotonically increasing, or ``bins[i-1] > x >= bins[i]`` if `bins` is monotonically decreasing. If values in `x` are beyond the bounds of `bins`, 0 or ``len(bins)`` is returned as appropriate. If right is True, then the right bin is closed so that the index ``i`` is such that ``bins[i-1] < x <= bins[i]`` or bins[i-1] >= x > bins[i]`` if `bins` is monotonically increasing or decreasing, respectively. Parameters ---------- x : array_like Input array to be binned. It has to be 1-dimensional. bins : array_like Array of bins. It has to be 1-dimensional and monotonic. right : bool, optional Indicating whether the intervals include the right or the left bin edge. Default behavior is (right==False) indicating that the interval does not include the right edge. The left bin and is open in this case. Ie., bins[i-1] <= x < bins[i] is the default behavior for monotonically increasing bins. Returns ------- out : ndarray of ints Output array of indices, of same shape as `x`. Raises ------ ValueError If the input is not 1-dimensional, or if `bins` is not monotonic. TypeError If the type of the input is complex. See Also -------- bincount, histogram, unique Notes ----- If values in `x` are such that they fall outside the bin range, attempting to index `bins` with the indices that `digitize` returns will result in an IndexError. Examples -------- >>> x = np.array([0.2, 6.4, 3.0, 1.6]) >>> bins = np.array([0.0, 1.0, 2.5, 4.0, 10.0]) >>> inds = np.digitize(x, bins) >>> inds array([1, 4, 3, 2]) >>> for n in range(x.size): ... print bins[inds[n]-1], "<=", x[n], "<", bins[inds[n]] ... 0.0 <= 0.2 < 1.0 4.0 <= 6.4 < 10.0 2.5 <= 3.0 < 4.0 1.0 <= 1.6 < 2.5 >>> x = np.array([1.2, 10.0, 12.4, 15.5, 20.]) >>> bins = np.array([0,5,10,15,20]) >>> np.digitize(x,bins,right=True) array([1, 2, 3, 4, 4]) >>> np.digitize(x,bins,right=False) array([1, 3, 3, 4, 5]) """) add_newdoc('numpy.lib._compiled_base', 'bincount', """ bincount(x, weights=None, minlength=None) Count number of occurrences of each value in array of non-negative ints. The number of bins (of size 1) is one larger than the largest value in `x`. If `minlength` is specified, there will be at least this number of bins in the output array (though it will be longer if necessary, depending on the contents of `x`). Each bin gives the number of occurrences of its index value in `x`. If `weights` is specified the input array is weighted by it, i.e. if a value ``n`` is found at position ``i``, ``out[n] += weight[i]`` instead of ``out[n] += 1``. Parameters ---------- x : array_like, 1 dimension, nonnegative ints Input array. weights : array_like, optional Weights, array of the same shape as `x`. minlength : int, optional .. versionadded:: 1.6.0 A minimum number of bins for the output array. Returns ------- out : ndarray of ints The result of binning the input array. The length of `out` is equal to ``np.amax(x)+1``. Raises ------ ValueError If the input is not 1-dimensional, or contains elements with negative values, or if `minlength` is non-positive. TypeError If the type of the input is float or complex. See Also -------- histogram, digitize, unique Examples -------- >>> np.bincount(np.arange(5)) array([1, 1, 1, 1, 1]) >>> np.bincount(np.array([0, 1, 1, 3, 2, 1, 7])) array([1, 3, 1, 1, 0, 0, 0, 1]) >>> x = np.array([0, 1, 1, 3, 2, 1, 7, 23]) >>> np.bincount(x).size == np.amax(x)+1 True The input array needs to be of integer dtype, otherwise a TypeError is raised: >>> np.bincount(np.arange(5, dtype=np.float)) Traceback (most recent call last): File "", line 1, in TypeError: array cannot be safely cast to required type A possible use of ``bincount`` is to perform sums over variable-size chunks of an array, using the ``weights`` keyword. >>> w = np.array([0.3, 0.5, 0.2, 0.7, 1., -0.6]) # weights >>> x = np.array([0, 1, 1, 2, 2, 2]) >>> np.bincount(x, weights=w) array([ 0.3, 0.7, 1.1]) """) add_newdoc('numpy.lib._compiled_base', 'ravel_multi_index', """ ravel_multi_index(multi_index, dims, mode='raise', order='C') Converts a tuple of index arrays into an array of flat indices, applying boundary modes to the multi-index. Parameters ---------- multi_index : tuple of array_like A tuple of integer arrays, one array for each dimension. dims : tuple of ints The shape of array into which the indices from ``multi_index`` apply. mode : {'raise', 'wrap', 'clip'}, optional Specifies how out-of-bounds indices are handled. Can specify either one mode or a tuple of modes, one mode per index. * 'raise' -- raise an error (default) * 'wrap' -- wrap around * 'clip' -- clip to the range In 'clip' mode, a negative index which would normally wrap will clip to 0 instead. order : {'C', 'F'}, optional Determines whether the multi-index should be viewed as indexing in C (row-major) order or FORTRAN (column-major) order. Returns ------- raveled_indices : ndarray An array of indices into the flattened version of an array of dimensions ``dims``. See Also -------- unravel_index Notes ----- .. versionadded:: 1.6.0 Examples -------- >>> arr = np.array([[3,6,6],[4,5,1]]) >>> np.ravel_multi_index(arr, (7,6)) array([22, 41, 37]) >>> np.ravel_multi_index(arr, (7,6), order='F') array([31, 41, 13]) >>> np.ravel_multi_index(arr, (4,6), mode='clip') array([22, 23, 19]) >>> np.ravel_multi_index(arr, (4,4), mode=('clip','wrap')) array([12, 13, 13]) >>> np.ravel_multi_index((3,1,4,1), (6,7,8,9)) 1621 """) add_newdoc('numpy.lib._compiled_base', 'unravel_index', """ unravel_index(indices, dims, order='C') Converts a flat index or array of flat indices into a tuple of coordinate arrays. Parameters ---------- indices : array_like An integer array whose elements are indices into the flattened version of an array of dimensions ``dims``. Before version 1.6.0, this function accepted just one index value. dims : tuple of ints The shape of the array to use for unraveling ``indices``. order : {'C', 'F'}, optional .. versionadded:: 1.6.0 Determines whether the indices should be viewed as indexing in C (row-major) order or FORTRAN (column-major) order. Returns ------- unraveled_coords : tuple of ndarray Each array in the tuple has the same shape as the ``indices`` array. See Also -------- ravel_multi_index Examples -------- >>> np.unravel_index([22, 41, 37], (7,6)) (array([3, 6, 6]), array([4, 5, 1])) >>> np.unravel_index([31, 41, 13], (7,6), order='F') (array([3, 6, 6]), array([4, 5, 1])) >>> np.unravel_index(1621, (6,7,8,9)) (3, 1, 4, 1) """) add_newdoc('numpy.lib._compiled_base', 'add_docstring', """ add_docstring(obj, docstring) Add a docstring to a built-in obj if possible. If the obj already has a docstring raise a RuntimeError If this routine does not know how to add a docstring to the object raise a TypeError """) add_newdoc('numpy.lib._compiled_base', 'add_newdoc_ufunc', """ add_ufunc_docstring(ufunc, new_docstring) Replace the docstring for a ufunc with new_docstring. This method will only work if the current docstring for the ufunc is NULL. (At the C level, i.e. when ufunc->doc is NULL.) Parameters ---------- ufunc : numpy.ufunc A ufunc whose current doc is NULL. new_docstring : string The new docstring for the ufunc. Notes ----- This method allocates memory for new_docstring on the heap. Technically this creates a mempory leak, since this memory will not be reclaimed until the end of the program even if the ufunc itself is removed. However this will only be a problem if the user is repeatedly creating ufuncs with no documentation, adding documentation via add_newdoc_ufunc, and then throwing away the ufunc. """) add_newdoc('numpy.lib._compiled_base', 'packbits', """ packbits(myarray, axis=None) Packs the elements of a binary-valued array into bits in a uint8 array. The result is padded to full bytes by inserting zero bits at the end. Parameters ---------- myarray : array_like An integer type array whose elements should be packed to bits. axis : int, optional The dimension over which bit-packing is done. ``None`` implies packing the flattened array. Returns ------- packed : ndarray Array of type uint8 whose elements represent bits corresponding to the logical (0 or nonzero) value of the input elements. The shape of `packed` has the same number of dimensions as the input (unless `axis` is None, in which case the output is 1-D). See Also -------- unpackbits: Unpacks elements of a uint8 array into a binary-valued output array. Examples -------- >>> a = np.array([[[1,0,1], ... [0,1,0]], ... [[1,1,0], ... [0,0,1]]]) >>> b = np.packbits(a, axis=-1) >>> b array([[[160],[64]],[[192],[32]]], dtype=uint8) Note that in binary 160 = 1010 0000, 64 = 0100 0000, 192 = 1100 0000, and 32 = 0010 0000. """) add_newdoc('numpy.lib._compiled_base', 'unpackbits', """ unpackbits(myarray, axis=None) Unpacks elements of a uint8 array into a binary-valued output array. Each element of `myarray` represents a bit-field that should be unpacked into a binary-valued output array. The shape of the output array is either 1-D (if `axis` is None) or the same shape as the input array with unpacking done along the axis specified. Parameters ---------- myarray : ndarray, uint8 type Input array. axis : int, optional Unpacks along this axis. Returns ------- unpacked : ndarray, uint8 type The elements are binary-valued (0 or 1). See Also -------- packbits : Packs the elements of a binary-valued array into bits in a uint8 array. Examples -------- >>> a = np.array([[2], [7], [23]], dtype=np.uint8) >>> a array([[ 2], [ 7], [23]], dtype=uint8) >>> b = np.unpackbits(a, axis=1) >>> b array([[0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 1, 1, 1], [0, 0, 0, 1, 0, 1, 1, 1]], dtype=uint8) """) ############################################################################## # # Documentation for ufunc attributes and methods # ############################################################################## ############################################################################## # # ufunc object # ############################################################################## add_newdoc('numpy.core', 'ufunc', """ Functions that operate element by element on whole arrays. To see the documentation for a specific ufunc, use np.info(). For example, np.info(np.sin). Because ufuncs are written in C (for speed) and linked into Python with NumPy's ufunc facility, Python's help() function finds this page whenever help() is called on a ufunc. A detailed explanation of ufuncs can be found in the "ufuncs.rst" file in the NumPy reference guide. Unary ufuncs: ============= op(X, out=None) Apply op to X elementwise Parameters ---------- X : array_like Input array. out : array_like An array to store the output. Must be the same shape as `X`. Returns ------- r : array_like `r` will have the same shape as `X`; if out is provided, `r` will be equal to out. Binary ufuncs: ============== op(X, Y, out=None) Apply `op` to `X` and `Y` elementwise. May "broadcast" to make the shapes of `X` and `Y` congruent. The broadcasting rules are: * Dimensions of length 1 may be prepended to either array. * Arrays may be repeated along dimensions of length 1. Parameters ---------- X : array_like First input array. Y : array_like Second input array. out : array_like An array to store the output. Must be the same shape as the output would have. Returns ------- r : array_like The return value; if out is provided, `r` will be equal to out. """) ############################################################################## # # ufunc attributes # ############################################################################## add_newdoc('numpy.core', 'ufunc', ('identity', """ The identity value. Data attribute containing the identity element for the ufunc, if it has one. If it does not, the attribute value is None. Examples -------- >>> np.add.identity 0 >>> np.multiply.identity 1 >>> np.power.identity 1 >>> print np.exp.identity None """)) add_newdoc('numpy.core', 'ufunc', ('nargs', """ The number of arguments. Data attribute containing the number of arguments the ufunc takes, including optional ones. Notes ----- Typically this value will be one more than what you might expect because all ufuncs take the optional "out" argument. Examples -------- >>> np.add.nargs 3 >>> np.multiply.nargs 3 >>> np.power.nargs 3 >>> np.exp.nargs 2 """)) add_newdoc('numpy.core', 'ufunc', ('nin', """ The number of inputs. Data attribute containing the number of arguments the ufunc treats as input. Examples -------- >>> np.add.nin 2 >>> np.multiply.nin 2 >>> np.power.nin 2 >>> np.exp.nin 1 """)) add_newdoc('numpy.core', 'ufunc', ('nout', """ The number of outputs. Data attribute containing the number of arguments the ufunc treats as output. Notes ----- Since all ufuncs can take output arguments, this will always be (at least) 1. Examples -------- >>> np.add.nout 1 >>> np.multiply.nout 1 >>> np.power.nout 1 >>> np.exp.nout 1 """)) add_newdoc('numpy.core', 'ufunc', ('ntypes', """ The number of types. The number of numerical NumPy types - of which there are 18 total - on which the ufunc can operate. See Also -------- numpy.ufunc.types Examples -------- >>> np.add.ntypes 18 >>> np.multiply.ntypes 18 >>> np.power.ntypes 17 >>> np.exp.ntypes 7 >>> np.remainder.ntypes 14 """)) add_newdoc('numpy.core', 'ufunc', ('types', """ Returns a list with types grouped input->output. Data attribute listing the data-type "Domain-Range" groupings the ufunc can deliver. The data-types are given using the character codes. See Also -------- numpy.ufunc.ntypes Examples -------- >>> np.add.types ['??->?', 'bb->b', 'BB->B', 'hh->h', 'HH->H', 'ii->i', 'II->I', 'll->l', 'LL->L', 'qq->q', 'QQ->Q', 'ff->f', 'dd->d', 'gg->g', 'FF->F', 'DD->D', 'GG->G', 'OO->O'] >>> np.multiply.types ['??->?', 'bb->b', 'BB->B', 'hh->h', 'HH->H', 'ii->i', 'II->I', 'll->l', 'LL->L', 'qq->q', 'QQ->Q', 'ff->f', 'dd->d', 'gg->g', 'FF->F', 'DD->D', 'GG->G', 'OO->O'] >>> np.power.types ['bb->b', 'BB->B', 'hh->h', 'HH->H', 'ii->i', 'II->I', 'll->l', 'LL->L', 'qq->q', 'QQ->Q', 'ff->f', 'dd->d', 'gg->g', 'FF->F', 'DD->D', 'GG->G', 'OO->O'] >>> np.exp.types ['f->f', 'd->d', 'g->g', 'F->F', 'D->D', 'G->G', 'O->O'] >>> np.remainder.types ['bb->b', 'BB->B', 'hh->h', 'HH->H', 'ii->i', 'II->I', 'll->l', 'LL->L', 'qq->q', 'QQ->Q', 'ff->f', 'dd->d', 'gg->g', 'OO->O'] """)) ############################################################################## # # ufunc methods # ############################################################################## add_newdoc('numpy.core', 'ufunc', ('reduce', """ reduce(a, axis=0, dtype=None, out=None, keepdims=False) Reduces `a`'s dimension by one, by applying ufunc along one axis. Let :math:`a.shape = (N_0, ..., N_i, ..., N_{M-1})`. Then :math:`ufunc.reduce(a, axis=i)[k_0, ..,k_{i-1}, k_{i+1}, .., k_{M-1}]` = the result of iterating `j` over :math:`range(N_i)`, cumulatively applying ufunc to each :math:`a[k_0, ..,k_{i-1}, j, k_{i+1}, .., k_{M-1}]`. For a one-dimensional array, reduce produces results equivalent to: :: r = op.identity # op = ufunc for i in range(len(A)): r = op(r, A[i]) return r For example, add.reduce() is equivalent to sum(). Parameters ---------- a : array_like The array to act on. axis : None or int or tuple of ints, optional Axis or axes along which a reduction is performed. The default (`axis` = 0) is perform a reduction over the first dimension of the input array. `axis` may be negative, in which case it counts from the last to the first axis. .. versionadded:: 1.7.0 If this is `None`, a reduction is performed over all the axes. If this is a tuple of ints, a reduction is performed on multiple axes, instead of a single axis or all the axes as before. For operations which are either not commutative or not associative, doing a reduction over multiple axes is not well-defined. The ufuncs do not currently raise an exception in this case, but will likely do so in the future. dtype : data-type code, optional The type used to represent the intermediate results. Defaults to the data-type of the output array if this is provided, or the data-type of the input array if no output array is provided. out : ndarray, optional A location into which the result is stored. If not provided, a freshly-allocated array is returned. 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 ------- r : ndarray The reduced array. If `out` was supplied, `r` is a reference to it. Examples -------- >>> np.multiply.reduce([2,3,5]) 30 A multi-dimensional array example: >>> X = np.arange(8).reshape((2,2,2)) >>> X array([[[0, 1], [2, 3]], [[4, 5], [6, 7]]]) >>> np.add.reduce(X, 0) array([[ 4, 6], [ 8, 10]]) >>> np.add.reduce(X) # confirm: default axis value is 0 array([[ 4, 6], [ 8, 10]]) >>> np.add.reduce(X, 1) array([[ 2, 4], [10, 12]]) >>> np.add.reduce(X, 2) array([[ 1, 5], [ 9, 13]]) """)) add_newdoc('numpy.core', 'ufunc', ('accumulate', """ accumulate(array, axis=0, dtype=None, out=None) Accumulate the result of applying the operator to all elements. For a one-dimensional array, accumulate produces results equivalent to:: r = np.empty(len(A)) t = op.identity # op = the ufunc being applied to A's elements for i in range(len(A)): t = op(t, A[i]) r[i] = t return r For example, add.accumulate() is equivalent to np.cumsum(). For a multi-dimensional array, accumulate is applied along only one axis (axis zero by default; see Examples below) so repeated use is necessary if one wants to accumulate over multiple axes. Parameters ---------- array : array_like The array to act on. axis : int, optional The axis along which to apply the accumulation; default is zero. dtype : data-type code, optional The data-type used to represent the intermediate results. Defaults to the data-type of the output array if such is provided, or the the data-type of the input array if no output array is provided. out : ndarray, optional A location into which the result is stored. If not provided a freshly-allocated array is returned. Returns ------- r : ndarray The accumulated values. If `out` was supplied, `r` is a reference to `out`. Examples -------- 1-D array examples: >>> np.add.accumulate([2, 3, 5]) array([ 2, 5, 10]) >>> np.multiply.accumulate([2, 3, 5]) array([ 2, 6, 30]) 2-D array examples: >>> I = np.eye(2) >>> I array([[ 1., 0.], [ 0., 1.]]) Accumulate along axis 0 (rows), down columns: >>> np.add.accumulate(I, 0) array([[ 1., 0.], [ 1., 1.]]) >>> np.add.accumulate(I) # no axis specified = axis zero array([[ 1., 0.], [ 1., 1.]]) Accumulate along axis 1 (columns), through rows: >>> np.add.accumulate(I, 1) array([[ 1., 1.], [ 0., 1.]]) """)) add_newdoc('numpy.core', 'ufunc', ('reduceat', """ reduceat(a, indices, axis=0, dtype=None, out=None) Performs a (local) reduce with specified slices over a single axis. For i in ``range(len(indices))``, `reduceat` computes ``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: * 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]]``. 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]``). Parameters ---------- a : array_like The array to act on. indices : array_like Paired indices, comma separated (not colon), specifying slices to reduce. axis : int, optional The axis along which to apply the reduceat. dtype : data-type code, optional The type used to represent the intermediate results. Defaults to the data type of the output array if this is provided, or the data type of the input array if no output array is provided. out : ndarray, optional A location into which the result is stored. If not provided a freshly-allocated array is returned. Returns ------- r : ndarray The reduced values. If `out` was supplied, `r` is a reference to `out`. Notes ----- A descriptive example: If `a` is 1-D, the function `ufunc.accumulate(a)` is the same as ``ufunc.reduceat(a, indices)[::2]`` where `indices` is ``range(len(array) - 1)`` with a zero placed in every other element: ``indices = zeros(2 * len(a) - 1)``, ``indices[1::2] = range(1, len(a))``. Don't be fooled by this attribute's name: `reduceat(a)` is not necessarily smaller than `a`. Examples -------- To take the running sum of four successive values: >>> np.add.reduceat(np.arange(8),[0,4, 1,5, 2,6, 3,7])[::2] array([ 6, 10, 14, 18]) A 2-D example: >>> x = np.linspace(0, 15, 16).reshape(4,4) >>> x array([[ 0., 1., 2., 3.], [ 4., 5., 6., 7.], [ 8., 9., 10., 11.], [ 12., 13., 14., 15.]]) :: # reduce such that the result has the following five rows: # [row1 + row2 + row3] # [row4] # [row2] # [row3] # [row1 + row2 + row3 + row4] >>> np.add.reduceat(x, [0, 3, 1, 2, 0]) array([[ 12., 15., 18., 21.], [ 12., 13., 14., 15.], [ 4., 5., 6., 7.], [ 8., 9., 10., 11.], [ 24., 28., 32., 36.]]) :: # reduce such that result has the following two columns: # [col1 * col2 * col3, col4] >>> np.multiply.reduceat(x, [0, 3], 1) array([[ 0., 3.], [ 120., 7.], [ 720., 11.], [ 2184., 15.]]) """)) add_newdoc('numpy.core', 'ufunc', ('outer', """ outer(A, B) Apply the ufunc `op` to all pairs (a, b) with a in `A` and b in `B`. Let ``M = A.ndim``, ``N = B.ndim``. Then the result, `C`, of ``op.outer(A, B)`` is an array of dimension M + N such that: .. math:: C[i_0, ..., i_{M-1}, j_0, ..., j_{N-1}] = op(A[i_0, ..., i_{M-1}], B[j_0, ..., j_{N-1}]) For `A` and `B` one-dimensional, this is equivalent to:: r = empty(len(A),len(B)) for i in range(len(A)): for j in range(len(B)): r[i,j] = op(A[i], B[j]) # op = ufunc in question Parameters ---------- A : array_like First array B : array_like Second array Returns ------- r : ndarray Output array See Also -------- numpy.outer Examples -------- >>> np.multiply.outer([1, 2, 3], [4, 5, 6]) array([[ 4, 5, 6], [ 8, 10, 12], [12, 15, 18]]) A multi-dimensional example: >>> A = np.array([[1, 2, 3], [4, 5, 6]]) >>> A.shape (2, 3) >>> B = np.array([[1, 2, 3, 4]]) >>> B.shape (1, 4) >>> C = np.multiply.outer(A, B) >>> C.shape; C (2, 3, 1, 4) array([[[[ 1, 2, 3, 4]], [[ 2, 4, 6, 8]], [[ 3, 6, 9, 12]]], [[[ 4, 8, 12, 16]], [[ 5, 10, 15, 20]], [[ 6, 12, 18, 24]]]]) """)) add_newdoc('numpy.core', 'ufunc', ('at', """ at(a, indices, b=None) Performs unbuffered in place operation on operand 'a' for elements specified by 'indices'. For addition ufunc, this method is equivalent to `a[indices] += b`, except that results are accumulated for elements that are indexed more than once. For example, `a[[0,0]] += 1` will only 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 The array to perform in place operation on. indices : array_like or tuple Array like index object or slice object for indexing into first operand. If first operand has multiple dimensions, indices can be a tuple of array like index objects or slice objects. b : array_like Second operand for ufuncs requiring two operands. Operand must be broadcastable over first operand after indexing or slicing. Examples -------- Set items 0 and 1 to their negative values: >>> a = np.array([1, 2, 3, 4]) >>> np.negative.at(a, [0, 1]) >>> print(a) array([-1, -2, 3, 4]) :: Increment items 0 and 1, and increment item 2 twice: >>> a = np.array([1, 2, 3, 4]) >>> np.add.at(a, [0, 1, 2, 2], 1) >>> print(a) array([2, 3, 5, 4]) :: Add items 0 and 1 in first array to second array, and store results in first array: >>> a = np.array([1, 2, 3, 4]) >>> b = np.array([1, 2]) >>> np.add.at(a, [0, 1], b) >>> print(a) array([2, 4, 3, 4]) """)) ############################################################################## # # Documentation for dtype attributes and methods # ############################################################################## ############################################################################## # # dtype object # ############################################################################## add_newdoc('numpy.core.multiarray', 'dtype', """ dtype(obj, align=False, copy=False) Create a data type object. A numpy array is homogeneous, and contains elements described by a dtype object. A dtype object can be constructed from different combinations of fundamental numeric types. Parameters ---------- obj Object to be converted to a data type object. align : bool, optional Add padding to the fields to match what a C compiler would output for a similar C-struct. Can be ``True`` only if `obj` is a dictionary or a comma-separated string. If a struct dtype is being created, this also sets a sticky alignment flag ``isalignedstruct``. copy : bool, optional Make a new copy of the data-type object. If ``False``, the result may just be a reference to a built-in data-type object. See also -------- result_type Examples -------- Using array-scalar type: >>> np.dtype(np.int16) dtype('int16') Record, one field name 'f1', containing int16: >>> np.dtype([('f1', np.int16)]) dtype([('f1', '>> np.dtype([('f1', [('f1', np.int16)])]) dtype([('f1', [('f1', '>> np.dtype([('f1', np.uint), ('f2', np.int32)]) dtype([('f1', '>> np.dtype([('a','f8'),('b','S10')]) dtype([('a', '>> np.dtype("i4, (2,3)f8") dtype([('f0', '>> np.dtype([('hello',(np.int,3)),('world',np.void,10)]) dtype([('hello', '>> np.dtype((np.int16, {'x':(np.int8,0), 'y':(np.int8,1)})) dtype(('>> np.dtype({'names':['gender','age'], 'formats':['S1',np.uint8]}) dtype([('gender', '|S1'), ('age', '|u1')]) Offsets in bytes, here 0 and 25: >>> np.dtype({'surname':('S25',0),'age':(np.uint8,25)}) dtype([('surname', '|S25'), ('age', '|u1')]) """) ############################################################################## # # dtype attributes # ############################################################################## add_newdoc('numpy.core.multiarray', 'dtype', ('alignment', """ The required alignment (bytes) of this data-type according to the compiler. More information is available in the C-API section of the manual. """)) add_newdoc('numpy.core.multiarray', 'dtype', ('byteorder', """ A character indicating the byte-order of this data-type object. One of: === ============== '=' native '<' little-endian '>' big-endian '|' not applicable === ============== All built-in data-type objects have byteorder either '=' or '|'. Examples -------- >>> dt = np.dtype('i2') >>> dt.byteorder '=' >>> # endian is not relevant for 8 bit numbers >>> np.dtype('i1').byteorder '|' >>> # or ASCII strings >>> np.dtype('S2').byteorder '|' >>> # Even if specific code is given, and it is native >>> # '=' is the byteorder >>> import sys >>> sys_is_le = sys.byteorder == 'little' >>> native_code = sys_is_le and '<' or '>' >>> swapped_code = sys_is_le and '>' or '<' >>> dt = np.dtype(native_code + 'i2') >>> dt.byteorder '=' >>> # Swapped code shows up as itself >>> dt = np.dtype(swapped_code + 'i2') >>> dt.byteorder == swapped_code True """)) add_newdoc('numpy.core.multiarray', 'dtype', ('char', """A unique character code for each of the 21 different built-in types.""")) add_newdoc('numpy.core.multiarray', 'dtype', ('descr', """ Array-interface compliant full description of the data-type. The format is that required by the 'descr' key in the `__array_interface__` attribute. """)) add_newdoc('numpy.core.multiarray', 'dtype', ('fields', """ Dictionary of named fields defined for this data type, or ``None``. The dictionary is indexed by keys that are the names of the fields. Each entry in the dictionary is a tuple fully describing the field:: (dtype, offset[, title]) If present, the optional title can be any object (if it is a string or unicode then it will also be a key in the fields dictionary, otherwise it's meta-data). Notice also that the first two elements of the tuple can be passed directly as arguments to the ``ndarray.getfield`` and ``ndarray.setfield`` methods. See Also -------- ndarray.getfield, ndarray.setfield Examples -------- >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))]) >>> print dt.fields {'grades': (dtype(('float64',(2,))), 16), 'name': (dtype('|S16'), 0)} """)) add_newdoc('numpy.core.multiarray', 'dtype', ('flags', """ Bit-flags describing how this data type is to be interpreted. Bit-masks are in `numpy.core.multiarray` as the constants `ITEM_HASOBJECT`, `LIST_PICKLE`, `ITEM_IS_POINTER`, `NEEDS_INIT`, `NEEDS_PYAPI`, `USE_GETITEM`, `USE_SETITEM`. A full explanation of these flags is in C-API documentation; they are largely useful for user-defined data-types. """)) add_newdoc('numpy.core.multiarray', 'dtype', ('hasobject', """ Boolean indicating whether this dtype contains any reference-counted objects in any fields or sub-dtypes. Recall that what is actually in the ndarray memory representing the Python object is the memory address of that object (a pointer). Special handling may be required, and this attribute is useful for distinguishing data types that may contain arbitrary Python objects and data-types that won't. """)) add_newdoc('numpy.core.multiarray', 'dtype', ('isbuiltin', """ Integer indicating how this dtype relates to the built-in dtypes. Read-only. = ======================================================================== 0 if this is a structured array type, with fields 1 if this is a dtype compiled into numpy (such as ints, floats etc) 2 if the dtype is for a user-defined numpy type A user-defined type uses the numpy C-API machinery to extend numpy to handle a new array type. See :ref:`user.user-defined-data-types` in the Numpy manual. = ======================================================================== Examples -------- >>> dt = np.dtype('i2') >>> dt.isbuiltin 1 >>> dt = np.dtype('f8') >>> dt.isbuiltin 1 >>> dt = np.dtype([('field1', 'f8')]) >>> dt.isbuiltin 0 """)) add_newdoc('numpy.core.multiarray', 'dtype', ('isnative', """ Boolean indicating whether the byte order of this dtype is native to the platform. """)) add_newdoc('numpy.core.multiarray', 'dtype', ('isalignedstruct', """ Boolean indicating whether the dtype is a struct which maintains field alignment. This flag is sticky, so when combining multiple structs together, it is preserved and produces new dtypes which are also aligned. """)) add_newdoc('numpy.core.multiarray', 'dtype', ('itemsize', """ The element size of this data-type object. For 18 of the 21 types this number is fixed by the data-type. For the flexible data-types, this number can be anything. """)) add_newdoc('numpy.core.multiarray', 'dtype', ('kind', """ A character code (one of 'biufcSUV') identifying the general kind of data. """)) add_newdoc('numpy.core.multiarray', 'dtype', ('name', """ A bit-width name for this data-type. Un-sized flexible data-type objects do not have this attribute. """)) add_newdoc('numpy.core.multiarray', 'dtype', ('names', """ Ordered list of field names, or ``None`` if there are no fields. The names are ordered according to increasing byte offset. This can be used, for example, to walk through all of the named fields in offset order. Examples -------- >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))]) >>> dt.names ('name', 'grades') """)) add_newdoc('numpy.core.multiarray', 'dtype', ('num', """ A unique number for each of the 21 different built-in types. These are roughly ordered from least-to-most precision. """)) add_newdoc('numpy.core.multiarray', 'dtype', ('shape', """ Shape tuple of the sub-array if this data type describes a sub-array, and ``()`` otherwise. """)) add_newdoc('numpy.core.multiarray', 'dtype', ('str', """The array-protocol typestring of this data-type object.""")) add_newdoc('numpy.core.multiarray', 'dtype', ('subdtype', """ Tuple ``(item_dtype, shape)`` if this `dtype` describes a sub-array, and None otherwise. The *shape* is the fixed shape of the sub-array described by this data type, and *item_dtype* the data type of the array. If a field whose dtype object has this attribute is retrieved, then the extra dimensions implied by *shape* are tacked on to the end of the retrieved array. """)) add_newdoc('numpy.core.multiarray', 'dtype', ('type', """The type object used to instantiate a scalar of this data-type.""")) ############################################################################## # # dtype methods # ############################################################################## add_newdoc('numpy.core.multiarray', 'dtype', ('newbyteorder', """ newbyteorder(new_order='S') Return a new dtype with a different byte order. Changes are also made in all fields and sub-arrays of the data type. Parameters ---------- new_order : string, optional Byte order to force; a value from the byte order specifications below. The default value ('S') results in swapping the current byte order. `new_order` codes can be any of:: * 'S' - swap dtype from current to opposite endian * {'<', 'L'} - little endian * {'>', 'B'} - big endian * {'=', 'N'} - native order * {'|', 'I'} - ignore (no change to byte order) The code does a case-insensitive check on the first letter of `new_order` for these alternatives. For example, any of '>' or 'B' or 'b' or 'brian' are valid to specify big-endian. Returns ------- new_dtype : dtype New dtype object with the given change to the byte order. Notes ----- Changes are also made in all fields and sub-arrays of the data type. Examples -------- >>> import sys >>> sys_is_le = sys.byteorder == 'little' >>> native_code = sys_is_le and '<' or '>' >>> swapped_code = sys_is_le and '>' or '<' >>> native_dt = np.dtype(native_code+'i2') >>> swapped_dt = np.dtype(swapped_code+'i2') >>> native_dt.newbyteorder('S') == swapped_dt True >>> native_dt.newbyteorder() == swapped_dt True >>> native_dt == swapped_dt.newbyteorder('S') True >>> native_dt == swapped_dt.newbyteorder('=') True >>> native_dt == swapped_dt.newbyteorder('N') True >>> native_dt == native_dt.newbyteorder('|') True >>> np.dtype('>> np.dtype('>> np.dtype('>i2') == native_dt.newbyteorder('>') True >>> np.dtype('>i2') == native_dt.newbyteorder('B') True """)) ############################################################################## # # Datetime-related Methods # ############################################################################## add_newdoc('numpy.core.multiarray', 'busdaycalendar', """ busdaycalendar(weekmask='1111100', holidays=None) A business day calendar object that efficiently stores information defining valid days for the busday family of functions. The default valid days are Monday through Friday ("business days"). A busdaycalendar object can be specified with any set of weekly valid days, plus an optional "holiday" dates that always will be invalid. Once a busdaycalendar object is created, the weekmask and holidays cannot be modified. .. versionadded:: 1.7.0 Parameters ---------- weekmask : str or array_like of bool, optional A seven-element array indicating which of Monday through Sunday are valid days. May be specified as a length-seven list or array, like [1,1,1,1,1,0,0]; a length-seven string, like '1111100'; or a string like "Mon Tue Wed Thu Fri", made up of 3-character abbreviations for weekdays, optionally separated by white space. Valid abbreviations are: Mon Tue Wed Thu Fri Sat Sun holidays : array_like of datetime64[D], optional An array of dates to consider as invalid dates, no matter which weekday they fall upon. Holiday dates may be specified in any order, and NaT (not-a-time) dates are ignored. This list is saved in a normalized form that is suited for fast calculations of valid days. Returns ------- out : busdaycalendar A business day calendar object containing the specified weekmask and holidays values. See Also -------- is_busday : Returns a boolean array indicating valid days. busday_offset : Applies an offset counted in valid days. busday_count : Counts how many valid days are in a half-open date range. Attributes ---------- Note: once a busdaycalendar object is created, you cannot modify the weekmask or holidays. The attributes return copies of internal data. weekmask : (copy) seven-element array of bool holidays : (copy) sorted array of datetime64[D] Examples -------- >>> # Some important days in July ... bdd = np.busdaycalendar( ... holidays=['2011-07-01', '2011-07-04', '2011-07-17']) >>> # Default is Monday to Friday weekdays ... bdd.weekmask array([ True, True, True, True, True, False, False], dtype='bool') >>> # Any holidays already on the weekend are removed ... bdd.holidays array(['2011-07-01', '2011-07-04'], dtype='datetime64[D]') """) add_newdoc('numpy.core.multiarray', 'busdaycalendar', ('weekmask', """A copy of the seven-element boolean mask indicating valid days.""")) add_newdoc('numpy.core.multiarray', 'busdaycalendar', ('holidays', """A copy of the holiday array indicating additional invalid days.""")) add_newdoc('numpy.core.multiarray', 'is_busday', """ is_busday(dates, weekmask='1111100', holidays=None, busdaycal=None, out=None) Calculates which of the given dates are valid days, and which are not. .. versionadded:: 1.7.0 Parameters ---------- dates : array_like of datetime64[D] The array of dates to process. weekmask : str or array_like of bool, optional A seven-element array indicating which of Monday through Sunday are valid days. May be specified as a length-seven list or array, like [1,1,1,1,1,0,0]; a length-seven string, like '1111100'; or a string like "Mon Tue Wed Thu Fri", made up of 3-character abbreviations for weekdays, optionally separated by white space. Valid abbreviations are: Mon Tue Wed Thu Fri Sat Sun holidays : array_like of datetime64[D], optional An array of dates to consider as invalid dates. They may be specified in any order, and NaT (not-a-time) dates are ignored. This list is saved in a normalized form that is suited for fast calculations of valid days. busdaycal : busdaycalendar, optional A `busdaycalendar` object which specifies the valid days. If this parameter is provided, neither weekmask nor holidays may be provided. out : array of bool, optional If provided, this array is filled with the result. Returns ------- out : array of bool An array with the same shape as ``dates``, containing True for each valid day, and False for each invalid day. See Also -------- busdaycalendar: An object that specifies a custom set of valid days. busday_offset : Applies an offset counted in valid days. busday_count : Counts how many valid days are in a half-open date range. Examples -------- >>> # The weekdays are Friday, Saturday, and Monday ... np.is_busday(['2011-07-01', '2011-07-02', '2011-07-18'], ... holidays=['2011-07-01', '2011-07-04', '2011-07-17']) array([False, False, True], dtype='bool') """) add_newdoc('numpy.core.multiarray', 'busday_offset', """ busday_offset(dates, offsets, roll='raise', weekmask='1111100', holidays=None, busdaycal=None, out=None) First adjusts the date to fall on a valid day according to the ``roll`` rule, then applies offsets to the given dates counted in valid days. .. versionadded:: 1.7.0 Parameters ---------- dates : array_like of datetime64[D] The array of dates to process. offsets : array_like of int The array of offsets, which is broadcast with ``dates``. roll : {'raise', 'nat', 'forward', 'following', 'backward', 'preceding', 'modifiedfollowing', 'modifiedpreceding'}, optional How to treat dates that do not fall on a valid day. The default is 'raise'. * 'raise' means to raise an exception for an invalid day. * 'nat' means to return a NaT (not-a-time) for an invalid day. * 'forward' and 'following' mean to take the first valid day later in time. * 'backward' and 'preceding' mean to take the first valid day earlier in time. * 'modifiedfollowing' means to take the first valid day later in time unless it is across a Month boundary, in which case to take the first valid day earlier in time. * 'modifiedpreceding' means to take the first valid day earlier in time unless it is across a Month boundary, in which case to take the first valid day later in time. weekmask : str or array_like of bool, optional A seven-element array indicating which of Monday through Sunday are valid days. May be specified as a length-seven list or array, like [1,1,1,1,1,0,0]; a length-seven string, like '1111100'; or a string like "Mon Tue Wed Thu Fri", made up of 3-character abbreviations for weekdays, optionally separated by white space. Valid abbreviations are: Mon Tue Wed Thu Fri Sat Sun holidays : array_like of datetime64[D], optional An array of dates to consider as invalid dates. They may be specified in any order, and NaT (not-a-time) dates are ignored. This list is saved in a normalized form that is suited for fast calculations of valid days. busdaycal : busdaycalendar, optional A `busdaycalendar` object which specifies the valid days. If this parameter is provided, neither weekmask nor holidays may be provided. out : array of datetime64[D], optional If provided, this array is filled with the result. Returns ------- out : array of datetime64[D] An array with a shape from broadcasting ``dates`` and ``offsets`` together, containing the dates with offsets applied. See Also -------- busdaycalendar: An object that specifies a custom set of valid days. is_busday : Returns a boolean array indicating valid days. busday_count : Counts how many valid days are in a half-open date range. Examples -------- >>> # First business day in October 2011 (not accounting for holidays) ... np.busday_offset('2011-10', 0, roll='forward') numpy.datetime64('2011-10-03','D') >>> # Last business day in February 2012 (not accounting for holidays) ... np.busday_offset('2012-03', -1, roll='forward') numpy.datetime64('2012-02-29','D') >>> # Third Wednesday in January 2011 ... np.busday_offset('2011-01', 2, roll='forward', weekmask='Wed') numpy.datetime64('2011-01-19','D') >>> # 2012 Mother's Day in Canada and the U.S. ... np.busday_offset('2012-05', 1, roll='forward', weekmask='Sun') numpy.datetime64('2012-05-13','D') >>> # First business day on or after a date ... np.busday_offset('2011-03-20', 0, roll='forward') numpy.datetime64('2011-03-21','D') >>> np.busday_offset('2011-03-22', 0, roll='forward') numpy.datetime64('2011-03-22','D') >>> # First business day after a date ... np.busday_offset('2011-03-20', 1, roll='backward') numpy.datetime64('2011-03-21','D') >>> np.busday_offset('2011-03-22', 1, roll='backward') numpy.datetime64('2011-03-23','D') """) add_newdoc('numpy.core.multiarray', 'busday_count', """ busday_count(begindates, enddates, weekmask='1111100', holidays=[], busdaycal=None, out=None) Counts the number of valid days between `begindates` and `enddates`, not including the day of `enddates`. If ``enddates`` specifies a date value that is earlier than the corresponding ``begindates`` date value, the count will be negative. .. versionadded:: 1.7.0 Parameters ---------- begindates : array_like of datetime64[D] The array of the first dates for counting. enddates : array_like of datetime64[D] The array of the end dates for counting, which are excluded from the count themselves. weekmask : str or array_like of bool, optional A seven-element array indicating which of Monday through Sunday are valid days. May be specified as a length-seven list or array, like [1,1,1,1,1,0,0]; a length-seven string, like '1111100'; or a string like "Mon Tue Wed Thu Fri", made up of 3-character abbreviations for weekdays, optionally separated by white space. Valid abbreviations are: Mon Tue Wed Thu Fri Sat Sun holidays : array_like of datetime64[D], optional An array of dates to consider as invalid dates. They may be specified in any order, and NaT (not-a-time) dates are ignored. This list is saved in a normalized form that is suited for fast calculations of valid days. busdaycal : busdaycalendar, optional A `busdaycalendar` object which specifies the valid days. If this parameter is provided, neither weekmask nor holidays may be provided. out : array of int, optional If provided, this array is filled with the result. Returns ------- out : array of int An array with a shape from broadcasting ``begindates`` and ``enddates`` together, containing the number of valid days between the begin and end dates. See Also -------- busdaycalendar: An object that specifies a custom set of valid days. is_busday : Returns a boolean array indicating valid days. busday_offset : Applies an offset counted in valid days. Examples -------- >>> # Number of weekdays in January 2011 ... np.busday_count('2011-01', '2011-02') 21 >>> # Number of weekdays in 2011 ... np.busday_count('2011', '2012') 260 >>> # Number of Saturdays in 2011 ... np.busday_count('2011', '2012', weekmask='Sat') 53 """) ############################################################################## # # nd_grid instances # ############################################################################## add_newdoc('numpy.lib.index_tricks', 'mgrid', """ `nd_grid` instance which returns a dense multi-dimensional "meshgrid". An instance of `numpy.lib.index_tricks.nd_grid` which returns an dense (or fleshed out) mesh-grid when indexed, so that each returned argument has the same shape. The dimensions and number of the output arrays are equal to the number of indexing dimensions. If the step length is not a complex number, then the stop is not inclusive. However, if the step length is a **complex number** (e.g. 5j), then the integer part of its magnitude is interpreted as specifying the number of points to create between the start and stop values, where the stop value **is inclusive**. Returns ---------- mesh-grid `ndarrays` all of the same dimensions See Also -------- numpy.lib.index_tricks.nd_grid : class of `ogrid` and `mgrid` objects ogrid : like mgrid but returns open (not fleshed out) mesh grids r_ : array concatenator Examples -------- >>> np.mgrid[0:5,0:5] array([[[0, 0, 0, 0, 0], [1, 1, 1, 1, 1], [2, 2, 2, 2, 2], [3, 3, 3, 3, 3], [4, 4, 4, 4, 4]], [[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]]) >>> np.mgrid[-1:1:5j] array([-1. , -0.5, 0. , 0.5, 1. ]) """) add_newdoc('numpy.lib.index_tricks', 'ogrid', """ `nd_grid` instance which returns an open multi-dimensional "meshgrid". An instance of `numpy.lib.index_tricks.nd_grid` which returns an open (i.e. not fleshed out) mesh-grid when indexed, so that only one dimension of each returned array is greater than 1. The dimension and number of the output arrays are equal to the number of indexing dimensions. If the step length is not a complex number, then the stop is not inclusive. However, if the step length is a **complex number** (e.g. 5j), then the integer part of its magnitude is interpreted as specifying the number of points to create between the start and stop values, where the stop value **is inclusive**. Returns ---------- mesh-grid `ndarrays` with only one dimension :math:`\\neq 1` See Also -------- np.lib.index_tricks.nd_grid : class of `ogrid` and `mgrid` objects mgrid : like `ogrid` but returns dense (or fleshed out) mesh grids r_ : array concatenator Examples -------- >>> from numpy import ogrid >>> ogrid[-1:1:5j] array([-1. , -0.5, 0. , 0.5, 1. ]) >>> ogrid[0:5,0:5] [array([[0], [1], [2], [3], [4]]), array([[0, 1, 2, 3, 4]])] """) ############################################################################## # # Documentation for `generic` attributes and methods # ############################################################################## add_newdoc('numpy.core.numerictypes', 'generic', """ Base class for numpy scalar types. Class from which most (all?) numpy scalar types are derived. For consistency, exposes the same API as `ndarray`, despite many consequent attributes being either "get-only," or completely irrelevant. This is the class from which it is strongly suggested users should derive custom scalar types. """) # Attributes add_newdoc('numpy.core.numerictypes', 'generic', ('T', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('base', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('data', """Pointer to start of data.""")) add_newdoc('numpy.core.numerictypes', 'generic', ('dtype', """Get array data-descriptor.""")) add_newdoc('numpy.core.numerictypes', 'generic', ('flags', """The integer value of flags.""")) add_newdoc('numpy.core.numerictypes', 'generic', ('flat', """A 1-D view of the scalar.""")) add_newdoc('numpy.core.numerictypes', 'generic', ('imag', """The imaginary part of the scalar.""")) add_newdoc('numpy.core.numerictypes', 'generic', ('itemsize', """The length of one element in bytes.""")) add_newdoc('numpy.core.numerictypes', 'generic', ('nbytes', """The length of the scalar in bytes.""")) add_newdoc('numpy.core.numerictypes', 'generic', ('ndim', """The number of array dimensions.""")) add_newdoc('numpy.core.numerictypes', 'generic', ('real', """The real part of the scalar.""")) add_newdoc('numpy.core.numerictypes', 'generic', ('shape', """Tuple of array dimensions.""")) add_newdoc('numpy.core.numerictypes', 'generic', ('size', """The number of elements in the gentype.""")) add_newdoc('numpy.core.numerictypes', 'generic', ('strides', """Tuple of bytes steps in each dimension.""")) # Methods add_newdoc('numpy.core.numerictypes', 'generic', ('all', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('any', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('argmax', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('argmin', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('argsort', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('astype', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('byteswap', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('choose', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('clip', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('compress', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('conjugate', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('copy', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('cumprod', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('cumsum', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('diagonal', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('dump', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('dumps', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('fill', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('flatten', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('getfield', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('item', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('itemset', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('max', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('mean', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('min', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('newbyteorder', """ newbyteorder(new_order='S') Return a new `dtype` with a different byte order. Changes are also made in all fields and sub-arrays of the data type. The `new_order` code can be any from the following: * {'<', 'L'} - little endian * {'>', 'B'} - big endian * {'=', 'N'} - native order * 'S' - swap dtype from current to opposite endian * {'|', 'I'} - ignore (no change to byte order) Parameters ---------- new_order : str, optional Byte order to force; a value from the byte order specifications above. The default value ('S') results in swapping the current byte order. The code does a case-insensitive check on the first letter of `new_order` for the alternatives above. For example, any of 'B' or 'b' or 'biggish' are valid to specify big-endian. Returns ------- new_dtype : dtype New `dtype` object with the given change to the byte order. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('nonzero', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('prod', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('ptp', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('put', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('ravel', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('repeat', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('reshape', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('resize', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('round', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('searchsorted', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('setfield', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('setflags', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('sort', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('squeeze', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('std', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('sum', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('swapaxes', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('take', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('tofile', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('tolist', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('tostring', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('trace', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('transpose', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('var', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) add_newdoc('numpy.core.numerictypes', 'generic', ('view', """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """)) ############################################################################## # # Documentation for other scalar classes # ############################################################################## add_newdoc('numpy.core.numerictypes', 'bool_', """Numpy's Boolean type. Character code: ``?``. Alias: bool8""") add_newdoc('numpy.core.numerictypes', 'complex64', """ Complex number type composed of two 32 bit floats. Character code: 'F'. """) add_newdoc('numpy.core.numerictypes', 'complex128', """ Complex number type composed of two 64 bit floats. Character code: 'D'. Python complex compatible. """) add_newdoc('numpy.core.numerictypes', 'complex256', """ Complex number type composed of two 128-bit floats. Character code: 'G'. """) add_newdoc('numpy.core.numerictypes', 'float32', """ 32-bit floating-point number. Character code 'f'. C float compatible. """) add_newdoc('numpy.core.numerictypes', 'float64', """ 64-bit floating-point number. Character code 'd'. Python float compatible. """) add_newdoc('numpy.core.numerictypes', 'float96', """ """) add_newdoc('numpy.core.numerictypes', 'float128', """ 128-bit floating-point number. Character code: 'g'. C long float compatible. """) add_newdoc('numpy.core.numerictypes', 'int8', """8-bit integer. Character code ``b``. C char compatible.""") add_newdoc('numpy.core.numerictypes', 'int16', """16-bit integer. Character code ``h``. C short compatible.""") add_newdoc('numpy.core.numerictypes', 'int32', """32-bit integer. Character code 'i'. C int compatible.""") add_newdoc('numpy.core.numerictypes', 'int64', """64-bit integer. Character code 'l'. Python int compatible.""") add_newdoc('numpy.core.numerictypes', 'object_', """Any Python object. Character code: 'O'.""") numpy-1.8.2/numpy/doc/0000775000175100017510000000000012371375430015746 5ustar vagrantvagrant00000000000000numpy-1.8.2/numpy/doc/subclassing.py0000664000175100017510000004740112370216242020635 0ustar vagrantvagrant00000000000000""" ============================= Subclassing ndarray in python ============================= Credits ------- This page is based with thanks on the wiki page on subclassing by Pierre Gerard-Marchant - http://www.scipy.org/Subclasses. Introduction ------------ Subclassing ndarray is relatively simple, but it has some complications compared to other Python objects. On this page we explain the machinery that allows you to subclass ndarray, and the implications for implementing a subclass. ndarrays and object creation ============================ Subclassing ndarray is complicated by the fact that new instances of ndarray classes can come about in three different ways. These are: #. Explicit constructor call - as in ``MySubClass(params)``. This is the usual route to Python instance creation. #. View casting - casting an existing ndarray as a given subclass #. New from template - creating a new instance from a template instance. Examples include returning slices from a subclassed array, creating return types from ufuncs, and copying arrays. See :ref:`new-from-template` for more details The last two are characteristics of ndarrays - in order to support things like array slicing. The complications of subclassing ndarray are due to the mechanisms numpy has to support these latter two routes of instance creation. .. _view-casting: View casting ------------ *View casting* is the standard ndarray mechanism by which you take an ndarray of any subclass, and return a view of the array as another (specified) subclass: >>> import numpy as np >>> # create a completely useless ndarray subclass >>> class C(np.ndarray): pass >>> # create a standard ndarray >>> arr = np.zeros((3,)) >>> # take a view of it, as our useless subclass >>> c_arr = arr.view(C) >>> type(c_arr) .. _new-from-template: Creating new from template -------------------------- New instances of an ndarray subclass can also come about by a very similar mechanism to :ref:`view-casting`, when numpy finds it needs to create a new instance from a template instance. The most obvious place this has to happen is when you are taking slices of subclassed arrays. For example: >>> v = c_arr[1:] >>> type(v) # the view is of type 'C' >>> v is c_arr # but it's a new instance False The slice is a *view* onto the original ``c_arr`` data. So, when we take a view from the ndarray, we return a new ndarray, of the same class, that points to the data in the original. There are other points in the use of ndarrays where we need such views, such as copying arrays (``c_arr.copy()``), creating ufunc output arrays (see also :ref:`array-wrap`), and reducing methods (like ``c_arr.mean()``. Relationship of view casting and new-from-template -------------------------------------------------- These paths both use the same machinery. We make the distinction here, because they result in different input to your methods. Specifically, :ref:`view-casting` means you have created a new instance of your array type from any potential subclass of ndarray. :ref:`new-from-template` means you have created a new instance of your class from a pre-existing instance, allowing you - for example - to copy across attributes that are particular to your subclass. Implications for subclassing ---------------------------- If we subclass ndarray, we need to deal not only with explicit construction of our array type, but also :ref:`view-casting` or :ref:`new-from-template`. Numpy has the machinery to do this, and this machinery that makes subclassing slightly non-standard. There are two aspects to the machinery that ndarray uses to support views and new-from-template in subclasses. The first is the use of the ``ndarray.__new__`` method for the main work of object initialization, rather then the more usual ``__init__`` method. The second is the use of the ``__array_finalize__`` method to allow subclasses to clean up after the creation of views and new instances from templates. A brief Python primer on ``__new__`` and ``__init__`` ===================================================== ``__new__`` is a standard Python method, and, if present, is called before ``__init__`` when we create a class instance. See the `python __new__ documentation `_ for more detail. For example, consider the following Python code: .. testcode:: class C(object): def __new__(cls, *args): print 'Cls in __new__:', cls print 'Args in __new__:', args return object.__new__(cls, *args) def __init__(self, *args): print 'type(self) in __init__:', type(self) print 'Args in __init__:', args meaning that we get: >>> c = C('hello') Cls in __new__: Args in __new__: ('hello',) type(self) in __init__: Args in __init__: ('hello',) When we call ``C('hello')``, the ``__new__`` method gets its own class as first argument, and the passed argument, which is the string ``'hello'``. After python calls ``__new__``, it usually (see below) calls our ``__init__`` method, with the output of ``__new__`` as the first argument (now a class instance), and the passed arguments following. As you can see, the object can be initialized in the ``__new__`` method or the ``__init__`` method, or both, and in fact ndarray does not have an ``__init__`` method, because all the initialization is done in the ``__new__`` method. Why use ``__new__`` rather than just the usual ``__init__``? Because in some cases, as for ndarray, we want to be able to return an object of some other class. Consider the following: .. testcode:: class D(C): def __new__(cls, *args): print 'D cls is:', cls print 'D args in __new__:', args return C.__new__(C, *args) def __init__(self, *args): # we never get here print 'In D __init__' meaning that: >>> obj = D('hello') D cls is: D args in __new__: ('hello',) Cls in __new__: Args in __new__: ('hello',) >>> type(obj) The definition of ``C`` is the same as before, but for ``D``, the ``__new__`` method returns an instance of class ``C`` rather than ``D``. Note that the ``__init__`` method of ``D`` does not get called. In general, when the ``__new__`` method returns an object of class other than the class in which it is defined, the ``__init__`` method of that class is not called. This is how subclasses of the ndarray class are able to return views that preserve the class type. When taking a view, the standard ndarray machinery creates the new ndarray object with something like:: obj = ndarray.__new__(subtype, shape, ... where ``subdtype`` is the subclass. Thus the returned view is of the same class as the subclass, rather than being of class ``ndarray``. That solves the problem of returning views of the same type, but now we have a new problem. The machinery of ndarray can set the class this way, in its standard methods for taking views, but the ndarray ``__new__`` method knows nothing of what we have done in our own ``__new__`` method in order to set attributes, and so on. (Aside - why not call ``obj = subdtype.__new__(...`` then? Because we may not have a ``__new__`` method with the same call signature). The role of ``__array_finalize__`` ================================== ``__array_finalize__`` is the mechanism that numpy provides to allow subclasses to handle the various ways that new instances get created. Remember that subclass instances can come about in these three ways: #. explicit constructor call (``obj = MySubClass(params)``). This will call the usual sequence of ``MySubClass.__new__`` then (if it exists) ``MySubClass.__init__``. #. :ref:`view-casting` #. :ref:`new-from-template` Our ``MySubClass.__new__`` method only gets called in the case of the explicit constructor call, so we can't rely on ``MySubClass.__new__`` or ``MySubClass.__init__`` to deal with the view casting and new-from-template. It turns out that ``MySubClass.__array_finalize__`` *does* get called for all three methods of object creation, so this is where our object creation housekeeping usually goes. * For the explicit constructor call, our subclass will need to create a new ndarray instance of its own class. In practice this means that we, the authors of the code, will need to make a call to ``ndarray.__new__(MySubClass,...)``, or do view casting of an existing array (see below) * For view casting and new-from-template, the equivalent of ``ndarray.__new__(MySubClass,...`` is called, at the C level. The arguments that ``__array_finalize__`` recieves differ for the three methods of instance creation above. The following code allows us to look at the call sequences and arguments: .. testcode:: import numpy as np class C(np.ndarray): def __new__(cls, *args, **kwargs): print 'In __new__ with class %s' % cls return np.ndarray.__new__(cls, *args, **kwargs) def __init__(self, *args, **kwargs): # in practice you probably will not need or want an __init__ # method for your subclass print 'In __init__ with class %s' % self.__class__ def __array_finalize__(self, obj): print 'In array_finalize:' print ' self type is %s' % type(self) print ' obj type is %s' % type(obj) Now: >>> # Explicit constructor >>> c = C((10,)) In __new__ with class In array_finalize: self type is obj type is In __init__ with class >>> # View casting >>> a = np.arange(10) >>> cast_a = a.view(C) In array_finalize: self type is obj type is >>> # Slicing (example of new-from-template) >>> cv = c[:1] In array_finalize: self type is obj type is The signature of ``__array_finalize__`` is:: def __array_finalize__(self, obj): ``ndarray.__new__`` passes ``__array_finalize__`` the new object, of our own class (``self``) as well as the object from which the view has been taken (``obj``). As you can see from the output above, the ``self`` is always a newly created instance of our subclass, and the type of ``obj`` differs for the three instance creation methods: * When called from the explicit constructor, ``obj`` is ``None`` * When called from view casting, ``obj`` can be an instance of any subclass of ndarray, including our own. * When called in new-from-template, ``obj`` is another instance of our own subclass, that we might use to update the new ``self`` instance. Because ``__array_finalize__`` is the only method that always sees new instances being created, it is the sensible place to fill in instance defaults for new object attributes, among other tasks. This may be clearer with an example. Simple example - adding an extra attribute to ndarray ----------------------------------------------------- .. testcode:: import numpy as np class InfoArray(np.ndarray): def __new__(subtype, shape, dtype=float, buffer=None, offset=0, strides=None, order=None, info=None): # Create the ndarray instance of our type, given the usual # ndarray input arguments. This will call the standard # ndarray constructor, but return an object of our type. # It also triggers a call to InfoArray.__array_finalize__ obj = np.ndarray.__new__(subtype, shape, dtype, buffer, offset, strides, order) # set the new 'info' attribute to the value passed obj.info = info # Finally, we must return the newly created object: return obj def __array_finalize__(self, obj): # ``self`` is a new object resulting from # ndarray.__new__(InfoArray, ...), therefore it only has # attributes that the ndarray.__new__ constructor gave it - # i.e. those of a standard ndarray. # # We could have got to the ndarray.__new__ call in 3 ways: # From an explicit constructor - e.g. InfoArray(): # obj is None # (we're in the middle of the InfoArray.__new__ # constructor, and self.info will be set when we return to # InfoArray.__new__) if obj is None: return # From view casting - e.g arr.view(InfoArray): # obj is arr # (type(obj) can be InfoArray) # From new-from-template - e.g infoarr[:3] # type(obj) is InfoArray # # Note that it is here, rather than in the __new__ method, # that we set the default value for 'info', because this # method sees all creation of default objects - with the # InfoArray.__new__ constructor, but also with # arr.view(InfoArray). self.info = getattr(obj, 'info', None) # We do not need to return anything Using the object looks like this: >>> obj = InfoArray(shape=(3,)) # explicit constructor >>> type(obj) >>> obj.info is None True >>> obj = InfoArray(shape=(3,), info='information') >>> obj.info 'information' >>> v = obj[1:] # new-from-template - here - slicing >>> type(v) >>> v.info 'information' >>> arr = np.arange(10) >>> cast_arr = arr.view(InfoArray) # view casting >>> type(cast_arr) >>> cast_arr.info is None True This class isn't very useful, because it has the same constructor as the bare ndarray object, including passing in buffers and shapes and so on. We would probably prefer the constructor to be able to take an already formed ndarray from the usual numpy calls to ``np.array`` and return an object. Slightly more realistic example - attribute added to existing array ------------------------------------------------------------------- Here is a class that takes a standard ndarray that already exists, casts as our type, and adds an extra attribute. .. testcode:: import numpy as np class RealisticInfoArray(np.ndarray): def __new__(cls, input_array, info=None): # Input array is an already formed ndarray instance # We first cast to be our class type obj = np.asarray(input_array).view(cls) # add the new attribute to the created instance obj.info = info # Finally, we must return the newly created object: return obj def __array_finalize__(self, obj): # see InfoArray.__array_finalize__ for comments if obj is None: return self.info = getattr(obj, 'info', None) So: >>> arr = np.arange(5) >>> obj = RealisticInfoArray(arr, info='information') >>> type(obj) >>> obj.info 'information' >>> v = obj[1:] >>> type(v) >>> v.info 'information' .. _array-wrap: ``__array_wrap__`` for ufuncs ------------------------------------------------------- ``__array_wrap__`` gets called at the end of numpy ufuncs and other numpy functions, to allow a subclass to set the type of the return value and update attributes and metadata. Let's show how this works with an example. First we make the same subclass as above, but with a different name and some print statements: .. testcode:: import numpy as np class MySubClass(np.ndarray): def __new__(cls, input_array, info=None): obj = np.asarray(input_array).view(cls) obj.info = info return obj def __array_finalize__(self, obj): print 'In __array_finalize__:' print ' self is %s' % repr(self) print ' obj is %s' % repr(obj) if obj is None: return self.info = getattr(obj, 'info', None) def __array_wrap__(self, out_arr, context=None): print 'In __array_wrap__:' print ' self is %s' % repr(self) print ' arr is %s' % repr(out_arr) # then just call the parent return np.ndarray.__array_wrap__(self, out_arr, context) We run a ufunc on an instance of our new array: >>> obj = MySubClass(np.arange(5), info='spam') In __array_finalize__: self is MySubClass([0, 1, 2, 3, 4]) obj is array([0, 1, 2, 3, 4]) >>> arr2 = np.arange(5)+1 >>> ret = np.add(arr2, obj) In __array_wrap__: self is MySubClass([0, 1, 2, 3, 4]) arr is array([1, 3, 5, 7, 9]) In __array_finalize__: self is MySubClass([1, 3, 5, 7, 9]) obj is MySubClass([0, 1, 2, 3, 4]) >>> ret MySubClass([1, 3, 5, 7, 9]) >>> ret.info 'spam' Note that the ufunc (``np.add``) has called the ``__array_wrap__`` method of the input with the highest ``__array_priority__`` value, in this case ``MySubClass.__array_wrap__``, with arguments ``self`` as ``obj``, and ``out_arr`` as the (ndarray) result of the addition. In turn, the default ``__array_wrap__`` (``ndarray.__array_wrap__``) has cast the result to class ``MySubClass``, and called ``__array_finalize__`` - hence the copying of the ``info`` attribute. This has all happened at the C level. But, we could do anything we wanted: .. testcode:: class SillySubClass(np.ndarray): def __array_wrap__(self, arr, context=None): return 'I lost your data' >>> arr1 = np.arange(5) >>> obj = arr1.view(SillySubClass) >>> arr2 = np.arange(5) >>> ret = np.multiply(obj, arr2) >>> ret 'I lost your data' So, by defining a specific ``__array_wrap__`` method for our subclass, we can tweak the output from ufuncs. The ``__array_wrap__`` method requires ``self``, then an argument - which is the result of the ufunc - and an optional parameter *context*. This parameter is returned by some ufuncs as a 3-element tuple: (name of the ufunc, argument of the ufunc, domain of the ufunc). ``__array_wrap__`` should return an instance of its containing class. See the masked array subclass for an implementation. In addition to ``__array_wrap__``, which is called on the way out of the ufunc, there is also an ``__array_prepare__`` method which is called on the way into the ufunc, after the output arrays are created but before any computation has been performed. The default implementation does nothing but pass through the array. ``__array_prepare__`` should not attempt to access the array data or resize the array, it is intended for setting the output array type, updating attributes and metadata, and performing any checks based on the input that may be desired before computation begins. Like ``__array_wrap__``, ``__array_prepare__`` must return an ndarray or subclass thereof or raise an error. Extra gotchas - custom ``__del__`` methods and ndarray.base ----------------------------------------------------------- One of the problems that ndarray solves is keeping track of memory ownership of ndarrays and their views. Consider the case where we have created an ndarray, ``arr`` and have taken a slice with ``v = arr[1:]``. The two objects are looking at the same memory. Numpy keeps track of where the data came from for a particular array or view, with the ``base`` attribute: >>> # A normal ndarray, that owns its own data >>> arr = np.zeros((4,)) >>> # In this case, base is None >>> arr.base is None True >>> # We take a view >>> v1 = arr[1:] >>> # base now points to the array that it derived from >>> v1.base is arr True >>> # Take a view of a view >>> v2 = v1[1:] >>> # base points to the view it derived from >>> v2.base is v1 True In general, if the array owns its own memory, as for ``arr`` in this case, then ``arr.base`` will be None - there are some exceptions to this - see the numpy book for more details. The ``base`` attribute is useful in being able to tell whether we have a view or the original array. This in turn can be useful if we need to know whether or not to do some specific cleanup when the subclassed array is deleted. For example, we may only want to do the cleanup if the original array is deleted, but not the views. For an example of how this can work, have a look at the ``memmap`` class in ``numpy.core``. """ from __future__ import division, absolute_import, print_function numpy-1.8.2/numpy/doc/howtofind.py0000664000175100017510000000023712370216242020315 0ustar vagrantvagrant00000000000000""" ================= How to Find Stuff ================= How to find things in NumPy. """ from __future__ import division, absolute_import, print_function numpy-1.8.2/numpy/doc/indexing.py0000664000175100017510000003402112370216243020120 0ustar vagrantvagrant00000000000000""" ============== Array indexing ============== Array indexing refers to any use of the square brackets ([]) to index array values. There are many options to indexing, which give numpy indexing great power, but with power comes some complexity and the potential for confusion. This section is just an overview of the various options and issues related to indexing. Aside from single element indexing, the details on most of these options are to be found in related sections. Assignment vs referencing ========================= Most of the following examples show the use of indexing when referencing data in an array. The examples work just as well when assigning to an array. See the section at the end for specific examples and explanations on how assignments work. Single element indexing ======================= Single element indexing for a 1-D array is what one expects. It work exactly like that for other standard Python sequences. It is 0-based, and accepts negative indices for indexing from the end of the array. :: >>> x = np.arange(10) >>> x[2] 2 >>> x[-2] 8 Unlike lists and tuples, numpy arrays support multidimensional indexing for multidimensional arrays. That means that it is not necessary to separate each dimension's index into its own set of square brackets. :: >>> x.shape = (2,5) # now x is 2-dimensional >>> x[1,3] 8 >>> x[1,-1] 9 Note that if one indexes a multidimensional array with fewer indices than dimensions, one gets a subdimensional array. For example: :: >>> x[0] array([0, 1, 2, 3, 4]) That is, each index specified selects the array corresponding to the rest of the dimensions selected. In the above example, choosing 0 means that remaining dimension of lenth 5 is being left unspecified, and that what is returned is an array of that dimensionality and size. It must be noted that the returned array is not a copy of the original, but points to the same values in memory as does the original array. In this case, the 1-D array at the first position (0) is returned. So using a single index on the returned array, results in a single element being returned. That is: :: >>> x[0][2] 2 So note that ``x[0,2] = x[0][2]`` though the second case is more inefficient a new temporary array is created after the first index that is subsequently indexed by 2. Note to those used to IDL or Fortran memory order as it relates to indexing. Numpy uses C-order indexing. That means that the last index usually represents the most rapidly changing memory location, unlike Fortran or IDL, where the first index represents the most rapidly changing location in memory. This difference represents a great potential for confusion. Other indexing options ====================== It is possible to slice and stride arrays to extract arrays of the same number of dimensions, but of different sizes than the original. The slicing and striding works exactly the same way it does for lists and tuples except that they can be applied to multiple dimensions as well. A few examples illustrates best: :: >>> x = np.arange(10) >>> x[2:5] array([2, 3, 4]) >>> x[:-7] array([0, 1, 2]) >>> x[1:7:2] array([1, 3, 5]) >>> y = np.arange(35).reshape(5,7) >>> y[1:5:2,::3] array([[ 7, 10, 13], [21, 24, 27]]) Note that slices of arrays do not copy the internal array data but also produce new views of the original data. It is possible to index arrays with other arrays for the purposes of selecting lists of values out of arrays into new arrays. There are two different ways of accomplishing this. One uses one or more arrays of index values. The other involves giving a boolean array of the proper shape to indicate the values to be selected. Index arrays are a very powerful tool that allow one to avoid looping over individual elements in arrays and thus greatly improve performance. It is possible to use special features to effectively increase the number of dimensions in an array through indexing so the resulting array aquires the shape needed for use in an expression or with a specific function. Index arrays ============ Numpy arrays may be indexed with other arrays (or any other sequence- like object that can be converted to an array, such as lists, with the exception of tuples; see the end of this document for why this is). The use of index arrays ranges from simple, straightforward cases to complex, hard-to-understand cases. For all cases of index arrays, what is returned is a copy of the original data, not a view as one gets for slices. Index arrays must be of integer type. Each value in the array indicates which value in the array to use in place of the index. To illustrate: :: >>> x = np.arange(10,1,-1) >>> x array([10, 9, 8, 7, 6, 5, 4, 3, 2]) >>> x[np.array([3, 3, 1, 8])] array([7, 7, 9, 2]) The index array consisting of the values 3, 3, 1 and 8 correspondingly create an array of length 4 (same as the index array) where each index is replaced by the value the index array has in the array being indexed. Negative values are permitted and work as they do with single indices or slices: :: >>> x[np.array([3,3,-3,8])] array([7, 7, 4, 2]) It is an error to have index values out of bounds: :: >>> x[np.array([3, 3, 20, 8])] : index 20 out of bounds 0<=index<9 Generally speaking, what is returned when index arrays are used is an array with the same shape as the index array, but with the type and values of the array being indexed. As an example, we can use a multidimensional index array instead: :: >>> x[np.array([[1,1],[2,3]])] array([[9, 9], [8, 7]]) Indexing Multi-dimensional arrays ================================= Things become more complex when multidimensional arrays are indexed, particularly with multidimensional index arrays. These tend to be more unusal uses, but theyare permitted, and they are useful for some problems. We'll start with thesimplest multidimensional case (using the array y from the previous examples): :: >>> y[np.array([0,2,4]), np.array([0,1,2])] array([ 0, 15, 30]) In this case, if the index arrays have a matching shape, and there is an index array for each dimension of the array being indexed, the resultant array has the same shape as the index arrays, and the values correspond to the index set for each position in the index arrays. In this example, the first index value is 0 for both index arrays, and thus the first value of the resultant array is y[0,0]. The next value is y[2,1], and the last is y[4,2]. If the index arrays do not have the same shape, there is an attempt to broadcast them to the same shape. If they cannot be broadcast to the same shape, an exception is raised: :: >>> y[np.array([0,2,4]), np.array([0,1])] : shape mismatch: objects cannot be broadcast to a single shape The broadcasting mechanism permits index arrays to be combined with scalars for other indices. The effect is that the scalar value is used for all the corresponding values of the index arrays: :: >>> y[np.array([0,2,4]), 1] array([ 1, 15, 29]) Jumping to the next level of complexity, it is possible to only partially index an array with index arrays. It takes a bit of thought to understand what happens in such cases. For example if we just use one index array with y: :: >>> y[np.array([0,2,4])] array([[ 0, 1, 2, 3, 4, 5, 6], [14, 15, 16, 17, 18, 19, 20], [28, 29, 30, 31, 32, 33, 34]]) What results is the construction of a new array where each value of the index array selects one row from the array being indexed and the resultant array has the resulting shape (size of row, number index elements). An example of where this may be useful is for a color lookup table where we want to map the values of an image into RGB triples for display. The lookup table could have a shape (nlookup, 3). Indexing such an array with an image with shape (ny, nx) with dtype=np.uint8 (or any integer type so long as values are with the bounds of the lookup table) will result in an array of shape (ny, nx, 3) where a triple of RGB values is associated with each pixel location. In general, the shape of the resulant array will be the concatenation of the shape of the index array (or the shape that all the index arrays were broadcast to) with the shape of any unused dimensions (those not indexed) in the array being indexed. Boolean or "mask" index arrays ============================== Boolean arrays used as indices are treated in a different manner entirely than index arrays. Boolean arrays must be of the same shape as the array being indexed, or broadcastable to the same shape. In the most straightforward case, the boolean array has the same shape: :: >>> b = y>20 >>> y[b] array([21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34]) The result is a 1-D array containing all the elements in the indexed array corresponding to all the true elements in the boolean array. As with index arrays, what is returned is a copy of the data, not a view as one gets with slices. With broadcasting, multidimensional arrays may be the result. For example: :: >>> b[:,5] # use a 1-D boolean that broadcasts with y array([False, False, False, True, True], dtype=bool) >>> y[b[:,5]] array([[21, 22, 23, 24, 25, 26, 27], [28, 29, 30, 31, 32, 33, 34]]) Here the 4th and 5th rows are selected from the indexed array and combined to make a 2-D array. Combining index arrays with slices ================================== Index arrays may be combined with slices. For example: :: >>> y[np.array([0,2,4]),1:3] array([[ 1, 2], [15, 16], [29, 30]]) In effect, the slice is converted to an index array np.array([[1,2]]) (shape (1,2)) that is broadcast with the index array to produce a resultant array of shape (3,2). Likewise, slicing can be combined with broadcasted boolean indices: :: >>> y[b[:,5],1:3] array([[22, 23], [29, 30]]) Structural indexing tools ========================= To facilitate easy matching of array shapes with expressions and in assignments, the np.newaxis object can be used within array indices to add new dimensions with a size of 1. For example: :: >>> y.shape (5, 7) >>> y[:,np.newaxis,:].shape (5, 1, 7) Note that there are no new elements in the array, just that the dimensionality is increased. This can be handy to combine two arrays in a way that otherwise would require explicitly reshaping operations. For example: :: >>> x = np.arange(5) >>> x[:,np.newaxis] + x[np.newaxis,:] array([[0, 1, 2, 3, 4], [1, 2, 3, 4, 5], [2, 3, 4, 5, 6], [3, 4, 5, 6, 7], [4, 5, 6, 7, 8]]) The ellipsis syntax maybe used to indicate selecting in full any remaining unspecified dimensions. For example: :: >>> z = np.arange(81).reshape(3,3,3,3) >>> z[1,...,2] array([[29, 32, 35], [38, 41, 44], [47, 50, 53]]) This is equivalent to: :: >>> z[1,:,:,2] array([[29, 32, 35], [38, 41, 44], [47, 50, 53]]) Assigning values to indexed arrays ================================== As mentioned, one can select a subset of an array to assign to using a single index, slices, and index and mask arrays. The value being assigned to the indexed array must be shape consistent (the same shape or broadcastable to the shape the index produces). For example, it is permitted to assign a constant to a slice: :: >>> x = np.arange(10) >>> x[2:7] = 1 or an array of the right size: :: >>> x[2:7] = np.arange(5) Note that assignments may result in changes if assigning higher types to lower types (like floats to ints) or even exceptions (assigning complex to floats or ints): :: >>> x[1] = 1.2 >>> x[1] 1 >>> x[1] = 1.2j : can't convert complex to long; use long(abs(z)) Unlike some of the references (such as array and mask indices) assignments are always made to the original data in the array (indeed, nothing else would make sense!). Note though, that some actions may not work as one may naively expect. This particular example is often surprising to people: :: >>> x = np.arange(0, 50, 10) >>> x array([ 0, 10, 20, 30, 40]) >>> x[np.array([1, 1, 3, 1])] += 1 >>> x array([ 0, 11, 20, 31, 40]) Where people expect that the 1st location will be incremented by 3. In fact, it will only be incremented by 1. The reason is because a new array is extracted from the original (as a temporary) containing the values at 1, 1, 3, 1, then the value 1 is added to the temporary, and then the temporary is assigned back to the original array. Thus the value of the array at x[1]+1 is assigned to x[1] three times, rather than being incremented 3 times. Dealing with variable numbers of indices within programs ======================================================== The index syntax is very powerful but limiting when dealing with a variable number of indices. For example, if you want to write a function that can handle arguments with various numbers of dimensions without having to write special case code for each number of possible dimensions, how can that be done? If one supplies to the index a tuple, the tuple will be interpreted as a list of indices. For example (using the previous definition for the array z): :: >>> indices = (1,1,1,1) >>> z[indices] 40 So one can use code to construct tuples of any number of indices and then use these within an index. Slices can be specified within programs by using the slice() function in Python. For example: :: >>> indices = (1,1,1,slice(0,2)) # same as [1,1,1,0:2] >>> z[indices] array([39, 40]) Likewise, ellipsis can be specified by code by using the Ellipsis object: :: >>> indices = (1, Ellipsis, 1) # same as [1,...,1] >>> z[indices] array([[28, 31, 34], [37, 40, 43], [46, 49, 52]]) For this reason it is possible to use the output from the np.where() function directly as an index since it always returns a tuple of index arrays. Because the special treatment of tuples, they are not automatically converted to an array as a list would be. As an example: :: >>> z[[1,1,1,1]] # produces a large array array([[[[27, 28, 29], [30, 31, 32], ... >>> z[(1,1,1,1)] # returns a single value 40 """ from __future__ import division, absolute_import, print_function numpy-1.8.2/numpy/doc/basics.py0000664000175100017510000001323212370216242017557 0ustar vagrantvagrant00000000000000""" ============ Array basics ============ Array types and conversions between types ========================================= Numpy supports a much greater variety of numerical types than Python does. This section shows which are available, and how to modify an array's data-type. ========== ========================================================== Data type Description ========== ========================================================== bool_ Boolean (True or False) stored as a byte int_ Default integer type (same as C ``long``; normally either ``int64`` or ``int32``) intc Identical to C ``int`` (normally ``int32`` or ``int64``) intp Integer used for indexing (same as C ``ssize_t``; normally either ``int32`` or ``int64``) int8 Byte (-128 to 127) int16 Integer (-32768 to 32767) int32 Integer (-2147483648 to 2147483647) int64 Integer (-9223372036854775808 to 9223372036854775807) uint8 Unsigned integer (0 to 255) uint16 Unsigned integer (0 to 65535) uint32 Unsigned integer (0 to 4294967295) uint64 Unsigned integer (0 to 18446744073709551615) float_ Shorthand for ``float64``. float16 Half precision float: sign bit, 5 bits exponent, 10 bits mantissa float32 Single precision float: sign bit, 8 bits exponent, 23 bits mantissa float64 Double precision float: sign bit, 11 bits exponent, 52 bits mantissa complex_ Shorthand for ``complex128``. complex64 Complex number, represented by two 32-bit floats (real and imaginary components) complex128 Complex number, represented by two 64-bit floats (real and imaginary components) ========== ========================================================== Additionally to ``intc`` the platform dependent C integer types ``short``, ``long``, ``longlong`` and their unsigned versions are defined. Numpy numerical types are instances of ``dtype`` (data-type) objects, each having unique characteristics. Once you have imported NumPy using :: >>> import numpy as np the dtypes are available as ``np.bool_``, ``np.float32``, etc. Advanced types, not listed in the table above, are explored in section :ref:`structured_arrays`. There are 5 basic numerical types representing booleans (bool), integers (int), unsigned integers (uint) floating point (float) and complex. Those with numbers in their name indicate the bitsize of the type (i.e. how many bits are needed to represent a single value in memory). Some types, such as ``int`` and ``intp``, have differing bitsizes, dependent on the platforms (e.g. 32-bit vs. 64-bit machines). This should be taken into account when interfacing with low-level code (such as C or Fortran) where the raw memory is addressed. Data-types can be used as functions to convert python numbers to array scalars (see the array scalar section for an explanation), python sequences of numbers to arrays of that type, or as arguments to the dtype keyword that many numpy functions or methods accept. Some examples:: >>> import numpy as np >>> x = np.float32(1.0) >>> x 1.0 >>> y = np.int_([1,2,4]) >>> y array([1, 2, 4]) >>> z = np.arange(3, dtype=np.uint8) >>> z array([0, 1, 2], dtype=uint8) Array types can also be referred to by character codes, mostly to retain backward compatibility with older packages such as Numeric. Some documentation may still refer to these, for example:: >>> np.array([1, 2, 3], dtype='f') array([ 1., 2., 3.], dtype=float32) We recommend using dtype objects instead. To convert the type of an array, use the .astype() method (preferred) or the type itself as a function. For example: :: >>> z.astype(float) #doctest: +NORMALIZE_WHITESPACE array([ 0., 1., 2.]) >>> np.int8(z) array([0, 1, 2], dtype=int8) Note that, above, we use the *Python* float object as a dtype. NumPy knows that ``int`` refers to ``np.int_``, ``bool`` means ``np.bool_``, that ``float`` is ``np.float_`` and ``complex`` is ``np.complex_``. The other data-types do not have Python equivalents. To determine the type of an array, look at the dtype attribute:: >>> z.dtype dtype('uint8') dtype objects also contain information about the type, such as its bit-width and its byte-order. The data type can also be used indirectly to query properties of the type, such as whether it is an integer:: >>> d = np.dtype(int) >>> d dtype('int32') >>> np.issubdtype(d, int) True >>> np.issubdtype(d, float) False Array Scalars ============= Numpy generally returns elements of arrays as array scalars (a scalar with an associated dtype). Array scalars differ from Python scalars, but for the most part they can be used interchangeably (the primary exception is for versions of Python older than v2.x, where integer array scalars cannot act as indices for lists and tuples). There are some exceptions, such as when code requires very specific attributes of a scalar or when it checks specifically whether a value is a Python scalar. Generally, problems are easily fixed by explicitly converting array scalars to Python scalars, using the corresponding Python type function (e.g., ``int``, ``float``, ``complex``, ``str``, ``unicode``). The primary advantage of using array scalars is that they preserve the array type (Python may not have a matching scalar type available, e.g. ``int16``). Therefore, the use of array scalars ensures identical behaviour between arrays and scalars, irrespective of whether the value is inside an array or not. NumPy scalars also have many of the same methods arrays do. """ from __future__ import division, absolute_import, print_function numpy-1.8.2/numpy/doc/glossary.py0000664000175100017510000002741212370216242020163 0ustar vagrantvagrant00000000000000""" ======== Glossary ======== .. glossary:: along an axis Axes are defined for arrays with more than one dimension. A 2-dimensional array has two corresponding axes: the first running vertically downwards across rows (axis 0), and the second running horizontally across columns (axis 1). Many operation can take place along one of these axes. For example, we can sum each row of an array, in which case we operate along columns, or axis 1:: >>> x = np.arange(12).reshape((3,4)) >>> x array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]]) >>> x.sum(axis=1) array([ 6, 22, 38]) array A homogeneous container of numerical elements. Each element in the array occupies a fixed amount of memory (hence homogeneous), and can be a numerical element of a single type (such as float, int or complex) or a combination (such as ``(float, int, float)``). Each array has an associated data-type (or ``dtype``), which describes the numerical type of its elements:: >>> x = np.array([1, 2, 3], float) >>> x array([ 1., 2., 3.]) >>> x.dtype # floating point number, 64 bits of memory per element dtype('float64') # More complicated data type: each array element is a combination of # and integer and a floating point number >>> np.array([(1, 2.0), (3, 4.0)], dtype=[('x', int), ('y', float)]) array([(1, 2.0), (3, 4.0)], dtype=[('x', '>> x = np.array([1, 2, 3]) >>> x.shape (3,) BLAS `Basic Linear Algebra Subprograms `_ broadcast NumPy can do operations on arrays whose shapes are mismatched:: >>> x = np.array([1, 2]) >>> y = np.array([[3], [4]]) >>> x array([1, 2]) >>> y array([[3], [4]]) >>> x + y array([[4, 5], [5, 6]]) See `doc.broadcasting`_ for more information. C order See `row-major` column-major A way to represent items in a N-dimensional array in the 1-dimensional computer memory. In column-major order, the leftmost index "varies the fastest": for example the array:: [[1, 2, 3], [4, 5, 6]] is represented in the column-major order as:: [1, 4, 2, 5, 3, 6] Column-major order is also known as the Fortran order, as the Fortran programming language uses it. decorator An operator that transforms a function. For example, a ``log`` decorator may be defined to print debugging information upon function execution:: >>> def log(f): ... def new_logging_func(*args, **kwargs): ... print "Logging call with parameters:", args, kwargs ... return f(*args, **kwargs) ... ... return new_logging_func Now, when we define a function, we can "decorate" it using ``log``:: >>> @log ... def add(a, b): ... return a + b Calling ``add`` then yields: >>> add(1, 2) Logging call with parameters: (1, 2) {} 3 dictionary Resembling a language dictionary, which provides a mapping between words and descriptions thereof, a Python dictionary is a mapping between two objects:: >>> x = {1: 'one', 'two': [1, 2]} Here, `x` is a dictionary mapping keys to values, in this case the integer 1 to the string "one", and the string "two" to the list ``[1, 2]``. The values may be accessed using their corresponding keys:: >>> x[1] 'one' >>> x['two'] [1, 2] Note that dictionaries are not stored in any specific order. Also, most mutable (see *immutable* below) objects, such as lists, may not be used as keys. For more information on dictionaries, read the `Python tutorial `_. Fortran order See `column-major` flattened Collapsed to a one-dimensional array. See `ndarray.flatten`_ for details. immutable An object that cannot be modified after execution is called immutable. Two common examples are strings and tuples. instance A class definition gives the blueprint for constructing an object:: >>> class House(object): ... wall_colour = 'white' Yet, we have to *build* a house before it exists:: >>> h = House() # build a house Now, ``h`` is called a ``House`` instance. An instance is therefore a specific realisation of a class. iterable A sequence that allows "walking" (iterating) over items, typically using a loop such as:: >>> x = [1, 2, 3] >>> [item**2 for item in x] [1, 4, 9] It is often used in combintion with ``enumerate``:: >>> keys = ['a','b','c'] >>> for n, k in enumerate(keys): ... print "Key %d: %s" % (n, k) ... Key 0: a Key 1: b Key 2: c list A Python container that can hold any number of objects or items. The items do not have to be of the same type, and can even be lists themselves:: >>> x = [2, 2.0, "two", [2, 2.0]] The list `x` contains 4 items, each which can be accessed individually:: >>> x[2] # the string 'two' 'two' >>> x[3] # a list, containing an integer 2 and a float 2.0 [2, 2.0] It is also possible to select more than one item at a time, using *slicing*:: >>> x[0:2] # or, equivalently, x[:2] [2, 2.0] In code, arrays are often conveniently expressed as nested lists:: >>> np.array([[1, 2], [3, 4]]) array([[1, 2], [3, 4]]) For more information, read the section on lists in the `Python tutorial `_. For a mapping type (key-value), see *dictionary*. mask A boolean array, used to select only certain elements for an operation:: >>> x = np.arange(5) >>> x array([0, 1, 2, 3, 4]) >>> mask = (x > 2) >>> mask array([False, False, False, True, True], dtype=bool) >>> x[mask] = -1 >>> x array([ 0, 1, 2, -1, -1]) masked array Array that suppressed values indicated by a mask:: >>> x = np.ma.masked_array([np.nan, 2, np.nan], [True, False, True]) >>> x masked_array(data = [-- 2.0 --], mask = [ True False True], fill_value = 1e+20) >>> x + [1, 2, 3] masked_array(data = [-- 4.0 --], mask = [ True False True], fill_value = 1e+20) Masked arrays are often used when operating on arrays containing missing or invalid entries. matrix A 2-dimensional ndarray that preserves its two-dimensional nature throughout operations. It has certain special operations, such as ``*`` (matrix multiplication) and ``**`` (matrix power), defined:: >>> x = np.mat([[1, 2], [3, 4]]) >>> x matrix([[1, 2], [3, 4]]) >>> x**2 matrix([[ 7, 10], [15, 22]]) method A function associated with an object. For example, each ndarray has a method called ``repeat``:: >>> x = np.array([1, 2, 3]) >>> x.repeat(2) array([1, 1, 2, 2, 3, 3]) ndarray See *array*. reference If ``a`` is a reference to ``b``, then ``(a is b) == True``. Therefore, ``a`` and ``b`` are different names for the same Python object. row-major A way to represent items in a N-dimensional array in the 1-dimensional computer memory. In row-major order, the rightmost index "varies the fastest": for example the array:: [[1, 2, 3], [4, 5, 6]] is represented in the row-major order as:: [1, 2, 3, 4, 5, 6] Row-major order is also known as the C order, as the C programming language uses it. New Numpy arrays are by default in row-major order. self Often seen in method signatures, ``self`` refers to the instance of the associated class. For example: >>> class Paintbrush(object): ... color = 'blue' ... ... def paint(self): ... print "Painting the city %s!" % self.color ... >>> p = Paintbrush() >>> p.color = 'red' >>> p.paint() # self refers to 'p' Painting the city red! slice Used to select only certain elements from a sequence:: >>> x = range(5) >>> x [0, 1, 2, 3, 4] >>> x[1:3] # slice from 1 to 3 (excluding 3 itself) [1, 2] >>> x[1:5:2] # slice from 1 to 5, but skipping every second element [1, 3] >>> x[::-1] # slice a sequence in reverse [4, 3, 2, 1, 0] Arrays may have more than one dimension, each which can be sliced individually:: >>> x = np.array([[1, 2], [3, 4]]) >>> x array([[1, 2], [3, 4]]) >>> x[:, 1] array([2, 4]) tuple A sequence that may contain a variable number of types of any kind. A tuple is immutable, i.e., once constructed it cannot be changed. Similar to a list, it can be indexed and sliced:: >>> x = (1, 'one', [1, 2]) >>> x (1, 'one', [1, 2]) >>> x[0] 1 >>> x[:2] (1, 'one') A useful concept is "tuple unpacking", which allows variables to be assigned to the contents of a tuple:: >>> x, y = (1, 2) >>> x, y = 1, 2 This is often used when a function returns multiple values: >>> def return_many(): ... return 1, 'alpha', None >>> a, b, c = return_many() >>> a, b, c (1, 'alpha', None) >>> a 1 >>> b 'alpha' ufunc Universal function. A fast element-wise array operation. Examples include ``add``, ``sin`` and ``logical_or``. view An array that does not own its data, but refers to another array's data instead. For example, we may create a view that only shows every second element of another array:: >>> x = np.arange(5) >>> x array([0, 1, 2, 3, 4]) >>> y = x[::2] >>> y array([0, 2, 4]) >>> x[0] = 3 # changing x changes y as well, since y is a view on x >>> y array([3, 2, 4]) wrapper Python is a high-level (highly abstracted, or English-like) language. This abstraction comes at a price in execution speed, and sometimes it becomes necessary to use lower level languages to do fast computations. A wrapper is code that provides a bridge between high and the low level languages, allowing, e.g., Python to execute code written in C or Fortran. Examples include ctypes, SWIG and Cython (which wraps C and C++) and f2py (which wraps Fortran). """ from __future__ import division, absolute_import, print_function numpy-1.8.2/numpy/doc/constants.py0000664000175100017510000002137212370216242020333 0ustar vagrantvagrant00000000000000""" ========= Constants ========= Numpy includes several constants: %(constant_list)s """ # # Note: the docstring is autogenerated. # from __future__ import division, absolute_import, print_function import textwrap, re # Maintain same format as in numpy.add_newdocs constants = [] def add_newdoc(module, name, doc): constants.append((name, doc)) add_newdoc('numpy', 'Inf', """ IEEE 754 floating point representation of (positive) infinity. Use `inf` because `Inf`, `Infinity`, `PINF` and `infty` are aliases for `inf`. For more details, see `inf`. See Also -------- inf """) add_newdoc('numpy', 'Infinity', """ IEEE 754 floating point representation of (positive) infinity. Use `inf` because `Inf`, `Infinity`, `PINF` and `infty` are aliases for `inf`. For more details, see `inf`. See Also -------- inf """) add_newdoc('numpy', 'NAN', """ IEEE 754 floating point representation of Not a Number (NaN). `NaN` and `NAN` are equivalent definitions of `nan`. Please use `nan` instead of `NAN`. See Also -------- nan """) add_newdoc('numpy', 'NINF', """ IEEE 754 floating point representation of negative infinity. Returns ------- y : float A floating point representation of negative infinity. See Also -------- isinf : Shows which elements are positive or negative infinity isposinf : Shows which elements are positive infinity isneginf : Shows which elements are negative infinity isnan : Shows which elements are Not a Number isfinite : Shows which elements are finite (not one of Not a Number, positive infinity and negative infinity) Notes ----- 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. Examples -------- >>> np.NINF -inf >>> np.log(0) -inf """) add_newdoc('numpy', 'NZERO', """ IEEE 754 floating point representation of negative zero. Returns ------- y : float A floating point representation of negative zero. See Also -------- PZERO : Defines positive zero. isinf : Shows which elements are positive or negative infinity. isposinf : Shows which elements are positive infinity. isneginf : Shows which elements are negative infinity. isnan : Shows which elements are Not a Number. isfinite : Shows which elements are finite - not one of Not a Number, positive infinity and negative infinity. Notes ----- Numpy uses the IEEE Standard for Binary Floating-Point for Arithmetic (IEEE 754). Negative zero is considered to be a finite number. Examples -------- >>> np.NZERO -0.0 >>> np.PZERO 0.0 >>> np.isfinite([np.NZERO]) array([ True], dtype=bool) >>> np.isnan([np.NZERO]) array([False], dtype=bool) >>> np.isinf([np.NZERO]) array([False], dtype=bool) """) add_newdoc('numpy', 'NaN', """ IEEE 754 floating point representation of Not a Number (NaN). `NaN` and `NAN` are equivalent definitions of `nan`. Please use `nan` instead of `NaN`. See Also -------- nan """) add_newdoc('numpy', 'PINF', """ IEEE 754 floating point representation of (positive) infinity. Use `inf` because `Inf`, `Infinity`, `PINF` and `infty` are aliases for `inf`. For more details, see `inf`. See Also -------- inf """) add_newdoc('numpy', 'PZERO', """ IEEE 754 floating point representation of positive zero. Returns ------- y : float A floating point representation of positive zero. See Also -------- NZERO : Defines negative zero. isinf : Shows which elements are positive or negative infinity. isposinf : Shows which elements are positive infinity. isneginf : Shows which elements are negative infinity. isnan : Shows which elements are Not a Number. isfinite : Shows which elements are finite - not one of Not a Number, positive infinity and negative infinity. Notes ----- Numpy uses the IEEE Standard for Binary Floating-Point for Arithmetic (IEEE 754). Positive zero is considered to be a finite number. Examples -------- >>> np.PZERO 0.0 >>> np.NZERO -0.0 >>> np.isfinite([np.PZERO]) array([ True], dtype=bool) >>> np.isnan([np.PZERO]) array([False], dtype=bool) >>> np.isinf([np.PZERO]) array([False], dtype=bool) """) add_newdoc('numpy', 'e', """ Euler's constant, base of natural logarithms, Napier's constant. ``e = 2.71828182845904523536028747135266249775724709369995...`` See Also -------- exp : Exponential function log : Natural logarithm References ---------- .. [1] http://en.wikipedia.org/wiki/Napier_constant """) add_newdoc('numpy', 'inf', """ IEEE 754 floating point representation of (positive) infinity. Returns ------- y : float A floating point representation of positive infinity. See Also -------- isinf : Shows which elements are positive or negative infinity isposinf : Shows which elements are positive infinity isneginf : Shows which elements are negative infinity isnan : Shows which elements are Not a Number isfinite : Shows which elements are finite (not one of Not a Number, positive infinity and negative infinity) Notes ----- 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. `Inf`, `Infinity`, `PINF` and `infty` are aliases for `inf`. Examples -------- >>> np.inf inf >>> np.array([1]) / 0. array([ Inf]) """) add_newdoc('numpy', 'infty', """ IEEE 754 floating point representation of (positive) infinity. Use `inf` because `Inf`, `Infinity`, `PINF` and `infty` are aliases for `inf`. For more details, see `inf`. See Also -------- inf """) add_newdoc('numpy', 'nan', """ IEEE 754 floating point representation of Not a Number (NaN). Returns ------- y : A floating point representation of Not a Number. See Also -------- isnan : Shows which elements are Not a Number. isfinite : Shows which elements are finite (not one of Not a Number, positive infinity and negative infinity) Notes ----- Numpy uses the IEEE Standard for Binary Floating-Point for Arithmetic (IEEE 754). This means that Not a Number is not equivalent to infinity. `NaN` and `NAN` are aliases of `nan`. Examples -------- >>> np.nan nan >>> np.log(-1) nan >>> np.log([-1, 1, 2]) array([ NaN, 0. , 0.69314718]) """) add_newdoc('numpy', 'newaxis', """ A convenient alias for None, useful for indexing arrays. See Also -------- `numpy.doc.indexing` Examples -------- >>> newaxis is None True >>> x = np.arange(3) >>> x array([0, 1, 2]) >>> x[:, newaxis] array([[0], [1], [2]]) >>> x[:, newaxis, newaxis] array([[[0]], [[1]], [[2]]]) >>> x[:, newaxis] * x array([[0, 0, 0], [0, 1, 2], [0, 2, 4]]) Outer product, same as ``outer(x, y)``: >>> y = np.arange(3, 6) >>> x[:, newaxis] * y array([[ 0, 0, 0], [ 3, 4, 5], [ 6, 8, 10]]) ``x[newaxis, :]`` is equivalent to ``x[newaxis]`` and ``x[None]``: >>> x[newaxis, :].shape (1, 3) >>> x[newaxis].shape (1, 3) >>> x[None].shape (1, 3) >>> x[:, newaxis].shape (3, 1) """) if __doc__: constants_str = [] constants.sort() for name, doc in constants: s = textwrap.dedent(doc).replace("\n", "\n ") # Replace sections by rubrics lines = s.split("\n") new_lines = [] for line in lines: m = re.match(r'^(\s+)[-=]+\s*$', line) if m and new_lines: prev = textwrap.dedent(new_lines.pop()) new_lines.append('%s.. rubric:: %s' % (m.group(1), prev)) new_lines.append('') else: new_lines.append(line) s = "\n".join(new_lines) # Done. constants_str.append(""".. const:: %s\n %s""" % (name, s)) constants_str = "\n".join(constants_str) __doc__ = __doc__ % dict(constant_list=constants_str) del constants_str, name, doc del line, lines, new_lines, m, s, prev del constants, add_newdoc numpy-1.8.2/numpy/doc/creation.py0000664000175100017510000001257712370216242020132 0ustar vagrantvagrant00000000000000""" ============== Array Creation ============== Introduction ============ There are 5 general mechanisms for creating arrays: 1) Conversion from other Python structures (e.g., lists, tuples) 2) Intrinsic numpy array array creation objects (e.g., arange, ones, zeros, etc.) 3) Reading arrays from disk, either from standard or custom formats 4) Creating arrays from raw bytes through the use of strings or buffers 5) Use of special library functions (e.g., random) This section will not cover means of replicating, joining, or otherwise expanding or mutating existing arrays. Nor will it cover creating object arrays or record arrays. Both of those are covered in their own sections. Converting Python array_like Objects to Numpy Arrays ==================================================== In general, numerical data arranged in an array-like structure in Python can be converted to arrays through the use of the array() function. The most obvious examples are lists and tuples. See the documentation for array() for details for its use. Some objects may support the array-protocol and allow conversion to arrays this way. A simple way to find out if the object can be converted to a numpy array using array() is simply to try it interactively and see if it works! (The Python Way). Examples: :: >>> x = np.array([2,3,1,0]) >>> x = np.array([2, 3, 1, 0]) >>> x = np.array([[1,2.0],[0,0],(1+1j,3.)]) # note mix of tuple and lists, and types >>> x = np.array([[ 1.+0.j, 2.+0.j], [ 0.+0.j, 0.+0.j], [ 1.+1.j, 3.+0.j]]) Intrinsic Numpy Array Creation ============================== Numpy has built-in functions for creating arrays from scratch: zeros(shape) will create an array filled with 0 values with the specified shape. The default dtype is float64. ``>>> np.zeros((2, 3)) array([[ 0., 0., 0.], [ 0., 0., 0.]])`` ones(shape) will create an array filled with 1 values. It is identical to zeros in all other respects. arange() will create arrays with regularly incrementing values. Check the docstring for complete information on the various ways it can be used. A few examples will be given here: :: >>> np.arange(10) array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) >>> np.arange(2, 10, dtype=np.float) array([ 2., 3., 4., 5., 6., 7., 8., 9.]) >>> np.arange(2, 3, 0.1) array([ 2. , 2.1, 2.2, 2.3, 2.4, 2.5, 2.6, 2.7, 2.8, 2.9]) Note that there are some subtleties regarding the last usage that the user should be aware of that are described in the arange docstring. linspace() will create arrays with a specified number of elements, and spaced equally between the specified beginning and end values. For example: :: >>> np.linspace(1., 4., 6) array([ 1. , 1.6, 2.2, 2.8, 3.4, 4. ]) The advantage of this creation function is that one can guarantee the number of elements and the starting and end point, which arange() generally will not do for arbitrary start, stop, and step values. indices() will create a set of arrays (stacked as a one-higher dimensioned array), one per dimension with each representing variation in that dimension. An example illustrates much better than a verbal description: :: >>> np.indices((3,3)) array([[[0, 0, 0], [1, 1, 1], [2, 2, 2]], [[0, 1, 2], [0, 1, 2], [0, 1, 2]]]) This is particularly useful for evaluating functions of multiple dimensions on a regular grid. Reading Arrays From Disk ======================== This is presumably the most common case of large array creation. The details, of course, depend greatly on the format of data on disk and so this section can only give general pointers on how to handle various formats. Standard Binary Formats ----------------------- Various fields have standard formats for array data. The following lists the ones with known python libraries to read them and return numpy arrays (there may be others for which it is possible to read and convert to numpy arrays so check the last section as well) :: HDF5: PyTables FITS: PyFITS Examples of formats that cannot be read directly but for which it is not hard to convert are those formats supported by libraries like PIL (able to read and write many image formats such as jpg, png, etc). Common ASCII Formats ------------------------ Comma Separated Value files (CSV) are widely used (and an export and import option for programs like Excel). There are a number of ways of reading these files in Python. There are CSV functions in Python and functions in pylab (part of matplotlib). More generic ascii files can be read using the io package in scipy. Custom Binary Formats --------------------- There are a variety of approaches one can use. If the file has a relatively simple format then one can write a simple I/O library and use the numpy fromfile() function and .tofile() method to read and write numpy arrays directly (mind your byteorder though!) If a good C or C++ library exists that read the data, one can wrap that library with a variety of techniques though that certainly is much more work and requires significantly more advanced knowledge to interface with C or C++. Use of Special Libraries ------------------------ There are libraries that can be used to generate arrays for special purposes and it isn't possible to enumerate all of them. The most common uses are use of the many array generation functions in random that can generate arrays of random values, and some utility functions to generate special matrices (e.g. diagonal). """ from __future__ import division, absolute_import, print_function numpy-1.8.2/numpy/doc/internals.py0000664000175100017510000002271112370216242020314 0ustar vagrantvagrant00000000000000""" =============== Array Internals =============== Internal organization of numpy arrays ===================================== It helps to understand a bit about how numpy arrays are handled under the covers to help understand numpy better. This section will not go into great detail. Those wishing to understand the full details are referred to Travis Oliphant's book "Guide to Numpy". Numpy arrays consist of two major components, the raw array data (from now on, referred to as the data buffer), and the information about the raw array data. The data buffer is typically what people think of as arrays in C or Fortran, a contiguous (and fixed) block of memory containing fixed sized data items. Numpy also contains a significant set of data that describes how to interpret the data in the data buffer. This extra information contains (among other things): 1) The basic data element's size in bytes 2) The start of the data within the data buffer (an offset relative to the beginning of the data buffer). 3) The number of dimensions and the size of each dimension 4) The separation between elements for each dimension (the 'stride'). This does not have to be a multiple of the element size 5) The byte order of the data (which may not be the native byte order) 6) Whether the buffer is read-only 7) Information (via the dtype object) about the interpretation of the basic data element. The basic data element may be as simple as a int or a float, or it may be a compound object (e.g., struct-like), a fixed character field, or Python object pointers. 8) Whether the array is to interpreted as C-order or Fortran-order. This arrangement allow for very flexible use of arrays. One thing that it allows is simple changes of the metadata to change the interpretation of the array buffer. Changing the byteorder of the array is a simple change involving no rearrangement of the data. The shape of the array can be changed very easily without changing anything in the data buffer or any data copying at all Among other things that are made possible is one can create a new array metadata object that uses the same data buffer to create a new view of that data buffer that has a different interpretation of the buffer (e.g., different shape, offset, byte order, strides, etc) but shares the same data bytes. Many operations in numpy do just this such as slices. Other operations, such as transpose, don't move data elements around in the array, but rather change the information about the shape and strides so that the indexing of the array changes, but the data in the doesn't move. Typically these new versions of the array metadata but the same data buffer are new 'views' into the data buffer. There is a different ndarray object, but it uses the same data buffer. This is why it is necessary to force copies through use of the .copy() method if one really wants to make a new and independent copy of the data buffer. New views into arrays mean the the object reference counts for the data buffer increase. Simply doing away with the original array object will not remove the data buffer if other views of it still exist. Multidimensional Array Indexing Order Issues ============================================ What is the right way to index multi-dimensional arrays? Before you jump to conclusions about the one and true way to index multi-dimensional arrays, it pays to understand why this is a confusing issue. This section will try to explain in detail how numpy indexing works and why we adopt the convention we do for images, and when it may be appropriate to adopt other conventions. The first thing to understand is that there are two conflicting conventions for indexing 2-dimensional arrays. Matrix notation uses the first index to indicate which row is being selected and the second index to indicate which column is selected. This is opposite the geometrically oriented-convention for images where people generally think the first index represents x position (i.e., column) and the second represents y position (i.e., row). This alone is the source of much confusion; matrix-oriented users and image-oriented users expect two different things with regard to indexing. The second issue to understand is how indices correspond to the order the array is stored in memory. In Fortran the first index is the most rapidly varying index when moving through the elements of a two dimensional array as it is stored in memory. If you adopt the matrix convention for indexing, then this means the matrix is stored one column at a time (since the first index moves to the next row as it changes). Thus Fortran is considered a Column-major language. C has just the opposite convention. In C, the last index changes most rapidly as one moves through the array as stored in memory. Thus C is a Row-major language. The matrix is stored by rows. Note that in both cases it presumes that the matrix convention for indexing is being used, i.e., for both Fortran and C, the first index is the row. Note this convention implies that the indexing convention is invariant and that the data order changes to keep that so. But that's not the only way to look at it. Suppose one has large two-dimensional arrays (images or matrices) stored in data files. Suppose the data are stored by rows rather than by columns. If we are to preserve our index convention (whether matrix or image) that means that depending on the language we use, we may be forced to reorder the data if it is read into memory to preserve our indexing convention. For example if we read row-ordered data into memory without reordering, it will match the matrix indexing convention for C, but not for Fortran. Conversely, it will match the image indexing convention for Fortran, but not for C. For C, if one is using data stored in row order, and one wants to preserve the image index convention, the data must be reordered when reading into memory. In the end, which you do for Fortran or C depends on which is more important, not reordering data or preserving the indexing convention. For large images, reordering data is potentially expensive, and often the indexing convention is inverted to avoid that. The situation with numpy makes this issue yet more complicated. The internal machinery of numpy arrays is flexible enough to accept any ordering of indices. One can simply reorder indices by manipulating the internal stride information for arrays without reordering the data at all. Numpy will know how to map the new index order to the data without moving the data. So if this is true, why not choose the index order that matches what you most expect? In particular, why not define row-ordered images to use the image convention? (This is sometimes referred to as the Fortran convention vs the C convention, thus the 'C' and 'FORTRAN' order options for array ordering in numpy.) The drawback of doing this is potential performance penalties. It's common to access the data sequentially, either implicitly in array operations or explicitly by looping over rows of an image. When that is done, then the data will be accessed in non-optimal order. As the first index is incremented, what is actually happening is that elements spaced far apart in memory are being sequentially accessed, with usually poor memory access speeds. For example, for a two dimensional image 'im' defined so that im[0, 10] represents the value at x=0, y=10. To be consistent with usual Python behavior then im[0] would represent a column at x=0. Yet that data would be spread over the whole array since the data are stored in row order. Despite the flexibility of numpy's indexing, it can't really paper over the fact basic operations are rendered inefficient because of data order or that getting contiguous subarrays is still awkward (e.g., im[:,0] for the first row, vs im[0]), thus one can't use an idiom such as for row in im; for col in im does work, but doesn't yield contiguous column data. As it turns out, numpy is smart enough when dealing with ufuncs to determine which index is the most rapidly varying one in memory and uses that for the innermost loop. Thus for ufuncs there is no large intrinsic advantage to either approach in most cases. On the other hand, use of .flat with an FORTRAN ordered array will lead to non-optimal memory access as adjacent elements in the flattened array (iterator, actually) are not contiguous in memory. Indeed, the fact is that Python indexing on lists and other sequences naturally leads to an outside-to inside ordering (the first index gets the largest grouping, the next the next largest, and the last gets the smallest element). Since image data are normally stored by rows, this corresponds to position within rows being the last item indexed. If you do want to use Fortran ordering realize that there are two approaches to consider: 1) accept that the first index is just not the most rapidly changing in memory and have all your I/O routines reorder your data when going from memory to disk or visa versa, or use numpy's mechanism for mapping the first index to the most rapidly varying data. We recommend the former if possible. The disadvantage of the latter is that many of numpy's functions will yield arrays without Fortran ordering unless you are careful to use the 'order' keyword. Doing this would be highly inconvenient. Otherwise we recommend simply learning to reverse the usual order of indices when accessing elements of an array. Granted, it goes against the grain, but it is more in line with Python semantics and the natural order of the data. """ from __future__ import division, absolute_import, print_function numpy-1.8.2/numpy/doc/methods_vs_functions.py0000664000175100017510000000030312370216242022551 0ustar vagrantvagrant00000000000000""" ===================== Methods vs. Functions ===================== Placeholder for Methods vs. Functions documentation. """ from __future__ import division, absolute_import, print_function numpy-1.8.2/numpy/doc/byteswapping.py0000664000175100017510000001136012370216243021030 0ustar vagrantvagrant00000000000000""" ============================= Byteswapping and byte order ============================= Introduction to byte ordering and ndarrays ========================================== The ``ndarray`` is an object that provide a python array interface to data in memory. It often happens that the memory that you want to view with an array is not of the same byte ordering as the computer on which you are running Python. For example, I might be working on a computer with a little-endian CPU - such as an Intel Pentium, but I have loaded some data from a file written by a computer that is big-endian. Let's say I have loaded 4 bytes from a file written by a Sun (big-endian) computer. I know that these 4 bytes represent two 16-bit integers. On a big-endian machine, a two-byte integer is stored with the Most Significant Byte (MSB) first, and then the Least Significant Byte (LSB). Thus the bytes are, in memory order: #. MSB integer 1 #. LSB integer 1 #. MSB integer 2 #. LSB integer 2 Let's say the two integers were in fact 1 and 770. Because 770 = 256 * 3 + 2, the 4 bytes in memory would contain respectively: 0, 1, 3, 2. The bytes I have loaded from the file would have these contents: >>> big_end_str = chr(0) + chr(1) + chr(3) + chr(2) >>> big_end_str '\\x00\\x01\\x03\\x02' We might want to use an ``ndarray`` to access these integers. In that case, we can create an array around this memory, and tell numpy that there are two integers, and that they are 16 bit and big-endian: >>> import numpy as np >>> big_end_arr = np.ndarray(shape=(2,),dtype='>i2', buffer=big_end_str) >>> big_end_arr[0] 1 >>> big_end_arr[1] 770 Note the array ``dtype`` above of ``>i2``. The ``>`` means 'big-endian' (``<`` is little-endian) and ``i2`` means 'signed 2-byte integer'. For example, if our data represented a single unsigned 4-byte little-endian integer, the dtype string would be ``>> little_end_u4 = np.ndarray(shape=(1,),dtype='>> little_end_u4[0] == 1 * 256**1 + 3 * 256**2 + 2 * 256**3 True Returning to our ``big_end_arr`` - in this case our underlying data is big-endian (data endianness) and we've set the dtype to match (the dtype is also big-endian). However, sometimes you need to flip these around. Changing byte ordering ====================== As you can imagine from the introduction, there are two ways you can affect the relationship between the byte ordering of the array and the underlying memory it is looking at: * Change the byte-ordering information in the array dtype so that it interprets the undelying data as being in a different byte order. This is the role of ``arr.newbyteorder()`` * Change the byte-ordering of the underlying data, leaving the dtype interpretation as it was. This is what ``arr.byteswap()`` does. The common situations in which you need to change byte ordering are: #. Your data and dtype endianess don't match, and you want to change the dtype so that it matches the data. #. Your data and dtype endianess don't match, and you want to swap the data so that they match the dtype #. Your data and dtype endianess match, but you want the data swapped and the dtype to reflect this Data and dtype endianness don't match, change dtype to match data ----------------------------------------------------------------- We make something where they don't match: >>> wrong_end_dtype_arr = np.ndarray(shape=(2,),dtype='>> wrong_end_dtype_arr[0] 256 The obvious fix for this situation is to change the dtype so it gives the correct endianness: >>> fixed_end_dtype_arr = wrong_end_dtype_arr.newbyteorder() >>> fixed_end_dtype_arr[0] 1 Note the the array has not changed in memory: >>> fixed_end_dtype_arr.tostring() == big_end_str True Data and type endianness don't match, change data to match dtype ---------------------------------------------------------------- You might want to do this if you need the data in memory to be a certain ordering. For example you might be writing the memory out to a file that needs a certain byte ordering. >>> fixed_end_mem_arr = wrong_end_dtype_arr.byteswap() >>> fixed_end_mem_arr[0] 1 Now the array *has* changed in memory: >>> fixed_end_mem_arr.tostring() == big_end_str False Data and dtype endianness match, swap data and dtype ---------------------------------------------------- You may have a correctly specified array dtype, but you need the array to have the opposite byte order in memory, and you want the dtype to match so the array values make sense. In this case you just do both of the previous operations: >>> swapped_end_arr = big_end_arr.byteswap().newbyteorder() >>> swapped_end_arr[0] 1 >>> swapped_end_arr.tostring() == big_end_str False """ from __future__ import division, absolute_import, print_function numpy-1.8.2/numpy/doc/structured_arrays.py0000664000175100017510000002110712370216242022100 0ustar vagrantvagrant00000000000000""" ===================================== Structured Arrays (and Record Arrays) ===================================== Introduction ============ Numpy provides powerful capabilities to create arrays of structs or records. These arrays permit one to manipulate the data by the structs or by fields of the struct. A simple example will show what is meant.: :: >>> x = np.zeros((2,),dtype=('i4,f4,a10')) >>> x[:] = [(1,2.,'Hello'),(2,3.,"World")] >>> x array([(1, 2.0, 'Hello'), (2, 3.0, 'World')], dtype=[('f0', '>i4'), ('f1', '>f4'), ('f2', '|S10')]) Here we have created a one-dimensional array of length 2. Each element of this array is a record that contains three items, a 32-bit integer, a 32-bit float, and a string of length 10 or less. If we index this array at the second position we get the second record: :: >>> x[1] (2,3.,"World") Conveniently, one can access any field of the array by indexing using the string that names that field. In this case the fields have received the default names 'f0', 'f1' and 'f2'. :: >>> y = x['f1'] >>> y array([ 2., 3.], dtype=float32) >>> y[:] = 2*y >>> y array([ 4., 6.], dtype=float32) >>> x array([(1, 4.0, 'Hello'), (2, 6.0, 'World')], dtype=[('f0', '>i4'), ('f1', '>f4'), ('f2', '|S10')]) In these examples, y is a simple float array consisting of the 2nd field in the record. But, rather than being a copy of the data in the structured array, it is a view, i.e., it shares exactly the same memory locations. Thus, when we updated this array by doubling its values, the structured array shows the corresponding values as doubled as well. Likewise, if one changes the record, the field view also changes: :: >>> x[1] = (-1,-1.,"Master") >>> x array([(1, 4.0, 'Hello'), (-1, -1.0, 'Master')], dtype=[('f0', '>i4'), ('f1', '>f4'), ('f2', '|S10')]) >>> y array([ 4., -1.], dtype=float32) Defining Structured Arrays ========================== One defines a structured array through the dtype object. There are **several** alternative ways to define the fields of a record. Some of these variants provide backward compatibility with Numeric, numarray, or another module, and should not be used except for such purposes. These will be so noted. One specifies record structure in one of four alternative ways, using an argument (as supplied to a dtype function keyword or a dtype object constructor itself). This argument must be one of the following: 1) string, 2) tuple, 3) list, or 4) dictionary. Each of these is briefly described below. 1) String argument (as used in the above examples). In this case, the constructor expects a comma-separated list of type specifiers, optionally with extra shape information. The type specifiers can take 4 different forms: :: a) b1, i1, i2, i4, i8, u1, u2, u4, u8, f2, f4, f8, c8, c16, a (representing bytes, ints, unsigned ints, floats, complex and fixed length strings of specified byte lengths) b) int8,...,uint8,...,float16, float32, float64, complex64, complex128 (this time with bit sizes) c) older Numeric/numarray type specifications (e.g. Float32). Don't use these in new code! d) Single character type specifiers (e.g H for unsigned short ints). Avoid using these unless you must. Details can be found in the Numpy book These different styles can be mixed within the same string (but why would you want to do that?). Furthermore, each type specifier can be prefixed with a repetition number, or a shape. In these cases an array element is created, i.e., an array within a record. That array is still referred to as a single field. An example: :: >>> x = np.zeros(3, dtype='3int8, float32, (2,3)float64') >>> x array([([0, 0, 0], 0.0, [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]), ([0, 0, 0], 0.0, [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]), ([0, 0, 0], 0.0, [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]])], dtype=[('f0', '|i1', 3), ('f1', '>f4'), ('f2', '>f8', (2, 3))]) By using strings to define the record structure, it precludes being able to name the fields in the original definition. The names can be changed as shown later, however. 2) Tuple argument: The only relevant tuple case that applies to record structures is when a structure is mapped to an existing data type. This is done by pairing in a tuple, the existing data type with a matching dtype definition (using any of the variants being described here). As an example (using a definition using a list, so see 3) for further details): :: >>> x = np.zeros(3, dtype=('i4',[('r','u1'), ('g','u1'), ('b','u1'), ('a','u1')])) >>> x array([0, 0, 0]) >>> x['r'] array([0, 0, 0], dtype=uint8) In this case, an array is produced that looks and acts like a simple int32 array, but also has definitions for fields that use only one byte of the int32 (a bit like Fortran equivalencing). 3) List argument: In this case the record structure is defined with a list of tuples. Each tuple has 2 or 3 elements specifying: 1) The name of the field ('' is permitted), 2) the type of the field, and 3) the shape (optional). For example:: >>> x = np.zeros(3, dtype=[('x','f4'),('y',np.float32),('value','f4',(2,2))]) >>> x array([(0.0, 0.0, [[0.0, 0.0], [0.0, 0.0]]), (0.0, 0.0, [[0.0, 0.0], [0.0, 0.0]]), (0.0, 0.0, [[0.0, 0.0], [0.0, 0.0]])], dtype=[('x', '>f4'), ('y', '>f4'), ('value', '>f4', (2, 2))]) 4) Dictionary argument: two different forms are permitted. The first consists of a dictionary with two required keys ('names' and 'formats'), each having an equal sized list of values. The format list contains any type/shape specifier allowed in other contexts. The names must be strings. There are two optional keys: 'offsets' and 'titles'. Each must be a correspondingly matching list to the required two where offsets contain integer offsets for each field, and titles are objects containing metadata for each field (these do not have to be strings), where the value of None is permitted. As an example: :: >>> x = np.zeros(3, dtype={'names':['col1', 'col2'], 'formats':['i4','f4']}) >>> x array([(0, 0.0), (0, 0.0), (0, 0.0)], dtype=[('col1', '>i4'), ('col2', '>f4')]) The other dictionary form permitted is a dictionary of name keys with tuple values specifying type, offset, and an optional title. :: >>> x = np.zeros(3, dtype={'col1':('i1',0,'title 1'), 'col2':('f4',1,'title 2')}) >>> x array([(0, 0.0), (0, 0.0), (0, 0.0)], dtype=[(('title 1', 'col1'), '|i1'), (('title 2', 'col2'), '>f4')]) Accessing and modifying field names =================================== The field names are an attribute of the dtype object defining the record structure. For the last example: :: >>> x.dtype.names ('col1', 'col2') >>> x.dtype.names = ('x', 'y') >>> x array([(0, 0.0), (0, 0.0), (0, 0.0)], dtype=[(('title 1', 'x'), '|i1'), (('title 2', 'y'), '>f4')]) >>> x.dtype.names = ('x', 'y', 'z') # wrong number of names : must replace all names at once with a sequence of length 2 Accessing field titles ==================================== The field titles provide a standard place to put associated info for fields. They do not have to be strings. :: >>> x.dtype.fields['x'][2] 'title 1' Accessing multiple fields at once ==================================== You can access multiple fields at once using a list of field names: :: >>> x = np.array([(1.5,2.5,(1.0,2.0)),(3.,4.,(4.,5.)),(1.,3.,(2.,6.))], dtype=[('x','f4'),('y',np.float32),('value','f4',(2,2))]) Notice that `x` is created with a list of tuples. :: >>> x[['x','y']] array([(1.5, 2.5), (3.0, 4.0), (1.0, 3.0)], dtype=[('x', '>> x[['x','value']] array([(1.5, [[1.0, 2.0], [1.0, 2.0]]), (3.0, [[4.0, 5.0], [4.0, 5.0]]), (1.0, [[2.0, 6.0], [2.0, 6.0]])], dtype=[('x', '>> x[['y','x']] array([(2.5, 1.5), (4.0, 3.0), (3.0, 1.0)], dtype=[('y', '>> arr = np.zeros((5,), dtype=[('var1','f8'),('var2','f8')]) >>> arr['var1'] = np.arange(5) If you fill it in row by row, it takes a take a tuple (but not a list or array!):: >>> arr[0] = (10,20) >>> arr array([(10.0, 20.0), (1.0, 0.0), (2.0, 0.0), (3.0, 0.0), (4.0, 0.0)], dtype=[('var1', '`_. """ from __future__ import division, absolute_import, print_function numpy-1.8.2/numpy/doc/ufuncs.py0000664000175100017510000001246312370216242017623 0ustar vagrantvagrant00000000000000""" =================== Universal Functions =================== Ufuncs are, generally speaking, mathematical functions or operations that are applied element-by-element to the contents of an array. That is, the result in each output array element only depends on the value in the corresponding input array (or arrays) and on no other array elements. Numpy comes with a large suite of ufuncs, and scipy extends that suite substantially. The simplest example is the addition operator: :: >>> np.array([0,2,3,4]) + np.array([1,1,-1,2]) array([1, 3, 2, 6]) The unfunc module lists all the available ufuncs in numpy. Documentation on the specific ufuncs may be found in those modules. This documentation is intended to address the more general aspects of unfuncs common to most of them. All of the ufuncs that make use of Python operators (e.g., +, -, etc.) have equivalent functions defined (e.g. add() for +) Type coercion ============= What happens when a binary operator (e.g., +,-,\\*,/, etc) deals with arrays of two different types? What is the type of the result? Typically, the result is the higher of the two types. For example: :: float32 + float64 -> float64 int8 + int32 -> int32 int16 + float32 -> float32 float32 + complex64 -> complex64 There are some less obvious cases generally involving mixes of types (e.g. uints, ints and floats) where equal bit sizes for each are not capable of saving all the information in a different type of equivalent bit size. Some examples are int32 vs float32 or uint32 vs int32. Generally, the result is the higher type of larger size than both (if available). So: :: int32 + float32 -> float64 uint32 + int32 -> int64 Finally, the type coercion behavior when expressions involve Python scalars is different than that seen for arrays. Since Python has a limited number of types, combining a Python int with a dtype=np.int8 array does not coerce to the higher type but instead, the type of the array prevails. So the rules for Python scalars combined with arrays is that the result will be that of the array equivalent the Python scalar if the Python scalar is of a higher 'kind' than the array (e.g., float vs. int), otherwise the resultant type will be that of the array. For example: :: Python int + int8 -> int8 Python float + int8 -> float64 ufunc methods ============= Binary ufuncs support 4 methods. **.reduce(arr)** applies the binary operator to elements of the array in sequence. For example: :: >>> np.add.reduce(np.arange(10)) # adds all elements of array 45 For multidimensional arrays, the first dimension is reduced by default: :: >>> np.add.reduce(np.arange(10).reshape(2,5)) array([ 5, 7, 9, 11, 13]) The axis keyword can be used to specify different axes to reduce: :: >>> np.add.reduce(np.arange(10).reshape(2,5),axis=1) array([10, 35]) **.accumulate(arr)** applies the binary operator and generates an an equivalently shaped array that includes the accumulated amount for each element of the array. A couple examples: :: >>> np.add.accumulate(np.arange(10)) array([ 0, 1, 3, 6, 10, 15, 21, 28, 36, 45]) >>> np.multiply.accumulate(np.arange(1,9)) array([ 1, 2, 6, 24, 120, 720, 5040, 40320]) The behavior for multidimensional arrays is the same as for .reduce(), as is the use of the axis keyword). **.reduceat(arr,indices)** allows one to apply reduce to selected parts of an array. It is a difficult method to understand. See the documentation at: **.outer(arr1,arr2)** generates an outer operation on the two arrays arr1 and arr2. It will work on multidimensional arrays (the shape of the result is the concatenation of the two input shapes.: :: >>> np.multiply.outer(np.arange(3),np.arange(4)) array([[0, 0, 0, 0], [0, 1, 2, 3], [0, 2, 4, 6]]) Output arguments ================ All ufuncs accept an optional output array. The array must be of the expected output shape. Beware that if the type of the output array is of a different (and lower) type than the output result, the results may be silently truncated or otherwise corrupted in the downcast to the lower type. This usage is useful when one wants to avoid creating large temporary arrays and instead allows one to reuse the same array memory repeatedly (at the expense of not being able to use more convenient operator notation in expressions). Note that when the output argument is used, the ufunc still returns a reference to the result. >>> x = np.arange(2) >>> np.add(np.arange(2),np.arange(2.),x) array([0, 2]) >>> x array([0, 2]) and & or as ufuncs ================== Invariably people try to use the python 'and' and 'or' as logical operators (and quite understandably). But these operators do not behave as normal operators since Python treats these quite differently. They cannot be overloaded with array equivalents. Thus using 'and' or 'or' with an array results in an error. There are two alternatives: 1) use the ufunc functions logical_and() and logical_or(). 2) use the bitwise operators & and \\|. The drawback of these is that if the arguments to these operators are not boolean arrays, the result is likely incorrect. On the other hand, most usages of logical_and and logical_or are with boolean arrays. As long as one is careful, this is a convenient way to apply these operators. """ from __future__ import division, absolute_import, print_function numpy-1.8.2/numpy/doc/jargon.py0000664000175100017510000000024112370216242017567 0ustar vagrantvagrant00000000000000""" ====== Jargon ====== Placeholder for computer science, engineering and other jargon. """ from __future__ import division, absolute_import, print_function numpy-1.8.2/numpy/doc/__init__.py0000664000175100017510000000107612370216242020055 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function import os ref_dir = os.path.join(os.path.dirname(__file__)) __all__ = sorted(f[:-3] for f in os.listdir(ref_dir) if f.endswith('.py') and not f.startswith('__')) for f in __all__: __import__(__name__ + '.' + f) del f, ref_dir __doc__ = """\ Topical documentation ===================== The following topics are available: %s You can view them by >>> help(np.doc.TOPIC) #doctest: +SKIP """ % '\n- '.join([''] + __all__) __all__.extend(['__doc__']) numpy-1.8.2/numpy/doc/io.py0000664000175100017510000000022312370216242016716 0ustar vagrantvagrant00000000000000""" ========= Array I/O ========= Placeholder for array I/O documentation. """ from __future__ import division, absolute_import, print_function numpy-1.8.2/numpy/doc/misc.py0000664000175100017510000001404212370216243017247 0ustar vagrantvagrant00000000000000""" ============= Miscellaneous ============= IEEE 754 Floating Point Special Values: ----------------------------------------------- Special values defined in numpy: nan, inf, NaNs can be used as a poor-man's mask (if you don't care what the original value was) Note: cannot use equality to test NaNs. E.g.: :: >>> myarr = np.array([1., 0., np.nan, 3.]) >>> np.where(myarr == np.nan) >>> np.nan == np.nan # is always False! Use special numpy functions instead. False >>> myarr[myarr == np.nan] = 0. # doesn't work >>> myarr array([ 1., 0., NaN, 3.]) >>> myarr[np.isnan(myarr)] = 0. # use this instead find >>> myarr array([ 1., 0., 0., 3.]) Other related special value functions: :: isinf(): True if value is inf isfinite(): True if not nan or inf nan_to_num(): Map nan to 0, inf to max float, -inf to min float The following corresponds to the usual functions except that nans are excluded from the results: :: nansum() nanmax() nanmin() nanargmax() nanargmin() >>> x = np.arange(10.) >>> x[3] = np.nan >>> x.sum() nan >>> np.nansum(x) 42.0 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 set individually for different kinds of exceptions. The different behaviors are: - 'ignore' : Take no action when the exception occurs. - 'warn' : Print a `RuntimeWarning` (via the Python `warnings` module). - 'raise' : Raise a `FloatingPointError`. - 'call' : Call a function specified using the `seterrcall` function. - 'print' : Print a warning directly to ``stdout``. - 'log' : Record error in a Log object specified by `seterrcall`. These behaviors can be set for all kinds of errors or specific ones: - all : apply to all numeric exceptions - invalid : when NaNs are generated - divide : divide by zero (for integers as well!) - overflow : floating point overflows - underflow : floating point underflows Note that integer divide-by-zero is handled by the same machinery. These behaviors are set on a per-thread basis. Examples: ------------ :: >>> oldsettings = np.seterr(all='warn') >>> np.zeros(5,dtype=np.float32)/0. invalid value encountered in divide >>> j = np.seterr(under='ignore') >>> np.array([1.e-100])**10 >>> j = np.seterr(invalid='raise') >>> np.sqrt(np.array([-1.])) FloatingPointError: invalid value encountered in sqrt >>> def errorhandler(errstr, errflag): ... print "saw stupid error!" >>> np.seterrcall(errorhandler) >>> j = np.seterr(all='call') >>> np.zeros(5, dtype=np.int32)/0 FloatingPointError: invalid value encountered in divide saw stupid error! >>> j = np.seterr(**oldsettings) # restore previous ... # error-handling settings Interfacing to C: ----------------- Only a survey of the choices. Little detail on how each works. 1) Bare metal, wrap your own C-code manually. - Plusses: - Efficient - No dependencies on other tools - Minuses: - Lots of learning overhead: - need to learn basics of Python C API - need to learn basics of numpy C API - need to learn how to handle reference counting and love it. - Reference counting often difficult to get right. - getting it wrong leads to memory leaks, and worse, segfaults - API will change for Python 3.0! 2) pyrex - Plusses: - avoid learning C API's - no dealing with reference counting - can code in psuedo 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 - 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 - Plusses: - part of Python standard library - good for interfacing to existing sharable libraries, particularly Windows DLLs - avoids API/reference counting issues - good numpy support: arrays have all these in their ctypes attribute: :: a.ctypes.data a.ctypes.get_strides a.ctypes.data_as a.ctypes.shape a.ctypes.get_as_parameter a.ctypes.shape_as a.ctypes.get_data a.ctypes.strides a.ctypes.get_shape a.ctypes.strides_as - Minuses: - can't use for writing code to be turned into C extensions, only a wrapper tool. 5) SWIG (automatic wrapper generator) - Plusses: - around a long time - multiple scripting language support - C++ support - Good for wrapping large (many functions) existing C libraries - Minuses: - generates lots of code between Python and the C code - can cause performance problems that are nearly impossible to optimize out - interface files can be hard to write - doesn't necessarily avoid reference counting issues or needing to know API's 7) 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 interfaces and compile, etc. - Minuses: - Future uncertain--lacks a champion 8) Psyco - Plusses: - Turns pure python into efficient machine code through jit-like optimizations - very fast when it optimizes well - Minuses: - Only on intel (windows?) - Doesn't do much for numpy? Interfacing to Fortran: ----------------------- Fortran: Clear choice is f2py. (Pyfort is an older alternative, but not supported 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) 5) SIP (used mainly in PyQT) """ from __future__ import division, absolute_import, print_function numpy-1.8.2/numpy/doc/performance.py0000664000175100017510000000024512370216242020614 0ustar vagrantvagrant00000000000000""" =========== Performance =========== Placeholder for Improving Performance documentation. """ from __future__ import division, absolute_import, print_function numpy-1.8.2/numpy/doc/broadcasting.py0000664000175100017510000001271012370216243020754 0ustar vagrantvagrant00000000000000""" ======================== Broadcasting over arrays ======================== The term broadcasting describes how numpy treats arrays with different shapes during arithmetic operations. Subject to certain constraints, the smaller array is "broadcast" across the larger array so that they have compatible shapes. Broadcasting provides a means of vectorizing array operations so that looping occurs in C instead of Python. It does this without making needless copies of data and usually leads to efficient algorithm implementations. There are, however, cases where broadcasting is a bad idea because it leads to inefficient use of memory that slows computation. NumPy operations are usually done on pairs of arrays on an element-by-element basis. In the simplest case, the two arrays must have exactly the same shape, as in the following example: >>> a = np.array([1.0, 2.0, 3.0]) >>> b = np.array([2.0, 2.0, 2.0]) >>> a * b array([ 2., 4., 6.]) NumPy's broadcasting rule relaxes this constraint when the arrays' shapes meet certain constraints. The simplest broadcasting example occurs when an array and a scalar value are combined in an operation: >>> a = np.array([1.0, 2.0, 3.0]) >>> b = 2.0 >>> a * b array([ 2., 4., 6.]) The result is equivalent to the previous example where ``b`` was an array. We can think of the scalar ``b`` being *stretched* during the arithmetic operation into an array with the same shape as ``a``. The new elements in ``b`` are simply copies of the original scalar. The stretching analogy is only conceptual. NumPy is smart enough to use the original scalar value without actually making copies, so that broadcasting operations are as memory and computationally efficient as possible. The code in the second example is more efficient than that in the first because broadcasting moves less memory around during the multiplication (``b`` is a scalar rather than an array). General Broadcasting Rules ========================== When operating on two arrays, NumPy compares their shapes element-wise. It starts with the trailing dimensions, and works its way forward. Two dimensions are compatible when 1) they are equal, or 2) one of them is 1 If these conditions are not met, a ``ValueError: frames are not aligned`` exception is thrown, indicating that the arrays have incompatible shapes. The size of the resulting array is the maximum size along each dimension of the input arrays. Arrays do not need to have the same *number* of dimensions. For example, if you have a ``256x256x3`` array of RGB values, and you want to scale each color in the image by a different value, you can multiply the image by a one-dimensional array with 3 values. Lining up the sizes of the trailing axes of these arrays according to the broadcast rules, shows that they are compatible:: Image (3d array): 256 x 256 x 3 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" to match the other. In the following example, both the ``A`` and ``B`` arrays have axes with length one that are expanded to a larger size during the broadcast operation:: A (4d array): 8 x 1 x 6 x 1 B (3d array): 7 x 1 x 5 Result (4d array): 8 x 7 x 6 x 5 Here are some more examples:: A (2d array): 5 x 4 B (1d array): 1 Result (2d array): 5 x 4 A (2d array): 5 x 4 B (1d array): 4 Result (2d array): 5 x 4 A (3d array): 15 x 3 x 5 B (3d array): 15 x 1 x 5 Result (3d array): 15 x 3 x 5 A (3d array): 15 x 3 x 5 B (2d array): 3 x 5 Result (3d array): 15 x 3 x 5 A (3d array): 15 x 3 x 5 B (2d array): 3 x 1 Result (3d array): 15 x 3 x 5 Here are examples of shapes that do not broadcast:: A (1d array): 3 B (1d array): 4 # trailing dimensions do not match A (2d array): 2 x 1 B (3d array): 8 x 4 x 3 # second from last dimensions mismatched An example of broadcasting in practice:: >>> x = np.arange(4) >>> xx = x.reshape(4,1) >>> y = np.ones(5) >>> z = np.ones((3,4)) >>> x.shape (4,) >>> y.shape (5,) >>> x + y : shape mismatch: objects cannot be broadcast to a single shape >>> xx.shape (4, 1) >>> y.shape (5,) >>> (xx + y).shape (4, 5) >>> xx + y array([[ 1., 1., 1., 1., 1.], [ 2., 2., 2., 2., 2.], [ 3., 3., 3., 3., 3.], [ 4., 4., 4., 4., 4.]]) >>> x.shape (4,) >>> z.shape (3, 4) >>> (x + z).shape (3, 4) >>> x + z array([[ 1., 2., 3., 4.], [ 1., 2., 3., 4.], [ 1., 2., 3., 4.]]) Broadcasting provides a convenient way of taking the outer product (or any other outer operation) of two arrays. The following example shows an outer addition operation of two 1-d arrays:: >>> a = np.array([0.0, 10.0, 20.0, 30.0]) >>> b = np.array([1.0, 2.0, 3.0]) >>> a[:, np.newaxis] + b array([[ 1., 2., 3.], [ 11., 12., 13.], [ 21., 22., 23.], [ 31., 32., 33.]]) 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 `_ for illustrations of broadcasting concepts. """ from __future__ import division, absolute_import, print_function numpy-1.8.2/numpy/_import_tools.py0000664000175100017510000003141212370216243020440 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function import os import sys __all__ = ['PackageLoader'] class PackageLoader(object): def __init__(self, verbose=False, infunc=False): """ Manages loading packages. """ if infunc: _level = 2 else: _level = 1 self.parent_frame = frame = sys._getframe(_level) self.parent_name = eval('__name__', frame.f_globals, frame.f_locals) parent_path = eval('__path__', frame.f_globals, frame.f_locals) if isinstance(parent_path, str): parent_path = [parent_path] self.parent_path = parent_path if '__all__' not in frame.f_locals: exec('__all__ = []', frame.f_globals, frame.f_locals) self.parent_export_names = eval('__all__', frame.f_globals, frame.f_locals) self.info_modules = {} self.imported_packages = [] self.verbose = None def _get_info_files(self, package_dir, parent_path, parent_package=None): """ Return list of (package name,info.py file) from parent_path subdirectories. """ from glob import glob files = glob(os.path.join(parent_path, package_dir, 'info.py')) for info_file in glob(os.path.join(parent_path, package_dir, 'info.pyc')): if info_file[:-1] not in files: files.append(info_file) info_files = [] for info_file in files: package_name = os.path.dirname(info_file[len(parent_path)+1:])\ .replace(os.sep, '.') if parent_package: package_name = parent_package + '.' + package_name info_files.append((package_name, info_file)) info_files.extend(self._get_info_files('*', os.path.dirname(info_file), package_name)) return info_files def _init_info_modules(self, packages=None): """Initialize info_modules = {: }. """ import imp info_files = [] info_modules = self.info_modules if packages is None: for path in self.parent_path: info_files.extend(self._get_info_files('*', path)) else: for package_name in packages: package_dir = os.path.join(*package_name.split('.')) for path in self.parent_path: names_files = self._get_info_files(package_dir, path) if names_files: info_files.extend(names_files) break else: try: exec('import %s.info as info' % (package_name)) info_modules[package_name] = info except ImportError as msg: self.warn('No scipy-style subpackage %r found in %s. '\ 'Ignoring: %s'\ % (package_name, ':'.join(self.parent_path), msg)) for package_name, info_file in info_files: if package_name in info_modules: continue fullname = self.parent_name +'.'+ package_name if info_file[-1]=='c': filedescriptor = ('.pyc', 'rb', 2) else: filedescriptor = ('.py', 'U', 1) try: info_module = imp.load_module(fullname+'.info', open(info_file, filedescriptor[1]), info_file, filedescriptor) except Exception as msg: self.error(msg) info_module = None if info_module is None or getattr(info_module, 'ignore', False): info_modules.pop(package_name, None) else: self._init_info_modules(getattr(info_module, 'depends', [])) info_modules[package_name] = info_module return def _get_sorted_names(self): """ Return package names sorted in the order as they should be imported due to dependence relations between packages. """ depend_dict = {} for name, info_module in self.info_modules.items(): depend_dict[name] = getattr(info_module, 'depends', []) package_names = [] for name in 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(): new_lst = [n for n in lst if n in depend_dict] if not new_lst: package_names.append(name) del depend_dict[name] else: depend_dict[name] = new_lst return package_names def __call__(self,*packages, **options): """Load one or more packages into parent package top-level namespace. This function is intended to shorten the need to import many subpackages, say of scipy, constantly with statements such as import scipy.linalg, scipy.fftpack, scipy.etc... Instead, you can say: import scipy scipy.pkgload('linalg','fftpack',...) or scipy.pkgload() to load all of them in one call. If a name which doesn't exist in scipy's namespace is given, a warning is shown. Parameters ---------- *packages : arg-tuple the names (one or more strings) of all the modules one wishes to load into the top-level namespace. verbose= : integer verbosity level [default: -1]. verbose=-1 will suspend also warnings. force= : bool when True, force reloading loaded packages [default: False]. postpone= : bool when True, don't load packages [default: False] """ frame = self.parent_frame self.info_modules = {} if options.get('force', False): self.imported_packages = [] self.verbose = verbose = options.get('verbose', -1) postpone = options.get('postpone', None) self._init_info_modules(packages or None) self.log('Imports to %r namespace\n----------------------------'\ % self.parent_name) for package_name in self._get_sorted_names(): if package_name in self.imported_packages: continue info_module = self.info_modules[package_name] global_symbols = getattr(info_module, 'global_symbols', []) postpone_import = getattr(info_module, 'postpone_import', False) if (postpone and not global_symbols) \ or (postpone_import and postpone is not None): continue old_object = frame.f_locals.get(package_name, None) cmdstr = 'import '+package_name if self._execcmd(cmdstr): continue self.imported_packages.append(package_name) if verbose!=-1: new_object = frame.f_locals.get(package_name) if old_object is not None and old_object is not new_object: self.warn('Overwriting %s=%s (was %s)' \ % (package_name, self._obj2repr(new_object), self._obj2repr(old_object))) if '.' not in package_name: self.parent_export_names.append(package_name) for symbol in global_symbols: if symbol=='*': symbols = eval('getattr(%s,"__all__",None)'\ % (package_name), frame.f_globals, frame.f_locals) if symbols is None: symbols = eval('dir(%s)' % (package_name), frame.f_globals, frame.f_locals) symbols = [s for s in symbols if not s.startswith('_')] else: symbols = [symbol] if verbose!=-1: old_objects = {} for s in symbols: if s in frame.f_locals: old_objects[s] = frame.f_locals[s] cmdstr = 'from '+package_name+' import '+symbol if self._execcmd(cmdstr): continue if verbose!=-1: for s, old_object in old_objects.items(): new_object = frame.f_locals[s] if new_object is not old_object: self.warn('Overwriting %s=%s (was %s)' \ % (s, self._obj2repr(new_object), self._obj2repr(old_object))) if symbol=='*': self.parent_export_names.extend(symbols) else: self.parent_export_names.append(symbol) return def _execcmd(self, cmdstr): """ Execute command in parent_frame.""" frame = self.parent_frame try: exec (cmdstr, frame.f_globals, frame.f_locals) except Exception as msg: self.error('%s -> failed: %s' % (cmdstr, msg)) return True else: self.log('%s -> success' % (cmdstr)) return def _obj2repr(self, obj): """ Return repr(obj) with""" module = getattr(obj, '__module__', None) file = getattr(obj, '__file__', None) if module is not None: return repr(obj) + ' from ' + module if file is not None: return repr(obj) + ' from ' + file return repr(obj) def log(self, mess): if self.verbose>1: print(str(mess), file=sys.stderr) def warn(self, mess): if self.verbose>=0: print(str(mess), file=sys.stderr) def error(self, mess): if self.verbose!=-1: print(str(mess), file=sys.stderr) def _get_doc_title(self, info_module): """ Get the title from a package info.py file. """ title = getattr(info_module, '__doc_title__', None) if title is not None: return title title = getattr(info_module, '__doc__', None) if title is not None: title = title.lstrip().split('\n', 1)[0] return title return '* Not Available *' def _format_titles(self,titles,colsep='---'): display_window_width = 70 # How to determine the correct value in runtime?? lengths = [len(name)-name.find('.')-1 for (name, title) in titles]+[0] max_length = max(lengths) lines = [] for (name, title) in titles: name = name[name.find('.')+1:] w = max_length - len(name) words = title.split() line = '%s%s %s' % (name, w*' ', colsep) tab = len(line) * ' ' while words: word = words.pop(0) if len(line)+len(word)>display_window_width: lines.append(line) line = tab line += ' ' + word else: lines.append(line) return '\n'.join(lines) def get_pkgdocs(self): """ Return documentation summary of subpackages. """ import sys self.info_modules = {} self._init_info_modules(None) titles = [] symbols = [] for package_name, info_module in self.info_modules.items(): global_symbols = getattr(info_module, 'global_symbols', []) fullname = self.parent_name +'.'+ package_name note = '' if fullname not in sys.modules: note = ' [*]' titles.append((fullname, self._get_doc_title(info_module) + note)) if global_symbols: symbols.append((package_name, ', '.join(global_symbols))) retstr = self._format_titles(titles) +\ '\n [*] - using a package requires explicit import (see pkgload)' if symbols: retstr += """\n\nGlobal symbols from subpackages"""\ """\n-------------------------------\n""" +\ self._format_titles(symbols, '-->') return retstr class PackageLoaderDebug(PackageLoader): def _execcmd(self, cmdstr): """ Execute command in parent_frame.""" frame = self.parent_frame print('Executing', repr(cmdstr), '...', end=' ') sys.stdout.flush() exec (cmdstr, frame.f_globals, frame.f_locals) print('ok') sys.stdout.flush() return if int(os.environ.get('NUMPY_IMPORT_DEBUG', '0')): PackageLoader = PackageLoaderDebug numpy-1.8.2/numpy/matlib.py0000664000175100017510000002254112370216242017021 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function import numpy as np from numpy.matrixlib.defmatrix import matrix, asmatrix # need * as we're copying the numpy namespace from numpy import * __version__ = np.__version__ __all__ = np.__all__[:] # copy numpy namespace __all__ += ['rand', 'randn', 'repmat'] def empty(shape, dtype=None, order='C'): """ Return a new matrix of given shape and type, without initializing entries. Parameters ---------- shape : int or tuple of int Shape of the empty matrix. dtype : data-type, optional Desired output data-type. order : {'C', 'F'}, optional Whether to store multi-dimensional data in C (row-major) or Fortran (column-major) order in memory. See Also -------- empty_like, zeros Notes ----- `empty`, unlike `zeros`, does not set the matrix values to zero, and may therefore be marginally faster. On the other hand, it requires the user to manually set all the values in the array, and should be used with caution. Examples -------- >>> import numpy.matlib >>> np.matlib.empty((2, 2)) # filled with random data matrix([[ 6.76425276e-320, 9.79033856e-307], [ 7.39337286e-309, 3.22135945e-309]]) #random >>> np.matlib.empty((2, 2), dtype=int) matrix([[ 6600475, 0], [ 6586976, 22740995]]) #random """ return ndarray.__new__(matrix, shape, dtype, order=order) def ones(shape, dtype=None, order='C'): """ Matrix of ones. Return a matrix of given shape and type, filled with ones. Parameters ---------- shape : {sequence of ints, int} Shape of the matrix dtype : data-type, optional The desired data-type for the matrix, default is np.float64. order : {'C', 'F'}, optional Whether to store matrix in C- or Fortran-contiguous order, default is 'C'. Returns ------- out : matrix Matrix of ones of given shape, dtype, and order. See Also -------- ones : Array of ones. matlib.zeros : Zero matrix. Notes ----- If `shape` has length one i.e. ``(N,)``, or is a scalar ``N``, `out` becomes a single row matrix of shape ``(1,N)``. Examples -------- >>> np.matlib.ones((2,3)) matrix([[ 1., 1., 1.], [ 1., 1., 1.]]) >>> np.matlib.ones(2) matrix([[ 1., 1.]]) """ a = ndarray.__new__(matrix, shape, dtype, order=order) a.fill(1) return a def zeros(shape, dtype=None, order='C'): """ Return a matrix of given shape and type, filled with zeros. Parameters ---------- shape : int or sequence of ints Shape of the matrix dtype : data-type, optional The desired data-type for the matrix, default is float. order : {'C', 'F'}, optional Whether to store the result in C- or Fortran-contiguous order, default is 'C'. Returns ------- out : matrix Zero matrix of given shape, dtype, and order. See Also -------- numpy.zeros : Equivalent array function. matlib.ones : Return a matrix of ones. Notes ----- If `shape` has length one i.e. ``(N,)``, or is a scalar ``N``, `out` becomes a single row matrix of shape ``(1,N)``. Examples -------- >>> import numpy.matlib >>> np.matlib.zeros((2, 3)) matrix([[ 0., 0., 0.], [ 0., 0., 0.]]) >>> np.matlib.zeros(2) matrix([[ 0., 0.]]) """ a = ndarray.__new__(matrix, shape, dtype, order=order) a.fill(0) return a def identity(n,dtype=None): """ Returns the square identity matrix of given size. Parameters ---------- n : int Size of the returned identity matrix. dtype : data-type, optional Data-type of the output. Defaults to ``float``. Returns ------- out : matrix `n` x `n` matrix with its main diagonal set to one, and all other elements zero. See Also -------- numpy.identity : Equivalent array function. matlib.eye : More general matrix identity function. Examples -------- >>> import numpy.matlib >>> np.matlib.identity(3, dtype=int) matrix([[1, 0, 0], [0, 1, 0], [0, 0, 1]]) """ a = array([1]+n*[0], dtype=dtype) b = empty((n, n), dtype=dtype) b.flat = a return b def eye(n,M=None, k=0, dtype=float): """ Return a matrix with ones on the diagonal and zeros elsewhere. Parameters ---------- n : int Number of rows in the output. M : int, optional Number of columns in the output, defaults to `n`. k : int, optional Index of the diagonal: 0 refers to the main diagonal, a positive value refers to an upper diagonal, and a negative value to a lower diagonal. dtype : dtype, optional Data-type of the returned matrix. Returns ------- I : matrix A `n` x `M` matrix where all elements are equal to zero, except for the `k`-th diagonal, whose values are equal to one. See Also -------- numpy.eye : Equivalent array function. identity : Square identity matrix. Examples -------- >>> import numpy.matlib >>> np.matlib.eye(3, k=1, dtype=float) matrix([[ 0., 1., 0.], [ 0., 0., 1.], [ 0., 0., 0.]]) """ return asmatrix(np.eye(n, M, k, dtype)) def rand(*args): """ Return a matrix of random values with given shape. Create a matrix of the given shape and propagate it with random samples from a uniform distribution over ``[0, 1)``. Parameters ---------- \\*args : Arguments Shape of the output. If given as N integers, each integer specifies the size of one dimension. If given as a tuple, this tuple gives the complete shape. Returns ------- out : ndarray The matrix of random values with shape given by `\\*args`. See Also -------- randn, numpy.random.rand Examples -------- >>> import numpy.matlib >>> np.matlib.rand(2, 3) matrix([[ 0.68340382, 0.67926887, 0.83271405], [ 0.00793551, 0.20468222, 0.95253525]]) #random >>> np.matlib.rand((2, 3)) matrix([[ 0.84682055, 0.73626594, 0.11308016], [ 0.85429008, 0.3294825 , 0.89139555]]) #random If the first argument is a tuple, other arguments are ignored: >>> np.matlib.rand((2, 3), 4) matrix([[ 0.46898646, 0.15163588, 0.95188261], [ 0.59208621, 0.09561818, 0.00583606]]) #random """ if isinstance(args[0], tuple): args = args[0] return asmatrix(np.random.rand(*args)) def randn(*args): """ Return a random matrix with data from the "standard normal" distribution. `randn` generates a matrix filled with random floats sampled from a univariate "normal" (Gaussian) distribution of mean 0 and variance 1. Parameters ---------- \\*args : Arguments Shape of the output. If given as N integers, each integer specifies the size of one dimension. If given as a tuple, this tuple gives the complete shape. Returns ------- Z : matrix of floats A matrix of floating-point samples drawn from the standard normal distribution. See Also -------- rand, random.randn Notes ----- For random samples from :math:`N(\\mu, \\sigma^2)`, use: ``sigma * np.matlib.randn(...) + mu`` Examples -------- >>> import numpy.matlib >>> np.matlib.randn(1) matrix([[-0.09542833]]) #random >>> np.matlib.randn(1, 2, 3) matrix([[ 0.16198284, 0.0194571 , 0.18312985], [-0.7509172 , 1.61055 , 0.45298599]]) #random Two-by-four matrix of samples from :math:`N(3, 6.25)`: >>> 2.5 * np.matlib.randn((2, 4)) + 3 matrix([[ 4.74085004, 8.89381862, 4.09042411, 4.83721922], [ 7.52373709, 5.07933944, -2.64043543, 0.45610557]]) #random """ if isinstance(args[0], tuple): args = args[0] return asmatrix(np.random.randn(*args)) def repmat(a, m, n): """ Repeat a 0-D to 2-D array or matrix MxN times. Parameters ---------- a : array_like The array or matrix to be repeated. m, n : int The number of times `a` is repeated along the first and second axes. Returns ------- out : ndarray The result of repeating `a`. Examples -------- >>> import numpy.matlib >>> a0 = np.array(1) >>> np.matlib.repmat(a0, 2, 3) array([[1, 1, 1], [1, 1, 1]]) >>> a1 = np.arange(4) >>> np.matlib.repmat(a1, 2, 2) array([[0, 1, 2, 3, 0, 1, 2, 3], [0, 1, 2, 3, 0, 1, 2, 3]]) >>> a2 = np.asmatrix(np.arange(6).reshape(2, 3)) >>> np.matlib.repmat(a2, 2, 3) matrix([[0, 1, 2, 0, 1, 2, 0, 1, 2], [3, 4, 5, 3, 4, 5, 3, 4, 5], [0, 1, 2, 0, 1, 2, 0, 1, 2], [3, 4, 5, 3, 4, 5, 3, 4, 5]]) """ a = asanyarray(a) ndim = a.ndim if ndim == 0: origrows, origcols = (1, 1) elif ndim == 1: origrows, origcols = (1, a.shape[0]) else: origrows, origcols = a.shape rows = origrows * m cols = origcols * n c = a.reshape(1, a.size).repeat(m, 0).reshape(rows, origcols).repeat(n, 0) return c.reshape(rows, cols) numpy-1.8.2/numpy/testing/0000775000175100017510000000000012371375430016656 5ustar vagrantvagrant00000000000000numpy-1.8.2/numpy/testing/print_coercion_tables.py0000775000175100017510000000520112370216242023572 0ustar vagrantvagrant00000000000000#!/usr/bin/env python """Prints type-coercion tables for the built-in NumPy types """ from __future__ import division, absolute_import, print_function import numpy as np # Generic object that can be added, but doesn't do anything else class GenericObject(object): def __init__(self, v): self.v = v def __add__(self, other): return self def __radd__(self, other): return self dtype = np.dtype('O') def print_cancast_table(ntypes): print('X', end=' ') for char in ntypes: print(char, end=' ') print() for row in ntypes: print(row, end=' ') for col in ntypes: print(int(np.can_cast(row, col)), end=' ') print() def print_coercion_table(ntypes, inputfirstvalue, inputsecondvalue, firstarray, use_promote_types=False): print('+', end=' ') for char in ntypes: print(char, end=' ') print() for row in ntypes: if row == 'O': rowtype = GenericObject else: rowtype = np.obj2sctype(row) print(row, end=' ') for col in ntypes: if col == 'O': coltype = GenericObject else: coltype = np.obj2sctype(col) try: if firstarray: rowvalue = np.array([rowtype(inputfirstvalue)], dtype=rowtype) else: rowvalue = rowtype(inputfirstvalue) colvalue = coltype(inputsecondvalue) if use_promote_types: char = np.promote_types(rowvalue.dtype, colvalue.dtype).char else: value = np.add(rowvalue, colvalue) if isinstance(value, np.ndarray): char = value.dtype.char else: char = np.dtype(type(value)).char except ValueError: char = '!' except OverflowError: char = '@' except TypeError: char = '#' print(char, end=' ') print() print("can cast") print_cancast_table(np.typecodes['All']) print() print("In these tables, ValueError is '!', OverflowError is '@', TypeError is '#'") print() print("scalar + scalar") print_coercion_table(np.typecodes['All'], 0, 0, False) print() print("scalar + neg scalar") print_coercion_table(np.typecodes['All'], 0, -1, False) print() print("array + scalar") print_coercion_table(np.typecodes['All'], 0, 0, True) print() print("array + neg scalar") print_coercion_table(np.typecodes['All'], 0, -1, True) print() print("promote_types") print_coercion_table(np.typecodes['All'], 0, 0, False, True) numpy-1.8.2/numpy/testing/decorators.py0000664000175100017510000002042012370216242021365 0ustar vagrantvagrant00000000000000""" Decorators for labeling and modifying behavior of test objects. Decorators that merely return a modified version of the original function object are straightforward. Decorators that return a new function object need to use :: nose.tools.make_decorator(original_function)(decorator) in returning the decorator, in order to preserve meta-data such as function name, setup and teardown functions and so on - see ``nose.tools`` for more information. """ from __future__ import division, absolute_import, print_function import warnings import collections def slow(t): """ Label a test as 'slow'. The exact definition of a slow test is obviously both subjective and hardware-dependent, but in general any individual test that requires more than a second or two should be labeled as slow (the whole suite consits of thousands of tests, so even a second is significant). Parameters ---------- t : callable The test to label as slow. Returns ------- t : callable The decorated test `t`. Examples -------- The `numpy.testing` module includes ``import decorators as dec``. A test can be decorated as slow like this:: from numpy.testing import * @dec.slow def test_big(self): print 'Big, slow test' """ t.slow = True return t def setastest(tf=True): """ Signals to nose that this function is or is not a test. Parameters ---------- tf : bool If True, specifies that the decorated callable is a test. If False, specifies that the decorated callable is not a test. Default is True. Notes ----- This decorator can't use the nose namespace, because it can be called from a non-test module. See also ``istest`` and ``nottest`` in ``nose.tools``. Examples -------- `setastest` can be used in the following way:: from numpy.testing.decorators import setastest @setastest(False) def func_with_test_in_name(arg1, arg2): pass """ def set_test(t): t.__test__ = tf return t return set_test def skipif(skip_condition, msg=None): """ Make function raise SkipTest exception if a given condition is true. If the condition is a callable, it is used at runtime to dynamically make the decision. This is useful for tests that may require costly imports, to delay the cost until the test suite is actually executed. Parameters ---------- skip_condition : bool or callable Flag to determine whether to skip the decorated test. msg : str, optional Message to give on raising a SkipTest exception. Default is None. Returns ------- decorator : function Decorator which, when applied to a function, causes SkipTest to be raised when `skip_condition` is True, and the function to be called normally otherwise. Notes ----- The decorator itself is decorated with the ``nose.tools.make_decorator`` function in order to transmit function name, and various other metadata. """ def skip_decorator(f): # Local import to avoid a hard nose dependency and only incur the # import time overhead at actual test-time. import nose # Allow for both boolean or callable skip conditions. if isinstance(skip_condition, collections.Callable): skip_val = lambda : skip_condition() else: skip_val = lambda : skip_condition def get_msg(func,msg=None): """Skip message with information about function being skipped.""" if msg is None: out = 'Test skipped due to test condition' else: out = msg return "Skipping test: %s: %s" % (func.__name__, out) # We need to define *two* skippers because Python doesn't allow both # return with value and yield inside the same function. def skipper_func(*args, **kwargs): """Skipper for normal test functions.""" if skip_val(): raise nose.SkipTest(get_msg(f, msg)) else: return f(*args, **kwargs) def skipper_gen(*args, **kwargs): """Skipper for test generators.""" if skip_val(): raise nose.SkipTest(get_msg(f, msg)) else: for x in f(*args, **kwargs): yield x # Choose the right skipper to use when building the actual decorator. if nose.util.isgenerator(f): skipper = skipper_gen else: skipper = skipper_func return nose.tools.make_decorator(f)(skipper) return skip_decorator def knownfailureif(fail_condition, msg=None): """ Make function raise KnownFailureTest exception if given condition is true. If the condition is a callable, it is used at runtime to dynamically make the decision. This is useful for tests that may require costly imports, to delay the cost until the test suite is actually executed. Parameters ---------- fail_condition : bool or callable Flag to determine whether to mark the decorated test as a known failure (if True) or not (if False). msg : str, optional Message to give on raising a KnownFailureTest exception. Default is None. Returns ------- decorator : function Decorator, which, when applied to a function, causes SkipTest to be raised when `skip_condition` is True, and the function to be called normally otherwise. Notes ----- The decorator itself is decorated with the ``nose.tools.make_decorator`` function in order to transmit function name, and various other metadata. """ if msg is None: msg = 'Test skipped due to known failure' # Allow for both boolean or callable known failure conditions. if isinstance(fail_condition, collections.Callable): fail_val = lambda : fail_condition() else: fail_val = lambda : fail_condition def knownfail_decorator(f): # Local import to avoid a hard nose dependency and only incur the # import time overhead at actual test-time. import nose from .noseclasses import KnownFailureTest def knownfailer(*args, **kwargs): if fail_val(): raise KnownFailureTest(msg) else: return f(*args, **kwargs) return nose.tools.make_decorator(f)(knownfailer) return knownfail_decorator def deprecated(conditional=True): """ Filter deprecation warnings while running the test suite. This decorator can be used to filter DeprecationWarning's, to avoid printing them during the test suite run, while checking that the test actually raises a DeprecationWarning. Parameters ---------- conditional : bool or callable, optional Flag to determine whether to mark test as deprecated or not. If the condition is a callable, it is used at runtime to dynamically make the decision. Default is True. Returns ------- decorator : function The `deprecated` decorator itself. Notes ----- .. versionadded:: 1.4.0 """ def deprecate_decorator(f): # Local import to avoid a hard nose dependency and only incur the # import time overhead at actual test-time. import nose from .noseclasses import KnownFailureTest def _deprecated_imp(*args, **kwargs): # Poor man's replacement for the with statement with warnings.catch_warnings(record=True) as l: warnings.simplefilter('always') f(*args, **kwargs) if not len(l) > 0: raise AssertionError("No warning raised when calling %s" % f.__name__) if not l[0].category is DeprecationWarning: raise AssertionError("First warning for %s is not a " \ "DeprecationWarning( is %s)" % (f.__name__, l[0])) if isinstance(conditional, collections.Callable): cond = conditional() else: cond = conditional if cond: return nose.tools.make_decorator(f)(_deprecated_imp) else: return f return deprecate_decorator numpy-1.8.2/numpy/testing/numpytest.py0000664000175100017510000000206412370216243021275 0ustar vagrantvagrant00000000000000from __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 numpy-1.8.2/numpy/testing/utils.py0000664000175100017510000015047712370216243020401 0ustar vagrantvagrant00000000000000""" Utility function to facilitate testing. """ from __future__ import division, absolute_import, print_function import os import sys import re import operator import warnings from .nosetester import import_nose from numpy.core import float32, empty, arange if sys.version_info[0] >= 3: from io import StringIO else: from StringIO import StringIO __all__ = ['assert_equal', 'assert_almost_equal', 'assert_approx_equal', 'assert_array_equal', 'assert_array_less', 'assert_string_equal', 'assert_array_almost_equal', 'assert_raises', 'build_err_msg', 'decorate_methods', 'jiffies', 'memusage', 'print_assert_equal', 'raises', 'rand', 'rundocs', 'runstring', 'verbose', 'measure', 'assert_', 'assert_array_almost_equal_nulp', 'assert_array_max_ulp', 'assert_warns', 'assert_no_warnings', 'assert_allclose', 'IgnoreException'] verbose = 0 def assert_(val, msg='') : """ Assert that works in release mode. The Python built-in ``assert`` does not work when executing code in optimized mode (the ``-O`` flag) - no byte-code is generated for it. For documentation on usage, refer to the Python documentation. """ if not val : raise AssertionError(msg) def gisnan(x): """like isnan, but always raise an error if type not supported instead of returning a TypeError object. Notes ----- isnan and other ufunc sometimes return a NotImplementedType object instead of raising any exception. This function is a wrapper to make sure an exception is always raised. This should be removed once this problem is solved at the Ufunc level.""" from numpy.core import isnan st = isnan(x) if isinstance(st, type(NotImplemented)): raise TypeError("isnan not supported for this type") return st def gisfinite(x): """like isfinite, but always raise an error if type not supported instead of returning a TypeError object. Notes ----- isfinite and other ufunc sometimes return a NotImplementedType object instead of raising any exception. This function is a wrapper to make sure an exception is always raised. This should be removed once this problem is solved at the Ufunc level.""" from numpy.core import isfinite, errstate with errstate(invalid='ignore'): st = isfinite(x) if isinstance(st, type(NotImplemented)): raise TypeError("isfinite not supported for this type") return st def gisinf(x): """like isinf, but always raise an error if type not supported instead of returning a TypeError object. Notes ----- isinf and other ufunc sometimes return a NotImplementedType object instead of raising any exception. This function is a wrapper to make sure an exception is always raised. This should be removed once this problem is solved at the Ufunc level.""" from numpy.core import isinf, errstate with errstate(invalid='ignore'): st = isinf(x) if isinstance(st, type(NotImplemented)): raise TypeError("isinf not supported for this type") return st def rand(*args): """Returns an array of random numbers with the given shape. This only uses the standard library, so it is useful for testing purposes. """ import random from numpy.core import zeros, float64 results = zeros(args, float64) f = results.flat for i in range(len(f)): f[i] = random.random() return results if sys.platform[:5]=='linux': def jiffies(_proc_pid_stat = '/proc/%s/stat'%(os.getpid()), _load_time=[]): """ Return number of jiffies (1/100ths of a second) that this process has been scheduled in user mode. See man 5 proc. """ import time if not _load_time: _load_time.append(time.time()) try: f=open(_proc_pid_stat, 'r') l = f.readline().split(' ') f.close() return int(l[13]) except: return int(100*(time.time()-_load_time[0])) def memusage(_proc_pid_stat = '/proc/%s/stat'%(os.getpid())): """ Return virtual memory size in bytes of the running python. """ try: f=open(_proc_pid_stat, 'r') l = f.readline().split(' ') f.close() return int(l[22]) except: return else: # os.getpid is not in all platforms available. # Using time is safe but inaccurate, especially when process # was suspended or sleeping. def jiffies(_load_time=[]): """ Return number of jiffies (1/100ths of a second) that this process has been scheduled in user mode. [Emulation with time.time]. """ import time if not _load_time: _load_time.append(time.time()) return int(100*(time.time()-_load_time[0])) def memusage(): """ Return memory usage of running python. [Not implemented]""" raise NotImplementedError if os.name=='nt' and sys.version[:3] > '2.3': # Code "stolen" from enthought/debug/memusage.py def GetPerformanceAttributes(object, counter, instance = None, inum=-1, format = None, machine=None): # NOTE: Many counters require 2 samples to give accurate results, # including "% Processor Time" (as by definition, at any instant, a # thread's CPU usage is either 0 or 100). To read counters like this, # you should copy this function, but keep the counter open, and call # CollectQueryData() each time you need to know. # See http://msdn.microsoft.com/library/en-us/dnperfmo/html/perfmonpt2.asp # My older explanation for this was that the "AddCounter" process forced # the CPU to 100%, but the above makes more sense :) import win32pdh if format is None: format = win32pdh.PDH_FMT_LONG path = win32pdh.MakeCounterPath( (machine, object, instance, None, inum, counter) ) hq = win32pdh.OpenQuery() try: hc = win32pdh.AddCounter(hq, path) try: win32pdh.CollectQueryData(hq) type, val = win32pdh.GetFormattedCounterValue(hc, format) return val finally: win32pdh.RemoveCounter(hc) finally: win32pdh.CloseQuery(hq) def memusage(processName="python", instance=0): # from win32pdhutil, part of the win32all package import win32pdh return GetPerformanceAttributes("Process", "Virtual Bytes", processName, instance, win32pdh.PDH_FMT_LONG, None) def build_err_msg(arrays, err_msg, header='Items are not equal:', verbose=True, names=('ACTUAL', 'DESIRED')): msg = ['\n' + header] if err_msg: if err_msg.find('\n') == -1 and len(err_msg) < 79-len(header): msg = [msg[0] + ' ' + err_msg] else: msg.append(err_msg) if verbose: for i, a in enumerate(arrays): try: r = repr(a) except: r = '[repr failed]' if r.count('\n') > 3: r = '\n'.join(r.splitlines()[:3]) r += '...' msg.append(' %s: %s' % (names[i], r)) return '\n'.join(msg) def assert_equal(actual,desired,err_msg='',verbose=True): """ Raise an assertion if two objects are not equal. Given two objects (scalars, lists, tuples, dictionaries or numpy arrays), check that all elements of these objects are equal. An exception is raised at the first conflicting values. Parameters ---------- actual : array_like The object to check. desired : array_like The expected object. err_msg : str, optional The error message to be printed in case of failure. verbose : bool, optional If True, the conflicting values are appended to the error message. Raises ------ AssertionError If actual and desired are not equal. Examples -------- >>> np.testing.assert_equal([4,5], [4,6]) ... : Items are not equal: item=1 ACTUAL: 5 DESIRED: 6 """ if isinstance(desired, dict): if not isinstance(actual, dict) : raise AssertionError(repr(type(actual))) assert_equal(len(actual), len(desired), err_msg, verbose) for k, i in desired.items(): if k not in actual : raise AssertionError(repr(k)) assert_equal(actual[k], desired[k], 'key=%r\n%s' % (k, err_msg), verbose) return if isinstance(desired, (list, tuple)) and isinstance(actual, (list, tuple)): assert_equal(len(actual), len(desired), err_msg, verbose) for k in range(len(desired)): assert_equal(actual[k], desired[k], 'item=%r\n%s' % (k, err_msg), verbose) return from numpy.core import ndarray, isscalar, signbit from numpy.lib import iscomplexobj, real, imag if isinstance(actual, ndarray) or isinstance(desired, ndarray): return assert_array_equal(actual, desired, err_msg, verbose) msg = build_err_msg([actual, desired], err_msg, verbose=verbose) # Handle complex numbers: separate into real/imag to handle # nan/inf/negative zero correctly # XXX: catch ValueError for subclasses of ndarray where iscomplex fail try: usecomplex = iscomplexobj(actual) or iscomplexobj(desired) except ValueError: usecomplex = False if usecomplex: if iscomplexobj(actual): actualr = real(actual) actuali = imag(actual) else: actualr = actual actuali = 0 if iscomplexobj(desired): desiredr = real(desired) desiredi = imag(desired) else: desiredr = desired desiredi = 0 try: assert_equal(actualr, desiredr) assert_equal(actuali, desiredi) except AssertionError: raise AssertionError(msg) # Inf/nan/negative zero handling try: # isscalar test to check cases such as [np.nan] != np.nan if isscalar(desired) != isscalar(actual): raise AssertionError(msg) # If one of desired/actual is not finite, handle it specially here: # check that both are nan if any is a nan, and test for equality # otherwise if not (gisfinite(desired) and gisfinite(actual)): isdesnan = gisnan(desired) isactnan = gisnan(actual) if isdesnan or isactnan: if not (isdesnan and isactnan): raise AssertionError(msg) else: if not desired == actual: raise AssertionError(msg) return elif desired == 0 and actual == 0: if not signbit(desired) == signbit(actual): raise AssertionError(msg) # If TypeError or ValueError raised while using isnan and co, just handle # as before except (TypeError, ValueError, NotImplementedError): pass if desired != actual : raise AssertionError(msg) def print_assert_equal(test_string, actual, desired): """ Test if two objects are equal, and print an error message if test fails. The test is performed with ``actual == desired``. Parameters ---------- test_string : str The message supplied to AssertionError. actual : object The object to test for equality against `desired`. desired : object The expected result. Examples -------- >>> np.testing.print_assert_equal('Test XYZ of func xyz', [0, 1], [0, 1]) >>> np.testing.print_assert_equal('Test XYZ of func xyz', [0, 1], [0, 2]) Traceback (most recent call last): ... AssertionError: Test XYZ of func xyz failed ACTUAL: [0, 1] DESIRED: [0, 2] """ import pprint if not (actual == desired): msg = StringIO() msg.write(test_string) msg.write(' failed\nACTUAL: \n') pprint.pprint(actual, msg) msg.write('DESIRED: \n') pprint.pprint(desired, msg) raise AssertionError(msg.getvalue()) def assert_almost_equal(actual,desired,decimal=7,err_msg='',verbose=True): """ Raise an assertion if two items are not equal up to desired precision. .. note:: It is recommended to use one of `assert_allclose`, `assert_array_almost_equal_nulp` or `assert_array_max_ulp` instead of this function for more consistent floating point comparisons. The test is equivalent to ``abs(desired-actual) < 0.5 * 10**(-decimal)``. Given two objects (numbers or ndarrays), check that all elements of these objects are almost equal. An exception is raised at conflicting values. For ndarrays this delegates to assert_array_almost_equal Parameters ---------- actual : array_like The object to check. desired : array_like The expected object. decimal : int, optional Desired precision, default is 7. err_msg : str, optional The error message to be printed in case of failure. verbose : bool, optional If True, the conflicting values are appended to the error message. Raises ------ AssertionError If actual and desired are not equal up to specified precision. See Also -------- assert_allclose: Compare two array_like objects for equality with desired relative and/or absolute precision. assert_array_almost_equal_nulp, assert_array_max_ulp, assert_equal Examples -------- >>> import numpy.testing as npt >>> npt.assert_almost_equal(2.3333333333333, 2.33333334) >>> npt.assert_almost_equal(2.3333333333333, 2.33333334, decimal=10) ... : Items are not equal: ACTUAL: 2.3333333333333002 DESIRED: 2.3333333399999998 >>> npt.assert_almost_equal(np.array([1.0,2.3333333333333]), ... np.array([1.0,2.33333334]), decimal=9) ... : Arrays are not almost equal (mismatch 50.0%) x: array([ 1. , 2.33333333]) y: array([ 1. , 2.33333334]) """ from numpy.core import ndarray from numpy.lib import iscomplexobj, real, imag # Handle complex numbers: separate into real/imag to handle # nan/inf/negative zero correctly # XXX: catch ValueError for subclasses of ndarray where iscomplex fail try: usecomplex = iscomplexobj(actual) or iscomplexobj(desired) except ValueError: usecomplex = False msg = build_err_msg([actual, desired], err_msg, verbose=verbose, header=('Arrays are not almost equal to %d decimals' % decimal)) if usecomplex: if iscomplexobj(actual): actualr = real(actual) actuali = imag(actual) else: actualr = actual actuali = 0 if iscomplexobj(desired): desiredr = real(desired) desiredi = imag(desired) else: desiredr = desired desiredi = 0 try: assert_almost_equal(actualr, desiredr, decimal=decimal) assert_almost_equal(actuali, desiredi, decimal=decimal) except AssertionError: raise AssertionError(msg) if isinstance(actual, (ndarray, tuple, list)) \ or isinstance(desired, (ndarray, tuple, list)): return assert_array_almost_equal(actual, desired, decimal, err_msg) try: # If one of desired/actual is not finite, handle it specially here: # check that both are nan if any is a nan, and test for equality # otherwise if not (gisfinite(desired) and gisfinite(actual)): if gisnan(desired) or gisnan(actual): if not (gisnan(desired) and gisnan(actual)): raise AssertionError(msg) else: if not desired == actual: raise AssertionError(msg) return except (NotImplementedError, TypeError): pass if round(abs(desired - actual), decimal) != 0 : raise AssertionError(msg) def assert_approx_equal(actual,desired,significant=7,err_msg='',verbose=True): """ Raise an assertion if two items are not equal up to significant digits. .. note:: It is recommended to use one of `assert_allclose`, `assert_array_almost_equal_nulp` or `assert_array_max_ulp` instead of this function for more consistent floating point comparisons. Given two numbers, check that they are approximately equal. Approximately equal is defined as the number of significant digits that agree. Parameters ---------- actual : scalar The object to check. desired : scalar The expected object. significant : int, optional Desired precision, default is 7. err_msg : str, optional The error message to be printed in case of failure. verbose : bool, optional If True, the conflicting values are appended to the error message. Raises ------ AssertionError If actual and desired are not equal up to specified precision. See Also -------- assert_allclose: Compare two array_like objects for equality with desired relative and/or absolute precision. assert_array_almost_equal_nulp, assert_array_max_ulp, assert_equal Examples -------- >>> np.testing.assert_approx_equal(0.12345677777777e-20, 0.1234567e-20) >>> np.testing.assert_approx_equal(0.12345670e-20, 0.12345671e-20, significant=8) >>> np.testing.assert_approx_equal(0.12345670e-20, 0.12345672e-20, significant=8) ... : Items are not equal to 8 significant digits: ACTUAL: 1.234567e-021 DESIRED: 1.2345672000000001e-021 the evaluated condition that raises the exception is >>> abs(0.12345670e-20/1e-21 - 0.12345672e-20/1e-21) >= 10**-(8-1) True """ import numpy as np (actual, desired) = map(float, (actual, desired)) if desired==actual: return # Normalized the numbers to be in range (-10.0,10.0) # scale = float(pow(10,math.floor(math.log10(0.5*(abs(desired)+abs(actual)))))) with np.errstate(invalid='ignore'): scale = 0.5*(np.abs(desired) + np.abs(actual)) scale = np.power(10, np.floor(np.log10(scale))) try: sc_desired = desired/scale except ZeroDivisionError: sc_desired = 0.0 try: sc_actual = actual/scale except ZeroDivisionError: sc_actual = 0.0 msg = build_err_msg([actual, desired], err_msg, header='Items are not equal to %d significant digits:' % significant, verbose=verbose) try: # If one of desired/actual is not finite, handle it specially here: # check that both are nan if any is a nan, and test for equality # otherwise if not (gisfinite(desired) and gisfinite(actual)): if gisnan(desired) or gisnan(actual): if not (gisnan(desired) and gisnan(actual)): raise AssertionError(msg) else: if not desired == actual: raise AssertionError(msg) return except (TypeError, NotImplementedError): pass if np.abs(sc_desired - sc_actual) >= np.power(10., -(significant-1)) : raise AssertionError(msg) def assert_array_compare(comparison, x, y, err_msg='', verbose=True, header=''): from numpy.core import array, isnan, isinf, any, all, inf x = array(x, copy=False, subok=True) y = array(y, copy=False, subok=True) def isnumber(x): return x.dtype.char in '?bhilqpBHILQPefdgFDG' def chk_same_position(x_id, y_id, hasval='nan'): """Handling nan/inf: check that x and y have the nan/inf at the same locations.""" try: assert_array_equal(x_id, y_id) except AssertionError: msg = build_err_msg([x, y], err_msg + '\nx and y %s location mismatch:' \ % (hasval), verbose=verbose, header=header, names=('x', 'y')) raise AssertionError(msg) try: cond = (x.shape==() or y.shape==()) or x.shape == y.shape if not cond: msg = build_err_msg([x, y], err_msg + '\n(shapes %s, %s mismatch)' % (x.shape, y.shape), verbose=verbose, header=header, names=('x', 'y')) if not cond : raise AssertionError(msg) if isnumber(x) and isnumber(y): x_isnan, y_isnan = isnan(x), isnan(y) x_isinf, y_isinf = isinf(x), isinf(y) # Validate that the special values are in the same place if any(x_isnan) or any(y_isnan): chk_same_position(x_isnan, y_isnan, hasval='nan') if any(x_isinf) or any(y_isinf): # Check +inf and -inf separately, since they are different chk_same_position(x == +inf, y == +inf, hasval='+inf') chk_same_position(x == -inf, y == -inf, hasval='-inf') # Combine all the special values x_id, y_id = x_isnan, y_isnan x_id |= x_isinf y_id |= y_isinf # Only do the comparison if actual values are left if all(x_id): return if any(x_id): val = comparison(x[~x_id], y[~y_id]) else: val = comparison(x, y) else: val = comparison(x, y) if isinstance(val, bool): cond = val reduced = [0] else: reduced = val.ravel() cond = reduced.all() reduced = reduced.tolist() if not cond: match = 100-100.0*reduced.count(1)/len(reduced) msg = build_err_msg([x, y], err_msg + '\n(mismatch %s%%)' % (match,), verbose=verbose, header=header, names=('x', 'y')) if not cond : raise AssertionError(msg) except ValueError as e: import traceback efmt = traceback.format_exc() 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')) raise ValueError(msg) def assert_array_equal(x, y, err_msg='', verbose=True): """ Raise an assertion if two array_like objects are not equal. Given two array_like objects, check that the shape is equal and all elements of these objects are equal. An exception is raised at shape mismatch or conflicting values. In contrast to the standard usage in numpy, NaNs are compared like numbers, no assertion is raised if both objects have NaNs in the same positions. The usual caution for verifying equality with floating point numbers is advised. Parameters ---------- x : array_like The actual object to check. y : array_like The desired, expected object. err_msg : str, optional The error message to be printed in case of failure. verbose : bool, optional If True, the conflicting values are appended to the error message. Raises ------ AssertionError If actual and desired objects are not equal. See Also -------- assert_allclose: Compare two array_like objects for equality with desired relative and/or absolute precision. assert_array_almost_equal_nulp, assert_array_max_ulp, assert_equal Examples -------- The first assert does not raise an exception: >>> np.testing.assert_array_equal([1.0,2.33333,np.nan], ... [np.exp(0),2.33333, np.nan]) Assert fails with numerical inprecision with floats: >>> np.testing.assert_array_equal([1.0,np.pi,np.nan], ... [1, np.sqrt(np.pi)**2, np.nan]) ... : AssertionError: Arrays are not equal (mismatch 50.0%) x: array([ 1. , 3.14159265, NaN]) y: array([ 1. , 3.14159265, NaN]) Use `assert_allclose` or one of the nulp (number of floating point values) functions for these cases instead: >>> np.testing.assert_allclose([1.0,np.pi,np.nan], ... [1, np.sqrt(np.pi)**2, np.nan], ... rtol=1e-10, atol=0) """ assert_array_compare(operator.__eq__, x, y, err_msg=err_msg, verbose=verbose, header='Arrays are not equal') def assert_array_almost_equal(x, y, decimal=6, err_msg='', verbose=True): """ Raise an assertion if two objects are not equal up to desired precision. .. note:: It is recommended to use one of `assert_allclose`, `assert_array_almost_equal_nulp` or `assert_array_max_ulp` instead of this function for more consistent floating point comparisons. The test verifies identical shapes and verifies values with ``abs(desired-actual) < 0.5 * 10**(-decimal)``. Given two array_like objects, check that the shape is equal and all elements of these objects are almost equal. An exception is raised at shape mismatch or conflicting values. In contrast to the standard usage in numpy, NaNs are compared like numbers, no assertion is raised if both objects have NaNs in the same positions. Parameters ---------- x : array_like The actual object to check. y : array_like The desired, expected object. decimal : int, optional Desired precision, default is 6. err_msg : str, optional The error message to be printed in case of failure. verbose : bool, optional If True, the conflicting values are appended to the error message. Raises ------ AssertionError If actual and desired are not equal up to specified precision. See Also -------- assert_allclose: Compare two array_like objects for equality with desired relative and/or absolute precision. assert_array_almost_equal_nulp, assert_array_max_ulp, assert_equal Examples -------- the first assert does not raise an exception >>> np.testing.assert_array_almost_equal([1.0,2.333,np.nan], [1.0,2.333,np.nan]) >>> np.testing.assert_array_almost_equal([1.0,2.33333,np.nan], ... [1.0,2.33339,np.nan], decimal=5) ... : AssertionError: Arrays are not almost equal (mismatch 50.0%) x: array([ 1. , 2.33333, NaN]) y: array([ 1. , 2.33339, NaN]) >>> np.testing.assert_array_almost_equal([1.0,2.33333,np.nan], ... [1.0,2.33333, 5], decimal=5) : ValueError: Arrays are not almost equal x: array([ 1. , 2.33333, NaN]) y: array([ 1. , 2.33333, 5. ]) """ from numpy.core import around, number, float_ from numpy.core.numerictypes import issubdtype from numpy.core.fromnumeric import any as npany def compare(x, y): try: if npany(gisinf(x)) or npany( gisinf(y)): xinfid = gisinf(x) yinfid = gisinf(y) if not xinfid == yinfid: return False # if one item, x and y is +- inf if x.size == y.size == 1: return x == y x = x[~xinfid] y = y[~yinfid] except (TypeError, NotImplementedError): pass 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)) def assert_array_less(x, y, err_msg='', verbose=True): """ Raise an assertion if two array_like objects are not ordered by less than. Given two array_like objects, check that the shape is equal and all elements of the first object are strictly smaller than those of the second object. An exception is raised at shape mismatch or incorrectly ordered values. Shape mismatch does not raise if an object has zero dimension. In contrast to the standard usage in numpy, NaNs are compared, no assertion is raised if both objects have NaNs in the same positions. Parameters ---------- x : array_like The smaller object to check. y : array_like The larger object to compare. err_msg : string The error message to be printed in case of failure. verbose : bool If True, the conflicting values are appended to the error message. Raises ------ AssertionError If actual and desired objects are not equal. See Also -------- assert_array_equal: tests objects for equality assert_array_almost_equal: test objects for equality up to precision Examples -------- >>> np.testing.assert_array_less([1.0, 1.0, np.nan], [1.1, 2.0, np.nan]) >>> np.testing.assert_array_less([1.0, 1.0, np.nan], [1, 2.0, np.nan]) ... : Arrays are not less-ordered (mismatch 50.0%) x: array([ 1., 1., NaN]) y: array([ 1., 2., NaN]) >>> np.testing.assert_array_less([1.0, 4.0], 3) ... : Arrays are not less-ordered (mismatch 50.0%) x: array([ 1., 4.]) y: array(3) >>> np.testing.assert_array_less([1.0, 2.0, 3.0], [4]) ... : Arrays are not less-ordered (shapes (3,), (1,) mismatch) x: array([ 1., 2., 3.]) y: array([4]) """ assert_array_compare(operator.__lt__, x, y, err_msg=err_msg, verbose=verbose, header='Arrays are not less-ordered') def runstring(astr, dict): exec(astr, dict) def assert_string_equal(actual, desired): """ Test if two strings are equal. If the given strings are equal, `assert_string_equal` does nothing. If they are not equal, an AssertionError is raised, and the diff between the strings is shown. Parameters ---------- actual : str The string to test for equality against the expected string. desired : str The expected string. Examples -------- >>> np.testing.assert_string_equal('abc', 'abc') >>> np.testing.assert_string_equal('abc', 'abcd') Traceback (most recent call last): File "", line 1, in ... AssertionError: Differences in strings: - abc+ abcd? + """ # delay import of difflib to reduce startup time import difflib if not isinstance(actual, str) : raise AssertionError(repr(type(actual))) if not isinstance(desired, str): raise AssertionError(repr(type(desired))) if re.match(r'\A'+desired+r'\Z', actual, re.M): return diff = list(difflib.Differ().compare(actual.splitlines(1), desired.splitlines(1))) diff_list = [] while diff: d1 = diff.pop(0) if d1.startswith(' '): continue if d1.startswith('- '): l = [d1] d2 = diff.pop(0) if d2.startswith('? '): l.append(d2) d2 = diff.pop(0) if not d2.startswith('+ ') : raise AssertionError(repr(d2)) l.append(d2) d3 = diff.pop(0) if d3.startswith('? '): l.append(d3) else: diff.insert(0, d3) if re.match(r'\A'+d2[2:]+r'\Z', d1[2:]): continue diff_list.extend(l) continue raise AssertionError(repr(d1)) if not diff_list: return msg = 'Differences in strings:\n%s' % (''.join(diff_list)).rstrip() if actual != desired : raise AssertionError(msg) def rundocs(filename=None, raise_on_error=True): """ Run doctests found in the given file. By default `rundocs` raises an AssertionError on failure. Parameters ---------- filename : str The path to the file for which the doctests are run. raise_on_error : bool Whether to raise an AssertionError when a doctest fails. Default is True. Notes ----- The doctests can be run by the user/developer by adding the ``doctests`` argument to the ``test()`` call. For example, to run all tests (including doctests) for `numpy.lib`: >>> np.lib.test(doctests=True) #doctest: +SKIP """ import doctest, imp if filename is None: f = sys._getframe(1) filename = f.f_globals['__file__'] name = os.path.splitext(os.path.basename(filename))[0] path = [os.path.dirname(filename)] file, pathname, description = imp.find_module(name, path) try: m = imp.load_module(name, file, pathname, description) finally: file.close() tests = doctest.DocTestFinder().find(m) runner = doctest.DocTestRunner(verbose=False) msg = [] if raise_on_error: out = lambda s: msg.append(s) else: out = None for test in tests: runner.run(test, out=out) if runner.failures > 0 and raise_on_error: raise AssertionError("Some doctests failed:\n%s" % "\n".join(msg)) def raises(*args,**kwargs): nose = import_nose() return nose.tools.raises(*args,**kwargs) def assert_raises(*args,**kwargs): """ assert_raises(exception_class, callable, *args, **kwargs) Fail unless an exception of class exception_class is thrown by callable when invoked with arguments args and keyword arguments kwargs. If a different type of exception is thrown, it will not be caught, and the test case will be deemed to have suffered an error, exactly as for an unexpected exception. """ nose = import_nose() return nose.tools.assert_raises(*args,**kwargs) def decorate_methods(cls, decorator, testmatch=None): """ Apply a decorator to all methods in a class matching a regular expression. The given decorator is applied to all public methods of `cls` that are matched by the regular expression `testmatch` (``testmatch.search(methodname)``). Methods that are private, i.e. start with an underscore, are ignored. Parameters ---------- cls : class Class whose methods to decorate. decorator : function Decorator to apply to methods testmatch : compiled regexp or str, optional The regular expression. Default value is None, in which case the nose default (``re.compile(r'(?:^|[\\b_\\.%s-])[Tt]est' % os.sep)``) is used. If `testmatch` is a string, it is compiled to a regular expression first. """ if testmatch is None: testmatch = re.compile(r'(?:^|[\\b_\\.%s-])[Tt]est' % os.sep) else: testmatch = re.compile(testmatch) cls_attr = cls.__dict__ # delayed import to reduce startup time from inspect import isfunction methods = [_m for _m in cls_attr.values() if isfunction(_m)] for function in methods: try: if hasattr(function, 'compat_func_name'): funcname = function.compat_func_name else: funcname = function.__name__ except AttributeError: # not a function continue if testmatch.search(funcname) and not funcname.startswith('_'): setattr(cls, funcname, decorator(function)) return def measure(code_str,times=1,label=None): """ Return elapsed time for executing code in the namespace of the caller. The supplied code string is compiled with the Python builtin ``compile``. The precision of the timing is 10 milli-seconds. If the code will execute fast on this timescale, it can be executed many times to get reasonable timing accuracy. Parameters ---------- code_str : str The code to be timed. times : int, optional The number of times the code is executed. Default is 1. The code is only compiled once. label : str, optional A label to identify `code_str` with. This is passed into ``compile`` as the second argument (for run-time error messages). Returns ------- elapsed : float Total elapsed time in seconds for executing `code_str` `times` times. Examples -------- >>> etime = np.testing.measure('for i in range(1000): np.sqrt(i**2)', ... times=times) >>> print "Time for a single execution : ", etime / times, "s" Time for a single execution : 0.005 s """ frame = sys._getframe(1) locs, globs = frame.f_locals, frame.f_globals code = compile(code_str, 'Test name: %s ' % label, 'exec') i = 0 elapsed = jiffies() while i < times: i += 1 exec(code, globs, locs) elapsed = jiffies() - elapsed return 0.01*elapsed def _assert_valid_refcount(op): """ Check that ufuncs don't mishandle refcount of object `1`. Used in a few regression tests. """ import numpy as np a = np.arange(100 * 100) b = np.arange(100*100).reshape(100, 100) c = b i = 1 rc = sys.getrefcount(i) for j in range(15): d = op(b, c) assert_(sys.getrefcount(i) >= rc) def assert_allclose(actual, desired, rtol=1e-7, atol=0, err_msg='', verbose=True): """ Raise an assertion if two objects are not equal up to desired tolerance. The test is equivalent to ``allclose(actual, desired, rtol, atol)``. It compares the difference between `actual` and `desired` to ``atol + rtol * abs(desired)``. .. versionadded:: 1.5.0 Parameters ---------- actual : array_like Array obtained. desired : array_like Array desired. rtol : float, optional Relative tolerance. atol : float, optional Absolute tolerance. err_msg : str, optional The error message to be printed in case of failure. verbose : bool, optional If True, the conflicting values are appended to the error message. Raises ------ AssertionError If actual and desired are not equal up to specified precision. See Also -------- assert_array_almost_equal_nulp, assert_array_max_ulp Examples -------- >>> x = [1e-5, 1e-3, 1e-1] >>> y = np.arccos(np.cos(x)) >>> assert_allclose(x, y, rtol=1e-5, atol=0) """ import numpy as np def compare(x, y): return np.allclose(x, y, rtol=rtol, atol=atol) actual, desired = np.asanyarray(actual), np.asanyarray(desired) header = 'Not equal to tolerance rtol=%g, atol=%g' % (rtol, atol) assert_array_compare(compare, actual, desired, err_msg=str(err_msg), verbose=verbose, header=header) def assert_array_almost_equal_nulp(x, y, nulp=1): """ Compare two arrays relatively to their spacing. This is a relatively robust method to compare two arrays whose amplitude is variable. Parameters ---------- x, y : array_like Input arrays. nulp : int, optional The maximum number of unit in the last place for tolerance (see Notes). Default is 1. Returns ------- None Raises ------ AssertionError If the spacing between `x` and `y` for one or more elements is larger than `nulp`. See Also -------- assert_array_max_ulp : Check that all items of arrays differ in at most N Units in the Last Place. spacing : Return the distance between x and the nearest adjacent number. Notes ----- An assertion is raised if the following condition is not met:: abs(x - y) <= nulps * spacing(max(abs(x), abs(y))) Examples -------- >>> x = np.array([1., 1e-10, 1e-20]) >>> eps = np.finfo(x.dtype).eps >>> np.testing.assert_array_almost_equal_nulp(x, x*eps/2 + x) >>> np.testing.assert_array_almost_equal_nulp(x, x*eps + x) ------------------------------------------------------------ Traceback (most recent call last): ... AssertionError: X and Y are not equal to 1 ULP (max is 2) """ import numpy as np ax = np.abs(x) ay = np.abs(y) ref = nulp * np.spacing(np.where(ax > ay, ax, ay)) if not np.all(np.abs(x-y) <= ref): if np.iscomplexobj(x) or np.iscomplexobj(y): msg = "X and Y are not equal to %d ULP" % nulp else: max_nulp = np.max(nulp_diff(x, y)) msg = "X and Y are not equal to %d ULP (max is %g)" % (nulp, max_nulp) raise AssertionError(msg) def assert_array_max_ulp(a, b, maxulp=1, dtype=None): """ Check that all items of arrays differ in at most N Units in the Last Place. Parameters ---------- a, b : array_like Input arrays to be compared. maxulp : int, optional The maximum number of units in the last place that elements of `a` and `b` can differ. Default is 1. dtype : dtype, optional Data-type to convert `a` and `b` to if given. Default is None. Returns ------- ret : ndarray Array containing number of representable floating point numbers between items in `a` and `b`. Raises ------ AssertionError If one or more elements differ by more than `maxulp`. See Also -------- assert_array_almost_equal_nulp : Compare two arrays relatively to their spacing. Examples -------- >>> a = np.linspace(0., 1., 100) >>> res = np.testing.assert_array_max_ulp(a, np.arcsin(np.sin(a))) """ import numpy as np ret = nulp_diff(a, b, dtype) if not np.all(ret <= maxulp): raise AssertionError("Arrays are not almost equal up to %g ULP" % \ maxulp) return ret def nulp_diff(x, y, dtype=None): """For each item in x and y, return the number of representable floating points between them. Parameters ---------- x : array_like first input array y : array_like second input array Returns ------- nulp : array_like number of representable floating point numbers between each item in x and y. Examples -------- # By definition, epsilon is the smallest number such as 1 + eps != 1, so # there should be exactly one ULP between 1 and 1 + eps >>> nulp_diff(1, 1 + np.finfo(x.dtype).eps) 1.0 """ import numpy as np if dtype: x = np.array(x, dtype=dtype) y = np.array(y, dtype=dtype) else: x = np.array(x) y = np.array(y) t = np.common_type(x, y) if np.iscomplexobj(x) or np.iscomplexobj(y): raise NotImplementedError("_nulp not implemented for complex array") x = np.array(x, dtype=t) y = np.array(y, dtype=t) if not x.shape == y.shape: raise ValueError("x and y do not have the same shape: %s - %s" % \ (x.shape, y.shape)) def _diff(rx, ry, vdt): diff = np.array(rx-ry, dtype=vdt) return np.abs(diff) rx = integer_repr(x) ry = integer_repr(y) return _diff(rx, ry, t) def _integer_repr(x, vdt, comp): # Reinterpret binary representation of the float as sign-magnitude: # take into account two-complement representation # See also # http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm rx = x.view(vdt) if not (rx.size == 1): rx[rx < 0] = comp - rx[rx<0] else: if rx < 0: rx = comp - rx return rx def integer_repr(x): """Return the signed-magnitude interpretation of the binary representation of x.""" import numpy as np if x.dtype == np.float32: return _integer_repr(x, np.int32, np.int32(-2**31)) elif x.dtype == np.float64: return _integer_repr(x, np.int64, np.int64(-2**63)) else: raise ValueError("Unsupported dtype %s" % x.dtype) # The following two classes are copied from python 2.6 warnings module (context # manager) class WarningMessage(object): """ Holds the result of a single showwarning() call. Deprecated in 1.8.0 Notes ----- `WarningMessage` is copied from the Python 2.6 warnings module, so it can be used in NumPy with older Python versions. """ _WARNING_DETAILS = ("message", "category", "filename", "lineno", "file", "line") def __init__(self, message, category, filename, lineno, file=None, line=None): local_values = locals() for attr in self._WARNING_DETAILS: setattr(self, attr, local_values[attr]) if category: self._category_name = category.__name__ else: self._category_name = None def __str__(self): return ("{message : %r, category : %r, filename : %r, lineno : %s, " "line : %r}" % (self.message, self._category_name, self.filename, self.lineno, self.line)) class WarningManager(object): """ A context manager that copies and restores the warnings filter upon exiting the context. The 'record' argument specifies whether warnings should be captured by a custom implementation of ``warnings.showwarning()`` and be appended to a list returned by the context manager. Otherwise None is returned by the context manager. The objects appended to the list are arguments whose attributes mirror the arguments to ``showwarning()``. The 'module' argument is to specify an alternative module to the module named 'warnings' and imported under that name. This argument is only useful when testing the warnings module itself. Deprecated in 1.8.0 Notes ----- `WarningManager` is a copy of the ``catch_warnings`` context manager from the Python 2.6 warnings module, with slight modifications. It is copied so it can be used in NumPy with older Python versions. """ def __init__(self, record=False, module=None): self._record = record if module is None: self._module = sys.modules['warnings'] else: self._module = module self._entered = False def __enter__(self): if self._entered: raise RuntimeError("Cannot enter %r twice" % self) self._entered = True self._filters = self._module.filters self._module.filters = self._filters[:] self._showwarning = self._module.showwarning if self._record: log = [] def showwarning(*args, **kwargs): log.append(WarningMessage(*args, **kwargs)) self._module.showwarning = showwarning return log else: return None def __exit__(self): if not self._entered: raise RuntimeError("Cannot exit %r without entering first" % self) 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. A warning of class warning_class should be thrown by the callable when invoked with arguments args and keyword arguments kwargs. If a different type of warning is thrown, it will not be caught, and the test case will be deemed to have suffered an error. .. versionadded:: 1.4.0 Parameters ---------- warning_class : class The class defining the warning that `func` is expected to throw. func : callable The callable to test. \\*args : Arguments Arguments passed to `func`. \\*\\*kwargs : Kwargs Keyword arguments passed to `func`. Returns ------- The value returned by `func`. """ with warnings.catch_warnings(record=True) as l: warnings.simplefilter('always') result = func(*args, **kw) if not len(l) > 0: raise AssertionError("No warning raised when calling %s" % func.__name__) if not l[0].category is warning_class: raise AssertionError("First warning for %s is not a " \ "%s( is %s)" % (func.__name__, warning_class, l[0])) return result def assert_no_warnings(func, *args, **kw): """ Fail if the given callable produces any warnings. .. versionadded:: 1.7.0 Parameters ---------- func : callable The callable to test. \\*args : Arguments Arguments passed to `func`. \\*\\*kwargs : Kwargs Keyword arguments passed to `func`. Returns ------- The value returned by `func`. """ with warnings.catch_warnings(record=True) as l: warnings.simplefilter('always') result = func(*args, **kw) if len(l) > 0: raise AssertionError("Got warnings when calling %s: %s" % (func.__name__, l)) return result def _gen_alignment_data(dtype=float32, type='binary', max_size=24): """ generator producing data with different alignment and offsets to test simd vectorization Parameters ---------- dtype : dtype data type to produce type : string 'unary': create data for unary operations, creates one input and output array 'binary': create data for unary operations, creates two input and output array max_size : integer maximum size of data to produce Returns ------- if type is 'unary' yields one output, one input array and a message containing information on the data if type is 'binary' yields one output array, two input array and a message containing information on the data """ ufmt = 'unary offset=(%d, %d), size=%d, dtype=%r, %s' bfmt = 'binary offset=(%d, %d, %d), size=%d, dtype=%r, %s' for o in range(3): for s in range(o + 2, max(o + 3, max_size)): if type == 'unary': inp = lambda : arange(s, dtype=dtype)[o:] out = empty((s,), dtype=dtype)[o:] yield out, inp(), ufmt % (o, o, s, dtype, 'out of place') yield inp(), inp(), ufmt % (o, o, s, dtype, 'in place') yield out[1:], inp()[:-1], ufmt % \ (o + 1, o, s - 1, dtype, 'out of place') yield out[:-1], inp()[1:], ufmt % \ (o, o + 1, s - 1, dtype, 'out of place') yield inp()[:-1], inp()[1:], ufmt % \ (o, o + 1, s - 1, dtype, 'aliased') yield inp()[1:], inp()[:-1], ufmt % \ (o + 1, o, s - 1, dtype, 'aliased') if type == 'binary': inp1 = lambda :arange(s, dtype=dtype)[o:] inp2 = lambda :arange(s, dtype=dtype)[o:] out = empty((s,), dtype=dtype)[o:] yield out, inp1(), inp2(), bfmt % \ (o, o, o, s, dtype, 'out of place') yield inp1(), inp1(), inp2(), bfmt % \ (o, o, o, s, dtype, 'in place1') yield inp2(), inp1(), inp2(), bfmt % \ (o, o, o, s, dtype, 'in place2') yield out[1:], inp1()[:-1], inp2()[:-1], bfmt % \ (o + 1, o, o, s - 1, dtype, 'out of place') yield out[:-1], inp1()[1:], inp2()[:-1], bfmt % \ (o, o + 1, o, s - 1, dtype, 'out of place') yield out[:-1], inp1()[:-1], inp2()[1:], bfmt % \ (o, o, o + 1, s - 1, dtype, 'out of place') yield inp1()[1:], inp1()[:-1], inp2()[:-1], bfmt % \ (o + 1, o, o, s - 1, dtype, 'aliased') yield inp1()[:-1], inp1()[1:], inp2()[:-1], bfmt % \ (o, o + 1, o, s - 1, dtype, 'aliased') yield inp1()[:-1], inp1()[:-1], inp2()[1:], bfmt % \ (o, o, o + 1, s - 1, dtype, 'aliased') class IgnoreException(Exception): "Ignoring this exception due to disabled feature" numpy-1.8.2/numpy/testing/setup.py0000775000175100017510000000121112370216242020360 0ustar vagrantvagrant00000000000000#!/usr/bin/env python from __future__ import division, print_function def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('testing', parent_package, top_path) config.add_data_dir('tests') return config if __name__ == '__main__': from numpy.distutils.core import setup setup(maintainer = "NumPy Developers", maintainer_email = "numpy-dev@numpy.org", description = "NumPy test module", url = "http://www.numpy.org", license = "NumPy License (BSD Style)", configuration = configuration, ) numpy-1.8.2/numpy/testing/tests/0000775000175100017510000000000012371375430020020 5ustar vagrantvagrant00000000000000numpy-1.8.2/numpy/testing/tests/test_decorators.py0000664000175100017510000001004612370216242023571 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function import numpy as np from numpy.testing import * from numpy.testing.noseclasses import KnownFailureTest import nose def test_slow(): @dec.slow def slow_func(x, y, z): pass assert_(slow_func.slow) def test_setastest(): @dec.setastest() def f_default(a): pass @dec.setastest(True) def f_istest(a): pass @dec.setastest(False) def f_isnottest(a): pass assert_(f_default.__test__) assert_(f_istest.__test__) assert_(not f_isnottest.__test__) class DidntSkipException(Exception): pass def test_skip_functions_hardcoded(): @dec.skipif(True) def f1(x): raise DidntSkipException try: f1('a') except DidntSkipException: raise Exception('Failed to skip') except nose.SkipTest: pass @dec.skipif(False) def f2(x): raise DidntSkipException try: f2('a') except DidntSkipException: pass except nose.SkipTest: raise Exception('Skipped when not expected to') def test_skip_functions_callable(): def skip_tester(): return skip_flag == 'skip me!' @dec.skipif(skip_tester) def f1(x): raise DidntSkipException try: skip_flag = 'skip me!' f1('a') except DidntSkipException: raise Exception('Failed to skip') except nose.SkipTest: pass @dec.skipif(skip_tester) def f2(x): raise DidntSkipException try: skip_flag = 'five is right out!' f2('a') except DidntSkipException: pass except nose.SkipTest: raise Exception('Skipped when not expected to') def test_skip_generators_hardcoded(): @dec.knownfailureif(True, "This test is known to fail") def g1(x): for i in range(x): yield i try: for j in g1(10): pass except KnownFailureTest: pass else: raise Exception('Failed to mark as known failure') @dec.knownfailureif(False, "This test is NOT known to fail") def g2(x): for i in range(x): yield i raise DidntSkipException('FAIL') try: for j in g2(10): pass except KnownFailureTest: raise Exception('Marked incorretly as known failure') except DidntSkipException: pass def test_skip_generators_callable(): def skip_tester(): return skip_flag == 'skip me!' @dec.knownfailureif(skip_tester, "This test is known to fail") def g1(x): for i in range(x): yield i try: skip_flag = 'skip me!' for j in g1(10): pass except KnownFailureTest: pass else: raise Exception('Failed to mark as known failure') @dec.knownfailureif(skip_tester, "This test is NOT known to fail") def g2(x): for i in range(x): yield i raise DidntSkipException('FAIL') try: skip_flag = 'do not skip' for j in g2(10): pass except KnownFailureTest: raise Exception('Marked incorretly as known failure') except DidntSkipException: pass def test_deprecated(): @dec.deprecated(True) def non_deprecated_func(): pass @dec.deprecated() def deprecated_func(): import warnings warnings.warn("TEST: deprecated func", DeprecationWarning) @dec.deprecated() def deprecated_func2(): import warnings warnings.warn("AHHHH") raise ValueError @dec.deprecated() def deprecated_func3(): import warnings warnings.warn("AHHHH") # marked as deprecated, but does not raise DeprecationWarning assert_raises(AssertionError, non_deprecated_func) # should be silent deprecated_func() # fails if deprecated decorator just disables test. See #1453. assert_raises(ValueError, deprecated_func2) # first warnings is not a DeprecationWarning assert_raises(AssertionError, deprecated_func3) if __name__ == '__main__': run_module_suite() numpy-1.8.2/numpy/testing/tests/test_doctesting.py0000664000175100017510000000245212370216242023571 0ustar vagrantvagrant00000000000000""" Doctests for NumPy-specific nose/doctest modifications """ from __future__ import division, absolute_import, print_function # try the #random directive on the output line def check_random_directive(): ''' >>> 2+2 #random: may vary on your system ''' # check the implicit "import numpy as np" def check_implicit_np(): ''' >>> np.array([1,2,3]) array([1, 2, 3]) ''' # there's some extraneous whitespace around the correct responses def check_whitespace_enabled(): ''' # whitespace after the 3 >>> 1+2 3 # whitespace before the 7 >>> 3+4 7 ''' def check_empty_output(): """ Check that no output does not cause an error. This is related to nose bug 445; the numpy plugin changed the doctest-result-variable default and therefore hit this bug: http://code.google.com/p/python-nose/issues/detail?id=445 >>> a = 10 """ def check_skip(): """ Check skip directive The test below should not run >>> 1/0 #doctest: +SKIP """ if __name__ == '__main__': # Run tests outside numpy test rig import nose from numpy.testing.noseclasses import NumpyDoctest argv = ['', __file__, '--with-numpydoctest'] nose.core.TestProgram(argv=argv, addplugins=[NumpyDoctest()]) numpy-1.8.2/numpy/testing/tests/test_utils.py0000664000175100017510000003651112370216243022572 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function import warnings import sys import numpy as np from numpy.testing import * import unittest class _GenericTest(object): def _test_equal(self, a, b): self._assert_func(a, b) def _test_not_equal(self, a, b): try: self._assert_func(a, b) passed = True except AssertionError: pass else: raise AssertionError("a and b are found equal but are not") def test_array_rank1_eq(self): """Test two equal array of rank 1 are found equal.""" a = np.array([1, 2]) b = np.array([1, 2]) self._test_equal(a, b) def test_array_rank1_noteq(self): """Test two different array of rank 1 are found not equal.""" a = np.array([1, 2]) b = np.array([2, 2]) self._test_not_equal(a, b) def test_array_rank2_eq(self): """Test two equal array of rank 2 are found equal.""" a = np.array([[1, 2], [3, 4]]) b = np.array([[1, 2], [3, 4]]) self._test_equal(a, b) def test_array_diffshape(self): """Test two arrays with different shapes are found not equal.""" a = np.array([1, 2]) b = np.array([[1, 2], [1, 2]]) self._test_not_equal(a, b) def test_objarray(self): """Test object arrays.""" a = np.array([1, 1], dtype=np.object) self._test_equal(a, 1) class TestArrayEqual(_GenericTest, unittest.TestCase): def setUp(self): self._assert_func = assert_array_equal def test_generic_rank1(self): """Test rank 1 array for all dtypes.""" def foo(t): a = np.empty(2, t) a.fill(1) b = a.copy() c = a.copy() c.fill(0) self._test_equal(a, b) self._test_not_equal(c, b) # Test numeric types and object for t in '?bhilqpBHILQPfdgFDG': foo(t) # Test strings for t in ['S1', 'U1']: foo(t) def test_generic_rank3(self): """Test rank 3 array for all dtypes.""" def foo(t): a = np.empty((4, 2, 3), t) a.fill(1) b = a.copy() c = a.copy() c.fill(0) self._test_equal(a, b) self._test_not_equal(c, b) # Test numeric types and object for t in '?bhilqpBHILQPfdgFDG': foo(t) # Test strings for t in ['S1', 'U1']: foo(t) def test_nan_array(self): """Test arrays with nan values in them.""" a = np.array([1, 2, np.nan]) b = np.array([1, 2, np.nan]) self._test_equal(a, b) c = np.array([1, 2, 3]) self._test_not_equal(c, b) def test_string_arrays(self): """Test two arrays with different shapes are found not equal.""" a = np.array(['floupi', 'floupa']) b = np.array(['floupi', 'floupa']) self._test_equal(a, b) c = np.array(['floupipi', 'floupa']) self._test_not_equal(c, b) def test_recarrays(self): """Test record arrays.""" a = np.empty(2, [('floupi', np.float), ('floupa', np.float)]) a['floupi'] = [1, 2] a['floupa'] = [1, 2] b = a.copy() self._test_equal(a, b) c = np.empty(2, [('floupipi', np.float), ('floupa', np.float)]) c['floupipi'] = a['floupi'].copy() c['floupa'] = a['floupa'].copy() self._test_not_equal(c, b) class TestEqual(TestArrayEqual): def setUp(self): self._assert_func = assert_equal def test_nan_items(self): self._assert_func(np.nan, np.nan) self._assert_func([np.nan], [np.nan]) self._test_not_equal(np.nan, [np.nan]) self._test_not_equal(np.nan, 1) def test_inf_items(self): self._assert_func(np.inf, np.inf) self._assert_func([np.inf], [np.inf]) self._test_not_equal(np.inf, [np.inf]) def test_non_numeric(self): self._assert_func('ab', 'ab') self._test_not_equal('ab', 'abb') def test_complex_item(self): self._assert_func(complex(1, 2), complex(1, 2)) self._assert_func(complex(1, np.nan), complex(1, np.nan)) self._test_not_equal(complex(1, np.nan), complex(1, 2)) self._test_not_equal(complex(np.nan, 1), complex(1, np.nan)) self._test_not_equal(complex(np.nan, np.inf), complex(np.nan, 2)) def test_negative_zero(self): self._test_not_equal(np.PZERO, np.NZERO) def test_complex(self): x = np.array([complex(1, 2), complex(1, np.nan)]) y = np.array([complex(1, 2), complex(1, 2)]) self._assert_func(x, x) self._test_not_equal(x, y) class TestArrayAlmostEqual(_GenericTest, unittest.TestCase): def setUp(self): self._assert_func = assert_array_almost_equal def test_simple(self): x = np.array([1234.2222]) y = np.array([1234.2223]) self._assert_func(x, y, decimal=3) self._assert_func(x, y, decimal=4) self.assertRaises(AssertionError, lambda: self._assert_func(x, y, decimal=5)) def test_nan(self): anan = np.array([np.nan]) aone = np.array([1]) ainf = np.array([np.inf]) self._assert_func(anan, anan) self.assertRaises(AssertionError, lambda : self._assert_func(anan, aone)) self.assertRaises(AssertionError, lambda : self._assert_func(anan, ainf)) self.assertRaises(AssertionError, lambda : self._assert_func(ainf, anan)) def test_inf(self): a = np.array([[1., 2.], [3., 4.]]) b = a.copy() a[0, 0] = np.inf self.assertRaises(AssertionError, lambda : self._assert_func(a, b)) class TestAlmostEqual(_GenericTest, unittest.TestCase): def setUp(self): self._assert_func = assert_almost_equal def test_nan_item(self): self._assert_func(np.nan, np.nan) self.assertRaises(AssertionError, lambda : self._assert_func(np.nan, 1)) self.assertRaises(AssertionError, lambda : self._assert_func(np.nan, np.inf)) self.assertRaises(AssertionError, lambda : self._assert_func(np.inf, np.nan)) def test_inf_item(self): self._assert_func(np.inf, np.inf) self._assert_func(-np.inf, -np.inf) self.assertRaises(AssertionError, lambda : self._assert_func(np.inf, 1)) def test_simple_item(self): self._test_not_equal(1, 2) def test_complex_item(self): self._assert_func(complex(1, 2), complex(1, 2)) self._assert_func(complex(1, np.nan), complex(1, np.nan)) self._assert_func(complex(np.inf, np.nan), complex(np.inf, np.nan)) self._test_not_equal(complex(1, np.nan), complex(1, 2)) self._test_not_equal(complex(np.nan, 1), complex(1, np.nan)) self._test_not_equal(complex(np.nan, np.inf), complex(np.nan, 2)) def test_complex(self): x = np.array([complex(1, 2), complex(1, np.nan)]) z = np.array([complex(1, 2), complex(np.nan, 1)]) y = np.array([complex(1, 2), complex(1, 2)]) self._assert_func(x, x) self._test_not_equal(x, y) self._test_not_equal(x, z) class TestApproxEqual(unittest.TestCase): def setUp(self): self._assert_func = assert_approx_equal def test_simple_arrays(self): x = np.array([1234.22]) y = np.array([1234.23]) self._assert_func(x, y, significant=5) self._assert_func(x, y, significant=6) self.assertRaises(AssertionError, lambda: self._assert_func(x, y, significant=7)) def test_simple_items(self): x = 1234.22 y = 1234.23 self._assert_func(x, y, significant=4) self._assert_func(x, y, significant=5) self._assert_func(x, y, significant=6) self.assertRaises(AssertionError, lambda: self._assert_func(x, y, significant=7)) def test_nan_array(self): anan = np.array(np.nan) aone = np.array(1) ainf = np.array(np.inf) self._assert_func(anan, anan) self.assertRaises(AssertionError, lambda : self._assert_func(anan, aone)) self.assertRaises(AssertionError, lambda : self._assert_func(anan, ainf)) self.assertRaises(AssertionError, lambda : self._assert_func(ainf, anan)) def test_nan_items(self): anan = np.array(np.nan) aone = np.array(1) ainf = np.array(np.inf) self._assert_func(anan, anan) self.assertRaises(AssertionError, lambda : self._assert_func(anan, aone)) self.assertRaises(AssertionError, lambda : self._assert_func(anan, ainf)) self.assertRaises(AssertionError, lambda : self._assert_func(ainf, anan)) class TestRaises(unittest.TestCase): def setUp(self): class MyException(Exception): pass self.e = MyException def raises_exception(self, e): raise e def does_not_raise_exception(self): pass def test_correct_catch(self): f = raises(self.e)(self.raises_exception)(self.e) def test_wrong_exception(self): try: f = raises(self.e)(self.raises_exception)(RuntimeError) except RuntimeError: return else: raise AssertionError("should have caught RuntimeError") def test_catch_no_raise(self): try: f = raises(self.e)(self.does_not_raise_exception)() except AssertionError: return else: raise AssertionError("should have raised an AssertionError") class TestWarns(unittest.TestCase): def test_warn(self): def f(): warnings.warn("yo") return 3 before_filters = sys.modules['warnings'].filters[:] assert_equal(assert_warns(UserWarning, f), 3) after_filters = sys.modules['warnings'].filters assert_raises(AssertionError, assert_no_warnings, f) assert_equal(assert_no_warnings(lambda x: x, 1), 1) # Check that the warnings state is unchanged assert_equal(before_filters, after_filters, "assert_warns does not preserver warnings state") def test_warn_wrong_warning(self): def f(): warnings.warn("yo", DeprecationWarning) failed = False filters = sys.modules['warnings'].filters[:] try: try: # Should raise an AssertionError assert_warns(UserWarning, f) failed = True except AssertionError: pass finally: sys.modules['warnings'].filters = filters if failed: raise AssertionError("wrong warning caught by assert_warn") class TestAssertAllclose(unittest.TestCase): def test_simple(self): x = 1e-3 y = 1e-9 assert_allclose(x, y, atol=1) self.assertRaises(AssertionError, assert_allclose, x, y) a = np.array([x, y, x, y]) b = np.array([x, y, x, x]) assert_allclose(a, b, atol=1) self.assertRaises(AssertionError, assert_allclose, a, b) b[-1] = y * (1 + 1e-8) assert_allclose(a, b) self.assertRaises(AssertionError, assert_allclose, a, b, rtol=1e-9) assert_allclose(6, 10, rtol=0.5) self.assertRaises(AssertionError, assert_allclose, 10, 6, rtol=0.5) class TestArrayAlmostEqualNulp(unittest.TestCase): @dec.knownfailureif(True, "Github issue #347") def test_simple(self): np.random.seed(12345) for i in range(100): dev = np.random.randn(10) x = np.ones(10) y = x + dev * np.finfo(np.float64).eps assert_array_almost_equal_nulp(x, y, nulp=2 * np.max(dev)) def test_simple2(self): x = np.random.randn(10) y = 2 * x def failure(): return assert_array_almost_equal_nulp(x, y, nulp=1000) self.assertRaises(AssertionError, failure) def test_big_float32(self): x = (1e10 * np.random.randn(10)).astype(np.float32) y = x + 1 assert_array_almost_equal_nulp(x, y, nulp=1000) def test_big_float64(self): x = 1e10 * np.random.randn(10) y = x + 1 def failure(): assert_array_almost_equal_nulp(x, y, nulp=1000) self.assertRaises(AssertionError, failure) def test_complex(self): x = np.random.randn(10) + 1j * np.random.randn(10) y = x + 1 def failure(): assert_array_almost_equal_nulp(x, y, nulp=1000) self.assertRaises(AssertionError, failure) def test_complex2(self): x = np.random.randn(10) y = np.array(x, np.complex) + 1e-16 * np.random.randn(10) assert_array_almost_equal_nulp(x, y, nulp=1000) class TestULP(unittest.TestCase): def test_equal(self): x = np.random.randn(10) assert_array_max_ulp(x, x, maxulp=0) def test_single(self): # Generate 1 + small deviation, check that adding eps gives a few UNL x = np.ones(10).astype(np.float32) x += 0.01 * np.random.randn(10).astype(np.float32) eps = np.finfo(np.float32).eps assert_array_max_ulp(x, x+eps, maxulp=20) def test_double(self): # Generate 1 + small deviation, check that adding eps gives a few UNL x = np.ones(10).astype(np.float64) x += 0.01 * np.random.randn(10).astype(np.float64) eps = np.finfo(np.float64).eps assert_array_max_ulp(x, x+eps, maxulp=200) def test_inf(self): for dt in [np.float32, np.float64]: inf = np.array([np.inf]).astype(dt) big = np.array([np.finfo(dt).max]) assert_array_max_ulp(inf, big, maxulp=200) def test_nan(self): # Test that nan is 'far' from small, tiny, inf, max and min for dt in [np.float32, np.float64]: if dt == np.float32: maxulp = 1e6 else: maxulp = 1e12 inf = np.array([np.inf]).astype(dt) nan = np.array([np.nan]).astype(dt) big = np.array([np.finfo(dt).max]) tiny = np.array([np.finfo(dt).tiny]) zero = np.array([np.PZERO]).astype(dt) nzero = np.array([np.NZERO]).astype(dt) self.assertRaises(AssertionError, lambda: assert_array_max_ulp(nan, inf, maxulp=maxulp)) self.assertRaises(AssertionError, lambda: assert_array_max_ulp(nan, big, maxulp=maxulp)) self.assertRaises(AssertionError, lambda: assert_array_max_ulp(nan, tiny, maxulp=maxulp)) self.assertRaises(AssertionError, lambda: assert_array_max_ulp(nan, zero, maxulp=maxulp)) self.assertRaises(AssertionError, lambda: assert_array_max_ulp(nan, nzero, maxulp=maxulp)) if __name__ == '__main__': run_module_suite() numpy-1.8.2/numpy/testing/__init__.py0000664000175100017510000000102712370216243020762 0ustar vagrantvagrant00000000000000"""Common test support for all numpy test scripts. This single module should provide all the common functionality for numpy tests in a single location, so that test scripts can just import it and work right away. """ from __future__ import division, absolute_import, print_function 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 numpy-1.8.2/numpy/testing/noseclasses.py0000664000175100017510000003401612370216242021550 0ustar vagrantvagrant00000000000000# These classes implement a doctest runner plugin for nose, a "known failure" # error class, and a customized TestProgram for NumPy. # Because this module imports nose directly, it should not # be used except by nosetester.py to avoid a general NumPy # dependency on nose. from __future__ import division, absolute_import, print_function import os import doctest import nose from nose.plugins import doctests as npd from nose.plugins.errorclass import ErrorClass, ErrorClassPlugin from nose.plugins.base import Plugin from nose.util import src import numpy from .nosetester import get_package_name import inspect # Some of the classes in this module begin with 'Numpy' to clearly distinguish # them from the plethora of very similar names from nose/unittest/doctest #----------------------------------------------------------------------------- # Modified version of the one in the stdlib, that fixes a python bug (doctests # not found in extension modules, http://bugs.python.org/issue3158) class NumpyDocTestFinder(doctest.DocTestFinder): def _from_module(self, module, object): """ Return true if the given object is defined in the given module. """ if module is None: #print '_fm C1' # dbg return True elif inspect.isfunction(object): #print '_fm C2' # dbg return module.__dict__ is object.__globals__ elif inspect.isbuiltin(object): #print '_fm C2-1' # dbg return module.__name__ == object.__module__ elif inspect.isclass(object): #print '_fm C3' # dbg return module.__name__ == object.__module__ elif inspect.ismethod(object): # This one may be a bug in cython that fails to correctly set the # __module__ attribute of methods, but since the same error is easy # to make by extension code writers, having this safety in place # isn't such a bad idea #print '_fm C3-1' # dbg return module.__name__ == object.__self__.__class__.__module__ elif inspect.getmodule(object) is not None: #print '_fm C4' # dbg #print 'C4 mod',module,'obj',object # dbg return module is inspect.getmodule(object) elif hasattr(object, '__module__'): #print '_fm C5' # dbg return module.__name__ == object.__module__ elif isinstance(object, property): #print '_fm C6' # dbg return True # [XX] no way not be sure. else: raise ValueError("object must be a class or function") def _find(self, tests, obj, name, module, source_lines, globs, seen): """ Find tests for the given object and any contained objects, and add them to `tests`. """ doctest.DocTestFinder._find(self, tests, obj, name, module, source_lines, globs, seen) # Below we re-run pieces of the above method with manual modifications, # because the original code is buggy and fails to correctly identify # doctests in extension modules. # Local shorthands from inspect import isroutine, isclass, ismodule, isfunction, \ ismethod # Look for tests in a module's contained objects. if ismodule(obj) and self._recurse: for valname, val in obj.__dict__.items(): valname1 = '%s.%s' % (name, valname) if ( (isroutine(val) or isclass(val)) and self._from_module(module, val) ): self._find(tests, val, valname1, module, source_lines, globs, seen) # Look for tests in a class's contained objects. if isclass(obj) and self._recurse: #print 'RECURSE into class:',obj # dbg for valname, val in obj.__dict__.items(): #valname1 = '%s.%s' % (name, valname) # dbg #print 'N',name,'VN:',valname,'val:',str(val)[:77] # dbg # Special handling for staticmethod/classmethod. if isinstance(val, staticmethod): val = getattr(obj, valname) if isinstance(val, classmethod): val = getattr(obj, valname).__func__ # Recurse to methods, properties, and nested classes. if ((isfunction(val) or isclass(val) or ismethod(val) or isinstance(val, property)) and self._from_module(module, val)): valname = '%s.%s' % (name, valname) self._find(tests, val, valname, module, source_lines, globs, seen) # second-chance checker; if the default comparison doesn't # pass, then see if the expected output string contains flags that # tell us to ignore the output class NumpyOutputChecker(doctest.OutputChecker): def check_output(self, want, got, optionflags): ret = doctest.OutputChecker.check_output(self, want, got, optionflags) if not ret: if "#random" in want: return True # it would be useful to normalize endianness so that # bigendian machines don't fail all the tests (and there are # actually some bigendian examples in the doctests). Let's try # making them all little endian got = got.replace("'>", "'<") want= want.replace("'>", "'<") # try to normalize out 32 and 64 bit default int sizes for sz in [4, 8]: got = got.replace("'>> np.testing.nosetester.get_package_name('nonsense') 'numpy' """ fullpath = filepath[:] pkg_name = [] while 'site-packages' in filepath or 'dist-packages' in filepath: filepath, p2 = os.path.split(filepath) if p2 in ('site-packages', 'dist-packages'): break pkg_name.append(p2) # if package name determination failed, just default to numpy/scipy if not pkg_name: if 'scipy' in fullpath: return 'scipy' else: return 'numpy' # otherwise, reverse to get correct order and return pkg_name.reverse() # don't include the outer egg directory if pkg_name[0].endswith('.egg'): pkg_name.pop(0) return '.'.join(pkg_name) def import_nose(): """ Import nose only when needed. """ fine_nose = True minimum_nose_version = (0, 10, 0) try: import nose except ImportError: fine_nose = False else: if nose.__versioninfo__ < minimum_nose_version: fine_nose = False if not fine_nose: msg = 'Need nose >= %d.%d.%d for tests - see ' \ 'http://somethingaboutorange.com/mrl/projects/nose' % \ minimum_nose_version raise ImportError(msg) return nose def run_module_suite(file_to_run = None): 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]) class NoseTester(object): """ Nose test runner. This class is made available as numpy.testing.Tester, and a test function is typically added to a package's __init__.py like so:: from numpy.testing import Tester test = Tester().test Calling this test function finds and runs all tests associated with the package and all its sub-packages. Attributes ---------- package_path : str Full path to the package to test. package_name : str Name of the package to test. Parameters ---------- package : module, str or None, optional The package to test. If a string, this should be the full path to the package. If None (default), `package` is set to the module from which `NoseTester` is initialized. raise_warnings : str or sequence of warnings, optional This specifies which warnings to configure as 'raise' instead of 'warn' during the test execution. Valid strings are: - "develop" : equals ``(DeprecationWarning, RuntimeWarning)`` - "release" : equals ``()``, don't raise on any warnings. See Notes for more details. Notes ----- The default for `raise_warnings` is ``(DeprecationWarning, RuntimeWarning)`` for the master branch of NumPy, and ``()`` for maintenance branches and released versions. The purpose of this switching behavior is to catch as many warnings as possible during development, but not give problems for packaging of released versions. """ # Stuff to exclude from tests. These are from numpy.distutils excludes = ['f2py_ext', 'f2py_f90_ext', 'gen_ext', 'pyrex_ext', 'swig_ext'] def __init__(self, package=None, raise_warnings="release"): package_name = None if package is None: f = sys._getframe(1) package_path = f.f_locals.get('__file__', None) if package_path is None: raise AssertionError package_path = os.path.dirname(package_path) package_name = f.f_locals.get('__name__', None) elif isinstance(package, type(os)): package_path = os.path.dirname(package.__file__) package_name = getattr(package, '__name__', None) else: package_path = str(package) self.package_path = package_path # Find the package name under test; this name is used to limit coverage # reporting (if enabled). if package_name is None: package_name = get_package_name(package_path) self.package_name = package_name # Set to "release" in constructor in maintenance branches. self.raise_warnings = raise_warnings def _test_argv(self, label, verbose, extra_argv): ''' Generate argv for nosetest command Parameters ---------- label : {'fast', 'full', '', attribute identifier}, optional see ``test`` docstring verbose : int, optional Verbosity value for test outputs, in the range 1-10. Default is 1. extra_argv : list, optional List with any extra arguments to pass to nosetests. Returns ------- argv : list command line arguments that will be passed to nose ''' argv = [__file__, self.package_path, '-s'] if label and label != 'full': if not isinstance(label, basestring): raise TypeError('Selection label should be a string') if label == 'fast': label = 'not slow' argv += ['-A', label] argv += ['--verbosity', str(verbose)] # When installing with setuptools, and also in some other cases, the # test_*.py files end up marked +x executable. Nose, by default, does # not run files marked with +x as they might be scripts. However, in # our case nose only looks for test_*.py files under the package # directory, which should be safe. argv += ['--exe'] if extra_argv: argv += extra_argv return argv def _show_system_info(self): nose = import_nose() import numpy print("NumPy version %s" % numpy.__version__) npdir = os.path.dirname(numpy.__file__) print("NumPy is installed in %s" % npdir) if 'scipy' in self.package_name: import scipy print("SciPy version %s" % scipy.__version__) spdir = os.path.dirname(scipy.__file__) print("SciPy is installed in %s" % spdir) pyversion = sys.version.replace('\n', '') print("Python version %s" % pyversion) print("nose version %d.%d.%d" % nose.__versioninfo__) def _get_custom_doctester(self): """ Return instantiated plugin for doctests Allows subclassing of this class to override doctester A return value of None means use the nose builtin doctest plugin """ from .noseclasses import NumpyDoctest return NumpyDoctest() def prepare_test_args(self, label='fast', verbose=1, extra_argv=None, doctests=False, coverage=False): """ Run tests for module using nose. This method does the heavy lifting for the `test` method. It takes all the same arguments, for details see `test`. See Also -------- test """ # fail with nice error message if nose is not present import_nose() # compile argv argv = self._test_argv(label, verbose, extra_argv) # bypass tests noted for exclude for ename in self.excludes: argv += ['--exclude', ename] # our way of doing coverage if coverage: argv+=['--cover-package=%s' % self.package_name, '--with-coverage', '--cover-tests', '--cover-erase'] # construct list of plugins import nose.plugins.builtin from .noseclasses import KnownFailure, Unplugger plugins = [KnownFailure()] plugins += [p() for p in nose.plugins.builtin.plugins] # add doctesting if required doctest_argv = '--with-doctest' in argv if doctests == False and doctest_argv: doctests = True plug = self._get_custom_doctester() if plug is None: # use standard doctesting if doctests and not doctest_argv: argv += ['--with-doctest'] else: # custom doctesting if doctest_argv: # in fact the unplugger would take care of this argv.remove('--with-doctest') plugins += [Unplugger('doctest'), plug] if doctests: argv += ['--with-' + plug.name] return argv, plugins def test(self, label='fast', verbose=1, extra_argv=None, doctests=False, coverage=False, raise_warnings=None): """ Run tests for module using nose. Parameters ---------- label : {'fast', 'full', '', attribute identifier}, optional Identifies the tests to run. This can be a string to pass to the nosetests executable with the '-A' option, or one of several special values. Special values are: * 'fast' - the default - which corresponds to the ``nosetests -A`` option of 'not slow'. * 'full' - fast (as above) and slow tests as in the 'no -A' option to nosetests - this is the same as ''. * None or '' - run all tests. attribute_identifier - string passed directly to nosetests as '-A'. verbose : int, optional Verbosity value for test outputs, in the range 1-10. Default is 1. extra_argv : list, optional List with any extra arguments to pass to nosetests. doctests : bool, optional If True, run doctests in module. Default is False. coverage : bool, optional If True, report coverage of NumPy code. Default is False. (This requires the `coverage module: `_). raise_warnings : str or sequence of warnings, optional This specifies which warnings to configure as 'raise' instead of 'warn' during the test execution. Valid strings are: - "develop" : equals ``(DeprecationWarning, RuntimeWarning)`` - "release" : equals ``()``, don't raise on any warnings. Returns ------- result : object Returns the result of running the tests as a ``nose.result.TextTestResult`` object. Notes ----- Each NumPy module exposes `test` in its namespace to run all tests for it. For example, to run all tests for numpy.lib: >>> np.lib.test() #doctest: +SKIP Examples -------- >>> result = np.lib.test() #doctest: +SKIP Running unit tests for numpy.lib ... Ran 976 tests in 3.933s OK >>> result.errors #doctest: +SKIP [] >>> result.knownfail #doctest: +SKIP [] """ # cap verbosity at 3 because nose becomes *very* verbose beyond that verbose = min(verbose, 3) from . import utils utils.verbose = verbose if doctests: print("Running unit tests and doctests for %s" % self.package_name) else: print("Running unit tests for %s" % self.package_name) self._show_system_info() # reset doctest state on every run import doctest doctest.master = None if raise_warnings is None: raise_warnings = self.raise_warnings _warn_opts = dict(develop=(DeprecationWarning, RuntimeWarning), release=()) if raise_warnings in _warn_opts.keys(): raise_warnings = _warn_opts[raise_warnings] with warnings.catch_warnings(): # Reset the warning filters to the default state, # so that running the tests is more repeatable. warnings.resetwarnings() # If deprecation warnings are not set to 'error' below, # at least set them to 'warn'. warnings.filterwarnings('always', category=DeprecationWarning) # Force the requested warnings to raise for warningtype in raise_warnings: warnings.filterwarnings('error', category=warningtype) # Filter out annoying import messages. warnings.filterwarnings('ignore', message='Not importing directory') warnings.filterwarnings("ignore", message="numpy.dtype size changed") warnings.filterwarnings("ignore", message="numpy.ufunc size changed") warnings.filterwarnings("ignore", category=ModuleDeprecationWarning) warnings.filterwarnings("ignore", category=FutureWarning) from .noseclasses import NumpyTestProgram argv, plugins = self.prepare_test_args( label, verbose, extra_argv, doctests, coverage) t = NumpyTestProgram(argv=argv, exit=False, plugins=plugins) return t.result def bench(self, label='fast', verbose=1, extra_argv=None): """ Run benchmarks for module using nose. Parameters ---------- label : {'fast', 'full', '', attribute identifier}, optional Identifies the benchmarks to run. This can be a string to pass to the nosetests executable with the '-A' option, or one of several special values. Special values are: * 'fast' - the default - which corresponds to the ``nosetests -A`` option of 'not slow'. * 'full' - fast (as above) and slow benchmarks as in the 'no -A' option to nosetests - this is the same as ''. * None or '' - run all tests. attribute_identifier - string passed directly to nosetests as '-A'. verbose : int, optional Verbosity value for benchmark outputs, in the range 1-10. Default is 1. extra_argv : list, optional List with any extra arguments to pass to nosetests. Returns ------- success : bool Returns True if running the benchmarks works, False if an error occurred. Notes ----- Benchmarks are like tests, but have names starting with "bench" instead of "test", and can be found under the "benchmarks" sub-directory of the module. Each NumPy module exposes `bench` in its namespace to run all benchmarks for it. Examples -------- >>> success = np.lib.bench() #doctest: +SKIP Running benchmarks for numpy.lib ... using 562341 items: unique: 0.11 unique1d: 0.11 ratio: 1.0 nUnique: 56230 == 56230 ... OK >>> success #doctest: +SKIP True """ print("Running benchmarks for %s" % self.package_name) self._show_system_info() argv = self._test_argv(label, verbose, extra_argv) argv += ['--match', r'(?:^|[\\b_\\.%s-])[Bb]ench' % os.sep] # import nose or make informative error nose = import_nose() # get plugin to disable doctests from .noseclasses import Unplugger add_plugins = [Unplugger('doctest')] return nose.run(argv=argv, addplugins=add_plugins) numpy-1.8.2/numpy/distutils/0000775000175100017510000000000012371375430017225 5ustar vagrantvagrant00000000000000numpy-1.8.2/numpy/distutils/fcompiler/0000775000175100017510000000000012371375430021205 5ustar vagrantvagrant00000000000000numpy-1.8.2/numpy/distutils/fcompiler/vast.py0000664000175100017510000000335712370216242022536 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function import os from numpy.distutils.fcompiler.gnu import GnuFCompiler compilers = ['VastFCompiler'] class VastFCompiler(GnuFCompiler): compiler_type = 'vast' compiler_aliases = () description = 'Pacific-Sierra Research Fortran 90 Compiler' version_pattern = r'\s*Pacific-Sierra Research vf90 '\ '(Personal|Professional)\s+(?P[^\s]*)' # VAST f90 does not support -o with -c. So, object files are created # to the current directory and then moved to build directory object_switch = ' && function _mvfile { mv -v `basename $1` $1 ; } && _mvfile ' executables = { 'version_cmd' : ["vf90", "-v"], 'compiler_f77' : ["g77"], 'compiler_fix' : ["f90", "-Wv,-ya"], 'compiler_f90' : ["f90"], 'linker_so' : [""], 'archiver' : ["ar", "-cr"], 'ranlib' : ["ranlib"] } module_dir_switch = None #XXX Fix me module_include_switch = None #XXX Fix me def find_executables(self): pass def get_version_cmd(self): f90 = self.compiler_f90[0] d, b = os.path.split(f90) vf90 = os.path.join(d, 'v'+b) return vf90 def get_flags_arch(self): vast_version = self.get_version() gnu = GnuFCompiler() gnu.customize(None) self.version = gnu.get_version() opt = GnuFCompiler.get_flags_arch(self) self.version = vast_version return opt if __name__ == '__main__': from distutils import log log.set_verbosity(2) from numpy.distutils.fcompiler import new_fcompiler compiler = new_fcompiler(compiler='vast') compiler.customize() print(compiler.get_version()) numpy-1.8.2/numpy/distutils/fcompiler/ibm.py0000664000175100017510000000652012370216242022323 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function import os import re import sys from numpy.distutils.fcompiler import FCompiler from numpy.distutils.exec_command import exec_command, find_executable from numpy.distutils.misc_util import make_temp_file from distutils import log compilers = ['IBMFCompiler'] class IBMFCompiler(FCompiler): compiler_type = 'ibm' description = 'IBM XL Fortran Compiler' version_pattern = r'(xlf\(1\)\s*|)IBM XL Fortran ((Advanced Edition |)Version |Enterprise Edition V|for AIX, V)(?P[^\s*]*)' #IBM XL Fortran Enterprise Edition V10.1 for AIX \nVersion: 10.01.0000.0004 executables = { 'version_cmd' : ["", "-qversion"], 'compiler_f77' : ["xlf"], 'compiler_fix' : ["xlf90", "-qfixed"], 'compiler_f90' : ["xlf90"], 'linker_so' : ["xlf95"], 'archiver' : ["ar", "-cr"], 'ranlib' : ["ranlib"] } def get_version(self,*args,**kwds): version = FCompiler.get_version(self,*args,**kwds) if version is None and sys.platform.startswith('aix'): # use lslpp to find out xlf version lslpp = find_executable('lslpp') xlf = find_executable('xlf') if os.path.exists(xlf) and os.path.exists(lslpp): s, o = exec_command(lslpp + ' -Lc xlfcmp') m = re.search('xlfcmp:(?P\d+([.]\d+)+)', o) if m: version = m.group('version') xlf_dir = '/etc/opt/ibmcmp/xlf' if version is None and os.path.isdir(xlf_dir): # linux: # If the output of xlf does not contain version info # (that's the case with xlf 8.1, for instance) then # let's try another method: l = sorted(os.listdir(xlf_dir)) l.reverse() l = [d for d in l if os.path.isfile(os.path.join(xlf_dir, d, 'xlf.cfg'))] if l: from distutils.version import LooseVersion self.version = version = LooseVersion(l[0]) return version def get_flags(self): return ['-qextname'] def get_flags_debug(self): return ['-g'] def get_flags_linker_so(self): opt = [] if sys.platform=='darwin': opt.append('-Wl,-bundle,-flat_namespace,-undefined,suppress') else: opt.append('-bshared') version = self.get_version(ok_status=[0, 40]) if version is not None: if sys.platform.startswith('aix'): xlf_cfg = '/etc/xlf.cfg' else: xlf_cfg = '/etc/opt/ibmcmp/xlf/%s/xlf.cfg' % version fo, new_cfg = make_temp_file(suffix='_xlf.cfg') log.info('Creating '+new_cfg) fi = open(xlf_cfg, 'r') crt1_match = re.compile(r'\s*crt\s*[=]\s*(?P.*)/crt1.o').match for line in fi: m = crt1_match(line) if m: fo.write('crt = %s/bundle1.o\n' % (m.group('path'))) else: fo.write(line) fi.close() fo.close() opt.append('-F'+new_cfg) return opt def get_flags_opt(self): return ['-O3'] if __name__ == '__main__': log.set_verbosity(2) compiler = IBMFCompiler() compiler.customize() print(compiler.get_version()) numpy-1.8.2/numpy/distutils/fcompiler/compaq.py0000664000175100017510000001006112370216242023027 0ustar vagrantvagrant00000000000000 #http://www.compaq.com/fortran/docs/ from __future__ import division, absolute_import, print_function import os import sys from numpy.distutils.fcompiler import FCompiler from numpy.distutils.compat import get_exception from distutils.errors import DistutilsPlatformError compilers = ['CompaqFCompiler'] if os.name != 'posix' or sys.platform[:6] == 'cygwin' : # Otherwise we'd get a false positive on posix systems with # case-insensitive filesystems (like darwin), because we'll pick # up /bin/df compilers.append('CompaqVisualFCompiler') class CompaqFCompiler(FCompiler): compiler_type = 'compaq' description = 'Compaq Fortran Compiler' version_pattern = r'Compaq Fortran (?P[^\s]*).*' if sys.platform[:5]=='linux': fc_exe = 'fort' else: fc_exe = 'f90' executables = { 'version_cmd' : ['', "-version"], 'compiler_f77' : [fc_exe, "-f77rtl", "-fixed"], 'compiler_fix' : [fc_exe, "-fixed"], 'compiler_f90' : [fc_exe], 'linker_so' : [''], 'archiver' : ["ar", "-cr"], 'ranlib' : ["ranlib"] } module_dir_switch = '-module ' # not tested module_include_switch = '-I' def get_flags(self): return ['-assume no2underscore', '-nomixed_str_len_arg'] def get_flags_debug(self): return ['-g', '-check bounds'] def get_flags_opt(self): return ['-O4', '-align dcommons', '-assume bigarrays', '-assume nozsize', '-math_library fast'] def get_flags_arch(self): return ['-arch host', '-tune host'] def get_flags_linker_so(self): if sys.platform[:5]=='linux': return ['-shared'] return ['-shared', '-Wl,-expect_unresolved,*'] class CompaqVisualFCompiler(FCompiler): compiler_type = 'compaqv' description = 'DIGITAL or Compaq Visual Fortran Compiler' version_pattern = r'(DIGITAL|Compaq) Visual Fortran Optimizing Compiler'\ ' Version (?P[^\s]*).*' compile_switch = '/compile_only' object_switch = '/object:' library_switch = '/OUT:' #No space after /OUT:! static_lib_extension = ".lib" static_lib_format = "%s%s" module_dir_switch = '/module:' module_include_switch = '/I' ar_exe = 'lib.exe' fc_exe = 'DF' if sys.platform=='win32': from distutils.msvccompiler import MSVCCompiler try: m = MSVCCompiler() m.initialize() ar_exe = m.lib except DistutilsPlatformError: pass except AttributeError: msg = get_exception() if '_MSVCCompiler__root' in str(msg): print('Ignoring "%s" (I think it is msvccompiler.py bug)' % (msg)) else: raise except IOError: e = get_exception() if not "vcvarsall.bat" in str(e): print("Unexpected IOError in", __file__) raise e except ValueError: e = get_exception() if not "path']" in str(e): print("Unexpected ValueError in", __file__) raise e executables = { 'version_cmd' : ['', "/what"], 'compiler_f77' : [fc_exe, "/f77rtl", "/fixed"], 'compiler_fix' : [fc_exe, "/fixed"], 'compiler_f90' : [fc_exe], 'linker_so' : [''], 'archiver' : [ar_exe, "/OUT:"], 'ranlib' : None } def get_flags(self): return ['/nologo', '/MD', '/WX', '/iface=(cref,nomixed_str_len_arg)', '/names:lowercase', '/assume:underscore'] def get_flags_opt(self): return ['/Ox', '/fast', '/optimize:5', '/unroll:0', '/math_library:fast'] def get_flags_arch(self): return ['/threads'] def get_flags_debug(self): return ['/debug'] if __name__ == '__main__': from distutils import log log.set_verbosity(2) from numpy.distutils.fcompiler import new_fcompiler compiler = new_fcompiler(compiler='compaq') compiler.customize() print(compiler.get_version()) numpy-1.8.2/numpy/distutils/fcompiler/intel.py0000664000175100017510000001465012370216243022673 0ustar vagrantvagrant00000000000000# http://developer.intel.com/software/products/compilers/flin/ from __future__ import division, absolute_import, print_function import sys from numpy.distutils.ccompiler import simple_version_match from numpy.distutils.fcompiler import FCompiler, dummy_fortran_file compilers = ['IntelFCompiler', 'IntelVisualFCompiler', 'IntelItaniumFCompiler', 'IntelItaniumVisualFCompiler', 'IntelEM64VisualFCompiler', 'IntelEM64TFCompiler'] def intel_version_match(type): # Match against the important stuff in the version string return simple_version_match(start=r'Intel.*?Fortran.*?(?:%s).*?Version' % (type,)) class BaseIntelFCompiler(FCompiler): def update_executables(self): f = dummy_fortran_file() self.executables['version_cmd'] = ['', '-FI', '-V', '-c', f + '.f', '-o', f + '.o'] class IntelFCompiler(BaseIntelFCompiler): compiler_type = 'intel' compiler_aliases = ('ifort',) description = 'Intel Fortran Compiler for 32-bit apps' version_match = intel_version_match('32-bit|IA-32') possible_executables = ['ifort', 'ifc'] executables = { 'version_cmd' : None, # set by update_executables 'compiler_f77' : [None, "-72", "-w90", "-w95"], 'compiler_f90' : [None], 'compiler_fix' : [None, "-FI"], 'linker_so' : ["", "-shared"], 'archiver' : ["ar", "-cr"], 'ranlib' : ["ranlib"] } pic_flags = ['-fPIC'] module_dir_switch = '-module ' # Don't remove ending space! module_include_switch = '-I' def get_flags_free(self): return ["-FR"] def get_flags(self): return ['-fPIC'] def get_flags_opt(self): #return ['-i8 -xhost -openmp -fp-model strict'] return ['-xhost -openmp -fp-model strict'] def get_flags_arch(self): return [] def get_flags_linker_so(self): opt = FCompiler.get_flags_linker_so(self) v = self.get_version() if v and v >= '8.0': opt.append('-nofor_main') if sys.platform == 'darwin': # Here, it's -dynamiclib try: idx = opt.index('-shared') opt.remove('-shared') except ValueError: idx = 0 opt[idx:idx] = ['-dynamiclib', '-Wl,-undefined,dynamic_lookup', '-Wl,-framework,Python'] return opt class IntelItaniumFCompiler(IntelFCompiler): compiler_type = 'intele' compiler_aliases = () description = 'Intel Fortran Compiler for Itanium apps' version_match = intel_version_match('Itanium|IA-64') possible_executables = ['ifort', 'efort', 'efc'] executables = { 'version_cmd' : None, 'compiler_f77' : [None, "-FI", "-w90", "-w95"], 'compiler_fix' : [None, "-FI"], 'compiler_f90' : [None], 'linker_so' : ['', "-shared"], 'archiver' : ["ar", "-cr"], 'ranlib' : ["ranlib"] } class IntelEM64TFCompiler(IntelFCompiler): compiler_type = 'intelem' compiler_aliases = () description = 'Intel Fortran Compiler for 64-bit apps' version_match = intel_version_match('EM64T-based|Intel\\(R\\) 64|64|IA-64|64-bit') possible_executables = ['ifort', 'efort', 'efc'] executables = { 'version_cmd' : None, 'compiler_f77' : [None, "-FI"], 'compiler_fix' : [None, "-FI"], 'compiler_f90' : [None], 'linker_so' : ['', "-shared"], 'archiver' : ["ar", "-cr"], 'ranlib' : ["ranlib"] } def get_flags(self): return ['-fPIC'] def get_flags_opt(self): #return ['-i8 -xhost -openmp -fp-model strict'] return ['-xhost -openmp -fp-model strict'] def get_flags_arch(self): return [] # Is there no difference in the version string between the above compilers # and the Visual compilers? class IntelVisualFCompiler(BaseIntelFCompiler): compiler_type = 'intelv' description = 'Intel Visual Fortran Compiler for 32-bit apps' version_match = intel_version_match('32-bit|IA-32') def update_executables(self): f = dummy_fortran_file() self.executables['version_cmd'] = ['', '/FI', '/c', f + '.f', '/o', f + '.o'] ar_exe = 'lib.exe' possible_executables = ['ifort', 'ifl'] executables = { 'version_cmd' : None, 'compiler_f77' : [None, "-FI", "-w90", "-w95"], 'compiler_fix' : [None, "-FI", "-4L72", "-w"], 'compiler_f90' : [None], 'linker_so' : ['', "-shared"], 'archiver' : [ar_exe, "/verbose", "/OUT:"], 'ranlib' : None } compile_switch = '/c ' object_switch = '/Fo' #No space after /Fo! library_switch = '/OUT:' #No space after /OUT:! module_dir_switch = '/module:' #No space after /module: module_include_switch = '/I' def get_flags(self): opt = ['/nologo', '/MD', '/nbs', '/Qlowercase', '/us'] return opt def get_flags_free(self): return ["-FR"] def get_flags_debug(self): return ['/4Yb', '/d2'] def get_flags_opt(self): return ['/O1'] # Scipy test failures with /O2 def get_flags_arch(self): return ["/arch:IA-32", "/QaxSSE3"] class IntelItaniumVisualFCompiler(IntelVisualFCompiler): compiler_type = 'intelev' description = 'Intel Visual Fortran Compiler for Itanium apps' version_match = intel_version_match('Itanium') possible_executables = ['efl'] # XXX this is a wild guess ar_exe = IntelVisualFCompiler.ar_exe executables = { 'version_cmd' : None, 'compiler_f77' : [None, "-FI", "-w90", "-w95"], 'compiler_fix' : [None, "-FI", "-4L72", "-w"], 'compiler_f90' : [None], 'linker_so' : ['', "-shared"], 'archiver' : [ar_exe, "/verbose", "/OUT:"], 'ranlib' : None } class IntelEM64VisualFCompiler(IntelVisualFCompiler): compiler_type = 'intelvem' description = 'Intel Visual Fortran Compiler for 64-bit apps' version_match = simple_version_match(start='Intel\(R\).*?64,') def get_flags_arch(self): return ["/arch:SSE2"] if __name__ == '__main__': from distutils import log log.set_verbosity(2) from numpy.distutils.fcompiler import new_fcompiler compiler = new_fcompiler(compiler='intel') compiler.customize() print(compiler.get_version()) numpy-1.8.2/numpy/distutils/fcompiler/gnu.py0000664000175100017510000003407212370216242022350 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function import re import os import sys import warnings import platform import tempfile from subprocess import Popen, PIPE, STDOUT from numpy.distutils.cpuinfo import cpu from numpy.distutils.fcompiler import FCompiler from numpy.distutils.exec_command import exec_command from numpy.distutils.misc_util import msvc_runtime_library from numpy.distutils.compat import get_exception compilers = ['GnuFCompiler', 'Gnu95FCompiler'] TARGET_R = re.compile("Target: ([a-zA-Z0-9_\-]*)") # XXX: handle cross compilation def is_win64(): return sys.platform == "win32" and platform.architecture()[0] == "64bit" if is_win64(): #_EXTRAFLAGS = ["-fno-leading-underscore"] _EXTRAFLAGS = [] else: _EXTRAFLAGS = [] class GnuFCompiler(FCompiler): compiler_type = 'gnu' compiler_aliases = ('g77',) description = 'GNU Fortran 77 compiler' def gnu_version_match(self, version_string): """Handle the different versions of GNU fortran compilers""" m = re.search(r'GNU Fortran', version_string) if not m: return None m = re.search(r'GNU Fortran\s+95.*?([0-9-.]+)', version_string) if m: return ('gfortran', m.group(1)) m = re.search(r'GNU Fortran.*?\-?([0-9-.]+)', version_string) if m: v = m.group(1) if v.startswith('0') or v.startswith('2') or v.startswith('3'): # the '0' is for early g77's return ('g77', v) else: # at some point in the 4.x series, the ' 95' was dropped # from the version string return ('gfortran', v) def version_match(self, version_string): v = self.gnu_version_match(version_string) if not v or v[0] != 'g77': return None return v[1] # 'g77 --version' results # SunOS: GNU Fortran (GCC 3.2) 3.2 20020814 (release) # Debian: GNU Fortran (GCC) 3.3.3 20040110 (prerelease) (Debian) # GNU Fortran (GCC) 3.3.3 (Debian 20040401) # GNU Fortran 0.5.25 20010319 (prerelease) # Redhat: GNU Fortran (GCC 3.2.2 20030222 (Red Hat Linux 3.2.2-5)) 3.2.2 20030222 (Red Hat Linux 3.2.2-5) # GNU Fortran (GCC) 3.4.2 (mingw-special) possible_executables = ['g77', 'f77'] executables = { 'version_cmd' : [None, "--version"], 'compiler_f77' : [None, "-g", "-Wall", "-fno-second-underscore"], 'compiler_f90' : None, # Use --fcompiler=gnu95 for f90 codes 'compiler_fix' : None, 'linker_so' : [None, "-g", "-Wall"], 'archiver' : ["ar", "-cr"], 'ranlib' : ["ranlib"], 'linker_exe' : [None, "-g", "-Wall"] } module_dir_switch = None module_include_switch = None # Cygwin: f771: warning: -fPIC ignored for target (all code is # position independent) if os.name != 'nt' and sys.platform != 'cygwin': pic_flags = ['-fPIC'] # use -mno-cygwin for g77 when Python is not Cygwin-Python if sys.platform == 'win32': for key in ['version_cmd', 'compiler_f77', 'linker_so', 'linker_exe']: executables[key].append('-mno-cygwin') g2c = 'g2c' suggested_f90_compiler = 'gnu95' #def get_linker_so(self): # # win32 linking should be handled by standard linker # # Darwin g77 cannot be used as a linker. # #if re.match(r'(darwin)', sys.platform): # # return # return FCompiler.get_linker_so(self) def get_flags_linker_so(self): opt = self.linker_so[1:] if sys.platform=='darwin': target = os.environ.get('MACOSX_DEPLOYMENT_TARGET', None) # If MACOSX_DEPLOYMENT_TARGET is set, we simply trust the value # and leave it alone. But, distutils will complain if the # environment's value is different from the one in the Python # Makefile used to build Python. We let disutils handle this # error checking. if not target: # If MACOSX_DEPLOYMENT_TARGET is not set in the environment, # we try to get it first from the Python Makefile and then we # fall back to setting it to 10.3 to maximize the set of # versions we can work with. This is a reasonable default # even when using the official Python dist and those derived # from it. import distutils.sysconfig as sc g = {} filename = sc.get_makefile_filename() sc.parse_makefile(filename, g) target = g.get('MACOSX_DEPLOYMENT_TARGET', '10.3') os.environ['MACOSX_DEPLOYMENT_TARGET'] = target if target == '10.3': s = 'Env. variable MACOSX_DEPLOYMENT_TARGET set to 10.3' warnings.warn(s) opt.extend(['-undefined', 'dynamic_lookup', '-bundle']) else: opt.append("-shared") if sys.platform.startswith('sunos'): # SunOS often has dynamically loaded symbols defined in the # static library libg2c.a The linker doesn't like this. To # ignore the problem, use the -mimpure-text flag. It isn't # the safest thing, but seems to work. 'man gcc' says: # ".. Instead of using -mimpure-text, you should compile all # source code with -fpic or -fPIC." opt.append('-mimpure-text') return opt def get_libgcc_dir(self): status, output = exec_command(self.compiler_f77 + ['-print-libgcc-file-name'], use_tee=0) if not status: return os.path.dirname(output) return None def get_library_dirs(self): opt = [] if sys.platform[:5] != 'linux': d = self.get_libgcc_dir() if d: # if windows and not cygwin, libg2c lies in a different folder if sys.platform == 'win32' and not d.startswith('/usr/lib'): d = os.path.normpath(d) if not os.path.exists(os.path.join(d, "lib%s.a" % self.g2c)): d2 = os.path.abspath(os.path.join(d, '../../../../lib')) if os.path.exists(os.path.join(d2, "lib%s.a" % self.g2c)): opt.append(d2) opt.append(d) return opt def get_libraries(self): opt = [] d = self.get_libgcc_dir() if d is not None: g2c = self.g2c + '-pic' f = self.static_lib_format % (g2c, self.static_lib_extension) if not os.path.isfile(os.path.join(d, f)): g2c = self.g2c else: g2c = self.g2c if g2c is not None: opt.append(g2c) c_compiler = self.c_compiler if sys.platform == 'win32' and c_compiler and \ c_compiler.compiler_type=='msvc': # the following code is not needed (read: breaks) when using MinGW # in case want to link F77 compiled code with MSVC opt.append('gcc') runtime_lib = msvc_runtime_library() if runtime_lib: opt.append(runtime_lib) if sys.platform == 'darwin': opt.append('cc_dynamic') return opt def get_flags_debug(self): return ['-g'] def get_flags_opt(self): v = self.get_version() if v and v<='3.3.3': # With this compiler version building Fortran BLAS/LAPACK # with -O3 caused failures in lib.lapack heevr,syevr tests. opt = ['-O2'] else: opt = ['-O3'] opt.append('-funroll-loops') return opt def _c_arch_flags(self): """ Return detected arch flags from CFLAGS """ from distutils import sysconfig try: cflags = sysconfig.get_config_vars()['CFLAGS'] except KeyError: return [] arch_re = re.compile(r"-arch\s+(\w+)") arch_flags = [] for arch in arch_re.findall(cflags): arch_flags += ['-arch', arch] return arch_flags def get_flags_arch(self): return [] class Gnu95FCompiler(GnuFCompiler): compiler_type = 'gnu95' compiler_aliases = ('gfortran',) description = 'GNU Fortran 95 compiler' def version_match(self, version_string): v = self.gnu_version_match(version_string) if not v or v[0] != 'gfortran': return None v = v[1] if v>='4.': # gcc-4 series releases do not support -mno-cygwin option pass else: # use -mno-cygwin flag for gfortran when Python is not Cygwin-Python if sys.platform == 'win32': for key in ['version_cmd', 'compiler_f77', 'compiler_f90', 'compiler_fix', 'linker_so', 'linker_exe']: self.executables[key].append('-mno-cygwin') return v # 'gfortran --version' results: # XXX is the below right? # Debian: GNU Fortran 95 (GCC 4.0.3 20051023 (prerelease) (Debian 4.0.2-3)) # GNU Fortran 95 (GCC) 4.1.2 20061115 (prerelease) (Debian 4.1.1-21) # OS X: GNU Fortran 95 (GCC) 4.1.0 # GNU Fortran 95 (GCC) 4.2.0 20060218 (experimental) # GNU Fortran (GCC) 4.3.0 20070316 (experimental) possible_executables = ['gfortran', 'f95'] executables = { 'version_cmd' : ["", "--version"], 'compiler_f77' : [None, "-Wall", "-ffixed-form", "-fno-second-underscore"] + _EXTRAFLAGS, 'compiler_f90' : [None, "-Wall", "-fno-second-underscore"] + _EXTRAFLAGS, 'compiler_fix' : [None, "-Wall", "-ffixed-form", "-fno-second-underscore"] + _EXTRAFLAGS, 'linker_so' : ["", "-Wall"], 'archiver' : ["ar", "-cr"], 'ranlib' : ["ranlib"], 'linker_exe' : [None, "-Wall"] } module_dir_switch = '-J' module_include_switch = '-I' g2c = 'gfortran' def _universal_flags(self, cmd): """Return a list of -arch flags for every supported architecture.""" if not sys.platform == 'darwin': return [] arch_flags = [] # get arches the C compiler gets. c_archs = self._c_arch_flags() if "i386" in c_archs: c_archs[c_archs.index("i386")] = "i686" # check the arches the Fortran compiler supports, and compare with # arch flags from C compiler for arch in ["ppc", "i686", "x86_64", "ppc64"]: if _can_target(cmd, arch) and arch in c_archs: arch_flags.extend(["-arch", arch]) return arch_flags def get_flags(self): flags = GnuFCompiler.get_flags(self) arch_flags = self._universal_flags(self.compiler_f90) if arch_flags: flags[:0] = arch_flags return flags def get_flags_linker_so(self): flags = GnuFCompiler.get_flags_linker_so(self) arch_flags = self._universal_flags(self.linker_so) if arch_flags: flags[:0] = arch_flags return flags def get_library_dirs(self): opt = GnuFCompiler.get_library_dirs(self) if sys.platform == 'win32': c_compiler = self.c_compiler if c_compiler and c_compiler.compiler_type == "msvc": target = self.get_target() if target: d = os.path.normpath(self.get_libgcc_dir()) root = os.path.join(d, os.pardir, os.pardir, os.pardir, os.pardir) mingwdir = os.path.normpath(os.path.join(root, target, "lib")) full = os.path.join(mingwdir, "libmingwex.a") if os.path.exists(full): opt.append(mingwdir) return opt def get_libraries(self): opt = GnuFCompiler.get_libraries(self) if sys.platform == 'darwin': opt.remove('cc_dynamic') if sys.platform == 'win32': c_compiler = self.c_compiler if c_compiler and c_compiler.compiler_type == "msvc": if "gcc" in opt: i = opt.index("gcc") opt.insert(i+1, "mingwex") opt.insert(i+1, "mingw32") # XXX: fix this mess, does not work for mingw if is_win64(): c_compiler = self.c_compiler if c_compiler and c_compiler.compiler_type == "msvc": return [] else: raise NotImplementedError("Only MS compiler supported with gfortran on win64") return opt def get_target(self): status, output = exec_command(self.compiler_f77 + ['-v'], use_tee=0) if not status: m = TARGET_R.search(output) if m: return m.group(1) return "" def get_flags_opt(self): if is_win64(): return ['-O0'] else: return GnuFCompiler.get_flags_opt(self) def _can_target(cmd, arch): """Return true is the command supports the -arch flag for the given architecture.""" newcmd = cmd[:] fid, filename = tempfile.mkstemp(suffix=".f") try: d = os.path.dirname(filename) output = os.path.splitext(filename)[0] + ".o" try: newcmd.extend(["-arch", arch, "-c", filename]) p = Popen(newcmd, stderr=STDOUT, stdout=PIPE, cwd=d) p.communicate() return p.returncode == 0 finally: if os.path.exists(output): os.remove(output) finally: os.remove(filename) return False if __name__ == '__main__': from distutils import log log.set_verbosity(2) compiler = GnuFCompiler() compiler.customize() print(compiler.get_version()) try: compiler = Gnu95FCompiler() compiler.customize() print(compiler.get_version()) except Exception: msg = get_exception() print(msg) numpy-1.8.2/numpy/distutils/fcompiler/pg.py0000664000175100017510000000350612370216242022163 0ustar vagrantvagrant00000000000000# http://www.pgroup.com from __future__ import division, absolute_import, print_function from numpy.distutils.fcompiler import FCompiler from sys import platform compilers = ['PGroupFCompiler'] class PGroupFCompiler(FCompiler): compiler_type = 'pg' description = 'Portland Group Fortran Compiler' version_pattern = r'\s*pg(f77|f90|hpf|fortran) (?P[\d.-]+).*' if platform == 'darwin': executables = { 'version_cmd' : ["", "-V"], 'compiler_f77' : ["pgfortran", "-dynamiclib"], 'compiler_fix' : ["pgfortran", "-Mfixed", "-dynamiclib"], 'compiler_f90' : ["pgfortran", "-dynamiclib"], 'linker_so' : ["libtool"], 'archiver' : ["ar", "-cr"], 'ranlib' : ["ranlib"] } pic_flags = [''] else: executables = { 'version_cmd' : ["", "-V"], 'compiler_f77' : ["pgfortran"], 'compiler_fix' : ["pgfortran", "-Mfixed"], 'compiler_f90' : ["pgfortran"], 'linker_so' : ["pgfortran", "-shared", "-fpic"], 'archiver' : ["ar", "-cr"], 'ranlib' : ["ranlib"] } pic_flags = ['-fpic'] module_dir_switch = '-module ' module_include_switch = '-I' def get_flags(self): opt = ['-Minform=inform', '-Mnosecond_underscore'] return self.pic_flags + opt def get_flags_opt(self): return ['-fast'] def get_flags_debug(self): return ['-g'] if platform == 'darwin': def get_flags_linker_so(self): return ["-dynamic", '-undefined', 'dynamic_lookup'] if __name__ == '__main__': from distutils import log log.set_verbosity(2) from numpy.distutils.fcompiler import new_fcompiler compiler = new_fcompiler(compiler='pg') compiler.customize() print(compiler.get_version()) numpy-1.8.2/numpy/distutils/fcompiler/none.py0000664000175100017510000000144212370216242022511 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function from numpy.distutils.fcompiler import FCompiler compilers = ['NoneFCompiler'] class NoneFCompiler(FCompiler): compiler_type = 'none' description = 'Fake Fortran compiler' executables = {'compiler_f77': None, 'compiler_f90': None, 'compiler_fix': None, 'linker_so': None, 'linker_exe': None, 'archiver': None, 'ranlib': None, 'version_cmd': None, } def find_executables(self): pass if __name__ == '__main__': from distutils import log log.set_verbosity(2) compiler = NoneFCompiler() compiler.customize() print(compiler.get_version()) numpy-1.8.2/numpy/distutils/fcompiler/absoft.py0000664000175100017510000001275412370216242023040 0ustar vagrantvagrant00000000000000 # http://www.absoft.com/literature/osxuserguide.pdf # http://www.absoft.com/documentation.html # Notes: # - when using -g77 then use -DUNDERSCORE_G77 to compile f2py # generated extension modules (works for f2py v2.45.241_1936 and up) from __future__ import division, absolute_import, print_function import os from numpy.distutils.cpuinfo import cpu from numpy.distutils.fcompiler import FCompiler, dummy_fortran_file from numpy.distutils.misc_util import cyg2win32 compilers = ['AbsoftFCompiler'] class AbsoftFCompiler(FCompiler): compiler_type = 'absoft' description = 'Absoft Corp Fortran Compiler' #version_pattern = r'FORTRAN 77 Compiler (?P[^\s*,]*).*?Absoft Corp' version_pattern = r'(f90:.*?(Absoft Pro FORTRAN Version|FORTRAN 77 Compiler|Absoft Fortran Compiler Version|Copyright Absoft Corporation.*?Version))'+\ r' (?P[^\s*,]*)(.*?Absoft Corp|)' # on windows: f90 -V -c dummy.f # f90: Copyright Absoft Corporation 1994-1998 mV2; Cray Research, Inc. 1994-1996 CF90 (2.x.x.x f36t87) Version 2.3 Wed Apr 19, 2006 13:05:16 # samt5735(8)$ f90 -V -c dummy.f # f90: Copyright Absoft Corporation 1994-2002; Absoft Pro FORTRAN Version 8.0 # Note that fink installs g77 as f77, so need to use f90 for detection. executables = { 'version_cmd' : None, # set by update_executables 'compiler_f77' : ["f77"], 'compiler_fix' : ["f90"], 'compiler_f90' : ["f90"], 'linker_so' : [""], 'archiver' : ["ar", "-cr"], 'ranlib' : ["ranlib"] } if os.name=='nt': library_switch = '/out:' #No space after /out:! module_dir_switch = None module_include_switch = '-p' def update_executables(self): f = cyg2win32(dummy_fortran_file()) self.executables['version_cmd'] = ['', '-V', '-c', f+'.f', '-o', f+'.o'] def get_flags_linker_so(self): if os.name=='nt': opt = ['/dll'] # The "-K shared" switches are being left in for pre-9.0 versions # of Absoft though I don't think versions earlier than 9 can # actually be used to build shared libraries. In fact, version # 8 of Absoft doesn't recognize "-K shared" and will fail. elif self.get_version() >= '9.0': opt = ['-shared'] else: opt = ["-K", "shared"] return opt def library_dir_option(self, dir): if os.name=='nt': return ['-link', '/PATH:"%s"' % (dir)] return "-L" + dir def library_option(self, lib): if os.name=='nt': return '%s.lib' % (lib) return "-l" + lib def get_library_dirs(self): opt = FCompiler.get_library_dirs(self) d = os.environ.get('ABSOFT') if d: if self.get_version() >= '10.0': # use shared libraries, the static libraries were not compiled -fPIC prefix = 'sh' else: prefix = '' if cpu.is_64bit(): suffix = '64' else: suffix = '' opt.append(os.path.join(d, '%slib%s' % (prefix, suffix))) return opt def get_libraries(self): opt = FCompiler.get_libraries(self) if self.get_version() >= '11.0': opt.extend(['af90math', 'afio', 'af77math', 'amisc']) elif self.get_version() >= '10.0': opt.extend(['af90math', 'afio', 'af77math', 'U77']) elif self.get_version() >= '8.0': opt.extend(['f90math', 'fio', 'f77math', 'U77']) else: opt.extend(['fio', 'f90math', 'fmath', 'U77']) if os.name =='nt': opt.append('COMDLG32') return opt def get_flags(self): opt = FCompiler.get_flags(self) if os.name != 'nt': opt.extend(['-s']) if self.get_version(): if self.get_version()>='8.2': opt.append('-fpic') return opt def get_flags_f77(self): opt = FCompiler.get_flags_f77(self) opt.extend(['-N22', '-N90', '-N110']) v = self.get_version() if os.name == 'nt': if v and v>='8.0': opt.extend(['-f', '-N15']) else: opt.append('-f') if v: if v<='4.6': opt.append('-B108') else: # Though -N15 is undocumented, it works with # Absoft 8.0 on Linux opt.append('-N15') return opt def get_flags_f90(self): opt = FCompiler.get_flags_f90(self) opt.extend(["-YCFRL=1", "-YCOM_NAMES=LCS", "-YCOM_PFX", "-YEXT_PFX", "-YCOM_SFX=_", "-YEXT_SFX=_", "-YEXT_NAMES=LCS"]) if self.get_version(): if self.get_version()>'4.6': opt.extend(["-YDEALLOC=ALL"]) return opt def get_flags_fix(self): opt = FCompiler.get_flags_fix(self) opt.extend(["-YCFRL=1", "-YCOM_NAMES=LCS", "-YCOM_PFX", "-YEXT_PFX", "-YCOM_SFX=_", "-YEXT_SFX=_", "-YEXT_NAMES=LCS"]) opt.extend(["-f", "fixed"]) return opt def get_flags_opt(self): opt = ['-O'] return opt if __name__ == '__main__': from distutils import log log.set_verbosity(2) from numpy.distutils.fcompiler import new_fcompiler compiler = new_fcompiler(compiler='absoft') compiler.customize() print(compiler.get_version()) numpy-1.8.2/numpy/distutils/fcompiler/sun.py0000664000175100017510000000311412370216242022355 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function from numpy.distutils.ccompiler import simple_version_match from numpy.distutils.fcompiler import FCompiler compilers = ['SunFCompiler'] class SunFCompiler(FCompiler): compiler_type = 'sun' description = 'Sun or Forte Fortran 95 Compiler' # ex: # f90: Sun WorkShop 6 update 2 Fortran 95 6.2 Patch 111690-10 2003/08/28 version_match = simple_version_match( start=r'f9[05]: (Sun|Forte|WorkShop).*Fortran 95') executables = { 'version_cmd' : ["", "-V"], 'compiler_f77' : ["f90"], 'compiler_fix' : ["f90", "-fixed"], 'compiler_f90' : ["f90"], 'linker_so' : ["", "-Bdynamic", "-G"], 'archiver' : ["ar", "-cr"], 'ranlib' : ["ranlib"] } module_dir_switch = '-moddir=' module_include_switch = '-M' pic_flags = ['-xcode=pic32'] def get_flags_f77(self): ret = ["-ftrap=%none"] if (self.get_version() or '') >= '7': ret.append("-f77") else: ret.append("-fixed") return ret def get_opt(self): return ['-fast', '-dalign'] def get_arch(self): return ['-xtarget=generic'] def get_libraries(self): opt = [] opt.extend(['fsu', 'sunmath', 'mvec']) return opt if __name__ == '__main__': from distutils import log log.set_verbosity(2) from numpy.distutils.fcompiler import new_fcompiler compiler = new_fcompiler(compiler='sun') compiler.customize() print(compiler.get_version()) numpy-1.8.2/numpy/distutils/fcompiler/hpux.py0000664000175100017510000000267012370216242022542 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function from numpy.distutils.fcompiler import FCompiler compilers = ['HPUXFCompiler'] class HPUXFCompiler(FCompiler): compiler_type = 'hpux' description = 'HP Fortran 90 Compiler' version_pattern = r'HP F90 (?P[^\s*,]*)' executables = { 'version_cmd' : ["f90", "+version"], 'compiler_f77' : ["f90"], 'compiler_fix' : ["f90"], 'compiler_f90' : ["f90"], 'linker_so' : ["ld", "-b"], 'archiver' : ["ar", "-cr"], 'ranlib' : ["ranlib"] } module_dir_switch = None #XXX: fix me module_include_switch = None #XXX: fix me pic_flags = ['+Z'] def get_flags(self): return self.pic_flags + ['+ppu', '+DD64'] def get_flags_opt(self): return ['-O3'] def get_libraries(self): return ['m'] def get_library_dirs(self): opt = ['/usr/lib/hpux64'] return opt def get_version(self, force=0, ok_status=[256, 0, 1]): # XXX status==256 may indicate 'unrecognized option' or # 'no input file'. So, version_cmd needs more work. return FCompiler.get_version(self, force, ok_status) if __name__ == '__main__': from distutils import log log.set_verbosity(10) from numpy.distutils.fcompiler import new_fcompiler compiler = new_fcompiler(compiler='hpux') compiler.customize() print(compiler.get_version()) numpy-1.8.2/numpy/distutils/fcompiler/mips.py0000664000175100017510000000344112370216242022523 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function from numpy.distutils.cpuinfo import cpu from numpy.distutils.fcompiler import FCompiler compilers = ['MIPSFCompiler'] class MIPSFCompiler(FCompiler): compiler_type = 'mips' description = 'MIPSpro Fortran Compiler' version_pattern = r'MIPSpro Compilers: Version (?P[^\s*,]*)' executables = { 'version_cmd' : ["", "-version"], 'compiler_f77' : ["f77", "-f77"], 'compiler_fix' : ["f90", "-fixedform"], 'compiler_f90' : ["f90"], 'linker_so' : ["f90", "-shared"], 'archiver' : ["ar", "-cr"], 'ranlib' : None } module_dir_switch = None #XXX: fix me module_include_switch = None #XXX: fix me pic_flags = ['-KPIC'] def get_flags(self): return self.pic_flags + ['-n32'] def get_flags_opt(self): return ['-O3'] def get_flags_arch(self): opt = [] for a in '19 20 21 22_4k 22_5k 24 25 26 27 28 30 32_5k 32_10k'.split(): if getattr(cpu, 'is_IP%s'%a)(): opt.append('-TARG:platform=IP%s' % a) break return opt def get_flags_arch_f77(self): r = None if cpu.is_r10000(): r = 10000 elif cpu.is_r12000(): r = 12000 elif cpu.is_r8000(): r = 8000 elif cpu.is_r5000(): r = 5000 elif cpu.is_r4000(): r = 4000 if r is not None: return ['r%s' % (r)] return [] def get_flags_arch_f90(self): r = self.get_flags_arch_f77() if r: r[0] = '-' + r[0] return r if __name__ == '__main__': from numpy.distutils.fcompiler import new_fcompiler compiler = new_fcompiler(compiler='mips') compiler.customize() print(compiler.get_version()) numpy-1.8.2/numpy/distutils/fcompiler/__init__.py0000664000175100017510000011252012370216243023312 0ustar vagrantvagrant00000000000000"""numpy.distutils.fcompiler Contains FCompiler, an abstract base class that defines the interface for the numpy.distutils Fortran compiler abstraction model. Terminology: To be consistent, where the term 'executable' is used, it means the single file, like 'gcc', that is executed, and should be a string. In contrast, 'command' means the entire command line, like ['gcc', '-c', 'file.c'], and should be a list. But note that FCompiler.executables is actually a dictionary of commands. """ from __future__ import division, absolute_import, print_function __all__ = ['FCompiler', 'new_fcompiler', 'show_fcompilers', 'dummy_fortran_file'] import os import sys import re import types try: set except NameError: from sets import Set as set from numpy.compat import open_latin1 from distutils.sysconfig import get_python_lib from distutils.fancy_getopt import FancyGetopt from distutils.errors import DistutilsModuleError, \ DistutilsExecError, CompileError, LinkError, DistutilsPlatformError from distutils.util import split_quoted, strtobool from numpy.distutils.ccompiler import CCompiler, gen_lib_options from numpy.distutils import log from numpy.distutils.misc_util import is_string, all_strings, is_sequence, \ make_temp_file, get_shared_lib_extension from numpy.distutils.environment import EnvironmentConfig from numpy.distutils.exec_command import find_executable from numpy.distutils.compat import get_exception __metaclass__ = type class CompilerNotFound(Exception): pass def flaglist(s): if is_string(s): return split_quoted(s) else: return s def str2bool(s): if is_string(s): return strtobool(s) return bool(s) def is_sequence_of_strings(seq): return is_sequence(seq) and all_strings(seq) class FCompiler(CCompiler): """Abstract base class to define the interface that must be implemented by real Fortran compiler classes. Methods that subclasses may redefine: update_executables(), find_executables(), get_version() get_flags(), get_flags_opt(), get_flags_arch(), get_flags_debug() get_flags_f77(), get_flags_opt_f77(), get_flags_arch_f77(), get_flags_debug_f77(), get_flags_f90(), get_flags_opt_f90(), get_flags_arch_f90(), get_flags_debug_f90(), get_flags_fix(), get_flags_linker_so() DON'T call these methods (except get_version) after constructing a compiler instance or inside any other method. All methods, except update_executables() and find_executables(), may call the get_version() method. After constructing a compiler instance, always call customize(dist=None) method that finalizes compiler construction and makes the following attributes available: compiler_f77 compiler_f90 compiler_fix linker_so archiver ranlib libraries library_dirs """ # These are the environment variables and distutils keys used. # Each configuration descripition is # (, , , ) # The hook names are handled by the self._environment_hook method. # - names starting with 'self.' call methods in this class # - names starting with 'exe.' return the key in the executables dict # - names like 'flags.YYY' return self.get_flag_YYY() # convert is either None or a function to convert a string to the # appropiate type used. distutils_vars = EnvironmentConfig( distutils_section='config_fc', noopt = (None, None, 'noopt', str2bool), noarch = (None, None, 'noarch', str2bool), debug = (None, None, 'debug', str2bool), verbose = (None, None, 'verbose', str2bool), ) command_vars = EnvironmentConfig( distutils_section='config_fc', compiler_f77 = ('exe.compiler_f77', 'F77', 'f77exec', None), compiler_f90 = ('exe.compiler_f90', 'F90', 'f90exec', None), compiler_fix = ('exe.compiler_fix', 'F90', 'f90exec', None), version_cmd = ('exe.version_cmd', None, None, None), linker_so = ('exe.linker_so', 'LDSHARED', 'ldshared', None), linker_exe = ('exe.linker_exe', 'LD', 'ld', None), archiver = (None, 'AR', 'ar', None), ranlib = (None, 'RANLIB', 'ranlib', None), ) flag_vars = EnvironmentConfig( distutils_section='config_fc', f77 = ('flags.f77', 'F77FLAGS', 'f77flags', flaglist), f90 = ('flags.f90', 'F90FLAGS', 'f90flags', flaglist), free = ('flags.free', 'FREEFLAGS', 'freeflags', flaglist), fix = ('flags.fix', None, None, flaglist), opt = ('flags.opt', 'FOPT', 'opt', flaglist), opt_f77 = ('flags.opt_f77', None, None, flaglist), opt_f90 = ('flags.opt_f90', None, None, flaglist), arch = ('flags.arch', 'FARCH', 'arch', flaglist), arch_f77 = ('flags.arch_f77', None, None, flaglist), arch_f90 = ('flags.arch_f90', None, None, flaglist), debug = ('flags.debug', 'FDEBUG', 'fdebug', flaglist), debug_f77 = ('flags.debug_f77', None, None, flaglist), debug_f90 = ('flags.debug_f90', None, None, flaglist), flags = ('self.get_flags', 'FFLAGS', 'fflags', flaglist), linker_so = ('flags.linker_so', 'LDFLAGS', 'ldflags', flaglist), linker_exe = ('flags.linker_exe', 'LDFLAGS', 'ldflags', flaglist), ar = ('flags.ar', 'ARFLAGS', 'arflags', flaglist), ) language_map = {'.f': 'f77', '.for': 'f77', '.F': 'f77', # XXX: needs preprocessor '.ftn': 'f77', '.f77': 'f77', '.f90': 'f90', '.F90': 'f90', # XXX: needs preprocessor '.f95': 'f90', } language_order = ['f90', 'f77'] # These will be set by the subclass compiler_type = None compiler_aliases = () version_pattern = None possible_executables = [] executables = { 'version_cmd': ["f77", "-v"], 'compiler_f77': ["f77"], 'compiler_f90': ["f90"], 'compiler_fix': ["f90", "-fixed"], 'linker_so': ["f90", "-shared"], 'linker_exe': ["f90"], 'archiver': ["ar", "-cr"], 'ranlib': None, } # If compiler does not support compiling Fortran 90 then it can # suggest using another compiler. For example, gnu would suggest # gnu95 compiler type when there are F90 sources. suggested_f90_compiler = None compile_switch = "-c" object_switch = "-o " # Ending space matters! It will be stripped # but if it is missing then object_switch # will be prefixed to object file name by # string concatenation. library_switch = "-o " # Ditto! # Switch to specify where module files are created and searched # for USE statement. Normally it is a string and also here ending # space matters. See above. module_dir_switch = None # Switch to specify where module files are searched for USE statement. module_include_switch = '-I' pic_flags = [] # Flags to create position-independent code src_extensions = ['.for', '.ftn', '.f77', '.f', '.f90', '.f95', '.F', '.F90'] obj_extension = ".o" shared_lib_extension = get_shared_lib_extension() static_lib_extension = ".a" # or .lib static_lib_format = "lib%s%s" # or %s%s shared_lib_format = "%s%s" exe_extension = "" _exe_cache = {} _executable_keys = ['version_cmd', 'compiler_f77', 'compiler_f90', 'compiler_fix', 'linker_so', 'linker_exe', 'archiver', 'ranlib'] # This will be set by new_fcompiler when called in # command/{build_ext.py, build_clib.py, config.py} files. c_compiler = None # extra_{f77,f90}_compile_args are set by build_ext.build_extension method extra_f77_compile_args = [] extra_f90_compile_args = [] def __init__(self, *args, **kw): CCompiler.__init__(self, *args, **kw) self.distutils_vars = self.distutils_vars.clone(self._environment_hook) self.command_vars = self.command_vars.clone(self._environment_hook) self.flag_vars = self.flag_vars.clone(self._environment_hook) self.executables = self.executables.copy() for e in self._executable_keys: if e not in self.executables: self.executables[e] = None # Some methods depend on .customize() being called first, so # this keeps track of whether that's happened yet. self._is_customised = False def __copy__(self): obj = self.__new__(self.__class__) obj.__dict__.update(self.__dict__) obj.distutils_vars = obj.distutils_vars.clone(obj._environment_hook) obj.command_vars = obj.command_vars.clone(obj._environment_hook) obj.flag_vars = obj.flag_vars.clone(obj._environment_hook) obj.executables = obj.executables.copy() return obj def copy(self): return self.__copy__() # Use properties for the attributes used by CCompiler. Setting them # as attributes from the self.executables dictionary is error-prone, # so we get them from there each time. def _command_property(key): def fget(self): assert self._is_customised return self.executables[key] return property(fget=fget) version_cmd = _command_property('version_cmd') compiler_f77 = _command_property('compiler_f77') compiler_f90 = _command_property('compiler_f90') compiler_fix = _command_property('compiler_fix') linker_so = _command_property('linker_so') linker_exe = _command_property('linker_exe') archiver = _command_property('archiver') ranlib = _command_property('ranlib') # Make our terminology consistent. def set_executable(self, key, value): self.set_command(key, value) def set_commands(self, **kw): for k, v in kw.items(): self.set_command(k, v) def set_command(self, key, value): if not key in self._executable_keys: raise ValueError( "unknown executable '%s' for class %s" % (key, self.__class__.__name__)) if is_string(value): value = split_quoted(value) assert value is None or is_sequence_of_strings(value[1:]), (key, value) self.executables[key] = value ###################################################################### ## Methods that subclasses may redefine. But don't call these methods! ## They are private to FCompiler class and may return unexpected ## results if used elsewhere. So, you have been warned.. def find_executables(self): """Go through the self.executables dictionary, and attempt to find and assign appropiate executables. Executable names are looked for in the environment (environment variables, the distutils.cfg, and command line), the 0th-element of the command list, and the self.possible_executables list. Also, if the 0th element is "" or "", the Fortran 77 or the Fortran 90 compiler executable is used, unless overridden by an environment setting. Subclasses should call this if overriden. """ assert self._is_customised exe_cache = self._exe_cache def cached_find_executable(exe): if exe in exe_cache: return exe_cache[exe] fc_exe = find_executable(exe) exe_cache[exe] = exe_cache[fc_exe] = fc_exe return fc_exe def verify_command_form(name, value): if value is not None and not is_sequence_of_strings(value): raise ValueError( "%s value %r is invalid in class %s" % (name, value, self.__class__.__name__)) def set_exe(exe_key, f77=None, f90=None): cmd = self.executables.get(exe_key, None) if not cmd: return None # Note that we get cmd[0] here if the environment doesn't # have anything set exe_from_environ = getattr(self.command_vars, exe_key) if not exe_from_environ: possibles = [f90, f77] + self.possible_executables else: possibles = [exe_from_environ] + self.possible_executables seen = set() unique_possibles = [] for e in possibles: if e == '': e = f77 elif e == '': e = f90 if not e or e in seen: continue seen.add(e) unique_possibles.append(e) for exe in unique_possibles: fc_exe = cached_find_executable(exe) if fc_exe: cmd[0] = fc_exe return fc_exe self.set_command(exe_key, None) return None ctype = self.compiler_type f90 = set_exe('compiler_f90') if not f90: f77 = set_exe('compiler_f77') if f77: log.warn('%s: no Fortran 90 compiler found' % ctype) else: raise CompilerNotFound('%s: f90 nor f77' % ctype) else: f77 = set_exe('compiler_f77', f90=f90) if not f77: log.warn('%s: no Fortran 77 compiler found' % ctype) set_exe('compiler_fix', f90=f90) set_exe('linker_so', f77=f77, f90=f90) set_exe('linker_exe', f77=f77, f90=f90) set_exe('version_cmd', f77=f77, f90=f90) set_exe('archiver') set_exe('ranlib') def update_executables(elf): """Called at the beginning of customisation. Subclasses should override this if they need to set up the executables dictionary. Note that self.find_executables() is run afterwards, so the self.executables dictionary values can contain or as the command, which will be replaced by the found F77 or F90 compiler. """ pass def get_flags(self): """List of flags common to all compiler types.""" return [] + self.pic_flags def _get_command_flags(self, key): cmd = self.executables.get(key, None) if cmd is None: return [] return cmd[1:] def get_flags_f77(self): """List of Fortran 77 specific flags.""" return self._get_command_flags('compiler_f77') def get_flags_f90(self): """List of Fortran 90 specific flags.""" return self._get_command_flags('compiler_f90') def get_flags_free(self): """List of Fortran 90 free format specific flags.""" return [] def get_flags_fix(self): """List of Fortran 90 fixed format specific flags.""" return self._get_command_flags('compiler_fix') def get_flags_linker_so(self): """List of linker flags to build a shared library.""" return self._get_command_flags('linker_so') def get_flags_linker_exe(self): """List of linker flags to build an executable.""" return self._get_command_flags('linker_exe') def get_flags_ar(self): """List of archiver flags. """ return self._get_command_flags('archiver') def get_flags_opt(self): """List of architecture independent compiler flags.""" return [] def get_flags_arch(self): """List of architecture dependent compiler flags.""" return [] def get_flags_debug(self): """List of compiler flags to compile with debugging information.""" return [] get_flags_opt_f77 = get_flags_opt_f90 = get_flags_opt get_flags_arch_f77 = get_flags_arch_f90 = get_flags_arch get_flags_debug_f77 = get_flags_debug_f90 = get_flags_debug def get_libraries(self): """List of compiler libraries.""" return self.libraries[:] def get_library_dirs(self): """List of compiler library directories.""" return self.library_dirs[:] def get_version(self, force=False, ok_status=[0]): assert self._is_customised version = CCompiler.get_version(self, force=force, ok_status=ok_status) if version is None: raise CompilerNotFound() return version ############################################################ ## Public methods: def customize(self, dist = None): """Customize Fortran compiler. This method gets Fortran compiler specific information from (i) class definition, (ii) environment, (iii) distutils config files, and (iv) command line (later overrides earlier). This method should be always called after constructing a compiler instance. But not in __init__ because Distribution instance is needed for (iii) and (iv). """ log.info('customize %s' % (self.__class__.__name__)) self._is_customised = True self.distutils_vars.use_distribution(dist) self.command_vars.use_distribution(dist) self.flag_vars.use_distribution(dist) self.update_executables() # find_executables takes care of setting the compiler commands, # version_cmd, linker_so, linker_exe, ar, and ranlib self.find_executables() noopt = self.distutils_vars.get('noopt', False) noarch = self.distutils_vars.get('noarch', noopt) debug = self.distutils_vars.get('debug', False) f77 = self.command_vars.compiler_f77 f90 = self.command_vars.compiler_f90 f77flags = [] f90flags = [] freeflags = [] fixflags = [] if f77: f77flags = self.flag_vars.f77 if f90: f90flags = self.flag_vars.f90 freeflags = self.flag_vars.free # XXX Assuming that free format is default for f90 compiler. fix = self.command_vars.compiler_fix if fix: fixflags = self.flag_vars.fix + f90flags oflags, aflags, dflags = [], [], [] # examine get_flags__ for extra flags # only add them if the method is different from get_flags_ def get_flags(tag, flags): # note that self.flag_vars. calls self.get_flags_() flags.extend(getattr(self.flag_vars, tag)) this_get = getattr(self, 'get_flags_' + tag) for name, c, flagvar in [('f77', f77, f77flags), ('f90', f90, f90flags), ('f90', fix, fixflags)]: t = '%s_%s' % (tag, name) if c and this_get is not getattr(self, 'get_flags_' + t): flagvar.extend(getattr(self.flag_vars, t)) if not noopt: get_flags('opt', oflags) if not noarch: get_flags('arch', aflags) if debug: get_flags('debug', dflags) fflags = self.flag_vars.flags + dflags + oflags + aflags if f77: self.set_commands(compiler_f77=[f77]+f77flags+fflags) if f90: self.set_commands(compiler_f90=[f90]+freeflags+f90flags+fflags) if fix: self.set_commands(compiler_fix=[fix]+fixflags+fflags) #XXX: Do we need LDSHARED->SOSHARED, LDFLAGS->SOFLAGS linker_so = self.linker_so if linker_so: linker_so_flags = self.flag_vars.linker_so if sys.platform.startswith('aix'): python_lib = get_python_lib(standard_lib=1) ld_so_aix = os.path.join(python_lib, 'config', 'ld_so_aix') python_exp = os.path.join(python_lib, 'config', 'python.exp') linker_so = [ld_so_aix] + linker_so + ['-bI:'+python_exp] self.set_commands(linker_so=linker_so+linker_so_flags) linker_exe = self.linker_exe if linker_exe: linker_exe_flags = self.flag_vars.linker_exe self.set_commands(linker_exe=linker_exe+linker_exe_flags) ar = self.command_vars.archiver if ar: arflags = self.flag_vars.ar self.set_commands(archiver=[ar]+arflags) self.set_library_dirs(self.get_library_dirs()) self.set_libraries(self.get_libraries()) def dump_properties(self): """Print out the attributes of a compiler instance.""" props = [] for key in list(self.executables.keys()) + \ ['version', 'libraries', 'library_dirs', 'object_switch', 'compile_switch']: if hasattr(self, key): v = getattr(self, key) props.append((key, None, '= '+repr(v))) props.sort() pretty_printer = FancyGetopt(props) for l in pretty_printer.generate_help("%s instance properties:" \ % (self.__class__.__name__)): if l[:4]==' --': l = ' ' + l[4:] print(l) ################### def _compile(self, obj, src, ext, cc_args, extra_postargs, pp_opts): """Compile 'src' to product 'obj'.""" src_flags = {} if is_f_file(src) and not has_f90_header(src): flavor = ':f77' compiler = self.compiler_f77 src_flags = get_f77flags(src) extra_compile_args = self.extra_f77_compile_args or [] elif is_free_format(src): flavor = ':f90' compiler = self.compiler_f90 if compiler is None: raise DistutilsExecError('f90 not supported by %s needed for %s'\ % (self.__class__.__name__, src)) extra_compile_args = self.extra_f90_compile_args or [] else: flavor = ':fix' compiler = self.compiler_fix if compiler is None: raise DistutilsExecError('f90 (fixed) not supported by %s needed for %s'\ % (self.__class__.__name__, src)) extra_compile_args = self.extra_f90_compile_args or [] if self.object_switch[-1]==' ': o_args = [self.object_switch.strip(), obj] else: o_args = [self.object_switch.strip()+obj] assert self.compile_switch.strip() s_args = [self.compile_switch, src] if extra_compile_args: log.info('extra %s options: %r' \ % (flavor[1:], ' '.join(extra_compile_args))) extra_flags = src_flags.get(self.compiler_type, []) if extra_flags: log.info('using compile options from source: %r' \ % ' '.join(extra_flags)) command = compiler + cc_args + extra_flags + s_args + o_args \ + extra_postargs + extra_compile_args display = '%s: %s' % (os.path.basename(compiler[0]) + flavor, src) try: self.spawn(command, display=display) except DistutilsExecError: msg = str(get_exception()) raise CompileError(msg) def module_options(self, module_dirs, module_build_dir): options = [] if self.module_dir_switch is not None: if self.module_dir_switch[-1]==' ': options.extend([self.module_dir_switch.strip(), module_build_dir]) else: options.append(self.module_dir_switch.strip()+module_build_dir) else: print('XXX: module_build_dir=%r option ignored' % (module_build_dir)) print('XXX: Fix module_dir_switch for ', self.__class__.__name__) if self.module_include_switch is not None: for d in [module_build_dir]+module_dirs: options.append('%s%s' % (self.module_include_switch, d)) else: print('XXX: module_dirs=%r option ignored' % (module_dirs)) print('XXX: Fix module_include_switch for ', self.__class__.__name__) return options def library_option(self, lib): return "-l" + lib def library_dir_option(self, dir): return "-L" + dir def link(self, target_desc, objects, output_filename, output_dir=None, libraries=None, library_dirs=None, runtime_library_dirs=None, export_symbols=None, debug=0, extra_preargs=None, extra_postargs=None, build_temp=None, target_lang=None): objects, output_dir = self._fix_object_args(objects, output_dir) libraries, library_dirs, runtime_library_dirs = \ self._fix_lib_args(libraries, library_dirs, runtime_library_dirs) lib_opts = gen_lib_options(self, library_dirs, runtime_library_dirs, libraries) if is_string(output_dir): output_filename = os.path.join(output_dir, output_filename) elif output_dir is not None: raise TypeError("'output_dir' must be a string or None") if self._need_link(objects, output_filename): if self.library_switch[-1]==' ': o_args = [self.library_switch.strip(), output_filename] else: o_args = [self.library_switch.strip()+output_filename] if is_string(self.objects): ld_args = objects + [self.objects] else: ld_args = objects + self.objects ld_args = ld_args + lib_opts + o_args if debug: ld_args[:0] = ['-g'] if extra_preargs: ld_args[:0] = extra_preargs if extra_postargs: ld_args.extend(extra_postargs) self.mkpath(os.path.dirname(output_filename)) if target_desc == CCompiler.EXECUTABLE: linker = self.linker_exe[:] else: linker = self.linker_so[:] command = linker + ld_args try: self.spawn(command) except DistutilsExecError: msg = str(get_exception()) raise LinkError(msg) else: log.debug("skipping %s (up-to-date)", output_filename) def _environment_hook(self, name, hook_name): if hook_name is None: return None if is_string(hook_name): if hook_name.startswith('self.'): hook_name = hook_name[5:] hook = getattr(self, hook_name) return hook() elif hook_name.startswith('exe.'): hook_name = hook_name[4:] var = self.executables[hook_name] if var: return var[0] else: return None elif hook_name.startswith('flags.'): hook_name = hook_name[6:] hook = getattr(self, 'get_flags_' + hook_name) return hook() else: return hook_name() ## class FCompiler _default_compilers = ( # sys.platform mappings ('win32', ('gnu', 'intelv', 'absoft', 'compaqv', 'intelev', 'gnu95', 'g95', 'intelvem', 'intelem')), ('cygwin.*', ('gnu', 'intelv', 'absoft', 'compaqv', 'intelev', 'gnu95', 'g95')), ('linux.*', ('gnu95', 'intel', 'lahey', 'pg', 'absoft', 'nag', 'vast', 'compaq', 'intele', 'intelem', 'gnu', 'g95', 'pathf95')), ('darwin.*', ('gnu95', 'nag', 'absoft', 'ibm', 'intel', 'gnu', 'g95', 'pg')), ('sunos.*', ('sun', 'gnu', 'gnu95', 'g95')), ('irix.*', ('mips', 'gnu', 'gnu95',)), ('aix.*', ('ibm', 'gnu', 'gnu95',)), # os.name mappings ('posix', ('gnu', 'gnu95',)), ('nt', ('gnu', 'gnu95',)), ('mac', ('gnu95', 'gnu', 'pg')), ) fcompiler_class = None fcompiler_aliases = None def load_all_fcompiler_classes(): """Cache all the FCompiler classes found in modules in the numpy.distutils.fcompiler package. """ from glob import glob global fcompiler_class, fcompiler_aliases if fcompiler_class is not None: return pys = os.path.join(os.path.dirname(__file__), '*.py') fcompiler_class = {} fcompiler_aliases = {} for fname in glob(pys): module_name, ext = os.path.splitext(os.path.basename(fname)) module_name = 'numpy.distutils.fcompiler.' + module_name __import__ (module_name) module = sys.modules[module_name] if hasattr(module, 'compilers'): for cname in module.compilers: klass = getattr(module, cname) desc = (klass.compiler_type, klass, klass.description) fcompiler_class[klass.compiler_type] = desc for alias in klass.compiler_aliases: if alias in fcompiler_aliases: raise ValueError("alias %r defined for both %s and %s" % (alias, klass.__name__, fcompiler_aliases[alias][1].__name__)) fcompiler_aliases[alias] = desc def _find_existing_fcompiler(compiler_types, osname=None, platform=None, requiref90=False, c_compiler=None): from numpy.distutils.core import get_distribution dist = get_distribution(always=True) for compiler_type in compiler_types: v = None try: c = new_fcompiler(plat=platform, compiler=compiler_type, c_compiler=c_compiler) c.customize(dist) v = c.get_version() if requiref90 and c.compiler_f90 is None: v = None new_compiler = c.suggested_f90_compiler if new_compiler: log.warn('Trying %r compiler as suggested by %r ' 'compiler for f90 support.' % (compiler_type, new_compiler)) c = new_fcompiler(plat=platform, compiler=new_compiler, c_compiler=c_compiler) c.customize(dist) v = c.get_version() if v is not None: compiler_type = new_compiler if requiref90 and c.compiler_f90 is None: raise ValueError('%s does not support compiling f90 codes, ' 'skipping.' % (c.__class__.__name__)) except DistutilsModuleError: log.debug("_find_existing_fcompiler: compiler_type='%s' raised DistutilsModuleError", compiler_type) except CompilerNotFound: log.debug("_find_existing_fcompiler: compiler_type='%s' not found", compiler_type) if v is not None: return compiler_type return None def available_fcompilers_for_platform(osname=None, platform=None): if osname is None: osname = os.name if platform is None: platform = sys.platform matching_compiler_types = [] for pattern, compiler_type in _default_compilers: if re.match(pattern, platform) or re.match(pattern, osname): for ct in compiler_type: if ct not in matching_compiler_types: matching_compiler_types.append(ct) if not matching_compiler_types: matching_compiler_types.append('gnu') return matching_compiler_types def get_default_fcompiler(osname=None, platform=None, requiref90=False, c_compiler=None): """Determine the default Fortran compiler to use for the given platform.""" matching_compiler_types = available_fcompilers_for_platform(osname, platform) compiler_type = _find_existing_fcompiler(matching_compiler_types, osname=osname, platform=platform, requiref90=requiref90, c_compiler=c_compiler) return compiler_type # Flag to avoid rechecking for Fortran compiler every time failed_fcompiler = False def new_fcompiler(plat=None, compiler=None, verbose=0, dry_run=0, force=0, requiref90=False, c_compiler = None): """Generate an instance of some FCompiler subclass for the supplied platform/compiler combination. """ global failed_fcompiler if failed_fcompiler: return None load_all_fcompiler_classes() if plat is None: plat = os.name if compiler is None: compiler = get_default_fcompiler(plat, requiref90=requiref90, c_compiler=c_compiler) if compiler in fcompiler_class: module_name, klass, long_description = fcompiler_class[compiler] elif compiler in fcompiler_aliases: module_name, klass, long_description = fcompiler_aliases[compiler] else: msg = "don't know how to compile Fortran code on platform '%s'" % plat if compiler is not None: msg = msg + " with '%s' compiler." % compiler msg = msg + " Supported compilers are: %s)" \ % (','.join(fcompiler_class.keys())) log.warn(msg) failed_fcompiler = True return None compiler = klass(verbose=verbose, dry_run=dry_run, force=force) compiler.c_compiler = c_compiler return compiler def show_fcompilers(dist=None): """Print list of available compilers (used by the "--help-fcompiler" option to "config_fc"). """ if dist is None: from distutils.dist import Distribution from numpy.distutils.command.config_compiler import config_fc dist = Distribution() dist.script_name = os.path.basename(sys.argv[0]) dist.script_args = ['config_fc'] + sys.argv[1:] try: dist.script_args.remove('--help-fcompiler') except ValueError: pass dist.cmdclass['config_fc'] = config_fc dist.parse_config_files() dist.parse_command_line() compilers = [] compilers_na = [] compilers_ni = [] if not fcompiler_class: load_all_fcompiler_classes() platform_compilers = available_fcompilers_for_platform() for compiler in platform_compilers: v = None log.set_verbosity(-2) try: c = new_fcompiler(compiler=compiler, verbose=dist.verbose) c.customize(dist) v = c.get_version() except (DistutilsModuleError, CompilerNotFound): e = get_exception() log.debug("show_fcompilers: %s not found" % (compiler,)) log.debug(repr(e)) if v is None: compilers_na.append(("fcompiler="+compiler, None, fcompiler_class[compiler][2])) else: c.dump_properties() compilers.append(("fcompiler="+compiler, None, fcompiler_class[compiler][2] + ' (%s)' % v)) compilers_ni = list(set(fcompiler_class.keys()) - set(platform_compilers)) compilers_ni = [("fcompiler="+fc, None, fcompiler_class[fc][2]) for fc in compilers_ni] compilers.sort() compilers_na.sort() compilers_ni.sort() pretty_printer = FancyGetopt(compilers) pretty_printer.print_help("Fortran compilers found:") pretty_printer = FancyGetopt(compilers_na) pretty_printer.print_help("Compilers available for this " "platform, but not found:") if compilers_ni: pretty_printer = FancyGetopt(compilers_ni) pretty_printer.print_help("Compilers not available on this platform:") print("For compiler details, run 'config_fc --verbose' setup command.") def dummy_fortran_file(): fo, name = make_temp_file(suffix='.f') fo.write(" subroutine dummy()\n end\n") fo.close() return name[:-2] is_f_file = re.compile(r'.*[.](for|ftn|f77|f)\Z', re.I).match _has_f_header = re.compile(r'-[*]-\s*fortran\s*-[*]-', re.I).search _has_f90_header = re.compile(r'-[*]-\s*f90\s*-[*]-', re.I).search _has_fix_header = re.compile(r'-[*]-\s*fix\s*-[*]-', re.I).search _free_f90_start = re.compile(r'[^c*!]\s*[^\s\d\t]', re.I).match def is_free_format(file): """Check if file is in free format Fortran.""" # f90 allows both fixed and free format, assuming fixed unless # signs of free format are detected. result = 0 f = open_latin1(file, 'r') line = f.readline() n = 10000 # the number of non-comment lines to scan for hints if _has_f_header(line): n = 0 elif _has_f90_header(line): n = 0 result = 1 while n>0 and line: line = line.rstrip() if line and line[0]!='!': n -= 1 if (line[0]!='\t' and _free_f90_start(line[:5])) or line[-1:]=='&': result = 1 break line = f.readline() f.close() return result def has_f90_header(src): f = open_latin1(src, 'r') line = f.readline() f.close() return _has_f90_header(line) or _has_fix_header(line) _f77flags_re = re.compile(r'(c|)f77flags\s*\(\s*(?P\w+)\s*\)\s*=\s*(?P.*)', re.I) def get_f77flags(src): """ Search the first 20 lines of fortran 77 code for line pattern `CF77FLAGS()=` Return a dictionary {:}. """ flags = {} f = open_latin1(src, 'r') i = 0 for line in f: i += 1 if i>20: break m = _f77flags_re.match(line) if not m: continue fcname = m.group('fcname').strip() fflags = m.group('fflags').strip() flags[fcname] = split_quoted(fflags) f.close() return flags # TODO: implement get_f90flags and use it in _compile similarly to get_f77flags if __name__ == '__main__': show_fcompilers() numpy-1.8.2/numpy/distutils/fcompiler/nag.py0000664000175100017510000000257312370216242022325 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function import sys from numpy.distutils.fcompiler import FCompiler compilers = ['NAGFCompiler'] class NAGFCompiler(FCompiler): compiler_type = 'nag' description = 'NAGWare Fortran 95 Compiler' version_pattern = r'NAGWare Fortran 95 compiler Release (?P[^\s]*)' executables = { 'version_cmd' : ["", "-V"], 'compiler_f77' : ["f95", "-fixed"], 'compiler_fix' : ["f95", "-fixed"], 'compiler_f90' : ["f95"], 'linker_so' : [""], 'archiver' : ["ar", "-cr"], 'ranlib' : ["ranlib"] } def get_flags_linker_so(self): if sys.platform=='darwin': return ['-unsharedf95', '-Wl,-bundle,-flat_namespace,-undefined,suppress'] return ["-Wl,-shared"] def get_flags_opt(self): return ['-O4'] def get_flags_arch(self): version = self.get_version() if version and version < '5.1': return ['-target=native'] else: return [''] def get_flags_debug(self): return ['-g', '-gline', '-g90', '-nan', '-C'] if __name__ == '__main__': from distutils import log log.set_verbosity(2) from numpy.distutils.fcompiler import new_fcompiler compiler = new_fcompiler(compiler='nag') compiler.customize() print(compiler.get_version()) numpy-1.8.2/numpy/distutils/fcompiler/g95.py0000664000175100017510000000254312370216242022161 0ustar vagrantvagrant00000000000000# http://g95.sourceforge.net/ from __future__ import division, absolute_import, print_function from numpy.distutils.fcompiler import FCompiler compilers = ['G95FCompiler'] class G95FCompiler(FCompiler): compiler_type = 'g95' description = 'G95 Fortran Compiler' # version_pattern = r'G95 \((GCC (?P[\d.]+)|.*?) \(g95!\) (?P.*)\).*' # $ g95 --version # G95 (GCC 4.0.3 (g95!) May 22 2006) version_pattern = r'G95 \((GCC (?P[\d.]+)|.*?) \(g95 (?P.*)!\) (?P.*)\).*' # $ g95 --version # G95 (GCC 4.0.3 (g95 0.90!) Aug 22 2006) executables = { 'version_cmd' : ["", "--version"], 'compiler_f77' : ["g95", "-ffixed-form"], 'compiler_fix' : ["g95", "-ffixed-form"], 'compiler_f90' : ["g95"], 'linker_so' : ["", "-shared"], 'archiver' : ["ar", "-cr"], 'ranlib' : ["ranlib"] } pic_flags = ['-fpic'] module_dir_switch = '-fmod=' module_include_switch = '-I' def get_flags(self): return ['-fno-second-underscore'] def get_flags_opt(self): return ['-O'] def get_flags_debug(self): return ['-g'] if __name__ == '__main__': from distutils import log log.set_verbosity(2) compiler = G95FCompiler() compiler.customize() print(compiler.get_version()) numpy-1.8.2/numpy/distutils/fcompiler/pathf95.py0000664000175100017510000000227112370216242023033 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function from numpy.distutils.fcompiler import FCompiler compilers = ['PathScaleFCompiler'] class PathScaleFCompiler(FCompiler): compiler_type = 'pathf95' description = 'PathScale Fortran Compiler' version_pattern = r'PathScale\(TM\) Compiler Suite: Version (?P[\d.]+)' executables = { 'version_cmd' : ["pathf95", "-version"], 'compiler_f77' : ["pathf95", "-fixedform"], 'compiler_fix' : ["pathf95", "-fixedform"], 'compiler_f90' : ["pathf95"], 'linker_so' : ["pathf95", "-shared"], 'archiver' : ["ar", "-cr"], 'ranlib' : ["ranlib"] } pic_flags = ['-fPIC'] module_dir_switch = '-module ' # Don't remove ending space! module_include_switch = '-I' def get_flags_opt(self): return ['-O3'] def get_flags_debug(self): return ['-g'] if __name__ == '__main__': from distutils import log log.set_verbosity(2) #compiler = PathScaleFCompiler() from numpy.distutils.fcompiler import new_fcompiler compiler = new_fcompiler(compiler='pathf95') compiler.customize() print(compiler.get_version()) numpy-1.8.2/numpy/distutils/fcompiler/lahey.py0000664000175100017510000000263612370216242022662 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function import os from numpy.distutils.fcompiler import FCompiler compilers = ['LaheyFCompiler'] class LaheyFCompiler(FCompiler): compiler_type = 'lahey' description = 'Lahey/Fujitsu Fortran 95 Compiler' version_pattern = r'Lahey/Fujitsu Fortran 95 Compiler Release (?P[^\s*]*)' executables = { 'version_cmd' : ["", "--version"], 'compiler_f77' : ["lf95", "--fix"], 'compiler_fix' : ["lf95", "--fix"], 'compiler_f90' : ["lf95"], 'linker_so' : ["lf95", "-shared"], 'archiver' : ["ar", "-cr"], 'ranlib' : ["ranlib"] } module_dir_switch = None #XXX Fix me module_include_switch = None #XXX Fix me def get_flags_opt(self): return ['-O'] def get_flags_debug(self): return ['-g', '--chk', '--chkglobal'] def get_library_dirs(self): opt = [] d = os.environ.get('LAHEY') if d: opt.append(os.path.join(d, 'lib')) return opt def get_libraries(self): opt = [] opt.extend(['fj9f6', 'fj9i6', 'fj9ipp', 'fj9e6']) return opt if __name__ == '__main__': from distutils import log log.set_verbosity(2) from numpy.distutils.fcompiler import new_fcompiler compiler = new_fcompiler(compiler='lahey') compiler.customize() print(compiler.get_version()) numpy-1.8.2/numpy/distutils/mingw/0000775000175100017510000000000012371375430020346 5ustar vagrantvagrant00000000000000numpy-1.8.2/numpy/distutils/mingw/gfortran_vs2003_hack.c0000664000175100017510000000011212370216242024323 0ustar vagrantvagrant00000000000000int _get_output_format(void) { return 0; } int _imp____lc_codepage = 0; numpy-1.8.2/numpy/distutils/misc_util.py0000664000175100017510000023521212370216243021567 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function import os import re import sys import imp import copy import glob import atexit import tempfile import subprocess import shutil import distutils from distutils.errors import DistutilsError try: set except NameError: from sets import Set as set from numpy.distutils.compat import get_exception __all__ = ['Configuration', 'get_numpy_include_dirs', 'default_config_dict', 'dict_append', 'appendpath', 'generate_config_py', 'get_cmd', 'allpath', 'get_mathlibs', 'terminal_has_colors', 'red_text', 'green_text', 'yellow_text', 'blue_text', 'cyan_text', 'cyg2win32', 'mingw32', 'all_strings', 'has_f_sources', 'has_cxx_sources', 'filter_sources', 'get_dependencies', 'is_local_src_dir', 'get_ext_source_files', 'get_script_files', 'get_lib_source_files', 'get_data_files', 'dot_join', 'get_frame', 'minrelpath', 'njoin', 'is_sequence', 'is_string', 'as_list', 'gpaths', 'get_language', 'quote_args', 'get_build_architecture', 'get_info', 'get_pkg_info'] class InstallableLib(object): """ Container to hold information on an installable library. Parameters ---------- name : str Name of the installed library. build_info : dict Dictionary holding build information. target_dir : str Absolute path specifying where to install the library. See Also -------- Configuration.add_installed_library Notes ----- The three parameters are stored as attributes with the same names. """ def __init__(self, name, build_info, target_dir): self.name = name self.build_info = build_info self.target_dir = target_dir def quote_args(args): # don't used _nt_quote_args as it does not check if # args items already have quotes or not. args = list(args) for i in range(len(args)): a = args[i] if ' ' in a and a[0] not in '"\'': args[i] = '"%s"' % (a) return args def allpath(name): "Convert a /-separated pathname to one using the OS's path separator." splitted = name.split('/') return os.path.join(*splitted) def rel_path(path, parent_path): """Return path relative to parent_path. """ pd = os.path.abspath(parent_path) apath = os.path.abspath(path) if len(apath)= 0 and curses.tigetnum("pairs") >= 0 and ((curses.tigetstr("setf") is not None and curses.tigetstr("setb") is not None) or (curses.tigetstr("setaf") is not None and curses.tigetstr("setab") is not None) or curses.tigetstr("scp") is not None)): return 1 except Exception: pass return 0 if terminal_has_colors(): _colour_codes = dict(black=0, red=1, green=2, yellow=3, blue=4, magenta=5, cyan=6, white=7, default=9) def colour_text(s, fg=None, bg=None, bold=False): seq = [] if bold: seq.append('1') if fg: fgcode = 30 + _colour_codes.get(fg.lower(), 0) seq.append(str(fgcode)) if bg: bgcode = 40 + _colour_codes.get(fg.lower(), 7) seq.append(str(bgcode)) if seq: return '\x1b[%sm%s\x1b[0m' % (';'.join(seq), s) else: return s else: def colour_text(s, fg=None, bg=None): return s def default_text(s): return colour_text(s, 'default') def red_text(s): return colour_text(s, 'red') def green_text(s): return colour_text(s, 'green') def yellow_text(s): return colour_text(s, 'yellow') def cyan_text(s): return colour_text(s, 'cyan') def blue_text(s): return colour_text(s, 'blue') ######################### def cyg2win32(path): if sys.platform=='cygwin' and path.startswith('/cygdrive'): path = path[10] + ':' + os.path.normcase(path[11:]) return path def mingw32(): """Return true when using mingw32 environment. """ if sys.platform=='win32': if os.environ.get('OSTYPE', '')=='msys': return True if os.environ.get('MSYSTEM', '')=='MINGW32': return True return False def msvc_runtime_library(): "Return name of MSVC runtime library if Python was built with MSVC >= 7" msc_pos = sys.version.find('MSC v.') if msc_pos != -1: msc_ver = sys.version[msc_pos+6:msc_pos+10] lib = {'1300': 'msvcr70', # MSVC 7.0 '1310': 'msvcr71', # MSVC 7.1 '1400': 'msvcr80', # MSVC 8 '1500': 'msvcr90', # MSVC 9 (VS 2008) '1600': 'msvcr100', # MSVC 10 (aka 2010) }.get(msc_ver, None) else: lib = None return lib ######################### #XXX need support for .C that is also C++ cxx_ext_match = re.compile(r'.*[.](cpp|cxx|cc)\Z', re.I).match fortran_ext_match = re.compile(r'.*[.](f90|f95|f77|for|ftn|f)\Z', re.I).match f90_ext_match = re.compile(r'.*[.](f90|f95)\Z', re.I).match f90_module_name_match = re.compile(r'\s*module\s*(?P[\w_]+)', re.I).match def _get_f90_modules(source): """Return a list of Fortran f90 module names that given source file defines. """ if not f90_ext_match(source): return [] modules = [] f = open(source, 'r') for line in f: m = f90_module_name_match(line) if m: name = m.group('name') modules.append(name) # break # XXX can we assume that there is one module per file? f.close() return modules def is_string(s): return isinstance(s, str) def all_strings(lst): """Return True if all items in lst are string objects. """ for item in lst: if not is_string(item): return False return True def is_sequence(seq): if is_string(seq): return False try: len(seq) except: return False return True def is_glob_pattern(s): return is_string(s) and ('*' in s or '?' is s) def as_list(seq): if is_sequence(seq): return list(seq) else: return [seq] def get_language(sources): # not used in numpy/scipy packages, use build_ext.detect_language instead """Determine language value (c,f77,f90) from sources """ language = None for source in sources: if isinstance(source, str): if f90_ext_match(source): language = 'f90' break elif fortran_ext_match(source): language = 'f77' return language def has_f_sources(sources): """Return True if sources contains Fortran files """ for source in sources: if fortran_ext_match(source): return True return False def has_cxx_sources(sources): """Return True if sources contains C++ files """ for source in sources: if cxx_ext_match(source): return True return False def filter_sources(sources): """Return four lists of filenames containing C, C++, Fortran, and Fortran 90 module sources, respectively. """ c_sources = [] cxx_sources = [] f_sources = [] fmodule_sources = [] for source in sources: if fortran_ext_match(source): modules = _get_f90_modules(source) if modules: fmodule_sources.append(source) else: f_sources.append(source) elif cxx_ext_match(source): cxx_sources.append(source) else: c_sources.append(source) return c_sources, cxx_sources, f_sources, fmodule_sources def _get_headers(directory_list): # get *.h files from list of directories headers = [] for d in directory_list: head = glob.glob(os.path.join(d, "*.h")) #XXX: *.hpp files?? headers.extend(head) return headers def _get_directories(list_of_sources): # get unique directories from list of sources. direcs = [] for f in list_of_sources: d = os.path.split(f) if d[0] != '' and not d[0] in direcs: direcs.append(d[0]) return direcs def get_dependencies(sources): #XXX scan sources for include statements return _get_headers(_get_directories(sources)) def is_local_src_dir(directory): """Return true if directory is local directory. """ if not is_string(directory): return False abs_dir = os.path.abspath(directory) c = os.path.commonprefix([os.getcwd(), abs_dir]) new_dir = abs_dir[len(c):].split(os.sep) if new_dir and not new_dir[0]: new_dir = new_dir[1:] if new_dir and new_dir[0]=='build': return False new_dir = os.sep.join(new_dir) return os.path.isdir(new_dir) def general_source_files(top_path): pruned_directories = {'CVS':1, '.svn':1, 'build':1} prune_file_pat = re.compile(r'(?:[~#]|\.py[co]|\.o)$') for dirpath, dirnames, filenames in os.walk(top_path, topdown=True): pruned = [ d for d in dirnames if d not in pruned_directories ] dirnames[:] = pruned for f in filenames: if not prune_file_pat.search(f): yield os.path.join(dirpath, f) def general_source_directories_files(top_path): """Return a directory name relative to top_path and files contained. """ pruned_directories = ['CVS', '.svn', 'build'] prune_file_pat = re.compile(r'(?:[~#]|\.py[co]|\.o)$') for dirpath, dirnames, filenames in os.walk(top_path, topdown=True): pruned = [ d for d in dirnames if d not in pruned_directories ] dirnames[:] = pruned for d in dirnames: dpath = os.path.join(dirpath, d) rpath = rel_path(dpath, top_path) files = [] for f in os.listdir(dpath): fn = os.path.join(dpath, f) if os.path.isfile(fn) and not prune_file_pat.search(fn): files.append(fn) yield rpath, files dpath = top_path rpath = rel_path(dpath, top_path) filenames = [os.path.join(dpath, f) for f in os.listdir(dpath) \ if not prune_file_pat.search(f)] files = [f for f in filenames if os.path.isfile(f)] yield rpath, files def get_ext_source_files(ext): # Get sources and any include files in the same directory. filenames = [] sources = [_m for _m in ext.sources if is_string(_m)] filenames.extend(sources) filenames.extend(get_dependencies(sources)) for d in ext.depends: if is_local_src_dir(d): filenames.extend(list(general_source_files(d))) elif os.path.isfile(d): filenames.append(d) return filenames def get_script_files(scripts): scripts = [_m for _m in scripts if is_string(_m)] return scripts def get_lib_source_files(lib): filenames = [] sources = lib[1].get('sources', []) sources = [_m for _m in sources if is_string(_m)] filenames.extend(sources) filenames.extend(get_dependencies(sources)) depends = lib[1].get('depends', []) for d in depends: if is_local_src_dir(d): filenames.extend(list(general_source_files(d))) elif os.path.isfile(d): filenames.append(d) return filenames def get_shared_lib_extension(is_python_ext=False): """Return the correct file extension for shared libraries. Parameters ---------- is_python_ext : bool, optional Whether the shared library is a Python extension. Default is False. Returns ------- so_ext : str The shared library extension. Notes ----- For Python shared libs, `so_ext` will typically be '.so' on Linux and OS X, and '.pyd' on Windows. For Python >= 3.2 `so_ext` has a tag prepended on POSIX systems according to PEP 3149. For Python 3.2 this is implemented on Linux, but not on OS X. """ confvars = distutils.sysconfig.get_config_vars() # SO is deprecated in 3.3.1, use EXT_SUFFIX instead so_ext = confvars.get('EXT_SUFFIX', None) if so_ext is None: so_ext = confvars.get('SO', '') if not is_python_ext: # hardcode known values, config vars (including SHLIB_SUFFIX) are # unreliable (see #3182) # darwin, windows and debug linux are wrong in 3.3.1 and older if (sys.platform.startswith('linux') or sys.platform.startswith('gnukfreebsd')): so_ext = '.so' elif sys.platform.startswith('darwin'): so_ext = '.dylib' elif sys.platform.startswith('win'): so_ext = '.dll' else: # fall back to config vars for unknown platforms # fix long extension for Python >=3.2, see PEP 3149. if 'SOABI' in confvars: # Does nothing unless SOABI config var exists so_ext = so_ext.replace('.' + confvars.get('SOABI'), '', 1) return so_ext def get_data_files(data): if is_string(data): return [data] sources = data[1] filenames = [] for s in sources: if hasattr(s, '__call__'): continue if is_local_src_dir(s): filenames.extend(list(general_source_files(s))) elif is_string(s): if os.path.isfile(s): filenames.append(s) else: print('Not existing data file:', s) else: raise TypeError(repr(s)) return filenames def dot_join(*args): return '.'.join([a for a in args if a]) def get_frame(level=0): """Return frame object from call stack with given level. """ try: return sys._getframe(level+1) except AttributeError: frame = sys.exc_info()[2].tb_frame for _ in range(level+1): frame = frame.f_back return frame ###################### class Configuration(object): _list_keys = ['packages', 'ext_modules', 'data_files', 'include_dirs', 'libraries', 'headers', 'scripts', 'py_modules', 'installed_libraries', 'define_macros'] _dict_keys = ['package_dir', 'installed_pkg_config'] _extra_keys = ['name', 'version'] numpy_include_dirs = [] def __init__(self, package_name=None, parent_name=None, top_path=None, package_path=None, caller_level=1, setup_name='setup.py', **attrs): """Construct configuration instance of a package. package_name -- name of the package Ex.: 'distutils' parent_name -- name of the parent package Ex.: 'numpy' top_path -- directory of the toplevel package Ex.: the directory where the numpy package source sits package_path -- directory of package. Will be computed by magic from the directory of the caller module if not specified Ex.: the directory where numpy.distutils is caller_level -- frame level to caller namespace, internal parameter. """ self.name = dot_join(parent_name, package_name) self.version = None caller_frame = get_frame(caller_level) self.local_path = get_path_from_frame(caller_frame, top_path) # local_path -- directory of a file (usually setup.py) that # defines a configuration() function. # local_path -- directory of a file (usually setup.py) that # defines a configuration() function. if top_path is None: top_path = self.local_path self.local_path = '' if package_path is None: package_path = self.local_path elif os.path.isdir(njoin(self.local_path, package_path)): package_path = njoin(self.local_path, package_path) if not os.path.isdir(package_path or '.'): raise ValueError("%r is not a directory" % (package_path,)) self.top_path = top_path self.package_path = package_path # this is the relative path in the installed package self.path_in_package = os.path.join(*self.name.split('.')) self.list_keys = self._list_keys[:] self.dict_keys = self._dict_keys[:] for n in self.list_keys: v = copy.copy(attrs.get(n, [])) setattr(self, n, as_list(v)) for n in self.dict_keys: v = copy.copy(attrs.get(n, {})) setattr(self, n, v) known_keys = self.list_keys + self.dict_keys self.extra_keys = self._extra_keys[:] for n in attrs.keys(): if n in known_keys: continue a = attrs[n] setattr(self, n, a) if isinstance(a, list): self.list_keys.append(n) elif isinstance(a, dict): self.dict_keys.append(n) else: self.extra_keys.append(n) if os.path.exists(njoin(package_path, '__init__.py')): self.packages.append(self.name) self.package_dir[self.name] = package_path self.options = dict( ignore_setup_xxx_py = False, assume_default_configuration = False, delegate_options_to_subpackages = False, quiet = False, ) caller_instance = None for i in range(1, 3): try: f = get_frame(i) except ValueError: break try: caller_instance = eval('self', f.f_globals, f.f_locals) break except NameError: pass if isinstance(caller_instance, self.__class__): if caller_instance.options['delegate_options_to_subpackages']: self.set_options(**caller_instance.options) self.setup_name = setup_name def todict(self): """ Return a dictionary compatible with the keyword arguments of distutils setup function. Examples -------- >>> setup(**config.todict()) #doctest: +SKIP """ self._optimize_data_files() d = {} known_keys = self.list_keys + self.dict_keys + self.extra_keys for n in known_keys: a = getattr(self, n) if a: d[n] = a return d def info(self, message): if not self.options['quiet']: print(message) def warn(self, message): sys.stderr.write('Warning: %s' % (message,)) def set_options(self, **options): """ Configure Configuration instance. The following options are available: - ignore_setup_xxx_py - assume_default_configuration - delegate_options_to_subpackages - quiet """ for key, value in options.items(): if key in self.options: self.options[key] = value else: raise ValueError('Unknown option: '+key) def get_distribution(self): """Return the distutils distribution object for self.""" from numpy.distutils.core import get_distribution return get_distribution() def _wildcard_get_subpackage(self, subpackage_name, parent_name, caller_level = 1): l = subpackage_name.split('.') subpackage_path = njoin([self.local_path]+l) dirs = [_m for _m in glob.glob(subpackage_path) if os.path.isdir(_m)] config_list = [] for d in dirs: if not os.path.isfile(njoin(d, '__init__.py')): continue if 'build' in d.split(os.sep): continue n = '.'.join(d.split(os.sep)[-len(l):]) c = self.get_subpackage(n, parent_name = parent_name, caller_level = caller_level+1) config_list.extend(c) return config_list def _get_configuration_from_setup_py(self, setup_py, subpackage_name, subpackage_path, parent_name, caller_level = 1): # In case setup_py imports local modules: sys.path.insert(0, os.path.dirname(setup_py)) try: fo_setup_py = open(setup_py, 'U') setup_name = os.path.splitext(os.path.basename(setup_py))[0] n = dot_join(self.name, subpackage_name, setup_name) setup_module = imp.load_module('_'.join(n.split('.')), fo_setup_py, setup_py, ('.py', 'U', 1)) fo_setup_py.close() if not hasattr(setup_module, 'configuration'): if not self.options['assume_default_configuration']: self.warn('Assuming default configuration '\ '(%s does not define configuration())'\ % (setup_module)) config = Configuration(subpackage_name, parent_name, self.top_path, subpackage_path, caller_level = caller_level + 1) else: pn = dot_join(*([parent_name] + subpackage_name.split('.')[:-1])) args = (pn,) def fix_args_py2(args): if setup_module.configuration.__code__.co_argcount > 1: args = args + (self.top_path,) return args def fix_args_py3(args): if setup_module.configuration.__code__.co_argcount > 1: args = args + (self.top_path,) return args if sys.version_info[0] < 3: args = fix_args_py2(args) else: args = fix_args_py3(args) config = setup_module.configuration(*args) if config.name!=dot_join(parent_name, subpackage_name): self.warn('Subpackage %r configuration returned as %r' % \ (dot_join(parent_name, subpackage_name), config.name)) finally: del sys.path[0] return config def get_subpackage(self,subpackage_name, subpackage_path=None, parent_name=None, caller_level = 1): """Return list of subpackage configurations. Parameters ---------- subpackage_name : str or None Name of the subpackage to get the configuration. '*' in subpackage_name is handled as a wildcard. subpackage_path : str If None, then the path is assumed to be the local path plus the subpackage_name. If a setup.py file is not found in the subpackage_path, then a default configuration is used. parent_name : str Parent name. """ if subpackage_name is None: if subpackage_path is None: raise ValueError( "either subpackage_name or subpackage_path must be specified") subpackage_name = os.path.basename(subpackage_path) # handle wildcards l = subpackage_name.split('.') if subpackage_path is None and '*' in subpackage_name: return self._wildcard_get_subpackage(subpackage_name, parent_name, caller_level = caller_level+1) assert '*' not in subpackage_name, repr((subpackage_name, subpackage_path, parent_name)) if subpackage_path is None: subpackage_path = njoin([self.local_path] + l) else: subpackage_path = njoin([subpackage_path] + l[:-1]) subpackage_path = self.paths([subpackage_path])[0] setup_py = njoin(subpackage_path, self.setup_name) if not self.options['ignore_setup_xxx_py']: if not os.path.isfile(setup_py): setup_py = njoin(subpackage_path, 'setup_%s.py' % (subpackage_name)) if not os.path.isfile(setup_py): if not self.options['assume_default_configuration']: self.warn('Assuming default configuration '\ '(%s/{setup_%s,setup}.py was not found)' \ % (os.path.dirname(setup_py), subpackage_name)) config = Configuration(subpackage_name, parent_name, self.top_path, subpackage_path, caller_level = caller_level+1) else: config = self._get_configuration_from_setup_py( setup_py, subpackage_name, subpackage_path, parent_name, caller_level = caller_level + 1) if config: return [config] else: return [] def add_subpackage(self,subpackage_name, subpackage_path=None, standalone = False): """Add a sub-package to the current Configuration instance. This is useful in a setup.py script for adding sub-packages to a package. Parameters ---------- subpackage_name : str name of the subpackage subpackage_path : str if given, the subpackage path such as the subpackage is in subpackage_path / subpackage_name. If None,the subpackage is assumed to be located in the local path / subpackage_name. standalone : bool """ if standalone: parent_name = None else: parent_name = self.name config_list = self.get_subpackage(subpackage_name, subpackage_path, parent_name = parent_name, caller_level = 2) if not config_list: self.warn('No configuration returned, assuming unavailable.') for config in config_list: d = config if isinstance(config, Configuration): d = config.todict() assert isinstance(d, dict), repr(type(d)) self.info('Appending %s configuration to %s' \ % (d.get('name'), self.name)) self.dict_append(**d) dist = self.get_distribution() if dist is not None: self.warn('distutils distribution has been initialized,'\ ' it may be too late to add a subpackage '+ subpackage_name) def add_data_dir(self, data_path): """Recursively add files under data_path to data_files list. Recursively add files under data_path to the list of data_files to be installed (and distributed). The data_path can be either a relative path-name, or an absolute path-name, or a 2-tuple where the first argument shows where in the install directory the data directory should be installed to. Parameters ---------- data_path : seq or str Argument can be either * 2-sequence (, ) * path to data directory where python datadir suffix defaults to package dir. Notes ----- Rules for installation paths: foo/bar -> (foo/bar, foo/bar) -> parent/foo/bar (gun, foo/bar) -> parent/gun foo/* -> (foo/a, foo/a), (foo/b, foo/b) -> parent/foo/a, parent/foo/b (gun, foo/*) -> (gun, foo/a), (gun, foo/b) -> gun (gun/*, foo/*) -> parent/gun/a, parent/gun/b /foo/bar -> (bar, /foo/bar) -> parent/bar (gun, /foo/bar) -> parent/gun (fun/*/gun/*, sun/foo/bar) -> parent/fun/foo/gun/bar Examples -------- For example suppose the source directory contains fun/foo.dat and fun/bar/car.dat:: >>> self.add_data_dir('fun') #doctest: +SKIP >>> self.add_data_dir(('sun', 'fun')) #doctest: +SKIP >>> self.add_data_dir(('gun', '/full/path/to/fun'))#doctest: +SKIP Will install data-files to the locations:: / fun/ foo.dat bar/ car.dat sun/ foo.dat bar/ car.dat gun/ foo.dat car.dat """ if is_sequence(data_path): d, data_path = data_path else: d = None if is_sequence(data_path): [self.add_data_dir((d, p)) for p in data_path] return if not is_string(data_path): raise TypeError("not a string: %r" % (data_path,)) if d is None: if os.path.isabs(data_path): return self.add_data_dir((os.path.basename(data_path), data_path)) return self.add_data_dir((data_path, data_path)) paths = self.paths(data_path, include_non_existing=False) if is_glob_pattern(data_path): if is_glob_pattern(d): pattern_list = allpath(d).split(os.sep) pattern_list.reverse() # /a/*//b/ -> /a/*/b rl = list(range(len(pattern_list)-1)); rl.reverse() for i in rl: if not pattern_list[i]: del pattern_list[i] # for path in paths: if not os.path.isdir(path): print('Not a directory, skipping', path) continue rpath = rel_path(path, self.local_path) path_list = rpath.split(os.sep) path_list.reverse() target_list = [] i = 0 for s in pattern_list: if is_glob_pattern(s): if i>=len(path_list): raise ValueError('cannot fill pattern %r with %r' \ % (d, path)) target_list.append(path_list[i]) else: assert s==path_list[i], repr((s, path_list[i], data_path, d, path, rpath)) target_list.append(s) i += 1 if path_list[i:]: self.warn('mismatch of pattern_list=%s and path_list=%s'\ % (pattern_list, path_list)) target_list.reverse() self.add_data_dir((os.sep.join(target_list), path)) else: for path in paths: self.add_data_dir((d, path)) return assert not is_glob_pattern(d), repr(d) dist = self.get_distribution() if dist is not None and dist.data_files is not None: data_files = dist.data_files else: data_files = self.data_files for path in paths: for d1, f in list(general_source_directories_files(path)): target_path = os.path.join(self.path_in_package, d, d1) data_files.append((target_path, f)) def _optimize_data_files(self): data_dict = {} for p, files in self.data_files: if p not in data_dict: data_dict[p] = set() for f in files: data_dict[p].add(f) self.data_files[:] = [(p, list(files)) for p, files in data_dict.items()] def add_data_files(self,*files): """Add data files to configuration data_files. Parameters ---------- files : sequence Argument(s) can be either * 2-sequence (,) * paths to data files where python datadir prefix defaults to package dir. Notes ----- The form of each element of the files sequence is very flexible allowing many combinations of where to get the files from the package and where they should ultimately be installed on the system. The most basic usage is for an element of the files argument sequence to be a simple filename. This will cause that file from the local path to be installed to the installation path of the self.name package (package path). The file argument can also be a relative path in which case the entire relative path will be installed into the package directory. Finally, the file can be an absolute path name in which case the file will be found at the absolute path name but installed to the package path. This basic behavior can be augmented by passing a 2-tuple in as the file argument. The first element of the tuple should specify the relative path (under the package install directory) where the remaining sequence of files should be installed to (it has nothing to do with the file-names in the source distribution). The second element of the tuple is the sequence of files that should be installed. The files in this sequence can be filenames, relative paths, or absolute paths. For absolute paths the file will be installed in the top-level package installation directory (regardless of the first argument). Filenames and relative path names will be installed in the package install directory under the path name given as the first element of the tuple. Rules for installation paths: #. file.txt -> (., file.txt)-> parent/file.txt #. foo/file.txt -> (foo, foo/file.txt) -> parent/foo/file.txt #. /foo/bar/file.txt -> (., /foo/bar/file.txt) -> parent/file.txt #. *.txt -> parent/a.txt, parent/b.txt #. foo/*.txt -> parent/foo/a.txt, parent/foo/b.txt #. */*.txt -> (*, */*.txt) -> parent/c/a.txt, parent/d/b.txt #. (sun, file.txt) -> parent/sun/file.txt #. (sun, bar/file.txt) -> parent/sun/file.txt #. (sun, /foo/bar/file.txt) -> parent/sun/file.txt #. (sun, *.txt) -> parent/sun/a.txt, parent/sun/b.txt #. (sun, bar/*.txt) -> parent/sun/a.txt, parent/sun/b.txt #. (sun/*, */*.txt) -> parent/sun/c/a.txt, parent/d/b.txt An additional feature is that the path to a data-file can actually be a function that takes no arguments and returns the actual path(s) to the data-files. This is useful when the data files are generated while building the package. Examples -------- Add files to the list of data_files to be included with the package. >>> self.add_data_files('foo.dat', ... ('fun', ['gun.dat', 'nun/pun.dat', '/tmp/sun.dat']), ... 'bar/cat.dat', ... '/full/path/to/can.dat') #doctest: +SKIP will install these data files to:: / foo.dat fun/ gun.dat nun/ pun.dat sun.dat bar/ car.dat can.dat where is the package (or sub-package) directory such as '/usr/lib/python2.4/site-packages/mypackage' ('C: \\Python2.4 \\Lib \\site-packages \\mypackage') or '/usr/lib/python2.4/site- packages/mypackage/mysubpackage' ('C: \\Python2.4 \\Lib \\site-packages \\mypackage \\mysubpackage'). """ if len(files)>1: for f in files: self.add_data_files(f) return assert len(files)==1 if is_sequence(files[0]): d, files = files[0] else: d = None if is_string(files): filepat = files elif is_sequence(files): if len(files)==1: filepat = files[0] else: for f in files: self.add_data_files((d, f)) return else: raise TypeError(repr(type(files))) if d is None: if hasattr(filepat, '__call__'): d = '' elif os.path.isabs(filepat): d = '' else: d = os.path.dirname(filepat) self.add_data_files((d, files)) return paths = self.paths(filepat, include_non_existing=False) if is_glob_pattern(filepat): if is_glob_pattern(d): pattern_list = d.split(os.sep) pattern_list.reverse() for path in paths: path_list = path.split(os.sep) path_list.reverse() path_list.pop() # filename target_list = [] i = 0 for s in pattern_list: if is_glob_pattern(s): target_list.append(path_list[i]) i += 1 else: target_list.append(s) target_list.reverse() self.add_data_files((os.sep.join(target_list), path)) else: self.add_data_files((d, paths)) return assert not is_glob_pattern(d), repr((d, filepat)) dist = self.get_distribution() if dist is not None and dist.data_files is not None: data_files = dist.data_files else: data_files = self.data_files data_files.append((os.path.join(self.path_in_package, d), paths)) ### XXX Implement add_py_modules def add_define_macros(self, macros): """Add define macros to configuration Add the given sequence of macro name and value duples to the beginning of the define_macros list This list will be visible to all extension modules of the current package. """ dist = self.get_distribution() if dist is not None: if not hasattr(dist, 'define_macros'): dist.define_macros = [] dist.define_macros.extend(macros) else: self.define_macros.extend(macros) def add_include_dirs(self,*paths): """Add paths to configuration include directories. Add the given sequence of paths to the beginning of the include_dirs list. This list will be visible to all extension modules of the current package. """ include_dirs = self.paths(paths) dist = self.get_distribution() if dist is not None: if dist.include_dirs is None: dist.include_dirs = [] dist.include_dirs.extend(include_dirs) else: self.include_dirs.extend(include_dirs) def add_numarray_include_dirs(self): import numpy.numarray.util as nnu self.add_include_dirs(*nnu.get_numarray_include_dirs()) def add_headers(self,*files): """Add installable headers to configuration. Add the given sequence of files to the beginning of the headers list. By default, headers will be installed under // directory. If an item of files is a tuple, then its first argument specifies the actual installation location relative to the path. Parameters ---------- files : str or seq Argument(s) can be either: * 2-sequence (,) * path(s) to header file(s) where python includedir suffix will default to package name. """ headers = [] for path in files: if is_string(path): [headers.append((self.name, p)) for p in self.paths(path)] else: if not isinstance(path, (tuple, list)) or len(path) != 2: raise TypeError(repr(path)) [headers.append((path[0], p)) for p in self.paths(path[1])] dist = self.get_distribution() if dist is not None: if dist.headers is None: dist.headers = [] dist.headers.extend(headers) else: self.headers.extend(headers) def paths(self,*paths,**kws): """Apply glob to paths and prepend local_path if needed. Applies glob.glob(...) to each path in the sequence (if needed) and pre-pends the local_path if needed. Because this is called on all source lists, this allows wildcard characters to be specified in lists of sources for extension modules and libraries and scripts and allows path-names be relative to the source directory. """ include_non_existing = kws.get('include_non_existing', True) return gpaths(paths, local_path = self.local_path, include_non_existing=include_non_existing) def _fix_paths_dict(self, kw): for k in kw.keys(): v = kw[k] if k in ['sources', 'depends', 'include_dirs', 'library_dirs', 'module_dirs', 'extra_objects']: new_v = self.paths(v) kw[k] = new_v def add_extension(self,name,sources,**kw): """Add extension to configuration. Create and add an Extension instance to the ext_modules list. This method also takes the following optional keyword arguments that are passed on to the Extension constructor. Parameters ---------- name : str name of the extension sources : seq list of the sources. The list of sources may contain functions (called source generators) which must take an extension instance and a build directory as inputs and return a source file or list of source files or None. If None is returned then no sources are generated. If the Extension instance has no sources after processing all source generators, then no extension module is built. include_dirs : define_macros : undef_macros : library_dirs : libraries : runtime_library_dirs : extra_objects : extra_compile_args : extra_link_args : extra_f77_compile_args : extra_f90_compile_args : export_symbols : swig_opts : depends : The depends list contains paths to files or directories that the sources of the extension module depend on. If any path in the depends list is newer than the extension module, then the module will be rebuilt. language : f2py_options : module_dirs : extra_info : dict or list dict or list of dict of keywords to be appended to keywords. Notes ----- The self.paths(...) method is applied to all lists that may contain paths. """ ext_args = copy.copy(kw) ext_args['name'] = dot_join(self.name, name) ext_args['sources'] = sources if 'extra_info' in ext_args: extra_info = ext_args['extra_info'] del ext_args['extra_info'] if isinstance(extra_info, dict): extra_info = [extra_info] for info in extra_info: assert isinstance(info, dict), repr(info) dict_append(ext_args,**info) self._fix_paths_dict(ext_args) # Resolve out-of-tree dependencies libraries = ext_args.get('libraries', []) libnames = [] ext_args['libraries'] = [] for libname in libraries: if isinstance(libname, tuple): self._fix_paths_dict(libname[1]) # Handle library names of the form libname@relative/path/to/library if '@' in libname: lname, lpath = libname.split('@', 1) lpath = os.path.abspath(njoin(self.local_path, lpath)) if os.path.isdir(lpath): c = self.get_subpackage(None, lpath, caller_level = 2) if isinstance(c, Configuration): c = c.todict() for l in [l[0] for l in c.get('libraries', [])]: llname = l.split('__OF__', 1)[0] if llname == lname: c.pop('name', None) dict_append(ext_args,**c) break continue libnames.append(libname) ext_args['libraries'] = libnames + ext_args['libraries'] ext_args['define_macros'] = \ self.define_macros + ext_args.get('define_macros', []) from numpy.distutils.core import Extension ext = Extension(**ext_args) self.ext_modules.append(ext) dist = self.get_distribution() if dist is not None: self.warn('distutils distribution has been initialized,'\ ' it may be too late to add an extension '+name) return ext def add_library(self,name,sources,**build_info): """ Add library to configuration. Parameters ---------- name : str Name of the extension. sources : sequence List of the sources. The list of sources may contain functions (called source generators) which must take an extension instance and a build directory as inputs and return a source file or list of source files or None. If None is returned then no sources are generated. If the Extension instance has no sources after processing all source generators, then no extension module is built. build_info : dict, optional The following keys are allowed: * depends * macros * include_dirs * extra_compiler_args * extra_f77_compiler_args * extra_f90_compiler_args * f2py_options * language """ self._add_library(name, sources, None, build_info) dist = self.get_distribution() if dist is not None: self.warn('distutils distribution has been initialized,'\ ' it may be too late to add a library '+ name) def _add_library(self, name, sources, install_dir, build_info): """Common implementation for add_library and add_installed_library. Do not use directly""" build_info = copy.copy(build_info) name = name #+ '__OF__' + self.name build_info['sources'] = sources # Sometimes, depends is not set up to an empty list by default, and if # depends is not given to add_library, distutils barfs (#1134) if not 'depends' in build_info: build_info['depends'] = [] self._fix_paths_dict(build_info) # Add to libraries list so that it is build with build_clib self.libraries.append((name, build_info)) def add_installed_library(self, name, sources, install_dir, build_info=None): """ Similar to add_library, but the specified library is installed. Most C libraries used with `distutils` are only used to build python extensions, but libraries built through this method will be installed so that they can be reused by third-party packages. Parameters ---------- name : str Name of the installed library. sources : sequence List of the library's source files. See `add_library` for details. install_dir : str Path to install the library, relative to the current sub-package. build_info : dict, optional The following keys are allowed: * depends * macros * include_dirs * extra_compiler_args * extra_f77_compiler_args * extra_f90_compiler_args * f2py_options * language Returns ------- None See Also -------- add_library, add_npy_pkg_config, get_info Notes ----- The best way to encode the options required to link against the specified C libraries is to use a "libname.ini" file, and use `get_info` to retrieve the required options (see `add_npy_pkg_config` for more information). """ if not build_info: build_info = {} install_dir = os.path.join(self.package_path, install_dir) self._add_library(name, sources, install_dir, build_info) self.installed_libraries.append(InstallableLib(name, build_info, install_dir)) def add_npy_pkg_config(self, template, install_dir, subst_dict=None): """ Generate and install a npy-pkg config file from a template. The config file generated from `template` is installed in the given install directory, using `subst_dict` for variable substitution. Parameters ---------- template : str The path of the template, relatively to the current package path. install_dir : str Where to install the npy-pkg config file, relatively to the current package path. subst_dict : dict, optional If given, any string of the form ``@key@`` will be replaced by ``subst_dict[key]`` in the template file when installed. The install prefix is always available through the variable ``@prefix@``, since the install prefix is not easy to get reliably from setup.py. See also -------- add_installed_library, get_info Notes ----- This works for both standard installs and in-place builds, i.e. the ``@prefix@`` refer to the source directory for in-place builds. Examples -------- :: config.add_npy_pkg_config('foo.ini.in', 'lib', {'foo': bar}) Assuming the foo.ini.in file has the following content:: [meta] Name=@foo@ Version=1.0 Description=dummy description [default] Cflags=-I@prefix@/include Libs= The generated file will have the following content:: [meta] Name=bar Version=1.0 Description=dummy description [default] Cflags=-Iprefix_dir/include Libs= and will be installed as foo.ini in the 'lib' subpath. """ if subst_dict is None: subst_dict = {} basename = os.path.splitext(template)[0] template = os.path.join(self.package_path, template) if self.name in self.installed_pkg_config: self.installed_pkg_config[self.name].append((template, install_dir, subst_dict)) else: self.installed_pkg_config[self.name] = [(template, install_dir, subst_dict)] def add_scripts(self,*files): """Add scripts to configuration. Add the sequence of files to the beginning of the scripts list. Scripts will be installed under the /bin/ directory. """ scripts = self.paths(files) dist = self.get_distribution() if dist is not None: if dist.scripts is None: dist.scripts = [] dist.scripts.extend(scripts) else: self.scripts.extend(scripts) def dict_append(self,**dict): for key in self.list_keys: a = getattr(self, key) a.extend(dict.get(key, [])) for key in self.dict_keys: a = getattr(self, key) a.update(dict.get(key, {})) known_keys = self.list_keys + self.dict_keys + self.extra_keys for key in dict.keys(): if key not in known_keys: a = getattr(self, key, None) if a and a==dict[key]: continue self.warn('Inheriting attribute %r=%r from %r' \ % (key, dict[key], dict.get('name', '?'))) setattr(self, key, dict[key]) self.extra_keys.append(key) elif key in self.extra_keys: self.info('Ignoring attempt to set %r (from %r to %r)' \ % (key, getattr(self, key), dict[key])) elif key in known_keys: # key is already processed above pass else: raise ValueError("Don't know about key=%r" % (key)) def __str__(self): from pprint import pformat known_keys = self.list_keys + self.dict_keys + self.extra_keys s = '<'+5*'-' + '\n' s += 'Configuration of '+self.name+':\n' known_keys.sort() for k in known_keys: a = getattr(self, k, None) if a: s += '%s = %s\n' % (k, pformat(a)) s += 5*'-' + '>' return s def get_config_cmd(self): """ Returns the numpy.distutils config command instance. """ cmd = get_cmd('config') cmd.ensure_finalized() cmd.dump_source = 0 cmd.noisy = 0 old_path = os.environ.get('PATH') if old_path: path = os.pathsep.join(['.', old_path]) os.environ['PATH'] = path return cmd def get_build_temp_dir(self): """ Return a path to a temporary directory where temporary files should be placed. """ cmd = get_cmd('build') cmd.ensure_finalized() return cmd.build_temp def have_f77c(self): """Check for availability of Fortran 77 compiler. Use it inside source generating function to ensure that setup distribution instance has been initialized. Notes ----- True if a Fortran 77 compiler is available (because a simple Fortran 77 code was able to be compiled successfully). """ simple_fortran_subroutine = ''' subroutine simple end ''' config_cmd = self.get_config_cmd() flag = config_cmd.try_compile(simple_fortran_subroutine, lang='f77') return flag def have_f90c(self): """Check for availability of Fortran 90 compiler. Use it inside source generating function to ensure that setup distribution instance has been initialized. Notes ----- True if a Fortran 90 compiler is available (because a simple Fortran 90 code was able to be compiled successfully) """ simple_fortran_subroutine = ''' subroutine simple end ''' config_cmd = self.get_config_cmd() flag = config_cmd.try_compile(simple_fortran_subroutine, lang='f90') return flag def append_to(self, extlib): """Append libraries, include_dirs to extension or library item. """ if is_sequence(extlib): lib_name, build_info = extlib dict_append(build_info, libraries=self.libraries, include_dirs=self.include_dirs) else: from numpy.distutils.core import Extension assert isinstance(extlib, Extension), repr(extlib) extlib.libraries.extend(self.libraries) extlib.include_dirs.extend(self.include_dirs) def _get_svn_revision(self, path): """Return path's SVN revision number. """ revision = None m = None cwd = os.getcwd() try: os.chdir(path or '.') p = subprocess.Popen(['svnversion'], shell=True, stdout=subprocess.PIPE, stderr=None, close_fds=True) sout = p.stdout m = re.match(r'(?P\d+)', sout.read()) except: pass os.chdir(cwd) if m: revision = int(m.group('revision')) return revision if sys.platform=='win32' and os.environ.get('SVN_ASP_DOT_NET_HACK', None): entries = njoin(path, '_svn', 'entries') else: entries = njoin(path, '.svn', 'entries') if os.path.isfile(entries): f = open(entries) fstr = f.read() f.close() if fstr[:5] == '\d+)"', fstr) if m: revision = int(m.group('revision')) else: # non-xml entries file --- check to be sure that m = re.search(r'dir[\n\r]+(?P\d+)', fstr) if m: revision = int(m.group('revision')) return revision def _get_hg_revision(self, path): """Return path's Mercurial revision number. """ revision = None m = None cwd = os.getcwd() try: os.chdir(path or '.') p = subprocess.Popen(['hg identify --num'], shell=True, stdout=subprocess.PIPE, stderr=None, close_fds=True) sout = p.stdout m = re.match(r'(?P\d+)', sout.read()) except: pass os.chdir(cwd) if m: revision = int(m.group('revision')) return revision branch_fn = njoin(path, '.hg', 'branch') branch_cache_fn = njoin(path, '.hg', 'branch.cache') if os.path.isfile(branch_fn): branch0 = None f = open(branch_fn) revision0 = f.read().strip() f.close() branch_map = {} for line in file(branch_cache_fn, 'r'): branch1, revision1 = line.split()[:2] if revision1==revision0: branch0 = branch1 try: revision1 = int(revision1) except ValueError: continue branch_map[branch1] = revision1 revision = branch_map.get(branch0) return revision def get_version(self, version_file=None, version_variable=None): """Try to get version string of a package. Return a version string of the current package or None if the version information could not be detected. Notes ----- This method scans files named __version__.py, _version.py, version.py, and __svn_version__.py for string variables version, __version\__, and _version, until a version number is found. """ version = getattr(self, 'version', None) if version is not None: return version # Get version from version file. if version_file is None: files = ['__version__.py', self.name.split('.')[-1]+'_version.py', 'version.py', '__svn_version__.py', '__hg_version__.py'] else: files = [version_file] if version_variable is None: version_vars = ['version', '__version__', self.name.split('.')[-1]+'_version'] else: version_vars = [version_variable] for f in files: fn = njoin(self.local_path, f) if os.path.isfile(fn): info = (open(fn), fn, ('.py', 'U', 1)) name = os.path.splitext(os.path.basename(fn))[0] n = dot_join(self.name, name) try: version_module = imp.load_module('_'.join(n.split('.')),*info) except ImportError: msg = get_exception() self.warn(str(msg)) version_module = None if version_module is None: continue for a in version_vars: version = getattr(version_module, a, None) if version is not None: break if version is not None: break if version is not None: self.version = version return version # Get version as SVN or Mercurial revision number revision = self._get_svn_revision(self.local_path) if revision is None: revision = self._get_hg_revision(self.local_path) if revision is not None: version = str(revision) self.version = version return version def make_svn_version_py(self, delete=True): """Appends a data function to the data_files list that will generate __svn_version__.py file to the current package directory. Generate package __svn_version__.py file from SVN revision number, it will be removed after python exits but will be available when sdist, etc commands are executed. Notes ----- If __svn_version__.py existed before, nothing is done. This is intended for working with source directories that are in an SVN repository. """ target = njoin(self.local_path, '__svn_version__.py') revision = self._get_svn_revision(self.local_path) if os.path.isfile(target) or revision is None: return else: def generate_svn_version_py(): if not os.path.isfile(target): version = str(revision) self.info('Creating %s (version=%r)' % (target, version)) f = open(target, 'w') f.write('version = %r\n' % (version)) f.close() import atexit def rm_file(f=target,p=self.info): if delete: try: os.remove(f); p('removed '+f) except OSError: pass try: os.remove(f+'c'); p('removed '+f+'c') except OSError: pass atexit.register(rm_file) return target self.add_data_files(('', generate_svn_version_py())) def make_hg_version_py(self, delete=True): """Appends a data function to the data_files list that will generate __hg_version__.py file to the current package directory. Generate package __hg_version__.py file from Mercurial revision, it will be removed after python exits but will be available when sdist, etc commands are executed. Notes ----- If __hg_version__.py existed before, nothing is done. This is intended for working with source directories that are in an Mercurial repository. """ target = njoin(self.local_path, '__hg_version__.py') revision = self._get_hg_revision(self.local_path) if os.path.isfile(target) or revision is None: return else: def generate_hg_version_py(): if not os.path.isfile(target): version = str(revision) self.info('Creating %s (version=%r)' % (target, version)) f = open(target, 'w') f.write('version = %r\n' % (version)) f.close() import atexit def rm_file(f=target,p=self.info): if delete: try: os.remove(f); p('removed '+f) except OSError: pass try: os.remove(f+'c'); p('removed '+f+'c') except OSError: pass atexit.register(rm_file) return target self.add_data_files(('', generate_hg_version_py())) def make_config_py(self,name='__config__'): """Generate package __config__.py file containing system_info information used during building the package. This file is installed to the package installation directory. """ self.py_modules.append((self.name, name, generate_config_py)) def get_info(self,*names): """Get resources information. Return information (from system_info.get_info) for all of the names in the argument list in a single dictionary. """ from .system_info import get_info, dict_append info_dict = {} for a in names: dict_append(info_dict,**get_info(a)) return info_dict def get_cmd(cmdname, _cache={}): if cmdname not in _cache: import distutils.core dist = distutils.core._setup_distribution if dist is None: from distutils.errors import DistutilsInternalError raise DistutilsInternalError( 'setup distribution instance not initialized') cmd = dist.get_command_obj(cmdname) _cache[cmdname] = cmd return _cache[cmdname] def get_numpy_include_dirs(): # numpy_include_dirs are set by numpy/core/setup.py, otherwise [] include_dirs = Configuration.numpy_include_dirs[:] if not include_dirs: import numpy include_dirs = [ numpy.get_include() ] # else running numpy/core/setup.py return include_dirs def get_npy_pkg_dir(): """Return the path where to find the npy-pkg-config directory.""" # XXX: import here for bootstrapping reasons import numpy d = os.path.join(os.path.dirname(numpy.__file__), 'core', 'lib', 'npy-pkg-config') return d def get_pkg_info(pkgname, dirs=None): """ Return library info for the given package. Parameters ---------- pkgname : str Name of the package (should match the name of the .ini file, without the extension, e.g. foo for the file foo.ini). dirs : sequence, optional If given, should be a sequence of additional directories where to look for npy-pkg-config files. Those directories are searched prior to the NumPy directory. Returns ------- pkginfo : class instance The `LibraryInfo` instance containing the build information. Raises ------ PkgNotFound If the package is not found. See Also -------- Configuration.add_npy_pkg_config, Configuration.add_installed_library, get_info """ from numpy.distutils.npy_pkg_config import read_config if dirs: dirs.append(get_npy_pkg_dir()) else: dirs = [get_npy_pkg_dir()] return read_config(pkgname, dirs) def get_info(pkgname, dirs=None): """ Return an info dict for a given C library. The info dict contains the necessary options to use the C library. Parameters ---------- pkgname : str Name of the package (should match the name of the .ini file, without the extension, e.g. foo for the file foo.ini). dirs : sequence, optional If given, should be a sequence of additional directories where to look for npy-pkg-config files. Those directories are searched prior to the NumPy directory. Returns ------- info : dict The dictionary with build information. Raises ------ PkgNotFound If the package is not found. See Also -------- Configuration.add_npy_pkg_config, Configuration.add_installed_library, get_pkg_info Examples -------- To get the necessary information for the npymath library from NumPy: >>> npymath_info = np.distutils.misc_util.get_info('npymath') >>> npymath_info #doctest: +SKIP {'define_macros': [], 'libraries': ['npymath'], 'library_dirs': ['.../numpy/core/lib'], 'include_dirs': ['.../numpy/core/include']} This info dict can then be used as input to a `Configuration` instance:: config.add_extension('foo', sources=['foo.c'], extra_info=npymath_info) """ from numpy.distutils.npy_pkg_config import parse_flags pkg_info = get_pkg_info(pkgname, dirs) # Translate LibraryInfo instance into a build_info dict info = parse_flags(pkg_info.cflags()) for k, v in parse_flags(pkg_info.libs()).items(): info[k].extend(v) # add_extension extra_info argument is ANAL info['define_macros'] = info['macros'] del info['macros'] del info['ignored'] return info def is_bootstrapping(): if sys.version_info[0] >= 3: import builtins else: import __builtin__ as builtins try: builtins.__NUMPY_SETUP__ return True except AttributeError: return False __NUMPY_SETUP__ = False ######################### def default_config_dict(name = None, parent_name = None, local_path=None): """Return a configuration dictionary for usage in configuration() function defined in file setup_.py. """ import warnings warnings.warn('Use Configuration(%r,%r,top_path=%r) instead of '\ 'deprecated default_config_dict(%r,%r,%r)' % (name, parent_name, local_path, name, parent_name, local_path, )) c = Configuration(name, parent_name, local_path) return c.todict() def dict_append(d, **kws): for k, v in kws.items(): if k in d: ov = d[k] if isinstance(ov, str): d[k] = v else: d[k].extend(v) else: d[k] = v def appendpath(prefix, path): if os.path.sep != '/': prefix = prefix.replace('/', os.path.sep) path = path.replace('/', os.path.sep) drive = '' if os.path.isabs(path): drive = os.path.splitdrive(prefix)[0] absprefix = os.path.splitdrive(os.path.abspath(prefix))[1] pathdrive, path = os.path.splitdrive(path) d = os.path.commonprefix([absprefix, path]) if os.path.join(absprefix[:len(d)], absprefix[len(d):]) != absprefix \ or os.path.join(path[:len(d)], path[len(d):]) != path: # Handle invalid paths d = os.path.dirname(d) subpath = path[len(d):] if os.path.isabs(subpath): subpath = subpath[1:] else: subpath = path return os.path.normpath(njoin(drive + prefix, subpath)) def generate_config_py(target): """Generate config.py file containing system_info information used during building the package. Usage: config['py_modules'].append((packagename, '__config__',generate_config_py)) """ from numpy.distutils.system_info import system_info from distutils.dir_util import mkpath mkpath(os.path.dirname(target)) f = open(target, 'w') f.write('# This file is generated by %s\n' % (os.path.abspath(sys.argv[0]))) f.write('# It contains system_info results at the time of building this package.\n') f.write('__all__ = ["get_info","show"]\n\n') for k, i in system_info.saved_results.items(): f.write('%s=%r\n' % (k, i)) f.write(r''' def get_info(name): g = globals() return g.get(name, g.get(name + "_info", {})) def show(): for name,info_dict in globals().items(): if name[0] == "_" or type(info_dict) is not type({}): continue print(name + ":") if not info_dict: print(" NOT AVAILABLE") for k,v in info_dict.items(): v = str(v) if k == "sources" and len(v) > 200: v = v[:60] + " ...\n... " + v[-60:] print(" %s = %s" % (k,v)) ''') f.close() return target def msvc_version(compiler): """Return version major and minor of compiler instance if it is MSVC, raise an exception otherwise.""" if not compiler.compiler_type == "msvc": raise ValueError("Compiler instance is not msvc (%s)"\ % compiler.compiler_type) return compiler._MSVCCompiler__version if sys.version[:3] >= '2.5': def get_build_architecture(): from distutils.msvccompiler import get_build_architecture return get_build_architecture() else: #copied from python 2.5.1 distutils/msvccompiler.py def get_build_architecture(): """Return the processor architecture. Possible results are "Intel", "Itanium", or "AMD64". """ prefix = " bit (" i = sys.version.find(prefix) if i == -1: return "Intel" j = sys.version.find(")", i) return sys.version[i+len(prefix):j] numpy-1.8.2/numpy/distutils/extension.py0000664000175100017510000000574312370216242021616 0ustar vagrantvagrant00000000000000"""distutils.extension Provides the Extension class, used to describe C/C++ extension modules in setup scripts. Overridden to support f2py. """ from __future__ import division, absolute_import, print_function import sys import re from distutils.extension import Extension as old_Extension if sys.version_info[0] >= 3: basestring = str cxx_ext_re = re.compile(r'.*[.](cpp|cxx|cc)\Z', re.I).match fortran_pyf_ext_re = re.compile(r'.*[.](f90|f95|f77|for|ftn|f|pyf)\Z', re.I).match class Extension(old_Extension): def __init__ (self, name, sources, include_dirs=None, define_macros=None, undef_macros=None, library_dirs=None, libraries=None, runtime_library_dirs=None, extra_objects=None, extra_compile_args=None, extra_link_args=None, export_symbols=None, swig_opts=None, depends=None, language=None, f2py_options=None, module_dirs=None, extra_f77_compile_args=None, extra_f90_compile_args=None, ): old_Extension.__init__(self, name, [], include_dirs, define_macros, undef_macros, library_dirs, libraries, runtime_library_dirs, extra_objects, extra_compile_args, extra_link_args, export_symbols) # Avoid assert statements checking that sources contains strings: self.sources = sources # Python 2.4 distutils new features self.swig_opts = swig_opts or [] # swig_opts is assumed to be a list. Here we handle the case where it # is specified as a string instead. if isinstance(self.swig_opts, basestring): import warnings msg = "swig_opts is specified as a string instead of a list" warnings.warn(msg, SyntaxWarning) self.swig_opts = self.swig_opts.split() # Python 2.3 distutils new features self.depends = depends or [] self.language = language # numpy_distutils features self.f2py_options = f2py_options or [] self.module_dirs = module_dirs or [] self.extra_f77_compile_args = extra_f77_compile_args or [] self.extra_f90_compile_args = extra_f90_compile_args or [] return def has_cxx_sources(self): for source in self.sources: if cxx_ext_re(str(source)): return True return False def has_f2py_sources(self): for source in self.sources: if fortran_pyf_ext_re(source): return True return False # class Extension numpy-1.8.2/numpy/distutils/conv_template.py0000664000175100017510000002272112370216242022435 0ustar vagrantvagrant00000000000000#!/usr/bin/python """ takes templated file .xxx.src and produces .xxx file where .xxx is .i or .c or .h, using the following template rules /**begin repeat -- on a line by itself marks the start of a repeated code segment /**end repeat**/ -- on a line by itself marks it's end After the /**begin repeat and before the */, all the named templates are placed these should all have the same number of replacements Repeat blocks can be nested, with each nested block labeled with its depth, i.e. /**begin repeat1 *.... */ /**end repeat1**/ When using nested loops, you can optionally exlude particular combinations of the variables using (inside the comment portion of the inner loop): :exclude: var1=value1, var2=value2, ... This will exlude the pattern where var1 is value1 and var2 is value2 when the result is being generated. In the main body each replace will use one entry from the list of named replacements Note that all #..# forms in a block must have the same number of comma-separated entries. Example: An input file containing /**begin repeat * #a = 1,2,3# * #b = 1,2,3# */ /**begin repeat1 * #c = ted, jim# */ @a@, @b@, @c@ /**end repeat1**/ /**end repeat**/ produces line 1 "template.c.src" /* ********************************************************************* ** This file was autogenerated from a template DO NOT EDIT!!** ** Changes should be made to the original source (.src) file ** ********************************************************************* */ #line 9 1, 1, ted #line 9 1, 1, jim #line 9 2, 2, ted #line 9 2, 2, jim #line 9 3, 3, ted #line 9 3, 3, jim """ from __future__ import division, absolute_import, print_function __all__ = ['process_str', 'process_file'] import os import sys import re from numpy.distutils.compat import get_exception # names for replacement that are already global. global_names = {} # header placed at the front of head processed file header =\ """ /* ***************************************************************************** ** This file was autogenerated from a template DO NOT EDIT!!!! ** ** Changes should be made to the original source (.src) file ** ***************************************************************************** */ """ # Parse string for repeat loops def parse_structure(astr, level): """ The returned line number is from the beginning of the string, starting at zero. Returns an empty list if no loops found. """ if level == 0 : loopbeg = "/**begin repeat" loopend = "/**end repeat**/" else : loopbeg = "/**begin repeat%d" % level loopend = "/**end repeat%d**/" % level ind = 0 line = 0 spanlist = [] while True: start = astr.find(loopbeg, ind) if start == -1: break start2 = astr.find("*/", start) start2 = astr.find("\n", start2) fini1 = astr.find(loopend, start2) fini2 = astr.find("\n", fini1) line += astr.count("\n", ind, start2+1) spanlist.append((start, start2+1, fini1, fini2+1, line)) line += astr.count("\n", start2+1, fini2) ind = fini2 spanlist.sort() return spanlist def paren_repl(obj): torep = obj.group(1) numrep = obj.group(2) return ','.join([torep]*int(numrep)) parenrep = re.compile(r"[(]([^)]*)[)]\*(\d+)") plainrep = re.compile(r"([^*]+)\*(\d+)") def parse_values(astr): # replaces all occurrences of '(a,b,c)*4' in astr # with 'a,b,c,a,b,c,a,b,c,a,b,c'. Empty braces generate # empty values, i.e., ()*4 yields ',,,'. The result is # split at ',' and a list of values returned. astr = parenrep.sub(paren_repl, astr) # replaces occurences of xxx*3 with xxx, xxx, xxx astr = ','.join([plainrep.sub(paren_repl, x.strip()) for x in astr.split(',')]) return astr.split(',') stripast = re.compile(r"\n\s*\*?") named_re = re.compile(r"#\s*(\w*)\s*=([^#]*)#") exclude_vars_re = re.compile(r"(\w*)=(\w*)") exclude_re = re.compile(":exclude:") def parse_loop_header(loophead) : """Find all named replacements in the header Returns a list of dictionaries, one for each loop iteration, where each key is a name to be substituted and the corresponding value is the replacement string. Also return a list of exclusions. The exclusions are dictionaries of key value pairs. There can be more than one exclusion. [{'var1':'value1', 'var2', 'value2'[,...]}, ...] """ # Strip out '\n' and leading '*', if any, in continuation lines. # This should not effect code previous to this change as # continuation lines were not allowed. loophead = stripast.sub("", loophead) # parse out the names and lists of values names = [] reps = named_re.findall(loophead) nsub = None for rep in reps: name = rep[0] vals = parse_values(rep[1]) size = len(vals) if nsub is None : nsub = size elif nsub != size : msg = "Mismatch in number of values:\n%s = %s" % (name, vals) raise ValueError(msg) names.append((name, vals)) # Find any exclude variables excludes = [] for obj in exclude_re.finditer(loophead): span = obj.span() # find next newline endline = loophead.find('\n', span[1]) substr = loophead[span[1]:endline] ex_names = exclude_vars_re.findall(substr) excludes.append(dict(ex_names)) # generate list of dictionaries, one for each template iteration dlist = [] if nsub is None : raise ValueError("No substitution variables found") for i in range(nsub) : tmp = {} for name, vals in names : tmp[name] = vals[i] dlist.append(tmp) return dlist replace_re = re.compile(r"@([\w]+)@") def parse_string(astr, env, level, line) : lineno = "#line %d\n" % line # local function for string replacement, uses env def replace(match): name = match.group(1) try : val = env[name] except KeyError: msg = 'line %d: no definition of key "%s"'%(line, name) raise ValueError(msg) return val code = [lineno] struct = parse_structure(astr, level) if struct : # recurse over inner loops oldend = 0 newlevel = level + 1 for sub in struct: pref = astr[oldend:sub[0]] head = astr[sub[0]:sub[1]] text = astr[sub[1]:sub[2]] oldend = sub[3] newline = line + sub[4] code.append(replace_re.sub(replace, pref)) try : envlist = parse_loop_header(head) except ValueError: e = get_exception() msg = "line %d: %s" % (newline, e) raise ValueError(msg) for newenv in envlist : newenv.update(env) newcode = parse_string(text, newenv, newlevel, newline) code.extend(newcode) suff = astr[oldend:] code.append(replace_re.sub(replace, suff)) else : # replace keys code.append(replace_re.sub(replace, astr)) code.append('\n') return ''.join(code) def process_str(astr): code = [header] code.extend(parse_string(astr, global_names, 0, 1)) return ''.join(code) include_src_re = re.compile(r"(\n|\A)#include\s*['\"]" r"(?P[\w\d./\\]+[.]src)['\"]", re.I) def resolve_includes(source): d = os.path.dirname(source) fid = open(source) lines = [] for line in fid: m = include_src_re.match(line) if m: fn = m.group('name') if not os.path.isabs(fn): fn = os.path.join(d, fn) if os.path.isfile(fn): print('Including file', fn) lines.extend(resolve_includes(fn)) else: lines.append(line) else: lines.append(line) fid.close() return lines def process_file(source): lines = resolve_includes(source) sourcefile = os.path.normcase(source).replace("\\", "\\\\") try: code = process_str(''.join(lines)) except ValueError: e = get_exception() raise ValueError('In "%s" loop at %s' % (sourcefile, e)) return '#line 1 "%s"\n%s' % (sourcefile, code) def unique_key(adict): # this obtains a unique key given a dictionary # currently it works by appending together n of the letters of the # current keys and increasing n until a unique key is found # -- not particularly quick allkeys = list(adict.keys()) done = False n = 1 while not done: newkey = "".join([x[:n] for x in allkeys]) if newkey in allkeys: n += 1 else: done = True return newkey if __name__ == "__main__": try: file = sys.argv[1] except IndexError: fid = sys.stdin outfile = sys.stdout else: fid = open(file, 'r') (base, ext) = os.path.splitext(file) newname = base outfile = open(newname, 'w') allstr = fid.read() try: writestr = process_str(allstr) except ValueError: e = get_exception() raise ValueError("In %s loop at %s" % (file, e)) outfile.write(writestr) numpy-1.8.2/numpy/distutils/from_template.py0000664000175100017510000001721612370216242022436 0ustar vagrantvagrant00000000000000#!/usr/bin/python """ process_file(filename) takes templated file .xxx.src and produces .xxx file where .xxx is .pyf .f90 or .f using the following template rules: '<..>' denotes a template. All function and subroutine blocks in a source file with names that contain '<..>' will be replicated according to the rules in '<..>'. The number of comma-separeted words in '<..>' will determine the number of replicates. '<..>' may have two different forms, named and short. For example, named: where anywhere inside a block '

    ' will be replaced with 'd', 's', 'z', and 'c' for each replicate of the block. <_c> is already defined: <_c=s,d,c,z> <_t> is already defined: <_t=real,double precision,complex,double complex> short: , a short form of the named, useful when no

    appears inside a block. In general, '<..>' contains a comma separated list of arbitrary expressions. If these expression must contain a comma|leftarrow|rightarrow, then prepend the comma|leftarrow|rightarrow with a backslash. If an expression matches '\\' then it will be replaced by -th expression. Note that all '<..>' forms in a block must have the same number of comma-separated entries. Predefined named template rules: """ from __future__ import division, absolute_import, print_function __all__ = ['process_str', 'process_file'] import os import sys import re routine_start_re = re.compile(r'(\n|\A)(( (\$|\*))|)\s*(subroutine|function)\b', re.I) routine_end_re = re.compile(r'\n\s*end\s*(subroutine|function)\b.*(\n|\Z)', re.I) function_start_re = re.compile(r'\n (\$|\*)\s*function\b', re.I) def parse_structure(astr): """ Return a list of tuples for each function or subroutine each tuple is the start and end of a subroutine or function to be expanded. """ spanlist = [] ind = 0 while True: m = routine_start_re.search(astr, ind) if m is None: break start = m.start() if function_start_re.match(astr, start, m.end()): while True: i = astr.rfind('\n', ind, start) if i==-1: break start = i if astr[i:i+7]!='\n $': break start += 1 m = routine_end_re.search(astr, m.end()) ind = end = m and m.end()-1 or len(astr) spanlist.append((start, end)) return spanlist template_re = re.compile(r"<\s*(\w[\w\d]*)\s*>") named_re = re.compile(r"<\s*(\w[\w\d]*)\s*=\s*(.*?)\s*>") list_re = re.compile(r"<\s*((.*?))\s*>") def find_repl_patterns(astr): reps = named_re.findall(astr) names = {} for rep in reps: name = rep[0].strip() or unique_key(names) repl = rep[1].replace('\,', '@comma@') thelist = conv(repl) names[name] = thelist return names item_re = re.compile(r"\A\\(?P\d+)\Z") def conv(astr): b = astr.split(',') l = [x.strip() for x in b] for i in range(len(l)): m = item_re.match(l[i]) if m: j = int(m.group('index')) l[i] = l[j] return ','.join(l) def unique_key(adict): """ Obtain a unique key given a dictionary.""" allkeys = list(adict.keys()) done = False n = 1 while not done: newkey = '__l%s' % (n) if newkey in allkeys: n += 1 else: done = True return newkey template_name_re = re.compile(r'\A\s*(\w[\w\d]*)\s*\Z') def expand_sub(substr, names): substr = substr.replace('\>', '@rightarrow@') substr = substr.replace('\<', '@leftarrow@') lnames = find_repl_patterns(substr) substr = named_re.sub(r"<\1>", substr) # get rid of definition templates def listrepl(mobj): thelist = conv(mobj.group(1).replace('\,', '@comma@')) if template_name_re.match(thelist): return "<%s>" % (thelist) name = None for key in lnames.keys(): # see if list is already in dictionary if lnames[key] == thelist: name = key if name is None: # this list is not in the dictionary yet name = unique_key(lnames) lnames[name] = thelist return "<%s>" % name substr = list_re.sub(listrepl, substr) # convert all lists to named templates # newnames are constructed as needed numsubs = None base_rule = None rules = {} for r in template_re.findall(substr): if r not in rules: thelist = lnames.get(r, names.get(r, None)) if thelist is None: raise ValueError('No replicates found for <%s>' % (r)) if r not in names and not thelist.startswith('_'): names[r] = thelist rule = [i.replace('@comma@', ',') for i in thelist.split(',')] num = len(rule) if numsubs is None: numsubs = num rules[r] = rule base_rule = r elif num == numsubs: rules[r] = rule else: print("Mismatch in number of replacements (base <%s=%s>)" " for <%s=%s>. Ignoring." % (base_rule, ','.join(rules[base_rule]), r, thelist)) if not rules: return substr def namerepl(mobj): name = mobj.group(1) return rules.get(name, (k+1)*[name])[k] newstr = '' for k in range(numsubs): newstr += template_re.sub(namerepl, substr) + '\n\n' newstr = newstr.replace('@rightarrow@', '>') newstr = newstr.replace('@leftarrow@', '<') return newstr def process_str(allstr): newstr = allstr writestr = '' #_head # using _head will break free-format files struct = parse_structure(newstr) oldend = 0 names = {} names.update(_special_names) for sub in struct: writestr += newstr[oldend:sub[0]] names.update(find_repl_patterns(newstr[oldend:sub[0]])) writestr += expand_sub(newstr[sub[0]:sub[1]], names) oldend = sub[1] writestr += newstr[oldend:] return writestr include_src_re = re.compile(r"(\n|\A)\s*include\s*['\"](?P[\w\d./\\]+[.]src)['\"]", re.I) def resolve_includes(source): d = os.path.dirname(source) fid = open(source) lines = [] for line in fid: m = include_src_re.match(line) if m: fn = m.group('name') if not os.path.isabs(fn): fn = os.path.join(d, fn) if os.path.isfile(fn): print('Including file', fn) lines.extend(resolve_includes(fn)) else: lines.append(line) else: lines.append(line) fid.close() return lines def process_file(source): lines = resolve_includes(source) return process_str(''.join(lines)) _special_names = find_repl_patterns(''' <_c=s,d,c,z> <_t=real,double precision,complex,double complex> ''') if __name__ == "__main__": try: file = sys.argv[1] except IndexError: fid = sys.stdin outfile = sys.stdout else: fid = open(file, 'r') (base, ext) = os.path.splitext(file) newname = base outfile = open(newname, 'w') allstr = fid.read() writestr = process_str(allstr) outfile.write(writestr) numpy-1.8.2/numpy/distutils/compat.py0000664000175100017510000000033212370216242021052 0ustar vagrantvagrant00000000000000"""Small modules to cope with python 2 vs 3 incompatibilities inside numpy.distutils """ from __future__ import division, absolute_import, print_function import sys def get_exception(): return sys.exc_info()[1] numpy-1.8.2/numpy/distutils/numpy_distribution.py0000664000175100017510000000127412370216242023544 0ustar vagrantvagrant00000000000000# XXX: Handle setuptools ? from __future__ import division, absolute_import, print_function from distutils.core import Distribution # This class is used because we add new files (sconscripts, and so on) with the # scons command class NumpyDistribution(Distribution): def __init__(self, attrs = None): # A list of (sconscripts, pre_hook, post_hook, src, parent_names) self.scons_data = [] # A list of installable libraries self.installed_libraries = [] # A dict of pkg_config files to generate/install self.installed_pkg_config = {} Distribution.__init__(self, attrs) def has_scons_scripts(self): return bool(self.scons_data) numpy-1.8.2/numpy/distutils/npy_pkg_config.py0000664000175100017510000003256412370216242022577 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function import sys import re import os import shlex if sys.version_info[0] < 3: from ConfigParser import SafeConfigParser, NoOptionError else: from configparser import ConfigParser, SafeConfigParser, NoOptionError __all__ = ['FormatError', 'PkgNotFound', 'LibraryInfo', 'VariableSet', 'read_config', 'parse_flags'] _VAR = re.compile('\$\{([a-zA-Z0-9_-]+)\}') class FormatError(IOError): """ Exception thrown when there is a problem parsing a configuration file. """ def __init__(self, msg): self.msg = msg def __str__(self): return self.msg class PkgNotFound(IOError): """Exception raised when a package can not be located.""" def __init__(self, msg): self.msg = msg def __str__(self): return self.msg def parse_flags(line): """ Parse a line from a config file containing compile flags. Parameters ---------- line : str A single line containing one or more compile flags. Returns ------- d : dict Dictionary of parsed flags, split into relevant categories. These categories are the keys of `d`: * 'include_dirs' * 'library_dirs' * 'libraries' * 'macros' * 'ignored' """ lexer = shlex.shlex(line) lexer.whitespace_split = True d = {'include_dirs': [], 'library_dirs': [], 'libraries': [], 'macros': [], 'ignored': []} def next_token(t): if t.startswith('-I'): if len(t) > 2: d['include_dirs'].append(t[2:]) else: t = lexer.get_token() d['include_dirs'].append(t) elif t.startswith('-L'): if len(t) > 2: d['library_dirs'].append(t[2:]) else: t = lexer.get_token() d['library_dirs'].append(t) elif t.startswith('-l'): d['libraries'].append(t[2:]) elif t.startswith('-D'): d['macros'].append(t[2:]) else: d['ignored'].append(t) return lexer.get_token() t = lexer.get_token() while t: t = next_token(t) return d def _escape_backslash(val): return val.replace('\\', '\\\\') class LibraryInfo(object): """ Object containing build information about a library. Parameters ---------- name : str The library name. description : str Description of the library. version : str Version string. sections : dict The sections of the configuration file for the library. The keys are the section headers, the values the text under each header. vars : class instance A `VariableSet` instance, which contains ``(name, value)`` pairs for variables defined in the configuration file for the library. requires : sequence, optional The required libraries for the library to be installed. Notes ----- All input parameters (except "sections" which is a method) are available as attributes of the same name. """ def __init__(self, name, description, version, sections, vars, requires=None): self.name = name self.description = description if requires: self.requires = requires else: self.requires = [] self.version = version self._sections = sections self.vars = vars def sections(self): """ Return the section headers of the config file. Parameters ---------- None Returns ------- keys : list of str The list of section headers. """ return list(self._sections.keys()) def cflags(self, section="default"): val = self.vars.interpolate(self._sections[section]['cflags']) return _escape_backslash(val) def libs(self, section="default"): val = self.vars.interpolate(self._sections[section]['libs']) return _escape_backslash(val) def __str__(self): m = ['Name: %s' % self.name] m.append('Description: %s' % self.description) if self.requires: m.append('Requires:') else: m.append('Requires: %s' % ",".join(self.requires)) m.append('Version: %s' % self.version) return "\n".join(m) class VariableSet(object): """ Container object for the variables defined in a config file. `VariableSet` can be used as a plain dictionary, with the variable names as keys. Parameters ---------- d : dict Dict of items in the "variables" section of the configuration file. """ def __init__(self, d): self._raw_data = dict([(k, v) for k, v in d.items()]) self._re = {} self._re_sub = {} self._init_parse() def _init_parse(self): for k, v in self._raw_data.items(): self._init_parse_var(k, v) def _init_parse_var(self, name, value): self._re[name] = re.compile(r'\$\{%s\}' % name) self._re_sub[name] = value def interpolate(self, value): # Brute force: we keep interpolating until there is no '${var}' anymore # or until interpolated string is equal to input string def _interpolate(value): for k in self._re.keys(): value = self._re[k].sub(self._re_sub[k], value) return value while _VAR.search(value): nvalue = _interpolate(value) if nvalue == value: break value = nvalue return value def variables(self): """ Return the list of variable names. Parameters ---------- None Returns ------- names : list of str The names of all variables in the `VariableSet` instance. """ return list(self._raw_data.keys()) # Emulate a dict to set/get variables values def __getitem__(self, name): return self._raw_data[name] def __setitem__(self, name, value): self._raw_data[name] = value self._init_parse_var(name, value) def parse_meta(config): if not config.has_section('meta'): raise FormatError("No meta section found !") d = {} for name, value in config.items('meta'): d[name] = value for k in ['name', 'description', 'version']: if not k in d: raise FormatError("Option %s (section [meta]) is mandatory, " "but not found" % k) if not 'requires' in d: d['requires'] = [] return d def parse_variables(config): if not config.has_section('variables'): raise FormatError("No variables section found !") d = {} for name, value in config.items("variables"): d[name] = value return VariableSet(d) def parse_sections(config): return meta_d, r def pkg_to_filename(pkg_name): return "%s.ini" % pkg_name def parse_config(filename, dirs=None): if dirs: filenames = [os.path.join(d, filename) for d in dirs] else: filenames = [filename] if sys.version[:3] > '3.1': # SafeConfigParser is deprecated in py-3.2 and renamed to ConfigParser config = ConfigParser() else: config = SafeConfigParser() n = config.read(filenames) if not len(n) >= 1: raise PkgNotFound("Could not find file(s) %s" % str(filenames)) # Parse meta and variables sections meta = parse_meta(config) vars = {} if config.has_section('variables'): for name, value in config.items("variables"): vars[name] = _escape_backslash(value) # Parse "normal" sections secs = [s for s in config.sections() if not s in ['meta', 'variables']] sections = {} requires = {} for s in secs: d = {} if config.has_option(s, "requires"): requires[s] = config.get(s, 'requires') for name, value in config.items(s): d[name] = value sections[s] = d return meta, vars, sections, requires def _read_config_imp(filenames, dirs=None): def _read_config(f): meta, vars, sections, reqs = parse_config(f, dirs) # recursively add sections and variables of required libraries for rname, rvalue in reqs.items(): nmeta, nvars, nsections, nreqs = _read_config(pkg_to_filename(rvalue)) # Update var dict for variables not in 'top' config file for k, v in nvars.items(): if not k in vars: vars[k] = v # Update sec dict for oname, ovalue in nsections[rname].items(): if ovalue: sections[rname][oname] += ' %s' % ovalue return meta, vars, sections, reqs meta, vars, sections, reqs = _read_config(filenames) # FIXME: document this. If pkgname is defined in the variables section, and # there is no pkgdir variable defined, pkgdir is automatically defined to # the path of pkgname. This requires the package to be imported to work if not 'pkgdir' in vars and "pkgname" in vars: pkgname = vars["pkgname"] if not pkgname in sys.modules: raise ValueError("You should import %s to get information on %s" % (pkgname, meta["name"])) mod = sys.modules[pkgname] vars["pkgdir"] = _escape_backslash(os.path.dirname(mod.__file__)) return LibraryInfo(name=meta["name"], description=meta["description"], version=meta["version"], sections=sections, vars=VariableSet(vars)) # Trivial cache to cache LibraryInfo instances creation. To be really # efficient, the cache should be handled in read_config, since a same file can # be parsed many time outside LibraryInfo creation, but I doubt this will be a # problem in practice _CACHE = {} def read_config(pkgname, dirs=None): """ Return library info for a package from its configuration file. Parameters ---------- pkgname : str Name of the package (should match the name of the .ini file, without the extension, e.g. foo for the file foo.ini). dirs : sequence, optional If given, should be a sequence of directories - usually including the NumPy base directory - where to look for npy-pkg-config files. Returns ------- pkginfo : class instance The `LibraryInfo` instance containing the build information. Raises ------ PkgNotFound If the package is not found. See Also -------- misc_util.get_info, misc_util.get_pkg_info Examples -------- >>> npymath_info = np.distutils.npy_pkg_config.read_config('npymath') >>> type(npymath_info) >>> print npymath_info Name: npymath Description: Portable, core math library implementing C99 standard Requires: Version: 0.1 #random """ try: return _CACHE[pkgname] except KeyError: v = _read_config_imp(pkg_to_filename(pkgname), dirs) _CACHE[pkgname] = v return v # TODO: # - implements version comparison (modversion + atleast) # pkg-config simple emulator - useful for debugging, and maybe later to query # the system if __name__ == '__main__': import sys from optparse import OptionParser import glob parser = OptionParser() parser.add_option("--cflags", dest="cflags", action="store_true", help="output all preprocessor and compiler flags") parser.add_option("--libs", dest="libs", action="store_true", help="output all linker flags") parser.add_option("--use-section", dest="section", help="use this section instead of default for options") parser.add_option("--version", dest="version", action="store_true", help="output version") parser.add_option("--atleast-version", dest="min_version", help="Minimal version") parser.add_option("--list-all", dest="list_all", action="store_true", help="Minimal version") parser.add_option("--define-variable", dest="define_variable", help="Replace variable with the given value") (options, args) = parser.parse_args(sys.argv) if len(args) < 2: raise ValueError("Expect package name on the command line:") if options.list_all: files = glob.glob("*.ini") for f in files: info = read_config(f) print("%s\t%s - %s" % (info.name, info.name, info.description)) pkg_name = args[1] import os d = os.environ.get('NPY_PKG_CONFIG_PATH') if d: info = read_config(pkg_name, ['numpy/core/lib/npy-pkg-config', '.', d]) else: info = read_config(pkg_name, ['numpy/core/lib/npy-pkg-config', '.']) if options.section: section = options.section else: section = "default" if options.define_variable: m = re.search('([\S]+)=([\S]+)', options.define_variable) if not m: raise ValueError("--define-variable option should be of " \ "the form --define-variable=foo=bar") else: name = m.group(1) value = m.group(2) info.vars[name] = value if options.cflags: print(info.cflags(section)) if options.libs: print(info.libs(section)) if options.version: print(info.version) if options.min_version: print(info.version >= options.min_version) numpy-1.8.2/numpy/distutils/log.py0000664000175100017510000000527112370216242020357 0ustar vagrantvagrant00000000000000# Colored log, requires Python 2.3 or up. from __future__ import division, absolute_import, print_function import sys from distutils.log import * from distutils.log import Log as old_Log from distutils.log import _global_log if sys.version_info[0] < 3: from .misc_util import (red_text, default_text, cyan_text, green_text, is_sequence, is_string) else: from numpy.distutils.misc_util import (red_text, default_text, cyan_text, green_text, is_sequence, is_string) def _fix_args(args,flag=1): if is_string(args): return args.replace('%', '%%') if flag and is_sequence(args): return tuple([_fix_args(a, flag=0) for a in args]) return args class Log(old_Log): def _log(self, level, msg, args): if level >= self.threshold: if args: msg = msg % _fix_args(args) if 0: if msg.startswith('copying ') and msg.find(' -> ') != -1: return if msg.startswith('byte-compiling '): return print(_global_color_map[level](msg)) sys.stdout.flush() def good(self, msg, *args): """ If we log WARN messages, log this message as a 'nice' anti-warn message. """ if WARN >= self.threshold: if args: print(green_text(msg % _fix_args(args))) else: print(green_text(msg)) sys.stdout.flush() _global_log.__class__ = Log good = _global_log.good def set_threshold(level, force=False): prev_level = _global_log.threshold if prev_level > DEBUG or force: # If we're running at DEBUG, don't change the threshold, as there's # likely a good reason why we're running at this level. _global_log.threshold = level if level <= DEBUG: info('set_threshold: setting threshold to DEBUG level,' ' it can be changed only with force argument') else: info('set_threshold: not changing threshold from DEBUG level' ' %s to %s' % (prev_level, level)) return prev_level def set_verbosity(v, force=False): prev_level = _global_log.threshold if v < 0: set_threshold(ERROR, force) elif v == 0: set_threshold(WARN, force) elif v == 1: set_threshold(INFO, force) elif v >= 2: set_threshold(DEBUG, force) return {FATAL:-2,ERROR:-1,WARN:0,INFO:1,DEBUG:2}.get(prev_level, 1) _global_color_map = { DEBUG:cyan_text, INFO:default_text, WARN:red_text, ERROR:red_text, FATAL:red_text } # don't use INFO,.. flags in set_verbosity, these flags are for set_threshold. set_verbosity(0, force=True) numpy-1.8.2/numpy/distutils/unixccompiler.py0000664000175100017510000001001212370216242022444 0ustar vagrantvagrant00000000000000""" unixccompiler - can handle very long argument lists for ar. """ from __future__ import division, absolute_import, print_function import os from distutils.errors import DistutilsExecError, CompileError from distutils.unixccompiler import * from numpy.distutils.ccompiler import replace_method from numpy.distutils.compat import get_exception if sys.version_info[0] < 3: from . import log else: from numpy.distutils import log # Note that UnixCCompiler._compile appeared in Python 2.3 def UnixCCompiler__compile(self, obj, src, ext, cc_args, extra_postargs, pp_opts): """Compile a single source files with a Unix-style compiler.""" # HP ad-hoc fix, see ticket 1383 ccomp = self.compiler_so if ccomp[0] == 'aCC': # remove flags that will trigger ANSI-C mode for aCC if '-Ae' in ccomp: ccomp.remove('-Ae') if '-Aa' in ccomp: ccomp.remove('-Aa') # add flags for (almost) sane C++ handling ccomp += ['-AA'] self.compiler_so = ccomp display = '%s: %s' % (os.path.basename(self.compiler_so[0]), src) try: self.spawn(self.compiler_so + cc_args + [src, '-o', obj] + extra_postargs, display = display) except DistutilsExecError: msg = str(get_exception()) raise CompileError(msg) replace_method(UnixCCompiler, '_compile', UnixCCompiler__compile) def UnixCCompiler_create_static_lib(self, objects, output_libname, output_dir=None, debug=0, target_lang=None): """ Build a static library in a separate sub-process. Parameters ---------- objects : list or tuple of str List of paths to object files used to build the static library. output_libname : str The library name as an absolute or relative (if `output_dir` is used) path. output_dir : str, optional The path to the output directory. Default is None, in which case the ``output_dir`` attribute of the UnixCCompiler instance. debug : bool, optional This parameter is not used. target_lang : str, optional This parameter is not used. Returns ------- None """ objects, output_dir = self._fix_object_args(objects, output_dir) output_filename = \ self.library_filename(output_libname, output_dir=output_dir) if self._need_link(objects, output_filename): try: # previous .a may be screwed up; best to remove it first # and recreate. # Also, ar on OS X doesn't handle updating universal archives os.unlink(output_filename) except (IOError, OSError): pass self.mkpath(os.path.dirname(output_filename)) tmp_objects = objects + self.objects while tmp_objects: objects = tmp_objects[:50] tmp_objects = tmp_objects[50:] display = '%s: adding %d object files to %s' % ( os.path.basename(self.archiver[0]), len(objects), output_filename) self.spawn(self.archiver + [output_filename] + objects, display = display) # Not many Unices required ranlib anymore -- SunOS 4.x is, I # think the only major Unix that does. Maybe we need some # platform intelligence here to skip ranlib if it's not # needed -- or maybe Python's configure script took care of # it for us, hence the check for leading colon. if self.ranlib: display = '%s:@ %s' % (os.path.basename(self.ranlib[0]), output_filename) try: self.spawn(self.ranlib + [output_filename], display = display) except DistutilsExecError: msg = str(get_exception()) raise LibError(msg) else: log.debug("skipping %s (up-to-date)", output_filename) return replace_method(UnixCCompiler, 'create_static_lib', UnixCCompiler_create_static_lib) numpy-1.8.2/numpy/distutils/command/0000775000175100017510000000000012371375430020643 5ustar vagrantvagrant00000000000000numpy-1.8.2/numpy/distutils/command/install.py0000664000175100017510000000577012370216243022667 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function import sys if 'setuptools' in sys.modules: import setuptools.command.install as old_install_mod have_setuptools = True else: import distutils.command.install as old_install_mod have_setuptools = False old_install = old_install_mod.install from distutils.file_util import write_file class install(old_install): # Always run install_clib - the command is cheap, so no need to bypass it; # but it's not run by setuptools -- so it's run again in install_data sub_commands = old_install.sub_commands + [ ('install_clib', lambda x: True) ] def finalize_options (self): old_install.finalize_options(self) self.install_lib = self.install_libbase def setuptools_run(self): """ The setuptools version of the .run() method. We must pull in the entire code so we can override the level used in the _getframe() call since we wrap this call by one more level. """ # 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) # Attempt to detect whether we were called from setup() or by another # command. If we were called by setup(), our caller will be the # 'run_command' method in 'distutils.dist', and *its* caller will be # the 'run_commands' method. If we were called any other way, our # immediate caller *might* be 'run_command', but it won't have been # called by 'run_commands'. This is slightly kludgy, but seems to # work. # caller = sys._getframe(3) caller_module = caller.f_globals.get('__name__', '') caller_name = caller.f_code.co_name if caller_module != 'distutils.dist' or caller_name!='run_commands': # We weren't called from the command line or setup(), so we # should run in backward-compatibility mode to support bdist_* # commands. old_install_mod._install.run(self) else: self.do_egg_install() def run(self): if not have_setuptools: r = old_install.run(self) else: r = self.setuptools_run() if self.record: # bdist_rpm fails when INSTALLED_FILES contains # paths with spaces. Such paths must be enclosed # with double-quotes. f = open(self.record, 'r') lines = [] need_rewrite = False for l in f: l = l.rstrip() if ' ' in l: need_rewrite = True l = '"%s"' % (l) lines.append(l) f.close() if need_rewrite: self.execute(write_file, (self.record, lines), "re-writing list of installed files to '%s'" % self.record) return r numpy-1.8.2/numpy/distutils/command/build_ext.py0000664000175100017510000005175312370216242023201 0ustar vagrantvagrant00000000000000""" Modified version of build_ext that handles fortran source files. """ from __future__ import division, absolute_import, print_function import os import sys from glob import glob from distutils.dep_util import newer_group from distutils.command.build_ext import build_ext as old_build_ext from distutils.errors import DistutilsFileError, DistutilsSetupError,\ DistutilsError from distutils.file_util import copy_file from numpy.distutils import log from numpy.distutils.exec_command import exec_command from numpy.distutils.system_info import combine_paths from numpy.distutils.misc_util import filter_sources, has_f_sources, \ has_cxx_sources, get_ext_source_files, \ get_numpy_include_dirs, is_sequence, get_build_architecture, \ msvc_version from numpy.distutils.command.config_compiler import show_fortran_compilers try: set except NameError: from sets import Set as set class build_ext (old_build_ext): description = "build C/C++/F extensions (compile/link to build directory)" user_options = old_build_ext.user_options + [ ('fcompiler=', None, "specify the Fortran compiler type"), ] help_options = old_build_ext.help_options + [ ('help-fcompiler', None, "list available Fortran compilers", show_fortran_compilers), ] def initialize_options(self): old_build_ext.initialize_options(self) self.fcompiler = None def finalize_options(self): incl_dirs = self.include_dirs old_build_ext.finalize_options(self) if incl_dirs is not None: self.include_dirs.extend(self.distribution.include_dirs or []) def run(self): if not self.extensions: return # Make sure that extension sources are complete. self.run_command('build_src') if self.distribution.has_c_libraries(): if self.inplace: if self.distribution.have_run.get('build_clib'): log.warn('build_clib already run, it is too late to ' \ 'ensure in-place build of build_clib') build_clib = self.distribution.get_command_obj('build_clib') else: build_clib = self.distribution.get_command_obj('build_clib') build_clib.inplace = 1 build_clib.ensure_finalized() build_clib.run() self.distribution.have_run['build_clib'] = 1 else: self.run_command('build_clib') build_clib = self.get_finalized_command('build_clib') self.library_dirs.append(build_clib.build_clib) else: build_clib = None # Not including C libraries to the list of # extension libraries automatically to prevent # bogus linking commands. Extensions must # explicitly specify the C libraries that they use. from distutils.ccompiler import new_compiler from numpy.distutils.fcompiler import new_fcompiler compiler_type = self.compiler # Initialize C compiler: self.compiler = new_compiler(compiler=compiler_type, verbose=self.verbose, dry_run=self.dry_run, force=self.force) self.compiler.customize(self.distribution) self.compiler.customize_cmd(self) self.compiler.show_customization() # Create mapping of libraries built by build_clib: clibs = {} if build_clib is not None: for libname, build_info in build_clib.libraries or []: if libname in clibs and clibs[libname] != build_info: log.warn('library %r defined more than once,'\ ' overwriting build_info\n%s... \nwith\n%s...' \ % (libname, repr(clibs[libname])[:300], repr(build_info)[:300])) clibs[libname] = build_info # .. and distribution libraries: for libname, build_info in self.distribution.libraries or []: if libname in clibs: # build_clib libraries have a precedence before distribution ones continue clibs[libname] = build_info # Determine if C++/Fortran 77/Fortran 90 compilers are needed. # Update extension libraries, library_dirs, and macros. all_languages = set() for ext in self.extensions: ext_languages = set() c_libs = [] c_lib_dirs = [] macros = [] for libname in ext.libraries: if libname in clibs: binfo = clibs[libname] c_libs += binfo.get('libraries', []) c_lib_dirs += binfo.get('library_dirs', []) for m in binfo.get('macros', []): if m not in macros: macros.append(m) for l in clibs.get(libname, {}).get('source_languages', []): ext_languages.add(l) if c_libs: new_c_libs = ext.libraries + c_libs log.info('updating extension %r libraries from %r to %r' % (ext.name, ext.libraries, new_c_libs)) ext.libraries = new_c_libs ext.library_dirs = ext.library_dirs + c_lib_dirs if macros: log.info('extending extension %r defined_macros with %r' % (ext.name, macros)) ext.define_macros = ext.define_macros + macros # determine extension languages if has_f_sources(ext.sources): ext_languages.add('f77') if has_cxx_sources(ext.sources): ext_languages.add('c++') l = ext.language or self.compiler.detect_language(ext.sources) if l: ext_languages.add(l) # reset language attribute for choosing proper linker if 'c++' in ext_languages: ext_language = 'c++' elif 'f90' in ext_languages: ext_language = 'f90' elif 'f77' in ext_languages: ext_language = 'f77' else: ext_language = 'c' # default if l and l != ext_language and ext.language: log.warn('resetting extension %r language from %r to %r.' % (ext.name, l, ext_language)) ext.language = ext_language # global language all_languages.update(ext_languages) need_f90_compiler = 'f90' in all_languages need_f77_compiler = 'f77' in all_languages need_cxx_compiler = 'c++' in all_languages # Initialize C++ compiler: if need_cxx_compiler: self._cxx_compiler = new_compiler(compiler=compiler_type, verbose=self.verbose, dry_run=self.dry_run, force=self.force) compiler = self._cxx_compiler compiler.customize(self.distribution, need_cxx=need_cxx_compiler) compiler.customize_cmd(self) compiler.show_customization() self._cxx_compiler = compiler.cxx_compiler() else: self._cxx_compiler = None # Initialize Fortran 77 compiler: if need_f77_compiler: ctype = self.fcompiler self._f77_compiler = new_fcompiler(compiler=self.fcompiler, verbose=self.verbose, dry_run=self.dry_run, force=self.force, requiref90=False, c_compiler=self.compiler) fcompiler = self._f77_compiler if fcompiler: ctype = fcompiler.compiler_type fcompiler.customize(self.distribution) if fcompiler and fcompiler.get_version(): fcompiler.customize_cmd(self) fcompiler.show_customization() else: self.warn('f77_compiler=%s is not available.' % (ctype)) self._f77_compiler = None else: self._f77_compiler = None # Initialize Fortran 90 compiler: if need_f90_compiler: ctype = self.fcompiler self._f90_compiler = new_fcompiler(compiler=self.fcompiler, verbose=self.verbose, dry_run=self.dry_run, force=self.force, requiref90=True, c_compiler = self.compiler) fcompiler = self._f90_compiler if fcompiler: ctype = fcompiler.compiler_type fcompiler.customize(self.distribution) if fcompiler and fcompiler.get_version(): fcompiler.customize_cmd(self) fcompiler.show_customization() else: self.warn('f90_compiler=%s is not available.' % (ctype)) self._f90_compiler = None else: self._f90_compiler = None # Build extensions self.build_extensions() def swig_sources(self, sources): # Do nothing. Swig sources have beed handled in build_src command. return sources def build_extension(self, ext): sources = ext.sources if sources is None or not is_sequence(sources): raise DistutilsSetupError( ("in 'ext_modules' option (extension '%s'), " + "'sources' must be present and must be " + "a list of source filenames") % ext.name) sources = list(sources) if not sources: return fullname = self.get_ext_fullname(ext.name) if self.inplace: modpath = fullname.split('.') package = '.'.join(modpath[0:-1]) base = modpath[-1] build_py = self.get_finalized_command('build_py') package_dir = build_py.get_package_dir(package) ext_filename = os.path.join(package_dir, self.get_ext_filename(base)) else: ext_filename = os.path.join(self.build_lib, self.get_ext_filename(fullname)) depends = sources + ext.depends if not (self.force or newer_group(depends, ext_filename, 'newer')): log.debug("skipping '%s' extension (up-to-date)", ext.name) return else: log.info("building '%s' extension", ext.name) extra_args = ext.extra_compile_args or [] macros = ext.define_macros[:] for undef in ext.undef_macros: macros.append((undef,)) c_sources, cxx_sources, f_sources, fmodule_sources = \ filter_sources(ext.sources) if self.compiler.compiler_type=='msvc': if cxx_sources: # Needed to compile kiva.agg._agg extension. extra_args.append('/Zm1000') # this hack works around the msvc compiler attributes # problem, msvc uses its own convention :( c_sources += cxx_sources cxx_sources = [] # Set Fortran/C++ compilers for compilation and linking. if ext.language=='f90': fcompiler = self._f90_compiler elif ext.language=='f77': fcompiler = self._f77_compiler else: # in case ext.language is c++, for instance fcompiler = self._f90_compiler or self._f77_compiler if fcompiler is not None: fcompiler.extra_f77_compile_args = (ext.extra_f77_compile_args or []) if hasattr(ext, 'extra_f77_compile_args') else [] fcompiler.extra_f90_compile_args = (ext.extra_f90_compile_args or []) if hasattr(ext, 'extra_f90_compile_args') else [] cxx_compiler = self._cxx_compiler # check for the availability of required compilers if cxx_sources and cxx_compiler is None: raise DistutilsError("extension %r has C++ sources" \ "but no C++ compiler found" % (ext.name)) if (f_sources or fmodule_sources) and fcompiler is None: raise DistutilsError("extension %r has Fortran sources " \ "but no Fortran compiler found" % (ext.name)) if ext.language in ['f77', 'f90'] and fcompiler is None: self.warn("extension %r has Fortran libraries " \ "but no Fortran linker found, using default linker" % (ext.name)) if ext.language=='c++' and cxx_compiler is None: self.warn("extension %r has C++ libraries " \ "but no C++ linker found, using default linker" % (ext.name)) kws = {'depends':ext.depends} output_dir = self.build_temp include_dirs = ext.include_dirs + get_numpy_include_dirs() c_objects = [] if c_sources: log.info("compiling C sources") c_objects = self.compiler.compile(c_sources, output_dir=output_dir, macros=macros, include_dirs=include_dirs, debug=self.debug, extra_postargs=extra_args, **kws) if cxx_sources: log.info("compiling C++ sources") c_objects += cxx_compiler.compile(cxx_sources, output_dir=output_dir, macros=macros, include_dirs=include_dirs, debug=self.debug, extra_postargs=extra_args, **kws) extra_postargs = [] f_objects = [] if fmodule_sources: log.info("compiling Fortran 90 module sources") module_dirs = ext.module_dirs[:] module_build_dir = os.path.join( self.build_temp, os.path.dirname( self.get_ext_filename(fullname))) self.mkpath(module_build_dir) if fcompiler.module_dir_switch is None: existing_modules = glob('*.mod') extra_postargs += fcompiler.module_options( module_dirs, module_build_dir) f_objects += fcompiler.compile(fmodule_sources, output_dir=self.build_temp, macros=macros, include_dirs=include_dirs, debug=self.debug, extra_postargs=extra_postargs, depends=ext.depends) if fcompiler.module_dir_switch is None: for f in glob('*.mod'): if f in existing_modules: continue t = os.path.join(module_build_dir, f) if os.path.abspath(f)==os.path.abspath(t): continue if os.path.isfile(t): os.remove(t) try: self.move_file(f, module_build_dir) except DistutilsFileError: log.warn('failed to move %r to %r' % (f, module_build_dir)) if f_sources: log.info("compiling Fortran sources") f_objects += fcompiler.compile(f_sources, output_dir=self.build_temp, macros=macros, include_dirs=include_dirs, debug=self.debug, extra_postargs=extra_postargs, depends=ext.depends) objects = c_objects + f_objects if ext.extra_objects: objects.extend(ext.extra_objects) extra_args = ext.extra_link_args or [] libraries = self.get_libraries(ext)[:] library_dirs = ext.library_dirs[:] linker = self.compiler.link_shared_object # Always use system linker when using MSVC compiler. if self.compiler.compiler_type=='msvc': # expand libraries with fcompiler libraries as we are # not using fcompiler linker self._libs_with_msvc_and_fortran(fcompiler, libraries, library_dirs) elif ext.language in ['f77', 'f90'] and fcompiler is not None: linker = fcompiler.link_shared_object if ext.language=='c++' and cxx_compiler is not None: linker = cxx_compiler.link_shared_object if sys.version[:3]>='2.3': kws = {'target_lang':ext.language} else: kws = {} linker(objects, ext_filename, libraries=libraries, library_dirs=library_dirs, runtime_library_dirs=ext.runtime_library_dirs, extra_postargs=extra_args, export_symbols=self.get_export_symbols(ext), debug=self.debug, build_temp=self.build_temp,**kws) def _add_dummy_mingwex_sym(self, c_sources): build_src = self.get_finalized_command("build_src").build_src build_clib = self.get_finalized_command("build_clib").build_clib objects = self.compiler.compile([os.path.join(build_src, "gfortran_vs2003_hack.c")], output_dir=self.build_temp) self.compiler.create_static_lib(objects, "_gfortran_workaround", output_dir=build_clib, debug=self.debug) def _libs_with_msvc_and_fortran(self, fcompiler, c_libraries, c_library_dirs): if fcompiler is None: return for libname in c_libraries: if libname.startswith('msvc'): continue fileexists = False for libdir in c_library_dirs or []: libfile = os.path.join(libdir, '%s.lib' % (libname)) if os.path.isfile(libfile): fileexists = True break if fileexists: continue # make g77-compiled static libs available to MSVC fileexists = False for libdir in c_library_dirs: libfile = os.path.join(libdir, 'lib%s.a' % (libname)) if os.path.isfile(libfile): # copy libname.a file to name.lib so that MSVC linker # can find it libfile2 = os.path.join(self.build_temp, libname + '.lib') copy_file(libfile, libfile2) if self.build_temp not in c_library_dirs: c_library_dirs.append(self.build_temp) fileexists = True break if fileexists: continue log.warn('could not find library %r in directories %s' % (libname, c_library_dirs)) # Always use system linker when using MSVC compiler. f_lib_dirs = [] for dir in fcompiler.library_dirs: # correct path when compiling in Cygwin but with normal Win # Python if dir.startswith('/usr/lib'): s, o = exec_command(['cygpath', '-w', dir], use_tee=False) if not s: dir = o f_lib_dirs.append(dir) c_library_dirs.extend(f_lib_dirs) # make g77-compiled static libs available to MSVC for lib in fcompiler.libraries: if not lib.startswith('msvc'): c_libraries.append(lib) p = combine_paths(f_lib_dirs, 'lib' + lib + '.a') if p: dst_name = os.path.join(self.build_temp, lib + '.lib') if not os.path.isfile(dst_name): copy_file(p[0], dst_name) if self.build_temp not in c_library_dirs: c_library_dirs.append(self.build_temp) def get_source_files (self): self.check_extensions_list(self.extensions) filenames = [] for ext in self.extensions: filenames.extend(get_ext_source_files(ext)) return filenames def get_outputs (self): self.check_extensions_list(self.extensions) outputs = [] for ext in self.extensions: if not ext.sources: continue fullname = self.get_ext_fullname(ext.name) outputs.append(os.path.join(self.build_lib, self.get_ext_filename(fullname))) return outputs numpy-1.8.2/numpy/distutils/command/egg_info.py0000664000175100017510000000065212370216242022767 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function from setuptools.command.egg_info import egg_info as _egg_info class egg_info(_egg_info): def run(self): # We need to ensure that build_src has been executed in order to give # setuptools' egg_info command real filenames instead of functions which # generate files. self.run_command("build_src") _egg_info.run(self) numpy-1.8.2/numpy/distutils/command/config.py0000664000175100017510000004147412370216243022467 0ustar vagrantvagrant00000000000000# Added Fortran compiler support to config. Currently useful only for # try_compile call. try_run works but is untested for most of Fortran # compilers (they must define linker_exe first). # Pearu Peterson from __future__ import division, absolute_import, print_function import os, signal import warnings import sys from distutils.command.config import config as old_config from distutils.command.config import LANG_EXT from distutils import log from distutils.file_util import copy_file from distutils.ccompiler import CompileError, LinkError import distutils from numpy.distutils.exec_command import exec_command from numpy.distutils.mingw32ccompiler import generate_manifest from numpy.distutils.command.autodist import check_inline, check_compiler_gcc4 from numpy.distutils.compat import get_exception LANG_EXT['f77'] = '.f' LANG_EXT['f90'] = '.f90' class config(old_config): old_config.user_options += [ ('fcompiler=', None, "specify the Fortran compiler type"), ] def initialize_options(self): self.fcompiler = None old_config.initialize_options(self) def try_run(self, body, headers=None, include_dirs=None, libraries=None, library_dirs=None, lang="c"): warnings.warn("\n+++++++++++++++++++++++++++++++++++++++++++++++++\n" \ "Usage of try_run is deprecated: please do not \n" \ "use it anymore, and avoid configuration checks \n" \ "involving running executable on the target machine.\n" \ "+++++++++++++++++++++++++++++++++++++++++++++++++\n", DeprecationWarning) return old_config.try_run(self, body, headers, include_dirs, libraries, library_dirs, lang) def _check_compiler (self): old_config._check_compiler(self) from numpy.distutils.fcompiler import FCompiler, new_fcompiler if sys.platform == 'win32' and self.compiler.compiler_type == 'msvc': # XXX: hack to circumvent a python 2.6 bug with msvc9compiler: # initialize call query_vcvarsall, which throws an IOError, and # causes an error along the way without much information. We try to # catch it here, hoping it is early enough, and print an helpful # message instead of Error: None. if not self.compiler.initialized: try: self.compiler.initialize() except IOError: e = get_exception() msg = """\ Could not initialize compiler instance: do you have Visual Studio installed ? If you are trying to build with mingw, please use python setup.py build -c mingw32 instead ). If you have Visual Studio installed, check it is correctly installed, and the right version (VS 2008 for python 2.6, VS 2003 for 2.5, etc...). Original exception was: %s, and the Compiler class was %s ============================================================================""" \ % (e, self.compiler.__class__.__name__) print ("""\ ============================================================================""") raise distutils.errors.DistutilsPlatformError(msg) if not isinstance(self.fcompiler, FCompiler): self.fcompiler = new_fcompiler(compiler=self.fcompiler, dry_run=self.dry_run, force=1, c_compiler=self.compiler) if self.fcompiler is not None: self.fcompiler.customize(self.distribution) if self.fcompiler.get_version(): self.fcompiler.customize_cmd(self) self.fcompiler.show_customization() def _wrap_method(self, mth, lang, args): from distutils.ccompiler import CompileError from distutils.errors import DistutilsExecError save_compiler = self.compiler if lang in ['f77', 'f90']: self.compiler = self.fcompiler try: ret = mth(*((self,)+args)) except (DistutilsExecError, CompileError): msg = str(get_exception()) self.compiler = save_compiler raise CompileError self.compiler = save_compiler return ret def _compile (self, body, headers, include_dirs, lang): return self._wrap_method(old_config._compile, lang, (body, headers, include_dirs, lang)) def _link (self, body, headers, include_dirs, libraries, library_dirs, lang): if self.compiler.compiler_type=='msvc': libraries = (libraries or [])[:] library_dirs = (library_dirs or [])[:] if lang in ['f77', 'f90']: lang = 'c' # always use system linker when using MSVC compiler if self.fcompiler: for d in self.fcompiler.library_dirs or []: # correct path when compiling in Cygwin but with # normal Win Python if d.startswith('/usr/lib'): s, o = exec_command(['cygpath', '-w', d], use_tee=False) if not s: d = o library_dirs.append(d) for libname in self.fcompiler.libraries or []: if libname not in libraries: libraries.append(libname) for libname in libraries: if libname.startswith('msvc'): continue fileexists = False for libdir in library_dirs or []: libfile = os.path.join(libdir, '%s.lib' % (libname)) if os.path.isfile(libfile): fileexists = True break if fileexists: continue # make g77-compiled static libs available to MSVC fileexists = False for libdir in library_dirs: libfile = os.path.join(libdir, 'lib%s.a' % (libname)) if os.path.isfile(libfile): # copy libname.a file to name.lib so that MSVC linker # can find it libfile2 = os.path.join(libdir, '%s.lib' % (libname)) copy_file(libfile, libfile2) self.temp_files.append(libfile2) fileexists = True break if fileexists: continue log.warn('could not find library %r in directories %s' \ % (libname, library_dirs)) elif self.compiler.compiler_type == 'mingw32': generate_manifest(self) return self._wrap_method(old_config._link, lang, (body, headers, include_dirs, libraries, library_dirs, lang)) def check_header(self, header, include_dirs=None, library_dirs=None, lang='c'): self._check_compiler() return self.try_compile( "/* we need a dummy line to make distutils happy */", [header], include_dirs) def check_decl(self, symbol, headers=None, include_dirs=None): self._check_compiler() body = """ int main() { #ifndef %s (void) %s; #endif ; return 0; }""" % (symbol, symbol) return self.try_compile(body, headers, include_dirs) def check_macro_true(self, symbol, headers=None, include_dirs=None): self._check_compiler() body = """ int main() { #if %s #else #error false or undefined macro #endif ; return 0; }""" % (symbol,) return self.try_compile(body, headers, include_dirs) def check_type(self, type_name, headers=None, include_dirs=None, library_dirs=None): """Check type availability. Return True if the type can be compiled, False otherwise""" self._check_compiler() # First check the type can be compiled body = r""" int main() { if ((%(name)s *) 0) return 0; if (sizeof (%(name)s)) return 0; } """ % {'name': type_name} st = False try: try: self._compile(body % {'type': type_name}, headers, include_dirs, 'c') st = True except distutils.errors.CompileError: st = False finally: self._clean() return st def check_type_size(self, type_name, headers=None, include_dirs=None, library_dirs=None, expected=None): """Check size of a given type.""" self._check_compiler() # First check the type can be compiled body = r""" typedef %(type)s npy_check_sizeof_type; int main () { static int test_array [1 - 2 * !(((long) (sizeof (npy_check_sizeof_type))) >= 0)]; test_array [0] = 0 ; return 0; } """ self._compile(body % {'type': type_name}, headers, include_dirs, 'c') self._clean() if expected: body = r""" typedef %(type)s npy_check_sizeof_type; int main () { static int test_array [1 - 2 * !(((long) (sizeof (npy_check_sizeof_type))) == %(size)s)]; test_array [0] = 0 ; return 0; } """ for size in expected: try: self._compile(body % {'type': type_name, 'size': size}, headers, include_dirs, 'c') self._clean() return size except CompileError: pass # this fails to *compile* if size > sizeof(type) body = r""" typedef %(type)s npy_check_sizeof_type; int main () { static int test_array [1 - 2 * !(((long) (sizeof (npy_check_sizeof_type))) <= %(size)s)]; test_array [0] = 0 ; return 0; } """ # The principle is simple: we first find low and high bounds of size # for the type, where low/high are looked up on a log scale. Then, we # do a binary search to find the exact size between low and high low = 0 mid = 0 while True: try: self._compile(body % {'type': type_name, 'size': mid}, headers, include_dirs, 'c') self._clean() break except CompileError: #log.info("failure to test for bound %d" % mid) low = mid + 1 mid = 2 * mid + 1 high = mid # Binary search: while low != high: mid = (high - low) // 2 + low try: self._compile(body % {'type': type_name, 'size': mid}, headers, include_dirs, 'c') self._clean() high = mid except CompileError: low = mid + 1 return low def check_func(self, func, headers=None, include_dirs=None, libraries=None, library_dirs=None, decl=False, call=False, call_args=None): # clean up distutils's config a bit: add void to main(), and # return a value. self._check_compiler() body = [] if decl: body.append("int %s (void);" % func) # Handle MSVC intrinsics: force MS compiler to make a function call. # Useful to test for some functions when built with optimization on, to # avoid build error because the intrinsic and our 'fake' test # declaration do not match. body.append("#ifdef _MSC_VER") body.append("#pragma function(%s)" % func) body.append("#endif") body.append("int main (void) {") if call: if call_args is None: call_args = '' body.append(" %s(%s);" % (func, call_args)) else: body.append(" %s;" % func) body.append(" return 0;") body.append("}") body = '\n'.join(body) + "\n" return self.try_link(body, headers, include_dirs, libraries, library_dirs) def check_funcs_once(self, funcs, headers=None, include_dirs=None, libraries=None, library_dirs=None, decl=False, call=False, call_args=None): """Check a list of functions at once. This is useful to speed up things, since all the functions in the funcs list will be put in one compilation unit. Arguments --------- funcs : seq list of functions to test include_dirs : seq list of header paths libraries : seq list of libraries to link the code snippet to libraru_dirs : seq list of library paths decl : dict for every (key, value), the declaration in the value will be used for function in key. If a function is not in the dictionay, no declaration will be used. call : dict for every item (f, value), if the value is True, a call will be done to the function f. """ self._check_compiler() body = [] if decl: for f, v in decl.items(): if v: body.append("int %s (void);" % f) # Handle MS intrinsics. See check_func for more info. body.append("#ifdef _MSC_VER") for func in funcs: body.append("#pragma function(%s)" % func) body.append("#endif") body.append("int main (void) {") if call: for f in funcs: if f in call and call[f]: if not (call_args and f in call_args and call_args[f]): args = '' else: args = call_args[f] body.append(" %s(%s);" % (f, args)) else: body.append(" %s;" % f) else: for f in funcs: body.append(" %s;" % f) body.append(" return 0;") body.append("}") body = '\n'.join(body) + "\n" return self.try_link(body, headers, include_dirs, libraries, library_dirs) def check_inline(self): """Return the inline keyword recognized by the compiler, empty string otherwise.""" return check_inline(self) def check_compiler_gcc4(self): """Return True if the C compiler is gcc >= 4.""" return check_compiler_gcc4(self) def get_output(self, body, headers=None, include_dirs=None, libraries=None, library_dirs=None, lang="c", use_tee=None): """Try to compile, link to an executable, and run a program built from 'body' and 'headers'. Returns the exit status code of the program and its output. """ warnings.warn("\n+++++++++++++++++++++++++++++++++++++++++++++++++\n" \ "Usage of get_output is deprecated: please do not \n" \ "use it anymore, and avoid configuration checks \n" \ "involving running executable on the target machine.\n" \ "+++++++++++++++++++++++++++++++++++++++++++++++++\n", DeprecationWarning) from distutils.ccompiler import CompileError, LinkError self._check_compiler() exitcode, output = 255, '' try: grabber = GrabStdout() try: src, obj, exe = self._link(body, headers, include_dirs, libraries, library_dirs, lang) grabber.restore() except: output = grabber.data grabber.restore() raise exe = os.path.join('.', exe) exitstatus, output = exec_command(exe, execute_in='.', use_tee=use_tee) if hasattr(os, 'WEXITSTATUS'): exitcode = os.WEXITSTATUS(exitstatus) if os.WIFSIGNALED(exitstatus): sig = os.WTERMSIG(exitstatus) log.error('subprocess exited with signal %d' % (sig,)) if sig == signal.SIGINT: # control-C raise KeyboardInterrupt else: exitcode = exitstatus log.info("success!") except (CompileError, LinkError): log.info("failure.") self._clean() return exitcode, output class GrabStdout(object): def __init__(self): self.sys_stdout = sys.stdout self.data = '' sys.stdout = self def write (self, data): self.sys_stdout.write(data) self.data += data def flush (self): self.sys_stdout.flush() def restore(self): sys.stdout = self.sys_stdout numpy-1.8.2/numpy/distutils/command/build_clib.py0000664000175100017510000002701612370216242023305 0ustar vagrantvagrant00000000000000""" Modified version of build_clib that handles fortran source files. """ from __future__ import division, absolute_import, print_function import os from glob import glob import shutil from distutils.command.build_clib import build_clib as old_build_clib from distutils.errors import DistutilsSetupError, DistutilsError, \ DistutilsFileError from numpy.distutils import log from distutils.dep_util import newer_group from numpy.distutils.misc_util import filter_sources, has_f_sources,\ has_cxx_sources, all_strings, get_lib_source_files, is_sequence, \ get_numpy_include_dirs # Fix Python distutils bug sf #1718574: _l = old_build_clib.user_options for _i in range(len(_l)): if _l[_i][0] in ['build-clib', 'build-temp']: _l[_i] = (_l[_i][0]+'=',)+_l[_i][1:] # class build_clib(old_build_clib): description = "build C/C++/F libraries used by Python extensions" user_options = old_build_clib.user_options + [ ('fcompiler=', None, "specify the Fortran compiler type"), ('inplace', 'i', 'Build in-place'), ] boolean_options = old_build_clib.boolean_options + ['inplace'] def initialize_options(self): old_build_clib.initialize_options(self) self.fcompiler = None self.inplace = 0 return def have_f_sources(self): for (lib_name, build_info) in self.libraries: if has_f_sources(build_info.get('sources', [])): return True return False def have_cxx_sources(self): for (lib_name, build_info) in self.libraries: if has_cxx_sources(build_info.get('sources', [])): return True return False def run(self): if not self.libraries: return # Make sure that library sources are complete. languages = [] # Make sure that extension sources are complete. self.run_command('build_src') for (lib_name, build_info) in self.libraries: l = build_info.get('language', None) if l and l not in languages: languages.append(l) from distutils.ccompiler import new_compiler self.compiler = new_compiler(compiler=self.compiler, dry_run=self.dry_run, force=self.force) self.compiler.customize(self.distribution, need_cxx=self.have_cxx_sources()) libraries = self.libraries self.libraries = None self.compiler.customize_cmd(self) self.libraries = libraries self.compiler.show_customization() if self.have_f_sources(): from numpy.distutils.fcompiler import new_fcompiler self._f_compiler = new_fcompiler(compiler=self.fcompiler, verbose=self.verbose, dry_run=self.dry_run, force=self.force, requiref90='f90' in languages, c_compiler=self.compiler) if self._f_compiler is not None: self._f_compiler.customize(self.distribution) libraries = self.libraries self.libraries = None self._f_compiler.customize_cmd(self) self.libraries = libraries self._f_compiler.show_customization() else: self._f_compiler = None self.build_libraries(self.libraries) if self.inplace: for l in self.distribution.installed_libraries: libname = self.compiler.library_filename(l.name) source = os.path.join(self.build_clib, libname) target = os.path.join(l.target_dir, libname) self.mkpath(l.target_dir) shutil.copy(source, target) def get_source_files(self): self.check_library_list(self.libraries) filenames = [] for lib in self.libraries: filenames.extend(get_lib_source_files(lib)) return filenames def build_libraries(self, libraries): for (lib_name, build_info) in libraries: self.build_a_library(build_info, lib_name, libraries) def build_a_library(self, build_info, lib_name, libraries): # default compilers compiler = self.compiler fcompiler = self._f_compiler sources = build_info.get('sources') if sources is None or not is_sequence(sources): raise DistutilsSetupError(("in 'libraries' option (library '%s'), " + "'sources' must be present and must be " + "a list of source filenames") % lib_name) sources = list(sources) c_sources, cxx_sources, f_sources, fmodule_sources \ = filter_sources(sources) requiref90 = not not fmodule_sources or \ build_info.get('language', 'c')=='f90' # save source type information so that build_ext can use it. source_languages = [] if c_sources: source_languages.append('c') if cxx_sources: source_languages.append('c++') if requiref90: source_languages.append('f90') elif f_sources: source_languages.append('f77') build_info['source_languages'] = source_languages lib_file = compiler.library_filename(lib_name, output_dir=self.build_clib) depends = sources + build_info.get('depends', []) if not (self.force or newer_group(depends, lib_file, 'newer')): log.debug("skipping '%s' library (up-to-date)", lib_name) return else: log.info("building '%s' library", lib_name) config_fc = build_info.get('config_fc', {}) if fcompiler is not None and config_fc: log.info('using additional config_fc from setup script '\ 'for fortran compiler: %s' \ % (config_fc,)) from numpy.distutils.fcompiler import new_fcompiler fcompiler = new_fcompiler(compiler=fcompiler.compiler_type, verbose=self.verbose, dry_run=self.dry_run, force=self.force, requiref90=requiref90, c_compiler=self.compiler) if fcompiler is not None: dist = self.distribution base_config_fc = dist.get_option_dict('config_fc').copy() base_config_fc.update(config_fc) fcompiler.customize(base_config_fc) # check availability of Fortran compilers if (f_sources or fmodule_sources) and fcompiler is None: raise DistutilsError("library %s has Fortran sources"\ " but no Fortran compiler found" % (lib_name)) if fcompiler is not None: fcompiler.extra_f77_compile_args = build_info.get('extra_f77_compile_args') or [] fcompiler.extra_f90_compile_args = build_info.get('extra_f90_compile_args') or [] macros = build_info.get('macros') include_dirs = build_info.get('include_dirs') if include_dirs is None: include_dirs = [] extra_postargs = build_info.get('extra_compiler_args') or [] include_dirs.extend(get_numpy_include_dirs()) # where compiled F90 module files are: module_dirs = build_info.get('module_dirs') or [] module_build_dir = os.path.dirname(lib_file) if requiref90: self.mkpath(module_build_dir) if compiler.compiler_type=='msvc': # this hack works around the msvc compiler attributes # problem, msvc uses its own convention :( c_sources += cxx_sources cxx_sources = [] objects = [] if c_sources: log.info("compiling C sources") objects = compiler.compile(c_sources, output_dir=self.build_temp, macros=macros, include_dirs=include_dirs, debug=self.debug, extra_postargs=extra_postargs) if cxx_sources: log.info("compiling C++ sources") cxx_compiler = compiler.cxx_compiler() cxx_objects = cxx_compiler.compile(cxx_sources, output_dir=self.build_temp, macros=macros, include_dirs=include_dirs, debug=self.debug, extra_postargs=extra_postargs) objects.extend(cxx_objects) if f_sources or fmodule_sources: extra_postargs = [] f_objects = [] if requiref90: if fcompiler.module_dir_switch is None: existing_modules = glob('*.mod') extra_postargs += fcompiler.module_options(\ module_dirs, module_build_dir) if fmodule_sources: log.info("compiling Fortran 90 module sources") f_objects += fcompiler.compile(fmodule_sources, output_dir=self.build_temp, macros=macros, include_dirs=include_dirs, debug=self.debug, extra_postargs=extra_postargs) if requiref90 and self._f_compiler.module_dir_switch is None: # move new compiled F90 module files to module_build_dir for f in glob('*.mod'): if f in existing_modules: continue t = os.path.join(module_build_dir, f) if os.path.abspath(f)==os.path.abspath(t): continue if os.path.isfile(t): os.remove(t) try: self.move_file(f, module_build_dir) except DistutilsFileError: log.warn('failed to move %r to %r' \ % (f, module_build_dir)) if f_sources: log.info("compiling Fortran sources") f_objects += fcompiler.compile(f_sources, output_dir=self.build_temp, macros=macros, include_dirs=include_dirs, debug=self.debug, extra_postargs=extra_postargs) else: f_objects = [] objects.extend(f_objects) # assume that default linker is suitable for # linking Fortran object files compiler.create_static_lib(objects, lib_name, output_dir=self.build_clib, debug=self.debug) # fix library dependencies clib_libraries = build_info.get('libraries', []) for lname, binfo in libraries: if lname in clib_libraries: clib_libraries.extend(binfo[1].get('libraries', [])) if clib_libraries: build_info['libraries'] = clib_libraries numpy-1.8.2/numpy/distutils/command/install_headers.py0000664000175100017510000000173112370216242024352 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function import os from distutils.command.install_headers import install_headers as old_install_headers class install_headers (old_install_headers): def run (self): headers = self.distribution.headers if not headers: return prefix = os.path.dirname(self.install_dir) for header in headers: if isinstance(header, tuple): # Kind of a hack, but I don't know where else to change this... if header[0] == 'numpy.core': header = ('numpy', header[1]) if os.path.splitext(header[1])[1] == '.inc': continue d = os.path.join(*([prefix]+header[0].split('.'))) header = header[1] else: d = self.install_dir self.mkpath(d) (out, _) = self.copy_file(header, d) self.outfiles.append(out) numpy-1.8.2/numpy/distutils/command/install_clib.py0000664000175100017510000000244312370216242023651 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function import os from distutils.core import Command from distutils.ccompiler import new_compiler from numpy.distutils.misc_util import get_cmd class install_clib(Command): description = "Command to install installable C libraries" user_options = [] def initialize_options(self): self.install_dir = None self.outfiles = [] def finalize_options(self): self.set_undefined_options('install', ('install_lib', 'install_dir')) def run (self): build_clib_cmd = get_cmd("build_clib") build_dir = build_clib_cmd.build_clib # We need the compiler to get the library name -> filename association if not build_clib_cmd.compiler: compiler = new_compiler(compiler=None) compiler.customize(self.distribution) else: compiler = build_clib_cmd.compiler for l in self.distribution.installed_libraries: target_dir = os.path.join(self.install_dir, l.target_dir) name = compiler.library_filename(l.name) source = os.path.join(build_dir, name) self.mkpath(target_dir) self.outfiles.append(self.copy_file(source, target_dir)[0]) def get_outputs(self): return self.outfiles numpy-1.8.2/numpy/distutils/command/build_py.py0000664000175100017510000000227212370216242023021 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function from distutils.command.build_py import build_py as old_build_py from numpy.distutils.misc_util import is_string class build_py(old_build_py): def run(self): build_src = self.get_finalized_command('build_src') if build_src.py_modules_dict and self.packages is None: self.packages = list(build_src.py_modules_dict.keys ()) old_build_py.run(self) def find_package_modules(self, package, package_dir): modules = old_build_py.find_package_modules(self, package, package_dir) # Find build_src generated *.py files. build_src = self.get_finalized_command('build_src') modules += build_src.py_modules_dict.get(package, []) return modules def find_modules(self): old_py_modules = self.py_modules[:] new_py_modules = [_m for _m in self.py_modules if is_string(_m)] self.py_modules[:] = new_py_modules modules = old_build_py.find_modules(self) self.py_modules[:] = old_py_modules return modules # XXX: Fix find_source_files for item in py_modules such that item is 3-tuple # and item[2] is source file. numpy-1.8.2/numpy/distutils/command/build.py0000664000175100017510000000245212370216242022311 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function import os import sys from distutils.command.build import build as old_build from distutils.util import get_platform from numpy.distutils.command.config_compiler import show_fortran_compilers class build(old_build): sub_commands = [('config_cc', lambda *args: True), ('config_fc', lambda *args: True), ('build_src', old_build.has_ext_modules), ] + old_build.sub_commands user_options = old_build.user_options + [ ('fcompiler=', None, "specify the Fortran compiler type"), ] help_options = old_build.help_options + [ ('help-fcompiler', None, "list available Fortran compilers", show_fortran_compilers), ] def initialize_options(self): old_build.initialize_options(self) self.fcompiler = None def finalize_options(self): build_scripts = self.build_scripts old_build.finalize_options(self) plat_specifier = ".%s-%s" % (get_platform(), sys.version[0:3]) if build_scripts is None: self.build_scripts = os.path.join(self.build_base, 'scripts' + plat_specifier) def run(self): old_build.run(self) numpy-1.8.2/numpy/distutils/command/__init__.py0000664000175100017510000000211212370216242022742 0ustar vagrantvagrant00000000000000"""distutils.command Package containing implementation of all the standard Distutils commands. """ from __future__ import division, absolute_import, print_function def test_na_writable_attributes_deletion(): a = np.NA(2) attr = ['payload', 'dtype'] for s in attr: assert_raises(AttributeError, delattr, a, s) __revision__ = "$Id: __init__.py,v 1.3 2005/05/16 11:08:49 pearu Exp $" distutils_all = [ #'build_py', 'clean', 'install_clib', 'install_scripts', 'bdist', 'bdist_dumb', 'bdist_wininst', ] __import__('distutils.command', globals(), locals(), distutils_all) __all__ = ['build', 'config_compiler', 'config', 'build_src', 'build_py', 'build_ext', 'build_clib', 'build_scripts', 'install', 'install_data', 'install_headers', 'install_lib', 'bdist_rpm', 'sdist', ] + distutils_all numpy-1.8.2/numpy/distutils/command/build_scripts.py0000664000175100017510000000330312370216242024054 0ustar vagrantvagrant00000000000000""" Modified version of build_scripts that handles building scripts from functions. """ from __future__ import division, absolute_import, print_function from distutils.command.build_scripts import build_scripts as old_build_scripts from numpy.distutils import log from numpy.distutils.misc_util import is_string class build_scripts(old_build_scripts): def generate_scripts(self, scripts): new_scripts = [] func_scripts = [] for script in scripts: if is_string(script): new_scripts.append(script) else: func_scripts.append(script) if not func_scripts: return new_scripts build_dir = self.build_dir self.mkpath(build_dir) for func in func_scripts: script = func(build_dir) if not script: continue if is_string(script): log.info(" adding '%s' to scripts" % (script,)) new_scripts.append(script) else: [log.info(" adding '%s' to scripts" % (s,)) for s in script] new_scripts.extend(list(script)) return new_scripts def run (self): if not self.scripts: return self.scripts = self.generate_scripts(self.scripts) # Now make sure that the distribution object has this list of scripts. # setuptools' develop command requires that this be a list of filenames, # not functions. self.distribution.scripts = self.scripts return old_build_scripts.run(self) def get_source_files(self): from numpy.distutils.misc_util import get_script_files return get_script_files(self.scripts) numpy-1.8.2/numpy/distutils/command/autodist.py0000664000175100017510000000162212370216243023045 0ustar vagrantvagrant00000000000000"""This module implements additional tests ala autoconf which can be useful. """ from __future__ import division, absolute_import, print_function # We put them here since they could be easily reused outside numpy.distutils def check_inline(cmd): """Return the inline identifier (may be empty).""" cmd._check_compiler() body = """ #ifndef __cplusplus static %(inline)s int static_func (void) { return 0; } %(inline)s int nostatic_func (void) { return 0; } #endif""" for kw in ['inline', '__inline__', '__inline']: st = cmd.try_compile(body % {'inline': kw}, None, None) if st: return kw return '' def check_compiler_gcc4(cmd): """Return True if the C compiler is GCC 4.x.""" cmd._check_compiler() body = """ int main() { #ifndef __GNUC__ && (__GNUC__ >= 4) die in an horrible death #endif } """ return cmd.try_compile(body, None, None) numpy-1.8.2/numpy/distutils/command/sdist.py0000664000175100017510000000143712370216242022342 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function import sys if 'setuptools' in sys.modules: from setuptools.command.sdist import sdist as old_sdist else: from distutils.command.sdist import sdist as old_sdist from numpy.distutils.misc_util import get_data_files class sdist(old_sdist): def add_defaults (self): old_sdist.add_defaults(self) dist = self.distribution if dist.has_data_files(): for data in dist.data_files: self.filelist.extend(get_data_files(data)) if dist.has_headers(): headers = [] for h in dist.headers: if isinstance(h, str): headers.append(h) else: headers.append(h[1]) self.filelist.extend(headers) return numpy-1.8.2/numpy/distutils/command/config_compiler.py0000664000175100017510000001043312370216242024347 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function from distutils.core import Command from numpy.distutils import log #XXX: Linker flags def show_fortran_compilers(_cache=[]): # Using cache to prevent infinite recursion if _cache: return _cache.append(1) from numpy.distutils.fcompiler import show_fcompilers import distutils.core dist = distutils.core._setup_distribution show_fcompilers(dist) class config_fc(Command): """ Distutils command to hold user specified options to Fortran compilers. config_fc command is used by the FCompiler.customize() method. """ description = "specify Fortran 77/Fortran 90 compiler information" user_options = [ ('fcompiler=', None, "specify Fortran compiler type"), ('f77exec=', None, "specify F77 compiler command"), ('f90exec=', None, "specify F90 compiler command"), ('f77flags=', None, "specify F77 compiler flags"), ('f90flags=', None, "specify F90 compiler flags"), ('opt=', None, "specify optimization flags"), ('arch=', None, "specify architecture specific optimization flags"), ('debug', 'g', "compile with debugging information"), ('noopt', None, "compile without optimization"), ('noarch', None, "compile without arch-dependent optimization"), ] help_options = [ ('help-fcompiler', None, "list available Fortran compilers", show_fortran_compilers), ] boolean_options = ['debug', 'noopt', 'noarch'] def initialize_options(self): self.fcompiler = None self.f77exec = None self.f90exec = None self.f77flags = None self.f90flags = None self.opt = None self.arch = None self.debug = None self.noopt = None self.noarch = None def finalize_options(self): log.info('unifing config_fc, config, build_clib, build_ext, build commands --fcompiler options') build_clib = self.get_finalized_command('build_clib') build_ext = self.get_finalized_command('build_ext') config = self.get_finalized_command('config') build = self.get_finalized_command('build') cmd_list = [self, config, build_clib, build_ext, build] for a in ['fcompiler']: l = [] for c in cmd_list: v = getattr(c, a) if v is not None: if not isinstance(v, str): v = v.compiler_type if v not in l: l.append(v) if not l: v1 = None else: v1 = l[0] if len(l)>1: log.warn(' commands have different --%s options: %s'\ ', using first in list as default' % (a, l)) if v1: for c in cmd_list: if getattr(c, a) is None: setattr(c, a, v1) def run(self): # Do nothing. return class config_cc(Command): """ Distutils command to hold user specified options to C/C++ compilers. """ description = "specify C/C++ compiler information" user_options = [ ('compiler=', None, "specify C/C++ compiler type"), ] def initialize_options(self): self.compiler = None def finalize_options(self): log.info('unifing config_cc, config, build_clib, build_ext, build commands --compiler options') build_clib = self.get_finalized_command('build_clib') build_ext = self.get_finalized_command('build_ext') config = self.get_finalized_command('config') build = self.get_finalized_command('build') cmd_list = [self, config, build_clib, build_ext, build] for a in ['compiler']: l = [] for c in cmd_list: v = getattr(c, a) if v is not None: if not isinstance(v, str): v = v.compiler_type if v not in l: l.append(v) if not l: v1 = None else: v1 = l[0] if len(l)>1: log.warn(' commands have different --%s options: %s'\ ', using first in list as default' % (a, l)) if v1: for c in cmd_list: if getattr(c, a) is None: setattr(c, a, v1) return def run(self): # Do nothing. return numpy-1.8.2/numpy/distutils/command/bdist_rpm.py0000664000175100017510000000140712370216242023174 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function import os import sys if 'setuptools' in sys.modules: from setuptools.command.bdist_rpm import bdist_rpm as old_bdist_rpm else: from distutils.command.bdist_rpm import bdist_rpm as old_bdist_rpm class bdist_rpm(old_bdist_rpm): def _make_spec_file(self): spec_file = old_bdist_rpm._make_spec_file(self) # Replace hardcoded setup.py script name # with the real setup script name. setup_py = os.path.basename(sys.argv[0]) if setup_py == 'setup.py': return spec_file new_spec_file = [] for line in spec_file: line = line.replace('setup.py', setup_py) new_spec_file.append(line) return new_spec_file numpy-1.8.2/numpy/distutils/command/build_src.py0000664000175100017510000007700212370216242023163 0ustar vagrantvagrant00000000000000""" Build swig, f2py, pyrex sources. """ from __future__ import division, absolute_import, print_function import os import re import sys import shlex import copy from distutils.command import build_ext from distutils.dep_util import newer_group, newer from distutils.util import get_platform from distutils.errors import DistutilsError, DistutilsSetupError def have_pyrex(): try: import Pyrex.Compiler.Main return True except ImportError: return False # this import can't be done here, as it uses numpy stuff only available # after it's installed #import numpy.f2py from numpy.distutils import log from numpy.distutils.misc_util import fortran_ext_match, \ appendpath, is_string, is_sequence, get_cmd from numpy.distutils.from_template import process_file as process_f_file from numpy.distutils.conv_template import process_file as process_c_file def subst_vars(target, source, d): """Substitute any occurence of @foo@ by d['foo'] from source file into target.""" var = re.compile('@([a-zA-Z_]+)@') fs = open(source, 'r') try: ft = open(target, 'w') try: for l in fs: m = var.search(l) if m: ft.write(l.replace('@%s@' % m.group(1), d[m.group(1)])) else: ft.write(l) finally: ft.close() finally: fs.close() class build_src(build_ext.build_ext): description = "build sources from SWIG, F2PY files or a function" user_options = [ ('build-src=', 'd', "directory to \"build\" sources to"), ('f2py-opts=', None, "list of f2py command line options"), ('swig=', None, "path to the SWIG executable"), ('swig-opts=', None, "list of SWIG command line options"), ('swig-cpp', None, "make SWIG create C++ files (default is autodetected from sources)"), ('f2pyflags=', None, "additional flags to f2py (use --f2py-opts= instead)"), # obsolete ('swigflags=', None, "additional flags to swig (use --swig-opts= instead)"), # obsolete ('force', 'f', "forcibly build everything (ignore file timestamps)"), ('inplace', 'i', "ignore build-lib and put compiled extensions into the source " + "directory alongside your pure Python modules"), ] boolean_options = ['force', 'inplace'] help_options = [] def initialize_options(self): self.extensions = None self.package = None self.py_modules = None self.py_modules_dict = None self.build_src = None self.build_lib = None self.build_base = None self.force = None self.inplace = None self.package_dir = None self.f2pyflags = None # obsolete self.f2py_opts = None self.swigflags = None # obsolete self.swig_opts = None self.swig_cpp = None self.swig = None def finalize_options(self): self.set_undefined_options('build', ('build_base', 'build_base'), ('build_lib', 'build_lib'), ('force', 'force')) if self.package is None: self.package = self.distribution.ext_package self.extensions = self.distribution.ext_modules self.libraries = self.distribution.libraries or [] self.py_modules = self.distribution.py_modules or [] self.data_files = self.distribution.data_files or [] if self.build_src is None: plat_specifier = ".%s-%s" % (get_platform(), sys.version[0:3]) self.build_src = os.path.join(self.build_base, 'src'+plat_specifier) # py_modules_dict is used in build_py.find_package_modules self.py_modules_dict = {} if self.f2pyflags: if self.f2py_opts: log.warn('ignoring --f2pyflags as --f2py-opts already used') else: self.f2py_opts = self.f2pyflags self.f2pyflags = None if self.f2py_opts is None: self.f2py_opts = [] else: self.f2py_opts = shlex.split(self.f2py_opts) if self.swigflags: if self.swig_opts: log.warn('ignoring --swigflags as --swig-opts already used') else: self.swig_opts = self.swigflags self.swigflags = None if self.swig_opts is None: self.swig_opts = [] else: self.swig_opts = shlex.split(self.swig_opts) # use options from build_ext command build_ext = self.get_finalized_command('build_ext') if self.inplace is None: self.inplace = build_ext.inplace if self.swig_cpp is None: self.swig_cpp = build_ext.swig_cpp for c in ['swig', 'swig_opt']: o = '--'+c.replace('_', '-') v = getattr(build_ext, c, None) if v: if getattr(self, c): log.warn('both build_src and build_ext define %s option' % (o)) else: log.info('using "%s=%s" option from build_ext command' % (o, v)) setattr(self, c, v) def run(self): log.info("build_src") if not (self.extensions or self.libraries): return self.build_sources() def build_sources(self): if self.inplace: self.get_package_dir = \ self.get_finalized_command('build_py').get_package_dir self.build_py_modules_sources() for libname_info in self.libraries: self.build_library_sources(*libname_info) if self.extensions: self.check_extensions_list(self.extensions) for ext in self.extensions: self.build_extension_sources(ext) self.build_data_files_sources() self.build_npy_pkg_config() def build_data_files_sources(self): if not self.data_files: return log.info('building data_files sources') from numpy.distutils.misc_util import get_data_files new_data_files = [] for data in self.data_files: if isinstance(data, str): new_data_files.append(data) elif isinstance(data, tuple): d, files = data if self.inplace: build_dir = self.get_package_dir('.'.join(d.split(os.sep))) else: build_dir = os.path.join(self.build_src, d) funcs = [f for f in files if hasattr(f, '__call__')] files = [f for f in files if not hasattr(f, '__call__')] for f in funcs: if f.__code__.co_argcount==1: s = f(build_dir) else: s = f() if s is not None: if isinstance(s, list): files.extend(s) elif isinstance(s, str): files.append(s) else: raise TypeError(repr(s)) filenames = get_data_files((d, files)) new_data_files.append((d, filenames)) else: raise TypeError(repr(data)) self.data_files[:] = new_data_files def _build_npy_pkg_config(self, info, gd): import shutil template, install_dir, subst_dict = info template_dir = os.path.dirname(template) for k, v in gd.items(): subst_dict[k] = v if self.inplace == 1: generated_dir = os.path.join(template_dir, install_dir) else: generated_dir = os.path.join(self.build_src, template_dir, install_dir) generated = os.path.basename(os.path.splitext(template)[0]) generated_path = os.path.join(generated_dir, generated) if not os.path.exists(generated_dir): os.makedirs(generated_dir) subst_vars(generated_path, template, subst_dict) # Where to install relatively to install prefix full_install_dir = os.path.join(template_dir, install_dir) return full_install_dir, generated_path def build_npy_pkg_config(self): log.info('build_src: building npy-pkg config files') # XXX: another ugly workaround to circumvent distutils brain damage. We # need the install prefix here, but finalizing the options of the # install command when only building sources cause error. Instead, we # copy the install command instance, and finalize the copy so that it # does not disrupt how distutils want to do things when with the # original install command instance. install_cmd = copy.copy(get_cmd('install')) if not install_cmd.finalized == 1: install_cmd.finalize_options() build_npkg = False gd = {} if self.inplace == 1: top_prefix = '.' build_npkg = True elif hasattr(install_cmd, 'install_libbase'): top_prefix = install_cmd.install_libbase build_npkg = True if build_npkg: for pkg, infos in self.distribution.installed_pkg_config.items(): pkg_path = self.distribution.package_dir[pkg] prefix = os.path.join(os.path.abspath(top_prefix), pkg_path) d = {'prefix': prefix} for info in infos: install_dir, generated = self._build_npy_pkg_config(info, d) self.distribution.data_files.append((install_dir, [generated])) def build_py_modules_sources(self): if not self.py_modules: return log.info('building py_modules sources') new_py_modules = [] for source in self.py_modules: if is_sequence(source) and len(source)==3: package, module_base, source = source if self.inplace: build_dir = self.get_package_dir(package) else: build_dir = os.path.join(self.build_src, os.path.join(*package.split('.'))) if hasattr(source, '__call__'): target = os.path.join(build_dir, module_base + '.py') source = source(target) if source is None: continue modules = [(package, module_base, source)] if package not in self.py_modules_dict: self.py_modules_dict[package] = [] self.py_modules_dict[package] += modules else: new_py_modules.append(source) self.py_modules[:] = new_py_modules def build_library_sources(self, lib_name, build_info): sources = list(build_info.get('sources', [])) if not sources: return log.info('building library "%s" sources' % (lib_name)) sources = self.generate_sources(sources, (lib_name, build_info)) sources = self.template_sources(sources, (lib_name, build_info)) sources, h_files = self.filter_h_files(sources) if h_files: log.info('%s - nothing done with h_files = %s', self.package, h_files) #for f in h_files: # self.distribution.headers.append((lib_name,f)) build_info['sources'] = sources return def build_extension_sources(self, ext): sources = list(ext.sources) log.info('building extension "%s" sources' % (ext.name)) fullname = self.get_ext_fullname(ext.name) modpath = fullname.split('.') package = '.'.join(modpath[0:-1]) if self.inplace: self.ext_target_dir = self.get_package_dir(package) sources = self.generate_sources(sources, ext) sources = self.template_sources(sources, ext) sources = self.swig_sources(sources, ext) sources = self.f2py_sources(sources, ext) sources = self.pyrex_sources(sources, ext) sources, py_files = self.filter_py_files(sources) if package not in self.py_modules_dict: self.py_modules_dict[package] = [] modules = [] for f in py_files: module = os.path.splitext(os.path.basename(f))[0] modules.append((package, module, f)) self.py_modules_dict[package] += modules sources, h_files = self.filter_h_files(sources) if h_files: log.info('%s - nothing done with h_files = %s', package, h_files) #for f in h_files: # self.distribution.headers.append((package,f)) ext.sources = sources def generate_sources(self, sources, extension): new_sources = [] func_sources = [] for source in sources: if is_string(source): new_sources.append(source) else: func_sources.append(source) if not func_sources: return new_sources if self.inplace and not is_sequence(extension): build_dir = self.ext_target_dir else: if is_sequence(extension): name = extension[0] # if 'include_dirs' not in extension[1]: # extension[1]['include_dirs'] = [] # incl_dirs = extension[1]['include_dirs'] else: name = extension.name # incl_dirs = extension.include_dirs #if self.build_src not in incl_dirs: # incl_dirs.append(self.build_src) build_dir = os.path.join(*([self.build_src]\ +name.split('.')[:-1])) self.mkpath(build_dir) for func in func_sources: source = func(extension, build_dir) if not source: continue if is_sequence(source): [log.info(" adding '%s' to sources." % (s,)) for s in source] new_sources.extend(source) else: log.info(" adding '%s' to sources." % (source,)) new_sources.append(source) return new_sources def filter_py_files(self, sources): return self.filter_files(sources, ['.py']) def filter_h_files(self, sources): return self.filter_files(sources, ['.h', '.hpp', '.inc']) def filter_files(self, sources, exts = []): new_sources = [] files = [] for source in sources: (base, ext) = os.path.splitext(source) if ext in exts: files.append(source) else: new_sources.append(source) return new_sources, files def template_sources(self, sources, extension): new_sources = [] if is_sequence(extension): depends = extension[1].get('depends') include_dirs = extension[1].get('include_dirs') else: depends = extension.depends include_dirs = extension.include_dirs for source in sources: (base, ext) = os.path.splitext(source) if ext == '.src': # Template file if self.inplace: target_dir = os.path.dirname(base) else: target_dir = appendpath(self.build_src, os.path.dirname(base)) self.mkpath(target_dir) target_file = os.path.join(target_dir, os.path.basename(base)) if (self.force or newer_group([source] + depends, target_file)): if _f_pyf_ext_match(base): log.info("from_template:> %s" % (target_file)) outstr = process_f_file(source) else: log.info("conv_template:> %s" % (target_file)) outstr = process_c_file(source) fid = open(target_file, 'w') fid.write(outstr) fid.close() if _header_ext_match(target_file): d = os.path.dirname(target_file) if d not in include_dirs: log.info(" adding '%s' to include_dirs." % (d)) include_dirs.append(d) new_sources.append(target_file) else: new_sources.append(source) return new_sources def pyrex_sources(self, sources, extension): new_sources = [] ext_name = extension.name.split('.')[-1] for source in sources: (base, ext) = os.path.splitext(source) if ext == '.pyx': target_file = self.generate_a_pyrex_source(base, ext_name, source, extension) new_sources.append(target_file) else: new_sources.append(source) return new_sources def generate_a_pyrex_source(self, base, ext_name, source, extension): if self.inplace or not have_pyrex(): target_dir = os.path.dirname(base) else: target_dir = appendpath(self.build_src, os.path.dirname(base)) target_file = os.path.join(target_dir, ext_name + '.c') depends = [source] + extension.depends if self.force or newer_group(depends, target_file, 'newer'): if have_pyrex(): import Pyrex.Compiler.Main log.info("pyrexc:> %s" % (target_file)) self.mkpath(target_dir) options = Pyrex.Compiler.Main.CompilationOptions( defaults=Pyrex.Compiler.Main.default_options, include_path=extension.include_dirs, output_file=target_file) pyrex_result = Pyrex.Compiler.Main.compile(source, options=options) if pyrex_result.num_errors != 0: raise DistutilsError("%d errors while compiling %r with Pyrex" \ % (pyrex_result.num_errors, source)) elif os.path.isfile(target_file): log.warn("Pyrex required for compiling %r but not available,"\ " using old target %r"\ % (source, target_file)) else: raise DistutilsError("Pyrex required for compiling %r"\ " but notavailable" % (source,)) return target_file def f2py_sources(self, sources, extension): new_sources = [] f2py_sources = [] f_sources = [] f2py_targets = {} target_dirs = [] ext_name = extension.name.split('.')[-1] skip_f2py = 0 for source in sources: (base, ext) = os.path.splitext(source) if ext == '.pyf': # F2PY interface file if self.inplace: target_dir = os.path.dirname(base) else: target_dir = appendpath(self.build_src, os.path.dirname(base)) if os.path.isfile(source): name = get_f2py_modulename(source) if name != ext_name: raise DistutilsSetupError('mismatch of extension names: %s ' 'provides %r but expected %r' % ( source, name, ext_name)) target_file = os.path.join(target_dir, name+'module.c') else: log.debug(' source %s does not exist: skipping f2py\'ing.' \ % (source)) name = ext_name skip_f2py = 1 target_file = os.path.join(target_dir, name+'module.c') if not os.path.isfile(target_file): log.warn(' target %s does not exist:\n '\ 'Assuming %smodule.c was generated with '\ '"build_src --inplace" command.' \ % (target_file, name)) target_dir = os.path.dirname(base) target_file = os.path.join(target_dir, name+'module.c') if not os.path.isfile(target_file): raise DistutilsSetupError("%r missing" % (target_file,)) log.info(' Yes! Using %r as up-to-date target.' \ % (target_file)) target_dirs.append(target_dir) f2py_sources.append(source) f2py_targets[source] = target_file new_sources.append(target_file) elif fortran_ext_match(ext): f_sources.append(source) else: new_sources.append(source) if not (f2py_sources or f_sources): return new_sources for d in target_dirs: self.mkpath(d) f2py_options = extension.f2py_options + self.f2py_opts if self.distribution.libraries: for name, build_info in self.distribution.libraries: if name in extension.libraries: f2py_options.extend(build_info.get('f2py_options', [])) log.info("f2py options: %s" % (f2py_options)) if f2py_sources: if len(f2py_sources) != 1: raise DistutilsSetupError( 'only one .pyf file is allowed per extension module but got'\ ' more: %r' % (f2py_sources,)) source = f2py_sources[0] target_file = f2py_targets[source] target_dir = os.path.dirname(target_file) or '.' depends = [source] + extension.depends if (self.force or newer_group(depends, target_file, 'newer')) \ and not skip_f2py: log.info("f2py: %s" % (source)) import numpy.f2py numpy.f2py.run_main(f2py_options + ['--build-dir', target_dir, source]) else: log.debug(" skipping '%s' f2py interface (up-to-date)" % (source)) else: #XXX TODO: --inplace support for sdist command if is_sequence(extension): name = extension[0] else: name = extension.name target_dir = os.path.join(*([self.build_src]\ +name.split('.')[:-1])) target_file = os.path.join(target_dir, ext_name + 'module.c') new_sources.append(target_file) depends = f_sources + extension.depends if (self.force or newer_group(depends, target_file, 'newer')) \ and not skip_f2py: log.info("f2py:> %s" % (target_file)) self.mkpath(target_dir) import numpy.f2py numpy.f2py.run_main(f2py_options + ['--lower', '--build-dir', target_dir]+\ ['-m', ext_name]+f_sources) else: log.debug(" skipping f2py fortran files for '%s' (up-to-date)"\ % (target_file)) if not os.path.isfile(target_file): raise DistutilsError("f2py target file %r not generated" % (target_file,)) target_c = os.path.join(self.build_src, 'fortranobject.c') target_h = os.path.join(self.build_src, 'fortranobject.h') log.info(" adding '%s' to sources." % (target_c)) new_sources.append(target_c) if self.build_src not in extension.include_dirs: log.info(" adding '%s' to include_dirs." \ % (self.build_src)) extension.include_dirs.append(self.build_src) if not skip_f2py: import numpy.f2py d = os.path.dirname(numpy.f2py.__file__) source_c = os.path.join(d, 'src', 'fortranobject.c') source_h = os.path.join(d, 'src', 'fortranobject.h') if newer(source_c, target_c) or newer(source_h, target_h): self.mkpath(os.path.dirname(target_c)) self.copy_file(source_c, target_c) self.copy_file(source_h, target_h) else: if not os.path.isfile(target_c): raise DistutilsSetupError("f2py target_c file %r not found" % (target_c,)) if not os.path.isfile(target_h): raise DistutilsSetupError("f2py target_h file %r not found" % (target_h,)) for name_ext in ['-f2pywrappers.f', '-f2pywrappers2.f90']: filename = os.path.join(target_dir, ext_name + name_ext) if os.path.isfile(filename): log.info(" adding '%s' to sources." % (filename)) f_sources.append(filename) return new_sources + f_sources def swig_sources(self, sources, extension): # Assuming SWIG 1.3.14 or later. See compatibility note in # http://www.swig.org/Doc1.3/Python.html#Python_nn6 new_sources = [] swig_sources = [] swig_targets = {} target_dirs = [] py_files = [] # swig generated .py files target_ext = '.c' if '-c++' in extension.swig_opts: typ = 'c++' is_cpp = True extension.swig_opts.remove('-c++') elif self.swig_cpp: typ = 'c++' is_cpp = True else: typ = None is_cpp = False skip_swig = 0 ext_name = extension.name.split('.')[-1] for source in sources: (base, ext) = os.path.splitext(source) if ext == '.i': # SWIG interface file # the code below assumes that the sources list # contains not more than one .i SWIG interface file if self.inplace: target_dir = os.path.dirname(base) py_target_dir = self.ext_target_dir else: target_dir = appendpath(self.build_src, os.path.dirname(base)) py_target_dir = target_dir if os.path.isfile(source): name = get_swig_modulename(source) if name != ext_name[1:]: raise DistutilsSetupError( 'mismatch of extension names: %s provides %r' ' but expected %r' % (source, name, ext_name[1:])) if typ is None: typ = get_swig_target(source) is_cpp = typ=='c++' else: typ2 = get_swig_target(source) if typ2 is None: log.warn('source %r does not define swig target, assuming %s swig target' \ % (source, typ)) elif typ!=typ2: log.warn('expected %r but source %r defines %r swig target' \ % (typ, source, typ2)) if typ2=='c++': log.warn('resetting swig target to c++ (some targets may have .c extension)') is_cpp = True else: log.warn('assuming that %r has c++ swig target' % (source)) if is_cpp: target_ext = '.cpp' target_file = os.path.join(target_dir, '%s_wrap%s' \ % (name, target_ext)) else: log.warn(' source %s does not exist: skipping swig\'ing.' \ % (source)) name = ext_name[1:] skip_swig = 1 target_file = _find_swig_target(target_dir, name) if not os.path.isfile(target_file): log.warn(' target %s does not exist:\n '\ 'Assuming %s_wrap.{c,cpp} was generated with '\ '"build_src --inplace" command.' \ % (target_file, name)) target_dir = os.path.dirname(base) target_file = _find_swig_target(target_dir, name) if not os.path.isfile(target_file): raise DistutilsSetupError("%r missing" % (target_file,)) log.warn(' Yes! Using %r as up-to-date target.' \ % (target_file)) target_dirs.append(target_dir) new_sources.append(target_file) py_files.append(os.path.join(py_target_dir, name+'.py')) swig_sources.append(source) swig_targets[source] = new_sources[-1] else: new_sources.append(source) if not swig_sources: return new_sources if skip_swig: return new_sources + py_files for d in target_dirs: self.mkpath(d) swig = self.swig or self.find_swig() swig_cmd = [swig, "-python"] + extension.swig_opts if is_cpp: swig_cmd.append('-c++') for d in extension.include_dirs: swig_cmd.append('-I'+d) for source in swig_sources: target = swig_targets[source] depends = [source] + extension.depends if self.force or newer_group(depends, target, 'newer'): log.info("%s: %s" % (os.path.basename(swig) \ + (is_cpp and '++' or ''), source)) self.spawn(swig_cmd + self.swig_opts \ + ["-o", target, '-outdir', py_target_dir, source]) else: log.debug(" skipping '%s' swig interface (up-to-date)" \ % (source)) return new_sources + py_files _f_pyf_ext_match = re.compile(r'.*[.](f90|f95|f77|for|ftn|f|pyf)\Z', re.I).match _header_ext_match = re.compile(r'.*[.](inc|h|hpp)\Z', re.I).match #### SWIG related auxiliary functions #### _swig_module_name_match = re.compile(r'\s*%module\s*(.*\(\s*package\s*=\s*"(?P[\w_]+)".*\)|)\s*(?P[\w_]+)', re.I).match _has_c_header = re.compile(r'-[*]-\s*c\s*-[*]-', re.I).search _has_cpp_header = re.compile(r'-[*]-\s*c[+][+]\s*-[*]-', re.I).search def get_swig_target(source): f = open(source, 'r') result = None line = f.readline() if _has_cpp_header(line): result = 'c++' if _has_c_header(line): result = 'c' f.close() return result def get_swig_modulename(source): f = open(source, 'r') name = None for line in f: m = _swig_module_name_match(line) if m: name = m.group('name') break f.close() return name def _find_swig_target(target_dir, name): for ext in ['.cpp', '.c']: target = os.path.join(target_dir, '%s_wrap%s' % (name, ext)) if os.path.isfile(target): break return target #### F2PY related auxiliary functions #### _f2py_module_name_match = re.compile(r'\s*python\s*module\s*(?P[\w_]+)', re.I).match _f2py_user_module_name_match = re.compile(r'\s*python\s*module\s*(?P[\w_]*?'\ '__user__[\w_]*)', re.I).match def get_f2py_modulename(source): name = None f = open(source) for line in f: m = _f2py_module_name_match(line) if m: if _f2py_user_module_name_match(line): # skip *__user__* names continue name = m.group('name') break f.close() return name ########################################## numpy-1.8.2/numpy/distutils/command/install_data.py0000664000175100017510000000162212370216242023647 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function import sys have_setuptools = ('setuptools' in sys.modules) from distutils.command.install_data import install_data as old_install_data #data installer with improved intelligence over distutils #data files are copied into the project directory instead #of willy-nilly class install_data (old_install_data): def run(self): old_install_data.run(self) if have_setuptools: # Run install_clib again, since setuptools does not run sub-commands # of install automatically self.run_command('install_clib') def finalize_options (self): self.set_undefined_options('install', ('install_lib', 'install_dir'), ('root', 'root'), ('force', 'force'), ) numpy-1.8.2/numpy/distutils/command/develop.py0000664000175100017510000000120112370216242022637 0ustar vagrantvagrant00000000000000""" Override the develop command from setuptools so we can ensure that our generated files (from build_src or build_scripts) are properly converted to real files with filenames. """ from __future__ import division, absolute_import, print_function from setuptools.command.develop import develop as old_develop class develop(old_develop): __doc__ = old_develop.__doc__ def install_for_development(self): # Build sources in-place, too. self.reinitialize_command('build_src', inplace=1) # Make sure scripts are built. self.run_command('build_scripts') old_develop.install_for_development(self) numpy-1.8.2/numpy/distutils/__version__.py0000664000175100017510000000022712370216242022053 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function major = 0 minor = 4 micro = 0 version = '%(major)d.%(minor)d.%(micro)d' % (locals()) numpy-1.8.2/numpy/distutils/exec_command.py0000664000175100017510000004601712370216242022223 0ustar vagrantvagrant00000000000000#!/usr/bin/env python """ exec_command Implements exec_command function that is (almost) equivalent to commands.getstatusoutput function but on NT, DOS systems the returned status is actually correct (though, the returned status values may be different by a factor). In addition, exec_command takes keyword arguments for (re-)defining environment variables. Provides functions: exec_command --- execute command in a specified directory and in the modified environment. find_executable --- locate a command using info from environment variable PATH. Equivalent to posix `which` command. Author: Pearu Peterson Created: 11 January 2003 Requires: Python 2.x Succesfully tested on: os.name | sys.platform | comments --------+--------------+---------- posix | linux2 | Debian (sid) Linux, Python 2.1.3+, 2.2.3+, 2.3.3 PyCrust 0.9.3, Idle 1.0.2 posix | linux2 | Red Hat 9 Linux, Python 2.1.3, 2.2.2, 2.3.2 posix | sunos5 | SunOS 5.9, Python 2.2, 2.3.2 posix | darwin | Darwin 7.2.0, Python 2.3 nt | win32 | Windows Me Python 2.3(EE), Idle 1.0, PyCrust 0.7.2 Python 2.1.1 Idle 0.8 nt | win32 | Windows 98, Python 2.1.1. Idle 0.8 nt | win32 | Cygwin 98-4.10, Python 2.1.1(MSC) - echo tests fail i.e. redefining environment variables may not work. FIXED: don't use cygwin echo! Comment: also `cmd /c echo` will not work but redefining environment variables do work. posix | cygwin | Cygwin 98-4.10, Python 2.3.3(cygming special) nt | win32 | Windows XP, Python 2.3.3 Known bugs: - Tests, that send messages to stderr, fail when executed from MSYS prompt because the messages are lost at some point. """ from __future__ import division, absolute_import, print_function __all__ = ['exec_command', 'find_executable'] import os import sys import shlex from numpy.distutils.misc_util import is_sequence, make_temp_file from numpy.distutils import log from numpy.distutils.compat import get_exception from numpy.compat import open_latin1 def temp_file_name(): fo, name = make_temp_file() fo.close() return name def get_pythonexe(): pythonexe = sys.executable if os.name in ['nt', 'dos']: fdir, fn = os.path.split(pythonexe) fn = fn.upper().replace('PYTHONW', 'PYTHON') pythonexe = os.path.join(fdir, fn) assert os.path.isfile(pythonexe), '%r is not a file' % (pythonexe,) return pythonexe def splitcmdline(line): import warnings warnings.warn('splitcmdline is deprecated; use shlex.split', DeprecationWarning) return shlex.split(line) def find_executable(exe, path=None, _cache={}): """Return full path of a executable or None. Symbolic links are not followed. """ key = exe, path try: return _cache[key] except KeyError: pass log.debug('find_executable(%r)' % exe) orig_exe = exe if path is None: path = os.environ.get('PATH', os.defpath) if os.name=='posix': realpath = os.path.realpath else: realpath = lambda a:a if exe.startswith('"'): exe = exe[1:-1] suffixes = [''] if os.name in ['nt', 'dos', 'os2']: fn, ext = os.path.splitext(exe) extra_suffixes = ['.exe', '.com', '.bat'] if ext.lower() not in extra_suffixes: suffixes = extra_suffixes if os.path.isabs(exe): paths = [''] else: paths = [ os.path.abspath(p) for p in path.split(os.pathsep) ] for path in paths: fn = os.path.join(path, exe) for s in suffixes: f_ext = fn+s if not os.path.islink(f_ext): f_ext = realpath(f_ext) if os.path.isfile(f_ext) and os.access(f_ext, os.X_OK): log.info('Found executable %s' % f_ext) _cache[key] = f_ext return f_ext log.warn('Could not locate executable %s' % orig_exe) return None ############################################################ def _preserve_environment( names ): log.debug('_preserve_environment(%r)' % (names)) env = {} for name in names: env[name] = os.environ.get(name) return env def _update_environment( **env ): log.debug('_update_environment(...)') for name, value in env.items(): os.environ[name] = value or '' def _supports_fileno(stream): """ Returns True if 'stream' supports the file descriptor and allows fileno(). """ if hasattr(stream, 'fileno'): try: r = stream.fileno() return True except IOError: return False else: return False def exec_command( command, execute_in='', use_shell=None, use_tee = None, _with_python = 1, **env ): """ Return (status,output) of executed command. command is a concatenated string of executable and arguments. The output contains both stdout and stderr messages. The following special keyword arguments can be used: use_shell - execute `sh -c command` use_tee - pipe the output of command through tee execute_in - before run command `cd execute_in` and after `cd -`. On NT, DOS systems the returned status is correct for external commands. Wild cards will not work for non-posix systems or when use_shell=0. """ log.debug('exec_command(%r,%s)' % (command,\ ','.join(['%s=%r'%kv for kv in env.items()]))) if use_tee is None: use_tee = os.name=='posix' if use_shell is None: use_shell = os.name=='posix' execute_in = os.path.abspath(execute_in) oldcwd = os.path.abspath(os.getcwd()) if __name__[-12:] == 'exec_command': exec_dir = os.path.dirname(os.path.abspath(__file__)) elif os.path.isfile('exec_command.py'): exec_dir = os.path.abspath('.') else: exec_dir = os.path.abspath(sys.argv[0]) if os.path.isfile(exec_dir): exec_dir = os.path.dirname(exec_dir) if oldcwd!=execute_in: os.chdir(execute_in) log.debug('New cwd: %s' % execute_in) else: log.debug('Retaining cwd: %s' % oldcwd) oldenv = _preserve_environment( list(env.keys()) ) _update_environment( **env ) try: # _exec_command is robust but slow, it relies on # usable sys.std*.fileno() descriptors. If they # are bad (like in win32 Idle, PyCrust environments) # then _exec_command_python (even slower) # will be used as a last resort. # # _exec_command_posix uses os.system and is faster # but not on all platforms os.system will return # a correct status. if (_with_python and _supports_fileno(sys.stdout) and sys.stdout.fileno() == -1): st = _exec_command_python(command, exec_command_dir = exec_dir, **env) elif os.name=='posix': st = _exec_command_posix(command, use_shell=use_shell, use_tee=use_tee, **env) else: st = _exec_command(command, use_shell=use_shell, use_tee=use_tee,**env) finally: if oldcwd!=execute_in: os.chdir(oldcwd) log.debug('Restored cwd to %s' % oldcwd) _update_environment(**oldenv) return st def _exec_command_posix( command, use_shell = None, use_tee = None, **env ): log.debug('_exec_command_posix(...)') if is_sequence(command): command_str = ' '.join(list(command)) else: command_str = command tmpfile = temp_file_name() stsfile = None if use_tee: stsfile = temp_file_name() filter = '' if use_tee == 2: filter = r'| tr -cd "\n" | tr "\n" "."; echo' command_posix = '( %s ; echo $? > %s ) 2>&1 | tee %s %s'\ % (command_str, stsfile, tmpfile, filter) else: stsfile = temp_file_name() command_posix = '( %s ; echo $? > %s ) > %s 2>&1'\ % (command_str, stsfile, tmpfile) #command_posix = '( %s ) > %s 2>&1' % (command_str,tmpfile) log.debug('Running os.system(%r)' % (command_posix)) status = os.system(command_posix) if use_tee: if status: # if command_tee fails then fall back to robust exec_command log.warn('_exec_command_posix failed (status=%s)' % status) return _exec_command(command, use_shell=use_shell, **env) if stsfile is not None: f = open_latin1(stsfile, 'r') status_text = f.read() status = int(status_text) f.close() os.remove(stsfile) f = open_latin1(tmpfile, 'r') text = f.read() f.close() os.remove(tmpfile) if text[-1:]=='\n': text = text[:-1] return status, text def _exec_command_python(command, exec_command_dir='', **env): log.debug('_exec_command_python(...)') python_exe = get_pythonexe() cmdfile = temp_file_name() stsfile = temp_file_name() outfile = temp_file_name() f = open(cmdfile, 'w') f.write('import os\n') f.write('import sys\n') f.write('sys.path.insert(0,%r)\n' % (exec_command_dir)) f.write('from exec_command import exec_command\n') f.write('del sys.path[0]\n') f.write('cmd = %r\n' % command) f.write('os.environ = %r\n' % (os.environ)) f.write('s,o = exec_command(cmd, _with_python=0, **%r)\n' % (env)) f.write('f=open(%r,"w")\nf.write(str(s))\nf.close()\n' % (stsfile)) f.write('f=open(%r,"w")\nf.write(o)\nf.close()\n' % (outfile)) f.close() cmd = '%s %s' % (python_exe, cmdfile) status = os.system(cmd) if status: raise RuntimeError("%r failed" % (cmd,)) os.remove(cmdfile) f = open_latin1(stsfile, 'r') status = int(f.read()) f.close() os.remove(stsfile) f = open_latin1(outfile, 'r') text = f.read() f.close() os.remove(outfile) return status, text def quote_arg(arg): if arg[0]!='"' and ' ' in arg: return '"%s"' % arg return arg def _exec_command( command, use_shell=None, use_tee = None, **env ): log.debug('_exec_command(...)') if use_shell is None: use_shell = os.name=='posix' if use_tee is None: use_tee = os.name=='posix' using_command = 0 if use_shell: # We use shell (unless use_shell==0) so that wildcards can be # used. sh = os.environ.get('SHELL', '/bin/sh') if is_sequence(command): argv = [sh, '-c', ' '.join(list(command))] else: argv = [sh, '-c', command] else: # On NT, DOS we avoid using command.com as it's exit status is # not related to the exit status of a command. if is_sequence(command): argv = command[:] else: argv = shlex.split(command) if hasattr(os, 'spawnvpe'): spawn_command = os.spawnvpe else: spawn_command = os.spawnve argv[0] = find_executable(argv[0]) or argv[0] if not os.path.isfile(argv[0]): log.warn('Executable %s does not exist' % (argv[0])) if os.name in ['nt', 'dos']: # argv[0] might be internal command argv = [os.environ['COMSPEC'], '/C'] + argv using_command = 1 _so_has_fileno = _supports_fileno(sys.stdout) _se_has_fileno = _supports_fileno(sys.stderr) so_flush = sys.stdout.flush se_flush = sys.stderr.flush if _so_has_fileno: so_fileno = sys.stdout.fileno() so_dup = os.dup(so_fileno) if _se_has_fileno: se_fileno = sys.stderr.fileno() se_dup = os.dup(se_fileno) outfile = temp_file_name() fout = open(outfile, 'w') if using_command: errfile = temp_file_name() ferr = open(errfile, 'w') log.debug('Running %s(%s,%r,%r,os.environ)' \ % (spawn_command.__name__, os.P_WAIT, argv[0], argv)) argv0 = argv[0] if not using_command: argv[0] = quote_arg(argv0) so_flush() se_flush() if _so_has_fileno: os.dup2(fout.fileno(), so_fileno) if _se_has_fileno: if using_command: #XXX: disabled for now as it does not work from cmd under win32. # Tests fail on msys os.dup2(ferr.fileno(), se_fileno) else: os.dup2(fout.fileno(), se_fileno) try: status = spawn_command(os.P_WAIT, argv0, argv, os.environ) except OSError: errmess = str(get_exception()) status = 999 sys.stderr.write('%s: %s'%(errmess, argv[0])) so_flush() se_flush() if _so_has_fileno: os.dup2(so_dup, so_fileno) if _se_has_fileno: os.dup2(se_dup, se_fileno) fout.close() fout = open_latin1(outfile, 'r') text = fout.read() fout.close() os.remove(outfile) if using_command: ferr.close() ferr = open_latin1(errfile, 'r') errmess = ferr.read() ferr.close() os.remove(errfile) if errmess and not status: # Not sure how to handle the case where errmess # contains only warning messages and that should # not be treated as errors. #status = 998 if text: text = text + '\n' #text = '%sCOMMAND %r FAILED: %s' %(text,command,errmess) text = text + errmess print (errmess) if text[-1:]=='\n': text = text[:-1] if status is None: status = 0 if use_tee: print (text) return status, text def test_nt(**kws): pythonexe = get_pythonexe() echo = find_executable('echo') using_cygwin_echo = echo != 'echo' if using_cygwin_echo: log.warn('Using cygwin echo in win32 environment is not supported') s, o=exec_command(pythonexe\ +' -c "import os;print os.environ.get(\'AAA\',\'\')"') assert s==0 and o=='', (s, o) s, o=exec_command(pythonexe\ +' -c "import os;print os.environ.get(\'AAA\')"', AAA='Tere') assert s==0 and o=='Tere', (s, o) os.environ['BBB'] = 'Hi' s, o=exec_command(pythonexe\ +' -c "import os;print os.environ.get(\'BBB\',\'\')"') assert s==0 and o=='Hi', (s, o) s, o=exec_command(pythonexe\ +' -c "import os;print os.environ.get(\'BBB\',\'\')"', BBB='Hey') assert s==0 and o=='Hey', (s, o) s, o=exec_command(pythonexe\ +' -c "import os;print os.environ.get(\'BBB\',\'\')"') assert s==0 and o=='Hi', (s, o) elif 0: s, o=exec_command('echo Hello') assert s==0 and o=='Hello', (s, o) s, o=exec_command('echo a%AAA%') assert s==0 and o=='a', (s, o) s, o=exec_command('echo a%AAA%', AAA='Tere') assert s==0 and o=='aTere', (s, o) os.environ['BBB'] = 'Hi' s, o=exec_command('echo a%BBB%') assert s==0 and o=='aHi', (s, o) s, o=exec_command('echo a%BBB%', BBB='Hey') assert s==0 and o=='aHey', (s, o) s, o=exec_command('echo a%BBB%') assert s==0 and o=='aHi', (s, o) s, o=exec_command('this_is_not_a_command') assert s and o!='', (s, o) s, o=exec_command('type not_existing_file') assert s and o!='', (s, o) s, o=exec_command('echo path=%path%') assert s==0 and o!='', (s, o) s, o=exec_command('%s -c "import sys;sys.stderr.write(sys.platform)"' \ % pythonexe) assert s==0 and o=='win32', (s, o) s, o=exec_command('%s -c "raise \'Ignore me.\'"' % pythonexe) assert s==1 and o, (s, o) s, o=exec_command('%s -c "import sys;sys.stderr.write(\'0\');sys.stderr.write(\'1\');sys.stderr.write(\'2\')"'\ % pythonexe) assert s==0 and o=='012', (s, o) s, o=exec_command('%s -c "import sys;sys.exit(15)"' % pythonexe) assert s==15 and o=='', (s, o) s, o=exec_command('%s -c "print \'Heipa\'"' % pythonexe) assert s==0 and o=='Heipa', (s, o) print ('ok') def test_posix(**kws): s, o=exec_command("echo Hello",**kws) assert s==0 and o=='Hello', (s, o) s, o=exec_command('echo $AAA',**kws) assert s==0 and o=='', (s, o) s, o=exec_command('echo "$AAA"',AAA='Tere',**kws) assert s==0 and o=='Tere', (s, o) s, o=exec_command('echo "$AAA"',**kws) assert s==0 and o=='', (s, o) os.environ['BBB'] = 'Hi' s, o=exec_command('echo "$BBB"',**kws) assert s==0 and o=='Hi', (s, o) s, o=exec_command('echo "$BBB"',BBB='Hey',**kws) assert s==0 and o=='Hey', (s, o) s, o=exec_command('echo "$BBB"',**kws) assert s==0 and o=='Hi', (s, o) s, o=exec_command('this_is_not_a_command',**kws) assert s!=0 and o!='', (s, o) s, o=exec_command('echo path=$PATH',**kws) assert s==0 and o!='', (s, o) s, o=exec_command('python -c "import sys,os;sys.stderr.write(os.name)"',**kws) assert s==0 and o=='posix', (s, o) s, o=exec_command('python -c "raise \'Ignore me.\'"',**kws) assert s==1 and o, (s, o) s, o=exec_command('python -c "import sys;sys.stderr.write(\'0\');sys.stderr.write(\'1\');sys.stderr.write(\'2\')"',**kws) assert s==0 and o=='012', (s, o) s, o=exec_command('python -c "import sys;sys.exit(15)"',**kws) assert s==15 and o=='', (s, o) s, o=exec_command('python -c "print \'Heipa\'"',**kws) assert s==0 and o=='Heipa', (s, o) print ('ok') def test_execute_in(**kws): pythonexe = get_pythonexe() tmpfile = temp_file_name() fn = os.path.basename(tmpfile) tmpdir = os.path.dirname(tmpfile) f = open(tmpfile, 'w') f.write('Hello') f.close() s, o = exec_command('%s -c "print \'Ignore the following IOError:\','\ 'open(%r,\'r\')"' % (pythonexe, fn),**kws) assert s and o!='', (s, o) s, o = exec_command('%s -c "print open(%r,\'r\').read()"' % (pythonexe, fn), execute_in = tmpdir,**kws) assert s==0 and o=='Hello', (s, o) os.remove(tmpfile) print ('ok') def test_svn(**kws): s, o = exec_command(['svn', 'status'],**kws) assert s, (s, o) print ('svn ok') def test_cl(**kws): if os.name=='nt': s, o = exec_command(['cl', '/V'],**kws) assert s, (s, o) print ('cl ok') if os.name=='posix': test = test_posix elif os.name in ['nt', 'dos']: test = test_nt else: raise NotImplementedError('exec_command tests for ', os.name) ############################################################ if __name__ == "__main__": test(use_tee=0) test(use_tee=1) test_execute_in(use_tee=0) test_execute_in(use_tee=1) test_svn(use_tee=1) test_cl(use_tee=1) numpy-1.8.2/numpy/distutils/info.py0000664000175100017510000000023512370216242020524 0ustar vagrantvagrant00000000000000""" Enhanced distutils with Fortran compilers support and more. """ from __future__ import division, absolute_import, print_function postpone_import = True numpy-1.8.2/numpy/distutils/pathccompiler.py0000664000175100017510000000141312370216242022422 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function from distutils.unixccompiler import UnixCCompiler class PathScaleCCompiler(UnixCCompiler): """ PathScale compiler compatible with an gcc built Python. """ compiler_type = 'pathcc' cc_exe = 'pathcc' cxx_exe = 'pathCC' def __init__ (self, verbose=0, dry_run=0, force=0): UnixCCompiler.__init__ (self, verbose, dry_run, force) cc_compiler = self.cc_exe cxx_compiler = self.cxx_exe self.set_executables(compiler=cc_compiler, compiler_so=cc_compiler, compiler_cxx=cxx_compiler, linker_exe=cc_compiler, linker_so=cc_compiler + ' -shared') numpy-1.8.2/numpy/distutils/intelccompiler.py0000664000175100017510000000335712370216242022612 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function from distutils.unixccompiler import UnixCCompiler from numpy.distutils.exec_command import find_executable class IntelCCompiler(UnixCCompiler): """ A modified Intel compiler compatible with an gcc built Python.""" compiler_type = 'intel' cc_exe = 'icc' cc_args = 'fPIC' def __init__ (self, verbose=0, dry_run=0, force=0): UnixCCompiler.__init__ (self, verbose, dry_run, force) self.cc_exe = 'icc -fPIC' compiler = self.cc_exe self.set_executables(compiler=compiler, compiler_so=compiler, compiler_cxx=compiler, linker_exe=compiler, linker_so=compiler + ' -shared') class IntelItaniumCCompiler(IntelCCompiler): compiler_type = 'intele' # On Itanium, the Intel Compiler used to be called ecc, let's search for # it (now it's also icc, so ecc is last in the search). for cc_exe in map(find_executable, ['icc', 'ecc']): if cc_exe: break class IntelEM64TCCompiler(UnixCCompiler): """ A modified Intel x86_64 compiler compatible with a 64bit gcc built Python. """ compiler_type = 'intelem' cc_exe = 'icc -m64 -fPIC' cc_args = "-fPIC" def __init__ (self, verbose=0, dry_run=0, force=0): UnixCCompiler.__init__ (self, verbose, dry_run, force) self.cc_exe = 'icc -m64 -fPIC' compiler = self.cc_exe self.set_executables(compiler=compiler, compiler_so=compiler, compiler_cxx=compiler, linker_exe=compiler, linker_so=compiler + ' -shared') numpy-1.8.2/numpy/distutils/setup.py0000664000175100017510000000114312370216242020730 0ustar vagrantvagrant00000000000000#!/usr/bin/env python from __future__ import division, print_function def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('distutils', parent_package, top_path) config.add_subpackage('command') config.add_subpackage('fcompiler') config.add_data_dir('tests') config.add_data_files('site.cfg') config.add_data_files('mingw/gfortran_vs2003_hack.c') config.make_config_py() return config if __name__ == '__main__': from numpy.distutils.core import setup setup(configuration=configuration) numpy-1.8.2/numpy/distutils/ccompiler.py0000664000175100017510000005442612370216242021561 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function import re import os import sys import types from copy import copy from distutils.ccompiler import * from distutils import ccompiler from distutils.errors import DistutilsExecError, DistutilsModuleError, \ DistutilsPlatformError from distutils.sysconfig import customize_compiler from distutils.version import LooseVersion from numpy.distutils import log from numpy.distutils.exec_command import exec_command from numpy.distutils.misc_util import cyg2win32, is_sequence, mingw32, \ quote_args from numpy.distutils.compat import get_exception def replace_method(klass, method_name, func): if sys.version_info[0] < 3: m = types.MethodType(func, None, klass) else: # Py3k does not have unbound method anymore, MethodType does not work m = lambda self, *args, **kw: func(self, *args, **kw) setattr(klass, method_name, m) # Using customized CCompiler.spawn. def CCompiler_spawn(self, cmd, display=None): """ Execute a command in a sub-process. Parameters ---------- cmd : str The command to execute. display : str or sequence of str, optional The text to add to the log file kept by `numpy.distutils`. If not given, `display` is equal to `cmd`. Returns ------- None Raises ------ DistutilsExecError If the command failed, i.e. the exit status was not 0. """ if display is None: display = cmd if is_sequence(display): display = ' '.join(list(display)) log.info(display) s, o = exec_command(cmd) if s: if is_sequence(cmd): cmd = ' '.join(list(cmd)) try: print(o) except UnicodeError: # When installing through pip, `o` can contain non-ascii chars pass if re.search('Too many open files', o): msg = '\nTry rerunning setup command until build succeeds.' else: msg = '' raise DistutilsExecError('Command "%s" failed with exit status %d%s' % (cmd, s, msg)) replace_method(CCompiler, 'spawn', CCompiler_spawn) def CCompiler_object_filenames(self, source_filenames, strip_dir=0, output_dir=''): """ Return the name of the object files for the given source files. Parameters ---------- source_filenames : list of str The list of paths to source files. Paths can be either relative or absolute, this is handled transparently. strip_dir : bool, optional Whether to strip the directory from the returned paths. If True, the file name prepended by `output_dir` is returned. Default is False. output_dir : str, optional If given, this path is prepended to the returned paths to the object files. Returns ------- obj_names : list of str The list of paths to the object files corresponding to the source files in `source_filenames`. """ if output_dir is None: output_dir = '' obj_names = [] for src_name in source_filenames: base, ext = os.path.splitext(os.path.normpath(src_name)) base = os.path.splitdrive(base)[1] # Chop off the drive base = base[os.path.isabs(base):] # If abs, chop off leading / if base.startswith('..'): # Resolve starting relative path components, middle ones # (if any) have been handled by os.path.normpath above. i = base.rfind('..')+2 d = base[:i] d = os.path.basename(os.path.abspath(d)) base = d + base[i:] if ext not in self.src_extensions: raise UnknownFileError("unknown file type '%s' (from '%s')" % (ext, src_name)) if strip_dir: base = os.path.basename(base) obj_name = os.path.join(output_dir, base + self.obj_extension) obj_names.append(obj_name) return obj_names replace_method(CCompiler, 'object_filenames', CCompiler_object_filenames) def CCompiler_compile(self, sources, output_dir=None, macros=None, include_dirs=None, debug=0, extra_preargs=None, extra_postargs=None, depends=None): """ Compile one or more source files. Please refer to the Python distutils API reference for more details. Parameters ---------- sources : list of str A list of filenames output_dir : str, optional Path to the output directory. macros : list of tuples A list of macro definitions. include_dirs : list of str, optional The directories to add to the default include file search path for this compilation only. debug : bool, optional Whether or not to output debug symbols in or alongside the object file(s). extra_preargs, extra_postargs : ? Extra pre- and post-arguments. depends : list of str, optional A list of file names that all targets depend on. Returns ------- objects : list of str A list of object file names, one per source file `sources`. Raises ------ CompileError If compilation fails. """ # This method is effective only with Python >=2.3 distutils. # Any changes here should be applied also to fcompiler.compile # method to support pre Python 2.3 distutils. if not sources: return [] # FIXME:RELATIVE_IMPORT if sys.version_info[0] < 3: from .fcompiler import FCompiler else: from numpy.distutils.fcompiler import FCompiler if isinstance(self, FCompiler): display = [] for fc in ['f77', 'f90', 'fix']: fcomp = getattr(self, 'compiler_'+fc) if fcomp is None: continue display.append("Fortran %s compiler: %s" % (fc, ' '.join(fcomp))) display = '\n'.join(display) else: ccomp = self.compiler_so display = "C compiler: %s\n" % (' '.join(ccomp),) log.info(display) macros, objects, extra_postargs, pp_opts, build = \ self._setup_compile(output_dir, macros, include_dirs, sources, depends, extra_postargs) cc_args = self._get_cc_args(pp_opts, debug, extra_preargs) display = "compile options: '%s'" % (' '.join(cc_args)) if extra_postargs: display += "\nextra options: '%s'" % (' '.join(extra_postargs)) log.info(display) # build any sources in same order as they were originally specified # especially important for fortran .f90 files using modules if isinstance(self, FCompiler): objects_to_build = list(build.keys()) for obj in objects: if obj in objects_to_build: src, ext = build[obj] if self.compiler_type=='absoft': obj = cyg2win32(obj) src = cyg2win32(src) self._compile(obj, src, ext, cc_args, extra_postargs, pp_opts) else: for obj, (src, ext) in build.items(): self._compile(obj, src, ext, cc_args, extra_postargs, pp_opts) # Return *all* object filenames, not just the ones we just built. return objects replace_method(CCompiler, 'compile', CCompiler_compile) def CCompiler_customize_cmd(self, cmd, ignore=()): """ Customize compiler using distutils command. Parameters ---------- cmd : class instance An instance inheriting from `distutils.cmd.Command`. ignore : sequence of str, optional List of `CCompiler` commands (without ``'set_'``) that should not be altered. Strings that are checked for are: ``('include_dirs', 'define', 'undef', 'libraries', 'library_dirs', 'rpath', 'link_objects')``. Returns ------- None """ log.info('customize %s using %s' % (self.__class__.__name__, cmd.__class__.__name__)) def allow(attr): return getattr(cmd, attr, None) is not None and attr not in ignore if allow('include_dirs'): self.set_include_dirs(cmd.include_dirs) if allow('define'): for (name, value) in cmd.define: self.define_macro(name, value) if allow('undef'): for macro in cmd.undef: self.undefine_macro(macro) if allow('libraries'): self.set_libraries(self.libraries + cmd.libraries) if allow('library_dirs'): self.set_library_dirs(self.library_dirs + cmd.library_dirs) if allow('rpath'): self.set_runtime_library_dirs(cmd.rpath) if allow('link_objects'): self.set_link_objects(cmd.link_objects) replace_method(CCompiler, 'customize_cmd', CCompiler_customize_cmd) def _compiler_to_string(compiler): props = [] mx = 0 keys = list(compiler.executables.keys()) for key in ['version', 'libraries', 'library_dirs', 'object_switch', 'compile_switch', 'include_dirs', 'define', 'undef', 'rpath', 'link_objects']: if key not in keys: keys.append(key) for key in keys: if hasattr(compiler, key): v = getattr(compiler, key) mx = max(mx, len(key)) props.append((key, repr(v))) lines = [] format = '%-' + repr(mx+1) + 's = %s' for prop in props: lines.append(format % prop) return '\n'.join(lines) def CCompiler_show_customization(self): """ Print the compiler customizations to stdout. Parameters ---------- None Returns ------- None Notes ----- Printing is only done if the distutils log threshold is < 2. """ if 0: for attrname in ['include_dirs', 'define', 'undef', 'libraries', 'library_dirs', 'rpath', 'link_objects']: attr = getattr(self, attrname, None) if not attr: continue log.info("compiler '%s' is set to %s" % (attrname, attr)) try: self.get_version() except: pass if log._global_log.threshold<2: print('*'*80) print(self.__class__) print(_compiler_to_string(self)) print('*'*80) replace_method(CCompiler, 'show_customization', CCompiler_show_customization) def CCompiler_customize(self, dist, need_cxx=0): """ Do any platform-specific customization of a compiler instance. This method calls `distutils.sysconfig.customize_compiler` for platform-specific customization, as well as optionally remove a flag to suppress spurious warnings in case C++ code is being compiled. Parameters ---------- dist : object This parameter is not used for anything. need_cxx : bool, optional Whether or not C++ has to be compiled. If so (True), the ``"-Wstrict-prototypes"`` option is removed to prevent spurious warnings. Default is False. Returns ------- None Notes ----- All the default options used by distutils can be extracted with:: from distutils import sysconfig sysconfig.get_config_vars('CC', 'CXX', 'OPT', 'BASECFLAGS', 'CCSHARED', 'LDSHARED', 'SO') """ # See FCompiler.customize for suggested usage. log.info('customize %s' % (self.__class__.__name__)) customize_compiler(self) if need_cxx: # In general, distutils uses -Wstrict-prototypes, but this option is # not valid for C++ code, only for C. Remove it if it's there to # avoid a spurious warning on every compilation. try: self.compiler_so.remove('-Wstrict-prototypes') except (AttributeError, ValueError): pass if hasattr(self, 'compiler') and 'cc' in self.compiler[0]: if not self.compiler_cxx: if self.compiler[0].startswith('gcc'): a, b = 'gcc', 'g++' else: a, b = 'cc', 'c++' self.compiler_cxx = [self.compiler[0].replace(a, b)]\ + self.compiler[1:] else: if hasattr(self, 'compiler'): log.warn("#### %s #######" % (self.compiler,)) log.warn('Missing compiler_cxx fix for '+self.__class__.__name__) return replace_method(CCompiler, 'customize', CCompiler_customize) def simple_version_match(pat=r'[-.\d]+', ignore='', start=''): """ Simple matching of version numbers, for use in CCompiler and FCompiler. Parameters ---------- pat : str, optional A regular expression matching version numbers. Default is ``r'[-.\\d]+'``. ignore : str, optional A regular expression matching patterns to skip. Default is ``''``, in which case nothing is skipped. start : str, optional A regular expression matching the start of where to start looking for version numbers. Default is ``''``, in which case searching is started at the beginning of the version string given to `matcher`. Returns ------- matcher : callable A function that is appropriate to use as the ``.version_match`` attribute of a `CCompiler` class. `matcher` takes a single parameter, a version string. """ def matcher(self, version_string): # version string may appear in the second line, so getting rid # of new lines: version_string = version_string.replace('\n', ' ') pos = 0 if start: m = re.match(start, version_string) if not m: return None pos = m.end() while True: m = re.search(pat, version_string[pos:]) if not m: return None if ignore and re.match(ignore, m.group(0)): pos = m.end() continue break return m.group(0) return matcher def CCompiler_get_version(self, force=False, ok_status=[0]): """ Return compiler version, or None if compiler is not available. Parameters ---------- force : bool, optional If True, force a new determination of the version, even if the compiler already has a version attribute. Default is False. ok_status : list of int, optional The list of status values returned by the version look-up process for which a version string is returned. If the status value is not in `ok_status`, None is returned. Default is ``[0]``. Returns ------- version : str or None Version string, in the format of `distutils.version.LooseVersion`. """ if not force and hasattr(self, 'version'): return self.version self.find_executables() try: version_cmd = self.version_cmd except AttributeError: return None if not version_cmd or not version_cmd[0]: return None try: matcher = self.version_match except AttributeError: try: pat = self.version_pattern except AttributeError: return None def matcher(version_string): m = re.match(pat, version_string) if not m: return None version = m.group('version') return version status, output = exec_command(version_cmd, use_tee=0) version = None if status in ok_status: version = matcher(output) if version: version = LooseVersion(version) self.version = version return version replace_method(CCompiler, 'get_version', CCompiler_get_version) def CCompiler_cxx_compiler(self): """ Return the C++ compiler. Parameters ---------- None Returns ------- cxx : class instance The C++ compiler, as a `CCompiler` instance. """ if self.compiler_type=='msvc': return self cxx = copy(self) cxx.compiler_so = [cxx.compiler_cxx[0]] + cxx.compiler_so[1:] if sys.platform.startswith('aix') and 'ld_so_aix' in cxx.linker_so[0]: # AIX needs the ld_so_aix script included with Python cxx.linker_so = [cxx.linker_so[0], cxx.compiler_cxx[0]] \ + cxx.linker_so[2:] else: cxx.linker_so = [cxx.compiler_cxx[0]] + cxx.linker_so[1:] return cxx replace_method(CCompiler, 'cxx_compiler', CCompiler_cxx_compiler) compiler_class['intel'] = ('intelccompiler', 'IntelCCompiler', "Intel C Compiler for 32-bit applications") compiler_class['intele'] = ('intelccompiler', 'IntelItaniumCCompiler', "Intel C Itanium Compiler for Itanium-based applications") compiler_class['intelem'] = ('intelccompiler', 'IntelEM64TCCompiler', "Intel C Compiler for 64-bit applications") compiler_class['pathcc'] = ('pathccompiler', 'PathScaleCCompiler', "PathScale Compiler for SiCortex-based applications") ccompiler._default_compilers += (('linux.*', 'intel'), ('linux.*', 'intele'), ('linux.*', 'intelem'), ('linux.*', 'pathcc')) if sys.platform == 'win32': compiler_class['mingw32'] = ('mingw32ccompiler', 'Mingw32CCompiler', "Mingw32 port of GNU C Compiler for Win32"\ "(for MSC built Python)") if mingw32(): # On windows platforms, we want to default to mingw32 (gcc) # because msvc can't build blitz stuff. log.info('Setting mingw32 as default compiler for nt.') ccompiler._default_compilers = (('nt', 'mingw32'),) \ + ccompiler._default_compilers _distutils_new_compiler = new_compiler def new_compiler (plat=None, compiler=None, verbose=0, dry_run=0, force=0): # Try first C compilers from numpy.distutils. if plat is None: plat = os.name try: if compiler is None: compiler = get_default_compiler(plat) (module_name, class_name, long_description) = compiler_class[compiler] except KeyError: msg = "don't know how to compile C/C++ code on platform '%s'" % plat if compiler is not None: msg = msg + " with '%s' compiler" % compiler raise DistutilsPlatformError(msg) module_name = "numpy.distutils." + module_name try: __import__ (module_name) except ImportError: msg = str(get_exception()) log.info('%s in numpy.distutils; trying from distutils', str(msg)) module_name = module_name[6:] try: __import__(module_name) except ImportError: msg = str(get_exception()) raise DistutilsModuleError("can't compile C/C++ code: unable to load module '%s'" % \ module_name) try: module = sys.modules[module_name] klass = vars(module)[class_name] except KeyError: raise DistutilsModuleError(("can't compile C/C++ code: unable to find class '%s' " + "in module '%s'") % (class_name, module_name)) compiler = klass(None, dry_run, force) log.debug('new_compiler returns %s' % (klass)) return compiler ccompiler.new_compiler = new_compiler _distutils_gen_lib_options = gen_lib_options def gen_lib_options(compiler, library_dirs, runtime_library_dirs, libraries): library_dirs = quote_args(library_dirs) runtime_library_dirs = quote_args(runtime_library_dirs) r = _distutils_gen_lib_options(compiler, library_dirs, runtime_library_dirs, libraries) lib_opts = [] for i in r: if is_sequence(i): lib_opts.extend(list(i)) else: lib_opts.append(i) return lib_opts ccompiler.gen_lib_options = gen_lib_options # Also fix up the various compiler modules, which do # from distutils.ccompiler import gen_lib_options # Don't bother with mwerks, as we don't support Classic Mac. for _cc in ['msvc', 'bcpp', 'cygwinc', 'emxc', 'unixc']: _m = sys.modules.get('distutils.'+_cc+'compiler') if _m is not None: setattr(_m, 'gen_lib_options', gen_lib_options) _distutils_gen_preprocess_options = gen_preprocess_options def gen_preprocess_options (macros, include_dirs): include_dirs = quote_args(include_dirs) return _distutils_gen_preprocess_options(macros, include_dirs) ccompiler.gen_preprocess_options = gen_preprocess_options ##Fix distutils.util.split_quoted: # NOTE: I removed this fix in revision 4481 (see ticket #619), but it appears # that removing this fix causes f2py problems on Windows XP (see ticket #723). # Specifically, on WinXP when gfortran is installed in a directory path, which # contains spaces, then f2py is unable to find it. import re import string _wordchars_re = re.compile(r'[^\\\'\"%s ]*' % string.whitespace) _squote_re = re.compile(r"'(?:[^'\\]|\\.)*'") _dquote_re = re.compile(r'"(?:[^"\\]|\\.)*"') _has_white_re = re.compile(r'\s') def split_quoted(s): s = s.strip() words = [] pos = 0 while s: m = _wordchars_re.match(s, pos) end = m.end() if end == len(s): words.append(s[:end]) break if s[end] in string.whitespace: # unescaped, unquoted whitespace: now words.append(s[:end]) # we definitely have a word delimiter s = s[end:].lstrip() pos = 0 elif s[end] == '\\': # preserve whatever is being escaped; # will become part of the current word s = s[:end] + s[end+1:] pos = end+1 else: if s[end] == "'": # slurp singly-quoted string m = _squote_re.match(s, end) elif s[end] == '"': # slurp doubly-quoted string m = _dquote_re.match(s, end) else: raise RuntimeError("this can't happen (bad char '%c')" % s[end]) if m is None: raise ValueError("bad string (mismatched %s quotes?)" % s[end]) (beg, end) = m.span() if _has_white_re.search(s[beg+1:end-1]): s = s[:beg] + s[beg+1:end-1] + s[end:] pos = m.end() - 2 else: # Keeping quotes when a quoted word does not contain # white-space. XXX: send a patch to distutils pos = m.end() if pos >= len(s): words.append(s) break return words ccompiler.split_quoted = split_quoted ##Fix distutils.util.split_quoted: numpy-1.8.2/numpy/distutils/mingw32ccompiler.py0000664000175100017510000005364312370216242022770 0ustar vagrantvagrant00000000000000""" Support code for building Python extensions on Windows. # NT stuff # 1. Make sure libpython.a exists for gcc. If not, build it. # 2. Force windows to use gcc (we're struggling with MSVC and g77 support) # 3. Force windows to use g77 """ from __future__ import division, absolute_import, print_function import os import sys import subprocess import re # Overwrite certain distutils.ccompiler functions: import numpy.distutils.ccompiler if sys.version_info[0] < 3: from . import log else: from numpy.distutils import log # NT stuff # 1. Make sure libpython.a exists for gcc. If not, build it. # 2. Force windows to use gcc (we're struggling with MSVC and g77 support) # --> this is done in numpy/distutils/ccompiler.py # 3. Force windows to use g77 import distutils.cygwinccompiler from distutils.version import StrictVersion from numpy.distutils.ccompiler import gen_preprocess_options, gen_lib_options from distutils.errors import DistutilsExecError, CompileError, UnknownFileError from distutils.unixccompiler import UnixCCompiler from distutils.msvccompiler import get_build_version as get_build_msvc_version from numpy.distutils.misc_util import msvc_runtime_library, get_build_architecture # Useful to generate table of symbols from a dll _START = re.compile(r'\[Ordinal/Name Pointer\] Table') _TABLE = re.compile(r'^\s+\[([\s*[0-9]*)\] ([a-zA-Z0-9_]*)') # the same as cygwin plus some additional parameters class Mingw32CCompiler(distutils.cygwinccompiler.CygwinCCompiler): """ A modified MingW32 compiler compatible with an MSVC built Python. """ compiler_type = 'mingw32' def __init__ (self, verbose=0, dry_run=0, force=0): distutils.cygwinccompiler.CygwinCCompiler.__init__ (self, verbose, dry_run, force) # we need to support 3.2 which doesn't match the standard # get_versions methods regex if self.gcc_version is None: import re p = subprocess.Popen(['gcc', '-dumpversion'], shell=True, stdout=subprocess.PIPE) out_string = p.stdout.read() p.stdout.close() result = re.search('(\d+\.\d+)', out_string) if result: self.gcc_version = StrictVersion(result.group(1)) # A real mingw32 doesn't need to specify a different entry point, # but cygwin 2.91.57 in no-cygwin-mode needs it. if self.gcc_version <= "2.91.57": entry_point = '--entry _DllMain@12' else: entry_point = '' if self.linker_dll == 'dllwrap': # Commented out '--driver-name g++' part that fixes weird # g++.exe: g++: No such file or directory # error (mingw 1.0 in Enthon24 tree, gcc-3.4.5). # If the --driver-name part is required for some environment # then make the inclusion of this part specific to that environment. self.linker = 'dllwrap' # --driver-name g++' elif self.linker_dll == 'gcc': self.linker = 'g++' # **changes: eric jones 4/11/01 # 1. Check for import library on Windows. Build if it doesn't exist. build_import_library() # Check for custom msvc runtime library on Windows. Build if it doesn't exist. msvcr_success = build_msvcr_library() msvcr_dbg_success = build_msvcr_library(debug=True) if msvcr_success or msvcr_dbg_success: # add preprocessor statement for using customized msvcr lib self.define_macro('NPY_MINGW_USE_CUSTOM_MSVCR') # Define the MSVC version as hint for MinGW msvcr_version = '0x%03i0' % int(msvc_runtime_library().lstrip('msvcr')) self.define_macro('__MSVCRT_VERSION__', msvcr_version) # **changes: eric jones 4/11/01 # 2. increased optimization and turned off all warnings # 3. also added --driver-name g++ #self.set_executables(compiler='gcc -mno-cygwin -O2 -w', # compiler_so='gcc -mno-cygwin -mdll -O2 -w', # linker_exe='gcc -mno-cygwin', # linker_so='%s --driver-name g++ -mno-cygwin -mdll -static %s' # % (self.linker, entry_point)) # MS_WIN64 should be defined when building for amd64 on windows, but # python headers define it only for MS compilers, which has all kind of # bad consequences, like using Py_ModuleInit4 instead of # Py_ModuleInit4_64, etc... So we add it here if get_build_architecture() == 'AMD64': if self.gcc_version < "4.0": self.set_executables( compiler='gcc -g -DDEBUG -DMS_WIN64 -mno-cygwin -O0 -Wall', compiler_so='gcc -g -DDEBUG -DMS_WIN64 -mno-cygwin -O0 -Wall -Wstrict-prototypes', linker_exe='gcc -g -mno-cygwin', linker_so='gcc -g -mno-cygwin -shared') else: # gcc-4 series releases do not support -mno-cygwin option self.set_executables( compiler='gcc -g -DDEBUG -DMS_WIN64 -O0 -Wall', compiler_so='gcc -g -DDEBUG -DMS_WIN64 -O0 -Wall -Wstrict-prototypes', linker_exe='gcc -g', linker_so='gcc -g -shared') else: if self.gcc_version <= "3.0.0": self.set_executables(compiler='gcc -mno-cygwin -O2 -w', compiler_so='gcc -mno-cygwin -mdll -O2 -w -Wstrict-prototypes', linker_exe='g++ -mno-cygwin', linker_so='%s -mno-cygwin -mdll -static %s' % (self.linker, entry_point)) elif self.gcc_version < "4.0": self.set_executables(compiler='gcc -mno-cygwin -O2 -Wall', compiler_so='gcc -mno-cygwin -O2 -Wall -Wstrict-prototypes', linker_exe='g++ -mno-cygwin', linker_so='g++ -mno-cygwin -shared') else: # gcc-4 series releases do not support -mno-cygwin option self.set_executables(compiler='gcc -O2 -Wall', compiler_so='gcc -O2 -Wall -Wstrict-prototypes', linker_exe='g++ ', linker_so='g++ -shared') # added for python2.3 support # we can't pass it through set_executables because pre 2.2 would fail self.compiler_cxx = ['g++'] # Maybe we should also append -mthreads, but then the finished # dlls need another dll (mingwm10.dll see Mingw32 docs) # (-mthreads: Support thread-safe exception handling on `Mingw32') # no additional libraries needed #self.dll_libraries=[] return # __init__ () def link(self, target_desc, objects, output_filename, output_dir, libraries, library_dirs, runtime_library_dirs, export_symbols = None, debug=0, extra_preargs=None, extra_postargs=None, build_temp=None, target_lang=None): # Include the appropiate MSVC runtime library if Python was built # with MSVC >= 7.0 (MinGW standard is msvcrt) runtime_library = msvc_runtime_library() if runtime_library: if not libraries: libraries = [] libraries.append(runtime_library) args = (self, target_desc, objects, output_filename, output_dir, libraries, library_dirs, runtime_library_dirs, None, #export_symbols, we do this in our def-file debug, extra_preargs, extra_postargs, build_temp, target_lang) if self.gcc_version < "3.0.0": func = distutils.cygwinccompiler.CygwinCCompiler.link else: func = UnixCCompiler.link func(*args[:func.__code__.co_argcount]) return def object_filenames (self, source_filenames, strip_dir=0, output_dir=''): if output_dir is None: output_dir = '' obj_names = [] for src_name in source_filenames: # use normcase to make sure '.rc' is really '.rc' and not '.RC' (base, ext) = os.path.splitext (os.path.normcase(src_name)) # added these lines to strip off windows drive letters # without it, .o files are placed next to .c files # instead of the build directory drv, base = os.path.splitdrive(base) if drv: base = base[1:] if ext not in (self.src_extensions + ['.rc', '.res']): raise UnknownFileError( "unknown file type '%s' (from '%s')" % \ (ext, src_name)) if strip_dir: base = os.path.basename (base) if ext == '.res' or ext == '.rc': # these need to be compiled to object files obj_names.append (os.path.join (output_dir, base + ext + self.obj_extension)) else: obj_names.append (os.path.join (output_dir, base + self.obj_extension)) return obj_names # object_filenames () def find_python_dll(): maj, min, micro = [int(i) for i in sys.version_info[:3]] dllname = 'python%d%d.dll' % (maj, min) print("Looking for %s" % dllname) # We can't do much here: # - find it in python main dir # - in system32, # - ortherwise (Sxs), I don't know how to get it. lib_dirs = [] lib_dirs.append(sys.prefix) lib_dirs.append(os.path.join(sys.prefix, 'lib')) try: lib_dirs.append(os.path.join(os.environ['SYSTEMROOT'], 'system32')) except KeyError: pass for d in lib_dirs: dll = os.path.join(d, dllname) if os.path.exists(dll): return dll raise ValueError("%s not found in %s" % (dllname, lib_dirs)) def dump_table(dll): st = subprocess.Popen(["objdump.exe", "-p", dll], stdout=subprocess.PIPE) return st.stdout.readlines() def generate_def(dll, dfile): """Given a dll file location, get all its exported symbols and dump them into the given def file. The .def file will be overwritten""" dump = dump_table(dll) for i in range(len(dump)): if _START.match(dump[i].decode()): break else: raise ValueError("Symbol table not found") syms = [] for j in range(i+1, len(dump)): m = _TABLE.match(dump[j].decode()) if m: syms.append((int(m.group(1).strip()), m.group(2))) else: break if len(syms) == 0: log.warn('No symbols found in %s' % dll) d = open(dfile, 'w') d.write('LIBRARY %s\n' % os.path.basename(dll)) d.write(';CODE PRELOAD MOVEABLE DISCARDABLE\n') d.write(';DATA PRELOAD SINGLE\n') d.write('\nEXPORTS\n') for s in syms: #d.write('@%d %s\n' % (s[0], s[1])) d.write('%s\n' % s[1]) d.close() def find_dll(dll_name): arch = {'AMD64' : 'amd64', 'Intel' : 'x86'}[get_build_architecture()] def _find_dll_in_winsxs(dll_name): # Walk through the WinSxS directory to find the dll. winsxs_path = os.path.join(os.environ['WINDIR'], 'winsxs') if not os.path.exists(winsxs_path): return None for root, dirs, files in os.walk(winsxs_path): if dll_name in files and arch in root: return os.path.join(root, dll_name) return None def _find_dll_in_path(dll_name): # First, look in the Python directory, then scan PATH for # the given dll name. for path in [sys.prefix] + os.environ['PATH'].split(';'): filepath = os.path.join(path, dll_name) if os.path.exists(filepath): return os.path.abspath(filepath) return _find_dll_in_winsxs(dll_name) or _find_dll_in_path(dll_name) def build_msvcr_library(debug=False): if os.name != 'nt': return False msvcr_name = msvc_runtime_library() # Skip using a custom library for versions < MSVC 8.0 if int(msvcr_name.lstrip('msvcr')) < 80: log.debug('Skip building msvcr library: custom functionality not present') return False if debug: msvcr_name += 'd' # Skip if custom library already exists out_name = "lib%s.a" % msvcr_name out_file = os.path.join(sys.prefix, 'libs', out_name) if os.path.isfile(out_file): log.debug('Skip building msvcr library: "%s" exists' % (out_file)) return True # Find the msvcr dll msvcr_dll_name = msvcr_name + '.dll' dll_file = find_dll(msvcr_dll_name) if not dll_file: log.warn('Cannot build msvcr library: "%s" not found' % msvcr_dll_name) return False def_name = "lib%s.def" % msvcr_name def_file = os.path.join(sys.prefix, 'libs', def_name) log.info('Building msvcr library: "%s" (from %s)' \ % (out_file, dll_file)) # Generate a symbol definition file from the msvcr dll generate_def(dll_file, def_file) # Create a custom mingw library for the given symbol definitions cmd = ['dlltool', '-d', def_file, '-l', out_file] retcode = subprocess.call(cmd) # Clean up symbol definitions os.remove(def_file) return (not retcode) def build_import_library(): if os.name != 'nt': return arch = get_build_architecture() if arch == 'AMD64': return _build_import_library_amd64() elif arch == 'Intel': return _build_import_library_x86() else: raise ValueError("Unhandled arch %s" % arch) def _build_import_library_amd64(): dll_file = find_python_dll() out_name = "libpython%d%d.a" % tuple(sys.version_info[:2]) out_file = os.path.join(sys.prefix, 'libs', out_name) if os.path.isfile(out_file): log.debug('Skip building import library: "%s" exists' % (out_file)) return def_name = "python%d%d.def" % tuple(sys.version_info[:2]) def_file = os.path.join(sys.prefix, 'libs', def_name) log.info('Building import library (arch=AMD64): "%s" (from %s)' \ % (out_file, dll_file)) generate_def(dll_file, def_file) cmd = ['dlltool', '-d', def_file, '-l', out_file] subprocess.Popen(cmd) def _build_import_library_x86(): """ Build the import libraries for Mingw32-gcc on Windows """ lib_name = "python%d%d.lib" % tuple(sys.version_info[:2]) lib_file = os.path.join(sys.prefix, 'libs', lib_name) out_name = "libpython%d%d.a" % tuple(sys.version_info[:2]) out_file = os.path.join(sys.prefix, 'libs', out_name) if not os.path.isfile(lib_file): log.warn('Cannot build import library: "%s" not found' % (lib_file)) return if os.path.isfile(out_file): log.debug('Skip building import library: "%s" exists' % (out_file)) return log.info('Building import library (ARCH=x86): "%s"' % (out_file)) from numpy.distutils import lib2def def_name = "python%d%d.def" % tuple(sys.version_info[:2]) def_file = os.path.join(sys.prefix, 'libs', def_name) nm_cmd = '%s %s' % (lib2def.DEFAULT_NM, lib_file) nm_output = lib2def.getnm(nm_cmd) dlist, flist = lib2def.parse_nm(nm_output) lib2def.output_def(dlist, flist, lib2def.DEF_HEADER, open(def_file, 'w')) dll_name = "python%d%d.dll" % tuple(sys.version_info[:2]) args = (dll_name, def_file, out_file) cmd = 'dlltool --dllname %s --def %s --output-lib %s' % args status = os.system(cmd) # for now, fail silently if status: log.warn('Failed to build import library for gcc. Linking will fail.') #if not success: # msg = "Couldn't find import library, and failed to build it." # raise DistutilsPlatformError(msg) return #===================================== # Dealing with Visual Studio MANIFESTS #===================================== # Functions to deal with visual studio manifests. Manifest are a mechanism to # enforce strong DLL versioning on windows, and has nothing to do with # distutils MANIFEST. manifests are XML files with version info, and used by # the OS loader; they are necessary when linking against a DLL not in the # system path; in particular, official python 2.6 binary is built against the # MS runtime 9 (the one from VS 2008), which is not available on most windows # systems; python 2.6 installer does install it in the Win SxS (Side by side) # directory, but this requires the manifest for this to work. This is a big # mess, thanks MS for a wonderful system. # XXX: ideally, we should use exactly the same version as used by python. I # submitted a patch to get this version, but it was only included for python # 2.6.1 and above. So for versions below, we use a "best guess". _MSVCRVER_TO_FULLVER = {} if sys.platform == 'win32': try: import msvcrt # I took one version in my SxS directory: no idea if it is the good # one, and we can't retrieve it from python _MSVCRVER_TO_FULLVER['80'] = "8.0.50727.42" _MSVCRVER_TO_FULLVER['90'] = "9.0.21022.8" # Value from msvcrt.CRT_ASSEMBLY_VERSION under Python 3.3.0 on Windows XP: _MSVCRVER_TO_FULLVER['100'] = "10.0.30319.460" if hasattr(msvcrt, "CRT_ASSEMBLY_VERSION"): major, minor, rest = msvcrt.CRT_ASSEMBLY_VERSION.split(".", 2) _MSVCRVER_TO_FULLVER[major + minor] = msvcrt.CRT_ASSEMBLY_VERSION del major, minor, rest except ImportError: # If we are here, means python was not built with MSVC. Not sure what to do # in that case: manifest building will fail, but it should not be used in # that case anyway log.warn('Cannot import msvcrt: using manifest will not be possible') def msvc_manifest_xml(maj, min): """Given a major and minor version of the MSVCR, returns the corresponding XML file.""" try: fullver = _MSVCRVER_TO_FULLVER[str(maj * 10 + min)] except KeyError: raise ValueError("Version %d,%d of MSVCRT not supported yet" \ % (maj, min)) # Don't be fooled, it looks like an XML, but it is not. In particular, it # should not have any space before starting, and its size should be # divisible by 4, most likely for alignement constraints when the xml is # embedded in the binary... # This template was copied directly from the python 2.6 binary (using # strings.exe from mingw on python.exe). template = """\ """ return template % {'fullver': fullver, 'maj': maj, 'min': min} def manifest_rc(name, type='dll'): """Return the rc file used to generate the res file which will be embedded as manifest for given manifest file name, of given type ('dll' or 'exe'). Parameters ---------- name : str name of the manifest file to embed type : str {'dll', 'exe'} type of the binary which will embed the manifest """ if type == 'dll': rctype = 2 elif type == 'exe': rctype = 1 else: raise ValueError("Type %s not supported" % type) return """\ #include "winuser.h" %d RT_MANIFEST %s""" % (rctype, name) def check_embedded_msvcr_match_linked(msver): """msver is the ms runtime version used for the MANIFEST.""" # check msvcr major version are the same for linking and # embedding msvcv = msvc_runtime_library() if msvcv: assert msvcv.startswith("msvcr"), msvcv # Dealing with something like "mscvr90" or "mscvr100", the last # last digit is the minor release, want int("9") or int("10"): maj = int(msvcv[5:-1]) if not maj == int(msver): raise ValueError( "Discrepancy between linked msvcr " \ "(%d) and the one about to be embedded " \ "(%d)" % (int(msver), maj)) def configtest_name(config): base = os.path.basename(config._gen_temp_sourcefile("yo", [], "c")) return os.path.splitext(base)[0] def manifest_name(config): # Get configest name (including suffix) root = configtest_name(config) exext = config.compiler.exe_extension return root + exext + ".manifest" def rc_name(config): # Get configest name (including suffix) root = configtest_name(config) return root + ".rc" def generate_manifest(config): msver = get_build_msvc_version() if msver is not None: if msver >= 8: check_embedded_msvcr_match_linked(msver) ma = int(msver) mi = int((msver - ma) * 10) # Write the manifest file manxml = msvc_manifest_xml(ma, mi) man = open(manifest_name(config), "w") config.temp_files.append(manifest_name(config)) man.write(manxml) man.close() # # Write the rc file # manrc = manifest_rc(manifest_name(self), "exe") # rc = open(rc_name(self), "w") # self.temp_files.append(manrc) # rc.write(manrc) # rc.close() numpy-1.8.2/numpy/distutils/cpuinfo.py0000664000175100017510000005467212370216242021252 0ustar vagrantvagrant00000000000000#!/usr/bin/env python """ cpuinfo Copyright 2002 Pearu Peterson all rights reserved, Pearu Peterson Permission to use, modify, and distribute this software is given under the terms of the NumPy (BSD style) license. See LICENSE.txt that came with this distribution for specifics. NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. Pearu Peterson """ from __future__ import division, absolute_import, print_function __all__ = ['cpu'] import sys, re, types import os if sys.version_info[0] >= 3: from subprocess import getstatusoutput else: from commands import getstatusoutput import warnings import platform from numpy.distutils.compat import get_exception def getoutput(cmd, successful_status=(0,), stacklevel=1): try: status, output = getstatusoutput(cmd) except EnvironmentError: e = get_exception() warnings.warn(str(e), UserWarning, stacklevel=stacklevel) return False, output if os.WIFEXITED(status) and os.WEXITSTATUS(status) in successful_status: return True, output return False, output def command_info(successful_status=(0,), stacklevel=1, **kw): info = {} for key in kw: ok, output = getoutput(kw[key], successful_status=successful_status, stacklevel=stacklevel+1) if ok: info[key] = output.strip() return info def command_by_line(cmd, successful_status=(0,), stacklevel=1): ok, output = getoutput(cmd, successful_status=successful_status, stacklevel=stacklevel+1) if not ok: return for line in output.splitlines(): yield line.strip() def key_value_from_command(cmd, sep, successful_status=(0,), stacklevel=1): d = {} for line in command_by_line(cmd, successful_status=successful_status, stacklevel=stacklevel+1): l = [s.strip() for s in line.split(sep, 1)] if len(l) == 2: d[l[0]] = l[1] return d class CPUInfoBase(object): """Holds CPU information and provides methods for requiring the availability of various CPU features. """ def _try_call(self, func): try: return func() except: pass def __getattr__(self, name): if not name.startswith('_'): if hasattr(self, '_'+name): attr = getattr(self, '_'+name) if isinstance(attr, types.MethodType): return lambda func=self._try_call,attr=attr : func(attr) else: return lambda : None raise AttributeError(name) def _getNCPUs(self): return 1 def __get_nbits(self): abits = platform.architecture()[0] nbits = re.compile('(\d+)bit').search(abits).group(1) return nbits def _is_32bit(self): return self.__get_nbits() == '32' def _is_64bit(self): return self.__get_nbits() == '64' class LinuxCPUInfo(CPUInfoBase): info = None def __init__(self): if self.info is not None: return info = [ {} ] ok, output = getoutput('uname -m') if ok: info[0]['uname_m'] = output.strip() try: fo = open('/proc/cpuinfo') except EnvironmentError: e = get_exception() warnings.warn(str(e), UserWarning) else: for line in fo: name_value = [s.strip() for s in line.split(':', 1)] if len(name_value) != 2: continue name, value = name_value if not info or name in info[-1]: # next processor info.append({}) info[-1][name] = value fo.close() self.__class__.info = info def _not_impl(self): pass # Athlon def _is_AMD(self): return self.info[0]['vendor_id']=='AuthenticAMD' def _is_AthlonK6_2(self): return self._is_AMD() and self.info[0]['model'] == '2' def _is_AthlonK6_3(self): return self._is_AMD() and self.info[0]['model'] == '3' def _is_AthlonK6(self): return re.match(r'.*?AMD-K6', self.info[0]['model name']) is not None def _is_AthlonK7(self): return re.match(r'.*?AMD-K7', self.info[0]['model name']) is not None def _is_AthlonMP(self): return re.match(r'.*?Athlon\(tm\) MP\b', self.info[0]['model name']) is not None def _is_AMD64(self): return self.is_AMD() and self.info[0]['family'] == '15' def _is_Athlon64(self): return re.match(r'.*?Athlon\(tm\) 64\b', self.info[0]['model name']) is not None def _is_AthlonHX(self): return re.match(r'.*?Athlon HX\b', self.info[0]['model name']) is not None def _is_Opteron(self): return re.match(r'.*?Opteron\b', self.info[0]['model name']) is not None def _is_Hammer(self): return re.match(r'.*?Hammer\b', self.info[0]['model name']) is not None # Alpha def _is_Alpha(self): return self.info[0]['cpu']=='Alpha' def _is_EV4(self): return self.is_Alpha() and self.info[0]['cpu model'] == 'EV4' def _is_EV5(self): return self.is_Alpha() and self.info[0]['cpu model'] == 'EV5' def _is_EV56(self): return self.is_Alpha() and self.info[0]['cpu model'] == 'EV56' def _is_PCA56(self): return self.is_Alpha() and self.info[0]['cpu model'] == 'PCA56' # Intel #XXX _is_i386 = _not_impl def _is_Intel(self): return self.info[0]['vendor_id']=='GenuineIntel' def _is_i486(self): return self.info[0]['cpu']=='i486' def _is_i586(self): return self.is_Intel() and self.info[0]['cpu family'] == '5' def _is_i686(self): return self.is_Intel() and self.info[0]['cpu family'] == '6' def _is_Celeron(self): return re.match(r'.*?Celeron', self.info[0]['model name']) is not None def _is_Pentium(self): return re.match(r'.*?Pentium', self.info[0]['model name']) is not None def _is_PentiumII(self): return re.match(r'.*?Pentium.*?II\b', self.info[0]['model name']) is not None def _is_PentiumPro(self): return re.match(r'.*?PentiumPro\b', self.info[0]['model name']) is not None def _is_PentiumMMX(self): return re.match(r'.*?Pentium.*?MMX\b', self.info[0]['model name']) is not None def _is_PentiumIII(self): return re.match(r'.*?Pentium.*?III\b', self.info[0]['model name']) is not None def _is_PentiumIV(self): return re.match(r'.*?Pentium.*?(IV|4)\b', self.info[0]['model name']) is not None def _is_PentiumM(self): return re.match(r'.*?Pentium.*?M\b', self.info[0]['model name']) is not None def _is_Prescott(self): return self.is_PentiumIV() and self.has_sse3() def _is_Nocona(self): return self.is_Intel() \ and (self.info[0]['cpu family'] == '6' \ or self.info[0]['cpu family'] == '15' ) \ and (self.has_sse3() and not self.has_ssse3())\ and re.match(r'.*?\blm\b', self.info[0]['flags']) is not None def _is_Core2(self): return self.is_64bit() and self.is_Intel() and \ re.match(r'.*?Core\(TM\)2\b', \ self.info[0]['model name']) is not None def _is_Itanium(self): return re.match(r'.*?Itanium\b', self.info[0]['family']) is not None def _is_XEON(self): return re.match(r'.*?XEON\b', self.info[0]['model name'], re.IGNORECASE) is not None _is_Xeon = _is_XEON # Varia def _is_singleCPU(self): return len(self.info) == 1 def _getNCPUs(self): return len(self.info) def _has_fdiv_bug(self): return self.info[0]['fdiv_bug']=='yes' def _has_f00f_bug(self): return self.info[0]['f00f_bug']=='yes' def _has_mmx(self): return re.match(r'.*?\bmmx\b', self.info[0]['flags']) is not None def _has_sse(self): return re.match(r'.*?\bsse\b', self.info[0]['flags']) is not None def _has_sse2(self): return re.match(r'.*?\bsse2\b', self.info[0]['flags']) is not None def _has_sse3(self): return re.match(r'.*?\bpni\b', self.info[0]['flags']) is not None def _has_ssse3(self): return re.match(r'.*?\bssse3\b', self.info[0]['flags']) is not None def _has_3dnow(self): return re.match(r'.*?\b3dnow\b', self.info[0]['flags']) is not None def _has_3dnowext(self): return re.match(r'.*?\b3dnowext\b', self.info[0]['flags']) is not None class IRIXCPUInfo(CPUInfoBase): info = None def __init__(self): if self.info is not None: return info = key_value_from_command('sysconf', sep=' ', successful_status=(0, 1)) self.__class__.info = info def _not_impl(self): pass def _is_singleCPU(self): return self.info.get('NUM_PROCESSORS') == '1' def _getNCPUs(self): return int(self.info.get('NUM_PROCESSORS', 1)) def __cputype(self, n): return self.info.get('PROCESSORS').split()[0].lower() == 'r%s' % (n) def _is_r2000(self): return self.__cputype(2000) def _is_r3000(self): return self.__cputype(3000) def _is_r3900(self): return self.__cputype(3900) def _is_r4000(self): return self.__cputype(4000) def _is_r4100(self): return self.__cputype(4100) def _is_r4300(self): return self.__cputype(4300) def _is_r4400(self): return self.__cputype(4400) def _is_r4600(self): return self.__cputype(4600) def _is_r4650(self): return self.__cputype(4650) def _is_r5000(self): return self.__cputype(5000) def _is_r6000(self): return self.__cputype(6000) def _is_r8000(self): return self.__cputype(8000) def _is_r10000(self): return self.__cputype(10000) def _is_r12000(self): return self.__cputype(12000) def _is_rorion(self): return self.__cputype('orion') def get_ip(self): try: return self.info.get('MACHINE') except: pass def __machine(self, n): return self.info.get('MACHINE').lower() == 'ip%s' % (n) def _is_IP19(self): return self.__machine(19) def _is_IP20(self): return self.__machine(20) def _is_IP21(self): return self.__machine(21) def _is_IP22(self): return self.__machine(22) def _is_IP22_4k(self): return self.__machine(22) and self._is_r4000() def _is_IP22_5k(self): return self.__machine(22) and self._is_r5000() def _is_IP24(self): return self.__machine(24) def _is_IP25(self): return self.__machine(25) def _is_IP26(self): return self.__machine(26) def _is_IP27(self): return self.__machine(27) def _is_IP28(self): return self.__machine(28) def _is_IP30(self): return self.__machine(30) def _is_IP32(self): return self.__machine(32) def _is_IP32_5k(self): return self.__machine(32) and self._is_r5000() def _is_IP32_10k(self): return self.__machine(32) and self._is_r10000() class DarwinCPUInfo(CPUInfoBase): info = None def __init__(self): if self.info is not None: return info = command_info(arch='arch', machine='machine') info['sysctl_hw'] = key_value_from_command('sysctl hw', sep='=') self.__class__.info = info def _not_impl(self): pass def _getNCPUs(self): return int(self.info['sysctl_hw'].get('hw.ncpu', 1)) def _is_Power_Macintosh(self): return self.info['sysctl_hw']['hw.machine']=='Power Macintosh' def _is_i386(self): return self.info['arch']=='i386' def _is_ppc(self): return self.info['arch']=='ppc' def __machine(self, n): return self.info['machine'] == 'ppc%s'%n def _is_ppc601(self): return self.__machine(601) def _is_ppc602(self): return self.__machine(602) def _is_ppc603(self): return self.__machine(603) def _is_ppc603e(self): return self.__machine('603e') def _is_ppc604(self): return self.__machine(604) def _is_ppc604e(self): return self.__machine('604e') def _is_ppc620(self): return self.__machine(620) def _is_ppc630(self): return self.__machine(630) def _is_ppc740(self): return self.__machine(740) def _is_ppc7400(self): return self.__machine(7400) def _is_ppc7450(self): return self.__machine(7450) def _is_ppc750(self): return self.__machine(750) def _is_ppc403(self): return self.__machine(403) def _is_ppc505(self): return self.__machine(505) def _is_ppc801(self): return self.__machine(801) def _is_ppc821(self): return self.__machine(821) def _is_ppc823(self): return self.__machine(823) def _is_ppc860(self): return self.__machine(860) class SunOSCPUInfo(CPUInfoBase): info = None def __init__(self): if self.info is not None: return info = command_info(arch='arch', mach='mach', uname_i='uname_i', isainfo_b='isainfo -b', isainfo_n='isainfo -n', ) info['uname_X'] = key_value_from_command('uname -X', sep='=') for line in command_by_line('psrinfo -v 0'): m = re.match(r'\s*The (?P

    [\w\d]+) processor operates at', line) if m: info['processor'] = m.group('p') break self.__class__.info = info def _not_impl(self): pass def _is_i386(self): return self.info['isainfo_n']=='i386' def _is_sparc(self): return self.info['isainfo_n']=='sparc' def _is_sparcv9(self): return self.info['isainfo_n']=='sparcv9' def _getNCPUs(self): return int(self.info['uname_X'].get('NumCPU', 1)) def _is_sun4(self): return self.info['arch']=='sun4' def _is_SUNW(self): return re.match(r'SUNW', self.info['uname_i']) is not None def _is_sparcstation5(self): return re.match(r'.*SPARCstation-5', self.info['uname_i']) is not None def _is_ultra1(self): return re.match(r'.*Ultra-1', self.info['uname_i']) is not None def _is_ultra250(self): return re.match(r'.*Ultra-250', self.info['uname_i']) is not None def _is_ultra2(self): return re.match(r'.*Ultra-2', self.info['uname_i']) is not None def _is_ultra30(self): return re.match(r'.*Ultra-30', self.info['uname_i']) is not None def _is_ultra4(self): return re.match(r'.*Ultra-4', self.info['uname_i']) is not None def _is_ultra5_10(self): return re.match(r'.*Ultra-5_10', self.info['uname_i']) is not None def _is_ultra5(self): return re.match(r'.*Ultra-5', self.info['uname_i']) is not None def _is_ultra60(self): return re.match(r'.*Ultra-60', self.info['uname_i']) is not None def _is_ultra80(self): return re.match(r'.*Ultra-80', self.info['uname_i']) is not None def _is_ultraenterprice(self): return re.match(r'.*Ultra-Enterprise', self.info['uname_i']) is not None def _is_ultraenterprice10k(self): return re.match(r'.*Ultra-Enterprise-10000', self.info['uname_i']) is not None def _is_sunfire(self): return re.match(r'.*Sun-Fire', self.info['uname_i']) is not None def _is_ultra(self): return re.match(r'.*Ultra', self.info['uname_i']) is not None def _is_cpusparcv7(self): return self.info['processor']=='sparcv7' def _is_cpusparcv8(self): return self.info['processor']=='sparcv8' def _is_cpusparcv9(self): return self.info['processor']=='sparcv9' class Win32CPUInfo(CPUInfoBase): info = None pkey = r"HARDWARE\DESCRIPTION\System\CentralProcessor" # XXX: what does the value of # HKEY_LOCAL_MACHINE\HARDWARE\DESCRIPTION\System\CentralProcessor\0 # mean? def __init__(self): if self.info is not None: return info = [] try: #XXX: Bad style to use so long `try:...except:...`. Fix it! if sys.version_info[0] >= 3: import winreg else: import _winreg as winreg prgx = re.compile(r"family\s+(?P\d+)\s+model\s+(?P\d+)"\ "\s+stepping\s+(?P\d+)", re.IGNORECASE) chnd=winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, self.pkey) pnum=0 while True: try: proc=winreg.EnumKey(chnd, pnum) except winreg.error: break else: pnum+=1 info.append({"Processor":proc}) phnd=winreg.OpenKey(chnd, proc) pidx=0 while True: try: name, value, vtpe=winreg.EnumValue(phnd, pidx) except winreg.error: break else: pidx=pidx+1 info[-1][name]=value if name=="Identifier": srch=prgx.search(value) if srch: info[-1]["Family"]=int(srch.group("FML")) info[-1]["Model"]=int(srch.group("MDL")) info[-1]["Stepping"]=int(srch.group("STP")) except: print(sys.exc_info()[1], '(ignoring)') self.__class__.info = info def _not_impl(self): pass # Athlon def _is_AMD(self): return self.info[0]['VendorIdentifier']=='AuthenticAMD' def _is_Am486(self): return self.is_AMD() and self.info[0]['Family']==4 def _is_Am5x86(self): return self.is_AMD() and self.info[0]['Family']==4 def _is_AMDK5(self): return self.is_AMD() and self.info[0]['Family']==5 \ and self.info[0]['Model'] in [0, 1, 2, 3] def _is_AMDK6(self): return self.is_AMD() and self.info[0]['Family']==5 \ and self.info[0]['Model'] in [6, 7] def _is_AMDK6_2(self): return self.is_AMD() and self.info[0]['Family']==5 \ and self.info[0]['Model']==8 def _is_AMDK6_3(self): return self.is_AMD() and self.info[0]['Family']==5 \ and self.info[0]['Model']==9 def _is_AMDK7(self): return self.is_AMD() and self.info[0]['Family'] == 6 # To reliably distinguish between the different types of AMD64 chips # (Athlon64, Operton, Athlon64 X2, Semperon, Turion 64, etc.) would # require looking at the 'brand' from cpuid def _is_AMD64(self): return self.is_AMD() and self.info[0]['Family'] == 15 # Intel def _is_Intel(self): return self.info[0]['VendorIdentifier']=='GenuineIntel' def _is_i386(self): return self.info[0]['Family']==3 def _is_i486(self): return self.info[0]['Family']==4 def _is_i586(self): return self.is_Intel() and self.info[0]['Family']==5 def _is_i686(self): return self.is_Intel() and self.info[0]['Family']==6 def _is_Pentium(self): return self.is_Intel() and self.info[0]['Family']==5 def _is_PentiumMMX(self): return self.is_Intel() and self.info[0]['Family']==5 \ and self.info[0]['Model']==4 def _is_PentiumPro(self): return self.is_Intel() and self.info[0]['Family']==6 \ and self.info[0]['Model']==1 def _is_PentiumII(self): return self.is_Intel() and self.info[0]['Family']==6 \ and self.info[0]['Model'] in [3, 5, 6] def _is_PentiumIII(self): return self.is_Intel() and self.info[0]['Family']==6 \ and self.info[0]['Model'] in [7, 8, 9, 10, 11] def _is_PentiumIV(self): return self.is_Intel() and self.info[0]['Family']==15 def _is_PentiumM(self): return self.is_Intel() and self.info[0]['Family'] == 6 \ and self.info[0]['Model'] in [9, 13, 14] def _is_Core2(self): return self.is_Intel() and self.info[0]['Family'] == 6 \ and self.info[0]['Model'] in [15, 16, 17] # Varia def _is_singleCPU(self): return len(self.info) == 1 def _getNCPUs(self): return len(self.info) def _has_mmx(self): if self.is_Intel(): return (self.info[0]['Family']==5 and self.info[0]['Model']==4) \ or (self.info[0]['Family'] in [6, 15]) elif self.is_AMD(): return self.info[0]['Family'] in [5, 6, 15] else: return False def _has_sse(self): if self.is_Intel(): return (self.info[0]['Family']==6 and \ self.info[0]['Model'] in [7, 8, 9, 10, 11]) \ or self.info[0]['Family']==15 elif self.is_AMD(): return (self.info[0]['Family']==6 and \ self.info[0]['Model'] in [6, 7, 8, 10]) \ or self.info[0]['Family']==15 else: return False def _has_sse2(self): if self.is_Intel(): return self.is_Pentium4() or self.is_PentiumM() \ or self.is_Core2() elif self.is_AMD(): return self.is_AMD64() else: return False def _has_3dnow(self): return self.is_AMD() and self.info[0]['Family'] in [5, 6, 15] def _has_3dnowext(self): return self.is_AMD() and self.info[0]['Family'] in [6, 15] if sys.platform.startswith('linux'): # variations: linux2,linux-i386 (any others?) cpuinfo = LinuxCPUInfo elif sys.platform.startswith('irix'): cpuinfo = IRIXCPUInfo elif sys.platform == 'darwin': cpuinfo = DarwinCPUInfo elif sys.platform.startswith('sunos'): cpuinfo = SunOSCPUInfo elif sys.platform.startswith('win32'): cpuinfo = Win32CPUInfo elif sys.platform.startswith('cygwin'): cpuinfo = LinuxCPUInfo #XXX: other OS's. Eg. use _winreg on Win32. Or os.uname on unices. else: cpuinfo = CPUInfoBase cpu = cpuinfo() #if __name__ == "__main__": # # cpu.is_blaa() # cpu.is_Intel() # cpu.is_Alpha() # # print 'CPU information:', # for name in dir(cpuinfo): # if name[0]=='_' and name[1]!='_': # r = getattr(cpu,name[1:])() # if r: # if r!=1: # print '%s=%s' %(name[1:],r), # else: # print name[1:], # print numpy-1.8.2/numpy/distutils/tests/0000775000175100017510000000000012371375430020367 5ustar vagrantvagrant00000000000000numpy-1.8.2/numpy/distutils/tests/test_fcompiler_intel.py0000664000175100017510000000225112370216242025145 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function from numpy.testing import * import numpy.distutils.fcompiler intel_32bit_version_strings = [ ("Intel(R) Fortran Intel(R) 32-bit Compiler Professional for applications"\ "running on Intel(R) 32, Version 11.1", '11.1'), ] intel_64bit_version_strings = [ ("Intel(R) Fortran IA-64 Compiler Professional for applications"\ "running on IA-64, Version 11.0", '11.0'), ("Intel(R) Fortran Intel(R) 64 Compiler Professional for applications"\ "running on Intel(R) 64, Version 11.1", '11.1') ] class TestIntelFCompilerVersions(TestCase): def test_32bit_version(self): fc = numpy.distutils.fcompiler.new_fcompiler(compiler='intel') for vs, version in intel_32bit_version_strings: v = fc.version_match(vs) assert_(v == version) class TestIntelEM64TFCompilerVersions(TestCase): def test_64bit_version(self): fc = numpy.distutils.fcompiler.new_fcompiler(compiler='intelem') for vs, version in intel_64bit_version_strings: v = fc.version_match(vs) assert_(v == version) if __name__ == '__main__': run_module_suite() numpy-1.8.2/numpy/distutils/tests/f2py_f90_ext/0000775000175100017510000000000012371375430022605 5ustar vagrantvagrant00000000000000numpy-1.8.2/numpy/distutils/tests/f2py_f90_ext/src/0000775000175100017510000000000012371375430023374 5ustar vagrantvagrant00000000000000numpy-1.8.2/numpy/distutils/tests/f2py_f90_ext/src/foo_free.f900000664000175100017510000000010212370216242025463 0ustar vagrantvagrant00000000000000module foo_free contains include "body.f90" end module foo_free numpy-1.8.2/numpy/distutils/tests/f2py_f90_ext/setup.py0000664000175100017510000000126312370216242024313 0ustar vagrantvagrant00000000000000#!/usr/bin/env python from __future__ import division, print_function def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('f2py_f90_ext', parent_package, top_path) config.add_extension('foo', ['src/foo_free.f90'], include_dirs=['include'], f2py_options=['--include_paths', config.paths('include')[0]] ) config.add_data_dir('tests') return config if __name__ == "__main__": from numpy.distutils.core import setup setup(configuration=configuration) numpy-1.8.2/numpy/distutils/tests/f2py_f90_ext/include/0000775000175100017510000000000012371375430024230 5ustar vagrantvagrant00000000000000numpy-1.8.2/numpy/distutils/tests/f2py_f90_ext/include/body.f900000664000175100017510000000013612370216242025477 0ustar vagrantvagrant00000000000000 subroutine bar13(a) !f2py intent(out) a integer a a = 13 end subroutine bar13 numpy-1.8.2/numpy/distutils/tests/f2py_f90_ext/tests/0000775000175100017510000000000012371375430023747 5ustar vagrantvagrant00000000000000numpy-1.8.2/numpy/distutils/tests/f2py_f90_ext/tests/test_foo.py0000664000175100017510000000043712370216242026141 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function import sys from numpy.testing import * from f2py_f90_ext import foo class TestFoo(TestCase): def test_foo_free(self): assert_equal(foo.foo_free.bar13(), 13) if __name__ == "__main__": run_module_suite() numpy-1.8.2/numpy/distutils/tests/f2py_f90_ext/__init__.py0000664000175100017510000000010112370216242024700 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function numpy-1.8.2/numpy/distutils/tests/test_misc_util.py0000664000175100017510000000604012370216242023762 0ustar vagrantvagrant00000000000000#!/usr/bin/env python from __future__ import division, absolute_import, print_function from numpy.testing import * from numpy.distutils.misc_util import appendpath, minrelpath, \ gpaths, get_shared_lib_extension from os.path import join, sep, dirname ajoin = lambda *paths: join(*((sep,)+paths)) class TestAppendpath(TestCase): def test_1(self): assert_equal(appendpath('prefix', 'name'), join('prefix', 'name')) assert_equal(appendpath('/prefix', 'name'), ajoin('prefix', 'name')) assert_equal(appendpath('/prefix', '/name'), ajoin('prefix', 'name')) assert_equal(appendpath('prefix', '/name'), join('prefix', 'name')) def test_2(self): assert_equal(appendpath('prefix/sub', 'name'), join('prefix', 'sub', 'name')) assert_equal(appendpath('prefix/sub', 'sup/name'), join('prefix', 'sub', 'sup', 'name')) assert_equal(appendpath('/prefix/sub', '/prefix/name'), ajoin('prefix', 'sub', 'name')) def test_3(self): assert_equal(appendpath('/prefix/sub', '/prefix/sup/name'), ajoin('prefix', 'sub', 'sup', 'name')) assert_equal(appendpath('/prefix/sub/sub2', '/prefix/sup/sup2/name'), ajoin('prefix', 'sub', 'sub2', 'sup', 'sup2', 'name')) assert_equal(appendpath('/prefix/sub/sub2', '/prefix/sub/sup/name'), ajoin('prefix', 'sub', 'sub2', 'sup', 'name')) class TestMinrelpath(TestCase): def test_1(self): n = lambda path: path.replace('/', sep) assert_equal(minrelpath(n('aa/bb')), n('aa/bb')) assert_equal(minrelpath('..'), '..') assert_equal(minrelpath(n('aa/..')), '') assert_equal(minrelpath(n('aa/../bb')), 'bb') assert_equal(minrelpath(n('aa/bb/..')), 'aa') assert_equal(minrelpath(n('aa/bb/../..')), '') assert_equal(minrelpath(n('aa/bb/../cc/../dd')), n('aa/dd')) assert_equal(minrelpath(n('.././..')), n('../..')) assert_equal(minrelpath(n('aa/bb/.././../dd')), n('dd')) class TestGpaths(TestCase): def test_gpaths(self): local_path = minrelpath(join(dirname(__file__), '..')) ls = gpaths('command/*.py', local_path) assert_(join(local_path, 'command', 'build_src.py') in ls, repr(ls)) f = gpaths('system_info.py', local_path) assert_(join(local_path, 'system_info.py')==f[0], repr(f)) class TestSharedExtension(TestCase): def test_get_shared_lib_extension(self): import sys ext = get_shared_lib_extension(is_python_ext=False) if sys.platform.startswith('linux'): assert_equal(ext, '.so') elif sys.platform.startswith('gnukfreebsd'): assert_equal(ext, '.so') elif sys.platform.startswith('darwin'): assert_equal(ext, '.dylib') elif sys.platform.startswith('win'): assert_equal(ext, '.dll') # just check for no crash assert_(get_shared_lib_extension(is_python_ext=True)) if __name__ == "__main__": run_module_suite() numpy-1.8.2/numpy/distutils/tests/test_exec_command.py0000664000175100017510000000603112370216242024414 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function import os import sys from tempfile import TemporaryFile from numpy.distutils import exec_command # In python 3 stdout, stderr are text (unicode compliant) devices, so to # emulate them import StringIO from the io module. if sys.version_info[0] >= 3: from io import StringIO else: from StringIO import StringIO class redirect_stdout(object): """Context manager to redirect stdout for exec_command test.""" def __init__(self, stdout=None): self._stdout = stdout or sys.stdout def __enter__(self): self.old_stdout = sys.stdout sys.stdout = self._stdout def __exit__(self, exc_type, exc_value, traceback): self._stdout.flush() sys.stdout = self.old_stdout # note: closing sys.stdout won't close it. self._stdout.close() class redirect_stderr(object): """Context manager to redirect stderr for exec_command test.""" def __init__(self, stderr=None): self._stderr = stderr or sys.stderr def __enter__(self): self.old_stderr = sys.stderr sys.stderr = self._stderr def __exit__(self, exc_type, exc_value, traceback): self._stderr.flush() sys.stderr = self.old_stderr # note: closing sys.stderr won't close it. self._stderr.close() class emulate_nonposix(object): """Context manager to emulate os.name != 'posix' """ def __init__(self, osname='non-posix'): self._new_name = osname def __enter__(self): self._old_name = os.name os.name = self._new_name def __exit__(self, exc_type, exc_value, traceback): os.name = self._old_name def test_exec_command_stdout(): # Regression test for gh-2999 and gh-2915. # There are several packages (nose, scipy.weave.inline, Sage inline # Fortran) that replace stdout, in which case it doesn't have a fileno # method. This is tested here, with a do-nothing command that fails if the # presence of fileno() is assumed in exec_command. # The code has a special case for posix systems, so if we are on posix test # both that the special case works and that the generic code works. # Test posix version: with redirect_stdout(StringIO()): with redirect_stderr(TemporaryFile()): exec_command.exec_command("cd '.'") if os.name == 'posix': # Test general (non-posix) version: with emulate_nonposix(): with redirect_stdout(StringIO()): with redirect_stderr(TemporaryFile()): exec_command.exec_command("cd '.'") def test_exec_command_stderr(): # Test posix version: with redirect_stdout(TemporaryFile(mode='w+')): with redirect_stderr(StringIO()): exec_command.exec_command("cd '.'") if os.name == 'posix': # Test general (non-posix) version: with emulate_nonposix(): with redirect_stdout(TemporaryFile()): with redirect_stderr(StringIO()): exec_command.exec_command("cd '.'") numpy-1.8.2/numpy/distutils/tests/setup.py0000664000175100017510000000110112370216242022064 0ustar vagrantvagrant00000000000000#!/usr/bin/env python from __future__ import division, print_function def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('testnumpydistutils', parent_package, top_path) config.add_subpackage('pyrex_ext') config.add_subpackage('f2py_ext') #config.add_subpackage('f2py_f90_ext') config.add_subpackage('swig_ext') config.add_subpackage('gen_ext') return config if __name__ == "__main__": from numpy.distutils.core import setup setup(configuration=configuration) numpy-1.8.2/numpy/distutils/tests/test_fcompiler_gnu.py0000664000175100017510000000360612370216242024630 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function from numpy.testing import * import numpy.distutils.fcompiler g77_version_strings = [ ('GNU Fortran 0.5.25 20010319 (prerelease)', '0.5.25'), ('GNU Fortran (GCC 3.2) 3.2 20020814 (release)', '3.2'), ('GNU Fortran (GCC) 3.3.3 20040110 (prerelease) (Debian)', '3.3.3'), ('GNU Fortran (GCC) 3.3.3 (Debian 20040401)', '3.3.3'), ('GNU Fortran (GCC 3.2.2 20030222 (Red Hat Linux 3.2.2-5)) 3.2.2' ' 20030222 (Red Hat Linux 3.2.2-5)', '3.2.2'), ] gfortran_version_strings = [ ('GNU Fortran 95 (GCC 4.0.3 20051023 (prerelease) (Debian 4.0.2-3))', '4.0.3'), ('GNU Fortran 95 (GCC) 4.1.0', '4.1.0'), ('GNU Fortran 95 (GCC) 4.2.0 20060218 (experimental)', '4.2.0'), ('GNU Fortran (GCC) 4.3.0 20070316 (experimental)', '4.3.0'), ('GNU Fortran (rubenvb-4.8.0) 4.8.0', '4.8.0'), ] class TestG77Versions(TestCase): def test_g77_version(self): fc = numpy.distutils.fcompiler.new_fcompiler(compiler='gnu') for vs, version in g77_version_strings: v = fc.version_match(vs) assert_(v == version, (vs, v)) def test_not_g77(self): fc = numpy.distutils.fcompiler.new_fcompiler(compiler='gnu') for vs, _ in gfortran_version_strings: v = fc.version_match(vs) assert_(v is None, (vs, v)) class TestGortranVersions(TestCase): def test_gfortran_version(self): fc = numpy.distutils.fcompiler.new_fcompiler(compiler='gnu95') for vs, version in gfortran_version_strings: v = fc.version_match(vs) assert_(v == version, (vs, v)) def test_not_gfortran(self): fc = numpy.distutils.fcompiler.new_fcompiler(compiler='gnu95') for vs, _ in g77_version_strings: v = fc.version_match(vs) assert_(v is None, (vs, v)) if __name__ == '__main__': run_module_suite() numpy-1.8.2/numpy/distutils/tests/swig_ext/0000775000175100017510000000000012371375430022220 5ustar vagrantvagrant00000000000000numpy-1.8.2/numpy/distutils/tests/swig_ext/src/0000775000175100017510000000000012371375430023007 5ustar vagrantvagrant00000000000000numpy-1.8.2/numpy/distutils/tests/swig_ext/src/zoo.cc0000664000175100017510000000041412370216242024116 0ustar vagrantvagrant00000000000000#include "zoo.h" #include #include Zoo::Zoo() { n = 0; } void Zoo::shut_up(char *animal) { if (n < 10) { strcpy(animals[n], animal); n++; } } void Zoo::display() { int i; for(i = 0; i < n; i++) printf("%s\n", animals[i]); } numpy-1.8.2/numpy/distutils/tests/swig_ext/src/zoo.h0000664000175100017510000000016112370216242023757 0ustar vagrantvagrant00000000000000 class Zoo{ int n; char animals[10][50]; public: Zoo(); void shut_up(char *animal); void display(); }; numpy-1.8.2/numpy/distutils/tests/swig_ext/src/example.i0000664000175100017510000000043512370216242024610 0ustar vagrantvagrant00000000000000/* -*- c -*- */ /* File : example.i */ %module example %{ /* Put headers and other declarations here */ extern double My_variable; extern int fact(int); extern int my_mod(int n, int m); %} extern double My_variable; extern int fact(int); extern int my_mod(int n, int m); numpy-1.8.2/numpy/distutils/tests/swig_ext/src/example.c0000664000175100017510000000034312370216242024600 0ustar vagrantvagrant00000000000000/* File : example.c */ double My_variable = 3.0; /* Compute factorial of n */ int fact(int n) { if (n <= 1) return 1; else return n*fact(n-1); } /* Compute n mod m */ int my_mod(int n, int m) { return(n % m); } numpy-1.8.2/numpy/distutils/tests/swig_ext/src/zoo.i0000664000175100017510000000021712370216242023762 0ustar vagrantvagrant00000000000000// -*- c++ -*- // Example copied from http://linuxgazette.net/issue49/pramode.html %module example2 %{ #include "zoo.h" %} %include "zoo.h" numpy-1.8.2/numpy/distutils/tests/swig_ext/setup.py0000664000175100017510000000134612370216242023730 0ustar vagrantvagrant00000000000000#!/usr/bin/env python from __future__ import division, print_function def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('swig_ext', parent_package, top_path) config.add_extension('_example', ['src/example.i', 'src/example.c'] ) config.add_extension('_example2', ['src/zoo.i', 'src/zoo.cc'], depends=['src/zoo.h'], include_dirs=['src'] ) config.add_data_dir('tests') return config if __name__ == "__main__": from numpy.distutils.core import setup setup(configuration=configuration) numpy-1.8.2/numpy/distutils/tests/swig_ext/tests/0000775000175100017510000000000012371375430023362 5ustar vagrantvagrant00000000000000numpy-1.8.2/numpy/distutils/tests/swig_ext/tests/test_example.py0000664000175100017510000000071012370216242026416 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function import sys from numpy.testing import * from swig_ext import example class TestExample(TestCase): def test_fact(self): assert_equal(example.fact(10), 3628800) def test_cvar(self): assert_equal(example.cvar.My_variable, 3.0) example.cvar.My_variable = 5 assert_equal(example.cvar.My_variable, 5.0) if __name__ == "__main__": run_module_suite() numpy-1.8.2/numpy/distutils/tests/swig_ext/tests/test_example2.py0000664000175100017510000000052612370216242026505 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function import sys from numpy.testing import * from swig_ext import example2 class TestExample2(TestCase): def test_zoo(self): z = example2.Zoo() z.shut_up('Tiger') z.shut_up('Lion') z.display() if __name__ == "__main__": run_module_suite() numpy-1.8.2/numpy/distutils/tests/swig_ext/__init__.py0000664000175100017510000000010112370216242024313 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function numpy-1.8.2/numpy/distutils/tests/test_npy_pkg_config.py0000664000175100017510000000577512370216242025004 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function import os from tempfile import mkstemp from numpy.testing import * from numpy.distutils.npy_pkg_config import read_config, parse_flags simple = """\ [meta] Name = foo Description = foo lib Version = 0.1 [default] cflags = -I/usr/include libs = -L/usr/lib """ simple_d = {'cflags': '-I/usr/include', 'libflags': '-L/usr/lib', 'version': '0.1', 'name': 'foo'} simple_variable = """\ [meta] Name = foo Description = foo lib Version = 0.1 [variables] prefix = /foo/bar libdir = ${prefix}/lib includedir = ${prefix}/include [default] cflags = -I${includedir} libs = -L${libdir} """ simple_variable_d = {'cflags': '-I/foo/bar/include', 'libflags': '-L/foo/bar/lib', 'version': '0.1', 'name': 'foo'} class TestLibraryInfo(TestCase): def test_simple(self): fd, filename = mkstemp('foo.ini') try: pkg = os.path.splitext(filename)[0] try: os.write(fd, simple.encode('ascii')) finally: os.close(fd) out = read_config(pkg) self.assertTrue(out.cflags() == simple_d['cflags']) self.assertTrue(out.libs() == simple_d['libflags']) self.assertTrue(out.name == simple_d['name']) self.assertTrue(out.version == simple_d['version']) finally: os.remove(filename) def test_simple_variable(self): fd, filename = mkstemp('foo.ini') try: pkg = os.path.splitext(filename)[0] try: os.write(fd, simple_variable.encode('ascii')) finally: os.close(fd) out = read_config(pkg) self.assertTrue(out.cflags() == simple_variable_d['cflags']) self.assertTrue(out.libs() == simple_variable_d['libflags']) self.assertTrue(out.name == simple_variable_d['name']) self.assertTrue(out.version == simple_variable_d['version']) out.vars['prefix'] = '/Users/david' self.assertTrue(out.cflags() == '-I/Users/david/include') finally: os.remove(filename) class TestParseFlags(TestCase): def test_simple_cflags(self): d = parse_flags("-I/usr/include") self.assertTrue(d['include_dirs'] == ['/usr/include']) d = parse_flags("-I/usr/include -DFOO") self.assertTrue(d['include_dirs'] == ['/usr/include']) self.assertTrue(d['macros'] == ['FOO']) d = parse_flags("-I /usr/include -DFOO") self.assertTrue(d['include_dirs'] == ['/usr/include']) self.assertTrue(d['macros'] == ['FOO']) def test_simple_lflags(self): d = parse_flags("-L/usr/lib -lfoo -L/usr/lib -lbar") self.assertTrue(d['library_dirs'] == ['/usr/lib', '/usr/lib']) self.assertTrue(d['libraries'] == ['foo', 'bar']) d = parse_flags("-L /usr/lib -lfoo -L/usr/lib -lbar") self.assertTrue(d['library_dirs'] == ['/usr/lib', '/usr/lib']) self.assertTrue(d['libraries'] == ['foo', 'bar']) numpy-1.8.2/numpy/distutils/tests/pyrex_ext/0000775000175100017510000000000012371375430022416 5ustar vagrantvagrant00000000000000numpy-1.8.2/numpy/distutils/tests/pyrex_ext/primes.pyx0000664000175100017510000000051612370216242024453 0ustar vagrantvagrant00000000000000# # Calculate prime numbers # def primes(int kmax): cdef int n, k, i cdef int p[1000] result = [] if kmax > 1000: kmax = 1000 k = 0 n = 2 while k < kmax: i = 0 while i < k and n % p[i] <> 0: i = i + 1 if i == k: p[k] = n k = k + 1 result.append(n) n = n + 1 return result numpy-1.8.2/numpy/distutils/tests/pyrex_ext/setup.py0000664000175100017510000000074212370216242024125 0ustar vagrantvagrant00000000000000#!/usr/bin/env python from __future__ import division, print_function def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('pyrex_ext', parent_package, top_path) config.add_extension('primes', ['primes.pyx']) config.add_data_dir('tests') return config if __name__ == "__main__": from numpy.distutils.core import setup setup(configuration=configuration) numpy-1.8.2/numpy/distutils/tests/pyrex_ext/tests/0000775000175100017510000000000012371375430023560 5ustar vagrantvagrant00000000000000numpy-1.8.2/numpy/distutils/tests/pyrex_ext/tests/test_primes.py0000664000175100017510000000052712370216242026466 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function import sys from numpy.testing import * from pyrex_ext.primes import primes class TestPrimes(TestCase): def test_simple(self, level=1): l = primes(10) assert_equal(l, [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]) if __name__ == "__main__": run_module_suite() numpy-1.8.2/numpy/distutils/tests/pyrex_ext/__init__.py0000664000175100017510000000010112370216242024511 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function numpy-1.8.2/numpy/distutils/tests/gen_ext/0000775000175100017510000000000012371375430022020 5ustar vagrantvagrant00000000000000numpy-1.8.2/numpy/distutils/tests/gen_ext/setup.py0000664000175100017510000000217712370216242023533 0ustar vagrantvagrant00000000000000#!/usr/bin/env python from __future__ import division, print_function fib3_f = ''' C FILE: FIB3.F SUBROUTINE FIB(A,N) C C CALCULATE FIRST N FIBONACCI NUMBERS C INTEGER N REAL*8 A(N) Cf2py intent(in) n Cf2py intent(out) a Cf2py depend(n) a DO I=1,N IF (I.EQ.1) THEN A(I) = 0.0D0 ELSEIF (I.EQ.2) THEN A(I) = 1.0D0 ELSE A(I) = A(I-1) + A(I-2) ENDIF ENDDO END C END FILE FIB3.F ''' def source_func(ext, build_dir): import os from distutils.dep_util import newer target = os.path.join(build_dir, 'fib3.f') if newer(__file__, target): f = open(target, 'w') f.write(fib3_f) f.close() return [target] def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('gen_ext', parent_package, top_path) config.add_extension('fib3', [source_func] ) return config if __name__ == "__main__": from numpy.distutils.core import setup setup(configuration=configuration) numpy-1.8.2/numpy/distutils/tests/gen_ext/tests/0000775000175100017510000000000012371375430023162 5ustar vagrantvagrant00000000000000numpy-1.8.2/numpy/distutils/tests/gen_ext/tests/test_fib3.py0000664000175100017510000000044412370216242025412 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function import sys from numpy.testing import * from gen_ext import fib3 class TestFib3(TestCase): def test_fib(self): assert_array_equal(fib3.fib(6), [0, 1, 1, 2, 3, 5]) if __name__ == "__main__": run_module_suite() numpy-1.8.2/numpy/distutils/tests/gen_ext/__init__.py0000664000175100017510000000010112370216242024113 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function numpy-1.8.2/numpy/distutils/tests/f2py_ext/0000775000175100017510000000000012371375430022127 5ustar vagrantvagrant00000000000000numpy-1.8.2/numpy/distutils/tests/f2py_ext/src/0000775000175100017510000000000012371375430022716 5ustar vagrantvagrant00000000000000numpy-1.8.2/numpy/distutils/tests/f2py_ext/src/fib2.pyf0000664000175100017510000000036212370216242024253 0ustar vagrantvagrant00000000000000! -*- f90 -*- python module fib2 interface subroutine fib(a,n) real*8 dimension(n),intent(out),depend(n) :: a integer intent(in) :: n end subroutine fib end interface end python module fib2 numpy-1.8.2/numpy/distutils/tests/f2py_ext/src/fib1.f0000664000175100017510000000053312370216242023701 0ustar vagrantvagrant00000000000000C FILE: FIB1.F SUBROUTINE FIB(A,N) C C CALCULATE FIRST N FIBONACCI NUMBERS C INTEGER N REAL*8 A(N) DO I=1,N IF (I.EQ.1) THEN A(I) = 0.0D0 ELSEIF (I.EQ.2) THEN A(I) = 1.0D0 ELSE A(I) = A(I-1) + A(I-2) ENDIF ENDDO END C END FILE FIB1.F numpy-1.8.2/numpy/distutils/tests/f2py_ext/setup.py0000664000175100017510000000072612370216242023640 0ustar vagrantvagrant00000000000000#!/usr/bin/env python from __future__ import division, print_function def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('f2py_ext', parent_package, top_path) config.add_extension('fib2', ['src/fib2.pyf', 'src/fib1.f']) config.add_data_dir('tests') return config if __name__ == "__main__": from numpy.distutils.core import setup setup(configuration=configuration) numpy-1.8.2/numpy/distutils/tests/f2py_ext/tests/0000775000175100017510000000000012371375430023271 5ustar vagrantvagrant00000000000000numpy-1.8.2/numpy/distutils/tests/f2py_ext/tests/test_fib2.py0000664000175100017510000000044612370216242025522 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function import sys from numpy.testing import * from f2py_ext import fib2 class TestFib2(TestCase): def test_fib(self): assert_array_equal(fib2.fib(6), [0, 1, 1, 2, 3, 5]) if __name__ == "__main__": run_module_suite() numpy-1.8.2/numpy/distutils/tests/f2py_ext/__init__.py0000664000175100017510000000010112370216242024222 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function numpy-1.8.2/numpy/distutils/environment.py0000664000175100017510000000445212370216242022142 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function import os from distutils.dist import Distribution __metaclass__ = type class EnvironmentConfig(object): def __init__(self, distutils_section='ALL', **kw): self._distutils_section = distutils_section self._conf_keys = kw self._conf = None self._hook_handler = None def dump_variable(self, name): conf_desc = self._conf_keys[name] hook, envvar, confvar, convert = conf_desc if not convert: convert = lambda x : x print('%s.%s:' % (self._distutils_section, name)) v = self._hook_handler(name, hook) print(' hook : %s' % (convert(v),)) if envvar: v = os.environ.get(envvar, None) print(' environ: %s' % (convert(v),)) if confvar and self._conf: v = self._conf.get(confvar, (None, None))[1] print(' config : %s' % (convert(v),)) def dump_variables(self): for name in self._conf_keys: self.dump_variable(name) def __getattr__(self, name): try: conf_desc = self._conf_keys[name] except KeyError: raise AttributeError(name) return self._get_var(name, conf_desc) def get(self, name, default=None): try: conf_desc = self._conf_keys[name] except KeyError: return default var = self._get_var(name, conf_desc) if var is None: var = default return var def _get_var(self, name, conf_desc): hook, envvar, confvar, convert = conf_desc var = self._hook_handler(name, hook) if envvar is not None: var = os.environ.get(envvar, var) if confvar is not None and self._conf: var = self._conf.get(confvar, (None, var))[1] if convert is not None: var = convert(var) return var def clone(self, hook_handler): ec = self.__class__(distutils_section=self._distutils_section, **self._conf_keys) ec._hook_handler = hook_handler return ec def use_distribution(self, dist): if isinstance(dist, Distribution): self._conf = dist.get_option_dict(self._distutils_section) else: self._conf = dist numpy-1.8.2/numpy/distutils/line_endings.py0000664000175100017510000000400512370216242022226 0ustar vagrantvagrant00000000000000""" Functions for converting from DOS to UNIX line endings """ from __future__ import division, absolute_import, print_function import sys, re, os def dos2unix(file): "Replace CRLF with LF in argument files. Print names of changed files." if os.path.isdir(file): print(file, "Directory!") return data = open(file, "rb").read() if '\0' in data: print(file, "Binary!") return newdata = re.sub("\r\n", "\n", data) if newdata != data: print('dos2unix:', file) f = open(file, "wb") f.write(newdata) f.close() return file else: print(file, 'ok') def dos2unix_one_dir(modified_files, dir_name, file_names): for file in file_names: full_path = os.path.join(dir_name, file) file = dos2unix(full_path) if file is not None: modified_files.append(file) def dos2unix_dir(dir_name): modified_files = [] os.path.walk(dir_name, dos2unix_one_dir, modified_files) return modified_files #---------------------------------- def unix2dos(file): "Replace LF with CRLF in argument files. Print names of changed files." if os.path.isdir(file): print(file, "Directory!") return data = open(file, "rb").read() if '\0' in data: print(file, "Binary!") return newdata = re.sub("\r\n", "\n", data) newdata = re.sub("\n", "\r\n", newdata) if newdata != data: print('unix2dos:', file) f = open(file, "wb") f.write(newdata) f.close() return file else: print(file, 'ok') def unix2dos_one_dir(modified_files, dir_name, file_names): for file in file_names: full_path = os.path.join(dir_name, file) unix2dos(full_path) if file is not None: modified_files.append(file) def unix2dos_dir(dir_name): modified_files = [] os.path.walk(dir_name, unix2dos_one_dir, modified_files) return modified_files if __name__ == "__main__": dos2unix_dir(sys.argv[1]) numpy-1.8.2/numpy/distutils/__init__.py0000664000175100017510000000206212370216242021330 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function import sys if sys.version_info[0] < 3: from .__version__ import version as __version__ # Must import local ccompiler ASAP in order to get # customized CCompiler.spawn effective. from . import ccompiler from . import unixccompiler from .info import __doc__ from .npy_pkg_config import * try: import __config__ _INSTALLED = True except ImportError: _INSTALLED = False else: from numpy.distutils.__version__ import version as __version__ # Must import local ccompiler ASAP in order to get # customized CCompiler.spawn effective. import numpy.distutils.ccompiler import numpy.distutils.unixccompiler from numpy.distutils.info import __doc__ from numpy.distutils.npy_pkg_config import * try: import numpy.distutils.__config__ _INSTALLED = True except ImportError: _INSTALLED = False if _INSTALLED: from numpy.testing import Tester test = Tester().test bench = Tester().bench numpy-1.8.2/numpy/distutils/lib2def.py0000664000175100017510000000663712370216242021114 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function import re import sys import os import subprocess __doc__ = """This module generates a DEF file from the symbols in an MSVC-compiled DLL import library. It correctly discriminates between data and functions. The data is collected from the output of the program nm(1). Usage: python lib2def.py [libname.lib] [output.def] or python lib2def.py [libname.lib] > output.def libname.lib defaults to python.lib and output.def defaults to stdout Author: Robert Kern Last Update: April 30, 1999 """ __version__ = '0.1a' py_ver = "%d%d" % tuple(sys.version_info[:2]) DEFAULT_NM = 'nm -Cs' DEF_HEADER = """LIBRARY python%s.dll ;CODE PRELOAD MOVEABLE DISCARDABLE ;DATA PRELOAD SINGLE EXPORTS """ % py_ver # the header of the DEF file FUNC_RE = re.compile(r"^(.*) in python%s\.dll" % py_ver, re.MULTILINE) DATA_RE = re.compile(r"^_imp__(.*) in python%s\.dll" % py_ver, re.MULTILINE) def parse_cmd(): """Parses the command-line arguments. libfile, deffile = parse_cmd()""" if len(sys.argv) == 3: if sys.argv[1][-4:] == '.lib' and sys.argv[2][-4:] == '.def': libfile, deffile = sys.argv[1:] elif sys.argv[1][-4:] == '.def' and sys.argv[2][-4:] == '.lib': deffile, libfile = sys.argv[1:] else: print("I'm assuming that your first argument is the library") print("and the second is the DEF file.") elif len(sys.argv) == 2: if sys.argv[1][-4:] == '.def': deffile = sys.argv[1] libfile = 'python%s.lib' % py_ver elif sys.argv[1][-4:] == '.lib': deffile = None libfile = sys.argv[1] else: libfile = 'python%s.lib' % py_ver deffile = None return libfile, deffile def getnm(nm_cmd = ['nm', '-Cs', 'python%s.lib' % py_ver]): """Returns the output of nm_cmd via a pipe. nm_output = getnam(nm_cmd = 'nm -Cs py_lib')""" f = subprocess.Popen(nm_cmd, shell=True, stdout=subprocess.PIPE) nm_output = f.stdout.read() f.stdout.close() return nm_output def parse_nm(nm_output): """Returns a tuple of lists: dlist for the list of data symbols and flist for the list of function symbols. dlist, flist = parse_nm(nm_output)""" data = DATA_RE.findall(nm_output) func = FUNC_RE.findall(nm_output) flist = [] for sym in data: if sym in func and (sym[:2] == 'Py' or sym[:3] == '_Py' or sym[:4] == 'init'): flist.append(sym) dlist = [] for sym in data: if sym not in flist and (sym[:2] == 'Py' or sym[:3] == '_Py'): dlist.append(sym) dlist.sort() flist.sort() return dlist, flist def output_def(dlist, flist, header, file = sys.stdout): """Outputs the final DEF file to a file defaulting to stdout. output_def(dlist, flist, header, file = sys.stdout)""" for data_sym in dlist: header = header + '\t%s DATA\n' % data_sym header = header + '\n' # blank line for func_sym in flist: header = header + '\t%s\n' % func_sym file.write(header) if __name__ == '__main__': libfile, deffile = parse_cmd() if deffile is None: deffile = sys.stdout else: deffile = open(deffile, 'w') nm_cmd = [str(DEFAULT_NM), str(libfile)] nm_output = getnm(nm_cmd) dlist, flist = parse_nm(nm_output) output_def(dlist, flist, DEF_HEADER, deffile) numpy-1.8.2/numpy/distutils/core.py0000664000175100017510000001742312370216242020530 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function import sys from distutils.core import * if 'setuptools' in sys.modules: have_setuptools = True from setuptools import setup as old_setup # easy_install imports math, it may be picked up from cwd from setuptools.command import easy_install try: # very old versions of setuptools don't have this from setuptools.command import bdist_egg except ImportError: have_setuptools = False else: from distutils.core import setup as old_setup have_setuptools = False import warnings import distutils.core import distutils.dist from numpy.distutils.extension import Extension from numpy.distutils.numpy_distribution import NumpyDistribution from numpy.distutils.command import config, config_compiler, \ build, build_py, build_ext, build_clib, build_src, build_scripts, \ sdist, install_data, install_headers, install, bdist_rpm, \ install_clib from numpy.distutils.misc_util import get_data_files, is_sequence, is_string numpy_cmdclass = {'build': build.build, 'build_src': build_src.build_src, 'build_scripts': build_scripts.build_scripts, 'config_cc': config_compiler.config_cc, 'config_fc': config_compiler.config_fc, 'config': config.config, 'build_ext': build_ext.build_ext, 'build_py': build_py.build_py, 'build_clib': build_clib.build_clib, 'sdist': sdist.sdist, 'install_data': install_data.install_data, 'install_headers': install_headers.install_headers, 'install_clib': install_clib.install_clib, 'install': install.install, 'bdist_rpm': bdist_rpm.bdist_rpm, } if have_setuptools: # Use our own versions of develop and egg_info to ensure that build_src is # handled appropriately. from numpy.distutils.command import develop, egg_info numpy_cmdclass['bdist_egg'] = bdist_egg.bdist_egg numpy_cmdclass['develop'] = develop.develop numpy_cmdclass['easy_install'] = easy_install.easy_install numpy_cmdclass['egg_info'] = egg_info.egg_info def _dict_append(d, **kws): for k, v in kws.items(): if k not in d: d[k] = v continue dv = d[k] if isinstance(dv, tuple): d[k] = dv + tuple(v) elif isinstance(dv, list): d[k] = dv + list(v) elif isinstance(dv, dict): _dict_append(dv, **v) elif is_string(dv): d[k] = dv + v else: raise TypeError(repr(type(dv))) def _command_line_ok(_cache=[]): """ Return True if command line does not contain any help or display requests. """ if _cache: return _cache[0] ok = True display_opts = ['--'+n for n in Distribution.display_option_names] for o in Distribution.display_options: if o[1]: display_opts.append('-'+o[1]) for arg in sys.argv: if arg.startswith('--help') or arg=='-h' or arg in display_opts: ok = False break _cache.append(ok) return ok def get_distribution(always=False): dist = distutils.core._setup_distribution # XXX Hack to get numpy installable with easy_install. # The problem is easy_install runs it's own setup(), which # sets up distutils.core._setup_distribution. However, # when our setup() runs, that gets overwritten and lost. # We can't use isinstance, as the DistributionWithoutHelpCommands # class is local to a function in setuptools.command.easy_install if dist is not None and \ 'DistributionWithoutHelpCommands' in repr(dist): dist = None if always and dist is None: dist = NumpyDistribution() return dist def setup(**attr): cmdclass = numpy_cmdclass.copy() new_attr = attr.copy() if 'cmdclass' in new_attr: cmdclass.update(new_attr['cmdclass']) new_attr['cmdclass'] = cmdclass if 'configuration' in new_attr: # To avoid calling configuration if there are any errors # or help request in command in the line. configuration = new_attr.pop('configuration') old_dist = distutils.core._setup_distribution old_stop = distutils.core._setup_stop_after distutils.core._setup_distribution = None distutils.core._setup_stop_after = "commandline" try: dist = setup(**new_attr) finally: distutils.core._setup_distribution = old_dist distutils.core._setup_stop_after = old_stop if dist.help or not _command_line_ok(): # probably displayed help, skip running any commands return dist # create setup dictionary and append to new_attr config = configuration() if hasattr(config, 'todict'): config = config.todict() _dict_append(new_attr, **config) # Move extension source libraries to libraries libraries = [] for ext in new_attr.get('ext_modules', []): new_libraries = [] for item in ext.libraries: if is_sequence(item): lib_name, build_info = item _check_append_ext_library(libraries, lib_name, build_info) new_libraries.append(lib_name) elif is_string(item): new_libraries.append(item) else: raise TypeError("invalid description of extension module " "library %r" % (item,)) ext.libraries = new_libraries if libraries: if 'libraries' not in new_attr: new_attr['libraries'] = [] for item in libraries: _check_append_library(new_attr['libraries'], item) # sources in ext_modules or libraries may contain header files if ('ext_modules' in new_attr or 'libraries' in new_attr) \ and 'headers' not in new_attr: new_attr['headers'] = [] # Use our custom NumpyDistribution class instead of distutils' one new_attr['distclass'] = NumpyDistribution return old_setup(**new_attr) def _check_append_library(libraries, item): for libitem in libraries: if is_sequence(libitem): if is_sequence(item): if item[0]==libitem[0]: if item[1] is libitem[1]: return warnings.warn("[0] libraries list contains %r with" " different build_info" % (item[0],)) break else: if item==libitem[0]: warnings.warn("[1] libraries list contains %r with" " no build_info" % (item[0],)) break else: if is_sequence(item): if item[0]==libitem: warnings.warn("[2] libraries list contains %r with" " no build_info" % (item[0],)) break else: if item==libitem: return libraries.append(item) def _check_append_ext_library(libraries, lib_name, build_info): for item in libraries: if is_sequence(item): if item[0]==lib_name: if item[1] is build_info: return warnings.warn("[3] libraries list contains %r with" " different build_info" % (lib_name,)) break elif item==lib_name: warnings.warn("[4] libraries list contains %r with" " no build_info" % (lib_name,)) break libraries.append((lib_name, build_info)) numpy-1.8.2/numpy/distutils/system_info.py0000664000175100017510000022553112370216243022141 0ustar vagrantvagrant00000000000000#!/bin/env python """ This file defines a set of system_info classes for getting information about various resources (libraries, library directories, include directories, etc.) in the system. Currently, the following classes are available: atlas_info atlas_threads_info atlas_blas_info atlas_blas_threads_info lapack_atlas_info blas_info lapack_info openblas_info blas_opt_info # usage recommended lapack_opt_info # usage recommended fftw_info,dfftw_info,sfftw_info fftw_threads_info,dfftw_threads_info,sfftw_threads_info djbfft_info x11_info lapack_src_info blas_src_info numpy_info numarray_info numpy_info boost_python_info agg2_info wx_info gdk_pixbuf_xlib_2_info gdk_pixbuf_2_info gdk_x11_2_info gtkp_x11_2_info gtkp_2_info xft_info freetype2_info umfpack_info Usage: info_dict = get_info() where is a string 'atlas','x11','fftw','lapack','blas', 'lapack_src', 'blas_src', etc. For a complete list of allowed names, see the definition of get_info() function below. Returned info_dict is a dictionary which is compatible with distutils.setup keyword arguments. If info_dict == {}, then the asked resource is not available (system_info could not find it). Several *_info classes specify an environment variable to specify the locations of software. When setting the corresponding environment variable to 'None' then the software will be ignored, even when it is available in system. Global parameters: system_info.search_static_first - search static libraries (.a) in precedence to shared ones (.so, .sl) if enabled. system_info.verbosity - output the results to stdout if enabled. The file 'site.cfg' is looked for in 1) Directory of main setup.py file being run. 2) Home directory of user running the setup.py file as ~/.numpy-site.cfg 3) System wide directory (location of this file...) The first one found is used to get system configuration options The format is that used by ConfigParser (i.e., Windows .INI style). The section ALL has options that are the default for each section. The available sections are fftw, atlas, and x11. Appropiate defaults are used if nothing is specified. The order of finding the locations of resources is the following: 1. environment variable 2. section in site.cfg 3. ALL section in site.cfg Only the first complete match is returned. Example: ---------- [ALL] library_dirs = /usr/lib:/usr/local/lib:/opt/lib include_dirs = /usr/include:/usr/local/include:/opt/include src_dirs = /usr/local/src:/opt/src # search static libraries (.a) in preference to shared ones (.so) search_static_first = 0 [fftw] fftw_libs = rfftw, fftw fftw_opt_libs = rfftw_threaded, fftw_threaded # if the above aren't found, look for {s,d}fftw_libs and {s,d}fftw_opt_libs [atlas] library_dirs = /usr/lib/3dnow:/usr/lib/3dnow/atlas # for overriding the names of the atlas libraries atlas_libs = lapack, f77blas, cblas, atlas [x11] library_dirs = /usr/X11R6/lib include_dirs = /usr/X11R6/include ---------- Authors: Pearu Peterson , February 2002 David M. Cooke , April 2002 Copyright 2002 Pearu Peterson all rights reserved, Pearu Peterson Permission to use, modify, and distribute this software is given under the terms of the NumPy (BSD style) license. See LICENSE.txt that came with this distribution for specifics. NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. """ from __future__ import division, absolute_import, print_function import sys import os import re import copy import warnings from glob import glob from functools import reduce if sys.version_info[0] < 3: from ConfigParser import NoOptionError, ConfigParser else: from configparser import NoOptionError, ConfigParser from distutils.errors import DistutilsError from distutils.dist import Distribution import distutils.sysconfig from distutils import log from distutils.util import get_platform from numpy.distutils.exec_command import \ find_executable, exec_command, get_pythonexe from numpy.distutils.misc_util import is_sequence, is_string, \ get_shared_lib_extension from numpy.distutils.command.config import config as cmd_config from numpy.distutils.compat import get_exception # Determine number of bits import platform _bits = {'32bit': 32, '64bit': 64} platform_bits = _bits[platform.architecture()[0]] def libpaths(paths, bits): """Return a list of library paths valid on 32 or 64 bit systems. Inputs: paths : sequence A sequence of strings (typically paths) bits : int An integer, the only valid values are 32 or 64. A ValueError exception is raised otherwise. Examples: Consider a list of directories >>> paths = ['/usr/X11R6/lib','/usr/X11/lib','/usr/lib'] For a 32-bit platform, this is already valid: >>> np.distutils.system_info.libpaths(paths,32) ['/usr/X11R6/lib', '/usr/X11/lib', '/usr/lib'] On 64 bits, we prepend the '64' postfix >>> np.distutils.system_info.libpaths(paths,64) ['/usr/X11R6/lib64', '/usr/X11R6/lib', '/usr/X11/lib64', '/usr/X11/lib', '/usr/lib64', '/usr/lib'] """ if bits not in (32, 64): raise ValueError("Invalid bit size in libpaths: 32 or 64 only") # Handle 32bit case if bits == 32: return paths # Handle 64bit case out = [] for p in paths: out.extend([p + '64', p]) return out if sys.platform == 'win32': default_lib_dirs = ['C:\\', os.path.join(distutils.sysconfig.EXEC_PREFIX, 'libs')] default_include_dirs = [] default_src_dirs = ['.'] default_x11_lib_dirs = [] default_x11_include_dirs = [] else: default_lib_dirs = libpaths(['/usr/local/lib', '/opt/lib', '/usr/lib', '/opt/local/lib', '/sw/lib'], platform_bits) default_include_dirs = ['/usr/local/include', '/opt/include', '/usr/include', # path of umfpack under macports '/opt/local/include/ufsparse', '/opt/local/include', '/sw/include', '/usr/include/suitesparse'] default_src_dirs = ['.', '/usr/local/src', '/opt/src', '/sw/src'] default_x11_lib_dirs = libpaths(['/usr/X11R6/lib', '/usr/X11/lib', '/usr/lib'], platform_bits) default_x11_include_dirs = ['/usr/X11R6/include', '/usr/X11/include', '/usr/include'] if os.path.exists('/usr/lib/X11'): globbed_x11_dir = glob('/usr/lib/*/libX11.so') if globbed_x11_dir: x11_so_dir = os.path.split(globbed_x11_dir[0])[0] default_x11_lib_dirs.extend([x11_so_dir, '/usr/lib/X11']) default_x11_include_dirs.extend(['/usr/lib/X11/include', '/usr/include/X11']) import subprocess as sp tmp = None try: # Explicitly open/close file to avoid ResourceWarning when # tests are run in debug mode Python 3. tmp = open(os.devnull, 'w') p = sp.Popen(["gcc", "-print-multiarch"], stdout=sp.PIPE, stderr=tmp) except (OSError, DistutilsError): # OSError if gcc is not installed, or SandboxViolation (DistutilsError # subclass) if an old setuptools bug is triggered (see gh-3160). pass else: triplet = str(p.communicate()[0].decode().strip()) if p.returncode == 0: # gcc supports the "-print-multiarch" option default_x11_lib_dirs += [os.path.join("/usr/lib/", triplet)] default_lib_dirs += [os.path.join("/usr/lib/", triplet)] finally: if tmp is not None: tmp.close() if os.path.join(sys.prefix, 'lib') not in default_lib_dirs: default_lib_dirs.insert(0, os.path.join(sys.prefix, 'lib')) default_include_dirs.append(os.path.join(sys.prefix, 'include')) default_src_dirs.append(os.path.join(sys.prefix, 'src')) default_lib_dirs = [_m for _m in default_lib_dirs if os.path.isdir(_m)] default_include_dirs = [_m for _m in default_include_dirs if os.path.isdir(_m)] default_src_dirs = [_m for _m in default_src_dirs if os.path.isdir(_m)] so_ext = get_shared_lib_extension() def get_standard_file(fname): """Returns a list of files named 'fname' from 1) System-wide directory (directory-location of this module) 2) Users HOME directory (os.environ['HOME']) 3) Local directory """ # System-wide file filenames = [] try: f = __file__ except NameError: f = sys.argv[0] else: sysfile = os.path.join(os.path.split(os.path.abspath(f))[0], fname) if os.path.isfile(sysfile): filenames.append(sysfile) # Home directory # And look for the user config file try: f = os.environ['HOME'] except KeyError: pass else: user_file = os.path.join(f, fname) if os.path.isfile(user_file): filenames.append(user_file) # Local file if os.path.isfile(fname): filenames.append(os.path.abspath(fname)) return filenames def get_info(name, notfound_action=0): """ notfound_action: 0 - do nothing 1 - display warning message 2 - raise error """ cl = {'atlas': atlas_info, # use lapack_opt or blas_opt instead 'atlas_threads': atlas_threads_info, # ditto 'atlas_blas': atlas_blas_info, 'atlas_blas_threads': atlas_blas_threads_info, 'lapack_atlas': lapack_atlas_info, # use lapack_opt instead 'lapack_atlas_threads': lapack_atlas_threads_info, # ditto 'mkl': mkl_info, 'openblas': openblas_info, # use blas_opt instead 'lapack_mkl': lapack_mkl_info, # use lapack_opt instead 'blas_mkl': blas_mkl_info, # use blas_opt instead 'x11': x11_info, 'fft_opt': fft_opt_info, 'fftw': fftw_info, 'fftw2': fftw2_info, 'fftw3': fftw3_info, 'dfftw': dfftw_info, 'sfftw': sfftw_info, 'fftw_threads': fftw_threads_info, 'dfftw_threads': dfftw_threads_info, 'sfftw_threads': sfftw_threads_info, 'djbfft': djbfft_info, 'blas': blas_info, # use blas_opt instead 'lapack': lapack_info, # use lapack_opt instead 'lapack_src': lapack_src_info, 'blas_src': blas_src_info, 'numpy': numpy_info, 'f2py': f2py_info, 'Numeric': Numeric_info, 'numeric': Numeric_info, 'numarray': numarray_info, 'numerix': numerix_info, 'lapack_opt': lapack_opt_info, 'blas_opt': blas_opt_info, 'boost_python': boost_python_info, 'agg2': agg2_info, 'wx': wx_info, 'gdk_pixbuf_xlib_2': gdk_pixbuf_xlib_2_info, 'gdk-pixbuf-xlib-2.0': gdk_pixbuf_xlib_2_info, 'gdk_pixbuf_2': gdk_pixbuf_2_info, 'gdk-pixbuf-2.0': gdk_pixbuf_2_info, 'gdk': gdk_info, 'gdk_2': gdk_2_info, 'gdk-2.0': gdk_2_info, 'gdk_x11_2': gdk_x11_2_info, 'gdk-x11-2.0': gdk_x11_2_info, 'gtkp_x11_2': gtkp_x11_2_info, 'gtk+-x11-2.0': gtkp_x11_2_info, 'gtkp_2': gtkp_2_info, 'gtk+-2.0': gtkp_2_info, 'xft': xft_info, 'freetype2': freetype2_info, 'umfpack': umfpack_info, 'amd': amd_info, }.get(name.lower(), system_info) return cl().get_info(notfound_action) class NotFoundError(DistutilsError): """Some third-party program or library is not found.""" class AtlasNotFoundError(NotFoundError): """ Atlas (http://math-atlas.sourceforge.net/) libraries not found. Directories to search for the libraries can be specified in the numpy/distutils/site.cfg file (section [atlas]) or by setting the ATLAS environment variable.""" class LapackNotFoundError(NotFoundError): """ Lapack (http://www.netlib.org/lapack/) libraries not found. Directories to search for the libraries can be specified in the numpy/distutils/site.cfg file (section [lapack]) or by setting the LAPACK environment variable.""" class LapackSrcNotFoundError(LapackNotFoundError): """ Lapack (http://www.netlib.org/lapack/) sources not found. Directories to search for the sources can be specified in the numpy/distutils/site.cfg file (section [lapack_src]) or by setting the LAPACK_SRC environment variable.""" class BlasNotFoundError(NotFoundError): """ Blas (http://www.netlib.org/blas/) libraries not found. Directories to search for the libraries can be specified in the numpy/distutils/site.cfg file (section [blas]) or by setting the BLAS environment variable.""" class BlasSrcNotFoundError(BlasNotFoundError): """ Blas (http://www.netlib.org/blas/) sources not found. Directories to search for the sources can be specified in the numpy/distutils/site.cfg file (section [blas_src]) or by setting the BLAS_SRC environment variable.""" class FFTWNotFoundError(NotFoundError): """ FFTW (http://www.fftw.org/) libraries not found. Directories to search for the libraries can be specified in the numpy/distutils/site.cfg file (section [fftw]) or by setting the FFTW environment variable.""" class DJBFFTNotFoundError(NotFoundError): """ DJBFFT (http://cr.yp.to/djbfft.html) libraries not found. Directories to search for the libraries can be specified in the numpy/distutils/site.cfg file (section [djbfft]) or by setting the DJBFFT environment variable.""" class NumericNotFoundError(NotFoundError): """ Numeric (http://www.numpy.org/) module not found. Get it from above location, install it, and retry setup.py.""" class X11NotFoundError(NotFoundError): """X11 libraries not found.""" class UmfpackNotFoundError(NotFoundError): """ UMFPACK sparse solver (http://www.cise.ufl.edu/research/sparse/umfpack/) not found. Directories to search for the libraries can be specified in the numpy/distutils/site.cfg file (section [umfpack]) or by setting the UMFPACK environment variable.""" class system_info: """ get_info() is the only public method. Don't use others. """ section = 'ALL' dir_env_var = None search_static_first = 0 # XXX: disabled by default, may disappear in # future unless it is proved to be useful. verbosity = 1 saved_results = {} notfounderror = NotFoundError def __init__(self, default_lib_dirs=default_lib_dirs, default_include_dirs=default_include_dirs, verbosity=1, ): self.__class__.info = {} self.local_prefixes = [] defaults = {} 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) defaults['search_static_first'] = str(self.search_static_first) self.cp = ConfigParser(defaults) self.files = [] self.files.extend(get_standard_file('.numpy-site.cfg')) self.files.extend(get_standard_file('site.cfg')) self.parse_config_files() if self.section is not None: self.search_static_first = self.cp.getboolean( self.section, 'search_static_first') assert isinstance(self.search_static_first, int) def parse_config_files(self): self.cp.read(self.files) if not self.cp.has_section(self.section): if self.section is not None: self.cp.add_section(self.section) def calc_libraries_info(self): libs = self.get_libraries() dirs = self.get_lib_dirs() info = {} for lib in libs: i = self.check_libs(dirs, [lib]) if i is not None: dict_append(info, **i) else: log.info('Library %s was not found. Ignoring' % (lib)) return info def set_info(self, **info): if info: lib_info = self.calc_libraries_info() dict_append(info, **lib_info) self.saved_results[self.__class__.__name__] = info def has_info(self): return self.__class__.__name__ in self.saved_results def get_info(self, notfound_action=0): """ Return a dictonary with items that are compatible with numpy.distutils.setup keyword arguments. """ flag = 0 if not self.has_info(): flag = 1 log.info(self.__class__.__name__ + ':') if hasattr(self, 'calc_info'): self.calc_info() if notfound_action: if not self.has_info(): if notfound_action == 1: warnings.warn(self.notfounderror.__doc__) elif notfound_action == 2: raise self.notfounderror(self.notfounderror.__doc__) else: raise ValueError(repr(notfound_action)) if not self.has_info(): log.info(' NOT AVAILABLE') self.set_info() else: log.info(' FOUND:') res = self.saved_results.get(self.__class__.__name__) if self.verbosity > 0 and flag: for k, v in res.items(): v = str(v) if k in ['sources', 'libraries'] and len(v) > 270: v = v[:120] + '...\n...\n...' + v[-120:] log.info(' %s = %s', k, v) log.info('') return copy.deepcopy(res) def get_paths(self, section, key): dirs = self.cp.get(section, key).split(os.pathsep) env_var = self.dir_env_var if env_var: if is_sequence(env_var): e0 = env_var[-1] for e in env_var: if e in os.environ: e0 = e break if not env_var[0] == e0: log.info('Setting %s=%s' % (env_var[0], e0)) env_var = e0 if env_var and env_var in os.environ: d = os.environ[env_var] if d == 'None': log.info('Disabled %s: %s', self.__class__.__name__, '(%s is None)' % (env_var,)) return [] if os.path.isfile(d): dirs = [os.path.dirname(d)] + dirs l = getattr(self, '_lib_names', []) if len(l) == 1: b = os.path.basename(d) b = os.path.splitext(b)[0] if b[:3] == 'lib': log.info('Replacing _lib_names[0]==%r with %r' \ % (self._lib_names[0], b[3:])) self._lib_names[0] = b[3:] else: ds = d.split(os.pathsep) ds2 = [] for d in ds: if os.path.isdir(d): ds2.append(d) for dd in ['include', 'lib']: d1 = os.path.join(d, dd) if os.path.isdir(d1): ds2.append(d1) dirs = ds2 + dirs default_dirs = self.cp.get(self.section, key).split(os.pathsep) dirs.extend(default_dirs) ret = [] for d in dirs: if not os.path.isdir(d): warnings.warn('Specified path %s is invalid.' % d) continue if d not in ret: ret.append(d) log.debug('( %s = %s )', key, ':'.join(ret)) return ret def get_lib_dirs(self, key='library_dirs'): return self.get_paths(self.section, key) def get_include_dirs(self, key='include_dirs'): return self.get_paths(self.section, key) def get_src_dirs(self, key='src_dirs'): return self.get_paths(self.section, key) def get_libs(self, key, default): try: libs = self.cp.get(self.section, key) except NoOptionError: if not default: return [] if is_string(default): return [default] return default return [b for b in [a.strip() for a in libs.split(',')] if b] def get_libraries(self, key='libraries'): return self.get_libs(key, '') def library_extensions(self): static_exts = ['.a'] if sys.platform == 'win32': static_exts.append('.lib') # .lib is used by MSVC if self.search_static_first: exts = static_exts + [so_ext] else: exts = [so_ext] + static_exts if sys.platform == 'cygwin': exts.append('.dll.a') if sys.platform == 'darwin': exts.append('.dylib') # Debian and Ubuntu added a g3f suffix to shared library to deal with # g77 -> gfortran ABI transition # XXX: disabled, it hides more problem than it solves. #if sys.platform[:5] == 'linux': # exts.append('.so.3gf') return exts def check_libs(self, lib_dirs, libs, opt_libs=[]): """If static or shared libraries are available then return their info dictionary. Checks for all libraries as shared libraries first, then static (or vice versa if self.search_static_first is True). """ exts = self.library_extensions() info = None for ext in exts: info = self._check_libs(lib_dirs, libs, opt_libs, [ext]) if info is not None: break if not info: log.info(' libraries %s not found in %s', ','.join(libs), lib_dirs) return info def check_libs2(self, lib_dirs, libs, opt_libs=[]): """If static or shared libraries are available then return their info dictionary. Checks each library for shared or static. """ exts = self.library_extensions() info = self._check_libs(lib_dirs, libs, opt_libs, exts) if not info: log.info(' libraries %s not found in %s', ','.join(libs), lib_dirs) return info def _lib_list(self, lib_dir, libs, exts): assert is_string(lib_dir) liblist = [] # under windows first try without 'lib' prefix if sys.platform == 'win32': lib_prefixes = ['', 'lib'] else: lib_prefixes = ['lib'] # for each library name, see if we can find a file for it. for l in libs: for ext in exts: for prefix in lib_prefixes: p = self.combine_paths(lib_dir, prefix + l + ext) if p: break if p: assert len(p) == 1 # ??? splitext on p[0] would do this for cygwin # doesn't seem correct if ext == '.dll.a': l += '.dll' liblist.append(l) break return liblist def _check_libs(self, lib_dirs, libs, opt_libs, exts): """Find mandatory and optional libs in expected paths. Missing optional libraries are silently forgotten. """ # First, try to find the mandatory libraries if is_sequence(lib_dirs): found_libs, found_dirs = [], [] for dir_ in lib_dirs: found_libs1 = self._lib_list(dir_, libs, exts) # It's possible that we'll find the same library in multiple # directories. It's also possible that we'll find some # libraries on in directory, and some in another. So the # obvious thing would be to use a set instead of a list, but I # don't know if preserving order matters (does it?). for found_lib in found_libs1: if found_lib not in found_libs: found_libs.append(found_lib) if dir_ not in found_dirs: found_dirs.append(dir_) else: found_libs = self._lib_list(lib_dirs, libs, exts) found_dirs = [lib_dirs] 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): for dir_ in lib_dirs: opt_found_libs = self._lib_list(dir_, opt_libs, exts) if opt_found_libs: if dir_ not in found_dirs: found_dirs.extend(dir_) found_libs.extend(opt_found_libs) else: opt_found_libs = self._lib_list(lib_dirs, opt_libs, exts) if opt_found_libs: found_libs.extend(opt_found_libs) return info else: return None def combine_paths(self, *args): """Return a list of existing paths composed by all combinations of items from the arguments. """ return combine_paths(*args, **{'verbosity': self.verbosity}) class fft_opt_info(system_info): def calc_info(self): info = {} fftw_info = get_info('fftw3') or get_info('fftw2') or get_info('dfftw') djbfft_info = get_info('djbfft') if fftw_info: dict_append(info, **fftw_info) if djbfft_info: dict_append(info, **djbfft_info) self.set_info(**info) return class fftw_info(system_info): #variables to override section = 'fftw' dir_env_var = 'FFTW' notfounderror = FFTWNotFoundError ver_info = [{'name':'fftw3', 'libs':['fftw3'], 'includes':['fftw3.h'], 'macros':[('SCIPY_FFTW3_H', None)]}, {'name':'fftw2', 'libs':['rfftw', 'fftw'], 'includes':['fftw.h', 'rfftw.h'], 'macros':[('SCIPY_FFTW_H', None)]}] def calc_ver_info(self, ver_param): """Returns True on successful version detection, else False""" lib_dirs = self.get_lib_dirs() incl_dirs = self.get_include_dirs() incl_dir = None libs = self.get_libs(self.section + '_libs', ver_param['libs']) info = self.check_libs(lib_dirs, libs) if info is not None: flag = 0 for d in incl_dirs: if len(self.combine_paths(d, ver_param['includes'])) \ == len(ver_param['includes']): dict_append(info, include_dirs=[d]) flag = 1 incl_dirs = [d] break if flag: dict_append(info, define_macros=ver_param['macros']) else: info = None if info is not None: self.set_info(**info) return True else: log.info(' %s not found' % (ver_param['name'])) return False def calc_info(self): for i in self.ver_info: if self.calc_ver_info(i): break class fftw2_info(fftw_info): #variables to override section = 'fftw' dir_env_var = 'FFTW' notfounderror = FFTWNotFoundError ver_info = [{'name':'fftw2', 'libs':['rfftw', 'fftw'], 'includes':['fftw.h', 'rfftw.h'], 'macros':[('SCIPY_FFTW_H', None)]} ] class fftw3_info(fftw_info): #variables to override section = 'fftw3' dir_env_var = 'FFTW3' notfounderror = FFTWNotFoundError ver_info = [{'name':'fftw3', 'libs':['fftw3'], 'includes':['fftw3.h'], 'macros':[('SCIPY_FFTW3_H', None)]}, ] class dfftw_info(fftw_info): section = 'fftw' dir_env_var = 'FFTW' ver_info = [{'name':'dfftw', 'libs':['drfftw', 'dfftw'], 'includes':['dfftw.h', 'drfftw.h'], 'macros':[('SCIPY_DFFTW_H', None)]}] class sfftw_info(fftw_info): section = 'fftw' dir_env_var = 'FFTW' ver_info = [{'name':'sfftw', 'libs':['srfftw', 'sfftw'], 'includes':['sfftw.h', 'srfftw.h'], 'macros':[('SCIPY_SFFTW_H', None)]}] class fftw_threads_info(fftw_info): section = 'fftw' dir_env_var = 'FFTW' ver_info = [{'name':'fftw threads', 'libs':['rfftw_threads', 'fftw_threads'], 'includes':['fftw_threads.h', 'rfftw_threads.h'], 'macros':[('SCIPY_FFTW_THREADS_H', None)]}] class dfftw_threads_info(fftw_info): section = 'fftw' dir_env_var = 'FFTW' ver_info = [{'name':'dfftw threads', 'libs':['drfftw_threads', 'dfftw_threads'], 'includes':['dfftw_threads.h', 'drfftw_threads.h'], 'macros':[('SCIPY_DFFTW_THREADS_H', None)]}] class sfftw_threads_info(fftw_info): section = 'fftw' dir_env_var = 'FFTW' ver_info = [{'name':'sfftw threads', 'libs':['srfftw_threads', 'sfftw_threads'], 'includes':['sfftw_threads.h', 'srfftw_threads.h'], 'macros':[('SCIPY_SFFTW_THREADS_H', None)]}] class djbfft_info(system_info): section = 'djbfft' dir_env_var = 'DJBFFT' notfounderror = DJBFFTNotFoundError def get_paths(self, section, key): pre_dirs = system_info.get_paths(self, section, key) dirs = [] for d in pre_dirs: dirs.extend(self.combine_paths(d, ['djbfft']) + [d]) return [d for d in dirs if os.path.isdir(d)] def calc_info(self): lib_dirs = self.get_lib_dirs() incl_dirs = self.get_include_dirs() info = None for d in lib_dirs: p = self.combine_paths(d, ['djbfft.a']) if p: info = {'extra_objects': p} break p = self.combine_paths(d, ['libdjbfft.a', 'libdjbfft' + so_ext]) if p: info = {'libraries': ['djbfft'], 'library_dirs': [d]} break if info is None: return for d in incl_dirs: if len(self.combine_paths(d, ['fftc8.h', 'fftfreq.h'])) == 2: dict_append(info, include_dirs=[d], define_macros=[('SCIPY_DJBFFT_H', None)]) self.set_info(**info) return return class mkl_info(system_info): section = 'mkl' dir_env_var = 'MKL' _lib_mkl = ['mkl', 'vml', 'guide'] def get_mkl_rootdir(self): mklroot = os.environ.get('MKLROOT', None) if mklroot is not None: return mklroot paths = os.environ.get('LD_LIBRARY_PATH', '').split(os.pathsep) ld_so_conf = '/etc/ld.so.conf' if os.path.isfile(ld_so_conf): for d in open(ld_so_conf, 'r'): d = d.strip() if d: paths.append(d) intel_mkl_dirs = [] for path in paths: path_atoms = path.split(os.sep) for m in path_atoms: if m.startswith('mkl'): d = os.sep.join(path_atoms[:path_atoms.index(m) + 2]) intel_mkl_dirs.append(d) break for d in paths: dirs = glob(os.path.join(d, 'mkl', '*')) dirs += glob(os.path.join(d, 'mkl*')) for d in dirs: if os.path.isdir(os.path.join(d, 'lib')): return d return None def __init__(self): mklroot = self.get_mkl_rootdir() if mklroot is None: system_info.__init__(self) else: from .cpuinfo import cpu l = 'mkl' # use shared library if cpu.is_Itanium(): plt = '64' #l = 'mkl_ipf' elif cpu.is_Xeon(): plt = 'em64t' #l = 'mkl_em64t' else: plt = '32' #l = 'mkl_ia32' if l not in self._lib_mkl: self._lib_mkl.insert(0, l) system_info.__init__( self, default_lib_dirs=[os.path.join(mklroot, 'lib', plt)], default_include_dirs=[os.path.join(mklroot, 'include')]) def calc_info(self): lib_dirs = self.get_lib_dirs() incl_dirs = self.get_include_dirs() mkl_libs = self.get_libs('mkl_libs', self._lib_mkl) info = self.check_libs2(lib_dirs, mkl_libs) if info is None: return dict_append(info, define_macros=[('SCIPY_MKL_H', None)], include_dirs=incl_dirs) if sys.platform == 'win32': pass # win32 has no pthread library else: dict_append(info, libraries=['pthread']) self.set_info(**info) class lapack_mkl_info(mkl_info): def calc_info(self): mkl = get_info('mkl') if not mkl: return if sys.platform == 'win32': lapack_libs = self.get_libs('lapack_libs', ['mkl_lapack']) else: lapack_libs = self.get_libs('lapack_libs', ['mkl_lapack32', 'mkl_lapack64']) info = {'libraries': lapack_libs} dict_append(info, **mkl) self.set_info(**info) class blas_mkl_info(mkl_info): pass class atlas_info(system_info): section = 'atlas' dir_env_var = 'ATLAS' _lib_names = ['f77blas', 'cblas'] if sys.platform[:7] == 'freebsd': _lib_atlas = ['atlas_r'] _lib_lapack = ['alapack_r'] else: _lib_atlas = ['atlas'] _lib_lapack = ['lapack'] notfounderror = AtlasNotFoundError def get_paths(self, section, key): pre_dirs = system_info.get_paths(self, section, key) dirs = [] for d in pre_dirs: dirs.extend(self.combine_paths(d, ['atlas*', 'ATLAS*', 'sse', '3dnow', 'sse2']) + [d]) return [d for d in dirs if os.path.isdir(d)] def calc_info(self): lib_dirs = self.get_lib_dirs() info = {} atlas_libs = self.get_libs('atlas_libs', self._lib_names + self._lib_atlas) lapack_libs = self.get_libs('lapack_libs', self._lib_lapack) atlas = None lapack = None atlas_1 = None for d in lib_dirs: atlas = self.check_libs2(d, atlas_libs, []) lapack_atlas = self.check_libs2(d, ['lapack_atlas'], []) if atlas is not None: lib_dirs2 = [d] + self.combine_paths(d, ['atlas*', 'ATLAS*']) lapack = self.check_libs2(lib_dirs2, lapack_libs, []) if lapack is not None: break if atlas: atlas_1 = atlas log.info(self.__class__) if atlas is None: atlas = atlas_1 if atlas is None: return include_dirs = self.get_include_dirs() h = (self.combine_paths(lib_dirs + include_dirs, 'cblas.h') or [None]) h = h[0] if h: h = os.path.dirname(h) dict_append(info, include_dirs=[h]) info['language'] = 'c' if lapack is not None: dict_append(info, **lapack) dict_append(info, **atlas) elif 'lapack_atlas' in atlas['libraries']: dict_append(info, **atlas) dict_append(info, define_macros=[('ATLAS_WITH_LAPACK_ATLAS', None)]) self.set_info(**info) return else: dict_append(info, **atlas) dict_append(info, define_macros=[('ATLAS_WITHOUT_LAPACK', None)]) message = """ ********************************************************************* Could not find lapack library within the ATLAS installation. ********************************************************************* """ warnings.warn(message) self.set_info(**info) return # Check if lapack library is complete, only warn if it is not. lapack_dir = lapack['library_dirs'][0] lapack_name = lapack['libraries'][0] lapack_lib = None lib_prefixes = ['lib'] if sys.platform == 'win32': lib_prefixes.append('') for e in self.library_extensions(): for prefix in lib_prefixes: fn = os.path.join(lapack_dir, prefix + lapack_name + e) if os.path.exists(fn): lapack_lib = fn break if lapack_lib: break if lapack_lib is not None: sz = os.stat(lapack_lib)[6] if sz <= 4000 * 1024: message = """ ********************************************************************* Lapack library (from ATLAS) is probably incomplete: size of %s is %sk (expected >4000k) Follow the instructions in the KNOWN PROBLEMS section of the file numpy/INSTALL.txt. ********************************************************************* """ % (lapack_lib, sz / 1024) warnings.warn(message) else: info['language'] = 'f77' atlas_version, atlas_extra_info = get_atlas_version(**atlas) dict_append(info, **atlas_extra_info) self.set_info(**info) class atlas_blas_info(atlas_info): _lib_names = ['f77blas', 'cblas'] def calc_info(self): lib_dirs = self.get_lib_dirs() info = {} atlas_libs = self.get_libs('atlas_libs', self._lib_names + self._lib_atlas) atlas = self.check_libs2(lib_dirs, atlas_libs, []) if atlas is None: return include_dirs = self.get_include_dirs() h = (self.combine_paths(lib_dirs + include_dirs, 'cblas.h') or [None]) h = h[0] if h: h = os.path.dirname(h) dict_append(info, include_dirs=[h]) info['language'] = 'c' atlas_version, atlas_extra_info = get_atlas_version(**atlas) dict_append(atlas, **atlas_extra_info) dict_append(info, **atlas) self.set_info(**info) return class atlas_threads_info(atlas_info): dir_env_var = ['PTATLAS', 'ATLAS'] _lib_names = ['ptf77blas', 'ptcblas'] class atlas_blas_threads_info(atlas_blas_info): dir_env_var = ['PTATLAS', 'ATLAS'] _lib_names = ['ptf77blas', 'ptcblas'] class lapack_atlas_info(atlas_info): _lib_names = ['lapack_atlas'] + atlas_info._lib_names class lapack_atlas_threads_info(atlas_threads_info): _lib_names = ['lapack_atlas'] + atlas_threads_info._lib_names class lapack_info(system_info): section = 'lapack' dir_env_var = 'LAPACK' _lib_names = ['lapack'] notfounderror = LapackNotFoundError def calc_info(self): lib_dirs = self.get_lib_dirs() lapack_libs = self.get_libs('lapack_libs', self._lib_names) info = self.check_libs(lib_dirs, lapack_libs, []) if info is None: return info['language'] = 'f77' self.set_info(**info) class lapack_src_info(system_info): section = 'lapack_src' dir_env_var = 'LAPACK_SRC' notfounderror = LapackSrcNotFoundError def get_paths(self, section, key): pre_dirs = system_info.get_paths(self, section, key) dirs = [] for d in pre_dirs: dirs.extend([d] + self.combine_paths(d, ['LAPACK*/SRC', 'SRC'])) return [d for d in dirs if os.path.isdir(d)] def calc_info(self): src_dirs = self.get_src_dirs() src_dir = '' for d in src_dirs: if os.path.isfile(os.path.join(d, 'dgesv.f')): src_dir = d break if not src_dir: #XXX: Get sources from netlib. May be ask first. return # The following is extracted from LAPACK-3.0/SRC/Makefile. # Added missing names from lapack-lite-3.1.1/SRC/Makefile # while keeping removed names for Lapack-3.0 compatibility. allaux = ''' ilaenv ieeeck lsame lsamen xerbla iparmq ''' # *.f laux = ''' bdsdc bdsqr disna labad lacpy ladiv lae2 laebz laed0 laed1 laed2 laed3 laed4 laed5 laed6 laed7 laed8 laed9 laeda laev2 lagtf lagts lamch lamrg lanst lapy2 lapy3 larnv larrb larre larrf lartg laruv las2 lascl lasd0 lasd1 lasd2 lasd3 lasd4 lasd5 lasd6 lasd7 lasd8 lasd9 lasda lasdq lasdt laset lasq1 lasq2 lasq3 lasq4 lasq5 lasq6 lasr lasrt lassq lasv2 pttrf stebz stedc steqr sterf larra larrc larrd larr larrk larrj larrr laneg laisnan isnan lazq3 lazq4 ''' # [s|d]*.f lasrc = ''' gbbrd gbcon gbequ gbrfs gbsv gbsvx gbtf2 gbtrf gbtrs gebak gebal gebd2 gebrd gecon geequ gees geesx geev geevx gegs gegv gehd2 gehrd gelq2 gelqf gels gelsd gelss gelsx gelsy geql2 geqlf geqp3 geqpf geqr2 geqrf gerfs gerq2 gerqf gesc2 gesdd gesv gesvd gesvx getc2 getf2 getrf getri getrs ggbak ggbal gges ggesx ggev ggevx ggglm gghrd gglse ggqrf ggrqf ggsvd ggsvp gtcon gtrfs gtsv gtsvx gttrf gttrs gtts2 hgeqz hsein hseqr labrd lacon laein lags2 lagtm lahqr lahrd laic1 lals0 lalsa lalsd langb lange langt lanhs lansb lansp lansy lantb lantp lantr lapll lapmt laqgb laqge laqp2 laqps laqsb laqsp laqsy lar1v lar2v larf larfb larfg larft larfx largv larrv lartv larz larzb larzt laswp lasyf latbs latdf latps latrd latrs latrz latzm lauu2 lauum pbcon pbequ pbrfs pbstf pbsv pbsvx pbtf2 pbtrf pbtrs pocon poequ porfs posv posvx potf2 potrf potri potrs ppcon ppequ pprfs ppsv ppsvx pptrf pptri pptrs ptcon pteqr ptrfs ptsv ptsvx pttrs ptts2 spcon sprfs spsv spsvx sptrf sptri sptrs stegr stein sycon syrfs sysv sysvx sytf2 sytrf sytri sytrs tbcon tbrfs tbtrs tgevc tgex2 tgexc tgsen tgsja tgsna tgsy2 tgsyl tpcon tprfs tptri tptrs trcon trevc trexc trrfs trsen trsna trsyl trti2 trtri trtrs tzrqf tzrzf lacn2 lahr2 stemr laqr0 laqr1 laqr2 laqr3 laqr4 laqr5 ''' # [s|c|d|z]*.f sd_lasrc = ''' laexc lag2 lagv2 laln2 lanv2 laqtr lasy2 opgtr opmtr org2l org2r orgbr orghr orgl2 orglq orgql orgqr orgr2 orgrq orgtr orm2l orm2r ormbr ormhr orml2 ormlq ormql ormqr ormr2 ormr3 ormrq ormrz ormtr rscl sbev sbevd sbevx sbgst sbgv sbgvd sbgvx sbtrd spev spevd spevx spgst spgv spgvd spgvx sptrd stev stevd stevr stevx syev syevd syevr syevx sygs2 sygst sygv sygvd sygvx sytd2 sytrd ''' # [s|d]*.f cz_lasrc = ''' bdsqr hbev hbevd hbevx hbgst hbgv hbgvd hbgvx hbtrd hecon heev heevd heevr heevx hegs2 hegst hegv hegvd hegvx herfs hesv hesvx hetd2 hetf2 hetrd hetrf hetri hetrs hpcon hpev hpevd hpevx hpgst hpgv hpgvd hpgvx hprfs hpsv hpsvx hptrd hptrf hptri hptrs lacgv lacp2 lacpy lacrm lacrt ladiv laed0 laed7 laed8 laesy laev2 lahef lanhb lanhe lanhp lanht laqhb laqhe laqhp larcm larnv lartg lascl laset lasr lassq pttrf rot spmv spr stedc steqr symv syr ung2l ung2r ungbr unghr ungl2 unglq ungql ungqr ungr2 ungrq ungtr unm2l unm2r unmbr unmhr unml2 unmlq unmql unmqr unmr2 unmr3 unmrq unmrz unmtr upgtr upmtr ''' # [c|z]*.f ####### sclaux = laux + ' econd ' # s*.f dzlaux = laux + ' secnd ' # d*.f slasrc = lasrc + sd_lasrc # s*.f dlasrc = lasrc + sd_lasrc # d*.f clasrc = lasrc + cz_lasrc + ' srot srscl ' # c*.f zlasrc = lasrc + cz_lasrc + ' drot drscl ' # z*.f oclasrc = ' icmax1 scsum1 ' # *.f ozlasrc = ' izmax1 dzsum1 ' # *.f sources = ['s%s.f' % f for f in (sclaux + slasrc).split()] \ + ['d%s.f' % f for f in (dzlaux + dlasrc).split()] \ + ['c%s.f' % f for f in (clasrc).split()] \ + ['z%s.f' % f for f in (zlasrc).split()] \ + ['%s.f' % f for f in (allaux + oclasrc + ozlasrc).split()] sources = [os.path.join(src_dir, f) for f in sources] # Lapack 3.1: src_dir2 = os.path.join(src_dir, '..', 'INSTALL') sources += [os.path.join(src_dir2, p + 'lamch.f') for p in 'sdcz'] # Lapack 3.2.1: sources += [os.path.join(src_dir, p + 'larfp.f') for p in 'sdcz'] sources += [os.path.join(src_dir, 'ila' + p + 'lr.f') for p in 'sdcz'] sources += [os.path.join(src_dir, 'ila' + p + 'lc.f') for p in 'sdcz'] # Should we check here actual existence of source files? # Yes, the file listing is different between 3.0 and 3.1 # versions. sources = [f for f in sources if os.path.isfile(f)] info = {'sources': sources, 'language': 'f77'} self.set_info(**info) atlas_version_c_text = r''' /* This file is generated from numpy/distutils/system_info.py */ void ATL_buildinfo(void); int main(void) { ATL_buildinfo(); return 0; } ''' _cached_atlas_version = {} def get_atlas_version(**config): libraries = config.get('libraries', []) library_dirs = config.get('library_dirs', []) key = (tuple(libraries), tuple(library_dirs)) if key in _cached_atlas_version: return _cached_atlas_version[key] c = cmd_config(Distribution()) atlas_version = None info = {} try: s, o = c.get_output(atlas_version_c_text, libraries=libraries, library_dirs=library_dirs, use_tee=(system_info.verbosity > 0)) if s and re.search(r'undefined reference to `_gfortran', o, re.M): s, o = c.get_output(atlas_version_c_text, libraries=libraries + ['gfortran'], library_dirs=library_dirs, use_tee=(system_info.verbosity > 0)) if not s: warnings.warn(""" ***************************************************** Linkage with ATLAS requires gfortran. Use python setup.py config_fc --fcompiler=gnu95 ... when building extension libraries that use ATLAS. Make sure that -lgfortran is used for C++ extensions. ***************************************************** """) dict_append(info, language='f90', define_macros=[('ATLAS_REQUIRES_GFORTRAN', None)]) except Exception: # failed to get version from file -- maybe on Windows # look at directory name for o in library_dirs: m = re.search(r'ATLAS_(?P\d+[.]\d+[.]\d+)_', o) if m: atlas_version = m.group('version') if atlas_version is not None: break # final choice --- look at ATLAS_VERSION environment # variable if atlas_version is None: atlas_version = os.environ.get('ATLAS_VERSION', None) if atlas_version: dict_append(info, define_macros=[( 'ATLAS_INFO', '"\\"%s\\""' % atlas_version) ]) else: dict_append(info, define_macros=[('NO_ATLAS_INFO', -1)]) return atlas_version or '?.?.?', info if not s: m = re.search(r'ATLAS version (?P\d+[.]\d+[.]\d+)', o) if m: atlas_version = m.group('version') if atlas_version is None: if re.search(r'undefined symbol: ATL_buildinfo', o, re.M): atlas_version = '3.2.1_pre3.3.6' else: log.info('Status: %d', s) log.info('Output: %s', o) if atlas_version == '3.2.1_pre3.3.6': dict_append(info, define_macros=[('NO_ATLAS_INFO', -2)]) else: dict_append(info, define_macros=[( 'ATLAS_INFO', '"\\"%s\\""' % atlas_version) ]) result = _cached_atlas_version[key] = atlas_version, info return result class lapack_opt_info(system_info): notfounderror = LapackNotFoundError def calc_info(self): openblas_info = get_info('openblas') if openblas_info: self.set_info(**openblas_info) return lapack_mkl_info = get_info('lapack_mkl') if lapack_mkl_info: self.set_info(**lapack_mkl_info) return atlas_info = get_info('atlas_threads') if not atlas_info: atlas_info = get_info('atlas') if sys.platform == 'darwin' and not atlas_info: # Use the system lapack from Accelerate or vecLib under OSX args = [] link_args = [] if get_platform()[-4:] == 'i386' or 'intel' in get_platform() or \ 'x86_64' in get_platform() or \ 'i386' in platform.platform(): intel = 1 else: intel = 0 if os.path.exists('/System/Library/Frameworks' '/Accelerate.framework/'): if intel: args.extend(['-msse3']) else: args.extend(['-faltivec']) link_args.extend(['-Wl,-framework', '-Wl,Accelerate']) elif os.path.exists('/System/Library/Frameworks' '/vecLib.framework/'): if intel: args.extend(['-msse3']) else: args.extend(['-faltivec']) link_args.extend(['-Wl,-framework', '-Wl,vecLib']) if args: self.set_info(extra_compile_args=args, extra_link_args=link_args, define_macros=[('NO_ATLAS_INFO', 3)]) return #atlas_info = {} ## uncomment for testing need_lapack = 0 need_blas = 0 info = {} if atlas_info: l = atlas_info.get('define_macros', []) if ('ATLAS_WITH_LAPACK_ATLAS', None) in l \ or ('ATLAS_WITHOUT_LAPACK', None) in l: need_lapack = 1 info = atlas_info else: warnings.warn(AtlasNotFoundError.__doc__) need_blas = 1 need_lapack = 1 dict_append(info, define_macros=[('NO_ATLAS_INFO', 1)]) if need_lapack: lapack_info = get_info('lapack') #lapack_info = {} ## uncomment for testing if lapack_info: dict_append(info, **lapack_info) else: warnings.warn(LapackNotFoundError.__doc__) lapack_src_info = get_info('lapack_src') if not lapack_src_info: warnings.warn(LapackSrcNotFoundError.__doc__) return dict_append(info, libraries=[('flapack_src', lapack_src_info)]) if need_blas: blas_info = get_info('blas') #blas_info = {} ## uncomment for testing if blas_info: dict_append(info, **blas_info) else: warnings.warn(BlasNotFoundError.__doc__) blas_src_info = get_info('blas_src') if not blas_src_info: warnings.warn(BlasSrcNotFoundError.__doc__) return dict_append(info, libraries=[('fblas_src', blas_src_info)]) self.set_info(**info) return class blas_opt_info(system_info): notfounderror = BlasNotFoundError def calc_info(self): blas_mkl_info = get_info('blas_mkl') if blas_mkl_info: self.set_info(**blas_mkl_info) return openblas_info = get_info('openblas') if openblas_info: self.set_info(**openblas_info) return atlas_info = get_info('atlas_blas_threads') if not atlas_info: atlas_info = get_info('atlas_blas') if sys.platform == 'darwin' and not atlas_info: # Use the system BLAS from Accelerate or vecLib under OSX args = [] link_args = [] if get_platform()[-4:] == 'i386' or 'intel' in get_platform() or \ 'x86_64' in get_platform() or \ 'i386' in platform.platform(): intel = 1 else: intel = 0 if os.path.exists('/System/Library/Frameworks' '/Accelerate.framework/'): if intel: args.extend(['-msse3']) else: args.extend(['-faltivec']) args.extend([ '-I/System/Library/Frameworks/vecLib.framework/Headers']) link_args.extend(['-Wl,-framework', '-Wl,Accelerate']) elif os.path.exists('/System/Library/Frameworks' '/vecLib.framework/'): if intel: args.extend(['-msse3']) else: args.extend(['-faltivec']) args.extend([ '-I/System/Library/Frameworks/vecLib.framework/Headers']) link_args.extend(['-Wl,-framework', '-Wl,vecLib']) if args: self.set_info(extra_compile_args=args, extra_link_args=link_args, define_macros=[('NO_ATLAS_INFO', 3)]) return need_blas = 0 info = {} if atlas_info: info = atlas_info else: warnings.warn(AtlasNotFoundError.__doc__) need_blas = 1 dict_append(info, define_macros=[('NO_ATLAS_INFO', 1)]) if need_blas: blas_info = get_info('blas') if blas_info: dict_append(info, **blas_info) else: warnings.warn(BlasNotFoundError.__doc__) blas_src_info = get_info('blas_src') if not blas_src_info: warnings.warn(BlasSrcNotFoundError.__doc__) return dict_append(info, libraries=[('fblas_src', blas_src_info)]) self.set_info(**info) return class blas_info(system_info): section = 'blas' dir_env_var = 'BLAS' _lib_names = ['blas'] notfounderror = BlasNotFoundError def calc_info(self): lib_dirs = self.get_lib_dirs() blas_libs = self.get_libs('blas_libs', self._lib_names) info = self.check_libs(lib_dirs, blas_libs, []) if info is None: return info['language'] = 'f77' # XXX: is it generally true? self.set_info(**info) class openblas_info(blas_info): section = 'openblas' dir_env_var = 'OPENBLAS' _lib_names = ['openblas'] notfounderror = BlasNotFoundError def calc_info(self): lib_dirs = self.get_lib_dirs() openblas_libs = self.get_libs('libraries', self._lib_names) if openblas_libs == self._lib_names: # backward compat with 1.8.0 openblas_libs = self.get_libs('openblas_libs', self._lib_names) info = self.check_libs(lib_dirs, openblas_libs, []) if info is None: return info['language'] = 'f77' # XXX: is it generally true? self.set_info(**info) class blas_src_info(system_info): section = 'blas_src' dir_env_var = 'BLAS_SRC' notfounderror = BlasSrcNotFoundError def get_paths(self, section, key): pre_dirs = system_info.get_paths(self, section, key) dirs = [] for d in pre_dirs: dirs.extend([d] + self.combine_paths(d, ['blas'])) return [d for d in dirs if os.path.isdir(d)] def calc_info(self): src_dirs = self.get_src_dirs() src_dir = '' for d in src_dirs: if os.path.isfile(os.path.join(d, 'daxpy.f')): src_dir = d break if not src_dir: #XXX: Get sources from netlib. May be ask first. return blas1 = ''' caxpy csscal dnrm2 dzasum saxpy srotg zdotc ccopy cswap drot dznrm2 scasum srotm zdotu cdotc dasum drotg icamax scnrm2 srotmg zdrot cdotu daxpy drotm idamax scopy sscal zdscal crotg dcabs1 drotmg isamax sdot sswap zrotg cscal dcopy dscal izamax snrm2 zaxpy zscal csrot ddot dswap sasum srot zcopy zswap scabs1 ''' blas2 = ''' cgbmv chpmv ctrsv dsymv dtrsv sspr2 strmv zhemv ztpmv cgemv chpr dgbmv dsyr lsame ssymv strsv zher ztpsv cgerc chpr2 dgemv dsyr2 sgbmv ssyr xerbla zher2 ztrmv cgeru ctbmv dger dtbmv sgemv ssyr2 zgbmv zhpmv ztrsv chbmv ctbsv dsbmv dtbsv sger stbmv zgemv zhpr chemv ctpmv dspmv dtpmv ssbmv stbsv zgerc zhpr2 cher ctpsv dspr dtpsv sspmv stpmv zgeru ztbmv cher2 ctrmv dspr2 dtrmv sspr stpsv zhbmv ztbsv ''' blas3 = ''' cgemm csymm ctrsm dsyrk sgemm strmm zhemm zsyr2k chemm csyr2k dgemm dtrmm ssymm strsm zher2k zsyrk cher2k csyrk dsymm dtrsm ssyr2k zherk ztrmm cherk ctrmm dsyr2k ssyrk zgemm zsymm ztrsm ''' sources = [os.path.join(src_dir, f + '.f') \ for f in (blas1 + blas2 + blas3).split()] #XXX: should we check here actual existence of source files? sources = [f for f in sources if os.path.isfile(f)] info = {'sources': sources, 'language': 'f77'} self.set_info(**info) class x11_info(system_info): section = 'x11' notfounderror = X11NotFoundError def __init__(self): system_info.__init__(self, default_lib_dirs=default_x11_lib_dirs, default_include_dirs=default_x11_include_dirs) def calc_info(self): if sys.platform in ['win32']: return lib_dirs = self.get_lib_dirs() include_dirs = self.get_include_dirs() x11_libs = self.get_libs('x11_libs', ['X11']) info = self.check_libs(lib_dirs, x11_libs, []) if info is None: return inc_dir = None for d in include_dirs: if self.combine_paths(d, 'X11/X.h'): inc_dir = d break if inc_dir is not None: dict_append(info, include_dirs=[inc_dir]) self.set_info(**info) class _numpy_info(system_info): section = 'Numeric' modulename = 'Numeric' notfounderror = NumericNotFoundError def __init__(self): include_dirs = [] try: module = __import__(self.modulename) prefix = [] for name in module.__file__.split(os.sep): if name == 'lib': break prefix.append(name) # Ask numpy for its own include path before attempting # anything else try: include_dirs.append(getattr(module, 'get_include')()) except AttributeError: pass include_dirs.append(distutils.sysconfig.get_python_inc( prefix=os.sep.join(prefix))) except ImportError: pass py_incl_dir = distutils.sysconfig.get_python_inc() include_dirs.append(py_incl_dir) py_pincl_dir = distutils.sysconfig.get_python_inc(plat_specific=True) if py_pincl_dir not in include_dirs: include_dirs.append(py_pincl_dir) for d in default_include_dirs: d = os.path.join(d, os.path.basename(py_incl_dir)) if d not in include_dirs: include_dirs.append(d) system_info.__init__(self, default_lib_dirs=[], default_include_dirs=include_dirs) def calc_info(self): try: module = __import__(self.modulename) except ImportError: return info = {} macros = [] for v in ['__version__', 'version']: vrs = getattr(module, v, None) if vrs is None: continue macros = [(self.modulename.upper() + '_VERSION', '"\\"%s\\""' % (vrs)), (self.modulename.upper(), None)] break ## try: ## macros.append( ## (self.modulename.upper()+'_VERSION_HEX', ## hex(vstr2hex(module.__version__))), ## ) ## except Exception as msg: ## print msg dict_append(info, define_macros=macros) include_dirs = self.get_include_dirs() inc_dir = None for d in include_dirs: if self.combine_paths(d, os.path.join(self.modulename, 'arrayobject.h')): inc_dir = d break if inc_dir is not None: dict_append(info, include_dirs=[inc_dir]) if info: self.set_info(**info) return class numarray_info(_numpy_info): section = 'numarray' modulename = 'numarray' class Numeric_info(_numpy_info): section = 'Numeric' modulename = 'Numeric' class numpy_info(_numpy_info): section = 'numpy' modulename = 'numpy' class numerix_info(system_info): section = 'numerix' def calc_info(self): which = None, None if os.getenv("NUMERIX"): which = os.getenv("NUMERIX"), "environment var" # If all the above fail, default to numpy. if which[0] is None: which = "numpy", "defaulted" try: import numpy which = "numpy", "defaulted" except ImportError: msg1 = str(get_exception()) try: import Numeric which = "numeric", "defaulted" except ImportError: msg2 = str(get_exception()) try: import numarray which = "numarray", "defaulted" except ImportError: msg3 = str(get_exception()) log.info(msg1) log.info(msg2) log.info(msg3) which = which[0].strip().lower(), which[1] if which[0] not in ["numeric", "numarray", "numpy"]: raise ValueError("numerix selector must be either 'Numeric' " "or 'numarray' or 'numpy' but the value obtained" " from the %s was '%s'." % (which[1], which[0])) os.environ['NUMERIX'] = which[0] self.set_info(**get_info(which[0])) class f2py_info(system_info): def calc_info(self): try: import numpy.f2py as f2py except ImportError: return f2py_dir = os.path.join(os.path.dirname(f2py.__file__), 'src') self.set_info(sources=[os.path.join(f2py_dir, 'fortranobject.c')], include_dirs=[f2py_dir]) return class boost_python_info(system_info): section = 'boost_python' dir_env_var = 'BOOST' def get_paths(self, section, key): pre_dirs = system_info.get_paths(self, section, key) dirs = [] for d in pre_dirs: dirs.extend([d] + self.combine_paths(d, ['boost*'])) return [d for d in dirs if os.path.isdir(d)] def calc_info(self): src_dirs = self.get_src_dirs() src_dir = '' for d in src_dirs: if os.path.isfile(os.path.join(d, 'libs', 'python', 'src', 'module.cpp')): src_dir = d break if not src_dir: return py_incl_dirs = [distutils.sysconfig.get_python_inc()] py_pincl_dir = distutils.sysconfig.get_python_inc(plat_specific=True) if py_pincl_dir not in py_incl_dirs: py_incl_dirs.append(py_pincl_dir) srcs_dir = os.path.join(src_dir, 'libs', 'python', 'src') bpl_srcs = glob(os.path.join(srcs_dir, '*.cpp')) bpl_srcs += glob(os.path.join(srcs_dir, '*', '*.cpp')) info = {'libraries': [('boost_python_src', {'include_dirs': [src_dir] + py_incl_dirs, 'sources':bpl_srcs} )], 'include_dirs': [src_dir], } if info: self.set_info(**info) return class agg2_info(system_info): section = 'agg2' dir_env_var = 'AGG2' def get_paths(self, section, key): pre_dirs = system_info.get_paths(self, section, key) dirs = [] for d in pre_dirs: dirs.extend([d] + self.combine_paths(d, ['agg2*'])) return [d for d in dirs if os.path.isdir(d)] def calc_info(self): src_dirs = self.get_src_dirs() src_dir = '' for d in src_dirs: if os.path.isfile(os.path.join(d, 'src', 'agg_affine_matrix.cpp')): src_dir = d break if not src_dir: return if sys.platform == 'win32': agg2_srcs = glob(os.path.join(src_dir, 'src', 'platform', 'win32', 'agg_win32_bmp.cpp')) else: agg2_srcs = glob(os.path.join(src_dir, 'src', '*.cpp')) agg2_srcs += [os.path.join(src_dir, 'src', 'platform', 'X11', 'agg_platform_support.cpp')] info = {'libraries': [('agg2_src', {'sources': agg2_srcs, 'include_dirs': [os.path.join(src_dir, 'include')], } )], 'include_dirs': [os.path.join(src_dir, 'include')], } if info: self.set_info(**info) return class _pkg_config_info(system_info): section = None config_env_var = 'PKG_CONFIG' default_config_exe = 'pkg-config' append_config_exe = '' version_macro_name = None release_macro_name = None version_flag = '--modversion' cflags_flag = '--cflags' def get_config_exe(self): if self.config_env_var in os.environ: return os.environ[self.config_env_var] return self.default_config_exe def get_config_output(self, config_exe, option): cmd = config_exe + ' ' + self.append_config_exe + ' ' + option s, o = exec_command(cmd, use_tee=0) if not s: return o def calc_info(self): config_exe = find_executable(self.get_config_exe()) if not config_exe: log.warn('File not found: %s. Cannot determine %s info.' \ % (config_exe, self.section)) return info = {} macros = [] libraries = [] library_dirs = [] include_dirs = [] extra_link_args = [] extra_compile_args = [] version = self.get_config_output(config_exe, self.version_flag) if version: macros.append((self.__class__.__name__.split('.')[-1].upper(), '"\\"%s\\""' % (version))) if self.version_macro_name: macros.append((self.version_macro_name + '_%s' % (version.replace('.', '_')), None)) if self.release_macro_name: release = self.get_config_output(config_exe, '--release') if release: macros.append((self.release_macro_name + '_%s' % (release.replace('.', '_')), None)) opts = self.get_config_output(config_exe, '--libs') if opts: for opt in opts.split(): if opt[:2] == '-l': libraries.append(opt[2:]) elif opt[:2] == '-L': library_dirs.append(opt[2:]) else: extra_link_args.append(opt) opts = self.get_config_output(config_exe, self.cflags_flag) if opts: for opt in opts.split(): if opt[:2] == '-I': include_dirs.append(opt[2:]) elif opt[:2] == '-D': if '=' in opt: n, v = opt[2:].split('=') macros.append((n, v)) else: macros.append((opt[2:], None)) else: extra_compile_args.append(opt) if macros: dict_append(info, define_macros=macros) if libraries: dict_append(info, libraries=libraries) if library_dirs: dict_append(info, library_dirs=library_dirs) if include_dirs: dict_append(info, include_dirs=include_dirs) if extra_link_args: dict_append(info, extra_link_args=extra_link_args) if extra_compile_args: dict_append(info, extra_compile_args=extra_compile_args) if info: self.set_info(**info) return class wx_info(_pkg_config_info): section = 'wx' config_env_var = 'WX_CONFIG' default_config_exe = 'wx-config' append_config_exe = '' version_macro_name = 'WX_VERSION' release_macro_name = 'WX_RELEASE' version_flag = '--version' cflags_flag = '--cxxflags' class gdk_pixbuf_xlib_2_info(_pkg_config_info): section = 'gdk_pixbuf_xlib_2' append_config_exe = 'gdk-pixbuf-xlib-2.0' version_macro_name = 'GDK_PIXBUF_XLIB_VERSION' class gdk_pixbuf_2_info(_pkg_config_info): section = 'gdk_pixbuf_2' append_config_exe = 'gdk-pixbuf-2.0' version_macro_name = 'GDK_PIXBUF_VERSION' class gdk_x11_2_info(_pkg_config_info): section = 'gdk_x11_2' append_config_exe = 'gdk-x11-2.0' version_macro_name = 'GDK_X11_VERSION' class gdk_2_info(_pkg_config_info): section = 'gdk_2' append_config_exe = 'gdk-2.0' version_macro_name = 'GDK_VERSION' class gdk_info(_pkg_config_info): section = 'gdk' append_config_exe = 'gdk' version_macro_name = 'GDK_VERSION' class gtkp_x11_2_info(_pkg_config_info): section = 'gtkp_x11_2' append_config_exe = 'gtk+-x11-2.0' version_macro_name = 'GTK_X11_VERSION' class gtkp_2_info(_pkg_config_info): section = 'gtkp_2' append_config_exe = 'gtk+-2.0' version_macro_name = 'GTK_VERSION' class xft_info(_pkg_config_info): section = 'xft' append_config_exe = 'xft' version_macro_name = 'XFT_VERSION' class freetype2_info(_pkg_config_info): section = 'freetype2' append_config_exe = 'freetype2' version_macro_name = 'FREETYPE2_VERSION' class amd_info(system_info): section = 'amd' dir_env_var = 'AMD' _lib_names = ['amd'] def calc_info(self): lib_dirs = self.get_lib_dirs() amd_libs = self.get_libs('amd_libs', self._lib_names) info = self.check_libs(lib_dirs, amd_libs, []) if info is None: return include_dirs = self.get_include_dirs() inc_dir = None for d in include_dirs: p = self.combine_paths(d, 'amd.h') if p: inc_dir = os.path.dirname(p[0]) break if inc_dir is not None: dict_append(info, include_dirs=[inc_dir], define_macros=[('SCIPY_AMD_H', None)], swig_opts=['-I' + inc_dir]) self.set_info(**info) return class umfpack_info(system_info): section = 'umfpack' dir_env_var = 'UMFPACK' notfounderror = UmfpackNotFoundError _lib_names = ['umfpack'] def calc_info(self): lib_dirs = self.get_lib_dirs() umfpack_libs = self.get_libs('umfpack_libs', self._lib_names) info = self.check_libs(lib_dirs, umfpack_libs, []) if info is None: return include_dirs = self.get_include_dirs() inc_dir = None for d in include_dirs: p = self.combine_paths(d, ['', 'umfpack'], 'umfpack.h') if p: inc_dir = os.path.dirname(p[0]) break if inc_dir is not None: dict_append(info, include_dirs=[inc_dir], define_macros=[('SCIPY_UMFPACK_H', None)], swig_opts=['-I' + inc_dir]) amd = get_info('amd') dict_append(info, **get_info('amd')) self.set_info(**info) return ## def vstr2hex(version): ## bits = [] ## n = [24,16,8,4,0] ## r = 0 ## for s in version.split('.'): ## r |= int(s) << n[0] ## del n[0] ## return r #-------------------------------------------------------------------- def combine_paths(*args, **kws): """ Return a list of existing paths composed by all combinations of items from arguments. """ r = [] for a in args: if not a: continue if is_string(a): a = [a] r.append(a) args = r if not args: return [] if len(args) == 1: result = reduce(lambda a, b: a + b, map(glob, args[0]), []) elif len(args) == 2: result = [] for a0 in args[0]: for a1 in args[1]: result.extend(glob(os.path.join(a0, a1))) else: result = combine_paths(*(combine_paths(args[0], args[1]) + args[2:])) verbosity = kws.get('verbosity', 1) log.debug('(paths: %s)', ','.join(result)) return result language_map = {'c': 0, 'c++': 1, 'f77': 2, 'f90': 3} inv_language_map = {0: 'c', 1: 'c++', 2: 'f77', 3: 'f90'} def dict_append(d, **kws): languages = [] for k, v in kws.items(): if k == 'language': languages.append(v) continue if k in d: if k in ['library_dirs', 'include_dirs', 'define_macros']: [d[k].append(vv) for vv in v if vv not in d[k]] else: d[k].extend(v) else: d[k] = v if languages: l = inv_language_map[max([language_map.get(l, 0) for l in languages])] d['language'] = l return def parseCmdLine(argv=(None,)): import optparse parser = optparse.OptionParser("usage: %prog [-v] [info objs]") parser.add_option('-v', '--verbose', action='store_true', dest='verbose', default=False, help='be verbose and print more messages') opts, args = parser.parse_args(args=argv[1:]) return opts, args def show_all(argv=None): import inspect if argv is None: argv = sys.argv opts, args = parseCmdLine(argv) if opts.verbose: log.set_threshold(log.DEBUG) else: log.set_threshold(log.INFO) show_only = [] for n in args: if n[-5:] != '_info': n = n + '_info' show_only.append(n) show_all = not show_only _gdict_ = globals().copy() for name, c in _gdict_.items(): if not inspect.isclass(c): continue if not issubclass(c, system_info) or c is system_info: continue if not show_all: if name not in show_only: continue del show_only[show_only.index(name)] conf = c() conf.verbosity = 2 r = conf.get_info() if show_only: log.info('Info classes not defined: %s', ','.join(show_only)) if __name__ == "__main__": show_all() numpy-1.8.2/numpy/f2py/0000775000175100017510000000000012371375430016061 5ustar vagrantvagrant00000000000000numpy-1.8.2/numpy/f2py/docs/0000775000175100017510000000000012371375430017011 5ustar vagrantvagrant00000000000000numpy-1.8.2/numpy/f2py/docs/README.txt0000664000175100017510000003406412370216243020511 0ustar vagrantvagrant00000000000000.. -*- rest -*- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ F2PY: Fortran to Python interface generator ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Author: Pearu Peterson :License: NumPy License :Web-site: http://cens.ioc.ee/projects/f2py2e/ :Discussions to: `f2py-users mailing list`_ :Documentation: `User's Guide`__, FAQ__ :Platforms: All :Date: $Date: 2005/01/30 18:54:53 $ .. _f2py-users mailing list: http://cens.ioc.ee/mailman/listinfo/f2py-users/ __ usersguide/index.html __ FAQ.html ------------------------------- .. topic:: NEWS!!! January 5, 2006 WARNING -- these notes are out of date! The package structure for NumPy and SciPy has changed considerably. Much of this information is now incorrect. January 30, 2005 Latest F2PY release (version 2.45.241_1926). New features: wrapping unsigned integers, support for ``.pyf.src`` template files, callback arguments can now be CObjects, fortran objects, built-in functions. Introduced ``intent(aux)`` attribute. Wrapped objects have ``_cpointer`` attribute holding C pointer to wrapped functions or variables. Many bug fixes and improvements, updated documentation. `Differences with the previous release (version 2.43.239_1831)`__. __ http://cens.ioc.ee/cgi-bin/cvsweb/python/f2py2e/docs/HISTORY.txt.diff?r1=1.163&r2=1.137&f=h October 4, 2004 F2PY bug fix release (version 2.43.239_1831). Better support for 64-bit platforms. Introduced ``--help-link`` and ``--link-`` options. Bug fixes. `Differences with the previous release (version 2.43.239_1806)`__. __ http://cens.ioc.ee/cgi-bin/cvsweb/python/f2py2e/docs/HISTORY.txt.diff?r1=1.137&r2=1.131&f=h September 25, 2004 Latest F2PY release (version 2.43.239_1806). Support for ``ENTRY`` statement. New attributes: ``intent(inplace)``, ``intent(callback)``. Supports Numarray 1.1. Introduced ``-*- fix -*-`` header content. Improved ``PARAMETER`` support. Documentation updates. `Differences with the previous release (version 2.39.235-1693)`__. __ http://cens.ioc.ee/cgi-bin/cvsweb/python/f2py2e/docs/HISTORY.txt.diff?r1=1.131&r2=1.98&f=h `History of NEWS`__ __ OLDNEWS.html ------------------------------- .. Contents:: ============== Introduction ============== The purpose of the F2PY --*Fortran to Python interface generator*-- project is to provide connection between Python_ and Fortran languages. F2PY is a Python extension tool for creating Python C/API modules from (handwritten or F2PY generated) signature files (or directly from Fortran sources). The generated extension modules facilitate: * Calling Fortran 77/90/95, Fortran 90/95 module, and C functions from Python. * Accessing Fortran 77 ``COMMON`` blocks and Fortran 90/95 module data (including allocatable arrays) from Python. * Calling Python functions from Fortran or C (call-backs). * Automatically handling the difference in the data storage order of multi-dimensional Fortran and Numerical Python (i.e. C) arrays. In addition, F2PY can build the generated extension modules to shared libraries with one command. F2PY uses the ``numpy_distutils`` module from SciPy_ that supports number of major Fortran compilers. .. (see `COMPILERS.txt`_ for more information). F2PY generated extension modules depend on NumPy_ package that provides fast multi-dimensional array language facility to Python. --------------- Main features --------------- Here follows a more detailed list of F2PY features: * F2PY scans real Fortran codes to produce the so-called signature files (.pyf files). The signature files contain all the information (function names, arguments and their types, etc.) that is needed to construct Python bindings to Fortran (or C) functions. The syntax of signature files is borrowed from the Fortran 90/95 language specification and has some F2PY specific extensions. The signature files can be modified to dictate how Fortran (or C) programs are called from Python: + F2PY solves dependencies between arguments (this is relevant for the order of initializing variables in extension modules). + Arguments can be specified to be optional or hidden that simplifies calling Fortran programs from Python considerably. + In principle, one can design any Python signature for a given Fortran function, e.g. change the order arguments, introduce auxiliary arguments, hide the arguments, process the arguments before passing to Fortran, return arguments as output of F2PY generated functions, etc. * F2PY automatically generates __doc__ strings (and optionally LaTeX documentation) for extension modules. * F2PY generated functions accept arbitrary (but sensible) Python objects as arguments. The F2PY interface automatically takes care of type-casting and handling of non-contiguous arrays. * The following Fortran constructs are recognized by F2PY: + All basic Fortran types:: integer[ | *1 | *2 | *4 | *8 ], logical[ | *1 | *2 | *4 | *8 ] integer*([ -1 | -2 | -4 | -8 ]) character[ | *(*) | *1 | *2 | *3 | ... ] real[ | *4 | *8 | *16 ], double precision complex[ | *8 | *16 | *32 ] Negative ``integer`` kinds are used to wrap unsigned integers. + Multi-dimensional arrays of all basic types with the following dimension specifications:: | : | * | : + Attributes and statements:: intent([ in | inout | out | hide | in,out | inout,out | c | copy | cache | callback | inplace | aux ]) dimension() common, parameter allocatable optional, required, external depend([]) check([]) note() usercode, callstatement, callprotoargument, threadsafe, fortranname pymethoddef entry * Because there are only little (and easily handleable) differences between calling C and Fortran functions from F2PY generated extension modules, then F2PY is also well suited for wrapping C libraries to Python. * Practice has shown that F2PY generated interfaces (to C or Fortran functions) are less error prone and even more efficient than handwritten extension modules. The F2PY generated interfaces are easy to maintain and any future optimization of F2PY generated interfaces transparently apply to extension modules by just regenerating them with the latest version of F2PY. * `F2PY Users Guide and Reference Manual`_ =============== Prerequisites =============== F2PY requires the following software installed: * Python_ (versions 1.5.2 or later; 2.1 and up are recommended). You must have python-dev package installed. * NumPy_ (versions 13 or later; 20.x, 21.x, 22.x, 23.x are recommended) * Numarray_ (version 0.9 and up), optional, partial support. * Scipy_distutils (version 0.2.2 and up are recommended) from SciPy_ project. Get it from Scipy CVS or download it below. Python 1.x users also need distutils_. Of course, to build extension modules, you'll need also working C and/or Fortran compilers installed. ========== Download ========== You can download the sources for the latest F2PY and numpy_distutils releases as: * `2.x`__/`F2PY-2-latest.tar.gz`__ * `2.x`__/`numpy_distutils-latest.tar.gz`__ Windows users might be interested in Win32 installer for F2PY and Scipy_distutils (these installers are built using Python 2.3): * `2.x`__/`F2PY-2-latest.win32.exe`__ * `2.x`__/`numpy_distutils-latest.win32.exe`__ Older releases are also available in the directories `rel-0.x`__, `rel-1.x`__, `rel-2.x`__, `rel-3.x`__, `rel-4.x`__, `rel-5.x`__, if you need them. .. __: 2.x/ .. __: 2.x/F2PY-2-latest.tar.gz .. __: 2.x/ .. __: 2.x/numpy_distutils-latest.tar.gz .. __: 2.x/ .. __: 2.x/F2PY-2-latest.win32.exe .. __: 2.x/ .. __: 2.x/numpy_distutils-latest.win32.exe .. __: rel-0.x .. __: rel-1.x .. __: rel-2.x .. __: rel-3.x .. __: rel-4.x .. __: rel-5.x Development version of F2PY from CVS is available as `f2py2e.tar.gz`__. __ http://cens.ioc.ee/cgi-bin/viewcvs.cgi/python/f2py2e/f2py2e.tar.gz?tarball=1 Debian Sid users can simply install ``python-f2py`` package. ============== Installation ============== Unpack the source file, change to directrory ``F2PY-?-???/`` and run (you may need to become a root):: python setup.py install The F2PY installation installs a Python package ``f2py2e`` to your Python ``site-packages`` directory and a script ``f2py`` to your Python executable path. See also Installation__ section in `F2PY FAQ`_. .. __: FAQ.html#installation Similarly, to install ``numpy_distutils``, unpack its tar-ball and run:: python setup.py install ======= Usage ======= To check if F2PY is installed correctly, run :: f2py without any arguments. This should print out the usage information of the ``f2py`` program. Next, try out the following three steps: 1) Create a Fortran file `hello.f`__ that contains:: C File hello.f subroutine foo (a) integer a print*, "Hello from Fortran!" print*, "a=",a end __ hello.f 2) Run :: f2py -c -m hello hello.f This will build an extension module ``hello.so`` (or ``hello.sl``, or ``hello.pyd``, etc. depending on your platform) into the current directory. 3) Now in Python try:: >>> import hello >>> print hello.__doc__ >>> print hello.foo.__doc__ >>> hello.foo(4) Hello from Fortran! a= 4 >>> If the above works, then you can try out more thorough `F2PY unit tests`__ and read the `F2PY Users Guide and Reference Manual`_. __ FAQ.html#q-how-to-test-if-f2py-is-working-correctly =============== Documentation =============== The documentation of the F2PY project is collected in ``f2py2e/docs/`` directory. It contains the following documents: `README.txt`_ (in CVS__) The first thing to read about F2PY -- this document. __ http://cens.ioc.ee/cgi-bin/cvsweb/python/f2py2e/docs/README.txt?rev=HEAD&content-type=text/x-cvsweb-markup `usersguide/index.txt`_, `usersguide/f2py_usersguide.pdf`_ F2PY Users Guide and Reference Manual. Contains lots of examples. `FAQ.txt`_ (in CVS__) F2PY Frequently Asked Questions. __ http://cens.ioc.ee/cgi-bin/cvsweb/python/f2py2e/docs/FAQ.txt?rev=HEAD&content-type=text/x-cvsweb-markup `TESTING.txt`_ (in CVS__) About F2PY testing site. What tests are available and how to run them. __ http://cens.ioc.ee/cgi-bin/cvsweb/python/f2py2e/docs/TESTING.txt?rev=HEAD&content-type=text/x-cvsweb-markup `HISTORY.txt`_ (in CVS__) A list of latest changes in F2PY. This is the most up-to-date document on F2PY. __ http://cens.ioc.ee/cgi-bin/cvsweb/python/f2py2e/docs/HISTORY.txt?rev=HEAD&content-type=text/x-cvsweb-markup `THANKS.txt`_ Acknowledgments. .. `COMPILERS.txt`_ Compiler and platform specific notes. =============== Mailing list =============== A mailing list f2py-users@cens.ioc.ee is open for F2PY releated discussion/questions/etc. * `Subscribe..`__ * `Archives..`__ __ http://cens.ioc.ee/mailman/listinfo/f2py-users __ http://cens.ioc.ee/pipermail/f2py-users ===== CVS ===== F2PY is being developed under CVS_. The CVS version of F2PY can be obtained as follows: 1) First you need to login (the password is ``guest``):: cvs -d :pserver:anonymous@cens.ioc.ee:/home/cvs login 2) and then do the checkout:: cvs -z6 -d :pserver:anonymous@cens.ioc.ee:/home/cvs checkout f2py2e 3) You can update your local F2PY tree ``f2py2e/`` by executing:: cvs -z6 update -P -d You can browse the `F2PY CVS`_ repository. =============== Contributions =============== * `A short introduction to F2PY`__ by Pierre Schnizer. * `F2PY notes`__ by Fernando Perez. * `Debian packages of F2PY`__ by José Fonseca. [OBSOLETE, Debian Sid ships python-f2py package] __ http://fubphpc.tu-graz.ac.at/~pierre/f2py_tutorial.tar.gz __ http://cens.ioc.ee/pipermail/f2py-users/2003-April/000472.html __ http://jrfonseca.dyndns.org/debian/ =============== Related sites =============== * `Numerical Python`_ -- adds a fast array facility to the Python language. * Pyfort_ -- A Python-Fortran connection tool. * SciPy_ -- An open source library of scientific tools for Python. * `Scientific Python`_ -- A collection of Python modules that are useful for scientific computing. * `The Fortran Company`_ -- A place to find products, services, and general information related to the Fortran programming language. * `American National Standard Programming Language FORTRAN ANSI(R) X3.9-1978`__ * `J3`_ -- The US Fortran standards committee. * SWIG_ -- A software development tool that connects programs written in C and C++ with a variety of high-level programming languages. * `Mathtools.net`_ -- A technical computing portal for all scientific and engineering needs. .. __: http://www.fortran.com/fortran/F77_std/rjcnf.html .. References ========== .. _F2PY Users Guide and Reference Manual: usersguide/index.html .. _usersguide/index.txt: usersguide/index.html .. _usersguide/f2py_usersguide.pdf: usersguide/f2py_usersguide.pdf .. _README.txt: README.html .. _COMPILERS.txt: COMPILERS.html .. _F2PY FAQ: .. _FAQ.txt: FAQ.html .. _HISTORY.txt: HISTORY.html .. _HISTORY.txt from CVS: http://cens.ioc.ee/cgi-bin/cvsweb/python/f2py2e/docs/HISTORY.txt?rev=HEAD&content-type=text/x-cvsweb-markup .. _THANKS.txt: THANKS.html .. _TESTING.txt: TESTING.html .. _F2PY CVS2: http://cens.ioc.ee/cgi-bin/cvsweb/python/f2py2e/ .. _F2PY CVS: http://cens.ioc.ee/cgi-bin/viewcvs.cgi/python/f2py2e/ .. _CVS: http://www.cvshome.org/ .. _Python: http://www.python.org/ .. _SciPy: http://www.numpy.org/ .. _NumPy: http://www.numpy.org/ .. _Numarray: http://www.stsci.edu/resources/software_hardware/numarray .. _docutils: http://docutils.sourceforge.net/ .. _distutils: http://www.python.org/sigs/distutils-sig/ .. _Numerical Python: http://www.numpy.org/ .. _Pyfort: http://pyfortran.sourceforge.net/ .. _Scientific Python: http://starship.python.net/crew/hinsen/scientific.html .. _The Fortran Company: http://www.fortran.com/fortran/ .. _J3: http://www.j3-fortran.org/ .. _Mathtools.net: http://www.mathtools.net/ .. _SWIG: http://www.swig.org/ .. Local Variables: mode: indented-text indent-tabs-mode: nil sentence-end-double-space: t fill-column: 70 End: numpy-1.8.2/numpy/f2py/docs/pyforttest.pyf0000664000175100017510000000016312370216243021747 0ustar vagrantvagrant00000000000000subroutine foo(a,m,n) integer m = size(a,1) integer n = size(a,2) real, intent(inout) :: a(m,n) end subroutine foo numpy-1.8.2/numpy/f2py/docs/TESTING.txt0000664000175100017510000000604312370216243020665 0ustar vagrantvagrant00000000000000 ======================================================= F2PY unit testing site ======================================================= .. Contents:: Tests ----- * To run all F2PY unit tests in one command:: cd tests python run_all.py [] For example:: localhost:~/src_cvs/f2py2e/tests$ python2.2 run_all.py 100 --quiet ********************************************** Running '/usr/bin/python2.2 f77/return_integer.py 100 --quiet' run 1000 tests in 1.87 seconds initial virtual memory size: 3952640 bytes current virtual memory size: 3952640 bytes ok ********************************************** Running '/usr/bin/python2.2 f77/return_logical.py 100 --quiet' run 1000 tests in 1.47 seconds initial virtual memory size: 3952640 bytes current virtual memory size: 3952640 bytes ok ... If some tests fail, try to run the failing tests separately (without the ``--quiet`` option) as described below to get more information about the failure. * Test intent(in), intent(out) scalar arguments, scalars returned by F77 functions and F90 module functions:: tests/f77/return_integer.py tests/f77/return_real.py tests/f77/return_logical.py tests/f77/return_complex.py tests/f77/return_character.py tests/f90/return_integer.py tests/f90/return_real.py tests/f90/return_logical.py tests/f90/return_complex.py tests/f90/return_character.py Change to tests/ directory and run:: python f77/return_.py [] python f90/return_.py [] where ```` is integer, real, logical, complex, or character. Test scripts options are described below. A test is considered succesful if the last printed line is "ok". If you get import errors like:: ImportError: No module named f77_ext_return_integer but ``f77_ext_return_integer.so`` exists in the current directory then it means that the current directory is not included in to `sys.path` in your Python installation. As a fix, prepend ``.`` to ``PYTHONPATH`` environment variable and rerun the tests. For example:: PYTHONPATH=. python f77/return_integer.py * Test mixing Fortran 77, Fortran 90 fixed and free format codes:: tests/mixed/run.py * Test basic callback hooks:: tests/f77/callback.py Options ------- You may want to use the following options when running the test scripts: ```` Run tests ```` times. Useful for detecting memory leaks. Under Linux tests scripts output virtual memory size state of the process before and after calling the wrapped functions. ``--quiet`` Suppress all messages. On success only "ok" should be displayed. ``--fcompiler=`` Use:: f2py -c --help-fcompiler to find out what compilers are available (or more precisely, which ones are recognized by ``numpy_distutils``). Reporting failures ------------------ XXX: (1) make sure that failures are due to f2py and (2) send full stdout/stderr messages to me. Also add compiler,python,platform information. numpy-1.8.2/numpy/f2py/docs/hello.f0000664000175100017510000000017412370216243020260 0ustar vagrantvagrant00000000000000C File hello.f subroutine foo (a) integer a print*, "Hello from Fortran!" print*, "a=",a end numpy-1.8.2/numpy/f2py/docs/FAQ.txt0000664000175100017510000004760112370216243020164 0ustar vagrantvagrant00000000000000 ====================================================================== F2PY Frequently Asked Questions ====================================================================== .. contents:: General information =================== Q: How to get started? ---------------------- First, install__ F2PY. Then check that F2PY installation works properly (see below__). Try out a `simple example`__. Read `F2PY Users Guide and Reference Manual`__. It contains lots of complete examples. If you have any questions/problems when using F2PY, don't hesitate to turn to `F2PY users mailing list`__ or directly to me. __ index.html#installation __ #testing __ index.html#usage __ usersguide/index.html __ index.html#mailing-list Q: When to report bugs? ----------------------- * If F2PY scanning fails on Fortran sources that otherwise compile fine. * After checking that you have the latest version of F2PY from its CVS. It is possible that a bug has been fixed already. See also the log entries in the file `HISTORY.txt`_ (`HISTORY.txt in CVS`_). * After checking that your Python and Numerical Python installations work correctly. * After checking that your C and Fortran compilers work correctly. Q: How to report bugs? ---------------------- You can send bug reports directly to me. Please, include information about your platform (operating system, version) and compilers/linkers, e.g. the output (both stdout/stderr) of :: python -c 'import f2py2e.diagnose;f2py2e.diagnose.run()' Feel free to add any other relevant information. However, avoid sending the output of F2PY generated ``.pyf`` files (unless they are manually modified) or any binary files like shared libraries or object codes. While reporting bugs, you may find the following notes useful: * `How To Ask Questions The Smart Way`__ by E. S. Raymond and R. Moen. * `How to Report Bugs Effectively`__ by S. Tatham. __ http://www.catb.org/~esr/faqs/smart-questions.html __ http://www.chiark.greenend.org.uk/~sgtatham/bugs.html Installation ============ Q: How to use F2PY with different Python versions? -------------------------------------------------- Run the installation command using the corresponding Python executable. For example, :: python2.1 setup.py install installs the ``f2py`` script as ``f2py2.1``. See `Distutils User Documentation`__ for more information how to install Python modules to non-standard locations. __ http://www.python.org/sigs/distutils-sig/doc/inst/inst.html Q: Why F2PY is not working after upgrading? ------------------------------------------- If upgrading from F2PY version 2.3.321 or earlier then remove all f2py specific files from ``/path/to/python/bin`` directory before running installation command. Q: How to get/upgrade numpy_distutils when using F2PY from CVS? --------------------------------------------------------------- To get numpy_distutils from SciPy CVS repository, run :: cd cvs/f2py2e/ make numpy_distutils This will checkout numpy_distutils to the current directory. You can upgrade numpy_distutils by executing :: cd cvs/f2py2e/numpy_distutils cvs update -Pd and install it by executing :: cd cvs/f2py2e/numpy_distutils python setup_numpy_distutils.py install In most of the time, f2py2e and numpy_distutils can be upgraded independently. Testing ======= Q: How to test if F2PY is installed correctly? ---------------------------------------------- Run :: f2py without arguments. If F2PY is installed correctly then it should print the usage information for f2py. Q: How to test if F2PY is working correctly? -------------------------------------------- For a quick test, try out an example problem from Usage__ section in `README.txt`_. __ index.html#usage For running F2PY unit tests, see `TESTING.txt`_. Q: How to run tests and examples in f2py2e/test-suite/ directory? --------------------------------------------------------------------- You shouldn't. These tests are obsolete and I have no intention to make them work. They will be removed in future. Compiler/Platform-specific issues ================================= Q: What are supported platforms and compilers? ---------------------------------------------- F2PY is developed on Linux system with a GCC compiler (versions 2.95.x, 3.x). Fortran 90 related hooks are tested against Intel Fortran Compiler. F2PY should work under any platform where Python and Numeric are installed and has supported Fortran compiler installed. To see a list of supported compilers, execute:: f2py -c --help-fcompiler Example output:: List of available Fortran compilers: --fcompiler=gnu GNU Fortran Compiler (3.3.4) --fcompiler=intel Intel Fortran Compiler for 32-bit apps (8.0) List of unavailable Fortran compilers: --fcompiler=absoft Absoft Corp Fortran Compiler --fcompiler=compaq Compaq Fortran Compiler --fcompiler=compaqv DIGITAL|Compaq Visual Fortran Compiler --fcompiler=hpux HP Fortran 90 Compiler --fcompiler=ibm IBM XL Fortran Compiler --fcompiler=intele Intel Fortran Compiler for Itanium apps --fcompiler=intelev Intel Visual Fortran Compiler for Itanium apps --fcompiler=intelv Intel Visual Fortran Compiler for 32-bit apps --fcompiler=lahey Lahey/Fujitsu Fortran 95 Compiler --fcompiler=mips MIPSpro Fortran Compiler --fcompiler=nag NAGWare Fortran 95 Compiler --fcompiler=pg Portland Group Fortran Compiler --fcompiler=sun Sun|Forte Fortran 95 Compiler --fcompiler=vast Pacific-Sierra Research Fortran 90 Compiler List of unimplemented Fortran compilers: --fcompiler=f Fortran Company/NAG F Compiler For compiler details, run 'config_fc --verbose' setup command. Q: How to use the F compiler in F2PY? ------------------------------------- Read `f2py2e/doc/using_F_compiler.txt`__. It describes why the F compiler cannot be used in a normal way (i.e. using ``-c`` switch) to build F2PY generated modules. It also gives a workaround to this problem. __ http://cens.ioc.ee/cgi-bin/viewcvs.cgi/python/f2py2e/doc/using_F_compiler.txt?rev=HEAD&content-type=text/vnd.viewcvs-markup Q: How to use F2PY under Windows? --------------------------------- F2PY can be used both within Cygwin__ and MinGW__ environments under Windows, F2PY can be used also in Windows native terminal. See the section `Setting up environment`__ for Cygwin and MinGW. __ http://cygwin.com/ __ http://www.mingw.org/ __ http://cens.ioc.ee/~pearu/numpy/BUILD_WIN32.html#setting-up-environment Install numpy_distutils and F2PY. Win32 installers of these packages are provided in `F2PY Download`__ section. __ http://cens.ioc.ee/projects/f2py2e/#download Use ``--compiler=`` and ``--fcompiler`` F2PY command line switches to to specify which C and Fortran compilers F2PY should use, respectively. Under MinGW environment, ``mingw32`` is default for a C compiler. Supported and Unsupported Features ================================== Q: Does F2PY support ``ENTRY`` statements? ------------------------------------------ Yes, starting at F2PY version higher than 2.39.235_1706. Q: Does F2PY support derived types in F90 code? ----------------------------------------------- Not yet. However I do have plans to implement support for F90 TYPE constructs in future. But note that the task in non-trivial and may require the next edition of F2PY for which I don't have resources to work with at the moment. Jeffrey Hagelberg from LLNL has made progress on adding support for derived types to f2py. He writes: At this point, I have a version of f2py that supports derived types for most simple cases. I have multidimensional arrays of derived types and allocatable arrays of derived types working. I'm just now starting to work on getting nested derived types to work. I also haven't tried putting complex number in derived types yet. Hopefully he can contribute his changes to f2py soon. Q: Does F2PY support pointer data in F90 code? ----------------------------------------------- No. I have never needed it and I haven't studied if there are any obstacles to add pointer data support to F2PY. Q: What if Fortran 90 code uses ``(kind=KIND(..))``? --------------------------------------------------------------- Currently, F2PY can handle only ``(kind=)`` declarations where ```` is a numeric integer (e.g. 1, 2, 4,...) but not a function call ``KIND(..)`` or any other expression. F2PY needs to know what would be the corresponding C type and a general solution for that would be too complicated to implement. However, F2PY provides a hook to overcome this difficulty, namely, users can define their own to maps. For example, if Fortran 90 code contains:: REAL(kind=KIND(0.0D0)) ... then create a file ``.f2py_f2cmap`` (into the working directory) containing a Python dictionary:: {'real':{'KIND(0.0D0)':'double'}} for instance. Or more generally, the file ``.f2py_f2cmap`` must contain a dictionary with items:: : {:} that defines mapping between Fortran type:: ([kind=]) and the corresponding ````. ```` can be one of the following:: char signed_char short int long_long float double long_double complex_float complex_double complex_long_double string For more information, see ``f2py2e/capi_maps.py``. Related software ================ Q: How F2PY distinguishes from Pyfort? -------------------------------------- F2PY and Pyfort have very similar aims and ideology of how they are targeted. Both projects started to evolve in the same year 1999 independently. When we discovered each others projects, a discussion started to join the projects but that unfortunately failed for various reasons, e.g. both projects had evolved too far that merging the tools would have been impractical and giving up the efforts that the developers of both projects have made was unacceptable to both parties. And so, nowadays we have two tools for connecting Fortran with Python and this fact will hardly change in near future. To decide which one to choose is a matter of taste, I can only recommend to try out both to make up your choice. At the moment F2PY can handle more wrapping tasks than Pyfort, e.g. with F2PY one can wrap Fortran 77 common blocks, Fortran 90 module routines, Fortran 90 module data (including allocatable arrays), one can call Python from Fortran, etc etc. F2PY scans Fortran codes to create signature (.pyf) files. F2PY is free from most of the limitations listed in in `the corresponding section of Pyfort Reference Manual`__. __ http://pyfortran.sourceforge.net/pyfort/pyfort_reference.htm#pgfId-296925 There is a conceptual difference on how F2PY and Pyfort handle the issue of different data ordering in Fortran and C multi-dimensional arrays. Pyfort generated wrapper functions have optional arguments TRANSPOSE and MIRROR that can be used to control explicitly how the array arguments and their dimensions are passed to Fortran routine in order to deal with the C/Fortran data ordering issue. F2PY generated wrapper functions hide the whole issue from an end-user so that translation between Fortran and C/Python loops and array element access codes is one-to-one. How the F2PY generated wrappers deal with the issue is determined by a person who creates a signature file via using attributes like ``intent(c)``, ``intent(copy|overwrite)``, ``intent(inout|in,out|inplace)`` etc. For example, let's consider a typical usage of both F2PY and Pyfort when wrapping the following simple Fortran code: .. include:: simple.f :literal: The comment lines starting with ``cf2py`` are read by F2PY (so that we don't need to generate/handwrite an intermediate signature file in this simple case) while for a Fortran compiler they are just comment lines. And here is a Python version of the Fortran code: .. include:: pytest.py :literal: To generate a wrapper for subroutine ``foo`` using F2PY, execute:: $ f2py -m f2pytest simple.f -c that will generate an extension module ``f2pytest`` into the current directory. To generate a wrapper using Pyfort, create the following file .. include:: pyforttest.pyf :literal: and execute:: $ pyfort pyforttest In Pyfort GUI add ``simple.f`` to the list of Fortran sources and check that the signature file is in free format. And then copy ``pyforttest.so`` from the build directory to the current directory. Now, in Python .. include:: simple_session.dat :literal: Q: Can Pyfort .pyf files used with F2PY and vice versa? ------------------------------------------------------- After some simple modifications, yes. You should take into account the following differences in Pyfort and F2PY .pyf files. + F2PY signature file contains ``python module`` and ``interface`` blocks that are equivalent to Pyfort ``module`` block usage. + F2PY attribute ``intent(inplace)`` is equivalent to Pyfort ``intent(inout)``. F2PY ``intent(inout)`` is a strict (but safe) version of ``intent(inplace)``, any mismatch in arguments with expected type, size, or contiguouness will trigger an exception while ``intent(inplace)`` (dangerously) modifies arguments attributes in-place. Misc ==== Q: How to establish which Fortran compiler F2PY will use? --------------------------------------------------------- This question may be releavant when using F2PY in Makefiles. Here follows a script demonstrating how to determine which Fortran compiler and flags F2PY will use:: # Using post-0.2.2 numpy_distutils from numpy_distutils.fcompiler import new_fcompiler compiler = new_fcompiler() # or new_fcompiler(compiler='intel') compiler.dump_properties() # Using pre-0.2.2 numpy_distutils import os from numpy_distutils.command.build_flib import find_fortran_compiler def main(): fcompiler = os.environ.get('FC_VENDOR') fcompiler_exec = os.environ.get('F77') f90compiler_exec = os.environ.get('F90') fc = find_fortran_compiler(fcompiler, fcompiler_exec, f90compiler_exec, verbose = 0) print 'FC=',fc.f77_compiler print 'FFLAGS=',fc.f77_switches print 'FOPT=',fc.f77_opt if __name__ == "__main__": main() Users feedback ============== Q: Where to find additional information on using F2PY? ------------------------------------------------------ There are several F2PY related tutorials, slides, papers, etc available: + `Fortran to Python Interface Generator with an Application to Aerospace Engineering`__ by P. Peterson, J. R. R. A. Martins, and J. J. Alonso in `In Proceedings of the 9th International Python Conference`__, Long Beach, California, 2001. __ http://www.python9.org/p9-cdrom/07/index.htm __ http://www.python9.org/ + Section `Adding Fortran90 code`__ in the UG of `The Bolometer Data Analysis Project`__. __ http://www.astro.rub.de/laboca/download/boa_master_doc/7_4Adding_Fortran90_code.html __ http://www.openboa.de/ + Powerpoint presentation `Python for Scientific Computing`__ by Eric Jones in `The Ninth International Python Conference`__. __ http://www.python9.org/p9-jones.ppt __ http://www.python9.org/ + Paper `Scripting a Large Fortran Code with Python`__ by Alvaro Caceres Calleja in `International Workshop on Software Engineering for High Performance Computing System Applications`__. __ http://csdl.ics.hawaii.edu/se-hpcs/pdf/calleja.pdf __ http://csdl.ics.hawaii.edu/se-hpcs/ + Section `Automatic building of C/Fortran extension for Python`__ by Simon Lacoste-Julien in `Summer 2002 Report about Hybrid Systems Modelling`__. __ http://moncs.cs.mcgill.ca/people/slacoste/research/report/SummerReport.html#tth_sEc3.4 __ http://moncs.cs.mcgill.ca/people/slacoste/research/report/SummerReport.html + `Scripting for Computational Science`__ by Hans Petter Langtangen (see the `Mixed language programming`__ and `NumPy array programming`__ sections for examples on using F2PY). __ http://www.ifi.uio.no/~inf3330/lecsplit/ __ http://www.ifi.uio.no/~inf3330/lecsplit/slide662.html __ http://www.ifi.uio.no/~inf3330/lecsplit/slide718.html + Chapters 5 and 9 of `Python Scripting for Computational Science`__ by H. P. Langtangen for case studies on using F2PY. __ http://www.springeronline.com/3-540-43508-5 + Section `Fortran Wrapping`__ in `Continuity`__, a computational tool for continuum problems in bioengineering and physiology. __ http://www.continuity.ucsd.edu/cont6_html/docs_fram.html __ http://www.continuity.ucsd.edu/ + Presentation `PYFORT and F2PY: 2 ways to bind C and Fortran with Python`__ by Reiner Vogelsang. __ http://www.prism.enes.org/WPs/WP4a/Slides/pyfort/pyfort.html + Lecture slides of `Extending Python: speed it up`__. __ http://www.astro.uni-bonn.de/~heith/lecture_pdf/friedrich5.pdf + Wiki topics on `Wrapping Tools`__ and `Wrapping Bemchmarks`__ for Climate System Center at the University of Chicago. __ https://geodoc.uchicago.edu/climatewiki/DiscussWrappingTools __ https://geodoc.uchicago.edu/climatewiki/WrappingBenchmarks + `Performance Python with Weave`__ by Prabhu Ramachandran. __ http://www.numpy.org/documentation/weave/weaveperformance.html + `How To Install py-f2py on Mac OSX`__ __ http://py-f2py.darwinports.com/ Please, let me know if there are any other sites that document F2PY usage in one or another way. Q: What projects use F2PY? -------------------------- + `SciPy: Scientific tools for Python`__ __ http://www.numpy.org/ + `The Bolometer Data Analysis Project`__ __ http://www.openboa.de/ + `pywavelet`__ __ http://www.met.wau.nl/index.html?http://www.met.wau.nl/medewerkers/moenea/python/pywavelet.html + `PyARTS: an ARTS related Python package`__. __ http://www.met.ed.ac.uk/~cory/PyARTS/ + `Python interface to PSPLINE`__, a collection of Spline and Hermite interpolation tools for 1D, 2D, and 3D datasets on rectilinear grids. __ http://pypspline.sourceforge.net + `Markovian Analysis Package for Python`__. __ http://pymc.sourceforge.net + `Modular toolkit for Data Processing (MDP)`__ __ http://mdp-toolkit.sourceforge.net/ Please, send me a note if you are using F2PY in your project. Q: What people think about F2PY? -------------------------------- *F2PY is GOOD*: Here are some comments people have posted to f2py mailing list and c.l.py: + Ryan Krauss: I really appreciate f2py. It seems weird to say, but I am excited about relearning FORTRAN to compliment my python stuff. + Fabien Wahl: f2py is great, and is used extensively over here... + Fernando Perez: Anyway, many many thanks for this amazing tool. I haven't used pyfort, but I can definitely vouch for the amazing quality of f2py. And since f2py is actively used by numpy, it won't go unmaintained. It's quite impressive, and very easy to use. + Kevin Mueller: First off, thanks to those responsible for F2PY; its been an integral tool of my research for years now. + David Linke: Best regards and thanks for the great tool! + Perrin Meyer: F2Py is really useful! + Hans Petter Langtangen: First of all, thank you for developing F2py. This is a very important contribution to the scientific computing community. We are using F2py a lot and are very happy with it. + Berthold Höllmann: Thank's alot. It seems it is also working in my 'real' application :-) + John Hunter: At first I wrapped them with f2py (unbelievably easy!)... + Cameron Laird: Among many other features, Python boasts a mature f2py, which makes it particularly rewarding to yoke Fortran- and Python-coded modules into finished applications. + Ryan Gutenkunst: f2py is sweet magic. *F2PY is BAD*: + `Is it worth using on a large scale python drivers for Fortran subroutines, interfaced with f2py?`__ __ http://sepwww.stanford.edu/internal/computing/python.html Additional comments on F2PY, good or bad, are welcome! .. References: .. _README.txt: index.html .. _HISTORY.txt: HISTORY.html .. _HISTORY.txt in CVS: http://cens.ioc.ee/cgi-bin/cvsweb/python/f2py2e/docs/HISTORY.txt?rev=HEAD&content-type=text/x-cvsweb-markup .. _TESTING.txt: TESTING.html numpy-1.8.2/numpy/f2py/docs/simple_session.dat0000664000175100017510000000271212370216243022534 0ustar vagrantvagrant00000000000000>>> import pytest >>> import f2pytest >>> import pyforttest >>> print f2pytest.foo.__doc__ foo - Function signature: a = foo(a) Required arguments: a : input rank-2 array('f') with bounds (m,n) Return objects: a : rank-2 array('f') with bounds (m,n) >>> print pyforttest.foo.__doc__ foo(a) >>> pytest.foo([[1,2],[3,4]]) array([[12, 14], [24, 26]]) >>> f2pytest.foo([[1,2],[3,4]]) # F2PY can handle arbitrary input sequences array([[ 12., 14.], [ 24., 26.]],'f') >>> pyforttest.foo([[1,2],[3,4]]) Traceback (most recent call last): File "", line 1, in ? pyforttest.error: foo, argument A: Argument intent(inout) must be an array. >>> import Numeric >>> a=Numeric.array([[1,2],[3,4]],'f') >>> f2pytest.foo(a) array([[ 12., 14.], [ 24., 26.]],'f') >>> a # F2PY makes a copy when input array is not Fortran contiguous array([[ 1., 2.], [ 3., 4.]],'f') >>> a=Numeric.transpose(Numeric.array([[1,3],[2,4]],'f')) >>> a array([[ 1., 2.], [ 3., 4.]],'f') >>> f2pytest.foo(a) array([[ 12., 14.], [ 24., 26.]],'f') >>> a # F2PY passes Fortran contiguous input array directly to Fortran array([[ 12., 14.], [ 24., 26.]],'f') # See intent(copy), intent(overwrite), intent(inplace), intent(inout) # attributes documentation to enhance the above behavior. >>> a=Numeric.array([[1,2],[3,4]],'f') >>> pyforttest.foo(a) >>> a # Huh? Pyfort 8.5 gives wrong results.. array([[ 12., 23.], [ 15., 26.]],'f') numpy-1.8.2/numpy/f2py/docs/usersguide/0000775000175100017510000000000012371375430021170 5ustar vagrantvagrant00000000000000numpy-1.8.2/numpy/f2py/docs/usersguide/callback_session.dat0000664000175100017510000000071712370216243025161 0ustar vagrantvagrant00000000000000>>> import callback >>> print callback.foo.__doc__ foo - Function signature: r = foo(fun,[fun_extra_args]) Required arguments: fun : call-back function Optional arguments: fun_extra_args := () input tuple Return objects: r : float Call-back functions: def fun(i): return r Required arguments: i : input int Return objects: r : float >>> def f(i): return i*i ... >>> print callback.foo(f) 110.0 >>> print callback.foo(lambda i:1) 11.0 numpy-1.8.2/numpy/f2py/docs/usersguide/var_session.dat0000664000175100017510000000003412370216243024205 0ustar vagrantvagrant00000000000000>>> import var >>> var.BAR 5numpy-1.8.2/numpy/f2py/docs/usersguide/calculate_session.dat0000664000175100017510000000034412370216243025356 0ustar vagrantvagrant00000000000000>>> import foo >>> foo.calculate(range(5), lambda x: x*x) array([ 0., 1., 4., 9., 16.]) >>> import math >>> foo.calculate(range(5), math.exp) array([ 1. , 2.71828175, 7.38905621, 20.08553696, 54.59814835]) numpy-1.8.2/numpy/f2py/docs/usersguide/callback2.pyf0000664000175100017510000000072212370216243023522 0ustar vagrantvagrant00000000000000! -*- f90 -*- python module __user__routines interface function fun(i) result (r) integer :: i real*8 :: r end function fun end interface end python module __user__routines python module callback2 interface subroutine foo(f,r) use __user__routines, f=>fun external f real*8 intent(out) :: r end subroutine foo end interface end python module callback2 numpy-1.8.2/numpy/f2py/docs/usersguide/setup_example.py0000664000175100017510000000121512370216243024407 0ustar vagrantvagrant00000000000000#!/usr/bin/env python from __future__ import division, absolute_import, print_function # File: setup_example.py from numpy_distutils.core import Extension ext1 = Extension(name = 'scalar', sources = ['scalar.f']) ext2 = Extension(name = 'fib2', sources = ['fib2.pyf', 'fib1.f']) if __name__ == "__main__": from numpy_distutils.core import setup setup(name = 'f2py_example', description = "F2PY Users Guide examples", author = "Pearu Peterson", author_email = "pearu@cens.ioc.ee", ext_modules = [ext1, ext2] ) # End of setup_example.py numpy-1.8.2/numpy/f2py/docs/usersguide/array.f0000664000175100017510000000061712370216243022454 0ustar vagrantvagrant00000000000000C FILE: ARRAY.F SUBROUTINE FOO(A,N,M) C C INCREMENT THE FIRST ROW AND DECREMENT THE FIRST COLUMN OF A C INTEGER N,M,I,J REAL*8 A(N,M) Cf2py intent(in,out,copy) a Cf2py integer intent(hide),depend(a) :: n=shape(a,0), m=shape(a,1) DO J=1,M A(1,J) = A(1,J) + 1D0 ENDDO DO I=1,N A(I,1) = A(I,1) - 1D0 ENDDO END C END OF FILE ARRAY.F numpy-1.8.2/numpy/f2py/docs/usersguide/callback.f0000664000175100017510000000033212370216243023064 0ustar vagrantvagrant00000000000000C FILE: CALLBACK.F SUBROUTINE FOO(FUN,R) EXTERNAL FUN INTEGER I REAL*8 R Cf2py intent(out) r R = 0D0 DO I=-5,5 R = R + FUN(I) ENDDO END C END OF FILE CALLBACK.F numpy-1.8.2/numpy/f2py/docs/usersguide/spam_session.dat0000664000175100017510000000017412370216243024362 0ustar vagrantvagrant00000000000000>>> import spam >>> status = spam.system('whoami') pearu >> status = spam.system('blah') sh: line 1: blah: command not foundnumpy-1.8.2/numpy/f2py/docs/usersguide/common.f0000664000175100017510000000047612370216243022631 0ustar vagrantvagrant00000000000000C FILE: COMMON.F SUBROUTINE FOO INTEGER I,X REAL A COMMON /DATA/ I,X(4),A(2,3) PRINT*, "I=",I PRINT*, "X=[",X,"]" PRINT*, "A=[" PRINT*, "[",A(1,1),",",A(1,2),",",A(1,3),"]" PRINT*, "[",A(2,1),",",A(2,2),",",A(2,3),"]" PRINT*, "]" END C END OF COMMON.F numpy-1.8.2/numpy/f2py/docs/usersguide/array_session.dat0000664000175100017510000000354312370216243024543 0ustar vagrantvagrant00000000000000>>> import arr >>> from Numeric import array >>> print arr.foo.__doc__ foo - Function signature: a = foo(a,[overwrite_a]) Required arguments: a : input rank-2 array('d') with bounds (n,m) Optional arguments: overwrite_a := 0 input int Return objects: a : rank-2 array('d') with bounds (n,m) >>> a=arr.foo([[1,2,3], ... [4,5,6]]) copied an array using PyArray_CopyFromObject: size=6, elsize=8 >>> print a [[ 1. 3. 4.] [ 3. 5. 6.]] >>> a.iscontiguous(), arr.has_column_major_storage(a) (0, 1) >>> b=arr.foo(a) # even if a is proper-contiguous ... # and has proper type, a copy is made ... # forced by intent(copy) attribute ... # to preserve its original contents ... copied an array using copy_ND_array: size=6, elsize=8 >>> print a [[ 1. 3. 4.] [ 3. 5. 6.]] >>> print b [[ 1. 4. 5.] [ 2. 5. 6.]] >>> b=arr.foo(a,overwrite_a=1) # a is passed directly to Fortran ... # routine and its contents is discarded ... >>> print a [[ 1. 4. 5.] [ 2. 5. 6.]] >>> print b [[ 1. 4. 5.] [ 2. 5. 6.]] >>> a is b # a and b are acctually the same objects 1 >>> print arr.foo([1,2,3]) # different rank arrays are allowed copied an array using PyArray_CopyFromObject: size=3, elsize=8 [ 1. 1. 2.] >>> print arr.foo([[[1],[2],[3]]]) copied an array using PyArray_CopyFromObject: size=3, elsize=8 [ [[ 1.] [ 3.] [ 4.]]] >>> >>> # Creating arrays with column major data storage order: ... >>> s = arr.as_column_major_storage(array([[1,2,3],[4,5,6]])) copied an array using copy_ND_array: size=6, elsize=4 >>> arr.has_column_major_storage(s) 1 >>> print s [[1 2 3] [4 5 6]] >>> s2 = arr.as_column_major_storage(s) >>> s2 is s # an array with column major storage order # is returned immediately 1numpy-1.8.2/numpy/f2py/docs/usersguide/allocarr_session.dat0000664000175100017510000000150712370216243025222 0ustar vagrantvagrant00000000000000>>> import allocarr >>> print allocarr.mod.__doc__ b - 'f'-array(-1,-1), not allocated foo - Function signature: foo() >>> allocarr.mod.foo() b is not allocated >>> allocarr.mod.b = [[1,2,3],[4,5,6]] # allocate/initialize b >>> allocarr.mod.foo() b=[ 1.000000 2.000000 3.000000 4.000000 5.000000 6.000000 ] >>> allocarr.mod.b # b is Fortran-contiguous array([[ 1., 2., 3.], [ 4., 5., 6.]],'f') >>> allocarr.mod.b = [[1,2,3],[4,5,6],[7,8,9]] # reallocate/initialize b >>> allocarr.mod.foo() b=[ 1.000000 2.000000 3.000000 4.000000 5.000000 6.000000 7.000000 8.000000 9.000000 ] >>> allocarr.mod.b = None # deallocate array >>> allocarr.mod.foo() b is not allocated numpy-1.8.2/numpy/f2py/docs/usersguide/string_session.dat0000664000175100017510000000107412370216243024730 0ustar vagrantvagrant00000000000000>>> import mystring >>> print mystring.foo.__doc__ foo - Function signature: foo(a,b,c,d) Required arguments: a : input string(len=5) b : in/output rank-0 array(string(len=5),'c') c : input string(len=-1) d : in/output rank-0 array(string(len=-1),'c') >>> import Numeric >>> a=Numeric.array('123') >>> b=Numeric.array('123') >>> c=Numeric.array('123') >>> d=Numeric.array('123') >>> mystring.foo(a,b,c,d) A=123 B=123 C=123 D=123 CHANGE A,B,C,D A=A23 B=B23 C=C23 D=D23 >>> a.tostring(),b.tostring(),c.tostring(),d.tostring() ('123', 'B23', '123', 'D23')numpy-1.8.2/numpy/f2py/docs/usersguide/fib3.f0000664000175100017510000000062412370216243022157 0ustar vagrantvagrant00000000000000C FILE: FIB3.F SUBROUTINE FIB(A,N) C C CALCULATE FIRST N FIBONACCI NUMBERS C INTEGER N REAL*8 A(N) Cf2py intent(in) n Cf2py intent(out) a Cf2py depend(n) a DO I=1,N IF (I.EQ.1) THEN A(I) = 0.0D0 ELSEIF (I.EQ.2) THEN A(I) = 1.0D0 ELSE A(I) = A(I-1) + A(I-2) ENDIF ENDDO END C END FILE FIB3.F numpy-1.8.2/numpy/f2py/docs/usersguide/extcallback_session.dat0000664000175100017510000000061612370216243025700 0ustar vagrantvagrant00000000000000>>> import pfromf >>> pfromf.f2() Traceback (most recent call last): File "", line 1, in ? pfromf.error: Callback fpy not defined (as an argument or module pfromf attribute). >>> def f(): print "python f" ... >>> pfromf.fpy = f >>> pfromf.f2() in f2, calling f2py.. python f >>> pfromf.f1() in f1, calling f2 twice.. in f2, calling f2py.. python f in f2, calling f2py.. python f >>> numpy-1.8.2/numpy/f2py/docs/usersguide/allocarr.f900000664000175100017510000000050512370216243023302 0ustar vagrantvagrant00000000000000module mod real, allocatable, dimension(:,:) :: b contains subroutine foo integer k if (allocated(b)) then print*, "b=[" do k = 1,size(b,1) print*, b(k,1:size(b,2)) enddo print*, "]" else print*, "b is not allocated" endif end subroutine foo end module mod numpy-1.8.2/numpy/f2py/docs/usersguide/fib1.pyf0000664000175100017510000000061512370216243022526 0ustar vagrantvagrant00000000000000! -*- f90 -*- python module fib2 ! in interface ! in :fib2 subroutine fib(a,n) ! in :fib2:fib1.f real*8 dimension(n) :: a integer optional,check(len(a)>=n),depend(a) :: n=len(a) end subroutine fib end interface end python module fib2 ! This file was auto-generated with f2py (version:2.28.198-1366). ! See http://cens.ioc.ee/projects/f2py2e/ numpy-1.8.2/numpy/f2py/docs/usersguide/common_session.dat0000664000175100017510000000076012370216243024713 0ustar vagrantvagrant00000000000000>>> import common >>> print common.data.__doc__ i - 'i'-scalar x - 'i'-array(4) a - 'f'-array(2,3) >>> common.data.i = 5 >>> common.data.x[1] = 2 >>> common.data.a = [[1,2,3],[4,5,6]] >>> common.foo() I= 5 X=[ 0 2 0 0] A=[ [ 1., 2., 3.] [ 4., 5., 6.] ] >>> common.data.a[1] = 45 >>> common.foo() I= 5 X=[ 0 2 0 0] A=[ [ 1., 2., 3.] [ 45., 45., 45.] ] >>> common.data.a # a is Fortran-contiguous array([[ 1., 2., 3.], [ 45., 45., 45.]],'f') numpy-1.8.2/numpy/f2py/docs/usersguide/fib2.pyf0000664000175100017510000000036312370216243022527 0ustar vagrantvagrant00000000000000! -*- f90 -*- python module fib2 interface subroutine fib(a,n) real*8 dimension(n),intent(out),depend(n) :: a integer intent(in) :: n end subroutine fib end interface end python module fib2 numpy-1.8.2/numpy/f2py/docs/usersguide/spam.pyf0000664000175100017510000000072712370216243022651 0ustar vagrantvagrant00000000000000! -*- f90 -*- python module spam usercode ''' static char doc_spam_system[] = "Execute a shell command."; static PyObject *spam_system(PyObject *self, PyObject *args) { char *command; int sts; if (!PyArg_ParseTuple(args, "s", &command)) return NULL; sts = system(command); return Py_BuildValue("i", sts); } ''' pymethoddef ''' {"system", spam_system, METH_VARARGS, doc_spam_system}, ''' end python module spam numpy-1.8.2/numpy/f2py/docs/usersguide/default.css0000664000175100017510000000605112370216243023323 0ustar vagrantvagrant00000000000000/* :Author: David Goodger :Contact: goodger@users.sourceforge.net :date: $Date: 2002/12/07 23:59:33 $ :version: $Revision: 1.2 $ :copyright: This stylesheet has been placed in the public domain. Default cascading style sheet for the HTML output of Docutils. */ body { background: #FFFFFF ; color: #000000 } a.footnote-reference { font-size: smaller ; vertical-align: super } a.target { color: blue } a.toc-backref { text-decoration: none ; color: black } dd { margin-bottom: 0.5em } div.abstract { margin: 2em 5em } div.abstract p.topic-title { font-weight: bold ; text-align: center } div.attention, div.caution, div.danger, div.error, div.hint, div.important, div.note, div.tip, div.warning { margin: 2em ; border: medium outset ; padding: 1em } div.attention p.admonition-title, div.caution p.admonition-title, div.danger p.admonition-title, div.error p.admonition-title, div.warning p.admonition-title { color: red ; font-weight: bold ; font-family: sans-serif } div.hint p.admonition-title, div.important p.admonition-title, div.note p.admonition-title, div.tip p.admonition-title { font-weight: bold ; font-family: sans-serif } div.dedication { margin: 2em 5em ; text-align: center ; font-style: italic } div.dedication p.topic-title { font-weight: bold ; font-style: normal } div.figure { margin-left: 2em } div.footer, div.header { font-size: smaller } div.system-messages { margin: 5em } div.system-messages h1 { color: red } div.system-message { border: medium outset ; padding: 1em } div.system-message p.system-message-title { color: red ; font-weight: bold } div.topic { margin: 2em } h1.title { text-align: center } h2.subtitle { text-align: center } hr { width: 75% } ol.simple, ul.simple { margin-bottom: 1em } ol.arabic { list-style: decimal } ol.loweralpha { list-style: lower-alpha } ol.upperalpha { list-style: upper-alpha } ol.lowerroman { list-style: lower-roman } ol.upperroman { list-style: upper-roman } p.caption { font-style: italic } p.credits { font-style: italic ; font-size: smaller } p.first { margin-top: 0 } p.label { white-space: nowrap } p.topic-title { font-weight: bold } pre.literal-block, pre.doctest-block { margin-left: 2em ; margin-right: 2em ; background-color: #ee9e9e } span.classifier { font-family: sans-serif ; font-style: oblique } span.classifier-delimiter { font-family: sans-serif ; font-weight: bold } span.field-argument { font-style: italic } span.interpreted { font-family: sans-serif } span.option-argument { font-style: italic } span.problematic { color: red } table { margin-top: 0.5em ; margin-bottom: 0.5em } table.citation { border-left: solid thin gray ; padding-left: 0.5ex } table.docinfo { margin: 2em 4em } table.footnote { border-left: solid thin black ; padding-left: 0.5ex } td, th { padding-left: 0.5em ; padding-right: 0.5em ; vertical-align: baseline } td.docinfo-name { font-weight: bold ; text-align: right } td.field-name { font-weight: bold } numpy-1.8.2/numpy/f2py/docs/usersguide/calculate.f0000664000175100017510000000046512370216243023274 0ustar vagrantvagrant00000000000000 subroutine calculate(x,n) cf2py intent(callback) func external func c The following lines define the signature of func for F2PY: cf2py real*8 y cf2py y = func(y) c cf2py intent(in,out,copy) x integer n,i real*8 x(n) do i=1,n x(i) = func(x(i)) end do end numpy-1.8.2/numpy/f2py/docs/usersguide/scalar.f0000664000175100017510000000041712370216243022601 0ustar vagrantvagrant00000000000000C FILE: SCALAR.F SUBROUTINE FOO(A,B) REAL*8 A, B Cf2py intent(in) a Cf2py intent(inout) b PRINT*, " A=",A," B=",B PRINT*, "INCREMENT A AND B" A = A + 1D0 B = B + 1D0 PRINT*, "NEW A=",A," B=",B END C END OF FILE SCALAR.F numpy-1.8.2/numpy/f2py/docs/usersguide/extcallback.f0000664000175100017510000000046312370216243023612 0ustar vagrantvagrant00000000000000 subroutine f1() print *, "in f1, calling f2 twice.." call f2() call f2() return end subroutine f2() cf2py intent(callback, hide) fpy external fpy print *, "in f2, calling f2py.." call fpy() return end numpy-1.8.2/numpy/f2py/docs/usersguide/fib1.f0000664000175100017510000000053312370216243022154 0ustar vagrantvagrant00000000000000C FILE: FIB1.F SUBROUTINE FIB(A,N) C C CALCULATE FIRST N FIBONACCI NUMBERS C INTEGER N REAL*8 A(N) DO I=1,N IF (I.EQ.1) THEN A(I) = 0.0D0 ELSEIF (I.EQ.2) THEN A(I) = 1.0D0 ELSE A(I) = A(I-1) + A(I-2) ENDIF ENDDO END C END FILE FIB1.F numpy-1.8.2/numpy/f2py/docs/usersguide/scalar_session.dat0000664000175100017510000000075012370216243024667 0ustar vagrantvagrant00000000000000>>> import scalar >>> print scalar.foo.__doc__ foo - Function signature: foo(a,b) Required arguments: a : input float b : in/output rank-0 array(float,'d') >>> scalar.foo(2,3) A= 2. B= 3. INCREMENT A AND B NEW A= 3. B= 4. >>> import Numeric >>> a=Numeric.array(2) # these are integer rank-0 arrays >>> b=Numeric.array(3) >>> scalar.foo(a,b) A= 2. B= 3. INCREMENT A AND B NEW A= 3. B= 4. >>> print a,b # note that only b is changed in situ 2 4numpy-1.8.2/numpy/f2py/docs/usersguide/index.txt0000664000175100017510000016102412370216243023037 0ustar vagrantvagrant00000000000000.. -*- rest -*- ////////////////////////////////////////////////////////////////////// F2PY Users Guide and Reference Manual ////////////////////////////////////////////////////////////////////// :Author: Pearu Peterson :Contact: pearu@cens.ioc.ee :Web site: http://cens.ioc.ee/projects/f2py2e/ :Date: $Date: 2005/04/02 10:03:26 $ :Revision: $Revision: 1.27 $ .. section-numbering:: .. Contents:: ================ Introduction ================ The purpose of the F2PY_ --*Fortran to Python interface generator*-- project is to provide a connection between Python and Fortran languages. F2PY is a Python_ package (with a command line tool ``f2py`` and a module ``f2py2e``) that facilitates creating/building Python C/API extension modules that make it possible * to call Fortran 77/90/95 external subroutines and Fortran 90/95 module subroutines as well as C functions; * to access Fortran 77 ``COMMON`` blocks and Fortran 90/95 module data, including allocatable arrays from Python. See F2PY_ web site for more information and installation instructions. ====================================== Three ways to wrap - getting started ====================================== Wrapping Fortran or C functions to Python using F2PY consists of the following steps: * Creating the so-called signature file that contains descriptions of wrappers to Fortran or C functions, also called as signatures of the functions. In the case of Fortran routines, F2PY can create initial signature file by scanning Fortran source codes and catching all relevant information needed to create wrapper functions. * Optionally, F2PY created signature files can be edited to optimize wrappers functions, make them "smarter" and more "Pythonic". * F2PY reads a signature file and writes a Python C/API module containing Fortran/C/Python bindings. * F2PY compiles all sources and builds an extension module containing the wrappers. In building extension modules, F2PY uses ``numpy_distutils`` that supports a number of Fortran 77/90/95 compilers, including Gnu, Intel, Sun Fortre, SGI MIPSpro, Absoft, NAG, Compaq etc. compilers. Depending on a particular situation, these steps can be carried out either by just in one command or step-by-step, some steps can be ommited or combined with others. Below I'll describe three typical approaches of using F2PY. The following `example Fortran 77 code`__ will be used for illustration: .. include:: fib1.f :literal: __ fib1.f The quick way ============== The quickest way to wrap the Fortran subroutine ``FIB`` to Python is to run :: f2py -c fib1.f -m fib1 This command builds (see ``-c`` flag, execute ``f2py`` without arguments to see the explanation of command line options) an extension module ``fib1.so`` (see ``-m`` flag) to the current directory. Now, in Python the Fortran subroutine ``FIB`` is accessible via ``fib1.fib``:: >>> import Numeric >>> import fib1 >>> print fib1.fib.__doc__ fib - Function signature: fib(a,[n]) Required arguments: a : input rank-1 array('d') with bounds (n) Optional arguments: n := len(a) input int >>> a=Numeric.zeros(8,'d') >>> fib1.fib(a) >>> print a [ 0. 1. 1. 2. 3. 5. 8. 13.] .. topic:: Comments * Note that F2PY found that the second argument ``n`` is the dimension of the first array argument ``a``. Since by default all arguments are input-only arguments, F2PY concludes that ``n`` can be optional with the default value ``len(a)``. * One can use different values for optional ``n``:: >>> a1=Numeric.zeros(8,'d') >>> fib1.fib(a1,6) >>> print a1 [ 0. 1. 1. 2. 3. 5. 0. 0.] but an exception is raised when it is incompatible with the input array ``a``:: >>> fib1.fib(a,10) fib:n=10 Traceback (most recent call last): File "", line 1, in ? fib.error: (len(a)>=n) failed for 1st keyword n >>> This demonstrates one of the useful features in F2PY, that it, F2PY implements basic compatibility checks between related arguments in order to avoid any unexpected crashes. * When a Numeric array, that is Fortran contiguous and has a typecode corresponding to presumed Fortran type, is used as an input array argument, then its C pointer is directly passed to Fortran. Otherwise F2PY makes a contiguous copy (with a proper typecode) of the input array and passes C pointer of the copy to Fortran subroutine. As a result, any possible changes to the (copy of) input array have no effect to the original argument, as demonstrated below:: >>> a=Numeric.ones(8,'i') >>> fib1.fib(a) >>> print a [1 1 1 1 1 1 1 1] Clearly, this is not an expected behaviour. The fact that the above example worked with ``typecode='d'`` is considered accidental. F2PY provides ``intent(inplace)`` attribute that would modify the attributes of an input array so that any changes made by Fortran routine will be effective also in input argument. For example, if one specifies ``intent(inplace) a`` (see below, how), then the example above would read: >>> a=Numeric.ones(8,'i') >>> fib1.fib(a) >>> print a [ 0. 1. 1. 2. 3. 5. 8. 13.] However, the recommended way to get changes made by Fortran subroutine back to python is to use ``intent(out)`` attribute. It is more efficient and a cleaner solution. * The usage of ``fib1.fib`` in Python is very similar to using ``FIB`` in Fortran. However, using *in situ* output arguments in Python indicates a poor style as there is no safety mechanism in Python with respect to wrong argument types. When using Fortran or C, compilers naturally discover any type mismatches during compile time but in Python the types must be checked in runtime. So, using *in situ* output arguments in Python may cause difficult to find bugs, not to mention that the codes will be less readable when all required type checks are implemented. Though the demonstrated way of wrapping Fortran routines to Python is very straightforward, it has several drawbacks (see the comments above). These drawbacks are due to the fact that there is no way that F2PY can determine what is the acctual intention of one or the other argument, is it input or output argument, or both, or something else. So, F2PY conservatively assumes that all arguments are input arguments by default. However, there are ways (see below) how to "teach" F2PY about the true intentions (among other things) of function arguments; and then F2PY is able to generate more Pythonic (more explicit, easier to use, and less error prone) wrappers to Fortran functions. The smart way ============== Let's apply the steps of wrapping Fortran functions to Python one by one. * First, we create a signature file from ``fib1.f`` by running :: f2py fib1.f -m fib2 -h fib1.pyf The signature file is saved to ``fib1.pyf`` (see ``-h`` flag) and its contents is shown below. .. include:: fib1.pyf :literal: * Next, we'll teach F2PY that the argument ``n`` is a input argument (use ``intent(in)`` attribute) and that the result, i.e. the contents of ``a`` after calling Fortran function ``FIB``, should be returned to Python (use ``intent(out)`` attribute). In addition, an array ``a`` should be created dynamically using the size given by the input argument ``n`` (use ``depend(n)`` attribute to indicate dependence relation). The content of a modified version of ``fib1.pyf`` (saved as ``fib2.pyf``) is as follows: .. include:: fib2.pyf :literal: * And finally, we build the extension module by running :: f2py -c fib2.pyf fib1.f In Python:: >>> import fib2 >>> print fib2.fib.__doc__ fib - Function signature: a = fib(n) Required arguments: n : input int Return objects: a : rank-1 array('d') with bounds (n) >>> print fib2.fib(8) [ 0. 1. 1. 2. 3. 5. 8. 13.] .. topic:: Comments * Clearly, the signature of ``fib2.fib`` now corresponds to the intention of Fortran subroutine ``FIB`` more closely: given the number ``n``, ``fib2.fib`` returns the first ``n`` Fibonacci numbers as a Numeric array. Also, the new Python signature ``fib2.fib`` rules out any surprises that we experienced with ``fib1.fib``. * Note that by default using single ``intent(out)`` also implies ``intent(hide)``. Argument that has ``intent(hide)`` attribute specified, will not be listed in the argument list of a wrapper function. The quick and smart way ======================== The "smart way" of wrapping Fortran functions, as explained above, is suitable for wrapping (e.g. third party) Fortran codes for which modifications to their source codes are not desirable nor even possible. However, if editing Fortran codes is acceptable, then the generation of an intermediate signature file can be skipped in most cases. Namely, F2PY specific attributes can be inserted directly to Fortran source codes using the so-called F2PY directive. A F2PY directive defines special comment lines (starting with ``Cf2py``, for example) which are ignored by Fortran compilers but F2PY interprets them as normal lines. Here is shown a `modified version of the example Fortran code`__, saved as ``fib3.f``: .. include:: fib3.f :literal: __ fib3.f Building the extension module can be now carried out in one command:: f2py -c -m fib3 fib3.f Notice that the resulting wrapper to ``FIB`` is as "smart" as in previous case:: >>> import fib3 >>> print fib3.fib.__doc__ fib - Function signature: a = fib(n) Required arguments: n : input int Return objects: a : rank-1 array('d') with bounds (n) >>> print fib3.fib(8) [ 0. 1. 1. 2. 3. 5. 8. 13.] ================== Signature file ================== The syntax specification for signature files (.pyf files) is borrowed from the Fortran 90/95 language specification. Almost all Fortran 90/95 standard constructs are understood, both in free and fixed format (recall that Fortran 77 is a subset of Fortran 90/95). F2PY introduces also some extensions to Fortran 90/95 language specification that help designing Fortran to Python interface, make it more "Pythonic". Signature files may contain arbitrary Fortran code (so that Fortran codes can be considered as signature files). F2PY silently ignores Fortran constructs that are irrelevant for creating the interface. However, this includes also syntax errors. So, be careful not making ones;-). In general, the contents of signature files is case-sensitive. When scanning Fortran codes and writing a signature file, F2PY lowers all cases automatically except in multi-line blocks or when ``--no-lower`` option is used. The syntax of signature files is overvied below. Python module block ===================== A signature file may contain one (recommended) or more ``python module`` blocks. ``python module`` block describes the contents of a Python/C extension module ``module.c`` that F2PY generates. Exception: if ```` contains a substring ``__user__``, then the corresponding ``python module`` block describes the signatures of so-called call-back functions (see `Call-back arguments`_). A ``python module`` block has the following structure:: python module []... [ interface end [interface] ]... [ interface module [] [] end [module []] end [interface] ]... end [python module []] Here brackets ``[]`` indicate a optional part, dots ``...`` indicate one or more of a previous part. So, ``[]...`` reads zero or more of a previous part. Fortran/C routine signatures ============================= The signature of a Fortran routine has the following structure:: [] function | subroutine \ [ ( [] ) ] [ result ( ) ] [] [] [] [] [] end [ function | subroutine [] ] From a Fortran routine signature F2PY generates a Python/C extension function that has the following signature:: def ([,]): ... return The signature of a Fortran block data has the following structure:: block data [ ] [] [] [] [] [] end [ block data [] ] Type declarations ------------------- The definition of the ```` part is :: [ [] :: ] where :: := byte | character [] | complex [] | real [] | double complex | double precision | integer [] | logical [] := * | ( [len=] [ , [kind=] ] ) | ( kind= [ , len= ] ) := * | ( [kind=] ) := [ [ * ] [ ( ) ] | [ ( ) ] * ] | [ / / | = ] \ [ , ] and + ```` is a comma separated list of attributes_; + ```` is a comma separated list of dimension bounds; + ```` is a `C expression`__. + ```` may be negative integer for ``integer`` type specifications. In such cases ``integer*`` represents unsigned C integers. __ `C expressions`_ If an argument has no ````, its type is determined by applying ``implicit`` rules to its name. Statements ------------ Attribute statements: The ```` is ```` without ````. In addition, in an attribute statement one cannot use other attributes, also ```` can be only a list of names. Use statements: The definition of the ```` part is :: use [ , | , ONLY : ] where :: := => [ , ] Currently F2PY uses ``use`` statement only for linking call-back modules and ``external`` arguments (call-back functions), see `Call-back arguments`_. Common block statements: The definition of the ```` part is :: common / / where :: := [ ( ) ] [ , ] One ``python module`` block should not contain two or more ``common`` blocks with the same name. Otherwise, the latter ones are ignored. The types of variables in ```` are defined using ````. Note that the corresponding ```` may contain array specifications; then you don't need to specify these in ````. Other statements: The ```` part refers to any other Fortran language constructs that are not described above. F2PY ignores most of them except + ``call`` statements and function calls of ``external`` arguments (`more details`__?); __ external_ + ``include`` statements :: include '' include "" If a file ```` does not exist, the ``include`` statement is ignored. Otherwise, the file ```` is included to a signature file. ``include`` statements can be used in any part of a signature file, also outside the Fortran/C routine signature blocks. + ``implicit`` statements :: implicit none implicit where :: := ( ) Implicit rules are used to deterimine the type specification of a variable (from the first-letter of its name) if the variable is not defined using ````. Default implicit rule is given by :: implicit real (a-h,o-z,$_), integer (i-m) + ``entry`` statements :: entry [([])] F2PY generates wrappers to all entry names using the signature of the routine block. Tip: ``entry`` statement can be used to describe the signature of an arbitrary routine allowing F2PY to generate a number of wrappers from only one routine block signature. There are few restrictions while doing this: ``fortranname`` cannot be used, ``callstatement`` and ``callprotoargument`` can be used only if they are valid for all entry routines, etc. In addition, F2PY introduces the following statements: + ``threadsafe`` Use ``Py_BEGIN_ALLOW_THREADS .. Py_END_ALLOW_THREADS`` block around the call to Fortran/C function. + ``callstatement `` Replace F2PY generated call statement to Fortran/C function with ````. The wrapped Fortran/C function is available as ``(*f2py_func)``. To raise an exception, set ``f2py_success = 0`` in ````. + ``callprotoargument `` When ``callstatement`` statement is used then F2PY may not generate proper prototypes for Fortran/C functions (because ```` may contain any function calls and F2PY has no way to determine what should be the proper prototype). With this statement you can explicitely specify the arguments of the corresponding prototype:: extern FUNC_F(,)(); + ``fortranname []`` You can use arbitrary ```` for a given Fortran/C function. Then you have to specify ```` with this statement. If ``fortranname`` statement is used without ```` then a dummy wrapper is generated. + ``usercode `` When used inside ``python module`` block, then given C code will be inserted to generated C/API source just before wrapper function definitions. Here you can define arbitrary C functions to be used in initialization of optional arguments, for example. If ``usercode`` is used twise inside ``python module`` block then the second multi-line block is inserted after the definition of external routines. When used inside ````, then given C code will be inserted to the corresponding wrapper function just after declaring variables but before any C statements. So, ``usercode`` follow-up can contain both declarations and C statements. When used inside the first ``interface`` block, then given C code will be inserted at the end of the initialization function of the extension module. Here you can modify extension modules dictionary. For example, for defining additional variables etc. + ``pymethoddef `` Multiline block will be inserted to the definition of module methods ``PyMethodDef``-array. It must be a comma-separated list of C arrays (see `Extending and Embedding`__ Python documentation for details). ``pymethoddef`` statement can be used only inside ``python module`` block. __ http://www.python.org/doc/current/ext/ext.html Attributes ------------ The following attributes are used by F2PY: ``optional`` The corresponding argument is moved to the end of ```` list. A default value for an optional argument can be specified ````, see ``entitydecl`` definition. Note that the default value must be given as a valid C expression. Note that whenever ```` is used, ``optional`` attribute is set automatically by F2PY. For an optional array argument, all its dimensions must be bounded. ``required`` The corresponding argument is considered as a required one. This is default. You need to specify ``required`` only if there is a need to disable automatic ``optional`` setting when ```` is used. If Python ``None`` object is used as an required argument, the argument is treated as optional. That is, in the case of array argument, the memory is allocated. And if ```` is given, the corresponding initialization is carried out. ``dimension()`` The corresponding variable is considered as an array with given dimensions in ````. ``intent()`` This specifies the "intention" of the corresponding argument. ```` is a comma separated list of the following keys: + ``in`` The argument is considered as an input-only argument. It means that the value of the argument is passed to Fortran/C function and that function is expected not to change the value of an argument. + ``inout`` The argument is considered as an input/output or *in situ* output argument. ``intent(inout)`` arguments can be only "contiguous" Numeric arrays with proper type and size. Here "contiguous" can be either in Fortran or C sense. The latter one coincides with the contiguous concept used in Numeric and is effective only if ``intent(c)`` is used. Fortran-contiguousness is assumed by default. Using ``intent(inout)`` is generally not recommended, use ``intent(in,out)`` instead. See also ``intent(inplace)`` attribute. + ``inplace`` The argument is considered as an input/output or *in situ* output argument. ``intent(inplace)`` arguments must be Numeric arrays with proper size. If the type of an array is not "proper" or the array is non-contiguous then the array will be changed in-place to fix the type and make it contiguous. Using ``intent(inplace)`` is generally not recommended either. For example, when slices have been taken from an ``intent(inplace)`` argument then after in-place changes, slices data pointers may point to unallocated memory area. + ``out`` The argument is considered as an return variable. It is appended to the ```` list. Using ``intent(out)`` sets ``intent(hide)`` automatically, unless also ``intent(in)`` or ``intent(inout)`` were used. By default, returned multidimensional arrays are Fortran-contiguous. If ``intent(c)`` is used, then returned multi-dimensional arrays are C-contiguous. + ``hide`` The argument is removed from the list of required or optional arguments. Typically ``intent(hide)`` is used with ``intent(out)`` or when ```` completely determines the value of the argument like in the following example:: integer intent(hide),depend(a) :: n = len(a) real intent(in),dimension(n) :: a + ``c`` The argument is treated as a C scalar or C array argument. In the case of a scalar argument, its value is passed to C function as a C scalar argument (recall that Fortran scalar arguments are actually C pointer arguments). In the case of an array argument, the wrapper function is assumed to treat multi-dimensional arrays as C-contiguous arrays. There is no need to use ``intent(c)`` for one-dimensional arrays, no matter if the wrapped function is either a Fortran or a C function. This is because the concepts of Fortran- and C-contiguousness overlap in one-dimensional cases. If ``intent(c)`` is used as an statement but without entity declaration list, then F2PY adds ``intent(c)`` attibute to all arguments. Also, when wrapping C functions, one must use ``intent(c)`` attribute for ```` in order to disable Fortran specific ``F_FUNC(..,..)`` macros. + ``cache`` The argument is treated as a junk of memory. No Fortran nor C contiguousness checks are carried out. Using ``intent(cache)`` makes sense only for array arguments, also in connection with ``intent(hide)`` or ``optional`` attributes. + ``copy`` Ensure that the original contents of ``intent(in)`` argument is preserved. Typically used in connection with ``intent(in,out)`` attribute. F2PY creates an optional argument ``overwrite_`` with the default value ``0``. + ``overwrite`` The original contents of the ``intent(in)`` argument may be altered by the Fortran/C function. F2PY creates an optional argument ``overwrite_`` with the default value ``1``. + ``out=`` Replace the return name with ```` in the ``__doc__`` string of a wrapper function. + ``callback`` Construct an external function suitable for calling Python function from Fortran. ``intent(callback)`` must be specified before the corresponding ``external`` statement. If 'argument' is not in argument list then it will be added to Python wrapper but only initializing external function. Use ``intent(callback)`` in situations where a Fortran/C code assumes that a user implements a function with given prototype and links it to an executable. Don't use ``intent(callback)`` if function appears in the argument list of a Fortran routine. With ``intent(hide)`` or ``optional`` attributes specified and using a wrapper function without specifying the callback argument in argument list then call-back function is looked in the namespace of F2PY generated extension module where it can be set as a module attribute by a user. + ``aux`` Define auxiliary C variable in F2PY generated wrapper function. Useful to save parameter values so that they can be accessed in initialization expression of other variables. Note that ``intent(aux)`` silently implies ``intent(c)``. The following rules apply: + If no ``intent(in | inout | out | hide)`` is specified, ``intent(in)`` is assumed. + ``intent(in,inout)`` is ``intent(in)``. + ``intent(in,hide)`` or ``intent(inout,hide)`` is ``intent(hide)``. + ``intent(out)`` is ``intent(out,hide)`` unless ``intent(in)`` or ``intent(inout)`` is specified. + If ``intent(copy)`` or ``intent(overwrite)`` is used, then an additional optional argument is introduced with a name ``overwrite_`` and a default value 0 or 1, respectively. + ``intent(inout,inplace)`` is ``intent(inplace)``. + ``intent(in,inplace)`` is ``intent(inplace)``. + ``intent(hide)`` disables ``optional`` and ``required``. ``check([])`` Perform consistency check of arguments by evaluating ````; if ```` returns 0, an exception is raised. If ``check(..)`` is not used then F2PY generates few standard checks (e.g. in a case of an array argument, check for the proper shape and size) automatically. Use ``check()`` to disable checks generated by F2PY. ``depend([])`` This declares that the corresponding argument depends on the values of variables in the list ````. For example, ```` may use the values of other arguments. Using information given by ``depend(..)`` attributes, F2PY ensures that arguments are initialized in a proper order. If ``depend(..)`` attribute is not used then F2PY determines dependence relations automatically. Use ``depend()`` to disable dependence relations generated by F2PY. When you edit dependence relations that were initially generated by F2PY, be careful not to break the dependence relations of other relevant variables. Another thing to watch out is cyclic dependencies. F2PY is able to detect cyclic dependencies when constructing wrappers and it complains if any are found. ``allocatable`` The corresponding variable is Fortran 90 allocatable array defined as Fortran 90 module data. .. _external: ``external`` The corresponding argument is a function provided by user. The signature of this so-called call-back function can be defined - in ``__user__`` module block, - or by demonstrative (or real, if the signature file is a real Fortran code) call in the ```` block. For example, F2PY generates from :: external cb_sub, cb_fun integer n real a(n),r call cb_sub(a,n) r = cb_fun(4) the following call-back signatures:: subroutine cb_sub(a,n) real dimension(n) :: a integer optional,check(len(a)>=n),depend(a) :: n=len(a) end subroutine cb_sub function cb_fun(e_4_e) result (r) integer :: e_4_e real :: r end function cb_fun The corresponding user-provided Python function are then:: def cb_sub(a,[n]): ... return def cb_fun(e_4_e): ... return r See also ``intent(callback)`` attribute. ``parameter`` The corresponding variable is a parameter and it must have a fixed value. F2PY replaces all parameter occurrences by their corresponding values. Extensions ============ F2PY directives ----------------- The so-called F2PY directives allow using F2PY signature file constructs also in Fortran 77/90 source codes. With this feature you can skip (almost) completely intermediate signature file generations and apply F2PY directly to Fortran source codes. F2PY directive has the following form:: f2py ... where allowed comment characters for fixed and free format Fortran codes are ``cC*!#`` and ``!``, respectively. Everything that follows ``f2py`` is ignored by a compiler but read by F2PY as a normal Fortran (non-comment) line: When F2PY finds a line with F2PY directive, the directive is first replaced by 5 spaces and then the line is reread. For fixed format Fortran codes, ```` must be at the first column of a file, of course. For free format Fortran codes, F2PY directives can appear anywhere in a file. C expressions -------------- C expressions are used in the following parts of signature files: * ```` of variable initialization; * ```` of the ``check`` attribute; * `` of the ``dimension`` attribute; * ``callstatement`` statement, here also a C multi-line block can be used. A C expression may contain: * standard C constructs; * functions from ``math.h`` and ``Python.h``; * variables from the argument list, presumably initialized before according to given dependence relations; * the following CPP macros: ``rank()`` Returns the rank of an array ````. ``shape(,)`` Returns the ````-th dimension of an array ````. ``len()`` Returns the lenght of an array ````. ``size()`` Returns the size of an array ````. ``slen()`` Returns the length of a string ````. For initializing an array ````, F2PY generates a loop over all indices and dimensions that executes the following pseudo-statement:: (_i[0],_i[1],...) = ; where ``_i[]`` refers to the ````-th index value and that runs from ``0`` to ``shape(,)-1``. For example, a function ``myrange(n)`` generated from the following signature :: subroutine myrange(a,n) fortranname ! myrange is a dummy wrapper integer intent(in) :: n real*8 intent(c,out),dimension(n),depend(n) :: a = _i[0] end subroutine myrange is equivalent to ``Numeric.arange(n,typecode='d')``. .. topic:: Warning! F2PY may lower cases also in C expressions when scanning Fortran codes (see ``--[no]-lower`` option). Multi-line blocks ------------------ A multi-line block starts with ``'''`` (triple single-quotes) and ends with ``'''`` in some *strictly* subsequent line. Multi-line blocks can be used only within .pyf files. The contents of a multi-line block can be arbitrary (except that it cannot contain ``'''``) and no transformations (e.g. lowering cases) are applied to it. Currently, multi-line blocks can be used in the following constructs: + as a C expression of the ``callstatement`` statement; + as a C type specification of the ``callprotoargument`` statement; + as a C code block of the ``usercode`` statement; + as a list of C arrays of the ``pymethoddef`` statement; + as documentation string. ================================== Using F2PY bindings in Python ================================== All wrappers (to Fortran/C routines or to common blocks or to Fortran 90 module data) generated by F2PY are exposed to Python as ``fortran`` type objects. Routine wrappers are callable ``fortran`` type objects while wrappers to Fortran data have attributes referring to data objects. All ``fortran`` type object have attribute ``_cpointer`` that contains CObject referring to the C pointer of the corresponding Fortran/C function or variable in C level. Such CObjects can be used as an callback argument of F2PY generated functions to bypass Python C/API layer of calling Python functions from Fortran or C when the computational part of such functions is implemented in C or Fortran and wrapped with F2PY (or any other tool capable of providing CObject of a function). .. topic:: Example Consider a `Fortran 77 file`__ ``ftype.f``: .. include:: ftype.f :literal: and build a wrapper using:: f2py -c ftype.f -m ftype __ ftype.f In Python: .. include:: ftype_session.dat :literal: Scalar arguments ================= In general, a scalar argument of a F2PY generated wrapper function can be ordinary Python scalar (integer, float, complex number) as well as an arbitrary sequence object (list, tuple, array, string) of scalars. In the latter case, the first element of the sequence object is passed to Fortran routine as a scalar argument. Note that when type-casting is required and there is possible loss of information (e.g. when type-casting float to integer or complex to float), F2PY does not raise any exception. In complex to real type-casting only the real part of a complex number is used. ``intent(inout)`` scalar arguments are assumed to be array objects in order to *in situ* changes to be effective. It is recommended to use arrays with proper type but also other types work. .. topic:: Example Consider the following `Fortran 77 code`__: .. include:: scalar.f :literal: and wrap it using ``f2py -c -m scalar scalar.f``. __ scalar.f In Python: .. include:: scalar_session.dat :literal: String arguments ================= F2PY generated wrapper functions accept (almost) any Python object as a string argument, ``str`` is applied for non-string objects. Exceptions are Numeric arrays that must have type code ``'c'`` or ``'1'`` when used as string arguments. A string can have arbitrary length when using it as a string argument to F2PY generated wrapper function. If the length is greater than expected, the string is truncated. If the length is smaller that expected, additional memory is allocated and filled with ``\0``. Because Python strings are immutable, an ``intent(inout)`` argument expects an array version of a string in order to *in situ* changes to be effective. .. topic:: Example Consider the following `Fortran 77 code`__: .. include:: string.f :literal: and wrap it using ``f2py -c -m mystring string.f``. __ string.f Python session: .. include:: string_session.dat :literal: Array arguments ================ In general, array arguments of F2PY generated wrapper functions accept arbitrary sequences that can be transformed to Numeric array objects. An exception is ``intent(inout)`` array arguments that always must be proper-contiguous and have proper type, otherwise an exception is raised. Another exception is ``intent(inplace)`` array arguments that attributes will be changed in-situ if the argument has different type than expected (see ``intent(inplace)`` attribute for more information). In general, if a Numeric array is proper-contiguous and has a proper type then it is directly passed to wrapped Fortran/C function. Otherwise, an element-wise copy of an input array is made and the copy, being proper-contiguous and with proper type, is used as an array argument. There are two types of proper-contiguous Numeric arrays: * Fortran-contiguous arrays when data is stored column-wise, i.e. indexing of data as stored in memory starts from the lowest dimension; * C-contiguous or simply contiguous arrays when data is stored row-wise, i.e. indexing of data as stored in memory starts from the highest dimension. For one-dimensional arrays these notions coincide. For example, an 2x2 array ``A`` is Fortran-contiguous if its elements are stored in memory in the following order:: A[0,0] A[1,0] A[0,1] A[1,1] and C-contiguous if the order is as follows:: A[0,0] A[0,1] A[1,0] A[1,1] To test whether an array is C-contiguous, use ``.iscontiguous()`` method of Numeric arrays. To test for Fortran-contiguousness, all F2PY generated extension modules provide a function ``has_column_major_storage()``. This function is equivalent to ``Numeric.transpose().iscontiguous()`` but more efficient. Usually there is no need to worry about how the arrays are stored in memory and whether the wrapped functions, being either Fortran or C functions, assume one or another storage order. F2PY automatically ensures that wrapped functions get arguments with proper storage order; the corresponding algorithm is designed to make copies of arrays only when absolutely necessary. However, when dealing with very large multi-dimensional input arrays with sizes close to the size of the physical memory in your computer, then a care must be taken to use always proper-contiguous and proper type arguments. To transform input arrays to column major storage order before passing them to Fortran routines, use a function ``as_column_major_storage()`` that is provided by all F2PY generated extension modules. .. topic:: Example Consider `Fortran 77 code`__: .. include:: array.f :literal: and wrap it using ``f2py -c -m arr array.f -DF2PY_REPORT_ON_ARRAY_COPY=1``. __ array.f In Python: .. include:: array_session.dat :literal: Call-back arguments ==================== F2PY supports calling Python functions from Fortran or C codes. .. topic:: Example Consider the following `Fortran 77 code`__ .. include:: callback.f :literal: and wrap it using ``f2py -c -m callback callback.f``. __ callback.f In Python: .. include:: callback_session.dat :literal: In the above example F2PY was able to guess accurately the signature of a call-back function. However, sometimes F2PY cannot establish the signature as one would wish and then the signature of a call-back function must be modified in the signature file manually. Namely, signature files may contain special modules (the names of such modules contain a substring ``__user__``) that collect various signatures of call-back functions. Callback arguments in routine signatures have attribute ``external`` (see also ``intent(callback)`` attribute). To relate a callback argument and its signature in ``__user__`` module block, use ``use`` statement as illustrated below. The same signature of a callback argument can be referred in different routine signatures. .. topic:: Example We use the same `Fortran 77 code`__ as in previous example but now we'll pretend that F2PY was not able to guess the signatures of call-back arguments correctly. First, we create an initial signature file ``callback2.pyf`` using F2PY:: f2py -m callback2 -h callback2.pyf callback.f Then modify it as follows .. include:: callback2.pyf :literal: Finally, build the extension module using:: f2py -c callback2.pyf callback.f An example Python session would be identical to the previous example except that argument names would differ. __ callback.f Sometimes a Fortran package may require that users provide routines that the package will use. F2PY can construct an interface to such routines so that Python functions could be called from Fortran. .. topic:: Example Consider the following `Fortran 77 subroutine`__ that takes an array and applies a function ``func`` to its elements. .. include:: calculate.f :literal: __ calculate.f It is expected that function ``func`` has been defined externally. In order to use a Python function as ``func``, it must have an attribute ``intent(callback)`` (it must be specified before the ``external`` statement). Finally, build an extension module using:: f2py -c -m foo calculate.f In Python: .. include:: calculate_session.dat :literal: The function is included as an argument to the python function call to the FORTRAN subroutine eventhough it was NOT in the FORTRAN subroutine argument list. The "external" refers to the C function generated by f2py, not the python function itself. The python function must be supplied to the C function. The callback function may also be explicitly set in the module. Then it is not necessary to pass the function in the argument list to the FORTRAN function. This may be desired if the FORTRAN function calling the python callback function is itself called by another FORTRAN function. .. topic:: Example Consider the following `Fortran 77 subroutine`__. .. include:: extcallback.f :literal: __ extcallback.f and wrap it using ``f2py -c -m pfromf extcallback.f``. In Python: .. include:: extcallback_session.dat :literal: Resolving arguments to call-back functions ------------------------------------------ F2PY generated interface is very flexible with respect to call-back arguments. For each call-back argument an additional optional argument ``_extra_args`` is introduced by F2PY. This argument can be used to pass extra arguments to user provided call-back arguments. If a F2PY generated wrapper function expects the following call-back argument:: def fun(a_1,...,a_n): ... return x_1,...,x_k but the following Python function :: def gun(b_1,...,b_m): ... return y_1,...,y_l is provided by an user, and in addition, :: fun_extra_args = (e_1,...,e_p) is used, then the following rules are applied when a Fortran or C function calls the call-back argument ``gun``: * If ``p==0`` then ``gun(a_1,...,a_q)`` is called, here ``q=min(m,n)``. * If ``n+p<=m`` then ``gun(a_1,...,a_n,e_1,...,e_p)`` is called. * If ``p<=mm`` then ``gun(e_1,...,e_m)`` is called. * If ``n+p`` is less than the number of required arguments to ``gun`` then an exception is raised. The function ``gun`` may return any number of objects as a tuple. Then following rules are applied: * If ``kl``, then only ``x_1,...,x_l`` are set. Common blocks ============== F2PY generates wrappers to ``common`` blocks defined in a routine signature block. Common blocks are visible by all Fortran codes linked with the current extension module, but not to other extension modules (this restriction is due to how Python imports shared libraries). In Python, the F2PY wrappers to ``common`` blocks are ``fortran`` type objects that have (dynamic) attributes related to data members of common blocks. When accessed, these attributes return as Numeric array objects (multi-dimensional arrays are Fortran-contiguous) that directly link to data members in common blocks. Data members can be changed by direct assignment or by in-place changes to the corresponding array objects. .. topic:: Example Consider the following `Fortran 77 code`__ .. include:: common.f :literal: and wrap it using ``f2py -c -m common common.f``. __ common.f In Python: .. include:: common_session.dat :literal: Fortran 90 module data ======================= The F2PY interface to Fortran 90 module data is similar to Fortran 77 common blocks. .. topic:: Example Consider the following `Fortran 90 code`__ .. include:: moddata.f90 :literal: and wrap it using ``f2py -c -m moddata moddata.f90``. __ moddata.f90 In Python: .. include:: moddata_session.dat :literal: Allocatable arrays ------------------- F2PY has basic support for Fortran 90 module allocatable arrays. .. topic:: Example Consider the following `Fortran 90 code`__ .. include:: allocarr.f90 :literal: and wrap it using ``f2py -c -m allocarr allocarr.f90``. __ allocarr.f90 In Python: .. include:: allocarr_session.dat :literal: =========== Using F2PY =========== F2PY can be used either as a command line tool ``f2py`` or as a Python module ``f2py2e``. Command ``f2py`` ================= When used as a command line tool, ``f2py`` has three major modes, distinguished by the usage of ``-c`` and ``-h`` switches: 1. To scan Fortran sources and generate a signature file, use :: f2py -h \ [[ only: : ] \ [ skip: : ]]... \ [ ...] Note that a Fortran source file can contain many routines, and not necessarily all routines are needed to be used from Python. So, you can either specify which routines should be wrapped (in ``only: .. :`` part) or which routines F2PY should ignored (in ``skip: .. :`` part). If ```` is specified as ``stdout`` then signatures are send to standard output instead of a file. Among other options (see below), the following options can be used in this mode: ``--overwrite-signature`` Overwrite existing signature file. 2. To construct an extension module, use :: f2py \ [[ only: : ] \ [ skip: : ]]... \ [ ...] The constructed extension module is saved as ``module.c`` to the current directory. Here ```` may also contain signature files. Among other options (see below), the following options can be used in this mode: ``--debug-capi`` Add debugging hooks to the extension module. When using this extension module, various information about the wrapper is printed to standard output, for example, the values of variables, the steps taken, etc. ``-include''`` Add a CPP ``#include`` statement to the extension module source. ```` should be given in one of the following forms:: "filename.ext" The include statement is inserted just before the wrapper functions. This feature enables using arbitrary C functions (defined in ````) in F2PY generated wrappers. This option is deprecated. Use ``usercode`` statement to specify C codelets directly in signature filess ``--[no-]wrap-functions`` Create Fortran subroutine wrappers to Fortran functions. ``--wrap-functions`` is default because it ensures maximum portability and compiler independence. ``--include-paths ::..`` Search include files from given directories. ``--help-link []`` List system resources found by ``numpy_distutils/system_info.py``. For example, try ``f2py --help-link lapack_opt``. 3. To build an extension module, use :: f2py -c \ [[ only: : ] \ [ skip: : ]]... \ [ ] [ <.o, .a, .so files> ] If ```` contains a signature file, then a source for an extension module is constructed, all Fortran and C sources are compiled, and finally all object and library files are linked to the extension module ``.so`` which is saved into the current directory. If ```` does not contain a signature file, then an extension module is constructed by scanning all Fortran source codes for routine signatures. Among other options (see below) and options described in previous mode, the following options can be used in this mode: ``--help-fcompiler`` List available Fortran compilers. ``--help-compiler`` [depreciated] List available Fortran compilers. ``--fcompiler=`` Specify Fortran compiler type by vendor. ``--f77exec=`` Specify the path to F77 compiler ``--fcompiler-exec=`` [depreciated] Specify the path to F77 compiler ``--f90exec=`` Specify the path to F90 compiler ``--f90compiler-exec=`` [depreciated] Specify the path to F90 compiler ``--f77flags=`` Specify F77 compiler flags ``--f90flags=`` Specify F90 compiler flags ``--opt=`` Specify optimization flags ``--arch=`` Specify architecture specific optimization flags ``--noopt`` Compile without optimization ``--noarch`` Compile without arch-dependent optimization ``--debug`` Compile with debugging information ``-l`` Use the library ```` when linking. ``-D[=]`` Define macro ```` as ````. ``-U`` Define macro ```` ``-I

    `` Append directory ```` to the list of directories searched for include files. ``-L`` Add directory ```` to the list of directories to be searched for ``-l``. ``link-`` Link extension module with as defined by ``numpy_distutils/system_info.py``. E.g. to link with optimized LAPACK libraries (vecLib on MacOSX, ATLAS elsewhere), use ``--link-lapack_opt``. See also ``--help-link`` switch. When building an extension module, a combination of the following macros may be required for non-gcc Fortran compilers:: -DPREPEND_FORTRAN -DNO_APPEND_FORTRAN -DUPPERCASE_FORTRAN To test the performance of F2PY generated interfaces, use ``-DF2PY_REPORT_ATEXIT``. Then a report of various timings is printed out at the exit of Python. This feature may not work on all platforms, currently only Linux platform is supported. To see whether F2PY generated interface performs copies of array arguments, use ``-DF2PY_REPORT_ON_ARRAY_COPY=``. When the size of an array argument is larger than ````, a message about the coping is sent to ``stderr``. Other options: ``-m `` Name of an extension module. Default is ``untitled``. Don't use this option if a signature file (*.pyf) is used. ``--[no-]lower`` Do [not] lower the cases in ````. By default, ``--lower`` is assumed with ``-h`` switch, and ``--no-lower`` without the ``-h`` switch. ``--build-dir `` All F2PY generated files are created in ````. Default is ``tempfile.mkdtemp()``. ``--quiet`` Run quietly. ``--verbose`` Run with extra verbosity. ``-v`` Print f2py version ID and exit. Execute ``f2py`` without any options to get an up-to-date list of available options. Python module ``f2py2e`` ========================= .. topic:: Warning The current Python interface to ``f2py2e`` module is not mature and may change in future depending on users needs. The following functions are provided by the ``f2py2e`` module: ``run_main()`` Equivalent to running:: f2py where ``=string.join(,' ')``, but in Python. Unless ``-h`` is used, this function returns a dictionary containing information on generated modules and their dependencies on source files. For example, the command ``f2py -m scalar scalar.f`` can be executed from Python as follows .. include:: run_main_session.dat :literal: You cannot build extension modules with this function, that is, using ``-c`` is not allowed. Use ``compile`` command instead, see below. ``compile(source, modulename='untitled', extra_args='', verbose=1, source_fn=None)`` Build extension module from Fortran 77 source string ``source``. Return 0 if successful. Note that this function actually calls ``f2py -c ..`` from shell to ensure safety of the current Python process. For example, .. include:: compile_session.dat :literal: ========================== Using ``numpy_distutils`` ========================== ``numpy_distutils`` is part of the SciPy_ project and aims to extend standard Python ``distutils`` to deal with Fortran sources and F2PY signature files, e.g. compile Fortran sources, call F2PY to construct extension modules, etc. .. topic:: Example Consider the following `setup file`__: .. include:: setup_example.py :literal: Running :: python setup_example.py build will build two extension modules ``scalar`` and ``fib2`` to the build directory. __ setup_example.py ``numpy_distutils`` extends ``distutils`` with the following features: * ``Extension`` class argument ``sources`` may contain Fortran source files. In addition, the list ``sources`` may contain at most one F2PY signature file, and then the name of an Extension module must match with the ```` used in signature file. It is assumed that an F2PY signature file contains exactly one ``python module`` block. If ``sources`` does not contain a signature files, then F2PY is used to scan Fortran source files for routine signatures to construct the wrappers to Fortran codes. Additional options to F2PY process can be given using ``Extension`` class argument ``f2py_options``. ``numpy_distutils`` 0.2.2 and up ================================ * The following new ``distutils`` commands are defined: ``build_src`` to construct Fortran wrapper extension modules, among many other things. ``config_fc`` to change Fortran compiler options as well as ``build_ext`` and ``build_clib`` commands are enhanced to support Fortran sources. Run :: python config_fc build_src build_ext --help to see available options for these commands. * When building Python packages containing Fortran sources, then one can choose different Fortran compilers by using ``build_ext`` command option ``--fcompiler=``. Here ```` can be one of the following names:: absoft sun mips intel intelv intele intelev nag compaq compaqv gnu vast pg hpux See ``numpy_distutils/fcompiler.py`` for up-to-date list of supported compilers or run :: f2py -c --help-fcompiler ``numpy_distutils`` pre 0.2.2 ============================= * The following new ``distutils`` commands are defined: ``build_flib`` to build f77/f90 libraries used by Python extensions; ``run_f2py`` to construct Fortran wrapper extension modules. Run :: python build_flib run_f2py --help to see available options for these commands. * When building Python packages containing Fortran sources, then one can choose different Fortran compilers either by using ``build_flib`` command option ``--fcompiler=`` or by defining environment variable ``FC_VENDOR=``. Here ```` can be one of the following names:: Absoft Sun SGI Intel Itanium NAG Compaq Digital Gnu VAST PG See ``numpy_distutils/command/build_flib.py`` for up-to-date list of supported compilers. ====================== Extended F2PY usages ====================== Adding self-written functions to F2PY generated modules ======================================================= Self-written Python C/API functions can be defined inside signature files using ``usercode`` and ``pymethoddef`` statements (they must be used inside the ``python module`` block). For example, the following signature file ``spam.pyf`` .. include:: spam.pyf :literal: wraps the C library function ``system()``:: f2py -c spam.pyf In Python: .. include:: spam_session.dat :literal: Modifying the dictionary of a F2PY generated module =================================================== The following example illustrates how to add an user-defined variables to a F2PY generated extension module. Given the following signature file .. include:: var.pyf :literal: compile it as ``f2py -c var.pyf``. Notice that the second ``usercode`` statement must be defined inside an ``interface`` block and where the module dictionary is available through the variable ``d`` (see ``f2py var.pyf``-generated ``varmodule.c`` for additional details). In Python: .. include:: var_session.dat :literal: .. References ========== .. _F2PY: http://cens.ioc.ee/projects/f2py2e/ .. _Python: http://www.python.org/ .. _NumPy: http://www.numpy.org/ .. _SciPy: http://www.numpy.org/ numpy-1.8.2/numpy/f2py/docs/usersguide/ftype_session.dat0000664000175100017510000000102612370216243024546 0ustar vagrantvagrant00000000000000>>> import ftype >>> print ftype.__doc__ This module 'ftype' is auto-generated with f2py (version:2.28.198-1366). Functions: foo(n=13) COMMON blocks: /data/ a,x(3) . >>> type(ftype.foo),type(ftype.data) (, ) >>> ftype.foo() IN FOO: N= 13 A= 0. X=[ 0. 0. 0.] >>> ftype.data.a = 3 >>> ftype.data.x = [1,2,3] >>> ftype.foo() IN FOO: N= 13 A= 3. X=[ 1. 2. 3.] >>> ftype.data.x[1] = 45 >>> ftype.foo(24) IN FOO: N= 24 A= 3. X=[ 1. 45. 3.] >>> ftype.data.x array([ 1., 45., 3.],'f') numpy-1.8.2/numpy/f2py/docs/usersguide/ftype.f0000664000175100017510000000035012370216243022457 0ustar vagrantvagrant00000000000000C FILE: FTYPE.F SUBROUTINE FOO(N) INTEGER N Cf2py integer optional,intent(in) :: n = 13 REAL A,X COMMON /DATA/ A,X(3) PRINT*, "IN FOO: N=",N," A=",A," X=[",X(1),X(2),X(3),"]" END C END OF FTYPE.F numpy-1.8.2/numpy/f2py/docs/usersguide/var.pyf0000664000175100017510000000031112370216243022466 0ustar vagrantvagrant00000000000000! -*- f90 -*- python module var usercode ''' int BAR = 5; ''' interface usercode ''' PyDict_SetItemString(d,"BAR",PyInt_FromLong(BAR)); ''' end interface end python module numpy-1.8.2/numpy/f2py/docs/usersguide/moddata.f900000664000175100017510000000064612370216243023122 0ustar vagrantvagrant00000000000000module mod integer i integer :: x(4) real, dimension(2,3) :: a real, allocatable, dimension(:,:) :: b contains subroutine foo integer k print*, "i=",i print*, "x=[",x,"]" print*, "a=[" print*, "[",a(1,1),",",a(1,2),",",a(1,3),"]" print*, "[",a(2,1),",",a(2,2),",",a(2,3),"]" print*, "]" print*, "Setting a(1,2)=a(1,2)+3" a(1,2) = a(1,2)+3 end subroutine foo end module mod numpy-1.8.2/numpy/f2py/docs/usersguide/run_main_session.dat0000664000175100017510000000104312370216243025226 0ustar vagrantvagrant00000000000000>>> import f2py2e >>> r=f2py2e.run_main(['-m','scalar','docs/usersguide/scalar.f']) Reading fortran codes... Reading file 'docs/usersguide/scalar.f' Post-processing... Block: scalar Block: FOO Building modules... Building module "scalar"... Wrote C/API module "scalar" to file "./scalarmodule.c" >>> print r {'scalar': {'h': ['/home/users/pearu/src_cvs/f2py2e/src/fortranobject.h'], 'csrc': ['./scalarmodule.c', '/home/users/pearu/src_cvs/f2py2e/src/fortranobject.c']}} numpy-1.8.2/numpy/f2py/docs/usersguide/compile_session.dat0000664000175100017510000000033712370216243025053 0ustar vagrantvagrant00000000000000>>> import f2py2e >>> fsource = ''' ... subroutine foo ... print*, "Hello world!" ... end ... ''' >>> f2py2e.compile(fsource,modulename='hello',verbose=0) 0 >>> import hello >>> hello.foo() Hello world! numpy-1.8.2/numpy/f2py/docs/usersguide/string.f0000664000175100017510000000067712370216243022652 0ustar vagrantvagrant00000000000000C FILE: STRING.F SUBROUTINE FOO(A,B,C,D) CHARACTER*5 A, B CHARACTER*(*) C,D Cf2py intent(in) a,c Cf2py intent(inout) b,d PRINT*, "A=",A PRINT*, "B=",B PRINT*, "C=",C PRINT*, "D=",D PRINT*, "CHANGE A,B,C,D" A(1:1) = 'A' B(1:1) = 'B' C(1:1) = 'C' D(1:1) = 'D' PRINT*, "A=",A PRINT*, "B=",B PRINT*, "C=",C PRINT*, "D=",D END C END OF FILE STRING.F numpy-1.8.2/numpy/f2py/docs/usersguide/moddata_session.dat0000664000175100017510000000111512370216243025027 0ustar vagrantvagrant00000000000000>>> import moddata >>> print moddata.mod.__doc__ i - 'i'-scalar x - 'i'-array(4) a - 'f'-array(2,3) foo - Function signature: foo() >>> moddata.mod.i = 5 >>> moddata.mod.x[:2] = [1,2] >>> moddata.mod.a = [[1,2,3],[4,5,6]] >>> moddata.mod.foo() i= 5 x=[ 1 2 0 0 ] a=[ [ 1.000000 , 2.000000 , 3.000000 ] [ 4.000000 , 5.000000 , 6.000000 ] ] Setting a(1,2)=a(1,2)+3 >>> moddata.mod.a # a is Fortran-contiguous array([[ 1., 5., 3.], [ 4., 5., 6.]],'f') numpy-1.8.2/numpy/f2py/docs/usersguide/docutils.conf0000664000175100017510000000057612370216243023670 0ustar vagrantvagrant00000000000000[general] # These entries affect all processing: #source-link: 1 datestamp: %Y-%m-%d %H:%M UTC generator: 1 # These entries affect HTML output: #stylesheet-path: f2py_style.css output-encoding: latin-1 # These entries affect reStructuredText-style PEPs: #pep-template: pep-html-template #pep-stylesheet-path: stylesheets/pep.css #python-home: http://www.python.org #no-random: 1 numpy-1.8.2/numpy/f2py/docs/simple.f0000664000175100017510000000036212370216243020445 0ustar vagrantvagrant00000000000000cFile: simple.f subroutine foo(a,m,n) integer m,n,i,j real a(m,n) cf2py intent(in,out) a cf2py intent(hide) m,n do i=1,m do j=1,n a(i,j) = a(i,j) + 10*i+j enddo enddo end cEOF numpy-1.8.2/numpy/f2py/docs/pytest.py0000664000175100017510000000041712370216243020710 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function #File: pytest.py import Numeric def foo(a): a = Numeric.array(a) m, n = a.shape for i in range(m): for j in range(n): a[i, j] = a[i, j] + 10*(i+1) + (j+1) return a #eof numpy-1.8.2/numpy/f2py/docs/default.css0000664000175100017510000000605112370216243021144 0ustar vagrantvagrant00000000000000/* :Author: David Goodger :Contact: goodger@users.sourceforge.net :date: $Date: 2002/08/01 20:52:44 $ :version: $Revision: 1.1 $ :copyright: This stylesheet has been placed in the public domain. Default cascading style sheet for the HTML output of Docutils. */ body { background: #FFFFFF ; color: #000000 } a.footnote-reference { font-size: smaller ; vertical-align: super } a.target { color: blue } a.toc-backref { text-decoration: none ; color: black } dd { margin-bottom: 0.5em } div.abstract { margin: 2em 5em } div.abstract p.topic-title { font-weight: bold ; text-align: center } div.attention, div.caution, div.danger, div.error, div.hint, div.important, div.note, div.tip, div.warning { margin: 2em ; border: medium outset ; padding: 1em } div.attention p.admonition-title, div.caution p.admonition-title, div.danger p.admonition-title, div.error p.admonition-title, div.warning p.admonition-title { color: red ; font-weight: bold ; font-family: sans-serif } div.hint p.admonition-title, div.important p.admonition-title, div.note p.admonition-title, div.tip p.admonition-title { font-weight: bold ; font-family: sans-serif } div.dedication { margin: 2em 5em ; text-align: center ; font-style: italic } div.dedication p.topic-title { font-weight: bold ; font-style: normal } div.figure { margin-left: 2em } div.footer, div.header { font-size: smaller } div.system-messages { margin: 5em } div.system-messages h1 { color: red } div.system-message { border: medium outset ; padding: 1em } div.system-message p.system-message-title { color: red ; font-weight: bold } div.topic { margin: 2em } h1.title { text-align: center } h2.subtitle { text-align: center } hr { width: 75% } ol.simple, ul.simple { margin-bottom: 1em } ol.arabic { list-style: decimal } ol.loweralpha { list-style: lower-alpha } ol.upperalpha { list-style: upper-alpha } ol.lowerroman { list-style: lower-roman } ol.upperroman { list-style: upper-roman } p.caption { font-style: italic } p.credits { font-style: italic ; font-size: smaller } p.first { margin-top: 0 } p.label { white-space: nowrap } p.topic-title { font-weight: bold } pre.literal-block, pre.doctest-block { margin-left: 2em ; margin-right: 2em ; background-color: #eeeeee } span.classifier { font-family: sans-serif ; font-style: oblique } span.classifier-delimiter { font-family: sans-serif ; font-weight: bold } span.field-argument { font-style: italic } span.interpreted { font-family: sans-serif } span.option-argument { font-style: italic } span.problematic { color: red } table { margin-top: 0.5em ; margin-bottom: 0.5em } table.citation { border-left: solid thin gray ; padding-left: 0.5ex } table.docinfo { margin: 2em 4em } table.footnote { border-left: solid thin black ; padding-left: 0.5ex } td, th { padding-left: 0.5em ; padding-right: 0.5em ; vertical-align: baseline } td.docinfo-name { font-weight: bold ; text-align: right } td.field-name { font-weight: bold } numpy-1.8.2/numpy/f2py/docs/THANKS.txt0000664000175100017510000000535712370216243020547 0ustar vagrantvagrant00000000000000 ================= Acknowledgments ================= F2PY__ is an open source Python package and command line tool developed and maintained by Pearu Peterson (me__). .. __: http://cens.ioc.ee/projects/f2py2e/ .. __: http://cens.ioc.ee/~pearu/ Many people have contributed to the F2PY project in terms of interest, encouragement, suggestions, criticism, bug reports, code contributions, and keeping me busy with developing F2PY. For all that I thank James Amundson, John Barnard, David Beazley, Frank Bertoldi, Roman Bertle, James Boyle, Moritz Braun, Rolv Erlend Bredesen, John Chaffer, Fred Clare, Adam Collard, Ben Cornett, Jose L Gomez Dans, Jaime D. Perea Duarte, Paul F Dubois, Thilo Ernst, Bonilla Fabian, Martin Gelfand, Eduardo A. Gonzalez, Siegfried Gonzi, Bernhard Gschaider, Charles Doutriaux, Jeff Hagelberg, Janko Hauser, Thomas Hauser, Heiko Henkelmann, William Henney, Yueqiang Huang, Asim Hussain, Berthold Höllmann, Vladimir Janku, Henk Jansen, Curtis Jensen, Eric Jones, Tiffany Kamm, Andrey Khavryuchenko, Greg Kochanski, Jochen Küpper, Simon Lacoste-Julien, Tim Lahey, Hans Petter Langtangen, Jeff Layton, Matthew Lewis, Patrick LeGresley, Joaquim R R A Martins, Paul Magwene Lionel Maziere, Craig McNeile, Todd Miller, David C. Morrill, Dirk Muders, Kevin Mueller, Andrew Mullhaupt, Vijayendra Munikoti, Travis Oliphant, Kevin O'Mara, Arno Paehler, Fernando Perez, Didrik Pinte, Todd Alan Pitts, Prabhu Ramachandran, Brad Reisfeld, Steve M. Robbins, Theresa Robinson, Pedro Rodrigues, Les Schaffer, Christoph Scheurer, Herb Schilling, Pierre Schnizer, Kevin Smith, Paulo Teotonio Sobrinho, José Rui Faustino de Sousa, Andrew Swan, Dustin Tang, Charlie Taylor, Paul le Texier, Michael Tiller, Semen Trygubenko, Ravi C Venkatesan, Peter Verveer, Nils Wagner, R. Clint Whaley, Erik Wilsher, Martin Wiechert, Gilles Zerah, SungPil Yoon. (This list may not be complete. Please forgive me if I have left you out and let me know, I'll add your name.) Special thanks are due to ... Eric Jones - he and Travis O. are responsible for starting the numpy_distutils project that allowed to move most of the platform and compiler specific codes out from F2PY. This simplified maintaining the F2PY project considerably. Joaquim R R A Martins - he made possible for me to test F2PY on IRIX64 platform. He also presented our paper about F2PY in the 9th Python Conference that I planned to attend but had to cancel in very last minutes. Travis Oliphant - his knowledge and experience on Numerical Python C/API has been invaluable in early development of the F2PY program. His major contributions are call-back mechanism and copying N-D arrays of arbitrary types. Todd Miller - he is responsible for Numarray support in F2PY. Thanks! Pearu numpy-1.8.2/numpy/f2py/docs/HISTORY.txt0000664000175100017510000010612412370216243020712 0ustar vagrantvagrant00000000000000.. -*- rest -*- ========================= F2PY History ========================= :Author: Pearu Peterson :Web-site: http://cens.ioc.ee/projects/f2py2e/ :Date: $Date: 2005/09/16 08:36:45 $ :Revision: $Revision: 1.191 $ .. Contents:: Release 2.46.243 ===================== * common_rules.py - Fixed compiler warnings. * fortranobject.c - Fixed another dims calculation bug. - Fixed dims calculation bug and added the corresponding check. - Accept higher dimensional arrays if their effective rank matches. Effective rank is multiplication of non-unit dimensions. * f2py2e.py - Added support for numpy.distutils version 0.4.0. * Documentation - Added example about ``intent(callback,hide)`` usage. Updates. - Updated FAQ. * cb_rules.py - Fixed missing need kw error. - Fixed getting callback non-existing extra arguments. - External callback functions and extra_args can be set via ext.module namespace. - Avoid crash when external callback function is not set. * rules.py - Enabled ``intent(out)`` for ``intent(aux)`` non-complex scalars. - Fixed splitting lines in F90 fixed form mode. - Fixed FORTRANAME typo, relevant when wrapping scalar functions with ``--no-wrap-functions``. - Improved failure handling for callback functions. - Fixed bug in writting F90 wrapper functions when a line length is exactly 66. * cfuncs.py - Fixed dependency issue with typedefs. - Introduced ``-DUNDERSCORE_G77`` that cause extra underscore to be used for external names that contain an underscore. * capi_maps.py - Fixed typos. - Fixed using complex cb functions. * crackfortran.py - Introduced parent_block key. Get ``use`` statements recursively from parent blocks. - Apply parameter values to kindselectors. - Fixed bug evaluating ``selected_int_kind`` function. - Ignore Name and Syntax errors when evaluating scalars. - Treat ``_intType`` as ```` in get_parameters. - Added support for F90 line continuation in fix format mode. - Include optional attribute of external to signature file. - Add ``entry`` arguments to variable lists. - Treat \xa0 character as space. - Fixed bug where __user__ callback subroutine was added to its argument list. - In strict 77 mode read only the first 72 columns. - Fixed parsing ``v(i) = func(r)``. - Fixed parsing ``integer*4::``. - Fixed parsing ``1.d-8`` when used as a parameter value. Release 2.45.241_1926 ===================== * diagnose.py - Clean up output. * cb_rules.py - Fixed ``_cpointer`` usage for subroutines. - Fortran function ``_cpointer`` can be used for callbacks. * func2subr.py - Use result name when wrapping functions with subroutines. * f2py2e.py - Fixed ``--help-link`` switch. - Fixed ``--[no-]lower`` usage with ``-c`` option. - Added support for ``.pyf.src`` template files. * __init__.py - Using ``exec_command`` in ``compile()``. * setup.py - Clean up. - Disabled ``need_numpy_distutils`` function. From now on it is assumed that proper version of ``numpy_distutils`` is already installed. * capi_maps.py - Added support for wrapping unsigned integers. In a .pyf file ``integer(-1)``, ``integer(-2)``, ``integer(-4)`` correspond to ``unsigned char``, ``unsigned short``, ``unsigned`` C types, respectively. * tests/c/return_real.py - Added tests to wrap C functions returning float/double. * fortranobject.c - Added ``_cpointer`` attribute to wrapped objects. * rules.py - ``_cpointer`` feature for wrapped module functions is not functional at the moment. - Introduced ``intent(aux)`` attribute. Useful to save a value of a parameter to auxiliary C variable. Note that ``intent(aux)`` implies ``intent(c)``. - Added ``usercode`` section. When ``usercode`` is used in ``python module`` block twise then the contents of the second multi-line block is inserted after the definition of external routines. - Call-back function arguments can be CObjects. * cfuncs.py - Allow call-back function arguments to be fortran objects. - Allow call-back function arguments to be built-in functions. * crackfortran.py - Fixed detection of a function signature from usage example. - Cleaned up -h output for intent(callback) variables. - Repair malformed argument list (missing argument name). - Warn on the usage of multiple attributes without type specification. - Evaluate only scalars ```` (e.g. not of strings). - Evaluate ```` using parameters name space. - Fixed resolving `()[result()]` pattern. - ``usercode`` can be used more than once in the same context. Release 2.43.239_1831 ===================== * auxfuncs.py - Made ``intent(in,inplace)`` to mean ``intent(inplace)``. * f2py2e.py - Intoduced ``--help-link`` and ``--link-`` switches to link generated extension module with system ```` as defined by numpy_distutils/system_info.py. * fortranobject.c - Patch to make PyArray_CanCastSafely safe on 64-bit machines. Fixes incorrect results when passing ``array('l')`` to ``real*8 intent(in,out,overwrite)`` arguments. * rules.py - Avoid empty continuation lines in Fortran wrappers. * cfuncs.py - Adding ``\0`` at the end of a space-padded string, fixes tests on 64-bit Gentoo. * crackfortran.py - Fixed splitting lines with string parameters. Release 2.43.239_1806 ===================== * Tests - Fixed test site that failed after padding strings with spaces instead of zeros. * Documentation - Documented ``intent(inplace)`` attribute. - Documented ``intent(callback)`` attribute. - Updated FAQ, added Users Feedback section. * cfuncs.py - Padding longer (than provided from Python side) strings with spaces (that is Fortran behavior) instead of nulls (that is C strncpy behavior). * f90mod_rules.py - Undoing rmbadnames in Python and Fortran layers. * common_rules.py - Renaming common block items that have names identical to C keywords. - Fixed wrapping blank common blocks. * fortranobject.h - Updated numarray (0.9, 1.0, 1.1) support (patch by Todd Miller). * fortranobject.c - Introduced ``intent(inplace)`` feature. - Fix numarray reference counts (patch by Todd). - Updated numarray (0.9, 1.0, 1.1) support (patch by Todd Miller). - Enabled F2PY_REPORT_ON_ARRAY_COPY for Numarray. * capi_maps.py - Always normalize .f2py_f2cmap keys to lower case. * rules.py - Disabled ``index`` macro as it conflicts with the one defined in string.h. - Moved ``externroutines`` up to make it visible to ``usercode``. - Fixed bug in f90 code generation: no empty line continuation is allowed. - Fixed undefined symbols failure when ``fortranname`` is used to rename a wrapped function. - Support for ``entry`` statement. * auxfuncs.py - Made is* functions more robust with respect to parameters that have no typespec specified. - Using ``size_t`` instead of ``int`` as the type of string length. Fixes issues on 64-bit platforms. * setup.py - Fixed bug of installing ``f2py`` script as ``.exe`` file. * f2py2e.py - ``--compiler=`` and ``--fcompiler=`` can be specified at the same time. * crackfortran.py - Fixed dependency detection for non-intent(in|inout|inplace) arguments. They must depend on their dimensions, not vice-versa. - Don't match ``!!f2py`` as a start of f2py directive. - Only effective intent attributes will be output to ``-h`` target. - Introduced ``intent(callback)`` to build interface between Python functions and Fortran external routines. - Avoid including external arguments to __user__ modules. - Initial hooks to evaluate ``kind`` and ``selected_int_kind``. - Evaluating parameters in {char,kind}selectors and applying rmbadname. - Evaluating parameters using also module parameters. Fixed the order of parameter evaluation. - Fixed silly bug: when block name was not lower cased, it was not recognized correctly. - Applying mapping '.false.'->'False', '.true.'->'True' to logical parameters. TODO: Support for logical expressions is needed. - Added support for multiple statements in one line (separated with semicolon). - Impl. get_useparameters function for using parameter values from other f90 modules. - Applied Bertholds patch to fix bug in evaluating expressions like ``1.d0/dvar``. - Fixed bug in reading string parameters. - Evaluating parameters in charselector. Code cleanup. - Using F90 module parameters to resolve kindselectors. - Made the evaluation of module data init-expression more robust. - Support for ``entry`` statement. - Fixed ``determineexprtype`` that in the case of parameters returned non-dictionary objects. - Use ``-*- fix -*-`` to specify that a file is in fixed format. Release 2.39.235_1693 ===================== * fortranobject.{h,c} - Support for allocatable string arrays. * cfuncs.py - Call-back arguments can now be also instances that have ``__call__`` method as well as instance methods. * f2py2e.py - Introduced ``--include_paths ::..`` command line option. - Added ``--compiler=`` support to change the C/C++ compiler from f2py command line. * capi_maps.py - Handle ``XDY`` parameter constants. * crackfortran.py - Handle ``XDY`` parameter constants. - Introduced formatpattern to workaround a corner case where reserved keywords are used in format statement. Other than that, format pattern has no use. - Parameters are now fully evaluated. * More splitting of documentation strings. * func2subr.py - fixed bug for function names that f77 compiler would set ``integer`` type. Release 2.39.235_1660 ===================== * f2py2e.py - Fixed bug in using --f90flags=.. * f90mod_rules.py - Splitted generated documentation strings (to avoid MSVC issue when string length>2k) - Ignore ``private`` module data. Release 2.39.235_1644 ===================== :Date:24 February 2004 * Character arrays: - Finished complete support for character arrays and arrays of strings. - ``character*n a(m)`` is treated like ``character a(m,n)`` with ``intent(c)``. - Character arrays are now considered as ordinary arrays (not as arrays of strings which actually didn't work). * docs - Initial f2py manpage file f2py.1. - Updated usersguide and other docs when using numpy_distutils 0.2.2 and up. * capi_maps.py - Try harder to use .f2py_f2cmap mappings when kind is used. * crackfortran.py - Included files are first search in the current directory and then from the source file directory. - Ignoring dimension and character selector changes. - Fixed bug in Fortran 90 comments of fixed format. - Warn when .pyf signatures contain undefined symbols. - Better detection of source code formats. Using ``-*- fortran -*-`` or ``-*- f90 -*-`` in the first line of a Fortran source file is recommended to help f2py detect the format, fixed or free, respectively, correctly. * cfuncs.py - Fixed intent(inout) scalars when typecode=='l'. - Fixed intent(inout) scalars when not using numarray. - Fixed intent(inout) scalars when using numarray. * diagnose.py - Updated for numpy_distutils 0.2.2 and up. - Added numarray support to diagnose. * fortranobject.c - Fixed nasty bug with intent(in,copy) complex slice arrays. - Applied Todd's patch to support numarray's byteswapped or misaligned arrays, requires numarray-0.8 or higher. * f2py2e.py - Applying new hooks for numpy_distutils 0.2.2 and up, keeping backward compatibility with depreciation messages. - Using always os.system on non-posix platforms in f2py2e.compile function. * rules.py - Changed the order of buildcallback and usercode junks. * setup.cfg - Added so that docs/ and tests/ directories are included to RPMs. * setup.py - Installing f2py.py instead of f2py.bat under NT. - Introduced ``--with-numpy_distutils`` that is useful when making f2py tar-ball with numpy_distutils included. Release 2.37.233-1545 ===================== :Date: 11 September 2003 * rules.py - Introduced ``interface_usercode`` replacement. When ``usercode`` statement is used inside the first interface block, its contents will be inserted at the end of initialization function of a F2PY generated extension module (feature request: Berthold Höllmann). - Introduced auxiliary function ``as_column_major_storage`` that converts input array to an array with column major storage order (feature request: Hans Petter Langtangen). * crackfortran.py - Introduced ``pymethoddef`` statement. * cfuncs.py - Fixed "#ifdef in #define TRYPYARRAYTEMPLATE" bug (patch thanks to Bernhard Gschaider) * auxfuncs.py - Introduced ``getpymethod`` function. - Enabled multi-line blocks in ``callprotoargument`` statement. * f90mod_rules.py - Undone "Fixed Warning 43 emitted by Intel Fortran compiler" that causes (curios) segfaults. * fortranobject.c - Fixed segfaults (that were introduced with recent memory leak fixes) when using allocatable arrays. - Introduced F2PY_REPORT_ON_ARRAY_COPY CPP macro int-variable. If defined then a message is printed to stderr whenever a copy of an array is made and arrays size is larger than F2PY_REPORT_ON_ARRAY_COPY. Release 2.35.229-1505 ===================== :Date: 5 August 2003 * General - Introduced ``usercode`` statement (dropped ``c_code`` hooks). * setup.py - Updated the CVS location of numpy_distutils. * auxfuncs.py - Introduced ``isint1array(var)`` for fixing ``integer*1 intent(out)`` support. * tests/f77/callback.py Introduced some basic tests. * src/fortranobject.{c,h} - Fixed memory leaks when getting/setting allocatable arrays. (Bug report by Bernhard Gschaider) - Initial support for numarray (Todd Miller's patch). Use -DNUMARRAY on the f2py command line to enable numarray support. Note that there is no character arrays support and these hooks are not tested with F90 compilers yet. * cfuncs.py - Fixed reference counting bug that appeared when constructing extra argument list to callback functions. - Added ``NPY_LONG != NPY_INT`` test. * f2py2e.py Undocumented ``--f90compiler``. * crackfortran.py - Introduced ``usercode`` statement. - Fixed newlines when outputting multi-line blocks. - Optimized ``getlincoef`` loop and ``analyzevars`` for cases where len(vars) is large. - Fixed callback string argument detection. - Fixed evaluating expressions: only int|float expressions are evaluated succesfully. * docs Documented -DF2PY_REPORT_ATEXIT feature. * diagnose.py Added CPU information and sys.prefix printout. * tests/run_all.py Added cwd to PYTHONPATH. * tests/f??/return_{real,complex}.py Pass "infinity" check in SunOS. * rules.py - Fixed ``integer*1 intent(out)`` support - Fixed free format continuation of f2py generated F90 files. * tests/mixed/ Introduced tests for mixing Fortran 77, Fortran 90 fixed and free format codes in one module. * f90mod_rules.py - Fixed non-prototype warnings. - Fixed Warning 43 emitted by Intel Fortran compiler. - Avoid long lines in Fortran codes to reduce possible problems with continuations of lines. Public Release 2.32.225-1419 ============================ :Date: 8 December 2002 * docs/usersguide/ Complete revision of F2PY Users Guide * tests/run_all.py - New file. A Python script to run all f2py unit tests. * Removed files: buildmakefile.py, buildsetup.py. * tests/f77/ - Added intent(out) scalar tests. * f2py_testing.py - Introduced. It contains jiffies, memusage, run, cmdline functions useful for f2py unit tests site. * setup.py - Install numpy_distutils only if it is missing or is too old for f2py. * f90modrules.py - Fixed wrapping f90 module data. - Fixed wrapping f90 module subroutines. - Fixed f90 compiler warnings for wrapped functions by using interface instead of external stmt for functions. * tests/f90/ - Introduced return_*.py tests. * func2subr.py - Added optional signature argument to createfuncwrapper. - In f2pywrappers routines, declare external, scalar, remaining arguments in that order. Fixes compiler error 'Invalid declaration' for:: real function foo(a,b) integer b real a(b) end * crackfortran.py - Removed first-line comment information support. - Introduced multiline block. Currently usable only for ``callstatement`` statement. - Improved array length calculation in getarrlen(..). - "From sky" program group is created only if ``groupcounter<1``. See TODO.txt. - Added support for ``dimension(n:*)``, ``dimension(*:n)``. They are treated as ``dimesnion(*)`` by f2py. - Fixed parameter substitution (this fixes TODO item by Patrick LeGresley, 22 Aug 2001). * f2py2e.py - Disabled all makefile, setup, manifest file generation hooks. - Disabled --[no]-external-modroutines option. All F90 module subroutines will have Fortran/C interface hooks. - --build-dir can be used with -c option. - only/skip modes can be used with -c option. - Fixed and documented `-h stdout` feature. - Documented extra options. - Introduced --quiet and --verbose flags. * cb_rules.py - Fixed debugcapi hooks for intent(c) scalar call-back arguments (bug report: Pierre Schnizer). - Fixed intent(c) for scalar call-back arguments. - Improved failure reports. * capi_maps.py - Fixed complex(kind=..) to C type mapping bug. The following hold complex==complex(kind=4)==complex*8, complex(kind=8)==complex*16 - Using signed_char for integer*1 (bug report: Steve M. Robbins). - Fixed logical*8 function bug: changed its C correspondence to long_long. - Fixed memory leak when returning complex scalar. * __init__.py - Introduced a new function (for f2py test site, but could be useful in general) ``compile(source[,modulename,extra_args])`` for compiling fortran source codes directly from Python. * src/fortranobject.c - Multi-dimensional common block members and allocatable arrays are returned as Fortran-contiguous arrays. - Fixed NULL return to Python without exception. - Fixed memory leak in getattr(,'__doc__'). - .__doc__ is saved to .__dict__ (previously it was generated each time when requested). - Fixed a nasty typo from the previous item that caused data corruption and occasional SEGFAULTs. - array_from_pyobj accepts arbitrary rank arrays if the last dimension is undefined. E.g. dimension(3,*) accepts a(3,4,5) and the result is array with dimension(3,20). - Fixed (void*) casts to make g++ happy (bug report: eric). - Changed the interface of ARR_IS_NULL macro to avoid "``NULL used in arithmetics``" warnings from g++. * src/fortranobject.h - Undone previous item. Defining NO_IMPORT_ARRAY for src/fortranobject.c (bug report: travis) - Ensured that PY_ARRAY_UNIQUE_SYMBOL is defined only for src/fortranobject.c (bug report: eric). * rules.py - Introduced dummy routine feature. - F77 and F90 wrapper subroutines (if any) as saved to different files, -f2pywrappers.f and -f2pywrappers2.f90, respectively. Therefore, wrapping F90 requires numpy_distutils >= 0.2.0_alpha_2.229. - Fixed compiler warnings about meaningless ``const void (*f2py_func)(..)``. - Improved error messages for ``*_from_pyobj``. - Changed __CPLUSPLUS__ macros to __cplusplus (bug report: eric). - Changed (void*) casts to (f2py_init_func) (bug report: eric). - Removed unnecessary (void*) cast for f2py_has_column_major_storage in f2py_module_methods definition (bug report: eric). - Changed the interface of f2py_has_column_major_storage function: removed const from the 1st argument. * cfuncs.py - Introduced -DPREPEND_FORTRAN. - Fixed bus error on SGI by using PyFloat_AsDouble when ``__sgi`` is defined. This seems to be `know bug`__ with Python 2.1 and SGI. - string_from_pyobj accepts only arrays whos elements size==sizeof(char). - logical scalars (intent(in),function) are normalized to 0 or 1. - Removed NUMFROMARROBJ macro. - (char|short)_from_pyobj now use int_from_pyobj. - (float|long_double)_from_pyobj now use double_from_pyobj. - complex_(float|long_double)_from_pyobj now use complex_double_from_pyobj. - Rewrote ``*_from_pyobj`` to be more robust. This fixes segfaults if getting * from a string. Note that int_from_pyobj differs from PyNumber_Int in that it accepts also complex arguments (takes the real part) and sequences (takes the 1st element). - Removed unnecessary void* casts in NUMFROMARROBJ. - Fixed casts in ``*_from_pyobj`` functions. - Replaced CNUMFROMARROBJ with NUMFROMARROBJ. .. __: http://sourceforge.net/tracker/index.php?func=detail&aid=435026&group_id=5470&atid=105470 * auxfuncs.py - Introduced isdummyroutine(). - Fixed islong_* functions. - Fixed isintent_in for intent(c) arguments (bug report: Pierre Schnizer). - Introduced F2PYError and throw_error. Using throw_error, f2py rejects illegal .pyf file constructs that otherwise would cause compilation failures or python crashes. - Fixed islong_long(logical*8)->True. - Introduced islogical() and islogicalfunction(). - Fixed prototype string argument (bug report: eric). * Updated README.txt and doc strings. Starting to use docutils. * Speed up for ``*_from_pyobj`` functions if obj is a sequence. * Fixed SegFault (reported by M.Braun) due to invalid ``Py_DECREF`` in ``GETSCALARFROMPYTUPLE``. Older Releases ============== :: *** Fixed missing includes when wrapping F90 module data. *** Fixed typos in docs of build_flib options. *** Implemented prototype calculator if no callstatement or callprotoargument statements are used. A warning is issued if callstatement is used without callprotoargument. *** Fixed transposing issue with array arguments in callback functions. *** Removed -pyinc command line option. *** Complete tests for Fortran 77 functions returning scalars. *** Fixed returning character bug if --no-wrap-functions. *** Described how to wrap F compiled Fortran F90 module procedures with F2PY. See doc/using_F_compiler.txt. *** Fixed the order of build_flib options when using --fcompiler=... *** Recognize .f95 and .F95 files as Fortran sources with free format. *** Cleaned up the output of 'f2py -h': removed obsolete items, added build_flib options section. *** Added --help-compiler option: it lists available Fortran compilers as detected by numpy_distutils/command/build_flib.py. This option is available only with -c option. :Release: 2.13.175-1250 :Date: 4 April 2002 :: *** Fixed copying of non-contigious 1-dimensional arrays bug. (Thanks to Travis O.). :Release: 2.13.175-1242 :Date: 26 March 2002 :: *** Fixed ignoring type declarations. *** Turned F2PY_REPORT_ATEXIT off by default. *** Made MAX,MIN macros available by default so that they can be always used in signature files. *** Disabled F2PY_REPORT_ATEXIT for FreeBSD. :Release: 2.13.175-1233 :Date: 13 March 2002 :: *** Fixed Win32 port when using f2py.bat. (Thanks to Erik Wilsher). *** F2PY_REPORT_ATEXIT is disabled for MACs. *** Fixed incomplete dependency calculator. :Release: 2.13.175-1222 :Date: 3 March 2002 :: *** Plugged a memory leak for intent(out) arrays with overwrite=0. *** Introduced CDOUBLE_to_CDOUBLE,.. functions for copy_ND_array. These cast functions probably work incorrectly in Numeric. :Release: 2.13.175-1212 :Date: 23 February 2002 :: *** Updated f2py for the latest numpy_distutils. *** A nasty bug with multi-dimensional Fortran arrays is fixed (intent(out) arrays had wrong shapes). (Thanks to Eric for pointing out this bug). *** F2PY_REPORT_ATEXIT is disabled by default for __WIN32__. :Release: 2.11.174-1161 :Date: 14 February 2002 :: *** Updated f2py for the latest numpy_distutils. *** Fixed raise error when f2py missed -m flag. *** Script name `f2py' now depends on the name of python executable. For example, `python2.2 setup.py install' will create a f2py script with a name `f2py2.2'. *** Introduced 'callprotoargument' statement so that proper prototypes can be declared. This is crucial when wrapping C functions as it will fix segmentation faults when these wrappers use non-pointer arguments (thanks to R. Clint Whaley for explaining this to me). Note that in f2py generated wrapper, the prototypes have the following forms: extern #rtype# #fortranname#(#callprotoargument#); or extern #rtype# F_FUNC(#fortranname#,#FORTRANNAME#)(#callprotoargument#); *** Cosmetic fixes to F2PY_REPORT_ATEXIT feature. :Release: 2.11.174-1146 :Date: 3 February 2002 :: *** Reviewed reference counting in call-back mechanism. Fixed few bugs. *** Enabled callstatement for complex functions. *** Fixed bug with initializing capi_overwrite_ *** Introduced intent(overwrite) that is similar to intent(copy) but has opposite effect. Renamed copy_=1 to overwrite_=0. intent(overwrite) will make default overwrite_=1. *** Introduced intent(in|inout,out,out=) attribute that renames arguments name when returned. This renaming has effect only in documentation strings. *** Introduced 'callstatement' statement to pyf file syntax. With this one can specify explicitly how wrapped function should be called from the f2py generated module. WARNING: this is a dangerous feature and should be used with care. It is introduced to provide a hack to construct wrappers that may have very different signature pattern from the wrapped function. Currently 'callstatement' can be used only inside a subroutine or function block (it should be enough though) and must be only in one continuous line. The syntax of the statement is: callstatement ; :Release: 2.11.174 :Date: 18 January 2002 :: *** Fixed memory-leak for PyFortranObject. *** Introduced extra keyword argument copy_ for intent(copy) variables. It defaults to 1 and forces to make a copy for intent(in) variables when passing on to wrapped functions (in case they undesirably change the variable in-situ). *** Introduced has_column_major_storage member function for all f2py generated extension modules. It is equivalent to Python call 'transpose(obj).iscontiguous()' but very efficient. *** Introduced -DF2PY_REPORT_ATEXIT. If this is used when compiling, a report is printed to stderr as python exits. The report includes the following timings: 1) time spent in all wrapped function calls; 2) time spent in f2py generated interface around the wrapped functions. This gives a hint whether one should worry about storing data in proper order (C or Fortran). 3) time spent in Python functions called by wrapped functions through call-back interface. 4) time spent in f2py generated call-back interface. For now, -DF2PY_REPORT_ATEXIT is enabled by default. Use -DF2PY_REPORT_ATEXIT_DISABLE to disable it (I am not sure if Windows has needed tools, let me know). Also, I appreciate if you could send me the output of 'F2PY performance report' (with CPU and platform information) so that I could optimize f2py generated interfaces for future releases. *** Extension modules can be linked with dmalloc library. Use -DDMALLOC when compiling. *** Moved array_from_pyobj to fortranobject.c. *** Usage of intent(inout) arguments is made more strict -- only with proper type contiguous arrays are accepted. In general, you should avoid using intent(inout) attribute as it makes wrappers of C and Fortran functions asymmetric. I recommend using intent(in,out) instead. *** intent(..) has new keywords: copy,cache. intent(copy,in) - forces a copy of an input argument; this may be useful for cases where the wrapped function changes the argument in situ and this may not be desired side effect. Otherwise, it is safe to not use intent(copy) for the sake of a better performance. intent(cache,hide|optional) - just creates a junk of memory. It does not care about proper storage order. Can be also intent(in) but then the corresponding argument must be a contiguous array with a proper elsize. *** intent(c) can be used also for subroutine names so that -DNO_APPEND_FORTRAN can be avoided for C functions. *** IMPORTANT BREAKING GOOD ... NEWS!!!: From now on you don't have to worry about the proper storage order in multi-dimensional arrays that was earlier a real headache when wrapping Fortran functions. Now f2py generated modules take care of the proper conversations when needed. I have carefully designed and optimized this interface to avoid any unnecessary memory usage or copying of data. However, it is wise to use input arrays that has proper storage order: for C arguments it is row-major and for Fortran arguments it is column-major. But you don't need to worry about that when developing your programs. The optimization of initializing the program with proper data for possibly better memory usage can be safely postponed until the program is working. This change also affects the signatures in .pyf files. If you have created wrappers that take multi-dimensional arrays in arguments, it is better to let f2py re-generate these files. Or you have to manually do the following changes: reverse the axes indices in all 'shape' macros. For example, if you have defined an array A(n,m) and n=shape(A,1), m=shape(A,0) then you must change the last statements to n=shape(A,0), m=shape(A,1). :Release: 2.8.172 :Date: 13 January 2002 :: *** Fixed -c process. Removed pyf_extensions function and pyf_file class. *** Reorganized setup.py. It generates f2py or f2py.bat scripts depending on the OS and the location of the python executable. *** Started to use update_version from numpy_distutils that makes f2py startup faster. As a side effect, the version number system changed. *** Introduced test-site/test_f2py2e.py script that runs all tests. *** Fixed global variables initialization problem in crackfortran when run_main is called several times. *** Added 'import Numeric' to C/API init function. *** Fixed f2py.bat in setup.py. *** Switched over to numpy_distutils and dropped fortran_support. *** On Windows create f2py.bat file. *** Introduced -c option: read fortran or pyf files, construct extension modules, build, and save them to current directory. In one word: do-it-all-in-one-call. *** Introduced pyf_extensions(sources,f2py_opts) function. It simplifies the extension building process considerably. Only for internal use. *** Converted tests to use numpy_distutils in order to improve portability: a,b,c *** f2py2e.run_main() returns a pyf_file class instance containing information about f2py generated files. *** Introduced `--build-dir ' command line option. *** Fixed setup.py for bdist_rpm command. *** Added --numpy-setup command line option. *** Fixed crackfortran that did not recognized capitalized type specification with --no-lower flag. *** `-h stdout' writes signature to stdout. *** Fixed incorrect message for check() with empty name list. :Release: 2.4.366 :Date: 17 December 2001 :: *** Added command line option --[no-]manifest. *** `make test' should run on Windows, but the results are not truthful. *** Reorganized f2py2e.py a bit. Introduced run_main(comline_list) function that can be useful when running f2py from another Python module. *** Removed command line options -f77,-fix,-f90 as the file format is determined from the extension of the fortran file or from its header (first line starting with `!%' and containing keywords free, fix, or f77). The later overrides the former one. *** Introduced command line options --[no-]makefile,--[no-]latex-doc. Users must explicitly use --makefile,--latex-doc if Makefile-, module.tex is desired. --setup is default. Use --no-setup to disable setup_.py generation. --overwrite-makefile will set --makefile. *** Added `f2py_rout_' to #capiname# in rules.py. *** intent(...) statement with empty namelist forces intent(...) attribute for all arguments. *** Dropped DL_IMPORT and DL_EXPORT in fortranobject.h. *** Added missing PyFortran_Type.ob_type initialization. *** Added gcc-3.0 support. *** Raising non-existing/broken Numeric as a FatalError exception. *** Fixed Python 2.x specific += construct in fortran_support.py. *** Fixed copy_ND_array for 1-rank arrays that used to call calloc(0,..) and caused core dump with a non-gcc compiler (Thanks to Pierre Schnizer for reporting this bug). *** Fixed "warning: variable `..' might be clobbered by `longjmp' or `vfork'": - Reorganized the structure of wrapper functions to get rid of `goto capi_fail' statements that caused the above warning. :Release: 2.3.343 :Date: 12 December 2001 :: *** Issues with the Win32 support (thanks to Eric Jones and Tiffany Kamm): - Using DL_EXPORT macro for init#modulename#. - Changed PyObject_HEAD_INIT(&PyType_Type) to PyObject_HEAD_INIT(0). - Initializing #name#_capi=NULL instead of Py_None in cb hooks. *** Fixed some 'warning: function declaration isn't a prototype', mainly in fortranobject.{c,h}. *** Fixed 'warning: missing braces around initializer'. *** Fixed reading a line containing only a label. *** Fixed nonportable 'cp -fv' to shutil.copy in f2py2e.py. *** Replaced PyEval_CallObject with PyObject_CallObject in cb_rules. *** Replaced Py_DECREF with Py_XDECREF when freeing hidden arguments. (Reason: Py_DECREF caused segfault when an error was raised) *** Impl. support for `include "file"' (in addition to `include 'file'') *** Fixed bugs (buildsetup.py missing in Makefile, in generated MANIFEST.in) :Release: 2.3.327 :Date: 4 December 2001 :: *** Sending out the third public release of f2py. *** Support for Intel(R) Fortran Compiler (thanks to Patrick LeGresley). *** Introduced `threadsafe' statement to pyf-files (or to be used with the 'f2py' directive in fortran codes) to force Py_BEGIN|END_ALLOW_THREADS block around the Fortran subroutine calling statement in Python C/API. `threadsafe' statement has an effect only inside a subroutine block. *** Introduced `fortranname ' statement to be used only within pyf-files. This is useful when the wrapper (Python C/API) function has different name from the wrapped (Fortran) function. *** Introduced `intent(c)' directive and statement. It is useful when wrapping C functions. Use intent(c) for arguments that are scalars (not pointers) or arrays (with row-ordering of elements). :Release: 2.3.321 :Date: 3 December 2001 :: *** f2py2e can be installed using distutils (run `python setup.py install'). *** f2py builds setup_.py. Use --[no-]setup to control this feature. setup_.py uses fortran_support module (from SciPy), but for your convenience it is included also with f2py as an additional package. Note that it has not as many compilers supported as with using Makefile-, but new compilers should be added to fortran_support module, not to f2py2e package. *** Fixed some compiler warnings about else statements. numpy-1.8.2/numpy/f2py/docs/OLDNEWS.txt0000664000175100017510000000463612370216243020671 0ustar vagrantvagrant00000000000000 .. topic:: Old F2PY NEWS March 30, 2004 F2PY bug fix release (version 2.39.235-1693). Two new command line switches: ``--compiler`` and ``--include_paths``. Support for allocatable string arrays. Callback arguments may now be arbitrary callable objects. Win32 installers for F2PY and Scipy_core are provided. `Differences with the previous release (version 2.37.235-1660)`__. __ http://cens.ioc.ee/cgi-bin/cvsweb/python/f2py2e/docs/HISTORY.txt.diff?r1=1.98&r2=1.87&f=h March 9, 2004 F2PY bug fix release (version 2.39.235-1660). `Differences with the previous release (version 2.37.235-1644)`__. __ http://cens.ioc.ee/cgi-bin/cvsweb/python/f2py2e/docs/HISTORY.txt.diff?r1=1.87&r2=1.83&f=h February 24, 2004 Latest F2PY release (version 2.39.235-1644). Support for numpy_distutils 0.2.2 and up (e.g. compiler flags can be changed via f2py command line options). Implemented support for character arrays and arrays of strings (e.g. ``character*(*) a(m,..)``). *Important bug fixes regarding complex arguments, upgrading is highly recommended*. Documentation updates. `Differences with the previous release (version 2.37.233-1545)`__. __ http://cens.ioc.ee/cgi-bin/cvsweb/python/f2py2e/docs/HISTORY.txt.diff?r1=1.83&r2=1.58&f=h September 11, 2003 Latest F2PY release (version 2.37.233-1545). New statements: ``pymethoddef`` and ``usercode`` in interface blocks. New function: ``as_column_major_storage``. New CPP macro: ``F2PY_REPORT_ON_ARRAY_COPY``. Bug fixes. `Differences with the previous release (version 2.35.229-1505)`__. __ http://cens.ioc.ee/cgi-bin/cvsweb/python/f2py2e/docs/HISTORY.txt.diff?r1=1.58&r2=1.49&f=h August 2, 2003 Latest F2PY release (version 2.35.229-1505). `Differences with the previous release (version 2.32.225-1419)`__. __ http://cens.ioc.ee/cgi-bin/cvsweb/python/f2py2e/docs/HISTORY.txt.diff?r1=1.49&r2=1.28&f=h April 2, 2003 Initial support for Numarray_ (thanks to Todd Miller). December 8, 2002 Sixth public release of F2PY (version 2.32.225-1419). Comes with revised `F2PY Users Guide`__, `new testing site`__, lots of fixes and other improvements, see `HISTORY.txt`_ for details. __ usersguide/index.html __ TESTING.txt_ .. References ========== .. _HISTORY.txt: HISTORY.html .. _Numarray: http://www.stsci.edu/resources/software_hardware/numarray .. _TESTING.txt: TESTING.html numpy-1.8.2/numpy/f2py/docs/docutils.conf0000664000175100017510000000057712370216243021512 0ustar vagrantvagrant00000000000000[general] # These entries affect all processing: #source-link: 1 datestamp: %Y-%m-%d %H:%M UTC generator: 1 # These entries affect HTML output: #stylesheet-path: pearu_style.css output-encoding: latin-1 # These entries affect reStructuredText-style PEPs: #pep-template: pep-html-template #pep-stylesheet-path: stylesheets/pep.css #python-home: http://www.python.org #no-random: 1 numpy-1.8.2/numpy/f2py/common_rules.py0000664000175100017510000001122012370216242021123 0ustar vagrantvagrant00000000000000#!/usr/bin/env python """ Build common block mechanism for f2py2e. Copyright 2000 Pearu Peterson all rights reserved, Pearu Peterson Permission to use, modify, and distribute this software is given under the terms of the NumPy License NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. $Date: 2005/05/06 10:57:33 $ Pearu Peterson """ from __future__ import division, absolute_import, print_function __version__ = "$Revision: 1.19 $"[10:-1] from . import __version__ f2py_version = __version__.version import pprint import sys errmess=sys.stderr.write outmess=sys.stdout.write show=pprint.pprint from .auxfuncs import * from . import capi_maps from . import func2subr from .crackfortran import rmbadname ############## def findcommonblocks(block,top=1): ret = [] if hascommon(block): for n in block['common'].keys(): vars={} for v in block['common'][n]: vars[v]=block['vars'][v] ret.append((n, block['common'][n], vars)) elif hasbody(block): for b in block['body']: ret=ret+findcommonblocks(b, 0) if top: tret=[] names=[] for t in ret: if t[0] not in names: names.append(t[0]) tret.append(t) return tret return ret def buildhooks(m): ret = {'commonhooks':[],'initcommonhooks':[],'docs':['"COMMON blocks:\\n"']} fwrap = [''] def fadd(line,s=fwrap): s[0] = '%s\n %s'%(s[0], line) chooks = [''] def cadd(line,s=chooks): s[0] = '%s\n%s'%(s[0], line) ihooks = [''] def iadd(line,s=ihooks): s[0] = '%s\n%s'%(s[0], line) doc = [''] def dadd(line,s=doc): s[0] = '%s\n%s'%(s[0], line) for (name, vnames, vars) in findcommonblocks(m): lower_name = name.lower() hnames, inames = [], [] for n in vnames: if isintent_hide(vars[n]): hnames.append(n) else: inames.append(n) if hnames: outmess('\t\tConstructing COMMON block support for "%s"...\n\t\t %s\n\t\t Hidden: %s\n'%(name, ','.join(inames), ','.join(hnames))) else: outmess('\t\tConstructing COMMON block support for "%s"...\n\t\t %s\n'%(name, ','.join(inames))) fadd('subroutine f2pyinit%s(setupfunc)'%name) fadd('external setupfunc') for n in vnames: fadd(func2subr.var2fixfortran(vars, n)) if name=='_BLNK_': fadd('common %s'%(','.join(vnames))) else: fadd('common /%s/ %s'%(name, ','.join(vnames))) fadd('call setupfunc(%s)'%(','.join(inames))) fadd('end\n') cadd('static FortranDataDef f2py_%s_def[] = {'%(name)) idims=[] for n in inames: ct = capi_maps.getctype(vars[n]) at = capi_maps.c2capi_map[ct] dm = capi_maps.getarrdims(n, vars[n]) if dm['dims']: idims.append('(%s)'%(dm['dims'])) else: idims.append('') dms=dm['dims'].strip() if not dms: dms='-1' cadd('\t{\"%s\",%s,{{%s}},%s},'%(n, dm['rank'], dms, at)) cadd('\t{NULL}\n};') inames1 = rmbadname(inames) inames1_tps = ','.join(['char *'+s for s in inames1]) cadd('static void f2py_setup_%s(%s) {'%(name, inames1_tps)) cadd('\tint i_f2py=0;') for n in inames1: cadd('\tf2py_%s_def[i_f2py++].data = %s;'%(name, n)) cadd('}') if '_' in lower_name: F_FUNC='F_FUNC_US' else: F_FUNC='F_FUNC' cadd('extern void %s(f2pyinit%s,F2PYINIT%s)(void(*)(%s));'\ %(F_FUNC, lower_name, name.upper(), ','.join(['char*']*len(inames1)))) cadd('static void f2py_init_%s(void) {'%name) cadd('\t%s(f2pyinit%s,F2PYINIT%s)(f2py_setup_%s);'\ %(F_FUNC, lower_name, name.upper(), name)) cadd('}\n') iadd('\tF2PyDict_SetItemString(d, \"%s\", PyFortranObject_New(f2py_%s_def,f2py_init_%s));'%(name, name, name)) tname = name.replace('_', '\\_') dadd('\\subsection{Common block \\texttt{%s}}\n'%(tname)) dadd('\\begin{description}') for n in inames: dadd('\\item[]{{}\\verb@%s@{}}'%(capi_maps.getarrdocsign(n, vars[n]))) if hasnote(vars[n]): note = vars[n]['note'] if isinstance(note, list): note='\n'.join(note) dadd('--- %s'%(note)) dadd('\\end{description}') ret['docs'].append('"\t/%s/ %s\\n"'%(name, ','.join(map(lambda v, d:v+d, inames, idims)))) ret['commonhooks']=chooks ret['initcommonhooks']=ihooks ret['latexdoc']=doc[0] if len(ret['docs'])<=1: ret['docs']='' return ret, fwrap[0] numpy-1.8.2/numpy/f2py/use_rules.py0000664000175100017510000000667212370216242020446 0ustar vagrantvagrant00000000000000#!/usr/bin/env python """ Build 'use others module data' mechanism for f2py2e. Unfinished. Copyright 2000 Pearu Peterson all rights reserved, Pearu Peterson Permission to use, modify, and distribute this software is given under the terms of the NumPy License. NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. $Date: 2000/09/10 12:35:43 $ Pearu Peterson """ from __future__ import division, absolute_import, print_function __version__ = "$Revision: 1.3 $"[10:-1] f2py_version='See `f2py -v`' import pprint import sys errmess=sys.stderr.write outmess=sys.stdout.write show=pprint.pprint from .auxfuncs import * ############## usemodule_rules={ 'body':""" #begintitle# static char doc_#apiname#[] = \"\\\nVariable wrapper signature:\\n\\ \t #name# = get_#name#()\\n\\ Arguments:\\n\\ #docstr#\"; extern F_MODFUNC(#usemodulename#,#USEMODULENAME#,#realname#,#REALNAME#); static PyObject *#apiname#(PyObject *capi_self, PyObject *capi_args) { /*#decl#*/ \tif (!PyArg_ParseTuple(capi_args, \"\")) goto capi_fail; printf(\"c: %d\\n\",F_MODFUNC(#usemodulename#,#USEMODULENAME#,#realname#,#REALNAME#)); \treturn Py_BuildValue(\"\"); capi_fail: \treturn NULL; } """, 'method':'\t{\"get_#name#\",#apiname#,METH_VARARGS|METH_KEYWORDS,doc_#apiname#},', 'need':['F_MODFUNC'] } ################ def buildusevars(m, r): ret={} outmess('\t\tBuilding use variable hooks for module "%s" (feature only for F90/F95)...\n'%(m['name'])) varsmap={} revmap={} if 'map' in r: for k in r['map'].keys(): if r['map'][k] in revmap: outmess('\t\t\tVariable "%s<=%s" is already mapped by "%s". Skipping.\n'%(r['map'][k], k, revmap[r['map'][k]])) else: revmap[r['map'][k]]=k if 'only' in r and r['only']: for v in r['map'].keys(): if r['map'][v] in m['vars']: if revmap[r['map'][v]]==v: varsmap[v]=r['map'][v] else: outmess('\t\t\tIgnoring map "%s=>%s". See above.\n'%(v, r['map'][v])) else: outmess('\t\t\tNo definition for variable "%s=>%s". Skipping.\n'%(v, r['map'][v])) else: for v in m['vars'].keys(): if v in revmap: varsmap[v]=revmap[v] else: varsmap[v]=v for v in varsmap.keys(): ret=dictappend(ret, buildusevar(v, varsmap[v], m['vars'], m['name'])) return ret def buildusevar(name, realname, vars, usemodulename): outmess('\t\t\tConstructing wrapper function for variable "%s=>%s"...\n'%(name, realname)) ret={} vrd={'name':name, 'realname':realname, 'REALNAME':realname.upper(), 'usemodulename':usemodulename, 'USEMODULENAME':usemodulename.upper(), 'texname':name.replace('_', '\\_'), 'begintitle':gentitle('%s=>%s'%(name, realname)), 'endtitle':gentitle('end of %s=>%s'%(name, realname)), 'apiname':'#modulename#_use_%s_from_%s'%(realname, usemodulename) } nummap={0:'Ro',1:'Ri',2:'Rii',3:'Riii',4:'Riv',5:'Rv',6:'Rvi',7:'Rvii',8:'Rviii',9:'Rix'} vrd['texnamename']=name for i in nummap.keys(): vrd['texnamename']=vrd['texnamename'].replace(repr(i), nummap[i]) if hasnote(vars[realname]): vrd['note']=vars[realname]['note'] rd=dictappend({}, vrd) var=vars[realname] print(name, realname, vars[realname]) ret=applyrules(usemodule_rules, rd) return ret numpy-1.8.2/numpy/f2py/src/0000775000175100017510000000000012371375430016650 5ustar vagrantvagrant00000000000000numpy-1.8.2/numpy/f2py/src/fortranobject.c0000664000175100017510000010060412370216243021652 0ustar vagrantvagrant00000000000000#define FORTRANOBJECT_C #include "fortranobject.h" #ifdef __cplusplus extern "C" { #endif /* This file implements: FortranObject, array_from_pyobj, copy_ND_array Author: Pearu Peterson $Revision: 1.52 $ $Date: 2005/07/11 07:44:20 $ */ int F2PyDict_SetItemString(PyObject *dict, char *name, PyObject *obj) { if (obj==NULL) { fprintf(stderr, "Error loading %s\n", name); if (PyErr_Occurred()) { PyErr_Print(); PyErr_Clear(); } return -1; } return PyDict_SetItemString(dict, name, obj); } /************************* FortranObject *******************************/ typedef PyObject *(*fortranfunc)(PyObject *,PyObject *,PyObject *,void *); PyObject * PyFortranObject_New(FortranDataDef* defs, f2py_void_func init) { int i; PyFortranObject *fp = NULL; PyObject *v = NULL; if (init!=NULL) /* Initialize F90 module objects */ (*(init))(); if ((fp = PyObject_New(PyFortranObject, &PyFortran_Type))==NULL) return NULL; if ((fp->dict = PyDict_New())==NULL) return NULL; fp->len = 0; while (defs[fp->len].name != NULL) fp->len++; if (fp->len == 0) goto fail; fp->defs = defs; for (i=0;ilen;i++) if (fp->defs[i].rank == -1) { /* Is Fortran routine */ v = PyFortranObject_NewAsAttr(&(fp->defs[i])); if (v==NULL) return NULL; PyDict_SetItemString(fp->dict,fp->defs[i].name,v); } else if ((fp->defs[i].data)!=NULL) { /* Is Fortran variable or array (not allocatable) */ if (fp->defs[i].type == NPY_STRING) { int n = fp->defs[i].rank-1; v = PyArray_New(&PyArray_Type, n, fp->defs[i].dims.d, NPY_STRING, NULL, fp->defs[i].data, fp->defs[i].dims.d[n], NPY_FARRAY, NULL); } else { v = PyArray_New(&PyArray_Type, fp->defs[i].rank, fp->defs[i].dims.d, fp->defs[i].type, NULL, fp->defs[i].data, 0, NPY_FARRAY, NULL); } if (v==NULL) return NULL; PyDict_SetItemString(fp->dict,fp->defs[i].name,v); } Py_XDECREF(v); return (PyObject *)fp; fail: Py_XDECREF(v); return NULL; } PyObject * PyFortranObject_NewAsAttr(FortranDataDef* defs) { /* used for calling F90 module routines */ PyFortranObject *fp = NULL; fp = PyObject_New(PyFortranObject, &PyFortran_Type); if (fp == NULL) return NULL; if ((fp->dict = PyDict_New())==NULL) return NULL; fp->len = 1; fp->defs = defs; return (PyObject *)fp; } /* Fortran methods */ static void fortran_dealloc(PyFortranObject *fp) { Py_XDECREF(fp->dict); PyMem_Del(fp); } #if PY_VERSION_HEX >= 0x03000000 #else static PyMethodDef fortran_methods[] = { {NULL, NULL} /* sentinel */ }; #endif static PyObject * fortran_doc (FortranDataDef def) { char *p; /* p is used as a buffer to hold generated documentation strings. A common operation in generating the documentation strings, is appending a string to the buffer p. Earlier, the following idiom was: sprintf(p, "%s", p); but this does not work when _FORTIFY_SOURCE=2 is enabled: instead of appending the string, the string is inserted. As a fix, the following idiom should be used for appending strings to a buffer p: sprintf(p + strlen(p), ""); */ PyObject *s = NULL; int i; unsigned size=100; if (def.doc!=NULL) size += strlen(def.doc); p = (char*)malloc (size); p[0] = '\0'; /* make sure that the buffer has zero length */ if (def.rank==-1) { if (def.doc==NULL) { if (sprintf(p,"%s - ",def.name)==0) goto fail; if (sprintf(p+strlen(p),"no docs available")==0) goto fail; } else { if (sprintf(p+strlen(p),"%s",def.doc)==0) goto fail; } } else { PyArray_Descr *d = PyArray_DescrFromType(def.type); if (sprintf(p+strlen(p),"'%c'-",d->type)==0) { Py_DECREF(d); goto fail; } Py_DECREF(d); if (def.data==NULL) { if (sprintf(p+strlen(p),"array(%" NPY_INTP_FMT,def.dims.d[0])==0) goto fail; for(i=1;i0) { if (sprintf(p+strlen(p),"array(%"NPY_INTP_FMT,def.dims.d[0])==0) goto fail; for(i=1;isize) { fprintf(stderr,"fortranobject.c:fortran_doc:len(p)=%zd>%d(size):"\ " too long doc string required, increase size\n",\ strlen(p),size); goto fail; } #if PY_VERSION_HEX >= 0x03000000 s = PyUnicode_FromString(p); #else s = PyString_FromString(p); #endif fail: free(p); return s; } static FortranDataDef *save_def; /* save pointer of an allocatable array */ static void set_data(char *d,npy_intp *f) { /* callback from Fortran */ if (*f) /* In fortran f=allocated(d) */ save_def->data = d; else save_def->data = NULL; /* printf("set_data: d=%p,f=%d\n",d,*f); */ } static PyObject * fortran_getattr(PyFortranObject *fp, char *name) { int i,j,k,flag; if (fp->dict != NULL) { PyObject *v = PyDict_GetItemString(fp->dict, name); if (v != NULL) { Py_INCREF(v); return v; } } for (i=0,j=1;ilen && (j=strcmp(name,fp->defs[i].name));i++); if (j==0) if (fp->defs[i].rank!=-1) { /* F90 allocatable array */ if (fp->defs[i].func==NULL) return NULL; for(k=0;kdefs[i].rank;++k) fp->defs[i].dims.d[k]=-1; save_def = &fp->defs[i]; (*(fp->defs[i].func))(&fp->defs[i].rank,fp->defs[i].dims.d,set_data,&flag); if (flag==2) k = fp->defs[i].rank + 1; else k = fp->defs[i].rank; if (fp->defs[i].data !=NULL) { /* array is allocated */ PyObject *v = PyArray_New(&PyArray_Type, k, fp->defs[i].dims.d, fp->defs[i].type, NULL, fp->defs[i].data, 0, NPY_FARRAY, NULL); if (v==NULL) return NULL; /* Py_INCREF(v); */ return v; } else { /* array is not allocated */ Py_INCREF(Py_None); return Py_None; } } if (strcmp(name,"__dict__")==0) { Py_INCREF(fp->dict); return fp->dict; } if (strcmp(name,"__doc__")==0) { #if PY_VERSION_HEX >= 0x03000000 PyObject *s = PyUnicode_FromString(""), *s2, *s3; for (i=0;ilen;i++) { s2 = fortran_doc(fp->defs[i]); s3 = PyUnicode_Concat(s, s2); Py_DECREF(s2); Py_DECREF(s); s = s3; } #else PyObject *s = PyString_FromString(""); for (i=0;ilen;i++) PyString_ConcatAndDel(&s,fortran_doc(fp->defs[i])); #endif if (PyDict_SetItemString(fp->dict, name, s)) return NULL; return s; } if ((strcmp(name,"_cpointer")==0) && (fp->len==1)) { PyObject *cobj = F2PyCapsule_FromVoidPtr((void *)(fp->defs[0].data),NULL); if (PyDict_SetItemString(fp->dict, name, cobj)) return NULL; return cobj; } #if PY_VERSION_HEX >= 0x03000000 if (1) { PyObject *str, *ret; str = PyUnicode_FromString(name); ret = PyObject_GenericGetAttr((PyObject *)fp, str); Py_DECREF(str); return ret; } #else return Py_FindMethod(fortran_methods, (PyObject *)fp, name); #endif } static int fortran_setattr(PyFortranObject *fp, char *name, PyObject *v) { int i,j,flag; PyArrayObject *arr = NULL; for (i=0,j=1;ilen && (j=strcmp(name,fp->defs[i].name));i++); if (j==0) { if (fp->defs[i].rank==-1) { PyErr_SetString(PyExc_AttributeError,"over-writing fortran routine"); return -1; } if (fp->defs[i].func!=NULL) { /* is allocatable array */ npy_intp dims[F2PY_MAX_DIMS]; int k; save_def = &fp->defs[i]; if (v!=Py_None) { /* set new value (reallocate if needed -- see f2py generated code for more details ) */ for(k=0;kdefs[i].rank;k++) dims[k]=-1; if ((arr = array_from_pyobj(fp->defs[i].type,dims,fp->defs[i].rank,F2PY_INTENT_IN,v))==NULL) return -1; (*(fp->defs[i].func))(&fp->defs[i].rank,arr->dimensions,set_data,&flag); } else { /* deallocate */ for(k=0;kdefs[i].rank;k++) dims[k]=0; (*(fp->defs[i].func))(&fp->defs[i].rank,dims,set_data,&flag); for(k=0;kdefs[i].rank;k++) dims[k]=-1; } memcpy(fp->defs[i].dims.d,dims,fp->defs[i].rank*sizeof(npy_intp)); } else { /* not allocatable array */ if ((arr = array_from_pyobj(fp->defs[i].type,fp->defs[i].dims.d,fp->defs[i].rank,F2PY_INTENT_IN,v))==NULL) return -1; } if (fp->defs[i].data!=NULL) { /* copy Python object to Fortran array */ npy_intp s = PyArray_MultiplyList(fp->defs[i].dims.d,arr->nd); if (s==-1) s = PyArray_MultiplyList(arr->dimensions,arr->nd); if (s<0 || (memcpy(fp->defs[i].data,arr->data,s*PyArray_ITEMSIZE(arr)))==NULL) { if ((PyObject*)arr!=v) { Py_DECREF(arr); } return -1; } if ((PyObject*)arr!=v) { Py_DECREF(arr); } } else return (fp->defs[i].func==NULL?-1:0); return 0; /* succesful */ } if (fp->dict == NULL) { fp->dict = PyDict_New(); if (fp->dict == NULL) return -1; } if (v == NULL) { int rv = PyDict_DelItemString(fp->dict, name); if (rv < 0) PyErr_SetString(PyExc_AttributeError,"delete non-existing fortran attribute"); return rv; } else return PyDict_SetItemString(fp->dict, name, v); } static PyObject* fortran_call(PyFortranObject *fp, PyObject *arg, PyObject *kw) { int i = 0; /* printf("fortran call 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)) { PyErr_Format(PyExc_RuntimeError, "no function to call"); return NULL; } else if (fp->defs[i].data==NULL) /* dummy routine */ return (*((fortranfunc)(fp->defs[i].func)))((PyObject *)fp,arg,kw,NULL); else return (*((fortranfunc)(fp->defs[i].func)))((PyObject *)fp,arg,kw, (void *)fp->defs[i].data); } PyErr_Format(PyExc_TypeError, "this fortran object is not callable"); return NULL; } static PyObject * fortran_repr(PyFortranObject *fp) { PyObject *name = NULL, *repr = NULL; name = PyObject_GetAttrString((PyObject *)fp, "__name__"); PyErr_Clear(); #if PY_VERSION_HEX >= 0x03000000 if (name != NULL && PyUnicode_Check(name)) { repr = PyUnicode_FromFormat("", name); } else { repr = PyUnicode_FromString(""); } #else if (name != NULL && PyString_Check(name)) { repr = PyString_FromFormat("", PyString_AsString(name)); } else { repr = PyString_FromString(""); } #endif Py_XDECREF(name); return repr; } PyTypeObject PyFortran_Type = { #if PY_VERSION_HEX >= 0x03000000 PyVarObject_HEAD_INIT(NULL, 0) #else PyObject_HEAD_INIT(0) 0, /*ob_size*/ #endif "fortran", /*tp_name*/ sizeof(PyFortranObject), /*tp_basicsize*/ 0, /*tp_itemsize*/ /* methods */ (destructor)fortran_dealloc, /*tp_dealloc*/ 0, /*tp_print*/ (getattrfunc)fortran_getattr, /*tp_getattr*/ (setattrfunc)fortran_setattr, /*tp_setattr*/ 0, /*tp_compare/tp_reserved*/ (reprfunc)fortran_repr, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash*/ (ternaryfunc)fortran_call, /*tp_call*/ }; /************************* f2py_report_atexit *******************************/ #ifdef F2PY_REPORT_ATEXIT static int passed_time = 0; static int passed_counter = 0; static int passed_call_time = 0; static struct timeb start_time; static struct timeb stop_time; static struct timeb start_call_time; static struct timeb stop_call_time; static int cb_passed_time = 0; static int cb_passed_counter = 0; static int cb_passed_call_time = 0; static struct timeb cb_start_time; static struct timeb cb_stop_time; static struct timeb cb_start_call_time; static struct timeb cb_stop_call_time; extern void f2py_start_clock(void) { ftime(&start_time); } extern void f2py_start_call_clock(void) { f2py_stop_clock(); ftime(&start_call_time); } extern void f2py_stop_clock(void) { ftime(&stop_time); passed_time += 1000*(stop_time.time - start_time.time); passed_time += stop_time.millitm - start_time.millitm; } extern void f2py_stop_call_clock(void) { ftime(&stop_call_time); passed_call_time += 1000*(stop_call_time.time - start_call_time.time); passed_call_time += stop_call_time.millitm - start_call_time.millitm; passed_counter += 1; f2py_start_clock(); } extern void f2py_cb_start_clock(void) { ftime(&cb_start_time); } extern void f2py_cb_start_call_clock(void) { f2py_cb_stop_clock(); ftime(&cb_start_call_time); } extern void f2py_cb_stop_clock(void) { ftime(&cb_stop_time); cb_passed_time += 1000*(cb_stop_time.time - cb_start_time.time); cb_passed_time += cb_stop_time.millitm - cb_start_time.millitm; } extern void f2py_cb_stop_call_clock(void) { ftime(&cb_stop_call_time); cb_passed_call_time += 1000*(cb_stop_call_time.time - cb_start_call_time.time); cb_passed_call_time += cb_stop_call_time.millitm - cb_start_call_time.millitm; cb_passed_counter += 1; f2py_cb_start_clock(); } static int f2py_report_on_exit_been_here = 0; extern void f2py_report_on_exit(int exit_flag,void *name) { if (f2py_report_on_exit_been_here) { fprintf(stderr," %s\n",(char*)name); return; } f2py_report_on_exit_been_here = 1; fprintf(stderr," /-----------------------\\\n"); fprintf(stderr," < F2PY performance report >\n"); fprintf(stderr," \\-----------------------/\n"); fprintf(stderr,"Overall time spent in ...\n"); fprintf(stderr,"(a) wrapped (Fortran/C) functions : %8d msec\n", passed_call_time); fprintf(stderr,"(b) f2py interface, %6d calls : %8d msec\n", passed_counter,passed_time); fprintf(stderr,"(c) call-back (Python) functions : %8d msec\n", cb_passed_call_time); fprintf(stderr,"(d) f2py call-back interface, %6d calls : %8d msec\n", cb_passed_counter,cb_passed_time); fprintf(stderr,"(e) wrapped (Fortran/C) functions (acctual) : %8d msec\n\n", passed_call_time-cb_passed_call_time-cb_passed_time); fprintf(stderr,"Use -DF2PY_REPORT_ATEXIT_DISABLE to disable this message.\n"); fprintf(stderr,"Exit status: %d\n",exit_flag); fprintf(stderr,"Modules : %s\n",(char*)name); } #endif /********************** report on array copy ****************************/ #ifdef F2PY_REPORT_ON_ARRAY_COPY static void f2py_report_on_array_copy(PyArrayObject* arr) { const long arr_size = PyArray_Size((PyObject *)arr); if (arr_size>F2PY_REPORT_ON_ARRAY_COPY) { fprintf(stderr,"copied an array: size=%ld, elsize=%d\n", arr_size, PyArray_ITEMSIZE(arr)); } } static void f2py_report_on_array_copy_fromany(void) { fprintf(stderr,"created an array from object\n"); } #define F2PY_REPORT_ON_ARRAY_COPY_FROMARR f2py_report_on_array_copy((PyArrayObject *)arr) #define F2PY_REPORT_ON_ARRAY_COPY_FROMANY f2py_report_on_array_copy_fromany() #else #define F2PY_REPORT_ON_ARRAY_COPY_FROMARR #define F2PY_REPORT_ON_ARRAY_COPY_FROMANY #endif /************************* array_from_obj *******************************/ /* * File: array_from_pyobj.c * * Description: * ------------ * Provides array_from_pyobj function that returns a contigious array * object with the given dimensions and required storage order, either * in row-major (C) or column-major (Fortran) order. The function * array_from_pyobj is very flexible about its Python object argument * that can be any number, list, tuple, or array. * * array_from_pyobj is used in f2py generated Python extension * modules. * * Author: Pearu Peterson * Created: 13-16 January 2002 * $Id: fortranobject.c,v 1.52 2005/07/11 07:44:20 pearu Exp $ */ static int count_nonpos(const int rank, const npy_intp *dims) { int i=0,r=0; while (ind; npy_intp size = PyArray_Size((PyObject *)arr); printf("\trank = %d, flags = %d, size = %" NPY_INTP_FMT "\n", rank,arr->flags,size); printf("\tstrides = "); dump_dims(rank,arr->strides); printf("\tdimensions = "); dump_dims(rank,arr->dimensions); } #endif #define SWAPTYPE(a,b,t) {t c; c = (a); (a) = (b); (b) = c; } static int swap_arrays(PyArrayObject* arr1, PyArrayObject* arr2) { SWAPTYPE(arr1->data,arr2->data,char*); SWAPTYPE(arr1->nd,arr2->nd,int); SWAPTYPE(arr1->dimensions,arr2->dimensions,npy_intp*); SWAPTYPE(arr1->strides,arr2->strides,npy_intp*); SWAPTYPE(arr1->base,arr2->base,PyObject*); SWAPTYPE(arr1->descr,arr2->descr,PyArray_Descr*); SWAPTYPE(arr1->flags,arr2->flags,int); /* SWAPTYPE(arr1->weakreflist,arr2->weakreflist,PyObject*); */ return 0; } #define ARRAY_ISCOMPATIBLE(arr,type_num) \ ( (PyArray_ISINTEGER(arr) && PyTypeNum_ISINTEGER(type_num)) \ ||(PyArray_ISFLOAT(arr) && PyTypeNum_ISFLOAT(type_num)) \ ||(PyArray_ISCOMPLEX(arr) && PyTypeNum_ISCOMPLEX(type_num)) \ ||(PyArray_ISBOOL(arr) && PyTypeNum_ISBOOL(type_num)) \ ) extern PyArrayObject* array_from_pyobj(const int type_num, npy_intp *dims, const int rank, const int intent, PyObject *obj) { /* Note about reference counting ----------------------------- If the caller returns the array to Python, it must be done with Py_BuildValue("N",arr). Otherwise, if obj!=arr then the caller must call Py_DECREF(arr). Note on intent(cache,out,..) --------------------- Don't expect correct data when returning intent(cache) array. */ char mess[200]; PyArrayObject *arr = NULL; PyArray_Descr *descr; char typechar; int elsize; if ((intent & F2PY_INTENT_HIDE) || ((intent & F2PY_INTENT_CACHE) && (obj==Py_None)) || ((intent & F2PY_OPTIONAL) && (obj==Py_None)) ) { /* intent(cache), optional, intent(hide) */ if (count_nonpos(rank,dims)) { int i; sprintf(mess,"failed to create intent(cache|hide)|optional array" "-- must have defined dimensions but got ("); for(i=0;ielsize; typechar = descr->type; Py_DECREF(descr); if (PyArray_Check(obj)) { arr = (PyArrayObject *)obj; if (intent & F2PY_INTENT_CACHE) { /* intent(cache) */ if (PyArray_ISONESEGMENT(obj) && PyArray_ITEMSIZE((PyArrayObject *)obj)>=elsize) { if (check_and_fix_dimensions((PyArrayObject *)obj,rank,dims)) { return NULL; /*XXX: set exception */ } if (intent & F2PY_INTENT_OUT) Py_INCREF(obj); return (PyArrayObject *)obj; } sprintf(mess,"failed to initialize intent(cache) array"); if (!PyArray_ISONESEGMENT(obj)) sprintf(mess+strlen(mess)," -- input must be in one segment"); if (PyArray_ITEMSIZE(arr)descr->type,typechar); if (!(F2PY_CHECK_ALIGNMENT(arr, intent))) sprintf(mess+strlen(mess)," -- input not %d-aligned", F2PY_GET_ALIGNMENT(intent)); PyErr_SetString(PyExc_ValueError,mess); return NULL; } /* here we have always intent(in) or intent(inplace) */ { PyArrayObject *retarr = (PyArrayObject *) \ PyArray_New(&PyArray_Type, arr->nd, arr->dimensions, type_num, NULL,NULL,0, !(intent&F2PY_INTENT_C), NULL); if (retarr==NULL) return NULL; F2PY_REPORT_ON_ARRAY_COPY_FROMARR; if (PyArray_CopyInto(retarr, arr)) { Py_DECREF(retarr); return NULL; } if (intent & F2PY_INTENT_INPLACE) { if (swap_arrays(arr,retarr)) return NULL; /* XXX: set exception */ Py_XDECREF(retarr); if (intent & F2PY_INTENT_OUT) Py_INCREF(arr); } else { arr = retarr; } } 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); return NULL; } { F2PY_REPORT_ON_ARRAY_COPY_FROMANY; arr = (PyArrayObject *) \ PyArray_FromAny(obj,PyArray_DescrFromType(type_num), 0,0, ((intent & F2PY_INTENT_C)?NPY_CARRAY:NPY_FARRAY) \ | NPY_FORCECAST, NULL); if (arr==NULL) return NULL; if (check_and_fix_dimensions(arr,rank,dims)) return NULL; /*XXX: set exception */ return arr; } } /*****************************************/ /* Helper functions for array_from_pyobj */ /*****************************************/ static int check_and_fix_dimensions(const PyArrayObject* arr,const int rank,npy_intp *dims) { /* This function fills in blanks (that are -1\'s) in dims list using the dimensions from arr. It also checks that non-blank dims will match with the corresponding values in arr dimensions. */ const npy_intp arr_size = (arr->nd)?PyArray_Size((PyObject *)arr):1; #ifdef DEBUG_COPY_ND_ARRAY dump_attrs(arr); printf("check_and_fix_dimensions:init: dims="); dump_dims(rank,dims); #endif if (rank > arr->nd) { /* [1,2] -> [[1],[2]]; 1 -> [[1]] */ npy_intp new_size = 1; int free_axe = -1; int i; npy_intp d; /* Fill dims where -1 or 0; check dimensions; calc new_size; */ for(i=0;ind;++i) { d = arr->dimensions[i]; if (dims[i] >= 0) { if (d>1 && dims[i]!=d) { fprintf(stderr,"%d-th dimension must be fixed to %" NPY_INTP_FMT " but got %" NPY_INTP_FMT "\n", i,dims[i], d); return 1; } if (!dims[i]) dims[i] = 1; } else { dims[i] = d ? d : 1; } new_size *= dims[i]; } for(i=arr->nd;i1) { fprintf(stderr,"%d-th dimension must be %" NPY_INTP_FMT " but got 0 (not defined).\n", i,dims[i]); return 1; } else if (free_axe<0) free_axe = i; else dims[i] = 1; if (free_axe>=0) { dims[free_axe] = arr_size/new_size; new_size *= dims[free_axe]; } if (new_size != arr_size) { fprintf(stderr,"unexpected array size: new_size=%" NPY_INTP_FMT ", got array with arr_size=%" NPY_INTP_FMT " (maybe too many free" " indices)\n", new_size,arr_size); return 1; } } else if (rank==arr->nd) { npy_intp new_size = 1; int i; npy_intp d; for (i=0; idimensions[i]; if (dims[i]>=0) { if (d > 1 && d!=dims[i]) { fprintf(stderr,"%d-th dimension must be fixed to %" NPY_INTP_FMT " but got %" NPY_INTP_FMT "\n", i,dims[i],d); return 1; } if (!dims[i]) dims[i] = 1; } else dims[i] = d; new_size *= dims[i]; } if (new_size != arr_size) { fprintf(stderr,"unexpected array size: new_size=%" NPY_INTP_FMT ", got array with arr_size=%" NPY_INTP_FMT "\n", new_size,arr_size); return 1; } } else { /* [[1,2]] -> [[1],[2]] */ int i,j; npy_intp d; int effrank; npy_intp size; for (i=0,effrank=0;ind;++i) if (arr->dimensions[i]>1) ++effrank; if (dims[rank-1]>=0) if (effrank>rank) { fprintf(stderr,"too many axes: %d (effrank=%d), expected rank=%d\n", arr->nd,effrank,rank); return 1; } for (i=0,j=0;ind && arr->dimensions[j]<2) ++j; if (j>=arr->nd) d = 1; else d = arr->dimensions[j++]; if (dims[i]>=0) { if (d>1 && d!=dims[i]) { fprintf(stderr,"%d-th dimension must be fixed to %" NPY_INTP_FMT " but got %" NPY_INTP_FMT " (real index=%d)\n", i,dims[i],d,j-1); return 1; } if (!dims[i]) dims[i] = 1; } else dims[i] = d; } for (i=rank;ind;++i) { /* [[1,2],[3,4]] -> [1,2,3,4] */ while (jnd && arr->dimensions[j]<2) ++j; if (j>=arr->nd) d = 1; else d = arr->dimensions[j++]; dims[rank-1] *= d; } for (i=0,size=1;ind); for (i=0;ind;++i) fprintf(stderr," %" NPY_INTP_FMT,arr->dimensions[i]); fprintf(stderr," ]\n"); return 1; } } #ifdef DEBUG_COPY_ND_ARRAY printf("check_and_fix_dimensions:end: dims="); dump_dims(rank,dims); #endif return 0; } /* End of file: array_from_pyobj.c */ /************************* copy_ND_array *******************************/ extern int copy_ND_array(const PyArrayObject *arr, PyArrayObject *out) { F2PY_REPORT_ON_ARRAY_COPY_FROMARR; return PyArray_CopyInto(out, (PyArrayObject *)arr); } /*********************************************/ /* Compatibility functions for Python >= 3.0 */ /*********************************************/ #if PY_VERSION_HEX >= 0x03000000 PyObject * F2PyCapsule_FromVoidPtr(void *ptr, void (*dtor)(PyObject *)) { PyObject *ret = PyCapsule_New(ptr, NULL, dtor); if (ret == NULL) { PyErr_Clear(); } return ret; } void * F2PyCapsule_AsVoidPtr(PyObject *obj) { void *ret = PyCapsule_GetPointer(obj, NULL); if (ret == NULL) { PyErr_Clear(); } return ret; } int F2PyCapsule_Check(PyObject *ptr) { return PyCapsule_CheckExact(ptr); } #else PyObject * F2PyCapsule_FromVoidPtr(void *ptr, void (*dtor)(void *)) { return PyCObject_FromVoidPtr(ptr, dtor); } void * F2PyCapsule_AsVoidPtr(PyObject *ptr) { return PyCObject_AsVoidPtr(ptr); } int F2PyCapsule_Check(PyObject *ptr) { return PyCObject_Check(ptr); } #endif #ifdef __cplusplus } #endif /************************* EOF fortranobject.c *******************************/ numpy-1.8.2/numpy/f2py/src/fortranobject.h0000664000175100017510000001125612370216243021663 0ustar vagrantvagrant00000000000000#ifndef Py_FORTRANOBJECT_H #define Py_FORTRANOBJECT_H #ifdef __cplusplus extern "C" { #endif #include "Python.h" #ifdef FORTRANOBJECT_C #define NO_IMPORT_ARRAY #endif #define PY_ARRAY_UNIQUE_SYMBOL _npy_f2py_ARRAY_API #include "numpy/arrayobject.h" /* * Python 3 support macros */ #if PY_VERSION_HEX >= 0x03000000 #define PyString_Check PyBytes_Check #define PyString_GET_SIZE PyBytes_GET_SIZE #define PyString_AS_STRING PyBytes_AS_STRING #define PyString_FromString PyBytes_FromString #define PyString_ConcatAndDel PyBytes_ConcatAndDel #define PyString_AsString PyBytes_AsString #define PyInt_Check PyLong_Check #define PyInt_FromLong PyLong_FromLong #define PyInt_AS_LONG PyLong_AsLong #define PyInt_AsLong PyLong_AsLong #define PyNumber_Int PyNumber_Long #endif #ifdef F2PY_REPORT_ATEXIT #include extern void f2py_start_clock(void); extern void f2py_stop_clock(void); extern void f2py_start_call_clock(void); extern void f2py_stop_call_clock(void); extern void f2py_cb_start_clock(void); extern void f2py_cb_stop_clock(void); extern void f2py_cb_start_call_clock(void); extern void f2py_cb_stop_call_clock(void); extern void f2py_report_on_exit(int,void*); #endif #ifdef DMALLOC #include "dmalloc.h" #endif /* Fortran object interface */ /* 123456789-123456789-123456789-123456789-123456789-123456789-123456789-12 PyFortranObject represents various Fortran objects: Fortran (module) routines, COMMON blocks, module data. Author: Pearu Peterson */ #define F2PY_MAX_DIMS 40 typedef void (*f2py_set_data_func)(char*,npy_intp*); typedef void (*f2py_void_func)(void); typedef void (*f2py_init_func)(int*,npy_intp*,f2py_set_data_func,int*); /*typedef void* (*f2py_c_func)(void*,...);*/ typedef void *(*f2pycfunc)(void); typedef struct { char *name; /* attribute (array||routine) name */ int rank; /* array rank, 0 for scalar, max is F2PY_MAX_DIMS, || rank=-1 for Fortran routine */ struct {npy_intp d[F2PY_MAX_DIMS];} dims; /* dimensions of the array, || not used */ int type; /* PyArray_ || not used */ char *data; /* pointer to array || Fortran routine */ f2py_init_func func; /* initialization function for allocatable arrays: func(&rank,dims,set_ptr_func,name,len(name)) || C/API wrapper for Fortran routine */ char *doc; /* documentation string; only recommended for routines. */ } FortranDataDef; typedef struct { PyObject_HEAD int len; /* Number of attributes */ FortranDataDef *defs; /* An array of FortranDataDef's */ PyObject *dict; /* Fortran object attribute dictionary */ } PyFortranObject; #define PyFortran_Check(op) (Py_TYPE(op) == &PyFortran_Type) #define PyFortran_Check1(op) (0==strcmp(Py_TYPE(op)->tp_name,"fortran")) extern PyTypeObject PyFortran_Type; extern int F2PyDict_SetItemString(PyObject* dict, char *name, PyObject *obj); extern PyObject * PyFortranObject_New(FortranDataDef* defs, f2py_void_func init); extern PyObject * PyFortranObject_NewAsAttr(FortranDataDef* defs); #if PY_VERSION_HEX >= 0x03000000 PyObject * F2PyCapsule_FromVoidPtr(void *ptr, void (*dtor)(PyObject *)); void * F2PyCapsule_AsVoidPtr(PyObject *obj); int F2PyCapsule_Check(PyObject *ptr); #else PyObject * F2PyCapsule_FromVoidPtr(void *ptr, void (*dtor)(void *)); void * F2PyCapsule_AsVoidPtr(PyObject *ptr); int F2PyCapsule_Check(PyObject *ptr); #endif #define ISCONTIGUOUS(m) ((m)->flags & NPY_CONTIGUOUS) #define F2PY_INTENT_IN 1 #define F2PY_INTENT_INOUT 2 #define F2PY_INTENT_OUT 4 #define F2PY_INTENT_HIDE 8 #define F2PY_INTENT_CACHE 16 #define F2PY_INTENT_COPY 32 #define F2PY_INTENT_C 64 #define F2PY_OPTIONAL 128 #define F2PY_INTENT_INPLACE 256 #define F2PY_INTENT_ALIGNED4 512 #define F2PY_INTENT_ALIGNED8 1024 #define F2PY_INTENT_ALIGNED16 2048 #define ARRAY_ISALIGNED(ARR, SIZE) ((size_t)(PyArray_DATA(ARR)) % (SIZE) == 0) #define F2PY_ALIGN4(intent) (intent & F2PY_INTENT_ALIGNED4) #define F2PY_ALIGN8(intent) (intent & F2PY_INTENT_ALIGNED8) #define F2PY_ALIGN16(intent) (intent & F2PY_INTENT_ALIGNED16) #define F2PY_GET_ALIGNMENT(intent) \ (F2PY_ALIGN4(intent) ? 4 : \ (F2PY_ALIGN8(intent) ? 8 : \ (F2PY_ALIGN16(intent) ? 16 : 1) )) #define F2PY_CHECK_ALIGNMENT(arr, intent) ARRAY_ISALIGNED(arr, F2PY_GET_ALIGNMENT(intent)) extern PyArrayObject* array_from_pyobj(const int type_num, npy_intp *dims, const int rank, const int intent, PyObject *obj); extern int copy_ND_array(const PyArrayObject *in, PyArrayObject *out); #ifdef DEBUG_COPY_ND_ARRAY extern void dump_attrs(const PyArrayObject* arr); #endif #ifdef __cplusplus } #endif #endif /* !Py_FORTRANOBJECT_H */ numpy-1.8.2/numpy/f2py/auxfuncs.py0000664000175100017510000004701312370216242020266 0ustar vagrantvagrant00000000000000#!/usr/bin/env python """ Auxiliary functions for f2py2e. Copyright 1999,2000 Pearu Peterson all rights reserved, Pearu Peterson Permission to use, modify, and distribute this software is given under the terms of the NumPy (BSD style) LICENSE. NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. $Date: 2005/07/24 19:01:55 $ Pearu Peterson """ from __future__ import division, absolute_import, print_function import pprint import sys import types from functools import reduce from . import __version__ from . import cfuncs f2py_version = __version__.version errmess=sys.stderr.write #outmess=sys.stdout.write show=pprint.pprint options={} debugoptions=[] wrapfuncs = 1 def outmess(t): if options.get('verbose', 1): sys.stdout.write(t) def debugcapi(var): return 'capi' in debugoptions def _isstring(var): return 'typespec' in var and var['typespec']=='character' and (not isexternal(var)) def isstring(var): return _isstring(var) and not isarray(var) def ischaracter(var): return isstring(var) and 'charselector' not in var def isstringarray(var): return isarray(var) and _isstring(var) def isarrayofstrings(var): # leaving out '*' for now so that # `character*(*) a(m)` and `character a(m,*)` # are treated differently. Luckily `character**` is illegal. return isstringarray(var) and var['dimension'][-1]=='(*)' def isarray(var): return 'dimension' in var and (not isexternal(var)) def isscalar(var): return not (isarray(var) or isstring(var) or isexternal(var)) def iscomplex(var): return isscalar(var) and var.get('typespec') in ['complex', 'double complex'] def islogical(var): return isscalar(var) and var.get('typespec')=='logical' def isinteger(var): return isscalar(var) and var.get('typespec')=='integer' def isreal(var): return isscalar(var) and var.get('typespec')=='real' def get_kind(var): try: return var['kindselector']['*'] except KeyError: try: return var['kindselector']['kind'] except KeyError: pass def islong_long(var): if not isscalar(var): return 0 if var.get('typespec') not in ['integer', 'logical']: return 0 return get_kind(var)=='8' def isunsigned_char(var): if not isscalar(var): return 0 if var.get('typespec') != 'integer': return 0 return get_kind(var)=='-1' def isunsigned_short(var): if not isscalar(var): return 0 if var.get('typespec') != 'integer': return 0 return get_kind(var)=='-2' def isunsigned(var): if not isscalar(var): return 0 if var.get('typespec') != 'integer': return 0 return get_kind(var)=='-4' def isunsigned_long_long(var): if not isscalar(var): return 0 if var.get('typespec') != 'integer': return 0 return get_kind(var)=='-8' def isdouble(var): if not isscalar(var): return 0 if not var.get('typespec')=='real': return 0 return get_kind(var)=='8' def islong_double(var): if not isscalar(var): return 0 if not var.get('typespec')=='real': return 0 return get_kind(var)=='16' def islong_complex(var): if not iscomplex(var): return 0 return get_kind(var)=='32' def iscomplexarray(var): return isarray(var) and var.get('typespec') in ['complex', 'double complex'] def isint1array(var): return isarray(var) and var.get('typespec')=='integer' \ and get_kind(var)=='1' def isunsigned_chararray(var): return isarray(var) and var.get('typespec') in ['integer', 'logical']\ and get_kind(var)=='-1' def isunsigned_shortarray(var): return isarray(var) and var.get('typespec') in ['integer', 'logical']\ and get_kind(var)=='-2' def isunsignedarray(var): return isarray(var) and var.get('typespec') in ['integer', 'logical']\ and get_kind(var)=='-4' def isunsigned_long_longarray(var): return isarray(var) and var.get('typespec') in ['integer', 'logical']\ and get_kind(var)=='-8' def issigned_chararray(var): return isarray(var) and var.get('typespec') in ['integer', 'logical']\ and get_kind(var)=='1' def issigned_shortarray(var): return isarray(var) and var.get('typespec') in ['integer', 'logical']\ and get_kind(var)=='2' def issigned_array(var): return isarray(var) and var.get('typespec') in ['integer', 'logical']\ and get_kind(var)=='4' def issigned_long_longarray(var): return isarray(var) and var.get('typespec') in ['integer', 'logical']\ and get_kind(var)=='8' def isallocatable(var): return 'attrspec' in var and 'allocatable' in var['attrspec'] def ismutable(var): return not (not 'dimension' in var or isstring(var)) def ismoduleroutine(rout): return 'modulename' in rout def ismodule(rout): return ('block' in rout and 'module'==rout['block']) def isfunction(rout): return ('block' in rout and 'function'==rout['block']) #def isfunction_wrap(rout): # return wrapfuncs and (iscomplexfunction(rout) or isstringfunction(rout)) and (not isexternal(rout)) def isfunction_wrap(rout): if isintent_c(rout): return 0 return wrapfuncs and isfunction(rout) and (not isexternal(rout)) def issubroutine(rout): return ('block' in rout and 'subroutine'==rout['block']) def issubroutine_wrap(rout): if isintent_c(rout): return 0 return issubroutine(rout) and hasassumedshape(rout) def hasassumedshape(rout): if rout.get('hasassumedshape'): return True for a in rout['args']: for d in rout['vars'].get(a, {}).get('dimension', []): if d==':': rout['hasassumedshape'] = True return True return False def isroutine(rout): return isfunction(rout) or issubroutine(rout) def islogicalfunction(rout): if not isfunction(rout): return 0 if 'result' in rout: a=rout['result'] else: a=rout['name'] if a in rout['vars']: return islogical(rout['vars'][a]) return 0 def islong_longfunction(rout): if not isfunction(rout): return 0 if 'result' in rout: a=rout['result'] else: a=rout['name'] if a in rout['vars']: return islong_long(rout['vars'][a]) return 0 def islong_doublefunction(rout): if not isfunction(rout): return 0 if 'result' in rout: a=rout['result'] else: a=rout['name'] if a in rout['vars']: return islong_double(rout['vars'][a]) return 0 def iscomplexfunction(rout): if not isfunction(rout): return 0 if 'result' in rout: a=rout['result'] else: a=rout['name'] if a in rout['vars']: return iscomplex(rout['vars'][a]) return 0 def iscomplexfunction_warn(rout): if iscomplexfunction(rout): outmess("""\ ************************************************************** Warning: code with a function returning complex value may not work correctly with your Fortran compiler. Run the following test before using it in your applications: $(f2py install dir)/test-site/{b/runme_scalar,e/runme} When using GNU gcc/g77 compilers, codes should work correctly. **************************************************************\n""") return 1 return 0 def isstringfunction(rout): if not isfunction(rout): return 0 if 'result' in rout: a=rout['result'] else: a=rout['name'] if a in rout['vars']: return isstring(rout['vars'][a]) return 0 def hasexternals(rout): return 'externals' in rout and rout['externals'] def isthreadsafe(rout): return 'f2pyenhancements' in rout and 'threadsafe' in rout['f2pyenhancements'] def hasvariables(rout): return 'vars' in rout and rout['vars'] def isoptional(var): return ('attrspec' in var and 'optional' in var['attrspec'] and 'required' not in var['attrspec']) and isintent_nothide(var) def isexternal(var): return ('attrspec' in var and 'external' in var['attrspec']) def isrequired(var): return not isoptional(var) and isintent_nothide(var) def isintent_in(var): if 'intent' not in var: return 1 if 'hide' in var['intent']: return 0 if 'inplace' in var['intent']: return 0 if 'in' in var['intent']: return 1 if 'out' in var['intent']: return 0 if 'inout' in var['intent']: return 0 if 'outin' in var['intent']: return 0 return 1 def isintent_inout(var): return 'intent' in var and ('inout' in var['intent'] or 'outin' in var['intent']) and 'in' not in var['intent'] and 'hide' not in var['intent'] and 'inplace' not in var['intent'] def isintent_out(var): return 'out' in var.get('intent', []) def isintent_hide(var): return ('intent' in var and ('hide' in var['intent'] or ('out' in var['intent'] and 'in' not in var['intent'] and (not l_or(isintent_inout, isintent_inplace)(var))))) def isintent_nothide(var): return not isintent_hide(var) def isintent_c(var): return 'c' in var.get('intent', []) # def isintent_f(var): # return not isintent_c(var) def isintent_cache(var): return 'cache' in var.get('intent', []) def isintent_copy(var): return 'copy' in var.get('intent', []) def isintent_overwrite(var): return 'overwrite' in var.get('intent', []) def isintent_callback(var): return 'callback' in var.get('intent', []) def isintent_inplace(var): return 'inplace' in var.get('intent', []) def isintent_aux(var): return 'aux' in var.get('intent', []) def isintent_aligned4(var): return 'aligned4' in var.get('intent', []) def isintent_aligned8(var): return 'aligned8' in var.get('intent', []) def isintent_aligned16(var): return 'aligned16' in var.get('intent', []) isintent_dict = {isintent_in: 'INTENT_IN', isintent_inout: 'INTENT_INOUT', isintent_out: 'INTENT_OUT', isintent_hide: 'INTENT_HIDE', isintent_cache: 'INTENT_CACHE', isintent_c: 'INTENT_C', isoptional: 'OPTIONAL', isintent_inplace: 'INTENT_INPLACE', isintent_aligned4: 'INTENT_ALIGNED4', isintent_aligned8: 'INTENT_ALIGNED8', isintent_aligned16: 'INTENT_ALIGNED16', } def isprivate(var): return 'attrspec' in var and 'private' in var['attrspec'] def hasinitvalue(var): return '=' in var def hasinitvalueasstring(var): if not hasinitvalue(var): return 0 return var['='][0] in ['"', "'"] def hasnote(var): return 'note' in var def hasresultnote(rout): if not isfunction(rout): return 0 if 'result' in rout: a=rout['result'] else: a=rout['name'] if a in rout['vars']: return hasnote(rout['vars'][a]) return 0 def hascommon(rout): return 'common' in rout def containscommon(rout): if hascommon(rout): return 1 if hasbody(rout): for b in rout['body']: if containscommon(b): return 1 return 0 def containsmodule(block): if ismodule(block): return 1 if not hasbody(block): return 0 for b in block['body']: if containsmodule(b): return 1 return 0 def hasbody(rout): return 'body' in rout def hascallstatement(rout): return getcallstatement(rout) is not None def istrue(var): return 1 def isfalse(var): return 0 class F2PYError(Exception): pass class throw_error: def __init__(self, mess): self.mess = mess def __call__(self, var): mess = '\n\n var = %s\n Message: %s\n' % (var, self.mess) raise F2PYError(mess) def l_and(*f): l, l2='lambda v', [] for i in range(len(f)): l='%s,f%d=f[%d]'%(l, i, i) l2.append('f%d(v)'%(i)) return eval('%s:%s'%(l, ' and '.join(l2))) def l_or(*f): l, l2='lambda v', [] for i in range(len(f)): l='%s,f%d=f[%d]'%(l, i, i) l2.append('f%d(v)'%(i)) return eval('%s:%s'%(l, ' or '.join(l2))) def l_not(f): return eval('lambda v,f=f:not f(v)') def isdummyroutine(rout): try: return rout['f2pyenhancements']['fortranname']=='' except KeyError: return 0 def getfortranname(rout): try: name = rout['f2pyenhancements']['fortranname'] if name=='': raise KeyError if not name: errmess('Failed to use fortranname from %s\n'%(rout['f2pyenhancements'])) raise KeyError except KeyError: name = rout['name'] return name def getmultilineblock(rout,blockname,comment=1,counter=0): try: r = rout['f2pyenhancements'].get(blockname) except KeyError: return if not r: return if counter > 0 and isinstance(r, str): return if isinstance(r, list): if counter>=len(r): return r = r[counter] if r[:3]=="'''": if comment: r = '\t/* start ' + blockname + ' multiline ('+repr(counter)+') */\n' + r[3:] else: r = r[3:] if r[-3:]=="'''": if comment: r = r[:-3] + '\n\t/* end multiline ('+repr(counter)+')*/' else: r = r[:-3] else: errmess("%s multiline block should end with `'''`: %s\n" \ % (blockname, repr(r))) return r def getcallstatement(rout): return getmultilineblock(rout, 'callstatement') def getcallprotoargument(rout,cb_map={}): r = getmultilineblock(rout, 'callprotoargument', comment=0) if r: return r if hascallstatement(rout): outmess('warning: callstatement is defined without callprotoargument\n') return from .capi_maps import getctype arg_types, arg_types2 = [], [] if l_and(isstringfunction, l_not(isfunction_wrap))(rout): arg_types.extend(['char*', 'size_t']) for n in rout['args']: var = rout['vars'][n] if isintent_callback(var): continue if n in cb_map: ctype = cb_map[n]+'_typedef' else: ctype = getctype(var) if l_and(isintent_c, l_or(isscalar, iscomplex))(var): pass elif isstring(var): pass #ctype = 'void*' else: ctype = ctype+'*' if isstring(var) or isarrayofstrings(var): arg_types2.append('size_t') arg_types.append(ctype) proto_args = ','.join(arg_types+arg_types2) if not proto_args: proto_args = 'void' #print proto_args return proto_args def getusercode(rout): return getmultilineblock(rout, 'usercode') def getusercode1(rout): return getmultilineblock(rout, 'usercode', counter=1) def getpymethoddef(rout): return getmultilineblock(rout, 'pymethoddef') def getargs(rout): sortargs, args=[], [] if 'args' in rout: args=rout['args'] if 'sortvars' in rout: for a in rout['sortvars']: if a in args: sortargs.append(a) for a in args: if a not in sortargs: sortargs.append(a) else: sortargs=rout['args'] return args, sortargs def getargs2(rout): sortargs, args=[], rout.get('args', []) auxvars = [a for a in rout['vars'].keys() if isintent_aux(rout['vars'][a])\ and a not in args] args = auxvars + args if 'sortvars' in rout: for a in rout['sortvars']: if a in args: sortargs.append(a) for a in args: if a not in sortargs: sortargs.append(a) else: sortargs=auxvars + rout['args'] return args, sortargs def getrestdoc(rout): if 'f2pymultilines' not in rout: return None k = None if rout['block']=='python module': k = rout['block'], rout['name'] return rout['f2pymultilines'].get(k, None) def gentitle(name): l=(80-len(name)-6)//2 return '/*%s %s %s*/'%(l*'*', name, l*'*') def flatlist(l): if isinstance(l, list): return reduce(lambda x,y,f=flatlist:x+f(y), l, []) return [l] def stripcomma(s): if s and s[-1]==',': return s[:-1] return s def replace(str,d,defaultsep=''): if isinstance(d, list): return [replace(str, _m, defaultsep) for _m in d] if isinstance(str, list): return [replace(_m, d, defaultsep) for _m in str] for k in 2*list(d.keys()): if k=='separatorsfor': continue if 'separatorsfor' in d and k in d['separatorsfor']: sep=d['separatorsfor'][k] else: sep=defaultsep if isinstance(d[k], list): str=str.replace('#%s#'%(k), sep.join(flatlist(d[k]))) else: str=str.replace('#%s#'%(k), d[k]) return str def dictappend(rd, ar): if isinstance(ar, list): for a in ar: rd=dictappend(rd, a) return rd for k in ar.keys(): if k[0]=='_': continue if k in rd: if isinstance(rd[k], str): rd[k]=[rd[k]] if isinstance(rd[k], list): if isinstance(ar[k], list): rd[k]=rd[k]+ar[k] else: rd[k].append(ar[k]) elif isinstance(rd[k], dict): if isinstance(ar[k], dict): if k=='separatorsfor': for k1 in ar[k].keys(): if k1 not in rd[k]: rd[k][k1]=ar[k][k1] else: rd[k]=dictappend(rd[k], ar[k]) else: rd[k]=ar[k] return rd def applyrules(rules,d,var={}): ret={} if isinstance(rules, list): for r in rules: rr=applyrules(r, d, var) ret=dictappend(ret, rr) if '_break' in rr: break return ret if '_check' in rules and (not rules['_check'](var)): return ret if 'need' in rules: res = applyrules({'needs':rules['need']}, d, var) if 'needs' in res: cfuncs.append_needs(res['needs']) for k in rules.keys(): if k=='separatorsfor': ret[k]=rules[k]; continue if isinstance(rules[k], str): ret[k]=replace(rules[k], d) elif isinstance(rules[k], list): ret[k]=[] for i in rules[k]: ar=applyrules({k:i}, d, var) if k in ar: ret[k].append(ar[k]) elif k[0]=='_': continue elif isinstance(rules[k], dict): ret[k]=[] for k1 in rules[k].keys(): if isinstance(k1, types.FunctionType) and k1(var): if isinstance(rules[k][k1], list): for i in rules[k][k1]: if isinstance(i, dict): res=applyrules({'supertext':i}, d, var) if 'supertext' in res: i=res['supertext'] else: i='' ret[k].append(replace(i, d)) else: i=rules[k][k1] if isinstance(i, dict): res=applyrules({'supertext':i}, d) if 'supertext' in res: i=res['supertext'] else: i='' ret[k].append(replace(i, d)) else: errmess('applyrules: ignoring rule %s.\n'%repr(rules[k])) if isinstance(ret[k], list): if len(ret[k])==1: ret[k]=ret[k][0] if ret[k]==[]: del ret[k] return ret numpy-1.8.2/numpy/f2py/f2py_testing.py0000664000175100017510000000300412370216242021037 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function import sys import re from numpy.testing.utils import jiffies, memusage def cmdline(): m=re.compile(r'\A\d+\Z') args = [] repeat = 1 for a in sys.argv[1:]: if m.match(a): repeat = eval(a) else: args.append(a) f2py_opts = ' '.join(args) return repeat, f2py_opts def run(runtest,test_functions,repeat=1): l = [(t, repr(t.__doc__.split('\n')[1].strip())) for t in test_functions] #l = [(t,'') for t in test_functions] start_memusage = memusage() diff_memusage = None start_jiffies = jiffies() i = 0 while i Permission to use, modify, and distribute this software is given under the terms of the NumPy License. NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. $Date: 2004/11/26 11:13:06 $ Pearu Peterson """ from __future__ import division, absolute_import, print_function __version__ = "$Revision: 1.16 $"[10:-1] f2py_version='See `f2py -v`' import pprint import copy import sys errmess=sys.stderr.write outmess=sys.stdout.write show=pprint.pprint from .auxfuncs import * def var2fixfortran(vars,a,fa=None,f90mode=None): if fa is None: fa = a if a not in vars: show(vars) outmess('var2fixfortran: No definition for argument "%s".\n'%a) return '' if 'typespec' not in vars[a]: show(vars[a]) outmess('var2fixfortran: No typespec for argument "%s".\n'%a) return '' vardef=vars[a]['typespec'] if vardef=='type' and 'typename' in vars[a]: vardef='%s(%s)'%(vardef, vars[a]['typename']) selector={} lk = '' if 'kindselector' in vars[a]: selector=vars[a]['kindselector'] lk = 'kind' elif 'charselector' in vars[a]: selector=vars[a]['charselector'] lk = 'len' if '*' in selector: if f90mode: if selector['*'] in ['*', ':', '(*)']: vardef='%s(len=*)'%(vardef) else: vardef='%s(%s=%s)'%(vardef, lk, selector['*']) else: if selector['*'] in ['*', ':']: vardef='%s*(%s)'%(vardef, selector['*']) else: vardef='%s*%s'%(vardef, selector['*']) else: if 'len' in selector: vardef='%s(len=%s'%(vardef, selector['len']) if 'kind' in selector: vardef='%s,kind=%s)'%(vardef, selector['kind']) else: vardef='%s)'%(vardef) elif 'kind' in selector: vardef='%s(kind=%s)'%(vardef, selector['kind']) vardef='%s %s'%(vardef, fa) if 'dimension' in vars[a]: vardef='%s(%s)'%(vardef, ','.join(vars[a]['dimension'])) return vardef def createfuncwrapper(rout,signature=0): assert isfunction(rout) extra_args = [] vars = rout['vars'] for a in rout['args']: v = rout['vars'][a] for i, d in enumerate(v.get('dimension', [])): if d==':': dn = 'f2py_%s_d%s' % (a, i) dv = dict(typespec='integer', intent=['hide']) dv['='] = 'shape(%s, %s)' % (a, i) extra_args.append(dn) vars[dn] = dv v['dimension'][i] = dn rout['args'].extend(extra_args) need_interface = bool(extra_args) ret = [''] def add(line,ret=ret): ret[0] = '%s\n %s'%(ret[0], line) name = rout['name'] fortranname = getfortranname(rout) f90mode = ismoduleroutine(rout) newname = '%sf2pywrap'%(name) if newname not in vars: vars[newname] = vars[name] args = [newname]+rout['args'][1:] else: args = [newname]+rout['args'] l = var2fixfortran(vars, name, newname, f90mode) return_char_star = 0 if l[:13]=='character*(*)': return_char_star = 1 if f90mode: l = 'character(len=10)'+l[13:] else: l = 'character*10'+l[13:] charselect = vars[name]['charselector'] if charselect.get('*', '')=='(*)': charselect['*'] = '10' sargs = ', '.join(args) if f90mode: add('subroutine f2pywrap_%s_%s (%s)'%(rout['modulename'], name, sargs)) if not signature: add('use %s, only : %s'%(rout['modulename'], fortranname)) else: add('subroutine f2pywrap%s (%s)'%(name, sargs)) if not need_interface: add('external %s'%(fortranname)) l = l + ', '+fortranname if need_interface: for line in rout['saved_interface'].split('\n'): if line.lstrip().startswith('use '): add(line) args = args[1:] dumped_args = [] for a in args: if isexternal(vars[a]): add('external %s'%(a)) dumped_args.append(a) for a in args: if a in dumped_args: continue if isscalar(vars[a]): add(var2fixfortran(vars, a, f90mode=f90mode)) dumped_args.append(a) for a in args: if a in dumped_args: continue if isintent_in(vars[a]): add(var2fixfortran(vars, a, f90mode=f90mode)) dumped_args.append(a) for a in args: if a in dumped_args: continue add(var2fixfortran(vars, a, f90mode=f90mode)) add(l) if need_interface: if f90mode: # f90 module already defines needed interface pass else: add('interface') add(rout['saved_interface'].lstrip()) add('end interface') sargs = ', '.join([a for a in args if a not in extra_args]) if not signature: if islogicalfunction(rout): add('%s = .not.(.not.%s(%s))'%(newname, fortranname, sargs)) else: add('%s = %s(%s)'%(newname, fortranname, sargs)) if f90mode: add('end subroutine f2pywrap_%s_%s'%(rout['modulename'], name)) else: add('end') #print '**'*10 #print ret[0] #print '**'*10 return ret[0] def createsubrwrapper(rout,signature=0): assert issubroutine(rout) extra_args = [] vars = rout['vars'] for a in rout['args']: v = rout['vars'][a] for i, d in enumerate(v.get('dimension', [])): if d==':': dn = 'f2py_%s_d%s' % (a, i) dv = dict(typespec='integer', intent=['hide']) dv['='] = 'shape(%s, %s)' % (a, i) extra_args.append(dn) vars[dn] = dv v['dimension'][i] = dn rout['args'].extend(extra_args) need_interface = bool(extra_args) ret = [''] def add(line,ret=ret): ret[0] = '%s\n %s'%(ret[0], line) name = rout['name'] fortranname = getfortranname(rout) f90mode = ismoduleroutine(rout) args = rout['args'] sargs = ', '.join(args) if f90mode: add('subroutine f2pywrap_%s_%s (%s)'%(rout['modulename'], name, sargs)) if not signature: add('use %s, only : %s'%(rout['modulename'], fortranname)) else: add('subroutine f2pywrap%s (%s)'%(name, sargs)) if not need_interface: add('external %s'%(fortranname)) if need_interface: for line in rout['saved_interface'].split('\n'): if line.lstrip().startswith('use '): add(line) dumped_args = [] for a in args: if isexternal(vars[a]): add('external %s'%(a)) dumped_args.append(a) for a in args: if a in dumped_args: continue if isscalar(vars[a]): add(var2fixfortran(vars, a, f90mode=f90mode)) dumped_args.append(a) for a in args: if a in dumped_args: continue add(var2fixfortran(vars, a, f90mode=f90mode)) if need_interface: if f90mode: # f90 module already defines needed interface pass else: add('interface') add(rout['saved_interface'].lstrip()) add('end interface') sargs = ', '.join([a for a in args if a not in extra_args]) if not signature: add('call %s(%s)'%(fortranname, sargs)) if f90mode: add('end subroutine f2pywrap_%s_%s'%(rout['modulename'], name)) else: add('end') #print '**'*10 #print ret[0] #print '**'*10 return ret[0] def assubr(rout): if isfunction_wrap(rout): fortranname = getfortranname(rout) name = rout['name'] outmess('\t\tCreating wrapper for Fortran function "%s"("%s")...\n'%(name, fortranname)) rout = copy.copy(rout) fname = name rname = fname if 'result' in rout: rname = rout['result'] rout['vars'][fname]=rout['vars'][rname] fvar = rout['vars'][fname] if not isintent_out(fvar): if 'intent' not in fvar: fvar['intent']=[] fvar['intent'].append('out') flag=1 for i in fvar['intent']: if i.startswith('out='): flag = 0 break if flag: fvar['intent'].append('out=%s' % (rname)) rout['args'][:] = [fname] + rout['args'] return rout, createfuncwrapper(rout) if issubroutine_wrap(rout): fortranname = getfortranname(rout) name = rout['name'] outmess('\t\tCreating wrapper for Fortran subroutine "%s"("%s")...\n'%(name, fortranname)) rout = copy.copy(rout) return rout, createsubrwrapper(rout) return rout, '' numpy-1.8.2/numpy/f2py/__version__.py0000664000175100017510000000037612370216242020714 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function major = 2 try: from __svn_version__ import version version_info = (major, version) version = '%s_%s' % version_info except (ImportError, ValueError): version = str(major) numpy-1.8.2/numpy/f2py/f2py.10000664000175100017510000001344312370216243017023 0ustar vagrantvagrant00000000000000.TH "F2PY" 1 .SH NAME f2py \- Fortran to Python interface generator .SH SYNOPSIS (1) To construct extension module sources: .B f2py [] [[[only:]||[skip:]] ] [: ...] (2) To compile fortran files and build extension modules: .B f2py -c [, , ] (3) To generate signature files: .B f2py -h ...< same options as in (1) > .SH DESCRIPTION This program generates a Python C/API file (module.c) that contains wrappers for given Fortran or C functions so that they can be called from Python. With the \-c option the corresponding extension modules are built. .SH OPTIONS .TP .B \-h Write signatures of the fortran routines to file and exit. You can then edit and use it instead of . If ==stdout then the signatures are printed to stdout. .TP .B Names of fortran routines for which Python C/API functions will be generated. Default is all that are found in . .TP .B skip: Ignore fortran functions that follow until `:'. .TP .B only: Use only fortran functions that follow until `:'. .TP .B : Get back to mode. .TP .B \-m Name of the module; f2py generates a Python/C API file module.c or extension module . Default is \'untitled\'. .TP .B \-\-[no\-]lower Do [not] lower the cases in . By default, \-\-lower is assumed with \-h key, and \-\-no\-lower without \-h key. .TP .B \-\-build\-dir All f2py generated files are created in . Default is tempfile.mkdtemp(). .TP .B \-\-overwrite\-signature Overwrite existing signature file. .TP .B \-\-[no\-]latex\-doc Create (or not) module.tex. Default is \-\-no\-latex\-doc. .TP .B \-\-short\-latex Create 'incomplete' LaTeX document (without commands \\documentclass, \\tableofcontents, and \\begin{document}, \\end{document}). .TP .B \-\-[no\-]rest\-doc Create (or not) module.rst. Default is \-\-no\-rest\-doc. .TP .B \-\-debug\-capi Create C/API code that reports the state of the wrappers during runtime. Useful for debugging. .TP .B \-include\'\' Add CPP #include statement to the C/API code. should be in the format of either `"filename.ext"' or `'. As a result will be included just before wrapper functions part in the C/API code. The option is depreciated, use `usercode` statement in signature files instead. .TP .B \-\-[no\-]wrap\-functions Create Fortran subroutine wrappers to Fortran 77 functions. \-\-wrap\-functions is default because it ensures maximum portability/compiler independence. .TP .B \-\-help\-link [..] List system resources found by system_info.py. [..] may contain a list of resources names. See also \-\-link\- switch below. .TP .B \-\-quiet Run quietly. .TP .B \-\-verbose Run with extra verbosity. .TP .B \-v Print f2py version ID and exit. .TP .B \-\-include_paths path1:path2:... Search include files (that f2py will scan) from the given directories. .SH "CONFIG_FC OPTIONS" The following options are effective only when \-c switch is used. .TP .B \-\-help-compiler List available Fortran compilers [DEPRECIATED]. .TP .B \-\-fcompiler= Specify Fortran compiler type by vendor. .TP .B \-\-compiler= Specify C compiler type (as defined by distutils) .TP .B \-\-fcompiler-exec= Specify the path to F77 compiler [DEPRECIATED]. .TP .B \-\-f90compiler\-exec= Specify the path to F90 compiler [DEPRECIATED]. .TP .B \-\-help\-fcompiler List available Fortran compilers and exit. .TP .B \-\-f77exec= Specify the path to F77 compiler. .TP .B \-\-f90exec= Specify the path to F90 compiler. .TP .B \-\-f77flags="..." Specify F77 compiler flags. .TP .B \-\-f90flags="..." Specify F90 compiler flags. .TP .B \-\-opt="..." Specify optimization flags. .TP .B \-\-arch="..." Specify architecture specific optimization flags. .TP .B \-\-noopt Compile without optimization. .TP .B \-\-noarch Compile without arch-dependent optimization. .TP .B \-\-debug Compile with debugging information. .SH "EXTRA OPTIONS" The following options are effective only when \-c switch is used. .TP .B \-\-link- Link extension module with as defined by numpy_distutils/system_info.py. E.g. to link with optimized LAPACK libraries (vecLib on MacOSX, ATLAS elsewhere), use \-\-link\-lapack_opt. See also \-\-help\-link switch. .TP .B -L/path/to/lib/ -l .TP .B -D -U -I/path/to/include/ .TP .B .o .so .a .TP .B -DPREPEND_FORTRAN -DNO_APPEND_FORTRAN -DUPPERCASE_FORTRAN -DUNDERSCORE_G77 Macros that might be required with non-gcc Fortran compilers. .TP .B -DF2PY_REPORT_ATEXIT To print out a performance report of F2PY interface when python exits. Available for Linux. .TP .B -DF2PY_REPORT_ON_ARRAY_COPY= To send a message to stderr whenever F2PY interface makes a copy of an array. Integer sets the threshold for array sizes when a message should be shown. .SH REQUIREMENTS Python 1.5.2 or higher (2.x is supported). Numerical Python 13 or higher (20.x,21.x,22.x,23.x are supported). Optional Numarray 0.9 or higher partially supported. numpy_distutils from Scipy (can be downloaded from F2PY homepage) .SH "SEE ALSO" python(1) .SH BUGS For instructions on reporting bugs, see http://cens.ioc.ee/projects/f2py2e/FAQ.html .SH AUTHOR Pearu Peterson .SH "INTERNET RESOURCES" Main website: http://cens.ioc.ee/projects/f2py2e/ User's Guide: http://cens.ioc.ee/projects/f2py2e/usersguide/ Mailing list: http://cens.ioc.ee/mailman/listinfo/f2py-users/ Scipy website: http://www.numpy.org .SH COPYRIGHT Copyright (c) 1999, 2000, 2001, 2002, 2003, 2004, 2005 Pearu Peterson .SH LICENSE NumPy License .SH VERSION 2.45.241 numpy-1.8.2/numpy/f2py/info.py0000664000175100017510000000021012370216242017351 0ustar vagrantvagrant00000000000000"""Fortran to Python Interface Generator. """ from __future__ import division, absolute_import, print_function postpone_import = True numpy-1.8.2/numpy/f2py/cb_rules.py0000664000175100017510000005037612370216242020236 0ustar vagrantvagrant00000000000000#!/usr/bin/env python """ Build call-back mechanism for f2py2e. Copyright 2000 Pearu Peterson all rights reserved, Pearu Peterson Permission to use, modify, and distribute this software is given under the terms of the NumPy License. NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. $Date: 2005/07/20 11:27:58 $ Pearu Peterson """ from __future__ import division, absolute_import, print_function import pprint import sys from . import __version__ from .auxfuncs import * from . import cfuncs f2py_version = __version__.version errmess=sys.stderr.write outmess=sys.stdout.write show=pprint.pprint ################## Rules for callback function ############## cb_routine_rules={ 'cbtypedefs':'typedef #rctype#(*#name#_typedef)(#optargs_td##args_td##strarglens_td##noargs#);', 'body':""" #begintitle# PyObject *#name#_capi = NULL;/*was Py_None*/ PyTupleObject *#name#_args_capi = NULL; int #name#_nofargs = 0; jmp_buf #name#_jmpbuf; /*typedef #rctype#(*#name#_typedef)(#optargs_td##args_td##strarglens_td##noargs#);*/ #static# #rctype# #callbackname# (#optargs##args##strarglens##noargs#) { \tPyTupleObject *capi_arglist = #name#_args_capi; \tPyObject *capi_return = NULL; \tPyObject *capi_tmp = NULL; \tint capi_j,capi_i = 0; \tint capi_longjmp_ok = 1; #decl# #ifdef F2PY_REPORT_ATEXIT f2py_cb_start_clock(); #endif \tCFUNCSMESS(\"cb:Call-back function #name# (maxnofargs=#maxnofargs#(-#nofoptargs#))\\n\"); \tCFUNCSMESSPY(\"cb:#name#_capi=\",#name#_capi); \tif (#name#_capi==NULL) { \t\tcapi_longjmp_ok = 0; \t\t#name#_capi = PyObject_GetAttrString(#modulename#_module,\"#argname#\"); \t} \tif (#name#_capi==NULL) { \t\tPyErr_SetString(#modulename#_error,\"cb: Callback #argname# not defined (as an argument or module #modulename# attribute).\\n\"); \t\tgoto capi_fail; \t} \tif (F2PyCapsule_Check(#name#_capi)) { \t#name#_typedef #name#_cptr; \t#name#_cptr = F2PyCapsule_AsVoidPtr(#name#_capi); \t#returncptr#(*#name#_cptr)(#optargs_nm##args_nm##strarglens_nm#); \t#return# \t} \tif (capi_arglist==NULL) { \t\tcapi_longjmp_ok = 0; \t\tcapi_tmp = PyObject_GetAttrString(#modulename#_module,\"#argname#_extra_args\"); \t\tif (capi_tmp) { \t\t\tcapi_arglist = (PyTupleObject *)PySequence_Tuple(capi_tmp); \t\t\tif (capi_arglist==NULL) { \t\t\t\tPyErr_SetString(#modulename#_error,\"Failed to convert #modulename#.#argname#_extra_args to tuple.\\n\"); \t\t\t\tgoto capi_fail; \t\t\t} \t\t} else { \t\t\tPyErr_Clear(); \t\t\tcapi_arglist = (PyTupleObject *)Py_BuildValue(\"()\"); \t\t} \t} \tif (capi_arglist == NULL) { \t\tPyErr_SetString(#modulename#_error,\"Callback #argname# argument list is not set.\\n\"); \t\tgoto capi_fail; \t} #setdims# #pyobjfrom# \tCFUNCSMESSPY(\"cb:capi_arglist=\",capi_arglist); \tCFUNCSMESS(\"cb:Call-back calling Python function #argname#.\\n\"); #ifdef F2PY_REPORT_ATEXIT f2py_cb_start_call_clock(); #endif \tcapi_return = PyObject_CallObject(#name#_capi,(PyObject *)capi_arglist); #ifdef F2PY_REPORT_ATEXIT f2py_cb_stop_call_clock(); #endif \tCFUNCSMESSPY(\"cb:capi_return=\",capi_return); \tif (capi_return == NULL) { \t\tfprintf(stderr,\"capi_return is NULL\\n\"); \t\tgoto capi_fail; \t} \tif (capi_return == Py_None) { \t\tPy_DECREF(capi_return); \t\tcapi_return = Py_BuildValue(\"()\"); \t} \telse if (!PyTuple_Check(capi_return)) { \t\tcapi_return = Py_BuildValue(\"(N)\",capi_return); \t} \tcapi_j = PyTuple_Size(capi_return); \tcapi_i = 0; #frompyobj# \tCFUNCSMESS(\"cb:#name#:successful\\n\"); \tPy_DECREF(capi_return); #ifdef F2PY_REPORT_ATEXIT f2py_cb_stop_clock(); #endif \tgoto capi_return_pt; capi_fail: \tfprintf(stderr,\"Call-back #name# failed.\\n\"); \tPy_XDECREF(capi_return); \tif (capi_longjmp_ok) \t\tlongjmp(#name#_jmpbuf,-1); capi_return_pt: \t; #return# } #endtitle# """, 'need':['setjmp.h', 'CFUNCSMESS'], 'maxnofargs':'#maxnofargs#', 'nofoptargs':'#nofoptargs#', 'docstr':"""\ \tdef #argname#(#docsignature#): return #docreturn#\\n\\ #docstrsigns#""", 'latexdocstr':""" {{}\\verb@def #argname#(#latexdocsignature#): return #docreturn#@{}} #routnote# #latexdocstrsigns#""", 'docstrshort':'def #argname#(#docsignature#): return #docreturn#' } cb_rout_rules=[ {# Init 'separatorsfor': {'decl': '\n', 'args': ',', 'optargs': '', 'pyobjfrom': '\n', 'freemem': '\n', 'args_td': ',', 'optargs_td': '', 'args_nm': ',', 'optargs_nm': '', 'frompyobj': '\n', 'setdims': '\n', 'docstrsigns': '\\n"\n"', 'latexdocstrsigns': '\n', 'latexdocstrreq': '\n', 'latexdocstropt': '\n', 'latexdocstrout': '\n', 'latexdocstrcbs': '\n', }, 'decl': '/*decl*/', 'pyobjfrom': '/*pyobjfrom*/', 'frompyobj': '/*frompyobj*/', 'args': [], 'optargs': '', 'return': '', 'strarglens': '', 'freemem': '/*freemem*/', 'args_td': [], 'optargs_td': '', 'strarglens_td': '', 'args_nm': [], 'optargs_nm': '', 'strarglens_nm': '', 'noargs': '', 'setdims': '/*setdims*/', 'docstrsigns': '', 'latexdocstrsigns': '', 'docstrreq': '\tRequired arguments:', 'docstropt': '\tOptional arguments:', 'docstrout': '\tReturn objects:', 'docstrcbs': '\tCall-back functions:', 'docreturn': '', 'docsign': '', 'docsignopt': '', 'latexdocstrreq': '\\noindent Required arguments:', 'latexdocstropt': '\\noindent Optional arguments:', 'latexdocstrout': '\\noindent Return objects:', 'latexdocstrcbs': '\\noindent Call-back functions:', 'routnote': {hasnote:'--- #note#',l_not(hasnote):''}, }, { # Function 'decl':'\t#ctype# return_value;', 'frompyobj':[{debugcapi:'\tCFUNCSMESS("cb:Getting return_value->");'}, '\tif (capi_j>capi_i)\n\t\tGETSCALARFROMPYTUPLE(capi_return,capi_i++,&return_value,#ctype#,"#ctype#_from_pyobj failed in converting return_value of call-back function #name# to C #ctype#\\n");', {debugcapi:'\tfprintf(stderr,"#showvalueformat#.\\n",return_value);'} ], 'need':['#ctype#_from_pyobj', {debugcapi:'CFUNCSMESS'}, 'GETSCALARFROMPYTUPLE'], 'return':'\treturn return_value;', '_check':l_and(isfunction, l_not(isstringfunction), l_not(iscomplexfunction)) }, {# String function 'pyobjfrom':{debugcapi:'\tfprintf(stderr,"debug-capi:cb:#name#:%d:\\n",return_value_len);'}, 'args':'#ctype# return_value,int return_value_len', 'args_nm':'return_value,&return_value_len', 'args_td':'#ctype# ,int', 'frompyobj':[{debugcapi:'\tCFUNCSMESS("cb:Getting return_value->\\"");'}, """\tif (capi_j>capi_i) \t\tGETSTRFROMPYTUPLE(capi_return,capi_i++,return_value,return_value_len);""", {debugcapi:'\tfprintf(stderr,"#showvalueformat#\\".\\n",return_value);'} ], 'need':['#ctype#_from_pyobj', {debugcapi:'CFUNCSMESS'}, 'string.h', 'GETSTRFROMPYTUPLE'], 'return':'return;', '_check':isstringfunction }, {# Complex function 'optargs':""" #ifndef F2PY_CB_RETURNCOMPLEX #ctype# *return_value #endif """, 'optargs_nm':""" #ifndef F2PY_CB_RETURNCOMPLEX return_value #endif """, 'optargs_td':""" #ifndef F2PY_CB_RETURNCOMPLEX #ctype# * #endif """, 'decl':""" #ifdef F2PY_CB_RETURNCOMPLEX \t#ctype# return_value; #endif """, 'frompyobj':[{debugcapi:'\tCFUNCSMESS("cb:Getting return_value->");'}, """\ \tif (capi_j>capi_i) #ifdef F2PY_CB_RETURNCOMPLEX \t\tGETSCALARFROMPYTUPLE(capi_return,capi_i++,&return_value,#ctype#,\"#ctype#_from_pyobj failed in converting return_value of call-back function #name# to C #ctype#\\n\"); #else \t\tGETSCALARFROMPYTUPLE(capi_return,capi_i++,return_value,#ctype#,\"#ctype#_from_pyobj failed in converting return_value of call-back function #name# to C #ctype#\\n\"); #endif """, {debugcapi:""" #ifdef F2PY_CB_RETURNCOMPLEX \tfprintf(stderr,\"#showvalueformat#.\\n\",(return_value).r,(return_value).i); #else \tfprintf(stderr,\"#showvalueformat#.\\n\",(*return_value).r,(*return_value).i); #endif """} ], 'return':""" #ifdef F2PY_CB_RETURNCOMPLEX \treturn return_value; #else \treturn; #endif """, 'need':['#ctype#_from_pyobj', {debugcapi:'CFUNCSMESS'}, 'string.h', 'GETSCALARFROMPYTUPLE', '#ctype#'], '_check':iscomplexfunction }, {'docstrout':'\t\t#pydocsignout#', 'latexdocstrout':['\\item[]{{}\\verb@#pydocsignout#@{}}', {hasnote:'--- #note#'}], 'docreturn':'#rname#,', '_check':isfunction}, {'_check':issubroutine,'return':'return;'} ] cb_arg_rules=[ { # Doc 'docstropt':{l_and(isoptional, isintent_nothide):'\t\t#pydocsign#'}, 'docstrreq':{l_and(isrequired, isintent_nothide):'\t\t#pydocsign#'}, 'docstrout':{isintent_out:'\t\t#pydocsignout#'}, 'latexdocstropt':{l_and(isoptional, isintent_nothide):['\\item[]{{}\\verb@#pydocsign#@{}}', {hasnote:'--- #note#'}]}, 'latexdocstrreq':{l_and(isrequired, isintent_nothide):['\\item[]{{}\\verb@#pydocsign#@{}}', {hasnote:'--- #note#'}]}, 'latexdocstrout':{isintent_out:['\\item[]{{}\\verb@#pydocsignout#@{}}', {l_and(hasnote, isintent_hide):'--- #note#', l_and(hasnote, isintent_nothide):'--- See above.'}]}, 'docsign':{l_and(isrequired, isintent_nothide):'#varname#,'}, 'docsignopt':{l_and(isoptional, isintent_nothide):'#varname#,'}, 'depend':'' }, { 'args': { l_and (isscalar, isintent_c):'#ctype# #varname_i#', l_and (isscalar, l_not(isintent_c)):'#ctype# *#varname_i#_cb_capi', isarray:'#ctype# *#varname_i#', isstring:'#ctype# #varname_i#' }, 'args_nm': { l_and (isscalar, isintent_c):'#varname_i#', l_and (isscalar, l_not(isintent_c)):'#varname_i#_cb_capi', isarray:'#varname_i#', isstring:'#varname_i#' }, 'args_td': { l_and (isscalar, isintent_c):'#ctype#', l_and (isscalar, l_not(isintent_c)):'#ctype# *', isarray:'#ctype# *', isstring:'#ctype#' }, 'strarglens': {isstring:',int #varname_i#_cb_len'}, # untested with multiple args 'strarglens_td': {isstring:',int'}, # untested with multiple args 'strarglens_nm': {isstring:',#varname_i#_cb_len'}, # untested with multiple args }, { # Scalars 'decl':{l_not(isintent_c):'\t#ctype# #varname_i#=(*#varname_i#_cb_capi);'}, 'error': {l_and(isintent_c, isintent_out, throw_error('intent(c,out) is forbidden for callback scalar arguments')):\ ''}, 'frompyobj':[{debugcapi:'\tCFUNCSMESS("cb:Getting #varname#->");'}, {isintent_out:'\tif (capi_j>capi_i)\n\t\tGETSCALARFROMPYTUPLE(capi_return,capi_i++,#varname_i#_cb_capi,#ctype#,"#ctype#_from_pyobj failed in converting argument #varname# of call-back function #name# to C #ctype#\\n");'}, {l_and(debugcapi, l_and(l_not(iscomplex), isintent_c)):'\tfprintf(stderr,"#showvalueformat#.\\n",#varname_i#);'}, {l_and(debugcapi, l_and(l_not(iscomplex), l_not(isintent_c))):'\tfprintf(stderr,"#showvalueformat#.\\n",*#varname_i#_cb_capi);'}, {l_and(debugcapi, l_and(iscomplex, isintent_c)):'\tfprintf(stderr,"#showvalueformat#.\\n",(#varname_i#).r,(#varname_i#).i);'}, {l_and(debugcapi, l_and(iscomplex, l_not(isintent_c))):'\tfprintf(stderr,"#showvalueformat#.\\n",(*#varname_i#_cb_capi).r,(*#varname_i#_cb_capi).i);'}, ], 'need':[{isintent_out:['#ctype#_from_pyobj', 'GETSCALARFROMPYTUPLE']}, {debugcapi:'CFUNCSMESS'}], '_check':isscalar }, { 'pyobjfrom':[{isintent_in:"""\ \tif (#name#_nofargs>capi_i) \t\tif (PyTuple_SetItem((PyObject *)capi_arglist,capi_i++,pyobj_from_#ctype#1(#varname_i#))) \t\t\tgoto capi_fail;"""}, {isintent_inout:"""\ \tif (#name#_nofargs>capi_i) \t\tif (PyTuple_SetItem((PyObject *)capi_arglist,capi_i++,pyarr_from_p_#ctype#1(#varname_i#_cb_capi))) \t\t\tgoto capi_fail;"""}], 'need':[{isintent_in:'pyobj_from_#ctype#1'}, {isintent_inout:'pyarr_from_p_#ctype#1'}, {iscomplex:'#ctype#'}], '_check':l_and(isscalar, isintent_nothide), '_optional':'' }, {# String 'frompyobj':[{debugcapi:'\tCFUNCSMESS("cb:Getting #varname#->\\"");'}, """\tif (capi_j>capi_i) \t\tGETSTRFROMPYTUPLE(capi_return,capi_i++,#varname_i#,#varname_i#_cb_len);""", {debugcapi:'\tfprintf(stderr,"#showvalueformat#\\":%d:.\\n",#varname_i#,#varname_i#_cb_len);'}, ], 'need':['#ctype#', 'GETSTRFROMPYTUPLE', {debugcapi:'CFUNCSMESS'}, 'string.h'], '_check':l_and(isstring, isintent_out) }, { 'pyobjfrom':[{debugcapi:'\tfprintf(stderr,"debug-capi:cb:#varname#=\\"#showvalueformat#\\":%d:\\n",#varname_i#,#varname_i#_cb_len);'}, {isintent_in:"""\ \tif (#name#_nofargs>capi_i) \t\tif (PyTuple_SetItem((PyObject *)capi_arglist,capi_i++,pyobj_from_#ctype#1size(#varname_i#,#varname_i#_cb_len))) \t\t\tgoto capi_fail;"""}, {isintent_inout:"""\ \tif (#name#_nofargs>capi_i) { \t\tint #varname_i#_cb_dims[] = {#varname_i#_cb_len}; \t\tif (PyTuple_SetItem((PyObject *)capi_arglist,capi_i++,pyarr_from_p_#ctype#1(#varname_i#,#varname_i#_cb_dims))) \t\t\tgoto capi_fail; \t}"""}], 'need':[{isintent_in:'pyobj_from_#ctype#1size'}, {isintent_inout:'pyarr_from_p_#ctype#1'}], '_check':l_and(isstring, isintent_nothide), '_optional':'' }, # Array ... { 'decl':'\tnpy_intp #varname_i#_Dims[#rank#] = {#rank*[-1]#};', 'setdims':'\t#cbsetdims#;', '_check':isarray, '_depend':'' }, { 'pyobjfrom': [{debugcapi:'\tfprintf(stderr,"debug-capi:cb:#varname#\\n");'}, {isintent_c: """\ \tif (#name#_nofargs>capi_i) { \t\tPyArrayObject *tmp_arr = (PyArrayObject *)PyArray_New(&PyArray_Type,#rank#,#varname_i#_Dims,#atype#,NULL,(char*)#varname_i#,0,NPY_CARRAY,NULL); /*XXX: Hmm, what will destroy this array??? */ """, l_not(isintent_c): """\ \tif (#name#_nofargs>capi_i) { \t\tPyArrayObject *tmp_arr = (PyArrayObject *)PyArray_New(&PyArray_Type,#rank#,#varname_i#_Dims,#atype#,NULL,(char*)#varname_i#,0,NPY_FARRAY,NULL); /*XXX: Hmm, what will destroy this array??? */ """, }, """ \t\tif (tmp_arr==NULL) \t\t\tgoto capi_fail; \t\tif (PyTuple_SetItem((PyObject *)capi_arglist,capi_i++,(PyObject *)tmp_arr)) \t\t\tgoto capi_fail; }"""], '_check': l_and(isarray, isintent_nothide, l_or(isintent_in, isintent_inout)), '_optional': '', }, { 'frompyobj':[{debugcapi:'\tCFUNCSMESS("cb:Getting #varname#->");'}, """\tif (capi_j>capi_i) { \t\tPyArrayObject *rv_cb_arr = NULL; \t\tif ((capi_tmp = PyTuple_GetItem(capi_return,capi_i++))==NULL) goto capi_fail; \t\trv_cb_arr = array_from_pyobj(#atype#,#varname_i#_Dims,#rank#,F2PY_INTENT_IN""", {isintent_c:'|F2PY_INTENT_C'}, """,capi_tmp); \t\tif (rv_cb_arr == NULL) { \t\t\tfprintf(stderr,\"rv_cb_arr is NULL\\n\"); \t\t\tgoto capi_fail; \t\t} \t\tMEMCOPY(#varname_i#,rv_cb_arr->data,PyArray_NBYTES(rv_cb_arr)); \t\tif (capi_tmp != (PyObject *)rv_cb_arr) { \t\t\tPy_DECREF(rv_cb_arr); \t\t} \t}""", {debugcapi:'\tfprintf(stderr,"<-.\\n");'}, ], 'need':['MEMCOPY', {iscomplexarray:'#ctype#'}], '_check':l_and(isarray, isintent_out) }, { 'docreturn':'#varname#,', '_check':isintent_out } ] ################## Build call-back module ############# cb_map={} def buildcallbacks(m): global cb_map cb_map[m['name']]=[] for bi in m['body']: if bi['block']=='interface': for b in bi['body']: if b: buildcallback(b, m['name']) else: errmess('warning: empty body for %s\n' % (m['name'])) def buildcallback(rout, um): global cb_map from . import capi_maps outmess('\tConstructing call-back function "cb_%s_in_%s"\n'%(rout['name'], um)) args, depargs=getargs(rout) capi_maps.depargs=depargs var=rout['vars'] vrd=capi_maps.cb_routsign2map(rout, um) rd=dictappend({}, vrd) cb_map[um].append([rout['name'], rd['name']]) for r in cb_rout_rules: if ('_check' in r and r['_check'](rout)) or ('_check' not in r): ar=applyrules(r, vrd, rout) rd=dictappend(rd, ar) savevrd={} for i, a in enumerate(args): vrd=capi_maps.cb_sign2map(a, var[a], index=i) savevrd[a]=vrd for r in cb_arg_rules: if '_depend' in r: continue if '_optional' in r and isoptional(var[a]): continue if ('_check' in r and r['_check'](var[a])) or ('_check' not in r): ar=applyrules(r, vrd, var[a]) rd=dictappend(rd, ar) if '_break' in r: break for a in args: vrd=savevrd[a] for r in cb_arg_rules: if '_depend' in r: continue if ('_optional' not in r) or ('_optional' in r and isrequired(var[a])): continue if ('_check' in r and r['_check'](var[a])) or ('_check' not in r): ar=applyrules(r, vrd, var[a]) rd=dictappend(rd, ar) if '_break' in r: break for a in depargs: vrd=savevrd[a] for r in cb_arg_rules: if '_depend' not in r: continue if '_optional' in r: continue if ('_check' in r and r['_check'](var[a])) or ('_check' not in r): ar=applyrules(r, vrd, var[a]) rd=dictappend(rd, ar) if '_break' in r: break if 'args' in rd and 'optargs' in rd: if isinstance(rd['optargs'], list): rd['optargs']=rd['optargs']+[""" #ifndef F2PY_CB_RETURNCOMPLEX , #endif """] rd['optargs_nm']=rd['optargs_nm']+[""" #ifndef F2PY_CB_RETURNCOMPLEX , #endif """] rd['optargs_td']=rd['optargs_td']+[""" #ifndef F2PY_CB_RETURNCOMPLEX , #endif """] if isinstance(rd['docreturn'], list): rd['docreturn']=stripcomma(replace('#docreturn#', {'docreturn':rd['docreturn']})) optargs=stripcomma(replace('#docsignopt#', {'docsignopt':rd['docsignopt']} )) if optargs=='': rd['docsignature']=stripcomma(replace('#docsign#', {'docsign':rd['docsign']})) else: rd['docsignature']=replace('#docsign#[#docsignopt#]', {'docsign': rd['docsign'], 'docsignopt': optargs, }) rd['latexdocsignature']=rd['docsignature'].replace('_', '\\_') rd['latexdocsignature']=rd['latexdocsignature'].replace(',', ', ') rd['docstrsigns']=[] rd['latexdocstrsigns']=[] for k in ['docstrreq', 'docstropt', 'docstrout', 'docstrcbs']: if k in rd and isinstance(rd[k], list): rd['docstrsigns']=rd['docstrsigns']+rd[k] k='latex'+k if k in rd and isinstance(rd[k], list): rd['latexdocstrsigns']=rd['latexdocstrsigns']+rd[k][0:1]+\ ['\\begin{description}']+rd[k][1:]+\ ['\\end{description}'] if 'args' not in rd: rd['args']='' rd['args_td']='' rd['args_nm']='' if not (rd.get('args') or rd.get('optargs') or rd.get('strarglens')): rd['noargs'] = 'void' ar=applyrules(cb_routine_rules, rd) cfuncs.callbacks[rd['name']]=ar['body'] if isinstance(ar['need'], str): ar['need']=[ar['need']] if 'need' in rd: for t in cfuncs.typedefs.keys(): if t in rd['need']: ar['need'].append(t) cfuncs.typedefs_generated[rd['name']+'_typedef'] = ar['cbtypedefs'] ar['need'].append(rd['name']+'_typedef') cfuncs.needs[rd['name']]=ar['need'] capi_maps.lcb2_map[rd['name']]={'maxnofargs':ar['maxnofargs'], 'nofoptargs':ar['nofoptargs'], 'docstr':ar['docstr'], 'latexdocstr':ar['latexdocstr'], 'argname':rd['argname'] } outmess('\t %s\n'%(ar['docstrshort'])) #print ar['body'] return ################## Build call-back function ############# numpy-1.8.2/numpy/f2py/setup.py0000664000175100017510000001032112370216242017562 0ustar vagrantvagrant00000000000000#!/usr/bin/env python """ setup.py for installing F2PY Usage: python setup.py install Copyright 2001-2005 Pearu Peterson all rights reserved, Pearu Peterson Permission to use, modify, and distribute this software is given under the terms of the NumPy License. NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. $Revision: 1.32 $ $Date: 2005/01/30 17:22:14 $ Pearu Peterson """ from __future__ import division, print_function __version__ = "$Id: setup.py,v 1.32 2005/01/30 17:22:14 pearu Exp $" import os import sys from distutils.dep_util import newer from numpy.distutils import log from numpy.distutils.core import setup from numpy.distutils.misc_util import Configuration from __version__ import version def configuration(parent_package='',top_path=None): config = Configuration('f2py', parent_package, top_path) config.add_data_dir('docs') config.add_data_dir('tests') config.add_data_files('src/fortranobject.c', 'src/fortranobject.h', 'f2py.1' ) config.make_svn_version_py() def generate_f2py_py(build_dir): f2py_exe = 'f2py'+os.path.basename(sys.executable)[6:] if f2py_exe[-4:]=='.exe': f2py_exe = f2py_exe[:-4] + '.py' if 'bdist_wininst' in sys.argv and f2py_exe[-3:] != '.py': f2py_exe = f2py_exe + '.py' target = os.path.join(build_dir, f2py_exe) if newer(__file__, target): log.info('Creating %s', target) f = open(target, 'w') f.write('''\ #!%s # See http://cens.ioc.ee/projects/f2py2e/ import os, sys for mode in ["g3-numpy", "2e-numeric", "2e-numarray", "2e-numpy"]: try: i=sys.argv.index("--"+mode) del sys.argv[i] break except ValueError: pass os.environ["NO_SCIPY_IMPORT"]="f2py" if mode=="g3-numpy": sys.stderr.write("G3 f2py support is not implemented, yet.\\n") sys.exit(1) elif mode=="2e-numeric": from f2py2e import main elif mode=="2e-numarray": sys.argv.append("-DNUMARRAY") from f2py2e import main elif mode=="2e-numpy": from numpy.f2py import main else: sys.stderr.write("Unknown mode: " + repr(mode) + "\\n") sys.exit(1) main() '''%(sys.executable)) f.close() return target config.add_scripts(generate_f2py_py) log.info('F2PY Version %s', config.get_version()) return config if __name__ == "__main__": config = configuration(top_path='') version = config.get_version() print('F2PY Version', version) config = config.todict() if sys.version[:3]>='2.3': config['download_url'] = "http://cens.ioc.ee/projects/f2py2e/2.x"\ "/F2PY-2-latest.tar.gz" config['classifiers'] = [ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: NumPy License', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: C', 'Programming Language :: Fortran', 'Programming Language :: Python', 'Topic :: Scientific/Engineering', 'Topic :: Software Development :: Code Generators', ] setup(version=version, description = "F2PY - Fortran to Python Interface Generaton", author = "Pearu Peterson", author_email = "pearu@cens.ioc.ee", maintainer = "Pearu Peterson", maintainer_email = "pearu@cens.ioc.ee", license = "BSD", platforms = "Unix, Windows (mingw|cygwin), Mac OSX", long_description = """\ The Fortran to Python Interface Generator, or F2PY for short, is a command line tool (f2py) for generating Python C/API modules for wrapping Fortran 77/90/95 subroutines, accessing common blocks from Python, and calling Python functions from Fortran (call-backs). Interfacing subroutines/data from Fortran 90/95 modules is supported.""", url = "http://cens.ioc.ee/projects/f2py2e/", keywords = ['Fortran', 'f2py'], **config) numpy-1.8.2/numpy/f2py/tests/0000775000175100017510000000000012371375430017223 5ustar vagrantvagrant00000000000000numpy-1.8.2/numpy/f2py/tests/test_return_integer.py0000664000175100017510000001103712370216242023664 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function from numpy.testing import * from numpy import array from numpy.compat import long import util class TestReturnInteger(util.F2PyTest): def check_function(self, t): assert_( t(123)==123, repr(t(123))) assert_( t(123.6)==123) assert_( t(long(123))==123) assert_( t('123')==123) assert_( t(-123)==-123) assert_( t([123])==123) assert_( t((123,))==123) assert_( t(array(123))==123) assert_( t(array([123]))==123) assert_( t(array([[123]]))==123) assert_( t(array([123], 'b'))==123) assert_( t(array([123], 'h'))==123) assert_( t(array([123], 'i'))==123) assert_( t(array([123], 'l'))==123) assert_( t(array([123], 'B'))==123) assert_( t(array([123], 'f'))==123) assert_( t(array([123], 'd'))==123) #assert_raises(ValueError, t, array([123],'S3')) assert_raises(ValueError, t, 'abc') assert_raises(IndexError, t, []) assert_raises(IndexError, t, ()) assert_raises(Exception, t, t) assert_raises(Exception, t, {}) if t.__doc__.split()[0] in ['t8', 's8']: assert_raises(OverflowError, t, 100000000000000000000000) assert_raises(OverflowError, t, 10000000011111111111111.23) class TestF77ReturnInteger(TestReturnInteger): code = """ function t0(value) integer value integer t0 t0 = value end function t1(value) integer*1 value integer*1 t1 t1 = value end function t2(value) integer*2 value integer*2 t2 t2 = value end function t4(value) integer*4 value integer*4 t4 t4 = value end function t8(value) integer*8 value integer*8 t8 t8 = value end subroutine s0(t0,value) integer value integer t0 cf2py intent(out) t0 t0 = value end subroutine s1(t1,value) integer*1 value integer*1 t1 cf2py intent(out) t1 t1 = value end subroutine s2(t2,value) integer*2 value integer*2 t2 cf2py intent(out) t2 t2 = value end subroutine s4(t4,value) integer*4 value integer*4 t4 cf2py intent(out) t4 t4 = value end subroutine s8(t8,value) integer*8 value integer*8 t8 cf2py intent(out) t8 t8 = value end """ @dec.slow def test_all(self): for name in "t0,t1,t2,t4,t8,s0,s1,s2,s4,s8".split(","): self.check_function(getattr(self.module, name)) class TestF90ReturnInteger(TestReturnInteger): suffix = ".f90" code = """ module f90_return_integer contains function t0(value) integer :: value integer :: t0 t0 = value end function t0 function t1(value) integer(kind=1) :: value integer(kind=1) :: t1 t1 = value end function t1 function t2(value) integer(kind=2) :: value integer(kind=2) :: t2 t2 = value end function t2 function t4(value) integer(kind=4) :: value integer(kind=4) :: t4 t4 = value end function t4 function t8(value) integer(kind=8) :: value integer(kind=8) :: t8 t8 = value end function t8 subroutine s0(t0,value) integer :: value integer :: t0 !f2py intent(out) t0 t0 = value end subroutine s0 subroutine s1(t1,value) integer(kind=1) :: value integer(kind=1) :: t1 !f2py intent(out) t1 t1 = value end subroutine s1 subroutine s2(t2,value) integer(kind=2) :: value integer(kind=2) :: t2 !f2py intent(out) t2 t2 = value end subroutine s2 subroutine s4(t4,value) integer(kind=4) :: value integer(kind=4) :: t4 !f2py intent(out) t4 t4 = value end subroutine s4 subroutine s8(t8,value) integer(kind=8) :: value integer(kind=8) :: t8 !f2py intent(out) t8 t8 = value end subroutine s8 end module f90_return_integer """ @dec.slow def test_all(self): for name in "t0,t1,t2,t4,t8,s0,s1,s2,s4,s8".split(","): self.check_function(getattr(self.module.f90_return_integer, name)) if __name__ == "__main__": import nose nose.runmodule() numpy-1.8.2/numpy/f2py/tests/test_kind.py0000664000175100017510000000217012370216242021553 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function import os import math from numpy.testing import * from numpy import array import util def _path(*a): return os.path.join(*((os.path.dirname(__file__),) + a)) from numpy.f2py.crackfortran import _selected_int_kind_func as selected_int_kind from numpy.f2py.crackfortran import _selected_real_kind_func as selected_real_kind class TestKind(util.F2PyTest): sources = [_path('src', 'kind', 'foo.f90'), ] @dec.slow def test_all(self): selectedrealkind = self.module.selectedrealkind selectedintkind = self.module.selectedintkind for i in range(40): assert_(selectedintkind(i) in [selected_int_kind(i), -1],\ 'selectedintkind(%s): expected %r but got %r' % (i, selected_int_kind(i), selectedintkind(i))) for i in range(20): assert_(selectedrealkind(i) in [selected_real_kind(i), -1],\ 'selectedrealkind(%s): expected %r but got %r' % (i, selected_real_kind(i), selectedrealkind(i))) if __name__ == "__main__": import nose nose.runmodule() numpy-1.8.2/numpy/f2py/tests/util.py0000664000175100017510000002231612370216242020550 0ustar vagrantvagrant00000000000000""" Utility functions for - building and importing modules on test time, using a temporary location - detecting if compilers are present """ from __future__ import division, absolute_import, print_function import os import sys import subprocess import tempfile import shutil import atexit import textwrap import re import random import nose from numpy.compat import asbytes, asstr import numpy.f2py try: from hashlib import md5 except ImportError: from md5 import new as md5 # # Maintaining a temporary module directory # _module_dir = None def _cleanup(): global _module_dir if _module_dir is not None: try: sys.path.remove(_module_dir) except ValueError: pass try: shutil.rmtree(_module_dir) except (IOError, OSError): pass _module_dir = None def get_module_dir(): global _module_dir if _module_dir is None: _module_dir = tempfile.mkdtemp() atexit.register(_cleanup) if _module_dir not in sys.path: sys.path.insert(0, _module_dir) return _module_dir def get_temp_module_name(): # Assume single-threaded, and the module dir usable only by this thread d = get_module_dir() for j in range(5403, 9999999): name = "_test_ext_module_%d" % j fn = os.path.join(d, name) if name not in sys.modules and not os.path.isfile(fn+'.py'): return name raise RuntimeError("Failed to create a temporary module name") def _memoize(func): memo = {} def wrapper(*a, **kw): key = repr((a, kw)) if key not in memo: try: memo[key] = func(*a, **kw) except Exception as e: memo[key] = e raise ret = memo[key] if isinstance(ret, Exception): raise ret return ret wrapper.__name__ = func.__name__ return wrapper # # Building modules # @_memoize def build_module(source_files, options=[], skip=[], only=[], module_name=None): """ Compile and import a f2py module, built from the given files. """ code = ("import sys; sys.path = %s; import numpy.f2py as f2py2e; " "f2py2e.main()" % repr(sys.path)) d = get_module_dir() # Copy files dst_sources = [] for fn in source_files: if not os.path.isfile(fn): raise RuntimeError("%s is not a file" % fn) dst = os.path.join(d, os.path.basename(fn)) shutil.copyfile(fn, dst) dst_sources.append(dst) fn = os.path.join(os.path.dirname(fn), '.f2py_f2cmap') if os.path.isfile(fn): dst = os.path.join(d, os.path.basename(fn)) if not os.path.isfile(dst): shutil.copyfile(fn, dst) # Prepare options if module_name is None: module_name = get_temp_module_name() f2py_opts = ['-c', '-m', module_name] + options + dst_sources if skip: f2py_opts += ['skip:'] + skip if only: f2py_opts += ['only:'] + only # Build cwd = os.getcwd() try: os.chdir(d) cmd = [sys.executable, '-c', code] + f2py_opts p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) out, err = p.communicate() if p.returncode != 0: raise RuntimeError("Running f2py failed: %s\n%s" % (cmd[4:], asstr(out))) finally: os.chdir(cwd) # Partial cleanup for fn in dst_sources: os.unlink(fn) # Import __import__(module_name) return sys.modules[module_name] @_memoize def build_code(source_code, options=[], skip=[], only=[], suffix=None, module_name=None): """ Compile and import Fortran code using f2py. """ if suffix is None: suffix = '.f' fd, tmp_fn = tempfile.mkstemp(suffix=suffix) os.write(fd, asbytes(source_code)) os.close(fd) try: return build_module([tmp_fn], options=options, skip=skip, only=only, module_name=module_name) finally: os.unlink(tmp_fn) # # Check if compilers are available at all... # _compiler_status = None def _get_compiler_status(): global _compiler_status if _compiler_status is not None: return _compiler_status _compiler_status = (False, False, False) # XXX: this is really ugly. But I don't know how to invoke Distutils # in a safer way... code = """ import os import sys sys.path = %(syspath)s def configuration(parent_name='',top_path=None): global config from numpy.distutils.misc_util import Configuration config = Configuration('', parent_name, top_path) return config from numpy.distutils.core import setup setup(configuration=configuration) config_cmd = config.get_config_cmd() have_c = config_cmd.try_compile('void foo() {}') print('COMPILERS:%%d,%%d,%%d' %% (have_c, config.have_f77c(), config.have_f90c())) sys.exit(99) """ code = code % dict(syspath=repr(sys.path)) fd, script = tempfile.mkstemp(suffix='.py') os.write(fd, asbytes(code)) os.close(fd) try: cmd = [sys.executable, script, 'config'] p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) out, err = p.communicate() m = re.search(asbytes(r'COMPILERS:(\d+),(\d+),(\d+)'), out) if m: _compiler_status = (bool(int(m.group(1))), bool(int(m.group(2))), bool(int(m.group(3)))) finally: os.unlink(script) # Finished return _compiler_status def has_c_compiler(): return _get_compiler_status()[0] def has_f77_compiler(): return _get_compiler_status()[1] def has_f90_compiler(): return _get_compiler_status()[2] # # Building with distutils # @_memoize def build_module_distutils(source_files, config_code, module_name, **kw): """ Build a module via distutils and import it. """ from numpy.distutils.misc_util import Configuration from numpy.distutils.core import setup d = get_module_dir() # Copy files dst_sources = [] for fn in source_files: if not os.path.isfile(fn): raise RuntimeError("%s is not a file" % fn) dst = os.path.join(d, os.path.basename(fn)) shutil.copyfile(fn, dst) dst_sources.append(dst) # Build script config_code = textwrap.dedent(config_code).replace("\n", "\n ") code = """\ import os import sys sys.path = %(syspath)s def configuration(parent_name='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('', parent_name, top_path) %(config_code)s return config if __name__ == "__main__": from numpy.distutils.core import setup setup(configuration=configuration) """ % dict(config_code=config_code, syspath = repr(sys.path)) script = os.path.join(d, get_temp_module_name() + '.py') dst_sources.append(script) f = open(script, 'wb') f.write(asbytes(code)) f.close() # Build cwd = os.getcwd() try: os.chdir(d) cmd = [sys.executable, script, 'build_ext', '-i'] p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) out, err = p.communicate() if p.returncode != 0: raise RuntimeError("Running distutils build failed: %s\n%s" % (cmd[4:], asstr(out))) finally: os.chdir(cwd) # Partial cleanup for fn in dst_sources: os.unlink(fn) # Import __import__(module_name) return sys.modules[module_name] # # Unittest convenience # class F2PyTest(object): code = None sources = None options = [] skip = [] only = [] suffix = '.f' module = None module_name = None def setUp(self): if self.module is not None: return # Check compiler availability first if not has_c_compiler(): raise nose.SkipTest("No C compiler available") codes = [] if self.sources: codes.extend(self.sources) if self.code is not None: codes.append(self.suffix) needs_f77 = False needs_f90 = False for fn in codes: if fn.endswith('.f'): needs_f77 = True elif fn.endswith('.f90'): needs_f90 = True if needs_f77 and not has_f77_compiler(): raise nose.SkipTest("No Fortran 77 compiler available") if needs_f90 and not has_f90_compiler(): raise nose.SkipTest("No Fortran 90 compiler available") # Build the module if self.code is not None: self.module = build_code(self.code, options=self.options, skip=self.skip, only=self.only, suffix=self.suffix, module_name=self.module_name) if self.sources is not None: self.module = build_module(self.sources, options=self.options, skip=self.skip, only=self.only, module_name=self.module_name) numpy-1.8.2/numpy/f2py/tests/src/0000775000175100017510000000000012371375427020020 5ustar vagrantvagrant00000000000000numpy-1.8.2/numpy/f2py/tests/src/kind/0000775000175100017510000000000012371375430020737 5ustar vagrantvagrant00000000000000numpy-1.8.2/numpy/f2py/tests/src/kind/foo.f900000664000175100017510000000053312370216242022035 0ustar vagrantvagrant00000000000000 subroutine selectedrealkind(p, r, res) implicit none integer, intent(in) :: p, r !f2py integer :: r=0 integer, intent(out) :: res res = selected_real_kind(p, r) end subroutine subroutine selectedintkind(p, res) implicit none integer, intent(in) :: p integer, intent(out) :: res res = selected_int_kind(p) end subroutine numpy-1.8.2/numpy/f2py/tests/src/array_from_pyobj/0000775000175100017510000000000012371375430023356 5ustar vagrantvagrant00000000000000numpy-1.8.2/numpy/f2py/tests/src/array_from_pyobj/wrapmodule.c0000664000175100017510000002046512370216242025702 0ustar vagrantvagrant00000000000000/* File: wrapmodule.c * This file is auto-generated with f2py (version:2_1330). * Hand edited by Pearu. * f2py is a Fortran to Python Interface Generator (FPIG), Second Edition, * written by Pearu Peterson . * See http://cens.ioc.ee/projects/f2py2e/ * Generation date: Fri Oct 21 22:41:12 2005 * $Revision:$ * $Date:$ * Do not edit this file directly unless you know what you are doing!!! */ #ifdef __cplusplus extern "C" { #endif /*********************** See f2py2e/cfuncs.py: includes ***********************/ #include "Python.h" #include "fortranobject.h" #include static PyObject *wrap_error; static PyObject *wrap_module; /************************************ call ************************************/ static char doc_f2py_rout_wrap_call[] = "\ Function signature:\n\ arr = call(type_num,dims,intent,obj)\n\ Required arguments:\n" " type_num : input int\n" " dims : input int-sequence\n" " intent : input int\n" " obj : input python object\n" "Return objects:\n" " arr : array"; static PyObject *f2py_rout_wrap_call(PyObject *capi_self, PyObject *capi_args) { PyObject * volatile capi_buildvalue = NULL; int type_num = 0; npy_intp *dims = NULL; PyObject *dims_capi = Py_None; int rank = 0; int intent = 0; PyArrayObject *capi_arr_tmp = NULL; PyObject *arr_capi = Py_None; int i; if (!PyArg_ParseTuple(capi_args,"iOiO|:wrap.call",\ &type_num,&dims_capi,&intent,&arr_capi)) return NULL; rank = PySequence_Length(dims_capi); dims = malloc(rank*sizeof(npy_intp)); for (i=0;idata); dimensions = PyTuple_New(arr->nd); strides = PyTuple_New(arr->nd); for (i=0;ind;++i) { PyTuple_SetItem(dimensions,i,PyInt_FromLong(arr->dimensions[i])); PyTuple_SetItem(strides,i,PyInt_FromLong(arr->strides[i])); } return Py_BuildValue("siOOO(cciii)ii",s,arr->nd, dimensions,strides, (arr->base==NULL?Py_None:arr->base), arr->descr->kind, arr->descr->type, arr->descr->type_num, arr->descr->elsize, arr->descr->alignment, arr->flags, PyArray_ITEMSIZE(arr)); } static PyMethodDef f2py_module_methods[] = { {"call",f2py_rout_wrap_call,METH_VARARGS,doc_f2py_rout_wrap_call}, {"array_attrs",f2py_rout_wrap_attrs,METH_VARARGS,doc_f2py_rout_wrap_attrs}, {NULL,NULL} }; #if PY_VERSION_HEX >= 0x03000000 static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, "test_array_from_pyobj_ext", NULL, -1, f2py_module_methods, NULL, NULL, NULL, NULL }; #endif #if PY_VERSION_HEX >= 0x03000000 #define RETVAL m PyMODINIT_FUNC PyInit_test_array_from_pyobj_ext(void) { #else #define RETVAL PyMODINIT_FUNC inittest_array_from_pyobj_ext(void) { #endif PyObject *m,*d, *s; #if PY_VERSION_HEX >= 0x03000000 m = wrap_module = PyModule_Create(&moduledef); #else m = wrap_module = Py_InitModule("test_array_from_pyobj_ext", f2py_module_methods); #endif Py_TYPE(&PyFortran_Type) = &PyType_Type; import_array(); if (PyErr_Occurred()) Py_FatalError("can't initialize module wrap (failed to import numpy)"); d = PyModule_GetDict(m); s = PyString_FromString("This module 'wrap' is auto-generated with f2py (version:2_1330).\nFunctions:\n" " arr = call(type_num,dims,intent,obj)\n" "."); PyDict_SetItemString(d, "__doc__", s); wrap_error = PyErr_NewException ("wrap.error", NULL, NULL); Py_DECREF(s); PyDict_SetItemString(d, "F2PY_INTENT_IN", PyInt_FromLong(F2PY_INTENT_IN)); PyDict_SetItemString(d, "F2PY_INTENT_INOUT", PyInt_FromLong(F2PY_INTENT_INOUT)); PyDict_SetItemString(d, "F2PY_INTENT_OUT", PyInt_FromLong(F2PY_INTENT_OUT)); PyDict_SetItemString(d, "F2PY_INTENT_HIDE", PyInt_FromLong(F2PY_INTENT_HIDE)); PyDict_SetItemString(d, "F2PY_INTENT_CACHE", PyInt_FromLong(F2PY_INTENT_CACHE)); PyDict_SetItemString(d, "F2PY_INTENT_COPY", PyInt_FromLong(F2PY_INTENT_COPY)); PyDict_SetItemString(d, "F2PY_INTENT_C", PyInt_FromLong(F2PY_INTENT_C)); PyDict_SetItemString(d, "F2PY_OPTIONAL", PyInt_FromLong(F2PY_OPTIONAL)); PyDict_SetItemString(d, "F2PY_INTENT_INPLACE", PyInt_FromLong(F2PY_INTENT_INPLACE)); PyDict_SetItemString(d, "NPY_BOOL", PyInt_FromLong(NPY_BOOL)); PyDict_SetItemString(d, "NPY_BYTE", PyInt_FromLong(NPY_BYTE)); PyDict_SetItemString(d, "NPY_UBYTE", PyInt_FromLong(NPY_UBYTE)); PyDict_SetItemString(d, "NPY_SHORT", PyInt_FromLong(NPY_SHORT)); PyDict_SetItemString(d, "NPY_USHORT", PyInt_FromLong(NPY_USHORT)); PyDict_SetItemString(d, "NPY_INT", PyInt_FromLong(NPY_INT)); PyDict_SetItemString(d, "NPY_UINT", PyInt_FromLong(NPY_UINT)); PyDict_SetItemString(d, "NPY_INTP", PyInt_FromLong(NPY_INTP)); PyDict_SetItemString(d, "NPY_UINTP", PyInt_FromLong(NPY_UINTP)); PyDict_SetItemString(d, "NPY_LONG", PyInt_FromLong(NPY_LONG)); PyDict_SetItemString(d, "NPY_ULONG", PyInt_FromLong(NPY_ULONG)); PyDict_SetItemString(d, "NPY_LONGLONG", PyInt_FromLong(NPY_LONGLONG)); PyDict_SetItemString(d, "NPY_ULONGLONG", PyInt_FromLong(NPY_ULONGLONG)); PyDict_SetItemString(d, "NPY_FLOAT", PyInt_FromLong(NPY_FLOAT)); PyDict_SetItemString(d, "NPY_DOUBLE", PyInt_FromLong(NPY_DOUBLE)); PyDict_SetItemString(d, "NPY_LONGDOUBLE", PyInt_FromLong(NPY_LONGDOUBLE)); PyDict_SetItemString(d, "NPY_CFLOAT", PyInt_FromLong(NPY_CFLOAT)); PyDict_SetItemString(d, "NPY_CDOUBLE", PyInt_FromLong(NPY_CDOUBLE)); PyDict_SetItemString(d, "NPY_CLONGDOUBLE", PyInt_FromLong(NPY_CLONGDOUBLE)); PyDict_SetItemString(d, "NPY_OBJECT", PyInt_FromLong(NPY_OBJECT)); PyDict_SetItemString(d, "NPY_STRING", PyInt_FromLong(NPY_STRING)); PyDict_SetItemString(d, "NPY_UNICODE", PyInt_FromLong(NPY_UNICODE)); PyDict_SetItemString(d, "NPY_VOID", PyInt_FromLong(NPY_VOID)); PyDict_SetItemString(d, "NPY_NTYPES", PyInt_FromLong(NPY_NTYPES)); PyDict_SetItemString(d, "NPY_NOTYPE", PyInt_FromLong(NPY_NOTYPE)); PyDict_SetItemString(d, "NPY_USERDEF", PyInt_FromLong(NPY_USERDEF)); PyDict_SetItemString(d, "CONTIGUOUS", PyInt_FromLong(NPY_CONTIGUOUS)); PyDict_SetItemString(d, "FORTRAN", PyInt_FromLong(NPY_FORTRAN)); PyDict_SetItemString(d, "OWNDATA", PyInt_FromLong(NPY_OWNDATA)); PyDict_SetItemString(d, "FORCECAST", PyInt_FromLong(NPY_FORCECAST)); PyDict_SetItemString(d, "ENSURECOPY", PyInt_FromLong(NPY_ENSURECOPY)); PyDict_SetItemString(d, "ENSUREARRAY", PyInt_FromLong(NPY_ENSUREARRAY)); PyDict_SetItemString(d, "ALIGNED", PyInt_FromLong(NPY_ALIGNED)); PyDict_SetItemString(d, "WRITEABLE", PyInt_FromLong(NPY_WRITEABLE)); PyDict_SetItemString(d, "UPDATEIFCOPY", PyInt_FromLong(NPY_UPDATEIFCOPY)); PyDict_SetItemString(d, "BEHAVED", PyInt_FromLong(NPY_BEHAVED)); PyDict_SetItemString(d, "BEHAVED_NS", PyInt_FromLong(NPY_BEHAVED_NS)); PyDict_SetItemString(d, "CARRAY", PyInt_FromLong(NPY_CARRAY)); PyDict_SetItemString(d, "FARRAY", PyInt_FromLong(NPY_FARRAY)); PyDict_SetItemString(d, "CARRAY_RO", PyInt_FromLong(NPY_CARRAY_RO)); PyDict_SetItemString(d, "FARRAY_RO", PyInt_FromLong(NPY_FARRAY_RO)); PyDict_SetItemString(d, "DEFAULT", PyInt_FromLong(NPY_DEFAULT)); PyDict_SetItemString(d, "UPDATE_ALL", PyInt_FromLong(NPY_UPDATE_ALL)); if (PyErr_Occurred()) Py_FatalError("can't initialize module wrap"); #ifdef F2PY_REPORT_ATEXIT on_exit(f2py_report_on_exit,(void*)"array_from_pyobj.wrap.call"); #endif return RETVAL; } #ifdef __cplusplus } #endif numpy-1.8.2/numpy/f2py/tests/src/size/0000775000175100017510000000000012371375430020764 5ustar vagrantvagrant00000000000000numpy-1.8.2/numpy/f2py/tests/src/size/foo.f900000664000175100017510000000145712370216242022070 0ustar vagrantvagrant00000000000000 subroutine foo(a, n, m, b) implicit none real, intent(in) :: a(n, m) integer, intent(in) :: n, m real, intent(out) :: b(size(a, 1)) integer :: i do i = 1, size(b) b(i) = sum(a(i,:)) enddo end subroutine subroutine trans(x,y) implicit none real, intent(in), dimension(:,:) :: x real, intent(out), dimension( size(x,2), size(x,1) ) :: y integer :: N, M, i, j N = size(x,1) M = size(x,2) DO i=1,N do j=1,M y(j,i) = x(i,j) END DO END DO end subroutine trans subroutine flatten(x,y) implicit none real, intent(in), dimension(:,:) :: x real, intent(out), dimension( size(x) ) :: y integer :: N, M, i, j, k N = size(x,1) M = size(x,2) k = 1 DO i=1,N do j=1,M y(k) = x(i,j) k = k + 1 END DO END DO end subroutine flatten numpy-1.8.2/numpy/f2py/tests/src/assumed_shape/0000775000175100017510000000000012371375430022633 5ustar vagrantvagrant00000000000000numpy-1.8.2/numpy/f2py/tests/src/assumed_shape/foo_mod.f900000664000175100017510000000076312370216242024575 0ustar vagrantvagrant00000000000000 module mod contains subroutine sum(x, res) implicit none real, intent(in) :: x(:) real, intent(out) :: res integer :: i !print *, "sum: size(x) = ", size(x) res = 0.0 do i = 1, size(x) res = res + x(i) enddo end subroutine sum function fsum(x) result (res) implicit none real, intent(in) :: x(:) real :: res integer :: i !print *, "fsum: size(x) = ", size(x) res = 0.0 do i = 1, size(x) res = res + x(i) enddo end function fsum end module mod numpy-1.8.2/numpy/f2py/tests/src/assumed_shape/foo_free.f900000664000175100017510000000071412370216242024733 0ustar vagrantvagrant00000000000000 subroutine sum(x, res) implicit none real, intent(in) :: x(:) real, intent(out) :: res integer :: i !print *, "sum: size(x) = ", size(x) res = 0.0 do i = 1, size(x) res = res + x(i) enddo end subroutine sum function fsum(x) result (res) implicit none real, intent(in) :: x(:) real :: res integer :: i !print *, "fsum: size(x) = ", size(x) res = 0.0 do i = 1, size(x) res = res + x(i) enddo end function fsum numpy-1.8.2/numpy/f2py/tests/src/assumed_shape/foo_use.f900000664000175100017510000000041512370216242024604 0ustar vagrantvagrant00000000000000subroutine sum_with_use(x, res) use precision implicit none real(kind=rk), intent(in) :: x(:) real(kind=rk), intent(out) :: res integer :: i !print *, "size(x) = ", size(x) res = 0.0 do i = 1, size(x) res = res + x(i) enddo end subroutine numpy-1.8.2/numpy/f2py/tests/src/assumed_shape/precision.f900000664000175100017510000000020212370216242025132 0ustar vagrantvagrant00000000000000module precision integer, parameter :: rk = selected_real_kind(8) integer, parameter :: ik = selected_real_kind(4) end module numpy-1.8.2/numpy/f2py/tests/src/assumed_shape/.f2py_f2cmap0000664000175100017510000000003512370216242024734 0ustar vagrantvagrant00000000000000dict(real=dict(rk="double")) numpy-1.8.2/numpy/f2py/tests/src/mixed/0000775000175100017510000000000012371375430021120 5ustar vagrantvagrant00000000000000numpy-1.8.2/numpy/f2py/tests/src/mixed/foo_free.f900000664000175100017510000000021312370216242023212 0ustar vagrantvagrant00000000000000module foo_free contains subroutine bar13(a) !f2py intent(out) a integer a a = 13 end subroutine bar13 end module foo_free numpy-1.8.2/numpy/f2py/tests/src/mixed/foo.f0000664000175100017510000000012512370216242022042 0ustar vagrantvagrant00000000000000 subroutine bar11(a) cf2py intent(out) a integer a a = 11 end numpy-1.8.2/numpy/f2py/tests/src/mixed/foo_fixed.f900000664000175100017510000000026312370216242023375 0ustar vagrantvagrant00000000000000 module foo_fixed contains subroutine bar12(a) !f2py intent(out) a integer a a = 12 end subroutine bar12 end module foo_fixed numpy-1.8.2/numpy/f2py/tests/test_assumed_shape.py0000664000175100017510000000175412370216242023456 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function import os import math from numpy.testing import * from numpy import array import util def _path(*a): return os.path.join(*((os.path.dirname(__file__),) + a)) class TestAssumedShapeSumExample(util.F2PyTest): sources = [_path('src', 'assumed_shape', 'foo_free.f90'), _path('src', 'assumed_shape', 'foo_use.f90'), _path('src', 'assumed_shape', 'precision.f90'), _path('src', 'assumed_shape', 'foo_mod.f90'), ] @dec.slow def test_all(self): r = self.module.fsum([1, 2]) assert_(r==3, repr(r)) r = self.module.sum([1, 2]) assert_(r==3, repr(r)) r = self.module.sum_with_use([1, 2]) assert_(r==3, repr(r)) r = self.module.mod.sum([1, 2]) assert_(r==3, repr(r)) r = self.module.mod.fsum([1, 2]) assert_(r==3, repr(r)) if __name__ == "__main__": import nose nose.runmodule() numpy-1.8.2/numpy/f2py/tests/test_return_character.py0000664000175100017510000000747712370216242024200 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function from numpy.testing import * from numpy import array from numpy.compat import asbytes import util class TestReturnCharacter(util.F2PyTest): def check_function(self, t): tname = t.__doc__.split()[0] if tname in ['t0', 't1', 's0', 's1']: assert_( t(23)==asbytes('2')) r = t('ab');assert_( r==asbytes('a'), repr(r)) r = t(array('ab'));assert_( r==asbytes('a'), repr(r)) r = t(array(77, 'u1'));assert_( r==asbytes('M'), repr(r)) #assert_(_raises(ValueError, t, array([77,87]))) #assert_(_raises(ValueError, t, array(77))) elif tname in ['ts', 'ss']: assert_( t(23)==asbytes('23 '), repr(t(23))) assert_( t('123456789abcdef')==asbytes('123456789a')) elif tname in ['t5', 's5']: assert_( t(23)==asbytes('23 '), repr(t(23))) assert_( t('ab')==asbytes('ab '), repr(t('ab'))) assert_( t('123456789abcdef')==asbytes('12345')) else: raise NotImplementedError class TestF77ReturnCharacter(TestReturnCharacter): code = """ function t0(value) character value character t0 t0 = value end function t1(value) character*1 value character*1 t1 t1 = value end function t5(value) character*5 value character*5 t5 t5 = value end function ts(value) character*(*) value character*(*) ts ts = value end subroutine s0(t0,value) character value character t0 cf2py intent(out) t0 t0 = value end subroutine s1(t1,value) character*1 value character*1 t1 cf2py intent(out) t1 t1 = value end subroutine s5(t5,value) character*5 value character*5 t5 cf2py intent(out) t5 t5 = value end subroutine ss(ts,value) character*(*) value character*10 ts cf2py intent(out) ts ts = value end """ @dec.slow def test_all(self): for name in "t0,t1,t5,s0,s1,s5,ss".split(","): self.check_function(getattr(self.module, name)) class TestF90ReturnCharacter(TestReturnCharacter): suffix = ".f90" code = """ module f90_return_char contains function t0(value) character :: value character :: t0 t0 = value end function t0 function t1(value) character(len=1) :: value character(len=1) :: t1 t1 = value end function t1 function t5(value) character(len=5) :: value character(len=5) :: t5 t5 = value end function t5 function ts(value) character(len=*) :: value character(len=10) :: ts ts = value end function ts subroutine s0(t0,value) character :: value character :: t0 !f2py intent(out) t0 t0 = value end subroutine s0 subroutine s1(t1,value) character(len=1) :: value character(len=1) :: t1 !f2py intent(out) t1 t1 = value end subroutine s1 subroutine s5(t5,value) character(len=5) :: value character(len=5) :: t5 !f2py intent(out) t5 t5 = value end subroutine s5 subroutine ss(ts,value) character(len=*) :: value character(len=10) :: ts !f2py intent(out) ts ts = value end subroutine ss end module f90_return_char """ @dec.slow def test_all(self): for name in "t0,t1,t5,ts,s0,s1,s5,ss".split(","): self.check_function(getattr(self.module.f90_return_char, name)) if __name__ == "__main__": import nose nose.runmodule() numpy-1.8.2/numpy/f2py/tests/test_callback.py0000664000175100017510000000467512370216243022377 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function from numpy.testing import * from numpy import array import math import util import textwrap class TestF77Callback(util.F2PyTest): code = """ subroutine t(fun,a) integer a cf2py intent(out) a external fun call fun(a) end subroutine func(a) cf2py intent(in,out) a integer a a = a + 11 end subroutine func0(a) cf2py intent(out) a integer a a = 11 end subroutine t2(a) cf2py intent(callback) fun integer a cf2py intent(out) a external fun call fun(a) end """ @dec.slow def test_all(self): for name in "t,t2".split(","): self.check_function(name) @dec.slow def test_docstring(self): expected = """ a = t(fun,[fun_extra_args]) Wrapper for ``t``. Parameters ---------- fun : call-back function Other Parameters ---------------- fun_extra_args : input tuple, optional Default: () Returns ------- a : int Notes ----- Call-back functions:: def fun(): return a Return objects: a : int """ assert_equal(self.module.t.__doc__, textwrap.dedent(expected).lstrip()) def check_function(self, name): t = getattr(self.module, name) r = t(lambda : 4) assert_( r==4, repr(r)) r = t(lambda a:5, fun_extra_args=(6,)) assert_( r==5, repr(r)) r = t(lambda a:a, fun_extra_args=(6,)) assert_( r==6, repr(r)) r = t(lambda a:5+a, fun_extra_args=(7,)) assert_( r==12, repr(r)) r = t(lambda a:math.degrees(a), fun_extra_args=(math.pi,)) assert_( r==180, repr(r)) r = t(math.degrees, fun_extra_args=(math.pi,)) assert_( r==180, repr(r)) r = t(self.module.func, fun_extra_args=(6,)) assert_( r==17, repr(r)) r = t(self.module.func0) assert_( r==11, repr(r)) r = t(self.module.func0._cpointer) assert_( r==11, repr(r)) class A(object): def __call__(self): return 7 def mth(self): return 9 a = A() r = t(a) assert_( r==7, repr(r)) r = t(a.mth) assert_( r==9, repr(r)) if __name__ == "__main__": import nose nose.runmodule() numpy-1.8.2/numpy/f2py/tests/test_array_from_pyobj.py0000664000175100017510000005127012370216243024200 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function import unittest import os import sys import copy import nose from numpy.testing import * from numpy import array, alltrue, ndarray, asarray, can_cast, zeros, dtype from numpy.core.multiarray import typeinfo import util wrap = None def setup(): """ Build the required testing extension module """ global wrap # Check compiler availability first if not util.has_c_compiler(): raise nose.SkipTest("No C compiler available") if wrap is None: config_code = """ config.add_extension('test_array_from_pyobj_ext', sources=['wrapmodule.c', 'fortranobject.c'], define_macros=[]) """ d = os.path.dirname(__file__) src = [os.path.join(d, 'src', 'array_from_pyobj', 'wrapmodule.c'), os.path.join(d, '..', 'src', 'fortranobject.c'), os.path.join(d, '..', 'src', 'fortranobject.h')] wrap = util.build_module_distutils(src, config_code, 'test_array_from_pyobj_ext') def flags_info(arr): flags = wrap.array_attrs(arr)[6] return flags2names(flags) def flags2names(flags): info = [] for flagname in ['CONTIGUOUS', 'FORTRAN', 'OWNDATA', 'ENSURECOPY', 'ENSUREARRAY', 'ALIGNED', 'NOTSWAPPED', 'WRITEABLE', 'UPDATEIFCOPY', 'BEHAVED', 'BEHAVED_RO', 'CARRAY', 'FARRAY' ]: if abs(flags) & getattr(wrap, flagname, 0): info.append(flagname) return info class Intent(object): def __init__(self,intent_list=[]): self.intent_list = intent_list[:] flags = 0 for i in intent_list: if i=='optional': flags |= wrap.F2PY_OPTIONAL else: flags |= getattr(wrap, 'F2PY_INTENT_'+i.upper()) self.flags = flags def __getattr__(self, name): name = name.lower() if name=='in_': name='in' return self.__class__(self.intent_list+[name]) def __str__(self): return 'intent(%s)' % (','.join(self.intent_list)) def __repr__(self): return 'Intent(%r)' % (self.intent_list) def is_intent(self,*names): for name in names: if name not in self.intent_list: return False return True def is_intent_exact(self,*names): return len(self.intent_list)==len(names) and self.is_intent(*names) 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'] _cast_dict['CDOUBLE'] = _cast_dict['DOUBLE'] + ['CFLOAT', 'CDOUBLE'] _cast_dict['CLONGDOUBLE'] = _cast_dict['LONGDOUBLE'] + ['CFLOAT', 'CDOUBLE', 'CLONGDOUBLE'] def __new__(cls, name): if isinstance(name, dtype): dtype0 = name name = None for n, i in typeinfo.items(): if isinstance(i, tuple) and dtype0.type is i[-1]: name = n break obj = cls._type_cache.get(name.upper(), None) if obj is not None: return obj obj = object.__new__(cls) obj._init(name) cls._type_cache[name.upper()] = obj return obj def _init(self, name): self.NAME = name.upper() self.type_num = getattr(wrap, 'NPY_'+self.NAME) assert_equal(self.type_num, typeinfo[self.NAME][1]) self.dtype = typeinfo[self.NAME][-1] self.elsize = typeinfo[self.NAME][2] / 8 self.dtypechar = typeinfo[self.NAME][0] def cast_types(self): return [self.__class__(_m) for _m in self._cast_dict[self.NAME]] def all_types(self): return [self.__class__(_m) for _m in self._type_names] def smaller_types(self): bits = typeinfo[self.NAME][3] types = [] for name in self._type_names: if typeinfo[name][3]bits: types.append(Type(name)) return types class Array(object): def __init__(self, typ, dims, intent, obj): self.type = typ self.dims = dims self.intent = intent self.obj_copy = copy.deepcopy(obj) self.obj = obj # arr.dtypechar may be different from typ.dtypechar self.arr = wrap.call(typ.type_num, dims, intent.flags, obj) assert_(isinstance(self.arr, ndarray), repr(type(self.arr))) self.arr_attr = wrap.array_attrs(self.arr) if len(dims)>1: if self.intent.is_intent('c'): assert_(intent.flags & wrap.F2PY_INTENT_C) assert_(not self.arr.flags['FORTRAN'], repr((self.arr.flags, getattr(obj, 'flags', None)))) assert_(self.arr.flags['CONTIGUOUS']) assert_(not self.arr_attr[6] & wrap.FORTRAN) else: assert_(not intent.flags & wrap.F2PY_INTENT_C) assert_(self.arr.flags['FORTRAN']) assert_(not self.arr.flags['CONTIGUOUS']) assert_(self.arr_attr[6] & wrap.FORTRAN) if obj is None: self.pyarr = None self.pyarr_attr = None return if intent.is_intent('cache'): assert_(isinstance(obj, ndarray), repr(type(obj))) self.pyarr = array(obj).reshape(*dims).copy() else: self.pyarr = array(array(obj, dtype = typ.dtypechar).reshape(*dims), order=self.intent.is_intent('c') and 'C' or 'F') assert_(self.pyarr.dtype == typ, \ repr((self.pyarr.dtype, typ))) assert_(self.pyarr.flags['OWNDATA'], (obj, intent)) self.pyarr_attr = wrap.array_attrs(self.pyarr) if len(dims)>1: if self.intent.is_intent('c'): assert_(not self.pyarr.flags['FORTRAN']) assert_(self.pyarr.flags['CONTIGUOUS']) assert_(not self.pyarr_attr[6] & wrap.FORTRAN) else: assert_(self.pyarr.flags['FORTRAN']) assert_(not self.pyarr.flags['CONTIGUOUS']) assert_(self.pyarr_attr[6] & wrap.FORTRAN) assert_(self.arr_attr[1]==self.pyarr_attr[1]) # nd 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 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],\ repr((self.arr_attr[6], self.pyarr_attr[6], flags2names(0*self.arr_attr[6]-self.pyarr_attr[6]), flags2names(self.arr_attr[6]), intent))) # flags if intent.is_intent('cache'): assert_(self.arr_attr[5][3]>=self.type.elsize,\ repr((self.arr_attr[5][3], self.type.elsize))) else: assert_(self.arr_attr[5][3]==self.type.elsize,\ repr((self.arr_attr[5][3], self.type.elsize))) assert_(self.arr_equal(self.pyarr, self.arr)) if isinstance(self.obj, ndarray): if typ.elsize==Type(obj.dtype).elsize: if not intent.is_intent('copy') and self.arr_attr[1]<=1: assert_(self.has_shared_memory()) def arr_equal(self, arr1, arr2): if arr1.shape != arr2.shape: return False s = arr1==arr2 return alltrue(s.flatten()) def __str__(self): return str(self.arr) def has_shared_memory(self): """Check that created array shares data with input array. """ if self.obj is self.arr: return True if not isinstance(self.obj, ndarray): return False obj_attr = wrap.array_attrs(self.obj) return obj_attr[0]==self.arr_attr[0] ################################################## class test_intent(unittest.TestCase): def test_in_out(self): assert_equal(str(intent.in_.out), 'intent(in,out)') assert_(intent.in_.c.is_intent('c')) assert_(not intent.in_.c.is_intent_exact('c')) assert_(intent.in_.c.is_intent_exact('c', 'in')) assert_(intent.in_.c.is_intent_exact('in', 'c')) assert_(not intent.in_.is_intent('c')) class _test_shared_memory: num2seq = [1, 2] num23seq = [[1, 2, 3], [4, 5, 6]] def test_in_from_2seq(self): a = self.array([2], intent.in_, self.num2seq) assert_(not a.has_shared_memory()) def test_in_from_2casttype(self): for t in self.type.cast_types(): obj = array(self.num2seq, dtype=t.dtype) a = self.array([len(self.num2seq)], intent.in_, obj) if t.elsize==self.type.elsize: assert_(a.has_shared_memory(), repr((self.type.dtype, t.dtype))) else: assert_(not a.has_shared_memory(), repr(t.dtype)) def test_inout_2seq(self): obj = array(self.num2seq, dtype=self.type.dtype) a = self.array([len(self.num2seq)], intent.inout, obj) assert_(a.has_shared_memory()) try: a = self.array([2], intent.in_.inout, self.num2seq) except TypeError as msg: if not str(msg).startswith('failed to initialize intent(inout|inplace|cache) array'): raise else: raise SystemError('intent(inout) should have failed on sequence') def test_f_inout_23seq(self): obj = array(self.num23seq, dtype=self.type.dtype, order='F') shape = (len(self.num23seq), len(self.num23seq[0])) a = self.array(shape, intent.in_.inout, obj) assert_(a.has_shared_memory()) obj = array(self.num23seq, dtype=self.type.dtype, order='C') shape = (len(self.num23seq), len(self.num23seq[0])) try: a = self.array(shape, intent.in_.inout, obj) except ValueError as msg: if not str(msg).startswith('failed to initialize intent(inout) array'): raise else: raise SystemError('intent(inout) should have failed on improper array') def test_c_inout_23seq(self): obj = array(self.num23seq, dtype=self.type.dtype) shape = (len(self.num23seq), len(self.num23seq[0])) a = self.array(shape, intent.in_.c.inout, obj) assert_(a.has_shared_memory()) def test_in_copy_from_2casttype(self): for t in self.type.cast_types(): obj = array(self.num2seq, dtype=t.dtype) a = self.array([len(self.num2seq)], intent.in_.copy, obj) assert_(not a.has_shared_memory(), repr(t.dtype)) def test_c_in_from_23seq(self): a = self.array([len(self.num23seq), len(self.num23seq[0])], intent.in_, self.num23seq) assert_(not a.has_shared_memory()) def test_in_from_23casttype(self): for t in self.type.cast_types(): obj = array(self.num23seq, dtype=t.dtype) a = self.array([len(self.num23seq), len(self.num23seq[0])], intent.in_, obj) assert_(not a.has_shared_memory(), repr(t.dtype)) def test_f_in_from_23casttype(self): for t in self.type.cast_types(): obj = array(self.num23seq, dtype=t.dtype, order='F') a = self.array([len(self.num23seq), len(self.num23seq[0])], intent.in_, obj) if t.elsize==self.type.elsize: assert_(a.has_shared_memory(), repr(t.dtype)) else: assert_(not a.has_shared_memory(), repr(t.dtype)) def test_c_in_from_23casttype(self): for t in self.type.cast_types(): obj = array(self.num23seq, dtype=t.dtype) a = self.array([len(self.num23seq), len(self.num23seq[0])], intent.in_.c, obj) if t.elsize==self.type.elsize: assert_(a.has_shared_memory(), repr(t.dtype)) else: assert_(not a.has_shared_memory(), repr(t.dtype)) def test_f_copy_in_from_23casttype(self): for t in self.type.cast_types(): obj = array(self.num23seq, dtype=t.dtype, order='F') a = self.array([len(self.num23seq), len(self.num23seq[0])], intent.in_.copy, obj) assert_(not a.has_shared_memory(), repr(t.dtype)) def test_c_copy_in_from_23casttype(self): for t in self.type.cast_types(): obj = array(self.num23seq, dtype=t.dtype) a = self.array([len(self.num23seq), len(self.num23seq[0])], intent.in_.c.copy, obj) assert_(not a.has_shared_memory(), repr(t.dtype)) def test_in_cache_from_2casttype(self): for t in self.type.all_types(): if t.elsize != self.type.elsize: continue obj = array(self.num2seq, dtype=t.dtype) shape = (len(self.num2seq),) a = self.array(shape, intent.in_.c.cache, obj) assert_(a.has_shared_memory(), repr(t.dtype)) a = self.array(shape, intent.in_.cache, obj) assert_(a.has_shared_memory(), repr(t.dtype)) obj = array(self.num2seq, dtype=t.dtype, order='F') a = self.array(shape, intent.in_.c.cache, obj) assert_(a.has_shared_memory(), repr(t.dtype)) a = self.array(shape, intent.in_.cache, obj) assert_(a.has_shared_memory(), repr(t.dtype)) try: a = self.array(shape, intent.in_.cache, obj[::-1]) except ValueError as msg: if not str(msg).startswith('failed to initialize intent(cache) array'): raise else: raise SystemError('intent(cache) should have failed on multisegmented array') def test_in_cache_from_2casttype_failure(self): for t in self.type.all_types(): if t.elsize >= self.type.elsize: continue obj = array(self.num2seq, dtype=t.dtype) shape = (len(self.num2seq),) try: a = self.array(shape, intent.in_.cache, obj) except ValueError as msg: if not str(msg).startswith('failed to initialize intent(cache) array'): raise else: raise SystemError('intent(cache) should have failed on smaller array') def test_cache_hidden(self): shape = (2,) a = self.array(shape, intent.cache.hide, None) assert_(a.arr.shape==shape) shape = (2, 3) a = self.array(shape, intent.cache.hide, None) assert_(a.arr.shape==shape) shape = (-1, 3) try: a = self.array(shape, intent.cache.hide, None) except ValueError as msg: if not str(msg).startswith('failed to create intent(cache|hide)|optional array'): raise else: raise SystemError('intent(cache) should have failed on undefined dimensions') def test_hidden(self): shape = (2,) a = self.array(shape, intent.hide, None) assert_(a.arr.shape==shape) assert_(a.arr_equal(a.arr, zeros(shape, dtype=self.type.dtype))) shape = (2, 3) a = self.array(shape, intent.hide, None) assert_(a.arr.shape==shape) assert_(a.arr_equal(a.arr, zeros(shape, dtype=self.type.dtype))) assert_(a.arr.flags['FORTRAN'] and not a.arr.flags['CONTIGUOUS']) shape = (2, 3) a = self.array(shape, intent.c.hide, None) assert_(a.arr.shape==shape) assert_(a.arr_equal(a.arr, zeros(shape, dtype=self.type.dtype))) assert_(not a.arr.flags['FORTRAN'] and a.arr.flags['CONTIGUOUS']) shape = (-1, 3) try: a = self.array(shape, intent.hide, None) except ValueError as msg: if not str(msg).startswith('failed to create intent(cache|hide)|optional array'): raise else: raise SystemError('intent(hide) should have failed on undefined dimensions') def test_optional_none(self): shape = (2,) a = self.array(shape, intent.optional, None) assert_(a.arr.shape==shape) assert_(a.arr_equal(a.arr, zeros(shape, dtype=self.type.dtype))) shape = (2, 3) a = self.array(shape, intent.optional, None) assert_(a.arr.shape==shape) assert_(a.arr_equal(a.arr, zeros(shape, dtype=self.type.dtype))) assert_(a.arr.flags['FORTRAN'] and not a.arr.flags['CONTIGUOUS']) shape = (2, 3) a = self.array(shape, intent.c.optional, None) assert_(a.arr.shape==shape) assert_(a.arr_equal(a.arr, zeros(shape, dtype=self.type.dtype))) assert_(not a.arr.flags['FORTRAN'] and a.arr.flags['CONTIGUOUS']) def test_optional_from_2seq(self): obj = self.num2seq shape = (len(obj),) a = self.array(shape, intent.optional, obj) assert_(a.arr.shape==shape) assert_(not a.has_shared_memory()) def test_optional_from_23seq(self): obj = self.num23seq shape = (len(obj), len(obj[0])) a = self.array(shape, intent.optional, obj) assert_(a.arr.shape==shape) assert_(not a.has_shared_memory()) a = self.array(shape, intent.optional.c, obj) assert_(a.arr.shape==shape) assert_(not a.has_shared_memory()) def test_inplace(self): obj = array(self.num23seq, dtype=self.type.dtype) assert_(not obj.flags['FORTRAN'] and obj.flags['CONTIGUOUS']) shape = obj.shape a = self.array(shape, intent.inplace, obj) assert_(obj[1][2]==a.arr[1][2], repr((obj, a.arr))) a.arr[1][2]=54 assert_(obj[1][2]==a.arr[1][2]==array(54, dtype=self.type.dtype), repr((obj, a.arr))) assert_(a.arr is obj) assert_(obj.flags['FORTRAN']) # obj attributes are changed inplace! assert_(not obj.flags['CONTIGUOUS']) def test_inplace_from_casttype(self): for t in self.type.cast_types(): if t is self.type: continue obj = array(self.num23seq, dtype=t.dtype) assert_(obj.dtype.type==t.dtype) assert_(obj.dtype.type is not self.type.dtype) assert_(not obj.flags['FORTRAN'] and obj.flags['CONTIGUOUS']) shape = obj.shape a = self.array(shape, intent.inplace, obj) assert_(obj[1][2]==a.arr[1][2], repr((obj, a.arr))) a.arr[1][2]=54 assert_(obj[1][2]==a.arr[1][2]==array(54, dtype=self.type.dtype), repr((obj, a.arr))) assert_(a.arr is obj) assert_(obj.flags['FORTRAN']) # obj attributes are changed inplace! assert_(not obj.flags['CONTIGUOUS']) assert_(obj.dtype.type is self.type.dtype) # obj type is changed inplace! for t in Type._type_names: exec('''\ class test_%s_gen(unittest.TestCase, _test_shared_memory ): def setUp(self): self.type = Type(%r) array = lambda self,dims,intent,obj: Array(Type(%r),dims,intent,obj) ''' % (t, t, t)) if __name__ == "__main__": setup() import nose nose.runmodule() numpy-1.8.2/numpy/f2py/tests/test_return_real.py0000664000175100017510000001231312370216242023150 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function from numpy.testing import * from numpy import array from numpy.compat import long import math import util class TestReturnReal(util.F2PyTest): def check_function(self, t): if t.__doc__.split()[0] in ['t0', 't4', 's0', 's4']: err = 1e-5 else: err = 0.0 assert_( abs(t(234)-234.0)<=err) assert_( abs(t(234.6)-234.6)<=err) assert_( abs(t(long(234))-234.0)<=err) assert_( abs(t('234')-234)<=err) assert_( abs(t('234.6')-234.6)<=err) assert_( abs(t(-234)+234)<=err) assert_( abs(t([234])-234)<=err) assert_( abs(t((234,))-234.)<=err) assert_( abs(t(array(234))-234.)<=err) assert_( abs(t(array([234]))-234.)<=err) assert_( abs(t(array([[234]]))-234.)<=err) assert_( abs(t(array([234], 'b'))+22)<=err) assert_( abs(t(array([234], 'h'))-234.)<=err) assert_( abs(t(array([234], 'i'))-234.)<=err) assert_( abs(t(array([234], 'l'))-234.)<=err) assert_( abs(t(array([234], 'B'))-234.)<=err) assert_( abs(t(array([234], 'f'))-234.)<=err) assert_( abs(t(array([234], 'd'))-234.)<=err) if t.__doc__.split()[0] in ['t0', 't4', 's0', 's4']: assert_( t(1e200)==t(1e300)) # inf #assert_raises(ValueError, t, array([234], 'S1')) assert_raises(ValueError, t, 'abc') assert_raises(IndexError, t, []) assert_raises(IndexError, t, ()) assert_raises(Exception, t, t) assert_raises(Exception, t, {}) try: r = t(10**400) assert_( repr(r) in ['inf', 'Infinity'], repr(r)) except OverflowError: pass class TestCReturnReal(TestReturnReal): suffix = ".pyf" module_name = "c_ext_return_real" code = """ python module c_ext_return_real usercode \'\'\' float t4(float value) { return value; } void s4(float *t4, float value) { *t4 = value; } double t8(double value) { return value; } void s8(double *t8, double value) { *t8 = value; } \'\'\' interface function t4(value) real*4 intent(c) :: t4,value end function t8(value) real*8 intent(c) :: t8,value end subroutine s4(t4,value) intent(c) s4 real*4 intent(out) :: t4 real*4 intent(c) :: value end subroutine s8(t8,value) intent(c) s8 real*8 intent(out) :: t8 real*8 intent(c) :: value end end interface end python module c_ext_return_real """ @dec.slow def test_all(self): for name in "t4,t8,s4,s8".split(","): self.check_function(getattr(self.module, name)) class TestF77ReturnReal(TestReturnReal): code = """ function t0(value) real value real t0 t0 = value end function t4(value) real*4 value real*4 t4 t4 = value end function t8(value) real*8 value real*8 t8 t8 = value end function td(value) double precision value double precision td td = value end subroutine s0(t0,value) real value real t0 cf2py intent(out) t0 t0 = value end subroutine s4(t4,value) real*4 value real*4 t4 cf2py intent(out) t4 t4 = value end subroutine s8(t8,value) real*8 value real*8 t8 cf2py intent(out) t8 t8 = value end subroutine sd(td,value) double precision value double precision td cf2py intent(out) td td = value end """ @dec.slow def test_all(self): for name in "t0,t4,t8,td,s0,s4,s8,sd".split(","): self.check_function(getattr(self.module, name)) class TestF90ReturnReal(TestReturnReal): suffix = ".f90" code = """ module f90_return_real contains function t0(value) real :: value real :: t0 t0 = value end function t0 function t4(value) real(kind=4) :: value real(kind=4) :: t4 t4 = value end function t4 function t8(value) real(kind=8) :: value real(kind=8) :: t8 t8 = value end function t8 function td(value) double precision :: value double precision :: td td = value end function td subroutine s0(t0,value) real :: value real :: t0 !f2py intent(out) t0 t0 = value end subroutine s0 subroutine s4(t4,value) real(kind=4) :: value real(kind=4) :: t4 !f2py intent(out) t4 t4 = value end subroutine s4 subroutine s8(t8,value) real(kind=8) :: value real(kind=8) :: t8 !f2py intent(out) t8 t8 = value end subroutine s8 subroutine sd(td,value) double precision :: value double precision :: td !f2py intent(out) td td = value end subroutine sd end module f90_return_real """ @dec.slow def test_all(self): for name in "t0,t4,t8,td,s0,s4,s8,sd".split(","): self.check_function(getattr(self.module.f90_return_real, name)) if __name__ == "__main__": import nose nose.runmodule() numpy-1.8.2/numpy/f2py/tests/test_return_complex.py0000664000175100017510000001110012370216242023665 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function from numpy.testing import * from numpy import array from numpy.compat import long import util class TestReturnComplex(util.F2PyTest): def check_function(self, t): tname = t.__doc__.split()[0] if tname in ['t0', 't8', 's0', 's8']: err = 1e-5 else: err = 0.0 assert_( abs(t(234j)-234.0j)<=err) assert_( abs(t(234.6)-234.6)<=err) assert_( abs(t(long(234))-234.0)<=err) assert_( abs(t(234.6+3j)-(234.6+3j))<=err) #assert_( abs(t('234')-234.)<=err) #assert_( abs(t('234.6')-234.6)<=err) assert_( abs(t(-234)+234.)<=err) assert_( abs(t([234])-234.)<=err) assert_( abs(t((234,))-234.)<=err) assert_( abs(t(array(234))-234.)<=err) assert_( abs(t(array(23+4j, 'F'))-(23+4j))<=err) assert_( abs(t(array([234]))-234.)<=err) assert_( abs(t(array([[234]]))-234.)<=err) assert_( abs(t(array([234], 'b'))+22.)<=err) assert_( abs(t(array([234], 'h'))-234.)<=err) assert_( abs(t(array([234], 'i'))-234.)<=err) assert_( abs(t(array([234], 'l'))-234.)<=err) assert_( abs(t(array([234], 'q'))-234.)<=err) assert_( abs(t(array([234], 'f'))-234.)<=err) assert_( abs(t(array([234], 'd'))-234.)<=err) assert_( abs(t(array([234+3j], 'F'))-(234+3j))<=err) assert_( abs(t(array([234], 'D'))-234.)<=err) #assert_raises(TypeError, t, array([234], 'a1')) assert_raises(TypeError, t, 'abc') assert_raises(IndexError, t, []) assert_raises(IndexError, t, ()) assert_raises(TypeError, t, t) assert_raises(TypeError, t, {}) try: r = t(10**400) assert_( repr(r) in ['(inf+0j)', '(Infinity+0j)'], repr(r)) except OverflowError: pass class TestF77ReturnComplex(TestReturnComplex): code = """ function t0(value) complex value complex t0 t0 = value end function t8(value) complex*8 value complex*8 t8 t8 = value end function t16(value) complex*16 value complex*16 t16 t16 = value end function td(value) double complex value double complex td td = value end subroutine s0(t0,value) complex value complex t0 cf2py intent(out) t0 t0 = value end subroutine s8(t8,value) complex*8 value complex*8 t8 cf2py intent(out) t8 t8 = value end subroutine s16(t16,value) complex*16 value complex*16 t16 cf2py intent(out) t16 t16 = value end subroutine sd(td,value) double complex value double complex td cf2py intent(out) td td = value end """ @dec.slow def test_all(self): for name in "t0,t8,t16,td,s0,s8,s16,sd".split(","): self.check_function(getattr(self.module, name)) class TestF90ReturnComplex(TestReturnComplex): suffix = ".f90" code = """ module f90_return_complex contains function t0(value) complex :: value complex :: t0 t0 = value end function t0 function t8(value) complex(kind=4) :: value complex(kind=4) :: t8 t8 = value end function t8 function t16(value) complex(kind=8) :: value complex(kind=8) :: t16 t16 = value end function t16 function td(value) double complex :: value double complex :: td td = value end function td subroutine s0(t0,value) complex :: value complex :: t0 !f2py intent(out) t0 t0 = value end subroutine s0 subroutine s8(t8,value) complex(kind=4) :: value complex(kind=4) :: t8 !f2py intent(out) t8 t8 = value end subroutine s8 subroutine s16(t16,value) complex(kind=8) :: value complex(kind=8) :: t16 !f2py intent(out) t16 t16 = value end subroutine s16 subroutine sd(td,value) double complex :: value double complex :: td !f2py intent(out) td td = value end subroutine sd end module f90_return_complex """ @dec.slow def test_all(self): for name in "t0,t8,t16,td,s0,s8,s16,sd".split(","): self.check_function(getattr(self.module.f90_return_complex, name)) if __name__ == "__main__": import nose nose.runmodule() numpy-1.8.2/numpy/f2py/tests/test_mixed.py0000664000175100017510000000167412370216242021744 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function import os import math from numpy.testing import * from numpy import array import util import textwrap def _path(*a): return os.path.join(*((os.path.dirname(__file__),) + a)) class TestMixed(util.F2PyTest): sources = [_path('src', 'mixed', 'foo.f'), _path('src', 'mixed', 'foo_fixed.f90'), _path('src', 'mixed', 'foo_free.f90')] @dec.slow def test_all(self): assert_( self.module.bar11() == 11) assert_( self.module.foo_fixed.bar12() == 12) assert_( self.module.foo_free.bar13() == 13) @dec.slow def test_docstring(self): expected = """ a = bar11() Wrapper for ``bar11``. Returns ------- a : int """ assert_equal(self.module.bar11.__doc__, textwrap.dedent(expected).lstrip()) if __name__ == "__main__": import nose nose.runmodule() numpy-1.8.2/numpy/f2py/tests/test_return_logical.py0000664000175100017510000001140212370216242023635 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function from numpy.testing import * from numpy import array from numpy.compat import long import util class TestReturnLogical(util.F2PyTest): def check_function(self, t): assert_( t(True)==1, repr(t(True))) assert_( t(False)==0, repr(t(False))) assert_( t(0)==0) assert_( t(None)==0) assert_( t(0.0)==0) assert_( t(0j)==0) assert_( t(1j)==1) assert_( t(234)==1) assert_( t(234.6)==1) assert_( t(long(234))==1) assert_( t(234.6+3j)==1) assert_( t('234')==1) assert_( t('aaa')==1) assert_( t('')==0) assert_( t([])==0) assert_( t(())==0) assert_( t({})==0) assert_( t(t)==1) assert_( t(-234)==1) assert_( t(10**100)==1) assert_( t([234])==1) assert_( t((234,))==1) assert_( t(array(234))==1) assert_( t(array([234]))==1) assert_( t(array([[234]]))==1) assert_( t(array([234], 'b'))==1) assert_( t(array([234], 'h'))==1) assert_( t(array([234], 'i'))==1) assert_( t(array([234], 'l'))==1) assert_( t(array([234], 'f'))==1) assert_( t(array([234], 'd'))==1) assert_( t(array([234+3j], 'F'))==1) assert_( t(array([234], 'D'))==1) assert_( t(array(0))==0) assert_( t(array([0]))==0) assert_( t(array([[0]]))==0) assert_( t(array([0j]))==0) assert_( t(array([1]))==1) assert_raises(ValueError, t, array([0, 0])) class TestF77ReturnLogical(TestReturnLogical): code = """ function t0(value) logical value logical t0 t0 = value end function t1(value) logical*1 value logical*1 t1 t1 = value end function t2(value) logical*2 value logical*2 t2 t2 = value end function t4(value) logical*4 value logical*4 t4 t4 = value end c function t8(value) c logical*8 value c logical*8 t8 c t8 = value c end subroutine s0(t0,value) logical value logical t0 cf2py intent(out) t0 t0 = value end subroutine s1(t1,value) logical*1 value logical*1 t1 cf2py intent(out) t1 t1 = value end subroutine s2(t2,value) logical*2 value logical*2 t2 cf2py intent(out) t2 t2 = value end subroutine s4(t4,value) logical*4 value logical*4 t4 cf2py intent(out) t4 t4 = value end c subroutine s8(t8,value) c logical*8 value c logical*8 t8 cf2py intent(out) t8 c t8 = value c end """ @dec.slow def test_all(self): for name in "t0,t1,t2,t4,s0,s1,s2,s4".split(","): self.check_function(getattr(self.module, name)) class TestF90ReturnLogical(TestReturnLogical): suffix = ".f90" code = """ module f90_return_logical contains function t0(value) logical :: value logical :: t0 t0 = value end function t0 function t1(value) logical(kind=1) :: value logical(kind=1) :: t1 t1 = value end function t1 function t2(value) logical(kind=2) :: value logical(kind=2) :: t2 t2 = value end function t2 function t4(value) logical(kind=4) :: value logical(kind=4) :: t4 t4 = value end function t4 function t8(value) logical(kind=8) :: value logical(kind=8) :: t8 t8 = value end function t8 subroutine s0(t0,value) logical :: value logical :: t0 !f2py intent(out) t0 t0 = value end subroutine s0 subroutine s1(t1,value) logical(kind=1) :: value logical(kind=1) :: t1 !f2py intent(out) t1 t1 = value end subroutine s1 subroutine s2(t2,value) logical(kind=2) :: value logical(kind=2) :: t2 !f2py intent(out) t2 t2 = value end subroutine s2 subroutine s4(t4,value) logical(kind=4) :: value logical(kind=4) :: t4 !f2py intent(out) t4 t4 = value end subroutine s4 subroutine s8(t8,value) logical(kind=8) :: value logical(kind=8) :: t8 !f2py intent(out) t8 t8 = value end subroutine s8 end module f90_return_logical """ @dec.slow def test_all(self): for name in "t0,t1,t2,t4,t8,s0,s1,s2,s4,s8".split(","): self.check_function(getattr(self.module.f90_return_logical, name)) if __name__ == "__main__": import nose nose.runmodule() numpy-1.8.2/numpy/f2py/tests/test_size.py0000664000175100017510000000224212370216242021600 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function import os import math from numpy.testing import * from numpy import array import util def _path(*a): return os.path.join(*((os.path.dirname(__file__),) + a)) class TestSizeSumExample(util.F2PyTest): sources = [_path('src', 'size', 'foo.f90'), ] @dec.slow def test_all(self): r = self.module.foo([[1, 2]]) assert_equal(r, [3], repr(r)) r = self.module.foo([[1, 2], [3, 4]]) assert_equal(r, [3, 7], repr(r)) r = self.module.foo([[1, 2], [3, 4], [5, 6]]) assert_equal(r, [3, 7, 11], repr(r)) @dec.slow def test_transpose(self): r = self.module.trans([[1, 2]]) assert_equal(r, [[1], [2]], repr(r)) r = self.module.trans([[1, 2, 3], [4, 5, 6]]) assert_equal(r, [[1, 4], [2, 5], [3, 6]], repr(r)) @dec.slow def test_flatten(self): r = self.module.flatten([[1, 2]]) assert_equal(r, [1, 2], repr(r)) r = self.module.flatten([[1, 2, 3], [4, 5, 6]]) assert_equal(r, [1, 2, 3, 4, 5, 6], repr(r)) if __name__ == "__main__": import nose nose.runmodule() numpy-1.8.2/numpy/f2py/capi_maps.py0000664000175100017510000007130412370216242020366 0ustar vagrantvagrant00000000000000#!/usr/bin/env python """ Copyright 1999,2000 Pearu Peterson all rights reserved, Pearu Peterson Permission to use, modify, and distribute this software is given under the terms of the NumPy License. NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. $Date: 2005/05/06 10:57:33 $ Pearu Peterson """ from __future__ import division, absolute_import, print_function __version__ = "$Revision: 1.60 $"[10:-1] from . import __version__ f2py_version = __version__.version import copy import re import os import sys from .auxfuncs import * from .crackfortran import markoutercomma from . import cb_rules # Numarray and Numeric users should set this False using_newcore = True depargs=[] lcb_map={} lcb2_map={} # forced casting: mainly caused by the fact that Python or Numeric # C/APIs do not support the corresponding C types. c2py_map={'double': 'float', 'float': 'float', # forced casting 'long_double': 'float', # forced casting 'char': 'int', # forced casting 'signed_char': 'int', # forced casting 'unsigned_char': 'int', # forced casting 'short': 'int', # forced casting 'unsigned_short': 'int', # forced casting 'int': 'int', # (forced casting) 'long': 'int', 'long_long': 'long', 'unsigned': 'int', # forced casting 'complex_float': 'complex', # forced casting 'complex_double': 'complex', 'complex_long_double': 'complex', # forced casting 'string': 'string', } c2capi_map={'double':'NPY_DOUBLE', 'float':'NPY_FLOAT', 'long_double':'NPY_DOUBLE', # forced casting 'char':'NPY_CHAR', 'unsigned_char':'NPY_UBYTE', 'signed_char':'NPY_BYTE', 'short':'NPY_SHORT', 'unsigned_short':'NPY_USHORT', 'int':'NPY_INT', 'unsigned':'NPY_UINT', 'long':'NPY_LONG', 'long_long':'NPY_LONG', # forced casting 'complex_float':'NPY_CFLOAT', 'complex_double':'NPY_CDOUBLE', 'complex_long_double':'NPY_CDOUBLE', # forced casting 'string':'NPY_CHAR'} #These new maps aren't used anyhere yet, but should be by default # unless building numeric or numarray extensions. if using_newcore: c2capi_map={'double': 'NPY_DOUBLE', 'float': 'NPY_FLOAT', 'long_double': 'NPY_LONGDOUBLE', 'char': 'NPY_BYTE', 'unsigned_char': 'NPY_UBYTE', 'signed_char': 'NPY_BYTE', 'short': 'NPY_SHORT', 'unsigned_short': 'NPY_USHORT', 'int': 'NPY_INT', 'unsigned': 'NPY_UINT', 'long': 'NPY_LONG', 'unsigned_long': 'NPY_ULONG', 'long_long': 'NPY_LONGLONG', 'unsigned_long_long': 'NPY_ULONGLONG', 'complex_float': 'NPY_CFLOAT', 'complex_double': 'NPY_CDOUBLE', 'complex_long_double': 'NPY_CDOUBLE', 'string': 'NPY_CHAR', # f2py 2e is not ready for NPY_STRING (must set itemisize etc) #'string':'NPY_STRING' } c2pycode_map={'double':'d', 'float':'f', 'long_double':'d', # forced casting 'char':'1', 'signed_char':'1', 'unsigned_char':'b', 'short':'s', 'unsigned_short':'w', 'int':'i', 'unsigned':'u', 'long':'l', 'long_long':'L', 'complex_float':'F', 'complex_double':'D', 'complex_long_double':'D', # forced casting 'string':'c' } if using_newcore: c2pycode_map={'double':'d', 'float':'f', 'long_double':'g', 'char':'b', 'unsigned_char':'B', 'signed_char':'b', 'short':'h', 'unsigned_short':'H', 'int':'i', 'unsigned':'I', 'long':'l', 'unsigned_long':'L', 'long_long':'q', 'unsigned_long_long':'Q', 'complex_float':'F', 'complex_double':'D', 'complex_long_double':'G', 'string':'S'} c2buildvalue_map={'double':'d', 'float':'f', 'char':'b', 'signed_char':'b', 'short':'h', 'int':'i', 'long':'l', 'long_long':'L', 'complex_float':'N', 'complex_double':'N', 'complex_long_double':'N', 'string':'z'} if sys.version_info[0] >= 3: # Bytes, not Unicode strings c2buildvalue_map['string'] = 'y' if using_newcore: #c2buildvalue_map=??? pass f2cmap_all={'real':{'':'float','4':'float','8':'double','12':'long_double','16':'long_double'}, 'integer':{'':'int','1':'signed_char','2':'short','4':'int','8':'long_long', '-1':'unsigned_char','-2':'unsigned_short','-4':'unsigned', '-8':'unsigned_long_long'}, 'complex':{'':'complex_float','8':'complex_float', '16':'complex_double','24':'complex_long_double', '32':'complex_long_double'}, 'complexkind':{'':'complex_float','4':'complex_float', '8':'complex_double','12':'complex_long_double', '16':'complex_long_double'}, 'logical':{'':'int','1':'char','2':'short','4':'int','8':'long_long'}, 'double complex':{'':'complex_double'}, 'double precision':{'':'double'}, 'byte':{'':'char'}, 'character':{'':'string'} } if os.path.isfile('.f2py_f2cmap'): # User defined additions to f2cmap_all. # .f2py_f2cmap must contain a dictionary of dictionaries, only. # For example, {'real':{'low':'float'}} means that Fortran 'real(low)' is # interpreted as C 'float'. # This feature is useful for F90/95 users if they use PARAMETERSs # in type specifications. try: outmess('Reading .f2py_f2cmap ...\n') f = open('.f2py_f2cmap', 'r') d = eval(f.read(), {}, {}) f.close() for k, d1 in d.items(): for k1 in d1.keys(): d1[k1.lower()] = d1[k1] d[k.lower()] = d[k] for k in d.keys(): if k not in f2cmap_all: f2cmap_all[k]={} for k1 in d[k].keys(): if d[k][k1] in c2py_map: if k1 in f2cmap_all[k]: outmess("\tWarning: redefinition of {'%s':{'%s':'%s'->'%s'}}\n"%(k, k1, f2cmap_all[k][k1], d[k][k1])) f2cmap_all[k][k1] = d[k][k1] outmess('\tMapping "%s(kind=%s)" to "%s"\n' % (k, k1, d[k][k1])) else: errmess("\tIgnoring map {'%s':{'%s':'%s'}}: '%s' must be in %s\n"%(k, k1, d[k][k1], d[k][k1], list(c2py_map.keys()))) outmess('Succesfully applied user defined changes from .f2py_f2cmap\n') except Exception as msg: errmess('Failed to apply user defined changes from .f2py_f2cmap: %s. Skipping.\n' % (msg)) cformat_map={'double': '%g', 'float': '%g', 'long_double': '%Lg', 'char': '%d', 'signed_char': '%d', 'unsigned_char': '%hhu', 'short': '%hd', 'unsigned_short': '%hu', 'int': '%d', 'unsigned': '%u', 'long': '%ld', 'unsigned_long': '%lu', 'long_long': '%ld', 'complex_float': '(%g,%g)', 'complex_double': '(%g,%g)', 'complex_long_double': '(%Lg,%Lg)', 'string': '%s', } ############### Auxiliary functions def getctype(var): """ Determines C type """ ctype='void' if isfunction(var): if 'result' in var: a=var['result'] else: a=var['name'] if a in var['vars']: return getctype(var['vars'][a]) else: errmess('getctype: function %s has no return value?!\n'%a) elif issubroutine(var): return ctype elif 'typespec' in var and var['typespec'].lower() in f2cmap_all: typespec = var['typespec'].lower() f2cmap=f2cmap_all[typespec] ctype=f2cmap[''] # default type if 'kindselector' in var: if '*' in var['kindselector']: try: ctype=f2cmap[var['kindselector']['*']] except KeyError: errmess('getctype: "%s %s %s" not supported.\n'%(var['typespec'], '*', var['kindselector']['*'])) elif 'kind' in var['kindselector']: if typespec+'kind' in f2cmap_all: f2cmap=f2cmap_all[typespec+'kind'] try: ctype=f2cmap[var['kindselector']['kind']] except KeyError: if typespec in f2cmap_all: f2cmap=f2cmap_all[typespec] try: ctype=f2cmap[str(var['kindselector']['kind'])] except KeyError: errmess('getctype: "%s(kind=%s)" is mapped to C "%s" (to override define dict(%s = dict(%s="")) in %s/.f2py_f2cmap file).\n'\ %(typespec, var['kindselector']['kind'], ctype, typespec, var['kindselector']['kind'], os.getcwd())) else: if not isexternal(var): errmess('getctype: No C-type found in "%s", assuming void.\n'%var) return ctype def getstrlength(var): if isstringfunction(var): if 'result' in var: a=var['result'] else: a=var['name'] if a in var['vars']: return getstrlength(var['vars'][a]) else: errmess('getstrlength: function %s has no return value?!\n'%a) if not isstring(var): errmess('getstrlength: expected a signature of a string but got: %s\n'%(repr(var))) len='1' if 'charselector' in var: a=var['charselector'] if '*' in a: len=a['*'] elif 'len' in a: len=a['len'] if re.match(r'\(\s*([*]|[:])\s*\)', len) or re.match(r'([*]|[:])', len): #if len in ['(*)','*','(:)',':']: if isintent_hide(var): errmess('getstrlength:intent(hide): expected a string with defined length but got: %s\n'%(repr(var))) len='-1' return len def getarrdims(a,var,verbose=0): global depargs ret={} if isstring(var) and not isarray(var): ret['dims']=getstrlength(var) ret['size']=ret['dims'] ret['rank']='1' elif isscalar(var): ret['size']='1' ret['rank']='0' ret['dims']='' elif isarray(var): # if not isintent_c(var): # var['dimension'].reverse() dim=copy.copy(var['dimension']) ret['size']='*'.join(dim) try: ret['size']=repr(eval(ret['size'])) except: pass ret['dims']=','.join(dim) ret['rank']=repr(len(dim)) ret['rank*[-1]']=repr(len(dim)*[-1])[1:-1] for i in range(len(dim)): # solve dim for dependecies v=[] if dim[i] in depargs: v=[dim[i]] else: for va in depargs: if re.match(r'.*?\b%s\b.*'%va, dim[i]): v.append(va) for va in v: if depargs.index(va)>depargs.index(a): dim[i]='*' break ret['setdims'], i='', -1 for d in dim: i=i+1 if d not in ['*', ':', '(*)', '(:)']: ret['setdims']='%s#varname#_Dims[%d]=%s,'%(ret['setdims'], i, d) if ret['setdims']: ret['setdims']=ret['setdims'][:-1] ret['cbsetdims'], i='', -1 for d in var['dimension']: i=i+1 if d not in ['*', ':', '(*)', '(:)']: ret['cbsetdims']='%s#varname#_Dims[%d]=%s,'%(ret['cbsetdims'], i, d) elif isintent_in(var): outmess('getarrdims:warning: assumed shape array, using 0 instead of %r\n' \ % (d)) ret['cbsetdims']='%s#varname#_Dims[%d]=%s,'%(ret['cbsetdims'], i, 0) elif verbose : errmess('getarrdims: If in call-back function: array argument %s must have bounded dimensions: got %s\n'%(repr(a), repr(d))) if ret['cbsetdims']: ret['cbsetdims']=ret['cbsetdims'][:-1] # if not isintent_c(var): # var['dimension'].reverse() return ret def getpydocsign(a, var): global lcb_map if isfunction(var): if 'result' in var: af=var['result'] else: af=var['name'] if af in var['vars']: return getpydocsign(af, var['vars'][af]) else: errmess('getctype: function %s has no return value?!\n'%af) return '', '' sig, sigout=a, a opt='' if isintent_in(var): opt='input' elif isintent_inout(var): opt='in/output' out_a = a if isintent_out(var): for k in var['intent']: if k[:4]=='out=': out_a = k[4:] break init='' ctype=getctype(var) if hasinitvalue(var): init, showinit=getinit(a, var) init = ', optional\\n Default: %s' % showinit if isscalar(var): if isintent_inout(var): sig='%s : %s rank-0 array(%s,\'%s\')%s'%(a, opt, c2py_map[ctype], c2pycode_map[ctype], init) else: sig='%s : %s %s%s'%(a, opt, c2py_map[ctype], init) sigout='%s : %s'%(out_a, c2py_map[ctype]) elif isstring(var): if isintent_inout(var): sig='%s : %s rank-0 array(string(len=%s),\'c\')%s'%(a, opt, getstrlength(var), init) else: sig='%s : %s string(len=%s)%s'%(a, opt, getstrlength(var), init) sigout='%s : string(len=%s)'%(out_a, getstrlength(var)) elif isarray(var): dim=var['dimension'] rank=repr(len(dim)) sig='%s : %s rank-%s array(\'%s\') with bounds (%s)%s'%(a, opt, rank, c2pycode_map[ctype], ','.join(dim), init) if a==out_a: sigout='%s : rank-%s array(\'%s\') with bounds (%s)'\ %(a, rank, c2pycode_map[ctype], ','.join(dim)) else: sigout='%s : rank-%s array(\'%s\') with bounds (%s) and %s storage'\ %(out_a, rank, c2pycode_map[ctype], ','.join(dim), a) elif isexternal(var): ua='' if a in lcb_map and lcb_map[a] in lcb2_map and 'argname' in lcb2_map[lcb_map[a]]: ua=lcb2_map[lcb_map[a]]['argname'] if not ua==a: ua=' => %s'%ua else: ua='' sig='%s : call-back function%s'%(a, ua) sigout=sig else: errmess('getpydocsign: Could not resolve docsignature for "%s".\\n'%a) return sig, sigout def getarrdocsign(a, var): ctype=getctype(var) if isstring(var) and (not isarray(var)): sig='%s : rank-0 array(string(len=%s),\'c\')'%(a, getstrlength(var)) elif isscalar(var): sig='%s : rank-0 array(%s,\'%s\')'%(a, c2py_map[ctype], c2pycode_map[ctype],) elif isarray(var): dim=var['dimension'] rank=repr(len(dim)) sig='%s : rank-%s array(\'%s\') with bounds (%s)'%(a, rank, c2pycode_map[ctype], ','.join(dim)) return sig def getinit(a, var): if isstring(var): init, showinit='""', "''" else: init, showinit='', '' if hasinitvalue(var): init=var['='] showinit=init if iscomplex(var) or iscomplexarray(var): ret={} try: v = var["="] if ',' in v: ret['init.r'], ret['init.i']=markoutercomma(v[1:-1]).split('@,@') else: v = eval(v, {}, {}) ret['init.r'], ret['init.i']=str(v.real), str(v.imag) except: raise ValueError('getinit: expected complex number `(r,i)\' but got `%s\' as initial value of %r.' % (init, a)) if isarray(var): init='(capi_c.r=%s,capi_c.i=%s,capi_c)'%(ret['init.r'], ret['init.i']) elif isstring(var): if not init: init, showinit='""', "''" if init[0]=="'": init='"%s"'%(init[1:-1].replace('"', '\\"')) if init[0]=='"': showinit="'%s'"%(init[1:-1]) return init, showinit def sign2map(a, var): """ varname,ctype,atype init,init.r,init.i,pytype vardebuginfo,vardebugshowvalue,varshowvalue varrfromat intent """ global lcb_map, cb_map out_a = a if isintent_out(var): for k in var['intent']: if k[:4]=='out=': out_a = k[4:] break ret={'varname':a,'outvarname':out_a} ret['ctype']=getctype(var) intent_flags = [] for f, s in isintent_dict.items(): if f(var): intent_flags.append('F2PY_%s'%s) if intent_flags: #XXX: Evaluate intent_flags here. ret['intent'] = '|'.join(intent_flags) else: ret['intent'] = 'F2PY_INTENT_IN' if isarray(var): ret['varrformat']='N' elif ret['ctype'] in c2buildvalue_map: ret['varrformat']=c2buildvalue_map[ret['ctype']] else: ret['varrformat']='O' ret['init'], ret['showinit']=getinit(a, var) if hasinitvalue(var) and iscomplex(var) and not isarray(var): ret['init.r'], ret['init.i'] = markoutercomma(ret['init'][1:-1]).split('@,@') if isexternal(var): ret['cbnamekey']=a if a in lcb_map: ret['cbname']=lcb_map[a] ret['maxnofargs']=lcb2_map[lcb_map[a]]['maxnofargs'] ret['nofoptargs']=lcb2_map[lcb_map[a]]['nofoptargs'] ret['cbdocstr']=lcb2_map[lcb_map[a]]['docstr'] ret['cblatexdocstr']=lcb2_map[lcb_map[a]]['latexdocstr'] else: ret['cbname']=a errmess('sign2map: Confused: external %s is not in lcb_map%s.\n'%(a, list(lcb_map.keys()))) if isstring(var): ret['length']=getstrlength(var) if isarray(var): ret=dictappend(ret, getarrdims(a, var)) dim=copy.copy(var['dimension']) if ret['ctype'] in c2capi_map: ret['atype']=c2capi_map[ret['ctype']] # Debug info if debugcapi(var): il=[isintent_in, 'input', isintent_out, 'output', isintent_inout, 'inoutput', isrequired, 'required', isoptional, 'optional', isintent_hide, 'hidden', iscomplex, 'complex scalar', l_and(isscalar, l_not(iscomplex)), 'scalar', isstring, 'string', isarray, 'array', iscomplexarray, 'complex array', isstringarray, 'string array', iscomplexfunction, 'complex function', l_and(isfunction, l_not(iscomplexfunction)), 'function', isexternal, 'callback', isintent_callback, 'callback', isintent_aux, 'auxiliary', #ismutable,'mutable',l_not(ismutable),'immutable', ] rl=[] for i in range(0, len(il), 2): if il[i](var): rl.append(il[i+1]) if isstring(var): rl.append('slen(%s)=%s'%(a, ret['length'])) if isarray(var): # if not isintent_c(var): # var['dimension'].reverse() ddim=','.join(map(lambda x, y:'%s|%s'%(x, y), var['dimension'], dim)) rl.append('dims(%s)'%ddim) # if not isintent_c(var): # var['dimension'].reverse() if isexternal(var): ret['vardebuginfo']='debug-capi:%s=>%s:%s'%(a, ret['cbname'], ','.join(rl)) else: ret['vardebuginfo']='debug-capi:%s %s=%s:%s'%(ret['ctype'], a, ret['showinit'], ','.join(rl)) if isscalar(var): if ret['ctype'] in cformat_map: ret['vardebugshowvalue']='debug-capi:%s=%s'%(a, cformat_map[ret['ctype']]) if isstring(var): ret['vardebugshowvalue']='debug-capi:slen(%s)=%%d %s=\\"%%s\\"'%(a, a) if isexternal(var): ret['vardebugshowvalue']='debug-capi:%s=%%p'%(a) if ret['ctype'] in cformat_map: ret['varshowvalue']='#name#:%s=%s'%(a, cformat_map[ret['ctype']]) ret['showvalueformat']='%s'%(cformat_map[ret['ctype']]) if isstring(var): ret['varshowvalue']='#name#:slen(%s)=%%d %s=\\"%%s\\"'%(a, a) ret['pydocsign'], ret['pydocsignout']=getpydocsign(a, var) if hasnote(var): ret['note']=var['note'] return ret def routsign2map(rout): """ name,NAME,begintitle,endtitle rname,ctype,rformat routdebugshowvalue """ global lcb_map name = rout['name'] fname = getfortranname(rout) ret={'name': name, 'texname': name.replace('_', '\\_'), 'name_lower': name.lower(), 'NAME': name.upper(), 'begintitle': gentitle(name), 'endtitle': gentitle('end of %s'%name), 'fortranname': fname, 'FORTRANNAME': fname.upper(), 'callstatement': getcallstatement(rout) or '', 'usercode': getusercode(rout) or '', 'usercode1': getusercode1(rout) or '', } if '_' in fname: ret['F_FUNC'] = 'F_FUNC_US' else: ret['F_FUNC'] = 'F_FUNC' if '_' in name: ret['F_WRAPPEDFUNC'] = 'F_WRAPPEDFUNC_US' else: ret['F_WRAPPEDFUNC'] = 'F_WRAPPEDFUNC' lcb_map={} if 'use' in rout: for u in rout['use'].keys(): if u in cb_rules.cb_map: for un in cb_rules.cb_map[u]: ln=un[0] if 'map' in rout['use'][u]: for k in rout['use'][u]['map'].keys(): if rout['use'][u]['map'][k]==un[0]: ln=k;break lcb_map[ln]=un[1] #else: # errmess('routsign2map: cb_map does not contain module "%s" used in "use" statement.\n'%(u)) elif 'externals' in rout and rout['externals']: errmess('routsign2map: Confused: function %s has externals %s but no "use" statement.\n'%(ret['name'], repr(rout['externals']))) ret['callprotoargument'] = getcallprotoargument(rout, lcb_map) or '' if isfunction(rout): if 'result' in rout: a=rout['result'] else: a=rout['name'] ret['rname']=a ret['pydocsign'], ret['pydocsignout']=getpydocsign(a, rout) ret['ctype']=getctype(rout['vars'][a]) if hasresultnote(rout): ret['resultnote']=rout['vars'][a]['note'] rout['vars'][a]['note']=['See elsewhere.'] if ret['ctype'] in c2buildvalue_map: ret['rformat']=c2buildvalue_map[ret['ctype']] else: ret['rformat']='O' errmess('routsign2map: no c2buildvalue key for type %s\n'%(repr(ret['ctype']))) if debugcapi(rout): if ret['ctype'] in cformat_map: ret['routdebugshowvalue']='debug-capi:%s=%s'%(a, cformat_map[ret['ctype']]) if isstringfunction(rout): ret['routdebugshowvalue']='debug-capi:slen(%s)=%%d %s=\\"%%s\\"'%(a, a) if isstringfunction(rout): ret['rlength']=getstrlength(rout['vars'][a]) if ret['rlength']=='-1': errmess('routsign2map: expected explicit specification of the length of the string returned by the fortran function %s; taking 10.\n'%(repr(rout['name']))) ret['rlength']='10' if hasnote(rout): ret['note']=rout['note'] rout['note']=['See elsewhere.'] return ret def modsign2map(m): """ modulename """ if ismodule(m): ret={'f90modulename':m['name'], 'F90MODULENAME':m['name'].upper(), 'texf90modulename':m['name'].replace('_', '\\_')} else: ret={'modulename':m['name'], 'MODULENAME':m['name'].upper(), 'texmodulename':m['name'].replace('_', '\\_')} ret['restdoc'] = getrestdoc(m) or [] if hasnote(m): ret['note']=m['note'] #m['note']=['See elsewhere.'] ret['usercode'] = getusercode(m) or '' ret['usercode1'] = getusercode1(m) or '' if m['body']: ret['interface_usercode'] = getusercode(m['body'][0]) or '' else: ret['interface_usercode'] = '' ret['pymethoddef'] = getpymethoddef(m) or '' if 'coutput' in m: ret['coutput'] = m['coutput'] if 'f2py_wrapper_output' in m: ret['f2py_wrapper_output'] = m['f2py_wrapper_output'] return ret def cb_sign2map(a,var,index=None): ret={'varname':a} if index is None or 1: # disable 7712 patch ret['varname_i'] = ret['varname'] else: ret['varname_i'] = ret['varname'] + '_' + str(index) ret['ctype']=getctype(var) if ret['ctype'] in c2capi_map: ret['atype']=c2capi_map[ret['ctype']] if ret['ctype'] in cformat_map: ret['showvalueformat']='%s'%(cformat_map[ret['ctype']]) if isarray(var): ret=dictappend(ret, getarrdims(a, var)) ret['pydocsign'], ret['pydocsignout']=getpydocsign(a, var) if hasnote(var): ret['note']=var['note'] var['note']=['See elsewhere.'] return ret def cb_routsign2map(rout, um): """ name,begintitle,endtitle,argname ctype,rctype,maxnofargs,nofoptargs,returncptr """ ret={'name':'cb_%s_in_%s'%(rout['name'], um), 'returncptr':''} if isintent_callback(rout): if '_' in rout['name']: F_FUNC='F_FUNC_US' else: F_FUNC='F_FUNC' ret['callbackname'] = '%s(%s,%s)' \ % (F_FUNC, rout['name'].lower(), rout['name'].upper(), ) ret['static'] = 'extern' else: ret['callbackname'] = ret['name'] ret['static'] = 'static' ret['argname']=rout['name'] ret['begintitle']=gentitle(ret['name']) ret['endtitle']=gentitle('end of %s'%ret['name']) ret['ctype']=getctype(rout) ret['rctype']='void' if ret['ctype']=='string': ret['rctype']='void' else: ret['rctype']=ret['ctype'] if ret['rctype']!='void': if iscomplexfunction(rout): ret['returncptr'] = """ #ifdef F2PY_CB_RETURNCOMPLEX return_value= #endif """ else: ret['returncptr'] = 'return_value=' if ret['ctype'] in cformat_map: ret['showvalueformat']='%s'%(cformat_map[ret['ctype']]) if isstringfunction(rout): ret['strlength']=getstrlength(rout) if isfunction(rout): if 'result' in rout: a=rout['result'] else: a=rout['name'] if hasnote(rout['vars'][a]): ret['note']=rout['vars'][a]['note'] rout['vars'][a]['note']=['See elsewhere.'] ret['rname']=a ret['pydocsign'], ret['pydocsignout']=getpydocsign(a, rout) if iscomplexfunction(rout): ret['rctype']=""" #ifdef F2PY_CB_RETURNCOMPLEX #ctype# #else void #endif """ else: if hasnote(rout): ret['note']=rout['note'] rout['note']=['See elsewhere.'] nofargs=0 nofoptargs=0 if 'args' in rout and 'vars' in rout: for a in rout['args']: var=rout['vars'][a] if l_or(isintent_in, isintent_inout)(var): nofargs=nofargs+1 if isoptional(var): nofoptargs=nofoptargs+1 ret['maxnofargs']=repr(nofargs) ret['nofoptargs']=repr(nofoptargs) if hasnote(rout) and isfunction(rout) and 'result' in rout: ret['routnote']=rout['note'] rout['note']=['See elsewhere.'] return ret def common_sign2map(a, var): # obsolute ret={'varname':a} ret['ctype']=getctype(var) if isstringarray(var): ret['ctype']='char' if ret['ctype'] in c2capi_map: ret['atype']=c2capi_map[ret['ctype']] if ret['ctype'] in cformat_map: ret['showvalueformat']='%s'%(cformat_map[ret['ctype']]) if isarray(var): ret=dictappend(ret, getarrdims(a, var)) elif isstring(var): ret['size']=getstrlength(var) ret['rank']='1' ret['pydocsign'], ret['pydocsignout']=getpydocsign(a, var) if hasnote(var): ret['note']=var['note'] var['note']=['See elsewhere.'] ret['arrdocstr']=getarrdocsign(a, var) # for strings this returns 0-rank but actually is 1-rank return ret numpy-1.8.2/numpy/f2py/__init__.py0000664000175100017510000000225212370216242020165 0ustar vagrantvagrant00000000000000#!/usr/bin/env python from __future__ import division, absolute_import, print_function __all__ = ['run_main', 'compile', 'f2py_testing'] import os import sys import subprocess from . import f2py2e from . import f2py_testing from . import diagnose from .info import __doc__ run_main = f2py2e.run_main main = f2py2e.main def compile(source, modulename = 'untitled', extra_args = '', verbose = 1, source_fn = None ): ''' Build extension module from processing source with f2py. Read the source of this function for more information. ''' from numpy.distutils.exec_command import exec_command import tempfile if source_fn is None: f = tempfile.NamedTemporaryFile(suffix='.f') else: 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 test = Tester().test bench = Tester().bench numpy-1.8.2/numpy/f2py/f90mod_rules.py0000664000175100017510000002234112370216242020737 0ustar vagrantvagrant00000000000000#!/usr/bin/env python """ Build F90 module support for f2py2e. Copyright 2000 Pearu Peterson all rights reserved, Pearu Peterson Permission to use, modify, and distribute this software is given under the terms of the NumPy License. NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. $Date: 2005/02/03 19:30:23 $ Pearu Peterson """ from __future__ import division, absolute_import, print_function __version__ = "$Revision: 1.27 $"[10:-1] f2py_version='See `f2py -v`' import pprint import sys errmess=sys.stderr.write outmess=sys.stdout.write show=pprint.pprint from .auxfuncs import * import numpy as np from . import capi_maps from . import func2subr from .crackfortran import undo_rmbadname, undo_rmbadname1 options={} def findf90modules(m): if ismodule(m): return [m] if not hasbody(m): return [] ret = [] for b in m['body']: if ismodule(b): ret.append(b) else: ret=ret+findf90modules(b) return ret fgetdims1 = """\ external f2pysetdata logical ns integer r,i,j integer(%d) s(*) ns = .FALSE. if (allocated(d)) then do i=1,r if ((size(d,i).ne.s(i)).and.(s(i).ge.0)) then ns = .TRUE. end if end do if (ns) then deallocate(d) end if end if if ((.not.allocated(d)).and.(s(1).ge.1)) then""" % np.intp().itemsize fgetdims2="""\ end if if (allocated(d)) then do i=1,r s(i) = size(d,i) end do end if flag = 1 call f2pysetdata(d,allocated(d))""" fgetdims2_sa="""\ end if if (allocated(d)) then do i=1,r s(i) = size(d,i) end do !s(r) must be equal to len(d(1)) end if flag = 2 call f2pysetdata(d,allocated(d))""" def buildhooks(pymod): global fgetdims1, fgetdims2 from . import rules ret = {'f90modhooks':[],'initf90modhooks':[],'body':[], 'need':['F_FUNC', 'arrayobject.h'], 'separatorsfor':{'includes0':'\n','includes':'\n'}, 'docs':['"Fortran 90/95 modules:\\n"'], 'latexdoc':[]} fhooks=[''] def fadd(line,s=fhooks): s[0] = '%s\n %s'%(s[0], line) doc = [''] def dadd(line,s=doc): s[0] = '%s\n%s'%(s[0], line) for m in findf90modules(pymod): sargs, fargs, efargs, modobjs, notvars, onlyvars=[], [], [], [], [m['name']], [] sargsp = [] ifargs = [] mfargs = [] if hasbody(m): for b in m['body']: notvars.append(b['name']) for n in m['vars'].keys(): var = m['vars'][n] if (n not in notvars) and (not l_or(isintent_hide, isprivate)(var)): onlyvars.append(n) mfargs.append(n) outmess('\t\tConstructing F90 module support for "%s"...\n'%(m['name'])) if onlyvars: outmess('\t\t Variables: %s\n'%(' '.join(onlyvars))) chooks=[''] def cadd(line,s=chooks): s[0] = '%s\n%s'%(s[0], line) ihooks=[''] def iadd(line,s=ihooks): s[0] = '%s\n%s'%(s[0], line) vrd=capi_maps.modsign2map(m) cadd('static FortranDataDef f2py_%s_def[] = {'%(m['name'])) dadd('\\subsection{Fortran 90/95 module \\texttt{%s}}\n'%(m['name'])) if hasnote(m): note = m['note'] if isinstance(note, list): note='\n'.join(note) dadd(note) if onlyvars: dadd('\\begin{description}') for n in onlyvars: var = m['vars'][n] modobjs.append(n) ct = capi_maps.getctype(var) at = capi_maps.c2capi_map[ct] dm = capi_maps.getarrdims(n, var) dms = dm['dims'].replace('*', '-1').strip() dms = dms.replace(':', '-1').strip() if not dms: dms='-1' use_fgetdims2 = fgetdims2 if isstringarray(var): if 'charselector' in var and 'len' in var['charselector']: cadd('\t{"%s",%s,{{%s,%s}},%s},'\ %(undo_rmbadname1(n), dm['rank'], dms, var['charselector']['len'], at)) use_fgetdims2 = fgetdims2_sa else: cadd('\t{"%s",%s,{{%s}},%s},'%(undo_rmbadname1(n), dm['rank'], dms, at)) else: cadd('\t{"%s",%s,{{%s}},%s},'%(undo_rmbadname1(n), dm['rank'], dms, at)) dadd('\\item[]{{}\\verb@%s@{}}'%(capi_maps.getarrdocsign(n, var))) if hasnote(var): note = var['note'] if isinstance(note, list): note='\n'.join(note) dadd('--- %s'%(note)) if isallocatable(var): fargs.append('f2py_%s_getdims_%s'%(m['name'], n)) efargs.append(fargs[-1]) sargs.append('void (*%s)(int*,int*,void(*)(char*,int*),int*)'%(n)) sargsp.append('void (*)(int*,int*,void(*)(char*,int*),int*)') iadd('\tf2py_%s_def[i_f2py++].func = %s;'%(m['name'], n)) fadd('subroutine %s(r,s,f2pysetdata,flag)'%(fargs[-1])) fadd('use %s, only: d => %s\n'%(m['name'], undo_rmbadname1(n))) fadd('integer flag\n') fhooks[0]=fhooks[0]+fgetdims1 dms = eval('range(1,%s+1)'%(dm['rank'])) fadd(' allocate(d(%s))\n'%(','.join(['s(%s)'%i for i in dms]))) fhooks[0]=fhooks[0]+use_fgetdims2 fadd('end subroutine %s'%(fargs[-1])) else: fargs.append(n) sargs.append('char *%s'%(n)) sargsp.append('char*') iadd('\tf2py_%s_def[i_f2py++].data = %s;'%(m['name'], n)) if onlyvars: dadd('\\end{description}') if hasbody(m): for b in m['body']: if not isroutine(b): print('Skipping', b['block'], b['name']) continue modobjs.append('%s()'%(b['name'])) b['modulename'] = m['name'] api, wrap=rules.buildapi(b) if isfunction(b): fhooks[0]=fhooks[0]+wrap fargs.append('f2pywrap_%s_%s'%(m['name'], b['name'])) #efargs.append(fargs[-1]) ifargs.append(func2subr.createfuncwrapper(b, signature=1)) else: if wrap: fhooks[0]=fhooks[0]+wrap fargs.append('f2pywrap_%s_%s'%(m['name'], b['name'])) ifargs.append(func2subr.createsubrwrapper(b, signature=1)) else: fargs.append(b['name']) mfargs.append(fargs[-1]) #if '--external-modroutines' in options and options['--external-modroutines']: # outmess('\t\t\tapplying --external-modroutines for %s\n'%(b['name'])) # efargs.append(fargs[-1]) api['externroutines']=[] ar=applyrules(api, vrd) ar['docs']=[] ar['docshort']=[] ret=dictappend(ret, ar) cadd('\t{"%s",-1,{{-1}},0,NULL,(void *)f2py_rout_#modulename#_%s_%s,doc_f2py_rout_#modulename#_%s_%s},'%(b['name'], m['name'], b['name'], m['name'], b['name'])) sargs.append('char *%s'%(b['name'])) sargsp.append('char *') iadd('\tf2py_%s_def[i_f2py++].data = %s;'%(m['name'], b['name'])) cadd('\t{NULL}\n};\n') iadd('}') ihooks[0]='static void f2py_setup_%s(%s) {\n\tint i_f2py=0;%s'%(m['name'], ','.join(sargs), ihooks[0]) if '_' in m['name']: F_FUNC='F_FUNC_US' else: F_FUNC='F_FUNC' iadd('extern void %s(f2pyinit%s,F2PYINIT%s)(void (*)(%s));'\ %(F_FUNC, m['name'], m['name'].upper(), ','.join(sargsp))) iadd('static void f2py_init_%s(void) {'%(m['name'])) iadd('\t%s(f2pyinit%s,F2PYINIT%s)(f2py_setup_%s);'\ %(F_FUNC, m['name'], m['name'].upper(), m['name'])) iadd('}\n') ret['f90modhooks']=ret['f90modhooks']+chooks+ihooks ret['initf90modhooks']=['\tPyDict_SetItemString(d, "%s", PyFortranObject_New(f2py_%s_def,f2py_init_%s));'%(m['name'], m['name'], m['name'])]+ret['initf90modhooks'] fadd('') fadd('subroutine f2pyinit%s(f2pysetupfunc)'%(m['name'])) #fadd('use %s'%(m['name'])) if mfargs: for a in undo_rmbadname(mfargs): fadd('use %s, only : %s'%(m['name'], a)) if ifargs: fadd(' '.join(['interface']+ifargs)) fadd('end interface') fadd('external f2pysetupfunc') if efargs: for a in undo_rmbadname(efargs): fadd('external %s'%(a)) fadd('call f2pysetupfunc(%s)'%(','.join(undo_rmbadname(fargs)))) fadd('end subroutine f2pyinit%s\n'%(m['name'])) dadd('\n'.join(ret['latexdoc']).replace(r'\subsection{', r'\subsubsection{')) ret['latexdoc']=[] ret['docs'].append('"\t%s --- %s"'%(m['name'], ','.join(undo_rmbadname(modobjs)))) ret['routine_defs']='' ret['doc']=[] ret['docshort']=[] ret['latexdoc']=doc[0] if len(ret['docs'])<=1: ret['docs']='' return ret, fhooks[0] numpy-1.8.2/numpy/f2py/f2py2e.py0000775000175100017510000005335112370216243017547 0ustar vagrantvagrant00000000000000#!/usr/bin/env python """ f2py2e - Fortran to Python C/API generator. 2nd Edition. See __usage__ below. Copyright 1999--2011 Pearu Peterson all rights reserved, Pearu Peterson Permission to use, modify, and distribute this software is given under the terms of the NumPy License. NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. $Date: 2005/05/06 08:31:19 $ Pearu Peterson """ from __future__ import division, absolute_import, print_function import sys import os import pprint import re from . import crackfortran from . import rules from . import cb_rules from . import auxfuncs from . import cfuncs from . import f90mod_rules from . import __version__ f2py_version = __version__.version errmess = sys.stderr.write #outmess=sys.stdout.write show = pprint.pprint outmess = auxfuncs.outmess try: from numpy import __version__ as numpy_version except ImportError: numpy_version = 'N/A' __usage__ = """\ Usage: 1) To construct extension module sources: f2py [] [[[only:]||[skip:]] \\ ] \\ [: ...] 2) To compile fortran files and build extension modules: f2py -c [, , ] 3) To generate signature files: f2py -h ...< same options as in (1) > Description: This program generates a Python C/API file (module.c) that contains wrappers for given fortran functions so that they can be called from Python. With the -c option the corresponding extension modules are built. Options: --2d-numpy Use numpy.f2py tool with NumPy support. [DEFAULT] --2d-numeric Use f2py2e tool with Numeric support. --2d-numarray Use f2py2e tool with Numarray support. --g3-numpy Use 3rd generation f2py from the separate f2py package. [NOT AVAILABLE YET] -h Write signatures of the fortran routines to file and exit. You can then edit and use it instead of . If ==stdout then the signatures are printed to stdout. Names of fortran routines for which Python C/API functions will be generated. Default is all that are found in . Paths to fortran/signature files that will be scanned for in order to determine their signatures. skip: Ignore fortran functions that follow until `:'. only: Use only fortran functions that follow until `:'. : Get back to mode. -m Name of the module; f2py generates a Python/C API file module.c or extension module . Default is 'untitled'. --[no-]lower Do [not] lower the cases in . By default, --lower is assumed with -h key, and --no-lower without -h key. --build-dir All f2py generated files are created in . Default is tempfile.mkdtemp(). --overwrite-signature Overwrite existing signature file. --[no-]latex-doc Create (or not) module.tex. Default is --no-latex-doc. --short-latex Create 'incomplete' LaTeX document (without commands \\documentclass, \\tableofcontents, and \\begin{document}, \\end{document}). --[no-]rest-doc Create (or not) module.rst. Default is --no-rest-doc. --debug-capi Create C/API code that reports the state of the wrappers during runtime. Useful for debugging. --[no-]wrap-functions Create Fortran subroutine wrappers to Fortran 77 functions. --wrap-functions is default because it ensures maximum portability/compiler independence. --include-paths ::... Search include files from the given directories. --help-link [..] List system resources found by system_info.py. See also --link- switch below. [..] is optional list of resources names. E.g. try 'f2py --help-link lapack_opt'. --quiet Run quietly. --verbose Run with extra verbosity. -v Print f2py version ID and exit. numpy.distutils options (only effective with -c): --fcompiler= Specify Fortran compiler type by vendor --compiler= Specify C compiler type (as defined by distutils) --help-fcompiler List available Fortran compilers and exit --f77exec= Specify the path to F77 compiler --f90exec= Specify the path to F90 compiler --f77flags= Specify F77 compiler flags --f90flags= Specify F90 compiler flags --opt= Specify optimization flags --arch= Specify architecture specific optimization flags --noopt Compile without optimization --noarch Compile without arch-dependent optimization --debug Compile with debugging information Extra options (only effective with -c): --link- Link extension module with as defined by numpy.distutils/system_info.py. E.g. to link with optimized LAPACK libraries (vecLib on MacOSX, ATLAS elsewhere), use --link-lapack_opt. See also --help-link switch. -L/path/to/lib/ -l -D -U -I/path/to/include/ .o .so .a Using the following macros may be required with non-gcc Fortran compilers: -DPREPEND_FORTRAN -DNO_APPEND_FORTRAN -DUPPERCASE_FORTRAN -DUNDERSCORE_G77 When using -DF2PY_REPORT_ATEXIT, a performance report of F2PY interface is printed out at exit (platforms: Linux). When using -DF2PY_REPORT_ON_ARRAY_COPY=, a message is sent to stderr whenever F2PY interface makes a copy of an array. Integer sets the threshold for array sizes when a message should be shown. Version: %s numpy Version: %s Requires: Python 2.3 or higher. License: NumPy license (see LICENSE.txt in the NumPy source code) Copyright 1999 - 2011 Pearu Peterson all rights reserved. http://cens.ioc.ee/projects/f2py2e/"""%(f2py_version, numpy_version) def scaninputline(inputline): files, funcs, skipfuncs, onlyfuncs, debug=[], [], [], [], [] f, f2, f3, f4, f5, f6, f7, f8, f9=1, 0, 0, 0, 0, 0, 0, 0, 0 verbose = 1 dolc=-1 dolatexdoc = 0 dorestdoc = 0 wrapfuncs = 1 buildpath = '.' include_paths = [] signsfile, modulename=None, None options = {'buildpath':buildpath, 'coutput': None, 'f2py_wrapper_output': None} for l in inputline: if l=='': pass elif l=='only:': f=0 elif l=='skip:': f=-1 elif l==':': f=1;f4=0 elif l[:8]=='--debug-': debug.append(l[8:]) elif l=='--lower': dolc=1 elif l=='--build-dir': f6=1 elif l=='--no-lower': dolc=0 elif l=='--quiet': verbose = 0 elif l=='--verbose': verbose += 1 elif l=='--latex-doc': dolatexdoc=1 elif l=='--no-latex-doc': dolatexdoc=0 elif l=='--rest-doc': dorestdoc=1 elif l=='--no-rest-doc': dorestdoc=0 elif l=='--wrap-functions': wrapfuncs=1 elif l=='--no-wrap-functions': wrapfuncs=0 elif l=='--short-latex': options['shortlatex']=1 elif l=='--coutput': f8=1 elif l=='--f2py-wrapper-output': f9=1 elif l=='--overwrite-signature': options['h-overwrite']=1 elif l=='-h': f2=1 elif l=='-m': f3=1 elif l[:2]=='-v': print(f2py_version) sys.exit() elif l=='--show-compilers': f5=1 elif l[:8]=='-include': cfuncs.outneeds['userincludes'].append(l[9:-1]) cfuncs.userincludes[l[9:-1]]='#include '+l[8:] elif l[:15] in '--include_paths': outmess('f2py option --include_paths is deprecated, use --include-paths instead.\n') f7=1 elif l[:15] in '--include-paths': f7=1 elif l[0]=='-': errmess('Unknown option %s\n'%repr(l)) sys.exit() elif f2: f2=0;signsfile=l elif f3: f3=0;modulename=l elif f6: f6=0;buildpath=l elif f7: f7=0;include_paths.extend(l.split(os.pathsep)) elif f8: f8=0;options["coutput"]=l elif f9: f9=0;options["f2py_wrapper_output"]=l elif f==1: try: open(l).close() files.append(l) except IOError as detail: errmess('IOError: %s. Skipping file "%s".\n'%(str(detail), l)) elif f==-1: skipfuncs.append(l) elif f==0: onlyfuncs.append(l) if not f5 and not files and not modulename: print(__usage__) sys.exit() if not os.path.isdir(buildpath): if not verbose: outmess('Creating build directory %s'%(buildpath)) os.mkdir(buildpath) if signsfile: signsfile = os.path.join(buildpath, signsfile) if signsfile and os.path.isfile(signsfile) and 'h-overwrite' not in options: errmess('Signature file "%s" exists!!! Use --overwrite-signature to overwrite.\n'%(signsfile)) sys.exit() options['debug']=debug options['verbose']=verbose if dolc==-1 and not signsfile: options['do-lower']=0 else: options['do-lower']=dolc if modulename: options['module']=modulename if signsfile: options['signsfile']=signsfile if onlyfuncs: options['onlyfuncs']=onlyfuncs if skipfuncs: options['skipfuncs']=skipfuncs options['dolatexdoc'] = dolatexdoc options['dorestdoc'] = dorestdoc options['wrapfuncs'] = wrapfuncs options['buildpath']=buildpath options['include_paths']=include_paths return files, options def callcrackfortran(files, options): rules.options=options funcs=[] crackfortran.debug=options['debug'] crackfortran.verbose=options['verbose'] if 'module' in options: crackfortran.f77modulename=options['module'] if 'skipfuncs' in options: crackfortran.skipfuncs=options['skipfuncs'] if 'onlyfuncs' in options: crackfortran.onlyfuncs=options['onlyfuncs'] crackfortran.include_paths[:]=options['include_paths'] crackfortran.dolowercase=options['do-lower'] postlist=crackfortran.crackfortran(files) if 'signsfile' in options: outmess('Saving signatures to file "%s"\n'%(options['signsfile'])) pyf=crackfortran.crack2fortran(postlist) if options['signsfile'][-6:]=='stdout': sys.stdout.write(pyf) else: f=open(options['signsfile'], 'w') f.write(pyf) f.close() if options["coutput"] is None: for mod in postlist: mod["coutput"] = "%smodule.c" % mod["name"] else: for mod in postlist: mod["coutput"] = options["coutput"] if options["f2py_wrapper_output"] is None: for mod in postlist: mod["f2py_wrapper_output"] = "%s-f2pywrappers.f" % mod["name"] else: for mod in postlist: mod["f2py_wrapper_output"] = options["f2py_wrapper_output"] return postlist def buildmodules(lst): cfuncs.buildcfuncs() outmess('Building modules...\n') modules, mnames, isusedby=[], [], {} for i in range(len(lst)): if '__user__' in lst[i]['name']: cb_rules.buildcallbacks(lst[i]) else: if 'use' in lst[i]: for u in lst[i]['use'].keys(): if u not in isusedby: isusedby[u]=[] isusedby[u].append(lst[i]['name']) modules.append(lst[i]) mnames.append(lst[i]['name']) ret = {} for i in range(len(mnames)): if mnames[i] in isusedby: outmess('\tSkipping module "%s" which is used by %s.\n'%(mnames[i], ','.join(['"%s"'%s for s in isusedby[mnames[i]]]))) else: um=[] if 'use' in modules[i]: for u in modules[i]['use'].keys(): if u in isusedby and u in mnames: um.append(modules[mnames.index(u)]) else: outmess('\tModule "%s" uses nonexisting "%s" which will be ignored.\n'%(mnames[i], u)) ret[mnames[i]] = {} dict_append(ret[mnames[i]], rules.buildmodule(modules[i], um)) return ret def dict_append(d_out, d_in): for (k, v) in d_in.items(): if k not in d_out: d_out[k] = [] if isinstance(v, list): d_out[k] = d_out[k] + v else: d_out[k].append(v) def run_main(comline_list): """Run f2py as if string.join(comline_list,' ') is used as a command line. In case of using -h flag, return None. """ if sys.version_info[0] >= 3: import imp imp.reload(crackfortran) else: reload(crackfortran) f2pydir=os.path.dirname(os.path.abspath(cfuncs.__file__)) fobjhsrc = os.path.join(f2pydir, 'src', 'fortranobject.h') fobjcsrc = os.path.join(f2pydir, 'src', 'fortranobject.c') files, options=scaninputline(comline_list) auxfuncs.options=options postlist=callcrackfortran(files, options) isusedby={} for i in range(len(postlist)): if 'use' in postlist[i]: for u in postlist[i]['use'].keys(): if u not in isusedby: isusedby[u]=[] isusedby[u].append(postlist[i]['name']) for i in range(len(postlist)): if postlist[i]['block']=='python module' and '__user__' in postlist[i]['name']: if postlist[i]['name'] in isusedby: #if not quiet: outmess('Skipping Makefile build for module "%s" which is used by %s\n'%(postlist[i]['name'], ','.join(['"%s"'%s for s in isusedby[postlist[i]['name']]]))) if 'signsfile' in options: if options['verbose']>1: outmess('Stopping. Edit the signature file and then run f2py on the signature file: ') outmess('%s %s\n'%(os.path.basename(sys.argv[0]), options['signsfile'])) return for i in range(len(postlist)): if postlist[i]['block']!='python module': if 'python module' not in options: errmess('Tip: If your original code is Fortran source then you must use -m option.\n') raise TypeError('All blocks must be python module blocks but got %s'%(repr(postlist[i]['block']))) auxfuncs.debugoptions=options['debug'] f90mod_rules.options=options auxfuncs.wrapfuncs=options['wrapfuncs'] ret=buildmodules(postlist) for mn in ret.keys(): dict_append(ret[mn], {'csrc':fobjcsrc,'h':fobjhsrc}) return ret def filter_files(prefix,suffix,files,remove_prefix=None): """ Filter files by prefix and suffix. """ filtered, rest = [], [] match = re.compile(prefix+r'.*'+suffix+r'\Z').match if remove_prefix: ind = len(prefix) else: ind = 0 for file in [x.strip() for x in files]: if match(file): filtered.append(file[ind:]) else: rest.append(file) return filtered, rest def get_prefix(module): p = os.path.dirname(os.path.dirname(module.__file__)) return p def run_compile(): """ Do it all in one call! """ import tempfile i = sys.argv.index('-c') del sys.argv[i] remove_build_dir = 0 try: i = sys.argv.index('--build-dir') except ValueError: i=None if i is not None: build_dir = sys.argv[i+1] del sys.argv[i+1] del sys.argv[i] else: remove_build_dir = 1 build_dir = tempfile.mkdtemp() _reg1 = re.compile(r'[-][-]link[-]') sysinfo_flags = [_m for _m in sys.argv[1:] if _reg1.match(_m)] sys.argv = [_m for _m in sys.argv if _m not in sysinfo_flags] if sysinfo_flags: sysinfo_flags = [f[7:] for f in sysinfo_flags] _reg2 = re.compile(r'[-][-]((no[-]|)(wrap[-]functions|lower)|debug[-]capi|quiet)|[-]include') f2py_flags = [_m for _m in sys.argv[1:] if _reg2.match(_m)] sys.argv = [_m for _m in sys.argv if _m not in f2py_flags] f2py_flags2 = [] fl = 0 for a in sys.argv[1:]: if a in ['only:', 'skip:']: fl = 1 elif a==':': fl = 0 if fl or a==':': f2py_flags2.append(a) if f2py_flags2 and f2py_flags2[-1]!=':': f2py_flags2.append(':') f2py_flags.extend(f2py_flags2) sys.argv = [_m for _m in sys.argv if _m not in f2py_flags2] _reg3 = re.compile(r'[-][-]((f(90)?compiler([-]exec|)|compiler)=|help[-]compiler)') flib_flags = [_m for _m in sys.argv[1:] if _reg3.match(_m)] sys.argv = [_m for _m in sys.argv if _m not in flib_flags] _reg4 = re.compile(r'[-][-]((f(77|90)(flags|exec)|opt|arch)=|(debug|noopt|noarch|help[-]fcompiler))') fc_flags = [_m for _m in sys.argv[1:] if _reg4.match(_m)] sys.argv = [_m for _m in sys.argv if _m not in fc_flags] if 1: del_list = [] for s in flib_flags: v = '--fcompiler=' if s[:len(v)]==v: from numpy.distutils import fcompiler fcompiler.load_all_fcompiler_classes() allowed_keys = list(fcompiler.fcompiler_class.keys()) nv = ov = s[len(v):].lower() if ov not in allowed_keys: vmap = {} # XXX try: nv = vmap[ov] except KeyError: if ov not in vmap.values(): print('Unknown vendor: "%s"' % (s[len(v):])) nv = ov i = flib_flags.index(s) flib_flags[i] = '--fcompiler=' + nv continue for s in del_list: i = flib_flags.index(s) del flib_flags[i] assert len(flib_flags)<=2, repr(flib_flags) _reg5 = re.compile(r'[-][-](verbose)') setup_flags = [_m for _m in sys.argv[1:] if _reg5.match(_m)] sys.argv = [_m for _m in sys.argv if _m not in setup_flags] if '--quiet' in f2py_flags: setup_flags.append('--quiet') modulename = 'untitled' sources = sys.argv[1:] for optname in ['--include_paths', '--include-paths']: if optname in sys.argv: i = sys.argv.index (optname) f2py_flags.extend (sys.argv[i:i+2]) del sys.argv[i+1], sys.argv[i] sources = sys.argv[1:] if '-m' in sys.argv: i = sys.argv.index('-m') modulename = sys.argv[i+1] del sys.argv[i+1], sys.argv[i] sources = sys.argv[1:] else: from numpy.distutils.command.build_src import get_f2py_modulename pyf_files, sources = filter_files('', '[.]pyf([.]src|)', sources) sources = pyf_files + sources for f in pyf_files: modulename = get_f2py_modulename(f) if modulename: break extra_objects, sources = filter_files('', '[.](o|a|so)', sources) include_dirs, sources = filter_files('-I', '', sources, remove_prefix=1) library_dirs, sources = filter_files('-L', '', sources, remove_prefix=1) libraries, sources = filter_files('-l', '', sources, remove_prefix=1) undef_macros, sources = filter_files('-U', '', sources, remove_prefix=1) define_macros, sources = filter_files('-D', '', sources, remove_prefix=1) using_numarray = 0 using_numeric = 0 for i in range(len(define_macros)): name_value = define_macros[i].split('=', 1) if len(name_value)==1: name_value.append(None) if len(name_value)==2: define_macros[i] = tuple(name_value) else: print('Invalid use of -D:', name_value) from numpy.distutils.system_info import get_info num_include_dir = None num_info = {} #import numpy #n = 'numpy' #p = get_prefix(numpy) #from numpy.distutils.misc_util import get_numpy_include_dirs #num_info = {'include_dirs': get_numpy_include_dirs()} if num_info: include_dirs.extend(num_info.get('include_dirs', [])) from numpy.distutils.core import setup, Extension ext_args = {'name': modulename, 'sources': sources, 'include_dirs': include_dirs, 'library_dirs': library_dirs, 'libraries': libraries, 'define_macros': define_macros, 'undef_macros': undef_macros, 'extra_objects': extra_objects, 'f2py_options': f2py_flags, } if sysinfo_flags: from numpy.distutils.misc_util import dict_append for n in sysinfo_flags: i = get_info(n) if not i: outmess('No %s resources found in system'\ ' (try `f2py --help-link`)\n' % (repr(n))) dict_append(ext_args,**i) ext = Extension(**ext_args) sys.argv = [sys.argv[0]] + setup_flags sys.argv.extend(['build', '--build-temp', build_dir, '--build-base', build_dir, '--build-platlib', '.']) if fc_flags: sys.argv.extend(['config_fc']+fc_flags) if flib_flags: sys.argv.extend(['build_ext']+flib_flags) setup(ext_modules = [ext]) if remove_build_dir and os.path.exists(build_dir): import shutil outmess('Removing build directory %s\n'%(build_dir)) shutil.rmtree(build_dir) def main(): if '--help-link' in sys.argv[1:]: sys.argv.remove('--help-link') from numpy.distutils.system_info import show_all show_all() return if '-c' in sys.argv[1:]: run_compile() else: run_main(sys.argv[1:]) #if __name__ == "__main__": # main() # EOF numpy-1.8.2/numpy/f2py/crackfortran.py0000775000175100017510000034700012370216243021114 0ustar vagrantvagrant00000000000000#!/usr/bin/env python """ crackfortran --- read fortran (77,90) code and extract declaration information. Copyright 1999-2004 Pearu Peterson all rights reserved, Pearu Peterson Permission to use, modify, and distribute this software is given under the terms of the NumPy License. NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. $Date: 2005/09/27 07:13:49 $ Pearu Peterson Usage of crackfortran: ====================== Command line keys: -quiet,-verbose,-fix,-f77,-f90,-show,-h -m ,--ignore-contains Functions: crackfortran, crack2fortran The following Fortran statements/constructions are supported (or will be if needed): block data,byte,call,character,common,complex,contains,data, dimension,double complex,double precision,end,external,function, implicit,integer,intent,interface,intrinsic, logical,module,optional,parameter,private,public, program,real,(sequence?),subroutine,type,use,virtual, include,pythonmodule Note: 'virtual' is mapped to 'dimension'. Note: 'implicit integer (z) static (z)' is 'implicit static (z)' (this is minor bug). Note: code after 'contains' will be ignored until its scope ends. Note: 'common' statement is extended: dimensions are moved to variable definitions Note: f2py directive: f2py is read as Note: pythonmodule is introduced to represent Python module Usage: `postlist=crackfortran(files,funcs)` `postlist` contains declaration information read from the list of files `files`. `crack2fortran(postlist)` returns a fortran code to be saved to pyf-file `postlist` has the following structure: *** it is a list of dictionaries containing `blocks': B = {'block','body','vars','parent_block'[,'name','prefix','args','result', 'implicit','externals','interfaced','common','sortvars', 'commonvars','note']} B['block'] = 'interface' | 'function' | 'subroutine' | 'module' | 'program' | 'block data' | 'type' | 'pythonmodule' B['body'] --- list containing `subblocks' with the same structure as `blocks' B['parent_block'] --- dictionary of a parent block: C['body'][]['parent_block'] is C B['vars'] --- dictionary of variable definitions B['sortvars'] --- dictionary of variable definitions sorted by dependence (independent first) B['name'] --- name of the block (not if B['block']=='interface') B['prefix'] --- prefix string (only if B['block']=='function') B['args'] --- list of argument names if B['block']== 'function' | 'subroutine' B['result'] --- name of the return value (only if B['block']=='function') B['implicit'] --- dictionary {'a':,'b':...} | None B['externals'] --- list of variables being external B['interfaced'] --- list of variables being external and defined B['common'] --- dictionary of common blocks (list of objects) B['commonvars'] --- list of variables used in common blocks (dimensions are moved to variable definitions) B['from'] --- string showing the 'parents' of the current block B['use'] --- dictionary of modules used in current block: {:{['only':<0|1>],['map':{:,...}]}} B['note'] --- list of LaTeX comments on the block B['f2pyenhancements'] --- optional dictionary {'threadsafe':'','fortranname':, 'callstatement':|, 'callprotoargument':, 'usercode':|, 'pymethoddef:' } B['entry'] --- dictionary {entryname:argslist,..} B['varnames'] --- list of variable names given in the order of reading the Fortran code, useful for derived types. B['saved_interface'] --- a string of scanned routine signature, defines explicit interface *** Variable definition is a dictionary D = B['vars'][] = {'typespec'[,'attrspec','kindselector','charselector','=','typename']} D['typespec'] = 'byte' | 'character' | 'complex' | 'double complex' | 'double precision' | 'integer' | 'logical' | 'real' | 'type' D['attrspec'] --- list of attributes (e.g. 'dimension()', 'external','intent(in|out|inout|hide|c|callback|cache|aligned4|aligned8|aligned16)', 'optional','required', etc) K = D['kindselector'] = {['*','kind']} (only if D['typespec'] = 'complex' | 'integer' | 'logical' | 'real' ) C = D['charselector'] = {['*','len','kind']} (only if D['typespec']=='character') D['='] --- initialization expression string D['typename'] --- name of the type if D['typespec']=='type' D['dimension'] --- list of dimension bounds D['intent'] --- list of intent specifications D['depend'] --- list of variable names on which current variable depends on D['check'] --- list of C-expressions; if C-expr returns zero, exception is raised D['note'] --- list of LaTeX comments on the variable *** Meaning of kind/char selectors (few examples): D['typespec>']*K['*'] D['typespec'](kind=K['kind']) character*C['*'] character(len=C['len'],kind=C['kind']) (see also fortran type declaration statement formats below) Fortran 90 type declaration statement format (F77 is subset of F90) ==================================================================== (Main source: IBM XL Fortran 5.1 Language Reference Manual) type declaration = [[]::] = byte | character[] | complex[] | double complex | double precision | integer[] | logical[] | real[] | type() = * | ([len=][,[kind=]]) | (kind=[,len=]) = * | ([kind=]) = comma separated list of attributes. Only the following attributes are used in building up the interface: external (parameter --- affects '=' key) optional intent Other attributes are ignored. = in | out | inout = comma separated list of dimension bounds. = [[*][()] | [()]*] [// | =] [,] In addition, the following attributes are used: check,depend,note TODO: * Apply 'parameter' attribute (e.g. 'integer parameter :: i=2' 'real x(i)' -> 'real x(2)') The above may be solved by creating appropriate preprocessor program, for example. """ from __future__ import division, absolute_import, print_function import sys import string import fileinput import re import pprint import os import copy import platform from . import __version__ from .auxfuncs import * f2py_version = __version__.version # Global flags: strictf77=1 # Ignore `!' comments unless line[0]=='!' sourcecodeform='fix' # 'fix','free' quiet=0 # Be verbose if 0 (Obsolete: not used any more) verbose=1 # Be quiet if 0, extra verbose if > 1. tabchar=4*' ' pyffilename='' f77modulename='' skipemptyends=0 # for old F77 programs without 'program' statement ignorecontains=1 dolowercase=1 debug=[] ## do_analyze = 1 ###### global variables ## use reload(crackfortran) to reset these variables groupcounter=0 grouplist={groupcounter:[]} neededmodule=-1 expectbegin=1 skipblocksuntil=-1 usermodules=[] f90modulevars={} gotnextfile=1 filepositiontext='' currentfilename='' skipfunctions=[] skipfuncs=[] onlyfuncs=[] include_paths=[] previous_context = None ###### Some helper functions def show(o,f=0):pprint.pprint(o) errmess=sys.stderr.write def outmess(line,flag=1): global filepositiontext if not verbose: return if not quiet: if flag:sys.stdout.write(filepositiontext) sys.stdout.write(line) re._MAXCACHE=50 defaultimplicitrules={} for c in "abcdefghopqrstuvwxyz$_": defaultimplicitrules[c]={'typespec':'real'} for c in "ijklmn": defaultimplicitrules[c]={'typespec':'integer'} del c badnames={} invbadnames={} for n in ['int', 'double', 'float', 'char', 'short', 'long', 'void', 'case', 'while', 'return', 'signed', 'unsigned', 'if', 'for', 'typedef', 'sizeof', 'union', 'struct', 'static', 'register', 'new', 'break', 'do', 'goto', 'switch', 'continue', 'else', 'inline', 'extern', 'delete', 'const', 'auto', 'len', 'rank', 'shape', 'index', 'slen', 'size', '_i', 'max', 'min', 'flen', 'fshape', 'string', 'complex_double', 'float_double', 'stdin', 'stderr', 'stdout', 'type', 'default']: badnames[n]=n+'_bn' invbadnames[n+'_bn']=n def rmbadname1(name): if name in badnames: errmess('rmbadname1: Replacing "%s" with "%s".\n'%(name, badnames[name])) return badnames[name] return name def rmbadname(names): return [rmbadname1(_m) for _m in names] def undo_rmbadname1(name): if name in invbadnames: errmess('undo_rmbadname1: Replacing "%s" with "%s".\n'\ %(name, invbadnames[name])) return invbadnames[name] return name def undo_rmbadname(names): return [undo_rmbadname1(_m) for _m in names] def getextension(name): i=name.rfind('.') if i==-1: return '' if '\\' in name[i:]: return '' if '/' in name[i:]: return '' return name[i+1:] is_f_file = re.compile(r'.*[.](for|ftn|f77|f)\Z', re.I).match _has_f_header = re.compile(r'-[*]-\s*fortran\s*-[*]-', re.I).search _has_f90_header = re.compile(r'-[*]-\s*f90\s*-[*]-', re.I).search _has_fix_header = re.compile(r'-[*]-\s*fix\s*-[*]-', re.I).search _free_f90_start = re.compile(r'[^c*]\s*[^\s\d\t]', re.I).match def is_free_format(file): """Check if file is in free format Fortran.""" # f90 allows both fixed and free format, assuming fixed unless # signs of free format are detected. result = 0 f = open(file, 'r') line = f.readline() n = 15 # the number of non-comment lines to scan for hints if _has_f_header(line): n = 0 elif _has_f90_header(line): n = 0 result = 1 while n>0 and line: if line[0]!='!' and line.strip(): n -= 1 if (line[0]!='\t' and _free_f90_start(line[:5])) or line[-2:-1]=='&': result = 1 break line = f.readline() f.close() return result ####### Read fortran (77,90) code def readfortrancode(ffile,dowithline=show,istop=1): """ Read fortran codes from files and 1) Get rid of comments, line continuations, and empty lines; lower cases. 2) Call dowithline(line) on every line. 3) Recursively call itself when statement \"include ''\" is met. """ global gotnextfile, filepositiontext, currentfilename, sourcecodeform, strictf77,\ beginpattern, quiet, verbose, dolowercase, include_paths if not istop: saveglobals=gotnextfile, filepositiontext, currentfilename, sourcecodeform, strictf77,\ beginpattern, quiet, verbose, dolowercase if ffile==[]: return localdolowercase = dolowercase cont=0 finalline='' ll='' commentline=re.compile(r'(?P([^"]*["][^"]*["][^"!]*|[^\']*\'[^\']*\'[^\'!]*|[^!\'"]*))!{1}(?P.*)') includeline=re.compile(r'\s*include\s*(\'|")(?P[^\'"]*)(\'|")', re.I) cont1=re.compile(r'(?P.*)&\s*\Z') cont2=re.compile(r'(\s*&|)(?P.*)') mline_mark = re.compile(r".*?'''") if istop: dowithline('', -1) ll, l1='', '' spacedigits=[' '] + [str(_m) for _m in range(10)] filepositiontext='' fin=fileinput.FileInput(ffile) while True: l=fin.readline() if not l: break if fin.isfirstline(): filepositiontext='' currentfilename=fin.filename() gotnextfile=1 l1=l strictf77=0 sourcecodeform='fix' ext = os.path.splitext(currentfilename)[1] if is_f_file(currentfilename) and \ not (_has_f90_header(l) or _has_fix_header(l)): strictf77=1 elif is_free_format(currentfilename) and not _has_fix_header(l): sourcecodeform='free' if strictf77: beginpattern=beginpattern77 else: beginpattern=beginpattern90 outmess('\tReading file %s (format:%s%s)\n'\ %(repr(currentfilename), sourcecodeform, strictf77 and ',strict' or '')) l=l.expandtabs().replace('\xa0', ' ') while not l=='': # Get rid of newline characters if l[-1] not in "\n\r\f": break l=l[:-1] if not strictf77: r=commentline.match(l) if r: l=r.group('line')+' ' # Strip comments starting with `!' rl=r.group('rest') if rl[:4].lower()=='f2py': # f2py directive l = l + 4*' ' r=commentline.match(rl[4:]) if r: l=l+r.group('line') else: l = l + rl[4:] if l.strip()=='': # Skip empty line cont=0 continue if sourcecodeform=='fix': if l[0] in ['*', 'c', '!', 'C', '#']: if l[1:5].lower()=='f2py': # f2py directive l=' '+l[5:] else: # Skip comment line cont=0 continue elif strictf77: if len(l)>72: l=l[:72] if not (l[0] in spacedigits): raise Exception('readfortrancode: Found non-(space,digit) char ' 'in the first column.\n\tAre you sure that ' 'this code is in fix form?\n\tline=%s' % repr(l)) if (not cont or strictf77) and (len(l)>5 and not l[5]==' '): # Continuation of a previous line ll=ll+l[6:] finalline='' origfinalline='' else: if not strictf77: # F90 continuation r=cont1.match(l) if r: l=r.group('line') # Continuation follows .. if cont: ll=ll+cont2.match(l).group('line') finalline='' origfinalline='' else: l=' '+l[5:] # clean up line beginning from possible digits. if localdolowercase: finalline=ll.lower() else: finalline=ll origfinalline=ll ll=l cont=(r is not None) else: l=' '+l[5:] # clean up line beginning from possible digits. if localdolowercase: finalline=ll.lower() else: finalline=ll origfinalline =ll ll=l elif sourcecodeform=='free': if not cont and ext=='.pyf' and mline_mark.match(l): l = l + '\n' while True: lc = fin.readline() if not lc: errmess('Unexpected end of file when reading multiline\n') break l = l + lc if mline_mark.match(lc): break l = l.rstrip() r=cont1.match(l) if r: l=r.group('line') # Continuation follows .. if cont: ll=ll+cont2.match(l).group('line') finalline='' origfinalline='' else: if localdolowercase: finalline=ll.lower() else: finalline=ll origfinalline =ll ll=l cont=(r is not None) else: raise ValueError("Flag sourcecodeform must be either 'fix' or 'free': %s"%repr(sourcecodeform)) filepositiontext='Line #%d in %s:"%s"\n\t' % (fin.filelineno()-1, currentfilename, l1) m=includeline.match(origfinalline) if m: fn=m.group('name') if os.path.isfile(fn): readfortrancode(fn, dowithline=dowithline, istop=0) else: include_dirs = [os.path.dirname(currentfilename)] + include_paths foundfile = 0 for inc_dir in include_dirs: fn1 = os.path.join(inc_dir, fn) if os.path.isfile(fn1): foundfile = 1 readfortrancode(fn1, dowithline=dowithline, istop=0) break if not foundfile: outmess('readfortrancode: could not find include file %s in %s. Ignoring.\n'%(repr(fn), os.pathsep.join(include_dirs))) else: dowithline(finalline) l1=ll if localdolowercase: finalline=ll.lower() else: finalline=ll origfinalline = ll filepositiontext='Line #%d in %s:"%s"\n\t' % (fin.filelineno()-1, currentfilename, l1) m=includeline.match(origfinalline) if m: fn=m.group('name') if os.path.isfile(fn): readfortrancode(fn, dowithline=dowithline, istop=0) else: include_dirs = [os.path.dirname(currentfilename)] + include_paths foundfile = 0 for inc_dir in include_dirs: fn1 = os.path.join(inc_dir, fn) if os.path.isfile(fn1): foundfile = 1 readfortrancode(fn1, dowithline=dowithline, istop=0) break if not foundfile: outmess('readfortrancode: could not find include file %s in %s. Ignoring.\n'%(repr(fn), os.pathsep.join(include_dirs))) else: dowithline(finalline) filepositiontext='' fin.close() if istop: dowithline('', 1) else: gotnextfile, filepositiontext, currentfilename, sourcecodeform, strictf77,\ beginpattern, quiet, verbose, dolowercase=saveglobals ########### Crack line beforethisafter=r'\s*(?P%s(?=\s*(\b(%s)\b)))'+ \ r'\s*(?P(\b(%s)\b))'+ \ r'\s*(?P%s)\s*\Z' ## fortrantypes='character|logical|integer|real|complex|double\s*(precision\s*(complex|)|complex)|type(?=\s*\([\w\s,=(*)]*\))|byte' typespattern=re.compile(beforethisafter%('', fortrantypes, fortrantypes, '.*'), re.I), 'type' typespattern4implicit=re.compile(beforethisafter%('', fortrantypes+'|static|automatic|undefined', fortrantypes+'|static|automatic|undefined', '.*'), re.I) # functionpattern=re.compile(beforethisafter%('([a-z]+[\w\s(=*+-/)]*?|)', 'function', 'function', '.*'), re.I), 'begin' subroutinepattern=re.compile(beforethisafter%('[a-z\s]*?', 'subroutine', 'subroutine', '.*'), re.I), 'begin' #modulepattern=re.compile(beforethisafter%('[a-z\s]*?','module','module','.*'),re.I),'begin' # groupbegins77=r'program|block\s*data' beginpattern77=re.compile(beforethisafter%('', groupbegins77, groupbegins77, '.*'), re.I), 'begin' groupbegins90=groupbegins77+r'|module(?!\s*procedure)|python\s*module|interface|type(?!\s*\()' beginpattern90=re.compile(beforethisafter%('', groupbegins90, groupbegins90, '.*'), re.I), 'begin' groupends=r'end|endprogram|endblockdata|endmodule|endpythonmodule|endinterface' endpattern=re.compile(beforethisafter%('', groupends, groupends, '[\w\s]*'), re.I), 'end' #endifs='end\s*(if|do|where|select|while|forall)' endifs='(end\s*(if|do|where|select|while|forall))|(module\s*procedure)' endifpattern=re.compile(beforethisafter%('[\w]*?', endifs, endifs, '[\w\s]*'), re.I), 'endif' # implicitpattern=re.compile(beforethisafter%('', 'implicit', 'implicit', '.*'), re.I), 'implicit' dimensionpattern=re.compile(beforethisafter%('', 'dimension|virtual', 'dimension|virtual', '.*'), re.I), 'dimension' externalpattern=re.compile(beforethisafter%('', 'external', 'external', '.*'), re.I), 'external' optionalpattern=re.compile(beforethisafter%('', 'optional', 'optional', '.*'), re.I), 'optional' requiredpattern=re.compile(beforethisafter%('', 'required', 'required', '.*'), re.I), 'required' publicpattern=re.compile(beforethisafter%('', 'public', 'public', '.*'), re.I), 'public' privatepattern=re.compile(beforethisafter%('', 'private', 'private', '.*'), re.I), 'private' intrisicpattern=re.compile(beforethisafter%('', 'intrisic', 'intrisic', '.*'), re.I), 'intrisic' intentpattern=re.compile(beforethisafter%('', 'intent|depend|note|check', 'intent|depend|note|check', '\s*\(.*?\).*'), re.I), 'intent' parameterpattern=re.compile(beforethisafter%('', 'parameter', 'parameter', '\s*\(.*'), re.I), 'parameter' datapattern=re.compile(beforethisafter%('', 'data', 'data', '.*'), re.I), 'data' callpattern=re.compile(beforethisafter%('', 'call', 'call', '.*'), re.I), 'call' entrypattern=re.compile(beforethisafter%('', 'entry', 'entry', '.*'), re.I), 'entry' callfunpattern=re.compile(beforethisafter%('', 'callfun', 'callfun', '.*'), re.I), 'callfun' commonpattern=re.compile(beforethisafter%('', 'common', 'common', '.*'), re.I), 'common' usepattern=re.compile(beforethisafter%('', 'use', 'use', '.*'), re.I), 'use' containspattern=re.compile(beforethisafter%('', 'contains', 'contains', ''), re.I), 'contains' formatpattern=re.compile(beforethisafter%('', 'format', 'format', '.*'), re.I), 'format' ## Non-fortran and f2py-specific statements f2pyenhancementspattern=re.compile(beforethisafter%('', 'threadsafe|fortranname|callstatement|callprotoargument|usercode|pymethoddef', 'threadsafe|fortranname|callstatement|callprotoargument|usercode|pymethoddef', '.*'), re.I|re.S), 'f2pyenhancements' multilinepattern = re.compile(r"\s*(?P''')(?P.*?)(?P''')\s*\Z", re.S), 'multiline' ## def _simplifyargs(argsline): a = [] for n in markoutercomma(argsline).split('@,@'): for r in '(),': n = n.replace(r, '_') a.append(n) return ','.join(a) crackline_re_1 = re.compile(r'\s*(?P\b[a-z]+[\w]*\b)\s*[=].*', re.I) def crackline(line,reset=0): """ reset=-1 --- initialize reset=0 --- crack the line reset=1 --- final check if mismatch of blocks occured Cracked data is saved in grouplist[0]. """ global beginpattern, groupcounter, groupname, groupcache, grouplist, gotnextfile,\ filepositiontext, currentfilename, neededmodule, expectbegin, skipblocksuntil,\ skipemptyends, previous_context if ';' in line and not (f2pyenhancementspattern[0].match(line) or multilinepattern[0].match(line)): for l in line.split(';'): assert reset==0, repr(reset) # XXX: non-zero reset values need testing crackline(l, reset) return if reset<0: groupcounter=0 groupname={groupcounter:''} groupcache={groupcounter:{}} grouplist={groupcounter:[]} groupcache[groupcounter]['body']=[] groupcache[groupcounter]['vars']={} groupcache[groupcounter]['block']='' groupcache[groupcounter]['name']='' neededmodule=-1 skipblocksuntil=-1 return if reset>0: fl=0 if f77modulename and neededmodule==groupcounter: fl=2 while groupcounter>fl: outmess('crackline: groupcounter=%s groupname=%s\n'%(repr(groupcounter), repr(groupname))) outmess('crackline: Mismatch of blocks encountered. Trying to fix it by assuming "end" statement.\n') grouplist[groupcounter-1].append(groupcache[groupcounter]) grouplist[groupcounter-1][-1]['body']=grouplist[groupcounter] del grouplist[groupcounter] groupcounter=groupcounter-1 if f77modulename and neededmodule==groupcounter: grouplist[groupcounter-1].append(groupcache[groupcounter]) grouplist[groupcounter-1][-1]['body']=grouplist[groupcounter] del grouplist[groupcounter] groupcounter=groupcounter-1 # end interface grouplist[groupcounter-1].append(groupcache[groupcounter]) grouplist[groupcounter-1][-1]['body']=grouplist[groupcounter] del grouplist[groupcounter] groupcounter=groupcounter-1 # end module neededmodule=-1 return if line=='': return flag=0 for pat in [dimensionpattern, externalpattern, intentpattern, optionalpattern, requiredpattern, parameterpattern, datapattern, publicpattern, privatepattern, intrisicpattern, endifpattern, endpattern, formatpattern, beginpattern, functionpattern, subroutinepattern, implicitpattern, typespattern, commonpattern, callpattern, usepattern, containspattern, entrypattern, f2pyenhancementspattern, multilinepattern ]: m = pat[0].match(line) if m: break flag=flag+1 if not m: re_1 = crackline_re_1 if 0<=skipblocksuntil<=groupcounter:return if 'externals' in groupcache[groupcounter]: for name in groupcache[groupcounter]['externals']: if name in invbadnames: name=invbadnames[name] if 'interfaced' in groupcache[groupcounter] and name in groupcache[groupcounter]['interfaced']: continue m1=re.match(r'(?P[^"]*)\b%s\b\s*@\(@(?P[^@]*)@\)@.*\Z'%name, markouterparen(line), re.I) if m1: m2 = re_1.match(m1.group('before')) a = _simplifyargs(m1.group('args')) if m2: line='callfun %s(%s) result (%s)'%(name, a, m2.group('result')) else: line='callfun %s(%s)'%(name, a) m = callfunpattern[0].match(line) if not m: outmess('crackline: could not resolve function call for line=%s.\n'%repr(line)) return analyzeline(m, 'callfun', line) return if verbose>1 or (verbose==1 and currentfilename.lower().endswith('.pyf')): previous_context = None outmess('crackline:%d: No pattern for line\n'%(groupcounter)) return elif pat[1]=='end': if 0<=skipblocksuntil(@\(@.*?@\)@|[*][\d*]+|[*]\s*@\(@.*?@\)@|))(?P.*)\Z', re.I) nameargspattern=re.compile(r'\s*(?P\b[\w$]+\b)\s*(@\(@\s*(?P[\w\s,]*)\s*@\)@|)\s*((result(\s*@\(@\s*(?P\b[\w$]+\b)\s*@\)@|))|(bind\s*@\(@\s*(?P.*)\s*@\)@))*\s*\Z', re.I) callnameargspattern=re.compile(r'\s*(?P\b[\w$]+\b)\s*@\(@\s*(?P.*)\s*@\)@\s*\Z', re.I) real16pattern = re.compile(r'([-+]?(?:\d+(?:\.\d*)?|\d*\.\d+))[dD]((?:[-+]?\d+)?)') real8pattern = re.compile(r'([-+]?((?:\d+(?:\.\d*)?|\d*\.\d+))[eE]((?:[-+]?\d+)?)|(\d+\.\d*))') _intentcallbackpattern = re.compile(r'intent\s*\(.*?\bcallback\b', re.I) def _is_intent_callback(vdecl): for a in vdecl.get('attrspec', []): if _intentcallbackpattern.match(a): return 1 return 0 def _resolvenameargspattern(line): line = markouterparen(line) m1=nameargspattern.match(line) if m1: return m1.group('name'), m1.group('args'), m1.group('result'), m1.group('bind') m1=callnameargspattern.match(line) if m1: return m1.group('name'), m1.group('args'), None, None return None, [], None, None def analyzeline(m, case, line): global groupcounter, groupname, groupcache, grouplist, filepositiontext,\ currentfilename, f77modulename, neededinterface, neededmodule, expectbegin,\ gotnextfile, previous_context block=m.group('this') if case != 'multiline': previous_context = None if expectbegin and case not in ['begin', 'call', 'callfun', 'type'] \ and not skipemptyends and groupcounter<1: newname=os.path.basename(currentfilename).split('.')[0] outmess('analyzeline: no group yet. Creating program group with name "%s".\n'%newname) gotnextfile=0 groupcounter=groupcounter+1 groupname[groupcounter]='program' groupcache[groupcounter]={} grouplist[groupcounter]=[] groupcache[groupcounter]['body']=[] groupcache[groupcounter]['vars']={} groupcache[groupcounter]['block']='program' groupcache[groupcounter]['name']=newname groupcache[groupcounter]['from']='fromsky' expectbegin=0 if case in ['begin', 'call', 'callfun']: # Crack line => block,name,args,result block = block.lower() if re.match(r'block\s*data', block, re.I): block='block data' if re.match(r'python\s*module', block, re.I): block='python module' name, args, result, bind = _resolvenameargspattern(m.group('after')) if name is None: if block=='block data': name = '_BLOCK_DATA_' else: name = '' if block not in ['interface', 'block data']: outmess('analyzeline: No name/args pattern found for line.\n') previous_context = (block, name, groupcounter) if args: args=rmbadname([x.strip() for x in markoutercomma(args).split('@,@')]) else: args=[] if '' in args: while '' in args: args.remove('') outmess('analyzeline: argument list is malformed (missing argument).\n') # end of crack line => block,name,args,result needmodule=0 needinterface=0 if case in ['call', 'callfun']: needinterface=1 if 'args' not in groupcache[groupcounter]: return if name not in groupcache[groupcounter]['args']: return for it in grouplist[groupcounter]: if it['name']==name: return if name in groupcache[groupcounter]['interfaced']: return block={'call':'subroutine','callfun':'function'}[case] if f77modulename and neededmodule==-1 and groupcounter<=1: neededmodule=groupcounter+2 needmodule=1 if block != 'interface': needinterface=1 # Create new block(s) groupcounter=groupcounter+1 groupcache[groupcounter]={} grouplist[groupcounter]=[] if needmodule: if verbose>1: outmess('analyzeline: Creating module block %s\n'%repr(f77modulename), 0) groupname[groupcounter]='module' groupcache[groupcounter]['block']='python module' groupcache[groupcounter]['name']=f77modulename groupcache[groupcounter]['from']='' groupcache[groupcounter]['body']=[] groupcache[groupcounter]['externals']=[] groupcache[groupcounter]['interfaced']=[] groupcache[groupcounter]['vars']={} groupcounter=groupcounter+1 groupcache[groupcounter]={} grouplist[groupcounter]=[] if needinterface: if verbose>1: outmess('analyzeline: Creating additional interface block (groupcounter=%s).\n' % (groupcounter), 0) groupname[groupcounter]='interface' groupcache[groupcounter]['block']='interface' groupcache[groupcounter]['name']='unknown_interface' groupcache[groupcounter]['from']='%s:%s'%(groupcache[groupcounter-1]['from'], groupcache[groupcounter-1]['name']) groupcache[groupcounter]['body']=[] groupcache[groupcounter]['externals']=[] groupcache[groupcounter]['interfaced']=[] groupcache[groupcounter]['vars']={} groupcounter=groupcounter+1 groupcache[groupcounter]={} grouplist[groupcounter]=[] groupname[groupcounter]=block groupcache[groupcounter]['block']=block if not name: name='unknown_'+block groupcache[groupcounter]['prefix']=m.group('before') groupcache[groupcounter]['name']=rmbadname1(name) groupcache[groupcounter]['result']=result if groupcounter==1: groupcache[groupcounter]['from']=currentfilename else: if f77modulename and groupcounter==3: groupcache[groupcounter]['from']='%s:%s'%(groupcache[groupcounter-1]['from'], currentfilename) else: groupcache[groupcounter]['from']='%s:%s'%(groupcache[groupcounter-1]['from'], groupcache[groupcounter-1]['name']) for k in list(groupcache[groupcounter].keys()): if not groupcache[groupcounter][k]: del groupcache[groupcounter][k] groupcache[groupcounter]['args']=args groupcache[groupcounter]['body']=[] groupcache[groupcounter]['externals']=[] groupcache[groupcounter]['interfaced']=[] groupcache[groupcounter]['vars']={} groupcache[groupcounter]['entry']={} # end of creation if block=='type': groupcache[groupcounter]['varnames'] = [] if case in ['call', 'callfun']: # set parents variables if name not in groupcache[groupcounter-2]['externals']: groupcache[groupcounter-2]['externals'].append(name) groupcache[groupcounter]['vars']=copy.deepcopy(groupcache[groupcounter-2]['vars']) #try: del groupcache[groupcounter]['vars'][groupcache[groupcounter-2]['name']] #except: pass try: del groupcache[groupcounter]['vars'][name][groupcache[groupcounter]['vars'][name]['attrspec'].index('external')] except: pass if block in ['function', 'subroutine']: # set global attributes try: groupcache[groupcounter]['vars'][name]=appenddecl(groupcache[groupcounter]['vars'][name], groupcache[groupcounter-2]['vars']['']) except: pass if case=='callfun': # return type if result and result in groupcache[groupcounter]['vars']: if not name==result: groupcache[groupcounter]['vars'][name]=appenddecl(groupcache[groupcounter]['vars'][name], groupcache[groupcounter]['vars'][result]) #if groupcounter>1: # name is interfaced try: groupcache[groupcounter-2]['interfaced'].append(name) except: pass if block=='function': t=typespattern[0].match(m.group('before')+' '+name) if t: typespec, selector, attr, edecl=cracktypespec0(t.group('this'), t.group('after')) updatevars(typespec, selector, attr, edecl) if case in ['call', 'callfun']: grouplist[groupcounter-1].append(groupcache[groupcounter]) grouplist[groupcounter-1][-1]['body']=grouplist[groupcounter] del grouplist[groupcounter] groupcounter=groupcounter-1 # end routine grouplist[groupcounter-1].append(groupcache[groupcounter]) grouplist[groupcounter-1][-1]['body']=grouplist[groupcounter] del grouplist[groupcounter] groupcounter=groupcounter-1 # end interface elif case=='entry': name, args, result, bind=_resolvenameargspattern(m.group('after')) if name is not None: if args: args=rmbadname([x.strip() for x in markoutercomma(args).split('@,@')]) else: args=[] assert result is None, repr(result) groupcache[groupcounter]['entry'][name] = args previous_context = ('entry', name, groupcounter) elif case=='type': typespec, selector, attr, edecl=cracktypespec0(block, m.group('after')) last_name = updatevars(typespec, selector, attr, edecl) if last_name is not None: previous_context = ('variable', last_name, groupcounter) elif case in ['dimension', 'intent', 'optional', 'required', 'external', 'public', 'private', 'intrisic']: edecl=groupcache[groupcounter]['vars'] ll=m.group('after').strip() i=ll.find('::') if i<0 and case=='intent': i=markouterparen(ll).find('@)@')-2 ll=ll[:i+1]+'::'+ll[i+1:] i=ll.find('::') if ll[i:]=='::' and 'args' in groupcache[groupcounter]: outmess('All arguments will have attribute %s%s\n'%(m.group('this'), ll[:i])) ll = ll + ','.join(groupcache[groupcounter]['args']) if i<0:i=0;pl='' else: pl=ll[:i].strip();ll=ll[i+2:] ch = markoutercomma(pl).split('@,@') if len(ch)>1: pl = ch[0] outmess('analyzeline: cannot handle multiple attributes without type specification. Ignoring %r.\n' % (','.join(ch[1:]))) last_name = None for e in [x.strip() for x in markoutercomma(ll).split('@,@')]: m1=namepattern.match(e) if not m1: if case in ['public', 'private']: k='' else: print(m.groupdict()) outmess('analyzeline: no name pattern found in %s statement for %s. Skipping.\n'%(case, repr(e))) continue else: k=rmbadname1(m1.group('name')) if k not in edecl: edecl[k]={} if case=='dimension': ap=case+m1.group('after') if case=='intent': ap=m.group('this')+pl if _intentcallbackpattern.match(ap): if k not in groupcache[groupcounter]['args']: if groupcounter>1: if '__user__' not in groupcache[groupcounter-2]['name']: outmess('analyzeline: missing __user__ module (could be nothing)\n') if k!=groupcache[groupcounter]['name']: # fixes ticket 1693 outmess('analyzeline: appending intent(callback) %s'\ ' to %s arguments\n' % (k, groupcache[groupcounter]['name'])) groupcache[groupcounter]['args'].append(k) else: errmess('analyzeline: intent(callback) %s is ignored' % (k)) else: errmess('analyzeline: intent(callback) %s is already'\ ' in argument list' % (k)) if case in ['optional', 'required', 'public', 'external', 'private', 'intrisic']: ap=case if 'attrspec' in edecl[k]: edecl[k]['attrspec'].append(ap) else: edecl[k]['attrspec']=[ap] if case=='external': if groupcache[groupcounter]['block']=='program': outmess('analyzeline: ignoring program arguments\n') continue if k not in groupcache[groupcounter]['args']: #outmess('analyzeline: ignoring external %s (not in arguments list)\n'%(`k`)) continue if 'externals' not in groupcache[groupcounter]: groupcache[groupcounter]['externals']=[] groupcache[groupcounter]['externals'].append(k) last_name = k groupcache[groupcounter]['vars']=edecl if last_name is not None: previous_context = ('variable', last_name, groupcounter) elif case=='parameter': edecl=groupcache[groupcounter]['vars'] ll=m.group('after').strip()[1:-1] last_name = None for e in markoutercomma(ll).split('@,@'): try: k, initexpr=[x.strip() for x in e.split('=')] except: outmess('analyzeline: could not extract name,expr in parameter statement "%s" of "%s"\n'%(e, ll));continue params = get_parameters(edecl) k=rmbadname1(k) if k not in edecl: edecl[k]={} if '=' in edecl[k] and (not edecl[k]['=']==initexpr): outmess('analyzeline: Overwriting the value of parameter "%s" ("%s") with "%s".\n'%(k, edecl[k]['='], initexpr)) t = determineexprtype(initexpr, params) if t: if t.get('typespec')=='real': tt = list(initexpr) for m in real16pattern.finditer(initexpr): tt[m.start():m.end()] = list(\ initexpr[m.start():m.end()].lower().replace('d', 'e')) initexpr = ''.join(tt) elif t.get('typespec')=='complex': initexpr = initexpr[1:].lower().replace('d', 'e').\ replace(',', '+1j*(') try: v = eval(initexpr, {}, params) except (SyntaxError, NameError, TypeError) as msg: errmess('analyzeline: Failed to evaluate %r. Ignoring: %s\n'\ % (initexpr, msg)) continue edecl[k]['='] = repr(v) if 'attrspec' in edecl[k]: edecl[k]['attrspec'].append('parameter') else: edecl[k]['attrspec']=['parameter'] last_name = k groupcache[groupcounter]['vars']=edecl if last_name is not None: previous_context = ('variable', last_name, groupcounter) elif case=='implicit': if m.group('after').strip().lower()=='none': groupcache[groupcounter]['implicit']=None elif m.group('after'): if 'implicit' in groupcache[groupcounter]: impl=groupcache[groupcounter]['implicit'] else: impl={} if impl is None: outmess('analyzeline: Overwriting earlier "implicit none" statement.\n') impl={} for e in markoutercomma(m.group('after')).split('@,@'): decl={} m1=re.match(r'\s*(?P.*?)\s*(\(\s*(?P[a-z-, ]+)\s*\)\s*|)\Z', e, re.I) if not m1: outmess('analyzeline: could not extract info of implicit statement part "%s"\n'%(e));continue m2=typespattern4implicit.match(m1.group('this')) if not m2: outmess('analyzeline: could not extract types pattern of implicit statement part "%s"\n'%(e));continue typespec, selector, attr, edecl=cracktypespec0(m2.group('this'), m2.group('after')) kindselect, charselect, typename=cracktypespec(typespec, selector) decl['typespec']=typespec decl['kindselector']=kindselect decl['charselector']=charselect decl['typename']=typename for k in list(decl.keys()): if not decl[k]: del decl[k] for r in markoutercomma(m1.group('after')).split('@,@'): if '-' in r: try: begc, endc=[x.strip() for x in r.split('-')] except: outmess('analyzeline: expected "-" instead of "%s" in range list of implicit statement\n'%r);continue else: begc=endc=r.strip() if not len(begc)==len(endc)==1: outmess('analyzeline: expected "-" instead of "%s" in range list of implicit statement (2)\n'%r);continue for o in range(ord(begc), ord(endc)+1): impl[chr(o)]=decl groupcache[groupcounter]['implicit']=impl elif case=='data': ll=[] dl='';il='';f=0;fc=1;inp=0 for c in m.group('after'): if not inp: if c=="'": fc=not fc if c=='/' and fc: f=f+1;continue if c=='(': inp = inp + 1 elif c==')': inp = inp - 1 if f==0: dl=dl+c elif f==1: il=il+c elif f==2: dl = dl.strip() if dl.startswith(','): dl = dl[1:].strip() ll.append([dl, il]) dl=c;il='';f=0 if f==2: dl = dl.strip() if dl.startswith(','): dl = dl[1:].strip() ll.append([dl, il]) vars={} if 'vars' in groupcache[groupcounter]: vars=groupcache[groupcounter]['vars'] last_name = None for l in ll: l=[x.strip() for x in l] if l[0][0]==',':l[0]=l[0][1:] if l[0][0]=='(': outmess('analyzeline: implied-DO list "%s" is not supported. Skipping.\n'%l[0]) continue #if '(' in l[0]: # #outmess('analyzeline: ignoring this data statement.\n') # continue i=0;j=0;llen=len(l[1]) for v in rmbadname([x.strip() for x in markoutercomma(l[0]).split('@,@')]): if v[0]=='(': outmess('analyzeline: implied-DO list "%s" is not supported. Skipping.\n'%v) # XXX: subsequent init expressions may get wrong values. # Ignoring since data statements are irrelevant for wrapping. continue fc=0 while (i=3: bn = bn.strip() if not bn: bn='_BLNK_' cl.append([bn, ol]) f=f-2;bn='';ol='' if f%2: bn=bn+c else: ol=ol+c bn = bn.strip() if not bn: bn='_BLNK_' cl.append([bn, ol]) commonkey={} if 'common' in groupcache[groupcounter]: commonkey=groupcache[groupcounter]['common'] for c in cl: if c[0] in commonkey: outmess('analyzeline: previously defined common block encountered. Skipping.\n') continue commonkey[c[0]]=[] for i in [x.strip() for x in markoutercomma(c[1]).split('@,@')]: if i: commonkey[c[0]].append(i) groupcache[groupcounter]['common']=commonkey previous_context = ('common', bn, groupcounter) elif case=='use': m1=re.match(r'\A\s*(?P\b[\w]+\b)\s*((,(\s*\bonly\b\s*:|(?P))\s*(?P.*))|)\s*\Z', m.group('after'), re.I) if m1: mm=m1.groupdict() if 'use' not in groupcache[groupcounter]: groupcache[groupcounter]['use']={} name=m1.group('name') groupcache[groupcounter]['use'][name]={} isonly=0 if 'list' in mm and mm['list'] is not None: if 'notonly' in mm and mm['notonly'] is None: isonly=1 groupcache[groupcounter]['use'][name]['only']=isonly ll=[x.strip() for x in mm['list'].split(',')] rl={} for l in ll: if '=' in l: m2=re.match(r'\A\s*(?P\b[\w]+\b)\s*=\s*>\s*(?P\b[\w]+\b)\s*\Z', l, re.I) if m2: rl[m2.group('local').strip()]=m2.group('use').strip() else: outmess('analyzeline: Not local=>use pattern found in %s\n'%repr(l)) else: rl[l]=l groupcache[groupcounter]['use'][name]['map']=rl else: pass else: print(m.groupdict()) outmess('analyzeline: Could not crack the use statement.\n') elif case in ['f2pyenhancements']: if 'f2pyenhancements' not in groupcache[groupcounter]: groupcache[groupcounter]['f2pyenhancements'] = {} d = groupcache[groupcounter]['f2pyenhancements'] if m.group('this')=='usercode' and 'usercode' in d: if isinstance(d['usercode'], str): d['usercode'] = [d['usercode']] d['usercode'].append(m.group('after')) else: d[m.group('this')] = m.group('after') elif case=='multiline': if previous_context is None: if verbose: outmess('analyzeline: No context for multiline block.\n') return gc = groupcounter #gc = previous_context[2] appendmultiline(groupcache[gc], previous_context[:2], m.group('this')) else: if verbose>1: print(m.groupdict()) outmess('analyzeline: No code implemented for line.\n') def appendmultiline(group, context_name, ml): if 'f2pymultilines' not in group: group['f2pymultilines'] = {} d = group['f2pymultilines'] if context_name not in d: d[context_name] = [] d[context_name].append(ml) return def cracktypespec0(typespec, ll): selector=None attr=None if re.match(r'double\s*complex', typespec, re.I): typespec='double complex' elif re.match(r'double\s*precision', typespec, re.I): typespec='double precision' else: typespec=typespec.strip().lower() m1=selectpattern.match(markouterparen(ll)) if not m1: outmess('cracktypespec0: no kind/char_selector pattern found for line.\n') return d=m1.groupdict() for k in list(d.keys()): d[k]=unmarkouterparen(d[k]) if typespec in ['complex', 'integer', 'logical', 'real', 'character', 'type']: selector=d['this'] ll=d['after'] i=ll.find('::') if i>=0: attr=ll[:i].strip() ll=ll[i+2:] return typespec, selector, attr, ll ##### namepattern=re.compile(r'\s*(?P\b[\w]+\b)\s*(?P.*)\s*\Z', re.I) kindselector=re.compile(r'\s*(\(\s*(kind\s*=)?\s*(?P.*)\s*\)|[*]\s*(?P.*?))\s*\Z', re.I) charselector=re.compile(r'\s*(\((?P.*)\)|[*]\s*(?P.*))\s*\Z', re.I) lenkindpattern=re.compile(r'\s*(kind\s*=\s*(?P.*?)\s*(@,@\s*len\s*=\s*(?P.*)|)|(len\s*=\s*|)(?P.*?)\s*(@,@\s*(kind\s*=\s*|)(?P.*)|))\s*\Z', re.I) lenarraypattern=re.compile(r'\s*(@\(@\s*(?!/)\s*(?P.*?)\s*@\)@\s*[*]\s*(?P.*?)|([*]\s*(?P.*?)|)\s*(@\(@\s*(?!/)\s*(?P.*?)\s*@\)@|))\s*(=\s*(?P.*?)|(@\(@|)/\s*(?P.*?)\s*/(@\)@|)|)\s*\Z', re.I) def removespaces(expr): expr=expr.strip() if len(expr)<=1: return expr expr2=expr[0] for i in range(1, len(expr)-1): if expr[i]==' ' and \ ((expr[i+1] in "()[]{}=+-/* ") or (expr[i-1] in "()[]{}=+-/* ")): continue expr2=expr2+expr[i] expr2=expr2+expr[-1] return expr2 def markinnerspaces(line): l='';f=0 cc='\'' cc1='"' cb='' for c in line: if cb=='\\' and c in ['\\', '\'', '"']: l=l+c; cb=c continue if f==0 and c in ['\'', '"']: cc=c; cc1={'\'':'"','"':'\''}[c] if c==cc:f=f+1 elif c==cc:f=f-1 elif c==' ' and f==1: l=l+'@_@'; continue l=l+c;cb=c return l def updatevars(typespec, selector, attrspec, entitydecl): global groupcache, groupcounter last_name = None kindselect, charselect, typename=cracktypespec(typespec, selector) if attrspec: attrspec=[x.strip() for x in markoutercomma(attrspec).split('@,@')] l = [] c = re.compile(r'(?P[a-zA-Z]+)') for a in attrspec: if not a: continue m = c.match(a) if m: s = m.group('start').lower() a = s + a[len(s):] l.append(a) attrspec = l el=[x.strip() for x in markoutercomma(entitydecl).split('@,@')] el1=[] for e in el: for e1 in [x.strip() for x in markoutercomma(removespaces(markinnerspaces(e)), comma=' ').split('@ @')]: if e1: el1.append(e1.replace('@_@', ' ')) for e in el1: m=namepattern.match(e) if not m: outmess('updatevars: no name pattern found for entity=%s. Skipping.\n'%(repr(e))) continue ename=rmbadname1(m.group('name')) edecl={} if ename in groupcache[groupcounter]['vars']: edecl=groupcache[groupcounter]['vars'][ename].copy() not_has_typespec = 'typespec' not in edecl if not_has_typespec: edecl['typespec']=typespec elif typespec and (not typespec==edecl['typespec']): outmess('updatevars: attempt to change the type of "%s" ("%s") to "%s". Ignoring.\n' % (ename, edecl['typespec'], typespec)) if 'kindselector' not in edecl: edecl['kindselector']=copy.copy(kindselect) elif kindselect: for k in list(kindselect.keys()): if k in edecl['kindselector'] and (not kindselect[k]==edecl['kindselector'][k]): outmess('updatevars: attempt to change the kindselector "%s" of "%s" ("%s") to "%s". Ignoring.\n' % (k, ename, edecl['kindselector'][k], kindselect[k])) else: edecl['kindselector'][k]=copy.copy(kindselect[k]) if 'charselector' not in edecl and charselect: if not_has_typespec: edecl['charselector']=charselect else: errmess('updatevars:%s: attempt to change empty charselector to %r. Ignoring.\n' \ %(ename, charselect)) elif charselect: for k in list(charselect.keys()): if k in edecl['charselector'] and (not charselect[k]==edecl['charselector'][k]): outmess('updatevars: attempt to change the charselector "%s" of "%s" ("%s") to "%s". Ignoring.\n' % (k, ename, edecl['charselector'][k], charselect[k])) else: edecl['charselector'][k]=copy.copy(charselect[k]) if 'typename' not in edecl: edecl['typename']=typename elif typename and (not edecl['typename']==typename): outmess('updatevars: attempt to change the typename of "%s" ("%s") to "%s". Ignoring.\n' % (ename, edecl['typename'], typename)) if 'attrspec' not in edecl: edecl['attrspec']=copy.copy(attrspec) elif attrspec: for a in attrspec: if a not in edecl['attrspec']: edecl['attrspec'].append(a) else: edecl['typespec']=copy.copy(typespec) edecl['kindselector']=copy.copy(kindselect) edecl['charselector']=copy.copy(charselect) edecl['typename']=typename edecl['attrspec']=copy.copy(attrspec) if m.group('after'): m1=lenarraypattern.match(markouterparen(m.group('after'))) if m1: d1=m1.groupdict() for lk in ['len', 'array', 'init']: if d1[lk+'2'] is not None: d1[lk]=d1[lk+'2']; del d1[lk+'2'] for k in list(d1.keys()): if d1[k] is not None: d1[k]=unmarkouterparen(d1[k]) else: del d1[k] if 'len' in d1 and 'array' in d1: if d1['len']=='': d1['len']=d1['array'] del d1['array'] else: d1['array']=d1['array']+','+d1['len'] del d1['len'] errmess('updatevars: "%s %s" is mapped to "%s %s(%s)"\n'%(typespec, e, typespec, ename, d1['array'])) if 'array' in d1: dm = 'dimension(%s)'%d1['array'] if 'attrspec' not in edecl or (not edecl['attrspec']): edecl['attrspec']=[dm] else: edecl['attrspec'].append(dm) for dm1 in edecl['attrspec']: if dm1[:9]=='dimension' and dm1!=dm: del edecl['attrspec'][-1] errmess('updatevars:%s: attempt to change %r to %r. Ignoring.\n' \ % (ename, dm1, dm)) break if 'len' in d1: if typespec in ['complex', 'integer', 'logical', 'real']: if ('kindselector' not in edecl) or (not edecl['kindselector']): edecl['kindselector']={} edecl['kindselector']['*']=d1['len'] elif typespec == 'character': if ('charselector' not in edecl) or (not edecl['charselector']): edecl['charselector']={} if 'len' in edecl['charselector']: del edecl['charselector']['len'] edecl['charselector']['*']=d1['len'] if 'init' in d1: if '=' in edecl and (not edecl['=']==d1['init']): outmess('updatevars: attempt to change the init expression of "%s" ("%s") to "%s". Ignoring.\n' % (ename, edecl['='], d1['init'])) else: edecl['=']=d1['init'] else: outmess('updatevars: could not crack entity declaration "%s". Ignoring.\n'%(ename+m.group('after'))) for k in list(edecl.keys()): if not edecl[k]: del edecl[k] groupcache[groupcounter]['vars'][ename]=edecl if 'varnames' in groupcache[groupcounter]: groupcache[groupcounter]['varnames'].append(ename) last_name = ename return last_name def cracktypespec(typespec, selector): kindselect=None charselect=None typename=None if selector: if typespec in ['complex', 'integer', 'logical', 'real']: kindselect=kindselector.match(selector) if not kindselect: outmess('cracktypespec: no kindselector pattern found for %s\n'%(repr(selector))) return kindselect=kindselect.groupdict() kindselect['*']=kindselect['kind2'] del kindselect['kind2'] for k in list(kindselect.keys()): if not kindselect[k]: del kindselect[k] for k, i in list(kindselect.items()): kindselect[k] = rmbadname1(i) elif typespec=='character': charselect=charselector.match(selector) if not charselect: outmess('cracktypespec: no charselector pattern found for %s\n'%(repr(selector))) return charselect=charselect.groupdict() charselect['*']=charselect['charlen'] del charselect['charlen'] if charselect['lenkind']: lenkind=lenkindpattern.match(markoutercomma(charselect['lenkind'])) lenkind=lenkind.groupdict() for lk in ['len', 'kind']: if lenkind[lk+'2']: lenkind[lk]=lenkind[lk+'2'] charselect[lk]=lenkind[lk] del lenkind[lk+'2'] del charselect['lenkind'] for k in list(charselect.keys()): if not charselect[k]: del charselect[k] for k, i in list(charselect.items()): charselect[k] = rmbadname1(i) elif typespec=='type': typename=re.match(r'\s*\(\s*(?P\w+)\s*\)', selector, re.I) if typename: typename=typename.group('name') else: outmess('cracktypespec: no typename found in %s\n'%(repr(typespec+selector))) else: outmess('cracktypespec: no selector used for %s\n'%(repr(selector))) return kindselect, charselect, typename ###### def setattrspec(decl,attr,force=0): if not decl: decl={} if not attr: return decl if 'attrspec' not in decl: decl['attrspec']=[attr] return decl if force: decl['attrspec'].append(attr) if attr in decl['attrspec']: return decl if attr=='static' and 'automatic' not in decl['attrspec']: decl['attrspec'].append(attr) elif attr=='automatic' and 'static' not in decl['attrspec']: decl['attrspec'].append(attr) elif attr=='public' and 'private' not in decl['attrspec']: decl['attrspec'].append(attr) elif attr=='private' and 'public' not in decl['attrspec']: decl['attrspec'].append(attr) else: decl['attrspec'].append(attr) return decl def setkindselector(decl,sel,force=0): if not decl: decl={} if not sel: return decl if 'kindselector' not in decl: decl['kindselector']=sel return decl for k in list(sel.keys()): if force or k not in decl['kindselector']: decl['kindselector'][k]=sel[k] return decl def setcharselector(decl,sel,force=0): if not decl: decl={} if not sel: return decl if 'charselector' not in decl: decl['charselector']=sel return decl for k in list(sel.keys()): if force or k not in decl['charselector']: decl['charselector'][k]=sel[k] return decl def getblockname(block,unknown='unknown'): if 'name' in block: return block['name'] return unknown ###### post processing def setmesstext(block): global filepositiontext try: filepositiontext='In: %s:%s\n'%(block['from'], block['name']) except: pass def get_usedict(block): usedict = {} if 'parent_block' in block: usedict = get_usedict(block['parent_block']) if 'use' in block: usedict.update(block['use']) return usedict def get_useparameters(block, param_map=None): global f90modulevars if param_map is None: param_map = {} usedict = get_usedict(block) if not usedict: return param_map for usename, mapping in list(usedict.items()): usename = usename.lower() if usename not in f90modulevars: outmess('get_useparameters: no module %s info used by %s\n' % (usename, block.get('name'))) continue mvars = f90modulevars[usename] params = get_parameters(mvars) if not params: continue # XXX: apply mapping if mapping: errmess('get_useparameters: mapping for %s not impl.' % (mapping)) for k, v in list(params.items()): if k in param_map: outmess('get_useparameters: overriding parameter %s with'\ ' value from module %s' % (repr(k), repr(usename))) param_map[k] = v return param_map def postcrack2(block,tab='',param_map=None): global f90modulevars if not f90modulevars: return block if isinstance(block, list): ret = [] for g in block: g = postcrack2(g, tab=tab+'\t', param_map=param_map) ret.append(g) return ret setmesstext(block) outmess('%sBlock: %s\n'%(tab, block['name']), 0) if param_map is None: param_map = get_useparameters(block) if param_map is not None and 'vars' in block: vars = block['vars'] for n in list(vars.keys()): var = vars[n] if 'kindselector' in var: kind = var['kindselector'] if 'kind' in kind: val = kind['kind'] if val in param_map: kind['kind'] = param_map[val] new_body = [] for b in block['body']: b = postcrack2(b, tab=tab+'\t', param_map=param_map) new_body.append(b) block['body'] = new_body return block def postcrack(block,args=None,tab=''): """ TODO: function return values determine expression types if in argument list """ global usermodules, onlyfunctions if isinstance(block, list): gret=[] uret=[] for g in block: setmesstext(g) g=postcrack(g, tab=tab+'\t') if 'name' in g and '__user__' in g['name']: # sort user routines to appear first uret.append(g) else: gret.append(g) return uret+gret setmesstext(block) if not isinstance(block, dict) and 'block' not in block: raise Exception('postcrack: Expected block dictionary instead of ' + \ str(block)) if 'name' in block and not block['name']=='unknown_interface': outmess('%sBlock: %s\n'%(tab, block['name']), 0) blocktype=block['block'] block=analyzeargs(block) block=analyzecommon(block) block['vars']=analyzevars(block) block['sortvars']=sortvarnames(block['vars']) if 'args' in block and block['args']: args=block['args'] block['body']=analyzebody(block, args, tab=tab) userisdefined=[] ## fromuser = [] if 'use' in block: useblock=block['use'] for k in list(useblock.keys()): if '__user__' in k: userisdefined.append(k) ## if 'map' in useblock[k]: ## for n in useblock[k]['map'].itervalues(): ## if n not in fromuser: fromuser.append(n) else: useblock={} name='' if 'name' in block: name=block['name'] if 'externals' in block and block['externals']:# and not userisdefined: # Build a __user__ module interfaced=[] if 'interfaced' in block: interfaced=block['interfaced'] mvars=copy.copy(block['vars']) if name: mname=name+'__user__routines' else: mname='unknown__user__routines' if mname in userisdefined: i=1 while '%s_%i'%(mname, i) in userisdefined: i=i+1 mname='%s_%i'%(mname, i) interface={'block':'interface','body':[],'vars':{},'name':name+'_user_interface'} for e in block['externals']: ## if e in fromuser: ## outmess(' Skipping %s that is defined explicitly in another use statement\n'%(`e`)) ## continue if e in interfaced: edef=[] j=-1 for b in block['body']: j=j+1 if b['block']=='interface': i=-1 for bb in b['body']: i=i+1 if 'name' in bb and bb['name']==e: edef=copy.copy(bb) del b['body'][i] break if edef: if not b['body']: del block['body'][j] del interfaced[interfaced.index(e)] break interface['body'].append(edef) else: if e in mvars and not isexternal(mvars[e]): interface['vars'][e]=mvars[e] if interface['vars'] or interface['body']: block['interfaced']=interfaced mblock={'block':'python module','body':[interface],'vars':{},'name':mname,'interfaced':block['externals']} useblock[mname]={} usermodules.append(mblock) if useblock: block['use']=useblock return block def sortvarnames(vars): indep = [] dep = [] for v in list(vars.keys()): if 'depend' in vars[v] and vars[v]['depend']: dep.append(v) #print '%s depends on %s'%(v,vars[v]['depend']) else: indep.append(v) n = len(dep) i = 0 while dep: #XXX: How to catch dependence cycles correctly? v = dep[0] fl = 0 for w in dep[1:]: if w in vars[v]['depend']: fl = 1 break if fl: dep = dep[1:]+[v] i = i + 1 if i>n: errmess('sortvarnames: failed to compute dependencies because' ' of cyclic dependencies between ' +', '.join(dep)+'\n') indep = indep + dep break else: indep.append(v) dep = dep[1:] n = len(dep) i = 0 #print indep return indep def analyzecommon(block): if not hascommon(block): return block commonvars=[] for k in list(block['common'].keys()): comvars=[] for e in block['common'][k]: m=re.match(r'\A\s*\b(?P.*?)\b\s*(\((?P.*?)\)|)\s*\Z', e, re.I) if m: dims=[] if m.group('dims'): dims=[x.strip() for x in markoutercomma(m.group('dims')).split('@,@')] n=m.group('name').strip() if n in block['vars']: if 'attrspec' in block['vars'][n]: block['vars'][n]['attrspec'].append('dimension(%s)'%(','.join(dims))) else: block['vars'][n]['attrspec']=['dimension(%s)'%(','.join(dims))] else: if dims: block['vars'][n]={'attrspec':['dimension(%s)'%(','.join(dims))]} else: block['vars'][n]={} if n not in commonvars: commonvars.append(n) else: n=e errmess('analyzecommon: failed to extract "[()]" from "%s" in common /%s/.\n'%(e, k)) comvars.append(n) block['common'][k]=comvars if 'commonvars' not in block: block['commonvars']=commonvars else: block['commonvars']=block['commonvars']+commonvars return block def analyzebody(block,args,tab=''): global usermodules, skipfuncs, onlyfuncs, f90modulevars setmesstext(block) body=[] for b in block['body']: b['parent_block'] = block if b['block'] in ['function', 'subroutine']: if args is not None and b['name'] not in args: continue else: as_=b['args'] if b['name'] in skipfuncs: continue if onlyfuncs and b['name'] not in onlyfuncs: continue b['saved_interface'] = crack2fortrangen(b, '\n'+' '*6, as_interface=True) else: as_=args b=postcrack(b, as_, tab=tab+'\t') if b['block']=='interface' and not b['body']: if 'f2pyenhancements' not in b: continue if b['block'].replace(' ', '')=='pythonmodule': usermodules.append(b) else: if b['block']=='module': f90modulevars[b['name']] = b['vars'] body.append(b) return body def buildimplicitrules(block): setmesstext(block) implicitrules=defaultimplicitrules attrrules={} if 'implicit' in block: if block['implicit'] is None: implicitrules=None if verbose>1: outmess('buildimplicitrules: no implicit rules for routine %s.\n'%repr(block['name'])) else: for k in list(block['implicit'].keys()): if block['implicit'][k].get('typespec') not in ['static', 'automatic']: implicitrules[k]=block['implicit'][k] else: attrrules[k]=block['implicit'][k]['typespec'] return implicitrules, attrrules def myeval(e,g=None,l=None): r = eval(e, g, l) if type(r) in [type(0), type(0.0)]: return r raise ValueError('r=%r' % (r)) getlincoef_re_1 = re.compile(r'\A\b\w+\b\Z', re.I) def getlincoef(e, xset): # e = a*x+b ; x in xset try: c = int(myeval(e, {}, {})) return 0, c, None except: pass if getlincoef_re_1.match(e): return 1, 0, e len_e = len(e) for x in xset: if len(x)>len_e: continue if re.search(r'\w\s*\([^)]*\b'+x+r'\b', e): # skip function calls having x as an argument, e.g max(1, x) continue re_1 = re.compile(r'(?P.*?)\b'+x+r'\b(?P.*)', re.I) m = re_1.match(e) if m: try: m1 = re_1.match(e) while m1: ee = '%s(%s)%s'%(m1.group('before'), 0, m1.group('after')) m1 = re_1.match(ee) b = myeval(ee, {}, {}) m1 = re_1.match(e) while m1: ee = '%s(%s)%s'%(m1.group('before'), 1, m1.group('after')) m1 = re_1.match(ee) a = myeval(ee, {}, {}) - b m1 = re_1.match(e) while m1: ee = '%s(%s)%s'%(m1.group('before'), 0.5, m1.group('after')) m1 = re_1.match(ee) c = myeval(ee, {}, {}) # computing another point to be sure that expression is linear m1 = re_1.match(e) while m1: ee = '%s(%s)%s'%(m1.group('before'), 1.5, m1.group('after')) m1 = re_1.match(ee) c2 = myeval(ee, {}, {}) if (a*0.5+b==c and a*1.5+b==c2): return a, b, x except: pass break return None, None, None _varname_match = re.compile(r'\A[a-z]\w*\Z').match def getarrlen(dl,args,star='*'): edl = [] try: edl.append(myeval(dl[0], {}, {})) except: edl.append(dl[0]) try: edl.append(myeval(dl[1], {}, {})) except: edl.append(dl[1]) if isinstance(edl[0], int): p1 = 1-edl[0] if p1==0: d = str(dl[1]) elif p1<0: d = '%s-%s'%(dl[1], -p1) else: d = '%s+%s'%(dl[1], p1) elif isinstance(edl[1], int): p1 = 1+edl[1] if p1==0: d='-(%s)' % (dl[0]) else: d='%s-(%s)' % (p1, dl[0]) else: d = '%s-(%s)+1'%(dl[1], dl[0]) try: return repr(myeval(d, {}, {})), None, None except: pass d1, d2=getlincoef(dl[0], args), getlincoef(dl[1], args) if None not in [d1[0], d2[0]]: if (d1[0], d2[0])==(0, 0): return repr(d2[1]-d1[1]+1), None, None b = d2[1] - d1[1] + 1 d1 = (d1[0], 0, d1[2]) d2 = (d2[0], b, d2[2]) if d1[0]==0 and d2[2] in args: if b<0: return '%s * %s - %s'%(d2[0], d2[2], -b), d2[2], '+%s)/(%s)'%(-b, d2[0]) elif b: return '%s * %s + %s'%(d2[0], d2[2], b), d2[2], '-%s)/(%s)'%(b, d2[0]) else: return '%s * %s'%(d2[0], d2[2]), d2[2], ')/(%s)'%(d2[0]) if d2[0]==0 and d1[2] in args: if b<0: return '%s * %s - %s'%(-d1[0], d1[2], -b), d1[2], '+%s)/(%s)'%(-b, -d1[0]) elif b: return '%s * %s + %s'%(-d1[0], d1[2], b), d1[2], '-%s)/(%s)'%(b, -d1[0]) else: return '%s * %s'%(-d1[0], d1[2]), d1[2], ')/(%s)'%(-d1[0]) if d1[2]==d2[2] and d1[2] in args: a = d2[0] - d1[0] if not a: return repr(b), None, None if b<0: return '%s * %s - %s'%(a, d1[2], -b), d2[2], '+%s)/(%s)'%(-b, a) elif b: return '%s * %s + %s'%(a, d1[2], b), d2[2], '-%s)/(%s)'%(b, a) else: return '%s * %s'%(a, d1[2]), d2[2], ')/(%s)'%(a) if d1[0]==d2[0]==1: c = str(d1[2]) if c not in args: if _varname_match(c): outmess('\tgetarrlen:variable "%s" undefined\n' % (c)) c = '(%s)'%c if b==0: d='%s-%s' % (d2[2], c) elif b<0: d='%s-%s-%s' % (d2[2], c, -b) else: d='%s-%s+%s' % (d2[2], c, b) elif d1[0]==0: c2 = str(d2[2]) if c2 not in args: if _varname_match(c2): outmess('\tgetarrlen:variable "%s" undefined\n' % (c2)) c2 = '(%s)'%c2 if d2[0]==1: pass elif d2[0]==-1: c2='-%s' %c2 else: c2='%s*%s'%(d2[0], c2) if b==0: d=c2 elif b<0: d='%s-%s' % (c2, -b) else: d='%s+%s' % (c2, b) elif d2[0]==0: c1 = str(d1[2]) if c1 not in args: if _varname_match(c1): outmess('\tgetarrlen:variable "%s" undefined\n' % (c1)) c1 = '(%s)'%c1 if d1[0]==1: c1='-%s'%c1 elif d1[0]==-1: c1='+%s'%c1 elif d1[0]<0: c1='+%s*%s'%(-d1[0], c1) else: c1 = '-%s*%s' % (d1[0], c1) if b==0: d=c1 elif b<0: d='%s-%s' % (c1, -b) else: d='%s+%s' % (c1, b) else: c1 = str(d1[2]) if c1 not in args: if _varname_match(c1): outmess('\tgetarrlen:variable "%s" undefined\n' % (c1)) c1 = '(%s)'%c1 if d1[0]==1: c1='-%s'%c1 elif d1[0]==-1: c1='+%s'%c1 elif d1[0]<0: c1='+%s*%s'%(-d1[0], c1) else: c1 = '-%s*%s' % (d1[0], c1) c2 = str(d2[2]) if c2 not in args: if _varname_match(c2): outmess('\tgetarrlen:variable "%s" undefined\n' % (c2)) c2 = '(%s)'%c2 if d2[0]==1: pass elif d2[0]==-1: c2='-%s' %c2 else: c2='%s*%s'%(d2[0], c2) if b==0: d='%s%s' % (c2, c1) elif b<0: d='%s%s-%s' % (c2, c1, -b) else: d='%s%s+%s' % (c2, c1, b) return d, None, None word_pattern = re.compile(r'\b[a-z][\w$]*\b', re.I) def _get_depend_dict(name, vars, deps): if name in vars: words = vars[name].get('depend', []) if '=' in vars[name] and not isstring(vars[name]): for word in word_pattern.findall(vars[name]['=']): if word not in words and word in vars: words.append(word) for word in words[:]: for w in deps.get(word, []) \ or _get_depend_dict(word, vars, deps): if w not in words: words.append(w) else: outmess('_get_depend_dict: no dependence info for %s\n' % (repr(name))) words = [] deps[name] = words return words def _calc_depend_dict(vars): names = list(vars.keys()) depend_dict = {} for n in names: _get_depend_dict(n, vars, depend_dict) return depend_dict def get_sorted_names(vars): """ """ depend_dict = _calc_depend_dict(vars) names = [] for name in list(depend_dict.keys()): if not depend_dict[name]: names.append(name) del depend_dict[name] while depend_dict: for name, lst in list(depend_dict.items()): new_lst = [n for n in lst if n in depend_dict] if not new_lst: names.append(name) del depend_dict[name] else: depend_dict[name] = new_lst return [name for name in names if name in vars] def _kind_func(string): #XXX: return something sensible. if string[0] in "'\"": string = string[1:-1] if real16pattern.match(string): return 8 elif real8pattern.match(string): return 4 return 'kind('+string+')' def _selected_int_kind_func(r): #XXX: This should be processor dependent m = 10**r if m<=2**8: return 1 if m<=2**16: return 2 if m<=2**32: return 4 if m<=2**63: return 8 if m<=2**128: return 16 return -1 def _selected_real_kind_func(p, r=0, radix=0): #XXX: This should be processor dependent # This is only good for 0 <= p <= 20 if p < 7: return 4 if p < 16: return 8 if platform.machine().lower().startswith('power'): if p <= 20: return 16 else: if p < 19: return 10 elif p <= 20: return 16 return -1 def get_parameters(vars, global_params={}): params = copy.copy(global_params) g_params = copy.copy(global_params) for name, func in [('kind', _kind_func), ('selected_int_kind', _selected_int_kind_func), ('selected_real_kind', _selected_real_kind_func), ]: if name not in g_params: g_params[name] = func param_names = [] for n in get_sorted_names(vars): if 'attrspec' in vars[n] and 'parameter' in vars[n]['attrspec']: param_names.append(n) kind_re = re.compile(r'\bkind\s*\(\s*(?P.*)\s*\)', re.I) selected_int_kind_re = re.compile(r'\bselected_int_kind\s*\(\s*(?P.*)\s*\)', re.I) selected_kind_re = re.compile(r'\bselected_(int|real)_kind\s*\(\s*(?P.*)\s*\)', re.I) for n in param_names: if '=' in vars[n]: v = vars[n]['='] if islogical(vars[n]): v = v.lower() for repl in [ ('.false.', 'False'), ('.true.', 'True'), #TODO: test .eq., .neq., etc replacements. ]: v = v.replace(*repl) v = kind_re.sub(r'kind("\1")', v) v = selected_int_kind_re.sub(r'selected_int_kind(\1)', v) if isinteger(vars[n]) and not selected_kind_re.match(v): v = v.split('_')[0] if isdouble(vars[n]): tt = list(v) for m in real16pattern.finditer(v): tt[m.start():m.end()] = list(\ v[m.start():m.end()].lower().replace('d', 'e')) v = ''.join(tt) if iscomplex(vars[n]): if v[0]=='(' and v[-1]==')': l = markoutercomma(v[1:-1]).split('@,@') try: params[n] = eval(v, g_params, params) except Exception as msg: params[n] = v #print params outmess('get_parameters: got "%s" on %s\n' % (msg, repr(v))) if isstring(vars[n]) and isinstance(params[n], int): params[n] = chr(params[n]) nl = n.lower() if nl!=n: params[nl] = params[n] else: print(vars[n]) outmess('get_parameters:parameter %s does not have value?!\n'%(repr(n))) return params def _eval_length(length, params): if length in ['(:)', '(*)', '*']: return '(*)' return _eval_scalar(length, params) _is_kind_number = re.compile(r'\d+_').match def _eval_scalar(value, params): if _is_kind_number(value): value = value.split('_')[0] try: value = str(eval(value, {}, params)) except (NameError, SyntaxError): return value except Exception as msg: errmess('"%s" in evaluating %r '\ '(available names: %s)\n' \ % (msg, value, list(params.keys()))) return value def analyzevars(block): global f90modulevars setmesstext(block) implicitrules, attrrules=buildimplicitrules(block) vars=copy.copy(block['vars']) if block['block']=='function' and block['name'] not in vars: vars[block['name']]={} if '' in block['vars']: del vars[''] if 'attrspec' in block['vars']['']: gen=block['vars']['']['attrspec'] for n in list(vars.keys()): for k in ['public', 'private']: if k in gen: vars[n]=setattrspec(vars[n], k) svars=[] args = block['args'] for a in args: try: vars[a] svars.append(a) except KeyError: pass for n in list(vars.keys()): if n not in args: svars.append(n) params = get_parameters(vars, get_useparameters(block)) dep_matches = {} name_match = re.compile(r'\w[\w\d_$]*').match for v in list(vars.keys()): m = name_match(v) if m: n = v[m.start():m.end()] try: dep_matches[n] except KeyError: dep_matches[n] = re.compile(r'.*\b%s\b'%(v), re.I).match for n in svars: if n[0] in list(attrrules.keys()): vars[n]=setattrspec(vars[n], attrrules[n[0]]) if 'typespec' not in vars[n]: if not('attrspec' in vars[n] and 'external' in vars[n]['attrspec']): if implicitrules: ln0 = n[0].lower() for k in list(implicitrules[ln0].keys()): if k=='typespec' and implicitrules[ln0][k]=='undefined': continue if k not in vars[n]: vars[n][k]=implicitrules[ln0][k] elif k=='attrspec': for l in implicitrules[ln0][k]: vars[n]=setattrspec(vars[n], l) elif n in block['args']: outmess('analyzevars: typespec of variable %s is not defined in routine %s.\n'%(repr(n), block['name'])) if 'charselector' in vars[n]: if 'len' in vars[n]['charselector']: l = vars[n]['charselector']['len'] try: l = str(eval(l, {}, params)) except: pass vars[n]['charselector']['len'] = l if 'kindselector' in vars[n]: if 'kind' in vars[n]['kindselector']: l = vars[n]['kindselector']['kind'] try: l = str(eval(l, {}, params)) except: pass vars[n]['kindselector']['kind'] = l savelindims = {} if 'attrspec' in vars[n]: attr=vars[n]['attrspec'] attr.reverse() vars[n]['attrspec']=[] dim, intent, depend, check, note=None, None, None, None, None for a in attr: if a[:9]=='dimension': dim=(a[9:].strip())[1:-1] elif a[:6]=='intent': intent=(a[6:].strip())[1:-1] elif a[:6]=='depend': depend=(a[6:].strip())[1:-1] elif a[:5]=='check': check=(a[5:].strip())[1:-1] elif a[:4]=='note': note=(a[4:].strip())[1:-1] else: vars[n]=setattrspec(vars[n], a) if intent: if 'intent' not in vars[n]: vars[n]['intent']=[] for c in [x.strip() for x in markoutercomma(intent).split('@,@')]: if not c in vars[n]['intent']: vars[n]['intent'].append(c) intent=None if note: note=note.replace('\\n\\n', '\n\n') note=note.replace('\\n ', '\n') if 'note' not in vars[n]: vars[n]['note']=[note] else: vars[n]['note'].append(note) note=None if depend is not None: if 'depend' not in vars[n]: vars[n]['depend']=[] for c in rmbadname([x.strip() for x in markoutercomma(depend).split('@,@')]): if c not in vars[n]['depend']: vars[n]['depend'].append(c) depend=None if check is not None: if 'check' not in vars[n]: vars[n]['check']=[] for c in [x.strip() for x in markoutercomma(check).split('@,@')]: if not c in vars[n]['check']: vars[n]['check'].append(c) check=None if dim and 'dimension' not in vars[n]: vars[n]['dimension']=[] for d in rmbadname([x.strip() for x in markoutercomma(dim).split('@,@')]): star = '*' if d==':': star=':' if d in params: d = str(params[d]) for p in list(params.keys()): m = re.match(r'(?P.*?)\b'+p+r'\b(?P.*)', d, re.I) if m: #outmess('analyzevars:replacing parameter %s in %s (dimension of %s) with %s\n'%(`p`,`d`,`n`,`params[p]`)) d = m.group('before')+str(params[p])+m.group('after') if d==star: dl = [star] else: dl=markoutercomma(d, ':').split('@:@') if len(dl)==2 and '*' in dl: # e.g. dimension(5:*) dl = ['*'] d = '*' if len(dl)==1 and not dl[0]==star: dl = ['1', dl[0]] if len(dl)==2: d, v, di = getarrlen(dl, list(block['vars'].keys())) if d[:4] == '1 * ': d = d[4:] if di and di[-4:] == '/(1)': di = di[:-4] if v: savelindims[d] = v, di vars[n]['dimension'].append(d) if 'dimension' in vars[n]: if isintent_c(vars[n]): shape_macro = 'shape' else: shape_macro = 'shape'#'fshape' if isstringarray(vars[n]): if 'charselector' in vars[n]: d = vars[n]['charselector'] if '*' in d: d = d['*'] errmess('analyzevars: character array "character*%s %s(%s)" is considered as "character %s(%s)"; "intent(c)" is forced.\n'\ %(d, n, ','.join(vars[n]['dimension']), n, ','.join(vars[n]['dimension']+[d]))) vars[n]['dimension'].append(d) del vars[n]['charselector'] if 'intent' not in vars[n]: vars[n]['intent'] = [] if 'c' not in vars[n]['intent']: vars[n]['intent'].append('c') else: errmess("analyzevars: charselector=%r unhandled." % (d)) if 'check' not in vars[n] and 'args' in block and n in block['args']: flag = 'depend' not in vars[n] if flag: vars[n]['depend']=[] vars[n]['check']=[] if 'dimension' in vars[n]: #/----< no check #vars[n]['check'].append('rank(%s)==%s'%(n,len(vars[n]['dimension']))) i=-1; ni=len(vars[n]['dimension']) for d in vars[n]['dimension']: ddeps=[] # dependecies of 'd' ad='' pd='' #origd = d if d not in vars: if d in savelindims: pd, ad='(', savelindims[d][1] d = savelindims[d][0] else: for r in block['args']: #for r in block['vars'].iterkeys(): if r not in vars: continue if re.match(r'.*?\b'+r+r'\b', d, re.I): ddeps.append(r) if d in vars: if 'attrspec' in vars[d]: for aa in vars[d]['attrspec']: if aa[:6]=='depend': ddeps += aa[6:].strip()[1:-1].split(',') if 'depend' in vars[d]: ddeps=ddeps+vars[d]['depend'] i=i+1 if d in vars and ('depend' not in vars[d]) \ and ('=' not in vars[d]) and (d not in vars[n]['depend']) \ and l_or(isintent_in, isintent_inout, isintent_inplace)(vars[n]): vars[d]['depend']=[n] if ni>1: vars[d]['=']='%s%s(%s,%s)%s'% (pd, shape_macro, n, i, ad) else: vars[d]['=']='%slen(%s)%s'% (pd, n, ad) # /---< no check if 1 and 'check' not in vars[d]: if ni>1: vars[d]['check']=['%s%s(%s,%i)%s==%s'\ %(pd, shape_macro, n, i, ad, d)] else: vars[d]['check']=['%slen(%s)%s>=%s'%(pd, n, ad, d)] if 'attrspec' not in vars[d]: vars[d]['attrspec']=['optional'] if ('optional' not in vars[d]['attrspec']) and\ ('required' not in vars[d]['attrspec']): vars[d]['attrspec'].append('optional') elif d not in ['*', ':']: #/----< no check #if ni>1: vars[n]['check'].append('shape(%s,%i)==%s'%(n,i,d)) #else: vars[n]['check'].append('len(%s)>=%s'%(n,d)) if flag: if d in vars: if n not in ddeps: vars[n]['depend'].append(d) else: vars[n]['depend'] = vars[n]['depend'] + ddeps elif isstring(vars[n]): length='1' if 'charselector' in vars[n]: if '*' in vars[n]['charselector']: length = _eval_length(vars[n]['charselector']['*'], params) vars[n]['charselector']['*']=length elif 'len' in vars[n]['charselector']: length = _eval_length(vars[n]['charselector']['len'], params) del vars[n]['charselector']['len'] vars[n]['charselector']['*']=length if not vars[n]['check']: del vars[n]['check'] if flag and not vars[n]['depend']: del vars[n]['depend'] if '=' in vars[n]: if 'attrspec' not in vars[n]: vars[n]['attrspec']=[] if ('optional' not in vars[n]['attrspec']) and \ ('required' not in vars[n]['attrspec']): vars[n]['attrspec'].append('optional') if 'depend' not in vars[n]: vars[n]['depend']=[] for v, m in list(dep_matches.items()): if m(vars[n]['=']): vars[n]['depend'].append(v) if not vars[n]['depend']: del vars[n]['depend'] if isscalar(vars[n]): vars[n]['='] = _eval_scalar(vars[n]['='], params) for n in list(vars.keys()): if n==block['name']: # n is block name if 'note' in vars[n]: block['note']=vars[n]['note'] if block['block']=='function': if 'result' in block and block['result'] in vars: vars[n]=appenddecl(vars[n], vars[block['result']]) if 'prefix' in block: pr=block['prefix']; ispure=0; isrec=1 pr1=pr.replace('pure', '') ispure=(not pr==pr1) pr=pr1.replace('recursive', '') isrec=(not pr==pr1) m=typespattern[0].match(pr) if m: typespec, selector, attr, edecl=cracktypespec0(m.group('this'), m.group('after')) kindselect, charselect, typename=cracktypespec(typespec, selector) vars[n]['typespec']=typespec if kindselect: if 'kind' in kindselect: try: kindselect['kind'] = eval(kindselect['kind'], {}, params) except: pass vars[n]['kindselector']=kindselect if charselect: vars[n]['charselector']=charselect if typename: vars[n]['typename']=typename if ispure: vars[n]=setattrspec(vars[n], 'pure') if isrec: vars[n]=setattrspec(vars[n], 'recursive') else: outmess('analyzevars: prefix (%s) were not used\n'%repr(block['prefix'])) if not block['block'] in ['module', 'pythonmodule', 'python module', 'block data']: if 'commonvars' in block: neededvars=copy.copy(block['args']+block['commonvars']) else: neededvars=copy.copy(block['args']) for n in list(vars.keys()): if l_or(isintent_callback, isintent_aux)(vars[n]): neededvars.append(n) if 'entry' in block: neededvars.extend(list(block['entry'].keys())) for k in list(block['entry'].keys()): for n in block['entry'][k]: if n not in neededvars: neededvars.append(n) if block['block']=='function': if 'result' in block: neededvars.append(block['result']) else: neededvars.append(block['name']) if block['block'] in ['subroutine', 'function']: name = block['name'] if name in vars and 'intent' in vars[name]: block['intent'] = vars[name]['intent'] if block['block'] == 'type': neededvars.extend(list(vars.keys())) for n in list(vars.keys()): if n not in neededvars: del vars[n] return vars analyzeargs_re_1 = re.compile(r'\A[a-z]+[\w$]*\Z', re.I) def expr2name(a, block, args=[]): orig_a = a a_is_expr = not analyzeargs_re_1.match(a) if a_is_expr: # `a` is an expression implicitrules, attrrules=buildimplicitrules(block) at=determineexprtype(a, block['vars'], implicitrules) na='e_' for c in a: c = c.lower() if c not in string.ascii_lowercase+string.digits: c='_' na=na+c if na[-1]=='_': na=na+'e' else: na=na+'_e' a=na while a in block['vars'] or a in block['args']: a=a+'r' if a in args: k = 1 while a + str(k) in args: k = k + 1 a = a + str(k) if a_is_expr: block['vars'][a]=at else: if a not in block['vars']: if orig_a in block['vars']: block['vars'][a] = block['vars'][orig_a] else: block['vars'][a]={} if 'externals' in block and orig_a in block['externals']+block['interfaced']: block['vars'][a]=setattrspec(block['vars'][a], 'external') return a def analyzeargs(block): setmesstext(block) implicitrules, attrrules=buildimplicitrules(block) if 'args' not in block: block['args']=[] args=[] for a in block['args']: a = expr2name(a, block, args) args.append(a) block['args']=args if 'entry' in block: for k, args1 in list(block['entry'].items()): for a in args1: if a not in block['vars']: block['vars'][a]={} for b in block['body']: if b['name'] in args: if 'externals' not in block: block['externals']=[] if b['name'] not in block['externals']: block['externals'].append(b['name']) if 'result' in block and block['result'] not in block['vars']: block['vars'][block['result']]={} return block determineexprtype_re_1 = re.compile(r'\A\(.+?[,].+?\)\Z', re.I) determineexprtype_re_2 = re.compile(r'\A[+-]?\d+(_(P[\w]+)|)\Z', re.I) determineexprtype_re_3 = re.compile(r'\A[+-]?[\d.]+[\d+-de.]*(_(P[\w]+)|)\Z', re.I) determineexprtype_re_4 = re.compile(r'\A\(.*\)\Z', re.I) determineexprtype_re_5 = re.compile(r'\A(?P\w+)\s*\(.*?\)\s*\Z', re.I) def _ensure_exprdict(r): if isinstance(r, int): return {'typespec':'integer'} if isinstance(r, float): return {'typespec':'real'} if isinstance(r, complex): return {'typespec':'complex'} if isinstance(r, dict): return r raise AssertionError(repr(r)) def determineexprtype(expr,vars,rules={}): if expr in vars: return _ensure_exprdict(vars[expr]) expr=expr.strip() if determineexprtype_re_1.match(expr): return {'typespec':'complex'} m=determineexprtype_re_2.match(expr) if m: if 'name' in m.groupdict() and m.group('name'): outmess('determineexprtype: selected kind types not supported (%s)\n'%repr(expr)) return {'typespec':'integer'} m = determineexprtype_re_3.match(expr) if m: if 'name' in m.groupdict() and m.group('name'): outmess('determineexprtype: selected kind types not supported (%s)\n'%repr(expr)) return {'typespec':'real'} for op in ['+', '-', '*', '/']: for e in [x.strip() for x in markoutercomma(expr, comma=op).split('@'+op+'@')]: if e in vars: return _ensure_exprdict(vars[e]) t={} if determineexprtype_re_4.match(expr): # in parenthesis t=determineexprtype(expr[1:-1], vars, rules) else: m = determineexprtype_re_5.match(expr) if m: rn=m.group('name') t=determineexprtype(m.group('name'), vars, rules) if t and 'attrspec' in t: del t['attrspec'] if not t: if rn[0] in rules: return _ensure_exprdict(rules[rn[0]]) if expr[0] in '\'"': return {'typespec':'character','charselector':{'*':'*'}} if not t: outmess('determineexprtype: could not determine expressions (%s) type.\n'%(repr(expr))) return t ###### def crack2fortrangen(block,tab='\n', as_interface=False): global skipfuncs, onlyfuncs setmesstext(block) ret='' if isinstance(block, list): for g in block: if g and g['block'] in ['function', 'subroutine']: if g['name'] in skipfuncs: continue if onlyfuncs and g['name'] not in onlyfuncs: continue ret=ret+crack2fortrangen(g, tab, as_interface=as_interface) return ret prefix='' name='' args='' blocktype=block['block'] if blocktype=='program': return '' argsl = [] if 'name' in block: name=block['name'] if 'args' in block: vars = block['vars'] for a in block['args']: a = expr2name(a, block, argsl) if not isintent_callback(vars[a]): argsl.append(a) if block['block']=='function' or argsl: args='(%s)'%','.join(argsl) f2pyenhancements = '' if 'f2pyenhancements' in block: for k in list(block['f2pyenhancements'].keys()): f2pyenhancements = '%s%s%s %s'%(f2pyenhancements, tab+tabchar, k, block['f2pyenhancements'][k]) intent_lst = block.get('intent', [])[:] if blocktype=='function' and 'callback' in intent_lst: intent_lst.remove('callback') if intent_lst: f2pyenhancements = '%s%sintent(%s) %s'%\ (f2pyenhancements, tab+tabchar, ','.join(intent_lst), name) use='' if 'use' in block: use=use2fortran(block['use'], tab+tabchar) common='' if 'common' in block: common=common2fortran(block['common'], tab+tabchar) if name=='unknown_interface': name='' result='' if 'result' in block: result=' result (%s)'%block['result'] if block['result'] not in argsl: argsl.append(block['result']) #if 'prefix' in block: # prefix=block['prefix']+' ' body=crack2fortrangen(block['body'], tab+tabchar) vars=vars2fortran(block, block['vars'], argsl, tab+tabchar, as_interface=as_interface) mess='' if 'from' in block and not as_interface: mess='! in %s'%block['from'] if 'entry' in block: entry_stmts = '' for k, i in list(block['entry'].items()): entry_stmts = '%s%sentry %s(%s)' \ % (entry_stmts, tab+tabchar, k, ','.join(i)) body = body + entry_stmts if blocktype=='block data' and name=='_BLOCK_DATA_': name = '' ret='%s%s%s %s%s%s %s%s%s%s%s%s%send %s %s'%(tab, prefix, blocktype, name, args, result, mess, f2pyenhancements, use, vars, common, body, tab, blocktype, name) return ret def common2fortran(common,tab=''): ret='' for k in list(common.keys()): if k=='_BLNK_': ret='%s%scommon %s'%(ret, tab, ','.join(common[k])) else: ret='%s%scommon /%s/ %s'%(ret, tab, k, ','.join(common[k])) return ret def use2fortran(use,tab=''): ret='' for m in list(use.keys()): ret='%s%suse %s,'%(ret, tab, m) if use[m]=={}: if ret and ret[-1]==',': ret=ret[:-1] continue if 'only' in use[m] and use[m]['only']: ret='%s only:'%(ret) if 'map' in use[m] and use[m]['map']: c=' ' for k in list(use[m]['map'].keys()): if k==use[m]['map'][k]: ret='%s%s%s'%(ret, c, k); c=',' else: ret='%s%s%s=>%s'%(ret, c, k, use[m]['map'][k]); c=',' if ret and ret[-1]==',': ret=ret[:-1] return ret def true_intent_list(var): lst = var['intent'] ret = [] for intent in lst: try: c = eval('isintent_%s(var)' % intent) except NameError: c = 0 if c: ret.append(intent) return ret def vars2fortran(block,vars,args,tab='', as_interface=False): """ TODO: public sub ... """ setmesstext(block) ret='' nout=[] for a in args: if a in block['vars']: nout.append(a) if 'commonvars' in block: for a in block['commonvars']: if a in vars: if a not in nout: nout.append(a) else: errmess('vars2fortran: Confused?!: "%s" is not defined in vars.\n'%a) if 'varnames' in block: nout.extend(block['varnames']) if not as_interface: for a in list(vars.keys()): if a not in nout: nout.append(a) for a in nout: if 'depend' in vars[a]: for d in vars[a]['depend']: if d in vars and 'depend' in vars[d] and a in vars[d]['depend']: errmess('vars2fortran: Warning: cross-dependence between variables "%s" and "%s"\n'%(a, d)) if 'externals' in block and a in block['externals']: if isintent_callback(vars[a]): ret='%s%sintent(callback) %s'%(ret, tab, a) ret='%s%sexternal %s'%(ret, tab, a) if isoptional(vars[a]): ret='%s%soptional %s'%(ret, tab, a) if a in vars and 'typespec' not in vars[a]: continue cont=1 for b in block['body']: if a==b['name'] and b['block']=='function': cont=0;break if cont: continue if a not in vars: show(vars) outmess('vars2fortran: No definition for argument "%s".\n'%a) continue if a==block['name'] and not block['block']=='function': continue if 'typespec' not in vars[a]: if 'attrspec' in vars[a] and 'external' in vars[a]['attrspec']: if a in args: ret='%s%sexternal %s'%(ret, tab, a) continue show(vars[a]) outmess('vars2fortran: No typespec for argument "%s".\n'%a) continue vardef=vars[a]['typespec'] if vardef=='type' and 'typename' in vars[a]: vardef='%s(%s)'%(vardef, vars[a]['typename']) selector={} if 'kindselector' in vars[a]: selector=vars[a]['kindselector'] elif 'charselector' in vars[a]: selector=vars[a]['charselector'] if '*' in selector: if selector['*'] in ['*', ':']: vardef='%s*(%s)'%(vardef, selector['*']) else: vardef='%s*%s'%(vardef, selector['*']) else: if 'len' in selector: vardef='%s(len=%s'%(vardef, selector['len']) if 'kind' in selector: vardef='%s,kind=%s)'%(vardef, selector['kind']) else: vardef='%s)'%(vardef) elif 'kind' in selector: vardef='%s(kind=%s)'%(vardef, selector['kind']) c=' ' if 'attrspec' in vars[a]: attr=[] for l in vars[a]['attrspec']: if l not in ['external']: attr.append(l) if attr: vardef='%s, %s'%(vardef, ','.join(attr)) c=',' if 'dimension' in vars[a]: # if not isintent_c(vars[a]): # vars[a]['dimension'].reverse() vardef='%s%sdimension(%s)'%(vardef, c, ','.join(vars[a]['dimension'])) c=',' if 'intent' in vars[a]: lst = true_intent_list(vars[a]) if lst: vardef='%s%sintent(%s)'%(vardef, c, ','.join(lst)) c=',' if 'check' in vars[a]: vardef='%s%scheck(%s)'%(vardef, c, ','.join(vars[a]['check'])) c=',' if 'depend' in vars[a]: vardef='%s%sdepend(%s)'%(vardef, c, ','.join(vars[a]['depend'])) c=',' if '=' in vars[a]: v = vars[a]['='] if vars[a]['typespec'] in ['complex', 'double complex']: try: v = eval(v) v = '(%s,%s)' % (v.real, v.imag) except: pass vardef='%s :: %s=%s'%(vardef, a, v) else: vardef='%s :: %s'%(vardef, a) ret='%s%s%s'%(ret, tab, vardef) return ret ###### def crackfortran(files): global usermodules outmess('Reading fortran codes...\n', 0) readfortrancode(files, crackline) outmess('Post-processing...\n', 0) usermodules=[] postlist=postcrack(grouplist[0]) outmess('Post-processing (stage 2)...\n', 0) postlist=postcrack2(postlist) return usermodules+postlist def crack2fortran(block): global f2py_version pyf=crack2fortrangen(block)+'\n' header="""! -*- f90 -*- ! Note: the context of this file is case sensitive. """ footer=""" ! This file was auto-generated with f2py (version:%s). ! See http://cens.ioc.ee/projects/f2py2e/ """%(f2py_version) return header+pyf+footer if __name__ == "__main__": files=[] funcs=[] f=1;f2=0;f3=0 showblocklist=0 for l in sys.argv[1:]: if l=='': pass elif l[0]==':': f=0 elif l=='-quiet': quiet=1 verbose=0 elif l=='-verbose': verbose=2 quiet=0 elif l=='-fix': if strictf77: outmess('Use option -f90 before -fix if Fortran 90 code is in fix form.\n', 0) skipemptyends=1 sourcecodeform='fix' elif l=='-skipemptyends': skipemptyends=1 elif l=='--ignore-contains': ignorecontains=1 elif l=='-f77': strictf77=1 sourcecodeform='fix' elif l=='-f90': strictf77=0 sourcecodeform='free' skipemptyends=1 elif l=='-h': f2=1 elif l=='-show': showblocklist=1 elif l=='-m': f3=1 elif l[0]=='-': errmess('Unknown option %s\n'%repr(l)) elif f2: f2=0 pyffilename=l elif f3: f3=0 f77modulename=l elif f: try: open(l).close() files.append(l) except IOError as detail: errmess('IOError: %s\n'%str(detail)) else: funcs.append(l) if not strictf77 and f77modulename and not skipemptyends: outmess("""\ Warning: You have specifyied module name for non Fortran 77 code that should not need one (expect if you are scanning F90 code for non module blocks but then you should use flag -skipemptyends and also be sure that the files do not contain programs without program statement). """, 0) postlist=crackfortran(files, funcs) if pyffilename: outmess('Writing fortran code to file %s\n'%repr(pyffilename), 0) pyf=crack2fortran(postlist) f=open(pyffilename, 'w') f.write(pyf) f.close() if showblocklist: show(postlist) numpy-1.8.2/numpy/f2py/cfuncs.py0000664000175100017510000012234012370216243017711 0ustar vagrantvagrant00000000000000#!/usr/bin/env python """ C declarations, CPP macros, and C functions for f2py2e. Only required declarations/macros/functions will be used. Copyright 1999,2000 Pearu Peterson all rights reserved, Pearu Peterson Permission to use, modify, and distribute this software is given under the terms of the NumPy License. NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. $Date: 2005/05/06 11:42:34 $ Pearu Peterson """ from __future__ import division, absolute_import, print_function import sys import copy from . import __version__ f2py_version = __version__.version errmess = sys.stderr.write ##################### Definitions ################## outneeds={'includes0':[],'includes':[],'typedefs':[],'typedefs_generated':[], 'userincludes':[], 'cppmacros':[],'cfuncs':[],'callbacks':[],'f90modhooks':[], 'commonhooks':[]} needs={} includes0={'includes0':'/*need_includes0*/'} includes={'includes':'/*need_includes*/'} userincludes={'userincludes':'/*need_userincludes*/'} typedefs={'typedefs':'/*need_typedefs*/'} typedefs_generated={'typedefs_generated':'/*need_typedefs_generated*/'} cppmacros={'cppmacros':'/*need_cppmacros*/'} cfuncs={'cfuncs':'/*need_cfuncs*/'} callbacks={'callbacks':'/*need_callbacks*/'} f90modhooks={'f90modhooks': '/*need_f90modhooks*/', 'initf90modhooksstatic': '/*initf90modhooksstatic*/', 'initf90modhooksdynamic': '/*initf90modhooksdynamic*/', } commonhooks={'commonhooks': '/*need_commonhooks*/', 'initcommonhooks': '/*need_initcommonhooks*/', } ############ Includes ################### includes0['math.h']='#include ' includes0['string.h']='#include ' includes0['setjmp.h']='#include ' includes['Python.h']='#include "Python.h"' needs['arrayobject.h']=['Python.h'] includes['arrayobject.h']='''#define PY_ARRAY_UNIQUE_SYMBOL PyArray_API #include "arrayobject.h"''' includes['arrayobject.h']='#include "fortranobject.h"' includes['stdarg.h']='#include ' ############# Type definitions ############### typedefs['unsigned_char']='typedef unsigned char unsigned_char;' typedefs['unsigned_short']='typedef unsigned short unsigned_short;' typedefs['unsigned_long']='typedef unsigned long unsigned_long;' typedefs['signed_char']='typedef signed char signed_char;' typedefs['long_long']="""\ #ifdef _WIN32 typedef __int64 long_long; #else typedef long long long_long; typedef unsigned long long unsigned_long_long; #endif """ typedefs['insinged_long_long']="""\ #ifdef _WIN32 typedef __uint64 long_long; #else typedef unsigned long long unsigned_long_long; #endif """ typedefs['long_double']="""\ #ifndef _LONG_DOUBLE typedef long double long_double; #endif """ typedefs['complex_long_double']='typedef struct {long double r,i;} complex_long_double;' typedefs['complex_float']='typedef struct {float r,i;} complex_float;' typedefs['complex_double']='typedef struct {double r,i;} complex_double;' typedefs['string']="""typedef char * string;""" ############### CPP macros #################### cppmacros['CFUNCSMESS']="""\ #ifdef DEBUGCFUNCS #define CFUNCSMESS(mess) fprintf(stderr,\"debug-capi:\"mess); #define CFUNCSMESSPY(mess,obj) CFUNCSMESS(mess) \\ \tPyObject_Print((PyObject *)obj,stderr,Py_PRINT_RAW);\\ \tfprintf(stderr,\"\\n\"); #else #define CFUNCSMESS(mess) #define CFUNCSMESSPY(mess,obj) #endif """ cppmacros['F_FUNC']="""\ #if defined(PREPEND_FORTRAN) #if defined(NO_APPEND_FORTRAN) #if defined(UPPERCASE_FORTRAN) #define F_FUNC(f,F) _##F #else #define F_FUNC(f,F) _##f #endif #else #if defined(UPPERCASE_FORTRAN) #define F_FUNC(f,F) _##F##_ #else #define F_FUNC(f,F) _##f##_ #endif #endif #else #if defined(NO_APPEND_FORTRAN) #if defined(UPPERCASE_FORTRAN) #define F_FUNC(f,F) F #else #define F_FUNC(f,F) f #endif #else #if defined(UPPERCASE_FORTRAN) #define F_FUNC(f,F) F##_ #else #define F_FUNC(f,F) f##_ #endif #endif #endif #if defined(UNDERSCORE_G77) #define F_FUNC_US(f,F) F_FUNC(f##_,F##_) #else #define F_FUNC_US(f,F) F_FUNC(f,F) #endif """ cppmacros['F_WRAPPEDFUNC']="""\ #if defined(PREPEND_FORTRAN) #if defined(NO_APPEND_FORTRAN) #if defined(UPPERCASE_FORTRAN) #define F_WRAPPEDFUNC(f,F) _F2PYWRAP##F #else #define F_WRAPPEDFUNC(f,F) _f2pywrap##f #endif #else #if defined(UPPERCASE_FORTRAN) #define F_WRAPPEDFUNC(f,F) _F2PYWRAP##F##_ #else #define F_WRAPPEDFUNC(f,F) _f2pywrap##f##_ #endif #endif #else #if defined(NO_APPEND_FORTRAN) #if defined(UPPERCASE_FORTRAN) #define F_WRAPPEDFUNC(f,F) F2PYWRAP##F #else #define F_WRAPPEDFUNC(f,F) f2pywrap##f #endif #else #if defined(UPPERCASE_FORTRAN) #define F_WRAPPEDFUNC(f,F) F2PYWRAP##F##_ #else #define F_WRAPPEDFUNC(f,F) f2pywrap##f##_ #endif #endif #endif #if defined(UNDERSCORE_G77) #define F_WRAPPEDFUNC_US(f,F) F_WRAPPEDFUNC(f##_,F##_) #else #define F_WRAPPEDFUNC_US(f,F) F_WRAPPEDFUNC(f,F) #endif """ cppmacros['F_MODFUNC']="""\ #if defined(F90MOD2CCONV1) /*E.g. Compaq Fortran */ #if defined(NO_APPEND_FORTRAN) #define F_MODFUNCNAME(m,f) $ ## m ## $ ## f #else #define F_MODFUNCNAME(m,f) $ ## m ## $ ## f ## _ #endif #endif #if defined(F90MOD2CCONV2) /*E.g. IBM XL Fortran, not tested though */ #if defined(NO_APPEND_FORTRAN) #define F_MODFUNCNAME(m,f) __ ## m ## _MOD_ ## f #else #define F_MODFUNCNAME(m,f) __ ## m ## _MOD_ ## f ## _ #endif #endif #if defined(F90MOD2CCONV3) /*E.g. MIPSPro Compilers */ #if defined(NO_APPEND_FORTRAN) #define F_MODFUNCNAME(m,f) f ## .in. ## m #else #define F_MODFUNCNAME(m,f) f ## .in. ## m ## _ #endif #endif /* #if defined(UPPERCASE_FORTRAN) #define F_MODFUNC(m,M,f,F) F_MODFUNCNAME(M,F) #else #define F_MODFUNC(m,M,f,F) F_MODFUNCNAME(m,f) #endif */ #define F_MODFUNC(m,f) (*(f2pymodstruct##m##.##f)) """ cppmacros['SWAPUNSAFE']="""\ #define SWAP(a,b) (size_t)(a) = ((size_t)(a) ^ (size_t)(b));\\ (size_t)(b) = ((size_t)(a) ^ (size_t)(b));\\ (size_t)(a) = ((size_t)(a) ^ (size_t)(b)) """ cppmacros['SWAP']="""\ #define SWAP(a,b,t) {\\ \tt *c;\\ \tc = a;\\ \ta = b;\\ \tb = c;} """ #cppmacros['ISCONTIGUOUS']='#define ISCONTIGUOUS(m) ((m)->flags & NPY_CONTIGUOUS)' cppmacros['PRINTPYOBJERR']="""\ #define PRINTPYOBJERR(obj)\\ \tfprintf(stderr,\"#modulename#.error is related to \");\\ \tPyObject_Print((PyObject *)obj,stderr,Py_PRINT_RAW);\\ \tfprintf(stderr,\"\\n\"); """ cppmacros['MINMAX']="""\ #ifndef max #define max(a,b) ((a > b) ? (a) : (b)) #endif #ifndef min #define min(a,b) ((a < b) ? (a) : (b)) #endif #ifndef MAX #define MAX(a,b) ((a > b) ? (a) : (b)) #endif #ifndef MIN #define MIN(a,b) ((a < b) ? (a) : (b)) #endif """ needs['len..']=['f2py_size'] cppmacros['len..']="""\ #define rank(var) var ## _Rank #define shape(var,dim) var ## _Dims[dim] #define old_rank(var) (((PyArrayObject *)(capi_ ## var ## _tmp))->nd) #define old_shape(var,dim) (((PyArrayObject *)(capi_ ## var ## _tmp))->dimensions[dim]) #define fshape(var,dim) shape(var,rank(var)-dim-1) #define len(var) shape(var,0) #define flen(var) fshape(var,0) #define old_size(var) PyArray_SIZE((PyArrayObject *)(capi_ ## var ## _tmp)) /* #define index(i) capi_i ## i */ #define slen(var) capi_ ## var ## _len #define size(var, ...) f2py_size((PyArrayObject *)(capi_ ## var ## _tmp), ## __VA_ARGS__, -1) """ needs['f2py_size']=['stdarg.h'] cfuncs['f2py_size']="""\ static int f2py_size(PyArrayObject* var, ...) { npy_int sz = 0; npy_int dim; npy_int rank; va_list argp; va_start(argp, var); dim = va_arg(argp, npy_int); if (dim==-1) { sz = PyArray_SIZE(var); } else { rank = PyArray_NDIM(var); if (dim>=1 && dim<=rank) sz = PyArray_DIM(var, dim-1); else fprintf(stderr, \"f2py_size: 2nd argument value=%d fails to satisfy 1<=value<=%d. Result will be 0.\\n\", dim, rank); } va_end(argp); return sz; } """ cppmacros['pyobj_from_char1']='#define pyobj_from_char1(v) (PyInt_FromLong(v))' cppmacros['pyobj_from_short1']='#define pyobj_from_short1(v) (PyInt_FromLong(v))' needs['pyobj_from_int1']=['signed_char'] cppmacros['pyobj_from_int1']='#define pyobj_from_int1(v) (PyInt_FromLong(v))' cppmacros['pyobj_from_long1']='#define pyobj_from_long1(v) (PyLong_FromLong(v))' needs['pyobj_from_long_long1']=['long_long'] cppmacros['pyobj_from_long_long1']="""\ #ifdef HAVE_LONG_LONG #define pyobj_from_long_long1(v) (PyLong_FromLongLong(v)) #else #warning HAVE_LONG_LONG is not available. Redefining pyobj_from_long_long. #define pyobj_from_long_long1(v) (PyLong_FromLong(v)) #endif """ needs['pyobj_from_long_double1']=['long_double'] cppmacros['pyobj_from_long_double1']='#define pyobj_from_long_double1(v) (PyFloat_FromDouble(v))' cppmacros['pyobj_from_double1']='#define pyobj_from_double1(v) (PyFloat_FromDouble(v))' cppmacros['pyobj_from_float1']='#define pyobj_from_float1(v) (PyFloat_FromDouble(v))' needs['pyobj_from_complex_long_double1']=['complex_long_double'] cppmacros['pyobj_from_complex_long_double1']='#define pyobj_from_complex_long_double1(v) (PyComplex_FromDoubles(v.r,v.i))' needs['pyobj_from_complex_double1']=['complex_double'] cppmacros['pyobj_from_complex_double1']='#define pyobj_from_complex_double1(v) (PyComplex_FromDoubles(v.r,v.i))' needs['pyobj_from_complex_float1']=['complex_float'] cppmacros['pyobj_from_complex_float1']='#define pyobj_from_complex_float1(v) (PyComplex_FromDoubles(v.r,v.i))' 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))' needs['TRYPYARRAYTEMPLATE']=['PRINTPYOBJERR'] cppmacros['TRYPYARRAYTEMPLATE']="""\ /* New SciPy */ #define TRYPYARRAYTEMPLATECHAR case NPY_STRING: *(char *)(arr->data)=*v; break; #define TRYPYARRAYTEMPLATELONG case NPY_LONG: *(long *)(arr->data)=*v; break; #define TRYPYARRAYTEMPLATEOBJECT case NPY_OBJECT: (arr->descr->f->setitem)(pyobj_from_ ## ctype ## 1(*v),arr->data); break; #define TRYPYARRAYTEMPLATE(ctype,typecode) \\ PyArrayObject *arr = NULL;\\ if (!obj) return -2;\\ if (!PyArray_Check(obj)) return -1;\\ if (!(arr=(PyArrayObject *)obj)) {fprintf(stderr,\"TRYPYARRAYTEMPLATE:\");PRINTPYOBJERR(obj);return 0;}\\ if (arr->descr->type==typecode) {*(ctype *)(arr->data)=*v; return 1;}\\ switch (arr->descr->type_num) {\\ case NPY_DOUBLE: *(double *)(arr->data)=*v; break;\\ case NPY_INT: *(int *)(arr->data)=*v; break;\\ case NPY_LONG: *(long *)(arr->data)=*v; break;\\ case NPY_FLOAT: *(float *)(arr->data)=*v; break;\\ case NPY_CDOUBLE: *(double *)(arr->data)=*v; break;\\ case NPY_CFLOAT: *(float *)(arr->data)=*v; break;\\ case NPY_BOOL: *(npy_bool *)(arr->data)=(*v!=0); break;\\ case NPY_UBYTE: *(unsigned char *)(arr->data)=*v; break;\\ case NPY_BYTE: *(signed char *)(arr->data)=*v; break;\\ case NPY_SHORT: *(short *)(arr->data)=*v; break;\\ case NPY_USHORT: *(npy_ushort *)(arr->data)=*v; break;\\ case NPY_UINT: *(npy_uint *)(arr->data)=*v; break;\\ case NPY_ULONG: *(npy_ulong *)(arr->data)=*v; break;\\ case NPY_LONGLONG: *(npy_longlong *)(arr->data)=*v; break;\\ case NPY_ULONGLONG: *(npy_ulonglong *)(arr->data)=*v; break;\\ case NPY_LONGDOUBLE: *(npy_longdouble *)(arr->data)=*v; break;\\ case NPY_CLONGDOUBLE: *(npy_longdouble *)(arr->data)=*v; break;\\ case NPY_OBJECT: (arr->descr->f->setitem)(pyobj_from_ ## ctype ## 1(*v),arr->data, arr); break;\\ default: return -2;\\ };\\ return 1 """ needs['TRYCOMPLEXPYARRAYTEMPLATE']=['PRINTPYOBJERR'] cppmacros['TRYCOMPLEXPYARRAYTEMPLATE']="""\ #define TRYCOMPLEXPYARRAYTEMPLATEOBJECT case NPY_OBJECT: (arr->descr->f->setitem)(pyobj_from_complex_ ## ctype ## 1((*v)),arr->data, arr); break; #define TRYCOMPLEXPYARRAYTEMPLATE(ctype,typecode)\\ PyArrayObject *arr = NULL;\\ if (!obj) return -2;\\ if (!PyArray_Check(obj)) return -1;\\ if (!(arr=(PyArrayObject *)obj)) {fprintf(stderr,\"TRYCOMPLEXPYARRAYTEMPLATE:\");PRINTPYOBJERR(obj);return 0;}\\ if (arr->descr->type==typecode) {\\ *(ctype *)(arr->data)=(*v).r;\\ *(ctype *)(arr->data+sizeof(ctype))=(*v).i;\\ return 1;\\ }\\ switch (arr->descr->type_num) {\\ case NPY_CDOUBLE: *(double *)(arr->data)=(*v).r;*(double *)(arr->data+sizeof(double))=(*v).i;break;\\ case NPY_CFLOAT: *(float *)(arr->data)=(*v).r;*(float *)(arr->data+sizeof(float))=(*v).i;break;\\ case NPY_DOUBLE: *(double *)(arr->data)=(*v).r; break;\\ case NPY_LONG: *(long *)(arr->data)=(*v).r; break;\\ case NPY_FLOAT: *(float *)(arr->data)=(*v).r; break;\\ case NPY_INT: *(int *)(arr->data)=(*v).r; break;\\ case NPY_SHORT: *(short *)(arr->data)=(*v).r; break;\\ case NPY_UBYTE: *(unsigned char *)(arr->data)=(*v).r; break;\\ case NPY_BYTE: *(signed char *)(arr->data)=(*v).r; break;\\ case NPY_BOOL: *(npy_bool *)(arr->data)=((*v).r!=0 && (*v).i!=0); break;\\ case NPY_USHORT: *(npy_ushort *)(arr->data)=(*v).r; break;\\ case NPY_UINT: *(npy_uint *)(arr->data)=(*v).r; break;\\ case NPY_ULONG: *(npy_ulong *)(arr->data)=(*v).r; break;\\ case NPY_LONGLONG: *(npy_longlong *)(arr->data)=(*v).r; break;\\ case NPY_ULONGLONG: *(npy_ulonglong *)(arr->data)=(*v).r; break;\\ case NPY_LONGDOUBLE: *(npy_longdouble *)(arr->data)=(*v).r; break;\\ case NPY_CLONGDOUBLE: *(npy_longdouble *)(arr->data)=(*v).r;*(npy_longdouble *)(arr->data+sizeof(npy_longdouble))=(*v).i;break;\\ case NPY_OBJECT: (arr->descr->f->setitem)(pyobj_from_complex_ ## ctype ## 1((*v)),arr->data, arr); break;\\ default: return -2;\\ };\\ return -1; """ ## cppmacros['NUMFROMARROBJ']="""\ ## #define NUMFROMARROBJ(typenum,ctype) \\ ## \tif (PyArray_Check(obj)) arr = (PyArrayObject *)obj;\\ ## \telse arr = (PyArrayObject *)PyArray_ContiguousFromObject(obj,typenum,0,0);\\ ## \tif (arr) {\\ ## \t\tif (arr->descr->type_num==NPY_OBJECT) {\\ ## \t\t\tif (!ctype ## _from_pyobj(v,(arr->descr->getitem)(arr->data),\"\"))\\ ## \t\t\tgoto capi_fail;\\ ## \t\t} else {\\ ## \t\t\t(arr->descr->cast[typenum])(arr->data,1,(char*)v,1,1);\\ ## \t\t}\\ ## \t\tif ((PyObject *)arr != obj) { Py_DECREF(arr); }\\ ## \t\treturn 1;\\ ## \t} ## """ ## #XXX: Note that CNUMFROMARROBJ is identical with NUMFROMARROBJ ## cppmacros['CNUMFROMARROBJ']="""\ ## #define CNUMFROMARROBJ(typenum,ctype) \\ ## \tif (PyArray_Check(obj)) arr = (PyArrayObject *)obj;\\ ## \telse arr = (PyArrayObject *)PyArray_ContiguousFromObject(obj,typenum,0,0);\\ ## \tif (arr) {\\ ## \t\tif (arr->descr->type_num==NPY_OBJECT) {\\ ## \t\t\tif (!ctype ## _from_pyobj(v,(arr->descr->getitem)(arr->data),\"\"))\\ ## \t\t\tgoto capi_fail;\\ ## \t\t} else {\\ ## \t\t\t(arr->descr->cast[typenum])((void *)(arr->data),1,(void *)(v),1,1);\\ ## \t\t}\\ ## \t\tif ((PyObject *)arr != obj) { Py_DECREF(arr); }\\ ## \t\treturn 1;\\ ## \t} ## """ needs['GETSTRFROMPYTUPLE']=['STRINGCOPYN', 'PRINTPYOBJERR'] cppmacros['GETSTRFROMPYTUPLE']="""\ #define GETSTRFROMPYTUPLE(tuple,index,str,len) {\\ \t\tPyObject *rv_cb_str = PyTuple_GetItem((tuple),(index));\\ \t\tif (rv_cb_str == NULL)\\ \t\t\tgoto capi_fail;\\ \t\tif (PyString_Check(rv_cb_str)) {\\ \t\t\tstr[len-1]='\\0';\\ \t\t\tSTRINGCOPYN((str),PyString_AS_STRING((PyStringObject*)rv_cb_str),(len));\\ \t\t} else {\\ \t\t\tPRINTPYOBJERR(rv_cb_str);\\ \t\t\tPyErr_SetString(#modulename#_error,\"string object expected\");\\ \t\t\tgoto capi_fail;\\ \t\t}\\ \t} """ cppmacros['GETSCALARFROMPYTUPLE']="""\ #define GETSCALARFROMPYTUPLE(tuple,index,var,ctype,mess) {\\ \t\tif ((capi_tmp = PyTuple_GetItem((tuple),(index)))==NULL) goto capi_fail;\\ \t\tif (!(ctype ## _from_pyobj((var),capi_tmp,mess)))\\ \t\t\tgoto capi_fail;\\ \t} """ cppmacros['FAILNULL']="""\\ #define FAILNULL(p) do { \\ if ((p) == NULL) { \\ PyErr_SetString(PyExc_MemoryError, "NULL pointer found"); \\ goto capi_fail; \\ } \\ } while (0) """ needs['MEMCOPY']=['string.h', 'FAILNULL'] cppmacros['MEMCOPY']="""\ #define MEMCOPY(to,from,n)\\ do { FAILNULL(to); FAILNULL(from); (void)memcpy(to,from,n); } while (0) """ cppmacros['STRINGMALLOC']="""\ #define STRINGMALLOC(str,len)\\ \tif ((str = (string)malloc(sizeof(char)*(len+1))) == NULL) {\\ \t\tPyErr_SetString(PyExc_MemoryError, \"out of memory\");\\ \t\tgoto capi_fail;\\ \t} else {\\ \t\t(str)[len] = '\\0';\\ \t} """ cppmacros['STRINGFREE']="""\ #define STRINGFREE(str) do {if (!(str == NULL)) free(str);} while (0) """ needs['STRINGCOPYN']=['string.h', 'FAILNULL'] cppmacros['STRINGCOPYN']="""\ #define STRINGCOPYN(to,from,buf_size) \\ do { \\ int _m = (buf_size); \\ char *_to = (to); \\ char *_from = (from); \\ FAILNULL(_to); FAILNULL(_from); \\ (void)strncpy(_to, _from, sizeof(char)*_m); \\ _to[_m-1] = '\\0'; \\ /* Padding with spaces instead of nulls */ \\ for (_m -= 2; _m >= 0 && _to[_m] == '\\0'; _m--) { \\ _to[_m] = ' '; \\ } \\ } while (0) """ needs['STRINGCOPY']=['string.h', 'FAILNULL'] cppmacros['STRINGCOPY']="""\ #define STRINGCOPY(to,from)\\ do { FAILNULL(to); FAILNULL(from); (void)strcpy(to,from); } while (0) """ cppmacros['CHECKGENERIC']="""\ #define CHECKGENERIC(check,tcheck,name) \\ \tif (!(check)) {\\ \t\tPyErr_SetString(#modulename#_error,\"(\"tcheck\") failed for \"name);\\ \t\t/*goto capi_fail;*/\\ \t} else """ cppmacros['CHECKARRAY']="""\ #define CHECKARRAY(check,tcheck,name) \\ \tif (!(check)) {\\ \t\tPyErr_SetString(#modulename#_error,\"(\"tcheck\") failed for \"name);\\ \t\t/*goto capi_fail;*/\\ \t} else """ cppmacros['CHECKSTRING']="""\ #define CHECKSTRING(check,tcheck,name,show,var)\\ \tif (!(check)) {\\ \t\tchar errstring[256];\\ \t\tsprintf(errstring, \"%s: \"show, \"(\"tcheck\") failed for \"name, slen(var), var);\\ \t\tPyErr_SetString(#modulename#_error, errstring);\\ \t\t/*goto capi_fail;*/\\ \t} else """ cppmacros['CHECKSCALAR']="""\ #define CHECKSCALAR(check,tcheck,name,show,var)\\ \tif (!(check)) {\\ \t\tchar errstring[256];\\ \t\tsprintf(errstring, \"%s: \"show, \"(\"tcheck\") failed for \"name, var);\\ \t\tPyErr_SetString(#modulename#_error,errstring);\\ \t\t/*goto capi_fail;*/\\ \t} else """ ## cppmacros['CHECKDIMS']="""\ ## #define CHECKDIMS(dims,rank) \\ ## \tfor (int i=0;i<(rank);i++)\\ ## \t\tif (dims[i]<0) {\\ ## \t\t\tfprintf(stderr,\"Unspecified array argument requires a complete dimension specification.\\n\");\\ ## \t\t\tgoto capi_fail;\\ ## \t\t} ## """ cppmacros['ARRSIZE']='#define ARRSIZE(dims,rank) (_PyArray_multiply_list(dims,rank))' cppmacros['OLDPYNUM']="""\ #ifdef OLDPYNUM #error You need to intall Numeric Python version 13 or higher. Get it from http:/sourceforge.net/project/?group_id=1369 #endif """ ################# C functions ############### cfuncs['calcarrindex']="""\ static int calcarrindex(int *i,PyArrayObject *arr) { \tint k,ii = i[0]; \tfor (k=1; k < arr->nd; k++) \t\tii += (ii*(arr->dimensions[k] - 1)+i[k]); /* assuming contiguous arr */ \treturn ii; }""" cfuncs['calcarrindextr']="""\ static int calcarrindextr(int *i,PyArrayObject *arr) { \tint k,ii = i[arr->nd-1]; \tfor (k=1; k < arr->nd; k++) \t\tii += (ii*(arr->dimensions[arr->nd-k-1] - 1)+i[arr->nd-k-1]); /* assuming contiguous arr */ \treturn ii; }""" cfuncs['forcomb']="""\ static struct { int nd;npy_intp *d;int *i,*i_tr,tr; } forcombcache; static int initforcomb(npy_intp *dims,int nd,int tr) { int k; if (dims==NULL) return 0; if (nd<0) return 0; forcombcache.nd = nd; forcombcache.d = dims; forcombcache.tr = tr; if ((forcombcache.i = (int *)malloc(sizeof(int)*nd))==NULL) return 0; if ((forcombcache.i_tr = (int *)malloc(sizeof(int)*nd))==NULL) return 0; for (k=1;kdata,str,PyArray_NBYTES(arr)); } \treturn 1; capi_fail: \tPRINTPYOBJERR(obj); \tPyErr_SetString(#modulename#_error,\"try_pyarr_from_string failed\"); \treturn 0; } """ needs['string_from_pyobj']=['string', 'STRINGMALLOC', 'STRINGCOPYN'] cfuncs['string_from_pyobj']="""\ static int string_from_pyobj(string *str,int *len,const string inistr,PyObject *obj,const char *errmess) { \tPyArrayObject *arr = NULL; \tPyObject *tmp = NULL; #ifdef DEBUGCFUNCS fprintf(stderr,\"string_from_pyobj(str='%s',len=%d,inistr='%s',obj=%p)\\n\",(char*)str,*len,(char *)inistr,obj); #endif \tif (obj == Py_None) { \t\tif (*len == -1) \t\t\t*len = strlen(inistr); /* Will this cause problems? */ \t\tSTRINGMALLOC(*str,*len); \t\tSTRINGCOPYN(*str,inistr,*len+1); \t\treturn 1; \t} \tif (PyArray_Check(obj)) { \t\tif ((arr = (PyArrayObject *)obj) == NULL) \t\t\tgoto capi_fail; \t\tif (!ISCONTIGUOUS(arr)) { \t\t\tPyErr_SetString(PyExc_ValueError,\"array object is non-contiguous.\"); \t\t\tgoto capi_fail; \t\t} \t\tif (*len == -1) \t\t\t*len = (arr->descr->elsize)*PyArray_SIZE(arr); \t\tSTRINGMALLOC(*str,*len); \t\tSTRINGCOPYN(*str,arr->data,*len+1); \t\treturn 1; \t} \tif (PyString_Check(obj)) { \t\ttmp = obj; \t\tPy_INCREF(tmp); \t} #if PY_VERSION_HEX >= 0x03000000 \telse if (PyUnicode_Check(obj)) { \t\ttmp = PyUnicode_AsASCIIString(obj); \t} \telse { \t\tPyObject *tmp2; \t\ttmp2 = PyObject_Str(obj); \t\tif (tmp2) { \t\t\ttmp = PyUnicode_AsASCIIString(tmp2); \t\t\tPy_DECREF(tmp2); \t\t} \t\telse { \t\t\ttmp = NULL; \t\t} \t} #else \telse { \t\ttmp = PyObject_Str(obj); \t} #endif \tif (tmp == NULL) goto capi_fail; \tif (*len == -1) \t\t*len = PyString_GET_SIZE(tmp); \tSTRINGMALLOC(*str,*len); \tSTRINGCOPYN(*str,PyString_AS_STRING(tmp),*len+1); \tPy_DECREF(tmp); \treturn 1; capi_fail: \tPy_XDECREF(tmp); \t{ \t\tPyObject* err = PyErr_Occurred(); \t\tif (err==NULL) err = #modulename#_error; \t\tPyErr_SetString(err,errmess); \t} \treturn 0; } """ needs['char_from_pyobj']=['int_from_pyobj'] cfuncs['char_from_pyobj']="""\ static int char_from_pyobj(char* v,PyObject *obj,const char *errmess) { \tint i=0; \tif (int_from_pyobj(&i,obj,errmess)) { \t\t*v = (char)i; \t\treturn 1; \t} \treturn 0; } """ needs['signed_char_from_pyobj']=['int_from_pyobj', 'signed_char'] cfuncs['signed_char_from_pyobj']="""\ static int signed_char_from_pyobj(signed_char* v,PyObject *obj,const char *errmess) { \tint i=0; \tif (int_from_pyobj(&i,obj,errmess)) { \t\t*v = (signed_char)i; \t\treturn 1; \t} \treturn 0; } """ needs['short_from_pyobj']=['int_from_pyobj'] cfuncs['short_from_pyobj']="""\ static int short_from_pyobj(short* v,PyObject *obj,const char *errmess) { \tint i=0; \tif (int_from_pyobj(&i,obj,errmess)) { \t\t*v = (short)i; \t\treturn 1; \t} \treturn 0; } """ cfuncs['int_from_pyobj']="""\ static int int_from_pyobj(int* v,PyObject *obj,const char *errmess) { \tPyObject* tmp = NULL; \tif (PyInt_Check(obj)) { \t\t*v = (int)PyInt_AS_LONG(obj); \t\treturn 1; \t} \ttmp = PyNumber_Int(obj); \tif (tmp) { \t\t*v = PyInt_AS_LONG(tmp); \t\tPy_DECREF(tmp); \t\treturn 1; \t} \tif (PyComplex_Check(obj)) \t\ttmp = PyObject_GetAttrString(obj,\"real\"); \telse if (PyString_Check(obj) || PyUnicode_Check(obj)) \t\t/*pass*/; \telse if (PySequence_Check(obj)) \t\ttmp = PySequence_GetItem(obj,0); \tif (tmp) { \t\tPyErr_Clear(); \t\tif (int_from_pyobj(v,tmp,errmess)) {Py_DECREF(tmp); return 1;} \t\tPy_DECREF(tmp); \t} \t{ \t\tPyObject* err = PyErr_Occurred(); \t\tif (err==NULL) err = #modulename#_error; \t\tPyErr_SetString(err,errmess); \t} \treturn 0; } """ cfuncs['long_from_pyobj']="""\ static int long_from_pyobj(long* v,PyObject *obj,const char *errmess) { \tPyObject* tmp = NULL; \tif (PyInt_Check(obj)) { \t\t*v = PyInt_AS_LONG(obj); \t\treturn 1; \t} \ttmp = PyNumber_Int(obj); \tif (tmp) { \t\t*v = PyInt_AS_LONG(tmp); \t\tPy_DECREF(tmp); \t\treturn 1; \t} \tif (PyComplex_Check(obj)) \t\ttmp = PyObject_GetAttrString(obj,\"real\"); \telse if (PyString_Check(obj) || PyUnicode_Check(obj)) \t\t/*pass*/; \telse if (PySequence_Check(obj)) \t\ttmp = PySequence_GetItem(obj,0); \tif (tmp) { \t\tPyErr_Clear(); \t\tif (long_from_pyobj(v,tmp,errmess)) {Py_DECREF(tmp); return 1;} \t\tPy_DECREF(tmp); \t} \t{ \t\tPyObject* err = PyErr_Occurred(); \t\tif (err==NULL) err = #modulename#_error; \t\tPyErr_SetString(err,errmess); \t} \treturn 0; } """ needs['long_long_from_pyobj']=['long_long'] cfuncs['long_long_from_pyobj']="""\ static int long_long_from_pyobj(long_long* v,PyObject *obj,const char *errmess) { \tPyObject* tmp = NULL; \tif (PyLong_Check(obj)) { \t\t*v = PyLong_AsLongLong(obj); \t\treturn (!PyErr_Occurred()); \t} \tif (PyInt_Check(obj)) { \t\t*v = (long_long)PyInt_AS_LONG(obj); \t\treturn 1; \t} \ttmp = PyNumber_Long(obj); \tif (tmp) { \t\t*v = PyLong_AsLongLong(tmp); \t\tPy_DECREF(tmp); \t\treturn (!PyErr_Occurred()); \t} \tif (PyComplex_Check(obj)) \t\ttmp = PyObject_GetAttrString(obj,\"real\"); \telse if (PyString_Check(obj) || PyUnicode_Check(obj)) \t\t/*pass*/; \telse if (PySequence_Check(obj)) \t\ttmp = PySequence_GetItem(obj,0); \tif (tmp) { \t\tPyErr_Clear(); \t\tif (long_long_from_pyobj(v,tmp,errmess)) {Py_DECREF(tmp); return 1;} \t\tPy_DECREF(tmp); \t} \t{ \t\tPyObject* err = PyErr_Occurred(); \t\tif (err==NULL) err = #modulename#_error; \t\tPyErr_SetString(err,errmess); \t} \treturn 0; } """ needs['long_double_from_pyobj']=['double_from_pyobj', 'long_double'] cfuncs['long_double_from_pyobj']="""\ static int long_double_from_pyobj(long_double* v,PyObject *obj,const char *errmess) { \tdouble d=0; \tif (PyArray_CheckScalar(obj)){ \t\tif PyArray_IsScalar(obj, LongDouble) { \t\t\tPyArray_ScalarAsCtype(obj, v); \t\t\treturn 1; \t\t} \t\telse if (PyArray_Check(obj) && PyArray_TYPE(obj)==NPY_LONGDOUBLE) { \t\t\t(*v) = *((npy_longdouble *)PyArray_DATA(obj)); \t\t\treturn 1; \t\t} \t} \tif (double_from_pyobj(&d,obj,errmess)) { \t\t*v = (long_double)d; \t\treturn 1; \t} \treturn 0; } """ cfuncs['double_from_pyobj']="""\ static int double_from_pyobj(double* v,PyObject *obj,const char *errmess) { \tPyObject* tmp = NULL; \tif (PyFloat_Check(obj)) { #ifdef __sgi \t\t*v = PyFloat_AsDouble(obj); #else \t\t*v = PyFloat_AS_DOUBLE(obj); #endif \t\treturn 1; \t} \ttmp = PyNumber_Float(obj); \tif (tmp) { #ifdef __sgi \t\t*v = PyFloat_AsDouble(tmp); #else \t\t*v = PyFloat_AS_DOUBLE(tmp); #endif \t\tPy_DECREF(tmp); \t\treturn 1; \t} \tif (PyComplex_Check(obj)) \t\ttmp = PyObject_GetAttrString(obj,\"real\"); \telse if (PyString_Check(obj) || PyUnicode_Check(obj)) \t\t/*pass*/; \telse if (PySequence_Check(obj)) \t\ttmp = PySequence_GetItem(obj,0); \tif (tmp) { \t\tPyErr_Clear(); \t\tif (double_from_pyobj(v,tmp,errmess)) {Py_DECREF(tmp); return 1;} \t\tPy_DECREF(tmp); \t} \t{ \t\tPyObject* err = PyErr_Occurred(); \t\tif (err==NULL) err = #modulename#_error; \t\tPyErr_SetString(err,errmess); \t} \treturn 0; } """ needs['float_from_pyobj']=['double_from_pyobj'] cfuncs['float_from_pyobj']="""\ static int float_from_pyobj(float* v,PyObject *obj,const char *errmess) { \tdouble d=0.0; \tif (double_from_pyobj(&d,obj,errmess)) { \t\t*v = (float)d; \t\treturn 1; \t} \treturn 0; } """ needs['complex_long_double_from_pyobj']=['complex_long_double', 'long_double', 'complex_double_from_pyobj'] cfuncs['complex_long_double_from_pyobj']="""\ static int complex_long_double_from_pyobj(complex_long_double* v,PyObject *obj,const char *errmess) { \tcomplex_double cd={0.0,0.0}; \tif (PyArray_CheckScalar(obj)){ \t\tif PyArray_IsScalar(obj, CLongDouble) { \t\t\tPyArray_ScalarAsCtype(obj, v); \t\t\treturn 1; \t\t} \t\telse if (PyArray_Check(obj) && PyArray_TYPE(obj)==NPY_CLONGDOUBLE) { \t\t\t(*v).r = ((npy_clongdouble *)PyArray_DATA(obj))->real; \t\t\t(*v).i = ((npy_clongdouble *)PyArray_DATA(obj))->imag; \t\t\treturn 1; \t\t} \t} \tif (complex_double_from_pyobj(&cd,obj,errmess)) { \t\t(*v).r = (long_double)cd.r; \t\t(*v).i = (long_double)cd.i; \t\treturn 1; \t} \treturn 0; } """ needs['complex_double_from_pyobj']=['complex_double'] cfuncs['complex_double_from_pyobj']="""\ static int complex_double_from_pyobj(complex_double* v,PyObject *obj,const char *errmess) { \tPy_complex c; \tif (PyComplex_Check(obj)) { \t\tc=PyComplex_AsCComplex(obj); \t\t(*v).r=c.real, (*v).i=c.imag; \t\treturn 1; \t} \tif (PyArray_IsScalar(obj, ComplexFloating)) { \t\tif (PyArray_IsScalar(obj, CFloat)) { \t\t\tnpy_cfloat new; \t\t\tPyArray_ScalarAsCtype(obj, &new); \t\t\t(*v).r = (double)new.real; \t\t\t(*v).i = (double)new.imag; \t\t} \t\telse if (PyArray_IsScalar(obj, CLongDouble)) { \t\t\tnpy_clongdouble new; \t\t\tPyArray_ScalarAsCtype(obj, &new); \t\t\t(*v).r = (double)new.real; \t\t\t(*v).i = (double)new.imag; \t\t} \t\telse { /* if (PyArray_IsScalar(obj, CDouble)) */ \t\t\tPyArray_ScalarAsCtype(obj, v); \t\t} \t\treturn 1; \t} \tif (PyArray_CheckScalar(obj)) { /* 0-dim array or still array scalar */ \t\tPyObject *arr; \t\tif (PyArray_Check(obj)) { \t\t\tarr = PyArray_Cast((PyArrayObject *)obj, NPY_CDOUBLE); \t\t} \t\telse { \t\t\tarr = PyArray_FromScalar(obj, PyArray_DescrFromType(NPY_CDOUBLE)); \t\t} \t\tif (arr==NULL) return 0; \t\t(*v).r = ((npy_cdouble *)PyArray_DATA(arr))->real; \t\t(*v).i = ((npy_cdouble *)PyArray_DATA(arr))->imag; \t\treturn 1; \t} \t/* Python does not provide PyNumber_Complex function :-( */ \t(*v).i=0.0; \tif (PyFloat_Check(obj)) { #ifdef __sgi \t\t(*v).r = PyFloat_AsDouble(obj); #else \t\t(*v).r = PyFloat_AS_DOUBLE(obj); #endif \t\treturn 1; \t} \tif (PyInt_Check(obj)) { \t\t(*v).r = (double)PyInt_AS_LONG(obj); \t\treturn 1; \t} \tif (PyLong_Check(obj)) { \t\t(*v).r = PyLong_AsDouble(obj); \t\treturn (!PyErr_Occurred()); \t} \tif (PySequence_Check(obj) && !(PyString_Check(obj) || PyUnicode_Check(obj))) { \t\tPyObject *tmp = PySequence_GetItem(obj,0); \t\tif (tmp) { \t\t\tif (complex_double_from_pyobj(v,tmp,errmess)) { \t\t\t\tPy_DECREF(tmp); \t\t\t\treturn 1; \t\t\t} \t\t\tPy_DECREF(tmp); \t\t} \t} \t{ \t\tPyObject* err = PyErr_Occurred(); \t\tif (err==NULL) \t\t\terr = PyExc_TypeError; \t\tPyErr_SetString(err,errmess); \t} \treturn 0; } """ needs['complex_float_from_pyobj']=['complex_float', 'complex_double_from_pyobj'] cfuncs['complex_float_from_pyobj']="""\ static int complex_float_from_pyobj(complex_float* v,PyObject *obj,const char *errmess) { \tcomplex_double cd={0.0,0.0}; \tif (complex_double_from_pyobj(&cd,obj,errmess)) { \t\t(*v).r = (float)cd.r; \t\t(*v).i = (float)cd.i; \t\treturn 1; \t} \treturn 0; } """ needs['try_pyarr_from_char']=['pyobj_from_char1', 'TRYPYARRAYTEMPLATE'] cfuncs['try_pyarr_from_char']='static int try_pyarr_from_char(PyObject* obj,char* v) {\n\tTRYPYARRAYTEMPLATE(char,\'c\');\n}\n' needs['try_pyarr_from_signed_char']=['TRYPYARRAYTEMPLATE', 'unsigned_char'] cfuncs['try_pyarr_from_unsigned_char']='static int try_pyarr_from_unsigned_char(PyObject* obj,unsigned_char* v) {\n\tTRYPYARRAYTEMPLATE(unsigned_char,\'b\');\n}\n' needs['try_pyarr_from_signed_char']=['TRYPYARRAYTEMPLATE', 'signed_char'] cfuncs['try_pyarr_from_signed_char']='static int try_pyarr_from_signed_char(PyObject* obj,signed_char* v) {\n\tTRYPYARRAYTEMPLATE(signed_char,\'1\');\n}\n' needs['try_pyarr_from_short']=['pyobj_from_short1', 'TRYPYARRAYTEMPLATE'] cfuncs['try_pyarr_from_short']='static int try_pyarr_from_short(PyObject* obj,short* v) {\n\tTRYPYARRAYTEMPLATE(short,\'s\');\n}\n' needs['try_pyarr_from_int']=['pyobj_from_int1', 'TRYPYARRAYTEMPLATE'] cfuncs['try_pyarr_from_int']='static int try_pyarr_from_int(PyObject* obj,int* v) {\n\tTRYPYARRAYTEMPLATE(int,\'i\');\n}\n' needs['try_pyarr_from_long']=['pyobj_from_long1', 'TRYPYARRAYTEMPLATE'] cfuncs['try_pyarr_from_long']='static int try_pyarr_from_long(PyObject* obj,long* v) {\n\tTRYPYARRAYTEMPLATE(long,\'l\');\n}\n' needs['try_pyarr_from_long_long']=['pyobj_from_long_long1', 'TRYPYARRAYTEMPLATE', 'long_long'] cfuncs['try_pyarr_from_long_long']='static int try_pyarr_from_long_long(PyObject* obj,long_long* v) {\n\tTRYPYARRAYTEMPLATE(long_long,\'L\');\n}\n' needs['try_pyarr_from_float']=['pyobj_from_float1', 'TRYPYARRAYTEMPLATE'] cfuncs['try_pyarr_from_float']='static int try_pyarr_from_float(PyObject* obj,float* v) {\n\tTRYPYARRAYTEMPLATE(float,\'f\');\n}\n' needs['try_pyarr_from_double']=['pyobj_from_double1', 'TRYPYARRAYTEMPLATE'] cfuncs['try_pyarr_from_double']='static int try_pyarr_from_double(PyObject* obj,double* v) {\n\tTRYPYARRAYTEMPLATE(double,\'d\');\n}\n' needs['try_pyarr_from_complex_float']=['pyobj_from_complex_float1', 'TRYCOMPLEXPYARRAYTEMPLATE', 'complex_float'] cfuncs['try_pyarr_from_complex_float']='static int try_pyarr_from_complex_float(PyObject* obj,complex_float* v) {\n\tTRYCOMPLEXPYARRAYTEMPLATE(float,\'F\');\n}\n' needs['try_pyarr_from_complex_double']=['pyobj_from_complex_double1', 'TRYCOMPLEXPYARRAYTEMPLATE', 'complex_double'] cfuncs['try_pyarr_from_complex_double']='static int try_pyarr_from_complex_double(PyObject* obj,complex_double* v) {\n\tTRYCOMPLEXPYARRAYTEMPLATE(double,\'D\');\n}\n' needs['create_cb_arglist']=['CFUNCSMESS', 'PRINTPYOBJERR', 'MINMAX'] cfuncs['create_cb_arglist']="""\ static int create_cb_arglist(PyObject* fun,PyTupleObject* xa,const int maxnofargs,const int nofoptargs,int *nofargs,PyTupleObject **args,const char *errmess) { \tPyObject *tmp = NULL; \tPyObject *tmp_fun = NULL; \tint tot,opt,ext,siz,i,di=0; \tCFUNCSMESS(\"create_cb_arglist\\n\"); \ttot=opt=ext=siz=0; \t/* Get the total number of arguments */ \tif (PyFunction_Check(fun)) \t\ttmp_fun = fun; \telse { \t\tdi = 1; \t\tif (PyObject_HasAttrString(fun,\"im_func\")) { \t\t\ttmp_fun = PyObject_GetAttrString(fun,\"im_func\"); \t\t} \t\telse if (PyObject_HasAttrString(fun,\"__call__\")) { \t\t\ttmp = PyObject_GetAttrString(fun,\"__call__\"); \t\t\tif (PyObject_HasAttrString(tmp,\"im_func\")) \t\t\t\ttmp_fun = PyObject_GetAttrString(tmp,\"im_func\"); \t\t\telse { \t\t\t\ttmp_fun = fun; /* built-in function */ \t\t\t\ttot = maxnofargs; \t\t\t\tif (xa != NULL) \t\t\t\t\ttot += PyTuple_Size((PyObject *)xa); \t\t\t} \t\t\tPy_XDECREF(tmp); \t\t} \t\telse if (PyFortran_Check(fun) || PyFortran_Check1(fun)) { \t\t\ttot = maxnofargs; \t\t\tif (xa != NULL) \t\t\t\ttot += PyTuple_Size((PyObject *)xa); \t\t\ttmp_fun = fun; \t\t} \t\telse if (F2PyCapsule_Check(fun)) { \t\t\ttot = maxnofargs; \t\t\tif (xa != NULL) \t\t\t\text = PyTuple_Size((PyObject *)xa); \t\t\tif(ext>0) { \t\t\t\tfprintf(stderr,\"extra arguments tuple cannot be used with CObject call-back\\n\"); \t\t\t\tgoto capi_fail; \t\t\t} \t\t\ttmp_fun = fun; \t\t} \t} if (tmp_fun==NULL) { fprintf(stderr,\"Call-back argument must be function|instance|instance.__call__|f2py-function but got %s.\\n\",(fun==NULL?\"NULL\":Py_TYPE(fun)->tp_name)); goto capi_fail; } #if PY_VERSION_HEX >= 0x03000000 \tif (PyObject_HasAttrString(tmp_fun,\"__code__\")) { \t\tif (PyObject_HasAttrString(tmp = PyObject_GetAttrString(tmp_fun,\"__code__\"),\"co_argcount\")) #else \tif (PyObject_HasAttrString(tmp_fun,\"func_code\")) { \t\tif (PyObject_HasAttrString(tmp = PyObject_GetAttrString(tmp_fun,\"func_code\"),\"co_argcount\")) #endif \t\t\ttot = PyInt_AsLong(PyObject_GetAttrString(tmp,\"co_argcount\")) - di; \t\tPy_XDECREF(tmp); \t} \t/* Get the number of optional arguments */ #if PY_VERSION_HEX >= 0x03000000 \tif (PyObject_HasAttrString(tmp_fun,\"__defaults__\")) { \t\tif (PyTuple_Check(tmp = PyObject_GetAttrString(tmp_fun,\"__defaults__\"))) #else \tif (PyObject_HasAttrString(tmp_fun,\"func_defaults\")) { \t\tif (PyTuple_Check(tmp = PyObject_GetAttrString(tmp_fun,\"func_defaults\"))) #endif \t\t\topt = PyTuple_Size(tmp); \t\tPy_XDECREF(tmp); \t} \t/* Get the number of extra arguments */ \tif (xa != NULL) \t\text = PyTuple_Size((PyObject *)xa); \t/* Calculate the size of call-backs argument list */ \tsiz = MIN(maxnofargs+ext,tot); \t*nofargs = MAX(0,siz-ext); #ifdef DEBUGCFUNCS \tfprintf(stderr,\"debug-capi:create_cb_arglist:maxnofargs(-nofoptargs),tot,opt,ext,siz,nofargs=%d(-%d),%d,%d,%d,%d,%d\\n\",maxnofargs,nofoptargs,tot,opt,ext,siz,*nofargs); #endif \tif (siz0: if outneeds[n][0] not in needs: out.append(outneeds[n][0]) del outneeds[n][0] else: flag=0 for k in outneeds[n][1:]: if k in needs[outneeds[n][0]]: flag=1 break if flag: outneeds[n]=outneeds[n][1:]+[outneeds[n][0]] else: out.append(outneeds[n][0]) del outneeds[n][0] if saveout and (0 not in map(lambda x, y:x==y, saveout, outneeds[n])) \ and outneeds[n] != []: print(n, saveout) errmess('get_needs: no progress in sorting needs, probably circular dependence, skipping.\n') out=out+saveout break saveout=copy.copy(outneeds[n]) if out==[]: out=[n] res[n]=out return res numpy-1.8.2/numpy/f2py/diagnose.py0000664000175100017510000001207212370216242020220 0ustar vagrantvagrant00000000000000#!/usr/bin/env python from __future__ import division, absolute_import, print_function import os import sys import tempfile def run_command(cmd): print('Running %r:' % (cmd)) s = os.system(cmd) print('------') def run(): _path = os.getcwd() os.chdir(tempfile.gettempdir()) print('------') print('os.name=%r' % (os.name)) print('------') print('sys.platform=%r' % (sys.platform)) print('------') print('sys.version:') print(sys.version) print('------') print('sys.prefix:') print(sys.prefix) print('------') print('sys.path=%r' % (':'.join(sys.path))) print('------') try: import numpy has_newnumpy = 1 except ImportError: print('Failed to import new numpy:', sys.exc_info()[1]) has_newnumpy = 0 try: from numpy.f2py import f2py2e has_f2py2e = 1 except ImportError: print('Failed to import f2py2e:', sys.exc_info()[1]) has_f2py2e = 0 try: import numpy.distutils has_numpy_distutils = 2 except ImportError: try: import numpy_distutils has_numpy_distutils = 1 except ImportError: print('Failed to import numpy_distutils:', sys.exc_info()[1]) has_numpy_distutils = 0 if has_newnumpy: try: print('Found new numpy version %r in %s' % \ (numpy.__version__, numpy.__file__)) except Exception as msg: print('error:', msg) print('------') if has_f2py2e: try: print('Found f2py2e version %r in %s' % \ (f2py2e.__version__.version, f2py2e.__file__)) except Exception as msg: print('error:', msg) print('------') if has_numpy_distutils: try: if has_numpy_distutils == 2: print('Found numpy.distutils version %r in %r' % (\ numpy.distutils.__version__, numpy.distutils.__file__)) else: print('Found numpy_distutils version %r in %r' % (\ numpy_distutils.numpy_distutils_version.numpy_distutils_version, numpy_distutils.__file__)) print('------') except Exception as msg: print('error:', msg) print('------') try: if has_numpy_distutils == 1: print('Importing numpy_distutils.command.build_flib ...', end=' ') import numpy_distutils.command.build_flib as build_flib print('ok') print('------') try: print('Checking availability of supported Fortran compilers:') for compiler_class in build_flib.all_compilers: compiler_class(verbose=1).is_available() print('------') except Exception as msg: print('error:', msg) print('------') except Exception as msg: print('error:', msg, '(ignore it, build_flib is obsolute for numpy.distutils 0.2.2 and up)') print('------') try: if has_numpy_distutils == 2: print('Importing numpy.distutils.fcompiler ...', end=' ') import numpy.distutils.fcompiler as fcompiler else: print('Importing numpy_distutils.fcompiler ...', end=' ') import numpy_distutils.fcompiler as fcompiler print('ok') print('------') try: print('Checking availability of supported Fortran compilers:') fcompiler.show_fcompilers() print('------') except Exception as msg: print('error:', msg) print('------') except Exception as msg: print('error:', msg) print('------') try: if has_numpy_distutils == 2: print('Importing numpy.distutils.cpuinfo ...', end=' ') from numpy.distutils.cpuinfo import cpuinfo print('ok') print('------') else: try: print('Importing numpy_distutils.command.cpuinfo ...', end=' ') from numpy_distutils.command.cpuinfo import cpuinfo print('ok') print('------') except Exception as msg: print('error:', msg, '(ignore it)') print('Importing numpy_distutils.cpuinfo ...', end=' ') from numpy_distutils.cpuinfo import cpuinfo print('ok') print('------') cpu = cpuinfo() print('CPU information:', end=' ') for name in dir(cpuinfo): if name[0]=='_' and name[1]!='_' and getattr(cpu, name[1:])(): print(name[1:], end=' ') print('------') except Exception as msg: print('error:', msg) print('------') os.chdir(_path) if __name__ == "__main__": run() numpy-1.8.2/numpy/f2py/rules.py0000664000175100017510000015355712370216242017577 0ustar vagrantvagrant00000000000000#!/usr/bin/env python """ Rules for building C/API module with f2py2e. Here is a skeleton of a new wrapper function (13Dec2001): wrapper_function(args) declarations get_python_arguments, say, `a' and `b' get_a_from_python if (successful) { get_b_from_python if (successful) { callfortran if (succesful) { put_a_to_python if (succesful) { put_b_to_python if (succesful) { buildvalue = ... } } } } cleanup_b } cleanup_a return buildvalue Copyright 1999,2000 Pearu Peterson all rights reserved, Pearu Peterson Permission to use, modify, and distribute this software is given under the terms of the NumPy License. NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. $Date: 2005/08/30 08:58:42 $ Pearu Peterson """ from __future__ import division, absolute_import, print_function __version__ = "$Revision: 1.129 $"[10:-1] from . import __version__ f2py_version = __version__.version import pprint import sys import time import copy from .auxfuncs import * from . import capi_maps from .capi_maps import * from . import cfuncs from . import common_rules from . import use_rules from . import f90mod_rules from . import func2subr errmess = sys.stderr.write outmess = sys.stdout.write show = pprint.pprint options={} sepdict={} #for k in ['need_cfuncs']: sepdict[k]=',' for k in ['decl', 'frompyobj', 'cleanupfrompyobj', 'topyarr', 'method', 'pyobjfrom', 'closepyobjfrom', 'freemem', 'userincludes', 'includes0', 'includes', 'typedefs', 'typedefs_generated', 'cppmacros', 'cfuncs', 'callbacks', 'latexdoc', 'restdoc', 'routine_defs', 'externroutines', 'initf2pywraphooks', 'commonhooks', 'initcommonhooks', 'f90modhooks', 'initf90modhooks']: sepdict[k]='\n' #################### Rules for C/API module ################# module_rules={ 'modulebody':"""\ /* File: #modulename#module.c * This file is auto-generated with f2py (version:#f2py_version#). * f2py is a Fortran to Python Interface Generator (FPIG), Second Edition, * written by Pearu Peterson . * See http://cens.ioc.ee/projects/f2py2e/ * Generation date: """+time.asctime(time.localtime(time.time()))+""" * $R"""+"""evision:$ * $D"""+"""ate:$ * Do not edit this file directly unless you know what you are doing!!! */ #ifdef __cplusplus extern \"C\" { #endif """+gentitle("See f2py2e/cfuncs.py: includes")+""" #includes# #includes0# """+gentitle("See f2py2e/rules.py: mod_rules['modulebody']")+""" static PyObject *#modulename#_error; static PyObject *#modulename#_module; """+gentitle("See f2py2e/cfuncs.py: typedefs")+""" #typedefs# """+gentitle("See f2py2e/cfuncs.py: typedefs_generated")+""" #typedefs_generated# """+gentitle("See f2py2e/cfuncs.py: cppmacros")+""" #cppmacros# """+gentitle("See f2py2e/cfuncs.py: cfuncs")+""" #cfuncs# """+gentitle("See f2py2e/cfuncs.py: userincludes")+""" #userincludes# """+gentitle("See f2py2e/capi_rules.py: usercode")+""" #usercode# /* See f2py2e/rules.py */ #externroutines# """+gentitle("See f2py2e/capi_rules.py: usercode1")+""" #usercode1# """+gentitle("See f2py2e/cb_rules.py: buildcallback")+""" #callbacks# """+gentitle("See f2py2e/rules.py: buildapi")+""" #body# """+gentitle("See f2py2e/f90mod_rules.py: buildhooks")+""" #f90modhooks# """+gentitle("See f2py2e/rules.py: module_rules['modulebody']")+""" """+gentitle("See f2py2e/common_rules.py: buildhooks")+""" #commonhooks# """+gentitle("See f2py2e/rules.py")+""" static FortranDataDef f2py_routine_defs[] = { #routine_defs# \t{NULL} }; static PyMethodDef f2py_module_methods[] = { #pymethoddef# \t{NULL,NULL} }; #if PY_VERSION_HEX >= 0x03000000 static struct PyModuleDef moduledef = { \tPyModuleDef_HEAD_INIT, \t"#modulename#", \tNULL, \t-1, \tf2py_module_methods, \tNULL, \tNULL, \tNULL, \tNULL }; #endif #if PY_VERSION_HEX >= 0x03000000 #define RETVAL m PyMODINIT_FUNC PyInit_#modulename#(void) { #else #define RETVAL PyMODINIT_FUNC init#modulename#(void) { #endif \tint i; \tPyObject *m,*d, *s; #if PY_VERSION_HEX >= 0x03000000 \tm = #modulename#_module = PyModule_Create(&moduledef); #else \tm = #modulename#_module = Py_InitModule(\"#modulename#\", f2py_module_methods); #endif \tPy_TYPE(&PyFortran_Type) = &PyType_Type; \timport_array(); \tif (PyErr_Occurred()) \t\t{PyErr_SetString(PyExc_ImportError, \"can't initialize module #modulename# (failed to import numpy)\"); return RETVAL;} \td = PyModule_GetDict(m); \ts = PyString_FromString(\"$R"""+"""evision: $\"); \tPyDict_SetItemString(d, \"__version__\", s); #if PY_VERSION_HEX >= 0x03000000 \ts = PyUnicode_FromString( #else \ts = PyString_FromString( #endif \t\t\"This module '#modulename#' is auto-generated with f2py (version:#f2py_version#).\\nFunctions:\\n\"\n#docs#\".\"); \tPyDict_SetItemString(d, \"__doc__\", s); \t#modulename#_error = PyErr_NewException (\"#modulename#.error\", NULL, NULL); \tPy_DECREF(s); \tfor(i=0;f2py_routine_defs[i].name!=NULL;i++) \t\tPyDict_SetItemString(d, f2py_routine_defs[i].name,PyFortranObject_NewAsAttr(&f2py_routine_defs[i])); #initf2pywraphooks# #initf90modhooks# #initcommonhooks# #interface_usercode# #ifdef F2PY_REPORT_ATEXIT \tif (! PyErr_Occurred()) \t\ton_exit(f2py_report_on_exit,(void*)\"#modulename#\"); #endif \treturn RETVAL; } #ifdef __cplusplus } #endif """, 'separatorsfor':{'latexdoc':'\n\n', 'restdoc':'\n\n'}, 'latexdoc':['\\section{Module \\texttt{#texmodulename#}}\n', '#modnote#\n', '#latexdoc#'], 'restdoc':['Module #modulename#\n'+'='*80, '\n#restdoc#'] } defmod_rules=[ {'body': '/*eof body*/', 'method': '/*eof method*/', 'externroutines': '/*eof externroutines*/', 'routine_defs': '/*eof routine_defs*/', 'initf90modhooks': '/*eof initf90modhooks*/', 'initf2pywraphooks': '/*eof initf2pywraphooks*/', 'initcommonhooks': '/*eof initcommonhooks*/', 'latexdoc': '', 'restdoc': '', 'modnote': {hasnote:'#note#',l_not(hasnote):''}, } ] routine_rules={ 'separatorsfor':sepdict, 'body':""" #begintitle# static char doc_#apiname#[] = \"\\\n#docreturn##name#(#docsignatureshort#)\\n\\nWrapper for ``#name#``.\\\n\\n#docstrsigns#\"; /* #declfortranroutine# */ static PyObject *#apiname#(const PyObject *capi_self, PyObject *capi_args, PyObject *capi_keywds, #functype# (*f2py_func)(#callprotoargument#)) { \tPyObject * volatile capi_buildvalue = NULL; \tvolatile int f2py_success = 1; #decl# \tstatic char *capi_kwlist[] = {#kwlist##kwlistopt##kwlistxa#NULL}; #usercode# #routdebugenter# #ifdef F2PY_REPORT_ATEXIT f2py_start_clock(); #endif \tif (!PyArg_ParseTupleAndKeywords(capi_args,capi_keywds,\\ \t\t\"#argformat##keyformat##xaformat#:#pyname#\",\\ \t\tcapi_kwlist#args_capi##keys_capi##keys_xa#))\n\t\treturn NULL; #frompyobj# /*end of frompyobj*/ #ifdef F2PY_REPORT_ATEXIT f2py_start_call_clock(); #endif #callfortranroutine# if (PyErr_Occurred()) f2py_success = 0; #ifdef F2PY_REPORT_ATEXIT f2py_stop_call_clock(); #endif /*end of callfortranroutine*/ \t\tif (f2py_success) { #pyobjfrom# /*end of pyobjfrom*/ \t\tCFUNCSMESS(\"Building return value.\\n\"); \t\tcapi_buildvalue = Py_BuildValue(\"#returnformat#\"#return#); /*closepyobjfrom*/ #closepyobjfrom# \t\t} /*if (f2py_success) after callfortranroutine*/ /*cleanupfrompyobj*/ #cleanupfrompyobj# \tif (capi_buildvalue == NULL) { #routdebugfailure# \t} else { #routdebugleave# \t} \tCFUNCSMESS(\"Freeing memory.\\n\"); #freemem# #ifdef F2PY_REPORT_ATEXIT f2py_stop_clock(); #endif \treturn capi_buildvalue; } #endtitle# """, 'routine_defs':'#routine_def#', 'initf2pywraphooks':'#initf2pywraphook#', 'externroutines':'#declfortranroutine#', 'doc':'#docreturn##name#(#docsignature#)', 'docshort':'#docreturn##name#(#docsignatureshort#)', 'docs':'"\t#docreturn##name#(#docsignature#)\\n"\n', 'need':['arrayobject.h', 'CFUNCSMESS', 'MINMAX'], 'cppmacros':{debugcapi:'#define DEBUGCFUNCS'}, 'latexdoc':['\\subsection{Wrapper function \\texttt{#texname#}}\n', """ \\noindent{{}\\verb@#docreturn##name#@{}}\\texttt{(#latexdocsignatureshort#)} #routnote# #latexdocstrsigns# """], 'restdoc':['Wrapped function ``#name#``\n'+'-'*80, ] } ################## Rules for C/API function ############## rout_rules=[ { # Init 'separatorsfor': {'callfortranroutine': '\n', 'routdebugenter': '\n', 'decl': '\n', 'routdebugleave': '\n', 'routdebugfailure': '\n', 'setjmpbuf': ' || ', 'docstrreq': '\n', 'docstropt': '\n', 'docstrout': '\n', 'docstrcbs': '\n', 'docstrsigns': '\\n"\n"', 'latexdocstrsigns': '\n', 'latexdocstrreq': '\n', 'latexdocstropt': '\n', 'latexdocstrout': '\n', 'latexdocstrcbs': '\n', }, 'kwlist': '', 'kwlistopt': '', 'callfortran': '', 'callfortranappend': '', 'docsign': '', 'docsignopt': '', 'decl': '/*decl*/', 'freemem': '/*freemem*/', 'docsignshort': '', 'docsignoptshort': '', 'docstrsigns': '', 'latexdocstrsigns': '', 'docstrreq': '\\nParameters\\n----------', 'docstropt': '\\nOther Parameters\\n----------------', 'docstrout': '\\nReturns\\n-------', 'docstrcbs': '\\nNotes\\n-----\\nCall-back functions::\\n', 'latexdocstrreq': '\\noindent Required arguments:', 'latexdocstropt': '\\noindent Optional arguments:', 'latexdocstrout': '\\noindent Return objects:', 'latexdocstrcbs': '\\noindent Call-back functions:', 'args_capi': '', 'keys_capi': '', 'functype': '', 'frompyobj': '/*frompyobj*/', 'cleanupfrompyobj': ['/*end of cleanupfrompyobj*/'], #this list will be reversed 'pyobjfrom': '/*pyobjfrom*/', 'closepyobjfrom': ['/*end of closepyobjfrom*/'], #this list will be reversed 'topyarr': '/*topyarr*/', 'routdebugleave': '/*routdebugleave*/', 'routdebugenter': '/*routdebugenter*/', 'routdebugfailure': '/*routdebugfailure*/', 'callfortranroutine': '/*callfortranroutine*/', 'argformat': '', 'keyformat': '', 'need_cfuncs': '', 'docreturn': '', 'return': '', 'returnformat': '', 'rformat': '', 'kwlistxa': '', 'keys_xa': '', 'xaformat': '', 'docsignxa': '', 'docsignxashort': '', 'initf2pywraphook': '', 'routnote': {hasnote:'--- #note#',l_not(hasnote):''}, }, { 'apiname':'f2py_rout_#modulename#_#name#', 'pyname':'#modulename#.#name#', 'decl':'', '_check':l_not(ismoduleroutine) }, { 'apiname':'f2py_rout_#modulename#_#f90modulename#_#name#', 'pyname':'#modulename#.#f90modulename#.#name#', 'decl':'', '_check':ismoduleroutine }, { # Subroutine 'functype': 'void', 'declfortranroutine': {l_and(l_not(l_or(ismoduleroutine, isintent_c)), l_not(isdummyroutine)):'extern void #F_FUNC#(#fortranname#,#FORTRANNAME#)(#callprotoargument#);', l_and(l_not(ismoduleroutine), isintent_c, l_not(isdummyroutine)):'extern void #fortranname#(#callprotoargument#);', ismoduleroutine:'', isdummyroutine:'' }, 'routine_def': {l_not(l_or(ismoduleroutine, isintent_c, isdummyroutine)): '\t{\"#name#\",-1,{{-1}},0,(char *)#F_FUNC#(#fortranname#,#FORTRANNAME#),(f2py_init_func)#apiname#,doc_#apiname#},', l_and(l_not(ismoduleroutine), isintent_c, l_not(isdummyroutine)): '\t{\"#name#\",-1,{{-1}},0,(char *)#fortranname#,(f2py_init_func)#apiname#,doc_#apiname#},', l_and(l_not(ismoduleroutine), isdummyroutine): '\t{\"#name#\",-1,{{-1}},0,NULL,(f2py_init_func)#apiname#,doc_#apiname#},', }, 'need': {l_and(l_not(l_or(ismoduleroutine, isintent_c)), l_not(isdummyroutine)):'F_FUNC'}, 'callfortranroutine': [ {debugcapi:["""\tfprintf(stderr,\"debug-capi:Fortran subroutine `#fortranname#(#callfortran#)\'\\n\");"""]}, {hasexternals:"""\ \t\tif (#setjmpbuf#) { \t\t\tf2py_success = 0; \t\t} else {"""}, {isthreadsafe:'\t\t\tPy_BEGIN_ALLOW_THREADS'}, {hascallstatement:'''\t\t\t\t#callstatement#; \t\t\t\t/*(*f2py_func)(#callfortran#);*/'''}, {l_not(l_or(hascallstatement, isdummyroutine)):'\t\t\t\t(*f2py_func)(#callfortran#);'}, {isthreadsafe:'\t\t\tPy_END_ALLOW_THREADS'}, {hasexternals:"""\t\t}"""} ], '_check': l_and(issubroutine, l_not(issubroutine_wrap)), }, { # Wrapped function 'functype': 'void', 'declfortranroutine': {l_not(l_or(ismoduleroutine, isdummyroutine)): 'extern void #F_WRAPPEDFUNC#(#name_lower#,#NAME#)(#callprotoargument#);', isdummyroutine: '', }, 'routine_def': {l_not(l_or(ismoduleroutine, isdummyroutine)): '\t{\"#name#\",-1,{{-1}},0,(char *)#F_WRAPPEDFUNC#(#name_lower#,#NAME#),(f2py_init_func)#apiname#,doc_#apiname#},', isdummyroutine: '\t{\"#name#\",-1,{{-1}},0,NULL,(f2py_init_func)#apiname#,doc_#apiname#},', }, 'initf2pywraphook': {l_not(l_or(ismoduleroutine, isdummyroutine)):''' { extern #ctype# #F_FUNC#(#name_lower#,#NAME#)(void); PyObject* o = PyDict_GetItemString(d,"#name#"); PyObject_SetAttrString(o,"_cpointer", F2PyCapsule_FromVoidPtr((void*)#F_FUNC#(#name_lower#,#NAME#),NULL)); #if PY_VERSION_HEX >= 0x03000000 PyObject_SetAttrString(o,"__name__", PyUnicode_FromString("#name#")); #else PyObject_SetAttrString(o,"__name__", PyString_FromString("#name#")); #endif } '''}, 'need': {l_not(l_or(ismoduleroutine, isdummyroutine)):['F_WRAPPEDFUNC', 'F_FUNC']}, 'callfortranroutine': [ {debugcapi:["""\tfprintf(stderr,\"debug-capi:Fortran subroutine `f2pywrap#name_lower#(#callfortran#)\'\\n\");"""]}, {hasexternals:"""\ \tif (#setjmpbuf#) { \t\tf2py_success = 0; \t} else {"""}, {isthreadsafe:'\tPy_BEGIN_ALLOW_THREADS'}, {l_not(l_or(hascallstatement, isdummyroutine)):'\t(*f2py_func)(#callfortran#);'}, {hascallstatement:'\t#callstatement#;\n\t/*(*f2py_func)(#callfortran#);*/'}, {isthreadsafe:'\tPy_END_ALLOW_THREADS'}, {hasexternals:'\t}'} ], '_check': isfunction_wrap, }, { # Wrapped subroutine 'functype': 'void', 'declfortranroutine': {l_not(l_or(ismoduleroutine, isdummyroutine)): 'extern void #F_WRAPPEDFUNC#(#name_lower#,#NAME#)(#callprotoargument#);', isdummyroutine: '', }, 'routine_def': {l_not(l_or(ismoduleroutine, isdummyroutine)): '\t{\"#name#\",-1,{{-1}},0,(char *)#F_WRAPPEDFUNC#(#name_lower#,#NAME#),(f2py_init_func)#apiname#,doc_#apiname#},', isdummyroutine: '\t{\"#name#\",-1,{{-1}},0,NULL,(f2py_init_func)#apiname#,doc_#apiname#},', }, 'initf2pywraphook': {l_not(l_or(ismoduleroutine, isdummyroutine)):''' { extern void #F_FUNC#(#name_lower#,#NAME#)(void); PyObject* o = PyDict_GetItemString(d,"#name#"); PyObject_SetAttrString(o,"_cpointer", F2PyCapsule_FromVoidPtr((void*)#F_FUNC#(#name_lower#,#NAME#),NULL)); #if PY_VERSION_HEX >= 0x03000000 PyObject_SetAttrString(o,"__name__", PyUnicode_FromString("#name#")); #else PyObject_SetAttrString(o,"__name__", PyString_FromString("#name#")); #endif } '''}, 'need': {l_not(l_or(ismoduleroutine, isdummyroutine)):['F_WRAPPEDFUNC', 'F_FUNC']}, 'callfortranroutine': [ {debugcapi:["""\tfprintf(stderr,\"debug-capi:Fortran subroutine `f2pywrap#name_lower#(#callfortran#)\'\\n\");"""]}, {hasexternals:"""\ \tif (#setjmpbuf#) { \t\tf2py_success = 0; \t} else {"""}, {isthreadsafe:'\tPy_BEGIN_ALLOW_THREADS'}, {l_not(l_or(hascallstatement, isdummyroutine)):'\t(*f2py_func)(#callfortran#);'}, {hascallstatement:'\t#callstatement#;\n\t/*(*f2py_func)(#callfortran#);*/'}, {isthreadsafe:'\tPy_END_ALLOW_THREADS'}, {hasexternals:'\t}'} ], '_check': issubroutine_wrap, }, { # Function 'functype':'#ctype#', 'docreturn':{l_not(isintent_hide):'#rname#,'}, 'docstrout':'#pydocsignout#', 'latexdocstrout':['\\item[]{{}\\verb@#pydocsignout#@{}}', {hasresultnote:'--- #resultnote#'}], 'callfortranroutine':[{l_and(debugcapi, isstringfunction):"""\ #ifdef USESCOMPAQFORTRAN \tfprintf(stderr,\"debug-capi:Fortran function #ctype# #fortranname#(#callcompaqfortran#)\\n\"); #else \tfprintf(stderr,\"debug-capi:Fortran function #ctype# #fortranname#(#callfortran#)\\n\"); #endif """}, {l_and(debugcapi, l_not(isstringfunction)):"""\ \tfprintf(stderr,\"debug-capi:Fortran function #ctype# #fortranname#(#callfortran#)\\n\"); """} ], '_check':l_and(isfunction, l_not(isfunction_wrap)) }, { # Scalar function 'declfortranroutine':{l_and(l_not(l_or(ismoduleroutine, isintent_c)), l_not(isdummyroutine)):'extern #ctype# #F_FUNC#(#fortranname#,#FORTRANNAME#)(#callprotoargument#);', l_and(l_not(ismoduleroutine), isintent_c, l_not(isdummyroutine)):'extern #ctype# #fortranname#(#callprotoargument#);', isdummyroutine:'' }, 'routine_def':{l_and(l_not(l_or(ismoduleroutine, isintent_c)), l_not(isdummyroutine)): '\t{\"#name#\",-1,{{-1}},0,(char *)#F_FUNC#(#fortranname#,#FORTRANNAME#),(f2py_init_func)#apiname#,doc_#apiname#},', l_and(l_not(ismoduleroutine), isintent_c, l_not(isdummyroutine)): '\t{\"#name#\",-1,{{-1}},0,(char *)#fortranname#,(f2py_init_func)#apiname#,doc_#apiname#},', isdummyroutine: '\t{\"#name#\",-1,{{-1}},0,NULL,(f2py_init_func)#apiname#,doc_#apiname#},', }, 'decl':[{iscomplexfunction_warn:'\t#ctype# #name#_return_value={0,0};', l_not(iscomplexfunction):'\t#ctype# #name#_return_value=0;'}, {iscomplexfunction:'\tPyObject *#name#_return_value_capi = Py_None;'} ], 'callfortranroutine':[ {hasexternals:"""\ \tif (#setjmpbuf#) { \t\tf2py_success = 0; \t} else {"""}, {isthreadsafe:'\tPy_BEGIN_ALLOW_THREADS'}, {hascallstatement:'''\t#callstatement#; /*\t#name#_return_value = (*f2py_func)(#callfortran#);*/ '''}, {l_not(l_or(hascallstatement, isdummyroutine)):'\t#name#_return_value = (*f2py_func)(#callfortran#);'}, {isthreadsafe:'\tPy_END_ALLOW_THREADS'}, {hasexternals:'\t}'}, {l_and(debugcapi, iscomplexfunction):'\tfprintf(stderr,"#routdebugshowvalue#\\n",#name#_return_value.r,#name#_return_value.i);'}, {l_and(debugcapi, l_not(iscomplexfunction)):'\tfprintf(stderr,"#routdebugshowvalue#\\n",#name#_return_value);'}], 'pyobjfrom':{iscomplexfunction:'\t#name#_return_value_capi = pyobj_from_#ctype#1(#name#_return_value);'}, 'need':[{l_not(isdummyroutine):'F_FUNC'}, {iscomplexfunction:'pyobj_from_#ctype#1'}, {islong_longfunction:'long_long'}, {islong_doublefunction:'long_double'}], 'returnformat':{l_not(isintent_hide):'#rformat#'}, 'return':{iscomplexfunction:',#name#_return_value_capi', l_not(l_or(iscomplexfunction, isintent_hide)):',#name#_return_value'}, '_check':l_and(isfunction, l_not(isstringfunction), l_not(isfunction_wrap)) }, { # String function # in use for --no-wrap 'declfortranroutine':'extern void #F_FUNC#(#fortranname#,#FORTRANNAME#)(#callprotoargument#);', 'routine_def':{l_not(l_or(ismoduleroutine, isintent_c)): # '\t{\"#name#\",-1,{{-1}},0,(char *)F_FUNC(#fortranname#,#FORTRANNAME#),(void *)#apiname#,doc_#apiname#},', '\t{\"#name#\",-1,{{-1}},0,(char *)#F_FUNC#(#fortranname#,#FORTRANNAME#),(f2py_init_func)#apiname#,doc_#apiname#},', l_and(l_not(ismoduleroutine), isintent_c): # '\t{\"#name#\",-1,{{-1}},0,(char *)#fortranname#,(void *)#apiname#,doc_#apiname#},' '\t{\"#name#\",-1,{{-1}},0,(char *)#fortranname#,(f2py_init_func)#apiname#,doc_#apiname#},' }, 'decl':['\t#ctype# #name#_return_value = NULL;', '\tint #name#_return_value_len = 0;'], 'callfortran':'#name#_return_value,#name#_return_value_len,', 'callfortranroutine':['\t#name#_return_value_len = #rlength#;', '\tif ((#name#_return_value = (string)malloc(sizeof(char)*(#name#_return_value_len+1))) == NULL) {', '\t\tPyErr_SetString(PyExc_MemoryError, \"out of memory\");', '\t\tf2py_success = 0;', '\t} else {', "\t\t(#name#_return_value)[#name#_return_value_len] = '\\0';", '\t}', '\tif (f2py_success) {', {hasexternals:"""\ \t\tif (#setjmpbuf#) { \t\t\tf2py_success = 0; \t\t} else {"""}, {isthreadsafe:'\t\tPy_BEGIN_ALLOW_THREADS'}, """\ #ifdef USESCOMPAQFORTRAN \t\t(*f2py_func)(#callcompaqfortran#); #else \t\t(*f2py_func)(#callfortran#); #endif """, {isthreadsafe:'\t\tPy_END_ALLOW_THREADS'}, {hasexternals:'\t\t}'}, {debugcapi:'\t\tfprintf(stderr,"#routdebugshowvalue#\\n",#name#_return_value_len,#name#_return_value);'}, '\t} /* if (f2py_success) after (string)malloc */', ], 'returnformat':'#rformat#', 'return':',#name#_return_value', 'freemem':'\tSTRINGFREE(#name#_return_value);', 'need':['F_FUNC', '#ctype#', 'STRINGFREE'], '_check':l_and(isstringfunction, l_not(isfunction_wrap)) # ???obsolete }, { # Debugging 'routdebugenter':'\tfprintf(stderr,"debug-capi:Python C/API function #modulename#.#name#(#docsignature#)\\n");', 'routdebugleave':'\tfprintf(stderr,"debug-capi:Python C/API function #modulename#.#name#: successful.\\n");', 'routdebugfailure':'\tfprintf(stderr,"debug-capi:Python C/API function #modulename#.#name#: failure.\\n");', '_check':debugcapi } ] ################ Rules for arguments ################## typedef_need_dict = {islong_long: 'long_long', islong_double: 'long_double', islong_complex: 'complex_long_double', isunsigned_char: 'unsigned_char', isunsigned_short: 'unsigned_short', isunsigned: 'unsigned', isunsigned_long_long: 'unsigned_long_long', isunsigned_chararray: 'unsigned_char', isunsigned_shortarray: 'unsigned_short', isunsigned_long_longarray: 'unsigned_long_long', issigned_long_longarray: 'long_long', } aux_rules=[ { 'separatorsfor':sepdict }, { # Common 'frompyobj': ['\t/* Processing auxiliary variable #varname# */', {debugcapi:'\tfprintf(stderr,"#vardebuginfo#\\n");'},], 'cleanupfrompyobj': '\t/* End of cleaning variable #varname# */', 'need': typedef_need_dict, }, # Scalars (not complex) { # Common 'decl': '\t#ctype# #varname# = 0;', 'need': {hasinitvalue:'math.h'}, 'frompyobj': {hasinitvalue:'\t#varname# = #init#;'}, '_check': l_and(isscalar, l_not(iscomplex)), }, { 'return': ',#varname#', 'docstrout': '#pydocsignout#', 'docreturn': '#outvarname#,', 'returnformat': '#varrformat#', '_check': l_and(isscalar, l_not(iscomplex), isintent_out), }, # Complex scalars { # Common 'decl':'\t#ctype# #varname#;', 'frompyobj': {hasinitvalue:'\t#varname#.r = #init.r#, #varname#.i = #init.i#;'}, '_check':iscomplex }, # String { # Common 'decl':['\t#ctype# #varname# = NULL;', '\tint slen(#varname#);', ], 'need':['len..'], '_check':isstring }, # Array { # Common 'decl':['\t#ctype# *#varname# = NULL;', '\tnpy_intp #varname#_Dims[#rank#] = {#rank*[-1]#};', '\tconst int #varname#_Rank = #rank#;', ], 'need':['len..', {hasinitvalue:'forcomb'}, {hasinitvalue:'CFUNCSMESS'}], '_check':isarray }, # Scalararray { # Common '_check':l_and(isarray, l_not(iscomplexarray)) }, { # Not hidden '_check':l_and(isarray, l_not(iscomplexarray), isintent_nothide) }, # Integer*1 array {'need':'#ctype#', '_check':isint1array, '_depend':'' }, # Integer*-1 array {'need':'#ctype#', '_check':isunsigned_chararray, '_depend':'' }, # Integer*-2 array {'need':'#ctype#', '_check':isunsigned_shortarray, '_depend':'' }, # Integer*-8 array {'need':'#ctype#', '_check':isunsigned_long_longarray, '_depend':'' }, # Complexarray {'need':'#ctype#', '_check':iscomplexarray, '_depend':'' }, # Stringarray { 'callfortranappend':{isarrayofstrings:'flen(#varname#),'}, 'need':'string', '_check':isstringarray } ] arg_rules=[ { 'separatorsfor':sepdict }, { # Common 'frompyobj': ['\t/* Processing variable #varname# */', {debugcapi:'\tfprintf(stderr,"#vardebuginfo#\\n");'},], 'cleanupfrompyobj': '\t/* End of cleaning variable #varname# */', '_depend': '', 'need': typedef_need_dict, }, # Doc signatures { 'docstropt':{l_and(isoptional, isintent_nothide):'#pydocsign#'}, 'docstrreq':{l_and(isrequired, isintent_nothide):'#pydocsign#'}, 'docstrout':{isintent_out:'#pydocsignout#'}, 'latexdocstropt':{l_and(isoptional, isintent_nothide):['\\item[]{{}\\verb@#pydocsign#@{}}', {hasnote:'--- #note#'}]}, 'latexdocstrreq':{l_and(isrequired, isintent_nothide):['\\item[]{{}\\verb@#pydocsign#@{}}', {hasnote:'--- #note#'}]}, 'latexdocstrout':{isintent_out:['\\item[]{{}\\verb@#pydocsignout#@{}}', {l_and(hasnote, isintent_hide):'--- #note#', l_and(hasnote, isintent_nothide):'--- See above.'}]}, 'depend':'' }, # Required/Optional arguments { 'kwlist':'"#varname#",', 'docsign':'#varname#,', '_check':l_and(isintent_nothide, l_not(isoptional)) }, { 'kwlistopt':'"#varname#",', 'docsignopt':'#varname#=#showinit#,', 'docsignoptshort':'#varname#,', '_check':l_and(isintent_nothide, isoptional) }, # Docstring/BuildValue { 'docreturn':'#outvarname#,', 'returnformat':'#varrformat#', '_check':isintent_out }, # Externals (call-back functions) { # Common 'docsignxa':{isintent_nothide:'#varname#_extra_args=(),'}, 'docsignxashort':{isintent_nothide:'#varname#_extra_args,'}, 'docstropt':{isintent_nothide:'#varname#_extra_args : input tuple, optional\\n Default: ()'}, 'docstrcbs':'#cbdocstr#', 'latexdocstrcbs':'\\item[] #cblatexdocstr#', 'latexdocstropt':{isintent_nothide:'\\item[]{{}\\verb@#varname#_extra_args := () input tuple@{}} --- Extra arguments for call-back function {{}\\verb@#varname#@{}}.'}, 'decl':['\tPyObject *#varname#_capi = Py_None;', '\tPyTupleObject *#varname#_xa_capi = NULL;', '\tPyTupleObject *#varname#_args_capi = NULL;', '\tint #varname#_nofargs_capi = 0;', {l_not(isintent_callback):'\t#cbname#_typedef #varname#_cptr;'} ], 'kwlistxa':{isintent_nothide:'"#varname#_extra_args",'}, 'argformat':{isrequired:'O'}, 'keyformat':{isoptional:'O'}, 'xaformat':{isintent_nothide:'O!'}, 'args_capi':{isrequired:',&#varname#_capi'}, 'keys_capi':{isoptional:',&#varname#_capi'}, 'keys_xa':',&PyTuple_Type,&#varname#_xa_capi', 'setjmpbuf':'(setjmp(#cbname#_jmpbuf))', 'callfortran':{l_not(isintent_callback):'#varname#_cptr,'}, 'need':['#cbname#', 'setjmp.h'], '_check':isexternal }, { 'frompyobj':[{l_not(isintent_callback):"""\ if(F2PyCapsule_Check(#varname#_capi)) { #varname#_cptr = F2PyCapsule_AsVoidPtr(#varname#_capi); } else { #varname#_cptr = #cbname#; } """}, {isintent_callback:"""\ if (#varname#_capi==Py_None) { #varname#_capi = PyObject_GetAttrString(#modulename#_module,\"#varname#\"); if (#varname#_capi) { if (#varname#_xa_capi==NULL) { if (PyObject_HasAttrString(#modulename#_module,\"#varname#_extra_args\")) { PyObject* capi_tmp = PyObject_GetAttrString(#modulename#_module,\"#varname#_extra_args\"); if (capi_tmp) #varname#_xa_capi = (PyTupleObject *)PySequence_Tuple(capi_tmp); else #varname#_xa_capi = (PyTupleObject *)Py_BuildValue(\"()\"); if (#varname#_xa_capi==NULL) { PyErr_SetString(#modulename#_error,\"Failed to convert #modulename#.#varname#_extra_args to tuple.\\n\"); return NULL; } } } } if (#varname#_capi==NULL) { PyErr_SetString(#modulename#_error,\"Callback #varname# not defined (as an argument or module #modulename# attribute).\\n\"); return NULL; } } """}, ## {l_not(isintent_callback):"""\ ## if (#varname#_capi==Py_None) { ## printf(\"hoi\\n\"); ## } ## """}, """\ \t#varname#_nofargs_capi = #cbname#_nofargs; \tif (create_cb_arglist(#varname#_capi,#varname#_xa_capi,#maxnofargs#,#nofoptargs#,&#cbname#_nofargs,&#varname#_args_capi,\"failed in processing argument list for call-back #varname#.\")) { \t\tjmp_buf #varname#_jmpbuf;""", {debugcapi:["""\ \t\tfprintf(stderr,\"debug-capi:Assuming %d arguments; at most #maxnofargs#(-#nofoptargs#) is expected.\\n\",#cbname#_nofargs); \t\tCFUNCSMESSPY(\"for #varname#=\",#cbname#_capi);""", {l_not(isintent_callback):"""\t\tfprintf(stderr,\"#vardebugshowvalue# (call-back in C).\\n\",#cbname#);"""}]}, """\ \t\tCFUNCSMESS(\"Saving jmpbuf for `#varname#`.\\n\"); \t\tSWAP(#varname#_capi,#cbname#_capi,PyObject); \t\tSWAP(#varname#_args_capi,#cbname#_args_capi,PyTupleObject); \t\tmemcpy(&#varname#_jmpbuf,&#cbname#_jmpbuf,sizeof(jmp_buf));""", ], 'cleanupfrompyobj': """\ \t\tCFUNCSMESS(\"Restoring jmpbuf for `#varname#`.\\n\"); \t\t#cbname#_capi = #varname#_capi; \t\tPy_DECREF(#cbname#_args_capi); \t\t#cbname#_args_capi = #varname#_args_capi; \t\t#cbname#_nofargs = #varname#_nofargs_capi; \t\tmemcpy(&#cbname#_jmpbuf,&#varname#_jmpbuf,sizeof(jmp_buf)); \t}""", 'need':['SWAP', 'create_cb_arglist'], '_check':isexternal, '_depend':'' }, # Scalars (not complex) { # Common 'decl':'\t#ctype# #varname# = 0;', 'pyobjfrom':{debugcapi:'\tfprintf(stderr,"#vardebugshowvalue#\\n",#varname#);'}, 'callfortran':{isintent_c:'#varname#,',l_not(isintent_c):'&#varname#,'}, 'return':{isintent_out:',#varname#'}, '_check':l_and(isscalar, l_not(iscomplex)) }, { 'need': {hasinitvalue:'math.h'}, '_check': l_and(isscalar, l_not(iscomplex)), #'_depend':'' }, { # Not hidden 'decl':'\tPyObject *#varname#_capi = Py_None;', 'argformat':{isrequired:'O'}, 'keyformat':{isoptional:'O'}, 'args_capi':{isrequired:',&#varname#_capi'}, 'keys_capi':{isoptional:',&#varname#_capi'}, 'pyobjfrom':{isintent_inout:"""\ \tf2py_success = try_pyarr_from_#ctype#(#varname#_capi,&#varname#); \tif (f2py_success) {"""}, 'closepyobjfrom':{isintent_inout:"\t} /*if (f2py_success) of #varname# pyobjfrom*/"}, 'need':{isintent_inout:'try_pyarr_from_#ctype#'}, '_check':l_and(isscalar, l_not(iscomplex), isintent_nothide) }, { 'frompyobj':[ # hasinitvalue... # if pyobj is None: # varname = init # else # from_pyobj(varname) # # isoptional and noinitvalue... # if pyobj is not None: # from_pyobj(varname) # else: # varname is uninitialized # # ... # from_pyobj(varname) # {hasinitvalue:'\tif (#varname#_capi == Py_None) #varname# = #init#; else', '_depend':''}, {l_and(isoptional, l_not(hasinitvalue)):'\tif (#varname#_capi != Py_None)', '_depend':''}, {l_not(islogical):'''\ \t\tf2py_success = #ctype#_from_pyobj(&#varname#,#varname#_capi,"#pyname#() #nth# (#varname#) can\'t be converted to #ctype#"); \tif (f2py_success) {'''}, {islogical:'''\ \t\t#varname# = (#ctype#)PyObject_IsTrue(#varname#_capi); \t\tf2py_success = 1; \tif (f2py_success) {'''}, ], 'cleanupfrompyobj':'\t} /*if (f2py_success) of #varname#*/', 'need':{l_not(islogical):'#ctype#_from_pyobj'}, '_check':l_and(isscalar, l_not(iscomplex), isintent_nothide), '_depend':'' # },{ # Hidden # '_check':l_and(isscalar,l_not(iscomplex),isintent_hide) }, { # Hidden 'frompyobj':{hasinitvalue:'\t#varname# = #init#;'}, 'need':typedef_need_dict, '_check':l_and(isscalar, l_not(iscomplex), isintent_hide), '_depend':'' }, { # Common 'frompyobj':{debugcapi:'\tfprintf(stderr,"#vardebugshowvalue#\\n",#varname#);'}, '_check':l_and(isscalar, l_not(iscomplex)), '_depend':'' }, # Complex scalars { # Common 'decl':'\t#ctype# #varname#;', 'callfortran':{isintent_c:'#varname#,',l_not(isintent_c):'&#varname#,'}, 'pyobjfrom':{debugcapi:'\tfprintf(stderr,"#vardebugshowvalue#\\n",#varname#.r,#varname#.i);'}, 'return':{isintent_out:',#varname#_capi'}, '_check':iscomplex }, { # Not hidden 'decl':'\tPyObject *#varname#_capi = Py_None;', 'argformat':{isrequired:'O'}, 'keyformat':{isoptional:'O'}, 'args_capi':{isrequired:',&#varname#_capi'}, 'keys_capi':{isoptional:',&#varname#_capi'}, 'need':{isintent_inout:'try_pyarr_from_#ctype#'}, 'pyobjfrom':{isintent_inout:"""\ \t\tf2py_success = try_pyarr_from_#ctype#(#varname#_capi,&#varname#); \t\tif (f2py_success) {"""}, 'closepyobjfrom':{isintent_inout:"\t\t} /*if (f2py_success) of #varname# pyobjfrom*/"}, '_check':l_and(iscomplex, isintent_nothide) }, { 'frompyobj':[{hasinitvalue:'\tif (#varname#_capi==Py_None) {#varname#.r = #init.r#, #varname#.i = #init.i#;} else'}, {l_and(isoptional, l_not(hasinitvalue)):'\tif (#varname#_capi != Py_None)'}, # '\t\tf2py_success = #ctype#_from_pyobj(&#varname#,#varname#_capi,"#ctype#_from_pyobj failed in converting #nth# `#varname#\' of #pyname# to C #ctype#\\n");' '\t\tf2py_success = #ctype#_from_pyobj(&#varname#,#varname#_capi,"#pyname#() #nth# (#varname#) can\'t be converted to #ctype#");' '\n\tif (f2py_success) {'], 'cleanupfrompyobj':'\t} /*if (f2py_success) of #varname# frompyobj*/', 'need':['#ctype#_from_pyobj'], '_check':l_and(iscomplex, isintent_nothide), '_depend':'' }, { # Hidden 'decl':{isintent_out:'\tPyObject *#varname#_capi = Py_None;'}, '_check':l_and(iscomplex, isintent_hide) }, { 'frompyobj': {hasinitvalue:'\t#varname#.r = #init.r#, #varname#.i = #init.i#;'}, '_check':l_and(iscomplex, isintent_hide), '_depend':'' }, { # Common 'pyobjfrom':{isintent_out:'\t#varname#_capi = pyobj_from_#ctype#1(#varname#);'}, 'need':['pyobj_from_#ctype#1'], '_check':iscomplex }, { 'frompyobj':{debugcapi:'\tfprintf(stderr,"#vardebugshowvalue#\\n",#varname#.r,#varname#.i);'}, '_check':iscomplex, '_depend':'' }, # String { # Common 'decl':['\t#ctype# #varname# = NULL;', '\tint slen(#varname#);', '\tPyObject *#varname#_capi = Py_None;'], 'callfortran':'#varname#,', 'callfortranappend':'slen(#varname#),', 'pyobjfrom':{debugcapi:'\tfprintf(stderr,"#vardebugshowvalue#\\n",slen(#varname#),#varname#);'}, # 'freemem':'\tSTRINGFREE(#varname#);', 'return':{isintent_out:',#varname#'}, 'need':['len..'],#'STRINGFREE'], '_check':isstring }, { # Common 'frompyobj':"""\ \tslen(#varname#) = #length#; \tf2py_success = #ctype#_from_pyobj(&#varname#,&slen(#varname#),#init#,#varname#_capi,\"#ctype#_from_pyobj failed in converting #nth# `#varname#\' of #pyname# to C #ctype#\"); \tif (f2py_success) {""", 'cleanupfrompyobj':"""\ \t\tSTRINGFREE(#varname#); \t} /*if (f2py_success) of #varname#*/""", 'need':['#ctype#_from_pyobj', 'len..', 'STRINGFREE'], '_check':isstring, '_depend':'' }, { # Not hidden 'argformat':{isrequired:'O'}, 'keyformat':{isoptional:'O'}, 'args_capi':{isrequired:',&#varname#_capi'}, 'keys_capi':{isoptional:',&#varname#_capi'}, 'pyobjfrom':{isintent_inout:'''\ \tf2py_success = try_pyarr_from_#ctype#(#varname#_capi,#varname#); \tif (f2py_success) {'''}, 'closepyobjfrom':{isintent_inout:'\t} /*if (f2py_success) of #varname# pyobjfrom*/'}, 'need':{isintent_inout:'try_pyarr_from_#ctype#'}, '_check':l_and(isstring, isintent_nothide) }, { # Hidden '_check':l_and(isstring, isintent_hide) }, { 'frompyobj':{debugcapi:'\tfprintf(stderr,"#vardebugshowvalue#\\n",slen(#varname#),#varname#);'}, '_check':isstring, '_depend':'' }, # Array { # Common 'decl':['\t#ctype# *#varname# = NULL;', '\tnpy_intp #varname#_Dims[#rank#] = {#rank*[-1]#};', '\tconst int #varname#_Rank = #rank#;', '\tPyArrayObject *capi_#varname#_tmp = NULL;', '\tint capi_#varname#_intent = 0;', ], 'callfortran':'#varname#,', 'return':{isintent_out:',capi_#varname#_tmp'}, 'need':'len..', '_check':isarray }, { # intent(overwrite) array 'decl': '\tint capi_overwrite_#varname# = 1;', 'kwlistxa': '"overwrite_#varname#",', 'xaformat': 'i', 'keys_xa': ',&capi_overwrite_#varname#', 'docsignxa': 'overwrite_#varname#=1,', 'docsignxashort': 'overwrite_#varname#,', 'docstropt': 'overwrite_#varname# : input int, optional\\n Default: 1', '_check': l_and(isarray, isintent_overwrite), }, { 'frompyobj': '\tcapi_#varname#_intent |= (capi_overwrite_#varname#?0:F2PY_INTENT_COPY);', '_check': l_and(isarray, isintent_overwrite), '_depend': '', }, { # intent(copy) array 'decl': '\tint capi_overwrite_#varname# = 0;', 'kwlistxa': '"overwrite_#varname#",', 'xaformat': 'i', 'keys_xa': ',&capi_overwrite_#varname#', 'docsignxa': 'overwrite_#varname#=0,', 'docsignxashort': 'overwrite_#varname#,', 'docstropt': 'overwrite_#varname# : input int, optional\\n Default: 0', '_check': l_and(isarray, isintent_copy), }, { 'frompyobj': '\tcapi_#varname#_intent |= (capi_overwrite_#varname#?0:F2PY_INTENT_COPY);', '_check': l_and(isarray, isintent_copy), '_depend': '', }, { 'need':[{hasinitvalue:'forcomb'}, {hasinitvalue:'CFUNCSMESS'}], '_check':isarray, '_depend':'' }, { # Not hidden 'decl':'\tPyObject *#varname#_capi = Py_None;', 'argformat':{isrequired:'O'}, 'keyformat':{isoptional:'O'}, 'args_capi':{isrequired:',&#varname#_capi'}, 'keys_capi':{isoptional:',&#varname#_capi'}, # 'pyobjfrom':{isintent_inout:"""\ # /* Partly because of the following hack, intent(inout) is depreciated, # Use intent(in,out) instead. # \tif ((#varname#_capi != Py_None) && PyArray_Check(#varname#_capi) \\ # \t\t&& (#varname#_capi != (PyObject *)capi_#varname#_tmp)) { # \t\tif (((PyArrayObject *)#varname#_capi)->nd != capi_#varname#_tmp->nd) { # \t\t\tif (#varname#_capi != capi_#varname#_tmp->base) # \t\t\t\tcopy_ND_array((PyArrayObject *)capi_#varname#_tmp->base,(PyArrayObject *)#varname#_capi); # \t\t} else # \t\t\tcopy_ND_array(capi_#varname#_tmp,(PyArrayObject *)#varname#_capi); # \t} # */ # """}, # 'need':{isintent_inout:'copy_ND_array'}, '_check':l_and(isarray, isintent_nothide) }, { 'frompyobj':['\t#setdims#;', '\tcapi_#varname#_intent |= #intent#;', {isintent_hide:'\tcapi_#varname#_tmp = array_from_pyobj(#atype#,#varname#_Dims,#varname#_Rank,capi_#varname#_intent,Py_None);'}, {isintent_nothide:'\tcapi_#varname#_tmp = array_from_pyobj(#atype#,#varname#_Dims,#varname#_Rank,capi_#varname#_intent,#varname#_capi);'}, """\ \tif (capi_#varname#_tmp == NULL) { \t\tif (!PyErr_Occurred()) \t\t\tPyErr_SetString(#modulename#_error,\"failed in converting #nth# `#varname#\' of #pyname# to C/Fortran array\" ); \t} else { \t\t#varname# = (#ctype# *)(capi_#varname#_tmp->data); """, {hasinitvalue:[ {isintent_nothide:'\tif (#varname#_capi == Py_None) {'}, {isintent_hide:'\t{'}, {iscomplexarray:'\t\t#ctype# capi_c;'}, """\ \t\tint *_i,capi_i=0; \t\tCFUNCSMESS(\"#name#: Initializing #varname#=#init#\\n\"); \t\tif (initforcomb(capi_#varname#_tmp->dimensions,capi_#varname#_tmp->nd,1)) { \t\t\twhile ((_i = nextforcomb())) \t\t\t\t#varname#[capi_i++] = #init#; /* fortran way */ \t\t} else { \t\t\tif (!PyErr_Occurred()) \t\t\t\tPyErr_SetString(#modulename#_error,\"Initialization of #nth# #varname# failed (initforcomb).\"); \t\t\tf2py_success = 0; \t\t} \t} \tif (f2py_success) {"""]}, ], 'cleanupfrompyobj':[ # note that this list will be reversed '\t} /*if (capi_#varname#_tmp == NULL) ... else of #varname#*/', {l_not(l_or(isintent_out, isintent_hide)):"""\ \tif((PyObject *)capi_#varname#_tmp!=#varname#_capi) { \t\tPy_XDECREF(capi_#varname#_tmp); }"""}, {l_and(isintent_hide, l_not(isintent_out)):"""\t\tPy_XDECREF(capi_#varname#_tmp);"""}, {hasinitvalue:'\t} /*if (f2py_success) of #varname# init*/'}, ], '_check':isarray, '_depend':'' }, # { # Hidden # 'freemem':{l_not(isintent_out):'\tPy_XDECREF(capi_#varname#_tmp);'}, # '_check':l_and(isarray,isintent_hide) # }, # Scalararray { # Common '_check':l_and(isarray, l_not(iscomplexarray)) }, { # Not hidden '_check':l_and(isarray, l_not(iscomplexarray), isintent_nothide) }, # Integer*1 array {'need':'#ctype#', '_check':isint1array, '_depend':'' }, # Integer*-1 array {'need':'#ctype#', '_check':isunsigned_chararray, '_depend':'' }, # Integer*-2 array {'need':'#ctype#', '_check':isunsigned_shortarray, '_depend':'' }, # Integer*-8 array {'need':'#ctype#', '_check':isunsigned_long_longarray, '_depend':'' }, # Complexarray {'need':'#ctype#', '_check':iscomplexarray, '_depend':'' }, # Stringarray { 'callfortranappend':{isarrayofstrings:'flen(#varname#),'}, 'need':'string', '_check':isstringarray } ] ################# Rules for checking ############### check_rules=[ { 'frompyobj':{debugcapi:'\tfprintf(stderr,\"debug-capi:Checking `#check#\'\\n\");'}, 'need':'len..' }, { 'frompyobj':'\tCHECKSCALAR(#check#,\"#check#\",\"#nth# #varname#\",\"#varshowvalue#\",#varname#) {', 'cleanupfrompyobj':'\t} /*CHECKSCALAR(#check#)*/', 'need':'CHECKSCALAR', '_check':l_and(isscalar, l_not(iscomplex)), '_break':'' }, { 'frompyobj':'\tCHECKSTRING(#check#,\"#check#\",\"#nth# #varname#\",\"#varshowvalue#\",#varname#) {', 'cleanupfrompyobj':'\t} /*CHECKSTRING(#check#)*/', 'need':'CHECKSTRING', '_check':isstring, '_break':'' }, { 'need':'CHECKARRAY', 'frompyobj':'\tCHECKARRAY(#check#,\"#check#\",\"#nth# #varname#\") {', 'cleanupfrompyobj':'\t} /*CHECKARRAY(#check#)*/', '_check':isarray, '_break':'' }, { 'need': 'CHECKGENERIC', 'frompyobj': '\tCHECKGENERIC(#check#,\"#check#\",\"#nth# #varname#\") {', 'cleanupfrompyobj': '\t} /*CHECKGENERIC(#check#)*/', } ] ########## Applying the rules. No need to modify what follows ############# #################### Build C/API module ####################### def buildmodule(m, um): """ Return """ global f2py_version, options outmess('\tBuilding module "%s"...\n'%(m['name'])) ret = {} mod_rules=defmod_rules[:] vrd=modsign2map(m) rd=dictappend({'f2py_version':f2py_version}, vrd) funcwrappers = [] funcwrappers2 = [] # F90 codes for n in m['interfaced']: nb=None for bi in m['body']: if not bi['block']=='interface': errmess('buildmodule: Expected interface block. Skipping.\n') continue for b in bi['body']: if b['name']==n: nb=b;break if not nb: errmess('buildmodule: Could not found the body of interfaced routine "%s". Skipping.\n'%(n)) continue nb_list = [nb] if 'entry' in nb: for k, a in nb['entry'].items(): nb1 = copy.deepcopy(nb) del nb1['entry'] nb1['name'] = k nb1['args'] = a nb_list.append(nb1) for nb in nb_list: api, wrap=buildapi(nb) if wrap: if ismoduleroutine(nb): funcwrappers2.append(wrap) else: funcwrappers.append(wrap) ar=applyrules(api, vrd) rd=dictappend(rd, ar) # Construct COMMON block support cr, wrap = common_rules.buildhooks(m) if wrap: funcwrappers.append(wrap) ar=applyrules(cr, vrd) rd=dictappend(rd, ar) # Construct F90 module support mr, wrap = f90mod_rules.buildhooks(m) if wrap: funcwrappers2.append(wrap) ar=applyrules(mr, vrd) rd=dictappend(rd, ar) for u in um: ar=use_rules.buildusevars(u, m['use'][u['name']]) rd=dictappend(rd, ar) needs=cfuncs.get_needs() code={} for n in needs.keys(): code[n]=[] for k in needs[n]: c='' if k in cfuncs.includes0: c=cfuncs.includes0[k] elif k in cfuncs.includes: c=cfuncs.includes[k] elif k in cfuncs.userincludes: c=cfuncs.userincludes[k] elif k in cfuncs.typedefs: c=cfuncs.typedefs[k] elif k in cfuncs.typedefs_generated: c=cfuncs.typedefs_generated[k] elif k in cfuncs.cppmacros: c=cfuncs.cppmacros[k] elif k in cfuncs.cfuncs: c=cfuncs.cfuncs[k] elif k in cfuncs.callbacks: c=cfuncs.callbacks[k] elif k in cfuncs.f90modhooks: c=cfuncs.f90modhooks[k] elif k in cfuncs.commonhooks: c=cfuncs.commonhooks[k] else: errmess('buildmodule: unknown need %s.\n'%(repr(k)));continue code[n].append(c) mod_rules.append(code) for r in mod_rules: if ('_check' in r and r['_check'](m)) or ('_check' not in r): ar=applyrules(r, vrd, m) rd=dictappend(rd, ar) ar=applyrules(module_rules, rd) fn = os.path.join(options['buildpath'], vrd['coutput']) ret['csrc'] = fn f=open(fn, 'w') f.write(ar['modulebody'].replace('\t', 2*' ')) f.close() outmess('\tWrote C/API module "%s" to file "%s"\n'%(m['name'], fn)) if options['dorestdoc']: fn = os.path.join(options['buildpath'], vrd['modulename']+'module.rest') f=open(fn, 'w') f.write('.. -*- rest -*-\n') f.write('\n'.join(ar['restdoc'])) f.close() outmess('\tReST Documentation is saved to file "%s/%smodule.rest"\n'%(options['buildpath'], vrd['modulename'])) if options['dolatexdoc']: fn = os.path.join(options['buildpath'], vrd['modulename']+'module.tex') ret['ltx'] = fn f=open(fn, 'w') f.write('%% This file is auto-generated with f2py (version:%s)\n'%(f2py_version)) if 'shortlatex' not in options: f.write('\\documentclass{article}\n\\usepackage{a4wide}\n\\begin{document}\n\\tableofcontents\n\n') f.write('\n'.join(ar['latexdoc'])) if 'shortlatex' not in options: f.write('\\end{document}') f.close() outmess('\tDocumentation is saved to file "%s/%smodule.tex"\n'%(options['buildpath'], vrd['modulename'])) if funcwrappers: wn = os.path.join(options['buildpath'], vrd['f2py_wrapper_output']) ret['fsrc'] = wn f=open(wn, 'w') f.write('C -*- fortran -*-\n') f.write('C This file is autogenerated with f2py (version:%s)\n'%(f2py_version)) f.write('C It contains Fortran 77 wrappers to fortran functions.\n') lines = [] for l in ('\n\n'.join(funcwrappers)+'\n').split('\n'): if l and l[0]==' ': while len(l)>=66: lines.append(l[:66]+'\n &') l = l[66:] lines.append(l+'\n') else: lines.append(l+'\n') lines = ''.join(lines).replace('\n &\n', '\n') f.write(lines) f.close() outmess('\tFortran 77 wrappers are saved to "%s"\n'%(wn)) if funcwrappers2: wn = os.path.join(options['buildpath'], '%s-f2pywrappers2.f90'%(vrd['modulename'])) ret['fsrc'] = wn f=open(wn, 'w') f.write('! -*- f90 -*-\n') f.write('! This file is autogenerated with f2py (version:%s)\n'%(f2py_version)) f.write('! It contains Fortran 90 wrappers to fortran functions.\n') lines = [] for l in ('\n\n'.join(funcwrappers2)+'\n').split('\n'): if len(l)>72 and l[0]==' ': lines.append(l[:72]+'&\n &') l = l[72:] while len(l)>66: lines.append(l[:66]+'&\n &') l = l[66:] lines.append(l+'\n') else: lines.append(l+'\n') lines = ''.join(lines).replace('\n &\n', '\n') f.write(lines) f.close() outmess('\tFortran 90 wrappers are saved to "%s"\n'%(wn)) return ret ################## Build C/API function ############# stnd={1:'st',2:'nd',3:'rd',4:'th',5:'th',6:'th',7:'th',8:'th',9:'th',0:'th'} def buildapi(rout): rout, wrap = func2subr.assubr(rout) args, depargs=getargs2(rout) capi_maps.depargs=depargs var=rout['vars'] auxvars = [a for a in var.keys() if isintent_aux(var[a])] if ismoduleroutine(rout): outmess('\t\t\tConstructing wrapper function "%s.%s"...\n'%(rout['modulename'], rout['name'])) else: outmess('\t\tConstructing wrapper function "%s"...\n'%(rout['name'])) # Routine vrd=routsign2map(rout) rd=dictappend({}, vrd) for r in rout_rules: if ('_check' in r and r['_check'](rout)) or ('_check' not in r): ar=applyrules(r, vrd, rout) rd=dictappend(rd, ar) # Args nth, nthk=0, 0 savevrd={} for a in args: vrd=sign2map(a, var[a]) if isintent_aux(var[a]): _rules = aux_rules else: _rules = arg_rules if not isintent_hide(var[a]): if not isoptional(var[a]): nth=nth+1 vrd['nth']=repr(nth)+stnd[nth%10]+' argument' else: nthk=nthk+1 vrd['nth']=repr(nthk)+stnd[nthk%10]+' keyword' else: vrd['nth']='hidden' savevrd[a]=vrd for r in _rules: if '_depend' in r: continue if ('_check' in r and r['_check'](var[a])) or ('_check' not in r): ar=applyrules(r, vrd, var[a]) rd=dictappend(rd, ar) if '_break' in r: break for a in depargs: if isintent_aux(var[a]): _rules = aux_rules else: _rules = arg_rules vrd=savevrd[a] for r in _rules: if '_depend' not in r: continue if ('_check' in r and r['_check'](var[a])) or ('_check' not in r): ar=applyrules(r, vrd, var[a]) rd=dictappend(rd, ar) if '_break' in r: break if 'check' in var[a]: for c in var[a]['check']: vrd['check']=c ar=applyrules(check_rules, vrd, var[a]) rd=dictappend(rd, ar) if isinstance(rd['cleanupfrompyobj'], list): rd['cleanupfrompyobj'].reverse() if isinstance(rd['closepyobjfrom'], list): rd['closepyobjfrom'].reverse() rd['docsignature']=stripcomma(replace('#docsign##docsignopt##docsignxa#', {'docsign':rd['docsign'], 'docsignopt':rd['docsignopt'], 'docsignxa':rd['docsignxa']})) optargs=stripcomma(replace('#docsignopt##docsignxa#', {'docsignxa':rd['docsignxashort'], 'docsignopt':rd['docsignoptshort']} )) if optargs=='': rd['docsignatureshort']=stripcomma(replace('#docsign#', {'docsign':rd['docsign']})) else: rd['docsignatureshort']=replace('#docsign#[#docsignopt#]', {'docsign': rd['docsign'], 'docsignopt': optargs, }) rd['latexdocsignatureshort']=rd['docsignatureshort'].replace('_', '\\_') rd['latexdocsignatureshort']=rd['latexdocsignatureshort'].replace(',', ', ') cfs=stripcomma(replace('#callfortran##callfortranappend#', {'callfortran':rd['callfortran'],'callfortranappend':rd['callfortranappend']})) if len(rd['callfortranappend'])>1: rd['callcompaqfortran']=stripcomma(replace('#callfortran# 0,#callfortranappend#', {'callfortran':rd['callfortran'],'callfortranappend':rd['callfortranappend']})) else: rd['callcompaqfortran']=cfs rd['callfortran']=cfs if isinstance(rd['docreturn'], list): rd['docreturn']=stripcomma(replace('#docreturn#', {'docreturn':rd['docreturn']}))+' = ' rd['docstrsigns']=[] rd['latexdocstrsigns']=[] for k in ['docstrreq', 'docstropt', 'docstrout', 'docstrcbs']: if k in rd and isinstance(rd[k], list): rd['docstrsigns']=rd['docstrsigns']+rd[k] k='latex'+k if k in rd and isinstance(rd[k], list): rd['latexdocstrsigns']=rd['latexdocstrsigns']+rd[k][0:1]+\ ['\\begin{description}']+rd[k][1:]+\ ['\\end{description}'] # Workaround for Python 2.6, 2.6.1 bug: http://bugs.python.org/issue4720 if rd['keyformat'] or rd['xaformat']: argformat = rd['argformat'] if isinstance(argformat, list): argformat.append('|') else: assert isinstance(argformat, str), repr((argformat, type(argformat))) rd['argformat'] += '|' ar=applyrules(routine_rules, rd) if ismoduleroutine(rout): outmess('\t\t\t %s\n'%(ar['docshort'])) else: outmess('\t\t %s\n'%(ar['docshort'])) return ar, wrap #################### EOF rules.py ####################### numpy-1.8.2/numpy/ma/0000775000175100017510000000000012371375430015576 5ustar vagrantvagrant00000000000000numpy-1.8.2/numpy/ma/mrecords.py0000664000175100017510000006645312370216243017777 0ustar vagrantvagrant00000000000000""":mod:`numpy.ma..mrecords` Defines the equivalent of :class:`numpy.recarrays` for masked arrays, where fields can be accessed as attributes. Note that :class:`numpy.ma.MaskedArray` already supports structured datatypes and the masking of individual fields. :author: Pierre Gerard-Marchant """ from __future__ import division, absolute_import, print_function #!!!: * We should make sure that no field is called '_mask','mask','_fieldmask', #!!!: or whatever restricted keywords. #!!!: An idea would be to no bother in the first place, and then rename the #!!!: invalid fields with a trailing underscore... #!!!: Maybe we could just overload the parser function ? __author__ = "Pierre GF Gerard-Marchant" import sys import warnings import numpy as np import numpy.core.numerictypes as ntypes from numpy.compat import basestring from numpy import ( bool_, dtype, ndarray, recarray, array as narray ) from numpy.core.records import ( fromarrays as recfromarrays, fromrecords as recfromrecords ) _byteorderconv = np.core.records._byteorderconv _typestr = ntypes._typestr import numpy.ma as ma from numpy.ma import MAError, MaskedArray, masked, nomask, masked_array, \ getdata, getmaskarray, filled _check_fill_value = ma.core._check_fill_value __all__ = ['MaskedRecords', 'mrecarray', 'fromarrays', 'fromrecords', 'fromtextfile', 'addfield', ] reserved_fields = ['_data', '_mask', '_fieldmask', 'dtype'] def _getformats(data): "Returns the formats of each array of arraylist as a comma-separated string." if hasattr(data, 'dtype'): return ",".join([desc[1] for desc in data.dtype.descr]) formats = '' for obj in data: obj = np.asarray(obj) formats += _typestr[obj.dtype.type] if issubclass(obj.dtype.type, ntypes.flexible): formats += repr(obj.itemsize) formats += ',' return formats[:-1] def _checknames(descr, names=None): """Checks that the field names of the descriptor ``descr`` are not some reserved keywords. If this is the case, a default 'f%i' is substituted. If the argument `names` is not None, updates the field names to valid names. """ ndescr = len(descr) default_names = ['f%i' % i for i in range(ndescr)] if names is None: new_names = default_names else: if isinstance(names, (tuple, list)): new_names = names elif isinstance(names, str): new_names = names.split(',') else: raise NameError("illegal input names %s" % repr(names)) nnames = len(new_names) if nnames < ndescr: new_names += default_names[nnames:] ndescr = [] for (n, d, t) in zip(new_names, default_names, descr.descr): if n in reserved_fields: if t[0] in reserved_fields: ndescr.append((d, t[1])) else: ndescr.append(t) else: ndescr.append((n, t[1])) return np.dtype(ndescr) def _get_fieldmask(self): mdescr = [(n, '|b1') for n in self.dtype.names] fdmask = np.empty(self.shape, dtype=mdescr) fdmask.flat = tuple([False] * len(mdescr)) return fdmask class MaskedRecords(MaskedArray, object): """ *IVariables*: _data : {recarray} Underlying data, as a record array. _mask : {boolean array} Mask of the records. A record is masked when all its fields are masked. _fieldmask : {boolean recarray} Record array of booleans, setting the mask of each individual field of each record. _fill_value : {record} Filling values for each field. """ #............................................ def __new__(cls, shape, dtype=None, buf=None, offset=0, strides=None, formats=None, names=None, titles=None, byteorder=None, aligned=False, mask=nomask, hard_mask=False, fill_value=None, keep_mask=True, copy=False, **options): # self = recarray.__new__(cls, shape, dtype=dtype, buf=buf, offset=offset, strides=strides, formats=formats, names=names, titles=titles, byteorder=byteorder, aligned=aligned,) # mdtype = ma.make_mask_descr(self.dtype) if mask is nomask or not np.size(mask): if not keep_mask: self._mask = tuple([False] * len(mdtype)) else: mask = np.array(mask, copy=copy) if mask.shape != self.shape: (nd, nm) = (self.size, mask.size) if nm == 1: mask = np.resize(mask, self.shape) elif nm == nd: mask = np.reshape(mask, self.shape) else: msg = "Mask and data not compatible: data size is %i, " + \ "mask size is %i." raise MAError(msg % (nd, nm)) copy = True if not keep_mask: self.__setmask__(mask) self._sharedmask = True else: if mask.dtype == mdtype: _mask = mask else: _mask = np.array([tuple([m] * len(mdtype)) for m in mask], dtype=mdtype) self._mask = _mask return self #...................................................... def __array_finalize__(self, obj): # Make sure we have a _fieldmask by default .. _mask = getattr(obj, '_mask', None) if _mask is None: objmask = getattr(obj, '_mask', nomask) _dtype = ndarray.__getattribute__(self, 'dtype') if objmask is nomask: _mask = ma.make_mask_none(self.shape, dtype=_dtype) else: mdescr = ma.make_mask_descr(_dtype) _mask = narray([tuple([m] * len(mdescr)) for m in objmask], dtype=mdescr).view(recarray) # Update some of the attributes _dict = self.__dict__ _dict.update(_mask=_mask) self._update_from(obj) if _dict['_baseclass'] == ndarray: _dict['_baseclass'] = recarray return def _getdata(self): "Returns the data as a recarray." return ndarray.view(self, recarray) _data = property(fget=_getdata) def _getfieldmask(self): "Alias to mask" return self._mask _fieldmask = property(fget=_getfieldmask) def __len__(self): "Returns the length" # We have more than one record if self.ndim: return len(self._data) # We have only one record: return the nb of fields return len(self.dtype) def __getattribute__(self, attr): try: return object.__getattribute__(self, attr) except AttributeError: # attr must be a fieldname pass fielddict = ndarray.__getattribute__(self, 'dtype').fields try: res = fielddict[attr][:2] except (TypeError, KeyError): raise AttributeError("record array has no attribute %s" % attr) # So far, so good... _localdict = ndarray.__getattribute__(self, '__dict__') _data = ndarray.view(self, _localdict['_baseclass']) obj = _data.getfield(*res) if obj.dtype.fields: raise NotImplementedError("MaskedRecords is currently limited to"\ "simple records...") # Get some special attributes # Reset the object's mask hasmasked = False _mask = _localdict.get('_mask', None) if _mask is not None: try: _mask = _mask[attr] except IndexError: # Couldn't find a mask: use the default (nomask) pass hasmasked = _mask.view((np.bool, (len(_mask.dtype) or 1))).any() if (obj.shape or hasmasked): obj = obj.view(MaskedArray) obj._baseclass = ndarray obj._isfield = True obj._mask = _mask # Reset the field values _fill_value = _localdict.get('_fill_value', None) if _fill_value is not None: try: obj._fill_value = _fill_value[attr] except ValueError: obj._fill_value = None else: obj = obj.item() return obj def __setattr__(self, attr, val): "Sets the attribute attr to the value val." # Should we call __setmask__ first ? if attr in ['mask', 'fieldmask']: self.__setmask__(val) return # Create a shortcut (so that we don't have to call getattr all the time) _localdict = object.__getattribute__(self, '__dict__') # Check whether we're creating a new field newattr = attr not in _localdict try: # Is attr a generic attribute ? ret = object.__setattr__(self, attr, val) except: # Not a generic attribute: exit if it's not a valid field fielddict = ndarray.__getattribute__(self, 'dtype').fields or {} optinfo = ndarray.__getattribute__(self, '_optinfo') or {} if not (attr in fielddict or attr in optinfo): exctype, value = sys.exc_info()[:2] raise exctype(value) else: # Get the list of names ...... fielddict = ndarray.__getattribute__(self, 'dtype').fields or {} # Check the attribute if attr not in fielddict: return ret if newattr: # We just added this one try: # or this setattr worked on an internal # attribute. object.__delattr__(self, attr) except: return ret # Let's try to set the field try: res = fielddict[attr][:2] except (TypeError, KeyError): raise AttributeError("record array has no attribute %s" % attr) # if val is masked: _fill_value = _localdict['_fill_value'] if _fill_value is not None: dval = _localdict['_fill_value'][attr] else: dval = val mval = True else: dval = filled(val) mval = getmaskarray(val) obj = ndarray.__getattribute__(self, '_data').setfield(dval, *res) _localdict['_mask'].__setitem__(attr, mval) return obj def __getitem__(self, indx): """Returns all the fields sharing the same fieldname base. The fieldname base is either `_data` or `_mask`.""" _localdict = self.__dict__ _mask = ndarray.__getattribute__(self, '_mask') _data = ndarray.view(self, _localdict['_baseclass']) # We want a field ........ if isinstance(indx, basestring): #!!!: Make sure _sharedmask is True to propagate back to _fieldmask #!!!: Don't use _set_mask, there are some copies being made... #!!!: ...that break propagation #!!!: Don't force the mask to nomask, that wrecks easy masking obj = _data[indx].view(MaskedArray) obj._mask = _mask[indx] obj._sharedmask = True fval = _localdict['_fill_value'] if fval is not None: obj._fill_value = fval[indx] # Force to masked if the mask is True if not obj.ndim and obj._mask: return masked return obj # We want some elements .. # First, the data ........ obj = np.array(_data[indx], copy=False).view(mrecarray) obj._mask = np.array(_mask[indx], copy=False).view(recarray) return obj #.... def __setitem__(self, indx, value): "Sets the given record to value." MaskedArray.__setitem__(self, indx, value) if isinstance(indx, basestring): self._mask[indx] = ma.getmaskarray(value) def __str__(self): "Calculates the string representation." if self.size > 1: mstr = ["(%s)" % ",".join([str(i) for i in s]) for s in zip(*[getattr(self, f) for f in self.dtype.names])] return "[%s]" % ", ".join(mstr) else: mstr = ["%s" % ",".join([str(i) for i in s]) for s in zip([getattr(self, f) for f in self.dtype.names])] return "(%s)" % ", ".join(mstr) # def __repr__(self): "Calculates the repr representation." _names = self.dtype.names fmt = "%%%is : %%s" % (max([len(n) for n in _names]) + 4,) reprstr = [fmt % (f, getattr(self, f)) for f in self.dtype.names] reprstr.insert(0, 'masked_records(') reprstr.extend([fmt % (' fill_value', self.fill_value), ' )']) return str("\n".join(reprstr)) # #...................................................... def view(self, dtype=None, type=None): """Returns a view of the mrecarray.""" # OK, basic copy-paste from MaskedArray.view... if dtype is None: if type is None: output = ndarray.view(self) else: output = ndarray.view(self, type) # Here again... elif type is None: try: if issubclass(dtype, ndarray): output = ndarray.view(self, dtype) dtype = None else: output = ndarray.view(self, dtype) # OK, there's the change except TypeError: dtype = np.dtype(dtype) # we need to revert to MaskedArray, but keeping the possibility # ...of subclasses (eg, TimeSeriesRecords), so we'll force a type # ...set to the first parent if dtype.fields is None: basetype = self.__class__.__bases__[0] output = self.__array__().view(dtype, basetype) output._update_from(self) else: output = ndarray.view(self, dtype) output._fill_value = None else: output = ndarray.view(self, dtype, type) # Update the mask, just like in MaskedArray.view if (getattr(output, '_mask', nomask) is not nomask): mdtype = ma.make_mask_descr(output.dtype) output._mask = self._mask.view(mdtype, ndarray) output._mask.shape = output.shape return output def harden_mask(self): "Forces the mask to hard" self._hardmask = True def soften_mask(self): "Forces the mask to soft" self._hardmask = False def copy(self): """Returns a copy of the masked record.""" _localdict = self.__dict__ copied = self._data.copy().view(type(self)) copied._mask = self._mask.copy() return copied def tolist(self, fill_value=None): """Copy the data portion of the array to a hierarchical python list and returns that list. Data items are converted to the nearest compatible Python type. Masked values are converted to fill_value. If fill_value is None, the corresponding entries in the output list will be ``None``. """ if fill_value is not None: return self.filled(fill_value).tolist() result = narray(self.filled().tolist(), dtype=object) mask = narray(self._mask.tolist()) result[mask] = None return result.tolist() #-------------------------------------------- # Pickling def __getstate__(self): """Return the internal state of the masked array, for pickling purposes. """ state = (1, self.shape, self.dtype, self.flags.fnc, self._data.tostring(), self._mask.tostring(), self._fill_value, ) return state # def __setstate__(self, state): """Restore the internal state of the masked array, for pickling purposes. ``state`` is typically the output of the ``__getstate__`` output, and is a 5-tuple: - class name - a tuple giving the shape of the data - a typecode for the data - a binary string for the data - a binary string for the mask. """ (ver, shp, typ, isf, raw, msk, flv) = state ndarray.__setstate__(self, (shp, typ, isf, raw)) mdtype = dtype([(k, bool_) for (k, _) in self.dtype.descr]) self.__dict__['_mask'].__setstate__((shp, mdtype, isf, msk)) self.fill_value = flv # def __reduce__(self): """Return a 3-tuple for pickling a MaskedArray. """ return (_mrreconstruct, (self.__class__, self._baseclass, (0,), 'b',), self.__getstate__()) def _mrreconstruct(subtype, baseclass, baseshape, basetype,): """Internal function that builds a new MaskedArray from the information stored in a pickle. """ _data = ndarray.__new__(baseclass, baseshape, basetype).view(subtype) # _data._mask = ndarray.__new__(ndarray, baseshape, 'b1') # return _data _mask = ndarray.__new__(ndarray, baseshape, 'b1') return subtype.__new__(subtype, _data, mask=_mask, dtype=basetype,) mrecarray = MaskedRecords #####--------------------------------------------------------------------------- #---- --- Constructors --- #####--------------------------------------------------------------------------- def fromarrays(arraylist, dtype=None, shape=None, formats=None, names=None, titles=None, aligned=False, byteorder=None, fill_value=None): """Creates a mrecarray from a (flat) list of masked arrays. Parameters ---------- arraylist : sequence A list of (masked) arrays. Each element of the sequence is first converted to a masked array if needed. If a 2D array is passed as argument, it is processed line by line dtype : {None, dtype}, optional Data type descriptor. shape : {None, integer}, optional Number of records. If None, shape is defined from the shape of the first array in the list. formats : {None, sequence}, optional Sequence of formats for each individual field. If None, the formats will be autodetected by inspecting the fields and selecting the highest dtype possible. names : {None, sequence}, optional Sequence of the names of each field. fill_value : {None, sequence}, optional Sequence of data to be used as filling values. Notes ----- Lists of tuples should be preferred over lists of lists for faster processing. """ datalist = [getdata(x) for x in arraylist] masklist = [np.atleast_1d(getmaskarray(x)) for x in arraylist] _array = recfromarrays(datalist, dtype=dtype, shape=shape, formats=formats, names=names, titles=titles, aligned=aligned, byteorder=byteorder).view(mrecarray) _array._mask.flat = list(zip(*masklist)) if fill_value is not None: _array.fill_value = fill_value return _array #.............................................................................. def fromrecords(reclist, dtype=None, shape=None, formats=None, names=None, titles=None, aligned=False, byteorder=None, fill_value=None, mask=nomask): """Creates a MaskedRecords from a list of records. Parameters ---------- reclist : sequence A list of records. Each element of the sequence is first converted to a masked array if needed. If a 2D array is passed as argument, it is processed line by line dtype : {None, dtype}, optional Data type descriptor. shape : {None,int}, optional Number of records. If None, ``shape`` is defined from the shape of the first array in the list. formats : {None, sequence}, optional Sequence of formats for each individual field. If None, the formats will be autodetected by inspecting the fields and selecting the highest dtype possible. names : {None, sequence}, optional Sequence of the names of each field. fill_value : {None, sequence}, optional Sequence of data to be used as filling values. mask : {nomask, sequence}, optional. External mask to apply on the data. Notes ----- Lists of tuples should be preferred over lists of lists for faster processing. """ # Grab the initial _fieldmask, if needed: _mask = getattr(reclist, '_mask', None) # Get the list of records..... try: nfields = len(reclist[0]) except TypeError: nfields = len(reclist[0].dtype) if isinstance(reclist, ndarray): # Make sure we don't have some hidden mask if isinstance(reclist, MaskedArray): reclist = reclist.filled().view(ndarray) # Grab the initial dtype, just in case if dtype is None: dtype = reclist.dtype reclist = reclist.tolist() mrec = recfromrecords(reclist, dtype=dtype, shape=shape, formats=formats, names=names, titles=titles, aligned=aligned, byteorder=byteorder).view(mrecarray) # Set the fill_value if needed if fill_value is not None: mrec.fill_value = fill_value # Now, let's deal w/ the mask if mask is not nomask: mask = np.array(mask, copy=False) maskrecordlength = len(mask.dtype) if maskrecordlength: mrec._mask.flat = mask elif len(mask.shape) == 2: mrec._mask.flat = [tuple(m) for m in mask] else: mrec.__setmask__(mask) if _mask is not None: mrec._mask[:] = _mask return mrec def _guessvartypes(arr): """Tries to guess the dtypes of the str_ ndarray `arr`, by testing element-wise conversion. Returns a list of dtypes. The array is first converted to ndarray. If the array is 2D, the test is performed on the first line. An exception is raised if the file is 3D or more. """ vartypes = [] arr = np.asarray(arr) if len(arr.shape) == 2 : arr = arr[0] elif len(arr.shape) > 2: raise ValueError("The array should be 2D at most!") # Start the conversion loop ....... for f in arr: try: int(f) except ValueError: try: float(f) except ValueError: try: val = complex(f) except ValueError: vartypes.append(arr.dtype) else: vartypes.append(np.dtype(complex)) else: vartypes.append(np.dtype(float)) else: vartypes.append(np.dtype(int)) return vartypes def openfile(fname): "Opens the file handle of file `fname`" # A file handle ................... if hasattr(fname, 'readline'): return fname # Try to open the file and guess its type try: f = open(fname) except IOError: raise IOError("No such file: '%s'" % fname) if f.readline()[:2] != "\\x": f.seek(0, 0) return f f.close() raise NotImplementedError("Wow, binary file") def fromtextfile(fname, delimitor=None, commentchar='#', missingchar='', varnames=None, vartypes=None): """Creates a mrecarray from data stored in the file `filename`. Parameters ---------- filename : {file name/handle} Handle of an opened file. delimitor : {None, string}, optional Alphanumeric character used to separate columns in the file. If None, any (group of) white spacestring(s) will be used. commentchar : {'#', string}, optional Alphanumeric character used to mark the start of a comment. missingchar : {'', string}, optional String indicating missing data, and used to create the masks. varnames : {None, sequence}, optional Sequence of the variable names. If None, a list will be created from the first non empty line of the file. vartypes : {None, sequence}, optional Sequence of the variables dtypes. If None, it will be estimated from the first non-commented line. Ultra simple: the varnames are in the header, one line""" # Try to open the file ...................... f = openfile(fname) # Get the first non-empty line as the varnames while True: line = f.readline() firstline = line[:line.find(commentchar)].strip() _varnames = firstline.split(delimitor) if len(_varnames) > 1: break if varnames is None: varnames = _varnames # Get the data .............................. _variables = masked_array([line.strip().split(delimitor) for line in f if line[0] != commentchar and len(line) > 1]) (_, nfields) = _variables.shape f.close() # Try to guess the dtype .................... if vartypes is None: vartypes = _guessvartypes(_variables[0]) else: vartypes = [np.dtype(v) for v in vartypes] if len(vartypes) != nfields: msg = "Attempting to %i dtypes for %i fields!" msg += " Reverting to default." warnings.warn(msg % (len(vartypes), nfields)) vartypes = _guessvartypes(_variables[0]) # Construct the descriptor .................. mdescr = [(n, f) for (n, f) in zip(varnames, vartypes)] mfillv = [ma.default_fill_value(f) for f in vartypes] # Get the data and the mask ................. # We just need a list of masked_arrays. It's easier to create it like that: _mask = (_variables.T == missingchar) _datalist = [masked_array(a, mask=m, dtype=t, fill_value=f) for (a, m, t, f) in zip(_variables.T, _mask, vartypes, mfillv)] return fromarrays(_datalist, dtype=mdescr) #.................................................................... def addfield(mrecord, newfield, newfieldname=None): """Adds a new field to the masked record array, using `newfield` as data and `newfieldname` as name. If `newfieldname` is None, the new field name is set to 'fi', where `i` is the number of existing fields. """ _data = mrecord._data _mask = mrecord._mask if newfieldname is None or newfieldname in reserved_fields: newfieldname = 'f%i' % len(_data.dtype) newfield = ma.array(newfield) # Get the new data ............ # Create a new empty recarray newdtype = np.dtype(_data.dtype.descr + [(newfieldname, newfield.dtype)]) newdata = recarray(_data.shape, newdtype) # Add the exisintg field [newdata.setfield(_data.getfield(*f), *f) for f in _data.dtype.fields.values()] # Add the new field newdata.setfield(newfield._data, *newdata.dtype.fields[newfieldname]) newdata = newdata.view(MaskedRecords) # Get the new mask ............. # Create a new empty recarray newmdtype = np.dtype([(n, bool_) for n in newdtype.names]) newmask = recarray(_data.shape, newmdtype) # Add the old masks [newmask.setfield(_mask.getfield(*f), *f) for f in _mask.dtype.fields.values()] # Add the mask of the new field newmask.setfield(getmaskarray(newfield), *newmask.dtype.fields[newfieldname]) newdata._mask = newmask return newdata numpy-1.8.2/numpy/ma/extras.py0000664000175100017510000015443312370216243017463 0ustar vagrantvagrant00000000000000""" Masked arrays add-ons. A collection of utilities for `numpy.ma`. :author: Pierre Gerard-Marchant :contact: pierregm_at_uga_dot_edu :version: $Id: extras.py 3473 2007-10-29 15:18:13Z jarrod.millman $ """ from __future__ import division, absolute_import, print_function __author__ = "Pierre GF Gerard-Marchant ($Author: jarrod.millman $)" __version__ = '1.0' __revision__ = "$Revision: 3473 $" __date__ = '$Date: 2007-10-29 17:18:13 +0200 (Mon, 29 Oct 2007) $' __all__ = ['apply_along_axis', 'apply_over_axes', 'atleast_1d', 'atleast_2d', 'atleast_3d', 'average', 'clump_masked', 'clump_unmasked', 'column_stack', 'compress_cols', 'compress_rowcols', 'compress_rows', 'count_masked', 'corrcoef', 'cov', 'diagflat', 'dot', 'dstack', 'ediff1d', 'flatnotmasked_contiguous', 'flatnotmasked_edges', 'hsplit', 'hstack', 'in1d', 'intersect1d', 'mask_cols', 'mask_rowcols', 'mask_rows', 'masked_all', 'masked_all_like', 'median', 'mr_', 'notmasked_contiguous', 'notmasked_edges', 'polyfit', 'row_stack', 'setdiff1d', 'setxor1d', 'unique', 'union1d', 'vander', 'vstack', ] import itertools import warnings from . import core as ma from .core import MaskedArray, MAError, add, array, asarray, concatenate, count, \ filled, getmask, getmaskarray, make_mask_descr, masked, masked_array, \ mask_or, nomask, ones, sort, zeros #from core import * import numpy as np from numpy import ndarray, array as nxarray import numpy.core.umath as umath from numpy.lib.index_tricks import AxisConcatenator from numpy.linalg import lstsq #............................................................................... def issequence(seq): """Is seq a sequence (ndarray, list or tuple)?""" if isinstance(seq, (ndarray, tuple, list)): return True return False def count_masked(arr, axis=None): """ Count the number of masked elements along the given axis. Parameters ---------- arr : array_like An array with (possibly) masked elements. axis : int, optional Axis along which to count. If None (default), a flattened version of the array is used. Returns ------- count : int, ndarray The total number of masked elements (axis=None) or the number of masked elements along each slice of the given axis. See Also -------- MaskedArray.count : Count non-masked elements. Examples -------- >>> import numpy.ma as ma >>> a = np.arange(9).reshape((3,3)) >>> a = ma.array(a) >>> a[1, 0] = ma.masked >>> a[1, 2] = ma.masked >>> a[2, 1] = ma.masked >>> a masked_array(data = [[0 1 2] [-- 4 --] [6 -- 8]], mask = [[False False False] [ True False True] [False True False]], fill_value=999999) >>> ma.count_masked(a) 3 When the `axis` keyword is used an array is returned. >>> ma.count_masked(a, axis=0) array([1, 1, 1]) >>> ma.count_masked(a, axis=1) array([0, 2, 1]) """ m = getmaskarray(arr) return m.sum(axis) def masked_all(shape, dtype=float): """ Empty masked array with all elements masked. Return an empty masked array of the given shape and dtype, where all the data are masked. Parameters ---------- shape : tuple Shape of the required MaskedArray. dtype : dtype, optional Data type of the output. Returns ------- a : MaskedArray A masked array with all data masked. See Also -------- masked_all_like : Empty masked array modelled on an existing array. Examples -------- >>> import numpy.ma as ma >>> ma.masked_all((3, 3)) masked_array(data = [[-- -- --] [-- -- --] [-- -- --]], mask = [[ True True True] [ True True True] [ True True True]], fill_value=1e+20) The `dtype` parameter defines the underlying data type. >>> a = ma.masked_all((3, 3)) >>> a.dtype dtype('float64') >>> a = ma.masked_all((3, 3), dtype=np.int32) >>> a.dtype dtype('int32') """ a = masked_array(np.empty(shape, dtype), mask=np.ones(shape, make_mask_descr(dtype))) return a def masked_all_like(arr): """ Empty masked array with the properties of an existing array. Return an empty masked array of the same shape and dtype as the array `arr`, where all the data are masked. Parameters ---------- arr : ndarray An array describing the shape and dtype of the required MaskedArray. Returns ------- a : MaskedArray A masked array with all data masked. Raises ------ AttributeError If `arr` doesn't have a shape attribute (i.e. not an ndarray) See Also -------- masked_all : Empty masked array with all elements masked. Examples -------- >>> import numpy.ma as ma >>> arr = np.zeros((2, 3), dtype=np.float32) >>> arr array([[ 0., 0., 0.], [ 0., 0., 0.]], dtype=float32) >>> ma.masked_all_like(arr) masked_array(data = [[-- -- --] [-- -- --]], mask = [[ True True True] [ True True True]], fill_value=1e+20) The dtype of the masked array matches the dtype of `arr`. >>> arr.dtype dtype('float32') >>> ma.masked_all_like(arr).dtype dtype('float32') """ a = np.empty_like(arr).view(MaskedArray) a._mask = np.ones(a.shape, dtype=make_mask_descr(a.dtype)) return a #####-------------------------------------------------------------------------- #---- --- Standard functions --- #####-------------------------------------------------------------------------- class _fromnxfunction: """ Defines a wrapper to adapt NumPy functions to masked arrays. An instance of `_fromnxfunction` can be called with the same parameters as the wrapped NumPy function. The docstring of `newfunc` is adapted from the wrapped function as well, see `getdoc`. Parameters ---------- funcname : str The name of the function to be adapted. The function should be in the NumPy namespace (i.e. ``np.funcname``). """ def __init__(self, funcname): self.__name__ = funcname self.__doc__ = self.getdoc() def getdoc(self): """ Retrieve the docstring and signature from the function. The ``__doc__`` attribute of the function is used as the docstring for the new masked array version of the function. A note on application of the function to the mask is appended. .. warning:: If the function docstring already contained a Notes section, the new docstring will have two Notes sections instead of appending a note to the existing section. Parameters ---------- None """ npfunc = getattr(np, self.__name__, None) doc = getattr(npfunc, '__doc__', None) if doc: sig = self.__name__ + ma.get_object_signature(npfunc) locdoc = "Notes\n-----\nThe function is applied to both the _data"\ " and the _mask, if any." return '\n'.join((sig, doc, locdoc)) return def __call__(self, *args, **params): func = getattr(np, self.__name__) if len(args) == 1: x = args[0] if isinstance(x, ndarray): _d = func(x.__array__(), **params) _m = func(getmaskarray(x), **params) return masked_array(_d, mask=_m) elif isinstance(x, tuple) or isinstance(x, list): _d = func(tuple([np.asarray(a) for a in x]), **params) _m = func(tuple([getmaskarray(a) for a in x]), **params) return masked_array(_d, mask=_m) else: arrays = [] args = list(args) while len(args) > 0 and issequence(args[0]): arrays.append(args.pop(0)) res = [] for x in arrays: _d = func(np.asarray(x), *args, **params) _m = func(getmaskarray(x), *args, **params) res.append(masked_array(_d, mask=_m)) return res atleast_1d = _fromnxfunction('atleast_1d') atleast_2d = _fromnxfunction('atleast_2d') atleast_3d = _fromnxfunction('atleast_3d') #atleast_1d = np.atleast_1d #atleast_2d = np.atleast_2d #atleast_3d = np.atleast_3d vstack = row_stack = _fromnxfunction('vstack') hstack = _fromnxfunction('hstack') column_stack = _fromnxfunction('column_stack') dstack = _fromnxfunction('dstack') hsplit = _fromnxfunction('hsplit') diagflat = _fromnxfunction('diagflat') #####-------------------------------------------------------------------------- #---- #####-------------------------------------------------------------------------- def flatten_inplace(seq): """Flatten a sequence in place.""" k = 0 while (k != len(seq)): while hasattr(seq[k], '__iter__'): seq[k:(k + 1)] = seq[k] k += 1 return seq def apply_along_axis(func1d, axis, arr, *args, **kwargs): """ (This docstring should be overwritten) """ arr = array(arr, copy=False, subok=True) nd = arr.ndim if axis < 0: axis += nd if (axis >= nd): raise ValueError("axis must be less than arr.ndim; axis=%d, rank=%d." % (axis, nd)) ind = [0] * (nd - 1) i = np.zeros(nd, 'O') indlist = list(range(nd)) indlist.remove(axis) i[axis] = slice(None, None) outshape = np.asarray(arr.shape).take(indlist) i.put(indlist, ind) j = i.copy() res = func1d(arr[tuple(i.tolist())], *args, **kwargs) # if res is a number, then we have a smaller output array asscalar = np.isscalar(res) if not asscalar: try: len(res) except TypeError: asscalar = True # Note: we shouldn't set the dtype of the output from the first result... #...so we force the type to object, and build a list of dtypes #...we'll just take the largest, to avoid some downcasting dtypes = [] if asscalar: dtypes.append(np.asarray(res).dtype) outarr = zeros(outshape, object) outarr[tuple(ind)] = res Ntot = np.product(outshape) k = 1 while k < Ntot: # increment the index ind[-1] += 1 n = -1 while (ind[n] >= outshape[n]) and (n > (1 - nd)): ind[n - 1] += 1 ind[n] = 0 n -= 1 i.put(indlist, ind) res = func1d(arr[tuple(i.tolist())], *args, **kwargs) outarr[tuple(ind)] = res dtypes.append(asarray(res).dtype) k += 1 else: res = array(res, copy=False, subok=True) j = i.copy() j[axis] = ([slice(None, None)] * res.ndim) j.put(indlist, ind) Ntot = np.product(outshape) holdshape = outshape outshape = list(arr.shape) outshape[axis] = res.shape dtypes.append(asarray(res).dtype) outshape = flatten_inplace(outshape) outarr = zeros(outshape, object) outarr[tuple(flatten_inplace(j.tolist()))] = res k = 1 while k < Ntot: # increment the index ind[-1] += 1 n = -1 while (ind[n] >= holdshape[n]) and (n > (1 - nd)): ind[n - 1] += 1 ind[n] = 0 n -= 1 i.put(indlist, ind) j.put(indlist, ind) res = func1d(arr[tuple(i.tolist())], *args, **kwargs) outarr[tuple(flatten_inplace(j.tolist()))] = res dtypes.append(asarray(res).dtype) k += 1 max_dtypes = np.dtype(np.asarray(dtypes).max()) if not hasattr(arr, '_mask'): result = np.asarray(outarr, dtype=max_dtypes) else: result = asarray(outarr, dtype=max_dtypes) result.fill_value = ma.default_fill_value(result) return result apply_along_axis.__doc__ = np.apply_along_axis.__doc__ def apply_over_axes(func, a, axes): """ (This docstring will be overwritten) """ val = np.asarray(a) msk = getmaskarray(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))) if res.ndim == val.ndim: (val, msk) = (res._data, res._mask) else: res = ma.expand_dims(res, axis) if res.ndim == val.ndim: (val, msk) = (res._data, res._mask) else: raise ValueError("Function is not returning"\ " an array of correct shape") return val apply_over_axes.__doc__ = np.apply_over_axes.__doc__ def average(a, axis=None, weights=None, returned=False): """ Return the weighted average of array over the given axis. Parameters ---------- a : array_like 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. 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 the size of `a` along the given axis) or of the same shape as `a`. If ``weights=None``, then all data in `a` are assumed to have a weight equal to one. If `weights` is complex, the imaginary parts are ignored. returned : bool, optional Flag indicating whether a tuple ``(result, sum of weights)`` should be returned as output (True), or just the result (False). Default is False. Returns ------- average, [sum_of_weights] : (tuple of) scalar or MaskedArray The average along the specified axis. When returned is `True`, return a tuple with the average as the first element and the sum of the weights as the second element. The return type is `np.float64` if `a` is of integer type, otherwise it is of the same type as `a`. If returned, `sum_of_weights` is of the same type as `average`. Examples -------- >>> a = np.ma.array([1., 2., 3., 4.], mask=[False, False, True, True]) >>> np.ma.average(a, weights=[3, 1, 0, 0]) 1.25 >>> x = np.ma.arange(6.).reshape(3, 2) >>> print x [[ 0. 1.] [ 2. 3.] [ 4. 5.]] >>> avg, sumweights = np.ma.average(x, axis=0, weights=[1, 2, 3], ... returned=True) >>> print avg [2.66666666667 3.66666666667] """ a = asarray(a) mask = a.mask ash = a.shape if ash == (): ash = (1,) if axis is None: if mask is nomask: if weights is None: n = a.sum(axis=None) d = float(a.size) else: w = filled(weights, 0.0).ravel() n = umath.add.reduce(a._data.ravel() * w) d = umath.add.reduce(w) del w else: if weights is None: n = a.filled(0).sum(axis=None) d = float(umath.add.reduce((~mask).ravel())) else: w = array(filled(weights, 0.0), float, mask=mask).ravel() n = add.reduce(a.ravel() * w) d = add.reduce(w) del w else: if mask is nomask: if weights is None: d = ash[axis] * 1.0 n = add.reduce(a._data, axis) else: w = filled(weights, 0.0) wsh = w.shape if wsh == (): wsh = (1,) if wsh == ash: w = np.array(w, float, copy=0) n = add.reduce(a * w, axis) d = add.reduce(w, axis) del w elif wsh == (ash[axis],): ni = ash[axis] r = [None] * len(ash) r[axis] = slice(None, None, 1) w = eval ("w[" + repr(tuple(r)) + "] * ones(ash, float)") n = add.reduce(a * w, axis) d = add.reduce(w, axis, dtype=float) del w, r else: raise ValueError('average: weights wrong shape.') else: if weights is None: n = add.reduce(a, axis) d = umath.add.reduce((-mask), axis=axis, dtype=float) else: w = filled(weights, 0.0) wsh = w.shape if wsh == (): wsh = (1,) if wsh == ash: w = array(w, dtype=float, mask=mask, copy=0) n = add.reduce(a * w, axis) d = add.reduce(w, axis, dtype=float) elif wsh == (ash[axis],): ni = ash[axis] r = [None] * len(ash) r[axis] = slice(None, None, 1) w = eval ("w[" + repr(tuple(r)) + \ "] * masked_array(ones(ash, float), mask)") n = add.reduce(a * w, axis) d = add.reduce(w, axis, dtype=float) else: raise ValueError('average: weights wrong shape.') del w if n is masked or d is masked: return masked result = n / d del n if isinstance(result, MaskedArray): if ((axis is None) or (axis == 0 and a.ndim == 1)) and \ (result.mask is nomask): result = result._data if returned: if not isinstance(d, MaskedArray): d = masked_array(d) if isinstance(d, ndarray) and (not d.shape == result.shape): d = ones(result.shape, dtype=float) * d if returned: return result, d else: return result def median(a, axis=None, out=None, overwrite_input=False): """ Compute the median along the specified axis. Returns the median of the array elements. 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 (None) is to compute the median along a flattened version of the array. 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 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. Returns ------- median : ndarray A new array holding the result is returned unless out is specified, in which case a reference to out is returned. Return data-type is `float64` for integers and floats smaller than `float64`, or the input data-type, otherwise. See Also -------- mean Notes ----- Given a vector ``V`` with ``N`` non masked values, the median of ``V`` is the middle value of a sorted copy of ``V`` (``Vs``) - i.e. ``Vs[(N-1)/2]``, when ``N`` is odd, or ``{Vs[N/2 - 1] + Vs[N/2]}/2`` when ``N`` is even. Examples -------- >>> x = np.ma.array(np.arange(8), mask=[0]*4 + [1]*4) >>> np.ma.extras.median(x) 1.5 >>> x = np.ma.array(np.arange(10).reshape(2, 5), mask=[0]*6 + [1]*4) >>> np.ma.extras.median(x) 2.5 >>> np.ma.extras.median(x, axis=-1, overwrite_input=True) masked_array(data = [ 2. 5.], mask = 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 overwrite_input: if axis is None: asorted = a.ravel() asorted.sort() else: a.sort(axis=axis) asorted = a else: asorted = sort(a, axis=axis) if axis is None: result = _median1D(asorted) else: result = apply_along_axis(_median1D, axis, asorted) if out is not None: out = result return result #.............................................................................. def compress_rowcols(x, axis=None): """ Suppress the rows and/or columns of a 2-D array that contain masked values. The suppression behavior is selected with the `axis` parameter. - If axis is None, both rows and columns are suppressed. - If axis is 0, only rows are suppressed. - If axis is 1 or -1, only columns are suppressed. Parameters ---------- axis : int, optional Axis along which to perform the operation. Default is None. Returns ------- compressed_array : ndarray The compressed array. Examples -------- >>> x = np.ma.array(np.arange(9).reshape(3, 3), mask=[[1, 0, 0], ... [1, 0, 0], ... [0, 0, 0]]) >>> x masked_array(data = [[-- 1 2] [-- 4 5] [6 7 8]], mask = [[ True False False] [ True False False] [False False False]], fill_value = 999999) >>> np.ma.extras.compress_rowcols(x) array([[7, 8]]) >>> np.ma.extras.compress_rowcols(x, 0) array([[6, 7, 8]]) >>> np.ma.extras.compress_rowcols(x, 1) array([[1, 2], [4, 5], [7, 8]]) """ x = asarray(x) if x.ndim != 2: raise NotImplementedError("compress2d works for 2D arrays only.") m = getmask(x) # Nothing is masked: return x if m is nomask or not m.any(): return x._data # All is masked: return empty if m.all(): return nxarray([]) # Builds a list of rows/columns indices (idxr, idxc) = (list(range(len(x))), list(range(x.shape[1]))) masked = m.nonzero() if not axis: for i in np.unique(masked[0]): idxr.remove(i) if axis in [None, 1, -1]: for j in np.unique(masked[1]): idxc.remove(j) return x._data[idxr][:, idxc] def compress_rows(a): """ Suppress whole rows of a 2-D array that contain masked values. This is equivalent to ``np.ma.extras.compress_rowcols(a, 0)``, see `extras.compress_rowcols` for details. See Also -------- extras.compress_rowcols """ return compress_rowcols(a, 0) def compress_cols(a): """ Suppress whole columns of a 2-D array that contain masked values. This is equivalent to ``np.ma.extras.compress_rowcols(a, 1)``, see `extras.compress_rowcols` for details. See Also -------- extras.compress_rowcols """ return compress_rowcols(a, 1) def mask_rowcols(a, axis=None): """ Mask rows and/or columns of a 2D array that contain masked values. Mask whole rows and/or columns of a 2D array that contain masked values. The masking behavior is selected using the `axis` parameter. - If `axis` is None, rows *and* columns are masked. - If `axis` is 0, only rows are masked. - If `axis` is 1 or -1, only columns are masked. Parameters ---------- a : array_like, MaskedArray The array to mask. If not a MaskedArray instance (or if no array elements are masked). The result is a MaskedArray with `mask` set to `nomask` (False). Must be a 2D array. axis : int, optional Axis along which to perform the operation. If None, applies to a flattened version of the array. Returns ------- a : MaskedArray A modified version of the input array, masked depending on the value of the `axis` parameter. Raises ------ NotImplementedError If input array `a` is not 2D. See Also -------- mask_rows : Mask rows of a 2D array that contain masked values. mask_cols : Mask cols of a 2D array that contain masked values. masked_where : Mask where a condition is met. Notes ----- The input array's mask is modified by this function. Examples -------- >>> import numpy.ma as ma >>> a = np.zeros((3, 3), dtype=np.int) >>> a[1, 1] = 1 >>> a array([[0, 0, 0], [0, 1, 0], [0, 0, 0]]) >>> a = ma.masked_equal(a, 1) >>> a masked_array(data = [[0 0 0] [0 -- 0] [0 0 0]], mask = [[False False False] [False True False] [False False False]], fill_value=999999) >>> ma.mask_rowcols(a) masked_array(data = [[0 -- 0] [-- -- --] [0 -- 0]], mask = [[False True False] [ True True True] [False True False]], fill_value=999999) """ a = asarray(a) if a.ndim != 2: raise NotImplementedError("compress2d works for 2D arrays only.") m = getmask(a) # Nothing is masked: return a if m is nomask or not m.any(): return a maskedval = m.nonzero() a._mask = a._mask.copy() if not axis: a[np.unique(maskedval[0])] = masked if axis in [None, 1, -1]: a[:, np.unique(maskedval[1])] = masked return a def mask_rows(a, axis=None): """ Mask rows of a 2D array that contain masked values. This function is a shortcut to ``mask_rowcols`` with `axis` equal to 0. See Also -------- mask_rowcols : Mask rows and/or columns of a 2D array. masked_where : Mask where a condition is met. Examples -------- >>> import numpy.ma as ma >>> a = np.zeros((3, 3), dtype=np.int) >>> a[1, 1] = 1 >>> a array([[0, 0, 0], [0, 1, 0], [0, 0, 0]]) >>> a = ma.masked_equal(a, 1) >>> a masked_array(data = [[0 0 0] [0 -- 0] [0 0 0]], mask = [[False False False] [False True False] [False False False]], fill_value=999999) >>> ma.mask_rows(a) masked_array(data = [[0 0 0] [-- -- --] [0 0 0]], mask = [[False False False] [ True True True] [False False False]], fill_value=999999) """ return mask_rowcols(a, 0) def mask_cols(a, axis=None): """ Mask columns of a 2D array that contain masked values. This function is a shortcut to ``mask_rowcols`` with `axis` equal to 1. See Also -------- mask_rowcols : Mask rows and/or columns of a 2D array. masked_where : Mask where a condition is met. Examples -------- >>> import numpy.ma as ma >>> a = np.zeros((3, 3), dtype=np.int) >>> a[1, 1] = 1 >>> a array([[0, 0, 0], [0, 1, 0], [0, 0, 0]]) >>> a = ma.masked_equal(a, 1) >>> a masked_array(data = [[0 0 0] [0 -- 0] [0 0 0]], mask = [[False False False] [False True False] [False False False]], fill_value=999999) >>> ma.mask_cols(a) masked_array(data = [[0 -- 0] [0 -- 0] [0 -- 0]], mask = [[False True False] [False True False] [False True False]], fill_value=999999) """ return mask_rowcols(a, 1) def dot(a, b, strict=False): """ Return the dot product of two arrays. .. note:: Works only with 2-D arrays at the moment. This function is the equivalent of `numpy.dot` that takes masked values into account, see `numpy.dot` for details. Parameters ---------- a, b : ndarray Inputs arrays. strict : bool, optional Whether masked data are propagated (True) or set to 0 (False) for the computation. Default is False. Propagating the mask means that if a masked value appears in a row or column, the whole row or column is considered masked. See Also -------- numpy.dot : Equivalent function for ndarrays. Examples -------- >>> a = ma.array([[1, 2, 3], [4, 5, 6]], mask=[[1, 0, 0], [0, 0, 0]]) >>> b = ma.array([[1, 2], [3, 4], [5, 6]], mask=[[1, 0], [0, 0], [0, 0]]) >>> np.ma.dot(a, b) masked_array(data = [[21 26] [45 64]], mask = [[False False] [False False]], fill_value = 999999) >>> np.ma.dot(a, b, strict=True) masked_array(data = [[-- --] [-- 64]], mask = [[ True True] [ True False]], fill_value = 999999) """ #!!!: Works only with 2D arrays. There should be a way to get it to run with higher dimension if strict and (a.ndim == 2) and (b.ndim == 2): a = mask_rows(a) b = mask_cols(b) # d = np.dot(filled(a, 0), filled(b, 0)) # am = (~getmaskarray(a)) bm = (~getmaskarray(b)) m = ~np.dot(am, bm) return masked_array(d, mask=m) #####-------------------------------------------------------------------------- #---- --- arraysetops --- #####-------------------------------------------------------------------------- def ediff1d(arr, to_end=None, to_begin=None): """ Compute the differences between consecutive elements of an array. This function is the equivalent of `numpy.ediff1d` that takes masked values into account, see `numpy.ediff1d` for details. See Also -------- numpy.ediff1d : Equivalent function for ndarrays. """ arr = ma.asanyarray(arr).flat ed = arr[1:] - arr[:-1] arrays = [ed] # if to_begin is not None: arrays.insert(0, to_begin) if to_end is not None: arrays.append(to_end) # if len(arrays) != 1: # We'll save ourselves a copy of a potentially large array in the common # case where neither to_begin or to_end was given. ed = hstack(arrays) # return ed def unique(ar1, return_index=False, return_inverse=False): """ Finds the unique elements of an array. Masked values are considered the same element (masked). The output array is always a masked array. See `numpy.unique` for more details. See Also -------- numpy.unique : Equivalent function for ndarrays. """ output = np.unique(ar1, return_index=return_index, return_inverse=return_inverse) if isinstance(output, tuple): output = list(output) output[0] = output[0].view(MaskedArray) output = tuple(output) else: output = output.view(MaskedArray) return output def intersect1d(ar1, ar2, assume_unique=False): """ Returns the unique elements common to both arrays. Masked values are considered equal one to the other. The output is always a masked array. See `numpy.intersect1d` for more details. See Also -------- numpy.intersect1d : Equivalent function for ndarrays. Examples -------- >>> x = array([1, 3, 3, 3], mask=[0, 0, 0, 1]) >>> y = array([3, 1, 1, 1], mask=[0, 0, 0, 1]) >>> intersect1d(x, y) masked_array(data = [1 3 --], mask = [False False True], fill_value = 999999) """ if assume_unique: aux = ma.concatenate((ar1, ar2)) else: # Might be faster than unique( intersect1d( ar1, ar2 ) )? aux = ma.concatenate((unique(ar1), unique(ar2))) aux.sort() return aux[:-1][aux[1:] == aux[:-1]] def setxor1d(ar1, ar2, assume_unique=False): """ Set exclusive-or of 1-D arrays with unique elements. The output is always a masked array. See `numpy.setxor1d` for more details. See Also -------- numpy.setxor1d : Equivalent function for ndarrays. """ if not assume_unique: ar1 = unique(ar1) ar2 = unique(ar2) aux = ma.concatenate((ar1, ar2)) if aux.size == 0: return aux aux.sort() auxf = aux.filled() # flag = ediff1d( aux, to_end = 1, to_begin = 1 ) == 0 flag = ma.concatenate(([True], (auxf[1:] != auxf[:-1]), [True])) # flag2 = ediff1d( flag ) == 0 flag2 = (flag[1:] == flag[:-1]) return aux[flag2] def in1d(ar1, ar2, assume_unique=False, invert=False): """ Test whether each element of an array is also present in a second array. The output is always a masked array. See `numpy.in1d` for more details. See Also -------- numpy.in1d : Equivalent function for ndarrays. Notes ----- .. versionadded:: 1.4.0 """ if not assume_unique: ar1, rev_idx = unique(ar1, return_inverse=True) ar2 = unique(ar2) ar = ma.concatenate((ar1, ar2)) # We need this to be a stable sort, so always use 'mergesort' # here. The values from the first array should always come before # the values from the second array. order = ar.argsort(kind='mergesort') sar = ar[order] if invert: bool_ar = (sar[1:] != sar[:-1]) else: bool_ar = (sar[1:] == sar[:-1]) flag = ma.concatenate((bool_ar, [invert])) indx = order.argsort(kind='mergesort')[:len(ar1)] if assume_unique: return flag[indx] else: return flag[indx][rev_idx] def union1d(ar1, ar2): """ Union of two arrays. The output is always a masked array. See `numpy.union1d` for more details. See also -------- numpy.union1d : Equivalent function for ndarrays. """ return unique(ma.concatenate((ar1, ar2))) def setdiff1d(ar1, ar2, assume_unique=False): """ Set difference of 1D arrays with unique elements. The output is always a masked array. See `numpy.setdiff1d` for more details. See Also -------- numpy.setdiff1d : Equivalent function for ndarrays. Examples -------- >>> x = np.ma.array([1, 2, 3, 4], mask=[0, 1, 0, 1]) >>> np.ma.extras.setdiff1d(x, [1, 2]) masked_array(data = [3 --], mask = [False True], fill_value = 999999) """ if not assume_unique: ar1 = unique(ar1) ar2 = unique(ar2) aux = in1d(ar1, ar2, assume_unique=True) if aux.size == 0: return aux else: return ma.asarray(ar1)[aux == 0] #####-------------------------------------------------------------------------- #---- --- Covariance --- #####-------------------------------------------------------------------------- def _covhelper(x, y=None, rowvar=True, allow_masked=True): """ Private function for the computation of covariance and correlation coefficients. """ x = ma.array(x, ndmin=2, copy=True, dtype=float) xmask = ma.getmaskarray(x) # Quick exit if we can't process masked data if not allow_masked and xmask.any(): raise ValueError("Cannot process masked data...") # if x.shape[0] == 1: rowvar = True # Make sure that rowvar is either 0 or 1 rowvar = int(bool(rowvar)) axis = 1 - rowvar if rowvar: tup = (slice(None), None) else: tup = (None, slice(None)) # if y is None: xnotmask = np.logical_not(xmask).astype(int) else: y = array(y, copy=False, ndmin=2, dtype=float) ymask = ma.getmaskarray(y) if not allow_masked and ymask.any(): raise ValueError("Cannot process masked data...") if xmask.any() or ymask.any(): if y.shape == x.shape: # Define some common mask common_mask = np.logical_or(xmask, ymask) if common_mask is not nomask: x.unshare_mask() y.unshare_mask() xmask = x._mask = y._mask = ymask = common_mask x = ma.concatenate((x, y), axis) xnotmask = np.logical_not(np.concatenate((xmask, ymask), axis)).astype(int) x -= x.mean(axis=rowvar)[tup] return (x, xnotmask, rowvar) def cov(x, y=None, rowvar=True, bias=False, allow_masked=True, ddof=None): """ Estimate the covariance matrix. Except for the handling of missing data this function does the same as `numpy.cov`. For more details and examples, see `numpy.cov`. By default, masked values are recognized as such. If `x` and `y` have the same shape, a common mask is allocated: if ``x[i,j]`` is masked, then ``y[i,j]`` will also be masked. Setting `allow_masked` to False will raise an exception if values are missing in either of the input arrays. Parameters ---------- x : array_like A 1-D or 2-D array containing multiple variables and observations. Each row of `x` represents a variable, and each column a single observation of all those variables. Also see `rowvar` below. y : array_like, optional An additional set of variables and observations. `y` has the same form as `x`. rowvar : bool, optional If `rowvar` is True (default), then each row represents a variable, with observations in the columns. Otherwise, the relationship is transposed: each column represents a variable, while the rows contain observations. bias : bool, optional Default normalization (False) is by ``(N-1)``, where ``N`` is the number of observations given (unbiased estimate). If `bias` is True, then normalization is by ``N``. This keyword can be overridden by the keyword ``ddof`` in numpy versions >= 1.5. allow_masked : bool, optional If True, masked values are propagated pair-wise: if a value is masked in `x`, the corresponding value is masked in `y`. If False, raises a `ValueError` exception when some values are missing. ddof : {None, int}, optional .. versionadded:: 1.5 If not ``None`` normalization is by ``(N - ddof)``, where ``N`` is the number of observations; this overrides the value implied by ``bias``. The default value is ``None``. Raises ------ ValueError Raised if some values are missing and `allow_masked` is False. See Also -------- numpy.cov """ # Check inputs if ddof is not None and ddof != int(ddof): raise ValueError("ddof must be an integer") # Set up ddof if ddof is None: if bias: ddof = 0 else: ddof = 1 (x, xnotmask, rowvar) = _covhelper(x, y, rowvar, allow_masked) if not rowvar: fact = np.dot(xnotmask.T, xnotmask) * 1. - ddof result = (dot(x.T, x.conj(), strict=False) / fact).squeeze() else: fact = np.dot(xnotmask, xnotmask.T) * 1. - ddof result = (dot(x, x.T.conj(), strict=False) / fact).squeeze() return result def corrcoef(x, y=None, rowvar=True, bias=False, allow_masked=True, ddof=None): """ Return correlation coefficients of the input array. Except for the handling of missing data this function does the same as `numpy.corrcoef`. For more details and examples, see `numpy.corrcoef`. Parameters ---------- x : array_like A 1-D or 2-D array containing multiple variables and observations. Each row of `x` represents a variable, and each column a single observation of all those variables. Also see `rowvar` below. y : array_like, optional An additional set of variables and observations. `y` has the same shape as `x`. rowvar : bool, optional If `rowvar` is True (default), then each row represents a variable, with observations in the columns. Otherwise, the relationship is transposed: each column represents a variable, while the rows contain observations. bias : bool, optional Default normalization (False) is by ``(N-1)``, where ``N`` is the number of observations given (unbiased estimate). If `bias` is 1, then normalization is by ``N``. This keyword can be overridden by the keyword ``ddof`` in numpy versions >= 1.5. allow_masked : bool, optional If True, masked values are propagated pair-wise: if a value is masked in `x`, the corresponding value is masked in `y`. If False, raises an exception. ddof : {None, int}, optional .. versionadded:: 1.5 If not ``None`` normalization is by ``(N - ddof)``, where ``N`` is the number of observations; this overrides the value implied by ``bias``. The default value is ``None``. See Also -------- numpy.corrcoef : Equivalent function in top-level NumPy module. cov : Estimate the covariance matrix. """ # Check inputs if ddof is not None and ddof != int(ddof): raise ValueError("ddof must be an integer") # Set up ddof if ddof is None: if bias: ddof = 0 else: ddof = 1 # Get the data (x, xnotmask, rowvar) = _covhelper(x, y, rowvar, allow_masked) # Compute the covariance matrix if not rowvar: fact = np.dot(xnotmask.T, xnotmask) * 1. - ddof c = (dot(x.T, x.conj(), strict=False) / fact).squeeze() else: fact = np.dot(xnotmask, xnotmask.T) * 1. - ddof c = (dot(x, x.T.conj(), strict=False) / fact).squeeze() # Check whether we have a scalar try: diag = ma.diagonal(c) except ValueError: return 1 # if xnotmask.all(): _denom = ma.sqrt(ma.multiply.outer(diag, diag)) else: _denom = diagflat(diag) n = x.shape[1 - rowvar] if rowvar: for i in range(n - 1): for j in range(i + 1, n): _x = mask_cols(vstack((x[i], x[j]))).var(axis=1, ddof=ddof) _denom[i, j] = _denom[j, i] = ma.sqrt(ma.multiply.reduce(_x)) else: for i in range(n - 1): for j in range(i + 1, n): _x = mask_cols( vstack((x[:, i], x[:, j]))).var(axis=1, ddof=ddof) _denom[i, j] = _denom[j, i] = ma.sqrt(ma.multiply.reduce(_x)) return c / _denom #####-------------------------------------------------------------------------- #---- --- Concatenation helpers --- #####-------------------------------------------------------------------------- class MAxisConcatenator(AxisConcatenator): """ Translate slice objects to concatenation along an axis. For documentation on usage, see `mr_class`. See Also -------- mr_class """ def __init__(self, axis=0): AxisConcatenator.__init__(self, axis, matrix=False) def __getitem__(self, key): if isinstance(key, str): raise MAError("Unavailable for masked array.") if not isinstance(key, tuple): key = (key,) objs = [] scalars = [] final_dtypedescr = None for k in range(len(key)): scalar = False if isinstance(key[k], slice): step = key[k].step start = key[k].start stop = key[k].stop if start is None: start = 0 if step is None: step = 1 if isinstance(step, complex): size = int(abs(step)) newobj = np.linspace(start, stop, num=size) else: newobj = np.arange(start, stop, step) elif isinstance(key[k], str): if (key[k] in 'rc'): self.matrix = True self.col = (key[k] == 'c') continue try: self.axis = int(key[k]) continue except (ValueError, TypeError): raise ValueError("Unknown special directive") elif type(key[k]) in np.ScalarType: newobj = asarray([key[k]]) scalars.append(k) scalar = True else: newobj = key[k] objs.append(newobj) if isinstance(newobj, ndarray) and not scalar: if final_dtypedescr is None: final_dtypedescr = newobj.dtype elif newobj.dtype > final_dtypedescr: final_dtypedescr = newobj.dtype if final_dtypedescr is not None: for k in scalars: objs[k] = objs[k].astype(final_dtypedescr) res = concatenate(tuple(objs), axis=self.axis) return self._retval(res) class mr_class(MAxisConcatenator): """ Translate slice objects to concatenation along the first axis. This is the masked array version of `lib.index_tricks.RClass`. See Also -------- lib.index_tricks.RClass Examples -------- >>> np.ma.mr_[np.ma.array([1,2,3]), 0, 0, np.ma.array([4,5,6])] array([1, 2, 3, 0, 0, 4, 5, 6]) """ def __init__(self): MAxisConcatenator.__init__(self, 0) mr_ = mr_class() #####-------------------------------------------------------------------------- #---- Find unmasked data --- #####-------------------------------------------------------------------------- def flatnotmasked_edges(a): """ Find the indices of the first and last unmasked values. Expects a 1-D `MaskedArray`, returns None if all values are masked. Parameters ---------- arr : array_like Input 1-D `MaskedArray` Returns ------- edges : ndarray or None The indices of first and last non-masked value in the array. Returns None if all values are masked. See Also -------- flatnotmasked_contiguous, notmasked_contiguous, notmasked_edges, clump_masked, clump_unmasked Notes ----- Only accepts 1-D arrays. Examples -------- >>> a = np.ma.arange(10) >>> flatnotmasked_edges(a) [0,-1] >>> mask = (a < 3) | (a > 8) | (a == 5) >>> a[mask] = np.ma.masked >>> np.array(a[~a.mask]) array([3, 4, 6, 7, 8]) >>> flatnotmasked_edges(a) array([3, 8]) >>> a[:] = np.ma.masked >>> print flatnotmasked_edges(ma) None """ m = getmask(a) if m is nomask or not np.any(m): return np.array([0, a.size - 1]) unmasked = np.flatnonzero(~m) if len(unmasked) > 0: return unmasked[[0, -1]] else: return None def notmasked_edges(a, axis=None): """ Find the indices of the first and last unmasked values along an axis. If all values are masked, return None. Otherwise, return a list of two tuples, corresponding to the indices of the first and last unmasked values respectively. Parameters ---------- a : array_like The input array. axis : int, optional Axis along which to perform the operation. If None (default), applies to a flattened version of the array. Returns ------- edges : ndarray or list An array of start and end indexes if there are any masked data in the array. If there are no masked data in the array, `edges` is a list of the first and last index. See Also -------- flatnotmasked_contiguous, flatnotmasked_edges, notmasked_contiguous, clump_masked, clump_unmasked Examples -------- >>> a = np.arange(9).reshape((3, 3)) >>> m = np.zeros_like(a) >>> m[1:, 1:] = 1 >>> am = np.ma.array(a, mask=m) >>> np.array(am[~am.mask]) array([0, 1, 2, 3, 6]) >>> np.ma.extras.notmasked_edges(ma) array([0, 6]) """ a = asarray(a) if axis is None or a.ndim == 1: return flatnotmasked_edges(a) m = getmaskarray(a) idx = array(np.indices(a.shape), mask=np.asarray([m] * a.ndim)) return [tuple([idx[i].min(axis).compressed() for i in range(a.ndim)]), tuple([idx[i].max(axis).compressed() for i in range(a.ndim)]), ] def flatnotmasked_contiguous(a): """ Find contiguous unmasked data in a masked array along the given axis. Parameters ---------- a : narray The input array. Returns ------- slice_list : list A sorted sequence of slices (start index, end index). See Also -------- flatnotmasked_edges, notmasked_contiguous, notmasked_edges, clump_masked, clump_unmasked Notes ----- Only accepts 2-D arrays at most. Examples -------- >>> a = np.ma.arange(10) >>> np.ma.extras.flatnotmasked_contiguous(a) slice(0, 10, None) >>> mask = (a < 3) | (a > 8) | (a == 5) >>> a[mask] = np.ma.masked >>> np.array(a[~a.mask]) array([3, 4, 6, 7, 8]) >>> np.ma.extras.flatnotmasked_contiguous(a) [slice(3, 5, None), slice(6, 9, None)] >>> a[:] = np.ma.masked >>> print np.ma.extras.flatnotmasked_edges(a) None """ m = getmask(a) if m is nomask: return slice(0, a.size, None) i = 0 result = [] for (k, g) in itertools.groupby(m.ravel()): n = len(list(g)) if not k: result.append(slice(i, i + n)) i += n return result or None def notmasked_contiguous(a, axis=None): """ Find contiguous unmasked data in a masked array along the given axis. Parameters ---------- a : array_like The input array. axis : int, optional Axis along which to perform the operation. If None (default), applies to a flattened version of the array. Returns ------- endpoints : list A list of slices (start and end indexes) of unmasked indexes in the array. See Also -------- flatnotmasked_edges, flatnotmasked_contiguous, notmasked_edges, clump_masked, clump_unmasked Notes ----- Only accepts 2-D arrays at most. Examples -------- >>> a = np.arange(9).reshape((3, 3)) >>> mask = np.zeros_like(a) >>> mask[1:, 1:] = 1 >>> ma = np.ma.array(a, mask=mask) >>> np.array(ma[~ma.mask]) array([0, 1, 2, 3, 6]) >>> np.ma.extras.notmasked_contiguous(ma) [slice(0, 4, None), slice(6, 7, None)] """ a = asarray(a) nd = a.ndim if nd > 2: raise NotImplementedError("Currently limited to atmost 2D array.") if axis is None or nd == 1: return flatnotmasked_contiguous(a) # result = [] # other = (axis + 1) % 2 idx = [0, 0] idx[axis] = slice(None, None) # for i in range(a.shape[other]): idx[other] = i result.append(flatnotmasked_contiguous(a[idx]) or None) return result def _ezclump(mask): """ Finds the clumps (groups of data with the same values) for a 1D bool array. Returns a series of slices. """ #def clump_masked(a): if mask.ndim > 1: mask = mask.ravel() idx = (mask[1:] - mask[:-1]).nonzero() idx = idx[0] + 1 slices = [slice(left, right) for (left, right) in zip(itertools.chain([0], idx), itertools.chain(idx, [len(mask)]),)] return slices def clump_unmasked(a): """ Return list of slices corresponding to the unmasked clumps of a 1-D array. (A "clump" is defined as a contiguous region of the array). Parameters ---------- a : ndarray A one-dimensional masked array. Returns ------- slices : list of slice The list of slices, one for each continuous region of unmasked elements in `a`. Notes ----- .. versionadded:: 1.4.0 See Also -------- flatnotmasked_edges, flatnotmasked_contiguous, notmasked_edges, notmasked_contiguous, clump_masked Examples -------- >>> a = np.ma.masked_array(np.arange(10)) >>> a[[0, 1, 2, 6, 8, 9]] = np.ma.masked >>> np.ma.extras.clump_unmasked(a) [slice(3, 6, None), slice(7, 8, None)] """ mask = getattr(a, '_mask', nomask) if mask is nomask: return [slice(0, a.size)] slices = _ezclump(mask) if a[0] is masked: result = slices[1::2] else: result = slices[::2] return result def clump_masked(a): """ Returns a list of slices corresponding to the masked clumps of a 1-D array. (A "clump" is defined as a contiguous region of the array). Parameters ---------- a : ndarray A one-dimensional masked array. Returns ------- slices : list of slice The list of slices, one for each continuous region of masked elements in `a`. Notes ----- .. versionadded:: 1.4.0 See Also -------- flatnotmasked_edges, flatnotmasked_contiguous, notmasked_edges, notmasked_contiguous, clump_unmasked Examples -------- >>> a = np.ma.masked_array(np.arange(10)) >>> a[[0, 1, 2, 6, 8, 9]] = np.ma.masked >>> np.ma.extras.clump_masked(a) [slice(0, 3, None), slice(6, 7, None), slice(8, 10, None)] """ mask = ma.getmask(a) if mask is nomask: return [] slices = _ezclump(mask) if len(slices): if a[0] is masked: slices = slices[::2] else: slices = slices[1::2] return slices #####-------------------------------------------------------------------------- #---- Polynomial fit --- #####-------------------------------------------------------------------------- def vander(x, n=None): """ Masked values in the input array result in rows of zeros. """ _vander = np.vander(x, n) m = getmask(x) if m is not nomask: _vander[m] = 0 return _vander vander.__doc__ = ma.doc_note(np.vander.__doc__, vander.__doc__) def polyfit(x, y, deg, rcond=None, full=False, w=None, cov=False): """ Any masked values in x is propagated in y, and vice-versa. """ x = asarray(x) y = asarray(y) m = getmask(x) if y.ndim == 1: m = mask_or(m, getmask(y)) elif y.ndim == 2: my = getmask(mask_rows(y)) if my is not nomask: m = mask_or(m, my[:, 0]) else: raise TypeError("Expected a 1D or 2D array for y!") if w is not None: w = asarray(w) if w.ndim != 1: raise TypeError("expected a 1-d array for weights") if w.shape[0] != y.shape[0] : raise TypeError("expected w and y to have the same length") m = mask_or(m, getmask(w)) if m is not nomask: if w is not None: w = ~m*w else: w = ~m return np.polyfit(x, y, deg, rcond, full, w, cov) polyfit.__doc__ = ma.doc_note(np.polyfit.__doc__, polyfit.__doc__) ################################################################################ numpy-1.8.2/numpy/ma/setup.py0000664000175100017510000000117412370216242017305 0ustar vagrantvagrant00000000000000#!/usr/bin/env python from __future__ import division, print_function __author__ = "Pierre GF Gerard-Marchant ($Author: jarrod.millman $)" __version__ = '1.0' __revision__ = "$Revision: 3473 $" __date__ = '$Date: 2007-10-29 17:18:13 +0200 (Mon, 29 Oct 2007) $' import os def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('ma', parent_package, top_path) config.add_data_dir('tests') return config if __name__ == "__main__": from numpy.distutils.core import setup config = configuration(top_path='').todict() setup(**config) numpy-1.8.2/numpy/ma/tests/0000775000175100017510000000000012371375430016740 5ustar vagrantvagrant00000000000000numpy-1.8.2/numpy/ma/tests/test_core.py0000664000175100017510000041415112370216243021302 0ustar vagrantvagrant00000000000000# pylint: disable-msg=W0401,W0511,W0611,W0612,W0614,R0201,E1102 """Tests suite for MaskedArray & subclassing. :author: Pierre Gerard-Marchant :contact: pierregm_at_uga_dot_edu """ from __future__ import division, absolute_import, print_function __author__ = "Pierre GF Gerard-Marchant" import warnings import sys import pickle from functools import reduce import numpy as np import numpy.ma.core import numpy.core.fromnumeric as fromnumeric from numpy import ndarray from numpy.ma.testutils import * from numpy.ma.core import * from numpy.compat import asbytes, asbytes_nested pi = np.pi #.............................................................................. class TestMaskedArray(TestCase): "Base test class for MaskedArrays." def setUp (self): "Base data definition." x = np.array([1., 1., 1., -2., pi / 2.0, 4., 5., -10., 10., 1., 2., 3.]) y = np.array([5., 0., 3., 2., -1., -4., 0., -10., 10., 1., 0., 3.]) a10 = 10. m1 = [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0] m2 = [0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1] xm = masked_array(x, mask=m1) ym = masked_array(y, mask=m2) z = np.array([-.5, 0., .5, .8]) zm = masked_array(z, mask=[0, 1, 0, 0]) xf = np.where(m1, 1e+20, x) xm.set_fill_value(1e+20) self.d = (x, y, a10, m1, m2, xm, ym, z, zm, xf) def test_basicattributes(self): "Tests some basic array attributes." a = array([1, 3, 2]) b = array([1, 3, 2], mask=[1, 0, 1]) assert_equal(a.ndim, 1) assert_equal(b.ndim, 1) assert_equal(a.size, 3) assert_equal(b.size, 3) assert_equal(a.shape, (3,)) assert_equal(b.shape, (3,)) def test_basic0d(self): "Checks masking a scalar" x = masked_array(0) assert_equal(str(x), '0') x = masked_array(0, mask=True) assert_equal(str(x), str(masked_print_option)) x = masked_array(0, mask=False) assert_equal(str(x), '0') x = array(0, mask=1) self.assertTrue(x.filled().dtype is x._data.dtype) def test_basic1d(self): "Test of basic array creation and properties in 1 dimension." (x, y, a10, m1, m2, xm, ym, z, zm, xf) = self.d self.assertTrue(not isMaskedArray(x)) self.assertTrue(isMaskedArray(xm)) self.assertTrue((xm - ym).filled(0).any()) fail_if_equal(xm.mask.astype(int), ym.mask.astype(int)) s = x.shape assert_equal(np.shape(xm), s) assert_equal(xm.shape, s) assert_equal(xm.dtype, x.dtype) assert_equal(zm.dtype, z.dtype) assert_equal(xm.size, reduce(lambda x, y:x * y, s)) assert_equal(count(xm), len(m1) - reduce(lambda x, y:x + y, m1)) assert_array_equal(xm, xf) assert_array_equal(filled(xm, 1.e20), xf) assert_array_equal(x, xm) def test_basic2d(self): "Test of basic array creation and properties in 2 dimensions." (x, y, a10, m1, m2, xm, ym, z, zm, xf) = self.d for s in [(4, 3), (6, 2)]: x.shape = s y.shape = s xm.shape = s ym.shape = s xf.shape = s # self.assertTrue(not isMaskedArray(x)) self.assertTrue(isMaskedArray(xm)) assert_equal(shape(xm), s) assert_equal(xm.shape, s) assert_equal(xm.size, reduce(lambda x, y:x * y, s)) assert_equal(count(xm), len(m1) - reduce(lambda x, y:x + y, m1)) assert_equal(xm, xf) assert_equal(filled(xm, 1.e20), xf) assert_equal(x, xm) def test_concatenate_basic(self): "Tests concatenations." (x, y, a10, m1, m2, xm, ym, z, zm, xf) = self.d # basic concatenation assert_equal(np.concatenate((x, y)), concatenate((xm, ym))) assert_equal(np.concatenate((x, y)), concatenate((x, y))) assert_equal(np.concatenate((x, y)), concatenate((xm, y))) assert_equal(np.concatenate((x, y, x)), concatenate((x, ym, x))) def test_concatenate_alongaxis(self): "Tests concatenations." (x, y, a10, m1, m2, xm, ym, z, zm, xf) = self.d # Concatenation along an axis s = (3, 4) x.shape = y.shape = xm.shape = ym.shape = s assert_equal(xm.mask, np.reshape(m1, s)) assert_equal(ym.mask, np.reshape(m2, s)) xmym = concatenate((xm, ym), 1) assert_equal(np.concatenate((x, y), 1), xmym) assert_equal(np.concatenate((xm.mask, ym.mask), 1), xmym._mask) # x = zeros(2) y = array(ones(2), mask=[False, True]) z = concatenate((x, y)) assert_array_equal(z, [0, 0, 1, 1]) assert_array_equal(z.mask, [False, False, False, True]) z = concatenate((y, x)) assert_array_equal(z, [1, 1, 0, 0]) assert_array_equal(z.mask, [False, True, False, False]) def test_concatenate_flexible(self): "Tests the concatenation on flexible arrays." data = masked_array(list(zip(np.random.rand(10), np.arange(10))), dtype=[('a', float), ('b', int)]) # test = concatenate([data[:5], data[5:]]) assert_equal_records(test, data) def test_creation_ndmin(self): "Check the use of ndmin" x = array([1, 2, 3], mask=[1, 0, 0], ndmin=2) assert_equal(x.shape, (1, 3)) assert_equal(x._data, [[1, 2, 3]]) assert_equal(x._mask, [[1, 0, 0]]) def test_creation_ndmin_from_maskedarray(self): "Make sure we're not losing the original mask w/ ndmin" x = array([1, 2, 3]) x[-1] = masked xx = array(x, ndmin=2, dtype=float) assert_equal(x.shape, x._mask.shape) assert_equal(xx.shape, xx._mask.shape) def test_creation_maskcreation(self): "Tests how masks are initialized at the creation of Maskedarrays." data = arange(24, dtype=float) data[[3, 6, 15]] = masked dma_1 = MaskedArray(data) assert_equal(dma_1.mask, data.mask) dma_2 = MaskedArray(dma_1) assert_equal(dma_2.mask, dma_1.mask) dma_3 = MaskedArray(dma_1, mask=[1, 0, 0, 0] * 6) fail_if_equal(dma_3.mask, dma_1.mask) def test_creation_with_list_of_maskedarrays(self): "Tests creaating a masked array from alist of masked arrays." x = array(np.arange(5), mask=[1, 0, 0, 0, 0]) data = array((x, x[::-1])) assert_equal(data, [[0, 1, 2, 3, 4], [4, 3, 2, 1, 0]]) assert_equal(data._mask, [[1, 0, 0, 0, 0], [0, 0, 0, 0, 1]]) # x.mask = nomask data = array((x, x[::-1])) assert_equal(data, [[0, 1, 2, 3, 4], [4, 3, 2, 1, 0]]) self.assertTrue(data.mask is nomask) def test_asarray(self): (x, y, a10, m1, m2, xm, ym, z, zm, xf) = self.d xm.fill_value = -9999 xm._hardmask = True xmm = asarray(xm) assert_equal(xmm._data, xm._data) assert_equal(xmm._mask, xm._mask) assert_equal(xmm.fill_value, xm.fill_value) assert_equal(xmm._hardmask, xm._hardmask) def test_fix_invalid(self): "Checks fix_invalid." with np.errstate(): np.seterr(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.]) assert_equal(data_fixed._mask, [1., 0., 1.]) def test_maskedelement(self): "Test of masked element" x = arange(6) x[1] = masked self.assertTrue(str(masked) == '--') self.assertTrue(x[1] is masked) assert_equal(filled(x[1], 0), 0) # don't know why these should raise an exception... #self.assertRaises(Exception, lambda x,y: x+y, masked, masked) #self.assertRaises(Exception, lambda x,y: x+y, masked, 2) #self.assertRaises(Exception, lambda x,y: x+y, masked, xx) #self.assertRaises(Exception, lambda x,y: x+y, xx, masked) def test_set_element_as_object(self): """Tests setting elements with object""" a = empty(1, dtype=object) x = (1, 2, 3, 4, 5) a[0] = x assert_equal(a[0], x) self.assertTrue(a[0] is x) # import datetime dt = datetime.datetime.now() a[0] = dt self.assertTrue(a[0] is dt) def test_indexing(self): "Tests conversions and indexing" x1 = np.array([1, 2, 4, 3]) x2 = array(x1, mask=[1, 0, 0, 0]) x3 = array(x1, mask=[0, 1, 0, 1]) x4 = array(x1) # test conversion to strings junk, garbage = str(x2), repr(x2) assert_equal(np.sort(x1), sort(x2, endwith=False)) # tests of indexing assert_(type(x2[1]) is type(x1[1])) assert_(x1[1] == x2[1]) assert_(x2[0] is masked) assert_equal(x1[2], x2[2]) assert_equal(x1[2:5], x2[2:5]) assert_equal(x1[:], x2[:]) assert_equal(x1[1:], x3[1:]) x1[2] = 9 x2[2] = 9 assert_equal(x1, x2) x1[1:3] = 99 x2[1:3] = 99 assert_equal(x1, x2) x2[1] = masked assert_equal(x1, x2) x2[1:3] = masked assert_equal(x1, x2) x2[:] = x1 x2[1] = masked assert_(allequal(getmask(x2), array([0, 1, 0, 0]))) x3[:] = masked_array([1, 2, 3, 4], [0, 1, 1, 0]) assert_(allequal(getmask(x3), array([0, 1, 1, 0]))) x4[:] = masked_array([1, 2, 3, 4], [0, 1, 1, 0]) assert_(allequal(getmask(x4), array([0, 1, 1, 0]))) assert_(allequal(x4, array([1, 2, 3, 4]))) x1 = np.arange(5) * 1.0 x2 = masked_values(x1, 3.0) assert_equal(x1, x2) assert_(allequal(array([0, 0, 0, 1, 0], MaskType), x2.mask)) assert_equal(3.0, x2.fill_value) x1 = array([1, 'hello', 2, 3], object) x2 = np.array([1, 'hello', 2, 3], object) s1 = x1[1] s2 = x2[1] assert_equal(type(s2), str) assert_equal(type(s1), str) assert_equal(s1, s2) assert_(x1[1:1].shape == (0,)) def test_copy(self): "Tests of some subtle points of copying and sizing." n = [0, 0, 1, 0, 0] m = make_mask(n) m2 = make_mask(m) self.assertTrue(m is m2) m3 = make_mask(m, copy=1) self.assertTrue(m is not m3) x1 = np.arange(5) y1 = array(x1, mask=m) #self.assertTrue( y1._data is x1) assert_equal(y1._data.__array_interface__, x1.__array_interface__) self.assertTrue(allequal(x1, y1.data)) #self.assertTrue( y1.mask is m) assert_equal(y1._mask.__array_interface__, m.__array_interface__) y1a = array(y1) self.assertTrue(y1a._data.__array_interface__ == y1._data.__array_interface__) self.assertTrue(y1a.mask is y1.mask) y2 = array(x1, mask=m) self.assertTrue(y2._data.__array_interface__ == x1.__array_interface__) #self.assertTrue( y2.mask is m) self.assertTrue(y2._mask.__array_interface__ == m.__array_interface__) self.assertTrue(y2[2] is masked) y2[2] = 9 self.assertTrue(y2[2] is not masked) #self.assertTrue( y2.mask is not m) self.assertTrue(y2._mask.__array_interface__ != m.__array_interface__) self.assertTrue(allequal(y2.mask, 0)) y3 = array(x1 * 1.0, mask=m) self.assertTrue(filled(y3).dtype is (x1 * 1.0).dtype) x4 = arange(4) x4[2] = masked y4 = resize(x4, (8,)) assert_equal(concatenate([x4, x4]), y4) assert_equal(getmask(y4), [0, 0, 1, 0, 0, 0, 1, 0]) y5 = repeat(x4, (2, 2, 2, 2), axis=0) assert_equal(y5, [0, 0, 1, 1, 2, 2, 3, 3]) y6 = repeat(x4, 2, axis=0) assert_equal(y5, y6) y7 = x4.repeat((2, 2, 2, 2), axis=0) assert_equal(y5, y7) y8 = x4.repeat(2, 0) assert_equal(y5, y8) y9 = x4.copy() assert_equal(y9._data, x4._data) assert_equal(y9._mask, x4._mask) # x = masked_array([1, 2, 3], mask=[0, 1, 0]) # Copy is False by default y = masked_array(x) assert_equal(y._data.ctypes.data, x._data.ctypes.data) assert_equal(y._mask.ctypes.data, x._mask.ctypes.data) y = masked_array(x, copy=True) assert_not_equal(y._data.ctypes.data, x._data.ctypes.data) assert_not_equal(y._mask.ctypes.data, x._mask.ctypes.data) def test_deepcopy(self): from copy import deepcopy a = array([0, 1, 2], mask=[False, True, False]) copied = deepcopy(a) assert_equal(copied.mask, a.mask) assert_not_equal(id(a._mask), id(copied._mask)) # copied[1] = 1 assert_equal(copied.mask, [0, 0, 0]) assert_equal(a.mask, [0, 1, 0]) # copied = deepcopy(a) assert_equal(copied.mask, a.mask) copied.mask[1] = False assert_equal(copied.mask, [0, 0, 0]) assert_equal(a.mask, [0, 1, 0]) def test_pickling(self): "Tests pickling" a = arange(10) a[::3] = masked a.fill_value = 999 a_pickled = pickle.loads(a.dumps()) assert_equal(a_pickled._mask, a._mask) assert_equal(a_pickled._data, a._data) assert_equal(a_pickled.fill_value, 999) def test_pickling_subbaseclass(self): "Test pickling w/ a subclass of ndarray" a = array(np.matrix(list(range(10))), mask=[1, 0, 1, 0, 0] * 2) a_pickled = pickle.loads(a.dumps()) assert_equal(a_pickled._mask, a._mask) assert_equal(a_pickled, a) self.assertTrue(isinstance(a_pickled._data, np.matrix)) def test_pickling_maskedconstant(self): "Test pickling MaskedConstant" mc = np.ma.masked mc_pickled = pickle.loads(mc.dumps()) assert_equal(mc_pickled._baseclass, mc._baseclass) assert_equal(mc_pickled._mask, mc._mask) assert_equal(mc_pickled._data, mc._data) def test_pickling_wstructured(self): "Tests pickling w/ structured array" a = array([(1, 1.), (2, 2.)], mask=[(0, 0), (0, 1)], dtype=[('a', int), ('b', float)]) a_pickled = pickle.loads(a.dumps()) assert_equal(a_pickled._mask, a._mask) assert_equal(a_pickled, a) def test_pickling_keepalignment(self): "Tests pickling w/ F_CONTIGUOUS arrays" a = arange(10) a.shape = (-1, 2) b = a.T test = pickle.loads(pickle.dumps(b)) assert_equal(test, b) def test_single_element_subscript(self): "Tests single element subscripts of Maskedarrays." a = array([1, 3, 2]) b = array([1, 3, 2], mask=[1, 0, 1]) assert_equal(a[0].shape, ()) assert_equal(b[0].shape, ()) assert_equal(b[1].shape, ()) def test_topython(self): "Tests some communication issues with Python." assert_equal(1, int(array(1))) assert_equal(1.0, float(array(1))) assert_equal(1, int(array([[[1]]]))) assert_equal(1.0, float(array([[1]]))) self.assertRaises(TypeError, float, array([1, 1])) # with warnings.catch_warnings(): warnings.simplefilter('ignore', UserWarning) assert_(np.isnan(float(array([1], mask=[1])))) # a = array([1, 2, 3], mask=[1, 0, 0]) self.assertRaises(TypeError, lambda:float(a)) assert_equal(float(a[-1]), 3.) self.assertTrue(np.isnan(float(a[0]))) self.assertRaises(TypeError, int, a) assert_equal(int(a[-1]), 3) self.assertRaises(MAError, lambda:int(a[0])) def test_oddfeatures_1(self): "Test of other odd features" x = arange(20) x = x.reshape(4, 5) x.flat[5] = 12 assert_(x[1, 0] == 12) z = x + 10j * x assert_equal(z.real, x) assert_equal(z.imag, 10 * x) assert_equal((z * conjugate(z)).real, 101 * x * x) z.imag[...] = 0.0 # x = arange(10) x[3] = masked assert_(str(x[3]) == str(masked)) c = x >= 8 assert_(count(where(c, masked, masked)) == 0) assert_(shape(where(c, masked, masked)) == c.shape) # z = masked_where(c, x) assert_(z.dtype is x.dtype) assert_(z[3] is masked) assert_(z[4] is not masked) assert_(z[7] is not masked) assert_(z[8] is masked) assert_(z[9] is masked) assert_equal(x, z) def test_oddfeatures_2(self): "Tests some more features." x = array([1., 2., 3., 4., 5.]) c = array([1, 1, 1, 0, 0]) x[2] = masked z = where(c, x, -x) assert_equal(z, [1., 2., 0., -4., -5]) c[0] = masked z = where(c, x, -x) assert_equal(z, [1., 2., 0., -4., -5]) assert_(z[0] is masked) assert_(z[1] is not masked) assert_(z[2] is masked) def test_oddfeatures_3(self): """Tests some generic features.""" atest = array([10], mask=True) btest = array([20]) idx = atest.mask atest[idx] = btest[idx] assert_equal(atest, [20]) def test_filled_w_flexible_dtype(self): "Test filled w/ flexible dtype" flexi = array([(1, 1, 1)], dtype=[('i', int), ('s', '|S8'), ('f', float)]) flexi[0] = masked assert_equal(flexi.filled(), np.array([(default_fill_value(0), default_fill_value('0'), default_fill_value(0.),)], dtype=flexi.dtype)) flexi[0] = masked assert_equal(flexi.filled(1), np.array([(1, '1', 1.)], dtype=flexi.dtype)) def test_filled_w_mvoid(self): "Test filled w/ mvoid" ndtype = [('a', int), ('b', float)] a = mvoid((1, 2.), mask=[(0, 1)], dtype=ndtype) # Filled using default test = a.filled() assert_equal(tuple(test), (1, default_fill_value(1.))) # Explicit fill_value test = a.filled((-1, -1)) assert_equal(tuple(test), (1, -1)) # Using predefined filling values a.fill_value = (-999, -999) assert_equal(tuple(a.filled()), (1, -999)) def test_filled_w_nested_dtype(self): "Test filled w/ nested dtype" ndtype = [('A', int), ('B', [('BA', int), ('BB', int)])] a = array([(1, (1, 1)), (2, (2, 2))], mask=[(0, (1, 0)), (0, (0, 1))], dtype=ndtype) test = a.filled(0) control = np.array([(1, (0, 1)), (2, (2, 0))], dtype=ndtype) assert_equal(test, control) # test = a['B'].filled(0) control = np.array([(0, 1), (2, 0)], dtype=a['B'].dtype) assert_equal(test, control) def test_filled_w_f_order(self): "Test filled w/ F-contiguous array" a = array(np.array([(0, 1, 2), (4, 5, 6)], order='F'), mask=np.array([(0, 0, 1), (1, 0, 0)], order='F'), order='F') # this is currently ignored self.assertTrue(a.flags['F_CONTIGUOUS']) self.assertTrue(a.filled(0).flags['F_CONTIGUOUS']) def test_optinfo_propagation(self): "Checks that _optinfo dictionary isn't back-propagated" x = array([1, 2, 3, ], dtype=float) x._optinfo['info'] = '???' y = x.copy() assert_equal(y._optinfo['info'], '???') y._optinfo['info'] = '!!!' assert_equal(x._optinfo['info'], '???') def test_fancy_printoptions(self): "Test printing a masked array w/ fancy dtype." fancydtype = np.dtype([('x', int), ('y', [('t', int), ('s', float)])]) test = array([(1, (2, 3.0)), (4, (5, 6.0))], mask=[(1, (0, 1)), (0, (1, 0))], dtype=fancydtype) control = "[(--, (2, --)) (4, (--, 6.0))]" assert_equal(str(test), control) def test_flatten_structured_array(self): "Test flatten_structured_array on arrays" # On ndarray ndtype = [('a', int), ('b', float)] a = np.array([(1, 1), (2, 2)], dtype=ndtype) test = flatten_structured_array(a) control = np.array([[1., 1.], [2., 2.]], dtype=np.float) assert_equal(test, control) assert_equal(test.dtype, control.dtype) # On masked_array a = array([(1, 1), (2, 2)], mask=[(0, 1), (1, 0)], dtype=ndtype) test = flatten_structured_array(a) control = array([[1., 1.], [2., 2.]], mask=[[0, 1], [1, 0]], dtype=np.float) assert_equal(test, control) assert_equal(test.dtype, control.dtype) assert_equal(test.mask, control.mask) # On masked array with nested structure ndtype = [('a', int), ('b', [('ba', int), ('bb', float)])] a = array([(1, (1, 1.1)), (2, (2, 2.2))], mask=[(0, (1, 0)), (1, (0, 1))], dtype=ndtype) test = flatten_structured_array(a) control = array([[1., 1., 1.1], [2., 2., 2.2]], mask=[[0, 1, 0], [1, 0, 1]], dtype=np.float) assert_equal(test, control) assert_equal(test.dtype, control.dtype) assert_equal(test.mask, control.mask) # Keeping the initial shape ndtype = [('a', int), ('b', float)] a = np.array([[(1, 1), ], [(2, 2), ]], dtype=ndtype) test = flatten_structured_array(a) control = np.array([[[1., 1.], ], [[2., 2.], ]], dtype=np.float) assert_equal(test, control) assert_equal(test.dtype, control.dtype) def test_void0d(self): "Test creating a mvoid object" ndtype = [('a', int), ('b', int)] a = np.array([(1, 2,)], dtype=ndtype)[0] f = mvoid(a) assert_(isinstance(f, mvoid)) # a = masked_array([(1, 2)], mask=[(1, 0)], dtype=ndtype)[0] assert_(isinstance(a, mvoid)) # a = masked_array([(1, 2), (1, 2)], mask=[(1, 0), (0, 0)], dtype=ndtype) f = mvoid(a._data[0], a._mask[0]) assert_(isinstance(f, mvoid)) def test_mvoid_getitem(self): "Test mvoid.__getitem__" ndtype = [('a', int), ('b', int)] a = masked_array([(1, 2,), (3, 4)], mask=[(0, 0), (1, 0)], dtype=ndtype) # w/o mask f = a[0] self.assertTrue(isinstance(f, mvoid)) assert_equal((f[0], f['a']), (1, 1)) assert_equal(f['b'], 2) # w/ mask f = a[1] self.assertTrue(isinstance(f, mvoid)) self.assertTrue(f[0] is masked) self.assertTrue(f['a'] is masked) assert_equal(f[1], 4) def test_mvoid_iter(self): "Test iteration on __getitem__" ndtype = [('a', int), ('b', int)] a = masked_array([(1, 2,), (3, 4)], mask=[(0, 0), (1, 0)], dtype=ndtype) # w/o mask assert_equal(list(a[0]), [1, 2]) # w/ mask assert_equal(list(a[1]), [masked, 4]) def test_mvoid_print(self): "Test printing a mvoid" mx = array([(1, 1), (2, 2)], dtype=[('a', int), ('b', int)]) assert_equal(str(mx[0]), "(1, 1)") mx['b'][0] = masked ini_display = masked_print_option._display masked_print_option.set_display("-X-") try: assert_equal(str(mx[0]), "(1, -X-)") assert_equal(repr(mx[0]), "(1, -X-)") finally: masked_print_option.set_display(ini_display) #------------------------------------------------------------------------------ class TestMaskedArrayArithmetic(TestCase): "Base test class for MaskedArrays." def setUp (self): "Base data definition." x = np.array([1., 1., 1., -2., pi / 2.0, 4., 5., -10., 10., 1., 2., 3.]) y = np.array([5., 0., 3., 2., -1., -4., 0., -10., 10., 1., 0., 3.]) a10 = 10. m1 = [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0] m2 = [0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1] xm = masked_array(x, mask=m1) ym = masked_array(y, mask=m2) z = np.array([-.5, 0., .5, .8]) zm = masked_array(z, mask=[0, 1, 0, 0]) xf = np.where(m1, 1e+20, x) xm.set_fill_value(1e+20) self.d = (x, y, a10, m1, m2, xm, ym, z, zm, xf) self.err_status = np.geterr() np.seterr(divide='ignore', invalid='ignore') def tearDown(self): np.seterr(**self.err_status) def test_basic_arithmetic (self): "Test of basic arithmetic." (x, y, a10, m1, m2, xm, ym, z, zm, xf) = self.d a2d = array([[1, 2], [0, 4]]) a2dm = masked_array(a2d, [[0, 0], [1, 0]]) assert_equal(a2d * a2d, a2d * a2dm) assert_equal(a2d + a2d, a2d + a2dm) assert_equal(a2d - a2d, a2d - a2dm) for s in [(12,), (4, 3), (2, 6)]: x = x.reshape(s) y = y.reshape(s) xm = xm.reshape(s) ym = ym.reshape(s) xf = xf.reshape(s) assert_equal(-x, -xm) assert_equal(x + y, xm + ym) assert_equal(x - y, xm - ym) assert_equal(x * y, xm * ym) assert_equal(x / y, xm / ym) assert_equal(a10 + y, a10 + ym) assert_equal(a10 - y, a10 - ym) assert_equal(a10 * y, a10 * ym) assert_equal(a10 / y, a10 / ym) assert_equal(x + a10, xm + a10) assert_equal(x - a10, xm - a10) assert_equal(x * a10, xm * a10) assert_equal(x / a10, xm / a10) assert_equal(x ** 2, xm ** 2) assert_equal(abs(x) ** 2.5, abs(xm) ** 2.5) assert_equal(x ** y, xm ** ym) assert_equal(np.add(x, y), add(xm, ym)) assert_equal(np.subtract(x, y), subtract(xm, ym)) assert_equal(np.multiply(x, y), multiply(xm, ym)) assert_equal(np.divide(x, y), divide(xm, ym)) def test_divide_on_different_shapes(self): x = arange(6, dtype=float) x.shape = (2, 3) y = arange(3, dtype=float) # z = x / y assert_equal(z, [[-1., 1., 1.], [-1., 4., 2.5]]) assert_equal(z.mask, [[1, 0, 0], [1, 0, 0]]) # z = x / y[None,:] assert_equal(z, [[-1., 1., 1.], [-1., 4., 2.5]]) assert_equal(z.mask, [[1, 0, 0], [1, 0, 0]]) # y = arange(2, dtype=float) z = x / y[:, None] assert_equal(z, [[-1., -1., -1.], [3., 4., 5.]]) assert_equal(z.mask, [[1, 1, 1], [0, 0, 0]]) def test_mixed_arithmetic(self): "Tests mixed arithmetics." na = np.array([1]) ma = array([1]) self.assertTrue(isinstance(na + ma, MaskedArray)) self.assertTrue(isinstance(ma + na, MaskedArray)) def test_limits_arithmetic(self): tiny = np.finfo(float).tiny a = array([tiny, 1. / tiny, 0.]) assert_equal(getmaskarray(a / 2), [0, 0, 0]) assert_equal(getmaskarray(2 / a), [1, 0, 1]) def test_masked_singleton_arithmetic(self): "Tests some scalar arithmetics on MaskedArrays." # Masked singleton should remain masked no matter what xm = array(0, mask=1) self.assertTrue((1 / array(0)).mask) self.assertTrue((1 + xm).mask) self.assertTrue((-xm).mask) self.assertTrue(maximum(xm, xm).mask) self.assertTrue(minimum(xm, xm).mask) def test_masked_singleton_equality(self): "Tests (in)equality on masked snigleton" a = array([1, 2, 3], mask=[1, 1, 0]) assert_((a[0] == 0) is masked) assert_((a[0] != 0) is masked) assert_equal((a[-1] == 0), False) assert_equal((a[-1] != 0), True) def test_arithmetic_with_masked_singleton(self): "Checks that there's no collapsing to masked" x = masked_array([1, 2]) y = x * masked assert_equal(y.shape, x.shape) assert_equal(y._mask, [True, True]) y = x[0] * masked assert_(y is masked) y = x + masked assert_equal(y.shape, x.shape) assert_equal(y._mask, [True, True]) def test_arithmetic_with_masked_singleton_on_1d_singleton(self): "Check that we're not losing the shape of a singleton" x = masked_array([1, ]) y = x + masked assert_equal(y.shape, x.shape) assert_equal(y.mask, [True, ]) def test_scalar_arithmetic(self): x = array(0, mask=0) assert_equal(x.filled().ctypes.data, x.ctypes.data) # Make sure we don't lose the shape in some circumstances xm = array((0, 0)) / 0. assert_equal(xm.shape, (2,)) assert_equal(xm.mask, [1, 1]) def test_basic_ufuncs (self): "Test various functions such as sin, cos." (x, y, a10, m1, m2, xm, ym, z, zm, xf) = self.d assert_equal(np.cos(x), cos(xm)) assert_equal(np.cosh(x), cosh(xm)) assert_equal(np.sin(x), sin(xm)) assert_equal(np.sinh(x), sinh(xm)) assert_equal(np.tan(x), tan(xm)) assert_equal(np.tanh(x), tanh(xm)) assert_equal(np.sqrt(abs(x)), sqrt(xm)) assert_equal(np.log(abs(x)), log(xm)) assert_equal(np.log10(abs(x)), log10(xm)) assert_equal(np.exp(x), exp(xm)) assert_equal(np.arcsin(z), arcsin(zm)) assert_equal(np.arccos(z), arccos(zm)) assert_equal(np.arctan(z), arctan(zm)) assert_equal(np.arctan2(x, y), arctan2(xm, ym)) assert_equal(np.absolute(x), absolute(xm)) assert_equal(np.angle(x + 1j*y), angle(xm + 1j*ym)) assert_equal(np.angle(x + 1j*y, deg=True), angle(xm + 1j*ym, deg=True)) assert_equal(np.equal(x, y), equal(xm, ym)) assert_equal(np.not_equal(x, y), not_equal(xm, ym)) assert_equal(np.less(x, y), less(xm, ym)) assert_equal(np.greater(x, y), greater(xm, ym)) assert_equal(np.less_equal(x, y), less_equal(xm, ym)) assert_equal(np.greater_equal(x, y), greater_equal(xm, ym)) assert_equal(np.conjugate(x), conjugate(xm)) 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 = 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)) def test_minmax_func (self): "Tests minimum and maximum." (x, y, a10, m1, m2, xm, ym, z, zm, xf) = self.d xr = np.ravel(x) #max doesn't work if shaped xmr = ravel(xm) assert_equal(max(xr), maximum(xmr)) #true because of careful selection of data assert_equal(min(xr), minimum(xmr)) #true because of careful selection of data # assert_equal(minimum([1, 2, 3], [4, 0, 9]), [1, 0, 3]) assert_equal(maximum([1, 2, 3], [4, 0, 9]), [4, 2, 9]) x = arange(5) y = arange(5) - 2 x[3] = masked y[0] = masked assert_equal(minimum(x, y), where(less(x, y), x, y)) assert_equal(maximum(x, y), where(greater(x, y), x, y)) assert_(minimum(x) == 0) assert_(maximum(x) == 4) # x = arange(4).reshape(2, 2) x[-1, -1] = masked assert_equal(maximum(x), 2) def test_minimummaximum_func(self): a = np.ones((2, 2)) aminimum = minimum(a, a) self.assertTrue(isinstance(aminimum, MaskedArray)) assert_equal(aminimum, np.minimum(a, a)) # aminimum = minimum.outer(a, a) self.assertTrue(isinstance(aminimum, MaskedArray)) assert_equal(aminimum, np.minimum.outer(a, a)) # amaximum = maximum(a, a) self.assertTrue(isinstance(amaximum, MaskedArray)) assert_equal(amaximum, np.maximum(a, a)) # amaximum = maximum.outer(a, a) self.assertTrue(isinstance(amaximum, MaskedArray)) assert_equal(amaximum, np.maximum.outer(a, a)) def test_minmax_reduce(self): "Test np.min/maximum.reduce on array w/ full False mask" a = array([1, 2, 3], mask=[False, False, False]) b = np.maximum.reduce(a) assert_equal(b, 3) def test_minmax_funcs_with_output(self): "Tests the min/max functions with explicit outputs" mask = np.random.rand(12).round() xm = array(np.random.uniform(0, 10, 12), mask=mask) xm.shape = (3, 4) for funcname in ('min', 'max'): # Initialize npfunc = getattr(np, funcname) mafunc = getattr(numpy.ma.core, funcname) # Use the np version nout = np.empty((4,), dtype=int) try: result = npfunc(xm, axis=0, out=nout) except MaskError: pass nout = np.empty((4,), dtype=float) result = npfunc(xm, axis=0, out=nout) self.assertTrue(result is nout) # Use the ma version nout.fill(-999) result = mafunc(xm, axis=0, out=nout) self.assertTrue(result is nout) def test_minmax_methods(self): "Additional tests on max/min" (_, _, _, _, _, xm, _, _, _, _) = self.d xm.shape = (xm.size,) assert_equal(xm.max(), 10) self.assertTrue(xm[0].max() is masked) self.assertTrue(xm[0].max(0) is masked) self.assertTrue(xm[0].max(-1) is masked) assert_equal(xm.min(), -10.) self.assertTrue(xm[0].min() is masked) self.assertTrue(xm[0].min(0) is masked) self.assertTrue(xm[0].min(-1) is masked) assert_equal(xm.ptp(), 20.) self.assertTrue(xm[0].ptp() is masked) self.assertTrue(xm[0].ptp(0) is masked) self.assertTrue(xm[0].ptp(-1) is masked) # x = array([1, 2, 3], mask=True) self.assertTrue(x.min() is masked) self.assertTrue(x.max() is masked) self.assertTrue(x.ptp() is masked) def test_addsumprod (self): "Tests add, sum, product." (x, y, a10, m1, m2, xm, ym, z, zm, xf) = self.d assert_equal(np.add.reduce(x), add.reduce(x)) assert_equal(np.add.accumulate(x), add.accumulate(x)) assert_equal(4, sum(array(4), axis=0)) assert_equal(4, sum(array(4), axis=0)) assert_equal(np.sum(x, axis=0), sum(x, axis=0)) assert_equal(np.sum(filled(xm, 0), axis=0), sum(xm, axis=0)) assert_equal(np.sum(x, 0), sum(x, 0)) assert_equal(np.product(x, axis=0), product(x, axis=0)) assert_equal(np.product(x, 0), product(x, 0)) assert_equal(np.product(filled(xm, 1), axis=0), product(xm, axis=0)) s = (3, 4) x.shape = y.shape = xm.shape = ym.shape = s if len(s) > 1: assert_equal(np.concatenate((x, y), 1), concatenate((xm, ym), 1)) assert_equal(np.add.reduce(x, 1), add.reduce(x, 1)) assert_equal(np.sum(x, 1), sum(x, 1)) assert_equal(np.product(x, 1), product(x, 1)) def test_binops_d2D(self): "Test binary operations on 2D data" a = array([[1.], [2.], [3.]], mask=[[False], [True], [True]]) b = array([[2., 3.], [4., 5.], [6., 7.]]) # test = a * b control = array([[2., 3.], [2., 2.], [3., 3.]], mask=[[0, 0], [1, 1], [1, 1]]) assert_equal(test, control) assert_equal(test.data, control.data) assert_equal(test.mask, control.mask) # test = b * a control = array([[2., 3.], [4., 5.], [6., 7.]], mask=[[0, 0], [1, 1], [1, 1]]) assert_equal(test, control) assert_equal(test.data, control.data) assert_equal(test.mask, control.mask) # a = array([[1.], [2.], [3.]]) b = array([[2., 3.], [4., 5.], [6., 7.]], mask=[[0, 0], [0, 0], [0, 1]]) test = a * b control = array([[2, 3], [8, 10], [18, 3]], mask=[[0, 0], [0, 0], [0, 1]]) assert_equal(test, control) assert_equal(test.data, control.data) assert_equal(test.mask, control.mask) # test = b * a control = array([[2, 3], [8, 10], [18, 7]], mask=[[0, 0], [0, 0], [0, 1]]) assert_equal(test, control) assert_equal(test.data, control.data) assert_equal(test.mask, control.mask) def test_domained_binops_d2D(self): "Test domained binary operations on 2D data" a = array([[1.], [2.], [3.]], mask=[[False], [True], [True]]) b = array([[2., 3.], [4., 5.], [6., 7.]]) # test = a / b control = array([[1. / 2., 1. / 3.], [2., 2.], [3., 3.]], mask=[[0, 0], [1, 1], [1, 1]]) assert_equal(test, control) assert_equal(test.data, control.data) assert_equal(test.mask, control.mask) # test = b / a control = array([[2. / 1., 3. / 1.], [4., 5.], [6., 7.]], mask=[[0, 0], [1, 1], [1, 1]]) assert_equal(test, control) assert_equal(test.data, control.data) assert_equal(test.mask, control.mask) # a = array([[1.], [2.], [3.]]) b = array([[2., 3.], [4., 5.], [6., 7.]], mask=[[0, 0], [0, 0], [0, 1]]) test = a / b control = array([[1. / 2, 1. / 3], [2. / 4, 2. / 5], [3. / 6, 3]], mask=[[0, 0], [0, 0], [0, 1]]) assert_equal(test, control) assert_equal(test.data, control.data) assert_equal(test.mask, control.mask) # test = b / a control = array([[2 / 1., 3 / 1.], [4 / 2., 5 / 2.], [6 / 3., 7]], mask=[[0, 0], [0, 0], [0, 1]]) assert_equal(test, control) assert_equal(test.data, control.data) assert_equal(test.mask, control.mask) def test_noshrinking(self): "Check that we don't shrink a mask when not wanted" # Binary operations a = masked_array([1., 2., 3.], mask=[False, False, False], shrink=False) b = a + 1 assert_equal(b.mask, [0, 0, 0]) # In place binary operation a += 1 assert_equal(a.mask, [0, 0, 0]) # Domained binary operation b = a / 1. assert_equal(b.mask, [0, 0, 0]) # In place binary operation a /= 1. assert_equal(a.mask, [0, 0, 0]) def test_mod(self): "Tests mod" (x, y, a10, m1, m2, xm, ym, z, zm, xf) = self.d assert_equal(mod(x, y), mod(xm, ym)) test = mod(ym, xm) assert_equal(test, np.mod(ym, xm)) assert_equal(test.mask, mask_or(xm.mask, ym.mask)) test = mod(xm, ym) assert_equal(test, np.mod(xm, ym)) assert_equal(test.mask, mask_or(mask_or(xm.mask, ym.mask), (ym == 0))) def test_TakeTransposeInnerOuter(self): "Test of take, transpose, inner, outer products" x = arange(24) y = np.arange(24) x[5:6] = masked x = x.reshape(2, 3, 4) y = y.reshape(2, 3, 4) assert_equal(np.transpose(y, (2, 0, 1)), transpose(x, (2, 0, 1))) assert_equal(np.take(y, (2, 0, 1), 1), take(x, (2, 0, 1), 1)) assert_equal(np.inner(filled(x, 0), filled(y, 0)), inner(x, y)) assert_equal(np.outer(filled(x, 0), filled(y, 0)), outer(x, y)) y = array(['abc', 1, 'def', 2, 3], object) y[2] = masked t = take(y, [0, 3, 4]) assert_(t[0] == 'abc') assert_(t[1] == 2) assert_(t[2] == 3) def test_imag_real(self): "Check complex" xx = array([1 + 10j, 20 + 2j], mask=[1, 0]) assert_equal(xx.imag, [10, 2]) assert_equal(xx.imag.filled(), [1e+20, 2]) assert_equal(xx.imag.dtype, xx._data.imag.dtype) assert_equal(xx.real, [1, 20]) assert_equal(xx.real.filled(), [1e+20, 20]) assert_equal(xx.real.dtype, xx._data.real.dtype) def test_methods_with_output(self): xm = array(np.random.uniform(0, 10, 12)).reshape(3, 4) xm[:, 0] = xm[0] = xm[-1, -1] = masked # funclist = ('sum', 'prod', 'var', 'std', 'max', 'min', 'ptp', 'mean',) # for funcname in funclist: npfunc = getattr(np, funcname) xmmeth = getattr(xm, funcname) # A ndarray as explicit input output = np.empty(4, dtype=float) output.fill(-9999) result = npfunc(xm, axis=0, out=output) # ... the result should be the given output assert_(result is output) assert_equal(result, xmmeth(axis=0, out=output)) # output = empty(4, dtype=int) result = xmmeth(axis=0, out=output) assert_(result is output) assert_(output[0] is masked) def test_eq_on_structured(self): "Test the equality of structured arrays" ndtype = [('A', int), ('B', int)] a = array([(1, 1), (2, 2)], mask=[(0, 1), (0, 0)], dtype=ndtype) test = (a == a) assert_equal(test, [True, True]) assert_equal(test.mask, [False, False]) b = array([(1, 1), (2, 2)], mask=[(1, 0), (0, 0)], dtype=ndtype) test = (a == b) assert_equal(test, [False, True]) assert_equal(test.mask, [True, False]) b = array([(1, 1), (2, 2)], mask=[(0, 1), (1, 0)], dtype=ndtype) test = (a == b) assert_equal(test, [True, False]) assert_equal(test.mask, [False, False]) def test_ne_on_structured(self): "Test the equality of structured arrays" ndtype = [('A', int), ('B', int)] a = array([(1, 1), (2, 2)], mask=[(0, 1), (0, 0)], dtype=ndtype) test = (a != a) assert_equal(test, [False, False]) assert_equal(test.mask, [False, False]) b = array([(1, 1), (2, 2)], mask=[(1, 0), (0, 0)], dtype=ndtype) test = (a != b) assert_equal(test, [True, False]) assert_equal(test.mask, [True, False]) b = array([(1, 1), (2, 2)], mask=[(0, 1), (1, 0)], dtype=ndtype) test = (a != b) assert_equal(test, [False, True]) assert_equal(test.mask, [False, False]) def test_eq_w_None(self): # With partial mask a = array([1, 2], mask=[0, 1]) assert_equal(a == None, False) assert_equal(a.data == None, False) assert_equal(a.mask == None, False) assert_equal(a != None, True) # With nomask a = array([1, 2], mask=False) assert_equal(a == None, False) assert_equal(a != None, True) # With complete mask a = array([1, 2], mask=True) assert_equal(a == None, False) assert_equal(a != None, True) # With masked a = masked assert_equal(a == None, masked) def test_eq_w_scalar(self): a = array(1) assert_equal(a == 1, True) assert_equal(a == 0, False) assert_equal(a != 1, False) assert_equal(a != 0, True) def test_numpyarithmetics(self): "Check that the mask is not back-propagated when using numpy functions" a = masked_array([-1, 0, 1, 2, 3], mask=[0, 0, 0, 0, 1]) control = masked_array([np.nan, np.nan, 0, np.log(2), -1], mask=[1, 1, 0, 0, 1]) # test = log(a) assert_equal(test, control) assert_equal(test.mask, control.mask) assert_equal(a.mask, [0, 0, 0, 0, 1]) # test = np.log(a) assert_equal(test, control) assert_equal(test.mask, control.mask) assert_equal(a.mask, [0, 0, 0, 0, 1]) #------------------------------------------------------------------------------ class TestMaskedArrayAttributes(TestCase): def test_keepmask(self): "Tests the keep mask flag" x = masked_array([1, 2, 3], mask=[1, 0, 0]) mx = masked_array(x) assert_equal(mx.mask, x.mask) mx = masked_array(x, mask=[0, 1, 0], keep_mask=False) assert_equal(mx.mask, [0, 1, 0]) mx = masked_array(x, mask=[0, 1, 0], keep_mask=True) assert_equal(mx.mask, [1, 1, 0]) # We default to true mx = masked_array(x, mask=[0, 1, 0]) assert_equal(mx.mask, [1, 1, 0]) def test_hardmask(self): "Test hard_mask" d = arange(5) n = [0, 0, 0, 1, 1] m = make_mask(n) xh = array(d, mask=m, hard_mask=True) # We need to copy, to avoid updating d in xh ! xs = array(d, mask=m, hard_mask=False, copy=True) xh[[1, 4]] = [10, 40] xs[[1, 4]] = [10, 40] assert_equal(xh._data, [0, 10, 2, 3, 4]) assert_equal(xs._data, [0, 10, 2, 3, 40]) #assert_equal(xh.mask.ctypes._data, m.ctypes._data) assert_equal(xs.mask, [0, 0, 0, 1, 0]) self.assertTrue(xh._hardmask) self.assertTrue(not xs._hardmask) xh[1:4] = [10, 20, 30] xs[1:4] = [10, 20, 30] assert_equal(xh._data, [0, 10, 20, 3, 4]) assert_equal(xs._data, [0, 10, 20, 30, 40]) #assert_equal(xh.mask.ctypes._data, m.ctypes._data) assert_equal(xs.mask, nomask) xh[0] = masked xs[0] = masked assert_equal(xh.mask, [1, 0, 0, 1, 1]) assert_equal(xs.mask, [1, 0, 0, 0, 0]) xh[:] = 1 xs[:] = 1 assert_equal(xh._data, [0, 1, 1, 3, 4]) assert_equal(xs._data, [1, 1, 1, 1, 1]) assert_equal(xh.mask, [1, 0, 0, 1, 1]) assert_equal(xs.mask, nomask) # Switch to soft mask xh.soften_mask() xh[:] = arange(5) assert_equal(xh._data, [0, 1, 2, 3, 4]) assert_equal(xh.mask, nomask) # Switch back to hard mask xh.harden_mask() xh[xh < 3] = masked assert_equal(xh._data, [0, 1, 2, 3, 4]) assert_equal(xh._mask, [1, 1, 1, 0, 0]) xh[filled(xh > 1, False)] = 5 assert_equal(xh._data, [0, 1, 2, 5, 5]) assert_equal(xh._mask, [1, 1, 1, 0, 0]) # xh = array([[1, 2], [3, 4]], mask=[[1, 0], [0, 0]], hard_mask=True) xh[0] = 0 assert_equal(xh._data, [[1, 0], [3, 4]]) assert_equal(xh._mask, [[1, 0], [0, 0]]) xh[-1, -1] = 5 assert_equal(xh._data, [[1, 0], [3, 5]]) assert_equal(xh._mask, [[1, 0], [0, 0]]) xh[filled(xh < 5, False)] = 2 assert_equal(xh._data, [[1, 2], [2, 5]]) assert_equal(xh._mask, [[1, 0], [0, 0]]) def test_hardmask_again(self): "Another test of hardmask" d = arange(5) n = [0, 0, 0, 1, 1] m = make_mask(n) xh = array(d, mask=m, hard_mask=True) xh[4:5] = 999 #assert_equal(xh.mask.ctypes._data, m.ctypes._data) xh[0:1] = 999 assert_equal(xh._data, [999, 1, 2, 3, 4]) def test_hardmask_oncemore_yay(self): "OK, yet another test of hardmask" "Make sure that harden_mask/soften_mask//unshare_mask retursn self" a = array([1, 2, 3], mask=[1, 0, 0]) b = a.harden_mask() assert_equal(a, b) b[0] = 0 assert_equal(a, b) assert_equal(b, array([1, 2, 3], mask=[1, 0, 0])) a = b.soften_mask() a[0] = 0 assert_equal(a, b) assert_equal(b, array([0, 2, 3], mask=[0, 0, 0])) def test_smallmask(self): "Checks the behaviour of _smallmask" a = arange(10) a[1] = masked a[1] = 1 assert_equal(a._mask, nomask) a = arange(10) a._smallmask = False a[1] = masked a[1] = 1 assert_equal(a._mask, zeros(10)) def test_shrink_mask(self): "Tests .shrink_mask()" a = array([1, 2, 3], mask=[0, 0, 0]) b = a.shrink_mask() assert_equal(a, b) assert_equal(a.mask, nomask) def test_flat(self): "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 = masked_array(np.matrix([[1, 2, 3]]), mask=[0, 0, 1]) testflat = test.flat testflat[:] = testflat[[2, 1, 0]] assert_equal(test, control) #------------------------------------------------------------------------------ class TestFillingValues(TestCase): # def test_check_on_scalar(self): "Test _check_fill_value" _check_fill_value = np.ma.core._check_fill_value # fval = _check_fill_value(0, int) assert_equal(fval, 0) fval = _check_fill_value(None, int) assert_equal(fval, default_fill_value(0)) # fval = _check_fill_value(0, "|S3") 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)) def test_check_on_fields(self): "Tests _check_fill_value with records" _check_fill_value = np.ma.core._check_fill_value ndtype = [('a', int), ('b', float), ('c', "|S3")] # A check on a list should return a single record fval = _check_fill_value([-999, -12345678.9, "???"], ndtype) self.assertTrue(isinstance(fval, ndarray)) assert_equal(fval.item(), [-999, -12345678.9, asbytes("???")]) # A check on None should output the defaults fval = _check_fill_value(None, ndtype) self.assertTrue(isinstance(fval, ndarray)) assert_equal(fval.item(), [default_fill_value(0), default_fill_value(0.), asbytes(default_fill_value("0"))]) #.....Using a structured type as fill_value should work fill_val = np.array((-999, -12345678.9, "???"), dtype=ndtype) fval = _check_fill_value(fill_val, ndtype) self.assertTrue(isinstance(fval, ndarray)) assert_equal(fval.item(), [-999, -12345678.9, asbytes("???")]) #.....Using a flexible type w/ a different type shouldn't matter # BEHAVIOR in 1.5 and earlier: match structured types by position #fill_val = np.array((-999, -12345678.9, "???"), # dtype=[("A", int), ("B", float), ("C", "|S3")]) # BEHAVIOR in 1.6 and later: match structured types by name fill_val = np.array(("???", -999, -12345678.9), dtype=[("c", "|S3"), ("a", int), ("b", float), ]) fval = _check_fill_value(fill_val, ndtype) self.assertTrue(isinstance(fval, ndarray)) assert_equal(fval.item(), [-999, -12345678.9, asbytes("???")]) #.....Using an object-array shouldn't matter either fill_value = np.array((-999, -12345678.9, "???"), dtype=object) fval = _check_fill_value(fill_val, ndtype) self.assertTrue(isinstance(fval, ndarray)) assert_equal(fval.item(), [-999, -12345678.9, asbytes("???")]) # fill_value = np.array((-999, -12345678.9, "???")) fval = _check_fill_value(fill_val, ndtype) self.assertTrue(isinstance(fval, ndarray)) assert_equal(fval.item(), [-999, -12345678.9, asbytes("???")]) #.....One-field-only flexible type should work as well ndtype = [("a", int)] fval = _check_fill_value(-999999999, ndtype) self.assertTrue(isinstance(fval, ndarray)) assert_equal(fval.item(), (-999999999,)) def test_fillvalue_conversion(self): "Tests the behavior of fill_value during conversion" # We had a tailored comment to make sure special attributes are properly # dealt with a = array(asbytes_nested(['3', '4', '5'])) a._optinfo.update({'comment':"updated!"}) # b = array(a, dtype=int) assert_equal(b._data, [3, 4, 5]) assert_equal(b.fill_value, default_fill_value(0)) # b = array(a, dtype=float) assert_equal(b._data, [3, 4, 5]) assert_equal(b.fill_value, default_fill_value(0.)) # b = a.astype(int) assert_equal(b._data, [3, 4, 5]) assert_equal(b.fill_value, default_fill_value(0)) assert_equal(b._optinfo['comment'], "updated!") # b = a.astype([('a', '|S3')]) assert_equal(b['a']._data, a._data) assert_equal(b['a'].fill_value, a.fill_value) def test_fillvalue(self): "Yet more fun with the fill_value" data = masked_array([1, 2, 3], fill_value= -999) series = data[[0, 2, 1]] assert_equal(series._fill_value, data._fill_value) # mtype = [('f', float), ('s', '|S3')] x = array([(1, 'a'), (2, 'b'), (pi, 'pi')], dtype=mtype) x.fill_value = 999 assert_equal(x.fill_value.item(), [999., asbytes('999')]) assert_equal(x['f'].fill_value, 999) assert_equal(x['s'].fill_value, asbytes('999')) # x.fill_value = (9, '???') assert_equal(x.fill_value.item(), (9, asbytes('???'))) assert_equal(x['f'].fill_value, 9) assert_equal(x['s'].fill_value, asbytes('???')) # x = array([1, 2, 3.1]) x.fill_value = 999 assert_equal(np.asarray(x.fill_value).dtype, float) assert_equal(x.fill_value, 999.) assert_equal(x._fill_value, np.array(999.)) def test_fillvalue_exotic_dtype(self): "Tests yet more exotic flexible dtypes" _check_fill_value = np.ma.core._check_fill_value ndtype = [('i', int), ('s', '|S8'), ('f', float)] control = np.array((default_fill_value(0), default_fill_value('0'), default_fill_value(0.),), dtype=ndtype) assert_equal(_check_fill_value(None, ndtype), control) # The shape shouldn't matter ndtype = [('f0', float, (2, 2))] control = np.array((default_fill_value(0.),), dtype=[('f0', float)]).astype(ndtype) assert_equal(_check_fill_value(None, ndtype), control) control = np.array((0,), dtype=[('f0', float)]).astype(ndtype) assert_equal(_check_fill_value(0, ndtype), control) # ndtype = np.dtype("int, (2,3)float, float") control = np.array((default_fill_value(0), default_fill_value(0.), default_fill_value(0.),), dtype="int, float, float").astype(ndtype) test = _check_fill_value(None, ndtype) assert_equal(test, control) control = np.array((0, 0, 0), dtype="int, float, float").astype(ndtype) assert_equal(_check_fill_value(0, ndtype), control) def test_extremum_fill_value(self): "Tests extremum fill values for flexible type." a = array([(1, (2, 3)), (4, (5, 6))], dtype=[('A', int), ('B', [('BA', int), ('BB', int)])]) test = a.fill_value assert_equal(test['A'], default_fill_value(a['A'])) assert_equal(test['B']['BA'], default_fill_value(a['B']['BA'])) assert_equal(test['B']['BB'], default_fill_value(a['B']['BB'])) # test = minimum_fill_value(a) assert_equal(test[0], minimum_fill_value(a['A'])) assert_equal(test[1][0], minimum_fill_value(a['B']['BA'])) assert_equal(test[1][1], minimum_fill_value(a['B']['BB'])) assert_equal(test[1], minimum_fill_value(a['B'])) # test = maximum_fill_value(a) assert_equal(test[0], maximum_fill_value(a['A'])) assert_equal(test[1][0], maximum_fill_value(a['B']['BA'])) assert_equal(test[1][1], maximum_fill_value(a['B']['BB'])) assert_equal(test[1], maximum_fill_value(a['B'])) def test_fillvalue_individual_fields(self): "Test setting fill_value on individual fields" ndtype = [('a', int), ('b', int)] # Explicit fill_value a = array(list(zip([1, 2, 3], [4, 5, 6])), fill_value=(-999, -999), dtype=ndtype) f = a._fill_value aa = a['a'] aa.set_fill_value(10) assert_equal(aa._fill_value, np.array(10)) assert_equal(tuple(a.fill_value), (10, -999)) a.fill_value['b'] = -10 assert_equal(tuple(a.fill_value), (10, -10)) # Implicit fill_value t = array(list(zip([1, 2, 3], [4, 5, 6])), dtype=[('a', int), ('b', int)]) tt = t['a'] tt.set_fill_value(10) assert_equal(tt._fill_value, np.array(10)) assert_equal(tuple(t.fill_value), (10, default_fill_value(0))) def test_fillvalue_implicit_structured_array(self): "Check that fill_value is always defined for structured arrays" ndtype = ('b', float) adtype = ('a', float) a = array([(1.,), (2.,)], mask=[(False,), (False,)], fill_value=(np.nan,), dtype=np.dtype([adtype])) b = empty(a.shape, dtype=[adtype, ndtype]) b['a'] = a['a'] b['a'].set_fill_value(a['a'].fill_value) f = b._fill_value[()] assert_(np.isnan(f[0])) assert_equal(f[-1], default_fill_value(1.)) def test_fillvalue_as_arguments(self): "Test adding a fill_value parameter to empty/ones/zeros" a = empty(3, fill_value=999.) assert_equal(a.fill_value, 999.) # a = ones(3, fill_value=999., dtype=float) assert_equal(a.fill_value, 999.) # a = zeros(3, fill_value=0., dtype=complex) assert_equal(a.fill_value, 0.) # a = identity(3, fill_value=0., dtype=complex) assert_equal(a.fill_value, 0.) def test_fillvalue_in_view(self): "Test the behavior of fill_value in view" # Create initial masked array x = array([1, 2, 3], fill_value=1, dtype=np.int64) # Check that fill_value is preserved by default y = x.view() assert_(y.fill_value==1) # Check that fill_value is preserved if dtype is specified and the # dtype is an ndarray sub-class and has a _fill_value attribute y = x.view(MaskedArray) assert_(y.fill_value==1) # Check that fill_value is preserved if type is specified and the # dtype is an ndarray sub-class and has a _fill_value attribute (by # default, the first argument is dtype, not type) y = x.view(type=MaskedArray) assert_(y.fill_value==1) # Check that code does not crash if passed an ndarray sub-class that # does not have a _fill_value attribute y = x.view(np.ndarray) y = x.view(type=np.ndarray) # Check that fill_value can be overriden with view y = x.view(MaskedArray, fill_value=2) assert_(y.fill_value==2) # Check that fill_value can be overriden with view (using type=) y = x.view(type=MaskedArray, fill_value=2) assert_(y.fill_value==2) # Check that fill_value gets reset if passed a dtype but not a # fill_value. This is because even though in some cases one can safely # cast the fill_value, e.g. if taking an int64 view of an int32 array, # in other cases, this cannot be done (e.g. int32 view of an int64 # array with a large fill_value). y = x.view(dtype=np.int32) assert_(y.fill_value == 999999) #------------------------------------------------------------------------------ class TestUfuncs(TestCase): "Test class for the application of ufuncs on MaskedArrays." def setUp(self): "Base data definition." self.d = (array([1.0, 0, -1, pi / 2] * 2, mask=[0, 1] + [0] * 6), array([1.0, 0, -1, pi / 2] * 2, mask=[1, 0] + [0] * 6),) self.err_status = np.geterr() np.seterr(divide='ignore', invalid='ignore') def tearDown(self): np.seterr(**self.err_status) def test_testUfuncRegression(self): "Tests new ufuncs on MaskedArrays." for f in ['sqrt', 'log', 'log10', 'exp', 'conjugate', 'sin', 'cos', 'tan', 'arcsin', 'arccos', 'arctan', 'sinh', 'cosh', 'tanh', 'arcsinh', 'arccosh', 'arctanh', 'absolute', 'fabs', 'negative', # 'nonzero', 'around', 'floor', 'ceil', # 'sometrue', 'alltrue', 'logical_not', 'add', 'subtract', 'multiply', 'divide', 'true_divide', 'floor_divide', 'remainder', 'fmod', 'hypot', 'arctan2', 'equal', 'not_equal', 'less_equal', 'greater_equal', 'less', 'greater', 'logical_and', 'logical_or', 'logical_xor', ]: try: uf = getattr(umath, f) except AttributeError: uf = getattr(fromnumeric, f) mf = getattr(numpy.ma.core, f) args = self.d[:uf.nin] ur = uf(*args) mr = mf(*args) assert_equal(ur.filled(0), mr.filled(0), f) assert_mask_equal(ur.mask, mr.mask, err_msg=f) def test_reduce(self): "Tests reduce on MaskedArrays." a = self.d[0] self.assertTrue(not alltrue(a, axis=0)) self.assertTrue(sometrue(a, axis=0)) assert_equal(sum(a[:3], axis=0), 0) assert_equal(product(a, axis=0), 0) assert_equal(add.reduce(a), pi) def test_minmax(self): "Tests extrema on MaskedArrays." a = arange(1, 13).reshape(3, 4) amask = masked_where(a < 5, a) assert_equal(amask.max(), a.max()) assert_equal(amask.min(), 5) assert_equal(amask.max(0), a.max(0)) assert_equal(amask.min(0), [5, 6, 7, 8]) self.assertTrue(amask.max(1)[0].mask) self.assertTrue(amask.min(1)[0].mask) def test_ndarray_mask(self): "Check that the mask of the result is a ndarray (not a MaskedArray...)" a = masked_array([-1, 0, 1, 2, 3], mask=[0, 0, 0, 0, 1]) test = np.sqrt(a) control = masked_array([-1, 0, 1, np.sqrt(2), -1], mask=[1, 0, 0, 0, 1]) assert_equal(test, control) assert_equal(test.mask, control.mask) self.assertTrue(not isinstance(test.mask, MaskedArray)) def test_treatment_of_NotImplemented(self): "Check any NotImplemented returned by umath. is passed on" a = masked_array([1., 2.], mask=[1, 0]) # basic tests for _MaskedBinaryOperation assert_(a.__mul__('abc') is NotImplemented) assert_(multiply.outer(a, 'abc') is NotImplemented) # and for _DomainedBinaryOperation assert_(a.__div__('abc') is NotImplemented) # also check explicitly that rmul of another class can be accessed class MyClass(str): def __mul__(self, other): return "My mul" def __rmul__(self, other): return "My rmul" me = MyClass() assert_(me * a == "My mul") assert_(a * me == "My rmul") #------------------------------------------------------------------------------ class TestMaskedArrayInPlaceArithmetics(TestCase): "Test MaskedArray Arithmetics" def setUp(self): x = arange(10) y = arange(10) xm = arange(10) xm[2] = masked self.intdata = (x, y, xm) self.floatdata = (x.astype(float), y.astype(float), xm.astype(float)) def test_inplace_addition_scalar(self): """Test of inplace additions""" (x, y, xm) = self.intdata xm[2] = masked x += 1 assert_equal(x, y + 1) xm += 1 assert_equal(xm, y + 1) # (x, _, xm) = self.floatdata id1 = x.data.ctypes._data x += 1. assert_(id1 == x.data.ctypes._data) assert_equal(x, y + 1.) def test_inplace_addition_array(self): """Test of inplace additions""" (x, y, xm) = self.intdata m = xm.mask a = arange(10, dtype=np.int16) a[-1] = masked x += a xm += a assert_equal(x, y + a) assert_equal(xm, y + a) assert_equal(xm.mask, mask_or(m, a.mask)) def test_inplace_subtraction_scalar(self): """Test of inplace subtractions""" (x, y, xm) = self.intdata x -= 1 assert_equal(x, y - 1) xm -= 1 assert_equal(xm, y - 1) def test_inplace_subtraction_array(self): """Test of inplace subtractions""" (x, y, xm) = self.floatdata m = xm.mask a = arange(10, dtype=float) a[-1] = masked x -= a xm -= a assert_equal(x, y - a) assert_equal(xm, y - a) assert_equal(xm.mask, mask_or(m, a.mask)) def test_inplace_multiplication_scalar(self): """Test of inplace multiplication""" (x, y, xm) = self.floatdata x *= 2.0 assert_equal(x, y * 2) xm *= 2.0 assert_equal(xm, y * 2) def test_inplace_multiplication_array(self): """Test of inplace multiplication""" (x, y, xm) = self.floatdata m = xm.mask a = arange(10, dtype=float) a[-1] = masked x *= a xm *= a assert_equal(x, y * a) assert_equal(xm, y * a) assert_equal(xm.mask, mask_or(m, a.mask)) def test_inplace_division_scalar_int(self): """Test of inplace division""" (x, y, xm) = self.intdata x = arange(10) * 2 xm = arange(10) * 2 xm[2] = masked x //= 2 assert_equal(x, y) xm //= 2 assert_equal(xm, y) def test_inplace_division_scalar_float(self): """Test of inplace division""" (x, y, xm) = self.floatdata x /= 2.0 assert_equal(x, y / 2.0) xm /= arange(10) assert_equal(xm, ones((10,))) def test_inplace_division_array_float(self): """Test of inplace division""" (x, y, xm) = self.floatdata m = xm.mask a = arange(10, dtype=float) a[-1] = masked x /= a xm /= a assert_equal(x, y / a) assert_equal(xm, y / a) assert_equal(xm.mask, mask_or(mask_or(m, a.mask), (a == 0))) def test_inplace_division_misc(self): # x = [1., 1., 1., -2., pi / 2., 4., 5., -10., 10., 1., 2., 3.] y = [5., 0., 3., 2., -1., -4., 0., -10., 10., 1., 0., 3.] m1 = [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0] m2 = [0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1] xm = masked_array(x, mask=m1) ym = masked_array(y, mask=m2) # z = xm / ym assert_equal(z._mask, [1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1]) assert_equal(z._data, [1., 1., 1., -1., -pi / 2., 4., 5., 1., 1., 1., 2., 3.]) #assert_equal(z._data, [0.2,1.,1./3.,-1.,-pi/2.,-1.,5.,1.,1.,1.,2.,1.]) # xm = xm.copy() xm /= ym assert_equal(xm._mask, [1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1]) assert_equal(z._data, [1., 1., 1., -1., -pi / 2., 4., 5., 1., 1., 1., 2., 3.]) #assert_equal(xm._data, [1/5.,1.,1./3.,-1.,-pi/2.,-1.,5.,1.,1.,1.,2.,1.]) def test_datafriendly_add(self): "Test keeping data w/ (inplace) addition" x = array([1, 2, 3], mask=[0, 0, 1]) # Test add w/ scalar xx = x + 1 assert_equal(xx.data, [2, 3, 3]) assert_equal(xx.mask, [0, 0, 1]) # Test iadd w/ scalar x += 1 assert_equal(x.data, [2, 3, 3]) assert_equal(x.mask, [0, 0, 1]) # Test add w/ array x = array([1, 2, 3], mask=[0, 0, 1]) xx = x + array([1, 2, 3], mask=[1, 0, 0]) assert_equal(xx.data, [1, 4, 3]) assert_equal(xx.mask, [1, 0, 1]) # Test iadd w/ array x = array([1, 2, 3], mask=[0, 0, 1]) x += array([1, 2, 3], mask=[1, 0, 0]) assert_equal(x.data, [1, 4, 3]) assert_equal(x.mask, [1, 0, 1]) def test_datafriendly_sub(self): "Test keeping data w/ (inplace) subtraction" # Test sub w/ scalar x = array([1, 2, 3], mask=[0, 0, 1]) xx = x - 1 assert_equal(xx.data, [0, 1, 3]) assert_equal(xx.mask, [0, 0, 1]) # Test isub w/ scalar x = array([1, 2, 3], mask=[0, 0, 1]) x -= 1 assert_equal(x.data, [0, 1, 3]) assert_equal(x.mask, [0, 0, 1]) # Test sub w/ array x = array([1, 2, 3], mask=[0, 0, 1]) xx = x - array([1, 2, 3], mask=[1, 0, 0]) assert_equal(xx.data, [1, 0, 3]) assert_equal(xx.mask, [1, 0, 1]) # Test isub w/ array x = array([1, 2, 3], mask=[0, 0, 1]) x -= array([1, 2, 3], mask=[1, 0, 0]) assert_equal(x.data, [1, 0, 3]) assert_equal(x.mask, [1, 0, 1]) def test_datafriendly_mul(self): "Test keeping data w/ (inplace) multiplication" # Test mul w/ scalar x = array([1, 2, 3], mask=[0, 0, 1]) xx = x * 2 assert_equal(xx.data, [2, 4, 3]) assert_equal(xx.mask, [0, 0, 1]) # Test imul w/ scalar x = array([1, 2, 3], mask=[0, 0, 1]) x *= 2 assert_equal(x.data, [2, 4, 3]) assert_equal(x.mask, [0, 0, 1]) # Test mul w/ array x = array([1, 2, 3], mask=[0, 0, 1]) xx = x * array([10, 20, 30], mask=[1, 0, 0]) assert_equal(xx.data, [1, 40, 3]) assert_equal(xx.mask, [1, 0, 1]) # Test imul w/ array x = array([1, 2, 3], mask=[0, 0, 1]) x *= array([10, 20, 30], mask=[1, 0, 0]) assert_equal(x.data, [1, 40, 3]) assert_equal(x.mask, [1, 0, 1]) def test_datafriendly_div(self): "Test keeping data w/ (inplace) division" # Test div on scalar x = array([1, 2, 3], mask=[0, 0, 1]) xx = x / 2. assert_equal(xx.data, [1 / 2., 2 / 2., 3]) assert_equal(xx.mask, [0, 0, 1]) # Test idiv on scalar x = array([1., 2., 3.], mask=[0, 0, 1]) x /= 2. assert_equal(x.data, [1 / 2., 2 / 2., 3]) assert_equal(x.mask, [0, 0, 1]) # Test div on array x = array([1., 2., 3.], mask=[0, 0, 1]) xx = x / array([10., 20., 30.], mask=[1, 0, 0]) assert_equal(xx.data, [1., 2. / 20., 3.]) assert_equal(xx.mask, [1, 0, 1]) # Test idiv on array x = array([1., 2., 3.], mask=[0, 0, 1]) x /= array([10., 20., 30.], mask=[1, 0, 0]) assert_equal(x.data, [1., 2 / 20., 3.]) assert_equal(x.mask, [1, 0, 1]) def test_datafriendly_pow(self): "Test keeping data w/ (inplace) power" # Test pow on scalar x = array([1., 2., 3.], mask=[0, 0, 1]) xx = x ** 2.5 assert_equal(xx.data, [1., 2. ** 2.5, 3.]) assert_equal(xx.mask, [0, 0, 1]) # Test ipow on scalar x **= 2.5 assert_equal(x.data, [1., 2. ** 2.5, 3]) assert_equal(x.mask, [0, 0, 1]) def test_datafriendly_add_arrays(self): a = array([[1, 1], [3, 3]]) b = array([1, 1], mask=[0, 0]) a += b assert_equal(a, [[2, 2], [4, 4]]) if a.mask is not nomask: assert_equal(a.mask, [[0, 0], [0, 0]]) # a = array([[1, 1], [3, 3]]) b = array([1, 1], mask=[0, 1]) a += b assert_equal(a, [[2, 2], [4, 4]]) assert_equal(a.mask, [[0, 1], [0, 1]]) def test_datafriendly_sub_arrays(self): a = array([[1, 1], [3, 3]]) b = array([1, 1], mask=[0, 0]) a -= b assert_equal(a, [[0, 0], [2, 2]]) if a.mask is not nomask: assert_equal(a.mask, [[0, 0], [0, 0]]) # a = array([[1, 1], [3, 3]]) b = array([1, 1], mask=[0, 1]) a -= b assert_equal(a, [[0, 0], [2, 2]]) assert_equal(a.mask, [[0, 1], [0, 1]]) def test_datafriendly_mul_arrays(self): a = array([[1, 1], [3, 3]]) b = array([1, 1], mask=[0, 0]) a *= b assert_equal(a, [[1, 1], [3, 3]]) if a.mask is not nomask: assert_equal(a.mask, [[0, 0], [0, 0]]) # a = array([[1, 1], [3, 3]]) b = array([1, 1], mask=[0, 1]) a *= b assert_equal(a, [[1, 1], [3, 3]]) assert_equal(a.mask, [[0, 1], [0, 1]]) #------------------------------------------------------------------------------ class TestMaskedArrayMethods(TestCase): "Test class for miscellaneous MaskedArrays methods." def setUp(self): "Base data definition." x = np.array([ 8.375, 7.545, 8.828, 8.5, 1.757, 5.928, 8.43, 7.78, 9.865, 5.878, 8.979, 4.732, 3.012, 6.022, 5.095, 3.116, 5.238, 3.957, 6.04, 9.63, 7.712, 3.382, 4.489, 6.479, 7.189, 9.645, 5.395, 4.961, 9.894, 2.893, 7.357, 9.828, 6.272, 3.758, 6.693, 0.993]) X = x.reshape(6, 6) XX = x.reshape(3, 2, 2, 3) m = np.array([0, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0]) mx = array(data=x, mask=m) mX = array(data=X, mask=m.reshape(X.shape)) mXX = array(data=XX, mask=m.reshape(XX.shape)) m2 = np.array([1, 1, 0, 1, 0, 0, 1, 1, 1, 1, 0, 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 1]) m2x = array(data=x, mask=m2) m2X = array(data=X, mask=m2.reshape(X.shape)) m2XX = array(data=XX, mask=m2.reshape(XX.shape)) self.d = (x, X, XX, m, mx, mX, mXX, m2x, m2X, m2XX) def test_generic_methods(self): "Tests some MaskedArray methods." a = array([1, 3, 2]) b = array([1, 3, 2], mask=[1, 0, 1]) assert_equal(a.any(), a._data.any()) assert_equal(a.all(), a._data.all()) assert_equal(a.argmax(), a._data.argmax()) assert_equal(a.argmin(), a._data.argmin()) assert_equal(a.choose(0, 1, 2, 3, 4), a._data.choose(0, 1, 2, 3, 4)) assert_equal(a.compress([1, 0, 1]), a._data.compress([1, 0, 1])) assert_equal(a.conj(), a._data.conj()) assert_equal(a.conjugate(), a._data.conjugate()) # m = array([[1, 2], [3, 4]]) assert_equal(m.diagonal(), m._data.diagonal()) assert_equal(a.sum(), a._data.sum()) assert_equal(a.take([1, 2]), a._data.take([1, 2])) assert_equal(m.transpose(), m._data.transpose()) def test_allclose(self): "Tests allclose on arrays" a = np.random.rand(10) b = a + np.random.rand(10) * 1e-8 self.assertTrue(allclose(a, b)) # Test allclose w/ infs a[0] = np.inf self.assertTrue(not allclose(a, b)) b[0] = np.inf self.assertTrue(allclose(a, b)) # Test all close w/ masked a = masked_array(a) a[-1] = masked self.assertTrue(allclose(a, b, masked_equal=True)) self.assertTrue(not allclose(a, b, masked_equal=False)) # Test comparison w/ scalar a *= 1e-8 a[0] = 0 self.assertTrue(allclose(a, 0, masked_equal=True)) def test_allany(self): """Checks the any/all methods/functions.""" x = np.array([[ 0.13, 0.26, 0.90], [ 0.28, 0.33, 0.63], [ 0.31, 0.87, 0.70]]) m = np.array([[ True, False, False], [False, False, False], [True, True, False]], dtype=np.bool_) mx = masked_array(x, mask=m) xbig = np.array([[False, False, True], [False, False, True], [False, True, True]], dtype=np.bool_) mxbig = (mx > 0.5) mxsmall = (mx < 0.5) # assert_((mxbig.all() == False)) assert_((mxbig.any() == True)) assert_equal(mxbig.all(0), [False, False, True]) assert_equal(mxbig.all(1), [False, False, True]) assert_equal(mxbig.any(0), [False, False, True]) assert_equal(mxbig.any(1), [True, True, True]) # assert_((mxsmall.all() == False)) assert_((mxsmall.any() == True)) assert_equal(mxsmall.all(0), [True, True, False]) assert_equal(mxsmall.all(1), [False, False, False]) assert_equal(mxsmall.any(0), [True, True, False]) assert_equal(mxsmall.any(1), [True, True, False]) def test_allany_onmatrices(self): x = np.array([[ 0.13, 0.26, 0.90], [ 0.28, 0.33, 0.63], [ 0.31, 0.87, 0.70]]) X = np.matrix(x) m = np.array([[ True, False, False], [False, False, False], [True, True, False]], dtype=np.bool_) mX = masked_array(X, mask=m) mXbig = (mX > 0.5) mXsmall = (mX < 0.5) # assert_((mXbig.all() == False)) assert_((mXbig.any() == True)) assert_equal(mXbig.all(0), np.matrix([False, False, True])) assert_equal(mXbig.all(1), np.matrix([False, False, True]).T) assert_equal(mXbig.any(0), np.matrix([False, False, True])) assert_equal(mXbig.any(1), np.matrix([ True, True, True]).T) # assert_((mXsmall.all() == False)) assert_((mXsmall.any() == True)) assert_equal(mXsmall.all(0), np.matrix([True, True, False])) assert_equal(mXsmall.all(1), np.matrix([False, False, False]).T) assert_equal(mXsmall.any(0), np.matrix([True, True, False])) assert_equal(mXsmall.any(1), np.matrix([True, True, False]).T) def test_allany_oddities(self): "Some fun with all and any" store = empty((), dtype=bool) full = array([1, 2, 3], mask=True) # self.assertTrue(full.all() is masked) full.all(out=store) self.assertTrue(store) self.assertTrue(store._mask, True) self.assertTrue(store is not masked) # store = empty((), dtype=bool) self.assertTrue(full.any() is masked) full.any(out=store) self.assertTrue(not store) self.assertTrue(store._mask, True) self.assertTrue(store is not masked) def test_argmax_argmin(self): "Tests argmin & argmax on MaskedArrays." (x, X, XX, m, mx, mX, mXX, m2x, m2X, m2XX) = self.d # assert_equal(mx.argmin(), 35) assert_equal(mX.argmin(), 35) assert_equal(m2x.argmin(), 4) assert_equal(m2X.argmin(), 4) assert_equal(mx.argmax(), 28) assert_equal(mX.argmax(), 28) assert_equal(m2x.argmax(), 31) assert_equal(m2X.argmax(), 31) # assert_equal(mX.argmin(0), [2, 2, 2, 5, 0, 5]) assert_equal(m2X.argmin(0), [2, 2, 4, 5, 0, 4]) assert_equal(mX.argmax(0), [0, 5, 0, 5, 4, 0]) assert_equal(m2X.argmax(0), [5, 5, 0, 5, 1, 0]) # assert_equal(mX.argmin(1), [4, 1, 0, 0, 5, 5, ]) assert_equal(m2X.argmin(1), [4, 4, 0, 0, 5, 3]) assert_equal(mX.argmax(1), [2, 4, 1, 1, 4, 1]) assert_equal(m2X.argmax(1), [2, 4, 1, 1, 1, 1]) def test_clip(self): "Tests clip on MaskedArrays." x = np.array([ 8.375, 7.545, 8.828, 8.5, 1.757, 5.928, 8.43, 7.78, 9.865, 5.878, 8.979, 4.732, 3.012, 6.022, 5.095, 3.116, 5.238, 3.957, 6.04, 9.63, 7.712, 3.382, 4.489, 6.479, 7.189, 9.645, 5.395, 4.961, 9.894, 2.893, 7.357, 9.828, 6.272, 3.758, 6.693, 0.993]) m = np.array([0, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0]) mx = array(x, mask=m) clipped = mx.clip(2, 8) assert_equal(clipped.mask, mx.mask) assert_equal(clipped._data, x.clip(2, 8)) assert_equal(clipped._data, mx._data.clip(2, 8)) def test_compress(self): "test compress" a = masked_array([1., 2., 3., 4., 5.], fill_value=9999) condition = (a > 1.5) & (a < 3.5) assert_equal(a.compress(condition), [2., 3.]) # a[[2, 3]] = masked b = a.compress(condition) assert_equal(b._data, [2., 3.]) assert_equal(b._mask, [0, 1]) assert_equal(b.fill_value, 9999) assert_equal(b, a[condition]) # condition = (a < 4.) b = a.compress(condition) assert_equal(b._data, [1., 2., 3.]) assert_equal(b._mask, [0, 0, 1]) assert_equal(b.fill_value, 9999) assert_equal(b, a[condition]) # a = masked_array([[10, 20, 30], [40, 50, 60]], mask=[[0, 0, 1], [1, 0, 0]]) b = a.compress(a.ravel() >= 22) assert_equal(b._data, [30, 40, 50, 60]) assert_equal(b._mask, [1, 1, 0, 0]) # x = np.array([3, 1, 2]) b = a.compress(x >= 2, axis=1) assert_equal(b._data, [[10, 30], [40, 60]]) assert_equal(b._mask, [[0, 1], [1, 0]]) def test_compressed(self): "Tests compressed" a = array([1, 2, 3, 4], mask=[0, 0, 0, 0]) b = a.compressed() assert_equal(b, a) a[0] = masked b = a.compressed() assert_equal(b, [2, 3, 4]) # a = array(np.matrix([1, 2, 3, 4]), mask=[0, 0, 0, 0]) b = a.compressed() assert_equal(b, a) self.assertTrue(isinstance(b, np.matrix)) a[0, 0] = masked b = a.compressed() assert_equal(b, [[2, 3, 4]]) def test_empty(self): "Tests empty/like" datatype = [('a', int), ('b', float), ('c', '|S8')] a = masked_array([(1, 1.1, '1.1'), (2, 2.2, '2.2'), (3, 3.3, '3.3')], dtype=datatype) assert_equal(len(a.fill_value.item()), len(datatype)) # b = empty_like(a) assert_equal(b.shape, a.shape) assert_equal(b.fill_value, a.fill_value) # b = empty(len(a), dtype=datatype) assert_equal(b.shape, a.shape) assert_equal(b.fill_value, a.fill_value) def test_put(self): "Tests put." d = arange(5) n = [0, 0, 0, 1, 1] m = make_mask(n) x = array(d, mask=m) self.assertTrue(x[3] is masked) self.assertTrue(x[4] is masked) x[[1, 4]] = [10, 40] #self.assertTrue(x.mask is not m) self.assertTrue(x[3] is masked) self.assertTrue(x[4] is not masked) assert_equal(x, [0, 10, 2, -1, 40]) # x = masked_array(arange(10), mask=[1, 0, 0, 0, 0] * 2) i = [0, 2, 4, 6] x.put(i, [6, 4, 2, 0]) assert_equal(x, asarray([6, 1, 4, 3, 2, 5, 0, 7, 8, 9, ])) assert_equal(x.mask, [0, 0, 0, 0, 0, 1, 0, 0, 0, 0]) x.put(i, masked_array([0, 2, 4, 6], [1, 0, 1, 0])) assert_array_equal(x, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ]) assert_equal(x.mask, [1, 0, 0, 0, 1, 1, 0, 0, 0, 0]) # x = masked_array(arange(10), mask=[1, 0, 0, 0, 0] * 2) put(x, i, [6, 4, 2, 0]) assert_equal(x, asarray([6, 1, 4, 3, 2, 5, 0, 7, 8, 9, ])) assert_equal(x.mask, [0, 0, 0, 0, 0, 1, 0, 0, 0, 0]) put(x, i, masked_array([0, 2, 4, 6], [1, 0, 1, 0])) assert_array_equal(x, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ]) assert_equal(x.mask, [1, 0, 0, 0, 1, 1, 0, 0, 0, 0]) def test_put_hardmask(self): "Tests put on hardmask" d = arange(5) n = [0, 0, 0, 1, 1] m = make_mask(n) xh = array(d + 1, mask=m, hard_mask=True, copy=True) xh.put([4, 2, 0, 1, 3], [1, 2, 3, 4, 5]) assert_equal(xh._data, [3, 4, 2, 4, 5]) def test_putmask(self): x = arange(6) + 1 mx = array(x, mask=[0, 0, 0, 1, 1, 1]) mask = [0, 0, 1, 0, 0, 1] # w/o mask, w/o masked values xx = x.copy() putmask(xx, mask, 99) assert_equal(xx, [1, 2, 99, 4, 5, 99]) # w/ mask, w/o masked values mxx = mx.copy() putmask(mxx, mask, 99) assert_equal(mxx._data, [1, 2, 99, 4, 5, 99]) assert_equal(mxx._mask, [0, 0, 0, 1, 1, 0]) # w/o mask, w/ masked values values = array([10, 20, 30, 40, 50, 60], mask=[1, 1, 1, 0, 0, 0]) xx = x.copy() putmask(xx, mask, values) assert_equal(xx._data, [1, 2, 30, 4, 5, 60]) assert_equal(xx._mask, [0, 0, 1, 0, 0, 0]) # w/ mask, w/ masked values mxx = mx.copy() putmask(mxx, mask, values) assert_equal(mxx._data, [1, 2, 30, 4, 5, 60]) assert_equal(mxx._mask, [0, 0, 1, 1, 1, 0]) # w/ mask, w/ masked values + hardmask mxx = mx.copy() mxx.harden_mask() putmask(mxx, mask, values) assert_equal(mxx, [1, 2, 30, 4, 5, 60]) def test_ravel(self): "Tests ravel" a = array([[1, 2, 3, 4, 5]], mask=[[0, 1, 0, 0, 0]]) aravel = a.ravel() assert_equal(a._mask.shape, a.shape) a = array([0, 0], mask=[1, 1]) aravel = a.ravel() assert_equal(a._mask.shape, a.shape) a = array(np.matrix([1, 2, 3, 4, 5]), mask=[[0, 1, 0, 0, 0]]) aravel = a.ravel() assert_equal(a.shape, (1, 5)) assert_equal(a._mask.shape, a.shape) # Checks that small_mask is preserved a = array([1, 2, 3, 4], mask=[0, 0, 0, 0], shrink=False) assert_equal(a.ravel()._mask, [0, 0, 0, 0]) # Test that the fill_value is preserved a.fill_value = -99 a.shape = (2, 2) ar = a.ravel() assert_equal(ar._mask, [0, 0, 0, 0]) assert_equal(ar._data, [1, 2, 3, 4]) assert_equal(ar.fill_value, -99) def test_reshape(self): "Tests reshape" x = arange(4) x[0] = masked y = x.reshape(2, 2) assert_equal(y.shape, (2, 2,)) assert_equal(y._mask.shape, (2, 2,)) assert_equal(x.shape, (4,)) assert_equal(x._mask.shape, (4,)) def test_sort(self): "Test sort" x = array([1, 4, 2, 3], mask=[0, 1, 0, 0], dtype=np.uint8) # sortedx = sort(x) assert_equal(sortedx._data, [1, 2, 3, 4]) assert_equal(sortedx._mask, [0, 0, 0, 1]) # sortedx = sort(x, endwith=False) assert_equal(sortedx._data, [4, 1, 2, 3]) assert_equal(sortedx._mask, [1, 0, 0, 0]) # x.sort() assert_equal(x._data, [1, 2, 3, 4]) assert_equal(x._mask, [0, 0, 0, 1]) # x = array([1, 4, 2, 3], mask=[0, 1, 0, 0], dtype=np.uint8) x.sort(endwith=False) assert_equal(x._data, [4, 1, 2, 3]) assert_equal(x._mask, [1, 0, 0, 0]) # x = [1, 4, 2, 3] sortedx = sort(x) self.assertTrue(not isinstance(sorted, MaskedArray)) # x = array([0, 1, -1, -2, 2], mask=nomask, dtype=np.int8) sortedx = sort(x, endwith=False) assert_equal(sortedx._data, [-2, -1, 0, 1, 2]) x = array([0, 1, -1, -2, 2], mask=[0, 1, 0, 0, 1], dtype=np.int8) sortedx = sort(x, endwith=False) assert_equal(sortedx._data, [1, 2, -2, -1, 0]) assert_equal(sortedx._mask, [1, 1, 0, 0, 0]) def test_sort_2d(self): "Check sort of 2D array." # 2D array w/o mask a = masked_array([[8, 4, 1], [2, 0, 9]]) a.sort(0) assert_equal(a, [[2, 0, 1], [8, 4, 9]]) a = masked_array([[8, 4, 1], [2, 0, 9]]) a.sort(1) assert_equal(a, [[1, 4, 8], [0, 2, 9]]) # 2D array w/mask a = masked_array([[8, 4, 1], [2, 0, 9]], mask=[[1, 0, 0], [0, 0, 1]]) a.sort(0) assert_equal(a, [[2, 0, 1], [8, 4, 9]]) assert_equal(a._mask, [[0, 0, 0], [1, 0, 1]]) a = masked_array([[8, 4, 1], [2, 0, 9]], mask=[[1, 0, 0], [0, 0, 1]]) a.sort(1) assert_equal(a, [[1, 4, 8], [0, 2, 9]]) assert_equal(a._mask, [[0, 0, 1], [0, 0, 1]]) # 3D a = masked_array([[[7, 8, 9], [4, 5, 6], [1, 2, 3]], [[1, 2, 3], [7, 8, 9], [4, 5, 6]], [[7, 8, 9], [1, 2, 3], [4, 5, 6]], [[4, 5, 6], [1, 2, 3], [7, 8, 9]]]) a[a % 4 == 0] = masked am = a.copy() an = a.filled(99) am.sort(0) an.sort(0) assert_equal(am, an) am = a.copy() an = a.filled(99) am.sort(1) an.sort(1) assert_equal(am, an) am = a.copy() an = a.filled(99) am.sort(2) an.sort(2) assert_equal(am, an) def test_sort_flexible(self): "Test sort on flexible dtype." a = array([(3, 3), (3, 2), (2, 2), (2, 1), (1, 0), (1, 1), (1, 2)], mask=[(0, 0), (0, 1), (0, 0), (0, 0), (1, 0), (0, 0), (0, 0)], dtype=[('A', int), ('B', int)]) # test = sort(a) b = array([(1, 1), (1, 2), (2, 1), (2, 2), (3, 3), (3, 2), (1, 0)], mask=[(0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 1), (1, 0)], dtype=[('A', int), ('B', int)]) assert_equal(test, b) assert_equal(test.mask, b.mask) # test = sort(a, endwith=False) b = array([(1, 0), (1, 1), (1, 2), (2, 1), (2, 2), (3, 2), (3, 3), ], mask=[(1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 1), (0, 0), ], dtype=[('A', int), ('B', int)]) assert_equal(test, b) assert_equal(test.mask, b.mask) def test_argsort(self): "Test argsort" a = array([1, 5, 2, 4, 3], mask=[1, 0, 0, 1, 0]) assert_equal(np.argsort(a), argsort(a)) def test_squeeze(self): "Check squeeze" data = masked_array([[1, 2, 3]]) assert_equal(data.squeeze(), [1, 2, 3]) data = masked_array([[1, 2, 3]], mask=[[1, 1, 1]]) assert_equal(data.squeeze(), [1, 2, 3]) assert_equal(data.squeeze()._mask, [1, 1, 1]) data = masked_array([[1]], mask=True) self.assertTrue(data.squeeze() is masked) def test_swapaxes(self): "Tests swapaxes on MaskedArrays." x = np.array([ 8.375, 7.545, 8.828, 8.5, 1.757, 5.928, 8.43, 7.78, 9.865, 5.878, 8.979, 4.732, 3.012, 6.022, 5.095, 3.116, 5.238, 3.957, 6.04, 9.63, 7.712, 3.382, 4.489, 6.479, 7.189, 9.645, 5.395, 4.961, 9.894, 2.893, 7.357, 9.828, 6.272, 3.758, 6.693, 0.993]) m = np.array([0, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0]) mX = array(x, mask=m).reshape(6, 6) mXX = mX.reshape(3, 2, 2, 3) # mXswapped = mX.swapaxes(0, 1) assert_equal(mXswapped[-1], mX[:, -1]) mXXswapped = mXX.swapaxes(0, 2) assert_equal(mXXswapped.shape, (2, 2, 3, 3)) def test_take(self): "Tests take" x = masked_array([10, 20, 30, 40], [0, 1, 0, 1]) assert_equal(x.take([0, 0, 3]), masked_array([10, 10, 40], [0, 0, 1])) assert_equal(x.take([0, 0, 3]), x[[0, 0, 3]]) assert_equal(x.take([[0, 1], [0, 1]]), masked_array([[10, 20], [10, 20]], [[0, 1], [0, 1]])) # x = array([[10, 20, 30], [40, 50, 60]], mask=[[0, 0, 1], [1, 0, 0, ]]) assert_equal(x.take([0, 2], axis=1), array([[10, 30], [40, 60]], mask=[[0, 1], [1, 0]])) assert_equal(take(x, [0, 2], axis=1), array([[10, 30], [40, 60]], mask=[[0, 1], [1, 0]])) def test_take_masked_indices(self): "Test take w/ masked indices" a = np.array((40, 18, 37, 9, 22)) indices = np.arange(3)[None,:] + np.arange(5)[:, None] mindices = array(indices, mask=(indices >= len(a))) # No mask test = take(a, mindices, mode='clip') ctrl = array([[40, 18, 37], [18, 37, 9], [37, 9, 22], [ 9, 22, 22], [22, 22, 22]]) assert_equal(test, ctrl) # Masked indices test = take(a, mindices) ctrl = array([[40, 18, 37], [18, 37, 9], [37, 9, 22], [ 9, 22, 40], [22, 40, 40]]) ctrl[3, 2] = ctrl[4, 1] = ctrl[4, 2] = masked assert_equal(test, ctrl) assert_equal(test.mask, ctrl.mask) # Masked input + masked indices a = array((40, 18, 37, 9, 22), mask=(0, 1, 0, 0, 0)) test = take(a, mindices) ctrl[0, 1] = ctrl[1, 0] = masked assert_equal(test, ctrl) assert_equal(test.mask, ctrl.mask) def test_tolist(self): "Tests to list" # ... on 1D x = array(np.arange(12)) x[[1, -2]] = masked xlist = x.tolist() self.assertTrue(xlist[1] is None) self.assertTrue(xlist[-2] is None) # ... on 2D x.shape = (3, 4) xlist = x.tolist() ctrl = [[0, None, 2, 3], [4, 5, 6, 7], [8, 9, None, 11]] assert_equal(xlist[0], [0, None, 2, 3]) assert_equal(xlist[1], [4, 5, 6, 7]) assert_equal(xlist[2], [8, 9, None, 11]) assert_equal(xlist, ctrl) # ... on structured array w/ masked records x = array(list(zip([1, 2, 3], [1.1, 2.2, 3.3], ['one', 'two', 'thr'])), dtype=[('a', int), ('b', float), ('c', '|S8')]) x[-1] = masked assert_equal(x.tolist(), [(1, 1.1, asbytes('one')), (2, 2.2, asbytes('two')), (None, None, None)]) # ... on structured array w/ masked fields a = array([(1, 2,), (3, 4)], mask=[(0, 1), (0, 0)], dtype=[('a', int), ('b', int)]) test = a.tolist() assert_equal(test, [[1, None], [3, 4]]) # ... on mvoid a = a[0] test = a.tolist() assert_equal(test, [1, None]) def test_tolist_specialcase(self): "Test mvoid.tolist: make sure we return a standard Python object" a = array([(0, 1), (2, 3)], dtype=[('a', int), ('b', int)]) # w/o mask: each entry is a np.void whose elements are standard Python for entry in a: for item in entry.tolist(): assert_(not isinstance(item, np.generic)) # w/ mask: each entry is a ma.void whose elements should be standard Python a.mask[0] = (0, 1) for entry in a: for item in entry.tolist(): assert_(not isinstance(item, np.generic)) def test_toflex(self): "Test the conversion to records" data = arange(10) record = data.toflex() assert_equal(record['_data'], data._data) assert_equal(record['_mask'], data._mask) # data[[0, 1, 2, -1]] = masked record = data.toflex() assert_equal(record['_data'], data._data) assert_equal(record['_mask'], data._mask) # ndtype = [('i', int), ('s', '|S3'), ('f', float)] data = array([(i, s, f) for (i, s, f) in zip(np.arange(10), 'ABCDEFGHIJKLM', np.random.rand(10))], dtype=ndtype) data[[0, 1, 2, -1]] = masked record = data.toflex() assert_equal(record['_data'], data._data) assert_equal(record['_mask'], data._mask) # ndtype = np.dtype("int, (2,3)float, float") data = array([(i, f, ff) for (i, f, ff) in zip(np.arange(10), np.random.rand(10), np.random.rand(10))], dtype=ndtype) data[[0, 1, 2, -1]] = masked record = data.toflex() assert_equal_records(record['_data'], data._data) assert_equal_records(record['_mask'], data._mask) def test_fromflex(self): "Test the reconstruction of a masked_array from a record" a = array([1, 2, 3]) test = fromflex(a.toflex()) assert_equal(test, a) assert_equal(test.mask, a.mask) # a = array([1, 2, 3], mask=[0, 0, 1]) test = fromflex(a.toflex()) assert_equal(test, a) assert_equal(test.mask, a.mask) # a = array([(1, 1.), (2, 2.), (3, 3.)], mask=[(1, 0), (0, 0), (0, 1)], dtype=[('A', int), ('B', float)]) test = fromflex(a.toflex()) assert_equal(test, a) assert_equal(test.data, a.data) def test_arraymethod(self): "Test a _arraymethod w/ n argument" marray = masked_array([[1, 2, 3, 4, 5]], mask=[0, 0, 1, 0, 0]) control = masked_array([[1], [2], [3], [4], [5]], mask=[0, 0, 1, 0, 0]) assert_equal(marray.T, control) assert_equal(marray.transpose(), control) # assert_equal(MaskedArray.cumsum(marray.T, 0), control.cumsum(0)) #------------------------------------------------------------------------------ class TestMaskedArrayMathMethods(TestCase): def setUp(self): "Base data definition." x = np.array([ 8.375, 7.545, 8.828, 8.5, 1.757, 5.928, 8.43, 7.78, 9.865, 5.878, 8.979, 4.732, 3.012, 6.022, 5.095, 3.116, 5.238, 3.957, 6.04, 9.63, 7.712, 3.382, 4.489, 6.479, 7.189, 9.645, 5.395, 4.961, 9.894, 2.893, 7.357, 9.828, 6.272, 3.758, 6.693, 0.993]) X = x.reshape(6, 6) XX = x.reshape(3, 2, 2, 3) m = np.array([0, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0]) mx = array(data=x, mask=m) mX = array(data=X, mask=m.reshape(X.shape)) mXX = array(data=XX, mask=m.reshape(XX.shape)) m2 = np.array([1, 1, 0, 1, 0, 0, 1, 1, 1, 1, 0, 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 1]) m2x = array(data=x, mask=m2) m2X = array(data=X, mask=m2.reshape(X.shape)) m2XX = array(data=XX, mask=m2.reshape(XX.shape)) self.d = (x, X, XX, m, mx, mX, mXX, m2x, m2X, m2XX) def test_cumsumprod(self): "Tests cumsum & cumprod on MaskedArrays." (x, X, XX, m, mx, mX, mXX, m2x, m2X, m2XX) = self.d mXcp = mX.cumsum(0) assert_equal(mXcp._data, mX.filled(0).cumsum(0)) mXcp = mX.cumsum(1) assert_equal(mXcp._data, mX.filled(0).cumsum(1)) # mXcp = mX.cumprod(0) assert_equal(mXcp._data, mX.filled(1).cumprod(0)) mXcp = mX.cumprod(1) assert_equal(mXcp._data, mX.filled(1).cumprod(1)) def test_cumsumprod_with_output(self): "Tests cumsum/cumprod w/ output" xm = array(np.random.uniform(0, 10, 12)).reshape(3, 4) xm[:, 0] = xm[0] = xm[-1, -1] = masked # for funcname in ('cumsum', 'cumprod'): npfunc = getattr(np, funcname) xmmeth = getattr(xm, funcname) # A ndarray as explicit input output = np.empty((3, 4), dtype=float) output.fill(-9999) result = npfunc(xm, axis=0, out=output) # ... the result should be the given output self.assertTrue(result is output) assert_equal(result, xmmeth(axis=0, out=output)) # output = empty((3, 4), dtype=int) result = xmmeth(axis=0, out=output) self.assertTrue(result is output) def test_ptp(self): "Tests ptp on MaskedArrays." (x, X, XX, m, mx, mX, mXX, m2x, m2X, m2XX) = self.d (n, m) = X.shape assert_equal(mx.ptp(), mx.compressed().ptp()) rows = np.zeros(n, np.float) cols = np.zeros(m, np.float) for k in range(m): cols[k] = mX[:, k].compressed().ptp() for k in range(n): rows[k] = mX[k].compressed().ptp() assert_equal(mX.ptp(0), cols) assert_equal(mX.ptp(1), rows) def test_sum_object(self): "Test sum on object dtype" a = masked_array([1, 2, 3], mask=[1, 0, 0], dtype=np.object) assert_equal(a.sum(), 5) a = masked_array([[1, 2, 3], [4, 5, 6]], dtype=object) assert_equal(a.sum(axis=0), [5, 7, 9]) def test_prod_object(self): "Test prod on object dtype" a = masked_array([1, 2, 3], mask=[1, 0, 0], dtype=np.object) assert_equal(a.prod(), 2 * 3) a = masked_array([[1, 2, 3], [4, 5, 6]], dtype=object) assert_equal(a.prod(axis=0), [4, 10, 18]) def test_meananom_object(self): "Test mean/anom on object dtype" a = masked_array([1, 2, 3], dtype=np.object) assert_equal(a.mean(), 2) assert_equal(a.anom(), [-1, 0, 1]) def test_trace(self): "Tests trace on MaskedArrays." (x, X, XX, m, mx, mX, mXX, m2x, m2X, m2XX) = self.d mXdiag = mX.diagonal() assert_equal(mX.trace(), mX.diagonal().compressed().sum()) assert_almost_equal(mX.trace(), X.trace() - sum(mXdiag.mask * X.diagonal(), axis=0)) def test_varstd(self): "Tests var & std on MaskedArrays." (x, X, XX, m, mx, mX, mXX, m2x, m2X, m2XX) = self.d assert_almost_equal(mX.var(axis=None), mX.compressed().var()) assert_almost_equal(mX.std(axis=None), mX.compressed().std()) assert_almost_equal(mX.std(axis=None, ddof=1), mX.compressed().std(ddof=1)) assert_almost_equal(mX.var(axis=None, ddof=1), mX.compressed().var(ddof=1)) assert_equal(mXX.var(axis=3).shape, XX.var(axis=3).shape) assert_equal(mX.var().shape, X.var().shape) (mXvar0, mXvar1) = (mX.var(axis=0), mX.var(axis=1)) assert_almost_equal(mX.var(axis=None, ddof=2), mX.compressed().var(ddof=2)) assert_almost_equal(mX.std(axis=None, ddof=2), mX.compressed().std(ddof=2)) for k in range(6): assert_almost_equal(mXvar1[k], mX[k].compressed().var()) assert_almost_equal(mXvar0[k], mX[:, k].compressed().var()) assert_almost_equal(np.sqrt(mXvar0[k]), mX[:, k].compressed().std()) def test_varstd_specialcases(self): "Test a special case for var" nout = np.array(-1, dtype=float) mout = array(-1, dtype=float) # x = array(arange(10), mask=True) for methodname in ('var', 'std'): method = getattr(x, methodname) self.assertTrue(method() is masked) self.assertTrue(method(0) is masked) self.assertTrue(method(-1) is masked) # Using a masked array as explicit output with warnings.catch_warnings(): warnings.simplefilter('ignore') _ = method(out=mout) self.assertTrue(mout is not masked) assert_equal(mout.mask, True) # Using a ndarray as explicit output with warnings.catch_warnings(): warnings.simplefilter('ignore') _ = method(out=nout) self.assertTrue(np.isnan(nout)) # x = array(arange(10), mask=True) x[-1] = 9 for methodname in ('var', 'std'): method = getattr(x, methodname) self.assertTrue(method(ddof=1) is masked) self.assertTrue(method(0, ddof=1) is masked) self.assertTrue(method(-1, ddof=1) is masked) # Using a masked array as explicit output _ = method(out=mout, ddof=1) self.assertTrue(mout is not masked) assert_equal(mout.mask, True) # Using a ndarray as explicit output _ = method(out=nout, ddof=1) self.assertTrue(np.isnan(nout)) def test_varstd_ddof(self): a = array([[1, 1, 0], [1, 1, 0]], mask=[[0, 0, 1], [0, 0, 1]]) test = a.std(axis=0, ddof=0) assert_equal(test.filled(0), [0, 0, 0]) assert_equal(test.mask, [0, 0, 1]) test = a.std(axis=0, ddof=1) assert_equal(test.filled(0), [0, 0, 0]) assert_equal(test.mask, [0, 0, 1]) test = a.std(axis=0, ddof=2) assert_equal(test.filled(0), [0, 0, 0]) assert_equal(test.mask, [1, 1, 1]) def test_diag(self): "Test diag" x = arange(9).reshape((3, 3)) x[1, 1] = masked out = np.diag(x) assert_equal(out, [0, 4, 8]) out = diag(x) assert_equal(out, [0, 4, 8]) assert_equal(out.mask, [0, 1, 0]) out = diag(out) control = array([[0, 0, 0], [0, 4, 0], [0, 0, 8]], mask=[[0, 0, 0], [0, 1, 0], [0, 0, 0]]) assert_equal(out, control) def test_axis_methods_nomask(self): "Test the combination nomask & methods w/ axis" a = array([[1, 2, 3], [4, 5, 6]]) # assert_equal(a.sum(0), [5, 7, 9]) assert_equal(a.sum(-1), [6, 15]) assert_equal(a.sum(1), [6, 15]) # assert_equal(a.prod(0), [4, 10, 18]) assert_equal(a.prod(-1), [6, 120]) assert_equal(a.prod(1), [6, 120]) # assert_equal(a.min(0), [1, 2, 3]) assert_equal(a.min(-1), [1, 4]) assert_equal(a.min(1), [1, 4]) # assert_equal(a.max(0), [4, 5, 6]) assert_equal(a.max(-1), [3, 6]) assert_equal(a.max(1), [3, 6]) #------------------------------------------------------------------------------ class TestMaskedArrayMathMethodsComplex(TestCase): "Test class for miscellaneous MaskedArrays methods." def setUp(self): "Base data definition." x = np.array([ 8.375j, 7.545j, 8.828j, 8.5j, 1.757j, 5.928, 8.43, 7.78, 9.865, 5.878, 8.979, 4.732, 3.012, 6.022, 5.095, 3.116, 5.238, 3.957, 6.04, 9.63, 7.712, 3.382, 4.489, 6.479j, 7.189j, 9.645, 5.395, 4.961, 9.894, 2.893, 7.357, 9.828, 6.272, 3.758, 6.693, 0.993j]) X = x.reshape(6, 6) XX = x.reshape(3, 2, 2, 3) m = np.array([0, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0]) mx = array(data=x, mask=m) mX = array(data=X, mask=m.reshape(X.shape)) mXX = array(data=XX, mask=m.reshape(XX.shape)) m2 = np.array([1, 1, 0, 1, 0, 0, 1, 1, 1, 1, 0, 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 1]) m2x = array(data=x, mask=m2) m2X = array(data=X, mask=m2.reshape(X.shape)) m2XX = array(data=XX, mask=m2.reshape(XX.shape)) self.d = (x, X, XX, m, mx, mX, mXX, m2x, m2X, m2XX) def test_varstd(self): "Tests var & std on MaskedArrays." (x, X, XX, m, mx, mX, mXX, m2x, m2X, m2XX) = self.d assert_almost_equal(mX.var(axis=None), mX.compressed().var()) assert_almost_equal(mX.std(axis=None), mX.compressed().std()) assert_equal(mXX.var(axis=3).shape, XX.var(axis=3).shape) assert_equal(mX.var().shape, X.var().shape) (mXvar0, mXvar1) = (mX.var(axis=0), mX.var(axis=1)) assert_almost_equal(mX.var(axis=None, ddof=2), mX.compressed().var(ddof=2)) assert_almost_equal(mX.std(axis=None, ddof=2), mX.compressed().std(ddof=2)) for k in range(6): assert_almost_equal(mXvar1[k], mX[k].compressed().var()) assert_almost_equal(mXvar0[k], mX[:, k].compressed().var()) assert_almost_equal(np.sqrt(mXvar0[k]), mX[:, k].compressed().std()) #------------------------------------------------------------------------------ class TestMaskedArrayFunctions(TestCase): "Test class for miscellaneous functions." def setUp(self): x = np.array([1., 1., 1., -2., pi / 2.0, 4., 5., -10., 10., 1., 2., 3.]) y = np.array([5., 0., 3., 2., -1., -4., 0., -10., 10., 1., 0., 3.]) a10 = 10. m1 = [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0] m2 = [0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1] xm = masked_array(x, mask=m1) ym = masked_array(y, mask=m2) z = np.array([-.5, 0., .5, .8]) zm = masked_array(z, mask=[0, 1, 0, 0]) xf = np.where(m1, 1e+20, x) xm.set_fill_value(1e+20) self.info = (xm, ym) def test_masked_where_bool(self): x = [1, 2] y = masked_where(False, x) assert_equal(y, [1, 2]) assert_equal(y[1], 2) def test_masked_equal_wlist(self): x = [1, 2, 3] mx = masked_equal(x, 3) assert_equal(mx, x) assert_equal(mx._mask, [0, 0, 1]) mx = masked_not_equal(x, 3) assert_equal(mx, x) assert_equal(mx._mask, [1, 1, 0]) def test_masked_equal_fill_value(self): x = [1, 2, 3] mx = masked_equal(x, 3) assert_equal(mx._mask, [0, 0, 1]) assert_equal(mx.fill_value, 3) def test_masked_where_condition(self): "Tests masking functions." x = array([1., 2., 3., 4., 5.]) x[2] = masked assert_equal(masked_where(greater(x, 2), x), masked_greater(x, 2)) assert_equal(masked_where(greater_equal(x, 2), x), masked_greater_equal(x, 2)) assert_equal(masked_where(less(x, 2), x), masked_less(x, 2)) assert_equal(masked_where(less_equal(x, 2), x), masked_less_equal(x, 2)) assert_equal(masked_where(not_equal(x, 2), x), masked_not_equal(x, 2)) assert_equal(masked_where(equal(x, 2), x), masked_equal(x, 2)) assert_equal(masked_where(not_equal(x, 2), x), masked_not_equal(x, 2)) assert_equal(masked_where([1, 1, 0, 0, 0], [1, 2, 3, 4, 5]), [99, 99, 3, 4, 5]) def test_masked_where_oddities(self): """Tests some generic features.""" atest = ones((10, 10, 10), dtype=float) btest = zeros(atest.shape, MaskType) ctest = masked_where(btest, atest) assert_equal(atest, ctest) def test_masked_where_shape_constraint(self): a = arange(10) try: test = masked_equal(1, a) except IndexError: pass else: raise AssertionError("Should have failed...") test = masked_equal(a, 1) assert_equal(test.mask, [0, 1, 0, 0, 0, 0, 0, 0, 0, 0]) def test_masked_otherfunctions(self): assert_equal(masked_inside(list(range(5)), 1, 3), [0, 199, 199, 199, 4]) assert_equal(masked_outside(list(range(5)), 1, 3), [199, 1, 2, 3, 199]) assert_equal(masked_inside(array(list(range(5)), mask=[1, 0, 0, 0, 0]), 1, 3).mask, [1, 1, 1, 1, 0]) assert_equal(masked_outside(array(list(range(5)), mask=[0, 1, 0, 0, 0]), 1, 3).mask, [1, 1, 0, 0, 1]) assert_equal(masked_equal(array(list(range(5)), mask=[1, 0, 0, 0, 0]), 2).mask, [1, 0, 1, 0, 0]) assert_equal(masked_not_equal(array([2, 2, 1, 2, 1], mask=[1, 0, 0, 0, 0]), 2).mask, [1, 0, 1, 0, 1]) def test_round(self): a = array([1.23456, 2.34567, 3.45678, 4.56789, 5.67890], mask=[0, 1, 0, 0, 0]) assert_equal(a.round(), [1., 2., 3., 5., 6.]) assert_equal(a.round(1), [1.2, 2.3, 3.5, 4.6, 5.7]) assert_equal(a.round(3), [1.235, 2.346, 3.457, 4.568, 5.679]) b = empty_like(a) a.round(out=b) assert_equal(b, [1., 2., 3., 5., 6.]) x = array([1., 2., 3., 4., 5.]) c = array([1, 1, 1, 0, 0]) x[2] = masked z = where(c, x, -x) assert_equal(z, [1., 2., 0., -4., -5]) c[0] = masked z = where(c, x, -x) assert_equal(z, [1., 2., 0., -4., -5]) assert_(z[0] is masked) assert_(z[1] is not masked) assert_(z[2] is masked) def test_round_with_output(self): "Testing round with an explicit output" xm = array(np.random.uniform(0, 10, 12)).reshape(3, 4) xm[:, 0] = xm[0] = xm[-1, -1] = masked # A ndarray as explicit input output = np.empty((3, 4), dtype=float) output.fill(-9999) result = np.round(xm, decimals=2, out=output) # ... the result should be the given output self.assertTrue(result is output) assert_equal(result, xm.round(decimals=2, out=output)) # output = empty((3, 4), dtype=float) result = xm.round(decimals=2, out=output) self.assertTrue(result is output) def test_identity(self): a = identity(5) self.assertTrue(isinstance(a, MaskedArray)) assert_equal(a, np.identity(5)) def test_power(self): x = -1.1 assert_almost_equal(power(x, 2.), 1.21) self.assertTrue(power(x, masked) is masked) x = array([-1.1, -1.1, 1.1, 1.1, 0.]) b = array([0.5, 2., 0.5, 2., -1.], mask=[0, 0, 0, 0, 1]) y = power(x, b) assert_almost_equal(y, [0, 1.21, 1.04880884817, 1.21, 0.]) assert_equal(y._mask, [1, 0, 0, 0, 1]) b.mask = nomask y = power(x, b) assert_equal(y._mask, [1, 0, 0, 0, 1]) z = x ** b assert_equal(z._mask, y._mask) assert_almost_equal(z, y) assert_almost_equal(z._data, y._data) x **= b assert_equal(x._mask, y._mask) assert_almost_equal(x, y) assert_almost_equal(x._data, y._data) def test_power_w_broadcasting(self): "Test power w/ broadcasting" a2 = np.array([[1., 2., 3.], [4., 5., 6.]]) a2m = array(a2, mask=[[1, 0, 0], [0, 0, 1]]) b1 = np.array([2, 4, 3]) b1m = array(b1, mask=[0, 1, 0]) b2 = np.array([b1, b1]) b2m = array(b2, mask=[[0, 1, 0], [0, 1, 0]]) # ctrl = array([[1 ** 2, 2 ** 4, 3 ** 3], [4 ** 2, 5 ** 4, 6 ** 3]], mask=[[1, 1, 0], [0, 1, 1]]) # No broadcasting, base & exp w/ mask test = a2m ** b2m assert_equal(test, ctrl) assert_equal(test.mask, ctrl.mask) # No broadcasting, base w/ mask, exp w/o mask test = a2m ** b2 assert_equal(test, ctrl) assert_equal(test.mask, a2m.mask) # No broadcasting, base w/o mask, exp w/ mask test = a2 ** b2m assert_equal(test, ctrl) assert_equal(test.mask, b2m.mask) # ctrl = array([[2 ** 2, 4 ** 4, 3 ** 3], [2 ** 2, 4 ** 4, 3 ** 3]], mask=[[0, 1, 0], [0, 1, 0]]) test = b1 ** b2m assert_equal(test, ctrl) assert_equal(test.mask, ctrl.mask) test = b2m ** b1 assert_equal(test, ctrl) assert_equal(test.mask, ctrl.mask) def test_where(self): "Test the where function" x = np.array([1., 1., 1., -2., pi / 2.0, 4., 5., -10., 10., 1., 2., 3.]) y = np.array([5., 0., 3., 2., -1., -4., 0., -10., 10., 1., 0., 3.]) a10 = 10. m1 = [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0] m2 = [0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1] xm = masked_array(x, mask=m1) ym = masked_array(y, mask=m2) z = np.array([-.5, 0., .5, .8]) zm = masked_array(z, mask=[0, 1, 0, 0]) xf = np.where(m1, 1e+20, x) xm.set_fill_value(1e+20) # d = where(xm > 2, xm, -9) assert_equal(d, [-9., -9., -9., -9., -9., 4., -9., -9., 10., -9., -9., 3.]) assert_equal(d._mask, xm._mask) d = where(xm > 2, -9, ym) assert_equal(d, [5., 0., 3., 2., -1., -9., -9., -10., -9., 1., 0., -9.]) assert_equal(d._mask, [1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0]) d = where(xm > 2, xm, masked) assert_equal(d, [-9., -9., -9., -9., -9., 4., -9., -9., 10., -9., -9., 3.]) tmp = xm._mask.copy() tmp[(xm <= 2).filled(True)] = True assert_equal(d._mask, tmp) # ixm = xm.astype(int) d = where(ixm > 2, ixm, masked) assert_equal(d, [-9, -9, -9, -9, -9, 4, -9, -9, 10, -9, -9, 3]) assert_equal(d.dtype, ixm.dtype) def test_where_with_masked_choice(self): x = arange(10) x[3] = masked c = x >= 8 # Set False to masked z = where(c, x, masked) assert_(z.dtype is x.dtype) assert_(z[3] is masked) assert_(z[4] is masked) assert_(z[7] is masked) assert_(z[8] is not masked) assert_(z[9] is not masked) assert_equal(x, z) # Set True to masked z = where(c, masked, x) assert_(z.dtype is x.dtype) assert_(z[3] is masked) assert_(z[4] is not masked) assert_(z[7] is not masked) assert_(z[8] is masked) assert_(z[9] is masked) def test_where_with_masked_condition(self): x = array([1., 2., 3., 4., 5.]) c = array([1, 1, 1, 0, 0]) x[2] = masked z = where(c, x, -x) assert_equal(z, [1., 2., 0., -4., -5]) c[0] = masked z = where(c, x, -x) assert_equal(z, [1., 2., 0., -4., -5]) assert_(z[0] is masked) assert_(z[1] is not masked) assert_(z[2] is masked) # x = arange(1, 6) x[-1] = masked y = arange(1, 6) * 10 y[2] = masked c = array([1, 1, 1, 0, 0], mask=[1, 0, 0, 0, 0]) cm = c.filled(1) z = where(c, x, y) zm = where(cm, x, y) assert_equal(z, zm) assert_(getmask(zm) is nomask) assert_equal(zm, [1, 2, 3, 40, 50]) z = where(c, masked, 1) assert_equal(z, [99, 99, 99, 1, 1]) z = where(c, 1, masked) assert_equal(z, [99, 1, 1, 99, 99]) def test_where_type(self): "Test the type conservation with where" x = np.arange(4, dtype=np.int32) y = np.arange(4, dtype=np.float32) * 2.2 test = where(x > 1.5, y, x).dtype control = np.find_common_type([np.int32, np.float32], []) assert_equal(test, control) def test_choose(self): "Test choose" choices = [[0, 1, 2, 3], [10, 11, 12, 13], [20, 21, 22, 23], [30, 31, 32, 33]] chosen = choose([2, 3, 1, 0], choices) assert_equal(chosen, array([20, 31, 12, 3])) chosen = choose([2, 4, 1, 0], choices, mode='clip') assert_equal(chosen, array([20, 31, 12, 3])) chosen = choose([2, 4, 1, 0], choices, mode='wrap') assert_equal(chosen, array([20, 1, 12, 3])) # Check with some masked indices indices_ = array([2, 4, 1, 0], mask=[1, 0, 0, 1]) chosen = choose(indices_, choices, mode='wrap') assert_equal(chosen, array([99, 1, 12, 99])) assert_equal(chosen.mask, [1, 0, 0, 1]) # Check with some masked choices choices = array(choices, mask=[[0, 0, 0, 1], [1, 1, 0, 1], [1, 0, 0, 0], [0, 0, 0, 0]]) indices_ = [2, 3, 1, 0] chosen = choose(indices_, choices, mode='wrap') assert_equal(chosen, array([20, 31, 12, 3])) assert_equal(chosen.mask, [1, 0, 0, 1]) def test_choose_with_out(self): "Test choose with an explicit out keyword" choices = [[0, 1, 2, 3], [10, 11, 12, 13], [20, 21, 22, 23], [30, 31, 32, 33]] store = empty(4, dtype=int) chosen = choose([2, 3, 1, 0], choices, out=store) assert_equal(store, array([20, 31, 12, 3])) self.assertTrue(store is chosen) # Check with some masked indices + out store = empty(4, dtype=int) indices_ = array([2, 3, 1, 0], mask=[1, 0, 0, 1]) chosen = choose(indices_, choices, mode='wrap', out=store) assert_equal(store, array([99, 31, 12, 99])) assert_equal(store.mask, [1, 0, 0, 1]) # Check with some masked choices + out ina ndarray ! choices = array(choices, mask=[[0, 0, 0, 1], [1, 1, 0, 1], [1, 0, 0, 0], [0, 0, 0, 0]]) indices_ = [2, 3, 1, 0] store = empty(4, dtype=int).view(ndarray) chosen = choose(indices_, choices, mode='wrap', out=store) assert_equal(store, array([999999, 31, 12, 999999])) def test_reshape(self): a = arange(10) a[0] = masked # Try the default b = a.reshape((5, 2)) assert_equal(b.shape, (5, 2)) self.assertTrue(b.flags['C']) # Try w/ arguments as list instead of tuple b = a.reshape(5, 2) assert_equal(b.shape, (5, 2)) self.assertTrue(b.flags['C']) # Try w/ order b = a.reshape((5, 2), order='F') assert_equal(b.shape, (5, 2)) self.assertTrue(b.flags['F']) # Try w/ order b = a.reshape(5, 2, order='F') assert_equal(b.shape, (5, 2)) self.assertTrue(b.flags['F']) # c = np.reshape(a, (2, 5)) self.assertTrue(isinstance(c, MaskedArray)) assert_equal(c.shape, (2, 5)) self.assertTrue(c[0, 0] is masked) self.assertTrue(c.flags['C']) def test_make_mask_descr(self): "Test make_mask_descr" # Flexible ntype = [('a', np.float), ('b', np.float)] test = make_mask_descr(ntype) assert_equal(test, [('a', np.bool), ('b', np.bool)]) # Standard w/ shape ntype = (np.float, 2) test = make_mask_descr(ntype) assert_equal(test, (np.bool, 2)) # Standard standard ntype = np.float test = make_mask_descr(ntype) assert_equal(test, np.dtype(np.bool)) # Nested ntype = [('a', np.float), ('b', [('ba', np.float), ('bb', np.float)])] test = make_mask_descr(ntype) control = np.dtype([('a', 'b1'), ('b', [('ba', 'b1'), ('bb', 'b1')])]) assert_equal(test, control) # Named+ shape ntype = [('a', (np.float, 2))] test = make_mask_descr(ntype) assert_equal(test, np.dtype([('a', (np.bool, 2))])) # 2 names ntype = [(('A', 'a'), float)] test = make_mask_descr(ntype) assert_equal(test, np.dtype([(('A', 'a'), bool)])) def test_make_mask(self): "Test make_mask" # w/ a list as an input mask = [0, 1] test = make_mask(mask) assert_equal(test.dtype, MaskType) assert_equal(test, [0, 1]) # w/ a ndarray as an input mask = np.array([0, 1], dtype=np.bool) test = make_mask(mask) assert_equal(test.dtype, MaskType) assert_equal(test, [0, 1]) # w/ a flexible-type ndarray as an input - use default mdtype = [('a', np.bool), ('b', np.bool)] mask = np.array([(0, 0), (0, 1)], dtype=mdtype) test = make_mask(mask) assert_equal(test.dtype, MaskType) assert_equal(test, [1, 1]) # w/ a flexible-type ndarray as an input - use input dtype mdtype = [('a', np.bool), ('b', np.bool)] mask = np.array([(0, 0), (0, 1)], dtype=mdtype) test = make_mask(mask, dtype=mask.dtype) assert_equal(test.dtype, mdtype) assert_equal(test, mask) # w/ a flexible-type ndarray as an input - use input dtype mdtype = [('a', np.float), ('b', np.float)] bdtype = [('a', np.bool), ('b', np.bool)] mask = np.array([(0, 0), (0, 1)], dtype=mdtype) test = make_mask(mask, dtype=mask.dtype) assert_equal(test.dtype, bdtype) assert_equal(test, np.array([(0, 0), (0, 1)], dtype=bdtype)) def test_mask_or(self): # Initialize mtype = [('a', np.bool), ('b', np.bool)] mask = np.array([(0, 0), (0, 1), (1, 0), (0, 0)], dtype=mtype) # Test using nomask as input test = mask_or(mask, nomask) assert_equal(test, mask) test = mask_or(nomask, mask) assert_equal(test, mask) # Using False as input test = mask_or(mask, False) assert_equal(test, mask) # Using True as input. Won't work, but keep it for the kicks # test = mask_or(mask, True) # control = np.array([(1, 1), (1, 1), (1, 1), (1, 1)], dtype=mtype) # assert_equal(test, control) # Using another array w / the same dtype other = np.array([(0, 1), (0, 1), (0, 1), (0, 1)], dtype=mtype) test = mask_or(mask, other) control = np.array([(0, 1), (0, 1), (1, 1), (0, 1)], dtype=mtype) assert_equal(test, control) # Using another array w / a different dtype othertype = [('A', np.bool), ('B', np.bool)] other = np.array([(0, 1), (0, 1), (0, 1), (0, 1)], dtype=othertype) try: test = mask_or(mask, other) except ValueError: pass # Using nested arrays dtype = [('a', np.bool), ('b', [('ba', np.bool), ('bb', np.bool)])] amask = np.array([(0, (1, 0)), (0, (1, 0))], dtype=dtype) bmask = np.array([(1, (0, 1)), (0, (0, 0))], dtype=dtype) cntrl = np.array([(1, (1, 1)), (0, (1, 0))], dtype=dtype) assert_equal(mask_or(amask, bmask), cntrl) def test_flatten_mask(self): "Tests flatten mask" # Standarad dtype mask = np.array([0, 0, 1], dtype=np.bool) assert_equal(flatten_mask(mask), mask) # Flexible dtype mask = np.array([(0, 0), (0, 1)], dtype=[('a', bool), ('b', bool)]) test = flatten_mask(mask) control = np.array([0, 0, 0, 1], dtype=bool) assert_equal(test, control) mdtype = [('a', bool), ('b', [('ba', bool), ('bb', bool)])] data = [(0, (0, 0)), (0, (0, 1))] mask = np.array(data, dtype=mdtype) test = flatten_mask(mask) control = np.array([ 0, 0, 0, 0, 0, 1], dtype=bool) assert_equal(test, control) def test_on_ndarray(self): "Test functions on ndarrays" a = np.array([1, 2, 3, 4]) m = array(a, mask=False) test = anom(a) assert_equal(test, m.anom()) test = reshape(a, (2, 2)) assert_equal(test, m.reshape(2, 2)) def test_compress(self): # Test compress function on ndarray and masked array # Address Github #2495. arr = np.arange(8) arr.shape = 4, 2 cond = np.array([True, False, True, True]) control = arr[[0, 2, 3]] test = np.ma.compress(cond, arr, axis=0) assert_equal(test, control) marr = np.ma.array(arr) test = np.ma.compress(cond, marr, axis=0) assert_equal(test, control) #------------------------------------------------------------------------------ class TestMaskedFields(TestCase): # def setUp(self): ilist = [1, 2, 3, 4, 5] flist = [1.1, 2.2, 3.3, 4.4, 5.5] slist = ['one', 'two', 'three', 'four', 'five'] ddtype = [('a', int), ('b', float), ('c', '|S8')] mdtype = [('a', bool), ('b', bool), ('c', bool)] mask = [0, 1, 0, 0, 1] base = array(list(zip(ilist, flist, slist)), mask=mask, dtype=ddtype) self.data = dict(base=base, mask=mask, ddtype=ddtype, mdtype=mdtype) def test_set_records_masks(self): base = self.data['base'] mdtype = self.data['mdtype'] # Set w/ nomask or masked base.mask = nomask assert_equal_records(base._mask, np.zeros(base.shape, dtype=mdtype)) base.mask = masked assert_equal_records(base._mask, np.ones(base.shape, dtype=mdtype)) # Set w/ simple boolean base.mask = False assert_equal_records(base._mask, np.zeros(base.shape, dtype=mdtype)) base.mask = True assert_equal_records(base._mask, np.ones(base.shape, dtype=mdtype)) # Set w/ list base.mask = [0, 0, 0, 1, 1] assert_equal_records(base._mask, np.array([(x, x, x) for x in [0, 0, 0, 1, 1]], dtype=mdtype)) def test_set_record_element(self): "Check setting an element of a record)" base = self.data['base'] (base_a, base_b, base_c) = (base['a'], base['b'], base['c']) base[0] = (pi, pi, 'pi') assert_equal(base_a.dtype, int) assert_equal(base_a._data, [3, 2, 3, 4, 5]) assert_equal(base_b.dtype, float) assert_equal(base_b._data, [pi, 2.2, 3.3, 4.4, 5.5]) assert_equal(base_c.dtype, '|S8') assert_equal(base_c._data, asbytes_nested(['pi', 'two', 'three', 'four', 'five'])) def test_set_record_slice(self): base = self.data['base'] (base_a, base_b, base_c) = (base['a'], base['b'], base['c']) base[:3] = (pi, pi, 'pi') assert_equal(base_a.dtype, int) assert_equal(base_a._data, [3, 3, 3, 4, 5]) assert_equal(base_b.dtype, float) assert_equal(base_b._data, [pi, pi, pi, 4.4, 5.5]) assert_equal(base_c.dtype, '|S8') assert_equal(base_c._data, asbytes_nested(['pi', 'pi', 'pi', 'four', 'five'])) def test_mask_element(self): "Check record access" base = self.data['base'] (base_a, base_b, base_c) = (base['a'], base['b'], base['c']) base[0] = masked # for n in ('a', 'b', 'c'): assert_equal(base[n].mask, [1, 1, 0, 0, 1]) assert_equal(base[n]._data, base._data[n]) # def test_getmaskarray(self): "Test getmaskarray on flexible dtype" ndtype = [('a', int), ('b', float)] test = empty(3, dtype=ndtype) assert_equal(getmaskarray(test), np.array([(0, 0), (0, 0), (0, 0)], dtype=[('a', '|b1'), ('b', '|b1')])) test[:] = masked assert_equal(getmaskarray(test), np.array([(1, 1), (1, 1), (1, 1)], dtype=[('a', '|b1'), ('b', '|b1')])) # def test_view(self): "Test view w/ flexible dtype" iterator = list(zip(np.arange(10), np.random.rand(10))) data = np.array(iterator) a = array(iterator, dtype=[('a', float), ('b', float)]) a.mask[0] = (1, 0) controlmask = np.array([1] + 19 * [0], dtype=bool) # Transform globally to simple dtype test = a.view(float) assert_equal(test, data.ravel()) assert_equal(test.mask, controlmask) # Transform globally to dty test = a.view((float, 2)) assert_equal(test, data) assert_equal(test.mask, controlmask.reshape(-1, 2)) # test = a.view((float, 2), np.matrix) assert_equal(test, data) self.assertTrue(isinstance(test, np.matrix)) # def test_getitem(self): ndtype = [('a', float), ('b', float)] a = array(list(zip(np.random.rand(10), np.arange(10))), dtype=ndtype) a.mask = np.array(list(zip([0, 0, 0, 0, 0, 0, 0, 0, 1, 1], [1, 0, 0, 0, 0, 0, 0, 0, 1, 0])), dtype=[('a', bool), ('b', bool)]) # No mask self.assertTrue(isinstance(a[1], MaskedArray)) # One element masked self.assertTrue(isinstance(a[0], MaskedArray)) assert_equal_records(a[0]._data, a._data[0]) assert_equal_records(a[0]._mask, a._mask[0]) # All element masked self.assertTrue(isinstance(a[-2], MaskedArray)) assert_equal_records(a[-2]._data, a._data[-2]) assert_equal_records(a[-2]._mask, a._mask[-2]) def test_setitem(self): # Issue 2403 ndtype = np.dtype([('a', float), ('b', int)]) mdtype = np.dtype([('a', bool), ('b', bool)]) # soft mask control = np.array([(False, True), (True, True)], dtype=mdtype) a = np.ma.masked_all((2,), dtype=ndtype) a['a'][0] = 2 assert_equal(a.mask, control) a = np.ma.masked_all((2,), dtype=ndtype) a[0]['a'] = 2 assert_equal(a.mask, control) # hard mask control = np.array([(True, True), (True, True)], dtype=mdtype) a = np.ma.masked_all((2,), dtype=ndtype) a.harden_mask() a['a'][0] = 2 assert_equal(a.mask, control) a = np.ma.masked_all((2,), dtype=ndtype) a.harden_mask() a[0]['a'] = 2 assert_equal(a.mask, control) def test_element_len(self): # check that len() works for mvoid (Github issue #576) for rec in self.data['base']: assert_equal(len(rec), len(self.data['ddtype'])) #------------------------------------------------------------------------------ class TestMaskedView(TestCase): # def setUp(self): iterator = list(zip(np.arange(10), np.random.rand(10))) data = np.array(iterator) a = array(iterator, dtype=[('a', float), ('b', float)]) a.mask[0] = (1, 0) controlmask = np.array([1] + 19 * [0], dtype=bool) self.data = (data, a, controlmask) # def test_view_to_nothing(self): (data, a, controlmask) = self.data test = a.view() self.assertTrue(isinstance(test, MaskedArray)) assert_equal(test._data, a._data) assert_equal(test._mask, a._mask) # def test_view_to_type(self): (data, a, controlmask) = self.data test = a.view(np.ndarray) self.assertTrue(not isinstance(test, MaskedArray)) assert_equal(test, a._data) assert_equal_records(test, data.view(a.dtype).squeeze()) # def test_view_to_simple_dtype(self): (data, a, controlmask) = self.data # View globally test = a.view(float) self.assertTrue(isinstance(test, MaskedArray)) assert_equal(test, data.ravel()) assert_equal(test.mask, controlmask) # def test_view_to_flexible_dtype(self): (data, a, controlmask) = self.data # test = a.view([('A', float), ('B', float)]) assert_equal(test.mask.dtype.names, ('A', 'B')) assert_equal(test['A'], a['a']) assert_equal(test['B'], a['b']) # test = a[0].view([('A', float), ('B', float)]) self.assertTrue(isinstance(test, MaskedArray)) assert_equal(test.mask.dtype.names, ('A', 'B')) assert_equal(test['A'], a['a'][0]) assert_equal(test['B'], a['b'][0]) # test = a[-1].view([('A', float), ('B', float)]) self.assertTrue(isinstance(test, MaskedArray)) assert_equal(test.dtype.names, ('A', 'B')) assert_equal(test['A'], a['a'][-1]) assert_equal(test['B'], a['b'][-1]) # def test_view_to_subdtype(self): (data, a, controlmask) = self.data # View globally test = a.view((float, 2)) self.assertTrue(isinstance(test, MaskedArray)) assert_equal(test, data) assert_equal(test.mask, controlmask.reshape(-1, 2)) # View on 1 masked element test = a[0].view((float, 2)) self.assertTrue(isinstance(test, MaskedArray)) assert_equal(test, data[0]) assert_equal(test.mask, (1, 0)) # View on 1 unmasked element test = a[-1].view((float, 2)) self.assertTrue(isinstance(test, MaskedArray)) assert_equal(test, data[-1]) # def test_view_to_dtype_and_type(self): (data, a, controlmask) = self.data # test = a.view((float, 2), np.matrix) assert_equal(test, data) self.assertTrue(isinstance(test, np.matrix)) self.assertTrue(not isinstance(test, MaskedArray)) def test_masked_array(): a = np.ma.array([0, 1, 2, 3], mask=[0, 0, 1, 0]) assert_equal(np.argwhere(a), [[1], [3]]) ############################################################################### if __name__ == "__main__": run_module_suite() numpy-1.8.2/numpy/ma/tests/test_mrecords.py0000664000175100017510000005121612370216243022167 0ustar vagrantvagrant00000000000000# pylint: disable-msg=W0611, W0612, W0511,R0201 """Tests suite for mrecords. :author: Pierre Gerard-Marchant :contact: pierregm_at_uga_dot_edu """ from __future__ import division, absolute_import, print_function import sys import warnings import pickle import numpy as np import numpy.ma.testutils import numpy.ma as ma from numpy import recarray from numpy.core.records import fromrecords as recfromrecords, \ fromarrays as recfromarrays from numpy.compat import asbytes, asbytes_nested from numpy.ma.testutils import * from numpy.ma import masked, nomask from numpy.ma.mrecords import MaskedRecords, mrecarray, fromarrays, \ fromtextfile, fromrecords, addfield __author__ = "Pierre GF Gerard-Marchant ($Author: jarrod.millman $)" __revision__ = "$Revision: 3473 $" __date__ = '$Date: 2007-10-29 17:18:13 +0200 (Mon, 29 Oct 2007) $' #.............................................................................. class TestMRecords(TestCase): "Base test class for MaskedArrays." def __init__(self, *args, **kwds): TestCase.__init__(self, *args, **kwds) self.setup() def setup(self): "Generic setup" ilist = [1, 2, 3, 4, 5] flist = [1.1, 2.2, 3.3, 4.4, 5.5] slist = asbytes_nested(['one', 'two', 'three', 'four', 'five']) ddtype = [('a', int), ('b', float), ('c', '|S8')] mask = [0, 1, 0, 0, 1] self.base = ma.array(list(zip(ilist, flist, slist)), mask=mask, dtype=ddtype) def test_byview(self): "Test creation by view" base = self.base mbase = base.view(mrecarray) assert_equal(mbase.recordmask, base.recordmask) assert_equal_records(mbase._mask, base._mask) assert_(isinstance(mbase._data, recarray)) assert_equal_records(mbase._data, base._data.view(recarray)) for field in ('a', 'b', 'c'): assert_equal(base[field], mbase[field]) assert_equal_records(mbase.view(mrecarray), mbase) def test_get(self): "Tests fields retrieval" base = self.base.copy() mbase = base.view(mrecarray) # As fields.......... for field in ('a', 'b', 'c'): assert_equal(getattr(mbase, field), mbase[field]) assert_equal(base[field], mbase[field]) # as elements ....... mbase_first = mbase[0] assert_(isinstance(mbase_first, mrecarray)) assert_equal(mbase_first.dtype, mbase.dtype) assert_equal(mbase_first.tolist(), (1, 1.1, asbytes('one'))) # Used to be mask, now it's recordmask assert_equal(mbase_first.recordmask, nomask) assert_equal(mbase_first._mask.item(), (False, False, False)) assert_equal(mbase_first['a'], mbase['a'][0]) mbase_last = mbase[-1] assert_(isinstance(mbase_last, mrecarray)) assert_equal(mbase_last.dtype, mbase.dtype) assert_equal(mbase_last.tolist(), (None, None, None)) # Used to be mask, now it's recordmask assert_equal(mbase_last.recordmask, True) assert_equal(mbase_last._mask.item(), (True, True, True)) assert_equal(mbase_last['a'], mbase['a'][-1]) assert_((mbase_last['a'] is masked)) # as slice .......... mbase_sl = mbase[:2] assert_(isinstance(mbase_sl, mrecarray)) assert_equal(mbase_sl.dtype, mbase.dtype) # Used to be mask, now it's recordmask assert_equal(mbase_sl.recordmask, [0, 1]) assert_equal_records(mbase_sl.mask, np.array([(False, False, False), (True, True, True)], dtype=mbase._mask.dtype)) assert_equal_records(mbase_sl, base[:2].view(mrecarray)) for field in ('a', 'b', 'c'): assert_equal(getattr(mbase_sl, field), base[:2][field]) def test_set_fields(self): "Tests setting fields." base = self.base.copy() mbase = base.view(mrecarray) mbase = mbase.copy() mbase.fill_value = (999999, 1e20, 'N/A') # Change the data, the mask should be conserved mbase.a._data[:] = 5 assert_equal(mbase['a']._data, [5, 5, 5, 5, 5]) assert_equal(mbase['a']._mask, [0, 1, 0, 0, 1]) # Change the elements, and the mask will follow mbase.a = 1 assert_equal(mbase['a']._data, [1]*5) assert_equal(ma.getmaskarray(mbase['a']), [0]*5) # Use to be _mask, now it's recordmask assert_equal(mbase.recordmask, [False]*5) assert_equal(mbase._mask.tolist(), np.array([(0, 0, 0), (0, 1, 1), (0, 0, 0), (0, 0, 0), (0, 1, 1)], dtype=bool)) # Set a field to mask ........................ mbase.c = masked # Use to be mask, and now it's still mask ! assert_equal(mbase.c.mask, [1]*5) assert_equal(mbase.c.recordmask, [1]*5) assert_equal(ma.getmaskarray(mbase['c']), [1]*5) assert_equal(ma.getdata(mbase['c']), [asbytes('N/A')]*5) assert_equal(mbase._mask.tolist(), np.array([(0, 0, 1), (0, 1, 1), (0, 0, 1), (0, 0, 1), (0, 1, 1)], dtype=bool)) # Set fields by slices ....................... mbase = base.view(mrecarray).copy() mbase.a[3:] = 5 assert_equal(mbase.a, [1, 2, 3, 5, 5]) assert_equal(mbase.a._mask, [0, 1, 0, 0, 0]) mbase.b[3:] = masked assert_equal(mbase.b, base['b']) assert_equal(mbase.b._mask, [0, 1, 0, 1, 1]) # Set fields globally.......................... ndtype = [('alpha', '|S1'), ('num', int)] data = ma.array([('a', 1), ('b', 2), ('c', 3)], dtype=ndtype) rdata = data.view(MaskedRecords) val = ma.array([10, 20, 30], mask=[1, 0, 0]) # with warnings.catch_warnings(): warnings.simplefilter("ignore") rdata['num'] = val assert_equal(rdata.num, val) assert_equal(rdata.num.mask, [1, 0, 0]) def test_set_fields_mask(self): "Tests setting the mask of a field." base = self.base.copy() # This one has already a mask.... mbase = base.view(mrecarray) mbase['a'][-2] = masked assert_equal(mbase.a, [1, 2, 3, 4, 5]) assert_equal(mbase.a._mask, [0, 1, 0, 1, 1]) # This one has not yet mbase = fromarrays([np.arange(5), np.random.rand(5)], dtype=[('a', int), ('b', float)]) mbase['a'][-2] = masked assert_equal(mbase.a, [0, 1, 2, 3, 4]) assert_equal(mbase.a._mask, [0, 0, 0, 1, 0]) # def test_set_mask(self): base = self.base.copy() mbase = base.view(mrecarray) # Set the mask to True ....................... mbase.mask = masked assert_equal(ma.getmaskarray(mbase['b']), [1]*5) assert_equal(mbase['a']._mask, mbase['b']._mask) assert_equal(mbase['a']._mask, mbase['c']._mask) assert_equal(mbase._mask.tolist(), np.array([(1, 1, 1)]*5, dtype=bool)) # Delete the mask ............................ mbase.mask = nomask assert_equal(ma.getmaskarray(mbase['c']), [0]*5) assert_equal(mbase._mask.tolist(), np.array([(0, 0, 0)]*5, dtype=bool)) # def test_set_mask_fromarray(self): base = self.base.copy() mbase = base.view(mrecarray) # Sets the mask w/ an array mbase.mask = [1, 0, 0, 0, 1] assert_equal(mbase.a.mask, [1, 0, 0, 0, 1]) assert_equal(mbase.b.mask, [1, 0, 0, 0, 1]) assert_equal(mbase.c.mask, [1, 0, 0, 0, 1]) # Yay, once more ! mbase.mask = [0, 0, 0, 0, 1] assert_equal(mbase.a.mask, [0, 0, 0, 0, 1]) assert_equal(mbase.b.mask, [0, 0, 0, 0, 1]) assert_equal(mbase.c.mask, [0, 0, 0, 0, 1]) # def test_set_mask_fromfields(self): mbase = self.base.copy().view(mrecarray) # nmask = np.array([(0, 1, 0), (0, 1, 0), (1, 0, 1), (1, 0, 1), (0, 0, 0)], dtype=[('a', bool), ('b', bool), ('c', bool)]) mbase.mask = nmask assert_equal(mbase.a.mask, [0, 0, 1, 1, 0]) assert_equal(mbase.b.mask, [1, 1, 0, 0, 0]) assert_equal(mbase.c.mask, [0, 0, 1, 1, 0]) # Reinitalizes and redo mbase.mask = False mbase.fieldmask = nmask assert_equal(mbase.a.mask, [0, 0, 1, 1, 0]) assert_equal(mbase.b.mask, [1, 1, 0, 0, 0]) assert_equal(mbase.c.mask, [0, 0, 1, 1, 0]) # def test_set_elements(self): base = self.base.copy() # Set an element to mask ..................... mbase = base.view(mrecarray).copy() mbase[-2] = masked assert_equal(mbase._mask.tolist(), np.array([(0, 0, 0), (1, 1, 1), (0, 0, 0), (1, 1, 1), (1, 1, 1)], dtype=bool)) # Used to be mask, now it's recordmask! assert_equal(mbase.recordmask, [0, 1, 0, 1, 1]) # Set slices ................................. mbase = base.view(mrecarray).copy() mbase[:2] = (5, 5, 5) assert_equal(mbase.a._data, [5, 5, 3, 4, 5]) assert_equal(mbase.a._mask, [0, 0, 0, 0, 1]) assert_equal(mbase.b._data, [5., 5., 3.3, 4.4, 5.5]) assert_equal(mbase.b._mask, [0, 0, 0, 0, 1]) assert_equal(mbase.c._data, asbytes_nested(['5', '5', 'three', 'four', 'five'])) assert_equal(mbase.b._mask, [0, 0, 0, 0, 1]) # mbase = base.view(mrecarray).copy() mbase[:2] = masked assert_equal(mbase.a._data, [1, 2, 3, 4, 5]) assert_equal(mbase.a._mask, [1, 1, 0, 0, 1]) assert_equal(mbase.b._data, [1.1, 2.2, 3.3, 4.4, 5.5]) assert_equal(mbase.b._mask, [1, 1, 0, 0, 1]) assert_equal(mbase.c._data, asbytes_nested(['one', 'two', 'three', 'four', 'five'])) assert_equal(mbase.b._mask, [1, 1, 0, 0, 1]) # def test_setslices_hardmask(self): "Tests setting slices w/ hardmask." base = self.base.copy() mbase = base.view(mrecarray) mbase.harden_mask() try: mbase[-2:] = (5, 5, 5) assert_equal(mbase.a._data, [1, 2, 3, 5, 5]) assert_equal(mbase.b._data, [1.1, 2.2, 3.3, 5, 5.5]) assert_equal(mbase.c._data, asbytes_nested(['one', 'two', 'three', '5', 'five'])) assert_equal(mbase.a._mask, [0, 1, 0, 0, 1]) assert_equal(mbase.b._mask, mbase.a._mask) assert_equal(mbase.b._mask, mbase.c._mask) except NotImplementedError: # OK, not implemented yet... pass except AssertionError: raise else: raise Exception("Flexible hard masks should be supported !") # Not using a tuple should crash try: mbase[-2:] = 3 except (NotImplementedError, TypeError): pass else: raise TypeError("Should have expected a readable buffer object!") def test_hardmask(self): "Test hardmask" base = self.base.copy() mbase = base.view(mrecarray) mbase.harden_mask() self.assertTrue(mbase._hardmask) mbase.mask = nomask assert_equal_records(mbase._mask, base._mask) mbase.soften_mask() self.assertTrue(not mbase._hardmask) mbase.mask = nomask # So, the mask of a field is no longer set to nomask... assert_equal_records(mbase._mask, ma.make_mask_none(base.shape, base.dtype)) self.assertTrue(ma.make_mask(mbase['b']._mask) is nomask) assert_equal(mbase['a']._mask, mbase['b']._mask) # def test_pickling(self): "Test pickling" base = self.base.copy() mrec = base.view(mrecarray) _ = pickle.dumps(mrec) mrec_ = pickle.loads(_) assert_equal(mrec_.dtype, mrec.dtype) assert_equal_records(mrec_._data, mrec._data) assert_equal(mrec_._mask, mrec._mask) assert_equal_records(mrec_._mask, mrec._mask) # def test_filled(self): "Test filling the array" _a = ma.array([1, 2, 3], mask=[0, 0, 1], dtype=int) _b = ma.array([1.1, 2.2, 3.3], mask=[0, 0, 1], dtype=float) _c = ma.array(['one', 'two', 'three'], mask=[0, 0, 1], dtype='|S8') ddtype = [('a', int), ('b', float), ('c', '|S8')] mrec = fromarrays([_a, _b, _c], dtype=ddtype, fill_value=(99999, 99999., 'N/A')) mrecfilled = mrec.filled() assert_equal(mrecfilled['a'], np.array((1, 2, 99999), dtype=int)) assert_equal(mrecfilled['b'], np.array((1.1, 2.2, 99999.), dtype=float)) assert_equal(mrecfilled['c'], np.array(('one', 'two', 'N/A'), dtype='|S8')) # def test_tolist(self): "Test tolist." _a = ma.array([1, 2, 3], mask=[0, 0, 1], dtype=int) _b = ma.array([1.1, 2.2, 3.3], mask=[0, 0, 1], dtype=float) _c = ma.array(['one', 'two', 'three'], mask=[1, 0, 0], dtype='|S8') ddtype = [('a', int), ('b', float), ('c', '|S8')] mrec = fromarrays([_a, _b, _c], dtype=ddtype, fill_value=(99999, 99999., 'N/A')) # assert_equal(mrec.tolist(), [(1, 1.1, None), (2, 2.2, asbytes('two')), (None, None, asbytes('three'))]) # def test_withnames(self): "Test the creation w/ format and names" x = mrecarray(1, formats=float, names='base') x[0]['base'] = 10 assert_equal(x['base'][0], 10) # def test_exotic_formats(self): "Test that 'exotic' formats are processed properly" easy = mrecarray(1, dtype=[('i', int), ('s', '|S8'), ('f', float)]) easy[0] = masked assert_equal(easy.filled(1).item(), (1, asbytes('1'), 1.)) # solo = mrecarray(1, dtype=[('f0', ' 8) | (a == 5)] = masked test = flatnotmasked_contiguous(a) assert_equal(test, [slice(3, 5), slice(6, 9)]) # a[:] = masked test = flatnotmasked_contiguous(a) assert_equal(test, None) class TestAverage(TestCase): "Several tests of average. Why so many ? Good point..." def test_testAverage1(self): "Test of average." ott = array([0., 1., 2., 3.], mask=[True, False, False, False]) assert_equal(2.0, average(ott, axis=0)) assert_equal(2.0, average(ott, weights=[1., 1., 2., 1.])) result, wts = average(ott, weights=[1., 1., 2., 1.], returned=1) assert_equal(2.0, result) self.assertTrue(wts == 4.0) ott[:] = masked assert_equal(average(ott, axis=0).mask, [True]) ott = array([0., 1., 2., 3.], mask=[True, False, False, False]) ott = ott.reshape(2, 2) ott[:, 1] = masked assert_equal(average(ott, axis=0), [2.0, 0.0]) assert_equal(average(ott, axis=1).mask[0], [True]) assert_equal([2., 0.], average(ott, axis=0)) result, wts = average(ott, axis=0, returned=1) assert_equal(wts, [1., 0.]) def test_testAverage2(self): "More tests of average." w1 = [0, 1, 1, 1, 1, 0] w2 = [[0, 1, 1, 1, 1, 0], [1, 0, 0, 0, 0, 1]] x = arange(6, dtype=np.float_) assert_equal(average(x, axis=0), 2.5) assert_equal(average(x, axis=0, weights=w1), 2.5) y = array([arange(6, dtype=np.float_), 2.0 * arange(6)]) assert_equal(average(y, None), np.add.reduce(np.arange(6)) * 3. / 12.) assert_equal(average(y, axis=0), np.arange(6) * 3. / 2.) assert_equal(average(y, axis=1), [average(x, axis=0), average(x, axis=0) * 2.0]) assert_equal(average(y, None, weights=w2), 20. / 6.) assert_equal(average(y, axis=0, weights=w2), [0., 1., 2., 3., 4., 10.]) assert_equal(average(y, axis=1), [average(x, axis=0), average(x, axis=0) * 2.0]) m1 = zeros(6) m2 = [0, 0, 1, 1, 0, 0] m3 = [[0, 0, 1, 1, 0, 0], [0, 1, 1, 1, 1, 0]] m4 = ones(6) m5 = [0, 1, 1, 1, 1, 1] assert_equal(average(masked_array(x, m1), axis=0), 2.5) assert_equal(average(masked_array(x, m2), axis=0), 2.5) assert_equal(average(masked_array(x, m4), axis=0).mask, [True]) assert_equal(average(masked_array(x, m5), axis=0), 0.0) assert_equal(count(average(masked_array(x, m4), axis=0)), 0) z = masked_array(y, m3) assert_equal(average(z, None), 20. / 6.) assert_equal(average(z, axis=0), [0., 1., 99., 99., 4.0, 7.5]) assert_equal(average(z, axis=1), [2.5, 5.0]) assert_equal(average(z, axis=0, weights=w2), [0., 1., 99., 99., 4.0, 10.0]) def test_testAverage3(self): "Yet more tests of average!" a = arange(6) b = arange(6) * 3 r1, w1 = average([[a, b], [b, a]], axis=1, returned=1) assert_equal(shape(r1), shape(w1)) assert_equal(r1.shape, w1.shape) r2, w2 = average(ones((2, 2, 3)), axis=0, weights=[3, 1], returned=1) assert_equal(shape(w2), shape(r2)) r2, w2 = average(ones((2, 2, 3)), returned=1) assert_equal(shape(w2), shape(r2)) r2, w2 = average(ones((2, 2, 3)), weights=ones((2, 2, 3)), returned=1) assert_equal(shape(w2), shape(r2)) a2d = array([[1, 2], [0, 4]], float) a2dm = masked_array(a2d, [[False, False], [True, False]]) a2da = average(a2d, axis=0) assert_equal(a2da, [0.5, 3.0]) a2dma = average(a2dm, axis=0) assert_equal(a2dma, [1.0, 3.0]) a2dma = average(a2dm, axis=None) assert_equal(a2dma, 7. / 3.) a2dma = average(a2dm, axis=1) assert_equal(a2dma, [1.5, 4.0]) def test_onintegers_with_mask(self): "Test average on integers with mask" a = average(array([1, 2])) assert_equal(a, 1.5) a = average(array([1, 2, 3, 4], mask=[False, False, True, True])) assert_equal(a, 1.5) def test_complex(self): # Test with complex data. # (Regression test for https://github.com/numpy/numpy/issues/2684) mask = np.array([[0, 0, 0, 1, 0], [0, 1, 0, 0, 0]], dtype=bool) a = masked_array([[0, 1+2j, 3+4j, 5+6j, 7+8j], [9j, 0+1j, 2+3j, 4+5j, 7+7j]], mask=mask) av = average(a) expected = np.average(a.compressed()) assert_almost_equal(av.real, expected.real) assert_almost_equal(av.imag, expected.imag) av0 = average(a, axis=0) expected0 = average(a.real, axis=0) + average(a.imag, axis=0)*1j assert_almost_equal(av0.real, expected0.real) assert_almost_equal(av0.imag, expected0.imag) av1 = average(a, axis=1) expected1 = average(a.real, axis=1) + average(a.imag, axis=1)*1j assert_almost_equal(av1.real, expected1.real) assert_almost_equal(av1.imag, expected1.imag) # Test with the 'weights' argument. wts = np.array([[0.5, 1.0, 2.0, 1.0, 0.5], [1.0, 1.0, 1.0, 1.0, 1.0]]) wav = average(a, weights=wts) expected = np.average(a.compressed(), weights=wts[~mask]) assert_almost_equal(wav.real, expected.real) assert_almost_equal(wav.imag, expected.imag) wav0 = average(a, weights=wts, axis=0) expected0 = (average(a.real, weights=wts, axis=0) + average(a.imag, weights=wts, axis=0)*1j) assert_almost_equal(wav0.real, expected0.real) assert_almost_equal(wav0.imag, expected0.imag) wav1 = average(a, weights=wts, axis=1) expected1 = (average(a.real, weights=wts, axis=1) + average(a.imag, weights=wts, axis=1)*1j) assert_almost_equal(wav1.real, expected1.real) assert_almost_equal(wav1.imag, expected1.imag) class TestConcatenator(TestCase): """ Tests for mr_, the equivalent of r_ for masked arrays. """ def test_1d(self): "Tests mr_ on 1D arrays." assert_array_equal(mr_[1, 2, 3, 4, 5, 6], array([1, 2, 3, 4, 5, 6])) b = ones(5) m = [1, 0, 0, 0, 0] d = masked_array(b, mask=m) c = mr_[d, 0, 0, d] self.assertTrue(isinstance(c, MaskedArray)) assert_array_equal(c, [1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1]) assert_array_equal(c.mask, mr_[m, 0, 0, m]) def test_2d(self): "Tests mr_ on 2D arrays." a_1 = rand(5, 5) a_2 = rand(5, 5) m_1 = np.round_(rand(5, 5), 0) m_2 = np.round_(rand(5, 5), 0) b_1 = masked_array(a_1, mask=m_1) b_2 = masked_array(a_2, mask=m_2) d = mr_['1', b_1, b_2] # append columns self.assertTrue(d.shape == (5, 10)) assert_array_equal(d[:, :5], b_1) assert_array_equal(d[:, 5:], b_2) assert_array_equal(d.mask, np.r_['1', m_1, m_2]) d = mr_[b_1, b_2] self.assertTrue(d.shape == (10, 5)) assert_array_equal(d[:5,:], b_1) assert_array_equal(d[5:,:], b_2) assert_array_equal(d.mask, np.r_[m_1, m_2]) class TestNotMasked(TestCase): """ Tests notmasked_edges and notmasked_contiguous. """ def test_edges(self): "Tests unmasked_edges" data = masked_array(np.arange(25).reshape(5, 5), mask=[[0, 0, 1, 0, 0], [0, 0, 0, 1, 1], [1, 1, 0, 0, 0], [0, 0, 0, 0, 0], [1, 1, 1, 0, 0]],) test = notmasked_edges(data, None) assert_equal(test, [0, 24]) test = notmasked_edges(data, 0) assert_equal(test[0], [(0, 0, 1, 0, 0), (0, 1, 2, 3, 4)]) assert_equal(test[1], [(3, 3, 3, 4, 4), (0, 1, 2, 3, 4)]) test = notmasked_edges(data, 1) assert_equal(test[0], [(0, 1, 2, 3, 4), (0, 0, 2, 0, 3)]) assert_equal(test[1], [(0, 1, 2, 3, 4), (4, 2, 4, 4, 4)]) # test = notmasked_edges(data.data, None) assert_equal(test, [0, 24]) test = notmasked_edges(data.data, 0) assert_equal(test[0], [(0, 0, 0, 0, 0), (0, 1, 2, 3, 4)]) assert_equal(test[1], [(4, 4, 4, 4, 4), (0, 1, 2, 3, 4)]) test = notmasked_edges(data.data, -1) assert_equal(test[0], [(0, 1, 2, 3, 4), (0, 0, 0, 0, 0)]) assert_equal(test[1], [(0, 1, 2, 3, 4), (4, 4, 4, 4, 4)]) # data[-2] = masked test = notmasked_edges(data, 0) assert_equal(test[0], [(0, 0, 1, 0, 0), (0, 1, 2, 3, 4)]) assert_equal(test[1], [(1, 1, 2, 4, 4), (0, 1, 2, 3, 4)]) test = notmasked_edges(data, -1) assert_equal(test[0], [(0, 1, 2, 4), (0, 0, 2, 3)]) assert_equal(test[1], [(0, 1, 2, 4), (4, 2, 4, 4)]) def test_contiguous(self): "Tests notmasked_contiguous" a = masked_array(np.arange(24).reshape(3, 8), mask=[[0, 0, 0, 0, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 1, 0], ]) tmp = notmasked_contiguous(a, None) assert_equal(tmp[-1], slice(23, 24, None)) assert_equal(tmp[-2], slice(16, 22, None)) assert_equal(tmp[-3], slice(0, 4, None)) # tmp = notmasked_contiguous(a, 0) self.assertTrue(len(tmp[-1]) == 1) self.assertTrue(tmp[-2] is None) assert_equal(tmp[-3], tmp[-1]) self.assertTrue(len(tmp[0]) == 2) # tmp = notmasked_contiguous(a, 1) assert_equal(tmp[0][-1], slice(0, 4, None)) self.assertTrue(tmp[1] is None) assert_equal(tmp[2][-1], slice(7, 8, None)) assert_equal(tmp[2][-2], slice(0, 6, None)) class Test2DFunctions(TestCase): "Tests 2D functions" def test_compress2d(self): "Tests compress2d" x = array(np.arange(9).reshape(3, 3), mask=[[1, 0, 0], [0, 0, 0], [0, 0, 0]]) assert_equal(compress_rowcols(x), [[4, 5], [7, 8]]) assert_equal(compress_rowcols(x, 0), [[3, 4, 5], [6, 7, 8]]) assert_equal(compress_rowcols(x, 1), [[1, 2], [4, 5], [7, 8]]) x = array(x._data, mask=[[0, 0, 0], [0, 1, 0], [0, 0, 0]]) assert_equal(compress_rowcols(x), [[0, 2], [6, 8]]) assert_equal(compress_rowcols(x, 0), [[0, 1, 2], [6, 7, 8]]) assert_equal(compress_rowcols(x, 1), [[0, 2], [3, 5], [6, 8]]) x = array(x._data, mask=[[1, 0, 0], [0, 1, 0], [0, 0, 0]]) assert_equal(compress_rowcols(x), [[8]]) assert_equal(compress_rowcols(x, 0), [[6, 7, 8]]) assert_equal(compress_rowcols(x, 1,), [[2], [5], [8]]) x = array(x._data, mask=[[1, 0, 0], [0, 1, 0], [0, 0, 1]]) assert_equal(compress_rowcols(x).size, 0) assert_equal(compress_rowcols(x, 0).size, 0) assert_equal(compress_rowcols(x, 1).size, 0) def test_mask_rowcols(self): "Tests mask_rowcols." x = array(np.arange(9).reshape(3, 3), mask=[[1, 0, 0], [0, 0, 0], [0, 0, 0]]) assert_equal(mask_rowcols(x).mask, [[1, 1, 1], [1, 0, 0], [1, 0, 0]]) assert_equal(mask_rowcols(x, 0).mask, [[1, 1, 1], [0, 0, 0], [0, 0, 0]]) assert_equal(mask_rowcols(x, 1).mask, [[1, 0, 0], [1, 0, 0], [1, 0, 0]]) x = array(x._data, mask=[[0, 0, 0], [0, 1, 0], [0, 0, 0]]) assert_equal(mask_rowcols(x).mask, [[0, 1, 0], [1, 1, 1], [0, 1, 0]]) assert_equal(mask_rowcols(x, 0).mask, [[0, 0, 0], [1, 1, 1], [0, 0, 0]]) assert_equal(mask_rowcols(x, 1).mask, [[0, 1, 0], [0, 1, 0], [0, 1, 0]]) x = array(x._data, mask=[[1, 0, 0], [0, 1, 0], [0, 0, 0]]) assert_equal(mask_rowcols(x).mask, [[1, 1, 1], [1, 1, 1], [1, 1, 0]]) assert_equal(mask_rowcols(x, 0).mask, [[1, 1, 1], [1, 1, 1], [0, 0, 0]]) assert_equal(mask_rowcols(x, 1,).mask, [[1, 1, 0], [1, 1, 0], [1, 1, 0]]) x = array(x._data, mask=[[1, 0, 0], [0, 1, 0], [0, 0, 1]]) self.assertTrue(mask_rowcols(x).all() is masked) self.assertTrue(mask_rowcols(x, 0).all() is masked) self.assertTrue(mask_rowcols(x, 1).all() is masked) self.assertTrue(mask_rowcols(x).mask.all()) self.assertTrue(mask_rowcols(x, 0).mask.all()) self.assertTrue(mask_rowcols(x, 1).mask.all()) def test_dot(self): "Tests dot product" n = np.arange(1, 7) # m = [1, 0, 0, 0, 0, 0] a = masked_array(n, mask=m).reshape(2, 3) b = masked_array(n, mask=m).reshape(3, 2) c = dot(a, b, True) assert_equal(c.mask, [[1, 1], [1, 0]]) c = dot(b, a, True) assert_equal(c.mask, [[1, 1, 1], [1, 0, 0], [1, 0, 0]]) c = dot(a, b, False) assert_equal(c, np.dot(a.filled(0), b.filled(0))) c = dot(b, a, False) assert_equal(c, np.dot(b.filled(0), a.filled(0))) # m = [0, 0, 0, 0, 0, 1] a = masked_array(n, mask=m).reshape(2, 3) b = masked_array(n, mask=m).reshape(3, 2) c = dot(a, b, True) assert_equal(c.mask, [[0, 1], [1, 1]]) c = dot(b, a, True) assert_equal(c.mask, [[0, 0, 1], [0, 0, 1], [1, 1, 1]]) c = dot(a, b, False) assert_equal(c, np.dot(a.filled(0), b.filled(0))) assert_equal(c, dot(a, b)) c = dot(b, a, False) assert_equal(c, np.dot(b.filled(0), a.filled(0))) # m = [0, 0, 0, 0, 0, 0] a = masked_array(n, mask=m).reshape(2, 3) b = masked_array(n, mask=m).reshape(3, 2) c = dot(a, b) assert_equal(c.mask, nomask) c = dot(b, a) assert_equal(c.mask, nomask) # a = masked_array(n, mask=[1, 0, 0, 0, 0, 0]).reshape(2, 3) b = masked_array(n, mask=[0, 0, 0, 0, 0, 0]).reshape(3, 2) c = dot(a, b, True) assert_equal(c.mask, [[1, 1], [0, 0]]) c = dot(a, b, False) assert_equal(c, np.dot(a.filled(0), b.filled(0))) c = dot(b, a, True) assert_equal(c.mask, [[1, 0, 0], [1, 0, 0], [1, 0, 0]]) c = dot(b, a, False) assert_equal(c, np.dot(b.filled(0), a.filled(0))) # a = masked_array(n, mask=[0, 0, 0, 0, 0, 1]).reshape(2, 3) b = masked_array(n, mask=[0, 0, 0, 0, 0, 0]).reshape(3, 2) c = dot(a, b, True) assert_equal(c.mask, [[0, 0], [1, 1]]) c = dot(a, b) assert_equal(c, np.dot(a.filled(0), b.filled(0))) c = dot(b, a, True) assert_equal(c.mask, [[0, 0, 1], [0, 0, 1], [0, 0, 1]]) c = dot(b, a, False) assert_equal(c, np.dot(b.filled(0), a.filled(0))) # a = masked_array(n, mask=[0, 0, 0, 0, 0, 1]).reshape(2, 3) b = masked_array(n, mask=[0, 0, 1, 0, 0, 0]).reshape(3, 2) c = dot(a, b, True) assert_equal(c.mask, [[1, 0], [1, 1]]) c = dot(a, b, False) assert_equal(c, np.dot(a.filled(0), b.filled(0))) c = dot(b, a, True) assert_equal(c.mask, [[0, 0, 1], [1, 1, 1], [0, 0, 1]]) c = dot(b, a, False) assert_equal(c, np.dot(b.filled(0), a.filled(0))) class TestApplyAlongAxis(TestCase): "Tests 2D functions" def test_3d(self): a = arange(12.).reshape(2, 2, 3) def myfunc(b): return b[1] xa = apply_along_axis(myfunc, 2, a) assert_equal(xa, [[1, 4], [7, 10]]) class TestApplyOverAxes(TestCase): "Tests apply_over_axes" def test_basic(self): a = arange(24).reshape(2, 3, 4) test = apply_over_axes(np.sum, a, [0, 2]) ctrl = np.array([[[60], [92], [124]]]) 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]]]) class TestMedian(TestCase): def test_2d(self): "Tests median w/ 2D" (n, p) = (101, 30) x = masked_array(np.linspace(-1., 1., n),) x[:10] = x[-10:] = masked z = masked_array(np.empty((n, p), dtype=float)) z[:, 0] = x[:] idx = np.arange(len(x)) for i in range(1, p): np.random.shuffle(idx) z[:, i] = x[idx] assert_equal(median(z[:, 0]), 0) assert_equal(median(z), 0) assert_equal(median(z, axis=0), np.zeros(p)) assert_equal(median(z.T, axis=1), np.zeros(p)) def test_2d_waxis(self): "Tests median w/ 2D arrays and different axis." x = masked_array(np.arange(30).reshape(10, 3)) x[:3] = x[-3:] = masked assert_equal(median(x), 14.5) assert_equal(median(x, axis=0), [13.5, 14.5, 15.5]) assert_equal(median(x, axis=1), [0, 0, 0, 10, 13, 16, 19, 0, 0, 0]) assert_equal(median(x, axis=1).mask, [1, 1, 1, 0, 0, 0, 0, 1, 1, 1]) def test_3d(self): "Tests median w/ 3D" x = np.ma.arange(24).reshape(3, 4, 2) x[x % 3 == 0] = masked assert_equal(median(x, 0), [[12, 9], [6, 15], [12, 9], [18, 15]]) x.shape = (4, 3, 2) assert_equal(median(x, 0), [[99, 10], [11, 99], [13, 14]]) x = np.ma.arange(24).reshape(4, 3, 2) x[x % 5 == 0] = masked assert_equal(median(x, 0), [[12, 10], [8, 9], [16, 17]]) class TestCov(TestCase): def setUp(self): self.data = array(np.random.rand(12)) def test_1d_wo_missing(self): "Test cov on 1D variable w/o missing values" x = self.data assert_almost_equal(np.cov(x), cov(x)) assert_almost_equal(np.cov(x, rowvar=False), cov(x, rowvar=False)) assert_almost_equal(np.cov(x, rowvar=False, bias=True), cov(x, rowvar=False, bias=True)) def test_2d_wo_missing(self): "Test cov on 1 2D variable w/o missing values" x = self.data.reshape(3, 4) assert_almost_equal(np.cov(x), cov(x)) assert_almost_equal(np.cov(x, rowvar=False), cov(x, rowvar=False)) assert_almost_equal(np.cov(x, rowvar=False, bias=True), cov(x, rowvar=False, bias=True)) def test_1d_w_missing(self): "Test cov 1 1D variable w/missing values" x = self.data x[-1] = masked x -= x.mean() nx = x.compressed() assert_almost_equal(np.cov(nx), cov(x)) assert_almost_equal(np.cov(nx, rowvar=False), cov(x, rowvar=False)) assert_almost_equal(np.cov(nx, rowvar=False, bias=True), cov(x, rowvar=False, bias=True)) # try: cov(x, allow_masked=False) except ValueError: pass # # 2 1D variables w/ missing values nx = x[1:-1] assert_almost_equal(np.cov(nx, nx[::-1]), cov(x, x[::-1])) assert_almost_equal(np.cov(nx, nx[::-1], rowvar=False), cov(x, x[::-1], rowvar=False)) assert_almost_equal(np.cov(nx, nx[::-1], rowvar=False, bias=True), cov(x, x[::-1], rowvar=False, bias=True)) def test_2d_w_missing(self): "Test cov on 2D variable w/ missing value" x = self.data x[-1] = masked x = x.reshape(3, 4) valid = np.logical_not(getmaskarray(x)).astype(int) frac = np.dot(valid, valid.T) xf = (x - x.mean(1)[:, None]).filled(0) assert_almost_equal(cov(x), np.cov(xf) * (x.shape[1] - 1) / (frac - 1.)) assert_almost_equal(cov(x, bias=True), np.cov(xf, bias=True) * x.shape[1] / frac) frac = np.dot(valid.T, valid) xf = (x - x.mean(0)).filled(0) assert_almost_equal(cov(x, rowvar=False), (np.cov(xf, rowvar=False) * (x.shape[0] - 1) / (frac - 1.))) assert_almost_equal(cov(x, rowvar=False, bias=True), (np.cov(xf, rowvar=False, bias=True) * x.shape[0] / frac)) class TestCorrcoef(TestCase): def setUp(self): self.data = array(np.random.rand(12)) def test_ddof(self): "Test ddof keyword" x = self.data assert_almost_equal(np.corrcoef(x, ddof=0), corrcoef(x, ddof=0)) def test_1d_wo_missing(self): "Test cov on 1D variable w/o missing values" x = self.data assert_almost_equal(np.corrcoef(x), corrcoef(x)) assert_almost_equal(np.corrcoef(x, rowvar=False), corrcoef(x, rowvar=False)) assert_almost_equal(np.corrcoef(x, rowvar=False, bias=True), corrcoef(x, rowvar=False, bias=True)) def test_2d_wo_missing(self): "Test corrcoef on 1 2D variable w/o missing values" x = self.data.reshape(3, 4) assert_almost_equal(np.corrcoef(x), corrcoef(x)) assert_almost_equal(np.corrcoef(x, rowvar=False), corrcoef(x, rowvar=False)) assert_almost_equal(np.corrcoef(x, rowvar=False, bias=True), corrcoef(x, rowvar=False, bias=True)) def test_1d_w_missing(self): "Test corrcoef 1 1D variable w/missing values" x = self.data x[-1] = masked x -= x.mean() nx = x.compressed() assert_almost_equal(np.corrcoef(nx), corrcoef(x)) assert_almost_equal(np.corrcoef(nx, rowvar=False), corrcoef(x, rowvar=False)) assert_almost_equal(np.corrcoef(nx, rowvar=False, bias=True), corrcoef(x, rowvar=False, bias=True)) # try: corrcoef(x, allow_masked=False) except ValueError: pass # # 2 1D variables w/ missing values nx = x[1:-1] assert_almost_equal(np.corrcoef(nx, nx[::-1]), corrcoef(x, x[::-1])) assert_almost_equal(np.corrcoef(nx, nx[::-1], rowvar=False), corrcoef(x, x[::-1], rowvar=False)) assert_almost_equal(np.corrcoef(nx, nx[::-1], rowvar=False, bias=True), corrcoef(x, x[::-1], rowvar=False, bias=True)) def test_2d_w_missing(self): "Test corrcoef on 2D variable w/ missing value" x = self.data x[-1] = masked x = x.reshape(3, 4) test = corrcoef(x) control = np.corrcoef(x) assert_almost_equal(test[:-1, :-1], control[:-1, :-1]) class TestPolynomial(TestCase): # def test_polyfit(self): "Tests polyfit" # On ndarrays x = np.random.rand(10) y = np.random.rand(20).reshape(-1, 2) assert_almost_equal(polyfit(x, y, 3), np.polyfit(x, y, 3)) # ON 1D maskedarrays x = x.view(MaskedArray) x[0] = masked y = y.view(MaskedArray) y[0, 0] = y[-1, -1] = masked # (C, R, K, S, D) = polyfit(x, y[:, 0], 3, full=True) (c, r, k, s, d) = np.polyfit(x[1:], y[1:, 0].compressed(), 3, full=True) for (a, a_) in zip((C, R, K, S, D), (c, r, k, s, d)): assert_almost_equal(a, a_) # (C, R, K, S, D) = polyfit(x, y[:, -1], 3, full=True) (c, r, k, s, d) = np.polyfit(x[1:-1], y[1:-1, -1], 3, full=True) for (a, a_) in zip((C, R, K, S, D), (c, r, k, s, d)): assert_almost_equal(a, a_) # (C, R, K, S, D) = polyfit(x, y, 3, full=True) (c, r, k, s, d) = np.polyfit(x[1:-1], y[1:-1,:], 3, full=True) for (a, a_) in zip((C, R, K, S, D), (c, r, k, s, d)): assert_almost_equal(a, a_) # w = np.random.rand(10) + 1 wo = w.copy() xs = x[1:-1] ys = y[1:-1] ws = w[1:-1] (C, R, K, S, D) = polyfit(x, y, 3, full=True, w=w) (c, r, k, s, d) = np.polyfit(xs, ys, 3, full=True, w=ws) assert_equal(w, wo) for (a, a_) in zip((C, R, K, S, D), (c, r, k, s, d)): assert_almost_equal(a, a_) class TestArraySetOps(TestCase): def test_unique_onlist(self): "Test unique on list" data = [1, 1, 1, 2, 2, 3] test = unique(data, return_index=True, return_inverse=True) self.assertTrue(isinstance(test[0], MaskedArray)) assert_equal(test[0], masked_array([1, 2, 3], mask=[0, 0, 0])) assert_equal(test[1], [0, 3, 5]) assert_equal(test[2], [0, 0, 0, 1, 1, 2]) def test_unique_onmaskedarray(self): "Test unique on masked data w/use_mask=True" data = masked_array([1, 1, 1, 2, 2, 3], mask=[0, 0, 1, 0, 1, 0]) test = unique(data, return_index=True, return_inverse=True) assert_equal(test[0], masked_array([1, 2, 3, -1], mask=[0, 0, 0, 1])) assert_equal(test[1], [0, 3, 5, 2]) assert_equal(test[2], [0, 0, 3, 1, 3, 2]) # data.fill_value = 3 data = masked_array([1, 1, 1, 2, 2, 3], mask=[0, 0, 1, 0, 1, 0], fill_value=3) test = unique(data, return_index=True, return_inverse=True) assert_equal(test[0], masked_array([1, 2, 3, -1], mask=[0, 0, 0, 1])) assert_equal(test[1], [0, 3, 5, 2]) assert_equal(test[2], [0, 0, 3, 1, 3, 2]) def test_unique_allmasked(self): "Test all masked" data = masked_array([1, 1, 1], mask=True) test = unique(data, return_index=True, return_inverse=True) assert_equal(test[0], masked_array([1, ], mask=[True])) assert_equal(test[1], [0]) assert_equal(test[2], [0, 0, 0]) # "Test masked" data = masked test = unique(data, return_index=True, return_inverse=True) assert_equal(test[0], masked_array(masked)) assert_equal(test[1], [0]) assert_equal(test[2], [0]) def test_ediff1d(self): "Tests mediff1d" x = masked_array(np.arange(5), mask=[1, 0, 0, 0, 1]) control = array([1, 1, 1, 4], mask=[1, 0, 0, 1]) test = ediff1d(x) assert_equal(test, control) assert_equal(test.data, control.data) assert_equal(test.mask, control.mask) def test_ediff1d_tobegin(self): "Test ediff1d w/ to_begin" x = masked_array(np.arange(5), mask=[1, 0, 0, 0, 1]) test = ediff1d(x, to_begin=masked) control = array([0, 1, 1, 1, 4], mask=[1, 1, 0, 0, 1]) assert_equal(test, control) assert_equal(test.data, control.data) assert_equal(test.mask, control.mask) # test = ediff1d(x, to_begin=[1, 2, 3]) control = array([1, 2, 3, 1, 1, 1, 4], mask=[0, 0, 0, 1, 0, 0, 1]) assert_equal(test, control) assert_equal(test.data, control.data) assert_equal(test.mask, control.mask) def test_ediff1d_toend(self): "Test ediff1d w/ to_end" x = masked_array(np.arange(5), mask=[1, 0, 0, 0, 1]) test = ediff1d(x, to_end=masked) control = array([1, 1, 1, 4, 0], mask=[1, 0, 0, 1, 1]) assert_equal(test, control) assert_equal(test.data, control.data) assert_equal(test.mask, control.mask) # test = ediff1d(x, to_end=[1, 2, 3]) control = array([1, 1, 1, 4, 1, 2, 3], mask=[1, 0, 0, 1, 0, 0, 0]) assert_equal(test, control) assert_equal(test.data, control.data) assert_equal(test.mask, control.mask) def test_ediff1d_tobegin_toend(self): "Test ediff1d w/ to_begin and to_end" x = masked_array(np.arange(5), mask=[1, 0, 0, 0, 1]) test = ediff1d(x, to_end=masked, to_begin=masked) control = array([0, 1, 1, 1, 4, 0], mask=[1, 1, 0, 0, 1, 1]) assert_equal(test, control) assert_equal(test.data, control.data) assert_equal(test.mask, control.mask) # test = ediff1d(x, to_end=[1, 2, 3], to_begin=masked) control = array([0, 1, 1, 1, 4, 1, 2, 3], mask=[1, 1, 0, 0, 1, 0, 0, 0]) assert_equal(test, control) assert_equal(test.data, control.data) assert_equal(test.mask, control.mask) def test_ediff1d_ndarray(self): "Test ediff1d w/ a ndarray" x = np.arange(5) test = ediff1d(x) control = array([1, 1, 1, 1], mask=[0, 0, 0, 0]) assert_equal(test, control) self.assertTrue(isinstance(test, MaskedArray)) assert_equal(test.data, control.data) assert_equal(test.mask, control.mask) # test = ediff1d(x, to_end=masked, to_begin=masked) control = array([0, 1, 1, 1, 1, 0], mask=[1, 0, 0, 0, 0, 1]) self.assertTrue(isinstance(test, MaskedArray)) assert_equal(test.data, control.data) assert_equal(test.mask, control.mask) def test_intersect1d(self): "Test intersect1d" x = array([1, 3, 3, 3], mask=[0, 0, 0, 1]) y = array([3, 1, 1, 1], mask=[0, 0, 0, 1]) test = intersect1d(x, y) control = array([1, 3, -1], mask=[0, 0, 1]) assert_equal(test, control) def test_setxor1d(self): "Test setxor1d" a = array([1, 2, 5, 7, -1], mask=[0, 0, 0, 0, 1]) b = array([1, 2, 3, 4, 5, -1], mask=[0, 0, 0, 0, 0, 1]) test = setxor1d(a, b) assert_equal(test, array([3, 4, 7])) # a = array([1, 2, 5, 7, -1], mask=[0, 0, 0, 0, 1]) b = [1, 2, 3, 4, 5] test = setxor1d(a, b) assert_equal(test, array([3, 4, 7, -1], mask=[0, 0, 0, 1])) # a = array([1, 2, 3]) b = array([6, 5, 4]) test = setxor1d(a, b) assert_(isinstance(test, MaskedArray)) assert_equal(test, [1, 2, 3, 4, 5, 6]) # a = array([1, 8, 2, 3], mask=[0, 1, 0, 0]) b = array([6, 5, 4, 8], mask=[0, 0, 0, 1]) test = setxor1d(a, b) assert_(isinstance(test, MaskedArray)) assert_equal(test, [1, 2, 3, 4, 5, 6]) # assert_array_equal([], setxor1d([], [])) def test_in1d(self): "Test in1d" a = array([1, 2, 5, 7, -1], mask=[0, 0, 0, 0, 1]) b = array([1, 2, 3, 4, 5, -1], mask=[0, 0, 0, 0, 0, 1]) test = in1d(a, b) assert_equal(test, [True, True, True, False, True]) # a = array([5, 5, 2, 1, -1], mask=[0, 0, 0, 0, 1]) b = array([1, 5, -1], mask=[0, 0, 1]) test = in1d(a, b) assert_equal(test, [True, True, False, True, True]) # assert_array_equal([], in1d([], [])) def test_in1d_invert(self): "Test in1d's invert parameter" a = array([1, 2, 5, 7, -1], mask=[0, 0, 0, 0, 1]) b = array([1, 2, 3, 4, 5, -1], mask=[0, 0, 0, 0, 0, 1]) assert_equal(np.invert(in1d(a, b)), in1d(a, b, invert=True)) a = array([5, 5, 2, 1, -1], mask=[0, 0, 0, 0, 1]) b = array([1, 5, -1], mask=[0, 0, 1]) assert_equal(np.invert(in1d(a, b)), in1d(a, b, invert=True)) assert_array_equal([], in1d([], [], invert=True)) def test_union1d(self): "Test union1d" a = array([1, 2, 5, 7, 5, -1], mask=[0, 0, 0, 0, 0, 1]) b = array([1, 2, 3, 4, 5, -1], mask=[0, 0, 0, 0, 0, 1]) test = union1d(a, b) control = array([1, 2, 3, 4, 5, 7, -1], mask=[0, 0, 0, 0, 0, 0, 1]) assert_equal(test, control) # assert_array_equal([], union1d([], [])) def test_setdiff1d(self): "Test setdiff1d" a = array([6, 5, 4, 7, 7, 1, 2, 1], mask=[0, 0, 0, 0, 0, 0, 0, 1]) b = array([2, 4, 3, 3, 2, 1, 5]) test = setdiff1d(a, b) assert_equal(test, array([6, 7, -1], mask=[0, 0, 1])) # a = arange(10) b = arange(8) assert_equal(setdiff1d(a, b), array([8, 9])) def test_setdiff1d_char_array(self): "Test setdiff1d_charray" a = np.array(['a', 'b', 'c']) b = np.array(['a', 'b', 's']) assert_array_equal(setdiff1d(a, b), np.array(['c'])) class TestShapeBase(TestCase): # def test_atleast2d(self): "Test atleast_2d" a = masked_array([0, 1, 2], mask=[0, 1, 0]) b = atleast_2d(a) assert_equal(b.shape, (1, 3)) assert_equal(b.mask.shape, b.data.shape) assert_equal(a.shape, (3,)) assert_equal(a.mask.shape, a.data.shape) ############################################################################### #------------------------------------------------------------------------------ if __name__ == "__main__": run_module_suite() numpy-1.8.2/numpy/ma/tests/test_old_ma.py0000664000175100017510000010202112370216243021573 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function import sys from functools import reduce import numpy as np from numpy.ma import * from numpy.core.numerictypes import float32 from numpy.ma.core import umath from numpy.testing import * pi = np.pi def eq(v, w, msg=''): result = allclose(v, w) if not result: print("""Not eq:%s %s ---- %s""" % (msg, str(v), str(w))) return result class TestMa(TestCase): def setUp (self): x = np.array([1., 1., 1., -2., pi / 2.0, 4., 5., -10., 10., 1., 2., 3.]) y = np.array([5., 0., 3., 2., -1., -4., 0., -10., 10., 1., 0., 3.]) a10 = 10. m1 = [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0] m2 = [0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1] xm = array(x, mask=m1) ym = array(y, mask=m2) z = np.array([-.5, 0., .5, .8]) zm = array(z, mask=[0, 1, 0, 0]) xf = np.where(m1, 1e+20, x) s = x.shape xm.set_fill_value(1e+20) self.d = (x, y, a10, m1, m2, xm, ym, z, zm, xf, s) def test_testBasic1d(self): "Test of basic array creation and properties in 1 dimension." (x, y, a10, m1, m2, xm, ym, z, zm, xf, s) = self.d self.assertFalse(isMaskedArray(x)) self.assertTrue(isMaskedArray(xm)) self.assertEqual(shape(xm), s) self.assertEqual(xm.shape, s) self.assertEqual(xm.dtype, x.dtype) self.assertEqual(xm.size, reduce(lambda x, y:x * y, s)) self.assertEqual(count(xm), len(m1) - reduce(lambda x, y:x + y, m1)) self.assertTrue(eq(xm, xf)) self.assertTrue(eq(filled(xm, 1.e20), xf)) self.assertTrue(eq(x, xm)) def test_testBasic2d(self): "Test of basic array creation and properties in 2 dimensions." for s in [(4, 3), (6, 2)]: (x, y, a10, m1, m2, xm, ym, z, zm, xf, s) = self.d x.shape = s y.shape = s xm.shape = s ym.shape = s xf.shape = s self.assertFalse(isMaskedArray(x)) self.assertTrue(isMaskedArray(xm)) self.assertEqual(shape(xm), s) self.assertEqual(xm.shape, s) self.assertEqual(xm.size, reduce(lambda x, y:x * y, s)) self.assertEqual(count(xm), len(m1) - reduce(lambda x, y:x + y, m1)) self.assertTrue(eq(xm, xf)) self.assertTrue(eq(filled(xm, 1.e20), xf)) self.assertTrue(eq(x, xm)) self.setUp() def test_testArithmetic (self): "Test of basic arithmetic." (x, y, a10, m1, m2, xm, ym, z, zm, xf, s) = self.d a2d = array([[1, 2], [0, 4]]) a2dm = masked_array(a2d, [[0, 0], [1, 0]]) self.assertTrue(eq (a2d * a2d, a2d * a2dm)) self.assertTrue(eq (a2d + a2d, a2d + a2dm)) self.assertTrue(eq (a2d - a2d, a2d - a2dm)) for s in [(12,), (4, 3), (2, 6)]: x = x.reshape(s) y = y.reshape(s) xm = xm.reshape(s) ym = ym.reshape(s) xf = xf.reshape(s) self.assertTrue(eq(-x, -xm)) self.assertTrue(eq(x + y, xm + ym)) self.assertTrue(eq(x - y, xm - ym)) self.assertTrue(eq(x * y, xm * ym)) with np.errstate(divide='ignore', invalid='ignore'): self.assertTrue(eq(x / y, xm / ym)) self.assertTrue(eq(a10 + y, a10 + ym)) self.assertTrue(eq(a10 - y, a10 - ym)) self.assertTrue(eq(a10 * y, a10 * ym)) with np.errstate(divide='ignore', invalid='ignore'): self.assertTrue(eq(a10 / y, a10 / ym)) self.assertTrue(eq(x + a10, xm + a10)) self.assertTrue(eq(x - a10, xm - a10)) self.assertTrue(eq(x * a10, xm * a10)) self.assertTrue(eq(x / a10, xm / a10)) self.assertTrue(eq(x ** 2, xm ** 2)) self.assertTrue(eq(abs(x) ** 2.5, abs(xm) ** 2.5)) self.assertTrue(eq(x ** y, xm ** ym)) self.assertTrue(eq(np.add(x, y), add(xm, ym))) self.assertTrue(eq(np.subtract(x, y), subtract(xm, ym))) self.assertTrue(eq(np.multiply(x, y), multiply(xm, ym))) with np.errstate(divide='ignore', invalid='ignore'): self.assertTrue(eq(np.divide(x, y), divide(xm, ym))) def test_testMixedArithmetic(self): na = np.array([1]) ma = array([1]) self.assertTrue(isinstance(na + ma, MaskedArray)) self.assertTrue(isinstance(ma + na, MaskedArray)) def test_testUfuncs1 (self): "Test various functions such as sin, cos." (x, y, a10, m1, m2, xm, ym, z, zm, xf, s) = self.d self.assertTrue (eq(np.cos(x), cos(xm))) self.assertTrue (eq(np.cosh(x), cosh(xm))) self.assertTrue (eq(np.sin(x), sin(xm))) self.assertTrue (eq(np.sinh(x), sinh(xm))) self.assertTrue (eq(np.tan(x), tan(xm))) self.assertTrue (eq(np.tanh(x), tanh(xm))) with np.errstate(divide='ignore', invalid='ignore'): self.assertTrue (eq(np.sqrt(abs(x)), sqrt(xm))) self.assertTrue (eq(np.log(abs(x)), log(xm))) self.assertTrue (eq(np.log10(abs(x)), log10(xm))) self.assertTrue (eq(np.exp(x), exp(xm))) self.assertTrue (eq(np.arcsin(z), arcsin(zm))) self.assertTrue (eq(np.arccos(z), arccos(zm))) self.assertTrue (eq(np.arctan(z), arctan(zm))) self.assertTrue (eq(np.arctan2(x, y), arctan2(xm, ym))) self.assertTrue (eq(np.absolute(x), absolute(xm))) self.assertTrue (eq(np.equal(x, y), equal(xm, ym))) self.assertTrue (eq(np.not_equal(x, y), not_equal(xm, ym))) self.assertTrue (eq(np.less(x, y), less(xm, ym))) self.assertTrue (eq(np.greater(x, y), greater(xm, ym))) self.assertTrue (eq(np.less_equal(x, y), less_equal(xm, ym))) self.assertTrue (eq(np.greater_equal(x, y), greater_equal(xm, ym))) self.assertTrue (eq(np.conjugate(x), conjugate(xm))) self.assertTrue (eq(np.concatenate((x, y)), concatenate((xm, ym)))) self.assertTrue (eq(np.concatenate((x, y)), concatenate((x, y)))) self.assertTrue (eq(np.concatenate((x, y)), concatenate((xm, y)))) self.assertTrue (eq(np.concatenate((x, y, x)), concatenate((x, ym, x)))) 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.assertEqual(3, count(ott)) self.assertEqual(1, count(1)) self.assertTrue (eq(0, array(1, mask=[1]))) ott = ott.reshape((2, 2)) 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 (eq(3, count(ott))) assert_(getmask(count(ott, 0)) is nomask) self.assertTrue (eq([1, 2], count(ott, 0))) def test_testMinMax (self): "Test minimum and maximum." (x, y, a10, m1, m2, xm, ym, z, zm, xf, s) = self.d xr = np.ravel(x) #max doesn't work if shaped xmr = ravel(xm) #true because of careful selection of data self.assertTrue(eq(max(xr), maximum(xmr))) #true because of careful selection of data self.assertTrue(eq(min(xr), minimum(xmr))) def test_testAddSumProd (self): "Test add, sum, product." (x, y, a10, m1, m2, xm, ym, z, zm, xf, s) = self.d self.assertTrue (eq(np.add.reduce(x), add.reduce(x))) self.assertTrue (eq(np.add.accumulate(x), add.accumulate(x))) self.assertTrue (eq(4, sum(array(4), axis=0))) self.assertTrue (eq(4, sum(array(4), axis=0))) self.assertTrue (eq(np.sum(x, axis=0), sum(x, axis=0))) self.assertTrue (eq(np.sum(filled(xm, 0), axis=0), sum(xm, axis=0))) self.assertTrue (eq(np.sum(x, 0), sum(x, 0))) self.assertTrue (eq(np.product(x, axis=0), product(x, axis=0))) self.assertTrue (eq(np.product(x, 0), product(x, 0))) self.assertTrue (eq(np.product(filled(xm, 1), axis=0), product(xm, axis=0))) if len(s) > 1: self.assertTrue (eq(np.concatenate((x, y), 1), concatenate((xm, ym), 1))) self.assertTrue (eq(np.add.reduce(x, 1), add.reduce(x, 1))) self.assertTrue (eq(np.sum(x, 1), sum(x, 1))) self.assertTrue (eq(np.product(x, 1), product(x, 1))) def test_testCI(self): "Test of conversions and indexing" x1 = np.array([1, 2, 4, 3]) x2 = array(x1, mask=[1, 0, 0, 0]) x3 = array(x1, mask=[0, 1, 0, 1]) x4 = array(x1) # test conversion to strings junk, garbage = str(x2), repr(x2) assert_(eq(np.sort(x1), sort(x2, fill_value=0))) # tests of indexing assert_(type(x2[1]) is type(x1[1])) assert_(x1[1] == x2[1]) assert_(x2[0] is masked) assert_(eq(x1[2], x2[2])) assert_(eq(x1[2:5], x2[2:5])) assert_(eq(x1[:], x2[:])) assert_(eq(x1[1:], x3[1:])) x1[2] = 9 x2[2] = 9 assert_(eq(x1, x2)) x1[1:3] = 99 x2[1:3] = 99 assert_(eq(x1, x2)) x2[1] = masked assert_(eq(x1, x2)) x2[1:3] = masked assert_(eq(x1, x2)) x2[:] = x1 x2[1] = masked assert_(allequal(getmask(x2), array([0, 1, 0, 0]))) x3[:] = masked_array([1, 2, 3, 4], [0, 1, 1, 0]) assert_(allequal(getmask(x3), array([0, 1, 1, 0]))) x4[:] = masked_array([1, 2, 3, 4], [0, 1, 1, 0]) assert_(allequal(getmask(x4), array([0, 1, 1, 0]))) assert_(allequal(x4, array([1, 2, 3, 4]))) x1 = np.arange(5) * 1.0 x2 = masked_values(x1, 3.0) assert_(eq(x1, x2)) assert_(allequal(array([0, 0, 0, 1, 0], MaskType), x2.mask)) assert_(eq(3.0, x2.fill_value)) x1 = array([1, 'hello', 2, 3], object) x2 = np.array([1, 'hello', 2, 3], object) s1 = x1[1] s2 = x2[1] self.assertEqual(type(s2), str) self.assertEqual(type(s1), str) self.assertEqual(s1, s2) assert_(x1[1:1].shape == (0,)) def test_testCopySize(self): "Tests of some subtle points of copying and sizing." n = [0, 0, 1, 0, 0] m = make_mask(n) m2 = make_mask(m) self.assertTrue(m is m2) m3 = make_mask(m, copy=1) self.assertTrue(m is not m3) x1 = np.arange(5) y1 = array(x1, mask=m) self.assertTrue(y1._data is not x1) self.assertTrue(allequal(x1, y1._data)) self.assertTrue(y1.mask is m) y1a = array(y1, copy=0) self.assertTrue(y1a.mask is y1.mask) y2 = array(x1, mask=m, copy=0) self.assertTrue(y2.mask is m) self.assertTrue(y2[2] is masked) y2[2] = 9 self.assertTrue(y2[2] is not masked) self.assertTrue(y2.mask is not m) self.assertTrue(allequal(y2.mask, 0)) y3 = array(x1 * 1.0, mask=m) self.assertTrue(filled(y3).dtype is (x1 * 1.0).dtype) x4 = arange(4) x4[2] = masked y4 = resize(x4, (8,)) self.assertTrue(eq(concatenate([x4, x4]), y4)) self.assertTrue(eq(getmask(y4), [0, 0, 1, 0, 0, 0, 1, 0])) y5 = repeat(x4, (2, 2, 2, 2), axis=0) self.assertTrue(eq(y5, [0, 0, 1, 1, 2, 2, 3, 3])) y6 = repeat(x4, 2, axis=0) self.assertTrue(eq(y5, y6)) def test_testPut(self): "Test of put" d = arange(5) n = [0, 0, 0, 1, 1] m = make_mask(n) x = array(d, mask=m) self.assertTrue(x[3] is masked) self.assertTrue(x[4] is masked) x[[1, 4]] = [10, 40] self.assertTrue(x.mask is not m) self.assertTrue(x[3] is masked) self.assertTrue(x[4] is not masked) self.assertTrue(eq(x, [0, 10, 2, -1, 40])) x = array(d, mask=m) x.put([0, 1, 2], [-1, 100, 200]) self.assertTrue(eq(x, [-1, 100, 200, 0, 0])) self.assertTrue(x[3] is masked) self.assertTrue(x[4] is masked) def test_testMaPut(self): (x, y, a10, m1, m2, xm, ym, z, zm, xf, s) = self.d m = [1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1] i = np.nonzero(m)[0] put(ym, i, zm) assert_(all(take(ym, i, axis=0) == zm)) def test_testOddFeatures(self): "Test of other odd features" x = arange(20); x = x.reshape(4, 5) x.flat[5] = 12 assert_(x[1, 0] == 12) z = x + 10j * x assert_(eq(z.real, x)) assert_(eq(z.imag, 10 * x)) assert_(eq((z * conjugate(z)).real, 101 * x * x)) z.imag[...] = 0.0 x = arange(10) x[3] = masked assert_(str(x[3]) == str(masked)) c = x >= 8 assert_(count(where(c, masked, masked)) == 0) assert_(shape(where(c, masked, masked)) == c.shape) z = where(c, x, masked) assert_(z.dtype is x.dtype) assert_(z[3] is masked) assert_(z[4] is masked) assert_(z[7] is masked) assert_(z[8] is not masked) assert_(z[9] is not masked) assert_(eq(x, z)) z = where(c, masked, x) assert_(z.dtype is x.dtype) assert_(z[3] is masked) assert_(z[4] is not masked) assert_(z[7] is not masked) assert_(z[8] is masked) assert_(z[9] is masked) z = masked_where(c, x) assert_(z.dtype is x.dtype) assert_(z[3] is masked) assert_(z[4] is not masked) assert_(z[7] is not masked) assert_(z[8] is masked) assert_(z[9] is masked) assert_(eq(x, z)) x = array([1., 2., 3., 4., 5.]) c = array([1, 1, 1, 0, 0]) x[2] = masked z = where(c, x, -x) assert_(eq(z, [1., 2., 0., -4., -5])) c[0] = masked z = where(c, x, -x) assert_(eq(z, [1., 2., 0., -4., -5])) assert_(z[0] is masked) assert_(z[1] is not masked) assert_(z[2] is masked) assert_(eq(masked_where(greater(x, 2), x), masked_greater(x, 2))) assert_(eq(masked_where(greater_equal(x, 2), x), masked_greater_equal(x, 2))) assert_(eq(masked_where(less(x, 2), x), masked_less(x, 2))) assert_(eq(masked_where(less_equal(x, 2), x), masked_less_equal(x, 2))) assert_(eq(masked_where(not_equal(x, 2), x), masked_not_equal(x, 2))) assert_(eq(masked_where(equal(x, 2), x), masked_equal(x, 2))) assert_(eq(masked_where(not_equal(x, 2), x), masked_not_equal(x, 2))) assert_(eq(masked_inside(list(range(5)), 1, 3), [0, 199, 199, 199, 4])) assert_(eq(masked_outside(list(range(5)), 1, 3), [199, 1, 2, 3, 199])) assert_(eq(masked_inside(array(list(range(5)), mask=[1, 0, 0, 0, 0]), 1, 3).mask, [1, 1, 1, 1, 0])) assert_(eq(masked_outside(array(list(range(5)), mask=[0, 1, 0, 0, 0]), 1, 3).mask, [1, 1, 0, 0, 1])) assert_(eq(masked_equal(array(list(range(5)), mask=[1, 0, 0, 0, 0]), 2).mask, [1, 0, 1, 0, 0])) assert_(eq(masked_not_equal(array([2, 2, 1, 2, 1], mask=[1, 0, 0, 0, 0]), 2).mask, [1, 0, 1, 0, 1])) assert_(eq(masked_where([1, 1, 0, 0, 0], [1, 2, 3, 4, 5]), [99, 99, 3, 4, 5])) atest = ones((10, 10, 10), dtype=float32) btest = zeros(atest.shape, MaskType) ctest = masked_where(btest, atest) assert_(eq(atest, ctest)) z = choose(c, (-x, x)) assert_(eq(z, [1., 2., 0., -4., -5])) assert_(z[0] is masked) assert_(z[1] is not masked) assert_(z[2] is masked) x = arange(6) x[5] = masked y = arange(6) * 10 y[2] = masked c = array([1, 1, 1, 0, 0, 0], mask=[1, 0, 0, 0, 0, 0]) cm = c.filled(1) z = where(c, x, y) zm = where(cm, x, y) assert_(eq(z, zm)) assert_(getmask(zm) is nomask) assert_(eq(zm, [0, 1, 2, 30, 40, 50])) z = where(c, masked, 1) assert_(eq(z, [99, 99, 99, 1, 1, 1])) z = where(c, 1, masked) assert_(eq(z, [99, 1, 1, 99, 99, 99])) def test_testMinMax2(self): "Test of minumum, maximum." assert_(eq(minimum([1, 2, 3], [4, 0, 9]), [1, 0, 3])) assert_(eq(maximum([1, 2, 3], [4, 0, 9]), [4, 2, 9])) x = arange(5) y = arange(5) - 2 x[3] = masked y[0] = masked assert_(eq(minimum(x, y), where(less(x, y), x, y))) assert_(eq(maximum(x, y), where(greater(x, y), x, y))) assert_(minimum(x) == 0) assert_(maximum(x) == 4) def test_testTakeTransposeInnerOuter(self): "Test of take, transpose, inner, outer products" x = arange(24) y = np.arange(24) x[5:6] = masked x = x.reshape(2, 3, 4) y = y.reshape(2, 3, 4) assert_(eq(np.transpose(y, (2, 0, 1)), transpose(x, (2, 0, 1)))) assert_(eq(np.take(y, (2, 0, 1), 1), take(x, (2, 0, 1), 1))) assert_(eq(np.inner(filled(x, 0), filled(y, 0)), inner(x, y))) assert_(eq(np.outer(filled(x, 0), filled(y, 0)), outer(x, y))) y = array(['abc', 1, 'def', 2, 3], object) y[2] = masked t = take(y, [0, 3, 4]) assert_(t[0] == 'abc') assert_(t[1] == 2) assert_(t[2] == 3) def test_testInplace(self): """Test of inplace operations and rich comparisons""" y = arange(10) x = arange(10) xm = arange(10) xm[2] = masked x += 1 assert_(eq(x, y + 1)) xm += 1 assert_(eq(x, y + 1)) x = arange(10) xm = arange(10) xm[2] = masked x -= 1 assert_(eq(x, y - 1)) xm -= 1 assert_(eq(xm, y - 1)) x = arange(10) * 1.0 xm = arange(10) * 1.0 xm[2] = masked x *= 2.0 assert_(eq(x, y * 2)) xm *= 2.0 assert_(eq(xm, y * 2)) x = arange(10) * 2 xm = arange(10) xm[2] = masked x //= 2 assert_(eq(x, y)) xm //= 2 assert_(eq(x, y)) x = arange(10) * 1.0 xm = arange(10) * 1.0 xm[2] = masked x /= 2.0 assert_(eq(x, y / 2.0)) xm /= arange(10) assert_(eq(xm, ones((10,)))) x = arange(10).astype(float32) xm = arange(10) xm[2] = masked x += 1. assert_(eq(x, y + 1.)) def test_testPickle(self): "Test of pickling" import pickle x = arange(12) x[4:10:2] = masked x = x.reshape(4, 3) s = pickle.dumps(x) y = pickle.loads(s) assert_(eq(x, y)) def test_testMasked(self): "Test of masked element" xx = arange(6) xx[1] = masked self.assertTrue(str(masked) == '--') self.assertTrue(xx[1] is masked) self.assertEqual(filled(xx[1], 0), 0) # don't know why these should raise an exception... #self.assertRaises(Exception, lambda x,y: x+y, masked, masked) #self.assertRaises(Exception, lambda x,y: x+y, masked, 2) #self.assertRaises(Exception, lambda x,y: x+y, masked, xx) #self.assertRaises(Exception, lambda x,y: x+y, xx, masked) def test_testAverage1(self): "Test of average." ott = array([0., 1., 2., 3.], mask=[1, 0, 0, 0]) self.assertTrue(eq(2.0, average(ott, axis=0))) self.assertTrue(eq(2.0, average(ott, weights=[1., 1., 2., 1.]))) result, wts = average(ott, weights=[1., 1., 2., 1.], returned=1) self.assertTrue(eq(2.0, result)) self.assertTrue(wts == 4.0) ott[:] = masked self.assertTrue(average(ott, axis=0) is masked) ott = array([0., 1., 2., 3.], mask=[1, 0, 0, 0]) ott = ott.reshape(2, 2) ott[:, 1] = masked self.assertTrue(eq(average(ott, axis=0), [2.0, 0.0])) self.assertTrue(average(ott, axis=1)[0] is masked) self.assertTrue(eq([2., 0.], average(ott, axis=0))) result, wts = average(ott, axis=0, returned=1) self.assertTrue(eq(wts, [1., 0.])) def test_testAverage2(self): "More tests of average." w1 = [0, 1, 1, 1, 1, 0] w2 = [[0, 1, 1, 1, 1, 0], [1, 0, 0, 0, 0, 1]] x = arange(6) self.assertTrue(allclose(average(x, axis=0), 2.5)) self.assertTrue(allclose(average(x, axis=0, weights=w1), 2.5)) y = array([arange(6), 2.0 * arange(6)]) self.assertTrue(allclose(average(y, None), np.add.reduce(np.arange(6)) * 3. / 12.)) self.assertTrue(allclose(average(y, axis=0), np.arange(6) * 3. / 2.)) self.assertTrue(allclose(average(y, axis=1), [average(x, axis=0), average(x, axis=0) * 2.0])) self.assertTrue(allclose(average(y, None, weights=w2), 20. / 6.)) self.assertTrue(allclose(average(y, axis=0, weights=w2), [0., 1., 2., 3., 4., 10.])) self.assertTrue(allclose(average(y, axis=1), [average(x, axis=0), average(x, axis=0) * 2.0])) m1 = zeros(6) m2 = [0, 0, 1, 1, 0, 0] m3 = [[0, 0, 1, 1, 0, 0], [0, 1, 1, 1, 1, 0]] m4 = ones(6) m5 = [0, 1, 1, 1, 1, 1] self.assertTrue(allclose(average(masked_array(x, m1), axis=0), 2.5)) self.assertTrue(allclose(average(masked_array(x, m2), axis=0), 2.5)) self.assertTrue(average(masked_array(x, m4), axis=0) is masked) self.assertEqual(average(masked_array(x, m5), axis=0), 0.0) self.assertEqual(count(average(masked_array(x, m4), axis=0)), 0) z = masked_array(y, m3) self.assertTrue(allclose(average(z, None), 20. / 6.)) self.assertTrue(allclose(average(z, axis=0), [0., 1., 99., 99., 4.0, 7.5])) self.assertTrue(allclose(average(z, axis=1), [2.5, 5.0])) self.assertTrue(allclose(average(z, axis=0, weights=w2), [0., 1., 99., 99., 4.0, 10.0])) a = arange(6) b = arange(6) * 3 r1, w1 = average([[a, b], [b, a]], axis=1, returned=1) self.assertEqual(shape(r1), shape(w1)) self.assertEqual(r1.shape, w1.shape) r2, w2 = average(ones((2, 2, 3)), axis=0, weights=[3, 1], returned=1) self.assertEqual(shape(w2), shape(r2)) r2, w2 = average(ones((2, 2, 3)), returned=1) self.assertEqual(shape(w2), shape(r2)) r2, w2 = average(ones((2, 2, 3)), weights=ones((2, 2, 3)), returned=1) self.assertTrue(shape(w2) == shape(r2)) a2d = array([[1, 2], [0, 4]], float) a2dm = masked_array(a2d, [[0, 0], [1, 0]]) a2da = average(a2d, axis=0) self.assertTrue(eq (a2da, [0.5, 3.0])) a2dma = average(a2dm, axis=0) self.assertTrue(eq(a2dma, [1.0, 3.0])) a2dma = average(a2dm, axis=None) self.assertTrue(eq(a2dma, 7. / 3.)) a2dma = average(a2dm, axis=1) self.assertTrue(eq(a2dma, [1.5, 4.0])) def test_testToPython(self): self.assertEqual(1, int(array(1))) self.assertEqual(1.0, float(array(1))) self.assertEqual(1, int(array([[[1]]]))) self.assertEqual(1.0, float(array([[1]]))) self.assertRaises(TypeError, float, array([1, 1])) self.assertRaises(ValueError, bool, array([0, 1])) self.assertRaises(ValueError, bool, array([0, 0], mask=[0, 1])) 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') self.assertTrue((1 / array(0)).mask) self.assertTrue((1 + xm).mask) self.assertTrue((-xm).mask) self.assertTrue((-xm).mask) self.assertTrue(maximum(xm, xm).mask) self.assertTrue(minimum(xm, xm).mask) self.assertTrue(xm.filled().dtype is xm._data.dtype) x = array(0, mask=0) self.assertTrue(x.filled() == x._data) self.assertEqual(str(xm), str(masked_print_option)) def test_testArrayMethods(self): a = array([1, 3, 2]) b = array([1, 3, 2], mask=[1, 0, 1]) self.assertTrue(eq(a.any(), a._data.any())) self.assertTrue(eq(a.all(), a._data.all())) self.assertTrue(eq(a.argmax(), a._data.argmax())) self.assertTrue(eq(a.argmin(), a._data.argmin())) self.assertTrue(eq(a.choose(0, 1, 2, 3, 4), a._data.choose(0, 1, 2, 3, 4))) self.assertTrue(eq(a.compress([1, 0, 1]), a._data.compress([1, 0, 1]))) self.assertTrue(eq(a.conj(), a._data.conj())) self.assertTrue(eq(a.conjugate(), a._data.conjugate())) m = array([[1, 2], [3, 4]]) self.assertTrue(eq(m.diagonal(), m._data.diagonal())) self.assertTrue(eq(a.sum(), a._data.sum())) self.assertTrue(eq(a.take([1, 2]), a._data.take([1, 2]))) self.assertTrue(eq(m.transpose(), m._data.transpose())) def test_testArrayAttributes(self): a = array([1, 3, 2]) b = array([1, 3, 2], mask=[1, 0, 1]) self.assertEqual(a.ndim, 1) def test_testAPI(self): self.assertFalse([m for m in dir(np.ndarray) if m not in dir(MaskedArray) and not m.startswith('_')]) def test_testSingleElementSubscript(self): a = array([1, 3, 2]) b = array([1, 3, 2], mask=[1, 0, 1]) self.assertEqual(a[0].shape, ()) self.assertEqual(b[0].shape, ()) self.assertEqual(b[1].shape, ()) class TestUfuncs(TestCase): def setUp(self): self.d = (array([1.0, 0, -1, pi / 2] * 2, mask=[0, 1] + [0] * 6), array([1.0, 0, -1, pi / 2] * 2, mask=[1, 0] + [0] * 6),) def test_testUfuncRegression(self): f_invalid_ignore = ['sqrt', 'arctanh', 'arcsin', 'arccos', 'arccosh', 'arctanh', 'log', 'log10', 'divide', 'true_divide', 'floor_divide', 'remainder', 'fmod'] for f in ['sqrt', 'log', 'log10', 'exp', 'conjugate', 'sin', 'cos', 'tan', 'arcsin', 'arccos', 'arctan', 'sinh', 'cosh', 'tanh', 'arcsinh', 'arccosh', 'arctanh', 'absolute', 'fabs', 'negative', # 'nonzero', 'around', 'floor', 'ceil', # 'sometrue', 'alltrue', 'logical_not', 'add', 'subtract', 'multiply', 'divide', 'true_divide', 'floor_divide', 'remainder', 'fmod', 'hypot', 'arctan2', 'equal', 'not_equal', 'less_equal', 'greater_equal', 'less', 'greater', 'logical_and', 'logical_or', 'logical_xor', ]: try: uf = getattr(umath, f) except AttributeError: uf = getattr(fromnumeric, f) mf = getattr(np.ma, f) args = self.d[:uf.nin] with np.errstate(): if f in f_invalid_ignore: np.seterr(invalid='ignore') if f in ['arctanh', 'log', 'log10']: np.seterr(divide='ignore') ur = uf(*args) mr = mf(*args) self.assertTrue(eq(ur.filled(0), mr.filled(0), f)) self.assertTrue(eqmask(ur.mask, mr.mask)) def test_reduce(self): a = self.d[0] self.assertFalse(alltrue(a, axis=0)) self.assertTrue(sometrue(a, axis=0)) self.assertEqual(sum(a[:3], axis=0), 0) self.assertEqual(product(a, axis=0), 0) def test_minmax(self): a = arange(1, 13).reshape(3, 4) amask = masked_where(a < 5, a) self.assertEqual(amask.max(), a.max()) self.assertEqual(amask.min(), 5) self.assertTrue((amask.max(0) == a.max(0)).all()) self.assertTrue((amask.min(0) == [5, 6, 7, 8]).all()) self.assertTrue(amask.max(1)[0].mask) self.assertTrue(amask.min(1)[0].mask) def test_nonzero(self): for t in "?bhilqpBHILQPfdgFDGO": x = array([1, 0, 2, 0], mask=[0, 0, 1, 1]) self.assertTrue(eq(nonzero(x), [0])) class TestArrayMethods(TestCase): def setUp(self): x = np.array([ 8.375, 7.545, 8.828, 8.5, 1.757, 5.928, 8.43, 7.78, 9.865, 5.878, 8.979, 4.732, 3.012, 6.022, 5.095, 3.116, 5.238, 3.957, 6.04, 9.63, 7.712, 3.382, 4.489, 6.479, 7.189, 9.645, 5.395, 4.961, 9.894, 2.893, 7.357, 9.828, 6.272, 3.758, 6.693, 0.993]) X = x.reshape(6, 6) XX = x.reshape(3, 2, 2, 3) m = np.array([0, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0]) mx = array(data=x, mask=m) mX = array(data=X, mask=m.reshape(X.shape)) mXX = array(data=XX, mask=m.reshape(XX.shape)) m2 = np.array([1, 1, 0, 1, 0, 0, 1, 1, 1, 1, 0, 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 1]) m2x = array(data=x, mask=m2) m2X = array(data=X, mask=m2.reshape(X.shape)) m2XX = array(data=XX, mask=m2.reshape(XX.shape)) self.d = (x, X, XX, m, mx, mX, mXX) #------------------------------------------------------ def test_trace(self): (x, X, XX, m, mx, mX, mXX,) = self.d mXdiag = mX.diagonal() self.assertEqual(mX.trace(), mX.diagonal().compressed().sum()) self.assertTrue(eq(mX.trace(), X.trace() - sum(mXdiag.mask * X.diagonal(), axis=0))) def test_clip(self): (x, X, XX, m, mx, mX, mXX,) = self.d clipped = mx.clip(2, 8) self.assertTrue(eq(clipped.mask, mx.mask)) self.assertTrue(eq(clipped._data, x.clip(2, 8))) self.assertTrue(eq(clipped._data, mx._data.clip(2, 8))) def test_ptp(self): (x, X, XX, m, mx, mX, mXX,) = self.d (n, m) = X.shape self.assertEqual(mx.ptp(), mx.compressed().ptp()) rows = np.zeros(n, np.float_) cols = np.zeros(m, np.float_) for k in range(m): cols[k] = mX[:, k].compressed().ptp() for k in range(n): rows[k] = mX[k].compressed().ptp() self.assertTrue(eq(mX.ptp(0), cols)) self.assertTrue(eq(mX.ptp(1), rows)) def test_swapaxes(self): (x, X, XX, m, mx, mX, mXX,) = self.d mXswapped = mX.swapaxes(0, 1) self.assertTrue(eq(mXswapped[-1], mX[:, -1])) mXXswapped = mXX.swapaxes(0, 2) self.assertEqual(mXXswapped.shape, (2, 2, 3, 3)) def test_cumprod(self): (x, X, XX, m, mx, mX, mXX,) = self.d mXcp = mX.cumprod(0) self.assertTrue(eq(mXcp._data, mX.filled(1).cumprod(0))) mXcp = mX.cumprod(1) self.assertTrue(eq(mXcp._data, mX.filled(1).cumprod(1))) def test_cumsum(self): (x, X, XX, m, mx, mX, mXX,) = self.d mXcp = mX.cumsum(0) self.assertTrue(eq(mXcp._data, mX.filled(0).cumsum(0))) mXcp = mX.cumsum(1) self.assertTrue(eq(mXcp._data, mX.filled(0).cumsum(1))) def test_varstd(self): (x, X, XX, m, mx, mX, mXX,) = self.d self.assertTrue(eq(mX.var(axis=None), mX.compressed().var())) self.assertTrue(eq(mX.std(axis=None), mX.compressed().std())) self.assertTrue(eq(mXX.var(axis=3).shape, XX.var(axis=3).shape)) self.assertTrue(eq(mX.var().shape, X.var().shape)) (mXvar0, mXvar1) = (mX.var(axis=0), mX.var(axis=1)) for k in range(6): self.assertTrue(eq(mXvar1[k], mX[k].compressed().var())) self.assertTrue(eq(mXvar0[k], mX[:, k].compressed().var())) self.assertTrue(eq(np.sqrt(mXvar0[k]), mX[:, k].compressed().std())) def eqmask(m1, m2): if m1 is nomask: return m2 is nomask if m2 is nomask: return m1 is nomask return (m1 == m2).all() #def timingTest(): # for f in [testf, testinplace]: # for n in [1000,10000,50000]: # t = testta(n, f) # t1 = testtb(n, f) # t2 = testtc(n, f) # print f.test_name # print """\ #n = %7d #numpy time (ms) %6.1f #MA maskless ratio %6.1f #MA masked ratio %6.1f #""" % (n, t*1000.0, t1/t, t2/t) #def testta(n, f): # x=np.arange(n) + 1.0 # tn0 = time.time() # z = f(x) # return time.time() - tn0 #def testtb(n, f): # x=arange(n) + 1.0 # tn0 = time.time() # z = f(x) # return time.time() - tn0 #def testtc(n, f): # x=arange(n) + 1.0 # x[0] = masked # tn0 = time.time() # z = f(x) # return time.time() - tn0 #def testf(x): # for i in range(25): # y = x **2 + 2.0 * x - 1.0 # w = x **2 + 1.0 # z = (y / w) ** 2 # return z #testf.test_name = 'Simple arithmetic' #def testinplace(x): # for i in range(25): # y = x**2 # y += 2.0*x # y -= 1.0 # y /= x # return y #testinplace.test_name = 'Inplace operations' if __name__ == "__main__": run_module_suite() numpy-1.8.2/numpy/ma/tests/test_subclassing.py0000664000175100017510000001436012370216243022665 0ustar vagrantvagrant00000000000000# pylint: disable-msg=W0611, W0612, W0511,R0201 """Tests suite for MaskedArray & subclassing. :author: Pierre Gerard-Marchant :contact: pierregm_at_uga_dot_edu :version: $Id: test_subclassing.py 3473 2007-10-29 15:18:13Z jarrod.millman $ """ from __future__ import division, absolute_import, print_function __author__ = "Pierre GF Gerard-Marchant ($Author: jarrod.millman $)" __version__ = '1.0' __revision__ = "$Revision: 3473 $" __date__ = '$Date: 2007-10-29 17:18:13 +0200 (Mon, 29 Oct 2007) $' import numpy as np from numpy.testing import * from numpy.ma.testutils import * from numpy.ma.core import * class SubArray(np.ndarray): """Defines a generic np.ndarray subclass, that stores some metadata in the dictionary `info`.""" def __new__(cls,arr,info={}): x = np.asanyarray(arr).view(cls) x.info = info return x def __array_finalize__(self, obj): self.info = getattr(obj, 'info', {}) return def __add__(self, other): result = np.ndarray.__add__(self, other) result.info.update({'added':result.info.pop('added', 0)+1}) return result subarray = SubArray class MSubArray(SubArray, MaskedArray): def __new__(cls, data, info={}, mask=nomask): subarr = SubArray(data, info) _data = MaskedArray.__new__(cls, data=subarr, mask=mask) _data.info = subarr.info return _data def __array_finalize__(self, obj): MaskedArray.__array_finalize__(self, obj) SubArray.__array_finalize__(self, obj) return def _get_series(self): _view = self.view(MaskedArray) _view._sharedmask = False return _view _series = property(fget=_get_series) msubarray = MSubArray class MMatrix(MaskedArray, np.matrix,): def __new__(cls, data, mask=nomask): mat = np.matrix(data) _data = MaskedArray.__new__(cls, data=mat, mask=mask) return _data def __array_finalize__(self, obj): np.matrix.__array_finalize__(self, obj) MaskedArray.__array_finalize__(self, obj) return def _get_series(self): _view = self.view(MaskedArray) _view._sharedmask = False return _view _series = property(fget=_get_series) mmatrix = MMatrix class TestSubclassing(TestCase): """Test suite for masked subclasses of ndarray.""" def setUp(self): x = np.arange(5) mx = mmatrix(x, mask=[0, 1, 0, 0, 0]) self.data = (x, mx) def test_data_subclassing(self): "Tests whether the subclass is kept." x = np.arange(5) m = [0, 0, 1, 0, 0] xsub = SubArray(x) xmsub = masked_array(xsub, mask=m) self.assertTrue(isinstance(xmsub, MaskedArray)) assert_equal(xmsub._data, xsub) self.assertTrue(isinstance(xmsub._data, SubArray)) def test_maskedarray_subclassing(self): "Tests subclassing MaskedArray" (x, mx) = self.data self.assertTrue(isinstance(mx._data, np.matrix)) def test_masked_unary_operations(self): "Tests masked_unary_operation" (x, mx) = self.data with np.errstate(divide='ignore'): self.assertTrue(isinstance(log(mx), mmatrix)) assert_equal(log(x), np.log(x)) def test_masked_binary_operations(self): "Tests masked_binary_operation" (x, mx) = self.data # Result should be a mmatrix self.assertTrue(isinstance(add(mx, mx), mmatrix)) self.assertTrue(isinstance(add(mx, x), mmatrix)) # Result should work assert_equal(add(mx, x), mx+x) self.assertTrue(isinstance(add(mx, mx)._data, np.matrix)) self.assertTrue(isinstance(add.outer(mx, mx), mmatrix)) self.assertTrue(isinstance(hypot(mx, mx), mmatrix)) self.assertTrue(isinstance(hypot(mx, x), mmatrix)) def test_masked_binary_operations2(self): "Tests domained_masked_binary_operation" (x, mx) = self.data xmx = masked_array(mx.data.__array__(), mask=mx.mask) self.assertTrue(isinstance(divide(mx, mx), mmatrix)) self.assertTrue(isinstance(divide(mx, x), mmatrix)) assert_equal(divide(mx, mx), divide(xmx, xmx)) def test_attributepropagation(self): x = array(arange(5), mask=[0]+[1]*4) my = masked_array(subarray(x)) ym = msubarray(x) # z = (my+1) self.assertTrue(isinstance(z, MaskedArray)) self.assertTrue(not isinstance(z, MSubArray)) self.assertTrue(isinstance(z._data, SubArray)) assert_equal(z._data.info, {}) # z = (ym+1) self.assertTrue(isinstance(z, MaskedArray)) self.assertTrue(isinstance(z, MSubArray)) self.assertTrue(isinstance(z._data, SubArray)) self.assertTrue(z._data.info['added'] > 0) # ym._set_mask([1, 0, 0, 0, 1]) assert_equal(ym._mask, [1, 0, 0, 0, 1]) ym._series._set_mask([0, 0, 0, 0, 1]) assert_equal(ym._mask, [0, 0, 0, 0, 1]) # xsub = subarray(x, info={'name':'x'}) mxsub = masked_array(xsub) self.assertTrue(hasattr(mxsub, 'info')) assert_equal(mxsub.info, xsub.info) def test_subclasspreservation(self): "Checks that masked_array(...,subok=True) preserves the class." x = np.arange(5) m = [0, 0, 1, 0, 0] xinfo = [(i, j) for (i, j) in zip(x, m)] xsub = MSubArray(x, mask=m, info={'xsub':xinfo}) # mxsub = masked_array(xsub, subok=False) self.assertTrue(not isinstance(mxsub, MSubArray)) self.assertTrue(isinstance(mxsub, MaskedArray)) assert_equal(mxsub._mask, m) # mxsub = asarray(xsub) self.assertTrue(not isinstance(mxsub, MSubArray)) self.assertTrue(isinstance(mxsub, MaskedArray)) assert_equal(mxsub._mask, m) # mxsub = masked_array(xsub, subok=True) self.assertTrue(isinstance(mxsub, MSubArray)) assert_equal(mxsub.info, xsub.info) assert_equal(mxsub._mask, xsub._mask) # mxsub = asanyarray(xsub) self.assertTrue(isinstance(mxsub, MSubArray)) assert_equal(mxsub.info, xsub.info) assert_equal(mxsub._mask, m) ################################################################################ if __name__ == '__main__': run_module_suite() numpy-1.8.2/numpy/ma/bench.py0000664000175100017510000001504212370216242017223 0ustar vagrantvagrant00000000000000#! python # encoding: utf-8 from __future__ import division, absolute_import, print_function import timeit #import IPython.ipapi #ip = IPython.ipapi.get() #from IPython import ipmagic import numpy #from numpy import ma #from numpy.ma import filled #from numpy.ma.testutils import assert_equal #####--------------------------------------------------------------------------- #---- --- Global variables --- #####--------------------------------------------------------------------------- # Small arrays .................................. xs = numpy.random.uniform(-1, 1, 6).reshape(2, 3) ys = numpy.random.uniform(-1, 1, 6).reshape(2, 3) zs = xs + 1j * ys m1 = [[True, False, False], [False, False, True]] m2 = [[True, False, True], [False, False, True]] nmxs = numpy.ma.array(xs, mask=m1) nmys = numpy.ma.array(ys, mask=m2) nmzs = numpy.ma.array(zs, mask=m1) # Big arrays .................................... xl = numpy.random.uniform(-1, 1, 100*100).reshape(100, 100) yl = numpy.random.uniform(-1, 1, 100*100).reshape(100, 100) zl = xl + 1j * yl maskx = xl > 0.8 masky = yl < -0.8 nmxl = numpy.ma.array(xl, mask=maskx) nmyl = numpy.ma.array(yl, mask=masky) nmzl = numpy.ma.array(zl, mask=maskx) #####--------------------------------------------------------------------------- #---- --- Functions --- #####--------------------------------------------------------------------------- def timer(s, v='', nloop=500, nrep=3): units = ["s", "ms", "µs", "ns"] scaling = [1, 1e3, 1e6, 1e9] print("%s : %-50s : " % (v, s), end=' ') varnames = ["%ss,nm%ss,%sl,nm%sl" % tuple(x*4) for x in 'xyz'] setup = 'from __main__ import numpy, ma, %s' % ','.join(varnames) Timer = timeit.Timer(stmt=s, setup=setup) best = min(Timer.repeat(nrep, nloop)) / nloop if best > 0.0: order = min(-int(numpy.floor(numpy.log10(best)) // 3), 3) else: order = 3 print("%d loops, best of %d: %.*g %s per loop" % (nloop, nrep, 3, best * scaling[order], units[order])) # ip.magic('timeit -n%i %s' % (nloop,s)) def compare_functions_1v(func, nloop=500, xs=xs, nmxs=nmxs, xl=xl, nmxl=nmxl): funcname = func.__name__ print("-"*50) print("%s on small arrays" % funcname) module, data = "numpy.ma", "nmxs" timer("%(module)s.%(funcname)s(%(data)s)" % locals(), v="%11s" % module, nloop=nloop) # print("%s on large arrays" % funcname) module, data = "numpy.ma", "nmxl" timer("%(module)s.%(funcname)s(%(data)s)" % locals(), v="%11s" % module, nloop=nloop) return def compare_methods(methodname, args, vars='x', nloop=500, test=True, xs=xs, nmxs=nmxs, xl=xl, nmxl=nmxl): print("-"*50) print("%s on small arrays" % methodname) data, ver = "nm%ss" % vars, 'numpy.ma' timer("%(data)s.%(methodname)s(%(args)s)" % locals(), v=ver, nloop=nloop) # print("%s on large arrays" % methodname) data, ver = "nm%sl" % vars, 'numpy.ma' timer("%(data)s.%(methodname)s(%(args)s)" % locals(), v=ver, nloop=nloop) return def compare_functions_2v(func, nloop=500, test=True, xs=xs, nmxs=nmxs, ys=ys, nmys=nmys, xl=xl, nmxl=nmxl, yl=yl, nmyl=nmyl): funcname = func.__name__ print("-"*50) print("%s on small arrays" % funcname) module, data = "numpy.ma", "nmxs,nmys" timer("%(module)s.%(funcname)s(%(data)s)" % locals(), v="%11s" % module, nloop=nloop) # print("%s on large arrays" % funcname) module, data = "numpy.ma", "nmxl,nmyl" timer("%(module)s.%(funcname)s(%(data)s)" % locals(), v="%11s" % module, nloop=nloop) return ############################################################################### ################################################################################ if __name__ == '__main__': # # Small arrays .................................. # xs = numpy.random.uniform(-1,1,6).reshape(2,3) # ys = numpy.random.uniform(-1,1,6).reshape(2,3) # zs = xs + 1j * ys # m1 = [[True, False, False], [False, False, True]] # m2 = [[True, False, True], [False, False, True]] # nmxs = numpy.ma.array(xs, mask=m1) # nmys = numpy.ma.array(ys, mask=m2) # nmzs = numpy.ma.array(zs, mask=m1) # mmxs = maskedarray.array(xs, mask=m1) # mmys = maskedarray.array(ys, mask=m2) # mmzs = maskedarray.array(zs, mask=m1) # # Big arrays .................................... # xl = numpy.random.uniform(-1,1,100*100).reshape(100,100) # yl = numpy.random.uniform(-1,1,100*100).reshape(100,100) # zl = xl + 1j * yl # maskx = xl > 0.8 # masky = yl < -0.8 # nmxl = numpy.ma.array(xl, mask=maskx) # nmyl = numpy.ma.array(yl, mask=masky) # nmzl = numpy.ma.array(zl, mask=maskx) # mmxl = maskedarray.array(xl, mask=maskx, shrink=True) # mmyl = maskedarray.array(yl, mask=masky, shrink=True) # mmzl = maskedarray.array(zl, mask=maskx, shrink=True) # compare_functions_1v(numpy.sin) compare_functions_1v(numpy.log) compare_functions_1v(numpy.sqrt) #.................................................................... compare_functions_2v(numpy.multiply) compare_functions_2v(numpy.divide) compare_functions_2v(numpy.power) #.................................................................... compare_methods('ravel', '', nloop=1000) compare_methods('conjugate', '', 'z', nloop=1000) compare_methods('transpose', '', nloop=1000) compare_methods('compressed', '', nloop=1000) compare_methods('__getitem__', '0', nloop=1000) compare_methods('__getitem__', '(0,0)', nloop=1000) compare_methods('__getitem__', '[0,-1]', nloop=1000) compare_methods('__setitem__', '0, 17', nloop=1000, test=False) compare_methods('__setitem__', '(0,0), 17', nloop=1000, test=False) #.................................................................... print("-"*50) print("__setitem__ on small arrays") timer('nmxs.__setitem__((-1,0),numpy.ma.masked)', 'numpy.ma ', nloop=10000) print("-"*50) print("__setitem__ on large arrays") timer('nmxl.__setitem__((-1,0),numpy.ma.masked)', 'numpy.ma ', nloop=10000) #.................................................................... print("-"*50) print("where on small arrays") timer('numpy.ma.where(nmxs>2,nmxs,nmys)', 'numpy.ma ', nloop=1000) print("-"*50) print("where on large arrays") timer('numpy.ma.where(nmxl>2,nmxl,nmyl)', 'numpy.ma ', nloop=100) numpy-1.8.2/numpy/ma/testutils.py0000664000175100017510000002357612370216242020217 0ustar vagrantvagrant00000000000000"""Miscellaneous functions for testing masked arrays and subclasses :author: Pierre Gerard-Marchant :contact: pierregm_at_uga_dot_edu :version: $Id: testutils.py 3529 2007-11-13 08:01:14Z jarrod.millman $ """ from __future__ import division, absolute_import, print_function __author__ = "Pierre GF Gerard-Marchant ($Author: jarrod.millman $)" __version__ = "1.0" __revision__ = "$Revision: 3529 $" __date__ = "$Date: 2007-11-13 10:01:14 +0200 (Tue, 13 Nov 2007) $" import operator import numpy as np from numpy import ndarray, float_ import numpy.core.umath as umath from numpy.testing import * import numpy.testing.utils as utils from .core import mask_or, getmask, masked_array, nomask, masked, filled, \ equal, less #------------------------------------------------------------------------------ def approx (a, b, fill_value=True, rtol=1e-5, atol=1e-8): """Returns true if all components of a and b are equal subject to given tolerances. If fill_value is True, masked values considered equal. Otherwise, masked values are considered unequal. The relative error rtol should be positive and << 1.0 The absolute error atol comes into play for those elements of b that are very small or zero; it says how small a must be also. """ m = mask_or(getmask(a), getmask(b)) d1 = filled(a) d2 = filled(b) if d1.dtype.char == "O" or d2.dtype.char == "O": return np.equal(d1, d2).ravel() x = filled(masked_array(d1, copy=False, mask=m), fill_value).astype(float_) y = filled(masked_array(d2, copy=False, mask=m), 1).astype(float_) d = np.less_equal(umath.absolute(x - y), atol + rtol * umath.absolute(y)) return d.ravel() def almost(a, b, decimal=6, fill_value=True): """Returns True if a and b are equal up to decimal places. If fill_value is True, masked values considered equal. Otherwise, masked values are considered unequal. """ m = mask_or(getmask(a), getmask(b)) d1 = filled(a) d2 = filled(b) if d1.dtype.char == "O" or d2.dtype.char == "O": return np.equal(d1, d2).ravel() x = filled(masked_array(d1, copy=False, mask=m), fill_value).astype(float_) y = filled(masked_array(d2, copy=False, mask=m), 1).astype(float_) d = np.around(np.abs(x - y), decimal) <= 10.0 ** (-decimal) return d.ravel() #................................................ def _assert_equal_on_sequences(actual, desired, err_msg=''): "Asserts the equality of two non-array sequences." assert_equal(len(actual), len(desired), err_msg) for k in range(len(desired)): assert_equal(actual[k], desired[k], 'item=%r\n%s' % (k, err_msg)) return def assert_equal_records(a, b): """Asserts that two records are equal. Pretty crude for now.""" assert_equal(a.dtype, b.dtype) for f in a.dtype.names: (af, bf) = (operator.getitem(a, f), operator.getitem(b, f)) if not (af is masked) and not (bf is masked): assert_equal(operator.getitem(a, f), operator.getitem(b, f)) return def assert_equal(actual, desired, err_msg=''): "Asserts that two items are equal." # Case #1: dictionary ..... if isinstance(desired, dict): if not isinstance(actual, dict): raise AssertionError(repr(type(actual))) assert_equal(len(actual), len(desired), err_msg) for k, i in desired.items(): if not k in actual: raise AssertionError("%s not in %s" % (k, actual)) assert_equal(actual[k], desired[k], 'key=%r\n%s' % (k, err_msg)) return # Case #2: lists ..... if isinstance(desired, (list, tuple)) and isinstance(actual, (list, tuple)): return _assert_equal_on_sequences(actual, desired, err_msg='') if not (isinstance(actual, ndarray) or isinstance(desired, ndarray)): msg = build_err_msg([actual, desired], err_msg,) if not desired == actual: raise AssertionError(msg) return # Case #4. arrays or equivalent if ((actual is masked) and not (desired is masked)) or \ ((desired is masked) and not (actual is masked)): msg = build_err_msg([actual, desired], err_msg, header='', names=('x', 'y')) raise ValueError(msg) actual = np.array(actual, copy=False, subok=True) desired = np.array(desired, copy=False, subok=True) (actual_dtype, desired_dtype) = (actual.dtype, desired.dtype) if actual_dtype.char == "S" and desired_dtype.char == "S": return _assert_equal_on_sequences(actual.tolist(), desired.tolist(), err_msg='') # elif actual_dtype.char in "OV" and desired_dtype.char in "OV": # if (actual_dtype != desired_dtype) and actual_dtype: # msg = build_err_msg([actual_dtype, desired_dtype], # err_msg, header='', names=('actual', 'desired')) # raise ValueError(msg) # return _assert_equal_on_sequences(actual.tolist(), # desired.tolist(), # err_msg='') return assert_array_equal(actual, desired, err_msg) def fail_if_equal(actual, desired, err_msg='',): """Raises an assertion error if two items are equal. """ if isinstance(desired, dict): if not isinstance(actual, dict): raise AssertionError(repr(type(actual))) fail_if_equal(len(actual), len(desired), err_msg) for k, i in desired.items(): if not k in actual: raise AssertionError(repr(k)) fail_if_equal(actual[k], desired[k], 'key=%r\n%s' % (k, err_msg)) return if isinstance(desired, (list, tuple)) and isinstance(actual, (list, tuple)): fail_if_equal(len(actual), len(desired), err_msg) for k in range(len(desired)): fail_if_equal(actual[k], desired[k], 'item=%r\n%s' % (k, err_msg)) return if isinstance(actual, np.ndarray) or isinstance(desired, np.ndarray): return fail_if_array_equal(actual, desired, err_msg) msg = build_err_msg([actual, desired], err_msg) if not desired != actual: raise AssertionError(msg) assert_not_equal = fail_if_equal def assert_almost_equal(actual, desired, decimal=7, err_msg='', verbose=True): """Asserts that two items are almost equal. The test is equivalent to abs(desired-actual) < 0.5 * 10**(-decimal) """ if isinstance(actual, np.ndarray) or isinstance(desired, np.ndarray): return assert_array_almost_equal(actual, desired, decimal=decimal, err_msg=err_msg, verbose=verbose) msg = build_err_msg([actual, desired], err_msg=err_msg, verbose=verbose) if not round(abs(desired - actual), decimal) == 0: raise AssertionError(msg) assert_close = assert_almost_equal def assert_array_compare(comparison, x, y, err_msg='', verbose=True, header='', fill_value=True): """Asserts that a comparison relation between two masked arrays is satisfied elementwise.""" # Fill the data first # xf = filled(x) # yf = filled(y) # Allocate a common mask and refill m = mask_or(getmask(x), getmask(y)) x = masked_array(x, copy=False, mask=m, keep_mask=False, subok=False) y = masked_array(y, copy=False, mask=m, keep_mask=False, subok=False) if ((x is masked) and not (y is masked)) or \ ((y is masked) and not (x is masked)): msg = build_err_msg([x, y], err_msg=err_msg, verbose=verbose, header=header, names=('x', 'y')) raise ValueError(msg) # OK, now run the basic tests on filled versions return utils.assert_array_compare(comparison, x.filled(fill_value), y.filled(fill_value), err_msg=err_msg, verbose=verbose, header=header) def assert_array_equal(x, y, err_msg='', verbose=True): """Checks the elementwise equality of two masked arrays.""" assert_array_compare(operator.__eq__, x, y, err_msg=err_msg, verbose=verbose, header='Arrays are not equal') def fail_if_array_equal(x, y, err_msg='', verbose=True): "Raises an assertion error if two masked arrays are not equal (elementwise)." def compare(x, y): return (not np.alltrue(approx(x, y))) assert_array_compare(compare, x, y, err_msg=err_msg, verbose=verbose, header='Arrays are not equal') def assert_array_approx_equal(x, y, decimal=6, err_msg='', verbose=True): """Checks the elementwise equality of two masked arrays, up to a given number of decimals.""" def compare(x, y): "Returns the result of the loose comparison between x and y)." return approx(x, y, rtol=10. ** -decimal) assert_array_compare(compare, x, y, err_msg=err_msg, verbose=verbose, header='Arrays are not almost equal') def assert_array_almost_equal(x, y, decimal=6, err_msg='', verbose=True): """Checks the elementwise equality of two masked arrays, up to a given number of decimals.""" def compare(x, y): "Returns the result of the loose comparison between x and y)." return almost(x, y, decimal) assert_array_compare(compare, x, y, err_msg=err_msg, verbose=verbose, header='Arrays are not almost equal') def assert_array_less(x, y, err_msg='', verbose=True): "Checks that x is smaller than y elementwise." assert_array_compare(operator.__lt__, x, y, err_msg=err_msg, verbose=verbose, header='Arrays are not less-ordered') def assert_mask_equal(m1, m2, err_msg=''): """Asserts the equality of two masks.""" if m1 is nomask: assert_(m2 is nomask) if m2 is nomask: assert_(m1 is nomask) assert_array_equal(m1, m2, err_msg=err_msg) numpy-1.8.2/numpy/ma/__init__.py0000664000175100017510000000305012370216242017677 0ustar vagrantvagrant00000000000000""" ============= Masked Arrays ============= Arrays sometimes contain invalid or missing data. When doing operations on such arrays, we wish to suppress invalid values, which is the purpose masked arrays fulfill (an example of typical use is given below). For example, examine the following array: >>> x = np.array([2, 1, 3, np.nan, 5, 2, 3, np.nan]) When we try to calculate the mean of the data, the result is undetermined: >>> np.mean(x) nan The mean is calculated using roughly ``np.sum(x)/len(x)``, but since any number added to ``NaN`` [1]_ produces ``NaN``, this doesn't work. Enter masked arrays: >>> m = np.ma.masked_array(x, np.isnan(x)) >>> m masked_array(data = [2.0 1.0 3.0 -- 5.0 2.0 3.0 --], mask = [False False False True False False False True], fill_value=1e+20) Here, we construct a masked array that suppress all ``NaN`` values. We may now proceed to calculate the mean of the other values: >>> np.mean(m) 2.6666666666666665 .. [1] Not-a-Number, a floating point value that is the result of an invalid operation. """ from __future__ import division, absolute_import, print_function __author__ = "Pierre GF Gerard-Marchant ($Author: jarrod.millman $)" __version__ = '1.0' __revision__ = "$Revision: 3473 $" __date__ = '$Date: 2007-10-29 17:18:13 +0200 (Mon, 29 Oct 2007) $' from . import core from .core import * from . import extras from .extras import * __all__ = ['core', 'extras'] __all__ += core.__all__ __all__ += extras.__all__ from numpy.testing import Tester test = Tester().test bench = Tester().bench numpy-1.8.2/numpy/ma/core.py0000664000175100017510000070257012370216243017106 0ustar vagrantvagrant00000000000000""" numpy.ma : a package to handle missing or invalid values. This package was initially written for numarray by Paul F. Dubois at Lawrence Livermore National Laboratory. In 2006, the package was completely rewritten by Pierre Gerard-Marchant (University of Georgia) to make the MaskedArray class a subclass of ndarray, and to improve support of structured arrays. Copyright 1999, 2000, 2001 Regents of the University of California. Released for unlimited redistribution. * Adapted for numpy_core 2005 by Travis Oliphant and (mainly) Paul Dubois. * Subclassing of the base `ndarray` 2006 by Pierre Gerard-Marchant (pgmdevlist_AT_gmail_DOT_com) * Improvements suggested by Reggie Dugard (reggie_AT_merfinllc_DOT_com) .. moduleauthor:: Pierre Gerard-Marchant """ # pylint: disable-msg=E1002 from __future__ import division, absolute_import, print_function import sys import warnings from functools import reduce import numpy as np import numpy.core.umath as umath import numpy.core.numerictypes as ntypes from numpy import ndarray, amax, amin, iscomplexobj, bool_ from numpy import array as narray from numpy.lib.function_base import angle from numpy.compat import getargspec, formatargspec, long, basestring from numpy import expand_dims as n_expand_dims if sys.version_info[0] >= 3: import pickle else: import cPickle as pickle __author__ = "Pierre GF Gerard-Marchant" __docformat__ = "restructuredtext en" __all__ = ['MAError', 'MaskError', 'MaskType', 'MaskedArray', 'bool_', 'abs', 'absolute', 'add', 'all', 'allclose', 'allequal', 'alltrue', 'amax', 'amin', 'angle', 'anom', 'anomalies', 'any', 'arange', 'arccos', 'arccosh', 'arcsin', 'arcsinh', 'arctan', 'arctan2', 'arctanh', 'argmax', 'argmin', 'argsort', 'around', 'array', 'asarray', 'asanyarray', 'bitwise_and', 'bitwise_or', 'bitwise_xor', 'ceil', 'choose', 'clip', 'common_fill_value', 'compress', 'compressed', 'concatenate', 'conjugate', 'copy', 'cos', 'cosh', 'count', 'cumprod', 'cumsum', 'default_fill_value', 'diag', 'diagonal', 'diff', 'divide', 'dump', 'dumps', 'empty', 'empty_like', 'equal', 'exp', 'expand_dims', 'fabs', 'flatten_mask', 'fmod', 'filled', 'floor', 'floor_divide', 'fix_invalid', 'flatten_structured_array', 'frombuffer', 'fromflex', 'fromfunction', 'getdata', 'getmask', 'getmaskarray', 'greater', 'greater_equal', 'harden_mask', 'hypot', 'identity', 'ids', 'indices', 'inner', 'innerproduct', 'isMA', 'isMaskedArray', 'is_mask', 'is_masked', 'isarray', 'left_shift', 'less', 'less_equal', 'load', 'loads', 'log', 'log2', 'log10', 'logical_and', 'logical_not', 'logical_or', 'logical_xor', 'make_mask', 'make_mask_descr', 'make_mask_none', 'mask_or', 'masked', 'masked_array', 'masked_equal', 'masked_greater', 'masked_greater_equal', 'masked_inside', 'masked_invalid', 'masked_less', 'masked_less_equal', 'masked_not_equal', 'masked_object', 'masked_outside', 'masked_print_option', 'masked_singleton', 'masked_values', 'masked_where', 'max', 'maximum', 'maximum_fill_value', 'mean', 'min', 'minimum', 'minimum_fill_value', 'mod', 'multiply', 'mvoid', 'negative', 'nomask', 'nonzero', 'not_equal', 'ones', 'outer', 'outerproduct', 'power', 'prod', 'product', 'ptp', 'put', 'putmask', 'rank', 'ravel', 'remainder', 'repeat', 'reshape', 'resize', 'right_shift', 'round_', 'round', 'set_fill_value', 'shape', 'sin', 'sinh', 'size', 'sometrue', 'sort', 'soften_mask', 'sqrt', 'squeeze', 'std', 'subtract', 'sum', 'swapaxes', 'take', 'tan', 'tanh', 'trace', 'transpose', 'true_divide', 'var', 'where', 'zeros'] MaskType = np.bool_ nomask = MaskType(0) def doc_note(initialdoc, note): """ Adds a Notes section to an existing docstring. """ if initialdoc is None: return if note is None: return initialdoc newdoc = """ %s Notes ----- %s """ return newdoc % (initialdoc, note) def get_object_signature(obj): """ Get the signature from obj """ try: sig = formatargspec(*getargspec(obj)) except TypeError as errmsg: sig = '' # msg = "Unable to retrieve the signature of %s '%s'\n"\ # "(Initial error message: %s)" # warnings.warn(msg % (type(obj), # getattr(obj, '__name__', '???'), # errmsg)) return sig #####-------------------------------------------------------------------------- #---- --- Exceptions --- #####-------------------------------------------------------------------------- class MAError(Exception): """Class for masked array related errors.""" pass class MaskError(MAError): "Class for mask related errors." pass #####-------------------------------------------------------------------------- #---- --- Filling options --- #####-------------------------------------------------------------------------- # b: boolean - c: complex - f: floats - i: integer - O: object - S: string default_filler = {'b': True, 'c' : 1.e20 + 0.0j, 'f' : 1.e20, 'i' : 999999, 'O' : '?', 'S' : 'N/A', 'u' : 999999, 'V' : '???', 'U' : 'N/A', 'M8[D]' : np.datetime64('NaT', 'D'), 'M8[us]' : np.datetime64('NaT', 'us') } max_filler = ntypes._minvals max_filler.update([(k, -np.inf) for k in [np.float32, np.float64]]) min_filler = ntypes._maxvals min_filler.update([(k, +np.inf) for k in [np.float32, np.float64]]) if 'float128' in ntypes.typeDict: max_filler.update([(np.float128, -np.inf)]) min_filler.update([(np.float128, +np.inf)]) def default_fill_value(obj): """ Return the default fill value for the argument object. The default filling value depends on the datatype of the input array or the type of the input scalar: ======== ======== datatype default ======== ======== bool True int 999999 float 1.e20 complex 1.e20+0j object '?' string 'N/A' ======== ======== Parameters ---------- obj : ndarray, dtype or scalar The array data-type or scalar for which the default fill value is returned. Returns ------- fill_value : scalar The default fill value. Examples -------- >>> np.ma.default_fill_value(1) 999999 >>> np.ma.default_fill_value(np.array([1.1, 2., np.pi])) 1e+20 >>> np.ma.default_fill_value(np.dtype(complex)) (1e+20+0j) """ if hasattr(obj, 'dtype'): defval = _check_fill_value(None, obj.dtype) elif isinstance(obj, np.dtype): if obj.subdtype: defval = default_filler.get(obj.subdtype[0].kind, '?') elif obj.kind == 'M': defval = default_filler.get(obj.str[1:], '?') else: defval = default_filler.get(obj.kind, '?') elif isinstance(obj, float): defval = default_filler['f'] elif isinstance(obj, int) or isinstance(obj, long): defval = default_filler['i'] elif isinstance(obj, str): defval = default_filler['S'] elif isinstance(obj, unicode): defval = default_filler['U'] elif isinstance(obj, complex): defval = default_filler['c'] else: defval = default_filler['O'] return defval def _recursive_extremum_fill_value(ndtype, extremum): names = ndtype.names if names: deflist = [] for name in names: fval = _recursive_extremum_fill_value(ndtype[name], extremum) deflist.append(fval) return tuple(deflist) return extremum[ndtype] def minimum_fill_value(obj): """ Return the maximum value that can be represented by the dtype of an object. This function is useful for calculating a fill value suitable for taking the minimum of an array with a given dtype. Parameters ---------- obj : ndarray or dtype An object that can be queried for it's numeric type. Returns ------- val : scalar The maximum representable value. Raises ------ TypeError If `obj` isn't a suitable numeric type. See Also -------- maximum_fill_value : The inverse function. set_fill_value : Set the filling value of a masked array. MaskedArray.fill_value : Return current fill value. Examples -------- >>> import numpy.ma as ma >>> a = np.int8() >>> ma.minimum_fill_value(a) 127 >>> a = np.int32() >>> ma.minimum_fill_value(a) 2147483647 An array of numeric data can also be passed. >>> a = np.array([1, 2, 3], dtype=np.int8) >>> ma.minimum_fill_value(a) 127 >>> a = np.array([1, 2, 3], dtype=np.float32) >>> ma.minimum_fill_value(a) inf """ errmsg = "Unsuitable type for calculating minimum." if hasattr(obj, 'dtype'): return _recursive_extremum_fill_value(obj.dtype, min_filler) elif isinstance(obj, float): return min_filler[ntypes.typeDict['float_']] elif isinstance(obj, int): return min_filler[ntypes.typeDict['int_']] elif isinstance(obj, long): return min_filler[ntypes.typeDict['uint']] elif isinstance(obj, np.dtype): return min_filler[obj] else: raise TypeError(errmsg) def maximum_fill_value(obj): """ Return the minimum value that can be represented by the dtype of an object. This function is useful for calculating a fill value suitable for taking the maximum of an array with a given dtype. Parameters ---------- obj : {ndarray, dtype} An object that can be queried for it's numeric type. Returns ------- val : scalar The minimum representable value. Raises ------ TypeError If `obj` isn't a suitable numeric type. See Also -------- minimum_fill_value : The inverse function. set_fill_value : Set the filling value of a masked array. MaskedArray.fill_value : Return current fill value. Examples -------- >>> import numpy.ma as ma >>> a = np.int8() >>> ma.maximum_fill_value(a) -128 >>> a = np.int32() >>> ma.maximum_fill_value(a) -2147483648 An array of numeric data can also be passed. >>> a = np.array([1, 2, 3], dtype=np.int8) >>> ma.maximum_fill_value(a) -128 >>> a = np.array([1, 2, 3], dtype=np.float32) >>> ma.maximum_fill_value(a) -inf """ errmsg = "Unsuitable type for calculating maximum." if hasattr(obj, 'dtype'): return _recursive_extremum_fill_value(obj.dtype, max_filler) elif isinstance(obj, float): return max_filler[ntypes.typeDict['float_']] elif isinstance(obj, int): return max_filler[ntypes.typeDict['int_']] elif isinstance(obj, long): return max_filler[ntypes.typeDict['uint']] elif isinstance(obj, np.dtype): return max_filler[obj] else: raise TypeError(errmsg) def _recursive_set_default_fill_value(dtypedescr): deflist = [] for currentdescr in dtypedescr: currenttype = currentdescr[1] if isinstance(currenttype, list): deflist.append(tuple(_recursive_set_default_fill_value(currenttype))) else: deflist.append(default_fill_value(np.dtype(currenttype))) return tuple(deflist) def _recursive_set_fill_value(fillvalue, dtypedescr): fillvalue = np.resize(fillvalue, len(dtypedescr)) output_value = [] for (fval, descr) in zip(fillvalue, dtypedescr): cdtype = descr[1] if isinstance(cdtype, list): output_value.append(tuple(_recursive_set_fill_value(fval, cdtype))) else: output_value.append(np.array(fval, dtype=cdtype).item()) return tuple(output_value) def _check_fill_value(fill_value, ndtype): """ Private function validating the given `fill_value` for the given dtype. If fill_value is None, it is set to the default corresponding to the dtype if this latter is standard (no fields). If the datatype is flexible (named fields), fill_value is set to a tuple whose elements are the default fill values corresponding to each field. If fill_value is not None, its value is forced to the given dtype. """ ndtype = np.dtype(ndtype) fields = ndtype.fields if fill_value is None: if fields: descr = ndtype.descr fill_value = np.array(_recursive_set_default_fill_value(descr), dtype=ndtype,) else: fill_value = default_fill_value(ndtype) elif fields: fdtype = [(_[0], _[1]) for _ in ndtype.descr] if isinstance(fill_value, (ndarray, np.void)): try: fill_value = np.array(fill_value, copy=False, dtype=fdtype) except ValueError: err_msg = "Unable to transform %s to dtype %s" raise ValueError(err_msg % (fill_value, fdtype)) else: descr = ndtype.descr fill_value = np.asarray(fill_value, dtype=object) 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) else: # In case we want to convert 1e+20 to int... try: fill_value = np.array(fill_value, copy=False, dtype=ndtype)#.item() except OverflowError: fill_value = default_fill_value(ndtype) return np.array(fill_value) def set_fill_value(a, fill_value): """ Set the filling value of a, if a is a masked array. This function changes the fill value of the masked array `a` in place. If `a` is not a masked array, the function returns silently, without doing anything. Parameters ---------- a : array_like Input array. fill_value : dtype Filling value. A consistency test is performed to make sure the value is compatible with the dtype of `a`. Returns ------- None Nothing returned by this function. See Also -------- maximum_fill_value : Return the default fill value for a dtype. MaskedArray.fill_value : Return current fill value. MaskedArray.set_fill_value : Equivalent method. Examples -------- >>> import numpy.ma as ma >>> a = np.arange(5) >>> a array([0, 1, 2, 3, 4]) >>> a = ma.masked_where(a < 3, a) >>> a masked_array(data = [-- -- -- 3 4], mask = [ True True True False False], fill_value=999999) >>> ma.set_fill_value(a, -999) >>> a masked_array(data = [-- -- -- 3 4], mask = [ True True True False False], fill_value=-999) Nothing happens if `a` is not a masked array. >>> a = range(5) >>> a [0, 1, 2, 3, 4] >>> ma.set_fill_value(a, 100) >>> a [0, 1, 2, 3, 4] >>> a = np.arange(5) >>> a array([0, 1, 2, 3, 4]) >>> ma.set_fill_value(a, 100) >>> a array([0, 1, 2, 3, 4]) """ if isinstance(a, MaskedArray): a.set_fill_value(fill_value) return def get_fill_value(a): """ Return the filling value of a, if any. Otherwise, returns the default filling value for that type. """ if isinstance(a, MaskedArray): result = a.fill_value else: result = default_fill_value(a) return result def common_fill_value(a, b): """ Return the common filling value of two masked arrays, if any. If ``a.fill_value == b.fill_value``, return the fill value, otherwise return None. Parameters ---------- a, b : MaskedArray The masked arrays for which to compare fill values. Returns ------- fill_value : scalar or None The common fill value, or None. Examples -------- >>> x = np.ma.array([0, 1.], fill_value=3) >>> y = np.ma.array([0, 1.], fill_value=3) >>> np.ma.common_fill_value(x, y) 3.0 """ t1 = get_fill_value(a) t2 = get_fill_value(b) if t1 == t2: return t1 return None #####-------------------------------------------------------------------------- def filled(a, fill_value=None): """ Return input as an array with masked data replaced by a fill value. If `a` is not a `MaskedArray`, `a` itself is returned. If `a` is a `MaskedArray` and `fill_value` is None, `fill_value` is set to ``a.fill_value``. Parameters ---------- a : MaskedArray or array_like An input object. fill_value : scalar, optional Filling value. Default is None. Returns ------- a : ndarray The filled array. See Also -------- compressed Examples -------- >>> x = np.ma.array(np.arange(9).reshape(3, 3), mask=[[1, 0, 0], ... [1, 0, 0], ... [0, 0, 0]]) >>> x.filled() array([[999999, 1, 2], [999999, 4, 5], [ 6, 7, 8]]) """ if hasattr(a, 'filled'): return a.filled(fill_value) elif isinstance(a, ndarray): # Should we check for contiguity ? and a.flags['CONTIGUOUS']: return a elif isinstance(a, dict): return np.array(a, 'O') else: return np.array(a) #####-------------------------------------------------------------------------- def get_masked_subclass(*arrays): """ Return the youngest subclass of MaskedArray from a list of (masked) arrays. In case of siblings, the first listed takes over. """ if len(arrays) == 1: arr = arrays[0] if isinstance(arr, MaskedArray): rcls = type(arr) else: rcls = MaskedArray else: arrcls = [type(a) for a in arrays] rcls = arrcls[0] if not issubclass(rcls, MaskedArray): rcls = MaskedArray for cls in arrcls[1:]: if issubclass(cls, rcls): rcls = cls # Don't return MaskedConstant as result: revert to MaskedArray if rcls.__name__ == 'MaskedConstant': return MaskedArray return rcls #####-------------------------------------------------------------------------- def getdata(a, subok=True): """ Return the data of a masked array as an ndarray. Return the data of `a` (if any) as an ndarray if `a` is a ``MaskedArray``, else return `a` as a ndarray or subclass (depending on `subok`) if not. Parameters ---------- a : array_like Input ``MaskedArray``, alternatively a ndarray or a subclass thereof. subok : bool Whether to force the output to be a `pure` ndarray (False) or to return a subclass of ndarray if appropriate (True, default). See Also -------- getmask : Return the mask of a masked array, or nomask. getmaskarray : Return the mask of a masked array, or full array of False. Examples -------- >>> import numpy.ma as ma >>> a = ma.masked_equal([[1,2],[3,4]], 2) >>> a masked_array(data = [[1 --] [3 4]], mask = [[False True] [False False]], fill_value=999999) >>> ma.getdata(a) array([[1, 2], [3, 4]]) Equivalently use the ``MaskedArray`` `data` attribute. >>> a.data array([[1, 2], [3, 4]]) """ try: data = a._data except AttributeError: data = np.array(a, copy=False, subok=subok) if not subok: return data.view(ndarray) return data get_data = getdata def fix_invalid(a, mask=nomask, copy=True, fill_value=None): """ Return input with invalid data masked and replaced by a fill value. Invalid data means values of `nan`, `inf`, etc. Parameters ---------- a : array_like Input array, a (subclass of) ndarray. copy : bool, optional Whether to use a copy of `a` (True) or to fix `a` in place (False). Default is True. fill_value : scalar, optional Value used for fixing invalid data. Default is None, in which case the ``a.fill_value`` is used. Returns ------- b : MaskedArray The input array with invalid entries fixed. Notes ----- A copy is performed by default. Examples -------- >>> x = np.ma.array([1., -1, np.nan, np.inf], mask=[1] + [0]*3) >>> x masked_array(data = [-- -1.0 nan inf], mask = [ True False False False], fill_value = 1e+20) >>> np.ma.fix_invalid(x) masked_array(data = [-- -1.0 -- --], mask = [ True False True True], fill_value = 1e+20) >>> fixed = np.ma.fix_invalid(x) >>> fixed.data array([ 1.00000000e+00, -1.00000000e+00, 1.00000000e+20, 1.00000000e+20]) >>> x.data array([ 1., -1., NaN, Inf]) """ a = masked_array(a, copy=copy, mask=mask, subok=True) #invalid = (numpy.isnan(a._data) | numpy.isinf(a._data)) invalid = np.logical_not(np.isfinite(a._data)) if not invalid.any(): return a a._mask |= invalid if fill_value is None: fill_value = a.fill_value a._data[invalid] = fill_value return a #####-------------------------------------------------------------------------- #---- --- Ufuncs --- #####-------------------------------------------------------------------------- ufunc_domain = {} ufunc_fills = {} class _DomainCheckInterval: """ Define a valid interval, so that : ``domain_check_interval(a,b)(x) == True`` where ``x < a`` or ``x > b``. """ def __init__(self, a, b): "domain_check_interval(a,b)(x) = true where x < a or y > b" if (a > b): (a, b) = (b, a) self.a = a self.b = b def __call__ (self, x): "Execute the call behavior." return umath.logical_or(umath.greater (x, self.b), umath.less(x, self.a)) class _DomainTan: """Define a valid interval for the `tan` function, so that: ``domain_tan(eps) = True`` where ``abs(cos(x)) < eps`` """ def __init__(self, eps): "domain_tan(eps) = true where abs(cos(x)) < eps)" self.eps = eps def __call__ (self, x): "Executes the call behavior." return umath.less(umath.absolute(umath.cos(x)), self.eps) class _DomainSafeDivide: """Define a domain for safe division.""" def __init__ (self, tolerance=None): self.tolerance = tolerance def __call__ (self, a, b): # Delay the selection of the tolerance to here in order to reduce numpy # import times. The calculation of these parameters is a substantial # component of numpy's import time. if self.tolerance is None: self.tolerance = np.finfo(float).tiny return umath.absolute(a) * self.tolerance >= umath.absolute(b) class _DomainGreater: """DomainGreater(v)(x) is True where x <= v.""" def __init__(self, critical_value): "DomainGreater(v)(x) = true where x <= v" self.critical_value = critical_value def __call__ (self, x): "Executes the call behavior." return umath.less_equal(x, self.critical_value) class _DomainGreaterEqual: """DomainGreaterEqual(v)(x) is True where x < v.""" def __init__(self, critical_value): "DomainGreaterEqual(v)(x) = true where x < v" self.critical_value = critical_value def __call__ (self, x): "Executes the call behavior." return umath.less(x, self.critical_value) #.............................................................................. class _MaskedUnaryOperation: """ Defines masked version of unary operations, where invalid values are pre-masked. Parameters ---------- mufunc : callable The function for which to define a masked version. Made available as ``_MaskedUnaryOperation.f``. fill : scalar, optional Filling value, default is 0. domain : class instance Domain for the function. Should be one of the ``_Domain*`` classes. Default is None. """ def __init__ (self, mufunc, fill=0, domain=None): """ _MaskedUnaryOperation(aufunc, fill=0, domain=None) aufunc(fill) must be defined self(x) returns aufunc(x) with masked values where domain(x) is true or getmask(x) is true. """ self.f = mufunc self.fill = fill self.domain = domain self.__doc__ = getattr(mufunc, "__doc__", str(mufunc)) self.__name__ = getattr(mufunc, "__name__", str(mufunc)) ufunc_domain[mufunc] = domain ufunc_fills[mufunc] = fill # def __call__ (self, a, *args, **kwargs): "Execute the call behavior." d = getdata(a) # Case 1.1. : Domained function if self.domain is not None: with np.errstate(): np.seterr(divide='ignore', invalid='ignore') result = self.f(d, *args, **kwargs) # Make a mask m = ~umath.isfinite(result) m |= self.domain(d) m |= getmask(a) # Case 1.2. : Function without a domain else: # Get the result and the mask result = self.f(d, *args, **kwargs) m = getmask(a) # Case 2.1. : The result is scalarscalar if not result.ndim: if m: return masked return result # Case 2.2. The result is an array # We need to fill the invalid data back w/ the input # Now, that's plain silly: in C, we would just skip the element and keep # the original, but we do have to do it that way in Python if m is not nomask: # In case result has a lower dtype than the inputs (as in equal) try: np.copyto(result, d, where=m) except TypeError: pass # Transform to if isinstance(a, MaskedArray): subtype = type(a) else: subtype = MaskedArray result = result.view(subtype) result._mask = m result._update_from(a) return result # def __str__ (self): return "Masked version of %s. [Invalid values are masked]" % str(self.f) class _MaskedBinaryOperation: """ Define masked version of binary operations, where invalid values are pre-masked. Parameters ---------- mbfunc : function The function for which to define a masked version. Made available as ``_MaskedBinaryOperation.f``. domain : class instance Default domain for the function. Should be one of the ``_Domain*`` classes. Default is None. fillx : scalar, optional Filling value for the first argument, default is 0. filly : scalar, optional Filling value for the second argument, default is 0. """ def __init__ (self, mbfunc, fillx=0, filly=0): """abfunc(fillx, filly) must be defined. abfunc(x, filly) = x for all x to enable reduce. """ self.f = mbfunc self.fillx = fillx self.filly = filly self.__doc__ = getattr(mbfunc, "__doc__", str(mbfunc)) self.__name__ = getattr(mbfunc, "__name__", str(mbfunc)) ufunc_domain[mbfunc] = None ufunc_fills[mbfunc] = (fillx, filly) def __call__ (self, a, b, *args, **kwargs): "Execute the call behavior." # Get the data, as ndarray (da, db) = (getdata(a, subok=False), getdata(b, subok=False)) # Get the mask (ma, mb) = (getmask(a), getmask(b)) if ma is nomask: if mb is nomask: m = nomask else: m = umath.logical_or(getmaskarray(a), mb) elif mb is nomask: m = umath.logical_or(ma, getmaskarray(b)) else: m = umath.logical_or(ma, mb) # Get the result with np.errstate(): np.seterr(divide='ignore', invalid='ignore') result = self.f(da, db, *args, **kwargs) # check it worked if result is NotImplemented: return NotImplemented # Case 1. : scalar if not result.ndim: if m: return masked 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 # Transforms to a (subclass of) MaskedArray result = result.view(get_masked_subclass(a, b)) result._mask = m # Update the optional info from the inputs if isinstance(b, MaskedArray): if isinstance(a, MaskedArray): result._update_from(a) else: result._update_from(b) elif isinstance(a, MaskedArray): result._update_from(a) return result def reduce(self, target, axis=0, dtype=None): """Reduce `target` along the given `axis`.""" if isinstance(target, MaskedArray): tclass = type(target) else: tclass = MaskedArray m = getmask(target) t = filled(target, self.filly) if t.shape == (): t = t.reshape(1) if m is not nomask: m = make_mask(m, copy=1) m.shape = (1,) if m is nomask: return self.f.reduce(t, axis).view(tclass) t = t.view(tclass) t._mask = m tr = self.f.reduce(getdata(t), axis, dtype=dtype or t.dtype) mr = umath.logical_and.reduce(m, axis) tr = tr.view(tclass) if mr.ndim > 0: tr._mask = mr return tr elif mr: return masked return tr def outer (self, a, b): """Return the function applied to the outer product of a and b. """ ma = getmask(a) mb = getmask(b) if ma is nomask and mb is nomask: m = nomask else: ma = getmaskarray(a) mb = getmaskarray(b) m = umath.logical_or.outer(ma, mb) if (not m.ndim) and m: return masked (da, db) = (getdata(a), getdata(b)) d = self.f.outer(da, db) # check it worked if d is NotImplemented: return NotImplemented if m is not nomask: np.copyto(d, da, where=m) if d.shape: d = d.view(get_masked_subclass(a, b)) d._mask = m return d def accumulate (self, target, axis=0): """Accumulate `target` along `axis` after filling with y fill value. """ if isinstance(target, MaskedArray): tclass = type(target) else: tclass = MaskedArray t = filled(target, self.filly) return self.f.accumulate(t, axis).view(tclass) def __str__ (self): return "Masked version of " + str(self.f) class _DomainedBinaryOperation: """ Define binary operations that have a domain, like divide. They have no reduce, outer or accumulate. Parameters ---------- mbfunc : function The function for which to define a masked version. Made available as ``_DomainedBinaryOperation.f``. domain : class instance Default domain for the function. Should be one of the ``_Domain*`` classes. fillx : scalar, optional Filling value for the first argument, default is 0. filly : scalar, optional Filling value for the second argument, default is 0. """ def __init__ (self, dbfunc, domain, fillx=0, filly=0): """abfunc(fillx, filly) must be defined. abfunc(x, filly) = x for all x to enable reduce. """ self.f = dbfunc self.domain = domain self.fillx = fillx self.filly = filly self.__doc__ = getattr(dbfunc, "__doc__", str(dbfunc)) self.__name__ = getattr(dbfunc, "__name__", str(dbfunc)) ufunc_domain[dbfunc] = domain ufunc_fills[dbfunc] = (fillx, filly) def __call__(self, a, b, *args, **kwargs): "Execute the call behavior." # Get the data and the mask (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') result = self.f(da, db, *args, **kwargs) # check it worked if result is NotImplemented: return NotImplemented # Get the mask as a combination of ma, mb and invalid m = ~umath.isfinite(result) m |= ma m |= mb # Apply the domain domain = ufunc_domain.get(self.f, None) if domain is not None: m |= filled(domain(da, db), True) # Take care of the scalar case first if (not m.ndim): if m: return masked else: return result # When the mask is True, put back da np.copyto(result, 0, casting='unsafe', where=m) result += m * da result = result.view(get_masked_subclass(a, b)) result._mask = m if isinstance(b, MaskedArray): if isinstance(a, MaskedArray): result._update_from(a) else: result._update_from(b) elif isinstance(a, MaskedArray): result._update_from(a) return result def __str__ (self): return "Masked version of " + str(self.f) #.............................................................................. # Unary ufuncs exp = _MaskedUnaryOperation(umath.exp) conjugate = _MaskedUnaryOperation(umath.conjugate) sin = _MaskedUnaryOperation(umath.sin) cos = _MaskedUnaryOperation(umath.cos) tan = _MaskedUnaryOperation(umath.tan) arctan = _MaskedUnaryOperation(umath.arctan) arcsinh = _MaskedUnaryOperation(umath.arcsinh) sinh = _MaskedUnaryOperation(umath.sinh) cosh = _MaskedUnaryOperation(umath.cosh) tanh = _MaskedUnaryOperation(umath.tanh) abs = absolute = _MaskedUnaryOperation(umath.absolute) angle = _MaskedUnaryOperation(angle) # from numpy.lib.function_base fabs = _MaskedUnaryOperation(umath.fabs) negative = _MaskedUnaryOperation(umath.negative) floor = _MaskedUnaryOperation(umath.floor) ceil = _MaskedUnaryOperation(umath.ceil) around = _MaskedUnaryOperation(np.round_) logical_not = _MaskedUnaryOperation(umath.logical_not) # Domained unary ufuncs ....................................................... sqrt = _MaskedUnaryOperation(umath.sqrt, 0.0, _DomainGreaterEqual(0.0)) log = _MaskedUnaryOperation(umath.log, 1.0, _DomainGreater(0.0)) log2 = _MaskedUnaryOperation(umath.log2, 1.0, _DomainGreater(0.0)) log10 = _MaskedUnaryOperation(umath.log10, 1.0, _DomainGreater(0.0)) tan = _MaskedUnaryOperation(umath.tan, 0.0, _DomainTan(1e-35)) arcsin = _MaskedUnaryOperation(umath.arcsin, 0.0, _DomainCheckInterval(-1.0, 1.0)) arccos = _MaskedUnaryOperation(umath.arccos, 0.0, _DomainCheckInterval(-1.0, 1.0)) arccosh = _MaskedUnaryOperation(umath.arccosh, 1.0, _DomainGreaterEqual(1.0)) arctanh = _MaskedUnaryOperation(umath.arctanh, 0.0, _DomainCheckInterval(-1.0 + 1e-15, 1.0 - 1e-15)) # Binary ufuncs ............................................................... add = _MaskedBinaryOperation(umath.add) subtract = _MaskedBinaryOperation(umath.subtract) multiply = _MaskedBinaryOperation(umath.multiply, 1, 1) arctan2 = _MaskedBinaryOperation(umath.arctan2, 0.0, 1.0) equal = _MaskedBinaryOperation(umath.equal) equal.reduce = None not_equal = _MaskedBinaryOperation(umath.not_equal) not_equal.reduce = None less_equal = _MaskedBinaryOperation(umath.less_equal) less_equal.reduce = None greater_equal = _MaskedBinaryOperation(umath.greater_equal) greater_equal.reduce = None less = _MaskedBinaryOperation(umath.less) less.reduce = None greater = _MaskedBinaryOperation(umath.greater) greater.reduce = None logical_and = _MaskedBinaryOperation(umath.logical_and) alltrue = _MaskedBinaryOperation(umath.logical_and, 1, 1).reduce logical_or = _MaskedBinaryOperation(umath.logical_or) sometrue = logical_or.reduce logical_xor = _MaskedBinaryOperation(umath.logical_xor) bitwise_and = _MaskedBinaryOperation(umath.bitwise_and) bitwise_or = _MaskedBinaryOperation(umath.bitwise_or) bitwise_xor = _MaskedBinaryOperation(umath.bitwise_xor) hypot = _MaskedBinaryOperation(umath.hypot) # Domained binary ufuncs ...................................................... divide = _DomainedBinaryOperation(umath.divide, _DomainSafeDivide(), 0, 1) true_divide = _DomainedBinaryOperation(umath.true_divide, _DomainSafeDivide(), 0, 1) floor_divide = _DomainedBinaryOperation(umath.floor_divide, _DomainSafeDivide(), 0, 1) remainder = _DomainedBinaryOperation(umath.remainder, _DomainSafeDivide(), 0, 1) fmod = _DomainedBinaryOperation(umath.fmod, _DomainSafeDivide(), 0, 1) mod = _DomainedBinaryOperation(umath.mod, _DomainSafeDivide(), 0, 1) #####-------------------------------------------------------------------------- #---- --- Mask creation functions --- #####-------------------------------------------------------------------------- def _recursive_make_descr(datatype, newtype=bool_): "Private function allowing recursion in make_descr." # Do we have some name fields ? if datatype.names: descr = [] for name in datatype.names: field = datatype.fields[name] if len(field) == 3: # Prepend the title to the name name = (field[-1], name) descr.append((name, _recursive_make_descr(field[0], newtype))) return descr # Is this some kind of composite a la (np.float,2) elif datatype.subdtype: mdescr = list(datatype.subdtype) mdescr[0] = newtype return tuple(mdescr) else: return newtype def make_mask_descr(ndtype): """ Construct a dtype description list from a given dtype. Returns a new dtype object, with the type of all fields in `ndtype` to a boolean type. Field names are not altered. Parameters ---------- ndtype : dtype The dtype to convert. Returns ------- result : dtype A dtype that looks like `ndtype`, the type of all fields is boolean. Examples -------- >>> import numpy.ma as ma >>> dtype = np.dtype({'names':['foo', 'bar'], 'formats':[np.float32, np.int]}) >>> dtype dtype([('foo', '>> ma.make_mask_descr(dtype) dtype([('foo', '|b1'), ('bar', '|b1')]) >>> ma.make_mask_descr(np.float32) """ # Make sure we do have a dtype if not isinstance(ndtype, np.dtype): ndtype = np.dtype(ndtype) return np.dtype(_recursive_make_descr(ndtype, np.bool)) def getmask(a): """ Return the mask of a masked array, or nomask. Return the mask of `a` as an ndarray if `a` is a `MaskedArray` and the mask is not `nomask`, else return `nomask`. To guarantee a full array of booleans of the same shape as a, use `getmaskarray`. Parameters ---------- a : array_like Input `MaskedArray` for which the mask is required. See Also -------- getdata : Return the data of a masked array as an ndarray. getmaskarray : Return the mask of a masked array, or full array of False. Examples -------- >>> import numpy.ma as ma >>> a = ma.masked_equal([[1,2],[3,4]], 2) >>> a masked_array(data = [[1 --] [3 4]], mask = [[False True] [False False]], fill_value=999999) >>> ma.getmask(a) array([[False, True], [False, False]], dtype=bool) Equivalently use the `MaskedArray` `mask` attribute. >>> a.mask array([[False, True], [False, False]], dtype=bool) Result when mask == `nomask` >>> b = ma.masked_array([[1,2],[3,4]]) >>> b masked_array(data = [[1 2] [3 4]], mask = False, fill_value=999999) >>> ma.nomask False >>> ma.getmask(b) == ma.nomask True >>> b.mask == ma.nomask True """ return getattr(a, '_mask', nomask) get_mask = getmask def getmaskarray(arr): """ Return the mask of a masked array, or full boolean array of False. Return the mask of `arr` as an ndarray if `arr` is a `MaskedArray` and the mask is not `nomask`, else return a full boolean array of False of the same shape as `arr`. Parameters ---------- arr : array_like Input `MaskedArray` for which the mask is required. See Also -------- getmask : Return the mask of a masked array, or nomask. getdata : Return the data of a masked array as an ndarray. Examples -------- >>> import numpy.ma as ma >>> a = ma.masked_equal([[1,2],[3,4]], 2) >>> a masked_array(data = [[1 --] [3 4]], mask = [[False True] [False False]], fill_value=999999) >>> ma.getmaskarray(a) array([[False, True], [False, False]], dtype=bool) Result when mask == ``nomask`` >>> b = ma.masked_array([[1,2],[3,4]]) >>> b masked_array(data = [[1 2] [3 4]], mask = False, fill_value=999999) >>> >ma.getmaskarray(b) array([[False, False], [False, False]], dtype=bool) """ mask = getmask(arr) if mask is nomask: mask = make_mask_none(np.shape(arr), getdata(arr).dtype) return mask def is_mask(m): """ Return True if m is a valid, standard mask. This function does not check the contents of the input, only that the type is MaskType. In particular, this function returns False if the mask has a flexible dtype. Parameters ---------- m : array_like Array to test. Returns ------- result : bool True if `m.dtype.type` is MaskType, False otherwise. See Also -------- isMaskedArray : Test whether input is an instance of MaskedArray. Examples -------- >>> import numpy.ma as ma >>> m = ma.masked_equal([0, 1, 0, 2, 3], 0) >>> m masked_array(data = [-- 1 -- 2 3], mask = [ True False True False False], fill_value=999999) >>> ma.is_mask(m) False >>> ma.is_mask(m.mask) True Input must be an ndarray (or have similar attributes) for it to be considered a valid mask. >>> m = [False, True, False] >>> ma.is_mask(m) False >>> m = np.array([False, True, False]) >>> m array([False, True, False], dtype=bool) >>> ma.is_mask(m) True Arrays with complex dtypes don't return True. >>> dtype = np.dtype({'names':['monty', 'pithon'], 'formats':[np.bool, np.bool]}) >>> dtype dtype([('monty', '|b1'), ('pithon', '|b1')]) >>> m = np.array([(True, False), (False, True), (True, False)], dtype=dtype) >>> m array([(True, False), (False, True), (True, False)], dtype=[('monty', '|b1'), ('pithon', '|b1')]) >>> ma.is_mask(m) False """ try: return m.dtype.type is MaskType except AttributeError: return False def make_mask(m, copy=False, shrink=True, dtype=MaskType): """ Create a boolean mask from an array. Return `m` as a boolean mask, creating a copy if necessary or requested. The function can accept any sequence that is convertible to integers, or ``nomask``. Does not require that contents must be 0s and 1s, values of 0 are interepreted as False, everything else as True. Parameters ---------- m : array_like Potential mask. copy : bool, optional Whether to return a copy of `m` (True) or `m` itself (False). shrink : bool, optional Whether to shrink `m` to ``nomask`` if all its values are False. dtype : dtype, optional Data-type of the output mask. By default, the output mask has a dtype of MaskType (bool). If the dtype is flexible, each field has a boolean dtype. Returns ------- result : ndarray A boolean mask derived from `m`. Examples -------- >>> import numpy.ma as ma >>> m = [True, False, True, True] >>> ma.make_mask(m) array([ True, False, True, True], dtype=bool) >>> m = [1, 0, 1, 1] >>> ma.make_mask(m) array([ True, False, True, True], dtype=bool) >>> m = [1, 0, 2, -3] >>> ma.make_mask(m) array([ True, False, True, True], dtype=bool) Effect of the `shrink` parameter. >>> m = np.zeros(4) >>> m array([ 0., 0., 0., 0.]) >>> ma.make_mask(m) False >>> ma.make_mask(m, shrink=False) array([False, False, False, False], dtype=bool) Using a flexible `dtype`. >>> m = [1, 0, 1, 1] >>> n = [0, 1, 0, 0] >>> arr = [] >>> for man, mouse in zip(m, n): ... arr.append((man, mouse)) >>> arr [(1, 0), (0, 1), (1, 0), (1, 0)] >>> dtype = np.dtype({'names':['man', 'mouse'], 'formats':[np.int, np.int]}) >>> arr = np.array(arr, dtype=dtype) >>> arr array([(1, 0), (0, 1), (1, 0), (1, 0)], dtype=[('man', '>> ma.make_mask(arr, dtype=dtype) array([(True, False), (False, True), (True, False), (True, False)], dtype=[('man', '|b1'), ('mouse', '|b1')]) """ if m is nomask: return nomask elif isinstance(m, ndarray): # We won't return after this point to make sure we can shrink the mask # Fill the mask in case there are missing data m = filled(m, True) # Make sure the input dtype is valid dtype = make_mask_descr(dtype) if m.dtype == dtype: if copy: result = m.copy() else: result = m else: result = np.array(m, dtype=dtype, copy=copy) else: result = np.array(filled(m, True), dtype=MaskType) # Bas les masques ! if shrink and (not result.dtype.names) and (not result.any()): return nomask else: return result def make_mask_none(newshape, dtype=None): """ Return a boolean mask of the given shape, filled with False. This function returns a boolean ndarray with all entries False, that can be used in common mask manipulations. If a complex dtype is specified, the type of each field is converted to a boolean type. Parameters ---------- newshape : tuple A tuple indicating the shape of the mask. dtype : {None, dtype}, optional If None, use a MaskType instance. Otherwise, use a new datatype with the same fields as `dtype`, converted to boolean types. Returns ------- result : ndarray An ndarray of appropriate shape and dtype, filled with False. See Also -------- make_mask : Create a boolean mask from an array. make_mask_descr : Construct a dtype description list from a given dtype. Examples -------- >>> import numpy.ma as ma >>> ma.make_mask_none((3,)) array([False, False, False], dtype=bool) Defining a more complex dtype. >>> dtype = np.dtype({'names':['foo', 'bar'], 'formats':[np.float32, np.int]}) >>> dtype dtype([('foo', '>> ma.make_mask_none((3,), dtype=dtype) array([(False, False), (False, False), (False, False)], dtype=[('foo', '|b1'), ('bar', '|b1')]) """ if dtype is None: result = np.zeros(newshape, dtype=MaskType) else: result = np.zeros(newshape, dtype=make_mask_descr(dtype)) return result def mask_or (m1, m2, copy=False, shrink=True): """ Combine two masks with the ``logical_or`` operator. The result may be a view on `m1` or `m2` if the other is `nomask` (i.e. False). Parameters ---------- m1, m2 : array_like Input masks. copy : bool, optional If copy is False and one of the inputs is `nomask`, return a view of the other input mask. Defaults to False. shrink : bool, optional Whether to shrink the output to `nomask` if all its values are False. Defaults to True. Returns ------- mask : output mask The result masks values that are masked in either `m1` or `m2`. Raises ------ ValueError If `m1` and `m2` have different flexible dtypes. Examples -------- >>> m1 = np.ma.make_mask([0, 1, 1, 0]) >>> m2 = np.ma.make_mask([1, 0, 0, 0]) >>> np.ma.mask_or(m1, m2) array([ True, True, True, False], dtype=bool) """ def _recursive_mask_or(m1, m2, newmask): names = m1.dtype.names for name in names: current1 = m1[name] if current1.dtype.names: _recursive_mask_or(current1, m2[name], newmask[name]) else: umath.logical_or(current1, m2[name], newmask[name]) return # if (m1 is nomask) or (m1 is False): dtype = getattr(m2, 'dtype', MaskType) return make_mask(m2, copy=copy, shrink=shrink, dtype=dtype) if (m2 is nomask) or (m2 is False): dtype = getattr(m1, 'dtype', MaskType) return make_mask(m1, copy=copy, shrink=shrink, dtype=dtype) if m1 is m2 and is_mask(m1): return m1 (dtype1, dtype2) = (getattr(m1, 'dtype', None), getattr(m2, 'dtype', None)) if (dtype1 != dtype2): raise ValueError("Incompatible dtypes '%s'<>'%s'" % (dtype1, dtype2)) if dtype1.names: newmask = np.empty_like(m1) _recursive_mask_or(m1, m2, newmask) return newmask return make_mask(umath.logical_or(m1, m2), copy=copy, shrink=shrink) def flatten_mask(mask): """ Returns a completely flattened version of the mask, where nested fields are collapsed. Parameters ---------- mask : array_like Input array, which will be interpreted as booleans. Returns ------- flattened_mask : ndarray of bools The flattened input. Examples -------- >>> mask = np.array([0, 0, 1], dtype=np.bool) >>> flatten_mask(mask) array([False, False, True], dtype=bool) >>> mask = np.array([(0, 0), (0, 1)], dtype=[('a', bool), ('b', bool)]) >>> flatten_mask(mask) array([False, False, False, True], dtype=bool) >>> mdtype = [('a', bool), ('b', [('ba', bool), ('bb', bool)])] >>> mask = np.array([(0, (0, 0)), (0, (0, 1))], dtype=mdtype) >>> flatten_mask(mask) array([False, False, False, False, False, True], dtype=bool) """ # def _flatmask(mask): "Flatten the mask and returns a (maybe nested) sequence of booleans." mnames = mask.dtype.names if mnames: return [flatten_mask(mask[name]) for name in mnames] else: return mask # def _flatsequence(sequence): "Generates a flattened version of the sequence." try: for element in sequence: if hasattr(element, '__iter__'): for f in _flatsequence(element): yield f else: yield element except TypeError: yield sequence # mask = np.asarray(mask) flattened = _flatsequence(_flatmask(mask)) return np.array([_ for _ in flattened], dtype=bool) def _check_mask_axis(mask, axis): "Check whether there are masked values along the given axis" if mask is not nomask: return mask.all(axis=axis) return nomask #####-------------------------------------------------------------------------- #--- --- Masking functions --- #####-------------------------------------------------------------------------- def masked_where(condition, a, copy=True): """ Mask an array where a condition is met. Return `a` as an array masked where `condition` is True. Any masked values of `a` or `condition` are also masked in the output. Parameters ---------- condition : array_like Masking condition. When `condition` tests floating point values for equality, consider using ``masked_values`` instead. a : array_like Array to mask. copy : bool If True (default) make a copy of `a` in the result. If False modify `a` in place and return a view. Returns ------- result : MaskedArray The result of masking `a` where `condition` is True. See Also -------- masked_values : Mask using floating point equality. masked_equal : Mask where equal to a given value. masked_not_equal : Mask where `not` equal to a given value. masked_less_equal : Mask where less than or equal to a given value. masked_greater_equal : Mask where greater than or equal to a given value. masked_less : Mask where less than a given value. masked_greater : Mask where greater than a given value. masked_inside : Mask inside a given interval. masked_outside : Mask outside a given interval. masked_invalid : Mask invalid values (NaNs or infs). Examples -------- >>> import numpy.ma as ma >>> a = np.arange(4) >>> a array([0, 1, 2, 3]) >>> ma.masked_where(a <= 2, a) masked_array(data = [-- -- -- 3], mask = [ True True True False], fill_value=999999) Mask array `b` conditional on `a`. >>> b = ['a', 'b', 'c', 'd'] >>> ma.masked_where(a == 2, b) masked_array(data = [a b -- d], mask = [False False True False], fill_value=N/A) Effect of the `copy` argument. >>> c = ma.masked_where(a <= 2, a) >>> c masked_array(data = [-- -- -- 3], mask = [ True True True False], fill_value=999999) >>> c[0] = 99 >>> c masked_array(data = [99 -- -- 3], mask = [False True True False], fill_value=999999) >>> a array([0, 1, 2, 3]) >>> c = ma.masked_where(a <= 2, a, copy=False) >>> c[0] = 99 >>> c masked_array(data = [99 -- -- 3], mask = [False True True False], fill_value=999999) >>> a array([99, 1, 2, 3]) When `condition` or `a` contain masked values. >>> a = np.arange(4) >>> a = ma.masked_where(a == 2, a) >>> a masked_array(data = [0 1 -- 3], mask = [False False True False], fill_value=999999) >>> b = np.arange(4) >>> b = ma.masked_where(b == 0, b) >>> b masked_array(data = [-- 1 2 3], mask = [ True False False False], fill_value=999999) >>> ma.masked_where(a == 3, b) masked_array(data = [-- 1 -- --], mask = [ True False True True], fill_value=999999) """ # Make sure that condition is a valid standard-type mask. cond = make_mask(condition) a = np.array(a, copy=copy, subok=True) (cshape, ashape) = (cond.shape, a.shape) if cshape and cshape != ashape: raise IndexError("Inconsistant shape between the condition and the input" " (got %s and %s)" % (cshape, ashape)) if hasattr(a, '_mask'): cond = mask_or(cond, a._mask) cls = type(a) else: cls = MaskedArray result = a.view(cls) result._mask = cond return result def masked_greater(x, value, copy=True): """ Mask an array where greater than a given value. This function is a shortcut to ``masked_where``, with `condition` = (x > value). See Also -------- masked_where : Mask where a condition is met. Examples -------- >>> import numpy.ma as ma >>> a = np.arange(4) >>> a array([0, 1, 2, 3]) >>> ma.masked_greater(a, 2) masked_array(data = [0 1 2 --], mask = [False False False True], fill_value=999999) """ return masked_where(greater(x, value), x, copy=copy) def masked_greater_equal(x, value, copy=True): """ Mask an array where greater than or equal to a given value. This function is a shortcut to ``masked_where``, with `condition` = (x >= value). See Also -------- masked_where : Mask where a condition is met. Examples -------- >>> import numpy.ma as ma >>> a = np.arange(4) >>> a array([0, 1, 2, 3]) >>> ma.masked_greater_equal(a, 2) masked_array(data = [0 1 -- --], mask = [False False True True], fill_value=999999) """ return masked_where(greater_equal(x, value), x, copy=copy) def masked_less(x, value, copy=True): """ Mask an array where less than a given value. This function is a shortcut to ``masked_where``, with `condition` = (x < value). See Also -------- masked_where : Mask where a condition is met. Examples -------- >>> import numpy.ma as ma >>> a = np.arange(4) >>> a array([0, 1, 2, 3]) >>> ma.masked_less(a, 2) masked_array(data = [-- -- 2 3], mask = [ True True False False], fill_value=999999) """ return masked_where(less(x, value), x, copy=copy) def masked_less_equal(x, value, copy=True): """ Mask an array where less than or equal to a given value. This function is a shortcut to ``masked_where``, with `condition` = (x <= value). See Also -------- masked_where : Mask where a condition is met. Examples -------- >>> import numpy.ma as ma >>> a = np.arange(4) >>> a array([0, 1, 2, 3]) >>> ma.masked_less_equal(a, 2) masked_array(data = [-- -- -- 3], mask = [ True True True False], fill_value=999999) """ return masked_where(less_equal(x, value), x, copy=copy) def masked_not_equal(x, value, copy=True): """ Mask an array where `not` equal to a given value. This function is a shortcut to ``masked_where``, with `condition` = (x != value). See Also -------- masked_where : Mask where a condition is met. Examples -------- >>> import numpy.ma as ma >>> a = np.arange(4) >>> a array([0, 1, 2, 3]) >>> ma.masked_not_equal(a, 2) masked_array(data = [-- -- 2 --], mask = [ True True False True], fill_value=999999) """ return masked_where(not_equal(x, value), x, copy=copy) def masked_equal(x, value, copy=True): """ Mask an array where equal to a given value. This function is a shortcut to ``masked_where``, with `condition` = (x == value). For floating point arrays, consider using ``masked_values(x, value)``. See Also -------- masked_where : Mask where a condition is met. masked_values : Mask using floating point equality. Examples -------- >>> import numpy.ma as ma >>> a = np.arange(4) >>> a array([0, 1, 2, 3]) >>> ma.masked_equal(a, 2) masked_array(data = [0 1 -- 3], mask = [False False True False], fill_value=999999) """ # An alternative implementation relies on filling first: probably not needed. # d = filled(x, 0) # c = umath.equal(d, value) # m = mask_or(c, getmask(x)) # return array(d, mask=m, copy=copy) output = masked_where(equal(x, value), x, copy=copy) output.fill_value = value return output def masked_inside(x, v1, v2, copy=True): """ Mask an array inside a given interval. Shortcut to ``masked_where``, where `condition` is True for `x` inside the interval [v1,v2] (v1 <= x <= v2). The boundaries `v1` and `v2` can be given in either order. See Also -------- masked_where : Mask where a condition is met. Notes ----- The array `x` is prefilled with its filling value. Examples -------- >>> import numpy.ma as ma >>> x = [0.31, 1.2, 0.01, 0.2, -0.4, -1.1] >>> ma.masked_inside(x, -0.3, 0.3) masked_array(data = [0.31 1.2 -- -- -0.4 -1.1], mask = [False False True True False False], fill_value=1e+20) The order of `v1` and `v2` doesn't matter. >>> ma.masked_inside(x, 0.3, -0.3) masked_array(data = [0.31 1.2 -- -- -0.4 -1.1], mask = [False False True True False False], fill_value=1e+20) """ if v2 < v1: (v1, v2) = (v2, v1) xf = filled(x) condition = (xf >= v1) & (xf <= v2) return masked_where(condition, x, copy=copy) def masked_outside(x, v1, v2, copy=True): """ Mask an array outside a given interval. Shortcut to ``masked_where``, where `condition` is True for `x` outside the interval [v1,v2] (x < v1)|(x > v2). The boundaries `v1` and `v2` can be given in either order. See Also -------- masked_where : Mask where a condition is met. Notes ----- The array `x` is prefilled with its filling value. Examples -------- >>> import numpy.ma as ma >>> x = [0.31, 1.2, 0.01, 0.2, -0.4, -1.1] >>> ma.masked_outside(x, -0.3, 0.3) masked_array(data = [-- -- 0.01 0.2 -- --], mask = [ True True False False True True], fill_value=1e+20) The order of `v1` and `v2` doesn't matter. >>> ma.masked_outside(x, 0.3, -0.3) masked_array(data = [-- -- 0.01 0.2 -- --], mask = [ True True False False True True], fill_value=1e+20) """ if v2 < v1: (v1, v2) = (v2, v1) xf = filled(x) condition = (xf < v1) | (xf > v2) return masked_where(condition, x, copy=copy) def masked_object(x, value, copy=True, shrink=True): """ Mask the array `x` where the data are exactly equal to value. This function is similar to `masked_values`, but only suitable for object arrays: for floating point, use `masked_values` instead. Parameters ---------- x : array_like Array to mask value : object Comparison value copy : {True, False}, optional Whether to return a copy of `x`. shrink : {True, False}, optional Whether to collapse a mask full of False to nomask Returns ------- result : MaskedArray The result of masking `x` where equal to `value`. See Also -------- masked_where : Mask where a condition is met. masked_equal : Mask where equal to a given value (integers). masked_values : Mask using floating point equality. Examples -------- >>> import numpy.ma as ma >>> food = np.array(['green_eggs', 'ham'], dtype=object) >>> # don't eat spoiled food >>> eat = ma.masked_object(food, 'green_eggs') >>> print eat [-- ham] >>> # plain ol` ham is boring >>> fresh_food = np.array(['cheese', 'ham', 'pineapple'], dtype=object) >>> eat = ma.masked_object(fresh_food, 'green_eggs') >>> print eat [cheese ham pineapple] Note that `mask` is set to ``nomask`` if possible. >>> eat masked_array(data = [cheese ham pineapple], mask = False, fill_value=?) """ if isMaskedArray(x): condition = umath.equal(x._data, value) mask = x._mask else: condition = umath.equal(np.asarray(x), value) mask = nomask mask = mask_or(mask, make_mask(condition, shrink=shrink)) return masked_array(x, mask=mask, copy=copy, fill_value=value) def masked_values(x, value, rtol=1e-5, atol=1e-8, copy=True, shrink=True): """ Mask using floating point equality. Return a MaskedArray, masked where the data in array `x` are approximately equal to `value`, i.e. where the following condition is True (abs(x - value) <= atol+rtol*abs(value)) The fill_value is set to `value` and the mask is set to ``nomask`` if possible. For integers, consider using ``masked_equal``. Parameters ---------- x : array_like Array to mask. value : float Masking value. rtol : float, optional Tolerance parameter. atol : float, optional Tolerance parameter (1e-8). copy : bool, optional Whether to return a copy of `x`. shrink : bool, optional Whether to collapse a mask full of False to ``nomask``. Returns ------- result : MaskedArray The result of masking `x` where approximately equal to `value`. See Also -------- masked_where : Mask where a condition is met. masked_equal : Mask where equal to a given value (integers). Examples -------- >>> import numpy.ma as ma >>> x = np.array([1, 1.1, 2, 1.1, 3]) >>> ma.masked_values(x, 1.1) masked_array(data = [1.0 -- 2.0 -- 3.0], mask = [False True False True False], fill_value=1.1) Note that `mask` is set to ``nomask`` if possible. >>> ma.masked_values(x, 1.5) masked_array(data = [ 1. 1.1 2. 1.1 3. ], mask = False, fill_value=1.5) For integers, the fill value will be different in general to the result of ``masked_equal``. >>> x = np.arange(5) >>> x array([0, 1, 2, 3, 4]) >>> ma.masked_values(x, 2) masked_array(data = [0 1 -- 3 4], mask = [False False True False False], fill_value=2) >>> ma.masked_equal(x, 2) masked_array(data = [0 1 -- 3 4], mask = [False False True False False], fill_value=999999) """ mabs = umath.absolute xnew = filled(x, value) if issubclass(xnew.dtype.type, np.floating): condition = umath.less_equal(mabs(xnew - value), atol + rtol * mabs(value)) mask = getattr(x, '_mask', nomask) else: condition = umath.equal(xnew, value) mask = nomask mask = mask_or(mask, make_mask(condition, shrink=shrink)) return masked_array(xnew, mask=mask, copy=copy, fill_value=value) def masked_invalid(a, copy=True): """ Mask an array where invalid values occur (NaNs or infs). This function is a shortcut to ``masked_where``, with `condition` = ~(np.isfinite(a)). Any pre-existing mask is conserved. Only applies to arrays with a dtype where NaNs or infs make sense (i.e. floating point types), but accepts any array_like object. See Also -------- masked_where : Mask where a condition is met. Examples -------- >>> import numpy.ma as ma >>> a = np.arange(5, dtype=np.float) >>> a[2] = np.NaN >>> a[3] = np.PINF >>> a array([ 0., 1., NaN, Inf, 4.]) >>> ma.masked_invalid(a) masked_array(data = [0.0 1.0 -- -- 4.0], mask = [False False True True False], fill_value=1e+20) """ a = np.array(a, copy=copy, subok=True) mask = getattr(a, '_mask', None) if mask is not None: condition = ~(np.isfinite(getdata(a))) if mask is not nomask: condition |= mask cls = type(a) else: condition = ~(np.isfinite(a)) cls = MaskedArray result = a.view(cls) result._mask = condition return result #####-------------------------------------------------------------------------- #---- --- Printing options --- #####-------------------------------------------------------------------------- class _MaskedPrintOption: """ Handle the string used to represent missing data in a masked array. """ def __init__ (self, display): "Create the masked_print_option object." self._display = display self._enabled = True def display(self): "Display the string to print for masked values." return self._display def set_display (self, s): "Set the string to print for masked values." self._display = s def enabled(self): "Is the use of the display value enabled?" return self._enabled def enable(self, shrink=1): "Set the enabling shrink to `shrink`." self._enabled = shrink def __str__ (self): return str(self._display) __repr__ = __str__ #if you single index into a masked location you get this object. masked_print_option = _MaskedPrintOption('--') def _recursive_printoption(result, mask, printopt): """ Puts printoptions in result where mask is True. Private function allowing for recursion """ names = result.dtype.names for name in names: (curdata, curmask) = (result[name], mask[name]) if curdata.dtype.names: _recursive_printoption(curdata, curmask, printopt) else: np.copyto(curdata, printopt, where=curmask) return _print_templates = dict(long_std="""\ masked_%(name)s(data = %(data)s, %(nlen)s mask = %(mask)s, %(nlen)s fill_value = %(fill)s) """, short_std="""\ masked_%(name)s(data = %(data)s, %(nlen)s mask = %(mask)s, %(nlen)s fill_value = %(fill)s) """, long_flx="""\ masked_%(name)s(data = %(data)s, %(nlen)s mask = %(mask)s, %(nlen)s fill_value = %(fill)s, %(nlen)s dtype = %(dtype)s) """, short_flx="""\ masked_%(name)s(data = %(data)s, %(nlen)s mask = %(mask)s, %(nlen)s fill_value = %(fill)s, %(nlen)s dtype = %(dtype)s) """) #####-------------------------------------------------------------------------- #---- --- MaskedArray class --- #####-------------------------------------------------------------------------- def _recursive_filled(a, mask, fill_value): """ Recursively fill `a` with `fill_value`. Private function """ names = a.dtype.names for name in names: current = a[name] if current.dtype.names: _recursive_filled(current, mask[name], fill_value[name]) else: np.copyto(current, fill_value[name], where=mask[name]) def flatten_structured_array(a): """ Flatten a structured array. The data type of the output is chosen such that it can represent all of the (nested) fields. Parameters ---------- a : structured array Returns ------- output : masked array or ndarray A flattened masked array if the input is a masked array, otherwise a standard ndarray. Examples -------- >>> ndtype = [('a', int), ('b', float)] >>> a = np.array([(1, 1), (2, 2)], dtype=ndtype) >>> flatten_structured_array(a) array([[1., 1.], [2., 2.]]) """ # def flatten_sequence(iterable): """Flattens a compound of nested iterables.""" for elm in iter(iterable): if hasattr(elm, '__iter__'): for f in flatten_sequence(elm): yield f else: yield elm # a = np.asanyarray(a) inishape = a.shape a = a.ravel() if isinstance(a, MaskedArray): out = np.array([tuple(flatten_sequence(d.item())) for d in a._data]) out = out.view(MaskedArray) out._mask = np.array([tuple(flatten_sequence(d.item())) for d in getmaskarray(a)]) else: out = np.array([tuple(flatten_sequence(d.item())) for d in a]) if len(inishape) > 1: newshape = list(out.shape) newshape[0] = inishape out.shape = tuple(flatten_sequence(newshape)) return out class _arraymethod(object): """ Define a wrapper for basic array methods. Upon call, returns a masked array, where the new ``_data`` array is the output of the corresponding method called on the original ``_data``. If `onmask` is True, the new mask is the output of the method called on the initial mask. Otherwise, the new mask is just a reference to the initial mask. Attributes ---------- _onmask : bool Holds the `onmask` parameter. obj : object The object calling `_arraymethod`. Parameters ---------- funcname : str Name of the function to apply on data. onmask : bool Whether the mask must be processed also (True) or left alone (False). Default is True. Make available as `_onmask` attribute. """ def __init__(self, funcname, onmask=True): self.__name__ = funcname self._onmask = onmask self.obj = None self.__doc__ = self.getdoc() # def getdoc(self): "Return the doc of the function (from the doc of the method)." methdoc = getattr(ndarray, self.__name__, None) or \ getattr(np, self.__name__, None) if methdoc is not None: return methdoc.__doc__ # def __get__(self, obj, objtype=None): self.obj = obj return self # def __call__(self, *args, **params): methodname = self.__name__ instance = self.obj # Fallback : if the instance has not been initialized, use the first arg if instance is None: args = list(args) instance = args.pop(0) data = instance._data mask = instance._mask cls = type(instance) result = getattr(data, methodname)(*args, **params).view(cls) result._update_from(instance) if result.ndim: if not self._onmask: result.__setmask__(mask) elif mask is not nomask: result.__setmask__(getattr(mask, methodname)(*args, **params)) else: if mask.ndim and (not mask.dtype.names and mask.all()): return masked return result class MaskedIterator(object): """ Flat iterator object to iterate over masked arrays. A `MaskedIterator` iterator is returned by ``x.flat`` for any masked array `x`. It allows iterating over the array as if it were a 1-D array, either in a for-loop or by calling its `next` method. Iteration is done in C-contiguous style, with the last index varying the fastest. The iterator can also be indexed using basic slicing or advanced indexing. See Also -------- MaskedArray.flat : Return a flat iterator over an array. MaskedArray.flatten : Returns a flattened copy of an array. Notes ----- `MaskedIterator` is not exported by the `ma` module. Instead of instantiating a `MaskedIterator` directly, use `MaskedArray.flat`. Examples -------- >>> x = np.ma.array(arange(6).reshape(2, 3)) >>> fl = x.flat >>> type(fl) >>> for item in fl: ... print item ... 0 1 2 3 4 5 Extracting more than a single element b indexing the `MaskedIterator` returns a masked array: >>> fl[2:4] masked_array(data = [2 3], mask = False, fill_value = 999999) """ def __init__(self, ma): self.ma = ma self.dataiter = ma._data.flat # if ma._mask is nomask: self.maskiter = None else: self.maskiter = ma._mask.flat def __iter__(self): return self def __getitem__(self, indx): 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 return result ### This won't work is ravel makes a copy def __setitem__(self, index, value): self.dataiter[index] = getdata(value) if self.maskiter is not None: self.maskiter[index] = getmaskarray(value) def __next__(self): """ Return the next value, or raise StopIteration. Examples -------- >>> x = np.ma.array([3, 2], mask=[0, 1]) >>> fl = x.flat >>> fl.next() 3 >>> fl.next() masked_array(data = --, mask = True, fill_value = 1e+20) >>> fl.next() Traceback (most recent call last): File "", line 1, in File "/home/ralf/python/numpy/numpy/ma/core.py", line 2243, in next d = self.dataiter.next() StopIteration """ d = next(self.dataiter) if self.maskiter is not None and next(self.maskiter): d = masked return d next = __next__ class MaskedArray(ndarray): """ An array class with possibly masked values. Masked values of True exclude the corresponding element from any computation. Construction:: x = MaskedArray(data, mask=nomask, dtype=None, copy=False, subok=True, ndmin=0, fill_value=None, keep_mask=True, hard_mask=None, shrink=True) Parameters ---------- data : array_like Input data. mask : sequence, optional Mask. Must be convertible to an array of booleans with the same shape as `data`. True indicates a masked (i.e. invalid) data. dtype : dtype, optional Data type of the output. If `dtype` is None, the type of the data argument (``data.dtype``) is used. If `dtype` is not None and different from ``data.dtype``, a copy is performed. copy : bool, optional Whether to copy the input data (True), or to use a reference instead. Default is False. subok : bool, optional Whether to return a subclass of `MaskedArray` if possible (True) or a plain `MaskedArray`. Default is True. ndmin : int, optional Minimum number of dimensions. Default is 0. fill_value : scalar, optional Value used to fill in the masked values when necessary. If None, a default based on the data-type is used. keep_mask : bool, optional Whether to combine `mask` with the mask of the input data, if any (True), or to use only `mask` for the output (False). Default is True. hard_mask : bool, optional Whether to use a hard mask or not. With a hard mask, masked values cannot be unmasked. Default is False. shrink : bool, optional Whether to force compression of an empty mask. Default is True. """ __array_priority__ = 15 _defaultmask = nomask _defaulthardmask = False _baseclass = ndarray def __new__(cls, data=None, mask=nomask, dtype=None, copy=False, subok=True, ndmin=0, fill_value=None, keep_mask=True, hard_mask=None, shrink=True, **options): """ Create a new masked array from scratch. Notes ----- A masked array can also be created by taking a .view(MaskedArray). """ # Process data............ _data = np.array(data, dtype=dtype, copy=copy, subok=True, ndmin=ndmin) _baseclass = getattr(data, '_baseclass', type(_data)) # Check that we're not erasing the mask.......... if isinstance(data, MaskedArray) and (data.shape != _data.shape): copy = True # Careful, cls might not always be MaskedArray... if not isinstance(data, cls) or not subok: _data = ndarray.view(_data, cls) else: _data = ndarray.view(_data, type(data)) # Backwards compatibility w/ numpy.core.ma ....... if hasattr(data, '_mask') and not isinstance(data, ndarray): _data._mask = data._mask _sharedmask = True # Process mask ............................... # Number of named fields (or zero if none) names_ = _data.dtype.names or () # Type of the mask if names_: mdtype = make_mask_descr(_data.dtype) else: mdtype = MaskType # Case 1. : no mask in input ............ if mask is nomask: # Erase the current mask ? if not keep_mask: # With a reduced version if shrink: _data._mask = nomask # With full version else: _data._mask = np.zeros(_data.shape, dtype=mdtype) # Check whether we missed something elif isinstance(data, (tuple, list)): try: # If data is a sequence of masked array mask = np.array([getmaskarray(m) for m in data], dtype=mdtype) except ValueError: # If data is nested mask = nomask # Force shrinking of the mask if needed (and possible) if (mdtype == MaskType) and mask.any(): _data._mask = mask _data._sharedmask = False else: if copy: _data._mask = _data._mask.copy() _data._sharedmask = False # Reset the shape of the original mask if getmask(data) is not nomask: data._mask.shape = data.shape else: _data._sharedmask = True # Case 2. : With a mask in input ........ else: # Read the mask with the current mdtype try: mask = np.array(mask, copy=copy, dtype=mdtype) # Or assume it's a sequence of bool/int except TypeError: mask = np.array([tuple([m] * len(mdtype)) for m in mask], dtype=mdtype) # Make sure the mask and the data have the same shape if mask.shape != _data.shape: (nd, nm) = (_data.size, mask.size) if nm == 1: mask = np.resize(mask, _data.shape) elif nm == nd: mask = np.reshape(mask, _data.shape) else: msg = "Mask and data not compatible: data size is %i, " + \ "mask size is %i." raise MaskError(msg % (nd, nm)) copy = True # Set the mask to the new value if _data._mask is nomask: _data._mask = mask _data._sharedmask = not copy else: if not keep_mask: _data._mask = mask _data._sharedmask = not copy else: if names_: def _recursive_or(a, b): "do a|=b on each field of a, recursively" for name in a.dtype.names: (af, bf) = (a[name], b[name]) if af.dtype.names: _recursive_or(af, bf) else: af |= bf return _recursive_or(_data._mask, mask) else: _data._mask = np.logical_or(mask, _data._mask) _data._sharedmask = False # Update fill_value....... if fill_value is None: fill_value = getattr(data, '_fill_value', None) # But don't run the check unless we have something to check.... if fill_value is not None: _data._fill_value = _check_fill_value(fill_value, _data.dtype) # Process extra options .. if hard_mask is None: _data._hardmask = getattr(data, '_hardmask', False) else: _data._hardmask = hard_mask _data._baseclass = _baseclass return _data # def _update_from(self, obj): """Copies some attributes of obj to self. """ if obj is not None and isinstance(obj, ndarray): _baseclass = type(obj) else: _baseclass = ndarray # We need to copy the _basedict to avoid backward propagation _optinfo = {} _optinfo.update(getattr(obj, '_optinfo', {})) _optinfo.update(getattr(obj, '_basedict', {})) if not isinstance(obj, MaskedArray): _optinfo.update(getattr(obj, '__dict__', {})) _dict = dict(_fill_value=getattr(obj, '_fill_value', None), _hardmask=getattr(obj, '_hardmask', False), _sharedmask=getattr(obj, '_sharedmask', False), _isfield=getattr(obj, '_isfield', False), _baseclass=getattr(obj, '_baseclass', _baseclass), _optinfo=_optinfo, _basedict=_optinfo) self.__dict__.update(_dict) self.__dict__.update(_optinfo) return def __array_finalize__(self, obj): """Finalizes the masked array. """ # Get main attributes ......... self._update_from(obj) if isinstance(obj, ndarray): odtype = obj.dtype if odtype.names: _mask = getattr(obj, '_mask', make_mask_none(obj.shape, odtype)) else: _mask = getattr(obj, '_mask', nomask) else: _mask = nomask self._mask = _mask # Finalize the mask ........... if self._mask is not nomask: try: self._mask.shape = self.shape except ValueError: self._mask = nomask except (TypeError, AttributeError): # When _mask.shape is not writable (because it's a void) pass # Finalize the fill_value for structured arrays if self.dtype.names: if self._fill_value is None: self._fill_value = _check_fill_value(None, self.dtype) return def __array_wrap__(self, obj, context=None): """ Special hook for ufuncs. Wraps the numpy array and sets the mask according to context. """ result = obj.view(type(self)) result._update_from(self) #.......... if context is not None: result._mask = result._mask.copy() (func, args, _) = context m = reduce(mask_or, [getmaskarray(arg) for arg in args]) # Get the domain mask................ domain = ufunc_domain.get(func, None) if domain is not None: # Take the domain, and make sure it's a ndarray if len(args) > 2: d = filled(reduce(domain, args), True) else: d = filled(domain(*args), True) # Fill the result where the domain is wrong try: # Binary domain: take the last value fill_value = ufunc_fills[func][-1] except TypeError: # Unary domain: just use this one fill_value = ufunc_fills[func] except KeyError: # Domain not recognized, use fill_value instead fill_value = self.fill_value result = result.copy() np.copyto(result, fill_value, where=d) # Update the mask if m is nomask: if d is not nomask: m = d else: # Don't modify inplace, we risk back-propagation m = (m | d) # Make sure the mask has the proper size if result.shape == () and m: return masked else: result._mask = m result._sharedmask = False #.... return result def view(self, dtype=None, type=None, fill_value=None): """ Return a view of the MaskedArray data Parameters ---------- dtype : data-type or ndarray sub-class, optional Data-type descriptor of the returned view, e.g., float32 or int16. The default, None, results in the view having the same data-type as `a`. As with ``ndarray.view``, dtype can also be specified as an ndarray sub-class, which then specifies the type of the returned object (this is equivalent to setting the ``type`` parameter). type : Python type, optional Type of the returned view, e.g., ndarray or matrix. Again, the default None results in type preservation. Notes ----- ``a.view()`` is used two different ways: ``a.view(some_dtype)`` or ``a.view(dtype=some_dtype)`` constructs a view of the array's memory with a different data-type. This can cause a reinterpretation of the bytes of memory. ``a.view(ndarray_subclass)`` or ``a.view(type=ndarray_subclass)`` just returns an instance of `ndarray_subclass` that looks at the same array (same shape, dtype, etc.) This does not cause a reinterpretation of the memory. If `fill_value` is not specified, but `dtype` is specified (and is not an ndarray sub-class), the `fill_value` of the MaskedArray will be reset. If neither `fill_value` nor `dtype` are specified (or if `dtype` is an ndarray sub-class), then the fill value is preserved. Finally, if `fill_value` is specified, but `dtype` is not, the fill value is set to the specified value. For ``a.view(some_dtype)``, if ``some_dtype`` has a different number of bytes per entry than the previous dtype (for example, converting a regular array to a structured array), then the behavior of the view cannot be predicted just from the superficial appearance of ``a`` (shown by ``print(a)``). It also depends on exactly how ``a`` is stored in memory. Therefore if ``a`` is C-ordered versus fortran-ordered, versus defined as a slice or transpose, etc., the view may give different results. """ if dtype is None: if type is None: output = ndarray.view(self) else: output = ndarray.view(self, type) elif type is None: try: if issubclass(dtype, ndarray): output = ndarray.view(self, dtype) dtype = None else: output = ndarray.view(self, dtype) except TypeError: output = ndarray.view(self, dtype) else: output = ndarray.view(self, dtype, type) # Should we update the mask ? if (getattr(output, '_mask', nomask) is not nomask): if dtype is None: dtype = output.dtype mdtype = make_mask_descr(dtype) output._mask = self._mask.view(mdtype, ndarray) # Try to reset the shape of the mask (if we don't have a void) try: output._mask.shape = output.shape except (AttributeError, TypeError): pass # Make sure to reset the _fill_value if needed if getattr(output, '_fill_value', None) is not None: if fill_value is None: if dtype is None: pass # leave _fill_value as is else: output._fill_value = None else: output.fill_value = fill_value return output view.__doc__ = ndarray.view.__doc__ def astype(self, newtype): """ Returns a copy of the MaskedArray cast to given newtype. Returns ------- output : MaskedArray A copy of self cast to input newtype. The returned record shape matches self.shape. Examples -------- >>> x = np.ma.array([[1,2,3.1],[4,5,6],[7,8,9]], mask=[0] + [1,0]*4) >>> print x [[1.0 -- 3.1] [-- 5.0 --] [7.0 -- 9.0]] >>> print x.astype(int32) [[1 -- 3] [-- 5 --] [7 -- 9]] """ newtype = np.dtype(newtype) output = self._data.astype(newtype).view(type(self)) output._update_from(self) names = output.dtype.names if names is None: output._mask = self._mask.astype(bool) else: if self._mask is nomask: output._mask = nomask else: output._mask = self._mask.astype([(n, bool) for n in names]) # Don't check _fill_value if it's None, that'll speed things up if self._fill_value is not None: output._fill_value = _check_fill_value(self._fill_value, newtype) return output def __getitem__(self, indx): """x.__getitem__(y) <==> x[y] Return the item described by i, as a masked array. """ # This test is useful, but we should keep things light... # if getmask(indx) is not nomask: # msg = "Masked arrays must be filled before they can be used as indices!" # raise IndexError(msg) _data = ndarray.view(self, ndarray) dout = ndarray.__getitem__(_data, indx) # We could directly use ndarray.__getitem__ on self... # But then we would have to modify __array_finalize__ to prevent the # mask of being reshaped if it hasn't been set up properly yet... # So it's easier to stick to the current version _mask = self._mask if not getattr(dout, 'ndim', False): # A record ................ if isinstance(dout, np.void): mask = _mask[indx] # We should always re-cast to mvoid, otherwise users can # change masks on rows that already have masked values, but not # on rows that have no masked values, which is inconsistent. dout = mvoid(dout, mask=mask, hardmask=self._hardmask) # Just a scalar............ elif _mask is not nomask and _mask[indx]: return masked else: # Force dout to MA ........ dout = dout.view(type(self)) # Inherit attributes from self dout._update_from(self) # Check the fill_value .... if isinstance(indx, basestring): if self._fill_value is not None: dout._fill_value = self._fill_value[indx] dout._isfield = True # Update the mask if needed if _mask is not nomask: dout._mask = _mask[indx] dout._sharedmask = True # Note: Don't try to check for m.any(), that'll take too long... return dout def __setitem__(self, indx, value): """x.__setitem__(i, y) <==> x[i]=y Set item described by index. If value is masked, masks those locations. """ if self is masked: raise MaskError('Cannot alter the masked element.') # This test is useful, but we should keep things light... # if getmask(indx) is not nomask: # msg = "Masked arrays must be filled before they can be used as indices!" # raise IndexError(msg) _data = ndarray.view(self, ndarray.__getattribute__(self, '_baseclass')) _mask = ndarray.__getattribute__(self, '_mask') if isinstance(indx, basestring): ndarray.__setitem__(_data, indx, value) if _mask is nomask: self._mask = _mask = make_mask_none(self.shape, self.dtype) _mask[indx] = getmask(value) return #........................................ _dtype = ndarray.__getattribute__(_data, 'dtype') nbfields = len(_dtype.names or ()) #........................................ if value is masked: # The mask wasn't set: create a full version... if _mask is nomask: _mask = self._mask = make_mask_none(self.shape, _dtype) # Now, set the mask to its value. if nbfields: _mask[indx] = tuple([True] * nbfields) else: _mask[indx] = True if not self._isfield: self._sharedmask = False return #........................................ # Get the _data part of the new value dval = value # Get the _mask part of the new value mval = getattr(value, '_mask', nomask) if nbfields and mval is nomask: mval = tuple([False] * nbfields) if _mask is nomask: # Set the data, then the mask ndarray.__setitem__(_data, indx, dval) if mval is not nomask: _mask = self._mask = make_mask_none(self.shape, _dtype) ndarray.__setitem__(_mask, indx, mval) elif not self._hardmask: # Unshare the mask if necessary to avoid propagation if not self._isfield: self.unshare_mask() _mask = ndarray.__getattribute__(self, '_mask') # Set the data, then the mask ndarray.__setitem__(_data, indx, dval) ndarray.__setitem__(_mask, indx, mval) elif hasattr(indx, 'dtype') and (indx.dtype == MaskType): indx = indx * umath.logical_not(_mask) ndarray.__setitem__(_data, indx, dval) else: if nbfields: err_msg = "Flexible 'hard' masks are not yet supported..." raise NotImplementedError(err_msg) mindx = mask_or(_mask[indx], mval, copy=True) dindx = self._data[indx] if dindx.size > 1: np.copyto(dindx, dval, where=~mindx) elif mindx is nomask: dindx = dval ndarray.__setitem__(_data, indx, dindx) _mask[indx] = mindx return def __getslice__(self, i, j): """x.__getslice__(i, j) <==> x[i:j] Return the slice described by (i, j). The use of negative indices is not supported. """ return self.__getitem__(slice(i, j)) def __setslice__(self, i, j, value): """x.__setslice__(i, j, value) <==> x[i:j]=value Set the slice (i,j) of a to value. If value is masked, mask those locations. """ self.__setitem__(slice(i, j), value) def __setmask__(self, mask, copy=False): """Set the mask. """ idtype = ndarray.__getattribute__(self, 'dtype') current_mask = ndarray.__getattribute__(self, '_mask') if mask is masked: mask = True # Make sure the mask is set if (current_mask is nomask): # Just don't do anything is there's nothing to do... if mask is nomask: return current_mask = self._mask = make_mask_none(self.shape, idtype) # No named fields......... if idtype.names is None: # Hardmask: don't unmask the data if self._hardmask: current_mask |= mask # Softmask: set everything to False # If it's obviously a compatible scalar, use a quick update # method... elif isinstance(mask, (int, float, np.bool_, np.number)): current_mask[...] = mask # ...otherwise fall back to the slower, general purpose way. else: current_mask.flat = mask # Named fields w/ ............ else: mdtype = current_mask.dtype mask = np.array(mask, copy=False) # Mask is a singleton if not mask.ndim: # It's a boolean : make a record if mask.dtype.kind == 'b': mask = np.array(tuple([mask.item()]*len(mdtype)), dtype=mdtype) # It's a record: make sure the dtype is correct else: mask = mask.astype(mdtype) # Mask is a sequence else: # Make sure the new mask is a ndarray with the proper dtype try: mask = np.array(mask, copy=copy, dtype=mdtype) # Or assume it's a sequence of bool/int except TypeError: mask = np.array([tuple([m] * len(mdtype)) for m in mask], dtype=mdtype) # Hardmask: don't unmask the data if self._hardmask: for n in idtype.names: current_mask[n] |= mask[n] # Softmask: set everything to False # If it's obviously a compatible scalar, use a quick update # method... elif isinstance(mask, (int, float, np.bool_, np.number)): current_mask[...] = mask # ...otherwise fall back to the slower, general purpose way. else: current_mask.flat = mask # Reshape if needed if current_mask.shape: current_mask.shape = self.shape return _set_mask = __setmask__ #.... def _get_mask(self): """Return the current mask. """ # We could try to force a reshape, but that wouldn't work in some cases. # return self._mask.reshape(self.shape) return self._mask mask = property(fget=_get_mask, fset=__setmask__, doc="Mask") def _get_recordmask(self): """ Return the mask of the records. A record is masked when all the fields are masked. """ _mask = ndarray.__getattribute__(self, '_mask').view(ndarray) if _mask.dtype.names is None: return _mask return np.all(flatten_structured_array(_mask), axis= -1) def _set_recordmask(self): """Return the mask of the records. A record is masked when all the fields are masked. """ raise NotImplementedError("Coming soon: setting the mask per records!") recordmask = property(fget=_get_recordmask) #............................................ def harden_mask(self): """ Force the mask to hard. Whether the mask of a masked array is hard or soft is determined by its `hardmask` property. `harden_mask` sets `hardmask` to True. See Also -------- hardmask """ self._hardmask = True return self def soften_mask(self): """ Force the mask to soft. Whether the mask of a masked array is hard or soft is determined by its `hardmask` property. `soften_mask` sets `hardmask` to False. See Also -------- hardmask """ self._hardmask = False return self hardmask = property(fget=lambda self: self._hardmask, doc="Hardness of the mask") def unshare_mask(self): """ Copy the mask and set the sharedmask flag to False. Whether the mask is shared between masked arrays can be seen from the `sharedmask` property. `unshare_mask` ensures the mask is not shared. A copy of the mask is only made if it was shared. See Also -------- sharedmask """ if self._sharedmask: self._mask = self._mask.copy() self._sharedmask = False return self sharedmask = property(fget=lambda self: self._sharedmask, doc="Share status of the mask (read-only).") def shrink_mask(self): """ Reduce a mask to nomask when possible. Parameters ---------- None Returns ------- None Examples -------- >>> x = np.ma.array([[1,2 ], [3, 4]], mask=[0]*4) >>> x.mask array([[False, False], [False, False]], dtype=bool) >>> x.shrink_mask() >>> x.mask False """ m = self._mask if m.ndim and not m.any(): self._mask = nomask return self #............................................ baseclass = property(fget=lambda self:self._baseclass, doc="Class of the underlying data (read-only).") def _get_data(self): """Return the current data, as a view of the original underlying data. """ return ndarray.view(self, self._baseclass) _data = property(fget=_get_data) data = property(fget=_get_data) def _get_flat(self): "Return a flat iterator." return MaskedIterator(self) # def _set_flat (self, value): "Set a flattened version of self to value." y = self.ravel() y[:] = value # flat = property(fget=_get_flat, fset=_set_flat, doc="Flat version of the array.") def get_fill_value(self): """ Return the filling value of the masked array. Returns ------- fill_value : scalar The filling value. Examples -------- >>> for dt in [np.int32, np.int64, np.float64, np.complex128]: ... np.ma.array([0, 1], dtype=dt).get_fill_value() ... 999999 999999 1e+20 (1e+20+0j) >>> x = np.ma.array([0, 1.], fill_value=-np.inf) >>> x.get_fill_value() -inf """ if self._fill_value is None: self._fill_value = _check_fill_value(None, self.dtype) return self._fill_value[()] def set_fill_value(self, value=None): """ Set the filling value of the masked array. Parameters ---------- value : scalar, optional The new filling value. Default is None, in which case a default based on the data type is used. See Also -------- ma.set_fill_value : Equivalent function. Examples -------- >>> x = np.ma.array([0, 1.], fill_value=-np.inf) >>> x.fill_value -inf >>> x.set_fill_value(np.pi) >>> x.fill_value 3.1415926535897931 Reset to default: >>> x.set_fill_value() >>> x.fill_value 1e+20 """ target = _check_fill_value(value, self.dtype) _fill_value = self._fill_value if _fill_value is None: # Create the attribute if it was undefined self._fill_value = target else: # Don't overwrite the attribute, just fill it (for propagation) _fill_value[()] = target fill_value = property(fget=get_fill_value, fset=set_fill_value, doc="Filling value.") def filled(self, fill_value=None): """ Return a copy of self, with masked values filled with a given value. Parameters ---------- fill_value : scalar, optional The value to use for invalid entries (None by default). If None, the `fill_value` attribute of the array is used instead. Returns ------- filled_array : ndarray A copy of ``self`` with invalid entries replaced by *fill_value* (be it the function argument or the attribute of ``self``. Notes ----- The result is **not** a MaskedArray! Examples -------- >>> x = np.ma.array([1,2,3,4,5], mask=[0,0,1,0,1], fill_value=-999) >>> x.filled() array([1, 2, -999, 4, -999]) >>> type(x.filled()) Subclassing is preserved. This means that if the data part of the masked array is a matrix, `filled` returns a matrix: >>> x = np.ma.array(np.matrix([[1, 2], [3, 4]]), mask=[[0, 1], [1, 0]]) >>> x.filled() matrix([[ 1, 999999], [999999, 4]]) """ m = self._mask if m is nomask: return self._data # if fill_value is None: fill_value = self.fill_value else: fill_value = _check_fill_value(fill_value, self.dtype) # if self is masked_singleton: return np.asanyarray(fill_value) # if m.dtype.names: result = self._data.copy('K') _recursive_filled(result, self._mask, fill_value) elif not m.any(): return self._data else: result = self._data.copy('K') try: np.copyto(result, fill_value, where=m) except (TypeError, AttributeError): fill_value = narray(fill_value, dtype=object) d = result.astype(object) result = np.choose(m, (d, fill_value)) except IndexError: #ok, if scalar if self._data.shape: raise elif m: result = np.array(fill_value, dtype=self.dtype) else: result = self._data return result def compressed(self): """ Return all the non-masked data as a 1-D array. Returns ------- data : ndarray A new `ndarray` holding the non-masked data is returned. Notes ----- The result is **not** a MaskedArray! Examples -------- >>> x = np.ma.array(np.arange(5), mask=[0]*2 + [1]*3) >>> x.compressed() array([0, 1]) >>> type(x.compressed()) """ data = ndarray.ravel(self._data) if self._mask is not nomask: data = data.compress(np.logical_not(ndarray.ravel(self._mask))) return data def compress(self, condition, axis=None, out=None): """ Return `a` where condition is ``True``. If condition is a `MaskedArray`, missing values are considered as ``False``. Parameters ---------- condition : var Boolean 1-d array selecting which entries to return. If len(condition) is less than the size of a along the axis, then output is truncated to length of condition array. axis : {None, int}, optional Axis along which the operation must be performed. out : {None, ndarray}, optional Alternative output array in which to place the result. It must have the same shape as the expected output but the type will be cast if necessary. Returns ------- result : MaskedArray A :class:`MaskedArray` object. Notes ----- Please note the difference with :meth:`compressed` ! The output of :meth:`compress` has a mask, the output of :meth:`compressed` does not. Examples -------- >>> x = np.ma.array([[1,2,3],[4,5,6],[7,8,9]], mask=[0] + [1,0]*4) >>> print x [[1 -- 3] [-- 5 --] [7 -- 9]] >>> x.compress([1, 0, 1]) masked_array(data = [1 3], mask = [False False], fill_value=999999) >>> x.compress([1, 0, 1], axis=1) masked_array(data = [[1 3] [-- --] [7 9]], mask = [[False False] [ True True] [False False]], fill_value=999999) """ # Get the basic components (_data, _mask) = (self._data, self._mask) # Force the condition to a regular ndarray (forget the missing values...) condition = np.array(condition, copy=False, subok=False) # _new = _data.compress(condition, axis=axis, out=out).view(type(self)) _new._update_from(self) if _mask is not nomask: _new._mask = _mask.compress(condition, axis=axis) return _new #............................................ def __str__(self): """String representation. """ if masked_print_option.enabled(): f = masked_print_option if self is masked: return str(f) m = self._mask if m is nomask: res = self._data else: if m.shape == (): 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)) else: return str(self._data) elif m: return str(f) else: return str(self._data) # convert to object array to make filled work names = self.dtype.names if names is None: res = self._data.astype("O") res[m] = f else: rdtype = _recursive_make_descr(self.dtype, "O") res = self._data.astype(rdtype) _recursive_printoption(res, m, f) else: res = self.filled(self.fill_value) return str(res) def __repr__(self): """Literal string representation. """ n = len(self.shape) name = repr(self._data).split('(')[0] parameters = dict(name=name, nlen=" " * len(name), 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 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: return masked omask = getattr(other, '_mask', nomask) if omask is nomask: check = ndarray.__eq__(self.filled(0), other) try: check = check.view(type(self)) check._mask = self._mask except AttributeError: # Dang, we have a bool instead of an array: return the bool return check else: odata = filled(other, 0) check = ndarray.__eq__(self.filled(0), odata).view(type(self)) if self._mask is nomask: check._mask = omask else: mask = mask_or(self._mask, omask) if mask.dtype.names: if mask.size > 1: axis = 1 else: axis = None try: mask = mask.view((bool_, len(self.dtype))).all(axis) except ValueError: mask = np.all([[f[n].all() for n in mask.dtype.names] for f in mask], axis=axis) check._mask = mask return check # def __ne__(self, other): "Check whether other doesn't equal self elementwise" if self is masked: return masked omask = getattr(other, '_mask', nomask) if omask is nomask: check = ndarray.__ne__(self.filled(0), other) try: check = check.view(type(self)) check._mask = self._mask except AttributeError: # In case check is a boolean (or a numpy.bool) return check else: odata = filled(other, 0) check = ndarray.__ne__(self.filled(0), odata).view(type(self)) if self._mask is nomask: check._mask = omask else: mask = mask_or(self._mask, omask) if mask.dtype.names: if mask.size > 1: axis = 1 else: axis = None try: mask = mask.view((bool_, len(self.dtype))).all(axis) except ValueError: mask = np.all([[f[n].all() for n in mask.dtype.names] for f in mask], axis=axis) check._mask = mask return check # def __add__(self, other): "Add other to self, and return a new masked array." return add(self, other) # def __radd__(self, other): "Add other to self, and return a new masked array." return add(self, other) # def __sub__(self, other): "Subtract other to self, and return a new masked array." return subtract(self, other) # def __rsub__(self, other): "Subtract other to self, and return a new masked array." return subtract(other, self) # def __mul__(self, other): "Multiply other by self, and return a new masked array." return multiply(self, other) # def __rmul__(self, other): "Multiply other by self, and return a new masked array." return multiply(self, other) # def __div__(self, other): "Divide other into self, and return a new masked array." return divide(self, other) # def __truediv__(self, other): "Divide other into self, and return a new masked array." return true_divide(self, other) # def __rtruediv__(self, other): "Divide other into self, and return a new masked array." return true_divide(other, self) # def __floordiv__(self, other): "Divide other into self, and return a new masked array." return floor_divide(self, other) # def __rfloordiv__(self, other): "Divide other into self, and return a new masked array." return floor_divide(other, self) # def __pow__(self, other): "Raise self to the power other, masking the potential NaNs/Infs" return power(self, other) # def __rpow__(self, other): "Raise self to the power other, masking the potential NaNs/Infs" return power(other, self) #............................................ def __iadd__(self, other): "Add other to self in-place." m = getmask(other) if self._mask is nomask: if m is not nomask and m.any(): self._mask = make_mask_none(self.shape, self.dtype) self._mask += m else: if m is not nomask: self._mask += m ndarray.__iadd__(self._data, np.where(self._mask, 0, getdata(other))) return self #.... def __isub__(self, other): "Subtract other from self in-place." m = getmask(other) if self._mask is nomask: if m is not nomask and m.any(): self._mask = make_mask_none(self.shape, self.dtype) self._mask += m elif m is not nomask: self._mask += m ndarray.__isub__(self._data, np.where(self._mask, 0, getdata(other))) return self #.... def __imul__(self, other): "Multiply self by other in-place." m = getmask(other) if self._mask is nomask: if m is not nomask and m.any(): self._mask = make_mask_none(self.shape, self.dtype) self._mask += m elif m is not nomask: self._mask += m ndarray.__imul__(self._data, np.where(self._mask, 1, getdata(other))) return self #.... def __idiv__(self, other): "Divide self by other in-place." other_data = getdata(other) dom_mask = _DomainSafeDivide().__call__(self._data, other_data) other_mask = getmask(other) new_mask = mask_or(other_mask, dom_mask) # The following 3 lines control the domain filling if dom_mask.any(): (_, fval) = ufunc_fills[np.divide] other_data = np.where(dom_mask, fval, other_data) # self._mask = mask_or(self._mask, new_mask) self._mask |= new_mask ndarray.__idiv__(self._data, np.where(self._mask, 1, other_data)) return self #.... def __ifloordiv__(self, other): "Floor divide self by other in-place." other_data = getdata(other) dom_mask = _DomainSafeDivide().__call__(self._data, other_data) other_mask = getmask(other) new_mask = mask_or(other_mask, dom_mask) # The following 3 lines control the domain filling if dom_mask.any(): (_, fval) = ufunc_fills[np.floor_divide] other_data = np.where(dom_mask, fval, other_data) # self._mask = mask_or(self._mask, new_mask) self._mask |= new_mask ndarray.__ifloordiv__(self._data, np.where(self._mask, 1, other_data)) return self #.... def __itruediv__(self, other): "True divide self by other in-place." other_data = getdata(other) dom_mask = _DomainSafeDivide().__call__(self._data, other_data) other_mask = getmask(other) new_mask = mask_or(other_mask, dom_mask) # The following 3 lines control the domain filling if dom_mask.any(): (_, fval) = ufunc_fills[np.true_divide] other_data = np.where(dom_mask, fval, other_data) # self._mask = mask_or(self._mask, new_mask) self._mask |= new_mask ndarray.__itruediv__(self._data, np.where(self._mask, 1, other_data)) return self #... def __ipow__(self, other): "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') ndarray.__ipow__(self._data, np.where(self._mask, 1, other_data)) invalid = np.logical_not(np.isfinite(self._data)) if invalid.any(): if self._mask is not nomask: self._mask |= invalid else: self._mask = invalid np.copyto(self._data, self.fill_value, where=invalid) new_mask = mask_or(other_mask, invalid) self._mask = mask_or(self._mask, new_mask) return self #............................................ def __float__(self): "Convert to float." if self.size > 1: raise TypeError("Only length-1 arrays can be converted " "to Python scalars") elif self._mask: warnings.warn("Warning: converting a masked element to nan.") return np.nan return float(self.item()) def __int__(self): "Convert to int." if self.size > 1: raise TypeError("Only length-1 arrays can be converted " "to Python scalars") elif self._mask: raise MaskError('Cannot convert masked element to a Python int.') return int(self.item()) def get_imag(self): """ Return the imaginary part of the masked array. The returned array is a view on the imaginary part of the `MaskedArray` whose `get_imag` method is called. Parameters ---------- None Returns ------- result : MaskedArray The imaginary part of the masked array. See Also -------- get_real, real, imag Examples -------- >>> x = np.ma.array([1+1.j, -2j, 3.45+1.6j], mask=[False, True, False]) >>> x.get_imag() masked_array(data = [1.0 -- 1.6], mask = [False True False], fill_value = 1e+20) """ result = self._data.imag.view(type(self)) result.__setmask__(self._mask) return result imag = property(fget=get_imag, doc="Imaginary part.") def get_real(self): """ Return the real part of the masked array. The returned array is a view on the real part of the `MaskedArray` whose `get_real` method is called. Parameters ---------- None Returns ------- result : MaskedArray The real part of the masked array. See Also -------- get_imag, real, imag Examples -------- >>> x = np.ma.array([1+1.j, -2j, 3.45+1.6j], mask=[False, True, False]) >>> x.get_real() masked_array(data = [1.0 -- 3.45], mask = [False True False], fill_value = 1e+20) """ result = self._data.real.view(type(self)) result.__setmask__(self._mask) return result real = property(fget=get_real, doc="Real part") #............................................ def count(self, axis=None): """ Count the non-masked elements of the array along the given axis. Parameters ---------- axis : int, optional Axis along which to count the non-masked elements. If `axis` is `None`, all non-masked elements are counted. Returns ------- result : int or ndarray If `axis` is `None`, an integer count is returned. When `axis` is not `None`, an array with shape determined by the lengths of the remaining axes, is returned. See Also -------- count_masked : Count masked elements in array or along a given axis. Examples -------- >>> import numpy.ma as ma >>> a = ma.arange(6).reshape((2, 3)) >>> a[1, :] = ma.masked >>> a masked_array(data = [[0 1 2] [-- -- --]], mask = [[False False False] [ True True True]], fill_value = 999999) >>> a.count() 3 When the `axis` keyword is specified an array of appropriate size is returned. >>> a.count(axis=0) array([1, 1, 1]) >>> a.count(axis=1) array([3, 0]) """ 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 n1 = np.size(m, axis) n2 = m.astype(int).sum(axis) if axis is None: return (n1 - n2) else: return narray(n1 - n2) #............................................ flatten = _arraymethod('flatten') # def ravel(self): """ Returns a 1D version of self, as a view. Returns ------- MaskedArray Output view is of shape ``(self.size,)`` (or ``(np.ma.product(self.shape),)``). Examples -------- >>> x = np.ma.array([[1,2,3],[4,5,6],[7,8,9]], mask=[0] + [1,0]*4) >>> print x [[1 -- 3] [-- 5 --] [7 -- 9]] >>> print x.ravel() [1 -- 3 -- 5 -- 7 -- 9] """ r = ndarray.ravel(self._data).view(type(self)) r._update_from(self) if self._mask is not nomask: r._mask = ndarray.ravel(self._mask).reshape(r.shape) else: r._mask = nomask return r # repeat = _arraymethod('repeat') # def reshape (self, *s, **kwargs): """ Give a new shape to the array without changing its data. Returns a masked array containing the same data, but with a new shape. The result is a view on the original array; if this is not possible, a ValueError is raised. Parameters ---------- shape : int or tuple of ints The new shape should be compatible with the original shape. If an integer is supplied, then the result will be a 1-D array of that length. order : {'C', 'F'}, optional Determines whether the array data should be viewed as in C (row-major) or FORTRAN (column-major) order. Returns ------- reshaped_array : array A new view on the array. See Also -------- reshape : Equivalent function in the masked array module. numpy.ndarray.reshape : Equivalent method on ndarray object. numpy.reshape : Equivalent function in the NumPy module. Notes ----- The reshaping operation cannot guarantee that a copy will not be made, to modify the shape in place, use ``a.shape = s`` Examples -------- >>> x = np.ma.array([[1,2],[3,4]], mask=[1,0,0,1]) >>> print x [[-- 2] [3 --]] >>> x = x.reshape((4,1)) >>> print x [[--] [2] [3] [--]] """ kwargs.update(order=kwargs.get('order', 'C')) result = self._data.reshape(*s, **kwargs).view(type(self)) result._update_from(self) mask = self._mask if mask is not nomask: result._mask = mask.reshape(*s, **kwargs) return result # def resize(self, newshape, refcheck=True, order=False): """ .. warning:: This method does nothing, except raise a ValueError exception. A masked array does not own its data and therefore cannot safely be resized in place. Use the `numpy.ma.resize` function instead. This method is difficult to implement safely and may be deprecated in future releases of NumPy. """ # Note : the 'order' keyword looks broken, let's just drop it # try: # ndarray.resize(self, newshape, refcheck=refcheck) # if self.mask is not nomask: # self._mask.resize(newshape, refcheck=refcheck) # except ValueError: # raise ValueError("Cannot resize an array that has been referenced " # "or is referencing another array in this way.\n" # "Use the numpy.ma.resize function.") # return None errmsg = "A masked array does not own its data "\ "and therefore cannot be resized.\n" \ "Use the numpy.ma.resize function instead." raise ValueError(errmsg) # def put(self, indices, values, mode='raise'): """ Set storage-indexed locations to corresponding values. Sets self._data.flat[n] = values[n] for each n in indices. If `values` is shorter than `indices` then it will repeat. If `values` has some masked values, the initial mask is updated in consequence, else the corresponding values are unmasked. Parameters ---------- indices : 1-D array_like Target indices, interpreted as integers. values : array_like Values to place in self._data copy at target indices. mode : {'raise', 'wrap', 'clip'}, optional Specifies how out-of-bounds indices will behave. 'raise' : raise an error. 'wrap' : wrap around. 'clip' : clip to the range. Notes ----- `values` can be a scalar or length 1 array. Examples -------- >>> x = np.ma.array([[1,2,3],[4,5,6],[7,8,9]], mask=[0] + [1,0]*4) >>> print x [[1 -- 3] [-- 5 --] [7 -- 9]] >>> x.put([0,4,8],[10,20,30]) >>> print x [[10 -- 3] [-- 20 --] [7 -- 30]] >>> x.put(4,999) >>> print x [[10 -- 3] [-- 999 --] [7 -- 30]] """ m = self._mask # Hard mask: Get rid of the values/indices that fall on masked data if self._hardmask and self._mask is not nomask: mask = self._mask[indices] indices = narray(indices, copy=False) values = narray(values, copy=False, subok=True) values.resize(indices.shape) indices = indices[~mask] values = values[~mask] #.... self._data.put(indices, values, mode=mode) #.... if m is nomask: m = getmask(values) else: m = m.copy() if getmask(values) is nomask: m.put(indices, False, mode=mode) else: m.put(indices, values._mask, mode=mode) m = make_mask(m, copy=False, shrink=True) self._mask = m #............................................ def ids (self): """ Return the addresses of the data and mask areas. Parameters ---------- None Examples -------- >>> x = np.ma.array([1, 2, 3], mask=[0, 1, 1]) >>> x.ids() (166670640, 166659832) If the array has no mask, the address of `nomask` is returned. This address is typically not close to the data in memory: >>> x = np.ma.array([1, 2, 3]) >>> x.ids() (166691080, 3083169284L) """ if self._mask is nomask: return (self.ctypes.data, id(nomask)) return (self.ctypes.data, self._mask.ctypes.data) def iscontiguous(self): """ Return a boolean indicating whether the data is contiguous. Parameters ---------- None Examples -------- >>> x = np.ma.array([1, 2, 3]) >>> x.iscontiguous() True `iscontiguous` returns one of the flags of the masked array: >>> x.flags C_CONTIGUOUS : True F_CONTIGUOUS : True OWNDATA : False WRITEABLE : True ALIGNED : True UPDATEIFCOPY : False """ return self.flags['CONTIGUOUS'] #............................................ def all(self, axis=None, out=None): """ Check if all of the elements of `a` are true. Performs a :func:`logical_and` over the given axis and returns the result. Masked values are considered as True during computation. For convenience, the output array is masked where ALL the values along the current axis are masked: if the output would have been a scalar and that all the values are masked, then the output is `masked`. Parameters ---------- axis : {None, integer} Axis to perform the operation over. If None, perform over flattened array. out : {None, array}, optional Array into which the result can be placed. Its type is preserved and it must be of the right shape to hold the output. See Also -------- all : equivalent function Examples -------- >>> np.ma.array([1,2,3]).all() True >>> a = np.ma.array([1,2,3], mask=True) >>> (a.all() is np.ma.masked) True """ mask = _check_mask_axis(self._mask, axis) if out is None: d = self.filled(True).all(axis=axis).view(type(self)) if d.ndim: d.__setmask__(mask) elif mask: return masked return d self.filled(True).all(axis=axis, out=out) if isinstance(out, MaskedArray): if out.ndim or mask: out.__setmask__(mask) return out def any(self, axis=None, out=None): """ Check if any of the elements of `a` are true. Performs a logical_or over the given axis and returns the result. Masked values are considered as False during computation. Parameters ---------- axis : {None, integer} Axis to perform the operation over. If None, perform over flattened array and return a scalar. out : {None, array}, optional Array into which the result can be placed. Its type is preserved and it must be of the right shape to hold the output. See Also -------- any : equivalent function """ mask = _check_mask_axis(self._mask, axis) if out is None: d = self.filled(False).any(axis=axis).view(type(self)) if d.ndim: d.__setmask__(mask) elif mask: d = masked return d self.filled(False).any(axis=axis, out=out) if isinstance(out, MaskedArray): if out.ndim or mask: out.__setmask__(mask) return out def nonzero(self): """ Return the indices of unmasked elements that are not zero. Returns a tuple of arrays, one for each dimension, containing the indices of the non-zero elements in that dimension. The corresponding non-zero values can be obtained with:: a[a.nonzero()] To group the indices by element, rather than dimension, use instead:: np.transpose(a.nonzero()) The result of this is always a 2d array, with a row for each non-zero element. Parameters ---------- None Returns ------- tuple_of_arrays : tuple Indices of elements that are non-zero. See Also -------- numpy.nonzero : Function operating on ndarrays. flatnonzero : Return indices that are non-zero in the flattened version of the input array. ndarray.nonzero : Equivalent ndarray method. count_nonzero : Counts the number of non-zero elements in the input array. Examples -------- >>> import numpy.ma as ma >>> x = ma.array(np.eye(3)) >>> x masked_array(data = [[ 1. 0. 0.] [ 0. 1. 0.] [ 0. 0. 1.]], mask = False, fill_value=1e+20) >>> x.nonzero() (array([0, 1, 2]), array([0, 1, 2])) Masked elements are ignored. >>> x[1, 1] = ma.masked >>> x masked_array(data = [[1.0 0.0 0.0] [0.0 -- 0.0] [0.0 0.0 1.0]], mask = [[False False False] [False True False] [False False False]], fill_value=1e+20) >>> x.nonzero() (array([0, 2]), array([0, 2])) Indices can also be grouped by element. >>> np.transpose(x.nonzero()) array([[0, 0], [2, 2]]) A common use for ``nonzero`` is to find the indices of an array, where a condition is True. Given an array `a`, the condition `a` > 3 is a boolean array and since False is interpreted as 0, ma.nonzero(a > 3) yields the indices of the `a` where the condition is true. >>> a = ma.array([[1,2,3],[4,5,6],[7,8,9]]) >>> a > 3 masked_array(data = [[False False False] [ True True True] [ True True True]], mask = False, fill_value=999999) >>> ma.nonzero(a > 3) (array([1, 1, 1, 2, 2, 2]), array([0, 1, 2, 0, 1, 2])) The ``nonzero`` method of the condition array can also be called. >>> (a > 3).nonzero() (array([1, 1, 1, 2, 2, 2]), array([0, 1, 2, 0, 1, 2])) """ return narray(self.filled(0), copy=False).nonzero() def trace(self, offset=0, axis1=0, axis2=1, dtype=None, out=None): """ (this docstring should be overwritten) """ #!!!: implement out + test! m = self._mask if m is nomask: result = super(MaskedArray, self).trace(offset=offset, axis1=axis1, axis2=axis2, out=out) return result.astype(dtype) else: D = self.diagonal(offset=offset, axis1=axis1, axis2=axis2) return D.astype(dtype).filled(0).sum(axis=None, out=out) trace.__doc__ = ndarray.trace.__doc__ def sum(self, axis=None, dtype=None, out=None): """ Return the sum of the array elements over the given axis. Masked elements are set to 0 internally. Parameters ---------- axis : {None, -1, int}, optional Axis along which the sum is computed. The default (`axis` = None) is to compute over the flattened array. dtype : {None, dtype}, optional Determines the type of the returned array and of the accumulator where the elements are summed. If dtype has the value None and the type of a is an integer type of precision less than the default platform integer, then the default platform integer precision is used. Otherwise, the dtype is the same as that of a. out : {None, 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 will be cast if necessary. Returns ------- sum_along_axis : MaskedArray or scalar An array with the same shape as self, with the specified axis removed. If self is a 0-d array, or if `axis` is None, a scalar is returned. If an output array is specified, a reference to `out` is returned. Examples -------- >>> x = np.ma.array([[1,2,3],[4,5,6],[7,8,9]], mask=[0] + [1,0]*4) >>> print x [[1 -- 3] [-- 5 --] [7 -- 9]] >>> print x.sum() 25 >>> print x.sum(axis=1) [4 5 16] >>> print x.sum(axis=0) [8 5 12] >>> print type(x.sum(axis=0, dtype=np.int64)[0]) """ _mask = ndarray.__getattribute__(self, '_mask') newmask = _check_mask_axis(_mask, axis) # No explicit output if out is None: result = self.filled(0).sum(axis, dtype=dtype) rndim = getattr(result, 'ndim', 0) if rndim: result = result.view(type(self)) result.__setmask__(newmask) elif newmask: result = masked return result # Explicit output result = self.filled(0).sum(axis, dtype=dtype, out=out) if isinstance(out, MaskedArray): outmask = getattr(out, '_mask', nomask) if (outmask is nomask): outmask = out._mask = make_mask_none(out.shape) outmask.flat = newmask return out def cumsum(self, axis=None, dtype=None, out=None): """ Return the cumulative sum of the elements along the given axis. The cumulative sum is calculated over the flattened array by default, otherwise over the specified axis. Masked values are set to 0 internally during the computation. However, their position is saved, and the result will be masked at the same locations. Parameters ---------- axis : {None, -1, int}, optional Axis along which the sum is computed. The default (`axis` = None) is to compute over the flattened array. `axis` may be negative, in which case it counts from the last to the first axis. dtype : {None, dtype}, optional Type of the returned array and of the accumulator in which the elements are summed. If `dtype` is not specified, it defaults to the dtype of `a`, unless `a` has an integer dtype with a precision less than that of the default platform integer. In that case, the default platform integer is used. 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 will be cast if necessary. Returns ------- cumsum : ndarray. A new array holding the result is returned unless ``out`` is specified, in which case a reference to ``out`` is returned. Notes ----- The mask is lost if `out` is not a valid :class:`MaskedArray` ! Arithmetic is modular when using integer types, and no error is raised on overflow. Examples -------- >>> marr = np.ma.array(np.arange(10), mask=[0,0,0,1,1,1,0,0,0,0]) >>> print marr.cumsum() [0 1 3 -- -- -- 9 16 24 33] """ result = self.filled(0).cumsum(axis=axis, dtype=dtype, out=out) if out is not None: if isinstance(out, MaskedArray): out.__setmask__(self.mask) return out result = result.view(type(self)) result.__setmask__(self._mask) return result def prod(self, axis=None, dtype=None, out=None): """ Return the product of the array elements over the given axis. Masked elements are set to 1 internally for computation. Parameters ---------- axis : {None, int}, optional Axis over which the product is taken. If None is used, then the product is over all the array elements. dtype : {None, dtype}, optional Determines the type of the returned array and of the accumulator where the elements are multiplied. If ``dtype`` has the value ``None`` and the type of a is an integer type of precision less than the default platform integer, then the default platform integer precision is used. Otherwise, the dtype is the same as that of a. out : {None, array}, optional Alternative output array in which to place the result. It must have the same shape as the expected output but the type will be cast if necessary. Returns ------- product_along_axis : {array, scalar}, see dtype parameter above. Returns an array whose shape is the same as a with the specified axis removed. Returns a 0d array when a is 1d or axis=None. Returns a reference to the specified output array if specified. See Also -------- prod : equivalent function Notes ----- Arithmetic is modular when using integer types, and no error is raised on overflow. Examples -------- >>> np.prod([1.,2.]) 2.0 >>> np.prod([1.,2.], dtype=np.int32) 2 >>> np.prod([[1.,2.],[3.,4.]]) 24.0 >>> np.prod([[1.,2.],[3.,4.]], axis=1) array([ 2., 12.]) """ _mask = ndarray.__getattribute__(self, '_mask') newmask = _check_mask_axis(_mask, axis) # No explicit output if out is None: result = self.filled(1).prod(axis, dtype=dtype) rndim = getattr(result, 'ndim', 0) if rndim: result = result.view(type(self)) result.__setmask__(newmask) elif newmask: result = masked return result # Explicit output result = self.filled(1).prod(axis, dtype=dtype, out=out) if isinstance(out, MaskedArray): outmask = getattr(out, '_mask', nomask) if (outmask is nomask): outmask = out._mask = make_mask_none(out.shape) outmask.flat = newmask return out product = prod def cumprod(self, axis=None, dtype=None, out=None): """ Return the cumulative product of the elements along the given axis. The cumulative product is taken over the flattened array by default, otherwise over the specified axis. Masked values are set to 1 internally during the computation. However, their position is saved, and the result will be masked at the same locations. Parameters ---------- axis : {None, -1, int}, optional Axis along which the product is computed. The default (`axis` = None) is to compute over the flattened array. dtype : {None, dtype}, optional Determines the type of the returned array and of the accumulator where the elements are multiplied. If ``dtype`` has the value ``None`` and the type of ``a`` is an integer type of precision less than the default platform integer, then the default platform integer precision is used. Otherwise, the dtype is the same as that of ``a``. 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 will be cast if necessary. Returns ------- cumprod : ndarray A new array holding the result is returned unless out is specified, in which case a reference to out is returned. Notes ----- The mask is lost if `out` is not a valid MaskedArray ! Arithmetic is modular when using integer types, and no error is raised on overflow. """ result = self.filled(1).cumprod(axis=axis, dtype=dtype, out=out) if out is not None: if isinstance(out, MaskedArray): out.__setmask__(self._mask) return out result = result.view(type(self)) result.__setmask__(self._mask) return result def mean(self, axis=None, dtype=None, out=None): """ Returns the average of the array elements. Masked entries are ignored. The average is taken over the flattened array by default, otherwise over the specified axis. Refer to `numpy.mean` for the full documentation. Parameters ---------- a : array_like Array containing numbers whose mean is desired. If `a` is not an array, a conversion is attempted. axis : int, optional Axis along which the means are computed. The default is to compute the mean of the flattened array. dtype : dtype, optional Type to use in computing the mean. For integer inputs, the default is float64; for floating point, inputs it is the same as the input dtype. out : ndarray, optional Alternative output array in which to place the result. It must have the same shape as the expected output but the type will be cast if necessary. Returns ------- mean : ndarray, see dtype parameter above If `out=None`, returns a new array containing the mean values, otherwise a reference to the output array is returned. See Also -------- numpy.ma.mean : Equivalent function. numpy.mean : Equivalent function on non-masked arrays. numpy.ma.average: Weighted average. Examples -------- >>> a = np.ma.array([1,2,3], mask=[False, False, True]) >>> a masked_array(data = [1 2 --], mask = [False False True], fill_value = 999999) >>> a.mean() 1.5 """ if self._mask is nomask: result = super(MaskedArray, self).mean(axis=axis, dtype=dtype) else: dsum = self.sum(axis=axis, dtype=dtype) cnt = self.count(axis=axis) if cnt.shape == () and (cnt == 0): result = masked else: result = dsum * 1. / cnt if out is not None: out.flat = result if isinstance(out, MaskedArray): outmask = getattr(out, '_mask', nomask) if (outmask is nomask): outmask = out._mask = make_mask_none(out.shape) outmask.flat = getattr(result, '_mask', nomask) return out return result def anom(self, axis=None, dtype=None): """ Compute the anomalies (deviations from the arithmetic mean) along the given axis. Returns an array of anomalies, with the same shape as the input and where the arithmetic mean is computed along the given axis. Parameters ---------- axis : int, optional Axis over which the anomalies are taken. The default is to use the mean of the flattened array as reference. dtype : dtype, optional Type to use in computing the variance. For arrays of integer type the default is float32; for arrays of float types it is the same as the array type. See Also -------- mean : Compute the mean of the array. Examples -------- >>> a = np.ma.array([1,2,3]) >>> a.anom() masked_array(data = [-1. 0. 1.], mask = False, fill_value = 1e+20) """ m = self.mean(axis, dtype) if not axis: return (self - m) else: return (self - expand_dims(m, axis)) def var(self, axis=None, dtype=None, out=None, ddof=0): "" # Easy case: nomask, business as usual if self._mask is nomask: return self._data.var(axis=axis, dtype=dtype, out=out, ddof=ddof) # Some data are masked, yay! cnt = self.count(axis=axis) - ddof danom = self.anom(axis=axis, dtype=dtype) if iscomplexobj(self): danom = umath.absolute(danom) ** 2 else: danom *= danom dvar = divide(danom.sum(axis), cnt).view(type(self)) # Apply the mask if it's not a scalar if dvar.ndim: dvar._mask = mask_or(self._mask.all(axis), (cnt <= 0)) dvar._update_from(self) elif getattr(dvar, '_mask', False): # Make sure that masked is returned when the scalar is masked. dvar = masked if out is not None: if isinstance(out, MaskedArray): out.flat = 0 out.__setmask__(True) elif out.dtype.kind in 'biu': errmsg = "Masked data information would be lost in one or "\ "more location." raise MaskError(errmsg) else: out.flat = np.nan return out # In case with have an explicit output if out is not None: # Set the data out.flat = dvar # Set the mask if needed if isinstance(out, MaskedArray): out.__setmask__(dvar.mask) return out return dvar var.__doc__ = np.var.__doc__ def std(self, axis=None, dtype=None, out=None, ddof=0): "" dvar = self.var(axis=axis, dtype=dtype, out=out, ddof=ddof) if dvar is not masked: if out is not None: np.power(out, 0.5, out=out, casting='unsafe') return out dvar = sqrt(dvar) return dvar std.__doc__ = np.std.__doc__ #............................................ def round(self, decimals=0, out=None): """ Return an array rounded a to the given number of decimals. Refer to `numpy.around` for full documentation. See Also -------- numpy.around : equivalent function """ result = self._data.round(decimals=decimals, out=out).view(type(self)) result._mask = self._mask result._update_from(self) # No explicit output: we're done if out is None: return result if isinstance(out, MaskedArray): out.__setmask__(self._mask) return out round.__doc__ = ndarray.round.__doc__ #............................................ def argsort(self, axis=None, kind='quicksort', order=None, fill_value=None): """ Return an ndarray of indices that sort the array along the specified axis. Masked values are filled beforehand to `fill_value`. Parameters ---------- axis : int, optional Axis along which to sort. The default is -1 (last axis). If None, the flattened array is used. fill_value : var, optional Value used to fill the array before sorting. The default is the `fill_value` attribute of the input array. kind : {'quicksort', 'mergesort', 'heapsort'}, optional Sorting algorithm. order : list, optional When `a` is an array with fields defined, this argument specifies which fields to compare first, second, etc. Not all fields need be specified. Returns ------- index_array : ndarray, int Array of indices that sort `a` along the specified axis. In other words, ``a[index_array]`` yields a sorted `a`. See Also -------- sort : Describes sorting algorithms used. lexsort : Indirect stable sort with multiple keys. ndarray.sort : Inplace sort. Notes ----- See `sort` for notes on the different sorting algorithms. Examples -------- >>> a = np.ma.array([3,2,1], mask=[False, False, True]) >>> a masked_array(data = [3 2 --], mask = [False False True], fill_value = 999999) >>> a.argsort() array([1, 0, 2]) """ if fill_value is None: fill_value = default_fill_value(self) d = self.filled(fill_value).view(ndarray) return d.argsort(axis=axis, kind=kind, order=order) def argmin(self, axis=None, fill_value=None, out=None): """ Return array of indices to the minimum values along the given axis. Parameters ---------- axis : {None, integer} If None, the index is into the flattened array, otherwise along the specified axis fill_value : {var}, optional Value used to fill in the masked values. If None, the output of minimum_fill_value(self._data) is used instead. out : {None, array}, optional Array into which the result can be placed. Its type is preserved and it must be of the right shape to hold the output. Returns ------- {ndarray, scalar} If multi-dimension input, returns a new ndarray of indices to the minimum values along the given axis. Otherwise, returns a scalar of index to the minimum values along the given axis. Examples -------- >>> x = np.ma.array(arange(4), mask=[1,1,0,0]) >>> x.shape = (2,2) >>> print x [[-- --] [2 3]] >>> print x.argmin(axis=0, fill_value=-1) [0 0] >>> print x.argmin(axis=0, fill_value=9) [1 1] """ if fill_value is None: fill_value = minimum_fill_value(self) d = self.filled(fill_value).view(ndarray) return d.argmin(axis, out=out) def argmax(self, axis=None, fill_value=None, out=None): """ Returns array of indices of the maximum values along the given axis. Masked values are treated as if they had the value fill_value. Parameters ---------- axis : {None, integer} If None, the index is into the flattened array, otherwise along the specified axis fill_value : {var}, optional Value used to fill in the masked values. If None, the output of maximum_fill_value(self._data) is used instead. out : {None, array}, optional Array into which the result can be placed. Its type is preserved and it must be of the right shape to hold the output. Returns ------- index_array : {integer_array} Examples -------- >>> a = np.arange(6).reshape(2,3) >>> a.argmax() 5 >>> a.argmax(0) array([1, 1, 1]) >>> a.argmax(1) array([2, 2]) """ if fill_value is None: fill_value = maximum_fill_value(self._data) d = self.filled(fill_value).view(ndarray) return d.argmax(axis, out=out) def sort(self, axis= -1, kind='quicksort', order=None, endwith=True, fill_value=None): """ Sort the array, in-place Parameters ---------- a : array_like Array to be sorted. axis : int, optional Axis along which to sort. If None, the array is flattened before sorting. The default is -1, which sorts along the last axis. kind : {'quicksort', 'mergesort', 'heapsort'}, optional Sorting algorithm. Default is 'quicksort'. order : list, optional When `a` is a structured array, this argument specifies which fields to compare first, second, and so on. This list does not need to include all of the fields. endwith : {True, False}, optional Whether missing values (if any) should be forced in the upper indices (at the end of the array) (True) or lower indices (at the beginning). fill_value : {var}, optional Value used internally for the masked values. If ``fill_value`` is not None, it supersedes ``endwith``. Returns ------- sorted_array : ndarray Array of the same type and shape as `a`. See Also -------- ndarray.sort : Method to sort an array in-place. argsort : Indirect sort. lexsort : Indirect stable sort on multiple keys. searchsorted : Find elements in a sorted array. Notes ----- See ``sort`` for notes on the different sorting algorithms. Examples -------- >>> a = ma.array([1, 2, 5, 4, 3],mask=[0, 1, 0, 1, 0]) >>> # Default >>> a.sort() >>> print a [1 3 5 -- --] >>> a = ma.array([1, 2, 5, 4, 3],mask=[0, 1, 0, 1, 0]) >>> # Put missing values in the front >>> a.sort(endwith=False) >>> print a [-- -- 1 3 5] >>> a = ma.array([1, 2, 5, 4, 3],mask=[0, 1, 0, 1, 0]) >>> # fill_value takes over endwith >>> a.sort(endwith=False, fill_value=3) >>> print a [1 -- -- 3 5] """ if self._mask is nomask: ndarray.sort(self, axis=axis, kind=kind, order=order) else: if self is masked: return self if fill_value is None: if endwith: filler = minimum_fill_value(self) else: filler = maximum_fill_value(self) else: filler = fill_value idx = np.indices(self.shape) 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 self._data.flat = tmp_data self._mask.flat = tmp_mask return #............................................ def min(self, axis=None, out=None, fill_value=None): """ Return the minimum along a given axis. Parameters ---------- axis : {None, int}, optional Axis along which to operate. By default, ``axis`` is None and the flattened input is used. out : array_like, optional Alternative output array in which to place the result. Must be of the same shape and buffer length as the expected output. fill_value : {var}, optional Value used to fill in the masked values. If None, use the output of `minimum_fill_value`. Returns ------- amin : array_like New array holding the result. If ``out`` was specified, ``out`` is returned. See Also -------- minimum_fill_value Returns the minimum filling value for a given datatype. """ _mask = ndarray.__getattribute__(self, '_mask') newmask = _check_mask_axis(_mask, axis) if fill_value is None: fill_value = minimum_fill_value(self) # No explicit output if out is None: result = self.filled(fill_value).min(axis=axis, out=out).view(type(self)) if result.ndim: # Set the mask result.__setmask__(newmask) # Get rid of Infs if newmask.ndim: np.copyto(result, result.fill_value, where=newmask) elif newmask: result = masked return result # Explicit output result = self.filled(fill_value).min(axis=axis, out=out) if isinstance(out, MaskedArray): outmask = getattr(out, '_mask', nomask) if (outmask is nomask): outmask = out._mask = make_mask_none(out.shape) outmask.flat = newmask else: if out.dtype.kind in 'biu': errmsg = "Masked data information would be lost in one or more"\ " location." raise MaskError(errmsg) np.copyto(out, np.nan, where=newmask) return out def mini(self, axis=None): """ Return the array minimum along the specified axis. Parameters ---------- axis : int, optional The axis along which to find the minima. Default is None, in which case the minimum value in the whole array is returned. Returns ------- min : scalar or MaskedArray If `axis` is None, the result is a scalar. Otherwise, if `axis` is given and the array is at least 2-D, the result is a masked array with dimension one smaller than the array on which `mini` is called. Examples -------- >>> x = np.ma.array(np.arange(6), mask=[0 ,1, 0, 0, 0 ,1]).reshape(3, 2) >>> print x [[0 --] [2 3] [4 --]] >>> x.mini() 0 >>> x.mini(axis=0) masked_array(data = [0 3], mask = [False False], fill_value = 999999) >>> print x.mini(axis=1) [0 2 4] """ if axis is None: return minimum(self) else: return minimum.reduce(self, axis) #........................ def max(self, axis=None, out=None, fill_value=None): """ Return the maximum along a given axis. Parameters ---------- axis : {None, int}, optional Axis along which to operate. By default, ``axis`` is None and the flattened input is used. out : array_like, optional Alternative output array in which to place the result. Must be of the same shape and buffer length as the expected output. fill_value : {var}, optional Value used to fill in the masked values. If None, use the output of maximum_fill_value(). Returns ------- amax : array_like New array holding the result. If ``out`` was specified, ``out`` is returned. See Also -------- maximum_fill_value Returns the maximum filling value for a given datatype. """ _mask = ndarray.__getattribute__(self, '_mask') newmask = _check_mask_axis(_mask, axis) if fill_value is None: fill_value = maximum_fill_value(self) # No explicit output if out is None: result = self.filled(fill_value).max(axis=axis, out=out).view(type(self)) if result.ndim: # Set the mask result.__setmask__(newmask) # Get rid of Infs if newmask.ndim: np.copyto(result, result.fill_value, where=newmask) elif newmask: result = masked return result # Explicit output result = self.filled(fill_value).max(axis=axis, out=out) if isinstance(out, MaskedArray): outmask = getattr(out, '_mask', nomask) if (outmask is nomask): outmask = out._mask = make_mask_none(out.shape) outmask.flat = newmask else: if out.dtype.kind in 'biu': errmsg = "Masked data information would be lost in one or more"\ " location." raise MaskError(errmsg) np.copyto(out, np.nan, where=newmask) return out def ptp(self, axis=None, out=None, fill_value=None): """ Return (maximum - minimum) along the the given dimension (i.e. peak-to-peak value). Parameters ---------- axis : {None, int}, optional Axis along which to find the peaks. If None (default) the flattened array is used. out : {None, array_like}, 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 will be cast if necessary. fill_value : {var}, optional Value used to fill in the masked values. Returns ------- ptp : ndarray. A new array holding the result, unless ``out`` was specified, in which case a reference to ``out`` is returned. """ if out is None: result = self.max(axis=axis, fill_value=fill_value) result -= self.min(axis=axis, fill_value=fill_value) return result out.flat = self.max(axis=axis, out=out, fill_value=fill_value) min_value = self.min(axis=axis, fill_value=fill_value) np.subtract(out, min_value, out=out, casting='unsafe') return out def take(self, indices, axis=None, out=None, mode='raise'): """ """ (_data, _mask) = (self._data, self._mask) cls = type(self) # Make sure the indices are not masked maskindices = getattr(indices, '_mask', nomask) if maskindices is not nomask: indices = indices.filled(0) # Get the data if out is None: out = _data.take(indices, axis=axis, mode=mode).view(cls) else: np.take(_data, indices, axis=axis, mode=mode, out=out) # Get the mask if isinstance(out, MaskedArray): if _mask is nomask: outmask = maskindices else: outmask = _mask.take(indices, axis=axis, mode=mode) outmask |= maskindices out.__setmask__(outmask) return out # Array methods --------------------------------------- copy = _arraymethod('copy') diagonal = _arraymethod('diagonal') transpose = _arraymethod('transpose') T = property(fget=lambda self:self.transpose()) swapaxes = _arraymethod('swapaxes') clip = _arraymethod('clip', onmask=False) copy = _arraymethod('copy') squeeze = _arraymethod('squeeze') #-------------------------------------------- def tolist(self, fill_value=None): """ Return the data portion of the masked array as a hierarchical Python list. Data items are converted to the nearest compatible Python type. Masked values are converted to `fill_value`. If `fill_value` is None, the corresponding entries in the output list will be ``None``. Parameters ---------- fill_value : scalar, optional The value to use for invalid entries. Default is None. Returns ------- result : list The Python list representation of the masked array. Examples -------- >>> x = np.ma.array([[1,2,3], [4,5,6], [7,8,9]], mask=[0] + [1,0]*4) >>> x.tolist() [[1, None, 3], [None, 5, None], [7, None, 9]] >>> x.tolist(-999) [[1, -999, 3], [-999, 5, -999], [7, -999, 9]] """ _mask = self._mask # No mask ? Just return .data.tolist ? if _mask is nomask: return self._data.tolist() # Explicit fill_value: fill the array and get the list if fill_value is not None: return self.filled(fill_value).tolist() # Structured array ............. names = self.dtype.names if names: result = self._data.astype([(_, object) for _ in names]) for n in names: result[n][_mask[n]] = None return result.tolist() # Standard arrays ............... if _mask is nomask: return [None] # Set temps to save time when dealing w/ marrays... inishape = self.shape result = np.array(self._data.ravel(), dtype=object) result[_mask.ravel()] = None result.shape = inishape return result.tolist() # if fill_value is not None: # return self.filled(fill_value).tolist() # result = self.filled().tolist() # # Set temps to save time when dealing w/ mrecarrays... # _mask = self._mask # if _mask is nomask: # return result # nbdims = self.ndim # dtypesize = len(self.dtype) # if nbdims == 0: # return tuple([None] * dtypesize) # elif nbdims == 1: # maskedidx = _mask.nonzero()[0].tolist() # if dtypesize: # nodata = tuple([None] * dtypesize) # else: # nodata = None # [operator.setitem(result, i, nodata) for i in maskedidx] # else: # for idx in zip(*[i.tolist() for i in _mask.nonzero()]): # tmp = result # for i in idx[:-1]: # tmp = tmp[i] # tmp[idx[-1]] = None # return result #........................ def tostring(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. Parameters ---------- fill_value : scalar, optional Value used to fill in the masked values. Deafult is None, in which case `MaskedArray.fill_value` is used. order : {'C','F','A'}, optional Order of the data item in the copy. Default is 'C'. - 'C' -- C order (row major). - 'F' -- Fortran order (column major). - 'A' -- Any, current order of array. - None -- Same as 'A'. See Also -------- ndarray.tostring tolist, tofile Notes ----- As for `ndarray.tostring`, 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() '\\x01\\x00\\x00\\x00?B\\x0f\\x00?B\\x0f\\x00\\x04\\x00\\x00\\x00' """ return self.filled(fill_value).tostring(order=order) #........................ def tofile(self, fid, sep="", format="%s"): """ Save a masked array to a file in binary format. .. warning:: This function is not implemented yet. Raises ------ NotImplementedError When `tofile` is called. """ raise NotImplementedError("Not implemented yet, sorry...") def toflex(self): """ Transforms a masked array into a flexible-type array. The flexible type array that is returned will have two fields: * the ``_data`` field stores the ``_data`` part of the array. * the ``_mask`` field stores the ``_mask`` part of the array. Parameters ---------- None Returns ------- record : ndarray A new flexible-type `ndarray` with two fields: the first element containing a value, the second element containing the corresponding mask boolean. The returned record shape matches self.shape. Notes ----- A side-effect of transforming a masked array into a flexible `ndarray` is that meta information (``fill_value``, ...) will be lost. Examples -------- >>> x = np.ma.array([[1,2,3],[4,5,6],[7,8,9]], mask=[0] + [1,0]*4) >>> print x [[1 -- 3] [-- 5 --] [7 -- 9]] >>> print x.toflex() [[(1, False) (2, True) (3, False)] [(4, True) (5, False) (6, True)] [(7, False) (8, True) (9, False)]] """ # Get the basic dtype .... ddtype = self.dtype # Make sure we have a mask _mask = self._mask if _mask is None: _mask = make_mask_none(self.shape, ddtype) # And get its dtype mdtype = self._mask.dtype # record = np.ndarray(shape=self.shape, dtype=[('_data', ddtype), ('_mask', mdtype)]) record['_data'] = self._data record['_mask'] = self._mask return record torecords = toflex #-------------------------------------------- # Pickling def __getstate__(self): """Return the internal state of the masked array, for pickling purposes. """ cf = 'CF'[self.flags.fnc] state = (1, self.shape, self.dtype, self.flags.fnc, self._data.tostring(cf), #self._data.tolist(), getmaskarray(self).tostring(cf), #getmaskarray(self).tolist(), self._fill_value, ) return state # def __setstate__(self, state): """Restore the internal state of the masked array, for pickling purposes. ``state`` is typically the output of the ``__getstate__`` output, and is a 5-tuple: - class name - a tuple giving the shape of the data - a typecode for the data - a binary string for the data - a binary string for the mask. """ (_, shp, typ, isf, raw, msk, flv) = state ndarray.__setstate__(self, (shp, typ, isf, raw)) self._mask.__setstate__((shp, make_mask_descr(typ), isf, msk)) self.fill_value = flv # def __reduce__(self): """Return a 3-tuple for pickling a MaskedArray. """ return (_mareconstruct, (self.__class__, self._baseclass, (0,), 'b',), self.__getstate__()) # def __deepcopy__(self, memo=None): from copy import deepcopy copied = MaskedArray.__new__(type(self), self, copy=True) if memo is None: memo = {} memo[id(self)] = copied for (k, v) in self.__dict__.items(): copied.__dict__[k] = deepcopy(v, memo) return copied def _mareconstruct(subtype, baseclass, baseshape, basetype,): """Internal function that builds a new MaskedArray from the information stored in a pickle. """ _data = ndarray.__new__(baseclass, baseshape, basetype) _mask = ndarray.__new__(ndarray, baseshape, make_mask_descr(basetype)) return subtype.__new__(subtype, _data, mask=_mask, dtype=basetype,) class mvoid(MaskedArray): """ Fake a 'void' object to use for masked array with structured dtypes. """ # def __new__(self, data, mask=nomask, dtype=None, fill_value=None, hardmask=False): dtype = dtype or data.dtype _data = np.array(data, dtype=dtype) _data = _data.view(self) _data._hardmask = hardmask if mask is not nomask: if isinstance(mask, np.void): _data._mask = mask else: try: # Mask is already a 0D array _data._mask = np.void(mask) except TypeError: # Transform the mask to a void mdtype = make_mask_descr(dtype) _data._mask = np.array(mask, dtype=mdtype)[()] if fill_value is not None: _data.fill_value = fill_value return _data def _get_data(self): # Make sure that the _data part is a np.void return self.view(ndarray)[()] _data = property(fget=_get_data) def __getitem__(self, indx): "Get the index..." m = self._mask if m is not nomask and m[indx]: return masked return self._data[indx] def __setitem__(self, indx, value): self._data[indx] = value if self._hardmask: self._mask[indx] |= getattr(value, "_mask", False) else: self._mask[indx] = getattr(value, "_mask", False) def __str__(self): m = self._mask if (m is nomask): return self._data.__str__() m = tuple(m) if (not any(m)): return self._data.__str__() r = self._data.tolist() p = masked_print_option if not p.enabled(): p = 'N/A' else: p = str(p) r = [(str(_), p)[int(_m)] for (_, _m) in zip(r, m)] return "(%s)" % ", ".join(r) def __repr__(self): m = self._mask if (m is nomask): return self._data.__repr__() m = tuple(m) if not any(m): return self._data.__repr__() p = masked_print_option if not p.enabled(): return self.filled(self.fill_value).__repr__() p = str(p) r = [(str(_), p)[int(_m)] for (_, _m) in zip(self._data.tolist(), m)] return "(%s)" % ", ".join(r) def __iter__(self): "Defines an iterator for mvoid" (_data, _mask) = (self._data, self._mask) if _mask is nomask: for d in _data: yield d else: for (d, m) in zip(_data, _mask): if m: yield masked else: yield d def __len__(self): return self._data.__len__() def filled(self, fill_value=None): """ Return a copy with masked fields filled with a given value. Parameters ---------- fill_value : scalar, optional The value to use for invalid entries (None by default). If None, the `fill_value` attribute is used instead. Returns ------- filled_void A `np.void` object See Also -------- MaskedArray.filled """ return asarray(self).filled(fill_value)[()] def tolist(self): """ Transforms the mvoid object into a tuple. Masked fields are replaced by None. Returns ------- returned_tuple Tuple of fields """ _mask = self._mask if _mask is nomask: return self._data.tolist() result = [] for (d, m) in zip(self._data, self._mask): if m: result.append(None) else: # .item() makes sure we return a standard Python object result.append(d.item()) return tuple(result) #####-------------------------------------------------------------------------- #---- --- Shortcuts --- #####--------------------------------------------------------------------------- def isMaskedArray(x): """ Test whether input is an instance of MaskedArray. This function returns True if `x` is an instance of MaskedArray and returns False otherwise. Any object is accepted as input. Parameters ---------- x : object Object to test. Returns ------- result : bool True if `x` is a MaskedArray. See Also -------- isMA : Alias to isMaskedArray. isarray : Alias to isMaskedArray. Examples -------- >>> import numpy.ma as ma >>> a = np.eye(3, 3) >>> a array([[ 1., 0., 0.], [ 0., 1., 0.], [ 0., 0., 1.]]) >>> m = ma.masked_values(a, 0) >>> m masked_array(data = [[1.0 -- --] [-- 1.0 --] [-- -- 1.0]], mask = [[False True True] [ True False True] [ True True False]], fill_value=0.0) >>> ma.isMaskedArray(a) False >>> ma.isMaskedArray(m) True >>> ma.isMaskedArray([0, 1, 2]) False """ return isinstance(x, MaskedArray) isarray = isMaskedArray isMA = isMaskedArray #backward compatibility # We define the masked singleton as a float for higher precedence... # Note that it can be tricky sometimes w/ type comparison class MaskedConstant(MaskedArray): # _data = data = np.array(0.) _mask = mask = np.array(True) _baseclass = ndarray # def __new__(self): return self._data.view(self) # def __array_finalize__(self, obj): return # def __array_wrap__(self, obj): return self # def __str__(self): return str(masked_print_option._display) # def __repr__(self): return 'masked' # def flatten(self): return masked_array([self._data], dtype=float, mask=[True]) def __reduce__(self): """Override of MaskedArray's __reduce__. """ return (self.__class__, ()) masked = masked_singleton = MaskedConstant() masked_array = MaskedArray def array(data, dtype=None, copy=False, order=False, mask=nomask, fill_value=None, keep_mask=True, hard_mask=False, shrink=True, subok=True, ndmin=0, ): """array(data, dtype=None, copy=False, order=False, mask=nomask, fill_value=None, keep_mask=True, hard_mask=False, shrink=True, subok=True, ndmin=0) Acts as shortcut to MaskedArray, with options in a different order for convenience. And backwards compatibility... """ #!!!: we should try to put 'order' somwehere return MaskedArray(data, mask=mask, dtype=dtype, copy=copy, subok=subok, keep_mask=keep_mask, hard_mask=hard_mask, fill_value=fill_value, ndmin=ndmin, shrink=shrink) array.__doc__ = masked_array.__doc__ def is_masked(x): """ Determine whether input has masked values. Accepts any object as input, but always returns False unless the input is a MaskedArray containing masked values. Parameters ---------- x : array_like Array to check for masked values. Returns ------- result : bool True if `x` is a MaskedArray with masked values, False otherwise. Examples -------- >>> import numpy.ma as ma >>> x = ma.masked_equal([0, 1, 0, 2, 3], 0) >>> x masked_array(data = [-- 1 -- 2 3], mask = [ True False True False False], fill_value=999999) >>> ma.is_masked(x) True >>> x = ma.masked_equal([0, 1, 0, 2, 3], 42) >>> x masked_array(data = [0 1 0 2 3], mask = False, fill_value=999999) >>> ma.is_masked(x) False Always returns False if `x` isn't a MaskedArray. >>> x = [False, True, False] >>> ma.is_masked(x) False >>> x = 'a string' >>> ma.is_masked(x) False """ m = getmask(x) if m is nomask: return False elif m.any(): return True return False #####--------------------------------------------------------------------------- #---- --- Extrema functions --- #####--------------------------------------------------------------------------- class _extrema_operation(object): """ Generic class for maximum/minimum functions. .. note:: This is the base class for `_maximum_operation` and `_minimum_operation`. """ def __call__(self, a, b=None): "Executes the call behavior." if b is None: return self.reduce(a) return where(self.compare(a, b), a, b) #......... def reduce(self, target, axis=None): "Reduce target along the given axis." target = narray(target, copy=False, subok=True) m = getmask(target) if axis is not None: kargs = { 'axis' : axis } else: kargs = {} target = target.ravel() if not (m is nomask): m = m.ravel() if m is nomask: t = self.ufunc.reduce(target, **kargs) else: target = target.filled(self.fill_value_func(target)).view(type(target)) t = self.ufunc.reduce(target, **kargs) m = umath.logical_and.reduce(m, **kargs) if hasattr(t, '_mask'): t._mask = m elif m: t = masked return t #......... def outer (self, a, b): "Return the function applied to the outer product of a and b." ma = getmask(a) mb = getmask(b) if ma is nomask and mb is nomask: m = nomask else: ma = getmaskarray(a) mb = getmaskarray(b) m = logical_or.outer(ma, mb) result = self.ufunc.outer(filled(a), filled(b)) if not isinstance(result, MaskedArray): result = result.view(MaskedArray) result._mask = m return result #............................ class _minimum_operation(_extrema_operation): "Object to calculate minima" def __init__ (self): """minimum(a, b) or minimum(a) In one argument case, returns the scalar minimum. """ self.ufunc = umath.minimum self.afunc = amin self.compare = less self.fill_value_func = minimum_fill_value #............................ class _maximum_operation(_extrema_operation): "Object to calculate maxima" def __init__ (self): """maximum(a, b) or maximum(a) In one argument case returns the scalar maximum. """ self.ufunc = umath.maximum self.afunc = amax self.compare = greater self.fill_value_func = maximum_fill_value #.......................................................... def min(obj, axis=None, out=None, fill_value=None): try: return obj.min(axis=axis, fill_value=fill_value, out=out) except (AttributeError, TypeError): # If obj doesn't have a min method, # ...or if the method doesn't accept a fill_value argument return asanyarray(obj).min(axis=axis, fill_value=fill_value, out=out) min.__doc__ = MaskedArray.min.__doc__ def max(obj, axis=None, out=None, fill_value=None): try: return obj.max(axis=axis, fill_value=fill_value, out=out) except (AttributeError, TypeError): # If obj doesn't have a max method, # ...or if the method doesn't accept a fill_value argument return asanyarray(obj).max(axis=axis, fill_value=fill_value, out=out) max.__doc__ = MaskedArray.max.__doc__ def ptp(obj, axis=None, out=None, fill_value=None): """a.ptp(axis=None) = a.max(axis)-a.min(axis)""" try: return obj.ptp(axis, out=out, fill_value=fill_value) except (AttributeError, TypeError): # If obj doesn't have a ptp method, # ...or if the method doesn't accept a fill_value argument return asanyarray(obj).ptp(axis=axis, fill_value=fill_value, out=out) ptp.__doc__ = MaskedArray.ptp.__doc__ #####--------------------------------------------------------------------------- #---- --- Definition of functions from the corresponding methods --- #####--------------------------------------------------------------------------- class _frommethod: """ Define functions from existing MaskedArray methods. Parameters ---------- methodname : str Name of the method to transform. """ def __init__(self, methodname, reversed=False): self.__name__ = methodname self.__doc__ = self.getdoc() self.reversed = reversed # def getdoc(self): "Return the doc of the function (from the doc of the method)." meth = getattr(MaskedArray, self.__name__, None) or\ getattr(np, self.__name__, None) signature = self.__name__ + get_object_signature(meth) if meth is not None: doc = """ %s\n%s""" % (signature, getattr(meth, '__doc__', None)) return doc # def __call__(self, a, *args, **params): if self.reversed: args = list(args) arr = args[0] args[0] = a a = arr # Get the method from the array (if possible) method_name = self.__name__ method = getattr(a, method_name, None) if method is not None: return method(*args, **params) # Still here ? Then a is not a MaskedArray method = getattr(MaskedArray, method_name, None) if method is not None: return method(MaskedArray(a), *args, **params) # Still here ? OK, let's call the corresponding np function method = getattr(np, method_name) return method(a, *args, **params) all = _frommethod('all') anomalies = anom = _frommethod('anom') any = _frommethod('any') compress = _frommethod('compress', reversed=True) cumprod = _frommethod('cumprod') cumsum = _frommethod('cumsum') copy = _frommethod('copy') diagonal = _frommethod('diagonal') harden_mask = _frommethod('harden_mask') ids = _frommethod('ids') maximum = _maximum_operation() mean = _frommethod('mean') minimum = _minimum_operation() nonzero = _frommethod('nonzero') prod = _frommethod('prod') product = _frommethod('prod') ravel = _frommethod('ravel') repeat = _frommethod('repeat') shrink_mask = _frommethod('shrink_mask') soften_mask = _frommethod('soften_mask') std = _frommethod('std') sum = _frommethod('sum') swapaxes = _frommethod('swapaxes') #take = _frommethod('take') trace = _frommethod('trace') var = _frommethod('var') def take(a, indices, axis=None, out=None, mode='raise'): """ """ a = masked_array(a) return a.take(indices, axis=axis, out=out, mode=mode) #.............................................................................. def power(a, b, third=None): """ Returns element-wise base array raised to power from second array. This is the masked array version of `numpy.power`. For details see `numpy.power`. See Also -------- numpy.power Notes ----- The *out* argument to `numpy.power` is not supported, `third` has to be None. """ if third is not None: raise MaskError("3-argument power not supported.") # Get the masks ma = getmask(a) mb = getmask(b) m = mask_or(ma, mb) # Get the rawdata fa = getdata(a) fb = getdata(b) # Get the type of the result (so that we preserve subclasses) if isinstance(a, MaskedArray): basetype = type(a) else: basetype = MaskedArray # Get the result and view it as a (subclass of) MaskedArray with np.errstate(): np.seterr(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 invalid = np.logical_not(np.isfinite(result.view(ndarray))) # Add the initial mask if m is not nomask: if not (result.ndim): return masked result._mask = np.logical_or(m, invalid) # Fix the invalid parts if invalid.any(): if not result.ndim: return masked elif result._mask is nomask: result._mask = invalid result._data[invalid] = result.fill_value return result # if fb.dtype.char in typecodes["Integer"]: # return masked_array(umath.power(fa, fb), m) # m = mask_or(m, (fa < 0) & (fb != fb.astype(int))) # if m is nomask: # return masked_array(umath.power(fa, fb)) # else: # fa = fa.copy() # if m.all(): # fa.flat = 1 # else: # np.copyto(fa, 1, where=m) # return masked_array(umath.power(fa, fb), m) #.............................................................................. def argsort(a, axis=None, kind='quicksort', order=None, fill_value=None): "Function version of the eponymous method." if fill_value is None: fill_value = default_fill_value(a) d = filled(a, fill_value) if axis is None: return d.argsort(kind=kind, order=order) return d.argsort(axis, kind=kind, order=order) argsort.__doc__ = MaskedArray.argsort.__doc__ def argmin(a, axis=None, fill_value=None): "Function version of the eponymous method." if fill_value is None: fill_value = default_fill_value(a) d = filled(a, fill_value) return d.argmin(axis=axis) argmin.__doc__ = MaskedArray.argmin.__doc__ def argmax(a, axis=None, fill_value=None): "Function version of the eponymous method." if fill_value is None: fill_value = default_fill_value(a) try: fill_value = -fill_value except: pass d = filled(a, fill_value) return d.argmax(axis=axis) argmin.__doc__ = MaskedArray.argmax.__doc__ def sort(a, axis= -1, kind='quicksort', order=None, endwith=True, fill_value=None): "Function version of the eponymous method." a = narray(a, copy=True, subok=True) if axis is None: a = a.flatten() axis = 0 if fill_value is None: if endwith: filler = minimum_fill_value(a) else: filler = maximum_fill_value(a) else: filler = fill_value # return indx = np.indices(a.shape).tolist() indx[axis] = filled(a, filler).argsort(axis=axis, kind=kind, order=order) return a[indx] sort.__doc__ = MaskedArray.sort.__doc__ def compressed(x): """ Return all the non-masked data as a 1-D array. This function is equivalent to calling the "compressed" method of a `MaskedArray`, see `MaskedArray.compressed` for details. See Also -------- MaskedArray.compressed Equivalent method. """ if getmask(x) is nomask: return np.asanyarray(x) else: return x.compressed() def concatenate(arrays, axis=0): """ Concatenate a sequence of arrays along the given axis. Parameters ---------- arrays : sequence of array_like The arrays must have the same shape, except in the dimension corresponding to `axis` (the first, by default). axis : int, optional The axis along which the arrays will be joined. Default is 0. Returns ------- result : MaskedArray The concatenated array with any masked entries preserved. See Also -------- numpy.concatenate : Equivalent function in the top-level NumPy module. Examples -------- >>> import numpy.ma as ma >>> a = ma.arange(3) >>> a[1] = ma.masked >>> b = ma.arange(2, 5) >>> a masked_array(data = [0 -- 2], mask = [False True False], fill_value = 999999) >>> b masked_array(data = [2 3 4], mask = False, fill_value = 999999) >>> ma.concatenate([a, b]) masked_array(data = [0 -- 2 2 3 4], mask = [False True False False False False], fill_value = 999999) """ d = np.concatenate([getdata(a) for a in arrays], axis) rcls = get_masked_subclass(*arrays) data = d.view(rcls) # Check whether one of the arrays has a non-empty mask... for x in arrays: if getmask(x) is not nomask: break else: return data # OK, so we have to concatenate the masks dm = np.concatenate([getmaskarray(a) for a in arrays], axis) # If we decide to keep a '_shrinkmask' option, we want to check that ... # ... all of them are True, and then check for dm.any() # shrink = numpy.logical_or.reduce([getattr(a,'_shrinkmask',True) for a in arrays]) # if shrink and not dm.any(): if not dm.dtype.fields and not dm.any(): data._mask = nomask else: data._mask = dm.reshape(d.shape) return data def count(a, axis=None): if isinstance(a, MaskedArray): return a.count(axis) return masked_array(a, copy=False).count(axis) count.__doc__ = MaskedArray.count.__doc__ def diag(v, k=0): """ Extract a diagonal or construct a diagonal array. This function is the equivalent of `numpy.diag` that takes masked values into account, see `numpy.diag` for details. See Also -------- numpy.diag : Equivalent function for ndarrays. """ output = np.diag(v, k).view(MaskedArray) if getmask(v) is not nomask: output._mask = np.diag(v._mask, k) return output def expand_dims(x, axis): """ Expand the shape of an array. Expands the shape of the array by including a new axis before the one specified by the `axis` parameter. This function behaves the same as `numpy.expand_dims` but preserves masked elements. See Also -------- numpy.expand_dims : Equivalent function in top-level NumPy module. Examples -------- >>> import numpy.ma as ma >>> x = ma.array([1, 2, 4]) >>> x[1] = ma.masked >>> x masked_array(data = [1 -- 4], mask = [False True False], fill_value = 999999) >>> np.expand_dims(x, axis=0) array([[1, 2, 4]]) >>> ma.expand_dims(x, axis=0) masked_array(data = [[1 -- 4]], mask = [[False True False]], fill_value = 999999) The same result can be achieved using slicing syntax with `np.newaxis`. >>> x[np.newaxis, :] masked_array(data = [[1 -- 4]], mask = [[False True False]], fill_value = 999999) """ result = n_expand_dims(x, axis) if isinstance(x, MaskedArray): new_shape = result.shape result = x.view() result.shape = new_shape if result._mask is not nomask: result._mask.shape = new_shape return result #...................................... def left_shift (a, n): """ Shift the bits of an integer to the left. This is the masked array version of `numpy.left_shift`, for details see that function. See Also -------- numpy.left_shift """ m = getmask(a) if m is nomask: d = umath.left_shift(filled(a), n) return masked_array(d) else: d = umath.left_shift(filled(a, 0), n) return masked_array(d, mask=m) def right_shift (a, n): """ Shift the bits of an integer to the right. This is the masked array version of `numpy.right_shift`, for details see that function. See Also -------- numpy.right_shift """ m = getmask(a) if m is nomask: d = umath.right_shift(filled(a), n) return masked_array(d) else: d = umath.right_shift(filled(a, 0), n) return masked_array(d, mask=m) #...................................... def put(a, indices, values, mode='raise'): """ Set storage-indexed locations to corresponding values. This function is equivalent to `MaskedArray.put`, see that method for details. See Also -------- MaskedArray.put """ # We can't use 'frommethod', the order of arguments is different try: return a.put(indices, values, mode=mode) except AttributeError: return narray(a, copy=False).put(indices, values, mode=mode) def putmask(a, mask, values): #, mode='raise'): """ Changes elements of an array based on conditional and input values. This is the masked array version of `numpy.putmask`, for details see `numpy.putmask`. See Also -------- numpy.putmask Notes ----- Using a masked array as `values` will **not** transform a `ndarray` into a `MaskedArray`. """ # We can't use 'frommethod', the order of arguments is different if not isinstance(a, MaskedArray): a = a.view(MaskedArray) (valdata, valmask) = (getdata(values), getmask(values)) if getmask(a) is nomask: if valmask is not nomask: a._sharedmask = True a._mask = make_mask_none(a.shape, a.dtype) np.copyto(a._mask, valmask, where=mask) elif a._hardmask: if valmask is not nomask: m = a._mask.copy() np.copyto(m, valmask, where=mask) a.mask |= m else: if valmask is nomask: valmask = getmaskarray(values) np.copyto(a._mask, valmask, where=mask) np.copyto(a._data, valdata, where=mask) return def transpose(a, axes=None): """ Permute the dimensions of an array. This function is exactly equivalent to `numpy.transpose`. See Also -------- numpy.transpose : Equivalent function in top-level NumPy module. Examples -------- >>> import numpy.ma as ma >>> x = ma.arange(4).reshape((2,2)) >>> x[1, 1] = ma.masked >>>> x masked_array(data = [[0 1] [2 --]], mask = [[False False] [False True]], fill_value = 999999) >>> ma.transpose(x) masked_array(data = [[0 2] [1 --]], mask = [[False False] [False True]], fill_value = 999999) """ #We can't use 'frommethod', as 'transpose' doesn't take keywords try: return a.transpose(axes) except AttributeError: return narray(a, copy=False).transpose(axes).view(MaskedArray) def reshape(a, new_shape, order='C'): """ Returns an array containing the same data with a new shape. Refer to `MaskedArray.reshape` for full documentation. See Also -------- MaskedArray.reshape : equivalent function """ #We can't use 'frommethod', it whine about some parameters. Dmmit. try: return a.reshape(new_shape, order=order) except AttributeError: _tmp = narray(a, copy=False).reshape(new_shape, order=order) return _tmp.view(MaskedArray) def resize(x, new_shape): """ Return a new masked array with the specified size and shape. This is the masked equivalent of the `numpy.resize` function. The new array is filled with repeated copies of `x` (in the order that the data are stored in memory). If `x` is masked, the new array will be masked, and the new mask will be a repetition of the old one. See Also -------- numpy.resize : Equivalent function in the top level NumPy module. Examples -------- >>> import numpy.ma as ma >>> a = ma.array([[1, 2] ,[3, 4]]) >>> a[0, 1] = ma.masked >>> a masked_array(data = [[1 --] [3 4]], mask = [[False True] [False False]], fill_value = 999999) >>> np.resize(a, (3, 3)) array([[1, 2, 3], [4, 1, 2], [3, 4, 1]]) >>> ma.resize(a, (3, 3)) masked_array(data = [[1 -- 3] [4 1 --] [3 4 1]], mask = [[False True False] [False False True] [False False False]], fill_value = 999999) A MaskedArray is always returned, regardless of the input type. >>> a = np.array([[1, 2] ,[3, 4]]) >>> ma.resize(a, (3, 3)) masked_array(data = [[1 2 3] [4 1 2] [3 4 1]], mask = False, fill_value = 999999) """ # We can't use _frommethods here, as N.resize is notoriously whiny. m = getmask(x) if m is not nomask: m = np.resize(m, new_shape) result = np.resize(x, new_shape).view(get_masked_subclass(x)) if result.ndim: result._mask = m return result #................................................ def rank(obj): "maskedarray version of the numpy function." return np.rank(getdata(obj)) rank.__doc__ = np.rank.__doc__ # def shape(obj): "maskedarray version of the numpy function." return np.shape(getdata(obj)) shape.__doc__ = np.shape.__doc__ # def size(obj, axis=None): "maskedarray version of the numpy function." return np.size(getdata(obj), axis) size.__doc__ = np.size.__doc__ #................................................ #####-------------------------------------------------------------------------- #---- --- Extra functions --- #####-------------------------------------------------------------------------- def where (condition, x=None, y=None): """ Return a masked array with elements from x or y, depending on condition. Returns a masked array, shaped like condition, where the elements are from `x` when `condition` is True, and from `y` otherwise. If neither `x` nor `y` are given, the function returns a tuple of indices where `condition` is True (the result of ``condition.nonzero()``). Parameters ---------- condition : array_like, bool The condition to meet. For each True element, yield the corresponding element from `x`, otherwise from `y`. x, y : array_like, optional Values from which to choose. `x` and `y` need to have the same shape as condition, or be broadcast-able to that shape. Returns ------- out : MaskedArray or tuple of ndarrays The resulting masked array if `x` and `y` were given, otherwise the result of ``condition.nonzero()``. See Also -------- numpy.where : Equivalent function in the top-level NumPy module. Examples -------- >>> x = np.ma.array(np.arange(9.).reshape(3, 3), mask=[[0, 1, 0], ... [1, 0, 1], ... [0, 1, 0]]) >>> print x [[0.0 -- 2.0] [-- 4.0 --] [6.0 -- 8.0]] >>> np.ma.where(x > 5) # return the indices where x > 5 (array([2, 2]), array([0, 2])) >>> print np.ma.where(x > 5, x, -3.1416) [[-3.1416 -- -3.1416] [-- -3.1416 --] [6.0 -- 8.0]] """ if x is None and y is None: return filled(condition, 0).nonzero() elif x is None or y is None: raise ValueError("Either both or neither x and y should be given.") # Get the condition ............... fc = filled(condition, 0).astype(MaskType) notfc = np.logical_not(fc) # Get the data ...................................... xv = getdata(x) yv = getdata(y) if x is masked: ndtype = yv.dtype elif y is masked: ndtype = xv.dtype else: ndtype = np.find_common_type([xv.dtype, yv.dtype], []) # Construct an empty array and fill it d = np.empty(fc.shape, dtype=ndtype).view(MaskedArray) _data = d._data np.copyto(_data, xv.astype(ndtype), where=fc) np.copyto(_data, yv.astype(ndtype), where=notfc) # Create an empty mask and fill it _mask = d._mask = np.zeros(fc.shape, dtype=MaskType) np.copyto(_mask, getmask(x), where=fc) np.copyto(_mask, getmask(y), where=notfc) _mask |= getmaskarray(condition) if not _mask.any(): d._mask = nomask return d def choose (indices, choices, out=None, mode='raise'): """ Use an index array to construct a new array from a set of choices. Given an array of integers and a set of n choice arrays, this method will create a new array that merges each of the choice arrays. Where a value in `a` is i, the new array will have the value that choices[i] contains in the same place. Parameters ---------- a : ndarray of ints This array must contain integers in ``[0, n-1]``, where n is the number of choices. choices : sequence of arrays Choice arrays. The index array and all of the choices should be broadcastable to the same shape. out : array, optional If provided, the result will be inserted into this array. It should be of the appropriate shape and `dtype`. mode : {'raise', 'wrap', 'clip'}, optional Specifies how out-of-bounds indices will behave. * 'raise' : raise an error * 'wrap' : wrap around * 'clip' : clip to the range Returns ------- merged_array : array See Also -------- choose : equivalent function Examples -------- >>> choice = np.array([[1,1,1], [2,2,2], [3,3,3]]) >>> a = np.array([2, 1, 0]) >>> np.ma.choose(a, choice) masked_array(data = [3 2 1], mask = False, fill_value=999999) """ def fmask (x): "Returns the filled array, or True if masked." if x is masked: return True return filled(x) def nmask (x): "Returns the mask, True if ``masked``, False if ``nomask``." if x is masked: return True return getmask(x) # Get the indices...... c = filled(indices, 0) # Get the masks........ masks = [nmask(x) for x in choices] data = [fmask(x) for x in choices] # Construct the mask outputmask = np.choose(c, masks, mode=mode) outputmask = make_mask(mask_or(outputmask, getmask(indices)), copy=0, shrink=True) # Get the choices...... d = np.choose(c, data, mode=mode, out=out).view(MaskedArray) if out is not None: if isinstance(out, MaskedArray): out.__setmask__(outputmask) return out d.__setmask__(outputmask) return d def round_(a, decimals=0, out=None): """ Return a copy of a, rounded to 'decimals' places. When 'decimals' is negative, it specifies the number of positions to the left of the decimal point. The real and imaginary parts of complex numbers are rounded separately. Nothing is done if the array is not of float type and 'decimals' is greater than or equal to 0. Parameters ---------- decimals : int Number of decimals to round to. May be negative. out : array_like Existing array to use for output. If not given, returns a default copy of a. Notes ----- If out is given and does not have a mask attribute, the mask of a is lost! """ if out is None: return np.round_(a, decimals, out) else: np.round_(getdata(a), decimals, out) if hasattr(out, '_mask'): out._mask = getmask(a) return out round = round_ def inner(a, b): """ Returns the inner product of a and b for arrays of floating point types. Like the generic NumPy equivalent the product sum is over the last dimension of a and b. Notes ----- The first argument is not conjugated. """ fa = filled(a, 0) fb = filled(b, 0) if len(fa.shape) == 0: fa.shape = (1,) if len(fb.shape) == 0: fb.shape = (1,) return np.inner(fa, fb).view(MaskedArray) inner.__doc__ = doc_note(np.inner.__doc__, "Masked values are replaced by 0.") innerproduct = inner def outer(a, b): "maskedarray version of the numpy function." fa = filled(a, 0).ravel() fb = filled(b, 0).ravel() d = np.outer(fa, fb) ma = getmask(a) mb = getmask(b) if ma is nomask and mb is nomask: return masked_array(d) ma = getmaskarray(a) mb = getmaskarray(b) m = make_mask(1 - np.outer(1 - ma, 1 - mb), copy=0) return masked_array(d, mask=m) outer.__doc__ = doc_note(np.outer.__doc__, "Masked values are replaced by 0.") outerproduct = outer def allequal (a, b, fill_value=True): """ Return True if all entries of a and b are equal, using fill_value as a truth value where either or both are masked. Parameters ---------- a, b : array_like Input arrays to compare. fill_value : bool, optional Whether masked values in a or b are considered equal (True) or not (False). Returns ------- y : bool Returns True if the two arrays are equal within the given tolerance, False otherwise. If either array contains NaN, then False is returned. See Also -------- all, any numpy.ma.allclose Examples -------- >>> a = ma.array([1e10, 1e-7, 42.0], mask=[0, 0, 1]) >>> a masked_array(data = [10000000000.0 1e-07 --], mask = [False False True], fill_value=1e+20) >>> b = array([1e10, 1e-7, -42.0]) >>> b array([ 1.00000000e+10, 1.00000000e-07, -4.20000000e+01]) >>> ma.allequal(a, b, fill_value=False) False >>> ma.allequal(a, b) True """ m = mask_or(getmask(a), getmask(b)) if m is nomask: x = getdata(a) y = getdata(b) d = umath.equal(x, y) return d.all() elif fill_value: x = getdata(a) y = getdata(b) d = umath.equal(x, y) dm = array(d, mask=m, copy=False) return dm.filled(True).all(None) else: return False def allclose (a, b, masked_equal=True, rtol=1e-5, atol=1e-8): """ Returns True if two arrays are element-wise equal within a tolerance. This function is equivalent to `allclose` except that masked values are treated as equal (default) or unequal, depending on the `masked_equal` argument. Parameters ---------- a, b : array_like Input arrays to compare. masked_equal : bool, optional Whether masked values in `a` and `b` are considered equal (True) or not (False). They are considered equal by default. rtol : float, optional Relative tolerance. The relative difference is equal to ``rtol * b``. Default is 1e-5. atol : float, optional Absolute tolerance. The absolute difference is equal to `atol`. Default is 1e-8. Returns ------- y : bool Returns True if the two arrays are equal within the given tolerance, False otherwise. If either array contains NaN, then False is returned. See Also -------- all, any numpy.allclose : the non-masked `allclose`. Notes ----- If the following equation is element-wise True, then `allclose` returns True:: absolute(`a` - `b`) <= (`atol` + `rtol` * absolute(`b`)) Return True if all elements of `a` and `b` are equal subject to given tolerances. Examples -------- >>> a = ma.array([1e10, 1e-7, 42.0], mask=[0, 0, 1]) >>> a masked_array(data = [10000000000.0 1e-07 --], mask = [False False True], fill_value = 1e+20) >>> b = ma.array([1e10, 1e-8, -42.0], mask=[0, 0, 1]) >>> ma.allclose(a, b) False >>> a = ma.array([1e10, 1e-8, 42.0], mask=[0, 0, 1]) >>> b = ma.array([1.00001e10, 1e-9, -42.0], mask=[0, 0, 1]) >>> ma.allclose(a, b) True >>> ma.allclose(a, b, masked_equal=False) False Masked values are not compared directly. >>> a = ma.array([1e10, 1e-8, 42.0], mask=[0, 0, 1]) >>> b = ma.array([1.00001e10, 1e-9, 42.0], mask=[0, 0, 1]) >>> ma.allclose(a, b) True >>> ma.allclose(a, b, masked_equal=False) False """ x = masked_array(a, copy=False) y = masked_array(b, 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. if not np.all(xinf == filled(np.isinf(y), False)): return False # No infs at all if not np.any(xinf): d = filled(umath.less_equal(umath.absolute(x - y), 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) #.............................................................................. def asarray(a, dtype=None, order=None): """ Convert the input to a masked array of the given data-type. No copy is performed if the input is already an `ndarray`. If `a` is a subclass of `MaskedArray`, a base class `MaskedArray` is returned. Parameters ---------- a : array_like Input data, in any form that can be converted to a masked array. This includes lists, lists of tuples, tuples, tuples of tuples, tuples of lists, ndarrays and masked arrays. dtype : dtype, optional By default, the data-type is inferred from the input data. order : {'C', 'F'}, optional Whether to use row-major ('C') or column-major ('FORTRAN') memory representation. Default is 'C'. Returns ------- out : MaskedArray Masked array interpretation of `a`. See Also -------- asanyarray : Similar to `asarray`, but conserves subclasses. Examples -------- >>> x = np.arange(10.).reshape(2, 5) >>> x array([[ 0., 1., 2., 3., 4.], [ 5., 6., 7., 8., 9.]]) >>> np.ma.asarray(x) masked_array(data = [[ 0. 1. 2. 3. 4.] [ 5. 6. 7. 8. 9.]], mask = False, fill_value = 1e+20) >>> type(np.ma.asarray(x)) """ return masked_array(a, dtype=dtype, copy=False, keep_mask=True, subok=False) def asanyarray(a, dtype=None): """ Convert the input to a masked array, conserving subclasses. If `a` is a subclass of `MaskedArray`, its class is conserved. No copy is performed if the input is already an `ndarray`. Parameters ---------- a : array_like Input data, in any form that can be converted to an array. dtype : dtype, optional By default, the data-type is inferred from the input data. order : {'C', 'F'}, optional Whether to use row-major ('C') or column-major ('FORTRAN') memory representation. Default is 'C'. Returns ------- out : MaskedArray MaskedArray interpretation of `a`. See Also -------- asarray : Similar to `asanyarray`, but does not conserve subclass. Examples -------- >>> x = np.arange(10.).reshape(2, 5) >>> x array([[ 0., 1., 2., 3., 4.], [ 5., 6., 7., 8., 9.]]) >>> np.ma.asanyarray(x) masked_array(data = [[ 0. 1. 2. 3. 4.] [ 5. 6. 7. 8. 9.]], mask = False, fill_value = 1e+20) >>> type(np.ma.asanyarray(x)) """ return masked_array(a, dtype=dtype, copy=False, keep_mask=True, subok=True) #####-------------------------------------------------------------------------- #---- --- Pickling --- #####-------------------------------------------------------------------------- def dump(a, F): """ Pickle a masked array to a file. This is a wrapper around ``cPickle.dump``. Parameters ---------- a : MaskedArray The array to be pickled. F : str or file-like object The file to pickle `a` to. If a string, the full path to the file. """ if not hasattr(F, 'readline'): F = open(F, 'w') return pickle.dump(a, F) def dumps(a): """ Return a string corresponding to the pickling of a masked array. This is a wrapper around ``cPickle.dumps``. Parameters ---------- a : MaskedArray The array for which the string representation of the pickle is returned. """ return pickle.dumps(a) def load(F): """ Wrapper around ``cPickle.load`` which accepts either a file-like object or a filename. Parameters ---------- F : str or file The file or file name to load. See Also -------- dump : Pickle an array Notes ----- This is different from `numpy.load`, which does not use cPickle but loads the NumPy binary .npy format. """ if not hasattr(F, 'readline'): F = open(F, 'r') return pickle.load(F) def loads(strg): """ Load a pickle from the current string. The result of ``cPickle.loads(strg)`` is returned. Parameters ---------- strg : str The string to load. See Also -------- dumps : Return a string corresponding to the pickling of a masked array. """ return pickle.loads(strg) ################################################################################ def fromfile(file, dtype=float, count= -1, sep=''): raise NotImplementedError("Not yet implemented. Sorry") def fromflex(fxarray): """ Build a masked array from a suitable flexible-type array. The input array has to have a data-type with ``_data`` and ``_mask`` fields. This type of array is output by `MaskedArray.toflex`. Parameters ---------- fxarray : ndarray The structured input array, containing ``_data`` and ``_mask`` fields. If present, other fields are discarded. Returns ------- result : MaskedArray The constructed masked array. See Also -------- MaskedArray.toflex : Build a flexible-type array from a masked array. Examples -------- >>> x = np.ma.array(np.arange(9).reshape(3, 3), mask=[0] + [1, 0] * 4) >>> rec = x.toflex() >>> rec array([[(0, False), (1, True), (2, False)], [(3, True), (4, False), (5, True)], [(6, False), (7, True), (8, False)]], dtype=[('_data', '>> x2 = np.ma.fromflex(rec) >>> x2 masked_array(data = [[0 -- 2] [-- 4 --] [6 -- 8]], mask = [[False True False] [ True False True] [False True False]], fill_value = 999999) Extra fields can be present in the structured array but are discarded: >>> dt = [('_data', '>> rec2 = np.zeros((2, 2), dtype=dt) >>> rec2 array([[(0, False, 0.0), (0, False, 0.0)], [(0, False, 0.0), (0, False, 0.0)]], dtype=[('_data', '>> y = np.ma.fromflex(rec2) >>> y masked_array(data = [[0 0] [0 0]], mask = [[False False] [False False]], fill_value = 999999) """ return masked_array(fxarray['_data'], mask=fxarray['_mask']) class _convert2ma: """ Convert functions from numpy to numpy.ma. Parameters ---------- _methodname : string Name of the method to transform. """ __doc__ = None # def __init__(self, funcname, params=None): self._func = getattr(np, funcname) self.__doc__ = self.getdoc() self._extras = params or {} # def getdoc(self): "Return the doc of the function (from the doc of the method)." doc = getattr(self._func, '__doc__', None) sig = get_object_signature(self._func) if doc: # Add the signature of the function at the beginning of the doc if sig: sig = "%s%s\n" % (self._func.__name__, sig) doc = sig + doc return doc # def __call__(self, a, *args, **params): # Find the common parameters to the call and the definition _extras = self._extras common_params = set(params).intersection(_extras) # Drop the common parameters from the call for p in common_params: _extras[p] = params.pop(p) # Get the result result = self._func.__call__(a, *args, **params).view(MaskedArray) if "fill_value" in common_params: result.fill_value = _extras.get("fill_value", None) if "hardmask" in common_params: result._hardmask = bool(_extras.get("hard_mask", False)) return result arange = _convert2ma('arange', params=dict(fill_value=None, hardmask=False)) clip = np.clip diff = np.diff empty = _convert2ma('empty', params=dict(fill_value=None, hardmask=False)) empty_like = _convert2ma('empty_like') frombuffer = _convert2ma('frombuffer') fromfunction = _convert2ma('fromfunction') identity = _convert2ma('identity', params=dict(fill_value=None, hardmask=False)) indices = np.indices ones = _convert2ma('ones', params=dict(fill_value=None, hardmask=False)) ones_like = np.ones_like squeeze = np.squeeze zeros = _convert2ma('zeros', params=dict(fill_value=None, hardmask=False)) zeros_like = np.zeros_like ############################################################################### numpy-1.8.2/numpy/ma/timer_comparison.py0000664000175100017510000004213412370216242021520 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function import timeit from functools import reduce import numpy as np from numpy import float_ import np.core.fromnumeric as fromnumeric from np.testing.utils import build_err_msg # Fixme: this does not look right. np.seterr(all='ignore') pi = np.pi class moduletester(object): def __init__(self, module): self.module = module self.allequal = module.allequal self.arange = module.arange self.array = module.array # self.average = module.average self.concatenate = module.concatenate self.count = module.count self.equal = module.equal self.filled = module.filled self.getmask = module.getmask self.getmaskarray = module.getmaskarray self.id = id self.inner = module.inner self.make_mask = module.make_mask self.masked = module.masked self.masked_array = module.masked_array self.masked_values = module.masked_values self.mask_or = module.mask_or self.nomask = module.nomask self.ones = module.ones self.outer = module.outer self.repeat = module.repeat self.resize = module.resize self.sort = module.sort self.take = module.take self.transpose = module.transpose self.zeros = module.zeros self.MaskType = module.MaskType try: self.umath = module.umath except AttributeError: self.umath = module.core.umath self.testnames = [] def assert_array_compare(self, comparison, x, y, err_msg='', header='', fill_value=True): """Asserts that a comparison relation between two masked arrays is satisfied elementwise.""" xf = self.filled(x) yf = self.filled(y) m = self.mask_or(self.getmask(x), self.getmask(y)) x = self.filled(self.masked_array(xf, mask=m), fill_value) y = self.filled(self.masked_array(yf, mask=m), fill_value) if (x.dtype.char != "O"): x = x.astype(float_) if isinstance(x, np.ndarray) and x.size > 1: x[np.isnan(x)] = 0 elif np.isnan(x): x = 0 if (y.dtype.char != "O"): y = y.astype(float_) if isinstance(y, np.ndarray) and y.size > 1: y[np.isnan(y)] = 0 elif np.isnan(y): y = 0 try: cond = (x.shape==() or y.shape==()) or x.shape == y.shape if not cond: msg = build_err_msg([x, y], err_msg + '\n(shapes %s, %s mismatch)' % (x.shape, y.shape), header=header, names=('x', 'y')) assert cond, msg val = comparison(x, y) if m is not self.nomask and fill_value: val = self.masked_array(val, mask=m) if isinstance(val, bool): cond = val reduced = [0] else: reduced = val.ravel() cond = reduced.all() reduced = reduced.tolist() if not cond: match = 100-100.0*reduced.count(1)/len(reduced) msg = build_err_msg([x, y], err_msg + '\n(mismatch %s%%)' % (match,), header=header, names=('x', 'y')) assert cond, msg except ValueError: msg = build_err_msg([x, y], err_msg, header=header, names=('x', 'y')) raise ValueError(msg) def assert_array_equal(self, x, y, err_msg=''): """Checks the elementwise equality of two masked arrays.""" self.assert_array_compare(self.equal, x, y, err_msg=err_msg, header='Arrays are not equal') def test_0(self): "Tests creation" x = np.array([1., 1., 1., -2., pi/2.0, 4., 5., -10., 10., 1., 2., 3.]) m = [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0] xm = self.masked_array(x, mask=m) xm[0] def test_1(self): "Tests creation" x = np.array([1., 1., 1., -2., pi/2.0, 4., 5., -10., 10., 1., 2., 3.]) y = np.array([5., 0., 3., 2., -1., -4., 0., -10., 10., 1., 0., 3.]) a10 = 10. m1 = [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0] m2 = [0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1] xm = self.masked_array(x, mask=m1) ym = self.masked_array(y, mask=m2) z = np.array([-.5, 0., .5, .8]) zm = self.masked_array(z, mask=[0, 1, 0, 0]) xf = np.where(m1, 1.e+20, x) xm.set_fill_value(1.e+20) assert((xm-ym).filled(0).any()) #fail_if_equal(xm.mask.astype(int_), ym.mask.astype(int_)) s = x.shape assert(xm.size == reduce(lambda x, y:x*y, s)) assert(self.count(xm) == len(m1) - reduce(lambda x, y:x+y, m1)) for s in [(4, 3), (6, 2)]: x.shape = s y.shape = s xm.shape = s ym.shape = s xf.shape = s assert(self.count(xm) == len(m1) - reduce(lambda x, y:x+y, m1)) def test_2(self): "Tests conversions and indexing" x1 = np.array([1, 2, 4, 3]) x2 = self.array(x1, mask=[1, 0, 0, 0]) x3 = self.array(x1, mask=[0, 1, 0, 1]) x4 = self.array(x1) # test conversion to strings junk, garbage = str(x2), repr(x2) # assert_equal(np.sort(x1), self.sort(x2, fill_value=0)) # tests of indexing assert type(x2[1]) is type(x1[1]) assert x1[1] == x2[1] # assert self.allequal(x1[2],x2[2]) # assert self.allequal(x1[2:5],x2[2:5]) # assert self.allequal(x1[:],x2[:]) # assert self.allequal(x1[1:], x3[1:]) x1[2] = 9 x2[2] = 9 self.assert_array_equal(x1, x2) x1[1:3] = 99 x2[1:3] = 99 # assert self.allequal(x1,x2) x2[1] = self.masked # assert self.allequal(x1,x2) x2[1:3] = self.masked # assert self.allequal(x1,x2) x2[:] = x1 x2[1] = self.masked # assert self.allequal(self.getmask(x2),self.array([0,1,0,0])) x3[:] = self.masked_array([1, 2, 3, 4], [0, 1, 1, 0]) # assert self.allequal(self.getmask(x3), self.array([0,1,1,0])) x4[:] = self.masked_array([1, 2, 3, 4], [0, 1, 1, 0]) # assert self.allequal(self.getmask(x4), self.array([0,1,1,0])) # assert self.allequal(x4, self.array([1,2,3,4])) x1 = np.arange(5)*1.0 x2 = self.masked_values(x1, 3.0) # assert self.allequal(x1,x2) # assert self.allequal(self.array([0,0,0,1,0], self.MaskType), x2.mask) x1 = self.array([1, 'hello', 2, 3], object) x2 = np.array([1, 'hello', 2, 3], object) s1 = x1[1] s2 = x2[1] assert x1[1:1].shape == (0,) # Tests copy-size n = [0, 0, 1, 0, 0] m = self.make_mask(n) m2 = self.make_mask(m) assert(m is m2) m3 = self.make_mask(m, copy=1) assert(m is not m3) def test_3(self): "Tests resize/repeat" x4 = self.arange(4) x4[2] = self.masked y4 = self.resize(x4, (8,)) assert self.allequal(self.concatenate([x4, x4]), y4) assert self.allequal(self.getmask(y4), [0, 0, 1, 0, 0, 0, 1, 0]) y5 = self.repeat(x4, (2, 2, 2, 2), axis=0) self.assert_array_equal(y5, [0, 0, 1, 1, 2, 2, 3, 3]) y6 = self.repeat(x4, 2, axis=0) assert self.allequal(y5, y6) y7 = x4.repeat((2, 2, 2, 2), axis=0) assert self.allequal(y5, y7) y8 = x4.repeat(2, 0) assert self.allequal(y5, y8) #---------------------------------- def test_4(self): "Test of take, transpose, inner, outer products" x = self.arange(24) y = np.arange(24) x[5:6] = self.masked x = x.reshape(2, 3, 4) y = y.reshape(2, 3, 4) assert self.allequal(np.transpose(y, (2, 0, 1)), self.transpose(x, (2, 0, 1))) assert self.allequal(np.take(y, (2, 0, 1), 1), self.take(x, (2, 0, 1), 1)) assert self.allequal(np.inner(self.filled(x, 0), self.filled(y, 0)), self.inner(x, y)) assert self.allequal(np.outer(self.filled(x, 0), self.filled(y, 0)), self.outer(x, y)) y = self.array(['abc', 1, 'def', 2, 3], object) y[2] = self.masked t = self.take(y, [0, 3, 4]) assert t[0] == 'abc' assert t[1] == 2 assert t[2] == 3 #---------------------------------- def test_5(self): "Tests inplace w/ scalar" x = self.arange(10) y = self.arange(10) xm = self.arange(10) xm[2] = self.masked x += 1 assert self.allequal(x, y+1) xm += 1 assert self.allequal(xm, y+1) x = self.arange(10) xm = self.arange(10) xm[2] = self.masked x -= 1 assert self.allequal(x, y-1) xm -= 1 assert self.allequal(xm, y-1) x = self.arange(10)*1.0 xm = self.arange(10)*1.0 xm[2] = self.masked x *= 2.0 assert self.allequal(x, y*2) xm *= 2.0 assert self.allequal(xm, y*2) x = self.arange(10)*2 xm = self.arange(10)*2 xm[2] = self.masked x /= 2 assert self.allequal(x, y) xm /= 2 assert self.allequal(xm, y) x = self.arange(10)*1.0 xm = self.arange(10)*1.0 xm[2] = self.masked x /= 2.0 assert self.allequal(x, y/2.0) xm /= self.arange(10) self.assert_array_equal(xm, self.ones((10,))) x = self.arange(10).astype(float_) xm = self.arange(10) xm[2] = self.masked id1 = self.id(x.raw_data()) x += 1. #assert id1 == self.id(x.raw_data()) assert self.allequal(x, y+1.) def test_6(self): "Tests inplace w/ array" x = self.arange(10, dtype=float_) y = self.arange(10) xm = self.arange(10, dtype=float_) xm[2] = self.masked m = xm.mask a = self.arange(10, dtype=float_) a[-1] = self.masked x += a xm += a assert self.allequal(x, y+a) assert self.allequal(xm, y+a) assert self.allequal(xm.mask, self.mask_or(m, a.mask)) x = self.arange(10, dtype=float_) xm = self.arange(10, dtype=float_) xm[2] = self.masked m = xm.mask a = self.arange(10, dtype=float_) a[-1] = self.masked x -= a xm -= a assert self.allequal(x, y-a) assert self.allequal(xm, y-a) assert self.allequal(xm.mask, self.mask_or(m, a.mask)) x = self.arange(10, dtype=float_) xm = self.arange(10, dtype=float_) xm[2] = self.masked m = xm.mask a = self.arange(10, dtype=float_) a[-1] = self.masked x *= a xm *= a assert self.allequal(x, y*a) assert self.allequal(xm, y*a) assert self.allequal(xm.mask, self.mask_or(m, a.mask)) x = self.arange(10, dtype=float_) xm = self.arange(10, dtype=float_) xm[2] = self.masked m = xm.mask a = self.arange(10, dtype=float_) a[-1] = self.masked x /= a xm /= a #---------------------------------- def test_7(self): "Tests ufunc" d = (self.array([1.0, 0, -1, pi/2]*2, mask=[0, 1]+[0]*6), self.array([1.0, 0, -1, pi/2]*2, mask=[1, 0]+[0]*6),) for f in ['sqrt', 'log', 'log10', 'exp', 'conjugate', # 'sin', 'cos', 'tan', # 'arcsin', 'arccos', 'arctan', # 'sinh', 'cosh', 'tanh', # 'arcsinh', # 'arccosh', # 'arctanh', # 'absolute', 'fabs', 'negative', # # 'nonzero', 'around', # 'floor', 'ceil', # # 'sometrue', 'alltrue', # 'logical_not', # 'add', 'subtract', 'multiply', # 'divide', 'true_divide', 'floor_divide', # 'remainder', 'fmod', 'hypot', 'arctan2', # 'equal', 'not_equal', 'less_equal', 'greater_equal', # 'less', 'greater', # 'logical_and', 'logical_or', 'logical_xor', ]: #print f try: uf = getattr(self.umath, f) except AttributeError: uf = getattr(fromnumeric, f) mf = getattr(self.module, f) args = d[:uf.nin] ur = uf(*args) mr = mf(*args) self.assert_array_equal(ur.filled(0), mr.filled(0), f) self.assert_array_equal(ur._mask, mr._mask) #---------------------------------- def test_99(self): # test average ott = self.array([0., 1., 2., 3.], mask=[1, 0, 0, 0]) self.assert_array_equal(2.0, self.average(ott, axis=0)) self.assert_array_equal(2.0, self.average(ott, weights=[1., 1., 2., 1.])) result, wts = self.average(ott, weights=[1., 1., 2., 1.], returned=1) self.assert_array_equal(2.0, result) assert(wts == 4.0) ott[:] = self.masked assert(self.average(ott, axis=0) is self.masked) ott = self.array([0., 1., 2., 3.], mask=[1, 0, 0, 0]) ott = ott.reshape(2, 2) ott[:, 1] = self.masked self.assert_array_equal(self.average(ott, axis=0), [2.0, 0.0]) assert(self.average(ott, axis=1)[0] is self.masked) self.assert_array_equal([2., 0.], self.average(ott, axis=0)) result, wts = self.average(ott, axis=0, returned=1) self.assert_array_equal(wts, [1., 0.]) w1 = [0, 1, 1, 1, 1, 0] w2 = [[0, 1, 1, 1, 1, 0], [1, 0, 0, 0, 0, 1]] x = self.arange(6) self.assert_array_equal(self.average(x, axis=0), 2.5) self.assert_array_equal(self.average(x, axis=0, weights=w1), 2.5) y = self.array([self.arange(6), 2.0*self.arange(6)]) self.assert_array_equal(self.average(y, None), np.add.reduce(np.arange(6))*3./12.) self.assert_array_equal(self.average(y, axis=0), np.arange(6) * 3./2.) self.assert_array_equal(self.average(y, axis=1), [self.average(x, axis=0), self.average(x, axis=0) * 2.0]) self.assert_array_equal(self.average(y, None, weights=w2), 20./6.) self.assert_array_equal(self.average(y, axis=0, weights=w2), [0., 1., 2., 3., 4., 10.]) self.assert_array_equal(self.average(y, axis=1), [self.average(x, axis=0), self.average(x, axis=0) * 2.0]) m1 = self.zeros(6) m2 = [0, 0, 1, 1, 0, 0] m3 = [[0, 0, 1, 1, 0, 0], [0, 1, 1, 1, 1, 0]] m4 = self.ones(6) m5 = [0, 1, 1, 1, 1, 1] self.assert_array_equal(self.average(self.masked_array(x, m1), axis=0), 2.5) self.assert_array_equal(self.average(self.masked_array(x, m2), axis=0), 2.5) # assert(self.average(masked_array(x, m4),axis=0) is masked) self.assert_array_equal(self.average(self.masked_array(x, m5), axis=0), 0.0) self.assert_array_equal(self.count(self.average(self.masked_array(x, m4), axis=0)), 0) z = self.masked_array(y, m3) self.assert_array_equal(self.average(z, None), 20./6.) self.assert_array_equal(self.average(z, axis=0), [0., 1., 99., 99., 4.0, 7.5]) self.assert_array_equal(self.average(z, axis=1), [2.5, 5.0]) self.assert_array_equal(self.average(z, axis=0, weights=w2), [0., 1., 99., 99., 4.0, 10.0]) #------------------------ def test_A(self): x = self.arange(24) y = np.arange(24) x[5:6] = self.masked x = x.reshape(2, 3, 4) ################################################################################ if __name__ == '__main__': setup_base = "from __main__ import moduletester \n"\ "import numpy\n" \ "tester = moduletester(module)\n" # setup_new = "import np.ma.core_ini as module\n"+setup_base setup_cur = "import np.ma.core as module\n"+setup_base # setup_alt = "import np.ma.core_alt as module\n"+setup_base # setup_tmp = "import np.ma.core_tmp as module\n"+setup_base (nrepeat, nloop) = (10, 10) if 1: for i in range(1, 8): func = 'tester.test_%i()' % i # new = timeit.Timer(func, setup_new).repeat(nrepeat, nloop*10) cur = timeit.Timer(func, setup_cur).repeat(nrepeat, nloop*10) # alt = timeit.Timer(func, setup_alt).repeat(nrepeat, nloop*10) # tmp = timeit.Timer(func, setup_tmp).repeat(nrepeat, nloop*10) # new = np.sort(new) cur = np.sort(cur) # alt = np.sort(alt) # tmp = np.sort(tmp) print("#%i" % i +50*'.') print(eval("moduletester.test_%i.__doc__" % i)) # print "core_ini : %.3f - %.3f" % (new[0], new[1]) print("core_current : %.3f - %.3f" % (cur[0], cur[1])) # print "core_alt : %.3f - %.3f" % (alt[0], alt[1]) # print "core_tmp : %.3f - %.3f" % (tmp[0], tmp[1]) numpy-1.8.2/numpy/ma/version.py0000664000175100017510000000057412370216242017635 0ustar vagrantvagrant00000000000000"""Version number """ from __future__ import division, absolute_import, print_function version = '1.00' release = False if not release: from . import core from . import extras revision = [core.__revision__.split(':')[-1][:-1].strip(), extras.__revision__.split(':')[-1][:-1].strip(),] version += '.dev%04i' % max([int(rev) for rev in revision]) numpy-1.8.2/numpy/dual.py0000664000175100017510000000351012370216242016471 0ustar vagrantvagrant00000000000000""" Aliases for functions which may be accelerated by Scipy. Scipy_ can be built to use accelerated or otherwise improved libraries for FFTs, linear algebra, and special functions. This module allows developers to transparently support these accelerated functions when scipy is available but still support users who have only installed Numpy. .. _Scipy : http://www.scipy.org """ from __future__ import division, absolute_import, print_function # This module should be used for functions both in numpy and scipy if # you want to use the numpy version if available but the scipy version # otherwise. # Usage --- from numpy.dual import fft, inv __all__ = ['fft', 'ifft', 'fftn', 'ifftn', 'fft2', 'ifft2', 'norm', 'inv', 'svd', 'solve', 'det', 'eig', 'eigvals', 'eigh', 'eigvalsh', 'lstsq', 'pinv', 'cholesky', 'i0'] import numpy.linalg as linpkg import numpy.fft as fftpkg from numpy.lib import i0 import sys fft = fftpkg.fft ifft = fftpkg.ifft fftn = fftpkg.fftn ifftn = fftpkg.ifftn fft2 = fftpkg.fft2 ifft2 = fftpkg.ifft2 norm = linpkg.norm inv = linpkg.inv svd = linpkg.svd solve = linpkg.solve det = linpkg.det eig = linpkg.eig eigvals = linpkg.eigvals eigh = linpkg.eigh eigvalsh = linpkg.eigvalsh lstsq = linpkg.lstsq pinv = linpkg.pinv cholesky = linpkg.cholesky _restore_dict = {} def register_func(name, func): if name not in __all__: raise ValueError("%s not a dual function." % name) f = sys._getframe(0).f_globals _restore_dict[name] = f[name] f[name] = func def restore_func(name): if name not in __all__: raise ValueError("%s not a dual function." % name) try: val = _restore_dict[name] except KeyError: return else: sys._getframe(0).f_globals[name] = val def restore_all(): for name in _restore_dict.keys(): restore_func(name) numpy-1.8.2/numpy/random/0000775000175100017510000000000012371375430016461 5ustar vagrantvagrant00000000000000numpy-1.8.2/numpy/random/mtrand/0000775000175100017510000000000012371375430017746 5ustar vagrantvagrant00000000000000numpy-1.8.2/numpy/random/mtrand/Python.pxi0000664000175100017510000000317512370216242021751 0ustar vagrantvagrant00000000000000# :Author: Robert Kern # :Copyright: 2004, Enthought, Inc. # :License: BSD Style cdef extern from "Python.h": # Not part of the Python API, but we might as well define it here. # Note that the exact type doesn't actually matter for Pyrex. ctypedef int size_t # String API char* PyString_AsString(object string) char* PyString_AS_STRING(object string) object PyString_FromString(char* c_string) object PyString_FromStringAndSize(char* c_string, int length) # Float API double PyFloat_AsDouble(object ob) long PyInt_AsLong(object ob) # Memory API void* PyMem_Malloc(size_t n) void* PyMem_Realloc(void* buf, size_t n) void PyMem_Free(void* buf) void Py_DECREF(object obj) void Py_XDECREF(object obj) void Py_INCREF(object obj) void Py_XINCREF(object obj) # CObject API # If this is uncommented it needs to be fixed to use PyCapsule # for Python >= 3.0 # # ctypedef void (*destructor1)(void* cobj) # ctypedef void (*destructor2)(void* cobj, void* desc) # int PyCObject_Check(object p) # object PyCObject_FromVoidPtr(void* cobj, destructor1 destr) # object PyCObject_FromVoidPtrAndDesc(void* cobj, void* desc, # destructor2 destr) # void* PyCObject_AsVoidPtr(object self) # void* PyCObject_GetDesc(object self) # int PyCObject_SetVoidPtr(object self, void* cobj) # TypeCheck API int PyFloat_Check(object obj) int PyInt_Check(object obj) # Error API int PyErr_Occurred() void PyErr_Clear() cdef extern from "string.h": void *memcpy(void *s1, void *s2, int n) cdef extern from "math.h": double fabs(double x) numpy-1.8.2/numpy/random/mtrand/mtrand.pyx0000664000175100017510000047762712370216243022017 0ustar vagrantvagrant00000000000000# mtrand.pyx -- A Pyrex wrapper of Jean-Sebastien Roy's RandomKit # # Copyright 2005 Robert Kern (robert.kern@gmail.com) # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. # IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY # CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, # TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE # SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. include "Python.pxi" include "numpy.pxd" cdef extern from "math.h": double exp(double x) double log(double x) double floor(double x) double sin(double x) double cos(double x) cdef extern from "mtrand_py_helper.h": object empty_py_bytes(npy_intp length, void **bytes) cdef extern from "randomkit.h": ctypedef struct rk_state: unsigned long key[624] int pos int has_gauss double gauss ctypedef enum rk_error: RK_NOERR = 0 RK_ENODEV = 1 RK_ERR_MAX = 2 char *rk_strerror[2] # 0xFFFFFFFFUL unsigned long RK_MAX 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) 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) 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) cdef extern from "initarray.h": void init_by_array(rk_state *self, unsigned long *init_key, npy_intp key_length) # Initialize numpy import_array() import numpy as np import operator cdef object cont0_array(rk_state *state, rk_cont0 func, object size): cdef double *array_data cdef ndarray array "arrayObject" cdef npy_intp length cdef npy_intp i if size is None: return func(state) else: array = np.empty(size, np.float64) length = PyArray_SIZE(array) array_data = PyArray_DATA(array) 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 double *array_data cdef ndarray array "arrayObject" cdef npy_intp length cdef npy_intp i if size is None: return func(state, a) else: array = np.empty(size, np.float64) length = PyArray_SIZE(array) array_data = PyArray_DATA(array) 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 double *array_data cdef double *oa_data cdef ndarray array "arrayObject" cdef npy_intp length cdef npy_intp i cdef flatiter itera cdef broadcast multi if size is None: array = PyArray_SimpleNew(PyArray_NDIM(oa), PyArray_DIMS(oa) , NPY_DOUBLE) length = PyArray_SIZE(array) array_data = PyArray_DATA(array) itera = PyArray_IterNew(oa) for i from 0 <= i < length: array_data[i] = func(state, ((itera.dataptr))[0]) PyArray_ITER_NEXT(itera) else: array = np.empty(size, np.float64) array_data = PyArray_DATA(array) multi = PyArray_MultiIterNew(2, array, oa) if (multi.size != PyArray_SIZE(array)): raise ValueError("size is not compatible with inputs") for i from 0 <= i < multi.size: oa_data = 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): cdef double *array_data cdef ndarray array "arrayObject" cdef npy_intp length cdef npy_intp i if size is None: return func(state, a, b) else: array = np.empty(size, np.float64) length = PyArray_SIZE(array) array_data = PyArray_DATA(array) 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): cdef double *array_data cdef double *oa_data cdef double *ob_data cdef ndarray array "arrayObject" cdef npy_intp length cdef npy_intp i cdef broadcast multi if size is None: multi = PyArray_MultiIterNew(2, oa, ob) array = PyArray_SimpleNew(multi.nd, multi.dimensions, NPY_DOUBLE) array_data = PyArray_DATA(array) for i from 0 <= i < multi.size: oa_data = PyArray_MultiIter_DATA(multi, 0) ob_data = PyArray_MultiIter_DATA(multi, 1) array_data[i] = func(state, oa_data[0], ob_data[0]) PyArray_MultiIter_NEXT(multi) else: array = np.empty(size, np.float64) array_data = PyArray_DATA(array) multi = PyArray_MultiIterNew(3, array, oa, ob) if (multi.size != PyArray_SIZE(array)): raise ValueError("size is not compatible with inputs") for i from 0 <= i < multi.size: oa_data = PyArray_MultiIter_DATA(multi, 1) ob_data = 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): cdef double *array_data cdef ndarray array "arrayObject" cdef npy_intp length cdef npy_intp i if size is None: return func(state, a, b, c) else: array = np.empty(size, np.float64) length = PyArray_SIZE(array) array_data = PyArray_DATA(array) 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 double *array_data cdef double *oa_data cdef double *ob_data cdef double *oc_data cdef ndarray array "arrayObject" cdef npy_intp length cdef npy_intp i cdef broadcast multi if size is None: multi = PyArray_MultiIterNew(3, oa, ob, oc) array = PyArray_SimpleNew(multi.nd, multi.dimensions, NPY_DOUBLE) array_data = PyArray_DATA(array) for i from 0 <= i < multi.size: oa_data = PyArray_MultiIter_DATA(multi, 0) ob_data = PyArray_MultiIter_DATA(multi, 1) oc_data = 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 = np.empty(size, np.float64) array_data = PyArray_DATA(array) multi = PyArray_MultiIterNew(4, array, oa, ob, oc) if (multi.size != PyArray_SIZE(array)): raise ValueError("size is not compatible with inputs") for i from 0 <= i < multi.size: oa_data = PyArray_MultiIter_DATA(multi, 1) ob_data = PyArray_MultiIter_DATA(multi, 2) oc_data = 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 long *array_data cdef ndarray array "arrayObject" cdef npy_intp length cdef npy_intp i if size is None: return func(state) else: array = np.empty(size, int) length = PyArray_SIZE(array) array_data = PyArray_DATA(array) 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 long *array_data cdef ndarray array "arrayObject" cdef npy_intp length cdef npy_intp i if size is None: return func(state, n, p) else: array = np.empty(size, int) length = PyArray_SIZE(array) array_data = PyArray_DATA(array) 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 long *array_data cdef ndarray array "arrayObject" cdef npy_intp length cdef npy_intp i cdef double *op_data cdef long *on_data cdef broadcast multi if size is None: multi = PyArray_MultiIterNew(2, on, op) array = PyArray_SimpleNew(multi.nd, multi.dimensions, NPY_LONG) array_data = PyArray_DATA(array) for i from 0 <= i < multi.size: on_data = PyArray_MultiIter_DATA(multi, 0) op_data = PyArray_MultiIter_DATA(multi, 1) array_data[i] = func(state, on_data[0], op_data[0]) PyArray_MultiIter_NEXT(multi) else: array = np.empty(size, int) array_data = PyArray_DATA(array) multi = PyArray_MultiIterNew(3, array, on, op) if (multi.size != PyArray_SIZE(array)): raise ValueError("size is not compatible with inputs") for i from 0 <= i < multi.size: on_data = PyArray_MultiIter_DATA(multi, 1) op_data = 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 long *array_data cdef ndarray array "arrayObject" cdef npy_intp length cdef npy_intp i if size is None: return func(state, n, p) else: array = np.empty(size, int) length = PyArray_SIZE(array) array_data = PyArray_DATA(array) 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 long *array_data cdef ndarray array "arrayObject" cdef npy_intp length cdef npy_intp i cdef double *op_data cdef double *on_data cdef broadcast multi if size is None: multi = PyArray_MultiIterNew(2, on, op) array = PyArray_SimpleNew(multi.nd, multi.dimensions, NPY_LONG) array_data = PyArray_DATA(array) for i from 0 <= i < multi.size: on_data = PyArray_MultiIter_DATA(multi, 0) op_data = PyArray_MultiIter_DATA(multi, 1) array_data[i] = func(state, on_data[0], op_data[0]) PyArray_MultiIter_NEXT(multi) else: array = np.empty(size, int) array_data = PyArray_DATA(array) multi = PyArray_MultiIterNew(3, array, on, op) if (multi.size != PyArray_SIZE(array)): raise ValueError("size is not compatible with inputs") for i from 0 <= i < multi.size: on_data = PyArray_MultiIter_DATA(multi, 1) op_data = 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): cdef long *array_data cdef ndarray array "arrayObject" cdef npy_intp length cdef npy_intp i if size is None: return func(state, n, m, N) else: array = np.empty(size, int) length = PyArray_SIZE(array) array_data = PyArray_DATA(array) 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): cdef long *array_data cdef long *on_data cdef long *om_data cdef long *oN_data cdef ndarray array "arrayObject" cdef npy_intp length cdef npy_intp i cdef broadcast multi if size is None: multi = PyArray_MultiIterNew(3, on, om, oN) array = PyArray_SimpleNew(multi.nd, multi.dimensions, NPY_LONG) array_data = PyArray_DATA(array) for i from 0 <= i < multi.size: on_data = PyArray_MultiIter_DATA(multi, 0) om_data = PyArray_MultiIter_DATA(multi, 1) oN_data = 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 = np.empty(size, int) array_data = PyArray_DATA(array) multi = PyArray_MultiIterNew(4, array, on, om, oN) if (multi.size != PyArray_SIZE(array)): raise ValueError("size is not compatible with inputs") for i from 0 <= i < multi.size: on_data = PyArray_MultiIter_DATA(multi, 1) om_data = PyArray_MultiIter_DATA(multi, 2) oN_data = 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 long *array_data cdef ndarray array "arrayObject" cdef npy_intp length cdef npy_intp i if size is None: return func(state, a) else: array = np.empty(size, int) length = PyArray_SIZE(array) array_data = PyArray_DATA(array) 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 long *array_data cdef double *oa_data cdef ndarray array "arrayObject" cdef npy_intp length cdef npy_intp i cdef broadcast multi cdef flatiter itera if size is None: array = PyArray_SimpleNew(PyArray_NDIM(oa), PyArray_DIMS(oa), NPY_LONG) length = PyArray_SIZE(array) array_data = PyArray_DATA(array) itera = PyArray_IterNew(oa) for i from 0 <= i < length: array_data[i] = func(state, ((itera.dataptr))[0]) PyArray_ITER_NEXT(itera) else: array = np.empty(size, int) array_data = PyArray_DATA(array) multi = PyArray_MultiIterNew(2, array, oa) if (multi.size != PyArray_SIZE(array)): raise ValueError("size is not compatible with inputs") for i from 0 <= i < multi.size: oa_data = 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): cdef double c, y, t, sum cdef npy_intp i sum = darr[0] c = 0.0 for i from 1 <= i < n: y = darr[i] - c t = sum + y c = (t-sum) - y 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) Container for the Mersenne Twister pseudo-random number generator. `RandomState` exposes a number of methods for generating random numbers drawn from a variety of probability distributions. In addition to the distribution-specific arguments, each method takes a keyword argument `size` that defaults to ``None``. If `size` is ``None``, then a single value is generated and returned. If `size` is an integer, then a 1-D array filled with generated values is returned. If `size` is a tuple, then an array with that shape is filled and returned. Parameters ---------- seed : {None, int, array_like}, optional Random seed initializing the pseudo-random number generator. Can be an integer, an array (or other sequence) of integers of any length, or ``None`` (the default). If `seed` is ``None``, then `RandomState` will try to read data from ``/dev/urandom`` (or the Windows analogue) if available or seed from the clock otherwise. Notes ----- The Python stdlib module "random" also contains a Mersenne Twister pseudo-random number generator with a number of methods that are similar to the ones available in `RandomState`. `RandomState`, besides being NumPy-aware, has the advantage that it provides a much larger number of probability distributions to choose from. """ cdef rk_state *internal_state poisson_lam_max = np.iinfo('l').max - np.sqrt(np.iinfo('l').max)*10 def __init__(self, seed=None): self.internal_state = PyMem_Malloc(sizeof(rk_state)) self.seed(seed) def __dealloc__(self): if self.internal_state != NULL: PyMem_Free(self.internal_state) self.internal_state = NULL def seed(self, seed=None): """ seed(seed=None) Seed the generator. This method is called when `RandomState` is initialized. It can be called again to re-seed the generator. For details, see `RandomState`. Parameters ---------- seed : int or array_like, optional Seed for `RandomState`. See Also -------- RandomState """ cdef rk_error errcode cdef ndarray obj "arrayObject_obj" try: if seed is None: errcode = rk_randomseed(self.internal_state) else: rk_seed(operator.index(seed), self.internal_state) except TypeError: obj = PyArray_ContiguousFromObject(seed, NPY_LONG, 1, 1) init_by_array(self.internal_state, PyArray_DATA(obj), PyArray_DIM(obj, 0)) def get_state(self): """ get_state() Return a tuple representing the internal state of the generator. For more details, see `set_state`. Returns ------- out : tuple(str, ndarray of 624 uints, int, int, float) The returned tuple has the following items: 1. the string 'MT19937'. 2. a 1-D array of 624 unsigned integer keys. 3. an integer ``pos``. 4. an integer ``has_gauss``. 5. a float ``cached_gaussian``. See Also -------- set_state Notes ----- `set_state` and `get_state` are not needed to work with any of the random distributions in NumPy. If the internal state is manually altered, the user should know exactly what he/she is doing. """ cdef ndarray state "arrayObject_state" state = np.empty(624, np.uint) memcpy(PyArray_DATA(state), (self.internal_state.key), 624*sizeof(long)) state = 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): """ set_state(state) Set the internal state of the generator from a tuple. For use if one has reason to manually (re-)set the internal state of the "Mersenne Twister"[1]_ pseudo-random number generating algorithm. Parameters ---------- state : tuple(str, ndarray of 624 uints, int, int, float) The `state` tuple has the following items: 1. the string 'MT19937', specifying the Mersenne Twister algorithm. 2. a 1-D array of 624 unsigned integers ``keys``. 3. an integer ``pos``. 4. an integer ``has_gauss``. 5. a float ``cached_gaussian``. Returns ------- out : None Returns 'None' on success. See Also -------- get_state Notes ----- `set_state` and `get_state` are not needed to work with any of the random distributions in NumPy. If the internal state is manually altered, the user should know exactly what he/she is doing. For backwards compatibility, the form (str, array of 624 uints, int) is also accepted although it is missing some information about the cached Gaussian value: ``state = ('MT19937', keys, pos)``. References ---------- .. [1] M. Matsumoto and T. Nishimura, "Mersenne Twister: A 623-dimensionally equidistributed uniform pseudorandom number generator," *ACM Trans. on Modeling and Computer Simulation*, Vol. 8, No. 1, pp. 3-30, Jan. 1998. """ cdef ndarray obj "arrayObject_obj" cdef int pos algorithm_name = state[0] if algorithm_name != 'MT19937': raise ValueError("algorithm must be 'MT19937'") key, pos = state[1:3] if len(state) == 3: has_gauss = 0 cached_gaussian = 0.0 else: has_gauss, cached_gaussian = state[3:5] try: obj = PyArray_ContiguousFromObject(key, NPY_ULONG, 1, 1) except TypeError: # compatibility -- could be an older pickle obj = PyArray_ContiguousFromObject(key, NPY_LONG, 1, 1) if PyArray_DIM(obj, 0) != 624: raise ValueError("state must be 624 longs") memcpy((self.internal_state.key), PyArray_DATA(obj), 624*sizeof(long)) self.internal_state.pos = pos self.internal_state.has_gauss = has_gauss self.internal_state.gauss = cached_gaussian # Pickling support: def __getstate__(self): return self.get_state() def __setstate__(self, state): self.set_state(state) def __reduce__(self): return (np.random.__RandomState_ctor, (), self.get_state()) # Basic distributions: def random_sample(self, size=None): """ random_sample(size=None) Return random floats in the half-open interval [0.0, 1.0). Results are from the "continuous uniform" distribution over the stated interval. To sample :math:`Unif[a, b), b > a` multiply the output of `random_sample` by `(b-a)` and add `a`:: (b - a) * random_sample() + a 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. Returns ------- out : float or ndarray of floats Array of random floats of shape `size` (unless ``size=None``, in which case a single float is returned). Examples -------- >>> np.random.random_sample() 0.47108547995356098 >>> type(np.random.random_sample()) >>> np.random.random_sample((5,)) array([ 0.30220482, 0.86820401, 0.1654503 , 0.11659149, 0.54323428]) Three-by-two array of random numbers from [-5, 0): >>> 5 * np.random.random_sample((3, 2)) - 5 array([[-3.99149989, -0.52338984], [-2.99091858, -0.79479508], [-1.23204345, -1.75224494]]) """ return cont0_array(self.internal_state, rk_double, size) def tomaxint(self, size=None): """ tomaxint(size=None) Random integers between 0 and ``sys.maxint``, inclusive. Return a sample of uniformly distributed random integers in the interval [0, ``sys.maxint``]. 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. Returns ------- out : ndarray Drawn samples, with shape `size`. See Also -------- randint : Uniform sampling over a given half-open interval of integers. random_integers : Uniform sampling over a given closed interval of integers. Examples -------- >>> RS = np.random.mtrand.RandomState() # need a RandomState object >>> RS.tomaxint((2,2,2)) array([[[1170048599, 1600360186], [ 739731006, 1947757578]], [[1871712945, 752307660], [1601631370, 1479324245]]]) >>> import sys >>> sys.maxint 2147483647 >>> RS.tomaxint((2,2,2)) < sys.maxint array([[[ True, True], [ True, True]], [[ True, True], [ True, True]]], dtype=bool) """ return disc0_array(self.internal_state, rk_long, size) def randint(self, low, high=None, size=None): """ randint(low, high=None, size=None) Return random integers from `low` (inclusive) to `high` (exclusive). Return random integers from the "discrete uniform" distribution in the "half-open" interval [`low`, `high`). If `high` is None (the default), then results are from [0, `low`). Parameters ---------- low : int Lowest (signed) integer to be drawn from the distribution (unless ``high=None``, in which case this parameter is the *highest* such integer). high : int, optional 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. Returns ------- out : int or ndarray of ints `size`-shaped array of random integers from the appropriate distribution, or a single such random int if `size` not provided. See Also -------- random.random_integers : similar to `randint`, only for the closed interval [`low`, `high`], and 1 is the lowest value if `high` is omitted. In particular, this other one is the one to use to generate uniformly distributed discrete non-integers. Examples -------- >>> np.random.randint(2, size=10) array([1, 0, 0, 0, 1, 1, 0, 0, 1, 0]) >>> np.random.randint(1, size=10) array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) Generate a 2 x 4 array of ints between 0 and 4, inclusive: >>> np.random.randint(5, size=(2, 4)) array([[4, 0, 2, 1], [3, 2, 2, 0]]) """ cdef long lo, hi, rv cdef unsigned long diff cdef long *array_data cdef ndarray array "arrayObject" cdef npy_intp length cdef npy_intp i if high is None: lo = 0 hi = low else: lo = low hi = high if lo >= hi : raise ValueError("low >= high") diff = hi - lo - 1UL if size is None: rv = lo + rk_interval(diff, self. internal_state) return rv else: array = np.empty(size, int) length = PyArray_SIZE(array) array_data = PyArray_DATA(array) for i from 0 <= i < length: rv = lo + rk_interval(diff, self. internal_state) array_data[i] = rv return array def bytes(self, npy_intp length): """ bytes(length) Return random bytes. Parameters ---------- length : int Number of random bytes. Returns ------- out : str String of length `length`. Examples -------- >>> np.random.bytes(10) ' eh\\x85\\x022SZ\\xbf\\xa4' #random """ cdef void *bytes bytestring = empty_py_bytes(length, &bytes) rk_fill(bytes, length, self.internal_state) return bytestring def choice(self, a, size=None, replace=True, p=None): """ choice(a, size=None, replace=True, p=None) Generates a random sample from a given 1-D array .. versionadded:: 1.7.0 Parameters ----------- a : 1-D array-like or int 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. 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 entries in a. Returns -------- samples : 1-D ndarray, shape (size,) The generated random samples Raises ------- ValueError If a is an int and less than zero, if a or p are not 1-dimensional, if a is an array-like of size 0, if p is not a vector of probabilities, if a and p have different lengths, or if replace=False and the sample size is greater than the population size See Also --------- randint, shuffle, permutation Examples --------- Generate a uniform random sample from np.arange(5) of size 3: >>> np.random.choice(5, 3) array([0, 3, 4]) >>> #This is equivalent to np.random.randint(0,5,3) Generate a non-uniform random sample from np.arange(5) of size 3: >>> np.random.choice(5, 3, p=[0.1, 0, 0.3, 0.6, 0]) array([3, 3, 0]) Generate a uniform random sample from np.arange(5) of size 3 without replacement: >>> np.random.choice(5, 3, replace=False) array([3,1,0]) >>> #This is equivalent to np.random.shuffle(np.arange(5))[:3] Generate a non-uniform random sample from np.arange(5) of size 3 without replacement: >>> np.random.choice(5, 3, replace=False, p=[0.1, 0, 0.3, 0.6, 0]) array([2, 3, 0]) Any of the above can be repeated with an arbitrary array-like instead of just integers. For instance: >>> aa_milne_arr = ['pooh', 'rabbit', 'piglet', 'Christopher'] >>> np.random.choice(aa_milne_arr, 5, p=[0.5, 0.1, 0.1, 0.3]) array(['pooh', 'pooh', 'pooh', 'Christopher', 'piglet'], dtype='|S11') """ # Format and Verify input 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()) 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: 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") 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: 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") shape = size if shape is not None: size = np.prod(shape, dtype=np.intp) else: size = 1 # Actual sampling if replace: if None != p: 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 else: 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'") 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() 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: 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) unique_indices.sort() new = new.take(unique_indices) flat_found[n_uniq:n_uniq + new.size] = new n_uniq += new.size idx = found else: idx = self.permutation(pop_size)[:size] if shape is not None: 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) #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: # 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 # scalar and not an array. So this makes sure the result is an # 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 return a[idx] def uniform(self, low=0.0, high=1.0, size=None): """ uniform(low=0.0, high=1.0, size=1) Draw samples from a uniform distribution. Samples are uniformly distributed over the half-open interval ``[low, high)`` (includes low, but excludes high). In other words, any value within the given interval is equally likely to be drawn by `uniform`. Parameters ---------- low : float, optional Lower boundary of the output interval. All values generated will be greater than or equal to low. The default value is 0. high : float 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. Returns ------- out : ndarray Drawn samples, with shape `size`. See Also -------- randint : Discrete uniform distribution, yielding integers. random_integers : Discrete uniform distribution over the closed interval ``[low, high]``. random_sample : Floats uniformly distributed over ``[0, 1)``. random : Alias for `random_sample`. rand : Convenience function that accepts dimensions as input, e.g., ``rand(2,2)`` would generate a 2-by-2 array of floats, uniformly distributed over ``[0, 1)``. Notes ----- The probability density function of the uniform distribution is .. math:: p(x) = \\frac{1}{b - a} anywhere within the interval ``[a, b)``, and zero elsewhere. Examples -------- Draw samples from the distribution: >>> s = np.random.uniform(-1,0,1000) All values are within the given interval: >>> np.all(s >= -1) True >>> np.all(s < 0) True Display the histogram of the samples, along with the probability density function: >>> import matplotlib.pyplot as plt >>> count, bins, ignored = plt.hist(s, 15, normed=True) >>> plt.plot(bins, np.ones_like(bins), linewidth=2, color='r') >>> plt.show() """ cdef ndarray olow, ohigh, odiff cdef double flow, fhigh cdef object temp 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() olow = PyArray_FROM_OTF(low, NPY_DOUBLE, NPY_ARRAY_ALIGNED) ohigh = 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 = PyArray_EnsureArray(temp) return cont2_array(self.internal_state, rk_uniform, size, olow, odiff) def rand(self, *args): """ rand(d0, d1, ..., dn) Random values in a given shape. Create an array of the given shape and propagate it with random samples from a uniform distribution over ``[0, 1)``. Parameters ---------- d0, d1, ..., dn : int, optional The dimensions of the returned array, should all be positive. If no argument is given a single Python float is returned. Returns ------- out : ndarray, shape ``(d0, d1, ..., dn)`` Random values. See Also -------- random Notes ----- This is a convenience function. If you want an interface that takes a shape-tuple as the first argument, refer to np.random.random_sample . Examples -------- >>> np.random.rand(3,2) array([[ 0.14022471, 0.96360618], #random [ 0.37601032, 0.25528411], #random [ 0.49313049, 0.94909878]]) #random """ if len(args) == 0: return self.random_sample() else: return self.random_sample(size=args) def randn(self, *args): """ randn(d0, d1, ..., dn) Return a sample (or samples) from the "standard normal" distribution. If positive, int_like or int-convertible arguments are provided, `randn` generates an array of shape ``(d0, d1, ..., dn)``, filled with random floats sampled from a univariate "normal" (Gaussian) distribution of mean 0 and variance 1 (if any of the :math:`d_i` are floats, they are first converted to integers by truncation). A single float randomly sampled from the distribution is returned if no argument is provided. This is a convenience function. If you want an interface that takes a tuple as the first argument, use `numpy.random.standard_normal` instead. Parameters ---------- d0, d1, ..., dn : int, optional The dimensions of the returned array, should be all positive. If no argument is given a single Python float is returned. Returns ------- Z : ndarray or float A ``(d0, d1, ..., dn)``-shaped array of floating-point samples from the standard normal distribution, or a single such float if no parameters were supplied. See Also -------- random.standard_normal : Similar, but takes a tuple as its argument. Notes ----- For random samples from :math:`N(\\mu, \\sigma^2)`, use: ``sigma * np.random.randn(...) + mu`` Examples -------- >>> np.random.randn() 2.1923875335537315 #random Two-by-four array of samples from N(3, 6.25): >>> 2.5 * np.random.randn(2, 4) + 3 array([[-4.49401501, 4.00950034, -1.81814867, 7.29718677], #random [ 0.39924804, 4.68456316, 4.99394529, 4.84057254]]) #random """ if len(args) == 0: return self.standard_normal() else: return self.standard_normal(args) def random_integers(self, low, high=None, size=None): """ random_integers(low, high=None, size=None) Return random integers between `low` and `high`, inclusive. Return random integers from the "discrete uniform" distribution in the closed interval [`low`, `high`]. If `high` is None (the default), then results are from [1, `low`]. Parameters ---------- low : int Lowest (signed) integer to be drawn from the distribution (unless ``high=None``, in which case this parameter is the *highest* such integer). high : int, optional 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. Returns ------- out : int or ndarray of ints `size`-shaped array of random integers from the appropriate distribution, or a single such random int if `size` not provided. See Also -------- random.randint : Similar to `random_integers`, only for the half-open interval [`low`, `high`), and 0 is the lowest value if `high` is omitted. Notes ----- To sample from N evenly spaced floating-point numbers between a and b, use:: a + (b - a) * (np.random.random_integers(N) - 1) / (N - 1.) Examples -------- >>> np.random.random_integers(5) 4 >>> type(np.random.random_integers(5)) >>> np.random.random_integers(5, size=(3.,2.)) array([[5, 4], [3, 3], [4, 5]]) Choose five random numbers from the set of five evenly-spaced numbers between 0 and 2.5, inclusive (*i.e.*, from the set :math:`{0, 5/8, 10/8, 15/8, 20/8}`): >>> 2.5 * (np.random.random_integers(5, size=(5,)) - 1) / 4. array([ 0.625, 1.25 , 0.625, 0.625, 2.5 ]) Roll two six sided dice 1000 times and sum the results: >>> d1 = np.random.random_integers(1, 6, 1000) >>> d2 = np.random.random_integers(1, 6, 1000) >>> dsums = d1 + d2 Display results as a histogram: >>> import matplotlib.pyplot as plt >>> count, bins, ignored = plt.hist(dsums, 11, normed=True) >>> plt.show() """ if high is None: high = low low = 1 return self.randint(low, high+1, size) # Complicated, continuous distributions: def standard_normal(self, size=None): """ standard_normal(size=None) Returns samples from a Standard Normal distribution (mean=0, stdev=1). Parameters ---------- size : int or tuple of ints, optional Output shape. Default is None, in which case a single value is returned. Returns ------- out : float or ndarray Drawn samples. Examples -------- >>> s = np.random.standard_normal(8000) >>> s array([ 0.6888893 , 0.78096262, -0.89086505, ..., 0.49876311, #random -0.38672696, -0.4685006 ]) #random >>> s.shape (8000,) >>> s = np.random.standard_normal(size=(3, 4, 2)) >>> s.shape (3, 4, 2) """ 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) Draw random samples from a normal (Gaussian) distribution. The probability density function of the normal distribution, first derived by De Moivre and 200 years later by both Gauss and Laplace independently [2]_, is often called the bell curve because of its characteristic shape (see the example below). The normal distributions occurs often in nature. For example, it describes the commonly occurring distribution of samples influenced by a large number of tiny, random disturbances, each with its own unique distribution [2]_. Parameters ---------- loc : float Mean ("centre") of the distribution. scale : float Standard deviation (spread or "width") of the distribution. size : tuple of ints Output shape. If the given shape is, e.g., ``(m, n, k)``, then ``m * n * k`` samples are drawn. See Also -------- scipy.stats.distributions.norm : probability density function, distribution or cumulative density function, etc. Notes ----- The probability density for the Gaussian distribution is .. math:: p(x) = \\frac{1}{\\sqrt{ 2 \\pi \\sigma^2 }} e^{ - \\frac{ (x - \\mu)^2 } {2 \\sigma^2} }, where :math:`\\mu` is the mean and :math:`\\sigma` the standard deviation. The square of the standard deviation, :math:`\\sigma^2`, is called the variance. The function has its peak at the mean, and its "spread" increases with the standard deviation (the function reaches 0.607 times its maximum at :math:`x + \\sigma` and :math:`x - \\sigma` [2]_). This implies that `numpy.random.normal` is more likely to return samples lying close to the mean, rather than those far away. References ---------- .. [1] Wikipedia, "Normal distribution", http://en.wikipedia.org/wiki/Normal_distribution .. [2] P. R. Peebles Jr., "Central Limit Theorem" in "Probability, Random Variables and Random Signal Principles", 4th ed., 2001, pp. 51, 51, 125. Examples -------- Draw samples from the distribution: >>> mu, sigma = 0, 0.1 # mean and standard deviation >>> s = np.random.normal(mu, sigma, 1000) Verify the mean and the variance: >>> abs(mu - np.mean(s)) < 0.01 True >>> abs(sigma - np.std(s, ddof=1)) < 0.01 True Display the histogram of the samples, along with the probability density function: >>> import matplotlib.pyplot as plt >>> count, bins, ignored = plt.hist(s, 30, normed=True) >>> plt.plot(bins, 1/(sigma * np.sqrt(2 * np.pi)) * ... np.exp( - (bins - mu)**2 / (2 * sigma**2) ), ... linewidth=2, color='r') >>> plt.show() """ cdef ndarray oloc, oscale cdef double floc, fscale floc = PyFloat_AsDouble(loc) 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) 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)): raise ValueError("scale <= 0") return cont2_array(self.internal_state, rk_normal, size, oloc, oscale) def beta(self, a, b, size=None): """ beta(a, b, size=None) The Beta distribution over ``[0, 1]``. The Beta distribution is a special case of the Dirichlet distribution, and is related to the Gamma distribution. It has the probability distribution function .. math:: f(x; a,b) = \\frac{1}{B(\\alpha, \\beta)} x^{\\alpha - 1} (1 - x)^{\\beta - 1}, where the normalisation, B, is the beta function, .. math:: B(\\alpha, \\beta) = \\int_0^1 t^{\\alpha - 1} (1 - t)^{\\beta - 1} dt. It is often seen in Bayesian inference and order statistics. Parameters ---------- a : float 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. Returns ------- out : ndarray Array of the given shape, containing values drawn from a Beta distribution. """ cdef ndarray oa, ob cdef double fa, fb fa = PyFloat_AsDouble(a) fb = PyFloat_AsDouble(b) if not PyErr_Occurred(): 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) PyErr_Clear() oa = PyArray_FROM_OTF(a, NPY_DOUBLE, NPY_ARRAY_ALIGNED) ob = 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") 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) Exponential distribution. Its probability density function is .. math:: f(x; \\frac{1}{\\beta}) = \\frac{1}{\\beta} \\exp(-\\frac{x}{\\beta}), for ``x > 0`` and 0 elsewhere. :math:`\\beta` is the scale parameter, which is the inverse of the rate parameter :math:`\\lambda = 1/\\beta`. The rate parameter is an alternative, widely used parameterization of the exponential distribution [3]_. The exponential distribution is a continuous analogue of the geometric distribution. It describes many common situations, such as the size of raindrops measured over many rainstorms [1]_, or the time between page requests to Wikipedia [2]_. Parameters ---------- 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`. References ---------- .. [1] Peyton Z. Peebles Jr., "Probability, Random Variables and Random Signal Principles", 4th ed, 2001, p. 57. .. [2] "Poisson Process", Wikipedia, http://en.wikipedia.org/wiki/Poisson_process .. [3] "Exponential Distribution, Wikipedia, http://en.wikipedia.org/wiki/Exponential_distribution """ cdef ndarray oscale cdef double fscale 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) PyErr_Clear() oscale = 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) def standard_exponential(self, size=None): """ standard_exponential(size=None) Draw samples from the standard exponential distribution. `standard_exponential` is identical to the exponential distribution with a scale parameter of 1. Parameters ---------- size : int or tuple of ints Shape of the output. Returns ------- out : float or ndarray Drawn samples. Examples -------- Output a 3x8000 array: >>> n = np.random.standard_exponential((3, 8000)) """ return cont0_array(self.internal_state, rk_standard_exponential, size) def standard_gamma(self, shape, size=None): """ standard_gamma(shape, size=None) Draw samples from a Standard Gamma distribution. Samples are drawn from a Gamma distribution with specified parameters, shape (sometimes designated "k") and scale=1. Parameters ---------- shape : 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. Returns ------- samples : ndarray or scalar The drawn samples. See Also -------- scipy.stats.distributions.gamma : probability density function, distribution or cumulative density function, etc. Notes ----- The probability density for the Gamma distribution is .. math:: p(x) = x^{k-1}\\frac{e^{-x/\\theta}}{\\theta^k\\Gamma(k)}, where :math:`k` is the shape and :math:`\\theta` the scale, and :math:`\\Gamma` is the Gamma function. The Gamma distribution is often used to model the times to failure of electronic components, and arises naturally in processes for which the waiting times between Poisson distributed events are relevant. References ---------- .. [1] Weisstein, Eric W. "Gamma Distribution." From MathWorld--A Wolfram Web Resource. http://mathworld.wolfram.com/GammaDistribution.html .. [2] Wikipedia, "Gamma-distribution", http://en.wikipedia.org/wiki/Gamma-distribution Examples -------- Draw samples from the distribution: >>> shape, scale = 2., 1. # mean and width >>> s = np.random.standard_gamma(shape, 1000000) Display the histogram of the samples, along with the probability density function: >>> import matplotlib.pyplot as plt >>> import scipy.special as sps >>> count, bins, ignored = plt.hist(s, 50, normed=True) >>> y = bins**(shape-1) * ((np.exp(-bins/scale))/ \\ ... (sps.gamma(shape) * scale**shape)) >>> plt.plot(bins, y, linewidth=2, color='r') >>> plt.show() """ cdef ndarray oshape cdef double fshape 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) PyErr_Clear() oshape = 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) def gamma(self, shape, scale=1.0, size=None): """ gamma(shape, scale=1.0, size=None) Draw samples from a Gamma distribution. Samples are drawn from a Gamma distribution with specified parameters, `shape` (sometimes designated "k") and `scale` (sometimes designated "theta"), where both parameters are > 0. Parameters ---------- shape : scalar > 0 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 Output shape. If the given shape is, e.g., ``(m, n, k)``, then ``m * n * k`` samples are drawn. Returns ------- out : ndarray, float Returns one sample unless `size` parameter is specified. See Also -------- scipy.stats.distributions.gamma : probability density function, distribution or cumulative density function, etc. Notes ----- The probability density for the Gamma distribution is .. math:: p(x) = x^{k-1}\\frac{e^{-x/\\theta}}{\\theta^k\\Gamma(k)}, where :math:`k` is the shape and :math:`\\theta` the scale, and :math:`\\Gamma` is the Gamma function. The Gamma distribution is often used to model the times to failure of electronic components, and arises naturally in processes for which the waiting times between Poisson distributed events are relevant. References ---------- .. [1] Weisstein, Eric W. "Gamma Distribution." From MathWorld--A Wolfram Web Resource. http://mathworld.wolfram.com/GammaDistribution.html .. [2] Wikipedia, "Gamma-distribution", http://en.wikipedia.org/wiki/Gamma-distribution Examples -------- Draw samples from the distribution: >>> shape, scale = 2., 2. # mean and dispersion >>> s = np.random.gamma(shape, scale, 1000) Display the histogram of the samples, along with the probability density function: >>> import matplotlib.pyplot as plt >>> import scipy.special as sps >>> count, bins, ignored = plt.hist(s, 50, normed=True) >>> y = bins**(shape-1)*(np.exp(-bins/scale) / ... (sps.gamma(shape)*scale**shape)) >>> plt.plot(bins, y, linewidth=2, color='r') >>> plt.show() """ cdef ndarray oshape, oscale cdef double fshape, fscale fshape = PyFloat_AsDouble(shape) fscale = PyFloat_AsDouble(scale) if not PyErr_Occurred(): 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) PyErr_Clear() oshape = PyArray_FROM_OTF(shape, NPY_DOUBLE, NPY_ARRAY_ALIGNED) oscale = 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") return cont2_array(self.internal_state, rk_gamma, size, oshape, oscale) def f(self, dfnum, dfden, size=None): """ f(dfnum, dfden, size=None) Draw samples from a F distribution. Samples are drawn from an F distribution with specified parameters, `dfnum` (degrees of freedom in numerator) and `dfden` (degrees of freedom in denominator), where both parameters should be greater than zero. The random variate of the F distribution (also known as the Fisher distribution) is a continuous probability distribution that arises in ANOVA tests, and is the ratio of two chi-square variates. Parameters ---------- dfnum : float 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. Returns ------- samples : {ndarray, scalar} Samples from the Fisher distribution. See Also -------- scipy.stats.distributions.f : probability density function, distribution or cumulative density function, etc. Notes ----- The F statistic is used to compare in-group variances to between-group variances. Calculating the distribution depends on the sampling, and so it is a function of the respective degrees of freedom in the problem. The variable `dfnum` is the number of samples minus one, the between-groups degrees of freedom, while `dfden` is the within-groups degrees of freedom, the sum of the number of samples in each group minus the number of groups. References ---------- .. [1] Glantz, Stanton A. "Primer of Biostatistics.", McGraw-Hill, Fifth Edition, 2002. .. [2] Wikipedia, "F-distribution", http://en.wikipedia.org/wiki/F-distribution Examples -------- An example from Glantz[1], pp 47-40. Two groups, children of diabetics (25 people) and children from people without diabetes (25 controls). Fasting blood glucose was measured, case group had a mean value of 86.1, controls had a mean value of 82.2. Standard deviations were 2.09 and 2.49 respectively. Are these data consistent with the null hypothesis that the parents diabetic status does not affect their children's blood glucose levels? Calculating the F statistic from the data gives a value of 36.01. Draw samples from the distribution: >>> dfnum = 1. # between group degrees of freedom >>> dfden = 48. # within groups degrees of freedom >>> s = np.random.f(dfnum, dfden, 1000) The lower bound for the top 1% of the samples is : >>> sort(s)[-10] 7.61988120985 So there is about a 1% chance that the F statistic will exceed 7.62, the measured value is 36, so the null hypothesis is rejected at the 1% level. """ cdef ndarray odfnum, odfden cdef double fdfnum, fdfden fdfnum = PyFloat_AsDouble(dfnum) fdfden = PyFloat_AsDouble(dfden) if not PyErr_Occurred(): 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) PyErr_Clear() odfnum = PyArray_FROM_OTF(dfnum, NPY_DOUBLE, NPY_ARRAY_ALIGNED) odfden = 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") 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) Draw samples from the noncentral F distribution. Samples are drawn from an F distribution with specified parameters, `dfnum` (degrees of freedom in numerator) and `dfden` (degrees of freedom in denominator), where both parameters > 1. `nonc` is the non-centrality parameter. Parameters ---------- dfnum : int Parameter, should be > 1. dfden : int 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. Returns ------- samples : scalar or ndarray Drawn samples. Notes ----- When calculating the power of an experiment (power = probability of rejecting the null hypothesis when a specific alternative is true) the non-central F statistic becomes important. When the null hypothesis is true, the F statistic follows a central F distribution. When the null hypothesis is not true, then it follows a non-central F statistic. References ---------- Weisstein, Eric W. "Noncentral F-Distribution." From MathWorld--A Wolfram Web Resource. http://mathworld.wolfram.com/NoncentralF-Distribution.html Wikipedia, "Noncentral F distribution", http://en.wikipedia.org/wiki/Noncentral_F-distribution Examples -------- In a study, testing for a specific alternative to the null hypothesis requires use of the Noncentral F distribution. We need to calculate the area in the tail of the distribution that exceeds the value of the F distribution for the null hypothesis. We'll plot the two probability distributions for comparison. >>> dfnum = 3 # between group deg of freedom >>> dfden = 20 # within groups degrees of freedom >>> nonc = 3.0 >>> nc_vals = np.random.noncentral_f(dfnum, dfden, nonc, 1000000) >>> NF = np.histogram(nc_vals, bins=50, normed=True) >>> c_vals = np.random.f(dfnum, dfden, 1000000) >>> F = np.histogram(c_vals, bins=50, normed=True) >>> plt.plot(F[1][1:], F[0]) >>> plt.plot(NF[1][1:], NF[0]) >>> plt.show() """ cdef ndarray odfnum, odfden, ononc cdef double fdfnum, fdfden, fnonc fdfnum = PyFloat_AsDouble(dfnum) fdfden = PyFloat_AsDouble(dfden) fnonc = PyFloat_AsDouble(nonc) if not PyErr_Occurred(): if fdfnum <= 1: raise ValueError("dfnum <= 1") 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, fdfnum, fdfden, fnonc) PyErr_Clear() odfnum = PyArray_FROM_OTF(dfnum, NPY_DOUBLE, NPY_ARRAY_ALIGNED) odfden = PyArray_FROM_OTF(dfden, NPY_DOUBLE, NPY_ARRAY_ALIGNED) ononc = 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)): 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) def chisquare(self, df, size=None): """ chisquare(df, size=None) Draw samples from a chi-square distribution. When `df` independent random variables, each with standard normal distributions (mean 0, variance 1), are squared and summed, the resulting distribution is chi-square (see Notes). This distribution is often used in hypothesis testing. Parameters ---------- df : int Number of degrees of freedom. size : tuple of ints, int, optional Size of the returned array. By default, a scalar is returned. Returns ------- output : ndarray Samples drawn from the distribution, packed in a `size`-shaped array. Raises ------ ValueError When `df` <= 0 or when an inappropriate `size` (e.g. ``size=-1``) is given. Notes ----- The variable obtained by summing the squares of `df` independent, standard normally distributed random variables: .. math:: Q = \\sum_{i=0}^{\\mathtt{df}} X^2_i is chi-square distributed, denoted .. math:: Q \\sim \\chi^2_k. The probability density function of the chi-squared distribution is .. math:: p(x) = \\frac{(1/2)^{k/2}}{\\Gamma(k/2)} x^{k/2 - 1} e^{-x/2}, where :math:`\\Gamma` is the gamma function, .. math:: \\Gamma(x) = \\int_0^{-\\infty} t^{x - 1} e^{-t} dt. References ---------- `NIST/SEMATECH e-Handbook of Statistical Methods `_ Examples -------- >>> np.random.chisquare(2,4) array([ 1.89920014, 9.00867716, 3.13710533, 5.62318272]) """ cdef ndarray odf cdef double fdf 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) PyErr_Clear() odf = 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) def noncentral_chisquare(self, df, nonc, size=None): """ noncentral_chisquare(df, nonc, size=None) Draw samples from a noncentral chi-square distribution. The noncentral :math:`\\chi^2` distribution is a generalisation of the :math:`\\chi^2` distribution. Parameters ---------- df : int Degrees of freedom, should be >= 1. nonc : float Non-centrality, should be > 0. size : int or tuple of ints Shape of the output. Notes ----- The probability density function for the noncentral Chi-square distribution is .. math:: P(x;df,nonc) = \\sum^{\\infty}_{i=0} \\frac{e^{-nonc/2}(nonc/2)^{i}}{i!}P_{Y_{df+2i}}(x), where :math:`Y_{q}` is the Chi-square with q degrees of freedom. In Delhi (2007), it is noted that the noncentral chi-square is useful in bombing and coverage problems, the probability of killing the point target given by the noncentral chi-squared distribution. References ---------- .. [1] Delhi, M.S. Holla, "On a noncentral chi-square distribution in the analysis of weapon systems effectiveness", Metrika, Volume 15, Number 1 / December, 1970. .. [2] Wikipedia, "Noncentral chi-square distribution" http://en.wikipedia.org/wiki/Noncentral_chi-square_distribution Examples -------- Draw values from the distribution and plot the histogram >>> import matplotlib.pyplot as plt >>> values = plt.hist(np.random.noncentral_chisquare(3, 20, 100000), ... bins=200, normed=True) >>> plt.show() Draw values from a noncentral chisquare with very small noncentrality, and compare to a chisquare. >>> plt.figure() >>> values = plt.hist(np.random.noncentral_chisquare(3, .0000001, 100000), ... bins=np.arange(0., 25, .1), normed=True) >>> values2 = plt.hist(np.random.chisquare(3, 100000), ... bins=np.arange(0., 25, .1), normed=True) >>> plt.plot(values[1][0:-1], values[0]-values2[0], 'ob') >>> plt.show() Demonstrate how large values of non-centrality lead to a more symmetric distribution. >>> plt.figure() >>> values = plt.hist(np.random.noncentral_chisquare(3, 20, 100000), ... bins=200, normed=True) >>> plt.show() """ cdef ndarray odf, ononc cdef double fdf, fnonc fdf = PyFloat_AsDouble(df) fnonc = PyFloat_AsDouble(nonc) if not PyErr_Occurred(): if fdf <= 1: raise ValueError("df <= 0") if fnonc <= 0: raise ValueError("nonc <= 0") return cont2_array_sc(self.internal_state, rk_noncentral_chisquare, size, fdf, fnonc) PyErr_Clear() odf = PyArray_FROM_OTF(df, NPY_DOUBLE, NPY_ARRAY_ALIGNED) ononc = 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") return cont2_array(self.internal_state, rk_noncentral_chisquare, size, odf, ononc) def standard_cauchy(self, size=None): """ standard_cauchy(size=None) Standard Cauchy distribution with mode = 0. Also known as the Lorentz distribution. Parameters ---------- size : int or tuple of ints Shape of the output. Returns ------- samples : ndarray or scalar The drawn samples. Notes ----- The probability density function for the full Cauchy distribution is .. math:: P(x; x_0, \\gamma) = \\frac{1}{\\pi \\gamma \\bigl[ 1+ (\\frac{x-x_0}{\\gamma})^2 \\bigr] } and the Standard Cauchy distribution just sets :math:`x_0=0` and :math:`\\gamma=1` The Cauchy distribution arises in the solution to the driven harmonic oscillator problem, and also describes spectral line broadening. It also describes the distribution of values at which a line tilted at a random angle will cut the x axis. When studying hypothesis tests that assume normality, seeing how the tests perform on data from a Cauchy distribution is a good indicator of their sensitivity to a heavy-tailed distribution, since the Cauchy looks very much like a Gaussian distribution, but with heavier tails. References ---------- .. [1] NIST/SEMATECH e-Handbook of Statistical Methods, "Cauchy Distribution", http://www.itl.nist.gov/div898/handbook/eda/section3/eda3663.htm .. [2] Weisstein, Eric W. "Cauchy Distribution." From MathWorld--A Wolfram Web Resource. http://mathworld.wolfram.com/CauchyDistribution.html .. [3] Wikipedia, "Cauchy distribution" http://en.wikipedia.org/wiki/Cauchy_distribution Examples -------- Draw samples and plot the distribution: >>> s = np.random.standard_cauchy(1000000) >>> s = s[(s>-25) & (s<25)] # truncate distribution so it plots well >>> plt.hist(s, bins=100) >>> plt.show() """ return cont0_array(self.internal_state, rk_standard_cauchy, size) def standard_t(self, df, size=None): """ standard_t(df, size=None) Standard Student's t distribution with df degrees of freedom. A special case of the hyperbolic distribution. As `df` gets large, the result resembles that of the standard normal distribution (`standard_normal`). Parameters ---------- 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. Returns ------- samples : ndarray or scalar Drawn samples. Notes ----- The probability density function for the t distribution is .. math:: P(x, df) = \\frac{\\Gamma(\\frac{df+1}{2})}{\\sqrt{\\pi df} \\Gamma(\\frac{df}{2})}\\Bigl( 1+\\frac{x^2}{df} \\Bigr)^{-(df+1)/2} The t test is based on an assumption that the data come from a Normal distribution. The t test provides a way to test whether the sample mean (that is the mean calculated from the data) is a good estimate of the true mean. The derivation of the t-distribution was forst published in 1908 by William Gisset while working for the Guinness Brewery in Dublin. Due to proprietary issues, he had to publish under a pseudonym, and so he used the name Student. References ---------- .. [1] Dalgaard, Peter, "Introductory Statistics With R", Springer, 2002. .. [2] Wikipedia, "Student's t-distribution" http://en.wikipedia.org/wiki/Student's_t-distribution Examples -------- From Dalgaard page 83 [1]_, suppose the daily energy intake for 11 women in Kj is: >>> intake = np.array([5260., 5470, 5640, 6180, 6390, 6515, 6805, 7515, \\ ... 7515, 8230, 8770]) Does their energy intake deviate systematically from the recommended value of 7725 kJ? We have 10 degrees of freedom, so is the sample mean within 95% of the recommended value? >>> s = np.random.standard_t(10, size=100000) >>> np.mean(intake) 6753.636363636364 >>> intake.std(ddof=1) 1142.1232221373727 Calculate the t statistic, setting the ddof parameter to the unbiased value so the divisor in the standard deviation will be degrees of freedom, N-1. >>> t = (np.mean(intake)-7725)/(intake.std(ddof=1)/np.sqrt(len(intake))) >>> import matplotlib.pyplot as plt >>> h = plt.hist(s, bins=100, normed=True) For a one-sided t-test, how far out in the distribution does the t statistic appear? >>> >>> np.sum(s 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) def vonmises(self, mu, kappa, size=None): """ vonmises(mu, kappa, size=None) Draw samples from a von Mises distribution. Samples are drawn from a von Mises distribution with specified mode (mu) and dispersion (kappa), on the interval [-pi, pi]. The von Mises distribution (also known as the circular normal distribution) is a continuous probability distribution on the unit circle. It may be thought of as the circular analogue of the normal distribution. Parameters ---------- mu : float Mode ("center") of the distribution. kappa : float Dispersion of the distribution, has to be >=0. size : int or tuple of int Output shape. If the given shape is, e.g., ``(m, n, k)``, then ``m * n * k`` samples are drawn. Returns ------- samples : scalar or ndarray The returned samples, which are in the interval [-pi, pi]. See Also -------- scipy.stats.distributions.vonmises : probability density function, distribution, or cumulative density function, etc. Notes ----- The probability density for the von Mises distribution is .. math:: p(x) = \\frac{e^{\\kappa cos(x-\\mu)}}{2\\pi I_0(\\kappa)}, where :math:`\\mu` is the mode and :math:`\\kappa` the dispersion, and :math:`I_0(\\kappa)` is the modified Bessel function of order 0. The von Mises is named for Richard Edler von Mises, who was born in Austria-Hungary, in what is now the Ukraine. He fled to the United States in 1939 and became a professor at Harvard. He worked in probability theory, aerodynamics, fluid mechanics, and philosophy of science. References ---------- Abramowitz, M. and Stegun, I. A. (ed.), *Handbook of Mathematical Functions*, New York: Dover, 1965. von Mises, R., *Mathematical Theory of Probability and Statistics*, New York: Academic Press, 1964. Examples -------- Draw samples from the distribution: >>> mu, kappa = 0.0, 4.0 # mean and dispersion >>> s = np.random.vonmises(mu, kappa, 1000) Display the histogram of the samples, along with the probability density function: >>> import matplotlib.pyplot as plt >>> import scipy.special as sps >>> count, bins, ignored = plt.hist(s, 50, normed=True) >>> x = np.arange(-np.pi, np.pi, 2*np.pi/50.) >>> y = -np.exp(kappa*np.cos(x-mu))/(2*np.pi*sps.jn(0,kappa)) >>> plt.plot(x, y/max(y), linewidth=2, color='r') >>> plt.show() """ cdef ndarray omu, okappa cdef double fmu, fkappa fmu = PyFloat_AsDouble(mu) 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) PyErr_Clear() omu = PyArray_FROM_OTF(mu, NPY_DOUBLE, NPY_ARRAY_ALIGNED) okappa = 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) def pareto(self, a, size=None): """ pareto(a, size=None) Draw samples from a Pareto II or Lomax distribution with specified shape. The Lomax or Pareto II distribution is a shifted Pareto distribution. The classical Pareto distribution can be obtained from the Lomax distribution by adding the location parameter m, see below. The smallest value of the Lomax distribution is zero while for the classical Pareto distribution it is m, where the standard Pareto distribution has location m=1. Lomax can also be considered as a simplified version of the Generalized Pareto distribution (available in SciPy), with the scale set to one and the location set to zero. The Pareto distribution must be greater than zero, and is unbounded above. It is also known as the "80-20 rule". In this distribution, 80 percent of the weights are in the lowest 20 percent of the range, while the other 20 percent fill the remaining 80 percent of the range. Parameters ---------- shape : float, > 0. Shape of the distribution. size : tuple of ints Output shape. If the given shape is, e.g., ``(m, n, k)``, then ``m * n * k`` samples are drawn. See Also -------- scipy.stats.distributions.lomax.pdf : probability density function, distribution or cumulative density function, etc. scipy.stats.distributions.genpareto.pdf : probability density function, distribution or cumulative density function, etc. Notes ----- The probability density for the Pareto distribution is .. math:: p(x) = \\frac{am^a}{x^{a+1}} where :math:`a` is the shape and :math:`m` the location The Pareto distribution, named after the Italian economist Vilfredo Pareto, is a power law probability distribution useful in many real world problems. Outside the field of economics it is generally referred to as the Bradford distribution. Pareto developed the distribution to describe the distribution of wealth in an economy. It has also found use in insurance, web page access statistics, oil field sizes, and many other problems, including the download frequency for projects in Sourceforge [1]. It is one of the so-called "fat-tailed" distributions. References ---------- .. [1] Francis Hunt and Paul Johnson, On the Pareto Distribution of Sourceforge projects. .. [2] Pareto, V. (1896). Course of Political Economy. Lausanne. .. [3] Reiss, R.D., Thomas, M.(2001), Statistical Analysis of Extreme Values, Birkhauser Verlag, Basel, pp 23-30. .. [4] Wikipedia, "Pareto distribution", http://en.wikipedia.org/wiki/Pareto_distribution Examples -------- Draw samples from the distribution: >>> a, m = 3., 1. # shape and mode >>> s = np.random.pareto(a, 1000) + m Display the histogram of the samples, along with the probability density function: >>> import matplotlib.pyplot as plt >>> count, bins, ignored = plt.hist(s, 100, normed=True, align='center') >>> fit = a*m**a/bins**(a+1) >>> plt.plot(bins, max(count)*fit/max(fit),linewidth=2, color='r') >>> plt.show() """ cdef ndarray oa cdef double fa 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) PyErr_Clear() oa = 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) def weibull(self, a, size=None): """ weibull(a, size=None) Weibull distribution. Draw samples from a 1-parameter Weibull distribution with the given shape parameter `a`. .. math:: X = (-ln(U))^{1/a} Here, U is drawn from the uniform distribution over (0,1]. The more common 2-parameter Weibull, including a scale parameter :math:`\\lambda` is just :math:`X = \\lambda(-ln(U))^{1/a}`. Parameters ---------- a : float Shape of the distribution. size : tuple of ints Output shape. If the given shape is, e.g., ``(m, n, k)``, then ``m * n * k`` samples are drawn. See Also -------- scipy.stats.distributions.weibull_max scipy.stats.distributions.weibull_min scipy.stats.distributions.genextreme gumbel Notes ----- The Weibull (or Type III asymptotic extreme value distribution for smallest values, SEV Type III, or Rosin-Rammler distribution) is one of a class of Generalized Extreme Value (GEV) distributions used in modeling extreme value problems. This class includes the Gumbel and Frechet distributions. The probability density for the Weibull distribution is .. math:: p(x) = \\frac{a} {\\lambda}(\\frac{x}{\\lambda})^{a-1}e^{-(x/\\lambda)^a}, where :math:`a` is the shape and :math:`\\lambda` the scale. The function has its peak (the mode) at :math:`\\lambda(\\frac{a-1}{a})^{1/a}`. When ``a = 1``, the Weibull distribution reduces to the exponential distribution. References ---------- .. [1] Waloddi Weibull, Professor, Royal Technical University, Stockholm, 1939 "A Statistical Theory Of The Strength Of Materials", Ingeniorsvetenskapsakademiens Handlingar Nr 151, 1939, Generalstabens Litografiska Anstalts Forlag, Stockholm. .. [2] Waloddi Weibull, 1951 "A Statistical Distribution Function of Wide Applicability", Journal Of Applied Mechanics ASME Paper. .. [3] Wikipedia, "Weibull distribution", http://en.wikipedia.org/wiki/Weibull_distribution Examples -------- Draw samples from the distribution: >>> a = 5. # shape >>> s = np.random.weibull(a, 1000) Display the histogram of the samples, along with the probability density function: >>> import matplotlib.pyplot as plt >>> x = np.arange(1,100.)/50. >>> def weib(x,n,a): ... return (a / n) * (x / n)**(a - 1) * np.exp(-(x / n)**a) >>> count, bins, ignored = plt.hist(np.random.weibull(5.,1000)) >>> x = np.arange(1,100.)/50. >>> scale = count.max()/weib(x, 1., 5.).max() >>> plt.plot(x, weib(x, 1., 5.)*scale) >>> plt.show() """ cdef ndarray oa cdef double fa 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) PyErr_Clear() oa = 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) def power(self, a, size=None): """ power(a, size=None) Draws samples in [0, 1] from a power distribution with positive exponent a - 1. Also known as the power function distribution. Parameters ---------- a : float parameter, > 0 size : tuple of ints Output shape. If the given shape is, e.g., ``(m, n, k)``, then ``m * n * k`` samples are drawn. Returns ------- samples : {ndarray, scalar} The returned samples lie in [0, 1]. Raises ------ ValueError If a<1. Notes ----- The probability density function is .. math:: P(x; a) = ax^{a-1}, 0 \\le x \\le 1, a>0. The power function distribution is just the inverse of the Pareto distribution. It may also be seen as a special case of the Beta distribution. It is used, for example, in modeling the over-reporting of insurance claims. References ---------- .. [1] Christian Kleiber, Samuel Kotz, "Statistical size distributions in economics and actuarial sciences", Wiley, 2003. .. [2] Heckert, N. A. and Filliben, James J. (2003). NIST Handbook 148: Dataplot Reference Manual, Volume 2: Let Subcommands and Library Functions", National Institute of Standards and Technology Handbook Series, June 2003. http://www.itl.nist.gov/div898/software/dataplot/refman2/auxillar/powpdf.pdf Examples -------- Draw samples from the distribution: >>> a = 5. # shape >>> samples = 1000 >>> s = np.random.power(a, samples) Display the histogram of the samples, along with the probability density function: >>> import matplotlib.pyplot as plt >>> count, bins, ignored = plt.hist(s, bins=30) >>> x = np.linspace(0, 1, 100) >>> y = a*x**(a-1.) >>> normed_y = samples*np.diff(bins)[0]*y >>> plt.plot(x, normed_y) >>> plt.show() Compare the power function distribution to the inverse of the Pareto. >>> from scipy import stats >>> rvs = np.random.power(5, 1000000) >>> rvsp = np.random.pareto(5, 1000000) >>> xx = np.linspace(0,1,100) >>> powpdf = stats.powerlaw.pdf(xx,5) >>> plt.figure() >>> plt.hist(rvs, bins=50, normed=True) >>> plt.plot(xx,powpdf,'r-') >>> plt.title('np.random.power(5)') >>> plt.figure() >>> plt.hist(1./(1.+rvsp), bins=50, normed=True) >>> plt.plot(xx,powpdf,'r-') >>> plt.title('inverse of 1 + np.random.pareto(5)') >>> plt.figure() >>> plt.hist(1./(1.+rvsp), bins=50, normed=True) >>> plt.plot(xx,powpdf,'r-') >>> plt.title('inverse of stats.pareto(5)') """ cdef ndarray oa cdef double fa 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) PyErr_Clear() oa = 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) def laplace(self, loc=0.0, scale=1.0, size=None): """ laplace(loc=0.0, scale=1.0, size=None) Draw samples from the Laplace or double exponential distribution with specified location (or mean) and scale (decay). The Laplace distribution is similar to the Gaussian/normal distribution, but is sharper at the peak and has fatter tails. It represents the difference between two independent, identically distributed exponential random variables. Parameters ---------- loc : float The position, :math:`\\mu`, of the distribution peak. scale : float :math:`\\lambda`, the exponential decay. Notes ----- It has the probability density function .. math:: f(x; \\mu, \\lambda) = \\frac{1}{2\\lambda} \\exp\\left(-\\frac{|x - \\mu|}{\\lambda}\\right). The first law of Laplace, from 1774, states that the frequency of an error can be expressed as an exponential function of the absolute magnitude of the error, which leads to the Laplace distribution. For many problems in Economics and Health sciences, this distribution seems to model the data better than the standard Gaussian distribution References ---------- .. [1] Abramowitz, M. and Stegun, I. A. (Eds.). Handbook of Mathematical Functions with Formulas, Graphs, and Mathematical Tables, 9th printing. New York: Dover, 1972. .. [2] The Laplace distribution and generalizations By Samuel Kotz, Tomasz J. Kozubowski, Krzysztof Podgorski, Birkhauser, 2001. .. [3] Weisstein, Eric W. "Laplace Distribution." From MathWorld--A Wolfram Web Resource. http://mathworld.wolfram.com/LaplaceDistribution.html .. [4] Wikipedia, "Laplace distribution", http://en.wikipedia.org/wiki/Laplace_distribution Examples -------- Draw samples from the distribution >>> loc, scale = 0., 1. >>> s = np.random.laplace(loc, scale, 1000) Display the histogram of the samples, along with the probability density function: >>> import matplotlib.pyplot as plt >>> count, bins, ignored = plt.hist(s, 30, normed=True) >>> x = np.arange(-8., 8., .01) >>> pdf = np.exp(-abs(x-loc/scale))/(2.*scale) >>> plt.plot(x, pdf) Plot Gaussian for comparison: >>> g = (1/(scale * np.sqrt(2 * np.pi)) * ... np.exp( - (x - loc)**2 / (2 * scale**2) )) >>> plt.plot(x,g) """ cdef ndarray oloc, oscale cdef double floc, fscale floc = PyFloat_AsDouble(loc) 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) 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) def gumbel(self, loc=0.0, scale=1.0, size=None): """ gumbel(loc=0.0, scale=1.0, size=None) Gumbel distribution. Draw samples from a Gumbel distribution with specified location and scale. For more information on the Gumbel distribution, see Notes and References below. Parameters ---------- loc : float The location of the mode of the distribution. scale : float The scale parameter of the distribution. size : tuple of ints Output shape. If the given shape is, e.g., ``(m, n, k)``, then ``m * n * k`` samples are drawn. Returns ------- out : ndarray The samples See Also -------- scipy.stats.gumbel_l scipy.stats.gumbel_r scipy.stats.genextreme probability density function, distribution, or cumulative density function, etc. for each of the above weibull Notes ----- The Gumbel (or Smallest Extreme Value (SEV) or the Smallest Extreme Value Type I) distribution is one of a class of Generalized Extreme Value (GEV) distributions used in modeling extreme value problems. The Gumbel is a special case of the Extreme Value Type I distribution for maximums from distributions with "exponential-like" tails. The probability density for the Gumbel distribution is .. math:: p(x) = \\frac{e^{-(x - \\mu)/ \\beta}}{\\beta} e^{ -e^{-(x - \\mu)/ \\beta}}, where :math:`\\mu` is the mode, a location parameter, and :math:`\\beta` is the scale parameter. The Gumbel (named for German mathematician Emil Julius Gumbel) was used very early in the hydrology literature, for modeling the occurrence of flood events. It is also used for modeling maximum wind speed and rainfall rates. It is a "fat-tailed" distribution - the probability of an event in the tail of the distribution is larger than if one used a Gaussian, hence the surprisingly frequent occurrence of 100-year floods. Floods were initially modeled as a Gaussian process, which underestimated the frequency of extreme events. It is one of a class of extreme value distributions, the Generalized Extreme Value (GEV) distributions, which also includes the Weibull and Frechet. The function has a mean of :math:`\\mu + 0.57721\\beta` and a variance of :math:`\\frac{\\pi^2}{6}\\beta^2`. References ---------- Gumbel, E. J., *Statistics of Extremes*, New York: Columbia University Press, 1958. Reiss, R.-D. and Thomas, M., *Statistical Analysis of Extreme Values from Insurance, Finance, Hydrology and Other Fields*, Basel: Birkhauser Verlag, 2001. Examples -------- Draw samples from the distribution: >>> mu, beta = 0, 0.1 # location and scale >>> s = np.random.gumbel(mu, beta, 1000) Display the histogram of the samples, along with the probability density function: >>> import matplotlib.pyplot as plt >>> count, bins, ignored = plt.hist(s, 30, normed=True) >>> plt.plot(bins, (1/beta)*np.exp(-(bins - mu)/beta) ... * np.exp( -np.exp( -(bins - mu) /beta) ), ... linewidth=2, color='r') >>> plt.show() Show how an extreme value distribution can arise from a Gaussian process and compare to a Gaussian: >>> means = [] >>> maxima = [] >>> for i in range(0,1000) : ... a = np.random.normal(mu, beta, 1000) ... means.append(a.mean()) ... maxima.append(a.max()) >>> count, bins, ignored = plt.hist(maxima, 30, normed=True) >>> beta = np.std(maxima)*np.pi/np.sqrt(6) >>> mu = np.mean(maxima) - 0.57721*beta >>> plt.plot(bins, (1/beta)*np.exp(-(bins - mu)/beta) ... * np.exp(-np.exp(-(bins - mu)/beta)), ... linewidth=2, color='r') >>> plt.plot(bins, 1/(beta * np.sqrt(2 * np.pi)) ... * np.exp(-(bins - mu)**2 / (2 * beta**2)), ... linewidth=2, color='g') >>> plt.show() """ cdef ndarray oloc, oscale cdef double floc, fscale floc = PyFloat_AsDouble(loc) 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) 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) def logistic(self, loc=0.0, scale=1.0, size=None): """ logistic(loc=0.0, scale=1.0, size=None) Draw samples from a Logistic distribution. Samples are drawn from a Logistic distribution with specified parameters, loc (location or mean, also median), and scale (>0). Parameters ---------- loc : float scale : float > 0. size : {tuple, int} Output shape. If the given shape is, e.g., ``(m, n, k)``, then ``m * n * k`` samples are drawn. Returns ------- samples : {ndarray, scalar} where the values are all integers in [0, n]. See Also -------- scipy.stats.distributions.logistic : probability density function, distribution or cumulative density function, etc. Notes ----- The probability density for the Logistic distribution is .. math:: P(x) = P(x) = \\frac{e^{-(x-\\mu)/s}}{s(1+e^{-(x-\\mu)/s})^2}, where :math:`\\mu` = location and :math:`s` = scale. The Logistic distribution is used in Extreme Value problems where it can act as a mixture of Gumbel distributions, in Epidemiology, and by the World Chess Federation (FIDE) where it is used in the Elo ranking system, assuming the performance of each player is a logistically distributed random variable. References ---------- .. [1] Reiss, R.-D. and Thomas M. (2001), Statistical Analysis of Extreme Values, from Insurance, Finance, Hydrology and Other Fields, Birkhauser Verlag, Basel, pp 132-133. .. [2] Weisstein, Eric W. "Logistic Distribution." From MathWorld--A Wolfram Web Resource. http://mathworld.wolfram.com/LogisticDistribution.html .. [3] Wikipedia, "Logistic-distribution", http://en.wikipedia.org/wiki/Logistic-distribution Examples -------- Draw samples from the distribution: >>> loc, scale = 10, 1 >>> s = np.random.logistic(loc, scale, 10000) >>> count, bins, ignored = plt.hist(s, bins=50) # plot against distribution >>> def logist(x, loc, scale): ... return exp((loc-x)/scale)/(scale*(1+exp((loc-x)/scale))**2) >>> plt.plot(bins, logist(bins, loc, scale)*count.max()/\\ ... logist(bins, loc, scale).max()) >>> plt.show() """ cdef ndarray oloc, oscale cdef double floc, fscale floc = PyFloat_AsDouble(loc) 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) 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) def lognormal(self, mean=0.0, sigma=1.0, size=None): """ lognormal(mean=0.0, sigma=1.0, size=None) Return samples drawn from a log-normal distribution. Draw samples from a log-normal distribution with specified mean, standard deviation, and array shape. Note that the mean and standard deviation are not the values for the distribution itself, but of the underlying normal distribution it is derived from. Parameters ---------- mean : float Mean value of the underlying normal distribution sigma : float, > 0. Standard deviation of the underlying normal distribution size : tuple of ints Output shape. If the given shape is, e.g., ``(m, n, k)``, then ``m * n * k`` samples are drawn. Returns ------- samples : ndarray or float The desired samples. An array of the same shape as `size` if given, if `size` is None a float is returned. See Also -------- scipy.stats.lognorm : probability density function, distribution, cumulative density function, etc. Notes ----- A variable `x` has a log-normal distribution if `log(x)` is normally distributed. The probability density function for the log-normal distribution is: .. math:: p(x) = \\frac{1}{\\sigma x \\sqrt{2\\pi}} e^{(-\\frac{(ln(x)-\\mu)^2}{2\\sigma^2})} where :math:`\\mu` is the mean and :math:`\\sigma` is the standard deviation of the normally distributed logarithm of the variable. A log-normal distribution results if a random variable is the *product* of a large number of independent, identically-distributed variables in the same way that a normal distribution results if the variable is the *sum* of a large number of independent, identically-distributed variables. References ---------- Limpert, E., Stahel, W. A., and Abbt, M., "Log-normal Distributions across the Sciences: Keys and Clues," *BioScience*, Vol. 51, No. 5, May, 2001. http://stat.ethz.ch/~stahel/lognormal/bioscience.pdf Reiss, R.D. and Thomas, M., *Statistical Analysis of Extreme Values*, Basel: Birkhauser Verlag, 2001, pp. 31-32. Examples -------- Draw samples from the distribution: >>> mu, sigma = 3., 1. # mean and standard deviation >>> s = np.random.lognormal(mu, sigma, 1000) Display the histogram of the samples, along with the probability density function: >>> import matplotlib.pyplot as plt >>> count, bins, ignored = plt.hist(s, 100, normed=True, align='mid') >>> x = np.linspace(min(bins), max(bins), 10000) >>> pdf = (np.exp(-(np.log(x) - mu)**2 / (2 * sigma**2)) ... / (x * sigma * np.sqrt(2 * np.pi))) >>> plt.plot(x, pdf, linewidth=2, color='r') >>> plt.axis('tight') >>> plt.show() Demonstrate that taking the products of random samples from a uniform distribution can be fit well by a log-normal probability density function. >>> # Generate a thousand samples: each is the product of 100 random >>> # values, drawn from a normal distribution. >>> b = [] >>> for i in range(1000): ... a = 10. + np.random.random(100) ... b.append(np.product(a)) >>> b = np.array(b) / np.min(b) # scale values to be positive >>> count, bins, ignored = plt.hist(b, 100, normed=True, align='center') >>> sigma = np.std(np.log(b)) >>> mu = np.mean(np.log(b)) >>> x = np.linspace(min(bins), max(bins), 10000) >>> pdf = (np.exp(-(np.log(x) - mu)**2 / (2 * sigma**2)) ... / (x * sigma * np.sqrt(2 * np.pi))) >>> plt.plot(x, pdf, color='r', linewidth=2) >>> plt.show() """ cdef ndarray omean, osigma cdef double fmean, fsigma fmean = PyFloat_AsDouble(mean) fsigma = PyFloat_AsDouble(sigma) if not PyErr_Occurred(): if fsigma <= 0: raise ValueError("sigma <= 0") return cont2_array_sc(self.internal_state, rk_lognormal, size, fmean, fsigma) 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)): raise ValueError("sigma <= 0.0") 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) Draw samples from a Rayleigh distribution. The :math:`\\chi` and Weibull distributions are generalizations of the Rayleigh. Parameters ---------- 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. Notes ----- The probability density function for the Rayleigh distribution is .. math:: P(x;scale) = \\frac{x}{scale^2}e^{\\frac{-x^2}{2 \\cdotp scale^2}} The Rayleigh distribution arises if the wind speed and wind direction are both gaussian variables, then the vector wind velocity forms a Rayleigh distribution. The Rayleigh distribution is used to model the expected output from wind turbines. References ---------- .. [1] Brighton Webs Ltd., Rayleigh Distribution, http://www.brighton-webs.co.uk/distributions/rayleigh.asp .. [2] Wikipedia, "Rayleigh distribution" http://en.wikipedia.org/wiki/Rayleigh_distribution Examples -------- Draw values from the distribution and plot the histogram >>> values = hist(np.random.rayleigh(3, 100000), bins=200, normed=True) Wave heights tend to follow a Rayleigh distribution. If the mean wave height is 1 meter, what fraction of waves are likely to be larger than 3 meters? >>> meanvalue = 1 >>> modevalue = np.sqrt(2 / np.pi) * meanvalue >>> s = np.random.rayleigh(modevalue, 1000000) The percentage of waves larger than 3 meters is: >>> 100.*sum(s>3)/1000000. 0.087300000000000003 """ cdef ndarray oscale cdef double fscale fscale = PyFloat_AsDouble(scale) if not PyErr_Occurred(): if fscale <= 0: raise ValueError("scale <= 0") return cont1_array_sc(self.internal_state, rk_rayleigh, size, fscale) PyErr_Clear() oscale = 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) def wald(self, mean, scale, size=None): """ wald(mean, scale, size=None) Draw samples from a Wald, or Inverse Gaussian, distribution. As the scale approaches infinity, the distribution becomes more like a Gaussian. Some references claim that the Wald is an Inverse Gaussian with mean=1, but this is by no means universal. The Inverse Gaussian distribution was first studied in relationship to Brownian motion. In 1956 M.C.K. Tweedie used the name Inverse Gaussian because there is an inverse relationship between the time to cover a unit distance and distance covered in unit time. Parameters ---------- mean : scalar Distribution mean, should be > 0. 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. Returns ------- samples : ndarray or scalar Drawn sample, all greater than zero. Notes ----- The probability density function for the Wald distribution is .. math:: P(x;mean,scale) = \\sqrt{\\frac{scale}{2\\pi x^3}}e^ \\frac{-scale(x-mean)^2}{2\\cdotp mean^2x} As noted above the Inverse Gaussian distribution first arise from attempts to model Brownian Motion. It is also a competitor to the Weibull for use in reliability modeling and modeling stock returns and interest rate processes. References ---------- .. [1] Brighton Webs Ltd., Wald Distribution, http://www.brighton-webs.co.uk/distributions/wald.asp .. [2] Chhikara, Raj S., and Folks, J. Leroy, "The Inverse Gaussian Distribution: Theory : Methodology, and Applications", CRC Press, 1988. .. [3] Wikipedia, "Wald distribution" http://en.wikipedia.org/wiki/Wald_distribution Examples -------- Draw values from the distribution and plot the histogram: >>> import matplotlib.pyplot as plt >>> h = plt.hist(np.random.wald(3, 2, 100000), bins=200, normed=True) >>> plt.show() """ cdef ndarray omean, oscale cdef double fmean, fscale fmean = PyFloat_AsDouble(mean) fscale = PyFloat_AsDouble(scale) if not PyErr_Occurred(): 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) 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") 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) def triangular(self, left, mode, right, size=None): """ triangular(left, mode, right, size=None) Draw samples from the triangular distribution. The triangular distribution is a continuous probability distribution with lower limit left, peak at mode, and upper limit right. Unlike the other distributions, these parameters directly define the shape of the pdf. Parameters ---------- left : scalar Lower limit. mode : scalar The value where the peak of the distribution occurs. The value should fulfill the condition ``left <= mode <= right``. 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. Returns ------- samples : ndarray or scalar The returned samples all lie in the interval [left, right]. Notes ----- The probability density function for the Triangular distribution is .. math:: P(x;l, m, r) = \\begin{cases} \\frac{2(x-l)}{(r-l)(m-l)}& \\text{for $l \\leq x \\leq m$},\\\\ \\frac{2(m-x)}{(r-l)(r-m)}& \\text{for $m \\leq x \\leq r$},\\\\ 0& \\text{otherwise}. \\end{cases} The triangular distribution is often used in ill-defined problems where the underlying distribution is not known, but some knowledge of the limits and mode exists. Often it is used in simulations. References ---------- .. [1] Wikipedia, "Triangular distribution" http://en.wikipedia.org/wiki/Triangular_distribution Examples -------- Draw values from the distribution and plot the histogram: >>> import matplotlib.pyplot as plt >>> h = plt.hist(np.random.triangular(-3, 0, 8, 100000), bins=200, ... normed=True) >>> plt.show() """ cdef ndarray oleft, omode, oright cdef double fleft, fmode, fright fleft = PyFloat_AsDouble(left) fright = PyFloat_AsDouble(right) fmode = PyFloat_AsDouble(mode) if not PyErr_Occurred(): if fleft > fmode: raise ValueError("left > mode") 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, fmode, fright) PyErr_Clear() oleft = PyArray_FROM_OTF(left, NPY_DOUBLE, NPY_ARRAY_ALIGNED) omode = PyArray_FROM_OTF(mode, NPY_DOUBLE, NPY_ARRAY_ALIGNED) oright = 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)): 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) # Complicated, discrete distributions: def binomial(self, n, p, size=None): """ binomial(n, p, size=None) Draw samples from a binomial distribution. Samples are drawn from a Binomial distribution with specified parameters, n trials and p probability of success where n an integer >= 0 and p is in the interval [0,1]. (n may be input as a float, but it is truncated to an integer in use) Parameters ---------- n : float (but truncated to an integer) parameter, >= 0. p : float parameter, >= 0 and <=1. size : {tuple, int} Output shape. If the given shape is, e.g., ``(m, n, k)``, then ``m * n * k`` samples are drawn. Returns ------- samples : {ndarray, scalar} where the values are all integers in [0, n]. See Also -------- scipy.stats.distributions.binom : probability density function, distribution or cumulative density function, etc. Notes ----- The probability density for the Binomial distribution is .. math:: P(N) = \\binom{n}{N}p^N(1-p)^{n-N}, where :math:`n` is the number of trials, :math:`p` is the probability of success, and :math:`N` is the number of successes. When estimating the standard error of a proportion in a population by using a random sample, the normal distribution works well unless the product p*n <=5, where p = population proportion estimate, and n = number of samples, in which case the binomial distribution is used instead. For example, a sample of 15 people shows 4 who are left handed, and 11 who are right handed. Then p = 4/15 = 27%. 0.27*15 = 4, so the binomial distribution should be used in this case. References ---------- .. [1] Dalgaard, Peter, "Introductory Statistics with R", Springer-Verlag, 2002. .. [2] Glantz, Stanton A. "Primer of Biostatistics.", McGraw-Hill, Fifth Edition, 2002. .. [3] Lentner, Marvin, "Elementary Applied Statistics", Bogden and Quigley, 1972. .. [4] Weisstein, Eric W. "Binomial Distribution." From MathWorld--A Wolfram Web Resource. http://mathworld.wolfram.com/BinomialDistribution.html .. [5] Wikipedia, "Binomial-distribution", http://en.wikipedia.org/wiki/Binomial_distribution Examples -------- Draw samples from the distribution: >>> n, p = 10, .5 # number of trials, probability of each trial >>> s = np.random.binomial(n, p, 1000) # result of flipping a coin 10 times, tested 1000 times. A real world example. A company drills 9 wild-cat oil exploration wells, each with an estimated probability of success of 0.1. All nine wells fail. What is the probability of that happening? Let's do 20,000 trials of the model, and count the number that generate zero positive results. >>> sum(np.random.binomial(9,0.1,20000)==0)/20000. answer = 0.38885, or 38%. """ cdef ndarray on, op cdef long ln cdef double fp fp = PyFloat_AsDouble(p) ln = PyInt_AsLong(n) if not PyErr_Occurred(): if ln < 0: raise ValueError("n < 0") 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) PyErr_Clear() on = PyArray_FROM_OTF(n, NPY_LONG, NPY_ARRAY_ALIGNED) op = 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") 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): """ negative_binomial(n, p, size=None) Draw samples from a negative_binomial distribution. Samples are drawn from a negative_Binomial distribution with specified parameters, `n` trials and `p` probability of success where `n` is an integer > 0 and `p` is in the interval [0, 1]. Parameters ---------- n : int 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. Returns ------- samples : int or ndarray of ints Drawn samples. Notes ----- The probability density for the Negative Binomial distribution is .. math:: P(N;n,p) = \\binom{N+n-1}{n-1}p^{n}(1-p)^{N}, where :math:`n-1` is the number of successes, :math:`p` is the probability of success, and :math:`N+n-1` is the number of trials. The negative binomial distribution gives the probability of n-1 successes and N failures in N+n-1 trials, and success on the (N+n)th trial. If one throws a die repeatedly until the third time a "1" appears, then the probability distribution of the number of non-"1"s that appear before the third "1" is a negative binomial distribution. References ---------- .. [1] Weisstein, Eric W. "Negative Binomial Distribution." From MathWorld--A Wolfram Web Resource. http://mathworld.wolfram.com/NegativeBinomialDistribution.html .. [2] Wikipedia, "Negative binomial distribution", http://en.wikipedia.org/wiki/Negative_binomial_distribution Examples -------- Draw samples from the distribution: A real world example. A company drills wild-cat oil exploration wells, each with an estimated probability of success of 0.1. What is the probability of having one success for each successive well, that is what is the probability of a single success after drilling 5 wells, after 6 wells, etc.? >>> s = np.random.negative_binomial(1, 0.1, 100000) >>> for i in range(1, 11): ... probability = sum(s 1: raise ValueError("p > 1") return discdd_array_sc(self.internal_state, rk_negative_binomial, size, fn, fp) PyErr_Clear() on = PyArray_FROM_OTF(n, NPY_DOUBLE, NPY_ARRAY_ALIGNED) op = 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") if np.any(np.greater(p, 1)): raise ValueError("p > 1") return discdd_array(self.internal_state, rk_negative_binomial, size, on, op) def poisson(self, lam=1.0, size=None): """ poisson(lam=1.0, size=None) Draw samples from a Poisson distribution. The Poisson distribution is the limit of the Binomial distribution for large N. Parameters ---------- lam : float Expectation of interval, should be >= 0. 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. Notes ----- The Poisson distribution .. math:: f(k; \\lambda)=\\frac{\\lambda^k e^{-\\lambda}}{k!} For events with an expected separation :math:`\\lambda` the Poisson distribution :math:`f(k; \\lambda)` describes the probability of :math:`k` events occurring within the observed interval :math:`\\lambda`. Because the output is limited to the range of the C long type, a ValueError is raised when `lam` is within 10 sigma of the maximum representable value. References ---------- .. [1] Weisstein, Eric W. "Poisson Distribution." From MathWorld--A Wolfram Web Resource. http://mathworld.wolfram.com/PoissonDistribution.html .. [2] Wikipedia, "Poisson distribution", http://en.wikipedia.org/wiki/Poisson_distribution Examples -------- Draw samples from the distribution: >>> import numpy as np >>> s = np.random.poisson(5, 10000) Display histogram of the sample: >>> import matplotlib.pyplot as plt >>> count, bins, ignored = plt.hist(s, 14, normed=True) >>> plt.show() """ cdef ndarray olam cdef double flam flam = PyFloat_AsDouble(lam) if not PyErr_Occurred(): 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) PyErr_Clear() olam = 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.") return discd_array(self.internal_state, rk_poisson, size, olam) def zipf(self, a, size=None): """ zipf(a, size=None) Draw samples from a Zipf distribution. Samples are drawn from a Zipf distribution with specified parameter `a` > 1. The Zipf distribution (also known as the zeta distribution) is a continuous probability distribution that satisfies Zipf's law: the frequency of an item is inversely proportional to its rank in a frequency table. Parameters ---------- a : float > 1 Distribution parameter. size : int or tuple of int, 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. Returns ------- samples : scalar or ndarray The returned samples are greater than or equal to one. See Also -------- scipy.stats.distributions.zipf : probability density function, distribution, or cumulative density function, etc. Notes ----- The probability density for the Zipf distribution is .. math:: p(x) = \\frac{x^{-a}}{\\zeta(a)}, where :math:`\\zeta` is the Riemann Zeta function. It is named for the American linguist George Kingsley Zipf, who noted that the frequency of any word in a sample of a language is inversely proportional to its rank in the frequency table. References ---------- Zipf, G. K., *Selected Studies of the Principle of Relative Frequency in Language*, Cambridge, MA: Harvard Univ. Press, 1932. Examples -------- Draw samples from the distribution: >>> a = 2. # parameter >>> s = np.random.zipf(a, 1000) Display the histogram of the samples, along with the probability density function: >>> import matplotlib.pyplot as plt >>> import scipy.special as sps Truncate s values at 50 so plot is interesting >>> count, bins, ignored = plt.hist(s[s<50], 50, normed=True) >>> x = np.arange(1., 50.) >>> y = x**(-a)/sps.zetac(a) >>> plt.plot(x, y/max(y), linewidth=2, color='r') >>> plt.show() """ cdef ndarray oa cdef double fa 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) PyErr_Clear() oa = 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) def geometric(self, p, size=None): """ geometric(p, size=None) Draw samples from the geometric distribution. Bernoulli trials are experiments with one of two outcomes: success or failure (an example of such an experiment is flipping a coin). The geometric distribution models the number of trials that must be run in order to achieve success. It is therefore supported on the positive integers, ``k = 1, 2, ...``. The probability mass function of the geometric distribution is .. math:: f(k) = (1 - p)^{k - 1} p where `p` is the probability of success of an individual trial. Parameters ---------- 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`. Returns ------- out : ndarray Samples from the geometric distribution, shaped according to `size`. Examples -------- Draw ten thousand values from the geometric distribution, with the probability of an individual success equal to 0.35: >>> z = np.random.geometric(p=0.35, size=10000) How many trials succeeded after a single run? >>> (z == 1).sum() / 10000. 0.34889999999999999 #random """ cdef ndarray op cdef double fp fp = PyFloat_AsDouble(p) if not PyErr_Occurred(): 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) PyErr_Clear() op = 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") return discd_array(self.internal_state, rk_geometric, size, op) def hypergeometric(self, ngood, nbad, nsample, size=None): """ hypergeometric(ngood, nbad, nsample, size=None) Draw samples from a Hypergeometric distribution. Samples are drawn from a Hypergeometric distribution with specified parameters, ngood (ways to make a good selection), nbad (ways to make a bad selection), and nsample = number of items sampled, which is less than or equal to the sum ngood + nbad. Parameters ---------- ngood : int or array_like Number of ways to make a good selection. Must be nonnegative. nbad : int or array_like Number of ways to make a bad selection. Must be nonnegative. 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 Output shape. If the given shape is, e.g., ``(m, n, k)``, then ``m * n * k`` samples are drawn. Returns ------- samples : ndarray or scalar The values are all integers in [0, n]. See Also -------- scipy.stats.distributions.hypergeom : probability density function, distribution or cumulative density function, etc. Notes ----- The probability density for the Hypergeometric distribution is .. math:: P(x) = \\frac{\\binom{m}{n}\\binom{N-m}{n-x}}{\\binom{N}{n}}, where :math:`0 \\le x \\le m` and :math:`n+m-N \\le x \\le n` for P(x) the probability of x successes, n = ngood, m = nbad, and N = number of samples. Consider an urn with black and white marbles in it, ngood of them black and nbad are white. If you draw nsample balls without replacement, then the Hypergeometric distribution describes the distribution of black balls in the drawn sample. Note that this distribution is very similar to the Binomial distribution, except that in this case, samples are drawn without replacement, whereas in the Binomial case samples are drawn with replacement (or the sample space is infinite). As the sample space becomes large, this distribution approaches the Binomial. References ---------- .. [1] Lentner, Marvin, "Elementary Applied Statistics", Bogden and Quigley, 1972. .. [2] Weisstein, Eric W. "Hypergeometric Distribution." From MathWorld--A Wolfram Web Resource. http://mathworld.wolfram.com/HypergeometricDistribution.html .. [3] Wikipedia, "Hypergeometric-distribution", http://en.wikipedia.org/wiki/Hypergeometric-distribution Examples -------- Draw samples from the distribution: >>> ngood, nbad, nsamp = 100, 2, 10 # number of good, number of bad, and number of samples >>> s = np.random.hypergeometric(ngood, nbad, nsamp, 1000) >>> hist(s) # note that it is very unlikely to grab both bad items Suppose you have an urn with 15 white and 15 black marbles. If you pull 15 marbles at random, how likely is it that 12 or more of them are one color? >>> s = np.random.hypergeometric(15, 15, 15, 100000) >>> sum(s>=12)/100000. + sum(s<=3)/100000. # answer = 0.003 ... pretty unlikely! """ cdef ndarray ongood, onbad, onsample cdef long lngood, lnbad, lnsample lngood = PyInt_AsLong(ngood) lnbad = PyInt_AsLong(nbad) lnsample = PyInt_AsLong(nsample) if not PyErr_Occurred(): if lngood < 0: raise ValueError("ngood < 0") if lnbad < 0: raise ValueError("nbad < 0") 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, lngood, lnbad, lnsample) PyErr_Clear() ongood = PyArray_FROM_OTF(ngood, NPY_LONG, NPY_ARRAY_ALIGNED) onbad = PyArray_FROM_OTF(nbad, NPY_LONG, NPY_ARRAY_ALIGNED) onsample = 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") 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, ongood, onbad, onsample) def logseries(self, p, size=None): """ logseries(p, size=None) Draw samples from a Logarithmic Series distribution. Samples are drawn from a Log Series distribution with specified parameter, p (probability, 0 < p < 1). Parameters ---------- loc : float scale : float > 0. size : {tuple, int} Output shape. If the given shape is, e.g., ``(m, n, k)``, then ``m * n * k`` samples are drawn. Returns ------- samples : {ndarray, scalar} where the values are all integers in [0, n]. See Also -------- scipy.stats.distributions.logser : probability density function, distribution or cumulative density function, etc. Notes ----- The probability density for the Log Series distribution is .. math:: P(k) = \\frac{-p^k}{k \\ln(1-p)}, where p = probability. The Log Series distribution is frequently used to represent species richness and occurrence, first proposed by Fisher, Corbet, and Williams in 1943 [2]. It may also be used to model the numbers of occupants seen in cars [3]. References ---------- .. [1] Buzas, Martin A.; Culver, Stephen J., Understanding regional species diversity through the log series distribution of occurrences: BIODIVERSITY RESEARCH Diversity & Distributions, Volume 5, Number 5, September 1999 , pp. 187-195(9). .. [2] Fisher, R.A,, A.S. Corbet, and C.B. Williams. 1943. The relation between the number of species and the number of individuals in a random sample of an animal population. Journal of Animal Ecology, 12:42-58. .. [3] D. J. Hand, F. Daly, D. Lunn, E. Ostrowski, A Handbook of Small Data Sets, CRC Press, 1994. .. [4] Wikipedia, "Logarithmic-distribution", http://en.wikipedia.org/wiki/Logarithmic-distribution Examples -------- Draw samples from the distribution: >>> a = .6 >>> s = np.random.logseries(a, 10000) >>> count, bins, ignored = plt.hist(s) # plot against distribution >>> def logseries(k, p): ... return -p**k/(k*log(1-p)) >>> plt.plot(bins, logseries(bins, a)*count.max()/ logseries(bins, a).max(), 'r') >>> plt.show() """ cdef ndarray op cdef double fp fp = PyFloat_AsDouble(p) if not PyErr_Occurred(): 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) PyErr_Clear() op = 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") return discd_array(self.internal_state, rk_logseries, size, op) # Multivariate distributions: def multivariate_normal(self, mean, cov, size=None): """ multivariate_normal(mean, cov[, size]) Draw random samples from a multivariate normal distribution. The multivariate normal, multinormal or Gaussian distribution is a generalization of the one-dimensional normal distribution to higher dimensions. Such a distribution is specified by its mean and covariance matrix. These parameters are analogous to the mean (average or "center") and variance (standard deviation, or "width," squared) of the one-dimensional normal distribution. Parameters ---------- mean : 1-D array_like, of length N 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. 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 each sample is `N`-dimensional, the output shape is ``(m,n,k,N)``. If no shape is specified, a single (`N`-D) sample is returned. Returns ------- out : ndarray The drawn samples, of shape *size*, if that was provided. If not, the shape is ``(N,)``. In other words, each entry ``out[i,j,...,:]`` is an N-dimensional value drawn from the distribution. Notes ----- The mean is a coordinate in N-dimensional space, which represents the location where samples are most likely to be generated. This is analogous to the peak of the bell curve for the one-dimensional or univariate normal distribution. Covariance indicates the level to which two variables vary together. From the multivariate normal distribution, we draw N-dimensional samples, :math:`X = [x_1, x_2, ... x_N]`. The covariance matrix element :math:`C_{ij}` is the covariance of :math:`x_i` and :math:`x_j`. The element :math:`C_{ii}` is the variance of :math:`x_i` (i.e. its "spread"). Instead of specifying the full covariance matrix, popular approximations include: - Spherical covariance (*cov* is a multiple of the identity matrix) - Diagonal covariance (*cov* has non-negative elements, and only on the diagonal) This geometrical property can be seen in two dimensions by plotting generated data-points: >>> mean = [0,0] >>> cov = [[1,0],[0,100]] # diagonal covariance, points lie on x or y-axis >>> import matplotlib.pyplot as plt >>> x,y = np.random.multivariate_normal(mean,cov,5000).T >>> plt.plot(x,y,'x'); plt.axis('equal'); plt.show() Note that the covariance matrix must be non-negative definite. References ---------- Papoulis, A., *Probability, Random Variables, and Stochastic Processes*, 3rd ed., New York: McGraw-Hill, 1991. Duda, R. O., Hart, P. E., and Stork, D. G., *Pattern Classification*, 2nd ed., New York: Wiley, 2001. Examples -------- >>> mean = (1,2) >>> cov = [[1,0],[1,0]] >>> x = np.random.multivariate_normal(mean,cov,(3,3)) >>> x.shape (3, 3, 2) The following is probably true, given that 0.6 is roughly twice the standard deviation: >>> print list( (x[0,0,:] - mean) < 0.6 ) [True, True] """ # Check preconditions on arguments mean = np.array(mean) cov = np.array(cov) if size is None: shape = [] 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] 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]) # 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) x.shape = tuple(final_shape) return x def multinomial(self, npy_intp n, object pvals, size=None): """ multinomial(n, pvals, size=None) Draw samples from a multinomial distribution. The multinomial distribution is a multivariate generalisation of the binomial distribution. Take an experiment with one of ``p`` possible outcomes. An example of such an experiment is throwing a dice, where the outcome can be 1 through 6. Each sample drawn from the distribution represents `n` such experiments. Its values, ``X_i = [X_0, X_1, ..., X_p]``, represent the number of times the outcome was ``i``. Parameters ---------- n : int Number of experiments. pvals : sequence of floats, length p Probabilities of each of the ``p`` different outcomes. These should sum to 1 (however, the last element is always assumed to account for the remaining probability, as long as ``sum(pvals[:-1]) <= 1)``. size : tuple of ints Given a `size` of ``(M, N, K)``, then ``M*N*K`` samples are drawn, and the output shape becomes ``(M, N, K, p)``, since each sample has shape ``(p,)``. Examples -------- Throw a dice 20 times: >>> np.random.multinomial(20, [1/6.]*6, size=1) array([[4, 1, 7, 5, 2, 1]]) It landed 4 times on 1, once on 2, etc. Now, throw the dice 20 times, and 20 times again: >>> np.random.multinomial(20, [1/6.]*6, size=2) array([[3, 4, 3, 3, 4, 3], [2, 4, 3, 4, 0, 7]]) For the first run, we threw 3 times 1, 4 times 2, etc. For the second, we threw 2 times 1, 4 times 2, etc. A loaded dice is more likely to land on number 6: >>> np.random.multinomial(100, [1/7.]*5) array([13, 16, 13, 16, 42]) """ cdef npy_intp d cdef ndarray parr "arrayObject_parr", mnarr "arrayObject_mnarr" cdef double *pix cdef long *mnix cdef npy_intp i, j, dn cdef double Sum d = len(pvals) parr = PyArray_ContiguousFromObject(pvals, NPY_DOUBLE, 1, 1) pix = PyArray_DATA(parr) if kahan_sum(pix, d-1) > (1.0 + 1e-12): raise ValueError("sum(pvals[:-1]) > 1.0") shape = _shape_from_size(size, d) multin = np.zeros(shape, int) mnarr = multin mnix = 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 return multin def dirichlet(self, object alpha, size=None): """ dirichlet(alpha, size=None) Draw samples from the Dirichlet distribution. Draw `size` samples of dimension k from a Dirichlet distribution. A Dirichlet-distributed random variable can be seen as a multivariate generalization of a Beta distribution. Dirichlet pdf is the conjugate prior of a multinomial in Bayesian inference. Parameters ---------- alpha : array Parameter of the distribution (k dimension for sample of dimension k). size : array Number of samples to draw. Returns ------- samples : ndarray, The drawn samples, of shape (alpha.ndim, size). Notes ----- .. math:: X \\approx \\prod_{i=1}^{k}{x^{\\alpha_i-1}_i} Uses the following property for computation: for each dimension, draw a random sample y_i from a standard gamma generator of shape `alpha_i`, then :math:`X = \\frac{1}{\\sum_{i=1}^k{y_i}} (y_1, \\ldots, y_n)` is Dirichlet distributed. References ---------- .. [1] David McKay, "Information Theory, Inference and Learning Algorithms," chapter 23, http://www.inference.phy.cam.ac.uk/mackay/ .. [2] Wikipedia, "Dirichlet distribution", http://en.wikipedia.org/wiki/Dirichlet_distribution Examples -------- Taking an example cited in Wikipedia, this distribution can be used if one wanted to cut strings (each of initial length 1.0) into K pieces with different lengths, where each piece had, on average, a designated average length, but allowing some variation in the relative sizes of the pieces. >>> s = np.random.dirichlet((10, 5, 3), 20).transpose() >>> plt.barh(range(20), s[0]) >>> plt.barh(range(20), s[1], left=s[0], color='g') >>> plt.barh(range(20), s[2], left=s[0]+s[1], color='r') >>> plt.title("Lengths of Strings") """ #================= # Pure python algo #================= #alpha = N.atleast_1d(alpha) #k = alpha.size #if n == 1: # val = N.zeros(k) # for i in range(k): # val[i] = sgamma(alpha[i], n) # val /= N.sum(val) #else: # val = N.zeros((k, n)) # for i in range(k): # val[i] = sgamma(alpha[i], n) # val /= N.sum(val, axis = 0) # val = val.T #return val cdef npy_intp k cdef npy_intp totsize cdef ndarray alpha_arr, val_arr cdef double *alpha_data, *val_data cdef npy_intp i, j cdef double acc, invacc k = len(alpha) alpha_arr = PyArray_ContiguousFromObject(alpha, NPY_DOUBLE, 1, 1) alpha_data = PyArray_DATA(alpha_arr) shape = _shape_from_size(size, k) diric = np.zeros(shape, np.float64) val_arr = diric val_data= PyArray_DATA(val_arr) 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 return diric # Shuffling and permutations: def shuffle(self, object x): """ shuffle(x) Modify a sequence in-place by shuffling its contents. Parameters ---------- x : array_like The array or list to be shuffled. Returns ------- None Examples -------- >>> arr = np.arange(10) >>> np.random.shuffle(arr) >>> arr [1 7 5 2 9 4 3 6 0 8] This function only shuffles the array along the first index of a multi-dimensional array: >>> arr = np.arange(9).reshape((3, 3)) >>> np.random.shuffle(arr) >>> arr array([[3, 4, 5], [6, 7, 8], [0, 1, 2]]) """ cdef npy_intp i, j i = len(x) - 1 # Logic adapted from random.shuffle() 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_like(x[0]) while i > 0: j = rk_interval(i, self.internal_state) buf[...] = x[j] x[j] = x[i] x[i] = buf i = i - 1 else: # For single-dimensional arrays, lists, and any other Python # 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] i = i - 1 def permutation(self, object x): """ permutation(x) Randomly permute a sequence, or return a permuted range. If `x` is a multi-dimensional array, it is only shuffled along its first index. Parameters ---------- x : int or array_like If `x` is an integer, randomly permute ``np.arange(x)``. If `x` is an array, make a copy and shuffle the elements randomly. Returns ------- out : ndarray Permuted sequence or array range. Examples -------- >>> np.random.permutation(10) array([1, 7, 4, 3, 0, 9, 2, 5, 8, 6]) >>> np.random.permutation([1, 4, 9, 12, 15]) array([15, 1, 9, 4, 12]) >>> arr = np.arange(9).reshape((3, 3)) >>> np.random.permutation(arr) array([[6, 7, 8], [0, 1, 2], [3, 4, 5]]) """ if isinstance(x, (int, long, np.integer)): arr = np.arange(x) else: arr = np.array(x) self.shuffle(arr) return arr _rand = RandomState() seed = _rand.seed get_state = _rand.get_state set_state = _rand.set_state random_sample = _rand.random_sample choice = _rand.choice randint = _rand.randint bytes = _rand.bytes uniform = _rand.uniform rand = _rand.rand randn = _rand.randn random_integers = _rand.random_integers standard_normal = _rand.standard_normal normal = _rand.normal beta = _rand.beta exponential = _rand.exponential standard_exponential = _rand.standard_exponential standard_gamma = _rand.standard_gamma gamma = _rand.gamma f = _rand.f noncentral_f = _rand.noncentral_f chisquare = _rand.chisquare noncentral_chisquare = _rand.noncentral_chisquare standard_cauchy = _rand.standard_cauchy standard_t = _rand.standard_t vonmises = _rand.vonmises pareto = _rand.pareto weibull = _rand.weibull power = _rand.power laplace = _rand.laplace gumbel = _rand.gumbel logistic = _rand.logistic lognormal = _rand.lognormal rayleigh = _rand.rayleigh wald = _rand.wald triangular = _rand.triangular binomial = _rand.binomial negative_binomial = _rand.negative_binomial poisson = _rand.poisson zipf = _rand.zipf geometric = _rand.geometric hypergeometric = _rand.hypergeometric logseries = _rand.logseries multivariate_normal = _rand.multivariate_normal multinomial = _rand.multinomial dirichlet = _rand.dirichlet shuffle = _rand.shuffle permutation = _rand.permutation numpy-1.8.2/numpy/random/mtrand/distributions.c0000664000175100017510000005020212370216243023006 0ustar vagrantvagrant00000000000000/* Copyright 2005 Robert Kern (robert.kern@gmail.com) * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /* The implementations of rk_hypergeometric_hyp(), rk_hypergeometric_hrua(), * and rk_triangular() were adapted from Ivan Frohne's rv.py which has this * license: * * Copyright 1998 by Ivan Frohne; Wasilla, Alaska, U.S.A. * All Rights Reserved * * Permission to use, copy, modify and distribute this software and its * documentation for any purpose, free of charge, is granted subject to the * following conditions: * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the software. * * THE SOFTWARE AND DOCUMENTATION IS PROVIDED WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHOR * OR COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM OR DAMAGES IN A CONTRACT * ACTION, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR ITS DOCUMENTATION. */ #include #include "distributions.h" #include #ifndef min #define min(x,y) ((xy)?x:y) #endif #ifndef M_PI #define M_PI 3.14159265358979323846264338328 #endif /* log-gamma function to support some of these distributions. The * algorithm comes from SPECFUN by Shanjie Zhang and Jianming Jin and their * book "Computation of Special Functions", 1996, John Wiley & Sons, Inc. */ extern double loggam(double x); double loggam(double x) { double x0, x2, xp, gl, gl0; long k, n; static double a[10] = {8.333333333333333e-02,-2.777777777777778e-03, 7.936507936507937e-04,-5.952380952380952e-04, 8.417508417508418e-04,-1.917526917526918e-03, 6.410256410256410e-03,-2.955065359477124e-02, 1.796443723688307e-01,-1.39243221690590e+00}; x0 = x; n = 0; if ((x == 1.0) || (x == 2.0)) { return 0.0; } else if (x <= 7.0) { n = (long)(7 - x); x0 = x + n; } x2 = 1.0/(x0*x0); xp = 2*M_PI; gl0 = a[9]; for (k=8; k>=0; k--) { gl0 *= x2; gl0 += a[k]; } gl = gl0/x0 + 0.5*log(xp) + (x0-0.5)*log(x0) - x0; if (x <= 7.0) { for (k=1; k<=n; k++) { gl -= log(x0-1.0); x0 -= 1.0; } } return gl; } double rk_normal(rk_state *state, double loc, double scale) { return loc + scale*rk_gauss(state); } double rk_standard_exponential(rk_state *state) { /* We use -log(1-U) since U is [0, 1) */ return -log(1.0 - rk_double(state)); } double rk_exponential(rk_state *state, double scale) { return scale * rk_standard_exponential(state); } double rk_uniform(rk_state *state, double loc, double scale) { return loc + scale*rk_double(state); } double rk_standard_gamma(rk_state *state, double shape) { double b, c; double U, V, X, Y; if (shape == 1.0) { return rk_standard_exponential(state); } else if (shape < 1.0) { for (;;) { U = rk_double(state); V = rk_standard_exponential(state); if (U <= 1.0 - shape) { X = pow(U, 1./shape); if (X <= V) { return X; } } else { Y = -log((1-U)/shape); X = pow(1.0 - shape + shape*Y, 1./shape); if (X <= (V + Y)) { return X; } } } } else { b = shape - 1./3.; c = 1./sqrt(9*b); for (;;) { do { X = rk_gauss(state); V = 1.0 + c*X; } while (V <= 0.0); V = V*V*V; U = rk_double(state); if (U < 1.0 - 0.0331*(X*X)*(X*X)) return (b*V); if (log(U) < 0.5*X*X + b*(1. - V + log(V))) return (b*V); } } } double rk_gamma(rk_state *state, double shape, double scale) { return scale * rk_standard_gamma(state, shape); } double rk_beta(rk_state *state, double a, double b) { double Ga, Gb; if ((a <= 1.0) && (b <= 1.0)) { double U, V, X, Y; /* Use Jonk's algorithm */ while (1) { U = rk_double(state); V = rk_double(state); X = pow(U, 1.0/a); Y = pow(V, 1.0/b); if ((X + Y) <= 1.0) { return X / (X + Y); } } } else { Ga = rk_standard_gamma(state, a); Gb = rk_standard_gamma(state, b); return Ga/(Ga + Gb); } } double rk_chisquare(rk_state *state, double df) { return 2.0*rk_standard_gamma(state, df/2.0); } double rk_noncentral_chisquare(rk_state *state, double df, double nonc) { double Chi2, N; Chi2 = rk_chisquare(state, df-1); N = rk_gauss(state) + sqrt(nonc); return Chi2 + N*N; } double rk_f(rk_state *state, double dfnum, double dfden) { return ((rk_chisquare(state, dfnum) * dfden) / (rk_chisquare(state, dfden) * dfnum)); } double rk_noncentral_f(rk_state *state, double dfnum, double dfden, double nonc) { double t = rk_noncentral_chisquare(state, dfnum, nonc) * dfden; return t / (rk_chisquare(state, dfden) * dfnum); } long rk_binomial_btpe(rk_state *state, long n, double p) { double r,q,fm,p1,xm,xl,xr,c,laml,lamr,p2,p3,p4; double a,u,v,s,F,rho,t,A,nrq,x1,x2,f1,f2,z,z2,w,w2,x; long m,y,k,i; if (!(state->has_binomial) || (state->nsave != n) || (state->psave != p)) { /* initialize */ state->nsave = n; state->psave = p; state->has_binomial = 1; state->r = r = min(p, 1.0-p); state->q = q = 1.0 - r; state->fm = fm = n*r+r; state->m = m = (long)floor(state->fm); state->p1 = p1 = floor(2.195*sqrt(n*r*q)-4.6*q) + 0.5; state->xm = xm = m + 0.5; state->xl = xl = xm - p1; state->xr = xr = xm + p1; state->c = c = 0.134 + 20.5/(15.3 + m); a = (fm - xl)/(fm-xl*r); state->laml = laml = a*(1.0 + a/2.0); a = (xr - fm)/(xr*q); state->lamr = lamr = a*(1.0 + a/2.0); state->p2 = p2 = p1*(1.0 + 2.0*c); state->p3 = p3 = p2 + c/laml; state->p4 = p4 = p3 + c/lamr; } else { r = state->r; q = state->q; fm = state->fm; m = state->m; p1 = state->p1; xm = state->xm; xl = state->xl; xr = state->xr; c = state->c; laml = state->laml; lamr = state->lamr; p2 = state->p2; p3 = state->p3; p4 = state->p4; } /* sigh ... */ Step10: nrq = n*r*q; u = rk_double(state)*p4; v = rk_double(state); if (u > p1) goto Step20; y = (long)floor(xm - p1*v + u); goto Step60; Step20: if (u > p2) goto Step30; x = xl + (u - p1)/c; v = v*c + 1.0 - fabs(m - x + 0.5)/p1; if (v > 1.0) goto Step10; y = (long)floor(x); goto Step50; Step30: if (u > p3) goto Step40; y = (long)floor(xl + log(v)/laml); if (y < 0) goto Step10; v = v*(u-p2)*laml; goto Step50; Step40: y = (int)floor(xr - log(v)/lamr); if (y > n) goto Step10; v = v*(u-p3)*lamr; Step50: k = fabs(y - m); if ((k > 20) && (k < ((nrq)/2.0 - 1))) goto Step52; s = r/q; a = s*(n+1); F = 1.0; if (m < y) { for (i=m; i<=y; i++) { F *= (a/i - s); } } else if (m > y) { for (i=y; i<=m; i++) { F /= (a/i - s); } } else { if (v > F) goto Step10; goto Step60; } Step52: rho = (k/(nrq))*((k*(k/3.0 + 0.625) + 0.16666666666666666)/nrq + 0.5); t = -k*k/(2*nrq); A = log(v); if (A < (t - rho)) goto Step60; if (A > (t + rho)) goto Step10; x1 = y+1; f1 = m+1; z = n+1-m; w = n-y+1; x2 = x1*x1; f2 = f1*f1; z2 = z*z; w2 = w*w; if (A > (xm*log(f1/x1) + (n-m+0.5)*log(z/w) + (y-m)*log(w*r/(x1*q)) + (13680.-(462.-(132.-(99.-140./f2)/f2)/f2)/f2)/f1/166320. + (13680.-(462.-(132.-(99.-140./z2)/z2)/z2)/z2)/z/166320. + (13680.-(462.-(132.-(99.-140./x2)/x2)/x2)/x2)/x1/166320. + (13680.-(462.-(132.-(99.-140./w2)/w2)/w2)/w2)/w/166320.)) { goto Step10; } Step60: if (p > 0.5) { y = n - y; } return y; } long rk_binomial_inversion(rk_state *state, long n, double p) { double q, qn, np, px, U; long X, bound; if (!(state->has_binomial) || (state->nsave != n) || (state->psave != p)) { state->nsave = n; state->psave = p; state->has_binomial = 1; state->q = q = 1.0 - p; state->r = qn = exp(n * log(q)); state->c = np = n*p; state->m = bound = min(n, np + 10.0*sqrt(np*q + 1)); } else { q = state->q; qn = state->r; np = state->c; bound = state->m; } X = 0; px = qn; U = rk_double(state); while (U > px) { X++; if (X > bound) { X = 0; px = qn; U = rk_double(state); } else { U -= px; px = ((n-X+1) * p * px)/(X*q); } } return X; } long rk_binomial(rk_state *state, long n, double p) { double q; if (p <= 0.5) { if (p*n <= 30.0) { return rk_binomial_inversion(state, n, p); } else { return rk_binomial_btpe(state, n, p); } } else { q = 1.0-p; if (q*n <= 30.0) { return n - rk_binomial_inversion(state, n, q); } else { return n - rk_binomial_btpe(state, n, q); } } } long rk_negative_binomial(rk_state *state, double n, double p) { double Y; Y = rk_gamma(state, n, (1-p)/p); return rk_poisson(state, Y); } long rk_poisson_mult(rk_state *state, double lam) { long X; double prod, U, enlam; enlam = exp(-lam); X = 0; prod = 1.0; while (1) { U = rk_double(state); prod *= U; if (prod > enlam) { X += 1; } else { return X; } } } #define LS2PI 0.91893853320467267 #define TWELFTH 0.083333333333333333333333 long rk_poisson_ptrs(rk_state *state, double lam) { long k; double U, V, slam, loglam, a, b, invalpha, vr, us; slam = sqrt(lam); loglam = log(lam); b = 0.931 + 2.53*slam; a = -0.059 + 0.02483*b; invalpha = 1.1239 + 1.1328/(b-3.4); vr = 0.9277 - 3.6224/(b-2); while (1) { U = rk_double(state) - 0.5; V = rk_double(state); us = 0.5 - fabs(U); k = (long)floor((2*a/us + b)*U + lam + 0.43); if ((us >= 0.07) && (V <= vr)) { return k; } if ((k < 0) || ((us < 0.013) && (V > us))) { continue; } if ((log(V) + log(invalpha) - log(a/(us*us)+b)) <= (-lam + k*loglam - loggam(k+1))) { return k; } } } long rk_poisson(rk_state *state, double lam) { if (lam >= 10) { return rk_poisson_ptrs(state, lam); } else if (lam == 0) { return 0; } else { return rk_poisson_mult(state, lam); } } double rk_standard_cauchy(rk_state *state) { return rk_gauss(state) / rk_gauss(state); } double rk_standard_t(rk_state *state, double df) { double N, G, X; N = rk_gauss(state); G = rk_standard_gamma(state, df/2); X = sqrt(df/2)*N/sqrt(G); return X; } /* Uses the rejection algorithm compared against the wrapped Cauchy distribution suggested by Best and Fisher and documented in Chapter 9 of Luc's Non-Uniform Random Variate Generation. http://cg.scs.carleton.ca/~luc/rnbookindex.html (but corrected to match the algorithm in R and Python) */ double rk_vonmises(rk_state *state, double mu, double kappa) { double r, rho, s; double U, V, W, Y, Z; double result, mod; int neg; if (kappa < 1e-8) { return M_PI * (2*rk_double(state)-1); } else { r = 1 + sqrt(1 + 4*kappa*kappa); rho = (r - sqrt(2*r))/(2*kappa); s = (1 + rho*rho)/(2*rho); while (1) { U = rk_double(state); Z = cos(M_PI*U); W = (1 + s*Z)/(s + Z); Y = kappa * (s - W); V = rk_double(state); if ((Y*(2-Y) - V >= 0) || (log(Y/V)+1 - Y >= 0)) { break; } } U = rk_double(state); result = acos(W); if (U < 0.5) { result = -result; } result += mu; neg = (result < 0); mod = fabs(result); mod = (fmod(mod+M_PI, 2*M_PI)-M_PI); if (neg) { mod *= -1; } return mod; } } double rk_pareto(rk_state *state, double a) { return exp(rk_standard_exponential(state)/a) - 1; } double rk_weibull(rk_state *state, double a) { return pow(rk_standard_exponential(state), 1./a); } double rk_power(rk_state *state, double a) { return pow(1 - exp(-rk_standard_exponential(state)), 1./a); } double rk_laplace(rk_state *state, double loc, double scale) { double U; U = rk_double(state); if (U < 0.5) { U = loc + scale * log(U + U); } else { U = loc - scale * log(2.0 - U - U); } return U; } double rk_gumbel(rk_state *state, double loc, double scale) { double U; U = 1.0 - rk_double(state); return loc - scale * log(-log(U)); } double rk_logistic(rk_state *state, double loc, double scale) { double U; U = rk_double(state); return loc + scale * log(U/(1.0 - U)); } double rk_lognormal(rk_state *state, double mean, double sigma) { return exp(rk_normal(state, mean, sigma)); } double rk_rayleigh(rk_state *state, double mode) { return mode*sqrt(-2.0 * log(1.0 - rk_double(state))); } double rk_wald(rk_state *state, double mean, double scale) { double U, X, Y; double mu_2l; mu_2l = mean / (2*scale); Y = rk_gauss(state); Y = mean*Y*Y; X = mean + mu_2l*(Y - sqrt(4*scale*Y + Y*Y)); U = rk_double(state); if (U <= mean/(mean+X)) { return X; } else { return mean*mean/X; } } long rk_zipf(rk_state *state, double a) { double T, U, V; long X; double am1, b; am1 = a - 1.0; b = pow(2.0, am1); do { U = 1.0-rk_double(state); V = rk_double(state); X = (long)floor(pow(U, -1.0/am1)); /* The real result may be above what can be represented in a signed * long. It will get casted to -sys.maxint-1. Since this is * a straightforward rejection algorithm, we can just reject this value * in the rejection condition below. This function then models a Zipf * distribution truncated to sys.maxint. */ T = pow(1.0 + 1.0/X, am1); } while (((V*X*(T-1.0)/(b-1.0)) > (T/b)) || X < 1); return X; } long rk_geometric_search(rk_state *state, double p) { double U; long X; double sum, prod, q; X = 1; sum = prod = p; q = 1.0 - p; U = rk_double(state); while (U > sum) { prod *= q; sum += prod; X++; } return X; } long rk_geometric_inversion(rk_state *state, double p) { return (long)ceil(log(1.0-rk_double(state))/log(1.0-p)); } long rk_geometric(rk_state *state, double p) { if (p >= 0.333333333333333333333333) { return rk_geometric_search(state, p); } else { return rk_geometric_inversion(state, p); } } long rk_hypergeometric_hyp(rk_state *state, long good, long bad, long sample) { long d1, K, Z; double d2, U, Y; d1 = bad + good - sample; d2 = (double)min(bad, good); Y = d2; K = sample; while (Y > 0.0) { U = rk_double(state); Y -= (long)floor(U + Y/(d1 + K)); K--; if (K == 0) break; } Z = (long)(d2 - Y); if (good > bad) Z = sample - Z; return Z; } /* D1 = 2*sqrt(2/e) */ /* D2 = 3 - 2*sqrt(3/e) */ #define D1 1.7155277699214135 #define D2 0.8989161620588988 long rk_hypergeometric_hrua(rk_state *state, long good, long bad, long sample) { long mingoodbad, maxgoodbad, popsize, m, d9; double d4, d5, d6, d7, d8, d10, d11; long Z; double T, W, X, Y; mingoodbad = min(good, bad); popsize = good + bad; maxgoodbad = max(good, bad); m = min(sample, popsize - sample); d4 = ((double)mingoodbad) / popsize; d5 = 1.0 - d4; d6 = m*d4 + 0.5; d7 = sqrt((popsize - m) * sample * d4 *d5 / (popsize-1) + 0.5); d8 = D1*d7 + D2; d9 = (long)floor((double)((m+1)*(mingoodbad+1))/(popsize+2)); d10 = (loggam(d9+1) + loggam(mingoodbad-d9+1) + loggam(m-d9+1) + loggam(maxgoodbad-m+d9+1)); d11 = min(min(m, mingoodbad)+1.0, floor(d6+16*d7)); /* 16 for 16-decimal-digit precision in D1 and D2 */ while (1) { X = rk_double(state); Y = rk_double(state); W = d6 + d8*(Y- 0.5)/X; /* fast rejection: */ if ((W < 0.0) || (W >= d11)) continue; Z = (long)floor(W); T = d10 - (loggam(Z+1) + loggam(mingoodbad-Z+1) + loggam(m-Z+1) + loggam(maxgoodbad-m+Z+1)); /* fast acceptance: */ if ((X*(4.0-X)-3.0) <= T) break; /* fast rejection: */ if (X*(X-T) >= 1) continue; if (2.0*log(X) <= T) break; /* acceptance */ } /* this is a correction to HRUA* by Ivan Frohne in rv.py */ if (good > bad) Z = m - Z; /* another fix from rv.py to allow sample to exceed popsize/2 */ if (m < sample) Z = good - Z; return Z; } #undef D1 #undef D2 long rk_hypergeometric(rk_state *state, long good, long bad, long sample) { if (sample > 10) { return rk_hypergeometric_hrua(state, good, bad, sample); } else { return rk_hypergeometric_hyp(state, good, bad, sample); } } double rk_triangular(rk_state *state, double left, double mode, double right) { double base, leftbase, ratio, leftprod, rightprod; double U; base = right - left; leftbase = mode - left; ratio = leftbase / base; leftprod = leftbase*base; rightprod = (right - mode)*base; U = rk_double(state); if (U <= ratio) { return left + sqrt(U*leftprod); } else { return right - sqrt((1.0 - U) * rightprod); } } long rk_logseries(rk_state *state, double p) { double q, r, U, V; long result; r = log(1.0 - p); while (1) { V = rk_double(state); if (V >= p) { return 1; } U = rk_double(state); q = 1.0 - exp(r*U); if (V <= q*q) { result = (long)floor(1 + log(V)/log(q)); if (result < 1) { continue; } else { return result; } } if (V >= q) { return 1; } return 2; } } numpy-1.8.2/numpy/random/mtrand/randomkit.c0000664000175100017510000002461412370216242022103 0ustar vagrantvagrant00000000000000/* Random kit 1.3 */ /* * Copyright (c) 2003-2005, Jean-Sebastien Roy (js@jeannot.org) * * The rk_random and rk_seed functions algorithms and the original design of * the Mersenne Twister RNG: * * Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura, * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. The names of its contributors may not be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Original algorithm for the implementation of rk_interval function from * Richard J. Wagner's implementation of the Mersenne Twister RNG, optimised by * Magnus Jonsson. * * Constants used in the rk_double implementation by Isaku Wada. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /* static char const rcsid[] = "@(#) $Jeannot: randomkit.c,v 1.28 2005/07/21 22:14:09 js Exp $"; */ #include #include #include #include #include #include #ifdef _WIN32 /* * Windows * XXX: we have to use this ugly defined(__GNUC__) because it is not easy to * detect the compiler used in distutils itself */ #if (defined(__GNUC__) && defined(NPY_NEEDS_MINGW_TIME_WORKAROUND)) /* * FIXME: ideally, we should set this to the real version of MSVCRT. We need * something higher than 0x601 to enable _ftime64 and co */ #define __MSVCRT_VERSION__ 0x0700 #include #include /* * mingw msvcr lib import wrongly export _ftime, which does not exist in the * actual msvc runtime for version >= 8; we make it an alias to _ftime64, which * is available in those versions of the runtime */ #define _FTIME(x) _ftime64((x)) #else #include #include #define _FTIME(x) _ftime((x)) #endif #ifndef RK_NO_WINCRYPT /* Windows crypto */ #ifndef _WIN32_WINNT #define _WIN32_WINNT 0x0400 #endif #include #include #endif #else /* Unix */ #include #include #include #endif #include "randomkit.h" #ifndef RK_DEV_URANDOM #define RK_DEV_URANDOM "/dev/urandom" #endif #ifndef RK_DEV_RANDOM #define RK_DEV_RANDOM "/dev/random" #endif char *rk_strerror[RK_ERR_MAX] = { "no error", "random device unvavailable" }; /* static functions */ static unsigned long rk_hash(unsigned long key); void rk_seed(unsigned long seed, rk_state *state) { int pos; seed &= 0xffffffffUL; /* Knuth's PRNG as used in the Mersenne Twister reference implementation */ for (pos = 0; pos < RK_STATE_LEN; pos++) { state->key[pos] = seed; seed = (1812433253UL * (seed ^ (seed >> 30)) + pos + 1) & 0xffffffffUL; } state->pos = RK_STATE_LEN; state->gauss = 0; state->has_gauss = 0; state->has_binomial = 0; } /* Thomas Wang 32 bits integer hash function */ unsigned long rk_hash(unsigned long key) { key += ~(key << 15); key ^= (key >> 10); key += (key << 3); key ^= (key >> 6); key += ~(key << 11); key ^= (key >> 16); return key; } rk_error rk_randomseed(rk_state *state) { #ifndef _WIN32 struct timeval tv; #else struct _timeb tv; #endif int i; if (rk_devfill(state->key, sizeof(state->key), 0) == RK_NOERR) { /* ensures non-zero key */ state->key[0] |= 0x80000000UL; state->pos = RK_STATE_LEN; state->gauss = 0; state->has_gauss = 0; state->has_binomial = 0; for (i = 0; i < 624; i++) { state->key[i] &= 0xffffffffUL; } return RK_NOERR; } #ifndef _WIN32 gettimeofday(&tv, NULL); rk_seed(rk_hash(getpid()) ^ rk_hash(tv.tv_sec) ^ rk_hash(tv.tv_usec) ^ rk_hash(clock()), state); #else _FTIME(&tv); rk_seed(rk_hash(tv.time) ^ rk_hash(tv.millitm) ^ rk_hash(clock()), state); #endif return RK_ENODEV; } /* Magic Mersenne Twister constants */ #define N 624 #define M 397 #define MATRIX_A 0x9908b0dfUL #define UPPER_MASK 0x80000000UL #define LOWER_MASK 0x7fffffffUL /* Slightly optimised reference implementation of the Mersenne Twister */ unsigned long rk_random(rk_state *state) { unsigned long y; if (state->pos == RK_STATE_LEN) { int i; for (i = 0; i < N - M; i++) { y = (state->key[i] & UPPER_MASK) | (state->key[i+1] & LOWER_MASK); state->key[i] = state->key[i+M] ^ (y>>1) ^ (-(y & 1) & MATRIX_A); } for (; i < N - 1; i++) { y = (state->key[i] & UPPER_MASK) | (state->key[i+1] & LOWER_MASK); state->key[i] = state->key[i+(M-N)] ^ (y>>1) ^ (-(y & 1) & MATRIX_A); } y = (state->key[N - 1] & UPPER_MASK) | (state->key[0] & LOWER_MASK); state->key[N - 1] = state->key[M - 1] ^ (y >> 1) ^ (-(y & 1) & MATRIX_A); state->pos = 0; } y = state->key[state->pos++]; /* Tempering */ y ^= (y >> 11); y ^= (y << 7) & 0x9d2c5680UL; y ^= (y << 15) & 0xefc60000UL; y ^= (y >> 18); return y; } long rk_long(rk_state *state) { return rk_ulong(state) >> 1; } unsigned long rk_ulong(rk_state *state) { #if ULONG_MAX <= 0xffffffffUL return rk_random(state); #else return (rk_random(state) << 32) | (rk_random(state)); #endif } unsigned long rk_interval(unsigned long max, rk_state *state) { unsigned long mask = max, value; if (max == 0) { return 0; } /* Smallest bit mask >= max */ mask |= mask >> 1; mask |= mask >> 2; mask |= mask >> 4; mask |= mask >> 8; mask |= mask >> 16; #if ULONG_MAX > 0xffffffffUL mask |= mask >> 32; #endif /* Search a random value in [0..mask] <= max */ #if ULONG_MAX > 0xffffffffUL if (max <= 0xffffffffUL) { while ((value = (rk_random(state) & mask)) > max); } else { while ((value = (rk_ulong(state) & mask)) > max); } #else while ((value = (rk_ulong(state) & mask)) > max); #endif return value; } double rk_double(rk_state *state) { /* shifts : 67108864 = 0x4000000, 9007199254740992 = 0x20000000000000 */ long a = rk_random(state) >> 5, b = rk_random(state) >> 6; return (a * 67108864.0 + b) / 9007199254740992.0; } void rk_fill(void *buffer, size_t size, rk_state *state) { unsigned long r; unsigned char *buf = buffer; for (; size >= 4; size -= 4) { r = rk_random(state); *(buf++) = r & 0xFF; *(buf++) = (r >> 8) & 0xFF; *(buf++) = (r >> 16) & 0xFF; *(buf++) = (r >> 24) & 0xFF; } if (!size) { return; } r = rk_random(state); for (; size; r >>= 8, size --) { *(buf++) = (unsigned char)(r & 0xFF); } } rk_error rk_devfill(void *buffer, size_t size, int strong) { #ifndef _WIN32 FILE *rfile; int done; if (strong) { rfile = fopen(RK_DEV_RANDOM, "rb"); } else { rfile = fopen(RK_DEV_URANDOM, "rb"); } if (rfile == NULL) { return RK_ENODEV; } done = fread(buffer, size, 1, rfile); fclose(rfile); if (done) { return RK_NOERR; } #else #ifndef RK_NO_WINCRYPT HCRYPTPROV hCryptProv; BOOL done; if (!CryptAcquireContext(&hCryptProv, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT) || !hCryptProv) { return RK_ENODEV; } done = CryptGenRandom(hCryptProv, size, (unsigned char *)buffer); CryptReleaseContext(hCryptProv, 0); if (done) { return RK_NOERR; } #endif #endif return RK_ENODEV; } rk_error rk_altfill(void *buffer, size_t size, int strong, rk_state *state) { rk_error err; err = rk_devfill(buffer, size, strong); if (err) { rk_fill(buffer, size, state); } return err; } double rk_gauss(rk_state *state) { if (state->has_gauss) { const double tmp = state->gauss; state->gauss = 0; state->has_gauss = 0; return tmp; } else { double f, x1, x2, r2; do { x1 = 2.0*rk_double(state) - 1.0; x2 = 2.0*rk_double(state) - 1.0; r2 = x1*x1 + x2*x2; } while (r2 >= 1.0 || r2 == 0.0); /* Box-Muller transform */ f = sqrt(-2.0*log(r2)/r2); /* Keep for next call */ state->gauss = f*x1; state->has_gauss = 1; return f*x2; } } numpy-1.8.2/numpy/random/mtrand/initarray.c0000664000175100017510000001235512370216242022114 0ustar vagrantvagrant00000000000000/* * These function have been adapted from Python 2.4.1's _randommodule.c * * The following changes have been made to it in 2005 by Robert Kern: * * * init_by_array has been declared extern, has a void return, and uses the * rk_state structure to hold its data. * * The original file has the following verbatim comments: * * ------------------------------------------------------------------ * The code in this module was based on a download from: * http://www.math.keio.ac.jp/~matumoto/MT2002/emt19937ar.html * * It was modified in 2002 by Raymond Hettinger as follows: * * * the principal computational lines untouched except for tabbing. * * * renamed genrand_res53() to random_random() and wrapped * in python calling/return code. * * * genrand_int32() and the helper functions, init_genrand() * and init_by_array(), were declared static, wrapped in * Python calling/return code. also, their global data * references were replaced with structure references. * * * unused functions from the original were deleted. * new, original C python code was added to implement the * Random() interface. * * The following are the verbatim comments from the original code: * * A C-program for MT19937, with initialization improved 2002/1/26. * Coded by Takuji Nishimura and Makoto Matsumoto. * * Before using, initialize the state by using init_genrand(seed) * or init_by_array(init_key, key_length). * * Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura, * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. The names of its contributors may not be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * * Any feedback is very welcome. * http://www.math.keio.ac.jp/matumoto/emt.html * email: matumoto@math.keio.ac.jp */ #define NPY_NO_DEPRECATED_API NPY_API_VERSION #include "initarray.h" static void init_genrand(rk_state *self, unsigned long s); /* initializes mt[RK_STATE_LEN] with a seed */ static void init_genrand(rk_state *self, unsigned long s) { int mti; unsigned long *mt = self->key; mt[0] = s & 0xffffffffUL; for (mti = 1; mti < RK_STATE_LEN; mti++) { /* * See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. * In the previous versions, MSBs of the seed affect * only MSBs of the array mt[]. * 2002/01/09 modified by Makoto Matsumoto */ mt[mti] = (1812433253UL * (mt[mti-1] ^ (mt[mti-1] >> 30)) + mti); /* for > 32 bit machines */ mt[mti] &= 0xffffffffUL; } self->pos = mti; return; } /* * initialize by an array with array-length * init_key is the array for initializing keys * key_length is its length */ extern void init_by_array(rk_state *self, unsigned long init_key[], npy_intp key_length) { /* was signed in the original code. RDH 12/16/2002 */ npy_intp i = 1; npy_intp j = 0; unsigned long *mt = self->key; npy_intp k; init_genrand(self, 19650218UL); k = (RK_STATE_LEN > key_length ? RK_STATE_LEN : key_length); for (; k; k--) { /* non linear */ mt[i] = (mt[i] ^ ((mt[i - 1] ^ (mt[i - 1] >> 30)) * 1664525UL)) + init_key[j] + j; /* for > 32 bit machines */ mt[i] &= 0xffffffffUL; i++; j++; if (i >= RK_STATE_LEN) { mt[0] = mt[RK_STATE_LEN - 1]; i = 1; } if (j >= key_length) { j = 0; } } for (k = RK_STATE_LEN - 1; k; k--) { mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1566083941UL)) - i; /* non linear */ mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */ i++; if (i >= RK_STATE_LEN) { mt[0] = mt[RK_STATE_LEN - 1]; i = 1; } } mt[0] = 0x80000000UL; /* MSB is 1; assuring non-zero initial array */ self->gauss = 0; self->has_gauss = 0; self->has_binomial = 0; } numpy-1.8.2/numpy/random/mtrand/mtrand.c0000664000175100017510000534362512370216243021414 0ustar vagrantvagrant00000000000000/* Generated by Cython 0.19 on Thu Feb 27 20:15:06 2014 */ #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 /* 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 #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 #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":535 * return shape * * 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_RaiseArgtupleInvalid(const char* func_name, int exact, Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found); /*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 int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb); /*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*/ #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 PyObject *__pyx_pf_6mtrand__shape_from_size(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_size, PyObject *__pyx_v_d); /* proto */ 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__d[] = "d"; 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_198[] = "/home/jtaylor/prog/numpy/numpy/random/mtrand/mtrand.pyx"; static char __pyx_k_201[] = "standard_exponential"; static char __pyx_k_202[] = "noncentral_chisquare"; static char __pyx_k_203[] = "RandomState.random_sample (line 730)"; static char __pyx_k_204[] = "\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 \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_205[] = "RandomState.tomaxint (line 773)"; static char __pyx_k_206[] = "\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_207[] = "RandomState.randint (line 820)"; static char __pyx_k_208[] = "\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_209[] = "RandomState.bytes (line 900)"; static char __pyx_k_210[] = "\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_211[] = "RandomState.choice (line 928)"; static char __pyx_k_212[] = "\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_213[] = "RandomState.uniform (line 1100)"; static char __pyx_k_214[] = "\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_215[] = "RandomState.rand (line 1187)"; static char __pyx_k_216[] = "\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_217[] = "RandomState.randn (line 1231)"; static char __pyx_k_218[] = "\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_219[] = "RandomState.random_integers (line 1288)"; static char __pyx_k_220[] = "\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 \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_221[] = "RandomState.standard_normal (line 1366)"; static char __pyx_k_222[] = "\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_223[] = "RandomState.normal (line 1398)"; static char __pyx_k_224[] = "\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_225[] = "RandomState.standard_exponential (line 1611)"; static char __pyx_k_226[] = "\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_227[] = "RandomState.standard_gamma (line 1639)"; static char __pyx_k_228[] = "\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_229[] = "RandomState.gamma (line 1721)"; static char __pyx_k_230[] = "\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_231[] = "RandomState.f (line 1812)"; static char __pyx_k_232[] = "\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_233[] = "RandomState.noncentral_f (line 1914)"; static char __pyx_k_234[] = "\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_235[] = "RandomState.chisquare (line 2009)"; static char __pyx_k_236[] = "\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 `_\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_237[] = "RandomState.noncentral_chisquare (line 2087)"; static char __pyx_k_238[] = "\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_239[] = "RandomState.standard_cauchy (line 2179)"; static char __pyx_k_240[] = "\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_241[] = "RandomState.standard_t (line 2240)"; static char __pyx_k_242[] = "\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=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_245[] = "RandomState.pareto (line 2435)"; static char __pyx_k_246[] = "\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_247[] = "RandomState.weibull (line 2531)"; static char __pyx_k_248[] = "\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_249[] = "RandomState.power (line 2631)"; static char __pyx_k_250[] = "\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_251[] = "RandomState.laplace (line 2740)"; static char __pyx_k_252[] = "\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_253[] = "RandomState.gumbel (line 2830)"; static char __pyx_k_254[] = "\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_255[] = "RandomState.logistic (line 2961)"; static char __pyx_k_256[] = "\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_257[] = "RandomState.lognormal (line 3049)"; static char __pyx_k_258[] = "\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_259[] = "RandomState.rayleigh (line 3170)"; static char __pyx_k_260[] = "\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_261[] = "RandomState.wald (line 3242)"; static char __pyx_k_262[] = "\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_263[] = "RandomState.triangular (line 3328)"; static char __pyx_k_264[] = "\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_265[] = "RandomState.binomial (line 3416)"; static char __pyx_k_266[] = "\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_267[] = "RandomState.negative_binomial (line 3524)"; static char __pyx_k_268[] = "\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>> 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_271[] = "RandomState.zipf (line 3690)"; static char __pyx_k_272[] = "\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_273[] = "RandomState.geometric (line 3778)"; static char __pyx_k_274[] = "\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_275[] = "RandomState.hypergeometric (line 3844)"; static char __pyx_k_276[] = "\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_277[] = "RandomState.logseries (line 3963)"; static char __pyx_k_278[] = "\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_279[] = "RandomState.multivariate_normal (line 4058)"; static char __pyx_k_280[] = "\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_281[] = "RandomState.multinomial (line 4190)"; static char __pyx_k_282[] = "\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_283[] = "RandomState.dirichlet (line 4278)"; static char __pyx_k_284[] = "\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_285[] = "RandomState.shuffle (line 4389)"; static char __pyx_k_286[] = "\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_287[] = "RandomState.permutation (line 4448)"; static char __pyx_k_288[] = "\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__fields[] = "fields"; static char __pyx_k__gumbel[] = "gumbel"; static char __pyx_k__mtrand[] = "mtrand"; 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__empty_like[] = "empty_like"; 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___shape_from_size[] = "_shape_from_size"; 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_kp_s_198; static PyObject *__pyx_kp_s_20; static PyObject *__pyx_n_s_201; static PyObject *__pyx_n_s_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_u_287; static PyObject *__pyx_kp_u_288; 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___shape_from_size; 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__d; 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__empty_like; static PyObject *__pyx_n_s__equal; static PyObject *__pyx_n_s__exponential; static PyObject *__pyx_n_s__f; static PyObject *__pyx_n_s__fields; 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__mtrand; 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_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_196; static PyObject *__pyx_k_tuple_199; static PyObject *__pyx_k_tuple_200; static PyObject *__pyx_k_codeobj_197; /* "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 = 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 = np.empty(size, np.float64) # <<<<<<<<<<<<<< * length = PyArray_SIZE(array) * array_data = 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 = np.empty(size, np.float64) * length = PyArray_SIZE(array) # <<<<<<<<<<<<<< * array_data = PyArray_DATA(array) * for i from 0 <= i < length: */ __pyx_v_length = PyArray_SIZE(arrayObject); /* "mtrand.pyx":140 * array = np.empty(size, np.float64) * length = PyArray_SIZE(array) * array_data = 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 = 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 = 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 = 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 = np.empty(size, np.float64) # <<<<<<<<<<<<<< * length = PyArray_SIZE(array) * array_data = 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 = np.empty(size, np.float64) * length = PyArray_SIZE(array) # <<<<<<<<<<<<<< * array_data = PyArray_DATA(array) * for i from 0 <= i < length: */ __pyx_v_length = PyArray_SIZE(arrayObject); /* "mtrand.pyx":157 * array = np.empty(size, np.float64) * length = PyArray_SIZE(array) * array_data = 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 = 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 = 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 = 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 = PyArray_SimpleNew(PyArray_NDIM(oa), * PyArray_DIMS(oa) , NPY_DOUBLE) # <<<<<<<<<<<<<< * length = PyArray_SIZE(array) * array_data = 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 = PyArray_SimpleNew(PyArray_NDIM(oa), * PyArray_DIMS(oa) , NPY_DOUBLE) * length = PyArray_SIZE(array) # <<<<<<<<<<<<<< * array_data = PyArray_DATA(array) * itera = PyArray_IterNew(oa) */ __pyx_v_length = PyArray_SIZE(arrayObject); /* "mtrand.pyx":175 * PyArray_DIMS(oa) , NPY_DOUBLE) * length = PyArray_SIZE(array) * array_data = PyArray_DATA(array) # <<<<<<<<<<<<<< * itera = PyArray_IterNew(oa) * for i from 0 <= i < length: */ __pyx_v_array_data = ((double *)PyArray_DATA(arrayObject)); /* "mtrand.pyx":176 * length = PyArray_SIZE(array) * array_data = PyArray_DATA(array) * itera = PyArray_IterNew(oa) # <<<<<<<<<<<<<< * for i from 0 <= i < length: * array_data[i] = func(state, ((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 = PyArray_DATA(array) * itera = PyArray_IterNew(oa) * for i from 0 <= i < length: # <<<<<<<<<<<<<< * array_data[i] = func(state, ((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 = PyArray_IterNew(oa) * for i from 0 <= i < length: * array_data[i] = func(state, ((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, ((itera.dataptr))[0]) * PyArray_ITER_NEXT(itera) # <<<<<<<<<<<<<< * else: * array = np.empty(size, np.float64) */ PyArray_ITER_NEXT(__pyx_v_itera); } goto __pyx_L3; } /*else*/ { /* "mtrand.pyx":181 * PyArray_ITER_NEXT(itera) * else: * array = np.empty(size, np.float64) # <<<<<<<<<<<<<< * array_data = PyArray_DATA(array) * multi = PyArray_MultiIterNew(2, 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 = np.empty(size, np.float64) * array_data = PyArray_DATA(array) # <<<<<<<<<<<<<< * multi = PyArray_MultiIterNew(2, array, * oa) */ __pyx_v_array_data = ((double *)PyArray_DATA(arrayObject)); /* "mtrand.pyx":184 * array_data = PyArray_DATA(array) * multi = PyArray_MultiIterNew(2, array, * 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 = PyArray_MultiIterNew(2, array, * 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 * oa) * if (multi.size != PyArray_SIZE(array)): * raise ValueError("size is not compatible with inputs") # <<<<<<<<<<<<<< * for i from 0 <= i < multi.size: * oa_data = 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 = 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 = 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 = 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 = 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 = 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 = np.empty(size, np.float64) # <<<<<<<<<<<<<< * length = PyArray_SIZE(array) * array_data = 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 = np.empty(size, np.float64) * length = PyArray_SIZE(array) # <<<<<<<<<<<<<< * array_data = PyArray_DATA(array) * for i from 0 <= i < length: */ __pyx_v_length = PyArray_SIZE(arrayObject); /* "mtrand.pyx":205 * array = np.empty(size, np.float64) * length = PyArray_SIZE(array) * array_data = 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 = 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 = 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 = PyArray_MultiIterNew(2, oa, ob) * array = 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 = PyArray_MultiIterNew(2, oa, ob) # <<<<<<<<<<<<<< * array = PyArray_SimpleNew(multi.nd, multi.dimensions, NPY_DOUBLE) * array_data = 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 = PyArray_MultiIterNew(2, oa, ob) * array = PyArray_SimpleNew(multi.nd, multi.dimensions, NPY_DOUBLE) # <<<<<<<<<<<<<< * array_data = 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 = PyArray_MultiIterNew(2, oa, ob) * array = PyArray_SimpleNew(multi.nd, multi.dimensions, NPY_DOUBLE) * array_data = PyArray_DATA(array) # <<<<<<<<<<<<<< * for i from 0 <= i < multi.size: * oa_data = PyArray_MultiIter_DATA(multi, 0) */ __pyx_v_array_data = ((double *)PyArray_DATA(arrayObject)); /* "mtrand.pyx":225 * array = PyArray_SimpleNew(multi.nd, multi.dimensions, NPY_DOUBLE) * array_data = PyArray_DATA(array) * for i from 0 <= i < multi.size: # <<<<<<<<<<<<<< * oa_data = PyArray_MultiIter_DATA(multi, 0) * ob_data = 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 = PyArray_DATA(array) * for i from 0 <= i < multi.size: * oa_data = PyArray_MultiIter_DATA(multi, 0) # <<<<<<<<<<<<<< * ob_data = 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 = PyArray_MultiIter_DATA(multi, 0) * ob_data = 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 = PyArray_MultiIter_DATA(multi, 0) * ob_data = 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 = PyArray_MultiIter_DATA(multi, 1) * array_data[i] = func(state, oa_data[0], ob_data[0]) * PyArray_MultiIter_NEXT(multi) # <<<<<<<<<<<<<< * else: * array = np.empty(size, np.float64) */ PyArray_MultiIter_NEXT(__pyx_v_multi); } goto __pyx_L3; } /*else*/ { /* "mtrand.pyx":231 * PyArray_MultiIter_NEXT(multi) * else: * array = np.empty(size, np.float64) # <<<<<<<<<<<<<< * array_data = PyArray_DATA(array) * multi = PyArray_MultiIterNew(3, array, oa, 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 = np.empty(size, np.float64) * array_data = PyArray_DATA(array) # <<<<<<<<<<<<<< * multi = PyArray_MultiIterNew(3, array, oa, ob) * if (multi.size != PyArray_SIZE(array)): */ __pyx_v_array_data = ((double *)PyArray_DATA(arrayObject)); /* "mtrand.pyx":233 * array = np.empty(size, np.float64) * array_data = PyArray_DATA(array) * multi = PyArray_MultiIterNew(3, array, oa, 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 = PyArray_DATA(array) * multi = PyArray_MultiIterNew(3, array, oa, 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 = PyArray_MultiIterNew(3, array, oa, ob) * if (multi.size != PyArray_SIZE(array)): * raise ValueError("size is not compatible with inputs") # <<<<<<<<<<<<<< * for i from 0 <= i < multi.size: * oa_data = 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 = PyArray_MultiIter_DATA(multi, 1) * ob_data = 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 = PyArray_MultiIter_DATA(multi, 1) # <<<<<<<<<<<<<< * ob_data = 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 = PyArray_MultiIter_DATA(multi, 1) * ob_data = 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 = PyArray_MultiIter_DATA(multi, 1) * ob_data = 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 = 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 = 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 = np.empty(size, np.float64) # <<<<<<<<<<<<<< * length = PyArray_SIZE(array) * array_data = 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 = np.empty(size, np.float64) * length = PyArray_SIZE(array) # <<<<<<<<<<<<<< * array_data = PyArray_DATA(array) * for i from 0 <= i < length: */ __pyx_v_length = PyArray_SIZE(arrayObject); /* "mtrand.pyx":257 * array = np.empty(size, np.float64) * length = PyArray_SIZE(array) * array_data = 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 = 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 = 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 = PyArray_MultiIterNew(3, oa, ob, oc) * array = 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 = PyArray_MultiIterNew(3, oa, ob, oc) # <<<<<<<<<<<<<< * array = PyArray_SimpleNew(multi.nd, multi.dimensions, NPY_DOUBLE) * array_data = 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 = PyArray_MultiIterNew(3, oa, ob, oc) * array = PyArray_SimpleNew(multi.nd, multi.dimensions, NPY_DOUBLE) # <<<<<<<<<<<<<< * array_data = 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 = PyArray_MultiIterNew(3, oa, ob, oc) * array = PyArray_SimpleNew(multi.nd, multi.dimensions, NPY_DOUBLE) * array_data = PyArray_DATA(array) # <<<<<<<<<<<<<< * for i from 0 <= i < multi.size: * oa_data = PyArray_MultiIter_DATA(multi, 0) */ __pyx_v_array_data = ((double *)PyArray_DATA(arrayObject)); /* "mtrand.pyx":278 * array = PyArray_SimpleNew(multi.nd, multi.dimensions, NPY_DOUBLE) * array_data = PyArray_DATA(array) * for i from 0 <= i < multi.size: # <<<<<<<<<<<<<< * oa_data = PyArray_MultiIter_DATA(multi, 0) * ob_data = 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 = PyArray_DATA(array) * for i from 0 <= i < multi.size: * oa_data = PyArray_MultiIter_DATA(multi, 0) # <<<<<<<<<<<<<< * ob_data = PyArray_MultiIter_DATA(multi, 1) * oc_data = 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 = PyArray_MultiIter_DATA(multi, 0) * ob_data = PyArray_MultiIter_DATA(multi, 1) # <<<<<<<<<<<<<< * oc_data = 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 = PyArray_MultiIter_DATA(multi, 0) * ob_data = PyArray_MultiIter_DATA(multi, 1) * oc_data = 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 = PyArray_MultiIter_DATA(multi, 1) * oc_data = 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 = 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 = np.empty(size, np.float64) */ PyArray_MultiIter_NEXT(__pyx_v_multi); } goto __pyx_L3; } /*else*/ { /* "mtrand.pyx":285 * PyArray_MultiIter_NEXT(multi) * else: * array = np.empty(size, np.float64) # <<<<<<<<<<<<<< * array_data = PyArray_DATA(array) * multi = PyArray_MultiIterNew(4, array, 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 = np.empty(size, np.float64) * array_data = PyArray_DATA(array) # <<<<<<<<<<<<<< * multi = PyArray_MultiIterNew(4, array, oa, * ob, oc) */ __pyx_v_array_data = ((double *)PyArray_DATA(arrayObject)); /* "mtrand.pyx":288 * array_data = PyArray_DATA(array) * multi = PyArray_MultiIterNew(4, array, oa, * ob, 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 = PyArray_MultiIterNew(4, array, oa, * ob, 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 * ob, oc) * if (multi.size != PyArray_SIZE(array)): * raise ValueError("size is not compatible with inputs") # <<<<<<<<<<<<<< * for i from 0 <= i < multi.size: * oa_data = 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 = PyArray_MultiIter_DATA(multi, 1) * ob_data = 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 = PyArray_MultiIter_DATA(multi, 1) # <<<<<<<<<<<<<< * ob_data = PyArray_MultiIter_DATA(multi, 2) * oc_data = 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 = PyArray_MultiIter_DATA(multi, 1) * ob_data = PyArray_MultiIter_DATA(multi, 2) # <<<<<<<<<<<<<< * oc_data = 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 = PyArray_MultiIter_DATA(multi, 1) * ob_data = PyArray_MultiIter_DATA(multi, 2) * oc_data = 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 = PyArray_MultiIter_DATA(multi, 2) * oc_data = 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 = 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 = 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 = np.empty(size, int) # <<<<<<<<<<<<<< * length = PyArray_SIZE(array) * array_data = 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 = np.empty(size, int) * length = PyArray_SIZE(array) # <<<<<<<<<<<<<< * array_data = PyArray_DATA(array) * for i from 0 <= i < length: */ __pyx_v_length = PyArray_SIZE(arrayObject); /* "mtrand.pyx":310 * array = np.empty(size, int) * length = PyArray_SIZE(array) * array_data = 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 = 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 = 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 = 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 = np.empty(size, int) # <<<<<<<<<<<<<< * length = PyArray_SIZE(array) * array_data = 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 = np.empty(size, int) * length = PyArray_SIZE(array) # <<<<<<<<<<<<<< * array_data = PyArray_DATA(array) * for i from 0 <= i < length: */ __pyx_v_length = PyArray_SIZE(arrayObject); /* "mtrand.pyx":326 * array = np.empty(size, int) * length = PyArray_SIZE(array) * array_data = 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 = 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 = 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 = PyArray_MultiIterNew(2, on, op) * array = 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 = PyArray_MultiIterNew(2, on, op) # <<<<<<<<<<<<<< * array = PyArray_SimpleNew(multi.nd, multi.dimensions, NPY_LONG) * array_data = 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 = PyArray_MultiIterNew(2, on, op) * array = PyArray_SimpleNew(multi.nd, multi.dimensions, NPY_LONG) # <<<<<<<<<<<<<< * array_data = 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 = PyArray_MultiIterNew(2, on, op) * array = PyArray_SimpleNew(multi.nd, multi.dimensions, NPY_LONG) * array_data = PyArray_DATA(array) # <<<<<<<<<<<<<< * for i from 0 <= i < multi.size: * on_data = PyArray_MultiIter_DATA(multi, 0) */ __pyx_v_array_data = ((long *)PyArray_DATA(arrayObject)); /* "mtrand.pyx":344 * array = PyArray_SimpleNew(multi.nd, multi.dimensions, NPY_LONG) * array_data = PyArray_DATA(array) * for i from 0 <= i < multi.size: # <<<<<<<<<<<<<< * on_data = PyArray_MultiIter_DATA(multi, 0) * op_data = 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 = PyArray_DATA(array) * for i from 0 <= i < multi.size: * on_data = PyArray_MultiIter_DATA(multi, 0) # <<<<<<<<<<<<<< * op_data = 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 = PyArray_MultiIter_DATA(multi, 0) * op_data = 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 = PyArray_MultiIter_DATA(multi, 0) * op_data = 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 = PyArray_MultiIter_DATA(multi, 1) * array_data[i] = func(state, on_data[0], op_data[0]) * PyArray_MultiIter_NEXT(multi) # <<<<<<<<<<<<<< * else: * array = np.empty(size, int) */ PyArray_MultiIter_NEXT(__pyx_v_multi); } goto __pyx_L3; } /*else*/ { /* "mtrand.pyx":350 * PyArray_MultiIter_NEXT(multi) * else: * array = np.empty(size, int) # <<<<<<<<<<<<<< * array_data = PyArray_DATA(array) * multi = PyArray_MultiIterNew(3, array, on, 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 = np.empty(size, int) * array_data = PyArray_DATA(array) # <<<<<<<<<<<<<< * multi = PyArray_MultiIterNew(3, array, on, op) * if (multi.size != PyArray_SIZE(array)): */ __pyx_v_array_data = ((long *)PyArray_DATA(arrayObject)); /* "mtrand.pyx":352 * array = np.empty(size, int) * array_data = PyArray_DATA(array) * multi = PyArray_MultiIterNew(3, array, on, 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 = PyArray_DATA(array) * multi = PyArray_MultiIterNew(3, array, on, 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 = PyArray_MultiIterNew(3, array, on, op) * if (multi.size != PyArray_SIZE(array)): * raise ValueError("size is not compatible with inputs") # <<<<<<<<<<<<<< * for i from 0 <= i < multi.size: * on_data = 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 = PyArray_MultiIter_DATA(multi, 1) * op_data = 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 = PyArray_MultiIter_DATA(multi, 1) # <<<<<<<<<<<<<< * op_data = 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 = PyArray_MultiIter_DATA(multi, 1) * op_data = 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 = PyArray_MultiIter_DATA(multi, 1) * op_data = 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 = 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 = 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 = np.empty(size, int) # <<<<<<<<<<<<<< * length = PyArray_SIZE(array) * array_data = 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 = np.empty(size, int) * length = PyArray_SIZE(array) # <<<<<<<<<<<<<< * array_data = PyArray_DATA(array) * for i from 0 <= i < length: */ __pyx_v_length = PyArray_SIZE(arrayObject); /* "mtrand.pyx":375 * array = np.empty(size, int) * length = PyArray_SIZE(array) * array_data = 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 = 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 = 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 = PyArray_MultiIterNew(2, on, op) * array = 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 = PyArray_MultiIterNew(2, on, op) # <<<<<<<<<<<<<< * array = PyArray_SimpleNew(multi.nd, multi.dimensions, NPY_LONG) * array_data = 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 = PyArray_MultiIterNew(2, on, op) * array = PyArray_SimpleNew(multi.nd, multi.dimensions, NPY_LONG) # <<<<<<<<<<<<<< * array_data = 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 = PyArray_MultiIterNew(2, on, op) * array = PyArray_SimpleNew(multi.nd, multi.dimensions, NPY_LONG) * array_data = PyArray_DATA(array) # <<<<<<<<<<<<<< * for i from 0 <= i < multi.size: * on_data = PyArray_MultiIter_DATA(multi, 0) */ __pyx_v_array_data = ((long *)PyArray_DATA(arrayObject)); /* "mtrand.pyx":393 * array = PyArray_SimpleNew(multi.nd, multi.dimensions, NPY_LONG) * array_data = PyArray_DATA(array) * for i from 0 <= i < multi.size: # <<<<<<<<<<<<<< * on_data = PyArray_MultiIter_DATA(multi, 0) * op_data = 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 = PyArray_DATA(array) * for i from 0 <= i < multi.size: * on_data = PyArray_MultiIter_DATA(multi, 0) # <<<<<<<<<<<<<< * op_data = 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 = PyArray_MultiIter_DATA(multi, 0) * op_data = 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 = PyArray_MultiIter_DATA(multi, 0) * op_data = 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 = PyArray_MultiIter_DATA(multi, 1) * array_data[i] = func(state, on_data[0], op_data[0]) * PyArray_MultiIter_NEXT(multi) # <<<<<<<<<<<<<< * else: * array = np.empty(size, int) */ PyArray_MultiIter_NEXT(__pyx_v_multi); } goto __pyx_L3; } /*else*/ { /* "mtrand.pyx":399 * PyArray_MultiIter_NEXT(multi) * else: * array = np.empty(size, int) # <<<<<<<<<<<<<< * array_data = PyArray_DATA(array) * multi = PyArray_MultiIterNew(3, array, on, 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 = np.empty(size, int) * array_data = PyArray_DATA(array) # <<<<<<<<<<<<<< * multi = PyArray_MultiIterNew(3, array, on, op) * if (multi.size != PyArray_SIZE(array)): */ __pyx_v_array_data = ((long *)PyArray_DATA(arrayObject)); /* "mtrand.pyx":401 * array = np.empty(size, int) * array_data = PyArray_DATA(array) * multi = PyArray_MultiIterNew(3, array, on, 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 = PyArray_DATA(array) * multi = PyArray_MultiIterNew(3, array, on, 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 = PyArray_MultiIterNew(3, array, on, op) * if (multi.size != PyArray_SIZE(array)): * raise ValueError("size is not compatible with inputs") # <<<<<<<<<<<<<< * for i from 0 <= i < multi.size: * on_data = 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 = PyArray_MultiIter_DATA(multi, 1) * op_data = 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 = PyArray_MultiIter_DATA(multi, 1) # <<<<<<<<<<<<<< * op_data = 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 = PyArray_MultiIter_DATA(multi, 1) * op_data = 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 = PyArray_MultiIter_DATA(multi, 1) * op_data = 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 = 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 = 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 = np.empty(size, int) # <<<<<<<<<<<<<< * length = PyArray_SIZE(array) * array_data = 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 = np.empty(size, int) * length = PyArray_SIZE(array) # <<<<<<<<<<<<<< * array_data = PyArray_DATA(array) * for i from 0 <= i < length: */ __pyx_v_length = PyArray_SIZE(arrayObject); /* "mtrand.pyx":425 * array = np.empty(size, int) * length = PyArray_SIZE(array) * array_data = 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 = 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 = 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 = PyArray_MultiIterNew(3, on, om, oN) * array = 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 = PyArray_MultiIterNew(3, on, om, oN) # <<<<<<<<<<<<<< * array = PyArray_SimpleNew(multi.nd, multi.dimensions, NPY_LONG) * array_data = 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 = PyArray_MultiIterNew(3, on, om, oN) * array = PyArray_SimpleNew(multi.nd, multi.dimensions, NPY_LONG) # <<<<<<<<<<<<<< * array_data = 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 = PyArray_MultiIterNew(3, on, om, oN) * array = PyArray_SimpleNew(multi.nd, multi.dimensions, NPY_LONG) * array_data = PyArray_DATA(array) # <<<<<<<<<<<<<< * for i from 0 <= i < multi.size: * on_data = PyArray_MultiIter_DATA(multi, 0) */ __pyx_v_array_data = ((long *)PyArray_DATA(arrayObject)); /* "mtrand.pyx":445 * array = PyArray_SimpleNew(multi.nd, multi.dimensions, NPY_LONG) * array_data = PyArray_DATA(array) * for i from 0 <= i < multi.size: # <<<<<<<<<<<<<< * on_data = PyArray_MultiIter_DATA(multi, 0) * om_data = 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 = PyArray_DATA(array) * for i from 0 <= i < multi.size: * on_data = PyArray_MultiIter_DATA(multi, 0) # <<<<<<<<<<<<<< * om_data = PyArray_MultiIter_DATA(multi, 1) * oN_data = 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 = PyArray_MultiIter_DATA(multi, 0) * om_data = PyArray_MultiIter_DATA(multi, 1) # <<<<<<<<<<<<<< * oN_data = 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 = PyArray_MultiIter_DATA(multi, 0) * om_data = PyArray_MultiIter_DATA(multi, 1) * oN_data = 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 = PyArray_MultiIter_DATA(multi, 1) * oN_data = 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 = 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 = np.empty(size, int) */ PyArray_MultiIter_NEXT(__pyx_v_multi); } goto __pyx_L3; } /*else*/ { /* "mtrand.pyx":452 * PyArray_MultiIter_NEXT(multi) * else: * array = np.empty(size, int) # <<<<<<<<<<<<<< * array_data = PyArray_DATA(array) * multi = PyArray_MultiIterNew(4, array, on, 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 = np.empty(size, int) * array_data = PyArray_DATA(array) # <<<<<<<<<<<<<< * multi = PyArray_MultiIterNew(4, array, on, om, * oN) */ __pyx_v_array_data = ((long *)PyArray_DATA(arrayObject)); /* "mtrand.pyx":455 * array_data = PyArray_DATA(array) * multi = PyArray_MultiIterNew(4, array, on, om, * 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 = PyArray_MultiIterNew(4, array, on, om, * 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 * oN) * if (multi.size != PyArray_SIZE(array)): * raise ValueError("size is not compatible with inputs") # <<<<<<<<<<<<<< * for i from 0 <= i < multi.size: * on_data = 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 = PyArray_MultiIter_DATA(multi, 1) * om_data = 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 = PyArray_MultiIter_DATA(multi, 1) # <<<<<<<<<<<<<< * om_data = PyArray_MultiIter_DATA(multi, 2) * oN_data = 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 = PyArray_MultiIter_DATA(multi, 1) * om_data = PyArray_MultiIter_DATA(multi, 2) # <<<<<<<<<<<<<< * oN_data = 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 = PyArray_MultiIter_DATA(multi, 1) * om_data = PyArray_MultiIter_DATA(multi, 2) * oN_data = 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 = PyArray_MultiIter_DATA(multi, 2) * oN_data = 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 = 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 = 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 = np.empty(size, int) # <<<<<<<<<<<<<< * length = PyArray_SIZE(array) * array_data = 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 = np.empty(size, int) * length = PyArray_SIZE(array) # <<<<<<<<<<<<<< * array_data = PyArray_DATA(array) * for i from 0 <= i < length: */ __pyx_v_length = PyArray_SIZE(arrayObject); /* "mtrand.pyx":478 * array = np.empty(size, int) * length = PyArray_SIZE(array) * array_data = 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 = 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 = 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 = 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 = PyArray_SimpleNew(PyArray_NDIM(oa), * PyArray_DIMS(oa), NPY_LONG) # <<<<<<<<<<<<<< * length = PyArray_SIZE(array) * array_data = 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 = PyArray_SimpleNew(PyArray_NDIM(oa), * PyArray_DIMS(oa), NPY_LONG) * length = PyArray_SIZE(array) # <<<<<<<<<<<<<< * array_data = PyArray_DATA(array) * itera = PyArray_IterNew(oa) */ __pyx_v_length = PyArray_SIZE(arrayObject); /* "mtrand.pyx":496 * PyArray_DIMS(oa), NPY_LONG) * length = PyArray_SIZE(array) * array_data = PyArray_DATA(array) # <<<<<<<<<<<<<< * itera = PyArray_IterNew(oa) * for i from 0 <= i < length: */ __pyx_v_array_data = ((long *)PyArray_DATA(arrayObject)); /* "mtrand.pyx":497 * length = PyArray_SIZE(array) * array_data = PyArray_DATA(array) * itera = PyArray_IterNew(oa) # <<<<<<<<<<<<<< * for i from 0 <= i < length: * array_data[i] = func(state, ((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 = PyArray_DATA(array) * itera = PyArray_IterNew(oa) * for i from 0 <= i < length: # <<<<<<<<<<<<<< * array_data[i] = func(state, ((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 = PyArray_IterNew(oa) * for i from 0 <= i < length: * array_data[i] = func(state, ((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, ((itera.dataptr))[0]) * PyArray_ITER_NEXT(itera) # <<<<<<<<<<<<<< * else: * array = np.empty(size, int) */ PyArray_ITER_NEXT(__pyx_v_itera); } goto __pyx_L3; } /*else*/ { /* "mtrand.pyx":502 * PyArray_ITER_NEXT(itera) * else: * array = np.empty(size, int) # <<<<<<<<<<<<<< * array_data = PyArray_DATA(array) * multi = PyArray_MultiIterNew(2, array, 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 = np.empty(size, int) * array_data = PyArray_DATA(array) # <<<<<<<<<<<<<< * multi = PyArray_MultiIterNew(2, array, oa) * if (multi.size != PyArray_SIZE(array)): */ __pyx_v_array_data = ((long *)PyArray_DATA(arrayObject)); /* "mtrand.pyx":504 * array = np.empty(size, int) * array_data = PyArray_DATA(array) * multi = PyArray_MultiIterNew(2, array, 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 = PyArray_DATA(array) * multi = PyArray_MultiIterNew(2, array, 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 = PyArray_MultiIterNew(2, array, oa) * if (multi.size != PyArray_SIZE(array)): * raise ValueError("size is not compatible with inputs") # <<<<<<<<<<<<<< * for i from 0 <= i < multi.size: * oa_data = 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 = 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 = 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 = 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 = 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 # <<<<<<<<<<<<<< * * def _shape_from_size(size, d): */ __pyx_r = __pyx_v_sum; goto __pyx_L0; __pyx_r = 0; __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } /* Python wrapper */ static PyObject *__pyx_pw_6mtrand_1_shape_from_size(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static PyMethodDef __pyx_mdef_6mtrand_1_shape_from_size = {__Pyx_NAMESTR("_shape_from_size"), (PyCFunction)__pyx_pw_6mtrand_1_shape_from_size, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(0)}; static PyObject *__pyx_pw_6mtrand_1_shape_from_size(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { PyObject *__pyx_v_size = 0; PyObject *__pyx_v_d = 0; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("_shape_from_size (wrapper)", 0); { static PyObject **__pyx_pyargnames[] = {&__pyx_n_s__size,&__pyx_n_s__d,0}; PyObject* values[2] = {0,0}; 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__size)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; case 1: if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s__d)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("_shape_from_size", 1, 2, 2, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 525; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } if (unlikely(kw_args > 0)) { if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "_shape_from_size") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 525; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } else if (PyTuple_GET_SIZE(__pyx_args) != 2) { goto __pyx_L5_argtuple_error; } else { values[0] = PyTuple_GET_ITEM(__pyx_args, 0); values[1] = PyTuple_GET_ITEM(__pyx_args, 1); } __pyx_v_size = values[0]; __pyx_v_d = values[1]; } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; __Pyx_RaiseArgtupleInvalid("_shape_from_size", 1, 2, 2, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 525; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_L3_error:; __Pyx_AddTraceback("mtrand._shape_from_size", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; __pyx_r = __pyx_pf_6mtrand__shape_from_size(__pyx_self, __pyx_v_size, __pyx_v_d); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "mtrand.pyx":525 * return sum * * def _shape_from_size(size, d): # <<<<<<<<<<<<<< * if size is None: * shape = (d,) */ static PyObject *__pyx_pf_6mtrand__shape_from_size(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_size, PyObject *__pyx_v_d) { PyObject *__pyx_v_shape = NULL; 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; PyObject *__pyx_t_7 = NULL; int __pyx_t_8; PyObject *__pyx_t_9 = NULL; PyObject *__pyx_t_10 = NULL; PyObject *__pyx_t_11 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("_shape_from_size", 0); /* "mtrand.pyx":526 * * def _shape_from_size(size, d): * if size is None: # <<<<<<<<<<<<<< * shape = (d,) * else: */ __pyx_t_1 = (__pyx_v_size == Py_None); if (__pyx_t_1) { /* "mtrand.pyx":527 * def _shape_from_size(size, d): * if size is None: * shape = (d,) # <<<<<<<<<<<<<< * else: * try: */ __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 527; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_INCREF(__pyx_v_d); PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v_d); __Pyx_GIVEREF(__pyx_v_d); __pyx_v_shape = ((PyObject*)__pyx_t_2); __pyx_t_2 = 0; goto __pyx_L3; } /*else*/ { /* "mtrand.pyx":529 * shape = (d,) * else: * try: # <<<<<<<<<<<<<< * shape = (operator.index(size), d) * except TypeError: */ { __Pyx_ExceptionSave(&__pyx_t_3, &__pyx_t_4, &__pyx_t_5); __Pyx_XGOTREF(__pyx_t_3); __Pyx_XGOTREF(__pyx_t_4); __Pyx_XGOTREF(__pyx_t_5); /*try:*/ { /* "mtrand.pyx":530 * else: * try: * shape = (operator.index(size), d) # <<<<<<<<<<<<<< * except TypeError: * shape = tuple(size) + (d,) */ __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s__operator); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 530; __pyx_clineno = __LINE__; goto __pyx_L4_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s__index); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 530; __pyx_clineno = __LINE__; goto __pyx_L4_error;} __Pyx_GOTREF(__pyx_t_6); __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 = 530; __pyx_clineno = __LINE__; goto __pyx_L4_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_t_7 = PyObject_Call(__pyx_t_6, ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 530; __pyx_clineno = __LINE__; goto __pyx_L4_error;} __Pyx_GOTREF(__pyx_t_7); __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 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 = 530; __pyx_clineno = __LINE__; goto __pyx_L4_error;} __Pyx_GOTREF(__pyx_t_2); PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_7); __Pyx_GIVEREF(__pyx_t_7); __Pyx_INCREF(__pyx_v_d); PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_v_d); __Pyx_GIVEREF(__pyx_v_d); __pyx_t_7 = 0; __pyx_v_shape = ((PyObject*)__pyx_t_2); __pyx_t_2 = 0; } __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; goto __pyx_L11_try_end; __pyx_L4_error:; __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; /* "mtrand.pyx":531 * try: * shape = (operator.index(size), d) * except TypeError: # <<<<<<<<<<<<<< * shape = tuple(size) + (d,) * return shape */ __pyx_t_8 = PyErr_ExceptionMatches(__pyx_builtin_TypeError); if (__pyx_t_8) { __Pyx_AddTraceback("mtrand._shape_from_size", __pyx_clineno, __pyx_lineno, __pyx_filename); if (__Pyx_GetException(&__pyx_t_2, &__pyx_t_7, &__pyx_t_6) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 531; __pyx_clineno = __LINE__; goto __pyx_L6_except_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_GOTREF(__pyx_t_7); __Pyx_GOTREF(__pyx_t_6); /* "mtrand.pyx":532 * shape = (operator.index(size), d) * except TypeError: * shape = tuple(size) + (d,) # <<<<<<<<<<<<<< * return shape * */ __pyx_t_9 = PyTuple_New(1); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 532; __pyx_clineno = __LINE__; goto __pyx_L6_except_error;} __Pyx_GOTREF(__pyx_t_9); __Pyx_INCREF(__pyx_v_size); PyTuple_SET_ITEM(__pyx_t_9, 0, __pyx_v_size); __Pyx_GIVEREF(__pyx_v_size); __pyx_t_10 = PyObject_Call(((PyObject *)((PyObject*)(&PyTuple_Type))), ((PyObject *)__pyx_t_9), NULL); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 532; __pyx_clineno = __LINE__; goto __pyx_L6_except_error;} __Pyx_GOTREF(__pyx_t_10); __Pyx_DECREF(((PyObject *)__pyx_t_9)); __pyx_t_9 = 0; __pyx_t_9 = PyTuple_New(1); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 532; __pyx_clineno = __LINE__; goto __pyx_L6_except_error;} __Pyx_GOTREF(__pyx_t_9); __Pyx_INCREF(__pyx_v_d); PyTuple_SET_ITEM(__pyx_t_9, 0, __pyx_v_d); __Pyx_GIVEREF(__pyx_v_d); __pyx_t_11 = PyNumber_Add(__pyx_t_10, ((PyObject *)__pyx_t_9)); if (unlikely(!__pyx_t_11)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 532; __pyx_clineno = __LINE__; goto __pyx_L6_except_error;} __Pyx_GOTREF(((PyObject *)__pyx_t_11)); __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; __Pyx_DECREF(((PyObject *)__pyx_t_9)); __pyx_t_9 = 0; __Pyx_XDECREF(((PyObject *)__pyx_v_shape)); __pyx_v_shape = ((PyObject*)__pyx_t_11); __pyx_t_11 = 0; __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; goto __pyx_L5_exception_handled; } __pyx_L6_except_error:; __Pyx_XGIVEREF(__pyx_t_3); __Pyx_XGIVEREF(__pyx_t_4); __Pyx_XGIVEREF(__pyx_t_5); __Pyx_ExceptionReset(__pyx_t_3, __pyx_t_4, __pyx_t_5); goto __pyx_L1_error; __pyx_L5_exception_handled:; __Pyx_XGIVEREF(__pyx_t_3); __Pyx_XGIVEREF(__pyx_t_4); __Pyx_XGIVEREF(__pyx_t_5); __Pyx_ExceptionReset(__pyx_t_3, __pyx_t_4, __pyx_t_5); __pyx_L11_try_end:; } } __pyx_L3:; /* "mtrand.pyx":533 * except TypeError: * shape = tuple(size) + (d,) * return shape # <<<<<<<<<<<<<< * * cdef class RandomState: */ __Pyx_XDECREF(__pyx_r); __Pyx_INCREF(((PyObject *)__pyx_v_shape)); __pyx_r = ((PyObject *)__pyx_v_shape); 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_6); __Pyx_XDECREF(__pyx_t_7); __Pyx_XDECREF(__pyx_t_9); __Pyx_XDECREF(__pyx_t_10); __Pyx_XDECREF(__pyx_t_11); __Pyx_AddTraceback("mtrand._shape_from_size", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XDECREF(__pyx_v_shape); __Pyx_XGIVEREF(__pyx_r); __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":571 * poisson_lam_max = np.iinfo('l').max - np.sqrt(np.iinfo('l').max)*10 * * def __init__(self, seed=None): # <<<<<<<<<<<<<< * self.internal_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 = 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("__init__", 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.__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":572 * * def __init__(self, seed=None): * self.internal_state = PyMem_Malloc(sizeof(rk_state)) # <<<<<<<<<<<<<< * * self.seed(seed) */ __pyx_v_self->internal_state = ((rk_state *)PyMem_Malloc((sizeof(rk_state)))); /* "mtrand.pyx":574 * self.internal_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 = 574; __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 = 574; __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 = 574; __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":576 * 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":577 * * 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":578 * 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":579 * 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":581 * 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 = 581; __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 = 581; __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_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; int __pyx_t_4; PyObject *__pyx_t_5 = NULL; PyObject *__pyx_t_6 = NULL; PyObject *__pyx_t_7 = NULL; unsigned long __pyx_t_8; int __pyx_t_9; PyObject *__pyx_t_10 = NULL; PyObject *__pyx_t_11 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("seed", 0); /* "mtrand.pyx":602 * cdef rk_error errcode * cdef ndarray obj "arrayObject_obj" * try: # <<<<<<<<<<<<<< * if seed is None: * errcode = rk_randomseed(self.internal_state) */ { __Pyx_ExceptionSave(&__pyx_t_1, &__pyx_t_2, &__pyx_t_3); __Pyx_XGOTREF(__pyx_t_1); __Pyx_XGOTREF(__pyx_t_2); __Pyx_XGOTREF(__pyx_t_3); /*try:*/ { /* "mtrand.pyx":603 * cdef ndarray obj "arrayObject_obj" * try: * if seed is None: # <<<<<<<<<<<<<< * errcode = rk_randomseed(self.internal_state) * else: */ __pyx_t_4 = (__pyx_v_seed == Py_None); if (__pyx_t_4) { /* "mtrand.pyx":604 * try: * if seed is None: * errcode = rk_randomseed(self.internal_state) # <<<<<<<<<<<<<< * else: * rk_seed(operator.index(seed), self.internal_state) */ __pyx_v_errcode = rk_randomseed(__pyx_v_self->internal_state); goto __pyx_L11; } /*else*/ { /* "mtrand.pyx":606 * errcode = rk_randomseed(self.internal_state) * else: * rk_seed(operator.index(seed), self.internal_state) # <<<<<<<<<<<<<< * except TypeError: * obj = PyArray_ContiguousFromObject(seed, NPY_LONG, 1, 1) */ __pyx_t_5 = __Pyx_GetModuleGlobalName(__pyx_n_s__operator); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 606; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __Pyx_GOTREF(__pyx_t_5); __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_t_5, __pyx_n_s__index); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 606; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __Pyx_GOTREF(__pyx_t_6); __Pyx_DECREF(__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 = 606; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __Pyx_GOTREF(__pyx_t_5); __Pyx_INCREF(__pyx_v_seed); PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_v_seed); __Pyx_GIVEREF(__pyx_v_seed); __pyx_t_7 = PyObject_Call(__pyx_t_6, ((PyObject *)__pyx_t_5), NULL); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 606; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __Pyx_GOTREF(__pyx_t_7); __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; __Pyx_DECREF(((PyObject *)__pyx_t_5)); __pyx_t_5 = 0; __pyx_t_8 = __Pyx_PyInt_AsUnsignedLong(__pyx_t_7); if (unlikely((__pyx_t_8 == (unsigned long)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 606; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; rk_seed(__pyx_t_8, __pyx_v_self->internal_state); } __pyx_L11:; } __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; goto __pyx_L10_try_end; __pyx_L3_error:; __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; /* "mtrand.pyx":607 * else: * rk_seed(operator.index(seed), self.internal_state) * except TypeError: # <<<<<<<<<<<<<< * obj = PyArray_ContiguousFromObject(seed, NPY_LONG, 1, 1) * init_by_array(self.internal_state, PyArray_DATA(obj), */ __pyx_t_9 = PyErr_ExceptionMatches(__pyx_builtin_TypeError); if (__pyx_t_9) { __Pyx_AddTraceback("mtrand.RandomState.seed", __pyx_clineno, __pyx_lineno, __pyx_filename); if (__Pyx_GetException(&__pyx_t_7, &__pyx_t_5, &__pyx_t_6) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 607; __pyx_clineno = __LINE__; goto __pyx_L5_except_error;} __Pyx_GOTREF(__pyx_t_7); __Pyx_GOTREF(__pyx_t_5); __Pyx_GOTREF(__pyx_t_6); /* "mtrand.pyx":608 * rk_seed(operator.index(seed), self.internal_state) * except TypeError: * obj = PyArray_ContiguousFromObject(seed, NPY_LONG, 1, 1) # <<<<<<<<<<<<<< * init_by_array(self.internal_state, PyArray_DATA(obj), * PyArray_DIM(obj, 0)) */ __pyx_t_10 = PyArray_ContiguousFromObject(__pyx_v_seed, NPY_LONG, 1, 1); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 608; __pyx_clineno = __LINE__; goto __pyx_L5_except_error;} __Pyx_GOTREF(__pyx_t_10); __pyx_t_11 = __pyx_t_10; __Pyx_INCREF(__pyx_t_11); __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; arrayObject_obj = ((PyArrayObject *)__pyx_t_11); __pyx_t_11 = 0; /* "mtrand.pyx":610 * obj = PyArray_ContiguousFromObject(seed, NPY_LONG, 1, 1) * init_by_array(self.internal_state, 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_DECREF(__pyx_t_7); __pyx_t_7 = 0; __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; goto __pyx_L4_exception_handled; } __pyx_L5_except_error:; __Pyx_XGIVEREF(__pyx_t_1); __Pyx_XGIVEREF(__pyx_t_2); __Pyx_XGIVEREF(__pyx_t_3); __Pyx_ExceptionReset(__pyx_t_1, __pyx_t_2, __pyx_t_3); goto __pyx_L1_error; __pyx_L4_exception_handled:; __Pyx_XGIVEREF(__pyx_t_1); __Pyx_XGIVEREF(__pyx_t_2); __Pyx_XGIVEREF(__pyx_t_3); __Pyx_ExceptionReset(__pyx_t_1, __pyx_t_2, __pyx_t_3); __pyx_L10_try_end:; } __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_5); __Pyx_XDECREF(__pyx_t_6); __Pyx_XDECREF(__pyx_t_7); __Pyx_XDECREF(__pyx_t_10); __Pyx_XDECREF(__pyx_t_11); __Pyx_AddTraceback("mtrand.RandomState.seed", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XDECREF((PyObject *)arrayObject_obj); __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":612 * 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":643 * """ * cdef ndarray state "arrayObject_state" * state = np.empty(624, np.uint) # <<<<<<<<<<<<<< * memcpy(PyArray_DATA(state), (self.internal_state.key), 624*sizeof(long)) * state = 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 = 643; __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 = 643; __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 = 643; __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 = 643; __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 = 643; __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 = 643; __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":644 * cdef ndarray state "arrayObject_state" * state = np.empty(624, np.uint) * memcpy(PyArray_DATA(state), (self.internal_state.key), 624*sizeof(long)) # <<<<<<<<<<<<<< * state = 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":645 * state = np.empty(624, np.uint) * memcpy(PyArray_DATA(state), (self.internal_state.key), 624*sizeof(long)) * state = 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 = 645; __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 = 645; __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 = 645; __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 = 645; __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 = 645; __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 = 645; __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":646 * memcpy(PyArray_DATA(state), (self.internal_state.key), 624*sizeof(long)) * state = 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 = 646; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); /* "mtrand.pyx":647 * state = 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 = 647; __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 = 647; __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 = 646; __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":649 * 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":698 * 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 = 698; __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":699 * 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 = 699; __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 = 699; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; if (__pyx_t_2) { /* "mtrand.pyx":700 * 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 = 700; __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 = 700; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L3; } __pyx_L3:; /* "mtrand.pyx":701 * 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 = 701; __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 = 701; __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 = 701; __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 = 701; __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 = 701; __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 = 701; __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 = 701; __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 = 701; __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":702 * 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 = 702; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_2 = (__pyx_t_8 == 3); if (__pyx_t_2) { /* "mtrand.pyx":703 * 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":704 * 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 = 704; __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":706 * cached_gaussian = 0.0 * else: * has_gauss, cached_gaussian = state[3:5] # <<<<<<<<<<<<<< * try: * obj = 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 = 706; __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 = 706; __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 = 706; __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 = 706; __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 = 706; __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 = 706; __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 = 706; __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":707 * else: * has_gauss, cached_gaussian = state[3:5] * try: # <<<<<<<<<<<<<< * obj = 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":708 * has_gauss, cached_gaussian = state[3:5] * try: * obj = 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 = 708; __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":709 * try: * obj = PyArray_ContiguousFromObject(key, NPY_ULONG, 1, 1) * except TypeError: # <<<<<<<<<<<<<< * # compatibility -- could be an older pickle * obj = 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 = 709; __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":711 * except TypeError: * # compatibility -- could be an older pickle * obj = 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 = 711; __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":712 * # compatibility -- could be an older pickle * obj = PyArray_ContiguousFromObject(key, NPY_LONG, 1, 1) * if PyArray_DIM(obj, 0) != 624: # <<<<<<<<<<<<<< * raise ValueError("state must be 624 longs") * memcpy((self.internal_state.key), PyArray_DATA(obj), 624*sizeof(long)) */ __pyx_t_2 = (PyArray_DIM(arrayObject_obj, 0) != 624); if (__pyx_t_2) { /* "mtrand.pyx":713 * obj = PyArray_ContiguousFromObject(key, NPY_LONG, 1, 1) * if PyArray_DIM(obj, 0) != 624: * raise ValueError("state must be 624 longs") # <<<<<<<<<<<<<< * memcpy((self.internal_state.key), 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 = 713; __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 = 713; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L19; } __pyx_L19:; /* "mtrand.pyx":714 * if PyArray_DIM(obj, 0) != 624: * raise ValueError("state must be 624 longs") * memcpy((self.internal_state.key), 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":715 * raise ValueError("state must be 624 longs") * memcpy((self.internal_state.key), 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":716 * memcpy((self.internal_state.key), 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 = 716; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_v_self->internal_state->has_gauss = __pyx_t_7; /* "mtrand.pyx":717 * 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 = 717; __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":720 * * # 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":721 * # 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 = 721; __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 = 721; __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":723 * 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":724 * * 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 = 724; __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 = 724; __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 = 724; __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":726 * 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":727 * * 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 = 727; __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 = 727; __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 = 727; __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 = 727; __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 = 727; __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 = 727; __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 \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":730 * * # 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 = 730; __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 = 730; __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":771 * * """ * 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 = 771; __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":773 * 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 = 773; __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 = 773; __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":818 * * """ * 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 = 818; __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":820 * 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 = 820; __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 = 820; __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":877 * 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":878 * * if high is None: * lo = 0 # <<<<<<<<<<<<<< * hi = low * else: */ __pyx_v_lo = 0; /* "mtrand.pyx":879 * 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 = 879; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_v_hi = __pyx_t_2; goto __pyx_L3; } /*else*/ { /* "mtrand.pyx":881 * 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 = 881; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_v_lo = __pyx_t_2; /* "mtrand.pyx":882 * 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 = 882; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_v_hi = __pyx_t_2; } __pyx_L3:; /* "mtrand.pyx":884 * hi = high * * if lo >= hi : # <<<<<<<<<<<<<< * raise ValueError("low >= high") * */ __pyx_t_1 = (__pyx_v_lo >= __pyx_v_hi); if (__pyx_t_1) { /* "mtrand.pyx":885 * * if lo >= hi : * raise ValueError("low >= high") # <<<<<<<<<<<<<< * * diff = hi - 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 = 885; __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 = 885; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L4; } __pyx_L4:; /* "mtrand.pyx":887 * raise ValueError("low >= high") * * diff = hi - lo - 1UL # <<<<<<<<<<<<<< * if size is None: * rv = lo + rk_interval(diff, self. internal_state) */ __pyx_v_diff = ((((unsigned long)__pyx_v_hi) - ((unsigned long)__pyx_v_lo)) - 1UL); /* "mtrand.pyx":888 * * diff = hi - lo - 1UL * if size is None: # <<<<<<<<<<<<<< * rv = lo + rk_interval(diff, self. internal_state) * return rv */ __pyx_t_1 = (__pyx_v_size == Py_None); if (__pyx_t_1) { /* "mtrand.pyx":889 * diff = hi - lo - 1UL * if size is None: * rv = lo + 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":890 * if size is None: * rv = lo + rk_interval(diff, self. internal_state) * return rv # <<<<<<<<<<<<<< * else: * array = 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 = 890; __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":892 * return rv * else: * array = np.empty(size, int) # <<<<<<<<<<<<<< * length = PyArray_SIZE(array) * array_data = PyArray_DATA(array) */ __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 892; __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 = 892; __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 = 892; __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 = 892; __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":893 * else: * array = np.empty(size, int) * length = PyArray_SIZE(array) # <<<<<<<<<<<<<< * array_data = PyArray_DATA(array) * for i from 0 <= i < length: */ __pyx_v_length = PyArray_SIZE(arrayObject); /* "mtrand.pyx":894 * array = np.empty(size, int) * length = PyArray_SIZE(array) * array_data = PyArray_DATA(array) # <<<<<<<<<<<<<< * for i from 0 <= i < length: * rv = lo + rk_interval(diff, self. internal_state) */ __pyx_v_array_data = ((long *)PyArray_DATA(arrayObject)); /* "mtrand.pyx":895 * length = PyArray_SIZE(array) * array_data = PyArray_DATA(array) * for i from 0 <= i < length: # <<<<<<<<<<<<<< * rv = lo + 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":896 * array_data = PyArray_DATA(array) * for i from 0 <= i < length: * rv = lo + 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":897 * for i from 0 <= i < length: * rv = lo + rk_interval(diff, self. internal_state) * array_data[i] = rv # <<<<<<<<<<<<<< * return array * */ (__pyx_v_array_data[__pyx_v_i]) = __pyx_v_rv; } /* "mtrand.pyx":898 * rv = lo + 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 = 900; __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":900 * 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":923 * """ * 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 = 923; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_v_bytestring = __pyx_t_1; __pyx_t_1 = 0; /* "mtrand.pyx":924 * 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":925 * 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":928 * * * 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 = 928; __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 = 928; __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":1006 * * # 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 = 1006; __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 = 1006; __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 = 1006; __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 = 1006; __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 = 1006; __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 = 1006; __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 = 1006; __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":1007 * # 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 = 1007; __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 = 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 * 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":1010 * 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 = 1010; __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 = 1010; __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 = 1010; __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 = 1010; __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 = 1010; __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 = 1010; __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":1011 * # __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 = 1011; __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":1012 * 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 = 1012; __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 = 1012; __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":1013 * 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 = 1013; __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 = 1013; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_5) { /* "mtrand.pyx":1014 * 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 = 1014; __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 = 1014; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L14; } __pyx_L14:; goto __pyx_L3; } /* "mtrand.pyx":1015 * 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 = 1015; __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 = 1015; __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 = 1015; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_5) { /* "mtrand.pyx":1016 * 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 = 1016; __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 = 1016; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L3; } /*else*/ { /* "mtrand.pyx":1018 * 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 = 1018; __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 = 1018; __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":1019 * 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":1020 * 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 = 1020; __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 = 1020; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L15; } __pyx_L15:; } __pyx_L3:; /* "mtrand.pyx":1022 * 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 = 1022; __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 = 1022; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_5) { /* "mtrand.pyx":1023 * * 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 = 1023; __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 = 1023; __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 = 1023; __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 = 1023; __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 = 1023; __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 = 1023; __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 = 1023; __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 = 1023; __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 = 1023; __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 = 1023; __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 = 1023; __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":1024 * 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 = 1024; __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 = 1024; __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 = 1024; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; if (__pyx_t_5) { /* "mtrand.pyx":1025 * 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 = 1025; __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 = 1025; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L17; } __pyx_L17:; /* "mtrand.pyx":1026 * 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 = 1026; __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 = 1026; __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 = 1026; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; if (__pyx_t_5) { /* "mtrand.pyx":1027 * 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 = 1027; __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 = 1027; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L18; } __pyx_L18:; /* "mtrand.pyx":1028 * 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 = 1028; __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 = 1028; __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 = 1028; __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 = 1028; __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 = 1028; __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 = 1028; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; if (__pyx_t_5) { /* "mtrand.pyx":1029 * 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 = 1029; __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 = 1029; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L19; } __pyx_L19:; /* "mtrand.pyx":1030 * 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 = 1030; __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 = 1030; __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 = 1030; __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 = 1030; __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 = 1030; __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 = 1030; __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 = 1030; __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":1031 * 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 = 1031; __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 = 1031; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L20; } __pyx_L20:; goto __pyx_L16; } __pyx_L16:; /* "mtrand.pyx":1033 * 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":1034 * * 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":1035 * 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 = 1035; __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 = 1035; __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 = 1035; __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 = 1035; __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 = 1035; __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 = 1035; __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 = 1035; __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 = 1035; __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":1037 * 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":1040 * * # 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 = 1040; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (__pyx_t_11) { /* "mtrand.pyx":1041 * # 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 = 1041; __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 = 1041; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; if (__pyx_t_11) { /* "mtrand.pyx":1042 * 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 = 1042; __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 = 1042; __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":1043 * 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 = 1043; __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 = 1043; __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":1044 * 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 = 1044; __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 = 1044; __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 = 1044; __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":1045 * 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 = 1045; __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 = 1045; __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 = 1045; __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 = 1045; __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 = 1045; __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":1046 * 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 = 1046; __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 = 1046; __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 = 1046; __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 = 1046; __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 = 1046; __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 = 1046; __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 = 1046; __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":1048 * 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 = 1048; __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 = 1048; __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 = 1048; __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 = 1048; __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 = 1048; __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":1050 * 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 = 1050; __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 = 1050; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; if (__pyx_t_11) { /* "mtrand.pyx":1051 * 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 = 1051; __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 = 1051; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L24; } __pyx_L24:; /* "mtrand.pyx":1054 * "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 = 1054; __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 = 1054; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; if (__pyx_t_11) { /* "mtrand.pyx":1055 * * 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 = 1055; __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 = 1055; __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 = 1055; __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 = 1055; __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 = 1055; __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 = 1055; __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 = 1055; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_11) { /* "mtrand.pyx":1056 * 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 = 1056; __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 = 1056; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L26; } __pyx_L26:; /* "mtrand.pyx":1057 * 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":1058 * 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 = 1058; __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 = 1058; __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":1059 * 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 = 1059; __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 = 1059; __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 = 1059; __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 = 1059; __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 = 1059; __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 = 1059; __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 = 1059; __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 = 1059; __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":1060 * 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 = 1060; __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 = 1060; __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":1061 * 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 = 1061; __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 = 1061; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; if (!__pyx_t_11) break; /* "mtrand.pyx":1062 * 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 = 1062; __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 = 1062; __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 = 1062; __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 = 1062; __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":1063 * 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 = 1063; __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 = 1063; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_11) { /* "mtrand.pyx":1064 * 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 = 1064; __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 = 1064; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; goto __pyx_L29; } __pyx_L29:; /* "mtrand.pyx":1065 * 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 = 1065; __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 = 1065; __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 = 1065; __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 = 1065; __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":1066 * 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 = 1066; __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 = 1066; __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":1067 * 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 = 1067; __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 = 1067; __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 = 1067; __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 = 1067; __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 = 1067; __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":1068 * 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 = 1068; __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 = 1068; __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 = 1068; __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 = 1068; __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 = 1068; __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 = 1068; __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 = 1068; __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 = 1068; __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 = 1068; __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 = 1068; __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 = 1068; __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 = 1068; __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 = 1068; __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":1069 * 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 = 1069; __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 = 1069; __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":1070 * _, 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 = 1070; __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 = 1070; __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 = 1070; __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":1071 * 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 = 1071; __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 = 1071; __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 = 1071; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; /* "mtrand.pyx":1072 * 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 = 1072; __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 = 1072; __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":1073 * 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":1075 * 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 = 1075; __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 = 1075; __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 = 1075; __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 = 1075; __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":1076 * 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":1077 * 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 = 1077; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L32; } __pyx_L32:; } __pyx_L25:; } __pyx_L22:; /* "mtrand.pyx":1079 * 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 = 1079; __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 = 1079; __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 = 1079; __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":1081 * 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 = 1081; __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 = 1081; __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":1084 * * #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 = 1084; __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 = 1084; __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 = 1084; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_13) { /* "mtrand.pyx":1085 * #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":1087 * 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 = 1087; __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 = 1087; __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 = 1087; __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":1093 * # 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 = 1093; __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 = 1093; __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 = 1093; __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 = 1093; __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 = 1093; __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 = 1093; __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":1094 * # 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 = 1094; __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 = 1094; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; /* "mtrand.pyx":1095 * 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":1097 * 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 = 1097; __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":1100 * * * 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 = 1100; __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 = 1100; __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":1174 * 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":1175 * * 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":1176 * 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":1177 * fhigh = PyFloat_AsDouble(high) * if not PyErr_Occurred(): * return cont2_array_sc(self.internal_state, rk_uniform, size, flow, fhigh-flow) # <<<<<<<<<<<<<< * PyErr_Clear() * olow = 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 = 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; goto __pyx_L3; } __pyx_L3:; /* "mtrand.pyx":1178 * if not PyErr_Occurred(): * return cont2_array_sc(self.internal_state, rk_uniform, size, flow, fhigh-flow) * PyErr_Clear() # <<<<<<<<<<<<<< * olow = PyArray_FROM_OTF(low, NPY_DOUBLE, NPY_ARRAY_ALIGNED) * ohigh = PyArray_FROM_OTF(high, NPY_DOUBLE, NPY_ARRAY_ALIGNED) */ PyErr_Clear(); /* "mtrand.pyx":1179 * return cont2_array_sc(self.internal_state, rk_uniform, size, flow, fhigh-flow) * PyErr_Clear() * olow = PyArray_FROM_OTF(low, NPY_DOUBLE, NPY_ARRAY_ALIGNED) # <<<<<<<<<<<<<< * ohigh = 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 = 1179; __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":1180 * PyErr_Clear() * olow = PyArray_FROM_OTF(low, NPY_DOUBLE, NPY_ARRAY_ALIGNED) * ohigh = 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 = 1180; __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":1181 * olow = PyArray_FROM_OTF(low, NPY_DOUBLE, NPY_ARRAY_ALIGNED) * ohigh = 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 = 1181; __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 = 1181; __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 = 1181; __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 = 1181; __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":1182 * ohigh = 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 = PyArray_EnsureArray(temp) */ Py_INCREF(__pyx_v_temp); /* "mtrand.pyx":1184 * Py_INCREF(temp) # needed to get around Pyrex's automatic reference-counting * # rules because EnsureArray steals a reference * odiff = 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 = 1184; __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":1185 * # rules because EnsureArray steals a reference * odiff = 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 = 1185; __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":1187 * 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":1226 * * """ * 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 = 1226; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_2 = (__pyx_t_1 == 0); if (__pyx_t_2) { /* "mtrand.pyx":1227 * """ * 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 = 1227; __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 = 1227; __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":1229 * 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 = 1229; __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 = 1229; __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 = 1229; __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 = 1229; __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":1231 * 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":1283 * * """ * 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 = 1283; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_2 = (__pyx_t_1 == 0); if (__pyx_t_2) { /* "mtrand.pyx":1284 * """ * 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 = 1284; __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 = 1284; __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":1286 * 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 = 1286; __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 = 1286; __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 = 1286; __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 \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":1288 * 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 = 1288; __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 = 1288; __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":1360 * * """ * if high is None: # <<<<<<<<<<<<<< * high = low * low = 1 */ __pyx_t_1 = (__pyx_v_high == Py_None); if (__pyx_t_1) { /* "mtrand.pyx":1361 * """ * 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":1362 * 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":1363 * 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 = 1363; __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 = 1363; __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 = 1363; __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 = 1363; __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":1366 * * # 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 = 1366; __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 = 1366; __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":1396 * * """ * 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 = 1396; __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":1398 * 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 = 1398; __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 = 1398; __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":1483 * 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":1484 * * 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":1485 * 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":1486 * 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":1487 * 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 = 1487; __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 = 1487; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L4; } __pyx_L4:; /* "mtrand.pyx":1488 * 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 = 1488; __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":1490 * return cont2_array_sc(self.internal_state, rk_normal, size, floc, fscale) * * PyErr_Clear() # <<<<<<<<<<<<<< * * oloc = PyArray_FROM_OTF(loc, NPY_DOUBLE, NPY_ARRAY_ALIGNED) */ PyErr_Clear(); /* "mtrand.pyx":1492 * 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)): */ __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 = 1492; __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":1493 * * 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)): * 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 = 1493; __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":1494 * 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)): # <<<<<<<<<<<<<< * 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 = 1494; __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 = 1494; __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 = 1494; __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 = 1494; __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 = 1494; __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 = 1494; __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 = 1494; __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 = 1494; __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 = 1494; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_1) { /* "mtrand.pyx":1495 * oscale = 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 = 1495; __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 = 1495; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L5; } __pyx_L5:; /* "mtrand.pyx":1496 * 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 = 1496; __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":1498 * 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 = 1498; __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 = 1498; __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 = 1498; __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":1538 * 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":1539 * * 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":1540 * 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":1541 * 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":1542 * 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 = 1542; __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 = 1542; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L4; } __pyx_L4:; /* "mtrand.pyx":1543 * 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":1544 * 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 = 1544; __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 = 1544; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L5; } __pyx_L5:; /* "mtrand.pyx":1545 * 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 = 1545; __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":1547 * return cont2_array_sc(self.internal_state, rk_beta, size, fa, fb) * * PyErr_Clear() # <<<<<<<<<<<<<< * * oa = PyArray_FROM_OTF(a, NPY_DOUBLE, NPY_ARRAY_ALIGNED) */ PyErr_Clear(); /* "mtrand.pyx":1549 * PyErr_Clear() * * oa = PyArray_FROM_OTF(a, NPY_DOUBLE, NPY_ARRAY_ALIGNED) # <<<<<<<<<<<<<< * ob = 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 = 1549; __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":1550 * * oa = PyArray_FROM_OTF(a, NPY_DOUBLE, NPY_ARRAY_ALIGNED) * ob = 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 = 1550; __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":1551 * oa = PyArray_FROM_OTF(a, NPY_DOUBLE, NPY_ARRAY_ALIGNED) * ob = 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 = 1551; __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 = 1551; __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 = 1551; __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 = 1551; __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 = 1551; __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 = 1551; __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 = 1551; __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 = 1551; __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 = 1551; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_1) { /* "mtrand.pyx":1552 * ob = 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 = 1552; __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 = 1552; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L6; } __pyx_L6:; /* "mtrand.pyx":1553 * 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 = 1553; __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 = 1553; __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 = 1553; __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 = 1553; __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 = 1553; __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 = 1553; __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 = 1553; __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 = 1553; __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 = 1553; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_1) { /* "mtrand.pyx":1554 * 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 = 1554; __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 = 1554; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L7; } __pyx_L7:; /* "mtrand.pyx":1555 * 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 = 1555; __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":1557 * 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 = 1557; __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 = 1557; __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":1598 * cdef double fscale * * fscale = PyFloat_AsDouble(scale) # <<<<<<<<<<<<<< * if not PyErr_Occurred(): * if fscale <= 0: */ __pyx_v_fscale = PyFloat_AsDouble(__pyx_v_scale); /* "mtrand.pyx":1599 * * 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":1600 * 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":1601 * 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 = 1601; __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 = 1601; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L4; } __pyx_L4:; /* "mtrand.pyx":1602 * 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 = 1602; __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":1604 * return cont1_array_sc(self.internal_state, rk_exponential, size, fscale) * * PyErr_Clear() # <<<<<<<<<<<<<< * * oscale = PyArray_FROM_OTF(scale, NPY_DOUBLE, NPY_ARRAY_ALIGNED) */ PyErr_Clear(); /* "mtrand.pyx":1606 * PyErr_Clear() * * 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 = 1606; __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":1607 * * oscale = 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 = 1607; __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 = 1607; __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 = 1607; __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 = 1607; __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 = 1607; __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 = 1607; __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 = 1607; __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 = 1607; __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 = 1607; __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 = 1607; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_1) { /* "mtrand.pyx":1608 * oscale = 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 = 1608; __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 = 1608; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L5; } __pyx_L5:; /* "mtrand.pyx":1609 * 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 = 1609; __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":1611 * 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 = 1611; __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 = 1611; __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":1637 * * """ * 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 = 1637; __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":1639 * 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 = 1639; __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 = 1639; __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":1709 * cdef double fshape * * fshape = PyFloat_AsDouble(shape) # <<<<<<<<<<<<<< * if not PyErr_Occurred(): * if fshape <= 0: */ __pyx_v_fshape = PyFloat_AsDouble(__pyx_v_shape); /* "mtrand.pyx":1710 * * 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":1711 * 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":1712 * 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 = 1712; __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 = 1712; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L4; } __pyx_L4:; /* "mtrand.pyx":1713 * 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 = 1713; __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":1715 * return cont1_array_sc(self.internal_state, rk_standard_gamma, size, fshape) * * PyErr_Clear() # <<<<<<<<<<<<<< * oshape = PyArray_FROM_OTF(shape, NPY_DOUBLE, NPY_ARRAY_ALIGNED) * if np.any(np.less_equal(oshape, 0.0)): */ PyErr_Clear(); /* "mtrand.pyx":1716 * * PyErr_Clear() * oshape = 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 = 1716; __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":1717 * PyErr_Clear() * oshape = 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 = 1717; __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 = 1717; __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 = 1717; __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 = 1717; __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 = 1717; __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 = 1717; __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 = 1717; __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 = 1717; __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 = 1717; __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 = 1717; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_1) { /* "mtrand.pyx":1718 * oshape = 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 = 1718; __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 = 1718; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L5; } __pyx_L5:; /* "mtrand.pyx":1719 * 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 = 1719; __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":1721 * 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 = 1721; __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 = 1721; __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":1794 * 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":1795 * * 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":1796 * 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":1797 * 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":1798 * 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 = 1798; __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 = 1798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L4; } __pyx_L4:; /* "mtrand.pyx":1799 * 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":1800 * 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 = 1800; __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 = 1800; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L5; } __pyx_L5:; /* "mtrand.pyx":1801 * 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 = 1801; __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":1803 * return cont2_array_sc(self.internal_state, rk_gamma, size, fshape, fscale) * * PyErr_Clear() # <<<<<<<<<<<<<< * oshape = PyArray_FROM_OTF(shape, NPY_DOUBLE, NPY_ARRAY_ALIGNED) * oscale = PyArray_FROM_OTF(scale, NPY_DOUBLE, NPY_ARRAY_ALIGNED) */ PyErr_Clear(); /* "mtrand.pyx":1804 * * PyErr_Clear() * oshape = PyArray_FROM_OTF(shape, NPY_DOUBLE, NPY_ARRAY_ALIGNED) # <<<<<<<<<<<<<< * oscale = 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 = 1804; __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":1805 * PyErr_Clear() * oshape = PyArray_FROM_OTF(shape, NPY_DOUBLE, NPY_ARRAY_ALIGNED) * oscale = 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 = 1805; __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":1806 * oshape = PyArray_FROM_OTF(shape, NPY_DOUBLE, NPY_ARRAY_ALIGNED) * oscale = 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 = 1806; __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 = 1806; __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 = 1806; __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 = 1806; __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 = 1806; __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 = 1806; __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 = 1806; __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 = 1806; __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 = 1806; __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 = 1806; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; if (__pyx_t_1) { /* "mtrand.pyx":1807 * oscale = 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 = 1807; __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 = 1807; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L6; } __pyx_L6:; /* "mtrand.pyx":1808 * 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 = 1808; __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 = 1808; __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 = 1808; __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 = 1808; __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 = 1808; __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 = 1808; __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 = 1808; __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 = 1808; __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 = 1808; __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 = 1808; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; if (__pyx_t_1) { /* "mtrand.pyx":1809 * 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 = 1809; __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 = 1809; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L7; } __pyx_L7:; /* "mtrand.pyx":1810 * 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 = 1810; __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":1812 * 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 = 1812; __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 = 1812; __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 = 1812; __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":1895 * 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":1896 * * 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":1897 * 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":1898 * 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":1899 * 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 = 1899; __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 = 1899; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L4; } __pyx_L4:; /* "mtrand.pyx":1900 * 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":1901 * 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 = 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_L5; } __pyx_L5:; /* "mtrand.pyx":1902 * 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 = 1902; __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":1904 * return cont2_array_sc(self.internal_state, rk_f, size, fdfnum, fdfden) * * PyErr_Clear() # <<<<<<<<<<<<<< * * odfnum = PyArray_FROM_OTF(dfnum, NPY_DOUBLE, NPY_ARRAY_ALIGNED) */ PyErr_Clear(); /* "mtrand.pyx":1906 * PyErr_Clear() * * odfnum = PyArray_FROM_OTF(dfnum, NPY_DOUBLE, NPY_ARRAY_ALIGNED) # <<<<<<<<<<<<<< * odfden = 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 = 1906; __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":1907 * * odfnum = PyArray_FROM_OTF(dfnum, NPY_DOUBLE, NPY_ARRAY_ALIGNED) * odfden = 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 = 1907; __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":1908 * odfnum = PyArray_FROM_OTF(dfnum, NPY_DOUBLE, NPY_ARRAY_ALIGNED) * odfden = 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 = 1908; __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 = 1908; __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 = 1908; __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 = 1908; __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 = 1908; __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 = 1908; __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 = 1908; __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 = 1908; __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 = 1908; __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 = 1908; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; if (__pyx_t_1) { /* "mtrand.pyx":1909 * odfden = 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 = 1909; __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 = 1909; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L6; } __pyx_L6:; /* "mtrand.pyx":1910 * 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 = 1910; __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 = 1910; __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 = 1910; __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 = 1910; __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 = 1910; __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 = 1910; __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 = 1910; __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 = 1910; __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 = 1910; __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 = 1910; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; if (__pyx_t_1) { /* "mtrand.pyx":1911 * 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 = 1911; __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 = 1911; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L7; } __pyx_L7:; /* "mtrand.pyx":1912 * 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 = 1912; __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":1914 * 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 = 1914; __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 = 1914; __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 = 1914; __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 = 1914; __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":1981 * 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":1982 * * 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":1983 * 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":1984 * 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":1985 * 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":1986 * 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 = 1986; __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 = 1986; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L4; } __pyx_L4:; /* "mtrand.pyx":1987 * 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":1988 * 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 = 1988; __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 = 1988; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L5; } __pyx_L5:; /* "mtrand.pyx":1989 * 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":1990 * 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 = 1990; __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 = 1990; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L6; } __pyx_L6:; /* "mtrand.pyx":1991 * 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":1992 * 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 = 1991; __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":1994 * fdfnum, fdfden, fnonc) * * PyErr_Clear() # <<<<<<<<<<<<<< * * odfnum = PyArray_FROM_OTF(dfnum, NPY_DOUBLE, NPY_ARRAY_ALIGNED) */ PyErr_Clear(); /* "mtrand.pyx":1996 * PyErr_Clear() * * odfnum = PyArray_FROM_OTF(dfnum, NPY_DOUBLE, NPY_ARRAY_ALIGNED) # <<<<<<<<<<<<<< * odfden = PyArray_FROM_OTF(dfden, NPY_DOUBLE, NPY_ARRAY_ALIGNED) * ononc = 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 = 1996; __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":1997 * * odfnum = PyArray_FROM_OTF(dfnum, NPY_DOUBLE, NPY_ARRAY_ALIGNED) * odfden = PyArray_FROM_OTF(dfden, NPY_DOUBLE, NPY_ARRAY_ALIGNED) # <<<<<<<<<<<<<< * ononc = 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 = 1997; __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":1998 * odfnum = PyArray_FROM_OTF(dfnum, NPY_DOUBLE, NPY_ARRAY_ALIGNED) * odfden = PyArray_FROM_OTF(dfden, NPY_DOUBLE, NPY_ARRAY_ALIGNED) * ononc = 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 = 1998; __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":2000 * ononc = 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 = 2000; __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 = 2000; __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 = 2000; __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 = 2000; __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 = 2000; __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 = 2000; __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 = 2000; __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 = 2000; __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 = 2000; __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 = 2000; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_1) { /* "mtrand.pyx":2001 * * 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 = 2001; __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 = 2001; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L7; } __pyx_L7:; /* "mtrand.pyx":2002 * 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 = 2002; __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 = 2002; __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 = 2002; __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 = 2002; __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 = 2002; __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 = 2002; __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 = 2002; __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 = 2002; __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 = 2002; __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 = 2002; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_1) { /* "mtrand.pyx":2003 * 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 = 2003; __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 = 2003; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L8; } __pyx_L8:; /* "mtrand.pyx":2004 * 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 = 2004; __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 = 2004; __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 = 2004; __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 = 2004; __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 = 2004; __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 = 2004; __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 = 2004; __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 = 2004; __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 = 2004; __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 = 2004; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_1) { /* "mtrand.pyx":2005 * 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 = 2005; __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 = 2005; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L9; } __pyx_L9:; /* "mtrand.pyx":2006 * 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":2007 * 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 = 2006; __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 `_\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":2009 * 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 = 2009; __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 = 2009; __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":2074 * cdef double fdf * * fdf = PyFloat_AsDouble(df) # <<<<<<<<<<<<<< * if not PyErr_Occurred(): * if fdf <= 0: */ __pyx_v_fdf = PyFloat_AsDouble(__pyx_v_df); /* "mtrand.pyx":2075 * * 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":2076 * 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":2077 * 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 = 2077; __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 = 2077; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L4; } __pyx_L4:; /* "mtrand.pyx":2078 * 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 = 2078; __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":2080 * return cont1_array_sc(self.internal_state, rk_chisquare, size, fdf) * * PyErr_Clear() # <<<<<<<<<<<<<< * * odf = PyArray_FROM_OTF(df, NPY_DOUBLE, NPY_ARRAY_ALIGNED) */ PyErr_Clear(); /* "mtrand.pyx":2082 * PyErr_Clear() * * odf = 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 = 2082; __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":2083 * * odf = 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 = 2083; __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 = 2083; __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 = 2083; __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 = 2083; __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 = 2083; __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 = 2083; __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 = 2083; __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 = 2083; __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 = 2083; __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 = 2083; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_1) { /* "mtrand.pyx":2084 * odf = 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 = 2084; __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 = 2084; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L5; } __pyx_L5:; /* "mtrand.pyx":2085 * 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 = 2085; __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":2087 * 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 = 2087; __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 = 2087; __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 = 2087; __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":2158 * 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":2159 * 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":2160 * 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":2161 * 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":2162 * 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 = 2162; __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 = 2162; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L4; } __pyx_L4:; /* "mtrand.pyx":2163 * 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":2164 * 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 = 2164; __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 = 2164; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L5; } __pyx_L5:; /* "mtrand.pyx":2165 * 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":2166 * 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 = 2165; __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":2168 * size, fdf, fnonc) * * PyErr_Clear() # <<<<<<<<<<<<<< * * odf = PyArray_FROM_OTF(df, NPY_DOUBLE, NPY_ARRAY_ALIGNED) */ PyErr_Clear(); /* "mtrand.pyx":2170 * PyErr_Clear() * * odf = PyArray_FROM_OTF(df, NPY_DOUBLE, NPY_ARRAY_ALIGNED) # <<<<<<<<<<<<<< * ononc = 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 = 2170; __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":2171 * * odf = PyArray_FROM_OTF(df, NPY_DOUBLE, NPY_ARRAY_ALIGNED) * ononc = 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 = 2171; __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":2172 * odf = PyArray_FROM_OTF(df, NPY_DOUBLE, NPY_ARRAY_ALIGNED) * ononc = 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 = 2172; __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 = 2172; __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 = 2172; __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 = 2172; __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 = 2172; __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 = 2172; __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 = 2172; __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 = 2172; __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 = 2172; __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 = 2172; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; if (__pyx_t_1) { /* "mtrand.pyx":2173 * ononc = 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 = 2173; __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 = 2173; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L6; } __pyx_L6:; /* "mtrand.pyx":2174 * 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 = 2174; __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 = 2174; __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 = 2174; __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 = 2174; __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 = 2174; __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 = 2174; __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 = 2174; __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 = 2174; __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 = 2174; __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 = 2174; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; if (__pyx_t_1) { /* "mtrand.pyx":2175 * 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 = 2175; __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 = 2175; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L7; } __pyx_L7:; /* "mtrand.pyx":2176 * 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":2177 * 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 = 2176; __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":2179 * 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 = 2179; __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 = 2179; __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":2238 * * """ * 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 = 2238; __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 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 = 2240; __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 = 2240; __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":2328 * cdef double fdf * * fdf = PyFloat_AsDouble(df) # <<<<<<<<<<<<<< * if not PyErr_Occurred(): * if fdf <= 0: */ __pyx_v_fdf = PyFloat_AsDouble(__pyx_v_df); /* "mtrand.pyx":2329 * * 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":2330 * 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":2331 * 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 = 2331; __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 = 2331; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L4; } __pyx_L4:; /* "mtrand.pyx":2332 * 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 = 2332; __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":2334 * return cont1_array_sc(self.internal_state, rk_standard_t, size, fdf) * * PyErr_Clear() # <<<<<<<<<<<<<< * * odf = PyArray_FROM_OTF(df, NPY_DOUBLE, NPY_ARRAY_ALIGNED) */ PyErr_Clear(); /* "mtrand.pyx":2336 * PyErr_Clear() * * odf = 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 = 2336; __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":2337 * * odf = 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 = 2337; __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 = 2337; __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 = 2337; __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 = 2337; __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 = 2337; __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 = 2337; __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 = 2337; __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 = 2337; __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 = 2337; __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 = 2337; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_1) { /* "mtrand.pyx":2338 * odf = 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 = 2338; __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 = 2338; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L5; } __pyx_L5:; /* "mtrand.pyx":2339 * 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 = 2339; __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":2341 * 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 = 2341; __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 = 2341; __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 = 2341; __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":2420 * 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":2421 * * 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":2422 * 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":2423 * 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":2424 * 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 = 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_L4; } __pyx_L4:; /* "mtrand.pyx":2425 * 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 = 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; goto __pyx_L3; } __pyx_L3:; /* "mtrand.pyx":2427 * return cont2_array_sc(self.internal_state, rk_vonmises, size, fmu, fkappa) * * PyErr_Clear() # <<<<<<<<<<<<<< * * omu = PyArray_FROM_OTF(mu, NPY_DOUBLE, NPY_ARRAY_ALIGNED) */ PyErr_Clear(); /* "mtrand.pyx":2429 * PyErr_Clear() * * omu = PyArray_FROM_OTF(mu, NPY_DOUBLE, NPY_ARRAY_ALIGNED) # <<<<<<<<<<<<<< * okappa = 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 = 2429; __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":2430 * * omu = PyArray_FROM_OTF(mu, NPY_DOUBLE, NPY_ARRAY_ALIGNED) * okappa = 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 = 2430; __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":2431 * omu = PyArray_FROM_OTF(mu, NPY_DOUBLE, NPY_ARRAY_ALIGNED) * okappa = 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 = 2431; __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 = 2431; __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 = 2431; __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 = 2431; __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 = 2431; __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 = 2431; __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 = 2431; __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 = 2431; __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 = 2431; __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 = 2431; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; if (__pyx_t_1) { /* "mtrand.pyx":2432 * okappa = 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 = 2432; __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 = 2432; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L5; } __pyx_L5:; /* "mtrand.pyx":2433 * 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 = 2433; __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":2435 * 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 = 2435; __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 = 2435; __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":2518 * cdef double fa * * fa = PyFloat_AsDouble(a) # <<<<<<<<<<<<<< * if not PyErr_Occurred(): * if fa <= 0: */ __pyx_v_fa = PyFloat_AsDouble(__pyx_v_a); /* "mtrand.pyx":2519 * * 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":2520 * 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":2521 * 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 = 2521; __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 = 2521; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L4; } __pyx_L4:; /* "mtrand.pyx":2522 * 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 = 2522; __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":2524 * return cont1_array_sc(self.internal_state, rk_pareto, size, fa) * * PyErr_Clear() # <<<<<<<<<<<<<< * * oa = PyArray_FROM_OTF(a, NPY_DOUBLE, NPY_ARRAY_ALIGNED) */ PyErr_Clear(); /* "mtrand.pyx":2526 * PyErr_Clear() * * oa = 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 = 2526; __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":2527 * * oa = 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 = 2527; __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 = 2527; __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 = 2527; __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 = 2527; __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 = 2527; __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 = 2527; __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 = 2527; __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 = 2527; __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 = 2527; __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 = 2527; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_1) { /* "mtrand.pyx":2528 * oa = 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 = 2528; __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 = 2528; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L5; } __pyx_L5:; /* "mtrand.pyx":2529 * 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 = 2529; __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":2531 * 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 = 2531; __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 = 2531; __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":2618 * cdef double fa * * fa = PyFloat_AsDouble(a) # <<<<<<<<<<<<<< * if not PyErr_Occurred(): * if fa <= 0: */ __pyx_v_fa = PyFloat_AsDouble(__pyx_v_a); /* "mtrand.pyx":2619 * * 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":2620 * 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":2621 * 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 = 2621; __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 = 2621; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L4; } __pyx_L4:; /* "mtrand.pyx":2622 * 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 = 2622; __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":2624 * return cont1_array_sc(self.internal_state, rk_weibull, size, fa) * * PyErr_Clear() # <<<<<<<<<<<<<< * * oa = PyArray_FROM_OTF(a, NPY_DOUBLE, NPY_ARRAY_ALIGNED) */ PyErr_Clear(); /* "mtrand.pyx":2626 * PyErr_Clear() * * oa = 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 = 2626; __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":2627 * * oa = 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 = 2627; __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 = 2627; __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 = 2627; __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 = 2627; __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 = 2627; __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 = 2627; __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 = 2627; __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 = 2627; __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 = 2627; __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 = 2627; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_1) { /* "mtrand.pyx":2628 * oa = 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 = 2628; __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 = 2628; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L5; } __pyx_L5:; /* "mtrand.pyx":2629 * 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 = 2629; __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":2631 * 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 = 2631; __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 = 2631; __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":2727 * cdef double fa * * fa = PyFloat_AsDouble(a) # <<<<<<<<<<<<<< * if not PyErr_Occurred(): * if fa <= 0: */ __pyx_v_fa = PyFloat_AsDouble(__pyx_v_a); /* "mtrand.pyx":2728 * * 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":2729 * 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":2730 * 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 = 2730; __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 = 2730; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L4; } __pyx_L4:; /* "mtrand.pyx":2731 * 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 = 2731; __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":2733 * return cont1_array_sc(self.internal_state, rk_power, size, fa) * * PyErr_Clear() # <<<<<<<<<<<<<< * * oa = PyArray_FROM_OTF(a, NPY_DOUBLE, NPY_ARRAY_ALIGNED) */ PyErr_Clear(); /* "mtrand.pyx":2735 * PyErr_Clear() * * oa = 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 = 2735; __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":2736 * * oa = 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 = 2736; __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 = 2736; __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 = 2736; __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 = 2736; __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 = 2736; __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 = 2736; __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 = 2736; __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 = 2736; __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 = 2736; __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 = 2736; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_1) { /* "mtrand.pyx":2737 * oa = 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 = 2737; __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 = 2737; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L5; } __pyx_L5:; /* "mtrand.pyx":2738 * 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 = 2738; __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":2740 * 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 = 2740; __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 = 2740; __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":2816 * 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":2817 * * 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":2818 * 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":2819 * 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":2820 * 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 = 2820; __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 = 2820; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L4; } __pyx_L4:; /* "mtrand.pyx":2821 * 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 = 2821; __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":2823 * 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":2824 * * 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 = 2824; __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 = 2824; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_v_oloc = ((PyArrayObject *)__pyx_t_2); __pyx_t_2 = 0; /* "mtrand.pyx":2825 * 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 = 2825; __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 = 2825; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_v_oscale = ((PyArrayObject *)__pyx_t_2); __pyx_t_2 = 0; /* "mtrand.pyx":2826 * 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 = 2826; __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 = 2826; __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 = 2826; __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 = 2826; __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 = 2826; __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 = 2826; __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 = 2826; __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 = 2826; __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 = 2826; __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 = 2826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; if (__pyx_t_1) { /* "mtrand.pyx":2827 * 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 = 2827; __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 = 2827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L5; } __pyx_L5:; /* "mtrand.pyx":2828 * 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 = 2828; __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":2830 * 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 = 2830; __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 = 2830; __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":2947 * 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":2948 * * 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":2949 * 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":2950 * 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":2951 * 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 = 2951; __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 = 2951; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L4; } __pyx_L4:; /* "mtrand.pyx":2952 * 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 = 2952; __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":2954 * 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":2955 * * 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 = 2955; __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 = 2955; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_v_oloc = ((PyArrayObject *)__pyx_t_2); __pyx_t_2 = 0; /* "mtrand.pyx":2956 * 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 = 2956; __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 = 2956; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_v_oscale = ((PyArrayObject *)__pyx_t_2); __pyx_t_2 = 0; /* "mtrand.pyx":2957 * 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 = 2957; __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 = 2957; __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 = 2957; __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 = 2957; __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 = 2957; __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 = 2957; __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 = 2957; __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 = 2957; __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 = 2957; __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 = 2957; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; if (__pyx_t_1) { /* "mtrand.pyx":2958 * 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 = 2958; __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 = 2958; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L5; } __pyx_L5:; /* "mtrand.pyx":2959 * 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 = 2959; __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":2961 * 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 = 2961; __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 = 2961; __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":3035 * 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":3036 * * 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":3037 * 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":3038 * 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":3039 * 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 = 3039; __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 = 3039; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L4; } __pyx_L4:; /* "mtrand.pyx":3040 * 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 = 3040; __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":3042 * 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":3043 * * 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 = 3043; __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 = 3043; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_v_oloc = ((PyArrayObject *)__pyx_t_2); __pyx_t_2 = 0; /* "mtrand.pyx":3044 * 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 = 3044; __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 = 3044; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_v_oscale = ((PyArrayObject *)__pyx_t_2); __pyx_t_2 = 0; /* "mtrand.pyx":3045 * 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 = 3045; __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 = 3045; __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 = 3045; __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 = 3045; __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 = 3045; __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 = 3045; __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 = 3045; __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 = 3045; __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 = 3045; __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 = 3045; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; if (__pyx_t_1) { /* "mtrand.pyx":3046 * 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 = 3046; __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 = 3046; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L5; } __pyx_L5:; /* "mtrand.pyx":3047 * 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 = 3047; __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":3049 * 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 = 3049; __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 = 3049; __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":3154 * cdef double fmean, fsigma * * fmean = PyFloat_AsDouble(mean) # <<<<<<<<<<<<<< * fsigma = PyFloat_AsDouble(sigma) * */ __pyx_v_fmean = PyFloat_AsDouble(__pyx_v_mean); /* "mtrand.pyx":3155 * * fmean = PyFloat_AsDouble(mean) * fsigma = PyFloat_AsDouble(sigma) # <<<<<<<<<<<<<< * * if not PyErr_Occurred(): */ __pyx_v_fsigma = PyFloat_AsDouble(__pyx_v_sigma); /* "mtrand.pyx":3157 * 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":3158 * * 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":3159 * 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 = 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_L4; } __pyx_L4:; /* "mtrand.pyx":3160 * 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 = 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; goto __pyx_L3; } __pyx_L3:; /* "mtrand.pyx":3162 * 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":3164 * 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 = 3164; __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 = 3164; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_v_omean = ((PyArrayObject *)__pyx_t_2); __pyx_t_2 = 0; /* "mtrand.pyx":3165 * * 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 = 3165; __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 = 3165; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_v_osigma = ((PyArrayObject *)__pyx_t_2); __pyx_t_2 = 0; /* "mtrand.pyx":3166 * 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 = 3166; __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 = 3166; __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 = 3166; __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 = 3166; __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 = 3166; __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 = 3166; __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 = 3166; __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 = 3166; __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 = 3166; __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 = 3166; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; if (__pyx_t_1) { /* "mtrand.pyx":3167 * 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 = 3167; __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 = 3167; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L5; } __pyx_L5:; /* "mtrand.pyx":3168 * 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 = 3168; __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":3170 * 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 = 3170; __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 = 3170; __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":3228 * cdef double fscale * * fscale = PyFloat_AsDouble(scale) # <<<<<<<<<<<<<< * * if not PyErr_Occurred(): */ __pyx_v_fscale = PyFloat_AsDouble(__pyx_v_scale); /* "mtrand.pyx":3230 * 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":3231 * * 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":3232 * 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 = 3232; __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 = 3232; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L4; } __pyx_L4:; /* "mtrand.pyx":3233 * 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 = 3233; __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":3235 * return cont1_array_sc(self.internal_state, rk_rayleigh, size, fscale) * * PyErr_Clear() # <<<<<<<<<<<<<< * * oscale = PyArray_FROM_OTF(scale, NPY_DOUBLE, NPY_ARRAY_ALIGNED) */ PyErr_Clear(); /* "mtrand.pyx":3237 * PyErr_Clear() * * oscale = 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 = 3237; __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":3238 * * oscale = 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 = 3238; __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 = 3238; __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 = 3238; __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 = 3238; __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 = 3238; __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 = 3238; __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 = 3238; __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 = 3238; __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 = 3238; __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 = 3238; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_1) { /* "mtrand.pyx":3239 * oscale = 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 = 3239; __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 = 3239; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L5; } __pyx_L5:; /* "mtrand.pyx":3240 * 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 = 3240; __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":3242 * 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 = 3242; __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 = 3242; __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 = 3242; __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":3308 * 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":3309 * * 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":3310 * 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":3311 * 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":3312 * 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 = 3312; __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 = 3312; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L4; } __pyx_L4:; /* "mtrand.pyx":3313 * 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":3314 * 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 = 3314; __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 = 3314; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L5; } __pyx_L5:; /* "mtrand.pyx":3315 * 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 = 3315; __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":3317 * 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":3318 * * 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 = 3318; __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 = 3318; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_v_omean = ((PyArrayObject *)__pyx_t_2); __pyx_t_2 = 0; /* "mtrand.pyx":3319 * 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 = 3319; __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 = 3319; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_v_oscale = ((PyArrayObject *)__pyx_t_2); __pyx_t_2 = 0; /* "mtrand.pyx":3320 * 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 = 3320; __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 = 3320; __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 = 3320; __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 = 3320; __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 = 3320; __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 = 3320; __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 = 3320; __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 = 3320; __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 = 3320; __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 = 3320; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; if (__pyx_t_1) { /* "mtrand.pyx":3321 * 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 = 3321; __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 = 3321; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L6; } /* "mtrand.pyx":3322 * 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 = 3322; __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 = 3322; __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 = 3322; __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 = 3322; __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 = 3322; __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 = 3322; __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 = 3322; __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 = 3322; __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 = 3322; __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 = 3322; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; if (__pyx_t_1) { /* "mtrand.pyx":3323 * 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 = 3323; __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 = 3323; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L6; } __pyx_L6:; /* "mtrand.pyx":3324 * 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 = 3324; __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":3328 * * * 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 = 3328; __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 = 3328; __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 = 3328; __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 = 3328; __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":3388 * 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":3389 * * 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":3390 * 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":3391 * 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":3392 * 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":3393 * 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 = 3393; __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 = 3393; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L4; } __pyx_L4:; /* "mtrand.pyx":3394 * 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":3395 * 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 = 3395; __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 = 3395; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L5; } __pyx_L5:; /* "mtrand.pyx":3396 * 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":3397 * 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 = 3397; __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 = 3397; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L6; } __pyx_L6:; /* "mtrand.pyx":3398 * 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":3399 * 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 = 3398; __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":3401 * fmode, fright) * * PyErr_Clear() # <<<<<<<<<<<<<< * oleft = PyArray_FROM_OTF(left, NPY_DOUBLE, NPY_ARRAY_ALIGNED) * omode = PyArray_FROM_OTF(mode, NPY_DOUBLE, NPY_ARRAY_ALIGNED) */ PyErr_Clear(); /* "mtrand.pyx":3402 * * PyErr_Clear() * oleft = PyArray_FROM_OTF(left, NPY_DOUBLE, NPY_ARRAY_ALIGNED) # <<<<<<<<<<<<<< * omode = PyArray_FROM_OTF(mode, NPY_DOUBLE, NPY_ARRAY_ALIGNED) * oright = 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 = 3402; __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":3403 * PyErr_Clear() * oleft = PyArray_FROM_OTF(left, NPY_DOUBLE, NPY_ARRAY_ALIGNED) * omode = PyArray_FROM_OTF(mode, NPY_DOUBLE, NPY_ARRAY_ALIGNED) # <<<<<<<<<<<<<< * oright = 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 = 3403; __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":3404 * oleft = PyArray_FROM_OTF(left, NPY_DOUBLE, NPY_ARRAY_ALIGNED) * omode = PyArray_FROM_OTF(mode, NPY_DOUBLE, NPY_ARRAY_ALIGNED) * oright = 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 = 3404; __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":3406 * oright = 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 = 3406; __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 = 3406; __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 = 3406; __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 = 3406; __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 = 3406; __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 = 3406; __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 = 3406; __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 = 3406; __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 = 3406; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_1) { /* "mtrand.pyx":3407 * * 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 = 3407; __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 = 3407; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L7; } __pyx_L7:; /* "mtrand.pyx":3408 * 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 = 3408; __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 = 3408; __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 = 3408; __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 = 3408; __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 = 3408; __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 = 3408; __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 = 3408; __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 = 3408; __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 = 3408; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_1) { /* "mtrand.pyx":3409 * 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 = 3409; __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 = 3409; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L8; } __pyx_L8:; /* "mtrand.pyx":3410 * 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 = 3410; __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 = 3410; __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 = 3410; __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 = 3410; __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 = 3410; __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 = 3410; __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 = 3410; __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 = 3410; __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 = 3410; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; if (__pyx_t_1) { /* "mtrand.pyx":3411 * 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 = 3411; __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 = 3411; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L9; } __pyx_L9:; /* "mtrand.pyx":3412 * 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":3413 * 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 = 3412; __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":3416 * * # 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 = 3416; __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 = 3416; __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 = 3416; __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":3501 * 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":3502 * * 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":3503 * 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":3504 * 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":3505 * 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 = 3505; __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 = 3505; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L4; } __pyx_L4:; /* "mtrand.pyx":3506 * 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":3507 * 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 = 3507; __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 = 3507; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L5; } /* "mtrand.pyx":3508 * 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":3509 * 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 = 3509; __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 = 3509; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L5; } __pyx_L5:; /* "mtrand.pyx":3510 * 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 = 3510; __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":3512 * return discnp_array_sc(self.internal_state, rk_binomial, size, ln, fp) * * PyErr_Clear() # <<<<<<<<<<<<<< * * on = PyArray_FROM_OTF(n, NPY_LONG, NPY_ARRAY_ALIGNED) */ PyErr_Clear(); /* "mtrand.pyx":3514 * PyErr_Clear() * * on = PyArray_FROM_OTF(n, NPY_LONG, NPY_ARRAY_ALIGNED) # <<<<<<<<<<<<<< * op = 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 = 3514; __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":3515 * * on = PyArray_FROM_OTF(n, NPY_LONG, NPY_ARRAY_ALIGNED) * op = 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 = 3515; __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":3516 * on = PyArray_FROM_OTF(n, NPY_LONG, NPY_ARRAY_ALIGNED) * op = 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 = 3516; __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 = 3516; __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 = 3516; __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 = 3516; __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 = 3516; __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 = 3516; __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 = 3516; __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 = 3516; __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 = 3516; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_1) { /* "mtrand.pyx":3517 * op = 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 = 3517; __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 = 3517; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L6; } __pyx_L6:; /* "mtrand.pyx":3518 * 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 = 3518; __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 = 3518; __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 = 3518; __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 = 3518; __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 = 3518; __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 = 3518; __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 = 3518; __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 = 3518; __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 = 3518; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_1) { /* "mtrand.pyx":3519 * 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 = 3519; __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 = 3519; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L7; } __pyx_L7:; /* "mtrand.pyx":3520 * 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 = 3520; __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 = 3520; __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 = 3520; __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 = 3520; __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 = 3520; __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 = 3520; __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 = 3520; __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 = 3520; __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 = 3520; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_1) { /* "mtrand.pyx":3521 * 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 = 3521; __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 = 3521; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L8; } __pyx_L8:; /* "mtrand.pyx":3522 * 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 = 3522; __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 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 = 3524; __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 = 3524; __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":3594 * 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":3595 * * 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":3596 * 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":3597 * 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":3598 * 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 = 3598; __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 = 3598; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L4; } __pyx_L4:; /* "mtrand.pyx":3599 * 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":3600 * 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 = 3600; __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 = 3600; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L5; } /* "mtrand.pyx":3601 * 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":3602 * 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 = 3602; __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 = 3602; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L5; } __pyx_L5:; /* "mtrand.pyx":3603 * 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":3604 * 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 = 3603; __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":3606 * size, fn, fp) * * PyErr_Clear() # <<<<<<<<<<<<<< * * on = PyArray_FROM_OTF(n, NPY_DOUBLE, NPY_ARRAY_ALIGNED) */ PyErr_Clear(); /* "mtrand.pyx":3608 * PyErr_Clear() * * on = PyArray_FROM_OTF(n, NPY_DOUBLE, NPY_ARRAY_ALIGNED) # <<<<<<<<<<<<<< * op = 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 = 3608; __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":3609 * * on = PyArray_FROM_OTF(n, NPY_DOUBLE, NPY_ARRAY_ALIGNED) * op = 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 = 3609; __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":3610 * on = PyArray_FROM_OTF(n, NPY_DOUBLE, NPY_ARRAY_ALIGNED) * op = 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 = 3610; __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 = 3610; __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 = 3610; __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 = 3610; __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 = 3610; __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 = 3610; __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 = 3610; __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 = 3610; __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 = 3610; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_1) { /* "mtrand.pyx":3611 * op = 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 = 3611; __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 = 3611; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L6; } __pyx_L6:; /* "mtrand.pyx":3612 * 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 = 3612; __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 = 3612; __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 = 3612; __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 = 3612; __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 = 3612; __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 = 3612; __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 = 3612; __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 = 3612; __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 = 3612; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_1) { /* "mtrand.pyx":3613 * 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 = 3613; __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 = 3613; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L7; } __pyx_L7:; /* "mtrand.pyx":3614 * 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 = 3614; __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 = 3614; __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 = 3614; __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 = 3614; __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 = 3614; __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 = 3614; __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 = 3614; __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 = 3614; __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 = 3614; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_1) { /* "mtrand.pyx":3615 * 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 = 3615; __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 = 3615; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L8; } __pyx_L8:; /* "mtrand.pyx":3616 * 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":3617 * 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 = 3616; __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":3619 * 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 = 3619; __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 = 3619; __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":3673 * 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":3674 * 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":3675 * 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 = 3675; __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 = 3675; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; if (__pyx_t_1) { /* "mtrand.pyx":3676 * 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 = 3676; __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 = 3676; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L4; } __pyx_L4:; /* "mtrand.pyx":3677 * 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 = 3677; __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 = 3677; __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 = 3677; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_1) { /* "mtrand.pyx":3678 * 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 = 3678; __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 = 3678; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L5; } __pyx_L5:; /* "mtrand.pyx":3679 * 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 = 3679; __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":3681 * return discd_array_sc(self.internal_state, rk_poisson, size, flam) * * PyErr_Clear() # <<<<<<<<<<<<<< * * olam = PyArray_FROM_OTF(lam, NPY_DOUBLE, NPY_ARRAY_ALIGNED) */ PyErr_Clear(); /* "mtrand.pyx":3683 * PyErr_Clear() * * olam = 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 = 3683; __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":3684 * * olam = 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 = 3684; __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 = 3684; __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 = 3684; __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 = 3684; __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 = 3684; __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 = 3684; __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 = 3684; __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 = 3684; __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 = 3684; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_1) { /* "mtrand.pyx":3685 * olam = 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 = 3685; __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 = 3685; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L6; } __pyx_L6:; /* "mtrand.pyx":3686 * 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 = 3686; __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 = 3686; __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 = 3686; __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 = 3686; __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 = 3686; __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 = 3686; __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 = 3686; __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 = 3686; __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 = 3686; __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 = 3686; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_1) { /* "mtrand.pyx":3687 * 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 = 3687; __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 = 3687; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L7; } __pyx_L7:; /* "mtrand.pyx":3688 * 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 = 3688; __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":3690 * 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 = 3690; __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 = 3690; __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":3765 * 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":3766 * * 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":3767 * 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":3768 * 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 = 3768; __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 = 3768; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L4; } __pyx_L4:; /* "mtrand.pyx":3769 * 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 = 3769; __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":3771 * return discd_array_sc(self.internal_state, rk_zipf, size, fa) * * PyErr_Clear() # <<<<<<<<<<<<<< * * oa = PyArray_FROM_OTF(a, NPY_DOUBLE, NPY_ARRAY_ALIGNED) */ PyErr_Clear(); /* "mtrand.pyx":3773 * PyErr_Clear() * * oa = 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 = 3773; __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":3774 * * oa = 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 = 3774; __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 = 3774; __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 = 3774; __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 = 3774; __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 = 3774; __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 = 3774; __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 = 3774; __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 = 3774; __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 = 3774; __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 = 3774; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_1) { /* "mtrand.pyx":3775 * oa = 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 = 3775; __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 = 3775; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L5; } __pyx_L5:; /* "mtrand.pyx":3776 * 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 = 3776; __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":3778 * 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 = 3778; __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 = 3778; __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":3826 * 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":3827 * * 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":3828 * 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":3829 * 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 = 3829; __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 = 3829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L4; } __pyx_L4:; /* "mtrand.pyx":3830 * 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":3831 * 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 = 3831; __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 = 3831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L5; } __pyx_L5:; /* "mtrand.pyx":3832 * 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 = 3832; __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":3834 * return discd_array_sc(self.internal_state, rk_geometric, size, fp) * * PyErr_Clear() # <<<<<<<<<<<<<< * * */ PyErr_Clear(); /* "mtrand.pyx":3837 * * * op = 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 = 3837; __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":3838 * * op = 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 = 3838; __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 = 3838; __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 = 3838; __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 = 3838; __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 = 3838; __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 = 3838; __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 = 3838; __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 = 3838; __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 = 3838; __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 = 3838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_1) { /* "mtrand.pyx":3839 * op = 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 = 3839; __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 = 3839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L6; } __pyx_L6:; /* "mtrand.pyx":3840 * 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 = 3840; __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 = 3840; __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 = 3840; __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 = 3840; __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 = 3840; __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 = 3840; __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 = 3840; __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 = 3840; __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 = 3840; __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 = 3840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_1) { /* "mtrand.pyx":3841 * 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 = 3841; __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 = 3841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L7; } __pyx_L7:; /* "mtrand.pyx":3842 * 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 = 3842; __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":3844 * 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 = 3844; __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 = 3844; __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 = 3844; __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 = 3844; __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":3932 * 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":3933 * * 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":3934 * 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":3935 * 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":3936 * 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":3937 * 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 = 3937; __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 = 3937; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L4; } __pyx_L4:; /* "mtrand.pyx":3938 * 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":3939 * 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 = 3939; __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 = 3939; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L5; } __pyx_L5:; /* "mtrand.pyx":3940 * 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":3941 * 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 = 3941; __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 = 3941; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L6; } __pyx_L6:; /* "mtrand.pyx":3942 * 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":3943 * 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 = 3943; __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 = 3943; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L7; } __pyx_L7:; /* "mtrand.pyx":3944 * 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":3945 * 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 = 3944; __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":3947 * lngood, lnbad, lnsample) * * PyErr_Clear() # <<<<<<<<<<<<<< * * ongood = PyArray_FROM_OTF(ngood, NPY_LONG, NPY_ARRAY_ALIGNED) */ PyErr_Clear(); /* "mtrand.pyx":3949 * PyErr_Clear() * * ongood = PyArray_FROM_OTF(ngood, NPY_LONG, NPY_ARRAY_ALIGNED) # <<<<<<<<<<<<<< * onbad = PyArray_FROM_OTF(nbad, NPY_LONG, NPY_ARRAY_ALIGNED) * onsample = 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 = 3949; __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":3950 * * ongood = PyArray_FROM_OTF(ngood, NPY_LONG, NPY_ARRAY_ALIGNED) * onbad = PyArray_FROM_OTF(nbad, NPY_LONG, NPY_ARRAY_ALIGNED) # <<<<<<<<<<<<<< * onsample = 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 = 3950; __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":3951 * ongood = PyArray_FROM_OTF(ngood, NPY_LONG, NPY_ARRAY_ALIGNED) * onbad = PyArray_FROM_OTF(nbad, NPY_LONG, NPY_ARRAY_ALIGNED) * onsample = 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 = 3951; __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":3952 * onbad = PyArray_FROM_OTF(nbad, NPY_LONG, NPY_ARRAY_ALIGNED) * onsample = 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 = 3952; __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 = 3952; __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 = 3952; __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 = 3952; __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 = 3952; __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 = 3952; __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 = 3952; __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 = 3952; __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 = 3952; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (__pyx_t_1) { /* "mtrand.pyx":3953 * onsample = 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 = 3953; __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 = 3953; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L8; } __pyx_L8:; /* "mtrand.pyx":3954 * 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 = 3954; __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 = 3954; __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 = 3954; __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 = 3954; __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 = 3954; __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 = 3954; __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 = 3954; __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 = 3954; __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 = 3954; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_1) { /* "mtrand.pyx":3955 * 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 = 3955; __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 = 3955; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L9; } __pyx_L9:; /* "mtrand.pyx":3956 * 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 = 3956; __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 = 3956; __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 = 3956; __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 = 3956; __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 = 3956; __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 = 3956; __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 = 3956; __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 = 3956; __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 = 3956; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; if (__pyx_t_1) { /* "mtrand.pyx":3957 * 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 = 3957; __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 = 3957; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L10; } __pyx_L10:; /* "mtrand.pyx":3958 * 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 = 3958; __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 = 3958; __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 = 3958; __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 = 3958; __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 = 3958; __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 = 3958; __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 = 3958; __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 = 3958; __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 = 3958; __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 = 3958; __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 = 3958; __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 = 3958; __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 = 3958; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; if (__pyx_t_1) { /* "mtrand.pyx":3959 * 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 = 3959; __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 = 3959; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L11; } __pyx_L11:; /* "mtrand.pyx":3960 * 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":3961 * 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 = 3960; __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":3963 * 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 = 3963; __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 = 3963; __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":4040 * 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":4041 * * 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":4042 * 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":4043 * 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 = 4043; __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 = 4043; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L4; } __pyx_L4:; /* "mtrand.pyx":4044 * 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":4045 * 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 = 4045; __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 = 4045; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L5; } __pyx_L5:; /* "mtrand.pyx":4046 * 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 = 4046; __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":4048 * return discd_array_sc(self.internal_state, rk_logseries, size, fp) * * PyErr_Clear() # <<<<<<<<<<<<<< * * op = PyArray_FROM_OTF(p, NPY_DOUBLE, NPY_ARRAY_ALIGNED) */ PyErr_Clear(); /* "mtrand.pyx":4050 * PyErr_Clear() * * op = 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 = 4050; __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":4051 * * op = 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 = 4051; __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 = 4051; __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 = 4051; __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 = 4051; __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 = 4051; __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 = 4051; __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 = 4051; __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 = 4051; __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 = 4051; __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 = 4051; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_1) { /* "mtrand.pyx":4052 * op = 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 = 4052; __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 = 4052; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L6; } __pyx_L6:; /* "mtrand.pyx":4053 * 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 = 4053; __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 = 4053; __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 = 4053; __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 = 4053; __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 = 4053; __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 = 4053; __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 = 4053; __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 = 4053; __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 = 4053; __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 = 4053; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_1) { /* "mtrand.pyx":4054 * 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 = 4054; __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 = 4054; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L7; } __pyx_L7:; /* "mtrand.pyx":4055 * 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 = 4055; __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":4058 * * # 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 = 4058; __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 = 4058; __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 = 4058; __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":4150 * """ * # 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 = 4150; __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 = 4150; __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 = 4150; __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 = 4150; __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":4151 * # 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 = 4151; __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 = 4151; __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 = 4151; __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 = 4151; __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":4152 * 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":4153 * 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 = 4153; __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":4155 * 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":4156 * 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 = 4156; __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 = 4156; __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":4157 * 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 = 4157; __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 = 4157; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L4; } __pyx_L4:; /* "mtrand.pyx":4158 * 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 = 4158; __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 = 4158; __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 = 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_2 = __Pyx_PyObject_GetAttrStr(__pyx_v_cov, __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_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 = 4158; __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 = 4158; __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 = 4158; __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":4159 * 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 = 4159; __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 = 4159; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L5; } __pyx_L5:; /* "mtrand.pyx":4160 * 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 = 4160; __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 = 4160; __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 = 4160; __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 = 4160; __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 = 4160; __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 = 4160; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; if (__pyx_t_7) { /* "mtrand.pyx":4161 * 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 = 4161; __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 = 4161; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L6; } __pyx_L6:; /* "mtrand.pyx":4163 * 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 = 4163; __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 = 4163; __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 = 4163; __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 = 4163; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; if (__pyx_t_7) { /* "mtrand.pyx":4164 * # 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 = 4164; __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":4165 * 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 = 4165; __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 = 4165; __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 = 4165; __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":4166 * 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 = 4166; __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 = 4166; __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 = 4166; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; /* "mtrand.pyx":4170 * # 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 = 4170; __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 = 4170; __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 = 4170; __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 = 4170; __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 = 4170; __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 = 4170; __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 = 4170; __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 = 4170; __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":4171 * # 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 = 4171; __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 = 4171; __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 = 4171; __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 = 4171; __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 = 4171; __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 = 4171; __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 = 4171; __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":4172 * 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 = 4172; __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 = 4172; __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 = 4171; __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":4171 * # 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 = 4171; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(((PyObject *)__pyx_t_3)); __pyx_t_3 = 0; /* "mtrand.pyx":4180 * # 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 = 4180; __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 = 4180; __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 = 4180; __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":4182 * 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 = 4182; __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 = 4182; __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 = 4182; __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 = 4182; __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 = 4182; __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 = 4182; __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 = 4182; __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 = 4182; __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 = 4182; __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":4183 * # 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 = 4183; __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 = 4183; __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 = 4183; __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 = 4183; __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 = 4183; __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 = 4183; __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 = 4183; __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 = 4183; __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 = 4183; __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":4186 * # 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 = 4186; __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 = 4186; __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 = 4186; __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 = 4186; __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":4187 * # 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 = 4187; __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 = 4187; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; /* "mtrand.pyx":4188 * 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":4190 * 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 = 4190; __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 = 4190; __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 = 4190; __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 = 4190; __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":4249 * cdef double Sum * * d = len(pvals) # <<<<<<<<<<<<<< * parr = PyArray_ContiguousFromObject(pvals, NPY_DOUBLE, 1, 1) * pix = PyArray_DATA(parr) */ __pyx_t_1 = PyObject_Length(__pyx_v_pvals); if (unlikely(__pyx_t_1 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4249; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_v_d = __pyx_t_1; /* "mtrand.pyx":4250 * * d = len(pvals) * parr = PyArray_ContiguousFromObject(pvals, NPY_DOUBLE, 1, 1) # <<<<<<<<<<<<<< * pix = 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 = 4250; __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":4251 * d = len(pvals) * parr = PyArray_ContiguousFromObject(pvals, NPY_DOUBLE, 1, 1) * pix = PyArray_DATA(parr) # <<<<<<<<<<<<<< * * if kahan_sum(pix, d-1) > (1.0 + 1e-12): */ __pyx_v_pix = ((double *)PyArray_DATA(arrayObject_parr)); /* "mtrand.pyx":4253 * pix = 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":4254 * * if kahan_sum(pix, d-1) > (1.0 + 1e-12): * raise ValueError("sum(pvals[:-1]) > 1.0") # <<<<<<<<<<<<<< * * shape = _shape_from_size(size, d) */ __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 = 4254; __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 = 4254; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L3; } __pyx_L3:; /* "mtrand.pyx":4256 * raise ValueError("sum(pvals[:-1]) > 1.0") * * shape = _shape_from_size(size, d) # <<<<<<<<<<<<<< * * multin = np.zeros(shape, int) */ __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s___shape_from_size); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4256; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __pyx_t_2 = __Pyx_PyInt_to_py_npy_intp(__pyx_v_d); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4256; __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 = 4256; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __Pyx_INCREF(__pyx_v_size); PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_v_size); __Pyx_GIVEREF(__pyx_v_size); 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_3, ((PyObject *)__pyx_t_5), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4256; __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_v_shape = __pyx_t_2; __pyx_t_2 = 0; /* "mtrand.pyx":4258 * shape = _shape_from_size(size, d) * * multin = np.zeros(shape, int) # <<<<<<<<<<<<<< * mnarr = multin * mnix = PyArray_DATA(mnarr) */ __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4258; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s__zeros); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4258; __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 = 4258; __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_INCREF(((PyObject *)((PyObject*)(&PyInt_Type)))); PyTuple_SET_ITEM(__pyx_t_2, 1, ((PyObject *)((PyObject*)(&PyInt_Type)))); __Pyx_GIVEREF(((PyObject *)((PyObject*)(&PyInt_Type)))); __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 = 4258; __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_v_multin = __pyx_t_3; __pyx_t_3 = 0; /* "mtrand.pyx":4259 * * multin = np.zeros(shape, int) * mnarr = multin # <<<<<<<<<<<<<< * mnix = PyArray_DATA(mnarr) * i = 0 */ __Pyx_INCREF(((PyObject *)((PyArrayObject *)__pyx_v_multin))); arrayObject_mnarr = ((PyArrayObject *)__pyx_v_multin); /* "mtrand.pyx":4260 * multin = np.zeros(shape, int) * mnarr = multin * mnix = PyArray_DATA(mnarr) # <<<<<<<<<<<<<< * i = 0 * while i < PyArray_SIZE(mnarr): */ __pyx_v_mnix = ((long *)PyArray_DATA(arrayObject_mnarr)); /* "mtrand.pyx":4261 * mnarr = multin * mnix = PyArray_DATA(mnarr) * i = 0 # <<<<<<<<<<<<<< * while i < PyArray_SIZE(mnarr): * Sum = 1.0 */ __pyx_v_i = 0; /* "mtrand.pyx":4262 * mnix = 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":4263 * 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":4264 * 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":4265 * 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":4266 * 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 = 4266; __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":4267 * 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":4268 * 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":4269 * dn = dn - mnix[i+j] * if dn <= 0: * break # <<<<<<<<<<<<<< * Sum = Sum - pix[j] * if dn > 0: */ goto __pyx_L7_break; goto __pyx_L8; } __pyx_L8:; /* "mtrand.pyx":4270 * 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_L7_break:; /* "mtrand.pyx":4271 * 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":4272 * 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_L9; } __pyx_L9:; /* "mtrand.pyx":4274 * mnix[i+d-1] = dn * * i = i + d # <<<<<<<<<<<<<< * * return multin */ __pyx_v_i = (__pyx_v_i + __pyx_v_d); } /* "mtrand.pyx":4276 * 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":4278 * 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 = 4278; __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 = 4278; __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; PyObject *__pyx_t_4 = NULL; int __pyx_t_5; npy_intp __pyx_t_6; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("dirichlet", 0); /* "mtrand.pyx":4364 * cdef double acc, invacc * * k = len(alpha) # <<<<<<<<<<<<<< * alpha_arr = PyArray_ContiguousFromObject(alpha, NPY_DOUBLE, 1, 1) * alpha_data = 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 = 4364; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_v_k = __pyx_t_1; /* "mtrand.pyx":4365 * * k = len(alpha) * alpha_arr = PyArray_ContiguousFromObject(alpha, NPY_DOUBLE, 1, 1) # <<<<<<<<<<<<<< * alpha_data = 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 = 4365; __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":4366 * k = len(alpha) * alpha_arr = PyArray_ContiguousFromObject(alpha, NPY_DOUBLE, 1, 1) * alpha_data = PyArray_DATA(alpha_arr) # <<<<<<<<<<<<<< * * shape = _shape_from_size(size, k) */ __pyx_v_alpha_data = ((double *)PyArray_DATA(__pyx_v_alpha_arr)); /* "mtrand.pyx":4368 * alpha_data = PyArray_DATA(alpha_arr) * * shape = _shape_from_size(size, k) # <<<<<<<<<<<<<< * * diric = np.zeros(shape, np.float64) */ __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s___shape_from_size); 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_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_4 = PyTuple_New(2); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4368; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __Pyx_INCREF(__pyx_v_size); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_v_size); __Pyx_GIVEREF(__pyx_v_size); 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 = 4368; __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_v_shape = __pyx_t_2; __pyx_t_2 = 0; /* "mtrand.pyx":4370 * shape = _shape_from_size(size, k) * * diric = np.zeros(shape, np.float64) # <<<<<<<<<<<<<< * val_arr = diric * val_data= PyArray_DATA(val_arr) */ __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); 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); __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 = 4370; __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 = 4370; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s__float64); 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(__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 = 4370; __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); 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_4, ((PyObject *)__pyx_t_2), NULL); 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(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0; __pyx_v_diric = __pyx_t_3; __pyx_t_3 = 0; /* "mtrand.pyx":4371 * * diric = np.zeros(shape, np.float64) * val_arr = diric # <<<<<<<<<<<<<< * val_data= PyArray_DATA(val_arr) * */ __Pyx_INCREF(((PyObject *)((PyArrayObject *)__pyx_v_diric))); __pyx_v_val_arr = ((PyArrayObject *)__pyx_v_diric); /* "mtrand.pyx":4372 * diric = np.zeros(shape, np.float64) * val_arr = diric * val_data= PyArray_DATA(val_arr) # <<<<<<<<<<<<<< * * i = 0 */ __pyx_v_val_data = ((double *)PyArray_DATA(__pyx_v_val_arr)); /* "mtrand.pyx":4374 * val_data= PyArray_DATA(val_arr) * * i = 0 # <<<<<<<<<<<<<< * totsize = PyArray_SIZE(val_arr) * while i < totsize: */ __pyx_v_i = 0; /* "mtrand.pyx":4375 * * i = 0 * totsize = PyArray_SIZE(val_arr) # <<<<<<<<<<<<<< * while i < totsize: * acc = 0.0 */ __pyx_v_totsize = PyArray_SIZE(__pyx_v_val_arr); /* "mtrand.pyx":4376 * i = 0 * totsize = PyArray_SIZE(val_arr) * while i < totsize: # <<<<<<<<<<<<<< * acc = 0.0 * for j from 0 <= j < k: */ while (1) { __pyx_t_5 = (__pyx_v_i < __pyx_v_totsize); if (!__pyx_t_5) break; /* "mtrand.pyx":4377 * 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":4378 * 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":4379 * 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":4380 * 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":4381 * 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 = 4381; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_v_invacc = (1.0 / __pyx_v_acc); /* "mtrand.pyx":4382 * 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":4383 * 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":4384 * 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":4386 * 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_4); __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":4389 * * # 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; int __pyx_t_7; PyObject *__pyx_t_8 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("shuffle", 0); /* "mtrand.pyx":4424 * 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 = 4424; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_v_i = (__pyx_t_1 - 1); /* "mtrand.pyx":4427 * * # Logic adapted from random.shuffle() * 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 */ __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4427; __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 = 4427; __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 = 4427; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_4) { /* "mtrand.pyx":4428 * # Logic adapted from random.shuffle() * 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 */ __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 = 4428; __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 = 4428; __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 = 4428; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; if (!__pyx_t_5) { __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_v_x, __pyx_n_s__dtype); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4428; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s__fields); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4428; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_6 = (__pyx_t_3 != Py_None); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_7 = __pyx_t_6; } else { __pyx_t_7 = __pyx_t_5; } __pyx_t_5 = __pyx_t_7; } else { __pyx_t_5 = __pyx_t_4; } if (__pyx_t_5) { /* "mtrand.pyx":4432 * # each row. So we can't just use ordinary assignment to swap the * # rows; we need a bounce buffer. * buf = np.empty_like(x[0]) # <<<<<<<<<<<<<< * while i > 0: * j = rk_interval(i, self.internal_state) */ __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s__np); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4432; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s__empty_like); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4432; __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_GetItemInt(__pyx_v_x, 0, sizeof(long), PyInt_FromLong, 0, 0, 1); if (!__pyx_t_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4432; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __pyx_t_8 = PyTuple_New(1); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4432; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_8); PyTuple_SET_ITEM(__pyx_t_8, 0, __pyx_t_3); __Pyx_GIVEREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_3 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_t_8), NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4432; __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_8)); __pyx_t_8 = 0; __pyx_v_buf = __pyx_t_3; __pyx_t_3 = 0; /* "mtrand.pyx":4433 * # rows; we need a bounce buffer. * buf = np.empty_like(x[0]) * while i > 0: # <<<<<<<<<<<<<< * j = rk_interval(i, self.internal_state) * buf[...] = x[j] */ while (1) { __pyx_t_5 = (__pyx_v_i > 0); if (!__pyx_t_5) break; /* "mtrand.pyx":4434 * buf = np.empty_like(x[0]) * 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":4435 * while i > 0: * j = rk_interval(i, self.internal_state) * buf[...] = x[j] # <<<<<<<<<<<<<< * x[j] = x[i] * x[i] = buf */ __pyx_t_3 = __Pyx_GetItemInt(__pyx_v_x, __pyx_v_j, sizeof(npy_intp), __Pyx_PyInt_to_py_npy_intp, 0, 1, 1); if (!__pyx_t_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4435; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); if (PyObject_SetItem(__pyx_v_buf, Py_Ellipsis, __pyx_t_3) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4435; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; /* "mtrand.pyx":4436 * j = rk_interval(i, self.internal_state) * buf[...] = x[j] * x[j] = x[i] # <<<<<<<<<<<<<< * x[i] = buf * i = i - 1 */ __pyx_t_3 = __Pyx_GetItemInt(__pyx_v_x, __pyx_v_i, sizeof(npy_intp), __Pyx_PyInt_to_py_npy_intp, 0, 1, 1); if (!__pyx_t_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4436; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); if (__Pyx_SetItemInt(__pyx_v_x, __pyx_v_j, __pyx_t_3, sizeof(npy_intp), __Pyx_PyInt_to_py_npy_intp, 0, 1, 1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4436; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; /* "mtrand.pyx":4437 * 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 = 4437; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /* "mtrand.pyx":4438 * 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":4443 * # 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_5 = (__pyx_v_i > 0); if (!__pyx_t_5) break; /* "mtrand.pyx":4444 * # 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":4445 * while i > 0: * j = rk_interval(i, self.internal_state) * x[i], x[j] = x[j], x[i] # <<<<<<<<<<<<<< * i = i - 1 * */ __pyx_t_3 = __Pyx_GetItemInt(__pyx_v_x, __pyx_v_j, sizeof(npy_intp), __Pyx_PyInt_to_py_npy_intp, 0, 1, 1); if (!__pyx_t_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4445; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __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 = 4445; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_8); if (__Pyx_SetItemInt(__pyx_v_x, __pyx_v_i, __pyx_t_3, sizeof(npy_intp), __Pyx_PyInt_to_py_npy_intp, 0, 1, 1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4445; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; 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 = 4445; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; /* "mtrand.pyx":4446 * 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_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":4448 * 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":4484 * * """ * 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 = 4484; __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 = 4484; __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 = 4484; __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 = 4484; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0; if (__pyx_t_3) { /* "mtrand.pyx":4485 * """ * 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 = 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__arange); 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(1); 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(__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 = 4485; __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":4487 * 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 = 4487; __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 = 4487; __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 = 4487; __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 = 4487; __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":4488 * 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 = 4488; __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 = 4488; __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 = 4488; __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":4489 * 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 : {None, int, 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_kp_s_198, __pyx_k_198, sizeof(__pyx_k_198), 0, 0, 1, 0}, {&__pyx_kp_s_20, __pyx_k_20, sizeof(__pyx_k_20), 0, 0, 1, 0}, {&__pyx_n_s_201, __pyx_k_201, sizeof(__pyx_k_201), 0, 0, 1, 1}, {&__pyx_n_s_202, __pyx_k_202, sizeof(__pyx_k_202), 0, 0, 1, 1}, {&__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_u_287, __pyx_k_287, sizeof(__pyx_k_287), 0, 1, 0, 0}, {&__pyx_kp_u_288, __pyx_k_288, sizeof(__pyx_k_288), 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___shape_from_size, __pyx_k___shape_from_size, sizeof(__pyx_k___shape_from_size), 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__d, __pyx_k__d, sizeof(__pyx_k__d), 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__empty_like, __pyx_k__empty_like, sizeof(__pyx_k__empty_like), 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__fields, __pyx_k__fields, sizeof(__pyx_k__fields), 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__mtrand, __pyx_k__mtrand, sizeof(__pyx_k__mtrand), 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 = 531; __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 * oa) * if (multi.size != PyArray_SIZE(array)): * raise ValueError("size is not compatible with inputs") # <<<<<<<<<<<<<< * for i from 0 <= i < multi.size: * oa_data = 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 = PyArray_MultiIterNew(3, array, oa, ob) * if (multi.size != PyArray_SIZE(array)): * raise ValueError("size is not compatible with inputs") # <<<<<<<<<<<<<< * for i from 0 <= i < multi.size: * oa_data = 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 * ob, oc) * if (multi.size != PyArray_SIZE(array)): * raise ValueError("size is not compatible with inputs") # <<<<<<<<<<<<<< * for i from 0 <= i < multi.size: * oa_data = 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 = PyArray_MultiIterNew(3, array, on, op) * if (multi.size != PyArray_SIZE(array)): * raise ValueError("size is not compatible with inputs") # <<<<<<<<<<<<<< * for i from 0 <= i < multi.size: * on_data = 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 = PyArray_MultiIterNew(3, array, on, op) * if (multi.size != PyArray_SIZE(array)): * raise ValueError("size is not compatible with inputs") # <<<<<<<<<<<<<< * for i from 0 <= i < multi.size: * on_data = 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 * oN) * if (multi.size != PyArray_SIZE(array)): * raise ValueError("size is not compatible with inputs") # <<<<<<<<<<<<<< * for i from 0 <= i < multi.size: * on_data = 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 = PyArray_MultiIterNew(2, array, oa) * if (multi.size != PyArray_SIZE(array)): * raise ValueError("size is not compatible with inputs") # <<<<<<<<<<<<<< * for i from 0 <= i < multi.size: * oa_data = 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":700 * 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 = 700; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_10); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_10)); /* "mtrand.pyx":701 * 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 = 701; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_slice_11); __Pyx_GIVEREF(__pyx_k_slice_11); /* "mtrand.pyx":706 * cached_gaussian = 0.0 * else: * has_gauss, cached_gaussian = state[3:5] # <<<<<<<<<<<<<< * try: * obj = 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 = 706; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_slice_12); __Pyx_GIVEREF(__pyx_k_slice_12); /* "mtrand.pyx":713 * obj = PyArray_ContiguousFromObject(key, NPY_LONG, 1, 1) * if PyArray_DIM(obj, 0) != 624: * raise ValueError("state must be 624 longs") # <<<<<<<<<<<<<< * memcpy((self.internal_state.key), 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 = 713; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_14); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_14)); /* "mtrand.pyx":885 * * if lo >= hi : * raise ValueError("low >= high") # <<<<<<<<<<<<<< * * diff = hi - 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 = 885; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_16); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_16)); /* "mtrand.pyx":1012 * 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 = 1012; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_19); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_19)); /* "mtrand.pyx":1014 * 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 = 1014; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_21); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_21)); /* "mtrand.pyx":1016 * 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 = 1016; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_23); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_23)); /* "mtrand.pyx":1020 * 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 = 1020; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_25); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_25)); /* "mtrand.pyx":1025 * 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 = 1025; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_27); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_27)); /* "mtrand.pyx":1027 * 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 = 1027; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_29); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_29)); /* "mtrand.pyx":1029 * 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 = 1029; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_31); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_31)); /* "mtrand.pyx":1031 * 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 = 1031; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_33); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_33)); /* "mtrand.pyx":1051 * 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 = 1051; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_35); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_35)); /* "mtrand.pyx":1056 * 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 = 1056; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_37); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_37)); /* "mtrand.pyx":1081 * 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 = 1081; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_38); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_38)); /* "mtrand.pyx":1093 * # 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 = 1093; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_39); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_39)); /* "mtrand.pyx":1487 * 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 = 1487; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_45); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_45)); /* "mtrand.pyx":1495 * oscale = 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 = 1495; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_46); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_46)); /* "mtrand.pyx":1542 * 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 = 1542; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_48); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_48)); /* "mtrand.pyx":1544 * 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 = 1544; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_50); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_50)); /* "mtrand.pyx":1552 * ob = 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 = 1552; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_51); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_51)); /* "mtrand.pyx":1554 * 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 = 1554; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_52); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_52)); /* "mtrand.pyx":1601 * 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 = 1601; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_54); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_54)); /* "mtrand.pyx":1608 * oscale = 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 = 1608; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_55); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_55)); /* "mtrand.pyx":1712 * 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 = 1712; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_57); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_57)); /* "mtrand.pyx":1718 * oshape = 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 = 1718; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_58); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_58)); /* "mtrand.pyx":1798 * 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 = 1798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_60); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_60)); /* "mtrand.pyx":1800 * 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 = 1800; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_61); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_61)); /* "mtrand.pyx":1807 * oscale = 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 = 1807; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_62); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_62)); /* "mtrand.pyx":1809 * 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 = 1809; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_63); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_63)); /* "mtrand.pyx":1899 * 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 = 1899; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_64); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_64)); /* "mtrand.pyx":1901 * 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 = 1901; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_65); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_65)); /* "mtrand.pyx":1909 * odfden = 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 = 1909; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_67); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_67)); /* "mtrand.pyx":1911 * 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 = 1911; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_69); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_69)); /* "mtrand.pyx":1986 * 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 = 1986; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_71); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_71)); /* "mtrand.pyx":1988 * 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 = 1988; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_72); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_72)); /* "mtrand.pyx":1990 * 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 = 1990; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_74); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_74)); /* "mtrand.pyx":2001 * * 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 = 2001; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_75); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_75)); /* "mtrand.pyx":2003 * 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 = 2003; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_76); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_76)); /* "mtrand.pyx":2005 * 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 = 2005; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_77); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_77)); /* "mtrand.pyx":2077 * 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 = 2077; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_79); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_79)); /* "mtrand.pyx":2084 * odf = 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 = 2084; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_80); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_80)); /* "mtrand.pyx":2162 * 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 = 2162; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_81); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_81)); /* "mtrand.pyx":2164 * 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 = 2164; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_83); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_83)); /* "mtrand.pyx":2173 * ononc = 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 = 2173; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_85); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_85)); /* "mtrand.pyx":2175 * 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 = 2175; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_86); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_86)); /* "mtrand.pyx":2331 * 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 = 2331; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_87); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_87)); /* "mtrand.pyx":2338 * odf = 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 = 2338; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_88); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_88)); /* "mtrand.pyx":2424 * 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 = 2424; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_90); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_90)); /* "mtrand.pyx":2432 * okappa = 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 = 2432; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_91); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_91)); /* "mtrand.pyx":2521 * 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 = 2521; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_92); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_92)); /* "mtrand.pyx":2528 * oa = 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 = 2528; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_93); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_93)); /* "mtrand.pyx":2621 * 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 = 2621; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_94); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_94)); /* "mtrand.pyx":2628 * oa = 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 = 2628; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_95); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_95)); /* "mtrand.pyx":2730 * 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 = 2730; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_96); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_96)); /* "mtrand.pyx":2737 * oa = 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 = 2737; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_97); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_97)); /* "mtrand.pyx":2820 * 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 = 2820; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_100); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_100)); /* "mtrand.pyx":2827 * 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 = 2827; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_101); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_101)); /* "mtrand.pyx":2951 * 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 = 2951; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_104); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_104)); /* "mtrand.pyx":2958 * 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 = 2958; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_105); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_105)); /* "mtrand.pyx":3039 * 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 = 3039; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_108); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_108)); /* "mtrand.pyx":3046 * 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 = 3046; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_109); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_109)); /* "mtrand.pyx":3159 * 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 = 3159; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_113); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_113)); /* "mtrand.pyx":3167 * 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 = 3167; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_115); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_115)); /* "mtrand.pyx":3232 * 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 = 3232; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_117); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_117)); /* "mtrand.pyx":3239 * oscale = 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 = 3239; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_119); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_119)); /* "mtrand.pyx":3312 * 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 = 3312; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_121); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_121)); /* "mtrand.pyx":3314 * 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 = 3314; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_122); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_122)); /* "mtrand.pyx":3321 * 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 = 3321; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_124); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_124)); /* "mtrand.pyx":3323 * 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 = 3323; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_125); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_125)); /* "mtrand.pyx":3393 * 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 = 3393; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_127); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_127)); /* "mtrand.pyx":3395 * 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 = 3395; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_129); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_129)); /* "mtrand.pyx":3397 * 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 = 3397; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_131); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_131)); /* "mtrand.pyx":3407 * * 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 = 3407; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_132); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_132)); /* "mtrand.pyx":3409 * 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 = 3409; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_133); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_133)); /* "mtrand.pyx":3411 * 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 = 3411; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_134); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_134)); /* "mtrand.pyx":3505 * 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 = 3505; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_136); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_136)); /* "mtrand.pyx":3507 * 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 = 3507; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_138); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_138)); /* "mtrand.pyx":3509 * 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 = 3509; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_140); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_140)); /* "mtrand.pyx":3517 * op = 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 = 3517; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_141); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_141)); /* "mtrand.pyx":3519 * 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 = 3519; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_142); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_142)); /* "mtrand.pyx":3521 * 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 = 3521; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_143); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_143)); /* "mtrand.pyx":3598 * 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 = 3598; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_145); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_145)); /* "mtrand.pyx":3600 * 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 = 3600; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_146); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_146)); /* "mtrand.pyx":3602 * 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 = 3602; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_147); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_147)); /* "mtrand.pyx":3611 * op = 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 = 3611; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_148); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_148)); /* "mtrand.pyx":3613 * 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 = 3613; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_149); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_149)); /* "mtrand.pyx":3615 * 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 = 3615; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_150); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_150)); /* "mtrand.pyx":3676 * 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 = 3676; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_153); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_153)); /* "mtrand.pyx":3678 * 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 = 3678; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_155); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_155)); /* "mtrand.pyx":3685 * olam = 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 = 3685; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_156); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_156)); /* "mtrand.pyx":3687 * 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 = 3687; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_158); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_158)); /* "mtrand.pyx":3768 * 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 = 3768; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_160); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_160)); /* "mtrand.pyx":3775 * oa = 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 = 3775; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_161); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_161)); /* "mtrand.pyx":3829 * 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 = 3829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_163); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_163)); /* "mtrand.pyx":3831 * 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 = 3831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_165); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_165)); /* "mtrand.pyx":3839 * op = 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 = 3839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_166); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_166)); /* "mtrand.pyx":3841 * 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 = 3841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_167); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_167)); /* "mtrand.pyx":3937 * 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 = 3937; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_169); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_169)); /* "mtrand.pyx":3939 * 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 = 3939; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_171); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_171)); /* "mtrand.pyx":3941 * 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 = 3941; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_173); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_173)); /* "mtrand.pyx":3943 * 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 = 3943; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_175); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_175)); /* "mtrand.pyx":3953 * onsample = 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 = 3953; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_176); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_176)); /* "mtrand.pyx":3955 * 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 = 3955; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_177); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_177)); /* "mtrand.pyx":3957 * 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 = 3957; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_178); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_178)); /* "mtrand.pyx":3959 * 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 = 3959; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_179); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_179)); /* "mtrand.pyx":4043 * 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 = 4043; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_181); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_181)); /* "mtrand.pyx":4045 * 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 = 4045; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_183); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_183)); /* "mtrand.pyx":4052 * op = 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 = 4052; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_184); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_184)); /* "mtrand.pyx":4054 * 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 = 4054; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_185); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_185)); /* "mtrand.pyx":4157 * 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 = 4157; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_187); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_187)); /* "mtrand.pyx":4159 * 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 = 4159; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_189); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_189)); /* "mtrand.pyx":4161 * 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 = 4161; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_191); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_191)); /* "mtrand.pyx":4165 * 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 = 4165; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_slice_192); __Pyx_GIVEREF(__pyx_k_slice_192); /* "mtrand.pyx":4254 * * if kahan_sum(pix, d-1) > (1.0 + 1e-12): * raise ValueError("sum(pvals[:-1]) > 1.0") # <<<<<<<<<<<<<< * * shape = _shape_from_size(size, d) */ __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 = 4254; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_195); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_195)); /* "mtrand.pyx":525 * return sum * * def _shape_from_size(size, d): # <<<<<<<<<<<<<< * if size is None: * shape = (d,) */ __pyx_k_tuple_196 = PyTuple_Pack(3, ((PyObject *)__pyx_n_s__size), ((PyObject *)__pyx_n_s__d), ((PyObject *)__pyx_n_s__shape)); if (unlikely(!__pyx_k_tuple_196)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 525; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_196); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_196)); __pyx_k_codeobj_197 = (PyObject*)__Pyx_PyCode_New(2, 0, 3, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_k_tuple_196, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_198, __pyx_n_s___shape_from_size, 525, __pyx_empty_bytes); if (unlikely(!__pyx_k_codeobj_197)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 525; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /* "mtrand.pyx":569 * """ * 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_199 = PyTuple_Pack(1, ((PyObject *)__pyx_n_s__l)); if (unlikely(!__pyx_k_tuple_199)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 569; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_199); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_199)); __pyx_k_tuple_200 = PyTuple_Pack(1, ((PyObject *)__pyx_n_s__l)); if (unlikely(!__pyx_k_tuple_200)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 569; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_k_tuple_200); __Pyx_GIVEREF(((PyObject *)__pyx_k_tuple_200)); __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 = 535; __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 = 535; __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":525 * return sum * * def _shape_from_size(size, d): # <<<<<<<<<<<<<< * if size is None: * shape = (d,) */ __pyx_t_1 = PyCFunction_NewEx(&__pyx_mdef_6mtrand_1_shape_from_size, NULL, __pyx_n_s__mtrand); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 525; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); if (PyDict_SetItem(__pyx_d, __pyx_n_s___shape_from_size, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 525; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "mtrand.pyx":569 * """ * 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 = 569; __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 = 569; __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_199), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 569; __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 = 569; __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 = 569; __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 = 569; __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 = 569; __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 = 569; __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_200), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 569; __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 = 569; __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 = 569; __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 = 569; __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 = 569; __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 = 569; __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 = 569; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; PyType_Modified(__pyx_ptype_6mtrand_RandomState); /* "mtrand.pyx":928 * * * 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 = 928; __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":1100 * * * 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 = 1100; __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 = 1100; __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":1398 * 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 = 1398; __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 = 1398; __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":1557 * 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 = 1557; __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":1721 * 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 = 1721; __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":2740 * 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 = 2740; __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 = 2740; __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":2830 * 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 = 2830; __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 = 2830; __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":2961 * 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 = 2961; __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 = 2961; __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":3049 * 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 = 3049; __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 = 3049; __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":3170 * 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 = 3170; __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":3619 * 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 = 3619; __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":4491 * 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 = 4491; __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 = 4491; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; /* "mtrand.pyx":4492 * * _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 = 4492; __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 = 4492; __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 = 4492; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "mtrand.pyx":4493 * _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 = 4493; __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 = 4493; __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 = 4493; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; /* "mtrand.pyx":4494 * 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 = 4494; __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 = 4494; __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 = 4494; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "mtrand.pyx":4495 * 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 = 4495; __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 = 4495; __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 = 4495; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; /* "mtrand.pyx":4496 * 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 = 4496; __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 = 4496; __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 = 4496; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "mtrand.pyx":4497 * 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 = 4497; __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 = 4497; __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 = 4497; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; /* "mtrand.pyx":4498 * 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 = 4498; __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 = 4498; __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 = 4498; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "mtrand.pyx":4499 * 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 = 4499; __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 = 4499; __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 = 4499; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; /* "mtrand.pyx":4500 * 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 = 4500; __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 = 4500; __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 = 4500; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "mtrand.pyx":4501 * 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 = 4501; __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 = 4501; __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 = 4501; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; /* "mtrand.pyx":4502 * 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 = 4502; __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 = 4502; __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 = 4502; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "mtrand.pyx":4503 * 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 = 4503; __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 = 4503; __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 = 4503; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; /* "mtrand.pyx":4504 * 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 = 4504; __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 = 4504; __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 = 4504; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "mtrand.pyx":4505 * 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 = 4505; __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 = 4505; __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 = 4505; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; /* "mtrand.pyx":4506 * 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 = 4506; __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 = 4506; __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 = 4506; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "mtrand.pyx":4507 * 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 = 4507; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_201); 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_DECREF(__pyx_t_1); __pyx_t_1 = 0; if (PyDict_SetItem(__pyx_d, __pyx_n_s_201, __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4507; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; /* "mtrand.pyx":4508 * 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 = 4508; __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 = 4508; __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 = 4508; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "mtrand.pyx":4509 * 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 = 4509; __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 = 4509; __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 = 4509; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; /* "mtrand.pyx":4510 * 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 = 4510; __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 = 4510; __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 = 4510; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "mtrand.pyx":4511 * 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 = 4511; __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 = 4511; __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 = 4511; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; /* "mtrand.pyx":4512 * 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 = 4512; __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 = 4512; __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 = 4512; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "mtrand.pyx":4513 * 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 = 4513; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_202); 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_DECREF(__pyx_t_1); __pyx_t_1 = 0; if (PyDict_SetItem(__pyx_d, __pyx_n_s_202, __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4513; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; /* "mtrand.pyx":4514 * 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 = 4514; __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 = 4514; __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 = 4514; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "mtrand.pyx":4515 * 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 = 4515; __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 = 4515; __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 = 4515; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; /* "mtrand.pyx":4516 * 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 = 4516; __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 = 4516; __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 = 4516; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "mtrand.pyx":4517 * 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 = 4517; __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 = 4517; __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 = 4517; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; /* "mtrand.pyx":4518 * 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 = 4518; __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 = 4518; __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 = 4518; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "mtrand.pyx":4519 * 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 = 4519; __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 = 4519; __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 = 4519; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; /* "mtrand.pyx":4520 * 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 = 4520; __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 = 4520; __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 = 4520; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "mtrand.pyx":4521 * 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 = 4521; __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 = 4521; __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 = 4521; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; /* "mtrand.pyx":4522 * 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 = 4522; __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 = 4522; __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 = 4522; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "mtrand.pyx":4523 * 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 = 4523; __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 = 4523; __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 = 4523; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; /* "mtrand.pyx":4524 * 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 = 4524; __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 = 4524; __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 = 4524; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "mtrand.pyx":4525 * 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 = 4525; __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 = 4525; __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 = 4525; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; /* "mtrand.pyx":4526 * 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 = 4526; __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 = 4526; __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 = 4526; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "mtrand.pyx":4528 * 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 = 4528; __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 = 4528; __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 = 4528; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; /* "mtrand.pyx":4529 * * 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 = 4529; __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 = 4529; __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 = 4529; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "mtrand.pyx":4530 * 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 = 4530; __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 = 4530; __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 = 4530; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; /* "mtrand.pyx":4531 * 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 = 4531; __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 = 4531; __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 = 4531; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "mtrand.pyx":4532 * 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 = 4532; __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 = 4532; __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 = 4532; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; /* "mtrand.pyx":4533 * 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 = 4533; __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 = 4533; __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 = 4533; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "mtrand.pyx":4534 * 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 = 4534; __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 = 4534; __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 = 4534; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; /* "mtrand.pyx":4536 * 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 = 4536; __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 = 4536; __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 = 4536; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "mtrand.pyx":4537 * * 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 = 4537; __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 = 4537; __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 = 4537; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; /* "mtrand.pyx":4538 * 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 = 4538; __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 = 4538; __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 = 4538; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "mtrand.pyx":4540 * 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 = 4540; __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 = 4540; __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 = 4540; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; /* "mtrand.pyx":4541 * * 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 = 4541; __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 = 4541; __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 = 4541; __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_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_t_1, ((PyObject *)__pyx_kp_u_287), ((PyObject *)__pyx_kp_u_288)) < 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_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 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 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 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 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 */ numpy-1.8.2/numpy/random/mtrand/numpy.pxd0000664000175100017510000001017312370216243021630 0ustar vagrantvagrant00000000000000# :Author: Travis Oliphant cdef extern from "numpy/npy_no_deprecated_api.h": pass cdef extern from "numpy/arrayobject.h": cdef enum NPY_TYPES: NPY_BOOL NPY_BYTE NPY_UBYTE NPY_SHORT NPY_USHORT NPY_INT NPY_UINT NPY_LONG NPY_ULONG NPY_LONGLONG NPY_ULONGLONG NPY_FLOAT NPY_DOUBLE NPY_LONGDOUBLE NPY_CFLOAT NPY_CDOUBLE NPY_CLONGDOUBLE NPY_OBJECT NPY_STRING NPY_UNICODE NPY_VOID NPY_NTYPES NPY_NOTYPE cdef enum requirements: NPY_ARRAY_C_CONTIGUOUS NPY_ARRAY_F_CONTIGUOUS NPY_ARRAY_OWNDATA NPY_ARRAY_FORCECAST NPY_ARRAY_ENSURECOPY NPY_ARRAY_ENSUREARRAY NPY_ARRAY_ELEMENTSTRIDES NPY_ARRAY_ALIGNED NPY_ARRAY_NOTSWAPPED NPY_ARRAY_WRITEABLE NPY_ARRAY_UPDATEIFCOPY NPY_ARR_HAS_DESCR NPY_ARRAY_BEHAVED NPY_ARRAY_BEHAVED_NS NPY_ARRAY_CARRAY NPY_ARRAY_CARRAY_RO NPY_ARRAY_FARRAY NPY_ARRAY_FARRAY_RO NPY_ARRAY_DEFAULT NPY_ARRAY_IN_ARRAY NPY_ARRAY_OUT_ARRAY NPY_ARRAY_INOUT_ARRAY NPY_ARRAY_IN_FARRAY NPY_ARRAY_OUT_FARRAY NPY_ARRAY_INOUT_FARRAY NPY_ARRAY_UPDATE_ALL cdef enum defines: NPY_MAXDIMS ctypedef struct npy_cdouble: double real double imag ctypedef struct npy_cfloat: double real double imag ctypedef int npy_intp ctypedef extern class numpy.dtype [object PyArray_Descr]: pass ctypedef extern class numpy.ndarray [object PyArrayObject]: pass ctypedef extern class numpy.flatiter [object PyArrayIterObject]: cdef int nd_m1 cdef npy_intp index, size cdef ndarray ao cdef char *dataptr ctypedef extern class numpy.broadcast [object PyArrayMultiIterObject]: cdef int numiter cdef npy_intp size, index cdef int nd cdef npy_intp *dimensions cdef void **iters object PyArray_ZEROS(int ndims, npy_intp* dims, NPY_TYPES type_num, int fortran) object PyArray_EMPTY(int ndims, npy_intp* dims, NPY_TYPES type_num, int fortran) dtype PyArray_DescrFromTypeNum(NPY_TYPES type_num) object PyArray_SimpleNew(int ndims, npy_intp* dims, NPY_TYPES type_num) int PyArray_Check(object obj) object PyArray_ContiguousFromAny(object obj, NPY_TYPES type, int mindim, int maxdim) object PyArray_ContiguousFromObject(object obj, NPY_TYPES type, int mindim, int maxdim) npy_intp PyArray_SIZE(ndarray arr) npy_intp PyArray_NBYTES(ndarray arr) object PyArray_FromAny(object obj, dtype newtype, int mindim, int maxdim, int requirements, object context) object PyArray_FROMANY(object obj, NPY_TYPES type_num, int min, int max, int requirements) object PyArray_NewFromDescr(object subtype, dtype newtype, int nd, npy_intp* dims, npy_intp* strides, void* data, int flags, object parent) object PyArray_FROM_OTF(object obj, NPY_TYPES type, int flags) object PyArray_EnsureArray(object) 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) object PyArray_IterNew(object arr) void PyArray_ITER_NEXT(flatiter it) void import_array() # include functions that were once macros in the new api int PyArray_NDIM(ndarray arr) char * PyArray_DATA(ndarray arr) npy_intp * PyArray_DIMS(ndarray arr) npy_intp * PyArray_STRIDES(ndarray arr) npy_intp PyArray_DIM(ndarray arr, int idim) npy_intp PyArray_STRIDE(ndarray arr, int istride) object PyArray_BASE(ndarray arr) dtype PyArray_DESCR(ndarray arr) int PyArray_FLAGS(ndarray arr) npy_intp PyArray_ITEMSIZE(ndarray arr) int PyArray_TYPE(ndarray arr) int PyArray_CHKFLAGS(ndarray arr, int flags) object PyArray_GETITEM(ndarray arr, char *itemptr) numpy-1.8.2/numpy/random/mtrand/initarray.h0000664000175100017510000000026312370216243022115 0ustar vagrantvagrant00000000000000#include "Python.h" #include "numpy/arrayobject.h" #include "randomkit.h" extern void init_by_array(rk_state *self, unsigned long init_key[], npy_intp key_length); numpy-1.8.2/numpy/random/mtrand/randomkit.h0000664000175100017510000001240412370216242022102 0ustar vagrantvagrant00000000000000/* Random kit 1.3 */ /* * Copyright (c) 2003-2005, Jean-Sebastien Roy (js@jeannot.org) * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /* @(#) $Jeannot: randomkit.h,v 1.24 2005/07/21 22:14:09 js Exp $ */ /* * Typical use: * * { * rk_state state; * unsigned long seed = 1, random_value; * * rk_seed(seed, &state); // Initialize the RNG * ... * random_value = rk_random(&state); // Generate random values in [0..RK_MAX] * } * * Instead of rk_seed, you can use rk_randomseed which will get a random seed * from /dev/urandom (or the clock, if /dev/urandom is unavailable): * * { * rk_state state; * unsigned long random_value; * * rk_randomseed(&state); // Initialize the RNG with a random seed * ... * random_value = rk_random(&state); // Generate random values in [0..RK_MAX] * } */ /* * Useful macro: * RK_DEV_RANDOM: the device used for random seeding. * defaults to "/dev/urandom" */ #include #ifndef _RANDOMKIT_ #define _RANDOMKIT_ #define RK_STATE_LEN 624 typedef struct rk_state_ { unsigned long key[RK_STATE_LEN]; int pos; int has_gauss; /* !=0: gauss contains a gaussian deviate */ double gauss; /* The rk_state structure has been extended to store the following * information for the binomial generator. If the input values of n or p * are different than nsave and psave, then the other parameters will be * recomputed. RTK 2005-09-02 */ int has_binomial; /* !=0: following parameters initialized for binomial */ double psave; long nsave; double r; double q; double fm; long m; double p1; double xm; double xl; double xr; double c; double laml; double lamr; double p2; double p3; double p4; } rk_state; typedef enum { RK_NOERR = 0, /* no error */ RK_ENODEV = 1, /* no RK_DEV_RANDOM device */ RK_ERR_MAX = 2 } rk_error; /* error strings */ extern char *rk_strerror[RK_ERR_MAX]; /* Maximum generated random value */ #define RK_MAX 0xFFFFFFFFUL #ifdef __cplusplus extern "C" { #endif /* * Initialize the RNG state using the given seed. */ extern void rk_seed(unsigned long seed, rk_state *state); /* * Initialize the RNG state using a random seed. * Uses /dev/random or, when unavailable, the clock (see randomkit.c). * Returns RK_NOERR when no errors occurs. * Returns RK_ENODEV when the use of RK_DEV_RANDOM failed (for example because * there is no such device). In this case, the RNG was initialized using the * clock. */ extern rk_error rk_randomseed(rk_state *state); /* * Returns a random unsigned long between 0 and RK_MAX inclusive */ extern unsigned long rk_random(rk_state *state); /* * Returns a random long between 0 and LONG_MAX inclusive */ extern long rk_long(rk_state *state); /* * Returns a random unsigned long between 0 and ULONG_MAX inclusive */ extern unsigned long rk_ulong(rk_state *state); /* * Returns a random unsigned long between 0 and max inclusive. */ extern unsigned long rk_interval(unsigned long max, rk_state *state); /* * Returns a random double between 0.0 and 1.0, 1.0 excluded. */ extern double rk_double(rk_state *state); /* * fill the buffer with size random bytes */ extern void rk_fill(void *buffer, size_t size, rk_state *state); /* * fill the buffer with randombytes from the random device * Returns RK_ENODEV if the device is unavailable, or RK_NOERR if it is * On Unix, if strong is defined, RK_DEV_RANDOM is used. If not, RK_DEV_URANDOM * is used instead. This parameter has no effect on Windows. * Warning: on most unixes RK_DEV_RANDOM will wait for enough entropy to answer * which can take a very long time on quiet systems. */ extern rk_error rk_devfill(void *buffer, size_t size, int strong); /* * fill the buffer using rk_devfill if the random device is available and using * rk_fill if is is not * parameters have the same meaning as rk_fill and rk_devfill * Returns RK_ENODEV if the device is unavailable, or RK_NOERR if it is */ extern rk_error rk_altfill(void *buffer, size_t size, int strong, rk_state *state); /* * return a random gaussian deviate with variance unity and zero mean. */ extern double rk_gauss(rk_state *state); #ifdef __cplusplus } #endif #endif /* _RANDOMKIT_ */ numpy-1.8.2/numpy/random/mtrand/generate_mtrand_c.py0000664000175100017510000000314012370216242023751 0ustar vagrantvagrant00000000000000#!/usr/bin/env python from __future__ import division, absolute_import, print_function import sys import re import os unused_internal_funcs = ['__Pyx_PrintItem', '__Pyx_PrintNewline', '__Pyx_ReRaise', #'__Pyx_GetExcValue', '__Pyx_ArgTypeTest', '__Pyx_SetVtable', '__Pyx_GetVtable', '__Pyx_CreateClass'] if __name__ == '__main__': # Use cython here so that long docstrings are broken up. # This is needed for some VC++ compilers. os.system('cython mtrand.pyx') mtrand_c = open('mtrand.c', 'r') processed = open('mtrand_pp.c', 'w') unused_funcs_str = '(' + '|'.join(unused_internal_funcs) + ')' uifpat = re.compile(r'static \w+ \*?'+unused_funcs_str+r'.*/\*proto\*/') linepat = re.compile(r'/\* ".*/mtrand.pyx":') for linenum, line in enumerate(mtrand_c): m = re.match(r'^(\s+arrayObject\w*\s*=\s*[(])[(]PyObject\s*[*][)]', line) if m: line = '%s(PyArrayObject *)%s' % (m.group(1), line[m.end():]) m = uifpat.match(line) if m: line = '' m = re.search(unused_funcs_str, line) if m: print("%s was declared unused, but is used at line %d" % (m.group(), linenum+1), file=sys.stderr) line = linepat.sub(r'/* "mtrand.pyx":', line) processed.write(line) mtrand_c.close() processed.close() os.rename('mtrand_pp.c', 'mtrand.c') numpy-1.8.2/numpy/random/mtrand/distributions.h0000664000175100017510000001612512370216242023020 0ustar vagrantvagrant00000000000000/* Copyright 2005 Robert Kern (robert.kern@gmail.com) * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef _RK_DISTR_ #define _RK_DISTR_ #include "randomkit.h" #ifdef __cplusplus extern "C" { #endif /* References: * * Devroye, Luc. _Non-Uniform Random Variate Generation_. * Springer-Verlag, New York, 1986. * http://cgm.cs.mcgill.ca/~luc/rnbookindex.html * * Kachitvichyanukul, V. and Schmeiser, B. W. Binomial Random Variate * Generation. Communications of the ACM, 31, 2 (February, 1988) 216. * * Hoermann, W. The Transformed Rejection Method for Generating Poisson Random * Variables. Insurance: Mathematics and Economics, (to appear) * http://citeseer.csail.mit.edu/151115.html * * Marsaglia, G. and Tsang, W. W. A Simple Method for Generating Gamma * Variables. ACM Transactions on Mathematical Software, Vol. 26, No. 3, * September 2000, Pages 363–372. */ /* Normal distribution with mean=loc and standard deviation=scale. */ extern double rk_normal(rk_state *state, double loc, double scale); /* Standard exponential distribution (mean=1) computed by inversion of the * CDF. */ extern double rk_standard_exponential(rk_state *state); /* Exponential distribution with mean=scale. */ extern double rk_exponential(rk_state *state, double scale); /* Uniform distribution on interval [loc, loc+scale). */ extern double rk_uniform(rk_state *state, double loc, double scale); /* Standard gamma distribution with shape parameter. * When shape < 1, the algorithm given by (Devroye p. 304) is used. * When shape == 1, a Exponential variate is generated. * When shape > 1, the small and fast method of (Marsaglia and Tsang 2000) * is used. */ extern double rk_standard_gamma(rk_state *state, double shape); /* Gamma distribution with shape and scale. */ extern double rk_gamma(rk_state *state, double shape, double scale); /* Beta distribution computed by combining two gamma variates (Devroye p. 432). */ extern double rk_beta(rk_state *state, double a, double b); /* Chi^2 distribution computed by transforming a gamma variate (it being a * special case Gamma(df/2, 2)). */ extern double rk_chisquare(rk_state *state, double df); /* Noncentral Chi^2 distribution computed by modifying a Chi^2 variate. */ extern double rk_noncentral_chisquare(rk_state *state, double df, double nonc); /* F distribution computed by taking the ratio of two Chi^2 variates. */ extern double rk_f(rk_state *state, double dfnum, double dfden); /* Noncentral F distribution computed by taking the ratio of a noncentral Chi^2 * and a Chi^2 variate. */ extern double rk_noncentral_f(rk_state *state, double dfnum, double dfden, double nonc); /* Binomial distribution with n Bernoulli trials with success probability p. * When n*p <= 30, the "Second waiting time method" given by (Devroye p. 525) is * used. Otherwise, the BTPE algorithm of (Kachitvichyanukul and Schmeiser 1988) * is used. */ extern long rk_binomial(rk_state *state, long n, double p); /* Binomial distribution using BTPE. */ extern long rk_binomial_btpe(rk_state *state, long n, double p); /* Binomial distribution using inversion and chop-down */ extern long rk_binomial_inversion(rk_state *state, long n, double p); /* Negative binomial distribution computed by generating a Gamma(n, (1-p)/p) * variate Y and returning a Poisson(Y) variate (Devroye p. 543). */ extern long rk_negative_binomial(rk_state *state, double n, double p); /* Poisson distribution with mean=lam. * When lam < 10, a basic algorithm using repeated multiplications of uniform * variates is used (Devroye p. 504). * When lam >= 10, algorithm PTRS from (Hoermann 1992) is used. */ extern long rk_poisson(rk_state *state, double lam); /* Poisson distribution computed by repeated multiplication of uniform variates. */ extern long rk_poisson_mult(rk_state *state, double lam); /* Poisson distribution computer by the PTRS algorithm. */ extern long rk_poisson_ptrs(rk_state *state, double lam); /* Standard Cauchy distribution computed by dividing standard gaussians * (Devroye p. 451). */ extern double rk_standard_cauchy(rk_state *state); /* Standard t-distribution with df degrees of freedom (Devroye p. 445 as * corrected in the Errata). */ extern double rk_standard_t(rk_state *state, double df); /* von Mises circular distribution with center mu and shape kappa on [-pi,pi] * (Devroye p. 476 as corrected in the Errata). */ extern double rk_vonmises(rk_state *state, double mu, double kappa); /* Pareto distribution via inversion (Devroye p. 262) */ extern double rk_pareto(rk_state *state, double a); /* Weibull distribution via inversion (Devroye p. 262) */ extern double rk_weibull(rk_state *state, double a); /* Power distribution via inversion (Devroye p. 262) */ extern double rk_power(rk_state *state, double a); /* Laplace distribution */ extern double rk_laplace(rk_state *state, double loc, double scale); /* Gumbel distribution */ extern double rk_gumbel(rk_state *state, double loc, double scale); /* Logistic distribution */ extern double rk_logistic(rk_state *state, double loc, double scale); /* Log-normal distribution */ extern double rk_lognormal(rk_state *state, double mean, double sigma); /* Rayleigh distribution */ extern double rk_rayleigh(rk_state *state, double mode); /* Wald distribution */ extern double rk_wald(rk_state *state, double mean, double scale); /* Zipf distribution */ extern long rk_zipf(rk_state *state, double a); /* Geometric distribution */ extern long rk_geometric(rk_state *state, double p); extern long rk_geometric_search(rk_state *state, double p); extern long rk_geometric_inversion(rk_state *state, double p); /* Hypergeometric distribution */ extern long rk_hypergeometric(rk_state *state, long good, long bad, long sample); extern long rk_hypergeometric_hyp(rk_state *state, long good, long bad, long sample); extern long rk_hypergeometric_hrua(rk_state *state, long good, long bad, long sample); /* Triangular distribution */ extern double rk_triangular(rk_state *state, double left, double mode, double right); /* Logarithmic series distribution */ extern long rk_logseries(rk_state *state, double p); #ifdef __cplusplus } #endif #endif /* _RK_DISTR_ */ numpy-1.8.2/numpy/random/mtrand/mtrand_py_helper.h0000664000175100017510000000072412370216242023450 0ustar vagrantvagrant00000000000000#ifndef _MTRAND_PY_HELPER_H_ #define _MTRAND_PY_HELPER_H_ #include static PyObject *empty_py_bytes(npy_intp length, void **bytes) { PyObject *b; #if PY_MAJOR_VERSION >= 3 b = PyBytes_FromStringAndSize(NULL, length); if (b) { *bytes = PyBytes_AS_STRING(b); } #else b = PyString_FromStringAndSize(NULL, length); if (b) { *bytes = PyString_AS_STRING(b); } #endif return b; } #endif /* _MTRAND_PY_HELPER_H_ */ numpy-1.8.2/numpy/random/info.py0000664000175100017510000001202112370216243017755 0ustar vagrantvagrant00000000000000""" ======================== Random Number Generation ======================== ==================== ========================================================= Utility functions ============================================================================== random Uniformly distributed values of a given shape. bytes Uniformly distributed random bytes. random_integers Uniformly distributed integers in a given range. random_sample Uniformly distributed floats in a given range. permutation Randomly permute a sequence / generate a random sequence. shuffle Randomly permute a sequence in place. seed Seed the random number generator. ==================== ========================================================= ==================== ========================================================= Compatibility functions ============================================================================== rand Uniformly distributed values. randn Normally distributed values. ranf Uniformly distributed floating point numbers. randint Uniformly distributed integers in a given range. ==================== ========================================================= ==================== ========================================================= Univariate distributions ============================================================================== beta Beta distribution over ``[0, 1]``. binomial Binomial distribution. chisquare :math:`\\chi^2` distribution. exponential Exponential distribution. f F (Fisher-Snedecor) distribution. gamma Gamma distribution. geometric Geometric distribution. gumbel Gumbel distribution. hypergeometric Hypergeometric distribution. laplace Laplace distribution. logistic Logistic distribution. lognormal Log-normal distribution. logseries Logarithmic series distribution. negative_binomial Negative binomial distribution. noncentral_chisquare Non-central chi-square distribution. noncentral_f Non-central F distribution. normal Normal / Gaussian distribution. pareto Pareto distribution. poisson Poisson distribution. power Power distribution. rayleigh Rayleigh distribution. triangular Triangular distribution. uniform Uniform distribution. vonmises Von Mises circular distribution. wald Wald (inverse Gaussian) distribution. weibull Weibull distribution. zipf Zipf's distribution over ranked data. ==================== ========================================================= ==================== ========================================================= Multivariate distributions ============================================================================== dirichlet Multivariate generalization of Beta distribution. multinomial Multivariate generalization of the binomial distribution. multivariate_normal Multivariate generalization of the normal distribution. ==================== ========================================================= ==================== ========================================================= Standard distributions ============================================================================== standard_cauchy Standard Cauchy-Lorentz distribution. standard_exponential Standard exponential distribution. standard_gamma Standard Gamma distribution. standard_normal Standard normal distribution. standard_t Standard Student's t-distribution. ==================== ========================================================= ==================== ========================================================= Internal functions ============================================================================== get_state Get tuple representing internal state of generator. set_state Set state of generator. ==================== ========================================================= """ from __future__ import division, absolute_import, print_function depends = ['core'] __all__ = [ 'beta', 'binomial', 'bytes', 'chisquare', 'exponential', 'f', 'gamma', 'geometric', 'get_state', 'gumbel', 'hypergeometric', 'laplace', 'logistic', 'lognormal', 'logseries', 'multinomial', 'multivariate_normal', 'negative_binomial', 'noncentral_chisquare', 'noncentral_f', 'normal', 'pareto', 'permutation', 'poisson', 'power', 'rand', 'randint', 'randn', 'random_integers', 'random_sample', 'rayleigh', 'seed', 'set_state', 'shuffle', 'standard_cauchy', 'standard_exponential', 'standard_gamma', 'standard_normal', 'standard_t', 'triangular', 'uniform', 'vonmises', 'wald', 'weibull', 'zipf' ] numpy-1.8.2/numpy/random/setup.py0000664000175100017510000000464512370216242020176 0ustar vagrantvagrant00000000000000from __future__ import division, print_function from os.path import join, split, dirname import os import sys from distutils.dep_util import newer from distutils.msvccompiler import get_build_version as get_msvc_build_version def needs_mingw_ftime_workaround(): # We need the mingw workaround for _ftime if the msvc runtime version is # 7.1 or above and we build with mingw ... # ... but we can't easily detect compiler version outside distutils command # context, so we will need to detect in randomkit whether we build with gcc msver = get_msvc_build_version() if msver and msver >= 8: return True return False def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration, get_mathlibs config = Configuration('random', parent_package, top_path) def generate_libraries(ext, build_dir): config_cmd = config.get_config_cmd() libs = get_mathlibs() tc = testcode_wincrypt() if config_cmd.try_run(tc): libs.append('Advapi32') ext.libraries.extend(libs) return None # enable unix large file support on 32 bit systems # (64 bit off_t, lseek -> lseek64 etc.) defs = [('_FILE_OFFSET_BITS', '64'), ('_LARGEFILE_SOURCE', '1'), ('_LARGEFILE64_SOURCE', '1')] if needs_mingw_ftime_workaround(): defs.append(("NPY_NEEDS_MINGW_TIME_WORKAROUND", None)) libs = [] # Configure mtrand config.add_extension('mtrand', sources=[join('mtrand', x) for x in ['mtrand.c', 'randomkit.c', 'initarray.c', 'distributions.c']]+[generate_libraries], libraries=libs, depends = [join('mtrand', '*.h'), join('mtrand', '*.pyx'), join('mtrand', '*.pxi'), ], define_macros = defs, ) config.add_data_files(('.', join('mtrand', 'randomkit.h'))) config.add_data_dir('tests') return config def testcode_wincrypt(): return """\ /* check to see if _WIN32 is defined */ int main(int argc, char *argv[]) { #ifdef _WIN32 return 0; #else return 1; #endif } """ if __name__ == '__main__': from numpy.distutils.core import setup setup(configuration=configuration) numpy-1.8.2/numpy/random/tests/0000775000175100017510000000000012371375430017623 5ustar vagrantvagrant00000000000000numpy-1.8.2/numpy/random/tests/test_regression.py0000664000175100017510000000621312370216242023410 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function from numpy.testing import (TestCase, run_module_suite, assert_, assert_array_equal) from numpy import random from numpy.compat import long import numpy as np class TestRegression(TestCase): def test_VonMises_range(self): # Make sure generated random variables are in [-pi, pi]. # Regression test for ticket #986. for mu in np.linspace(-7., 7., 5): r = random.mtrand.vonmises(mu, 1, 50) assert_(np.all(r > -np.pi) and np.all(r <= np.pi)) def test_hypergeometric_range(self): # Test for ticket #921 assert_(np.all(np.random.hypergeometric(3, 18, 11, size=10) < 4)) assert_(np.all(np.random.hypergeometric(18, 3, 11, size=10) > 0)) def test_logseries_convergence(self): # Test for ticket #923 N = 1000 np.random.seed(0) rvsn = np.random.logseries(0.8, size=N) # these two frequency counts should be close to theoretical # numbers with this large sample # theoretical large N result is 0.49706795 freq = np.sum(rvsn == 1) / float(N) msg = "Frequency was %f, should be > 0.45" % freq assert_(freq > 0.45, msg) # theoretical large N result is 0.19882718 freq = np.sum(rvsn == 2) / float(N) msg = "Frequency was %f, should be < 0.23" % freq assert_(freq < 0.23, msg) def test_permutation_longs(self): np.random.seed(1234) a = np.random.permutation(12) np.random.seed(1234) b = np.random.permutation(long(12)) assert_array_equal(a, b) def test_randint_range(self) : # Test for ticket #1690 lmax = np.iinfo('l').max lmin = np.iinfo('l').min try: random.randint(lmin, lmax) except: raise AssertionError def test_shuffle_mixed_dimension(self): # Test for trac ticket #2074 for t in [[1, 2, 3, None], [(1, 1), (2, 2), (3, 3), None], [1, (2, 2), (3, 3), None], [(1, 1), 2, 3, None]]: np.random.seed(12345) shuffled = list(t) random.shuffle(shuffled) assert_array_equal(shuffled, [t[0], t[3], t[1], t[2]]) def test_call_within_randomstate(self): # Check that custom RandomState does not call into global state m = np.random.RandomState() res = np.array([0, 8, 7, 2, 1, 9, 4, 7, 0, 3]) for i in range(3): np.random.seed(i) m.seed(4321) # If m.state is not honored, the result will change assert_array_equal(m.choice(10, size=10, p=np.ones(10)/10.), res) def test_multivariate_normal_size_types(self): # Test for multivariate_normal issue with 'size' argument. # Check that the multivariate_normal size argument can be a # numpy integer. np.random.multivariate_normal([0], [[0]], size=1) np.random.multivariate_normal([0], [[0]], size=np.int_(1)) np.random.multivariate_normal([0], [[0]], size=np.int64(1)) if __name__ == "__main__": run_module_suite() numpy-1.8.2/numpy/random/tests/test_random.py0000664000175100017510000006606212370216243022521 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function from numpy.testing import TestCase, run_module_suite, assert_,\ assert_raises, assert_equal from numpy import random from numpy.compat import asbytes import numpy as np class TestBinomial(TestCase): def test_n_zero(self): # Tests the corner case of n == 0 for the binomial distribution. # binomial(0, p) should be zero for any p in [0, 1]. # This test addresses issue #3480. zeros = np.zeros(2, dtype='int') for p in [0, .5, 1]: assert_(random.binomial(0, p) == 0) np.testing.assert_array_equal(random.binomial(zeros, p), zeros) class TestMultinomial(TestCase): def test_basic(self): random.multinomial(100, [0.2, 0.8]) def test_zero_probability(self): random.multinomial(100, [0.2, 0.8, 0.0, 0.0, 0.0]) def test_int_negative_interval(self): assert_( -5 <= random.randint(-5, -1) < -1) x = random.randint(-5, -1, 5) assert_(np.all(-5 <= x)) assert_(np.all(x < -1)) def test_size(self): # gh-3173 p = [0.5, 0.5] assert_equal(np.random.multinomial(1 ,p, np.uint32(1)).shape, (1, 2)) assert_equal(np.random.multinomial(1 ,p, np.uint32(1)).shape, (1, 2)) assert_equal(np.random.multinomial(1 ,p, np.uint32(1)).shape, (1, 2)) assert_equal(np.random.multinomial(1 ,p, [2, 2]).shape, (2, 2, 2)) assert_equal(np.random.multinomial(1 ,p, (2, 2)).shape, (2, 2, 2)) assert_equal(np.random.multinomial(1 ,p, np.array((2, 2))).shape, (2, 2, 2)) assert_raises(TypeError, np.random.multinomial, 1 , p, np.float(1)) class TestSetState(TestCase): def setUp(self): self.seed = 1234567890 self.prng = random.RandomState(self.seed) self.state = self.prng.get_state() def test_basic(self): old = self.prng.tomaxint(16) self.prng.set_state(self.state) new = self.prng.tomaxint(16) assert_(np.all(old == new)) def test_gaussian_reset(self): """ Make sure the cached every-other-Gaussian is reset. """ old = self.prng.standard_normal(size=3) self.prng.set_state(self.state) new = self.prng.standard_normal(size=3) assert_(np.all(old == new)) def test_gaussian_reset_in_media_res(self): """ When the state is saved with a cached Gaussian, make sure the cached Gaussian is restored. """ self.prng.standard_normal() state = self.prng.get_state() old = self.prng.standard_normal(size=3) self.prng.set_state(state) new = self.prng.standard_normal(size=3) assert_(np.all(old == new)) def test_backwards_compatibility(self): """ Make sure we can accept old state tuples that do not have the cached Gaussian value. """ old_state = self.state[:-2] x1 = self.prng.standard_normal(size=16) self.prng.set_state(old_state) x2 = self.prng.standard_normal(size=16) self.prng.set_state(self.state) x3 = self.prng.standard_normal(size=16) assert_(np.all(x1 == x2)) assert_(np.all(x1 == x3)) def test_negative_binomial(self): """ Ensure that the negative binomial results take floating point arguments without truncation. """ self.prng.negative_binomial(0.5, 0.5) class TestRandomDist(TestCase): """ Make sure the random distrobution return the correct value for a given seed """ def setUp(self): self.seed = 1234567890 def test_rand(self): np.random.seed(self.seed) actual = np.random.rand(3, 2) desired = np.array([[ 0.61879477158567997, 0.59162362775974664], [ 0.88868358904449662, 0.89165480011560816], [ 0.4575674820298663, 0.7781880808593471 ]]) np.testing.assert_array_almost_equal(actual, desired, decimal=15) def test_randn(self): np.random.seed(self.seed) actual = np.random.randn(3, 2) desired = np.array([[ 1.34016345771863121, 1.73759122771936081], [ 1.498988344300628, -0.2286433324536169 ], [ 2.031033998682787, 2.17032494605655257]]) np.testing.assert_array_almost_equal(actual, desired, decimal=15) def test_randint(self): np.random.seed(self.seed) actual = np.random.randint(-99, 99, size=(3, 2)) desired = np.array([[ 31, 3], [-52, 41], [-48, -66]]) np.testing.assert_array_equal(actual, desired) def test_random_integers(self): np.random.seed(self.seed) actual = np.random.random_integers(-99, 99, size=(3, 2)) desired = np.array([[ 31, 3], [-52, 41], [-48, -66]]) np.testing.assert_array_equal(actual, desired) def test_random_sample(self): np.random.seed(self.seed) actual = np.random.random_sample((3, 2)) desired = np.array([[ 0.61879477158567997, 0.59162362775974664], [ 0.88868358904449662, 0.89165480011560816], [ 0.4575674820298663, 0.7781880808593471 ]]) np.testing.assert_array_almost_equal(actual, desired, decimal=15) def test_choice_uniform_replace(self): np.random.seed(self.seed) actual = np.random.choice(4, 4) desired = np.array([2, 3, 2, 3]) np.testing.assert_array_equal(actual, desired) def test_choice_nonuniform_replace(self): np.random.seed(self.seed) actual = np.random.choice(4, 4, p=[0.4, 0.4, 0.1, 0.1]) desired = np.array([1, 1, 2, 2]) np.testing.assert_array_equal(actual, desired) def test_choice_uniform_noreplace(self): np.random.seed(self.seed) actual = np.random.choice(4, 3, replace=False) desired = np.array([0, 1, 3]) np.testing.assert_array_equal(actual, desired) def test_choice_nonuniform_noreplace(self): np.random.seed(self.seed) actual = np.random.choice(4, 3, replace=False, p=[0.1, 0.3, 0.5, 0.1]) desired = np.array([2, 3, 1]) np.testing.assert_array_equal(actual, desired) def test_choice_noninteger(self): np.random.seed(self.seed) actual = np.random.choice(['a', 'b', 'c', 'd'], 4) desired = np.array(['c', 'd', 'c', 'd']) np.testing.assert_array_equal(actual, desired) def test_choice_exceptions(self): sample = np.random.choice assert_raises(ValueError, sample, -1, 3) assert_raises(ValueError, sample, 3., 3) assert_raises(ValueError, sample, [[1, 2], [3, 4]], 3) assert_raises(ValueError, sample, [], 3) assert_raises(ValueError, sample, [1, 2, 3, 4], 3, p=[[0.25, 0.25], [0.25, 0.25]]) assert_raises(ValueError, sample, [1, 2], 3, p=[0.4, 0.4, 0.2]) assert_raises(ValueError, sample, [1, 2], 3, p=[1.1, -0.1]) assert_raises(ValueError, sample, [1, 2], 3, p=[0.4, 0.4]) assert_raises(ValueError, sample, [1, 2, 3], 4, replace=False) assert_raises(ValueError, sample, [1, 2, 3], 2, replace=False, p=[1, 0, 0]) def test_choice_return_shape(self): p = [0.1, 0.9] # Check scalar assert_(np.isscalar(np.random.choice(2, replace=True))) assert_(np.isscalar(np.random.choice(2, replace=False))) assert_(np.isscalar(np.random.choice(2, replace=True, p=p))) assert_(np.isscalar(np.random.choice(2, replace=False, p=p))) assert_(np.isscalar(np.random.choice([1, 2], replace=True))) assert_(np.random.choice([None], replace=True) is None) a = np.array([1, 2]) arr = np.empty(1, dtype=object) arr[0] = a assert_(np.random.choice(arr, replace=True) is a) # Check 0-d array s = tuple() assert_(not np.isscalar(np.random.choice(2, s, replace=True))) assert_(not np.isscalar(np.random.choice(2, s, replace=False))) assert_(not np.isscalar(np.random.choice(2, s, replace=True, p=p))) assert_(not np.isscalar(np.random.choice(2, s, replace=False, p=p))) assert_(not np.isscalar(np.random.choice([1, 2], s, replace=True))) assert_(np.random.choice([None], s, replace=True).ndim == 0) a = np.array([1, 2]) arr = np.empty(1, dtype=object) arr[0] = a assert_(np.random.choice(arr, s, replace=True).item() is a) # Check multi dimensional array s = (2, 3) p = [0.1, 0.1, 0.1, 0.1, 0.4, 0.2] assert_(np.random.choice(6, s, replace=True).shape, s) assert_(np.random.choice(6, s, replace=False).shape, s) assert_(np.random.choice(6, s, replace=True, p=p).shape, s) assert_(np.random.choice(6, s, replace=False, p=p).shape, s) assert_(np.random.choice(np.arange(6), s, replace=True).shape, s) def test_bytes(self): np.random.seed(self.seed) actual = np.random.bytes(10) desired = asbytes('\x82Ui\x9e\xff\x97+Wf\xa5') np.testing.assert_equal(actual, desired) def test_shuffle(self): # Test lists, arrays, and multidimensional versions of both: for conv in [lambda x: x, np.asarray, lambda x: [(i, i) for i in x], lambda x: np.asarray([(i, i) for i in x])]: np.random.seed(self.seed) alist = conv([1, 2, 3, 4, 5, 6, 7, 8, 9, 0]) np.random.shuffle(alist) actual = alist 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)) desired = np.array([[ 1.45341850513746058e-02, 5.31297615662868145e-04], [ 1.85366619058432324e-06, 4.19214516800110563e-03], [ 1.58405155108498093e-04, 1.26252891949397652e-04]]) np.testing.assert_array_almost_equal(actual, desired, decimal=15) def test_binomial(self): np.random.seed(self.seed) actual = np.random.binomial(100.123, .456, size=(3, 2)) desired = np.array([[37, 43], [42, 48], [46, 45]]) np.testing.assert_array_equal(actual, desired) def test_chisquare(self): np.random.seed(self.seed) actual = np.random.chisquare(50, size=(3, 2)) desired = np.array([[ 63.87858175501090585, 68.68407748911370447], [ 65.77116116901505904, 47.09686762438974483], [ 72.3828403199695174, 74.18408615260374006]]) np.testing.assert_array_almost_equal(actual, desired, decimal=13) def test_dirichlet(self): np.random.seed(self.seed) alpha = np.array([51.72840233779265162, 39.74494232180943953]) actual = np.random.mtrand.dirichlet(alpha, size=(3, 2)) desired = np.array([[[ 0.54539444573611562, 0.45460555426388438], [ 0.62345816822039413, 0.37654183177960598]], [[ 0.55206000085785778, 0.44793999914214233], [ 0.58964023305154301, 0.41035976694845688]], [[ 0.59266909280647828, 0.40733090719352177], [ 0.56974431743975207, 0.43025568256024799]]]) 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)) desired = np.array([[ 1.08342649775011624, 1.00607889924557314], [ 2.46628830085216721, 2.49668106809923884], [ 0.68717433461363442, 1.69175666993575979]]) np.testing.assert_array_almost_equal(actual, desired, decimal=15) def test_f(self): np.random.seed(self.seed) actual = np.random.f(12, 77, size=(3, 2)) desired = np.array([[ 1.21975394418575878, 1.75135759791559775], [ 1.44803115017146489, 1.22108959480396262], [ 1.02176975757740629, 1.34431827623300415]]) np.testing.assert_array_almost_equal(actual, desired, decimal=15) def test_gamma(self): np.random.seed(self.seed) actual = np.random.gamma(5, 3, size=(3, 2)) desired = np.array([[ 24.60509188649287182, 28.54993563207210627], [ 26.13476110204064184, 12.56988482927716078], [ 31.71863275789960568, 33.30143302795922011]]) np.testing.assert_array_almost_equal(actual, desired, decimal=14) def test_geometric(self): np.random.seed(self.seed) actual = np.random.geometric(.123456789, size=(3, 2)) desired = np.array([[ 8, 7], [17, 17], [ 5, 12]]) np.testing.assert_array_equal(actual, desired) def test_gumbel(self): np.random.seed(self.seed) actual = np.random.gumbel(loc = .123456789, scale = 2.0, size = (3, 2)) desired = np.array([[ 0.19591898743416816, 0.34405539668096674], [-1.4492522252274278, -1.47374816298446865], [ 1.10651090478803416, -0.69535848626236174]]) np.testing.assert_array_almost_equal(actual, desired, decimal=15) def test_hypergeometric(self): np.random.seed(self.seed) actual = np.random.hypergeometric(10.1, 5.5, 14, size=(3, 2)) desired = np.array([[10, 10], [10, 10], [ 9, 9]]) np.testing.assert_array_equal(actual, desired) # Test nbad = 0 actual = np.random.hypergeometric(5, 0, 3, size=4) desired = np.array([3, 3, 3, 3]) np.testing.assert_array_equal(actual, desired) actual = np.random.hypergeometric(15, 0, 12, size=4) desired = np.array([12, 12, 12, 12]) np.testing.assert_array_equal(actual, desired) # Test ngood = 0 actual = np.random.hypergeometric(0, 5, 3, size=4) desired = np.array([0, 0, 0, 0]) np.testing.assert_array_equal(actual, desired) actual = np.random.hypergeometric(0, 15, 12, size=4) desired = np.array([0, 0, 0, 0]) np.testing.assert_array_equal(actual, desired) def test_laplace(self): np.random.seed(self.seed) actual = np.random.laplace(loc=.123456789, scale=2.0, size=(3, 2)) desired = np.array([[ 0.66599721112760157, 0.52829452552221945], [ 3.12791959514407125, 3.18202813572992005], [-0.05391065675859356, 1.74901336242837324]]) np.testing.assert_array_almost_equal(actual, desired, decimal=15) def test_logistic(self): np.random.seed(self.seed) actual = np.random.logistic(loc=.123456789, scale=2.0, size=(3, 2)) desired = np.array([[ 1.09232835305011444, 0.8648196662399954 ], [ 4.27818590694950185, 4.33897006346929714], [-0.21682183359214885, 2.63373365386060332]]) np.testing.assert_array_almost_equal(actual, desired, decimal=15) def test_lognormal(self): np.random.seed(self.seed) actual = np.random.lognormal(mean=.123456789, sigma=2.0, size=(3, 2)) desired = np.array([[ 16.50698631688883822, 36.54846706092654784], [ 22.67886599981281748, 0.71617561058995771], [ 65.72798501792723869, 86.84341601437161273]]) np.testing.assert_array_almost_equal(actual, desired, decimal=13) def test_logseries(self): np.random.seed(self.seed) actual = np.random.logseries(p=.923456789, size=(3, 2)) desired = np.array([[ 2, 2], [ 6, 17], [ 3, 6]]) np.testing.assert_array_equal(actual, desired) def test_multinomial(self): np.random.seed(self.seed) actual = np.random.multinomial(20, [1/6.]*6, size=(3, 2)) desired = np.array([[[4, 3, 5, 4, 2, 2], [5, 2, 8, 2, 2, 1]], [[3, 4, 3, 6, 0, 4], [2, 1, 4, 3, 6, 4]], [[4, 4, 2, 5, 2, 3], [4, 3, 4, 2, 3, 4]]]) np.testing.assert_array_equal(actual, desired) def test_multivariate_normal(self): np.random.seed(self.seed) mean= (.123456789, 10) 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. ]]]) np.testing.assert_array_almost_equal(actual, desired, decimal=15) def test_negative_binomial(self): np.random.seed(self.seed) actual = np.random.negative_binomial(n = 100, p = .12345, size = (3, 2)) desired = np.array([[848, 841], [892, 611], [779, 647]]) np.testing.assert_array_equal(actual, desired) def test_noncentral_chisquare(self): np.random.seed(self.seed) actual = np.random.noncentral_chisquare(df = 5, nonc = 5, size = (3, 2)) desired = np.array([[ 23.91905354498517511, 13.35324692733826346], [ 31.22452661329736401, 16.60047399466177254], [ 5.03461598262724586, 17.94973089023519464]]) np.testing.assert_array_almost_equal(actual, desired, decimal=14) def test_noncentral_f(self): np.random.seed(self.seed) actual = np.random.noncentral_f(dfnum = 5, dfden = 2, nonc = 1, size = (3, 2)) desired = np.array([[ 1.40598099674926669, 0.34207973179285761], [ 3.57715069265772545, 7.92632662577829805], [ 0.43741599463544162, 1.1774208752428319 ]]) np.testing.assert_array_almost_equal(actual, desired, decimal=14) def test_normal(self): np.random.seed(self.seed) actual = np.random.normal(loc = .123456789, scale = 2.0, size = (3, 2)) desired = np.array([[ 2.80378370443726244, 3.59863924443872163], [ 3.121433477601256, -0.33382987590723379], [ 4.18552478636557357, 4.46410668111310471]]) np.testing.assert_array_almost_equal(actual, desired, decimal=15) def test_pareto(self): np.random.seed(self.seed) actual = np.random.pareto(a =.123456789, size = (3, 2)) desired = np.array([[ 2.46852460439034849e+03, 1.41286880810518346e+03], [ 5.28287797029485181e+07, 6.57720981047328785e+07], [ 1.40840323350391515e+02, 1.98390255135251704e+05]]) # For some reason on 32-bit x86 Ubuntu 12.10 the [1, 0] entry in this # matrix differs by 24 nulps. Discussion: # http://mail.scipy.org/pipermail/numpy-discussion/2012-September/063801.html # Consensus is that this is probably some gcc quirk that affects # rounding but not in any important way, so we just use a looser # tolerance on this test: np.testing.assert_array_almost_equal_nulp(actual, desired, nulp=30) def test_poisson(self): np.random.seed(self.seed) actual = np.random.poisson(lam = .123456789, size=(3, 2)) desired = np.array([[0, 0], [1, 0], [0, 0]]) np.testing.assert_array_equal(actual, desired) def test_poisson_exceptions(self): lambig = np.iinfo('l').max lamneg = -1 assert_raises(ValueError, np.random.poisson, lamneg) assert_raises(ValueError, np.random.poisson, [lamneg]*10) assert_raises(ValueError, np.random.poisson, lambig) assert_raises(ValueError, np.random.poisson, [lambig]*10) def test_power(self): np.random.seed(self.seed) actual = np.random.power(a =.123456789, size = (3, 2)) desired = np.array([[ 0.02048932883240791, 0.01424192241128213], [ 0.38446073748535298, 0.39499689943484395], [ 0.00177699707563439, 0.13115505880863756]]) np.testing.assert_array_almost_equal(actual, desired, decimal=15) def test_rayleigh(self): np.random.seed(self.seed) actual = np.random.rayleigh(scale = 10, size = (3, 2)) desired = np.array([[ 13.8882496494248393, 13.383318339044731 ], [ 20.95413364294492098, 21.08285015800712614], [ 11.06066537006854311, 17.35468505778271009]]) np.testing.assert_array_almost_equal(actual, desired, decimal=14) def test_standard_cauchy(self): np.random.seed(self.seed) actual = np.random.standard_cauchy(size = (3, 2)) desired = np.array([[ 0.77127660196445336, -6.55601161955910605], [ 0.93582023391158309, -2.07479293013759447], [-4.74601644297011926, 0.18338989290760804]]) np.testing.assert_array_almost_equal(actual, desired, decimal=15) def test_standard_exponential(self): np.random.seed(self.seed) actual = np.random.standard_exponential(size = (3, 2)) desired = np.array([[ 0.96441739162374596, 0.89556604882105506], [ 2.1953785836319808, 2.22243285392490542], [ 0.6116915921431676, 1.50592546727413201]]) np.testing.assert_array_almost_equal(actual, desired, decimal=15) def test_standard_gamma(self): np.random.seed(self.seed) actual = np.random.standard_gamma(shape = 3, size = (3, 2)) desired = np.array([[ 5.50841531318455058, 6.62953470301903103], [ 5.93988484943779227, 2.31044849402133989], [ 7.54838614231317084, 8.012756093271868 ]]) np.testing.assert_array_almost_equal(actual, desired, decimal=14) def test_standard_normal(self): np.random.seed(self.seed) actual = np.random.standard_normal(size = (3, 2)) desired = np.array([[ 1.34016345771863121, 1.73759122771936081], [ 1.498988344300628, -0.2286433324536169 ], [ 2.031033998682787, 2.17032494605655257]]) np.testing.assert_array_almost_equal(actual, desired, decimal=15) def test_standard_t(self): np.random.seed(self.seed) actual = np.random.standard_t(df = 10, size = (3, 2)) desired = np.array([[ 0.97140611862659965, -0.08830486548450577], [ 1.36311143689505321, -0.55317463909867071], [-0.18473749069684214, 0.61181537341755321]]) np.testing.assert_array_almost_equal(actual, desired, decimal=15) def test_triangular(self): np.random.seed(self.seed) actual = np.random.triangular(left = 5.12, mode = 10.23, right = 20.34, size = (3, 2)) desired = np.array([[ 12.68117178949215784, 12.4129206149193152 ], [ 16.20131377335158263, 16.25692138747600524], [ 11.20400690911820263, 14.4978144835829923 ]]) np.testing.assert_array_almost_equal(actual, desired, decimal=14) def test_uniform(self): np.random.seed(self.seed) actual = np.random.uniform(low = 1.23, high=10.54, size = (3, 2)) desired = np.array([[ 6.99097932346268003, 6.73801597444323974], [ 9.50364421400426274, 9.53130618907631089], [ 5.48995325769805476, 8.47493103280052118]]) np.testing.assert_array_almost_equal(actual, desired, decimal=15) def test_vonmises(self): np.random.seed(self.seed) actual = np.random.vonmises(mu = 1.23, kappa = 1.54, size = (3, 2)) desired = np.array([[ 2.28567572673902042, 2.89163838442285037], [ 0.38198375564286025, 2.57638023113890746], [ 1.19153771588353052, 1.83509849681825354]]) np.testing.assert_array_almost_equal(actual, desired, decimal=15) def test_wald(self): np.random.seed(self.seed) actual = np.random.wald(mean = 1.23, scale = 1.54, size = (3, 2)) desired = np.array([[ 3.82935265715889983, 5.13125249184285526], [ 0.35045403618358717, 1.50832396872003538], [ 0.24124319895843183, 0.22031101461955038]]) np.testing.assert_array_almost_equal(actual, desired, decimal=14) def test_weibull(self): np.random.seed(self.seed) actual = np.random.weibull(a = 1.23, size = (3, 2)) desired = np.array([[ 0.97097342648766727, 0.91422896443565516], [ 1.89517770034962929, 1.91414357960479564], [ 0.67057783752390987, 1.39494046635066793]]) np.testing.assert_array_almost_equal(actual, desired, decimal=15) def test_zipf(self): np.random.seed(self.seed) actual = np.random.zipf(a = 1.23, size = (3, 2)) desired = np.array([[66, 29], [ 1, 1], [ 3, 13]]) np.testing.assert_array_equal(actual, desired) if __name__ == "__main__": run_module_suite() numpy-1.8.2/numpy/random/__init__.py0000664000175100017510000001173712370216243020576 0ustar vagrantvagrant00000000000000""" ======================== Random Number Generation ======================== ==================== ========================================================= Utility functions ============================================================================== random Uniformly distributed values of a given shape. bytes Uniformly distributed random bytes. random_integers Uniformly distributed integers in a given range. random_sample Uniformly distributed floats in a given range. random Alias for random_sample ranf Alias for random_sample sample Alias for random_sample choice Generate a weighted random sample from a given array-like permutation Randomly permute a sequence / generate a random sequence. shuffle Randomly permute a sequence in place. seed Seed the random number generator. ==================== ========================================================= ==================== ========================================================= Compatibility functions ============================================================================== rand Uniformly distributed values. randn Normally distributed values. ranf Uniformly distributed floating point numbers. randint Uniformly distributed integers in a given range. ==================== ========================================================= ==================== ========================================================= Univariate distributions ============================================================================== beta Beta distribution over ``[0, 1]``. binomial Binomial distribution. chisquare :math:`\\chi^2` distribution. exponential Exponential distribution. f F (Fisher-Snedecor) distribution. gamma Gamma distribution. geometric Geometric distribution. gumbel Gumbel distribution. hypergeometric Hypergeometric distribution. laplace Laplace distribution. logistic Logistic distribution. lognormal Log-normal distribution. logseries Logarithmic series distribution. negative_binomial Negative binomial distribution. noncentral_chisquare Non-central chi-square distribution. noncentral_f Non-central F distribution. normal Normal / Gaussian distribution. pareto Pareto distribution. poisson Poisson distribution. power Power distribution. rayleigh Rayleigh distribution. triangular Triangular distribution. uniform Uniform distribution. vonmises Von Mises circular distribution. wald Wald (inverse Gaussian) distribution. weibull Weibull distribution. zipf Zipf's distribution over ranked data. ==================== ========================================================= ==================== ========================================================= Multivariate distributions ============================================================================== dirichlet Multivariate generalization of Beta distribution. multinomial Multivariate generalization of the binomial distribution. multivariate_normal Multivariate generalization of the normal distribution. ==================== ========================================================= ==================== ========================================================= Standard distributions ============================================================================== standard_cauchy Standard Cauchy-Lorentz distribution. standard_exponential Standard exponential distribution. standard_gamma Standard Gamma distribution. standard_normal Standard normal distribution. standard_t Standard Student's t-distribution. ==================== ========================================================= ==================== ========================================================= Internal functions ============================================================================== get_state Get tuple representing internal state of generator. set_state Set state of generator. ==================== ========================================================= """ from __future__ import division, absolute_import, print_function import warnings # To get sub-modules from .info import __doc__, __all__ with warnings.catch_warnings(): warnings.filterwarnings("ignore", message="numpy.ndarray size changed") from .mtrand import * # Some aliases: ranf = random = sample = random_sample __all__.extend(['ranf', 'random', 'sample']) def __RandomState_ctor(): """Return a RandomState instance. This function exists solely to assist (un)pickling. """ return RandomState() from numpy.testing import Tester test = Tester().test bench = Tester().bench numpy-1.8.2/numpy/oldnumeric/0000775000175100017510000000000012371375430017342 5ustar vagrantvagrant00000000000000numpy-1.8.2/numpy/oldnumeric/precision.py0000664000175100017510000001034312370216243021703 0ustar vagrantvagrant00000000000000""" Lifted from Precision.py. This is for compatibility only. The character strings are still for "new" NumPy which is the only Incompatibility with Numeric """ from __future__ import division, absolute_import, print_function __all__ = ['Character', 'Complex', 'Float', 'PrecisionError', 'PyObject', 'Int', 'UInt', 'UnsignedInt', 'UnsignedInteger', 'string', 'typecodes', 'zeros'] from .functions import zeros import string # for backwards compatibility typecodes = {'Character':'c', 'Integer':'bhil', 'UnsignedInteger':'BHIL', 'Float':'fd', 'Complex':'FD'} def _get_precisions(typecodes): lst = [] for t in typecodes: lst.append( (zeros( (1,), t ).itemsize*8, t) ) return lst def _fill_table(typecodes, table={}): for key, value in typecodes.items(): table[key] = _get_precisions(value) return table _code_table = _fill_table(typecodes) class PrecisionError(Exception): pass def _lookup(table, key, required_bits): lst = table[key] for bits, typecode in lst: if bits >= required_bits: return typecode raise PrecisionError(key + " of " + str(required_bits) + " bits not available on this system") Character = 'c' try: UnsignedInt8 = _lookup(_code_table, "UnsignedInteger", 8) UInt8 = UnsignedInt8 __all__.extend(['UnsignedInt8', 'UInt8']) except(PrecisionError): pass try: UnsignedInt16 = _lookup(_code_table, "UnsignedInteger", 16) UInt16 = UnsignedInt16 __all__.extend(['UnsignedInt16', 'UInt16']) except(PrecisionError): pass try: UnsignedInt32 = _lookup(_code_table, "UnsignedInteger", 32) UInt32 = UnsignedInt32 __all__.extend(['UnsignedInt32', 'UInt32']) except(PrecisionError): pass try: UnsignedInt64 = _lookup(_code_table, "UnsignedInteger", 64) UInt64 = UnsignedInt64 __all__.extend(['UnsignedInt64', 'UInt64']) except(PrecisionError): pass try: UnsignedInt128 = _lookup(_code_table, "UnsignedInteger", 128) UInt128 = UnsignedInt128 __all__.extend(['UnsignedInt128', 'UInt128']) except(PrecisionError): pass UInt = UnsignedInt = UnsignedInteger = 'u' try: Int0 = _lookup(_code_table, 'Integer', 0) __all__.append('Int0') except(PrecisionError): pass try: Int8 = _lookup(_code_table, 'Integer', 8) __all__.append('Int8') except(PrecisionError): pass try: Int16 = _lookup(_code_table, 'Integer', 16) __all__.append('Int16') except(PrecisionError): pass try: Int32 = _lookup(_code_table, 'Integer', 32) __all__.append('Int32') except(PrecisionError): pass try: Int64 = _lookup(_code_table, 'Integer', 64) __all__.append('Int64') except(PrecisionError): pass try: Int128 = _lookup(_code_table, 'Integer', 128) __all__.append('Int128') except(PrecisionError): pass Int = 'l' try: Float0 = _lookup(_code_table, 'Float', 0) __all__.append('Float0') except(PrecisionError): pass try: Float8 = _lookup(_code_table, 'Float', 8) __all__.append('Float8') except(PrecisionError): pass try: Float16 = _lookup(_code_table, 'Float', 16) __all__.append('Float16') except(PrecisionError): pass try: Float32 = _lookup(_code_table, 'Float', 32) __all__.append('Float32') except(PrecisionError): pass try: Float64 = _lookup(_code_table, 'Float', 64) __all__.append('Float64') except(PrecisionError): pass try: Float128 = _lookup(_code_table, 'Float', 128) __all__.append('Float128') except(PrecisionError): pass Float = 'd' try: Complex0 = _lookup(_code_table, 'Complex', 0) __all__.append('Complex0') except(PrecisionError): pass try: Complex8 = _lookup(_code_table, 'Complex', 16) __all__.append('Complex8') except(PrecisionError): pass try: Complex16 = _lookup(_code_table, 'Complex', 32) __all__.append('Complex16') except(PrecisionError): pass try: Complex32 = _lookup(_code_table, 'Complex', 64) __all__.append('Complex32') except(PrecisionError): pass try: Complex64 = _lookup(_code_table, 'Complex', 128) __all__.append('Complex64') except(PrecisionError): pass try: Complex128 = _lookup(_code_table, 'Complex', 256) __all__.append('Complex128') except(PrecisionError): pass Complex = 'D' PyObject = 'O' numpy-1.8.2/numpy/oldnumeric/alter_code2.py0000664000175100017510000001115112370216243022071 0ustar vagrantvagrant00000000000000""" This module converts code written for numpy.oldnumeric to work with numpy FIXME: Flesh this out. Makes the following changes: * Converts typecharacters '1swu' to 'bhHI' respectively when used as typecodes * Changes import statements * Change typecode= to dtype= * Eliminates savespace=xxx keyword arguments * Removes it when keyword is not given as well * replaces matrixmultiply with dot * converts functions that don't give axis= keyword that have changed * converts functions that don't give typecode= keyword that have changed * converts use of capitalized type-names * converts old function names in oldnumeric.linear_algebra, oldnumeric.random_array, and oldnumeric.fft """ from __future__ import division, absolute_import, print_function #__all__ = ['convertfile', 'convertall', 'converttree'] __all__ = [] import warnings warnings.warn("numpy.oldnumeric.alter_code2 is not working yet.") import sys import os import re import glob # To convert typecharacters we need to # Not very safe. Disabled for now.. def replacetypechars(astr): astr = astr.replace("'s'", "'h'") astr = astr.replace("'b'", "'B'") astr = astr.replace("'1'", "'b'") astr = astr.replace("'w'", "'H'") astr = astr.replace("'u'", "'I'") return astr def changeimports(fstr, name, newname): importstr = 'import %s' % name importasstr = 'import %s as ' % name fromstr = 'from %s import ' % name fromall=0 fstr = fstr.replace(importasstr, 'import %s as ' % newname) fstr = fstr.replace(importstr, 'import %s as %s' % (newname, name)) ind = 0 Nlen = len(fromstr) Nlen2 = len("from %s import " % newname) while True: found = fstr.find(fromstr, ind) if (found < 0): break ind = found + Nlen if fstr[ind] == '*': continue fstr = "%sfrom %s import %s" % (fstr[:found], newname, fstr[ind:]) ind += Nlen2 - Nlen return fstr, fromall def replaceattr(astr): astr = astr.replace("matrixmultiply", "dot") return astr def replaceother(astr): astr = re.sub(r'typecode\s*=', 'dtype=', astr) astr = astr.replace('ArrayType', 'ndarray') astr = astr.replace('NewAxis', 'newaxis') return astr import datetime def fromstr(filestr): #filestr = replacetypechars(filestr) filestr, fromall1 = changeimports(filestr, 'numpy.oldnumeric', 'numpy') filestr, fromall1 = changeimports(filestr, 'numpy.core.multiarray', 'numpy') filestr, fromall1 = changeimports(filestr, 'numpy.core.umath', 'numpy') filestr, fromall3 = changeimports(filestr, 'LinearAlgebra', 'numpy.linalg.old') filestr, fromall3 = changeimports(filestr, 'RNG', 'numpy.random.oldrng') filestr, fromall3 = changeimports(filestr, 'RNG.Statistics', 'numpy.random.oldrngstats') filestr, fromall3 = changeimports(filestr, 'RandomArray', 'numpy.random.oldrandomarray') filestr, fromall3 = changeimports(filestr, 'FFT', 'numpy.fft.old') filestr, fromall3 = changeimports(filestr, 'MA', 'numpy.core.ma') fromall = fromall1 or fromall2 or fromall3 filestr = replaceattr(filestr) filestr = replaceother(filestr) today = datetime.date.today().strftime('%b %d, %Y') name = os.path.split(sys.argv[0])[-1] filestr = '## Automatically adapted for '\ 'numpy %s by %s\n\n%s' % (today, name, filestr) return filestr def makenewfile(name, filestr): fid = file(name, 'w') fid.write(filestr) fid.close() def getandcopy(name): fid = file(name) filestr = fid.read() fid.close() base, ext = os.path.splitext(name) makenewfile(base+'.orig', filestr) return filestr def convertfile(filename): """Convert the filename given from using Numeric to using NumPy Copies the file to filename.orig and then over-writes the file with the updated code """ filestr = getandcopy(filename) filestr = fromstr(filestr) makenewfile(filename, filestr) def fromargs(args): filename = args[1] convertfile(filename) def convertall(direc=os.path.curdir): """Convert all .py files to use NumPy (from Numeric) in the directory given For each file, a backup of .py is made as .py.orig. A new file named .py is then written with the updated code. """ files = glob.glob(os.path.join(direc, '*.py')) for afile in files: convertfile(afile) def _func(arg, dirname, fnames): convertall(dirname) def converttree(direc=os.path.curdir): """Convert all .py files in the tree given """ os.path.walk(direc, _func, None) if __name__ == '__main__': fromargs(sys.argv) numpy-1.8.2/numpy/oldnumeric/matrix.py0000664000175100017510000000321612370216243021215 0ustar vagrantvagrant00000000000000"""This module is for compatibility only. """ from __future__ import division, absolute_import, print_function __all__ = ['UserArray', 'squeeze', 'Matrix', 'asarray', 'dot', 'k', 'Numeric', 'LinearAlgebra', 'identity', 'multiply', 'types', 'string'] import types from .user_array import UserArray, asarray import numpy.oldnumeric as Numeric from numpy.oldnumeric import dot, identity, multiply import numpy.oldnumeric.linear_algebra as LinearAlgebra from numpy import matrix as Matrix, squeeze # Hidden names that will be the same. _table = [None]*256 for k in range(256): _table[k] = chr(k) _table = ''.join(_table) _numchars = '0123456789.-+jeEL' _todelete = [] for k in _table: if k not in _numchars: _todelete.append(k) _todelete = ''.join(_todelete) def _eval(astr): return eval(astr.translate(_table, _todelete)) def _convert_from_string(data): data.find rows = data.split(';') newdata = [] count = 0 for row in rows: trow = row.split(',') newrow = [] for col in trow: temp = col.split() newrow.extend(map(_eval, temp)) if count == 0: Ncols = len(newrow) elif len(newrow) != Ncols: raise ValueError("Rows not the same size.") count += 1 newdata.append(newrow) return newdata _lkup = {'0':'000', '1':'001', '2':'010', '3':'011', '4':'100', '5':'101', '6':'110', '7':'111'} def _binary(num): ostr = oct(num) bin = '' for ch in ostr[1:]: bin += _lkup[ch] ind = 0 while bin[ind] == '0': ind += 1 return bin[ind:] numpy-1.8.2/numpy/oldnumeric/rng.py0000664000175100017510000000734612370216243020507 0ustar vagrantvagrant00000000000000"""Re-create the RNG interface from Numeric. Replace import RNG with import numpy.oldnumeric.rng as RNG. It is for backwards compatibility only. """ from __future__ import division, absolute_import, print_function __all__ = ['CreateGenerator', 'ExponentialDistribution', 'LogNormalDistribution', 'NormalDistribution', 'UniformDistribution', 'error', 'ranf', 'default_distribution', 'random_sample', 'standard_generator'] import numpy.random.mtrand as mt import math class error(Exception): pass class Distribution(object): def __init__(self, meth, *args): self._meth = meth self._args = args def density(self, x): raise NotImplementedError def __call__(self, x): return self.density(x) def _onesample(self, rng): return getattr(rng, self._meth)(*self._args) def _sample(self, rng, n): kwds = {'size' : n} return getattr(rng, self._meth)(*self._args, **kwds) class ExponentialDistribution(Distribution): def __init__(self, lambda_): if (lambda_ <= 0): raise error("parameter must be positive") Distribution.__init__(self, 'exponential', lambda_) def density(x): if x < 0: return 0.0 else: lambda_ = self._args[0] return lambda_*math.exp(-lambda_*x) class LogNormalDistribution(Distribution): def __init__(self, m, s): m = float(m) s = float(s) if (s <= 0): raise error("standard deviation must be positive") Distribution.__init__(self, 'lognormal', m, s) sn = math.log(1.0+s*s/(m*m)); self._mn = math.log(m)-0.5*sn self._sn = math.sqrt(sn) self._fac = 1.0/math.sqrt(2*math.pi)/self._sn def density(x): m, s = self._args y = (math.log(x)-self._mn)/self._sn return self._fac*math.exp(-0.5*y*y)/x class NormalDistribution(Distribution): def __init__(self, m, s): m = float(m) s = float(s) if (s <= 0): raise error("standard deviation must be positive") Distribution.__init__(self, 'normal', m, s) self._fac = 1.0/math.sqrt(2*math.pi)/s def density(x): m, s = self._args y = (x-m)/s return self._fac*math.exp(-0.5*y*y) class UniformDistribution(Distribution): def __init__(self, a, b): a = float(a) b = float(b) width = b-a if (width <=0): raise error("width of uniform distribution must be > 0") Distribution.__init__(self, 'uniform', a, b) self._fac = 1.0/width def density(x): a, b = self._args if (x < a) or (x >= b): return 0.0 else: return self._fac default_distribution = UniformDistribution(0.0, 1.0) class CreateGenerator(object): def __init__(self, seed, dist=None): if seed <= 0: self._rng = mt.RandomState() elif seed > 0: self._rng = mt.RandomState(seed) if dist is None: dist = default_distribution if not isinstance(dist, Distribution): raise error("Not a distribution object") self._dist = dist def ranf(self): return self._dist._onesample(self._rng) def sample(self, n): return self._dist._sample(self._rng, n) standard_generator = CreateGenerator(-1) def ranf(): "ranf() = a random number from the standard generator." return standard_generator.ranf() def random_sample(*n): """random_sample(n) = array of n random numbers; random_sample(n1, n2, ...)= random array of shape (n1, n2, ..)""" if not n: return standard_generator.ranf() m = 1 for i in n: m = m * i return standard_generator.sample(m).reshape(*n) numpy-1.8.2/numpy/oldnumeric/typeconv.py0000664000175100017510000000323012370216243021554 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function __all__ = ['oldtype2dtype', 'convtypecode', 'convtypecode2', 'oldtypecodes'] import numpy as np oldtype2dtype = {'1': np.dtype(np.byte), 's': np.dtype(np.short), # 'i': np.dtype(np.intc), # 'l': np.dtype(int), # 'b': np.dtype(np.ubyte), 'w': np.dtype(np.ushort), 'u': np.dtype(np.uintc), # 'f': np.dtype(np.single), # 'd': np.dtype(float), # 'F': np.dtype(np.csingle), # 'D': np.dtype(complex), # 'O': np.dtype(object), # 'c': np.dtype('c'), None: np.dtype(int) } # converts typecode=None to int def convtypecode(typecode, dtype=None): if dtype is None: try: return oldtype2dtype[typecode] except: return np.dtype(typecode) else: return dtype #if both typecode and dtype are None # return None def convtypecode2(typecode, dtype=None): if dtype is None: if typecode is None: return None else: try: return oldtype2dtype[typecode] except: return np.dtype(typecode) else: return dtype _changedtypes = {'B': 'b', 'b': '1', 'h': 's', 'H': 'w', 'I': 'u'} class _oldtypecodes(dict): def __getitem__(self, obj): char = np.dtype(obj).char try: return _changedtypes[char] except KeyError: return char oldtypecodes = _oldtypecodes() numpy-1.8.2/numpy/oldnumeric/compat.py0000664000175100017510000000624312370216243021177 0ustar vagrantvagrant00000000000000"""Compatibility module containing deprecated names. """ from __future__ import division, absolute_import, print_function import sys import copy import pickle from pickle import dump, dumps import numpy.core.multiarray as multiarray import numpy.core.umath as um from numpy.core.numeric import array from . import functions __all__ = ['NewAxis', 'UFuncType', 'UfuncType', 'ArrayType', 'arraytype', 'LittleEndian', 'arrayrange', 'matrixmultiply', 'array_constructor', 'pickle_array', 'DumpArray', 'LoadArray', 'multiarray', # from cPickle 'dump', 'dumps', 'load', 'loads', 'Unpickler', 'Pickler' ] mu = multiarray #Use this to add a new axis to an array #compatibility only NewAxis = None #deprecated UFuncType = type(um.sin) UfuncType = type(um.sin) ArrayType = mu.ndarray arraytype = mu.ndarray LittleEndian = (sys.byteorder == 'little') from numpy import deprecate # backward compatibility arrayrange = deprecate(functions.arange, 'arrayrange', 'arange') # deprecated names matrixmultiply = deprecate(mu.dot, 'matrixmultiply', 'dot') def DumpArray(m, fp): m.dump(fp) def LoadArray(fp): return pickle.load(fp) def array_constructor(shape, typecode, thestr, Endian=LittleEndian): if typecode == "O": x = array(thestr, "O") else: x = mu.fromstring(thestr, typecode) x.shape = shape if LittleEndian != Endian: return x.byteswap(True) else: return x def pickle_array(a): if a.dtype.hasobject: return (array_constructor, a.shape, a.dtype.char, a.tolist(), LittleEndian) else: return (array_constructor, (a.shape, a.dtype.char, a.tostring(), LittleEndian)) def loads(astr): arr = pickle.loads(astr.replace('Numeric', 'numpy.oldnumeric')) return arr def load(fp): return loads(fp.read()) def _LoadArray(fp): from . import typeconv ln = fp.readline().split() if ln[0][0] == 'A': ln[0] = ln[0][1:] typecode = ln[0][0] endian = ln[0][1] itemsize = int(ln[0][2:]) shape = [int(x) for x in ln[1:]] sz = itemsize for val in shape: sz *= val dstr = fp.read(sz) m = mu.fromstring(dstr, typeconv.convtypecode(typecode)) m.shape = shape if (LittleEndian and endian == 'B') or (not LittleEndian and endian == 'L'): return m.byteswap(True) else: return m if sys.version_info[0] >= 3: class Unpickler(pickle.Unpickler): # XXX: should we implement this? It's not completely straightforward # to do. def __init__(self, *a, **kw): raise NotImplementedError( "numpy.oldnumeric.Unpickler is not supported on Python 3") else: class Unpickler(pickle.Unpickler): def load_array(self): self.stack.append(_LoadArray(self)) dispatch = copy.copy(pickle.Unpickler.dispatch) dispatch['A'] = load_array class Pickler(pickle.Pickler): def __init__(self, *args, **kwds): raise NotImplementedError("Don't pickle new arrays with this") def save_array(self, object): raise NotImplementedError("Don't pickle new arrays with this") numpy-1.8.2/numpy/oldnumeric/random_array.py0000664000175100017510000002650312370216243022373 0ustar vagrantvagrant00000000000000"""Backward compatible module for RandomArray """ from __future__ import division, absolute_import, print_function __all__ = ['ArgumentError', 'F', 'beta', 'binomial', 'chi_square', 'exponential', 'gamma', 'get_seed', 'mean_var_test', 'multinomial', 'multivariate_normal', 'negative_binomial', 'noncentral_F', 'noncentral_chi_square', 'normal', 'permutation', 'poisson', 'randint', 'random', 'random_integers', 'seed', 'standard_normal', 'uniform'] ArgumentError = ValueError import numpy.random.mtrand as mt import numpy as np def seed(x=0, y=0): if (x == 0 or y == 0): mt.seed() else: mt.seed((x, y)) def get_seed(): raise NotImplementedError( "If you want to save the state of the random number generator.\n" "Then you should use obj = numpy.random.get_state() followed by.\n" "numpy.random.set_state(obj).") def random(shape=[]): "random(n) or random([n, m, ...]) returns array of random numbers" if shape == []: shape = None return mt.random_sample(shape) def uniform(minimum, maximum, shape=[]): """uniform(minimum, maximum, shape=[]) returns array of given shape of random reals in given range""" if shape == []: shape = None return mt.uniform(minimum, maximum, shape) def randint(minimum, maximum=None, shape=[]): """randint(min, max, shape=[]) = random integers >=min, < max If max not given, random integers >= 0, = 0.6: raise SystemExit("uniform returned out of desired range") print("randint(1, 10, shape=[50])") print(randint(1, 10, shape=[50])) print("permutation(10)", permutation(10)) print("randint(3,9)", randint(3, 9)) print("random_integers(10, shape=[20])") print(random_integers(10, shape=[20])) s = 3.0 x = normal(2.0, s, [10, 1000]) if len(x.shape) != 2 or x.shape[0] != 10 or x.shape[1] != 1000: raise SystemExit("standard_normal returned wrong shape") x.shape = (10000,) mean_var_test(x, "normally distributed numbers with mean 2 and variance %f"%(s**2,), 2, s**2, 0) x = exponential(3, 10000) mean_var_test(x, "random numbers exponentially distributed with mean %f"%(s,), s, s**2, 2) x = multivariate_normal(np.array([10, 20]), np.array(([1, 2], [2, 4]))) print("\nA multivariate normal", x) if x.shape != (2,): raise SystemExit("multivariate_normal returned wrong shape") x = multivariate_normal(np.array([10, 20]), np.array([[1, 2], [2, 4]]), [4, 3]) print("A 4x3x2 array containing multivariate normals") print(x) if x.shape != (4, 3, 2): raise SystemExit("multivariate_normal returned wrong shape") x = multivariate_normal(np.array([-100, 0, 100]), np.array([[3, 2, 1], [2, 2, 1], [1, 1, 1]]), 10000) x_mean = np.sum(x, axis=0)/10000. print("Average of 10000 multivariate normals with mean [-100,0,100]") print(x_mean) x_minus_mean = x - x_mean print("Estimated covariance of 10000 multivariate normals with covariance [[3,2,1],[2,2,1],[1,1,1]]") print(np.dot(np.transpose(x_minus_mean), x_minus_mean)/9999.) x = beta(5.0, 10.0, 10000) mean_var_test(x, "beta(5.,10.) random numbers", 0.333, 0.014) x = gamma(.01, 2., 10000) mean_var_test(x, "gamma(.01,2.) random numbers", 2*100, 2*100*100) x = chi_square(11., 10000) mean_var_test(x, "chi squared random numbers with 11 degrees of freedom", 11, 22, 2*np.sqrt(2./11.)) x = F(5., 10., 10000) mean_var_test(x, "F random numbers with 5 and 10 degrees of freedom", 1.25, 1.35) x = poisson(50., 10000) mean_var_test(x, "poisson random numbers with mean 50", 50, 50, 0.14) print("\nEach element is the result of 16 binomial trials with probability 0.5:") print(binomial(16, 0.5, 16)) print("\nEach element is the result of 16 negative binomial trials with probability 0.5:") print(negative_binomial(16, 0.5, [16,])) print("\nEach row is the result of 16 multinomial trials with probabilities [0.1, 0.5, 0.1 0.3]:") x = multinomial(16, [0.1, 0.5, 0.1], 8) print(x) print("Mean = ", np.sum(x, axis=0)/8.) if __name__ == '__main__': test() numpy-1.8.2/numpy/oldnumeric/arrayfns.py0000664000175100017510000000505512370216243021541 0ustar vagrantvagrant00000000000000"""Backward compatible with arrayfns from Numeric. """ from __future__ import division, absolute_import, print_function __all__ = ['array_set', 'construct3', 'digitize', 'error', 'find_mask', 'histogram', 'index_sort', 'interp', 'nz', 'reverse', 'span', 'to_corners', 'zmin_zmax'] import numpy as np from numpy import asarray class error(Exception): pass def array_set(vals1, indices, vals2): indices = asarray(indices) if indices.ndim != 1: raise ValueError("index array must be 1-d") if not isinstance(vals1, np.ndarray): raise TypeError("vals1 must be an ndarray") vals1 = asarray(vals1) vals2 = asarray(vals2) if vals1.ndim != vals2.ndim or vals1.ndim < 1: raise error("vals1 and vals2 must have same number of dimensions (>=1)") vals1[indices] = vals2 from numpy import digitize from numpy import bincount as histogram def index_sort(arr): return asarray(arr).argsort(kind='heap') def interp(y, x, z, typ=None): """y(z) interpolated by treating y(x) as piecewise function """ res = np.interp(z, x, y) if typ is None or typ == 'd': return res if typ == 'f': return res.astype('f') raise error("incompatible typecode") def nz(x): x = asarray(x, dtype=np.ubyte) if x.ndim != 1: raise TypeError("intput must have 1 dimension.") indxs = np.flatnonzero(x != 0) return indxs[-1].item()+1 def reverse(x, n): x = asarray(x, dtype='d') if x.ndim != 2: raise ValueError("input must be 2-d") y = np.empty_like(x) if n == 0: y[...] = x[::-1,:] elif n == 1: y[...] = x[:, ::-1] return y def span(lo, hi, num, d2=0): x = np.linspace(lo, hi, num) if d2 <= 0: return x else: ret = np.empty((d2, num), x.dtype) ret[...] = x return ret def zmin_zmax(z, ireg): z = asarray(z, dtype=float) ireg = asarray(ireg, dtype=int) if z.shape != ireg.shape or z.ndim != 2: raise ValueError("z and ireg must be the same shape and 2-d") ix, iy = np.nonzero(ireg) # Now, add more indices x1m = ix - 1 y1m = iy-1 i1 = x1m>=0 i2 = y1m>=0 i3 = i1 & i2 nix = np.r_[ix, x1m[i1], x1m[i1], ix[i2] ] niy = np.r_[iy, iy[i1], y1m[i3], y1m[i2]] # remove any negative indices zres = z[nix, niy] return zres.min().item(), zres.max().item() def find_mask(fs, node_edges): raise NotImplementedError def to_corners(arr, nv, nvsum): raise NotImplementedError def construct3(mask, itype): raise NotImplementedError numpy-1.8.2/numpy/oldnumeric/linear_algebra.py0000664000175100017510000000430212370216243022635 0ustar vagrantvagrant00000000000000"""Backward compatible with LinearAlgebra from Numeric This module is a lite version of the linalg.py module in SciPy which contains high-level Python interface to the LAPACK library. The lite version only accesses the following LAPACK functions: dgesv, zgesv, dgeev, zgeev, dgesdd, zgesdd, dgelsd, zgelsd, dsyevd, zheevd, dgetrf, dpotrf. """ from __future__ import division, absolute_import, print_function __all__ = ['LinAlgError', 'solve_linear_equations', 'inverse', 'cholesky_decomposition', 'eigenvalues', 'Heigenvalues', 'generalized_inverse', 'determinant', 'singular_value_decomposition', 'eigenvectors', 'Heigenvectors', 'linear_least_squares' ] from numpy.core import transpose import numpy.linalg as linalg # Linear equations LinAlgError = linalg.LinAlgError def solve_linear_equations(a, b): return linalg.solve(a, b) # Matrix inversion def inverse(a): return linalg.inv(a) # Cholesky decomposition def cholesky_decomposition(a): return linalg.cholesky(a) # Eigenvalues def eigenvalues(a): return linalg.eigvals(a) def Heigenvalues(a, UPLO='L'): return linalg.eigvalsh(a, UPLO) # Eigenvectors def eigenvectors(A): w, v = linalg.eig(A) return w, transpose(v) def Heigenvectors(A): w, v = linalg.eigh(A) return w, transpose(v) # Generalized inverse def generalized_inverse(a, rcond = 1.e-10): return linalg.pinv(a, rcond) # Determinant def determinant(a): return linalg.det(a) # Linear Least Squares def linear_least_squares(a, b, rcond=1.e-10): """returns x,resids,rank,s where x minimizes 2-norm(|b - Ax|) resids is the sum square residuals rank is the rank of A s is the rank of the singular values of A in descending order If b is a matrix then x is also a matrix with corresponding columns. If the rank of A is less than the number of columns of A or greater than the number of rows, then residuals will be returned as an empty array otherwise resids = sum((b-dot(A,x)**2). Singular values less than s[0]*rcond are treated as zero. """ return linalg.lstsq(a, b, rcond) def singular_value_decomposition(A, full_matrices=0): return linalg.svd(A, full_matrices) numpy-1.8.2/numpy/oldnumeric/functions.py0000664000175100017510000000720412370216243021722 0ustar vagrantvagrant00000000000000"""Functions that should behave the same as Numeric and need changing """ from __future__ import division, absolute_import, print_function import numpy as np import numpy.core.multiarray as mu import numpy.core.numeric as nn from .typeconv import convtypecode, convtypecode2 __all__ = ['take', 'repeat', 'sum', 'product', 'sometrue', 'alltrue', 'cumsum', 'cumproduct', 'compress', 'fromfunction', 'ones', 'empty', 'identity', 'zeros', 'array', 'asarray', 'nonzero', 'reshape', 'arange', 'fromstring', 'ravel', 'trace', 'indices', 'where', 'sarray', 'cross_product', 'argmax', 'argmin', 'average'] def take(a, indicies, axis=0): return np.take(a, indicies, axis) def repeat(a, repeats, axis=0): return np.repeat(a, repeats, axis) def sum(x, axis=0): return np.sum(x, axis) def product(x, axis=0): return np.product(x, axis) def sometrue(x, axis=0): return np.sometrue(x, axis) def alltrue(x, axis=0): return np.alltrue(x, axis) def cumsum(x, axis=0): return np.cumsum(x, axis) def cumproduct(x, axis=0): return np.cumproduct(x, axis) def argmax(x, axis=-1): return np.argmax(x, axis) def argmin(x, axis=-1): return np.argmin(x, axis) def compress(condition, m, axis=-1): return np.compress(condition, m, axis) def fromfunction(args, dimensions): return np.fromfunction(args, dimensions, dtype=int) def ones(shape, typecode='l', savespace=0, dtype=None): """ones(shape, dtype=int) returns an array of the given dimensions which is initialized to all ones. """ dtype = convtypecode(typecode, dtype) a = mu.empty(shape, dtype) a.fill(1) return a def zeros(shape, typecode='l', savespace=0, dtype=None): """zeros(shape, dtype=int) returns an array of the given dimensions which is initialized to all zeros """ dtype = convtypecode(typecode, dtype) return mu.zeros(shape, dtype) def identity(n,typecode='l', dtype=None): """identity(n) returns the identity 2-d array of shape n x n. """ dtype = convtypecode(typecode, dtype) return nn.identity(n, dtype) def empty(shape, typecode='l', dtype=None): dtype = convtypecode(typecode, dtype) return mu.empty(shape, dtype) def array(sequence, typecode=None, copy=1, savespace=0, dtype=None): dtype = convtypecode2(typecode, dtype) return mu.array(sequence, dtype, copy=copy) def sarray(a, typecode=None, copy=False, dtype=None): dtype = convtypecode2(typecode, dtype) return mu.array(a, dtype, copy) def asarray(a, typecode=None, dtype=None): dtype = convtypecode2(typecode, dtype) return mu.array(a, dtype, copy=0) def nonzero(a): res = np.nonzero(a) if len(res) == 1: return res[0] else: raise ValueError("Input argument must be 1d") def reshape(a, shape): return np.reshape(a, shape) def arange(start, stop=None, step=1, typecode=None, dtype=None): dtype = convtypecode2(typecode, dtype) return mu.arange(start, stop, step, dtype) def fromstring(string, typecode='l', count=-1, dtype=None): dtype = convtypecode(typecode, dtype) return mu.fromstring(string, dtype, count=count) def ravel(m): return np.ravel(m) def trace(a, offset=0, axis1=0, axis2=1): return np.trace(a, offset=0, axis1=0, axis2=1) def indices(dimensions, typecode=None, dtype=None): dtype = convtypecode(typecode, dtype) return np.indices(dimensions, dtype) def where(condition, x, y): return np.where(condition, x, y) def cross_product(a, b, axis1=-1, axis2=-1): return np.cross(a, b, axis1, axis2) def average(a, axis=0, weights=None, returned=False): return np.average(a, axis, weights, returned) numpy-1.8.2/numpy/oldnumeric/fix_default_axis.py0000664000175100017510000001765712370216243023245 0ustar vagrantvagrant00000000000000""" This module adds the default axis argument to code which did not specify it for the functions where the default was changed in NumPy. The functions changed are add -1 ( all second argument) ====== nansum nanmax nanmin nanargmax nanargmin argmax argmin compress 3 add 0 ====== take 3 repeat 3 sum # might cause problems with builtin. product sometrue alltrue cumsum cumproduct average ptp cumprod prod std mean """ from __future__ import division, absolute_import, print_function __all__ = ['convertfile', 'convertall', 'converttree'] import sys import os import re import glob _args3 = ['compress', 'take', 'repeat'] _funcm1 = ['nansum', 'nanmax', 'nanmin', 'nanargmax', 'nanargmin', 'argmax', 'argmin', 'compress'] _func0 = ['take', 'repeat', 'sum', 'product', 'sometrue', 'alltrue', 'cumsum', 'cumproduct', 'average', 'ptp', 'cumprod', 'prod', 'std', 'mean'] _all = _func0 + _funcm1 func_re = {} for name in _all: _astr = r"""%s\s*[(]"""%name func_re[name] = re.compile(_astr) import string disallowed = '_' + string.uppercase + string.lowercase + string.digits def _add_axis(fstr, name, repl): alter = 0 if name in _args3: allowed_comma = 1 else: allowed_comma = 0 newcode = "" last = 0 for obj in func_re[name].finditer(fstr): nochange = 0 start, end = obj.span() if fstr[start-1] in disallowed: continue if fstr[start-1] == '.' \ and fstr[start-6:start-1] != 'numpy' \ and fstr[start-2:start-1] != 'N' \ and fstr[start-9:start-1] != 'numarray' \ and fstr[start-8:start-1] != 'numerix' \ and fstr[start-8:start-1] != 'Numeric': continue if fstr[start-1] in ['\t', ' ']: k = start-2 while fstr[k] in ['\t', ' ']: k -= 1 if fstr[k-2:k+1] == 'def' or \ fstr[k-4:k+1] == 'class': continue k = end stack = 1 ncommas = 0 N = len(fstr) while stack: if k>=N: nochange =1 break if fstr[k] == ')': stack -= 1 elif fstr[k] == '(': stack += 1 elif stack == 1 and fstr[k] == ',': ncommas += 1 if ncommas > allowed_comma: nochange = 1 break k += 1 if nochange: continue alter += 1 newcode = "%s%s,%s)" % (newcode, fstr[last:k-1], repl) last = k if not alter: newcode = fstr else: newcode = "%s%s" % (newcode, fstr[last:]) return newcode, alter def _import_change(fstr, names): # Four possibilities # 1.) import numpy with subsequent use of numpy. # change this to import numpy.oldnumeric as numpy # 2.) import numpy as XXXX with subsequent use of # XXXX. ==> import numpy.oldnumeric as XXXX # 3.) from numpy import * # with subsequent use of one of the names # 4.) from numpy import ..., , ... (could span multiple # lines. ==> remove all names from list and # add from numpy.oldnumeric import num = 0 # case 1 importstr = "import numpy" ind = fstr.find(importstr) if (ind > 0): found = 0 for name in names: ind2 = fstr.find("numpy.%s" % name, ind) if (ind2 > 0): found = 1 break if found: fstr = "%s%s%s" % (fstr[:ind], "import numpy.oldnumeric as numpy", fstr[ind+len(importstr):]) num += 1 # case 2 importre = re.compile("""import numpy as ([A-Za-z0-9_]+)""") modules = importre.findall(fstr) if len(modules) > 0: for module in modules: found = 0 for name in names: ind2 = fstr.find("%s.%s" % (module, name)) if (ind2 > 0): found = 1 break if found: importstr = "import numpy as %s" % module ind = fstr.find(importstr) fstr = "%s%s%s" % (fstr[:ind], "import numpy.oldnumeric as %s" % module, fstr[ind+len(importstr):]) num += 1 # case 3 importstr = "from numpy import *" ind = fstr.find(importstr) if (ind > 0): found = 0 for name in names: ind2 = fstr.find(name, ind) if (ind2 > 0) and fstr[ind2-1] not in disallowed: found = 1 break if found: fstr = "%s%s%s" % (fstr[:ind], "from numpy.oldnumeric import *", fstr[ind+len(importstr):]) num += 1 # case 4 ind = 0 importstr = "from numpy import" N = len(importstr) while True: ind = fstr.find(importstr, ind) if (ind < 0): break ind += N ptr = ind+1 stack = 1 while stack: if fstr[ptr] == '\\': stack += 1 elif fstr[ptr] == '\n': stack -= 1 ptr += 1 substr = fstr[ind:ptr] found = 0 substr = substr.replace('\n', ' ') substr = substr.replace('\\', '') importnames = [x.strip() for x in substr.split(',')] # determine if any of names are in importnames addnames = [] for name in names: if name in importnames: importnames.remove(name) addnames.append(name) if len(addnames) > 0: fstr = "%s%s\n%s\n%s" % \ (fstr[:ind], "from numpy import %s" % \ ", ".join(importnames), "from numpy.oldnumeric import %s" % \ ", ".join(addnames), fstr[ptr:]) num += 1 return fstr, num def add_axis(fstr, import_change=False): total = 0 if not import_change: for name in _funcm1: fstr, num = _add_axis(fstr, name, 'axis=-1') total += num for name in _func0: fstr, num = _add_axis(fstr, name, 'axis=0') total += num return fstr, total else: fstr, num = _import_change(fstr, _funcm1+_func0) return fstr, num def makenewfile(name, filestr): fid = file(name, 'w') fid.write(filestr) fid.close() def getfile(name): fid = file(name) filestr = fid.read() fid.close() return filestr def copyfile(name, fstr): base, ext = os.path.splitext(name) makenewfile(base+'.orig', fstr) return def convertfile(filename, import_change=False): """Convert the filename given from using Numeric to using NumPy Copies the file to filename.orig and then over-writes the file with the updated code """ filestr = getfile(filename) newstr, total = add_axis(filestr, import_change) if total > 0: print("Changing ", filename) copyfile(filename, filestr) makenewfile(filename, newstr) sys.stdout.flush() def fromargs(args): filename = args[1] convertfile(filename) def convertall(direc=os.path.curdir, import_change=False): """Convert all .py files in the directory given For each file, a backup of .py is made as .py.orig. A new file named .py is then written with the updated code. """ files = glob.glob(os.path.join(direc, '*.py')) for afile in files: convertfile(afile, import_change) def _func(arg, dirname, fnames): convertall(dirname, import_change=arg) def converttree(direc=os.path.curdir, import_change=False): """Convert all .py files in the tree given """ os.path.walk(direc, _func, import_change) if __name__ == '__main__': fromargs(sys.argv) numpy-1.8.2/numpy/oldnumeric/setup.py0000664000175100017510000000060112370216243021044 0ustar vagrantvagrant00000000000000from __future__ import division, print_function def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('oldnumeric', parent_package, top_path) config.add_data_dir('tests') return config if __name__ == '__main__': from numpy.distutils.core import setup setup(configuration=configuration) numpy-1.8.2/numpy/oldnumeric/user_array.py0000664000175100017510000000036612370216243022070 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function from numpy.oldnumeric import * from numpy.lib.user_array import container as UserArray import numpy.oldnumeric as nold __all__ = nold.__all__[:] __all__ += ['UserArray'] del nold numpy-1.8.2/numpy/oldnumeric/tests/0000775000175100017510000000000012371375430020504 5ustar vagrantvagrant00000000000000numpy-1.8.2/numpy/oldnumeric/tests/test_oldnumeric.py0000664000175100017510000000640112370216243024252 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function import unittest from numpy.testing import * from numpy import array from numpy.oldnumeric import * from numpy.core.numeric import float32, float64, complex64, complex128, int8, \ int16, int32, int64, uint, uint8, uint16, uint32, uint64 class test_oldtypes(unittest.TestCase): def test_oldtypes(self, level=1): a1 = array([0, 1, 0], Float) a2 = array([0, 1, 0], float) assert_array_equal(a1, a2) a1 = array([0, 1, 0], Float8) a2 = array([0, 1, 0], float) assert_array_equal(a1, a2) a1 = array([0, 1, 0], Float16) a2 = array([0, 1, 0], float) assert_array_equal(a1, a2) a1 = array([0, 1, 0], Float32) a2 = array([0, 1, 0], float32) assert_array_equal(a1, a2) a1 = array([0, 1, 0], Float64) a2 = array([0, 1, 0], float64) assert_array_equal(a1, a2) a1 = array([0, 1, 0], Complex) a2 = array([0, 1, 0], complex) assert_array_equal(a1, a2) a1 = array([0, 1, 0], Complex8) a2 = array([0, 1, 0], complex) assert_array_equal(a1, a2) a1 = array([0, 1, 0], Complex16) a2 = array([0, 1, 0], complex) assert_array_equal(a1, a2) a1 = array([0, 1, 0], Complex32) a2 = array([0, 1, 0], complex64) assert_array_equal(a1, a2) a1 = array([0, 1, 0], Complex64) a2 = array([0, 1, 0], complex128) assert_array_equal(a1, a2) a1 = array([0, 1, 0], Int) a2 = array([0, 1, 0], int) assert_array_equal(a1, a2) a1 = array([0, 1, 0], Int8) a2 = array([0, 1, 0], int8) assert_array_equal(a1, a2) a1 = array([0, 1, 0], Int16) a2 = array([0, 1, 0], int16) assert_array_equal(a1, a2) a1 = array([0, 1, 0], Int32) a2 = array([0, 1, 0], int32) assert_array_equal(a1, a2) try: a1 = array([0, 1, 0], Int64) a2 = array([0, 1, 0], int64) assert_array_equal(a1, a2) except NameError: # Not all systems have 64-bit integers. pass a1 = array([0, 1, 0], UnsignedInt) a2 = array([0, 1, 0], UnsignedInteger) a3 = array([0, 1, 0], uint) assert_array_equal(a1, a3) assert_array_equal(a2, a3) a1 = array([0, 1, 0], UInt8) a2 = array([0, 1, 0], UnsignedInt8) a3 = array([0, 1, 0], uint8) assert_array_equal(a1, a3) assert_array_equal(a2, a3) a1 = array([0, 1, 0], UInt16) a2 = array([0, 1, 0], UnsignedInt16) a3 = array([0, 1, 0], uint16) assert_array_equal(a1, a3) assert_array_equal(a2, a3) a1 = array([0, 1, 0], UInt32) a2 = array([0, 1, 0], UnsignedInt32) a3 = array([0, 1, 0], uint32) assert_array_equal(a1, a3) assert_array_equal(a2, a3) try: a1 = array([0, 1, 0], UInt64) a2 = array([0, 1, 0], UnsignedInt64) a3 = array([0, 1, 0], uint64) assert_array_equal(a1, a3) assert_array_equal(a2, a3) except NameError: # Not all systems have 64-bit integers. pass if __name__ == "__main__": import nose nose.main() numpy-1.8.2/numpy/oldnumeric/tests/test_regression.py0000664000175100017510000000103212370216243024264 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function from numpy.testing import * rlevel = 1 class TestRegression(TestCase): def test_numeric_random(self, level=rlevel): """Ticket #552""" from numpy.oldnumeric.random_array import randint randint(0, 50, [2, 3]) def test_mlab_import(self): """gh-3803""" try: from numpy.oldnumeric import mlab import numpy.oldnumeric.mlab as mlab except: raise AssertionError("mlab import failed") numpy-1.8.2/numpy/oldnumeric/fft.py0000664000175100017510000000164612370216243020475 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function __all__ = ['fft', 'fft2d', 'fftnd', 'hermite_fft', 'inverse_fft', 'inverse_fft2d', 'inverse_fftnd', 'inverse_hermite_fft', 'inverse_real_fft', 'inverse_real_fft2d', 'inverse_real_fftnd', 'real_fft', 'real_fft2d', 'real_fftnd'] from numpy.fft import fft from numpy.fft import fft2 as fft2d from numpy.fft import fftn as fftnd from numpy.fft import hfft as hermite_fft from numpy.fft import ifft as inverse_fft from numpy.fft import ifft2 as inverse_fft2d from numpy.fft import ifftn as inverse_fftnd from numpy.fft import ihfft as inverse_hermite_fft from numpy.fft import irfft as inverse_real_fft from numpy.fft import irfft2 as inverse_real_fft2d from numpy.fft import irfftn as inverse_real_fftnd from numpy.fft import rfft as real_fft from numpy.fft import rfft2 as real_fft2d from numpy.fft import rfftn as real_fftnd numpy-1.8.2/numpy/oldnumeric/rng_stats.py0000664000175100017510000000260112370216243021712 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function __all__ = ['average', 'histogram', 'standardDeviation', 'variance'] import numpy.oldnumeric as Numeric def average(data): data = Numeric.array(data) return Numeric.add.reduce(data)/len(data) def variance(data): data = Numeric.array(data) return Numeric.add.reduce((data-average(data, axis=0))**2)/(len(data)-1) def standardDeviation(data): data = Numeric.array(data) return Numeric.sqrt(variance(data)) def histogram(data, nbins, range = None): data = Numeric.array(data, Numeric.Float) if range is None: min = Numeric.minimum.reduce(data) max = Numeric.maximum.reduce(data) else: min, max = range data = Numeric.repeat(data, Numeric.logical_and(Numeric.less_equal(data, max), Numeric.greater_equal(data, min)), axis=0) bin_width = (max-min)/nbins data = Numeric.floor((data - min)/bin_width).astype(Numeric.Int) histo = Numeric.add.reduce(Numeric.equal( Numeric.arange(nbins)[:, Numeric.NewAxis], data), -1) histo[-1] = histo[-1] + Numeric.add.reduce(Numeric.equal(nbins, data)) bins = min + bin_width*(Numeric.arange(nbins)+0.5) return Numeric.transpose(Numeric.array([bins, histo])) numpy-1.8.2/numpy/oldnumeric/alter_code1.py0000664000175100017510000002061012370216243022070 0ustar vagrantvagrant00000000000000""" This module converts code written for Numeric to run with numpy Makes the following changes: * Changes import statements (warns of use of from Numeric import *) * Changes import statements (using numerix) ... * Makes search and replace changes to: - .typecode() - .iscontiguous() - .byteswapped() - .itemsize() - .toscalar() * Converts .flat to .ravel() except for .flat = xxx or .flat[xxx] * Replace xxx.spacesaver() with True * Convert xx.savespace(?) to pass + ## xx.savespace(?) * Converts uses of 'b' to 'B' in the typecode-position of functions: eye, tri (in position 4) ones, zeros, identity, empty, array, asarray, arange, fromstring, indices, array_constructor (in position 2) and methods: astype --- only argument -- converts uses of '1', 's', 'w', and 'u' to -- 'b', 'h', 'H', and 'I' * Converts uses of type(...) is isinstance(..., ) """ from __future__ import division, absolute_import, print_function __all__ = ['convertfile', 'convertall', 'converttree', 'convertsrc'] import sys import os import re import glob _func4 = ['eye', 'tri'] _meth1 = ['astype'] _func2 = ['ones', 'zeros', 'identity', 'fromstring', 'indices', 'empty', 'array', 'asarray', 'arange', 'array_constructor'] _chars = {'1':'b','s':'h','w':'H','u':'I'} func_re = {} meth_re = {} for name in _func2: _astr = r"""(%s\s*[(][^,]*?[,][^'"]*?['"])b(['"][^)]*?[)])"""%name func_re[name] = re.compile(_astr, re.DOTALL) for name in _func4: _astr = r"""(%s\s*[(][^,]*?[,][^,]*?[,][^,]*?[,][^'"]*?['"])b(['"][^)]*?[)])"""%name func_re[name] = re.compile(_astr, re.DOTALL) for name in _meth1: _astr = r"""(.%s\s*[(][^'"]*?['"])b(['"][^)]*?[)])"""%name func_re[name] = re.compile(_astr, re.DOTALL) for char in _chars.keys(): _astr = r"""(.astype\s*[(][^'"]*?['"])%s(['"][^)]*?[)])"""%char meth_re[char] = re.compile(_astr, re.DOTALL) def fixtypechars(fstr): for name in _func2 + _func4 + _meth1: fstr = func_re[name].sub('\\1B\\2', fstr) for char in _chars.keys(): fstr = meth_re[char].sub('\\1%s\\2'%_chars[char], fstr) return fstr flatindex_re = re.compile('([.]flat(\s*?[[=]))') def changeimports(fstr, name, newname): importstr = 'import %s' % name importasstr = 'import %s as ' % name fromstr = 'from %s import ' % name fromall=0 fstr = re.sub(r'(import\s+[^,\n\r]+,\s*)(%s)' % name, "\\1%s as %s" % (newname, name), fstr) fstr = fstr.replace(importasstr, 'import %s as ' % newname) fstr = fstr.replace(importstr, 'import %s as %s' % (newname, name)) ind = 0 Nlen = len(fromstr) Nlen2 = len("from %s import " % newname) while True: found = fstr.find(fromstr, ind) if (found < 0): break ind = found + Nlen if fstr[ind] == '*': continue fstr = "%sfrom %s import %s" % (fstr[:found], newname, fstr[ind:]) ind += Nlen2 - Nlen return fstr, fromall istest_re = {} _types = ['float', 'int', 'complex', 'ArrayType', 'FloatType', 'IntType', 'ComplexType'] for name in _types: _astr = r'type\s*[(]([^)]*)[)]\s+(?:is|==)\s+(.*?%s)'%name istest_re[name] = re.compile(_astr) def fixistesting(astr): for name in _types: astr = istest_re[name].sub('isinstance(\\1, \\2)', astr) return astr def replaceattr(astr): astr = astr.replace(".typecode()", ".dtype.char") astr = astr.replace(".iscontiguous()", ".flags.contiguous") astr = astr.replace(".byteswapped()", ".byteswap()") astr = astr.replace(".toscalar()", ".item()") astr = astr.replace(".itemsize()", ".itemsize") # preserve uses of flat that should be o.k. tmpstr = flatindex_re.sub(r"@@@@\2", astr) # replace other uses of flat tmpstr = tmpstr.replace(".flat", ".ravel()") # put back .flat where it was valid astr = tmpstr.replace("@@@@", ".flat") return astr svspc2 = re.compile(r'([^,(\s]+[.]spacesaver[(][)])') svspc3 = re.compile(r'(\S+[.]savespace[(].*[)])') #shpe = re.compile(r'(\S+\s*)[.]shape\s*=[^=]\s*(.+)') def replaceother(astr): astr = svspc2.sub('True', astr) astr = svspc3.sub(r'pass ## \1', astr) #astr = shpe.sub('\\1=\\1.reshape(\\2)', astr) return astr import datetime def fromstr(filestr): savestr = filestr[:] filestr = fixtypechars(filestr) filestr = fixistesting(filestr) filestr, fromall1 = changeimports(filestr, 'Numeric', 'numpy.oldnumeric') filestr, fromall1 = changeimports(filestr, 'multiarray', 'numpy.oldnumeric') filestr, fromall1 = changeimports(filestr, 'umath', 'numpy.oldnumeric') filestr, fromall1 = changeimports(filestr, 'Precision', 'numpy.oldnumeric.precision') filestr, fromall1 = changeimports(filestr, 'UserArray', 'numpy.oldnumeric.user_array') filestr, fromall1 = changeimports(filestr, 'ArrayPrinter', 'numpy.oldnumeric.array_printer') filestr, fromall2 = changeimports(filestr, 'numerix', 'numpy.oldnumeric') filestr, fromall3 = changeimports(filestr, 'scipy_base', 'numpy.oldnumeric') filestr, fromall3 = changeimports(filestr, 'Matrix', 'numpy.oldnumeric.matrix') filestr, fromall3 = changeimports(filestr, 'MLab', 'numpy.oldnumeric.mlab') filestr, fromall3 = changeimports(filestr, 'LinearAlgebra', 'numpy.oldnumeric.linear_algebra') filestr, fromall3 = changeimports(filestr, 'RNG', 'numpy.oldnumeric.rng') filestr, fromall3 = changeimports(filestr, 'RNG.Statistics', 'numpy.oldnumeric.rng_stats') filestr, fromall3 = changeimports(filestr, 'RandomArray', 'numpy.oldnumeric.random_array') filestr, fromall3 = changeimports(filestr, 'FFT', 'numpy.oldnumeric.fft') filestr, fromall3 = changeimports(filestr, 'MA', 'numpy.oldnumeric.ma') fromall = fromall1 or fromall2 or fromall3 filestr = replaceattr(filestr) filestr = replaceother(filestr) if savestr != filestr: today = datetime.date.today().strftime('%b %d, %Y') name = os.path.split(sys.argv[0])[-1] filestr = '## Automatically adapted for '\ 'numpy.oldnumeric %s by %s\n\n%s' % (today, name, filestr) return filestr, 1 return filestr, 0 def makenewfile(name, filestr): fid = file(name, 'w') fid.write(filestr) fid.close() def convertfile(filename, orig=1): """Convert the filename given from using Numeric to using NumPy Copies the file to filename.orig and then over-writes the file with the updated code """ fid = open(filename) filestr = fid.read() fid.close() filestr, changed = fromstr(filestr) if changed: if orig: base, ext = os.path.splitext(filename) os.rename(filename, base+".orig") else: os.remove(filename) makenewfile(filename, filestr) def fromargs(args): filename = args[1] converttree(filename) def convertall(direc=os.path.curdir, orig=1): """Convert all .py files to use numpy.oldnumeric (from Numeric) in the directory given For each changed file, a backup of .py is made as .py.orig. A new file named .py is then written with the updated code. """ files = glob.glob(os.path.join(direc, '*.py')) for afile in files: if afile[-8:] == 'setup.py': continue # skip these convertfile(afile, orig) header_re = re.compile(r'(Numeric/arrayobject.h)') def convertsrc(direc=os.path.curdir, ext=None, orig=1): """Replace Numeric/arrayobject.h with numpy/oldnumeric.h in all files in the directory with extension give by list ext (if ext is None, then all files are replaced).""" if ext is None: files = glob.glob(os.path.join(direc, '*')) else: files = [] for aext in ext: files.extend(glob.glob(os.path.join(direc, "*.%s" % aext))) for afile in files: fid = open(afile) fstr = fid.read() fid.close() fstr, n = header_re.subn(r'numpy/oldnumeric.h', fstr) if n > 0: if orig: base, ext = os.path.splitext(afile) os.rename(afile, base+".orig") else: os.remove(afile) makenewfile(afile, fstr) def _func(arg, dirname, fnames): convertall(dirname, orig=0) convertsrc(dirname, ext=['h', 'c'], orig=0) def converttree(direc=os.path.curdir): """Convert all .py files and source code files in the tree given """ os.path.walk(direc, _func, None) if __name__ == '__main__': fromargs(sys.argv) numpy-1.8.2/numpy/oldnumeric/ufuncs.py0000664000175100017510000000242112370216243021211 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function __all__ = ['less', 'cosh', 'arcsinh', 'add', 'ceil', 'arctan2', 'floor_divide', 'fmod', 'hypot', 'logical_and', 'power', 'sinh', 'remainder', 'cos', 'equal', 'arccos', 'less_equal', 'divide', 'bitwise_or', 'bitwise_and', 'logical_xor', 'log', 'subtract', 'invert', 'negative', 'log10', 'arcsin', 'arctanh', 'logical_not', 'not_equal', 'tanh', 'true_divide', 'maximum', 'arccosh', 'logical_or', 'minimum', 'conjugate', 'tan', 'greater', 'bitwise_xor', 'fabs', 'floor', 'sqrt', 'arctan', 'right_shift', 'absolute', 'sin', 'multiply', 'greater_equal', 'left_shift', 'exp', 'divide_safe'] from numpy import less, cosh, arcsinh, add, ceil, arctan2, floor_divide, \ fmod, hypot, logical_and, power, sinh, remainder, cos, \ equal, arccos, less_equal, divide, bitwise_or, bitwise_and, \ logical_xor, log, subtract, invert, negative, log10, arcsin, \ arctanh, logical_not, not_equal, tanh, true_divide, maximum, \ arccosh, logical_or, minimum, conjugate, tan, greater, bitwise_xor, \ fabs, floor, sqrt, arctan, right_shift, absolute, sin, \ multiply, greater_equal, left_shift, exp, divide as divide_safe numpy-1.8.2/numpy/oldnumeric/__init__.py0000664000175100017510000000206412370216243021450 0ustar vagrantvagrant00000000000000"""Don't add these to the __all__ variable though """ from __future__ import division, absolute_import, print_function import warnings from numpy import * _msg = "The oldnumeric module will be dropped in Numpy 1.9" warnings.warn(_msg, ModuleDeprecationWarning) def _move_axis_to_0(a, axis): if axis == 0: return a n = len(a.shape) if axis < 0: axis += n axes = list(range(1, axis+1)) + [0,] + list(range(axis+1, n)) return transpose(a, axes) # Add these from .compat import * from .functions import * from .precision import * from .ufuncs import * from .misc import * from . import compat from . import precision from . import functions from . import misc from . import ufuncs import numpy __version__ = numpy.__version__ del numpy __all__ = ['__version__'] __all__ += compat.__all__ __all__ += precision.__all__ __all__ += functions.__all__ __all__ += ufuncs.__all__ __all__ += misc.__all__ del compat del functions del precision del ufuncs del misc from numpy.testing import Tester test = Tester().test bench = Tester().bench numpy-1.8.2/numpy/oldnumeric/mlab.py0000664000175100017510000000703612370216243020630 0ustar vagrantvagrant00000000000000"""This module is for compatibility only. All functions are defined elsewhere. """ from __future__ import division, absolute_import, print_function __all__ = ['rand', 'tril', 'trapz', 'hanning', 'rot90', 'triu', 'diff', 'angle', 'roots', 'ptp', 'kaiser', 'randn', 'cumprod', 'diag', 'msort', 'LinearAlgebra', 'RandomArray', 'prod', 'std', 'hamming', 'flipud', 'max', 'blackman', 'corrcoef', 'bartlett', 'eye', 'squeeze', 'sinc', 'tri', 'cov', 'svd', 'min', 'median', 'fliplr', 'eig', 'mean'] import numpy.oldnumeric.linear_algebra as LinearAlgebra import numpy.oldnumeric.random_array as RandomArray from numpy import tril, trapz as _Ntrapz, hanning, rot90, triu, diff, \ angle, roots, ptp as _Nptp, kaiser, cumprod as _Ncumprod, \ diag, msort, prod as _Nprod, std as _Nstd, hamming, flipud, \ amax as _Nmax, amin as _Nmin, blackman, bartlett, \ squeeze, sinc, median, fliplr, mean as _Nmean, transpose, \ sqrt, multiply, __version__ from numpy.linalg import eig, svd from numpy.random import rand, randn import numpy as np from .typeconv import convtypecode def eye(N, M=None, k=0, typecode=None, dtype=None): """ eye returns a N-by-M 2-d array where the k-th diagonal is all ones, and everything else is zeros. """ dtype = convtypecode(typecode, dtype) if M is None: M = N m = np.equal(np.subtract.outer(np.arange(N), np.arange(M)), -k) if m.dtype != dtype: return m.astype(dtype) def tri(N, M=None, k=0, typecode=None, dtype=None): """ returns a N-by-M array where all the diagonals starting from lower left corner up to the k-th are all ones. """ dtype = convtypecode(typecode, dtype) if M is None: M = N m = np.greater_equal(np.subtract.outer(np.arange(N), np.arange(M)), -k) if m.dtype != dtype: return m.astype(dtype) def trapz(y, x=None, axis=-1): return _Ntrapz(y, x, axis=axis) def ptp(x, axis=0): return _Nptp(x, axis) def cumprod(x, axis=0): return _Ncumprod(x, axis) def max(x, axis=0): return _Nmax(x, axis) def min(x, axis=0): return _Nmin(x, axis) def prod(x, axis=0): return _Nprod(x, axis) def std(x, axis=0): N = asarray(x).shape[axis] return _Nstd(x, axis)*sqrt(N/(N-1.)) def mean(x, axis=0): return _Nmean(x, axis) # This is exactly the same cov function as in MLab def cov(m, y=None, rowvar=0, bias=0): if y is None: y = m else: y = y if rowvar: m = transpose(m) y = transpose(y) if (m.shape[0] == 1): m = transpose(m) if (y.shape[0] == 1): y = transpose(y) N = m.shape[0] if (y.shape[0] != N): raise ValueError("x and y must have the same number of observations") m = m - _Nmean(m, axis=0) y = y - _Nmean(y, axis=0) if bias: fact = N*1.0 else: fact = N-1.0 return squeeze(dot(transpose(m), conjugate(y)) / fact) def corrcoef(x, y=None): c = cov(x, y) d = diag(c) return c/sqrt(multiply.outer(d, d)) from .compat import * from .functions import * from .precision import * from .ufuncs import * from .misc import * from .compat import __all__ as compat_all from .functions import __all__ as functions_all from .precision import __all__ as precision_all from .ufuncs import __all__ as ufuncs_all from .misc import __all__ as misc_all __all__ += ['__version__'] __all__ += compat_all __all__ += precision_all __all__ += functions_all __all__ += ufuncs_all __all__ += misc_all del compat_all del precision_all del functions_all del ufuncs_all del misc_all numpy-1.8.2/numpy/oldnumeric/misc.py0000664000175100017510000000234712370216243020650 0ustar vagrantvagrant00000000000000"""Functions that already have the correct syntax or miscellaneous functions """ from __future__ import division, absolute_import, print_function __all__ = ['sort', 'copy_reg', 'clip', 'rank', 'sign', 'shape', 'types', 'allclose', 'size', 'choose', 'swapaxes', 'array_str', 'pi', 'math', 'concatenate', 'putmask', 'put', 'around', 'vdot', 'transpose', 'array2string', 'diagonal', 'searchsorted', 'copy', 'resize', 'array_repr', 'e', 'StringIO', 'pickle', 'argsort', 'convolve', 'cross_correlate', 'dot', 'outerproduct', 'innerproduct', 'insert'] import types import pickle import math import copy import sys if sys.version_info[0] >= 3: import copyreg as copy_reg from io import BytesIO as StringIO else: import copy_reg from StringIO import StringIO from numpy import sort, clip, rank, sign, shape, putmask, allclose, size,\ choose, swapaxes, array_str, array_repr, e, pi, put, \ resize, around, concatenate, vdot, transpose, \ diagonal, searchsorted, argsort, convolve, dot, \ outer as outerproduct, inner as innerproduct, \ correlate as cross_correlate, \ place as insert from .array_printer import array2string numpy-1.8.2/numpy/oldnumeric/ma.py0000664000175100017510000022471512370216243020317 0ustar vagrantvagrant00000000000000"""MA: a facility for dealing with missing observations MA is generally used as a numpy.array look-alike. by Paul F. Dubois. Copyright 1999, 2000, 2001 Regents of the University of California. Released for unlimited redistribution. Adapted for numpy_core 2005 by Travis Oliphant and (mainly) Paul Dubois. """ from __future__ import division, absolute_import, print_function import sys import types import warnings from functools import reduce import numpy.core.umath as umath import numpy.core.fromnumeric as fromnumeric import numpy.core.numeric as numeric from numpy.core.numeric import newaxis, ndarray, inf from numpy.core.fromnumeric import amax, amin from numpy.core.numerictypes import bool_, typecodes import numpy.core.numeric as numeric from numpy.compat import bytes, long if sys.version_info[0] >= 3: _MAXINT = sys.maxsize _MININT = -sys.maxsize - 1 else: _MAXINT = sys.maxint _MININT = -sys.maxint - 1 # Ufunc domain lookup for __array_wrap__ ufunc_domain = {} # Ufunc fills lookup for __array__ ufunc_fills = {} MaskType = bool_ nomask = MaskType(0) divide_tolerance = 1.e-35 class MAError (Exception): def __init__ (self, args=None): "Create an exception" # The .args attribute must be a tuple. if not isinstance(args, tuple): args = (args,) self.args = args def __str__(self): "Calculate the string representation" return str(self.args[0]) __repr__ = __str__ class _MaskedPrintOption: "One instance of this class, masked_print_option, is created." def __init__ (self, display): "Create the masked print option object." self.set_display(display) self._enabled = 1 def display (self): "Show what prints for masked values." return self._display def set_display (self, s): "set_display(s) sets what prints for masked values." self._display = s def enabled (self): "Is the use of the display value enabled?" return self._enabled def enable(self, flag=1): "Set the enabling flag to flag." self._enabled = flag def __str__ (self): return str(self._display) __repr__ = __str__ #if you single index into a masked location you get this object. masked_print_option = _MaskedPrintOption('--') # Use single element arrays or scalars. default_real_fill_value = 1.e20 default_complex_fill_value = 1.e20 + 0.0j default_character_fill_value = '-' default_integer_fill_value = 999999 default_object_fill_value = '?' def default_fill_value (obj): "Function to calculate default fill value for an object." if isinstance(obj, float): return default_real_fill_value elif isinstance(obj, int) or isinstance(obj, long): return default_integer_fill_value elif isinstance(obj, bytes): return default_character_fill_value elif isinstance(obj, complex): return default_complex_fill_value elif isinstance(obj, MaskedArray) or isinstance(obj, ndarray): x = obj.dtype.char if x in typecodes['Float']: return default_real_fill_value if x in typecodes['Integer']: return default_integer_fill_value if x in typecodes['Complex']: return default_complex_fill_value if x in typecodes['Character']: return default_character_fill_value if x in typecodes['UnsignedInteger']: return umath.absolute(default_integer_fill_value) return default_object_fill_value else: return default_object_fill_value def minimum_fill_value (obj): "Function to calculate default fill value suitable for taking minima." if isinstance(obj, float): return numeric.inf elif isinstance(obj, int) or isinstance(obj, long): return _MAXINT elif isinstance(obj, MaskedArray) or isinstance(obj, ndarray): x = obj.dtype.char if x in typecodes['Float']: return numeric.inf if x in typecodes['Integer']: return _MAXINT if x in typecodes['UnsignedInteger']: return _MAXINT else: raise TypeError('Unsuitable type for calculating minimum.') def maximum_fill_value (obj): "Function to calculate default fill value suitable for taking maxima." if isinstance(obj, float): return -inf elif isinstance(obj, int) or isinstance(obj, long): return -_MAXINT elif isinstance(obj, MaskedArray) or isinstance(obj, ndarray): x = obj.dtype.char if x in typecodes['Float']: return -inf if x in typecodes['Integer']: return -_MAXINT if x in typecodes['UnsignedInteger']: return 0 else: raise TypeError('Unsuitable type for calculating maximum.') def set_fill_value (a, fill_value): "Set fill value of a if it is a masked array." if isMaskedArray(a): a.set_fill_value (fill_value) def getmask (a): """Mask of values in a; could be nomask. Returns nomask if a is not a masked array. To get an array for sure use getmaskarray.""" if isinstance(a, MaskedArray): return a.raw_mask() else: return nomask def getmaskarray (a): """Mask of values in a; an array of zeros if mask is nomask or not a masked array, and is a byte-sized integer. Do not try to add up entries, for example. """ m = getmask(a) if m is nomask: return make_mask_none(shape(a)) else: return m def is_mask (m): """Is m a legal mask? Does not check contents, only type. """ try: return m.dtype.type is MaskType except AttributeError: return False def make_mask (m, copy=0, flag=0): """make_mask(m, copy=0, flag=0) return m as a mask, creating a copy if necessary or requested. Can accept any sequence of integers or nomask. Does not check that contents must be 0s and 1s. if flag, return nomask if m contains no true elements. """ if m is nomask: return nomask elif isinstance(m, ndarray): if m.dtype.type is MaskType: if copy: result = numeric.array(m, dtype=MaskType, copy=copy) else: result = m else: result = m.astype(MaskType) else: result = filled(m, True).astype(MaskType) if flag and not fromnumeric.sometrue(fromnumeric.ravel(result)): return nomask else: return result def make_mask_none (s): "Return a mask of all zeros of shape s." result = numeric.zeros(s, dtype=MaskType) result.shape = s return result def mask_or (m1, m2): """Logical or of the mask candidates m1 and m2, treating nomask as false. Result may equal m1 or m2 if the other is nomask. """ if m1 is nomask: return make_mask(m2) if m2 is nomask: return make_mask(m1) if m1 is m2 and is_mask(m1): return m1 return make_mask(umath.logical_or(m1, m2)) def filled (a, value = None): """a as a contiguous numeric array with any masked areas replaced by value if value is None or the special element "masked", get_fill_value(a) is used instead. If a is already a contiguous numeric array, a itself is returned. filled(a) can be used to be sure that the result is numeric when passing an object a to other software ignorant of MA, in particular to numeric itself. """ if isinstance(a, MaskedArray): return a.filled(value) elif isinstance(a, ndarray) and a.flags['CONTIGUOUS']: return a elif isinstance(a, dict): return numeric.array(a, 'O') else: return numeric.array(a) def get_fill_value (a): """ The fill value of a, if it has one; otherwise, the default fill value for that type. """ if isMaskedArray(a): result = a.fill_value() else: result = default_fill_value(a) return result def common_fill_value (a, b): "The common fill_value of a and b, if there is one, or None" t1 = get_fill_value(a) t2 = get_fill_value(b) if t1 == t2: return t1 return None # Domain functions return 1 where the argument(s) are not in the domain. class domain_check_interval: "domain_check_interval(a,b)(x) = true where x < a or y > b" def __init__(self, y1, y2): "domain_check_interval(a,b)(x) = true where x < a or y > b" self.y1 = y1 self.y2 = y2 def __call__ (self, x): "Execute the call behavior." return umath.logical_or(umath.greater (x, self.y2), umath.less(x, self.y1) ) class domain_tan: "domain_tan(eps) = true where abs(cos(x)) < eps)" def __init__(self, eps): "domain_tan(eps) = true where abs(cos(x)) < eps)" self.eps = eps def __call__ (self, x): "Execute the call behavior." return umath.less(umath.absolute(umath.cos(x)), self.eps) class domain_greater: "domain_greater(v)(x) = true where x <= v" def __init__(self, critical_value): "domain_greater(v)(x) = true where x <= v" self.critical_value = critical_value def __call__ (self, x): "Execute the call behavior." return umath.less_equal (x, self.critical_value) class domain_greater_equal: "domain_greater_equal(v)(x) = true where x < v" def __init__(self, critical_value): "domain_greater_equal(v)(x) = true where x < v" self.critical_value = critical_value def __call__ (self, x): "Execute the call behavior." return umath.less (x, self.critical_value) class masked_unary_operation: def __init__ (self, aufunc, fill=0, domain=None): """ masked_unary_operation(aufunc, fill=0, domain=None) aufunc(fill) must be defined self(x) returns aufunc(x) with masked values where domain(x) is true or getmask(x) is true. """ self.f = aufunc self.fill = fill self.domain = domain self.__doc__ = getattr(aufunc, "__doc__", str(aufunc)) self.__name__ = getattr(aufunc, "__name__", str(aufunc)) ufunc_domain[aufunc] = domain ufunc_fills[aufunc] = fill, def __call__ (self, a, *args, **kwargs): "Execute the call behavior." # numeric tries to return scalars rather than arrays when given scalars. m = getmask(a) d1 = filled(a, self.fill) if self.domain is not None: m = mask_or(m, self.domain(d1)) result = self.f(d1, *args, **kwargs) return masked_array(result, m) def __str__ (self): return "Masked version of " + str(self.f) class domain_safe_divide: def __init__ (self, tolerance=divide_tolerance): self.tolerance = tolerance def __call__ (self, a, b): return umath.absolute(a) * self.tolerance >= umath.absolute(b) class domained_binary_operation: """Binary operations that have a domain, like divide. These are complicated so they are a separate class. They have no reduce, outer or accumulate. """ def __init__ (self, abfunc, domain, fillx=0, filly=0): """abfunc(fillx, filly) must be defined. abfunc(x, filly) = x for all x to enable reduce. """ self.f = abfunc self.domain = domain self.fillx = fillx self.filly = filly self.__doc__ = getattr(abfunc, "__doc__", str(abfunc)) self.__name__ = getattr(abfunc, "__name__", str(abfunc)) ufunc_domain[abfunc] = domain ufunc_fills[abfunc] = fillx, filly def __call__(self, a, b): "Execute the call behavior." ma = getmask(a) mb = getmask(b) d1 = filled(a, self.fillx) d2 = filled(b, self.filly) t = self.domain(d1, d2) if fromnumeric.sometrue(t, None): d2 = where(t, self.filly, d2) mb = mask_or(mb, t) m = mask_or(ma, mb) result = self.f(d1, d2) return masked_array(result, m) def __str__ (self): return "Masked version of " + str(self.f) class masked_binary_operation: def __init__ (self, abfunc, fillx=0, filly=0): """abfunc(fillx, filly) must be defined. abfunc(x, filly) = x for all x to enable reduce. """ self.f = abfunc self.fillx = fillx self.filly = filly self.__doc__ = getattr(abfunc, "__doc__", str(abfunc)) ufunc_domain[abfunc] = None ufunc_fills[abfunc] = fillx, filly def __call__ (self, a, b, *args, **kwargs): "Execute the call behavior." m = mask_or(getmask(a), getmask(b)) d1 = filled(a, self.fillx) d2 = filled(b, self.filly) result = self.f(d1, d2, *args, **kwargs) if isinstance(result, ndarray) \ and m.ndim != 0 \ and m.shape != result.shape: m = mask_or(getmaskarray(a), getmaskarray(b)) return masked_array(result, m) def reduce (self, target, axis=0, dtype=None): """Reduce target along the given axis with this function.""" m = getmask(target) t = filled(target, self.filly) if t.shape == (): t = t.reshape(1) if m is not nomask: m = make_mask(m, copy=1) m.shape = (1,) if m is nomask: t = self.f.reduce(t, axis) else: t = masked_array (t, m) # XXX: "or t.dtype" below is a workaround for what appears # XXX: to be a bug in reduce. t = self.f.reduce(filled(t, self.filly), axis, dtype=dtype or t.dtype) m = umath.logical_and.reduce(m, axis) if isinstance(t, ndarray): return masked_array(t, m, get_fill_value(target)) elif m: return masked else: return t def outer (self, a, b): "Return the function applied to the outer product of a and b." ma = getmask(a) mb = getmask(b) if ma is nomask and mb is nomask: m = nomask else: ma = getmaskarray(a) mb = getmaskarray(b) m = logical_or.outer(ma, mb) d = self.f.outer(filled(a, self.fillx), filled(b, self.filly)) return masked_array(d, m) def accumulate (self, target, axis=0): """Accumulate target along axis after filling with y fill value.""" t = filled(target, self.filly) return masked_array (self.f.accumulate (t, axis)) def __str__ (self): return "Masked version of " + str(self.f) sqrt = masked_unary_operation(umath.sqrt, 0.0, domain_greater_equal(0.0)) log = masked_unary_operation(umath.log, 1.0, domain_greater(0.0)) log10 = masked_unary_operation(umath.log10, 1.0, domain_greater(0.0)) exp = masked_unary_operation(umath.exp) conjugate = masked_unary_operation(umath.conjugate) sin = masked_unary_operation(umath.sin) cos = masked_unary_operation(umath.cos) tan = masked_unary_operation(umath.tan, 0.0, domain_tan(1.e-35)) arcsin = masked_unary_operation(umath.arcsin, 0.0, domain_check_interval(-1.0, 1.0)) arccos = masked_unary_operation(umath.arccos, 0.0, domain_check_interval(-1.0, 1.0)) arctan = masked_unary_operation(umath.arctan) # Missing from numeric arcsinh = masked_unary_operation(umath.arcsinh) arccosh = masked_unary_operation(umath.arccosh, 1.0, domain_greater_equal(1.0)) arctanh = masked_unary_operation(umath.arctanh, 0.0, domain_check_interval(-1.0+1e-15, 1.0-1e-15)) sinh = masked_unary_operation(umath.sinh) cosh = masked_unary_operation(umath.cosh) tanh = masked_unary_operation(umath.tanh) absolute = masked_unary_operation(umath.absolute) fabs = masked_unary_operation(umath.fabs) negative = masked_unary_operation(umath.negative) def nonzero(a): """returns the indices of the elements of a which are not zero and not masked """ return numeric.asarray(filled(a, 0).nonzero()) around = masked_unary_operation(fromnumeric.round_) floor = masked_unary_operation(umath.floor) ceil = masked_unary_operation(umath.ceil) logical_not = masked_unary_operation(umath.logical_not) add = masked_binary_operation(umath.add) subtract = masked_binary_operation(umath.subtract) subtract.reduce = None multiply = masked_binary_operation(umath.multiply, 1, 1) divide = domained_binary_operation(umath.divide, domain_safe_divide(), 0, 1) true_divide = domained_binary_operation(umath.true_divide, domain_safe_divide(), 0, 1) floor_divide = domained_binary_operation(umath.floor_divide, domain_safe_divide(), 0, 1) remainder = domained_binary_operation(umath.remainder, domain_safe_divide(), 0, 1) fmod = domained_binary_operation(umath.fmod, domain_safe_divide(), 0, 1) hypot = masked_binary_operation(umath.hypot) arctan2 = masked_binary_operation(umath.arctan2, 0.0, 1.0) arctan2.reduce = None equal = masked_binary_operation(umath.equal) equal.reduce = None not_equal = masked_binary_operation(umath.not_equal) not_equal.reduce = None less_equal = masked_binary_operation(umath.less_equal) less_equal.reduce = None greater_equal = masked_binary_operation(umath.greater_equal) greater_equal.reduce = None less = masked_binary_operation(umath.less) less.reduce = None greater = masked_binary_operation(umath.greater) greater.reduce = None logical_and = masked_binary_operation(umath.logical_and) alltrue = masked_binary_operation(umath.logical_and, 1, 1).reduce logical_or = masked_binary_operation(umath.logical_or) sometrue = logical_or.reduce logical_xor = masked_binary_operation(umath.logical_xor) bitwise_and = masked_binary_operation(umath.bitwise_and) bitwise_or = masked_binary_operation(umath.bitwise_or) bitwise_xor = masked_binary_operation(umath.bitwise_xor) def rank (object): return fromnumeric.rank(filled(object)) def shape (object): return fromnumeric.shape(filled(object)) def size (object, axis=None): return fromnumeric.size(filled(object), axis) class MaskedArray (object): """Arrays with possibly masked values. Masked values of 1 exclude the corresponding element from any computation. Construction: x = array(data, dtype=None, copy=True, order=False, mask = nomask, fill_value=None) If copy=False, every effort is made not to copy the data: If data is a MaskedArray, and argument mask=nomask, then the candidate data is data.data and the mask used is data.mask. If data is a numeric array, it is used as the candidate raw data. If dtype is not None and is != data.dtype.char then a data copy is required. Otherwise, the candidate is used. If a data copy is required, raw data stored is the result of: numeric.array(data, dtype=dtype.char, copy=copy) If mask is nomask there are no masked values. Otherwise mask must be convertible to an array of booleans with the same shape as x. fill_value is used to fill in masked values when necessary, such as when printing and in method/function filled(). The fill_value is not used for computation within this module. """ __array_priority__ = 10.1 def __init__(self, data, dtype=None, copy=True, order=False, mask=nomask, fill_value=None): """array(data, dtype=None, copy=True, order=False, mask=nomask, fill_value=None) If data already a numeric array, its dtype becomes the default value of dtype. """ if dtype is None: tc = None else: tc = numeric.dtype(dtype) need_data_copied = copy if isinstance(data, MaskedArray): c = data.data if tc is None: tc = c.dtype elif tc != c.dtype: need_data_copied = True if mask is nomask: mask = data.mask elif mask is not nomask: #attempting to change the mask need_data_copied = True elif isinstance(data, ndarray): c = data if tc is None: tc = c.dtype elif tc != c.dtype: need_data_copied = True else: need_data_copied = False #because I'll do it now c = numeric.array(data, dtype=tc, copy=True, order=order) tc = c.dtype if need_data_copied: if tc == c.dtype: self._data = numeric.array(c, dtype=tc, copy=True, order=order) else: self._data = c.astype(tc) else: self._data = c if mask is nomask: self._mask = nomask self._shared_mask = 0 else: self._mask = make_mask (mask) if self._mask is nomask: self._shared_mask = 0 else: self._shared_mask = (self._mask is mask) nm = size(self._mask) nd = size(self._data) if nm != nd: if nm == 1: self._mask = fromnumeric.resize(self._mask, self._data.shape) self._shared_mask = 0 elif nd == 1: self._data = fromnumeric.resize(self._data, self._mask.shape) self._data.shape = self._mask.shape else: raise MAError("Mask and data not compatible.") elif nm == 1 and shape(self._mask) != shape(self._data): self.unshare_mask() self._mask.shape = self._data.shape self.set_fill_value(fill_value) def __array__ (self, t=None, context=None): "Special hook for numeric. Converts to numeric if possible." if self._mask is not nomask: if fromnumeric.ravel(self._mask).any(): if context is None: warnings.warn("Cannot automatically convert masked array to "\ "numeric because data\n is masked in one or "\ "more locations."); return self._data #raise MAError( # """Cannot automatically convert masked array to numeric because data # is masked in one or more locations. # """) else: func, args, i = context fills = ufunc_fills.get(func) if fills is None: raise MAError("%s not known to ma" % func) return self.filled(fills[i]) else: # Mask is all false # Optimize to avoid future invocations of this section. self._mask = nomask self._shared_mask = 0 if t: return self._data.astype(t) else: return self._data def __array_wrap__ (self, array, context=None): """Special hook for ufuncs. Wraps the numpy array and sets the mask according to context. """ if context is None: return MaskedArray(array, copy=False, mask=nomask) func, args = context[:2] domain = ufunc_domain[func] m = reduce(mask_or, [getmask(a) for a in args]) if domain is not None: m = mask_or(m, domain(*[getattr(a, '_data', a) for a in args])) if m is not nomask: try: shape = array.shape except AttributeError: pass else: if m.shape != shape: m = reduce(mask_or, [getmaskarray(a) for a in args]) return MaskedArray(array, copy=False, mask=m) def _get_shape(self): "Return the current shape." return self._data.shape def _set_shape (self, newshape): "Set the array's shape." self._data.shape = newshape if self._mask is not nomask: self._mask = self._mask.copy() self._mask.shape = newshape def _get_flat(self): """Calculate the flat value. """ if self._mask is nomask: return masked_array(self._data.ravel(), mask=nomask, fill_value = self.fill_value()) else: return masked_array(self._data.ravel(), mask=self._mask.ravel(), fill_value = self.fill_value()) def _set_flat (self, value): "x.flat = value" y = self.ravel() y[:] = value def _get_real(self): "Get the real part of a complex array." if self._mask is nomask: return masked_array(self._data.real, mask=nomask, fill_value = self.fill_value()) else: return masked_array(self._data.real, mask=self._mask, fill_value = self.fill_value()) def _set_real (self, value): "x.real = value" y = self.real y[...] = value def _get_imaginary(self): "Get the imaginary part of a complex array." if self._mask is nomask: return masked_array(self._data.imag, mask=nomask, fill_value = self.fill_value()) else: return masked_array(self._data.imag, mask=self._mask, fill_value = self.fill_value()) def _set_imaginary (self, value): "x.imaginary = value" y = self.imaginary y[...] = value def __str__(self): """Calculate the str representation, using masked for fill if it is enabled. Otherwise fill with fill value. """ if masked_print_option.enabled(): f = masked_print_option # XXX: Without the following special case masked # XXX: would print as "[--]", not "--". Can we avoid # XXX: checks for masked by choosing a different value # XXX: for the masked singleton? 2005-01-05 -- sasha if self is masked: return str(f) m = self._mask if m is not nomask and m.shape == () and m: return str(f) # convert to object array to make filled work self = self.astype(object) else: f = self.fill_value() res = self.filled(f) return str(res) def __repr__(self): """Calculate the repr representation, using masked for fill if it is enabled. Otherwise fill with fill value. """ with_mask = """\ array(data = %(data)s, mask = %(mask)s, fill_value=%(fill)s) """ with_mask1 = """\ array(data = %(data)s, mask = %(mask)s, fill_value=%(fill)s) """ without_mask = """array( %(data)s)""" without_mask1 = """array(%(data)s)""" n = len(self.shape) if self._mask is nomask: if n <= 1: return without_mask1 % {'data':str(self.filled())} return without_mask % {'data':str(self.filled())} else: if n <= 1: return with_mask % { 'data': str(self.filled()), 'mask': str(self._mask), 'fill': str(self.fill_value()) } return with_mask % { 'data': str(self.filled()), 'mask': str(self._mask), 'fill': str(self.fill_value()) } without_mask1 = """array(%(data)s)""" if self._mask is nomask: return without_mask % {'data':str(self.filled())} else: return with_mask % { 'data': str(self.filled()), 'mask': str(self._mask), 'fill': str(self.fill_value()) } def __float__(self): "Convert self to float." self.unmask() if self._mask is not nomask: raise MAError('Cannot convert masked element to a Python float.') return float(self.data.item()) def __int__(self): "Convert self to int." self.unmask() if self._mask is not nomask: raise MAError('Cannot convert masked element to a Python int.') return int(self.data.item()) def __getitem__(self, i): "Get item described by i. Not a copy as in previous versions." self.unshare_mask() m = self._mask dout = self._data[i] if m is nomask: try: if dout.size == 1: return dout else: return masked_array(dout, fill_value=self._fill_value) except AttributeError: return dout mi = m[i] if mi.size == 1: if mi: return masked else: return dout else: return masked_array(dout, mi, fill_value=self._fill_value) # -------- # setitem and setslice notes # note that if value is masked, it means to mask those locations. # setting a value changes the mask to match the value in those locations. def __setitem__(self, index, value): "Set item described by index. If value is masked, mask those locations." d = self._data if self is masked: raise MAError('Cannot alter masked elements.') if value is masked: if self._mask is nomask: self._mask = make_mask_none(d.shape) self._shared_mask = False else: self.unshare_mask() self._mask[index] = True return m = getmask(value) value = filled(value).astype(d.dtype) d[index] = value if m is nomask: if self._mask is not nomask: self.unshare_mask() self._mask[index] = False else: if self._mask is nomask: self._mask = make_mask_none(d.shape) self._shared_mask = True else: self.unshare_mask() self._mask[index] = m def __nonzero__(self): """returns true if any element is non-zero or masked """ # XXX: This changes bool conversion logic from MA. # XXX: In MA bool(a) == len(a) != 0, but in numpy # XXX: scalars do not have len m = self._mask d = self._data return bool(m is not nomask and m.any() or d is not nomask and d.any()) def __bool__(self): """returns true if any element is non-zero or masked """ # XXX: This changes bool conversion logic from MA. # XXX: In MA bool(a) == len(a) != 0, but in numpy # XXX: scalars do not have len m = self._mask d = self._data return bool(m is not nomask and m.any() or d is not nomask and d.any()) def __len__ (self): """Return length of first dimension. This is weird but Python's slicing behavior depends on it.""" return len(self._data) def __and__(self, other): "Return bitwise_and" return bitwise_and(self, other) def __or__(self, other): "Return bitwise_or" return bitwise_or(self, other) def __xor__(self, other): "Return bitwise_xor" return bitwise_xor(self, other) __rand__ = __and__ __ror__ = __or__ __rxor__ = __xor__ def __abs__(self): "Return absolute(self)" return absolute(self) def __neg__(self): "Return negative(self)" return negative(self) def __pos__(self): "Return array(self)" return array(self) def __add__(self, other): "Return add(self, other)" return add(self, other) __radd__ = __add__ def __mod__ (self, other): "Return remainder(self, other)" return remainder(self, other) def __rmod__ (self, other): "Return remainder(other, self)" return remainder(other, self) def __lshift__ (self, n): return left_shift(self, n) def __rshift__ (self, n): return right_shift(self, n) def __sub__(self, other): "Return subtract(self, other)" return subtract(self, other) def __rsub__(self, other): "Return subtract(other, self)" return subtract(other, self) def __mul__(self, other): "Return multiply(self, other)" return multiply(self, other) __rmul__ = __mul__ def __div__(self, other): "Return divide(self, other)" return divide(self, other) def __rdiv__(self, other): "Return divide(other, self)" return divide(other, self) def __truediv__(self, other): "Return divide(self, other)" return true_divide(self, other) def __rtruediv__(self, other): "Return divide(other, self)" return true_divide(other, self) def __floordiv__(self, other): "Return divide(self, other)" return floor_divide(self, other) def __rfloordiv__(self, other): "Return divide(other, self)" return floor_divide(other, self) def __pow__(self, other, third=None): "Return power(self, other, third)" return power(self, other, third) def __sqrt__(self): "Return sqrt(self)" return sqrt(self) def __iadd__(self, other): "Add other to self in place." t = self._data.dtype.char f = filled(other, 0) t1 = f.dtype.char if t == t1: pass elif t in typecodes['Integer']: if t1 in typecodes['Integer']: f = f.astype(t) else: raise TypeError('Incorrect type for in-place operation.') elif t in typecodes['Float']: if t1 in typecodes['Integer']: f = f.astype(t) elif t1 in typecodes['Float']: f = f.astype(t) else: raise TypeError('Incorrect type for in-place operation.') elif t in typecodes['Complex']: if t1 in typecodes['Integer']: f = f.astype(t) elif t1 in typecodes['Float']: f = f.astype(t) elif t1 in typecodes['Complex']: f = f.astype(t) else: raise TypeError('Incorrect type for in-place operation.') else: raise TypeError('Incorrect type for in-place operation.') if self._mask is nomask: self._data += f m = getmask(other) self._mask = m self._shared_mask = m is not nomask else: result = add(self, masked_array(f, mask=getmask(other))) self._data = result.data self._mask = result.mask self._shared_mask = 1 return self def __imul__(self, other): "Add other to self in place." t = self._data.dtype.char f = filled(other, 0) t1 = f.dtype.char if t == t1: pass elif t in typecodes['Integer']: if t1 in typecodes['Integer']: f = f.astype(t) else: raise TypeError('Incorrect type for in-place operation.') elif t in typecodes['Float']: if t1 in typecodes['Integer']: f = f.astype(t) elif t1 in typecodes['Float']: f = f.astype(t) else: raise TypeError('Incorrect type for in-place operation.') elif t in typecodes['Complex']: if t1 in typecodes['Integer']: f = f.astype(t) elif t1 in typecodes['Float']: f = f.astype(t) elif t1 in typecodes['Complex']: f = f.astype(t) else: raise TypeError('Incorrect type for in-place operation.') else: raise TypeError('Incorrect type for in-place operation.') if self._mask is nomask: self._data *= f m = getmask(other) self._mask = m self._shared_mask = m is not nomask else: result = multiply(self, masked_array(f, mask=getmask(other))) self._data = result.data self._mask = result.mask self._shared_mask = 1 return self def __isub__(self, other): "Subtract other from self in place." t = self._data.dtype.char f = filled(other, 0) t1 = f.dtype.char if t == t1: pass elif t in typecodes['Integer']: if t1 in typecodes['Integer']: f = f.astype(t) else: raise TypeError('Incorrect type for in-place operation.') elif t in typecodes['Float']: if t1 in typecodes['Integer']: f = f.astype(t) elif t1 in typecodes['Float']: f = f.astype(t) else: raise TypeError('Incorrect type for in-place operation.') elif t in typecodes['Complex']: if t1 in typecodes['Integer']: f = f.astype(t) elif t1 in typecodes['Float']: f = f.astype(t) elif t1 in typecodes['Complex']: f = f.astype(t) else: raise TypeError('Incorrect type for in-place operation.') else: raise TypeError('Incorrect type for in-place operation.') if self._mask is nomask: self._data -= f m = getmask(other) self._mask = m self._shared_mask = m is not nomask else: result = subtract(self, masked_array(f, mask=getmask(other))) self._data = result.data self._mask = result.mask self._shared_mask = 1 return self def __idiv__(self, other): "Divide self by other in place." t = self._data.dtype.char f = filled(other, 0) t1 = f.dtype.char if t == t1: pass elif t in typecodes['Integer']: if t1 in typecodes['Integer']: f = f.astype(t) else: raise TypeError('Incorrect type for in-place operation.') elif t in typecodes['Float']: if t1 in typecodes['Integer']: f = f.astype(t) elif t1 in typecodes['Float']: f = f.astype(t) else: raise TypeError('Incorrect type for in-place operation.') elif t in typecodes['Complex']: if t1 in typecodes['Integer']: f = f.astype(t) elif t1 in typecodes['Float']: f = f.astype(t) elif t1 in typecodes['Complex']: f = f.astype(t) else: raise TypeError('Incorrect type for in-place operation.') else: raise TypeError('Incorrect type for in-place operation.') mo = getmask(other) result = divide(self, masked_array(f, mask=mo)) self._data = result.data dm = result.raw_mask() if dm is not self._mask: self._mask = dm self._shared_mask = 1 return self def __eq__(self, other): return equal(self, other) def __ne__(self, other): return not_equal(self, other) def __lt__(self, other): return less(self, other) def __le__(self, other): return less_equal(self, other) def __gt__(self, other): return greater(self, other) def __ge__(self, other): return greater_equal(self, other) def astype (self, tc): "return self as array of given type." d = self._data.astype(tc) return array(d, mask=self._mask) def byte_swapped(self): """Returns the raw data field, byte_swapped. Included for consistency with numeric but doesn't make sense in this context. """ return self._data.byte_swapped() def compressed (self): "A 1-D array of all the non-masked data." d = fromnumeric.ravel(self._data) if self._mask is nomask: return array(d) else: m = 1 - fromnumeric.ravel(self._mask) c = fromnumeric.compress(m, d) return array(c, copy=0) def count (self, axis = None): "Count of the non-masked elements in a, or along a certain axis." m = self._mask s = self._data.shape ls = len(s) if m is nomask: if ls == 0: return 1 if ls == 1: return s[0] if axis is None: return reduce(lambda x, y:x*y, s) else: n = s[axis] t = list(s) del t[axis] return ones(t) * n if axis is None: w = fromnumeric.ravel(m).astype(int) n1 = size(w) if n1 == 1: n2 = w[0] else: n2 = umath.add.reduce(w) return n1 - n2 else: n1 = size(m, axis) n2 = sum(m.astype(int), axis) return n1 - n2 def dot (self, other): "s.dot(other) = innerproduct(s, other)" return innerproduct(self, other) def fill_value(self): "Get the current fill value." return self._fill_value def filled (self, fill_value=None): """A numeric array with masked values filled. If fill_value is None, use self.fill_value(). If mask is nomask, copy data only if not contiguous. Result is always a contiguous, numeric array. # Is contiguous really necessary now? """ d = self._data m = self._mask if m is nomask: if d.flags['CONTIGUOUS']: return d else: return d.copy() else: if fill_value is None: value = self._fill_value else: value = fill_value if self is masked: result = numeric.array(value) else: try: result = numeric.array(d, dtype=d.dtype, copy=1) result[m] = value except (TypeError, AttributeError): #ok, can't put that value in here value = numeric.array(value, dtype=object) d = d.astype(object) result = fromnumeric.choose(m, (d, value)) return result def ids (self): """Return the ids of the data and mask areas""" return (id(self._data), id(self._mask)) def iscontiguous (self): "Is the data contiguous?" return self._data.flags['CONTIGUOUS'] def itemsize(self): "Item size of each data item." return self._data.itemsize def outer(self, other): "s.outer(other) = outerproduct(s, other)" return outerproduct(self, other) def put (self, values): """Set the non-masked entries of self to filled(values). No change to mask """ iota = numeric.arange(self.size) d = self._data if self._mask is nomask: ind = iota else: ind = fromnumeric.compress(1 - self._mask, iota) d[ind] = filled(values).astype(d.dtype) def putmask (self, values): """Set the masked entries of self to filled(values). Mask changed to nomask. """ d = self._data if self._mask is not nomask: d[self._mask] = filled(values).astype(d.dtype) self._shared_mask = 0 self._mask = nomask def ravel (self): """Return a 1-D view of self.""" if self._mask is nomask: return masked_array(self._data.ravel()) else: return masked_array(self._data.ravel(), self._mask.ravel()) def raw_data (self): """ Obsolete; use data property instead. The raw data; portions may be meaningless. May be noncontiguous. Expert use only.""" return self._data data = property(fget=raw_data, doc="The data, but values at masked locations are meaningless.") def raw_mask (self): """ Obsolete; use mask property instead. May be noncontiguous. Expert use only. """ return self._mask mask = property(fget=raw_mask, doc="The mask, may be nomask. Values where mask true are meaningless.") def reshape (self, *s): """This array reshaped to shape s""" d = self._data.reshape(*s) if self._mask is nomask: return masked_array(d) else: m = self._mask.reshape(*s) return masked_array(d, m) def set_fill_value (self, v=None): "Set the fill value to v. Omit v to restore default." if v is None: v = default_fill_value (self.raw_data()) self._fill_value = v def _get_ndim(self): return self._data.ndim ndim = property(_get_ndim, doc=numeric.ndarray.ndim.__doc__) def _get_size (self): return self._data.size size = property(fget=_get_size, doc="Number of elements in the array.") ## CHECK THIS: signature of numeric.array.size? def _get_dtype(self): return self._data.dtype dtype = property(fget=_get_dtype, doc="type of the array elements.") def item(self, *args): "Return Python scalar if possible" if self._mask is not nomask: m = self._mask.item(*args) try: if m[0]: return masked except IndexError: return masked return self._data.item(*args) def itemset(self, *args): "Set Python scalar into array" item = args[-1] args = args[:-1] self[args] = item def tolist(self, fill_value=None): "Convert to list" return self.filled(fill_value).tolist() def tostring(self, fill_value=None): "Convert to string" return self.filled(fill_value).tostring() def unmask (self): "Replace the mask by nomask if possible." if self._mask is nomask: return m = make_mask(self._mask, flag=1) if m is nomask: self._mask = nomask self._shared_mask = 0 def unshare_mask (self): "If currently sharing mask, make a copy." if self._shared_mask: self._mask = make_mask (self._mask, copy=1, flag=0) self._shared_mask = 0 def _get_ctypes(self): return self._data.ctypes def _get_T(self): if (self.ndim < 2): return self return self.transpose() shape = property(_get_shape, _set_shape, doc = 'tuple giving the shape of the array') flat = property(_get_flat, _set_flat, doc = 'Access array in flat form.') real = property(_get_real, _set_real, doc = 'Access the real part of the array') imaginary = property(_get_imaginary, _set_imaginary, doc = 'Access the imaginary part of the array') imag = imaginary ctypes = property(_get_ctypes, None, doc="ctypes") T = property(_get_T, None, doc="get transpose") #end class MaskedArray array = MaskedArray def isMaskedArray (x): "Is x a masked array, that is, an instance of MaskedArray?" return isinstance(x, MaskedArray) isarray = isMaskedArray isMA = isMaskedArray #backward compatibility def allclose (a, b, fill_value=1, rtol=1.e-5, atol=1.e-8): """ Returns true if all components of a and b are equal subject to given tolerances. If fill_value is 1, masked values considered equal. If fill_value is 0, masked values considered unequal. The relative error rtol should be positive and << 1.0 The absolute error atol comes into play for those elements of b that are very small or zero; it says how small a must be also. """ m = mask_or(getmask(a), getmask(b)) d1 = filled(a) d2 = filled(b) x = filled(array(d1, copy=0, mask=m), fill_value).astype(float) y = filled(array(d2, copy=0, mask=m), 1).astype(float) d = umath.less_equal(umath.absolute(x-y), atol + rtol * umath.absolute(y)) return fromnumeric.alltrue(fromnumeric.ravel(d)) def allequal (a, b, fill_value=1): """ True if all entries of a and b are equal, using fill_value as a truth value where either or both are masked. """ m = mask_or(getmask(a), getmask(b)) if m is nomask: x = filled(a) y = filled(b) d = umath.equal(x, y) return fromnumeric.alltrue(fromnumeric.ravel(d)) elif fill_value: x = filled(a) y = filled(b) d = umath.equal(x, y) dm = array(d, mask=m, copy=0) return fromnumeric.alltrue(fromnumeric.ravel(filled(dm, 1))) else: return 0 def masked_values (data, value, rtol=1.e-5, atol=1.e-8, copy=1): """ masked_values(data, value, rtol=1.e-5, atol=1.e-8) Create a masked array; mask is nomask if possible. If copy==0, and otherwise possible, result may share data values with original array. Let d = filled(data, value). Returns d masked where abs(data-value)<= atol + rtol * abs(value) if d is of a floating point type. Otherwise returns masked_object(d, value, copy) """ abs = umath.absolute d = filled(data, value) if issubclass(d.dtype.type, numeric.floating): m = umath.less_equal(abs(d-value), atol+rtol*abs(value)) m = make_mask(m, flag=1) return array(d, mask = m, copy=copy, fill_value=value) else: return masked_object(d, value, copy=copy) def masked_object (data, value, copy=1): "Create array masked where exactly data equal to value" d = filled(data, value) dm = make_mask(umath.equal(d, value), flag=1) return array(d, mask=dm, copy=copy, fill_value=value) def arange(start, stop=None, step=1, dtype=None): """Just like range() except it returns a array whose type can be specified by the keyword argument dtype. """ return array(numeric.arange(start, stop, step, dtype)) arrayrange = arange def fromstring (s, t): "Construct a masked array from a string. Result will have no mask." return masked_array(numeric.fromstring(s, t)) def left_shift (a, n): "Left shift n bits" m = getmask(a) if m is nomask: d = umath.left_shift(filled(a), n) return masked_array(d) else: d = umath.left_shift(filled(a, 0), n) return masked_array(d, m) def right_shift (a, n): "Right shift n bits" m = getmask(a) if m is nomask: d = umath.right_shift(filled(a), n) return masked_array(d) else: d = umath.right_shift(filled(a, 0), n) return masked_array(d, m) def resize (a, new_shape): """resize(a, new_shape) returns a new array with the specified shape. The original array's total size can be any size.""" m = getmask(a) if m is not nomask: m = fromnumeric.resize(m, new_shape) result = array(fromnumeric.resize(filled(a), new_shape), mask=m) result.set_fill_value(get_fill_value(a)) return result def new_repeat(a, repeats, axis=None): """repeat elements of a repeats times along axis repeats is a sequence of length a.shape[axis] telling how many times to repeat each element. """ af = filled(a) if isinstance(repeats, int): if axis is None: num = af.size else: num = af.shape[axis] repeats = tuple([repeats]*num) m = getmask(a) if m is not nomask: m = fromnumeric.repeat(m, repeats, axis) d = fromnumeric.repeat(af, repeats, axis) result = masked_array(d, m) result.set_fill_value(get_fill_value(a)) return result def identity(n): """identity(n) returns the identity matrix of shape n x n. """ return array(numeric.identity(n)) def indices (dimensions, dtype=None): """indices(dimensions,dtype=None) returns an array representing a grid of indices with row-only, and column-only variation. """ return array(numeric.indices(dimensions, dtype)) def zeros (shape, dtype=float): """zeros(n, dtype=float) = an array of all zeros of the given length or shape.""" return array(numeric.zeros(shape, dtype)) def ones (shape, dtype=float): """ones(n, dtype=float) = an array of all ones of the given length or shape.""" return array(numeric.ones(shape, dtype)) def count (a, axis = None): "Count of the non-masked elements in a, or along a certain axis." a = masked_array(a) return a.count(axis) def power (a, b, third=None): "a**b" if third is not None: raise MAError("3-argument power not supported.") ma = getmask(a) mb = getmask(b) m = mask_or(ma, mb) fa = filled(a, 1) fb = filled(b, 1) if fb.dtype.char in typecodes["Integer"]: return masked_array(umath.power(fa, fb), m) md = make_mask(umath.less(fa, 0), flag=1) m = mask_or(m, md) if m is nomask: return masked_array(umath.power(fa, fb)) else: fa = numeric.where(m, 1, fa) return masked_array(umath.power(fa, fb), m) def masked_array (a, mask=nomask, fill_value=None): """masked_array(a, mask=nomask) = array(a, mask=mask, copy=0, fill_value=fill_value) """ return array(a, mask=mask, copy=0, fill_value=fill_value) def sum (target, axis=None, dtype=None): if axis is None: target = ravel(target) axis = 0 return add.reduce(target, axis, dtype) def product (target, axis=None, dtype=None): if axis is None: target = ravel(target) axis = 0 return multiply.reduce(target, axis, dtype) def new_average (a, axis=None, weights=None, returned = 0): """average(a, axis=None, weights=None) Computes average along indicated axis. If axis is None, average over the entire array Inputs can be integer or floating types; result is of type float. If weights are given, result is sum(a*weights,axis=0)/(sum(weights,axis=0)*1.0) weights must have a's shape or be the 1-d with length the size of a in the given axis. If returned, return a tuple: the result and the sum of the weights or count of values. Results will have the same shape. masked values in the weights will be set to 0.0 """ a = masked_array(a) mask = a.mask ash = a.shape if ash == (): ash = (1,) if axis is None: if mask is nomask: if weights is None: n = add.reduce(a.raw_data().ravel()) d = reduce(lambda x, y: x * y, ash, 1.0) else: w = filled(weights, 0.0).ravel() n = umath.add.reduce(a.raw_data().ravel() * w) d = umath.add.reduce(w) del w else: if weights is None: n = add.reduce(a.ravel()) w = fromnumeric.choose(mask, (1.0, 0.0)).ravel() d = umath.add.reduce(w) del w else: w = array(filled(weights, 0.0), float, mask=mask).ravel() n = add.reduce(a.ravel() * w) d = add.reduce(w) del w else: if mask is nomask: if weights is None: d = ash[axis] * 1.0 n = umath.add.reduce(a.raw_data(), axis) else: w = filled(weights, 0.0) wsh = w.shape if wsh == (): wsh = (1,) if wsh == ash: w = numeric.array(w, float, copy=0) n = add.reduce(a*w, axis) d = add.reduce(w, axis) del w elif wsh == (ash[axis],): r = [newaxis]*len(ash) r[axis] = slice(None, None, 1) w = eval ("w["+ repr(tuple(r)) + "] * ones(ash, float)") n = add.reduce(a*w, axis) d = add.reduce(w, axis) del w, r else: raise ValueError('average: weights wrong shape.') else: if weights is None: n = add.reduce(a, axis) w = numeric.choose(mask, (1.0, 0.0)) d = umath.add.reduce(w, axis) del w else: w = filled(weights, 0.0) wsh = w.shape if wsh == (): wsh = (1,) if wsh == ash: w = array(w, float, mask=mask, copy=0) n = add.reduce(a*w, axis) d = add.reduce(w, axis) elif wsh == (ash[axis],): r = [newaxis]*len(ash) r[axis] = slice(None, None, 1) w = eval ("w["+ repr(tuple(r)) + "] * masked_array(ones(ash, float), mask)") n = add.reduce(a*w, axis) d = add.reduce(w, axis) else: raise ValueError('average: weights wrong shape.') del w #print n, d, repr(mask), repr(weights) if n is masked or d is masked: return masked result = divide (n, d) del n if isinstance(result, MaskedArray): result.unmask() if returned: if not isinstance(d, MaskedArray): d = masked_array(d) if not d.shape == result.shape: d = ones(result.shape, float) * d d.unmask() if returned: return result, d else: return result def where (condition, x, y): """where(condition, x, y) is x where condition is nonzero, y otherwise. condition must be convertible to an integer array. Answer is always the shape of condition. The type depends on x and y. It is integer if both x and y are the value masked. """ fc = filled(not_equal(condition, 0), 0) xv = filled(x) xm = getmask(x) yv = filled(y) ym = getmask(y) d = numeric.choose(fc, (yv, xv)) md = numeric.choose(fc, (ym, xm)) m = getmask(condition) m = make_mask(mask_or(m, md), copy=0, flag=1) return masked_array(d, m) def choose (indices, t, out=None, mode='raise'): "Returns array shaped like indices with elements chosen from t" def fmask (x): if x is masked: return 1 return filled(x) def nmask (x): if x is masked: return 1 m = getmask(x) if m is nomask: return 0 return m c = filled(indices, 0) masks = [nmask(x) for x in t] a = [fmask(x) for x in t] d = numeric.choose(c, a) m = numeric.choose(c, masks) m = make_mask(mask_or(m, getmask(indices)), copy=0, flag=1) return masked_array(d, m) def masked_where(condition, x, copy=1): """Return x as an array masked where condition is true. Also masked where x or condition masked. """ cm = filled(condition, 1) m = mask_or(getmask(x), cm) return array(filled(x), copy=copy, mask=m) def masked_greater(x, value, copy=1): "masked_greater(x, value) = x masked where x > value" return masked_where(greater(x, value), x, copy) def masked_greater_equal(x, value, copy=1): "masked_greater_equal(x, value) = x masked where x >= value" return masked_where(greater_equal(x, value), x, copy) def masked_less(x, value, copy=1): "masked_less(x, value) = x masked where x < value" return masked_where(less(x, value), x, copy) def masked_less_equal(x, value, copy=1): "masked_less_equal(x, value) = x masked where x <= value" return masked_where(less_equal(x, value), x, copy) def masked_not_equal(x, value, copy=1): "masked_not_equal(x, value) = x masked where x != value" d = filled(x, 0) c = umath.not_equal(d, value) m = mask_or(c, getmask(x)) return array(d, mask=m, copy=copy) def masked_equal(x, value, copy=1): """masked_equal(x, value) = x masked where x == value For floating point consider masked_values(x, value) instead. """ d = filled(x, 0) c = umath.equal(d, value) m = mask_or(c, getmask(x)) return array(d, mask=m, copy=copy) def masked_inside(x, v1, v2, copy=1): """x with mask of all values of x that are inside [v1,v2] v1 and v2 can be given in either order. """ if v2 < v1: t = v2 v2 = v1 v1 = t d = filled(x, 0) c = umath.logical_and(umath.less_equal(d, v2), umath.greater_equal(d, v1)) m = mask_or(c, getmask(x)) return array(d, mask = m, copy=copy) def masked_outside(x, v1, v2, copy=1): """x with mask of all values of x that are outside [v1,v2] v1 and v2 can be given in either order. """ if v2 < v1: t = v2 v2 = v1 v1 = t d = filled(x, 0) c = umath.logical_or(umath.less(d, v1), umath.greater(d, v2)) m = mask_or(c, getmask(x)) return array(d, mask = m, copy=copy) def reshape (a, *newshape): "Copy of a with a new shape." m = getmask(a) d = filled(a).reshape(*newshape) if m is nomask: return masked_array(d) else: return masked_array(d, mask=numeric.reshape(m, *newshape)) def ravel (a): "a as one-dimensional, may share data and mask" m = getmask(a) d = fromnumeric.ravel(filled(a)) if m is nomask: return masked_array(d) else: return masked_array(d, mask=numeric.ravel(m)) def concatenate (arrays, axis=0): "Concatenate the arrays along the given axis" d = [] for x in arrays: d.append(filled(x)) d = numeric.concatenate(d, axis) for x in arrays: if getmask(x) is not nomask: break else: return masked_array(d) dm = [] for x in arrays: dm.append(getmaskarray(x)) dm = numeric.concatenate(dm, axis) return masked_array(d, mask=dm) def swapaxes (a, axis1, axis2): m = getmask(a) d = masked_array(a).data if m is nomask: return masked_array(data=numeric.swapaxes(d, axis1, axis2)) else: return masked_array(data=numeric.swapaxes(d, axis1, axis2), mask=numeric.swapaxes(m, axis1, axis2),) def new_take (a, indices, axis=None, out=None, mode='raise'): "returns selection of items from a." m = getmask(a) # d = masked_array(a).raw_data() d = masked_array(a).data if m is nomask: return masked_array(numeric.take(d, indices, axis)) else: return masked_array(numeric.take(d, indices, axis), mask = numeric.take(m, indices, axis)) def transpose(a, axes=None): "reorder dimensions per tuple axes" m = getmask(a) d = filled(a) if m is nomask: return masked_array(numeric.transpose(d, axes)) else: return masked_array(numeric.transpose(d, axes), mask = numeric.transpose(m, axes)) def put(a, indices, values, mode='raise'): """sets storage-indexed locations to corresponding values. Values and indices are filled if necessary. """ d = a.raw_data() ind = filled(indices) v = filled(values) numeric.put (d, ind, v) m = getmask(a) if m is not nomask: a.unshare_mask() numeric.put(a.raw_mask(), ind, 0) def putmask(a, mask, values): "putmask(a, mask, values) sets a where mask is true." if mask is nomask: return numeric.putmask(a.raw_data(), mask, values) m = getmask(a) if m is nomask: return a.unshare_mask() numeric.putmask(a.raw_mask(), mask, 0) def inner(a, b): """inner(a,b) returns the dot product of two arrays, which has shape a.shape[:-1] + b.shape[:-1] with elements computed by summing the product of the elements from the last dimensions of a and b. Masked elements are replace by zeros. """ fa = filled(a, 0) fb = filled(b, 0) if len(fa.shape) == 0: fa.shape = (1,) if len(fb.shape) == 0: fb.shape = (1,) return masked_array(numeric.inner(fa, fb)) innerproduct = inner def outer(a, b): """outer(a,b) = {a[i]*b[j]}, has shape (len(a),len(b))""" fa = filled(a, 0).ravel() fb = filled(b, 0).ravel() d = numeric.outer(fa, fb) ma = getmask(a) mb = getmask(b) if ma is nomask and mb is nomask: return masked_array(d) ma = getmaskarray(a) mb = getmaskarray(b) m = make_mask(1-numeric.outer(1-ma, 1-mb), copy=0) return masked_array(d, m) outerproduct = outer def dot(a, b): """dot(a,b) returns matrix-multiplication between a and b. The product-sum is over the last dimension of a and the second-to-last dimension of b. Masked values are replaced by zeros. See also innerproduct. """ return innerproduct(filled(a, 0), numeric.swapaxes(filled(b, 0), -1, -2)) def compress(condition, x, dimension=-1, out=None): """Select those parts of x for which condition is true. Masked values in condition are considered false. """ c = filled(condition, 0) m = getmask(x) if m is not nomask: m = numeric.compress(c, m, dimension) d = numeric.compress(c, filled(x), dimension) return masked_array(d, m) class _minimum_operation: "Object to calculate minima" def __init__ (self): """minimum(a, b) or minimum(a) In one argument case returns the scalar minimum. """ pass def __call__ (self, a, b=None): "Execute the call behavior." if b is None: m = getmask(a) if m is nomask: d = amin(filled(a).ravel()) return d ac = a.compressed() if len(ac) == 0: return masked else: return amin(ac.raw_data()) else: return where(less(a, b), a, b) def reduce (self, target, axis=0): """Reduce target along the given axis.""" m = getmask(target) if m is nomask: t = filled(target) return masked_array (umath.minimum.reduce (t, axis)) else: t = umath.minimum.reduce(filled(target, minimum_fill_value(target)), axis) m = umath.logical_and.reduce(m, axis) return masked_array(t, m, get_fill_value(target)) def outer (self, a, b): "Return the function applied to the outer product of a and b." ma = getmask(a) mb = getmask(b) if ma is nomask and mb is nomask: m = nomask else: ma = getmaskarray(a) mb = getmaskarray(b) m = logical_or.outer(ma, mb) d = umath.minimum.outer(filled(a), filled(b)) return masked_array(d, m) minimum = _minimum_operation () class _maximum_operation: "Object to calculate maxima" def __init__ (self): """maximum(a, b) or maximum(a) In one argument case returns the scalar maximum. """ pass def __call__ (self, a, b=None): "Execute the call behavior." if b is None: m = getmask(a) if m is nomask: d = amax(filled(a).ravel()) return d ac = a.compressed() if len(ac) == 0: return masked else: return amax(ac.raw_data()) else: return where(greater(a, b), a, b) def reduce (self, target, axis=0): """Reduce target along the given axis.""" m = getmask(target) if m is nomask: t = filled(target) return masked_array (umath.maximum.reduce (t, axis)) else: t = umath.maximum.reduce(filled(target, maximum_fill_value(target)), axis) m = umath.logical_and.reduce(m, axis) return masked_array(t, m, get_fill_value(target)) def outer (self, a, b): "Return the function applied to the outer product of a and b." ma = getmask(a) mb = getmask(b) if ma is nomask and mb is nomask: m = nomask else: ma = getmaskarray(a) mb = getmaskarray(b) m = logical_or.outer(ma, mb) d = umath.maximum.outer(filled(a), filled(b)) return masked_array(d, m) maximum = _maximum_operation () def sort (x, axis = -1, fill_value=None): """If x does not have a mask, return a masked array formed from the result of numeric.sort(x, axis). Otherwise, fill x with fill_value. Sort it. Set a mask where the result is equal to fill_value. Note that this may have unintended consequences if the data contains the fill value at a non-masked site. If fill_value is not given the default fill value for x's type will be used. """ if fill_value is None: fill_value = default_fill_value (x) d = filled(x, fill_value) s = fromnumeric.sort(d, axis) if getmask(x) is nomask: return masked_array(s) return masked_values(s, fill_value, copy=0) def diagonal(a, k = 0, axis1=0, axis2=1): """diagonal(a,k=0,axis1=0, axis2=1) = the k'th diagonal of a""" d = fromnumeric.diagonal(filled(a), k, axis1, axis2) m = getmask(a) if m is nomask: return masked_array(d, m) else: return masked_array(d, fromnumeric.diagonal(m, k, axis1, axis2)) def trace (a, offset=0, axis1=0, axis2=1, dtype=None, out=None): """trace(a,offset=0, axis1=0, axis2=1) returns the sum along diagonals (defined by the last two dimenions) of the array. """ return diagonal(a, offset, axis1, axis2).sum(dtype=dtype) def argsort (x, axis = -1, out=None, fill_value=None): """Treating masked values as if they have the value fill_value, return sort indices for sorting along given axis. if fill_value is None, use get_fill_value(x) Returns a numpy array. """ d = filled(x, fill_value) return fromnumeric.argsort(d, axis) def argmin (x, axis = -1, out=None, fill_value=None): """Treating masked values as if they have the value fill_value, return indices for minimum values along given axis. if fill_value is None, use get_fill_value(x). Returns a numpy array if x has more than one dimension. Otherwise, returns a scalar index. """ d = filled(x, fill_value) return fromnumeric.argmin(d, axis) def argmax (x, axis = -1, out=None, fill_value=None): """Treating masked values as if they have the value fill_value, return sort indices for maximum along given axis. if fill_value is None, use -get_fill_value(x) if it exists. Returns a numpy array if x has more than one dimension. Otherwise, returns a scalar index. """ if fill_value is None: fill_value = default_fill_value (x) try: fill_value = - fill_value except: pass d = filled(x, fill_value) return fromnumeric.argmax(d, axis) def fromfunction (f, s): """apply f to s to create array as in umath.""" return masked_array(numeric.fromfunction(f, s)) def asarray(data, dtype=None): """asarray(data, dtype) = array(data, dtype, copy=0) """ if isinstance(data, MaskedArray) and \ (dtype is None or dtype == data.dtype): return data return array(data, dtype=dtype, copy=0) # Add methods to support ndarray interface # XXX: I is better to to change the masked_*_operation adaptors # XXX: to wrap ndarray methods directly to create ma.array methods. def _m(f): return types.MethodType(f, None, array) def not_implemented(*args, **kwds): raise NotImplementedError("not yet implemented for numpy.ma arrays") array.all = _m(alltrue) array.any = _m(sometrue) array.argmax = _m(argmax) array.argmin = _m(argmin) array.argsort = _m(argsort) array.base = property(_m(not_implemented)) array.byteswap = _m(not_implemented) def _choose(self, *args, **kwds): return choose(self, args) array.choose = _m(_choose) del _choose def _clip(self,a_min,a_max,out=None): return MaskedArray(data = self.data.clip(asarray(a_min).data, asarray(a_max).data), mask = mask_or(self.mask, mask_or(getmask(a_min), getmask(a_max)))) array.clip = _m(_clip) def _compress(self, cond, axis=None, out=None): return compress(cond, self, axis) array.compress = _m(_compress) del _compress array.conj = array.conjugate = _m(conjugate) array.copy = _m(not_implemented) def _cumprod(self, axis=None, dtype=None, out=None): m = self.mask if m is not nomask: m = umath.logical_or.accumulate(self.mask, axis) return MaskedArray(data = self.filled(1).cumprod(axis, dtype), mask=m) array.cumprod = _m(_cumprod) def _cumsum(self, axis=None, dtype=None, out=None): m = self.mask if m is not nomask: m = umath.logical_or.accumulate(self.mask, axis) return MaskedArray(data=self.filled(0).cumsum(axis, dtype), mask=m) array.cumsum = _m(_cumsum) array.diagonal = _m(diagonal) array.dump = _m(not_implemented) array.dumps = _m(not_implemented) array.fill = _m(not_implemented) array.flags = property(_m(not_implemented)) array.flatten = _m(ravel) array.getfield = _m(not_implemented) def _max(a, axis=None, out=None): if out is not None: raise TypeError("Output arrays Unsupported for masked arrays") if axis is None: return maximum(a) else: return maximum.reduce(a, axis) array.max = _m(_max) del _max def _min(a, axis=None, out=None): if out is not None: raise TypeError("Output arrays Unsupported for masked arrays") if axis is None: return minimum(a) else: return minimum.reduce(a, axis) array.min = _m(_min) del _min array.mean = _m(new_average) array.nbytes = property(_m(not_implemented)) array.newbyteorder = _m(not_implemented) array.nonzero = _m(nonzero) array.prod = _m(product) def _ptp(a,axis=None,out=None): return a.max(axis, out)-a.min(axis) array.ptp = _m(_ptp) array.repeat = _m(new_repeat) array.resize = _m(resize) array.searchsorted = _m(not_implemented) array.setfield = _m(not_implemented) array.setflags = _m(not_implemented) array.sort = _m(not_implemented) # NB: ndarray.sort is inplace def _squeeze(self): try: result = MaskedArray(data = self.data.squeeze(), mask = self.mask.squeeze()) except AttributeError: result = _wrapit(self, 'squeeze') return result array.squeeze = _m(_squeeze) array.strides = property(_m(not_implemented)) array.sum = _m(sum) def _swapaxes(self, axis1, axis2): return MaskedArray(data = self.data.swapaxes(axis1, axis2), mask = self.mask.swapaxes(axis1, axis2)) array.swapaxes = _m(_swapaxes) array.take = _m(new_take) array.tofile = _m(not_implemented) array.trace = _m(trace) array.transpose = _m(transpose) def _var(self,axis=None,dtype=None, out=None): if axis is None: return numeric.asarray(self.compressed()).var() a = self.swapaxes(axis, 0) a = a - a.mean(axis=0) a *= a a /= a.count(axis=0) return a.swapaxes(0, axis).sum(axis) def _std(self,axis=None, dtype=None, out=None): return (self.var(axis, dtype))**0.5 array.var = _m(_var) array.std = _m(_std) array.view = _m(not_implemented) array.round = _m(around) del _m, not_implemented masked = MaskedArray(0, int, mask=1) def repeat(a, repeats, axis=0): return new_repeat(a, repeats, axis) def average(a, axis=0, weights=None, returned=0): return new_average(a, axis, weights, returned) def take(a, indices, axis=0): return new_take(a, indices, axis) numpy-1.8.2/numpy/oldnumeric/array_printer.py0000664000175100017510000000101112370216243022561 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function __all__ = ['array2string'] from numpy import array2string as _array2string def array2string(a, max_line_width=None, precision=None, suppress_small=None, separator=' ', array_output=0): if array_output: prefix="array(" style=repr else: prefix = "" style=str return _array2string(a, max_line_width, precision, suppress_small, separator, prefix, style) numpy-1.8.2/numpy/linalg/0000775000175100017510000000000012371375430016447 5ustar vagrantvagrant00000000000000numpy-1.8.2/numpy/linalg/lapack_litemodule.c0000664000175100017510000007724512370216243022303 0ustar vagrantvagrant00000000000000/*This module contributed by Doug Heisterkamp Modified by Jim Hugunin More modifications by Jeff Whitaker */ #define NPY_NO_DEPRECATED_API NPY_API_VERSION #include "Python.h" #include "numpy/arrayobject.h" #ifdef NO_APPEND_FORTRAN # define FNAME(x) x #else # define FNAME(x) x##_ #endif 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, double s[], double *rcond, int *rank, 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); extern int FNAME(zgeqrf)(int *m, int *n, f2c_doublecomplex a[], int *lda, f2c_doublecomplex tau[], f2c_doublecomplex work[], int *lwork, int *info); extern int FNAME(dorgqr)(int *m, int *n, int *k, double a[], int *lda, double tau[], double work[], int *lwork, int *info); extern int FNAME(zungqr)(int *m, int *n, int *k, f2c_doublecomplex a[], int *lda, f2c_doublecomplex tau[], f2c_doublecomplex work[], int *lwork, int *info); extern int FNAME(xerbla)(char *srname, int *info); static PyObject *LapackError; #define TRY(E) if (!(E)) return NULL static int check_object(PyObject *ob, int t, char *obname, char *tname, char *funname) { if (!PyArray_Check(ob)) { PyErr_Format(LapackError, "Expected an array for parameter %s in lapack_lite.%s", obname, funname); return 0; } else if (!PyArray_IS_C_CONTIGUOUS((PyArrayObject *)ob)) { PyErr_Format(LapackError, "Parameter %s is not contiguous in lapack_lite.%s", obname, funname); return 0; } else if (!(PyArray_TYPE((PyArrayObject *)ob) == t)) { PyErr_Format(LapackError, "Parameter %s is not of type %s in lapack_lite.%s", obname, tname, funname); return 0; } else if (PyArray_ISBYTESWAPPED((PyArrayObject *)ob)) { PyErr_Format(LapackError, "Parameter %s has non-native byte order in lapack_lite.%s", obname, funname); return 0; } else { return 1; } } #define CHDATA(p) ((char *) PyArray_DATA((PyArrayObject *)p)) #define SHDATA(p) ((short int *) PyArray_DATA((PyArrayObject *)p)) #define DDATA(p) ((double *) PyArray_DATA((PyArrayObject *)p)) #define FDATA(p) ((float *) PyArray_DATA((PyArrayObject *)p)) #define CDATA(p) ((f2c_complex *) PyArray_DATA((PyArrayObject *)p)) #define ZDATA(p) ((f2c_doublecomplex *) PyArray_DATA((PyArrayObject *)p)) #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__; int m; int n; int nrhs; PyObject *a; int lda; PyObject *b; int ldb; PyObject *s; double rcond; int rank; PyObject *work; PyObject *iwork; int lwork; int info; TRY(PyArg_ParseTuple(args,"iiiOiOiOdiOiOi", &m,&n,&nrhs,&a,&lda,&b,&ldb,&s,&rcond, &rank,&work,&lwork,&iwork,&info)); TRY(check_object(a,NPY_DOUBLE,"a","NPY_DOUBLE","dgelsd")); TRY(check_object(b,NPY_DOUBLE,"b","NPY_DOUBLE","dgelsd")); TRY(check_object(s,NPY_DOUBLE,"s","NPY_DOUBLE","dgelsd")); TRY(check_object(work,NPY_DOUBLE,"work","NPY_DOUBLE","dgelsd")); TRY(check_object(iwork,NPY_INT,"iwork","NPY_INT","dgelsd")); lapack_lite_status__ = \ FNAME(dgelsd)(&m,&n,&nrhs,DDATA(a),&lda,DDATA(b),&ldb, DDATA(s),&rcond,&rank,DDATA(work),&lwork, IDATA(iwork),&info); if (PyErr_Occurred()) { return NULL; } return Py_BuildValue("{s:i,s:i,s:i,s:i,s:i,s:i,s:d,s:i,s:i,s:i}","dgelsd_", lapack_lite_status__,"m",m,"n",n,"nrhs",nrhs, "lda",lda,"ldb",ldb,"rcond",rcond,"rank",rank, "lwork",lwork,"info",info); } 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__; int m, n, lwork; PyObject *a, *tau, *work; int lda; int info; TRY(PyArg_ParseTuple(args,"iiOiOOii",&m,&n,&a,&lda,&tau,&work,&lwork,&info)); /* check objects and convert to right storage order */ TRY(check_object(a,NPY_DOUBLE,"a","NPY_DOUBLE","dgeqrf")); TRY(check_object(tau,NPY_DOUBLE,"tau","NPY_DOUBLE","dgeqrf")); TRY(check_object(work,NPY_DOUBLE,"work","NPY_DOUBLE","dgeqrf")); lapack_lite_status__ = \ FNAME(dgeqrf)(&m, &n, DDATA(a), &lda, DDATA(tau), DDATA(work), &lwork, &info); if (PyErr_Occurred()) { return NULL; } return Py_BuildValue("{s:i,s:i,s:i,s:i,s:i,s:i}","dgeqrf_", lapack_lite_status__,"m",m,"n",n,"lda",lda, "lwork",lwork,"info",info); } static PyObject * lapack_lite_dorgqr(PyObject *NPY_UNUSED(self), PyObject *args) { int lapack_lite_status__; int m, n, k, lwork; PyObject *a, *tau, *work; int lda; int info; TRY(PyArg_ParseTuple(args,"iiiOiOOii", &m, &n, &k, &a, &lda, &tau, &work, &lwork, &info)); TRY(check_object(a,NPY_DOUBLE,"a","NPY_DOUBLE","dorgqr")); TRY(check_object(tau,NPY_DOUBLE,"tau","NPY_DOUBLE","dorgqr")); TRY(check_object(work,NPY_DOUBLE,"work","NPY_DOUBLE","dorgqr")); lapack_lite_status__ = \ FNAME(dorgqr)(&m, &n, &k, DDATA(a), &lda, DDATA(tau), DDATA(work), &lwork, &info); if (PyErr_Occurred()) { return NULL; } return Py_BuildValue("{s:i,s:i}","dorgqr_",lapack_lite_status__, "info",info); } 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__; int m; int n; int nrhs; PyObject *a; int lda; PyObject *b; int ldb; PyObject *s; double rcond; int rank; PyObject *work; int lwork; PyObject *rwork; PyObject *iwork; int info; TRY(PyArg_ParseTuple(args,"iiiOiOiOdiOiOOi", &m,&n,&nrhs,&a,&lda,&b,&ldb,&s,&rcond, &rank,&work,&lwork,&rwork,&iwork,&info)); TRY(check_object(a,NPY_CDOUBLE,"a","NPY_CDOUBLE","zgelsd")); TRY(check_object(b,NPY_CDOUBLE,"b","NPY_CDOUBLE","zgelsd")); TRY(check_object(s,NPY_DOUBLE,"s","NPY_DOUBLE","zgelsd")); TRY(check_object(work,NPY_CDOUBLE,"work","NPY_CDOUBLE","zgelsd")); TRY(check_object(rwork,NPY_DOUBLE,"rwork","NPY_DOUBLE","zgelsd")); TRY(check_object(iwork,NPY_INT,"iwork","NPY_INT","zgelsd")); lapack_lite_status__ = \ FNAME(zgelsd)(&m,&n,&nrhs,ZDATA(a),&lda,ZDATA(b),&ldb,DDATA(s),&rcond, &rank,ZDATA(work),&lwork,DDATA(rwork),IDATA(iwork),&info); if (PyErr_Occurred()) { return NULL; } return Py_BuildValue("{s:i,s:i,s:i,s:i,s:i,s:i,s:i,s:i,s:i}","zgelsd_", lapack_lite_status__,"m",m,"n",n,"nrhs",nrhs,"lda",lda, "ldb",ldb,"rank",rank,"lwork",lwork,"info",info); } 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__; int m, n, lwork; PyObject *a, *tau, *work; int lda; int info; TRY(PyArg_ParseTuple(args,"iiOiOOii",&m,&n,&a,&lda,&tau,&work,&lwork,&info)); /* check objects and convert to right storage order */ TRY(check_object(a,NPY_CDOUBLE,"a","NPY_CDOUBLE","zgeqrf")); TRY(check_object(tau,NPY_CDOUBLE,"tau","NPY_CDOUBLE","zgeqrf")); TRY(check_object(work,NPY_CDOUBLE,"work","NPY_CDOUBLE","zgeqrf")); lapack_lite_status__ = \ FNAME(zgeqrf)(&m, &n, ZDATA(a), &lda, ZDATA(tau), ZDATA(work), &lwork, &info); if (PyErr_Occurred()) { return NULL; } return Py_BuildValue("{s:i,s:i,s:i,s:i,s:i,s:i}","zgeqrf_",lapack_lite_status__,"m",m,"n",n,"lda",lda,"lwork",lwork,"info",info); } static PyObject * lapack_lite_zungqr(PyObject *NPY_UNUSED(self), PyObject *args) { int lapack_lite_status__; int m, n, k, lwork; PyObject *a, *tau, *work; int lda; int info; TRY(PyArg_ParseTuple(args,"iiiOiOOii", &m, &n, &k, &a, &lda, &tau, &work, &lwork, &info)); TRY(check_object(a,NPY_CDOUBLE,"a","NPY_CDOUBLE","zungqr")); TRY(check_object(tau,NPY_CDOUBLE,"tau","NPY_CDOUBLE","zungqr")); TRY(check_object(work,NPY_CDOUBLE,"work","NPY_CDOUBLE","zungqr")); lapack_lite_status__ = \ FNAME(zungqr)(&m, &n, &k, ZDATA(a), &lda, ZDATA(tau), ZDATA(work), &lwork, &info); if (PyErr_Occurred()) { return NULL; } return Py_BuildValue("{s:i,s:i}","zungqr_",lapack_lite_status__, "info",info); } static PyObject * lapack_lite_xerbla(PyObject *NPY_UNUSED(self), PyObject *args) { int info = -1; NPY_BEGIN_THREADS_DEF; NPY_BEGIN_THREADS; FNAME(xerbla)("test", &info); NPY_END_THREADS; if (PyErr_Occurred()) { return NULL; } Py_INCREF(Py_None); return Py_None; } #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), { NULL,NULL,0, NULL} }; static char lapack_lite_module_documentation[] = ""; #if PY_MAJOR_VERSION >= 3 static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, "lapack_lite", NULL, -1, lapack_lite_module_methods, NULL, NULL, NULL, NULL }; #endif /* Initialization function for the module */ #if PY_MAJOR_VERSION >= 3 #define RETVAL m PyMODINIT_FUNC PyInit_lapack_lite(void) #else #define RETVAL PyMODINIT_FUNC initlapack_lite(void) #endif { PyObject *m,*d; #if PY_MAJOR_VERSION >= 3 m = PyModule_Create(&moduledef); #else m = Py_InitModule4("lapack_lite", lapack_lite_module_methods, lapack_lite_module_documentation, (PyObject*)NULL,PYTHON_API_VERSION); #endif if (m == NULL) { return RETVAL; } import_array(); d = PyModule_GetDict(m); LapackError = PyErr_NewException("lapack_lite.LapackError", NULL, NULL); PyDict_SetItemString(d, "LapackError", LapackError); return RETVAL; } numpy-1.8.2/numpy/linalg/info.py0000664000175100017510000000225612370216242017753 0ustar vagrantvagrant00000000000000"""\ Core Linear Algebra Tools ------------------------- Linear algebra basics: - norm Vector or matrix norm - inv Inverse of a square matrix - solve Solve a linear system of equations - det Determinant of a square matrix - lstsq Solve linear least-squares problem - pinv Pseudo-inverse (Moore-Penrose) calculated using a singular value decomposition - matrix_power Integer power of a square matrix Eigenvalues and decompositions: - eig Eigenvalues and vectors of a square matrix - eigh Eigenvalues and eigenvectors of a Hermitian matrix - eigvals Eigenvalues of a square matrix - eigvalsh Eigenvalues of a Hermitian matrix - qr QR decomposition of a matrix - svd Singular value decomposition of a matrix - cholesky Cholesky decomposition of a matrix Tensor operations: - tensorsolve Solve a linear tensor equation - tensorinv Calculate an inverse of a tensor Exceptions: - LinAlgError Indicates a failed linear algebra operation """ from __future__ import division, absolute_import, print_function depends = ['core'] numpy-1.8.2/numpy/linalg/setup.py0000664000175100017510000000354412370216242020161 0ustar vagrantvagrant00000000000000from __future__ import division, print_function import os import sys def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration from numpy.distutils.system_info import get_info config = Configuration('linalg', parent_package, top_path) config.add_data_dir('tests') # Configure lapack_lite src_dir = 'lapack_lite' lapack_lite_src = [ os.path.join(src_dir, 'python_xerbla.c'), os.path.join(src_dir, 'zlapack_lite.c'), os.path.join(src_dir, 'dlapack_lite.c'), os.path.join(src_dir, 'blas_lite.c'), os.path.join(src_dir, 'dlamch.c'), os.path.join(src_dir, 'f2c_lite.c'), os.path.join(src_dir, 'f2c.h'), ] lapack_info = get_info('lapack_opt', 0) # and {} def get_lapack_lite_sources(ext, build_dir): if not lapack_info: print("### Warning: Using unoptimized lapack ###") return ext.depends[:-1] else: if sys.platform=='win32': print("### Warning: python_xerbla.c is disabled ###") return ext.depends[:1] return ext.depends[:2] config.add_extension('lapack_lite', sources = [get_lapack_lite_sources], depends = ['lapack_litemodule.c'] + lapack_lite_src, extra_info = lapack_info ) # umath_linalg module config.add_extension('_umath_linalg', sources = [get_lapack_lite_sources], depends = ['umath_linalg.c.src'] + lapack_lite_src, extra_info = lapack_info, libraries = ['npymath'], ) return config if __name__ == '__main__': from numpy.distutils.core import setup setup(configuration=configuration) numpy-1.8.2/numpy/linalg/tests/0000775000175100017510000000000012371375430017611 5ustar vagrantvagrant00000000000000numpy-1.8.2/numpy/linalg/tests/test_linalg.py0000664000175100017510000011622612370216243022473 0ustar vagrantvagrant00000000000000""" Test functions for linalg module """ from __future__ import division, absolute_import, print_function import os import sys import itertools import traceback import numpy as np from numpy import array, single, double, csingle, cdouble, dot, identity from numpy import multiply, atleast_2d, inf, asarray, matrix from numpy import linalg from numpy.linalg import matrix_power, norm, matrix_rank from numpy.testing import ( assert_, assert_equal, assert_raises, assert_array_equal, assert_almost_equal, assert_allclose, run_module_suite, dec ) def ifthen(a, b): return not a or b def imply(a, b): return not a or b old_assert_almost_equal = assert_almost_equal def assert_almost_equal(a, b, **kw): if asarray(a).dtype.type in (single, csingle): decimal = 6 else: decimal = 12 old_assert_almost_equal(a, b, decimal=decimal, **kw) def get_real_dtype(dtype): return {single: single, double: double, csingle: single, cdouble: double}[dtype] def get_complex_dtype(dtype): return {single: csingle, double: cdouble, csingle: csingle, cdouble: cdouble}[dtype] def get_rtol(dtype): # Choose a safe rtol if dtype in (single, csingle): return 1e-5 else: return 1e-11 class LinalgCase(object): def __init__(self, name, a, b, exception_cls=None): assert isinstance(name, str) self.name = name self.a = a self.b = b self.exception_cls = exception_cls def check(self, do): if self.exception_cls is None: do(self.a, self.b) else: assert_raises(self.exception_cls, do, self.a, self.b) def __repr__(self): return "" % (self.name,) # # Base test cases # np.random.seed(1234) SQUARE_CASES = [ LinalgCase("single", array([[1., 2.], [3., 4.]], dtype=single), array([2., 1.], dtype=single)), LinalgCase("double", array([[1., 2.], [3., 4.]], dtype=double), array([2., 1.], dtype=double)), LinalgCase("double_2", array([[1., 2.], [3., 4.]], dtype=double), array([[2., 1., 4.], [3., 4., 6.]], dtype=double)), LinalgCase("csingle", array([[1.+2j, 2+3j], [3+4j, 4+5j]], dtype=csingle), array([2.+1j, 1.+2j], dtype=csingle)), LinalgCase("cdouble", array([[1.+2j, 2+3j], [3+4j, 4+5j]], dtype=cdouble), array([2.+1j, 1.+2j], dtype=cdouble)), LinalgCase("cdouble_2", array([[1.+2j, 2+3j], [3+4j, 4+5j]], dtype=cdouble), array([[2.+1j, 1.+2j, 1+3j], [1-2j, 1-3j, 1-6j]], dtype=cdouble)), LinalgCase("empty", atleast_2d(array([], dtype = double)), atleast_2d(array([], dtype = double)), linalg.LinAlgError), LinalgCase("8x8", np.random.rand(8, 8), np.random.rand(8)), LinalgCase("1x1", np.random.rand(1, 1), np.random.rand(1)), LinalgCase("nonarray", [[1, 2], [3, 4]], [2, 1]), LinalgCase("matrix_b_only", array([[1., 2.], [3., 4.]]), matrix([2., 1.]).T), LinalgCase("matrix_a_and_b", matrix([[1., 2.], [3., 4.]]), matrix([2., 1.]).T), ] NONSQUARE_CASES = [ LinalgCase("single_nsq_1", array([[1., 2., 3.], [3., 4., 6.]], dtype=single), array([2., 1.], dtype=single)), LinalgCase("single_nsq_2", array([[1., 2.], [3., 4.], [5., 6.]], dtype=single), array([2., 1., 3.], dtype=single)), LinalgCase("double_nsq_1", array([[1., 2., 3.], [3., 4., 6.]], dtype=double), array([2., 1.], dtype=double)), LinalgCase("double_nsq_2", array([[1., 2.], [3., 4.], [5., 6.]], dtype=double), array([2., 1., 3.], dtype=double)), LinalgCase("csingle_nsq_1", array([[1.+1j, 2.+2j, 3.-3j], [3.-5j, 4.+9j, 6.+2j]], dtype=csingle), array([2.+1j, 1.+2j], dtype=csingle)), LinalgCase("csingle_nsq_2", array([[1.+1j, 2.+2j], [3.-3j, 4.-9j], [5.-4j, 6.+8j]], dtype=csingle), array([2.+1j, 1.+2j, 3.-3j], dtype=csingle)), LinalgCase("cdouble_nsq_1", array([[1.+1j, 2.+2j, 3.-3j], [3.-5j, 4.+9j, 6.+2j]], dtype=cdouble), array([2.+1j, 1.+2j], dtype=cdouble)), LinalgCase("cdouble_nsq_2", array([[1.+1j, 2.+2j], [3.-3j, 4.-9j], [5.-4j, 6.+8j]], dtype=cdouble), array([2.+1j, 1.+2j, 3.-3j], dtype=cdouble)), LinalgCase("cdouble_nsq_1_2", array([[1.+1j, 2.+2j, 3.-3j], [3.-5j, 4.+9j, 6.+2j]], dtype=cdouble), array([[2.+1j, 1.+2j], [1-1j, 2-2j]], dtype=cdouble)), LinalgCase("cdouble_nsq_2_2", array([[1.+1j, 2.+2j], [3.-3j, 4.-9j], [5.-4j, 6.+8j]], dtype=cdouble), array([[2.+1j, 1.+2j], [1-1j, 2-2j], [1-1j, 2-2j]], dtype=cdouble)), LinalgCase("8x11", np.random.rand(8, 11), np.random.rand(11)), LinalgCase("1x5", np.random.rand(1, 5), np.random.rand(5)), LinalgCase("5x1", np.random.rand(5, 1), np.random.rand(1)), ] HERMITIAN_CASES = [ LinalgCase("hsingle", array([[1., 2.], [2., 1.]], dtype=single), None), LinalgCase("hdouble", array([[1., 2.], [2., 1.]], dtype=double), None), LinalgCase("hcsingle", array([[1., 2+3j], [2-3j, 1]], dtype=csingle), None), LinalgCase("hcdouble", array([[1., 2+3j], [2-3j, 1]], dtype=cdouble), None), LinalgCase("hempty", atleast_2d(array([], dtype = double)), None, linalg.LinAlgError), LinalgCase("hnonarray", [[1, 2], [2, 1]], None), LinalgCase("matrix_b_only", array([[1., 2.], [2., 1.]]), None), LinalgCase("hmatrix_a_and_b", matrix([[1., 2.], [2., 1.]]), None), LinalgCase("hmatrix_1x1", np.random.rand(1, 1), None), ] # # Gufunc test cases # GENERALIZED_SQUARE_CASES = [] GENERALIZED_NONSQUARE_CASES = [] GENERALIZED_HERMITIAN_CASES = [] for tgt, src in ((GENERALIZED_SQUARE_CASES, SQUARE_CASES), (GENERALIZED_NONSQUARE_CASES, NONSQUARE_CASES), (GENERALIZED_HERMITIAN_CASES, HERMITIAN_CASES)): for case in src: if not isinstance(case.a, np.ndarray): continue a = np.array([case.a, 2*case.a, 3*case.a]) if case.b is None: b = None else: b = np.array([case.b, 7*case.b, 6*case.b]) new_case = LinalgCase(case.name + "_tile3", a, b, case.exception_cls) tgt.append(new_case) a = np.array([case.a]*2*3).reshape((3, 2) + case.a.shape) if case.b is None: b = None else: b = np.array([case.b]*2*3).reshape((3, 2) + case.b.shape) new_case = LinalgCase(case.name + "_tile213", a, b, case.exception_cls) tgt.append(new_case) # # Generate stride combination variations of the above # def _stride_comb_iter(x): """ Generate cartesian product of strides for all axes """ if not isinstance(x, np.ndarray): yield x, "nop" return stride_set = [(1,)]*x.ndim stride_set[-1] = (1, 3, -4) if x.ndim > 1: stride_set[-2] = (1, 3, -4) if x.ndim > 2: stride_set[-3] = (1, -4) for repeats in itertools.product(*tuple(stride_set)): new_shape = [abs(a*b) for a, b in zip(x.shape, repeats)] slices = tuple([slice(None, None, repeat) for repeat in repeats]) # new array with different strides, but same data xi = np.empty(new_shape, dtype=x.dtype) xi.view(np.uint32).fill(0xdeadbeef) xi = xi[slices] xi[...] = x xi = xi.view(x.__class__) assert np.all(xi == x) yield xi, "stride_" + "_".join(["%+d" % j for j in repeats]) # generate also zero strides if possible if x.ndim >= 1 and x.shape[-1] == 1: s = list(x.strides) s[-1] = 0 xi = np.lib.stride_tricks.as_strided(x, strides=s) yield xi, "stride_xxx_0" if x.ndim >= 2 and x.shape[-2] == 1: s = list(x.strides) s[-2] = 0 xi = np.lib.stride_tricks.as_strided(x, strides=s) yield xi, "stride_xxx_0_x" if x.ndim >= 2 and x.shape[:-2] == (1, 1): s = list(x.strides) s[-1] = 0 s[-2] = 0 xi = np.lib.stride_tricks.as_strided(x, strides=s) yield xi, "stride_xxx_0_0" for src in (SQUARE_CASES, NONSQUARE_CASES, HERMITIAN_CASES, GENERALIZED_SQUARE_CASES, GENERALIZED_NONSQUARE_CASES, GENERALIZED_HERMITIAN_CASES): new_cases = [] for case in src: for a, a_tag in _stride_comb_iter(case.a): for b, b_tag in _stride_comb_iter(case.b): new_case = LinalgCase(case.name + "_" + a_tag + "_" + b_tag, a, b, exception_cls=case.exception_cls) new_cases.append(new_case) src.extend(new_cases) # # Test different routines against the above cases # def _check_cases(func, cases): for case in cases: try: case.check(func) except Exception: msg = "In test case: %r\n\n" % case msg += traceback.format_exc() raise AssertionError(msg) class LinalgTestCase(object): def test_sq_cases(self): _check_cases(self.do, SQUARE_CASES) class LinalgNonsquareTestCase(object): def test_sq_cases(self): _check_cases(self.do, NONSQUARE_CASES) class LinalgGeneralizedTestCase(object): @dec.slow def test_generalized_sq_cases(self): _check_cases(self.do, GENERALIZED_SQUARE_CASES) class LinalgGeneralizedNonsquareTestCase(object): @dec.slow def test_generalized_nonsq_cases(self): _check_cases(self.do, GENERALIZED_NONSQUARE_CASES) class HermitianTestCase(object): def test_herm_cases(self): _check_cases(self.do, HERMITIAN_CASES) class HermitianGeneralizedTestCase(object): @dec.slow def test_generalized_herm_cases(self): _check_cases(self.do, GENERALIZED_HERMITIAN_CASES) def dot_generalized(a, b): a = asarray(a) if a.ndim >= 3: if a.ndim == b.ndim: # matrix x matrix new_shape = a.shape[:-1] + b.shape[-1:] elif a.ndim == b.ndim + 1: # matrix x vector new_shape = a.shape[:-1] else: raise ValueError("Not implemented...") r = np.empty(new_shape, dtype=np.common_type(a, b)) for c in itertools.product(*map(range, a.shape[:-2])): r[c] = dot(a[c], b[c]) return r else: return dot(a, b) def identity_like_generalized(a): a = asarray(a) if a.ndim >= 3: r = np.empty(a.shape, dtype=a.dtype) for c in itertools.product(*map(range, a.shape[:-2])): r[c] = identity(a.shape[-2]) return r else: return identity(a.shape[0]) class TestSolve(LinalgTestCase, LinalgGeneralizedTestCase): def do(self, a, b): x = linalg.solve(a, b) assert_almost_equal(b, dot_generalized(a, x)) assert_(imply(isinstance(b, matrix), isinstance(x, matrix))) def test_types(self): def check(dtype): x = np.array([[1, 0.5], [0.5, 1]], dtype=dtype) assert_equal(linalg.solve(x, x).dtype, dtype) for dtype in [single, double, csingle, cdouble]: yield check, dtype def test_0_size(self): class ArraySubclass(np.ndarray): pass # Test system of 0x0 matrices a = np.arange(8).reshape(2, 2, 2) b = np.arange(6).reshape(1, 2, 3).view(ArraySubclass) expected = linalg.solve(a, b)[:, 0:0,:] result = linalg.solve(a[:, 0:0, 0:0], b[:, 0:0,:]) assert_array_equal(result, expected) assert_(isinstance(result, ArraySubclass)) # Test errors for non-square and only b's dimension being 0 assert_raises(linalg.LinAlgError, linalg.solve, a[:, 0:0, 0:1], b) assert_raises(ValueError, linalg.solve, a, b[:, 0:0,:]) # Test broadcasting error b = np.arange(6).reshape(1, 3, 2) # broadcasting error assert_raises(ValueError, linalg.solve, a, b) assert_raises(ValueError, linalg.solve, a[0:0], b[0:0]) # Test zero "single equations" with 0x0 matrices. b = np.arange(2).reshape(1, 2).view(ArraySubclass) expected = linalg.solve(a, b)[:, 0:0] result = linalg.solve(a[:, 0:0, 0:0], b[:, 0:0]) assert_array_equal(result, expected) assert_(isinstance(result, ArraySubclass)) b = np.arange(3).reshape(1, 3) assert_raises(ValueError, linalg.solve, a, b) assert_raises(ValueError, linalg.solve, a[0:0], b[0:0]) assert_raises(ValueError, linalg.solve, a[:, 0:0, 0:0], b) def test_0_size_k(self): # test zero multiple equation (K=0) case. class ArraySubclass(np.ndarray): pass a = np.arange(4).reshape(1, 2, 2) b = np.arange(6).reshape(3, 2, 1).view(ArraySubclass) expected = linalg.solve(a, b)[:,:, 0:0] result = linalg.solve(a, b[:,:, 0:0]) assert_array_equal(result, expected) assert_(isinstance(result, ArraySubclass)) # test both zero. expected = linalg.solve(a, b)[:, 0:0, 0:0] result = linalg.solve(a[:, 0:0, 0:0], b[:,0:0, 0:0]) assert_array_equal(result, expected) assert_(isinstance(result, ArraySubclass)) class TestInv(LinalgTestCase, LinalgGeneralizedTestCase): def do(self, a, b): a_inv = linalg.inv(a) assert_almost_equal(dot_generalized(a, a_inv), identity_like_generalized(a)) assert_(imply(isinstance(a, matrix), isinstance(a_inv, matrix))) def test_types(self): def check(dtype): x = np.array([[1, 0.5], [0.5, 1]], dtype=dtype) assert_equal(linalg.inv(x).dtype, dtype) for dtype in [single, double, csingle, cdouble]: yield check, dtype def test_0_size(self): # Check that all kinds of 0-sized arrays work class ArraySubclass(np.ndarray): pass a = np.zeros((0, 1, 1), dtype=np.int_).view(ArraySubclass) res = linalg.inv(a) assert_(res.dtype.type is np.float64) assert_equal(a.shape, res.shape) assert_(isinstance(a, ArraySubclass)) a = np.zeros((0, 0), dtype=np.complex64).view(ArraySubclass) res = linalg.inv(a) assert_(res.dtype.type is np.complex64) assert_equal(a.shape, res.shape) class TestEigvals(LinalgTestCase, LinalgGeneralizedTestCase): def do(self, a, b): ev = linalg.eigvals(a) evalues, evectors = linalg.eig(a) assert_almost_equal(ev, evalues) def test_types(self): def check(dtype): x = np.array([[1, 0.5], [0.5, 1]], dtype=dtype) assert_equal(linalg.eigvals(x).dtype, dtype) x = np.array([[1, 0.5], [-1, 1]], dtype=dtype) assert_equal(linalg.eigvals(x).dtype, get_complex_dtype(dtype)) for dtype in [single, double, csingle, cdouble]: yield check, dtype class TestEig(LinalgTestCase, LinalgGeneralizedTestCase): def do(self, a, b): evalues, evectors = linalg.eig(a) assert_allclose(dot_generalized(a, evectors), np.asarray(evectors) * np.asarray(evalues)[...,None,:], rtol=get_rtol(evalues.dtype)) assert_(imply(isinstance(a, matrix), isinstance(evectors, matrix))) def test_types(self): def check(dtype): x = np.array([[1, 0.5], [0.5, 1]], dtype=dtype) w, v = np.linalg.eig(x) assert_equal(w.dtype, dtype) assert_equal(v.dtype, dtype) x = np.array([[1, 0.5], [-1, 1]], dtype=dtype) w, v = np.linalg.eig(x) assert_equal(w.dtype, get_complex_dtype(dtype)) assert_equal(v.dtype, get_complex_dtype(dtype)) for dtype in [single, double, csingle, cdouble]: yield check, dtype class TestSVD(LinalgTestCase, LinalgGeneralizedTestCase): def do(self, a, b): u, s, vt = linalg.svd(a, 0) assert_allclose(a, dot_generalized(np.asarray(u) * np.asarray(s)[...,None,:], np.asarray(vt)), rtol=get_rtol(u.dtype)) assert_(imply(isinstance(a, matrix), isinstance(u, matrix))) assert_(imply(isinstance(a, matrix), isinstance(vt, matrix))) def test_types(self): def check(dtype): x = np.array([[1, 0.5], [0.5, 1]], dtype=dtype) u, s, vh = linalg.svd(x) assert_equal(u.dtype, dtype) assert_equal(s.dtype, get_real_dtype(dtype)) assert_equal(vh.dtype, dtype) s = linalg.svd(x, compute_uv=False) assert_equal(s.dtype, get_real_dtype(dtype)) for dtype in [single, double, csingle, cdouble]: yield check, dtype class TestCondSVD(LinalgTestCase, LinalgGeneralizedTestCase): def do(self, a, b): c = asarray(a) # a might be a matrix s = linalg.svd(c, compute_uv=False) old_assert_almost_equal(s[0]/s[-1], linalg.cond(a), decimal=5) class TestCond2(LinalgTestCase): def do(self, a, b): c = asarray(a) # a might be a matrix s = linalg.svd(c, compute_uv=False) old_assert_almost_equal(s[0]/s[-1], linalg.cond(a, 2), decimal=5) class TestCondInf(object): def test(self): A = array([[1., 0, 0], [0, -2., 0], [0, 0, 3.]]) assert_almost_equal(linalg.cond(A, inf), 3.) class TestPinv(LinalgTestCase): def do(self, a, b): a_ginv = linalg.pinv(a) assert_almost_equal(dot(a, a_ginv), identity(asarray(a).shape[0])) assert_(imply(isinstance(a, matrix), isinstance(a_ginv, matrix))) class TestDet(LinalgTestCase, LinalgGeneralizedTestCase): def do(self, a, b): d = linalg.det(a) (s, ld) = linalg.slogdet(a) if asarray(a).dtype.type in (single, double): ad = asarray(a).astype(double) else: ad = asarray(a).astype(cdouble) ev = linalg.eigvals(ad) assert_almost_equal(d, multiply.reduce(ev, axis=-1)) assert_almost_equal(s * np.exp(ld), multiply.reduce(ev, axis=-1)) s = np.atleast_1d(s) ld = np.atleast_1d(ld) m = (s != 0) assert_almost_equal(np.abs(s[m]), 1) assert_equal(ld[~m], -inf) def test_zero(self): assert_equal(linalg.det([[0.0]]), 0.0) assert_equal(type(linalg.det([[0.0]])), double) assert_equal(linalg.det([[0.0j]]), 0.0) assert_equal(type(linalg.det([[0.0j]])), cdouble) assert_equal(linalg.slogdet([[0.0]]), (0.0, -inf)) assert_equal(type(linalg.slogdet([[0.0]])[0]), double) assert_equal(type(linalg.slogdet([[0.0]])[1]), double) assert_equal(linalg.slogdet([[0.0j]]), (0.0j, -inf)) assert_equal(type(linalg.slogdet([[0.0j]])[0]), cdouble) assert_equal(type(linalg.slogdet([[0.0j]])[1]), double) def test_types(self): def check(dtype): x = np.array([[1, 0.5], [0.5, 1]], dtype=dtype) assert_equal(np.linalg.det(x).dtype, dtype) ph, s = np.linalg.slogdet(x) assert_equal(s.dtype, get_real_dtype(dtype)) assert_equal(ph.dtype, dtype) for dtype in [single, double, csingle, cdouble]: yield check, dtype class TestLstsq(LinalgTestCase, LinalgNonsquareTestCase): def do(self, a, b): arr = np.asarray(a) m, n = arr.shape u, s, vt = linalg.svd(a, 0) x, residuals, rank, sv = linalg.lstsq(a, b) if m <= n: assert_almost_equal(b, dot(a, x)) assert_equal(rank, m) else: assert_equal(rank, n) assert_almost_equal(sv, sv.__array_wrap__(s)) if rank == n and m > n: expect_resids = (np.asarray(abs(np.dot(a, x) - b))**2).sum(axis=0) expect_resids = np.asarray(expect_resids) if len(np.asarray(b).shape) == 1: expect_resids.shape = (1,) assert_equal(residuals.shape, expect_resids.shape) else: expect_resids = np.array([]).view(type(x)) assert_almost_equal(residuals, expect_resids) assert_(np.issubdtype(residuals.dtype, np.floating)) assert_(imply(isinstance(b, matrix), isinstance(x, matrix))) assert_(imply(isinstance(b, matrix), isinstance(residuals, matrix))) class TestMatrixPower(object): R90 = array([[0, 1], [-1, 0]]) Arb22 = array([[4, -7], [-2, 10]]) noninv = array([[1, 0], [0, 0]]) arbfloat = array([[0.1, 3.2], [1.2, 0.7]]) large = identity(10) t = large[1,:].copy() large[1,:] = large[0,:] large[0,:] = t def test_large_power(self): assert_equal(matrix_power(self.R90, 2**100+2**10+2**5+1), self.R90) def test_large_power_trailing_zero(self): assert_equal(matrix_power(self.R90, 2**100+2**10+2**5), identity(2)) def testip_zero(self): def tz(M): mz = matrix_power(M, 0) assert_equal(mz, identity(M.shape[0])) assert_equal(mz.dtype, M.dtype) for M in [self.Arb22, self.arbfloat, self.large]: yield tz, M def testip_one(self): def tz(M): mz = matrix_power(M, 1) assert_equal(mz, M) assert_equal(mz.dtype, M.dtype) for M in [self.Arb22, self.arbfloat, self.large]: yield tz, M def testip_two(self): def tz(M): mz = matrix_power(M, 2) assert_equal(mz, dot(M, M)) assert_equal(mz.dtype, M.dtype) for M in [self.Arb22, self.arbfloat, self.large]: yield tz, M def testip_invert(self): def tz(M): mz = matrix_power(M, -1) assert_almost_equal(identity(M.shape[0]), dot(mz, M)) for M in [self.R90, self.Arb22, self.arbfloat, self.large]: yield tz, M def test_invert_noninvertible(self): import numpy.linalg assert_raises(numpy.linalg.linalg.LinAlgError, lambda: matrix_power(self.noninv, -1)) class TestBoolPower(object): def test_square(self): A = array([[True, False], [True, True]]) assert_equal(matrix_power(A, 2), A) class TestEigvalsh(HermitianTestCase, HermitianGeneralizedTestCase): def do(self, a, b): # note that eigenvalue arrays must be sorted since # their order isn't guaranteed. ev = linalg.eigvalsh(a, 'L') evalues, evectors = linalg.eig(a) ev.sort(axis=-1) evalues.sort(axis=-1) assert_allclose(ev, evalues, rtol=get_rtol(ev.dtype)) ev2 = linalg.eigvalsh(a, 'U') ev2.sort(axis=-1) assert_allclose(ev2, evalues, rtol=get_rtol(ev.dtype)) def test_types(self): def check(dtype): x = np.array([[1, 0.5], [0.5, 1]], dtype=dtype) w = np.linalg.eigvalsh(x) assert_equal(w.dtype, get_real_dtype(dtype)) for dtype in [single, double, csingle, cdouble]: yield check, dtype def test_invalid(self): x = np.array([[1, 0.5], [0.5, 1]], dtype=np.float32) assert_raises(ValueError, np.linalg.eigvalsh, x, UPLO="lrong") assert_raises(ValueError, np.linalg.eigvalsh, x, "lower") assert_raises(ValueError, np.linalg.eigvalsh, x, "upper") def test_UPLO(self): Klo = np.array([[0, 0],[1, 0]], dtype=np.double) Kup = np.array([[0, 1],[0, 0]], dtype=np.double) tgt = np.array([-1, 1], dtype=np.double) rtol = get_rtol(np.double) # Check default is 'L' w = np.linalg.eigvalsh(Klo) assert_allclose(np.sort(w), tgt, rtol=rtol) # Check 'L' w = np.linalg.eigvalsh(Klo, UPLO='L') assert_allclose(np.sort(w), tgt, rtol=rtol) # Check 'l' w = np.linalg.eigvalsh(Klo, UPLO='l') assert_allclose(np.sort(w), tgt, rtol=rtol) # Check 'U' w = np.linalg.eigvalsh(Kup, UPLO='U') assert_allclose(np.sort(w), tgt, rtol=rtol) # Check 'u' w = np.linalg.eigvalsh(Kup, UPLO='u') assert_allclose(np.sort(w), tgt, rtol=rtol) class TestEigh(HermitianTestCase, HermitianGeneralizedTestCase): def do(self, a, b): # note that eigenvalue arrays must be sorted since # their order isn't guaranteed. ev, evc = linalg.eigh(a) evalues, evectors = linalg.eig(a) ev.sort(axis=-1) evalues.sort(axis=-1) assert_almost_equal(ev, evalues) assert_allclose(dot_generalized(a, evc), np.asarray(ev)[...,None,:] * np.asarray(evc), rtol=get_rtol(ev.dtype)) ev2, evc2 = linalg.eigh(a, 'U') ev2.sort(axis=-1) assert_almost_equal(ev2, evalues) assert_allclose(dot_generalized(a, evc2), np.asarray(ev2)[...,None,:] * np.asarray(evc2), rtol=get_rtol(ev.dtype), err_msg=repr(a)) def test_types(self): def check(dtype): x = np.array([[1, 0.5], [0.5, 1]], dtype=dtype) w, v = np.linalg.eigh(x) assert_equal(w.dtype, get_real_dtype(dtype)) assert_equal(v.dtype, dtype) for dtype in [single, double, csingle, cdouble]: yield check, dtype def test_invalid(self): x = np.array([[1, 0.5], [0.5, 1]], dtype=np.float32) assert_raises(ValueError, np.linalg.eigh, x, UPLO="lrong") assert_raises(ValueError, np.linalg.eigh, x, "lower") assert_raises(ValueError, np.linalg.eigh, x, "upper") def test_UPLO(self): Klo = np.array([[0, 0],[1, 0]], dtype=np.double) Kup = np.array([[0, 1],[0, 0]], dtype=np.double) tgt = np.array([-1, 1], dtype=np.double) rtol = get_rtol(np.double) # Check default is 'L' w, v = np.linalg.eigh(Klo) assert_allclose(np.sort(w), tgt, rtol=rtol) # Check 'L' w, v = np.linalg.eigh(Klo, UPLO='L') assert_allclose(np.sort(w), tgt, rtol=rtol) # Check 'l' w, v = np.linalg.eigh(Klo, UPLO='l') assert_allclose(np.sort(w), tgt, rtol=rtol) # Check 'U' w, v = np.linalg.eigh(Kup, UPLO='U') assert_allclose(np.sort(w), tgt, rtol=rtol) # Check 'u' w, v = np.linalg.eigh(Kup, UPLO='u') assert_allclose(np.sort(w), tgt, rtol=rtol) class _TestNorm(object): dt = None dec = None def test_empty(self): assert_equal(norm([]), 0.0) assert_equal(norm(array([], dtype=self.dt)), 0.0) assert_equal(norm(atleast_2d(array([], dtype=self.dt))), 0.0) def test_vector(self): a = [1, 2, 3, 4] b = [-1, -2, -3, -4] c = [-1, 2, -3, 4] def _test(v): np.testing.assert_almost_equal(norm(v), 30**0.5, decimal=self.dec) np.testing.assert_almost_equal(norm(v, inf), 4.0, decimal=self.dec) np.testing.assert_almost_equal(norm(v, -inf), 1.0, decimal=self.dec) np.testing.assert_almost_equal(norm(v, 1), 10.0, decimal=self.dec) np.testing.assert_almost_equal(norm(v, -1), 12.0/25, decimal=self.dec) np.testing.assert_almost_equal(norm(v, 2), 30**0.5, decimal=self.dec) np.testing.assert_almost_equal(norm(v, -2), ((205./144)**-0.5), decimal=self.dec) np.testing.assert_almost_equal(norm(v, 0), 4, decimal=self.dec) for v in (a, b, c,): _test(v) for v in (array(a, dtype=self.dt), array(b, dtype=self.dt), array(c, dtype=self.dt)): _test(v) def test_matrix(self): A = matrix([[1, 3], [5, 7]], dtype=self.dt) assert_almost_equal(norm(A), 84**0.5) assert_almost_equal(norm(A, 'fro'), 84**0.5) assert_almost_equal(norm(A, inf), 12.0) assert_almost_equal(norm(A, -inf), 4.0) assert_almost_equal(norm(A, 1), 10.0) assert_almost_equal(norm(A, -1), 6.0) assert_almost_equal(norm(A, 2), 9.1231056256176615) assert_almost_equal(norm(A, -2), 0.87689437438234041) assert_raises(ValueError, norm, A, 'nofro') assert_raises(ValueError, norm, A, -3) assert_raises(ValueError, norm, A, 0) def test_axis(self): # Vector norms. # Compare the use of `axis` with computing the norm of each row # or column separately. A = array([[1, 2, 3], [4, 5, 6]], dtype=self.dt) for order in [None, -1, 0, 1, 2, 3, np.Inf, -np.Inf]: expected0 = [norm(A[:, k], ord=order) for k in range(A.shape[1])] assert_almost_equal(norm(A, ord=order, axis=0), expected0) expected1 = [norm(A[k,:], ord=order) for k in range(A.shape[0])] assert_almost_equal(norm(A, ord=order, axis=1), expected1) # Matrix norms. B = np.arange(1, 25, dtype=self.dt).reshape(2, 3, 4) for order in [None, -2, 2, -1, 1, np.Inf, -np.Inf, 'fro']: assert_almost_equal(norm(A, ord=order), norm(A, ord=order, axis=(0, 1))) n = norm(B, ord=order, axis=(1, 2)) expected = [norm(B[k], ord=order) for k in range(B.shape[0])] assert_almost_equal(n, expected) n = norm(B, ord=order, axis=(2, 1)) expected = [norm(B[k].T, ord=order) for k in range(B.shape[0])] assert_almost_equal(n, expected) n = norm(B, ord=order, axis=(0, 2)) expected = [norm(B[:, k,:], ord=order) for k in range(B.shape[1])] assert_almost_equal(n, expected) n = norm(B, ord=order, axis=(0, 1)) expected = [norm(B[:,:, k], ord=order) for k in range(B.shape[2])] assert_almost_equal(n, expected) def test_bad_args(self): # Check that bad arguments raise the appropriate exceptions. A = array([[1, 2, 3], [4, 5, 6]], dtype=self.dt) B = np.arange(1, 25, dtype=self.dt).reshape(2, 3, 4) # Using `axis=` or passing in a 1-D array implies vector # norms are being computed, so also using `ord='fro'` raises a # ValueError. assert_raises(ValueError, norm, A, 'fro', 0) assert_raises(ValueError, norm, [3, 4], 'fro', None) # Similarly, norm should raise an exception when ord is any finite # number other than 1, 2, -1 or -2 when computing matrix norms. for order in [0, 3]: assert_raises(ValueError, norm, A, order, None) assert_raises(ValueError, norm, A, order, (0, 1)) assert_raises(ValueError, norm, B, order, (1, 2)) # Invalid axis assert_raises(ValueError, norm, B, None, 3) assert_raises(ValueError, norm, B, None, (2, 3)) assert_raises(ValueError, norm, B, None, (0, 1, 2)) def test_longdouble_norm(self): # Non-regression test: p-norm of longdouble would previously raise # UnboundLocalError. x = np.arange(10, dtype=np.longdouble) old_assert_almost_equal(norm(x, ord=3), 12.65, decimal=2) def test_intmin(self): # Non-regression test: p-norm of signed integer would previously do # float cast and abs in the wrong order. x = np.array([-2 ** 31], dtype=np.int32) old_assert_almost_equal(norm(x, ord=3), 2 ** 31, decimal=5) def test_complex_high_ord(self): # gh-4156 d = np.empty((2,), dtype=np.clongdouble) d[0] = 6+7j d[1] = -6+7j res = 11.615898132184 old_assert_almost_equal(np.linalg.norm(d, ord=3), res, decimal=10) d = d.astype(np.complex128) old_assert_almost_equal(np.linalg.norm(d, ord=3), res, decimal=9) d = d.astype(np.complex64) old_assert_almost_equal(np.linalg.norm(d, ord=3), res, decimal=5) class TestNormDouble(_TestNorm): dt = np.double dec = 12 class TestNormSingle(_TestNorm): dt = np.float32 dec = 6 class TestNormInt64(_TestNorm): dt = np.int64 dec = 12 class TestMatrixRank(object): def test_matrix_rank(self): # Full rank matrix yield assert_equal, 4, matrix_rank(np.eye(4)) # rank deficient matrix I=np.eye(4); I[-1, -1] = 0. yield assert_equal, matrix_rank(I), 3 # All zeros - zero rank yield assert_equal, matrix_rank(np.zeros((4, 4))), 0 # 1 dimension - rank 1 unless all 0 yield assert_equal, matrix_rank([1, 0, 0, 0]), 1 yield assert_equal, matrix_rank(np.zeros((4,))), 0 # accepts array-like yield assert_equal, matrix_rank([1]), 1 # greater than 2 dimensions raises error yield assert_raises, TypeError, matrix_rank, np.zeros((2, 2, 2)) # works on scalar yield assert_equal, matrix_rank(1), 1 def test_reduced_rank(): # Test matrices with reduced rank rng = np.random.RandomState(20120714) for i in range(100): # Make a rank deficient matrix X = rng.normal(size=(40, 10)) X[:, 0] = X[:, 1] + X[:, 2] # Assert that matrix_rank detected deficiency assert_equal(matrix_rank(X), 9) X[:, 3] = X[:, 4] + X[:, 5] assert_equal(matrix_rank(X), 8) class TestQR(object): def check_qr(self, a): # This test expects the argument `a` to be an ndarray or # a subclass of an ndarray of inexact type. a_type = type(a) a_dtype = a.dtype m, n = a.shape k = min(m, n) # mode == 'complete' q, r = linalg.qr(a, mode='complete') assert_(q.dtype == a_dtype) assert_(r.dtype == a_dtype) assert_(isinstance(q, a_type)) assert_(isinstance(r, a_type)) assert_(q.shape == (m, m)) assert_(r.shape == (m, n)) assert_almost_equal(dot(q, r), a) assert_almost_equal(dot(q.T.conj(), q), np.eye(m)) assert_almost_equal(np.triu(r), r) # mode == 'reduced' q1, r1 = linalg.qr(a, mode='reduced') assert_(q1.dtype == a_dtype) assert_(r1.dtype == a_dtype) assert_(isinstance(q1, a_type)) assert_(isinstance(r1, a_type)) assert_(q1.shape == (m, k)) assert_(r1.shape == (k, n)) assert_almost_equal(dot(q1, r1), a) assert_almost_equal(dot(q1.T.conj(), q1), np.eye(k)) assert_almost_equal(np.triu(r1), r1) # mode == 'r' r2 = linalg.qr(a, mode='r') assert_(r2.dtype == a_dtype) assert_(isinstance(r2, a_type)) assert_almost_equal(r2, r1) def test_qr_empty(self): a = np.zeros((0, 2)) assert_raises(linalg.LinAlgError, linalg.qr, a) def test_mode_raw(self): # The factorization is not unique and varies between libraries, # so it is not possible to check against known values. Functional # testing is a possibility, but awaits the exposure of more # of the functions in lapack_lite. Consequently, this test is # very limited in scope. Note that the results are in FORTRAN # order, hence the h arrays are transposed. a = array([[1, 2], [3, 4], [5, 6]], dtype=np.double) b = a.astype(np.single) # Test double h, tau = linalg.qr(a, mode='raw') assert_(h.dtype == np.double) assert_(tau.dtype == np.double) assert_(h.shape == (2, 3)) assert_(tau.shape == (2,)) h, tau = linalg.qr(a.T, mode='raw') assert_(h.dtype == np.double) assert_(tau.dtype == np.double) assert_(h.shape == (3, 2)) assert_(tau.shape == (2,)) def test_mode_all_but_economic(self): a = array([[1, 2], [3, 4]]) b = array([[1, 2], [3, 4], [5, 6]]) for dt in "fd": m1 = a.astype(dt) m2 = b.astype(dt) self.check_qr(m1) self.check_qr(m2) self.check_qr(m2.T) self.check_qr(matrix(m1)) for dt in "fd": m1 = 1 + 1j * a.astype(dt) m2 = 1 + 1j * b.astype(dt) self.check_qr(m1) self.check_qr(m2) self.check_qr(m2.T) self.check_qr(matrix(m1)) def test_byteorder_check(): # Byte order check should pass for native order if sys.byteorder == 'little': native = '<' else: native = '>' for dtt in (np.float32, np.float64): arr = np.eye(4, dtype=dtt) n_arr = arr.newbyteorder(native) sw_arr = arr.newbyteorder('S').byteswap() assert_equal(arr.dtype.byteorder, '=') for routine in (linalg.inv, linalg.det, linalg.pinv): # Normal call res = routine(arr) # Native but not '=' assert_array_equal(res, routine(n_arr)) # Swapped assert_array_equal(res, routine(sw_arr)) def test_generalized_raise_multiloop(): # It should raise an error even if the error doesn't occur in the # last iteration of the ufunc inner loop invertible = np.array([[1, 2], [3, 4]]) non_invertible = np.array([[1, 1], [1, 1]]) x = np.zeros([4, 4, 2, 2])[1::2] x[...] = invertible x[0, 0] = non_invertible assert_raises(np.linalg.LinAlgError, np.linalg.inv, x) def test_xerbla_override(): # Check that our xerbla has been successfully linked in. If it is not, # the default xerbla routine is called, which prints a message to stdout # and may, or may not, abort the process depending on the LAPACK package. from nose import SkipTest try: pid = os.fork() except (OSError, AttributeError): # fork failed, or not running on POSIX raise SkipTest("Not POSIX or fork failed.") if pid == 0: # child; close i/o file handles os.close(1) os.close(0) # Avoid producing core files. import resource resource.setrlimit(resource.RLIMIT_CORE, (0, 0)) # These calls may abort. try: np.linalg.lapack_lite.xerbla() except ValueError: pass except: os._exit(os.EX_CONFIG) try: a = np.array([[1]]) np.linalg.lapack_lite.dgetrf( 1, 1, a.astype(np.double), 0, # <- invalid value a.astype(np.intc), 0) except ValueError as e: if "DGETRF parameter number 4" in str(e): # success os._exit(os.EX_OK) # Did not abort, but our xerbla was not linked in. os._exit(os.EX_CONFIG) else: # parent pid, status = os.wait() if os.WEXITSTATUS(status) != os.EX_OK or os.WIFSIGNALED(status): raise SkipTest('Numpy xerbla not linked in.') if __name__ == "__main__": run_module_suite() numpy-1.8.2/numpy/linalg/tests/test_build.py0000664000175100017510000000332612370216243022320 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function from subprocess import call, PIPE, Popen import sys import re import numpy as np from numpy.linalg import lapack_lite from numpy.testing import TestCase, dec from numpy.compat import asbytes_nested class FindDependenciesLdd(object): def __init__(self): self.cmd = ['ldd'] try: p = Popen(self.cmd, stdout=PIPE, stderr=PIPE) stdout, stderr = p.communicate() 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) stdout, stderr = p.communicate() if not (p.returncode == 0): raise RuntimeError("Failed to check dependencies for %s" % libfile) return stdout def grep_dependencies(self, file, deps): stdout = self.get_dependencies(file) rdeps = dict([(dep, re.compile(dep)) for dep in deps]) founds = [] for l in stdout.splitlines(): for k, v in rdeps.items(): if v.search(l): founds.append(k) return founds class TestF77Mismatch(TestCase): @dec.skipif(not(sys.platform[:5] == 'linux'), "Skipping fortran compiler mismatch on non Linux platform") def test_lapack(self): f = FindDependenciesLdd() deps = f.grep_dependencies(lapack_lite.__file__, asbytes_nested(['libg2c', 'libgfortran'])) self.assertFalse(len(deps) > 1, """Both g77 and gfortran runtimes linked in lapack_lite ! This is likely to cause random crashes and wrong results. See numpy INSTALL.txt for more information.""") numpy-1.8.2/numpy/linalg/tests/test_regression.py0000664000175100017510000000534712370216243023406 0ustar vagrantvagrant00000000000000""" Test functions for linalg module """ from __future__ import division, absolute_import, print_function from numpy.testing import * import numpy as np from numpy import linalg, arange, float64, array, dot, transpose rlevel = 1 class TestRegression(TestCase): def test_eig_build(self, level = rlevel): """Ticket #652""" rva = array([1.03221168e+02 +0.j, -1.91843603e+01 +0.j, -6.04004526e-01+15.84422474j, -6.04004526e-01-15.84422474j, -1.13692929e+01 +0.j, -6.57612485e-01+10.41755503j, -6.57612485e-01-10.41755503j, 1.82126812e+01 +0.j, 1.06011014e+01 +0.j, 7.80732773e+00 +0.j, -7.65390898e-01 +0.j, 1.51971555e-15 +0.j, -1.51308713e-15 +0.j]) a = arange(13*13, dtype = float64) a.shape = (13, 13) a = a%17 va, ve = linalg.eig(a) va.sort() rva.sort() assert_array_almost_equal(va, rva) def test_eigh_build(self, level = rlevel): """Ticket 662.""" rvals = [68.60568999, 89.57756725, 106.67185574] cov = array([[ 77.70273908, 3.51489954, 15.64602427], [3.51489954, 88.97013878, -1.07431931], [15.64602427, -1.07431931, 98.18223512]]) vals, vecs = linalg.eigh(cov) assert_array_almost_equal(vals, rvals) def test_svd_build(self, level = rlevel): """Ticket 627.""" a = array([[ 0., 1.], [ 1., 1.], [ 2., 1.], [ 3., 1.]]) m, n = a.shape u, s, vh = linalg.svd(a) b = dot(transpose(u[:, n:]), a) assert_array_almost_equal(b, np.zeros((2, 2))) def test_norm_vector_badarg(self): """Regression for #786: Froebenius norm for vectors raises TypeError.""" self.assertRaises(ValueError, linalg.norm, array([1., 2., 3.]), 'fro') def test_lapack_endian(self): # For bug #1482 a = array([[5.7998084, -2.1825367 ], [-2.1825367, 9.85910595]], dtype='>f8') b = array(a, dtype=' 0.5) assert_equal(c, 1) if __name__ == '__main__': run_module_suite() numpy-1.8.2/numpy/linalg/tests/test_deprecations.py0000664000175100017510000000130612370216242023674 0ustar vagrantvagrant00000000000000"""Test deprecation and future warnings. """ import numpy as np from numpy.testing import assert_warns, run_module_suite def test_qr_mode_full_future_warning(): """Check mode='full' FutureWarning. In numpy 1.8 the mode options 'full' and 'economic' in linalg.qr were deprecated. The release date will probably be sometime in the summer of 2013. """ a = np.eye(2) assert_warns(DeprecationWarning, np.linalg.qr, a, mode='full') assert_warns(DeprecationWarning, np.linalg.qr, a, mode='f') assert_warns(DeprecationWarning, np.linalg.qr, a, mode='economic') assert_warns(DeprecationWarning, np.linalg.qr, a, mode='e') if __name__ == "__main__": run_module_suite() numpy-1.8.2/numpy/linalg/__init__.py0000664000175100017510000000430612370216243020556 0ustar vagrantvagrant00000000000000""" Core Linear Algebra Tools ========================= =============== ========================================================== Linear algebra basics ========================================================================== norm Vector or matrix norm inv Inverse of a square matrix solve Solve a linear system of equations det Determinant of a square matrix slogdet Logarithm of the determinant of a square matrix lstsq Solve linear least-squares problem pinv Pseudo-inverse (Moore-Penrose) calculated using a singular value decomposition matrix_power Integer power of a square matrix =============== ========================================================== =============== ========================================================== Eigenvalues and decompositions ========================================================================== eig Eigenvalues and vectors of a square matrix eigh Eigenvalues and eigenvectors of a Hermitian matrix eigvals Eigenvalues of a square matrix eigvalsh Eigenvalues of a Hermitian matrix qr QR decomposition of a matrix svd Singular value decomposition of a matrix cholesky Cholesky decomposition of a matrix =============== ========================================================== =============== ========================================================== Tensor operations ========================================================================== tensorsolve Solve a linear tensor equation tensorinv Calculate an inverse of a tensor =============== ========================================================== =============== ========================================================== Exceptions ========================================================================== LinAlgError Indicates a failed linear algebra operation =============== ========================================================== """ from __future__ import division, absolute_import, print_function # To get sub-modules from .info import __doc__ from .linalg import * from numpy.testing import Tester test = Tester().test bench = Tester().test numpy-1.8.2/numpy/linalg/linalg.py0000664000175100017510000020317712370216243020274 0ustar vagrantvagrant00000000000000"""Lite version of scipy.linalg. Notes ----- This module is a lite version of the linalg.py module in SciPy which contains high-level Python interface to the LAPACK library. The lite version only accesses the following LAPACK functions: dgesv, zgesv, dgeev, zgeev, dgesdd, zgesdd, dgelsd, zgelsd, dsyevd, zheevd, dgetrf, zgetrf, dpotrf, zpotrf, dgeqrf, zgeqrf, zungqr, dorgqr. """ from __future__ import division, absolute_import, print_function __all__ = ['matrix_power', 'solve', 'tensorsolve', 'tensorinv', 'inv', 'cholesky', 'eigvals', 'eigvalsh', 'pinv', 'slogdet', 'det', 'svd', 'eig', 'eigh', 'lstsq', 'norm', 'qr', 'cond', 'matrix_rank', 'LinAlgError'] import warnings from numpy.core import ( array, asarray, zeros, empty, empty_like, transpose, intc, single, double, csingle, cdouble, inexact, complexfloating, newaxis, ravel, all, Inf, dot, add, multiply, sqrt, maximum, fastCopyAndTranspose, sum, isfinite, size, finfo, errstate, geterrobj, longdouble, rollaxis, amin, amax, product, abs, broadcast ) from numpy.lib import triu, asfarray from numpy.linalg import lapack_lite, _umath_linalg from numpy.matrixlib.defmatrix import matrix_power from numpy.compat import asbytes # For Python2/3 compatibility _N = asbytes('N') _V = asbytes('V') _A = asbytes('A') _S = asbytes('S') _L = asbytes('L') fortran_int = intc # Error object class LinAlgError(Exception): """ Generic Python-exception-derived object raised by linalg functions. General purpose exception class, derived from Python's exception.Exception class, programmatically raised in linalg functions when a Linear Algebra-related condition would prevent further correct execution of the function. Parameters ---------- None Examples -------- >>> from numpy import linalg as LA >>> LA.inv(np.zeros((2,2))) Traceback (most recent call last): File "", line 1, in File "...linalg.py", line 350, in inv return wrap(solve(a, identity(a.shape[0], dtype=a.dtype))) File "...linalg.py", line 249, in solve raise LinAlgError('Singular matrix') numpy.linalg.LinAlgError: Singular matrix """ pass # Dealing with errors in _umath_linalg _linalg_error_extobj = None def _determine_error_states(): global _linalg_error_extobj errobj = geterrobj() bufsize = errobj[0] with errstate(invalid='call', over='ignore', divide='ignore', under='ignore'): invalid_call_errmask = geterrobj()[1] _linalg_error_extobj = [bufsize, invalid_call_errmask, None] _determine_error_states() def _raise_linalgerror_singular(err, flag): raise LinAlgError("Singular matrix") def _raise_linalgerror_nonposdef(err, flag): raise LinAlgError("Matrix is not positive definite") def _raise_linalgerror_eigenvalues_nonconvergence(err, flag): raise LinAlgError("Eigenvalues did not converge") def _raise_linalgerror_svd_nonconvergence(err, flag): raise LinAlgError("SVD did not converge") def get_linalg_error_extobj(callback): extobj = list(_linalg_error_extobj) extobj[2] = callback return extobj def _makearray(a): new = asarray(a) wrap = getattr(a, "__array_prepare__", new.__array_wrap__) return new, wrap def isComplexType(t): return issubclass(t, complexfloating) _real_types_map = {single : single, double : double, csingle : single, cdouble : double} _complex_types_map = {single : csingle, double : cdouble, csingle : csingle, cdouble : cdouble} def _realType(t, default=double): return _real_types_map.get(t, default) def _complexType(t, default=cdouble): return _complex_types_map.get(t, default) def _linalgRealType(t): """Cast the type t to either double or cdouble.""" return double _complex_types_map = {single : csingle, double : cdouble, csingle : csingle, cdouble : cdouble} def _commonType(*arrays): # in lite version, use higher precision (always double or cdouble) result_type = single is_complex = False for a in arrays: if issubclass(a.dtype.type, inexact): if isComplexType(a.dtype.type): is_complex = True rt = _realType(a.dtype.type, default=None) if rt is None: # unsupported inexact scalar raise TypeError("array type %s is unsupported in linalg" % (a.dtype.name,)) else: rt = double if rt is double: result_type = double if is_complex: t = cdouble result_type = _complex_types_map[result_type] else: t = double return t, result_type # _fastCopyAndTranpose assumes the input is 2D (as all the calls in here are). _fastCT = fastCopyAndTranspose def _to_native_byte_order(*arrays): ret = [] for arr in arrays: if arr.dtype.byteorder not in ('=', '|'): ret.append(asarray(arr, dtype=arr.dtype.newbyteorder('='))) else: ret.append(arr) if len(ret) == 1: return ret[0] else: return ret def _fastCopyAndTranspose(type, *arrays): cast_arrays = () for a in arrays: if a.dtype.type is type: cast_arrays = cast_arrays + (_fastCT(a),) else: cast_arrays = cast_arrays + (_fastCT(a.astype(type)),) if len(cast_arrays) == 1: return cast_arrays[0] else: return cast_arrays def _assertRank2(*arrays): for a in arrays: if len(a.shape) != 2: raise LinAlgError('%d-dimensional array given. Array must be ' 'two-dimensional' % len(a.shape)) def _assertRankAtLeast2(*arrays): for a in arrays: if len(a.shape) < 2: raise LinAlgError('%d-dimensional array given. Array must be ' 'at least two-dimensional' % len(a.shape)) def _assertSquareness(*arrays): for a in arrays: if max(a.shape) != min(a.shape): raise LinAlgError('Array must be square') def _assertNdSquareness(*arrays): for a in arrays: if max(a.shape[-2:]) != min(a.shape[-2:]): raise LinAlgError('Last 2 dimensions of the array must be square') def _assertFinite(*arrays): for a in arrays: if not (isfinite(a).all()): raise LinAlgError("Array must not contain infs or NaNs") def _assertNoEmpty2d(*arrays): for a in arrays: if a.size == 0 and product(a.shape[-2:]) == 0: raise LinAlgError("Arrays cannot be empty") # Linear equations def tensorsolve(a, b, axes=None): """ Solve the tensor equation ``a x = b`` for x. It is assumed that all indices of `x` are summed over in the product, together with the rightmost indices of `a`, as is done in, for example, ``tensordot(a, x, axes=len(b.shape))``. Parameters ---------- a : array_like Coefficient tensor, of shape ``b.shape + Q``. `Q`, a tuple, equals the shape of that sub-tensor of `a` consisting of the appropriate number of its rightmost indices, and must be such that ``prod(Q) == prod(b.shape)`` (in which sense `a` is said to be 'square'). b : array_like Right-hand tensor, which can be of any shape. axes : tuple of ints, optional Axes in `a` to reorder to the right, before inversion. If None (default), no reordering is done. Returns ------- x : ndarray, shape Q Raises ------ LinAlgError If `a` is singular or not 'square' (in the above sense). See Also -------- tensordot, tensorinv, einsum Examples -------- >>> a = np.eye(2*3*4) >>> a.shape = (2*3, 4, 2, 3, 4) >>> b = np.random.randn(2*3, 4) >>> x = np.linalg.tensorsolve(a, b) >>> x.shape (2, 3, 4) >>> np.allclose(np.tensordot(a, x, axes=3), b) True """ a, wrap = _makearray(a) b = asarray(b) an = a.ndim if axes is not None: allaxes = list(range(0, an)) for k in axes: allaxes.remove(k) allaxes.insert(an, k) a = a.transpose(allaxes) oldshape = a.shape[-(an-b.ndim):] prod = 1 for k in oldshape: prod *= k a = a.reshape(-1, prod) b = b.ravel() res = wrap(solve(a, b)) res.shape = oldshape return res def solve(a, b): """ Solve a linear matrix equation, or system of linear scalar equations. Computes the "exact" solution, `x`, of the well-determined, i.e., full rank, linear matrix equation `ax = b`. Parameters ---------- a : (..., M, M) array_like Coefficient matrix. b : {(..., M,), (..., M, K)}, array_like Ordinate or "dependent variable" values. Returns ------- x : {(..., M,), (..., M, K)} ndarray Solution to the system a x = b. Returned shape is identical to `b`. Raises ------ LinAlgError If `a` is singular or not square. Notes ----- Broadcasting rules apply, see the `numpy.linalg` documentation for details. The solutions are computed using LAPACK routine _gesv `a` must be square and of full-rank, i.e., all rows (or, equivalently, columns) must be linearly independent; if either is not true, use `lstsq` for the least-squares best "solution" of the system/equation. References ---------- .. [1] G. Strang, *Linear Algebra and Its Applications*, 2nd Ed., Orlando, FL, Academic Press, Inc., 1980, pg. 22. Examples -------- Solve the system of equations ``3 * x0 + x1 = 9`` and ``x0 + 2 * x1 = 8``: >>> a = np.array([[3,1], [1,2]]) >>> b = np.array([9,8]) >>> x = np.linalg.solve(a, b) >>> x array([ 2., 3.]) Check that the solution is correct: >>> np.allclose(np.dot(a, x), b) True """ a, _ = _makearray(a) _assertRankAtLeast2(a) _assertNdSquareness(a) b, wrap = _makearray(b) t, result_t = _commonType(a, b) # We use the b = (..., M,) logic, only if the number of extra dimensions # match exactly if b.ndim == a.ndim - 1: if a.shape[-1] == 0 and b.shape[-1] == 0: # Legal, but the ufunc cannot handle the 0-sized inner dims # let the ufunc handle all wrong cases. a = a.reshape(a.shape[:-1]) bc = broadcast(a, b) return wrap(empty(bc.shape, dtype=result_t)) gufunc = _umath_linalg.solve1 else: if b.size == 0: if (a.shape[-1] == 0 and b.shape[-2] == 0) or b.shape[-1] == 0: a = a[:,:1].reshape(a.shape[:-1] + (1,)) bc = broadcast(a, b) return wrap(empty(bc.shape, dtype=result_t)) gufunc = _umath_linalg.solve signature = 'DD->D' if isComplexType(t) else 'dd->d' extobj = get_linalg_error_extobj(_raise_linalgerror_singular) r = gufunc(a, b, signature=signature, extobj=extobj) return wrap(r.astype(result_t)) def tensorinv(a, ind=2): """ Compute the 'inverse' of an N-dimensional array. The result is an inverse for `a` relative to the tensordot operation ``tensordot(a, b, ind)``, i. e., up to floating-point accuracy, ``tensordot(tensorinv(a), a, ind)`` is the "identity" tensor for the tensordot operation. Parameters ---------- a : array_like Tensor to 'invert'. Its shape must be 'square', i. e., ``prod(a.shape[:ind]) == prod(a.shape[ind:])``. ind : int, optional Number of first indices that are involved in the inverse sum. Must be a positive integer, default is 2. Returns ------- b : ndarray `a`'s tensordot inverse, shape ``a.shape[:ind] + a.shape[ind:]``. Raises ------ LinAlgError If `a` is singular or not 'square' (in the above sense). See Also -------- tensordot, tensorsolve Examples -------- >>> a = np.eye(4*6) >>> a.shape = (4, 6, 8, 3) >>> ainv = np.linalg.tensorinv(a, ind=2) >>> ainv.shape (8, 3, 4, 6) >>> b = np.random.randn(4, 6) >>> np.allclose(np.tensordot(ainv, b), np.linalg.tensorsolve(a, b)) True >>> a = np.eye(4*6) >>> a.shape = (24, 8, 3) >>> ainv = np.linalg.tensorinv(a, ind=1) >>> ainv.shape (8, 3, 24) >>> b = np.random.randn(24) >>> np.allclose(np.tensordot(ainv, b, 1), np.linalg.tensorsolve(a, b)) True """ a = asarray(a) oldshape = a.shape prod = 1 if ind > 0: invshape = oldshape[ind:] + oldshape[:ind] for k in oldshape[ind:]: prod *= k else: raise ValueError("Invalid ind argument.") a = a.reshape(prod, -1) ia = inv(a) return ia.reshape(*invshape) # Matrix inversion def inv(a): """ Compute the (multiplicative) inverse of a matrix. Given a square matrix `a`, return the matrix `ainv` satisfying ``dot(a, ainv) = dot(ainv, a) = eye(a.shape[0])``. Parameters ---------- a : (..., M, M) array_like Matrix to be inverted. Returns ------- ainv : (..., M, M) ndarray or matrix (Multiplicative) inverse of the matrix `a`. Raises ------ LinAlgError If `a` is not square or inversion fails. Notes ----- Broadcasting rules apply, see the `numpy.linalg` documentation for details. Examples -------- >>> from numpy.linalg import inv >>> a = np.array([[1., 2.], [3., 4.]]) >>> ainv = inv(a) >>> np.allclose(np.dot(a, ainv), np.eye(2)) True >>> np.allclose(np.dot(ainv, a), np.eye(2)) True If a is a matrix object, then the return value is a matrix as well: >>> ainv = inv(np.matrix(a)) >>> ainv matrix([[-2. , 1. ], [ 1.5, -0.5]]) Inverses of several matrices can be computed at once: >>> a = np.array([[[1., 2.], [3., 4.]], [[1, 3], [3, 5]]]) >>> inv(a) array([[[-2. , 1. ], [ 1.5, -0.5]], [[-5. , 2. ], [ 3. , -1. ]]]) """ a, wrap = _makearray(a) _assertRankAtLeast2(a) _assertNdSquareness(a) t, result_t = _commonType(a) if a.shape[-1] == 0: # The inner array is 0x0, the ufunc cannot handle this case return wrap(empty_like(a, dtype=result_t)) signature = 'D->D' if isComplexType(t) else 'd->d' extobj = get_linalg_error_extobj(_raise_linalgerror_singular) ainv = _umath_linalg.inv(a, signature=signature, extobj=extobj) return wrap(ainv.astype(result_t)) # Cholesky decomposition def cholesky(a): """ Cholesky decomposition. Return the Cholesky decomposition, `L * L.H`, of the square matrix `a`, where `L` is lower-triangular and .H is the conjugate transpose operator (which is the ordinary transpose if `a` is real-valued). `a` must be Hermitian (symmetric if real-valued) and positive-definite. Only `L` is actually returned. Parameters ---------- a : (..., M, M) array_like Hermitian (symmetric if all elements are real), positive-definite input matrix. Returns ------- L : (..., M, M) array_like Upper or lower-triangular Cholesky factor of `a`. Returns a matrix object if `a` is a matrix object. Raises ------ LinAlgError If the decomposition fails, for example, if `a` is not positive-definite. Notes ----- Broadcasting rules apply, see the `numpy.linalg` documentation for details. The Cholesky decomposition is often used as a fast way of solving .. math:: A \\mathbf{x} = \\mathbf{b} (when `A` is both Hermitian/symmetric and positive-definite). First, we solve for :math:`\\mathbf{y}` in .. math:: L \\mathbf{y} = \\mathbf{b}, and then for :math:`\\mathbf{x}` in .. math:: L.H \\mathbf{x} = \\mathbf{y}. Examples -------- >>> A = np.array([[1,-2j],[2j,5]]) >>> A array([[ 1.+0.j, 0.-2.j], [ 0.+2.j, 5.+0.j]]) >>> L = np.linalg.cholesky(A) >>> L array([[ 1.+0.j, 0.+0.j], [ 0.+2.j, 1.+0.j]]) >>> np.dot(L, L.T.conj()) # verify that L * L.H = A array([[ 1.+0.j, 0.-2.j], [ 0.+2.j, 5.+0.j]]) >>> A = [[1,-2j],[2j,5]] # what happens if A is only array_like? >>> np.linalg.cholesky(A) # an ndarray object is returned array([[ 1.+0.j, 0.+0.j], [ 0.+2.j, 1.+0.j]]) >>> # But a matrix object is returned if A is a matrix object >>> LA.cholesky(np.matrix(A)) matrix([[ 1.+0.j, 0.+0.j], [ 0.+2.j, 1.+0.j]]) """ extobj = get_linalg_error_extobj(_raise_linalgerror_nonposdef) gufunc = _umath_linalg.cholesky_lo a, wrap = _makearray(a) _assertRankAtLeast2(a) _assertNdSquareness(a) t, result_t = _commonType(a) signature = 'D->D' if isComplexType(t) else 'd->d' return wrap(gufunc(a, signature=signature, extobj=extobj).astype(result_t)) # QR decompostion def qr(a, mode='reduced'): """ Compute the qr factorization of a matrix. Factor the matrix `a` as *qr*, where `q` is orthonormal and `r` is upper-triangular. Parameters ---------- a : array_like, shape (M, N) Matrix to be factored. mode : {'reduced', 'complete', 'r', 'raw', 'full', 'economic'}, optional If K = min(M, N), then 'reduced' : returns q, r with dimensions (M, K), (K, N) (default) 'complete' : returns q, r with dimensions (M, M), (M, N) 'r' : returns r only with dimensions (K, N) 'raw' : returns h, tau with dimensions (N, M), (K,) 'full' : alias of 'reduced', deprecated 'economic' : returns h from 'raw', deprecated. The options 'reduced', 'complete, and 'raw' are new in numpy 1.8, see the notes for more information. The default is 'reduced' and to maintain backward compatibility with earlier versions of numpy both it and the old default 'full' can be omitted. Note that array h returned in 'raw' mode is transposed for calling Fortran. The 'economic' mode is deprecated. The modes 'full' and 'economic' may be passed using only the first letter for backwards compatibility, but all others must be spelled out. See the Notes for more explanation. Returns ------- q : ndarray of float or complex, optional A matrix with orthonormal columns. When mode = 'complete' the result is an orthogonal/unitary matrix depending on whether or not a is real/complex. The determinant may be either +/- 1 in that case. r : ndarray of float or complex, optional The upper-triangular matrix. (h, tau) : ndarrays of np.double or np.cdouble, optional The array h contains the Householder reflectors that generate q along with r. The tau array contains scaling factors for the reflectors. In the deprecated 'economic' mode only h is returned. Raises ------ LinAlgError If factoring fails. Notes ----- This is an interface to the LAPACK routines dgeqrf, zgeqrf, dorgqr, and zungqr. For more information on the qr factorization, see for example: http://en.wikipedia.org/wiki/QR_factorization Subclasses of `ndarray` are preserved except for the 'raw' mode. So if `a` is of type `matrix`, all the return values will be matrices too. New 'reduced', 'complete', and 'raw' options for mode were added in Numpy 1.8 and the old option 'full' was made an alias of 'reduced'. In addition the options 'full' and 'economic' were deprecated. Because 'full' was the previous default and 'reduced' is the new default, backward compatibility can be maintained by letting `mode` default. The 'raw' option was added so that LAPACK routines that can multiply arrays by q using the Householder reflectors can be used. Note that in this case the returned arrays are of type np.double or np.cdouble and the h array is transposed to be FORTRAN compatible. No routines using the 'raw' return are currently exposed by numpy, but some are available in lapack_lite and just await the necessary work. Examples -------- >>> a = np.random.randn(9, 6) >>> q, r = np.linalg.qr(a) >>> np.allclose(a, np.dot(q, r)) # a does equal qr True >>> r2 = np.linalg.qr(a, mode='r') >>> r3 = np.linalg.qr(a, mode='economic') >>> np.allclose(r, r2) # mode='r' returns the same r as mode='full' True >>> # But only triu parts are guaranteed equal when mode='economic' >>> np.allclose(r, np.triu(r3[:6,:6], k=0)) True Example illustrating a common use of `qr`: solving of least squares problems What are the least-squares-best `m` and `y0` in ``y = y0 + mx`` for the following data: {(0,1), (1,0), (1,2), (2,1)}. (Graph the points and you'll see that it should be y0 = 0, m = 1.) The answer is provided by solving the over-determined matrix equation ``Ax = b``, where:: A = array([[0, 1], [1, 1], [1, 1], [2, 1]]) x = array([[y0], [m]]) b = array([[1], [0], [2], [1]]) If A = qr such that q is orthonormal (which is always possible via Gram-Schmidt), then ``x = inv(r) * (q.T) * b``. (In numpy practice, however, we simply use `lstsq`.) >>> A = np.array([[0, 1], [1, 1], [1, 1], [2, 1]]) >>> A array([[0, 1], [1, 1], [1, 1], [2, 1]]) >>> b = np.array([1, 0, 2, 1]) >>> q, r = LA.qr(A) >>> p = np.dot(q.T, b) >>> np.dot(LA.inv(r), p) array([ 1.1e-16, 1.0e+00]) """ if mode not in ('reduced', 'complete', 'r', 'raw'): if mode in ('f', 'full'): msg = "".join(( "The 'full' option is deprecated in favor of 'reduced'.\n", "For backward compatibility let mode default.")) warnings.warn(msg, DeprecationWarning) mode = 'reduced' elif mode in ('e', 'economic'): msg = "The 'economic' option is deprecated.", warnings.warn(msg, DeprecationWarning) mode = 'economic' else: raise ValueError("Unrecognized mode '%s'" % mode) a, wrap = _makearray(a) _assertRank2(a) _assertNoEmpty2d(a) m, n = a.shape t, result_t = _commonType(a) a = _fastCopyAndTranspose(t, a) a = _to_native_byte_order(a) mn = min(m, n) tau = zeros((mn,), t) if isComplexType(t): lapack_routine = lapack_lite.zgeqrf routine_name = 'zgeqrf' else: lapack_routine = lapack_lite.dgeqrf routine_name = 'dgeqrf' # calculate optimal size of work data 'work' lwork = 1 work = zeros((lwork,), t) results = lapack_routine(m, n, a, m, tau, work, -1, 0) if results['info'] != 0: raise LinAlgError('%s returns %d' % (routine_name, results['info'])) # do qr decomposition lwork = int(abs(work[0])) work = zeros((lwork,), t) results = lapack_routine(m, n, a, m, tau, work, lwork, 0) if results['info'] != 0: raise LinAlgError('%s returns %d' % (routine_name, results['info'])) # handle modes that don't return q if mode == 'r': r = _fastCopyAndTranspose(result_t, a[:, :mn]) return wrap(triu(r)) if mode == 'raw': return a, tau if mode == 'economic': if t != result_t : a = a.astype(result_t) return wrap(a.T) # generate q from a if mode == 'complete' and m > n: mc = m q = empty((m, m), t) else: mc = mn q = empty((n, m), t) q[:n] = a if isComplexType(t): lapack_routine = lapack_lite.zungqr routine_name = 'zungqr' else: lapack_routine = lapack_lite.dorgqr routine_name = 'dorgqr' # determine optimal lwork lwork = 1 work = zeros((lwork,), t) results = lapack_routine(m, mc, mn, q, m, tau, work, -1, 0) if results['info'] != 0: raise LinAlgError('%s returns %d' % (routine_name, results['info'])) # compute q lwork = int(abs(work[0])) work = zeros((lwork,), t) results = lapack_routine(m, mc, mn, q, m, tau, work, lwork, 0) if results['info'] != 0: raise LinAlgError('%s returns %d' % (routine_name, results['info'])) q = _fastCopyAndTranspose(result_t, q[:mc]) r = _fastCopyAndTranspose(result_t, a[:, :mc]) return wrap(q), wrap(triu(r)) # Eigenvalues def eigvals(a): """ Compute the eigenvalues of a general matrix. Main difference between `eigvals` and `eig`: the eigenvectors aren't returned. Parameters ---------- a : (..., M, M) array_like A complex- or real-valued matrix whose eigenvalues will be computed. Returns ------- w : (..., M,) ndarray The eigenvalues, each repeated according to its multiplicity. They are not necessarily ordered, nor are they necessarily real for real matrices. Raises ------ LinAlgError If the eigenvalue computation does not converge. See Also -------- eig : eigenvalues and right eigenvectors of general arrays eigvalsh : eigenvalues of symmetric or Hermitian arrays. eigh : eigenvalues and eigenvectors of symmetric/Hermitian arrays. Notes ----- Broadcasting rules apply, see the `numpy.linalg` documentation for details. This is implemented using the _geev LAPACK routines which compute the eigenvalues and eigenvectors of general square arrays. Examples -------- Illustration, using the fact that the eigenvalues of a diagonal matrix are its diagonal elements, that multiplying a matrix on the left by an orthogonal matrix, `Q`, and on the right by `Q.T` (the transpose of `Q`), preserves the eigenvalues of the "middle" matrix. In other words, if `Q` is orthogonal, then ``Q * A * Q.T`` has the same eigenvalues as ``A``: >>> from numpy import linalg as LA >>> x = np.random.random() >>> Q = np.array([[np.cos(x), -np.sin(x)], [np.sin(x), np.cos(x)]]) >>> LA.norm(Q[0, :]), LA.norm(Q[1, :]), np.dot(Q[0, :],Q[1, :]) (1.0, 1.0, 0.0) Now multiply a diagonal matrix by Q on one side and by Q.T on the other: >>> D = np.diag((-1,1)) >>> LA.eigvals(D) array([-1., 1.]) >>> A = np.dot(Q, D) >>> A = np.dot(A, Q.T) >>> LA.eigvals(A) array([ 1., -1.]) """ a, wrap = _makearray(a) _assertNoEmpty2d(a) _assertRankAtLeast2(a) _assertNdSquareness(a) _assertFinite(a) t, result_t = _commonType(a) extobj = get_linalg_error_extobj( _raise_linalgerror_eigenvalues_nonconvergence) signature = 'D->D' if isComplexType(t) else 'd->D' w = _umath_linalg.eigvals(a, signature=signature, extobj=extobj) if not isComplexType(t): if all(w.imag == 0): w = w.real result_t = _realType(result_t) else: result_t = _complexType(result_t) return w.astype(result_t) def eigvalsh(a, UPLO='L'): """ Compute the eigenvalues of a Hermitian or real symmetric matrix. Main difference from eigh: the eigenvectors are not computed. Parameters ---------- a : (..., M, M) array_like A complex- or real-valued matrix whose eigenvalues are to be computed. UPLO : {'L', 'U'}, optional Same as `lower`, with 'L' for lower and 'U' for upper triangular. Deprecated. Returns ------- w : (..., M,) ndarray The eigenvalues, not necessarily ordered, each repeated according to its multiplicity. Raises ------ LinAlgError If the eigenvalue computation does not converge. See Also -------- eigh : eigenvalues and eigenvectors of symmetric/Hermitian arrays. eigvals : eigenvalues of general real or complex arrays. eig : eigenvalues and right eigenvectors of general real or complex arrays. Notes ----- Broadcasting rules apply, see the `numpy.linalg` documentation for details. The eigenvalues are computed using LAPACK routines _ssyevd, _heevd Examples -------- >>> from numpy import linalg as LA >>> a = np.array([[1, -2j], [2j, 5]]) >>> LA.eigvalsh(a) array([ 0.17157288+0.j, 5.82842712+0.j]) """ UPLO = UPLO.upper() if UPLO not in ('L', 'U'): raise ValueError("UPLO argument must be 'L' or 'U'") extobj = get_linalg_error_extobj( _raise_linalgerror_eigenvalues_nonconvergence) if UPLO == 'L': gufunc = _umath_linalg.eigvalsh_lo else: gufunc = _umath_linalg.eigvalsh_up a, wrap = _makearray(a) _assertNoEmpty2d(a) _assertRankAtLeast2(a) _assertNdSquareness(a) t, result_t = _commonType(a) signature = 'D->d' if isComplexType(t) else 'd->d' w = gufunc(a, signature=signature, extobj=extobj) return w.astype(_realType(result_t)) def _convertarray(a): t, result_t = _commonType(a) a = _fastCT(a.astype(t)) return a, t, result_t # Eigenvectors def eig(a): """ Compute the eigenvalues and right eigenvectors of a square array. Parameters ---------- a : (..., M, M) array Matrices for which the eigenvalues and right eigenvectors will be computed Returns ------- w : (..., M) array The eigenvalues, each repeated according to its multiplicity. The eigenvalues are not necessarily ordered. The resulting array will be always be of complex type. When `a` is real the resulting eigenvalues will be real (0 imaginary part) or occur in conjugate pairs v : (..., M, M) array The normalized (unit "length") eigenvectors, such that the column ``v[:,i]`` is the eigenvector corresponding to the eigenvalue ``w[i]``. Raises ------ LinAlgError If the eigenvalue computation does not converge. See Also -------- eigvalsh : eigenvalues of a symmetric or Hermitian (conjugate symmetric) array. eigvals : eigenvalues of a non-symmetric array. Notes ----- Broadcasting rules apply, see the `numpy.linalg` documentation for details. This is implemented using the _geev LAPACK routines which compute the eigenvalues and eigenvectors of general square arrays. The number `w` is an eigenvalue of `a` if there exists a vector `v` such that ``dot(a,v) = w * v``. Thus, the arrays `a`, `w`, and `v` satisfy the equations ``dot(a[:,:], v[:,i]) = w[i] * v[:,i]`` for :math:`i \\in \\{0,...,M-1\\}`. The array `v` of eigenvectors may not be of maximum rank, that is, some of the columns may be linearly dependent, although round-off error may obscure that fact. If the eigenvalues are all different, then theoretically the eigenvectors are linearly independent. Likewise, the (complex-valued) matrix of eigenvectors `v` is unitary if the matrix `a` is normal, i.e., if ``dot(a, a.H) = dot(a.H, a)``, where `a.H` denotes the conjugate transpose of `a`. Finally, it is emphasized that `v` consists of the *right* (as in right-hand side) eigenvectors of `a`. A vector `y` satisfying ``dot(y.T, a) = z * y.T`` for some number `z` is called a *left* eigenvector of `a`, and, in general, the left and right eigenvectors of a matrix are not necessarily the (perhaps conjugate) transposes of each other. References ---------- G. Strang, *Linear Algebra and Its Applications*, 2nd Ed., Orlando, FL, Academic Press, Inc., 1980, Various pp. Examples -------- >>> from numpy import linalg as LA (Almost) trivial example with real e-values and e-vectors. >>> w, v = LA.eig(np.diag((1, 2, 3))) >>> w; v array([ 1., 2., 3.]) array([[ 1., 0., 0.], [ 0., 1., 0.], [ 0., 0., 1.]]) Real matrix possessing complex e-values and e-vectors; note that the e-values are complex conjugates of each other. >>> w, v = LA.eig(np.array([[1, -1], [1, 1]])) >>> w; v array([ 1. + 1.j, 1. - 1.j]) array([[ 0.70710678+0.j , 0.70710678+0.j ], [ 0.00000000-0.70710678j, 0.00000000+0.70710678j]]) Complex-valued matrix with real e-values (but complex-valued e-vectors); note that a.conj().T = a, i.e., a is Hermitian. >>> a = np.array([[1, 1j], [-1j, 1]]) >>> w, v = LA.eig(a) >>> w; v array([ 2.00000000e+00+0.j, 5.98651912e-36+0.j]) # i.e., {2, 0} array([[ 0.00000000+0.70710678j, 0.70710678+0.j ], [ 0.70710678+0.j , 0.00000000+0.70710678j]]) Be careful about round-off error! >>> a = np.array([[1 + 1e-9, 0], [0, 1 - 1e-9]]) >>> # Theor. e-values are 1 +/- 1e-9 >>> w, v = LA.eig(a) >>> w; v array([ 1., 1.]) array([[ 1., 0.], [ 0., 1.]]) """ a, wrap = _makearray(a) _assertRankAtLeast2(a) _assertNdSquareness(a) _assertFinite(a) t, result_t = _commonType(a) extobj = get_linalg_error_extobj( _raise_linalgerror_eigenvalues_nonconvergence) signature = 'D->DD' if isComplexType(t) else 'd->DD' w, vt = _umath_linalg.eig(a, signature=signature, extobj=extobj) if not isComplexType(t) and all(w.imag == 0.0): w = w.real vt = vt.real result_t = _realType(result_t) else: result_t = _complexType(result_t) vt = vt.astype(result_t) return w.astype(result_t), wrap(vt) def eigh(a, UPLO='L'): """ Return the eigenvalues and eigenvectors of a Hermitian or symmetric matrix. Returns two objects, a 1-D array containing the eigenvalues of `a`, and a 2-D square array or matrix (depending on the input type) of the corresponding eigenvectors (in columns). Parameters ---------- A : (..., M, M) array Hermitian/Symmetric matrices whose eigenvalues and eigenvectors are to be computed. UPLO : {'L', 'U'}, optional Specifies whether the calculation is done with the lower triangular part of `a` ('L', default) or the upper triangular part ('U'). Returns ------- w : (..., M) ndarray The eigenvalues, not necessarily ordered. v : {(..., M, M) ndarray, (..., M, M) matrix} The column ``v[:, i]`` is the normalized eigenvector corresponding to the eigenvalue ``w[i]``. Will return a matrix object if `a` is a matrix object. Raises ------ LinAlgError If the eigenvalue computation does not converge. See Also -------- eigvalsh : eigenvalues of symmetric or Hermitian arrays. eig : eigenvalues and right eigenvectors for non-symmetric arrays. eigvals : eigenvalues of non-symmetric arrays. Notes ----- Broadcasting rules apply, see the `numpy.linalg` documentation for details. The eigenvalues/eigenvectors are computed using LAPACK routines _ssyevd, _heevd The eigenvalues of real symmetric or complex Hermitian matrices are always real. [1]_ The array `v` of (column) eigenvectors is unitary and `a`, `w`, and `v` satisfy the equations ``dot(a, v[:, i]) = w[i] * v[:, i]``. References ---------- .. [1] G. Strang, *Linear Algebra and Its Applications*, 2nd Ed., Orlando, FL, Academic Press, Inc., 1980, pg. 222. Examples -------- >>> from numpy import linalg as LA >>> a = np.array([[1, -2j], [2j, 5]]) >>> a array([[ 1.+0.j, 0.-2.j], [ 0.+2.j, 5.+0.j]]) >>> w, v = LA.eigh(a) >>> w; v array([ 0.17157288, 5.82842712]) array([[-0.92387953+0.j , -0.38268343+0.j ], [ 0.00000000+0.38268343j, 0.00000000-0.92387953j]]) >>> np.dot(a, v[:, 0]) - w[0] * v[:, 0] # verify 1st e-val/vec pair array([2.77555756e-17 + 0.j, 0. + 1.38777878e-16j]) >>> np.dot(a, v[:, 1]) - w[1] * v[:, 1] # verify 2nd e-val/vec pair array([ 0.+0.j, 0.+0.j]) >>> A = np.matrix(a) # what happens if input is a matrix object >>> A matrix([[ 1.+0.j, 0.-2.j], [ 0.+2.j, 5.+0.j]]) >>> w, v = LA.eigh(A) >>> w; v array([ 0.17157288, 5.82842712]) matrix([[-0.92387953+0.j , -0.38268343+0.j ], [ 0.00000000+0.38268343j, 0.00000000-0.92387953j]]) """ UPLO = UPLO.upper() if UPLO not in ('L', 'U'): raise ValueError("UPLO argument must be 'L' or 'U'") a, wrap = _makearray(a) _assertRankAtLeast2(a) _assertNdSquareness(a) t, result_t = _commonType(a) extobj = get_linalg_error_extobj( _raise_linalgerror_eigenvalues_nonconvergence) if UPLO == 'L': gufunc = _umath_linalg.eigh_lo else: gufunc = _umath_linalg.eigh_up signature = 'D->dD' if isComplexType(t) else 'd->dd' w, vt = gufunc(a, signature=signature, extobj=extobj) w = w.astype(_realType(result_t)) vt = vt.astype(result_t) return w, wrap(vt) # Singular value decomposition def svd(a, full_matrices=1, compute_uv=1): """ Singular Value Decomposition. Factors the matrix `a` as ``u * np.diag(s) * v``, where `u` and `v` are unitary and `s` is a 1-d array of `a`'s singular values. Parameters ---------- a : (..., M, N) array_like A real or complex matrix of shape (`M`, `N`) . full_matrices : bool, optional If True (default), `u` and `v` have the shapes (`M`, `M`) and (`N`, `N`), respectively. Otherwise, the shapes are (`M`, `K`) and (`K`, `N`), respectively, where `K` = min(`M`, `N`). compute_uv : bool, optional Whether or not to compute `u` and `v` in addition to `s`. True by default. Returns ------- u : { (..., M, M), (..., M, K) } array Unitary matrices. The actual shape depends on the value of ``full_matrices``. Only returned when ``compute_uv`` is True. s : (..., K) array The singular values for every matrix, sorted in descending order. v : { (..., N, N), (..., K, N) } array Unitary matrices. The actual shape depends on the value of ``full_matrices``. Only returned when ``compute_uv`` is True. Raises ------ LinAlgError If SVD computation does not converge. Notes ----- Broadcasting rules apply, see the `numpy.linalg` documentation for details. The decomposition is performed using LAPACK routine _gesdd The SVD is commonly written as ``a = U S V.H``. The `v` returned by this function is ``V.H`` and ``u = U``. If ``U`` is a unitary matrix, it means that it satisfies ``U.H = inv(U)``. The rows of `v` are the eigenvectors of ``a.H a``. The columns of `u` are the eigenvectors of ``a a.H``. For row ``i`` in `v` and column ``i`` in `u`, the corresponding eigenvalue is ``s[i]**2``. If `a` is a `matrix` object (as opposed to an `ndarray`), then so are all the return values. Examples -------- >>> a = np.random.randn(9, 6) + 1j*np.random.randn(9, 6) Reconstruction based on full SVD: >>> U, s, V = np.linalg.svd(a, full_matrices=True) >>> U.shape, V.shape, s.shape ((9, 9), (6, 6), (6,)) >>> S = np.zeros((9, 6), dtype=complex) >>> S[:6, :6] = np.diag(s) >>> np.allclose(a, np.dot(U, np.dot(S, V))) True Reconstruction based on reduced SVD: >>> U, s, V = np.linalg.svd(a, full_matrices=False) >>> U.shape, V.shape, s.shape ((9, 6), (6, 6), (6,)) >>> S = np.diag(s) >>> np.allclose(a, np.dot(U, np.dot(S, V))) True """ a, wrap = _makearray(a) _assertNoEmpty2d(a) _assertRankAtLeast2(a) t, result_t = _commonType(a) extobj = get_linalg_error_extobj(_raise_linalgerror_svd_nonconvergence) m = a.shape[-2] n = a.shape[-1] if compute_uv: if full_matrices: if m < n: gufunc = _umath_linalg.svd_m_f else: gufunc = _umath_linalg.svd_n_f else: if m < n: gufunc = _umath_linalg.svd_m_s else: gufunc = _umath_linalg.svd_n_s signature = 'D->DdD' if isComplexType(t) else 'd->ddd' u, s, vt = gufunc(a, signature=signature, extobj=extobj) u = u.astype(result_t) s = s.astype(_realType(result_t)) vt = vt.astype(result_t) return wrap(u), s, wrap(vt) else: if m < n: gufunc = _umath_linalg.svd_m else: gufunc = _umath_linalg.svd_n signature = 'D->d' if isComplexType(t) else 'd->d' s = gufunc(a, signature=signature, extobj=extobj) s = s.astype(_realType(result_t)) return s def cond(x, p=None): """ Compute the condition number of a matrix. This function is capable of returning the condition number using one of seven different norms, depending on the value of `p` (see Parameters below). Parameters ---------- x : (M, N) array_like The matrix whose condition number is sought. p : {None, 1, -1, 2, -2, inf, -inf, 'fro'}, optional Order of the norm: ===== ============================ p norm for matrices ===== ============================ None 2-norm, computed directly using the ``SVD`` 'fro' Frobenius norm inf max(sum(abs(x), axis=1)) -inf min(sum(abs(x), axis=1)) 1 max(sum(abs(x), axis=0)) -1 min(sum(abs(x), axis=0)) 2 2-norm (largest sing. value) -2 smallest singular value ===== ============================ inf means the numpy.inf object, and the Frobenius norm is the root-of-sum-of-squares norm. Returns ------- c : {float, inf} The condition number of the matrix. May be infinite. See Also -------- numpy.linalg.norm Notes ----- The condition number of `x` is defined as the norm of `x` times the norm of the inverse of `x` [1]_; the norm can be the usual L2-norm (root-of-sum-of-squares) or one of a number of other matrix norms. References ---------- .. [1] G. Strang, *Linear Algebra and Its Applications*, Orlando, FL, Academic Press, Inc., 1980, pg. 285. Examples -------- >>> from numpy import linalg as LA >>> a = np.array([[1, 0, -1], [0, 1, 0], [1, 0, 1]]) >>> a array([[ 1, 0, -1], [ 0, 1, 0], [ 1, 0, 1]]) >>> LA.cond(a) 1.4142135623730951 >>> LA.cond(a, 'fro') 3.1622776601683795 >>> LA.cond(a, np.inf) 2.0 >>> LA.cond(a, -np.inf) 1.0 >>> LA.cond(a, 1) 2.0 >>> LA.cond(a, -1) 1.0 >>> LA.cond(a, 2) 1.4142135623730951 >>> LA.cond(a, -2) 0.70710678118654746 >>> min(LA.svd(a, compute_uv=0))*min(LA.svd(LA.inv(a), compute_uv=0)) 0.70710678118654746 """ x = asarray(x) # in case we have a matrix if p is None: s = svd(x, compute_uv=False) return s[0]/s[-1] else: return norm(x, p)*norm(inv(x), p) def matrix_rank(M, tol=None): """ Return matrix rank of array using SVD method Rank of the array is the number of SVD singular values of the array that are greater than `tol`. Parameters ---------- M : {(M,), (M, N)} array_like array of <=2 dimensions tol : {None, float}, optional threshold below which SVD values are considered zero. If `tol` is None, and ``S`` is an array with singular values for `M`, and ``eps`` is the epsilon value for datatype of ``S``, then `tol` is set to ``S.max() * max(M.shape) * eps``. Notes ----- The default threshold to detect rank deficiency is a test on the magnitude of the singular values of `M`. By default, we identify singular values less than ``S.max() * max(M.shape) * eps`` as indicating rank deficiency (with the symbols defined above). This is the algorithm MATLAB uses [1]. It also appears in *Numerical recipes* in the discussion of SVD solutions for linear least squares [2]. This default threshold is designed to detect rank deficiency accounting for the numerical errors of the SVD computation. Imagine that there is a column in `M` that is an exact (in floating point) linear combination of other columns in `M`. Computing the SVD on `M` will not produce a singular value exactly equal to 0 in general: any difference of the smallest SVD value from 0 will be caused by numerical imprecision in the calculation of the SVD. Our threshold for small SVD values takes this numerical imprecision into account, and the default threshold will detect such numerical rank deficiency. The threshold may declare a matrix `M` rank deficient even if the linear combination of some columns of `M` is not exactly equal to another column of `M` but only numerically very close to another column of `M`. We chose our default threshold because it is in wide use. Other thresholds are possible. For example, elsewhere in the 2007 edition of *Numerical recipes* there is an alternative threshold of ``S.max() * np.finfo(M.dtype).eps / 2. * np.sqrt(m + n + 1.)``. The authors describe this threshold as being based on "expected roundoff error" (p 71). The thresholds above deal with floating point roundoff error in the calculation of the SVD. However, you may have more information about the sources of error in `M` that would make you consider other tolerance values to detect *effective* rank deficiency. The most useful measure of the tolerance depends on the operations you intend to use on your matrix. For example, if your data come from uncertain measurements with uncertainties greater than floating point epsilon, choosing a tolerance near that uncertainty may be preferable. The tolerance may be absolute if the uncertainties are absolute rather than relative. References ---------- .. [1] MATLAB reference documention, "Rank" http://www.mathworks.com/help/techdoc/ref/rank.html .. [2] W. H. Press, S. A. Teukolsky, W. T. Vetterling and B. P. Flannery, "Numerical Recipes (3rd edition)", Cambridge University Press, 2007, page 795. Examples -------- >>> from numpy.linalg import matrix_rank >>> matrix_rank(np.eye(4)) # Full rank matrix 4 >>> I=np.eye(4); I[-1,-1] = 0. # rank deficient matrix >>> matrix_rank(I) 3 >>> matrix_rank(np.ones((4,))) # 1 dimension - rank 1 unless all 0 1 >>> matrix_rank(np.zeros((4,))) 0 """ M = asarray(M) if M.ndim > 2: raise TypeError('array should have 2 or fewer dimensions') if M.ndim < 2: return int(not all(M==0)) S = svd(M, compute_uv=False) if tol is None: tol = S.max() * max(M.shape) * finfo(S.dtype).eps return sum(S > tol) # Generalized inverse def pinv(a, rcond=1e-15 ): """ Compute the (Moore-Penrose) pseudo-inverse of a matrix. Calculate the generalized inverse of a matrix using its singular-value decomposition (SVD) and including all *large* singular values. Parameters ---------- a : (M, N) array_like Matrix to be pseudo-inverted. rcond : float Cutoff for small singular values. Singular values smaller (in modulus) than `rcond` * largest_singular_value (again, in modulus) are set to zero. Returns ------- B : (N, M) ndarray The pseudo-inverse of `a`. If `a` is a `matrix` instance, then so is `B`. Raises ------ LinAlgError If the SVD computation does not converge. Notes ----- The pseudo-inverse of a matrix A, denoted :math:`A^+`, is defined as: "the matrix that 'solves' [the least-squares problem] :math:`Ax = b`," i.e., if :math:`\\bar{x}` is said solution, then :math:`A^+` is that matrix such that :math:`\\bar{x} = A^+b`. It can be shown that if :math:`Q_1 \\Sigma Q_2^T = A` is the singular value decomposition of A, then :math:`A^+ = Q_2 \\Sigma^+ Q_1^T`, where :math:`Q_{1,2}` are orthogonal matrices, :math:`\\Sigma` is a diagonal matrix consisting of A's so-called singular values, (followed, typically, by zeros), and then :math:`\\Sigma^+` is simply the diagonal matrix consisting of the reciprocals of A's singular values (again, followed by zeros). [1]_ References ---------- .. [1] G. Strang, *Linear Algebra and Its Applications*, 2nd Ed., Orlando, FL, Academic Press, Inc., 1980, pp. 139-142. Examples -------- The following example checks that ``a * a+ * a == a`` and ``a+ * a * a+ == a+``: >>> a = np.random.randn(9, 6) >>> B = np.linalg.pinv(a) >>> np.allclose(a, np.dot(a, np.dot(B, a))) True >>> np.allclose(B, np.dot(B, np.dot(a, B))) True """ a, wrap = _makearray(a) _assertNoEmpty2d(a) a = a.conjugate() u, s, vt = svd(a, 0) m = u.shape[0] n = vt.shape[1] cutoff = rcond*maximum.reduce(s) for i in range(min(n, m)): if s[i] > cutoff: s[i] = 1./s[i] else: s[i] = 0.; res = dot(transpose(vt), multiply(s[:, newaxis], transpose(u))) return wrap(res) # Determinant def slogdet(a): """ Compute the sign and (natural) logarithm of the determinant of an array. If an array has a very small or very large determinant, than a call to `det` may overflow or underflow. This routine is more robust against such issues, because it computes the logarithm of the determinant rather than the determinant itself. Parameters ---------- a : (..., M, M) array_like Input array, has to be a square 2-D array. Returns ------- sign : (...) array_like A number representing the sign of the determinant. For a real matrix, this is 1, 0, or -1. For a complex matrix, this is a complex number with absolute value 1 (i.e., it is on the unit circle), or else 0. logdet : (...) array_like The natural log of the absolute value of the determinant. If the determinant is zero, then `sign` will be 0 and `logdet` will be -Inf. In all cases, the determinant is equal to ``sign * np.exp(logdet)``. See Also -------- det Notes ----- Broadcasting rules apply, see the `numpy.linalg` documentation for details. The determinant is computed via LU factorization using the LAPACK routine z/dgetrf. .. versionadded:: 1.6.0. Examples -------- The determinant of a 2-D array ``[[a, b], [c, d]]`` is ``ad - bc``: >>> a = np.array([[1, 2], [3, 4]]) >>> (sign, logdet) = np.linalg.slogdet(a) >>> (sign, logdet) (-1, 0.69314718055994529) >>> sign * np.exp(logdet) -2.0 Computing log-determinants for a stack of matrices: >>> a = np.array([ [[1, 2], [3, 4]], [[1, 2], [2, 1]], [[1, 3], [3, 1]] ]) >>> a.shape (3, 2, 2) >>> sign, logdet = np.linalg.slogdet(a) >>> (sign, logdet) (array([-1., -1., -1.]), array([ 0.69314718, 1.09861229, 2.07944154])) >>> sign * np.exp(logdet) array([-2., -3., -8.]) This routine succeeds where ordinary `det` does not: >>> np.linalg.det(np.eye(500) * 0.1) 0.0 >>> np.linalg.slogdet(np.eye(500) * 0.1) (1, -1151.2925464970228) """ a = asarray(a) _assertNoEmpty2d(a) _assertRankAtLeast2(a) _assertNdSquareness(a) t, result_t = _commonType(a) real_t = _realType(result_t) signature = 'D->Dd' if isComplexType(t) else 'd->dd' sign, logdet = _umath_linalg.slogdet(a, signature=signature) return sign.astype(result_t), logdet.astype(real_t) def det(a): """ Compute the determinant of an array. Parameters ---------- a : (..., M, M) array_like Input array to compute determinants for. Returns ------- det : (...) array_like Determinant of `a`. See Also -------- slogdet : Another way to representing the determinant, more suitable for large matrices where underflow/overflow may occur. Notes ----- Broadcasting rules apply, see the `numpy.linalg` documentation for details. The determinant is computed via LU factorization using the LAPACK routine z/dgetrf. Examples -------- The determinant of a 2-D array [[a, b], [c, d]] is ad - bc: >>> a = np.array([[1, 2], [3, 4]]) >>> np.linalg.det(a) -2.0 Computing determinants for a stack of matrices: >>> a = np.array([ [[1, 2], [3, 4]], [[1, 2], [2, 1]], [[1, 3], [3, 1]] ]) >>> a.shape (2, 2, 2 >>> np.linalg.det(a) array([-2., -3., -8.]) """ a = asarray(a) _assertNoEmpty2d(a) _assertRankAtLeast2(a) _assertNdSquareness(a) t, result_t = _commonType(a) signature = 'D->D' if isComplexType(t) else 'd->d' return _umath_linalg.det(a, signature=signature).astype(result_t) # Linear Least Squares def lstsq(a, b, rcond=-1): """ Return the least-squares solution to a linear matrix equation. Solves the equation `a x = b` by computing a vector `x` that minimizes the Euclidean 2-norm `|| b - a x ||^2`. The equation may be under-, well-, or over- determined (i.e., the number of linearly independent rows of `a` can be less than, equal to, or greater than its number of linearly independent columns). If `a` is square and of full rank, then `x` (but for round-off error) is the "exact" solution of the equation. Parameters ---------- a : (M, N) array_like "Coefficient" matrix. b : {(M,), (M, K)} array_like Ordinate or "dependent variable" values. If `b` is two-dimensional, the least-squares solution is calculated for each of the `K` columns of `b`. rcond : float, optional Cut-off ratio for small singular values of `a`. Singular values are set to zero if they are smaller than `rcond` times the largest singular value of `a`. Returns ------- x : {(N,), (N, K)} ndarray Least-squares solution. If `b` is two-dimensional, the solutions are in the `K` columns of `x`. 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 `b` is 1-dimensional, this is a (1,) shape array. Otherwise the shape is (K,). rank : int Rank of matrix `a`. s : (min(M, N),) ndarray Singular values of `a`. Raises ------ LinAlgError If computation does not converge. Notes ----- If `b` is a matrix, then all array results are returned as matrices. Examples -------- Fit a line, ``y = mx + c``, through some noisy data-points: >>> x = np.array([0, 1, 2, 3]) >>> y = np.array([-1, 0.2, 0.9, 2.1]) By examining the coefficients, we see that the line should have a gradient of roughly 1 and cut the y-axis at, more or less, -1. We can rewrite the line equation as ``y = Ap``, where ``A = [[x 1]]`` and ``p = [[m], [c]]``. Now use `lstsq` to solve for `p`: >>> A = np.vstack([x, np.ones(len(x))]).T >>> A array([[ 0., 1.], [ 1., 1.], [ 2., 1.], [ 3., 1.]]) >>> m, c = np.linalg.lstsq(A, y)[0] >>> print m, c 1.0 -0.95 Plot the data along with the fitted line: >>> import matplotlib.pyplot as plt >>> plt.plot(x, y, 'o', label='Original data', markersize=10) >>> plt.plot(x, m*x + c, 'r', label='Fitted line') >>> plt.legend() >>> plt.show() """ import math a, _ = _makearray(a) b, wrap = _makearray(b) is_1d = len(b.shape) == 1 if is_1d: b = b[:, newaxis] _assertRank2(a, b) m = a.shape[0] n = a.shape[1] n_rhs = b.shape[1] ldb = max(n, m) if m != b.shape[0]: raise LinAlgError('Incompatible dimensions') t, result_t = _commonType(a, b) result_real_t = _realType(result_t) real_t = _linalgRealType(t) bstar = zeros((ldb, n_rhs), t) bstar[:b.shape[0], :n_rhs] = b.copy() a, bstar = _fastCopyAndTranspose(t, a, bstar) a, bstar = _to_native_byte_order(a, bstar) s = zeros((min(m, n),), real_t) nlvl = max( 0, int( math.log( float(min(m, n))/2. ) ) + 1 ) iwork = zeros((3*min(m, n)*nlvl+11*min(m, n),), fortran_int) if isComplexType(t): lapack_routine = lapack_lite.zgelsd lwork = 1 rwork = zeros((lwork,), real_t) work = zeros((lwork,), t) results = lapack_routine(m, n, n_rhs, a, m, bstar, ldb, s, rcond, 0, work, -1, rwork, iwork, 0) lwork = int(abs(work[0])) rwork = zeros((lwork,), real_t) a_real = zeros((m, n), real_t) bstar_real = zeros((ldb, n_rhs,), real_t) results = lapack_lite.dgelsd(m, n, n_rhs, a_real, m, bstar_real, ldb, s, rcond, 0, rwork, -1, iwork, 0) lrwork = int(rwork[0]) work = zeros((lwork,), t) rwork = zeros((lrwork,), real_t) results = lapack_routine(m, n, n_rhs, a, m, bstar, ldb, s, rcond, 0, work, lwork, rwork, iwork, 0) else: lapack_routine = lapack_lite.dgelsd lwork = 1 work = zeros((lwork,), t) results = lapack_routine(m, n, n_rhs, a, m, bstar, ldb, s, rcond, 0, work, -1, iwork, 0) lwork = int(work[0]) work = zeros((lwork,), t) results = lapack_routine(m, n, n_rhs, a, m, bstar, ldb, s, rcond, 0, work, lwork, iwork, 0) if results['info'] > 0: raise LinAlgError('SVD did not converge in Linear Least Squares') resids = array([], result_real_t) if is_1d: x = array(ravel(bstar)[:n], dtype=result_t, copy=True) if results['rank'] == n and m > n: if isComplexType(t): resids = array([sum(abs(ravel(bstar)[n:])**2)], dtype=result_real_t) else: resids = array([sum((ravel(bstar)[n:])**2)], dtype=result_real_t) else: x = array(transpose(bstar)[:n,:], dtype=result_t, copy=True) if results['rank'] == n and m > n: if isComplexType(t): resids = sum(abs(transpose(bstar)[n:,:])**2, axis=0).astype( result_real_t) else: resids = sum((transpose(bstar)[n:,:])**2, axis=0).astype( result_real_t) st = s[:min(n, m)].copy().astype(result_real_t) return wrap(x), wrap(resids), results['rank'], st def _multi_svd_norm(x, row_axis, col_axis, op): """Compute the extreme singular values of the 2-D matrices in `x`. This is a private utility function used by numpy.linalg.norm(). Parameters ---------- x : ndarray row_axis, col_axis : int The axes of `x` that hold the 2-D matrices. op : callable This should be either numpy.amin or numpy.amax. Returns ------- result : float or ndarray If `x` is 2-D, the return values is a float. Otherwise, it is an array with ``x.ndim - 2`` dimensions. The return values are either the minimum or maximum of the singular values of the matrices, depending on whether `op` is `numpy.amin` or `numpy.amax`. """ if row_axis > col_axis: row_axis -= 1 y = rollaxis(rollaxis(x, col_axis, x.ndim), row_axis, -1) result = op(svd(y, compute_uv=0), axis=-1) return result def norm(x, ord=None, axis=None): """ Matrix or vector norm. This function is able to return one of seven different matrix norms, or one of an infinite number of vector norms (described below), depending on the value of the ``ord`` parameter. Parameters ---------- x : array_like Input array. If `axis` is None, `x` must be 1-D or 2-D. ord : {non-zero int, inf, -inf, 'fro'}, optional Order of the norm (see table under ``Notes``). inf means numpy's `inf` object. axis : {int, 2-tuple of ints, None}, optional If `axis` is an integer, it specifies the axis of `x` along which to compute the vector norms. If `axis` is a 2-tuple, it specifies the axes that hold 2-D matrices, and the matrix norms of these matrices are computed. If `axis` is None then either a vector norm (when `x` is 1-D) or a matrix norm (when `x` is 2-D) is returned. Returns ------- n : float or ndarray Norm of the matrix or vector(s). Notes ----- For values of ``ord <= 0``, the result is, strictly speaking, not a mathematical 'norm', but it may still be useful for various numerical purposes. The following norms can be calculated: ===== ============================ ========================== ord norm for matrices norm for vectors ===== ============================ ========================== None Frobenius norm 2-norm 'fro' Frobenius norm -- inf max(sum(abs(x), axis=1)) max(abs(x)) -inf min(sum(abs(x), axis=1)) min(abs(x)) 0 -- sum(x != 0) 1 max(sum(abs(x), axis=0)) as below -1 min(sum(abs(x), axis=0)) as below 2 2-norm (largest sing. value) as below -2 smallest singular value as below other -- sum(abs(x)**ord)**(1./ord) ===== ============================ ========================== The Frobenius norm is given by [1]_: :math:`||A||_F = [\\sum_{i,j} abs(a_{i,j})^2]^{1/2}` References ---------- .. [1] G. H. Golub and C. F. Van Loan, *Matrix Computations*, Baltimore, MD, Johns Hopkins University Press, 1985, pg. 15 Examples -------- >>> from numpy import linalg as LA >>> a = np.arange(9) - 4 >>> a array([-4, -3, -2, -1, 0, 1, 2, 3, 4]) >>> b = a.reshape((3, 3)) >>> b array([[-4, -3, -2], [-1, 0, 1], [ 2, 3, 4]]) >>> LA.norm(a) 7.745966692414834 >>> LA.norm(b) 7.745966692414834 >>> LA.norm(b, 'fro') 7.745966692414834 >>> LA.norm(a, np.inf) 4 >>> LA.norm(b, np.inf) 9 >>> LA.norm(a, -np.inf) 0 >>> LA.norm(b, -np.inf) 2 >>> LA.norm(a, 1) 20 >>> LA.norm(b, 1) 7 >>> LA.norm(a, -1) -4.6566128774142013e-010 >>> LA.norm(b, -1) 6 >>> LA.norm(a, 2) 7.745966692414834 >>> LA.norm(b, 2) 7.3484692283495345 >>> LA.norm(a, -2) nan >>> LA.norm(b, -2) 1.8570331885190563e-016 >>> LA.norm(a, 3) 5.8480354764257312 >>> LA.norm(a, -3) nan Using the `axis` argument to compute vector norms: >>> c = np.array([[ 1, 2, 3], ... [-1, 1, 4]]) >>> LA.norm(c, axis=0) array([ 1.41421356, 2.23606798, 5. ]) >>> LA.norm(c, axis=1) array([ 3.74165739, 4.24264069]) >>> LA.norm(c, ord=1, axis=1) array([6, 6]) Using the `axis` argument to compute matrix norms: >>> m = np.arange(8).reshape(2,2,2) >>> LA.norm(m, axis=(1,2)) array([ 3.74165739, 11.22497216]) >>> LA.norm(m[0, :, :]), LA.norm(m[1, :, :]) (3.7416573867739413, 11.224972160321824) """ x = asarray(x) # 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)) # Normalize the `axis` argument to a tuple. nd = x.ndim if axis is None: axis = tuple(range(nd)) elif not isinstance(axis, tuple): axis = (axis,) if len(axis) == 1: if ord == Inf: return abs(x).max(axis=axis) elif ord == -Inf: return abs(x).min(axis=axis) elif ord == 0: # Zero norm return (x != 0).sum(axis=axis) elif ord == 1: # special case for speedup return add.reduce(abs(x), axis=axis) elif ord is None or ord == 2: # special case for speedup s = (x.conj() * x).real return sqrt(add.reduce(s, axis=axis)) else: try: ord + 1 except TypeError: raise ValueError("Invalid norm order for vectors.") if x.dtype.type is longdouble: # Convert to a float type, so integer arrays give # float results. Don't apply asfarray to longdouble arrays, # because it will downcast to float64. absx = abs(x) else: absx = x if isComplexType(x.dtype.type) else asfarray(x) if absx.dtype is x.dtype: absx = abs(absx) else: # if the type changed, we can safely overwrite absx abs(absx, out=absx) absx **= ord return add.reduce(absx, axis=axis) ** (1.0 / ord) elif len(axis) == 2: row_axis, col_axis = axis if not (-nd <= row_axis < nd and -nd <= col_axis < nd): raise ValueError('Invalid axis %r for an array with shape %r' % (axis, x.shape)) if row_axis % nd == col_axis % nd: raise ValueError('Duplicate axes given.') if ord == 2: return _multi_svd_norm(x, row_axis, col_axis, amax) elif ord == -2: return _multi_svd_norm(x, row_axis, col_axis, amin) elif ord == 1: if col_axis > row_axis: col_axis -= 1 return add.reduce(abs(x), axis=row_axis).max(axis=col_axis) elif ord == Inf: if row_axis > col_axis: row_axis -= 1 return add.reduce(abs(x), axis=col_axis).max(axis=row_axis) elif ord == -1: if col_axis > row_axis: col_axis -= 1 return add.reduce(abs(x), axis=row_axis).min(axis=col_axis) elif ord == -Inf: if row_axis > col_axis: row_axis -= 1 return add.reduce(abs(x), axis=col_axis).min(axis=row_axis) elif ord in [None, 'fro', 'f']: return sqrt(add.reduce((x.conj() * x).real, axis=axis)) else: raise ValueError("Invalid norm order for matrices.") else: raise ValueError("Improper number of dimensions to norm.") numpy-1.8.2/numpy/linalg/lapack_lite/0000775000175100017510000000000012371375430020717 5ustar vagrantvagrant00000000000000numpy-1.8.2/numpy/linalg/lapack_lite/zlapack_lite.c0000664000175100017510000300630312370216242023524 0ustar vagrantvagrant00000000000000/* NOTE: This is generated code. Look in Misc/lapack_lite for information on remaking this file. */ #include "f2c.h" #ifdef HAVE_CONFIG #include "config.h" #else extern doublereal dlamch_(char *); #define EPSILON dlamch_("Epsilon") #define SAFEMINIMUM dlamch_("Safe minimum") #define PRECISION dlamch_("Precision") #define BASE dlamch_("Base") #endif extern doublereal dlapy2_(doublereal *x, doublereal *y); /* Table of constant values */ static integer c__1 = 1; static doublecomplex c_b59 = {0.,0.}; static doublecomplex c_b60 = {1.,0.}; static integer c_n1 = -1; static integer c__3 = 3; static integer c__2 = 2; static integer c__0 = 0; static integer c__8 = 8; static integer c__4 = 4; static integer c__65 = 65; static integer c__6 = 6; static integer c__9 = 9; static doublereal c_b324 = 0.; static doublereal c_b1015 = 1.; static integer c__15 = 15; static logical c_false = FALSE_; static doublereal c_b1294 = -1.; static doublereal c_b2210 = .5; /* Subroutine */ int zdrot_(integer *n, doublecomplex *cx, integer *incx, doublecomplex *cy, integer *incy, doublereal *c__, doublereal *s) { /* System generated locals */ integer i__1, i__2, i__3, i__4; doublecomplex z__1, z__2, z__3; /* Local variables */ static integer i__, ix, iy; static doublecomplex ctemp; /* applies a plane rotation, where the cos and sin (c and s) are real and the vectors cx and cy are complex. jack dongarra, linpack, 3/11/78. ===================================================================== */ /* Parameter adjustments */ --cy; --cx; /* Function Body */ if (*n <= 0) { return 0; } if (*incx == 1 && *incy == 1) { goto L20; } /* code for unequal increments or equal increments not equal to 1 */ ix = 1; iy = 1; if (*incx < 0) { ix = (-(*n) + 1) * *incx + 1; } if (*incy < 0) { iy = (-(*n) + 1) * *incy + 1; } i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = ix; z__2.r = *c__ * cx[i__2].r, z__2.i = *c__ * cx[i__2].i; i__3 = iy; z__3.r = *s * cy[i__3].r, z__3.i = *s * cy[i__3].i; z__1.r = z__2.r + z__3.r, z__1.i = z__2.i + z__3.i; ctemp.r = z__1.r, ctemp.i = z__1.i; i__2 = iy; i__3 = iy; z__2.r = *c__ * cy[i__3].r, z__2.i = *c__ * cy[i__3].i; i__4 = ix; z__3.r = *s * cx[i__4].r, z__3.i = *s * cx[i__4].i; z__1.r = z__2.r - z__3.r, z__1.i = z__2.i - z__3.i; cy[i__2].r = z__1.r, cy[i__2].i = z__1.i; i__2 = ix; cx[i__2].r = ctemp.r, cx[i__2].i = ctemp.i; ix += *incx; iy += *incy; /* L10: */ } return 0; /* code for both increments equal to 1 */ L20: i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = i__; z__2.r = *c__ * cx[i__2].r, z__2.i = *c__ * cx[i__2].i; i__3 = i__; z__3.r = *s * cy[i__3].r, z__3.i = *s * cy[i__3].i; z__1.r = z__2.r + z__3.r, z__1.i = z__2.i + z__3.i; ctemp.r = z__1.r, ctemp.i = z__1.i; i__2 = i__; i__3 = i__; z__2.r = *c__ * cy[i__3].r, z__2.i = *c__ * cy[i__3].i; i__4 = i__; z__3.r = *s * cx[i__4].r, z__3.i = *s * cx[i__4].i; z__1.r = z__2.r - z__3.r, z__1.i = z__2.i - z__3.i; cy[i__2].r = z__1.r, cy[i__2].i = z__1.i; i__2 = i__; cx[i__2].r = ctemp.r, cx[i__2].i = ctemp.i; /* L30: */ } return 0; } /* zdrot_ */ /* Subroutine */ int zgebak_(char *job, char *side, integer *n, integer *ilo, integer *ihi, doublereal *scale, integer *m, doublecomplex *v, integer *ldv, integer *info) { /* System generated locals */ integer v_dim1, v_offset, i__1; /* Local variables */ static integer i__, k; static doublereal s; static integer ii; extern logical lsame_(char *, char *); static logical leftv; extern /* Subroutine */ int zswap_(integer *, doublecomplex *, integer *, doublecomplex *, integer *), xerbla_(char *, integer *), zdscal_(integer *, doublereal *, doublecomplex *, integer *); static logical rightv; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University September 30, 1994 Purpose ======= ZGEBAK forms the right or left eigenvectors of a complex general matrix by backward transformation on the computed eigenvectors of the balanced matrix output by ZGEBAL. Arguments ========= JOB (input) CHARACTER*1 Specifies the type of backward transformation required: = 'N', do nothing, return immediately; = 'P', do backward transformation for permutation only; = 'S', do backward transformation for scaling only; = 'B', do backward transformations for both permutation and scaling. JOB must be the same as the argument JOB supplied to ZGEBAL. SIDE (input) CHARACTER*1 = 'R': V contains right eigenvectors; = 'L': V contains left eigenvectors. N (input) INTEGER The number of rows of the matrix V. N >= 0. ILO (input) INTEGER IHI (input) INTEGER The integers ILO and IHI determined by ZGEBAL. 1 <= ILO <= IHI <= N, if N > 0; ILO=1 and IHI=0, if N=0. SCALE (input) DOUBLE PRECISION array, dimension (N) Details of the permutation and scaling factors, as returned by ZGEBAL. M (input) INTEGER The number of columns of the matrix V. M >= 0. V (input/output) COMPLEX*16 array, dimension (LDV,M) On entry, the matrix of right or left eigenvectors to be transformed, as returned by ZHSEIN or ZTREVC. On exit, V is overwritten by the transformed eigenvectors. LDV (input) INTEGER The leading dimension of the array V. LDV >= max(1,N). INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value. ===================================================================== Decode and Test the input parameters */ /* Parameter adjustments */ --scale; v_dim1 = *ldv; v_offset = 1 + v_dim1; v -= v_offset; /* Function Body */ rightv = lsame_(side, "R"); leftv = lsame_(side, "L"); *info = 0; if (! lsame_(job, "N") && ! lsame_(job, "P") && ! lsame_(job, "S") && ! lsame_(job, "B")) { *info = -1; } else if (! rightv && ! leftv) { *info = -2; } else if (*n < 0) { *info = -3; } else if ((*ilo < 1) || (*ilo > max(1,*n))) { *info = -4; } else if ((*ihi < min(*ilo,*n)) || (*ihi > *n)) { *info = -5; } else if (*m < 0) { *info = -7; } else if (*ldv < max(1,*n)) { *info = -9; } if (*info != 0) { i__1 = -(*info); xerbla_("ZGEBAK", &i__1); return 0; } /* Quick return if possible */ if (*n == 0) { return 0; } if (*m == 0) { return 0; } if (lsame_(job, "N")) { return 0; } if (*ilo == *ihi) { goto L30; } /* Backward balance */ if ((lsame_(job, "S")) || (lsame_(job, "B"))) { if (rightv) { i__1 = *ihi; for (i__ = *ilo; i__ <= i__1; ++i__) { s = scale[i__]; zdscal_(m, &s, &v[i__ + v_dim1], ldv); /* L10: */ } } if (leftv) { i__1 = *ihi; for (i__ = *ilo; i__ <= i__1; ++i__) { s = 1. / scale[i__]; zdscal_(m, &s, &v[i__ + v_dim1], ldv); /* L20: */ } } } /* Backward permutation For I = ILO-1 step -1 until 1, IHI+1 step 1 until N do -- */ L30: if ((lsame_(job, "P")) || (lsame_(job, "B"))) { if (rightv) { i__1 = *n; for (ii = 1; ii <= i__1; ++ii) { i__ = ii; if (i__ >= *ilo && i__ <= *ihi) { goto L40; } if (i__ < *ilo) { i__ = *ilo - ii; } k = (integer) scale[i__]; if (k == i__) { goto L40; } zswap_(m, &v[i__ + v_dim1], ldv, &v[k + v_dim1], ldv); L40: ; } } if (leftv) { i__1 = *n; for (ii = 1; ii <= i__1; ++ii) { i__ = ii; if (i__ >= *ilo && i__ <= *ihi) { goto L50; } if (i__ < *ilo) { i__ = *ilo - ii; } k = (integer) scale[i__]; if (k == i__) { goto L50; } zswap_(m, &v[i__ + v_dim1], ldv, &v[k + v_dim1], ldv); L50: ; } } } return 0; /* End of ZGEBAK */ } /* zgebak_ */ /* Subroutine */ int zgebal_(char *job, integer *n, doublecomplex *a, integer *lda, integer *ilo, integer *ihi, doublereal *scale, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3; doublereal d__1, d__2; /* Builtin functions */ double d_imag(doublecomplex *), z_abs(doublecomplex *); /* Local variables */ static doublereal c__, f, g; static integer i__, j, k, l, m; static doublereal r__, s, ca, ra; static integer ica, ira, iexc; extern logical lsame_(char *, char *); extern /* Subroutine */ int zswap_(integer *, doublecomplex *, integer *, doublecomplex *, integer *); static doublereal sfmin1, sfmin2, sfmax1, sfmax2; extern /* Subroutine */ int xerbla_(char *, integer *), zdscal_( integer *, doublereal *, doublecomplex *, integer *); extern integer izamax_(integer *, doublecomplex *, integer *); static logical noconv; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= ZGEBAL balances a general complex matrix A. This involves, first, permuting A by a similarity transformation to isolate eigenvalues in the first 1 to ILO-1 and last IHI+1 to N elements on the diagonal; and second, applying a diagonal similarity transformation to rows and columns ILO to IHI to make the rows and columns as close in norm as possible. Both steps are optional. Balancing may reduce the 1-norm of the matrix, and improve the accuracy of the computed eigenvalues and/or eigenvectors. Arguments ========= JOB (input) CHARACTER*1 Specifies the operations to be performed on A: = 'N': none: simply set ILO = 1, IHI = N, SCALE(I) = 1.0 for i = 1,...,N; = 'P': permute only; = 'S': scale only; = 'B': both permute and scale. N (input) INTEGER The order of the matrix A. N >= 0. A (input/output) COMPLEX*16 array, dimension (LDA,N) On entry, the input matrix A. On exit, A is overwritten by the balanced matrix. If JOB = 'N', A is not referenced. See Further Details. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,N). ILO (output) INTEGER IHI (output) INTEGER ILO and IHI are set to integers such that on exit A(i,j) = 0 if i > j and j = 1,...,ILO-1 or I = IHI+1,...,N. If JOB = 'N' or 'S', ILO = 1 and IHI = N. SCALE (output) DOUBLE PRECISION array, dimension (N) Details of the permutations and scaling factors applied to A. If P(j) is the index of the row and column interchanged with row and column j and D(j) is the scaling factor applied to row and column j, then SCALE(j) = P(j) for j = 1,...,ILO-1 = D(j) for j = ILO,...,IHI = P(j) for j = IHI+1,...,N. The order in which the interchanges are made is N to IHI+1, then 1 to ILO-1. INFO (output) INTEGER = 0: successful exit. < 0: if INFO = -i, the i-th argument had an illegal value. Further Details =============== The permutations consist of row and column interchanges which put the matrix in the form ( T1 X Y ) P A P = ( 0 B Z ) ( 0 0 T2 ) where T1 and T2 are upper triangular matrices whose eigenvalues lie along the diagonal. The column indices ILO and IHI mark the starting and ending columns of the submatrix B. Balancing consists of applying a diagonal similarity transformation inv(D) * B * D to make the 1-norms of each row of B and its corresponding column nearly equal. The output matrix is ( T1 X*D Y ) ( 0 inv(D)*B*D inv(D)*Z ). ( 0 0 T2 ) Information about the permutations P and the diagonal matrix D is returned in the vector SCALE. This subroutine is based on the EISPACK routine CBAL. Modified by Tzu-Yi Chen, Computer Science Division, University of California at Berkeley, USA ===================================================================== Test the input parameters */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --scale; /* Function Body */ *info = 0; if (! lsame_(job, "N") && ! lsame_(job, "P") && ! lsame_(job, "S") && ! lsame_(job, "B")) { *info = -1; } else if (*n < 0) { *info = -2; } else if (*lda < max(1,*n)) { *info = -4; } if (*info != 0) { i__1 = -(*info); xerbla_("ZGEBAL", &i__1); return 0; } k = 1; l = *n; if (*n == 0) { goto L210; } if (lsame_(job, "N")) { i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { scale[i__] = 1.; /* L10: */ } goto L210; } if (lsame_(job, "S")) { goto L120; } /* Permutation to isolate eigenvalues if possible */ goto L50; /* Row and column exchange. */ L20: scale[m] = (doublereal) j; if (j == m) { goto L30; } zswap_(&l, &a[j * a_dim1 + 1], &c__1, &a[m * a_dim1 + 1], &c__1); i__1 = *n - k + 1; zswap_(&i__1, &a[j + k * a_dim1], lda, &a[m + k * a_dim1], lda); L30: switch (iexc) { case 1: goto L40; case 2: goto L80; } /* Search for rows isolating an eigenvalue and push them down. */ L40: if (l == 1) { goto L210; } --l; L50: for (j = l; j >= 1; --j) { i__1 = l; for (i__ = 1; i__ <= i__1; ++i__) { if (i__ == j) { goto L60; } i__2 = j + i__ * a_dim1; if ((a[i__2].r != 0.) || (d_imag(&a[j + i__ * a_dim1]) != 0.)) { goto L70; } L60: ; } m = l; iexc = 1; goto L20; L70: ; } goto L90; /* Search for columns isolating an eigenvalue and push them left. */ L80: ++k; L90: i__1 = l; for (j = k; j <= i__1; ++j) { i__2 = l; for (i__ = k; i__ <= i__2; ++i__) { if (i__ == j) { goto L100; } i__3 = i__ + j * a_dim1; if ((a[i__3].r != 0.) || (d_imag(&a[i__ + j * a_dim1]) != 0.)) { goto L110; } L100: ; } m = k; iexc = 2; goto L20; L110: ; } L120: i__1 = l; for (i__ = k; i__ <= i__1; ++i__) { scale[i__] = 1.; /* L130: */ } if (lsame_(job, "P")) { goto L210; } /* Balance the submatrix in rows K to L. Iterative loop for norm reduction */ sfmin1 = SAFEMINIMUM / PRECISION; sfmax1 = 1. / sfmin1; sfmin2 = sfmin1 * 8.; sfmax2 = 1. / sfmin2; L140: noconv = FALSE_; i__1 = l; for (i__ = k; i__ <= i__1; ++i__) { c__ = 0.; r__ = 0.; i__2 = l; for (j = k; j <= i__2; ++j) { if (j == i__) { goto L150; } i__3 = j + i__ * a_dim1; c__ += (d__1 = a[i__3].r, abs(d__1)) + (d__2 = d_imag(&a[j + i__ * a_dim1]), abs(d__2)); i__3 = i__ + j * a_dim1; r__ += (d__1 = a[i__3].r, abs(d__1)) + (d__2 = d_imag(&a[i__ + j * a_dim1]), abs(d__2)); L150: ; } ica = izamax_(&l, &a[i__ * a_dim1 + 1], &c__1); ca = z_abs(&a[ica + i__ * a_dim1]); i__2 = *n - k + 1; ira = izamax_(&i__2, &a[i__ + k * a_dim1], lda); ra = z_abs(&a[i__ + (ira + k - 1) * a_dim1]); /* Guard against zero C or R due to underflow. */ if ((c__ == 0.) || (r__ == 0.)) { goto L200; } g = r__ / 8.; f = 1.; s = c__ + r__; L160: /* Computing MAX */ d__1 = max(f,c__); /* Computing MIN */ d__2 = min(r__,g); if (((c__ >= g) || (max(d__1,ca) >= sfmax2)) || (min(d__2,ra) <= sfmin2)) { goto L170; } f *= 8.; c__ *= 8.; ca *= 8.; r__ /= 8.; g /= 8.; ra /= 8.; goto L160; L170: g = c__ / 8.; L180: /* Computing MIN */ d__1 = min(f,c__), d__1 = min(d__1,g); if (((g < r__) || (max(r__,ra) >= sfmax2)) || (min(d__1,ca) <= sfmin2) ) { goto L190; } f /= 8.; c__ /= 8.; g /= 8.; ca /= 8.; r__ *= 8.; ra *= 8.; goto L180; /* Now balance. */ L190: if (c__ + r__ >= s * .95) { goto L200; } if (f < 1. && scale[i__] < 1.) { if (f * scale[i__] <= sfmin1) { goto L200; } } if (f > 1. && scale[i__] > 1.) { if (scale[i__] >= sfmax1 / f) { goto L200; } } g = 1. / f; scale[i__] *= f; noconv = TRUE_; i__2 = *n - k + 1; zdscal_(&i__2, &g, &a[i__ + k * a_dim1], lda); zdscal_(&l, &f, &a[i__ * a_dim1 + 1], &c__1); L200: ; } if (noconv) { goto L140; } L210: *ilo = k; *ihi = l; return 0; /* End of ZGEBAL */ } /* zgebal_ */ /* Subroutine */ int zgebd2_(integer *m, integer *n, doublecomplex *a, integer *lda, doublereal *d__, doublereal *e, doublecomplex *tauq, doublecomplex *taup, doublecomplex *work, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3, i__4; doublecomplex z__1; /* Builtin functions */ void d_cnjg(doublecomplex *, doublecomplex *); /* Local variables */ static integer i__; static doublecomplex alpha; extern /* Subroutine */ int zlarf_(char *, integer *, integer *, doublecomplex *, integer *, doublecomplex *, doublecomplex *, integer *, doublecomplex *), xerbla_(char *, integer *), zlarfg_(integer *, doublecomplex *, doublecomplex *, integer *, doublecomplex *), zlacgv_(integer *, doublecomplex *, integer *); /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University September 30, 1994 Purpose ======= ZGEBD2 reduces a complex general m by n matrix A to upper or lower real bidiagonal form B by a unitary transformation: Q' * A * P = B. If m >= n, B is upper bidiagonal; if m < n, B is lower bidiagonal. Arguments ========= M (input) INTEGER The number of rows in the matrix A. M >= 0. N (input) INTEGER The number of columns in the matrix A. N >= 0. A (input/output) COMPLEX*16 array, dimension (LDA,N) On entry, the m by n general matrix to be reduced. On exit, if m >= n, the diagonal and the first superdiagonal are overwritten with the upper bidiagonal matrix B; the elements below the diagonal, with the array TAUQ, represent the unitary matrix Q as a product of elementary reflectors, and the elements above the first superdiagonal, with the array TAUP, represent the unitary matrix P as a product of elementary reflectors; if m < n, the diagonal and the first subdiagonal are overwritten with the lower bidiagonal matrix B; the elements below the first subdiagonal, with the array TAUQ, represent the unitary matrix Q as a product of elementary reflectors, and the elements above the diagonal, with the array TAUP, represent the unitary matrix P as a product of elementary reflectors. See Further Details. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,M). D (output) DOUBLE PRECISION array, dimension (min(M,N)) The diagonal elements of the bidiagonal matrix B: D(i) = A(i,i). E (output) DOUBLE PRECISION array, dimension (min(M,N)-1) The off-diagonal elements of the bidiagonal matrix B: if m >= n, E(i) = A(i,i+1) for i = 1,2,...,n-1; if m < n, E(i) = A(i+1,i) for i = 1,2,...,m-1. TAUQ (output) COMPLEX*16 array dimension (min(M,N)) The scalar factors of the elementary reflectors which represent the unitary matrix Q. See Further Details. TAUP (output) COMPLEX*16 array, dimension (min(M,N)) The scalar factors of the elementary reflectors which represent the unitary matrix P. See Further Details. WORK (workspace) COMPLEX*16 array, dimension (max(M,N)) INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value. Further Details =============== The matrices Q and P are represented as products of elementary reflectors: If m >= n, Q = H(1) H(2) . . . H(n) and P = G(1) G(2) . . . G(n-1) Each H(i) and G(i) has the form: H(i) = I - tauq * v * v' and G(i) = I - taup * u * u' where tauq and taup are complex scalars, and v and u are complex vectors; v(1:i-1) = 0, v(i) = 1, and v(i+1:m) is stored on exit in A(i+1:m,i); u(1:i) = 0, u(i+1) = 1, and u(i+2:n) is stored on exit in A(i,i+2:n); tauq is stored in TAUQ(i) and taup in TAUP(i). If m < n, Q = H(1) H(2) . . . H(m-1) and P = G(1) G(2) . . . G(m) Each H(i) and G(i) has the form: H(i) = I - tauq * v * v' and G(i) = I - taup * u * u' where tauq and taup are complex scalars, v and u are complex vectors; v(1:i) = 0, v(i+1) = 1, and v(i+2:m) is stored on exit in A(i+2:m,i); u(1:i-1) = 0, u(i) = 1, and u(i+1:n) is stored on exit in A(i,i+1:n); tauq is stored in TAUQ(i) and taup in TAUP(i). The contents of A on exit are illustrated by the following examples: m = 6 and n = 5 (m > n): m = 5 and n = 6 (m < n): ( d e u1 u1 u1 ) ( d u1 u1 u1 u1 u1 ) ( v1 d e u2 u2 ) ( e d u2 u2 u2 u2 ) ( v1 v2 d e u3 ) ( v1 e d u3 u3 u3 ) ( v1 v2 v3 d e ) ( v1 v2 e d u4 u4 ) ( v1 v2 v3 v4 d ) ( v1 v2 v3 e d u5 ) ( v1 v2 v3 v4 v5 ) where d and e denote diagonal and off-diagonal elements of B, vi denotes an element of the vector defining H(i), and ui an element of the vector defining G(i). ===================================================================== Test the input parameters */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --d__; --e; --tauq; --taup; --work; /* Function Body */ *info = 0; if (*m < 0) { *info = -1; } else if (*n < 0) { *info = -2; } else if (*lda < max(1,*m)) { *info = -4; } if (*info < 0) { i__1 = -(*info); xerbla_("ZGEBD2", &i__1); return 0; } if (*m >= *n) { /* Reduce to upper bidiagonal form */ i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { /* Generate elementary reflector H(i) to annihilate A(i+1:m,i) */ i__2 = i__ + i__ * a_dim1; alpha.r = a[i__2].r, alpha.i = a[i__2].i; i__2 = *m - i__ + 1; /* Computing MIN */ i__3 = i__ + 1; zlarfg_(&i__2, &alpha, &a[min(i__3,*m) + i__ * a_dim1], &c__1, & tauq[i__]); i__2 = i__; d__[i__2] = alpha.r; i__2 = i__ + i__ * a_dim1; a[i__2].r = 1., a[i__2].i = 0.; /* Apply H(i)' to A(i:m,i+1:n) from the left */ i__2 = *m - i__ + 1; i__3 = *n - i__; d_cnjg(&z__1, &tauq[i__]); zlarf_("Left", &i__2, &i__3, &a[i__ + i__ * a_dim1], &c__1, &z__1, &a[i__ + (i__ + 1) * a_dim1], lda, &work[1]); i__2 = i__ + i__ * a_dim1; i__3 = i__; a[i__2].r = d__[i__3], a[i__2].i = 0.; if (i__ < *n) { /* Generate elementary reflector G(i) to annihilate A(i,i+2:n) */ i__2 = *n - i__; zlacgv_(&i__2, &a[i__ + (i__ + 1) * a_dim1], lda); i__2 = i__ + (i__ + 1) * a_dim1; alpha.r = a[i__2].r, alpha.i = a[i__2].i; i__2 = *n - i__; /* Computing MIN */ i__3 = i__ + 2; zlarfg_(&i__2, &alpha, &a[i__ + min(i__3,*n) * a_dim1], lda, & taup[i__]); i__2 = i__; e[i__2] = alpha.r; i__2 = i__ + (i__ + 1) * a_dim1; a[i__2].r = 1., a[i__2].i = 0.; /* Apply G(i) to A(i+1:m,i+1:n) from the right */ i__2 = *m - i__; i__3 = *n - i__; zlarf_("Right", &i__2, &i__3, &a[i__ + (i__ + 1) * a_dim1], lda, &taup[i__], &a[i__ + 1 + (i__ + 1) * a_dim1], lda, &work[1]); i__2 = *n - i__; zlacgv_(&i__2, &a[i__ + (i__ + 1) * a_dim1], lda); i__2 = i__ + (i__ + 1) * a_dim1; i__3 = i__; a[i__2].r = e[i__3], a[i__2].i = 0.; } else { i__2 = i__; taup[i__2].r = 0., taup[i__2].i = 0.; } /* L10: */ } } else { /* Reduce to lower bidiagonal form */ i__1 = *m; for (i__ = 1; i__ <= i__1; ++i__) { /* Generate elementary reflector G(i) to annihilate A(i,i+1:n) */ i__2 = *n - i__ + 1; zlacgv_(&i__2, &a[i__ + i__ * a_dim1], lda); i__2 = i__ + i__ * a_dim1; alpha.r = a[i__2].r, alpha.i = a[i__2].i; i__2 = *n - i__ + 1; /* Computing MIN */ i__3 = i__ + 1; zlarfg_(&i__2, &alpha, &a[i__ + min(i__3,*n) * a_dim1], lda, & taup[i__]); i__2 = i__; d__[i__2] = alpha.r; i__2 = i__ + i__ * a_dim1; a[i__2].r = 1., a[i__2].i = 0.; /* Apply G(i) to A(i+1:m,i:n) from the right */ i__2 = *m - i__; i__3 = *n - i__ + 1; /* Computing MIN */ i__4 = i__ + 1; zlarf_("Right", &i__2, &i__3, &a[i__ + i__ * a_dim1], lda, &taup[ i__], &a[min(i__4,*m) + i__ * a_dim1], lda, &work[1]); i__2 = *n - i__ + 1; zlacgv_(&i__2, &a[i__ + i__ * a_dim1], lda); i__2 = i__ + i__ * a_dim1; i__3 = i__; a[i__2].r = d__[i__3], a[i__2].i = 0.; if (i__ < *m) { /* Generate elementary reflector H(i) to annihilate A(i+2:m,i) */ i__2 = i__ + 1 + i__ * a_dim1; alpha.r = a[i__2].r, alpha.i = a[i__2].i; i__2 = *m - i__; /* Computing MIN */ i__3 = i__ + 2; zlarfg_(&i__2, &alpha, &a[min(i__3,*m) + i__ * a_dim1], &c__1, &tauq[i__]); i__2 = i__; e[i__2] = alpha.r; i__2 = i__ + 1 + i__ * a_dim1; a[i__2].r = 1., a[i__2].i = 0.; /* Apply H(i)' to A(i+1:m,i+1:n) from the left */ i__2 = *m - i__; i__3 = *n - i__; d_cnjg(&z__1, &tauq[i__]); zlarf_("Left", &i__2, &i__3, &a[i__ + 1 + i__ * a_dim1], & c__1, &z__1, &a[i__ + 1 + (i__ + 1) * a_dim1], lda, & work[1]); i__2 = i__ + 1 + i__ * a_dim1; i__3 = i__; a[i__2].r = e[i__3], a[i__2].i = 0.; } else { i__2 = i__; tauq[i__2].r = 0., tauq[i__2].i = 0.; } /* L20: */ } } return 0; /* End of ZGEBD2 */ } /* zgebd2_ */ /* Subroutine */ int zgebrd_(integer *m, integer *n, doublecomplex *a, integer *lda, doublereal *d__, doublereal *e, doublecomplex *tauq, doublecomplex *taup, doublecomplex *work, integer *lwork, integer * info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3, i__4, i__5; doublereal d__1; doublecomplex z__1; /* Local variables */ static integer i__, j, nb, nx; static doublereal ws; static integer nbmin, iinfo, minmn; extern /* Subroutine */ int zgemm_(char *, char *, integer *, integer *, integer *, doublecomplex *, doublecomplex *, integer *, doublecomplex *, integer *, doublecomplex *, doublecomplex *, integer *), zgebd2_(integer *, integer *, doublecomplex *, integer *, doublereal *, doublereal *, doublecomplex *, doublecomplex *, doublecomplex *, integer *), xerbla_(char *, integer *), zlabrd_(integer *, integer *, integer *, doublecomplex *, integer *, doublereal *, doublereal *, doublecomplex *, doublecomplex *, doublecomplex *, integer *, doublecomplex *, integer *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); static integer ldwrkx, ldwrky, lwkopt; static logical lquery; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= ZGEBRD reduces a general complex M-by-N matrix A to upper or lower bidiagonal form B by a unitary transformation: Q**H * A * P = B. If m >= n, B is upper bidiagonal; if m < n, B is lower bidiagonal. Arguments ========= M (input) INTEGER The number of rows in the matrix A. M >= 0. N (input) INTEGER The number of columns in the matrix A. N >= 0. A (input/output) COMPLEX*16 array, dimension (LDA,N) On entry, the M-by-N general matrix to be reduced. On exit, if m >= n, the diagonal and the first superdiagonal are overwritten with the upper bidiagonal matrix B; the elements below the diagonal, with the array TAUQ, represent the unitary matrix Q as a product of elementary reflectors, and the elements above the first superdiagonal, with the array TAUP, represent the unitary matrix P as a product of elementary reflectors; if m < n, the diagonal and the first subdiagonal are overwritten with the lower bidiagonal matrix B; the elements below the first subdiagonal, with the array TAUQ, represent the unitary matrix Q as a product of elementary reflectors, and the elements above the diagonal, with the array TAUP, represent the unitary matrix P as a product of elementary reflectors. See Further Details. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,M). D (output) DOUBLE PRECISION array, dimension (min(M,N)) The diagonal elements of the bidiagonal matrix B: D(i) = A(i,i). E (output) DOUBLE PRECISION array, dimension (min(M,N)-1) The off-diagonal elements of the bidiagonal matrix B: if m >= n, E(i) = A(i,i+1) for i = 1,2,...,n-1; if m < n, E(i) = A(i+1,i) for i = 1,2,...,m-1. TAUQ (output) COMPLEX*16 array dimension (min(M,N)) The scalar factors of the elementary reflectors which represent the unitary matrix Q. See Further Details. TAUP (output) COMPLEX*16 array, dimension (min(M,N)) The scalar factors of the elementary reflectors which represent the unitary matrix P. See Further Details. WORK (workspace/output) COMPLEX*16 array, dimension (LWORK) On exit, if INFO = 0, WORK(1) returns the optimal LWORK. LWORK (input) INTEGER The length of the array WORK. LWORK >= max(1,M,N). For optimum performance LWORK >= (M+N)*NB, where NB is the optimal blocksize. If LWORK = -1, then a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued by XERBLA. INFO (output) INTEGER = 0: successful exit. < 0: if INFO = -i, the i-th argument had an illegal value. Further Details =============== The matrices Q and P are represented as products of elementary reflectors: If m >= n, Q = H(1) H(2) . . . H(n) and P = G(1) G(2) . . . G(n-1) Each H(i) and G(i) has the form: H(i) = I - tauq * v * v' and G(i) = I - taup * u * u' where tauq and taup are complex scalars, and v and u are complex vectors; v(1:i-1) = 0, v(i) = 1, and v(i+1:m) is stored on exit in A(i+1:m,i); u(1:i) = 0, u(i+1) = 1, and u(i+2:n) is stored on exit in A(i,i+2:n); tauq is stored in TAUQ(i) and taup in TAUP(i). If m < n, Q = H(1) H(2) . . . H(m-1) and P = G(1) G(2) . . . G(m) Each H(i) and G(i) has the form: H(i) = I - tauq * v * v' and G(i) = I - taup * u * u' where tauq and taup are complex scalars, and v and u are complex vectors; v(1:i) = 0, v(i+1) = 1, and v(i+2:m) is stored on exit in A(i+2:m,i); u(1:i-1) = 0, u(i) = 1, and u(i+1:n) is stored on exit in A(i,i+1:n); tauq is stored in TAUQ(i) and taup in TAUP(i). The contents of A on exit are illustrated by the following examples: m = 6 and n = 5 (m > n): m = 5 and n = 6 (m < n): ( d e u1 u1 u1 ) ( d u1 u1 u1 u1 u1 ) ( v1 d e u2 u2 ) ( e d u2 u2 u2 u2 ) ( v1 v2 d e u3 ) ( v1 e d u3 u3 u3 ) ( v1 v2 v3 d e ) ( v1 v2 e d u4 u4 ) ( v1 v2 v3 v4 d ) ( v1 v2 v3 e d u5 ) ( v1 v2 v3 v4 v5 ) where d and e denote diagonal and off-diagonal elements of B, vi denotes an element of the vector defining H(i), and ui an element of the vector defining G(i). ===================================================================== Test the input parameters */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --d__; --e; --tauq; --taup; --work; /* Function Body */ *info = 0; /* Computing MAX */ i__1 = 1, i__2 = ilaenv_(&c__1, "ZGEBRD", " ", m, n, &c_n1, &c_n1, ( ftnlen)6, (ftnlen)1); nb = max(i__1,i__2); lwkopt = (*m + *n) * nb; d__1 = (doublereal) lwkopt; work[1].r = d__1, work[1].i = 0.; lquery = *lwork == -1; if (*m < 0) { *info = -1; } else if (*n < 0) { *info = -2; } else if (*lda < max(1,*m)) { *info = -4; } else /* if(complicated condition) */ { /* Computing MAX */ i__1 = max(1,*m); if (*lwork < max(i__1,*n) && ! lquery) { *info = -10; } } if (*info < 0) { i__1 = -(*info); xerbla_("ZGEBRD", &i__1); return 0; } else if (lquery) { return 0; } /* Quick return if possible */ minmn = min(*m,*n); if (minmn == 0) { work[1].r = 1., work[1].i = 0.; return 0; } ws = (doublereal) max(*m,*n); ldwrkx = *m; ldwrky = *n; if (nb > 1 && nb < minmn) { /* Set the crossover point NX. Computing MAX */ i__1 = nb, i__2 = ilaenv_(&c__3, "ZGEBRD", " ", m, n, &c_n1, &c_n1, ( ftnlen)6, (ftnlen)1); nx = max(i__1,i__2); /* Determine when to switch from blocked to unblocked code. */ if (nx < minmn) { ws = (doublereal) ((*m + *n) * nb); if ((doublereal) (*lwork) < ws) { /* Not enough work space for the optimal NB, consider using a smaller block size. */ nbmin = ilaenv_(&c__2, "ZGEBRD", " ", m, n, &c_n1, &c_n1, ( ftnlen)6, (ftnlen)1); if (*lwork >= (*m + *n) * nbmin) { nb = *lwork / (*m + *n); } else { nb = 1; nx = minmn; } } } } else { nx = minmn; } i__1 = minmn - nx; i__2 = nb; for (i__ = 1; i__2 < 0 ? i__ >= i__1 : i__ <= i__1; i__ += i__2) { /* Reduce rows and columns i:i+ib-1 to bidiagonal form and return the matrices X and Y which are needed to update the unreduced part of the matrix */ i__3 = *m - i__ + 1; i__4 = *n - i__ + 1; zlabrd_(&i__3, &i__4, &nb, &a[i__ + i__ * a_dim1], lda, &d__[i__], &e[ i__], &tauq[i__], &taup[i__], &work[1], &ldwrkx, &work[ldwrkx * nb + 1], &ldwrky); /* Update the trailing submatrix A(i+ib:m,i+ib:n), using an update of the form A := A - V*Y' - X*U' */ i__3 = *m - i__ - nb + 1; i__4 = *n - i__ - nb + 1; z__1.r = -1., z__1.i = -0.; zgemm_("No transpose", "Conjugate transpose", &i__3, &i__4, &nb, & z__1, &a[i__ + nb + i__ * a_dim1], lda, &work[ldwrkx * nb + nb + 1], &ldwrky, &c_b60, &a[i__ + nb + (i__ + nb) * a_dim1], lda); i__3 = *m - i__ - nb + 1; i__4 = *n - i__ - nb + 1; z__1.r = -1., z__1.i = -0.; zgemm_("No transpose", "No transpose", &i__3, &i__4, &nb, &z__1, & work[nb + 1], &ldwrkx, &a[i__ + (i__ + nb) * a_dim1], lda, & c_b60, &a[i__ + nb + (i__ + nb) * a_dim1], lda); /* Copy diagonal and off-diagonal elements of B back into A */ if (*m >= *n) { i__3 = i__ + nb - 1; for (j = i__; j <= i__3; ++j) { i__4 = j + j * a_dim1; i__5 = j; a[i__4].r = d__[i__5], a[i__4].i = 0.; i__4 = j + (j + 1) * a_dim1; i__5 = j; a[i__4].r = e[i__5], a[i__4].i = 0.; /* L10: */ } } else { i__3 = i__ + nb - 1; for (j = i__; j <= i__3; ++j) { i__4 = j + j * a_dim1; i__5 = j; a[i__4].r = d__[i__5], a[i__4].i = 0.; i__4 = j + 1 + j * a_dim1; i__5 = j; a[i__4].r = e[i__5], a[i__4].i = 0.; /* L20: */ } } /* L30: */ } /* Use unblocked code to reduce the remainder of the matrix */ i__2 = *m - i__ + 1; i__1 = *n - i__ + 1; zgebd2_(&i__2, &i__1, &a[i__ + i__ * a_dim1], lda, &d__[i__], &e[i__], & tauq[i__], &taup[i__], &work[1], &iinfo); work[1].r = ws, work[1].i = 0.; return 0; /* End of ZGEBRD */ } /* zgebrd_ */ /* Subroutine */ int zgeev_(char *jobvl, char *jobvr, integer *n, doublecomplex *a, integer *lda, doublecomplex *w, doublecomplex *vl, integer *ldvl, doublecomplex *vr, integer *ldvr, doublecomplex *work, integer *lwork, doublereal *rwork, integer *info) { /* System generated locals */ integer a_dim1, a_offset, vl_dim1, vl_offset, vr_dim1, vr_offset, i__1, i__2, i__3, i__4; doublereal d__1, d__2; doublecomplex z__1, z__2; /* Builtin functions */ double sqrt(doublereal), d_imag(doublecomplex *); void d_cnjg(doublecomplex *, doublecomplex *); /* Local variables */ static integer i__, k, ihi; static doublereal scl; static integer ilo; static doublereal dum[1], eps; static doublecomplex tmp; static integer ibal; static char side[1]; static integer maxb; static doublereal anrm; static integer ierr, itau, iwrk, nout; extern logical lsame_(char *, char *); extern /* Subroutine */ int zscal_(integer *, doublecomplex *, doublecomplex *, integer *), dlabad_(doublereal *, doublereal *); extern doublereal dznrm2_(integer *, doublecomplex *, integer *); static logical scalea; static doublereal cscale; extern /* Subroutine */ int zgebak_(char *, char *, integer *, integer *, integer *, doublereal *, integer *, doublecomplex *, integer *, integer *), zgebal_(char *, integer *, doublecomplex *, integer *, integer *, integer *, doublereal *, integer *); extern integer idamax_(integer *, doublereal *, integer *); extern /* Subroutine */ int xerbla_(char *, integer *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); static logical select[1]; extern /* Subroutine */ int zdscal_(integer *, doublereal *, doublecomplex *, integer *); static doublereal bignum; extern doublereal zlange_(char *, integer *, integer *, doublecomplex *, integer *, doublereal *); extern /* Subroutine */ int zgehrd_(integer *, integer *, integer *, doublecomplex *, integer *, doublecomplex *, doublecomplex *, integer *, integer *), zlascl_(char *, integer *, integer *, doublereal *, doublereal *, integer *, integer *, doublecomplex *, integer *, integer *), zlacpy_(char *, integer *, integer *, doublecomplex *, integer *, doublecomplex *, integer *); static integer minwrk, maxwrk; static logical wantvl; static doublereal smlnum; static integer hswork, irwork; extern /* Subroutine */ int zhseqr_(char *, char *, integer *, integer *, integer *, doublecomplex *, integer *, doublecomplex *, doublecomplex *, integer *, doublecomplex *, integer *, integer *), ztrevc_(char *, char *, logical *, integer *, doublecomplex *, integer *, doublecomplex *, integer *, doublecomplex *, integer *, integer *, integer *, doublecomplex *, doublereal *, integer *); static logical lquery, wantvr; extern /* Subroutine */ int zunghr_(integer *, integer *, integer *, doublecomplex *, integer *, doublecomplex *, doublecomplex *, integer *, integer *); /* -- LAPACK driver routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= ZGEEV computes for an N-by-N complex nonsymmetric matrix A, the eigenvalues and, optionally, the left and/or right eigenvectors. The right eigenvector v(j) of A satisfies A * v(j) = lambda(j) * v(j) where lambda(j) is its eigenvalue. The left eigenvector u(j) of A satisfies u(j)**H * A = lambda(j) * u(j)**H where u(j)**H denotes the conjugate transpose of u(j). The computed eigenvectors are normalized to have Euclidean norm equal to 1 and largest component real. Arguments ========= JOBVL (input) CHARACTER*1 = 'N': left eigenvectors of A are not computed; = 'V': left eigenvectors of are computed. JOBVR (input) CHARACTER*1 = 'N': right eigenvectors of A are not computed; = 'V': right eigenvectors of A are computed. N (input) INTEGER The order of the matrix A. N >= 0. A (input/output) COMPLEX*16 array, dimension (LDA,N) On entry, the N-by-N matrix A. On exit, A has been overwritten. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,N). W (output) COMPLEX*16 array, dimension (N) W contains the computed eigenvalues. VL (output) COMPLEX*16 array, dimension (LDVL,N) If JOBVL = 'V', the left eigenvectors u(j) are stored one after another in the columns of VL, in the same order as their eigenvalues. If JOBVL = 'N', VL is not referenced. u(j) = VL(:,j), the j-th column of VL. LDVL (input) INTEGER The leading dimension of the array VL. LDVL >= 1; if JOBVL = 'V', LDVL >= N. VR (output) COMPLEX*16 array, dimension (LDVR,N) If JOBVR = 'V', the right eigenvectors v(j) are stored one after another in the columns of VR, in the same order as their eigenvalues. If JOBVR = 'N', VR is not referenced. v(j) = VR(:,j), the j-th column of VR. LDVR (input) INTEGER The leading dimension of the array VR. LDVR >= 1; if JOBVR = 'V', LDVR >= N. WORK (workspace/output) COMPLEX*16 array, dimension (LWORK) On exit, if INFO = 0, WORK(1) returns the optimal LWORK. LWORK (input) INTEGER The dimension of the array WORK. LWORK >= max(1,2*N). For good performance, LWORK must generally be larger. If LWORK = -1, then a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued by XERBLA. RWORK (workspace) DOUBLE PRECISION array, dimension (2*N) INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value. > 0: if INFO = i, the QR algorithm failed to compute all the eigenvalues, and no eigenvectors have been computed; elements and i+1:N of W contain eigenvalues which have converged. ===================================================================== Test the input arguments */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --w; vl_dim1 = *ldvl; vl_offset = 1 + vl_dim1; vl -= vl_offset; vr_dim1 = *ldvr; vr_offset = 1 + vr_dim1; vr -= vr_offset; --work; --rwork; /* Function Body */ *info = 0; lquery = *lwork == -1; wantvl = lsame_(jobvl, "V"); wantvr = lsame_(jobvr, "V"); if (! wantvl && ! lsame_(jobvl, "N")) { *info = -1; } else if (! wantvr && ! lsame_(jobvr, "N")) { *info = -2; } else if (*n < 0) { *info = -3; } else if (*lda < max(1,*n)) { *info = -5; } else if ((*ldvl < 1) || (wantvl && *ldvl < *n)) { *info = -8; } else if ((*ldvr < 1) || (wantvr && *ldvr < *n)) { *info = -10; } /* Compute workspace (Note: Comments in the code beginning "Workspace:" describe the minimal amount of workspace needed at that point in the code, as well as the preferred amount for good performance. CWorkspace refers to complex workspace, and RWorkspace to real workspace. NB refers to the optimal block size for the immediately following subroutine, as returned by ILAENV. HSWORK refers to the workspace preferred by ZHSEQR, as calculated below. HSWORK is computed assuming ILO=1 and IHI=N, the worst case.) */ minwrk = 1; if (*info == 0 && ((*lwork >= 1) || (lquery))) { maxwrk = *n + *n * ilaenv_(&c__1, "ZGEHRD", " ", n, &c__1, n, &c__0, ( ftnlen)6, (ftnlen)1); if (! wantvl && ! wantvr) { /* Computing MAX */ i__1 = 1, i__2 = (*n) << (1); minwrk = max(i__1,i__2); /* Computing MAX */ i__1 = ilaenv_(&c__8, "ZHSEQR", "EN", n, &c__1, n, &c_n1, (ftnlen) 6, (ftnlen)2); maxb = max(i__1,2); /* Computing MIN Computing MAX */ i__3 = 2, i__4 = ilaenv_(&c__4, "ZHSEQR", "EN", n, &c__1, n, & c_n1, (ftnlen)6, (ftnlen)2); i__1 = min(maxb,*n), i__2 = max(i__3,i__4); k = min(i__1,i__2); /* Computing MAX */ i__1 = k * (k + 2), i__2 = (*n) << (1); hswork = max(i__1,i__2); maxwrk = max(maxwrk,hswork); } else { /* Computing MAX */ i__1 = 1, i__2 = (*n) << (1); minwrk = max(i__1,i__2); /* Computing MAX */ i__1 = maxwrk, i__2 = *n + (*n - 1) * ilaenv_(&c__1, "ZUNGHR", " ", n, &c__1, n, &c_n1, (ftnlen)6, (ftnlen)1); maxwrk = max(i__1,i__2); /* Computing MAX */ i__1 = ilaenv_(&c__8, "ZHSEQR", "SV", n, &c__1, n, &c_n1, (ftnlen) 6, (ftnlen)2); maxb = max(i__1,2); /* Computing MIN Computing MAX */ i__3 = 2, i__4 = ilaenv_(&c__4, "ZHSEQR", "SV", n, &c__1, n, & c_n1, (ftnlen)6, (ftnlen)2); i__1 = min(maxb,*n), i__2 = max(i__3,i__4); k = min(i__1,i__2); /* Computing MAX */ i__1 = k * (k + 2), i__2 = (*n) << (1); hswork = max(i__1,i__2); /* Computing MAX */ i__1 = max(maxwrk,hswork), i__2 = (*n) << (1); maxwrk = max(i__1,i__2); } work[1].r = (doublereal) maxwrk, work[1].i = 0.; } if (*lwork < minwrk && ! lquery) { *info = -12; } if (*info != 0) { i__1 = -(*info); xerbla_("ZGEEV ", &i__1); return 0; } else if (lquery) { return 0; } /* Quick return if possible */ if (*n == 0) { return 0; } /* Get machine constants */ eps = PRECISION; smlnum = SAFEMINIMUM; bignum = 1. / smlnum; dlabad_(&smlnum, &bignum); smlnum = sqrt(smlnum) / eps; bignum = 1. / smlnum; /* Scale A if max element outside range [SMLNUM,BIGNUM] */ anrm = zlange_("M", n, n, &a[a_offset], lda, dum); scalea = FALSE_; if (anrm > 0. && anrm < smlnum) { scalea = TRUE_; cscale = smlnum; } else if (anrm > bignum) { scalea = TRUE_; cscale = bignum; } if (scalea) { zlascl_("G", &c__0, &c__0, &anrm, &cscale, n, n, &a[a_offset], lda, & ierr); } /* Balance the matrix (CWorkspace: none) (RWorkspace: need N) */ ibal = 1; zgebal_("B", n, &a[a_offset], lda, &ilo, &ihi, &rwork[ibal], &ierr); /* Reduce to upper Hessenberg form (CWorkspace: need 2*N, prefer N+N*NB) (RWorkspace: none) */ itau = 1; iwrk = itau + *n; i__1 = *lwork - iwrk + 1; zgehrd_(n, &ilo, &ihi, &a[a_offset], lda, &work[itau], &work[iwrk], &i__1, &ierr); if (wantvl) { /* Want left eigenvectors Copy Householder vectors to VL */ *(unsigned char *)side = 'L'; zlacpy_("L", n, n, &a[a_offset], lda, &vl[vl_offset], ldvl) ; /* Generate unitary matrix in VL (CWorkspace: need 2*N-1, prefer N+(N-1)*NB) (RWorkspace: none) */ i__1 = *lwork - iwrk + 1; zunghr_(n, &ilo, &ihi, &vl[vl_offset], ldvl, &work[itau], &work[iwrk], &i__1, &ierr); /* Perform QR iteration, accumulating Schur vectors in VL (CWorkspace: need 1, prefer HSWORK (see comments) ) (RWorkspace: none) */ iwrk = itau; i__1 = *lwork - iwrk + 1; zhseqr_("S", "V", n, &ilo, &ihi, &a[a_offset], lda, &w[1], &vl[ vl_offset], ldvl, &work[iwrk], &i__1, info); if (wantvr) { /* Want left and right eigenvectors Copy Schur vectors to VR */ *(unsigned char *)side = 'B'; zlacpy_("F", n, n, &vl[vl_offset], ldvl, &vr[vr_offset], ldvr); } } else if (wantvr) { /* Want right eigenvectors Copy Householder vectors to VR */ *(unsigned char *)side = 'R'; zlacpy_("L", n, n, &a[a_offset], lda, &vr[vr_offset], ldvr) ; /* Generate unitary matrix in VR (CWorkspace: need 2*N-1, prefer N+(N-1)*NB) (RWorkspace: none) */ i__1 = *lwork - iwrk + 1; zunghr_(n, &ilo, &ihi, &vr[vr_offset], ldvr, &work[itau], &work[iwrk], &i__1, &ierr); /* Perform QR iteration, accumulating Schur vectors in VR (CWorkspace: need 1, prefer HSWORK (see comments) ) (RWorkspace: none) */ iwrk = itau; i__1 = *lwork - iwrk + 1; zhseqr_("S", "V", n, &ilo, &ihi, &a[a_offset], lda, &w[1], &vr[ vr_offset], ldvr, &work[iwrk], &i__1, info); } else { /* Compute eigenvalues only (CWorkspace: need 1, prefer HSWORK (see comments) ) (RWorkspace: none) */ iwrk = itau; i__1 = *lwork - iwrk + 1; zhseqr_("E", "N", n, &ilo, &ihi, &a[a_offset], lda, &w[1], &vr[ vr_offset], ldvr, &work[iwrk], &i__1, info); } /* If INFO > 0 from ZHSEQR, then quit */ if (*info > 0) { goto L50; } if ((wantvl) || (wantvr)) { /* Compute left and/or right eigenvectors (CWorkspace: need 2*N) (RWorkspace: need 2*N) */ irwork = ibal + *n; ztrevc_(side, "B", select, n, &a[a_offset], lda, &vl[vl_offset], ldvl, &vr[vr_offset], ldvr, n, &nout, &work[iwrk], &rwork[irwork], &ierr); } if (wantvl) { /* Undo balancing of left eigenvectors (CWorkspace: none) (RWorkspace: need N) */ zgebak_("B", "L", n, &ilo, &ihi, &rwork[ibal], n, &vl[vl_offset], ldvl, &ierr); /* Normalize left eigenvectors and make largest component real */ i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { scl = 1. / dznrm2_(n, &vl[i__ * vl_dim1 + 1], &c__1); zdscal_(n, &scl, &vl[i__ * vl_dim1 + 1], &c__1); i__2 = *n; for (k = 1; k <= i__2; ++k) { i__3 = k + i__ * vl_dim1; /* Computing 2nd power */ d__1 = vl[i__3].r; /* Computing 2nd power */ d__2 = d_imag(&vl[k + i__ * vl_dim1]); rwork[irwork + k - 1] = d__1 * d__1 + d__2 * d__2; /* L10: */ } k = idamax_(n, &rwork[irwork], &c__1); d_cnjg(&z__2, &vl[k + i__ * vl_dim1]); d__1 = sqrt(rwork[irwork + k - 1]); z__1.r = z__2.r / d__1, z__1.i = z__2.i / d__1; tmp.r = z__1.r, tmp.i = z__1.i; zscal_(n, &tmp, &vl[i__ * vl_dim1 + 1], &c__1); i__2 = k + i__ * vl_dim1; i__3 = k + i__ * vl_dim1; d__1 = vl[i__3].r; z__1.r = d__1, z__1.i = 0.; vl[i__2].r = z__1.r, vl[i__2].i = z__1.i; /* L20: */ } } if (wantvr) { /* Undo balancing of right eigenvectors (CWorkspace: none) (RWorkspace: need N) */ zgebak_("B", "R", n, &ilo, &ihi, &rwork[ibal], n, &vr[vr_offset], ldvr, &ierr); /* Normalize right eigenvectors and make largest component real */ i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { scl = 1. / dznrm2_(n, &vr[i__ * vr_dim1 + 1], &c__1); zdscal_(n, &scl, &vr[i__ * vr_dim1 + 1], &c__1); i__2 = *n; for (k = 1; k <= i__2; ++k) { i__3 = k + i__ * vr_dim1; /* Computing 2nd power */ d__1 = vr[i__3].r; /* Computing 2nd power */ d__2 = d_imag(&vr[k + i__ * vr_dim1]); rwork[irwork + k - 1] = d__1 * d__1 + d__2 * d__2; /* L30: */ } k = idamax_(n, &rwork[irwork], &c__1); d_cnjg(&z__2, &vr[k + i__ * vr_dim1]); d__1 = sqrt(rwork[irwork + k - 1]); z__1.r = z__2.r / d__1, z__1.i = z__2.i / d__1; tmp.r = z__1.r, tmp.i = z__1.i; zscal_(n, &tmp, &vr[i__ * vr_dim1 + 1], &c__1); i__2 = k + i__ * vr_dim1; i__3 = k + i__ * vr_dim1; d__1 = vr[i__3].r; z__1.r = d__1, z__1.i = 0.; vr[i__2].r = z__1.r, vr[i__2].i = z__1.i; /* L40: */ } } /* Undo scaling if necessary */ L50: if (scalea) { i__1 = *n - *info; /* Computing MAX */ i__3 = *n - *info; i__2 = max(i__3,1); zlascl_("G", &c__0, &c__0, &cscale, &anrm, &i__1, &c__1, &w[*info + 1] , &i__2, &ierr); if (*info > 0) { i__1 = ilo - 1; zlascl_("G", &c__0, &c__0, &cscale, &anrm, &i__1, &c__1, &w[1], n, &ierr); } } work[1].r = (doublereal) maxwrk, work[1].i = 0.; return 0; /* End of ZGEEV */ } /* zgeev_ */ /* Subroutine */ int zgehd2_(integer *n, integer *ilo, integer *ihi, doublecomplex *a, integer *lda, doublecomplex *tau, doublecomplex * work, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3; doublecomplex z__1; /* Builtin functions */ void d_cnjg(doublecomplex *, doublecomplex *); /* Local variables */ static integer i__; static doublecomplex alpha; extern /* Subroutine */ int zlarf_(char *, integer *, integer *, doublecomplex *, integer *, doublecomplex *, doublecomplex *, integer *, doublecomplex *), xerbla_(char *, integer *), zlarfg_(integer *, doublecomplex *, doublecomplex *, integer *, doublecomplex *); /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University September 30, 1994 Purpose ======= ZGEHD2 reduces a complex general matrix A to upper Hessenberg form H by a unitary similarity transformation: Q' * A * Q = H . Arguments ========= N (input) INTEGER The order of the matrix A. N >= 0. ILO (input) INTEGER IHI (input) INTEGER It is assumed that A is already upper triangular in rows and columns 1:ILO-1 and IHI+1:N. ILO and IHI are normally set by a previous call to ZGEBAL; otherwise they should be set to 1 and N respectively. See Further Details. 1 <= ILO <= IHI <= max(1,N). A (input/output) COMPLEX*16 array, dimension (LDA,N) On entry, the n by n general matrix to be reduced. On exit, the upper triangle and the first subdiagonal of A are overwritten with the upper Hessenberg matrix H, and the elements below the first subdiagonal, with the array TAU, represent the unitary matrix Q as a product of elementary reflectors. See Further Details. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,N). TAU (output) COMPLEX*16 array, dimension (N-1) The scalar factors of the elementary reflectors (see Further Details). WORK (workspace) COMPLEX*16 array, dimension (N) INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value. Further Details =============== The matrix Q is represented as a product of (ihi-ilo) elementary reflectors Q = H(ilo) H(ilo+1) . . . H(ihi-1). Each H(i) has the form H(i) = I - tau * v * v' where tau is a complex scalar, and v is a complex vector with v(1:i) = 0, v(i+1) = 1 and v(ihi+1:n) = 0; v(i+2:ihi) is stored on exit in A(i+2:ihi,i), and tau in TAU(i). The contents of A are illustrated by the following example, with n = 7, ilo = 2 and ihi = 6: on entry, on exit, ( a a a a a a a ) ( a a h h h h a ) ( a a a a a a ) ( a h h h h a ) ( a a a a a a ) ( h h h h h h ) ( a a a a a a ) ( v2 h h h h h ) ( a a a a a a ) ( v2 v3 h h h h ) ( a a a a a a ) ( v2 v3 v4 h h h ) ( a ) ( a ) where a denotes an element of the original matrix A, h denotes a modified element of the upper Hessenberg matrix H, and vi denotes an element of the vector defining H(i). ===================================================================== Test the input parameters */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --tau; --work; /* Function Body */ *info = 0; if (*n < 0) { *info = -1; } else if ((*ilo < 1) || (*ilo > max(1,*n))) { *info = -2; } else if ((*ihi < min(*ilo,*n)) || (*ihi > *n)) { *info = -3; } else if (*lda < max(1,*n)) { *info = -5; } if (*info != 0) { i__1 = -(*info); xerbla_("ZGEHD2", &i__1); return 0; } i__1 = *ihi - 1; for (i__ = *ilo; i__ <= i__1; ++i__) { /* Compute elementary reflector H(i) to annihilate A(i+2:ihi,i) */ i__2 = i__ + 1 + i__ * a_dim1; alpha.r = a[i__2].r, alpha.i = a[i__2].i; i__2 = *ihi - i__; /* Computing MIN */ i__3 = i__ + 2; zlarfg_(&i__2, &alpha, &a[min(i__3,*n) + i__ * a_dim1], &c__1, &tau[ i__]); i__2 = i__ + 1 + i__ * a_dim1; a[i__2].r = 1., a[i__2].i = 0.; /* Apply H(i) to A(1:ihi,i+1:ihi) from the right */ i__2 = *ihi - i__; zlarf_("Right", ihi, &i__2, &a[i__ + 1 + i__ * a_dim1], &c__1, &tau[ i__], &a[(i__ + 1) * a_dim1 + 1], lda, &work[1]); /* Apply H(i)' to A(i+1:ihi,i+1:n) from the left */ i__2 = *ihi - i__; i__3 = *n - i__; d_cnjg(&z__1, &tau[i__]); zlarf_("Left", &i__2, &i__3, &a[i__ + 1 + i__ * a_dim1], &c__1, &z__1, &a[i__ + 1 + (i__ + 1) * a_dim1], lda, &work[1]); i__2 = i__ + 1 + i__ * a_dim1; a[i__2].r = alpha.r, a[i__2].i = alpha.i; /* L10: */ } return 0; /* End of ZGEHD2 */ } /* zgehd2_ */ /* Subroutine */ int zgehrd_(integer *n, integer *ilo, integer *ihi, doublecomplex *a, integer *lda, doublecomplex *tau, doublecomplex * work, integer *lwork, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3, i__4; doublecomplex z__1; /* Local variables */ static integer i__; static doublecomplex t[4160] /* was [65][64] */; static integer ib; static doublecomplex ei; static integer nb, nh, nx, iws, nbmin, iinfo; extern /* Subroutine */ int zgemm_(char *, char *, integer *, integer *, integer *, doublecomplex *, doublecomplex *, integer *, doublecomplex *, integer *, doublecomplex *, doublecomplex *, integer *), zgehd2_(integer *, integer *, integer *, doublecomplex *, integer *, doublecomplex *, doublecomplex *, integer *), xerbla_(char *, integer *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); extern /* Subroutine */ int zlarfb_(char *, char *, char *, char *, integer *, integer *, integer *, doublecomplex *, integer *, doublecomplex *, integer *, doublecomplex *, integer *, doublecomplex *, integer *), zlahrd_(integer *, integer *, integer *, doublecomplex *, integer *, doublecomplex *, doublecomplex *, integer *, doublecomplex *, integer *); static integer ldwork, lwkopt; static logical lquery; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= ZGEHRD reduces a complex general matrix A to upper Hessenberg form H by a unitary similarity transformation: Q' * A * Q = H . Arguments ========= N (input) INTEGER The order of the matrix A. N >= 0. ILO (input) INTEGER IHI (input) INTEGER It is assumed that A is already upper triangular in rows and columns 1:ILO-1 and IHI+1:N. ILO and IHI are normally set by a previous call to ZGEBAL; otherwise they should be set to 1 and N respectively. See Further Details. 1 <= ILO <= IHI <= N, if N > 0; ILO=1 and IHI=0, if N=0. A (input/output) COMPLEX*16 array, dimension (LDA,N) On entry, the N-by-N general matrix to be reduced. On exit, the upper triangle and the first subdiagonal of A are overwritten with the upper Hessenberg matrix H, and the elements below the first subdiagonal, with the array TAU, represent the unitary matrix Q as a product of elementary reflectors. See Further Details. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,N). TAU (output) COMPLEX*16 array, dimension (N-1) The scalar factors of the elementary reflectors (see Further Details). Elements 1:ILO-1 and IHI:N-1 of TAU are set to zero. WORK (workspace/output) COMPLEX*16 array, dimension (LWORK) On exit, if INFO = 0, WORK(1) returns the optimal LWORK. LWORK (input) INTEGER The length of the array WORK. LWORK >= max(1,N). For optimum performance LWORK >= N*NB, where NB is the optimal blocksize. If LWORK = -1, then a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued by XERBLA. INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value. Further Details =============== The matrix Q is represented as a product of (ihi-ilo) elementary reflectors Q = H(ilo) H(ilo+1) . . . H(ihi-1). Each H(i) has the form H(i) = I - tau * v * v' where tau is a complex scalar, and v is a complex vector with v(1:i) = 0, v(i+1) = 1 and v(ihi+1:n) = 0; v(i+2:ihi) is stored on exit in A(i+2:ihi,i), and tau in TAU(i). The contents of A are illustrated by the following example, with n = 7, ilo = 2 and ihi = 6: on entry, on exit, ( a a a a a a a ) ( a a h h h h a ) ( a a a a a a ) ( a h h h h a ) ( a a a a a a ) ( h h h h h h ) ( a a a a a a ) ( v2 h h h h h ) ( a a a a a a ) ( v2 v3 h h h h ) ( a a a a a a ) ( v2 v3 v4 h h h ) ( a ) ( a ) where a denotes an element of the original matrix A, h denotes a modified element of the upper Hessenberg matrix H, and vi denotes an element of the vector defining H(i). ===================================================================== Test the input parameters */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --tau; --work; /* Function Body */ *info = 0; /* Computing MIN */ i__1 = 64, i__2 = ilaenv_(&c__1, "ZGEHRD", " ", n, ilo, ihi, &c_n1, ( ftnlen)6, (ftnlen)1); nb = min(i__1,i__2); lwkopt = *n * nb; work[1].r = (doublereal) lwkopt, work[1].i = 0.; lquery = *lwork == -1; if (*n < 0) { *info = -1; } else if ((*ilo < 1) || (*ilo > max(1,*n))) { *info = -2; } else if ((*ihi < min(*ilo,*n)) || (*ihi > *n)) { *info = -3; } else if (*lda < max(1,*n)) { *info = -5; } else if (*lwork < max(1,*n) && ! lquery) { *info = -8; } if (*info != 0) { i__1 = -(*info); xerbla_("ZGEHRD", &i__1); return 0; } else if (lquery) { return 0; } /* Set elements 1:ILO-1 and IHI:N-1 of TAU to zero */ i__1 = *ilo - 1; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = i__; tau[i__2].r = 0., tau[i__2].i = 0.; /* L10: */ } i__1 = *n - 1; for (i__ = max(1,*ihi); i__ <= i__1; ++i__) { i__2 = i__; tau[i__2].r = 0., tau[i__2].i = 0.; /* L20: */ } /* Quick return if possible */ nh = *ihi - *ilo + 1; if (nh <= 1) { work[1].r = 1., work[1].i = 0.; return 0; } nbmin = 2; iws = 1; if (nb > 1 && nb < nh) { /* Determine when to cross over from blocked to unblocked code (last block is always handled by unblocked code). Computing MAX */ i__1 = nb, i__2 = ilaenv_(&c__3, "ZGEHRD", " ", n, ilo, ihi, &c_n1, ( ftnlen)6, (ftnlen)1); nx = max(i__1,i__2); if (nx < nh) { /* Determine if workspace is large enough for blocked code. */ iws = *n * nb; if (*lwork < iws) { /* Not enough workspace to use optimal NB: determine the minimum value of NB, and reduce NB or force use of unblocked code. Computing MAX */ i__1 = 2, i__2 = ilaenv_(&c__2, "ZGEHRD", " ", n, ilo, ihi, & c_n1, (ftnlen)6, (ftnlen)1); nbmin = max(i__1,i__2); if (*lwork >= *n * nbmin) { nb = *lwork / *n; } else { nb = 1; } } } } ldwork = *n; if ((nb < nbmin) || (nb >= nh)) { /* Use unblocked code below */ i__ = *ilo; } else { /* Use blocked code */ i__1 = *ihi - 1 - nx; i__2 = nb; for (i__ = *ilo; i__2 < 0 ? i__ >= i__1 : i__ <= i__1; i__ += i__2) { /* Computing MIN */ i__3 = nb, i__4 = *ihi - i__; ib = min(i__3,i__4); /* Reduce columns i:i+ib-1 to Hessenberg form, returning the matrices V and T of the block reflector H = I - V*T*V' which performs the reduction, and also the matrix Y = A*V*T */ zlahrd_(ihi, &i__, &ib, &a[i__ * a_dim1 + 1], lda, &tau[i__], t, & c__65, &work[1], &ldwork); /* Apply the block reflector H to A(1:ihi,i+ib:ihi) from the right, computing A := A - Y * V'. V(i+ib,ib-1) must be set to 1. */ i__3 = i__ + ib + (i__ + ib - 1) * a_dim1; ei.r = a[i__3].r, ei.i = a[i__3].i; i__3 = i__ + ib + (i__ + ib - 1) * a_dim1; a[i__3].r = 1., a[i__3].i = 0.; i__3 = *ihi - i__ - ib + 1; z__1.r = -1., z__1.i = -0.; zgemm_("No transpose", "Conjugate transpose", ihi, &i__3, &ib, & z__1, &work[1], &ldwork, &a[i__ + ib + i__ * a_dim1], lda, &c_b60, &a[(i__ + ib) * a_dim1 + 1], lda); i__3 = i__ + ib + (i__ + ib - 1) * a_dim1; a[i__3].r = ei.r, a[i__3].i = ei.i; /* Apply the block reflector H to A(i+1:ihi,i+ib:n) from the left */ i__3 = *ihi - i__; i__4 = *n - i__ - ib + 1; zlarfb_("Left", "Conjugate transpose", "Forward", "Columnwise", & i__3, &i__4, &ib, &a[i__ + 1 + i__ * a_dim1], lda, t, & c__65, &a[i__ + 1 + (i__ + ib) * a_dim1], lda, &work[1], & ldwork); /* L30: */ } } /* Use unblocked code to reduce the rest of the matrix */ zgehd2_(n, &i__, ihi, &a[a_offset], lda, &tau[1], &work[1], &iinfo); work[1].r = (doublereal) iws, work[1].i = 0.; return 0; /* End of ZGEHRD */ } /* zgehrd_ */ /* Subroutine */ int zgelq2_(integer *m, integer *n, doublecomplex *a, integer *lda, doublecomplex *tau, doublecomplex *work, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3; /* Local variables */ static integer i__, k; static doublecomplex alpha; extern /* Subroutine */ int zlarf_(char *, integer *, integer *, doublecomplex *, integer *, doublecomplex *, doublecomplex *, integer *, doublecomplex *), xerbla_(char *, integer *), zlarfg_(integer *, doublecomplex *, doublecomplex *, integer *, doublecomplex *), zlacgv_(integer *, doublecomplex *, integer *); /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University September 30, 1994 Purpose ======= ZGELQ2 computes an LQ factorization of a complex m by n matrix A: A = L * Q. Arguments ========= M (input) INTEGER The number of rows of the matrix A. M >= 0. N (input) INTEGER The number of columns of the matrix A. N >= 0. A (input/output) COMPLEX*16 array, dimension (LDA,N) On entry, the m by n matrix A. On exit, the elements on and below the diagonal of the array contain the m by min(m,n) lower trapezoidal matrix L (L is lower triangular if m <= n); the elements above the diagonal, with the array TAU, represent the unitary matrix Q as a product of elementary reflectors (see Further Details). LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,M). TAU (output) COMPLEX*16 array, dimension (min(M,N)) The scalar factors of the elementary reflectors (see Further Details). WORK (workspace) COMPLEX*16 array, dimension (M) INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value Further Details =============== The matrix Q is represented as a product of elementary reflectors Q = H(k)' . . . H(2)' H(1)', where k = min(m,n). Each H(i) has the form H(i) = I - tau * v * v' where tau is a complex scalar, and v is a complex vector with v(1:i-1) = 0 and v(i) = 1; conjg(v(i+1:n)) is stored on exit in A(i,i+1:n), and tau in TAU(i). ===================================================================== Test the input arguments */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --tau; --work; /* Function Body */ *info = 0; if (*m < 0) { *info = -1; } else if (*n < 0) { *info = -2; } else if (*lda < max(1,*m)) { *info = -4; } if (*info != 0) { i__1 = -(*info); xerbla_("ZGELQ2", &i__1); return 0; } k = min(*m,*n); i__1 = k; for (i__ = 1; i__ <= i__1; ++i__) { /* Generate elementary reflector H(i) to annihilate A(i,i+1:n) */ i__2 = *n - i__ + 1; zlacgv_(&i__2, &a[i__ + i__ * a_dim1], lda); i__2 = i__ + i__ * a_dim1; alpha.r = a[i__2].r, alpha.i = a[i__2].i; i__2 = *n - i__ + 1; /* Computing MIN */ i__3 = i__ + 1; zlarfg_(&i__2, &alpha, &a[i__ + min(i__3,*n) * a_dim1], lda, &tau[i__] ); if (i__ < *m) { /* Apply H(i) to A(i+1:m,i:n) from the right */ i__2 = i__ + i__ * a_dim1; a[i__2].r = 1., a[i__2].i = 0.; i__2 = *m - i__; i__3 = *n - i__ + 1; zlarf_("Right", &i__2, &i__3, &a[i__ + i__ * a_dim1], lda, &tau[ i__], &a[i__ + 1 + i__ * a_dim1], lda, &work[1]); } i__2 = i__ + i__ * a_dim1; a[i__2].r = alpha.r, a[i__2].i = alpha.i; i__2 = *n - i__ + 1; zlacgv_(&i__2, &a[i__ + i__ * a_dim1], lda); /* L10: */ } return 0; /* End of ZGELQ2 */ } /* zgelq2_ */ /* Subroutine */ int zgelqf_(integer *m, integer *n, doublecomplex *a, integer *lda, doublecomplex *tau, doublecomplex *work, integer *lwork, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3, i__4; /* Local variables */ static integer i__, k, ib, nb, nx, iws, nbmin, iinfo; extern /* Subroutine */ int zgelq2_(integer *, integer *, doublecomplex *, integer *, doublecomplex *, doublecomplex *, integer *), xerbla_( char *, integer *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); extern /* Subroutine */ int zlarfb_(char *, char *, char *, char *, integer *, integer *, integer *, doublecomplex *, integer *, doublecomplex *, integer *, doublecomplex *, integer *, doublecomplex *, integer *); static integer ldwork; extern /* Subroutine */ int zlarft_(char *, char *, integer *, integer *, doublecomplex *, integer *, doublecomplex *, doublecomplex *, integer *); static integer lwkopt; static logical lquery; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= ZGELQF computes an LQ factorization of a complex M-by-N matrix A: A = L * Q. Arguments ========= M (input) INTEGER The number of rows of the matrix A. M >= 0. N (input) INTEGER The number of columns of the matrix A. N >= 0. A (input/output) COMPLEX*16 array, dimension (LDA,N) On entry, the M-by-N matrix A. On exit, the elements on and below the diagonal of the array contain the m-by-min(m,n) lower trapezoidal matrix L (L is lower triangular if m <= n); the elements above the diagonal, with the array TAU, represent the unitary matrix Q as a product of elementary reflectors (see Further Details). LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,M). TAU (output) COMPLEX*16 array, dimension (min(M,N)) The scalar factors of the elementary reflectors (see Further Details). WORK (workspace/output) COMPLEX*16 array, dimension (LWORK) On exit, if INFO = 0, WORK(1) returns the optimal LWORK. LWORK (input) INTEGER The dimension of the array WORK. LWORK >= max(1,M). For optimum performance LWORK >= M*NB, where NB is the optimal blocksize. If LWORK = -1, then a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued by XERBLA. INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value Further Details =============== The matrix Q is represented as a product of elementary reflectors Q = H(k)' . . . H(2)' H(1)', where k = min(m,n). Each H(i) has the form H(i) = I - tau * v * v' where tau is a complex scalar, and v is a complex vector with v(1:i-1) = 0 and v(i) = 1; conjg(v(i+1:n)) is stored on exit in A(i,i+1:n), and tau in TAU(i). ===================================================================== Test the input arguments */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --tau; --work; /* Function Body */ *info = 0; nb = ilaenv_(&c__1, "ZGELQF", " ", m, n, &c_n1, &c_n1, (ftnlen)6, (ftnlen) 1); lwkopt = *m * nb; work[1].r = (doublereal) lwkopt, work[1].i = 0.; lquery = *lwork == -1; if (*m < 0) { *info = -1; } else if (*n < 0) { *info = -2; } else if (*lda < max(1,*m)) { *info = -4; } else if (*lwork < max(1,*m) && ! lquery) { *info = -7; } if (*info != 0) { i__1 = -(*info); xerbla_("ZGELQF", &i__1); return 0; } else if (lquery) { return 0; } /* Quick return if possible */ k = min(*m,*n); if (k == 0) { work[1].r = 1., work[1].i = 0.; return 0; } nbmin = 2; nx = 0; iws = *m; if (nb > 1 && nb < k) { /* Determine when to cross over from blocked to unblocked code. Computing MAX */ i__1 = 0, i__2 = ilaenv_(&c__3, "ZGELQF", " ", m, n, &c_n1, &c_n1, ( ftnlen)6, (ftnlen)1); nx = max(i__1,i__2); if (nx < k) { /* Determine if workspace is large enough for blocked code. */ ldwork = *m; iws = ldwork * nb; if (*lwork < iws) { /* Not enough workspace to use optimal NB: reduce NB and determine the minimum value of NB. */ nb = *lwork / ldwork; /* Computing MAX */ i__1 = 2, i__2 = ilaenv_(&c__2, "ZGELQF", " ", m, n, &c_n1, & c_n1, (ftnlen)6, (ftnlen)1); nbmin = max(i__1,i__2); } } } if (nb >= nbmin && nb < k && nx < k) { /* Use blocked code initially */ i__1 = k - nx; i__2 = nb; for (i__ = 1; i__2 < 0 ? i__ >= i__1 : i__ <= i__1; i__ += i__2) { /* Computing MIN */ i__3 = k - i__ + 1; ib = min(i__3,nb); /* Compute the LQ factorization of the current block A(i:i+ib-1,i:n) */ i__3 = *n - i__ + 1; zgelq2_(&ib, &i__3, &a[i__ + i__ * a_dim1], lda, &tau[i__], &work[ 1], &iinfo); if (i__ + ib <= *m) { /* Form the triangular factor of the block reflector H = H(i) H(i+1) . . . H(i+ib-1) */ i__3 = *n - i__ + 1; zlarft_("Forward", "Rowwise", &i__3, &ib, &a[i__ + i__ * a_dim1], lda, &tau[i__], &work[1], &ldwork); /* Apply H to A(i+ib:m,i:n) from the right */ i__3 = *m - i__ - ib + 1; i__4 = *n - i__ + 1; zlarfb_("Right", "No transpose", "Forward", "Rowwise", &i__3, &i__4, &ib, &a[i__ + i__ * a_dim1], lda, &work[1], & ldwork, &a[i__ + ib + i__ * a_dim1], lda, &work[ib + 1], &ldwork); } /* L10: */ } } else { i__ = 1; } /* Use unblocked code to factor the last or only block. */ if (i__ <= k) { i__2 = *m - i__ + 1; i__1 = *n - i__ + 1; zgelq2_(&i__2, &i__1, &a[i__ + i__ * a_dim1], lda, &tau[i__], &work[1] , &iinfo); } work[1].r = (doublereal) iws, work[1].i = 0.; return 0; /* End of ZGELQF */ } /* zgelqf_ */ /* Subroutine */ int zgelsd_(integer *m, integer *n, integer *nrhs, doublecomplex *a, integer *lda, doublecomplex *b, integer *ldb, doublereal *s, doublereal *rcond, integer *rank, doublecomplex *work, integer *lwork, doublereal *rwork, integer *iwork, integer *info) { /* System generated locals */ integer a_dim1, a_offset, b_dim1, b_offset, i__1, i__2, i__3, i__4; doublereal d__1; doublecomplex z__1; /* Local variables */ static integer ie, il, mm; static doublereal eps, anrm, bnrm; static integer itau, iascl, ibscl; static doublereal sfmin; static integer minmn, maxmn, itaup, itauq, mnthr, nwork; extern /* Subroutine */ int dlabad_(doublereal *, doublereal *); extern /* Subroutine */ int dlascl_(char *, integer *, integer *, doublereal *, doublereal *, integer *, integer *, doublereal *, integer *, integer *), dlaset_(char *, integer *, integer *, doublereal *, doublereal *, doublereal *, integer *), xerbla_(char *, integer *), zgebrd_(integer *, integer *, doublecomplex *, integer *, doublereal *, doublereal *, doublecomplex *, doublecomplex *, doublecomplex *, integer *, integer *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); extern doublereal zlange_(char *, integer *, integer *, doublecomplex *, integer *, doublereal *); static doublereal bignum; extern /* Subroutine */ int zgelqf_(integer *, integer *, doublecomplex *, integer *, doublecomplex *, doublecomplex *, integer *, integer * ), zlalsd_(char *, integer *, integer *, integer *, doublereal *, doublereal *, doublecomplex *, integer *, doublereal *, integer *, doublecomplex *, doublereal *, integer *, integer *), zlascl_(char *, integer *, integer *, doublereal *, doublereal *, integer *, integer *, doublecomplex *, integer *, integer *), zgeqrf_(integer *, integer *, doublecomplex *, integer *, doublecomplex *, doublecomplex *, integer *, integer *); static integer ldwork; extern /* Subroutine */ int zlacpy_(char *, integer *, integer *, doublecomplex *, integer *, doublecomplex *, integer *), zlaset_(char *, integer *, integer *, doublecomplex *, doublecomplex *, doublecomplex *, integer *); static integer minwrk, maxwrk; static doublereal smlnum; extern /* Subroutine */ int zunmbr_(char *, char *, char *, integer *, integer *, integer *, doublecomplex *, integer *, doublecomplex *, doublecomplex *, integer *, doublecomplex *, integer *, integer * ); static logical lquery; static integer nrwork, smlsiz; extern /* Subroutine */ int zunmlq_(char *, char *, integer *, integer *, integer *, doublecomplex *, integer *, doublecomplex *, doublecomplex *, integer *, doublecomplex *, integer *, integer *), zunmqr_(char *, char *, integer *, integer *, integer *, doublecomplex *, integer *, doublecomplex *, doublecomplex *, integer *, doublecomplex *, integer *, integer *); /* -- LAPACK driver routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University October 31, 1999 Purpose ======= ZGELSD computes the minimum-norm solution to a real linear least squares problem: minimize 2-norm(| b - A*x |) using the singular value decomposition (SVD) of A. A is an M-by-N matrix which may be rank-deficient. Several right hand side vectors b and solution vectors x can be handled in a single call; they are stored as the columns of the M-by-NRHS right hand side matrix B and the N-by-NRHS solution matrix X. The problem is solved in three steps: (1) Reduce the coefficient matrix A to bidiagonal form with Householder tranformations, reducing the original problem into a "bidiagonal least squares problem" (BLS) (2) Solve the BLS using a divide and conquer approach. (3) Apply back all the Householder tranformations to solve the original least squares problem. The effective rank of A is determined by treating as zero those singular values which are less than RCOND times the largest singular value. The divide and conquer algorithm makes very mild assumptions about floating point arithmetic. It will work on machines with a guard digit in add/subtract, or on those binary machines without guard digits which subtract like the Cray X-MP, Cray Y-MP, Cray C-90, or Cray-2. It could conceivably fail on hexadecimal or decimal machines without guard digits, but we know of none. Arguments ========= M (input) INTEGER The number of rows of the matrix A. M >= 0. N (input) INTEGER The number of columns of the matrix A. N >= 0. NRHS (input) INTEGER The number of right hand sides, i.e., the number of columns of the matrices B and X. NRHS >= 0. A (input) COMPLEX*16 array, dimension (LDA,N) On entry, the M-by-N matrix A. On exit, A has been destroyed. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,M). B (input/output) COMPLEX*16 array, dimension (LDB,NRHS) On entry, the M-by-NRHS right hand side matrix B. On exit, B is overwritten by the N-by-NRHS solution matrix X. If m >= n and RANK = n, the residual sum-of-squares for the solution in the i-th column is given by the sum of squares of elements n+1:m in that column. LDB (input) INTEGER The leading dimension of the array B. LDB >= max(1,M,N). S (output) DOUBLE PRECISION array, dimension (min(M,N)) The singular values of A in decreasing order. The condition number of A in the 2-norm = S(1)/S(min(m,n)). RCOND (input) DOUBLE PRECISION RCOND is used to determine the effective rank of A. Singular values S(i) <= RCOND*S(1) are treated as zero. If RCOND < 0, machine precision is used instead. RANK (output) INTEGER The effective rank of A, i.e., the number of singular values which are greater than RCOND*S(1). WORK (workspace/output) COMPLEX*16 array, dimension (LWORK) On exit, if INFO = 0, WORK(1) returns the optimal LWORK. LWORK (input) INTEGER The dimension of the array WORK. LWORK must be at least 1. The exact minimum amount of workspace needed depends on M, N and NRHS. As long as LWORK is at least 2 * N + N * NRHS if M is greater than or equal to N or 2 * M + M * NRHS if M is less than N, the code will execute correctly. For good performance, LWORK should generally be larger. If LWORK = -1, then a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued by XERBLA. RWORK (workspace) DOUBLE PRECISION array, dimension at least 10*N + 2*N*SMLSIZ + 8*N*NLVL + 3*SMLSIZ*NRHS + (SMLSIZ+1)**2 if M is greater than or equal to N or 10*M + 2*M*SMLSIZ + 8*M*NLVL + 3*SMLSIZ*NRHS + (SMLSIZ+1)**2 if M is less than N, the code will execute correctly. SMLSIZ is returned by ILAENV and is equal to the maximum size of the subproblems at the bottom of the computation tree (usually about 25), and NLVL = MAX( 0, INT( LOG_2( MIN( M,N )/(SMLSIZ+1) ) ) + 1 ) IWORK (workspace) INTEGER array, dimension (LIWORK) LIWORK >= 3 * MINMN * NLVL + 11 * MINMN, where MINMN = MIN( M,N ). INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value. > 0: the algorithm for computing the SVD failed to converge; if INFO = i, i off-diagonal elements of an intermediate bidiagonal form did not converge to zero. Further Details =============== Based on contributions by Ming Gu and Ren-Cang Li, Computer Science Division, University of California at Berkeley, USA Osni Marques, LBNL/NERSC, USA ===================================================================== Test the input arguments. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; b_dim1 = *ldb; b_offset = 1 + b_dim1; b -= b_offset; --s; --work; --rwork; --iwork; /* Function Body */ *info = 0; minmn = min(*m,*n); maxmn = max(*m,*n); mnthr = ilaenv_(&c__6, "ZGELSD", " ", m, n, nrhs, &c_n1, (ftnlen)6, ( ftnlen)1); lquery = *lwork == -1; if (*m < 0) { *info = -1; } else if (*n < 0) { *info = -2; } else if (*nrhs < 0) { *info = -3; } else if (*lda < max(1,*m)) { *info = -5; } else if (*ldb < max(1,maxmn)) { *info = -7; } smlsiz = ilaenv_(&c__9, "ZGELSD", " ", &c__0, &c__0, &c__0, &c__0, ( ftnlen)6, (ftnlen)1); /* Compute workspace. (Note: Comments in the code beginning "Workspace:" describe the minimal amount of workspace needed at that point in the code, as well as the preferred amount for good performance. NB refers to the optimal block size for the immediately following subroutine, as returned by ILAENV.) */ minwrk = 1; if (*info == 0) { maxwrk = 0; mm = *m; if (*m >= *n && *m >= mnthr) { /* Path 1a - overdetermined, with many more rows than columns. */ mm = *n; /* Computing MAX */ i__1 = maxwrk, i__2 = *n * ilaenv_(&c__1, "ZGEQRF", " ", m, n, & c_n1, &c_n1, (ftnlen)6, (ftnlen)1); maxwrk = max(i__1,i__2); /* Computing MAX */ i__1 = maxwrk, i__2 = *nrhs * ilaenv_(&c__1, "ZUNMQR", "LC", m, nrhs, n, &c_n1, (ftnlen)6, (ftnlen)2); maxwrk = max(i__1,i__2); } if (*m >= *n) { /* Path 1 - overdetermined or exactly determined. Computing MAX */ i__1 = maxwrk, i__2 = ((*n) << (1)) + (mm + *n) * ilaenv_(&c__1, "ZGEBRD", " ", &mm, n, &c_n1, &c_n1, (ftnlen)6, (ftnlen)1) ; maxwrk = max(i__1,i__2); /* Computing MAX */ i__1 = maxwrk, i__2 = ((*n) << (1)) + *nrhs * ilaenv_(&c__1, "ZUNMBR", "QLC", &mm, nrhs, n, &c_n1, (ftnlen)6, (ftnlen) 3); maxwrk = max(i__1,i__2); /* Computing MAX */ i__1 = maxwrk, i__2 = ((*n) << (1)) + (*n - 1) * ilaenv_(&c__1, "ZUNMBR", "PLN", n, nrhs, n, &c_n1, (ftnlen)6, (ftnlen)3); maxwrk = max(i__1,i__2); /* Computing MAX */ i__1 = maxwrk, i__2 = ((*n) << (1)) + *n * *nrhs; maxwrk = max(i__1,i__2); /* Computing MAX */ i__1 = ((*n) << (1)) + mm, i__2 = ((*n) << (1)) + *n * *nrhs; minwrk = max(i__1,i__2); } if (*n > *m) { if (*n >= mnthr) { /* Path 2a - underdetermined, with many more columns than rows. */ maxwrk = *m + *m * ilaenv_(&c__1, "ZGELQF", " ", m, n, &c_n1, &c_n1, (ftnlen)6, (ftnlen)1); /* Computing MAX */ i__1 = maxwrk, i__2 = *m * *m + ((*m) << (2)) + ((*m) << (1)) * ilaenv_(&c__1, "ZGEBRD", " ", m, m, &c_n1, &c_n1, ( ftnlen)6, (ftnlen)1); maxwrk = max(i__1,i__2); /* Computing MAX */ i__1 = maxwrk, i__2 = *m * *m + ((*m) << (2)) + *nrhs * ilaenv_(&c__1, "ZUNMBR", "QLC", m, nrhs, m, &c_n1, ( ftnlen)6, (ftnlen)3); maxwrk = max(i__1,i__2); /* Computing MAX */ i__1 = maxwrk, i__2 = *m * *m + ((*m) << (2)) + (*m - 1) * ilaenv_(&c__1, "ZUNMLQ", "LC", n, nrhs, m, &c_n1, ( ftnlen)6, (ftnlen)2); maxwrk = max(i__1,i__2); if (*nrhs > 1) { /* Computing MAX */ i__1 = maxwrk, i__2 = *m * *m + *m + *m * *nrhs; maxwrk = max(i__1,i__2); } else { /* Computing MAX */ i__1 = maxwrk, i__2 = *m * *m + ((*m) << (1)); maxwrk = max(i__1,i__2); } /* Computing MAX */ i__1 = maxwrk, i__2 = *m * *m + ((*m) << (2)) + *m * *nrhs; maxwrk = max(i__1,i__2); } else { /* Path 2 - underdetermined. */ maxwrk = ((*m) << (1)) + (*n + *m) * ilaenv_(&c__1, "ZGEBRD", " ", m, n, &c_n1, &c_n1, (ftnlen)6, (ftnlen)1); /* Computing MAX */ i__1 = maxwrk, i__2 = ((*m) << (1)) + *nrhs * ilaenv_(&c__1, "ZUNMBR", "QLC", m, nrhs, m, &c_n1, (ftnlen)6, ( ftnlen)3); maxwrk = max(i__1,i__2); /* Computing MAX */ i__1 = maxwrk, i__2 = ((*m) << (1)) + *m * ilaenv_(&c__1, "ZUNMBR", "PLN", n, nrhs, m, &c_n1, (ftnlen)6, ( ftnlen)3); maxwrk = max(i__1,i__2); /* Computing MAX */ i__1 = maxwrk, i__2 = ((*m) << (1)) + *m * *nrhs; maxwrk = max(i__1,i__2); } /* Computing MAX */ i__1 = ((*m) << (1)) + *n, i__2 = ((*m) << (1)) + *m * *nrhs; minwrk = max(i__1,i__2); } minwrk = min(minwrk,maxwrk); d__1 = (doublereal) maxwrk; z__1.r = d__1, z__1.i = 0.; work[1].r = z__1.r, work[1].i = z__1.i; if (*lwork < minwrk && ! lquery) { *info = -12; } } if (*info != 0) { i__1 = -(*info); xerbla_("ZGELSD", &i__1); return 0; } else if (lquery) { goto L10; } /* Quick return if possible. */ if ((*m == 0) || (*n == 0)) { *rank = 0; return 0; } /* Get machine parameters. */ eps = PRECISION; sfmin = SAFEMINIMUM; smlnum = sfmin / eps; bignum = 1. / smlnum; dlabad_(&smlnum, &bignum); /* Scale A if max entry outside range [SMLNUM,BIGNUM]. */ anrm = zlange_("M", m, n, &a[a_offset], lda, &rwork[1]); iascl = 0; if (anrm > 0. && anrm < smlnum) { /* Scale matrix norm up to SMLNUM */ zlascl_("G", &c__0, &c__0, &anrm, &smlnum, m, n, &a[a_offset], lda, info); iascl = 1; } else if (anrm > bignum) { /* Scale matrix norm down to BIGNUM. */ zlascl_("G", &c__0, &c__0, &anrm, &bignum, m, n, &a[a_offset], lda, info); iascl = 2; } else if (anrm == 0.) { /* Matrix all zero. Return zero solution. */ i__1 = max(*m,*n); zlaset_("F", &i__1, nrhs, &c_b59, &c_b59, &b[b_offset], ldb); dlaset_("F", &minmn, &c__1, &c_b324, &c_b324, &s[1], &c__1) ; *rank = 0; goto L10; } /* Scale B if max entry outside range [SMLNUM,BIGNUM]. */ bnrm = zlange_("M", m, nrhs, &b[b_offset], ldb, &rwork[1]); ibscl = 0; if (bnrm > 0. && bnrm < smlnum) { /* Scale matrix norm up to SMLNUM. */ zlascl_("G", &c__0, &c__0, &bnrm, &smlnum, m, nrhs, &b[b_offset], ldb, info); ibscl = 1; } else if (bnrm > bignum) { /* Scale matrix norm down to BIGNUM. */ zlascl_("G", &c__0, &c__0, &bnrm, &bignum, m, nrhs, &b[b_offset], ldb, info); ibscl = 2; } /* If M < N make sure B(M+1:N,:) = 0 */ if (*m < *n) { i__1 = *n - *m; zlaset_("F", &i__1, nrhs, &c_b59, &c_b59, &b[*m + 1 + b_dim1], ldb); } /* Overdetermined case. */ if (*m >= *n) { /* Path 1 - overdetermined or exactly determined. */ mm = *m; if (*m >= mnthr) { /* Path 1a - overdetermined, with many more rows than columns */ mm = *n; itau = 1; nwork = itau + *n; /* Compute A=Q*R. (RWorkspace: need N) (CWorkspace: need N, prefer N*NB) */ i__1 = *lwork - nwork + 1; zgeqrf_(m, n, &a[a_offset], lda, &work[itau], &work[nwork], &i__1, info); /* Multiply B by transpose(Q). (RWorkspace: need N) (CWorkspace: need NRHS, prefer NRHS*NB) */ i__1 = *lwork - nwork + 1; zunmqr_("L", "C", m, nrhs, n, &a[a_offset], lda, &work[itau], &b[ b_offset], ldb, &work[nwork], &i__1, info); /* Zero out below R. */ if (*n > 1) { i__1 = *n - 1; i__2 = *n - 1; zlaset_("L", &i__1, &i__2, &c_b59, &c_b59, &a[a_dim1 + 2], lda); } } itauq = 1; itaup = itauq + *n; nwork = itaup + *n; ie = 1; nrwork = ie + *n; /* Bidiagonalize R in A. (RWorkspace: need N) (CWorkspace: need 2*N+MM, prefer 2*N+(MM+N)*NB) */ i__1 = *lwork - nwork + 1; zgebrd_(&mm, n, &a[a_offset], lda, &s[1], &rwork[ie], &work[itauq], & work[itaup], &work[nwork], &i__1, info); /* Multiply B by transpose of left bidiagonalizing vectors of R. (CWorkspace: need 2*N+NRHS, prefer 2*N+NRHS*NB) */ i__1 = *lwork - nwork + 1; zunmbr_("Q", "L", "C", &mm, nrhs, n, &a[a_offset], lda, &work[itauq], &b[b_offset], ldb, &work[nwork], &i__1, info); /* Solve the bidiagonal least squares problem. */ zlalsd_("U", &smlsiz, n, nrhs, &s[1], &rwork[ie], &b[b_offset], ldb, rcond, rank, &work[nwork], &rwork[nrwork], &iwork[1], info); if (*info != 0) { goto L10; } /* Multiply B by right bidiagonalizing vectors of R. */ i__1 = *lwork - nwork + 1; zunmbr_("P", "L", "N", n, nrhs, n, &a[a_offset], lda, &work[itaup], & b[b_offset], ldb, &work[nwork], &i__1, info); } else /* if(complicated condition) */ { /* Computing MAX */ i__1 = *m, i__2 = ((*m) << (1)) - 4, i__1 = max(i__1,i__2), i__1 = max(i__1,*nrhs), i__2 = *n - *m * 3; if (*n >= mnthr && *lwork >= ((*m) << (2)) + *m * *m + max(i__1,i__2)) { /* Path 2a - underdetermined, with many more columns than rows and sufficient workspace for an efficient algorithm. */ ldwork = *m; /* Computing MAX Computing MAX */ i__3 = *m, i__4 = ((*m) << (1)) - 4, i__3 = max(i__3,i__4), i__3 = max(i__3,*nrhs), i__4 = *n - *m * 3; i__1 = ((*m) << (2)) + *m * *lda + max(i__3,i__4), i__2 = *m * * lda + *m + *m * *nrhs; if (*lwork >= max(i__1,i__2)) { ldwork = *lda; } itau = 1; nwork = *m + 1; /* Compute A=L*Q. (CWorkspace: need 2*M, prefer M+M*NB) */ i__1 = *lwork - nwork + 1; zgelqf_(m, n, &a[a_offset], lda, &work[itau], &work[nwork], &i__1, info); il = nwork; /* Copy L to WORK(IL), zeroing out above its diagonal. */ zlacpy_("L", m, m, &a[a_offset], lda, &work[il], &ldwork); i__1 = *m - 1; i__2 = *m - 1; zlaset_("U", &i__1, &i__2, &c_b59, &c_b59, &work[il + ldwork], & ldwork); itauq = il + ldwork * *m; itaup = itauq + *m; nwork = itaup + *m; ie = 1; nrwork = ie + *m; /* Bidiagonalize L in WORK(IL). (RWorkspace: need M) (CWorkspace: need M*M+4*M, prefer M*M+4*M+2*M*NB) */ i__1 = *lwork - nwork + 1; zgebrd_(m, m, &work[il], &ldwork, &s[1], &rwork[ie], &work[itauq], &work[itaup], &work[nwork], &i__1, info); /* Multiply B by transpose of left bidiagonalizing vectors of L. (CWorkspace: need M*M+4*M+NRHS, prefer M*M+4*M+NRHS*NB) */ i__1 = *lwork - nwork + 1; zunmbr_("Q", "L", "C", m, nrhs, m, &work[il], &ldwork, &work[ itauq], &b[b_offset], ldb, &work[nwork], &i__1, info); /* Solve the bidiagonal least squares problem. */ zlalsd_("U", &smlsiz, m, nrhs, &s[1], &rwork[ie], &b[b_offset], ldb, rcond, rank, &work[nwork], &rwork[nrwork], &iwork[1], info); if (*info != 0) { goto L10; } /* Multiply B by right bidiagonalizing vectors of L. */ i__1 = *lwork - nwork + 1; zunmbr_("P", "L", "N", m, nrhs, m, &work[il], &ldwork, &work[ itaup], &b[b_offset], ldb, &work[nwork], &i__1, info); /* Zero out below first M rows of B. */ i__1 = *n - *m; zlaset_("F", &i__1, nrhs, &c_b59, &c_b59, &b[*m + 1 + b_dim1], ldb); nwork = itau + *m; /* Multiply transpose(Q) by B. (CWorkspace: need NRHS, prefer NRHS*NB) */ i__1 = *lwork - nwork + 1; zunmlq_("L", "C", n, nrhs, m, &a[a_offset], lda, &work[itau], &b[ b_offset], ldb, &work[nwork], &i__1, info); } else { /* Path 2 - remaining underdetermined cases. */ itauq = 1; itaup = itauq + *m; nwork = itaup + *m; ie = 1; nrwork = ie + *m; /* Bidiagonalize A. (RWorkspace: need M) (CWorkspace: need 2*M+N, prefer 2*M+(M+N)*NB) */ i__1 = *lwork - nwork + 1; zgebrd_(m, n, &a[a_offset], lda, &s[1], &rwork[ie], &work[itauq], &work[itaup], &work[nwork], &i__1, info); /* Multiply B by transpose of left bidiagonalizing vectors. (CWorkspace: need 2*M+NRHS, prefer 2*M+NRHS*NB) */ i__1 = *lwork - nwork + 1; zunmbr_("Q", "L", "C", m, nrhs, n, &a[a_offset], lda, &work[itauq] , &b[b_offset], ldb, &work[nwork], &i__1, info); /* Solve the bidiagonal least squares problem. */ zlalsd_("L", &smlsiz, m, nrhs, &s[1], &rwork[ie], &b[b_offset], ldb, rcond, rank, &work[nwork], &rwork[nrwork], &iwork[1], info); if (*info != 0) { goto L10; } /* Multiply B by right bidiagonalizing vectors of A. */ i__1 = *lwork - nwork + 1; zunmbr_("P", "L", "N", n, nrhs, m, &a[a_offset], lda, &work[itaup] , &b[b_offset], ldb, &work[nwork], &i__1, info); } } /* Undo scaling. */ if (iascl == 1) { zlascl_("G", &c__0, &c__0, &anrm, &smlnum, n, nrhs, &b[b_offset], ldb, info); dlascl_("G", &c__0, &c__0, &smlnum, &anrm, &minmn, &c__1, &s[1], & minmn, info); } else if (iascl == 2) { zlascl_("G", &c__0, &c__0, &anrm, &bignum, n, nrhs, &b[b_offset], ldb, info); dlascl_("G", &c__0, &c__0, &bignum, &anrm, &minmn, &c__1, &s[1], & minmn, info); } if (ibscl == 1) { zlascl_("G", &c__0, &c__0, &smlnum, &bnrm, n, nrhs, &b[b_offset], ldb, info); } else if (ibscl == 2) { zlascl_("G", &c__0, &c__0, &bignum, &bnrm, n, nrhs, &b[b_offset], ldb, info); } L10: d__1 = (doublereal) maxwrk; z__1.r = d__1, z__1.i = 0.; work[1].r = z__1.r, work[1].i = z__1.i; return 0; /* End of ZGELSD */ } /* zgelsd_ */ /* Subroutine */ int zgeqr2_(integer *m, integer *n, doublecomplex *a, integer *lda, doublecomplex *tau, doublecomplex *work, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3; doublecomplex z__1; /* Builtin functions */ void d_cnjg(doublecomplex *, doublecomplex *); /* Local variables */ static integer i__, k; static doublecomplex alpha; extern /* Subroutine */ int zlarf_(char *, integer *, integer *, doublecomplex *, integer *, doublecomplex *, doublecomplex *, integer *, doublecomplex *), xerbla_(char *, integer *), zlarfg_(integer *, doublecomplex *, doublecomplex *, integer *, doublecomplex *); /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University September 30, 1994 Purpose ======= ZGEQR2 computes a QR factorization of a complex m by n matrix A: A = Q * R. Arguments ========= M (input) INTEGER The number of rows of the matrix A. M >= 0. N (input) INTEGER The number of columns of the matrix A. N >= 0. A (input/output) COMPLEX*16 array, dimension (LDA,N) On entry, the m by n matrix A. On exit, the elements on and above the diagonal of the array contain the min(m,n) by n upper trapezoidal matrix R (R is upper triangular if m >= n); the elements below the diagonal, with the array TAU, represent the unitary matrix Q as a product of elementary reflectors (see Further Details). LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,M). TAU (output) COMPLEX*16 array, dimension (min(M,N)) The scalar factors of the elementary reflectors (see Further Details). WORK (workspace) COMPLEX*16 array, dimension (N) INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value Further Details =============== The matrix Q is represented as a product of elementary reflectors Q = H(1) H(2) . . . H(k), where k = min(m,n). Each H(i) has the form H(i) = I - tau * v * v' where tau is a complex scalar, and v is a complex vector with v(1:i-1) = 0 and v(i) = 1; v(i+1:m) is stored on exit in A(i+1:m,i), and tau in TAU(i). ===================================================================== Test the input arguments */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --tau; --work; /* Function Body */ *info = 0; if (*m < 0) { *info = -1; } else if (*n < 0) { *info = -2; } else if (*lda < max(1,*m)) { *info = -4; } if (*info != 0) { i__1 = -(*info); xerbla_("ZGEQR2", &i__1); return 0; } k = min(*m,*n); i__1 = k; for (i__ = 1; i__ <= i__1; ++i__) { /* Generate elementary reflector H(i) to annihilate A(i+1:m,i) */ i__2 = *m - i__ + 1; /* Computing MIN */ i__3 = i__ + 1; zlarfg_(&i__2, &a[i__ + i__ * a_dim1], &a[min(i__3,*m) + i__ * a_dim1] , &c__1, &tau[i__]); if (i__ < *n) { /* Apply H(i)' to A(i:m,i+1:n) from the left */ i__2 = i__ + i__ * a_dim1; alpha.r = a[i__2].r, alpha.i = a[i__2].i; i__2 = i__ + i__ * a_dim1; a[i__2].r = 1., a[i__2].i = 0.; i__2 = *m - i__ + 1; i__3 = *n - i__; d_cnjg(&z__1, &tau[i__]); zlarf_("Left", &i__2, &i__3, &a[i__ + i__ * a_dim1], &c__1, &z__1, &a[i__ + (i__ + 1) * a_dim1], lda, &work[1]); i__2 = i__ + i__ * a_dim1; a[i__2].r = alpha.r, a[i__2].i = alpha.i; } /* L10: */ } return 0; /* End of ZGEQR2 */ } /* zgeqr2_ */ /* Subroutine */ int zgeqrf_(integer *m, integer *n, doublecomplex *a, integer *lda, doublecomplex *tau, doublecomplex *work, integer *lwork, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3, i__4; /* Local variables */ static integer i__, k, ib, nb, nx, iws, nbmin, iinfo; extern /* Subroutine */ int zgeqr2_(integer *, integer *, doublecomplex *, integer *, doublecomplex *, doublecomplex *, integer *), xerbla_( char *, integer *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); extern /* Subroutine */ int zlarfb_(char *, char *, char *, char *, integer *, integer *, integer *, doublecomplex *, integer *, doublecomplex *, integer *, doublecomplex *, integer *, doublecomplex *, integer *); static integer ldwork; extern /* Subroutine */ int zlarft_(char *, char *, integer *, integer *, doublecomplex *, integer *, doublecomplex *, doublecomplex *, integer *); static integer lwkopt; static logical lquery; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= ZGEQRF computes a QR factorization of a complex M-by-N matrix A: A = Q * R. Arguments ========= M (input) INTEGER The number of rows of the matrix A. M >= 0. N (input) INTEGER The number of columns of the matrix A. N >= 0. A (input/output) COMPLEX*16 array, dimension (LDA,N) On entry, the M-by-N matrix A. On exit, the elements on and above the diagonal of the array contain the min(M,N)-by-N upper trapezoidal matrix R (R is upper triangular if m >= n); the elements below the diagonal, with the array TAU, represent the unitary matrix Q as a product of min(m,n) elementary reflectors (see Further Details). LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,M). TAU (output) COMPLEX*16 array, dimension (min(M,N)) The scalar factors of the elementary reflectors (see Further Details). WORK (workspace/output) COMPLEX*16 array, dimension (LWORK) On exit, if INFO = 0, WORK(1) returns the optimal LWORK. LWORK (input) INTEGER The dimension of the array WORK. LWORK >= max(1,N). For optimum performance LWORK >= N*NB, where NB is the optimal blocksize. If LWORK = -1, then a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued by XERBLA. INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value Further Details =============== The matrix Q is represented as a product of elementary reflectors Q = H(1) H(2) . . . H(k), where k = min(m,n). Each H(i) has the form H(i) = I - tau * v * v' where tau is a complex scalar, and v is a complex vector with v(1:i-1) = 0 and v(i) = 1; v(i+1:m) is stored on exit in A(i+1:m,i), and tau in TAU(i). ===================================================================== Test the input arguments */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --tau; --work; /* Function Body */ *info = 0; nb = ilaenv_(&c__1, "ZGEQRF", " ", m, n, &c_n1, &c_n1, (ftnlen)6, (ftnlen) 1); lwkopt = *n * nb; work[1].r = (doublereal) lwkopt, work[1].i = 0.; lquery = *lwork == -1; if (*m < 0) { *info = -1; } else if (*n < 0) { *info = -2; } else if (*lda < max(1,*m)) { *info = -4; } else if (*lwork < max(1,*n) && ! lquery) { *info = -7; } if (*info != 0) { i__1 = -(*info); xerbla_("ZGEQRF", &i__1); return 0; } else if (lquery) { return 0; } /* Quick return if possible */ k = min(*m,*n); if (k == 0) { work[1].r = 1., work[1].i = 0.; return 0; } nbmin = 2; nx = 0; iws = *n; if (nb > 1 && nb < k) { /* Determine when to cross over from blocked to unblocked code. Computing MAX */ i__1 = 0, i__2 = ilaenv_(&c__3, "ZGEQRF", " ", m, n, &c_n1, &c_n1, ( ftnlen)6, (ftnlen)1); nx = max(i__1,i__2); if (nx < k) { /* Determine if workspace is large enough for blocked code. */ ldwork = *n; iws = ldwork * nb; if (*lwork < iws) { /* Not enough workspace to use optimal NB: reduce NB and determine the minimum value of NB. */ nb = *lwork / ldwork; /* Computing MAX */ i__1 = 2, i__2 = ilaenv_(&c__2, "ZGEQRF", " ", m, n, &c_n1, & c_n1, (ftnlen)6, (ftnlen)1); nbmin = max(i__1,i__2); } } } if (nb >= nbmin && nb < k && nx < k) { /* Use blocked code initially */ i__1 = k - nx; i__2 = nb; for (i__ = 1; i__2 < 0 ? i__ >= i__1 : i__ <= i__1; i__ += i__2) { /* Computing MIN */ i__3 = k - i__ + 1; ib = min(i__3,nb); /* Compute the QR factorization of the current block A(i:m,i:i+ib-1) */ i__3 = *m - i__ + 1; zgeqr2_(&i__3, &ib, &a[i__ + i__ * a_dim1], lda, &tau[i__], &work[ 1], &iinfo); if (i__ + ib <= *n) { /* Form the triangular factor of the block reflector H = H(i) H(i+1) . . . H(i+ib-1) */ i__3 = *m - i__ + 1; zlarft_("Forward", "Columnwise", &i__3, &ib, &a[i__ + i__ * a_dim1], lda, &tau[i__], &work[1], &ldwork); /* Apply H' to A(i:m,i+ib:n) from the left */ i__3 = *m - i__ + 1; i__4 = *n - i__ - ib + 1; zlarfb_("Left", "Conjugate transpose", "Forward", "Columnwise" , &i__3, &i__4, &ib, &a[i__ + i__ * a_dim1], lda, & work[1], &ldwork, &a[i__ + (i__ + ib) * a_dim1], lda, &work[ib + 1], &ldwork); } /* L10: */ } } else { i__ = 1; } /* Use unblocked code to factor the last or only block. */ if (i__ <= k) { i__2 = *m - i__ + 1; i__1 = *n - i__ + 1; zgeqr2_(&i__2, &i__1, &a[i__ + i__ * a_dim1], lda, &tau[i__], &work[1] , &iinfo); } work[1].r = (doublereal) iws, work[1].i = 0.; return 0; /* End of ZGEQRF */ } /* zgeqrf_ */ /* Subroutine */ int zgesdd_(char *jobz, integer *m, integer *n, doublecomplex *a, integer *lda, doublereal *s, doublecomplex *u, integer *ldu, doublecomplex *vt, integer *ldvt, doublecomplex *work, integer *lwork, doublereal *rwork, integer *iwork, integer *info) { /* System generated locals */ integer a_dim1, a_offset, u_dim1, u_offset, vt_dim1, vt_offset, i__1, i__2, i__3; /* Builtin functions */ double sqrt(doublereal); /* Local variables */ static integer i__, ie, il, ir, iu, blk; static doublereal dum[1], eps; static integer iru, ivt, iscl; static doublereal anrm; static integer idum[1], ierr, itau, irvt; extern logical lsame_(char *, char *); static integer chunk, minmn; extern /* Subroutine */ int zgemm_(char *, char *, integer *, integer *, integer *, doublecomplex *, doublecomplex *, integer *, doublecomplex *, integer *, doublecomplex *, doublecomplex *, integer *); static integer wrkbl, itaup, itauq; static logical wntqa; static integer nwork; static logical wntqn, wntqo, wntqs; extern /* Subroutine */ int zlacp2_(char *, integer *, integer *, doublereal *, integer *, doublecomplex *, integer *); static integer mnthr1, mnthr2; extern /* Subroutine */ int dbdsdc_(char *, char *, integer *, doublereal *, doublereal *, doublereal *, integer *, doublereal *, integer *, doublereal *, integer *, doublereal *, integer *, integer *); extern /* Subroutine */ int dlascl_(char *, integer *, integer *, doublereal *, doublereal *, integer *, integer *, doublereal *, integer *, integer *), xerbla_(char *, integer *), zgebrd_(integer *, integer *, doublecomplex *, integer *, doublereal *, doublereal *, doublecomplex *, doublecomplex *, doublecomplex *, integer *, integer *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); static doublereal bignum; extern doublereal zlange_(char *, integer *, integer *, doublecomplex *, integer *, doublereal *); extern /* Subroutine */ int zgelqf_(integer *, integer *, doublecomplex *, integer *, doublecomplex *, doublecomplex *, integer *, integer * ), zlacrm_(integer *, integer *, doublecomplex *, integer *, doublereal *, integer *, doublecomplex *, integer *, doublereal *) , zlarcm_(integer *, integer *, doublereal *, integer *, doublecomplex *, integer *, doublecomplex *, integer *, doublereal *), zlascl_(char *, integer *, integer *, doublereal *, doublereal *, integer *, integer *, doublecomplex *, integer *, integer *), zgeqrf_(integer *, integer *, doublecomplex *, integer *, doublecomplex *, doublecomplex *, integer *, integer * ); static integer ldwrkl; extern /* Subroutine */ int zlacpy_(char *, integer *, integer *, doublecomplex *, integer *, doublecomplex *, integer *), zlaset_(char *, integer *, integer *, doublecomplex *, doublecomplex *, doublecomplex *, integer *); static integer ldwrkr, minwrk, ldwrku, maxwrk; extern /* Subroutine */ int zungbr_(char *, integer *, integer *, integer *, doublecomplex *, integer *, doublecomplex *, doublecomplex *, integer *, integer *); static integer ldwkvt; static doublereal smlnum; static logical wntqas; extern /* Subroutine */ int zunmbr_(char *, char *, char *, integer *, integer *, integer *, doublecomplex *, integer *, doublecomplex *, doublecomplex *, integer *, doublecomplex *, integer *, integer * ), zunglq_(integer *, integer *, integer * , doublecomplex *, integer *, doublecomplex *, doublecomplex *, integer *, integer *); static logical lquery; static integer nrwork; extern /* Subroutine */ int zungqr_(integer *, integer *, integer *, doublecomplex *, integer *, doublecomplex *, doublecomplex *, integer *, integer *); /* -- LAPACK driver routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University October 31, 1999 Purpose ======= ZGESDD computes the singular value decomposition (SVD) of a complex M-by-N matrix A, optionally computing the left and/or right singular vectors, by using divide-and-conquer method. The SVD is written A = U * SIGMA * conjugate-transpose(V) where SIGMA is an M-by-N matrix which is zero except for its min(m,n) diagonal elements, U is an M-by-M unitary matrix, and V is an N-by-N unitary matrix. The diagonal elements of SIGMA are the singular values of A; they are real and non-negative, and are returned in descending order. The first min(m,n) columns of U and V are the left and right singular vectors of A. Note that the routine returns VT = V**H, not V. The divide and conquer algorithm makes very mild assumptions about floating point arithmetic. It will work on machines with a guard digit in add/subtract, or on those binary machines without guard digits which subtract like the Cray X-MP, Cray Y-MP, Cray C-90, or Cray-2. It could conceivably fail on hexadecimal or decimal machines without guard digits, but we know of none. Arguments ========= JOBZ (input) CHARACTER*1 Specifies options for computing all or part of the matrix U: = 'A': all M columns of U and all N rows of V**H are returned in the arrays U and VT; = 'S': the first min(M,N) columns of U and the first min(M,N) rows of V**H are returned in the arrays U and VT; = 'O': If M >= N, the first N columns of U are overwritten on the array A and all rows of V**H are returned in the array VT; otherwise, all columns of U are returned in the array U and the first M rows of V**H are overwritten in the array VT; = 'N': no columns of U or rows of V**H are computed. M (input) INTEGER The number of rows of the input matrix A. M >= 0. N (input) INTEGER The number of columns of the input matrix A. N >= 0. A (input/output) COMPLEX*16 array, dimension (LDA,N) On entry, the M-by-N matrix A. On exit, if JOBZ = 'O', A is overwritten with the first N columns of U (the left singular vectors, stored columnwise) if M >= N; A is overwritten with the first M rows of V**H (the right singular vectors, stored rowwise) otherwise. if JOBZ .ne. 'O', the contents of A are destroyed. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,M). S (output) DOUBLE PRECISION array, dimension (min(M,N)) The singular values of A, sorted so that S(i) >= S(i+1). U (output) COMPLEX*16 array, dimension (LDU,UCOL) UCOL = M if JOBZ = 'A' or JOBZ = 'O' and M < N; UCOL = min(M,N) if JOBZ = 'S'. If JOBZ = 'A' or JOBZ = 'O' and M < N, U contains the M-by-M unitary matrix U; if JOBZ = 'S', U contains the first min(M,N) columns of U (the left singular vectors, stored columnwise); if JOBZ = 'O' and M >= N, or JOBZ = 'N', U is not referenced. LDU (input) INTEGER The leading dimension of the array U. LDU >= 1; if JOBZ = 'S' or 'A' or JOBZ = 'O' and M < N, LDU >= M. VT (output) COMPLEX*16 array, dimension (LDVT,N) If JOBZ = 'A' or JOBZ = 'O' and M >= N, VT contains the N-by-N unitary matrix V**H; if JOBZ = 'S', VT contains the first min(M,N) rows of V**H (the right singular vectors, stored rowwise); if JOBZ = 'O' and M < N, or JOBZ = 'N', VT is not referenced. LDVT (input) INTEGER The leading dimension of the array VT. LDVT >= 1; if JOBZ = 'A' or JOBZ = 'O' and M >= N, LDVT >= N; if JOBZ = 'S', LDVT >= min(M,N). WORK (workspace/output) COMPLEX*16 array, dimension (LWORK) On exit, if INFO = 0, WORK(1) returns the optimal LWORK. LWORK (input) INTEGER The dimension of the array WORK. LWORK >= 1. if JOBZ = 'N', LWORK >= 2*min(M,N)+max(M,N). if JOBZ = 'O', LWORK >= 2*min(M,N)*min(M,N)+2*min(M,N)+max(M,N). if JOBZ = 'S' or 'A', LWORK >= min(M,N)*min(M,N)+2*min(M,N)+max(M,N). For good performance, LWORK should generally be larger. If LWORK < 0 but other input arguments are legal, WORK(1) returns the optimal LWORK. RWORK (workspace) DOUBLE PRECISION array, dimension (LRWORK) If JOBZ = 'N', LRWORK >= 7*min(M,N). Otherwise, LRWORK >= 5*min(M,N)*min(M,N) + 5*min(M,N) IWORK (workspace) INTEGER array, dimension (8*min(M,N)) INFO (output) INTEGER = 0: successful exit. < 0: if INFO = -i, the i-th argument had an illegal value. > 0: The updating process of DBDSDC did not converge. Further Details =============== Based on contributions by Ming Gu and Huan Ren, Computer Science Division, University of California at Berkeley, USA ===================================================================== Test the input arguments */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --s; u_dim1 = *ldu; u_offset = 1 + u_dim1; u -= u_offset; vt_dim1 = *ldvt; vt_offset = 1 + vt_dim1; vt -= vt_offset; --work; --rwork; --iwork; /* Function Body */ *info = 0; minmn = min(*m,*n); mnthr1 = (integer) (minmn * 17. / 9.); mnthr2 = (integer) (minmn * 5. / 3.); wntqa = lsame_(jobz, "A"); wntqs = lsame_(jobz, "S"); wntqas = (wntqa) || (wntqs); wntqo = lsame_(jobz, "O"); wntqn = lsame_(jobz, "N"); minwrk = 1; maxwrk = 1; lquery = *lwork == -1; if (! ((((wntqa) || (wntqs)) || (wntqo)) || (wntqn))) { *info = -1; } else if (*m < 0) { *info = -2; } else if (*n < 0) { *info = -3; } else if (*lda < max(1,*m)) { *info = -5; } else if (((*ldu < 1) || (wntqas && *ldu < *m)) || (wntqo && *m < *n && * ldu < *m)) { *info = -8; } else if ((((*ldvt < 1) || (wntqa && *ldvt < *n)) || (wntqs && *ldvt < minmn)) || (wntqo && *m >= *n && *ldvt < *n)) { *info = -10; } /* Compute workspace (Note: Comments in the code beginning "Workspace:" describe the minimal amount of workspace needed at that point in the code, as well as the preferred amount for good performance. CWorkspace refers to complex workspace, and RWorkspace to real workspace. NB refers to the optimal block size for the immediately following subroutine, as returned by ILAENV.) */ if (*info == 0 && *m > 0 && *n > 0) { if (*m >= *n) { /* There is no complex work space needed for bidiagonal SVD The real work space needed for bidiagonal SVD is BDSPAC, BDSPAC = 3*N*N + 4*N */ if (*m >= mnthr1) { if (wntqn) { /* Path 1 (M much larger than N, JOBZ='N') */ wrkbl = *n + *n * ilaenv_(&c__1, "ZGEQRF", " ", m, n, & c_n1, &c_n1, (ftnlen)6, (ftnlen)1); /* Computing MAX */ i__1 = wrkbl, i__2 = ((*n) << (1)) + ((*n) << (1)) * ilaenv_(&c__1, "ZGEBRD", " ", n, n, &c_n1, &c_n1, (ftnlen)6, (ftnlen)1); wrkbl = max(i__1,i__2); maxwrk = wrkbl; minwrk = *n * 3; } else if (wntqo) { /* Path 2 (M much larger than N, JOBZ='O') */ wrkbl = *n + *n * ilaenv_(&c__1, "ZGEQRF", " ", m, n, & c_n1, &c_n1, (ftnlen)6, (ftnlen)1); /* Computing MAX */ i__1 = wrkbl, i__2 = *n + *n * ilaenv_(&c__1, "ZUNGQR", " ", m, n, n, &c_n1, (ftnlen)6, (ftnlen)1); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = ((*n) << (1)) + ((*n) << (1)) * ilaenv_(&c__1, "ZGEBRD", " ", n, n, &c_n1, &c_n1, (ftnlen)6, (ftnlen)1); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = ((*n) << (1)) + *n * ilaenv_(&c__1, "ZUNMBR", "QLN", n, n, n, &c_n1, (ftnlen)6, ( ftnlen)3); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = ((*n) << (1)) + *n * ilaenv_(&c__1, "ZUNMBR", "PRC", n, n, n, &c_n1, (ftnlen)6, ( ftnlen)3); wrkbl = max(i__1,i__2); maxwrk = *m * *n + *n * *n + wrkbl; minwrk = ((*n) << (1)) * *n + *n * 3; } else if (wntqs) { /* Path 3 (M much larger than N, JOBZ='S') */ wrkbl = *n + *n * ilaenv_(&c__1, "ZGEQRF", " ", m, n, & c_n1, &c_n1, (ftnlen)6, (ftnlen)1); /* Computing MAX */ i__1 = wrkbl, i__2 = *n + *n * ilaenv_(&c__1, "ZUNGQR", " ", m, n, n, &c_n1, (ftnlen)6, (ftnlen)1); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = ((*n) << (1)) + ((*n) << (1)) * ilaenv_(&c__1, "ZGEBRD", " ", n, n, &c_n1, &c_n1, (ftnlen)6, (ftnlen)1); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = ((*n) << (1)) + *n * ilaenv_(&c__1, "ZUNMBR", "QLN", n, n, n, &c_n1, (ftnlen)6, ( ftnlen)3); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = ((*n) << (1)) + *n * ilaenv_(&c__1, "ZUNMBR", "PRC", n, n, n, &c_n1, (ftnlen)6, ( ftnlen)3); wrkbl = max(i__1,i__2); maxwrk = *n * *n + wrkbl; minwrk = *n * *n + *n * 3; } else if (wntqa) { /* Path 4 (M much larger than N, JOBZ='A') */ wrkbl = *n + *n * ilaenv_(&c__1, "ZGEQRF", " ", m, n, & c_n1, &c_n1, (ftnlen)6, (ftnlen)1); /* Computing MAX */ i__1 = wrkbl, i__2 = *n + *m * ilaenv_(&c__1, "ZUNGQR", " ", m, m, n, &c_n1, (ftnlen)6, (ftnlen)1); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = ((*n) << (1)) + ((*n) << (1)) * ilaenv_(&c__1, "ZGEBRD", " ", n, n, &c_n1, &c_n1, (ftnlen)6, (ftnlen)1); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = ((*n) << (1)) + *n * ilaenv_(&c__1, "ZUNMBR", "QLN", n, n, n, &c_n1, (ftnlen)6, ( ftnlen)3); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = ((*n) << (1)) + *n * ilaenv_(&c__1, "ZUNMBR", "PRC", n, n, n, &c_n1, (ftnlen)6, ( ftnlen)3); wrkbl = max(i__1,i__2); maxwrk = *n * *n + wrkbl; minwrk = *n * *n + ((*n) << (1)) + *m; } } else if (*m >= mnthr2) { /* Path 5 (M much larger than N, but not as much as MNTHR1) */ maxwrk = ((*n) << (1)) + (*m + *n) * ilaenv_(&c__1, "ZGEBRD", " ", m, n, &c_n1, &c_n1, (ftnlen)6, (ftnlen)1); minwrk = ((*n) << (1)) + *m; if (wntqo) { /* Computing MAX */ i__1 = maxwrk, i__2 = ((*n) << (1)) + *n * ilaenv_(&c__1, "ZUNGBR", "P", n, n, n, &c_n1, (ftnlen)6, (ftnlen) 1); maxwrk = max(i__1,i__2); /* Computing MAX */ i__1 = maxwrk, i__2 = ((*n) << (1)) + *n * ilaenv_(&c__1, "ZUNGBR", "Q", m, n, n, &c_n1, (ftnlen)6, (ftnlen) 1); maxwrk = max(i__1,i__2); maxwrk += *m * *n; minwrk += *n * *n; } else if (wntqs) { /* Computing MAX */ i__1 = maxwrk, i__2 = ((*n) << (1)) + *n * ilaenv_(&c__1, "ZUNGBR", "P", n, n, n, &c_n1, (ftnlen)6, (ftnlen) 1); maxwrk = max(i__1,i__2); /* Computing MAX */ i__1 = maxwrk, i__2 = ((*n) << (1)) + *n * ilaenv_(&c__1, "ZUNGBR", "Q", m, n, n, &c_n1, (ftnlen)6, (ftnlen) 1); maxwrk = max(i__1,i__2); } else if (wntqa) { /* Computing MAX */ i__1 = maxwrk, i__2 = ((*n) << (1)) + *n * ilaenv_(&c__1, "ZUNGBR", "P", n, n, n, &c_n1, (ftnlen)6, (ftnlen) 1); maxwrk = max(i__1,i__2); /* Computing MAX */ i__1 = maxwrk, i__2 = ((*n) << (1)) + *m * ilaenv_(&c__1, "ZUNGBR", "Q", m, m, n, &c_n1, (ftnlen)6, (ftnlen) 1); maxwrk = max(i__1,i__2); } } else { /* Path 6 (M at least N, but not much larger) */ maxwrk = ((*n) << (1)) + (*m + *n) * ilaenv_(&c__1, "ZGEBRD", " ", m, n, &c_n1, &c_n1, (ftnlen)6, (ftnlen)1); minwrk = ((*n) << (1)) + *m; if (wntqo) { /* Computing MAX */ i__1 = maxwrk, i__2 = ((*n) << (1)) + *n * ilaenv_(&c__1, "ZUNMBR", "PRC", n, n, n, &c_n1, (ftnlen)6, ( ftnlen)3); maxwrk = max(i__1,i__2); /* Computing MAX */ i__1 = maxwrk, i__2 = ((*n) << (1)) + *n * ilaenv_(&c__1, "ZUNMBR", "QLN", m, n, n, &c_n1, (ftnlen)6, ( ftnlen)3); maxwrk = max(i__1,i__2); maxwrk += *m * *n; minwrk += *n * *n; } else if (wntqs) { /* Computing MAX */ i__1 = maxwrk, i__2 = ((*n) << (1)) + *n * ilaenv_(&c__1, "ZUNMBR", "PRC", n, n, n, &c_n1, (ftnlen)6, ( ftnlen)3); maxwrk = max(i__1,i__2); /* Computing MAX */ i__1 = maxwrk, i__2 = ((*n) << (1)) + *n * ilaenv_(&c__1, "ZUNMBR", "QLN", m, n, n, &c_n1, (ftnlen)6, ( ftnlen)3); maxwrk = max(i__1,i__2); } else if (wntqa) { /* Computing MAX */ i__1 = maxwrk, i__2 = ((*n) << (1)) + *n * ilaenv_(&c__1, "ZUNGBR", "PRC", n, n, n, &c_n1, (ftnlen)6, ( ftnlen)3); maxwrk = max(i__1,i__2); /* Computing MAX */ i__1 = maxwrk, i__2 = ((*n) << (1)) + *m * ilaenv_(&c__1, "ZUNGBR", "QLN", m, m, n, &c_n1, (ftnlen)6, ( ftnlen)3); maxwrk = max(i__1,i__2); } } } else { /* There is no complex work space needed for bidiagonal SVD The real work space needed for bidiagonal SVD is BDSPAC, BDSPAC = 3*M*M + 4*M */ if (*n >= mnthr1) { if (wntqn) { /* Path 1t (N much larger than M, JOBZ='N') */ maxwrk = *m + *m * ilaenv_(&c__1, "ZGELQF", " ", m, n, & c_n1, &c_n1, (ftnlen)6, (ftnlen)1); /* Computing MAX */ i__1 = maxwrk, i__2 = ((*m) << (1)) + ((*m) << (1)) * ilaenv_(&c__1, "ZGEBRD", " ", m, m, &c_n1, &c_n1, (ftnlen)6, (ftnlen)1); maxwrk = max(i__1,i__2); minwrk = *m * 3; } else if (wntqo) { /* Path 2t (N much larger than M, JOBZ='O') */ wrkbl = *m + *m * ilaenv_(&c__1, "ZGELQF", " ", m, n, & c_n1, &c_n1, (ftnlen)6, (ftnlen)1); /* Computing MAX */ i__1 = wrkbl, i__2 = *m + *m * ilaenv_(&c__1, "ZUNGLQ", " ", m, n, m, &c_n1, (ftnlen)6, (ftnlen)1); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = ((*m) << (1)) + ((*m) << (1)) * ilaenv_(&c__1, "ZGEBRD", " ", m, m, &c_n1, &c_n1, (ftnlen)6, (ftnlen)1); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = ((*m) << (1)) + *m * ilaenv_(&c__1, "ZUNMBR", "PRC", m, m, m, &c_n1, (ftnlen)6, ( ftnlen)3); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = ((*m) << (1)) + *m * ilaenv_(&c__1, "ZUNMBR", "QLN", m, m, m, &c_n1, (ftnlen)6, ( ftnlen)3); wrkbl = max(i__1,i__2); maxwrk = *m * *n + *m * *m + wrkbl; minwrk = ((*m) << (1)) * *m + *m * 3; } else if (wntqs) { /* Path 3t (N much larger than M, JOBZ='S') */ wrkbl = *m + *m * ilaenv_(&c__1, "ZGELQF", " ", m, n, & c_n1, &c_n1, (ftnlen)6, (ftnlen)1); /* Computing MAX */ i__1 = wrkbl, i__2 = *m + *m * ilaenv_(&c__1, "ZUNGLQ", " ", m, n, m, &c_n1, (ftnlen)6, (ftnlen)1); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = ((*m) << (1)) + ((*m) << (1)) * ilaenv_(&c__1, "ZGEBRD", " ", m, m, &c_n1, &c_n1, (ftnlen)6, (ftnlen)1); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = ((*m) << (1)) + *m * ilaenv_(&c__1, "ZUNMBR", "PRC", m, m, m, &c_n1, (ftnlen)6, ( ftnlen)3); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = ((*m) << (1)) + *m * ilaenv_(&c__1, "ZUNMBR", "QLN", m, m, m, &c_n1, (ftnlen)6, ( ftnlen)3); wrkbl = max(i__1,i__2); maxwrk = *m * *m + wrkbl; minwrk = *m * *m + *m * 3; } else if (wntqa) { /* Path 4t (N much larger than M, JOBZ='A') */ wrkbl = *m + *m * ilaenv_(&c__1, "ZGELQF", " ", m, n, & c_n1, &c_n1, (ftnlen)6, (ftnlen)1); /* Computing MAX */ i__1 = wrkbl, i__2 = *m + *n * ilaenv_(&c__1, "ZUNGLQ", " ", n, n, m, &c_n1, (ftnlen)6, (ftnlen)1); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = ((*m) << (1)) + ((*m) << (1)) * ilaenv_(&c__1, "ZGEBRD", " ", m, m, &c_n1, &c_n1, (ftnlen)6, (ftnlen)1); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = ((*m) << (1)) + *m * ilaenv_(&c__1, "ZUNMBR", "PRC", m, m, m, &c_n1, (ftnlen)6, ( ftnlen)3); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = ((*m) << (1)) + *m * ilaenv_(&c__1, "ZUNMBR", "QLN", m, m, m, &c_n1, (ftnlen)6, ( ftnlen)3); wrkbl = max(i__1,i__2); maxwrk = *m * *m + wrkbl; minwrk = *m * *m + ((*m) << (1)) + *n; } } else if (*n >= mnthr2) { /* Path 5t (N much larger than M, but not as much as MNTHR1) */ maxwrk = ((*m) << (1)) + (*m + *n) * ilaenv_(&c__1, "ZGEBRD", " ", m, n, &c_n1, &c_n1, (ftnlen)6, (ftnlen)1); minwrk = ((*m) << (1)) + *n; if (wntqo) { /* Computing MAX */ i__1 = maxwrk, i__2 = ((*m) << (1)) + *m * ilaenv_(&c__1, "ZUNGBR", "P", m, n, m, &c_n1, (ftnlen)6, (ftnlen) 1); maxwrk = max(i__1,i__2); /* Computing MAX */ i__1 = maxwrk, i__2 = ((*m) << (1)) + *m * ilaenv_(&c__1, "ZUNGBR", "Q", m, m, n, &c_n1, (ftnlen)6, (ftnlen) 1); maxwrk = max(i__1,i__2); maxwrk += *m * *n; minwrk += *m * *m; } else if (wntqs) { /* Computing MAX */ i__1 = maxwrk, i__2 = ((*m) << (1)) + *m * ilaenv_(&c__1, "ZUNGBR", "P", m, n, m, &c_n1, (ftnlen)6, (ftnlen) 1); maxwrk = max(i__1,i__2); /* Computing MAX */ i__1 = maxwrk, i__2 = ((*m) << (1)) + *m * ilaenv_(&c__1, "ZUNGBR", "Q", m, m, n, &c_n1, (ftnlen)6, (ftnlen) 1); maxwrk = max(i__1,i__2); } else if (wntqa) { /* Computing MAX */ i__1 = maxwrk, i__2 = ((*m) << (1)) + *n * ilaenv_(&c__1, "ZUNGBR", "P", n, n, m, &c_n1, (ftnlen)6, (ftnlen) 1); maxwrk = max(i__1,i__2); /* Computing MAX */ i__1 = maxwrk, i__2 = ((*m) << (1)) + *m * ilaenv_(&c__1, "ZUNGBR", "Q", m, m, n, &c_n1, (ftnlen)6, (ftnlen) 1); maxwrk = max(i__1,i__2); } } else { /* Path 6t (N greater than M, but not much larger) */ maxwrk = ((*m) << (1)) + (*m + *n) * ilaenv_(&c__1, "ZGEBRD", " ", m, n, &c_n1, &c_n1, (ftnlen)6, (ftnlen)1); minwrk = ((*m) << (1)) + *n; if (wntqo) { /* Computing MAX */ i__1 = maxwrk, i__2 = ((*m) << (1)) + *m * ilaenv_(&c__1, "ZUNMBR", "PRC", m, n, m, &c_n1, (ftnlen)6, ( ftnlen)3); maxwrk = max(i__1,i__2); /* Computing MAX */ i__1 = maxwrk, i__2 = ((*m) << (1)) + *m * ilaenv_(&c__1, "ZUNMBR", "QLN", m, m, n, &c_n1, (ftnlen)6, ( ftnlen)3); maxwrk = max(i__1,i__2); maxwrk += *m * *n; minwrk += *m * *m; } else if (wntqs) { /* Computing MAX */ i__1 = maxwrk, i__2 = ((*m) << (1)) + *m * ilaenv_(&c__1, "ZUNGBR", "PRC", m, n, m, &c_n1, (ftnlen)6, ( ftnlen)3); maxwrk = max(i__1,i__2); /* Computing MAX */ i__1 = maxwrk, i__2 = ((*m) << (1)) + *m * ilaenv_(&c__1, "ZUNGBR", "QLN", m, m, n, &c_n1, (ftnlen)6, ( ftnlen)3); maxwrk = max(i__1,i__2); } else if (wntqa) { /* Computing MAX */ i__1 = maxwrk, i__2 = ((*m) << (1)) + *n * ilaenv_(&c__1, "ZUNGBR", "PRC", n, n, m, &c_n1, (ftnlen)6, ( ftnlen)3); maxwrk = max(i__1,i__2); /* Computing MAX */ i__1 = maxwrk, i__2 = ((*m) << (1)) + *m * ilaenv_(&c__1, "ZUNGBR", "QLN", m, m, n, &c_n1, (ftnlen)6, ( ftnlen)3); maxwrk = max(i__1,i__2); } } } maxwrk = max(maxwrk,minwrk); work[1].r = (doublereal) maxwrk, work[1].i = 0.; } if (*lwork < minwrk && ! lquery) { *info = -13; } if (*info != 0) { i__1 = -(*info); xerbla_("ZGESDD", &i__1); return 0; } else if (lquery) { return 0; } /* Quick return if possible */ if ((*m == 0) || (*n == 0)) { if (*lwork >= 1) { work[1].r = 1., work[1].i = 0.; } return 0; } /* Get machine constants */ eps = PRECISION; smlnum = sqrt(SAFEMINIMUM) / eps; bignum = 1. / smlnum; /* Scale A if max element outside range [SMLNUM,BIGNUM] */ anrm = zlange_("M", m, n, &a[a_offset], lda, dum); iscl = 0; if (anrm > 0. && anrm < smlnum) { iscl = 1; zlascl_("G", &c__0, &c__0, &anrm, &smlnum, m, n, &a[a_offset], lda, & ierr); } else if (anrm > bignum) { iscl = 1; zlascl_("G", &c__0, &c__0, &anrm, &bignum, m, n, &a[a_offset], lda, & ierr); } if (*m >= *n) { /* A has at least as many rows as columns. If A has sufficiently more rows than columns, first reduce using the QR decomposition (if sufficient workspace available) */ if (*m >= mnthr1) { if (wntqn) { /* Path 1 (M much larger than N, JOBZ='N') No singular vectors to be computed */ itau = 1; nwork = itau + *n; /* Compute A=Q*R (CWorkspace: need 2*N, prefer N+N*NB) (RWorkspace: need 0) */ i__1 = *lwork - nwork + 1; zgeqrf_(m, n, &a[a_offset], lda, &work[itau], &work[nwork], & i__1, &ierr); /* Zero out below R */ i__1 = *n - 1; i__2 = *n - 1; zlaset_("L", &i__1, &i__2, &c_b59, &c_b59, &a[a_dim1 + 2], lda); ie = 1; itauq = 1; itaup = itauq + *n; nwork = itaup + *n; /* Bidiagonalize R in A (CWorkspace: need 3*N, prefer 2*N+2*N*NB) (RWorkspace: need N) */ i__1 = *lwork - nwork + 1; zgebrd_(n, n, &a[a_offset], lda, &s[1], &rwork[ie], &work[ itauq], &work[itaup], &work[nwork], &i__1, &ierr); nrwork = ie + *n; /* Perform bidiagonal SVD, compute singular values only (CWorkspace: 0) (RWorkspace: need BDSPAC) */ dbdsdc_("U", "N", n, &s[1], &rwork[ie], dum, &c__1, dum, & c__1, dum, idum, &rwork[nrwork], &iwork[1], info); } else if (wntqo) { /* Path 2 (M much larger than N, JOBZ='O') N left singular vectors to be overwritten on A and N right singular vectors to be computed in VT */ iu = 1; /* WORK(IU) is N by N */ ldwrku = *n; ir = iu + ldwrku * *n; if (*lwork >= *m * *n + *n * *n + *n * 3) { /* WORK(IR) is M by N */ ldwrkr = *m; } else { ldwrkr = (*lwork - *n * *n - *n * 3) / *n; } itau = ir + ldwrkr * *n; nwork = itau + *n; /* Compute A=Q*R (CWorkspace: need N*N+2*N, prefer M*N+N+N*NB) (RWorkspace: 0) */ i__1 = *lwork - nwork + 1; zgeqrf_(m, n, &a[a_offset], lda, &work[itau], &work[nwork], & i__1, &ierr); /* Copy R to WORK( IR ), zeroing out below it */ zlacpy_("U", n, n, &a[a_offset], lda, &work[ir], &ldwrkr); i__1 = *n - 1; i__2 = *n - 1; zlaset_("L", &i__1, &i__2, &c_b59, &c_b59, &work[ir + 1], & ldwrkr); /* Generate Q in A (CWorkspace: need 2*N, prefer N+N*NB) (RWorkspace: 0) */ i__1 = *lwork - nwork + 1; zungqr_(m, n, n, &a[a_offset], lda, &work[itau], &work[nwork], &i__1, &ierr); ie = 1; itauq = itau; itaup = itauq + *n; nwork = itaup + *n; /* Bidiagonalize R in WORK(IR) (CWorkspace: need N*N+3*N, prefer M*N+2*N+2*N*NB) (RWorkspace: need N) */ i__1 = *lwork - nwork + 1; zgebrd_(n, n, &work[ir], &ldwrkr, &s[1], &rwork[ie], &work[ itauq], &work[itaup], &work[nwork], &i__1, &ierr); /* Perform bidiagonal SVD, computing left singular vectors of R in WORK(IRU) and computing right singular vectors of R in WORK(IRVT) (CWorkspace: need 0) (RWorkspace: need BDSPAC) */ iru = ie + *n; irvt = iru + *n * *n; nrwork = irvt + *n * *n; dbdsdc_("U", "I", n, &s[1], &rwork[ie], &rwork[iru], n, & rwork[irvt], n, dum, idum, &rwork[nrwork], &iwork[1], info); /* Copy real matrix RWORK(IRU) to complex matrix WORK(IU) Overwrite WORK(IU) by the left singular vectors of R (CWorkspace: need 2*N*N+3*N, prefer M*N+N*N+2*N+N*NB) (RWorkspace: 0) */ zlacp2_("F", n, n, &rwork[iru], n, &work[iu], &ldwrku); i__1 = *lwork - nwork + 1; zunmbr_("Q", "L", "N", n, n, n, &work[ir], &ldwrkr, &work[ itauq], &work[iu], &ldwrku, &work[nwork], &i__1, & ierr); /* Copy real matrix RWORK(IRVT) to complex matrix VT Overwrite VT by the right singular vectors of R (CWorkspace: need N*N+3*N, prefer M*N+2*N+N*NB) (RWorkspace: 0) */ zlacp2_("F", n, n, &rwork[irvt], n, &vt[vt_offset], ldvt); i__1 = *lwork - nwork + 1; zunmbr_("P", "R", "C", n, n, n, &work[ir], &ldwrkr, &work[ itaup], &vt[vt_offset], ldvt, &work[nwork], &i__1, & ierr); /* Multiply Q in A by left singular vectors of R in WORK(IU), storing result in WORK(IR) and copying to A (CWorkspace: need 2*N*N, prefer N*N+M*N) (RWorkspace: 0) */ i__1 = *m; i__2 = ldwrkr; for (i__ = 1; i__2 < 0 ? i__ >= i__1 : i__ <= i__1; i__ += i__2) { /* Computing MIN */ i__3 = *m - i__ + 1; chunk = min(i__3,ldwrkr); zgemm_("N", "N", &chunk, n, n, &c_b60, &a[i__ + a_dim1], lda, &work[iu], &ldwrku, &c_b59, &work[ir], & ldwrkr); zlacpy_("F", &chunk, n, &work[ir], &ldwrkr, &a[i__ + a_dim1], lda); /* L10: */ } } else if (wntqs) { /* Path 3 (M much larger than N, JOBZ='S') N left singular vectors to be computed in U and N right singular vectors to be computed in VT */ ir = 1; /* WORK(IR) is N by N */ ldwrkr = *n; itau = ir + ldwrkr * *n; nwork = itau + *n; /* Compute A=Q*R (CWorkspace: need N*N+2*N, prefer N*N+N+N*NB) (RWorkspace: 0) */ i__2 = *lwork - nwork + 1; zgeqrf_(m, n, &a[a_offset], lda, &work[itau], &work[nwork], & i__2, &ierr); /* Copy R to WORK(IR), zeroing out below it */ zlacpy_("U", n, n, &a[a_offset], lda, &work[ir], &ldwrkr); i__2 = *n - 1; i__1 = *n - 1; zlaset_("L", &i__2, &i__1, &c_b59, &c_b59, &work[ir + 1], & ldwrkr); /* Generate Q in A (CWorkspace: need 2*N, prefer N+N*NB) (RWorkspace: 0) */ i__2 = *lwork - nwork + 1; zungqr_(m, n, n, &a[a_offset], lda, &work[itau], &work[nwork], &i__2, &ierr); ie = 1; itauq = itau; itaup = itauq + *n; nwork = itaup + *n; /* Bidiagonalize R in WORK(IR) (CWorkspace: need N*N+3*N, prefer N*N+2*N+2*N*NB) (RWorkspace: need N) */ i__2 = *lwork - nwork + 1; zgebrd_(n, n, &work[ir], &ldwrkr, &s[1], &rwork[ie], &work[ itauq], &work[itaup], &work[nwork], &i__2, &ierr); /* Perform bidiagonal SVD, computing left singular vectors of bidiagonal matrix in RWORK(IRU) and computing right singular vectors of bidiagonal matrix in RWORK(IRVT) (CWorkspace: need 0) (RWorkspace: need BDSPAC) */ iru = ie + *n; irvt = iru + *n * *n; nrwork = irvt + *n * *n; dbdsdc_("U", "I", n, &s[1], &rwork[ie], &rwork[iru], n, & rwork[irvt], n, dum, idum, &rwork[nrwork], &iwork[1], info); /* Copy real matrix RWORK(IRU) to complex matrix U Overwrite U by left singular vectors of R (CWorkspace: need N*N+3*N, prefer N*N+2*N+N*NB) (RWorkspace: 0) */ zlacp2_("F", n, n, &rwork[iru], n, &u[u_offset], ldu); i__2 = *lwork - nwork + 1; zunmbr_("Q", "L", "N", n, n, n, &work[ir], &ldwrkr, &work[ itauq], &u[u_offset], ldu, &work[nwork], &i__2, &ierr); /* Copy real matrix RWORK(IRVT) to complex matrix VT Overwrite VT by right singular vectors of R (CWorkspace: need N*N+3*N, prefer N*N+2*N+N*NB) (RWorkspace: 0) */ zlacp2_("F", n, n, &rwork[irvt], n, &vt[vt_offset], ldvt); i__2 = *lwork - nwork + 1; zunmbr_("P", "R", "C", n, n, n, &work[ir], &ldwrkr, &work[ itaup], &vt[vt_offset], ldvt, &work[nwork], &i__2, & ierr); /* Multiply Q in A by left singular vectors of R in WORK(IR), storing result in U (CWorkspace: need N*N) (RWorkspace: 0) */ zlacpy_("F", n, n, &u[u_offset], ldu, &work[ir], &ldwrkr); zgemm_("N", "N", m, n, n, &c_b60, &a[a_offset], lda, &work[ir] , &ldwrkr, &c_b59, &u[u_offset], ldu); } else if (wntqa) { /* Path 4 (M much larger than N, JOBZ='A') M left singular vectors to be computed in U and N right singular vectors to be computed in VT */ iu = 1; /* WORK(IU) is N by N */ ldwrku = *n; itau = iu + ldwrku * *n; nwork = itau + *n; /* Compute A=Q*R, copying result to U (CWorkspace: need 2*N, prefer N+N*NB) (RWorkspace: 0) */ i__2 = *lwork - nwork + 1; zgeqrf_(m, n, &a[a_offset], lda, &work[itau], &work[nwork], & i__2, &ierr); zlacpy_("L", m, n, &a[a_offset], lda, &u[u_offset], ldu); /* Generate Q in U (CWorkspace: need N+M, prefer N+M*NB) (RWorkspace: 0) */ i__2 = *lwork - nwork + 1; zungqr_(m, m, n, &u[u_offset], ldu, &work[itau], &work[nwork], &i__2, &ierr); /* Produce R in A, zeroing out below it */ i__2 = *n - 1; i__1 = *n - 1; zlaset_("L", &i__2, &i__1, &c_b59, &c_b59, &a[a_dim1 + 2], lda); ie = 1; itauq = itau; itaup = itauq + *n; nwork = itaup + *n; /* Bidiagonalize R in A (CWorkspace: need 3*N, prefer 2*N+2*N*NB) (RWorkspace: need N) */ i__2 = *lwork - nwork + 1; zgebrd_(n, n, &a[a_offset], lda, &s[1], &rwork[ie], &work[ itauq], &work[itaup], &work[nwork], &i__2, &ierr); iru = ie + *n; irvt = iru + *n * *n; nrwork = irvt + *n * *n; /* Perform bidiagonal SVD, computing left singular vectors of bidiagonal matrix in RWORK(IRU) and computing right singular vectors of bidiagonal matrix in RWORK(IRVT) (CWorkspace: need 0) (RWorkspace: need BDSPAC) */ dbdsdc_("U", "I", n, &s[1], &rwork[ie], &rwork[iru], n, & rwork[irvt], n, dum, idum, &rwork[nrwork], &iwork[1], info); /* Copy real matrix RWORK(IRU) to complex matrix WORK(IU) Overwrite WORK(IU) by left singular vectors of R (CWorkspace: need N*N+3*N, prefer N*N+2*N+N*NB) (RWorkspace: 0) */ zlacp2_("F", n, n, &rwork[iru], n, &work[iu], &ldwrku); i__2 = *lwork - nwork + 1; zunmbr_("Q", "L", "N", n, n, n, &a[a_offset], lda, &work[ itauq], &work[iu], &ldwrku, &work[nwork], &i__2, & ierr); /* Copy real matrix RWORK(IRVT) to complex matrix VT Overwrite VT by right singular vectors of R (CWorkspace: need 3*N, prefer 2*N+N*NB) (RWorkspace: 0) */ zlacp2_("F", n, n, &rwork[irvt], n, &vt[vt_offset], ldvt); i__2 = *lwork - nwork + 1; zunmbr_("P", "R", "C", n, n, n, &a[a_offset], lda, &work[ itaup], &vt[vt_offset], ldvt, &work[nwork], &i__2, & ierr); /* Multiply Q in U by left singular vectors of R in WORK(IU), storing result in A (CWorkspace: need N*N) (RWorkspace: 0) */ zgemm_("N", "N", m, n, n, &c_b60, &u[u_offset], ldu, &work[iu] , &ldwrku, &c_b59, &a[a_offset], lda); /* Copy left singular vectors of A from A to U */ zlacpy_("F", m, n, &a[a_offset], lda, &u[u_offset], ldu); } } else if (*m >= mnthr2) { /* MNTHR2 <= M < MNTHR1 Path 5 (M much larger than N, but not as much as MNTHR1) Reduce to bidiagonal form without QR decomposition, use ZUNGBR and matrix multiplication to compute singular vectors */ ie = 1; nrwork = ie + *n; itauq = 1; itaup = itauq + *n; nwork = itaup + *n; /* Bidiagonalize A (CWorkspace: need 2*N+M, prefer 2*N+(M+N)*NB) (RWorkspace: need N) */ i__2 = *lwork - nwork + 1; zgebrd_(m, n, &a[a_offset], lda, &s[1], &rwork[ie], &work[itauq], &work[itaup], &work[nwork], &i__2, &ierr); if (wntqn) { /* Compute singular values only (Cworkspace: 0) (Rworkspace: need BDSPAC) */ dbdsdc_("U", "N", n, &s[1], &rwork[ie], dum, &c__1, dum, & c__1, dum, idum, &rwork[nrwork], &iwork[1], info); } else if (wntqo) { iu = nwork; iru = nrwork; irvt = iru + *n * *n; nrwork = irvt + *n * *n; /* Copy A to VT, generate P**H (Cworkspace: need 2*N, prefer N+N*NB) (Rworkspace: 0) */ zlacpy_("U", n, n, &a[a_offset], lda, &vt[vt_offset], ldvt); i__2 = *lwork - nwork + 1; zungbr_("P", n, n, n, &vt[vt_offset], ldvt, &work[itaup], & work[nwork], &i__2, &ierr); /* Generate Q in A (CWorkspace: need 2*N, prefer N+N*NB) (RWorkspace: 0) */ i__2 = *lwork - nwork + 1; zungbr_("Q", m, n, n, &a[a_offset], lda, &work[itauq], &work[ nwork], &i__2, &ierr); if (*lwork >= *m * *n + *n * 3) { /* WORK( IU ) is M by N */ ldwrku = *m; } else { /* WORK(IU) is LDWRKU by N */ ldwrku = (*lwork - *n * 3) / *n; } nwork = iu + ldwrku * *n; /* Perform bidiagonal SVD, computing left singular vectors of bidiagonal matrix in RWORK(IRU) and computing right singular vectors of bidiagonal matrix in RWORK(IRVT) (CWorkspace: need 0) (RWorkspace: need BDSPAC) */ dbdsdc_("U", "I", n, &s[1], &rwork[ie], &rwork[iru], n, & rwork[irvt], n, dum, idum, &rwork[nrwork], &iwork[1], info); /* Multiply real matrix RWORK(IRVT) by P**H in VT, storing the result in WORK(IU), copying to VT (Cworkspace: need 0) (Rworkspace: need 3*N*N) */ zlarcm_(n, n, &rwork[irvt], n, &vt[vt_offset], ldvt, &work[iu] , &ldwrku, &rwork[nrwork]); zlacpy_("F", n, n, &work[iu], &ldwrku, &vt[vt_offset], ldvt); /* Multiply Q in A by real matrix RWORK(IRU), storing the result in WORK(IU), copying to A (CWorkspace: need N*N, prefer M*N) (Rworkspace: need 3*N*N, prefer N*N+2*M*N) */ nrwork = irvt; i__2 = *m; i__1 = ldwrku; for (i__ = 1; i__1 < 0 ? i__ >= i__2 : i__ <= i__2; i__ += i__1) { /* Computing MIN */ i__3 = *m - i__ + 1; chunk = min(i__3,ldwrku); zlacrm_(&chunk, n, &a[i__ + a_dim1], lda, &rwork[iru], n, &work[iu], &ldwrku, &rwork[nrwork]); zlacpy_("F", &chunk, n, &work[iu], &ldwrku, &a[i__ + a_dim1], lda); /* L20: */ } } else if (wntqs) { /* Copy A to VT, generate P**H (Cworkspace: need 2*N, prefer N+N*NB) (Rworkspace: 0) */ zlacpy_("U", n, n, &a[a_offset], lda, &vt[vt_offset], ldvt); i__1 = *lwork - nwork + 1; zungbr_("P", n, n, n, &vt[vt_offset], ldvt, &work[itaup], & work[nwork], &i__1, &ierr); /* Copy A to U, generate Q (Cworkspace: need 2*N, prefer N+N*NB) (Rworkspace: 0) */ zlacpy_("L", m, n, &a[a_offset], lda, &u[u_offset], ldu); i__1 = *lwork - nwork + 1; zungbr_("Q", m, n, n, &u[u_offset], ldu, &work[itauq], &work[ nwork], &i__1, &ierr); /* Perform bidiagonal SVD, computing left singular vectors of bidiagonal matrix in RWORK(IRU) and computing right singular vectors of bidiagonal matrix in RWORK(IRVT) (CWorkspace: need 0) (RWorkspace: need BDSPAC) */ iru = nrwork; irvt = iru + *n * *n; nrwork = irvt + *n * *n; dbdsdc_("U", "I", n, &s[1], &rwork[ie], &rwork[iru], n, & rwork[irvt], n, dum, idum, &rwork[nrwork], &iwork[1], info); /* Multiply real matrix RWORK(IRVT) by P**H in VT, storing the result in A, copying to VT (Cworkspace: need 0) (Rworkspace: need 3*N*N) */ zlarcm_(n, n, &rwork[irvt], n, &vt[vt_offset], ldvt, &a[ a_offset], lda, &rwork[nrwork]); zlacpy_("F", n, n, &a[a_offset], lda, &vt[vt_offset], ldvt); /* Multiply Q in U by real matrix RWORK(IRU), storing the result in A, copying to U (CWorkspace: need 0) (Rworkspace: need N*N+2*M*N) */ nrwork = irvt; zlacrm_(m, n, &u[u_offset], ldu, &rwork[iru], n, &a[a_offset], lda, &rwork[nrwork]); zlacpy_("F", m, n, &a[a_offset], lda, &u[u_offset], ldu); } else { /* Copy A to VT, generate P**H (Cworkspace: need 2*N, prefer N+N*NB) (Rworkspace: 0) */ zlacpy_("U", n, n, &a[a_offset], lda, &vt[vt_offset], ldvt); i__1 = *lwork - nwork + 1; zungbr_("P", n, n, n, &vt[vt_offset], ldvt, &work[itaup], & work[nwork], &i__1, &ierr); /* Copy A to U, generate Q (Cworkspace: need 2*N, prefer N+N*NB) (Rworkspace: 0) */ zlacpy_("L", m, n, &a[a_offset], lda, &u[u_offset], ldu); i__1 = *lwork - nwork + 1; zungbr_("Q", m, m, n, &u[u_offset], ldu, &work[itauq], &work[ nwork], &i__1, &ierr); /* Perform bidiagonal SVD, computing left singular vectors of bidiagonal matrix in RWORK(IRU) and computing right singular vectors of bidiagonal matrix in RWORK(IRVT) (CWorkspace: need 0) (RWorkspace: need BDSPAC) */ iru = nrwork; irvt = iru + *n * *n; nrwork = irvt + *n * *n; dbdsdc_("U", "I", n, &s[1], &rwork[ie], &rwork[iru], n, & rwork[irvt], n, dum, idum, &rwork[nrwork], &iwork[1], info); /* Multiply real matrix RWORK(IRVT) by P**H in VT, storing the result in A, copying to VT (Cworkspace: need 0) (Rworkspace: need 3*N*N) */ zlarcm_(n, n, &rwork[irvt], n, &vt[vt_offset], ldvt, &a[ a_offset], lda, &rwork[nrwork]); zlacpy_("F", n, n, &a[a_offset], lda, &vt[vt_offset], ldvt); /* Multiply Q in U by real matrix RWORK(IRU), storing the result in A, copying to U (CWorkspace: 0) (Rworkspace: need 3*N*N) */ nrwork = irvt; zlacrm_(m, n, &u[u_offset], ldu, &rwork[iru], n, &a[a_offset], lda, &rwork[nrwork]); zlacpy_("F", m, n, &a[a_offset], lda, &u[u_offset], ldu); } } else { /* M .LT. MNTHR2 Path 6 (M at least N, but not much larger) Reduce to bidiagonal form without QR decomposition Use ZUNMBR to compute singular vectors */ ie = 1; nrwork = ie + *n; itauq = 1; itaup = itauq + *n; nwork = itaup + *n; /* Bidiagonalize A (CWorkspace: need 2*N+M, prefer 2*N+(M+N)*NB) (RWorkspace: need N) */ i__1 = *lwork - nwork + 1; zgebrd_(m, n, &a[a_offset], lda, &s[1], &rwork[ie], &work[itauq], &work[itaup], &work[nwork], &i__1, &ierr); if (wntqn) { /* Compute singular values only (Cworkspace: 0) (Rworkspace: need BDSPAC) */ dbdsdc_("U", "N", n, &s[1], &rwork[ie], dum, &c__1, dum, & c__1, dum, idum, &rwork[nrwork], &iwork[1], info); } else if (wntqo) { iu = nwork; iru = nrwork; irvt = iru + *n * *n; nrwork = irvt + *n * *n; if (*lwork >= *m * *n + *n * 3) { /* WORK( IU ) is M by N */ ldwrku = *m; } else { /* WORK( IU ) is LDWRKU by N */ ldwrku = (*lwork - *n * 3) / *n; } nwork = iu + ldwrku * *n; /* Perform bidiagonal SVD, computing left singular vectors of bidiagonal matrix in RWORK(IRU) and computing right singular vectors of bidiagonal matrix in RWORK(IRVT) (CWorkspace: need 0) (RWorkspace: need BDSPAC) */ dbdsdc_("U", "I", n, &s[1], &rwork[ie], &rwork[iru], n, & rwork[irvt], n, dum, idum, &rwork[nrwork], &iwork[1], info); /* Copy real matrix RWORK(IRVT) to complex matrix VT Overwrite VT by right singular vectors of A (Cworkspace: need 2*N, prefer N+N*NB) (Rworkspace: need 0) */ zlacp2_("F", n, n, &rwork[irvt], n, &vt[vt_offset], ldvt); i__1 = *lwork - nwork + 1; zunmbr_("P", "R", "C", n, n, n, &a[a_offset], lda, &work[ itaup], &vt[vt_offset], ldvt, &work[nwork], &i__1, & ierr); if (*lwork >= *m * *n + *n * 3) { /* Copy real matrix RWORK(IRU) to complex matrix WORK(IU) Overwrite WORK(IU) by left singular vectors of A, copying to A (Cworkspace: need M*N+2*N, prefer M*N+N+N*NB) (Rworkspace: need 0) */ zlaset_("F", m, n, &c_b59, &c_b59, &work[iu], &ldwrku); zlacp2_("F", n, n, &rwork[iru], n, &work[iu], &ldwrku); i__1 = *lwork - nwork + 1; zunmbr_("Q", "L", "N", m, n, n, &a[a_offset], lda, &work[ itauq], &work[iu], &ldwrku, &work[nwork], &i__1, & ierr); zlacpy_("F", m, n, &work[iu], &ldwrku, &a[a_offset], lda); } else { /* Generate Q in A (Cworkspace: need 2*N, prefer N+N*NB) (Rworkspace: need 0) */ i__1 = *lwork - nwork + 1; zungbr_("Q", m, n, n, &a[a_offset], lda, &work[itauq], & work[nwork], &i__1, &ierr); /* Multiply Q in A by real matrix RWORK(IRU), storing the result in WORK(IU), copying to A (CWorkspace: need N*N, prefer M*N) (Rworkspace: need 3*N*N, prefer N*N+2*M*N) */ nrwork = irvt; i__1 = *m; i__2 = ldwrku; for (i__ = 1; i__2 < 0 ? i__ >= i__1 : i__ <= i__1; i__ += i__2) { /* Computing MIN */ i__3 = *m - i__ + 1; chunk = min(i__3,ldwrku); zlacrm_(&chunk, n, &a[i__ + a_dim1], lda, &rwork[iru], n, &work[iu], &ldwrku, &rwork[nrwork]); zlacpy_("F", &chunk, n, &work[iu], &ldwrku, &a[i__ + a_dim1], lda); /* L30: */ } } } else if (wntqs) { /* Perform bidiagonal SVD, computing left singular vectors of bidiagonal matrix in RWORK(IRU) and computing right singular vectors of bidiagonal matrix in RWORK(IRVT) (CWorkspace: need 0) (RWorkspace: need BDSPAC) */ iru = nrwork; irvt = iru + *n * *n; nrwork = irvt + *n * *n; dbdsdc_("U", "I", n, &s[1], &rwork[ie], &rwork[iru], n, & rwork[irvt], n, dum, idum, &rwork[nrwork], &iwork[1], info); /* Copy real matrix RWORK(IRU) to complex matrix U Overwrite U by left singular vectors of A (CWorkspace: need 3*N, prefer 2*N+N*NB) (RWorkspace: 0) */ zlaset_("F", m, n, &c_b59, &c_b59, &u[u_offset], ldu); zlacp2_("F", n, n, &rwork[iru], n, &u[u_offset], ldu); i__2 = *lwork - nwork + 1; zunmbr_("Q", "L", "N", m, n, n, &a[a_offset], lda, &work[ itauq], &u[u_offset], ldu, &work[nwork], &i__2, &ierr); /* Copy real matrix RWORK(IRVT) to complex matrix VT Overwrite VT by right singular vectors of A (CWorkspace: need 3*N, prefer 2*N+N*NB) (RWorkspace: 0) */ zlacp2_("F", n, n, &rwork[irvt], n, &vt[vt_offset], ldvt); i__2 = *lwork - nwork + 1; zunmbr_("P", "R", "C", n, n, n, &a[a_offset], lda, &work[ itaup], &vt[vt_offset], ldvt, &work[nwork], &i__2, & ierr); } else { /* Perform bidiagonal SVD, computing left singular vectors of bidiagonal matrix in RWORK(IRU) and computing right singular vectors of bidiagonal matrix in RWORK(IRVT) (CWorkspace: need 0) (RWorkspace: need BDSPAC) */ iru = nrwork; irvt = iru + *n * *n; nrwork = irvt + *n * *n; dbdsdc_("U", "I", n, &s[1], &rwork[ie], &rwork[iru], n, & rwork[irvt], n, dum, idum, &rwork[nrwork], &iwork[1], info); /* Set the right corner of U to identity matrix */ zlaset_("F", m, m, &c_b59, &c_b59, &u[u_offset], ldu); i__2 = *m - *n; i__1 = *m - *n; zlaset_("F", &i__2, &i__1, &c_b59, &c_b60, &u[*n + 1 + (*n + 1) * u_dim1], ldu); /* Copy real matrix RWORK(IRU) to complex matrix U Overwrite U by left singular vectors of A (CWorkspace: need 2*N+M, prefer 2*N+M*NB) (RWorkspace: 0) */ zlacp2_("F", n, n, &rwork[iru], n, &u[u_offset], ldu); i__2 = *lwork - nwork + 1; zunmbr_("Q", "L", "N", m, m, n, &a[a_offset], lda, &work[ itauq], &u[u_offset], ldu, &work[nwork], &i__2, &ierr); /* Copy real matrix RWORK(IRVT) to complex matrix VT Overwrite VT by right singular vectors of A (CWorkspace: need 3*N, prefer 2*N+N*NB) (RWorkspace: 0) */ zlacp2_("F", n, n, &rwork[irvt], n, &vt[vt_offset], ldvt); i__2 = *lwork - nwork + 1; zunmbr_("P", "R", "C", n, n, n, &a[a_offset], lda, &work[ itaup], &vt[vt_offset], ldvt, &work[nwork], &i__2, & ierr); } } } else { /* A has more columns than rows. If A has sufficiently more columns than rows, first reduce using the LQ decomposition (if sufficient workspace available) */ if (*n >= mnthr1) { if (wntqn) { /* Path 1t (N much larger than M, JOBZ='N') No singular vectors to be computed */ itau = 1; nwork = itau + *m; /* Compute A=L*Q (CWorkspace: need 2*M, prefer M+M*NB) (RWorkspace: 0) */ i__2 = *lwork - nwork + 1; zgelqf_(m, n, &a[a_offset], lda, &work[itau], &work[nwork], & i__2, &ierr); /* Zero out above L */ i__2 = *m - 1; i__1 = *m - 1; zlaset_("U", &i__2, &i__1, &c_b59, &c_b59, &a[((a_dim1) << (1) ) + 1], lda); ie = 1; itauq = 1; itaup = itauq + *m; nwork = itaup + *m; /* Bidiagonalize L in A (CWorkspace: need 3*M, prefer 2*M+2*M*NB) (RWorkspace: need M) */ i__2 = *lwork - nwork + 1; zgebrd_(m, m, &a[a_offset], lda, &s[1], &rwork[ie], &work[ itauq], &work[itaup], &work[nwork], &i__2, &ierr); nrwork = ie + *m; /* Perform bidiagonal SVD, compute singular values only (CWorkspace: 0) (RWorkspace: need BDSPAC) */ dbdsdc_("U", "N", m, &s[1], &rwork[ie], dum, &c__1, dum, & c__1, dum, idum, &rwork[nrwork], &iwork[1], info); } else if (wntqo) { /* Path 2t (N much larger than M, JOBZ='O') M right singular vectors to be overwritten on A and M left singular vectors to be computed in U */ ivt = 1; ldwkvt = *m; /* WORK(IVT) is M by M */ il = ivt + ldwkvt * *m; if (*lwork >= *m * *n + *m * *m + *m * 3) { /* WORK(IL) M by N */ ldwrkl = *m; chunk = *n; } else { /* WORK(IL) is M by CHUNK */ ldwrkl = *m; chunk = (*lwork - *m * *m - *m * 3) / *m; } itau = il + ldwrkl * chunk; nwork = itau + *m; /* Compute A=L*Q (CWorkspace: need 2*M, prefer M+M*NB) (RWorkspace: 0) */ i__2 = *lwork - nwork + 1; zgelqf_(m, n, &a[a_offset], lda, &work[itau], &work[nwork], & i__2, &ierr); /* Copy L to WORK(IL), zeroing about above it */ zlacpy_("L", m, m, &a[a_offset], lda, &work[il], &ldwrkl); i__2 = *m - 1; i__1 = *m - 1; zlaset_("U", &i__2, &i__1, &c_b59, &c_b59, &work[il + ldwrkl], &ldwrkl); /* Generate Q in A (CWorkspace: need M*M+2*M, prefer M*M+M+M*NB) (RWorkspace: 0) */ i__2 = *lwork - nwork + 1; zunglq_(m, n, m, &a[a_offset], lda, &work[itau], &work[nwork], &i__2, &ierr); ie = 1; itauq = itau; itaup = itauq + *m; nwork = itaup + *m; /* Bidiagonalize L in WORK(IL) (CWorkspace: need M*M+3*M, prefer M*M+2*M+2*M*NB) (RWorkspace: need M) */ i__2 = *lwork - nwork + 1; zgebrd_(m, m, &work[il], &ldwrkl, &s[1], &rwork[ie], &work[ itauq], &work[itaup], &work[nwork], &i__2, &ierr); /* Perform bidiagonal SVD, computing left singular vectors of bidiagonal matrix in RWORK(IRU) and computing right singular vectors of bidiagonal matrix in RWORK(IRVT) (CWorkspace: need 0) (RWorkspace: need BDSPAC) */ iru = ie + *m; irvt = iru + *m * *m; nrwork = irvt + *m * *m; dbdsdc_("U", "I", m, &s[1], &rwork[ie], &rwork[iru], m, & rwork[irvt], m, dum, idum, &rwork[nrwork], &iwork[1], info); /* Copy real matrix RWORK(IRU) to complex matrix WORK(IU) Overwrite WORK(IU) by the left singular vectors of L (CWorkspace: need N*N+3*N, prefer M*N+2*N+N*NB) (RWorkspace: 0) */ zlacp2_("F", m, m, &rwork[iru], m, &u[u_offset], ldu); i__2 = *lwork - nwork + 1; zunmbr_("Q", "L", "N", m, m, m, &work[il], &ldwrkl, &work[ itauq], &u[u_offset], ldu, &work[nwork], &i__2, &ierr); /* Copy real matrix RWORK(IRVT) to complex matrix WORK(IVT) Overwrite WORK(IVT) by the right singular vectors of L (CWorkspace: need N*N+3*N, prefer M*N+2*N+N*NB) (RWorkspace: 0) */ zlacp2_("F", m, m, &rwork[irvt], m, &work[ivt], &ldwkvt); i__2 = *lwork - nwork + 1; zunmbr_("P", "R", "C", m, m, m, &work[il], &ldwrkl, &work[ itaup], &work[ivt], &ldwkvt, &work[nwork], &i__2, & ierr); /* Multiply right singular vectors of L in WORK(IL) by Q in A, storing result in WORK(IL) and copying to A (CWorkspace: need 2*M*M, prefer M*M+M*N)) (RWorkspace: 0) */ i__2 = *n; i__1 = chunk; for (i__ = 1; i__1 < 0 ? i__ >= i__2 : i__ <= i__2; i__ += i__1) { /* Computing MIN */ i__3 = *n - i__ + 1; blk = min(i__3,chunk); zgemm_("N", "N", m, &blk, m, &c_b60, &work[ivt], m, &a[ i__ * a_dim1 + 1], lda, &c_b59, &work[il], & ldwrkl); zlacpy_("F", m, &blk, &work[il], &ldwrkl, &a[i__ * a_dim1 + 1], lda); /* L40: */ } } else if (wntqs) { /* Path 3t (N much larger than M, JOBZ='S') M right singular vectors to be computed in VT and M left singular vectors to be computed in U */ il = 1; /* WORK(IL) is M by M */ ldwrkl = *m; itau = il + ldwrkl * *m; nwork = itau + *m; /* Compute A=L*Q (CWorkspace: need 2*M, prefer M+M*NB) (RWorkspace: 0) */ i__1 = *lwork - nwork + 1; zgelqf_(m, n, &a[a_offset], lda, &work[itau], &work[nwork], & i__1, &ierr); /* Copy L to WORK(IL), zeroing out above it */ zlacpy_("L", m, m, &a[a_offset], lda, &work[il], &ldwrkl); i__1 = *m - 1; i__2 = *m - 1; zlaset_("U", &i__1, &i__2, &c_b59, &c_b59, &work[il + ldwrkl], &ldwrkl); /* Generate Q in A (CWorkspace: need M*M+2*M, prefer M*M+M+M*NB) (RWorkspace: 0) */ i__1 = *lwork - nwork + 1; zunglq_(m, n, m, &a[a_offset], lda, &work[itau], &work[nwork], &i__1, &ierr); ie = 1; itauq = itau; itaup = itauq + *m; nwork = itaup + *m; /* Bidiagonalize L in WORK(IL) (CWorkspace: need M*M+3*M, prefer M*M+2*M+2*M*NB) (RWorkspace: need M) */ i__1 = *lwork - nwork + 1; zgebrd_(m, m, &work[il], &ldwrkl, &s[1], &rwork[ie], &work[ itauq], &work[itaup], &work[nwork], &i__1, &ierr); /* Perform bidiagonal SVD, computing left singular vectors of bidiagonal matrix in RWORK(IRU) and computing right singular vectors of bidiagonal matrix in RWORK(IRVT) (CWorkspace: need 0) (RWorkspace: need BDSPAC) */ iru = ie + *m; irvt = iru + *m * *m; nrwork = irvt + *m * *m; dbdsdc_("U", "I", m, &s[1], &rwork[ie], &rwork[iru], m, & rwork[irvt], m, dum, idum, &rwork[nrwork], &iwork[1], info); /* Copy real matrix RWORK(IRU) to complex matrix U Overwrite U by left singular vectors of L (CWorkspace: need M*M+3*M, prefer M*M+2*M+M*NB) (RWorkspace: 0) */ zlacp2_("F", m, m, &rwork[iru], m, &u[u_offset], ldu); i__1 = *lwork - nwork + 1; zunmbr_("Q", "L", "N", m, m, m, &work[il], &ldwrkl, &work[ itauq], &u[u_offset], ldu, &work[nwork], &i__1, &ierr); /* Copy real matrix RWORK(IRVT) to complex matrix VT Overwrite VT by left singular vectors of L (CWorkspace: need M*M+3*M, prefer M*M+2*M+M*NB) (RWorkspace: 0) */ zlacp2_("F", m, m, &rwork[irvt], m, &vt[vt_offset], ldvt); i__1 = *lwork - nwork + 1; zunmbr_("P", "R", "C", m, m, m, &work[il], &ldwrkl, &work[ itaup], &vt[vt_offset], ldvt, &work[nwork], &i__1, & ierr); /* Copy VT to WORK(IL), multiply right singular vectors of L in WORK(IL) by Q in A, storing result in VT (CWorkspace: need M*M) (RWorkspace: 0) */ zlacpy_("F", m, m, &vt[vt_offset], ldvt, &work[il], &ldwrkl); zgemm_("N", "N", m, n, m, &c_b60, &work[il], &ldwrkl, &a[ a_offset], lda, &c_b59, &vt[vt_offset], ldvt); } else if (wntqa) { /* Path 9t (N much larger than M, JOBZ='A') N right singular vectors to be computed in VT and M left singular vectors to be computed in U */ ivt = 1; /* WORK(IVT) is M by M */ ldwkvt = *m; itau = ivt + ldwkvt * *m; nwork = itau + *m; /* Compute A=L*Q, copying result to VT (CWorkspace: need 2*M, prefer M+M*NB) (RWorkspace: 0) */ i__1 = *lwork - nwork + 1; zgelqf_(m, n, &a[a_offset], lda, &work[itau], &work[nwork], & i__1, &ierr); zlacpy_("U", m, n, &a[a_offset], lda, &vt[vt_offset], ldvt); /* Generate Q in VT (CWorkspace: need M+N, prefer M+N*NB) (RWorkspace: 0) */ i__1 = *lwork - nwork + 1; zunglq_(n, n, m, &vt[vt_offset], ldvt, &work[itau], &work[ nwork], &i__1, &ierr); /* Produce L in A, zeroing out above it */ i__1 = *m - 1; i__2 = *m - 1; zlaset_("U", &i__1, &i__2, &c_b59, &c_b59, &a[((a_dim1) << (1) ) + 1], lda); ie = 1; itauq = itau; itaup = itauq + *m; nwork = itaup + *m; /* Bidiagonalize L in A (CWorkspace: need M*M+3*M, prefer M*M+2*M+2*M*NB) (RWorkspace: need M) */ i__1 = *lwork - nwork + 1; zgebrd_(m, m, &a[a_offset], lda, &s[1], &rwork[ie], &work[ itauq], &work[itaup], &work[nwork], &i__1, &ierr); /* Perform bidiagonal SVD, computing left singular vectors of bidiagonal matrix in RWORK(IRU) and computing right singular vectors of bidiagonal matrix in RWORK(IRVT) (CWorkspace: need 0) (RWorkspace: need BDSPAC) */ iru = ie + *m; irvt = iru + *m * *m; nrwork = irvt + *m * *m; dbdsdc_("U", "I", m, &s[1], &rwork[ie], &rwork[iru], m, & rwork[irvt], m, dum, idum, &rwork[nrwork], &iwork[1], info); /* Copy real matrix RWORK(IRU) to complex matrix U Overwrite U by left singular vectors of L (CWorkspace: need 3*M, prefer 2*M+M*NB) (RWorkspace: 0) */ zlacp2_("F", m, m, &rwork[iru], m, &u[u_offset], ldu); i__1 = *lwork - nwork + 1; zunmbr_("Q", "L", "N", m, m, m, &a[a_offset], lda, &work[ itauq], &u[u_offset], ldu, &work[nwork], &i__1, &ierr); /* Copy real matrix RWORK(IRVT) to complex matrix WORK(IVT) Overwrite WORK(IVT) by right singular vectors of L (CWorkspace: need M*M+3*M, prefer M*M+2*M+M*NB) (RWorkspace: 0) */ zlacp2_("F", m, m, &rwork[irvt], m, &work[ivt], &ldwkvt); i__1 = *lwork - nwork + 1; zunmbr_("P", "R", "C", m, m, m, &a[a_offset], lda, &work[ itaup], &work[ivt], &ldwkvt, &work[nwork], &i__1, & ierr); /* Multiply right singular vectors of L in WORK(IVT) by Q in VT, storing result in A (CWorkspace: need M*M) (RWorkspace: 0) */ zgemm_("N", "N", m, n, m, &c_b60, &work[ivt], &ldwkvt, &vt[ vt_offset], ldvt, &c_b59, &a[a_offset], lda); /* Copy right singular vectors of A from A to VT */ zlacpy_("F", m, n, &a[a_offset], lda, &vt[vt_offset], ldvt); } } else if (*n >= mnthr2) { /* MNTHR2 <= N < MNTHR1 Path 5t (N much larger than M, but not as much as MNTHR1) Reduce to bidiagonal form without QR decomposition, use ZUNGBR and matrix multiplication to compute singular vectors */ ie = 1; nrwork = ie + *m; itauq = 1; itaup = itauq + *m; nwork = itaup + *m; /* Bidiagonalize A (CWorkspace: need 2*M+N, prefer 2*M+(M+N)*NB) (RWorkspace: M) */ i__1 = *lwork - nwork + 1; zgebrd_(m, n, &a[a_offset], lda, &s[1], &rwork[ie], &work[itauq], &work[itaup], &work[nwork], &i__1, &ierr); if (wntqn) { /* Compute singular values only (Cworkspace: 0) (Rworkspace: need BDSPAC) */ dbdsdc_("L", "N", m, &s[1], &rwork[ie], dum, &c__1, dum, & c__1, dum, idum, &rwork[nrwork], &iwork[1], info); } else if (wntqo) { irvt = nrwork; iru = irvt + *m * *m; nrwork = iru + *m * *m; ivt = nwork; /* Copy A to U, generate Q (Cworkspace: need 2*M, prefer M+M*NB) (Rworkspace: 0) */ zlacpy_("L", m, m, &a[a_offset], lda, &u[u_offset], ldu); i__1 = *lwork - nwork + 1; zungbr_("Q", m, m, n, &u[u_offset], ldu, &work[itauq], &work[ nwork], &i__1, &ierr); /* Generate P**H in A (Cworkspace: need 2*M, prefer M+M*NB) (Rworkspace: 0) */ i__1 = *lwork - nwork + 1; zungbr_("P", m, n, m, &a[a_offset], lda, &work[itaup], &work[ nwork], &i__1, &ierr); ldwkvt = *m; if (*lwork >= *m * *n + *m * 3) { /* WORK( IVT ) is M by N */ nwork = ivt + ldwkvt * *n; chunk = *n; } else { /* WORK( IVT ) is M by CHUNK */ chunk = (*lwork - *m * 3) / *m; nwork = ivt + ldwkvt * chunk; } /* Perform bidiagonal SVD, computing left singular vectors of bidiagonal matrix in RWORK(IRU) and computing right singular vectors of bidiagonal matrix in RWORK(IRVT) (CWorkspace: need 0) (RWorkspace: need BDSPAC) */ dbdsdc_("L", "I", m, &s[1], &rwork[ie], &rwork[iru], m, & rwork[irvt], m, dum, idum, &rwork[nrwork], &iwork[1], info); /* Multiply Q in U by real matrix RWORK(IRVT) storing the result in WORK(IVT), copying to U (Cworkspace: need 0) (Rworkspace: need 2*M*M) */ zlacrm_(m, m, &u[u_offset], ldu, &rwork[iru], m, &work[ivt], & ldwkvt, &rwork[nrwork]); zlacpy_("F", m, m, &work[ivt], &ldwkvt, &u[u_offset], ldu); /* Multiply RWORK(IRVT) by P**H in A, storing the result in WORK(IVT), copying to A (CWorkspace: need M*M, prefer M*N) (Rworkspace: need 2*M*M, prefer 2*M*N) */ nrwork = iru; i__1 = *n; i__2 = chunk; for (i__ = 1; i__2 < 0 ? i__ >= i__1 : i__ <= i__1; i__ += i__2) { /* Computing MIN */ i__3 = *n - i__ + 1; blk = min(i__3,chunk); zlarcm_(m, &blk, &rwork[irvt], m, &a[i__ * a_dim1 + 1], lda, &work[ivt], &ldwkvt, &rwork[nrwork]); zlacpy_("F", m, &blk, &work[ivt], &ldwkvt, &a[i__ * a_dim1 + 1], lda); /* L50: */ } } else if (wntqs) { /* Copy A to U, generate Q (Cworkspace: need 2*M, prefer M+M*NB) (Rworkspace: 0) */ zlacpy_("L", m, m, &a[a_offset], lda, &u[u_offset], ldu); i__2 = *lwork - nwork + 1; zungbr_("Q", m, m, n, &u[u_offset], ldu, &work[itauq], &work[ nwork], &i__2, &ierr); /* Copy A to VT, generate P**H (Cworkspace: need 2*M, prefer M+M*NB) (Rworkspace: 0) */ zlacpy_("U", m, n, &a[a_offset], lda, &vt[vt_offset], ldvt); i__2 = *lwork - nwork + 1; zungbr_("P", m, n, m, &vt[vt_offset], ldvt, &work[itaup], & work[nwork], &i__2, &ierr); /* Perform bidiagonal SVD, computing left singular vectors of bidiagonal matrix in RWORK(IRU) and computing right singular vectors of bidiagonal matrix in RWORK(IRVT) (CWorkspace: need 0) (RWorkspace: need BDSPAC) */ irvt = nrwork; iru = irvt + *m * *m; nrwork = iru + *m * *m; dbdsdc_("L", "I", m, &s[1], &rwork[ie], &rwork[iru], m, & rwork[irvt], m, dum, idum, &rwork[nrwork], &iwork[1], info); /* Multiply Q in U by real matrix RWORK(IRU), storing the result in A, copying to U (CWorkspace: need 0) (Rworkspace: need 3*M*M) */ zlacrm_(m, m, &u[u_offset], ldu, &rwork[iru], m, &a[a_offset], lda, &rwork[nrwork]); zlacpy_("F", m, m, &a[a_offset], lda, &u[u_offset], ldu); /* Multiply real matrix RWORK(IRVT) by P**H in VT, storing the result in A, copying to VT (Cworkspace: need 0) (Rworkspace: need M*M+2*M*N) */ nrwork = iru; zlarcm_(m, n, &rwork[irvt], m, &vt[vt_offset], ldvt, &a[ a_offset], lda, &rwork[nrwork]); zlacpy_("F", m, n, &a[a_offset], lda, &vt[vt_offset], ldvt); } else { /* Copy A to U, generate Q (Cworkspace: need 2*M, prefer M+M*NB) (Rworkspace: 0) */ zlacpy_("L", m, m, &a[a_offset], lda, &u[u_offset], ldu); i__2 = *lwork - nwork + 1; zungbr_("Q", m, m, n, &u[u_offset], ldu, &work[itauq], &work[ nwork], &i__2, &ierr); /* Copy A to VT, generate P**H (Cworkspace: need 2*M, prefer M+M*NB) (Rworkspace: 0) */ zlacpy_("U", m, n, &a[a_offset], lda, &vt[vt_offset], ldvt); i__2 = *lwork - nwork + 1; zungbr_("P", n, n, m, &vt[vt_offset], ldvt, &work[itaup], & work[nwork], &i__2, &ierr); /* Perform bidiagonal SVD, computing left singular vectors of bidiagonal matrix in RWORK(IRU) and computing right singular vectors of bidiagonal matrix in RWORK(IRVT) (CWorkspace: need 0) (RWorkspace: need BDSPAC) */ irvt = nrwork; iru = irvt + *m * *m; nrwork = iru + *m * *m; dbdsdc_("L", "I", m, &s[1], &rwork[ie], &rwork[iru], m, & rwork[irvt], m, dum, idum, &rwork[nrwork], &iwork[1], info); /* Multiply Q in U by real matrix RWORK(IRU), storing the result in A, copying to U (CWorkspace: need 0) (Rworkspace: need 3*M*M) */ zlacrm_(m, m, &u[u_offset], ldu, &rwork[iru], m, &a[a_offset], lda, &rwork[nrwork]); zlacpy_("F", m, m, &a[a_offset], lda, &u[u_offset], ldu); /* Multiply real matrix RWORK(IRVT) by P**H in VT, storing the result in A, copying to VT (Cworkspace: need 0) (Rworkspace: need M*M+2*M*N) */ zlarcm_(m, n, &rwork[irvt], m, &vt[vt_offset], ldvt, &a[ a_offset], lda, &rwork[nrwork]); zlacpy_("F", m, n, &a[a_offset], lda, &vt[vt_offset], ldvt); } } else { /* N .LT. MNTHR2 Path 6t (N greater than M, but not much larger) Reduce to bidiagonal form without LQ decomposition Use ZUNMBR to compute singular vectors */ ie = 1; nrwork = ie + *m; itauq = 1; itaup = itauq + *m; nwork = itaup + *m; /* Bidiagonalize A (CWorkspace: need 2*M+N, prefer 2*M+(M+N)*NB) (RWorkspace: M) */ i__2 = *lwork - nwork + 1; zgebrd_(m, n, &a[a_offset], lda, &s[1], &rwork[ie], &work[itauq], &work[itaup], &work[nwork], &i__2, &ierr); if (wntqn) { /* Compute singular values only (Cworkspace: 0) (Rworkspace: need BDSPAC) */ dbdsdc_("L", "N", m, &s[1], &rwork[ie], dum, &c__1, dum, & c__1, dum, idum, &rwork[nrwork], &iwork[1], info); } else if (wntqo) { ldwkvt = *m; ivt = nwork; if (*lwork >= *m * *n + *m * 3) { /* WORK( IVT ) is M by N */ zlaset_("F", m, n, &c_b59, &c_b59, &work[ivt], &ldwkvt); nwork = ivt + ldwkvt * *n; } else { /* WORK( IVT ) is M by CHUNK */ chunk = (*lwork - *m * 3) / *m; nwork = ivt + ldwkvt * chunk; } /* Perform bidiagonal SVD, computing left singular vectors of bidiagonal matrix in RWORK(IRU) and computing right singular vectors of bidiagonal matrix in RWORK(IRVT) (CWorkspace: need 0) (RWorkspace: need BDSPAC) */ irvt = nrwork; iru = irvt + *m * *m; nrwork = iru + *m * *m; dbdsdc_("L", "I", m, &s[1], &rwork[ie], &rwork[iru], m, & rwork[irvt], m, dum, idum, &rwork[nrwork], &iwork[1], info); /* Copy real matrix RWORK(IRU) to complex matrix U Overwrite U by left singular vectors of A (Cworkspace: need 2*M, prefer M+M*NB) (Rworkspace: need 0) */ zlacp2_("F", m, m, &rwork[iru], m, &u[u_offset], ldu); i__2 = *lwork - nwork + 1; zunmbr_("Q", "L", "N", m, m, n, &a[a_offset], lda, &work[ itauq], &u[u_offset], ldu, &work[nwork], &i__2, &ierr); if (*lwork >= *m * *n + *m * 3) { /* Copy real matrix RWORK(IRVT) to complex matrix WORK(IVT) Overwrite WORK(IVT) by right singular vectors of A, copying to A (Cworkspace: need M*N+2*M, prefer M*N+M+M*NB) (Rworkspace: need 0) */ zlacp2_("F", m, m, &rwork[irvt], m, &work[ivt], &ldwkvt); i__2 = *lwork - nwork + 1; zunmbr_("P", "R", "C", m, n, m, &a[a_offset], lda, &work[ itaup], &work[ivt], &ldwkvt, &work[nwork], &i__2, &ierr); zlacpy_("F", m, n, &work[ivt], &ldwkvt, &a[a_offset], lda); } else { /* Generate P**H in A (Cworkspace: need 2*M, prefer M+M*NB) (Rworkspace: need 0) */ i__2 = *lwork - nwork + 1; zungbr_("P", m, n, m, &a[a_offset], lda, &work[itaup], & work[nwork], &i__2, &ierr); /* Multiply Q in A by real matrix RWORK(IRU), storing the result in WORK(IU), copying to A (CWorkspace: need M*M, prefer M*N) (Rworkspace: need 3*M*M, prefer M*M+2*M*N) */ nrwork = iru; i__2 = *n; i__1 = chunk; for (i__ = 1; i__1 < 0 ? i__ >= i__2 : i__ <= i__2; i__ += i__1) { /* Computing MIN */ i__3 = *n - i__ + 1; blk = min(i__3,chunk); zlarcm_(m, &blk, &rwork[irvt], m, &a[i__ * a_dim1 + 1] , lda, &work[ivt], &ldwkvt, &rwork[nrwork]); zlacpy_("F", m, &blk, &work[ivt], &ldwkvt, &a[i__ * a_dim1 + 1], lda); /* L60: */ } } } else if (wntqs) { /* Perform bidiagonal SVD, computing left singular vectors of bidiagonal matrix in RWORK(IRU) and computing right singular vectors of bidiagonal matrix in RWORK(IRVT) (CWorkspace: need 0) (RWorkspace: need BDSPAC) */ irvt = nrwork; iru = irvt + *m * *m; nrwork = iru + *m * *m; dbdsdc_("L", "I", m, &s[1], &rwork[ie], &rwork[iru], m, & rwork[irvt], m, dum, idum, &rwork[nrwork], &iwork[1], info); /* Copy real matrix RWORK(IRU) to complex matrix U Overwrite U by left singular vectors of A (CWorkspace: need 3*M, prefer 2*M+M*NB) (RWorkspace: M*M) */ zlacp2_("F", m, m, &rwork[iru], m, &u[u_offset], ldu); i__1 = *lwork - nwork + 1; zunmbr_("Q", "L", "N", m, m, n, &a[a_offset], lda, &work[ itauq], &u[u_offset], ldu, &work[nwork], &i__1, &ierr); /* Copy real matrix RWORK(IRVT) to complex matrix VT Overwrite VT by right singular vectors of A (CWorkspace: need 3*M, prefer 2*M+M*NB) (RWorkspace: M*M) */ zlaset_("F", m, n, &c_b59, &c_b59, &vt[vt_offset], ldvt); zlacp2_("F", m, m, &rwork[irvt], m, &vt[vt_offset], ldvt); i__1 = *lwork - nwork + 1; zunmbr_("P", "R", "C", m, n, m, &a[a_offset], lda, &work[ itaup], &vt[vt_offset], ldvt, &work[nwork], &i__1, & ierr); } else { /* Perform bidiagonal SVD, computing left singular vectors of bidiagonal matrix in RWORK(IRU) and computing right singular vectors of bidiagonal matrix in RWORK(IRVT) (CWorkspace: need 0) (RWorkspace: need BDSPAC) */ irvt = nrwork; iru = irvt + *m * *m; nrwork = iru + *m * *m; dbdsdc_("L", "I", m, &s[1], &rwork[ie], &rwork[iru], m, & rwork[irvt], m, dum, idum, &rwork[nrwork], &iwork[1], info); /* Copy real matrix RWORK(IRU) to complex matrix U Overwrite U by left singular vectors of A (CWorkspace: need 3*M, prefer 2*M+M*NB) (RWorkspace: M*M) */ zlacp2_("F", m, m, &rwork[iru], m, &u[u_offset], ldu); i__1 = *lwork - nwork + 1; zunmbr_("Q", "L", "N", m, m, n, &a[a_offset], lda, &work[ itauq], &u[u_offset], ldu, &work[nwork], &i__1, &ierr); /* Set the right corner of VT to identity matrix */ i__1 = *n - *m; i__2 = *n - *m; zlaset_("F", &i__1, &i__2, &c_b59, &c_b60, &vt[*m + 1 + (*m + 1) * vt_dim1], ldvt); /* Copy real matrix RWORK(IRVT) to complex matrix VT Overwrite VT by right singular vectors of A (CWorkspace: need 2*M+N, prefer 2*M+N*NB) (RWorkspace: M*M) */ zlaset_("F", n, n, &c_b59, &c_b59, &vt[vt_offset], ldvt); zlacp2_("F", m, m, &rwork[irvt], m, &vt[vt_offset], ldvt); i__1 = *lwork - nwork + 1; zunmbr_("P", "R", "C", n, n, m, &a[a_offset], lda, &work[ itaup], &vt[vt_offset], ldvt, &work[nwork], &i__1, & ierr); } } } /* Undo scaling if necessary */ if (iscl == 1) { if (anrm > bignum) { dlascl_("G", &c__0, &c__0, &bignum, &anrm, &minmn, &c__1, &s[1], & minmn, &ierr); } if (anrm < smlnum) { dlascl_("G", &c__0, &c__0, &smlnum, &anrm, &minmn, &c__1, &s[1], & minmn, &ierr); } } /* Return optimal workspace in WORK(1) */ work[1].r = (doublereal) maxwrk, work[1].i = 0.; return 0; /* End of ZGESDD */ } /* zgesdd_ */ /* Subroutine */ int zgesv_(integer *n, integer *nrhs, doublecomplex *a, integer *lda, integer *ipiv, doublecomplex *b, integer *ldb, integer * info) { /* System generated locals */ integer a_dim1, a_offset, b_dim1, b_offset, i__1; /* Local variables */ extern /* Subroutine */ int xerbla_(char *, integer *), zgetrf_( integer *, integer *, doublecomplex *, integer *, integer *, integer *), zgetrs_(char *, integer *, integer *, doublecomplex *, integer *, integer *, doublecomplex *, integer *, integer *); /* -- LAPACK driver routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University March 31, 1993 Purpose ======= ZGESV computes the solution to a complex system of linear equations A * X = B, where A is an N-by-N matrix and X and B are N-by-NRHS matrices. The LU decomposition with partial pivoting and row interchanges is used to factor A as A = P * L * U, where P is a permutation matrix, L is unit lower triangular, and U is upper triangular. The factored form of A is then used to solve the system of equations A * X = B. Arguments ========= N (input) INTEGER The number of linear equations, i.e., the order of the matrix A. N >= 0. NRHS (input) INTEGER The number of right hand sides, i.e., the number of columns of the matrix B. NRHS >= 0. A (input/output) COMPLEX*16 array, dimension (LDA,N) On entry, the N-by-N coefficient matrix A. On exit, the factors L and U from the factorization A = P*L*U; the unit diagonal elements of L are not stored. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,N). IPIV (output) INTEGER array, dimension (N) The pivot indices that define the permutation matrix P; row i of the matrix was interchanged with row IPIV(i). B (input/output) COMPLEX*16 array, dimension (LDB,NRHS) On entry, the N-by-NRHS matrix of right hand side matrix B. On exit, if INFO = 0, the N-by-NRHS solution matrix X. LDB (input) INTEGER The leading dimension of the array B. LDB >= max(1,N). INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value > 0: if INFO = i, U(i,i) is exactly zero. The factorization has been completed, but the factor U is exactly singular, so the solution could not be computed. ===================================================================== Test the input parameters. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --ipiv; b_dim1 = *ldb; b_offset = 1 + b_dim1; b -= b_offset; /* Function Body */ *info = 0; if (*n < 0) { *info = -1; } else if (*nrhs < 0) { *info = -2; } else if (*lda < max(1,*n)) { *info = -4; } else if (*ldb < max(1,*n)) { *info = -7; } if (*info != 0) { i__1 = -(*info); xerbla_("ZGESV ", &i__1); return 0; } /* Compute the LU factorization of A. */ zgetrf_(n, n, &a[a_offset], lda, &ipiv[1], info); if (*info == 0) { /* Solve the system A*X = B, overwriting B with X. */ zgetrs_("No transpose", n, nrhs, &a[a_offset], lda, &ipiv[1], &b[ b_offset], ldb, info); } return 0; /* End of ZGESV */ } /* zgesv_ */ /* Subroutine */ int zgetf2_(integer *m, integer *n, doublecomplex *a, integer *lda, integer *ipiv, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3; doublecomplex z__1; /* Builtin functions */ void z_div(doublecomplex *, doublecomplex *, doublecomplex *); /* Local variables */ static integer j, jp; extern /* Subroutine */ int zscal_(integer *, doublecomplex *, doublecomplex *, integer *), zgeru_(integer *, integer *, doublecomplex *, doublecomplex *, integer *, doublecomplex *, integer *, doublecomplex *, integer *), zswap_(integer *, doublecomplex *, integer *, doublecomplex *, integer *), xerbla_( char *, integer *); extern integer izamax_(integer *, doublecomplex *, integer *); /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University September 30, 1994 Purpose ======= ZGETF2 computes an LU factorization of a general m-by-n matrix A using partial pivoting with row interchanges. The factorization has the form A = P * L * U where P is a permutation matrix, L is lower triangular with unit diagonal elements (lower trapezoidal if m > n), and U is upper triangular (upper trapezoidal if m < n). This is the right-looking Level 2 BLAS version of the algorithm. Arguments ========= M (input) INTEGER The number of rows of the matrix A. M >= 0. N (input) INTEGER The number of columns of the matrix A. N >= 0. A (input/output) COMPLEX*16 array, dimension (LDA,N) On entry, the m by n matrix to be factored. On exit, the factors L and U from the factorization A = P*L*U; the unit diagonal elements of L are not stored. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,M). IPIV (output) INTEGER array, dimension (min(M,N)) The pivot indices; for 1 <= i <= min(M,N), row i of the matrix was interchanged with row IPIV(i). INFO (output) INTEGER = 0: successful exit < 0: if INFO = -k, the k-th argument had an illegal value > 0: if INFO = k, U(k,k) is exactly zero. The factorization has been completed, but the factor U is exactly singular, and division by zero will occur if it is used to solve a system of equations. ===================================================================== Test the input parameters. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --ipiv; /* Function Body */ *info = 0; if (*m < 0) { *info = -1; } else if (*n < 0) { *info = -2; } else if (*lda < max(1,*m)) { *info = -4; } if (*info != 0) { i__1 = -(*info); xerbla_("ZGETF2", &i__1); return 0; } /* Quick return if possible */ if ((*m == 0) || (*n == 0)) { return 0; } i__1 = min(*m,*n); for (j = 1; j <= i__1; ++j) { /* Find pivot and test for singularity. */ i__2 = *m - j + 1; jp = j - 1 + izamax_(&i__2, &a[j + j * a_dim1], &c__1); ipiv[j] = jp; i__2 = jp + j * a_dim1; if ((a[i__2].r != 0.) || (a[i__2].i != 0.)) { /* Apply the interchange to columns 1:N. */ if (jp != j) { zswap_(n, &a[j + a_dim1], lda, &a[jp + a_dim1], lda); } /* Compute elements J+1:M of J-th column. */ if (j < *m) { i__2 = *m - j; z_div(&z__1, &c_b60, &a[j + j * a_dim1]); zscal_(&i__2, &z__1, &a[j + 1 + j * a_dim1], &c__1); } } else if (*info == 0) { *info = j; } if (j < min(*m,*n)) { /* Update trailing submatrix. */ i__2 = *m - j; i__3 = *n - j; z__1.r = -1., z__1.i = -0.; zgeru_(&i__2, &i__3, &z__1, &a[j + 1 + j * a_dim1], &c__1, &a[j + (j + 1) * a_dim1], lda, &a[j + 1 + (j + 1) * a_dim1], lda) ; } /* L10: */ } return 0; /* End of ZGETF2 */ } /* zgetf2_ */ /* Subroutine */ int zgetrf_(integer *m, integer *n, doublecomplex *a, integer *lda, integer *ipiv, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3, i__4, i__5; doublecomplex z__1; /* Local variables */ static integer i__, j, jb, nb, iinfo; extern /* Subroutine */ int zgemm_(char *, char *, integer *, integer *, integer *, doublecomplex *, doublecomplex *, integer *, doublecomplex *, integer *, doublecomplex *, doublecomplex *, integer *), ztrsm_(char *, char *, char *, char *, integer *, integer *, doublecomplex *, doublecomplex *, integer * , doublecomplex *, integer *), zgetf2_(integer *, integer *, doublecomplex *, integer *, integer *, integer *), xerbla_(char *, integer *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); extern /* Subroutine */ int zlaswp_(integer *, doublecomplex *, integer *, integer *, integer *, integer *, integer *); /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University September 30, 1994 Purpose ======= ZGETRF computes an LU factorization of a general M-by-N matrix A using partial pivoting with row interchanges. The factorization has the form A = P * L * U where P is a permutation matrix, L is lower triangular with unit diagonal elements (lower trapezoidal if m > n), and U is upper triangular (upper trapezoidal if m < n). This is the right-looking Level 3 BLAS version of the algorithm. Arguments ========= M (input) INTEGER The number of rows of the matrix A. M >= 0. N (input) INTEGER The number of columns of the matrix A. N >= 0. A (input/output) COMPLEX*16 array, dimension (LDA,N) On entry, the M-by-N matrix to be factored. On exit, the factors L and U from the factorization A = P*L*U; the unit diagonal elements of L are not stored. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,M). IPIV (output) INTEGER array, dimension (min(M,N)) The pivot indices; for 1 <= i <= min(M,N), row i of the matrix was interchanged with row IPIV(i). INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value > 0: if INFO = i, U(i,i) is exactly zero. The factorization has been completed, but the factor U is exactly singular, and division by zero will occur if it is used to solve a system of equations. ===================================================================== Test the input parameters. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --ipiv; /* Function Body */ *info = 0; if (*m < 0) { *info = -1; } else if (*n < 0) { *info = -2; } else if (*lda < max(1,*m)) { *info = -4; } if (*info != 0) { i__1 = -(*info); xerbla_("ZGETRF", &i__1); return 0; } /* Quick return if possible */ if ((*m == 0) || (*n == 0)) { return 0; } /* Determine the block size for this environment. */ nb = ilaenv_(&c__1, "ZGETRF", " ", m, n, &c_n1, &c_n1, (ftnlen)6, (ftnlen) 1); if ((nb <= 1) || (nb >= min(*m,*n))) { /* Use unblocked code. */ zgetf2_(m, n, &a[a_offset], lda, &ipiv[1], info); } else { /* Use blocked code. */ i__1 = min(*m,*n); i__2 = nb; for (j = 1; i__2 < 0 ? j >= i__1 : j <= i__1; j += i__2) { /* Computing MIN */ i__3 = min(*m,*n) - j + 1; jb = min(i__3,nb); /* Factor diagonal and subdiagonal blocks and test for exact singularity. */ i__3 = *m - j + 1; zgetf2_(&i__3, &jb, &a[j + j * a_dim1], lda, &ipiv[j], &iinfo); /* Adjust INFO and the pivot indices. */ if (*info == 0 && iinfo > 0) { *info = iinfo + j - 1; } /* Computing MIN */ i__4 = *m, i__5 = j + jb - 1; i__3 = min(i__4,i__5); for (i__ = j; i__ <= i__3; ++i__) { ipiv[i__] = j - 1 + ipiv[i__]; /* L10: */ } /* Apply interchanges to columns 1:J-1. */ i__3 = j - 1; i__4 = j + jb - 1; zlaswp_(&i__3, &a[a_offset], lda, &j, &i__4, &ipiv[1], &c__1); if (j + jb <= *n) { /* Apply interchanges to columns J+JB:N. */ i__3 = *n - j - jb + 1; i__4 = j + jb - 1; zlaswp_(&i__3, &a[(j + jb) * a_dim1 + 1], lda, &j, &i__4, & ipiv[1], &c__1); /* Compute block row of U. */ i__3 = *n - j - jb + 1; ztrsm_("Left", "Lower", "No transpose", "Unit", &jb, &i__3, & c_b60, &a[j + j * a_dim1], lda, &a[j + (j + jb) * a_dim1], lda); if (j + jb <= *m) { /* Update trailing submatrix. */ i__3 = *m - j - jb + 1; i__4 = *n - j - jb + 1; z__1.r = -1., z__1.i = -0.; zgemm_("No transpose", "No transpose", &i__3, &i__4, &jb, &z__1, &a[j + jb + j * a_dim1], lda, &a[j + (j + jb) * a_dim1], lda, &c_b60, &a[j + jb + (j + jb) * a_dim1], lda); } } /* L20: */ } } return 0; /* End of ZGETRF */ } /* zgetrf_ */ /* Subroutine */ int zgetrs_(char *trans, integer *n, integer *nrhs, doublecomplex *a, integer *lda, integer *ipiv, doublecomplex *b, integer *ldb, integer *info) { /* System generated locals */ integer a_dim1, a_offset, b_dim1, b_offset, i__1; /* Local variables */ extern logical lsame_(char *, char *); extern /* Subroutine */ int ztrsm_(char *, char *, char *, char *, integer *, integer *, doublecomplex *, doublecomplex *, integer *, doublecomplex *, integer *), xerbla_(char *, integer *); static logical notran; extern /* Subroutine */ int zlaswp_(integer *, doublecomplex *, integer *, integer *, integer *, integer *, integer *); /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University September 30, 1994 Purpose ======= ZGETRS solves a system of linear equations A * X = B, A**T * X = B, or A**H * X = B with a general N-by-N matrix A using the LU factorization computed by ZGETRF. Arguments ========= TRANS (input) CHARACTER*1 Specifies the form of the system of equations: = 'N': A * X = B (No transpose) = 'T': A**T * X = B (Transpose) = 'C': A**H * X = B (Conjugate transpose) N (input) INTEGER The order of the matrix A. N >= 0. NRHS (input) INTEGER The number of right hand sides, i.e., the number of columns of the matrix B. NRHS >= 0. A (input) COMPLEX*16 array, dimension (LDA,N) The factors L and U from the factorization A = P*L*U as computed by ZGETRF. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,N). IPIV (input) INTEGER array, dimension (N) The pivot indices from ZGETRF; for 1<=i<=N, row i of the matrix was interchanged with row IPIV(i). B (input/output) COMPLEX*16 array, dimension (LDB,NRHS) On entry, the right hand side matrix B. On exit, the solution matrix X. LDB (input) INTEGER The leading dimension of the array B. LDB >= max(1,N). INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value ===================================================================== Test the input parameters. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --ipiv; b_dim1 = *ldb; b_offset = 1 + b_dim1; b -= b_offset; /* Function Body */ *info = 0; notran = lsame_(trans, "N"); if (! notran && ! lsame_(trans, "T") && ! lsame_( trans, "C")) { *info = -1; } else if (*n < 0) { *info = -2; } else if (*nrhs < 0) { *info = -3; } else if (*lda < max(1,*n)) { *info = -5; } else if (*ldb < max(1,*n)) { *info = -8; } if (*info != 0) { i__1 = -(*info); xerbla_("ZGETRS", &i__1); return 0; } /* Quick return if possible */ if ((*n == 0) || (*nrhs == 0)) { return 0; } if (notran) { /* Solve A * X = B. Apply row interchanges to the right hand sides. */ zlaswp_(nrhs, &b[b_offset], ldb, &c__1, n, &ipiv[1], &c__1); /* Solve L*X = B, overwriting B with X. */ ztrsm_("Left", "Lower", "No transpose", "Unit", n, nrhs, &c_b60, &a[ a_offset], lda, &b[b_offset], ldb); /* Solve U*X = B, overwriting B with X. */ ztrsm_("Left", "Upper", "No transpose", "Non-unit", n, nrhs, &c_b60, & a[a_offset], lda, &b[b_offset], ldb); } else { /* Solve A**T * X = B or A**H * X = B. Solve U'*X = B, overwriting B with X. */ ztrsm_("Left", "Upper", trans, "Non-unit", n, nrhs, &c_b60, &a[ a_offset], lda, &b[b_offset], ldb); /* Solve L'*X = B, overwriting B with X. */ ztrsm_("Left", "Lower", trans, "Unit", n, nrhs, &c_b60, &a[a_offset], lda, &b[b_offset], ldb); /* Apply row interchanges to the solution vectors. */ zlaswp_(nrhs, &b[b_offset], ldb, &c__1, n, &ipiv[1], &c_n1); } return 0; /* End of ZGETRS */ } /* zgetrs_ */ /* Subroutine */ int zheevd_(char *jobz, char *uplo, integer *n, doublecomplex *a, integer *lda, doublereal *w, doublecomplex *work, integer *lwork, doublereal *rwork, integer *lrwork, integer *iwork, integer *liwork, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3, i__4; doublereal d__1, d__2; /* Builtin functions */ double sqrt(doublereal); /* Local variables */ static doublereal eps; static integer inde; static doublereal anrm; static integer imax; static doublereal rmin, rmax; static integer lopt; extern /* Subroutine */ int dscal_(integer *, doublereal *, doublereal *, integer *); static doublereal sigma; extern logical lsame_(char *, char *); static integer iinfo, lwmin, liopt; static logical lower; static integer llrwk, lropt; static logical wantz; static integer indwk2, llwrk2; static integer iscale; static doublereal safmin; extern /* Subroutine */ int xerbla_(char *, integer *); static doublereal bignum; extern doublereal zlanhe_(char *, char *, integer *, doublecomplex *, integer *, doublereal *); static integer indtau; extern /* Subroutine */ int dsterf_(integer *, doublereal *, doublereal *, integer *), zlascl_(char *, integer *, integer *, doublereal *, doublereal *, integer *, integer *, doublecomplex *, integer *, integer *), zstedc_(char *, integer *, doublereal *, doublereal *, doublecomplex *, integer *, doublecomplex *, integer *, doublereal *, integer *, integer *, integer *, integer *); static integer indrwk, indwrk, liwmin; extern /* Subroutine */ int zhetrd_(char *, integer *, doublecomplex *, integer *, doublereal *, doublereal *, doublecomplex *, doublecomplex *, integer *, integer *), zlacpy_(char *, integer *, integer *, doublecomplex *, integer *, doublecomplex *, integer *); static integer lrwmin, llwork; static doublereal smlnum; static logical lquery; extern /* Subroutine */ int zunmtr_(char *, char *, char *, integer *, integer *, doublecomplex *, integer *, doublecomplex *, doublecomplex *, integer *, doublecomplex *, integer *, integer *); /* -- LAPACK driver routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= ZHEEVD computes all eigenvalues and, optionally, eigenvectors of a complex Hermitian matrix A. If eigenvectors are desired, it uses a divide and conquer algorithm. The divide and conquer algorithm makes very mild assumptions about floating point arithmetic. It will work on machines with a guard digit in add/subtract, or on those binary machines without guard digits which subtract like the Cray X-MP, Cray Y-MP, Cray C-90, or Cray-2. It could conceivably fail on hexadecimal or decimal machines without guard digits, but we know of none. Arguments ========= JOBZ (input) CHARACTER*1 = 'N': Compute eigenvalues only; = 'V': Compute eigenvalues and eigenvectors. UPLO (input) CHARACTER*1 = 'U': Upper triangle of A is stored; = 'L': Lower triangle of A is stored. N (input) INTEGER The order of the matrix A. N >= 0. 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. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,N). W (output) DOUBLE PRECISION array, dimension (N) If INFO = 0, the eigenvalues in ascending order. WORK (workspace/output) COMPLEX*16 array, dimension (LWORK) On exit, if INFO = 0, WORK(1) returns the optimal LWORK. LWORK (input) INTEGER The length of the array WORK. If N <= 1, LWORK must be at least 1. If JOBZ = 'N' and N > 1, LWORK must be at least N + 1. If JOBZ = 'V' and N > 1, LWORK must be at least 2*N + N**2. If LWORK = -1, then a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued by XERBLA. RWORK (workspace/output) DOUBLE PRECISION array, dimension (LRWORK) On exit, if INFO = 0, RWORK(1) returns the optimal LRWORK. LRWORK (input) INTEGER The dimension of the array RWORK. If N <= 1, LRWORK must be at least 1. If JOBZ = 'N' and N > 1, LRWORK must be at least N. If JOBZ = 'V' and N > 1, LRWORK must be at least 1 + 5*N + 2*N**2. If LRWORK = -1, then a workspace query is assumed; the routine only calculates the optimal size of the RWORK array, returns this value as the first entry of the RWORK array, and no error message related to LRWORK is issued by XERBLA. IWORK (workspace/output) INTEGER array, dimension (LIWORK) On exit, if INFO = 0, IWORK(1) returns the optimal LIWORK. LIWORK (input) INTEGER The dimension of the array IWORK. If N <= 1, LIWORK must be at least 1. If JOBZ = 'N' and N > 1, LIWORK must be at least 1. If JOBZ = 'V' and N > 1, LIWORK must be at least 3 + 5*N. If LIWORK = -1, then a workspace query is assumed; the routine only calculates the optimal size of the IWORK array, returns this value as the first entry of the IWORK array, and no error message related to LIWORK is issued by XERBLA. 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. Further Details =============== Based on contributions by Jeff Rutter, Computer Science Division, University of California at Berkeley, USA ===================================================================== Test the input parameters. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --w; --work; --rwork; --iwork; /* Function Body */ wantz = lsame_(jobz, "V"); lower = lsame_(uplo, "L"); lquery = ((*lwork == -1) || (*lrwork == -1)) || (*liwork == -1); *info = 0; if (*n <= 1) { lwmin = 1; lrwmin = 1; liwmin = 1; lopt = lwmin; lropt = lrwmin; liopt = liwmin; } else { if (wantz) { lwmin = ((*n) << (1)) + *n * *n; /* Computing 2nd power */ i__1 = *n; lrwmin = *n * 5 + 1 + ((i__1 * i__1) << (1)); liwmin = *n * 5 + 3; } else { lwmin = *n + 1; lrwmin = *n; liwmin = 1; } lopt = lwmin; lropt = lrwmin; liopt = liwmin; } if (! ((wantz) || (lsame_(jobz, "N")))) { *info = -1; } else if (! ((lower) || (lsame_(uplo, "U")))) { *info = -2; } else if (*n < 0) { *info = -3; } else if (*lda < max(1,*n)) { *info = -5; } else if (*lwork < lwmin && ! lquery) { *info = -8; } else if (*lrwork < lrwmin && ! lquery) { *info = -10; } else if (*liwork < liwmin && ! lquery) { *info = -12; } if (*info == 0) { work[1].r = (doublereal) lopt, work[1].i = 0.; rwork[1] = (doublereal) lropt; iwork[1] = liopt; } if (*info != 0) { i__1 = -(*info); xerbla_("ZHEEVD", &i__1); return 0; } else if (lquery) { return 0; } /* Quick return if possible */ if (*n == 0) { return 0; } if (*n == 1) { i__1 = a_dim1 + 1; w[1] = a[i__1].r; if (wantz) { i__1 = a_dim1 + 1; a[i__1].r = 1., a[i__1].i = 0.; } return 0; } /* Get machine constants. */ safmin = SAFEMINIMUM; eps = PRECISION; smlnum = safmin / eps; bignum = 1. / smlnum; rmin = sqrt(smlnum); rmax = sqrt(bignum); /* Scale matrix to allowable range, if necessary. */ anrm = zlanhe_("M", uplo, n, &a[a_offset], lda, &rwork[1]); iscale = 0; if (anrm > 0. && anrm < rmin) { iscale = 1; sigma = rmin / anrm; } else if (anrm > rmax) { iscale = 1; sigma = rmax / anrm; } if (iscale == 1) { zlascl_(uplo, &c__0, &c__0, &c_b1015, &sigma, n, n, &a[a_offset], lda, info); } /* Call ZHETRD to reduce Hermitian matrix to tridiagonal form. */ inde = 1; indtau = 1; indwrk = indtau + *n; indrwk = inde + *n; indwk2 = indwrk + *n * *n; llwork = *lwork - indwrk + 1; llwrk2 = *lwork - indwk2 + 1; llrwk = *lrwork - indrwk + 1; zhetrd_(uplo, n, &a[a_offset], lda, &w[1], &rwork[inde], &work[indtau], & work[indwrk], &llwork, &iinfo); /* Computing MAX */ i__1 = indwrk; d__1 = (doublereal) lopt, d__2 = (doublereal) (*n) + work[i__1].r; lopt = (integer) max(d__1,d__2); /* For eigenvalues only, call DSTERF. For eigenvectors, first call ZSTEDC to generate the eigenvector matrix, WORK(INDWRK), of the tridiagonal matrix, then call ZUNMTR to multiply it to the Householder transformations represented as Householder vectors in A. */ if (! wantz) { dsterf_(n, &w[1], &rwork[inde], info); } else { zstedc_("I", n, &w[1], &rwork[inde], &work[indwrk], n, &work[indwk2], &llwrk2, &rwork[indrwk], &llrwk, &iwork[1], liwork, info); zunmtr_("L", uplo, "N", n, n, &a[a_offset], lda, &work[indtau], &work[ indwrk], n, &work[indwk2], &llwrk2, &iinfo); zlacpy_("A", n, n, &work[indwrk], n, &a[a_offset], lda); /* Computing MAX Computing 2nd power */ i__3 = *n; i__4 = indwk2; i__1 = lopt, i__2 = *n + i__3 * i__3 + (integer) work[i__4].r; lopt = max(i__1,i__2); } /* If matrix was scaled, then rescale eigenvalues appropriately. */ if (iscale == 1) { if (*info == 0) { imax = *n; } else { imax = *info - 1; } d__1 = 1. / sigma; dscal_(&imax, &d__1, &w[1], &c__1); } work[1].r = (doublereal) lopt, work[1].i = 0.; rwork[1] = (doublereal) lropt; iwork[1] = liopt; return 0; /* End of ZHEEVD */ } /* zheevd_ */ /* Subroutine */ int zhetd2_(char *uplo, integer *n, doublecomplex *a, integer *lda, doublereal *d__, doublereal *e, doublecomplex *tau, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3; doublereal d__1; doublecomplex z__1, z__2, z__3, z__4; /* Local variables */ static integer i__; static doublecomplex taui; extern /* Subroutine */ int zher2_(char *, integer *, doublecomplex *, doublecomplex *, integer *, doublecomplex *, integer *, doublecomplex *, integer *); static doublecomplex alpha; extern logical lsame_(char *, char *); extern /* Double Complex */ VOID zdotc_(doublecomplex *, integer *, doublecomplex *, integer *, doublecomplex *, integer *); extern /* Subroutine */ int zhemv_(char *, integer *, doublecomplex *, doublecomplex *, integer *, doublecomplex *, integer *, doublecomplex *, doublecomplex *, integer *); static logical upper; extern /* Subroutine */ int zaxpy_(integer *, doublecomplex *, doublecomplex *, integer *, doublecomplex *, integer *), xerbla_( char *, integer *), zlarfg_(integer *, doublecomplex *, doublecomplex *, integer *, doublecomplex *); /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University October 31, 1999 Purpose ======= ZHETD2 reduces a complex Hermitian matrix A to real symmetric tridiagonal form T by a unitary similarity transformation: Q' * A * Q = T. Arguments ========= UPLO (input) CHARACTER*1 Specifies whether the upper or lower triangular part of the Hermitian matrix A is stored: = 'U': Upper triangular = 'L': Lower triangular N (input) INTEGER The order of the matrix A. N >= 0. 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, and the strictly lower triangular part of A is not referenced. If UPLO = 'L', the leading n-by-n lower triangular part of A contains the lower triangular part of the matrix A, and the strictly upper triangular part of A is not referenced. On exit, if UPLO = 'U', the diagonal and first superdiagonal of A are overwritten by the corresponding elements of the tridiagonal matrix T, and the elements above the first superdiagonal, with the array TAU, represent the unitary matrix Q as a product of elementary reflectors; if UPLO = 'L', the diagonal and first subdiagonal of A are over- written by the corresponding elements of the tridiagonal matrix T, and the elements below the first subdiagonal, with the array TAU, represent the unitary matrix Q as a product of elementary reflectors. See Further Details. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,N). D (output) DOUBLE PRECISION array, dimension (N) The diagonal elements of the tridiagonal matrix T: D(i) = A(i,i). E (output) DOUBLE PRECISION array, dimension (N-1) The off-diagonal elements of the tridiagonal matrix T: E(i) = A(i,i+1) if UPLO = 'U', E(i) = A(i+1,i) if UPLO = 'L'. TAU (output) COMPLEX*16 array, dimension (N-1) The scalar factors of the elementary reflectors (see Further Details). INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value. Further Details =============== If UPLO = 'U', the matrix Q is represented as a product of elementary reflectors Q = H(n-1) . . . H(2) H(1). Each H(i) has the form H(i) = I - tau * v * v' where tau is a complex scalar, and v is a complex vector with v(i+1:n) = 0 and v(i) = 1; v(1:i-1) is stored on exit in A(1:i-1,i+1), and tau in TAU(i). If UPLO = 'L', the matrix Q is represented as a product of elementary reflectors Q = H(1) H(2) . . . H(n-1). Each H(i) has the form H(i) = I - tau * v * v' where tau is a complex scalar, and v is a complex vector with v(1:i) = 0 and v(i+1) = 1; v(i+2:n) is stored on exit in A(i+2:n,i), and tau in TAU(i). The contents of A on exit are illustrated by the following examples with n = 5: if UPLO = 'U': if UPLO = 'L': ( d e v2 v3 v4 ) ( d ) ( d e v3 v4 ) ( e d ) ( d e v4 ) ( v1 e d ) ( d e ) ( v1 v2 e d ) ( d ) ( v1 v2 v3 e d ) where d and e denote diagonal and off-diagonal elements of T, and vi denotes an element of the vector defining H(i). ===================================================================== Test the input parameters */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --d__; --e; --tau; /* Function Body */ *info = 0; upper = lsame_(uplo, "U"); if (! upper && ! lsame_(uplo, "L")) { *info = -1; } else if (*n < 0) { *info = -2; } else if (*lda < max(1,*n)) { *info = -4; } if (*info != 0) { i__1 = -(*info); xerbla_("ZHETD2", &i__1); return 0; } /* Quick return if possible */ if (*n <= 0) { return 0; } if (upper) { /* Reduce the upper triangle of A */ i__1 = *n + *n * a_dim1; i__2 = *n + *n * a_dim1; d__1 = a[i__2].r; a[i__1].r = d__1, a[i__1].i = 0.; for (i__ = *n - 1; i__ >= 1; --i__) { /* Generate elementary reflector H(i) = I - tau * v * v' to annihilate A(1:i-1,i+1) */ i__1 = i__ + (i__ + 1) * a_dim1; alpha.r = a[i__1].r, alpha.i = a[i__1].i; zlarfg_(&i__, &alpha, &a[(i__ + 1) * a_dim1 + 1], &c__1, &taui); i__1 = i__; e[i__1] = alpha.r; if ((taui.r != 0.) || (taui.i != 0.)) { /* Apply H(i) from both sides to A(1:i,1:i) */ i__1 = i__ + (i__ + 1) * a_dim1; a[i__1].r = 1., a[i__1].i = 0.; /* Compute x := tau * A * v storing x in TAU(1:i) */ zhemv_(uplo, &i__, &taui, &a[a_offset], lda, &a[(i__ + 1) * a_dim1 + 1], &c__1, &c_b59, &tau[1], &c__1) ; /* Compute w := x - 1/2 * tau * (x'*v) * v */ z__3.r = -.5, z__3.i = -0.; z__2.r = z__3.r * taui.r - z__3.i * taui.i, z__2.i = z__3.r * taui.i + z__3.i * taui.r; zdotc_(&z__4, &i__, &tau[1], &c__1, &a[(i__ + 1) * a_dim1 + 1] , &c__1); z__1.r = z__2.r * z__4.r - z__2.i * z__4.i, z__1.i = z__2.r * z__4.i + z__2.i * z__4.r; alpha.r = z__1.r, alpha.i = z__1.i; zaxpy_(&i__, &alpha, &a[(i__ + 1) * a_dim1 + 1], &c__1, &tau[ 1], &c__1); /* Apply the transformation as a rank-2 update: A := A - v * w' - w * v' */ z__1.r = -1., z__1.i = -0.; zher2_(uplo, &i__, &z__1, &a[(i__ + 1) * a_dim1 + 1], &c__1, & tau[1], &c__1, &a[a_offset], lda); } else { i__1 = i__ + i__ * a_dim1; i__2 = i__ + i__ * a_dim1; d__1 = a[i__2].r; a[i__1].r = d__1, a[i__1].i = 0.; } i__1 = i__ + (i__ + 1) * a_dim1; i__2 = i__; a[i__1].r = e[i__2], a[i__1].i = 0.; i__1 = i__ + 1; i__2 = i__ + 1 + (i__ + 1) * a_dim1; d__[i__1] = a[i__2].r; i__1 = i__; tau[i__1].r = taui.r, tau[i__1].i = taui.i; /* L10: */ } i__1 = a_dim1 + 1; d__[1] = a[i__1].r; } else { /* Reduce the lower triangle of A */ i__1 = a_dim1 + 1; i__2 = a_dim1 + 1; d__1 = a[i__2].r; a[i__1].r = d__1, a[i__1].i = 0.; i__1 = *n - 1; for (i__ = 1; i__ <= i__1; ++i__) { /* Generate elementary reflector H(i) = I - tau * v * v' to annihilate A(i+2:n,i) */ i__2 = i__ + 1 + i__ * a_dim1; alpha.r = a[i__2].r, alpha.i = a[i__2].i; i__2 = *n - i__; /* Computing MIN */ i__3 = i__ + 2; zlarfg_(&i__2, &alpha, &a[min(i__3,*n) + i__ * a_dim1], &c__1, & taui); i__2 = i__; e[i__2] = alpha.r; if ((taui.r != 0.) || (taui.i != 0.)) { /* Apply H(i) from both sides to A(i+1:n,i+1:n) */ i__2 = i__ + 1 + i__ * a_dim1; a[i__2].r = 1., a[i__2].i = 0.; /* Compute x := tau * A * v storing y in TAU(i:n-1) */ i__2 = *n - i__; zhemv_(uplo, &i__2, &taui, &a[i__ + 1 + (i__ + 1) * a_dim1], lda, &a[i__ + 1 + i__ * a_dim1], &c__1, &c_b59, &tau[ i__], &c__1); /* Compute w := x - 1/2 * tau * (x'*v) * v */ z__3.r = -.5, z__3.i = -0.; z__2.r = z__3.r * taui.r - z__3.i * taui.i, z__2.i = z__3.r * taui.i + z__3.i * taui.r; i__2 = *n - i__; zdotc_(&z__4, &i__2, &tau[i__], &c__1, &a[i__ + 1 + i__ * a_dim1], &c__1); z__1.r = z__2.r * z__4.r - z__2.i * z__4.i, z__1.i = z__2.r * z__4.i + z__2.i * z__4.r; alpha.r = z__1.r, alpha.i = z__1.i; i__2 = *n - i__; zaxpy_(&i__2, &alpha, &a[i__ + 1 + i__ * a_dim1], &c__1, &tau[ i__], &c__1); /* Apply the transformation as a rank-2 update: A := A - v * w' - w * v' */ i__2 = *n - i__; z__1.r = -1., z__1.i = -0.; zher2_(uplo, &i__2, &z__1, &a[i__ + 1 + i__ * a_dim1], &c__1, &tau[i__], &c__1, &a[i__ + 1 + (i__ + 1) * a_dim1], lda); } else { i__2 = i__ + 1 + (i__ + 1) * a_dim1; i__3 = i__ + 1 + (i__ + 1) * a_dim1; d__1 = a[i__3].r; a[i__2].r = d__1, a[i__2].i = 0.; } i__2 = i__ + 1 + i__ * a_dim1; i__3 = i__; a[i__2].r = e[i__3], a[i__2].i = 0.; i__2 = i__; i__3 = i__ + i__ * a_dim1; d__[i__2] = a[i__3].r; i__2 = i__; tau[i__2].r = taui.r, tau[i__2].i = taui.i; /* L20: */ } i__1 = *n; i__2 = *n + *n * a_dim1; d__[i__1] = a[i__2].r; } return 0; /* End of ZHETD2 */ } /* zhetd2_ */ /* Subroutine */ int zhetrd_(char *uplo, integer *n, doublecomplex *a, integer *lda, doublereal *d__, doublereal *e, doublecomplex *tau, doublecomplex *work, integer *lwork, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3, i__4, i__5; doublecomplex z__1; /* Local variables */ static integer i__, j, nb, kk, nx, iws; extern logical lsame_(char *, char *); static integer nbmin, iinfo; static logical upper; extern /* Subroutine */ int zhetd2_(char *, integer *, doublecomplex *, integer *, doublereal *, doublereal *, doublecomplex *, integer *), zher2k_(char *, char *, integer *, integer *, doublecomplex *, doublecomplex *, integer *, doublecomplex *, integer *, doublereal *, doublecomplex *, integer *), xerbla_(char *, integer *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); extern /* Subroutine */ int zlatrd_(char *, integer *, integer *, doublecomplex *, integer *, doublereal *, doublecomplex *, doublecomplex *, integer *); static integer ldwork, lwkopt; static logical lquery; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= ZHETRD reduces a complex Hermitian matrix A to real symmetric tridiagonal form T by a unitary similarity transformation: Q**H * A * Q = T. Arguments ========= UPLO (input) CHARACTER*1 = 'U': Upper triangle of A is stored; = 'L': Lower triangle of A is stored. N (input) INTEGER The order of the matrix A. N >= 0. 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, and the strictly lower triangular part of A is not referenced. If UPLO = 'L', the leading N-by-N lower triangular part of A contains the lower triangular part of the matrix A, and the strictly upper triangular part of A is not referenced. On exit, if UPLO = 'U', the diagonal and first superdiagonal of A are overwritten by the corresponding elements of the tridiagonal matrix T, and the elements above the first superdiagonal, with the array TAU, represent the unitary matrix Q as a product of elementary reflectors; if UPLO = 'L', the diagonal and first subdiagonal of A are over- written by the corresponding elements of the tridiagonal matrix T, and the elements below the first subdiagonal, with the array TAU, represent the unitary matrix Q as a product of elementary reflectors. See Further Details. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,N). D (output) DOUBLE PRECISION array, dimension (N) The diagonal elements of the tridiagonal matrix T: D(i) = A(i,i). E (output) DOUBLE PRECISION array, dimension (N-1) The off-diagonal elements of the tridiagonal matrix T: E(i) = A(i,i+1) if UPLO = 'U', E(i) = A(i+1,i) if UPLO = 'L'. TAU (output) COMPLEX*16 array, dimension (N-1) The scalar factors of the elementary reflectors (see Further Details). WORK (workspace/output) COMPLEX*16 array, dimension (LWORK) On exit, if INFO = 0, WORK(1) returns the optimal LWORK. LWORK (input) INTEGER The dimension of the array WORK. LWORK >= 1. For optimum performance LWORK >= N*NB, where NB is the optimal blocksize. If LWORK = -1, then a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued by XERBLA. INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value Further Details =============== If UPLO = 'U', the matrix Q is represented as a product of elementary reflectors Q = H(n-1) . . . H(2) H(1). Each H(i) has the form H(i) = I - tau * v * v' where tau is a complex scalar, and v is a complex vector with v(i+1:n) = 0 and v(i) = 1; v(1:i-1) is stored on exit in A(1:i-1,i+1), and tau in TAU(i). If UPLO = 'L', the matrix Q is represented as a product of elementary reflectors Q = H(1) H(2) . . . H(n-1). Each H(i) has the form H(i) = I - tau * v * v' where tau is a complex scalar, and v is a complex vector with v(1:i) = 0 and v(i+1) = 1; v(i+2:n) is stored on exit in A(i+2:n,i), and tau in TAU(i). The contents of A on exit are illustrated by the following examples with n = 5: if UPLO = 'U': if UPLO = 'L': ( d e v2 v3 v4 ) ( d ) ( d e v3 v4 ) ( e d ) ( d e v4 ) ( v1 e d ) ( d e ) ( v1 v2 e d ) ( d ) ( v1 v2 v3 e d ) where d and e denote diagonal and off-diagonal elements of T, and vi denotes an element of the vector defining H(i). ===================================================================== Test the input parameters */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --d__; --e; --tau; --work; /* Function Body */ *info = 0; upper = lsame_(uplo, "U"); lquery = *lwork == -1; if (! upper && ! lsame_(uplo, "L")) { *info = -1; } else if (*n < 0) { *info = -2; } else if (*lda < max(1,*n)) { *info = -4; } else if (*lwork < 1 && ! lquery) { *info = -9; } if (*info == 0) { /* Determine the block size. */ nb = ilaenv_(&c__1, "ZHETRD", uplo, n, &c_n1, &c_n1, &c_n1, (ftnlen)6, (ftnlen)1); lwkopt = *n * nb; work[1].r = (doublereal) lwkopt, work[1].i = 0.; } if (*info != 0) { i__1 = -(*info); xerbla_("ZHETRD", &i__1); return 0; } else if (lquery) { return 0; } /* Quick return if possible */ if (*n == 0) { work[1].r = 1., work[1].i = 0.; return 0; } nx = *n; iws = 1; if (nb > 1 && nb < *n) { /* Determine when to cross over from blocked to unblocked code (last block is always handled by unblocked code). Computing MAX */ i__1 = nb, i__2 = ilaenv_(&c__3, "ZHETRD", uplo, n, &c_n1, &c_n1, & c_n1, (ftnlen)6, (ftnlen)1); nx = max(i__1,i__2); if (nx < *n) { /* Determine if workspace is large enough for blocked code. */ ldwork = *n; iws = ldwork * nb; if (*lwork < iws) { /* Not enough workspace to use optimal NB: determine the minimum value of NB, and reduce NB or force use of unblocked code by setting NX = N. Computing MAX */ i__1 = *lwork / ldwork; nb = max(i__1,1); nbmin = ilaenv_(&c__2, "ZHETRD", uplo, n, &c_n1, &c_n1, &c_n1, (ftnlen)6, (ftnlen)1); if (nb < nbmin) { nx = *n; } } } else { nx = *n; } } else { nb = 1; } if (upper) { /* Reduce the upper triangle of A. Columns 1:kk are handled by the unblocked method. */ kk = *n - (*n - nx + nb - 1) / nb * nb; i__1 = kk + 1; i__2 = -nb; for (i__ = *n - nb + 1; i__2 < 0 ? i__ >= i__1 : i__ <= i__1; i__ += i__2) { /* Reduce columns i:i+nb-1 to tridiagonal form and form the matrix W which is needed to update the unreduced part of the matrix */ i__3 = i__ + nb - 1; zlatrd_(uplo, &i__3, &nb, &a[a_offset], lda, &e[1], &tau[1], & work[1], &ldwork); /* Update the unreduced submatrix A(1:i-1,1:i-1), using an update of the form: A := A - V*W' - W*V' */ i__3 = i__ - 1; z__1.r = -1., z__1.i = -0.; zher2k_(uplo, "No transpose", &i__3, &nb, &z__1, &a[i__ * a_dim1 + 1], lda, &work[1], &ldwork, &c_b1015, &a[a_offset], lda); /* Copy superdiagonal elements back into A, and diagonal elements into D */ i__3 = i__ + nb - 1; for (j = i__; j <= i__3; ++j) { i__4 = j - 1 + j * a_dim1; i__5 = j - 1; a[i__4].r = e[i__5], a[i__4].i = 0.; i__4 = j; i__5 = j + j * a_dim1; d__[i__4] = a[i__5].r; /* L10: */ } /* L20: */ } /* Use unblocked code to reduce the last or only block */ zhetd2_(uplo, &kk, &a[a_offset], lda, &d__[1], &e[1], &tau[1], &iinfo); } else { /* Reduce the lower triangle of A */ i__2 = *n - nx; i__1 = nb; for (i__ = 1; i__1 < 0 ? i__ >= i__2 : i__ <= i__2; i__ += i__1) { /* Reduce columns i:i+nb-1 to tridiagonal form and form the matrix W which is needed to update the unreduced part of the matrix */ i__3 = *n - i__ + 1; zlatrd_(uplo, &i__3, &nb, &a[i__ + i__ * a_dim1], lda, &e[i__], & tau[i__], &work[1], &ldwork); /* Update the unreduced submatrix A(i+nb:n,i+nb:n), using an update of the form: A := A - V*W' - W*V' */ i__3 = *n - i__ - nb + 1; z__1.r = -1., z__1.i = -0.; zher2k_(uplo, "No transpose", &i__3, &nb, &z__1, &a[i__ + nb + i__ * a_dim1], lda, &work[nb + 1], &ldwork, &c_b1015, &a[ i__ + nb + (i__ + nb) * a_dim1], lda); /* Copy subdiagonal elements back into A, and diagonal elements into D */ i__3 = i__ + nb - 1; for (j = i__; j <= i__3; ++j) { i__4 = j + 1 + j * a_dim1; i__5 = j; a[i__4].r = e[i__5], a[i__4].i = 0.; i__4 = j; i__5 = j + j * a_dim1; d__[i__4] = a[i__5].r; /* L30: */ } /* L40: */ } /* Use unblocked code to reduce the last or only block */ i__1 = *n - i__ + 1; zhetd2_(uplo, &i__1, &a[i__ + i__ * a_dim1], lda, &d__[i__], &e[i__], &tau[i__], &iinfo); } work[1].r = (doublereal) lwkopt, work[1].i = 0.; return 0; /* End of ZHETRD */ } /* zhetrd_ */ /* Subroutine */ int zhseqr_(char *job, char *compz, integer *n, integer *ilo, integer *ihi, doublecomplex *h__, integer *ldh, doublecomplex *w, doublecomplex *z__, integer *ldz, doublecomplex *work, integer *lwork, integer *info) { /* System generated locals */ address a__1[2]; integer h_dim1, h_offset, z_dim1, z_offset, i__1, i__2, i__3, i__4[2], i__5, i__6; doublereal d__1, d__2, d__3, d__4; doublecomplex z__1; char ch__1[2]; /* Builtin functions */ double d_imag(doublecomplex *); void d_cnjg(doublecomplex *, doublecomplex *); /* Subroutine */ int s_cat(char *, char **, integer *, integer *, ftnlen); /* Local variables */ static integer i__, j, k, l; static doublecomplex s[225] /* was [15][15] */, v[16]; static integer i1, i2, ii, nh, nr, ns, nv; static doublecomplex vv[16]; static integer itn; static doublecomplex tau; static integer its; static doublereal ulp, tst1; static integer maxb, ierr; static doublereal unfl; static doublecomplex temp; static doublereal ovfl; extern logical lsame_(char *, char *); extern /* Subroutine */ int zscal_(integer *, doublecomplex *, doublecomplex *, integer *); static integer itemp; static doublereal rtemp; extern /* Subroutine */ int zgemv_(char *, integer *, integer *, doublecomplex *, doublecomplex *, integer *, doublecomplex *, integer *, doublecomplex *, doublecomplex *, integer *); static logical initz, wantt, wantz; static doublereal rwork[1]; extern /* Subroutine */ int zcopy_(integer *, doublecomplex *, integer *, doublecomplex *, integer *); extern doublereal dlapy2_(doublereal *, doublereal *); extern /* Subroutine */ int dlabad_(doublereal *, doublereal *); extern /* Subroutine */ int xerbla_(char *, integer *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); extern /* Subroutine */ int zdscal_(integer *, doublereal *, doublecomplex *, integer *), zlarfg_(integer *, doublecomplex *, doublecomplex *, integer *, doublecomplex *); extern integer izamax_(integer *, doublecomplex *, integer *); extern doublereal zlanhs_(char *, integer *, doublecomplex *, integer *, doublereal *); extern /* Subroutine */ int zlahqr_(logical *, logical *, integer *, integer *, integer *, doublecomplex *, integer *, doublecomplex *, integer *, integer *, doublecomplex *, integer *, integer *), zlacpy_(char *, integer *, integer *, doublecomplex *, integer *, doublecomplex *, integer *), zlaset_(char *, integer *, integer *, doublecomplex *, doublecomplex *, doublecomplex *, integer *), zlarfx_(char *, integer *, integer *, doublecomplex *, doublecomplex *, doublecomplex *, integer *, doublecomplex *); static doublereal smlnum; static logical lquery; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= ZHSEQR computes the eigenvalues of a complex upper Hessenberg matrix H, and, optionally, the matrices T and Z from the Schur decomposition H = Z T Z**H, where T is an upper triangular matrix (the Schur form), and Z is the unitary matrix of Schur vectors. Optionally Z may be postmultiplied into an input unitary matrix Q, so that this routine can give the Schur factorization of a matrix A which has been reduced to the Hessenberg form H by the unitary matrix Q: A = Q*H*Q**H = (QZ)*T*(QZ)**H. Arguments ========= JOB (input) CHARACTER*1 = 'E': compute eigenvalues only; = 'S': compute eigenvalues and the Schur form T. COMPZ (input) CHARACTER*1 = 'N': no Schur vectors are computed; = 'I': Z is initialized to the unit matrix and the matrix Z of Schur vectors of H is returned; = 'V': Z must contain an unitary matrix Q on entry, and the product Q*Z is returned. N (input) INTEGER The order of the matrix H. N >= 0. ILO (input) INTEGER IHI (input) INTEGER It is assumed that H is already upper triangular in rows and columns 1:ILO-1 and IHI+1:N. ILO and IHI are normally set by a previous call to ZGEBAL, and then passed to CGEHRD when the matrix output by ZGEBAL is reduced to Hessenberg form. Otherwise ILO and IHI should be set to 1 and N respectively. 1 <= ILO <= IHI <= N, if N > 0; ILO=1 and IHI=0, if N=0. H (input/output) COMPLEX*16 array, dimension (LDH,N) On entry, the upper Hessenberg matrix H. On exit, if JOB = 'S', H contains the upper triangular matrix T from the Schur decomposition (the Schur form). If JOB = 'E', the contents of H are unspecified on exit. LDH (input) INTEGER The leading dimension of the array H. LDH >= max(1,N). W (output) COMPLEX*16 array, dimension (N) The computed eigenvalues. If JOB = 'S', the eigenvalues are stored in the same order as on the diagonal of the Schur form returned in H, with W(i) = H(i,i). Z (input/output) COMPLEX*16 array, dimension (LDZ,N) If COMPZ = 'N': Z is not referenced. If COMPZ = 'I': on entry, Z need not be set, and on exit, Z contains the unitary matrix Z of the Schur vectors of H. If COMPZ = 'V': on entry Z must contain an N-by-N matrix Q, which is assumed to be equal to the unit matrix except for the submatrix Z(ILO:IHI,ILO:IHI); on exit Z contains Q*Z. Normally Q is the unitary matrix generated by ZUNGHR after the call to ZGEHRD which formed the Hessenberg matrix H. LDZ (input) INTEGER The leading dimension of the array Z. LDZ >= max(1,N) if COMPZ = 'I' or 'V'; LDZ >= 1 otherwise. WORK (workspace/output) COMPLEX*16 array, dimension (LWORK) On exit, if INFO = 0, WORK(1) returns the optimal LWORK. LWORK (input) INTEGER The dimension of the array WORK. LWORK >= max(1,N). If LWORK = -1, then a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued by XERBLA. INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value > 0: if INFO = i, ZHSEQR failed to compute all the eigenvalues in a total of 30*(IHI-ILO+1) iterations; elements 1:ilo-1 and i+1:n of W contain those eigenvalues which have been successfully computed. ===================================================================== Decode and test the input parameters */ /* Parameter adjustments */ h_dim1 = *ldh; h_offset = 1 + h_dim1; h__ -= h_offset; --w; z_dim1 = *ldz; z_offset = 1 + z_dim1; z__ -= z_offset; --work; /* Function Body */ wantt = lsame_(job, "S"); initz = lsame_(compz, "I"); wantz = (initz) || (lsame_(compz, "V")); *info = 0; i__1 = max(1,*n); work[1].r = (doublereal) i__1, work[1].i = 0.; lquery = *lwork == -1; if (! lsame_(job, "E") && ! wantt) { *info = -1; } else if (! lsame_(compz, "N") && ! wantz) { *info = -2; } else if (*n < 0) { *info = -3; } else if ((*ilo < 1) || (*ilo > max(1,*n))) { *info = -4; } else if ((*ihi < min(*ilo,*n)) || (*ihi > *n)) { *info = -5; } else if (*ldh < max(1,*n)) { *info = -7; } else if ((*ldz < 1) || (wantz && *ldz < max(1,*n))) { *info = -10; } else if (*lwork < max(1,*n) && ! lquery) { *info = -12; } if (*info != 0) { i__1 = -(*info); xerbla_("ZHSEQR", &i__1); return 0; } else if (lquery) { return 0; } /* Initialize Z, if necessary */ if (initz) { zlaset_("Full", n, n, &c_b59, &c_b60, &z__[z_offset], ldz); } /* Store the eigenvalues isolated by ZGEBAL. */ i__1 = *ilo - 1; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = i__; i__3 = i__ + i__ * h_dim1; w[i__2].r = h__[i__3].r, w[i__2].i = h__[i__3].i; /* L10: */ } i__1 = *n; for (i__ = *ihi + 1; i__ <= i__1; ++i__) { i__2 = i__; i__3 = i__ + i__ * h_dim1; w[i__2].r = h__[i__3].r, w[i__2].i = h__[i__3].i; /* L20: */ } /* Quick return if possible. */ if (*n == 0) { return 0; } if (*ilo == *ihi) { i__1 = *ilo; i__2 = *ilo + *ilo * h_dim1; w[i__1].r = h__[i__2].r, w[i__1].i = h__[i__2].i; return 0; } /* Set rows and columns ILO to IHI to zero below the first subdiagonal. */ i__1 = *ihi - 2; for (j = *ilo; j <= i__1; ++j) { i__2 = *n; for (i__ = j + 2; i__ <= i__2; ++i__) { i__3 = i__ + j * h_dim1; h__[i__3].r = 0., h__[i__3].i = 0.; /* L30: */ } /* L40: */ } nh = *ihi - *ilo + 1; /* I1 and I2 are the indices of the first row and last column of H to which transformations must be applied. If eigenvalues only are being computed, I1 and I2 are re-set inside the main loop. */ if (wantt) { i1 = 1; i2 = *n; } else { i1 = *ilo; i2 = *ihi; } /* Ensure that the subdiagonal elements are real. */ i__1 = *ihi; for (i__ = *ilo + 1; i__ <= i__1; ++i__) { i__2 = i__ + (i__ - 1) * h_dim1; temp.r = h__[i__2].r, temp.i = h__[i__2].i; if (d_imag(&temp) != 0.) { d__1 = temp.r; d__2 = d_imag(&temp); rtemp = dlapy2_(&d__1, &d__2); i__2 = i__ + (i__ - 1) * h_dim1; h__[i__2].r = rtemp, h__[i__2].i = 0.; z__1.r = temp.r / rtemp, z__1.i = temp.i / rtemp; temp.r = z__1.r, temp.i = z__1.i; if (i2 > i__) { i__2 = i2 - i__; d_cnjg(&z__1, &temp); zscal_(&i__2, &z__1, &h__[i__ + (i__ + 1) * h_dim1], ldh); } i__2 = i__ - i1; zscal_(&i__2, &temp, &h__[i1 + i__ * h_dim1], &c__1); if (i__ < *ihi) { i__2 = i__ + 1 + i__ * h_dim1; i__3 = i__ + 1 + i__ * h_dim1; z__1.r = temp.r * h__[i__3].r - temp.i * h__[i__3].i, z__1.i = temp.r * h__[i__3].i + temp.i * h__[i__3].r; h__[i__2].r = z__1.r, h__[i__2].i = z__1.i; } if (wantz) { zscal_(&nh, &temp, &z__[*ilo + i__ * z_dim1], &c__1); } } /* L50: */ } /* Determine the order of the multi-shift QR algorithm to be used. Writing concatenation */ i__4[0] = 1, a__1[0] = job; i__4[1] = 1, a__1[1] = compz; s_cat(ch__1, a__1, i__4, &c__2, (ftnlen)2); ns = ilaenv_(&c__4, "ZHSEQR", ch__1, n, ilo, ihi, &c_n1, (ftnlen)6, ( ftnlen)2); /* Writing concatenation */ i__4[0] = 1, a__1[0] = job; i__4[1] = 1, a__1[1] = compz; s_cat(ch__1, a__1, i__4, &c__2, (ftnlen)2); maxb = ilaenv_(&c__8, "ZHSEQR", ch__1, n, ilo, ihi, &c_n1, (ftnlen)6, ( ftnlen)2); if (((ns <= 1) || (ns > nh)) || (maxb >= nh)) { /* Use the standard double-shift algorithm */ zlahqr_(&wantt, &wantz, n, ilo, ihi, &h__[h_offset], ldh, &w[1], ilo, ihi, &z__[z_offset], ldz, info); return 0; } maxb = max(2,maxb); /* Computing MIN */ i__1 = min(ns,maxb); ns = min(i__1,15); /* Now 1 < NS <= MAXB < NH. Set machine-dependent constants for the stopping criterion. If norm(H) <= sqrt(OVFL), overflow should not occur. */ unfl = SAFEMINIMUM; ovfl = 1. / unfl; dlabad_(&unfl, &ovfl); ulp = PRECISION; smlnum = unfl * (nh / ulp); /* ITN is the total number of multiple-shift QR iterations allowed. */ itn = nh * 30; /* The main loop begins here. I is the loop index and decreases from IHI to ILO in steps of at most MAXB. Each iteration of the loop works with the active submatrix in rows and columns L to I. Eigenvalues I+1 to IHI have already converged. Either L = ILO, or H(L,L-1) is negligible so that the matrix splits. */ i__ = *ihi; L60: if (i__ < *ilo) { goto L180; } /* Perform multiple-shift QR iterations on rows and columns ILO to I until a submatrix of order at most MAXB splits off at the bottom because a subdiagonal element has become negligible. */ l = *ilo; i__1 = itn; for (its = 0; its <= i__1; ++its) { /* Look for a single small subdiagonal element. */ i__2 = l + 1; for (k = i__; k >= i__2; --k) { i__3 = k - 1 + (k - 1) * h_dim1; i__5 = k + k * h_dim1; tst1 = (d__1 = h__[i__3].r, abs(d__1)) + (d__2 = d_imag(&h__[k - 1 + (k - 1) * h_dim1]), abs(d__2)) + ((d__3 = h__[i__5].r, abs(d__3)) + (d__4 = d_imag(&h__[k + k * h_dim1]), abs( d__4))); if (tst1 == 0.) { i__3 = i__ - l + 1; tst1 = zlanhs_("1", &i__3, &h__[l + l * h_dim1], ldh, rwork); } i__3 = k + (k - 1) * h_dim1; /* Computing MAX */ d__2 = ulp * tst1; if ((d__1 = h__[i__3].r, abs(d__1)) <= max(d__2,smlnum)) { goto L80; } /* L70: */ } L80: l = k; if (l > *ilo) { /* H(L,L-1) is negligible. */ i__2 = l + (l - 1) * h_dim1; h__[i__2].r = 0., h__[i__2].i = 0.; } /* Exit from loop if a submatrix of order <= MAXB has split off. */ if (l >= i__ - maxb + 1) { goto L170; } /* Now the active submatrix is in rows and columns L to I. If eigenvalues only are being computed, only the active submatrix need be transformed. */ if (! wantt) { i1 = l; i2 = i__; } if ((its == 20) || (its == 30)) { /* Exceptional shifts. */ i__2 = i__; for (ii = i__ - ns + 1; ii <= i__2; ++ii) { i__3 = ii; i__5 = ii + (ii - 1) * h_dim1; i__6 = ii + ii * h_dim1; d__3 = ((d__1 = h__[i__5].r, abs(d__1)) + (d__2 = h__[i__6].r, abs(d__2))) * 1.5; w[i__3].r = d__3, w[i__3].i = 0.; /* L90: */ } } else { /* Use eigenvalues of trailing submatrix of order NS as shifts. */ zlacpy_("Full", &ns, &ns, &h__[i__ - ns + 1 + (i__ - ns + 1) * h_dim1], ldh, s, &c__15); zlahqr_(&c_false, &c_false, &ns, &c__1, &ns, s, &c__15, &w[i__ - ns + 1], &c__1, &ns, &z__[z_offset], ldz, &ierr); if (ierr > 0) { /* If ZLAHQR failed to compute all NS eigenvalues, use the unconverged diagonal elements as the remaining shifts. */ i__2 = ierr; for (ii = 1; ii <= i__2; ++ii) { i__3 = i__ - ns + ii; i__5 = ii + ii * 15 - 16; w[i__3].r = s[i__5].r, w[i__3].i = s[i__5].i; /* L100: */ } } } /* Form the first column of (G-w(1)) (G-w(2)) . . . (G-w(ns)) where G is the Hessenberg submatrix H(L:I,L:I) and w is the vector of shifts (stored in W). The result is stored in the local array V. */ v[0].r = 1., v[0].i = 0.; i__2 = ns + 1; for (ii = 2; ii <= i__2; ++ii) { i__3 = ii - 1; v[i__3].r = 0., v[i__3].i = 0.; /* L110: */ } nv = 1; i__2 = i__; for (j = i__ - ns + 1; j <= i__2; ++j) { i__3 = nv + 1; zcopy_(&i__3, v, &c__1, vv, &c__1); i__3 = nv + 1; i__5 = j; z__1.r = -w[i__5].r, z__1.i = -w[i__5].i; zgemv_("No transpose", &i__3, &nv, &c_b60, &h__[l + l * h_dim1], ldh, vv, &c__1, &z__1, v, &c__1); ++nv; /* Scale V(1:NV) so that max(abs(V(i))) = 1. If V is zero, reset it to the unit vector. */ itemp = izamax_(&nv, v, &c__1); i__3 = itemp - 1; rtemp = (d__1 = v[i__3].r, abs(d__1)) + (d__2 = d_imag(&v[itemp - 1]), abs(d__2)); if (rtemp == 0.) { v[0].r = 1., v[0].i = 0.; i__3 = nv; for (ii = 2; ii <= i__3; ++ii) { i__5 = ii - 1; v[i__5].r = 0., v[i__5].i = 0.; /* L120: */ } } else { rtemp = max(rtemp,smlnum); d__1 = 1. / rtemp; zdscal_(&nv, &d__1, v, &c__1); } /* L130: */ } /* Multiple-shift QR step */ i__2 = i__ - 1; for (k = l; k <= i__2; ++k) { /* The first iteration of this loop determines a reflection G from the vector V and applies it from left and right to H, thus creating a nonzero bulge below the subdiagonal. Each subsequent iteration determines a reflection G to restore the Hessenberg form in the (K-1)th column, and thus chases the bulge one step toward the bottom of the active submatrix. NR is the order of G. Computing MIN */ i__3 = ns + 1, i__5 = i__ - k + 1; nr = min(i__3,i__5); if (k > l) { zcopy_(&nr, &h__[k + (k - 1) * h_dim1], &c__1, v, &c__1); } zlarfg_(&nr, v, &v[1], &c__1, &tau); if (k > l) { i__3 = k + (k - 1) * h_dim1; h__[i__3].r = v[0].r, h__[i__3].i = v[0].i; i__3 = i__; for (ii = k + 1; ii <= i__3; ++ii) { i__5 = ii + (k - 1) * h_dim1; h__[i__5].r = 0., h__[i__5].i = 0.; /* L140: */ } } v[0].r = 1., v[0].i = 0.; /* Apply G' from the left to transform the rows of the matrix in columns K to I2. */ i__3 = i2 - k + 1; d_cnjg(&z__1, &tau); zlarfx_("Left", &nr, &i__3, v, &z__1, &h__[k + k * h_dim1], ldh, & work[1]); /* Apply G from the right to transform the columns of the matrix in rows I1 to min(K+NR,I). Computing MIN */ i__5 = k + nr; i__3 = min(i__5,i__) - i1 + 1; zlarfx_("Right", &i__3, &nr, v, &tau, &h__[i1 + k * h_dim1], ldh, &work[1]); if (wantz) { /* Accumulate transformations in the matrix Z */ zlarfx_("Right", &nh, &nr, v, &tau, &z__[*ilo + k * z_dim1], ldz, &work[1]); } /* L150: */ } /* Ensure that H(I,I-1) is real. */ i__2 = i__ + (i__ - 1) * h_dim1; temp.r = h__[i__2].r, temp.i = h__[i__2].i; if (d_imag(&temp) != 0.) { d__1 = temp.r; d__2 = d_imag(&temp); rtemp = dlapy2_(&d__1, &d__2); i__2 = i__ + (i__ - 1) * h_dim1; h__[i__2].r = rtemp, h__[i__2].i = 0.; z__1.r = temp.r / rtemp, z__1.i = temp.i / rtemp; temp.r = z__1.r, temp.i = z__1.i; if (i2 > i__) { i__2 = i2 - i__; d_cnjg(&z__1, &temp); zscal_(&i__2, &z__1, &h__[i__ + (i__ + 1) * h_dim1], ldh); } i__2 = i__ - i1; zscal_(&i__2, &temp, &h__[i1 + i__ * h_dim1], &c__1); if (wantz) { zscal_(&nh, &temp, &z__[*ilo + i__ * z_dim1], &c__1); } } /* L160: */ } /* Failure to converge in remaining number of iterations */ *info = i__; return 0; L170: /* A submatrix of order <= MAXB in rows and columns L to I has split off. Use the double-shift QR algorithm to handle it. */ zlahqr_(&wantt, &wantz, n, &l, &i__, &h__[h_offset], ldh, &w[1], ilo, ihi, &z__[z_offset], ldz, info); if (*info > 0) { return 0; } /* Decrement number of remaining iterations, and return to start of the main loop with a new value of I. */ itn -= its; i__ = l - 1; goto L60; L180: i__1 = max(1,*n); work[1].r = (doublereal) i__1, work[1].i = 0.; return 0; /* End of ZHSEQR */ } /* zhseqr_ */ /* Subroutine */ int zlabrd_(integer *m, integer *n, integer *nb, doublecomplex *a, integer *lda, doublereal *d__, doublereal *e, doublecomplex *tauq, doublecomplex *taup, doublecomplex *x, integer * ldx, doublecomplex *y, integer *ldy) { /* System generated locals */ integer a_dim1, a_offset, x_dim1, x_offset, y_dim1, y_offset, i__1, i__2, i__3; doublecomplex z__1; /* Local variables */ static integer i__; static doublecomplex alpha; extern /* Subroutine */ int zscal_(integer *, doublecomplex *, doublecomplex *, integer *), zgemv_(char *, integer *, integer *, doublecomplex *, doublecomplex *, integer *, doublecomplex *, integer *, doublecomplex *, doublecomplex *, integer *), zlarfg_(integer *, doublecomplex *, doublecomplex *, integer *, doublecomplex *), zlacgv_(integer *, doublecomplex *, integer *); /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University September 30, 1994 Purpose ======= ZLABRD reduces the first NB rows and columns of a complex general m by n matrix A to upper or lower real bidiagonal form by a unitary transformation Q' * A * P, and returns the matrices X and Y which are needed to apply the transformation to the unreduced part of A. If m >= n, A is reduced to upper bidiagonal form; if m < n, to lower bidiagonal form. This is an auxiliary routine called by ZGEBRD Arguments ========= M (input) INTEGER The number of rows in the matrix A. N (input) INTEGER The number of columns in the matrix A. NB (input) INTEGER The number of leading rows and columns of A to be reduced. A (input/output) COMPLEX*16 array, dimension (LDA,N) On entry, the m by n general matrix to be reduced. On exit, the first NB rows and columns of the matrix are overwritten; the rest of the array is unchanged. If m >= n, elements on and below the diagonal in the first NB columns, with the array TAUQ, represent the unitary matrix Q as a product of elementary reflectors; and elements above the diagonal in the first NB rows, with the array TAUP, represent the unitary matrix P as a product of elementary reflectors. If m < n, elements below the diagonal in the first NB columns, with the array TAUQ, represent the unitary matrix Q as a product of elementary reflectors, and elements on and above the diagonal in the first NB rows, with the array TAUP, represent the unitary matrix P as a product of elementary reflectors. See Further Details. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,M). D (output) DOUBLE PRECISION array, dimension (NB) The diagonal elements of the first NB rows and columns of the reduced matrix. D(i) = A(i,i). E (output) DOUBLE PRECISION array, dimension (NB) The off-diagonal elements of the first NB rows and columns of the reduced matrix. TAUQ (output) COMPLEX*16 array dimension (NB) The scalar factors of the elementary reflectors which represent the unitary matrix Q. See Further Details. TAUP (output) COMPLEX*16 array, dimension (NB) The scalar factors of the elementary reflectors which represent the unitary matrix P. See Further Details. X (output) COMPLEX*16 array, dimension (LDX,NB) The m-by-nb matrix X required to update the unreduced part of A. LDX (input) INTEGER The leading dimension of the array X. LDX >= max(1,M). Y (output) COMPLEX*16 array, dimension (LDY,NB) The n-by-nb matrix Y required to update the unreduced part of A. LDY (output) INTEGER The leading dimension of the array Y. LDY >= max(1,N). Further Details =============== The matrices Q and P are represented as products of elementary reflectors: Q = H(1) H(2) . . . H(nb) and P = G(1) G(2) . . . G(nb) Each H(i) and G(i) has the form: H(i) = I - tauq * v * v' and G(i) = I - taup * u * u' where tauq and taup are complex scalars, and v and u are complex vectors. If m >= n, v(1:i-1) = 0, v(i) = 1, and v(i:m) is stored on exit in A(i:m,i); u(1:i) = 0, u(i+1) = 1, and u(i+1:n) is stored on exit in A(i,i+1:n); tauq is stored in TAUQ(i) and taup in TAUP(i). If m < n, v(1:i) = 0, v(i+1) = 1, and v(i+1:m) is stored on exit in A(i+2:m,i); u(1:i-1) = 0, u(i) = 1, and u(i:n) is stored on exit in A(i,i+1:n); tauq is stored in TAUQ(i) and taup in TAUP(i). The elements of the vectors v and u together form the m-by-nb matrix V and the nb-by-n matrix U' which are needed, with X and Y, to apply the transformation to the unreduced part of the matrix, using a block update of the form: A := A - V*Y' - X*U'. The contents of A on exit are illustrated by the following examples with nb = 2: m = 6 and n = 5 (m > n): m = 5 and n = 6 (m < n): ( 1 1 u1 u1 u1 ) ( 1 u1 u1 u1 u1 u1 ) ( v1 1 1 u2 u2 ) ( 1 1 u2 u2 u2 u2 ) ( v1 v2 a a a ) ( v1 1 a a a a ) ( v1 v2 a a a ) ( v1 v2 a a a a ) ( v1 v2 a a a ) ( v1 v2 a a a a ) ( v1 v2 a a a ) where a denotes an element of the original matrix which is unchanged, vi denotes an element of the vector defining H(i), and ui an element of the vector defining G(i). ===================================================================== Quick return if possible */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --d__; --e; --tauq; --taup; x_dim1 = *ldx; x_offset = 1 + x_dim1; x -= x_offset; y_dim1 = *ldy; y_offset = 1 + y_dim1; y -= y_offset; /* Function Body */ if ((*m <= 0) || (*n <= 0)) { return 0; } if (*m >= *n) { /* Reduce to upper bidiagonal form */ i__1 = *nb; for (i__ = 1; i__ <= i__1; ++i__) { /* Update A(i:m,i) */ i__2 = i__ - 1; zlacgv_(&i__2, &y[i__ + y_dim1], ldy); i__2 = *m - i__ + 1; i__3 = i__ - 1; z__1.r = -1., z__1.i = -0.; zgemv_("No transpose", &i__2, &i__3, &z__1, &a[i__ + a_dim1], lda, &y[i__ + y_dim1], ldy, &c_b60, &a[i__ + i__ * a_dim1], & c__1); i__2 = i__ - 1; zlacgv_(&i__2, &y[i__ + y_dim1], ldy); i__2 = *m - i__ + 1; i__3 = i__ - 1; z__1.r = -1., z__1.i = -0.; zgemv_("No transpose", &i__2, &i__3, &z__1, &x[i__ + x_dim1], ldx, &a[i__ * a_dim1 + 1], &c__1, &c_b60, &a[i__ + i__ * a_dim1], &c__1); /* Generate reflection Q(i) to annihilate A(i+1:m,i) */ i__2 = i__ + i__ * a_dim1; alpha.r = a[i__2].r, alpha.i = a[i__2].i; i__2 = *m - i__ + 1; /* Computing MIN */ i__3 = i__ + 1; zlarfg_(&i__2, &alpha, &a[min(i__3,*m) + i__ * a_dim1], &c__1, & tauq[i__]); i__2 = i__; d__[i__2] = alpha.r; if (i__ < *n) { i__2 = i__ + i__ * a_dim1; a[i__2].r = 1., a[i__2].i = 0.; /* Compute Y(i+1:n,i) */ i__2 = *m - i__ + 1; i__3 = *n - i__; zgemv_("Conjugate transpose", &i__2, &i__3, &c_b60, &a[i__ + ( i__ + 1) * a_dim1], lda, &a[i__ + i__ * a_dim1], & c__1, &c_b59, &y[i__ + 1 + i__ * y_dim1], &c__1); i__2 = *m - i__ + 1; i__3 = i__ - 1; zgemv_("Conjugate transpose", &i__2, &i__3, &c_b60, &a[i__ + a_dim1], lda, &a[i__ + i__ * a_dim1], &c__1, &c_b59, & y[i__ * y_dim1 + 1], &c__1); i__2 = *n - i__; i__3 = i__ - 1; z__1.r = -1., z__1.i = -0.; zgemv_("No transpose", &i__2, &i__3, &z__1, &y[i__ + 1 + y_dim1], ldy, &y[i__ * y_dim1 + 1], &c__1, &c_b60, &y[ i__ + 1 + i__ * y_dim1], &c__1); i__2 = *m - i__ + 1; i__3 = i__ - 1; zgemv_("Conjugate transpose", &i__2, &i__3, &c_b60, &x[i__ + x_dim1], ldx, &a[i__ + i__ * a_dim1], &c__1, &c_b59, & y[i__ * y_dim1 + 1], &c__1); i__2 = i__ - 1; i__3 = *n - i__; z__1.r = -1., z__1.i = -0.; zgemv_("Conjugate transpose", &i__2, &i__3, &z__1, &a[(i__ + 1) * a_dim1 + 1], lda, &y[i__ * y_dim1 + 1], &c__1, & c_b60, &y[i__ + 1 + i__ * y_dim1], &c__1); i__2 = *n - i__; zscal_(&i__2, &tauq[i__], &y[i__ + 1 + i__ * y_dim1], &c__1); /* Update A(i,i+1:n) */ i__2 = *n - i__; zlacgv_(&i__2, &a[i__ + (i__ + 1) * a_dim1], lda); zlacgv_(&i__, &a[i__ + a_dim1], lda); i__2 = *n - i__; z__1.r = -1., z__1.i = -0.; zgemv_("No transpose", &i__2, &i__, &z__1, &y[i__ + 1 + y_dim1], ldy, &a[i__ + a_dim1], lda, &c_b60, &a[i__ + (i__ + 1) * a_dim1], lda); zlacgv_(&i__, &a[i__ + a_dim1], lda); i__2 = i__ - 1; zlacgv_(&i__2, &x[i__ + x_dim1], ldx); i__2 = i__ - 1; i__3 = *n - i__; z__1.r = -1., z__1.i = -0.; zgemv_("Conjugate transpose", &i__2, &i__3, &z__1, &a[(i__ + 1) * a_dim1 + 1], lda, &x[i__ + x_dim1], ldx, &c_b60, &a[i__ + (i__ + 1) * a_dim1], lda); i__2 = i__ - 1; zlacgv_(&i__2, &x[i__ + x_dim1], ldx); /* Generate reflection P(i) to annihilate A(i,i+2:n) */ i__2 = i__ + (i__ + 1) * a_dim1; alpha.r = a[i__2].r, alpha.i = a[i__2].i; i__2 = *n - i__; /* Computing MIN */ i__3 = i__ + 2; zlarfg_(&i__2, &alpha, &a[i__ + min(i__3,*n) * a_dim1], lda, & taup[i__]); i__2 = i__; e[i__2] = alpha.r; i__2 = i__ + (i__ + 1) * a_dim1; a[i__2].r = 1., a[i__2].i = 0.; /* Compute X(i+1:m,i) */ i__2 = *m - i__; i__3 = *n - i__; zgemv_("No transpose", &i__2, &i__3, &c_b60, &a[i__ + 1 + ( i__ + 1) * a_dim1], lda, &a[i__ + (i__ + 1) * a_dim1], lda, &c_b59, &x[i__ + 1 + i__ * x_dim1], &c__1); i__2 = *n - i__; zgemv_("Conjugate transpose", &i__2, &i__, &c_b60, &y[i__ + 1 + y_dim1], ldy, &a[i__ + (i__ + 1) * a_dim1], lda, & c_b59, &x[i__ * x_dim1 + 1], &c__1); i__2 = *m - i__; z__1.r = -1., z__1.i = -0.; zgemv_("No transpose", &i__2, &i__, &z__1, &a[i__ + 1 + a_dim1], lda, &x[i__ * x_dim1 + 1], &c__1, &c_b60, &x[ i__ + 1 + i__ * x_dim1], &c__1); i__2 = i__ - 1; i__3 = *n - i__; zgemv_("No transpose", &i__2, &i__3, &c_b60, &a[(i__ + 1) * a_dim1 + 1], lda, &a[i__ + (i__ + 1) * a_dim1], lda, & c_b59, &x[i__ * x_dim1 + 1], &c__1); i__2 = *m - i__; i__3 = i__ - 1; z__1.r = -1., z__1.i = -0.; zgemv_("No transpose", &i__2, &i__3, &z__1, &x[i__ + 1 + x_dim1], ldx, &x[i__ * x_dim1 + 1], &c__1, &c_b60, &x[ i__ + 1 + i__ * x_dim1], &c__1); i__2 = *m - i__; zscal_(&i__2, &taup[i__], &x[i__ + 1 + i__ * x_dim1], &c__1); i__2 = *n - i__; zlacgv_(&i__2, &a[i__ + (i__ + 1) * a_dim1], lda); } /* L10: */ } } else { /* Reduce to lower bidiagonal form */ i__1 = *nb; for (i__ = 1; i__ <= i__1; ++i__) { /* Update A(i,i:n) */ i__2 = *n - i__ + 1; zlacgv_(&i__2, &a[i__ + i__ * a_dim1], lda); i__2 = i__ - 1; zlacgv_(&i__2, &a[i__ + a_dim1], lda); i__2 = *n - i__ + 1; i__3 = i__ - 1; z__1.r = -1., z__1.i = -0.; zgemv_("No transpose", &i__2, &i__3, &z__1, &y[i__ + y_dim1], ldy, &a[i__ + a_dim1], lda, &c_b60, &a[i__ + i__ * a_dim1], lda); i__2 = i__ - 1; zlacgv_(&i__2, &a[i__ + a_dim1], lda); i__2 = i__ - 1; zlacgv_(&i__2, &x[i__ + x_dim1], ldx); i__2 = i__ - 1; i__3 = *n - i__ + 1; z__1.r = -1., z__1.i = -0.; zgemv_("Conjugate transpose", &i__2, &i__3, &z__1, &a[i__ * a_dim1 + 1], lda, &x[i__ + x_dim1], ldx, &c_b60, &a[i__ + i__ * a_dim1], lda); i__2 = i__ - 1; zlacgv_(&i__2, &x[i__ + x_dim1], ldx); /* Generate reflection P(i) to annihilate A(i,i+1:n) */ i__2 = i__ + i__ * a_dim1; alpha.r = a[i__2].r, alpha.i = a[i__2].i; i__2 = *n - i__ + 1; /* Computing MIN */ i__3 = i__ + 1; zlarfg_(&i__2, &alpha, &a[i__ + min(i__3,*n) * a_dim1], lda, & taup[i__]); i__2 = i__; d__[i__2] = alpha.r; if (i__ < *m) { i__2 = i__ + i__ * a_dim1; a[i__2].r = 1., a[i__2].i = 0.; /* Compute X(i+1:m,i) */ i__2 = *m - i__; i__3 = *n - i__ + 1; zgemv_("No transpose", &i__2, &i__3, &c_b60, &a[i__ + 1 + i__ * a_dim1], lda, &a[i__ + i__ * a_dim1], lda, &c_b59, & x[i__ + 1 + i__ * x_dim1], &c__1); i__2 = *n - i__ + 1; i__3 = i__ - 1; zgemv_("Conjugate transpose", &i__2, &i__3, &c_b60, &y[i__ + y_dim1], ldy, &a[i__ + i__ * a_dim1], lda, &c_b59, &x[ i__ * x_dim1 + 1], &c__1); i__2 = *m - i__; i__3 = i__ - 1; z__1.r = -1., z__1.i = -0.; zgemv_("No transpose", &i__2, &i__3, &z__1, &a[i__ + 1 + a_dim1], lda, &x[i__ * x_dim1 + 1], &c__1, &c_b60, &x[ i__ + 1 + i__ * x_dim1], &c__1); i__2 = i__ - 1; i__3 = *n - i__ + 1; zgemv_("No transpose", &i__2, &i__3, &c_b60, &a[i__ * a_dim1 + 1], lda, &a[i__ + i__ * a_dim1], lda, &c_b59, &x[ i__ * x_dim1 + 1], &c__1); i__2 = *m - i__; i__3 = i__ - 1; z__1.r = -1., z__1.i = -0.; zgemv_("No transpose", &i__2, &i__3, &z__1, &x[i__ + 1 + x_dim1], ldx, &x[i__ * x_dim1 + 1], &c__1, &c_b60, &x[ i__ + 1 + i__ * x_dim1], &c__1); i__2 = *m - i__; zscal_(&i__2, &taup[i__], &x[i__ + 1 + i__ * x_dim1], &c__1); i__2 = *n - i__ + 1; zlacgv_(&i__2, &a[i__ + i__ * a_dim1], lda); /* Update A(i+1:m,i) */ i__2 = i__ - 1; zlacgv_(&i__2, &y[i__ + y_dim1], ldy); i__2 = *m - i__; i__3 = i__ - 1; z__1.r = -1., z__1.i = -0.; zgemv_("No transpose", &i__2, &i__3, &z__1, &a[i__ + 1 + a_dim1], lda, &y[i__ + y_dim1], ldy, &c_b60, &a[i__ + 1 + i__ * a_dim1], &c__1); i__2 = i__ - 1; zlacgv_(&i__2, &y[i__ + y_dim1], ldy); i__2 = *m - i__; z__1.r = -1., z__1.i = -0.; zgemv_("No transpose", &i__2, &i__, &z__1, &x[i__ + 1 + x_dim1], ldx, &a[i__ * a_dim1 + 1], &c__1, &c_b60, &a[ i__ + 1 + i__ * a_dim1], &c__1); /* Generate reflection Q(i) to annihilate A(i+2:m,i) */ i__2 = i__ + 1 + i__ * a_dim1; alpha.r = a[i__2].r, alpha.i = a[i__2].i; i__2 = *m - i__; /* Computing MIN */ i__3 = i__ + 2; zlarfg_(&i__2, &alpha, &a[min(i__3,*m) + i__ * a_dim1], &c__1, &tauq[i__]); i__2 = i__; e[i__2] = alpha.r; i__2 = i__ + 1 + i__ * a_dim1; a[i__2].r = 1., a[i__2].i = 0.; /* Compute Y(i+1:n,i) */ i__2 = *m - i__; i__3 = *n - i__; zgemv_("Conjugate transpose", &i__2, &i__3, &c_b60, &a[i__ + 1 + (i__ + 1) * a_dim1], lda, &a[i__ + 1 + i__ * a_dim1], &c__1, &c_b59, &y[i__ + 1 + i__ * y_dim1], & c__1); i__2 = *m - i__; i__3 = i__ - 1; zgemv_("Conjugate transpose", &i__2, &i__3, &c_b60, &a[i__ + 1 + a_dim1], lda, &a[i__ + 1 + i__ * a_dim1], &c__1, & c_b59, &y[i__ * y_dim1 + 1], &c__1); i__2 = *n - i__; i__3 = i__ - 1; z__1.r = -1., z__1.i = -0.; zgemv_("No transpose", &i__2, &i__3, &z__1, &y[i__ + 1 + y_dim1], ldy, &y[i__ * y_dim1 + 1], &c__1, &c_b60, &y[ i__ + 1 + i__ * y_dim1], &c__1); i__2 = *m - i__; zgemv_("Conjugate transpose", &i__2, &i__, &c_b60, &x[i__ + 1 + x_dim1], ldx, &a[i__ + 1 + i__ * a_dim1], &c__1, & c_b59, &y[i__ * y_dim1 + 1], &c__1); i__2 = *n - i__; z__1.r = -1., z__1.i = -0.; zgemv_("Conjugate transpose", &i__, &i__2, &z__1, &a[(i__ + 1) * a_dim1 + 1], lda, &y[i__ * y_dim1 + 1], &c__1, & c_b60, &y[i__ + 1 + i__ * y_dim1], &c__1); i__2 = *n - i__; zscal_(&i__2, &tauq[i__], &y[i__ + 1 + i__ * y_dim1], &c__1); } else { i__2 = *n - i__ + 1; zlacgv_(&i__2, &a[i__ + i__ * a_dim1], lda); } /* L20: */ } } return 0; /* End of ZLABRD */ } /* zlabrd_ */ /* Subroutine */ int zlacgv_(integer *n, doublecomplex *x, integer *incx) { /* System generated locals */ integer i__1, i__2; doublecomplex z__1; /* Builtin functions */ void d_cnjg(doublecomplex *, doublecomplex *); /* Local variables */ static integer i__, ioff; /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University October 31, 1992 Purpose ======= ZLACGV conjugates a complex vector of length N. Arguments ========= N (input) INTEGER The length of the vector X. N >= 0. X (input/output) COMPLEX*16 array, dimension (1+(N-1)*abs(INCX)) On entry, the vector of length N to be conjugated. On exit, X is overwritten with conjg(X). INCX (input) INTEGER The spacing between successive elements of X. ===================================================================== */ /* Parameter adjustments */ --x; /* Function Body */ if (*incx == 1) { i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = i__; d_cnjg(&z__1, &x[i__]); x[i__2].r = z__1.r, x[i__2].i = z__1.i; /* L10: */ } } else { ioff = 1; if (*incx < 0) { ioff = 1 - (*n - 1) * *incx; } i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = ioff; d_cnjg(&z__1, &x[ioff]); x[i__2].r = z__1.r, x[i__2].i = z__1.i; ioff += *incx; /* L20: */ } } return 0; /* End of ZLACGV */ } /* zlacgv_ */ /* Subroutine */ int zlacp2_(char *uplo, integer *m, integer *n, doublereal * a, integer *lda, doublecomplex *b, integer *ldb) { /* System generated locals */ integer a_dim1, a_offset, b_dim1, b_offset, i__1, i__2, i__3, i__4; /* Local variables */ static integer i__, j; extern logical lsame_(char *, char *); /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= ZLACP2 copies all or part of a real two-dimensional matrix A to a complex matrix B. Arguments ========= UPLO (input) CHARACTER*1 Specifies the part of the matrix A to be copied to B. = 'U': Upper triangular part = 'L': Lower triangular part Otherwise: All of the matrix A M (input) INTEGER The number of rows of the matrix A. M >= 0. N (input) INTEGER The number of columns of the matrix A. N >= 0. A (input) DOUBLE PRECISION array, dimension (LDA,N) The m by n matrix A. If UPLO = 'U', only the upper trapezium is accessed; if UPLO = 'L', only the lower trapezium is accessed. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,M). B (output) COMPLEX*16 array, dimension (LDB,N) On exit, B = A in the locations specified by UPLO. LDB (input) INTEGER The leading dimension of the array B. LDB >= max(1,M). ===================================================================== */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; b_dim1 = *ldb; b_offset = 1 + b_dim1; b -= b_offset; /* Function Body */ if (lsame_(uplo, "U")) { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = min(j,*m); for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * b_dim1; i__4 = i__ + j * a_dim1; b[i__3].r = a[i__4], b[i__3].i = 0.; /* L10: */ } /* L20: */ } } else if (lsame_(uplo, "L")) { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = j; i__ <= i__2; ++i__) { i__3 = i__ + j * b_dim1; i__4 = i__ + j * a_dim1; b[i__3].r = a[i__4], b[i__3].i = 0.; /* L30: */ } /* L40: */ } } else { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * b_dim1; i__4 = i__ + j * a_dim1; b[i__3].r = a[i__4], b[i__3].i = 0.; /* L50: */ } /* L60: */ } } return 0; /* End of ZLACP2 */ } /* zlacp2_ */ /* Subroutine */ int zlacpy_(char *uplo, integer *m, integer *n, doublecomplex *a, integer *lda, doublecomplex *b, integer *ldb) { /* System generated locals */ integer a_dim1, a_offset, b_dim1, b_offset, i__1, i__2, i__3, i__4; /* Local variables */ static integer i__, j; extern logical lsame_(char *, char *); /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University February 29, 1992 Purpose ======= ZLACPY copies all or part of a two-dimensional matrix A to another matrix B. Arguments ========= UPLO (input) CHARACTER*1 Specifies the part of the matrix A to be copied to B. = 'U': Upper triangular part = 'L': Lower triangular part Otherwise: All of the matrix A M (input) INTEGER The number of rows of the matrix A. M >= 0. N (input) INTEGER The number of columns of the matrix A. N >= 0. A (input) COMPLEX*16 array, dimension (LDA,N) The m by n matrix A. If UPLO = 'U', only the upper trapezium is accessed; if UPLO = 'L', only the lower trapezium is accessed. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,M). B (output) COMPLEX*16 array, dimension (LDB,N) On exit, B = A in the locations specified by UPLO. LDB (input) INTEGER The leading dimension of the array B. LDB >= max(1,M). ===================================================================== */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; b_dim1 = *ldb; b_offset = 1 + b_dim1; b -= b_offset; /* Function Body */ if (lsame_(uplo, "U")) { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = min(j,*m); for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * b_dim1; i__4 = i__ + j * a_dim1; b[i__3].r = a[i__4].r, b[i__3].i = a[i__4].i; /* L10: */ } /* L20: */ } } else if (lsame_(uplo, "L")) { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = j; i__ <= i__2; ++i__) { i__3 = i__ + j * b_dim1; i__4 = i__ + j * a_dim1; b[i__3].r = a[i__4].r, b[i__3].i = a[i__4].i; /* L30: */ } /* L40: */ } } else { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * b_dim1; i__4 = i__ + j * a_dim1; b[i__3].r = a[i__4].r, b[i__3].i = a[i__4].i; /* L50: */ } /* L60: */ } } return 0; /* End of ZLACPY */ } /* zlacpy_ */ /* Subroutine */ int zlacrm_(integer *m, integer *n, doublecomplex *a, integer *lda, doublereal *b, integer *ldb, doublecomplex *c__, integer *ldc, doublereal *rwork) { /* System generated locals */ integer b_dim1, b_offset, a_dim1, a_offset, c_dim1, c_offset, i__1, i__2, i__3, i__4, i__5; doublereal d__1; doublecomplex z__1; /* Builtin functions */ double d_imag(doublecomplex *); /* Local variables */ static integer i__, j, l; extern /* Subroutine */ int dgemm_(char *, char *, integer *, integer *, integer *, doublereal *, doublereal *, integer *, doublereal *, integer *, doublereal *, doublereal *, integer *); /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University September 30, 1994 Purpose ======= ZLACRM performs a very simple matrix-matrix multiplication: C := A * B, where A is M by N and complex; B is N by N and real; C is M by N and complex. Arguments ========= M (input) INTEGER The number of rows of the matrix A and of the matrix C. M >= 0. N (input) INTEGER The number of columns and rows of the matrix B and the number of columns of the matrix C. N >= 0. A (input) COMPLEX*16 array, dimension (LDA, N) A contains the M by N matrix A. LDA (input) INTEGER The leading dimension of the array A. LDA >=max(1,M). B (input) DOUBLE PRECISION array, dimension (LDB, N) B contains the N by N matrix B. LDB (input) INTEGER The leading dimension of the array B. LDB >=max(1,N). C (input) COMPLEX*16 array, dimension (LDC, N) C contains the M by N matrix C. LDC (input) INTEGER The leading dimension of the array C. LDC >=max(1,N). RWORK (workspace) DOUBLE PRECISION array, dimension (2*M*N) ===================================================================== Quick return if possible. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; b_dim1 = *ldb; b_offset = 1 + b_dim1; b -= b_offset; c_dim1 = *ldc; c_offset = 1 + c_dim1; c__ -= c_offset; --rwork; /* Function Body */ if ((*m == 0) || (*n == 0)) { return 0; } i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * a_dim1; rwork[(j - 1) * *m + i__] = a[i__3].r; /* L10: */ } /* L20: */ } l = *m * *n + 1; dgemm_("N", "N", m, n, n, &c_b1015, &rwork[1], m, &b[b_offset], ldb, & c_b324, &rwork[l], m); i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * c_dim1; i__4 = l + (j - 1) * *m + i__ - 1; c__[i__3].r = rwork[i__4], c__[i__3].i = 0.; /* L30: */ } /* L40: */ } i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { rwork[(j - 1) * *m + i__] = d_imag(&a[i__ + j * a_dim1]); /* L50: */ } /* L60: */ } dgemm_("N", "N", m, n, n, &c_b1015, &rwork[1], m, &b[b_offset], ldb, & c_b324, &rwork[l], m); i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * c_dim1; i__4 = i__ + j * c_dim1; d__1 = c__[i__4].r; i__5 = l + (j - 1) * *m + i__ - 1; z__1.r = d__1, z__1.i = rwork[i__5]; c__[i__3].r = z__1.r, c__[i__3].i = z__1.i; /* L70: */ } /* L80: */ } return 0; /* End of ZLACRM */ } /* zlacrm_ */ /* Double Complex */ VOID zladiv_(doublecomplex * ret_val, doublecomplex *x, doublecomplex *y) { /* System generated locals */ doublereal d__1, d__2, d__3, d__4; doublecomplex z__1; /* Builtin functions */ double d_imag(doublecomplex *); /* Local variables */ static doublereal zi, zr; extern /* Subroutine */ int dladiv_(doublereal *, doublereal *, doublereal *, doublereal *, doublereal *, doublereal *); /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University October 31, 1992 Purpose ======= ZLADIV := X / Y, where X and Y are complex. The computation of X / Y will not overflow on an intermediary step unless the results overflows. Arguments ========= X (input) COMPLEX*16 Y (input) COMPLEX*16 The complex scalars X and Y. ===================================================================== */ d__1 = x->r; d__2 = d_imag(x); d__3 = y->r; d__4 = d_imag(y); dladiv_(&d__1, &d__2, &d__3, &d__4, &zr, &zi); z__1.r = zr, z__1.i = zi; ret_val->r = z__1.r, ret_val->i = z__1.i; return ; /* End of ZLADIV */ } /* zladiv_ */ /* Subroutine */ int zlaed0_(integer *qsiz, integer *n, doublereal *d__, doublereal *e, doublecomplex *q, integer *ldq, doublecomplex *qstore, integer *ldqs, doublereal *rwork, integer *iwork, integer *info) { /* System generated locals */ integer q_dim1, q_offset, qstore_dim1, qstore_offset, i__1, i__2; doublereal d__1; /* Builtin functions */ double log(doublereal); integer pow_ii(integer *, integer *); /* Local variables */ static integer i__, j, k, ll, iq, lgn, msd2, smm1, spm1, spm2; static doublereal temp; static integer curr, iperm; extern /* Subroutine */ int dcopy_(integer *, doublereal *, integer *, doublereal *, integer *); static integer indxq, iwrem, iqptr, tlvls; extern /* Subroutine */ int zcopy_(integer *, doublecomplex *, integer *, doublecomplex *, integer *), zlaed7_(integer *, integer *, integer *, integer *, integer *, integer *, doublereal *, doublecomplex *, integer *, doublereal *, integer *, doublereal *, integer *, integer *, integer *, integer *, integer *, doublereal *, doublecomplex *, doublereal *, integer *, integer *) ; static integer igivcl; extern /* Subroutine */ int xerbla_(char *, integer *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); extern /* Subroutine */ int zlacrm_(integer *, integer *, doublecomplex *, integer *, doublereal *, integer *, doublecomplex *, integer *, doublereal *); static integer igivnm, submat, curprb, subpbs, igivpt; extern /* Subroutine */ int dsteqr_(char *, integer *, doublereal *, doublereal *, doublereal *, integer *, doublereal *, integer *); static integer curlvl, matsiz, iprmpt, smlsiz; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University September 30, 1994 Purpose ======= Using the divide and conquer method, ZLAED0 computes all eigenvalues of a symmetric tridiagonal matrix which is one diagonal block of those from reducing a dense or band Hermitian matrix and corresponding eigenvectors of the dense or band matrix. Arguments ========= QSIZ (input) INTEGER The dimension of the unitary matrix used to reduce the full matrix to tridiagonal form. QSIZ >= N if ICOMPQ = 1. N (input) INTEGER The dimension of the symmetric tridiagonal matrix. N >= 0. D (input/output) DOUBLE PRECISION array, dimension (N) On entry, the diagonal elements of the tridiagonal matrix. On exit, the eigenvalues in ascending order. E (input/output) DOUBLE PRECISION array, dimension (N-1) On entry, the off-diagonal elements of the tridiagonal matrix. On exit, E has been destroyed. Q (input/output) COMPLEX*16 array, dimension (LDQ,N) On entry, Q must contain an QSIZ x N matrix whose columns unitarily orthonormal. It is a part of the unitary matrix that reduces the full dense Hermitian matrix to a (reducible) symmetric tridiagonal matrix. LDQ (input) INTEGER The leading dimension of the array Q. LDQ >= max(1,N). IWORK (workspace) INTEGER array, the dimension of IWORK must be at least 6 + 6*N + 5*N*lg N ( lg( N ) = smallest integer k such that 2^k >= N ) RWORK (workspace) DOUBLE PRECISION array, dimension (1 + 3*N + 2*N*lg N + 3*N**2) ( lg( N ) = smallest integer k such that 2^k >= N ) QSTORE (workspace) COMPLEX*16 array, dimension (LDQS, N) Used to store parts of the eigenvector matrix when the updating matrix multiplies take place. LDQS (input) INTEGER The leading dimension of the array QSTORE. LDQS >= max(1,N). INFO (output) INTEGER = 0: successful exit. < 0: if INFO = -i, the i-th argument had an illegal value. > 0: The algorithm failed to compute an eigenvalue while working on the submatrix lying in rows and columns INFO/(N+1) through mod(INFO,N+1). ===================================================================== Warning: N could be as big as QSIZ! Test the input parameters. */ /* Parameter adjustments */ --d__; --e; q_dim1 = *ldq; q_offset = 1 + q_dim1; q -= q_offset; qstore_dim1 = *ldqs; qstore_offset = 1 + qstore_dim1; qstore -= qstore_offset; --rwork; --iwork; /* Function Body */ *info = 0; /* IF( ICOMPQ .LT. 0 .OR. ICOMPQ .GT. 2 ) THEN INFO = -1 ELSE IF( ( ICOMPQ .EQ. 1 ) .AND. ( QSIZ .LT. MAX( 0, N ) ) ) $ THEN */ if (*qsiz < max(0,*n)) { *info = -1; } else if (*n < 0) { *info = -2; } else if (*ldq < max(1,*n)) { *info = -6; } else if (*ldqs < max(1,*n)) { *info = -8; } if (*info != 0) { i__1 = -(*info); xerbla_("ZLAED0", &i__1); return 0; } /* Quick return if possible */ if (*n == 0) { return 0; } smlsiz = ilaenv_(&c__9, "ZLAED0", " ", &c__0, &c__0, &c__0, &c__0, ( ftnlen)6, (ftnlen)1); /* Determine the size and placement of the submatrices, and save in the leading elements of IWORK. */ iwork[1] = *n; subpbs = 1; tlvls = 0; L10: if (iwork[subpbs] > smlsiz) { for (j = subpbs; j >= 1; --j) { iwork[j * 2] = (iwork[j] + 1) / 2; iwork[((j) << (1)) - 1] = iwork[j] / 2; /* L20: */ } ++tlvls; subpbs <<= 1; goto L10; } i__1 = subpbs; for (j = 2; j <= i__1; ++j) { iwork[j] += iwork[j - 1]; /* L30: */ } /* Divide the matrix into SUBPBS submatrices of size at most SMLSIZ+1 using rank-1 modifications (cuts). */ spm1 = subpbs - 1; i__1 = spm1; for (i__ = 1; i__ <= i__1; ++i__) { submat = iwork[i__] + 1; smm1 = submat - 1; d__[smm1] -= (d__1 = e[smm1], abs(d__1)); d__[submat] -= (d__1 = e[smm1], abs(d__1)); /* L40: */ } indxq = ((*n) << (2)) + 3; /* Set up workspaces for eigenvalues only/accumulate new vectors routine */ temp = log((doublereal) (*n)) / log(2.); lgn = (integer) temp; if (pow_ii(&c__2, &lgn) < *n) { ++lgn; } if (pow_ii(&c__2, &lgn) < *n) { ++lgn; } iprmpt = indxq + *n + 1; iperm = iprmpt + *n * lgn; iqptr = iperm + *n * lgn; igivpt = iqptr + *n + 2; igivcl = igivpt + *n * lgn; igivnm = 1; iq = igivnm + ((*n) << (1)) * lgn; /* Computing 2nd power */ i__1 = *n; iwrem = iq + i__1 * i__1 + 1; /* Initialize pointers */ i__1 = subpbs; for (i__ = 0; i__ <= i__1; ++i__) { iwork[iprmpt + i__] = 1; iwork[igivpt + i__] = 1; /* L50: */ } iwork[iqptr] = 1; /* Solve each submatrix eigenproblem at the bottom of the divide and conquer tree. */ curr = 0; i__1 = spm1; for (i__ = 0; i__ <= i__1; ++i__) { if (i__ == 0) { submat = 1; matsiz = iwork[1]; } else { submat = iwork[i__] + 1; matsiz = iwork[i__ + 1] - iwork[i__]; } ll = iq - 1 + iwork[iqptr + curr]; dsteqr_("I", &matsiz, &d__[submat], &e[submat], &rwork[ll], &matsiz, & rwork[1], info); zlacrm_(qsiz, &matsiz, &q[submat * q_dim1 + 1], ldq, &rwork[ll], & matsiz, &qstore[submat * qstore_dim1 + 1], ldqs, &rwork[iwrem] ); /* Computing 2nd power */ i__2 = matsiz; iwork[iqptr + curr + 1] = iwork[iqptr + curr] + i__2 * i__2; ++curr; if (*info > 0) { *info = submat * (*n + 1) + submat + matsiz - 1; return 0; } k = 1; i__2 = iwork[i__ + 1]; for (j = submat; j <= i__2; ++j) { iwork[indxq + j] = k; ++k; /* L60: */ } /* L70: */ } /* Successively merge eigensystems of adjacent submatrices into eigensystem for the corresponding larger matrix. while ( SUBPBS > 1 ) */ curlvl = 1; L80: if (subpbs > 1) { spm2 = subpbs - 2; i__1 = spm2; for (i__ = 0; i__ <= i__1; i__ += 2) { if (i__ == 0) { submat = 1; matsiz = iwork[2]; msd2 = iwork[1]; curprb = 0; } else { submat = iwork[i__] + 1; matsiz = iwork[i__ + 2] - iwork[i__]; msd2 = matsiz / 2; ++curprb; } /* Merge lower order eigensystems (of size MSD2 and MATSIZ - MSD2) into an eigensystem of size MATSIZ. ZLAED7 handles the case when the eigenvectors of a full or band Hermitian matrix (which was reduced to tridiagonal form) are desired. I am free to use Q as a valuable working space until Loop 150. */ zlaed7_(&matsiz, &msd2, qsiz, &tlvls, &curlvl, &curprb, &d__[ submat], &qstore[submat * qstore_dim1 + 1], ldqs, &e[ submat + msd2 - 1], &iwork[indxq + submat], &rwork[iq], & iwork[iqptr], &iwork[iprmpt], &iwork[iperm], &iwork[ igivpt], &iwork[igivcl], &rwork[igivnm], &q[submat * q_dim1 + 1], &rwork[iwrem], &iwork[subpbs + 1], info); if (*info > 0) { *info = submat * (*n + 1) + submat + matsiz - 1; return 0; } iwork[i__ / 2 + 1] = iwork[i__ + 2]; /* L90: */ } subpbs /= 2; ++curlvl; goto L80; } /* end while Re-merge the eigenvalues/vectors which were deflated at the final merge step. */ i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { j = iwork[indxq + i__]; rwork[i__] = d__[j]; zcopy_(qsiz, &qstore[j * qstore_dim1 + 1], &c__1, &q[i__ * q_dim1 + 1] , &c__1); /* L100: */ } dcopy_(n, &rwork[1], &c__1, &d__[1], &c__1); return 0; /* End of ZLAED0 */ } /* zlaed0_ */ /* Subroutine */ int zlaed7_(integer *n, integer *cutpnt, integer *qsiz, integer *tlvls, integer *curlvl, integer *curpbm, doublereal *d__, doublecomplex *q, integer *ldq, doublereal *rho, integer *indxq, doublereal *qstore, integer *qptr, integer *prmptr, integer *perm, integer *givptr, integer *givcol, doublereal *givnum, doublecomplex * work, doublereal *rwork, integer *iwork, integer *info) { /* System generated locals */ integer q_dim1, q_offset, i__1, i__2; /* Builtin functions */ integer pow_ii(integer *, integer *); /* Local variables */ static integer i__, k, n1, n2, iq, iw, iz, ptr, ind1, ind2, indx, curr, indxc, indxp; extern /* Subroutine */ int dlaed9_(integer *, integer *, integer *, integer *, doublereal *, doublereal *, integer *, doublereal *, doublereal *, doublereal *, doublereal *, integer *, integer *), zlaed8_(integer *, integer *, integer *, doublecomplex *, integer *, doublereal *, doublereal *, integer *, doublereal *, doublereal *, doublecomplex *, integer *, doublereal *, integer *, integer *, integer *, integer *, integer *, integer *, doublereal *, integer *), dlaeda_(integer *, integer *, integer *, integer *, integer *, integer *, integer *, integer *, doublereal *, doublereal *, integer *, doublereal *, doublereal *, integer *); static integer idlmda; extern /* Subroutine */ int dlamrg_(integer *, integer *, doublereal *, integer *, integer *, integer *), xerbla_(char *, integer *), zlacrm_(integer *, integer *, doublecomplex *, integer *, doublereal *, integer *, doublecomplex *, integer *, doublereal * ); static integer coltyp; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University September 30, 1994 Purpose ======= ZLAED7 computes the updated eigensystem of a diagonal matrix after modification by a rank-one symmetric matrix. This routine is used only for the eigenproblem which requires all eigenvalues and optionally eigenvectors of a dense or banded Hermitian matrix that has been reduced to tridiagonal form. T = Q(in) ( D(in) + RHO * Z*Z' ) Q'(in) = Q(out) * D(out) * Q'(out) where Z = Q'u, u is a vector of length N with ones in the CUTPNT and CUTPNT + 1 th elements and zeros elsewhere. The eigenvectors of the original matrix are stored in Q, and the eigenvalues are in D. The algorithm consists of three stages: The first stage consists of deflating the size of the problem when there are multiple eigenvalues or if there is a zero in the Z vector. For each such occurence the dimension of the secular equation problem is reduced by one. This stage is performed by the routine DLAED2. The second stage consists of calculating the updated eigenvalues. This is done by finding the roots of the secular equation via the routine DLAED4 (as called by SLAED3). This routine also calculates the eigenvectors of the current problem. The final stage consists of computing the updated eigenvectors directly using the updated eigenvalues. The eigenvectors for the current problem are multiplied with the eigenvectors from the overall problem. Arguments ========= N (input) INTEGER The dimension of the symmetric tridiagonal matrix. N >= 0. CUTPNT (input) INTEGER Contains the location of the last eigenvalue in the leading sub-matrix. min(1,N) <= CUTPNT <= N. QSIZ (input) INTEGER The dimension of the unitary matrix used to reduce the full matrix to tridiagonal form. QSIZ >= N. TLVLS (input) INTEGER The total number of merging levels in the overall divide and conquer tree. CURLVL (input) INTEGER The current level in the overall merge routine, 0 <= curlvl <= tlvls. CURPBM (input) INTEGER The current problem in the current level in the overall merge routine (counting from upper left to lower right). D (input/output) DOUBLE PRECISION array, dimension (N) On entry, the eigenvalues of the rank-1-perturbed matrix. On exit, the eigenvalues of the repaired matrix. Q (input/output) COMPLEX*16 array, dimension (LDQ,N) On entry, the eigenvectors of the rank-1-perturbed matrix. On exit, the eigenvectors of the repaired tridiagonal matrix. LDQ (input) INTEGER The leading dimension of the array Q. LDQ >= max(1,N). RHO (input) DOUBLE PRECISION Contains the subdiagonal element used to create the rank-1 modification. INDXQ (output) INTEGER array, dimension (N) This contains the permutation which will reintegrate the subproblem just solved back into sorted order, ie. D( INDXQ( I = 1, N ) ) will be in ascending order. IWORK (workspace) INTEGER array, dimension (4*N) RWORK (workspace) DOUBLE PRECISION array, dimension (3*N+2*QSIZ*N) WORK (workspace) COMPLEX*16 array, dimension (QSIZ*N) QSTORE (input/output) DOUBLE PRECISION array, dimension (N**2+1) Stores eigenvectors of submatrices encountered during divide and conquer, packed together. QPTR points to beginning of the submatrices. QPTR (input/output) INTEGER array, dimension (N+2) List of indices pointing to beginning of submatrices stored in QSTORE. The submatrices are numbered starting at the bottom left of the divide and conquer tree, from left to right and bottom to top. PRMPTR (input) INTEGER array, dimension (N lg N) Contains a list of pointers which indicate where in PERM a level's permutation is stored. PRMPTR(i+1) - PRMPTR(i) indicates the size of the permutation and also the size of the full, non-deflated problem. PERM (input) INTEGER array, dimension (N lg N) Contains the permutations (from deflation and sorting) to be applied to each eigenblock. GIVPTR (input) INTEGER array, dimension (N lg N) Contains a list of pointers which indicate where in GIVCOL a level's Givens rotations are stored. GIVPTR(i+1) - GIVPTR(i) indicates the number of Givens rotations. GIVCOL (input) INTEGER array, dimension (2, N lg N) Each pair of numbers indicates a pair of columns to take place in a Givens rotation. GIVNUM (input) DOUBLE PRECISION array, dimension (2, N lg N) Each number indicates the S value to be used in the corresponding Givens rotation. INFO (output) INTEGER = 0: successful exit. < 0: if INFO = -i, the i-th argument had an illegal value. > 0: if INFO = 1, an eigenvalue did not converge ===================================================================== Test the input parameters. */ /* Parameter adjustments */ --d__; q_dim1 = *ldq; q_offset = 1 + q_dim1; q -= q_offset; --indxq; --qstore; --qptr; --prmptr; --perm; --givptr; givcol -= 3; givnum -= 3; --work; --rwork; --iwork; /* Function Body */ *info = 0; /* IF( ICOMPQ.LT.0 .OR. ICOMPQ.GT.1 ) THEN INFO = -1 ELSE IF( N.LT.0 ) THEN */ if (*n < 0) { *info = -1; } else if ((min(1,*n) > *cutpnt) || (*n < *cutpnt)) { *info = -2; } else if (*qsiz < *n) { *info = -3; } else if (*ldq < max(1,*n)) { *info = -9; } if (*info != 0) { i__1 = -(*info); xerbla_("ZLAED7", &i__1); return 0; } /* Quick return if possible */ if (*n == 0) { return 0; } /* The following values are for bookkeeping purposes only. They are integer pointers which indicate the portion of the workspace used by a particular array in DLAED2 and SLAED3. */ iz = 1; idlmda = iz + *n; iw = idlmda + *n; iq = iw + *n; indx = 1; indxc = indx + *n; coltyp = indxc + *n; indxp = coltyp + *n; /* Form the z-vector which consists of the last row of Q_1 and the first row of Q_2. */ ptr = pow_ii(&c__2, tlvls) + 1; i__1 = *curlvl - 1; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = *tlvls - i__; ptr += pow_ii(&c__2, &i__2); /* L10: */ } curr = ptr + *curpbm; dlaeda_(n, tlvls, curlvl, curpbm, &prmptr[1], &perm[1], &givptr[1], & givcol[3], &givnum[3], &qstore[1], &qptr[1], &rwork[iz], &rwork[ iz + *n], info); /* When solving the final problem, we no longer need the stored data, so we will overwrite the data from this level onto the previously used storage space. */ if (*curlvl == *tlvls) { qptr[curr] = 1; prmptr[curr] = 1; givptr[curr] = 1; } /* Sort and Deflate eigenvalues. */ zlaed8_(&k, n, qsiz, &q[q_offset], ldq, &d__[1], rho, cutpnt, &rwork[iz], &rwork[idlmda], &work[1], qsiz, &rwork[iw], &iwork[indxp], &iwork[ indx], &indxq[1], &perm[prmptr[curr]], &givptr[curr + 1], &givcol[ ((givptr[curr]) << (1)) + 1], &givnum[((givptr[curr]) << (1)) + 1] , info); prmptr[curr + 1] = prmptr[curr] + *n; givptr[curr + 1] += givptr[curr]; /* Solve Secular Equation. */ if (k != 0) { dlaed9_(&k, &c__1, &k, n, &d__[1], &rwork[iq], &k, rho, &rwork[idlmda] , &rwork[iw], &qstore[qptr[curr]], &k, info); zlacrm_(qsiz, &k, &work[1], qsiz, &qstore[qptr[curr]], &k, &q[ q_offset], ldq, &rwork[iq]); /* Computing 2nd power */ i__1 = k; qptr[curr + 1] = qptr[curr] + i__1 * i__1; if (*info != 0) { return 0; } /* Prepare the INDXQ sorting premutation. */ n1 = k; n2 = *n - k; ind1 = 1; ind2 = *n; dlamrg_(&n1, &n2, &d__[1], &c__1, &c_n1, &indxq[1]); } else { qptr[curr + 1] = qptr[curr]; i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { indxq[i__] = i__; /* L20: */ } } return 0; /* End of ZLAED7 */ } /* zlaed7_ */ /* Subroutine */ int zlaed8_(integer *k, integer *n, integer *qsiz, doublecomplex *q, integer *ldq, doublereal *d__, doublereal *rho, integer *cutpnt, doublereal *z__, doublereal *dlamda, doublecomplex * q2, integer *ldq2, doublereal *w, integer *indxp, integer *indx, integer *indxq, integer *perm, integer *givptr, integer *givcol, doublereal *givnum, integer *info) { /* System generated locals */ integer q_dim1, q_offset, q2_dim1, q2_offset, i__1; doublereal d__1; /* Builtin functions */ double sqrt(doublereal); /* Local variables */ static doublereal c__; static integer i__, j; static doublereal s, t; static integer k2, n1, n2, jp, n1p1; static doublereal eps, tau, tol; static integer jlam, imax, jmax; extern /* Subroutine */ int dscal_(integer *, doublereal *, doublereal *, integer *), dcopy_(integer *, doublereal *, integer *, doublereal *, integer *), zdrot_(integer *, doublecomplex *, integer *, doublecomplex *, integer *, doublereal *, doublereal *), zcopy_( integer *, doublecomplex *, integer *, doublecomplex *, integer *) ; extern integer idamax_(integer *, doublereal *, integer *); extern /* Subroutine */ int dlamrg_(integer *, integer *, doublereal *, integer *, integer *, integer *), xerbla_(char *, integer *), zlacpy_(char *, integer *, integer *, doublecomplex *, integer *, doublecomplex *, integer *); /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Oak Ridge National Lab, Argonne National Lab, Courant Institute, NAG Ltd., and Rice University September 30, 1994 Purpose ======= ZLAED8 merges the two sets of eigenvalues together into a single sorted set. Then it tries to deflate the size of the problem. There are two ways in which deflation can occur: when two or more eigenvalues are close together or if there is a tiny element in the Z vector. For each such occurrence the order of the related secular equation problem is reduced by one. Arguments ========= K (output) INTEGER Contains the number of non-deflated eigenvalues. This is the order of the related secular equation. N (input) INTEGER The dimension of the symmetric tridiagonal matrix. N >= 0. QSIZ (input) INTEGER The dimension of the unitary matrix used to reduce the dense or band matrix to tridiagonal form. QSIZ >= N if ICOMPQ = 1. Q (input/output) COMPLEX*16 array, dimension (LDQ,N) On entry, Q contains the eigenvectors of the partially solved system which has been previously updated in matrix multiplies with other partially solved eigensystems. On exit, Q contains the trailing (N-K) updated eigenvectors (those which were deflated) in its last N-K columns. LDQ (input) INTEGER The leading dimension of the array Q. LDQ >= max( 1, N ). D (input/output) DOUBLE PRECISION array, dimension (N) On entry, D contains the eigenvalues of the two submatrices to be combined. On exit, D contains the trailing (N-K) updated eigenvalues (those which were deflated) sorted into increasing order. RHO (input/output) DOUBLE PRECISION Contains the off diagonal element associated with the rank-1 cut which originally split the two submatrices which are now being recombined. RHO is modified during the computation to the value required by DLAED3. CUTPNT (input) INTEGER Contains the location of the last eigenvalue in the leading sub-matrix. MIN(1,N) <= CUTPNT <= N. Z (input) DOUBLE PRECISION array, dimension (N) On input this vector contains the updating vector (the last row of the first sub-eigenvector matrix and the first row of the second sub-eigenvector matrix). The contents of Z are destroyed during the updating process. DLAMDA (output) DOUBLE PRECISION array, dimension (N) Contains a copy of the first K eigenvalues which will be used by DLAED3 to form the secular equation. Q2 (output) COMPLEX*16 array, dimension (LDQ2,N) If ICOMPQ = 0, Q2 is not referenced. Otherwise, Contains a copy of the first K eigenvectors which will be used by DLAED7 in a matrix multiply (DGEMM) to update the new eigenvectors. LDQ2 (input) INTEGER The leading dimension of the array Q2. LDQ2 >= max( 1, N ). W (output) DOUBLE PRECISION array, dimension (N) This will hold the first k values of the final deflation-altered z-vector and will be passed to DLAED3. INDXP (workspace) INTEGER array, dimension (N) This will contain the permutation used to place deflated values of D at the end of the array. On output INDXP(1:K) points to the nondeflated D-values and INDXP(K+1:N) points to the deflated eigenvalues. INDX (workspace) INTEGER array, dimension (N) This will contain the permutation used to sort the contents of D into ascending order. INDXQ (input) INTEGER array, dimension (N) This contains the permutation which separately sorts the two sub-problems in D into ascending order. Note that elements in the second half of this permutation must first have CUTPNT added to their values in order to be accurate. PERM (output) INTEGER array, dimension (N) Contains the permutations (from deflation and sorting) to be applied to each eigenblock. GIVPTR (output) INTEGER Contains the number of Givens rotations which took place in this subproblem. GIVCOL (output) INTEGER array, dimension (2, N) Each pair of numbers indicates a pair of columns to take place in a Givens rotation. GIVNUM (output) DOUBLE PRECISION array, dimension (2, N) Each number indicates the S value to be used in the corresponding Givens rotation. INFO (output) INTEGER = 0: successful exit. < 0: if INFO = -i, the i-th argument had an illegal value. ===================================================================== Test the input parameters. */ /* Parameter adjustments */ q_dim1 = *ldq; q_offset = 1 + q_dim1; q -= q_offset; --d__; --z__; --dlamda; q2_dim1 = *ldq2; q2_offset = 1 + q2_dim1; q2 -= q2_offset; --w; --indxp; --indx; --indxq; --perm; givcol -= 3; givnum -= 3; /* Function Body */ *info = 0; if (*n < 0) { *info = -2; } else if (*qsiz < *n) { *info = -3; } else if (*ldq < max(1,*n)) { *info = -5; } else if ((*cutpnt < min(1,*n)) || (*cutpnt > *n)) { *info = -8; } else if (*ldq2 < max(1,*n)) { *info = -12; } if (*info != 0) { i__1 = -(*info); xerbla_("ZLAED8", &i__1); return 0; } /* Quick return if possible */ if (*n == 0) { return 0; } n1 = *cutpnt; n2 = *n - n1; n1p1 = n1 + 1; if (*rho < 0.) { dscal_(&n2, &c_b1294, &z__[n1p1], &c__1); } /* Normalize z so that norm(z) = 1 */ t = 1. / sqrt(2.); i__1 = *n; for (j = 1; j <= i__1; ++j) { indx[j] = j; /* L10: */ } dscal_(n, &t, &z__[1], &c__1); *rho = (d__1 = *rho * 2., abs(d__1)); /* Sort the eigenvalues into increasing order */ i__1 = *n; for (i__ = *cutpnt + 1; i__ <= i__1; ++i__) { indxq[i__] += *cutpnt; /* L20: */ } i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { dlamda[i__] = d__[indxq[i__]]; w[i__] = z__[indxq[i__]]; /* L30: */ } i__ = 1; j = *cutpnt + 1; dlamrg_(&n1, &n2, &dlamda[1], &c__1, &c__1, &indx[1]); i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { d__[i__] = dlamda[indx[i__]]; z__[i__] = w[indx[i__]]; /* L40: */ } /* Calculate the allowable deflation tolerance */ imax = idamax_(n, &z__[1], &c__1); jmax = idamax_(n, &d__[1], &c__1); eps = EPSILON; tol = eps * 8. * (d__1 = d__[jmax], abs(d__1)); /* If the rank-1 modifier is small enough, no more needs to be done -- except to reorganize Q so that its columns correspond with the elements in D. */ if (*rho * (d__1 = z__[imax], abs(d__1)) <= tol) { *k = 0; i__1 = *n; for (j = 1; j <= i__1; ++j) { perm[j] = indxq[indx[j]]; zcopy_(qsiz, &q[perm[j] * q_dim1 + 1], &c__1, &q2[j * q2_dim1 + 1] , &c__1); /* L50: */ } zlacpy_("A", qsiz, n, &q2[q2_dim1 + 1], ldq2, &q[q_dim1 + 1], ldq); return 0; } /* If there are multiple eigenvalues then the problem deflates. Here the number of equal eigenvalues are found. As each equal eigenvalue is found, an elementary reflector is computed to rotate the corresponding eigensubspace so that the corresponding components of Z are zero in this new basis. */ *k = 0; *givptr = 0; k2 = *n + 1; i__1 = *n; for (j = 1; j <= i__1; ++j) { if (*rho * (d__1 = z__[j], abs(d__1)) <= tol) { /* Deflate due to small z component. */ --k2; indxp[k2] = j; if (j == *n) { goto L100; } } else { jlam = j; goto L70; } /* L60: */ } L70: ++j; if (j > *n) { goto L90; } if (*rho * (d__1 = z__[j], abs(d__1)) <= tol) { /* Deflate due to small z component. */ --k2; indxp[k2] = j; } else { /* Check if eigenvalues are close enough to allow deflation. */ s = z__[jlam]; c__ = z__[j]; /* Find sqrt(a**2+b**2) without overflow or destructive underflow. */ tau = dlapy2_(&c__, &s); t = d__[j] - d__[jlam]; c__ /= tau; s = -s / tau; if ((d__1 = t * c__ * s, abs(d__1)) <= tol) { /* Deflation is possible. */ z__[j] = tau; z__[jlam] = 0.; /* Record the appropriate Givens rotation */ ++(*givptr); givcol[((*givptr) << (1)) + 1] = indxq[indx[jlam]]; givcol[((*givptr) << (1)) + 2] = indxq[indx[j]]; givnum[((*givptr) << (1)) + 1] = c__; givnum[((*givptr) << (1)) + 2] = s; zdrot_(qsiz, &q[indxq[indx[jlam]] * q_dim1 + 1], &c__1, &q[indxq[ indx[j]] * q_dim1 + 1], &c__1, &c__, &s); t = d__[jlam] * c__ * c__ + d__[j] * s * s; d__[j] = d__[jlam] * s * s + d__[j] * c__ * c__; d__[jlam] = t; --k2; i__ = 1; L80: if (k2 + i__ <= *n) { if (d__[jlam] < d__[indxp[k2 + i__]]) { indxp[k2 + i__ - 1] = indxp[k2 + i__]; indxp[k2 + i__] = jlam; ++i__; goto L80; } else { indxp[k2 + i__ - 1] = jlam; } } else { indxp[k2 + i__ - 1] = jlam; } jlam = j; } else { ++(*k); w[*k] = z__[jlam]; dlamda[*k] = d__[jlam]; indxp[*k] = jlam; jlam = j; } } goto L70; L90: /* Record the last eigenvalue. */ ++(*k); w[*k] = z__[jlam]; dlamda[*k] = d__[jlam]; indxp[*k] = jlam; L100: /* Sort the eigenvalues and corresponding eigenvectors into DLAMDA and Q2 respectively. The eigenvalues/vectors which were not deflated go into the first K slots of DLAMDA and Q2 respectively, while those which were deflated go into the last N - K slots. */ i__1 = *n; for (j = 1; j <= i__1; ++j) { jp = indxp[j]; dlamda[j] = d__[jp]; perm[j] = indxq[indx[jp]]; zcopy_(qsiz, &q[perm[j] * q_dim1 + 1], &c__1, &q2[j * q2_dim1 + 1], & c__1); /* L110: */ } /* The deflated eigenvalues and their corresponding vectors go back into the last N - K slots of D and Q respectively. */ if (*k < *n) { i__1 = *n - *k; dcopy_(&i__1, &dlamda[*k + 1], &c__1, &d__[*k + 1], &c__1); i__1 = *n - *k; zlacpy_("A", qsiz, &i__1, &q2[(*k + 1) * q2_dim1 + 1], ldq2, &q[(*k + 1) * q_dim1 + 1], ldq); } return 0; /* End of ZLAED8 */ } /* zlaed8_ */ /* Subroutine */ int zlahqr_(logical *wantt, logical *wantz, integer *n, integer *ilo, integer *ihi, doublecomplex *h__, integer *ldh, doublecomplex *w, integer *iloz, integer *ihiz, doublecomplex *z__, integer *ldz, integer *info) { /* System generated locals */ integer h_dim1, h_offset, z_dim1, z_offset, i__1, i__2, i__3, i__4, i__5; doublereal d__1, d__2, d__3, d__4, d__5, d__6; doublecomplex z__1, z__2, z__3, z__4; /* Builtin functions */ double d_imag(doublecomplex *); void z_sqrt(doublecomplex *, doublecomplex *), d_cnjg(doublecomplex *, doublecomplex *); double z_abs(doublecomplex *); /* Local variables */ static integer i__, j, k, l, m; static doublereal s; static doublecomplex t, u, v[2], x, y; static integer i1, i2; static doublecomplex t1; static doublereal t2; static doublecomplex v2; static doublereal h10; static doublecomplex h11; static doublereal h21; static doublecomplex h22; static integer nh, nz; static doublecomplex h11s; static integer itn, its; static doublereal ulp; static doublecomplex sum; static doublereal tst1; static doublecomplex temp; extern /* Subroutine */ int zscal_(integer *, doublecomplex *, doublecomplex *, integer *); static doublereal rtemp, rwork[1]; extern /* Subroutine */ int zcopy_(integer *, doublecomplex *, integer *, doublecomplex *, integer *); extern /* Subroutine */ int zlarfg_(integer *, doublecomplex *, doublecomplex *, integer *, doublecomplex *); extern /* Double Complex */ VOID zladiv_(doublecomplex *, doublecomplex *, doublecomplex *); extern doublereal zlanhs_(char *, integer *, doublecomplex *, integer *, doublereal *); static doublereal smlnum; /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= ZLAHQR is an auxiliary routine called by ZHSEQR to update the eigenvalues and Schur decomposition already computed by ZHSEQR, by dealing with the Hessenberg submatrix in rows and columns ILO to IHI. Arguments ========= WANTT (input) LOGICAL = .TRUE. : the full Schur form T is required; = .FALSE.: only eigenvalues are required. WANTZ (input) LOGICAL = .TRUE. : the matrix of Schur vectors Z is required; = .FALSE.: Schur vectors are not required. N (input) INTEGER The order of the matrix H. N >= 0. ILO (input) INTEGER IHI (input) INTEGER It is assumed that H is already upper triangular in rows and columns IHI+1:N, and that H(ILO,ILO-1) = 0 (unless ILO = 1). ZLAHQR works primarily with the Hessenberg submatrix in rows and columns ILO to IHI, but applies transformations to all of H if WANTT is .TRUE.. 1 <= ILO <= max(1,IHI); IHI <= N. H (input/output) COMPLEX*16 array, dimension (LDH,N) On entry, the upper Hessenberg matrix H. On exit, if WANTT is .TRUE., H is upper triangular in rows and columns ILO:IHI, with any 2-by-2 diagonal blocks in standard form. If WANTT is .FALSE., the contents of H are unspecified on exit. LDH (input) INTEGER The leading dimension of the array H. LDH >= max(1,N). W (output) COMPLEX*16 array, dimension (N) The computed eigenvalues ILO to IHI are stored in the corresponding elements of W. If WANTT is .TRUE., the eigenvalues are stored in the same order as on the diagonal of the Schur form returned in H, with W(i) = H(i,i). ILOZ (input) INTEGER IHIZ (input) INTEGER Specify the rows of Z to which transformations must be applied if WANTZ is .TRUE.. 1 <= ILOZ <= ILO; IHI <= IHIZ <= N. Z (input/output) COMPLEX*16 array, dimension (LDZ,N) If WANTZ is .TRUE., on entry Z must contain the current matrix Z of transformations accumulated by ZHSEQR, and on exit Z has been updated; transformations are applied only to the submatrix Z(ILOZ:IHIZ,ILO:IHI). If WANTZ is .FALSE., Z is not referenced. LDZ (input) INTEGER The leading dimension of the array Z. LDZ >= max(1,N). INFO (output) INTEGER = 0: successful exit > 0: if INFO = i, ZLAHQR failed to compute all the eigenvalues ILO to IHI in a total of 30*(IHI-ILO+1) iterations; elements i+1:ihi of W contain those eigenvalues which have been successfully computed. ===================================================================== */ /* Parameter adjustments */ h_dim1 = *ldh; h_offset = 1 + h_dim1; h__ -= h_offset; --w; z_dim1 = *ldz; z_offset = 1 + z_dim1; z__ -= z_offset; /* Function Body */ *info = 0; /* Quick return if possible */ if (*n == 0) { return 0; } if (*ilo == *ihi) { i__1 = *ilo; i__2 = *ilo + *ilo * h_dim1; w[i__1].r = h__[i__2].r, w[i__1].i = h__[i__2].i; return 0; } nh = *ihi - *ilo + 1; nz = *ihiz - *iloz + 1; /* Set machine-dependent constants for the stopping criterion. If norm(H) <= sqrt(OVFL), overflow should not occur. */ ulp = PRECISION; smlnum = SAFEMINIMUM / ulp; /* I1 and I2 are the indices of the first row and last column of H to which transformations must be applied. If eigenvalues only are being computed, I1 and I2 are set inside the main loop. */ if (*wantt) { i1 = 1; i2 = *n; } /* ITN is the total number of QR iterations allowed. */ itn = nh * 30; /* The main loop begins here. I is the loop index and decreases from IHI to ILO in steps of 1. Each iteration of the loop works with the active submatrix in rows and columns L to I. Eigenvalues I+1 to IHI have already converged. Either L = ILO, or H(L,L-1) is negligible so that the matrix splits. */ i__ = *ihi; L10: if (i__ < *ilo) { goto L130; } /* Perform QR iterations on rows and columns ILO to I until a submatrix of order 1 splits off at the bottom because a subdiagonal element has become negligible. */ l = *ilo; i__1 = itn; for (its = 0; its <= i__1; ++its) { /* Look for a single small subdiagonal element. */ i__2 = l + 1; for (k = i__; k >= i__2; --k) { i__3 = k - 1 + (k - 1) * h_dim1; i__4 = k + k * h_dim1; tst1 = (d__1 = h__[i__3].r, abs(d__1)) + (d__2 = d_imag(&h__[k - 1 + (k - 1) * h_dim1]), abs(d__2)) + ((d__3 = h__[i__4].r, abs(d__3)) + (d__4 = d_imag(&h__[k + k * h_dim1]), abs( d__4))); if (tst1 == 0.) { i__3 = i__ - l + 1; tst1 = zlanhs_("1", &i__3, &h__[l + l * h_dim1], ldh, rwork); } i__3 = k + (k - 1) * h_dim1; /* Computing MAX */ d__2 = ulp * tst1; if ((d__1 = h__[i__3].r, abs(d__1)) <= max(d__2,smlnum)) { goto L30; } /* L20: */ } L30: l = k; if (l > *ilo) { /* H(L,L-1) is negligible */ i__2 = l + (l - 1) * h_dim1; h__[i__2].r = 0., h__[i__2].i = 0.; } /* Exit from loop if a submatrix of order 1 has split off. */ if (l >= i__) { goto L120; } /* Now the active submatrix is in rows and columns L to I. If eigenvalues only are being computed, only the active submatrix need be transformed. */ if (! (*wantt)) { i1 = l; i2 = i__; } if ((its == 10) || (its == 20)) { /* Exceptional shift. */ i__2 = i__ + (i__ - 1) * h_dim1; s = (d__1 = h__[i__2].r, abs(d__1)) * .75; i__2 = i__ + i__ * h_dim1; z__1.r = s + h__[i__2].r, z__1.i = h__[i__2].i; t.r = z__1.r, t.i = z__1.i; } else { /* Wilkinson's shift. */ i__2 = i__ + i__ * h_dim1; t.r = h__[i__2].r, t.i = h__[i__2].i; i__2 = i__ - 1 + i__ * h_dim1; i__3 = i__ + (i__ - 1) * h_dim1; d__1 = h__[i__3].r; z__1.r = d__1 * h__[i__2].r, z__1.i = d__1 * h__[i__2].i; u.r = z__1.r, u.i = z__1.i; if ((u.r != 0.) || (u.i != 0.)) { i__2 = i__ - 1 + (i__ - 1) * h_dim1; z__2.r = h__[i__2].r - t.r, z__2.i = h__[i__2].i - t.i; z__1.r = z__2.r * .5, z__1.i = z__2.i * .5; x.r = z__1.r, x.i = z__1.i; z__3.r = x.r * x.r - x.i * x.i, z__3.i = x.r * x.i + x.i * x.r; z__2.r = z__3.r + u.r, z__2.i = z__3.i + u.i; z_sqrt(&z__1, &z__2); y.r = z__1.r, y.i = z__1.i; if (x.r * y.r + d_imag(&x) * d_imag(&y) < 0.) { z__1.r = -y.r, z__1.i = -y.i; y.r = z__1.r, y.i = z__1.i; } z__3.r = x.r + y.r, z__3.i = x.i + y.i; zladiv_(&z__2, &u, &z__3); z__1.r = t.r - z__2.r, z__1.i = t.i - z__2.i; t.r = z__1.r, t.i = z__1.i; } } /* Look for two consecutive small subdiagonal elements. */ i__2 = l + 1; for (m = i__ - 1; m >= i__2; --m) { /* Determine the effect of starting the single-shift QR iteration at row M, and see if this would make H(M,M-1) negligible. */ i__3 = m + m * h_dim1; h11.r = h__[i__3].r, h11.i = h__[i__3].i; i__3 = m + 1 + (m + 1) * h_dim1; h22.r = h__[i__3].r, h22.i = h__[i__3].i; z__1.r = h11.r - t.r, z__1.i = h11.i - t.i; h11s.r = z__1.r, h11s.i = z__1.i; i__3 = m + 1 + m * h_dim1; h21 = h__[i__3].r; s = (d__1 = h11s.r, abs(d__1)) + (d__2 = d_imag(&h11s), abs(d__2)) + abs(h21); z__1.r = h11s.r / s, z__1.i = h11s.i / s; h11s.r = z__1.r, h11s.i = z__1.i; h21 /= s; v[0].r = h11s.r, v[0].i = h11s.i; v[1].r = h21, v[1].i = 0.; i__3 = m + (m - 1) * h_dim1; h10 = h__[i__3].r; tst1 = ((d__1 = h11s.r, abs(d__1)) + (d__2 = d_imag(&h11s), abs( d__2))) * ((d__3 = h11.r, abs(d__3)) + (d__4 = d_imag(& h11), abs(d__4)) + ((d__5 = h22.r, abs(d__5)) + (d__6 = d_imag(&h22), abs(d__6)))); if ((d__1 = h10 * h21, abs(d__1)) <= ulp * tst1) { goto L50; } /* L40: */ } i__2 = l + l * h_dim1; h11.r = h__[i__2].r, h11.i = h__[i__2].i; i__2 = l + 1 + (l + 1) * h_dim1; h22.r = h__[i__2].r, h22.i = h__[i__2].i; z__1.r = h11.r - t.r, z__1.i = h11.i - t.i; h11s.r = z__1.r, h11s.i = z__1.i; i__2 = l + 1 + l * h_dim1; h21 = h__[i__2].r; s = (d__1 = h11s.r, abs(d__1)) + (d__2 = d_imag(&h11s), abs(d__2)) + abs(h21); z__1.r = h11s.r / s, z__1.i = h11s.i / s; h11s.r = z__1.r, h11s.i = z__1.i; h21 /= s; v[0].r = h11s.r, v[0].i = h11s.i; v[1].r = h21, v[1].i = 0.; L50: /* Single-shift QR step */ i__2 = i__ - 1; for (k = m; k <= i__2; ++k) { /* The first iteration of this loop determines a reflection G from the vector V and applies it from left and right to H, thus creating a nonzero bulge below the subdiagonal. Each subsequent iteration determines a reflection G to restore the Hessenberg form in the (K-1)th column, and thus chases the bulge one step toward the bottom of the active submatrix. V(2) is always real before the call to ZLARFG, and hence after the call T2 ( = T1*V(2) ) is also real. */ if (k > m) { zcopy_(&c__2, &h__[k + (k - 1) * h_dim1], &c__1, v, &c__1); } zlarfg_(&c__2, v, &v[1], &c__1, &t1); if (k > m) { i__3 = k + (k - 1) * h_dim1; h__[i__3].r = v[0].r, h__[i__3].i = v[0].i; i__3 = k + 1 + (k - 1) * h_dim1; h__[i__3].r = 0., h__[i__3].i = 0.; } v2.r = v[1].r, v2.i = v[1].i; z__1.r = t1.r * v2.r - t1.i * v2.i, z__1.i = t1.r * v2.i + t1.i * v2.r; t2 = z__1.r; /* Apply G from the left to transform the rows of the matrix in columns K to I2. */ i__3 = i2; for (j = k; j <= i__3; ++j) { d_cnjg(&z__3, &t1); i__4 = k + j * h_dim1; z__2.r = z__3.r * h__[i__4].r - z__3.i * h__[i__4].i, z__2.i = z__3.r * h__[i__4].i + z__3.i * h__[i__4].r; i__5 = k + 1 + j * h_dim1; z__4.r = t2 * h__[i__5].r, z__4.i = t2 * h__[i__5].i; z__1.r = z__2.r + z__4.r, z__1.i = z__2.i + z__4.i; sum.r = z__1.r, sum.i = z__1.i; i__4 = k + j * h_dim1; i__5 = k + j * h_dim1; z__1.r = h__[i__5].r - sum.r, z__1.i = h__[i__5].i - sum.i; h__[i__4].r = z__1.r, h__[i__4].i = z__1.i; i__4 = k + 1 + j * h_dim1; i__5 = k + 1 + j * h_dim1; z__2.r = sum.r * v2.r - sum.i * v2.i, z__2.i = sum.r * v2.i + sum.i * v2.r; z__1.r = h__[i__5].r - z__2.r, z__1.i = h__[i__5].i - z__2.i; h__[i__4].r = z__1.r, h__[i__4].i = z__1.i; /* L60: */ } /* Apply G from the right to transform the columns of the matrix in rows I1 to min(K+2,I). Computing MIN */ i__4 = k + 2; i__3 = min(i__4,i__); for (j = i1; j <= i__3; ++j) { i__4 = j + k * h_dim1; z__2.r = t1.r * h__[i__4].r - t1.i * h__[i__4].i, z__2.i = t1.r * h__[i__4].i + t1.i * h__[i__4].r; i__5 = j + (k + 1) * h_dim1; z__3.r = t2 * h__[i__5].r, z__3.i = t2 * h__[i__5].i; z__1.r = z__2.r + z__3.r, z__1.i = z__2.i + z__3.i; sum.r = z__1.r, sum.i = z__1.i; i__4 = j + k * h_dim1; i__5 = j + k * h_dim1; z__1.r = h__[i__5].r - sum.r, z__1.i = h__[i__5].i - sum.i; h__[i__4].r = z__1.r, h__[i__4].i = z__1.i; i__4 = j + (k + 1) * h_dim1; i__5 = j + (k + 1) * h_dim1; d_cnjg(&z__3, &v2); z__2.r = sum.r * z__3.r - sum.i * z__3.i, z__2.i = sum.r * z__3.i + sum.i * z__3.r; z__1.r = h__[i__5].r - z__2.r, z__1.i = h__[i__5].i - z__2.i; h__[i__4].r = z__1.r, h__[i__4].i = z__1.i; /* L70: */ } if (*wantz) { /* Accumulate transformations in the matrix Z */ i__3 = *ihiz; for (j = *iloz; j <= i__3; ++j) { i__4 = j + k * z_dim1; z__2.r = t1.r * z__[i__4].r - t1.i * z__[i__4].i, z__2.i = t1.r * z__[i__4].i + t1.i * z__[i__4].r; i__5 = j + (k + 1) * z_dim1; z__3.r = t2 * z__[i__5].r, z__3.i = t2 * z__[i__5].i; z__1.r = z__2.r + z__3.r, z__1.i = z__2.i + z__3.i; sum.r = z__1.r, sum.i = z__1.i; i__4 = j + k * z_dim1; i__5 = j + k * z_dim1; z__1.r = z__[i__5].r - sum.r, z__1.i = z__[i__5].i - sum.i; z__[i__4].r = z__1.r, z__[i__4].i = z__1.i; i__4 = j + (k + 1) * z_dim1; i__5 = j + (k + 1) * z_dim1; d_cnjg(&z__3, &v2); z__2.r = sum.r * z__3.r - sum.i * z__3.i, z__2.i = sum.r * z__3.i + sum.i * z__3.r; z__1.r = z__[i__5].r - z__2.r, z__1.i = z__[i__5].i - z__2.i; z__[i__4].r = z__1.r, z__[i__4].i = z__1.i; /* L80: */ } } if (k == m && m > l) { /* If the QR step was started at row M > L because two consecutive small subdiagonals were found, then extra scaling must be performed to ensure that H(M,M-1) remains real. */ z__1.r = 1. - t1.r, z__1.i = 0. - t1.i; temp.r = z__1.r, temp.i = z__1.i; d__1 = z_abs(&temp); z__1.r = temp.r / d__1, z__1.i = temp.i / d__1; temp.r = z__1.r, temp.i = z__1.i; i__3 = m + 1 + m * h_dim1; i__4 = m + 1 + m * h_dim1; d_cnjg(&z__2, &temp); z__1.r = h__[i__4].r * z__2.r - h__[i__4].i * z__2.i, z__1.i = h__[i__4].r * z__2.i + h__[i__4].i * z__2.r; h__[i__3].r = z__1.r, h__[i__3].i = z__1.i; if (m + 2 <= i__) { i__3 = m + 2 + (m + 1) * h_dim1; i__4 = m + 2 + (m + 1) * h_dim1; z__1.r = h__[i__4].r * temp.r - h__[i__4].i * temp.i, z__1.i = h__[i__4].r * temp.i + h__[i__4].i * temp.r; h__[i__3].r = z__1.r, h__[i__3].i = z__1.i; } i__3 = i__; for (j = m; j <= i__3; ++j) { if (j != m + 1) { if (i2 > j) { i__4 = i2 - j; zscal_(&i__4, &temp, &h__[j + (j + 1) * h_dim1], ldh); } i__4 = j - i1; d_cnjg(&z__1, &temp); zscal_(&i__4, &z__1, &h__[i1 + j * h_dim1], &c__1); if (*wantz) { d_cnjg(&z__1, &temp); zscal_(&nz, &z__1, &z__[*iloz + j * z_dim1], & c__1); } } /* L90: */ } } /* L100: */ } /* Ensure that H(I,I-1) is real. */ i__2 = i__ + (i__ - 1) * h_dim1; temp.r = h__[i__2].r, temp.i = h__[i__2].i; if (d_imag(&temp) != 0.) { rtemp = z_abs(&temp); i__2 = i__ + (i__ - 1) * h_dim1; h__[i__2].r = rtemp, h__[i__2].i = 0.; z__1.r = temp.r / rtemp, z__1.i = temp.i / rtemp; temp.r = z__1.r, temp.i = z__1.i; if (i2 > i__) { i__2 = i2 - i__; d_cnjg(&z__1, &temp); zscal_(&i__2, &z__1, &h__[i__ + (i__ + 1) * h_dim1], ldh); } i__2 = i__ - i1; zscal_(&i__2, &temp, &h__[i1 + i__ * h_dim1], &c__1); if (*wantz) { zscal_(&nz, &temp, &z__[*iloz + i__ * z_dim1], &c__1); } } /* L110: */ } /* Failure to converge in remaining number of iterations */ *info = i__; return 0; L120: /* H(I,I-1) is negligible: one eigenvalue has converged. */ i__1 = i__; i__2 = i__ + i__ * h_dim1; w[i__1].r = h__[i__2].r, w[i__1].i = h__[i__2].i; /* Decrement number of remaining iterations, and return to start of the main loop with new value of I. */ itn -= its; i__ = l - 1; goto L10; L130: return 0; /* End of ZLAHQR */ } /* zlahqr_ */ /* Subroutine */ int zlahrd_(integer *n, integer *k, integer *nb, doublecomplex *a, integer *lda, doublecomplex *tau, doublecomplex *t, integer *ldt, doublecomplex *y, integer *ldy) { /* System generated locals */ integer a_dim1, a_offset, t_dim1, t_offset, y_dim1, y_offset, i__1, i__2, i__3; doublecomplex z__1; /* Local variables */ static integer i__; static doublecomplex ei; extern /* Subroutine */ int zscal_(integer *, doublecomplex *, doublecomplex *, integer *), zgemv_(char *, integer *, integer *, doublecomplex *, doublecomplex *, integer *, doublecomplex *, integer *, doublecomplex *, doublecomplex *, integer *), zcopy_(integer *, doublecomplex *, integer *, doublecomplex *, integer *), zaxpy_(integer *, doublecomplex *, doublecomplex *, integer *, doublecomplex *, integer *), ztrmv_(char *, char *, char *, integer *, doublecomplex *, integer *, doublecomplex *, integer *), zlarfg_(integer *, doublecomplex *, doublecomplex *, integer *, doublecomplex *), zlacgv_(integer *, doublecomplex *, integer *); /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= ZLAHRD reduces the first NB columns of a complex general n-by-(n-k+1) matrix A so that elements below the k-th subdiagonal are zero. The reduction is performed by a unitary similarity transformation Q' * A * Q. The routine returns the matrices V and T which determine Q as a block reflector I - V*T*V', and also the matrix Y = A * V * T. This is an auxiliary routine called by ZGEHRD. Arguments ========= N (input) INTEGER The order of the matrix A. K (input) INTEGER The offset for the reduction. Elements below the k-th subdiagonal in the first NB columns are reduced to zero. NB (input) INTEGER The number of columns to be reduced. A (input/output) COMPLEX*16 array, dimension (LDA,N-K+1) On entry, the n-by-(n-k+1) general matrix A. On exit, the elements on and above the k-th subdiagonal in the first NB columns are overwritten with the corresponding elements of the reduced matrix; the elements below the k-th subdiagonal, with the array TAU, represent the matrix Q as a product of elementary reflectors. The other columns of A are unchanged. See Further Details. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,N). TAU (output) COMPLEX*16 array, dimension (NB) The scalar factors of the elementary reflectors. See Further Details. T (output) COMPLEX*16 array, dimension (LDT,NB) The upper triangular matrix T. LDT (input) INTEGER The leading dimension of the array T. LDT >= NB. Y (output) COMPLEX*16 array, dimension (LDY,NB) The n-by-nb matrix Y. LDY (input) INTEGER The leading dimension of the array Y. LDY >= max(1,N). Further Details =============== The matrix Q is represented as a product of nb elementary reflectors Q = H(1) H(2) . . . H(nb). Each H(i) has the form H(i) = I - tau * v * v' where tau is a complex scalar, and v is a complex vector with v(1:i+k-1) = 0, v(i+k) = 1; v(i+k+1:n) is stored on exit in A(i+k+1:n,i), and tau in TAU(i). The elements of the vectors v together form the (n-k+1)-by-nb matrix V which is needed, with T and Y, to apply the transformation to the unreduced part of the matrix, using an update of the form: A := (I - V*T*V') * (A - Y*V'). The contents of A on exit are illustrated by the following example with n = 7, k = 3 and nb = 2: ( a h a a a ) ( a h a a a ) ( a h a a a ) ( h h a a a ) ( v1 h a a a ) ( v1 v2 a a a ) ( v1 v2 a a a ) where a denotes an element of the original matrix A, h denotes a modified element of the upper Hessenberg matrix H, and vi denotes an element of the vector defining H(i). ===================================================================== Quick return if possible */ /* Parameter adjustments */ --tau; a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; t_dim1 = *ldt; t_offset = 1 + t_dim1; t -= t_offset; y_dim1 = *ldy; y_offset = 1 + y_dim1; y -= y_offset; /* Function Body */ if (*n <= 1) { return 0; } i__1 = *nb; for (i__ = 1; i__ <= i__1; ++i__) { if (i__ > 1) { /* Update A(1:n,i) Compute i-th column of A - Y * V' */ i__2 = i__ - 1; zlacgv_(&i__2, &a[*k + i__ - 1 + a_dim1], lda); i__2 = i__ - 1; z__1.r = -1., z__1.i = -0.; zgemv_("No transpose", n, &i__2, &z__1, &y[y_offset], ldy, &a[*k + i__ - 1 + a_dim1], lda, &c_b60, &a[i__ * a_dim1 + 1], & c__1); i__2 = i__ - 1; zlacgv_(&i__2, &a[*k + i__ - 1 + a_dim1], lda); /* Apply I - V * T' * V' to this column (call it b) from the left, using the last column of T as workspace Let V = ( V1 ) and b = ( b1 ) (first I-1 rows) ( V2 ) ( b2 ) where V1 is unit lower triangular w := V1' * b1 */ i__2 = i__ - 1; zcopy_(&i__2, &a[*k + 1 + i__ * a_dim1], &c__1, &t[*nb * t_dim1 + 1], &c__1); i__2 = i__ - 1; ztrmv_("Lower", "Conjugate transpose", "Unit", &i__2, &a[*k + 1 + a_dim1], lda, &t[*nb * t_dim1 + 1], &c__1); /* w := w + V2'*b2 */ i__2 = *n - *k - i__ + 1; i__3 = i__ - 1; zgemv_("Conjugate transpose", &i__2, &i__3, &c_b60, &a[*k + i__ + a_dim1], lda, &a[*k + i__ + i__ * a_dim1], &c__1, &c_b60, &t[*nb * t_dim1 + 1], &c__1); /* w := T'*w */ i__2 = i__ - 1; ztrmv_("Upper", "Conjugate transpose", "Non-unit", &i__2, &t[ t_offset], ldt, &t[*nb * t_dim1 + 1], &c__1); /* b2 := b2 - V2*w */ i__2 = *n - *k - i__ + 1; i__3 = i__ - 1; z__1.r = -1., z__1.i = -0.; zgemv_("No transpose", &i__2, &i__3, &z__1, &a[*k + i__ + a_dim1], lda, &t[*nb * t_dim1 + 1], &c__1, &c_b60, &a[*k + i__ + i__ * a_dim1], &c__1); /* b1 := b1 - V1*w */ i__2 = i__ - 1; ztrmv_("Lower", "No transpose", "Unit", &i__2, &a[*k + 1 + a_dim1] , lda, &t[*nb * t_dim1 + 1], &c__1); i__2 = i__ - 1; z__1.r = -1., z__1.i = -0.; zaxpy_(&i__2, &z__1, &t[*nb * t_dim1 + 1], &c__1, &a[*k + 1 + i__ * a_dim1], &c__1); i__2 = *k + i__ - 1 + (i__ - 1) * a_dim1; a[i__2].r = ei.r, a[i__2].i = ei.i; } /* Generate the elementary reflector H(i) to annihilate A(k+i+1:n,i) */ i__2 = *k + i__ + i__ * a_dim1; ei.r = a[i__2].r, ei.i = a[i__2].i; i__2 = *n - *k - i__ + 1; /* Computing MIN */ i__3 = *k + i__ + 1; zlarfg_(&i__2, &ei, &a[min(i__3,*n) + i__ * a_dim1], &c__1, &tau[i__]) ; i__2 = *k + i__ + i__ * a_dim1; a[i__2].r = 1., a[i__2].i = 0.; /* Compute Y(1:n,i) */ i__2 = *n - *k - i__ + 1; zgemv_("No transpose", n, &i__2, &c_b60, &a[(i__ + 1) * a_dim1 + 1], lda, &a[*k + i__ + i__ * a_dim1], &c__1, &c_b59, &y[i__ * y_dim1 + 1], &c__1); i__2 = *n - *k - i__ + 1; i__3 = i__ - 1; zgemv_("Conjugate transpose", &i__2, &i__3, &c_b60, &a[*k + i__ + a_dim1], lda, &a[*k + i__ + i__ * a_dim1], &c__1, &c_b59, &t[ i__ * t_dim1 + 1], &c__1); i__2 = i__ - 1; z__1.r = -1., z__1.i = -0.; zgemv_("No transpose", n, &i__2, &z__1, &y[y_offset], ldy, &t[i__ * t_dim1 + 1], &c__1, &c_b60, &y[i__ * y_dim1 + 1], &c__1); zscal_(n, &tau[i__], &y[i__ * y_dim1 + 1], &c__1); /* Compute T(1:i,i) */ i__2 = i__ - 1; i__3 = i__; z__1.r = -tau[i__3].r, z__1.i = -tau[i__3].i; zscal_(&i__2, &z__1, &t[i__ * t_dim1 + 1], &c__1); i__2 = i__ - 1; ztrmv_("Upper", "No transpose", "Non-unit", &i__2, &t[t_offset], ldt, &t[i__ * t_dim1 + 1], &c__1) ; i__2 = i__ + i__ * t_dim1; i__3 = i__; t[i__2].r = tau[i__3].r, t[i__2].i = tau[i__3].i; /* L10: */ } i__1 = *k + *nb + *nb * a_dim1; a[i__1].r = ei.r, a[i__1].i = ei.i; return 0; /* End of ZLAHRD */ } /* zlahrd_ */ /* Subroutine */ int zlals0_(integer *icompq, integer *nl, integer *nr, integer *sqre, integer *nrhs, doublecomplex *b, integer *ldb, doublecomplex *bx, integer *ldbx, integer *perm, integer *givptr, integer *givcol, integer *ldgcol, doublereal *givnum, integer *ldgnum, doublereal *poles, doublereal *difl, doublereal *difr, doublereal * z__, integer *k, doublereal *c__, doublereal *s, doublereal *rwork, integer *info) { /* System generated locals */ integer givcol_dim1, givcol_offset, difr_dim1, difr_offset, givnum_dim1, givnum_offset, poles_dim1, poles_offset, b_dim1, b_offset, bx_dim1, bx_offset, i__1, i__2, i__3, i__4, i__5; doublereal d__1; doublecomplex z__1; /* Builtin functions */ double d_imag(doublecomplex *); /* Local variables */ static integer i__, j, m, n; static doublereal dj; static integer nlp1, jcol; static doublereal temp; static integer jrow; extern doublereal dnrm2_(integer *, doublereal *, integer *); static doublereal diflj, difrj, dsigj; extern /* Subroutine */ int dgemv_(char *, integer *, integer *, doublereal *, doublereal *, integer *, doublereal *, integer *, doublereal *, doublereal *, integer *), zdrot_(integer *, doublecomplex *, integer *, doublecomplex *, integer *, doublereal *, doublereal *); extern doublereal dlamc3_(doublereal *, doublereal *); extern /* Subroutine */ int zcopy_(integer *, doublecomplex *, integer *, doublecomplex *, integer *), xerbla_(char *, integer *); static doublereal dsigjp; extern /* Subroutine */ int zdscal_(integer *, doublereal *, doublecomplex *, integer *), zlascl_(char *, integer *, integer *, doublereal *, doublereal *, integer *, integer *, doublecomplex * , integer *, integer *), zlacpy_(char *, integer *, integer *, doublecomplex *, integer *, doublecomplex *, integer *); /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University December 1, 1999 Purpose ======= ZLALS0 applies back the multiplying factors of either the left or the right singular vector matrix of a diagonal matrix appended by a row to the right hand side matrix B in solving the least squares problem using the divide-and-conquer SVD approach. For the left singular vector matrix, three types of orthogonal matrices are involved: (1L) Givens rotations: the number of such rotations is GIVPTR; the pairs of columns/rows they were applied to are stored in GIVCOL; and the C- and S-values of these rotations are stored in GIVNUM. (2L) Permutation. The (NL+1)-st row of B is to be moved to the first row, and for J=2:N, PERM(J)-th row of B is to be moved to the J-th row. (3L) The left singular vector matrix of the remaining matrix. For the right singular vector matrix, four types of orthogonal matrices are involved: (1R) The right singular vector matrix of the remaining matrix. (2R) If SQRE = 1, one extra Givens rotation to generate the right null space. (3R) The inverse transformation of (2L). (4R) The inverse transformation of (1L). Arguments ========= ICOMPQ (input) INTEGER Specifies whether singular vectors are to be computed in factored form: = 0: Left singular vector matrix. = 1: Right singular vector matrix. NL (input) INTEGER The row dimension of the upper block. NL >= 1. NR (input) INTEGER The row dimension of the lower block. NR >= 1. SQRE (input) INTEGER = 0: the lower block is an NR-by-NR square matrix. = 1: the lower block is an NR-by-(NR+1) rectangular matrix. The bidiagonal matrix has row dimension N = NL + NR + 1, and column dimension M = N + SQRE. NRHS (input) INTEGER The number of columns of B and BX. NRHS must be at least 1. B (input/output) COMPLEX*16 array, dimension ( LDB, NRHS ) On input, B contains the right hand sides of the least squares problem in rows 1 through M. On output, B contains the solution X in rows 1 through N. LDB (input) INTEGER The leading dimension of B. LDB must be at least max(1,MAX( M, N ) ). BX (workspace) COMPLEX*16 array, dimension ( LDBX, NRHS ) LDBX (input) INTEGER The leading dimension of BX. PERM (input) INTEGER array, dimension ( N ) The permutations (from deflation and sorting) applied to the two blocks. GIVPTR (input) INTEGER The number of Givens rotations which took place in this subproblem. GIVCOL (input) INTEGER array, dimension ( LDGCOL, 2 ) Each pair of numbers indicates a pair of rows/columns involved in a Givens rotation. LDGCOL (input) INTEGER The leading dimension of GIVCOL, must be at least N. GIVNUM (input) DOUBLE PRECISION array, dimension ( LDGNUM, 2 ) Each number indicates the C or S value used in the corresponding Givens rotation. LDGNUM (input) INTEGER The leading dimension of arrays DIFR, POLES and GIVNUM, must be at least K. POLES (input) DOUBLE PRECISION array, dimension ( LDGNUM, 2 ) On entry, POLES(1:K, 1) contains the new singular values obtained from solving the secular equation, and POLES(1:K, 2) is an array containing the poles in the secular equation. DIFL (input) DOUBLE PRECISION array, dimension ( K ). On entry, DIFL(I) is the distance between I-th updated (undeflated) singular value and the I-th (undeflated) old singular value. DIFR (input) DOUBLE PRECISION array, dimension ( LDGNUM, 2 ). On entry, DIFR(I, 1) contains the distances between I-th updated (undeflated) singular value and the I+1-th (undeflated) old singular value. And DIFR(I, 2) is the normalizing factor for the I-th right singular vector. Z (input) DOUBLE PRECISION array, dimension ( K ) Contain the components of the deflation-adjusted updating row vector. K (input) INTEGER Contains the dimension of the non-deflated matrix, This is the order of the related secular equation. 1 <= K <=N. C (input) DOUBLE PRECISION C contains garbage if SQRE =0 and the C-value of a Givens rotation related to the right null space if SQRE = 1. S (input) DOUBLE PRECISION S contains garbage if SQRE =0 and the S-value of a Givens rotation related to the right null space if SQRE = 1. RWORK (workspace) DOUBLE PRECISION array, dimension ( K*(1+NRHS) + 2*NRHS ) INFO (output) INTEGER = 0: successful exit. < 0: if INFO = -i, the i-th argument had an illegal value. Further Details =============== Based on contributions by Ming Gu and Ren-Cang Li, Computer Science Division, University of California at Berkeley, USA Osni Marques, LBNL/NERSC, USA ===================================================================== Test the input parameters. */ /* Parameter adjustments */ b_dim1 = *ldb; b_offset = 1 + b_dim1; b -= b_offset; bx_dim1 = *ldbx; bx_offset = 1 + bx_dim1; bx -= bx_offset; --perm; givcol_dim1 = *ldgcol; givcol_offset = 1 + givcol_dim1; givcol -= givcol_offset; difr_dim1 = *ldgnum; difr_offset = 1 + difr_dim1; difr -= difr_offset; poles_dim1 = *ldgnum; poles_offset = 1 + poles_dim1; poles -= poles_offset; givnum_dim1 = *ldgnum; givnum_offset = 1 + givnum_dim1; givnum -= givnum_offset; --difl; --z__; --rwork; /* Function Body */ *info = 0; if ((*icompq < 0) || (*icompq > 1)) { *info = -1; } else if (*nl < 1) { *info = -2; } else if (*nr < 1) { *info = -3; } else if ((*sqre < 0) || (*sqre > 1)) { *info = -4; } n = *nl + *nr + 1; if (*nrhs < 1) { *info = -5; } else if (*ldb < n) { *info = -7; } else if (*ldbx < n) { *info = -9; } else if (*givptr < 0) { *info = -11; } else if (*ldgcol < n) { *info = -13; } else if (*ldgnum < n) { *info = -15; } else if (*k < 1) { *info = -20; } if (*info != 0) { i__1 = -(*info); xerbla_("ZLALS0", &i__1); return 0; } m = n + *sqre; nlp1 = *nl + 1; if (*icompq == 0) { /* Apply back orthogonal transformations from the left. Step (1L): apply back the Givens rotations performed. */ i__1 = *givptr; for (i__ = 1; i__ <= i__1; ++i__) { zdrot_(nrhs, &b[givcol[i__ + ((givcol_dim1) << (1))] + b_dim1], ldb, &b[givcol[i__ + givcol_dim1] + b_dim1], ldb, &givnum[ i__ + ((givnum_dim1) << (1))], &givnum[i__ + givnum_dim1]) ; /* L10: */ } /* Step (2L): permute rows of B. */ zcopy_(nrhs, &b[nlp1 + b_dim1], ldb, &bx[bx_dim1 + 1], ldbx); i__1 = n; for (i__ = 2; i__ <= i__1; ++i__) { zcopy_(nrhs, &b[perm[i__] + b_dim1], ldb, &bx[i__ + bx_dim1], ldbx); /* L20: */ } /* Step (3L): apply the inverse of the left singular vector matrix to BX. */ if (*k == 1) { zcopy_(nrhs, &bx[bx_offset], ldbx, &b[b_offset], ldb); if (z__[1] < 0.) { zdscal_(nrhs, &c_b1294, &b[b_offset], ldb); } } else { i__1 = *k; for (j = 1; j <= i__1; ++j) { diflj = difl[j]; dj = poles[j + poles_dim1]; dsigj = -poles[j + ((poles_dim1) << (1))]; if (j < *k) { difrj = -difr[j + difr_dim1]; dsigjp = -poles[j + 1 + ((poles_dim1) << (1))]; } if ((z__[j] == 0.) || (poles[j + ((poles_dim1) << (1))] == 0.) ) { rwork[j] = 0.; } else { rwork[j] = -poles[j + ((poles_dim1) << (1))] * z__[j] / diflj / (poles[j + ((poles_dim1) << (1))] + dj); } i__2 = j - 1; for (i__ = 1; i__ <= i__2; ++i__) { if ((z__[i__] == 0.) || (poles[i__ + ((poles_dim1) << (1)) ] == 0.)) { rwork[i__] = 0.; } else { rwork[i__] = poles[i__ + ((poles_dim1) << (1))] * z__[ i__] / (dlamc3_(&poles[i__ + ((poles_dim1) << (1))], &dsigj) - diflj) / (poles[i__ + (( poles_dim1) << (1))] + dj); } /* L30: */ } i__2 = *k; for (i__ = j + 1; i__ <= i__2; ++i__) { if ((z__[i__] == 0.) || (poles[i__ + ((poles_dim1) << (1)) ] == 0.)) { rwork[i__] = 0.; } else { rwork[i__] = poles[i__ + ((poles_dim1) << (1))] * z__[ i__] / (dlamc3_(&poles[i__ + ((poles_dim1) << (1))], &dsigjp) + difrj) / (poles[i__ + (( poles_dim1) << (1))] + dj); } /* L40: */ } rwork[1] = -1.; temp = dnrm2_(k, &rwork[1], &c__1); /* Since B and BX are complex, the following call to DGEMV is performed in two steps (real and imaginary parts). CALL DGEMV( 'T', K, NRHS, ONE, BX, LDBX, WORK, 1, ZERO, $ B( J, 1 ), LDB ) */ i__ = *k + ((*nrhs) << (1)); i__2 = *nrhs; for (jcol = 1; jcol <= i__2; ++jcol) { i__3 = *k; for (jrow = 1; jrow <= i__3; ++jrow) { ++i__; i__4 = jrow + jcol * bx_dim1; rwork[i__] = bx[i__4].r; /* L50: */ } /* L60: */ } dgemv_("T", k, nrhs, &c_b1015, &rwork[*k + 1 + ((*nrhs) << (1) )], k, &rwork[1], &c__1, &c_b324, &rwork[*k + 1], & c__1); i__ = *k + ((*nrhs) << (1)); i__2 = *nrhs; for (jcol = 1; jcol <= i__2; ++jcol) { i__3 = *k; for (jrow = 1; jrow <= i__3; ++jrow) { ++i__; rwork[i__] = d_imag(&bx[jrow + jcol * bx_dim1]); /* L70: */ } /* L80: */ } dgemv_("T", k, nrhs, &c_b1015, &rwork[*k + 1 + ((*nrhs) << (1) )], k, &rwork[1], &c__1, &c_b324, &rwork[*k + 1 + * nrhs], &c__1); i__2 = *nrhs; for (jcol = 1; jcol <= i__2; ++jcol) { i__3 = j + jcol * b_dim1; i__4 = jcol + *k; i__5 = jcol + *k + *nrhs; z__1.r = rwork[i__4], z__1.i = rwork[i__5]; b[i__3].r = z__1.r, b[i__3].i = z__1.i; /* L90: */ } zlascl_("G", &c__0, &c__0, &temp, &c_b1015, &c__1, nrhs, &b[j + b_dim1], ldb, info); /* L100: */ } } /* Move the deflated rows of BX to B also. */ if (*k < max(m,n)) { i__1 = n - *k; zlacpy_("A", &i__1, nrhs, &bx[*k + 1 + bx_dim1], ldbx, &b[*k + 1 + b_dim1], ldb); } } else { /* Apply back the right orthogonal transformations. Step (1R): apply back the new right singular vector matrix to B. */ if (*k == 1) { zcopy_(nrhs, &b[b_offset], ldb, &bx[bx_offset], ldbx); } else { i__1 = *k; for (j = 1; j <= i__1; ++j) { dsigj = poles[j + ((poles_dim1) << (1))]; if (z__[j] == 0.) { rwork[j] = 0.; } else { rwork[j] = -z__[j] / difl[j] / (dsigj + poles[j + poles_dim1]) / difr[j + ((difr_dim1) << (1))]; } i__2 = j - 1; for (i__ = 1; i__ <= i__2; ++i__) { if (z__[j] == 0.) { rwork[i__] = 0.; } else { d__1 = -poles[i__ + 1 + ((poles_dim1) << (1))]; rwork[i__] = z__[j] / (dlamc3_(&dsigj, &d__1) - difr[ i__ + difr_dim1]) / (dsigj + poles[i__ + poles_dim1]) / difr[i__ + ((difr_dim1) << (1)) ]; } /* L110: */ } i__2 = *k; for (i__ = j + 1; i__ <= i__2; ++i__) { if (z__[j] == 0.) { rwork[i__] = 0.; } else { d__1 = -poles[i__ + ((poles_dim1) << (1))]; rwork[i__] = z__[j] / (dlamc3_(&dsigj, &d__1) - difl[ i__]) / (dsigj + poles[i__ + poles_dim1]) / difr[i__ + ((difr_dim1) << (1))]; } /* L120: */ } /* Since B and BX are complex, the following call to DGEMV is performed in two steps (real and imaginary parts). CALL DGEMV( 'T', K, NRHS, ONE, B, LDB, WORK, 1, ZERO, $ BX( J, 1 ), LDBX ) */ i__ = *k + ((*nrhs) << (1)); i__2 = *nrhs; for (jcol = 1; jcol <= i__2; ++jcol) { i__3 = *k; for (jrow = 1; jrow <= i__3; ++jrow) { ++i__; i__4 = jrow + jcol * b_dim1; rwork[i__] = b[i__4].r; /* L130: */ } /* L140: */ } dgemv_("T", k, nrhs, &c_b1015, &rwork[*k + 1 + ((*nrhs) << (1) )], k, &rwork[1], &c__1, &c_b324, &rwork[*k + 1], & c__1); i__ = *k + ((*nrhs) << (1)); i__2 = *nrhs; for (jcol = 1; jcol <= i__2; ++jcol) { i__3 = *k; for (jrow = 1; jrow <= i__3; ++jrow) { ++i__; rwork[i__] = d_imag(&b[jrow + jcol * b_dim1]); /* L150: */ } /* L160: */ } dgemv_("T", k, nrhs, &c_b1015, &rwork[*k + 1 + ((*nrhs) << (1) )], k, &rwork[1], &c__1, &c_b324, &rwork[*k + 1 + * nrhs], &c__1); i__2 = *nrhs; for (jcol = 1; jcol <= i__2; ++jcol) { i__3 = j + jcol * bx_dim1; i__4 = jcol + *k; i__5 = jcol + *k + *nrhs; z__1.r = rwork[i__4], z__1.i = rwork[i__5]; bx[i__3].r = z__1.r, bx[i__3].i = z__1.i; /* L170: */ } /* L180: */ } } /* Step (2R): if SQRE = 1, apply back the rotation that is related to the right null space of the subproblem. */ if (*sqre == 1) { zcopy_(nrhs, &b[m + b_dim1], ldb, &bx[m + bx_dim1], ldbx); zdrot_(nrhs, &bx[bx_dim1 + 1], ldbx, &bx[m + bx_dim1], ldbx, c__, s); } if (*k < max(m,n)) { i__1 = n - *k; zlacpy_("A", &i__1, nrhs, &b[*k + 1 + b_dim1], ldb, &bx[*k + 1 + bx_dim1], ldbx); } /* Step (3R): permute rows of B. */ zcopy_(nrhs, &bx[bx_dim1 + 1], ldbx, &b[nlp1 + b_dim1], ldb); if (*sqre == 1) { zcopy_(nrhs, &bx[m + bx_dim1], ldbx, &b[m + b_dim1], ldb); } i__1 = n; for (i__ = 2; i__ <= i__1; ++i__) { zcopy_(nrhs, &bx[i__ + bx_dim1], ldbx, &b[perm[i__] + b_dim1], ldb); /* L190: */ } /* Step (4R): apply back the Givens rotations performed. */ for (i__ = *givptr; i__ >= 1; --i__) { d__1 = -givnum[i__ + givnum_dim1]; zdrot_(nrhs, &b[givcol[i__ + ((givcol_dim1) << (1))] + b_dim1], ldb, &b[givcol[i__ + givcol_dim1] + b_dim1], ldb, &givnum[ i__ + ((givnum_dim1) << (1))], &d__1); /* L200: */ } } return 0; /* End of ZLALS0 */ } /* zlals0_ */ /* Subroutine */ int zlalsa_(integer *icompq, integer *smlsiz, integer *n, integer *nrhs, doublecomplex *b, integer *ldb, doublecomplex *bx, integer *ldbx, doublereal *u, integer *ldu, doublereal *vt, integer * k, doublereal *difl, doublereal *difr, doublereal *z__, doublereal * poles, integer *givptr, integer *givcol, integer *ldgcol, integer * perm, doublereal *givnum, doublereal *c__, doublereal *s, doublereal * rwork, integer *iwork, integer *info) { /* System generated locals */ integer givcol_dim1, givcol_offset, perm_dim1, perm_offset, difl_dim1, difl_offset, difr_dim1, difr_offset, givnum_dim1, givnum_offset, poles_dim1, poles_offset, u_dim1, u_offset, vt_dim1, vt_offset, z_dim1, z_offset, b_dim1, b_offset, bx_dim1, bx_offset, i__1, i__2, i__3, i__4, i__5, i__6; doublecomplex z__1; /* Builtin functions */ double d_imag(doublecomplex *); integer pow_ii(integer *, integer *); /* Local variables */ static integer i__, j, i1, ic, lf, nd, ll, nl, nr, im1, nlf, nrf, lvl, ndb1, nlp1, lvl2, nrp1, jcol, nlvl, sqre, jrow, jimag; extern /* Subroutine */ int dgemm_(char *, char *, integer *, integer *, integer *, doublereal *, doublereal *, integer *, doublereal *, integer *, doublereal *, doublereal *, integer *); static integer jreal, inode, ndiml, ndimr; extern /* Subroutine */ int zcopy_(integer *, doublecomplex *, integer *, doublecomplex *, integer *), zlals0_(integer *, integer *, integer *, integer *, integer *, doublecomplex *, integer *, doublecomplex *, integer *, integer *, integer *, integer *, integer *, doublereal *, integer *, doublereal *, doublereal *, doublereal *, doublereal *, integer *, doublereal *, doublereal *, doublereal *, integer *), dlasdt_(integer *, integer *, integer * , integer *, integer *, integer *, integer *), xerbla_(char *, integer *); /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= ZLALSA is an itermediate step in solving the least squares problem by computing the SVD of the coefficient matrix in compact form (The singular vectors are computed as products of simple orthorgonal matrices.). If ICOMPQ = 0, ZLALSA applies the inverse of the left singular vector matrix of an upper bidiagonal matrix to the right hand side; and if ICOMPQ = 1, ZLALSA applies the right singular vector matrix to the right hand side. The singular vector matrices were generated in compact form by ZLALSA. Arguments ========= ICOMPQ (input) INTEGER Specifies whether the left or the right singular vector matrix is involved. = 0: Left singular vector matrix = 1: Right singular vector matrix SMLSIZ (input) INTEGER The maximum size of the subproblems at the bottom of the computation tree. N (input) INTEGER The row and column dimensions of the upper bidiagonal matrix. NRHS (input) INTEGER The number of columns of B and BX. NRHS must be at least 1. B (input) COMPLEX*16 array, dimension ( LDB, NRHS ) On input, B contains the right hand sides of the least squares problem in rows 1 through M. On output, B contains the solution X in rows 1 through N. LDB (input) INTEGER The leading dimension of B in the calling subprogram. LDB must be at least max(1,MAX( M, N ) ). BX (output) COMPLEX*16 array, dimension ( LDBX, NRHS ) On exit, the result of applying the left or right singular vector matrix to B. LDBX (input) INTEGER The leading dimension of BX. U (input) DOUBLE PRECISION array, dimension ( LDU, SMLSIZ ). On entry, U contains the left singular vector matrices of all subproblems at the bottom level. LDU (input) INTEGER, LDU = > N. The leading dimension of arrays U, VT, DIFL, DIFR, POLES, GIVNUM, and Z. VT (input) DOUBLE PRECISION array, dimension ( LDU, SMLSIZ+1 ). On entry, VT' contains the right singular vector matrices of all subproblems at the bottom level. K (input) INTEGER array, dimension ( N ). DIFL (input) DOUBLE PRECISION array, dimension ( LDU, NLVL ). where NLVL = INT(log_2 (N/(SMLSIZ+1))) + 1. DIFR (input) DOUBLE PRECISION array, dimension ( LDU, 2 * NLVL ). On entry, DIFL(*, I) and DIFR(*, 2 * I -1) record distances between singular values on the I-th level and singular values on the (I -1)-th level, and DIFR(*, 2 * I) record the normalizing factors of the right singular vectors matrices of subproblems on I-th level. Z (input) DOUBLE PRECISION array, dimension ( LDU, NLVL ). On entry, Z(1, I) contains the components of the deflation- adjusted updating row vector for subproblems on the I-th level. POLES (input) DOUBLE PRECISION array, dimension ( LDU, 2 * NLVL ). On entry, POLES(*, 2 * I -1: 2 * I) contains the new and old singular values involved in the secular equations on the I-th level. GIVPTR (input) INTEGER array, dimension ( N ). On entry, GIVPTR( I ) records the number of Givens rotations performed on the I-th problem on the computation tree. GIVCOL (input) INTEGER array, dimension ( LDGCOL, 2 * NLVL ). On entry, for each I, GIVCOL(*, 2 * I - 1: 2 * I) records the locations of Givens rotations performed on the I-th level on the computation tree. LDGCOL (input) INTEGER, LDGCOL = > N. The leading dimension of arrays GIVCOL and PERM. PERM (input) INTEGER array, dimension ( LDGCOL, NLVL ). On entry, PERM(*, I) records permutations done on the I-th level of the computation tree. GIVNUM (input) DOUBLE PRECISION array, dimension ( LDU, 2 * NLVL ). On entry, GIVNUM(*, 2 *I -1 : 2 * I) records the C- and S- values of Givens rotations performed on the I-th level on the computation tree. C (input) DOUBLE PRECISION array, dimension ( N ). On entry, if the I-th subproblem is not square, C( I ) contains the C-value of a Givens rotation related to the right null space of the I-th subproblem. S (input) DOUBLE PRECISION array, dimension ( N ). On entry, if the I-th subproblem is not square, S( I ) contains the S-value of a Givens rotation related to the right null space of the I-th subproblem. RWORK (workspace) DOUBLE PRECISION array, dimension at least max ( N, (SMLSZ+1)*NRHS*3 ). IWORK (workspace) INTEGER array. The dimension must be at least 3 * N INFO (output) INTEGER = 0: successful exit. < 0: if INFO = -i, the i-th argument had an illegal value. Further Details =============== Based on contributions by Ming Gu and Ren-Cang Li, Computer Science Division, University of California at Berkeley, USA Osni Marques, LBNL/NERSC, USA ===================================================================== Test the input parameters. */ /* Parameter adjustments */ b_dim1 = *ldb; b_offset = 1 + b_dim1; b -= b_offset; bx_dim1 = *ldbx; bx_offset = 1 + bx_dim1; bx -= bx_offset; givnum_dim1 = *ldu; givnum_offset = 1 + givnum_dim1; givnum -= givnum_offset; poles_dim1 = *ldu; poles_offset = 1 + poles_dim1; poles -= poles_offset; z_dim1 = *ldu; z_offset = 1 + z_dim1; z__ -= z_offset; difr_dim1 = *ldu; difr_offset = 1 + difr_dim1; difr -= difr_offset; difl_dim1 = *ldu; difl_offset = 1 + difl_dim1; difl -= difl_offset; vt_dim1 = *ldu; vt_offset = 1 + vt_dim1; vt -= vt_offset; u_dim1 = *ldu; u_offset = 1 + u_dim1; u -= u_offset; --k; --givptr; perm_dim1 = *ldgcol; perm_offset = 1 + perm_dim1; perm -= perm_offset; givcol_dim1 = *ldgcol; givcol_offset = 1 + givcol_dim1; givcol -= givcol_offset; --c__; --s; --rwork; --iwork; /* Function Body */ *info = 0; if ((*icompq < 0) || (*icompq > 1)) { *info = -1; } else if (*smlsiz < 3) { *info = -2; } else if (*n < *smlsiz) { *info = -3; } else if (*nrhs < 1) { *info = -4; } else if (*ldb < *n) { *info = -6; } else if (*ldbx < *n) { *info = -8; } else if (*ldu < *n) { *info = -10; } else if (*ldgcol < *n) { *info = -19; } if (*info != 0) { i__1 = -(*info); xerbla_("ZLALSA", &i__1); return 0; } /* Book-keeping and setting up the computation tree. */ inode = 1; ndiml = inode + *n; ndimr = ndiml + *n; dlasdt_(n, &nlvl, &nd, &iwork[inode], &iwork[ndiml], &iwork[ndimr], smlsiz); /* The following code applies back the left singular vector factors. For applying back the right singular vector factors, go to 170. */ if (*icompq == 1) { goto L170; } /* The nodes on the bottom level of the tree were solved by DLASDQ. The corresponding left and right singular vector matrices are in explicit form. First apply back the left singular vector matrices. */ ndb1 = (nd + 1) / 2; i__1 = nd; for (i__ = ndb1; i__ <= i__1; ++i__) { /* IC : center row of each node NL : number of rows of left subproblem NR : number of rows of right subproblem NLF: starting row of the left subproblem NRF: starting row of the right subproblem */ i1 = i__ - 1; ic = iwork[inode + i1]; nl = iwork[ndiml + i1]; nr = iwork[ndimr + i1]; nlf = ic - nl; nrf = ic + 1; /* Since B and BX are complex, the following call to DGEMM is performed in two steps (real and imaginary parts). CALL DGEMM( 'T', 'N', NL, NRHS, NL, ONE, U( NLF, 1 ), LDU, $ B( NLF, 1 ), LDB, ZERO, BX( NLF, 1 ), LDBX ) */ j = (nl * *nrhs) << (1); i__2 = *nrhs; for (jcol = 1; jcol <= i__2; ++jcol) { i__3 = nlf + nl - 1; for (jrow = nlf; jrow <= i__3; ++jrow) { ++j; i__4 = jrow + jcol * b_dim1; rwork[j] = b[i__4].r; /* L10: */ } /* L20: */ } dgemm_("T", "N", &nl, nrhs, &nl, &c_b1015, &u[nlf + u_dim1], ldu, & rwork[((nl * *nrhs) << (1)) + 1], &nl, &c_b324, &rwork[1], & nl); j = (nl * *nrhs) << (1); i__2 = *nrhs; for (jcol = 1; jcol <= i__2; ++jcol) { i__3 = nlf + nl - 1; for (jrow = nlf; jrow <= i__3; ++jrow) { ++j; rwork[j] = d_imag(&b[jrow + jcol * b_dim1]); /* L30: */ } /* L40: */ } dgemm_("T", "N", &nl, nrhs, &nl, &c_b1015, &u[nlf + u_dim1], ldu, & rwork[((nl * *nrhs) << (1)) + 1], &nl, &c_b324, &rwork[nl * * nrhs + 1], &nl); jreal = 0; jimag = nl * *nrhs; i__2 = *nrhs; for (jcol = 1; jcol <= i__2; ++jcol) { i__3 = nlf + nl - 1; for (jrow = nlf; jrow <= i__3; ++jrow) { ++jreal; ++jimag; i__4 = jrow + jcol * bx_dim1; i__5 = jreal; i__6 = jimag; z__1.r = rwork[i__5], z__1.i = rwork[i__6]; bx[i__4].r = z__1.r, bx[i__4].i = z__1.i; /* L50: */ } /* L60: */ } /* Since B and BX are complex, the following call to DGEMM is performed in two steps (real and imaginary parts). CALL DGEMM( 'T', 'N', NR, NRHS, NR, ONE, U( NRF, 1 ), LDU, $ B( NRF, 1 ), LDB, ZERO, BX( NRF, 1 ), LDBX ) */ j = (nr * *nrhs) << (1); i__2 = *nrhs; for (jcol = 1; jcol <= i__2; ++jcol) { i__3 = nrf + nr - 1; for (jrow = nrf; jrow <= i__3; ++jrow) { ++j; i__4 = jrow + jcol * b_dim1; rwork[j] = b[i__4].r; /* L70: */ } /* L80: */ } dgemm_("T", "N", &nr, nrhs, &nr, &c_b1015, &u[nrf + u_dim1], ldu, & rwork[((nr * *nrhs) << (1)) + 1], &nr, &c_b324, &rwork[1], & nr); j = (nr * *nrhs) << (1); i__2 = *nrhs; for (jcol = 1; jcol <= i__2; ++jcol) { i__3 = nrf + nr - 1; for (jrow = nrf; jrow <= i__3; ++jrow) { ++j; rwork[j] = d_imag(&b[jrow + jcol * b_dim1]); /* L90: */ } /* L100: */ } dgemm_("T", "N", &nr, nrhs, &nr, &c_b1015, &u[nrf + u_dim1], ldu, & rwork[((nr * *nrhs) << (1)) + 1], &nr, &c_b324, &rwork[nr * * nrhs + 1], &nr); jreal = 0; jimag = nr * *nrhs; i__2 = *nrhs; for (jcol = 1; jcol <= i__2; ++jcol) { i__3 = nrf + nr - 1; for (jrow = nrf; jrow <= i__3; ++jrow) { ++jreal; ++jimag; i__4 = jrow + jcol * bx_dim1; i__5 = jreal; i__6 = jimag; z__1.r = rwork[i__5], z__1.i = rwork[i__6]; bx[i__4].r = z__1.r, bx[i__4].i = z__1.i; /* L110: */ } /* L120: */ } /* L130: */ } /* Next copy the rows of B that correspond to unchanged rows in the bidiagonal matrix to BX. */ i__1 = nd; for (i__ = 1; i__ <= i__1; ++i__) { ic = iwork[inode + i__ - 1]; zcopy_(nrhs, &b[ic + b_dim1], ldb, &bx[ic + bx_dim1], ldbx); /* L140: */ } /* Finally go through the left singular vector matrices of all the other subproblems bottom-up on the tree. */ j = pow_ii(&c__2, &nlvl); sqre = 0; for (lvl = nlvl; lvl >= 1; --lvl) { lvl2 = ((lvl) << (1)) - 1; /* find the first node LF and last node LL on the current level LVL */ if (lvl == 1) { lf = 1; ll = 1; } else { i__1 = lvl - 1; lf = pow_ii(&c__2, &i__1); ll = ((lf) << (1)) - 1; } i__1 = ll; for (i__ = lf; i__ <= i__1; ++i__) { im1 = i__ - 1; ic = iwork[inode + im1]; nl = iwork[ndiml + im1]; nr = iwork[ndimr + im1]; nlf = ic - nl; nrf = ic + 1; --j; zlals0_(icompq, &nl, &nr, &sqre, nrhs, &bx[nlf + bx_dim1], ldbx, & b[nlf + b_dim1], ldb, &perm[nlf + lvl * perm_dim1], & givptr[j], &givcol[nlf + lvl2 * givcol_dim1], ldgcol, & givnum[nlf + lvl2 * givnum_dim1], ldu, &poles[nlf + lvl2 * poles_dim1], &difl[nlf + lvl * difl_dim1], &difr[nlf + lvl2 * difr_dim1], &z__[nlf + lvl * z_dim1], &k[j], &c__[ j], &s[j], &rwork[1], info); /* L150: */ } /* L160: */ } goto L330; /* ICOMPQ = 1: applying back the right singular vector factors. */ L170: /* First now go through the right singular vector matrices of all the tree nodes top-down. */ j = 0; i__1 = nlvl; for (lvl = 1; lvl <= i__1; ++lvl) { lvl2 = ((lvl) << (1)) - 1; /* Find the first node LF and last node LL on the current level LVL. */ if (lvl == 1) { lf = 1; ll = 1; } else { i__2 = lvl - 1; lf = pow_ii(&c__2, &i__2); ll = ((lf) << (1)) - 1; } i__2 = lf; for (i__ = ll; i__ >= i__2; --i__) { im1 = i__ - 1; ic = iwork[inode + im1]; nl = iwork[ndiml + im1]; nr = iwork[ndimr + im1]; nlf = ic - nl; nrf = ic + 1; if (i__ == ll) { sqre = 0; } else { sqre = 1; } ++j; zlals0_(icompq, &nl, &nr, &sqre, nrhs, &b[nlf + b_dim1], ldb, &bx[ nlf + bx_dim1], ldbx, &perm[nlf + lvl * perm_dim1], & givptr[j], &givcol[nlf + lvl2 * givcol_dim1], ldgcol, & givnum[nlf + lvl2 * givnum_dim1], ldu, &poles[nlf + lvl2 * poles_dim1], &difl[nlf + lvl * difl_dim1], &difr[nlf + lvl2 * difr_dim1], &z__[nlf + lvl * z_dim1], &k[j], &c__[ j], &s[j], &rwork[1], info); /* L180: */ } /* L190: */ } /* The nodes on the bottom level of the tree were solved by DLASDQ. The corresponding right singular vector matrices are in explicit form. Apply them back. */ ndb1 = (nd + 1) / 2; i__1 = nd; for (i__ = ndb1; i__ <= i__1; ++i__) { i1 = i__ - 1; ic = iwork[inode + i1]; nl = iwork[ndiml + i1]; nr = iwork[ndimr + i1]; nlp1 = nl + 1; if (i__ == nd) { nrp1 = nr; } else { nrp1 = nr + 1; } nlf = ic - nl; nrf = ic + 1; /* Since B and BX are complex, the following call to DGEMM is performed in two steps (real and imaginary parts). CALL DGEMM( 'T', 'N', NLP1, NRHS, NLP1, ONE, VT( NLF, 1 ), LDU, $ B( NLF, 1 ), LDB, ZERO, BX( NLF, 1 ), LDBX ) */ j = (nlp1 * *nrhs) << (1); i__2 = *nrhs; for (jcol = 1; jcol <= i__2; ++jcol) { i__3 = nlf + nlp1 - 1; for (jrow = nlf; jrow <= i__3; ++jrow) { ++j; i__4 = jrow + jcol * b_dim1; rwork[j] = b[i__4].r; /* L200: */ } /* L210: */ } dgemm_("T", "N", &nlp1, nrhs, &nlp1, &c_b1015, &vt[nlf + vt_dim1], ldu, &rwork[((nlp1 * *nrhs) << (1)) + 1], &nlp1, &c_b324, & rwork[1], &nlp1); j = (nlp1 * *nrhs) << (1); i__2 = *nrhs; for (jcol = 1; jcol <= i__2; ++jcol) { i__3 = nlf + nlp1 - 1; for (jrow = nlf; jrow <= i__3; ++jrow) { ++j; rwork[j] = d_imag(&b[jrow + jcol * b_dim1]); /* L220: */ } /* L230: */ } dgemm_("T", "N", &nlp1, nrhs, &nlp1, &c_b1015, &vt[nlf + vt_dim1], ldu, &rwork[((nlp1 * *nrhs) << (1)) + 1], &nlp1, &c_b324, & rwork[nlp1 * *nrhs + 1], &nlp1); jreal = 0; jimag = nlp1 * *nrhs; i__2 = *nrhs; for (jcol = 1; jcol <= i__2; ++jcol) { i__3 = nlf + nlp1 - 1; for (jrow = nlf; jrow <= i__3; ++jrow) { ++jreal; ++jimag; i__4 = jrow + jcol * bx_dim1; i__5 = jreal; i__6 = jimag; z__1.r = rwork[i__5], z__1.i = rwork[i__6]; bx[i__4].r = z__1.r, bx[i__4].i = z__1.i; /* L240: */ } /* L250: */ } /* Since B and BX are complex, the following call to DGEMM is performed in two steps (real and imaginary parts). CALL DGEMM( 'T', 'N', NRP1, NRHS, NRP1, ONE, VT( NRF, 1 ), LDU, $ B( NRF, 1 ), LDB, ZERO, BX( NRF, 1 ), LDBX ) */ j = (nrp1 * *nrhs) << (1); i__2 = *nrhs; for (jcol = 1; jcol <= i__2; ++jcol) { i__3 = nrf + nrp1 - 1; for (jrow = nrf; jrow <= i__3; ++jrow) { ++j; i__4 = jrow + jcol * b_dim1; rwork[j] = b[i__4].r; /* L260: */ } /* L270: */ } dgemm_("T", "N", &nrp1, nrhs, &nrp1, &c_b1015, &vt[nrf + vt_dim1], ldu, &rwork[((nrp1 * *nrhs) << (1)) + 1], &nrp1, &c_b324, & rwork[1], &nrp1); j = (nrp1 * *nrhs) << (1); i__2 = *nrhs; for (jcol = 1; jcol <= i__2; ++jcol) { i__3 = nrf + nrp1 - 1; for (jrow = nrf; jrow <= i__3; ++jrow) { ++j; rwork[j] = d_imag(&b[jrow + jcol * b_dim1]); /* L280: */ } /* L290: */ } dgemm_("T", "N", &nrp1, nrhs, &nrp1, &c_b1015, &vt[nrf + vt_dim1], ldu, &rwork[((nrp1 * *nrhs) << (1)) + 1], &nrp1, &c_b324, & rwork[nrp1 * *nrhs + 1], &nrp1); jreal = 0; jimag = nrp1 * *nrhs; i__2 = *nrhs; for (jcol = 1; jcol <= i__2; ++jcol) { i__3 = nrf + nrp1 - 1; for (jrow = nrf; jrow <= i__3; ++jrow) { ++jreal; ++jimag; i__4 = jrow + jcol * bx_dim1; i__5 = jreal; i__6 = jimag; z__1.r = rwork[i__5], z__1.i = rwork[i__6]; bx[i__4].r = z__1.r, bx[i__4].i = z__1.i; /* L300: */ } /* L310: */ } /* L320: */ } L330: return 0; /* End of ZLALSA */ } /* zlalsa_ */ /* Subroutine */ int zlalsd_(char *uplo, integer *smlsiz, integer *n, integer *nrhs, doublereal *d__, doublereal *e, doublecomplex *b, integer *ldb, doublereal *rcond, integer *rank, doublecomplex *work, doublereal * rwork, integer *iwork, integer *info) { /* System generated locals */ integer b_dim1, b_offset, i__1, i__2, i__3, i__4, i__5, i__6; doublereal d__1; doublecomplex z__1; /* Builtin functions */ double d_imag(doublecomplex *), log(doublereal), d_sign(doublereal *, doublereal *); /* Local variables */ static integer c__, i__, j, k; static doublereal r__; static integer s, u, z__; static doublereal cs; static integer bx; static doublereal sn; static integer st, vt, nm1, st1; static doublereal eps; static integer iwk; static doublereal tol; static integer difl, difr, jcol, irwb, perm, nsub, nlvl, sqre, bxst, jrow, irwu, jimag; extern /* Subroutine */ int dgemm_(char *, char *, integer *, integer *, integer *, doublereal *, doublereal *, integer *, doublereal *, integer *, doublereal *, doublereal *, integer *); static integer jreal, irwib, poles, sizei, irwrb, nsize; extern /* Subroutine */ int zdrot_(integer *, doublecomplex *, integer *, doublecomplex *, integer *, doublereal *, doublereal *), zcopy_( integer *, doublecomplex *, integer *, doublecomplex *, integer *) ; static integer irwvt, icmpq1, icmpq2; extern /* Subroutine */ int dlasda_(integer *, integer *, integer *, integer *, doublereal *, doublereal *, doublereal *, integer *, doublereal *, integer *, doublereal *, doublereal *, doublereal *, doublereal *, integer *, integer *, integer *, integer *, doublereal *, doublereal *, doublereal *, doublereal *, integer *, integer *), dlascl_(char *, integer *, integer *, doublereal *, doublereal *, integer *, integer *, doublereal *, integer *, integer *); extern integer idamax_(integer *, doublereal *, integer *); extern /* Subroutine */ int dlasdq_(char *, integer *, integer *, integer *, integer *, integer *, doublereal *, doublereal *, doublereal *, integer *, doublereal *, integer *, doublereal *, integer *, doublereal *, integer *), dlaset_(char *, integer *, integer *, doublereal *, doublereal *, doublereal *, integer *), dlartg_(doublereal *, doublereal *, doublereal *, doublereal *, doublereal *), xerbla_(char *, integer *); static integer givcol; extern doublereal dlanst_(char *, integer *, doublereal *, doublereal *); extern /* Subroutine */ int zlalsa_(integer *, integer *, integer *, integer *, doublecomplex *, integer *, doublecomplex *, integer *, doublereal *, integer *, doublereal *, integer *, doublereal *, doublereal *, doublereal *, doublereal *, integer *, integer *, integer *, integer *, doublereal *, doublereal *, doublereal *, doublereal *, integer *, integer *), zlascl_(char *, integer *, integer *, doublereal *, doublereal *, integer *, integer *, doublecomplex *, integer *, integer *), dlasrt_(char *, integer *, doublereal *, integer *), zlacpy_(char *, integer *, integer *, doublecomplex *, integer *, doublecomplex *, integer *), zlaset_(char *, integer *, integer *, doublecomplex *, doublecomplex *, doublecomplex *, integer *); static doublereal orgnrm; static integer givnum, givptr, nrwork, irwwrk, smlszp; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University October 31, 1999 Purpose ======= ZLALSD uses the singular value decomposition of A to solve the least squares problem of finding X to minimize the Euclidean norm of each column of A*X-B, where A is N-by-N upper bidiagonal, and X and B are N-by-NRHS. The solution X overwrites B. The singular values of A smaller than RCOND times the largest singular value are treated as zero in solving the least squares problem; in this case a minimum norm solution is returned. The actual singular values are returned in D in ascending order. This code makes very mild assumptions about floating point arithmetic. It will work on machines with a guard digit in add/subtract, or on those binary machines without guard digits which subtract like the Cray XMP, Cray YMP, Cray C 90, or Cray 2. It could conceivably fail on hexadecimal or decimal machines without guard digits, but we know of none. Arguments ========= UPLO (input) CHARACTER*1 = 'U': D and E define an upper bidiagonal matrix. = 'L': D and E define a lower bidiagonal matrix. SMLSIZ (input) INTEGER The maximum size of the subproblems at the bottom of the computation tree. N (input) INTEGER The dimension of the bidiagonal matrix. N >= 0. NRHS (input) INTEGER The number of columns of B. NRHS must be at least 1. D (input/output) DOUBLE PRECISION array, dimension (N) On entry D contains the main diagonal of the bidiagonal matrix. On exit, if INFO = 0, D contains its singular values. E (input) DOUBLE PRECISION array, dimension (N-1) Contains the super-diagonal entries of the bidiagonal matrix. On exit, E has been destroyed. B (input/output) COMPLEX*16 array, dimension (LDB,NRHS) On input, B contains the right hand sides of the least squares problem. On output, B contains the solution X. LDB (input) INTEGER The leading dimension of B in the calling subprogram. LDB must be at least max(1,N). RCOND (input) DOUBLE PRECISION The singular values of A less than or equal to RCOND times the largest singular value are treated as zero in solving the least squares problem. If RCOND is negative, machine precision is used instead. For example, if diag(S)*X=B were the least squares problem, where diag(S) is a diagonal matrix of singular values, the solution would be X(i) = B(i) / S(i) if S(i) is greater than RCOND*max(S), and X(i) = 0 if S(i) is less than or equal to RCOND*max(S). RANK (output) INTEGER The number of singular values of A greater than RCOND times the largest singular value. WORK (workspace) COMPLEX*16 array, dimension at least (N * NRHS). RWORK (workspace) DOUBLE PRECISION array, dimension at least (9*N + 2*N*SMLSIZ + 8*N*NLVL + 3*SMLSIZ*NRHS + (SMLSIZ+1)**2), where NLVL = MAX( 0, INT( LOG_2( MIN( M,N )/(SMLSIZ+1) ) ) + 1 ) IWORK (workspace) INTEGER array, dimension at least (3*N*NLVL + 11*N). INFO (output) INTEGER = 0: successful exit. < 0: if INFO = -i, the i-th argument had an illegal value. > 0: The algorithm failed to compute an singular value while working on the submatrix lying in rows and columns INFO/(N+1) through MOD(INFO,N+1). Further Details =============== Based on contributions by Ming Gu and Ren-Cang Li, Computer Science Division, University of California at Berkeley, USA Osni Marques, LBNL/NERSC, USA ===================================================================== Test the input parameters. */ /* Parameter adjustments */ --d__; --e; b_dim1 = *ldb; b_offset = 1 + b_dim1; b -= b_offset; --work; --rwork; --iwork; /* Function Body */ *info = 0; if (*n < 0) { *info = -3; } else if (*nrhs < 1) { *info = -4; } else if ((*ldb < 1) || (*ldb < *n)) { *info = -8; } if (*info != 0) { i__1 = -(*info); xerbla_("ZLALSD", &i__1); return 0; } eps = EPSILON; /* Set up the tolerance. */ if ((*rcond <= 0.) || (*rcond >= 1.)) { *rcond = eps; } *rank = 0; /* Quick return if possible. */ if (*n == 0) { return 0; } else if (*n == 1) { if (d__[1] == 0.) { zlaset_("A", &c__1, nrhs, &c_b59, &c_b59, &b[b_offset], ldb); } else { *rank = 1; zlascl_("G", &c__0, &c__0, &d__[1], &c_b1015, &c__1, nrhs, &b[ b_offset], ldb, info); d__[1] = abs(d__[1]); } return 0; } /* Rotate the matrix if it is lower bidiagonal. */ if (*(unsigned char *)uplo == 'L') { i__1 = *n - 1; for (i__ = 1; i__ <= i__1; ++i__) { dlartg_(&d__[i__], &e[i__], &cs, &sn, &r__); d__[i__] = r__; e[i__] = sn * d__[i__ + 1]; d__[i__ + 1] = cs * d__[i__ + 1]; if (*nrhs == 1) { zdrot_(&c__1, &b[i__ + b_dim1], &c__1, &b[i__ + 1 + b_dim1], & c__1, &cs, &sn); } else { rwork[((i__) << (1)) - 1] = cs; rwork[i__ * 2] = sn; } /* L10: */ } if (*nrhs > 1) { i__1 = *nrhs; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = *n - 1; for (j = 1; j <= i__2; ++j) { cs = rwork[((j) << (1)) - 1]; sn = rwork[j * 2]; zdrot_(&c__1, &b[j + i__ * b_dim1], &c__1, &b[j + 1 + i__ * b_dim1], &c__1, &cs, &sn); /* L20: */ } /* L30: */ } } } /* Scale. */ nm1 = *n - 1; orgnrm = dlanst_("M", n, &d__[1], &e[1]); if (orgnrm == 0.) { zlaset_("A", n, nrhs, &c_b59, &c_b59, &b[b_offset], ldb); return 0; } dlascl_("G", &c__0, &c__0, &orgnrm, &c_b1015, n, &c__1, &d__[1], n, info); dlascl_("G", &c__0, &c__0, &orgnrm, &c_b1015, &nm1, &c__1, &e[1], &nm1, info); /* If N is smaller than the minimum divide size SMLSIZ, then solve the problem with another solver. */ if (*n <= *smlsiz) { irwu = 1; irwvt = irwu + *n * *n; irwwrk = irwvt + *n * *n; irwrb = irwwrk; irwib = irwrb + *n * *nrhs; irwb = irwib + *n * *nrhs; dlaset_("A", n, n, &c_b324, &c_b1015, &rwork[irwu], n); dlaset_("A", n, n, &c_b324, &c_b1015, &rwork[irwvt], n); dlasdq_("U", &c__0, n, n, n, &c__0, &d__[1], &e[1], &rwork[irwvt], n, &rwork[irwu], n, &rwork[irwwrk], &c__1, &rwork[irwwrk], info); if (*info != 0) { return 0; } /* In the real version, B is passed to DLASDQ and multiplied internally by Q'. Here B is complex and that product is computed below in two steps (real and imaginary parts). */ j = irwb - 1; i__1 = *nrhs; for (jcol = 1; jcol <= i__1; ++jcol) { i__2 = *n; for (jrow = 1; jrow <= i__2; ++jrow) { ++j; i__3 = jrow + jcol * b_dim1; rwork[j] = b[i__3].r; /* L40: */ } /* L50: */ } dgemm_("T", "N", n, nrhs, n, &c_b1015, &rwork[irwu], n, &rwork[irwb], n, &c_b324, &rwork[irwrb], n); j = irwb - 1; i__1 = *nrhs; for (jcol = 1; jcol <= i__1; ++jcol) { i__2 = *n; for (jrow = 1; jrow <= i__2; ++jrow) { ++j; rwork[j] = d_imag(&b[jrow + jcol * b_dim1]); /* L60: */ } /* L70: */ } dgemm_("T", "N", n, nrhs, n, &c_b1015, &rwork[irwu], n, &rwork[irwb], n, &c_b324, &rwork[irwib], n); jreal = irwrb - 1; jimag = irwib - 1; i__1 = *nrhs; for (jcol = 1; jcol <= i__1; ++jcol) { i__2 = *n; for (jrow = 1; jrow <= i__2; ++jrow) { ++jreal; ++jimag; i__3 = jrow + jcol * b_dim1; i__4 = jreal; i__5 = jimag; z__1.r = rwork[i__4], z__1.i = rwork[i__5]; b[i__3].r = z__1.r, b[i__3].i = z__1.i; /* L80: */ } /* L90: */ } tol = *rcond * (d__1 = d__[idamax_(n, &d__[1], &c__1)], abs(d__1)); i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { if (d__[i__] <= tol) { zlaset_("A", &c__1, nrhs, &c_b59, &c_b59, &b[i__ + b_dim1], ldb); } else { zlascl_("G", &c__0, &c__0, &d__[i__], &c_b1015, &c__1, nrhs, & b[i__ + b_dim1], ldb, info); ++(*rank); } /* L100: */ } /* Since B is complex, the following call to DGEMM is performed in two steps (real and imaginary parts). That is for V * B (in the real version of the code V' is stored in WORK). CALL DGEMM( 'T', 'N', N, NRHS, N, ONE, WORK, N, B, LDB, ZERO, $ WORK( NWORK ), N ) */ j = irwb - 1; i__1 = *nrhs; for (jcol = 1; jcol <= i__1; ++jcol) { i__2 = *n; for (jrow = 1; jrow <= i__2; ++jrow) { ++j; i__3 = jrow + jcol * b_dim1; rwork[j] = b[i__3].r; /* L110: */ } /* L120: */ } dgemm_("T", "N", n, nrhs, n, &c_b1015, &rwork[irwvt], n, &rwork[irwb], n, &c_b324, &rwork[irwrb], n); j = irwb - 1; i__1 = *nrhs; for (jcol = 1; jcol <= i__1; ++jcol) { i__2 = *n; for (jrow = 1; jrow <= i__2; ++jrow) { ++j; rwork[j] = d_imag(&b[jrow + jcol * b_dim1]); /* L130: */ } /* L140: */ } dgemm_("T", "N", n, nrhs, n, &c_b1015, &rwork[irwvt], n, &rwork[irwb], n, &c_b324, &rwork[irwib], n); jreal = irwrb - 1; jimag = irwib - 1; i__1 = *nrhs; for (jcol = 1; jcol <= i__1; ++jcol) { i__2 = *n; for (jrow = 1; jrow <= i__2; ++jrow) { ++jreal; ++jimag; i__3 = jrow + jcol * b_dim1; i__4 = jreal; i__5 = jimag; z__1.r = rwork[i__4], z__1.i = rwork[i__5]; b[i__3].r = z__1.r, b[i__3].i = z__1.i; /* L150: */ } /* L160: */ } /* Unscale. */ dlascl_("G", &c__0, &c__0, &c_b1015, &orgnrm, n, &c__1, &d__[1], n, info); dlasrt_("D", n, &d__[1], info); zlascl_("G", &c__0, &c__0, &orgnrm, &c_b1015, n, nrhs, &b[b_offset], ldb, info); return 0; } /* Book-keeping and setting up some constants. */ nlvl = (integer) (log((doublereal) (*n) / (doublereal) (*smlsiz + 1)) / log(2.)) + 1; smlszp = *smlsiz + 1; u = 1; vt = *smlsiz * *n + 1; difl = vt + smlszp * *n; difr = difl + nlvl * *n; z__ = difr + ((nlvl * *n) << (1)); c__ = z__ + nlvl * *n; s = c__ + *n; poles = s + *n; givnum = poles + ((nlvl) << (1)) * *n; nrwork = givnum + ((nlvl) << (1)) * *n; bx = 1; irwrb = nrwork; irwib = irwrb + *smlsiz * *nrhs; irwb = irwib + *smlsiz * *nrhs; sizei = *n + 1; k = sizei + *n; givptr = k + *n; perm = givptr + *n; givcol = perm + nlvl * *n; iwk = givcol + ((nlvl * *n) << (1)); st = 1; sqre = 0; icmpq1 = 1; icmpq2 = 0; nsub = 0; i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { if ((d__1 = d__[i__], abs(d__1)) < eps) { d__[i__] = d_sign(&eps, &d__[i__]); } /* L170: */ } i__1 = nm1; for (i__ = 1; i__ <= i__1; ++i__) { if (((d__1 = e[i__], abs(d__1)) < eps) || (i__ == nm1)) { ++nsub; iwork[nsub] = st; /* Subproblem found. First determine its size and then apply divide and conquer on it. */ if (i__ < nm1) { /* A subproblem with E(I) small for I < NM1. */ nsize = i__ - st + 1; iwork[sizei + nsub - 1] = nsize; } else if ((d__1 = e[i__], abs(d__1)) >= eps) { /* A subproblem with E(NM1) not too small but I = NM1. */ nsize = *n - st + 1; iwork[sizei + nsub - 1] = nsize; } else { /* A subproblem with E(NM1) small. This implies an 1-by-1 subproblem at D(N), which is not solved explicitly. */ nsize = i__ - st + 1; iwork[sizei + nsub - 1] = nsize; ++nsub; iwork[nsub] = *n; iwork[sizei + nsub - 1] = 1; zcopy_(nrhs, &b[*n + b_dim1], ldb, &work[bx + nm1], n); } st1 = st - 1; if (nsize == 1) { /* This is a 1-by-1 subproblem and is not solved explicitly. */ zcopy_(nrhs, &b[st + b_dim1], ldb, &work[bx + st1], n); } else if (nsize <= *smlsiz) { /* This is a small subproblem and is solved by DLASDQ. */ dlaset_("A", &nsize, &nsize, &c_b324, &c_b1015, &rwork[vt + st1], n); dlaset_("A", &nsize, &nsize, &c_b324, &c_b1015, &rwork[u + st1], n); dlasdq_("U", &c__0, &nsize, &nsize, &nsize, &c__0, &d__[st], & e[st], &rwork[vt + st1], n, &rwork[u + st1], n, & rwork[nrwork], &c__1, &rwork[nrwork], info) ; if (*info != 0) { return 0; } /* In the real version, B is passed to DLASDQ and multiplied internally by Q'. Here B is complex and that product is computed below in two steps (real and imaginary parts). */ j = irwb - 1; i__2 = *nrhs; for (jcol = 1; jcol <= i__2; ++jcol) { i__3 = st + nsize - 1; for (jrow = st; jrow <= i__3; ++jrow) { ++j; i__4 = jrow + jcol * b_dim1; rwork[j] = b[i__4].r; /* L180: */ } /* L190: */ } dgemm_("T", "N", &nsize, nrhs, &nsize, &c_b1015, &rwork[u + st1], n, &rwork[irwb], &nsize, &c_b324, &rwork[irwrb], &nsize); j = irwb - 1; i__2 = *nrhs; for (jcol = 1; jcol <= i__2; ++jcol) { i__3 = st + nsize - 1; for (jrow = st; jrow <= i__3; ++jrow) { ++j; rwork[j] = d_imag(&b[jrow + jcol * b_dim1]); /* L200: */ } /* L210: */ } dgemm_("T", "N", &nsize, nrhs, &nsize, &c_b1015, &rwork[u + st1], n, &rwork[irwb], &nsize, &c_b324, &rwork[irwib], &nsize); jreal = irwrb - 1; jimag = irwib - 1; i__2 = *nrhs; for (jcol = 1; jcol <= i__2; ++jcol) { i__3 = st + nsize - 1; for (jrow = st; jrow <= i__3; ++jrow) { ++jreal; ++jimag; i__4 = jrow + jcol * b_dim1; i__5 = jreal; i__6 = jimag; z__1.r = rwork[i__5], z__1.i = rwork[i__6]; b[i__4].r = z__1.r, b[i__4].i = z__1.i; /* L220: */ } /* L230: */ } zlacpy_("A", &nsize, nrhs, &b[st + b_dim1], ldb, &work[bx + st1], n); } else { /* A large problem. Solve it using divide and conquer. */ dlasda_(&icmpq1, smlsiz, &nsize, &sqre, &d__[st], &e[st], & rwork[u + st1], n, &rwork[vt + st1], &iwork[k + st1], &rwork[difl + st1], &rwork[difr + st1], &rwork[z__ + st1], &rwork[poles + st1], &iwork[givptr + st1], & iwork[givcol + st1], n, &iwork[perm + st1], &rwork[ givnum + st1], &rwork[c__ + st1], &rwork[s + st1], & rwork[nrwork], &iwork[iwk], info); if (*info != 0) { return 0; } bxst = bx + st1; zlalsa_(&icmpq2, smlsiz, &nsize, nrhs, &b[st + b_dim1], ldb, & work[bxst], n, &rwork[u + st1], n, &rwork[vt + st1], & iwork[k + st1], &rwork[difl + st1], &rwork[difr + st1] , &rwork[z__ + st1], &rwork[poles + st1], &iwork[ givptr + st1], &iwork[givcol + st1], n, &iwork[perm + st1], &rwork[givnum + st1], &rwork[c__ + st1], &rwork[ s + st1], &rwork[nrwork], &iwork[iwk], info); if (*info != 0) { return 0; } } st = i__ + 1; } /* L240: */ } /* Apply the singular values and treat the tiny ones as zero. */ tol = *rcond * (d__1 = d__[idamax_(n, &d__[1], &c__1)], abs(d__1)); i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { /* Some of the elements in D can be negative because 1-by-1 subproblems were not solved explicitly. */ if ((d__1 = d__[i__], abs(d__1)) <= tol) { zlaset_("A", &c__1, nrhs, &c_b59, &c_b59, &work[bx + i__ - 1], n); } else { ++(*rank); zlascl_("G", &c__0, &c__0, &d__[i__], &c_b1015, &c__1, nrhs, & work[bx + i__ - 1], n, info); } d__[i__] = (d__1 = d__[i__], abs(d__1)); /* L250: */ } /* Now apply back the right singular vectors. */ icmpq2 = 1; i__1 = nsub; for (i__ = 1; i__ <= i__1; ++i__) { st = iwork[i__]; st1 = st - 1; nsize = iwork[sizei + i__ - 1]; bxst = bx + st1; if (nsize == 1) { zcopy_(nrhs, &work[bxst], n, &b[st + b_dim1], ldb); } else if (nsize <= *smlsiz) { /* Since B and BX are complex, the following call to DGEMM is performed in two steps (real and imaginary parts). CALL DGEMM( 'T', 'N', NSIZE, NRHS, NSIZE, ONE, $ RWORK( VT+ST1 ), N, RWORK( BXST ), N, ZERO, $ B( ST, 1 ), LDB ) */ j = bxst - *n - 1; jreal = irwb - 1; i__2 = *nrhs; for (jcol = 1; jcol <= i__2; ++jcol) { j += *n; i__3 = nsize; for (jrow = 1; jrow <= i__3; ++jrow) { ++jreal; i__4 = j + jrow; rwork[jreal] = work[i__4].r; /* L260: */ } /* L270: */ } dgemm_("T", "N", &nsize, nrhs, &nsize, &c_b1015, &rwork[vt + st1], n, &rwork[irwb], &nsize, &c_b324, &rwork[irwrb], &nsize); j = bxst - *n - 1; jimag = irwb - 1; i__2 = *nrhs; for (jcol = 1; jcol <= i__2; ++jcol) { j += *n; i__3 = nsize; for (jrow = 1; jrow <= i__3; ++jrow) { ++jimag; rwork[jimag] = d_imag(&work[j + jrow]); /* L280: */ } /* L290: */ } dgemm_("T", "N", &nsize, nrhs, &nsize, &c_b1015, &rwork[vt + st1], n, &rwork[irwb], &nsize, &c_b324, &rwork[irwib], &nsize); jreal = irwrb - 1; jimag = irwib - 1; i__2 = *nrhs; for (jcol = 1; jcol <= i__2; ++jcol) { i__3 = st + nsize - 1; for (jrow = st; jrow <= i__3; ++jrow) { ++jreal; ++jimag; i__4 = jrow + jcol * b_dim1; i__5 = jreal; i__6 = jimag; z__1.r = rwork[i__5], z__1.i = rwork[i__6]; b[i__4].r = z__1.r, b[i__4].i = z__1.i; /* L300: */ } /* L310: */ } } else { zlalsa_(&icmpq2, smlsiz, &nsize, nrhs, &work[bxst], n, &b[st + b_dim1], ldb, &rwork[u + st1], n, &rwork[vt + st1], & iwork[k + st1], &rwork[difl + st1], &rwork[difr + st1], & rwork[z__ + st1], &rwork[poles + st1], &iwork[givptr + st1], &iwork[givcol + st1], n, &iwork[perm + st1], &rwork[ givnum + st1], &rwork[c__ + st1], &rwork[s + st1], &rwork[ nrwork], &iwork[iwk], info); if (*info != 0) { return 0; } } /* L320: */ } /* Unscale and sort the singular values. */ dlascl_("G", &c__0, &c__0, &c_b1015, &orgnrm, n, &c__1, &d__[1], n, info); dlasrt_("D", n, &d__[1], info); zlascl_("G", &c__0, &c__0, &orgnrm, &c_b1015, n, nrhs, &b[b_offset], ldb, info); return 0; /* End of ZLALSD */ } /* zlalsd_ */ doublereal zlange_(char *norm, integer *m, integer *n, doublecomplex *a, integer *lda, doublereal *work) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2; doublereal ret_val, d__1, d__2; /* Builtin functions */ double z_abs(doublecomplex *), sqrt(doublereal); /* Local variables */ static integer i__, j; static doublereal sum, scale; extern logical lsame_(char *, char *); static doublereal value; extern /* Subroutine */ int zlassq_(integer *, doublecomplex *, integer *, doublereal *, doublereal *); /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University October 31, 1992 Purpose ======= ZLANGE returns the value of the one norm, or the Frobenius norm, or the infinity norm, or the element of largest absolute value of a complex matrix A. Description =========== ZLANGE returns the value ZLANGE = ( max(abs(A(i,j))), NORM = 'M' or 'm' ( ( norm1(A), NORM = '1', 'O' or 'o' ( ( normI(A), NORM = 'I' or 'i' ( ( normF(A), NORM = 'F', 'f', 'E' or 'e' where norm1 denotes the one norm of a matrix (maximum column sum), normI denotes the infinity norm of a matrix (maximum row sum) and normF denotes the Frobenius norm of a matrix (square root of sum of squares). Note that max(abs(A(i,j))) is not a matrix norm. Arguments ========= NORM (input) CHARACTER*1 Specifies the value to be returned in ZLANGE as described above. M (input) INTEGER The number of rows of the matrix A. M >= 0. When M = 0, ZLANGE is set to zero. N (input) INTEGER The number of columns of the matrix A. N >= 0. When N = 0, ZLANGE is set to zero. A (input) COMPLEX*16 array, dimension (LDA,N) The m by n matrix A. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(M,1). WORK (workspace) DOUBLE PRECISION array, dimension (LWORK), where LWORK >= M when NORM = 'I'; otherwise, WORK is not referenced. ===================================================================== */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --work; /* Function Body */ if (min(*m,*n) == 0) { value = 0.; } else if (lsame_(norm, "M")) { /* Find max(abs(A(i,j))). */ value = 0.; i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { /* Computing MAX */ d__1 = value, d__2 = z_abs(&a[i__ + j * a_dim1]); value = max(d__1,d__2); /* L10: */ } /* L20: */ } } else if ((lsame_(norm, "O")) || (*(unsigned char * )norm == '1')) { /* Find norm1(A). */ value = 0.; i__1 = *n; for (j = 1; j <= i__1; ++j) { sum = 0.; i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { sum += z_abs(&a[i__ + j * a_dim1]); /* L30: */ } value = max(value,sum); /* L40: */ } } else if (lsame_(norm, "I")) { /* Find normI(A). */ i__1 = *m; for (i__ = 1; i__ <= i__1; ++i__) { work[i__] = 0.; /* L50: */ } i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { work[i__] += z_abs(&a[i__ + j * a_dim1]); /* L60: */ } /* L70: */ } value = 0.; i__1 = *m; for (i__ = 1; i__ <= i__1; ++i__) { /* Computing MAX */ d__1 = value, d__2 = work[i__]; value = max(d__1,d__2); /* L80: */ } } else if ((lsame_(norm, "F")) || (lsame_(norm, "E"))) { /* Find normF(A). */ scale = 0.; sum = 1.; i__1 = *n; for (j = 1; j <= i__1; ++j) { zlassq_(m, &a[j * a_dim1 + 1], &c__1, &scale, &sum); /* L90: */ } value = scale * sqrt(sum); } ret_val = value; return ret_val; /* End of ZLANGE */ } /* zlange_ */ doublereal zlanhe_(char *norm, char *uplo, integer *n, doublecomplex *a, integer *lda, doublereal *work) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2; doublereal ret_val, d__1, d__2, d__3; /* Builtin functions */ double z_abs(doublecomplex *), sqrt(doublereal); /* Local variables */ static integer i__, j; static doublereal sum, absa, scale; extern logical lsame_(char *, char *); static doublereal value; extern /* Subroutine */ int zlassq_(integer *, doublecomplex *, integer *, doublereal *, doublereal *); /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University October 31, 1992 Purpose ======= ZLANHE returns the value of the one norm, or the Frobenius norm, or the infinity norm, or the element of largest absolute value of a complex hermitian matrix A. Description =========== ZLANHE returns the value ZLANHE = ( max(abs(A(i,j))), NORM = 'M' or 'm' ( ( norm1(A), NORM = '1', 'O' or 'o' ( ( normI(A), NORM = 'I' or 'i' ( ( normF(A), NORM = 'F', 'f', 'E' or 'e' where norm1 denotes the one norm of a matrix (maximum column sum), normI denotes the infinity norm of a matrix (maximum row sum) and normF denotes the Frobenius norm of a matrix (square root of sum of squares). Note that max(abs(A(i,j))) is not a matrix norm. Arguments ========= NORM (input) CHARACTER*1 Specifies the value to be returned in ZLANHE as described above. UPLO (input) CHARACTER*1 Specifies whether the upper or lower triangular part of the hermitian matrix A is to be referenced. = 'U': Upper triangular part of A is referenced = 'L': Lower triangular part of A is referenced N (input) INTEGER The order of the matrix A. N >= 0. When N = 0, ZLANHE is set to zero. A (input) COMPLEX*16 array, dimension (LDA,N) 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, and the strictly lower triangular part of A is not referenced. If UPLO = 'L', the leading n by n lower triangular part of A contains the lower triangular part of the matrix A, and the strictly upper triangular part of A is not referenced. Note that the imaginary parts of the diagonal elements need not be set and are assumed to be zero. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(N,1). WORK (workspace) DOUBLE PRECISION array, dimension (LWORK), where LWORK >= N when NORM = 'I' or '1' or 'O'; otherwise, WORK is not referenced. ===================================================================== */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --work; /* Function Body */ if (*n == 0) { value = 0.; } else if (lsame_(norm, "M")) { /* Find max(abs(A(i,j))). */ value = 0.; if (lsame_(uplo, "U")) { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = j - 1; for (i__ = 1; i__ <= i__2; ++i__) { /* Computing MAX */ d__1 = value, d__2 = z_abs(&a[i__ + j * a_dim1]); value = max(d__1,d__2); /* L10: */ } /* Computing MAX */ i__2 = j + j * a_dim1; d__2 = value, d__3 = (d__1 = a[i__2].r, abs(d__1)); value = max(d__2,d__3); /* L20: */ } } else { i__1 = *n; for (j = 1; j <= i__1; ++j) { /* Computing MAX */ i__2 = j + j * a_dim1; d__2 = value, d__3 = (d__1 = a[i__2].r, abs(d__1)); value = max(d__2,d__3); i__2 = *n; for (i__ = j + 1; i__ <= i__2; ++i__) { /* Computing MAX */ d__1 = value, d__2 = z_abs(&a[i__ + j * a_dim1]); value = max(d__1,d__2); /* L30: */ } /* L40: */ } } } else if (((lsame_(norm, "I")) || (lsame_(norm, "O"))) || (*(unsigned char *)norm == '1')) { /* Find normI(A) ( = norm1(A), since A is hermitian). */ value = 0.; if (lsame_(uplo, "U")) { i__1 = *n; for (j = 1; j <= i__1; ++j) { sum = 0.; i__2 = j - 1; for (i__ = 1; i__ <= i__2; ++i__) { absa = z_abs(&a[i__ + j * a_dim1]); sum += absa; work[i__] += absa; /* L50: */ } i__2 = j + j * a_dim1; work[j] = sum + (d__1 = a[i__2].r, abs(d__1)); /* L60: */ } i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { /* Computing MAX */ d__1 = value, d__2 = work[i__]; value = max(d__1,d__2); /* L70: */ } } else { i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { work[i__] = 0.; /* L80: */ } i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = j + j * a_dim1; sum = work[j] + (d__1 = a[i__2].r, abs(d__1)); i__2 = *n; for (i__ = j + 1; i__ <= i__2; ++i__) { absa = z_abs(&a[i__ + j * a_dim1]); sum += absa; work[i__] += absa; /* L90: */ } value = max(value,sum); /* L100: */ } } } else if ((lsame_(norm, "F")) || (lsame_(norm, "E"))) { /* Find normF(A). */ scale = 0.; sum = 1.; if (lsame_(uplo, "U")) { i__1 = *n; for (j = 2; j <= i__1; ++j) { i__2 = j - 1; zlassq_(&i__2, &a[j * a_dim1 + 1], &c__1, &scale, &sum); /* L110: */ } } else { i__1 = *n - 1; for (j = 1; j <= i__1; ++j) { i__2 = *n - j; zlassq_(&i__2, &a[j + 1 + j * a_dim1], &c__1, &scale, &sum); /* L120: */ } } sum *= 2; i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = i__ + i__ * a_dim1; if (a[i__2].r != 0.) { i__2 = i__ + i__ * a_dim1; absa = (d__1 = a[i__2].r, abs(d__1)); if (scale < absa) { /* Computing 2nd power */ d__1 = scale / absa; sum = sum * (d__1 * d__1) + 1.; scale = absa; } else { /* Computing 2nd power */ d__1 = absa / scale; sum += d__1 * d__1; } } /* L130: */ } value = scale * sqrt(sum); } ret_val = value; return ret_val; /* End of ZLANHE */ } /* zlanhe_ */ doublereal zlanhs_(char *norm, integer *n, doublecomplex *a, integer *lda, doublereal *work) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3, i__4; doublereal ret_val, d__1, d__2; /* Builtin functions */ double z_abs(doublecomplex *), sqrt(doublereal); /* Local variables */ static integer i__, j; static doublereal sum, scale; extern logical lsame_(char *, char *); static doublereal value; extern /* Subroutine */ int zlassq_(integer *, doublecomplex *, integer *, doublereal *, doublereal *); /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University October 31, 1992 Purpose ======= ZLANHS returns the value of the one norm, or the Frobenius norm, or the infinity norm, or the element of largest absolute value of a Hessenberg matrix A. Description =========== ZLANHS returns the value ZLANHS = ( max(abs(A(i,j))), NORM = 'M' or 'm' ( ( norm1(A), NORM = '1', 'O' or 'o' ( ( normI(A), NORM = 'I' or 'i' ( ( normF(A), NORM = 'F', 'f', 'E' or 'e' where norm1 denotes the one norm of a matrix (maximum column sum), normI denotes the infinity norm of a matrix (maximum row sum) and normF denotes the Frobenius norm of a matrix (square root of sum of squares). Note that max(abs(A(i,j))) is not a matrix norm. Arguments ========= NORM (input) CHARACTER*1 Specifies the value to be returned in ZLANHS as described above. N (input) INTEGER The order of the matrix A. N >= 0. When N = 0, ZLANHS is set to zero. A (input) COMPLEX*16 array, dimension (LDA,N) The n by n upper Hessenberg matrix A; the part of A below the first sub-diagonal is not referenced. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(N,1). WORK (workspace) DOUBLE PRECISION array, dimension (LWORK), where LWORK >= N when NORM = 'I'; otherwise, WORK is not referenced. ===================================================================== */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --work; /* Function Body */ if (*n == 0) { value = 0.; } else if (lsame_(norm, "M")) { /* Find max(abs(A(i,j))). */ value = 0.; i__1 = *n; for (j = 1; j <= i__1; ++j) { /* Computing MIN */ i__3 = *n, i__4 = j + 1; i__2 = min(i__3,i__4); for (i__ = 1; i__ <= i__2; ++i__) { /* Computing MAX */ d__1 = value, d__2 = z_abs(&a[i__ + j * a_dim1]); value = max(d__1,d__2); /* L10: */ } /* L20: */ } } else if ((lsame_(norm, "O")) || (*(unsigned char * )norm == '1')) { /* Find norm1(A). */ value = 0.; i__1 = *n; for (j = 1; j <= i__1; ++j) { sum = 0.; /* Computing MIN */ i__3 = *n, i__4 = j + 1; i__2 = min(i__3,i__4); for (i__ = 1; i__ <= i__2; ++i__) { sum += z_abs(&a[i__ + j * a_dim1]); /* L30: */ } value = max(value,sum); /* L40: */ } } else if (lsame_(norm, "I")) { /* Find normI(A). */ i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { work[i__] = 0.; /* L50: */ } i__1 = *n; for (j = 1; j <= i__1; ++j) { /* Computing MIN */ i__3 = *n, i__4 = j + 1; i__2 = min(i__3,i__4); for (i__ = 1; i__ <= i__2; ++i__) { work[i__] += z_abs(&a[i__ + j * a_dim1]); /* L60: */ } /* L70: */ } value = 0.; i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { /* Computing MAX */ d__1 = value, d__2 = work[i__]; value = max(d__1,d__2); /* L80: */ } } else if ((lsame_(norm, "F")) || (lsame_(norm, "E"))) { /* Find normF(A). */ scale = 0.; sum = 1.; i__1 = *n; for (j = 1; j <= i__1; ++j) { /* Computing MIN */ i__3 = *n, i__4 = j + 1; i__2 = min(i__3,i__4); zlassq_(&i__2, &a[j * a_dim1 + 1], &c__1, &scale, &sum); /* L90: */ } value = scale * sqrt(sum); } ret_val = value; return ret_val; /* End of ZLANHS */ } /* zlanhs_ */ /* Subroutine */ int zlarcm_(integer *m, integer *n, doublereal *a, integer * lda, doublecomplex *b, integer *ldb, doublecomplex *c__, integer *ldc, doublereal *rwork) { /* System generated locals */ integer a_dim1, a_offset, b_dim1, b_offset, c_dim1, c_offset, i__1, i__2, i__3, i__4, i__5; doublereal d__1; doublecomplex z__1; /* Builtin functions */ double d_imag(doublecomplex *); /* Local variables */ static integer i__, j, l; extern /* Subroutine */ int dgemm_(char *, char *, integer *, integer *, integer *, doublereal *, doublereal *, integer *, doublereal *, integer *, doublereal *, doublereal *, integer *); /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= ZLARCM performs a very simple matrix-matrix multiplication: C := A * B, where A is M by M and real; B is M by N and complex; C is M by N and complex. Arguments ========= M (input) INTEGER The number of rows of the matrix A and of the matrix C. M >= 0. N (input) INTEGER The number of columns and rows of the matrix B and the number of columns of the matrix C. N >= 0. A (input) DOUBLE PRECISION array, dimension (LDA, M) A contains the M by M matrix A. LDA (input) INTEGER The leading dimension of the array A. LDA >=max(1,M). B (input) DOUBLE PRECISION array, dimension (LDB, N) B contains the M by N matrix B. LDB (input) INTEGER The leading dimension of the array B. LDB >=max(1,M). C (input) COMPLEX*16 array, dimension (LDC, N) C contains the M by N matrix C. LDC (input) INTEGER The leading dimension of the array C. LDC >=max(1,M). RWORK (workspace) DOUBLE PRECISION array, dimension (2*M*N) ===================================================================== Quick return if possible. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; b_dim1 = *ldb; b_offset = 1 + b_dim1; b -= b_offset; c_dim1 = *ldc; c_offset = 1 + c_dim1; c__ -= c_offset; --rwork; /* Function Body */ if ((*m == 0) || (*n == 0)) { return 0; } i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * b_dim1; rwork[(j - 1) * *m + i__] = b[i__3].r; /* L10: */ } /* L20: */ } l = *m * *n + 1; dgemm_("N", "N", m, n, m, &c_b1015, &a[a_offset], lda, &rwork[1], m, & c_b324, &rwork[l], m); i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * c_dim1; i__4 = l + (j - 1) * *m + i__ - 1; c__[i__3].r = rwork[i__4], c__[i__3].i = 0.; /* L30: */ } /* L40: */ } i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { rwork[(j - 1) * *m + i__] = d_imag(&b[i__ + j * b_dim1]); /* L50: */ } /* L60: */ } dgemm_("N", "N", m, n, m, &c_b1015, &a[a_offset], lda, &rwork[1], m, & c_b324, &rwork[l], m); i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * c_dim1; i__4 = i__ + j * c_dim1; d__1 = c__[i__4].r; i__5 = l + (j - 1) * *m + i__ - 1; z__1.r = d__1, z__1.i = rwork[i__5]; c__[i__3].r = z__1.r, c__[i__3].i = z__1.i; /* L70: */ } /* L80: */ } return 0; /* End of ZLARCM */ } /* zlarcm_ */ /* Subroutine */ int zlarf_(char *side, integer *m, integer *n, doublecomplex *v, integer *incv, doublecomplex *tau, doublecomplex *c__, integer * ldc, doublecomplex *work) { /* System generated locals */ integer c_dim1, c_offset; doublecomplex z__1; /* Local variables */ extern logical lsame_(char *, char *); extern /* Subroutine */ int zgerc_(integer *, integer *, doublecomplex *, doublecomplex *, integer *, doublecomplex *, integer *, doublecomplex *, integer *), zgemv_(char *, integer *, integer *, doublecomplex *, doublecomplex *, integer *, doublecomplex *, integer *, doublecomplex *, doublecomplex *, integer *); /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University September 30, 1994 Purpose ======= ZLARF applies a complex elementary reflector H to a complex M-by-N matrix C, from either the left or the right. H is represented in the form H = I - tau * v * v' where tau is a complex scalar and v is a complex vector. If tau = 0, then H is taken to be the unit matrix. To apply H' (the conjugate transpose of H), supply conjg(tau) instead tau. Arguments ========= SIDE (input) CHARACTER*1 = 'L': form H * C = 'R': form C * H M (input) INTEGER The number of rows of the matrix C. N (input) INTEGER The number of columns of the matrix C. V (input) COMPLEX*16 array, dimension (1 + (M-1)*abs(INCV)) if SIDE = 'L' or (1 + (N-1)*abs(INCV)) if SIDE = 'R' The vector v in the representation of H. V is not used if TAU = 0. INCV (input) INTEGER The increment between elements of v. INCV <> 0. TAU (input) COMPLEX*16 The value tau in the representation of H. C (input/output) COMPLEX*16 array, dimension (LDC,N) On entry, the M-by-N matrix C. On exit, C is overwritten by the matrix H * C if SIDE = 'L', or C * H if SIDE = 'R'. LDC (input) INTEGER The leading dimension of the array C. LDC >= max(1,M). WORK (workspace) COMPLEX*16 array, dimension (N) if SIDE = 'L' or (M) if SIDE = 'R' ===================================================================== */ /* Parameter adjustments */ --v; c_dim1 = *ldc; c_offset = 1 + c_dim1; c__ -= c_offset; --work; /* Function Body */ if (lsame_(side, "L")) { /* Form H * C */ if ((tau->r != 0.) || (tau->i != 0.)) { /* w := C' * v */ zgemv_("Conjugate transpose", m, n, &c_b60, &c__[c_offset], ldc, & v[1], incv, &c_b59, &work[1], &c__1); /* C := C - v * w' */ z__1.r = -tau->r, z__1.i = -tau->i; zgerc_(m, n, &z__1, &v[1], incv, &work[1], &c__1, &c__[c_offset], ldc); } } else { /* Form C * H */ if ((tau->r != 0.) || (tau->i != 0.)) { /* w := C * v */ zgemv_("No transpose", m, n, &c_b60, &c__[c_offset], ldc, &v[1], incv, &c_b59, &work[1], &c__1); /* C := C - w * v' */ z__1.r = -tau->r, z__1.i = -tau->i; zgerc_(m, n, &z__1, &work[1], &c__1, &v[1], incv, &c__[c_offset], ldc); } } return 0; /* End of ZLARF */ } /* zlarf_ */ /* Subroutine */ int zlarfb_(char *side, char *trans, char *direct, char * storev, integer *m, integer *n, integer *k, doublecomplex *v, integer *ldv, doublecomplex *t, integer *ldt, doublecomplex *c__, integer * ldc, doublecomplex *work, integer *ldwork) { /* System generated locals */ integer c_dim1, c_offset, t_dim1, t_offset, v_dim1, v_offset, work_dim1, work_offset, i__1, i__2, i__3, i__4, i__5; doublecomplex z__1, z__2; /* Builtin functions */ void d_cnjg(doublecomplex *, doublecomplex *); /* Local variables */ static integer i__, j; extern logical lsame_(char *, char *); extern /* Subroutine */ int zgemm_(char *, char *, integer *, integer *, integer *, doublecomplex *, doublecomplex *, integer *, doublecomplex *, integer *, doublecomplex *, doublecomplex *, integer *), zcopy_(integer *, doublecomplex *, integer *, doublecomplex *, integer *), ztrmm_(char *, char *, char *, char *, integer *, integer *, doublecomplex *, doublecomplex *, integer *, doublecomplex *, integer *), zlacgv_(integer *, doublecomplex *, integer *); static char transt[1]; /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University September 30, 1994 Purpose ======= ZLARFB applies a complex block reflector H or its transpose H' to a complex M-by-N matrix C, from either the left or the right. Arguments ========= SIDE (input) CHARACTER*1 = 'L': apply H or H' from the Left = 'R': apply H or H' from the Right TRANS (input) CHARACTER*1 = 'N': apply H (No transpose) = 'C': apply H' (Conjugate transpose) DIRECT (input) CHARACTER*1 Indicates how H is formed from a product of elementary reflectors = 'F': H = H(1) H(2) . . . H(k) (Forward) = 'B': H = H(k) . . . H(2) H(1) (Backward) STOREV (input) CHARACTER*1 Indicates how the vectors which define the elementary reflectors are stored: = 'C': Columnwise = 'R': Rowwise M (input) INTEGER The number of rows of the matrix C. N (input) INTEGER The number of columns of the matrix C. K (input) INTEGER The order of the matrix T (= the number of elementary reflectors whose product defines the block reflector). V (input) COMPLEX*16 array, dimension (LDV,K) if STOREV = 'C' (LDV,M) if STOREV = 'R' and SIDE = 'L' (LDV,N) if STOREV = 'R' and SIDE = 'R' The matrix V. See further details. LDV (input) INTEGER The leading dimension of the array V. If STOREV = 'C' and SIDE = 'L', LDV >= max(1,M); if STOREV = 'C' and SIDE = 'R', LDV >= max(1,N); if STOREV = 'R', LDV >= K. T (input) COMPLEX*16 array, dimension (LDT,K) The triangular K-by-K matrix T in the representation of the block reflector. LDT (input) INTEGER The leading dimension of the array T. LDT >= K. C (input/output) COMPLEX*16 array, dimension (LDC,N) On entry, the M-by-N matrix C. On exit, C is overwritten by H*C or H'*C or C*H or C*H'. LDC (input) INTEGER The leading dimension of the array C. LDC >= max(1,M). WORK (workspace) COMPLEX*16 array, dimension (LDWORK,K) LDWORK (input) INTEGER The leading dimension of the array WORK. If SIDE = 'L', LDWORK >= max(1,N); if SIDE = 'R', LDWORK >= max(1,M). ===================================================================== Quick return if possible */ /* Parameter adjustments */ v_dim1 = *ldv; v_offset = 1 + v_dim1; v -= v_offset; t_dim1 = *ldt; t_offset = 1 + t_dim1; t -= t_offset; c_dim1 = *ldc; c_offset = 1 + c_dim1; c__ -= c_offset; work_dim1 = *ldwork; work_offset = 1 + work_dim1; work -= work_offset; /* Function Body */ if ((*m <= 0) || (*n <= 0)) { return 0; } if (lsame_(trans, "N")) { *(unsigned char *)transt = 'C'; } else { *(unsigned char *)transt = 'N'; } if (lsame_(storev, "C")) { if (lsame_(direct, "F")) { /* Let V = ( V1 ) (first K rows) ( V2 ) where V1 is unit lower triangular. */ if (lsame_(side, "L")) { /* Form H * C or H' * C where C = ( C1 ) ( C2 ) W := C' * V = (C1'*V1 + C2'*V2) (stored in WORK) W := C1' */ i__1 = *k; for (j = 1; j <= i__1; ++j) { zcopy_(n, &c__[j + c_dim1], ldc, &work[j * work_dim1 + 1], &c__1); zlacgv_(n, &work[j * work_dim1 + 1], &c__1); /* L10: */ } /* W := W * V1 */ ztrmm_("Right", "Lower", "No transpose", "Unit", n, k, &c_b60, &v[v_offset], ldv, &work[work_offset], ldwork); if (*m > *k) { /* W := W + C2'*V2 */ i__1 = *m - *k; zgemm_("Conjugate transpose", "No transpose", n, k, &i__1, &c_b60, &c__[*k + 1 + c_dim1], ldc, &v[*k + 1 + v_dim1], ldv, &c_b60, &work[work_offset], ldwork); } /* W := W * T' or W * T */ ztrmm_("Right", "Upper", transt, "Non-unit", n, k, &c_b60, &t[ t_offset], ldt, &work[work_offset], ldwork); /* C := C - V * W' */ if (*m > *k) { /* C2 := C2 - V2 * W' */ i__1 = *m - *k; z__1.r = -1., z__1.i = -0.; zgemm_("No transpose", "Conjugate transpose", &i__1, n, k, &z__1, &v[*k + 1 + v_dim1], ldv, &work[ work_offset], ldwork, &c_b60, &c__[*k + 1 + c_dim1], ldc); } /* W := W * V1' */ ztrmm_("Right", "Lower", "Conjugate transpose", "Unit", n, k, &c_b60, &v[v_offset], ldv, &work[work_offset], ldwork); /* C1 := C1 - W' */ i__1 = *k; for (j = 1; j <= i__1; ++j) { i__2 = *n; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = j + i__ * c_dim1; i__4 = j + i__ * c_dim1; d_cnjg(&z__2, &work[i__ + j * work_dim1]); z__1.r = c__[i__4].r - z__2.r, z__1.i = c__[i__4].i - z__2.i; c__[i__3].r = z__1.r, c__[i__3].i = z__1.i; /* L20: */ } /* L30: */ } } else if (lsame_(side, "R")) { /* Form C * H or C * H' where C = ( C1 C2 ) W := C * V = (C1*V1 + C2*V2) (stored in WORK) W := C1 */ i__1 = *k; for (j = 1; j <= i__1; ++j) { zcopy_(m, &c__[j * c_dim1 + 1], &c__1, &work[j * work_dim1 + 1], &c__1); /* L40: */ } /* W := W * V1 */ ztrmm_("Right", "Lower", "No transpose", "Unit", m, k, &c_b60, &v[v_offset], ldv, &work[work_offset], ldwork); if (*n > *k) { /* W := W + C2 * V2 */ i__1 = *n - *k; zgemm_("No transpose", "No transpose", m, k, &i__1, & c_b60, &c__[(*k + 1) * c_dim1 + 1], ldc, &v[*k + 1 + v_dim1], ldv, &c_b60, &work[work_offset], ldwork); } /* W := W * T or W * T' */ ztrmm_("Right", "Upper", trans, "Non-unit", m, k, &c_b60, &t[ t_offset], ldt, &work[work_offset], ldwork); /* C := C - W * V' */ if (*n > *k) { /* C2 := C2 - W * V2' */ i__1 = *n - *k; z__1.r = -1., z__1.i = -0.; zgemm_("No transpose", "Conjugate transpose", m, &i__1, k, &z__1, &work[work_offset], ldwork, &v[*k + 1 + v_dim1], ldv, &c_b60, &c__[(*k + 1) * c_dim1 + 1], ldc); } /* W := W * V1' */ ztrmm_("Right", "Lower", "Conjugate transpose", "Unit", m, k, &c_b60, &v[v_offset], ldv, &work[work_offset], ldwork); /* C1 := C1 - W */ i__1 = *k; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * c_dim1; i__4 = i__ + j * c_dim1; i__5 = i__ + j * work_dim1; z__1.r = c__[i__4].r - work[i__5].r, z__1.i = c__[ i__4].i - work[i__5].i; c__[i__3].r = z__1.r, c__[i__3].i = z__1.i; /* L50: */ } /* L60: */ } } } else { /* Let V = ( V1 ) ( V2 ) (last K rows) where V2 is unit upper triangular. */ if (lsame_(side, "L")) { /* Form H * C or H' * C where C = ( C1 ) ( C2 ) W := C' * V = (C1'*V1 + C2'*V2) (stored in WORK) W := C2' */ i__1 = *k; for (j = 1; j <= i__1; ++j) { zcopy_(n, &c__[*m - *k + j + c_dim1], ldc, &work[j * work_dim1 + 1], &c__1); zlacgv_(n, &work[j * work_dim1 + 1], &c__1); /* L70: */ } /* W := W * V2 */ ztrmm_("Right", "Upper", "No transpose", "Unit", n, k, &c_b60, &v[*m - *k + 1 + v_dim1], ldv, &work[work_offset], ldwork); if (*m > *k) { /* W := W + C1'*V1 */ i__1 = *m - *k; zgemm_("Conjugate transpose", "No transpose", n, k, &i__1, &c_b60, &c__[c_offset], ldc, &v[v_offset], ldv, & c_b60, &work[work_offset], ldwork); } /* W := W * T' or W * T */ ztrmm_("Right", "Lower", transt, "Non-unit", n, k, &c_b60, &t[ t_offset], ldt, &work[work_offset], ldwork); /* C := C - V * W' */ if (*m > *k) { /* C1 := C1 - V1 * W' */ i__1 = *m - *k; z__1.r = -1., z__1.i = -0.; zgemm_("No transpose", "Conjugate transpose", &i__1, n, k, &z__1, &v[v_offset], ldv, &work[work_offset], ldwork, &c_b60, &c__[c_offset], ldc); } /* W := W * V2' */ ztrmm_("Right", "Upper", "Conjugate transpose", "Unit", n, k, &c_b60, &v[*m - *k + 1 + v_dim1], ldv, &work[ work_offset], ldwork); /* C2 := C2 - W' */ i__1 = *k; for (j = 1; j <= i__1; ++j) { i__2 = *n; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = *m - *k + j + i__ * c_dim1; i__4 = *m - *k + j + i__ * c_dim1; d_cnjg(&z__2, &work[i__ + j * work_dim1]); z__1.r = c__[i__4].r - z__2.r, z__1.i = c__[i__4].i - z__2.i; c__[i__3].r = z__1.r, c__[i__3].i = z__1.i; /* L80: */ } /* L90: */ } } else if (lsame_(side, "R")) { /* Form C * H or C * H' where C = ( C1 C2 ) W := C * V = (C1*V1 + C2*V2) (stored in WORK) W := C2 */ i__1 = *k; for (j = 1; j <= i__1; ++j) { zcopy_(m, &c__[(*n - *k + j) * c_dim1 + 1], &c__1, &work[ j * work_dim1 + 1], &c__1); /* L100: */ } /* W := W * V2 */ ztrmm_("Right", "Upper", "No transpose", "Unit", m, k, &c_b60, &v[*n - *k + 1 + v_dim1], ldv, &work[work_offset], ldwork); if (*n > *k) { /* W := W + C1 * V1 */ i__1 = *n - *k; zgemm_("No transpose", "No transpose", m, k, &i__1, & c_b60, &c__[c_offset], ldc, &v[v_offset], ldv, & c_b60, &work[work_offset], ldwork); } /* W := W * T or W * T' */ ztrmm_("Right", "Lower", trans, "Non-unit", m, k, &c_b60, &t[ t_offset], ldt, &work[work_offset], ldwork); /* C := C - W * V' */ if (*n > *k) { /* C1 := C1 - W * V1' */ i__1 = *n - *k; z__1.r = -1., z__1.i = -0.; zgemm_("No transpose", "Conjugate transpose", m, &i__1, k, &z__1, &work[work_offset], ldwork, &v[v_offset], ldv, &c_b60, &c__[c_offset], ldc); } /* W := W * V2' */ ztrmm_("Right", "Upper", "Conjugate transpose", "Unit", m, k, &c_b60, &v[*n - *k + 1 + v_dim1], ldv, &work[ work_offset], ldwork); /* C2 := C2 - W */ i__1 = *k; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + (*n - *k + j) * c_dim1; i__4 = i__ + (*n - *k + j) * c_dim1; i__5 = i__ + j * work_dim1; z__1.r = c__[i__4].r - work[i__5].r, z__1.i = c__[ i__4].i - work[i__5].i; c__[i__3].r = z__1.r, c__[i__3].i = z__1.i; /* L110: */ } /* L120: */ } } } } else if (lsame_(storev, "R")) { if (lsame_(direct, "F")) { /* Let V = ( V1 V2 ) (V1: first K columns) where V1 is unit upper triangular. */ if (lsame_(side, "L")) { /* Form H * C or H' * C where C = ( C1 ) ( C2 ) W := C' * V' = (C1'*V1' + C2'*V2') (stored in WORK) W := C1' */ i__1 = *k; for (j = 1; j <= i__1; ++j) { zcopy_(n, &c__[j + c_dim1], ldc, &work[j * work_dim1 + 1], &c__1); zlacgv_(n, &work[j * work_dim1 + 1], &c__1); /* L130: */ } /* W := W * V1' */ ztrmm_("Right", "Upper", "Conjugate transpose", "Unit", n, k, &c_b60, &v[v_offset], ldv, &work[work_offset], ldwork); if (*m > *k) { /* W := W + C2'*V2' */ i__1 = *m - *k; zgemm_("Conjugate transpose", "Conjugate transpose", n, k, &i__1, &c_b60, &c__[*k + 1 + c_dim1], ldc, &v[(* k + 1) * v_dim1 + 1], ldv, &c_b60, &work[ work_offset], ldwork); } /* W := W * T' or W * T */ ztrmm_("Right", "Upper", transt, "Non-unit", n, k, &c_b60, &t[ t_offset], ldt, &work[work_offset], ldwork); /* C := C - V' * W' */ if (*m > *k) { /* C2 := C2 - V2' * W' */ i__1 = *m - *k; z__1.r = -1., z__1.i = -0.; zgemm_("Conjugate transpose", "Conjugate transpose", & i__1, n, k, &z__1, &v[(*k + 1) * v_dim1 + 1], ldv, &work[work_offset], ldwork, &c_b60, &c__[*k + 1 + c_dim1], ldc); } /* W := W * V1 */ ztrmm_("Right", "Upper", "No transpose", "Unit", n, k, &c_b60, &v[v_offset], ldv, &work[work_offset], ldwork); /* C1 := C1 - W' */ i__1 = *k; for (j = 1; j <= i__1; ++j) { i__2 = *n; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = j + i__ * c_dim1; i__4 = j + i__ * c_dim1; d_cnjg(&z__2, &work[i__ + j * work_dim1]); z__1.r = c__[i__4].r - z__2.r, z__1.i = c__[i__4].i - z__2.i; c__[i__3].r = z__1.r, c__[i__3].i = z__1.i; /* L140: */ } /* L150: */ } } else if (lsame_(side, "R")) { /* Form C * H or C * H' where C = ( C1 C2 ) W := C * V' = (C1*V1' + C2*V2') (stored in WORK) W := C1 */ i__1 = *k; for (j = 1; j <= i__1; ++j) { zcopy_(m, &c__[j * c_dim1 + 1], &c__1, &work[j * work_dim1 + 1], &c__1); /* L160: */ } /* W := W * V1' */ ztrmm_("Right", "Upper", "Conjugate transpose", "Unit", m, k, &c_b60, &v[v_offset], ldv, &work[work_offset], ldwork); if (*n > *k) { /* W := W + C2 * V2' */ i__1 = *n - *k; zgemm_("No transpose", "Conjugate transpose", m, k, &i__1, &c_b60, &c__[(*k + 1) * c_dim1 + 1], ldc, &v[(*k + 1) * v_dim1 + 1], ldv, &c_b60, &work[ work_offset], ldwork); } /* W := W * T or W * T' */ ztrmm_("Right", "Upper", trans, "Non-unit", m, k, &c_b60, &t[ t_offset], ldt, &work[work_offset], ldwork); /* C := C - W * V */ if (*n > *k) { /* C2 := C2 - W * V2 */ i__1 = *n - *k; z__1.r = -1., z__1.i = -0.; zgemm_("No transpose", "No transpose", m, &i__1, k, &z__1, &work[work_offset], ldwork, &v[(*k + 1) * v_dim1 + 1], ldv, &c_b60, &c__[(*k + 1) * c_dim1 + 1], ldc); } /* W := W * V1 */ ztrmm_("Right", "Upper", "No transpose", "Unit", m, k, &c_b60, &v[v_offset], ldv, &work[work_offset], ldwork); /* C1 := C1 - W */ i__1 = *k; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * c_dim1; i__4 = i__ + j * c_dim1; i__5 = i__ + j * work_dim1; z__1.r = c__[i__4].r - work[i__5].r, z__1.i = c__[ i__4].i - work[i__5].i; c__[i__3].r = z__1.r, c__[i__3].i = z__1.i; /* L170: */ } /* L180: */ } } } else { /* Let V = ( V1 V2 ) (V2: last K columns) where V2 is unit lower triangular. */ if (lsame_(side, "L")) { /* Form H * C or H' * C where C = ( C1 ) ( C2 ) W := C' * V' = (C1'*V1' + C2'*V2') (stored in WORK) W := C2' */ i__1 = *k; for (j = 1; j <= i__1; ++j) { zcopy_(n, &c__[*m - *k + j + c_dim1], ldc, &work[j * work_dim1 + 1], &c__1); zlacgv_(n, &work[j * work_dim1 + 1], &c__1); /* L190: */ } /* W := W * V2' */ ztrmm_("Right", "Lower", "Conjugate transpose", "Unit", n, k, &c_b60, &v[(*m - *k + 1) * v_dim1 + 1], ldv, &work[ work_offset], ldwork); if (*m > *k) { /* W := W + C1'*V1' */ i__1 = *m - *k; zgemm_("Conjugate transpose", "Conjugate transpose", n, k, &i__1, &c_b60, &c__[c_offset], ldc, &v[v_offset], ldv, &c_b60, &work[work_offset], ldwork); } /* W := W * T' or W * T */ ztrmm_("Right", "Lower", transt, "Non-unit", n, k, &c_b60, &t[ t_offset], ldt, &work[work_offset], ldwork); /* C := C - V' * W' */ if (*m > *k) { /* C1 := C1 - V1' * W' */ i__1 = *m - *k; z__1.r = -1., z__1.i = -0.; zgemm_("Conjugate transpose", "Conjugate transpose", & i__1, n, k, &z__1, &v[v_offset], ldv, &work[ work_offset], ldwork, &c_b60, &c__[c_offset], ldc); } /* W := W * V2 */ ztrmm_("Right", "Lower", "No transpose", "Unit", n, k, &c_b60, &v[(*m - *k + 1) * v_dim1 + 1], ldv, &work[ work_offset], ldwork); /* C2 := C2 - W' */ i__1 = *k; for (j = 1; j <= i__1; ++j) { i__2 = *n; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = *m - *k + j + i__ * c_dim1; i__4 = *m - *k + j + i__ * c_dim1; d_cnjg(&z__2, &work[i__ + j * work_dim1]); z__1.r = c__[i__4].r - z__2.r, z__1.i = c__[i__4].i - z__2.i; c__[i__3].r = z__1.r, c__[i__3].i = z__1.i; /* L200: */ } /* L210: */ } } else if (lsame_(side, "R")) { /* Form C * H or C * H' where C = ( C1 C2 ) W := C * V' = (C1*V1' + C2*V2') (stored in WORK) W := C2 */ i__1 = *k; for (j = 1; j <= i__1; ++j) { zcopy_(m, &c__[(*n - *k + j) * c_dim1 + 1], &c__1, &work[ j * work_dim1 + 1], &c__1); /* L220: */ } /* W := W * V2' */ ztrmm_("Right", "Lower", "Conjugate transpose", "Unit", m, k, &c_b60, &v[(*n - *k + 1) * v_dim1 + 1], ldv, &work[ work_offset], ldwork); if (*n > *k) { /* W := W + C1 * V1' */ i__1 = *n - *k; zgemm_("No transpose", "Conjugate transpose", m, k, &i__1, &c_b60, &c__[c_offset], ldc, &v[v_offset], ldv, & c_b60, &work[work_offset], ldwork); } /* W := W * T or W * T' */ ztrmm_("Right", "Lower", trans, "Non-unit", m, k, &c_b60, &t[ t_offset], ldt, &work[work_offset], ldwork); /* C := C - W * V */ if (*n > *k) { /* C1 := C1 - W * V1 */ i__1 = *n - *k; z__1.r = -1., z__1.i = -0.; zgemm_("No transpose", "No transpose", m, &i__1, k, &z__1, &work[work_offset], ldwork, &v[v_offset], ldv, & c_b60, &c__[c_offset], ldc); } /* W := W * V2 */ ztrmm_("Right", "Lower", "No transpose", "Unit", m, k, &c_b60, &v[(*n - *k + 1) * v_dim1 + 1], ldv, &work[ work_offset], ldwork); /* C1 := C1 - W */ i__1 = *k; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + (*n - *k + j) * c_dim1; i__4 = i__ + (*n - *k + j) * c_dim1; i__5 = i__ + j * work_dim1; z__1.r = c__[i__4].r - work[i__5].r, z__1.i = c__[ i__4].i - work[i__5].i; c__[i__3].r = z__1.r, c__[i__3].i = z__1.i; /* L230: */ } /* L240: */ } } } } return 0; /* End of ZLARFB */ } /* zlarfb_ */ /* Subroutine */ int zlarfg_(integer *n, doublecomplex *alpha, doublecomplex * x, integer *incx, doublecomplex *tau) { /* System generated locals */ integer i__1; doublereal d__1, d__2; doublecomplex z__1, z__2; /* Builtin functions */ double d_imag(doublecomplex *), d_sign(doublereal *, doublereal *); /* Local variables */ static integer j, knt; static doublereal beta, alphi, alphr; extern /* Subroutine */ int zscal_(integer *, doublecomplex *, doublecomplex *, integer *); static doublereal xnorm; extern doublereal dlapy3_(doublereal *, doublereal *, doublereal *), dznrm2_(integer *, doublecomplex *, integer *), dlamch_(char *); static doublereal safmin; extern /* Subroutine */ int zdscal_(integer *, doublereal *, doublecomplex *, integer *); static doublereal rsafmn; extern /* Double Complex */ VOID zladiv_(doublecomplex *, doublecomplex *, doublecomplex *); /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University September 30, 1994 Purpose ======= ZLARFG generates a complex elementary reflector H of order n, such that H' * ( alpha ) = ( beta ), H' * H = I. ( x ) ( 0 ) where alpha and beta are scalars, with beta real, and x is an (n-1)-element complex vector. H is represented in the form H = I - tau * ( 1 ) * ( 1 v' ) , ( v ) where tau is a complex scalar and v is a complex (n-1)-element vector. Note that H is not hermitian. If the elements of x are all zero and alpha is real, then tau = 0 and H is taken to be the unit matrix. Otherwise 1 <= real(tau) <= 2 and abs(tau-1) <= 1 . Arguments ========= N (input) INTEGER The order of the elementary reflector. ALPHA (input/output) COMPLEX*16 On entry, the value alpha. On exit, it is overwritten with the value beta. X (input/output) COMPLEX*16 array, dimension (1+(N-2)*abs(INCX)) On entry, the vector x. On exit, it is overwritten with the vector v. INCX (input) INTEGER The increment between elements of X. INCX > 0. TAU (output) COMPLEX*16 The value tau. ===================================================================== */ /* Parameter adjustments */ --x; /* Function Body */ if (*n <= 0) { tau->r = 0., tau->i = 0.; return 0; } i__1 = *n - 1; xnorm = dznrm2_(&i__1, &x[1], incx); alphr = alpha->r; alphi = d_imag(alpha); if (xnorm == 0. && alphi == 0.) { /* H = I */ tau->r = 0., tau->i = 0.; } else { /* general case */ d__1 = dlapy3_(&alphr, &alphi, &xnorm); beta = -d_sign(&d__1, &alphr); safmin = SAFEMINIMUM / EPSILON; rsafmn = 1. / safmin; if (abs(beta) < safmin) { /* XNORM, BETA may be inaccurate; scale X and recompute them */ knt = 0; L10: ++knt; i__1 = *n - 1; zdscal_(&i__1, &rsafmn, &x[1], incx); beta *= rsafmn; alphi *= rsafmn; alphr *= rsafmn; if (abs(beta) < safmin) { goto L10; } /* New BETA is at most 1, at least SAFMIN */ i__1 = *n - 1; xnorm = dznrm2_(&i__1, &x[1], incx); z__1.r = alphr, z__1.i = alphi; alpha->r = z__1.r, alpha->i = z__1.i; d__1 = dlapy3_(&alphr, &alphi, &xnorm); beta = -d_sign(&d__1, &alphr); d__1 = (beta - alphr) / beta; d__2 = -alphi / beta; z__1.r = d__1, z__1.i = d__2; tau->r = z__1.r, tau->i = z__1.i; z__2.r = alpha->r - beta, z__2.i = alpha->i; zladiv_(&z__1, &c_b60, &z__2); alpha->r = z__1.r, alpha->i = z__1.i; i__1 = *n - 1; zscal_(&i__1, alpha, &x[1], incx); /* If ALPHA is subnormal, it may lose relative accuracy */ alpha->r = beta, alpha->i = 0.; i__1 = knt; for (j = 1; j <= i__1; ++j) { z__1.r = safmin * alpha->r, z__1.i = safmin * alpha->i; alpha->r = z__1.r, alpha->i = z__1.i; /* L20: */ } } else { d__1 = (beta - alphr) / beta; d__2 = -alphi / beta; z__1.r = d__1, z__1.i = d__2; tau->r = z__1.r, tau->i = z__1.i; z__2.r = alpha->r - beta, z__2.i = alpha->i; zladiv_(&z__1, &c_b60, &z__2); alpha->r = z__1.r, alpha->i = z__1.i; i__1 = *n - 1; zscal_(&i__1, alpha, &x[1], incx); alpha->r = beta, alpha->i = 0.; } } return 0; /* End of ZLARFG */ } /* zlarfg_ */ /* Subroutine */ int zlarft_(char *direct, char *storev, integer *n, integer * k, doublecomplex *v, integer *ldv, doublecomplex *tau, doublecomplex * t, integer *ldt) { /* System generated locals */ integer t_dim1, t_offset, v_dim1, v_offset, i__1, i__2, i__3, i__4; doublecomplex z__1; /* Local variables */ static integer i__, j; static doublecomplex vii; extern logical lsame_(char *, char *); extern /* Subroutine */ int zgemv_(char *, integer *, integer *, doublecomplex *, doublecomplex *, integer *, doublecomplex *, integer *, doublecomplex *, doublecomplex *, integer *), ztrmv_(char *, char *, char *, integer *, doublecomplex *, integer *, doublecomplex *, integer *), zlacgv_(integer *, doublecomplex *, integer *); /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University September 30, 1994 Purpose ======= ZLARFT forms the triangular factor T of a complex block reflector H of order n, which is defined as a product of k elementary reflectors. If DIRECT = 'F', H = H(1) H(2) . . . H(k) and T is upper triangular; If DIRECT = 'B', H = H(k) . . . H(2) H(1) and T is lower triangular. If STOREV = 'C', the vector which defines the elementary reflector H(i) is stored in the i-th column of the array V, and H = I - V * T * V' If STOREV = 'R', the vector which defines the elementary reflector H(i) is stored in the i-th row of the array V, and H = I - V' * T * V Arguments ========= DIRECT (input) CHARACTER*1 Specifies the order in which the elementary reflectors are multiplied to form the block reflector: = 'F': H = H(1) H(2) . . . H(k) (Forward) = 'B': H = H(k) . . . H(2) H(1) (Backward) STOREV (input) CHARACTER*1 Specifies how the vectors which define the elementary reflectors are stored (see also Further Details): = 'C': columnwise = 'R': rowwise N (input) INTEGER The order of the block reflector H. N >= 0. K (input) INTEGER The order of the triangular factor T (= the number of elementary reflectors). K >= 1. V (input/output) COMPLEX*16 array, dimension (LDV,K) if STOREV = 'C' (LDV,N) if STOREV = 'R' The matrix V. See further details. LDV (input) INTEGER The leading dimension of the array V. If STOREV = 'C', LDV >= max(1,N); if STOREV = 'R', LDV >= K. TAU (input) COMPLEX*16 array, dimension (K) TAU(i) must contain the scalar factor of the elementary reflector H(i). T (output) COMPLEX*16 array, dimension (LDT,K) The k by k triangular factor T of the block reflector. If DIRECT = 'F', T is upper triangular; if DIRECT = 'B', T is lower triangular. The rest of the array is not used. LDT (input) INTEGER The leading dimension of the array T. LDT >= K. Further Details =============== The shape of the matrix V and the storage of the vectors which define the H(i) is best illustrated by the following example with n = 5 and k = 3. The elements equal to 1 are not stored; the corresponding array elements are modified but restored on exit. The rest of the array is not used. DIRECT = 'F' and STOREV = 'C': DIRECT = 'F' and STOREV = 'R': V = ( 1 ) V = ( 1 v1 v1 v1 v1 ) ( v1 1 ) ( 1 v2 v2 v2 ) ( v1 v2 1 ) ( 1 v3 v3 ) ( v1 v2 v3 ) ( v1 v2 v3 ) DIRECT = 'B' and STOREV = 'C': DIRECT = 'B' and STOREV = 'R': V = ( v1 v2 v3 ) V = ( v1 v1 1 ) ( v1 v2 v3 ) ( v2 v2 v2 1 ) ( 1 v2 v3 ) ( v3 v3 v3 v3 1 ) ( 1 v3 ) ( 1 ) ===================================================================== Quick return if possible */ /* Parameter adjustments */ v_dim1 = *ldv; v_offset = 1 + v_dim1; v -= v_offset; --tau; t_dim1 = *ldt; t_offset = 1 + t_dim1; t -= t_offset; /* Function Body */ if (*n == 0) { return 0; } if (lsame_(direct, "F")) { i__1 = *k; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = i__; if (tau[i__2].r == 0. && tau[i__2].i == 0.) { /* H(i) = I */ i__2 = i__; for (j = 1; j <= i__2; ++j) { i__3 = j + i__ * t_dim1; t[i__3].r = 0., t[i__3].i = 0.; /* L10: */ } } else { /* general case */ i__2 = i__ + i__ * v_dim1; vii.r = v[i__2].r, vii.i = v[i__2].i; i__2 = i__ + i__ * v_dim1; v[i__2].r = 1., v[i__2].i = 0.; if (lsame_(storev, "C")) { /* T(1:i-1,i) := - tau(i) * V(i:n,1:i-1)' * V(i:n,i) */ i__2 = *n - i__ + 1; i__3 = i__ - 1; i__4 = i__; z__1.r = -tau[i__4].r, z__1.i = -tau[i__4].i; zgemv_("Conjugate transpose", &i__2, &i__3, &z__1, &v[i__ + v_dim1], ldv, &v[i__ + i__ * v_dim1], &c__1, & c_b59, &t[i__ * t_dim1 + 1], &c__1); } else { /* T(1:i-1,i) := - tau(i) * V(1:i-1,i:n) * V(i,i:n)' */ if (i__ < *n) { i__2 = *n - i__; zlacgv_(&i__2, &v[i__ + (i__ + 1) * v_dim1], ldv); } i__2 = i__ - 1; i__3 = *n - i__ + 1; i__4 = i__; z__1.r = -tau[i__4].r, z__1.i = -tau[i__4].i; zgemv_("No transpose", &i__2, &i__3, &z__1, &v[i__ * v_dim1 + 1], ldv, &v[i__ + i__ * v_dim1], ldv, & c_b59, &t[i__ * t_dim1 + 1], &c__1); if (i__ < *n) { i__2 = *n - i__; zlacgv_(&i__2, &v[i__ + (i__ + 1) * v_dim1], ldv); } } i__2 = i__ + i__ * v_dim1; v[i__2].r = vii.r, v[i__2].i = vii.i; /* T(1:i-1,i) := T(1:i-1,1:i-1) * T(1:i-1,i) */ i__2 = i__ - 1; ztrmv_("Upper", "No transpose", "Non-unit", &i__2, &t[ t_offset], ldt, &t[i__ * t_dim1 + 1], &c__1); i__2 = i__ + i__ * t_dim1; i__3 = i__; t[i__2].r = tau[i__3].r, t[i__2].i = tau[i__3].i; } /* L20: */ } } else { for (i__ = *k; i__ >= 1; --i__) { i__1 = i__; if (tau[i__1].r == 0. && tau[i__1].i == 0.) { /* H(i) = I */ i__1 = *k; for (j = i__; j <= i__1; ++j) { i__2 = j + i__ * t_dim1; t[i__2].r = 0., t[i__2].i = 0.; /* L30: */ } } else { /* general case */ if (i__ < *k) { if (lsame_(storev, "C")) { i__1 = *n - *k + i__ + i__ * v_dim1; vii.r = v[i__1].r, vii.i = v[i__1].i; i__1 = *n - *k + i__ + i__ * v_dim1; v[i__1].r = 1., v[i__1].i = 0.; /* T(i+1:k,i) := - tau(i) * V(1:n-k+i,i+1:k)' * V(1:n-k+i,i) */ i__1 = *n - *k + i__; i__2 = *k - i__; i__3 = i__; z__1.r = -tau[i__3].r, z__1.i = -tau[i__3].i; zgemv_("Conjugate transpose", &i__1, &i__2, &z__1, &v[ (i__ + 1) * v_dim1 + 1], ldv, &v[i__ * v_dim1 + 1], &c__1, &c_b59, &t[i__ + 1 + i__ * t_dim1], &c__1); i__1 = *n - *k + i__ + i__ * v_dim1; v[i__1].r = vii.r, v[i__1].i = vii.i; } else { i__1 = i__ + (*n - *k + i__) * v_dim1; vii.r = v[i__1].r, vii.i = v[i__1].i; i__1 = i__ + (*n - *k + i__) * v_dim1; v[i__1].r = 1., v[i__1].i = 0.; /* T(i+1:k,i) := - tau(i) * V(i+1:k,1:n-k+i) * V(i,1:n-k+i)' */ i__1 = *n - *k + i__ - 1; zlacgv_(&i__1, &v[i__ + v_dim1], ldv); i__1 = *k - i__; i__2 = *n - *k + i__; i__3 = i__; z__1.r = -tau[i__3].r, z__1.i = -tau[i__3].i; zgemv_("No transpose", &i__1, &i__2, &z__1, &v[i__ + 1 + v_dim1], ldv, &v[i__ + v_dim1], ldv, & c_b59, &t[i__ + 1 + i__ * t_dim1], &c__1); i__1 = *n - *k + i__ - 1; zlacgv_(&i__1, &v[i__ + v_dim1], ldv); i__1 = i__ + (*n - *k + i__) * v_dim1; v[i__1].r = vii.r, v[i__1].i = vii.i; } /* T(i+1:k,i) := T(i+1:k,i+1:k) * T(i+1:k,i) */ i__1 = *k - i__; ztrmv_("Lower", "No transpose", "Non-unit", &i__1, &t[i__ + 1 + (i__ + 1) * t_dim1], ldt, &t[i__ + 1 + i__ * t_dim1], &c__1) ; } i__1 = i__ + i__ * t_dim1; i__2 = i__; t[i__1].r = tau[i__2].r, t[i__1].i = tau[i__2].i; } /* L40: */ } } return 0; /* End of ZLARFT */ } /* zlarft_ */ /* Subroutine */ int zlarfx_(char *side, integer *m, integer *n, doublecomplex *v, doublecomplex *tau, doublecomplex *c__, integer * ldc, doublecomplex *work) { /* System generated locals */ integer c_dim1, c_offset, i__1, i__2, i__3, i__4, i__5, i__6, i__7, i__8, i__9, i__10, i__11; doublecomplex z__1, z__2, z__3, z__4, z__5, z__6, z__7, z__8, z__9, z__10, z__11, z__12, z__13, z__14, z__15, z__16, z__17, z__18, z__19; /* Builtin functions */ void d_cnjg(doublecomplex *, doublecomplex *); /* Local variables */ static integer j; static doublecomplex t1, t2, t3, t4, t5, t6, t7, t8, t9, v1, v2, v3, v4, v5, v6, v7, v8, v9, t10, v10, sum; extern logical lsame_(char *, char *); extern /* Subroutine */ int zgerc_(integer *, integer *, doublecomplex *, doublecomplex *, integer *, doublecomplex *, integer *, doublecomplex *, integer *), zgemv_(char *, integer *, integer *, doublecomplex *, doublecomplex *, integer *, doublecomplex *, integer *, doublecomplex *, doublecomplex *, integer *); /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University September 30, 1994 Purpose ======= ZLARFX applies a complex elementary reflector H to a complex m by n matrix C, from either the left or the right. H is represented in the form H = I - tau * v * v' where tau is a complex scalar and v is a complex vector. If tau = 0, then H is taken to be the unit matrix This version uses inline code if H has order < 11. Arguments ========= SIDE (input) CHARACTER*1 = 'L': form H * C = 'R': form C * H M (input) INTEGER The number of rows of the matrix C. N (input) INTEGER The number of columns of the matrix C. V (input) COMPLEX*16 array, dimension (M) if SIDE = 'L' or (N) if SIDE = 'R' The vector v in the representation of H. TAU (input) COMPLEX*16 The value tau in the representation of H. C (input/output) COMPLEX*16 array, dimension (LDC,N) On entry, the m by n matrix C. On exit, C is overwritten by the matrix H * C if SIDE = 'L', or C * H if SIDE = 'R'. LDC (input) INTEGER The leading dimension of the array C. LDA >= max(1,M). WORK (workspace) COMPLEX*16 array, dimension (N) if SIDE = 'L' or (M) if SIDE = 'R' WORK is not referenced if H has order < 11. ===================================================================== */ /* Parameter adjustments */ --v; c_dim1 = *ldc; c_offset = 1 + c_dim1; c__ -= c_offset; --work; /* Function Body */ if (tau->r == 0. && tau->i == 0.) { return 0; } if (lsame_(side, "L")) { /* Form H * C, where H has order m. */ switch (*m) { case 1: goto L10; case 2: goto L30; case 3: goto L50; case 4: goto L70; case 5: goto L90; case 6: goto L110; case 7: goto L130; case 8: goto L150; case 9: goto L170; case 10: goto L190; } /* Code for general M w := C'*v */ zgemv_("Conjugate transpose", m, n, &c_b60, &c__[c_offset], ldc, &v[1] , &c__1, &c_b59, &work[1], &c__1); /* C := C - tau * v * w' */ z__1.r = -tau->r, z__1.i = -tau->i; zgerc_(m, n, &z__1, &v[1], &c__1, &work[1], &c__1, &c__[c_offset], ldc); goto L410; L10: /* Special code for 1 x 1 Householder */ z__3.r = tau->r * v[1].r - tau->i * v[1].i, z__3.i = tau->r * v[1].i + tau->i * v[1].r; d_cnjg(&z__4, &v[1]); z__2.r = z__3.r * z__4.r - z__3.i * z__4.i, z__2.i = z__3.r * z__4.i + z__3.i * z__4.r; z__1.r = 1. - z__2.r, z__1.i = 0. - z__2.i; t1.r = z__1.r, t1.i = z__1.i; i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = j * c_dim1 + 1; i__3 = j * c_dim1 + 1; z__1.r = t1.r * c__[i__3].r - t1.i * c__[i__3].i, z__1.i = t1.r * c__[i__3].i + t1.i * c__[i__3].r; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; /* L20: */ } goto L410; L30: /* Special code for 2 x 2 Householder */ d_cnjg(&z__1, &v[1]); v1.r = z__1.r, v1.i = z__1.i; d_cnjg(&z__2, &v1); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t1.r = z__1.r, t1.i = z__1.i; d_cnjg(&z__1, &v[2]); v2.r = z__1.r, v2.i = z__1.i; d_cnjg(&z__2, &v2); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t2.r = z__1.r, t2.i = z__1.i; i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = j * c_dim1 + 1; z__2.r = v1.r * c__[i__2].r - v1.i * c__[i__2].i, z__2.i = v1.r * c__[i__2].i + v1.i * c__[i__2].r; i__3 = j * c_dim1 + 2; z__3.r = v2.r * c__[i__3].r - v2.i * c__[i__3].i, z__3.i = v2.r * c__[i__3].i + v2.i * c__[i__3].r; z__1.r = z__2.r + z__3.r, z__1.i = z__2.i + z__3.i; sum.r = z__1.r, sum.i = z__1.i; i__2 = j * c_dim1 + 1; i__3 = j * c_dim1 + 1; z__2.r = sum.r * t1.r - sum.i * t1.i, z__2.i = sum.r * t1.i + sum.i * t1.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; i__2 = j * c_dim1 + 2; i__3 = j * c_dim1 + 2; z__2.r = sum.r * t2.r - sum.i * t2.i, z__2.i = sum.r * t2.i + sum.i * t2.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; /* L40: */ } goto L410; L50: /* Special code for 3 x 3 Householder */ d_cnjg(&z__1, &v[1]); v1.r = z__1.r, v1.i = z__1.i; d_cnjg(&z__2, &v1); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t1.r = z__1.r, t1.i = z__1.i; d_cnjg(&z__1, &v[2]); v2.r = z__1.r, v2.i = z__1.i; d_cnjg(&z__2, &v2); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t2.r = z__1.r, t2.i = z__1.i; d_cnjg(&z__1, &v[3]); v3.r = z__1.r, v3.i = z__1.i; d_cnjg(&z__2, &v3); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t3.r = z__1.r, t3.i = z__1.i; i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = j * c_dim1 + 1; z__3.r = v1.r * c__[i__2].r - v1.i * c__[i__2].i, z__3.i = v1.r * c__[i__2].i + v1.i * c__[i__2].r; i__3 = j * c_dim1 + 2; z__4.r = v2.r * c__[i__3].r - v2.i * c__[i__3].i, z__4.i = v2.r * c__[i__3].i + v2.i * c__[i__3].r; z__2.r = z__3.r + z__4.r, z__2.i = z__3.i + z__4.i; i__4 = j * c_dim1 + 3; z__5.r = v3.r * c__[i__4].r - v3.i * c__[i__4].i, z__5.i = v3.r * c__[i__4].i + v3.i * c__[i__4].r; z__1.r = z__2.r + z__5.r, z__1.i = z__2.i + z__5.i; sum.r = z__1.r, sum.i = z__1.i; i__2 = j * c_dim1 + 1; i__3 = j * c_dim1 + 1; z__2.r = sum.r * t1.r - sum.i * t1.i, z__2.i = sum.r * t1.i + sum.i * t1.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; i__2 = j * c_dim1 + 2; i__3 = j * c_dim1 + 2; z__2.r = sum.r * t2.r - sum.i * t2.i, z__2.i = sum.r * t2.i + sum.i * t2.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; i__2 = j * c_dim1 + 3; i__3 = j * c_dim1 + 3; z__2.r = sum.r * t3.r - sum.i * t3.i, z__2.i = sum.r * t3.i + sum.i * t3.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; /* L60: */ } goto L410; L70: /* Special code for 4 x 4 Householder */ d_cnjg(&z__1, &v[1]); v1.r = z__1.r, v1.i = z__1.i; d_cnjg(&z__2, &v1); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t1.r = z__1.r, t1.i = z__1.i; d_cnjg(&z__1, &v[2]); v2.r = z__1.r, v2.i = z__1.i; d_cnjg(&z__2, &v2); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t2.r = z__1.r, t2.i = z__1.i; d_cnjg(&z__1, &v[3]); v3.r = z__1.r, v3.i = z__1.i; d_cnjg(&z__2, &v3); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t3.r = z__1.r, t3.i = z__1.i; d_cnjg(&z__1, &v[4]); v4.r = z__1.r, v4.i = z__1.i; d_cnjg(&z__2, &v4); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t4.r = z__1.r, t4.i = z__1.i; i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = j * c_dim1 + 1; z__4.r = v1.r * c__[i__2].r - v1.i * c__[i__2].i, z__4.i = v1.r * c__[i__2].i + v1.i * c__[i__2].r; i__3 = j * c_dim1 + 2; z__5.r = v2.r * c__[i__3].r - v2.i * c__[i__3].i, z__5.i = v2.r * c__[i__3].i + v2.i * c__[i__3].r; z__3.r = z__4.r + z__5.r, z__3.i = z__4.i + z__5.i; i__4 = j * c_dim1 + 3; z__6.r = v3.r * c__[i__4].r - v3.i * c__[i__4].i, z__6.i = v3.r * c__[i__4].i + v3.i * c__[i__4].r; z__2.r = z__3.r + z__6.r, z__2.i = z__3.i + z__6.i; i__5 = j * c_dim1 + 4; z__7.r = v4.r * c__[i__5].r - v4.i * c__[i__5].i, z__7.i = v4.r * c__[i__5].i + v4.i * c__[i__5].r; z__1.r = z__2.r + z__7.r, z__1.i = z__2.i + z__7.i; sum.r = z__1.r, sum.i = z__1.i; i__2 = j * c_dim1 + 1; i__3 = j * c_dim1 + 1; z__2.r = sum.r * t1.r - sum.i * t1.i, z__2.i = sum.r * t1.i + sum.i * t1.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; i__2 = j * c_dim1 + 2; i__3 = j * c_dim1 + 2; z__2.r = sum.r * t2.r - sum.i * t2.i, z__2.i = sum.r * t2.i + sum.i * t2.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; i__2 = j * c_dim1 + 3; i__3 = j * c_dim1 + 3; z__2.r = sum.r * t3.r - sum.i * t3.i, z__2.i = sum.r * t3.i + sum.i * t3.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; i__2 = j * c_dim1 + 4; i__3 = j * c_dim1 + 4; z__2.r = sum.r * t4.r - sum.i * t4.i, z__2.i = sum.r * t4.i + sum.i * t4.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; /* L80: */ } goto L410; L90: /* Special code for 5 x 5 Householder */ d_cnjg(&z__1, &v[1]); v1.r = z__1.r, v1.i = z__1.i; d_cnjg(&z__2, &v1); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t1.r = z__1.r, t1.i = z__1.i; d_cnjg(&z__1, &v[2]); v2.r = z__1.r, v2.i = z__1.i; d_cnjg(&z__2, &v2); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t2.r = z__1.r, t2.i = z__1.i; d_cnjg(&z__1, &v[3]); v3.r = z__1.r, v3.i = z__1.i; d_cnjg(&z__2, &v3); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t3.r = z__1.r, t3.i = z__1.i; d_cnjg(&z__1, &v[4]); v4.r = z__1.r, v4.i = z__1.i; d_cnjg(&z__2, &v4); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t4.r = z__1.r, t4.i = z__1.i; d_cnjg(&z__1, &v[5]); v5.r = z__1.r, v5.i = z__1.i; d_cnjg(&z__2, &v5); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t5.r = z__1.r, t5.i = z__1.i; i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = j * c_dim1 + 1; z__5.r = v1.r * c__[i__2].r - v1.i * c__[i__2].i, z__5.i = v1.r * c__[i__2].i + v1.i * c__[i__2].r; i__3 = j * c_dim1 + 2; z__6.r = v2.r * c__[i__3].r - v2.i * c__[i__3].i, z__6.i = v2.r * c__[i__3].i + v2.i * c__[i__3].r; z__4.r = z__5.r + z__6.r, z__4.i = z__5.i + z__6.i; i__4 = j * c_dim1 + 3; z__7.r = v3.r * c__[i__4].r - v3.i * c__[i__4].i, z__7.i = v3.r * c__[i__4].i + v3.i * c__[i__4].r; z__3.r = z__4.r + z__7.r, z__3.i = z__4.i + z__7.i; i__5 = j * c_dim1 + 4; z__8.r = v4.r * c__[i__5].r - v4.i * c__[i__5].i, z__8.i = v4.r * c__[i__5].i + v4.i * c__[i__5].r; z__2.r = z__3.r + z__8.r, z__2.i = z__3.i + z__8.i; i__6 = j * c_dim1 + 5; z__9.r = v5.r * c__[i__6].r - v5.i * c__[i__6].i, z__9.i = v5.r * c__[i__6].i + v5.i * c__[i__6].r; z__1.r = z__2.r + z__9.r, z__1.i = z__2.i + z__9.i; sum.r = z__1.r, sum.i = z__1.i; i__2 = j * c_dim1 + 1; i__3 = j * c_dim1 + 1; z__2.r = sum.r * t1.r - sum.i * t1.i, z__2.i = sum.r * t1.i + sum.i * t1.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; i__2 = j * c_dim1 + 2; i__3 = j * c_dim1 + 2; z__2.r = sum.r * t2.r - sum.i * t2.i, z__2.i = sum.r * t2.i + sum.i * t2.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; i__2 = j * c_dim1 + 3; i__3 = j * c_dim1 + 3; z__2.r = sum.r * t3.r - sum.i * t3.i, z__2.i = sum.r * t3.i + sum.i * t3.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; i__2 = j * c_dim1 + 4; i__3 = j * c_dim1 + 4; z__2.r = sum.r * t4.r - sum.i * t4.i, z__2.i = sum.r * t4.i + sum.i * t4.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; i__2 = j * c_dim1 + 5; i__3 = j * c_dim1 + 5; z__2.r = sum.r * t5.r - sum.i * t5.i, z__2.i = sum.r * t5.i + sum.i * t5.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; /* L100: */ } goto L410; L110: /* Special code for 6 x 6 Householder */ d_cnjg(&z__1, &v[1]); v1.r = z__1.r, v1.i = z__1.i; d_cnjg(&z__2, &v1); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t1.r = z__1.r, t1.i = z__1.i; d_cnjg(&z__1, &v[2]); v2.r = z__1.r, v2.i = z__1.i; d_cnjg(&z__2, &v2); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t2.r = z__1.r, t2.i = z__1.i; d_cnjg(&z__1, &v[3]); v3.r = z__1.r, v3.i = z__1.i; d_cnjg(&z__2, &v3); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t3.r = z__1.r, t3.i = z__1.i; d_cnjg(&z__1, &v[4]); v4.r = z__1.r, v4.i = z__1.i; d_cnjg(&z__2, &v4); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t4.r = z__1.r, t4.i = z__1.i; d_cnjg(&z__1, &v[5]); v5.r = z__1.r, v5.i = z__1.i; d_cnjg(&z__2, &v5); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t5.r = z__1.r, t5.i = z__1.i; d_cnjg(&z__1, &v[6]); v6.r = z__1.r, v6.i = z__1.i; d_cnjg(&z__2, &v6); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t6.r = z__1.r, t6.i = z__1.i; i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = j * c_dim1 + 1; z__6.r = v1.r * c__[i__2].r - v1.i * c__[i__2].i, z__6.i = v1.r * c__[i__2].i + v1.i * c__[i__2].r; i__3 = j * c_dim1 + 2; z__7.r = v2.r * c__[i__3].r - v2.i * c__[i__3].i, z__7.i = v2.r * c__[i__3].i + v2.i * c__[i__3].r; z__5.r = z__6.r + z__7.r, z__5.i = z__6.i + z__7.i; i__4 = j * c_dim1 + 3; z__8.r = v3.r * c__[i__4].r - v3.i * c__[i__4].i, z__8.i = v3.r * c__[i__4].i + v3.i * c__[i__4].r; z__4.r = z__5.r + z__8.r, z__4.i = z__5.i + z__8.i; i__5 = j * c_dim1 + 4; z__9.r = v4.r * c__[i__5].r - v4.i * c__[i__5].i, z__9.i = v4.r * c__[i__5].i + v4.i * c__[i__5].r; z__3.r = z__4.r + z__9.r, z__3.i = z__4.i + z__9.i; i__6 = j * c_dim1 + 5; z__10.r = v5.r * c__[i__6].r - v5.i * c__[i__6].i, z__10.i = v5.r * c__[i__6].i + v5.i * c__[i__6].r; z__2.r = z__3.r + z__10.r, z__2.i = z__3.i + z__10.i; i__7 = j * c_dim1 + 6; z__11.r = v6.r * c__[i__7].r - v6.i * c__[i__7].i, z__11.i = v6.r * c__[i__7].i + v6.i * c__[i__7].r; z__1.r = z__2.r + z__11.r, z__1.i = z__2.i + z__11.i; sum.r = z__1.r, sum.i = z__1.i; i__2 = j * c_dim1 + 1; i__3 = j * c_dim1 + 1; z__2.r = sum.r * t1.r - sum.i * t1.i, z__2.i = sum.r * t1.i + sum.i * t1.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; i__2 = j * c_dim1 + 2; i__3 = j * c_dim1 + 2; z__2.r = sum.r * t2.r - sum.i * t2.i, z__2.i = sum.r * t2.i + sum.i * t2.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; i__2 = j * c_dim1 + 3; i__3 = j * c_dim1 + 3; z__2.r = sum.r * t3.r - sum.i * t3.i, z__2.i = sum.r * t3.i + sum.i * t3.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; i__2 = j * c_dim1 + 4; i__3 = j * c_dim1 + 4; z__2.r = sum.r * t4.r - sum.i * t4.i, z__2.i = sum.r * t4.i + sum.i * t4.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; i__2 = j * c_dim1 + 5; i__3 = j * c_dim1 + 5; z__2.r = sum.r * t5.r - sum.i * t5.i, z__2.i = sum.r * t5.i + sum.i * t5.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; i__2 = j * c_dim1 + 6; i__3 = j * c_dim1 + 6; z__2.r = sum.r * t6.r - sum.i * t6.i, z__2.i = sum.r * t6.i + sum.i * t6.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; /* L120: */ } goto L410; L130: /* Special code for 7 x 7 Householder */ d_cnjg(&z__1, &v[1]); v1.r = z__1.r, v1.i = z__1.i; d_cnjg(&z__2, &v1); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t1.r = z__1.r, t1.i = z__1.i; d_cnjg(&z__1, &v[2]); v2.r = z__1.r, v2.i = z__1.i; d_cnjg(&z__2, &v2); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t2.r = z__1.r, t2.i = z__1.i; d_cnjg(&z__1, &v[3]); v3.r = z__1.r, v3.i = z__1.i; d_cnjg(&z__2, &v3); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t3.r = z__1.r, t3.i = z__1.i; d_cnjg(&z__1, &v[4]); v4.r = z__1.r, v4.i = z__1.i; d_cnjg(&z__2, &v4); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t4.r = z__1.r, t4.i = z__1.i; d_cnjg(&z__1, &v[5]); v5.r = z__1.r, v5.i = z__1.i; d_cnjg(&z__2, &v5); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t5.r = z__1.r, t5.i = z__1.i; d_cnjg(&z__1, &v[6]); v6.r = z__1.r, v6.i = z__1.i; d_cnjg(&z__2, &v6); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t6.r = z__1.r, t6.i = z__1.i; d_cnjg(&z__1, &v[7]); v7.r = z__1.r, v7.i = z__1.i; d_cnjg(&z__2, &v7); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t7.r = z__1.r, t7.i = z__1.i; i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = j * c_dim1 + 1; z__7.r = v1.r * c__[i__2].r - v1.i * c__[i__2].i, z__7.i = v1.r * c__[i__2].i + v1.i * c__[i__2].r; i__3 = j * c_dim1 + 2; z__8.r = v2.r * c__[i__3].r - v2.i * c__[i__3].i, z__8.i = v2.r * c__[i__3].i + v2.i * c__[i__3].r; z__6.r = z__7.r + z__8.r, z__6.i = z__7.i + z__8.i; i__4 = j * c_dim1 + 3; z__9.r = v3.r * c__[i__4].r - v3.i * c__[i__4].i, z__9.i = v3.r * c__[i__4].i + v3.i * c__[i__4].r; z__5.r = z__6.r + z__9.r, z__5.i = z__6.i + z__9.i; i__5 = j * c_dim1 + 4; z__10.r = v4.r * c__[i__5].r - v4.i * c__[i__5].i, z__10.i = v4.r * c__[i__5].i + v4.i * c__[i__5].r; z__4.r = z__5.r + z__10.r, z__4.i = z__5.i + z__10.i; i__6 = j * c_dim1 + 5; z__11.r = v5.r * c__[i__6].r - v5.i * c__[i__6].i, z__11.i = v5.r * c__[i__6].i + v5.i * c__[i__6].r; z__3.r = z__4.r + z__11.r, z__3.i = z__4.i + z__11.i; i__7 = j * c_dim1 + 6; z__12.r = v6.r * c__[i__7].r - v6.i * c__[i__7].i, z__12.i = v6.r * c__[i__7].i + v6.i * c__[i__7].r; z__2.r = z__3.r + z__12.r, z__2.i = z__3.i + z__12.i; i__8 = j * c_dim1 + 7; z__13.r = v7.r * c__[i__8].r - v7.i * c__[i__8].i, z__13.i = v7.r * c__[i__8].i + v7.i * c__[i__8].r; z__1.r = z__2.r + z__13.r, z__1.i = z__2.i + z__13.i; sum.r = z__1.r, sum.i = z__1.i; i__2 = j * c_dim1 + 1; i__3 = j * c_dim1 + 1; z__2.r = sum.r * t1.r - sum.i * t1.i, z__2.i = sum.r * t1.i + sum.i * t1.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; i__2 = j * c_dim1 + 2; i__3 = j * c_dim1 + 2; z__2.r = sum.r * t2.r - sum.i * t2.i, z__2.i = sum.r * t2.i + sum.i * t2.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; i__2 = j * c_dim1 + 3; i__3 = j * c_dim1 + 3; z__2.r = sum.r * t3.r - sum.i * t3.i, z__2.i = sum.r * t3.i + sum.i * t3.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; i__2 = j * c_dim1 + 4; i__3 = j * c_dim1 + 4; z__2.r = sum.r * t4.r - sum.i * t4.i, z__2.i = sum.r * t4.i + sum.i * t4.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; i__2 = j * c_dim1 + 5; i__3 = j * c_dim1 + 5; z__2.r = sum.r * t5.r - sum.i * t5.i, z__2.i = sum.r * t5.i + sum.i * t5.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; i__2 = j * c_dim1 + 6; i__3 = j * c_dim1 + 6; z__2.r = sum.r * t6.r - sum.i * t6.i, z__2.i = sum.r * t6.i + sum.i * t6.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; i__2 = j * c_dim1 + 7; i__3 = j * c_dim1 + 7; z__2.r = sum.r * t7.r - sum.i * t7.i, z__2.i = sum.r * t7.i + sum.i * t7.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; /* L140: */ } goto L410; L150: /* Special code for 8 x 8 Householder */ d_cnjg(&z__1, &v[1]); v1.r = z__1.r, v1.i = z__1.i; d_cnjg(&z__2, &v1); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t1.r = z__1.r, t1.i = z__1.i; d_cnjg(&z__1, &v[2]); v2.r = z__1.r, v2.i = z__1.i; d_cnjg(&z__2, &v2); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t2.r = z__1.r, t2.i = z__1.i; d_cnjg(&z__1, &v[3]); v3.r = z__1.r, v3.i = z__1.i; d_cnjg(&z__2, &v3); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t3.r = z__1.r, t3.i = z__1.i; d_cnjg(&z__1, &v[4]); v4.r = z__1.r, v4.i = z__1.i; d_cnjg(&z__2, &v4); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t4.r = z__1.r, t4.i = z__1.i; d_cnjg(&z__1, &v[5]); v5.r = z__1.r, v5.i = z__1.i; d_cnjg(&z__2, &v5); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t5.r = z__1.r, t5.i = z__1.i; d_cnjg(&z__1, &v[6]); v6.r = z__1.r, v6.i = z__1.i; d_cnjg(&z__2, &v6); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t6.r = z__1.r, t6.i = z__1.i; d_cnjg(&z__1, &v[7]); v7.r = z__1.r, v7.i = z__1.i; d_cnjg(&z__2, &v7); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t7.r = z__1.r, t7.i = z__1.i; d_cnjg(&z__1, &v[8]); v8.r = z__1.r, v8.i = z__1.i; d_cnjg(&z__2, &v8); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t8.r = z__1.r, t8.i = z__1.i; i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = j * c_dim1 + 1; z__8.r = v1.r * c__[i__2].r - v1.i * c__[i__2].i, z__8.i = v1.r * c__[i__2].i + v1.i * c__[i__2].r; i__3 = j * c_dim1 + 2; z__9.r = v2.r * c__[i__3].r - v2.i * c__[i__3].i, z__9.i = v2.r * c__[i__3].i + v2.i * c__[i__3].r; z__7.r = z__8.r + z__9.r, z__7.i = z__8.i + z__9.i; i__4 = j * c_dim1 + 3; z__10.r = v3.r * c__[i__4].r - v3.i * c__[i__4].i, z__10.i = v3.r * c__[i__4].i + v3.i * c__[i__4].r; z__6.r = z__7.r + z__10.r, z__6.i = z__7.i + z__10.i; i__5 = j * c_dim1 + 4; z__11.r = v4.r * c__[i__5].r - v4.i * c__[i__5].i, z__11.i = v4.r * c__[i__5].i + v4.i * c__[i__5].r; z__5.r = z__6.r + z__11.r, z__5.i = z__6.i + z__11.i; i__6 = j * c_dim1 + 5; z__12.r = v5.r * c__[i__6].r - v5.i * c__[i__6].i, z__12.i = v5.r * c__[i__6].i + v5.i * c__[i__6].r; z__4.r = z__5.r + z__12.r, z__4.i = z__5.i + z__12.i; i__7 = j * c_dim1 + 6; z__13.r = v6.r * c__[i__7].r - v6.i * c__[i__7].i, z__13.i = v6.r * c__[i__7].i + v6.i * c__[i__7].r; z__3.r = z__4.r + z__13.r, z__3.i = z__4.i + z__13.i; i__8 = j * c_dim1 + 7; z__14.r = v7.r * c__[i__8].r - v7.i * c__[i__8].i, z__14.i = v7.r * c__[i__8].i + v7.i * c__[i__8].r; z__2.r = z__3.r + z__14.r, z__2.i = z__3.i + z__14.i; i__9 = j * c_dim1 + 8; z__15.r = v8.r * c__[i__9].r - v8.i * c__[i__9].i, z__15.i = v8.r * c__[i__9].i + v8.i * c__[i__9].r; z__1.r = z__2.r + z__15.r, z__1.i = z__2.i + z__15.i; sum.r = z__1.r, sum.i = z__1.i; i__2 = j * c_dim1 + 1; i__3 = j * c_dim1 + 1; z__2.r = sum.r * t1.r - sum.i * t1.i, z__2.i = sum.r * t1.i + sum.i * t1.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; i__2 = j * c_dim1 + 2; i__3 = j * c_dim1 + 2; z__2.r = sum.r * t2.r - sum.i * t2.i, z__2.i = sum.r * t2.i + sum.i * t2.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; i__2 = j * c_dim1 + 3; i__3 = j * c_dim1 + 3; z__2.r = sum.r * t3.r - sum.i * t3.i, z__2.i = sum.r * t3.i + sum.i * t3.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; i__2 = j * c_dim1 + 4; i__3 = j * c_dim1 + 4; z__2.r = sum.r * t4.r - sum.i * t4.i, z__2.i = sum.r * t4.i + sum.i * t4.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; i__2 = j * c_dim1 + 5; i__3 = j * c_dim1 + 5; z__2.r = sum.r * t5.r - sum.i * t5.i, z__2.i = sum.r * t5.i + sum.i * t5.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; i__2 = j * c_dim1 + 6; i__3 = j * c_dim1 + 6; z__2.r = sum.r * t6.r - sum.i * t6.i, z__2.i = sum.r * t6.i + sum.i * t6.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; i__2 = j * c_dim1 + 7; i__3 = j * c_dim1 + 7; z__2.r = sum.r * t7.r - sum.i * t7.i, z__2.i = sum.r * t7.i + sum.i * t7.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; i__2 = j * c_dim1 + 8; i__3 = j * c_dim1 + 8; z__2.r = sum.r * t8.r - sum.i * t8.i, z__2.i = sum.r * t8.i + sum.i * t8.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; /* L160: */ } goto L410; L170: /* Special code for 9 x 9 Householder */ d_cnjg(&z__1, &v[1]); v1.r = z__1.r, v1.i = z__1.i; d_cnjg(&z__2, &v1); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t1.r = z__1.r, t1.i = z__1.i; d_cnjg(&z__1, &v[2]); v2.r = z__1.r, v2.i = z__1.i; d_cnjg(&z__2, &v2); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t2.r = z__1.r, t2.i = z__1.i; d_cnjg(&z__1, &v[3]); v3.r = z__1.r, v3.i = z__1.i; d_cnjg(&z__2, &v3); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t3.r = z__1.r, t3.i = z__1.i; d_cnjg(&z__1, &v[4]); v4.r = z__1.r, v4.i = z__1.i; d_cnjg(&z__2, &v4); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t4.r = z__1.r, t4.i = z__1.i; d_cnjg(&z__1, &v[5]); v5.r = z__1.r, v5.i = z__1.i; d_cnjg(&z__2, &v5); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t5.r = z__1.r, t5.i = z__1.i; d_cnjg(&z__1, &v[6]); v6.r = z__1.r, v6.i = z__1.i; d_cnjg(&z__2, &v6); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t6.r = z__1.r, t6.i = z__1.i; d_cnjg(&z__1, &v[7]); v7.r = z__1.r, v7.i = z__1.i; d_cnjg(&z__2, &v7); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t7.r = z__1.r, t7.i = z__1.i; d_cnjg(&z__1, &v[8]); v8.r = z__1.r, v8.i = z__1.i; d_cnjg(&z__2, &v8); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t8.r = z__1.r, t8.i = z__1.i; d_cnjg(&z__1, &v[9]); v9.r = z__1.r, v9.i = z__1.i; d_cnjg(&z__2, &v9); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t9.r = z__1.r, t9.i = z__1.i; i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = j * c_dim1 + 1; z__9.r = v1.r * c__[i__2].r - v1.i * c__[i__2].i, z__9.i = v1.r * c__[i__2].i + v1.i * c__[i__2].r; i__3 = j * c_dim1 + 2; z__10.r = v2.r * c__[i__3].r - v2.i * c__[i__3].i, z__10.i = v2.r * c__[i__3].i + v2.i * c__[i__3].r; z__8.r = z__9.r + z__10.r, z__8.i = z__9.i + z__10.i; i__4 = j * c_dim1 + 3; z__11.r = v3.r * c__[i__4].r - v3.i * c__[i__4].i, z__11.i = v3.r * c__[i__4].i + v3.i * c__[i__4].r; z__7.r = z__8.r + z__11.r, z__7.i = z__8.i + z__11.i; i__5 = j * c_dim1 + 4; z__12.r = v4.r * c__[i__5].r - v4.i * c__[i__5].i, z__12.i = v4.r * c__[i__5].i + v4.i * c__[i__5].r; z__6.r = z__7.r + z__12.r, z__6.i = z__7.i + z__12.i; i__6 = j * c_dim1 + 5; z__13.r = v5.r * c__[i__6].r - v5.i * c__[i__6].i, z__13.i = v5.r * c__[i__6].i + v5.i * c__[i__6].r; z__5.r = z__6.r + z__13.r, z__5.i = z__6.i + z__13.i; i__7 = j * c_dim1 + 6; z__14.r = v6.r * c__[i__7].r - v6.i * c__[i__7].i, z__14.i = v6.r * c__[i__7].i + v6.i * c__[i__7].r; z__4.r = z__5.r + z__14.r, z__4.i = z__5.i + z__14.i; i__8 = j * c_dim1 + 7; z__15.r = v7.r * c__[i__8].r - v7.i * c__[i__8].i, z__15.i = v7.r * c__[i__8].i + v7.i * c__[i__8].r; z__3.r = z__4.r + z__15.r, z__3.i = z__4.i + z__15.i; i__9 = j * c_dim1 + 8; z__16.r = v8.r * c__[i__9].r - v8.i * c__[i__9].i, z__16.i = v8.r * c__[i__9].i + v8.i * c__[i__9].r; z__2.r = z__3.r + z__16.r, z__2.i = z__3.i + z__16.i; i__10 = j * c_dim1 + 9; z__17.r = v9.r * c__[i__10].r - v9.i * c__[i__10].i, z__17.i = v9.r * c__[i__10].i + v9.i * c__[i__10].r; z__1.r = z__2.r + z__17.r, z__1.i = z__2.i + z__17.i; sum.r = z__1.r, sum.i = z__1.i; i__2 = j * c_dim1 + 1; i__3 = j * c_dim1 + 1; z__2.r = sum.r * t1.r - sum.i * t1.i, z__2.i = sum.r * t1.i + sum.i * t1.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; i__2 = j * c_dim1 + 2; i__3 = j * c_dim1 + 2; z__2.r = sum.r * t2.r - sum.i * t2.i, z__2.i = sum.r * t2.i + sum.i * t2.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; i__2 = j * c_dim1 + 3; i__3 = j * c_dim1 + 3; z__2.r = sum.r * t3.r - sum.i * t3.i, z__2.i = sum.r * t3.i + sum.i * t3.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; i__2 = j * c_dim1 + 4; i__3 = j * c_dim1 + 4; z__2.r = sum.r * t4.r - sum.i * t4.i, z__2.i = sum.r * t4.i + sum.i * t4.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; i__2 = j * c_dim1 + 5; i__3 = j * c_dim1 + 5; z__2.r = sum.r * t5.r - sum.i * t5.i, z__2.i = sum.r * t5.i + sum.i * t5.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; i__2 = j * c_dim1 + 6; i__3 = j * c_dim1 + 6; z__2.r = sum.r * t6.r - sum.i * t6.i, z__2.i = sum.r * t6.i + sum.i * t6.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; i__2 = j * c_dim1 + 7; i__3 = j * c_dim1 + 7; z__2.r = sum.r * t7.r - sum.i * t7.i, z__2.i = sum.r * t7.i + sum.i * t7.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; i__2 = j * c_dim1 + 8; i__3 = j * c_dim1 + 8; z__2.r = sum.r * t8.r - sum.i * t8.i, z__2.i = sum.r * t8.i + sum.i * t8.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; i__2 = j * c_dim1 + 9; i__3 = j * c_dim1 + 9; z__2.r = sum.r * t9.r - sum.i * t9.i, z__2.i = sum.r * t9.i + sum.i * t9.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; /* L180: */ } goto L410; L190: /* Special code for 10 x 10 Householder */ d_cnjg(&z__1, &v[1]); v1.r = z__1.r, v1.i = z__1.i; d_cnjg(&z__2, &v1); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t1.r = z__1.r, t1.i = z__1.i; d_cnjg(&z__1, &v[2]); v2.r = z__1.r, v2.i = z__1.i; d_cnjg(&z__2, &v2); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t2.r = z__1.r, t2.i = z__1.i; d_cnjg(&z__1, &v[3]); v3.r = z__1.r, v3.i = z__1.i; d_cnjg(&z__2, &v3); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t3.r = z__1.r, t3.i = z__1.i; d_cnjg(&z__1, &v[4]); v4.r = z__1.r, v4.i = z__1.i; d_cnjg(&z__2, &v4); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t4.r = z__1.r, t4.i = z__1.i; d_cnjg(&z__1, &v[5]); v5.r = z__1.r, v5.i = z__1.i; d_cnjg(&z__2, &v5); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t5.r = z__1.r, t5.i = z__1.i; d_cnjg(&z__1, &v[6]); v6.r = z__1.r, v6.i = z__1.i; d_cnjg(&z__2, &v6); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t6.r = z__1.r, t6.i = z__1.i; d_cnjg(&z__1, &v[7]); v7.r = z__1.r, v7.i = z__1.i; d_cnjg(&z__2, &v7); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t7.r = z__1.r, t7.i = z__1.i; d_cnjg(&z__1, &v[8]); v8.r = z__1.r, v8.i = z__1.i; d_cnjg(&z__2, &v8); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t8.r = z__1.r, t8.i = z__1.i; d_cnjg(&z__1, &v[9]); v9.r = z__1.r, v9.i = z__1.i; d_cnjg(&z__2, &v9); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t9.r = z__1.r, t9.i = z__1.i; d_cnjg(&z__1, &v[10]); v10.r = z__1.r, v10.i = z__1.i; d_cnjg(&z__2, &v10); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t10.r = z__1.r, t10.i = z__1.i; i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = j * c_dim1 + 1; z__10.r = v1.r * c__[i__2].r - v1.i * c__[i__2].i, z__10.i = v1.r * c__[i__2].i + v1.i * c__[i__2].r; i__3 = j * c_dim1 + 2; z__11.r = v2.r * c__[i__3].r - v2.i * c__[i__3].i, z__11.i = v2.r * c__[i__3].i + v2.i * c__[i__3].r; z__9.r = z__10.r + z__11.r, z__9.i = z__10.i + z__11.i; i__4 = j * c_dim1 + 3; z__12.r = v3.r * c__[i__4].r - v3.i * c__[i__4].i, z__12.i = v3.r * c__[i__4].i + v3.i * c__[i__4].r; z__8.r = z__9.r + z__12.r, z__8.i = z__9.i + z__12.i; i__5 = j * c_dim1 + 4; z__13.r = v4.r * c__[i__5].r - v4.i * c__[i__5].i, z__13.i = v4.r * c__[i__5].i + v4.i * c__[i__5].r; z__7.r = z__8.r + z__13.r, z__7.i = z__8.i + z__13.i; i__6 = j * c_dim1 + 5; z__14.r = v5.r * c__[i__6].r - v5.i * c__[i__6].i, z__14.i = v5.r * c__[i__6].i + v5.i * c__[i__6].r; z__6.r = z__7.r + z__14.r, z__6.i = z__7.i + z__14.i; i__7 = j * c_dim1 + 6; z__15.r = v6.r * c__[i__7].r - v6.i * c__[i__7].i, z__15.i = v6.r * c__[i__7].i + v6.i * c__[i__7].r; z__5.r = z__6.r + z__15.r, z__5.i = z__6.i + z__15.i; i__8 = j * c_dim1 + 7; z__16.r = v7.r * c__[i__8].r - v7.i * c__[i__8].i, z__16.i = v7.r * c__[i__8].i + v7.i * c__[i__8].r; z__4.r = z__5.r + z__16.r, z__4.i = z__5.i + z__16.i; i__9 = j * c_dim1 + 8; z__17.r = v8.r * c__[i__9].r - v8.i * c__[i__9].i, z__17.i = v8.r * c__[i__9].i + v8.i * c__[i__9].r; z__3.r = z__4.r + z__17.r, z__3.i = z__4.i + z__17.i; i__10 = j * c_dim1 + 9; z__18.r = v9.r * c__[i__10].r - v9.i * c__[i__10].i, z__18.i = v9.r * c__[i__10].i + v9.i * c__[i__10].r; z__2.r = z__3.r + z__18.r, z__2.i = z__3.i + z__18.i; i__11 = j * c_dim1 + 10; z__19.r = v10.r * c__[i__11].r - v10.i * c__[i__11].i, z__19.i = v10.r * c__[i__11].i + v10.i * c__[i__11].r; z__1.r = z__2.r + z__19.r, z__1.i = z__2.i + z__19.i; sum.r = z__1.r, sum.i = z__1.i; i__2 = j * c_dim1 + 1; i__3 = j * c_dim1 + 1; z__2.r = sum.r * t1.r - sum.i * t1.i, z__2.i = sum.r * t1.i + sum.i * t1.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; i__2 = j * c_dim1 + 2; i__3 = j * c_dim1 + 2; z__2.r = sum.r * t2.r - sum.i * t2.i, z__2.i = sum.r * t2.i + sum.i * t2.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; i__2 = j * c_dim1 + 3; i__3 = j * c_dim1 + 3; z__2.r = sum.r * t3.r - sum.i * t3.i, z__2.i = sum.r * t3.i + sum.i * t3.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; i__2 = j * c_dim1 + 4; i__3 = j * c_dim1 + 4; z__2.r = sum.r * t4.r - sum.i * t4.i, z__2.i = sum.r * t4.i + sum.i * t4.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; i__2 = j * c_dim1 + 5; i__3 = j * c_dim1 + 5; z__2.r = sum.r * t5.r - sum.i * t5.i, z__2.i = sum.r * t5.i + sum.i * t5.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; i__2 = j * c_dim1 + 6; i__3 = j * c_dim1 + 6; z__2.r = sum.r * t6.r - sum.i * t6.i, z__2.i = sum.r * t6.i + sum.i * t6.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; i__2 = j * c_dim1 + 7; i__3 = j * c_dim1 + 7; z__2.r = sum.r * t7.r - sum.i * t7.i, z__2.i = sum.r * t7.i + sum.i * t7.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; i__2 = j * c_dim1 + 8; i__3 = j * c_dim1 + 8; z__2.r = sum.r * t8.r - sum.i * t8.i, z__2.i = sum.r * t8.i + sum.i * t8.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; i__2 = j * c_dim1 + 9; i__3 = j * c_dim1 + 9; z__2.r = sum.r * t9.r - sum.i * t9.i, z__2.i = sum.r * t9.i + sum.i * t9.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; i__2 = j * c_dim1 + 10; i__3 = j * c_dim1 + 10; z__2.r = sum.r * t10.r - sum.i * t10.i, z__2.i = sum.r * t10.i + sum.i * t10.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; /* L200: */ } goto L410; } else { /* Form C * H, where H has order n. */ switch (*n) { case 1: goto L210; case 2: goto L230; case 3: goto L250; case 4: goto L270; case 5: goto L290; case 6: goto L310; case 7: goto L330; case 8: goto L350; case 9: goto L370; case 10: goto L390; } /* Code for general N w := C * v */ zgemv_("No transpose", m, n, &c_b60, &c__[c_offset], ldc, &v[1], & c__1, &c_b59, &work[1], &c__1); /* C := C - tau * w * v' */ z__1.r = -tau->r, z__1.i = -tau->i; zgerc_(m, n, &z__1, &work[1], &c__1, &v[1], &c__1, &c__[c_offset], ldc); goto L410; L210: /* Special code for 1 x 1 Householder */ z__3.r = tau->r * v[1].r - tau->i * v[1].i, z__3.i = tau->r * v[1].i + tau->i * v[1].r; d_cnjg(&z__4, &v[1]); z__2.r = z__3.r * z__4.r - z__3.i * z__4.i, z__2.i = z__3.r * z__4.i + z__3.i * z__4.r; z__1.r = 1. - z__2.r, z__1.i = 0. - z__2.i; t1.r = z__1.r, t1.i = z__1.i; i__1 = *m; for (j = 1; j <= i__1; ++j) { i__2 = j + c_dim1; i__3 = j + c_dim1; z__1.r = t1.r * c__[i__3].r - t1.i * c__[i__3].i, z__1.i = t1.r * c__[i__3].i + t1.i * c__[i__3].r; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; /* L220: */ } goto L410; L230: /* Special code for 2 x 2 Householder */ v1.r = v[1].r, v1.i = v[1].i; d_cnjg(&z__2, &v1); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t1.r = z__1.r, t1.i = z__1.i; v2.r = v[2].r, v2.i = v[2].i; d_cnjg(&z__2, &v2); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t2.r = z__1.r, t2.i = z__1.i; i__1 = *m; for (j = 1; j <= i__1; ++j) { i__2 = j + c_dim1; z__2.r = v1.r * c__[i__2].r - v1.i * c__[i__2].i, z__2.i = v1.r * c__[i__2].i + v1.i * c__[i__2].r; i__3 = j + ((c_dim1) << (1)); z__3.r = v2.r * c__[i__3].r - v2.i * c__[i__3].i, z__3.i = v2.r * c__[i__3].i + v2.i * c__[i__3].r; z__1.r = z__2.r + z__3.r, z__1.i = z__2.i + z__3.i; sum.r = z__1.r, sum.i = z__1.i; i__2 = j + c_dim1; i__3 = j + c_dim1; z__2.r = sum.r * t1.r - sum.i * t1.i, z__2.i = sum.r * t1.i + sum.i * t1.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; i__2 = j + ((c_dim1) << (1)); i__3 = j + ((c_dim1) << (1)); z__2.r = sum.r * t2.r - sum.i * t2.i, z__2.i = sum.r * t2.i + sum.i * t2.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; /* L240: */ } goto L410; L250: /* Special code for 3 x 3 Householder */ v1.r = v[1].r, v1.i = v[1].i; d_cnjg(&z__2, &v1); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t1.r = z__1.r, t1.i = z__1.i; v2.r = v[2].r, v2.i = v[2].i; d_cnjg(&z__2, &v2); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t2.r = z__1.r, t2.i = z__1.i; v3.r = v[3].r, v3.i = v[3].i; d_cnjg(&z__2, &v3); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t3.r = z__1.r, t3.i = z__1.i; i__1 = *m; for (j = 1; j <= i__1; ++j) { i__2 = j + c_dim1; z__3.r = v1.r * c__[i__2].r - v1.i * c__[i__2].i, z__3.i = v1.r * c__[i__2].i + v1.i * c__[i__2].r; i__3 = j + ((c_dim1) << (1)); z__4.r = v2.r * c__[i__3].r - v2.i * c__[i__3].i, z__4.i = v2.r * c__[i__3].i + v2.i * c__[i__3].r; z__2.r = z__3.r + z__4.r, z__2.i = z__3.i + z__4.i; i__4 = j + c_dim1 * 3; z__5.r = v3.r * c__[i__4].r - v3.i * c__[i__4].i, z__5.i = v3.r * c__[i__4].i + v3.i * c__[i__4].r; z__1.r = z__2.r + z__5.r, z__1.i = z__2.i + z__5.i; sum.r = z__1.r, sum.i = z__1.i; i__2 = j + c_dim1; i__3 = j + c_dim1; z__2.r = sum.r * t1.r - sum.i * t1.i, z__2.i = sum.r * t1.i + sum.i * t1.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; i__2 = j + ((c_dim1) << (1)); i__3 = j + ((c_dim1) << (1)); z__2.r = sum.r * t2.r - sum.i * t2.i, z__2.i = sum.r * t2.i + sum.i * t2.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; i__2 = j + c_dim1 * 3; i__3 = j + c_dim1 * 3; z__2.r = sum.r * t3.r - sum.i * t3.i, z__2.i = sum.r * t3.i + sum.i * t3.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; /* L260: */ } goto L410; L270: /* Special code for 4 x 4 Householder */ v1.r = v[1].r, v1.i = v[1].i; d_cnjg(&z__2, &v1); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t1.r = z__1.r, t1.i = z__1.i; v2.r = v[2].r, v2.i = v[2].i; d_cnjg(&z__2, &v2); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t2.r = z__1.r, t2.i = z__1.i; v3.r = v[3].r, v3.i = v[3].i; d_cnjg(&z__2, &v3); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t3.r = z__1.r, t3.i = z__1.i; v4.r = v[4].r, v4.i = v[4].i; d_cnjg(&z__2, &v4); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t4.r = z__1.r, t4.i = z__1.i; i__1 = *m; for (j = 1; j <= i__1; ++j) { i__2 = j + c_dim1; z__4.r = v1.r * c__[i__2].r - v1.i * c__[i__2].i, z__4.i = v1.r * c__[i__2].i + v1.i * c__[i__2].r; i__3 = j + ((c_dim1) << (1)); z__5.r = v2.r * c__[i__3].r - v2.i * c__[i__3].i, z__5.i = v2.r * c__[i__3].i + v2.i * c__[i__3].r; z__3.r = z__4.r + z__5.r, z__3.i = z__4.i + z__5.i; i__4 = j + c_dim1 * 3; z__6.r = v3.r * c__[i__4].r - v3.i * c__[i__4].i, z__6.i = v3.r * c__[i__4].i + v3.i * c__[i__4].r; z__2.r = z__3.r + z__6.r, z__2.i = z__3.i + z__6.i; i__5 = j + ((c_dim1) << (2)); z__7.r = v4.r * c__[i__5].r - v4.i * c__[i__5].i, z__7.i = v4.r * c__[i__5].i + v4.i * c__[i__5].r; z__1.r = z__2.r + z__7.r, z__1.i = z__2.i + z__7.i; sum.r = z__1.r, sum.i = z__1.i; i__2 = j + c_dim1; i__3 = j + c_dim1; z__2.r = sum.r * t1.r - sum.i * t1.i, z__2.i = sum.r * t1.i + sum.i * t1.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; i__2 = j + ((c_dim1) << (1)); i__3 = j + ((c_dim1) << (1)); z__2.r = sum.r * t2.r - sum.i * t2.i, z__2.i = sum.r * t2.i + sum.i * t2.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; i__2 = j + c_dim1 * 3; i__3 = j + c_dim1 * 3; z__2.r = sum.r * t3.r - sum.i * t3.i, z__2.i = sum.r * t3.i + sum.i * t3.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; i__2 = j + ((c_dim1) << (2)); i__3 = j + ((c_dim1) << (2)); z__2.r = sum.r * t4.r - sum.i * t4.i, z__2.i = sum.r * t4.i + sum.i * t4.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; /* L280: */ } goto L410; L290: /* Special code for 5 x 5 Householder */ v1.r = v[1].r, v1.i = v[1].i; d_cnjg(&z__2, &v1); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t1.r = z__1.r, t1.i = z__1.i; v2.r = v[2].r, v2.i = v[2].i; d_cnjg(&z__2, &v2); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t2.r = z__1.r, t2.i = z__1.i; v3.r = v[3].r, v3.i = v[3].i; d_cnjg(&z__2, &v3); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t3.r = z__1.r, t3.i = z__1.i; v4.r = v[4].r, v4.i = v[4].i; d_cnjg(&z__2, &v4); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t4.r = z__1.r, t4.i = z__1.i; v5.r = v[5].r, v5.i = v[5].i; d_cnjg(&z__2, &v5); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t5.r = z__1.r, t5.i = z__1.i; i__1 = *m; for (j = 1; j <= i__1; ++j) { i__2 = j + c_dim1; z__5.r = v1.r * c__[i__2].r - v1.i * c__[i__2].i, z__5.i = v1.r * c__[i__2].i + v1.i * c__[i__2].r; i__3 = j + ((c_dim1) << (1)); z__6.r = v2.r * c__[i__3].r - v2.i * c__[i__3].i, z__6.i = v2.r * c__[i__3].i + v2.i * c__[i__3].r; z__4.r = z__5.r + z__6.r, z__4.i = z__5.i + z__6.i; i__4 = j + c_dim1 * 3; z__7.r = v3.r * c__[i__4].r - v3.i * c__[i__4].i, z__7.i = v3.r * c__[i__4].i + v3.i * c__[i__4].r; z__3.r = z__4.r + z__7.r, z__3.i = z__4.i + z__7.i; i__5 = j + ((c_dim1) << (2)); z__8.r = v4.r * c__[i__5].r - v4.i * c__[i__5].i, z__8.i = v4.r * c__[i__5].i + v4.i * c__[i__5].r; z__2.r = z__3.r + z__8.r, z__2.i = z__3.i + z__8.i; i__6 = j + c_dim1 * 5; z__9.r = v5.r * c__[i__6].r - v5.i * c__[i__6].i, z__9.i = v5.r * c__[i__6].i + v5.i * c__[i__6].r; z__1.r = z__2.r + z__9.r, z__1.i = z__2.i + z__9.i; sum.r = z__1.r, sum.i = z__1.i; i__2 = j + c_dim1; i__3 = j + c_dim1; z__2.r = sum.r * t1.r - sum.i * t1.i, z__2.i = sum.r * t1.i + sum.i * t1.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; i__2 = j + ((c_dim1) << (1)); i__3 = j + ((c_dim1) << (1)); z__2.r = sum.r * t2.r - sum.i * t2.i, z__2.i = sum.r * t2.i + sum.i * t2.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; i__2 = j + c_dim1 * 3; i__3 = j + c_dim1 * 3; z__2.r = sum.r * t3.r - sum.i * t3.i, z__2.i = sum.r * t3.i + sum.i * t3.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; i__2 = j + ((c_dim1) << (2)); i__3 = j + ((c_dim1) << (2)); z__2.r = sum.r * t4.r - sum.i * t4.i, z__2.i = sum.r * t4.i + sum.i * t4.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; i__2 = j + c_dim1 * 5; i__3 = j + c_dim1 * 5; z__2.r = sum.r * t5.r - sum.i * t5.i, z__2.i = sum.r * t5.i + sum.i * t5.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; /* L300: */ } goto L410; L310: /* Special code for 6 x 6 Householder */ v1.r = v[1].r, v1.i = v[1].i; d_cnjg(&z__2, &v1); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t1.r = z__1.r, t1.i = z__1.i; v2.r = v[2].r, v2.i = v[2].i; d_cnjg(&z__2, &v2); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t2.r = z__1.r, t2.i = z__1.i; v3.r = v[3].r, v3.i = v[3].i; d_cnjg(&z__2, &v3); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t3.r = z__1.r, t3.i = z__1.i; v4.r = v[4].r, v4.i = v[4].i; d_cnjg(&z__2, &v4); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t4.r = z__1.r, t4.i = z__1.i; v5.r = v[5].r, v5.i = v[5].i; d_cnjg(&z__2, &v5); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t5.r = z__1.r, t5.i = z__1.i; v6.r = v[6].r, v6.i = v[6].i; d_cnjg(&z__2, &v6); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t6.r = z__1.r, t6.i = z__1.i; i__1 = *m; for (j = 1; j <= i__1; ++j) { i__2 = j + c_dim1; z__6.r = v1.r * c__[i__2].r - v1.i * c__[i__2].i, z__6.i = v1.r * c__[i__2].i + v1.i * c__[i__2].r; i__3 = j + ((c_dim1) << (1)); z__7.r = v2.r * c__[i__3].r - v2.i * c__[i__3].i, z__7.i = v2.r * c__[i__3].i + v2.i * c__[i__3].r; z__5.r = z__6.r + z__7.r, z__5.i = z__6.i + z__7.i; i__4 = j + c_dim1 * 3; z__8.r = v3.r * c__[i__4].r - v3.i * c__[i__4].i, z__8.i = v3.r * c__[i__4].i + v3.i * c__[i__4].r; z__4.r = z__5.r + z__8.r, z__4.i = z__5.i + z__8.i; i__5 = j + ((c_dim1) << (2)); z__9.r = v4.r * c__[i__5].r - v4.i * c__[i__5].i, z__9.i = v4.r * c__[i__5].i + v4.i * c__[i__5].r; z__3.r = z__4.r + z__9.r, z__3.i = z__4.i + z__9.i; i__6 = j + c_dim1 * 5; z__10.r = v5.r * c__[i__6].r - v5.i * c__[i__6].i, z__10.i = v5.r * c__[i__6].i + v5.i * c__[i__6].r; z__2.r = z__3.r + z__10.r, z__2.i = z__3.i + z__10.i; i__7 = j + c_dim1 * 6; z__11.r = v6.r * c__[i__7].r - v6.i * c__[i__7].i, z__11.i = v6.r * c__[i__7].i + v6.i * c__[i__7].r; z__1.r = z__2.r + z__11.r, z__1.i = z__2.i + z__11.i; sum.r = z__1.r, sum.i = z__1.i; i__2 = j + c_dim1; i__3 = j + c_dim1; z__2.r = sum.r * t1.r - sum.i * t1.i, z__2.i = sum.r * t1.i + sum.i * t1.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; i__2 = j + ((c_dim1) << (1)); i__3 = j + ((c_dim1) << (1)); z__2.r = sum.r * t2.r - sum.i * t2.i, z__2.i = sum.r * t2.i + sum.i * t2.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; i__2 = j + c_dim1 * 3; i__3 = j + c_dim1 * 3; z__2.r = sum.r * t3.r - sum.i * t3.i, z__2.i = sum.r * t3.i + sum.i * t3.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; i__2 = j + ((c_dim1) << (2)); i__3 = j + ((c_dim1) << (2)); z__2.r = sum.r * t4.r - sum.i * t4.i, z__2.i = sum.r * t4.i + sum.i * t4.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; i__2 = j + c_dim1 * 5; i__3 = j + c_dim1 * 5; z__2.r = sum.r * t5.r - sum.i * t5.i, z__2.i = sum.r * t5.i + sum.i * t5.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; i__2 = j + c_dim1 * 6; i__3 = j + c_dim1 * 6; z__2.r = sum.r * t6.r - sum.i * t6.i, z__2.i = sum.r * t6.i + sum.i * t6.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; /* L320: */ } goto L410; L330: /* Special code for 7 x 7 Householder */ v1.r = v[1].r, v1.i = v[1].i; d_cnjg(&z__2, &v1); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t1.r = z__1.r, t1.i = z__1.i; v2.r = v[2].r, v2.i = v[2].i; d_cnjg(&z__2, &v2); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t2.r = z__1.r, t2.i = z__1.i; v3.r = v[3].r, v3.i = v[3].i; d_cnjg(&z__2, &v3); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t3.r = z__1.r, t3.i = z__1.i; v4.r = v[4].r, v4.i = v[4].i; d_cnjg(&z__2, &v4); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t4.r = z__1.r, t4.i = z__1.i; v5.r = v[5].r, v5.i = v[5].i; d_cnjg(&z__2, &v5); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t5.r = z__1.r, t5.i = z__1.i; v6.r = v[6].r, v6.i = v[6].i; d_cnjg(&z__2, &v6); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t6.r = z__1.r, t6.i = z__1.i; v7.r = v[7].r, v7.i = v[7].i; d_cnjg(&z__2, &v7); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t7.r = z__1.r, t7.i = z__1.i; i__1 = *m; for (j = 1; j <= i__1; ++j) { i__2 = j + c_dim1; z__7.r = v1.r * c__[i__2].r - v1.i * c__[i__2].i, z__7.i = v1.r * c__[i__2].i + v1.i * c__[i__2].r; i__3 = j + ((c_dim1) << (1)); z__8.r = v2.r * c__[i__3].r - v2.i * c__[i__3].i, z__8.i = v2.r * c__[i__3].i + v2.i * c__[i__3].r; z__6.r = z__7.r + z__8.r, z__6.i = z__7.i + z__8.i; i__4 = j + c_dim1 * 3; z__9.r = v3.r * c__[i__4].r - v3.i * c__[i__4].i, z__9.i = v3.r * c__[i__4].i + v3.i * c__[i__4].r; z__5.r = z__6.r + z__9.r, z__5.i = z__6.i + z__9.i; i__5 = j + ((c_dim1) << (2)); z__10.r = v4.r * c__[i__5].r - v4.i * c__[i__5].i, z__10.i = v4.r * c__[i__5].i + v4.i * c__[i__5].r; z__4.r = z__5.r + z__10.r, z__4.i = z__5.i + z__10.i; i__6 = j + c_dim1 * 5; z__11.r = v5.r * c__[i__6].r - v5.i * c__[i__6].i, z__11.i = v5.r * c__[i__6].i + v5.i * c__[i__6].r; z__3.r = z__4.r + z__11.r, z__3.i = z__4.i + z__11.i; i__7 = j + c_dim1 * 6; z__12.r = v6.r * c__[i__7].r - v6.i * c__[i__7].i, z__12.i = v6.r * c__[i__7].i + v6.i * c__[i__7].r; z__2.r = z__3.r + z__12.r, z__2.i = z__3.i + z__12.i; i__8 = j + c_dim1 * 7; z__13.r = v7.r * c__[i__8].r - v7.i * c__[i__8].i, z__13.i = v7.r * c__[i__8].i + v7.i * c__[i__8].r; z__1.r = z__2.r + z__13.r, z__1.i = z__2.i + z__13.i; sum.r = z__1.r, sum.i = z__1.i; i__2 = j + c_dim1; i__3 = j + c_dim1; z__2.r = sum.r * t1.r - sum.i * t1.i, z__2.i = sum.r * t1.i + sum.i * t1.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; i__2 = j + ((c_dim1) << (1)); i__3 = j + ((c_dim1) << (1)); z__2.r = sum.r * t2.r - sum.i * t2.i, z__2.i = sum.r * t2.i + sum.i * t2.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; i__2 = j + c_dim1 * 3; i__3 = j + c_dim1 * 3; z__2.r = sum.r * t3.r - sum.i * t3.i, z__2.i = sum.r * t3.i + sum.i * t3.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; i__2 = j + ((c_dim1) << (2)); i__3 = j + ((c_dim1) << (2)); z__2.r = sum.r * t4.r - sum.i * t4.i, z__2.i = sum.r * t4.i + sum.i * t4.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; i__2 = j + c_dim1 * 5; i__3 = j + c_dim1 * 5; z__2.r = sum.r * t5.r - sum.i * t5.i, z__2.i = sum.r * t5.i + sum.i * t5.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; i__2 = j + c_dim1 * 6; i__3 = j + c_dim1 * 6; z__2.r = sum.r * t6.r - sum.i * t6.i, z__2.i = sum.r * t6.i + sum.i * t6.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; i__2 = j + c_dim1 * 7; i__3 = j + c_dim1 * 7; z__2.r = sum.r * t7.r - sum.i * t7.i, z__2.i = sum.r * t7.i + sum.i * t7.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; /* L340: */ } goto L410; L350: /* Special code for 8 x 8 Householder */ v1.r = v[1].r, v1.i = v[1].i; d_cnjg(&z__2, &v1); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t1.r = z__1.r, t1.i = z__1.i; v2.r = v[2].r, v2.i = v[2].i; d_cnjg(&z__2, &v2); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t2.r = z__1.r, t2.i = z__1.i; v3.r = v[3].r, v3.i = v[3].i; d_cnjg(&z__2, &v3); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t3.r = z__1.r, t3.i = z__1.i; v4.r = v[4].r, v4.i = v[4].i; d_cnjg(&z__2, &v4); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t4.r = z__1.r, t4.i = z__1.i; v5.r = v[5].r, v5.i = v[5].i; d_cnjg(&z__2, &v5); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t5.r = z__1.r, t5.i = z__1.i; v6.r = v[6].r, v6.i = v[6].i; d_cnjg(&z__2, &v6); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t6.r = z__1.r, t6.i = z__1.i; v7.r = v[7].r, v7.i = v[7].i; d_cnjg(&z__2, &v7); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t7.r = z__1.r, t7.i = z__1.i; v8.r = v[8].r, v8.i = v[8].i; d_cnjg(&z__2, &v8); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t8.r = z__1.r, t8.i = z__1.i; i__1 = *m; for (j = 1; j <= i__1; ++j) { i__2 = j + c_dim1; z__8.r = v1.r * c__[i__2].r - v1.i * c__[i__2].i, z__8.i = v1.r * c__[i__2].i + v1.i * c__[i__2].r; i__3 = j + ((c_dim1) << (1)); z__9.r = v2.r * c__[i__3].r - v2.i * c__[i__3].i, z__9.i = v2.r * c__[i__3].i + v2.i * c__[i__3].r; z__7.r = z__8.r + z__9.r, z__7.i = z__8.i + z__9.i; i__4 = j + c_dim1 * 3; z__10.r = v3.r * c__[i__4].r - v3.i * c__[i__4].i, z__10.i = v3.r * c__[i__4].i + v3.i * c__[i__4].r; z__6.r = z__7.r + z__10.r, z__6.i = z__7.i + z__10.i; i__5 = j + ((c_dim1) << (2)); z__11.r = v4.r * c__[i__5].r - v4.i * c__[i__5].i, z__11.i = v4.r * c__[i__5].i + v4.i * c__[i__5].r; z__5.r = z__6.r + z__11.r, z__5.i = z__6.i + z__11.i; i__6 = j + c_dim1 * 5; z__12.r = v5.r * c__[i__6].r - v5.i * c__[i__6].i, z__12.i = v5.r * c__[i__6].i + v5.i * c__[i__6].r; z__4.r = z__5.r + z__12.r, z__4.i = z__5.i + z__12.i; i__7 = j + c_dim1 * 6; z__13.r = v6.r * c__[i__7].r - v6.i * c__[i__7].i, z__13.i = v6.r * c__[i__7].i + v6.i * c__[i__7].r; z__3.r = z__4.r + z__13.r, z__3.i = z__4.i + z__13.i; i__8 = j + c_dim1 * 7; z__14.r = v7.r * c__[i__8].r - v7.i * c__[i__8].i, z__14.i = v7.r * c__[i__8].i + v7.i * c__[i__8].r; z__2.r = z__3.r + z__14.r, z__2.i = z__3.i + z__14.i; i__9 = j + ((c_dim1) << (3)); z__15.r = v8.r * c__[i__9].r - v8.i * c__[i__9].i, z__15.i = v8.r * c__[i__9].i + v8.i * c__[i__9].r; z__1.r = z__2.r + z__15.r, z__1.i = z__2.i + z__15.i; sum.r = z__1.r, sum.i = z__1.i; i__2 = j + c_dim1; i__3 = j + c_dim1; z__2.r = sum.r * t1.r - sum.i * t1.i, z__2.i = sum.r * t1.i + sum.i * t1.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; i__2 = j + ((c_dim1) << (1)); i__3 = j + ((c_dim1) << (1)); z__2.r = sum.r * t2.r - sum.i * t2.i, z__2.i = sum.r * t2.i + sum.i * t2.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; i__2 = j + c_dim1 * 3; i__3 = j + c_dim1 * 3; z__2.r = sum.r * t3.r - sum.i * t3.i, z__2.i = sum.r * t3.i + sum.i * t3.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; i__2 = j + ((c_dim1) << (2)); i__3 = j + ((c_dim1) << (2)); z__2.r = sum.r * t4.r - sum.i * t4.i, z__2.i = sum.r * t4.i + sum.i * t4.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; i__2 = j + c_dim1 * 5; i__3 = j + c_dim1 * 5; z__2.r = sum.r * t5.r - sum.i * t5.i, z__2.i = sum.r * t5.i + sum.i * t5.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; i__2 = j + c_dim1 * 6; i__3 = j + c_dim1 * 6; z__2.r = sum.r * t6.r - sum.i * t6.i, z__2.i = sum.r * t6.i + sum.i * t6.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; i__2 = j + c_dim1 * 7; i__3 = j + c_dim1 * 7; z__2.r = sum.r * t7.r - sum.i * t7.i, z__2.i = sum.r * t7.i + sum.i * t7.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; i__2 = j + ((c_dim1) << (3)); i__3 = j + ((c_dim1) << (3)); z__2.r = sum.r * t8.r - sum.i * t8.i, z__2.i = sum.r * t8.i + sum.i * t8.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; /* L360: */ } goto L410; L370: /* Special code for 9 x 9 Householder */ v1.r = v[1].r, v1.i = v[1].i; d_cnjg(&z__2, &v1); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t1.r = z__1.r, t1.i = z__1.i; v2.r = v[2].r, v2.i = v[2].i; d_cnjg(&z__2, &v2); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t2.r = z__1.r, t2.i = z__1.i; v3.r = v[3].r, v3.i = v[3].i; d_cnjg(&z__2, &v3); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t3.r = z__1.r, t3.i = z__1.i; v4.r = v[4].r, v4.i = v[4].i; d_cnjg(&z__2, &v4); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t4.r = z__1.r, t4.i = z__1.i; v5.r = v[5].r, v5.i = v[5].i; d_cnjg(&z__2, &v5); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t5.r = z__1.r, t5.i = z__1.i; v6.r = v[6].r, v6.i = v[6].i; d_cnjg(&z__2, &v6); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t6.r = z__1.r, t6.i = z__1.i; v7.r = v[7].r, v7.i = v[7].i; d_cnjg(&z__2, &v7); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t7.r = z__1.r, t7.i = z__1.i; v8.r = v[8].r, v8.i = v[8].i; d_cnjg(&z__2, &v8); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t8.r = z__1.r, t8.i = z__1.i; v9.r = v[9].r, v9.i = v[9].i; d_cnjg(&z__2, &v9); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t9.r = z__1.r, t9.i = z__1.i; i__1 = *m; for (j = 1; j <= i__1; ++j) { i__2 = j + c_dim1; z__9.r = v1.r * c__[i__2].r - v1.i * c__[i__2].i, z__9.i = v1.r * c__[i__2].i + v1.i * c__[i__2].r; i__3 = j + ((c_dim1) << (1)); z__10.r = v2.r * c__[i__3].r - v2.i * c__[i__3].i, z__10.i = v2.r * c__[i__3].i + v2.i * c__[i__3].r; z__8.r = z__9.r + z__10.r, z__8.i = z__9.i + z__10.i; i__4 = j + c_dim1 * 3; z__11.r = v3.r * c__[i__4].r - v3.i * c__[i__4].i, z__11.i = v3.r * c__[i__4].i + v3.i * c__[i__4].r; z__7.r = z__8.r + z__11.r, z__7.i = z__8.i + z__11.i; i__5 = j + ((c_dim1) << (2)); z__12.r = v4.r * c__[i__5].r - v4.i * c__[i__5].i, z__12.i = v4.r * c__[i__5].i + v4.i * c__[i__5].r; z__6.r = z__7.r + z__12.r, z__6.i = z__7.i + z__12.i; i__6 = j + c_dim1 * 5; z__13.r = v5.r * c__[i__6].r - v5.i * c__[i__6].i, z__13.i = v5.r * c__[i__6].i + v5.i * c__[i__6].r; z__5.r = z__6.r + z__13.r, z__5.i = z__6.i + z__13.i; i__7 = j + c_dim1 * 6; z__14.r = v6.r * c__[i__7].r - v6.i * c__[i__7].i, z__14.i = v6.r * c__[i__7].i + v6.i * c__[i__7].r; z__4.r = z__5.r + z__14.r, z__4.i = z__5.i + z__14.i; i__8 = j + c_dim1 * 7; z__15.r = v7.r * c__[i__8].r - v7.i * c__[i__8].i, z__15.i = v7.r * c__[i__8].i + v7.i * c__[i__8].r; z__3.r = z__4.r + z__15.r, z__3.i = z__4.i + z__15.i; i__9 = j + ((c_dim1) << (3)); z__16.r = v8.r * c__[i__9].r - v8.i * c__[i__9].i, z__16.i = v8.r * c__[i__9].i + v8.i * c__[i__9].r; z__2.r = z__3.r + z__16.r, z__2.i = z__3.i + z__16.i; i__10 = j + c_dim1 * 9; z__17.r = v9.r * c__[i__10].r - v9.i * c__[i__10].i, z__17.i = v9.r * c__[i__10].i + v9.i * c__[i__10].r; z__1.r = z__2.r + z__17.r, z__1.i = z__2.i + z__17.i; sum.r = z__1.r, sum.i = z__1.i; i__2 = j + c_dim1; i__3 = j + c_dim1; z__2.r = sum.r * t1.r - sum.i * t1.i, z__2.i = sum.r * t1.i + sum.i * t1.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; i__2 = j + ((c_dim1) << (1)); i__3 = j + ((c_dim1) << (1)); z__2.r = sum.r * t2.r - sum.i * t2.i, z__2.i = sum.r * t2.i + sum.i * t2.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; i__2 = j + c_dim1 * 3; i__3 = j + c_dim1 * 3; z__2.r = sum.r * t3.r - sum.i * t3.i, z__2.i = sum.r * t3.i + sum.i * t3.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; i__2 = j + ((c_dim1) << (2)); i__3 = j + ((c_dim1) << (2)); z__2.r = sum.r * t4.r - sum.i * t4.i, z__2.i = sum.r * t4.i + sum.i * t4.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; i__2 = j + c_dim1 * 5; i__3 = j + c_dim1 * 5; z__2.r = sum.r * t5.r - sum.i * t5.i, z__2.i = sum.r * t5.i + sum.i * t5.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; i__2 = j + c_dim1 * 6; i__3 = j + c_dim1 * 6; z__2.r = sum.r * t6.r - sum.i * t6.i, z__2.i = sum.r * t6.i + sum.i * t6.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; i__2 = j + c_dim1 * 7; i__3 = j + c_dim1 * 7; z__2.r = sum.r * t7.r - sum.i * t7.i, z__2.i = sum.r * t7.i + sum.i * t7.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; i__2 = j + ((c_dim1) << (3)); i__3 = j + ((c_dim1) << (3)); z__2.r = sum.r * t8.r - sum.i * t8.i, z__2.i = sum.r * t8.i + sum.i * t8.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; i__2 = j + c_dim1 * 9; i__3 = j + c_dim1 * 9; z__2.r = sum.r * t9.r - sum.i * t9.i, z__2.i = sum.r * t9.i + sum.i * t9.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; /* L380: */ } goto L410; L390: /* Special code for 10 x 10 Householder */ v1.r = v[1].r, v1.i = v[1].i; d_cnjg(&z__2, &v1); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t1.r = z__1.r, t1.i = z__1.i; v2.r = v[2].r, v2.i = v[2].i; d_cnjg(&z__2, &v2); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t2.r = z__1.r, t2.i = z__1.i; v3.r = v[3].r, v3.i = v[3].i; d_cnjg(&z__2, &v3); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t3.r = z__1.r, t3.i = z__1.i; v4.r = v[4].r, v4.i = v[4].i; d_cnjg(&z__2, &v4); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t4.r = z__1.r, t4.i = z__1.i; v5.r = v[5].r, v5.i = v[5].i; d_cnjg(&z__2, &v5); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t5.r = z__1.r, t5.i = z__1.i; v6.r = v[6].r, v6.i = v[6].i; d_cnjg(&z__2, &v6); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t6.r = z__1.r, t6.i = z__1.i; v7.r = v[7].r, v7.i = v[7].i; d_cnjg(&z__2, &v7); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t7.r = z__1.r, t7.i = z__1.i; v8.r = v[8].r, v8.i = v[8].i; d_cnjg(&z__2, &v8); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t8.r = z__1.r, t8.i = z__1.i; v9.r = v[9].r, v9.i = v[9].i; d_cnjg(&z__2, &v9); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t9.r = z__1.r, t9.i = z__1.i; v10.r = v[10].r, v10.i = v[10].i; d_cnjg(&z__2, &v10); z__1.r = tau->r * z__2.r - tau->i * z__2.i, z__1.i = tau->r * z__2.i + tau->i * z__2.r; t10.r = z__1.r, t10.i = z__1.i; i__1 = *m; for (j = 1; j <= i__1; ++j) { i__2 = j + c_dim1; z__10.r = v1.r * c__[i__2].r - v1.i * c__[i__2].i, z__10.i = v1.r * c__[i__2].i + v1.i * c__[i__2].r; i__3 = j + ((c_dim1) << (1)); z__11.r = v2.r * c__[i__3].r - v2.i * c__[i__3].i, z__11.i = v2.r * c__[i__3].i + v2.i * c__[i__3].r; z__9.r = z__10.r + z__11.r, z__9.i = z__10.i + z__11.i; i__4 = j + c_dim1 * 3; z__12.r = v3.r * c__[i__4].r - v3.i * c__[i__4].i, z__12.i = v3.r * c__[i__4].i + v3.i * c__[i__4].r; z__8.r = z__9.r + z__12.r, z__8.i = z__9.i + z__12.i; i__5 = j + ((c_dim1) << (2)); z__13.r = v4.r * c__[i__5].r - v4.i * c__[i__5].i, z__13.i = v4.r * c__[i__5].i + v4.i * c__[i__5].r; z__7.r = z__8.r + z__13.r, z__7.i = z__8.i + z__13.i; i__6 = j + c_dim1 * 5; z__14.r = v5.r * c__[i__6].r - v5.i * c__[i__6].i, z__14.i = v5.r * c__[i__6].i + v5.i * c__[i__6].r; z__6.r = z__7.r + z__14.r, z__6.i = z__7.i + z__14.i; i__7 = j + c_dim1 * 6; z__15.r = v6.r * c__[i__7].r - v6.i * c__[i__7].i, z__15.i = v6.r * c__[i__7].i + v6.i * c__[i__7].r; z__5.r = z__6.r + z__15.r, z__5.i = z__6.i + z__15.i; i__8 = j + c_dim1 * 7; z__16.r = v7.r * c__[i__8].r - v7.i * c__[i__8].i, z__16.i = v7.r * c__[i__8].i + v7.i * c__[i__8].r; z__4.r = z__5.r + z__16.r, z__4.i = z__5.i + z__16.i; i__9 = j + ((c_dim1) << (3)); z__17.r = v8.r * c__[i__9].r - v8.i * c__[i__9].i, z__17.i = v8.r * c__[i__9].i + v8.i * c__[i__9].r; z__3.r = z__4.r + z__17.r, z__3.i = z__4.i + z__17.i; i__10 = j + c_dim1 * 9; z__18.r = v9.r * c__[i__10].r - v9.i * c__[i__10].i, z__18.i = v9.r * c__[i__10].i + v9.i * c__[i__10].r; z__2.r = z__3.r + z__18.r, z__2.i = z__3.i + z__18.i; i__11 = j + c_dim1 * 10; z__19.r = v10.r * c__[i__11].r - v10.i * c__[i__11].i, z__19.i = v10.r * c__[i__11].i + v10.i * c__[i__11].r; z__1.r = z__2.r + z__19.r, z__1.i = z__2.i + z__19.i; sum.r = z__1.r, sum.i = z__1.i; i__2 = j + c_dim1; i__3 = j + c_dim1; z__2.r = sum.r * t1.r - sum.i * t1.i, z__2.i = sum.r * t1.i + sum.i * t1.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; i__2 = j + ((c_dim1) << (1)); i__3 = j + ((c_dim1) << (1)); z__2.r = sum.r * t2.r - sum.i * t2.i, z__2.i = sum.r * t2.i + sum.i * t2.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; i__2 = j + c_dim1 * 3; i__3 = j + c_dim1 * 3; z__2.r = sum.r * t3.r - sum.i * t3.i, z__2.i = sum.r * t3.i + sum.i * t3.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; i__2 = j + ((c_dim1) << (2)); i__3 = j + ((c_dim1) << (2)); z__2.r = sum.r * t4.r - sum.i * t4.i, z__2.i = sum.r * t4.i + sum.i * t4.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; i__2 = j + c_dim1 * 5; i__3 = j + c_dim1 * 5; z__2.r = sum.r * t5.r - sum.i * t5.i, z__2.i = sum.r * t5.i + sum.i * t5.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; i__2 = j + c_dim1 * 6; i__3 = j + c_dim1 * 6; z__2.r = sum.r * t6.r - sum.i * t6.i, z__2.i = sum.r * t6.i + sum.i * t6.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; i__2 = j + c_dim1 * 7; i__3 = j + c_dim1 * 7; z__2.r = sum.r * t7.r - sum.i * t7.i, z__2.i = sum.r * t7.i + sum.i * t7.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; i__2 = j + ((c_dim1) << (3)); i__3 = j + ((c_dim1) << (3)); z__2.r = sum.r * t8.r - sum.i * t8.i, z__2.i = sum.r * t8.i + sum.i * t8.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; i__2 = j + c_dim1 * 9; i__3 = j + c_dim1 * 9; z__2.r = sum.r * t9.r - sum.i * t9.i, z__2.i = sum.r * t9.i + sum.i * t9.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; i__2 = j + c_dim1 * 10; i__3 = j + c_dim1 * 10; z__2.r = sum.r * t10.r - sum.i * t10.i, z__2.i = sum.r * t10.i + sum.i * t10.r; z__1.r = c__[i__3].r - z__2.r, z__1.i = c__[i__3].i - z__2.i; c__[i__2].r = z__1.r, c__[i__2].i = z__1.i; /* L400: */ } goto L410; } L410: return 0; /* End of ZLARFX */ } /* zlarfx_ */ /* Subroutine */ int zlascl_(char *type__, integer *kl, integer *ku, doublereal *cfrom, doublereal *cto, integer *m, integer *n, doublecomplex *a, integer *lda, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3, i__4, i__5; doublecomplex z__1; /* Local variables */ static integer i__, j, k1, k2, k3, k4; static doublereal mul, cto1; static logical done; static doublereal ctoc; extern logical lsame_(char *, char *); static integer itype; static doublereal cfrom1; static doublereal cfromc; extern /* Subroutine */ int xerbla_(char *, integer *); static doublereal bignum, smlnum; /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University February 29, 1992 Purpose ======= ZLASCL multiplies the M by N complex matrix A by the real scalar CTO/CFROM. This is done without over/underflow as long as the final result CTO*A(I,J)/CFROM does not over/underflow. TYPE specifies that A may be full, upper triangular, lower triangular, upper Hessenberg, or banded. Arguments ========= TYPE (input) CHARACTER*1 TYPE indices the storage type of the input matrix. = 'G': A is a full matrix. = 'L': A is a lower triangular matrix. = 'U': A is an upper triangular matrix. = 'H': A is an upper Hessenberg matrix. = 'B': A is a symmetric band matrix with lower bandwidth KL and upper bandwidth KU and with the only the lower half stored. = 'Q': A is a symmetric band matrix with lower bandwidth KL and upper bandwidth KU and with the only the upper half stored. = 'Z': A is a band matrix with lower bandwidth KL and upper bandwidth KU. KL (input) INTEGER The lower bandwidth of A. Referenced only if TYPE = 'B', 'Q' or 'Z'. KU (input) INTEGER The upper bandwidth of A. Referenced only if TYPE = 'B', 'Q' or 'Z'. CFROM (input) DOUBLE PRECISION CTO (input) DOUBLE PRECISION The matrix A is multiplied by CTO/CFROM. A(I,J) is computed without over/underflow if the final result CTO*A(I,J)/CFROM can be represented without over/underflow. CFROM must be nonzero. M (input) INTEGER The number of rows of the matrix A. M >= 0. N (input) INTEGER The number of columns of the matrix A. N >= 0. A (input/output) COMPLEX*16 array, dimension (LDA,M) The matrix to be multiplied by CTO/CFROM. See TYPE for the storage type. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,M). INFO (output) INTEGER 0 - successful exit <0 - if INFO = -i, the i-th argument had an illegal value. ===================================================================== Test the input arguments */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; /* Function Body */ *info = 0; if (lsame_(type__, "G")) { itype = 0; } else if (lsame_(type__, "L")) { itype = 1; } else if (lsame_(type__, "U")) { itype = 2; } else if (lsame_(type__, "H")) { itype = 3; } else if (lsame_(type__, "B")) { itype = 4; } else if (lsame_(type__, "Q")) { itype = 5; } else if (lsame_(type__, "Z")) { itype = 6; } else { itype = -1; } if (itype == -1) { *info = -1; } else if (*cfrom == 0.) { *info = -4; } else if (*m < 0) { *info = -6; } else if (((*n < 0) || (itype == 4 && *n != *m)) || (itype == 5 && *n != *m)) { *info = -7; } else if (itype <= 3 && *lda < max(1,*m)) { *info = -9; } else if (itype >= 4) { /* Computing MAX */ i__1 = *m - 1; if ((*kl < 0) || (*kl > max(i__1,0))) { *info = -2; } else /* if(complicated condition) */ { /* Computing MAX */ i__1 = *n - 1; if (((*ku < 0) || (*ku > max(i__1,0))) || (((itype == 4) || ( itype == 5)) && *kl != *ku)) { *info = -3; } else if (((itype == 4 && *lda < *kl + 1) || (itype == 5 && *lda < *ku + 1)) || (itype == 6 && *lda < ((*kl) << (1)) + *ku + 1)) { *info = -9; } } } if (*info != 0) { i__1 = -(*info); xerbla_("ZLASCL", &i__1); return 0; } /* Quick return if possible */ if ((*n == 0) || (*m == 0)) { return 0; } /* Get machine parameters */ smlnum = SAFEMINIMUM; bignum = 1. / smlnum; cfromc = *cfrom; ctoc = *cto; L10: cfrom1 = cfromc * smlnum; cto1 = ctoc / bignum; if (abs(cfrom1) > abs(ctoc) && ctoc != 0.) { mul = smlnum; done = FALSE_; cfromc = cfrom1; } else if (abs(cto1) > abs(cfromc)) { mul = bignum; done = FALSE_; ctoc = cto1; } else { mul = ctoc / cfromc; done = TRUE_; } if (itype == 0) { /* Full matrix */ i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * a_dim1; i__4 = i__ + j * a_dim1; z__1.r = mul * a[i__4].r, z__1.i = mul * a[i__4].i; a[i__3].r = z__1.r, a[i__3].i = z__1.i; /* L20: */ } /* L30: */ } } else if (itype == 1) { /* Lower triangular matrix */ i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = j; i__ <= i__2; ++i__) { i__3 = i__ + j * a_dim1; i__4 = i__ + j * a_dim1; z__1.r = mul * a[i__4].r, z__1.i = mul * a[i__4].i; a[i__3].r = z__1.r, a[i__3].i = z__1.i; /* L40: */ } /* L50: */ } } else if (itype == 2) { /* Upper triangular matrix */ i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = min(j,*m); for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * a_dim1; i__4 = i__ + j * a_dim1; z__1.r = mul * a[i__4].r, z__1.i = mul * a[i__4].i; a[i__3].r = z__1.r, a[i__3].i = z__1.i; /* L60: */ } /* L70: */ } } else if (itype == 3) { /* Upper Hessenberg matrix */ i__1 = *n; for (j = 1; j <= i__1; ++j) { /* Computing MIN */ i__3 = j + 1; i__2 = min(i__3,*m); for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * a_dim1; i__4 = i__ + j * a_dim1; z__1.r = mul * a[i__4].r, z__1.i = mul * a[i__4].i; a[i__3].r = z__1.r, a[i__3].i = z__1.i; /* L80: */ } /* L90: */ } } else if (itype == 4) { /* Lower half of a symmetric band matrix */ k3 = *kl + 1; k4 = *n + 1; i__1 = *n; for (j = 1; j <= i__1; ++j) { /* Computing MIN */ i__3 = k3, i__4 = k4 - j; i__2 = min(i__3,i__4); for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * a_dim1; i__4 = i__ + j * a_dim1; z__1.r = mul * a[i__4].r, z__1.i = mul * a[i__4].i; a[i__3].r = z__1.r, a[i__3].i = z__1.i; /* L100: */ } /* L110: */ } } else if (itype == 5) { /* Upper half of a symmetric band matrix */ k1 = *ku + 2; k3 = *ku + 1; i__1 = *n; for (j = 1; j <= i__1; ++j) { /* Computing MAX */ i__2 = k1 - j; i__3 = k3; for (i__ = max(i__2,1); i__ <= i__3; ++i__) { i__2 = i__ + j * a_dim1; i__4 = i__ + j * a_dim1; z__1.r = mul * a[i__4].r, z__1.i = mul * a[i__4].i; a[i__2].r = z__1.r, a[i__2].i = z__1.i; /* L120: */ } /* L130: */ } } else if (itype == 6) { /* Band matrix */ k1 = *kl + *ku + 2; k2 = *kl + 1; k3 = ((*kl) << (1)) + *ku + 1; k4 = *kl + *ku + 1 + *m; i__1 = *n; for (j = 1; j <= i__1; ++j) { /* Computing MAX */ i__3 = k1 - j; /* Computing MIN */ i__4 = k3, i__5 = k4 - j; i__2 = min(i__4,i__5); for (i__ = max(i__3,k2); i__ <= i__2; ++i__) { i__3 = i__ + j * a_dim1; i__4 = i__ + j * a_dim1; z__1.r = mul * a[i__4].r, z__1.i = mul * a[i__4].i; a[i__3].r = z__1.r, a[i__3].i = z__1.i; /* L140: */ } /* L150: */ } } if (! done) { goto L10; } return 0; /* End of ZLASCL */ } /* zlascl_ */ /* Subroutine */ int zlaset_(char *uplo, integer *m, integer *n, doublecomplex *alpha, doublecomplex *beta, doublecomplex *a, integer * lda) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3; /* Local variables */ static integer i__, j; extern logical lsame_(char *, char *); /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University October 31, 1992 Purpose ======= ZLASET initializes a 2-D array A to BETA on the diagonal and ALPHA on the offdiagonals. Arguments ========= UPLO (input) CHARACTER*1 Specifies the part of the matrix A to be set. = 'U': Upper triangular part is set. The lower triangle is unchanged. = 'L': Lower triangular part is set. The upper triangle is unchanged. Otherwise: All of the matrix A is set. M (input) INTEGER On entry, M specifies the number of rows of A. N (input) INTEGER On entry, N specifies the number of columns of A. ALPHA (input) COMPLEX*16 All the offdiagonal array elements are set to ALPHA. BETA (input) COMPLEX*16 All the diagonal array elements are set to BETA. A (input/output) COMPLEX*16 array, dimension (LDA,N) On entry, the m by n matrix A. On exit, A(i,j) = ALPHA, 1 <= i <= m, 1 <= j <= n, i.ne.j; A(i,i) = BETA , 1 <= i <= min(m,n) LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,M). ===================================================================== */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; /* Function Body */ if (lsame_(uplo, "U")) { /* Set the diagonal to BETA and the strictly upper triangular part of the array to ALPHA. */ i__1 = *n; for (j = 2; j <= i__1; ++j) { /* Computing MIN */ i__3 = j - 1; i__2 = min(i__3,*m); for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * a_dim1; a[i__3].r = alpha->r, a[i__3].i = alpha->i; /* L10: */ } /* L20: */ } i__1 = min(*n,*m); for (i__ = 1; i__ <= i__1; ++i__) { i__2 = i__ + i__ * a_dim1; a[i__2].r = beta->r, a[i__2].i = beta->i; /* L30: */ } } else if (lsame_(uplo, "L")) { /* Set the diagonal to BETA and the strictly lower triangular part of the array to ALPHA. */ i__1 = min(*m,*n); for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = j + 1; i__ <= i__2; ++i__) { i__3 = i__ + j * a_dim1; a[i__3].r = alpha->r, a[i__3].i = alpha->i; /* L40: */ } /* L50: */ } i__1 = min(*n,*m); for (i__ = 1; i__ <= i__1; ++i__) { i__2 = i__ + i__ * a_dim1; a[i__2].r = beta->r, a[i__2].i = beta->i; /* L60: */ } } else { /* Set the array to BETA on the diagonal and ALPHA on the offdiagonal. */ i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * a_dim1; a[i__3].r = alpha->r, a[i__3].i = alpha->i; /* L70: */ } /* L80: */ } i__1 = min(*m,*n); for (i__ = 1; i__ <= i__1; ++i__) { i__2 = i__ + i__ * a_dim1; a[i__2].r = beta->r, a[i__2].i = beta->i; /* L90: */ } } return 0; /* End of ZLASET */ } /* zlaset_ */ /* Subroutine */ int zlasr_(char *side, char *pivot, char *direct, integer *m, integer *n, doublereal *c__, doublereal *s, doublecomplex *a, integer *lda) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3, i__4; doublecomplex z__1, z__2, z__3; /* Local variables */ static integer i__, j, info; static doublecomplex temp; extern logical lsame_(char *, char *); static doublereal ctemp, stemp; extern /* Subroutine */ int xerbla_(char *, integer *); /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University October 31, 1992 Purpose ======= ZLASR performs the transformation A := P*A, when SIDE = 'L' or 'l' ( Left-hand side ) A := A*P', when SIDE = 'R' or 'r' ( Right-hand side ) where A is an m by n complex matrix and P is an orthogonal matrix, consisting of a sequence of plane rotations determined by the parameters PIVOT and DIRECT as follows ( z = m when SIDE = 'L' or 'l' and z = n when SIDE = 'R' or 'r' ): When DIRECT = 'F' or 'f' ( Forward sequence ) then P = P( z - 1 )*...*P( 2 )*P( 1 ), and when DIRECT = 'B' or 'b' ( Backward sequence ) then P = P( 1 )*P( 2 )*...*P( z - 1 ), where P( k ) is a plane rotation matrix for the following planes: when PIVOT = 'V' or 'v' ( Variable pivot ), the plane ( k, k + 1 ) when PIVOT = 'T' or 't' ( Top pivot ), the plane ( 1, k + 1 ) when PIVOT = 'B' or 'b' ( Bottom pivot ), the plane ( k, z ) c( k ) and s( k ) must contain the cosine and sine that define the matrix P( k ). The two by two plane rotation part of the matrix P( k ), R( k ), is assumed to be of the form R( k ) = ( c( k ) s( k ) ). ( -s( k ) c( k ) ) Arguments ========= SIDE (input) CHARACTER*1 Specifies whether the plane rotation matrix P is applied to A on the left or the right. = 'L': Left, compute A := P*A = 'R': Right, compute A:= A*P' DIRECT (input) CHARACTER*1 Specifies whether P is a forward or backward sequence of plane rotations. = 'F': Forward, P = P( z - 1 )*...*P( 2 )*P( 1 ) = 'B': Backward, P = P( 1 )*P( 2 )*...*P( z - 1 ) PIVOT (input) CHARACTER*1 Specifies the plane for which P(k) is a plane rotation matrix. = 'V': Variable pivot, the plane (k,k+1) = 'T': Top pivot, the plane (1,k+1) = 'B': Bottom pivot, the plane (k,z) M (input) INTEGER The number of rows of the matrix A. If m <= 1, an immediate return is effected. N (input) INTEGER The number of columns of the matrix A. If n <= 1, an immediate return is effected. C, S (input) DOUBLE PRECISION arrays, dimension (M-1) if SIDE = 'L' (N-1) if SIDE = 'R' c(k) and s(k) contain the cosine and sine that define the matrix P(k). The two by two plane rotation part of the matrix P(k), R(k), is assumed to be of the form R( k ) = ( c( k ) s( k ) ). ( -s( k ) c( k ) ) A (input/output) COMPLEX*16 array, dimension (LDA,N) The m by n matrix A. On exit, A is overwritten by P*A if SIDE = 'R' or by A*P' if SIDE = 'L'. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,M). ===================================================================== Test the input parameters */ /* Parameter adjustments */ --c__; --s; a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; /* Function Body */ info = 0; if (! ((lsame_(side, "L")) || (lsame_(side, "R")))) { info = 1; } else if (! (((lsame_(pivot, "V")) || (lsame_( pivot, "T"))) || (lsame_(pivot, "B")))) { info = 2; } else if (! ((lsame_(direct, "F")) || (lsame_( direct, "B")))) { info = 3; } else if (*m < 0) { info = 4; } else if (*n < 0) { info = 5; } else if (*lda < max(1,*m)) { info = 9; } if (info != 0) { xerbla_("ZLASR ", &info); return 0; } /* Quick return if possible */ if ((*m == 0) || (*n == 0)) { return 0; } if (lsame_(side, "L")) { /* Form P * A */ if (lsame_(pivot, "V")) { if (lsame_(direct, "F")) { i__1 = *m - 1; for (j = 1; j <= i__1; ++j) { ctemp = c__[j]; stemp = s[j]; if ((ctemp != 1.) || (stemp != 0.)) { i__2 = *n; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = j + 1 + i__ * a_dim1; temp.r = a[i__3].r, temp.i = a[i__3].i; i__3 = j + 1 + i__ * a_dim1; z__2.r = ctemp * temp.r, z__2.i = ctemp * temp.i; i__4 = j + i__ * a_dim1; z__3.r = stemp * a[i__4].r, z__3.i = stemp * a[ i__4].i; z__1.r = z__2.r - z__3.r, z__1.i = z__2.i - z__3.i; a[i__3].r = z__1.r, a[i__3].i = z__1.i; i__3 = j + i__ * a_dim1; z__2.r = stemp * temp.r, z__2.i = stemp * temp.i; i__4 = j + i__ * a_dim1; z__3.r = ctemp * a[i__4].r, z__3.i = ctemp * a[ i__4].i; z__1.r = z__2.r + z__3.r, z__1.i = z__2.i + z__3.i; a[i__3].r = z__1.r, a[i__3].i = z__1.i; /* L10: */ } } /* L20: */ } } else if (lsame_(direct, "B")) { for (j = *m - 1; j >= 1; --j) { ctemp = c__[j]; stemp = s[j]; if ((ctemp != 1.) || (stemp != 0.)) { i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = j + 1 + i__ * a_dim1; temp.r = a[i__2].r, temp.i = a[i__2].i; i__2 = j + 1 + i__ * a_dim1; z__2.r = ctemp * temp.r, z__2.i = ctemp * temp.i; i__3 = j + i__ * a_dim1; z__3.r = stemp * a[i__3].r, z__3.i = stemp * a[ i__3].i; z__1.r = z__2.r - z__3.r, z__1.i = z__2.i - z__3.i; a[i__2].r = z__1.r, a[i__2].i = z__1.i; i__2 = j + i__ * a_dim1; z__2.r = stemp * temp.r, z__2.i = stemp * temp.i; i__3 = j + i__ * a_dim1; z__3.r = ctemp * a[i__3].r, z__3.i = ctemp * a[ i__3].i; z__1.r = z__2.r + z__3.r, z__1.i = z__2.i + z__3.i; a[i__2].r = z__1.r, a[i__2].i = z__1.i; /* L30: */ } } /* L40: */ } } } else if (lsame_(pivot, "T")) { if (lsame_(direct, "F")) { i__1 = *m; for (j = 2; j <= i__1; ++j) { ctemp = c__[j - 1]; stemp = s[j - 1]; if ((ctemp != 1.) || (stemp != 0.)) { i__2 = *n; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = j + i__ * a_dim1; temp.r = a[i__3].r, temp.i = a[i__3].i; i__3 = j + i__ * a_dim1; z__2.r = ctemp * temp.r, z__2.i = ctemp * temp.i; i__4 = i__ * a_dim1 + 1; z__3.r = stemp * a[i__4].r, z__3.i = stemp * a[ i__4].i; z__1.r = z__2.r - z__3.r, z__1.i = z__2.i - z__3.i; a[i__3].r = z__1.r, a[i__3].i = z__1.i; i__3 = i__ * a_dim1 + 1; z__2.r = stemp * temp.r, z__2.i = stemp * temp.i; i__4 = i__ * a_dim1 + 1; z__3.r = ctemp * a[i__4].r, z__3.i = ctemp * a[ i__4].i; z__1.r = z__2.r + z__3.r, z__1.i = z__2.i + z__3.i; a[i__3].r = z__1.r, a[i__3].i = z__1.i; /* L50: */ } } /* L60: */ } } else if (lsame_(direct, "B")) { for (j = *m; j >= 2; --j) { ctemp = c__[j - 1]; stemp = s[j - 1]; if ((ctemp != 1.) || (stemp != 0.)) { i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = j + i__ * a_dim1; temp.r = a[i__2].r, temp.i = a[i__2].i; i__2 = j + i__ * a_dim1; z__2.r = ctemp * temp.r, z__2.i = ctemp * temp.i; i__3 = i__ * a_dim1 + 1; z__3.r = stemp * a[i__3].r, z__3.i = stemp * a[ i__3].i; z__1.r = z__2.r - z__3.r, z__1.i = z__2.i - z__3.i; a[i__2].r = z__1.r, a[i__2].i = z__1.i; i__2 = i__ * a_dim1 + 1; z__2.r = stemp * temp.r, z__2.i = stemp * temp.i; i__3 = i__ * a_dim1 + 1; z__3.r = ctemp * a[i__3].r, z__3.i = ctemp * a[ i__3].i; z__1.r = z__2.r + z__3.r, z__1.i = z__2.i + z__3.i; a[i__2].r = z__1.r, a[i__2].i = z__1.i; /* L70: */ } } /* L80: */ } } } else if (lsame_(pivot, "B")) { if (lsame_(direct, "F")) { i__1 = *m - 1; for (j = 1; j <= i__1; ++j) { ctemp = c__[j]; stemp = s[j]; if ((ctemp != 1.) || (stemp != 0.)) { i__2 = *n; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = j + i__ * a_dim1; temp.r = a[i__3].r, temp.i = a[i__3].i; i__3 = j + i__ * a_dim1; i__4 = *m + i__ * a_dim1; z__2.r = stemp * a[i__4].r, z__2.i = stemp * a[ i__4].i; z__3.r = ctemp * temp.r, z__3.i = ctemp * temp.i; z__1.r = z__2.r + z__3.r, z__1.i = z__2.i + z__3.i; a[i__3].r = z__1.r, a[i__3].i = z__1.i; i__3 = *m + i__ * a_dim1; i__4 = *m + i__ * a_dim1; z__2.r = ctemp * a[i__4].r, z__2.i = ctemp * a[ i__4].i; z__3.r = stemp * temp.r, z__3.i = stemp * temp.i; z__1.r = z__2.r - z__3.r, z__1.i = z__2.i - z__3.i; a[i__3].r = z__1.r, a[i__3].i = z__1.i; /* L90: */ } } /* L100: */ } } else if (lsame_(direct, "B")) { for (j = *m - 1; j >= 1; --j) { ctemp = c__[j]; stemp = s[j]; if ((ctemp != 1.) || (stemp != 0.)) { i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = j + i__ * a_dim1; temp.r = a[i__2].r, temp.i = a[i__2].i; i__2 = j + i__ * a_dim1; i__3 = *m + i__ * a_dim1; z__2.r = stemp * a[i__3].r, z__2.i = stemp * a[ i__3].i; z__3.r = ctemp * temp.r, z__3.i = ctemp * temp.i; z__1.r = z__2.r + z__3.r, z__1.i = z__2.i + z__3.i; a[i__2].r = z__1.r, a[i__2].i = z__1.i; i__2 = *m + i__ * a_dim1; i__3 = *m + i__ * a_dim1; z__2.r = ctemp * a[i__3].r, z__2.i = ctemp * a[ i__3].i; z__3.r = stemp * temp.r, z__3.i = stemp * temp.i; z__1.r = z__2.r - z__3.r, z__1.i = z__2.i - z__3.i; a[i__2].r = z__1.r, a[i__2].i = z__1.i; /* L110: */ } } /* L120: */ } } } } else if (lsame_(side, "R")) { /* Form A * P' */ if (lsame_(pivot, "V")) { if (lsame_(direct, "F")) { i__1 = *n - 1; for (j = 1; j <= i__1; ++j) { ctemp = c__[j]; stemp = s[j]; if ((ctemp != 1.) || (stemp != 0.)) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + (j + 1) * a_dim1; temp.r = a[i__3].r, temp.i = a[i__3].i; i__3 = i__ + (j + 1) * a_dim1; z__2.r = ctemp * temp.r, z__2.i = ctemp * temp.i; i__4 = i__ + j * a_dim1; z__3.r = stemp * a[i__4].r, z__3.i = stemp * a[ i__4].i; z__1.r = z__2.r - z__3.r, z__1.i = z__2.i - z__3.i; a[i__3].r = z__1.r, a[i__3].i = z__1.i; i__3 = i__ + j * a_dim1; z__2.r = stemp * temp.r, z__2.i = stemp * temp.i; i__4 = i__ + j * a_dim1; z__3.r = ctemp * a[i__4].r, z__3.i = ctemp * a[ i__4].i; z__1.r = z__2.r + z__3.r, z__1.i = z__2.i + z__3.i; a[i__3].r = z__1.r, a[i__3].i = z__1.i; /* L130: */ } } /* L140: */ } } else if (lsame_(direct, "B")) { for (j = *n - 1; j >= 1; --j) { ctemp = c__[j]; stemp = s[j]; if ((ctemp != 1.) || (stemp != 0.)) { i__1 = *m; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = i__ + (j + 1) * a_dim1; temp.r = a[i__2].r, temp.i = a[i__2].i; i__2 = i__ + (j + 1) * a_dim1; z__2.r = ctemp * temp.r, z__2.i = ctemp * temp.i; i__3 = i__ + j * a_dim1; z__3.r = stemp * a[i__3].r, z__3.i = stemp * a[ i__3].i; z__1.r = z__2.r - z__3.r, z__1.i = z__2.i - z__3.i; a[i__2].r = z__1.r, a[i__2].i = z__1.i; i__2 = i__ + j * a_dim1; z__2.r = stemp * temp.r, z__2.i = stemp * temp.i; i__3 = i__ + j * a_dim1; z__3.r = ctemp * a[i__3].r, z__3.i = ctemp * a[ i__3].i; z__1.r = z__2.r + z__3.r, z__1.i = z__2.i + z__3.i; a[i__2].r = z__1.r, a[i__2].i = z__1.i; /* L150: */ } } /* L160: */ } } } else if (lsame_(pivot, "T")) { if (lsame_(direct, "F")) { i__1 = *n; for (j = 2; j <= i__1; ++j) { ctemp = c__[j - 1]; stemp = s[j - 1]; if ((ctemp != 1.) || (stemp != 0.)) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * a_dim1; temp.r = a[i__3].r, temp.i = a[i__3].i; i__3 = i__ + j * a_dim1; z__2.r = ctemp * temp.r, z__2.i = ctemp * temp.i; i__4 = i__ + a_dim1; z__3.r = stemp * a[i__4].r, z__3.i = stemp * a[ i__4].i; z__1.r = z__2.r - z__3.r, z__1.i = z__2.i - z__3.i; a[i__3].r = z__1.r, a[i__3].i = z__1.i; i__3 = i__ + a_dim1; z__2.r = stemp * temp.r, z__2.i = stemp * temp.i; i__4 = i__ + a_dim1; z__3.r = ctemp * a[i__4].r, z__3.i = ctemp * a[ i__4].i; z__1.r = z__2.r + z__3.r, z__1.i = z__2.i + z__3.i; a[i__3].r = z__1.r, a[i__3].i = z__1.i; /* L170: */ } } /* L180: */ } } else if (lsame_(direct, "B")) { for (j = *n; j >= 2; --j) { ctemp = c__[j - 1]; stemp = s[j - 1]; if ((ctemp != 1.) || (stemp != 0.)) { i__1 = *m; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = i__ + j * a_dim1; temp.r = a[i__2].r, temp.i = a[i__2].i; i__2 = i__ + j * a_dim1; z__2.r = ctemp * temp.r, z__2.i = ctemp * temp.i; i__3 = i__ + a_dim1; z__3.r = stemp * a[i__3].r, z__3.i = stemp * a[ i__3].i; z__1.r = z__2.r - z__3.r, z__1.i = z__2.i - z__3.i; a[i__2].r = z__1.r, a[i__2].i = z__1.i; i__2 = i__ + a_dim1; z__2.r = stemp * temp.r, z__2.i = stemp * temp.i; i__3 = i__ + a_dim1; z__3.r = ctemp * a[i__3].r, z__3.i = ctemp * a[ i__3].i; z__1.r = z__2.r + z__3.r, z__1.i = z__2.i + z__3.i; a[i__2].r = z__1.r, a[i__2].i = z__1.i; /* L190: */ } } /* L200: */ } } } else if (lsame_(pivot, "B")) { if (lsame_(direct, "F")) { i__1 = *n - 1; for (j = 1; j <= i__1; ++j) { ctemp = c__[j]; stemp = s[j]; if ((ctemp != 1.) || (stemp != 0.)) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * a_dim1; temp.r = a[i__3].r, temp.i = a[i__3].i; i__3 = i__ + j * a_dim1; i__4 = i__ + *n * a_dim1; z__2.r = stemp * a[i__4].r, z__2.i = stemp * a[ i__4].i; z__3.r = ctemp * temp.r, z__3.i = ctemp * temp.i; z__1.r = z__2.r + z__3.r, z__1.i = z__2.i + z__3.i; a[i__3].r = z__1.r, a[i__3].i = z__1.i; i__3 = i__ + *n * a_dim1; i__4 = i__ + *n * a_dim1; z__2.r = ctemp * a[i__4].r, z__2.i = ctemp * a[ i__4].i; z__3.r = stemp * temp.r, z__3.i = stemp * temp.i; z__1.r = z__2.r - z__3.r, z__1.i = z__2.i - z__3.i; a[i__3].r = z__1.r, a[i__3].i = z__1.i; /* L210: */ } } /* L220: */ } } else if (lsame_(direct, "B")) { for (j = *n - 1; j >= 1; --j) { ctemp = c__[j]; stemp = s[j]; if ((ctemp != 1.) || (stemp != 0.)) { i__1 = *m; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = i__ + j * a_dim1; temp.r = a[i__2].r, temp.i = a[i__2].i; i__2 = i__ + j * a_dim1; i__3 = i__ + *n * a_dim1; z__2.r = stemp * a[i__3].r, z__2.i = stemp * a[ i__3].i; z__3.r = ctemp * temp.r, z__3.i = ctemp * temp.i; z__1.r = z__2.r + z__3.r, z__1.i = z__2.i + z__3.i; a[i__2].r = z__1.r, a[i__2].i = z__1.i; i__2 = i__ + *n * a_dim1; i__3 = i__ + *n * a_dim1; z__2.r = ctemp * a[i__3].r, z__2.i = ctemp * a[ i__3].i; z__3.r = stemp * temp.r, z__3.i = stemp * temp.i; z__1.r = z__2.r - z__3.r, z__1.i = z__2.i - z__3.i; a[i__2].r = z__1.r, a[i__2].i = z__1.i; /* L230: */ } } /* L240: */ } } } } return 0; /* End of ZLASR */ } /* zlasr_ */ /* Subroutine */ int zlassq_(integer *n, doublecomplex *x, integer *incx, doublereal *scale, doublereal *sumsq) { /* System generated locals */ integer i__1, i__2, i__3; doublereal d__1; /* Builtin functions */ double d_imag(doublecomplex *); /* Local variables */ static integer ix; static doublereal temp1; /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= ZLASSQ returns the values scl and ssq such that ( scl**2 )*ssq = x( 1 )**2 +...+ x( n )**2 + ( scale**2 )*sumsq, where x( i ) = abs( X( 1 + ( i - 1 )*INCX ) ). The value of sumsq is assumed to be at least unity and the value of ssq will then satisfy 1.0 .le. ssq .le. ( sumsq + 2*n ). scale is assumed to be non-negative and scl returns the value scl = max( scale, abs( real( x( i ) ) ), abs( aimag( x( i ) ) ) ), i scale and sumsq must be supplied in SCALE and SUMSQ respectively. SCALE and SUMSQ are overwritten by scl and ssq respectively. The routine makes only one pass through the vector X. Arguments ========= N (input) INTEGER The number of elements to be used from the vector X. X (input) COMPLEX*16 array, dimension (N) The vector x as described above. x( i ) = X( 1 + ( i - 1 )*INCX ), 1 <= i <= n. INCX (input) INTEGER The increment between successive values of the vector X. INCX > 0. SCALE (input/output) DOUBLE PRECISION On entry, the value scale in the equation above. On exit, SCALE is overwritten with the value scl . SUMSQ (input/output) DOUBLE PRECISION On entry, the value sumsq in the equation above. On exit, SUMSQ is overwritten with the value ssq . ===================================================================== */ /* Parameter adjustments */ --x; /* Function Body */ if (*n > 0) { i__1 = (*n - 1) * *incx + 1; i__2 = *incx; for (ix = 1; i__2 < 0 ? ix >= i__1 : ix <= i__1; ix += i__2) { i__3 = ix; if (x[i__3].r != 0.) { i__3 = ix; temp1 = (d__1 = x[i__3].r, abs(d__1)); if (*scale < temp1) { /* Computing 2nd power */ d__1 = *scale / temp1; *sumsq = *sumsq * (d__1 * d__1) + 1; *scale = temp1; } else { /* Computing 2nd power */ d__1 = temp1 / *scale; *sumsq += d__1 * d__1; } } if (d_imag(&x[ix]) != 0.) { temp1 = (d__1 = d_imag(&x[ix]), abs(d__1)); if (*scale < temp1) { /* Computing 2nd power */ d__1 = *scale / temp1; *sumsq = *sumsq * (d__1 * d__1) + 1; *scale = temp1; } else { /* Computing 2nd power */ d__1 = temp1 / *scale; *sumsq += d__1 * d__1; } } /* L10: */ } } return 0; /* End of ZLASSQ */ } /* zlassq_ */ /* Subroutine */ int zlaswp_(integer *n, doublecomplex *a, integer *lda, integer *k1, integer *k2, integer *ipiv, integer *incx) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3, i__4, i__5, i__6; /* Local variables */ static integer i__, j, k, i1, i2, n32, ip, ix, ix0, inc; static doublecomplex temp; /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= ZLASWP performs a series of row interchanges on the matrix A. One row interchange is initiated for each of rows K1 through K2 of A. Arguments ========= N (input) INTEGER The number of columns of the matrix A. A (input/output) COMPLEX*16 array, dimension (LDA,N) On entry, the matrix of column dimension N to which the row interchanges will be applied. On exit, the permuted matrix. LDA (input) INTEGER The leading dimension of the array A. K1 (input) INTEGER The first element of IPIV for which a row interchange will be done. K2 (input) INTEGER The last element of IPIV for which a row interchange will be done. IPIV (input) INTEGER array, dimension (M*abs(INCX)) The vector of pivot indices. Only the elements in positions K1 through K2 of IPIV are accessed. IPIV(K) = L implies rows K and L are to be interchanged. INCX (input) INTEGER The increment between successive values of IPIV. If IPIV is negative, the pivots are applied in reverse order. Further Details =============== Modified by R. C. Whaley, Computer Science Dept., Univ. of Tenn., Knoxville, USA ===================================================================== Interchange row I with row IPIV(I) for each of rows K1 through K2. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --ipiv; /* Function Body */ if (*incx > 0) { ix0 = *k1; i1 = *k1; i2 = *k2; inc = 1; } else if (*incx < 0) { ix0 = (1 - *k2) * *incx + 1; i1 = *k2; i2 = *k1; inc = -1; } else { return 0; } n32 = (*n / 32) << (5); if (n32 != 0) { i__1 = n32; for (j = 1; j <= i__1; j += 32) { ix = ix0; i__2 = i2; i__3 = inc; for (i__ = i1; i__3 < 0 ? i__ >= i__2 : i__ <= i__2; i__ += i__3) { ip = ipiv[ix]; if (ip != i__) { i__4 = j + 31; for (k = j; k <= i__4; ++k) { i__5 = i__ + k * a_dim1; temp.r = a[i__5].r, temp.i = a[i__5].i; i__5 = i__ + k * a_dim1; i__6 = ip + k * a_dim1; a[i__5].r = a[i__6].r, a[i__5].i = a[i__6].i; i__5 = ip + k * a_dim1; a[i__5].r = temp.r, a[i__5].i = temp.i; /* L10: */ } } ix += *incx; /* L20: */ } /* L30: */ } } if (n32 != *n) { ++n32; ix = ix0; i__1 = i2; i__3 = inc; for (i__ = i1; i__3 < 0 ? i__ >= i__1 : i__ <= i__1; i__ += i__3) { ip = ipiv[ix]; if (ip != i__) { i__2 = *n; for (k = n32; k <= i__2; ++k) { i__4 = i__ + k * a_dim1; temp.r = a[i__4].r, temp.i = a[i__4].i; i__4 = i__ + k * a_dim1; i__5 = ip + k * a_dim1; a[i__4].r = a[i__5].r, a[i__4].i = a[i__5].i; i__4 = ip + k * a_dim1; a[i__4].r = temp.r, a[i__4].i = temp.i; /* L40: */ } } ix += *incx; /* L50: */ } } return 0; /* End of ZLASWP */ } /* zlaswp_ */ /* Subroutine */ int zlatrd_(char *uplo, integer *n, integer *nb, doublecomplex *a, integer *lda, doublereal *e, doublecomplex *tau, doublecomplex *w, integer *ldw) { /* System generated locals */ integer a_dim1, a_offset, w_dim1, w_offset, i__1, i__2, i__3; doublereal d__1; doublecomplex z__1, z__2, z__3, z__4; /* Local variables */ static integer i__, iw; static doublecomplex alpha; extern logical lsame_(char *, char *); extern /* Subroutine */ int zscal_(integer *, doublecomplex *, doublecomplex *, integer *); extern /* Double Complex */ VOID zdotc_(doublecomplex *, integer *, doublecomplex *, integer *, doublecomplex *, integer *); extern /* Subroutine */ int zgemv_(char *, integer *, integer *, doublecomplex *, doublecomplex *, integer *, doublecomplex *, integer *, doublecomplex *, doublecomplex *, integer *), zhemv_(char *, integer *, doublecomplex *, doublecomplex *, integer *, doublecomplex *, integer *, doublecomplex *, doublecomplex *, integer *), zaxpy_(integer *, doublecomplex *, doublecomplex *, integer *, doublecomplex *, integer *), zlarfg_(integer *, doublecomplex *, doublecomplex *, integer *, doublecomplex *), zlacgv_(integer *, doublecomplex *, integer *); /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University September 30, 1994 Purpose ======= ZLATRD reduces NB rows and columns of a complex Hermitian matrix A to Hermitian tridiagonal form by a unitary similarity transformation Q' * A * Q, and returns the matrices V and W which are needed to apply the transformation to the unreduced part of A. If UPLO = 'U', ZLATRD reduces the last NB rows and columns of a matrix, of which the upper triangle is supplied; if UPLO = 'L', ZLATRD reduces the first NB rows and columns of a matrix, of which the lower triangle is supplied. This is an auxiliary routine called by ZHETRD. Arguments ========= UPLO (input) CHARACTER Specifies whether the upper or lower triangular part of the Hermitian matrix A is stored: = 'U': Upper triangular = 'L': Lower triangular N (input) INTEGER The order of the matrix A. NB (input) INTEGER The number of rows and columns to be reduced. 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, and the strictly lower triangular part of A is not referenced. If UPLO = 'L', the leading n-by-n lower triangular part of A contains the lower triangular part of the matrix A, and the strictly upper triangular part of A is not referenced. On exit: if UPLO = 'U', the last NB columns have been reduced to tridiagonal form, with the diagonal elements overwriting the diagonal elements of A; the elements above the diagonal with the array TAU, represent the unitary matrix Q as a product of elementary reflectors; if UPLO = 'L', the first NB columns have been reduced to tridiagonal form, with the diagonal elements overwriting the diagonal elements of A; the elements below the diagonal with the array TAU, represent the unitary matrix Q as a product of elementary reflectors. See Further Details. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,N). E (output) DOUBLE PRECISION array, dimension (N-1) If UPLO = 'U', E(n-nb:n-1) contains the superdiagonal elements of the last NB columns of the reduced matrix; if UPLO = 'L', E(1:nb) contains the subdiagonal elements of the first NB columns of the reduced matrix. TAU (output) COMPLEX*16 array, dimension (N-1) The scalar factors of the elementary reflectors, stored in TAU(n-nb:n-1) if UPLO = 'U', and in TAU(1:nb) if UPLO = 'L'. See Further Details. W (output) COMPLEX*16 array, dimension (LDW,NB) The n-by-nb matrix W required to update the unreduced part of A. LDW (input) INTEGER The leading dimension of the array W. LDW >= max(1,N). Further Details =============== If UPLO = 'U', the matrix Q is represented as a product of elementary reflectors Q = H(n) H(n-1) . . . H(n-nb+1). Each H(i) has the form H(i) = I - tau * v * v' where tau is a complex scalar, and v is a complex vector with v(i:n) = 0 and v(i-1) = 1; v(1:i-1) is stored on exit in A(1:i-1,i), and tau in TAU(i-1). If UPLO = 'L', the matrix Q is represented as a product of elementary reflectors Q = H(1) H(2) . . . H(nb). Each H(i) has the form H(i) = I - tau * v * v' where tau is a complex scalar, and v is a complex vector with v(1:i) = 0 and v(i+1) = 1; v(i+1:n) is stored on exit in A(i+1:n,i), and tau in TAU(i). The elements of the vectors v together form the n-by-nb matrix V which is needed, with W, to apply the transformation to the unreduced part of the matrix, using a Hermitian rank-2k update of the form: A := A - V*W' - W*V'. The contents of A on exit are illustrated by the following examples with n = 5 and nb = 2: if UPLO = 'U': if UPLO = 'L': ( a a a v4 v5 ) ( d ) ( a a v4 v5 ) ( 1 d ) ( a 1 v5 ) ( v1 1 a ) ( d 1 ) ( v1 v2 a a ) ( d ) ( v1 v2 a a a ) where d denotes a diagonal element of the reduced matrix, a denotes an element of the original matrix that is unchanged, and vi denotes an element of the vector defining H(i). ===================================================================== Quick return if possible */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --e; --tau; w_dim1 = *ldw; w_offset = 1 + w_dim1; w -= w_offset; /* Function Body */ if (*n <= 0) { return 0; } if (lsame_(uplo, "U")) { /* Reduce last NB columns of upper triangle */ i__1 = *n - *nb + 1; for (i__ = *n; i__ >= i__1; --i__) { iw = i__ - *n + *nb; if (i__ < *n) { /* Update A(1:i,i) */ i__2 = i__ + i__ * a_dim1; i__3 = i__ + i__ * a_dim1; d__1 = a[i__3].r; a[i__2].r = d__1, a[i__2].i = 0.; i__2 = *n - i__; zlacgv_(&i__2, &w[i__ + (iw + 1) * w_dim1], ldw); i__2 = *n - i__; z__1.r = -1., z__1.i = -0.; zgemv_("No transpose", &i__, &i__2, &z__1, &a[(i__ + 1) * a_dim1 + 1], lda, &w[i__ + (iw + 1) * w_dim1], ldw, & c_b60, &a[i__ * a_dim1 + 1], &c__1); i__2 = *n - i__; zlacgv_(&i__2, &w[i__ + (iw + 1) * w_dim1], ldw); i__2 = *n - i__; zlacgv_(&i__2, &a[i__ + (i__ + 1) * a_dim1], lda); i__2 = *n - i__; z__1.r = -1., z__1.i = -0.; zgemv_("No transpose", &i__, &i__2, &z__1, &w[(iw + 1) * w_dim1 + 1], ldw, &a[i__ + (i__ + 1) * a_dim1], lda, & c_b60, &a[i__ * a_dim1 + 1], &c__1); i__2 = *n - i__; zlacgv_(&i__2, &a[i__ + (i__ + 1) * a_dim1], lda); i__2 = i__ + i__ * a_dim1; i__3 = i__ + i__ * a_dim1; d__1 = a[i__3].r; a[i__2].r = d__1, a[i__2].i = 0.; } if (i__ > 1) { /* Generate elementary reflector H(i) to annihilate A(1:i-2,i) */ i__2 = i__ - 1 + i__ * a_dim1; alpha.r = a[i__2].r, alpha.i = a[i__2].i; i__2 = i__ - 1; zlarfg_(&i__2, &alpha, &a[i__ * a_dim1 + 1], &c__1, &tau[i__ - 1]); i__2 = i__ - 1; e[i__2] = alpha.r; i__2 = i__ - 1 + i__ * a_dim1; a[i__2].r = 1., a[i__2].i = 0.; /* Compute W(1:i-1,i) */ i__2 = i__ - 1; zhemv_("Upper", &i__2, &c_b60, &a[a_offset], lda, &a[i__ * a_dim1 + 1], &c__1, &c_b59, &w[iw * w_dim1 + 1], & c__1); if (i__ < *n) { i__2 = i__ - 1; i__3 = *n - i__; zgemv_("Conjugate transpose", &i__2, &i__3, &c_b60, &w[( iw + 1) * w_dim1 + 1], ldw, &a[i__ * a_dim1 + 1], &c__1, &c_b59, &w[i__ + 1 + iw * w_dim1], &c__1); i__2 = i__ - 1; i__3 = *n - i__; z__1.r = -1., z__1.i = -0.; zgemv_("No transpose", &i__2, &i__3, &z__1, &a[(i__ + 1) * a_dim1 + 1], lda, &w[i__ + 1 + iw * w_dim1], & c__1, &c_b60, &w[iw * w_dim1 + 1], &c__1); i__2 = i__ - 1; i__3 = *n - i__; zgemv_("Conjugate transpose", &i__2, &i__3, &c_b60, &a[( i__ + 1) * a_dim1 + 1], lda, &a[i__ * a_dim1 + 1], &c__1, &c_b59, &w[i__ + 1 + iw * w_dim1], &c__1); i__2 = i__ - 1; i__3 = *n - i__; z__1.r = -1., z__1.i = -0.; zgemv_("No transpose", &i__2, &i__3, &z__1, &w[(iw + 1) * w_dim1 + 1], ldw, &w[i__ + 1 + iw * w_dim1], & c__1, &c_b60, &w[iw * w_dim1 + 1], &c__1); } i__2 = i__ - 1; zscal_(&i__2, &tau[i__ - 1], &w[iw * w_dim1 + 1], &c__1); z__3.r = -.5, z__3.i = -0.; i__2 = i__ - 1; z__2.r = z__3.r * tau[i__2].r - z__3.i * tau[i__2].i, z__2.i = z__3.r * tau[i__2].i + z__3.i * tau[i__2].r; i__3 = i__ - 1; zdotc_(&z__4, &i__3, &w[iw * w_dim1 + 1], &c__1, &a[i__ * a_dim1 + 1], &c__1); z__1.r = z__2.r * z__4.r - z__2.i * z__4.i, z__1.i = z__2.r * z__4.i + z__2.i * z__4.r; alpha.r = z__1.r, alpha.i = z__1.i; i__2 = i__ - 1; zaxpy_(&i__2, &alpha, &a[i__ * a_dim1 + 1], &c__1, &w[iw * w_dim1 + 1], &c__1); } /* L10: */ } } else { /* Reduce first NB columns of lower triangle */ i__1 = *nb; for (i__ = 1; i__ <= i__1; ++i__) { /* Update A(i:n,i) */ i__2 = i__ + i__ * a_dim1; i__3 = i__ + i__ * a_dim1; d__1 = a[i__3].r; a[i__2].r = d__1, a[i__2].i = 0.; i__2 = i__ - 1; zlacgv_(&i__2, &w[i__ + w_dim1], ldw); i__2 = *n - i__ + 1; i__3 = i__ - 1; z__1.r = -1., z__1.i = -0.; zgemv_("No transpose", &i__2, &i__3, &z__1, &a[i__ + a_dim1], lda, &w[i__ + w_dim1], ldw, &c_b60, &a[i__ + i__ * a_dim1], & c__1); i__2 = i__ - 1; zlacgv_(&i__2, &w[i__ + w_dim1], ldw); i__2 = i__ - 1; zlacgv_(&i__2, &a[i__ + a_dim1], lda); i__2 = *n - i__ + 1; i__3 = i__ - 1; z__1.r = -1., z__1.i = -0.; zgemv_("No transpose", &i__2, &i__3, &z__1, &w[i__ + w_dim1], ldw, &a[i__ + a_dim1], lda, &c_b60, &a[i__ + i__ * a_dim1], & c__1); i__2 = i__ - 1; zlacgv_(&i__2, &a[i__ + a_dim1], lda); i__2 = i__ + i__ * a_dim1; i__3 = i__ + i__ * a_dim1; d__1 = a[i__3].r; a[i__2].r = d__1, a[i__2].i = 0.; if (i__ < *n) { /* Generate elementary reflector H(i) to annihilate A(i+2:n,i) */ i__2 = i__ + 1 + i__ * a_dim1; alpha.r = a[i__2].r, alpha.i = a[i__2].i; i__2 = *n - i__; /* Computing MIN */ i__3 = i__ + 2; zlarfg_(&i__2, &alpha, &a[min(i__3,*n) + i__ * a_dim1], &c__1, &tau[i__]); i__2 = i__; e[i__2] = alpha.r; i__2 = i__ + 1 + i__ * a_dim1; a[i__2].r = 1., a[i__2].i = 0.; /* Compute W(i+1:n,i) */ i__2 = *n - i__; zhemv_("Lower", &i__2, &c_b60, &a[i__ + 1 + (i__ + 1) * a_dim1], lda, &a[i__ + 1 + i__ * a_dim1], &c__1, & c_b59, &w[i__ + 1 + i__ * w_dim1], &c__1); i__2 = *n - i__; i__3 = i__ - 1; zgemv_("Conjugate transpose", &i__2, &i__3, &c_b60, &w[i__ + 1 + w_dim1], ldw, &a[i__ + 1 + i__ * a_dim1], &c__1, & c_b59, &w[i__ * w_dim1 + 1], &c__1); i__2 = *n - i__; i__3 = i__ - 1; z__1.r = -1., z__1.i = -0.; zgemv_("No transpose", &i__2, &i__3, &z__1, &a[i__ + 1 + a_dim1], lda, &w[i__ * w_dim1 + 1], &c__1, &c_b60, &w[ i__ + 1 + i__ * w_dim1], &c__1); i__2 = *n - i__; i__3 = i__ - 1; zgemv_("Conjugate transpose", &i__2, &i__3, &c_b60, &a[i__ + 1 + a_dim1], lda, &a[i__ + 1 + i__ * a_dim1], &c__1, & c_b59, &w[i__ * w_dim1 + 1], &c__1); i__2 = *n - i__; i__3 = i__ - 1; z__1.r = -1., z__1.i = -0.; zgemv_("No transpose", &i__2, &i__3, &z__1, &w[i__ + 1 + w_dim1], ldw, &w[i__ * w_dim1 + 1], &c__1, &c_b60, &w[ i__ + 1 + i__ * w_dim1], &c__1); i__2 = *n - i__; zscal_(&i__2, &tau[i__], &w[i__ + 1 + i__ * w_dim1], &c__1); z__3.r = -.5, z__3.i = -0.; i__2 = i__; z__2.r = z__3.r * tau[i__2].r - z__3.i * tau[i__2].i, z__2.i = z__3.r * tau[i__2].i + z__3.i * tau[i__2].r; i__3 = *n - i__; zdotc_(&z__4, &i__3, &w[i__ + 1 + i__ * w_dim1], &c__1, &a[ i__ + 1 + i__ * a_dim1], &c__1); z__1.r = z__2.r * z__4.r - z__2.i * z__4.i, z__1.i = z__2.r * z__4.i + z__2.i * z__4.r; alpha.r = z__1.r, alpha.i = z__1.i; i__2 = *n - i__; zaxpy_(&i__2, &alpha, &a[i__ + 1 + i__ * a_dim1], &c__1, &w[ i__ + 1 + i__ * w_dim1], &c__1); } /* L20: */ } } return 0; /* End of ZLATRD */ } /* zlatrd_ */ /* Subroutine */ int zlatrs_(char *uplo, char *trans, char *diag, char * normin, integer *n, doublecomplex *a, integer *lda, doublecomplex *x, doublereal *scale, doublereal *cnorm, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3, i__4, i__5; doublereal d__1, d__2, d__3, d__4; doublecomplex z__1, z__2, z__3, z__4; /* Builtin functions */ double d_imag(doublecomplex *); void d_cnjg(doublecomplex *, doublecomplex *); /* Local variables */ static integer i__, j; static doublereal xj, rec, tjj; static integer jinc; static doublereal xbnd; static integer imax; static doublereal tmax; static doublecomplex tjjs; static doublereal xmax, grow; extern /* Subroutine */ int dscal_(integer *, doublereal *, doublereal *, integer *); extern logical lsame_(char *, char *); static doublereal tscal; static doublecomplex uscal; static integer jlast; static doublecomplex csumj; extern /* Double Complex */ VOID zdotc_(doublecomplex *, integer *, doublecomplex *, integer *, doublecomplex *, integer *); static logical upper; extern /* Double Complex */ VOID zdotu_(doublecomplex *, integer *, doublecomplex *, integer *, doublecomplex *, integer *); extern /* Subroutine */ int zaxpy_(integer *, doublecomplex *, doublecomplex *, integer *, doublecomplex *, integer *), ztrsv_( char *, char *, char *, integer *, doublecomplex *, integer *, doublecomplex *, integer *), dlabad_( doublereal *, doublereal *); extern integer idamax_(integer *, doublereal *, integer *); extern /* Subroutine */ int xerbla_(char *, integer *), zdscal_( integer *, doublereal *, doublecomplex *, integer *); static doublereal bignum; extern integer izamax_(integer *, doublecomplex *, integer *); extern /* Double Complex */ VOID zladiv_(doublecomplex *, doublecomplex *, doublecomplex *); static logical notran; static integer jfirst; extern doublereal dzasum_(integer *, doublecomplex *, integer *); static doublereal smlnum; static logical nounit; /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1992 Purpose ======= ZLATRS solves one of the triangular systems A * x = s*b, A**T * x = s*b, or A**H * x = s*b, with scaling to prevent overflow. Here A is an upper or lower triangular matrix, A**T denotes the transpose of A, A**H denotes the conjugate transpose of A, x and b are n-element vectors, and s is a scaling factor, usually less than or equal to 1, chosen so that the components of x will be less than the overflow threshold. If the unscaled problem will not cause overflow, the Level 2 BLAS routine ZTRSV is called. If the matrix A is singular (A(j,j) = 0 for some j), then s is set to 0 and a non-trivial solution to A*x = 0 is returned. Arguments ========= UPLO (input) CHARACTER*1 Specifies whether the matrix A is upper or lower triangular. = 'U': Upper triangular = 'L': Lower triangular TRANS (input) CHARACTER*1 Specifies the operation applied to A. = 'N': Solve A * x = s*b (No transpose) = 'T': Solve A**T * x = s*b (Transpose) = 'C': Solve A**H * x = s*b (Conjugate transpose) DIAG (input) CHARACTER*1 Specifies whether or not the matrix A is unit triangular. = 'N': Non-unit triangular = 'U': Unit triangular NORMIN (input) CHARACTER*1 Specifies whether CNORM has been set or not. = 'Y': CNORM contains the column norms on entry = 'N': CNORM is not set on entry. On exit, the norms will be computed and stored in CNORM. N (input) INTEGER The order of the matrix A. N >= 0. A (input) COMPLEX*16 array, dimension (LDA,N) The triangular matrix A. If UPLO = 'U', the leading n by n upper triangular part of the array A contains the upper triangular matrix, and the strictly lower triangular part of A is not referenced. If UPLO = 'L', the leading n by n lower triangular part of the array A contains the lower triangular matrix, and the strictly upper triangular part of A is not referenced. If DIAG = 'U', the diagonal elements of A are also not referenced and are assumed to be 1. LDA (input) INTEGER The leading dimension of the array A. LDA >= max (1,N). X (input/output) COMPLEX*16 array, dimension (N) On entry, the right hand side b of the triangular system. On exit, X is overwritten by the solution vector x. SCALE (output) DOUBLE PRECISION The scaling factor s for the triangular system A * x = s*b, A**T * x = s*b, or A**H * x = s*b. If SCALE = 0, the matrix A is singular or badly scaled, and the vector x is an exact or approximate solution to A*x = 0. CNORM (input or output) DOUBLE PRECISION array, dimension (N) If NORMIN = 'Y', CNORM is an input argument and CNORM(j) contains the norm of the off-diagonal part of the j-th column of A. If TRANS = 'N', CNORM(j) must be greater than or equal to the infinity-norm, and if TRANS = 'T' or 'C', CNORM(j) must be greater than or equal to the 1-norm. If NORMIN = 'N', CNORM is an output argument and CNORM(j) returns the 1-norm of the offdiagonal part of the j-th column of A. INFO (output) INTEGER = 0: successful exit < 0: if INFO = -k, the k-th argument had an illegal value Further Details ======= ======= A rough bound on x is computed; if that is less than overflow, ZTRSV is called, otherwise, specific code is used which checks for possible overflow or divide-by-zero at every operation. A columnwise scheme is used for solving A*x = b. The basic algorithm if A is lower triangular is x[1:n] := b[1:n] for j = 1, ..., n x(j) := x(j) / A(j,j) x[j+1:n] := x[j+1:n] - x(j) * A[j+1:n,j] end Define bounds on the components of x after j iterations of the loop: M(j) = bound on x[1:j] G(j) = bound on x[j+1:n] Initially, let M(0) = 0 and G(0) = max{x(i), i=1,...,n}. Then for iteration j+1 we have M(j+1) <= G(j) / | A(j+1,j+1) | G(j+1) <= G(j) + M(j+1) * | A[j+2:n,j+1] | <= G(j) ( 1 + CNORM(j+1) / | A(j+1,j+1) | ) where CNORM(j+1) is greater than or equal to the infinity-norm of column j+1 of A, not counting the diagonal. Hence G(j) <= G(0) product ( 1 + CNORM(i) / | A(i,i) | ) 1<=i<=j and |x(j)| <= ( G(0) / |A(j,j)| ) product ( 1 + CNORM(i) / |A(i,i)| ) 1<=i< j Since |x(j)| <= M(j), we use the Level 2 BLAS routine ZTRSV if the reciprocal of the largest M(j), j=1,..,n, is larger than max(underflow, 1/overflow). The bound on x(j) is also used to determine when a step in the columnwise method can be performed without fear of overflow. If the computed bound is greater than a large constant, x is scaled to prevent overflow, but if the bound overflows, x is set to 0, x(j) to 1, and scale to 0, and a non-trivial solution to A*x = 0 is found. Similarly, a row-wise scheme is used to solve A**T *x = b or A**H *x = b. The basic algorithm for A upper triangular is for j = 1, ..., n x(j) := ( b(j) - A[1:j-1,j]' * x[1:j-1] ) / A(j,j) end We simultaneously compute two bounds G(j) = bound on ( b(i) - A[1:i-1,i]' * x[1:i-1] ), 1<=i<=j M(j) = bound on x(i), 1<=i<=j The initial values are G(0) = 0, M(0) = max{b(i), i=1,..,n}, and we add the constraint G(j) >= G(j-1) and M(j) >= M(j-1) for j >= 1. Then the bound on x(j) is M(j) <= M(j-1) * ( 1 + CNORM(j) ) / | A(j,j) | <= M(0) * product ( ( 1 + CNORM(i) ) / |A(i,i)| ) 1<=i<=j and we can safely call ZTRSV if 1/M(n) and 1/G(n) are both greater than max(underflow, 1/overflow). ===================================================================== */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --x; --cnorm; /* Function Body */ *info = 0; upper = lsame_(uplo, "U"); notran = lsame_(trans, "N"); nounit = lsame_(diag, "N"); /* Test the input parameters. */ if (! upper && ! lsame_(uplo, "L")) { *info = -1; } else if (! notran && ! lsame_(trans, "T") && ! lsame_(trans, "C")) { *info = -2; } else if (! nounit && ! lsame_(diag, "U")) { *info = -3; } else if (! lsame_(normin, "Y") && ! lsame_(normin, "N")) { *info = -4; } else if (*n < 0) { *info = -5; } else if (*lda < max(1,*n)) { *info = -7; } if (*info != 0) { i__1 = -(*info); xerbla_("ZLATRS", &i__1); return 0; } /* Quick return if possible */ if (*n == 0) { return 0; } /* Determine machine dependent parameters to control overflow. */ smlnum = SAFEMINIMUM; bignum = 1. / smlnum; dlabad_(&smlnum, &bignum); smlnum /= PRECISION; bignum = 1. / smlnum; *scale = 1.; if (lsame_(normin, "N")) { /* Compute the 1-norm of each column, not including the diagonal. */ if (upper) { /* A is upper triangular. */ i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = j - 1; cnorm[j] = dzasum_(&i__2, &a[j * a_dim1 + 1], &c__1); /* L10: */ } } else { /* A is lower triangular. */ i__1 = *n - 1; for (j = 1; j <= i__1; ++j) { i__2 = *n - j; cnorm[j] = dzasum_(&i__2, &a[j + 1 + j * a_dim1], &c__1); /* L20: */ } cnorm[*n] = 0.; } } /* Scale the column norms by TSCAL if the maximum element in CNORM is greater than BIGNUM/2. */ imax = idamax_(n, &cnorm[1], &c__1); tmax = cnorm[imax]; if (tmax <= bignum * .5) { tscal = 1.; } else { tscal = .5 / (smlnum * tmax); dscal_(n, &tscal, &cnorm[1], &c__1); } /* Compute a bound on the computed solution vector to see if the Level 2 BLAS routine ZTRSV can be used. */ xmax = 0.; i__1 = *n; for (j = 1; j <= i__1; ++j) { /* Computing MAX */ i__2 = j; d__3 = xmax, d__4 = (d__1 = x[i__2].r / 2., abs(d__1)) + (d__2 = d_imag(&x[j]) / 2., abs(d__2)); xmax = max(d__3,d__4); /* L30: */ } xbnd = xmax; if (notran) { /* Compute the growth in A * x = b. */ if (upper) { jfirst = *n; jlast = 1; jinc = -1; } else { jfirst = 1; jlast = *n; jinc = 1; } if (tscal != 1.) { grow = 0.; goto L60; } if (nounit) { /* A is non-unit triangular. Compute GROW = 1/G(j) and XBND = 1/M(j). Initially, G(0) = max{x(i), i=1,...,n}. */ grow = .5 / max(xbnd,smlnum); xbnd = grow; i__1 = jlast; i__2 = jinc; for (j = jfirst; i__2 < 0 ? j >= i__1 : j <= i__1; j += i__2) { /* Exit the loop if the growth factor is too small. */ if (grow <= smlnum) { goto L60; } i__3 = j + j * a_dim1; tjjs.r = a[i__3].r, tjjs.i = a[i__3].i; tjj = (d__1 = tjjs.r, abs(d__1)) + (d__2 = d_imag(&tjjs), abs( d__2)); if (tjj >= smlnum) { /* M(j) = G(j-1) / abs(A(j,j)) Computing MIN */ d__1 = xbnd, d__2 = min(1.,tjj) * grow; xbnd = min(d__1,d__2); } else { /* M(j) could overflow, set XBND to 0. */ xbnd = 0.; } if (tjj + cnorm[j] >= smlnum) { /* G(j) = G(j-1)*( 1 + CNORM(j) / abs(A(j,j)) ) */ grow *= tjj / (tjj + cnorm[j]); } else { /* G(j) could overflow, set GROW to 0. */ grow = 0.; } /* L40: */ } grow = xbnd; } else { /* A is unit triangular. Compute GROW = 1/G(j), where G(0) = max{x(i), i=1,...,n}. Computing MIN */ d__1 = 1., d__2 = .5 / max(xbnd,smlnum); grow = min(d__1,d__2); i__2 = jlast; i__1 = jinc; for (j = jfirst; i__1 < 0 ? j >= i__2 : j <= i__2; j += i__1) { /* Exit the loop if the growth factor is too small. */ if (grow <= smlnum) { goto L60; } /* G(j) = G(j-1)*( 1 + CNORM(j) ) */ grow *= 1. / (cnorm[j] + 1.); /* L50: */ } } L60: ; } else { /* Compute the growth in A**T * x = b or A**H * x = b. */ if (upper) { jfirst = 1; jlast = *n; jinc = 1; } else { jfirst = *n; jlast = 1; jinc = -1; } if (tscal != 1.) { grow = 0.; goto L90; } if (nounit) { /* A is non-unit triangular. Compute GROW = 1/G(j) and XBND = 1/M(j). Initially, M(0) = max{x(i), i=1,...,n}. */ grow = .5 / max(xbnd,smlnum); xbnd = grow; i__1 = jlast; i__2 = jinc; for (j = jfirst; i__2 < 0 ? j >= i__1 : j <= i__1; j += i__2) { /* Exit the loop if the growth factor is too small. */ if (grow <= smlnum) { goto L90; } /* G(j) = max( G(j-1), M(j-1)*( 1 + CNORM(j) ) ) */ xj = cnorm[j] + 1.; /* Computing MIN */ d__1 = grow, d__2 = xbnd / xj; grow = min(d__1,d__2); i__3 = j + j * a_dim1; tjjs.r = a[i__3].r, tjjs.i = a[i__3].i; tjj = (d__1 = tjjs.r, abs(d__1)) + (d__2 = d_imag(&tjjs), abs( d__2)); if (tjj >= smlnum) { /* M(j) = M(j-1)*( 1 + CNORM(j) ) / abs(A(j,j)) */ if (xj > tjj) { xbnd *= tjj / xj; } } else { /* M(j) could overflow, set XBND to 0. */ xbnd = 0.; } /* L70: */ } grow = min(grow,xbnd); } else { /* A is unit triangular. Compute GROW = 1/G(j), where G(0) = max{x(i), i=1,...,n}. Computing MIN */ d__1 = 1., d__2 = .5 / max(xbnd,smlnum); grow = min(d__1,d__2); i__2 = jlast; i__1 = jinc; for (j = jfirst; i__1 < 0 ? j >= i__2 : j <= i__2; j += i__1) { /* Exit the loop if the growth factor is too small. */ if (grow <= smlnum) { goto L90; } /* G(j) = ( 1 + CNORM(j) )*G(j-1) */ xj = cnorm[j] + 1.; grow /= xj; /* L80: */ } } L90: ; } if (grow * tscal > smlnum) { /* Use the Level 2 BLAS solve if the reciprocal of the bound on elements of X is not too small. */ ztrsv_(uplo, trans, diag, n, &a[a_offset], lda, &x[1], &c__1); } else { /* Use a Level 1 BLAS solve, scaling intermediate results. */ if (xmax > bignum * .5) { /* Scale X so that its components are less than or equal to BIGNUM in absolute value. */ *scale = bignum * .5 / xmax; zdscal_(n, scale, &x[1], &c__1); xmax = bignum; } else { xmax *= 2.; } if (notran) { /* Solve A * x = b */ i__1 = jlast; i__2 = jinc; for (j = jfirst; i__2 < 0 ? j >= i__1 : j <= i__1; j += i__2) { /* Compute x(j) = b(j) / A(j,j), scaling x if necessary. */ i__3 = j; xj = (d__1 = x[i__3].r, abs(d__1)) + (d__2 = d_imag(&x[j]), abs(d__2)); if (nounit) { i__3 = j + j * a_dim1; z__1.r = tscal * a[i__3].r, z__1.i = tscal * a[i__3].i; tjjs.r = z__1.r, tjjs.i = z__1.i; } else { tjjs.r = tscal, tjjs.i = 0.; if (tscal == 1.) { goto L110; } } tjj = (d__1 = tjjs.r, abs(d__1)) + (d__2 = d_imag(&tjjs), abs( d__2)); if (tjj > smlnum) { /* abs(A(j,j)) > SMLNUM: */ if (tjj < 1.) { if (xj > tjj * bignum) { /* Scale x by 1/b(j). */ rec = 1. / xj; zdscal_(n, &rec, &x[1], &c__1); *scale *= rec; xmax *= rec; } } i__3 = j; zladiv_(&z__1, &x[j], &tjjs); x[i__3].r = z__1.r, x[i__3].i = z__1.i; i__3 = j; xj = (d__1 = x[i__3].r, abs(d__1)) + (d__2 = d_imag(&x[j]) , abs(d__2)); } else if (tjj > 0.) { /* 0 < abs(A(j,j)) <= SMLNUM: */ if (xj > tjj * bignum) { /* Scale x by (1/abs(x(j)))*abs(A(j,j))*BIGNUM to avoid overflow when dividing by A(j,j). */ rec = tjj * bignum / xj; if (cnorm[j] > 1.) { /* Scale by 1/CNORM(j) to avoid overflow when multiplying x(j) times column j. */ rec /= cnorm[j]; } zdscal_(n, &rec, &x[1], &c__1); *scale *= rec; xmax *= rec; } i__3 = j; zladiv_(&z__1, &x[j], &tjjs); x[i__3].r = z__1.r, x[i__3].i = z__1.i; i__3 = j; xj = (d__1 = x[i__3].r, abs(d__1)) + (d__2 = d_imag(&x[j]) , abs(d__2)); } else { /* A(j,j) = 0: Set x(1:n) = 0, x(j) = 1, and scale = 0, and compute a solution to A*x = 0. */ i__3 = *n; for (i__ = 1; i__ <= i__3; ++i__) { i__4 = i__; x[i__4].r = 0., x[i__4].i = 0.; /* L100: */ } i__3 = j; x[i__3].r = 1., x[i__3].i = 0.; xj = 1.; *scale = 0.; xmax = 0.; } L110: /* Scale x if necessary to avoid overflow when adding a multiple of column j of A. */ if (xj > 1.) { rec = 1. / xj; if (cnorm[j] > (bignum - xmax) * rec) { /* Scale x by 1/(2*abs(x(j))). */ rec *= .5; zdscal_(n, &rec, &x[1], &c__1); *scale *= rec; } } else if (xj * cnorm[j] > bignum - xmax) { /* Scale x by 1/2. */ zdscal_(n, &c_b2210, &x[1], &c__1); *scale *= .5; } if (upper) { if (j > 1) { /* Compute the update x(1:j-1) := x(1:j-1) - x(j) * A(1:j-1,j) */ i__3 = j - 1; i__4 = j; z__2.r = -x[i__4].r, z__2.i = -x[i__4].i; z__1.r = tscal * z__2.r, z__1.i = tscal * z__2.i; zaxpy_(&i__3, &z__1, &a[j * a_dim1 + 1], &c__1, &x[1], &c__1); i__3 = j - 1; i__ = izamax_(&i__3, &x[1], &c__1); i__3 = i__; xmax = (d__1 = x[i__3].r, abs(d__1)) + (d__2 = d_imag( &x[i__]), abs(d__2)); } } else { if (j < *n) { /* Compute the update x(j+1:n) := x(j+1:n) - x(j) * A(j+1:n,j) */ i__3 = *n - j; i__4 = j; z__2.r = -x[i__4].r, z__2.i = -x[i__4].i; z__1.r = tscal * z__2.r, z__1.i = tscal * z__2.i; zaxpy_(&i__3, &z__1, &a[j + 1 + j * a_dim1], &c__1, & x[j + 1], &c__1); i__3 = *n - j; i__ = j + izamax_(&i__3, &x[j + 1], &c__1); i__3 = i__; xmax = (d__1 = x[i__3].r, abs(d__1)) + (d__2 = d_imag( &x[i__]), abs(d__2)); } } /* L120: */ } } else if (lsame_(trans, "T")) { /* Solve A**T * x = b */ i__2 = jlast; i__1 = jinc; for (j = jfirst; i__1 < 0 ? j >= i__2 : j <= i__2; j += i__1) { /* Compute x(j) = b(j) - sum A(k,j)*x(k). k<>j */ i__3 = j; xj = (d__1 = x[i__3].r, abs(d__1)) + (d__2 = d_imag(&x[j]), abs(d__2)); uscal.r = tscal, uscal.i = 0.; rec = 1. / max(xmax,1.); if (cnorm[j] > (bignum - xj) * rec) { /* If x(j) could overflow, scale x by 1/(2*XMAX). */ rec *= .5; if (nounit) { i__3 = j + j * a_dim1; z__1.r = tscal * a[i__3].r, z__1.i = tscal * a[i__3] .i; tjjs.r = z__1.r, tjjs.i = z__1.i; } else { tjjs.r = tscal, tjjs.i = 0.; } tjj = (d__1 = tjjs.r, abs(d__1)) + (d__2 = d_imag(&tjjs), abs(d__2)); if (tjj > 1.) { /* Divide by A(j,j) when scaling x if A(j,j) > 1. Computing MIN */ d__1 = 1., d__2 = rec * tjj; rec = min(d__1,d__2); zladiv_(&z__1, &uscal, &tjjs); uscal.r = z__1.r, uscal.i = z__1.i; } if (rec < 1.) { zdscal_(n, &rec, &x[1], &c__1); *scale *= rec; xmax *= rec; } } csumj.r = 0., csumj.i = 0.; if (uscal.r == 1. && uscal.i == 0.) { /* If the scaling needed for A in the dot product is 1, call ZDOTU to perform the dot product. */ if (upper) { i__3 = j - 1; zdotu_(&z__1, &i__3, &a[j * a_dim1 + 1], &c__1, &x[1], &c__1); csumj.r = z__1.r, csumj.i = z__1.i; } else if (j < *n) { i__3 = *n - j; zdotu_(&z__1, &i__3, &a[j + 1 + j * a_dim1], &c__1, & x[j + 1], &c__1); csumj.r = z__1.r, csumj.i = z__1.i; } } else { /* Otherwise, use in-line code for the dot product. */ if (upper) { i__3 = j - 1; for (i__ = 1; i__ <= i__3; ++i__) { i__4 = i__ + j * a_dim1; z__3.r = a[i__4].r * uscal.r - a[i__4].i * uscal.i, z__3.i = a[i__4].r * uscal.i + a[ i__4].i * uscal.r; i__5 = i__; z__2.r = z__3.r * x[i__5].r - z__3.i * x[i__5].i, z__2.i = z__3.r * x[i__5].i + z__3.i * x[ i__5].r; z__1.r = csumj.r + z__2.r, z__1.i = csumj.i + z__2.i; csumj.r = z__1.r, csumj.i = z__1.i; /* L130: */ } } else if (j < *n) { i__3 = *n; for (i__ = j + 1; i__ <= i__3; ++i__) { i__4 = i__ + j * a_dim1; z__3.r = a[i__4].r * uscal.r - a[i__4].i * uscal.i, z__3.i = a[i__4].r * uscal.i + a[ i__4].i * uscal.r; i__5 = i__; z__2.r = z__3.r * x[i__5].r - z__3.i * x[i__5].i, z__2.i = z__3.r * x[i__5].i + z__3.i * x[ i__5].r; z__1.r = csumj.r + z__2.r, z__1.i = csumj.i + z__2.i; csumj.r = z__1.r, csumj.i = z__1.i; /* L140: */ } } } z__1.r = tscal, z__1.i = 0.; if (uscal.r == z__1.r && uscal.i == z__1.i) { /* Compute x(j) := ( x(j) - CSUMJ ) / A(j,j) if 1/A(j,j) was not used to scale the dotproduct. */ i__3 = j; i__4 = j; z__1.r = x[i__4].r - csumj.r, z__1.i = x[i__4].i - csumj.i; x[i__3].r = z__1.r, x[i__3].i = z__1.i; i__3 = j; xj = (d__1 = x[i__3].r, abs(d__1)) + (d__2 = d_imag(&x[j]) , abs(d__2)); if (nounit) { i__3 = j + j * a_dim1; z__1.r = tscal * a[i__3].r, z__1.i = tscal * a[i__3] .i; tjjs.r = z__1.r, tjjs.i = z__1.i; } else { tjjs.r = tscal, tjjs.i = 0.; if (tscal == 1.) { goto L160; } } /* Compute x(j) = x(j) / A(j,j), scaling if necessary. */ tjj = (d__1 = tjjs.r, abs(d__1)) + (d__2 = d_imag(&tjjs), abs(d__2)); if (tjj > smlnum) { /* abs(A(j,j)) > SMLNUM: */ if (tjj < 1.) { if (xj > tjj * bignum) { /* Scale X by 1/abs(x(j)). */ rec = 1. / xj; zdscal_(n, &rec, &x[1], &c__1); *scale *= rec; xmax *= rec; } } i__3 = j; zladiv_(&z__1, &x[j], &tjjs); x[i__3].r = z__1.r, x[i__3].i = z__1.i; } else if (tjj > 0.) { /* 0 < abs(A(j,j)) <= SMLNUM: */ if (xj > tjj * bignum) { /* Scale x by (1/abs(x(j)))*abs(A(j,j))*BIGNUM. */ rec = tjj * bignum / xj; zdscal_(n, &rec, &x[1], &c__1); *scale *= rec; xmax *= rec; } i__3 = j; zladiv_(&z__1, &x[j], &tjjs); x[i__3].r = z__1.r, x[i__3].i = z__1.i; } else { /* A(j,j) = 0: Set x(1:n) = 0, x(j) = 1, and scale = 0 and compute a solution to A**T *x = 0. */ i__3 = *n; for (i__ = 1; i__ <= i__3; ++i__) { i__4 = i__; x[i__4].r = 0., x[i__4].i = 0.; /* L150: */ } i__3 = j; x[i__3].r = 1., x[i__3].i = 0.; *scale = 0.; xmax = 0.; } L160: ; } else { /* Compute x(j) := x(j) / A(j,j) - CSUMJ if the dot product has already been divided by 1/A(j,j). */ i__3 = j; zladiv_(&z__2, &x[j], &tjjs); z__1.r = z__2.r - csumj.r, z__1.i = z__2.i - csumj.i; x[i__3].r = z__1.r, x[i__3].i = z__1.i; } /* Computing MAX */ i__3 = j; d__3 = xmax, d__4 = (d__1 = x[i__3].r, abs(d__1)) + (d__2 = d_imag(&x[j]), abs(d__2)); xmax = max(d__3,d__4); /* L170: */ } } else { /* Solve A**H * x = b */ i__1 = jlast; i__2 = jinc; for (j = jfirst; i__2 < 0 ? j >= i__1 : j <= i__1; j += i__2) { /* Compute x(j) = b(j) - sum A(k,j)*x(k). k<>j */ i__3 = j; xj = (d__1 = x[i__3].r, abs(d__1)) + (d__2 = d_imag(&x[j]), abs(d__2)); uscal.r = tscal, uscal.i = 0.; rec = 1. / max(xmax,1.); if (cnorm[j] > (bignum - xj) * rec) { /* If x(j) could overflow, scale x by 1/(2*XMAX). */ rec *= .5; if (nounit) { d_cnjg(&z__2, &a[j + j * a_dim1]); z__1.r = tscal * z__2.r, z__1.i = tscal * z__2.i; tjjs.r = z__1.r, tjjs.i = z__1.i; } else { tjjs.r = tscal, tjjs.i = 0.; } tjj = (d__1 = tjjs.r, abs(d__1)) + (d__2 = d_imag(&tjjs), abs(d__2)); if (tjj > 1.) { /* Divide by A(j,j) when scaling x if A(j,j) > 1. Computing MIN */ d__1 = 1., d__2 = rec * tjj; rec = min(d__1,d__2); zladiv_(&z__1, &uscal, &tjjs); uscal.r = z__1.r, uscal.i = z__1.i; } if (rec < 1.) { zdscal_(n, &rec, &x[1], &c__1); *scale *= rec; xmax *= rec; } } csumj.r = 0., csumj.i = 0.; if (uscal.r == 1. && uscal.i == 0.) { /* If the scaling needed for A in the dot product is 1, call ZDOTC to perform the dot product. */ if (upper) { i__3 = j - 1; zdotc_(&z__1, &i__3, &a[j * a_dim1 + 1], &c__1, &x[1], &c__1); csumj.r = z__1.r, csumj.i = z__1.i; } else if (j < *n) { i__3 = *n - j; zdotc_(&z__1, &i__3, &a[j + 1 + j * a_dim1], &c__1, & x[j + 1], &c__1); csumj.r = z__1.r, csumj.i = z__1.i; } } else { /* Otherwise, use in-line code for the dot product. */ if (upper) { i__3 = j - 1; for (i__ = 1; i__ <= i__3; ++i__) { d_cnjg(&z__4, &a[i__ + j * a_dim1]); z__3.r = z__4.r * uscal.r - z__4.i * uscal.i, z__3.i = z__4.r * uscal.i + z__4.i * uscal.r; i__4 = i__; z__2.r = z__3.r * x[i__4].r - z__3.i * x[i__4].i, z__2.i = z__3.r * x[i__4].i + z__3.i * x[ i__4].r; z__1.r = csumj.r + z__2.r, z__1.i = csumj.i + z__2.i; csumj.r = z__1.r, csumj.i = z__1.i; /* L180: */ } } else if (j < *n) { i__3 = *n; for (i__ = j + 1; i__ <= i__3; ++i__) { d_cnjg(&z__4, &a[i__ + j * a_dim1]); z__3.r = z__4.r * uscal.r - z__4.i * uscal.i, z__3.i = z__4.r * uscal.i + z__4.i * uscal.r; i__4 = i__; z__2.r = z__3.r * x[i__4].r - z__3.i * x[i__4].i, z__2.i = z__3.r * x[i__4].i + z__3.i * x[ i__4].r; z__1.r = csumj.r + z__2.r, z__1.i = csumj.i + z__2.i; csumj.r = z__1.r, csumj.i = z__1.i; /* L190: */ } } } z__1.r = tscal, z__1.i = 0.; if (uscal.r == z__1.r && uscal.i == z__1.i) { /* Compute x(j) := ( x(j) - CSUMJ ) / A(j,j) if 1/A(j,j) was not used to scale the dotproduct. */ i__3 = j; i__4 = j; z__1.r = x[i__4].r - csumj.r, z__1.i = x[i__4].i - csumj.i; x[i__3].r = z__1.r, x[i__3].i = z__1.i; i__3 = j; xj = (d__1 = x[i__3].r, abs(d__1)) + (d__2 = d_imag(&x[j]) , abs(d__2)); if (nounit) { d_cnjg(&z__2, &a[j + j * a_dim1]); z__1.r = tscal * z__2.r, z__1.i = tscal * z__2.i; tjjs.r = z__1.r, tjjs.i = z__1.i; } else { tjjs.r = tscal, tjjs.i = 0.; if (tscal == 1.) { goto L210; } } /* Compute x(j) = x(j) / A(j,j), scaling if necessary. */ tjj = (d__1 = tjjs.r, abs(d__1)) + (d__2 = d_imag(&tjjs), abs(d__2)); if (tjj > smlnum) { /* abs(A(j,j)) > SMLNUM: */ if (tjj < 1.) { if (xj > tjj * bignum) { /* Scale X by 1/abs(x(j)). */ rec = 1. / xj; zdscal_(n, &rec, &x[1], &c__1); *scale *= rec; xmax *= rec; } } i__3 = j; zladiv_(&z__1, &x[j], &tjjs); x[i__3].r = z__1.r, x[i__3].i = z__1.i; } else if (tjj > 0.) { /* 0 < abs(A(j,j)) <= SMLNUM: */ if (xj > tjj * bignum) { /* Scale x by (1/abs(x(j)))*abs(A(j,j))*BIGNUM. */ rec = tjj * bignum / xj; zdscal_(n, &rec, &x[1], &c__1); *scale *= rec; xmax *= rec; } i__3 = j; zladiv_(&z__1, &x[j], &tjjs); x[i__3].r = z__1.r, x[i__3].i = z__1.i; } else { /* A(j,j) = 0: Set x(1:n) = 0, x(j) = 1, and scale = 0 and compute a solution to A**H *x = 0. */ i__3 = *n; for (i__ = 1; i__ <= i__3; ++i__) { i__4 = i__; x[i__4].r = 0., x[i__4].i = 0.; /* L200: */ } i__3 = j; x[i__3].r = 1., x[i__3].i = 0.; *scale = 0.; xmax = 0.; } L210: ; } else { /* Compute x(j) := x(j) / A(j,j) - CSUMJ if the dot product has already been divided by 1/A(j,j). */ i__3 = j; zladiv_(&z__2, &x[j], &tjjs); z__1.r = z__2.r - csumj.r, z__1.i = z__2.i - csumj.i; x[i__3].r = z__1.r, x[i__3].i = z__1.i; } /* Computing MAX */ i__3 = j; d__3 = xmax, d__4 = (d__1 = x[i__3].r, abs(d__1)) + (d__2 = d_imag(&x[j]), abs(d__2)); xmax = max(d__3,d__4); /* L220: */ } } *scale /= tscal; } /* Scale the column norms by 1/TSCAL for return. */ if (tscal != 1.) { d__1 = 1. / tscal; dscal_(n, &d__1, &cnorm[1], &c__1); } return 0; /* End of ZLATRS */ } /* zlatrs_ */ /* Subroutine */ int zlauu2_(char *uplo, integer *n, doublecomplex *a, integer *lda, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3; doublereal d__1; doublecomplex z__1; /* Local variables */ static integer i__; static doublereal aii; extern logical lsame_(char *, char *); extern /* Double Complex */ VOID zdotc_(doublecomplex *, integer *, doublecomplex *, integer *, doublecomplex *, integer *); extern /* Subroutine */ int zgemv_(char *, integer *, integer *, doublecomplex *, doublecomplex *, integer *, doublecomplex *, integer *, doublecomplex *, doublecomplex *, integer *); static logical upper; extern /* Subroutine */ int xerbla_(char *, integer *), zdscal_( integer *, doublereal *, doublecomplex *, integer *), zlacgv_( integer *, doublecomplex *, integer *); /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University September 30, 1994 Purpose ======= ZLAUU2 computes the product U * U' or L' * L, where the triangular factor U or L is stored in the upper or lower triangular part of the array A. If UPLO = 'U' or 'u' then the upper triangle of the result is stored, overwriting the factor U in A. If UPLO = 'L' or 'l' then the lower triangle of the result is stored, overwriting the factor L in A. This is the unblocked form of the algorithm, calling Level 2 BLAS. Arguments ========= UPLO (input) CHARACTER*1 Specifies whether the triangular factor stored in the array A is upper or lower triangular: = 'U': Upper triangular = 'L': Lower triangular N (input) INTEGER The order of the triangular factor U or L. N >= 0. A (input/output) COMPLEX*16 array, dimension (LDA,N) On entry, the triangular factor U or L. On exit, if UPLO = 'U', the upper triangle of A is overwritten with the upper triangle of the product U * U'; if UPLO = 'L', the lower triangle of A is overwritten with the lower triangle of the product L' * L. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,N). INFO (output) INTEGER = 0: successful exit < 0: if INFO = -k, the k-th argument had an illegal value ===================================================================== Test the input parameters. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; /* Function Body */ *info = 0; upper = lsame_(uplo, "U"); if (! upper && ! lsame_(uplo, "L")) { *info = -1; } else if (*n < 0) { *info = -2; } else if (*lda < max(1,*n)) { *info = -4; } if (*info != 0) { i__1 = -(*info); xerbla_("ZLAUU2", &i__1); return 0; } /* Quick return if possible */ if (*n == 0) { return 0; } if (upper) { /* Compute the product U * U'. */ i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = i__ + i__ * a_dim1; aii = a[i__2].r; if (i__ < *n) { i__2 = i__ + i__ * a_dim1; i__3 = *n - i__; zdotc_(&z__1, &i__3, &a[i__ + (i__ + 1) * a_dim1], lda, &a[ i__ + (i__ + 1) * a_dim1], lda); d__1 = aii * aii + z__1.r; a[i__2].r = d__1, a[i__2].i = 0.; i__2 = *n - i__; zlacgv_(&i__2, &a[i__ + (i__ + 1) * a_dim1], lda); i__2 = i__ - 1; i__3 = *n - i__; z__1.r = aii, z__1.i = 0.; zgemv_("No transpose", &i__2, &i__3, &c_b60, &a[(i__ + 1) * a_dim1 + 1], lda, &a[i__ + (i__ + 1) * a_dim1], lda, & z__1, &a[i__ * a_dim1 + 1], &c__1); i__2 = *n - i__; zlacgv_(&i__2, &a[i__ + (i__ + 1) * a_dim1], lda); } else { zdscal_(&i__, &aii, &a[i__ * a_dim1 + 1], &c__1); } /* L10: */ } } else { /* Compute the product L' * L. */ i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = i__ + i__ * a_dim1; aii = a[i__2].r; if (i__ < *n) { i__2 = i__ + i__ * a_dim1; i__3 = *n - i__; zdotc_(&z__1, &i__3, &a[i__ + 1 + i__ * a_dim1], &c__1, &a[ i__ + 1 + i__ * a_dim1], &c__1); d__1 = aii * aii + z__1.r; a[i__2].r = d__1, a[i__2].i = 0.; i__2 = i__ - 1; zlacgv_(&i__2, &a[i__ + a_dim1], lda); i__2 = *n - i__; i__3 = i__ - 1; z__1.r = aii, z__1.i = 0.; zgemv_("Conjugate transpose", &i__2, &i__3, &c_b60, &a[i__ + 1 + a_dim1], lda, &a[i__ + 1 + i__ * a_dim1], &c__1, & z__1, &a[i__ + a_dim1], lda); i__2 = i__ - 1; zlacgv_(&i__2, &a[i__ + a_dim1], lda); } else { zdscal_(&i__, &aii, &a[i__ + a_dim1], lda); } /* L20: */ } } return 0; /* End of ZLAUU2 */ } /* zlauu2_ */ /* Subroutine */ int zlauum_(char *uplo, integer *n, doublecomplex *a, integer *lda, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3, i__4; /* Local variables */ static integer i__, ib, nb; extern logical lsame_(char *, char *); extern /* Subroutine */ int zgemm_(char *, char *, integer *, integer *, integer *, doublecomplex *, doublecomplex *, integer *, doublecomplex *, integer *, doublecomplex *, doublecomplex *, integer *), zherk_(char *, char *, integer *, integer *, doublereal *, doublecomplex *, integer *, doublereal *, doublecomplex *, integer *); static logical upper; extern /* Subroutine */ int ztrmm_(char *, char *, char *, char *, integer *, integer *, doublecomplex *, doublecomplex *, integer *, doublecomplex *, integer *), zlauu2_(char *, integer *, doublecomplex *, integer *, integer *), xerbla_(char *, integer *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University September 30, 1994 Purpose ======= ZLAUUM computes the product U * U' or L' * L, where the triangular factor U or L is stored in the upper or lower triangular part of the array A. If UPLO = 'U' or 'u' then the upper triangle of the result is stored, overwriting the factor U in A. If UPLO = 'L' or 'l' then the lower triangle of the result is stored, overwriting the factor L in A. This is the blocked form of the algorithm, calling Level 3 BLAS. Arguments ========= UPLO (input) CHARACTER*1 Specifies whether the triangular factor stored in the array A is upper or lower triangular: = 'U': Upper triangular = 'L': Lower triangular N (input) INTEGER The order of the triangular factor U or L. N >= 0. A (input/output) COMPLEX*16 array, dimension (LDA,N) On entry, the triangular factor U or L. On exit, if UPLO = 'U', the upper triangle of A is overwritten with the upper triangle of the product U * U'; if UPLO = 'L', the lower triangle of A is overwritten with the lower triangle of the product L' * L. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,N). INFO (output) INTEGER = 0: successful exit < 0: if INFO = -k, the k-th argument had an illegal value ===================================================================== Test the input parameters. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; /* Function Body */ *info = 0; upper = lsame_(uplo, "U"); if (! upper && ! lsame_(uplo, "L")) { *info = -1; } else if (*n < 0) { *info = -2; } else if (*lda < max(1,*n)) { *info = -4; } if (*info != 0) { i__1 = -(*info); xerbla_("ZLAUUM", &i__1); return 0; } /* Quick return if possible */ if (*n == 0) { return 0; } /* Determine the block size for this environment. */ nb = ilaenv_(&c__1, "ZLAUUM", uplo, n, &c_n1, &c_n1, &c_n1, (ftnlen)6, ( ftnlen)1); if ((nb <= 1) || (nb >= *n)) { /* Use unblocked code */ zlauu2_(uplo, n, &a[a_offset], lda, info); } else { /* Use blocked code */ if (upper) { /* Compute the product U * U'. */ i__1 = *n; i__2 = nb; for (i__ = 1; i__2 < 0 ? i__ >= i__1 : i__ <= i__1; i__ += i__2) { /* Computing MIN */ i__3 = nb, i__4 = *n - i__ + 1; ib = min(i__3,i__4); i__3 = i__ - 1; ztrmm_("Right", "Upper", "Conjugate transpose", "Non-unit", & i__3, &ib, &c_b60, &a[i__ + i__ * a_dim1], lda, &a[ i__ * a_dim1 + 1], lda); zlauu2_("Upper", &ib, &a[i__ + i__ * a_dim1], lda, info); if (i__ + ib <= *n) { i__3 = i__ - 1; i__4 = *n - i__ - ib + 1; zgemm_("No transpose", "Conjugate transpose", &i__3, &ib, &i__4, &c_b60, &a[(i__ + ib) * a_dim1 + 1], lda, & a[i__ + (i__ + ib) * a_dim1], lda, &c_b60, &a[i__ * a_dim1 + 1], lda); i__3 = *n - i__ - ib + 1; zherk_("Upper", "No transpose", &ib, &i__3, &c_b1015, &a[ i__ + (i__ + ib) * a_dim1], lda, &c_b1015, &a[i__ + i__ * a_dim1], lda); } /* L10: */ } } else { /* Compute the product L' * L. */ i__2 = *n; i__1 = nb; for (i__ = 1; i__1 < 0 ? i__ >= i__2 : i__ <= i__2; i__ += i__1) { /* Computing MIN */ i__3 = nb, i__4 = *n - i__ + 1; ib = min(i__3,i__4); i__3 = i__ - 1; ztrmm_("Left", "Lower", "Conjugate transpose", "Non-unit", & ib, &i__3, &c_b60, &a[i__ + i__ * a_dim1], lda, &a[ i__ + a_dim1], lda); zlauu2_("Lower", &ib, &a[i__ + i__ * a_dim1], lda, info); if (i__ + ib <= *n) { i__3 = i__ - 1; i__4 = *n - i__ - ib + 1; zgemm_("Conjugate transpose", "No transpose", &ib, &i__3, &i__4, &c_b60, &a[i__ + ib + i__ * a_dim1], lda, & a[i__ + ib + a_dim1], lda, &c_b60, &a[i__ + a_dim1], lda); i__3 = *n - i__ - ib + 1; zherk_("Lower", "Conjugate transpose", &ib, &i__3, & c_b1015, &a[i__ + ib + i__ * a_dim1], lda, & c_b1015, &a[i__ + i__ * a_dim1], lda); } /* L20: */ } } } return 0; /* End of ZLAUUM */ } /* zlauum_ */ /* Subroutine */ int zpotf2_(char *uplo, integer *n, doublecomplex *a, integer *lda, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3; doublereal d__1; doublecomplex z__1, z__2; /* Builtin functions */ double sqrt(doublereal); /* Local variables */ static integer j; static doublereal ajj; extern logical lsame_(char *, char *); extern /* Double Complex */ VOID zdotc_(doublecomplex *, integer *, doublecomplex *, integer *, doublecomplex *, integer *); extern /* Subroutine */ int zgemv_(char *, integer *, integer *, doublecomplex *, doublecomplex *, integer *, doublecomplex *, integer *, doublecomplex *, doublecomplex *, integer *); static logical upper; extern /* Subroutine */ int xerbla_(char *, integer *), zdscal_( integer *, doublereal *, doublecomplex *, integer *), zlacgv_( integer *, doublecomplex *, integer *); /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University September 30, 1994 Purpose ======= ZPOTF2 computes the Cholesky factorization of a complex Hermitian positive definite matrix A. The factorization has the form A = U' * U , if UPLO = 'U', or A = L * L', if UPLO = 'L', where U is an upper triangular matrix and L is lower triangular. This is the unblocked version of the algorithm, calling Level 2 BLAS. Arguments ========= UPLO (input) CHARACTER*1 Specifies whether the upper or lower triangular part of the Hermitian matrix A is stored. = 'U': Upper triangular = 'L': Lower triangular N (input) INTEGER The order of the matrix A. N >= 0. 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, and the strictly lower triangular part of A is not referenced. If UPLO = 'L', the leading n by n lower triangular part of A contains the lower triangular part of the matrix A, and the strictly upper triangular part of A is not referenced. On exit, if INFO = 0, the factor U or L from the Cholesky factorization A = U'*U or A = L*L'. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,N). INFO (output) INTEGER = 0: successful exit < 0: if INFO = -k, the k-th argument had an illegal value > 0: if INFO = k, the leading minor of order k is not positive definite, and the factorization could not be completed. ===================================================================== Test the input parameters. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; /* Function Body */ *info = 0; upper = lsame_(uplo, "U"); if (! upper && ! lsame_(uplo, "L")) { *info = -1; } else if (*n < 0) { *info = -2; } else if (*lda < max(1,*n)) { *info = -4; } if (*info != 0) { i__1 = -(*info); xerbla_("ZPOTF2", &i__1); return 0; } /* Quick return if possible */ if (*n == 0) { return 0; } if (upper) { /* Compute the Cholesky factorization A = U'*U. */ i__1 = *n; for (j = 1; j <= i__1; ++j) { /* Compute U(J,J) and test for non-positive-definiteness. */ i__2 = j + j * a_dim1; d__1 = a[i__2].r; i__3 = j - 1; zdotc_(&z__2, &i__3, &a[j * a_dim1 + 1], &c__1, &a[j * a_dim1 + 1] , &c__1); z__1.r = d__1 - z__2.r, z__1.i = -z__2.i; ajj = z__1.r; if (ajj <= 0.) { i__2 = j + j * a_dim1; a[i__2].r = ajj, a[i__2].i = 0.; goto L30; } ajj = sqrt(ajj); i__2 = j + j * a_dim1; a[i__2].r = ajj, a[i__2].i = 0.; /* Compute elements J+1:N of row J. */ if (j < *n) { i__2 = j - 1; zlacgv_(&i__2, &a[j * a_dim1 + 1], &c__1); i__2 = j - 1; i__3 = *n - j; z__1.r = -1., z__1.i = -0.; zgemv_("Transpose", &i__2, &i__3, &z__1, &a[(j + 1) * a_dim1 + 1], lda, &a[j * a_dim1 + 1], &c__1, &c_b60, &a[j + ( j + 1) * a_dim1], lda); i__2 = j - 1; zlacgv_(&i__2, &a[j * a_dim1 + 1], &c__1); i__2 = *n - j; d__1 = 1. / ajj; zdscal_(&i__2, &d__1, &a[j + (j + 1) * a_dim1], lda); } /* L10: */ } } else { /* Compute the Cholesky factorization A = L*L'. */ i__1 = *n; for (j = 1; j <= i__1; ++j) { /* Compute L(J,J) and test for non-positive-definiteness. */ i__2 = j + j * a_dim1; d__1 = a[i__2].r; i__3 = j - 1; zdotc_(&z__2, &i__3, &a[j + a_dim1], lda, &a[j + a_dim1], lda); z__1.r = d__1 - z__2.r, z__1.i = -z__2.i; ajj = z__1.r; if (ajj <= 0.) { i__2 = j + j * a_dim1; a[i__2].r = ajj, a[i__2].i = 0.; goto L30; } ajj = sqrt(ajj); i__2 = j + j * a_dim1; a[i__2].r = ajj, a[i__2].i = 0.; /* Compute elements J+1:N of column J. */ if (j < *n) { i__2 = j - 1; zlacgv_(&i__2, &a[j + a_dim1], lda); i__2 = *n - j; i__3 = j - 1; z__1.r = -1., z__1.i = -0.; zgemv_("No transpose", &i__2, &i__3, &z__1, &a[j + 1 + a_dim1] , lda, &a[j + a_dim1], lda, &c_b60, &a[j + 1 + j * a_dim1], &c__1); i__2 = j - 1; zlacgv_(&i__2, &a[j + a_dim1], lda); i__2 = *n - j; d__1 = 1. / ajj; zdscal_(&i__2, &d__1, &a[j + 1 + j * a_dim1], &c__1); } /* L20: */ } } goto L40; L30: *info = j; L40: return 0; /* End of ZPOTF2 */ } /* zpotf2_ */ /* Subroutine */ int zpotrf_(char *uplo, integer *n, doublecomplex *a, integer *lda, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3, i__4; doublecomplex z__1; /* Local variables */ static integer j, jb, nb; extern logical lsame_(char *, char *); extern /* Subroutine */ int zgemm_(char *, char *, integer *, integer *, integer *, doublecomplex *, doublecomplex *, integer *, doublecomplex *, integer *, doublecomplex *, doublecomplex *, integer *), zherk_(char *, char *, integer *, integer *, doublereal *, doublecomplex *, integer *, doublereal *, doublecomplex *, integer *); static logical upper; extern /* Subroutine */ int ztrsm_(char *, char *, char *, char *, integer *, integer *, doublecomplex *, doublecomplex *, integer *, doublecomplex *, integer *), zpotf2_(char *, integer *, doublecomplex *, integer *, integer *), xerbla_(char *, integer *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University September 30, 1994 Purpose ======= ZPOTRF computes the Cholesky factorization of a complex Hermitian positive definite matrix A. The factorization has the form A = U**H * U, if UPLO = 'U', or A = L * L**H, if UPLO = 'L', where U is an upper triangular matrix and L is lower triangular. This is the block version of the algorithm, calling Level 3 BLAS. Arguments ========= UPLO (input) CHARACTER*1 = 'U': Upper triangle of A is stored; = 'L': Lower triangle of A is stored. N (input) INTEGER The order of the matrix A. N >= 0. 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, and the strictly lower triangular part of A is not referenced. If UPLO = 'L', the leading N-by-N lower triangular part of A contains the lower triangular part of the matrix A, and the strictly upper triangular part of A is not referenced. On exit, if INFO = 0, the factor U or L from the Cholesky factorization A = U**H*U or A = L*L**H. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,N). INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value > 0: if INFO = i, the leading minor of order i is not positive definite, and the factorization could not be completed. ===================================================================== Test the input parameters. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; /* Function Body */ *info = 0; upper = lsame_(uplo, "U"); if (! upper && ! lsame_(uplo, "L")) { *info = -1; } else if (*n < 0) { *info = -2; } else if (*lda < max(1,*n)) { *info = -4; } if (*info != 0) { i__1 = -(*info); xerbla_("ZPOTRF", &i__1); return 0; } /* Quick return if possible */ if (*n == 0) { return 0; } /* Determine the block size for this environment. */ nb = ilaenv_(&c__1, "ZPOTRF", uplo, n, &c_n1, &c_n1, &c_n1, (ftnlen)6, ( ftnlen)1); if ((nb <= 1) || (nb >= *n)) { /* Use unblocked code. */ zpotf2_(uplo, n, &a[a_offset], lda, info); } else { /* Use blocked code. */ if (upper) { /* Compute the Cholesky factorization A = U'*U. */ i__1 = *n; i__2 = nb; for (j = 1; i__2 < 0 ? j >= i__1 : j <= i__1; j += i__2) { /* Update and factorize the current diagonal block and test for non-positive-definiteness. Computing MIN */ i__3 = nb, i__4 = *n - j + 1; jb = min(i__3,i__4); i__3 = j - 1; zherk_("Upper", "Conjugate transpose", &jb, &i__3, &c_b1294, & a[j * a_dim1 + 1], lda, &c_b1015, &a[j + j * a_dim1], lda); zpotf2_("Upper", &jb, &a[j + j * a_dim1], lda, info); if (*info != 0) { goto L30; } if (j + jb <= *n) { /* Compute the current block row. */ i__3 = *n - j - jb + 1; i__4 = j - 1; z__1.r = -1., z__1.i = -0.; zgemm_("Conjugate transpose", "No transpose", &jb, &i__3, &i__4, &z__1, &a[j * a_dim1 + 1], lda, &a[(j + jb) * a_dim1 + 1], lda, &c_b60, &a[j + (j + jb) * a_dim1], lda); i__3 = *n - j - jb + 1; ztrsm_("Left", "Upper", "Conjugate transpose", "Non-unit", &jb, &i__3, &c_b60, &a[j + j * a_dim1], lda, &a[ j + (j + jb) * a_dim1], lda); } /* L10: */ } } else { /* Compute the Cholesky factorization A = L*L'. */ i__2 = *n; i__1 = nb; for (j = 1; i__1 < 0 ? j >= i__2 : j <= i__2; j += i__1) { /* Update and factorize the current diagonal block and test for non-positive-definiteness. Computing MIN */ i__3 = nb, i__4 = *n - j + 1; jb = min(i__3,i__4); i__3 = j - 1; zherk_("Lower", "No transpose", &jb, &i__3, &c_b1294, &a[j + a_dim1], lda, &c_b1015, &a[j + j * a_dim1], lda); zpotf2_("Lower", &jb, &a[j + j * a_dim1], lda, info); if (*info != 0) { goto L30; } if (j + jb <= *n) { /* Compute the current block column. */ i__3 = *n - j - jb + 1; i__4 = j - 1; z__1.r = -1., z__1.i = -0.; zgemm_("No transpose", "Conjugate transpose", &i__3, &jb, &i__4, &z__1, &a[j + jb + a_dim1], lda, &a[j + a_dim1], lda, &c_b60, &a[j + jb + j * a_dim1], lda); i__3 = *n - j - jb + 1; ztrsm_("Right", "Lower", "Conjugate transpose", "Non-unit" , &i__3, &jb, &c_b60, &a[j + j * a_dim1], lda, &a[ j + jb + j * a_dim1], lda); } /* L20: */ } } } goto L40; L30: *info = *info + j - 1; L40: return 0; /* End of ZPOTRF */ } /* zpotrf_ */ /* Subroutine */ int zpotri_(char *uplo, integer *n, doublecomplex *a, integer *lda, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1; /* Local variables */ extern logical lsame_(char *, char *); extern /* Subroutine */ int xerbla_(char *, integer *), zlauum_( char *, integer *, doublecomplex *, integer *, integer *), ztrtri_(char *, char *, integer *, doublecomplex *, integer *, integer *); /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University March 31, 1993 Purpose ======= ZPOTRI computes the inverse of a complex Hermitian positive definite matrix A using the Cholesky factorization A = U**H*U or A = L*L**H computed by ZPOTRF. Arguments ========= UPLO (input) CHARACTER*1 = 'U': Upper triangle of A is stored; = 'L': Lower triangle of A is stored. N (input) INTEGER The order of the matrix A. N >= 0. A (input/output) COMPLEX*16 array, dimension (LDA,N) On entry, the triangular factor U or L from the Cholesky factorization A = U**H*U or A = L*L**H, as computed by ZPOTRF. On exit, the upper or lower triangle of the (Hermitian) inverse of A, overwriting the input factor U or L. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,N). INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value > 0: if INFO = i, the (i,i) element of the factor U or L is zero, and the inverse could not be computed. ===================================================================== Test the input parameters. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; /* Function Body */ *info = 0; if (! lsame_(uplo, "U") && ! lsame_(uplo, "L")) { *info = -1; } else if (*n < 0) { *info = -2; } else if (*lda < max(1,*n)) { *info = -4; } if (*info != 0) { i__1 = -(*info); xerbla_("ZPOTRI", &i__1); return 0; } /* Quick return if possible */ if (*n == 0) { return 0; } /* Invert the triangular Cholesky factor U or L. */ ztrtri_(uplo, "Non-unit", n, &a[a_offset], lda, info); if (*info > 0) { return 0; } /* Form inv(U)*inv(U)' or inv(L)'*inv(L). */ zlauum_(uplo, n, &a[a_offset], lda, info); return 0; /* End of ZPOTRI */ } /* zpotri_ */ /* Subroutine */ int zpotrs_(char *uplo, integer *n, integer *nrhs, doublecomplex *a, integer *lda, doublecomplex *b, integer *ldb, integer *info) { /* System generated locals */ integer a_dim1, a_offset, b_dim1, b_offset, i__1; /* Local variables */ extern logical lsame_(char *, char *); static logical upper; extern /* Subroutine */ int ztrsm_(char *, char *, char *, char *, integer *, integer *, doublecomplex *, doublecomplex *, integer *, doublecomplex *, integer *), xerbla_(char *, integer *); /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University September 30, 1994 Purpose ======= ZPOTRS solves a system of linear equations A*X = B with a Hermitian positive definite matrix A using the Cholesky factorization A = U**H*U or A = L*L**H computed by ZPOTRF. Arguments ========= UPLO (input) CHARACTER*1 = 'U': Upper triangle of A is stored; = 'L': Lower triangle of A is stored. N (input) INTEGER The order of the matrix A. N >= 0. NRHS (input) INTEGER The number of right hand sides, i.e., the number of columns of the matrix B. NRHS >= 0. A (input) COMPLEX*16 array, dimension (LDA,N) The triangular factor U or L from the Cholesky factorization A = U**H*U or A = L*L**H, as computed by ZPOTRF. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,N). B (input/output) COMPLEX*16 array, dimension (LDB,NRHS) On entry, the right hand side matrix B. On exit, the solution matrix X. LDB (input) INTEGER The leading dimension of the array B. LDB >= max(1,N). INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value ===================================================================== Test the input parameters. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; b_dim1 = *ldb; b_offset = 1 + b_dim1; b -= b_offset; /* Function Body */ *info = 0; upper = lsame_(uplo, "U"); if (! upper && ! lsame_(uplo, "L")) { *info = -1; } else if (*n < 0) { *info = -2; } else if (*nrhs < 0) { *info = -3; } else if (*lda < max(1,*n)) { *info = -5; } else if (*ldb < max(1,*n)) { *info = -7; } if (*info != 0) { i__1 = -(*info); xerbla_("ZPOTRS", &i__1); return 0; } /* Quick return if possible */ if ((*n == 0) || (*nrhs == 0)) { return 0; } if (upper) { /* Solve A*X = B where A = U'*U. Solve U'*X = B, overwriting B with X. */ ztrsm_("Left", "Upper", "Conjugate transpose", "Non-unit", n, nrhs, & c_b60, &a[a_offset], lda, &b[b_offset], ldb); /* Solve U*X = B, overwriting B with X. */ ztrsm_("Left", "Upper", "No transpose", "Non-unit", n, nrhs, &c_b60, & a[a_offset], lda, &b[b_offset], ldb); } else { /* Solve A*X = B where A = L*L'. Solve L*X = B, overwriting B with X. */ ztrsm_("Left", "Lower", "No transpose", "Non-unit", n, nrhs, &c_b60, & a[a_offset], lda, &b[b_offset], ldb); /* Solve L'*X = B, overwriting B with X. */ ztrsm_("Left", "Lower", "Conjugate transpose", "Non-unit", n, nrhs, & c_b60, &a[a_offset], lda, &b[b_offset], ldb); } return 0; /* End of ZPOTRS */ } /* zpotrs_ */ /* Subroutine */ int zstedc_(char *compz, integer *n, doublereal *d__, doublereal *e, doublecomplex *z__, integer *ldz, doublecomplex *work, integer *lwork, doublereal *rwork, integer *lrwork, integer *iwork, integer *liwork, integer *info) { /* System generated locals */ integer z_dim1, z_offset, i__1, i__2, i__3, i__4; doublereal d__1, d__2; /* Builtin functions */ double log(doublereal); integer pow_ii(integer *, integer *); double sqrt(doublereal); /* Local variables */ static integer i__, j, k, m; static doublereal p; static integer ii, ll, end, lgn; static doublereal eps, tiny; extern logical lsame_(char *, char *); static integer lwmin, start; extern /* Subroutine */ int zswap_(integer *, doublecomplex *, integer *, doublecomplex *, integer *), zlaed0_(integer *, integer *, doublereal *, doublereal *, doublecomplex *, integer *, doublecomplex *, integer *, doublereal *, integer *, integer *); extern /* Subroutine */ int dlascl_(char *, integer *, integer *, doublereal *, doublereal *, integer *, integer *, doublereal *, integer *, integer *), dstedc_(char *, integer *, doublereal *, doublereal *, doublereal *, integer *, doublereal *, integer *, integer *, integer *, integer *), dlaset_( char *, integer *, integer *, doublereal *, doublereal *, doublereal *, integer *), xerbla_(char *, integer *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); extern doublereal dlanst_(char *, integer *, doublereal *, doublereal *); extern /* Subroutine */ int dsterf_(integer *, doublereal *, doublereal *, integer *), zlacrm_(integer *, integer *, doublecomplex *, integer *, doublereal *, integer *, doublecomplex *, integer *, doublereal *); static integer liwmin, icompz; extern /* Subroutine */ int dsteqr_(char *, integer *, doublereal *, doublereal *, doublereal *, integer *, doublereal *, integer *), zlacpy_(char *, integer *, integer *, doublecomplex *, integer *, doublecomplex *, integer *); static doublereal orgnrm; static integer lrwmin; static logical lquery; static integer smlsiz; extern /* Subroutine */ int zsteqr_(char *, integer *, doublereal *, doublereal *, doublecomplex *, integer *, doublereal *, integer *); /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= ZSTEDC computes all eigenvalues and, optionally, eigenvectors of a symmetric tridiagonal matrix using the divide and conquer method. The eigenvectors of a full or band complex Hermitian matrix can also be found if ZHETRD or ZHPTRD or ZHBTRD has been used to reduce this matrix to tridiagonal form. This code makes very mild assumptions about floating point arithmetic. It will work on machines with a guard digit in add/subtract, or on those binary machines without guard digits which subtract like the Cray X-MP, Cray Y-MP, Cray C-90, or Cray-2. It could conceivably fail on hexadecimal or decimal machines without guard digits, but we know of none. See DLAED3 for details. Arguments ========= COMPZ (input) CHARACTER*1 = 'N': Compute eigenvalues only. = 'I': Compute eigenvectors of tridiagonal matrix also. = 'V': Compute eigenvectors of original Hermitian matrix also. On entry, Z contains the unitary matrix used to reduce the original matrix to tridiagonal form. N (input) INTEGER The dimension of the symmetric tridiagonal matrix. N >= 0. D (input/output) DOUBLE PRECISION array, dimension (N) On entry, the diagonal elements of the tridiagonal matrix. On exit, if INFO = 0, the eigenvalues in ascending order. E (input/output) DOUBLE PRECISION array, dimension (N-1) On entry, the subdiagonal elements of the tridiagonal matrix. On exit, E has been destroyed. Z (input/output) COMPLEX*16 array, dimension (LDZ,N) On entry, if COMPZ = 'V', then Z contains the unitary matrix used in the reduction to tridiagonal form. On exit, if INFO = 0, then if COMPZ = 'V', Z contains the orthonormal eigenvectors of the original Hermitian matrix, and if COMPZ = 'I', Z contains the orthonormal eigenvectors of the symmetric tridiagonal matrix. If COMPZ = 'N', then Z is not referenced. LDZ (input) INTEGER The leading dimension of the array Z. LDZ >= 1. If eigenvectors are desired, then LDZ >= max(1,N). WORK (workspace/output) COMPLEX*16 array, dimension (LWORK) On exit, if INFO = 0, WORK(1) returns the optimal LWORK. LWORK (input) INTEGER The dimension of the array WORK. If COMPZ = 'N' or 'I', or N <= 1, LWORK must be at least 1. If COMPZ = 'V' and N > 1, LWORK must be at least N*N. If LWORK = -1, then a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued by XERBLA. RWORK (workspace/output) DOUBLE PRECISION array, dimension (LRWORK) On exit, if INFO = 0, RWORK(1) returns the optimal LRWORK. LRWORK (input) INTEGER The dimension of the array RWORK. If COMPZ = 'N' or N <= 1, LRWORK must be at least 1. If COMPZ = 'V' and N > 1, LRWORK must be at least 1 + 3*N + 2*N*lg N + 3*N**2 , where lg( N ) = smallest integer k such that 2**k >= N. If COMPZ = 'I' and N > 1, LRWORK must be at least 1 + 4*N + 2*N**2 . If LRWORK = -1, then a workspace query is assumed; the routine only calculates the optimal size of the RWORK array, returns this value as the first entry of the RWORK array, and no error message related to LRWORK is issued by XERBLA. IWORK (workspace/output) INTEGER array, dimension (LIWORK) On exit, if INFO = 0, IWORK(1) returns the optimal LIWORK. LIWORK (input) INTEGER The dimension of the array IWORK. If COMPZ = 'N' or N <= 1, LIWORK must be at least 1. If COMPZ = 'V' or N > 1, LIWORK must be at least 6 + 6*N + 5*N*lg N. If COMPZ = 'I' or N > 1, LIWORK must be at least 3 + 5*N . If LIWORK = -1, then a workspace query is assumed; the routine only calculates the optimal size of the IWORK array, returns this value as the first entry of the IWORK array, and no error message related to LIWORK is issued by XERBLA. INFO (output) INTEGER = 0: successful exit. < 0: if INFO = -i, the i-th argument had an illegal value. > 0: The algorithm failed to compute an eigenvalue while working on the submatrix lying in rows and columns INFO/(N+1) through mod(INFO,N+1). Further Details =============== Based on contributions by Jeff Rutter, Computer Science Division, University of California at Berkeley, USA ===================================================================== Test the input parameters. */ /* Parameter adjustments */ --d__; --e; z_dim1 = *ldz; z_offset = 1 + z_dim1; z__ -= z_offset; --work; --rwork; --iwork; /* Function Body */ *info = 0; lquery = ((*lwork == -1) || (*lrwork == -1)) || (*liwork == -1); if (lsame_(compz, "N")) { icompz = 0; } else if (lsame_(compz, "V")) { icompz = 1; } else if (lsame_(compz, "I")) { icompz = 2; } else { icompz = -1; } if ((*n <= 1) || (icompz <= 0)) { lwmin = 1; liwmin = 1; lrwmin = 1; } else { lgn = (integer) (log((doublereal) (*n)) / log(2.)); if (pow_ii(&c__2, &lgn) < *n) { ++lgn; } if (pow_ii(&c__2, &lgn) < *n) { ++lgn; } if (icompz == 1) { lwmin = *n * *n; /* Computing 2nd power */ i__1 = *n; lrwmin = *n * 3 + 1 + ((*n) << (1)) * lgn + i__1 * i__1 * 3; liwmin = *n * 6 + 6 + *n * 5 * lgn; } else if (icompz == 2) { lwmin = 1; /* Computing 2nd power */ i__1 = *n; lrwmin = ((*n) << (2)) + 1 + ((i__1 * i__1) << (1)); liwmin = *n * 5 + 3; } } if (icompz < 0) { *info = -1; } else if (*n < 0) { *info = -2; } else if ((*ldz < 1) || (icompz > 0 && *ldz < max(1,*n))) { *info = -6; } else if (*lwork < lwmin && ! lquery) { *info = -8; } else if (*lrwork < lrwmin && ! lquery) { *info = -10; } else if (*liwork < liwmin && ! lquery) { *info = -12; } if (*info == 0) { work[1].r = (doublereal) lwmin, work[1].i = 0.; rwork[1] = (doublereal) lrwmin; iwork[1] = liwmin; } if (*info != 0) { i__1 = -(*info); xerbla_("ZSTEDC", &i__1); return 0; } else if (lquery) { return 0; } /* Quick return if possible */ if (*n == 0) { return 0; } if (*n == 1) { if (icompz != 0) { i__1 = z_dim1 + 1; z__[i__1].r = 1., z__[i__1].i = 0.; } return 0; } smlsiz = ilaenv_(&c__9, "ZSTEDC", " ", &c__0, &c__0, &c__0, &c__0, ( ftnlen)6, (ftnlen)1); /* If the following conditional clause is removed, then the routine will use the Divide and Conquer routine to compute only the eigenvalues, which requires (3N + 3N**2) real workspace and (2 + 5N + 2N lg(N)) integer workspace. Since on many architectures DSTERF is much faster than any other algorithm for finding eigenvalues only, it is used here as the default. If COMPZ = 'N', use DSTERF to compute the eigenvalues. */ if (icompz == 0) { dsterf_(n, &d__[1], &e[1], info); return 0; } /* If N is smaller than the minimum divide size (SMLSIZ+1), then solve the problem with another solver. */ if (*n <= smlsiz) { if (icompz == 0) { dsterf_(n, &d__[1], &e[1], info); return 0; } else if (icompz == 2) { zsteqr_("I", n, &d__[1], &e[1], &z__[z_offset], ldz, &rwork[1], info); return 0; } else { zsteqr_("V", n, &d__[1], &e[1], &z__[z_offset], ldz, &rwork[1], info); return 0; } } /* If COMPZ = 'I', we simply call DSTEDC instead. */ if (icompz == 2) { dlaset_("Full", n, n, &c_b324, &c_b1015, &rwork[1], n); ll = *n * *n + 1; i__1 = *lrwork - ll + 1; dstedc_("I", n, &d__[1], &e[1], &rwork[1], n, &rwork[ll], &i__1, & iwork[1], liwork, info); i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *n; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * z_dim1; i__4 = (j - 1) * *n + i__; z__[i__3].r = rwork[i__4], z__[i__3].i = 0.; /* L10: */ } /* L20: */ } return 0; } /* From now on, only option left to be handled is COMPZ = 'V', i.e. ICOMPZ = 1. Scale. */ orgnrm = dlanst_("M", n, &d__[1], &e[1]); if (orgnrm == 0.) { return 0; } eps = EPSILON; start = 1; /* while ( START <= N ) */ L30: if (start <= *n) { /* Let END be the position of the next subdiagonal entry such that E( END ) <= TINY or END = N if no such subdiagonal exists. The matrix identified by the elements between START and END constitutes an independent sub-problem. */ end = start; L40: if (end < *n) { tiny = eps * sqrt((d__1 = d__[end], abs(d__1))) * sqrt((d__2 = d__[end + 1], abs(d__2))); if ((d__1 = e[end], abs(d__1)) > tiny) { ++end; goto L40; } } /* (Sub) Problem determined. Compute its size and solve it. */ m = end - start + 1; if (m > smlsiz) { *info = smlsiz; /* Scale. */ orgnrm = dlanst_("M", &m, &d__[start], &e[start]); dlascl_("G", &c__0, &c__0, &orgnrm, &c_b1015, &m, &c__1, &d__[ start], &m, info); i__1 = m - 1; i__2 = m - 1; dlascl_("G", &c__0, &c__0, &orgnrm, &c_b1015, &i__1, &c__1, &e[ start], &i__2, info); zlaed0_(n, &m, &d__[start], &e[start], &z__[start * z_dim1 + 1], ldz, &work[1], n, &rwork[1], &iwork[1], info); if (*info > 0) { *info = (*info / (m + 1) + start - 1) * (*n + 1) + *info % (m + 1) + start - 1; return 0; } /* Scale back. */ dlascl_("G", &c__0, &c__0, &c_b1015, &orgnrm, &m, &c__1, &d__[ start], &m, info); } else { dsteqr_("I", &m, &d__[start], &e[start], &rwork[1], &m, &rwork[m * m + 1], info); zlacrm_(n, &m, &z__[start * z_dim1 + 1], ldz, &rwork[1], &m, & work[1], n, &rwork[m * m + 1]); zlacpy_("A", n, &m, &work[1], n, &z__[start * z_dim1 + 1], ldz); if (*info > 0) { *info = start * (*n + 1) + end; return 0; } } start = end + 1; goto L30; } /* endwhile If the problem split any number of times, then the eigenvalues will not be properly ordered. Here we permute the eigenvalues (and the associated eigenvectors) into ascending order. */ if (m != *n) { /* Use Selection Sort to minimize swaps of eigenvectors */ i__1 = *n; for (ii = 2; ii <= i__1; ++ii) { i__ = ii - 1; k = i__; p = d__[i__]; i__2 = *n; for (j = ii; j <= i__2; ++j) { if (d__[j] < p) { k = j; p = d__[j]; } /* L50: */ } if (k != i__) { d__[k] = d__[i__]; d__[i__] = p; zswap_(n, &z__[i__ * z_dim1 + 1], &c__1, &z__[k * z_dim1 + 1], &c__1); } /* L60: */ } } work[1].r = (doublereal) lwmin, work[1].i = 0.; rwork[1] = (doublereal) lrwmin; iwork[1] = liwmin; return 0; /* End of ZSTEDC */ } /* zstedc_ */ /* Subroutine */ int zsteqr_(char *compz, integer *n, doublereal *d__, doublereal *e, doublecomplex *z__, integer *ldz, doublereal *work, integer *info) { /* System generated locals */ integer z_dim1, z_offset, i__1, i__2; doublereal d__1, d__2; /* Builtin functions */ double sqrt(doublereal), d_sign(doublereal *, doublereal *); /* Local variables */ static doublereal b, c__, f, g; static integer i__, j, k, l, m; static doublereal p, r__, s; static integer l1, ii, mm, lm1, mm1, nm1; static doublereal rt1, rt2, eps; static integer lsv; static doublereal tst, eps2; static integer lend, jtot; extern /* Subroutine */ int dlae2_(doublereal *, doublereal *, doublereal *, doublereal *, doublereal *); extern logical lsame_(char *, char *); static doublereal anorm; extern /* Subroutine */ int zlasr_(char *, char *, char *, integer *, integer *, doublereal *, doublereal *, doublecomplex *, integer *), zswap_(integer *, doublecomplex *, integer *, doublecomplex *, integer *), dlaev2_(doublereal *, doublereal *, doublereal *, doublereal *, doublereal *, doublereal *, doublereal *); static integer lendm1, lendp1; static integer iscale; extern /* Subroutine */ int dlascl_(char *, integer *, integer *, doublereal *, doublereal *, integer *, integer *, doublereal *, integer *, integer *); static doublereal safmin; extern /* Subroutine */ int dlartg_(doublereal *, doublereal *, doublereal *, doublereal *, doublereal *); static doublereal safmax; extern /* Subroutine */ int xerbla_(char *, integer *); extern doublereal dlanst_(char *, integer *, doublereal *, doublereal *); extern /* Subroutine */ int dlasrt_(char *, integer *, doublereal *, integer *); static integer lendsv; static doublereal ssfmin; static integer nmaxit, icompz; static doublereal ssfmax; extern /* Subroutine */ int zlaset_(char *, integer *, integer *, doublecomplex *, doublecomplex *, doublecomplex *, integer *); /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University September 30, 1994 Purpose ======= ZSTEQR computes all eigenvalues and, optionally, eigenvectors of a symmetric tridiagonal matrix using the implicit QL or QR method. The eigenvectors of a full or band complex Hermitian matrix can also be found if ZHETRD or ZHPTRD or ZHBTRD has been used to reduce this matrix to tridiagonal form. Arguments ========= COMPZ (input) CHARACTER*1 = 'N': Compute eigenvalues only. = 'V': Compute eigenvalues and eigenvectors of the original Hermitian matrix. On entry, Z must contain the unitary matrix used to reduce the original matrix to tridiagonal form. = 'I': Compute eigenvalues and eigenvectors of the tridiagonal matrix. Z is initialized to the identity matrix. N (input) INTEGER The order of the matrix. N >= 0. D (input/output) DOUBLE PRECISION array, dimension (N) On entry, the diagonal elements of the tridiagonal matrix. On exit, if INFO = 0, the eigenvalues in ascending order. E (input/output) DOUBLE PRECISION array, dimension (N-1) On entry, the (n-1) subdiagonal elements of the tridiagonal matrix. On exit, E has been destroyed. Z (input/output) COMPLEX*16 array, dimension (LDZ, N) On entry, if COMPZ = 'V', then Z contains the unitary matrix used in the reduction to tridiagonal form. On exit, if INFO = 0, then if COMPZ = 'V', Z contains the orthonormal eigenvectors of the original Hermitian matrix, and if COMPZ = 'I', Z contains the orthonormal eigenvectors of the symmetric tridiagonal matrix. If COMPZ = 'N', then Z is not referenced. LDZ (input) INTEGER The leading dimension of the array Z. LDZ >= 1, and if eigenvectors are desired, then LDZ >= max(1,N). WORK (workspace) DOUBLE PRECISION array, dimension (max(1,2*N-2)) If COMPZ = 'N', then WORK is not referenced. INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value > 0: the algorithm has failed to find all the eigenvalues in a total of 30*N iterations; if INFO = i, then i elements of E have not converged to zero; on exit, D and E contain the elements of a symmetric tridiagonal matrix which is unitarily similar to the original matrix. ===================================================================== Test the input parameters. */ /* Parameter adjustments */ --d__; --e; z_dim1 = *ldz; z_offset = 1 + z_dim1; z__ -= z_offset; --work; /* Function Body */ *info = 0; if (lsame_(compz, "N")) { icompz = 0; } else if (lsame_(compz, "V")) { icompz = 1; } else if (lsame_(compz, "I")) { icompz = 2; } else { icompz = -1; } if (icompz < 0) { *info = -1; } else if (*n < 0) { *info = -2; } else if ((*ldz < 1) || (icompz > 0 && *ldz < max(1,*n))) { *info = -6; } if (*info != 0) { i__1 = -(*info); xerbla_("ZSTEQR", &i__1); return 0; } /* Quick return if possible */ if (*n == 0) { return 0; } if (*n == 1) { if (icompz == 2) { i__1 = z_dim1 + 1; z__[i__1].r = 1., z__[i__1].i = 0.; } return 0; } /* Determine the unit roundoff and over/underflow thresholds. */ eps = EPSILON; /* Computing 2nd power */ d__1 = eps; eps2 = d__1 * d__1; safmin = SAFEMINIMUM; safmax = 1. / safmin; ssfmax = sqrt(safmax) / 3.; ssfmin = sqrt(safmin) / eps2; /* Compute the eigenvalues and eigenvectors of the tridiagonal matrix. */ if (icompz == 2) { zlaset_("Full", n, n, &c_b59, &c_b60, &z__[z_offset], ldz); } nmaxit = *n * 30; jtot = 0; /* Determine where the matrix splits and choose QL or QR iteration for each block, according to whether top or bottom diagonal element is smaller. */ l1 = 1; nm1 = *n - 1; L10: if (l1 > *n) { goto L160; } if (l1 > 1) { e[l1 - 1] = 0.; } if (l1 <= nm1) { i__1 = nm1; for (m = l1; m <= i__1; ++m) { tst = (d__1 = e[m], abs(d__1)); if (tst == 0.) { goto L30; } if (tst <= sqrt((d__1 = d__[m], abs(d__1))) * sqrt((d__2 = d__[m + 1], abs(d__2))) * eps) { e[m] = 0.; goto L30; } /* L20: */ } } m = *n; L30: l = l1; lsv = l; lend = m; lendsv = lend; l1 = m + 1; if (lend == l) { goto L10; } /* Scale submatrix in rows and columns L to LEND */ i__1 = lend - l + 1; anorm = dlanst_("I", &i__1, &d__[l], &e[l]); iscale = 0; if (anorm == 0.) { goto L10; } if (anorm > ssfmax) { iscale = 1; i__1 = lend - l + 1; dlascl_("G", &c__0, &c__0, &anorm, &ssfmax, &i__1, &c__1, &d__[l], n, info); i__1 = lend - l; dlascl_("G", &c__0, &c__0, &anorm, &ssfmax, &i__1, &c__1, &e[l], n, info); } else if (anorm < ssfmin) { iscale = 2; i__1 = lend - l + 1; dlascl_("G", &c__0, &c__0, &anorm, &ssfmin, &i__1, &c__1, &d__[l], n, info); i__1 = lend - l; dlascl_("G", &c__0, &c__0, &anorm, &ssfmin, &i__1, &c__1, &e[l], n, info); } /* Choose between QL and QR iteration */ if ((d__1 = d__[lend], abs(d__1)) < (d__2 = d__[l], abs(d__2))) { lend = lsv; l = lendsv; } if (lend > l) { /* QL Iteration Look for small subdiagonal element. */ L40: if (l != lend) { lendm1 = lend - 1; i__1 = lendm1; for (m = l; m <= i__1; ++m) { /* Computing 2nd power */ d__2 = (d__1 = e[m], abs(d__1)); tst = d__2 * d__2; if (tst <= eps2 * (d__1 = d__[m], abs(d__1)) * (d__2 = d__[m + 1], abs(d__2)) + safmin) { goto L60; } /* L50: */ } } m = lend; L60: if (m < lend) { e[m] = 0.; } p = d__[l]; if (m == l) { goto L80; } /* If remaining matrix is 2-by-2, use DLAE2 or SLAEV2 to compute its eigensystem. */ if (m == l + 1) { if (icompz > 0) { dlaev2_(&d__[l], &e[l], &d__[l + 1], &rt1, &rt2, &c__, &s); work[l] = c__; work[*n - 1 + l] = s; zlasr_("R", "V", "B", n, &c__2, &work[l], &work[*n - 1 + l], & z__[l * z_dim1 + 1], ldz); } else { dlae2_(&d__[l], &e[l], &d__[l + 1], &rt1, &rt2); } d__[l] = rt1; d__[l + 1] = rt2; e[l] = 0.; l += 2; if (l <= lend) { goto L40; } goto L140; } if (jtot == nmaxit) { goto L140; } ++jtot; /* Form shift. */ g = (d__[l + 1] - p) / (e[l] * 2.); r__ = dlapy2_(&g, &c_b1015); g = d__[m] - p + e[l] / (g + d_sign(&r__, &g)); s = 1.; c__ = 1.; p = 0.; /* Inner loop */ mm1 = m - 1; i__1 = l; for (i__ = mm1; i__ >= i__1; --i__) { f = s * e[i__]; b = c__ * e[i__]; dlartg_(&g, &f, &c__, &s, &r__); if (i__ != m - 1) { e[i__ + 1] = r__; } g = d__[i__ + 1] - p; r__ = (d__[i__] - g) * s + c__ * 2. * b; p = s * r__; d__[i__ + 1] = g + p; g = c__ * r__ - b; /* If eigenvectors are desired, then save rotations. */ if (icompz > 0) { work[i__] = c__; work[*n - 1 + i__] = -s; } /* L70: */ } /* If eigenvectors are desired, then apply saved rotations. */ if (icompz > 0) { mm = m - l + 1; zlasr_("R", "V", "B", n, &mm, &work[l], &work[*n - 1 + l], &z__[l * z_dim1 + 1], ldz); } d__[l] -= p; e[l] = g; goto L40; /* Eigenvalue found. */ L80: d__[l] = p; ++l; if (l <= lend) { goto L40; } goto L140; } else { /* QR Iteration Look for small superdiagonal element. */ L90: if (l != lend) { lendp1 = lend + 1; i__1 = lendp1; for (m = l; m >= i__1; --m) { /* Computing 2nd power */ d__2 = (d__1 = e[m - 1], abs(d__1)); tst = d__2 * d__2; if (tst <= eps2 * (d__1 = d__[m], abs(d__1)) * (d__2 = d__[m - 1], abs(d__2)) + safmin) { goto L110; } /* L100: */ } } m = lend; L110: if (m > lend) { e[m - 1] = 0.; } p = d__[l]; if (m == l) { goto L130; } /* If remaining matrix is 2-by-2, use DLAE2 or SLAEV2 to compute its eigensystem. */ if (m == l - 1) { if (icompz > 0) { dlaev2_(&d__[l - 1], &e[l - 1], &d__[l], &rt1, &rt2, &c__, &s) ; work[m] = c__; work[*n - 1 + m] = s; zlasr_("R", "V", "F", n, &c__2, &work[m], &work[*n - 1 + m], & z__[(l - 1) * z_dim1 + 1], ldz); } else { dlae2_(&d__[l - 1], &e[l - 1], &d__[l], &rt1, &rt2); } d__[l - 1] = rt1; d__[l] = rt2; e[l - 1] = 0.; l += -2; if (l >= lend) { goto L90; } goto L140; } if (jtot == nmaxit) { goto L140; } ++jtot; /* Form shift. */ g = (d__[l - 1] - p) / (e[l - 1] * 2.); r__ = dlapy2_(&g, &c_b1015); g = d__[m] - p + e[l - 1] / (g + d_sign(&r__, &g)); s = 1.; c__ = 1.; p = 0.; /* Inner loop */ lm1 = l - 1; i__1 = lm1; for (i__ = m; i__ <= i__1; ++i__) { f = s * e[i__]; b = c__ * e[i__]; dlartg_(&g, &f, &c__, &s, &r__); if (i__ != m) { e[i__ - 1] = r__; } g = d__[i__] - p; r__ = (d__[i__ + 1] - g) * s + c__ * 2. * b; p = s * r__; d__[i__] = g + p; g = c__ * r__ - b; /* If eigenvectors are desired, then save rotations. */ if (icompz > 0) { work[i__] = c__; work[*n - 1 + i__] = s; } /* L120: */ } /* If eigenvectors are desired, then apply saved rotations. */ if (icompz > 0) { mm = l - m + 1; zlasr_("R", "V", "F", n, &mm, &work[m], &work[*n - 1 + m], &z__[m * z_dim1 + 1], ldz); } d__[l] -= p; e[lm1] = g; goto L90; /* Eigenvalue found. */ L130: d__[l] = p; --l; if (l >= lend) { goto L90; } goto L140; } /* Undo scaling if necessary */ L140: if (iscale == 1) { i__1 = lendsv - lsv + 1; dlascl_("G", &c__0, &c__0, &ssfmax, &anorm, &i__1, &c__1, &d__[lsv], n, info); i__1 = lendsv - lsv; dlascl_("G", &c__0, &c__0, &ssfmax, &anorm, &i__1, &c__1, &e[lsv], n, info); } else if (iscale == 2) { i__1 = lendsv - lsv + 1; dlascl_("G", &c__0, &c__0, &ssfmin, &anorm, &i__1, &c__1, &d__[lsv], n, info); i__1 = lendsv - lsv; dlascl_("G", &c__0, &c__0, &ssfmin, &anorm, &i__1, &c__1, &e[lsv], n, info); } /* Check for no convergence to an eigenvalue after a total of N*MAXIT iterations. */ if (jtot == nmaxit) { i__1 = *n - 1; for (i__ = 1; i__ <= i__1; ++i__) { if (e[i__] != 0.) { ++(*info); } /* L150: */ } return 0; } goto L10; /* Order eigenvalues and eigenvectors. */ L160: if (icompz == 0) { /* Use Quick Sort */ dlasrt_("I", n, &d__[1], info); } else { /* Use Selection Sort to minimize swaps of eigenvectors */ i__1 = *n; for (ii = 2; ii <= i__1; ++ii) { i__ = ii - 1; k = i__; p = d__[i__]; i__2 = *n; for (j = ii; j <= i__2; ++j) { if (d__[j] < p) { k = j; p = d__[j]; } /* L170: */ } if (k != i__) { d__[k] = d__[i__]; d__[i__] = p; zswap_(n, &z__[i__ * z_dim1 + 1], &c__1, &z__[k * z_dim1 + 1], &c__1); } /* L180: */ } } return 0; /* End of ZSTEQR */ } /* zsteqr_ */ /* Subroutine */ int ztrevc_(char *side, char *howmny, logical *select, integer *n, doublecomplex *t, integer *ldt, doublecomplex *vl, integer *ldvl, doublecomplex *vr, integer *ldvr, integer *mm, integer *m, doublecomplex *work, doublereal *rwork, integer *info) { /* System generated locals */ integer t_dim1, t_offset, vl_dim1, vl_offset, vr_dim1, vr_offset, i__1, i__2, i__3, i__4, i__5; doublereal d__1, d__2, d__3; doublecomplex z__1, z__2; /* Builtin functions */ double d_imag(doublecomplex *); void d_cnjg(doublecomplex *, doublecomplex *); /* Local variables */ static integer i__, j, k, ii, ki, is; static doublereal ulp; static logical allv; static doublereal unfl, ovfl, smin; static logical over; static doublereal scale; extern logical lsame_(char *, char *); static doublereal remax; static logical leftv, bothv; extern /* Subroutine */ int zgemv_(char *, integer *, integer *, doublecomplex *, doublecomplex *, integer *, doublecomplex *, integer *, doublecomplex *, doublecomplex *, integer *); static logical somev; extern /* Subroutine */ int zcopy_(integer *, doublecomplex *, integer *, doublecomplex *, integer *), dlabad_(doublereal *, doublereal *); extern /* Subroutine */ int xerbla_(char *, integer *), zdscal_( integer *, doublereal *, doublecomplex *, integer *); extern integer izamax_(integer *, doublecomplex *, integer *); static logical rightv; extern doublereal dzasum_(integer *, doublecomplex *, integer *); static doublereal smlnum; extern /* Subroutine */ int zlatrs_(char *, char *, char *, char *, integer *, doublecomplex *, integer *, doublecomplex *, doublereal *, doublereal *, integer *); /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= ZTREVC computes some or all of the right and/or left eigenvectors of a complex upper triangular matrix T. The right eigenvector x and the left eigenvector y of T corresponding to an eigenvalue w are defined by: T*x = w*x, y'*T = w*y' where y' denotes the conjugate transpose of the vector y. If all eigenvectors are requested, the routine may either return the matrices X and/or Y of right or left eigenvectors of T, or the products Q*X and/or Q*Y, where Q is an input unitary matrix. If T was obtained from the Schur factorization of an original matrix A = Q*T*Q', then Q*X and Q*Y are the matrices of right or left eigenvectors of A. Arguments ========= SIDE (input) CHARACTER*1 = 'R': compute right eigenvectors only; = 'L': compute left eigenvectors only; = 'B': compute both right and left eigenvectors. HOWMNY (input) CHARACTER*1 = 'A': compute all right and/or left eigenvectors; = 'B': compute all right and/or left eigenvectors, and backtransform them using the input matrices supplied in VR and/or VL; = 'S': compute selected right and/or left eigenvectors, specified by the logical array SELECT. SELECT (input) LOGICAL array, dimension (N) If HOWMNY = 'S', SELECT specifies the eigenvectors to be computed. If HOWMNY = 'A' or 'B', SELECT is not referenced. To select the eigenvector corresponding to the j-th eigenvalue, SELECT(j) must be set to .TRUE.. N (input) INTEGER The order of the matrix T. N >= 0. T (input/output) COMPLEX*16 array, dimension (LDT,N) The upper triangular matrix T. T is modified, but restored on exit. LDT (input) INTEGER The leading dimension of the array T. LDT >= max(1,N). VL (input/output) COMPLEX*16 array, dimension (LDVL,MM) On entry, if SIDE = 'L' or 'B' and HOWMNY = 'B', VL must contain an N-by-N matrix Q (usually the unitary matrix Q of Schur vectors returned by ZHSEQR). On exit, if SIDE = 'L' or 'B', VL contains: if HOWMNY = 'A', the matrix Y of left eigenvectors of T; VL is lower triangular. The i-th column VL(i) of VL is the eigenvector corresponding to T(i,i). if HOWMNY = 'B', the matrix Q*Y; if HOWMNY = 'S', the left eigenvectors of T specified by SELECT, stored consecutively in the columns of VL, in the same order as their eigenvalues. If SIDE = 'R', VL is not referenced. LDVL (input) INTEGER The leading dimension of the array VL. LDVL >= max(1,N) if SIDE = 'L' or 'B'; LDVL >= 1 otherwise. VR (input/output) COMPLEX*16 array, dimension (LDVR,MM) On entry, if SIDE = 'R' or 'B' and HOWMNY = 'B', VR must contain an N-by-N matrix Q (usually the unitary matrix Q of Schur vectors returned by ZHSEQR). On exit, if SIDE = 'R' or 'B', VR contains: if HOWMNY = 'A', the matrix X of right eigenvectors of T; VR is upper triangular. The i-th column VR(i) of VR is the eigenvector corresponding to T(i,i). if HOWMNY = 'B', the matrix Q*X; if HOWMNY = 'S', the right eigenvectors of T specified by SELECT, stored consecutively in the columns of VR, in the same order as their eigenvalues. If SIDE = 'L', VR is not referenced. LDVR (input) INTEGER The leading dimension of the array VR. LDVR >= max(1,N) if SIDE = 'R' or 'B'; LDVR >= 1 otherwise. MM (input) INTEGER The number of columns in the arrays VL and/or VR. MM >= M. M (output) INTEGER The number of columns in the arrays VL and/or VR actually used to store the eigenvectors. If HOWMNY = 'A' or 'B', M is set to N. Each selected eigenvector occupies one column. WORK (workspace) COMPLEX*16 array, dimension (2*N) RWORK (workspace) DOUBLE PRECISION array, dimension (N) INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value Further Details =============== The algorithm used in this program is basically backward (forward) substitution, with scaling to make the the code robust against possible overflow. Each eigenvector is normalized so that the element of largest magnitude has magnitude 1; here the magnitude of a complex number (x,y) is taken to be |x| + |y|. ===================================================================== Decode and test the input parameters */ /* Parameter adjustments */ --select; t_dim1 = *ldt; t_offset = 1 + t_dim1; t -= t_offset; vl_dim1 = *ldvl; vl_offset = 1 + vl_dim1; vl -= vl_offset; vr_dim1 = *ldvr; vr_offset = 1 + vr_dim1; vr -= vr_offset; --work; --rwork; /* Function Body */ bothv = lsame_(side, "B"); rightv = (lsame_(side, "R")) || (bothv); leftv = (lsame_(side, "L")) || (bothv); allv = lsame_(howmny, "A"); over = lsame_(howmny, "B"); somev = lsame_(howmny, "S"); /* Set M to the number of columns required to store the selected eigenvectors. */ if (somev) { *m = 0; i__1 = *n; for (j = 1; j <= i__1; ++j) { if (select[j]) { ++(*m); } /* L10: */ } } else { *m = *n; } *info = 0; if (! rightv && ! leftv) { *info = -1; } else if (! allv && ! over && ! somev) { *info = -2; } else if (*n < 0) { *info = -4; } else if (*ldt < max(1,*n)) { *info = -6; } else if ((*ldvl < 1) || (leftv && *ldvl < *n)) { *info = -8; } else if ((*ldvr < 1) || (rightv && *ldvr < *n)) { *info = -10; } else if (*mm < *m) { *info = -11; } if (*info != 0) { i__1 = -(*info); xerbla_("ZTREVC", &i__1); return 0; } /* Quick return if possible. */ if (*n == 0) { return 0; } /* Set the constants to control overflow. */ unfl = SAFEMINIMUM; ovfl = 1. / unfl; dlabad_(&unfl, &ovfl); ulp = PRECISION; smlnum = unfl * (*n / ulp); /* Store the diagonal elements of T in working array WORK. */ i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = i__ + *n; i__3 = i__ + i__ * t_dim1; work[i__2].r = t[i__3].r, work[i__2].i = t[i__3].i; /* L20: */ } /* Compute 1-norm of each column of strictly upper triangular part of T to control overflow in triangular solver. */ rwork[1] = 0.; i__1 = *n; for (j = 2; j <= i__1; ++j) { i__2 = j - 1; rwork[j] = dzasum_(&i__2, &t[j * t_dim1 + 1], &c__1); /* L30: */ } if (rightv) { /* Compute right eigenvectors. */ is = *m; for (ki = *n; ki >= 1; --ki) { if (somev) { if (! select[ki]) { goto L80; } } /* Computing MAX */ i__1 = ki + ki * t_dim1; d__3 = ulp * ((d__1 = t[i__1].r, abs(d__1)) + (d__2 = d_imag(&t[ ki + ki * t_dim1]), abs(d__2))); smin = max(d__3,smlnum); work[1].r = 1., work[1].i = 0.; /* Form right-hand side. */ i__1 = ki - 1; for (k = 1; k <= i__1; ++k) { i__2 = k; i__3 = k + ki * t_dim1; z__1.r = -t[i__3].r, z__1.i = -t[i__3].i; work[i__2].r = z__1.r, work[i__2].i = z__1.i; /* L40: */ } /* Solve the triangular system: (T(1:KI-1,1:KI-1) - T(KI,KI))*X = SCALE*WORK. */ i__1 = ki - 1; for (k = 1; k <= i__1; ++k) { i__2 = k + k * t_dim1; i__3 = k + k * t_dim1; i__4 = ki + ki * t_dim1; z__1.r = t[i__3].r - t[i__4].r, z__1.i = t[i__3].i - t[i__4] .i; t[i__2].r = z__1.r, t[i__2].i = z__1.i; i__2 = k + k * t_dim1; if ((d__1 = t[i__2].r, abs(d__1)) + (d__2 = d_imag(&t[k + k * t_dim1]), abs(d__2)) < smin) { i__3 = k + k * t_dim1; t[i__3].r = smin, t[i__3].i = 0.; } /* L50: */ } if (ki > 1) { i__1 = ki - 1; zlatrs_("Upper", "No transpose", "Non-unit", "Y", &i__1, &t[ t_offset], ldt, &work[1], &scale, &rwork[1], info); i__1 = ki; work[i__1].r = scale, work[i__1].i = 0.; } /* Copy the vector x or Q*x to VR and normalize. */ if (! over) { zcopy_(&ki, &work[1], &c__1, &vr[is * vr_dim1 + 1], &c__1); ii = izamax_(&ki, &vr[is * vr_dim1 + 1], &c__1); i__1 = ii + is * vr_dim1; remax = 1. / ((d__1 = vr[i__1].r, abs(d__1)) + (d__2 = d_imag( &vr[ii + is * vr_dim1]), abs(d__2))); zdscal_(&ki, &remax, &vr[is * vr_dim1 + 1], &c__1); i__1 = *n; for (k = ki + 1; k <= i__1; ++k) { i__2 = k + is * vr_dim1; vr[i__2].r = 0., vr[i__2].i = 0.; /* L60: */ } } else { if (ki > 1) { i__1 = ki - 1; z__1.r = scale, z__1.i = 0.; zgemv_("N", n, &i__1, &c_b60, &vr[vr_offset], ldvr, &work[ 1], &c__1, &z__1, &vr[ki * vr_dim1 + 1], &c__1); } ii = izamax_(n, &vr[ki * vr_dim1 + 1], &c__1); i__1 = ii + ki * vr_dim1; remax = 1. / ((d__1 = vr[i__1].r, abs(d__1)) + (d__2 = d_imag( &vr[ii + ki * vr_dim1]), abs(d__2))); zdscal_(n, &remax, &vr[ki * vr_dim1 + 1], &c__1); } /* Set back the original diagonal elements of T. */ i__1 = ki - 1; for (k = 1; k <= i__1; ++k) { i__2 = k + k * t_dim1; i__3 = k + *n; t[i__2].r = work[i__3].r, t[i__2].i = work[i__3].i; /* L70: */ } --is; L80: ; } } if (leftv) { /* Compute left eigenvectors. */ is = 1; i__1 = *n; for (ki = 1; ki <= i__1; ++ki) { if (somev) { if (! select[ki]) { goto L130; } } /* Computing MAX */ i__2 = ki + ki * t_dim1; d__3 = ulp * ((d__1 = t[i__2].r, abs(d__1)) + (d__2 = d_imag(&t[ ki + ki * t_dim1]), abs(d__2))); smin = max(d__3,smlnum); i__2 = *n; work[i__2].r = 1., work[i__2].i = 0.; /* Form right-hand side. */ i__2 = *n; for (k = ki + 1; k <= i__2; ++k) { i__3 = k; d_cnjg(&z__2, &t[ki + k * t_dim1]); z__1.r = -z__2.r, z__1.i = -z__2.i; work[i__3].r = z__1.r, work[i__3].i = z__1.i; /* L90: */ } /* Solve the triangular system: (T(KI+1:N,KI+1:N) - T(KI,KI))'*X = SCALE*WORK. */ i__2 = *n; for (k = ki + 1; k <= i__2; ++k) { i__3 = k + k * t_dim1; i__4 = k + k * t_dim1; i__5 = ki + ki * t_dim1; z__1.r = t[i__4].r - t[i__5].r, z__1.i = t[i__4].i - t[i__5] .i; t[i__3].r = z__1.r, t[i__3].i = z__1.i; i__3 = k + k * t_dim1; if ((d__1 = t[i__3].r, abs(d__1)) + (d__2 = d_imag(&t[k + k * t_dim1]), abs(d__2)) < smin) { i__4 = k + k * t_dim1; t[i__4].r = smin, t[i__4].i = 0.; } /* L100: */ } if (ki < *n) { i__2 = *n - ki; zlatrs_("Upper", "Conjugate transpose", "Non-unit", "Y", & i__2, &t[ki + 1 + (ki + 1) * t_dim1], ldt, &work[ki + 1], &scale, &rwork[1], info); i__2 = ki; work[i__2].r = scale, work[i__2].i = 0.; } /* Copy the vector x or Q*x to VL and normalize. */ if (! over) { i__2 = *n - ki + 1; zcopy_(&i__2, &work[ki], &c__1, &vl[ki + is * vl_dim1], &c__1) ; i__2 = *n - ki + 1; ii = izamax_(&i__2, &vl[ki + is * vl_dim1], &c__1) + ki - 1; i__2 = ii + is * vl_dim1; remax = 1. / ((d__1 = vl[i__2].r, abs(d__1)) + (d__2 = d_imag( &vl[ii + is * vl_dim1]), abs(d__2))); i__2 = *n - ki + 1; zdscal_(&i__2, &remax, &vl[ki + is * vl_dim1], &c__1); i__2 = ki - 1; for (k = 1; k <= i__2; ++k) { i__3 = k + is * vl_dim1; vl[i__3].r = 0., vl[i__3].i = 0.; /* L110: */ } } else { if (ki < *n) { i__2 = *n - ki; z__1.r = scale, z__1.i = 0.; zgemv_("N", n, &i__2, &c_b60, &vl[(ki + 1) * vl_dim1 + 1], ldvl, &work[ki + 1], &c__1, &z__1, &vl[ki * vl_dim1 + 1], &c__1); } ii = izamax_(n, &vl[ki * vl_dim1 + 1], &c__1); i__2 = ii + ki * vl_dim1; remax = 1. / ((d__1 = vl[i__2].r, abs(d__1)) + (d__2 = d_imag( &vl[ii + ki * vl_dim1]), abs(d__2))); zdscal_(n, &remax, &vl[ki * vl_dim1 + 1], &c__1); } /* Set back the original diagonal elements of T. */ i__2 = *n; for (k = ki + 1; k <= i__2; ++k) { i__3 = k + k * t_dim1; i__4 = k + *n; t[i__3].r = work[i__4].r, t[i__3].i = work[i__4].i; /* L120: */ } ++is; L130: ; } } return 0; /* End of ZTREVC */ } /* ztrevc_ */ /* Subroutine */ int ztrti2_(char *uplo, char *diag, integer *n, doublecomplex *a, integer *lda, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2; doublecomplex z__1; /* Builtin functions */ void z_div(doublecomplex *, doublecomplex *, doublecomplex *); /* Local variables */ static integer j; static doublecomplex ajj; extern logical lsame_(char *, char *); extern /* Subroutine */ int zscal_(integer *, doublecomplex *, doublecomplex *, integer *); static logical upper; extern /* Subroutine */ int ztrmv_(char *, char *, char *, integer *, doublecomplex *, integer *, doublecomplex *, integer *), xerbla_(char *, integer *); static logical nounit; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University September 30, 1994 Purpose ======= ZTRTI2 computes the inverse of a complex upper or lower triangular matrix. This is the Level 2 BLAS version of the algorithm. Arguments ========= UPLO (input) CHARACTER*1 Specifies whether the matrix A is upper or lower triangular. = 'U': Upper triangular = 'L': Lower triangular DIAG (input) CHARACTER*1 Specifies whether or not the matrix A is unit triangular. = 'N': Non-unit triangular = 'U': Unit triangular N (input) INTEGER The order of the matrix A. N >= 0. A (input/output) COMPLEX*16 array, dimension (LDA,N) On entry, the triangular matrix A. If UPLO = 'U', the leading n by n upper triangular part of the array A contains the upper triangular matrix, and the strictly lower triangular part of A is not referenced. If UPLO = 'L', the leading n by n lower triangular part of the array A contains the lower triangular matrix, and the strictly upper triangular part of A is not referenced. If DIAG = 'U', the diagonal elements of A are also not referenced and are assumed to be 1. On exit, the (triangular) inverse of the original matrix, in the same storage format. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,N). INFO (output) INTEGER = 0: successful exit < 0: if INFO = -k, the k-th argument had an illegal value ===================================================================== Test the input parameters. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; /* Function Body */ *info = 0; upper = lsame_(uplo, "U"); nounit = lsame_(diag, "N"); if (! upper && ! lsame_(uplo, "L")) { *info = -1; } else if (! nounit && ! lsame_(diag, "U")) { *info = -2; } else if (*n < 0) { *info = -3; } else if (*lda < max(1,*n)) { *info = -5; } if (*info != 0) { i__1 = -(*info); xerbla_("ZTRTI2", &i__1); return 0; } if (upper) { /* Compute inverse of upper triangular matrix. */ i__1 = *n; for (j = 1; j <= i__1; ++j) { if (nounit) { i__2 = j + j * a_dim1; z_div(&z__1, &c_b60, &a[j + j * a_dim1]); a[i__2].r = z__1.r, a[i__2].i = z__1.i; i__2 = j + j * a_dim1; z__1.r = -a[i__2].r, z__1.i = -a[i__2].i; ajj.r = z__1.r, ajj.i = z__1.i; } else { z__1.r = -1., z__1.i = -0.; ajj.r = z__1.r, ajj.i = z__1.i; } /* Compute elements 1:j-1 of j-th column. */ i__2 = j - 1; ztrmv_("Upper", "No transpose", diag, &i__2, &a[a_offset], lda, & a[j * a_dim1 + 1], &c__1); i__2 = j - 1; zscal_(&i__2, &ajj, &a[j * a_dim1 + 1], &c__1); /* L10: */ } } else { /* Compute inverse of lower triangular matrix. */ for (j = *n; j >= 1; --j) { if (nounit) { i__1 = j + j * a_dim1; z_div(&z__1, &c_b60, &a[j + j * a_dim1]); a[i__1].r = z__1.r, a[i__1].i = z__1.i; i__1 = j + j * a_dim1; z__1.r = -a[i__1].r, z__1.i = -a[i__1].i; ajj.r = z__1.r, ajj.i = z__1.i; } else { z__1.r = -1., z__1.i = -0.; ajj.r = z__1.r, ajj.i = z__1.i; } if (j < *n) { /* Compute elements j+1:n of j-th column. */ i__1 = *n - j; ztrmv_("Lower", "No transpose", diag, &i__1, &a[j + 1 + (j + 1) * a_dim1], lda, &a[j + 1 + j * a_dim1], &c__1); i__1 = *n - j; zscal_(&i__1, &ajj, &a[j + 1 + j * a_dim1], &c__1); } /* L20: */ } } return 0; /* End of ZTRTI2 */ } /* ztrti2_ */ /* Subroutine */ int ztrtri_(char *uplo, char *diag, integer *n, doublecomplex *a, integer *lda, integer *info) { /* System generated locals */ address a__1[2]; integer a_dim1, a_offset, i__1, i__2, i__3[2], i__4, i__5; doublecomplex z__1; char ch__1[2]; /* Builtin functions */ /* Subroutine */ int s_cat(char *, char **, integer *, integer *, ftnlen); /* Local variables */ static integer j, jb, nb, nn; extern logical lsame_(char *, char *); static logical upper; extern /* Subroutine */ int ztrmm_(char *, char *, char *, char *, integer *, integer *, doublecomplex *, doublecomplex *, integer *, doublecomplex *, integer *), ztrsm_(char *, char *, char *, char *, integer *, integer *, doublecomplex *, doublecomplex *, integer *, doublecomplex *, integer *), ztrti2_(char *, char * , integer *, doublecomplex *, integer *, integer *), xerbla_(char *, integer *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); static logical nounit; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University September 30, 1994 Purpose ======= ZTRTRI computes the inverse of a complex upper or lower triangular matrix A. This is the Level 3 BLAS version of the algorithm. Arguments ========= UPLO (input) CHARACTER*1 = 'U': A is upper triangular; = 'L': A is lower triangular. DIAG (input) CHARACTER*1 = 'N': A is non-unit triangular; = 'U': A is unit triangular. N (input) INTEGER The order of the matrix A. N >= 0. A (input/output) COMPLEX*16 array, dimension (LDA,N) On entry, the triangular matrix A. If UPLO = 'U', the leading N-by-N upper triangular part of the array A contains the upper triangular matrix, and the strictly lower triangular part of A is not referenced. If UPLO = 'L', the leading N-by-N lower triangular part of the array A contains the lower triangular matrix, and the strictly upper triangular part of A is not referenced. If DIAG = 'U', the diagonal elements of A are also not referenced and are assumed to be 1. On exit, the (triangular) inverse of the original matrix, in the same storage format. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,N). INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value > 0: if INFO = i, A(i,i) is exactly zero. The triangular matrix is singular and its inverse can not be computed. ===================================================================== Test the input parameters. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; /* Function Body */ *info = 0; upper = lsame_(uplo, "U"); nounit = lsame_(diag, "N"); if (! upper && ! lsame_(uplo, "L")) { *info = -1; } else if (! nounit && ! lsame_(diag, "U")) { *info = -2; } else if (*n < 0) { *info = -3; } else if (*lda < max(1,*n)) { *info = -5; } if (*info != 0) { i__1 = -(*info); xerbla_("ZTRTRI", &i__1); return 0; } /* Quick return if possible */ if (*n == 0) { return 0; } /* Check for singularity if non-unit. */ if (nounit) { i__1 = *n; for (*info = 1; *info <= i__1; ++(*info)) { i__2 = *info + *info * a_dim1; if (a[i__2].r == 0. && a[i__2].i == 0.) { return 0; } /* L10: */ } *info = 0; } /* Determine the block size for this environment. Writing concatenation */ i__3[0] = 1, a__1[0] = uplo; i__3[1] = 1, a__1[1] = diag; s_cat(ch__1, a__1, i__3, &c__2, (ftnlen)2); nb = ilaenv_(&c__1, "ZTRTRI", ch__1, n, &c_n1, &c_n1, &c_n1, (ftnlen)6, ( ftnlen)2); if ((nb <= 1) || (nb >= *n)) { /* Use unblocked code */ ztrti2_(uplo, diag, n, &a[a_offset], lda, info); } else { /* Use blocked code */ if (upper) { /* Compute inverse of upper triangular matrix */ i__1 = *n; i__2 = nb; for (j = 1; i__2 < 0 ? j >= i__1 : j <= i__1; j += i__2) { /* Computing MIN */ i__4 = nb, i__5 = *n - j + 1; jb = min(i__4,i__5); /* Compute rows 1:j-1 of current block column */ i__4 = j - 1; ztrmm_("Left", "Upper", "No transpose", diag, &i__4, &jb, & c_b60, &a[a_offset], lda, &a[j * a_dim1 + 1], lda); i__4 = j - 1; z__1.r = -1., z__1.i = -0.; ztrsm_("Right", "Upper", "No transpose", diag, &i__4, &jb, & z__1, &a[j + j * a_dim1], lda, &a[j * a_dim1 + 1], lda); /* Compute inverse of current diagonal block */ ztrti2_("Upper", diag, &jb, &a[j + j * a_dim1], lda, info); /* L20: */ } } else { /* Compute inverse of lower triangular matrix */ nn = (*n - 1) / nb * nb + 1; i__2 = -nb; for (j = nn; i__2 < 0 ? j >= 1 : j <= 1; j += i__2) { /* Computing MIN */ i__1 = nb, i__4 = *n - j + 1; jb = min(i__1,i__4); if (j + jb <= *n) { /* Compute rows j+jb:n of current block column */ i__1 = *n - j - jb + 1; ztrmm_("Left", "Lower", "No transpose", diag, &i__1, &jb, &c_b60, &a[j + jb + (j + jb) * a_dim1], lda, &a[j + jb + j * a_dim1], lda); i__1 = *n - j - jb + 1; z__1.r = -1., z__1.i = -0.; ztrsm_("Right", "Lower", "No transpose", diag, &i__1, &jb, &z__1, &a[j + j * a_dim1], lda, &a[j + jb + j * a_dim1], lda); } /* Compute inverse of current diagonal block */ ztrti2_("Lower", diag, &jb, &a[j + j * a_dim1], lda, info); /* L30: */ } } } return 0; /* End of ZTRTRI */ } /* ztrtri_ */ /* Subroutine */ int zung2r_(integer *m, integer *n, integer *k, doublecomplex *a, integer *lda, doublecomplex *tau, doublecomplex * work, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3; doublecomplex z__1; /* Local variables */ static integer i__, j, l; extern /* Subroutine */ int zscal_(integer *, doublecomplex *, doublecomplex *, integer *), zlarf_(char *, integer *, integer *, doublecomplex *, integer *, doublecomplex *, doublecomplex *, integer *, doublecomplex *), xerbla_(char *, integer *); /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University September 30, 1994 Purpose ======= ZUNG2R generates an m by n complex matrix Q with orthonormal columns, which is defined as the first n columns of a product of k elementary reflectors of order m Q = H(1) H(2) . . . H(k) as returned by ZGEQRF. Arguments ========= M (input) INTEGER The number of rows of the matrix Q. M >= 0. N (input) INTEGER The number of columns of the matrix Q. M >= N >= 0. K (input) INTEGER The number of elementary reflectors whose product defines the matrix Q. N >= K >= 0. A (input/output) COMPLEX*16 array, dimension (LDA,N) On entry, the i-th column must contain the vector which defines the elementary reflector H(i), for i = 1,2,...,k, as returned by ZGEQRF in the first k columns of its array argument A. On exit, the m by n matrix Q. LDA (input) INTEGER The first dimension of the array A. LDA >= max(1,M). TAU (input) COMPLEX*16 array, dimension (K) TAU(i) must contain the scalar factor of the elementary reflector H(i), as returned by ZGEQRF. WORK (workspace) COMPLEX*16 array, dimension (N) INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument has an illegal value ===================================================================== Test the input arguments */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --tau; --work; /* Function Body */ *info = 0; if (*m < 0) { *info = -1; } else if ((*n < 0) || (*n > *m)) { *info = -2; } else if ((*k < 0) || (*k > *n)) { *info = -3; } else if (*lda < max(1,*m)) { *info = -5; } if (*info != 0) { i__1 = -(*info); xerbla_("ZUNG2R", &i__1); return 0; } /* Quick return if possible */ if (*n <= 0) { return 0; } /* Initialise columns k+1:n to columns of the unit matrix */ i__1 = *n; for (j = *k + 1; j <= i__1; ++j) { i__2 = *m; for (l = 1; l <= i__2; ++l) { i__3 = l + j * a_dim1; a[i__3].r = 0., a[i__3].i = 0.; /* L10: */ } i__2 = j + j * a_dim1; a[i__2].r = 1., a[i__2].i = 0.; /* L20: */ } for (i__ = *k; i__ >= 1; --i__) { /* Apply H(i) to A(i:m,i:n) from the left */ if (i__ < *n) { i__1 = i__ + i__ * a_dim1; a[i__1].r = 1., a[i__1].i = 0.; i__1 = *m - i__ + 1; i__2 = *n - i__; zlarf_("Left", &i__1, &i__2, &a[i__ + i__ * a_dim1], &c__1, &tau[ i__], &a[i__ + (i__ + 1) * a_dim1], lda, &work[1]); } if (i__ < *m) { i__1 = *m - i__; i__2 = i__; z__1.r = -tau[i__2].r, z__1.i = -tau[i__2].i; zscal_(&i__1, &z__1, &a[i__ + 1 + i__ * a_dim1], &c__1); } i__1 = i__ + i__ * a_dim1; i__2 = i__; z__1.r = 1. - tau[i__2].r, z__1.i = 0. - tau[i__2].i; a[i__1].r = z__1.r, a[i__1].i = z__1.i; /* Set A(1:i-1,i) to zero */ i__1 = i__ - 1; for (l = 1; l <= i__1; ++l) { i__2 = l + i__ * a_dim1; a[i__2].r = 0., a[i__2].i = 0.; /* L30: */ } /* L40: */ } return 0; /* End of ZUNG2R */ } /* zung2r_ */ /* Subroutine */ int zungbr_(char *vect, integer *m, integer *n, integer *k, doublecomplex *a, integer *lda, doublecomplex *tau, doublecomplex * work, integer *lwork, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3; /* Local variables */ static integer i__, j, nb, mn; extern logical lsame_(char *, char *); static integer iinfo; static logical wantq; extern /* Subroutine */ int xerbla_(char *, integer *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); static integer lwkopt; static logical lquery; extern /* Subroutine */ int zunglq_(integer *, integer *, integer *, doublecomplex *, integer *, doublecomplex *, doublecomplex *, integer *, integer *), zungqr_(integer *, integer *, integer *, doublecomplex *, integer *, doublecomplex *, doublecomplex *, integer *, integer *); /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= ZUNGBR generates one of the complex unitary matrices Q or P**H determined by ZGEBRD when reducing a complex matrix A to bidiagonal form: A = Q * B * P**H. Q and P**H are defined as products of elementary reflectors H(i) or G(i) respectively. If VECT = 'Q', A is assumed to have been an M-by-K matrix, and Q is of order M: if m >= k, Q = H(1) H(2) . . . H(k) and ZUNGBR returns the first n columns of Q, where m >= n >= k; if m < k, Q = H(1) H(2) . . . H(m-1) and ZUNGBR returns Q as an M-by-M matrix. If VECT = 'P', A is assumed to have been a K-by-N matrix, and P**H is of order N: if k < n, P**H = G(k) . . . G(2) G(1) and ZUNGBR returns the first m rows of P**H, where n >= m >= k; if k >= n, P**H = G(n-1) . . . G(2) G(1) and ZUNGBR returns P**H as an N-by-N matrix. Arguments ========= VECT (input) CHARACTER*1 Specifies whether the matrix Q or the matrix P**H is required, as defined in the transformation applied by ZGEBRD: = 'Q': generate Q; = 'P': generate P**H. M (input) INTEGER The number of rows of the matrix Q or P**H to be returned. M >= 0. N (input) INTEGER The number of columns of the matrix Q or P**H to be returned. N >= 0. If VECT = 'Q', M >= N >= min(M,K); if VECT = 'P', N >= M >= min(N,K). K (input) INTEGER If VECT = 'Q', the number of columns in the original M-by-K matrix reduced by ZGEBRD. If VECT = 'P', the number of rows in the original K-by-N matrix reduced by ZGEBRD. K >= 0. A (input/output) COMPLEX*16 array, dimension (LDA,N) On entry, the vectors which define the elementary reflectors, as returned by ZGEBRD. On exit, the M-by-N matrix Q or P**H. LDA (input) INTEGER The leading dimension of the array A. LDA >= M. TAU (input) COMPLEX*16 array, dimension (min(M,K)) if VECT = 'Q' (min(N,K)) if VECT = 'P' TAU(i) must contain the scalar factor of the elementary reflector H(i) or G(i), which determines Q or P**H, as returned by ZGEBRD in its array argument TAUQ or TAUP. WORK (workspace/output) COMPLEX*16 array, dimension (LWORK) On exit, if INFO = 0, WORK(1) returns the optimal LWORK. LWORK (input) INTEGER The dimension of the array WORK. LWORK >= max(1,min(M,N)). For optimum performance LWORK >= min(M,N)*NB, where NB is the optimal blocksize. If LWORK = -1, then a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued by XERBLA. INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value ===================================================================== Test the input arguments */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --tau; --work; /* Function Body */ *info = 0; wantq = lsame_(vect, "Q"); mn = min(*m,*n); lquery = *lwork == -1; if (! wantq && ! lsame_(vect, "P")) { *info = -1; } else if (*m < 0) { *info = -2; } else if (((*n < 0) || (wantq && ((*n > *m) || (*n < min(*m,*k))))) || (! wantq && ((*m > *n) || (*m < min(*n,*k))))) { *info = -3; } else if (*k < 0) { *info = -4; } else if (*lda < max(1,*m)) { *info = -6; } else if (*lwork < max(1,mn) && ! lquery) { *info = -9; } if (*info == 0) { if (wantq) { nb = ilaenv_(&c__1, "ZUNGQR", " ", m, n, k, &c_n1, (ftnlen)6, ( ftnlen)1); } else { nb = ilaenv_(&c__1, "ZUNGLQ", " ", m, n, k, &c_n1, (ftnlen)6, ( ftnlen)1); } lwkopt = max(1,mn) * nb; work[1].r = (doublereal) lwkopt, work[1].i = 0.; } if (*info != 0) { i__1 = -(*info); xerbla_("ZUNGBR", &i__1); return 0; } else if (lquery) { return 0; } /* Quick return if possible */ if ((*m == 0) || (*n == 0)) { work[1].r = 1., work[1].i = 0.; return 0; } if (wantq) { /* Form Q, determined by a call to ZGEBRD to reduce an m-by-k matrix */ if (*m >= *k) { /* If m >= k, assume m >= n >= k */ zungqr_(m, n, k, &a[a_offset], lda, &tau[1], &work[1], lwork, & iinfo); } else { /* If m < k, assume m = n Shift the vectors which define the elementary reflectors one column to the right, and set the first row and column of Q to those of the unit matrix */ for (j = *m; j >= 2; --j) { i__1 = j * a_dim1 + 1; a[i__1].r = 0., a[i__1].i = 0.; i__1 = *m; for (i__ = j + 1; i__ <= i__1; ++i__) { i__2 = i__ + j * a_dim1; i__3 = i__ + (j - 1) * a_dim1; a[i__2].r = a[i__3].r, a[i__2].i = a[i__3].i; /* L10: */ } /* L20: */ } i__1 = a_dim1 + 1; a[i__1].r = 1., a[i__1].i = 0.; i__1 = *m; for (i__ = 2; i__ <= i__1; ++i__) { i__2 = i__ + a_dim1; a[i__2].r = 0., a[i__2].i = 0.; /* L30: */ } if (*m > 1) { /* Form Q(2:m,2:m) */ i__1 = *m - 1; i__2 = *m - 1; i__3 = *m - 1; zungqr_(&i__1, &i__2, &i__3, &a[((a_dim1) << (1)) + 2], lda, & tau[1], &work[1], lwork, &iinfo); } } } else { /* Form P', determined by a call to ZGEBRD to reduce a k-by-n matrix */ if (*k < *n) { /* If k < n, assume k <= m <= n */ zunglq_(m, n, k, &a[a_offset], lda, &tau[1], &work[1], lwork, & iinfo); } else { /* If k >= n, assume m = n Shift the vectors which define the elementary reflectors one row downward, and set the first row and column of P' to those of the unit matrix */ i__1 = a_dim1 + 1; a[i__1].r = 1., a[i__1].i = 0.; i__1 = *n; for (i__ = 2; i__ <= i__1; ++i__) { i__2 = i__ + a_dim1; a[i__2].r = 0., a[i__2].i = 0.; /* L40: */ } i__1 = *n; for (j = 2; j <= i__1; ++j) { for (i__ = j - 1; i__ >= 2; --i__) { i__2 = i__ + j * a_dim1; i__3 = i__ - 1 + j * a_dim1; a[i__2].r = a[i__3].r, a[i__2].i = a[i__3].i; /* L50: */ } i__2 = j * a_dim1 + 1; a[i__2].r = 0., a[i__2].i = 0.; /* L60: */ } if (*n > 1) { /* Form P'(2:n,2:n) */ i__1 = *n - 1; i__2 = *n - 1; i__3 = *n - 1; zunglq_(&i__1, &i__2, &i__3, &a[((a_dim1) << (1)) + 2], lda, & tau[1], &work[1], lwork, &iinfo); } } } work[1].r = (doublereal) lwkopt, work[1].i = 0.; return 0; /* End of ZUNGBR */ } /* zungbr_ */ /* Subroutine */ int zunghr_(integer *n, integer *ilo, integer *ihi, doublecomplex *a, integer *lda, doublecomplex *tau, doublecomplex * work, integer *lwork, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3, i__4; /* Local variables */ static integer i__, j, nb, nh, iinfo; extern /* Subroutine */ int xerbla_(char *, integer *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); static integer lwkopt; static logical lquery; extern /* Subroutine */ int zungqr_(integer *, integer *, integer *, doublecomplex *, integer *, doublecomplex *, doublecomplex *, integer *, integer *); /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= ZUNGHR generates a complex unitary matrix Q which is defined as the product of IHI-ILO elementary reflectors of order N, as returned by ZGEHRD: Q = H(ilo) H(ilo+1) . . . H(ihi-1). Arguments ========= N (input) INTEGER The order of the matrix Q. N >= 0. ILO (input) INTEGER IHI (input) INTEGER ILO and IHI must have the same values as in the previous call of ZGEHRD. Q is equal to the unit matrix except in the submatrix Q(ilo+1:ihi,ilo+1:ihi). 1 <= ILO <= IHI <= N, if N > 0; ILO=1 and IHI=0, if N=0. A (input/output) COMPLEX*16 array, dimension (LDA,N) On entry, the vectors which define the elementary reflectors, as returned by ZGEHRD. On exit, the N-by-N unitary matrix Q. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,N). TAU (input) COMPLEX*16 array, dimension (N-1) TAU(i) must contain the scalar factor of the elementary reflector H(i), as returned by ZGEHRD. WORK (workspace/output) COMPLEX*16 array, dimension (LWORK) On exit, if INFO = 0, WORK(1) returns the optimal LWORK. LWORK (input) INTEGER The dimension of the array WORK. LWORK >= IHI-ILO. For optimum performance LWORK >= (IHI-ILO)*NB, where NB is the optimal blocksize. If LWORK = -1, then a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued by XERBLA. INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value ===================================================================== Test the input arguments */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --tau; --work; /* Function Body */ *info = 0; nh = *ihi - *ilo; lquery = *lwork == -1; if (*n < 0) { *info = -1; } else if ((*ilo < 1) || (*ilo > max(1,*n))) { *info = -2; } else if ((*ihi < min(*ilo,*n)) || (*ihi > *n)) { *info = -3; } else if (*lda < max(1,*n)) { *info = -5; } else if (*lwork < max(1,nh) && ! lquery) { *info = -8; } if (*info == 0) { nb = ilaenv_(&c__1, "ZUNGQR", " ", &nh, &nh, &nh, &c_n1, (ftnlen)6, ( ftnlen)1); lwkopt = max(1,nh) * nb; work[1].r = (doublereal) lwkopt, work[1].i = 0.; } if (*info != 0) { i__1 = -(*info); xerbla_("ZUNGHR", &i__1); return 0; } else if (lquery) { return 0; } /* Quick return if possible */ if (*n == 0) { work[1].r = 1., work[1].i = 0.; return 0; } /* Shift the vectors which define the elementary reflectors one column to the right, and set the first ilo and the last n-ihi rows and columns to those of the unit matrix */ i__1 = *ilo + 1; for (j = *ihi; j >= i__1; --j) { i__2 = j - 1; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * a_dim1; a[i__3].r = 0., a[i__3].i = 0.; /* L10: */ } i__2 = *ihi; for (i__ = j + 1; i__ <= i__2; ++i__) { i__3 = i__ + j * a_dim1; i__4 = i__ + (j - 1) * a_dim1; a[i__3].r = a[i__4].r, a[i__3].i = a[i__4].i; /* L20: */ } i__2 = *n; for (i__ = *ihi + 1; i__ <= i__2; ++i__) { i__3 = i__ + j * a_dim1; a[i__3].r = 0., a[i__3].i = 0.; /* L30: */ } /* L40: */ } i__1 = *ilo; for (j = 1; j <= i__1; ++j) { i__2 = *n; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * a_dim1; a[i__3].r = 0., a[i__3].i = 0.; /* L50: */ } i__2 = j + j * a_dim1; a[i__2].r = 1., a[i__2].i = 0.; /* L60: */ } i__1 = *n; for (j = *ihi + 1; j <= i__1; ++j) { i__2 = *n; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * a_dim1; a[i__3].r = 0., a[i__3].i = 0.; /* L70: */ } i__2 = j + j * a_dim1; a[i__2].r = 1., a[i__2].i = 0.; /* L80: */ } if (nh > 0) { /* Generate Q(ilo+1:ihi,ilo+1:ihi) */ zungqr_(&nh, &nh, &nh, &a[*ilo + 1 + (*ilo + 1) * a_dim1], lda, &tau[* ilo], &work[1], lwork, &iinfo); } work[1].r = (doublereal) lwkopt, work[1].i = 0.; return 0; /* End of ZUNGHR */ } /* zunghr_ */ /* Subroutine */ int zungl2_(integer *m, integer *n, integer *k, doublecomplex *a, integer *lda, doublecomplex *tau, doublecomplex * work, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3; doublecomplex z__1, z__2; /* Builtin functions */ void d_cnjg(doublecomplex *, doublecomplex *); /* Local variables */ static integer i__, j, l; extern /* Subroutine */ int zscal_(integer *, doublecomplex *, doublecomplex *, integer *), zlarf_(char *, integer *, integer *, doublecomplex *, integer *, doublecomplex *, doublecomplex *, integer *, doublecomplex *), xerbla_(char *, integer *), zlacgv_(integer *, doublecomplex *, integer *); /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= ZUNGL2 generates an m-by-n complex matrix Q with orthonormal rows, which is defined as the first m rows of a product of k elementary reflectors of order n Q = H(k)' . . . H(2)' H(1)' as returned by ZGELQF. Arguments ========= M (input) INTEGER The number of rows of the matrix Q. M >= 0. N (input) INTEGER The number of columns of the matrix Q. N >= M. K (input) INTEGER The number of elementary reflectors whose product defines the matrix Q. M >= K >= 0. A (input/output) COMPLEX*16 array, dimension (LDA,N) On entry, the i-th row must contain the vector which defines the elementary reflector H(i), for i = 1,2,...,k, as returned by ZGELQF in the first k rows of its array argument A. On exit, the m by n matrix Q. LDA (input) INTEGER The first dimension of the array A. LDA >= max(1,M). TAU (input) COMPLEX*16 array, dimension (K) TAU(i) must contain the scalar factor of the elementary reflector H(i), as returned by ZGELQF. WORK (workspace) COMPLEX*16 array, dimension (M) INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument has an illegal value ===================================================================== Test the input arguments */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --tau; --work; /* Function Body */ *info = 0; if (*m < 0) { *info = -1; } else if (*n < *m) { *info = -2; } else if ((*k < 0) || (*k > *m)) { *info = -3; } else if (*lda < max(1,*m)) { *info = -5; } if (*info != 0) { i__1 = -(*info); xerbla_("ZUNGL2", &i__1); return 0; } /* Quick return if possible */ if (*m <= 0) { return 0; } if (*k < *m) { /* Initialise rows k+1:m to rows of the unit matrix */ i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (l = *k + 1; l <= i__2; ++l) { i__3 = l + j * a_dim1; a[i__3].r = 0., a[i__3].i = 0.; /* L10: */ } if (j > *k && j <= *m) { i__2 = j + j * a_dim1; a[i__2].r = 1., a[i__2].i = 0.; } /* L20: */ } } for (i__ = *k; i__ >= 1; --i__) { /* Apply H(i)' to A(i:m,i:n) from the right */ if (i__ < *n) { i__1 = *n - i__; zlacgv_(&i__1, &a[i__ + (i__ + 1) * a_dim1], lda); if (i__ < *m) { i__1 = i__ + i__ * a_dim1; a[i__1].r = 1., a[i__1].i = 0.; i__1 = *m - i__; i__2 = *n - i__ + 1; d_cnjg(&z__1, &tau[i__]); zlarf_("Right", &i__1, &i__2, &a[i__ + i__ * a_dim1], lda, & z__1, &a[i__ + 1 + i__ * a_dim1], lda, &work[1]); } i__1 = *n - i__; i__2 = i__; z__1.r = -tau[i__2].r, z__1.i = -tau[i__2].i; zscal_(&i__1, &z__1, &a[i__ + (i__ + 1) * a_dim1], lda); i__1 = *n - i__; zlacgv_(&i__1, &a[i__ + (i__ + 1) * a_dim1], lda); } i__1 = i__ + i__ * a_dim1; d_cnjg(&z__2, &tau[i__]); z__1.r = 1. - z__2.r, z__1.i = 0. - z__2.i; a[i__1].r = z__1.r, a[i__1].i = z__1.i; /* Set A(i,1:i-1) to zero */ i__1 = i__ - 1; for (l = 1; l <= i__1; ++l) { i__2 = i__ + l * a_dim1; a[i__2].r = 0., a[i__2].i = 0.; /* L30: */ } /* L40: */ } return 0; /* End of ZUNGL2 */ } /* zungl2_ */ /* Subroutine */ int zunglq_(integer *m, integer *n, integer *k, doublecomplex *a, integer *lda, doublecomplex *tau, doublecomplex * work, integer *lwork, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3, i__4; /* Local variables */ static integer i__, j, l, ib, nb, ki, kk, nx, iws, nbmin, iinfo; extern /* Subroutine */ int zungl2_(integer *, integer *, integer *, doublecomplex *, integer *, doublecomplex *, doublecomplex *, integer *), xerbla_(char *, integer *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); extern /* Subroutine */ int zlarfb_(char *, char *, char *, char *, integer *, integer *, integer *, doublecomplex *, integer *, doublecomplex *, integer *, doublecomplex *, integer *, doublecomplex *, integer *); static integer ldwork; extern /* Subroutine */ int zlarft_(char *, char *, integer *, integer *, doublecomplex *, integer *, doublecomplex *, doublecomplex *, integer *); static logical lquery; static integer lwkopt; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= ZUNGLQ generates an M-by-N complex matrix Q with orthonormal rows, which is defined as the first M rows of a product of K elementary reflectors of order N Q = H(k)' . . . H(2)' H(1)' as returned by ZGELQF. Arguments ========= M (input) INTEGER The number of rows of the matrix Q. M >= 0. N (input) INTEGER The number of columns of the matrix Q. N >= M. K (input) INTEGER The number of elementary reflectors whose product defines the matrix Q. M >= K >= 0. A (input/output) COMPLEX*16 array, dimension (LDA,N) On entry, the i-th row must contain the vector which defines the elementary reflector H(i), for i = 1,2,...,k, as returned by ZGELQF in the first k rows of its array argument A. On exit, the M-by-N matrix Q. LDA (input) INTEGER The first dimension of the array A. LDA >= max(1,M). TAU (input) COMPLEX*16 array, dimension (K) TAU(i) must contain the scalar factor of the elementary reflector H(i), as returned by ZGELQF. WORK (workspace/output) COMPLEX*16 array, dimension (LWORK) On exit, if INFO = 0, WORK(1) returns the optimal LWORK. LWORK (input) INTEGER The dimension of the array WORK. LWORK >= max(1,M). For optimum performance LWORK >= M*NB, where NB is the optimal blocksize. If LWORK = -1, then a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued by XERBLA. INFO (output) INTEGER = 0: successful exit; < 0: if INFO = -i, the i-th argument has an illegal value ===================================================================== Test the input arguments */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --tau; --work; /* Function Body */ *info = 0; nb = ilaenv_(&c__1, "ZUNGLQ", " ", m, n, k, &c_n1, (ftnlen)6, (ftnlen)1); lwkopt = max(1,*m) * nb; work[1].r = (doublereal) lwkopt, work[1].i = 0.; lquery = *lwork == -1; if (*m < 0) { *info = -1; } else if (*n < *m) { *info = -2; } else if ((*k < 0) || (*k > *m)) { *info = -3; } else if (*lda < max(1,*m)) { *info = -5; } else if (*lwork < max(1,*m) && ! lquery) { *info = -8; } if (*info != 0) { i__1 = -(*info); xerbla_("ZUNGLQ", &i__1); return 0; } else if (lquery) { return 0; } /* Quick return if possible */ if (*m <= 0) { work[1].r = 1., work[1].i = 0.; return 0; } nbmin = 2; nx = 0; iws = *m; if (nb > 1 && nb < *k) { /* Determine when to cross over from blocked to unblocked code. Computing MAX */ i__1 = 0, i__2 = ilaenv_(&c__3, "ZUNGLQ", " ", m, n, k, &c_n1, ( ftnlen)6, (ftnlen)1); nx = max(i__1,i__2); if (nx < *k) { /* Determine if workspace is large enough for blocked code. */ ldwork = *m; iws = ldwork * nb; if (*lwork < iws) { /* Not enough workspace to use optimal NB: reduce NB and determine the minimum value of NB. */ nb = *lwork / ldwork; /* Computing MAX */ i__1 = 2, i__2 = ilaenv_(&c__2, "ZUNGLQ", " ", m, n, k, &c_n1, (ftnlen)6, (ftnlen)1); nbmin = max(i__1,i__2); } } } if (nb >= nbmin && nb < *k && nx < *k) { /* Use blocked code after the last block. The first kk rows are handled by the block method. */ ki = (*k - nx - 1) / nb * nb; /* Computing MIN */ i__1 = *k, i__2 = ki + nb; kk = min(i__1,i__2); /* Set A(kk+1:m,1:kk) to zero. */ i__1 = kk; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = kk + 1; i__ <= i__2; ++i__) { i__3 = i__ + j * a_dim1; a[i__3].r = 0., a[i__3].i = 0.; /* L10: */ } /* L20: */ } } else { kk = 0; } /* Use unblocked code for the last or only block. */ if (kk < *m) { i__1 = *m - kk; i__2 = *n - kk; i__3 = *k - kk; zungl2_(&i__1, &i__2, &i__3, &a[kk + 1 + (kk + 1) * a_dim1], lda, & tau[kk + 1], &work[1], &iinfo); } if (kk > 0) { /* Use blocked code */ i__1 = -nb; for (i__ = ki + 1; i__1 < 0 ? i__ >= 1 : i__ <= 1; i__ += i__1) { /* Computing MIN */ i__2 = nb, i__3 = *k - i__ + 1; ib = min(i__2,i__3); if (i__ + ib <= *m) { /* Form the triangular factor of the block reflector H = H(i) H(i+1) . . . H(i+ib-1) */ i__2 = *n - i__ + 1; zlarft_("Forward", "Rowwise", &i__2, &ib, &a[i__ + i__ * a_dim1], lda, &tau[i__], &work[1], &ldwork); /* Apply H' to A(i+ib:m,i:n) from the right */ i__2 = *m - i__ - ib + 1; i__3 = *n - i__ + 1; zlarfb_("Right", "Conjugate transpose", "Forward", "Rowwise", &i__2, &i__3, &ib, &a[i__ + i__ * a_dim1], lda, &work[ 1], &ldwork, &a[i__ + ib + i__ * a_dim1], lda, &work[ ib + 1], &ldwork); } /* Apply H' to columns i:n of current block */ i__2 = *n - i__ + 1; zungl2_(&ib, &i__2, &ib, &a[i__ + i__ * a_dim1], lda, &tau[i__], & work[1], &iinfo); /* Set columns 1:i-1 of current block to zero */ i__2 = i__ - 1; for (j = 1; j <= i__2; ++j) { i__3 = i__ + ib - 1; for (l = i__; l <= i__3; ++l) { i__4 = l + j * a_dim1; a[i__4].r = 0., a[i__4].i = 0.; /* L30: */ } /* L40: */ } /* L50: */ } } work[1].r = (doublereal) iws, work[1].i = 0.; return 0; /* End of ZUNGLQ */ } /* zunglq_ */ /* Subroutine */ int zungqr_(integer *m, integer *n, integer *k, doublecomplex *a, integer *lda, doublecomplex *tau, doublecomplex * work, integer *lwork, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3, i__4; /* Local variables */ static integer i__, j, l, ib, nb, ki, kk, nx, iws, nbmin, iinfo; extern /* Subroutine */ int zung2r_(integer *, integer *, integer *, doublecomplex *, integer *, doublecomplex *, doublecomplex *, integer *), xerbla_(char *, integer *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); extern /* Subroutine */ int zlarfb_(char *, char *, char *, char *, integer *, integer *, integer *, doublecomplex *, integer *, doublecomplex *, integer *, doublecomplex *, integer *, doublecomplex *, integer *); static integer ldwork; extern /* Subroutine */ int zlarft_(char *, char *, integer *, integer *, doublecomplex *, integer *, doublecomplex *, doublecomplex *, integer *); static integer lwkopt; static logical lquery; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= ZUNGQR generates an M-by-N complex matrix Q with orthonormal columns, which is defined as the first N columns of a product of K elementary reflectors of order M Q = H(1) H(2) . . . H(k) as returned by ZGEQRF. Arguments ========= M (input) INTEGER The number of rows of the matrix Q. M >= 0. N (input) INTEGER The number of columns of the matrix Q. M >= N >= 0. K (input) INTEGER The number of elementary reflectors whose product defines the matrix Q. N >= K >= 0. A (input/output) COMPLEX*16 array, dimension (LDA,N) On entry, the i-th column must contain the vector which defines the elementary reflector H(i), for i = 1,2,...,k, as returned by ZGEQRF in the first k columns of its array argument A. On exit, the M-by-N matrix Q. LDA (input) INTEGER The first dimension of the array A. LDA >= max(1,M). TAU (input) COMPLEX*16 array, dimension (K) TAU(i) must contain the scalar factor of the elementary reflector H(i), as returned by ZGEQRF. WORK (workspace/output) COMPLEX*16 array, dimension (LWORK) On exit, if INFO = 0, WORK(1) returns the optimal LWORK. LWORK (input) INTEGER The dimension of the array WORK. LWORK >= max(1,N). For optimum performance LWORK >= N*NB, where NB is the optimal blocksize. If LWORK = -1, then a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued by XERBLA. INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument has an illegal value ===================================================================== Test the input arguments */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --tau; --work; /* Function Body */ *info = 0; nb = ilaenv_(&c__1, "ZUNGQR", " ", m, n, k, &c_n1, (ftnlen)6, (ftnlen)1); lwkopt = max(1,*n) * nb; work[1].r = (doublereal) lwkopt, work[1].i = 0.; lquery = *lwork == -1; if (*m < 0) { *info = -1; } else if ((*n < 0) || (*n > *m)) { *info = -2; } else if ((*k < 0) || (*k > *n)) { *info = -3; } else if (*lda < max(1,*m)) { *info = -5; } else if (*lwork < max(1,*n) && ! lquery) { *info = -8; } if (*info != 0) { i__1 = -(*info); xerbla_("ZUNGQR", &i__1); return 0; } else if (lquery) { return 0; } /* Quick return if possible */ if (*n <= 0) { work[1].r = 1., work[1].i = 0.; return 0; } nbmin = 2; nx = 0; iws = *n; if (nb > 1 && nb < *k) { /* Determine when to cross over from blocked to unblocked code. Computing MAX */ i__1 = 0, i__2 = ilaenv_(&c__3, "ZUNGQR", " ", m, n, k, &c_n1, ( ftnlen)6, (ftnlen)1); nx = max(i__1,i__2); if (nx < *k) { /* Determine if workspace is large enough for blocked code. */ ldwork = *n; iws = ldwork * nb; if (*lwork < iws) { /* Not enough workspace to use optimal NB: reduce NB and determine the minimum value of NB. */ nb = *lwork / ldwork; /* Computing MAX */ i__1 = 2, i__2 = ilaenv_(&c__2, "ZUNGQR", " ", m, n, k, &c_n1, (ftnlen)6, (ftnlen)1); nbmin = max(i__1,i__2); } } } if (nb >= nbmin && nb < *k && nx < *k) { /* Use blocked code after the last block. The first kk columns are handled by the block method. */ ki = (*k - nx - 1) / nb * nb; /* Computing MIN */ i__1 = *k, i__2 = ki + nb; kk = min(i__1,i__2); /* Set A(1:kk,kk+1:n) to zero. */ i__1 = *n; for (j = kk + 1; j <= i__1; ++j) { i__2 = kk; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * a_dim1; a[i__3].r = 0., a[i__3].i = 0.; /* L10: */ } /* L20: */ } } else { kk = 0; } /* Use unblocked code for the last or only block. */ if (kk < *n) { i__1 = *m - kk; i__2 = *n - kk; i__3 = *k - kk; zung2r_(&i__1, &i__2, &i__3, &a[kk + 1 + (kk + 1) * a_dim1], lda, & tau[kk + 1], &work[1], &iinfo); } if (kk > 0) { /* Use blocked code */ i__1 = -nb; for (i__ = ki + 1; i__1 < 0 ? i__ >= 1 : i__ <= 1; i__ += i__1) { /* Computing MIN */ i__2 = nb, i__3 = *k - i__ + 1; ib = min(i__2,i__3); if (i__ + ib <= *n) { /* Form the triangular factor of the block reflector H = H(i) H(i+1) . . . H(i+ib-1) */ i__2 = *m - i__ + 1; zlarft_("Forward", "Columnwise", &i__2, &ib, &a[i__ + i__ * a_dim1], lda, &tau[i__], &work[1], &ldwork); /* Apply H to A(i:m,i+ib:n) from the left */ i__2 = *m - i__ + 1; i__3 = *n - i__ - ib + 1; zlarfb_("Left", "No transpose", "Forward", "Columnwise", & i__2, &i__3, &ib, &a[i__ + i__ * a_dim1], lda, &work[ 1], &ldwork, &a[i__ + (i__ + ib) * a_dim1], lda, & work[ib + 1], &ldwork); } /* Apply H to rows i:m of current block */ i__2 = *m - i__ + 1; zung2r_(&i__2, &ib, &ib, &a[i__ + i__ * a_dim1], lda, &tau[i__], & work[1], &iinfo); /* Set rows 1:i-1 of current block to zero */ i__2 = i__ + ib - 1; for (j = i__; j <= i__2; ++j) { i__3 = i__ - 1; for (l = 1; l <= i__3; ++l) { i__4 = l + j * a_dim1; a[i__4].r = 0., a[i__4].i = 0.; /* L30: */ } /* L40: */ } /* L50: */ } } work[1].r = (doublereal) iws, work[1].i = 0.; return 0; /* End of ZUNGQR */ } /* zungqr_ */ /* Subroutine */ int zunm2l_(char *side, char *trans, integer *m, integer *n, integer *k, doublecomplex *a, integer *lda, doublecomplex *tau, doublecomplex *c__, integer *ldc, doublecomplex *work, integer *info) { /* System generated locals */ integer a_dim1, a_offset, c_dim1, c_offset, i__1, i__2, i__3; doublecomplex z__1; /* Builtin functions */ void d_cnjg(doublecomplex *, doublecomplex *); /* Local variables */ static integer i__, i1, i2, i3, mi, ni, nq; static doublecomplex aii; static logical left; static doublecomplex taui; extern logical lsame_(char *, char *); extern /* Subroutine */ int zlarf_(char *, integer *, integer *, doublecomplex *, integer *, doublecomplex *, doublecomplex *, integer *, doublecomplex *), xerbla_(char *, integer *); static logical notran; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University September 30, 1994 Purpose ======= ZUNM2L overwrites the general complex m-by-n matrix C with Q * C if SIDE = 'L' and TRANS = 'N', or Q'* C if SIDE = 'L' and TRANS = 'C', or C * Q if SIDE = 'R' and TRANS = 'N', or C * Q' if SIDE = 'R' and TRANS = 'C', where Q is a complex unitary matrix defined as the product of k elementary reflectors Q = H(k) . . . H(2) H(1) as returned by ZGEQLF. Q is of order m if SIDE = 'L' and of order n if SIDE = 'R'. Arguments ========= SIDE (input) CHARACTER*1 = 'L': apply Q or Q' from the Left = 'R': apply Q or Q' from the Right TRANS (input) CHARACTER*1 = 'N': apply Q (No transpose) = 'C': apply Q' (Conjugate transpose) M (input) INTEGER The number of rows of the matrix C. M >= 0. N (input) INTEGER The number of columns of the matrix C. N >= 0. K (input) INTEGER The number of elementary reflectors whose product defines the matrix Q. If SIDE = 'L', M >= K >= 0; if SIDE = 'R', N >= K >= 0. A (input) COMPLEX*16 array, dimension (LDA,K) The i-th column must contain the vector which defines the elementary reflector H(i), for i = 1,2,...,k, as returned by ZGEQLF in the last k columns of its array argument A. A is modified by the routine but restored on exit. LDA (input) INTEGER The leading dimension of the array A. If SIDE = 'L', LDA >= max(1,M); if SIDE = 'R', LDA >= max(1,N). TAU (input) COMPLEX*16 array, dimension (K) TAU(i) must contain the scalar factor of the elementary reflector H(i), as returned by ZGEQLF. C (input/output) COMPLEX*16 array, dimension (LDC,N) On entry, the m-by-n matrix C. On exit, C is overwritten by Q*C or Q'*C or C*Q' or C*Q. LDC (input) INTEGER The leading dimension of the array C. LDC >= max(1,M). WORK (workspace) COMPLEX*16 array, dimension (N) if SIDE = 'L', (M) if SIDE = 'R' INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value ===================================================================== Test the input arguments */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --tau; c_dim1 = *ldc; c_offset = 1 + c_dim1; c__ -= c_offset; --work; /* Function Body */ *info = 0; left = lsame_(side, "L"); notran = lsame_(trans, "N"); /* NQ is the order of Q */ if (left) { nq = *m; } else { nq = *n; } if (! left && ! lsame_(side, "R")) { *info = -1; } else if (! notran && ! lsame_(trans, "C")) { *info = -2; } else if (*m < 0) { *info = -3; } else if (*n < 0) { *info = -4; } else if ((*k < 0) || (*k > nq)) { *info = -5; } else if (*lda < max(1,nq)) { *info = -7; } else if (*ldc < max(1,*m)) { *info = -10; } if (*info != 0) { i__1 = -(*info); xerbla_("ZUNM2L", &i__1); return 0; } /* Quick return if possible */ if (((*m == 0) || (*n == 0)) || (*k == 0)) { return 0; } if ((left && notran) || (! left && ! notran)) { i1 = 1; i2 = *k; i3 = 1; } else { i1 = *k; i2 = 1; i3 = -1; } if (left) { ni = *n; } else { mi = *m; } i__1 = i2; i__2 = i3; for (i__ = i1; i__2 < 0 ? i__ >= i__1 : i__ <= i__1; i__ += i__2) { if (left) { /* H(i) or H(i)' is applied to C(1:m-k+i,1:n) */ mi = *m - *k + i__; } else { /* H(i) or H(i)' is applied to C(1:m,1:n-k+i) */ ni = *n - *k + i__; } /* Apply H(i) or H(i)' */ if (notran) { i__3 = i__; taui.r = tau[i__3].r, taui.i = tau[i__3].i; } else { d_cnjg(&z__1, &tau[i__]); taui.r = z__1.r, taui.i = z__1.i; } i__3 = nq - *k + i__ + i__ * a_dim1; aii.r = a[i__3].r, aii.i = a[i__3].i; i__3 = nq - *k + i__ + i__ * a_dim1; a[i__3].r = 1., a[i__3].i = 0.; zlarf_(side, &mi, &ni, &a[i__ * a_dim1 + 1], &c__1, &taui, &c__[ c_offset], ldc, &work[1]); i__3 = nq - *k + i__ + i__ * a_dim1; a[i__3].r = aii.r, a[i__3].i = aii.i; /* L10: */ } return 0; /* End of ZUNM2L */ } /* zunm2l_ */ /* Subroutine */ int zunm2r_(char *side, char *trans, integer *m, integer *n, integer *k, doublecomplex *a, integer *lda, doublecomplex *tau, doublecomplex *c__, integer *ldc, doublecomplex *work, integer *info) { /* System generated locals */ integer a_dim1, a_offset, c_dim1, c_offset, i__1, i__2, i__3; doublecomplex z__1; /* Builtin functions */ void d_cnjg(doublecomplex *, doublecomplex *); /* Local variables */ static integer i__, i1, i2, i3, ic, jc, mi, ni, nq; static doublecomplex aii; static logical left; static doublecomplex taui; extern logical lsame_(char *, char *); extern /* Subroutine */ int zlarf_(char *, integer *, integer *, doublecomplex *, integer *, doublecomplex *, doublecomplex *, integer *, doublecomplex *), xerbla_(char *, integer *); static logical notran; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University September 30, 1994 Purpose ======= ZUNM2R overwrites the general complex m-by-n matrix C with Q * C if SIDE = 'L' and TRANS = 'N', or Q'* C if SIDE = 'L' and TRANS = 'C', or C * Q if SIDE = 'R' and TRANS = 'N', or C * Q' if SIDE = 'R' and TRANS = 'C', where Q is a complex unitary matrix defined as the product of k elementary reflectors Q = H(1) H(2) . . . H(k) as returned by ZGEQRF. Q is of order m if SIDE = 'L' and of order n if SIDE = 'R'. Arguments ========= SIDE (input) CHARACTER*1 = 'L': apply Q or Q' from the Left = 'R': apply Q or Q' from the Right TRANS (input) CHARACTER*1 = 'N': apply Q (No transpose) = 'C': apply Q' (Conjugate transpose) M (input) INTEGER The number of rows of the matrix C. M >= 0. N (input) INTEGER The number of columns of the matrix C. N >= 0. K (input) INTEGER The number of elementary reflectors whose product defines the matrix Q. If SIDE = 'L', M >= K >= 0; if SIDE = 'R', N >= K >= 0. A (input) COMPLEX*16 array, dimension (LDA,K) The i-th column must contain the vector which defines the elementary reflector H(i), for i = 1,2,...,k, as returned by ZGEQRF in the first k columns of its array argument A. A is modified by the routine but restored on exit. LDA (input) INTEGER The leading dimension of the array A. If SIDE = 'L', LDA >= max(1,M); if SIDE = 'R', LDA >= max(1,N). TAU (input) COMPLEX*16 array, dimension (K) TAU(i) must contain the scalar factor of the elementary reflector H(i), as returned by ZGEQRF. C (input/output) COMPLEX*16 array, dimension (LDC,N) On entry, the m-by-n matrix C. On exit, C is overwritten by Q*C or Q'*C or C*Q' or C*Q. LDC (input) INTEGER The leading dimension of the array C. LDC >= max(1,M). WORK (workspace) COMPLEX*16 array, dimension (N) if SIDE = 'L', (M) if SIDE = 'R' INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value ===================================================================== Test the input arguments */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --tau; c_dim1 = *ldc; c_offset = 1 + c_dim1; c__ -= c_offset; --work; /* Function Body */ *info = 0; left = lsame_(side, "L"); notran = lsame_(trans, "N"); /* NQ is the order of Q */ if (left) { nq = *m; } else { nq = *n; } if (! left && ! lsame_(side, "R")) { *info = -1; } else if (! notran && ! lsame_(trans, "C")) { *info = -2; } else if (*m < 0) { *info = -3; } else if (*n < 0) { *info = -4; } else if ((*k < 0) || (*k > nq)) { *info = -5; } else if (*lda < max(1,nq)) { *info = -7; } else if (*ldc < max(1,*m)) { *info = -10; } if (*info != 0) { i__1 = -(*info); xerbla_("ZUNM2R", &i__1); return 0; } /* Quick return if possible */ if (((*m == 0) || (*n == 0)) || (*k == 0)) { return 0; } if ((left && ! notran) || (! left && notran)) { i1 = 1; i2 = *k; i3 = 1; } else { i1 = *k; i2 = 1; i3 = -1; } if (left) { ni = *n; jc = 1; } else { mi = *m; ic = 1; } i__1 = i2; i__2 = i3; for (i__ = i1; i__2 < 0 ? i__ >= i__1 : i__ <= i__1; i__ += i__2) { if (left) { /* H(i) or H(i)' is applied to C(i:m,1:n) */ mi = *m - i__ + 1; ic = i__; } else { /* H(i) or H(i)' is applied to C(1:m,i:n) */ ni = *n - i__ + 1; jc = i__; } /* Apply H(i) or H(i)' */ if (notran) { i__3 = i__; taui.r = tau[i__3].r, taui.i = tau[i__3].i; } else { d_cnjg(&z__1, &tau[i__]); taui.r = z__1.r, taui.i = z__1.i; } i__3 = i__ + i__ * a_dim1; aii.r = a[i__3].r, aii.i = a[i__3].i; i__3 = i__ + i__ * a_dim1; a[i__3].r = 1., a[i__3].i = 0.; zlarf_(side, &mi, &ni, &a[i__ + i__ * a_dim1], &c__1, &taui, &c__[ic + jc * c_dim1], ldc, &work[1]); i__3 = i__ + i__ * a_dim1; a[i__3].r = aii.r, a[i__3].i = aii.i; /* L10: */ } return 0; /* End of ZUNM2R */ } /* zunm2r_ */ /* Subroutine */ int zunmbr_(char *vect, char *side, char *trans, integer *m, integer *n, integer *k, doublecomplex *a, integer *lda, doublecomplex *tau, doublecomplex *c__, integer *ldc, doublecomplex *work, integer * lwork, integer *info) { /* System generated locals */ address a__1[2]; integer a_dim1, a_offset, c_dim1, c_offset, i__1, i__2, i__3[2]; char ch__1[2]; /* Builtin functions */ /* Subroutine */ int s_cat(char *, char **, integer *, integer *, ftnlen); /* Local variables */ static integer i1, i2, nb, mi, ni, nq, nw; static logical left; extern logical lsame_(char *, char *); static integer iinfo; extern /* Subroutine */ int xerbla_(char *, integer *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); static logical notran, applyq; static char transt[1]; static integer lwkopt; static logical lquery; extern /* Subroutine */ int zunmlq_(char *, char *, integer *, integer *, integer *, doublecomplex *, integer *, doublecomplex *, doublecomplex *, integer *, doublecomplex *, integer *, integer *), zunmqr_(char *, char *, integer *, integer *, integer *, doublecomplex *, integer *, doublecomplex *, doublecomplex *, integer *, doublecomplex *, integer *, integer *); /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= If VECT = 'Q', ZUNMBR overwrites the general complex M-by-N matrix C with SIDE = 'L' SIDE = 'R' TRANS = 'N': Q * C C * Q TRANS = 'C': Q**H * C C * Q**H If VECT = 'P', ZUNMBR overwrites the general complex M-by-N matrix C with SIDE = 'L' SIDE = 'R' TRANS = 'N': P * C C * P TRANS = 'C': P**H * C C * P**H Here Q and P**H are the unitary matrices determined by ZGEBRD when reducing a complex matrix A to bidiagonal form: A = Q * B * P**H. Q and P**H are defined as products of elementary reflectors H(i) and G(i) respectively. Let nq = m if SIDE = 'L' and nq = n if SIDE = 'R'. Thus nq is the order of the unitary matrix Q or P**H that is applied. If VECT = 'Q', A is assumed to have been an NQ-by-K matrix: if nq >= k, Q = H(1) H(2) . . . H(k); if nq < k, Q = H(1) H(2) . . . H(nq-1). If VECT = 'P', A is assumed to have been a K-by-NQ matrix: if k < nq, P = G(1) G(2) . . . G(k); if k >= nq, P = G(1) G(2) . . . G(nq-1). Arguments ========= VECT (input) CHARACTER*1 = 'Q': apply Q or Q**H; = 'P': apply P or P**H. SIDE (input) CHARACTER*1 = 'L': apply Q, Q**H, P or P**H from the Left; = 'R': apply Q, Q**H, P or P**H from the Right. TRANS (input) CHARACTER*1 = 'N': No transpose, apply Q or P; = 'C': Conjugate transpose, apply Q**H or P**H. M (input) INTEGER The number of rows of the matrix C. M >= 0. N (input) INTEGER The number of columns of the matrix C. N >= 0. K (input) INTEGER If VECT = 'Q', the number of columns in the original matrix reduced by ZGEBRD. If VECT = 'P', the number of rows in the original matrix reduced by ZGEBRD. K >= 0. A (input) COMPLEX*16 array, dimension (LDA,min(nq,K)) if VECT = 'Q' (LDA,nq) if VECT = 'P' The vectors which define the elementary reflectors H(i) and G(i), whose products determine the matrices Q and P, as returned by ZGEBRD. LDA (input) INTEGER The leading dimension of the array A. If VECT = 'Q', LDA >= max(1,nq); if VECT = 'P', LDA >= max(1,min(nq,K)). TAU (input) COMPLEX*16 array, dimension (min(nq,K)) TAU(i) must contain the scalar factor of the elementary reflector H(i) or G(i) which determines Q or P, as returned by ZGEBRD in the array argument TAUQ or TAUP. C (input/output) COMPLEX*16 array, dimension (LDC,N) On entry, the M-by-N matrix C. On exit, C is overwritten by Q*C or Q**H*C or C*Q**H or C*Q or P*C or P**H*C or C*P or C*P**H. LDC (input) INTEGER The leading dimension of the array C. LDC >= max(1,M). WORK (workspace/output) COMPLEX*16 array, dimension (LWORK) On exit, if INFO = 0, WORK(1) returns the optimal LWORK. LWORK (input) INTEGER The dimension of the array WORK. If SIDE = 'L', LWORK >= max(1,N); if SIDE = 'R', LWORK >= max(1,M). For optimum performance LWORK >= N*NB if SIDE = 'L', and LWORK >= M*NB if SIDE = 'R', where NB is the optimal blocksize. If LWORK = -1, then a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued by XERBLA. INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value ===================================================================== Test the input arguments */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --tau; c_dim1 = *ldc; c_offset = 1 + c_dim1; c__ -= c_offset; --work; /* Function Body */ *info = 0; applyq = lsame_(vect, "Q"); left = lsame_(side, "L"); notran = lsame_(trans, "N"); lquery = *lwork == -1; /* NQ is the order of Q or P and NW is the minimum dimension of WORK */ if (left) { nq = *m; nw = *n; } else { nq = *n; nw = *m; } if (! applyq && ! lsame_(vect, "P")) { *info = -1; } else if (! left && ! lsame_(side, "R")) { *info = -2; } else if (! notran && ! lsame_(trans, "C")) { *info = -3; } else if (*m < 0) { *info = -4; } else if (*n < 0) { *info = -5; } else if (*k < 0) { *info = -6; } else /* if(complicated condition) */ { /* Computing MAX */ i__1 = 1, i__2 = min(nq,*k); if ((applyq && *lda < max(1,nq)) || (! applyq && *lda < max(i__1,i__2) )) { *info = -8; } else if (*ldc < max(1,*m)) { *info = -11; } else if (*lwork < max(1,nw) && ! lquery) { *info = -13; } } if (*info == 0) { if (applyq) { if (left) { /* Writing concatenation */ i__3[0] = 1, a__1[0] = side; i__3[1] = 1, a__1[1] = trans; s_cat(ch__1, a__1, i__3, &c__2, (ftnlen)2); i__1 = *m - 1; i__2 = *m - 1; nb = ilaenv_(&c__1, "ZUNMQR", ch__1, &i__1, n, &i__2, &c_n1, ( ftnlen)6, (ftnlen)2); } else { /* Writing concatenation */ i__3[0] = 1, a__1[0] = side; i__3[1] = 1, a__1[1] = trans; s_cat(ch__1, a__1, i__3, &c__2, (ftnlen)2); i__1 = *n - 1; i__2 = *n - 1; nb = ilaenv_(&c__1, "ZUNMQR", ch__1, m, &i__1, &i__2, &c_n1, ( ftnlen)6, (ftnlen)2); } } else { if (left) { /* Writing concatenation */ i__3[0] = 1, a__1[0] = side; i__3[1] = 1, a__1[1] = trans; s_cat(ch__1, a__1, i__3, &c__2, (ftnlen)2); i__1 = *m - 1; i__2 = *m - 1; nb = ilaenv_(&c__1, "ZUNMLQ", ch__1, &i__1, n, &i__2, &c_n1, ( ftnlen)6, (ftnlen)2); } else { /* Writing concatenation */ i__3[0] = 1, a__1[0] = side; i__3[1] = 1, a__1[1] = trans; s_cat(ch__1, a__1, i__3, &c__2, (ftnlen)2); i__1 = *n - 1; i__2 = *n - 1; nb = ilaenv_(&c__1, "ZUNMLQ", ch__1, m, &i__1, &i__2, &c_n1, ( ftnlen)6, (ftnlen)2); } } lwkopt = max(1,nw) * nb; work[1].r = (doublereal) lwkopt, work[1].i = 0.; } if (*info != 0) { i__1 = -(*info); xerbla_("ZUNMBR", &i__1); return 0; } else if (lquery) { } /* Quick return if possible */ work[1].r = 1., work[1].i = 0.; if ((*m == 0) || (*n == 0)) { return 0; } if (applyq) { /* Apply Q */ if (nq >= *k) { /* Q was determined by a call to ZGEBRD with nq >= k */ zunmqr_(side, trans, m, n, k, &a[a_offset], lda, &tau[1], &c__[ c_offset], ldc, &work[1], lwork, &iinfo); } else if (nq > 1) { /* Q was determined by a call to ZGEBRD with nq < k */ if (left) { mi = *m - 1; ni = *n; i1 = 2; i2 = 1; } else { mi = *m; ni = *n - 1; i1 = 1; i2 = 2; } i__1 = nq - 1; zunmqr_(side, trans, &mi, &ni, &i__1, &a[a_dim1 + 2], lda, &tau[1] , &c__[i1 + i2 * c_dim1], ldc, &work[1], lwork, &iinfo); } } else { /* Apply P */ if (notran) { *(unsigned char *)transt = 'C'; } else { *(unsigned char *)transt = 'N'; } if (nq > *k) { /* P was determined by a call to ZGEBRD with nq > k */ zunmlq_(side, transt, m, n, k, &a[a_offset], lda, &tau[1], &c__[ c_offset], ldc, &work[1], lwork, &iinfo); } else if (nq > 1) { /* P was determined by a call to ZGEBRD with nq <= k */ if (left) { mi = *m - 1; ni = *n; i1 = 2; i2 = 1; } else { mi = *m; ni = *n - 1; i1 = 1; i2 = 2; } i__1 = nq - 1; zunmlq_(side, transt, &mi, &ni, &i__1, &a[((a_dim1) << (1)) + 1], lda, &tau[1], &c__[i1 + i2 * c_dim1], ldc, &work[1], lwork, &iinfo); } } work[1].r = (doublereal) lwkopt, work[1].i = 0.; return 0; /* End of ZUNMBR */ } /* zunmbr_ */ /* Subroutine */ int zunml2_(char *side, char *trans, integer *m, integer *n, integer *k, doublecomplex *a, integer *lda, doublecomplex *tau, doublecomplex *c__, integer *ldc, doublecomplex *work, integer *info) { /* System generated locals */ integer a_dim1, a_offset, c_dim1, c_offset, i__1, i__2, i__3; doublecomplex z__1; /* Builtin functions */ void d_cnjg(doublecomplex *, doublecomplex *); /* Local variables */ static integer i__, i1, i2, i3, ic, jc, mi, ni, nq; static doublecomplex aii; static logical left; static doublecomplex taui; extern logical lsame_(char *, char *); extern /* Subroutine */ int zlarf_(char *, integer *, integer *, doublecomplex *, integer *, doublecomplex *, doublecomplex *, integer *, doublecomplex *), xerbla_(char *, integer *), zlacgv_(integer *, doublecomplex *, integer *); static logical notran; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University September 30, 1994 Purpose ======= ZUNML2 overwrites the general complex m-by-n matrix C with Q * C if SIDE = 'L' and TRANS = 'N', or Q'* C if SIDE = 'L' and TRANS = 'C', or C * Q if SIDE = 'R' and TRANS = 'N', or C * Q' if SIDE = 'R' and TRANS = 'C', where Q is a complex unitary matrix defined as the product of k elementary reflectors Q = H(k)' . . . H(2)' H(1)' as returned by ZGELQF. Q is of order m if SIDE = 'L' and of order n if SIDE = 'R'. Arguments ========= SIDE (input) CHARACTER*1 = 'L': apply Q or Q' from the Left = 'R': apply Q or Q' from the Right TRANS (input) CHARACTER*1 = 'N': apply Q (No transpose) = 'C': apply Q' (Conjugate transpose) M (input) INTEGER The number of rows of the matrix C. M >= 0. N (input) INTEGER The number of columns of the matrix C. N >= 0. K (input) INTEGER The number of elementary reflectors whose product defines the matrix Q. If SIDE = 'L', M >= K >= 0; if SIDE = 'R', N >= K >= 0. A (input) COMPLEX*16 array, dimension (LDA,M) if SIDE = 'L', (LDA,N) if SIDE = 'R' The i-th row must contain the vector which defines the elementary reflector H(i), for i = 1,2,...,k, as returned by ZGELQF in the first k rows of its array argument A. A is modified by the routine but restored on exit. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,K). TAU (input) COMPLEX*16 array, dimension (K) TAU(i) must contain the scalar factor of the elementary reflector H(i), as returned by ZGELQF. C (input/output) COMPLEX*16 array, dimension (LDC,N) On entry, the m-by-n matrix C. On exit, C is overwritten by Q*C or Q'*C or C*Q' or C*Q. LDC (input) INTEGER The leading dimension of the array C. LDC >= max(1,M). WORK (workspace) COMPLEX*16 array, dimension (N) if SIDE = 'L', (M) if SIDE = 'R' INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value ===================================================================== Test the input arguments */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --tau; c_dim1 = *ldc; c_offset = 1 + c_dim1; c__ -= c_offset; --work; /* Function Body */ *info = 0; left = lsame_(side, "L"); notran = lsame_(trans, "N"); /* NQ is the order of Q */ if (left) { nq = *m; } else { nq = *n; } if (! left && ! lsame_(side, "R")) { *info = -1; } else if (! notran && ! lsame_(trans, "C")) { *info = -2; } else if (*m < 0) { *info = -3; } else if (*n < 0) { *info = -4; } else if ((*k < 0) || (*k > nq)) { *info = -5; } else if (*lda < max(1,*k)) { *info = -7; } else if (*ldc < max(1,*m)) { *info = -10; } if (*info != 0) { i__1 = -(*info); xerbla_("ZUNML2", &i__1); return 0; } /* Quick return if possible */ if (((*m == 0) || (*n == 0)) || (*k == 0)) { return 0; } if ((left && notran) || (! left && ! notran)) { i1 = 1; i2 = *k; i3 = 1; } else { i1 = *k; i2 = 1; i3 = -1; } if (left) { ni = *n; jc = 1; } else { mi = *m; ic = 1; } i__1 = i2; i__2 = i3; for (i__ = i1; i__2 < 0 ? i__ >= i__1 : i__ <= i__1; i__ += i__2) { if (left) { /* H(i) or H(i)' is applied to C(i:m,1:n) */ mi = *m - i__ + 1; ic = i__; } else { /* H(i) or H(i)' is applied to C(1:m,i:n) */ ni = *n - i__ + 1; jc = i__; } /* Apply H(i) or H(i)' */ if (notran) { d_cnjg(&z__1, &tau[i__]); taui.r = z__1.r, taui.i = z__1.i; } else { i__3 = i__; taui.r = tau[i__3].r, taui.i = tau[i__3].i; } if (i__ < nq) { i__3 = nq - i__; zlacgv_(&i__3, &a[i__ + (i__ + 1) * a_dim1], lda); } i__3 = i__ + i__ * a_dim1; aii.r = a[i__3].r, aii.i = a[i__3].i; i__3 = i__ + i__ * a_dim1; a[i__3].r = 1., a[i__3].i = 0.; zlarf_(side, &mi, &ni, &a[i__ + i__ * a_dim1], lda, &taui, &c__[ic + jc * c_dim1], ldc, &work[1]); i__3 = i__ + i__ * a_dim1; a[i__3].r = aii.r, a[i__3].i = aii.i; if (i__ < nq) { i__3 = nq - i__; zlacgv_(&i__3, &a[i__ + (i__ + 1) * a_dim1], lda); } /* L10: */ } return 0; /* End of ZUNML2 */ } /* zunml2_ */ /* Subroutine */ int zunmlq_(char *side, char *trans, integer *m, integer *n, integer *k, doublecomplex *a, integer *lda, doublecomplex *tau, doublecomplex *c__, integer *ldc, doublecomplex *work, integer *lwork, integer *info) { /* System generated locals */ address a__1[2]; integer a_dim1, a_offset, c_dim1, c_offset, i__1, i__2, i__3[2], i__4, i__5; char ch__1[2]; /* Builtin functions */ /* Subroutine */ int s_cat(char *, char **, integer *, integer *, ftnlen); /* Local variables */ static integer i__; static doublecomplex t[4160] /* was [65][64] */; static integer i1, i2, i3, ib, ic, jc, nb, mi, ni, nq, nw, iws; static logical left; extern logical lsame_(char *, char *); static integer nbmin, iinfo; extern /* Subroutine */ int zunml2_(char *, char *, integer *, integer *, integer *, doublecomplex *, integer *, doublecomplex *, doublecomplex *, integer *, doublecomplex *, integer *), xerbla_(char *, integer *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); extern /* Subroutine */ int zlarfb_(char *, char *, char *, char *, integer *, integer *, integer *, doublecomplex *, integer *, doublecomplex *, integer *, doublecomplex *, integer *, doublecomplex *, integer *); static logical notran; static integer ldwork; extern /* Subroutine */ int zlarft_(char *, char *, integer *, integer *, doublecomplex *, integer *, doublecomplex *, doublecomplex *, integer *); static char transt[1]; static integer lwkopt; static logical lquery; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= ZUNMLQ overwrites the general complex M-by-N matrix C with SIDE = 'L' SIDE = 'R' TRANS = 'N': Q * C C * Q TRANS = 'C': Q**H * C C * Q**H where Q is a complex unitary matrix defined as the product of k elementary reflectors Q = H(k)' . . . H(2)' H(1)' as returned by ZGELQF. Q is of order M if SIDE = 'L' and of order N if SIDE = 'R'. Arguments ========= SIDE (input) CHARACTER*1 = 'L': apply Q or Q**H from the Left; = 'R': apply Q or Q**H from the Right. TRANS (input) CHARACTER*1 = 'N': No transpose, apply Q; = 'C': Conjugate transpose, apply Q**H. M (input) INTEGER The number of rows of the matrix C. M >= 0. N (input) INTEGER The number of columns of the matrix C. N >= 0. K (input) INTEGER The number of elementary reflectors whose product defines the matrix Q. If SIDE = 'L', M >= K >= 0; if SIDE = 'R', N >= K >= 0. A (input) COMPLEX*16 array, dimension (LDA,M) if SIDE = 'L', (LDA,N) if SIDE = 'R' The i-th row must contain the vector which defines the elementary reflector H(i), for i = 1,2,...,k, as returned by ZGELQF in the first k rows of its array argument A. A is modified by the routine but restored on exit. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,K). TAU (input) COMPLEX*16 array, dimension (K) TAU(i) must contain the scalar factor of the elementary reflector H(i), as returned by ZGELQF. C (input/output) COMPLEX*16 array, dimension (LDC,N) On entry, the M-by-N matrix C. On exit, C is overwritten by Q*C or Q**H*C or C*Q**H or C*Q. LDC (input) INTEGER The leading dimension of the array C. LDC >= max(1,M). WORK (workspace/output) COMPLEX*16 array, dimension (LWORK) On exit, if INFO = 0, WORK(1) returns the optimal LWORK. LWORK (input) INTEGER The dimension of the array WORK. If SIDE = 'L', LWORK >= max(1,N); if SIDE = 'R', LWORK >= max(1,M). For optimum performance LWORK >= N*NB if SIDE 'L', and LWORK >= M*NB if SIDE = 'R', where NB is the optimal blocksize. If LWORK = -1, then a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued by XERBLA. INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value ===================================================================== Test the input arguments */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --tau; c_dim1 = *ldc; c_offset = 1 + c_dim1; c__ -= c_offset; --work; /* Function Body */ *info = 0; left = lsame_(side, "L"); notran = lsame_(trans, "N"); lquery = *lwork == -1; /* NQ is the order of Q and NW is the minimum dimension of WORK */ if (left) { nq = *m; nw = *n; } else { nq = *n; nw = *m; } if (! left && ! lsame_(side, "R")) { *info = -1; } else if (! notran && ! lsame_(trans, "C")) { *info = -2; } else if (*m < 0) { *info = -3; } else if (*n < 0) { *info = -4; } else if ((*k < 0) || (*k > nq)) { *info = -5; } else if (*lda < max(1,*k)) { *info = -7; } else if (*ldc < max(1,*m)) { *info = -10; } else if (*lwork < max(1,nw) && ! lquery) { *info = -12; } if (*info == 0) { /* Determine the block size. NB may be at most NBMAX, where NBMAX is used to define the local array T. Computing MIN Writing concatenation */ i__3[0] = 1, a__1[0] = side; i__3[1] = 1, a__1[1] = trans; s_cat(ch__1, a__1, i__3, &c__2, (ftnlen)2); i__1 = 64, i__2 = ilaenv_(&c__1, "ZUNMLQ", ch__1, m, n, k, &c_n1, ( ftnlen)6, (ftnlen)2); nb = min(i__1,i__2); lwkopt = max(1,nw) * nb; work[1].r = (doublereal) lwkopt, work[1].i = 0.; } if (*info != 0) { i__1 = -(*info); xerbla_("ZUNMLQ", &i__1); return 0; } else if (lquery) { return 0; } /* Quick return if possible */ if (((*m == 0) || (*n == 0)) || (*k == 0)) { work[1].r = 1., work[1].i = 0.; return 0; } nbmin = 2; ldwork = nw; if (nb > 1 && nb < *k) { iws = nw * nb; if (*lwork < iws) { nb = *lwork / ldwork; /* Computing MAX Writing concatenation */ i__3[0] = 1, a__1[0] = side; i__3[1] = 1, a__1[1] = trans; s_cat(ch__1, a__1, i__3, &c__2, (ftnlen)2); i__1 = 2, i__2 = ilaenv_(&c__2, "ZUNMLQ", ch__1, m, n, k, &c_n1, ( ftnlen)6, (ftnlen)2); nbmin = max(i__1,i__2); } } else { iws = nw; } if ((nb < nbmin) || (nb >= *k)) { /* Use unblocked code */ zunml2_(side, trans, m, n, k, &a[a_offset], lda, &tau[1], &c__[ c_offset], ldc, &work[1], &iinfo); } else { /* Use blocked code */ if ((left && notran) || (! left && ! notran)) { i1 = 1; i2 = *k; i3 = nb; } else { i1 = (*k - 1) / nb * nb + 1; i2 = 1; i3 = -nb; } if (left) { ni = *n; jc = 1; } else { mi = *m; ic = 1; } if (notran) { *(unsigned char *)transt = 'C'; } else { *(unsigned char *)transt = 'N'; } i__1 = i2; i__2 = i3; for (i__ = i1; i__2 < 0 ? i__ >= i__1 : i__ <= i__1; i__ += i__2) { /* Computing MIN */ i__4 = nb, i__5 = *k - i__ + 1; ib = min(i__4,i__5); /* Form the triangular factor of the block reflector H = H(i) H(i+1) . . . H(i+ib-1) */ i__4 = nq - i__ + 1; zlarft_("Forward", "Rowwise", &i__4, &ib, &a[i__ + i__ * a_dim1], lda, &tau[i__], t, &c__65); if (left) { /* H or H' is applied to C(i:m,1:n) */ mi = *m - i__ + 1; ic = i__; } else { /* H or H' is applied to C(1:m,i:n) */ ni = *n - i__ + 1; jc = i__; } /* Apply H or H' */ zlarfb_(side, transt, "Forward", "Rowwise", &mi, &ni, &ib, &a[i__ + i__ * a_dim1], lda, t, &c__65, &c__[ic + jc * c_dim1], ldc, &work[1], &ldwork); /* L10: */ } } work[1].r = (doublereal) lwkopt, work[1].i = 0.; return 0; /* End of ZUNMLQ */ } /* zunmlq_ */ /* Subroutine */ int zunmql_(char *side, char *trans, integer *m, integer *n, integer *k, doublecomplex *a, integer *lda, doublecomplex *tau, doublecomplex *c__, integer *ldc, doublecomplex *work, integer *lwork, integer *info) { /* System generated locals */ address a__1[2]; integer a_dim1, a_offset, c_dim1, c_offset, i__1, i__2, i__3[2], i__4, i__5; char ch__1[2]; /* Builtin functions */ /* Subroutine */ int s_cat(char *, char **, integer *, integer *, ftnlen); /* Local variables */ static integer i__; static doublecomplex t[4160] /* was [65][64] */; static integer i1, i2, i3, ib, nb, mi, ni, nq, nw, iws; static logical left; extern logical lsame_(char *, char *); static integer nbmin, iinfo; extern /* Subroutine */ int zunm2l_(char *, char *, integer *, integer *, integer *, doublecomplex *, integer *, doublecomplex *, doublecomplex *, integer *, doublecomplex *, integer *), xerbla_(char *, integer *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); extern /* Subroutine */ int zlarfb_(char *, char *, char *, char *, integer *, integer *, integer *, doublecomplex *, integer *, doublecomplex *, integer *, doublecomplex *, integer *, doublecomplex *, integer *); static logical notran; static integer ldwork; extern /* Subroutine */ int zlarft_(char *, char *, integer *, integer *, doublecomplex *, integer *, doublecomplex *, doublecomplex *, integer *); static integer lwkopt; static logical lquery; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= ZUNMQL overwrites the general complex M-by-N matrix C with SIDE = 'L' SIDE = 'R' TRANS = 'N': Q * C C * Q TRANS = 'C': Q**H * C C * Q**H where Q is a complex unitary matrix defined as the product of k elementary reflectors Q = H(k) . . . H(2) H(1) as returned by ZGEQLF. Q is of order M if SIDE = 'L' and of order N if SIDE = 'R'. Arguments ========= SIDE (input) CHARACTER*1 = 'L': apply Q or Q**H from the Left; = 'R': apply Q or Q**H from the Right. TRANS (input) CHARACTER*1 = 'N': No transpose, apply Q; = 'C': Transpose, apply Q**H. M (input) INTEGER The number of rows of the matrix C. M >= 0. N (input) INTEGER The number of columns of the matrix C. N >= 0. K (input) INTEGER The number of elementary reflectors whose product defines the matrix Q. If SIDE = 'L', M >= K >= 0; if SIDE = 'R', N >= K >= 0. A (input) COMPLEX*16 array, dimension (LDA,K) The i-th column must contain the vector which defines the elementary reflector H(i), for i = 1,2,...,k, as returned by ZGEQLF in the last k columns of its array argument A. A is modified by the routine but restored on exit. LDA (input) INTEGER The leading dimension of the array A. If SIDE = 'L', LDA >= max(1,M); if SIDE = 'R', LDA >= max(1,N). TAU (input) COMPLEX*16 array, dimension (K) TAU(i) must contain the scalar factor of the elementary reflector H(i), as returned by ZGEQLF. C (input/output) COMPLEX*16 array, dimension (LDC,N) On entry, the M-by-N matrix C. On exit, C is overwritten by Q*C or Q**H*C or C*Q**H or C*Q. LDC (input) INTEGER The leading dimension of the array C. LDC >= max(1,M). WORK (workspace/output) COMPLEX*16 array, dimension (LWORK) On exit, if INFO = 0, WORK(1) returns the optimal LWORK. LWORK (input) INTEGER The dimension of the array WORK. If SIDE = 'L', LWORK >= max(1,N); if SIDE = 'R', LWORK >= max(1,M). For optimum performance LWORK >= N*NB if SIDE = 'L', and LWORK >= M*NB if SIDE = 'R', where NB is the optimal blocksize. If LWORK = -1, then a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued by XERBLA. INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value ===================================================================== Test the input arguments */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --tau; c_dim1 = *ldc; c_offset = 1 + c_dim1; c__ -= c_offset; --work; /* Function Body */ *info = 0; left = lsame_(side, "L"); notran = lsame_(trans, "N"); lquery = *lwork == -1; /* NQ is the order of Q and NW is the minimum dimension of WORK */ if (left) { nq = *m; nw = *n; } else { nq = *n; nw = *m; } if (! left && ! lsame_(side, "R")) { *info = -1; } else if (! notran && ! lsame_(trans, "C")) { *info = -2; } else if (*m < 0) { *info = -3; } else if (*n < 0) { *info = -4; } else if ((*k < 0) || (*k > nq)) { *info = -5; } else if (*lda < max(1,nq)) { *info = -7; } else if (*ldc < max(1,*m)) { *info = -10; } else if (*lwork < max(1,nw) && ! lquery) { *info = -12; } if (*info == 0) { /* Determine the block size. NB may be at most NBMAX, where NBMAX is used to define the local array T. Computing MIN Writing concatenation */ i__3[0] = 1, a__1[0] = side; i__3[1] = 1, a__1[1] = trans; s_cat(ch__1, a__1, i__3, &c__2, (ftnlen)2); i__1 = 64, i__2 = ilaenv_(&c__1, "ZUNMQL", ch__1, m, n, k, &c_n1, ( ftnlen)6, (ftnlen)2); nb = min(i__1,i__2); lwkopt = max(1,nw) * nb; work[1].r = (doublereal) lwkopt, work[1].i = 0.; } if (*info != 0) { i__1 = -(*info); xerbla_("ZUNMQL", &i__1); return 0; } else if (lquery) { return 0; } /* Quick return if possible */ if (((*m == 0) || (*n == 0)) || (*k == 0)) { work[1].r = 1., work[1].i = 0.; return 0; } nbmin = 2; ldwork = nw; if (nb > 1 && nb < *k) { iws = nw * nb; if (*lwork < iws) { nb = *lwork / ldwork; /* Computing MAX Writing concatenation */ i__3[0] = 1, a__1[0] = side; i__3[1] = 1, a__1[1] = trans; s_cat(ch__1, a__1, i__3, &c__2, (ftnlen)2); i__1 = 2, i__2 = ilaenv_(&c__2, "ZUNMQL", ch__1, m, n, k, &c_n1, ( ftnlen)6, (ftnlen)2); nbmin = max(i__1,i__2); } } else { iws = nw; } if ((nb < nbmin) || (nb >= *k)) { /* Use unblocked code */ zunm2l_(side, trans, m, n, k, &a[a_offset], lda, &tau[1], &c__[ c_offset], ldc, &work[1], &iinfo); } else { /* Use blocked code */ if ((left && notran) || (! left && ! notran)) { i1 = 1; i2 = *k; i3 = nb; } else { i1 = (*k - 1) / nb * nb + 1; i2 = 1; i3 = -nb; } if (left) { ni = *n; } else { mi = *m; } i__1 = i2; i__2 = i3; for (i__ = i1; i__2 < 0 ? i__ >= i__1 : i__ <= i__1; i__ += i__2) { /* Computing MIN */ i__4 = nb, i__5 = *k - i__ + 1; ib = min(i__4,i__5); /* Form the triangular factor of the block reflector H = H(i+ib-1) . . . H(i+1) H(i) */ i__4 = nq - *k + i__ + ib - 1; zlarft_("Backward", "Columnwise", &i__4, &ib, &a[i__ * a_dim1 + 1] , lda, &tau[i__], t, &c__65); if (left) { /* H or H' is applied to C(1:m-k+i+ib-1,1:n) */ mi = *m - *k + i__ + ib - 1; } else { /* H or H' is applied to C(1:m,1:n-k+i+ib-1) */ ni = *n - *k + i__ + ib - 1; } /* Apply H or H' */ zlarfb_(side, trans, "Backward", "Columnwise", &mi, &ni, &ib, &a[ i__ * a_dim1 + 1], lda, t, &c__65, &c__[c_offset], ldc, & work[1], &ldwork); /* L10: */ } } work[1].r = (doublereal) lwkopt, work[1].i = 0.; return 0; /* End of ZUNMQL */ } /* zunmql_ */ /* Subroutine */ int zunmqr_(char *side, char *trans, integer *m, integer *n, integer *k, doublecomplex *a, integer *lda, doublecomplex *tau, doublecomplex *c__, integer *ldc, doublecomplex *work, integer *lwork, integer *info) { /* System generated locals */ address a__1[2]; integer a_dim1, a_offset, c_dim1, c_offset, i__1, i__2, i__3[2], i__4, i__5; char ch__1[2]; /* Builtin functions */ /* Subroutine */ int s_cat(char *, char **, integer *, integer *, ftnlen); /* Local variables */ static integer i__; static doublecomplex t[4160] /* was [65][64] */; static integer i1, i2, i3, ib, ic, jc, nb, mi, ni, nq, nw, iws; static logical left; extern logical lsame_(char *, char *); static integer nbmin, iinfo; extern /* Subroutine */ int zunm2r_(char *, char *, integer *, integer *, integer *, doublecomplex *, integer *, doublecomplex *, doublecomplex *, integer *, doublecomplex *, integer *), xerbla_(char *, integer *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); extern /* Subroutine */ int zlarfb_(char *, char *, char *, char *, integer *, integer *, integer *, doublecomplex *, integer *, doublecomplex *, integer *, doublecomplex *, integer *, doublecomplex *, integer *); static logical notran; static integer ldwork; extern /* Subroutine */ int zlarft_(char *, char *, integer *, integer *, doublecomplex *, integer *, doublecomplex *, doublecomplex *, integer *); static integer lwkopt; static logical lquery; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= ZUNMQR overwrites the general complex M-by-N matrix C with SIDE = 'L' SIDE = 'R' TRANS = 'N': Q * C C * Q TRANS = 'C': Q**H * C C * Q**H where Q is a complex unitary matrix defined as the product of k elementary reflectors Q = H(1) H(2) . . . H(k) as returned by ZGEQRF. Q is of order M if SIDE = 'L' and of order N if SIDE = 'R'. Arguments ========= SIDE (input) CHARACTER*1 = 'L': apply Q or Q**H from the Left; = 'R': apply Q or Q**H from the Right. TRANS (input) CHARACTER*1 = 'N': No transpose, apply Q; = 'C': Conjugate transpose, apply Q**H. M (input) INTEGER The number of rows of the matrix C. M >= 0. N (input) INTEGER The number of columns of the matrix C. N >= 0. K (input) INTEGER The number of elementary reflectors whose product defines the matrix Q. If SIDE = 'L', M >= K >= 0; if SIDE = 'R', N >= K >= 0. A (input) COMPLEX*16 array, dimension (LDA,K) The i-th column must contain the vector which defines the elementary reflector H(i), for i = 1,2,...,k, as returned by ZGEQRF in the first k columns of its array argument A. A is modified by the routine but restored on exit. LDA (input) INTEGER The leading dimension of the array A. If SIDE = 'L', LDA >= max(1,M); if SIDE = 'R', LDA >= max(1,N). TAU (input) COMPLEX*16 array, dimension (K) TAU(i) must contain the scalar factor of the elementary reflector H(i), as returned by ZGEQRF. C (input/output) COMPLEX*16 array, dimension (LDC,N) On entry, the M-by-N matrix C. On exit, C is overwritten by Q*C or Q**H*C or C*Q**H or C*Q. LDC (input) INTEGER The leading dimension of the array C. LDC >= max(1,M). WORK (workspace/output) COMPLEX*16 array, dimension (LWORK) On exit, if INFO = 0, WORK(1) returns the optimal LWORK. LWORK (input) INTEGER The dimension of the array WORK. If SIDE = 'L', LWORK >= max(1,N); if SIDE = 'R', LWORK >= max(1,M). For optimum performance LWORK >= N*NB if SIDE = 'L', and LWORK >= M*NB if SIDE = 'R', where NB is the optimal blocksize. If LWORK = -1, then a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued by XERBLA. INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value ===================================================================== Test the input arguments */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --tau; c_dim1 = *ldc; c_offset = 1 + c_dim1; c__ -= c_offset; --work; /* Function Body */ *info = 0; left = lsame_(side, "L"); notran = lsame_(trans, "N"); lquery = *lwork == -1; /* NQ is the order of Q and NW is the minimum dimension of WORK */ if (left) { nq = *m; nw = *n; } else { nq = *n; nw = *m; } if (! left && ! lsame_(side, "R")) { *info = -1; } else if (! notran && ! lsame_(trans, "C")) { *info = -2; } else if (*m < 0) { *info = -3; } else if (*n < 0) { *info = -4; } else if ((*k < 0) || (*k > nq)) { *info = -5; } else if (*lda < max(1,nq)) { *info = -7; } else if (*ldc < max(1,*m)) { *info = -10; } else if (*lwork < max(1,nw) && ! lquery) { *info = -12; } if (*info == 0) { /* Determine the block size. NB may be at most NBMAX, where NBMAX is used to define the local array T. Computing MIN Writing concatenation */ i__3[0] = 1, a__1[0] = side; i__3[1] = 1, a__1[1] = trans; s_cat(ch__1, a__1, i__3, &c__2, (ftnlen)2); i__1 = 64, i__2 = ilaenv_(&c__1, "ZUNMQR", ch__1, m, n, k, &c_n1, ( ftnlen)6, (ftnlen)2); nb = min(i__1,i__2); lwkopt = max(1,nw) * nb; work[1].r = (doublereal) lwkopt, work[1].i = 0.; } if (*info != 0) { i__1 = -(*info); xerbla_("ZUNMQR", &i__1); return 0; } else if (lquery) { return 0; } /* Quick return if possible */ if (((*m == 0) || (*n == 0)) || (*k == 0)) { work[1].r = 1., work[1].i = 0.; return 0; } nbmin = 2; ldwork = nw; if (nb > 1 && nb < *k) { iws = nw * nb; if (*lwork < iws) { nb = *lwork / ldwork; /* Computing MAX Writing concatenation */ i__3[0] = 1, a__1[0] = side; i__3[1] = 1, a__1[1] = trans; s_cat(ch__1, a__1, i__3, &c__2, (ftnlen)2); i__1 = 2, i__2 = ilaenv_(&c__2, "ZUNMQR", ch__1, m, n, k, &c_n1, ( ftnlen)6, (ftnlen)2); nbmin = max(i__1,i__2); } } else { iws = nw; } if ((nb < nbmin) || (nb >= *k)) { /* Use unblocked code */ zunm2r_(side, trans, m, n, k, &a[a_offset], lda, &tau[1], &c__[ c_offset], ldc, &work[1], &iinfo); } else { /* Use blocked code */ if ((left && ! notran) || (! left && notran)) { i1 = 1; i2 = *k; i3 = nb; } else { i1 = (*k - 1) / nb * nb + 1; i2 = 1; i3 = -nb; } if (left) { ni = *n; jc = 1; } else { mi = *m; ic = 1; } i__1 = i2; i__2 = i3; for (i__ = i1; i__2 < 0 ? i__ >= i__1 : i__ <= i__1; i__ += i__2) { /* Computing MIN */ i__4 = nb, i__5 = *k - i__ + 1; ib = min(i__4,i__5); /* Form the triangular factor of the block reflector H = H(i) H(i+1) . . . H(i+ib-1) */ i__4 = nq - i__ + 1; zlarft_("Forward", "Columnwise", &i__4, &ib, &a[i__ + i__ * a_dim1], lda, &tau[i__], t, &c__65) ; if (left) { /* H or H' is applied to C(i:m,1:n) */ mi = *m - i__ + 1; ic = i__; } else { /* H or H' is applied to C(1:m,i:n) */ ni = *n - i__ + 1; jc = i__; } /* Apply H or H' */ zlarfb_(side, trans, "Forward", "Columnwise", &mi, &ni, &ib, &a[ i__ + i__ * a_dim1], lda, t, &c__65, &c__[ic + jc * c_dim1], ldc, &work[1], &ldwork); /* L10: */ } } work[1].r = (doublereal) lwkopt, work[1].i = 0.; return 0; /* End of ZUNMQR */ } /* zunmqr_ */ /* Subroutine */ int zunmtr_(char *side, char *uplo, char *trans, integer *m, integer *n, doublecomplex *a, integer *lda, doublecomplex *tau, doublecomplex *c__, integer *ldc, doublecomplex *work, integer *lwork, integer *info) { /* System generated locals */ address a__1[2]; integer a_dim1, a_offset, c_dim1, c_offset, i__1[2], i__2, i__3; char ch__1[2]; /* Builtin functions */ /* Subroutine */ int s_cat(char *, char **, integer *, integer *, ftnlen); /* Local variables */ static integer i1, i2, nb, mi, ni, nq, nw; static logical left; extern logical lsame_(char *, char *); static integer iinfo; static logical upper; extern /* Subroutine */ int xerbla_(char *, integer *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); static integer lwkopt; static logical lquery; extern /* Subroutine */ int zunmql_(char *, char *, integer *, integer *, integer *, doublecomplex *, integer *, doublecomplex *, doublecomplex *, integer *, doublecomplex *, integer *, integer *), zunmqr_(char *, char *, integer *, integer *, integer *, doublecomplex *, integer *, doublecomplex *, doublecomplex *, integer *, doublecomplex *, integer *, integer *); /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= ZUNMTR overwrites the general complex M-by-N matrix C with SIDE = 'L' SIDE = 'R' TRANS = 'N': Q * C C * Q TRANS = 'C': Q**H * C C * Q**H where Q is a complex unitary matrix of order nq, with nq = m if SIDE = 'L' and nq = n if SIDE = 'R'. Q is defined as the product of nq-1 elementary reflectors, as returned by ZHETRD: if UPLO = 'U', Q = H(nq-1) . . . H(2) H(1); if UPLO = 'L', Q = H(1) H(2) . . . H(nq-1). Arguments ========= SIDE (input) CHARACTER*1 = 'L': apply Q or Q**H from the Left; = 'R': apply Q or Q**H from the Right. UPLO (input) CHARACTER*1 = 'U': Upper triangle of A contains elementary reflectors from ZHETRD; = 'L': Lower triangle of A contains elementary reflectors from ZHETRD. TRANS (input) CHARACTER*1 = 'N': No transpose, apply Q; = 'C': Conjugate transpose, apply Q**H. M (input) INTEGER The number of rows of the matrix C. M >= 0. N (input) INTEGER The number of columns of the matrix C. N >= 0. A (input) COMPLEX*16 array, dimension (LDA,M) if SIDE = 'L' (LDA,N) if SIDE = 'R' The vectors which define the elementary reflectors, as returned by ZHETRD. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,M) if SIDE = 'L'; LDA >= max(1,N) if SIDE = 'R'. TAU (input) COMPLEX*16 array, dimension (M-1) if SIDE = 'L' (N-1) if SIDE = 'R' TAU(i) must contain the scalar factor of the elementary reflector H(i), as returned by ZHETRD. C (input/output) COMPLEX*16 array, dimension (LDC,N) On entry, the M-by-N matrix C. On exit, C is overwritten by Q*C or Q**H*C or C*Q**H or C*Q. LDC (input) INTEGER The leading dimension of the array C. LDC >= max(1,M). WORK (workspace/output) COMPLEX*16 array, dimension (LWORK) On exit, if INFO = 0, WORK(1) returns the optimal LWORK. LWORK (input) INTEGER The dimension of the array WORK. If SIDE = 'L', LWORK >= max(1,N); if SIDE = 'R', LWORK >= max(1,M). For optimum performance LWORK >= N*NB if SIDE = 'L', and LWORK >=M*NB if SIDE = 'R', where NB is the optimal blocksize. If LWORK = -1, then a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued by XERBLA. INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value ===================================================================== Test the input arguments */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --tau; c_dim1 = *ldc; c_offset = 1 + c_dim1; c__ -= c_offset; --work; /* Function Body */ *info = 0; left = lsame_(side, "L"); upper = lsame_(uplo, "U"); lquery = *lwork == -1; /* NQ is the order of Q and NW is the minimum dimension of WORK */ if (left) { nq = *m; nw = *n; } else { nq = *n; nw = *m; } if (! left && ! lsame_(side, "R")) { *info = -1; } else if (! upper && ! lsame_(uplo, "L")) { *info = -2; } else if (! lsame_(trans, "N") && ! lsame_(trans, "C")) { *info = -3; } else if (*m < 0) { *info = -4; } else if (*n < 0) { *info = -5; } else if (*lda < max(1,nq)) { *info = -7; } else if (*ldc < max(1,*m)) { *info = -10; } else if (*lwork < max(1,nw) && ! lquery) { *info = -12; } if (*info == 0) { if (upper) { if (left) { /* Writing concatenation */ i__1[0] = 1, a__1[0] = side; i__1[1] = 1, a__1[1] = trans; s_cat(ch__1, a__1, i__1, &c__2, (ftnlen)2); i__2 = *m - 1; i__3 = *m - 1; nb = ilaenv_(&c__1, "ZUNMQL", ch__1, &i__2, n, &i__3, &c_n1, ( ftnlen)6, (ftnlen)2); } else { /* Writing concatenation */ i__1[0] = 1, a__1[0] = side; i__1[1] = 1, a__1[1] = trans; s_cat(ch__1, a__1, i__1, &c__2, (ftnlen)2); i__2 = *n - 1; i__3 = *n - 1; nb = ilaenv_(&c__1, "ZUNMQL", ch__1, m, &i__2, &i__3, &c_n1, ( ftnlen)6, (ftnlen)2); } } else { if (left) { /* Writing concatenation */ i__1[0] = 1, a__1[0] = side; i__1[1] = 1, a__1[1] = trans; s_cat(ch__1, a__1, i__1, &c__2, (ftnlen)2); i__2 = *m - 1; i__3 = *m - 1; nb = ilaenv_(&c__1, "ZUNMQR", ch__1, &i__2, n, &i__3, &c_n1, ( ftnlen)6, (ftnlen)2); } else { /* Writing concatenation */ i__1[0] = 1, a__1[0] = side; i__1[1] = 1, a__1[1] = trans; s_cat(ch__1, a__1, i__1, &c__2, (ftnlen)2); i__2 = *n - 1; i__3 = *n - 1; nb = ilaenv_(&c__1, "ZUNMQR", ch__1, m, &i__2, &i__3, &c_n1, ( ftnlen)6, (ftnlen)2); } } lwkopt = max(1,nw) * nb; work[1].r = (doublereal) lwkopt, work[1].i = 0.; } if (*info != 0) { i__2 = -(*info); xerbla_("ZUNMTR", &i__2); return 0; } else if (lquery) { return 0; } /* Quick return if possible */ if (((*m == 0) || (*n == 0)) || (nq == 1)) { work[1].r = 1., work[1].i = 0.; return 0; } if (left) { mi = *m - 1; ni = *n; } else { mi = *m; ni = *n - 1; } if (upper) { /* Q was determined by a call to ZHETRD with UPLO = 'U' */ i__2 = nq - 1; zunmql_(side, trans, &mi, &ni, &i__2, &a[((a_dim1) << (1)) + 1], lda, &tau[1], &c__[c_offset], ldc, &work[1], lwork, &iinfo); } else { /* Q was determined by a call to ZHETRD with UPLO = 'L' */ if (left) { i1 = 2; i2 = 1; } else { i1 = 1; i2 = 2; } i__2 = nq - 1; zunmqr_(side, trans, &mi, &ni, &i__2, &a[a_dim1 + 2], lda, &tau[1], & c__[i1 + i2 * c_dim1], ldc, &work[1], lwork, &iinfo); } work[1].r = (doublereal) lwkopt, work[1].i = 0.; return 0; /* End of ZUNMTR */ } /* zunmtr_ */ numpy-1.8.2/numpy/linalg/lapack_lite/f2c_lite.c0000664000175100017510000002426312370216242022553 0ustar vagrantvagrant00000000000000#include #include #include #include #include "f2c.h" extern void s_wsfe(cilist *f) {;} extern void e_wsfe(void) {;} extern void do_fio(integer *c, char *s, ftnlen l) {;} /* You'll want this if you redo the *_lite.c files with the -C option * to f2c for checking array subscripts. (It's not suggested you do that * for production use, of course.) */ extern int s_rnge(char *var, int index, char *routine, int lineno) { fprintf(stderr, "array index out-of-bounds for %s[%d] in routine %s:%d\n", var, index, routine, lineno); fflush(stderr); abort(); } #ifdef KR_headers extern float sqrtf(); double f__cabsf(real, imag) float real, imag; #else #undef abs double f__cabsf(float real, float imag) #endif { float temp; if(real < 0.0f) real = -real; if(imag < 0.0f) imag = -imag; if(imag > real){ temp = real; real = imag; imag = temp; } if((imag+real) == real) return((float)real); temp = imag/real; temp = real*sqrtf(1.0 + temp*temp); /*overflow!!*/ return(temp); } #ifdef KR_headers extern double sqrt(); double f__cabs(real, imag) double real, imag; #else #undef abs double f__cabs(double real, double imag) #endif { double temp; if(real < 0) real = -real; if(imag < 0) imag = -imag; if(imag > real){ temp = real; real = imag; imag = temp; } if((imag+real) == real) return((double)real); temp = imag/real; temp = real*sqrt(1.0 + temp*temp); /*overflow!!*/ return(temp); } VOID #ifdef KR_headers r_cnjg(r, z) complex *r, *z; #else r_cnjg(complex *r, complex *z) #endif { r->r = z->r; r->i = - z->i; } VOID #ifdef KR_headers d_cnjg(r, z) doublecomplex *r, *z; #else d_cnjg(doublecomplex *r, doublecomplex *z) #endif { r->r = z->r; r->i = - z->i; } #ifdef KR_headers float r_imag(z) complex *z; #else float r_imag(complex *z) #endif { return(z->i); } #ifdef KR_headers double d_imag(z) doublecomplex *z; #else double d_imag(doublecomplex *z) #endif { return(z->i); } #define log10e 0.43429448190325182765 #ifdef KR_headers float logf(); float r_lg10(x) real *x; #else #undef abs float r_lg10(real *x) #endif { return( log10e * logf(*x) ); } #ifdef KR_headers double log(); double d_lg10(x) doublereal *x; #else #undef abs double d_lg10(doublereal *x) #endif { return( log10e * log(*x) ); } #ifdef KR_headers double r_sign(a,b) real *a, *b; #else double r_sign(real *a, real *b) #endif { float x; x = (*a >= 0.0f ? *a : - *a); return( *b >= 0.0f ? x : -x); } #ifdef KR_headers double d_sign(a,b) doublereal *a, *b; #else double d_sign(doublereal *a, doublereal *b) #endif { double x; x = (*a >= 0 ? *a : - *a); return( *b >= 0 ? x : -x); } #ifdef KR_headers double floor(); integer i_dnnt(x) doublereal *x; #else #undef abs integer i_dnnt(doublereal *x) #endif { return( (*x)>=0 ? floor(*x + .5) : -floor(.5 - *x) ); } #ifdef KR_headers double pow(); double pow_dd(ap, bp) doublereal *ap, *bp; #else #undef abs double pow_dd(doublereal *ap, doublereal *bp) #endif { return(pow(*ap, *bp) ); } #ifdef KR_headers double pow_ri(ap, bp) real *ap; integer *bp; #else double pow_ri(real *ap, integer *bp) #endif { float pow, x; integer n; unsigned long u; pow = 1; x = *ap; n = *bp; if(n != 0) { if(n < 0) { n = -n; x = 1.0f/x; } for(u = n; ; ) { if(u & 01) pow *= x; if(u >>= 1) x *= x; else break; } } return(pow); } #ifdef KR_headers double pow_di(ap, bp) doublereal *ap; integer *bp; #else double pow_di(doublereal *ap, integer *bp) #endif { double pow, x; integer n; unsigned long u; pow = 1; x = *ap; n = *bp; if(n != 0) { if(n < 0) { n = -n; x = 1/x; } for(u = n; ; ) { if(u & 01) pow *= x; if(u >>= 1) x *= x; else break; } } return(pow); } /* Unless compiled with -DNO_OVERWRITE, this variant of s_cat allows the * target of a concatenation to appear on its right-hand side (contrary * to the Fortran 77 Standard, but in accordance with Fortran 90). */ #define NO_OVERWRITE #ifndef NO_OVERWRITE #undef abs #ifdef KR_headers extern char *F77_aloc(); extern void free(); extern void exit_(); #else extern char *F77_aloc(ftnlen, char*); #endif #endif /* NO_OVERWRITE */ VOID #ifdef KR_headers s_cat(lp, rpp, rnp, np, ll) char *lp, *rpp[]; ftnlen rnp[], *np, ll; #else s_cat(char *lp, char *rpp[], ftnlen rnp[], ftnlen *np, ftnlen ll) #endif { ftnlen i, nc; char *rp; ftnlen n = *np; #ifndef NO_OVERWRITE ftnlen L, m; char *lp0, *lp1; lp0 = 0; lp1 = lp; L = ll; i = 0; while(i < n) { rp = rpp[i]; m = rnp[i++]; if (rp >= lp1 || rp + m <= lp) { if ((L -= m) <= 0) { n = i; break; } lp1 += m; continue; } lp0 = lp; lp = lp1 = F77_aloc(L = ll, "s_cat"); break; } lp1 = lp; #endif /* NO_OVERWRITE */ for(i = 0 ; i < n ; ++i) { nc = ll; if(rnp[i] < nc) nc = rnp[i]; ll -= nc; rp = rpp[i]; while(--nc >= 0) *lp++ = *rp++; } while(--ll >= 0) *lp++ = ' '; #ifndef NO_OVERWRITE if (lp0) { memmove(lp0, lp1, L); free(lp1); } #endif } /* compare two strings */ #ifdef KR_headers integer s_cmp(a0, b0, la, lb) char *a0, *b0; ftnlen la, lb; #else integer s_cmp(char *a0, char *b0, ftnlen la, ftnlen lb) #endif { register unsigned char *a, *aend, *b, *bend; a = (unsigned char *)a0; b = (unsigned char *)b0; aend = a + la; bend = b + lb; if(la <= lb) { while(a < aend) if(*a != *b) return( *a - *b ); else { ++a; ++b; } while(b < bend) if(*b != ' ') return( ' ' - *b ); else ++b; } else { while(b < bend) if(*a == *b) { ++a; ++b; } else return( *a - *b ); while(a < aend) if(*a != ' ') return(*a - ' '); else ++a; } return(0); } /* Unless compiled with -DNO_OVERWRITE, this variant of s_copy allows the * target of an assignment to appear on its right-hand side (contrary * to the Fortran 77 Standard, but in accordance with Fortran 90), * as in a(2:5) = a(4:7) . */ /* assign strings: a = b */ #ifdef KR_headers VOID s_copy(a, b, la, lb) register char *a, *b; ftnlen la, lb; #else void s_copy(register char *a, register char *b, ftnlen la, ftnlen lb) #endif { register char *aend, *bend; aend = a + la; if(la <= lb) #ifndef NO_OVERWRITE if (a <= b || a >= b + la) #endif while(a < aend) *a++ = *b++; #ifndef NO_OVERWRITE else for(b += la; a < aend; ) *--aend = *--b; #endif else { bend = b + lb; #ifndef NO_OVERWRITE if (a <= b || a >= bend) #endif while(b < bend) *a++ = *b++; #ifndef NO_OVERWRITE else { a += lb; while(b < bend) *--a = *--bend; a += lb; } #endif while(a < aend) *a++ = ' '; } } #ifdef KR_headers double f__cabsf(); double c_abs(z) complex *z; #else double f__cabsf(float, float); double c_abs(complex *z) #endif { return( f__cabsf( z->r, z->i ) ); } #ifdef KR_headers double f__cabs(); double z_abs(z) doublecomplex *z; #else double f__cabs(double, double); double z_abs(doublecomplex *z) #endif { return( f__cabs( z->r, z->i ) ); } #ifdef KR_headers extern void sig_die(); VOID c_div(c, a, b) complex *a, *b, *c; #else extern void sig_die(char*, int); void c_div(complex *c, complex *a, complex *b) #endif { float ratio, den; float abr, abi; if( (abr = b->r) < 0.f) abr = - abr; if( (abi = b->i) < 0.f) abi = - abi; if( abr <= abi ) { /*Let IEEE Infinties handle this ;( */ /*if(abi == 0) sig_die("complex division by zero", 1);*/ ratio = b->r / b->i ; den = b->i * (1 + ratio*ratio); c->r = (a->r*ratio + a->i) / den; c->i = (a->i*ratio - a->r) / den; } else { ratio = b->i / b->r ; den = b->r * (1.f + ratio*ratio); c->r = (a->r + a->i*ratio) / den; c->i = (a->i - a->r*ratio) / den; } } #ifdef KR_headers extern void sig_die(); VOID z_div(c, a, b) doublecomplex *a, *b, *c; #else extern void sig_die(char*, int); void z_div(doublecomplex *c, doublecomplex *a, doublecomplex *b) #endif { double ratio, den; double abr, abi; if( (abr = b->r) < 0.) abr = - abr; if( (abi = b->i) < 0.) abi = - abi; if( abr <= abi ) { /*Let IEEE Infinties handle this ;( */ /*if(abi == 0) sig_die("complex division by zero", 1);*/ ratio = b->r / b->i ; den = b->i * (1 + ratio*ratio); c->r = (a->r*ratio + a->i) / den; c->i = (a->i*ratio - a->r) / den; } else { ratio = b->i / b->r ; den = b->r * (1 + ratio*ratio); c->r = (a->r + a->i*ratio) / den; c->i = (a->i - a->r*ratio) / den; } } #ifdef KR_headers float sqrtf(), f__cabsf(); VOID c_sqrt(r, z) complex *r, *z; #else #undef abs extern double f__cabsf(float, float); void c_sqrt(complex *r, complex *z) #endif { float mag; if( (mag = f__cabsf(z->r, z->i)) == 0.f) r->r = r->i = 0.f; else if(z->r > 0.0f) { r->r = sqrtf(0.5f * (mag + z->r) ); r->i = z->i / r->r / 2.0f; } else { r->i = sqrtf(0.5f * (mag - z->r) ); if(z->i < 0.0f) r->i = - r->i; r->r = z->i / r->i / 2.0f; } } #ifdef KR_headers double sqrt(), f__cabs(); VOID z_sqrt(r, z) doublecomplex *r, *z; #else #undef abs extern double f__cabs(double, double); void z_sqrt(doublecomplex *r, doublecomplex *z) #endif { double mag; if( (mag = f__cabs(z->r, z->i)) == 0.) r->r = r->i = 0.; else if(z->r > 0) { r->r = sqrt(0.5 * (mag + z->r) ); r->i = z->i / r->r / 2; } else { r->i = sqrt(0.5 * (mag - z->r) ); if(z->i < 0) r->i = - r->i; r->r = z->i / r->i / 2; } } #ifdef __cplusplus extern "C" { #endif #ifdef KR_headers integer pow_ii(ap, bp) integer *ap, *bp; #else integer pow_ii(integer *ap, integer *bp) #endif { integer pow, x, n; unsigned long u; x = *ap; n = *bp; if (n <= 0) { if (n == 0 || x == 1) return 1; if (x != -1) return x == 0 ? 1/x : 0; n = -n; } u = n; for(pow = 1; ; ) { if(u & 01) pow *= x; if(u >>= 1) x *= x; else break; } return(pow); } #ifdef __cplusplus } #endif #ifdef KR_headers extern void f_exit(); VOID s_stop(s, n) char *s; ftnlen n; #else #undef abs #undef min #undef max #ifdef __cplusplus extern "C" { #endif #ifdef __cplusplus extern "C" { #endif void f_exit(void); int s_stop(char *s, ftnlen n) #endif { int i; if(n > 0) { fprintf(stderr, "STOP "); for(i = 0; i #include "f2c.h" /* If config.h is available, we only need dlamc3 */ #ifndef HAVE_CONFIG doublereal dlamch_(char *cmach) { /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University October 31, 1992 Purpose ======= DLAMCH determines double precision machine parameters. Arguments ========= CMACH (input) CHARACTER*1 Specifies the value to be returned by DLAMCH: = 'E' or 'e', DLAMCH := eps = 'S' or 's , DLAMCH := sfmin = 'B' or 'b', DLAMCH := base = 'P' or 'p', DLAMCH := eps*base = 'N' or 'n', DLAMCH := t = 'R' or 'r', DLAMCH := rnd = 'M' or 'm', DLAMCH := emin = 'U' or 'u', DLAMCH := rmin = 'L' or 'l', DLAMCH := emax = 'O' or 'o', DLAMCH := rmax where eps = relative machine precision sfmin = safe minimum, such that 1/sfmin does not overflow base = base of the machine prec = eps*base t = number of (base) digits in the mantissa rnd = 1.0 when rounding occurs in addition, 0.0 otherwise emin = minimum exponent before (gradual) underflow rmin = underflow threshold - base**(emin-1) emax = largest exponent before overflow rmax = overflow threshold - (base**emax)*(1-eps) ===================================================================== */ /* >>Start of File<< Initialized data */ static logical first = TRUE_; /* System generated locals */ integer i__1; doublereal ret_val; /* Builtin functions */ double pow_di(doublereal *, integer *); /* Local variables */ static doublereal base; static integer beta; static doublereal emin, prec, emax; static integer imin, imax; static logical lrnd; static doublereal rmin, rmax, t, rmach; extern logical lsame_(char *, char *); static doublereal small, sfmin; extern /* Subroutine */ int dlamc2_(integer *, integer *, logical *, doublereal *, integer *, doublereal *, integer *, doublereal *); static integer it; static doublereal rnd, eps; if (first) { first = FALSE_; dlamc2_(&beta, &it, &lrnd, &eps, &imin, &rmin, &imax, &rmax); base = (doublereal) beta; t = (doublereal) it; if (lrnd) { rnd = 1.; i__1 = 1 - it; eps = pow_di(&base, &i__1) / 2; } else { rnd = 0.; i__1 = 1 - it; eps = pow_di(&base, &i__1); } prec = eps * base; emin = (doublereal) imin; emax = (doublereal) imax; sfmin = rmin; small = 1. / rmax; if (small >= sfmin) { /* Use SMALL plus a bit, to avoid the possibility of rou nding causing overflow when computing 1/sfmin. */ sfmin = small * (eps + 1.); } } if (lsame_(cmach, "E")) { rmach = eps; } else if (lsame_(cmach, "S")) { rmach = sfmin; } else if (lsame_(cmach, "B")) { rmach = base; } else if (lsame_(cmach, "P")) { rmach = prec; } else if (lsame_(cmach, "N")) { rmach = t; } else if (lsame_(cmach, "R")) { rmach = rnd; } else if (lsame_(cmach, "M")) { rmach = emin; } else if (lsame_(cmach, "U")) { rmach = rmin; } else if (lsame_(cmach, "L")) { rmach = emax; } else if (lsame_(cmach, "O")) { rmach = rmax; } ret_val = rmach; return ret_val; /* End of DLAMCH */ } /* dlamch_ */ /* Subroutine */ int dlamc1_(integer *beta, integer *t, logical *rnd, logical *ieee1) { /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University October 31, 1992 Purpose ======= DLAMC1 determines the machine parameters given by BETA, T, RND, and IEEE1. Arguments ========= BETA (output) INTEGER The base of the machine. T (output) INTEGER The number of ( BETA ) digits in the mantissa. RND (output) LOGICAL Specifies whether proper rounding ( RND = .TRUE. ) or chopping ( RND = .FALSE. ) occurs in addition. This may not be a reliable guide to the way in which the machine performs its arithmetic. IEEE1 (output) LOGICAL Specifies whether rounding appears to be done in the IEEE 'round to nearest' style. Further Details =============== The routine is based on the routine ENVRON by Malcolm and incorporates suggestions by Gentleman and Marovich. See Malcolm M. A. (1972) Algorithms to reveal properties of floating-point arithmetic. Comms. of the ACM, 15, 949-951. Gentleman W. M. and Marovich S. B. (1974) More on algorithms that reveal properties of floating point arithmetic units. Comms. of the ACM, 17, 276-277. ===================================================================== */ /* Initialized data */ static logical first = TRUE_; /* System generated locals */ doublereal d__1, d__2; /* Local variables */ static logical lrnd; static doublereal a, b, c, f; static integer lbeta; static doublereal savec; extern doublereal dlamc3_(doublereal *, doublereal *); static logical lieee1; static doublereal t1, t2; static integer lt; static doublereal one, qtr; if (first) { first = FALSE_; one = 1.; /* LBETA, LIEEE1, LT and LRND are the local values of BE TA, IEEE1, T and RND. Throughout this routine we use the function DLAMC3 to ens ure that relevant values are stored and not held in registers, or are not affected by optimizers. Compute a = 2.0**m with the smallest positive integer m s uch that fl( a + 1.0 ) = a. */ a = 1.; c = 1.; /* + WHILE( C.EQ.ONE )LOOP */ L10: if (c == one) { a *= 2; c = dlamc3_(&a, &one); d__1 = -a; c = dlamc3_(&c, &d__1); goto L10; } /* + END WHILE Now compute b = 2.0**m with the smallest positive integer m such that fl( a + b ) .gt. a. */ b = 1.; c = dlamc3_(&a, &b); /* + WHILE( C.EQ.A )LOOP */ L20: if (c == a) { b *= 2; c = dlamc3_(&a, &b); goto L20; } /* + END WHILE Now compute the base. a and c are neighbouring floating po int numbers in the interval ( beta**t, beta**( t + 1 ) ) and so their difference is beta. Adding 0.25 to c is to ensure that it is truncated to beta and not ( beta - 1 ). */ qtr = one / 4; savec = c; d__1 = -a; c = dlamc3_(&c, &d__1); lbeta = (integer) (c + qtr); /* Now determine whether rounding or chopping occurs, by addin g a bit less than beta/2 and a bit more than beta/2 to a. */ b = (doublereal) lbeta; d__1 = b / 2; d__2 = -b / 100; f = dlamc3_(&d__1, &d__2); c = dlamc3_(&f, &a); if (c == a) { lrnd = TRUE_; } else { lrnd = FALSE_; } d__1 = b / 2; d__2 = b / 100; f = dlamc3_(&d__1, &d__2); c = dlamc3_(&f, &a); if (lrnd && c == a) { lrnd = FALSE_; } /* Try and decide whether rounding is done in the IEEE 'round to nearest' style. B/2 is half a unit in the last place of the two numbers A and SAVEC. Furthermore, A is even, i.e. has last bit zero, and SAVEC is odd. Thus adding B/2 to A should not cha nge A, but adding B/2 to SAVEC should change SAVEC. */ d__1 = b / 2; t1 = dlamc3_(&d__1, &a); d__1 = b / 2; t2 = dlamc3_(&d__1, &savec); lieee1 = t1 == a && t2 > savec && lrnd; /* Now find the mantissa, t. It should be the integer part of log to the base beta of a, however it is safer to determine t by powering. So we find t as the smallest positive integer for which fl( beta**t + 1.0 ) = 1.0. */ lt = 0; a = 1.; c = 1.; /* + WHILE( C.EQ.ONE )LOOP */ L30: if (c == one) { ++lt; a *= lbeta; c = dlamc3_(&a, &one); d__1 = -a; c = dlamc3_(&c, &d__1); goto L30; } /* + END WHILE */ } *beta = lbeta; *t = lt; *rnd = lrnd; *ieee1 = lieee1; return 0; /* End of DLAMC1 */ } /* dlamc1_ */ /* Subroutine */ int dlamc2_(integer *beta, integer *t, logical *rnd, doublereal *eps, integer *emin, doublereal *rmin, integer *emax, doublereal *rmax) { /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University October 31, 1992 Purpose ======= DLAMC2 determines the machine parameters specified in its argument list. Arguments ========= BETA (output) INTEGER The base of the machine. T (output) INTEGER The number of ( BETA ) digits in the mantissa. RND (output) LOGICAL Specifies whether proper rounding ( RND = .TRUE. ) or chopping ( RND = .FALSE. ) occurs in addition. This may not be a reliable guide to the way in which the machine performs its arithmetic. EPS (output) DOUBLE PRECISION The smallest positive number such that fl( 1.0 - EPS ) .LT. 1.0, where fl denotes the computed value. EMIN (output) INTEGER The minimum exponent before (gradual) underflow occurs. RMIN (output) DOUBLE PRECISION The smallest normalized number for the machine, given by BASE**( EMIN - 1 ), where BASE is the floating point value of BETA. EMAX (output) INTEGER The maximum exponent before overflow occurs. RMAX (output) DOUBLE PRECISION The largest positive number for the machine, given by BASE**EMAX * ( 1 - EPS ), where BASE is the floating point value of BETA. Further Details =============== The computation of EPS is based on a routine PARANOIA by W. Kahan of the University of California at Berkeley. ===================================================================== */ /* Initialized data */ static logical first = TRUE_; static logical iwarn = FALSE_; /* System generated locals */ integer i__1; doublereal d__1, d__2, d__3, d__4, d__5; /* Builtin functions */ double pow_di(doublereal *, integer *); /* Local variables */ static logical ieee; static doublereal half; static logical lrnd; static doublereal leps, zero, a, b, c; static integer i, lbeta; static doublereal rbase; static integer lemin, lemax, gnmin; static doublereal small; static integer gpmin; static doublereal third, lrmin, lrmax, sixth; extern /* Subroutine */ int dlamc1_(integer *, integer *, logical *, logical *); extern doublereal dlamc3_(doublereal *, doublereal *); static logical lieee1; extern /* Subroutine */ int dlamc4_(integer *, doublereal *, integer *), dlamc5_(integer *, integer *, integer *, logical *, integer *, doublereal *); static integer lt, ngnmin, ngpmin; static doublereal one, two; if (first) { first = FALSE_; zero = 0.; one = 1.; two = 2.; /* LBETA, LT, LRND, LEPS, LEMIN and LRMIN are the local values of BETA, T, RND, EPS, EMIN and RMIN. Throughout this routine we use the function DLAMC3 to ens ure that relevant values are stored and not held in registers, or are not affected by optimizers. DLAMC1 returns the parameters LBETA, LT, LRND and LIEEE1. */ dlamc1_(&lbeta, <, &lrnd, &lieee1); /* Start to find EPS. */ b = (doublereal) lbeta; i__1 = -lt; a = pow_di(&b, &i__1); leps = a; /* Try some tricks to see whether or not this is the correct E PS. */ b = two / 3; half = one / 2; d__1 = -half; sixth = dlamc3_(&b, &d__1); third = dlamc3_(&sixth, &sixth); d__1 = -half; b = dlamc3_(&third, &d__1); b = dlamc3_(&b, &sixth); b = abs(b); if (b < leps) { b = leps; } leps = 1.; /* + WHILE( ( LEPS.GT.B ).AND.( B.GT.ZERO ) )LOOP */ L10: if (leps > b && b > zero) { leps = b; d__1 = half * leps; /* Computing 5th power */ d__3 = two, d__4 = d__3, d__3 *= d__3; /* Computing 2nd power */ d__5 = leps; d__2 = d__4 * (d__3 * d__3) * (d__5 * d__5); c = dlamc3_(&d__1, &d__2); d__1 = -c; c = dlamc3_(&half, &d__1); b = dlamc3_(&half, &c); d__1 = -b; c = dlamc3_(&half, &d__1); b = dlamc3_(&half, &c); goto L10; } /* + END WHILE */ if (a < leps) { leps = a; } /* Computation of EPS complete. Now find EMIN. Let A = + or - 1, and + or - (1 + BASE**(-3 )). Keep dividing A by BETA until (gradual) underflow occurs. T his is detected when we cannot recover the previous A. */ rbase = one / lbeta; small = one; for (i = 1; i <= 3; ++i) { d__1 = small * rbase; small = dlamc3_(&d__1, &zero); /* L20: */ } a = dlamc3_(&one, &small); dlamc4_(&ngpmin, &one, &lbeta); d__1 = -one; dlamc4_(&ngnmin, &d__1, &lbeta); dlamc4_(&gpmin, &a, &lbeta); d__1 = -a; dlamc4_(&gnmin, &d__1, &lbeta); ieee = FALSE_; if (ngpmin == ngnmin && gpmin == gnmin) { if (ngpmin == gpmin) { lemin = ngpmin; /* ( Non twos-complement machines, no gradual under flow; e.g., VAX ) */ } else if (gpmin - ngpmin == 3) { lemin = ngpmin - 1 + lt; ieee = TRUE_; /* ( Non twos-complement machines, with gradual und erflow; e.g., IEEE standard followers ) */ } else { lemin = min(ngpmin,gpmin); /* ( A guess; no known machine ) */ iwarn = TRUE_; } } else if (ngpmin == gpmin && ngnmin == gnmin) { if ((i__1 = ngpmin - ngnmin, abs(i__1)) == 1) { lemin = max(ngpmin,ngnmin); /* ( Twos-complement machines, no gradual underflow ; e.g., CYBER 205 ) */ } else { lemin = min(ngpmin,ngnmin); /* ( A guess; no known machine ) */ iwarn = TRUE_; } } else if ((i__1 = ngpmin - ngnmin, abs(i__1)) == 1 && gpmin == gnmin) { if (gpmin - min(ngpmin,ngnmin) == 3) { lemin = max(ngpmin,ngnmin) - 1 + lt; /* ( Twos-complement machines with gradual underflo w; no known machine ) */ } else { lemin = min(ngpmin,ngnmin); /* ( A guess; no known machine ) */ iwarn = TRUE_; } } else { /* Computing MIN */ i__1 = min(ngpmin,ngnmin), i__1 = min(i__1,gpmin); lemin = min(i__1,gnmin); /* ( A guess; no known machine ) */ iwarn = TRUE_; } /* ** Comment out this if block if EMIN is ok */ if (iwarn) { first = TRUE_; printf("\n\n WARNING. The value EMIN may be incorrect:- "); printf("EMIN = %8i\n",lemin); printf("If, after inspection, the value EMIN looks acceptable"); printf("please comment out \n the IF block as marked within the"); printf("code of routine DLAMC2, \n otherwise supply EMIN"); printf("explicitly.\n"); } /* ** Assume IEEE arithmetic if we found denormalised numbers abo ve, or if arithmetic seems to round in the IEEE style, determi ned in routine DLAMC1. A true IEEE machine should have both thi ngs true; however, faulty machines may have one or the other. */ ieee = ieee || lieee1; /* Compute RMIN by successive division by BETA. We could comp ute RMIN as BASE**( EMIN - 1 ), but some machines underflow dur ing this computation. */ lrmin = 1.; i__1 = 1 - lemin; for (i = 1; i <= 1-lemin; ++i) { d__1 = lrmin * rbase; lrmin = dlamc3_(&d__1, &zero); /* L30: */ } /* Finally, call DLAMC5 to compute EMAX and RMAX. */ dlamc5_(&lbeta, <, &lemin, &ieee, &lemax, &lrmax); } *beta = lbeta; *t = lt; *rnd = lrnd; *eps = leps; *emin = lemin; *rmin = lrmin; *emax = lemax; *rmax = lrmax; return 0; /* End of DLAMC2 */ } /* dlamc2_ */ #endif doublereal dlamc3_(doublereal *a, doublereal *b) { /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University October 31, 1992 Purpose ======= DLAMC3 is intended to force A and B to be stored prior to doing the addition of A and B , for use in situations where optimizers might hold one of these in a register. Arguments ========= A, B (input) DOUBLE PRECISION The values A and B. ===================================================================== */ /* >>Start of File<< System generated locals */ volatile doublereal ret_val; ret_val = *a + *b; return ret_val; /* End of DLAMC3 */ } /* dlamc3_ */ #ifndef HAVE_CONFIG /* Subroutine */ int dlamc4_(integer *emin, doublereal *start, integer *base) { /* -- LAPACK auxiliary routine (version 2.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University October 31, 1992 Purpose ======= DLAMC4 is a service routine for DLAMC2. Arguments ========= EMIN (output) EMIN The minimum exponent before (gradual) underflow, computed by setting A = START and dividing by BASE until the previous A can not be recovered. START (input) DOUBLE PRECISION The starting point for determining EMIN. BASE (input) INTEGER The base of the machine. ===================================================================== */ /* System generated locals */ integer i__1; doublereal d__1; /* Local variables */ static doublereal zero, a; static integer i; static doublereal rbase, b1, b2, c1, c2, d1, d2; extern doublereal dlamc3_(doublereal *, doublereal *); static doublereal one; a = *start; one = 1.; rbase = one / *base; zero = 0.; *emin = 1; d__1 = a * rbase; b1 = dlamc3_(&d__1, &zero); c1 = a; c2 = a; d1 = a; d2 = a; /* + WHILE( ( C1.EQ.A ).AND.( C2.EQ.A ).AND. $ ( D1.EQ.A ).AND.( D2.EQ.A ) )LOOP */ L10: if (c1 == a && c2 == a && d1 == a && d2 == a) { --(*emin); a = b1; d__1 = a / *base; b1 = dlamc3_(&d__1, &zero); d__1 = b1 * *base; c1 = dlamc3_(&d__1, &zero); d1 = zero; i__1 = *base; for (i = 1; i <= *base; ++i) { d1 += b1; /* L20: */ } d__1 = a * rbase; b2 = dlamc3_(&d__1, &zero); d__1 = b2 / rbase; c2 = dlamc3_(&d__1, &zero); d2 = zero; i__1 = *base; for (i = 1; i <= *base; ++i) { d2 += b2; /* L30: */ } goto L10; } /* + END WHILE */ return 0; /* End of DLAMC4 */ } /* dlamc4_ */ /* Subroutine */ int dlamc5_(integer *beta, integer *p, integer *emin, logical *ieee, integer *emax, doublereal *rmax) { /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University October 31, 1992 Purpose ======= DLAMC5 attempts to compute RMAX, the largest machine floating-point number, without overflow. It assumes that EMAX + abs(EMIN) sum approximately to a power of 2. It will fail on machines where this assumption does not hold, for example, the Cyber 205 (EMIN = -28625, EMAX = 28718). It will also fail if the value supplied for EMIN is too large (i.e. too close to zero), probably with overflow. Arguments ========= BETA (input) INTEGER The base of floating-point arithmetic. P (input) INTEGER The number of base BETA digits in the mantissa of a floating-point value. EMIN (input) INTEGER The minimum exponent before (gradual) underflow. IEEE (input) LOGICAL A logical flag specifying whether or not the arithmetic system is thought to comply with the IEEE standard. EMAX (output) INTEGER The largest exponent before overflow RMAX (output) DOUBLE PRECISION The largest machine floating-point number. ===================================================================== First compute LEXP and UEXP, two powers of 2 that bound abs(EMIN). We then assume that EMAX + abs(EMIN) will sum approximately to the bound that is closest to abs(EMIN). (EMAX is the exponent of the required number RMAX). */ /* Table of constant values */ static doublereal c_b5 = 0.; /* System generated locals */ integer i__1; doublereal d__1; /* Local variables */ static integer lexp; static doublereal oldy; static integer uexp, i; static doublereal y, z; static integer nbits; extern doublereal dlamc3_(doublereal *, doublereal *); static doublereal recbas; static integer exbits, expsum, try__; lexp = 1; exbits = 1; L10: try__ = lexp << 1; if (try__ <= -(*emin)) { lexp = try__; ++exbits; goto L10; } if (lexp == -(*emin)) { uexp = lexp; } else { uexp = try__; ++exbits; } /* Now -LEXP is less than or equal to EMIN, and -UEXP is greater than or equal to EMIN. EXBITS is the number of bits needed to store the exponent. */ if (uexp + *emin > -lexp - *emin) { expsum = lexp << 1; } else { expsum = uexp << 1; } /* EXPSUM is the exponent range, approximately equal to EMAX - EMIN + 1 . */ *emax = expsum + *emin - 1; nbits = exbits + 1 + *p; /* NBITS is the total number of bits needed to store a floating-point number. */ if (nbits % 2 == 1 && *beta == 2) { /* Either there are an odd number of bits used to store a floating-point number, which is unlikely, or some bits are not used in the representation of numbers, which is possible , (e.g. Cray machines) or the mantissa has an implicit bit, (e.g. IEEE machines, Dec Vax machines), which is perhaps the most likely. We have to assume the last alternative. If this is true, then we need to reduce EMAX by one because there must be some way of representing zero in an implicit-b it system. On machines like Cray, we are reducing EMAX by one unnecessarily. */ --(*emax); } if (*ieee) { /* Assume we are on an IEEE machine which reserves one exponent for infinity and NaN. */ --(*emax); } /* Now create RMAX, the largest machine number, which should be equal to (1.0 - BETA**(-P)) * BETA**EMAX . First compute 1.0 - BETA**(-P), being careful that the result is less than 1.0 . */ recbas = 1. / *beta; z = *beta - 1.; y = 0.; i__1 = *p; for (i = 1; i <= *p; ++i) { z *= recbas; if (y < 1.) { oldy = y; } y = dlamc3_(&y, &z); /* L20: */ } if (y >= 1.) { y = oldy; } /* Now multiply by BETA**EMAX to get RMAX. */ i__1 = *emax; for (i = 1; i <= *emax; ++i) { d__1 = y * *beta; y = dlamc3_(&d__1, &c_b5); /* L30: */ } *rmax = y; return 0; /* End of DLAMC5 */ } /* dlamc5_ */ #endif numpy-1.8.2/numpy/linalg/lapack_lite/f2c.h0000664000175100017510000001026412370216242021537 0ustar vagrantvagrant00000000000000/* f2c.h -- Standard Fortran to C header file */ /** barf [ba:rf] 2. "He suggested using FORTRAN, and everybody barfed." - From The Shogakukan DICTIONARY OF NEW ENGLISH (Second edition) */ #ifndef F2C_INCLUDE #define F2C_INCLUDE typedef int integer; typedef char *address; typedef short int shortint; typedef float real; typedef double doublereal; typedef struct { real r, i; } complex; typedef struct { doublereal r, i; } doublecomplex; typedef int logical; typedef short int shortlogical; typedef char logical1; typedef char integer1; #define TRUE_ (1) #define FALSE_ (0) /* Extern is for use with -E */ #ifndef Extern #define Extern extern #endif /* I/O stuff */ #ifdef f2c_i2 /* for -i2 */ typedef short flag; typedef short ftnlen; typedef short ftnint; #else typedef int flag; typedef int ftnlen; typedef int ftnint; #endif /*external read, write*/ typedef struct { flag cierr; ftnint ciunit; flag ciend; char *cifmt; ftnint cirec; } cilist; /*internal read, write*/ typedef struct { flag icierr; char *iciunit; flag iciend; char *icifmt; ftnint icirlen; ftnint icirnum; } icilist; /*open*/ typedef struct { flag oerr; ftnint ounit; char *ofnm; ftnlen ofnmlen; char *osta; char *oacc; char *ofm; ftnint orl; char *oblnk; } olist; /*close*/ typedef struct { flag cerr; ftnint cunit; char *csta; } cllist; /*rewind, backspace, endfile*/ typedef struct { flag aerr; ftnint aunit; } alist; /* inquire */ typedef struct { flag inerr; ftnint inunit; char *infile; ftnlen infilen; ftnint *inex; /*parameters in standard's order*/ ftnint *inopen; ftnint *innum; ftnint *innamed; char *inname; ftnlen innamlen; char *inacc; ftnlen inacclen; char *inseq; ftnlen inseqlen; char *indir; ftnlen indirlen; char *infmt; ftnlen infmtlen; char *inform; ftnint informlen; char *inunf; ftnlen inunflen; ftnint *inrecl; ftnint *innrec; char *inblank; ftnlen inblanklen; } inlist; #define VOID void union Multitype { /* for multiple entry points */ shortint h; integer i; real r; doublereal d; complex c; doublecomplex z; }; typedef union Multitype Multitype; typedef long Long; /* No longer used; formerly in Namelist */ struct Vardesc { /* for Namelist */ char *name; char *addr; ftnlen *dims; int type; }; typedef struct Vardesc Vardesc; struct Namelist { char *name; Vardesc **vars; int nvars; }; typedef struct Namelist Namelist; #ifndef abs #define abs(x) ((x) >= 0 ? (x) : -(x)) #endif #define dabs(x) (doublereal)abs(x) #ifndef min #define min(a,b) ((a) <= (b) ? (a) : (b)) #endif #ifndef max #define max(a,b) ((a) >= (b) ? (a) : (b)) #endif #define dmin(a,b) (doublereal)min(a,b) #define dmax(a,b) (doublereal)max(a,b) /* procedure parameter types for -A and -C++ */ #define F2C_proc_par_types 1 #ifdef __cplusplus typedef int /* Unknown procedure type */ (*U_fp)(...); typedef shortint (*J_fp)(...); typedef integer (*I_fp)(...); typedef real (*R_fp)(...); typedef doublereal (*D_fp)(...), (*E_fp)(...); typedef /* Complex */ VOID (*C_fp)(...); typedef /* Double Complex */ VOID (*Z_fp)(...); typedef logical (*L_fp)(...); typedef shortlogical (*K_fp)(...); typedef /* Character */ VOID (*H_fp)(...); typedef /* Subroutine */ int (*S_fp)(...); #else typedef int /* Unknown procedure type */ (*U_fp)(void); typedef shortint (*J_fp)(void); typedef integer (*I_fp)(void); typedef real (*R_fp)(void); typedef doublereal (*D_fp)(void), (*E_fp)(void); typedef /* Complex */ VOID (*C_fp)(void); typedef /* Double Complex */ VOID (*Z_fp)(void); typedef logical (*L_fp)(void); typedef shortlogical (*K_fp)(void); typedef /* Character */ VOID (*H_fp)(void); typedef /* Subroutine */ int (*S_fp)(void); #endif /* E_fp is for real functions when -R is not specified */ typedef VOID C_f; /* complex function */ typedef VOID H_f; /* character function */ typedef VOID Z_f; /* double complex function */ typedef doublereal E_f; /* real function with -R not specified */ /* undef any lower-case symbols that your C compiler predefines, e.g.: */ #ifndef Skip_f2c_Undefs #undef cray #undef gcos #undef mc68010 #undef mc68020 #undef mips #undef pdp11 #undef sgi #undef sparc #undef sun #undef sun2 #undef sun3 #undef sun4 #undef u370 #undef u3b #undef u3b2 #undef u3b5 #undef unix #undef vax #endif #endif numpy-1.8.2/numpy/linalg/lapack_lite/dlapack_lite.c0000664000175100017510001255703012370216242023506 0ustar vagrantvagrant00000000000000/* NOTE: This is generated code. Look in Misc/lapack_lite for information on remaking this file. */ #include "f2c.h" #ifdef HAVE_CONFIG #include "config.h" #else extern doublereal dlamch_(char *); #define EPSILON dlamch_("Epsilon") #define SAFEMINIMUM dlamch_("Safe minimum") #define PRECISION dlamch_("Precision") #define BASE dlamch_("Base") #endif extern doublereal dlapy2_(doublereal *x, doublereal *y); /* Table of constant values */ static integer c__1 = 1; static complex c_b55 = {0.f,0.f}; static complex c_b56 = {1.f,0.f}; static integer c_n1 = -1; static integer c__3 = 3; static integer c__2 = 2; static integer c__0 = 0; static integer c__8 = 8; static integer c__4 = 4; static integer c__65 = 65; static integer c__6 = 6; static integer c__9 = 9; static real c_b320 = 0.f; static real c_b1011 = 1.f; static integer c__15 = 15; static logical c_false = FALSE_; static real c_b1290 = -1.f; static real c_b2206 = .5f; static doublereal c_b2865 = 1.; static doublereal c_b2879 = 0.; static doublereal c_b2944 = -.125; static doublereal c_b3001 = -1.; static integer c__10 = 10; static integer c__11 = 11; static doublereal c_b5654 = 2.; static logical c_true = TRUE_; static real c_b9647 = 2.f; /* Subroutine */ int cgebak_(char *job, char *side, integer *n, integer *ilo, integer *ihi, real *scale, integer *m, complex *v, integer *ldv, integer *info) { /* System generated locals */ integer v_dim1, v_offset, i__1; /* Local variables */ static integer i__, k; static real s; static integer ii; extern logical lsame_(char *, char *); extern /* Subroutine */ int cswap_(integer *, complex *, integer *, complex *, integer *); static logical leftv; extern /* Subroutine */ int csscal_(integer *, real *, complex *, integer *), xerbla_(char *, integer *); static logical rightv; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University September 30, 1994 Purpose ======= CGEBAK forms the right or left eigenvectors of a complex general matrix by backward transformation on the computed eigenvectors of the balanced matrix output by CGEBAL. Arguments ========= JOB (input) CHARACTER*1 Specifies the type of backward transformation required: = 'N', do nothing, return immediately; = 'P', do backward transformation for permutation only; = 'S', do backward transformation for scaling only; = 'B', do backward transformations for both permutation and scaling. JOB must be the same as the argument JOB supplied to CGEBAL. SIDE (input) CHARACTER*1 = 'R': V contains right eigenvectors; = 'L': V contains left eigenvectors. N (input) INTEGER The number of rows of the matrix V. N >= 0. ILO (input) INTEGER IHI (input) INTEGER The integers ILO and IHI determined by CGEBAL. 1 <= ILO <= IHI <= N, if N > 0; ILO=1 and IHI=0, if N=0. SCALE (input) REAL array, dimension (N) Details of the permutation and scaling factors, as returned by CGEBAL. M (input) INTEGER The number of columns of the matrix V. M >= 0. V (input/output) COMPLEX array, dimension (LDV,M) On entry, the matrix of right or left eigenvectors to be transformed, as returned by CHSEIN or CTREVC. On exit, V is overwritten by the transformed eigenvectors. LDV (input) INTEGER The leading dimension of the array V. LDV >= max(1,N). INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value. ===================================================================== Decode and Test the input parameters */ /* Parameter adjustments */ --scale; v_dim1 = *ldv; v_offset = 1 + v_dim1; v -= v_offset; /* Function Body */ rightv = lsame_(side, "R"); leftv = lsame_(side, "L"); *info = 0; if (! lsame_(job, "N") && ! lsame_(job, "P") && ! lsame_(job, "S") && ! lsame_(job, "B")) { *info = -1; } else if (! rightv && ! leftv) { *info = -2; } else if (*n < 0) { *info = -3; } else if ((*ilo < 1) || (*ilo > max(1,*n))) { *info = -4; } else if ((*ihi < min(*ilo,*n)) || (*ihi > *n)) { *info = -5; } else if (*m < 0) { *info = -7; } else if (*ldv < max(1,*n)) { *info = -9; } if (*info != 0) { i__1 = -(*info); xerbla_("CGEBAK", &i__1); return 0; } /* Quick return if possible */ if (*n == 0) { return 0; } if (*m == 0) { return 0; } if (lsame_(job, "N")) { return 0; } if (*ilo == *ihi) { goto L30; } /* Backward balance */ if ((lsame_(job, "S")) || (lsame_(job, "B"))) { if (rightv) { i__1 = *ihi; for (i__ = *ilo; i__ <= i__1; ++i__) { s = scale[i__]; csscal_(m, &s, &v[i__ + v_dim1], ldv); /* L10: */ } } if (leftv) { i__1 = *ihi; for (i__ = *ilo; i__ <= i__1; ++i__) { s = 1.f / scale[i__]; csscal_(m, &s, &v[i__ + v_dim1], ldv); /* L20: */ } } } /* Backward permutation For I = ILO-1 step -1 until 1, IHI+1 step 1 until N do -- */ L30: if ((lsame_(job, "P")) || (lsame_(job, "B"))) { if (rightv) { i__1 = *n; for (ii = 1; ii <= i__1; ++ii) { i__ = ii; if (i__ >= *ilo && i__ <= *ihi) { goto L40; } if (i__ < *ilo) { i__ = *ilo - ii; } k = scale[i__]; if (k == i__) { goto L40; } cswap_(m, &v[i__ + v_dim1], ldv, &v[k + v_dim1], ldv); L40: ; } } if (leftv) { i__1 = *n; for (ii = 1; ii <= i__1; ++ii) { i__ = ii; if (i__ >= *ilo && i__ <= *ihi) { goto L50; } if (i__ < *ilo) { i__ = *ilo - ii; } k = scale[i__]; if (k == i__) { goto L50; } cswap_(m, &v[i__ + v_dim1], ldv, &v[k + v_dim1], ldv); L50: ; } } } return 0; /* End of CGEBAK */ } /* cgebak_ */ /* Subroutine */ int cgebal_(char *job, integer *n, complex *a, integer *lda, integer *ilo, integer *ihi, real *scale, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3; real r__1, r__2; /* Builtin functions */ double r_imag(complex *), c_abs(complex *); /* Local variables */ static real c__, f, g; static integer i__, j, k, l, m; static real r__, s, ca, ra; static integer ica, ira, iexc; extern logical lsame_(char *, char *); extern /* Subroutine */ int cswap_(integer *, complex *, integer *, complex *, integer *); static real sfmin1, sfmin2, sfmax1, sfmax2; extern integer icamax_(integer *, complex *, integer *); extern doublereal slamch_(char *); extern /* Subroutine */ int csscal_(integer *, real *, complex *, integer *), xerbla_(char *, integer *); static logical noconv; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= CGEBAL balances a general complex matrix A. This involves, first, permuting A by a similarity transformation to isolate eigenvalues in the first 1 to ILO-1 and last IHI+1 to N elements on the diagonal; and second, applying a diagonal similarity transformation to rows and columns ILO to IHI to make the rows and columns as close in norm as possible. Both steps are optional. Balancing may reduce the 1-norm of the matrix, and improve the accuracy of the computed eigenvalues and/or eigenvectors. Arguments ========= JOB (input) CHARACTER*1 Specifies the operations to be performed on A: = 'N': none: simply set ILO = 1, IHI = N, SCALE(I) = 1.0 for i = 1,...,N; = 'P': permute only; = 'S': scale only; = 'B': both permute and scale. N (input) INTEGER The order of the matrix A. N >= 0. A (input/output) COMPLEX array, dimension (LDA,N) On entry, the input matrix A. On exit, A is overwritten by the balanced matrix. If JOB = 'N', A is not referenced. See Further Details. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,N). ILO (output) INTEGER IHI (output) INTEGER ILO and IHI are set to integers such that on exit A(i,j) = 0 if i > j and j = 1,...,ILO-1 or I = IHI+1,...,N. If JOB = 'N' or 'S', ILO = 1 and IHI = N. SCALE (output) REAL array, dimension (N) Details of the permutations and scaling factors applied to A. If P(j) is the index of the row and column interchanged with row and column j and D(j) is the scaling factor applied to row and column j, then SCALE(j) = P(j) for j = 1,...,ILO-1 = D(j) for j = ILO,...,IHI = P(j) for j = IHI+1,...,N. The order in which the interchanges are made is N to IHI+1, then 1 to ILO-1. INFO (output) INTEGER = 0: successful exit. < 0: if INFO = -i, the i-th argument had an illegal value. Further Details =============== The permutations consist of row and column interchanges which put the matrix in the form ( T1 X Y ) P A P = ( 0 B Z ) ( 0 0 T2 ) where T1 and T2 are upper triangular matrices whose eigenvalues lie along the diagonal. The column indices ILO and IHI mark the starting and ending columns of the submatrix B. Balancing consists of applying a diagonal similarity transformation inv(D) * B * D to make the 1-norms of each row of B and its corresponding column nearly equal. The output matrix is ( T1 X*D Y ) ( 0 inv(D)*B*D inv(D)*Z ). ( 0 0 T2 ) Information about the permutations P and the diagonal matrix D is returned in the vector SCALE. This subroutine is based on the EISPACK routine CBAL. Modified by Tzu-Yi Chen, Computer Science Division, University of California at Berkeley, USA ===================================================================== Test the input parameters */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --scale; /* Function Body */ *info = 0; if (! lsame_(job, "N") && ! lsame_(job, "P") && ! lsame_(job, "S") && ! lsame_(job, "B")) { *info = -1; } else if (*n < 0) { *info = -2; } else if (*lda < max(1,*n)) { *info = -4; } if (*info != 0) { i__1 = -(*info); xerbla_("CGEBAL", &i__1); return 0; } k = 1; l = *n; if (*n == 0) { goto L210; } if (lsame_(job, "N")) { i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { scale[i__] = 1.f; /* L10: */ } goto L210; } if (lsame_(job, "S")) { goto L120; } /* Permutation to isolate eigenvalues if possible */ goto L50; /* Row and column exchange. */ L20: scale[m] = (real) j; if (j == m) { goto L30; } cswap_(&l, &a[j * a_dim1 + 1], &c__1, &a[m * a_dim1 + 1], &c__1); i__1 = *n - k + 1; cswap_(&i__1, &a[j + k * a_dim1], lda, &a[m + k * a_dim1], lda); L30: switch (iexc) { case 1: goto L40; case 2: goto L80; } /* Search for rows isolating an eigenvalue and push them down. */ L40: if (l == 1) { goto L210; } --l; L50: for (j = l; j >= 1; --j) { i__1 = l; for (i__ = 1; i__ <= i__1; ++i__) { if (i__ == j) { goto L60; } i__2 = j + i__ * a_dim1; if ((a[i__2].r != 0.f) || (r_imag(&a[j + i__ * a_dim1]) != 0.f)) { goto L70; } L60: ; } m = l; iexc = 1; goto L20; L70: ; } goto L90; /* Search for columns isolating an eigenvalue and push them left. */ L80: ++k; L90: i__1 = l; for (j = k; j <= i__1; ++j) { i__2 = l; for (i__ = k; i__ <= i__2; ++i__) { if (i__ == j) { goto L100; } i__3 = i__ + j * a_dim1; if ((a[i__3].r != 0.f) || (r_imag(&a[i__ + j * a_dim1]) != 0.f)) { goto L110; } L100: ; } m = k; iexc = 2; goto L20; L110: ; } L120: i__1 = l; for (i__ = k; i__ <= i__1; ++i__) { scale[i__] = 1.f; /* L130: */ } if (lsame_(job, "P")) { goto L210; } /* Balance the submatrix in rows K to L. Iterative loop for norm reduction */ sfmin1 = slamch_("S") / slamch_("P"); sfmax1 = 1.f / sfmin1; sfmin2 = sfmin1 * 8.f; sfmax2 = 1.f / sfmin2; L140: noconv = FALSE_; i__1 = l; for (i__ = k; i__ <= i__1; ++i__) { c__ = 0.f; r__ = 0.f; i__2 = l; for (j = k; j <= i__2; ++j) { if (j == i__) { goto L150; } i__3 = j + i__ * a_dim1; c__ += (r__1 = a[i__3].r, dabs(r__1)) + (r__2 = r_imag(&a[j + i__ * a_dim1]), dabs(r__2)); i__3 = i__ + j * a_dim1; r__ += (r__1 = a[i__3].r, dabs(r__1)) + (r__2 = r_imag(&a[i__ + j * a_dim1]), dabs(r__2)); L150: ; } ica = icamax_(&l, &a[i__ * a_dim1 + 1], &c__1); ca = c_abs(&a[ica + i__ * a_dim1]); i__2 = *n - k + 1; ira = icamax_(&i__2, &a[i__ + k * a_dim1], lda); ra = c_abs(&a[i__ + (ira + k - 1) * a_dim1]); /* Guard against zero C or R due to underflow. */ if ((c__ == 0.f) || (r__ == 0.f)) { goto L200; } g = r__ / 8.f; f = 1.f; s = c__ + r__; L160: /* Computing MAX */ r__1 = max(f,c__); /* Computing MIN */ r__2 = min(r__,g); if (((c__ >= g) || (dmax(r__1,ca) >= sfmax2)) || (dmin(r__2,ra) <= sfmin2)) { goto L170; } f *= 8.f; c__ *= 8.f; ca *= 8.f; r__ /= 8.f; g /= 8.f; ra /= 8.f; goto L160; L170: g = c__ / 8.f; L180: /* Computing MIN */ r__1 = min(f,c__), r__1 = min(r__1,g); if (((g < r__) || (dmax(r__,ra) >= sfmax2)) || (dmin(r__1,ca) <= sfmin2)) { goto L190; } f /= 8.f; c__ /= 8.f; g /= 8.f; ca /= 8.f; r__ *= 8.f; ra *= 8.f; goto L180; /* Now balance. */ L190: if (c__ + r__ >= s * .95f) { goto L200; } if (f < 1.f && scale[i__] < 1.f) { if (f * scale[i__] <= sfmin1) { goto L200; } } if (f > 1.f && scale[i__] > 1.f) { if (scale[i__] >= sfmax1 / f) { goto L200; } } g = 1.f / f; scale[i__] *= f; noconv = TRUE_; i__2 = *n - k + 1; csscal_(&i__2, &g, &a[i__ + k * a_dim1], lda); csscal_(&l, &f, &a[i__ * a_dim1 + 1], &c__1); L200: ; } if (noconv) { goto L140; } L210: *ilo = k; *ihi = l; return 0; /* End of CGEBAL */ } /* cgebal_ */ /* Subroutine */ int cgebd2_(integer *m, integer *n, complex *a, integer *lda, real *d__, real *e, complex *tauq, complex *taup, complex *work, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3, i__4; complex q__1; /* Builtin functions */ void r_cnjg(complex *, complex *); /* Local variables */ static integer i__; static complex alpha; extern /* Subroutine */ int clarf_(char *, integer *, integer *, complex * , integer *, complex *, complex *, integer *, complex *), clarfg_(integer *, complex *, complex *, integer *, complex *), clacgv_(integer *, complex *, integer *), xerbla_(char *, integer *); /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University September 30, 1994 Purpose ======= CGEBD2 reduces a complex general m by n matrix A to upper or lower real bidiagonal form B by a unitary transformation: Q' * A * P = B. If m >= n, B is upper bidiagonal; if m < n, B is lower bidiagonal. Arguments ========= M (input) INTEGER The number of rows in the matrix A. M >= 0. N (input) INTEGER The number of columns in the matrix A. N >= 0. A (input/output) COMPLEX array, dimension (LDA,N) On entry, the m by n general matrix to be reduced. On exit, if m >= n, the diagonal and the first superdiagonal are overwritten with the upper bidiagonal matrix B; the elements below the diagonal, with the array TAUQ, represent the unitary matrix Q as a product of elementary reflectors, and the elements above the first superdiagonal, with the array TAUP, represent the unitary matrix P as a product of elementary reflectors; if m < n, the diagonal and the first subdiagonal are overwritten with the lower bidiagonal matrix B; the elements below the first subdiagonal, with the array TAUQ, represent the unitary matrix Q as a product of elementary reflectors, and the elements above the diagonal, with the array TAUP, represent the unitary matrix P as a product of elementary reflectors. See Further Details. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,M). D (output) REAL array, dimension (min(M,N)) The diagonal elements of the bidiagonal matrix B: D(i) = A(i,i). E (output) REAL array, dimension (min(M,N)-1) The off-diagonal elements of the bidiagonal matrix B: if m >= n, E(i) = A(i,i+1) for i = 1,2,...,n-1; if m < n, E(i) = A(i+1,i) for i = 1,2,...,m-1. TAUQ (output) COMPLEX array dimension (min(M,N)) The scalar factors of the elementary reflectors which represent the unitary matrix Q. See Further Details. TAUP (output) COMPLEX array, dimension (min(M,N)) The scalar factors of the elementary reflectors which represent the unitary matrix P. See Further Details. WORK (workspace) COMPLEX array, dimension (max(M,N)) INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value. Further Details =============== The matrices Q and P are represented as products of elementary reflectors: If m >= n, Q = H(1) H(2) . . . H(n) and P = G(1) G(2) . . . G(n-1) Each H(i) and G(i) has the form: H(i) = I - tauq * v * v' and G(i) = I - taup * u * u' where tauq and taup are complex scalars, and v and u are complex vectors; v(1:i-1) = 0, v(i) = 1, and v(i+1:m) is stored on exit in A(i+1:m,i); u(1:i) = 0, u(i+1) = 1, and u(i+2:n) is stored on exit in A(i,i+2:n); tauq is stored in TAUQ(i) and taup in TAUP(i). If m < n, Q = H(1) H(2) . . . H(m-1) and P = G(1) G(2) . . . G(m) Each H(i) and G(i) has the form: H(i) = I - tauq * v * v' and G(i) = I - taup * u * u' where tauq and taup are complex scalars, v and u are complex vectors; v(1:i) = 0, v(i+1) = 1, and v(i+2:m) is stored on exit in A(i+2:m,i); u(1:i-1) = 0, u(i) = 1, and u(i+1:n) is stored on exit in A(i,i+1:n); tauq is stored in TAUQ(i) and taup in TAUP(i). The contents of A on exit are illustrated by the following examples: m = 6 and n = 5 (m > n): m = 5 and n = 6 (m < n): ( d e u1 u1 u1 ) ( d u1 u1 u1 u1 u1 ) ( v1 d e u2 u2 ) ( e d u2 u2 u2 u2 ) ( v1 v2 d e u3 ) ( v1 e d u3 u3 u3 ) ( v1 v2 v3 d e ) ( v1 v2 e d u4 u4 ) ( v1 v2 v3 v4 d ) ( v1 v2 v3 e d u5 ) ( v1 v2 v3 v4 v5 ) where d and e denote diagonal and off-diagonal elements of B, vi denotes an element of the vector defining H(i), and ui an element of the vector defining G(i). ===================================================================== Test the input parameters */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --d__; --e; --tauq; --taup; --work; /* Function Body */ *info = 0; if (*m < 0) { *info = -1; } else if (*n < 0) { *info = -2; } else if (*lda < max(1,*m)) { *info = -4; } if (*info < 0) { i__1 = -(*info); xerbla_("CGEBD2", &i__1); return 0; } if (*m >= *n) { /* Reduce to upper bidiagonal form */ i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { /* Generate elementary reflector H(i) to annihilate A(i+1:m,i) */ i__2 = i__ + i__ * a_dim1; alpha.r = a[i__2].r, alpha.i = a[i__2].i; i__2 = *m - i__ + 1; /* Computing MIN */ i__3 = i__ + 1; clarfg_(&i__2, &alpha, &a[min(i__3,*m) + i__ * a_dim1], &c__1, & tauq[i__]); i__2 = i__; d__[i__2] = alpha.r; i__2 = i__ + i__ * a_dim1; a[i__2].r = 1.f, a[i__2].i = 0.f; /* Apply H(i)' to A(i:m,i+1:n) from the left */ i__2 = *m - i__ + 1; i__3 = *n - i__; r_cnjg(&q__1, &tauq[i__]); clarf_("Left", &i__2, &i__3, &a[i__ + i__ * a_dim1], &c__1, &q__1, &a[i__ + (i__ + 1) * a_dim1], lda, &work[1]); i__2 = i__ + i__ * a_dim1; i__3 = i__; a[i__2].r = d__[i__3], a[i__2].i = 0.f; if (i__ < *n) { /* Generate elementary reflector G(i) to annihilate A(i,i+2:n) */ i__2 = *n - i__; clacgv_(&i__2, &a[i__ + (i__ + 1) * a_dim1], lda); i__2 = i__ + (i__ + 1) * a_dim1; alpha.r = a[i__2].r, alpha.i = a[i__2].i; i__2 = *n - i__; /* Computing MIN */ i__3 = i__ + 2; clarfg_(&i__2, &alpha, &a[i__ + min(i__3,*n) * a_dim1], lda, & taup[i__]); i__2 = i__; e[i__2] = alpha.r; i__2 = i__ + (i__ + 1) * a_dim1; a[i__2].r = 1.f, a[i__2].i = 0.f; /* Apply G(i) to A(i+1:m,i+1:n) from the right */ i__2 = *m - i__; i__3 = *n - i__; clarf_("Right", &i__2, &i__3, &a[i__ + (i__ + 1) * a_dim1], lda, &taup[i__], &a[i__ + 1 + (i__ + 1) * a_dim1], lda, &work[1]); i__2 = *n - i__; clacgv_(&i__2, &a[i__ + (i__ + 1) * a_dim1], lda); i__2 = i__ + (i__ + 1) * a_dim1; i__3 = i__; a[i__2].r = e[i__3], a[i__2].i = 0.f; } else { i__2 = i__; taup[i__2].r = 0.f, taup[i__2].i = 0.f; } /* L10: */ } } else { /* Reduce to lower bidiagonal form */ i__1 = *m; for (i__ = 1; i__ <= i__1; ++i__) { /* Generate elementary reflector G(i) to annihilate A(i,i+1:n) */ i__2 = *n - i__ + 1; clacgv_(&i__2, &a[i__ + i__ * a_dim1], lda); i__2 = i__ + i__ * a_dim1; alpha.r = a[i__2].r, alpha.i = a[i__2].i; i__2 = *n - i__ + 1; /* Computing MIN */ i__3 = i__ + 1; clarfg_(&i__2, &alpha, &a[i__ + min(i__3,*n) * a_dim1], lda, & taup[i__]); i__2 = i__; d__[i__2] = alpha.r; i__2 = i__ + i__ * a_dim1; a[i__2].r = 1.f, a[i__2].i = 0.f; /* Apply G(i) to A(i+1:m,i:n) from the right */ i__2 = *m - i__; i__3 = *n - i__ + 1; /* Computing MIN */ i__4 = i__ + 1; clarf_("Right", &i__2, &i__3, &a[i__ + i__ * a_dim1], lda, &taup[ i__], &a[min(i__4,*m) + i__ * a_dim1], lda, &work[1]); i__2 = *n - i__ + 1; clacgv_(&i__2, &a[i__ + i__ * a_dim1], lda); i__2 = i__ + i__ * a_dim1; i__3 = i__; a[i__2].r = d__[i__3], a[i__2].i = 0.f; if (i__ < *m) { /* Generate elementary reflector H(i) to annihilate A(i+2:m,i) */ i__2 = i__ + 1 + i__ * a_dim1; alpha.r = a[i__2].r, alpha.i = a[i__2].i; i__2 = *m - i__; /* Computing MIN */ i__3 = i__ + 2; clarfg_(&i__2, &alpha, &a[min(i__3,*m) + i__ * a_dim1], &c__1, &tauq[i__]); i__2 = i__; e[i__2] = alpha.r; i__2 = i__ + 1 + i__ * a_dim1; a[i__2].r = 1.f, a[i__2].i = 0.f; /* Apply H(i)' to A(i+1:m,i+1:n) from the left */ i__2 = *m - i__; i__3 = *n - i__; r_cnjg(&q__1, &tauq[i__]); clarf_("Left", &i__2, &i__3, &a[i__ + 1 + i__ * a_dim1], & c__1, &q__1, &a[i__ + 1 + (i__ + 1) * a_dim1], lda, & work[1]); i__2 = i__ + 1 + i__ * a_dim1; i__3 = i__; a[i__2].r = e[i__3], a[i__2].i = 0.f; } else { i__2 = i__; tauq[i__2].r = 0.f, tauq[i__2].i = 0.f; } /* L20: */ } } return 0; /* End of CGEBD2 */ } /* cgebd2_ */ /* Subroutine */ int cgebrd_(integer *m, integer *n, complex *a, integer *lda, real *d__, real *e, complex *tauq, complex *taup, complex *work, integer *lwork, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3, i__4, i__5; real r__1; complex q__1; /* Local variables */ static integer i__, j, nb, nx; static real ws; extern /* Subroutine */ int cgemm_(char *, char *, integer *, integer *, integer *, complex *, complex *, integer *, complex *, integer *, complex *, complex *, integer *); static integer nbmin, iinfo, minmn; extern /* Subroutine */ int cgebd2_(integer *, integer *, complex *, integer *, real *, real *, complex *, complex *, complex *, integer *), clabrd_(integer *, integer *, integer *, complex *, integer *, real *, real *, complex *, complex *, complex *, integer *, complex *, integer *), xerbla_(char *, integer *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); static integer ldwrkx, ldwrky, lwkopt; static logical lquery; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= CGEBRD reduces a general complex M-by-N matrix A to upper or lower bidiagonal form B by a unitary transformation: Q**H * A * P = B. If m >= n, B is upper bidiagonal; if m < n, B is lower bidiagonal. Arguments ========= M (input) INTEGER The number of rows in the matrix A. M >= 0. N (input) INTEGER The number of columns in the matrix A. N >= 0. A (input/output) COMPLEX array, dimension (LDA,N) On entry, the M-by-N general matrix to be reduced. On exit, if m >= n, the diagonal and the first superdiagonal are overwritten with the upper bidiagonal matrix B; the elements below the diagonal, with the array TAUQ, represent the unitary matrix Q as a product of elementary reflectors, and the elements above the first superdiagonal, with the array TAUP, represent the unitary matrix P as a product of elementary reflectors; if m < n, the diagonal and the first subdiagonal are overwritten with the lower bidiagonal matrix B; the elements below the first subdiagonal, with the array TAUQ, represent the unitary matrix Q as a product of elementary reflectors, and the elements above the diagonal, with the array TAUP, represent the unitary matrix P as a product of elementary reflectors. See Further Details. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,M). D (output) REAL array, dimension (min(M,N)) The diagonal elements of the bidiagonal matrix B: D(i) = A(i,i). E (output) REAL array, dimension (min(M,N)-1) The off-diagonal elements of the bidiagonal matrix B: if m >= n, E(i) = A(i,i+1) for i = 1,2,...,n-1; if m < n, E(i) = A(i+1,i) for i = 1,2,...,m-1. TAUQ (output) COMPLEX array dimension (min(M,N)) The scalar factors of the elementary reflectors which represent the unitary matrix Q. See Further Details. TAUP (output) COMPLEX array, dimension (min(M,N)) The scalar factors of the elementary reflectors which represent the unitary matrix P. See Further Details. WORK (workspace/output) COMPLEX array, dimension (LWORK) On exit, if INFO = 0, WORK(1) returns the optimal LWORK. LWORK (input) INTEGER The length of the array WORK. LWORK >= max(1,M,N). For optimum performance LWORK >= (M+N)*NB, where NB is the optimal blocksize. If LWORK = -1, then a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued by XERBLA. INFO (output) INTEGER = 0: successful exit. < 0: if INFO = -i, the i-th argument had an illegal value. Further Details =============== The matrices Q and P are represented as products of elementary reflectors: If m >= n, Q = H(1) H(2) . . . H(n) and P = G(1) G(2) . . . G(n-1) Each H(i) and G(i) has the form: H(i) = I - tauq * v * v' and G(i) = I - taup * u * u' where tauq and taup are complex scalars, and v and u are complex vectors; v(1:i-1) = 0, v(i) = 1, and v(i+1:m) is stored on exit in A(i+1:m,i); u(1:i) = 0, u(i+1) = 1, and u(i+2:n) is stored on exit in A(i,i+2:n); tauq is stored in TAUQ(i) and taup in TAUP(i). If m < n, Q = H(1) H(2) . . . H(m-1) and P = G(1) G(2) . . . G(m) Each H(i) and G(i) has the form: H(i) = I - tauq * v * v' and G(i) = I - taup * u * u' where tauq and taup are complex scalars, and v and u are complex vectors; v(1:i) = 0, v(i+1) = 1, and v(i+2:m) is stored on exit in A(i+2:m,i); u(1:i-1) = 0, u(i) = 1, and u(i+1:n) is stored on exit in A(i,i+1:n); tauq is stored in TAUQ(i) and taup in TAUP(i). The contents of A on exit are illustrated by the following examples: m = 6 and n = 5 (m > n): m = 5 and n = 6 (m < n): ( d e u1 u1 u1 ) ( d u1 u1 u1 u1 u1 ) ( v1 d e u2 u2 ) ( e d u2 u2 u2 u2 ) ( v1 v2 d e u3 ) ( v1 e d u3 u3 u3 ) ( v1 v2 v3 d e ) ( v1 v2 e d u4 u4 ) ( v1 v2 v3 v4 d ) ( v1 v2 v3 e d u5 ) ( v1 v2 v3 v4 v5 ) where d and e denote diagonal and off-diagonal elements of B, vi denotes an element of the vector defining H(i), and ui an element of the vector defining G(i). ===================================================================== Test the input parameters */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --d__; --e; --tauq; --taup; --work; /* Function Body */ *info = 0; /* Computing MAX */ i__1 = 1, i__2 = ilaenv_(&c__1, "CGEBRD", " ", m, n, &c_n1, &c_n1, ( ftnlen)6, (ftnlen)1); nb = max(i__1,i__2); lwkopt = (*m + *n) * nb; r__1 = (real) lwkopt; work[1].r = r__1, work[1].i = 0.f; lquery = *lwork == -1; if (*m < 0) { *info = -1; } else if (*n < 0) { *info = -2; } else if (*lda < max(1,*m)) { *info = -4; } else /* if(complicated condition) */ { /* Computing MAX */ i__1 = max(1,*m); if (*lwork < max(i__1,*n) && ! lquery) { *info = -10; } } if (*info < 0) { i__1 = -(*info); xerbla_("CGEBRD", &i__1); return 0; } else if (lquery) { return 0; } /* Quick return if possible */ minmn = min(*m,*n); if (minmn == 0) { work[1].r = 1.f, work[1].i = 0.f; return 0; } ws = (real) max(*m,*n); ldwrkx = *m; ldwrky = *n; if (nb > 1 && nb < minmn) { /* Set the crossover point NX. Computing MAX */ i__1 = nb, i__2 = ilaenv_(&c__3, "CGEBRD", " ", m, n, &c_n1, &c_n1, ( ftnlen)6, (ftnlen)1); nx = max(i__1,i__2); /* Determine when to switch from blocked to unblocked code. */ if (nx < minmn) { ws = (real) ((*m + *n) * nb); if ((real) (*lwork) < ws) { /* Not enough work space for the optimal NB, consider using a smaller block size. */ nbmin = ilaenv_(&c__2, "CGEBRD", " ", m, n, &c_n1, &c_n1, ( ftnlen)6, (ftnlen)1); if (*lwork >= (*m + *n) * nbmin) { nb = *lwork / (*m + *n); } else { nb = 1; nx = minmn; } } } } else { nx = minmn; } i__1 = minmn - nx; i__2 = nb; for (i__ = 1; i__2 < 0 ? i__ >= i__1 : i__ <= i__1; i__ += i__2) { /* Reduce rows and columns i:i+ib-1 to bidiagonal form and return the matrices X and Y which are needed to update the unreduced part of the matrix */ i__3 = *m - i__ + 1; i__4 = *n - i__ + 1; clabrd_(&i__3, &i__4, &nb, &a[i__ + i__ * a_dim1], lda, &d__[i__], &e[ i__], &tauq[i__], &taup[i__], &work[1], &ldwrkx, &work[ldwrkx * nb + 1], &ldwrky); /* Update the trailing submatrix A(i+ib:m,i+ib:n), using an update of the form A := A - V*Y' - X*U' */ i__3 = *m - i__ - nb + 1; i__4 = *n - i__ - nb + 1; q__1.r = -1.f, q__1.i = -0.f; cgemm_("No transpose", "Conjugate transpose", &i__3, &i__4, &nb, & q__1, &a[i__ + nb + i__ * a_dim1], lda, &work[ldwrkx * nb + nb + 1], &ldwrky, &c_b56, &a[i__ + nb + (i__ + nb) * a_dim1], lda); i__3 = *m - i__ - nb + 1; i__4 = *n - i__ - nb + 1; q__1.r = -1.f, q__1.i = -0.f; cgemm_("No transpose", "No transpose", &i__3, &i__4, &nb, &q__1, & work[nb + 1], &ldwrkx, &a[i__ + (i__ + nb) * a_dim1], lda, & c_b56, &a[i__ + nb + (i__ + nb) * a_dim1], lda); /* Copy diagonal and off-diagonal elements of B back into A */ if (*m >= *n) { i__3 = i__ + nb - 1; for (j = i__; j <= i__3; ++j) { i__4 = j + j * a_dim1; i__5 = j; a[i__4].r = d__[i__5], a[i__4].i = 0.f; i__4 = j + (j + 1) * a_dim1; i__5 = j; a[i__4].r = e[i__5], a[i__4].i = 0.f; /* L10: */ } } else { i__3 = i__ + nb - 1; for (j = i__; j <= i__3; ++j) { i__4 = j + j * a_dim1; i__5 = j; a[i__4].r = d__[i__5], a[i__4].i = 0.f; i__4 = j + 1 + j * a_dim1; i__5 = j; a[i__4].r = e[i__5], a[i__4].i = 0.f; /* L20: */ } } /* L30: */ } /* Use unblocked code to reduce the remainder of the matrix */ i__2 = *m - i__ + 1; i__1 = *n - i__ + 1; cgebd2_(&i__2, &i__1, &a[i__ + i__ * a_dim1], lda, &d__[i__], &e[i__], & tauq[i__], &taup[i__], &work[1], &iinfo); work[1].r = ws, work[1].i = 0.f; return 0; /* End of CGEBRD */ } /* cgebrd_ */ /* Subroutine */ int cgeev_(char *jobvl, char *jobvr, integer *n, complex *a, integer *lda, complex *w, complex *vl, integer *ldvl, complex *vr, integer *ldvr, complex *work, integer *lwork, real *rwork, integer * info) { /* System generated locals */ integer a_dim1, a_offset, vl_dim1, vl_offset, vr_dim1, vr_offset, i__1, i__2, i__3, i__4; real r__1, r__2; complex q__1, q__2; /* Builtin functions */ double sqrt(doublereal), r_imag(complex *); void r_cnjg(complex *, complex *); /* Local variables */ static integer i__, k, ihi; static real scl; static integer ilo; static real dum[1], eps; static complex tmp; static integer ibal; static char side[1]; static integer maxb; static real anrm; static integer ierr, itau, iwrk, nout; extern /* Subroutine */ int cscal_(integer *, complex *, complex *, integer *); extern logical lsame_(char *, char *); extern doublereal scnrm2_(integer *, complex *, integer *); extern /* Subroutine */ int cgebak_(char *, char *, integer *, integer *, integer *, real *, integer *, complex *, integer *, integer *), cgebal_(char *, integer *, complex *, integer *, integer *, integer *, real *, integer *), slabad_(real *, real *); static logical scalea; extern doublereal clange_(char *, integer *, integer *, complex *, integer *, real *); static real cscale; extern /* Subroutine */ int cgehrd_(integer *, integer *, integer *, complex *, integer *, complex *, complex *, integer *, integer *), clascl_(char *, integer *, integer *, real *, real *, integer *, integer *, complex *, integer *, integer *); extern doublereal slamch_(char *); extern /* Subroutine */ int csscal_(integer *, real *, complex *, integer *), clacpy_(char *, integer *, integer *, complex *, integer *, complex *, integer *), xerbla_(char *, integer *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); static logical select[1]; static real bignum; extern integer isamax_(integer *, real *, integer *); extern /* Subroutine */ int chseqr_(char *, char *, integer *, integer *, integer *, complex *, integer *, complex *, complex *, integer *, complex *, integer *, integer *), ctrevc_(char *, char *, logical *, integer *, complex *, integer *, complex *, integer *, complex *, integer *, integer *, integer *, complex *, real *, integer *), cunghr_(integer *, integer *, integer *, complex *, integer *, complex *, complex *, integer *, integer *); static integer minwrk, maxwrk; static logical wantvl; static real smlnum; static integer hswork, irwork; static logical lquery, wantvr; /* -- LAPACK driver routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= CGEEV computes for an N-by-N complex nonsymmetric matrix A, the eigenvalues and, optionally, the left and/or right eigenvectors. The right eigenvector v(j) of A satisfies A * v(j) = lambda(j) * v(j) where lambda(j) is its eigenvalue. The left eigenvector u(j) of A satisfies u(j)**H * A = lambda(j) * u(j)**H where u(j)**H denotes the conjugate transpose of u(j). The computed eigenvectors are normalized to have Euclidean norm equal to 1 and largest component real. Arguments ========= JOBVL (input) CHARACTER*1 = 'N': left eigenvectors of A are not computed; = 'V': left eigenvectors of are computed. JOBVR (input) CHARACTER*1 = 'N': right eigenvectors of A are not computed; = 'V': right eigenvectors of A are computed. N (input) INTEGER The order of the matrix A. N >= 0. A (input/output) COMPLEX array, dimension (LDA,N) On entry, the N-by-N matrix A. On exit, A has been overwritten. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,N). W (output) COMPLEX array, dimension (N) W contains the computed eigenvalues. VL (output) COMPLEX array, dimension (LDVL,N) If JOBVL = 'V', the left eigenvectors u(j) are stored one after another in the columns of VL, in the same order as their eigenvalues. If JOBVL = 'N', VL is not referenced. u(j) = VL(:,j), the j-th column of VL. LDVL (input) INTEGER The leading dimension of the array VL. LDVL >= 1; if JOBVL = 'V', LDVL >= N. VR (output) COMPLEX array, dimension (LDVR,N) If JOBVR = 'V', the right eigenvectors v(j) are stored one after another in the columns of VR, in the same order as their eigenvalues. If JOBVR = 'N', VR is not referenced. v(j) = VR(:,j), the j-th column of VR. LDVR (input) INTEGER The leading dimension of the array VR. LDVR >= 1; if JOBVR = 'V', LDVR >= N. WORK (workspace/output) COMPLEX array, dimension (LWORK) On exit, if INFO = 0, WORK(1) returns the optimal LWORK. LWORK (input) INTEGER The dimension of the array WORK. LWORK >= max(1,2*N). For good performance, LWORK must generally be larger. If LWORK = -1, then a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued by XERBLA. RWORK (workspace) REAL array, dimension (2*N) INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value. > 0: if INFO = i, the QR algorithm failed to compute all the eigenvalues, and no eigenvectors have been computed; elements and i+1:N of W contain eigenvalues which have converged. ===================================================================== Test the input arguments */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --w; vl_dim1 = *ldvl; vl_offset = 1 + vl_dim1; vl -= vl_offset; vr_dim1 = *ldvr; vr_offset = 1 + vr_dim1; vr -= vr_offset; --work; --rwork; /* Function Body */ *info = 0; lquery = *lwork == -1; wantvl = lsame_(jobvl, "V"); wantvr = lsame_(jobvr, "V"); if (! wantvl && ! lsame_(jobvl, "N")) { *info = -1; } else if (! wantvr && ! lsame_(jobvr, "N")) { *info = -2; } else if (*n < 0) { *info = -3; } else if (*lda < max(1,*n)) { *info = -5; } else if ((*ldvl < 1) || (wantvl && *ldvl < *n)) { *info = -8; } else if ((*ldvr < 1) || (wantvr && *ldvr < *n)) { *info = -10; } /* Compute workspace (Note: Comments in the code beginning "Workspace:" describe the minimal amount of workspace needed at that point in the code, as well as the preferred amount for good performance. CWorkspace refers to complex workspace, and RWorkspace to real workspace. NB refers to the optimal block size for the immediately following subroutine, as returned by ILAENV. HSWORK refers to the workspace preferred by CHSEQR, as calculated below. HSWORK is computed assuming ILO=1 and IHI=N, the worst case.) */ minwrk = 1; if (*info == 0 && ((*lwork >= 1) || (lquery))) { maxwrk = *n + *n * ilaenv_(&c__1, "CGEHRD", " ", n, &c__1, n, &c__0, ( ftnlen)6, (ftnlen)1); if (! wantvl && ! wantvr) { /* Computing MAX */ i__1 = 1, i__2 = (*n) << (1); minwrk = max(i__1,i__2); /* Computing MAX */ i__1 = ilaenv_(&c__8, "CHSEQR", "EN", n, &c__1, n, &c_n1, (ftnlen) 6, (ftnlen)2); maxb = max(i__1,2); /* Computing MIN Computing MAX */ i__3 = 2, i__4 = ilaenv_(&c__4, "CHSEQR", "EN", n, &c__1, n, & c_n1, (ftnlen)6, (ftnlen)2); i__1 = min(maxb,*n), i__2 = max(i__3,i__4); k = min(i__1,i__2); /* Computing MAX */ i__1 = k * (k + 2), i__2 = (*n) << (1); hswork = max(i__1,i__2); maxwrk = max(maxwrk,hswork); } else { /* Computing MAX */ i__1 = 1, i__2 = (*n) << (1); minwrk = max(i__1,i__2); /* Computing MAX */ i__1 = maxwrk, i__2 = *n + (*n - 1) * ilaenv_(&c__1, "CUNGHR", " ", n, &c__1, n, &c_n1, (ftnlen)6, (ftnlen)1); maxwrk = max(i__1,i__2); /* Computing MAX */ i__1 = ilaenv_(&c__8, "CHSEQR", "SV", n, &c__1, n, &c_n1, (ftnlen) 6, (ftnlen)2); maxb = max(i__1,2); /* Computing MIN Computing MAX */ i__3 = 2, i__4 = ilaenv_(&c__4, "CHSEQR", "SV", n, &c__1, n, & c_n1, (ftnlen)6, (ftnlen)2); i__1 = min(maxb,*n), i__2 = max(i__3,i__4); k = min(i__1,i__2); /* Computing MAX */ i__1 = k * (k + 2), i__2 = (*n) << (1); hswork = max(i__1,i__2); /* Computing MAX */ i__1 = max(maxwrk,hswork), i__2 = (*n) << (1); maxwrk = max(i__1,i__2); } work[1].r = (real) maxwrk, work[1].i = 0.f; } if (*lwork < minwrk && ! lquery) { *info = -12; } if (*info != 0) { i__1 = -(*info); xerbla_("CGEEV ", &i__1); return 0; } else if (lquery) { return 0; } /* Quick return if possible */ if (*n == 0) { return 0; } /* Get machine constants */ eps = slamch_("P"); smlnum = slamch_("S"); bignum = 1.f / smlnum; slabad_(&smlnum, &bignum); smlnum = sqrt(smlnum) / eps; bignum = 1.f / smlnum; /* Scale A if max element outside range [SMLNUM,BIGNUM] */ anrm = clange_("M", n, n, &a[a_offset], lda, dum); scalea = FALSE_; if (anrm > 0.f && anrm < smlnum) { scalea = TRUE_; cscale = smlnum; } else if (anrm > bignum) { scalea = TRUE_; cscale = bignum; } if (scalea) { clascl_("G", &c__0, &c__0, &anrm, &cscale, n, n, &a[a_offset], lda, & ierr); } /* Balance the matrix (CWorkspace: none) (RWorkspace: need N) */ ibal = 1; cgebal_("B", n, &a[a_offset], lda, &ilo, &ihi, &rwork[ibal], &ierr); /* Reduce to upper Hessenberg form (CWorkspace: need 2*N, prefer N+N*NB) (RWorkspace: none) */ itau = 1; iwrk = itau + *n; i__1 = *lwork - iwrk + 1; cgehrd_(n, &ilo, &ihi, &a[a_offset], lda, &work[itau], &work[iwrk], &i__1, &ierr); if (wantvl) { /* Want left eigenvectors Copy Householder vectors to VL */ *(unsigned char *)side = 'L'; clacpy_("L", n, n, &a[a_offset], lda, &vl[vl_offset], ldvl) ; /* Generate unitary matrix in VL (CWorkspace: need 2*N-1, prefer N+(N-1)*NB) (RWorkspace: none) */ i__1 = *lwork - iwrk + 1; cunghr_(n, &ilo, &ihi, &vl[vl_offset], ldvl, &work[itau], &work[iwrk], &i__1, &ierr); /* Perform QR iteration, accumulating Schur vectors in VL (CWorkspace: need 1, prefer HSWORK (see comments) ) (RWorkspace: none) */ iwrk = itau; i__1 = *lwork - iwrk + 1; chseqr_("S", "V", n, &ilo, &ihi, &a[a_offset], lda, &w[1], &vl[ vl_offset], ldvl, &work[iwrk], &i__1, info); if (wantvr) { /* Want left and right eigenvectors Copy Schur vectors to VR */ *(unsigned char *)side = 'B'; clacpy_("F", n, n, &vl[vl_offset], ldvl, &vr[vr_offset], ldvr); } } else if (wantvr) { /* Want right eigenvectors Copy Householder vectors to VR */ *(unsigned char *)side = 'R'; clacpy_("L", n, n, &a[a_offset], lda, &vr[vr_offset], ldvr) ; /* Generate unitary matrix in VR (CWorkspace: need 2*N-1, prefer N+(N-1)*NB) (RWorkspace: none) */ i__1 = *lwork - iwrk + 1; cunghr_(n, &ilo, &ihi, &vr[vr_offset], ldvr, &work[itau], &work[iwrk], &i__1, &ierr); /* Perform QR iteration, accumulating Schur vectors in VR (CWorkspace: need 1, prefer HSWORK (see comments) ) (RWorkspace: none) */ iwrk = itau; i__1 = *lwork - iwrk + 1; chseqr_("S", "V", n, &ilo, &ihi, &a[a_offset], lda, &w[1], &vr[ vr_offset], ldvr, &work[iwrk], &i__1, info); } else { /* Compute eigenvalues only (CWorkspace: need 1, prefer HSWORK (see comments) ) (RWorkspace: none) */ iwrk = itau; i__1 = *lwork - iwrk + 1; chseqr_("E", "N", n, &ilo, &ihi, &a[a_offset], lda, &w[1], &vr[ vr_offset], ldvr, &work[iwrk], &i__1, info); } /* If INFO > 0 from CHSEQR, then quit */ if (*info > 0) { goto L50; } if ((wantvl) || (wantvr)) { /* Compute left and/or right eigenvectors (CWorkspace: need 2*N) (RWorkspace: need 2*N) */ irwork = ibal + *n; ctrevc_(side, "B", select, n, &a[a_offset], lda, &vl[vl_offset], ldvl, &vr[vr_offset], ldvr, n, &nout, &work[iwrk], &rwork[irwork], &ierr); } if (wantvl) { /* Undo balancing of left eigenvectors (CWorkspace: none) (RWorkspace: need N) */ cgebak_("B", "L", n, &ilo, &ihi, &rwork[ibal], n, &vl[vl_offset], ldvl, &ierr); /* Normalize left eigenvectors and make largest component real */ i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { scl = 1.f / scnrm2_(n, &vl[i__ * vl_dim1 + 1], &c__1); csscal_(n, &scl, &vl[i__ * vl_dim1 + 1], &c__1); i__2 = *n; for (k = 1; k <= i__2; ++k) { i__3 = k + i__ * vl_dim1; /* Computing 2nd power */ r__1 = vl[i__3].r; /* Computing 2nd power */ r__2 = r_imag(&vl[k + i__ * vl_dim1]); rwork[irwork + k - 1] = r__1 * r__1 + r__2 * r__2; /* L10: */ } k = isamax_(n, &rwork[irwork], &c__1); r_cnjg(&q__2, &vl[k + i__ * vl_dim1]); r__1 = sqrt(rwork[irwork + k - 1]); q__1.r = q__2.r / r__1, q__1.i = q__2.i / r__1; tmp.r = q__1.r, tmp.i = q__1.i; cscal_(n, &tmp, &vl[i__ * vl_dim1 + 1], &c__1); i__2 = k + i__ * vl_dim1; i__3 = k + i__ * vl_dim1; r__1 = vl[i__3].r; q__1.r = r__1, q__1.i = 0.f; vl[i__2].r = q__1.r, vl[i__2].i = q__1.i; /* L20: */ } } if (wantvr) { /* Undo balancing of right eigenvectors (CWorkspace: none) (RWorkspace: need N) */ cgebak_("B", "R", n, &ilo, &ihi, &rwork[ibal], n, &vr[vr_offset], ldvr, &ierr); /* Normalize right eigenvectors and make largest component real */ i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { scl = 1.f / scnrm2_(n, &vr[i__ * vr_dim1 + 1], &c__1); csscal_(n, &scl, &vr[i__ * vr_dim1 + 1], &c__1); i__2 = *n; for (k = 1; k <= i__2; ++k) { i__3 = k + i__ * vr_dim1; /* Computing 2nd power */ r__1 = vr[i__3].r; /* Computing 2nd power */ r__2 = r_imag(&vr[k + i__ * vr_dim1]); rwork[irwork + k - 1] = r__1 * r__1 + r__2 * r__2; /* L30: */ } k = isamax_(n, &rwork[irwork], &c__1); r_cnjg(&q__2, &vr[k + i__ * vr_dim1]); r__1 = sqrt(rwork[irwork + k - 1]); q__1.r = q__2.r / r__1, q__1.i = q__2.i / r__1; tmp.r = q__1.r, tmp.i = q__1.i; cscal_(n, &tmp, &vr[i__ * vr_dim1 + 1], &c__1); i__2 = k + i__ * vr_dim1; i__3 = k + i__ * vr_dim1; r__1 = vr[i__3].r; q__1.r = r__1, q__1.i = 0.f; vr[i__2].r = q__1.r, vr[i__2].i = q__1.i; /* L40: */ } } /* Undo scaling if necessary */ L50: if (scalea) { i__1 = *n - *info; /* Computing MAX */ i__3 = *n - *info; i__2 = max(i__3,1); clascl_("G", &c__0, &c__0, &cscale, &anrm, &i__1, &c__1, &w[*info + 1] , &i__2, &ierr); if (*info > 0) { i__1 = ilo - 1; clascl_("G", &c__0, &c__0, &cscale, &anrm, &i__1, &c__1, &w[1], n, &ierr); } } work[1].r = (real) maxwrk, work[1].i = 0.f; return 0; /* End of CGEEV */ } /* cgeev_ */ /* Subroutine */ int cgehd2_(integer *n, integer *ilo, integer *ihi, complex * a, integer *lda, complex *tau, complex *work, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3; complex q__1; /* Builtin functions */ void r_cnjg(complex *, complex *); /* Local variables */ static integer i__; static complex alpha; extern /* Subroutine */ int clarf_(char *, integer *, integer *, complex * , integer *, complex *, complex *, integer *, complex *), clarfg_(integer *, complex *, complex *, integer *, complex *), xerbla_(char *, integer *); /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University September 30, 1994 Purpose ======= CGEHD2 reduces a complex general matrix A to upper Hessenberg form H by a unitary similarity transformation: Q' * A * Q = H . Arguments ========= N (input) INTEGER The order of the matrix A. N >= 0. ILO (input) INTEGER IHI (input) INTEGER It is assumed that A is already upper triangular in rows and columns 1:ILO-1 and IHI+1:N. ILO and IHI are normally set by a previous call to CGEBAL; otherwise they should be set to 1 and N respectively. See Further Details. 1 <= ILO <= IHI <= max(1,N). A (input/output) COMPLEX array, dimension (LDA,N) On entry, the n by n general matrix to be reduced. On exit, the upper triangle and the first subdiagonal of A are overwritten with the upper Hessenberg matrix H, and the elements below the first subdiagonal, with the array TAU, represent the unitary matrix Q as a product of elementary reflectors. See Further Details. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,N). TAU (output) COMPLEX array, dimension (N-1) The scalar factors of the elementary reflectors (see Further Details). WORK (workspace) COMPLEX array, dimension (N) INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value. Further Details =============== The matrix Q is represented as a product of (ihi-ilo) elementary reflectors Q = H(ilo) H(ilo+1) . . . H(ihi-1). Each H(i) has the form H(i) = I - tau * v * v' where tau is a complex scalar, and v is a complex vector with v(1:i) = 0, v(i+1) = 1 and v(ihi+1:n) = 0; v(i+2:ihi) is stored on exit in A(i+2:ihi,i), and tau in TAU(i). The contents of A are illustrated by the following example, with n = 7, ilo = 2 and ihi = 6: on entry, on exit, ( a a a a a a a ) ( a a h h h h a ) ( a a a a a a ) ( a h h h h a ) ( a a a a a a ) ( h h h h h h ) ( a a a a a a ) ( v2 h h h h h ) ( a a a a a a ) ( v2 v3 h h h h ) ( a a a a a a ) ( v2 v3 v4 h h h ) ( a ) ( a ) where a denotes an element of the original matrix A, h denotes a modified element of the upper Hessenberg matrix H, and vi denotes an element of the vector defining H(i). ===================================================================== Test the input parameters */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --tau; --work; /* Function Body */ *info = 0; if (*n < 0) { *info = -1; } else if ((*ilo < 1) || (*ilo > max(1,*n))) { *info = -2; } else if ((*ihi < min(*ilo,*n)) || (*ihi > *n)) { *info = -3; } else if (*lda < max(1,*n)) { *info = -5; } if (*info != 0) { i__1 = -(*info); xerbla_("CGEHD2", &i__1); return 0; } i__1 = *ihi - 1; for (i__ = *ilo; i__ <= i__1; ++i__) { /* Compute elementary reflector H(i) to annihilate A(i+2:ihi,i) */ i__2 = i__ + 1 + i__ * a_dim1; alpha.r = a[i__2].r, alpha.i = a[i__2].i; i__2 = *ihi - i__; /* Computing MIN */ i__3 = i__ + 2; clarfg_(&i__2, &alpha, &a[min(i__3,*n) + i__ * a_dim1], &c__1, &tau[ i__]); i__2 = i__ + 1 + i__ * a_dim1; a[i__2].r = 1.f, a[i__2].i = 0.f; /* Apply H(i) to A(1:ihi,i+1:ihi) from the right */ i__2 = *ihi - i__; clarf_("Right", ihi, &i__2, &a[i__ + 1 + i__ * a_dim1], &c__1, &tau[ i__], &a[(i__ + 1) * a_dim1 + 1], lda, &work[1]); /* Apply H(i)' to A(i+1:ihi,i+1:n) from the left */ i__2 = *ihi - i__; i__3 = *n - i__; r_cnjg(&q__1, &tau[i__]); clarf_("Left", &i__2, &i__3, &a[i__ + 1 + i__ * a_dim1], &c__1, &q__1, &a[i__ + 1 + (i__ + 1) * a_dim1], lda, &work[1]); i__2 = i__ + 1 + i__ * a_dim1; a[i__2].r = alpha.r, a[i__2].i = alpha.i; /* L10: */ } return 0; /* End of CGEHD2 */ } /* cgehd2_ */ /* Subroutine */ int cgehrd_(integer *n, integer *ilo, integer *ihi, complex * a, integer *lda, complex *tau, complex *work, integer *lwork, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3, i__4; complex q__1; /* Local variables */ static integer i__; static complex t[4160] /* was [65][64] */; static integer ib; static complex ei; static integer nb, nh, nx, iws; extern /* Subroutine */ int cgemm_(char *, char *, integer *, integer *, integer *, complex *, complex *, integer *, complex *, integer *, complex *, complex *, integer *); static integer nbmin, iinfo; extern /* Subroutine */ int cgehd2_(integer *, integer *, integer *, complex *, integer *, complex *, complex *, integer *), clarfb_( char *, char *, char *, char *, integer *, integer *, integer *, complex *, integer *, complex *, integer *, complex *, integer *, complex *, integer *), clahrd_( integer *, integer *, integer *, complex *, integer *, complex *, complex *, integer *, complex *, integer *), xerbla_(char *, integer *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); static integer ldwork, lwkopt; static logical lquery; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= CGEHRD reduces a complex general matrix A to upper Hessenberg form H by a unitary similarity transformation: Q' * A * Q = H . Arguments ========= N (input) INTEGER The order of the matrix A. N >= 0. ILO (input) INTEGER IHI (input) INTEGER It is assumed that A is already upper triangular in rows and columns 1:ILO-1 and IHI+1:N. ILO and IHI are normally set by a previous call to CGEBAL; otherwise they should be set to 1 and N respectively. See Further Details. 1 <= ILO <= IHI <= N, if N > 0; ILO=1 and IHI=0, if N=0. A (input/output) COMPLEX array, dimension (LDA,N) On entry, the N-by-N general matrix to be reduced. On exit, the upper triangle and the first subdiagonal of A are overwritten with the upper Hessenberg matrix H, and the elements below the first subdiagonal, with the array TAU, represent the unitary matrix Q as a product of elementary reflectors. See Further Details. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,N). TAU (output) COMPLEX array, dimension (N-1) The scalar factors of the elementary reflectors (see Further Details). Elements 1:ILO-1 and IHI:N-1 of TAU are set to zero. WORK (workspace/output) COMPLEX array, dimension (LWORK) On exit, if INFO = 0, WORK(1) returns the optimal LWORK. LWORK (input) INTEGER The length of the array WORK. LWORK >= max(1,N). For optimum performance LWORK >= N*NB, where NB is the optimal blocksize. If LWORK = -1, then a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued by XERBLA. INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value. Further Details =============== The matrix Q is represented as a product of (ihi-ilo) elementary reflectors Q = H(ilo) H(ilo+1) . . . H(ihi-1). Each H(i) has the form H(i) = I - tau * v * v' where tau is a complex scalar, and v is a complex vector with v(1:i) = 0, v(i+1) = 1 and v(ihi+1:n) = 0; v(i+2:ihi) is stored on exit in A(i+2:ihi,i), and tau in TAU(i). The contents of A are illustrated by the following example, with n = 7, ilo = 2 and ihi = 6: on entry, on exit, ( a a a a a a a ) ( a a h h h h a ) ( a a a a a a ) ( a h h h h a ) ( a a a a a a ) ( h h h h h h ) ( a a a a a a ) ( v2 h h h h h ) ( a a a a a a ) ( v2 v3 h h h h ) ( a a a a a a ) ( v2 v3 v4 h h h ) ( a ) ( a ) where a denotes an element of the original matrix A, h denotes a modified element of the upper Hessenberg matrix H, and vi denotes an element of the vector defining H(i). ===================================================================== Test the input parameters */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --tau; --work; /* Function Body */ *info = 0; /* Computing MIN */ i__1 = 64, i__2 = ilaenv_(&c__1, "CGEHRD", " ", n, ilo, ihi, &c_n1, ( ftnlen)6, (ftnlen)1); nb = min(i__1,i__2); lwkopt = *n * nb; work[1].r = (real) lwkopt, work[1].i = 0.f; lquery = *lwork == -1; if (*n < 0) { *info = -1; } else if ((*ilo < 1) || (*ilo > max(1,*n))) { *info = -2; } else if ((*ihi < min(*ilo,*n)) || (*ihi > *n)) { *info = -3; } else if (*lda < max(1,*n)) { *info = -5; } else if (*lwork < max(1,*n) && ! lquery) { *info = -8; } if (*info != 0) { i__1 = -(*info); xerbla_("CGEHRD", &i__1); return 0; } else if (lquery) { return 0; } /* Set elements 1:ILO-1 and IHI:N-1 of TAU to zero */ i__1 = *ilo - 1; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = i__; tau[i__2].r = 0.f, tau[i__2].i = 0.f; /* L10: */ } i__1 = *n - 1; for (i__ = max(1,*ihi); i__ <= i__1; ++i__) { i__2 = i__; tau[i__2].r = 0.f, tau[i__2].i = 0.f; /* L20: */ } /* Quick return if possible */ nh = *ihi - *ilo + 1; if (nh <= 1) { work[1].r = 1.f, work[1].i = 0.f; return 0; } nbmin = 2; iws = 1; if (nb > 1 && nb < nh) { /* Determine when to cross over from blocked to unblocked code (last block is always handled by unblocked code). Computing MAX */ i__1 = nb, i__2 = ilaenv_(&c__3, "CGEHRD", " ", n, ilo, ihi, &c_n1, ( ftnlen)6, (ftnlen)1); nx = max(i__1,i__2); if (nx < nh) { /* Determine if workspace is large enough for blocked code. */ iws = *n * nb; if (*lwork < iws) { /* Not enough workspace to use optimal NB: determine the minimum value of NB, and reduce NB or force use of unblocked code. Computing MAX */ i__1 = 2, i__2 = ilaenv_(&c__2, "CGEHRD", " ", n, ilo, ihi, & c_n1, (ftnlen)6, (ftnlen)1); nbmin = max(i__1,i__2); if (*lwork >= *n * nbmin) { nb = *lwork / *n; } else { nb = 1; } } } } ldwork = *n; if ((nb < nbmin) || (nb >= nh)) { /* Use unblocked code below */ i__ = *ilo; } else { /* Use blocked code */ i__1 = *ihi - 1 - nx; i__2 = nb; for (i__ = *ilo; i__2 < 0 ? i__ >= i__1 : i__ <= i__1; i__ += i__2) { /* Computing MIN */ i__3 = nb, i__4 = *ihi - i__; ib = min(i__3,i__4); /* Reduce columns i:i+ib-1 to Hessenberg form, returning the matrices V and T of the block reflector H = I - V*T*V' which performs the reduction, and also the matrix Y = A*V*T */ clahrd_(ihi, &i__, &ib, &a[i__ * a_dim1 + 1], lda, &tau[i__], t, & c__65, &work[1], &ldwork); /* Apply the block reflector H to A(1:ihi,i+ib:ihi) from the right, computing A := A - Y * V'. V(i+ib,ib-1) must be set to 1. */ i__3 = i__ + ib + (i__ + ib - 1) * a_dim1; ei.r = a[i__3].r, ei.i = a[i__3].i; i__3 = i__ + ib + (i__ + ib - 1) * a_dim1; a[i__3].r = 1.f, a[i__3].i = 0.f; i__3 = *ihi - i__ - ib + 1; q__1.r = -1.f, q__1.i = -0.f; cgemm_("No transpose", "Conjugate transpose", ihi, &i__3, &ib, & q__1, &work[1], &ldwork, &a[i__ + ib + i__ * a_dim1], lda, &c_b56, &a[(i__ + ib) * a_dim1 + 1], lda); i__3 = i__ + ib + (i__ + ib - 1) * a_dim1; a[i__3].r = ei.r, a[i__3].i = ei.i; /* Apply the block reflector H to A(i+1:ihi,i+ib:n) from the left */ i__3 = *ihi - i__; i__4 = *n - i__ - ib + 1; clarfb_("Left", "Conjugate transpose", "Forward", "Columnwise", & i__3, &i__4, &ib, &a[i__ + 1 + i__ * a_dim1], lda, t, & c__65, &a[i__ + 1 + (i__ + ib) * a_dim1], lda, &work[1], & ldwork); /* L30: */ } } /* Use unblocked code to reduce the rest of the matrix */ cgehd2_(n, &i__, ihi, &a[a_offset], lda, &tau[1], &work[1], &iinfo); work[1].r = (real) iws, work[1].i = 0.f; return 0; /* End of CGEHRD */ } /* cgehrd_ */ /* Subroutine */ int cgelq2_(integer *m, integer *n, complex *a, integer *lda, complex *tau, complex *work, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3; /* Local variables */ static integer i__, k; static complex alpha; extern /* Subroutine */ int clarf_(char *, integer *, integer *, complex * , integer *, complex *, complex *, integer *, complex *), clarfg_(integer *, complex *, complex *, integer *, complex *), clacgv_(integer *, complex *, integer *), xerbla_(char *, integer *); /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University September 30, 1994 Purpose ======= CGELQ2 computes an LQ factorization of a complex m by n matrix A: A = L * Q. Arguments ========= M (input) INTEGER The number of rows of the matrix A. M >= 0. N (input) INTEGER The number of columns of the matrix A. N >= 0. A (input/output) COMPLEX array, dimension (LDA,N) On entry, the m by n matrix A. On exit, the elements on and below the diagonal of the array contain the m by min(m,n) lower trapezoidal matrix L (L is lower triangular if m <= n); the elements above the diagonal, with the array TAU, represent the unitary matrix Q as a product of elementary reflectors (see Further Details). LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,M). TAU (output) COMPLEX array, dimension (min(M,N)) The scalar factors of the elementary reflectors (see Further Details). WORK (workspace) COMPLEX array, dimension (M) INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value Further Details =============== The matrix Q is represented as a product of elementary reflectors Q = H(k)' . . . H(2)' H(1)', where k = min(m,n). Each H(i) has the form H(i) = I - tau * v * v' where tau is a complex scalar, and v is a complex vector with v(1:i-1) = 0 and v(i) = 1; conjg(v(i+1:n)) is stored on exit in A(i,i+1:n), and tau in TAU(i). ===================================================================== Test the input arguments */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --tau; --work; /* Function Body */ *info = 0; if (*m < 0) { *info = -1; } else if (*n < 0) { *info = -2; } else if (*lda < max(1,*m)) { *info = -4; } if (*info != 0) { i__1 = -(*info); xerbla_("CGELQ2", &i__1); return 0; } k = min(*m,*n); i__1 = k; for (i__ = 1; i__ <= i__1; ++i__) { /* Generate elementary reflector H(i) to annihilate A(i,i+1:n) */ i__2 = *n - i__ + 1; clacgv_(&i__2, &a[i__ + i__ * a_dim1], lda); i__2 = i__ + i__ * a_dim1; alpha.r = a[i__2].r, alpha.i = a[i__2].i; i__2 = *n - i__ + 1; /* Computing MIN */ i__3 = i__ + 1; clarfg_(&i__2, &alpha, &a[i__ + min(i__3,*n) * a_dim1], lda, &tau[i__] ); if (i__ < *m) { /* Apply H(i) to A(i+1:m,i:n) from the right */ i__2 = i__ + i__ * a_dim1; a[i__2].r = 1.f, a[i__2].i = 0.f; i__2 = *m - i__; i__3 = *n - i__ + 1; clarf_("Right", &i__2, &i__3, &a[i__ + i__ * a_dim1], lda, &tau[ i__], &a[i__ + 1 + i__ * a_dim1], lda, &work[1]); } i__2 = i__ + i__ * a_dim1; a[i__2].r = alpha.r, a[i__2].i = alpha.i; i__2 = *n - i__ + 1; clacgv_(&i__2, &a[i__ + i__ * a_dim1], lda); /* L10: */ } return 0; /* End of CGELQ2 */ } /* cgelq2_ */ /* Subroutine */ int cgelqf_(integer *m, integer *n, complex *a, integer *lda, complex *tau, complex *work, integer *lwork, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3, i__4; /* Local variables */ static integer i__, k, ib, nb, nx, iws, nbmin, iinfo; extern /* Subroutine */ int cgelq2_(integer *, integer *, complex *, integer *, complex *, complex *, integer *), clarfb_(char *, char *, char *, char *, integer *, integer *, integer *, complex *, integer *, complex *, integer *, complex *, integer *, complex *, integer *), clarft_(char *, char * , integer *, integer *, complex *, integer *, complex *, complex * , integer *), xerbla_(char *, integer *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); static integer ldwork, lwkopt; static logical lquery; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= CGELQF computes an LQ factorization of a complex M-by-N matrix A: A = L * Q. Arguments ========= M (input) INTEGER The number of rows of the matrix A. M >= 0. N (input) INTEGER The number of columns of the matrix A. N >= 0. A (input/output) COMPLEX array, dimension (LDA,N) On entry, the M-by-N matrix A. On exit, the elements on and below the diagonal of the array contain the m-by-min(m,n) lower trapezoidal matrix L (L is lower triangular if m <= n); the elements above the diagonal, with the array TAU, represent the unitary matrix Q as a product of elementary reflectors (see Further Details). LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,M). TAU (output) COMPLEX array, dimension (min(M,N)) The scalar factors of the elementary reflectors (see Further Details). WORK (workspace/output) COMPLEX array, dimension (LWORK) On exit, if INFO = 0, WORK(1) returns the optimal LWORK. LWORK (input) INTEGER The dimension of the array WORK. LWORK >= max(1,M). For optimum performance LWORK >= M*NB, where NB is the optimal blocksize. If LWORK = -1, then a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued by XERBLA. INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value Further Details =============== The matrix Q is represented as a product of elementary reflectors Q = H(k)' . . . H(2)' H(1)', where k = min(m,n). Each H(i) has the form H(i) = I - tau * v * v' where tau is a complex scalar, and v is a complex vector with v(1:i-1) = 0 and v(i) = 1; conjg(v(i+1:n)) is stored on exit in A(i,i+1:n), and tau in TAU(i). ===================================================================== Test the input arguments */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --tau; --work; /* Function Body */ *info = 0; nb = ilaenv_(&c__1, "CGELQF", " ", m, n, &c_n1, &c_n1, (ftnlen)6, (ftnlen) 1); lwkopt = *m * nb; work[1].r = (real) lwkopt, work[1].i = 0.f; lquery = *lwork == -1; if (*m < 0) { *info = -1; } else if (*n < 0) { *info = -2; } else if (*lda < max(1,*m)) { *info = -4; } else if (*lwork < max(1,*m) && ! lquery) { *info = -7; } if (*info != 0) { i__1 = -(*info); xerbla_("CGELQF", &i__1); return 0; } else if (lquery) { return 0; } /* Quick return if possible */ k = min(*m,*n); if (k == 0) { work[1].r = 1.f, work[1].i = 0.f; return 0; } nbmin = 2; nx = 0; iws = *m; if (nb > 1 && nb < k) { /* Determine when to cross over from blocked to unblocked code. Computing MAX */ i__1 = 0, i__2 = ilaenv_(&c__3, "CGELQF", " ", m, n, &c_n1, &c_n1, ( ftnlen)6, (ftnlen)1); nx = max(i__1,i__2); if (nx < k) { /* Determine if workspace is large enough for blocked code. */ ldwork = *m; iws = ldwork * nb; if (*lwork < iws) { /* Not enough workspace to use optimal NB: reduce NB and determine the minimum value of NB. */ nb = *lwork / ldwork; /* Computing MAX */ i__1 = 2, i__2 = ilaenv_(&c__2, "CGELQF", " ", m, n, &c_n1, & c_n1, (ftnlen)6, (ftnlen)1); nbmin = max(i__1,i__2); } } } if (nb >= nbmin && nb < k && nx < k) { /* Use blocked code initially */ i__1 = k - nx; i__2 = nb; for (i__ = 1; i__2 < 0 ? i__ >= i__1 : i__ <= i__1; i__ += i__2) { /* Computing MIN */ i__3 = k - i__ + 1; ib = min(i__3,nb); /* Compute the LQ factorization of the current block A(i:i+ib-1,i:n) */ i__3 = *n - i__ + 1; cgelq2_(&ib, &i__3, &a[i__ + i__ * a_dim1], lda, &tau[i__], &work[ 1], &iinfo); if (i__ + ib <= *m) { /* Form the triangular factor of the block reflector H = H(i) H(i+1) . . . H(i+ib-1) */ i__3 = *n - i__ + 1; clarft_("Forward", "Rowwise", &i__3, &ib, &a[i__ + i__ * a_dim1], lda, &tau[i__], &work[1], &ldwork); /* Apply H to A(i+ib:m,i:n) from the right */ i__3 = *m - i__ - ib + 1; i__4 = *n - i__ + 1; clarfb_("Right", "No transpose", "Forward", "Rowwise", &i__3, &i__4, &ib, &a[i__ + i__ * a_dim1], lda, &work[1], & ldwork, &a[i__ + ib + i__ * a_dim1], lda, &work[ib + 1], &ldwork); } /* L10: */ } } else { i__ = 1; } /* Use unblocked code to factor the last or only block. */ if (i__ <= k) { i__2 = *m - i__ + 1; i__1 = *n - i__ + 1; cgelq2_(&i__2, &i__1, &a[i__ + i__ * a_dim1], lda, &tau[i__], &work[1] , &iinfo); } work[1].r = (real) iws, work[1].i = 0.f; return 0; /* End of CGELQF */ } /* cgelqf_ */ /* Subroutine */ int cgelsd_(integer *m, integer *n, integer *nrhs, complex * a, integer *lda, complex *b, integer *ldb, real *s, real *rcond, integer *rank, complex *work, integer *lwork, real *rwork, integer * iwork, integer *info) { /* System generated locals */ integer a_dim1, a_offset, b_dim1, b_offset, i__1, i__2, i__3, i__4; real r__1; complex q__1; /* Local variables */ static integer ie, il, mm; static real eps, anrm, bnrm; static integer itau, iascl, ibscl; static real sfmin; static integer minmn, maxmn, itaup, itauq, mnthr, nwork; extern /* Subroutine */ int cgebrd_(integer *, integer *, complex *, integer *, real *, real *, complex *, complex *, complex *, integer *, integer *), slabad_(real *, real *); extern doublereal clange_(char *, integer *, integer *, complex *, integer *, real *); extern /* Subroutine */ int cgelqf_(integer *, integer *, complex *, integer *, complex *, complex *, integer *, integer *), clalsd_( char *, integer *, integer *, integer *, real *, real *, complex * , integer *, real *, integer *, complex *, real *, integer *, integer *), clascl_(char *, integer *, integer *, real *, real *, integer *, integer *, complex *, integer *, integer *), cgeqrf_(integer *, integer *, complex *, integer *, complex *, complex *, integer *, integer *); extern doublereal slamch_(char *); extern /* Subroutine */ int clacpy_(char *, integer *, integer *, complex *, integer *, complex *, integer *), claset_(char *, integer *, integer *, complex *, complex *, complex *, integer *), xerbla_(char *, integer *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); static real bignum; extern /* Subroutine */ int slascl_(char *, integer *, integer *, real *, real *, integer *, integer *, real *, integer *, integer *), cunmbr_(char *, char *, char *, integer *, integer *, integer *, complex *, integer *, complex *, complex *, integer *, complex *, integer *, integer *), slaset_( char *, integer *, integer *, real *, real *, real *, integer *), cunmlq_(char *, char *, integer *, integer *, integer *, complex *, integer *, complex *, complex *, integer *, complex *, integer *, integer *); static integer ldwork; extern /* Subroutine */ int cunmqr_(char *, char *, integer *, integer *, integer *, complex *, integer *, complex *, complex *, integer *, complex *, integer *, integer *); static integer minwrk, maxwrk; static real smlnum; static logical lquery; static integer nrwork, smlsiz; /* -- LAPACK driver routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University October 31, 1999 Purpose ======= CGELSD computes the minimum-norm solution to a real linear least squares problem: minimize 2-norm(| b - A*x |) using the singular value decomposition (SVD) of A. A is an M-by-N matrix which may be rank-deficient. Several right hand side vectors b and solution vectors x can be handled in a single call; they are stored as the columns of the M-by-NRHS right hand side matrix B and the N-by-NRHS solution matrix X. The problem is solved in three steps: (1) Reduce the coefficient matrix A to bidiagonal form with Householder tranformations, reducing the original problem into a "bidiagonal least squares problem" (BLS) (2) Solve the BLS using a divide and conquer approach. (3) Apply back all the Householder tranformations to solve the original least squares problem. The effective rank of A is determined by treating as zero those singular values which are less than RCOND times the largest singular value. The divide and conquer algorithm makes very mild assumptions about floating point arithmetic. It will work on machines with a guard digit in add/subtract, or on those binary machines without guard digits which subtract like the Cray X-MP, Cray Y-MP, Cray C-90, or Cray-2. It could conceivably fail on hexadecimal or decimal machines without guard digits, but we know of none. Arguments ========= M (input) INTEGER The number of rows of the matrix A. M >= 0. N (input) INTEGER The number of columns of the matrix A. N >= 0. NRHS (input) INTEGER The number of right hand sides, i.e., the number of columns of the matrices B and X. NRHS >= 0. A (input/output) COMPLEX array, dimension (LDA,N) On entry, the M-by-N matrix A. On exit, A has been destroyed. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,M). B (input/output) COMPLEX array, dimension (LDB,NRHS) On entry, the M-by-NRHS right hand side matrix B. On exit, B is overwritten by the N-by-NRHS solution matrix X. If m >= n and RANK = n, the residual sum-of-squares for the solution in the i-th column is given by the sum of squares of elements n+1:m in that column. LDB (input) INTEGER The leading dimension of the array B. LDB >= max(1,M,N). S (output) REAL array, dimension (min(M,N)) The singular values of A in decreasing order. The condition number of A in the 2-norm = S(1)/S(min(m,n)). RCOND (input) REAL RCOND is used to determine the effective rank of A. Singular values S(i) <= RCOND*S(1) are treated as zero. If RCOND < 0, machine precision is used instead. RANK (output) INTEGER The effective rank of A, i.e., the number of singular values which are greater than RCOND*S(1). WORK (workspace/output) COMPLEX array, dimension (LWORK) On exit, if INFO = 0, WORK(1) returns the optimal LWORK. LWORK (input) INTEGER The dimension of the array WORK. LWORK must be at least 1. The exact minimum amount of workspace needed depends on M, N and NRHS. As long as LWORK is at least 2 * N + N * NRHS if M is greater than or equal to N or 2 * M + M * NRHS if M is less than N, the code will execute correctly. For good performance, LWORK should generally be larger. If LWORK = -1, then a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued by XERBLA. RWORK (workspace) REAL array, dimension at least 10*N + 2*N*SMLSIZ + 8*N*NLVL + 3*SMLSIZ*NRHS + (SMLSIZ+1)**2 if M is greater than or equal to N or 10*M + 2*M*SMLSIZ + 8*M*NLVL + 3*SMLSIZ*NRHS + (SMLSIZ+1)**2 if M is less than N, the code will execute correctly. SMLSIZ is returned by ILAENV and is equal to the maximum size of the subproblems at the bottom of the computation tree (usually about 25), and NLVL = MAX( 0, INT( LOG_2( MIN( M,N )/(SMLSIZ+1) ) ) + 1 ) IWORK (workspace) INTEGER array, dimension (LIWORK) LIWORK >= 3 * MINMN * NLVL + 11 * MINMN, where MINMN = MIN( M,N ). INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value. > 0: the algorithm for computing the SVD failed to converge; if INFO = i, i off-diagonal elements of an intermediate bidiagonal form did not converge to zero. Further Details =============== Based on contributions by Ming Gu and Ren-Cang Li, Computer Science Division, University of California at Berkeley, USA Osni Marques, LBNL/NERSC, USA ===================================================================== Test the input arguments. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; b_dim1 = *ldb; b_offset = 1 + b_dim1; b -= b_offset; --s; --work; --rwork; --iwork; /* Function Body */ *info = 0; minmn = min(*m,*n); maxmn = max(*m,*n); mnthr = ilaenv_(&c__6, "CGELSD", " ", m, n, nrhs, &c_n1, (ftnlen)6, ( ftnlen)1); lquery = *lwork == -1; if (*m < 0) { *info = -1; } else if (*n < 0) { *info = -2; } else if (*nrhs < 0) { *info = -3; } else if (*lda < max(1,*m)) { *info = -5; } else if (*ldb < max(1,maxmn)) { *info = -7; } smlsiz = ilaenv_(&c__9, "CGELSD", " ", &c__0, &c__0, &c__0, &c__0, ( ftnlen)6, (ftnlen)1); /* Compute workspace. (Note: Comments in the code beginning "Workspace:" describe the minimal amount of workspace needed at that point in the code, as well as the preferred amount for good performance. NB refers to the optimal block size for the immediately following subroutine, as returned by ILAENV.) */ minwrk = 1; if (*info == 0) { maxwrk = 0; mm = *m; if (*m >= *n && *m >= mnthr) { /* Path 1a - overdetermined, with many more rows than columns. */ mm = *n; /* Computing MAX */ i__1 = maxwrk, i__2 = *n * ilaenv_(&c__1, "CGEQRF", " ", m, n, & c_n1, &c_n1, (ftnlen)6, (ftnlen)1); maxwrk = max(i__1,i__2); /* Computing MAX */ i__1 = maxwrk, i__2 = *nrhs * ilaenv_(&c__1, "CUNMQR", "LC", m, nrhs, n, &c_n1, (ftnlen)6, (ftnlen)2); maxwrk = max(i__1,i__2); } if (*m >= *n) { /* Path 1 - overdetermined or exactly determined. Computing MAX */ i__1 = maxwrk, i__2 = ((*n) << (1)) + (mm + *n) * ilaenv_(&c__1, "CGEBRD", " ", &mm, n, &c_n1, &c_n1, (ftnlen)6, (ftnlen)1) ; maxwrk = max(i__1,i__2); /* Computing MAX */ i__1 = maxwrk, i__2 = ((*n) << (1)) + *nrhs * ilaenv_(&c__1, "CUNMBR", "QLC", &mm, nrhs, n, &c_n1, (ftnlen)6, (ftnlen) 3); maxwrk = max(i__1,i__2); /* Computing MAX */ i__1 = maxwrk, i__2 = ((*n) << (1)) + (*n - 1) * ilaenv_(&c__1, "CUNMBR", "PLN", n, nrhs, n, &c_n1, (ftnlen)6, (ftnlen)3); maxwrk = max(i__1,i__2); /* Computing MAX */ i__1 = maxwrk, i__2 = ((*n) << (1)) + *n * *nrhs; maxwrk = max(i__1,i__2); /* Computing MAX */ i__1 = ((*n) << (1)) + mm, i__2 = ((*n) << (1)) + *n * *nrhs; minwrk = max(i__1,i__2); } if (*n > *m) { if (*n >= mnthr) { /* Path 2a - underdetermined, with many more columns than rows. */ maxwrk = *m + *m * ilaenv_(&c__1, "CGELQF", " ", m, n, &c_n1, &c_n1, (ftnlen)6, (ftnlen)1); /* Computing MAX */ i__1 = maxwrk, i__2 = *m * *m + ((*m) << (2)) + ((*m) << (1)) * ilaenv_(&c__1, "CGEBRD", " ", m, m, &c_n1, &c_n1, ( ftnlen)6, (ftnlen)1); maxwrk = max(i__1,i__2); /* Computing MAX */ i__1 = maxwrk, i__2 = *m * *m + ((*m) << (2)) + *nrhs * ilaenv_(&c__1, "CUNMBR", "QLC", m, nrhs, m, &c_n1, ( ftnlen)6, (ftnlen)3); maxwrk = max(i__1,i__2); /* Computing MAX */ i__1 = maxwrk, i__2 = *m * *m + ((*m) << (2)) + (*m - 1) * ilaenv_(&c__1, "CUNMLQ", "LC", n, nrhs, m, &c_n1, ( ftnlen)6, (ftnlen)2); maxwrk = max(i__1,i__2); if (*nrhs > 1) { /* Computing MAX */ i__1 = maxwrk, i__2 = *m * *m + *m + *m * *nrhs; maxwrk = max(i__1,i__2); } else { /* Computing MAX */ i__1 = maxwrk, i__2 = *m * *m + ((*m) << (1)); maxwrk = max(i__1,i__2); } /* Computing MAX */ i__1 = maxwrk, i__2 = *m * *m + ((*m) << (2)) + *m * *nrhs; maxwrk = max(i__1,i__2); } else { /* Path 2 - underdetermined. */ maxwrk = ((*m) << (1)) + (*n + *m) * ilaenv_(&c__1, "CGEBRD", " ", m, n, &c_n1, &c_n1, (ftnlen)6, (ftnlen)1); /* Computing MAX */ i__1 = maxwrk, i__2 = ((*m) << (1)) + *nrhs * ilaenv_(&c__1, "CUNMBR", "QLC", m, nrhs, m, &c_n1, (ftnlen)6, ( ftnlen)3); maxwrk = max(i__1,i__2); /* Computing MAX */ i__1 = maxwrk, i__2 = ((*m) << (1)) + *m * ilaenv_(&c__1, "CUNMBR", "PLN", n, nrhs, m, &c_n1, (ftnlen)6, ( ftnlen)3); maxwrk = max(i__1,i__2); /* Computing MAX */ i__1 = maxwrk, i__2 = ((*m) << (1)) + *m * *nrhs; maxwrk = max(i__1,i__2); } /* Computing MAX */ i__1 = ((*m) << (1)) + *n, i__2 = ((*m) << (1)) + *m * *nrhs; minwrk = max(i__1,i__2); } minwrk = min(minwrk,maxwrk); r__1 = (real) maxwrk; q__1.r = r__1, q__1.i = 0.f; work[1].r = q__1.r, work[1].i = q__1.i; if (*lwork < minwrk && ! lquery) { *info = -12; } } if (*info != 0) { i__1 = -(*info); xerbla_("CGELSD", &i__1); return 0; } else if (lquery) { goto L10; } /* Quick return if possible. */ if ((*m == 0) || (*n == 0)) { *rank = 0; return 0; } /* Get machine parameters. */ eps = slamch_("P"); sfmin = slamch_("S"); smlnum = sfmin / eps; bignum = 1.f / smlnum; slabad_(&smlnum, &bignum); /* Scale A if max entry outside range [SMLNUM,BIGNUM]. */ anrm = clange_("M", m, n, &a[a_offset], lda, &rwork[1]); iascl = 0; if (anrm > 0.f && anrm < smlnum) { /* Scale matrix norm up to SMLNUM */ clascl_("G", &c__0, &c__0, &anrm, &smlnum, m, n, &a[a_offset], lda, info); iascl = 1; } else if (anrm > bignum) { /* Scale matrix norm down to BIGNUM. */ clascl_("G", &c__0, &c__0, &anrm, &bignum, m, n, &a[a_offset], lda, info); iascl = 2; } else if (anrm == 0.f) { /* Matrix all zero. Return zero solution. */ i__1 = max(*m,*n); claset_("F", &i__1, nrhs, &c_b55, &c_b55, &b[b_offset], ldb); slaset_("F", &minmn, &c__1, &c_b320, &c_b320, &s[1], &c__1) ; *rank = 0; goto L10; } /* Scale B if max entry outside range [SMLNUM,BIGNUM]. */ bnrm = clange_("M", m, nrhs, &b[b_offset], ldb, &rwork[1]); ibscl = 0; if (bnrm > 0.f && bnrm < smlnum) { /* Scale matrix norm up to SMLNUM. */ clascl_("G", &c__0, &c__0, &bnrm, &smlnum, m, nrhs, &b[b_offset], ldb, info); ibscl = 1; } else if (bnrm > bignum) { /* Scale matrix norm down to BIGNUM. */ clascl_("G", &c__0, &c__0, &bnrm, &bignum, m, nrhs, &b[b_offset], ldb, info); ibscl = 2; } /* If M < N make sure B(M+1:N,:) = 0 */ if (*m < *n) { i__1 = *n - *m; claset_("F", &i__1, nrhs, &c_b55, &c_b55, &b[*m + 1 + b_dim1], ldb); } /* Overdetermined case. */ if (*m >= *n) { /* Path 1 - overdetermined or exactly determined. */ mm = *m; if (*m >= mnthr) { /* Path 1a - overdetermined, with many more rows than columns */ mm = *n; itau = 1; nwork = itau + *n; /* Compute A=Q*R. (RWorkspace: need N) (CWorkspace: need N, prefer N*NB) */ i__1 = *lwork - nwork + 1; cgeqrf_(m, n, &a[a_offset], lda, &work[itau], &work[nwork], &i__1, info); /* Multiply B by transpose(Q). (RWorkspace: need N) (CWorkspace: need NRHS, prefer NRHS*NB) */ i__1 = *lwork - nwork + 1; cunmqr_("L", "C", m, nrhs, n, &a[a_offset], lda, &work[itau], &b[ b_offset], ldb, &work[nwork], &i__1, info); /* Zero out below R. */ if (*n > 1) { i__1 = *n - 1; i__2 = *n - 1; claset_("L", &i__1, &i__2, &c_b55, &c_b55, &a[a_dim1 + 2], lda); } } itauq = 1; itaup = itauq + *n; nwork = itaup + *n; ie = 1; nrwork = ie + *n; /* Bidiagonalize R in A. (RWorkspace: need N) (CWorkspace: need 2*N+MM, prefer 2*N+(MM+N)*NB) */ i__1 = *lwork - nwork + 1; cgebrd_(&mm, n, &a[a_offset], lda, &s[1], &rwork[ie], &work[itauq], & work[itaup], &work[nwork], &i__1, info); /* Multiply B by transpose of left bidiagonalizing vectors of R. (CWorkspace: need 2*N+NRHS, prefer 2*N+NRHS*NB) */ i__1 = *lwork - nwork + 1; cunmbr_("Q", "L", "C", &mm, nrhs, n, &a[a_offset], lda, &work[itauq], &b[b_offset], ldb, &work[nwork], &i__1, info); /* Solve the bidiagonal least squares problem. */ clalsd_("U", &smlsiz, n, nrhs, &s[1], &rwork[ie], &b[b_offset], ldb, rcond, rank, &work[nwork], &rwork[nrwork], &iwork[1], info); if (*info != 0) { goto L10; } /* Multiply B by right bidiagonalizing vectors of R. */ i__1 = *lwork - nwork + 1; cunmbr_("P", "L", "N", n, nrhs, n, &a[a_offset], lda, &work[itaup], & b[b_offset], ldb, &work[nwork], &i__1, info); } else /* if(complicated condition) */ { /* Computing MAX */ i__1 = *m, i__2 = ((*m) << (1)) - 4, i__1 = max(i__1,i__2), i__1 = max(i__1,*nrhs), i__2 = *n - *m * 3; if (*n >= mnthr && *lwork >= ((*m) << (2)) + *m * *m + max(i__1,i__2)) { /* Path 2a - underdetermined, with many more columns than rows and sufficient workspace for an efficient algorithm. */ ldwork = *m; /* Computing MAX Computing MAX */ i__3 = *m, i__4 = ((*m) << (1)) - 4, i__3 = max(i__3,i__4), i__3 = max(i__3,*nrhs), i__4 = *n - *m * 3; i__1 = ((*m) << (2)) + *m * *lda + max(i__3,i__4), i__2 = *m * * lda + *m + *m * *nrhs; if (*lwork >= max(i__1,i__2)) { ldwork = *lda; } itau = 1; nwork = *m + 1; /* Compute A=L*Q. (CWorkspace: need 2*M, prefer M+M*NB) */ i__1 = *lwork - nwork + 1; cgelqf_(m, n, &a[a_offset], lda, &work[itau], &work[nwork], &i__1, info); il = nwork; /* Copy L to WORK(IL), zeroing out above its diagonal. */ clacpy_("L", m, m, &a[a_offset], lda, &work[il], &ldwork); i__1 = *m - 1; i__2 = *m - 1; claset_("U", &i__1, &i__2, &c_b55, &c_b55, &work[il + ldwork], & ldwork); itauq = il + ldwork * *m; itaup = itauq + *m; nwork = itaup + *m; ie = 1; nrwork = ie + *m; /* Bidiagonalize L in WORK(IL). (RWorkspace: need M) (CWorkspace: need M*M+4*M, prefer M*M+4*M+2*M*NB) */ i__1 = *lwork - nwork + 1; cgebrd_(m, m, &work[il], &ldwork, &s[1], &rwork[ie], &work[itauq], &work[itaup], &work[nwork], &i__1, info); /* Multiply B by transpose of left bidiagonalizing vectors of L. (CWorkspace: need M*M+4*M+NRHS, prefer M*M+4*M+NRHS*NB) */ i__1 = *lwork - nwork + 1; cunmbr_("Q", "L", "C", m, nrhs, m, &work[il], &ldwork, &work[ itauq], &b[b_offset], ldb, &work[nwork], &i__1, info); /* Solve the bidiagonal least squares problem. */ clalsd_("U", &smlsiz, m, nrhs, &s[1], &rwork[ie], &b[b_offset], ldb, rcond, rank, &work[nwork], &rwork[nrwork], &iwork[1], info); if (*info != 0) { goto L10; } /* Multiply B by right bidiagonalizing vectors of L. */ i__1 = *lwork - nwork + 1; cunmbr_("P", "L", "N", m, nrhs, m, &work[il], &ldwork, &work[ itaup], &b[b_offset], ldb, &work[nwork], &i__1, info); /* Zero out below first M rows of B. */ i__1 = *n - *m; claset_("F", &i__1, nrhs, &c_b55, &c_b55, &b[*m + 1 + b_dim1], ldb); nwork = itau + *m; /* Multiply transpose(Q) by B. (CWorkspace: need NRHS, prefer NRHS*NB) */ i__1 = *lwork - nwork + 1; cunmlq_("L", "C", n, nrhs, m, &a[a_offset], lda, &work[itau], &b[ b_offset], ldb, &work[nwork], &i__1, info); } else { /* Path 2 - remaining underdetermined cases. */ itauq = 1; itaup = itauq + *m; nwork = itaup + *m; ie = 1; nrwork = ie + *m; /* Bidiagonalize A. (RWorkspace: need M) (CWorkspace: need 2*M+N, prefer 2*M+(M+N)*NB) */ i__1 = *lwork - nwork + 1; cgebrd_(m, n, &a[a_offset], lda, &s[1], &rwork[ie], &work[itauq], &work[itaup], &work[nwork], &i__1, info); /* Multiply B by transpose of left bidiagonalizing vectors. (CWorkspace: need 2*M+NRHS, prefer 2*M+NRHS*NB) */ i__1 = *lwork - nwork + 1; cunmbr_("Q", "L", "C", m, nrhs, n, &a[a_offset], lda, &work[itauq] , &b[b_offset], ldb, &work[nwork], &i__1, info); /* Solve the bidiagonal least squares problem. */ clalsd_("L", &smlsiz, m, nrhs, &s[1], &rwork[ie], &b[b_offset], ldb, rcond, rank, &work[nwork], &rwork[nrwork], &iwork[1], info); if (*info != 0) { goto L10; } /* Multiply B by right bidiagonalizing vectors of A. */ i__1 = *lwork - nwork + 1; cunmbr_("P", "L", "N", n, nrhs, m, &a[a_offset], lda, &work[itaup] , &b[b_offset], ldb, &work[nwork], &i__1, info); } } /* Undo scaling. */ if (iascl == 1) { clascl_("G", &c__0, &c__0, &anrm, &smlnum, n, nrhs, &b[b_offset], ldb, info); slascl_("G", &c__0, &c__0, &smlnum, &anrm, &minmn, &c__1, &s[1], & minmn, info); } else if (iascl == 2) { clascl_("G", &c__0, &c__0, &anrm, &bignum, n, nrhs, &b[b_offset], ldb, info); slascl_("G", &c__0, &c__0, &bignum, &anrm, &minmn, &c__1, &s[1], & minmn, info); } if (ibscl == 1) { clascl_("G", &c__0, &c__0, &smlnum, &bnrm, n, nrhs, &b[b_offset], ldb, info); } else if (ibscl == 2) { clascl_("G", &c__0, &c__0, &bignum, &bnrm, n, nrhs, &b[b_offset], ldb, info); } L10: r__1 = (real) maxwrk; q__1.r = r__1, q__1.i = 0.f; work[1].r = q__1.r, work[1].i = q__1.i; return 0; /* End of CGELSD */ } /* cgelsd_ */ /* Subroutine */ int cgeqr2_(integer *m, integer *n, complex *a, integer *lda, complex *tau, complex *work, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3; complex q__1; /* Builtin functions */ void r_cnjg(complex *, complex *); /* Local variables */ static integer i__, k; static complex alpha; extern /* Subroutine */ int clarf_(char *, integer *, integer *, complex * , integer *, complex *, complex *, integer *, complex *), clarfg_(integer *, complex *, complex *, integer *, complex *), xerbla_(char *, integer *); /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University September 30, 1994 Purpose ======= CGEQR2 computes a QR factorization of a complex m by n matrix A: A = Q * R. Arguments ========= M (input) INTEGER The number of rows of the matrix A. M >= 0. N (input) INTEGER The number of columns of the matrix A. N >= 0. A (input/output) COMPLEX array, dimension (LDA,N) On entry, the m by n matrix A. On exit, the elements on and above the diagonal of the array contain the min(m,n) by n upper trapezoidal matrix R (R is upper triangular if m >= n); the elements below the diagonal, with the array TAU, represent the unitary matrix Q as a product of elementary reflectors (see Further Details). LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,M). TAU (output) COMPLEX array, dimension (min(M,N)) The scalar factors of the elementary reflectors (see Further Details). WORK (workspace) COMPLEX array, dimension (N) INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value Further Details =============== The matrix Q is represented as a product of elementary reflectors Q = H(1) H(2) . . . H(k), where k = min(m,n). Each H(i) has the form H(i) = I - tau * v * v' where tau is a complex scalar, and v is a complex vector with v(1:i-1) = 0 and v(i) = 1; v(i+1:m) is stored on exit in A(i+1:m,i), and tau in TAU(i). ===================================================================== Test the input arguments */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --tau; --work; /* Function Body */ *info = 0; if (*m < 0) { *info = -1; } else if (*n < 0) { *info = -2; } else if (*lda < max(1,*m)) { *info = -4; } if (*info != 0) { i__1 = -(*info); xerbla_("CGEQR2", &i__1); return 0; } k = min(*m,*n); i__1 = k; for (i__ = 1; i__ <= i__1; ++i__) { /* Generate elementary reflector H(i) to annihilate A(i+1:m,i) */ i__2 = *m - i__ + 1; /* Computing MIN */ i__3 = i__ + 1; clarfg_(&i__2, &a[i__ + i__ * a_dim1], &a[min(i__3,*m) + i__ * a_dim1] , &c__1, &tau[i__]); if (i__ < *n) { /* Apply H(i)' to A(i:m,i+1:n) from the left */ i__2 = i__ + i__ * a_dim1; alpha.r = a[i__2].r, alpha.i = a[i__2].i; i__2 = i__ + i__ * a_dim1; a[i__2].r = 1.f, a[i__2].i = 0.f; i__2 = *m - i__ + 1; i__3 = *n - i__; r_cnjg(&q__1, &tau[i__]); clarf_("Left", &i__2, &i__3, &a[i__ + i__ * a_dim1], &c__1, &q__1, &a[i__ + (i__ + 1) * a_dim1], lda, &work[1]); i__2 = i__ + i__ * a_dim1; a[i__2].r = alpha.r, a[i__2].i = alpha.i; } /* L10: */ } return 0; /* End of CGEQR2 */ } /* cgeqr2_ */ /* Subroutine */ int cgeqrf_(integer *m, integer *n, complex *a, integer *lda, complex *tau, complex *work, integer *lwork, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3, i__4; /* Local variables */ static integer i__, k, ib, nb, nx, iws, nbmin, iinfo; extern /* Subroutine */ int cgeqr2_(integer *, integer *, complex *, integer *, complex *, complex *, integer *), clarfb_(char *, char *, char *, char *, integer *, integer *, integer *, complex *, integer *, complex *, integer *, complex *, integer *, complex *, integer *), clarft_(char *, char * , integer *, integer *, complex *, integer *, complex *, complex * , integer *), xerbla_(char *, integer *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); static integer ldwork, lwkopt; static logical lquery; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= CGEQRF computes a QR factorization of a complex M-by-N matrix A: A = Q * R. Arguments ========= M (input) INTEGER The number of rows of the matrix A. M >= 0. N (input) INTEGER The number of columns of the matrix A. N >= 0. A (input/output) COMPLEX array, dimension (LDA,N) On entry, the M-by-N matrix A. On exit, the elements on and above the diagonal of the array contain the min(M,N)-by-N upper trapezoidal matrix R (R is upper triangular if m >= n); the elements below the diagonal, with the array TAU, represent the unitary matrix Q as a product of min(m,n) elementary reflectors (see Further Details). LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,M). TAU (output) COMPLEX array, dimension (min(M,N)) The scalar factors of the elementary reflectors (see Further Details). WORK (workspace/output) COMPLEX array, dimension (LWORK) On exit, if INFO = 0, WORK(1) returns the optimal LWORK. LWORK (input) INTEGER The dimension of the array WORK. LWORK >= max(1,N). For optimum performance LWORK >= N*NB, where NB is the optimal blocksize. If LWORK = -1, then a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued by XERBLA. INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value Further Details =============== The matrix Q is represented as a product of elementary reflectors Q = H(1) H(2) . . . H(k), where k = min(m,n). Each H(i) has the form H(i) = I - tau * v * v' where tau is a complex scalar, and v is a complex vector with v(1:i-1) = 0 and v(i) = 1; v(i+1:m) is stored on exit in A(i+1:m,i), and tau in TAU(i). ===================================================================== Test the input arguments */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --tau; --work; /* Function Body */ *info = 0; nb = ilaenv_(&c__1, "CGEQRF", " ", m, n, &c_n1, &c_n1, (ftnlen)6, (ftnlen) 1); lwkopt = *n * nb; work[1].r = (real) lwkopt, work[1].i = 0.f; lquery = *lwork == -1; if (*m < 0) { *info = -1; } else if (*n < 0) { *info = -2; } else if (*lda < max(1,*m)) { *info = -4; } else if (*lwork < max(1,*n) && ! lquery) { *info = -7; } if (*info != 0) { i__1 = -(*info); xerbla_("CGEQRF", &i__1); return 0; } else if (lquery) { return 0; } /* Quick return if possible */ k = min(*m,*n); if (k == 0) { work[1].r = 1.f, work[1].i = 0.f; return 0; } nbmin = 2; nx = 0; iws = *n; if (nb > 1 && nb < k) { /* Determine when to cross over from blocked to unblocked code. Computing MAX */ i__1 = 0, i__2 = ilaenv_(&c__3, "CGEQRF", " ", m, n, &c_n1, &c_n1, ( ftnlen)6, (ftnlen)1); nx = max(i__1,i__2); if (nx < k) { /* Determine if workspace is large enough for blocked code. */ ldwork = *n; iws = ldwork * nb; if (*lwork < iws) { /* Not enough workspace to use optimal NB: reduce NB and determine the minimum value of NB. */ nb = *lwork / ldwork; /* Computing MAX */ i__1 = 2, i__2 = ilaenv_(&c__2, "CGEQRF", " ", m, n, &c_n1, & c_n1, (ftnlen)6, (ftnlen)1); nbmin = max(i__1,i__2); } } } if (nb >= nbmin && nb < k && nx < k) { /* Use blocked code initially */ i__1 = k - nx; i__2 = nb; for (i__ = 1; i__2 < 0 ? i__ >= i__1 : i__ <= i__1; i__ += i__2) { /* Computing MIN */ i__3 = k - i__ + 1; ib = min(i__3,nb); /* Compute the QR factorization of the current block A(i:m,i:i+ib-1) */ i__3 = *m - i__ + 1; cgeqr2_(&i__3, &ib, &a[i__ + i__ * a_dim1], lda, &tau[i__], &work[ 1], &iinfo); if (i__ + ib <= *n) { /* Form the triangular factor of the block reflector H = H(i) H(i+1) . . . H(i+ib-1) */ i__3 = *m - i__ + 1; clarft_("Forward", "Columnwise", &i__3, &ib, &a[i__ + i__ * a_dim1], lda, &tau[i__], &work[1], &ldwork); /* Apply H' to A(i:m,i+ib:n) from the left */ i__3 = *m - i__ + 1; i__4 = *n - i__ - ib + 1; clarfb_("Left", "Conjugate transpose", "Forward", "Columnwise" , &i__3, &i__4, &ib, &a[i__ + i__ * a_dim1], lda, & work[1], &ldwork, &a[i__ + (i__ + ib) * a_dim1], lda, &work[ib + 1], &ldwork); } /* L10: */ } } else { i__ = 1; } /* Use unblocked code to factor the last or only block. */ if (i__ <= k) { i__2 = *m - i__ + 1; i__1 = *n - i__ + 1; cgeqr2_(&i__2, &i__1, &a[i__ + i__ * a_dim1], lda, &tau[i__], &work[1] , &iinfo); } work[1].r = (real) iws, work[1].i = 0.f; return 0; /* End of CGEQRF */ } /* cgeqrf_ */ /* Subroutine */ int cgesdd_(char *jobz, integer *m, integer *n, complex *a, integer *lda, real *s, complex *u, integer *ldu, complex *vt, integer *ldvt, complex *work, integer *lwork, real *rwork, integer *iwork, integer *info) { /* System generated locals */ integer a_dim1, a_offset, u_dim1, u_offset, vt_dim1, vt_offset, i__1, i__2, i__3; /* Builtin functions */ double sqrt(doublereal); /* Local variables */ static integer i__, ie, il, ir, iu, blk; static real dum[1], eps; static integer iru, ivt, iscl; static real anrm; static integer idum[1], ierr, itau, irvt; extern /* Subroutine */ int cgemm_(char *, char *, integer *, integer *, integer *, complex *, complex *, integer *, complex *, integer *, complex *, complex *, integer *); extern logical lsame_(char *, char *); static integer chunk, minmn, wrkbl, itaup, itauq; static logical wntqa; static integer nwork; extern /* Subroutine */ int clacp2_(char *, integer *, integer *, real *, integer *, complex *, integer *); static logical wntqn, wntqo, wntqs; static integer mnthr1, mnthr2; extern /* Subroutine */ int cgebrd_(integer *, integer *, complex *, integer *, real *, real *, complex *, complex *, complex *, integer *, integer *); extern doublereal clange_(char *, integer *, integer *, complex *, integer *, real *); extern /* Subroutine */ int cgelqf_(integer *, integer *, complex *, integer *, complex *, complex *, integer *, integer *), clacrm_( integer *, integer *, complex *, integer *, real *, integer *, complex *, integer *, real *), clarcm_(integer *, integer *, real *, integer *, complex *, integer *, complex *, integer *, real *), clascl_(char *, integer *, integer *, real *, real *, integer *, integer *, complex *, integer *, integer *), sbdsdc_(char *, char *, integer *, real *, real *, real *, integer *, real *, integer *, real *, integer *, real *, integer *, integer *), cgeqrf_(integer *, integer *, complex *, integer *, complex *, complex *, integer *, integer *); extern doublereal slamch_(char *); extern /* Subroutine */ int clacpy_(char *, integer *, integer *, complex *, integer *, complex *, integer *), claset_(char *, integer *, integer *, complex *, complex *, complex *, integer *), xerbla_(char *, integer *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); extern /* Subroutine */ int cungbr_(char *, integer *, integer *, integer *, complex *, integer *, complex *, complex *, integer *, integer *); static real bignum; extern /* Subroutine */ int slascl_(char *, integer *, integer *, real *, real *, integer *, integer *, real *, integer *, integer *), cunmbr_(char *, char *, char *, integer *, integer *, integer *, complex *, integer *, complex *, complex *, integer *, complex *, integer *, integer *), cunglq_( integer *, integer *, integer *, complex *, integer *, complex *, complex *, integer *, integer *); static integer ldwrkl; extern /* Subroutine */ int cungqr_(integer *, integer *, integer *, complex *, integer *, complex *, complex *, integer *, integer *); static integer ldwrkr, minwrk, ldwrku, maxwrk, ldwkvt; static real smlnum; static logical wntqas, lquery; static integer nrwork; /* -- LAPACK driver routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University October 31, 1999 Purpose ======= CGESDD computes the singular value decomposition (SVD) of a complex M-by-N matrix A, optionally computing the left and/or right singular vectors, by using divide-and-conquer method. The SVD is written A = U * SIGMA * conjugate-transpose(V) where SIGMA is an M-by-N matrix which is zero except for its min(m,n) diagonal elements, U is an M-by-M unitary matrix, and V is an N-by-N unitary matrix. The diagonal elements of SIGMA are the singular values of A; they are real and non-negative, and are returned in descending order. The first min(m,n) columns of U and V are the left and right singular vectors of A. Note that the routine returns VT = V**H, not V. The divide and conquer algorithm makes very mild assumptions about floating point arithmetic. It will work on machines with a guard digit in add/subtract, or on those binary machines without guard digits which subtract like the Cray X-MP, Cray Y-MP, Cray C-90, or Cray-2. It could conceivably fail on hexadecimal or decimal machines without guard digits, but we know of none. Arguments ========= JOBZ (input) CHARACTER*1 Specifies options for computing all or part of the matrix U: = 'A': all M columns of U and all N rows of V**H are returned in the arrays U and VT; = 'S': the first min(M,N) columns of U and the first min(M,N) rows of V**H are returned in the arrays U and VT; = 'O': If M >= N, the first N columns of U are overwritten on the array A and all rows of V**H are returned in the array VT; otherwise, all columns of U are returned in the array U and the first M rows of V**H are overwritten in the array VT; = 'N': no columns of U or rows of V**H are computed. M (input) INTEGER The number of rows of the input matrix A. M >= 0. N (input) INTEGER The number of columns of the input matrix A. N >= 0. A (input/output) COMPLEX array, dimension (LDA,N) On entry, the M-by-N matrix A. On exit, if JOBZ = 'O', A is overwritten with the first N columns of U (the left singular vectors, stored columnwise) if M >= N; A is overwritten with the first M rows of V**H (the right singular vectors, stored rowwise) otherwise. if JOBZ .ne. 'O', the contents of A are destroyed. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,M). S (output) REAL array, dimension (min(M,N)) The singular values of A, sorted so that S(i) >= S(i+1). U (output) COMPLEX array, dimension (LDU,UCOL) UCOL = M if JOBZ = 'A' or JOBZ = 'O' and M < N; UCOL = min(M,N) if JOBZ = 'S'. If JOBZ = 'A' or JOBZ = 'O' and M < N, U contains the M-by-M unitary matrix U; if JOBZ = 'S', U contains the first min(M,N) columns of U (the left singular vectors, stored columnwise); if JOBZ = 'O' and M >= N, or JOBZ = 'N', U is not referenced. LDU (input) INTEGER The leading dimension of the array U. LDU >= 1; if JOBZ = 'S' or 'A' or JOBZ = 'O' and M < N, LDU >= M. VT (output) COMPLEX array, dimension (LDVT,N) If JOBZ = 'A' or JOBZ = 'O' and M >= N, VT contains the N-by-N unitary matrix V**H; if JOBZ = 'S', VT contains the first min(M,N) rows of V**H (the right singular vectors, stored rowwise); if JOBZ = 'O' and M < N, or JOBZ = 'N', VT is not referenced. LDVT (input) INTEGER The leading dimension of the array VT. LDVT >= 1; if JOBZ = 'A' or JOBZ = 'O' and M >= N, LDVT >= N; if JOBZ = 'S', LDVT >= min(M,N). WORK (workspace/output) COMPLEX array, dimension (LWORK) On exit, if INFO = 0, WORK(1) returns the optimal LWORK. LWORK (input) INTEGER The dimension of the array WORK. LWORK >= 1. if JOBZ = 'N', LWORK >= 2*min(M,N)+max(M,N). if JOBZ = 'O', LWORK >= 2*min(M,N)*min(M,N)+2*min(M,N)+max(M,N). if JOBZ = 'S' or 'A', LWORK >= min(M,N)*min(M,N)+2*min(M,N)+max(M,N). For good performance, LWORK should generally be larger. If LWORK < 0 but other input arguments are legal, WORK(1) returns the optimal LWORK. RWORK (workspace) REAL array, dimension (LRWORK) If JOBZ = 'N', LRWORK >= 7*min(M,N). Otherwise, LRWORK >= 5*min(M,N)*min(M,N) + 5*min(M,N) IWORK (workspace) INTEGER array, dimension (8*min(M,N)) INFO (output) INTEGER = 0: successful exit. < 0: if INFO = -i, the i-th argument had an illegal value. > 0: The updating process of SBDSDC did not converge. Further Details =============== Based on contributions by Ming Gu and Huan Ren, Computer Science Division, University of California at Berkeley, USA ===================================================================== Test the input arguments */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --s; u_dim1 = *ldu; u_offset = 1 + u_dim1; u -= u_offset; vt_dim1 = *ldvt; vt_offset = 1 + vt_dim1; vt -= vt_offset; --work; --rwork; --iwork; /* Function Body */ *info = 0; minmn = min(*m,*n); mnthr1 = (integer) (minmn * 17.f / 9.f); mnthr2 = (integer) (minmn * 5.f / 3.f); wntqa = lsame_(jobz, "A"); wntqs = lsame_(jobz, "S"); wntqas = (wntqa) || (wntqs); wntqo = lsame_(jobz, "O"); wntqn = lsame_(jobz, "N"); minwrk = 1; maxwrk = 1; lquery = *lwork == -1; if (! ((((wntqa) || (wntqs)) || (wntqo)) || (wntqn))) { *info = -1; } else if (*m < 0) { *info = -2; } else if (*n < 0) { *info = -3; } else if (*lda < max(1,*m)) { *info = -5; } else if (((*ldu < 1) || (wntqas && *ldu < *m)) || (wntqo && *m < *n && * ldu < *m)) { *info = -8; } else if ((((*ldvt < 1) || (wntqa && *ldvt < *n)) || (wntqs && *ldvt < minmn)) || (wntqo && *m >= *n && *ldvt < *n)) { *info = -10; } /* Compute workspace (Note: Comments in the code beginning "Workspace:" describe the minimal amount of workspace needed at that point in the code, as well as the preferred amount for good performance. CWorkspace refers to complex workspace, and RWorkspace to real workspace. NB refers to the optimal block size for the immediately following subroutine, as returned by ILAENV.) */ if (*info == 0 && *m > 0 && *n > 0) { if (*m >= *n) { /* There is no complex work space needed for bidiagonal SVD The real work space needed for bidiagonal SVD is BDSPAC, BDSPAC = 3*N*N + 4*N */ if (*m >= mnthr1) { if (wntqn) { /* Path 1 (M much larger than N, JOBZ='N') */ wrkbl = *n + *n * ilaenv_(&c__1, "CGEQRF", " ", m, n, & c_n1, &c_n1, (ftnlen)6, (ftnlen)1); /* Computing MAX */ i__1 = wrkbl, i__2 = ((*n) << (1)) + ((*n) << (1)) * ilaenv_(&c__1, "CGEBRD", " ", n, n, &c_n1, &c_n1, (ftnlen)6, (ftnlen)1); wrkbl = max(i__1,i__2); maxwrk = wrkbl; minwrk = *n * 3; } else if (wntqo) { /* Path 2 (M much larger than N, JOBZ='O') */ wrkbl = *n + *n * ilaenv_(&c__1, "CGEQRF", " ", m, n, & c_n1, &c_n1, (ftnlen)6, (ftnlen)1); /* Computing MAX */ i__1 = wrkbl, i__2 = *n + *n * ilaenv_(&c__1, "CUNGQR", " ", m, n, n, &c_n1, (ftnlen)6, (ftnlen)1); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = ((*n) << (1)) + ((*n) << (1)) * ilaenv_(&c__1, "CGEBRD", " ", n, n, &c_n1, &c_n1, (ftnlen)6, (ftnlen)1); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = ((*n) << (1)) + *n * ilaenv_(&c__1, "CUNMBR", "QLN", n, n, n, &c_n1, (ftnlen)6, ( ftnlen)3); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = ((*n) << (1)) + *n * ilaenv_(&c__1, "CUNMBR", "PRC", n, n, n, &c_n1, (ftnlen)6, ( ftnlen)3); wrkbl = max(i__1,i__2); maxwrk = *m * *n + *n * *n + wrkbl; minwrk = ((*n) << (1)) * *n + *n * 3; } else if (wntqs) { /* Path 3 (M much larger than N, JOBZ='S') */ wrkbl = *n + *n * ilaenv_(&c__1, "CGEQRF", " ", m, n, & c_n1, &c_n1, (ftnlen)6, (ftnlen)1); /* Computing MAX */ i__1 = wrkbl, i__2 = *n + *n * ilaenv_(&c__1, "CUNGQR", " ", m, n, n, &c_n1, (ftnlen)6, (ftnlen)1); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = ((*n) << (1)) + ((*n) << (1)) * ilaenv_(&c__1, "CGEBRD", " ", n, n, &c_n1, &c_n1, (ftnlen)6, (ftnlen)1); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = ((*n) << (1)) + *n * ilaenv_(&c__1, "CUNMBR", "QLN", n, n, n, &c_n1, (ftnlen)6, ( ftnlen)3); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = ((*n) << (1)) + *n * ilaenv_(&c__1, "CUNMBR", "PRC", n, n, n, &c_n1, (ftnlen)6, ( ftnlen)3); wrkbl = max(i__1,i__2); maxwrk = *n * *n + wrkbl; minwrk = *n * *n + *n * 3; } else if (wntqa) { /* Path 4 (M much larger than N, JOBZ='A') */ wrkbl = *n + *n * ilaenv_(&c__1, "CGEQRF", " ", m, n, & c_n1, &c_n1, (ftnlen)6, (ftnlen)1); /* Computing MAX */ i__1 = wrkbl, i__2 = *n + *m * ilaenv_(&c__1, "CUNGQR", " ", m, m, n, &c_n1, (ftnlen)6, (ftnlen)1); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = ((*n) << (1)) + ((*n) << (1)) * ilaenv_(&c__1, "CGEBRD", " ", n, n, &c_n1, &c_n1, (ftnlen)6, (ftnlen)1); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = ((*n) << (1)) + *n * ilaenv_(&c__1, "CUNMBR", "QLN", n, n, n, &c_n1, (ftnlen)6, ( ftnlen)3); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = ((*n) << (1)) + *n * ilaenv_(&c__1, "CUNMBR", "PRC", n, n, n, &c_n1, (ftnlen)6, ( ftnlen)3); wrkbl = max(i__1,i__2); maxwrk = *n * *n + wrkbl; minwrk = *n * *n + ((*n) << (1)) + *m; } } else if (*m >= mnthr2) { /* Path 5 (M much larger than N, but not as much as MNTHR1) */ maxwrk = ((*n) << (1)) + (*m + *n) * ilaenv_(&c__1, "CGEBRD", " ", m, n, &c_n1, &c_n1, (ftnlen)6, (ftnlen)1); minwrk = ((*n) << (1)) + *m; if (wntqo) { /* Computing MAX */ i__1 = maxwrk, i__2 = ((*n) << (1)) + *n * ilaenv_(&c__1, "CUNGBR", "P", n, n, n, &c_n1, (ftnlen)6, (ftnlen) 1); maxwrk = max(i__1,i__2); /* Computing MAX */ i__1 = maxwrk, i__2 = ((*n) << (1)) + *n * ilaenv_(&c__1, "CUNGBR", "Q", m, n, n, &c_n1, (ftnlen)6, (ftnlen) 1); maxwrk = max(i__1,i__2); maxwrk += *m * *n; minwrk += *n * *n; } else if (wntqs) { /* Computing MAX */ i__1 = maxwrk, i__2 = ((*n) << (1)) + *n * ilaenv_(&c__1, "CUNGBR", "P", n, n, n, &c_n1, (ftnlen)6, (ftnlen) 1); maxwrk = max(i__1,i__2); /* Computing MAX */ i__1 = maxwrk, i__2 = ((*n) << (1)) + *n * ilaenv_(&c__1, "CUNGBR", "Q", m, n, n, &c_n1, (ftnlen)6, (ftnlen) 1); maxwrk = max(i__1,i__2); } else if (wntqa) { /* Computing MAX */ i__1 = maxwrk, i__2 = ((*n) << (1)) + *n * ilaenv_(&c__1, "CUNGBR", "P", n, n, n, &c_n1, (ftnlen)6, (ftnlen) 1); maxwrk = max(i__1,i__2); /* Computing MAX */ i__1 = maxwrk, i__2 = ((*n) << (1)) + *m * ilaenv_(&c__1, "CUNGBR", "Q", m, m, n, &c_n1, (ftnlen)6, (ftnlen) 1); maxwrk = max(i__1,i__2); } } else { /* Path 6 (M at least N, but not much larger) */ maxwrk = ((*n) << (1)) + (*m + *n) * ilaenv_(&c__1, "CGEBRD", " ", m, n, &c_n1, &c_n1, (ftnlen)6, (ftnlen)1); minwrk = ((*n) << (1)) + *m; if (wntqo) { /* Computing MAX */ i__1 = maxwrk, i__2 = ((*n) << (1)) + *n * ilaenv_(&c__1, "CUNMBR", "PRC", n, n, n, &c_n1, (ftnlen)6, ( ftnlen)3); maxwrk = max(i__1,i__2); /* Computing MAX */ i__1 = maxwrk, i__2 = ((*n) << (1)) + *n * ilaenv_(&c__1, "CUNMBR", "QLN", m, n, n, &c_n1, (ftnlen)6, ( ftnlen)3); maxwrk = max(i__1,i__2); maxwrk += *m * *n; minwrk += *n * *n; } else if (wntqs) { /* Computing MAX */ i__1 = maxwrk, i__2 = ((*n) << (1)) + *n * ilaenv_(&c__1, "CUNMBR", "PRC", n, n, n, &c_n1, (ftnlen)6, ( ftnlen)3); maxwrk = max(i__1,i__2); /* Computing MAX */ i__1 = maxwrk, i__2 = ((*n) << (1)) + *n * ilaenv_(&c__1, "CUNMBR", "QLN", m, n, n, &c_n1, (ftnlen)6, ( ftnlen)3); maxwrk = max(i__1,i__2); } else if (wntqa) { /* Computing MAX */ i__1 = maxwrk, i__2 = ((*n) << (1)) + *n * ilaenv_(&c__1, "CUNGBR", "PRC", n, n, n, &c_n1, (ftnlen)6, ( ftnlen)3); maxwrk = max(i__1,i__2); /* Computing MAX */ i__1 = maxwrk, i__2 = ((*n) << (1)) + *m * ilaenv_(&c__1, "CUNGBR", "QLN", m, m, n, &c_n1, (ftnlen)6, ( ftnlen)3); maxwrk = max(i__1,i__2); } } } else { /* There is no complex work space needed for bidiagonal SVD The real work space needed for bidiagonal SVD is BDSPAC, BDSPAC = 3*M*M + 4*M */ if (*n >= mnthr1) { if (wntqn) { /* Path 1t (N much larger than M, JOBZ='N') */ maxwrk = *m + *m * ilaenv_(&c__1, "CGELQF", " ", m, n, & c_n1, &c_n1, (ftnlen)6, (ftnlen)1); /* Computing MAX */ i__1 = maxwrk, i__2 = ((*m) << (1)) + ((*m) << (1)) * ilaenv_(&c__1, "CGEBRD", " ", m, m, &c_n1, &c_n1, (ftnlen)6, (ftnlen)1); maxwrk = max(i__1,i__2); minwrk = *m * 3; } else if (wntqo) { /* Path 2t (N much larger than M, JOBZ='O') */ wrkbl = *m + *m * ilaenv_(&c__1, "CGELQF", " ", m, n, & c_n1, &c_n1, (ftnlen)6, (ftnlen)1); /* Computing MAX */ i__1 = wrkbl, i__2 = *m + *m * ilaenv_(&c__1, "CUNGLQ", " ", m, n, m, &c_n1, (ftnlen)6, (ftnlen)1); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = ((*m) << (1)) + ((*m) << (1)) * ilaenv_(&c__1, "CGEBRD", " ", m, m, &c_n1, &c_n1, (ftnlen)6, (ftnlen)1); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = ((*m) << (1)) + *m * ilaenv_(&c__1, "CUNMBR", "PRC", m, m, m, &c_n1, (ftnlen)6, ( ftnlen)3); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = ((*m) << (1)) + *m * ilaenv_(&c__1, "CUNMBR", "QLN", m, m, m, &c_n1, (ftnlen)6, ( ftnlen)3); wrkbl = max(i__1,i__2); maxwrk = *m * *n + *m * *m + wrkbl; minwrk = ((*m) << (1)) * *m + *m * 3; } else if (wntqs) { /* Path 3t (N much larger than M, JOBZ='S') */ wrkbl = *m + *m * ilaenv_(&c__1, "CGELQF", " ", m, n, & c_n1, &c_n1, (ftnlen)6, (ftnlen)1); /* Computing MAX */ i__1 = wrkbl, i__2 = *m + *m * ilaenv_(&c__1, "CUNGLQ", " ", m, n, m, &c_n1, (ftnlen)6, (ftnlen)1); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = ((*m) << (1)) + ((*m) << (1)) * ilaenv_(&c__1, "CGEBRD", " ", m, m, &c_n1, &c_n1, (ftnlen)6, (ftnlen)1); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = ((*m) << (1)) + *m * ilaenv_(&c__1, "CUNMBR", "PRC", m, m, m, &c_n1, (ftnlen)6, ( ftnlen)3); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = ((*m) << (1)) + *m * ilaenv_(&c__1, "CUNMBR", "QLN", m, m, m, &c_n1, (ftnlen)6, ( ftnlen)3); wrkbl = max(i__1,i__2); maxwrk = *m * *m + wrkbl; minwrk = *m * *m + *m * 3; } else if (wntqa) { /* Path 4t (N much larger than M, JOBZ='A') */ wrkbl = *m + *m * ilaenv_(&c__1, "CGELQF", " ", m, n, & c_n1, &c_n1, (ftnlen)6, (ftnlen)1); /* Computing MAX */ i__1 = wrkbl, i__2 = *m + *n * ilaenv_(&c__1, "CUNGLQ", " ", n, n, m, &c_n1, (ftnlen)6, (ftnlen)1); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = ((*m) << (1)) + ((*m) << (1)) * ilaenv_(&c__1, "CGEBRD", " ", m, m, &c_n1, &c_n1, (ftnlen)6, (ftnlen)1); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = ((*m) << (1)) + *m * ilaenv_(&c__1, "CUNMBR", "PRC", m, m, m, &c_n1, (ftnlen)6, ( ftnlen)3); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = ((*m) << (1)) + *m * ilaenv_(&c__1, "CUNMBR", "QLN", m, m, m, &c_n1, (ftnlen)6, ( ftnlen)3); wrkbl = max(i__1,i__2); maxwrk = *m * *m + wrkbl; minwrk = *m * *m + ((*m) << (1)) + *n; } } else if (*n >= mnthr2) { /* Path 5t (N much larger than M, but not as much as MNTHR1) */ maxwrk = ((*m) << (1)) + (*m + *n) * ilaenv_(&c__1, "CGEBRD", " ", m, n, &c_n1, &c_n1, (ftnlen)6, (ftnlen)1); minwrk = ((*m) << (1)) + *n; if (wntqo) { /* Computing MAX */ i__1 = maxwrk, i__2 = ((*m) << (1)) + *m * ilaenv_(&c__1, "CUNGBR", "P", m, n, m, &c_n1, (ftnlen)6, (ftnlen) 1); maxwrk = max(i__1,i__2); /* Computing MAX */ i__1 = maxwrk, i__2 = ((*m) << (1)) + *m * ilaenv_(&c__1, "CUNGBR", "Q", m, m, n, &c_n1, (ftnlen)6, (ftnlen) 1); maxwrk = max(i__1,i__2); maxwrk += *m * *n; minwrk += *m * *m; } else if (wntqs) { /* Computing MAX */ i__1 = maxwrk, i__2 = ((*m) << (1)) + *m * ilaenv_(&c__1, "CUNGBR", "P", m, n, m, &c_n1, (ftnlen)6, (ftnlen) 1); maxwrk = max(i__1,i__2); /* Computing MAX */ i__1 = maxwrk, i__2 = ((*m) << (1)) + *m * ilaenv_(&c__1, "CUNGBR", "Q", m, m, n, &c_n1, (ftnlen)6, (ftnlen) 1); maxwrk = max(i__1,i__2); } else if (wntqa) { /* Computing MAX */ i__1 = maxwrk, i__2 = ((*m) << (1)) + *n * ilaenv_(&c__1, "CUNGBR", "P", n, n, m, &c_n1, (ftnlen)6, (ftnlen) 1); maxwrk = max(i__1,i__2); /* Computing MAX */ i__1 = maxwrk, i__2 = ((*m) << (1)) + *m * ilaenv_(&c__1, "CUNGBR", "Q", m, m, n, &c_n1, (ftnlen)6, (ftnlen) 1); maxwrk = max(i__1,i__2); } } else { /* Path 6t (N greater than M, but not much larger) */ maxwrk = ((*m) << (1)) + (*m + *n) * ilaenv_(&c__1, "CGEBRD", " ", m, n, &c_n1, &c_n1, (ftnlen)6, (ftnlen)1); minwrk = ((*m) << (1)) + *n; if (wntqo) { /* Computing MAX */ i__1 = maxwrk, i__2 = ((*m) << (1)) + *m * ilaenv_(&c__1, "CUNMBR", "PRC", m, n, m, &c_n1, (ftnlen)6, ( ftnlen)3); maxwrk = max(i__1,i__2); /* Computing MAX */ i__1 = maxwrk, i__2 = ((*m) << (1)) + *m * ilaenv_(&c__1, "CUNMBR", "QLN", m, m, n, &c_n1, (ftnlen)6, ( ftnlen)3); maxwrk = max(i__1,i__2); maxwrk += *m * *n; minwrk += *m * *m; } else if (wntqs) { /* Computing MAX */ i__1 = maxwrk, i__2 = ((*m) << (1)) + *m * ilaenv_(&c__1, "CUNGBR", "PRC", m, n, m, &c_n1, (ftnlen)6, ( ftnlen)3); maxwrk = max(i__1,i__2); /* Computing MAX */ i__1 = maxwrk, i__2 = ((*m) << (1)) + *m * ilaenv_(&c__1, "CUNGBR", "QLN", m, m, n, &c_n1, (ftnlen)6, ( ftnlen)3); maxwrk = max(i__1,i__2); } else if (wntqa) { /* Computing MAX */ i__1 = maxwrk, i__2 = ((*m) << (1)) + *n * ilaenv_(&c__1, "CUNGBR", "PRC", n, n, m, &c_n1, (ftnlen)6, ( ftnlen)3); maxwrk = max(i__1,i__2); /* Computing MAX */ i__1 = maxwrk, i__2 = ((*m) << (1)) + *m * ilaenv_(&c__1, "CUNGBR", "QLN", m, m, n, &c_n1, (ftnlen)6, ( ftnlen)3); maxwrk = max(i__1,i__2); } } } maxwrk = max(maxwrk,minwrk); work[1].r = (real) maxwrk, work[1].i = 0.f; } if (*lwork < minwrk && ! lquery) { *info = -13; } if (*info != 0) { i__1 = -(*info); xerbla_("CGESDD", &i__1); return 0; } else if (lquery) { return 0; } /* Quick return if possible */ if ((*m == 0) || (*n == 0)) { if (*lwork >= 1) { work[1].r = 1.f, work[1].i = 0.f; } return 0; } /* Get machine constants */ eps = slamch_("P"); smlnum = sqrt(slamch_("S")) / eps; bignum = 1.f / smlnum; /* Scale A if max element outside range [SMLNUM,BIGNUM] */ anrm = clange_("M", m, n, &a[a_offset], lda, dum); iscl = 0; if (anrm > 0.f && anrm < smlnum) { iscl = 1; clascl_("G", &c__0, &c__0, &anrm, &smlnum, m, n, &a[a_offset], lda, & ierr); } else if (anrm > bignum) { iscl = 1; clascl_("G", &c__0, &c__0, &anrm, &bignum, m, n, &a[a_offset], lda, & ierr); } if (*m >= *n) { /* A has at least as many rows as columns. If A has sufficiently more rows than columns, first reduce using the QR decomposition (if sufficient workspace available) */ if (*m >= mnthr1) { if (wntqn) { /* Path 1 (M much larger than N, JOBZ='N') No singular vectors to be computed */ itau = 1; nwork = itau + *n; /* Compute A=Q*R (CWorkspace: need 2*N, prefer N+N*NB) (RWorkspace: need 0) */ i__1 = *lwork - nwork + 1; cgeqrf_(m, n, &a[a_offset], lda, &work[itau], &work[nwork], & i__1, &ierr); /* Zero out below R */ i__1 = *n - 1; i__2 = *n - 1; claset_("L", &i__1, &i__2, &c_b55, &c_b55, &a[a_dim1 + 2], lda); ie = 1; itauq = 1; itaup = itauq + *n; nwork = itaup + *n; /* Bidiagonalize R in A (CWorkspace: need 3*N, prefer 2*N+2*N*NB) (RWorkspace: need N) */ i__1 = *lwork - nwork + 1; cgebrd_(n, n, &a[a_offset], lda, &s[1], &rwork[ie], &work[ itauq], &work[itaup], &work[nwork], &i__1, &ierr); nrwork = ie + *n; /* Perform bidiagonal SVD, compute singular values only (CWorkspace: 0) (RWorkspace: need BDSPAC) */ sbdsdc_("U", "N", n, &s[1], &rwork[ie], dum, &c__1, dum, & c__1, dum, idum, &rwork[nrwork], &iwork[1], info); } else if (wntqo) { /* Path 2 (M much larger than N, JOBZ='O') N left singular vectors to be overwritten on A and N right singular vectors to be computed in VT */ iu = 1; /* WORK(IU) is N by N */ ldwrku = *n; ir = iu + ldwrku * *n; if (*lwork >= *m * *n + *n * *n + *n * 3) { /* WORK(IR) is M by N */ ldwrkr = *m; } else { ldwrkr = (*lwork - *n * *n - *n * 3) / *n; } itau = ir + ldwrkr * *n; nwork = itau + *n; /* Compute A=Q*R (CWorkspace: need N*N+2*N, prefer M*N+N+N*NB) (RWorkspace: 0) */ i__1 = *lwork - nwork + 1; cgeqrf_(m, n, &a[a_offset], lda, &work[itau], &work[nwork], & i__1, &ierr); /* Copy R to WORK( IR ), zeroing out below it */ clacpy_("U", n, n, &a[a_offset], lda, &work[ir], &ldwrkr); i__1 = *n - 1; i__2 = *n - 1; claset_("L", &i__1, &i__2, &c_b55, &c_b55, &work[ir + 1], & ldwrkr); /* Generate Q in A (CWorkspace: need 2*N, prefer N+N*NB) (RWorkspace: 0) */ i__1 = *lwork - nwork + 1; cungqr_(m, n, n, &a[a_offset], lda, &work[itau], &work[nwork], &i__1, &ierr); ie = 1; itauq = itau; itaup = itauq + *n; nwork = itaup + *n; /* Bidiagonalize R in WORK(IR) (CWorkspace: need N*N+3*N, prefer M*N+2*N+2*N*NB) (RWorkspace: need N) */ i__1 = *lwork - nwork + 1; cgebrd_(n, n, &work[ir], &ldwrkr, &s[1], &rwork[ie], &work[ itauq], &work[itaup], &work[nwork], &i__1, &ierr); /* Perform bidiagonal SVD, computing left singular vectors of R in WORK(IRU) and computing right singular vectors of R in WORK(IRVT) (CWorkspace: need 0) (RWorkspace: need BDSPAC) */ iru = ie + *n; irvt = iru + *n * *n; nrwork = irvt + *n * *n; sbdsdc_("U", "I", n, &s[1], &rwork[ie], &rwork[iru], n, & rwork[irvt], n, dum, idum, &rwork[nrwork], &iwork[1], info); /* Copy real matrix RWORK(IRU) to complex matrix WORK(IU) Overwrite WORK(IU) by the left singular vectors of R (CWorkspace: need 2*N*N+3*N, prefer M*N+N*N+2*N+N*NB) (RWorkspace: 0) */ clacp2_("F", n, n, &rwork[iru], n, &work[iu], &ldwrku); i__1 = *lwork - nwork + 1; cunmbr_("Q", "L", "N", n, n, n, &work[ir], &ldwrkr, &work[ itauq], &work[iu], &ldwrku, &work[nwork], &i__1, & ierr); /* Copy real matrix RWORK(IRVT) to complex matrix VT Overwrite VT by the right singular vectors of R (CWorkspace: need N*N+3*N, prefer M*N+2*N+N*NB) (RWorkspace: 0) */ clacp2_("F", n, n, &rwork[irvt], n, &vt[vt_offset], ldvt); i__1 = *lwork - nwork + 1; cunmbr_("P", "R", "C", n, n, n, &work[ir], &ldwrkr, &work[ itaup], &vt[vt_offset], ldvt, &work[nwork], &i__1, & ierr); /* Multiply Q in A by left singular vectors of R in WORK(IU), storing result in WORK(IR) and copying to A (CWorkspace: need 2*N*N, prefer N*N+M*N) (RWorkspace: 0) */ i__1 = *m; i__2 = ldwrkr; for (i__ = 1; i__2 < 0 ? i__ >= i__1 : i__ <= i__1; i__ += i__2) { /* Computing MIN */ i__3 = *m - i__ + 1; chunk = min(i__3,ldwrkr); cgemm_("N", "N", &chunk, n, n, &c_b56, &a[i__ + a_dim1], lda, &work[iu], &ldwrku, &c_b55, &work[ir], & ldwrkr); clacpy_("F", &chunk, n, &work[ir], &ldwrkr, &a[i__ + a_dim1], lda); /* L10: */ } } else if (wntqs) { /* Path 3 (M much larger than N, JOBZ='S') N left singular vectors to be computed in U and N right singular vectors to be computed in VT */ ir = 1; /* WORK(IR) is N by N */ ldwrkr = *n; itau = ir + ldwrkr * *n; nwork = itau + *n; /* Compute A=Q*R (CWorkspace: need N*N+2*N, prefer N*N+N+N*NB) (RWorkspace: 0) */ i__2 = *lwork - nwork + 1; cgeqrf_(m, n, &a[a_offset], lda, &work[itau], &work[nwork], & i__2, &ierr); /* Copy R to WORK(IR), zeroing out below it */ clacpy_("U", n, n, &a[a_offset], lda, &work[ir], &ldwrkr); i__2 = *n - 1; i__1 = *n - 1; claset_("L", &i__2, &i__1, &c_b55, &c_b55, &work[ir + 1], & ldwrkr); /* Generate Q in A (CWorkspace: need 2*N, prefer N+N*NB) (RWorkspace: 0) */ i__2 = *lwork - nwork + 1; cungqr_(m, n, n, &a[a_offset], lda, &work[itau], &work[nwork], &i__2, &ierr); ie = 1; itauq = itau; itaup = itauq + *n; nwork = itaup + *n; /* Bidiagonalize R in WORK(IR) (CWorkspace: need N*N+3*N, prefer N*N+2*N+2*N*NB) (RWorkspace: need N) */ i__2 = *lwork - nwork + 1; cgebrd_(n, n, &work[ir], &ldwrkr, &s[1], &rwork[ie], &work[ itauq], &work[itaup], &work[nwork], &i__2, &ierr); /* Perform bidiagonal SVD, computing left singular vectors of bidiagonal matrix in RWORK(IRU) and computing right singular vectors of bidiagonal matrix in RWORK(IRVT) (CWorkspace: need 0) (RWorkspace: need BDSPAC) */ iru = ie + *n; irvt = iru + *n * *n; nrwork = irvt + *n * *n; sbdsdc_("U", "I", n, &s[1], &rwork[ie], &rwork[iru], n, & rwork[irvt], n, dum, idum, &rwork[nrwork], &iwork[1], info); /* Copy real matrix RWORK(IRU) to complex matrix U Overwrite U by left singular vectors of R (CWorkspace: need N*N+3*N, prefer N*N+2*N+N*NB) (RWorkspace: 0) */ clacp2_("F", n, n, &rwork[iru], n, &u[u_offset], ldu); i__2 = *lwork - nwork + 1; cunmbr_("Q", "L", "N", n, n, n, &work[ir], &ldwrkr, &work[ itauq], &u[u_offset], ldu, &work[nwork], &i__2, &ierr); /* Copy real matrix RWORK(IRVT) to complex matrix VT Overwrite VT by right singular vectors of R (CWorkspace: need N*N+3*N, prefer N*N+2*N+N*NB) (RWorkspace: 0) */ clacp2_("F", n, n, &rwork[irvt], n, &vt[vt_offset], ldvt); i__2 = *lwork - nwork + 1; cunmbr_("P", "R", "C", n, n, n, &work[ir], &ldwrkr, &work[ itaup], &vt[vt_offset], ldvt, &work[nwork], &i__2, & ierr); /* Multiply Q in A by left singular vectors of R in WORK(IR), storing result in U (CWorkspace: need N*N) (RWorkspace: 0) */ clacpy_("F", n, n, &u[u_offset], ldu, &work[ir], &ldwrkr); cgemm_("N", "N", m, n, n, &c_b56, &a[a_offset], lda, &work[ir] , &ldwrkr, &c_b55, &u[u_offset], ldu); } else if (wntqa) { /* Path 4 (M much larger than N, JOBZ='A') M left singular vectors to be computed in U and N right singular vectors to be computed in VT */ iu = 1; /* WORK(IU) is N by N */ ldwrku = *n; itau = iu + ldwrku * *n; nwork = itau + *n; /* Compute A=Q*R, copying result to U (CWorkspace: need 2*N, prefer N+N*NB) (RWorkspace: 0) */ i__2 = *lwork - nwork + 1; cgeqrf_(m, n, &a[a_offset], lda, &work[itau], &work[nwork], & i__2, &ierr); clacpy_("L", m, n, &a[a_offset], lda, &u[u_offset], ldu); /* Generate Q in U (CWorkspace: need N+M, prefer N+M*NB) (RWorkspace: 0) */ i__2 = *lwork - nwork + 1; cungqr_(m, m, n, &u[u_offset], ldu, &work[itau], &work[nwork], &i__2, &ierr); /* Produce R in A, zeroing out below it */ i__2 = *n - 1; i__1 = *n - 1; claset_("L", &i__2, &i__1, &c_b55, &c_b55, &a[a_dim1 + 2], lda); ie = 1; itauq = itau; itaup = itauq + *n; nwork = itaup + *n; /* Bidiagonalize R in A (CWorkspace: need 3*N, prefer 2*N+2*N*NB) (RWorkspace: need N) */ i__2 = *lwork - nwork + 1; cgebrd_(n, n, &a[a_offset], lda, &s[1], &rwork[ie], &work[ itauq], &work[itaup], &work[nwork], &i__2, &ierr); iru = ie + *n; irvt = iru + *n * *n; nrwork = irvt + *n * *n; /* Perform bidiagonal SVD, computing left singular vectors of bidiagonal matrix in RWORK(IRU) and computing right singular vectors of bidiagonal matrix in RWORK(IRVT) (CWorkspace: need 0) (RWorkspace: need BDSPAC) */ sbdsdc_("U", "I", n, &s[1], &rwork[ie], &rwork[iru], n, & rwork[irvt], n, dum, idum, &rwork[nrwork], &iwork[1], info); /* Copy real matrix RWORK(IRU) to complex matrix WORK(IU) Overwrite WORK(IU) by left singular vectors of R (CWorkspace: need N*N+3*N, prefer N*N+2*N+N*NB) (RWorkspace: 0) */ clacp2_("F", n, n, &rwork[iru], n, &work[iu], &ldwrku); i__2 = *lwork - nwork + 1; cunmbr_("Q", "L", "N", n, n, n, &a[a_offset], lda, &work[ itauq], &work[iu], &ldwrku, &work[nwork], &i__2, & ierr); /* Copy real matrix RWORK(IRVT) to complex matrix VT Overwrite VT by right singular vectors of R (CWorkspace: need 3*N, prefer 2*N+N*NB) (RWorkspace: 0) */ clacp2_("F", n, n, &rwork[irvt], n, &vt[vt_offset], ldvt); i__2 = *lwork - nwork + 1; cunmbr_("P", "R", "C", n, n, n, &a[a_offset], lda, &work[ itaup], &vt[vt_offset], ldvt, &work[nwork], &i__2, & ierr); /* Multiply Q in U by left singular vectors of R in WORK(IU), storing result in A (CWorkspace: need N*N) (RWorkspace: 0) */ cgemm_("N", "N", m, n, n, &c_b56, &u[u_offset], ldu, &work[iu] , &ldwrku, &c_b55, &a[a_offset], lda); /* Copy left singular vectors of A from A to U */ clacpy_("F", m, n, &a[a_offset], lda, &u[u_offset], ldu); } } else if (*m >= mnthr2) { /* MNTHR2 <= M < MNTHR1 Path 5 (M much larger than N, but not as much as MNTHR1) Reduce to bidiagonal form without QR decomposition, use CUNGBR and matrix multiplication to compute singular vectors */ ie = 1; nrwork = ie + *n; itauq = 1; itaup = itauq + *n; nwork = itaup + *n; /* Bidiagonalize A (CWorkspace: need 2*N+M, prefer 2*N+(M+N)*NB) (RWorkspace: need N) */ i__2 = *lwork - nwork + 1; cgebrd_(m, n, &a[a_offset], lda, &s[1], &rwork[ie], &work[itauq], &work[itaup], &work[nwork], &i__2, &ierr); if (wntqn) { /* Compute singular values only (Cworkspace: 0) (Rworkspace: need BDSPAC) */ sbdsdc_("U", "N", n, &s[1], &rwork[ie], dum, &c__1, dum, & c__1, dum, idum, &rwork[nrwork], &iwork[1], info); } else if (wntqo) { iu = nwork; iru = nrwork; irvt = iru + *n * *n; nrwork = irvt + *n * *n; /* Copy A to VT, generate P**H (Cworkspace: need 2*N, prefer N+N*NB) (Rworkspace: 0) */ clacpy_("U", n, n, &a[a_offset], lda, &vt[vt_offset], ldvt); i__2 = *lwork - nwork + 1; cungbr_("P", n, n, n, &vt[vt_offset], ldvt, &work[itaup], & work[nwork], &i__2, &ierr); /* Generate Q in A (CWorkspace: need 2*N, prefer N+N*NB) (RWorkspace: 0) */ i__2 = *lwork - nwork + 1; cungbr_("Q", m, n, n, &a[a_offset], lda, &work[itauq], &work[ nwork], &i__2, &ierr); if (*lwork >= *m * *n + *n * 3) { /* WORK( IU ) is M by N */ ldwrku = *m; } else { /* WORK(IU) is LDWRKU by N */ ldwrku = (*lwork - *n * 3) / *n; } nwork = iu + ldwrku * *n; /* Perform bidiagonal SVD, computing left singular vectors of bidiagonal matrix in RWORK(IRU) and computing right singular vectors of bidiagonal matrix in RWORK(IRVT) (CWorkspace: need 0) (RWorkspace: need BDSPAC) */ sbdsdc_("U", "I", n, &s[1], &rwork[ie], &rwork[iru], n, & rwork[irvt], n, dum, idum, &rwork[nrwork], &iwork[1], info); /* Multiply real matrix RWORK(IRVT) by P**H in VT, storing the result in WORK(IU), copying to VT (Cworkspace: need 0) (Rworkspace: need 3*N*N) */ clarcm_(n, n, &rwork[irvt], n, &vt[vt_offset], ldvt, &work[iu] , &ldwrku, &rwork[nrwork]); clacpy_("F", n, n, &work[iu], &ldwrku, &vt[vt_offset], ldvt); /* Multiply Q in A by real matrix RWORK(IRU), storing the result in WORK(IU), copying to A (CWorkspace: need N*N, prefer M*N) (Rworkspace: need 3*N*N, prefer N*N+2*M*N) */ nrwork = irvt; i__2 = *m; i__1 = ldwrku; for (i__ = 1; i__1 < 0 ? i__ >= i__2 : i__ <= i__2; i__ += i__1) { /* Computing MIN */ i__3 = *m - i__ + 1; chunk = min(i__3,ldwrku); clacrm_(&chunk, n, &a[i__ + a_dim1], lda, &rwork[iru], n, &work[iu], &ldwrku, &rwork[nrwork]); clacpy_("F", &chunk, n, &work[iu], &ldwrku, &a[i__ + a_dim1], lda); /* L20: */ } } else if (wntqs) { /* Copy A to VT, generate P**H (Cworkspace: need 2*N, prefer N+N*NB) (Rworkspace: 0) */ clacpy_("U", n, n, &a[a_offset], lda, &vt[vt_offset], ldvt); i__1 = *lwork - nwork + 1; cungbr_("P", n, n, n, &vt[vt_offset], ldvt, &work[itaup], & work[nwork], &i__1, &ierr); /* Copy A to U, generate Q (Cworkspace: need 2*N, prefer N+N*NB) (Rworkspace: 0) */ clacpy_("L", m, n, &a[a_offset], lda, &u[u_offset], ldu); i__1 = *lwork - nwork + 1; cungbr_("Q", m, n, n, &u[u_offset], ldu, &work[itauq], &work[ nwork], &i__1, &ierr); /* Perform bidiagonal SVD, computing left singular vectors of bidiagonal matrix in RWORK(IRU) and computing right singular vectors of bidiagonal matrix in RWORK(IRVT) (CWorkspace: need 0) (RWorkspace: need BDSPAC) */ iru = nrwork; irvt = iru + *n * *n; nrwork = irvt + *n * *n; sbdsdc_("U", "I", n, &s[1], &rwork[ie], &rwork[iru], n, & rwork[irvt], n, dum, idum, &rwork[nrwork], &iwork[1], info); /* Multiply real matrix RWORK(IRVT) by P**H in VT, storing the result in A, copying to VT (Cworkspace: need 0) (Rworkspace: need 3*N*N) */ clarcm_(n, n, &rwork[irvt], n, &vt[vt_offset], ldvt, &a[ a_offset], lda, &rwork[nrwork]); clacpy_("F", n, n, &a[a_offset], lda, &vt[vt_offset], ldvt); /* Multiply Q in U by real matrix RWORK(IRU), storing the result in A, copying to U (CWorkspace: need 0) (Rworkspace: need N*N+2*M*N) */ nrwork = irvt; clacrm_(m, n, &u[u_offset], ldu, &rwork[iru], n, &a[a_offset], lda, &rwork[nrwork]); clacpy_("F", m, n, &a[a_offset], lda, &u[u_offset], ldu); } else { /* Copy A to VT, generate P**H (Cworkspace: need 2*N, prefer N+N*NB) (Rworkspace: 0) */ clacpy_("U", n, n, &a[a_offset], lda, &vt[vt_offset], ldvt); i__1 = *lwork - nwork + 1; cungbr_("P", n, n, n, &vt[vt_offset], ldvt, &work[itaup], & work[nwork], &i__1, &ierr); /* Copy A to U, generate Q (Cworkspace: need 2*N, prefer N+N*NB) (Rworkspace: 0) */ clacpy_("L", m, n, &a[a_offset], lda, &u[u_offset], ldu); i__1 = *lwork - nwork + 1; cungbr_("Q", m, m, n, &u[u_offset], ldu, &work[itauq], &work[ nwork], &i__1, &ierr); /* Perform bidiagonal SVD, computing left singular vectors of bidiagonal matrix in RWORK(IRU) and computing right singular vectors of bidiagonal matrix in RWORK(IRVT) (CWorkspace: need 0) (RWorkspace: need BDSPAC) */ iru = nrwork; irvt = iru + *n * *n; nrwork = irvt + *n * *n; sbdsdc_("U", "I", n, &s[1], &rwork[ie], &rwork[iru], n, & rwork[irvt], n, dum, idum, &rwork[nrwork], &iwork[1], info); /* Multiply real matrix RWORK(IRVT) by P**H in VT, storing the result in A, copying to VT (Cworkspace: need 0) (Rworkspace: need 3*N*N) */ clarcm_(n, n, &rwork[irvt], n, &vt[vt_offset], ldvt, &a[ a_offset], lda, &rwork[nrwork]); clacpy_("F", n, n, &a[a_offset], lda, &vt[vt_offset], ldvt); /* Multiply Q in U by real matrix RWORK(IRU), storing the result in A, copying to U (CWorkspace: 0) (Rworkspace: need 3*N*N) */ nrwork = irvt; clacrm_(m, n, &u[u_offset], ldu, &rwork[iru], n, &a[a_offset], lda, &rwork[nrwork]); clacpy_("F", m, n, &a[a_offset], lda, &u[u_offset], ldu); } } else { /* M .LT. MNTHR2 Path 6 (M at least N, but not much larger) Reduce to bidiagonal form without QR decomposition Use CUNMBR to compute singular vectors */ ie = 1; nrwork = ie + *n; itauq = 1; itaup = itauq + *n; nwork = itaup + *n; /* Bidiagonalize A (CWorkspace: need 2*N+M, prefer 2*N+(M+N)*NB) (RWorkspace: need N) */ i__1 = *lwork - nwork + 1; cgebrd_(m, n, &a[a_offset], lda, &s[1], &rwork[ie], &work[itauq], &work[itaup], &work[nwork], &i__1, &ierr); if (wntqn) { /* Compute singular values only (Cworkspace: 0) (Rworkspace: need BDSPAC) */ sbdsdc_("U", "N", n, &s[1], &rwork[ie], dum, &c__1, dum, & c__1, dum, idum, &rwork[nrwork], &iwork[1], info); } else if (wntqo) { iu = nwork; iru = nrwork; irvt = iru + *n * *n; nrwork = irvt + *n * *n; if (*lwork >= *m * *n + *n * 3) { /* WORK( IU ) is M by N */ ldwrku = *m; } else { /* WORK( IU ) is LDWRKU by N */ ldwrku = (*lwork - *n * 3) / *n; } nwork = iu + ldwrku * *n; /* Perform bidiagonal SVD, computing left singular vectors of bidiagonal matrix in RWORK(IRU) and computing right singular vectors of bidiagonal matrix in RWORK(IRVT) (CWorkspace: need 0) (RWorkspace: need BDSPAC) */ sbdsdc_("U", "I", n, &s[1], &rwork[ie], &rwork[iru], n, & rwork[irvt], n, dum, idum, &rwork[nrwork], &iwork[1], info); /* Copy real matrix RWORK(IRVT) to complex matrix VT Overwrite VT by right singular vectors of A (Cworkspace: need 2*N, prefer N+N*NB) (Rworkspace: need 0) */ clacp2_("F", n, n, &rwork[irvt], n, &vt[vt_offset], ldvt); i__1 = *lwork - nwork + 1; cunmbr_("P", "R", "C", n, n, n, &a[a_offset], lda, &work[ itaup], &vt[vt_offset], ldvt, &work[nwork], &i__1, & ierr); if (*lwork >= *m * *n + *n * 3) { /* Copy real matrix RWORK(IRU) to complex matrix WORK(IU) Overwrite WORK(IU) by left singular vectors of A, copying to A (Cworkspace: need M*N+2*N, prefer M*N+N+N*NB) (Rworkspace: need 0) */ claset_("F", m, n, &c_b55, &c_b55, &work[iu], &ldwrku); clacp2_("F", n, n, &rwork[iru], n, &work[iu], &ldwrku); i__1 = *lwork - nwork + 1; cunmbr_("Q", "L", "N", m, n, n, &a[a_offset], lda, &work[ itauq], &work[iu], &ldwrku, &work[nwork], &i__1, & ierr); clacpy_("F", m, n, &work[iu], &ldwrku, &a[a_offset], lda); } else { /* Generate Q in A (Cworkspace: need 2*N, prefer N+N*NB) (Rworkspace: need 0) */ i__1 = *lwork - nwork + 1; cungbr_("Q", m, n, n, &a[a_offset], lda, &work[itauq], & work[nwork], &i__1, &ierr); /* Multiply Q in A by real matrix RWORK(IRU), storing the result in WORK(IU), copying to A (CWorkspace: need N*N, prefer M*N) (Rworkspace: need 3*N*N, prefer N*N+2*M*N) */ nrwork = irvt; i__1 = *m; i__2 = ldwrku; for (i__ = 1; i__2 < 0 ? i__ >= i__1 : i__ <= i__1; i__ += i__2) { /* Computing MIN */ i__3 = *m - i__ + 1; chunk = min(i__3,ldwrku); clacrm_(&chunk, n, &a[i__ + a_dim1], lda, &rwork[iru], n, &work[iu], &ldwrku, &rwork[nrwork]); clacpy_("F", &chunk, n, &work[iu], &ldwrku, &a[i__ + a_dim1], lda); /* L30: */ } } } else if (wntqs) { /* Perform bidiagonal SVD, computing left singular vectors of bidiagonal matrix in RWORK(IRU) and computing right singular vectors of bidiagonal matrix in RWORK(IRVT) (CWorkspace: need 0) (RWorkspace: need BDSPAC) */ iru = nrwork; irvt = iru + *n * *n; nrwork = irvt + *n * *n; sbdsdc_("U", "I", n, &s[1], &rwork[ie], &rwork[iru], n, & rwork[irvt], n, dum, idum, &rwork[nrwork], &iwork[1], info); /* Copy real matrix RWORK(IRU) to complex matrix U Overwrite U by left singular vectors of A (CWorkspace: need 3*N, prefer 2*N+N*NB) (RWorkspace: 0) */ claset_("F", m, n, &c_b55, &c_b55, &u[u_offset], ldu); clacp2_("F", n, n, &rwork[iru], n, &u[u_offset], ldu); i__2 = *lwork - nwork + 1; cunmbr_("Q", "L", "N", m, n, n, &a[a_offset], lda, &work[ itauq], &u[u_offset], ldu, &work[nwork], &i__2, &ierr); /* Copy real matrix RWORK(IRVT) to complex matrix VT Overwrite VT by right singular vectors of A (CWorkspace: need 3*N, prefer 2*N+N*NB) (RWorkspace: 0) */ clacp2_("F", n, n, &rwork[irvt], n, &vt[vt_offset], ldvt); i__2 = *lwork - nwork + 1; cunmbr_("P", "R", "C", n, n, n, &a[a_offset], lda, &work[ itaup], &vt[vt_offset], ldvt, &work[nwork], &i__2, & ierr); } else { /* Perform bidiagonal SVD, computing left singular vectors of bidiagonal matrix in RWORK(IRU) and computing right singular vectors of bidiagonal matrix in RWORK(IRVT) (CWorkspace: need 0) (RWorkspace: need BDSPAC) */ iru = nrwork; irvt = iru + *n * *n; nrwork = irvt + *n * *n; sbdsdc_("U", "I", n, &s[1], &rwork[ie], &rwork[iru], n, & rwork[irvt], n, dum, idum, &rwork[nrwork], &iwork[1], info); /* Set the right corner of U to identity matrix */ claset_("F", m, m, &c_b55, &c_b55, &u[u_offset], ldu); i__2 = *m - *n; i__1 = *m - *n; claset_("F", &i__2, &i__1, &c_b55, &c_b56, &u[*n + 1 + (*n + 1) * u_dim1], ldu); /* Copy real matrix RWORK(IRU) to complex matrix U Overwrite U by left singular vectors of A (CWorkspace: need 2*N+M, prefer 2*N+M*NB) (RWorkspace: 0) */ clacp2_("F", n, n, &rwork[iru], n, &u[u_offset], ldu); i__2 = *lwork - nwork + 1; cunmbr_("Q", "L", "N", m, m, n, &a[a_offset], lda, &work[ itauq], &u[u_offset], ldu, &work[nwork], &i__2, &ierr); /* Copy real matrix RWORK(IRVT) to complex matrix VT Overwrite VT by right singular vectors of A (CWorkspace: need 3*N, prefer 2*N+N*NB) (RWorkspace: 0) */ clacp2_("F", n, n, &rwork[irvt], n, &vt[vt_offset], ldvt); i__2 = *lwork - nwork + 1; cunmbr_("P", "R", "C", n, n, n, &a[a_offset], lda, &work[ itaup], &vt[vt_offset], ldvt, &work[nwork], &i__2, & ierr); } } } else { /* A has more columns than rows. If A has sufficiently more columns than rows, first reduce using the LQ decomposition (if sufficient workspace available) */ if (*n >= mnthr1) { if (wntqn) { /* Path 1t (N much larger than M, JOBZ='N') No singular vectors to be computed */ itau = 1; nwork = itau + *m; /* Compute A=L*Q (CWorkspace: need 2*M, prefer M+M*NB) (RWorkspace: 0) */ i__2 = *lwork - nwork + 1; cgelqf_(m, n, &a[a_offset], lda, &work[itau], &work[nwork], & i__2, &ierr); /* Zero out above L */ i__2 = *m - 1; i__1 = *m - 1; claset_("U", &i__2, &i__1, &c_b55, &c_b55, &a[((a_dim1) << (1) ) + 1], lda); ie = 1; itauq = 1; itaup = itauq + *m; nwork = itaup + *m; /* Bidiagonalize L in A (CWorkspace: need 3*M, prefer 2*M+2*M*NB) (RWorkspace: need M) */ i__2 = *lwork - nwork + 1; cgebrd_(m, m, &a[a_offset], lda, &s[1], &rwork[ie], &work[ itauq], &work[itaup], &work[nwork], &i__2, &ierr); nrwork = ie + *m; /* Perform bidiagonal SVD, compute singular values only (CWorkspace: 0) (RWorkspace: need BDSPAC) */ sbdsdc_("U", "N", m, &s[1], &rwork[ie], dum, &c__1, dum, & c__1, dum, idum, &rwork[nrwork], &iwork[1], info); } else if (wntqo) { /* Path 2t (N much larger than M, JOBZ='O') M right singular vectors to be overwritten on A and M left singular vectors to be computed in U */ ivt = 1; ldwkvt = *m; /* WORK(IVT) is M by M */ il = ivt + ldwkvt * *m; if (*lwork >= *m * *n + *m * *m + *m * 3) { /* WORK(IL) M by N */ ldwrkl = *m; chunk = *n; } else { /* WORK(IL) is M by CHUNK */ ldwrkl = *m; chunk = (*lwork - *m * *m - *m * 3) / *m; } itau = il + ldwrkl * chunk; nwork = itau + *m; /* Compute A=L*Q (CWorkspace: need 2*M, prefer M+M*NB) (RWorkspace: 0) */ i__2 = *lwork - nwork + 1; cgelqf_(m, n, &a[a_offset], lda, &work[itau], &work[nwork], & i__2, &ierr); /* Copy L to WORK(IL), zeroing about above it */ clacpy_("L", m, m, &a[a_offset], lda, &work[il], &ldwrkl); i__2 = *m - 1; i__1 = *m - 1; claset_("U", &i__2, &i__1, &c_b55, &c_b55, &work[il + ldwrkl], &ldwrkl); /* Generate Q in A (CWorkspace: need M*M+2*M, prefer M*M+M+M*NB) (RWorkspace: 0) */ i__2 = *lwork - nwork + 1; cunglq_(m, n, m, &a[a_offset], lda, &work[itau], &work[nwork], &i__2, &ierr); ie = 1; itauq = itau; itaup = itauq + *m; nwork = itaup + *m; /* Bidiagonalize L in WORK(IL) (CWorkspace: need M*M+3*M, prefer M*M+2*M+2*M*NB) (RWorkspace: need M) */ i__2 = *lwork - nwork + 1; cgebrd_(m, m, &work[il], &ldwrkl, &s[1], &rwork[ie], &work[ itauq], &work[itaup], &work[nwork], &i__2, &ierr); /* Perform bidiagonal SVD, computing left singular vectors of bidiagonal matrix in RWORK(IRU) and computing right singular vectors of bidiagonal matrix in RWORK(IRVT) (CWorkspace: need 0) (RWorkspace: need BDSPAC) */ iru = ie + *m; irvt = iru + *m * *m; nrwork = irvt + *m * *m; sbdsdc_("U", "I", m, &s[1], &rwork[ie], &rwork[iru], m, & rwork[irvt], m, dum, idum, &rwork[nrwork], &iwork[1], info); /* Copy real matrix RWORK(IRU) to complex matrix WORK(IU) Overwrite WORK(IU) by the left singular vectors of L (CWorkspace: need N*N+3*N, prefer M*N+2*N+N*NB) (RWorkspace: 0) */ clacp2_("F", m, m, &rwork[iru], m, &u[u_offset], ldu); i__2 = *lwork - nwork + 1; cunmbr_("Q", "L", "N", m, m, m, &work[il], &ldwrkl, &work[ itauq], &u[u_offset], ldu, &work[nwork], &i__2, &ierr); /* Copy real matrix RWORK(IRVT) to complex matrix WORK(IVT) Overwrite WORK(IVT) by the right singular vectors of L (CWorkspace: need N*N+3*N, prefer M*N+2*N+N*NB) (RWorkspace: 0) */ clacp2_("F", m, m, &rwork[irvt], m, &work[ivt], &ldwkvt); i__2 = *lwork - nwork + 1; cunmbr_("P", "R", "C", m, m, m, &work[il], &ldwrkl, &work[ itaup], &work[ivt], &ldwkvt, &work[nwork], &i__2, & ierr); /* Multiply right singular vectors of L in WORK(IL) by Q in A, storing result in WORK(IL) and copying to A (CWorkspace: need 2*M*M, prefer M*M+M*N)) (RWorkspace: 0) */ i__2 = *n; i__1 = chunk; for (i__ = 1; i__1 < 0 ? i__ >= i__2 : i__ <= i__2; i__ += i__1) { /* Computing MIN */ i__3 = *n - i__ + 1; blk = min(i__3,chunk); cgemm_("N", "N", m, &blk, m, &c_b56, &work[ivt], m, &a[ i__ * a_dim1 + 1], lda, &c_b55, &work[il], & ldwrkl); clacpy_("F", m, &blk, &work[il], &ldwrkl, &a[i__ * a_dim1 + 1], lda); /* L40: */ } } else if (wntqs) { /* Path 3t (N much larger than M, JOBZ='S') M right singular vectors to be computed in VT and M left singular vectors to be computed in U */ il = 1; /* WORK(IL) is M by M */ ldwrkl = *m; itau = il + ldwrkl * *m; nwork = itau + *m; /* Compute A=L*Q (CWorkspace: need 2*M, prefer M+M*NB) (RWorkspace: 0) */ i__1 = *lwork - nwork + 1; cgelqf_(m, n, &a[a_offset], lda, &work[itau], &work[nwork], & i__1, &ierr); /* Copy L to WORK(IL), zeroing out above it */ clacpy_("L", m, m, &a[a_offset], lda, &work[il], &ldwrkl); i__1 = *m - 1; i__2 = *m - 1; claset_("U", &i__1, &i__2, &c_b55, &c_b55, &work[il + ldwrkl], &ldwrkl); /* Generate Q in A (CWorkspace: need M*M+2*M, prefer M*M+M+M*NB) (RWorkspace: 0) */ i__1 = *lwork - nwork + 1; cunglq_(m, n, m, &a[a_offset], lda, &work[itau], &work[nwork], &i__1, &ierr); ie = 1; itauq = itau; itaup = itauq + *m; nwork = itaup + *m; /* Bidiagonalize L in WORK(IL) (CWorkspace: need M*M+3*M, prefer M*M+2*M+2*M*NB) (RWorkspace: need M) */ i__1 = *lwork - nwork + 1; cgebrd_(m, m, &work[il], &ldwrkl, &s[1], &rwork[ie], &work[ itauq], &work[itaup], &work[nwork], &i__1, &ierr); /* Perform bidiagonal SVD, computing left singular vectors of bidiagonal matrix in RWORK(IRU) and computing right singular vectors of bidiagonal matrix in RWORK(IRVT) (CWorkspace: need 0) (RWorkspace: need BDSPAC) */ iru = ie + *m; irvt = iru + *m * *m; nrwork = irvt + *m * *m; sbdsdc_("U", "I", m, &s[1], &rwork[ie], &rwork[iru], m, & rwork[irvt], m, dum, idum, &rwork[nrwork], &iwork[1], info); /* Copy real matrix RWORK(IRU) to complex matrix U Overwrite U by left singular vectors of L (CWorkspace: need M*M+3*M, prefer M*M+2*M+M*NB) (RWorkspace: 0) */ clacp2_("F", m, m, &rwork[iru], m, &u[u_offset], ldu); i__1 = *lwork - nwork + 1; cunmbr_("Q", "L", "N", m, m, m, &work[il], &ldwrkl, &work[ itauq], &u[u_offset], ldu, &work[nwork], &i__1, &ierr); /* Copy real matrix RWORK(IRVT) to complex matrix VT Overwrite VT by left singular vectors of L (CWorkspace: need M*M+3*M, prefer M*M+2*M+M*NB) (RWorkspace: 0) */ clacp2_("F", m, m, &rwork[irvt], m, &vt[vt_offset], ldvt); i__1 = *lwork - nwork + 1; cunmbr_("P", "R", "C", m, m, m, &work[il], &ldwrkl, &work[ itaup], &vt[vt_offset], ldvt, &work[nwork], &i__1, & ierr); /* Copy VT to WORK(IL), multiply right singular vectors of L in WORK(IL) by Q in A, storing result in VT (CWorkspace: need M*M) (RWorkspace: 0) */ clacpy_("F", m, m, &vt[vt_offset], ldvt, &work[il], &ldwrkl); cgemm_("N", "N", m, n, m, &c_b56, &work[il], &ldwrkl, &a[ a_offset], lda, &c_b55, &vt[vt_offset], ldvt); } else if (wntqa) { /* Path 9t (N much larger than M, JOBZ='A') N right singular vectors to be computed in VT and M left singular vectors to be computed in U */ ivt = 1; /* WORK(IVT) is M by M */ ldwkvt = *m; itau = ivt + ldwkvt * *m; nwork = itau + *m; /* Compute A=L*Q, copying result to VT (CWorkspace: need 2*M, prefer M+M*NB) (RWorkspace: 0) */ i__1 = *lwork - nwork + 1; cgelqf_(m, n, &a[a_offset], lda, &work[itau], &work[nwork], & i__1, &ierr); clacpy_("U", m, n, &a[a_offset], lda, &vt[vt_offset], ldvt); /* Generate Q in VT (CWorkspace: need M+N, prefer M+N*NB) (RWorkspace: 0) */ i__1 = *lwork - nwork + 1; cunglq_(n, n, m, &vt[vt_offset], ldvt, &work[itau], &work[ nwork], &i__1, &ierr); /* Produce L in A, zeroing out above it */ i__1 = *m - 1; i__2 = *m - 1; claset_("U", &i__1, &i__2, &c_b55, &c_b55, &a[((a_dim1) << (1) ) + 1], lda); ie = 1; itauq = itau; itaup = itauq + *m; nwork = itaup + *m; /* Bidiagonalize L in A (CWorkspace: need M*M+3*M, prefer M*M+2*M+2*M*NB) (RWorkspace: need M) */ i__1 = *lwork - nwork + 1; cgebrd_(m, m, &a[a_offset], lda, &s[1], &rwork[ie], &work[ itauq], &work[itaup], &work[nwork], &i__1, &ierr); /* Perform bidiagonal SVD, computing left singular vectors of bidiagonal matrix in RWORK(IRU) and computing right singular vectors of bidiagonal matrix in RWORK(IRVT) (CWorkspace: need 0) (RWorkspace: need BDSPAC) */ iru = ie + *m; irvt = iru + *m * *m; nrwork = irvt + *m * *m; sbdsdc_("U", "I", m, &s[1], &rwork[ie], &rwork[iru], m, & rwork[irvt], m, dum, idum, &rwork[nrwork], &iwork[1], info); /* Copy real matrix RWORK(IRU) to complex matrix U Overwrite U by left singular vectors of L (CWorkspace: need 3*M, prefer 2*M+M*NB) (RWorkspace: 0) */ clacp2_("F", m, m, &rwork[iru], m, &u[u_offset], ldu); i__1 = *lwork - nwork + 1; cunmbr_("Q", "L", "N", m, m, m, &a[a_offset], lda, &work[ itauq], &u[u_offset], ldu, &work[nwork], &i__1, &ierr); /* Copy real matrix RWORK(IRVT) to complex matrix WORK(IVT) Overwrite WORK(IVT) by right singular vectors of L (CWorkspace: need M*M+3*M, prefer M*M+2*M+M*NB) (RWorkspace: 0) */ clacp2_("F", m, m, &rwork[irvt], m, &work[ivt], &ldwkvt); i__1 = *lwork - nwork + 1; cunmbr_("P", "R", "C", m, m, m, &a[a_offset], lda, &work[ itaup], &work[ivt], &ldwkvt, &work[nwork], &i__1, & ierr); /* Multiply right singular vectors of L in WORK(IVT) by Q in VT, storing result in A (CWorkspace: need M*M) (RWorkspace: 0) */ cgemm_("N", "N", m, n, m, &c_b56, &work[ivt], &ldwkvt, &vt[ vt_offset], ldvt, &c_b55, &a[a_offset], lda); /* Copy right singular vectors of A from A to VT */ clacpy_("F", m, n, &a[a_offset], lda, &vt[vt_offset], ldvt); } } else if (*n >= mnthr2) { /* MNTHR2 <= N < MNTHR1 Path 5t (N much larger than M, but not as much as MNTHR1) Reduce to bidiagonal form without QR decomposition, use CUNGBR and matrix multiplication to compute singular vectors */ ie = 1; nrwork = ie + *m; itauq = 1; itaup = itauq + *m; nwork = itaup + *m; /* Bidiagonalize A (CWorkspace: need 2*M+N, prefer 2*M+(M+N)*NB) (RWorkspace: M) */ i__1 = *lwork - nwork + 1; cgebrd_(m, n, &a[a_offset], lda, &s[1], &rwork[ie], &work[itauq], &work[itaup], &work[nwork], &i__1, &ierr); if (wntqn) { /* Compute singular values only (Cworkspace: 0) (Rworkspace: need BDSPAC) */ sbdsdc_("L", "N", m, &s[1], &rwork[ie], dum, &c__1, dum, & c__1, dum, idum, &rwork[nrwork], &iwork[1], info); } else if (wntqo) { irvt = nrwork; iru = irvt + *m * *m; nrwork = iru + *m * *m; ivt = nwork; /* Copy A to U, generate Q (Cworkspace: need 2*M, prefer M+M*NB) (Rworkspace: 0) */ clacpy_("L", m, m, &a[a_offset], lda, &u[u_offset], ldu); i__1 = *lwork - nwork + 1; cungbr_("Q", m, m, n, &u[u_offset], ldu, &work[itauq], &work[ nwork], &i__1, &ierr); /* Generate P**H in A (Cworkspace: need 2*M, prefer M+M*NB) (Rworkspace: 0) */ i__1 = *lwork - nwork + 1; cungbr_("P", m, n, m, &a[a_offset], lda, &work[itaup], &work[ nwork], &i__1, &ierr); ldwkvt = *m; if (*lwork >= *m * *n + *m * 3) { /* WORK( IVT ) is M by N */ nwork = ivt + ldwkvt * *n; chunk = *n; } else { /* WORK( IVT ) is M by CHUNK */ chunk = (*lwork - *m * 3) / *m; nwork = ivt + ldwkvt * chunk; } /* Perform bidiagonal SVD, computing left singular vectors of bidiagonal matrix in RWORK(IRU) and computing right singular vectors of bidiagonal matrix in RWORK(IRVT) (CWorkspace: need 0) (RWorkspace: need BDSPAC) */ sbdsdc_("L", "I", m, &s[1], &rwork[ie], &rwork[iru], m, & rwork[irvt], m, dum, idum, &rwork[nrwork], &iwork[1], info); /* Multiply Q in U by real matrix RWORK(IRVT) storing the result in WORK(IVT), copying to U (Cworkspace: need 0) (Rworkspace: need 2*M*M) */ clacrm_(m, m, &u[u_offset], ldu, &rwork[iru], m, &work[ivt], & ldwkvt, &rwork[nrwork]); clacpy_("F", m, m, &work[ivt], &ldwkvt, &u[u_offset], ldu); /* Multiply RWORK(IRVT) by P**H in A, storing the result in WORK(IVT), copying to A (CWorkspace: need M*M, prefer M*N) (Rworkspace: need 2*M*M, prefer 2*M*N) */ nrwork = iru; i__1 = *n; i__2 = chunk; for (i__ = 1; i__2 < 0 ? i__ >= i__1 : i__ <= i__1; i__ += i__2) { /* Computing MIN */ i__3 = *n - i__ + 1; blk = min(i__3,chunk); clarcm_(m, &blk, &rwork[irvt], m, &a[i__ * a_dim1 + 1], lda, &work[ivt], &ldwkvt, &rwork[nrwork]); clacpy_("F", m, &blk, &work[ivt], &ldwkvt, &a[i__ * a_dim1 + 1], lda); /* L50: */ } } else if (wntqs) { /* Copy A to U, generate Q (Cworkspace: need 2*M, prefer M+M*NB) (Rworkspace: 0) */ clacpy_("L", m, m, &a[a_offset], lda, &u[u_offset], ldu); i__2 = *lwork - nwork + 1; cungbr_("Q", m, m, n, &u[u_offset], ldu, &work[itauq], &work[ nwork], &i__2, &ierr); /* Copy A to VT, generate P**H (Cworkspace: need 2*M, prefer M+M*NB) (Rworkspace: 0) */ clacpy_("U", m, n, &a[a_offset], lda, &vt[vt_offset], ldvt); i__2 = *lwork - nwork + 1; cungbr_("P", m, n, m, &vt[vt_offset], ldvt, &work[itaup], & work[nwork], &i__2, &ierr); /* Perform bidiagonal SVD, computing left singular vectors of bidiagonal matrix in RWORK(IRU) and computing right singular vectors of bidiagonal matrix in RWORK(IRVT) (CWorkspace: need 0) (RWorkspace: need BDSPAC) */ irvt = nrwork; iru = irvt + *m * *m; nrwork = iru + *m * *m; sbdsdc_("L", "I", m, &s[1], &rwork[ie], &rwork[iru], m, & rwork[irvt], m, dum, idum, &rwork[nrwork], &iwork[1], info); /* Multiply Q in U by real matrix RWORK(IRU), storing the result in A, copying to U (CWorkspace: need 0) (Rworkspace: need 3*M*M) */ clacrm_(m, m, &u[u_offset], ldu, &rwork[iru], m, &a[a_offset], lda, &rwork[nrwork]); clacpy_("F", m, m, &a[a_offset], lda, &u[u_offset], ldu); /* Multiply real matrix RWORK(IRVT) by P**H in VT, storing the result in A, copying to VT (Cworkspace: need 0) (Rworkspace: need M*M+2*M*N) */ nrwork = iru; clarcm_(m, n, &rwork[irvt], m, &vt[vt_offset], ldvt, &a[ a_offset], lda, &rwork[nrwork]); clacpy_("F", m, n, &a[a_offset], lda, &vt[vt_offset], ldvt); } else { /* Copy A to U, generate Q (Cworkspace: need 2*M, prefer M+M*NB) (Rworkspace: 0) */ clacpy_("L", m, m, &a[a_offset], lda, &u[u_offset], ldu); i__2 = *lwork - nwork + 1; cungbr_("Q", m, m, n, &u[u_offset], ldu, &work[itauq], &work[ nwork], &i__2, &ierr); /* Copy A to VT, generate P**H (Cworkspace: need 2*M, prefer M+M*NB) (Rworkspace: 0) */ clacpy_("U", m, n, &a[a_offset], lda, &vt[vt_offset], ldvt); i__2 = *lwork - nwork + 1; cungbr_("P", n, n, m, &vt[vt_offset], ldvt, &work[itaup], & work[nwork], &i__2, &ierr); /* Perform bidiagonal SVD, computing left singular vectors of bidiagonal matrix in RWORK(IRU) and computing right singular vectors of bidiagonal matrix in RWORK(IRVT) (CWorkspace: need 0) (RWorkspace: need BDSPAC) */ irvt = nrwork; iru = irvt + *m * *m; nrwork = iru + *m * *m; sbdsdc_("L", "I", m, &s[1], &rwork[ie], &rwork[iru], m, & rwork[irvt], m, dum, idum, &rwork[nrwork], &iwork[1], info); /* Multiply Q in U by real matrix RWORK(IRU), storing the result in A, copying to U (CWorkspace: need 0) (Rworkspace: need 3*M*M) */ clacrm_(m, m, &u[u_offset], ldu, &rwork[iru], m, &a[a_offset], lda, &rwork[nrwork]); clacpy_("F", m, m, &a[a_offset], lda, &u[u_offset], ldu); /* Multiply real matrix RWORK(IRVT) by P**H in VT, storing the result in A, copying to VT (Cworkspace: need 0) (Rworkspace: need M*M+2*M*N) */ clarcm_(m, n, &rwork[irvt], m, &vt[vt_offset], ldvt, &a[ a_offset], lda, &rwork[nrwork]); clacpy_("F", m, n, &a[a_offset], lda, &vt[vt_offset], ldvt); } } else { /* N .LT. MNTHR2 Path 6t (N greater than M, but not much larger) Reduce to bidiagonal form without LQ decomposition Use CUNMBR to compute singular vectors */ ie = 1; nrwork = ie + *m; itauq = 1; itaup = itauq + *m; nwork = itaup + *m; /* Bidiagonalize A (CWorkspace: need 2*M+N, prefer 2*M+(M+N)*NB) (RWorkspace: M) */ i__2 = *lwork - nwork + 1; cgebrd_(m, n, &a[a_offset], lda, &s[1], &rwork[ie], &work[itauq], &work[itaup], &work[nwork], &i__2, &ierr); if (wntqn) { /* Compute singular values only (Cworkspace: 0) (Rworkspace: need BDSPAC) */ sbdsdc_("L", "N", m, &s[1], &rwork[ie], dum, &c__1, dum, & c__1, dum, idum, &rwork[nrwork], &iwork[1], info); } else if (wntqo) { ldwkvt = *m; ivt = nwork; if (*lwork >= *m * *n + *m * 3) { /* WORK( IVT ) is M by N */ claset_("F", m, n, &c_b55, &c_b55, &work[ivt], &ldwkvt); nwork = ivt + ldwkvt * *n; } else { /* WORK( IVT ) is M by CHUNK */ chunk = (*lwork - *m * 3) / *m; nwork = ivt + ldwkvt * chunk; } /* Perform bidiagonal SVD, computing left singular vectors of bidiagonal matrix in RWORK(IRU) and computing right singular vectors of bidiagonal matrix in RWORK(IRVT) (CWorkspace: need 0) (RWorkspace: need BDSPAC) */ irvt = nrwork; iru = irvt + *m * *m; nrwork = iru + *m * *m; sbdsdc_("L", "I", m, &s[1], &rwork[ie], &rwork[iru], m, & rwork[irvt], m, dum, idum, &rwork[nrwork], &iwork[1], info); /* Copy real matrix RWORK(IRU) to complex matrix U Overwrite U by left singular vectors of A (Cworkspace: need 2*M, prefer M+M*NB) (Rworkspace: need 0) */ clacp2_("F", m, m, &rwork[iru], m, &u[u_offset], ldu); i__2 = *lwork - nwork + 1; cunmbr_("Q", "L", "N", m, m, n, &a[a_offset], lda, &work[ itauq], &u[u_offset], ldu, &work[nwork], &i__2, &ierr); if (*lwork >= *m * *n + *m * 3) { /* Copy real matrix RWORK(IRVT) to complex matrix WORK(IVT) Overwrite WORK(IVT) by right singular vectors of A, copying to A (Cworkspace: need M*N+2*M, prefer M*N+M+M*NB) (Rworkspace: need 0) */ clacp2_("F", m, m, &rwork[irvt], m, &work[ivt], &ldwkvt); i__2 = *lwork - nwork + 1; cunmbr_("P", "R", "C", m, n, m, &a[a_offset], lda, &work[ itaup], &work[ivt], &ldwkvt, &work[nwork], &i__2, &ierr); clacpy_("F", m, n, &work[ivt], &ldwkvt, &a[a_offset], lda); } else { /* Generate P**H in A (Cworkspace: need 2*M, prefer M+M*NB) (Rworkspace: need 0) */ i__2 = *lwork - nwork + 1; cungbr_("P", m, n, m, &a[a_offset], lda, &work[itaup], & work[nwork], &i__2, &ierr); /* Multiply Q in A by real matrix RWORK(IRU), storing the result in WORK(IU), copying to A (CWorkspace: need M*M, prefer M*N) (Rworkspace: need 3*M*M, prefer M*M+2*M*N) */ nrwork = iru; i__2 = *n; i__1 = chunk; for (i__ = 1; i__1 < 0 ? i__ >= i__2 : i__ <= i__2; i__ += i__1) { /* Computing MIN */ i__3 = *n - i__ + 1; blk = min(i__3,chunk); clarcm_(m, &blk, &rwork[irvt], m, &a[i__ * a_dim1 + 1] , lda, &work[ivt], &ldwkvt, &rwork[nrwork]); clacpy_("F", m, &blk, &work[ivt], &ldwkvt, &a[i__ * a_dim1 + 1], lda); /* L60: */ } } } else if (wntqs) { /* Perform bidiagonal SVD, computing left singular vectors of bidiagonal matrix in RWORK(IRU) and computing right singular vectors of bidiagonal matrix in RWORK(IRVT) (CWorkspace: need 0) (RWorkspace: need BDSPAC) */ irvt = nrwork; iru = irvt + *m * *m; nrwork = iru + *m * *m; sbdsdc_("L", "I", m, &s[1], &rwork[ie], &rwork[iru], m, & rwork[irvt], m, dum, idum, &rwork[nrwork], &iwork[1], info); /* Copy real matrix RWORK(IRU) to complex matrix U Overwrite U by left singular vectors of A (CWorkspace: need 3*M, prefer 2*M+M*NB) (RWorkspace: M*M) */ clacp2_("F", m, m, &rwork[iru], m, &u[u_offset], ldu); i__1 = *lwork - nwork + 1; cunmbr_("Q", "L", "N", m, m, n, &a[a_offset], lda, &work[ itauq], &u[u_offset], ldu, &work[nwork], &i__1, &ierr); /* Copy real matrix RWORK(IRVT) to complex matrix VT Overwrite VT by right singular vectors of A (CWorkspace: need 3*M, prefer 2*M+M*NB) (RWorkspace: M*M) */ claset_("F", m, n, &c_b55, &c_b55, &vt[vt_offset], ldvt); clacp2_("F", m, m, &rwork[irvt], m, &vt[vt_offset], ldvt); i__1 = *lwork - nwork + 1; cunmbr_("P", "R", "C", m, n, m, &a[a_offset], lda, &work[ itaup], &vt[vt_offset], ldvt, &work[nwork], &i__1, & ierr); } else { /* Perform bidiagonal SVD, computing left singular vectors of bidiagonal matrix in RWORK(IRU) and computing right singular vectors of bidiagonal matrix in RWORK(IRVT) (CWorkspace: need 0) (RWorkspace: need BDSPAC) */ irvt = nrwork; iru = irvt + *m * *m; nrwork = iru + *m * *m; sbdsdc_("L", "I", m, &s[1], &rwork[ie], &rwork[iru], m, & rwork[irvt], m, dum, idum, &rwork[nrwork], &iwork[1], info); /* Copy real matrix RWORK(IRU) to complex matrix U Overwrite U by left singular vectors of A (CWorkspace: need 3*M, prefer 2*M+M*NB) (RWorkspace: M*M) */ clacp2_("F", m, m, &rwork[iru], m, &u[u_offset], ldu); i__1 = *lwork - nwork + 1; cunmbr_("Q", "L", "N", m, m, n, &a[a_offset], lda, &work[ itauq], &u[u_offset], ldu, &work[nwork], &i__1, &ierr); /* Set the right corner of VT to identity matrix */ i__1 = *n - *m; i__2 = *n - *m; claset_("F", &i__1, &i__2, &c_b55, &c_b56, &vt[*m + 1 + (*m + 1) * vt_dim1], ldvt); /* Copy real matrix RWORK(IRVT) to complex matrix VT Overwrite VT by right singular vectors of A (CWorkspace: need 2*M+N, prefer 2*M+N*NB) (RWorkspace: M*M) */ claset_("F", n, n, &c_b55, &c_b55, &vt[vt_offset], ldvt); clacp2_("F", m, m, &rwork[irvt], m, &vt[vt_offset], ldvt); i__1 = *lwork - nwork + 1; cunmbr_("P", "R", "C", n, n, m, &a[a_offset], lda, &work[ itaup], &vt[vt_offset], ldvt, &work[nwork], &i__1, & ierr); } } } /* Undo scaling if necessary */ if (iscl == 1) { if (anrm > bignum) { slascl_("G", &c__0, &c__0, &bignum, &anrm, &minmn, &c__1, &s[1], & minmn, &ierr); } if (anrm < smlnum) { slascl_("G", &c__0, &c__0, &smlnum, &anrm, &minmn, &c__1, &s[1], & minmn, &ierr); } } /* Return optimal workspace in WORK(1) */ work[1].r = (real) maxwrk, work[1].i = 0.f; return 0; /* End of CGESDD */ } /* cgesdd_ */ /* Subroutine */ int cgesv_(integer *n, integer *nrhs, complex *a, integer * lda, integer *ipiv, complex *b, integer *ldb, integer *info) { /* System generated locals */ integer a_dim1, a_offset, b_dim1, b_offset, i__1; /* Local variables */ extern /* Subroutine */ int cgetrf_(integer *, integer *, complex *, integer *, integer *, integer *), xerbla_(char *, integer *), cgetrs_(char *, integer *, integer *, complex *, integer *, integer *, complex *, integer *, integer *); /* -- LAPACK driver routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University March 31, 1993 Purpose ======= CGESV computes the solution to a complex system of linear equations A * X = B, where A is an N-by-N matrix and X and B are N-by-NRHS matrices. The LU decomposition with partial pivoting and row interchanges is used to factor A as A = P * L * U, where P is a permutation matrix, L is unit lower triangular, and U is upper triangular. The factored form of A is then used to solve the system of equations A * X = B. Arguments ========= N (input) INTEGER The number of linear equations, i.e., the order of the matrix A. N >= 0. NRHS (input) INTEGER The number of right hand sides, i.e., the number of columns of the matrix B. NRHS >= 0. A (input/output) COMPLEX array, dimension (LDA,N) On entry, the N-by-N coefficient matrix A. On exit, the factors L and U from the factorization A = P*L*U; the unit diagonal elements of L are not stored. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,N). IPIV (output) INTEGER array, dimension (N) The pivot indices that define the permutation matrix P; row i of the matrix was interchanged with row IPIV(i). B (input/output) COMPLEX array, dimension (LDB,NRHS) On entry, the N-by-NRHS matrix of right hand side matrix B. On exit, if INFO = 0, the N-by-NRHS solution matrix X. LDB (input) INTEGER The leading dimension of the array B. LDB >= max(1,N). INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value > 0: if INFO = i, U(i,i) is exactly zero. The factorization has been completed, but the factor U is exactly singular, so the solution could not be computed. ===================================================================== Test the input parameters. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --ipiv; b_dim1 = *ldb; b_offset = 1 + b_dim1; b -= b_offset; /* Function Body */ *info = 0; if (*n < 0) { *info = -1; } else if (*nrhs < 0) { *info = -2; } else if (*lda < max(1,*n)) { *info = -4; } else if (*ldb < max(1,*n)) { *info = -7; } if (*info != 0) { i__1 = -(*info); xerbla_("CGESV ", &i__1); return 0; } /* Compute the LU factorization of A. */ cgetrf_(n, n, &a[a_offset], lda, &ipiv[1], info); if (*info == 0) { /* Solve the system A*X = B, overwriting B with X. */ cgetrs_("No transpose", n, nrhs, &a[a_offset], lda, &ipiv[1], &b[ b_offset], ldb, info); } return 0; /* End of CGESV */ } /* cgesv_ */ /* Subroutine */ int cgetf2_(integer *m, integer *n, complex *a, integer *lda, integer *ipiv, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3; complex q__1; /* Builtin functions */ void c_div(complex *, complex *, complex *); /* Local variables */ static integer j, jp; extern /* Subroutine */ int cscal_(integer *, complex *, complex *, integer *), cgeru_(integer *, integer *, complex *, complex *, integer *, complex *, integer *, complex *, integer *), cswap_( integer *, complex *, integer *, complex *, integer *); extern integer icamax_(integer *, complex *, integer *); extern /* Subroutine */ int xerbla_(char *, integer *); /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University September 30, 1994 Purpose ======= CGETF2 computes an LU factorization of a general m-by-n matrix A using partial pivoting with row interchanges. The factorization has the form A = P * L * U where P is a permutation matrix, L is lower triangular with unit diagonal elements (lower trapezoidal if m > n), and U is upper triangular (upper trapezoidal if m < n). This is the right-looking Level 2 BLAS version of the algorithm. Arguments ========= M (input) INTEGER The number of rows of the matrix A. M >= 0. N (input) INTEGER The number of columns of the matrix A. N >= 0. A (input/output) COMPLEX array, dimension (LDA,N) On entry, the m by n matrix to be factored. On exit, the factors L and U from the factorization A = P*L*U; the unit diagonal elements of L are not stored. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,M). IPIV (output) INTEGER array, dimension (min(M,N)) The pivot indices; for 1 <= i <= min(M,N), row i of the matrix was interchanged with row IPIV(i). INFO (output) INTEGER = 0: successful exit < 0: if INFO = -k, the k-th argument had an illegal value > 0: if INFO = k, U(k,k) is exactly zero. The factorization has been completed, but the factor U is exactly singular, and division by zero will occur if it is used to solve a system of equations. ===================================================================== Test the input parameters. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --ipiv; /* Function Body */ *info = 0; if (*m < 0) { *info = -1; } else if (*n < 0) { *info = -2; } else if (*lda < max(1,*m)) { *info = -4; } if (*info != 0) { i__1 = -(*info); xerbla_("CGETF2", &i__1); return 0; } /* Quick return if possible */ if ((*m == 0) || (*n == 0)) { return 0; } i__1 = min(*m,*n); for (j = 1; j <= i__1; ++j) { /* Find pivot and test for singularity. */ i__2 = *m - j + 1; jp = j - 1 + icamax_(&i__2, &a[j + j * a_dim1], &c__1); ipiv[j] = jp; i__2 = jp + j * a_dim1; if ((a[i__2].r != 0.f) || (a[i__2].i != 0.f)) { /* Apply the interchange to columns 1:N. */ if (jp != j) { cswap_(n, &a[j + a_dim1], lda, &a[jp + a_dim1], lda); } /* Compute elements J+1:M of J-th column. */ if (j < *m) { i__2 = *m - j; c_div(&q__1, &c_b56, &a[j + j * a_dim1]); cscal_(&i__2, &q__1, &a[j + 1 + j * a_dim1], &c__1); } } else if (*info == 0) { *info = j; } if (j < min(*m,*n)) { /* Update trailing submatrix. */ i__2 = *m - j; i__3 = *n - j; q__1.r = -1.f, q__1.i = -0.f; cgeru_(&i__2, &i__3, &q__1, &a[j + 1 + j * a_dim1], &c__1, &a[j + (j + 1) * a_dim1], lda, &a[j + 1 + (j + 1) * a_dim1], lda) ; } /* L10: */ } return 0; /* End of CGETF2 */ } /* cgetf2_ */ /* Subroutine */ int cgetrf_(integer *m, integer *n, complex *a, integer *lda, integer *ipiv, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3, i__4, i__5; complex q__1; /* Local variables */ static integer i__, j, jb, nb; extern /* Subroutine */ int cgemm_(char *, char *, integer *, integer *, integer *, complex *, complex *, integer *, complex *, integer *, complex *, complex *, integer *); static integer iinfo; extern /* Subroutine */ int ctrsm_(char *, char *, char *, char *, integer *, integer *, complex *, complex *, integer *, complex *, integer *), cgetf2_(integer *, integer *, complex *, integer *, integer *, integer *), xerbla_( char *, integer *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); extern /* Subroutine */ int claswp_(integer *, complex *, integer *, integer *, integer *, integer *, integer *); /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University September 30, 1994 Purpose ======= CGETRF computes an LU factorization of a general M-by-N matrix A using partial pivoting with row interchanges. The factorization has the form A = P * L * U where P is a permutation matrix, L is lower triangular with unit diagonal elements (lower trapezoidal if m > n), and U is upper triangular (upper trapezoidal if m < n). This is the right-looking Level 3 BLAS version of the algorithm. Arguments ========= M (input) INTEGER The number of rows of the matrix A. M >= 0. N (input) INTEGER The number of columns of the matrix A. N >= 0. A (input/output) COMPLEX array, dimension (LDA,N) On entry, the M-by-N matrix to be factored. On exit, the factors L and U from the factorization A = P*L*U; the unit diagonal elements of L are not stored. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,M). IPIV (output) INTEGER array, dimension (min(M,N)) The pivot indices; for 1 <= i <= min(M,N), row i of the matrix was interchanged with row IPIV(i). INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value > 0: if INFO = i, U(i,i) is exactly zero. The factorization has been completed, but the factor U is exactly singular, and division by zero will occur if it is used to solve a system of equations. ===================================================================== Test the input parameters. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --ipiv; /* Function Body */ *info = 0; if (*m < 0) { *info = -1; } else if (*n < 0) { *info = -2; } else if (*lda < max(1,*m)) { *info = -4; } if (*info != 0) { i__1 = -(*info); xerbla_("CGETRF", &i__1); return 0; } /* Quick return if possible */ if ((*m == 0) || (*n == 0)) { return 0; } /* Determine the block size for this environment. */ nb = ilaenv_(&c__1, "CGETRF", " ", m, n, &c_n1, &c_n1, (ftnlen)6, (ftnlen) 1); if ((nb <= 1) || (nb >= min(*m,*n))) { /* Use unblocked code. */ cgetf2_(m, n, &a[a_offset], lda, &ipiv[1], info); } else { /* Use blocked code. */ i__1 = min(*m,*n); i__2 = nb; for (j = 1; i__2 < 0 ? j >= i__1 : j <= i__1; j += i__2) { /* Computing MIN */ i__3 = min(*m,*n) - j + 1; jb = min(i__3,nb); /* Factor diagonal and subdiagonal blocks and test for exact singularity. */ i__3 = *m - j + 1; cgetf2_(&i__3, &jb, &a[j + j * a_dim1], lda, &ipiv[j], &iinfo); /* Adjust INFO and the pivot indices. */ if (*info == 0 && iinfo > 0) { *info = iinfo + j - 1; } /* Computing MIN */ i__4 = *m, i__5 = j + jb - 1; i__3 = min(i__4,i__5); for (i__ = j; i__ <= i__3; ++i__) { ipiv[i__] = j - 1 + ipiv[i__]; /* L10: */ } /* Apply interchanges to columns 1:J-1. */ i__3 = j - 1; i__4 = j + jb - 1; claswp_(&i__3, &a[a_offset], lda, &j, &i__4, &ipiv[1], &c__1); if (j + jb <= *n) { /* Apply interchanges to columns J+JB:N. */ i__3 = *n - j - jb + 1; i__4 = j + jb - 1; claswp_(&i__3, &a[(j + jb) * a_dim1 + 1], lda, &j, &i__4, & ipiv[1], &c__1); /* Compute block row of U. */ i__3 = *n - j - jb + 1; ctrsm_("Left", "Lower", "No transpose", "Unit", &jb, &i__3, & c_b56, &a[j + j * a_dim1], lda, &a[j + (j + jb) * a_dim1], lda); if (j + jb <= *m) { /* Update trailing submatrix. */ i__3 = *m - j - jb + 1; i__4 = *n - j - jb + 1; q__1.r = -1.f, q__1.i = -0.f; cgemm_("No transpose", "No transpose", &i__3, &i__4, &jb, &q__1, &a[j + jb + j * a_dim1], lda, &a[j + (j + jb) * a_dim1], lda, &c_b56, &a[j + jb + (j + jb) * a_dim1], lda); } } /* L20: */ } } return 0; /* End of CGETRF */ } /* cgetrf_ */ /* Subroutine */ int cgetrs_(char *trans, integer *n, integer *nrhs, complex * a, integer *lda, integer *ipiv, complex *b, integer *ldb, integer * info) { /* System generated locals */ integer a_dim1, a_offset, b_dim1, b_offset, i__1; /* Local variables */ extern logical lsame_(char *, char *); extern /* Subroutine */ int ctrsm_(char *, char *, char *, char *, integer *, integer *, complex *, complex *, integer *, complex *, integer *), xerbla_(char *, integer *), claswp_(integer *, complex *, integer *, integer *, integer *, integer *, integer *); static logical notran; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University September 30, 1994 Purpose ======= CGETRS solves a system of linear equations A * X = B, A**T * X = B, or A**H * X = B with a general N-by-N matrix A using the LU factorization computed by CGETRF. Arguments ========= TRANS (input) CHARACTER*1 Specifies the form of the system of equations: = 'N': A * X = B (No transpose) = 'T': A**T * X = B (Transpose) = 'C': A**H * X = B (Conjugate transpose) N (input) INTEGER The order of the matrix A. N >= 0. NRHS (input) INTEGER The number of right hand sides, i.e., the number of columns of the matrix B. NRHS >= 0. A (input) COMPLEX array, dimension (LDA,N) The factors L and U from the factorization A = P*L*U as computed by CGETRF. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,N). IPIV (input) INTEGER array, dimension (N) The pivot indices from CGETRF; for 1<=i<=N, row i of the matrix was interchanged with row IPIV(i). B (input/output) COMPLEX array, dimension (LDB,NRHS) On entry, the right hand side matrix B. On exit, the solution matrix X. LDB (input) INTEGER The leading dimension of the array B. LDB >= max(1,N). INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value ===================================================================== Test the input parameters. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --ipiv; b_dim1 = *ldb; b_offset = 1 + b_dim1; b -= b_offset; /* Function Body */ *info = 0; notran = lsame_(trans, "N"); if (! notran && ! lsame_(trans, "T") && ! lsame_( trans, "C")) { *info = -1; } else if (*n < 0) { *info = -2; } else if (*nrhs < 0) { *info = -3; } else if (*lda < max(1,*n)) { *info = -5; } else if (*ldb < max(1,*n)) { *info = -8; } if (*info != 0) { i__1 = -(*info); xerbla_("CGETRS", &i__1); return 0; } /* Quick return if possible */ if ((*n == 0) || (*nrhs == 0)) { return 0; } if (notran) { /* Solve A * X = B. Apply row interchanges to the right hand sides. */ claswp_(nrhs, &b[b_offset], ldb, &c__1, n, &ipiv[1], &c__1); /* Solve L*X = B, overwriting B with X. */ ctrsm_("Left", "Lower", "No transpose", "Unit", n, nrhs, &c_b56, &a[ a_offset], lda, &b[b_offset], ldb); /* Solve U*X = B, overwriting B with X. */ ctrsm_("Left", "Upper", "No transpose", "Non-unit", n, nrhs, &c_b56, & a[a_offset], lda, &b[b_offset], ldb); } else { /* Solve A**T * X = B or A**H * X = B. Solve U'*X = B, overwriting B with X. */ ctrsm_("Left", "Upper", trans, "Non-unit", n, nrhs, &c_b56, &a[ a_offset], lda, &b[b_offset], ldb); /* Solve L'*X = B, overwriting B with X. */ ctrsm_("Left", "Lower", trans, "Unit", n, nrhs, &c_b56, &a[a_offset], lda, &b[b_offset], ldb); /* Apply row interchanges to the solution vectors. */ claswp_(nrhs, &b[b_offset], ldb, &c__1, n, &ipiv[1], &c_n1); } return 0; /* End of CGETRS */ } /* cgetrs_ */ /* Subroutine */ int cheevd_(char *jobz, char *uplo, integer *n, complex *a, integer *lda, real *w, complex *work, integer *lwork, real *rwork, integer *lrwork, integer *iwork, integer *liwork, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3, i__4; real r__1, r__2; /* Builtin functions */ double sqrt(doublereal); /* Local variables */ static real eps; static integer inde; static real anrm; static integer imax; static real rmin, rmax; static integer lopt; static real sigma; extern logical lsame_(char *, char *); static integer iinfo; extern /* Subroutine */ int sscal_(integer *, real *, real *, integer *); static integer lwmin, liopt; static logical lower; static integer llrwk, lropt; static logical wantz; static integer indwk2, llwrk2; extern doublereal clanhe_(char *, char *, integer *, complex *, integer *, real *); static integer iscale; extern /* Subroutine */ int clascl_(char *, integer *, integer *, real *, real *, integer *, integer *, complex *, integer *, integer *), cstedc_(char *, integer *, real *, real *, complex *, integer *, complex *, integer *, real *, integer *, integer *, integer *, integer *); extern doublereal slamch_(char *); extern /* Subroutine */ int chetrd_(char *, integer *, complex *, integer *, real *, real *, complex *, complex *, integer *, integer *), clacpy_(char *, integer *, integer *, complex *, integer *, complex *, integer *); static real safmin; extern /* Subroutine */ int xerbla_(char *, integer *); static real bignum; static integer indtau, indrwk, indwrk, liwmin; extern /* Subroutine */ int ssterf_(integer *, real *, real *, integer *); static integer lrwmin; extern /* Subroutine */ int cunmtr_(char *, char *, char *, integer *, integer *, complex *, integer *, complex *, complex *, integer *, complex *, integer *, integer *); static integer llwork; static real smlnum; static logical lquery; /* -- LAPACK driver routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= CHEEVD computes all eigenvalues and, optionally, eigenvectors of a complex Hermitian matrix A. If eigenvectors are desired, it uses a divide and conquer algorithm. The divide and conquer algorithm makes very mild assumptions about floating point arithmetic. It will work on machines with a guard digit in add/subtract, or on those binary machines without guard digits which subtract like the Cray X-MP, Cray Y-MP, Cray C-90, or Cray-2. It could conceivably fail on hexadecimal or decimal machines without guard digits, but we know of none. Arguments ========= JOBZ (input) CHARACTER*1 = 'N': Compute eigenvalues only; = 'V': Compute eigenvalues and eigenvectors. UPLO (input) CHARACTER*1 = 'U': Upper triangle of A is stored; = 'L': Lower triangle of A is stored. N (input) INTEGER The order of the matrix A. N >= 0. A (input/output) COMPLEX 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. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,N). W (output) REAL array, dimension (N) If INFO = 0, the eigenvalues in ascending order. WORK (workspace/output) COMPLEX array, dimension (LWORK) On exit, if INFO = 0, WORK(1) returns the optimal LWORK. LWORK (input) INTEGER The length of the array WORK. If N <= 1, LWORK must be at least 1. If JOBZ = 'N' and N > 1, LWORK must be at least N + 1. If JOBZ = 'V' and N > 1, LWORK must be at least 2*N + N**2. If LWORK = -1, then a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued by XERBLA. RWORK (workspace/output) REAL array, dimension (LRWORK) On exit, if INFO = 0, RWORK(1) returns the optimal LRWORK. LRWORK (input) INTEGER The dimension of the array RWORK. If N <= 1, LRWORK must be at least 1. If JOBZ = 'N' and N > 1, LRWORK must be at least N. If JOBZ = 'V' and N > 1, LRWORK must be at least 1 + 5*N + 2*N**2. If LRWORK = -1, then a workspace query is assumed; the routine only calculates the optimal size of the RWORK array, returns this value as the first entry of the RWORK array, and no error message related to LRWORK is issued by XERBLA. IWORK (workspace/output) INTEGER array, dimension (LIWORK) On exit, if INFO = 0, IWORK(1) returns the optimal LIWORK. LIWORK (input) INTEGER The dimension of the array IWORK. If N <= 1, LIWORK must be at least 1. If JOBZ = 'N' and N > 1, LIWORK must be at least 1. If JOBZ = 'V' and N > 1, LIWORK must be at least 3 + 5*N. If LIWORK = -1, then a workspace query is assumed; the routine only calculates the optimal size of the IWORK array, returns this value as the first entry of the IWORK array, and no error message related to LIWORK is issued by XERBLA. 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. Further Details =============== Based on contributions by Jeff Rutter, Computer Science Division, University of California at Berkeley, USA ===================================================================== Test the input parameters. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --w; --work; --rwork; --iwork; /* Function Body */ wantz = lsame_(jobz, "V"); lower = lsame_(uplo, "L"); lquery = ((*lwork == -1) || (*lrwork == -1)) || (*liwork == -1); *info = 0; if (*n <= 1) { lwmin = 1; lrwmin = 1; liwmin = 1; lopt = lwmin; lropt = lrwmin; liopt = liwmin; } else { if (wantz) { lwmin = ((*n) << (1)) + *n * *n; /* Computing 2nd power */ i__1 = *n; lrwmin = *n * 5 + 1 + ((i__1 * i__1) << (1)); liwmin = *n * 5 + 3; } else { lwmin = *n + 1; lrwmin = *n; liwmin = 1; } lopt = lwmin; lropt = lrwmin; liopt = liwmin; } if (! ((wantz) || (lsame_(jobz, "N")))) { *info = -1; } else if (! ((lower) || (lsame_(uplo, "U")))) { *info = -2; } else if (*n < 0) { *info = -3; } else if (*lda < max(1,*n)) { *info = -5; } else if (*lwork < lwmin && ! lquery) { *info = -8; } else if (*lrwork < lrwmin && ! lquery) { *info = -10; } else if (*liwork < liwmin && ! lquery) { *info = -12; } if (*info == 0) { work[1].r = (real) lopt, work[1].i = 0.f; rwork[1] = (real) lropt; iwork[1] = liopt; } if (*info != 0) { i__1 = -(*info); xerbla_("CHEEVD", &i__1); return 0; } else if (lquery) { return 0; } /* Quick return if possible */ if (*n == 0) { return 0; } if (*n == 1) { i__1 = a_dim1 + 1; w[1] = a[i__1].r; if (wantz) { i__1 = a_dim1 + 1; a[i__1].r = 1.f, a[i__1].i = 0.f; } return 0; } /* Get machine constants. */ safmin = slamch_("Safe minimum"); eps = slamch_("Precision"); smlnum = safmin / eps; bignum = 1.f / smlnum; rmin = sqrt(smlnum); rmax = sqrt(bignum); /* Scale matrix to allowable range, if necessary. */ anrm = clanhe_("M", uplo, n, &a[a_offset], lda, &rwork[1]); iscale = 0; if (anrm > 0.f && anrm < rmin) { iscale = 1; sigma = rmin / anrm; } else if (anrm > rmax) { iscale = 1; sigma = rmax / anrm; } if (iscale == 1) { clascl_(uplo, &c__0, &c__0, &c_b1011, &sigma, n, n, &a[a_offset], lda, info); } /* Call CHETRD to reduce Hermitian matrix to tridiagonal form. */ inde = 1; indtau = 1; indwrk = indtau + *n; indrwk = inde + *n; indwk2 = indwrk + *n * *n; llwork = *lwork - indwrk + 1; llwrk2 = *lwork - indwk2 + 1; llrwk = *lrwork - indrwk + 1; chetrd_(uplo, n, &a[a_offset], lda, &w[1], &rwork[inde], &work[indtau], & work[indwrk], &llwork, &iinfo); /* Computing MAX */ i__1 = indwrk; r__1 = (real) lopt, r__2 = (real) (*n) + work[i__1].r; lopt = dmax(r__1,r__2); /* For eigenvalues only, call SSTERF. For eigenvectors, first call CSTEDC to generate the eigenvector matrix, WORK(INDWRK), of the tridiagonal matrix, then call CUNMTR to multiply it to the Householder transformations represented as Householder vectors in A. */ if (! wantz) { ssterf_(n, &w[1], &rwork[inde], info); } else { cstedc_("I", n, &w[1], &rwork[inde], &work[indwrk], n, &work[indwk2], &llwrk2, &rwork[indrwk], &llrwk, &iwork[1], liwork, info); cunmtr_("L", uplo, "N", n, n, &a[a_offset], lda, &work[indtau], &work[ indwrk], n, &work[indwk2], &llwrk2, &iinfo); clacpy_("A", n, n, &work[indwrk], n, &a[a_offset], lda); /* Computing MAX Computing 2nd power */ i__3 = *n; i__4 = indwk2; i__1 = lopt, i__2 = *n + i__3 * i__3 + (integer) work[i__4].r; lopt = max(i__1,i__2); } /* If matrix was scaled, then rescale eigenvalues appropriately. */ if (iscale == 1) { if (*info == 0) { imax = *n; } else { imax = *info - 1; } r__1 = 1.f / sigma; sscal_(&imax, &r__1, &w[1], &c__1); } work[1].r = (real) lopt, work[1].i = 0.f; rwork[1] = (real) lropt; iwork[1] = liopt; return 0; /* End of CHEEVD */ } /* cheevd_ */ /* Subroutine */ int chetd2_(char *uplo, integer *n, complex *a, integer *lda, real *d__, real *e, complex *tau, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3; real r__1; complex q__1, q__2, q__3, q__4; /* Local variables */ static integer i__; static complex taui; extern /* Subroutine */ int cher2_(char *, integer *, complex *, complex * , integer *, complex *, integer *, complex *, integer *); static complex alpha; extern /* Complex */ VOID cdotc_(complex *, integer *, complex *, integer *, complex *, integer *); extern logical lsame_(char *, char *); extern /* Subroutine */ int chemv_(char *, integer *, complex *, complex * , integer *, complex *, integer *, complex *, complex *, integer * ), caxpy_(integer *, complex *, complex *, integer *, complex *, integer *); static logical upper; extern /* Subroutine */ int clarfg_(integer *, complex *, complex *, integer *, complex *), xerbla_(char *, integer *); /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University October 31, 1999 Purpose ======= CHETD2 reduces a complex Hermitian matrix A to real symmetric tridiagonal form T by a unitary similarity transformation: Q' * A * Q = T. Arguments ========= UPLO (input) CHARACTER*1 Specifies whether the upper or lower triangular part of the Hermitian matrix A is stored: = 'U': Upper triangular = 'L': Lower triangular N (input) INTEGER The order of the matrix A. N >= 0. A (input/output) COMPLEX 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, and the strictly lower triangular part of A is not referenced. If UPLO = 'L', the leading n-by-n lower triangular part of A contains the lower triangular part of the matrix A, and the strictly upper triangular part of A is not referenced. On exit, if UPLO = 'U', the diagonal and first superdiagonal of A are overwritten by the corresponding elements of the tridiagonal matrix T, and the elements above the first superdiagonal, with the array TAU, represent the unitary matrix Q as a product of elementary reflectors; if UPLO = 'L', the diagonal and first subdiagonal of A are over- written by the corresponding elements of the tridiagonal matrix T, and the elements below the first subdiagonal, with the array TAU, represent the unitary matrix Q as a product of elementary reflectors. See Further Details. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,N). D (output) REAL array, dimension (N) The diagonal elements of the tridiagonal matrix T: D(i) = A(i,i). E (output) REAL array, dimension (N-1) The off-diagonal elements of the tridiagonal matrix T: E(i) = A(i,i+1) if UPLO = 'U', E(i) = A(i+1,i) if UPLO = 'L'. TAU (output) COMPLEX array, dimension (N-1) The scalar factors of the elementary reflectors (see Further Details). INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value. Further Details =============== If UPLO = 'U', the matrix Q is represented as a product of elementary reflectors Q = H(n-1) . . . H(2) H(1). Each H(i) has the form H(i) = I - tau * v * v' where tau is a complex scalar, and v is a complex vector with v(i+1:n) = 0 and v(i) = 1; v(1:i-1) is stored on exit in A(1:i-1,i+1), and tau in TAU(i). If UPLO = 'L', the matrix Q is represented as a product of elementary reflectors Q = H(1) H(2) . . . H(n-1). Each H(i) has the form H(i) = I - tau * v * v' where tau is a complex scalar, and v is a complex vector with v(1:i) = 0 and v(i+1) = 1; v(i+2:n) is stored on exit in A(i+2:n,i), and tau in TAU(i). The contents of A on exit are illustrated by the following examples with n = 5: if UPLO = 'U': if UPLO = 'L': ( d e v2 v3 v4 ) ( d ) ( d e v3 v4 ) ( e d ) ( d e v4 ) ( v1 e d ) ( d e ) ( v1 v2 e d ) ( d ) ( v1 v2 v3 e d ) where d and e denote diagonal and off-diagonal elements of T, and vi denotes an element of the vector defining H(i). ===================================================================== Test the input parameters */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --d__; --e; --tau; /* Function Body */ *info = 0; upper = lsame_(uplo, "U"); if (! upper && ! lsame_(uplo, "L")) { *info = -1; } else if (*n < 0) { *info = -2; } else if (*lda < max(1,*n)) { *info = -4; } if (*info != 0) { i__1 = -(*info); xerbla_("CHETD2", &i__1); return 0; } /* Quick return if possible */ if (*n <= 0) { return 0; } if (upper) { /* Reduce the upper triangle of A */ i__1 = *n + *n * a_dim1; i__2 = *n + *n * a_dim1; r__1 = a[i__2].r; a[i__1].r = r__1, a[i__1].i = 0.f; for (i__ = *n - 1; i__ >= 1; --i__) { /* Generate elementary reflector H(i) = I - tau * v * v' to annihilate A(1:i-1,i+1) */ i__1 = i__ + (i__ + 1) * a_dim1; alpha.r = a[i__1].r, alpha.i = a[i__1].i; clarfg_(&i__, &alpha, &a[(i__ + 1) * a_dim1 + 1], &c__1, &taui); i__1 = i__; e[i__1] = alpha.r; if ((taui.r != 0.f) || (taui.i != 0.f)) { /* Apply H(i) from both sides to A(1:i,1:i) */ i__1 = i__ + (i__ + 1) * a_dim1; a[i__1].r = 1.f, a[i__1].i = 0.f; /* Compute x := tau * A * v storing x in TAU(1:i) */ chemv_(uplo, &i__, &taui, &a[a_offset], lda, &a[(i__ + 1) * a_dim1 + 1], &c__1, &c_b55, &tau[1], &c__1) ; /* Compute w := x - 1/2 * tau * (x'*v) * v */ q__3.r = -.5f, q__3.i = -0.f; q__2.r = q__3.r * taui.r - q__3.i * taui.i, q__2.i = q__3.r * taui.i + q__3.i * taui.r; cdotc_(&q__4, &i__, &tau[1], &c__1, &a[(i__ + 1) * a_dim1 + 1] , &c__1); q__1.r = q__2.r * q__4.r - q__2.i * q__4.i, q__1.i = q__2.r * q__4.i + q__2.i * q__4.r; alpha.r = q__1.r, alpha.i = q__1.i; caxpy_(&i__, &alpha, &a[(i__ + 1) * a_dim1 + 1], &c__1, &tau[ 1], &c__1); /* Apply the transformation as a rank-2 update: A := A - v * w' - w * v' */ q__1.r = -1.f, q__1.i = -0.f; cher2_(uplo, &i__, &q__1, &a[(i__ + 1) * a_dim1 + 1], &c__1, & tau[1], &c__1, &a[a_offset], lda); } else { i__1 = i__ + i__ * a_dim1; i__2 = i__ + i__ * a_dim1; r__1 = a[i__2].r; a[i__1].r = r__1, a[i__1].i = 0.f; } i__1 = i__ + (i__ + 1) * a_dim1; i__2 = i__; a[i__1].r = e[i__2], a[i__1].i = 0.f; i__1 = i__ + 1; i__2 = i__ + 1 + (i__ + 1) * a_dim1; d__[i__1] = a[i__2].r; i__1 = i__; tau[i__1].r = taui.r, tau[i__1].i = taui.i; /* L10: */ } i__1 = a_dim1 + 1; d__[1] = a[i__1].r; } else { /* Reduce the lower triangle of A */ i__1 = a_dim1 + 1; i__2 = a_dim1 + 1; r__1 = a[i__2].r; a[i__1].r = r__1, a[i__1].i = 0.f; i__1 = *n - 1; for (i__ = 1; i__ <= i__1; ++i__) { /* Generate elementary reflector H(i) = I - tau * v * v' to annihilate A(i+2:n,i) */ i__2 = i__ + 1 + i__ * a_dim1; alpha.r = a[i__2].r, alpha.i = a[i__2].i; i__2 = *n - i__; /* Computing MIN */ i__3 = i__ + 2; clarfg_(&i__2, &alpha, &a[min(i__3,*n) + i__ * a_dim1], &c__1, & taui); i__2 = i__; e[i__2] = alpha.r; if ((taui.r != 0.f) || (taui.i != 0.f)) { /* Apply H(i) from both sides to A(i+1:n,i+1:n) */ i__2 = i__ + 1 + i__ * a_dim1; a[i__2].r = 1.f, a[i__2].i = 0.f; /* Compute x := tau * A * v storing y in TAU(i:n-1) */ i__2 = *n - i__; chemv_(uplo, &i__2, &taui, &a[i__ + 1 + (i__ + 1) * a_dim1], lda, &a[i__ + 1 + i__ * a_dim1], &c__1, &c_b55, &tau[ i__], &c__1); /* Compute w := x - 1/2 * tau * (x'*v) * v */ q__3.r = -.5f, q__3.i = -0.f; q__2.r = q__3.r * taui.r - q__3.i * taui.i, q__2.i = q__3.r * taui.i + q__3.i * taui.r; i__2 = *n - i__; cdotc_(&q__4, &i__2, &tau[i__], &c__1, &a[i__ + 1 + i__ * a_dim1], &c__1); q__1.r = q__2.r * q__4.r - q__2.i * q__4.i, q__1.i = q__2.r * q__4.i + q__2.i * q__4.r; alpha.r = q__1.r, alpha.i = q__1.i; i__2 = *n - i__; caxpy_(&i__2, &alpha, &a[i__ + 1 + i__ * a_dim1], &c__1, &tau[ i__], &c__1); /* Apply the transformation as a rank-2 update: A := A - v * w' - w * v' */ i__2 = *n - i__; q__1.r = -1.f, q__1.i = -0.f; cher2_(uplo, &i__2, &q__1, &a[i__ + 1 + i__ * a_dim1], &c__1, &tau[i__], &c__1, &a[i__ + 1 + (i__ + 1) * a_dim1], lda); } else { i__2 = i__ + 1 + (i__ + 1) * a_dim1; i__3 = i__ + 1 + (i__ + 1) * a_dim1; r__1 = a[i__3].r; a[i__2].r = r__1, a[i__2].i = 0.f; } i__2 = i__ + 1 + i__ * a_dim1; i__3 = i__; a[i__2].r = e[i__3], a[i__2].i = 0.f; i__2 = i__; i__3 = i__ + i__ * a_dim1; d__[i__2] = a[i__3].r; i__2 = i__; tau[i__2].r = taui.r, tau[i__2].i = taui.i; /* L20: */ } i__1 = *n; i__2 = *n + *n * a_dim1; d__[i__1] = a[i__2].r; } return 0; /* End of CHETD2 */ } /* chetd2_ */ /* Subroutine */ int chetrd_(char *uplo, integer *n, complex *a, integer *lda, real *d__, real *e, complex *tau, complex *work, integer *lwork, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3, i__4, i__5; complex q__1; /* Local variables */ static integer i__, j, nb, kk, nx, iws; extern logical lsame_(char *, char *); static integer nbmin, iinfo; static logical upper; extern /* Subroutine */ int chetd2_(char *, integer *, complex *, integer *, real *, real *, complex *, integer *), cher2k_(char *, char *, integer *, integer *, complex *, complex *, integer *, complex *, integer *, real *, complex *, integer *), clatrd_(char *, integer *, integer *, complex *, integer *, real *, complex *, complex *, integer *), xerbla_(char *, integer *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); static integer ldwork, lwkopt; static logical lquery; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= CHETRD reduces a complex Hermitian matrix A to real symmetric tridiagonal form T by a unitary similarity transformation: Q**H * A * Q = T. Arguments ========= UPLO (input) CHARACTER*1 = 'U': Upper triangle of A is stored; = 'L': Lower triangle of A is stored. N (input) INTEGER The order of the matrix A. N >= 0. A (input/output) COMPLEX 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, and the strictly lower triangular part of A is not referenced. If UPLO = 'L', the leading N-by-N lower triangular part of A contains the lower triangular part of the matrix A, and the strictly upper triangular part of A is not referenced. On exit, if UPLO = 'U', the diagonal and first superdiagonal of A are overwritten by the corresponding elements of the tridiagonal matrix T, and the elements above the first superdiagonal, with the array TAU, represent the unitary matrix Q as a product of elementary reflectors; if UPLO = 'L', the diagonal and first subdiagonal of A are over- written by the corresponding elements of the tridiagonal matrix T, and the elements below the first subdiagonal, with the array TAU, represent the unitary matrix Q as a product of elementary reflectors. See Further Details. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,N). D (output) REAL array, dimension (N) The diagonal elements of the tridiagonal matrix T: D(i) = A(i,i). E (output) REAL array, dimension (N-1) The off-diagonal elements of the tridiagonal matrix T: E(i) = A(i,i+1) if UPLO = 'U', E(i) = A(i+1,i) if UPLO = 'L'. TAU (output) COMPLEX array, dimension (N-1) The scalar factors of the elementary reflectors (see Further Details). WORK (workspace/output) COMPLEX array, dimension (LWORK) On exit, if INFO = 0, WORK(1) returns the optimal LWORK. LWORK (input) INTEGER The dimension of the array WORK. LWORK >= 1. For optimum performance LWORK >= N*NB, where NB is the optimal blocksize. If LWORK = -1, then a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued by XERBLA. INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value Further Details =============== If UPLO = 'U', the matrix Q is represented as a product of elementary reflectors Q = H(n-1) . . . H(2) H(1). Each H(i) has the form H(i) = I - tau * v * v' where tau is a complex scalar, and v is a complex vector with v(i+1:n) = 0 and v(i) = 1; v(1:i-1) is stored on exit in A(1:i-1,i+1), and tau in TAU(i). If UPLO = 'L', the matrix Q is represented as a product of elementary reflectors Q = H(1) H(2) . . . H(n-1). Each H(i) has the form H(i) = I - tau * v * v' where tau is a complex scalar, and v is a complex vector with v(1:i) = 0 and v(i+1) = 1; v(i+2:n) is stored on exit in A(i+2:n,i), and tau in TAU(i). The contents of A on exit are illustrated by the following examples with n = 5: if UPLO = 'U': if UPLO = 'L': ( d e v2 v3 v4 ) ( d ) ( d e v3 v4 ) ( e d ) ( d e v4 ) ( v1 e d ) ( d e ) ( v1 v2 e d ) ( d ) ( v1 v2 v3 e d ) where d and e denote diagonal and off-diagonal elements of T, and vi denotes an element of the vector defining H(i). ===================================================================== Test the input parameters */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --d__; --e; --tau; --work; /* Function Body */ *info = 0; upper = lsame_(uplo, "U"); lquery = *lwork == -1; if (! upper && ! lsame_(uplo, "L")) { *info = -1; } else if (*n < 0) { *info = -2; } else if (*lda < max(1,*n)) { *info = -4; } else if (*lwork < 1 && ! lquery) { *info = -9; } if (*info == 0) { /* Determine the block size. */ nb = ilaenv_(&c__1, "CHETRD", uplo, n, &c_n1, &c_n1, &c_n1, (ftnlen)6, (ftnlen)1); lwkopt = *n * nb; work[1].r = (real) lwkopt, work[1].i = 0.f; } if (*info != 0) { i__1 = -(*info); xerbla_("CHETRD", &i__1); return 0; } else if (lquery) { return 0; } /* Quick return if possible */ if (*n == 0) { work[1].r = 1.f, work[1].i = 0.f; return 0; } nx = *n; iws = 1; if (nb > 1 && nb < *n) { /* Determine when to cross over from blocked to unblocked code (last block is always handled by unblocked code). Computing MAX */ i__1 = nb, i__2 = ilaenv_(&c__3, "CHETRD", uplo, n, &c_n1, &c_n1, & c_n1, (ftnlen)6, (ftnlen)1); nx = max(i__1,i__2); if (nx < *n) { /* Determine if workspace is large enough for blocked code. */ ldwork = *n; iws = ldwork * nb; if (*lwork < iws) { /* Not enough workspace to use optimal NB: determine the minimum value of NB, and reduce NB or force use of unblocked code by setting NX = N. Computing MAX */ i__1 = *lwork / ldwork; nb = max(i__1,1); nbmin = ilaenv_(&c__2, "CHETRD", uplo, n, &c_n1, &c_n1, &c_n1, (ftnlen)6, (ftnlen)1); if (nb < nbmin) { nx = *n; } } } else { nx = *n; } } else { nb = 1; } if (upper) { /* Reduce the upper triangle of A. Columns 1:kk are handled by the unblocked method. */ kk = *n - (*n - nx + nb - 1) / nb * nb; i__1 = kk + 1; i__2 = -nb; for (i__ = *n - nb + 1; i__2 < 0 ? i__ >= i__1 : i__ <= i__1; i__ += i__2) { /* Reduce columns i:i+nb-1 to tridiagonal form and form the matrix W which is needed to update the unreduced part of the matrix */ i__3 = i__ + nb - 1; clatrd_(uplo, &i__3, &nb, &a[a_offset], lda, &e[1], &tau[1], & work[1], &ldwork); /* Update the unreduced submatrix A(1:i-1,1:i-1), using an update of the form: A := A - V*W' - W*V' */ i__3 = i__ - 1; q__1.r = -1.f, q__1.i = -0.f; cher2k_(uplo, "No transpose", &i__3, &nb, &q__1, &a[i__ * a_dim1 + 1], lda, &work[1], &ldwork, &c_b1011, &a[a_offset], lda); /* Copy superdiagonal elements back into A, and diagonal elements into D */ i__3 = i__ + nb - 1; for (j = i__; j <= i__3; ++j) { i__4 = j - 1 + j * a_dim1; i__5 = j - 1; a[i__4].r = e[i__5], a[i__4].i = 0.f; i__4 = j; i__5 = j + j * a_dim1; d__[i__4] = a[i__5].r; /* L10: */ } /* L20: */ } /* Use unblocked code to reduce the last or only block */ chetd2_(uplo, &kk, &a[a_offset], lda, &d__[1], &e[1], &tau[1], &iinfo); } else { /* Reduce the lower triangle of A */ i__2 = *n - nx; i__1 = nb; for (i__ = 1; i__1 < 0 ? i__ >= i__2 : i__ <= i__2; i__ += i__1) { /* Reduce columns i:i+nb-1 to tridiagonal form and form the matrix W which is needed to update the unreduced part of the matrix */ i__3 = *n - i__ + 1; clatrd_(uplo, &i__3, &nb, &a[i__ + i__ * a_dim1], lda, &e[i__], & tau[i__], &work[1], &ldwork); /* Update the unreduced submatrix A(i+nb:n,i+nb:n), using an update of the form: A := A - V*W' - W*V' */ i__3 = *n - i__ - nb + 1; q__1.r = -1.f, q__1.i = -0.f; cher2k_(uplo, "No transpose", &i__3, &nb, &q__1, &a[i__ + nb + i__ * a_dim1], lda, &work[nb + 1], &ldwork, &c_b1011, &a[ i__ + nb + (i__ + nb) * a_dim1], lda); /* Copy subdiagonal elements back into A, and diagonal elements into D */ i__3 = i__ + nb - 1; for (j = i__; j <= i__3; ++j) { i__4 = j + 1 + j * a_dim1; i__5 = j; a[i__4].r = e[i__5], a[i__4].i = 0.f; i__4 = j; i__5 = j + j * a_dim1; d__[i__4] = a[i__5].r; /* L30: */ } /* L40: */ } /* Use unblocked code to reduce the last or only block */ i__1 = *n - i__ + 1; chetd2_(uplo, &i__1, &a[i__ + i__ * a_dim1], lda, &d__[i__], &e[i__], &tau[i__], &iinfo); } work[1].r = (real) lwkopt, work[1].i = 0.f; return 0; /* End of CHETRD */ } /* chetrd_ */ /* Subroutine */ int chseqr_(char *job, char *compz, integer *n, integer *ilo, integer *ihi, complex *h__, integer *ldh, complex *w, complex *z__, integer *ldz, complex *work, integer *lwork, integer *info) { /* System generated locals */ address a__1[2]; integer h_dim1, h_offset, z_dim1, z_offset, i__1, i__2, i__3, i__4[2], i__5, i__6; real r__1, r__2, r__3, r__4; complex q__1; char ch__1[2]; /* Builtin functions */ double r_imag(complex *); void r_cnjg(complex *, complex *); /* Subroutine */ int s_cat(char *, char **, integer *, integer *, ftnlen); /* Local variables */ static integer i__, j, k, l; static complex s[225] /* was [15][15] */, v[16]; static integer i1, i2, ii, nh, nr, ns, nv; static complex vv[16]; static integer itn; static complex tau; static integer its; static real ulp, tst1; static integer maxb, ierr; static real unfl; static complex temp; static real ovfl; extern /* Subroutine */ int cscal_(integer *, complex *, complex *, integer *); extern logical lsame_(char *, char *); extern /* Subroutine */ int cgemv_(char *, integer *, integer *, complex * , complex *, integer *, complex *, integer *, complex *, complex * , integer *), ccopy_(integer *, complex *, integer *, complex *, integer *); static integer itemp; static real rtemp; static logical initz, wantt, wantz; static real rwork[1]; extern doublereal slapy2_(real *, real *); extern /* Subroutine */ int slabad_(real *, real *), clarfg_(integer *, complex *, complex *, integer *, complex *); extern integer icamax_(integer *, complex *, integer *); extern doublereal slamch_(char *), clanhs_(char *, integer *, complex *, integer *, real *); extern /* Subroutine */ int csscal_(integer *, real *, complex *, integer *), clahqr_(logical *, logical *, integer *, integer *, integer *, complex *, integer *, complex *, integer *, integer *, complex *, integer *, integer *), clacpy_(char *, integer *, integer *, complex *, integer *, complex *, integer *), claset_(char *, integer *, integer *, complex *, complex *, complex *, integer *), xerbla_(char *, integer *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); extern /* Subroutine */ int clarfx_(char *, integer *, integer *, complex *, complex *, complex *, integer *, complex *); static real smlnum; static logical lquery; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= CHSEQR computes the eigenvalues of a complex upper Hessenberg matrix H, and, optionally, the matrices T and Z from the Schur decomposition H = Z T Z**H, where T is an upper triangular matrix (the Schur form), and Z is the unitary matrix of Schur vectors. Optionally Z may be postmultiplied into an input unitary matrix Q, so that this routine can give the Schur factorization of a matrix A which has been reduced to the Hessenberg form H by the unitary matrix Q: A = Q*H*Q**H = (QZ)*T*(QZ)**H. Arguments ========= JOB (input) CHARACTER*1 = 'E': compute eigenvalues only; = 'S': compute eigenvalues and the Schur form T. COMPZ (input) CHARACTER*1 = 'N': no Schur vectors are computed; = 'I': Z is initialized to the unit matrix and the matrix Z of Schur vectors of H is returned; = 'V': Z must contain an unitary matrix Q on entry, and the product Q*Z is returned. N (input) INTEGER The order of the matrix H. N >= 0. ILO (input) INTEGER IHI (input) INTEGER It is assumed that H is already upper triangular in rows and columns 1:ILO-1 and IHI+1:N. ILO and IHI are normally set by a previous call to CGEBAL, and then passed to CGEHRD when the matrix output by CGEBAL is reduced to Hessenberg form. Otherwise ILO and IHI should be set to 1 and N respectively. 1 <= ILO <= IHI <= N, if N > 0; ILO=1 and IHI=0, if N=0. H (input/output) COMPLEX array, dimension (LDH,N) On entry, the upper Hessenberg matrix H. On exit, if JOB = 'S', H contains the upper triangular matrix T from the Schur decomposition (the Schur form). If JOB = 'E', the contents of H are unspecified on exit. LDH (input) INTEGER The leading dimension of the array H. LDH >= max(1,N). W (output) COMPLEX array, dimension (N) The computed eigenvalues. If JOB = 'S', the eigenvalues are stored in the same order as on the diagonal of the Schur form returned in H, with W(i) = H(i,i). Z (input/output) COMPLEX array, dimension (LDZ,N) If COMPZ = 'N': Z is not referenced. If COMPZ = 'I': on entry, Z need not be set, and on exit, Z contains the unitary matrix Z of the Schur vectors of H. If COMPZ = 'V': on entry Z must contain an N-by-N matrix Q, which is assumed to be equal to the unit matrix except for the submatrix Z(ILO:IHI,ILO:IHI); on exit Z contains Q*Z. Normally Q is the unitary matrix generated by CUNGHR after the call to CGEHRD which formed the Hessenberg matrix H. LDZ (input) INTEGER The leading dimension of the array Z. LDZ >= max(1,N) if COMPZ = 'I' or 'V'; LDZ >= 1 otherwise. WORK (workspace/output) COMPLEX array, dimension (LWORK) On exit, if INFO = 0, WORK(1) returns the optimal LWORK. LWORK (input) INTEGER The dimension of the array WORK. LWORK >= max(1,N). If LWORK = -1, then a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued by XERBLA. INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value > 0: if INFO = i, CHSEQR failed to compute all the eigenvalues in a total of 30*(IHI-ILO+1) iterations; elements 1:ilo-1 and i+1:n of W contain those eigenvalues which have been successfully computed. ===================================================================== Decode and test the input parameters */ /* Parameter adjustments */ h_dim1 = *ldh; h_offset = 1 + h_dim1; h__ -= h_offset; --w; z_dim1 = *ldz; z_offset = 1 + z_dim1; z__ -= z_offset; --work; /* Function Body */ wantt = lsame_(job, "S"); initz = lsame_(compz, "I"); wantz = (initz) || (lsame_(compz, "V")); *info = 0; i__1 = max(1,*n); work[1].r = (real) i__1, work[1].i = 0.f; lquery = *lwork == -1; if (! lsame_(job, "E") && ! wantt) { *info = -1; } else if (! lsame_(compz, "N") && ! wantz) { *info = -2; } else if (*n < 0) { *info = -3; } else if ((*ilo < 1) || (*ilo > max(1,*n))) { *info = -4; } else if ((*ihi < min(*ilo,*n)) || (*ihi > *n)) { *info = -5; } else if (*ldh < max(1,*n)) { *info = -7; } else if ((*ldz < 1) || (wantz && *ldz < max(1,*n))) { *info = -10; } else if (*lwork < max(1,*n) && ! lquery) { *info = -12; } if (*info != 0) { i__1 = -(*info); xerbla_("CHSEQR", &i__1); return 0; } else if (lquery) { return 0; } /* Initialize Z, if necessary */ if (initz) { claset_("Full", n, n, &c_b55, &c_b56, &z__[z_offset], ldz); } /* Store the eigenvalues isolated by CGEBAL. */ i__1 = *ilo - 1; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = i__; i__3 = i__ + i__ * h_dim1; w[i__2].r = h__[i__3].r, w[i__2].i = h__[i__3].i; /* L10: */ } i__1 = *n; for (i__ = *ihi + 1; i__ <= i__1; ++i__) { i__2 = i__; i__3 = i__ + i__ * h_dim1; w[i__2].r = h__[i__3].r, w[i__2].i = h__[i__3].i; /* L20: */ } /* Quick return if possible. */ if (*n == 0) { return 0; } if (*ilo == *ihi) { i__1 = *ilo; i__2 = *ilo + *ilo * h_dim1; w[i__1].r = h__[i__2].r, w[i__1].i = h__[i__2].i; return 0; } /* Set rows and columns ILO to IHI to zero below the first subdiagonal. */ i__1 = *ihi - 2; for (j = *ilo; j <= i__1; ++j) { i__2 = *n; for (i__ = j + 2; i__ <= i__2; ++i__) { i__3 = i__ + j * h_dim1; h__[i__3].r = 0.f, h__[i__3].i = 0.f; /* L30: */ } /* L40: */ } nh = *ihi - *ilo + 1; /* I1 and I2 are the indices of the first row and last column of H to which transformations must be applied. If eigenvalues only are being computed, I1 and I2 are re-set inside the main loop. */ if (wantt) { i1 = 1; i2 = *n; } else { i1 = *ilo; i2 = *ihi; } /* Ensure that the subdiagonal elements are real. */ i__1 = *ihi; for (i__ = *ilo + 1; i__ <= i__1; ++i__) { i__2 = i__ + (i__ - 1) * h_dim1; temp.r = h__[i__2].r, temp.i = h__[i__2].i; if (r_imag(&temp) != 0.f) { r__1 = temp.r; r__2 = r_imag(&temp); rtemp = slapy2_(&r__1, &r__2); i__2 = i__ + (i__ - 1) * h_dim1; h__[i__2].r = rtemp, h__[i__2].i = 0.f; q__1.r = temp.r / rtemp, q__1.i = temp.i / rtemp; temp.r = q__1.r, temp.i = q__1.i; if (i2 > i__) { i__2 = i2 - i__; r_cnjg(&q__1, &temp); cscal_(&i__2, &q__1, &h__[i__ + (i__ + 1) * h_dim1], ldh); } i__2 = i__ - i1; cscal_(&i__2, &temp, &h__[i1 + i__ * h_dim1], &c__1); if (i__ < *ihi) { i__2 = i__ + 1 + i__ * h_dim1; i__3 = i__ + 1 + i__ * h_dim1; q__1.r = temp.r * h__[i__3].r - temp.i * h__[i__3].i, q__1.i = temp.r * h__[i__3].i + temp.i * h__[i__3].r; h__[i__2].r = q__1.r, h__[i__2].i = q__1.i; } if (wantz) { cscal_(&nh, &temp, &z__[*ilo + i__ * z_dim1], &c__1); } } /* L50: */ } /* Determine the order of the multi-shift QR algorithm to be used. Writing concatenation */ i__4[0] = 1, a__1[0] = job; i__4[1] = 1, a__1[1] = compz; s_cat(ch__1, a__1, i__4, &c__2, (ftnlen)2); ns = ilaenv_(&c__4, "CHSEQR", ch__1, n, ilo, ihi, &c_n1, (ftnlen)6, ( ftnlen)2); /* Writing concatenation */ i__4[0] = 1, a__1[0] = job; i__4[1] = 1, a__1[1] = compz; s_cat(ch__1, a__1, i__4, &c__2, (ftnlen)2); maxb = ilaenv_(&c__8, "CHSEQR", ch__1, n, ilo, ihi, &c_n1, (ftnlen)6, ( ftnlen)2); if (((ns <= 1) || (ns > nh)) || (maxb >= nh)) { /* Use the standard double-shift algorithm */ clahqr_(&wantt, &wantz, n, ilo, ihi, &h__[h_offset], ldh, &w[1], ilo, ihi, &z__[z_offset], ldz, info); return 0; } maxb = max(2,maxb); /* Computing MIN */ i__1 = min(ns,maxb); ns = min(i__1,15); /* Now 1 < NS <= MAXB < NH. Set machine-dependent constants for the stopping criterion. If norm(H) <= sqrt(OVFL), overflow should not occur. */ unfl = slamch_("Safe minimum"); ovfl = 1.f / unfl; slabad_(&unfl, &ovfl); ulp = slamch_("Precision"); smlnum = unfl * (nh / ulp); /* ITN is the total number of multiple-shift QR iterations allowed. */ itn = nh * 30; /* The main loop begins here. I is the loop index and decreases from IHI to ILO in steps of at most MAXB. Each iteration of the loop works with the active submatrix in rows and columns L to I. Eigenvalues I+1 to IHI have already converged. Either L = ILO, or H(L,L-1) is negligible so that the matrix splits. */ i__ = *ihi; L60: if (i__ < *ilo) { goto L180; } /* Perform multiple-shift QR iterations on rows and columns ILO to I until a submatrix of order at most MAXB splits off at the bottom because a subdiagonal element has become negligible. */ l = *ilo; i__1 = itn; for (its = 0; its <= i__1; ++its) { /* Look for a single small subdiagonal element. */ i__2 = l + 1; for (k = i__; k >= i__2; --k) { i__3 = k - 1 + (k - 1) * h_dim1; i__5 = k + k * h_dim1; tst1 = (r__1 = h__[i__3].r, dabs(r__1)) + (r__2 = r_imag(&h__[k - 1 + (k - 1) * h_dim1]), dabs(r__2)) + ((r__3 = h__[i__5] .r, dabs(r__3)) + (r__4 = r_imag(&h__[k + k * h_dim1]), dabs(r__4))); if (tst1 == 0.f) { i__3 = i__ - l + 1; tst1 = clanhs_("1", &i__3, &h__[l + l * h_dim1], ldh, rwork); } i__3 = k + (k - 1) * h_dim1; /* Computing MAX */ r__2 = ulp * tst1; if ((r__1 = h__[i__3].r, dabs(r__1)) <= dmax(r__2,smlnum)) { goto L80; } /* L70: */ } L80: l = k; if (l > *ilo) { /* H(L,L-1) is negligible. */ i__2 = l + (l - 1) * h_dim1; h__[i__2].r = 0.f, h__[i__2].i = 0.f; } /* Exit from loop if a submatrix of order <= MAXB has split off. */ if (l >= i__ - maxb + 1) { goto L170; } /* Now the active submatrix is in rows and columns L to I. If eigenvalues only are being computed, only the active submatrix need be transformed. */ if (! wantt) { i1 = l; i2 = i__; } if ((its == 20) || (its == 30)) { /* Exceptional shifts. */ i__2 = i__; for (ii = i__ - ns + 1; ii <= i__2; ++ii) { i__3 = ii; i__5 = ii + (ii - 1) * h_dim1; i__6 = ii + ii * h_dim1; r__3 = ((r__1 = h__[i__5].r, dabs(r__1)) + (r__2 = h__[i__6] .r, dabs(r__2))) * 1.5f; w[i__3].r = r__3, w[i__3].i = 0.f; /* L90: */ } } else { /* Use eigenvalues of trailing submatrix of order NS as shifts. */ clacpy_("Full", &ns, &ns, &h__[i__ - ns + 1 + (i__ - ns + 1) * h_dim1], ldh, s, &c__15); clahqr_(&c_false, &c_false, &ns, &c__1, &ns, s, &c__15, &w[i__ - ns + 1], &c__1, &ns, &z__[z_offset], ldz, &ierr); if (ierr > 0) { /* If CLAHQR failed to compute all NS eigenvalues, use the unconverged diagonal elements as the remaining shifts. */ i__2 = ierr; for (ii = 1; ii <= i__2; ++ii) { i__3 = i__ - ns + ii; i__5 = ii + ii * 15 - 16; w[i__3].r = s[i__5].r, w[i__3].i = s[i__5].i; /* L100: */ } } } /* Form the first column of (G-w(1)) (G-w(2)) . . . (G-w(ns)) where G is the Hessenberg submatrix H(L:I,L:I) and w is the vector of shifts (stored in W). The result is stored in the local array V. */ v[0].r = 1.f, v[0].i = 0.f; i__2 = ns + 1; for (ii = 2; ii <= i__2; ++ii) { i__3 = ii - 1; v[i__3].r = 0.f, v[i__3].i = 0.f; /* L110: */ } nv = 1; i__2 = i__; for (j = i__ - ns + 1; j <= i__2; ++j) { i__3 = nv + 1; ccopy_(&i__3, v, &c__1, vv, &c__1); i__3 = nv + 1; i__5 = j; q__1.r = -w[i__5].r, q__1.i = -w[i__5].i; cgemv_("No transpose", &i__3, &nv, &c_b56, &h__[l + l * h_dim1], ldh, vv, &c__1, &q__1, v, &c__1); ++nv; /* Scale V(1:NV) so that max(abs(V(i))) = 1. If V is zero, reset it to the unit vector. */ itemp = icamax_(&nv, v, &c__1); i__3 = itemp - 1; rtemp = (r__1 = v[i__3].r, dabs(r__1)) + (r__2 = r_imag(&v[itemp - 1]), dabs(r__2)); if (rtemp == 0.f) { v[0].r = 1.f, v[0].i = 0.f; i__3 = nv; for (ii = 2; ii <= i__3; ++ii) { i__5 = ii - 1; v[i__5].r = 0.f, v[i__5].i = 0.f; /* L120: */ } } else { rtemp = dmax(rtemp,smlnum); r__1 = 1.f / rtemp; csscal_(&nv, &r__1, v, &c__1); } /* L130: */ } /* Multiple-shift QR step */ i__2 = i__ - 1; for (k = l; k <= i__2; ++k) { /* The first iteration of this loop determines a reflection G from the vector V and applies it from left and right to H, thus creating a nonzero bulge below the subdiagonal. Each subsequent iteration determines a reflection G to restore the Hessenberg form in the (K-1)th column, and thus chases the bulge one step toward the bottom of the active submatrix. NR is the order of G. Computing MIN */ i__3 = ns + 1, i__5 = i__ - k + 1; nr = min(i__3,i__5); if (k > l) { ccopy_(&nr, &h__[k + (k - 1) * h_dim1], &c__1, v, &c__1); } clarfg_(&nr, v, &v[1], &c__1, &tau); if (k > l) { i__3 = k + (k - 1) * h_dim1; h__[i__3].r = v[0].r, h__[i__3].i = v[0].i; i__3 = i__; for (ii = k + 1; ii <= i__3; ++ii) { i__5 = ii + (k - 1) * h_dim1; h__[i__5].r = 0.f, h__[i__5].i = 0.f; /* L140: */ } } v[0].r = 1.f, v[0].i = 0.f; /* Apply G' from the left to transform the rows of the matrix in columns K to I2. */ i__3 = i2 - k + 1; r_cnjg(&q__1, &tau); clarfx_("Left", &nr, &i__3, v, &q__1, &h__[k + k * h_dim1], ldh, & work[1]); /* Apply G from the right to transform the columns of the matrix in rows I1 to min(K+NR,I). Computing MIN */ i__5 = k + nr; i__3 = min(i__5,i__) - i1 + 1; clarfx_("Right", &i__3, &nr, v, &tau, &h__[i1 + k * h_dim1], ldh, &work[1]); if (wantz) { /* Accumulate transformations in the matrix Z */ clarfx_("Right", &nh, &nr, v, &tau, &z__[*ilo + k * z_dim1], ldz, &work[1]); } /* L150: */ } /* Ensure that H(I,I-1) is real. */ i__2 = i__ + (i__ - 1) * h_dim1; temp.r = h__[i__2].r, temp.i = h__[i__2].i; if (r_imag(&temp) != 0.f) { r__1 = temp.r; r__2 = r_imag(&temp); rtemp = slapy2_(&r__1, &r__2); i__2 = i__ + (i__ - 1) * h_dim1; h__[i__2].r = rtemp, h__[i__2].i = 0.f; q__1.r = temp.r / rtemp, q__1.i = temp.i / rtemp; temp.r = q__1.r, temp.i = q__1.i; if (i2 > i__) { i__2 = i2 - i__; r_cnjg(&q__1, &temp); cscal_(&i__2, &q__1, &h__[i__ + (i__ + 1) * h_dim1], ldh); } i__2 = i__ - i1; cscal_(&i__2, &temp, &h__[i1 + i__ * h_dim1], &c__1); if (wantz) { cscal_(&nh, &temp, &z__[*ilo + i__ * z_dim1], &c__1); } } /* L160: */ } /* Failure to converge in remaining number of iterations */ *info = i__; return 0; L170: /* A submatrix of order <= MAXB in rows and columns L to I has split off. Use the double-shift QR algorithm to handle it. */ clahqr_(&wantt, &wantz, n, &l, &i__, &h__[h_offset], ldh, &w[1], ilo, ihi, &z__[z_offset], ldz, info); if (*info > 0) { return 0; } /* Decrement number of remaining iterations, and return to start of the main loop with a new value of I. */ itn -= its; i__ = l - 1; goto L60; L180: i__1 = max(1,*n); work[1].r = (real) i__1, work[1].i = 0.f; return 0; /* End of CHSEQR */ } /* chseqr_ */ /* Subroutine */ int clabrd_(integer *m, integer *n, integer *nb, complex *a, integer *lda, real *d__, real *e, complex *tauq, complex *taup, complex *x, integer *ldx, complex *y, integer *ldy) { /* System generated locals */ integer a_dim1, a_offset, x_dim1, x_offset, y_dim1, y_offset, i__1, i__2, i__3; complex q__1; /* Local variables */ static integer i__; static complex alpha; extern /* Subroutine */ int cscal_(integer *, complex *, complex *, integer *), cgemv_(char *, integer *, integer *, complex *, complex *, integer *, complex *, integer *, complex *, complex *, integer *), clarfg_(integer *, complex *, complex *, integer *, complex *), clacgv_(integer *, complex *, integer *); /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University September 30, 1994 Purpose ======= CLABRD reduces the first NB rows and columns of a complex general m by n matrix A to upper or lower real bidiagonal form by a unitary transformation Q' * A * P, and returns the matrices X and Y which are needed to apply the transformation to the unreduced part of A. If m >= n, A is reduced to upper bidiagonal form; if m < n, to lower bidiagonal form. This is an auxiliary routine called by CGEBRD Arguments ========= M (input) INTEGER The number of rows in the matrix A. N (input) INTEGER The number of columns in the matrix A. NB (input) INTEGER The number of leading rows and columns of A to be reduced. A (input/output) COMPLEX array, dimension (LDA,N) On entry, the m by n general matrix to be reduced. On exit, the first NB rows and columns of the matrix are overwritten; the rest of the array is unchanged. If m >= n, elements on and below the diagonal in the first NB columns, with the array TAUQ, represent the unitary matrix Q as a product of elementary reflectors; and elements above the diagonal in the first NB rows, with the array TAUP, represent the unitary matrix P as a product of elementary reflectors. If m < n, elements below the diagonal in the first NB columns, with the array TAUQ, represent the unitary matrix Q as a product of elementary reflectors, and elements on and above the diagonal in the first NB rows, with the array TAUP, represent the unitary matrix P as a product of elementary reflectors. See Further Details. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,M). D (output) REAL array, dimension (NB) The diagonal elements of the first NB rows and columns of the reduced matrix. D(i) = A(i,i). E (output) REAL array, dimension (NB) The off-diagonal elements of the first NB rows and columns of the reduced matrix. TAUQ (output) COMPLEX array dimension (NB) The scalar factors of the elementary reflectors which represent the unitary matrix Q. See Further Details. TAUP (output) COMPLEX array, dimension (NB) The scalar factors of the elementary reflectors which represent the unitary matrix P. See Further Details. X (output) COMPLEX array, dimension (LDX,NB) The m-by-nb matrix X required to update the unreduced part of A. LDX (input) INTEGER The leading dimension of the array X. LDX >= max(1,M). Y (output) COMPLEX array, dimension (LDY,NB) The n-by-nb matrix Y required to update the unreduced part of A. LDY (output) INTEGER The leading dimension of the array Y. LDY >= max(1,N). Further Details =============== The matrices Q and P are represented as products of elementary reflectors: Q = H(1) H(2) . . . H(nb) and P = G(1) G(2) . . . G(nb) Each H(i) and G(i) has the form: H(i) = I - tauq * v * v' and G(i) = I - taup * u * u' where tauq and taup are complex scalars, and v and u are complex vectors. If m >= n, v(1:i-1) = 0, v(i) = 1, and v(i:m) is stored on exit in A(i:m,i); u(1:i) = 0, u(i+1) = 1, and u(i+1:n) is stored on exit in A(i,i+1:n); tauq is stored in TAUQ(i) and taup in TAUP(i). If m < n, v(1:i) = 0, v(i+1) = 1, and v(i+1:m) is stored on exit in A(i+2:m,i); u(1:i-1) = 0, u(i) = 1, and u(i:n) is stored on exit in A(i,i+1:n); tauq is stored in TAUQ(i) and taup in TAUP(i). The elements of the vectors v and u together form the m-by-nb matrix V and the nb-by-n matrix U' which are needed, with X and Y, to apply the transformation to the unreduced part of the matrix, using a block update of the form: A := A - V*Y' - X*U'. The contents of A on exit are illustrated by the following examples with nb = 2: m = 6 and n = 5 (m > n): m = 5 and n = 6 (m < n): ( 1 1 u1 u1 u1 ) ( 1 u1 u1 u1 u1 u1 ) ( v1 1 1 u2 u2 ) ( 1 1 u2 u2 u2 u2 ) ( v1 v2 a a a ) ( v1 1 a a a a ) ( v1 v2 a a a ) ( v1 v2 a a a a ) ( v1 v2 a a a ) ( v1 v2 a a a a ) ( v1 v2 a a a ) where a denotes an element of the original matrix which is unchanged, vi denotes an element of the vector defining H(i), and ui an element of the vector defining G(i). ===================================================================== Quick return if possible */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --d__; --e; --tauq; --taup; x_dim1 = *ldx; x_offset = 1 + x_dim1; x -= x_offset; y_dim1 = *ldy; y_offset = 1 + y_dim1; y -= y_offset; /* Function Body */ if ((*m <= 0) || (*n <= 0)) { return 0; } if (*m >= *n) { /* Reduce to upper bidiagonal form */ i__1 = *nb; for (i__ = 1; i__ <= i__1; ++i__) { /* Update A(i:m,i) */ i__2 = i__ - 1; clacgv_(&i__2, &y[i__ + y_dim1], ldy); i__2 = *m - i__ + 1; i__3 = i__ - 1; q__1.r = -1.f, q__1.i = -0.f; cgemv_("No transpose", &i__2, &i__3, &q__1, &a[i__ + a_dim1], lda, &y[i__ + y_dim1], ldy, &c_b56, &a[i__ + i__ * a_dim1], & c__1); i__2 = i__ - 1; clacgv_(&i__2, &y[i__ + y_dim1], ldy); i__2 = *m - i__ + 1; i__3 = i__ - 1; q__1.r = -1.f, q__1.i = -0.f; cgemv_("No transpose", &i__2, &i__3, &q__1, &x[i__ + x_dim1], ldx, &a[i__ * a_dim1 + 1], &c__1, &c_b56, &a[i__ + i__ * a_dim1], &c__1); /* Generate reflection Q(i) to annihilate A(i+1:m,i) */ i__2 = i__ + i__ * a_dim1; alpha.r = a[i__2].r, alpha.i = a[i__2].i; i__2 = *m - i__ + 1; /* Computing MIN */ i__3 = i__ + 1; clarfg_(&i__2, &alpha, &a[min(i__3,*m) + i__ * a_dim1], &c__1, & tauq[i__]); i__2 = i__; d__[i__2] = alpha.r; if (i__ < *n) { i__2 = i__ + i__ * a_dim1; a[i__2].r = 1.f, a[i__2].i = 0.f; /* Compute Y(i+1:n,i) */ i__2 = *m - i__ + 1; i__3 = *n - i__; cgemv_("Conjugate transpose", &i__2, &i__3, &c_b56, &a[i__ + ( i__ + 1) * a_dim1], lda, &a[i__ + i__ * a_dim1], & c__1, &c_b55, &y[i__ + 1 + i__ * y_dim1], &c__1); i__2 = *m - i__ + 1; i__3 = i__ - 1; cgemv_("Conjugate transpose", &i__2, &i__3, &c_b56, &a[i__ + a_dim1], lda, &a[i__ + i__ * a_dim1], &c__1, &c_b55, & y[i__ * y_dim1 + 1], &c__1); i__2 = *n - i__; i__3 = i__ - 1; q__1.r = -1.f, q__1.i = -0.f; cgemv_("No transpose", &i__2, &i__3, &q__1, &y[i__ + 1 + y_dim1], ldy, &y[i__ * y_dim1 + 1], &c__1, &c_b56, &y[ i__ + 1 + i__ * y_dim1], &c__1); i__2 = *m - i__ + 1; i__3 = i__ - 1; cgemv_("Conjugate transpose", &i__2, &i__3, &c_b56, &x[i__ + x_dim1], ldx, &a[i__ + i__ * a_dim1], &c__1, &c_b55, & y[i__ * y_dim1 + 1], &c__1); i__2 = i__ - 1; i__3 = *n - i__; q__1.r = -1.f, q__1.i = -0.f; cgemv_("Conjugate transpose", &i__2, &i__3, &q__1, &a[(i__ + 1) * a_dim1 + 1], lda, &y[i__ * y_dim1 + 1], &c__1, & c_b56, &y[i__ + 1 + i__ * y_dim1], &c__1); i__2 = *n - i__; cscal_(&i__2, &tauq[i__], &y[i__ + 1 + i__ * y_dim1], &c__1); /* Update A(i,i+1:n) */ i__2 = *n - i__; clacgv_(&i__2, &a[i__ + (i__ + 1) * a_dim1], lda); clacgv_(&i__, &a[i__ + a_dim1], lda); i__2 = *n - i__; q__1.r = -1.f, q__1.i = -0.f; cgemv_("No transpose", &i__2, &i__, &q__1, &y[i__ + 1 + y_dim1], ldy, &a[i__ + a_dim1], lda, &c_b56, &a[i__ + (i__ + 1) * a_dim1], lda); clacgv_(&i__, &a[i__ + a_dim1], lda); i__2 = i__ - 1; clacgv_(&i__2, &x[i__ + x_dim1], ldx); i__2 = i__ - 1; i__3 = *n - i__; q__1.r = -1.f, q__1.i = -0.f; cgemv_("Conjugate transpose", &i__2, &i__3, &q__1, &a[(i__ + 1) * a_dim1 + 1], lda, &x[i__ + x_dim1], ldx, &c_b56, &a[i__ + (i__ + 1) * a_dim1], lda); i__2 = i__ - 1; clacgv_(&i__2, &x[i__ + x_dim1], ldx); /* Generate reflection P(i) to annihilate A(i,i+2:n) */ i__2 = i__ + (i__ + 1) * a_dim1; alpha.r = a[i__2].r, alpha.i = a[i__2].i; i__2 = *n - i__; /* Computing MIN */ i__3 = i__ + 2; clarfg_(&i__2, &alpha, &a[i__ + min(i__3,*n) * a_dim1], lda, & taup[i__]); i__2 = i__; e[i__2] = alpha.r; i__2 = i__ + (i__ + 1) * a_dim1; a[i__2].r = 1.f, a[i__2].i = 0.f; /* Compute X(i+1:m,i) */ i__2 = *m - i__; i__3 = *n - i__; cgemv_("No transpose", &i__2, &i__3, &c_b56, &a[i__ + 1 + ( i__ + 1) * a_dim1], lda, &a[i__ + (i__ + 1) * a_dim1], lda, &c_b55, &x[i__ + 1 + i__ * x_dim1], &c__1); i__2 = *n - i__; cgemv_("Conjugate transpose", &i__2, &i__, &c_b56, &y[i__ + 1 + y_dim1], ldy, &a[i__ + (i__ + 1) * a_dim1], lda, & c_b55, &x[i__ * x_dim1 + 1], &c__1); i__2 = *m - i__; q__1.r = -1.f, q__1.i = -0.f; cgemv_("No transpose", &i__2, &i__, &q__1, &a[i__ + 1 + a_dim1], lda, &x[i__ * x_dim1 + 1], &c__1, &c_b56, &x[ i__ + 1 + i__ * x_dim1], &c__1); i__2 = i__ - 1; i__3 = *n - i__; cgemv_("No transpose", &i__2, &i__3, &c_b56, &a[(i__ + 1) * a_dim1 + 1], lda, &a[i__ + (i__ + 1) * a_dim1], lda, & c_b55, &x[i__ * x_dim1 + 1], &c__1); i__2 = *m - i__; i__3 = i__ - 1; q__1.r = -1.f, q__1.i = -0.f; cgemv_("No transpose", &i__2, &i__3, &q__1, &x[i__ + 1 + x_dim1], ldx, &x[i__ * x_dim1 + 1], &c__1, &c_b56, &x[ i__ + 1 + i__ * x_dim1], &c__1); i__2 = *m - i__; cscal_(&i__2, &taup[i__], &x[i__ + 1 + i__ * x_dim1], &c__1); i__2 = *n - i__; clacgv_(&i__2, &a[i__ + (i__ + 1) * a_dim1], lda); } /* L10: */ } } else { /* Reduce to lower bidiagonal form */ i__1 = *nb; for (i__ = 1; i__ <= i__1; ++i__) { /* Update A(i,i:n) */ i__2 = *n - i__ + 1; clacgv_(&i__2, &a[i__ + i__ * a_dim1], lda); i__2 = i__ - 1; clacgv_(&i__2, &a[i__ + a_dim1], lda); i__2 = *n - i__ + 1; i__3 = i__ - 1; q__1.r = -1.f, q__1.i = -0.f; cgemv_("No transpose", &i__2, &i__3, &q__1, &y[i__ + y_dim1], ldy, &a[i__ + a_dim1], lda, &c_b56, &a[i__ + i__ * a_dim1], lda); i__2 = i__ - 1; clacgv_(&i__2, &a[i__ + a_dim1], lda); i__2 = i__ - 1; clacgv_(&i__2, &x[i__ + x_dim1], ldx); i__2 = i__ - 1; i__3 = *n - i__ + 1; q__1.r = -1.f, q__1.i = -0.f; cgemv_("Conjugate transpose", &i__2, &i__3, &q__1, &a[i__ * a_dim1 + 1], lda, &x[i__ + x_dim1], ldx, &c_b56, &a[i__ + i__ * a_dim1], lda); i__2 = i__ - 1; clacgv_(&i__2, &x[i__ + x_dim1], ldx); /* Generate reflection P(i) to annihilate A(i,i+1:n) */ i__2 = i__ + i__ * a_dim1; alpha.r = a[i__2].r, alpha.i = a[i__2].i; i__2 = *n - i__ + 1; /* Computing MIN */ i__3 = i__ + 1; clarfg_(&i__2, &alpha, &a[i__ + min(i__3,*n) * a_dim1], lda, & taup[i__]); i__2 = i__; d__[i__2] = alpha.r; if (i__ < *m) { i__2 = i__ + i__ * a_dim1; a[i__2].r = 1.f, a[i__2].i = 0.f; /* Compute X(i+1:m,i) */ i__2 = *m - i__; i__3 = *n - i__ + 1; cgemv_("No transpose", &i__2, &i__3, &c_b56, &a[i__ + 1 + i__ * a_dim1], lda, &a[i__ + i__ * a_dim1], lda, &c_b55, & x[i__ + 1 + i__ * x_dim1], &c__1); i__2 = *n - i__ + 1; i__3 = i__ - 1; cgemv_("Conjugate transpose", &i__2, &i__3, &c_b56, &y[i__ + y_dim1], ldy, &a[i__ + i__ * a_dim1], lda, &c_b55, &x[ i__ * x_dim1 + 1], &c__1); i__2 = *m - i__; i__3 = i__ - 1; q__1.r = -1.f, q__1.i = -0.f; cgemv_("No transpose", &i__2, &i__3, &q__1, &a[i__ + 1 + a_dim1], lda, &x[i__ * x_dim1 + 1], &c__1, &c_b56, &x[ i__ + 1 + i__ * x_dim1], &c__1); i__2 = i__ - 1; i__3 = *n - i__ + 1; cgemv_("No transpose", &i__2, &i__3, &c_b56, &a[i__ * a_dim1 + 1], lda, &a[i__ + i__ * a_dim1], lda, &c_b55, &x[ i__ * x_dim1 + 1], &c__1); i__2 = *m - i__; i__3 = i__ - 1; q__1.r = -1.f, q__1.i = -0.f; cgemv_("No transpose", &i__2, &i__3, &q__1, &x[i__ + 1 + x_dim1], ldx, &x[i__ * x_dim1 + 1], &c__1, &c_b56, &x[ i__ + 1 + i__ * x_dim1], &c__1); i__2 = *m - i__; cscal_(&i__2, &taup[i__], &x[i__ + 1 + i__ * x_dim1], &c__1); i__2 = *n - i__ + 1; clacgv_(&i__2, &a[i__ + i__ * a_dim1], lda); /* Update A(i+1:m,i) */ i__2 = i__ - 1; clacgv_(&i__2, &y[i__ + y_dim1], ldy); i__2 = *m - i__; i__3 = i__ - 1; q__1.r = -1.f, q__1.i = -0.f; cgemv_("No transpose", &i__2, &i__3, &q__1, &a[i__ + 1 + a_dim1], lda, &y[i__ + y_dim1], ldy, &c_b56, &a[i__ + 1 + i__ * a_dim1], &c__1); i__2 = i__ - 1; clacgv_(&i__2, &y[i__ + y_dim1], ldy); i__2 = *m - i__; q__1.r = -1.f, q__1.i = -0.f; cgemv_("No transpose", &i__2, &i__, &q__1, &x[i__ + 1 + x_dim1], ldx, &a[i__ * a_dim1 + 1], &c__1, &c_b56, &a[ i__ + 1 + i__ * a_dim1], &c__1); /* Generate reflection Q(i) to annihilate A(i+2:m,i) */ i__2 = i__ + 1 + i__ * a_dim1; alpha.r = a[i__2].r, alpha.i = a[i__2].i; i__2 = *m - i__; /* Computing MIN */ i__3 = i__ + 2; clarfg_(&i__2, &alpha, &a[min(i__3,*m) + i__ * a_dim1], &c__1, &tauq[i__]); i__2 = i__; e[i__2] = alpha.r; i__2 = i__ + 1 + i__ * a_dim1; a[i__2].r = 1.f, a[i__2].i = 0.f; /* Compute Y(i+1:n,i) */ i__2 = *m - i__; i__3 = *n - i__; cgemv_("Conjugate transpose", &i__2, &i__3, &c_b56, &a[i__ + 1 + (i__ + 1) * a_dim1], lda, &a[i__ + 1 + i__ * a_dim1], &c__1, &c_b55, &y[i__ + 1 + i__ * y_dim1], & c__1); i__2 = *m - i__; i__3 = i__ - 1; cgemv_("Conjugate transpose", &i__2, &i__3, &c_b56, &a[i__ + 1 + a_dim1], lda, &a[i__ + 1 + i__ * a_dim1], &c__1, & c_b55, &y[i__ * y_dim1 + 1], &c__1); i__2 = *n - i__; i__3 = i__ - 1; q__1.r = -1.f, q__1.i = -0.f; cgemv_("No transpose", &i__2, &i__3, &q__1, &y[i__ + 1 + y_dim1], ldy, &y[i__ * y_dim1 + 1], &c__1, &c_b56, &y[ i__ + 1 + i__ * y_dim1], &c__1); i__2 = *m - i__; cgemv_("Conjugate transpose", &i__2, &i__, &c_b56, &x[i__ + 1 + x_dim1], ldx, &a[i__ + 1 + i__ * a_dim1], &c__1, & c_b55, &y[i__ * y_dim1 + 1], &c__1); i__2 = *n - i__; q__1.r = -1.f, q__1.i = -0.f; cgemv_("Conjugate transpose", &i__, &i__2, &q__1, &a[(i__ + 1) * a_dim1 + 1], lda, &y[i__ * y_dim1 + 1], &c__1, & c_b56, &y[i__ + 1 + i__ * y_dim1], &c__1); i__2 = *n - i__; cscal_(&i__2, &tauq[i__], &y[i__ + 1 + i__ * y_dim1], &c__1); } else { i__2 = *n - i__ + 1; clacgv_(&i__2, &a[i__ + i__ * a_dim1], lda); } /* L20: */ } } return 0; /* End of CLABRD */ } /* clabrd_ */ /* Subroutine */ int clacgv_(integer *n, complex *x, integer *incx) { /* System generated locals */ integer i__1, i__2; complex q__1; /* Builtin functions */ void r_cnjg(complex *, complex *); /* Local variables */ static integer i__, ioff; /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University October 31, 1992 Purpose ======= CLACGV conjugates a complex vector of length N. Arguments ========= N (input) INTEGER The length of the vector X. N >= 0. X (input/output) COMPLEX array, dimension (1+(N-1)*abs(INCX)) On entry, the vector of length N to be conjugated. On exit, X is overwritten with conjg(X). INCX (input) INTEGER The spacing between successive elements of X. ===================================================================== */ /* Parameter adjustments */ --x; /* Function Body */ if (*incx == 1) { i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = i__; r_cnjg(&q__1, &x[i__]); x[i__2].r = q__1.r, x[i__2].i = q__1.i; /* L10: */ } } else { ioff = 1; if (*incx < 0) { ioff = 1 - (*n - 1) * *incx; } i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = ioff; r_cnjg(&q__1, &x[ioff]); x[i__2].r = q__1.r, x[i__2].i = q__1.i; ioff += *incx; /* L20: */ } } return 0; /* End of CLACGV */ } /* clacgv_ */ /* Subroutine */ int clacp2_(char *uplo, integer *m, integer *n, real *a, integer *lda, complex *b, integer *ldb) { /* System generated locals */ integer a_dim1, a_offset, b_dim1, b_offset, i__1, i__2, i__3, i__4; /* Local variables */ static integer i__, j; extern logical lsame_(char *, char *); /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= CLACP2 copies all or part of a real two-dimensional matrix A to a complex matrix B. Arguments ========= UPLO (input) CHARACTER*1 Specifies the part of the matrix A to be copied to B. = 'U': Upper triangular part = 'L': Lower triangular part Otherwise: All of the matrix A M (input) INTEGER The number of rows of the matrix A. M >= 0. N (input) INTEGER The number of columns of the matrix A. N >= 0. A (input) REAL array, dimension (LDA,N) The m by n matrix A. If UPLO = 'U', only the upper trapezium is accessed; if UPLO = 'L', only the lower trapezium is accessed. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,M). B (output) COMPLEX array, dimension (LDB,N) On exit, B = A in the locations specified by UPLO. LDB (input) INTEGER The leading dimension of the array B. LDB >= max(1,M). ===================================================================== */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; b_dim1 = *ldb; b_offset = 1 + b_dim1; b -= b_offset; /* Function Body */ if (lsame_(uplo, "U")) { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = min(j,*m); for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * b_dim1; i__4 = i__ + j * a_dim1; b[i__3].r = a[i__4], b[i__3].i = 0.f; /* L10: */ } /* L20: */ } } else if (lsame_(uplo, "L")) { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = j; i__ <= i__2; ++i__) { i__3 = i__ + j * b_dim1; i__4 = i__ + j * a_dim1; b[i__3].r = a[i__4], b[i__3].i = 0.f; /* L30: */ } /* L40: */ } } else { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * b_dim1; i__4 = i__ + j * a_dim1; b[i__3].r = a[i__4], b[i__3].i = 0.f; /* L50: */ } /* L60: */ } } return 0; /* End of CLACP2 */ } /* clacp2_ */ /* Subroutine */ int clacpy_(char *uplo, integer *m, integer *n, complex *a, integer *lda, complex *b, integer *ldb) { /* System generated locals */ integer a_dim1, a_offset, b_dim1, b_offset, i__1, i__2, i__3, i__4; /* Local variables */ static integer i__, j; extern logical lsame_(char *, char *); /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University February 29, 1992 Purpose ======= CLACPY copies all or part of a two-dimensional matrix A to another matrix B. Arguments ========= UPLO (input) CHARACTER*1 Specifies the part of the matrix A to be copied to B. = 'U': Upper triangular part = 'L': Lower triangular part Otherwise: All of the matrix A M (input) INTEGER The number of rows of the matrix A. M >= 0. N (input) INTEGER The number of columns of the matrix A. N >= 0. A (input) COMPLEX array, dimension (LDA,N) The m by n matrix A. If UPLO = 'U', only the upper trapezium is accessed; if UPLO = 'L', only the lower trapezium is accessed. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,M). B (output) COMPLEX array, dimension (LDB,N) On exit, B = A in the locations specified by UPLO. LDB (input) INTEGER The leading dimension of the array B. LDB >= max(1,M). ===================================================================== */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; b_dim1 = *ldb; b_offset = 1 + b_dim1; b -= b_offset; /* Function Body */ if (lsame_(uplo, "U")) { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = min(j,*m); for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * b_dim1; i__4 = i__ + j * a_dim1; b[i__3].r = a[i__4].r, b[i__3].i = a[i__4].i; /* L10: */ } /* L20: */ } } else if (lsame_(uplo, "L")) { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = j; i__ <= i__2; ++i__) { i__3 = i__ + j * b_dim1; i__4 = i__ + j * a_dim1; b[i__3].r = a[i__4].r, b[i__3].i = a[i__4].i; /* L30: */ } /* L40: */ } } else { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * b_dim1; i__4 = i__ + j * a_dim1; b[i__3].r = a[i__4].r, b[i__3].i = a[i__4].i; /* L50: */ } /* L60: */ } } return 0; /* End of CLACPY */ } /* clacpy_ */ /* Subroutine */ int clacrm_(integer *m, integer *n, complex *a, integer *lda, real *b, integer *ldb, complex *c__, integer *ldc, real *rwork) { /* System generated locals */ integer b_dim1, b_offset, a_dim1, a_offset, c_dim1, c_offset, i__1, i__2, i__3, i__4, i__5; real r__1; complex q__1; /* Builtin functions */ double r_imag(complex *); /* Local variables */ static integer i__, j, l; extern /* Subroutine */ int sgemm_(char *, char *, integer *, integer *, integer *, real *, real *, integer *, real *, integer *, real *, real *, integer *); /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University September 30, 1994 Purpose ======= CLACRM performs a very simple matrix-matrix multiplication: C := A * B, where A is M by N and complex; B is N by N and real; C is M by N and complex. Arguments ========= M (input) INTEGER The number of rows of the matrix A and of the matrix C. M >= 0. N (input) INTEGER The number of columns and rows of the matrix B and the number of columns of the matrix C. N >= 0. A (input) COMPLEX array, dimension (LDA, N) A contains the M by N matrix A. LDA (input) INTEGER The leading dimension of the array A. LDA >=max(1,M). B (input) REAL array, dimension (LDB, N) B contains the N by N matrix B. LDB (input) INTEGER The leading dimension of the array B. LDB >=max(1,N). C (input) COMPLEX array, dimension (LDC, N) C contains the M by N matrix C. LDC (input) INTEGER The leading dimension of the array C. LDC >=max(1,N). RWORK (workspace) REAL array, dimension (2*M*N) ===================================================================== Quick return if possible. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; b_dim1 = *ldb; b_offset = 1 + b_dim1; b -= b_offset; c_dim1 = *ldc; c_offset = 1 + c_dim1; c__ -= c_offset; --rwork; /* Function Body */ if ((*m == 0) || (*n == 0)) { return 0; } i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * a_dim1; rwork[(j - 1) * *m + i__] = a[i__3].r; /* L10: */ } /* L20: */ } l = *m * *n + 1; sgemm_("N", "N", m, n, n, &c_b1011, &rwork[1], m, &b[b_offset], ldb, & c_b320, &rwork[l], m); i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * c_dim1; i__4 = l + (j - 1) * *m + i__ - 1; c__[i__3].r = rwork[i__4], c__[i__3].i = 0.f; /* L30: */ } /* L40: */ } i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { rwork[(j - 1) * *m + i__] = r_imag(&a[i__ + j * a_dim1]); /* L50: */ } /* L60: */ } sgemm_("N", "N", m, n, n, &c_b1011, &rwork[1], m, &b[b_offset], ldb, & c_b320, &rwork[l], m); i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * c_dim1; i__4 = i__ + j * c_dim1; r__1 = c__[i__4].r; i__5 = l + (j - 1) * *m + i__ - 1; q__1.r = r__1, q__1.i = rwork[i__5]; c__[i__3].r = q__1.r, c__[i__3].i = q__1.i; /* L70: */ } /* L80: */ } return 0; /* End of CLACRM */ } /* clacrm_ */ /* Complex */ VOID cladiv_(complex * ret_val, complex *x, complex *y) { /* System generated locals */ real r__1, r__2, r__3, r__4; complex q__1; /* Builtin functions */ double r_imag(complex *); /* Local variables */ static real zi, zr; extern /* Subroutine */ int sladiv_(real *, real *, real *, real *, real * , real *); /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University October 31, 1992 Purpose ======= CLADIV := X / Y, where X and Y are complex. The computation of X / Y will not overflow on an intermediary step unless the results overflows. Arguments ========= X (input) COMPLEX Y (input) COMPLEX The complex scalars X and Y. ===================================================================== */ r__1 = x->r; r__2 = r_imag(x); r__3 = y->r; r__4 = r_imag(y); sladiv_(&r__1, &r__2, &r__3, &r__4, &zr, &zi); q__1.r = zr, q__1.i = zi; ret_val->r = q__1.r, ret_val->i = q__1.i; return ; /* End of CLADIV */ } /* cladiv_ */ /* Subroutine */ int claed0_(integer *qsiz, integer *n, real *d__, real *e, complex *q, integer *ldq, complex *qstore, integer *ldqs, real *rwork, integer *iwork, integer *info) { /* System generated locals */ integer q_dim1, q_offset, qstore_dim1, qstore_offset, i__1, i__2; real r__1; /* Builtin functions */ double log(doublereal); integer pow_ii(integer *, integer *); /* Local variables */ static integer i__, j, k, ll, iq, lgn, msd2, smm1, spm1, spm2; static real temp; static integer curr, iperm; extern /* Subroutine */ int ccopy_(integer *, complex *, integer *, complex *, integer *); static integer indxq, iwrem; extern /* Subroutine */ int scopy_(integer *, real *, integer *, real *, integer *); static integer iqptr; extern /* Subroutine */ int claed7_(integer *, integer *, integer *, integer *, integer *, integer *, real *, complex *, integer *, real *, integer *, real *, integer *, integer *, integer *, integer *, integer *, real *, complex *, real *, integer *, integer *); static integer tlvls; extern /* Subroutine */ int clacrm_(integer *, integer *, complex *, integer *, real *, integer *, complex *, integer *, real *); static integer igivcl; extern /* Subroutine */ int xerbla_(char *, integer *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); static integer igivnm, submat, curprb, subpbs, igivpt, curlvl, matsiz, iprmpt, smlsiz; extern /* Subroutine */ int ssteqr_(char *, integer *, real *, real *, real *, integer *, real *, integer *); /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University September 30, 1994 Purpose ======= Using the divide and conquer method, CLAED0 computes all eigenvalues of a symmetric tridiagonal matrix which is one diagonal block of those from reducing a dense or band Hermitian matrix and corresponding eigenvectors of the dense or band matrix. Arguments ========= QSIZ (input) INTEGER The dimension of the unitary matrix used to reduce the full matrix to tridiagonal form. QSIZ >= N if ICOMPQ = 1. N (input) INTEGER The dimension of the symmetric tridiagonal matrix. N >= 0. D (input/output) REAL array, dimension (N) On entry, the diagonal elements of the tridiagonal matrix. On exit, the eigenvalues in ascending order. E (input/output) REAL array, dimension (N-1) On entry, the off-diagonal elements of the tridiagonal matrix. On exit, E has been destroyed. Q (input/output) COMPLEX array, dimension (LDQ,N) On entry, Q must contain an QSIZ x N matrix whose columns unitarily orthonormal. It is a part of the unitary matrix that reduces the full dense Hermitian matrix to a (reducible) symmetric tridiagonal matrix. LDQ (input) INTEGER The leading dimension of the array Q. LDQ >= max(1,N). IWORK (workspace) INTEGER array, the dimension of IWORK must be at least 6 + 6*N + 5*N*lg N ( lg( N ) = smallest integer k such that 2^k >= N ) RWORK (workspace) REAL array, dimension (1 + 3*N + 2*N*lg N + 3*N**2) ( lg( N ) = smallest integer k such that 2^k >= N ) QSTORE (workspace) COMPLEX array, dimension (LDQS, N) Used to store parts of the eigenvector matrix when the updating matrix multiplies take place. LDQS (input) INTEGER The leading dimension of the array QSTORE. LDQS >= max(1,N). INFO (output) INTEGER = 0: successful exit. < 0: if INFO = -i, the i-th argument had an illegal value. > 0: The algorithm failed to compute an eigenvalue while working on the submatrix lying in rows and columns INFO/(N+1) through mod(INFO,N+1). ===================================================================== Warning: N could be as big as QSIZ! Test the input parameters. */ /* Parameter adjustments */ --d__; --e; q_dim1 = *ldq; q_offset = 1 + q_dim1; q -= q_offset; qstore_dim1 = *ldqs; qstore_offset = 1 + qstore_dim1; qstore -= qstore_offset; --rwork; --iwork; /* Function Body */ *info = 0; /* IF( ICOMPQ .LT. 0 .OR. ICOMPQ .GT. 2 ) THEN INFO = -1 ELSE IF( ( ICOMPQ .EQ. 1 ) .AND. ( QSIZ .LT. MAX( 0, N ) ) ) $ THEN */ if (*qsiz < max(0,*n)) { *info = -1; } else if (*n < 0) { *info = -2; } else if (*ldq < max(1,*n)) { *info = -6; } else if (*ldqs < max(1,*n)) { *info = -8; } if (*info != 0) { i__1 = -(*info); xerbla_("CLAED0", &i__1); return 0; } /* Quick return if possible */ if (*n == 0) { return 0; } smlsiz = ilaenv_(&c__9, "CLAED0", " ", &c__0, &c__0, &c__0, &c__0, ( ftnlen)6, (ftnlen)1); /* Determine the size and placement of the submatrices, and save in the leading elements of IWORK. */ iwork[1] = *n; subpbs = 1; tlvls = 0; L10: if (iwork[subpbs] > smlsiz) { for (j = subpbs; j >= 1; --j) { iwork[j * 2] = (iwork[j] + 1) / 2; iwork[((j) << (1)) - 1] = iwork[j] / 2; /* L20: */ } ++tlvls; subpbs <<= 1; goto L10; } i__1 = subpbs; for (j = 2; j <= i__1; ++j) { iwork[j] += iwork[j - 1]; /* L30: */ } /* Divide the matrix into SUBPBS submatrices of size at most SMLSIZ+1 using rank-1 modifications (cuts). */ spm1 = subpbs - 1; i__1 = spm1; for (i__ = 1; i__ <= i__1; ++i__) { submat = iwork[i__] + 1; smm1 = submat - 1; d__[smm1] -= (r__1 = e[smm1], dabs(r__1)); d__[submat] -= (r__1 = e[smm1], dabs(r__1)); /* L40: */ } indxq = ((*n) << (2)) + 3; /* Set up workspaces for eigenvalues only/accumulate new vectors routine */ temp = log((real) (*n)) / log(2.f); lgn = (integer) temp; if (pow_ii(&c__2, &lgn) < *n) { ++lgn; } if (pow_ii(&c__2, &lgn) < *n) { ++lgn; } iprmpt = indxq + *n + 1; iperm = iprmpt + *n * lgn; iqptr = iperm + *n * lgn; igivpt = iqptr + *n + 2; igivcl = igivpt + *n * lgn; igivnm = 1; iq = igivnm + ((*n) << (1)) * lgn; /* Computing 2nd power */ i__1 = *n; iwrem = iq + i__1 * i__1 + 1; /* Initialize pointers */ i__1 = subpbs; for (i__ = 0; i__ <= i__1; ++i__) { iwork[iprmpt + i__] = 1; iwork[igivpt + i__] = 1; /* L50: */ } iwork[iqptr] = 1; /* Solve each submatrix eigenproblem at the bottom of the divide and conquer tree. */ curr = 0; i__1 = spm1; for (i__ = 0; i__ <= i__1; ++i__) { if (i__ == 0) { submat = 1; matsiz = iwork[1]; } else { submat = iwork[i__] + 1; matsiz = iwork[i__ + 1] - iwork[i__]; } ll = iq - 1 + iwork[iqptr + curr]; ssteqr_("I", &matsiz, &d__[submat], &e[submat], &rwork[ll], &matsiz, & rwork[1], info); clacrm_(qsiz, &matsiz, &q[submat * q_dim1 + 1], ldq, &rwork[ll], & matsiz, &qstore[submat * qstore_dim1 + 1], ldqs, &rwork[iwrem] ); /* Computing 2nd power */ i__2 = matsiz; iwork[iqptr + curr + 1] = iwork[iqptr + curr] + i__2 * i__2; ++curr; if (*info > 0) { *info = submat * (*n + 1) + submat + matsiz - 1; return 0; } k = 1; i__2 = iwork[i__ + 1]; for (j = submat; j <= i__2; ++j) { iwork[indxq + j] = k; ++k; /* L60: */ } /* L70: */ } /* Successively merge eigensystems of adjacent submatrices into eigensystem for the corresponding larger matrix. while ( SUBPBS > 1 ) */ curlvl = 1; L80: if (subpbs > 1) { spm2 = subpbs - 2; i__1 = spm2; for (i__ = 0; i__ <= i__1; i__ += 2) { if (i__ == 0) { submat = 1; matsiz = iwork[2]; msd2 = iwork[1]; curprb = 0; } else { submat = iwork[i__] + 1; matsiz = iwork[i__ + 2] - iwork[i__]; msd2 = matsiz / 2; ++curprb; } /* Merge lower order eigensystems (of size MSD2 and MATSIZ - MSD2) into an eigensystem of size MATSIZ. CLAED7 handles the case when the eigenvectors of a full or band Hermitian matrix (which was reduced to tridiagonal form) are desired. I am free to use Q as a valuable working space until Loop 150. */ claed7_(&matsiz, &msd2, qsiz, &tlvls, &curlvl, &curprb, &d__[ submat], &qstore[submat * qstore_dim1 + 1], ldqs, &e[ submat + msd2 - 1], &iwork[indxq + submat], &rwork[iq], & iwork[iqptr], &iwork[iprmpt], &iwork[iperm], &iwork[ igivpt], &iwork[igivcl], &rwork[igivnm], &q[submat * q_dim1 + 1], &rwork[iwrem], &iwork[subpbs + 1], info); if (*info > 0) { *info = submat * (*n + 1) + submat + matsiz - 1; return 0; } iwork[i__ / 2 + 1] = iwork[i__ + 2]; /* L90: */ } subpbs /= 2; ++curlvl; goto L80; } /* end while Re-merge the eigenvalues/vectors which were deflated at the final merge step. */ i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { j = iwork[indxq + i__]; rwork[i__] = d__[j]; ccopy_(qsiz, &qstore[j * qstore_dim1 + 1], &c__1, &q[i__ * q_dim1 + 1] , &c__1); /* L100: */ } scopy_(n, &rwork[1], &c__1, &d__[1], &c__1); return 0; /* End of CLAED0 */ } /* claed0_ */ /* Subroutine */ int claed7_(integer *n, integer *cutpnt, integer *qsiz, integer *tlvls, integer *curlvl, integer *curpbm, real *d__, complex * q, integer *ldq, real *rho, integer *indxq, real *qstore, integer * qptr, integer *prmptr, integer *perm, integer *givptr, integer * givcol, real *givnum, complex *work, real *rwork, integer *iwork, integer *info) { /* System generated locals */ integer q_dim1, q_offset, i__1, i__2; /* Builtin functions */ integer pow_ii(integer *, integer *); /* Local variables */ static integer i__, k, n1, n2, iq, iw, iz, ptr, ind1, ind2, indx, curr, indxc, indxp; extern /* Subroutine */ int claed8_(integer *, integer *, integer *, complex *, integer *, real *, real *, integer *, real *, real *, complex *, integer *, real *, integer *, integer *, integer *, integer *, integer *, integer *, real *, integer *), slaed9_( integer *, integer *, integer *, integer *, real *, real *, integer *, real *, real *, real *, real *, integer *, integer *), slaeda_(integer *, integer *, integer *, integer *, integer *, integer *, integer *, integer *, real *, real *, integer *, real * , real *, integer *); static integer idlmda; extern /* Subroutine */ int clacrm_(integer *, integer *, complex *, integer *, real *, integer *, complex *, integer *, real *), xerbla_(char *, integer *), slamrg_(integer *, integer *, real *, integer *, integer *, integer *); static integer coltyp; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University September 30, 1994 Purpose ======= CLAED7 computes the updated eigensystem of a diagonal matrix after modification by a rank-one symmetric matrix. This routine is used only for the eigenproblem which requires all eigenvalues and optionally eigenvectors of a dense or banded Hermitian matrix that has been reduced to tridiagonal form. T = Q(in) ( D(in) + RHO * Z*Z' ) Q'(in) = Q(out) * D(out) * Q'(out) where Z = Q'u, u is a vector of length N with ones in the CUTPNT and CUTPNT + 1 th elements and zeros elsewhere. The eigenvectors of the original matrix are stored in Q, and the eigenvalues are in D. The algorithm consists of three stages: The first stage consists of deflating the size of the problem when there are multiple eigenvalues or if there is a zero in the Z vector. For each such occurence the dimension of the secular equation problem is reduced by one. This stage is performed by the routine SLAED2. The second stage consists of calculating the updated eigenvalues. This is done by finding the roots of the secular equation via the routine SLAED4 (as called by SLAED3). This routine also calculates the eigenvectors of the current problem. The final stage consists of computing the updated eigenvectors directly using the updated eigenvalues. The eigenvectors for the current problem are multiplied with the eigenvectors from the overall problem. Arguments ========= N (input) INTEGER The dimension of the symmetric tridiagonal matrix. N >= 0. CUTPNT (input) INTEGER Contains the location of the last eigenvalue in the leading sub-matrix. min(1,N) <= CUTPNT <= N. QSIZ (input) INTEGER The dimension of the unitary matrix used to reduce the full matrix to tridiagonal form. QSIZ >= N. TLVLS (input) INTEGER The total number of merging levels in the overall divide and conquer tree. CURLVL (input) INTEGER The current level in the overall merge routine, 0 <= curlvl <= tlvls. CURPBM (input) INTEGER The current problem in the current level in the overall merge routine (counting from upper left to lower right). D (input/output) REAL array, dimension (N) On entry, the eigenvalues of the rank-1-perturbed matrix. On exit, the eigenvalues of the repaired matrix. Q (input/output) COMPLEX array, dimension (LDQ,N) On entry, the eigenvectors of the rank-1-perturbed matrix. On exit, the eigenvectors of the repaired tridiagonal matrix. LDQ (input) INTEGER The leading dimension of the array Q. LDQ >= max(1,N). RHO (input) REAL Contains the subdiagonal element used to create the rank-1 modification. INDXQ (output) INTEGER array, dimension (N) This contains the permutation which will reintegrate the subproblem just solved back into sorted order, ie. D( INDXQ( I = 1, N ) ) will be in ascending order. IWORK (workspace) INTEGER array, dimension (4*N) RWORK (workspace) REAL array, dimension (3*N+2*QSIZ*N) WORK (workspace) COMPLEX array, dimension (QSIZ*N) QSTORE (input/output) REAL array, dimension (N**2+1) Stores eigenvectors of submatrices encountered during divide and conquer, packed together. QPTR points to beginning of the submatrices. QPTR (input/output) INTEGER array, dimension (N+2) List of indices pointing to beginning of submatrices stored in QSTORE. The submatrices are numbered starting at the bottom left of the divide and conquer tree, from left to right and bottom to top. PRMPTR (input) INTEGER array, dimension (N lg N) Contains a list of pointers which indicate where in PERM a level's permutation is stored. PRMPTR(i+1) - PRMPTR(i) indicates the size of the permutation and also the size of the full, non-deflated problem. PERM (input) INTEGER array, dimension (N lg N) Contains the permutations (from deflation and sorting) to be applied to each eigenblock. GIVPTR (input) INTEGER array, dimension (N lg N) Contains a list of pointers which indicate where in GIVCOL a level's Givens rotations are stored. GIVPTR(i+1) - GIVPTR(i) indicates the number of Givens rotations. GIVCOL (input) INTEGER array, dimension (2, N lg N) Each pair of numbers indicates a pair of columns to take place in a Givens rotation. GIVNUM (input) REAL array, dimension (2, N lg N) Each number indicates the S value to be used in the corresponding Givens rotation. INFO (output) INTEGER = 0: successful exit. < 0: if INFO = -i, the i-th argument had an illegal value. > 0: if INFO = 1, an eigenvalue did not converge ===================================================================== Test the input parameters. */ /* Parameter adjustments */ --d__; q_dim1 = *ldq; q_offset = 1 + q_dim1; q -= q_offset; --indxq; --qstore; --qptr; --prmptr; --perm; --givptr; givcol -= 3; givnum -= 3; --work; --rwork; --iwork; /* Function Body */ *info = 0; /* IF( ICOMPQ.LT.0 .OR. ICOMPQ.GT.1 ) THEN INFO = -1 ELSE IF( N.LT.0 ) THEN */ if (*n < 0) { *info = -1; } else if ((min(1,*n) > *cutpnt) || (*n < *cutpnt)) { *info = -2; } else if (*qsiz < *n) { *info = -3; } else if (*ldq < max(1,*n)) { *info = -9; } if (*info != 0) { i__1 = -(*info); xerbla_("CLAED7", &i__1); return 0; } /* Quick return if possible */ if (*n == 0) { return 0; } /* The following values are for bookkeeping purposes only. They are integer pointers which indicate the portion of the workspace used by a particular array in SLAED2 and SLAED3. */ iz = 1; idlmda = iz + *n; iw = idlmda + *n; iq = iw + *n; indx = 1; indxc = indx + *n; coltyp = indxc + *n; indxp = coltyp + *n; /* Form the z-vector which consists of the last row of Q_1 and the first row of Q_2. */ ptr = pow_ii(&c__2, tlvls) + 1; i__1 = *curlvl - 1; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = *tlvls - i__; ptr += pow_ii(&c__2, &i__2); /* L10: */ } curr = ptr + *curpbm; slaeda_(n, tlvls, curlvl, curpbm, &prmptr[1], &perm[1], &givptr[1], & givcol[3], &givnum[3], &qstore[1], &qptr[1], &rwork[iz], &rwork[ iz + *n], info); /* When solving the final problem, we no longer need the stored data, so we will overwrite the data from this level onto the previously used storage space. */ if (*curlvl == *tlvls) { qptr[curr] = 1; prmptr[curr] = 1; givptr[curr] = 1; } /* Sort and Deflate eigenvalues. */ claed8_(&k, n, qsiz, &q[q_offset], ldq, &d__[1], rho, cutpnt, &rwork[iz], &rwork[idlmda], &work[1], qsiz, &rwork[iw], &iwork[indxp], &iwork[ indx], &indxq[1], &perm[prmptr[curr]], &givptr[curr + 1], &givcol[ ((givptr[curr]) << (1)) + 1], &givnum[((givptr[curr]) << (1)) + 1] , info); prmptr[curr + 1] = prmptr[curr] + *n; givptr[curr + 1] += givptr[curr]; /* Solve Secular Equation. */ if (k != 0) { slaed9_(&k, &c__1, &k, n, &d__[1], &rwork[iq], &k, rho, &rwork[idlmda] , &rwork[iw], &qstore[qptr[curr]], &k, info); clacrm_(qsiz, &k, &work[1], qsiz, &qstore[qptr[curr]], &k, &q[ q_offset], ldq, &rwork[iq]); /* Computing 2nd power */ i__1 = k; qptr[curr + 1] = qptr[curr] + i__1 * i__1; if (*info != 0) { return 0; } /* Prepare the INDXQ sorting premutation. */ n1 = k; n2 = *n - k; ind1 = 1; ind2 = *n; slamrg_(&n1, &n2, &d__[1], &c__1, &c_n1, &indxq[1]); } else { qptr[curr + 1] = qptr[curr]; i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { indxq[i__] = i__; /* L20: */ } } return 0; /* End of CLAED7 */ } /* claed7_ */ /* Subroutine */ int claed8_(integer *k, integer *n, integer *qsiz, complex * q, integer *ldq, real *d__, real *rho, integer *cutpnt, real *z__, real *dlamda, complex *q2, integer *ldq2, real *w, integer *indxp, integer *indx, integer *indxq, integer *perm, integer *givptr, integer *givcol, real *givnum, integer *info) { /* System generated locals */ integer q_dim1, q_offset, q2_dim1, q2_offset, i__1; real r__1; /* Builtin functions */ double sqrt(doublereal); /* Local variables */ static real c__; static integer i__, j; static real s, t; static integer k2, n1, n2, jp, n1p1; static real eps, tau, tol; static integer jlam, imax, jmax; extern /* Subroutine */ int sscal_(integer *, real *, real *, integer *), ccopy_(integer *, complex *, integer *, complex *, integer *), csrot_(integer *, complex *, integer *, complex *, integer *, real *, real *), scopy_(integer *, real *, integer *, real *, integer *); extern doublereal slapy2_(real *, real *), slamch_(char *); extern /* Subroutine */ int clacpy_(char *, integer *, integer *, complex *, integer *, complex *, integer *), xerbla_(char *, integer *); extern integer isamax_(integer *, real *, integer *); extern /* Subroutine */ int slamrg_(integer *, integer *, real *, integer *, integer *, integer *); /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Oak Ridge National Lab, Argonne National Lab, Courant Institute, NAG Ltd., and Rice University September 30, 1994 Purpose ======= CLAED8 merges the two sets of eigenvalues together into a single sorted set. Then it tries to deflate the size of the problem. There are two ways in which deflation can occur: when two or more eigenvalues are close together or if there is a tiny element in the Z vector. For each such occurrence the order of the related secular equation problem is reduced by one. Arguments ========= K (output) INTEGER Contains the number of non-deflated eigenvalues. This is the order of the related secular equation. N (input) INTEGER The dimension of the symmetric tridiagonal matrix. N >= 0. QSIZ (input) INTEGER The dimension of the unitary matrix used to reduce the dense or band matrix to tridiagonal form. QSIZ >= N if ICOMPQ = 1. Q (input/output) COMPLEX array, dimension (LDQ,N) On entry, Q contains the eigenvectors of the partially solved system which has been previously updated in matrix multiplies with other partially solved eigensystems. On exit, Q contains the trailing (N-K) updated eigenvectors (those which were deflated) in its last N-K columns. LDQ (input) INTEGER The leading dimension of the array Q. LDQ >= max( 1, N ). D (input/output) REAL array, dimension (N) On entry, D contains the eigenvalues of the two submatrices to be combined. On exit, D contains the trailing (N-K) updated eigenvalues (those which were deflated) sorted into increasing order. RHO (input/output) REAL Contains the off diagonal element associated with the rank-1 cut which originally split the two submatrices which are now being recombined. RHO is modified during the computation to the value required by SLAED3. CUTPNT (input) INTEGER Contains the location of the last eigenvalue in the leading sub-matrix. MIN(1,N) <= CUTPNT <= N. Z (input) REAL array, dimension (N) On input this vector contains the updating vector (the last row of the first sub-eigenvector matrix and the first row of the second sub-eigenvector matrix). The contents of Z are destroyed during the updating process. DLAMDA (output) REAL array, dimension (N) Contains a copy of the first K eigenvalues which will be used by SLAED3 to form the secular equation. Q2 (output) COMPLEX array, dimension (LDQ2,N) If ICOMPQ = 0, Q2 is not referenced. Otherwise, Contains a copy of the first K eigenvectors which will be used by SLAED7 in a matrix multiply (SGEMM) to update the new eigenvectors. LDQ2 (input) INTEGER The leading dimension of the array Q2. LDQ2 >= max( 1, N ). W (output) REAL array, dimension (N) This will hold the first k values of the final deflation-altered z-vector and will be passed to SLAED3. INDXP (workspace) INTEGER array, dimension (N) This will contain the permutation used to place deflated values of D at the end of the array. On output INDXP(1:K) points to the nondeflated D-values and INDXP(K+1:N) points to the deflated eigenvalues. INDX (workspace) INTEGER array, dimension (N) This will contain the permutation used to sort the contents of D into ascending order. INDXQ (input) INTEGER array, dimension (N) This contains the permutation which separately sorts the two sub-problems in D into ascending order. Note that elements in the second half of this permutation must first have CUTPNT added to their values in order to be accurate. PERM (output) INTEGER array, dimension (N) Contains the permutations (from deflation and sorting) to be applied to each eigenblock. GIVPTR (output) INTEGER Contains the number of Givens rotations which took place in this subproblem. GIVCOL (output) INTEGER array, dimension (2, N) Each pair of numbers indicates a pair of columns to take place in a Givens rotation. GIVNUM (output) REAL array, dimension (2, N) Each number indicates the S value to be used in the corresponding Givens rotation. INFO (output) INTEGER = 0: successful exit. < 0: if INFO = -i, the i-th argument had an illegal value. ===================================================================== Test the input parameters. */ /* Parameter adjustments */ q_dim1 = *ldq; q_offset = 1 + q_dim1; q -= q_offset; --d__; --z__; --dlamda; q2_dim1 = *ldq2; q2_offset = 1 + q2_dim1; q2 -= q2_offset; --w; --indxp; --indx; --indxq; --perm; givcol -= 3; givnum -= 3; /* Function Body */ *info = 0; if (*n < 0) { *info = -2; } else if (*qsiz < *n) { *info = -3; } else if (*ldq < max(1,*n)) { *info = -5; } else if ((*cutpnt < min(1,*n)) || (*cutpnt > *n)) { *info = -8; } else if (*ldq2 < max(1,*n)) { *info = -12; } if (*info != 0) { i__1 = -(*info); xerbla_("CLAED8", &i__1); return 0; } /* Quick return if possible */ if (*n == 0) { return 0; } n1 = *cutpnt; n2 = *n - n1; n1p1 = n1 + 1; if (*rho < 0.f) { sscal_(&n2, &c_b1290, &z__[n1p1], &c__1); } /* Normalize z so that norm(z) = 1 */ t = 1.f / sqrt(2.f); i__1 = *n; for (j = 1; j <= i__1; ++j) { indx[j] = j; /* L10: */ } sscal_(n, &t, &z__[1], &c__1); *rho = (r__1 = *rho * 2.f, dabs(r__1)); /* Sort the eigenvalues into increasing order */ i__1 = *n; for (i__ = *cutpnt + 1; i__ <= i__1; ++i__) { indxq[i__] += *cutpnt; /* L20: */ } i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { dlamda[i__] = d__[indxq[i__]]; w[i__] = z__[indxq[i__]]; /* L30: */ } i__ = 1; j = *cutpnt + 1; slamrg_(&n1, &n2, &dlamda[1], &c__1, &c__1, &indx[1]); i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { d__[i__] = dlamda[indx[i__]]; z__[i__] = w[indx[i__]]; /* L40: */ } /* Calculate the allowable deflation tolerance */ imax = isamax_(n, &z__[1], &c__1); jmax = isamax_(n, &d__[1], &c__1); eps = slamch_("Epsilon"); tol = eps * 8.f * (r__1 = d__[jmax], dabs(r__1)); /* If the rank-1 modifier is small enough, no more needs to be done -- except to reorganize Q so that its columns correspond with the elements in D. */ if (*rho * (r__1 = z__[imax], dabs(r__1)) <= tol) { *k = 0; i__1 = *n; for (j = 1; j <= i__1; ++j) { perm[j] = indxq[indx[j]]; ccopy_(qsiz, &q[perm[j] * q_dim1 + 1], &c__1, &q2[j * q2_dim1 + 1] , &c__1); /* L50: */ } clacpy_("A", qsiz, n, &q2[q2_dim1 + 1], ldq2, &q[q_dim1 + 1], ldq); return 0; } /* If there are multiple eigenvalues then the problem deflates. Here the number of equal eigenvalues are found. As each equal eigenvalue is found, an elementary reflector is computed to rotate the corresponding eigensubspace so that the corresponding components of Z are zero in this new basis. */ *k = 0; *givptr = 0; k2 = *n + 1; i__1 = *n; for (j = 1; j <= i__1; ++j) { if (*rho * (r__1 = z__[j], dabs(r__1)) <= tol) { /* Deflate due to small z component. */ --k2; indxp[k2] = j; if (j == *n) { goto L100; } } else { jlam = j; goto L70; } /* L60: */ } L70: ++j; if (j > *n) { goto L90; } if (*rho * (r__1 = z__[j], dabs(r__1)) <= tol) { /* Deflate due to small z component. */ --k2; indxp[k2] = j; } else { /* Check if eigenvalues are close enough to allow deflation. */ s = z__[jlam]; c__ = z__[j]; /* Find sqrt(a**2+b**2) without overflow or destructive underflow. */ tau = slapy2_(&c__, &s); t = d__[j] - d__[jlam]; c__ /= tau; s = -s / tau; if ((r__1 = t * c__ * s, dabs(r__1)) <= tol) { /* Deflation is possible. */ z__[j] = tau; z__[jlam] = 0.f; /* Record the appropriate Givens rotation */ ++(*givptr); givcol[((*givptr) << (1)) + 1] = indxq[indx[jlam]]; givcol[((*givptr) << (1)) + 2] = indxq[indx[j]]; givnum[((*givptr) << (1)) + 1] = c__; givnum[((*givptr) << (1)) + 2] = s; csrot_(qsiz, &q[indxq[indx[jlam]] * q_dim1 + 1], &c__1, &q[indxq[ indx[j]] * q_dim1 + 1], &c__1, &c__, &s); t = d__[jlam] * c__ * c__ + d__[j] * s * s; d__[j] = d__[jlam] * s * s + d__[j] * c__ * c__; d__[jlam] = t; --k2; i__ = 1; L80: if (k2 + i__ <= *n) { if (d__[jlam] < d__[indxp[k2 + i__]]) { indxp[k2 + i__ - 1] = indxp[k2 + i__]; indxp[k2 + i__] = jlam; ++i__; goto L80; } else { indxp[k2 + i__ - 1] = jlam; } } else { indxp[k2 + i__ - 1] = jlam; } jlam = j; } else { ++(*k); w[*k] = z__[jlam]; dlamda[*k] = d__[jlam]; indxp[*k] = jlam; jlam = j; } } goto L70; L90: /* Record the last eigenvalue. */ ++(*k); w[*k] = z__[jlam]; dlamda[*k] = d__[jlam]; indxp[*k] = jlam; L100: /* Sort the eigenvalues and corresponding eigenvectors into DLAMDA and Q2 respectively. The eigenvalues/vectors which were not deflated go into the first K slots of DLAMDA and Q2 respectively, while those which were deflated go into the last N - K slots. */ i__1 = *n; for (j = 1; j <= i__1; ++j) { jp = indxp[j]; dlamda[j] = d__[jp]; perm[j] = indxq[indx[jp]]; ccopy_(qsiz, &q[perm[j] * q_dim1 + 1], &c__1, &q2[j * q2_dim1 + 1], & c__1); /* L110: */ } /* The deflated eigenvalues and their corresponding vectors go back into the last N - K slots of D and Q respectively. */ if (*k < *n) { i__1 = *n - *k; scopy_(&i__1, &dlamda[*k + 1], &c__1, &d__[*k + 1], &c__1); i__1 = *n - *k; clacpy_("A", qsiz, &i__1, &q2[(*k + 1) * q2_dim1 + 1], ldq2, &q[(*k + 1) * q_dim1 + 1], ldq); } return 0; /* End of CLAED8 */ } /* claed8_ */ /* Subroutine */ int clahqr_(logical *wantt, logical *wantz, integer *n, integer *ilo, integer *ihi, complex *h__, integer *ldh, complex *w, integer *iloz, integer *ihiz, complex *z__, integer *ldz, integer * info) { /* System generated locals */ integer h_dim1, h_offset, z_dim1, z_offset, i__1, i__2, i__3, i__4, i__5; real r__1, r__2, r__3, r__4, r__5, r__6; complex q__1, q__2, q__3, q__4; /* Builtin functions */ double r_imag(complex *); void c_sqrt(complex *, complex *), r_cnjg(complex *, complex *); double c_abs(complex *); /* Local variables */ static integer i__, j, k, l, m; static real s; static complex t, u, v[2], x, y; static integer i1, i2; static complex t1; static real t2; static complex v2; static real h10; static complex h11; static real h21; static complex h22; static integer nh, nz; static complex h11s; static integer itn, its; static real ulp; static complex sum; static real tst1; static complex temp; extern /* Subroutine */ int cscal_(integer *, complex *, complex *, integer *), ccopy_(integer *, complex *, integer *, complex *, integer *); static real rtemp, rwork[1]; extern /* Subroutine */ int clarfg_(integer *, complex *, complex *, integer *, complex *); extern /* Complex */ VOID cladiv_(complex *, complex *, complex *); extern doublereal slamch_(char *), clanhs_(char *, integer *, complex *, integer *, real *); static real smlnum; /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= CLAHQR is an auxiliary routine called by CHSEQR to update the eigenvalues and Schur decomposition already computed by CHSEQR, by dealing with the Hessenberg submatrix in rows and columns ILO to IHI. Arguments ========= WANTT (input) LOGICAL = .TRUE. : the full Schur form T is required; = .FALSE.: only eigenvalues are required. WANTZ (input) LOGICAL = .TRUE. : the matrix of Schur vectors Z is required; = .FALSE.: Schur vectors are not required. N (input) INTEGER The order of the matrix H. N >= 0. ILO (input) INTEGER IHI (input) INTEGER It is assumed that H is already upper triangular in rows and columns IHI+1:N, and that H(ILO,ILO-1) = 0 (unless ILO = 1). CLAHQR works primarily with the Hessenberg submatrix in rows and columns ILO to IHI, but applies transformations to all of H if WANTT is .TRUE.. 1 <= ILO <= max(1,IHI); IHI <= N. H (input/output) COMPLEX array, dimension (LDH,N) On entry, the upper Hessenberg matrix H. On exit, if WANTT is .TRUE., H is upper triangular in rows and columns ILO:IHI, with any 2-by-2 diagonal blocks in standard form. If WANTT is .FALSE., the contents of H are unspecified on exit. LDH (input) INTEGER The leading dimension of the array H. LDH >= max(1,N). W (output) COMPLEX array, dimension (N) The computed eigenvalues ILO to IHI are stored in the corresponding elements of W. If WANTT is .TRUE., the eigenvalues are stored in the same order as on the diagonal of the Schur form returned in H, with W(i) = H(i,i). ILOZ (input) INTEGER IHIZ (input) INTEGER Specify the rows of Z to which transformations must be applied if WANTZ is .TRUE.. 1 <= ILOZ <= ILO; IHI <= IHIZ <= N. Z (input/output) COMPLEX array, dimension (LDZ,N) If WANTZ is .TRUE., on entry Z must contain the current matrix Z of transformations accumulated by CHSEQR, and on exit Z has been updated; transformations are applied only to the submatrix Z(ILOZ:IHIZ,ILO:IHI). If WANTZ is .FALSE., Z is not referenced. LDZ (input) INTEGER The leading dimension of the array Z. LDZ >= max(1,N). INFO (output) INTEGER = 0: successful exit > 0: if INFO = i, CLAHQR failed to compute all the eigenvalues ILO to IHI in a total of 30*(IHI-ILO+1) iterations; elements i+1:ihi of W contain those eigenvalues which have been successfully computed. ===================================================================== */ /* Parameter adjustments */ h_dim1 = *ldh; h_offset = 1 + h_dim1; h__ -= h_offset; --w; z_dim1 = *ldz; z_offset = 1 + z_dim1; z__ -= z_offset; /* Function Body */ *info = 0; /* Quick return if possible */ if (*n == 0) { return 0; } if (*ilo == *ihi) { i__1 = *ilo; i__2 = *ilo + *ilo * h_dim1; w[i__1].r = h__[i__2].r, w[i__1].i = h__[i__2].i; return 0; } nh = *ihi - *ilo + 1; nz = *ihiz - *iloz + 1; /* Set machine-dependent constants for the stopping criterion. If norm(H) <= sqrt(OVFL), overflow should not occur. */ ulp = slamch_("Precision"); smlnum = slamch_("Safe minimum") / ulp; /* I1 and I2 are the indices of the first row and last column of H to which transformations must be applied. If eigenvalues only are being computed, I1 and I2 are set inside the main loop. */ if (*wantt) { i1 = 1; i2 = *n; } /* ITN is the total number of QR iterations allowed. */ itn = nh * 30; /* The main loop begins here. I is the loop index and decreases from IHI to ILO in steps of 1. Each iteration of the loop works with the active submatrix in rows and columns L to I. Eigenvalues I+1 to IHI have already converged. Either L = ILO, or H(L,L-1) is negligible so that the matrix splits. */ i__ = *ihi; L10: if (i__ < *ilo) { goto L130; } /* Perform QR iterations on rows and columns ILO to I until a submatrix of order 1 splits off at the bottom because a subdiagonal element has become negligible. */ l = *ilo; i__1 = itn; for (its = 0; its <= i__1; ++its) { /* Look for a single small subdiagonal element. */ i__2 = l + 1; for (k = i__; k >= i__2; --k) { i__3 = k - 1 + (k - 1) * h_dim1; i__4 = k + k * h_dim1; tst1 = (r__1 = h__[i__3].r, dabs(r__1)) + (r__2 = r_imag(&h__[k - 1 + (k - 1) * h_dim1]), dabs(r__2)) + ((r__3 = h__[i__4] .r, dabs(r__3)) + (r__4 = r_imag(&h__[k + k * h_dim1]), dabs(r__4))); if (tst1 == 0.f) { i__3 = i__ - l + 1; tst1 = clanhs_("1", &i__3, &h__[l + l * h_dim1], ldh, rwork); } i__3 = k + (k - 1) * h_dim1; /* Computing MAX */ r__2 = ulp * tst1; if ((r__1 = h__[i__3].r, dabs(r__1)) <= dmax(r__2,smlnum)) { goto L30; } /* L20: */ } L30: l = k; if (l > *ilo) { /* H(L,L-1) is negligible */ i__2 = l + (l - 1) * h_dim1; h__[i__2].r = 0.f, h__[i__2].i = 0.f; } /* Exit from loop if a submatrix of order 1 has split off. */ if (l >= i__) { goto L120; } /* Now the active submatrix is in rows and columns L to I. If eigenvalues only are being computed, only the active submatrix need be transformed. */ if (! (*wantt)) { i1 = l; i2 = i__; } if ((its == 10) || (its == 20)) { /* Exceptional shift. */ i__2 = i__ + (i__ - 1) * h_dim1; s = (r__1 = h__[i__2].r, dabs(r__1)) * .75f; i__2 = i__ + i__ * h_dim1; q__1.r = s + h__[i__2].r, q__1.i = h__[i__2].i; t.r = q__1.r, t.i = q__1.i; } else { /* Wilkinson's shift. */ i__2 = i__ + i__ * h_dim1; t.r = h__[i__2].r, t.i = h__[i__2].i; i__2 = i__ - 1 + i__ * h_dim1; i__3 = i__ + (i__ - 1) * h_dim1; r__1 = h__[i__3].r; q__1.r = r__1 * h__[i__2].r, q__1.i = r__1 * h__[i__2].i; u.r = q__1.r, u.i = q__1.i; if ((u.r != 0.f) || (u.i != 0.f)) { i__2 = i__ - 1 + (i__ - 1) * h_dim1; q__2.r = h__[i__2].r - t.r, q__2.i = h__[i__2].i - t.i; q__1.r = q__2.r * .5f, q__1.i = q__2.i * .5f; x.r = q__1.r, x.i = q__1.i; q__3.r = x.r * x.r - x.i * x.i, q__3.i = x.r * x.i + x.i * x.r; q__2.r = q__3.r + u.r, q__2.i = q__3.i + u.i; c_sqrt(&q__1, &q__2); y.r = q__1.r, y.i = q__1.i; if (x.r * y.r + r_imag(&x) * r_imag(&y) < 0.f) { q__1.r = -y.r, q__1.i = -y.i; y.r = q__1.r, y.i = q__1.i; } q__3.r = x.r + y.r, q__3.i = x.i + y.i; cladiv_(&q__2, &u, &q__3); q__1.r = t.r - q__2.r, q__1.i = t.i - q__2.i; t.r = q__1.r, t.i = q__1.i; } } /* Look for two consecutive small subdiagonal elements. */ i__2 = l + 1; for (m = i__ - 1; m >= i__2; --m) { /* Determine the effect of starting the single-shift QR iteration at row M, and see if this would make H(M,M-1) negligible. */ i__3 = m + m * h_dim1; h11.r = h__[i__3].r, h11.i = h__[i__3].i; i__3 = m + 1 + (m + 1) * h_dim1; h22.r = h__[i__3].r, h22.i = h__[i__3].i; q__1.r = h11.r - t.r, q__1.i = h11.i - t.i; h11s.r = q__1.r, h11s.i = q__1.i; i__3 = m + 1 + m * h_dim1; h21 = h__[i__3].r; s = (r__1 = h11s.r, dabs(r__1)) + (r__2 = r_imag(&h11s), dabs( r__2)) + dabs(h21); q__1.r = h11s.r / s, q__1.i = h11s.i / s; h11s.r = q__1.r, h11s.i = q__1.i; h21 /= s; v[0].r = h11s.r, v[0].i = h11s.i; v[1].r = h21, v[1].i = 0.f; i__3 = m + (m - 1) * h_dim1; h10 = h__[i__3].r; tst1 = ((r__1 = h11s.r, dabs(r__1)) + (r__2 = r_imag(&h11s), dabs( r__2))) * ((r__3 = h11.r, dabs(r__3)) + (r__4 = r_imag(& h11), dabs(r__4)) + ((r__5 = h22.r, dabs(r__5)) + (r__6 = r_imag(&h22), dabs(r__6)))); if ((r__1 = h10 * h21, dabs(r__1)) <= ulp * tst1) { goto L50; } /* L40: */ } i__2 = l + l * h_dim1; h11.r = h__[i__2].r, h11.i = h__[i__2].i; i__2 = l + 1 + (l + 1) * h_dim1; h22.r = h__[i__2].r, h22.i = h__[i__2].i; q__1.r = h11.r - t.r, q__1.i = h11.i - t.i; h11s.r = q__1.r, h11s.i = q__1.i; i__2 = l + 1 + l * h_dim1; h21 = h__[i__2].r; s = (r__1 = h11s.r, dabs(r__1)) + (r__2 = r_imag(&h11s), dabs(r__2)) + dabs(h21); q__1.r = h11s.r / s, q__1.i = h11s.i / s; h11s.r = q__1.r, h11s.i = q__1.i; h21 /= s; v[0].r = h11s.r, v[0].i = h11s.i; v[1].r = h21, v[1].i = 0.f; L50: /* Single-shift QR step */ i__2 = i__ - 1; for (k = m; k <= i__2; ++k) { /* The first iteration of this loop determines a reflection G from the vector V and applies it from left and right to H, thus creating a nonzero bulge below the subdiagonal. Each subsequent iteration determines a reflection G to restore the Hessenberg form in the (K-1)th column, and thus chases the bulge one step toward the bottom of the active submatrix. V(2) is always real before the call to CLARFG, and hence after the call T2 ( = T1*V(2) ) is also real. */ if (k > m) { ccopy_(&c__2, &h__[k + (k - 1) * h_dim1], &c__1, v, &c__1); } clarfg_(&c__2, v, &v[1], &c__1, &t1); if (k > m) { i__3 = k + (k - 1) * h_dim1; h__[i__3].r = v[0].r, h__[i__3].i = v[0].i; i__3 = k + 1 + (k - 1) * h_dim1; h__[i__3].r = 0.f, h__[i__3].i = 0.f; } v2.r = v[1].r, v2.i = v[1].i; q__1.r = t1.r * v2.r - t1.i * v2.i, q__1.i = t1.r * v2.i + t1.i * v2.r; t2 = q__1.r; /* Apply G from the left to transform the rows of the matrix in columns K to I2. */ i__3 = i2; for (j = k; j <= i__3; ++j) { r_cnjg(&q__3, &t1); i__4 = k + j * h_dim1; q__2.r = q__3.r * h__[i__4].r - q__3.i * h__[i__4].i, q__2.i = q__3.r * h__[i__4].i + q__3.i * h__[i__4].r; i__5 = k + 1 + j * h_dim1; q__4.r = t2 * h__[i__5].r, q__4.i = t2 * h__[i__5].i; q__1.r = q__2.r + q__4.r, q__1.i = q__2.i + q__4.i; sum.r = q__1.r, sum.i = q__1.i; i__4 = k + j * h_dim1; i__5 = k + j * h_dim1; q__1.r = h__[i__5].r - sum.r, q__1.i = h__[i__5].i - sum.i; h__[i__4].r = q__1.r, h__[i__4].i = q__1.i; i__4 = k + 1 + j * h_dim1; i__5 = k + 1 + j * h_dim1; q__2.r = sum.r * v2.r - sum.i * v2.i, q__2.i = sum.r * v2.i + sum.i * v2.r; q__1.r = h__[i__5].r - q__2.r, q__1.i = h__[i__5].i - q__2.i; h__[i__4].r = q__1.r, h__[i__4].i = q__1.i; /* L60: */ } /* Apply G from the right to transform the columns of the matrix in rows I1 to min(K+2,I). Computing MIN */ i__4 = k + 2; i__3 = min(i__4,i__); for (j = i1; j <= i__3; ++j) { i__4 = j + k * h_dim1; q__2.r = t1.r * h__[i__4].r - t1.i * h__[i__4].i, q__2.i = t1.r * h__[i__4].i + t1.i * h__[i__4].r; i__5 = j + (k + 1) * h_dim1; q__3.r = t2 * h__[i__5].r, q__3.i = t2 * h__[i__5].i; q__1.r = q__2.r + q__3.r, q__1.i = q__2.i + q__3.i; sum.r = q__1.r, sum.i = q__1.i; i__4 = j + k * h_dim1; i__5 = j + k * h_dim1; q__1.r = h__[i__5].r - sum.r, q__1.i = h__[i__5].i - sum.i; h__[i__4].r = q__1.r, h__[i__4].i = q__1.i; i__4 = j + (k + 1) * h_dim1; i__5 = j + (k + 1) * h_dim1; r_cnjg(&q__3, &v2); q__2.r = sum.r * q__3.r - sum.i * q__3.i, q__2.i = sum.r * q__3.i + sum.i * q__3.r; q__1.r = h__[i__5].r - q__2.r, q__1.i = h__[i__5].i - q__2.i; h__[i__4].r = q__1.r, h__[i__4].i = q__1.i; /* L70: */ } if (*wantz) { /* Accumulate transformations in the matrix Z */ i__3 = *ihiz; for (j = *iloz; j <= i__3; ++j) { i__4 = j + k * z_dim1; q__2.r = t1.r * z__[i__4].r - t1.i * z__[i__4].i, q__2.i = t1.r * z__[i__4].i + t1.i * z__[i__4].r; i__5 = j + (k + 1) * z_dim1; q__3.r = t2 * z__[i__5].r, q__3.i = t2 * z__[i__5].i; q__1.r = q__2.r + q__3.r, q__1.i = q__2.i + q__3.i; sum.r = q__1.r, sum.i = q__1.i; i__4 = j + k * z_dim1; i__5 = j + k * z_dim1; q__1.r = z__[i__5].r - sum.r, q__1.i = z__[i__5].i - sum.i; z__[i__4].r = q__1.r, z__[i__4].i = q__1.i; i__4 = j + (k + 1) * z_dim1; i__5 = j + (k + 1) * z_dim1; r_cnjg(&q__3, &v2); q__2.r = sum.r * q__3.r - sum.i * q__3.i, q__2.i = sum.r * q__3.i + sum.i * q__3.r; q__1.r = z__[i__5].r - q__2.r, q__1.i = z__[i__5].i - q__2.i; z__[i__4].r = q__1.r, z__[i__4].i = q__1.i; /* L80: */ } } if (k == m && m > l) { /* If the QR step was started at row M > L because two consecutive small subdiagonals were found, then extra scaling must be performed to ensure that H(M,M-1) remains real. */ q__1.r = 1.f - t1.r, q__1.i = 0.f - t1.i; temp.r = q__1.r, temp.i = q__1.i; r__1 = c_abs(&temp); q__1.r = temp.r / r__1, q__1.i = temp.i / r__1; temp.r = q__1.r, temp.i = q__1.i; i__3 = m + 1 + m * h_dim1; i__4 = m + 1 + m * h_dim1; r_cnjg(&q__2, &temp); q__1.r = h__[i__4].r * q__2.r - h__[i__4].i * q__2.i, q__1.i = h__[i__4].r * q__2.i + h__[i__4].i * q__2.r; h__[i__3].r = q__1.r, h__[i__3].i = q__1.i; if (m + 2 <= i__) { i__3 = m + 2 + (m + 1) * h_dim1; i__4 = m + 2 + (m + 1) * h_dim1; q__1.r = h__[i__4].r * temp.r - h__[i__4].i * temp.i, q__1.i = h__[i__4].r * temp.i + h__[i__4].i * temp.r; h__[i__3].r = q__1.r, h__[i__3].i = q__1.i; } i__3 = i__; for (j = m; j <= i__3; ++j) { if (j != m + 1) { if (i2 > j) { i__4 = i2 - j; cscal_(&i__4, &temp, &h__[j + (j + 1) * h_dim1], ldh); } i__4 = j - i1; r_cnjg(&q__1, &temp); cscal_(&i__4, &q__1, &h__[i1 + j * h_dim1], &c__1); if (*wantz) { r_cnjg(&q__1, &temp); cscal_(&nz, &q__1, &z__[*iloz + j * z_dim1], & c__1); } } /* L90: */ } } /* L100: */ } /* Ensure that H(I,I-1) is real. */ i__2 = i__ + (i__ - 1) * h_dim1; temp.r = h__[i__2].r, temp.i = h__[i__2].i; if (r_imag(&temp) != 0.f) { rtemp = c_abs(&temp); i__2 = i__ + (i__ - 1) * h_dim1; h__[i__2].r = rtemp, h__[i__2].i = 0.f; q__1.r = temp.r / rtemp, q__1.i = temp.i / rtemp; temp.r = q__1.r, temp.i = q__1.i; if (i2 > i__) { i__2 = i2 - i__; r_cnjg(&q__1, &temp); cscal_(&i__2, &q__1, &h__[i__ + (i__ + 1) * h_dim1], ldh); } i__2 = i__ - i1; cscal_(&i__2, &temp, &h__[i1 + i__ * h_dim1], &c__1); if (*wantz) { cscal_(&nz, &temp, &z__[*iloz + i__ * z_dim1], &c__1); } } /* L110: */ } /* Failure to converge in remaining number of iterations */ *info = i__; return 0; L120: /* H(I,I-1) is negligible: one eigenvalue has converged. */ i__1 = i__; i__2 = i__ + i__ * h_dim1; w[i__1].r = h__[i__2].r, w[i__1].i = h__[i__2].i; /* Decrement number of remaining iterations, and return to start of the main loop with new value of I. */ itn -= its; i__ = l - 1; goto L10; L130: return 0; /* End of CLAHQR */ } /* clahqr_ */ /* Subroutine */ int clahrd_(integer *n, integer *k, integer *nb, complex *a, integer *lda, complex *tau, complex *t, integer *ldt, complex *y, integer *ldy) { /* System generated locals */ integer a_dim1, a_offset, t_dim1, t_offset, y_dim1, y_offset, i__1, i__2, i__3; complex q__1; /* Local variables */ static integer i__; static complex ei; extern /* Subroutine */ int cscal_(integer *, complex *, complex *, integer *), cgemv_(char *, integer *, integer *, complex *, complex *, integer *, complex *, integer *, complex *, complex *, integer *), ccopy_(integer *, complex *, integer *, complex *, integer *), caxpy_(integer *, complex *, complex *, integer *, complex *, integer *), ctrmv_(char *, char *, char *, integer *, complex *, integer *, complex *, integer *), clarfg_(integer *, complex *, complex *, integer *, complex *), clacgv_(integer *, complex *, integer *); /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= CLAHRD reduces the first NB columns of a complex general n-by-(n-k+1) matrix A so that elements below the k-th subdiagonal are zero. The reduction is performed by a unitary similarity transformation Q' * A * Q. The routine returns the matrices V and T which determine Q as a block reflector I - V*T*V', and also the matrix Y = A * V * T. This is an auxiliary routine called by CGEHRD. Arguments ========= N (input) INTEGER The order of the matrix A. K (input) INTEGER The offset for the reduction. Elements below the k-th subdiagonal in the first NB columns are reduced to zero. NB (input) INTEGER The number of columns to be reduced. A (input/output) COMPLEX array, dimension (LDA,N-K+1) On entry, the n-by-(n-k+1) general matrix A. On exit, the elements on and above the k-th subdiagonal in the first NB columns are overwritten with the corresponding elements of the reduced matrix; the elements below the k-th subdiagonal, with the array TAU, represent the matrix Q as a product of elementary reflectors. The other columns of A are unchanged. See Further Details. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,N). TAU (output) COMPLEX array, dimension (NB) The scalar factors of the elementary reflectors. See Further Details. T (output) COMPLEX array, dimension (LDT,NB) The upper triangular matrix T. LDT (input) INTEGER The leading dimension of the array T. LDT >= NB. Y (output) COMPLEX array, dimension (LDY,NB) The n-by-nb matrix Y. LDY (input) INTEGER The leading dimension of the array Y. LDY >= max(1,N). Further Details =============== The matrix Q is represented as a product of nb elementary reflectors Q = H(1) H(2) . . . H(nb). Each H(i) has the form H(i) = I - tau * v * v' where tau is a complex scalar, and v is a complex vector with v(1:i+k-1) = 0, v(i+k) = 1; v(i+k+1:n) is stored on exit in A(i+k+1:n,i), and tau in TAU(i). The elements of the vectors v together form the (n-k+1)-by-nb matrix V which is needed, with T and Y, to apply the transformation to the unreduced part of the matrix, using an update of the form: A := (I - V*T*V') * (A - Y*V'). The contents of A on exit are illustrated by the following example with n = 7, k = 3 and nb = 2: ( a h a a a ) ( a h a a a ) ( a h a a a ) ( h h a a a ) ( v1 h a a a ) ( v1 v2 a a a ) ( v1 v2 a a a ) where a denotes an element of the original matrix A, h denotes a modified element of the upper Hessenberg matrix H, and vi denotes an element of the vector defining H(i). ===================================================================== Quick return if possible */ /* Parameter adjustments */ --tau; a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; t_dim1 = *ldt; t_offset = 1 + t_dim1; t -= t_offset; y_dim1 = *ldy; y_offset = 1 + y_dim1; y -= y_offset; /* Function Body */ if (*n <= 1) { return 0; } i__1 = *nb; for (i__ = 1; i__ <= i__1; ++i__) { if (i__ > 1) { /* Update A(1:n,i) Compute i-th column of A - Y * V' */ i__2 = i__ - 1; clacgv_(&i__2, &a[*k + i__ - 1 + a_dim1], lda); i__2 = i__ - 1; q__1.r = -1.f, q__1.i = -0.f; cgemv_("No transpose", n, &i__2, &q__1, &y[y_offset], ldy, &a[*k + i__ - 1 + a_dim1], lda, &c_b56, &a[i__ * a_dim1 + 1], & c__1); i__2 = i__ - 1; clacgv_(&i__2, &a[*k + i__ - 1 + a_dim1], lda); /* Apply I - V * T' * V' to this column (call it b) from the left, using the last column of T as workspace Let V = ( V1 ) and b = ( b1 ) (first I-1 rows) ( V2 ) ( b2 ) where V1 is unit lower triangular w := V1' * b1 */ i__2 = i__ - 1; ccopy_(&i__2, &a[*k + 1 + i__ * a_dim1], &c__1, &t[*nb * t_dim1 + 1], &c__1); i__2 = i__ - 1; ctrmv_("Lower", "Conjugate transpose", "Unit", &i__2, &a[*k + 1 + a_dim1], lda, &t[*nb * t_dim1 + 1], &c__1); /* w := w + V2'*b2 */ i__2 = *n - *k - i__ + 1; i__3 = i__ - 1; cgemv_("Conjugate transpose", &i__2, &i__3, &c_b56, &a[*k + i__ + a_dim1], lda, &a[*k + i__ + i__ * a_dim1], &c__1, &c_b56, &t[*nb * t_dim1 + 1], &c__1); /* w := T'*w */ i__2 = i__ - 1; ctrmv_("Upper", "Conjugate transpose", "Non-unit", &i__2, &t[ t_offset], ldt, &t[*nb * t_dim1 + 1], &c__1); /* b2 := b2 - V2*w */ i__2 = *n - *k - i__ + 1; i__3 = i__ - 1; q__1.r = -1.f, q__1.i = -0.f; cgemv_("No transpose", &i__2, &i__3, &q__1, &a[*k + i__ + a_dim1], lda, &t[*nb * t_dim1 + 1], &c__1, &c_b56, &a[*k + i__ + i__ * a_dim1], &c__1); /* b1 := b1 - V1*w */ i__2 = i__ - 1; ctrmv_("Lower", "No transpose", "Unit", &i__2, &a[*k + 1 + a_dim1] , lda, &t[*nb * t_dim1 + 1], &c__1); i__2 = i__ - 1; q__1.r = -1.f, q__1.i = -0.f; caxpy_(&i__2, &q__1, &t[*nb * t_dim1 + 1], &c__1, &a[*k + 1 + i__ * a_dim1], &c__1); i__2 = *k + i__ - 1 + (i__ - 1) * a_dim1; a[i__2].r = ei.r, a[i__2].i = ei.i; } /* Generate the elementary reflector H(i) to annihilate A(k+i+1:n,i) */ i__2 = *k + i__ + i__ * a_dim1; ei.r = a[i__2].r, ei.i = a[i__2].i; i__2 = *n - *k - i__ + 1; /* Computing MIN */ i__3 = *k + i__ + 1; clarfg_(&i__2, &ei, &a[min(i__3,*n) + i__ * a_dim1], &c__1, &tau[i__]) ; i__2 = *k + i__ + i__ * a_dim1; a[i__2].r = 1.f, a[i__2].i = 0.f; /* Compute Y(1:n,i) */ i__2 = *n - *k - i__ + 1; cgemv_("No transpose", n, &i__2, &c_b56, &a[(i__ + 1) * a_dim1 + 1], lda, &a[*k + i__ + i__ * a_dim1], &c__1, &c_b55, &y[i__ * y_dim1 + 1], &c__1); i__2 = *n - *k - i__ + 1; i__3 = i__ - 1; cgemv_("Conjugate transpose", &i__2, &i__3, &c_b56, &a[*k + i__ + a_dim1], lda, &a[*k + i__ + i__ * a_dim1], &c__1, &c_b55, &t[ i__ * t_dim1 + 1], &c__1); i__2 = i__ - 1; q__1.r = -1.f, q__1.i = -0.f; cgemv_("No transpose", n, &i__2, &q__1, &y[y_offset], ldy, &t[i__ * t_dim1 + 1], &c__1, &c_b56, &y[i__ * y_dim1 + 1], &c__1); cscal_(n, &tau[i__], &y[i__ * y_dim1 + 1], &c__1); /* Compute T(1:i,i) */ i__2 = i__ - 1; i__3 = i__; q__1.r = -tau[i__3].r, q__1.i = -tau[i__3].i; cscal_(&i__2, &q__1, &t[i__ * t_dim1 + 1], &c__1); i__2 = i__ - 1; ctrmv_("Upper", "No transpose", "Non-unit", &i__2, &t[t_offset], ldt, &t[i__ * t_dim1 + 1], &c__1) ; i__2 = i__ + i__ * t_dim1; i__3 = i__; t[i__2].r = tau[i__3].r, t[i__2].i = tau[i__3].i; /* L10: */ } i__1 = *k + *nb + *nb * a_dim1; a[i__1].r = ei.r, a[i__1].i = ei.i; return 0; /* End of CLAHRD */ } /* clahrd_ */ /* Subroutine */ int clals0_(integer *icompq, integer *nl, integer *nr, integer *sqre, integer *nrhs, complex *b, integer *ldb, complex *bx, integer *ldbx, integer *perm, integer *givptr, integer *givcol, integer *ldgcol, real *givnum, integer *ldgnum, real *poles, real * difl, real *difr, real *z__, integer *k, real *c__, real *s, real * rwork, integer *info) { /* System generated locals */ integer givcol_dim1, givcol_offset, difr_dim1, difr_offset, givnum_dim1, givnum_offset, poles_dim1, poles_offset, b_dim1, b_offset, bx_dim1, bx_offset, i__1, i__2, i__3, i__4, i__5; real r__1; complex q__1; /* Builtin functions */ double r_imag(complex *); /* Local variables */ static integer i__, j, m, n; static real dj; static integer nlp1, jcol; static real temp; static integer jrow; extern doublereal snrm2_(integer *, real *, integer *); static real diflj, difrj, dsigj; extern /* Subroutine */ int ccopy_(integer *, complex *, integer *, complex *, integer *), sgemv_(char *, integer *, integer *, real * , real *, integer *, real *, integer *, real *, real *, integer *), csrot_(integer *, complex *, integer *, complex *, integer *, real *, real *); extern doublereal slamc3_(real *, real *); extern /* Subroutine */ int clascl_(char *, integer *, integer *, real *, real *, integer *, integer *, complex *, integer *, integer *), csscal_(integer *, real *, complex *, integer *), clacpy_(char *, integer *, integer *, complex *, integer *, complex *, integer *), xerbla_(char *, integer *); static real dsigjp; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University December 1, 1999 Purpose ======= CLALS0 applies back the multiplying factors of either the left or the right singular vector matrix of a diagonal matrix appended by a row to the right hand side matrix B in solving the least squares problem using the divide-and-conquer SVD approach. For the left singular vector matrix, three types of orthogonal matrices are involved: (1L) Givens rotations: the number of such rotations is GIVPTR; the pairs of columns/rows they were applied to are stored in GIVCOL; and the C- and S-values of these rotations are stored in GIVNUM. (2L) Permutation. The (NL+1)-st row of B is to be moved to the first row, and for J=2:N, PERM(J)-th row of B is to be moved to the J-th row. (3L) The left singular vector matrix of the remaining matrix. For the right singular vector matrix, four types of orthogonal matrices are involved: (1R) The right singular vector matrix of the remaining matrix. (2R) If SQRE = 1, one extra Givens rotation to generate the right null space. (3R) The inverse transformation of (2L). (4R) The inverse transformation of (1L). Arguments ========= ICOMPQ (input) INTEGER Specifies whether singular vectors are to be computed in factored form: = 0: Left singular vector matrix. = 1: Right singular vector matrix. NL (input) INTEGER The row dimension of the upper block. NL >= 1. NR (input) INTEGER The row dimension of the lower block. NR >= 1. SQRE (input) INTEGER = 0: the lower block is an NR-by-NR square matrix. = 1: the lower block is an NR-by-(NR+1) rectangular matrix. The bidiagonal matrix has row dimension N = NL + NR + 1, and column dimension M = N + SQRE. NRHS (input) INTEGER The number of columns of B and BX. NRHS must be at least 1. B (input/output) COMPLEX array, dimension ( LDB, NRHS ) On input, B contains the right hand sides of the least squares problem in rows 1 through M. On output, B contains the solution X in rows 1 through N. LDB (input) INTEGER The leading dimension of B. LDB must be at least max(1,MAX( M, N ) ). BX (workspace) COMPLEX array, dimension ( LDBX, NRHS ) LDBX (input) INTEGER The leading dimension of BX. PERM (input) INTEGER array, dimension ( N ) The permutations (from deflation and sorting) applied to the two blocks. GIVPTR (input) INTEGER The number of Givens rotations which took place in this subproblem. GIVCOL (input) INTEGER array, dimension ( LDGCOL, 2 ) Each pair of numbers indicates a pair of rows/columns involved in a Givens rotation. LDGCOL (input) INTEGER The leading dimension of GIVCOL, must be at least N. GIVNUM (input) REAL array, dimension ( LDGNUM, 2 ) Each number indicates the C or S value used in the corresponding Givens rotation. LDGNUM (input) INTEGER The leading dimension of arrays DIFR, POLES and GIVNUM, must be at least K. POLES (input) REAL array, dimension ( LDGNUM, 2 ) On entry, POLES(1:K, 1) contains the new singular values obtained from solving the secular equation, and POLES(1:K, 2) is an array containing the poles in the secular equation. DIFL (input) REAL array, dimension ( K ). On entry, DIFL(I) is the distance between I-th updated (undeflated) singular value and the I-th (undeflated) old singular value. DIFR (input) REAL array, dimension ( LDGNUM, 2 ). On entry, DIFR(I, 1) contains the distances between I-th updated (undeflated) singular value and the I+1-th (undeflated) old singular value. And DIFR(I, 2) is the normalizing factor for the I-th right singular vector. Z (input) REAL array, dimension ( K ) Contain the components of the deflation-adjusted updating row vector. K (input) INTEGER Contains the dimension of the non-deflated matrix, This is the order of the related secular equation. 1 <= K <=N. C (input) REAL C contains garbage if SQRE =0 and the C-value of a Givens rotation related to the right null space if SQRE = 1. S (input) REAL S contains garbage if SQRE =0 and the S-value of a Givens rotation related to the right null space if SQRE = 1. RWORK (workspace) REAL array, dimension ( K*(1+NRHS) + 2*NRHS ) INFO (output) INTEGER = 0: successful exit. < 0: if INFO = -i, the i-th argument had an illegal value. Further Details =============== Based on contributions by Ming Gu and Ren-Cang Li, Computer Science Division, University of California at Berkeley, USA Osni Marques, LBNL/NERSC, USA ===================================================================== Test the input parameters. */ /* Parameter adjustments */ b_dim1 = *ldb; b_offset = 1 + b_dim1; b -= b_offset; bx_dim1 = *ldbx; bx_offset = 1 + bx_dim1; bx -= bx_offset; --perm; givcol_dim1 = *ldgcol; givcol_offset = 1 + givcol_dim1; givcol -= givcol_offset; difr_dim1 = *ldgnum; difr_offset = 1 + difr_dim1; difr -= difr_offset; poles_dim1 = *ldgnum; poles_offset = 1 + poles_dim1; poles -= poles_offset; givnum_dim1 = *ldgnum; givnum_offset = 1 + givnum_dim1; givnum -= givnum_offset; --difl; --z__; --rwork; /* Function Body */ *info = 0; if ((*icompq < 0) || (*icompq > 1)) { *info = -1; } else if (*nl < 1) { *info = -2; } else if (*nr < 1) { *info = -3; } else if ((*sqre < 0) || (*sqre > 1)) { *info = -4; } n = *nl + *nr + 1; if (*nrhs < 1) { *info = -5; } else if (*ldb < n) { *info = -7; } else if (*ldbx < n) { *info = -9; } else if (*givptr < 0) { *info = -11; } else if (*ldgcol < n) { *info = -13; } else if (*ldgnum < n) { *info = -15; } else if (*k < 1) { *info = -20; } if (*info != 0) { i__1 = -(*info); xerbla_("CLALS0", &i__1); return 0; } m = n + *sqre; nlp1 = *nl + 1; if (*icompq == 0) { /* Apply back orthogonal transformations from the left. Step (1L): apply back the Givens rotations performed. */ i__1 = *givptr; for (i__ = 1; i__ <= i__1; ++i__) { csrot_(nrhs, &b[givcol[i__ + ((givcol_dim1) << (1))] + b_dim1], ldb, &b[givcol[i__ + givcol_dim1] + b_dim1], ldb, &givnum[ i__ + ((givnum_dim1) << (1))], &givnum[i__ + givnum_dim1]) ; /* L10: */ } /* Step (2L): permute rows of B. */ ccopy_(nrhs, &b[nlp1 + b_dim1], ldb, &bx[bx_dim1 + 1], ldbx); i__1 = n; for (i__ = 2; i__ <= i__1; ++i__) { ccopy_(nrhs, &b[perm[i__] + b_dim1], ldb, &bx[i__ + bx_dim1], ldbx); /* L20: */ } /* Step (3L): apply the inverse of the left singular vector matrix to BX. */ if (*k == 1) { ccopy_(nrhs, &bx[bx_offset], ldbx, &b[b_offset], ldb); if (z__[1] < 0.f) { csscal_(nrhs, &c_b1290, &b[b_offset], ldb); } } else { i__1 = *k; for (j = 1; j <= i__1; ++j) { diflj = difl[j]; dj = poles[j + poles_dim1]; dsigj = -poles[j + ((poles_dim1) << (1))]; if (j < *k) { difrj = -difr[j + difr_dim1]; dsigjp = -poles[j + 1 + ((poles_dim1) << (1))]; } if ((z__[j] == 0.f) || (poles[j + ((poles_dim1) << (1))] == 0.f)) { rwork[j] = 0.f; } else { rwork[j] = -poles[j + ((poles_dim1) << (1))] * z__[j] / diflj / (poles[j + ((poles_dim1) << (1))] + dj); } i__2 = j - 1; for (i__ = 1; i__ <= i__2; ++i__) { if ((z__[i__] == 0.f) || (poles[i__ + ((poles_dim1) << (1) )] == 0.f)) { rwork[i__] = 0.f; } else { rwork[i__] = poles[i__ + ((poles_dim1) << (1))] * z__[ i__] / (slamc3_(&poles[i__ + ((poles_dim1) << (1))], &dsigj) - diflj) / (poles[i__ + (( poles_dim1) << (1))] + dj); } /* L30: */ } i__2 = *k; for (i__ = j + 1; i__ <= i__2; ++i__) { if ((z__[i__] == 0.f) || (poles[i__ + ((poles_dim1) << (1) )] == 0.f)) { rwork[i__] = 0.f; } else { rwork[i__] = poles[i__ + ((poles_dim1) << (1))] * z__[ i__] / (slamc3_(&poles[i__ + ((poles_dim1) << (1))], &dsigjp) + difrj) / (poles[i__ + (( poles_dim1) << (1))] + dj); } /* L40: */ } rwork[1] = -1.f; temp = snrm2_(k, &rwork[1], &c__1); /* Since B and BX are complex, the following call to SGEMV is performed in two steps (real and imaginary parts). CALL SGEMV( 'T', K, NRHS, ONE, BX, LDBX, WORK, 1, ZERO, $ B( J, 1 ), LDB ) */ i__ = *k + ((*nrhs) << (1)); i__2 = *nrhs; for (jcol = 1; jcol <= i__2; ++jcol) { i__3 = *k; for (jrow = 1; jrow <= i__3; ++jrow) { ++i__; i__4 = jrow + jcol * bx_dim1; rwork[i__] = bx[i__4].r; /* L50: */ } /* L60: */ } sgemv_("T", k, nrhs, &c_b1011, &rwork[*k + 1 + ((*nrhs) << (1) )], k, &rwork[1], &c__1, &c_b320, &rwork[*k + 1], & c__1); i__ = *k + ((*nrhs) << (1)); i__2 = *nrhs; for (jcol = 1; jcol <= i__2; ++jcol) { i__3 = *k; for (jrow = 1; jrow <= i__3; ++jrow) { ++i__; rwork[i__] = r_imag(&bx[jrow + jcol * bx_dim1]); /* L70: */ } /* L80: */ } sgemv_("T", k, nrhs, &c_b1011, &rwork[*k + 1 + ((*nrhs) << (1) )], k, &rwork[1], &c__1, &c_b320, &rwork[*k + 1 + * nrhs], &c__1); i__2 = *nrhs; for (jcol = 1; jcol <= i__2; ++jcol) { i__3 = j + jcol * b_dim1; i__4 = jcol + *k; i__5 = jcol + *k + *nrhs; q__1.r = rwork[i__4], q__1.i = rwork[i__5]; b[i__3].r = q__1.r, b[i__3].i = q__1.i; /* L90: */ } clascl_("G", &c__0, &c__0, &temp, &c_b1011, &c__1, nrhs, &b[j + b_dim1], ldb, info); /* L100: */ } } /* Move the deflated rows of BX to B also. */ if (*k < max(m,n)) { i__1 = n - *k; clacpy_("A", &i__1, nrhs, &bx[*k + 1 + bx_dim1], ldbx, &b[*k + 1 + b_dim1], ldb); } } else { /* Apply back the right orthogonal transformations. Step (1R): apply back the new right singular vector matrix to B. */ if (*k == 1) { ccopy_(nrhs, &b[b_offset], ldb, &bx[bx_offset], ldbx); } else { i__1 = *k; for (j = 1; j <= i__1; ++j) { dsigj = poles[j + ((poles_dim1) << (1))]; if (z__[j] == 0.f) { rwork[j] = 0.f; } else { rwork[j] = -z__[j] / difl[j] / (dsigj + poles[j + poles_dim1]) / difr[j + ((difr_dim1) << (1))]; } i__2 = j - 1; for (i__ = 1; i__ <= i__2; ++i__) { if (z__[j] == 0.f) { rwork[i__] = 0.f; } else { r__1 = -poles[i__ + 1 + ((poles_dim1) << (1))]; rwork[i__] = z__[j] / (slamc3_(&dsigj, &r__1) - difr[ i__ + difr_dim1]) / (dsigj + poles[i__ + poles_dim1]) / difr[i__ + ((difr_dim1) << (1)) ]; } /* L110: */ } i__2 = *k; for (i__ = j + 1; i__ <= i__2; ++i__) { if (z__[j] == 0.f) { rwork[i__] = 0.f; } else { r__1 = -poles[i__ + ((poles_dim1) << (1))]; rwork[i__] = z__[j] / (slamc3_(&dsigj, &r__1) - difl[ i__]) / (dsigj + poles[i__ + poles_dim1]) / difr[i__ + ((difr_dim1) << (1))]; } /* L120: */ } /* Since B and BX are complex, the following call to SGEMV is performed in two steps (real and imaginary parts). CALL SGEMV( 'T', K, NRHS, ONE, B, LDB, WORK, 1, ZERO, $ BX( J, 1 ), LDBX ) */ i__ = *k + ((*nrhs) << (1)); i__2 = *nrhs; for (jcol = 1; jcol <= i__2; ++jcol) { i__3 = *k; for (jrow = 1; jrow <= i__3; ++jrow) { ++i__; i__4 = jrow + jcol * b_dim1; rwork[i__] = b[i__4].r; /* L130: */ } /* L140: */ } sgemv_("T", k, nrhs, &c_b1011, &rwork[*k + 1 + ((*nrhs) << (1) )], k, &rwork[1], &c__1, &c_b320, &rwork[*k + 1], & c__1); i__ = *k + ((*nrhs) << (1)); i__2 = *nrhs; for (jcol = 1; jcol <= i__2; ++jcol) { i__3 = *k; for (jrow = 1; jrow <= i__3; ++jrow) { ++i__; rwork[i__] = r_imag(&b[jrow + jcol * b_dim1]); /* L150: */ } /* L160: */ } sgemv_("T", k, nrhs, &c_b1011, &rwork[*k + 1 + ((*nrhs) << (1) )], k, &rwork[1], &c__1, &c_b320, &rwork[*k + 1 + * nrhs], &c__1); i__2 = *nrhs; for (jcol = 1; jcol <= i__2; ++jcol) { i__3 = j + jcol * bx_dim1; i__4 = jcol + *k; i__5 = jcol + *k + *nrhs; q__1.r = rwork[i__4], q__1.i = rwork[i__5]; bx[i__3].r = q__1.r, bx[i__3].i = q__1.i; /* L170: */ } /* L180: */ } } /* Step (2R): if SQRE = 1, apply back the rotation that is related to the right null space of the subproblem. */ if (*sqre == 1) { ccopy_(nrhs, &b[m + b_dim1], ldb, &bx[m + bx_dim1], ldbx); csrot_(nrhs, &bx[bx_dim1 + 1], ldbx, &bx[m + bx_dim1], ldbx, c__, s); } if (*k < max(m,n)) { i__1 = n - *k; clacpy_("A", &i__1, nrhs, &b[*k + 1 + b_dim1], ldb, &bx[*k + 1 + bx_dim1], ldbx); } /* Step (3R): permute rows of B. */ ccopy_(nrhs, &bx[bx_dim1 + 1], ldbx, &b[nlp1 + b_dim1], ldb); if (*sqre == 1) { ccopy_(nrhs, &bx[m + bx_dim1], ldbx, &b[m + b_dim1], ldb); } i__1 = n; for (i__ = 2; i__ <= i__1; ++i__) { ccopy_(nrhs, &bx[i__ + bx_dim1], ldbx, &b[perm[i__] + b_dim1], ldb); /* L190: */ } /* Step (4R): apply back the Givens rotations performed. */ for (i__ = *givptr; i__ >= 1; --i__) { r__1 = -givnum[i__ + givnum_dim1]; csrot_(nrhs, &b[givcol[i__ + ((givcol_dim1) << (1))] + b_dim1], ldb, &b[givcol[i__ + givcol_dim1] + b_dim1], ldb, &givnum[ i__ + ((givnum_dim1) << (1))], &r__1); /* L200: */ } } return 0; /* End of CLALS0 */ } /* clals0_ */ /* Subroutine */ int clalsa_(integer *icompq, integer *smlsiz, integer *n, integer *nrhs, complex *b, integer *ldb, complex *bx, integer *ldbx, real *u, integer *ldu, real *vt, integer *k, real *difl, real *difr, real *z__, real *poles, integer *givptr, integer *givcol, integer * ldgcol, integer *perm, real *givnum, real *c__, real *s, real *rwork, integer *iwork, integer *info) { /* System generated locals */ integer givcol_dim1, givcol_offset, perm_dim1, perm_offset, difl_dim1, difl_offset, difr_dim1, difr_offset, givnum_dim1, givnum_offset, poles_dim1, poles_offset, u_dim1, u_offset, vt_dim1, vt_offset, z_dim1, z_offset, b_dim1, b_offset, bx_dim1, bx_offset, i__1, i__2, i__3, i__4, i__5, i__6; complex q__1; /* Builtin functions */ double r_imag(complex *); integer pow_ii(integer *, integer *); /* Local variables */ static integer i__, j, i1, ic, lf, nd, ll, nl, nr, im1, nlf, nrf, lvl, ndb1, nlp1, lvl2, nrp1, jcol, nlvl, sqre, jrow, jimag, jreal, inode, ndiml; extern /* Subroutine */ int sgemm_(char *, char *, integer *, integer *, integer *, real *, real *, integer *, real *, integer *, real *, real *, integer *); static integer ndimr; extern /* Subroutine */ int ccopy_(integer *, complex *, integer *, complex *, integer *), clals0_(integer *, integer *, integer *, integer *, integer *, complex *, integer *, complex *, integer *, integer *, integer *, integer *, integer *, real *, integer *, real *, real *, real *, real *, integer *, real *, real *, real *, integer *), xerbla_(char *, integer *), slasdt_(integer * , integer *, integer *, integer *, integer *, integer *, integer * ); /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= CLALSA is an itermediate step in solving the least squares problem by computing the SVD of the coefficient matrix in compact form (The singular vectors are computed as products of simple orthorgonal matrices.). If ICOMPQ = 0, CLALSA applies the inverse of the left singular vector matrix of an upper bidiagonal matrix to the right hand side; and if ICOMPQ = 1, CLALSA applies the right singular vector matrix to the right hand side. The singular vector matrices were generated in compact form by CLALSA. Arguments ========= ICOMPQ (input) INTEGER Specifies whether the left or the right singular vector matrix is involved. = 0: Left singular vector matrix = 1: Right singular vector matrix SMLSIZ (input) INTEGER The maximum size of the subproblems at the bottom of the computation tree. N (input) INTEGER The row and column dimensions of the upper bidiagonal matrix. NRHS (input) INTEGER The number of columns of B and BX. NRHS must be at least 1. B (input) COMPLEX array, dimension ( LDB, NRHS ) On input, B contains the right hand sides of the least squares problem in rows 1 through M. On output, B contains the solution X in rows 1 through N. LDB (input) INTEGER The leading dimension of B in the calling subprogram. LDB must be at least max(1,MAX( M, N ) ). BX (output) COMPLEX array, dimension ( LDBX, NRHS ) On exit, the result of applying the left or right singular vector matrix to B. LDBX (input) INTEGER The leading dimension of BX. U (input) REAL array, dimension ( LDU, SMLSIZ ). On entry, U contains the left singular vector matrices of all subproblems at the bottom level. LDU (input) INTEGER, LDU = > N. The leading dimension of arrays U, VT, DIFL, DIFR, POLES, GIVNUM, and Z. VT (input) REAL array, dimension ( LDU, SMLSIZ+1 ). On entry, VT' contains the right singular vector matrices of all subproblems at the bottom level. K (input) INTEGER array, dimension ( N ). DIFL (input) REAL array, dimension ( LDU, NLVL ). where NLVL = INT(log_2 (N/(SMLSIZ+1))) + 1. DIFR (input) REAL array, dimension ( LDU, 2 * NLVL ). On entry, DIFL(*, I) and DIFR(*, 2 * I -1) record distances between singular values on the I-th level and singular values on the (I -1)-th level, and DIFR(*, 2 * I) record the normalizing factors of the right singular vectors matrices of subproblems on I-th level. Z (input) REAL array, dimension ( LDU, NLVL ). On entry, Z(1, I) contains the components of the deflation- adjusted updating row vector for subproblems on the I-th level. POLES (input) REAL array, dimension ( LDU, 2 * NLVL ). On entry, POLES(*, 2 * I -1: 2 * I) contains the new and old singular values involved in the secular equations on the I-th level. GIVPTR (input) INTEGER array, dimension ( N ). On entry, GIVPTR( I ) records the number of Givens rotations performed on the I-th problem on the computation tree. GIVCOL (input) INTEGER array, dimension ( LDGCOL, 2 * NLVL ). On entry, for each I, GIVCOL(*, 2 * I - 1: 2 * I) records the locations of Givens rotations performed on the I-th level on the computation tree. LDGCOL (input) INTEGER, LDGCOL = > N. The leading dimension of arrays GIVCOL and PERM. PERM (input) INTEGER array, dimension ( LDGCOL, NLVL ). On entry, PERM(*, I) records permutations done on the I-th level of the computation tree. GIVNUM (input) REAL array, dimension ( LDU, 2 * NLVL ). On entry, GIVNUM(*, 2 *I -1 : 2 * I) records the C- and S- values of Givens rotations performed on the I-th level on the computation tree. C (input) REAL array, dimension ( N ). On entry, if the I-th subproblem is not square, C( I ) contains the C-value of a Givens rotation related to the right null space of the I-th subproblem. S (input) REAL array, dimension ( N ). On entry, if the I-th subproblem is not square, S( I ) contains the S-value of a Givens rotation related to the right null space of the I-th subproblem. RWORK (workspace) REAL array, dimension at least max ( N, (SMLSZ+1)*NRHS*3 ). IWORK (workspace) INTEGER array. The dimension must be at least 3 * N INFO (output) INTEGER = 0: successful exit. < 0: if INFO = -i, the i-th argument had an illegal value. Further Details =============== Based on contributions by Ming Gu and Ren-Cang Li, Computer Science Division, University of California at Berkeley, USA Osni Marques, LBNL/NERSC, USA ===================================================================== Test the input parameters. */ /* Parameter adjustments */ b_dim1 = *ldb; b_offset = 1 + b_dim1; b -= b_offset; bx_dim1 = *ldbx; bx_offset = 1 + bx_dim1; bx -= bx_offset; givnum_dim1 = *ldu; givnum_offset = 1 + givnum_dim1; givnum -= givnum_offset; poles_dim1 = *ldu; poles_offset = 1 + poles_dim1; poles -= poles_offset; z_dim1 = *ldu; z_offset = 1 + z_dim1; z__ -= z_offset; difr_dim1 = *ldu; difr_offset = 1 + difr_dim1; difr -= difr_offset; difl_dim1 = *ldu; difl_offset = 1 + difl_dim1; difl -= difl_offset; vt_dim1 = *ldu; vt_offset = 1 + vt_dim1; vt -= vt_offset; u_dim1 = *ldu; u_offset = 1 + u_dim1; u -= u_offset; --k; --givptr; perm_dim1 = *ldgcol; perm_offset = 1 + perm_dim1; perm -= perm_offset; givcol_dim1 = *ldgcol; givcol_offset = 1 + givcol_dim1; givcol -= givcol_offset; --c__; --s; --rwork; --iwork; /* Function Body */ *info = 0; if ((*icompq < 0) || (*icompq > 1)) { *info = -1; } else if (*smlsiz < 3) { *info = -2; } else if (*n < *smlsiz) { *info = -3; } else if (*nrhs < 1) { *info = -4; } else if (*ldb < *n) { *info = -6; } else if (*ldbx < *n) { *info = -8; } else if (*ldu < *n) { *info = -10; } else if (*ldgcol < *n) { *info = -19; } if (*info != 0) { i__1 = -(*info); xerbla_("CLALSA", &i__1); return 0; } /* Book-keeping and setting up the computation tree. */ inode = 1; ndiml = inode + *n; ndimr = ndiml + *n; slasdt_(n, &nlvl, &nd, &iwork[inode], &iwork[ndiml], &iwork[ndimr], smlsiz); /* The following code applies back the left singular vector factors. For applying back the right singular vector factors, go to 170. */ if (*icompq == 1) { goto L170; } /* The nodes on the bottom level of the tree were solved by SLASDQ. The corresponding left and right singular vector matrices are in explicit form. First apply back the left singular vector matrices. */ ndb1 = (nd + 1) / 2; i__1 = nd; for (i__ = ndb1; i__ <= i__1; ++i__) { /* IC : center row of each node NL : number of rows of left subproblem NR : number of rows of right subproblem NLF: starting row of the left subproblem NRF: starting row of the right subproblem */ i1 = i__ - 1; ic = iwork[inode + i1]; nl = iwork[ndiml + i1]; nr = iwork[ndimr + i1]; nlf = ic - nl; nrf = ic + 1; /* Since B and BX are complex, the following call to SGEMM is performed in two steps (real and imaginary parts). CALL SGEMM( 'T', 'N', NL, NRHS, NL, ONE, U( NLF, 1 ), LDU, $ B( NLF, 1 ), LDB, ZERO, BX( NLF, 1 ), LDBX ) */ j = (nl * *nrhs) << (1); i__2 = *nrhs; for (jcol = 1; jcol <= i__2; ++jcol) { i__3 = nlf + nl - 1; for (jrow = nlf; jrow <= i__3; ++jrow) { ++j; i__4 = jrow + jcol * b_dim1; rwork[j] = b[i__4].r; /* L10: */ } /* L20: */ } sgemm_("T", "N", &nl, nrhs, &nl, &c_b1011, &u[nlf + u_dim1], ldu, & rwork[((nl * *nrhs) << (1)) + 1], &nl, &c_b320, &rwork[1], & nl); j = (nl * *nrhs) << (1); i__2 = *nrhs; for (jcol = 1; jcol <= i__2; ++jcol) { i__3 = nlf + nl - 1; for (jrow = nlf; jrow <= i__3; ++jrow) { ++j; rwork[j] = r_imag(&b[jrow + jcol * b_dim1]); /* L30: */ } /* L40: */ } sgemm_("T", "N", &nl, nrhs, &nl, &c_b1011, &u[nlf + u_dim1], ldu, & rwork[((nl * *nrhs) << (1)) + 1], &nl, &c_b320, &rwork[nl * * nrhs + 1], &nl); jreal = 0; jimag = nl * *nrhs; i__2 = *nrhs; for (jcol = 1; jcol <= i__2; ++jcol) { i__3 = nlf + nl - 1; for (jrow = nlf; jrow <= i__3; ++jrow) { ++jreal; ++jimag; i__4 = jrow + jcol * bx_dim1; i__5 = jreal; i__6 = jimag; q__1.r = rwork[i__5], q__1.i = rwork[i__6]; bx[i__4].r = q__1.r, bx[i__4].i = q__1.i; /* L50: */ } /* L60: */ } /* Since B and BX are complex, the following call to SGEMM is performed in two steps (real and imaginary parts). CALL SGEMM( 'T', 'N', NR, NRHS, NR, ONE, U( NRF, 1 ), LDU, $ B( NRF, 1 ), LDB, ZERO, BX( NRF, 1 ), LDBX ) */ j = (nr * *nrhs) << (1); i__2 = *nrhs; for (jcol = 1; jcol <= i__2; ++jcol) { i__3 = nrf + nr - 1; for (jrow = nrf; jrow <= i__3; ++jrow) { ++j; i__4 = jrow + jcol * b_dim1; rwork[j] = b[i__4].r; /* L70: */ } /* L80: */ } sgemm_("T", "N", &nr, nrhs, &nr, &c_b1011, &u[nrf + u_dim1], ldu, & rwork[((nr * *nrhs) << (1)) + 1], &nr, &c_b320, &rwork[1], & nr); j = (nr * *nrhs) << (1); i__2 = *nrhs; for (jcol = 1; jcol <= i__2; ++jcol) { i__3 = nrf + nr - 1; for (jrow = nrf; jrow <= i__3; ++jrow) { ++j; rwork[j] = r_imag(&b[jrow + jcol * b_dim1]); /* L90: */ } /* L100: */ } sgemm_("T", "N", &nr, nrhs, &nr, &c_b1011, &u[nrf + u_dim1], ldu, & rwork[((nr * *nrhs) << (1)) + 1], &nr, &c_b320, &rwork[nr * * nrhs + 1], &nr); jreal = 0; jimag = nr * *nrhs; i__2 = *nrhs; for (jcol = 1; jcol <= i__2; ++jcol) { i__3 = nrf + nr - 1; for (jrow = nrf; jrow <= i__3; ++jrow) { ++jreal; ++jimag; i__4 = jrow + jcol * bx_dim1; i__5 = jreal; i__6 = jimag; q__1.r = rwork[i__5], q__1.i = rwork[i__6]; bx[i__4].r = q__1.r, bx[i__4].i = q__1.i; /* L110: */ } /* L120: */ } /* L130: */ } /* Next copy the rows of B that correspond to unchanged rows in the bidiagonal matrix to BX. */ i__1 = nd; for (i__ = 1; i__ <= i__1; ++i__) { ic = iwork[inode + i__ - 1]; ccopy_(nrhs, &b[ic + b_dim1], ldb, &bx[ic + bx_dim1], ldbx); /* L140: */ } /* Finally go through the left singular vector matrices of all the other subproblems bottom-up on the tree. */ j = pow_ii(&c__2, &nlvl); sqre = 0; for (lvl = nlvl; lvl >= 1; --lvl) { lvl2 = ((lvl) << (1)) - 1; /* find the first node LF and last node LL on the current level LVL */ if (lvl == 1) { lf = 1; ll = 1; } else { i__1 = lvl - 1; lf = pow_ii(&c__2, &i__1); ll = ((lf) << (1)) - 1; } i__1 = ll; for (i__ = lf; i__ <= i__1; ++i__) { im1 = i__ - 1; ic = iwork[inode + im1]; nl = iwork[ndiml + im1]; nr = iwork[ndimr + im1]; nlf = ic - nl; nrf = ic + 1; --j; clals0_(icompq, &nl, &nr, &sqre, nrhs, &bx[nlf + bx_dim1], ldbx, & b[nlf + b_dim1], ldb, &perm[nlf + lvl * perm_dim1], & givptr[j], &givcol[nlf + lvl2 * givcol_dim1], ldgcol, & givnum[nlf + lvl2 * givnum_dim1], ldu, &poles[nlf + lvl2 * poles_dim1], &difl[nlf + lvl * difl_dim1], &difr[nlf + lvl2 * difr_dim1], &z__[nlf + lvl * z_dim1], &k[j], &c__[ j], &s[j], &rwork[1], info); /* L150: */ } /* L160: */ } goto L330; /* ICOMPQ = 1: applying back the right singular vector factors. */ L170: /* First now go through the right singular vector matrices of all the tree nodes top-down. */ j = 0; i__1 = nlvl; for (lvl = 1; lvl <= i__1; ++lvl) { lvl2 = ((lvl) << (1)) - 1; /* Find the first node LF and last node LL on the current level LVL. */ if (lvl == 1) { lf = 1; ll = 1; } else { i__2 = lvl - 1; lf = pow_ii(&c__2, &i__2); ll = ((lf) << (1)) - 1; } i__2 = lf; for (i__ = ll; i__ >= i__2; --i__) { im1 = i__ - 1; ic = iwork[inode + im1]; nl = iwork[ndiml + im1]; nr = iwork[ndimr + im1]; nlf = ic - nl; nrf = ic + 1; if (i__ == ll) { sqre = 0; } else { sqre = 1; } ++j; clals0_(icompq, &nl, &nr, &sqre, nrhs, &b[nlf + b_dim1], ldb, &bx[ nlf + bx_dim1], ldbx, &perm[nlf + lvl * perm_dim1], & givptr[j], &givcol[nlf + lvl2 * givcol_dim1], ldgcol, & givnum[nlf + lvl2 * givnum_dim1], ldu, &poles[nlf + lvl2 * poles_dim1], &difl[nlf + lvl * difl_dim1], &difr[nlf + lvl2 * difr_dim1], &z__[nlf + lvl * z_dim1], &k[j], &c__[ j], &s[j], &rwork[1], info); /* L180: */ } /* L190: */ } /* The nodes on the bottom level of the tree were solved by SLASDQ. The corresponding right singular vector matrices are in explicit form. Apply them back. */ ndb1 = (nd + 1) / 2; i__1 = nd; for (i__ = ndb1; i__ <= i__1; ++i__) { i1 = i__ - 1; ic = iwork[inode + i1]; nl = iwork[ndiml + i1]; nr = iwork[ndimr + i1]; nlp1 = nl + 1; if (i__ == nd) { nrp1 = nr; } else { nrp1 = nr + 1; } nlf = ic - nl; nrf = ic + 1; /* Since B and BX are complex, the following call to SGEMM is performed in two steps (real and imaginary parts). CALL SGEMM( 'T', 'N', NLP1, NRHS, NLP1, ONE, VT( NLF, 1 ), LDU, $ B( NLF, 1 ), LDB, ZERO, BX( NLF, 1 ), LDBX ) */ j = (nlp1 * *nrhs) << (1); i__2 = *nrhs; for (jcol = 1; jcol <= i__2; ++jcol) { i__3 = nlf + nlp1 - 1; for (jrow = nlf; jrow <= i__3; ++jrow) { ++j; i__4 = jrow + jcol * b_dim1; rwork[j] = b[i__4].r; /* L200: */ } /* L210: */ } sgemm_("T", "N", &nlp1, nrhs, &nlp1, &c_b1011, &vt[nlf + vt_dim1], ldu, &rwork[((nlp1 * *nrhs) << (1)) + 1], &nlp1, &c_b320, & rwork[1], &nlp1); j = (nlp1 * *nrhs) << (1); i__2 = *nrhs; for (jcol = 1; jcol <= i__2; ++jcol) { i__3 = nlf + nlp1 - 1; for (jrow = nlf; jrow <= i__3; ++jrow) { ++j; rwork[j] = r_imag(&b[jrow + jcol * b_dim1]); /* L220: */ } /* L230: */ } sgemm_("T", "N", &nlp1, nrhs, &nlp1, &c_b1011, &vt[nlf + vt_dim1], ldu, &rwork[((nlp1 * *nrhs) << (1)) + 1], &nlp1, &c_b320, & rwork[nlp1 * *nrhs + 1], &nlp1); jreal = 0; jimag = nlp1 * *nrhs; i__2 = *nrhs; for (jcol = 1; jcol <= i__2; ++jcol) { i__3 = nlf + nlp1 - 1; for (jrow = nlf; jrow <= i__3; ++jrow) { ++jreal; ++jimag; i__4 = jrow + jcol * bx_dim1; i__5 = jreal; i__6 = jimag; q__1.r = rwork[i__5], q__1.i = rwork[i__6]; bx[i__4].r = q__1.r, bx[i__4].i = q__1.i; /* L240: */ } /* L250: */ } /* Since B and BX are complex, the following call to SGEMM is performed in two steps (real and imaginary parts). CALL SGEMM( 'T', 'N', NRP1, NRHS, NRP1, ONE, VT( NRF, 1 ), LDU, $ B( NRF, 1 ), LDB, ZERO, BX( NRF, 1 ), LDBX ) */ j = (nrp1 * *nrhs) << (1); i__2 = *nrhs; for (jcol = 1; jcol <= i__2; ++jcol) { i__3 = nrf + nrp1 - 1; for (jrow = nrf; jrow <= i__3; ++jrow) { ++j; i__4 = jrow + jcol * b_dim1; rwork[j] = b[i__4].r; /* L260: */ } /* L270: */ } sgemm_("T", "N", &nrp1, nrhs, &nrp1, &c_b1011, &vt[nrf + vt_dim1], ldu, &rwork[((nrp1 * *nrhs) << (1)) + 1], &nrp1, &c_b320, & rwork[1], &nrp1); j = (nrp1 * *nrhs) << (1); i__2 = *nrhs; for (jcol = 1; jcol <= i__2; ++jcol) { i__3 = nrf + nrp1 - 1; for (jrow = nrf; jrow <= i__3; ++jrow) { ++j; rwork[j] = r_imag(&b[jrow + jcol * b_dim1]); /* L280: */ } /* L290: */ } sgemm_("T", "N", &nrp1, nrhs, &nrp1, &c_b1011, &vt[nrf + vt_dim1], ldu, &rwork[((nrp1 * *nrhs) << (1)) + 1], &nrp1, &c_b320, & rwork[nrp1 * *nrhs + 1], &nrp1); jreal = 0; jimag = nrp1 * *nrhs; i__2 = *nrhs; for (jcol = 1; jcol <= i__2; ++jcol) { i__3 = nrf + nrp1 - 1; for (jrow = nrf; jrow <= i__3; ++jrow) { ++jreal; ++jimag; i__4 = jrow + jcol * bx_dim1; i__5 = jreal; i__6 = jimag; q__1.r = rwork[i__5], q__1.i = rwork[i__6]; bx[i__4].r = q__1.r, bx[i__4].i = q__1.i; /* L300: */ } /* L310: */ } /* L320: */ } L330: return 0; /* End of CLALSA */ } /* clalsa_ */ /* Subroutine */ int clalsd_(char *uplo, integer *smlsiz, integer *n, integer *nrhs, real *d__, real *e, complex *b, integer *ldb, real *rcond, integer *rank, complex *work, real *rwork, integer *iwork, integer * info) { /* System generated locals */ integer b_dim1, b_offset, i__1, i__2, i__3, i__4, i__5, i__6; real r__1; complex q__1; /* Builtin functions */ double r_imag(complex *), log(doublereal), r_sign(real *, real *); /* Local variables */ static integer c__, i__, j, k; static real r__; static integer s, u, z__; static real cs; static integer bx; static real sn; static integer st, vt, nm1, st1; static real eps; static integer iwk; static real tol; static integer difl, difr, jcol, irwb, perm, nsub, nlvl, sqre, bxst, jrow, irwu, jimag, jreal; extern /* Subroutine */ int sgemm_(char *, char *, integer *, integer *, integer *, real *, real *, integer *, real *, integer *, real *, real *, integer *); static integer irwib; extern /* Subroutine */ int ccopy_(integer *, complex *, integer *, complex *, integer *); static integer poles, sizei, irwrb, nsize; extern /* Subroutine */ int csrot_(integer *, complex *, integer *, complex *, integer *, real *, real *); static integer irwvt, icmpq1, icmpq2; extern /* Subroutine */ int clalsa_(integer *, integer *, integer *, integer *, complex *, integer *, complex *, integer *, real *, integer *, real *, integer *, real *, real *, real *, real *, integer *, integer *, integer *, integer *, real *, real *, real * , real *, integer *, integer *), clascl_(char *, integer *, integer *, real *, real *, integer *, integer *, complex *, integer *, integer *); extern doublereal slamch_(char *); extern /* Subroutine */ int slasda_(integer *, integer *, integer *, integer *, real *, real *, real *, integer *, real *, integer *, real *, real *, real *, real *, integer *, integer *, integer *, integer *, real *, real *, real *, real *, integer *, integer *), clacpy_(char *, integer *, integer *, complex *, integer *, complex *, integer *), claset_(char *, integer *, integer *, complex *, complex *, complex *, integer *), xerbla_( char *, integer *), slascl_(char *, integer *, integer *, real *, real *, integer *, integer *, real *, integer *, integer * ); extern integer isamax_(integer *, real *, integer *); static integer givcol; extern /* Subroutine */ int slasdq_(char *, integer *, integer *, integer *, integer *, integer *, real *, real *, real *, integer *, real * , integer *, real *, integer *, real *, integer *), slaset_(char *, integer *, integer *, real *, real *, real *, integer *), slartg_(real *, real *, real *, real *, real * ); static real orgnrm; static integer givnum; extern doublereal slanst_(char *, integer *, real *, real *); extern /* Subroutine */ int slasrt_(char *, integer *, real *, integer *); static integer givptr, nrwork, irwwrk, smlszp; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University October 31, 1999 Purpose ======= CLALSD uses the singular value decomposition of A to solve the least squares problem of finding X to minimize the Euclidean norm of each column of A*X-B, where A is N-by-N upper bidiagonal, and X and B are N-by-NRHS. The solution X overwrites B. The singular values of A smaller than RCOND times the largest singular value are treated as zero in solving the least squares problem; in this case a minimum norm solution is returned. The actual singular values are returned in D in ascending order. This code makes very mild assumptions about floating point arithmetic. It will work on machines with a guard digit in add/subtract, or on those binary machines without guard digits which subtract like the Cray XMP, Cray YMP, Cray C 90, or Cray 2. It could conceivably fail on hexadecimal or decimal machines without guard digits, but we know of none. Arguments ========= UPLO (input) CHARACTER*1 = 'U': D and E define an upper bidiagonal matrix. = 'L': D and E define a lower bidiagonal matrix. SMLSIZ (input) INTEGER The maximum size of the subproblems at the bottom of the computation tree. N (input) INTEGER The dimension of the bidiagonal matrix. N >= 0. NRHS (input) INTEGER The number of columns of B. NRHS must be at least 1. D (input/output) REAL array, dimension (N) On entry D contains the main diagonal of the bidiagonal matrix. On exit, if INFO = 0, D contains its singular values. E (input) REAL array, dimension (N-1) Contains the super-diagonal entries of the bidiagonal matrix. On exit, E has been destroyed. B (input/output) COMPLEX array, dimension (LDB,NRHS) On input, B contains the right hand sides of the least squares problem. On output, B contains the solution X. LDB (input) INTEGER The leading dimension of B in the calling subprogram. LDB must be at least max(1,N). RCOND (input) REAL The singular values of A less than or equal to RCOND times the largest singular value are treated as zero in solving the least squares problem. If RCOND is negative, machine precision is used instead. For example, if diag(S)*X=B were the least squares problem, where diag(S) is a diagonal matrix of singular values, the solution would be X(i) = B(i) / S(i) if S(i) is greater than RCOND*max(S), and X(i) = 0 if S(i) is less than or equal to RCOND*max(S). RANK (output) INTEGER The number of singular values of A greater than RCOND times the largest singular value. WORK (workspace) COMPLEX array, dimension at least (N * NRHS). RWORK (workspace) REAL array, dimension at least (9*N + 2*N*SMLSIZ + 8*N*NLVL + 3*SMLSIZ*NRHS + (SMLSIZ+1)**2), where NLVL = MAX( 0, INT( LOG_2( MIN( M,N )/(SMLSIZ+1) ) ) + 1 ) IWORK (workspace) INTEGER array, dimension at least (3*N*NLVL + 11*N). INFO (output) INTEGER = 0: successful exit. < 0: if INFO = -i, the i-th argument had an illegal value. > 0: The algorithm failed to compute an singular value while working on the submatrix lying in rows and columns INFO/(N+1) through MOD(INFO,N+1). Further Details =============== Based on contributions by Ming Gu and Ren-Cang Li, Computer Science Division, University of California at Berkeley, USA Osni Marques, LBNL/NERSC, USA ===================================================================== Test the input parameters. */ /* Parameter adjustments */ --d__; --e; b_dim1 = *ldb; b_offset = 1 + b_dim1; b -= b_offset; --work; --rwork; --iwork; /* Function Body */ *info = 0; if (*n < 0) { *info = -3; } else if (*nrhs < 1) { *info = -4; } else if ((*ldb < 1) || (*ldb < *n)) { *info = -8; } if (*info != 0) { i__1 = -(*info); xerbla_("CLALSD", &i__1); return 0; } eps = slamch_("Epsilon"); /* Set up the tolerance. */ if ((*rcond <= 0.f) || (*rcond >= 1.f)) { *rcond = eps; } *rank = 0; /* Quick return if possible. */ if (*n == 0) { return 0; } else if (*n == 1) { if (d__[1] == 0.f) { claset_("A", &c__1, nrhs, &c_b55, &c_b55, &b[b_offset], ldb); } else { *rank = 1; clascl_("G", &c__0, &c__0, &d__[1], &c_b1011, &c__1, nrhs, &b[ b_offset], ldb, info); d__[1] = dabs(d__[1]); } return 0; } /* Rotate the matrix if it is lower bidiagonal. */ if (*(unsigned char *)uplo == 'L') { i__1 = *n - 1; for (i__ = 1; i__ <= i__1; ++i__) { slartg_(&d__[i__], &e[i__], &cs, &sn, &r__); d__[i__] = r__; e[i__] = sn * d__[i__ + 1]; d__[i__ + 1] = cs * d__[i__ + 1]; if (*nrhs == 1) { csrot_(&c__1, &b[i__ + b_dim1], &c__1, &b[i__ + 1 + b_dim1], & c__1, &cs, &sn); } else { rwork[((i__) << (1)) - 1] = cs; rwork[i__ * 2] = sn; } /* L10: */ } if (*nrhs > 1) { i__1 = *nrhs; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = *n - 1; for (j = 1; j <= i__2; ++j) { cs = rwork[((j) << (1)) - 1]; sn = rwork[j * 2]; csrot_(&c__1, &b[j + i__ * b_dim1], &c__1, &b[j + 1 + i__ * b_dim1], &c__1, &cs, &sn); /* L20: */ } /* L30: */ } } } /* Scale. */ nm1 = *n - 1; orgnrm = slanst_("M", n, &d__[1], &e[1]); if (orgnrm == 0.f) { claset_("A", n, nrhs, &c_b55, &c_b55, &b[b_offset], ldb); return 0; } slascl_("G", &c__0, &c__0, &orgnrm, &c_b1011, n, &c__1, &d__[1], n, info); slascl_("G", &c__0, &c__0, &orgnrm, &c_b1011, &nm1, &c__1, &e[1], &nm1, info); /* If N is smaller than the minimum divide size SMLSIZ, then solve the problem with another solver. */ if (*n <= *smlsiz) { irwu = 1; irwvt = irwu + *n * *n; irwwrk = irwvt + *n * *n; irwrb = irwwrk; irwib = irwrb + *n * *nrhs; irwb = irwib + *n * *nrhs; slaset_("A", n, n, &c_b320, &c_b1011, &rwork[irwu], n); slaset_("A", n, n, &c_b320, &c_b1011, &rwork[irwvt], n); slasdq_("U", &c__0, n, n, n, &c__0, &d__[1], &e[1], &rwork[irwvt], n, &rwork[irwu], n, &rwork[irwwrk], &c__1, &rwork[irwwrk], info); if (*info != 0) { return 0; } /* In the real version, B is passed to SLASDQ and multiplied internally by Q'. Here B is complex and that product is computed below in two steps (real and imaginary parts). */ j = irwb - 1; i__1 = *nrhs; for (jcol = 1; jcol <= i__1; ++jcol) { i__2 = *n; for (jrow = 1; jrow <= i__2; ++jrow) { ++j; i__3 = jrow + jcol * b_dim1; rwork[j] = b[i__3].r; /* L40: */ } /* L50: */ } sgemm_("T", "N", n, nrhs, n, &c_b1011, &rwork[irwu], n, &rwork[irwb], n, &c_b320, &rwork[irwrb], n); j = irwb - 1; i__1 = *nrhs; for (jcol = 1; jcol <= i__1; ++jcol) { i__2 = *n; for (jrow = 1; jrow <= i__2; ++jrow) { ++j; rwork[j] = r_imag(&b[jrow + jcol * b_dim1]); /* L60: */ } /* L70: */ } sgemm_("T", "N", n, nrhs, n, &c_b1011, &rwork[irwu], n, &rwork[irwb], n, &c_b320, &rwork[irwib], n); jreal = irwrb - 1; jimag = irwib - 1; i__1 = *nrhs; for (jcol = 1; jcol <= i__1; ++jcol) { i__2 = *n; for (jrow = 1; jrow <= i__2; ++jrow) { ++jreal; ++jimag; i__3 = jrow + jcol * b_dim1; i__4 = jreal; i__5 = jimag; q__1.r = rwork[i__4], q__1.i = rwork[i__5]; b[i__3].r = q__1.r, b[i__3].i = q__1.i; /* L80: */ } /* L90: */ } tol = *rcond * (r__1 = d__[isamax_(n, &d__[1], &c__1)], dabs(r__1)); i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { if (d__[i__] <= tol) { claset_("A", &c__1, nrhs, &c_b55, &c_b55, &b[i__ + b_dim1], ldb); } else { clascl_("G", &c__0, &c__0, &d__[i__], &c_b1011, &c__1, nrhs, & b[i__ + b_dim1], ldb, info); ++(*rank); } /* L100: */ } /* Since B is complex, the following call to SGEMM is performed in two steps (real and imaginary parts). That is for V * B (in the real version of the code V' is stored in WORK). CALL SGEMM( 'T', 'N', N, NRHS, N, ONE, WORK, N, B, LDB, ZERO, $ WORK( NWORK ), N ) */ j = irwb - 1; i__1 = *nrhs; for (jcol = 1; jcol <= i__1; ++jcol) { i__2 = *n; for (jrow = 1; jrow <= i__2; ++jrow) { ++j; i__3 = jrow + jcol * b_dim1; rwork[j] = b[i__3].r; /* L110: */ } /* L120: */ } sgemm_("T", "N", n, nrhs, n, &c_b1011, &rwork[irwvt], n, &rwork[irwb], n, &c_b320, &rwork[irwrb], n); j = irwb - 1; i__1 = *nrhs; for (jcol = 1; jcol <= i__1; ++jcol) { i__2 = *n; for (jrow = 1; jrow <= i__2; ++jrow) { ++j; rwork[j] = r_imag(&b[jrow + jcol * b_dim1]); /* L130: */ } /* L140: */ } sgemm_("T", "N", n, nrhs, n, &c_b1011, &rwork[irwvt], n, &rwork[irwb], n, &c_b320, &rwork[irwib], n); jreal = irwrb - 1; jimag = irwib - 1; i__1 = *nrhs; for (jcol = 1; jcol <= i__1; ++jcol) { i__2 = *n; for (jrow = 1; jrow <= i__2; ++jrow) { ++jreal; ++jimag; i__3 = jrow + jcol * b_dim1; i__4 = jreal; i__5 = jimag; q__1.r = rwork[i__4], q__1.i = rwork[i__5]; b[i__3].r = q__1.r, b[i__3].i = q__1.i; /* L150: */ } /* L160: */ } /* Unscale. */ slascl_("G", &c__0, &c__0, &c_b1011, &orgnrm, n, &c__1, &d__[1], n, info); slasrt_("D", n, &d__[1], info); clascl_("G", &c__0, &c__0, &orgnrm, &c_b1011, n, nrhs, &b[b_offset], ldb, info); return 0; } /* Book-keeping and setting up some constants. */ nlvl = (integer) (log((real) (*n) / (real) (*smlsiz + 1)) / log(2.f)) + 1; smlszp = *smlsiz + 1; u = 1; vt = *smlsiz * *n + 1; difl = vt + smlszp * *n; difr = difl + nlvl * *n; z__ = difr + ((nlvl * *n) << (1)); c__ = z__ + nlvl * *n; s = c__ + *n; poles = s + *n; givnum = poles + ((nlvl) << (1)) * *n; nrwork = givnum + ((nlvl) << (1)) * *n; bx = 1; irwrb = nrwork; irwib = irwrb + *smlsiz * *nrhs; irwb = irwib + *smlsiz * *nrhs; sizei = *n + 1; k = sizei + *n; givptr = k + *n; perm = givptr + *n; givcol = perm + nlvl * *n; iwk = givcol + ((nlvl * *n) << (1)); st = 1; sqre = 0; icmpq1 = 1; icmpq2 = 0; nsub = 0; i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { if ((r__1 = d__[i__], dabs(r__1)) < eps) { d__[i__] = r_sign(&eps, &d__[i__]); } /* L170: */ } i__1 = nm1; for (i__ = 1; i__ <= i__1; ++i__) { if (((r__1 = e[i__], dabs(r__1)) < eps) || (i__ == nm1)) { ++nsub; iwork[nsub] = st; /* Subproblem found. First determine its size and then apply divide and conquer on it. */ if (i__ < nm1) { /* A subproblem with E(I) small for I < NM1. */ nsize = i__ - st + 1; iwork[sizei + nsub - 1] = nsize; } else if ((r__1 = e[i__], dabs(r__1)) >= eps) { /* A subproblem with E(NM1) not too small but I = NM1. */ nsize = *n - st + 1; iwork[sizei + nsub - 1] = nsize; } else { /* A subproblem with E(NM1) small. This implies an 1-by-1 subproblem at D(N), which is not solved explicitly. */ nsize = i__ - st + 1; iwork[sizei + nsub - 1] = nsize; ++nsub; iwork[nsub] = *n; iwork[sizei + nsub - 1] = 1; ccopy_(nrhs, &b[*n + b_dim1], ldb, &work[bx + nm1], n); } st1 = st - 1; if (nsize == 1) { /* This is a 1-by-1 subproblem and is not solved explicitly. */ ccopy_(nrhs, &b[st + b_dim1], ldb, &work[bx + st1], n); } else if (nsize <= *smlsiz) { /* This is a small subproblem and is solved by SLASDQ. */ slaset_("A", &nsize, &nsize, &c_b320, &c_b1011, &rwork[vt + st1], n); slaset_("A", &nsize, &nsize, &c_b320, &c_b1011, &rwork[u + st1], n); slasdq_("U", &c__0, &nsize, &nsize, &nsize, &c__0, &d__[st], & e[st], &rwork[vt + st1], n, &rwork[u + st1], n, & rwork[nrwork], &c__1, &rwork[nrwork], info) ; if (*info != 0) { return 0; } /* In the real version, B is passed to SLASDQ and multiplied internally by Q'. Here B is complex and that product is computed below in two steps (real and imaginary parts). */ j = irwb - 1; i__2 = *nrhs; for (jcol = 1; jcol <= i__2; ++jcol) { i__3 = st + nsize - 1; for (jrow = st; jrow <= i__3; ++jrow) { ++j; i__4 = jrow + jcol * b_dim1; rwork[j] = b[i__4].r; /* L180: */ } /* L190: */ } sgemm_("T", "N", &nsize, nrhs, &nsize, &c_b1011, &rwork[u + st1], n, &rwork[irwb], &nsize, &c_b320, &rwork[irwrb], &nsize); j = irwb - 1; i__2 = *nrhs; for (jcol = 1; jcol <= i__2; ++jcol) { i__3 = st + nsize - 1; for (jrow = st; jrow <= i__3; ++jrow) { ++j; rwork[j] = r_imag(&b[jrow + jcol * b_dim1]); /* L200: */ } /* L210: */ } sgemm_("T", "N", &nsize, nrhs, &nsize, &c_b1011, &rwork[u + st1], n, &rwork[irwb], &nsize, &c_b320, &rwork[irwib], &nsize); jreal = irwrb - 1; jimag = irwib - 1; i__2 = *nrhs; for (jcol = 1; jcol <= i__2; ++jcol) { i__3 = st + nsize - 1; for (jrow = st; jrow <= i__3; ++jrow) { ++jreal; ++jimag; i__4 = jrow + jcol * b_dim1; i__5 = jreal; i__6 = jimag; q__1.r = rwork[i__5], q__1.i = rwork[i__6]; b[i__4].r = q__1.r, b[i__4].i = q__1.i; /* L220: */ } /* L230: */ } clacpy_("A", &nsize, nrhs, &b[st + b_dim1], ldb, &work[bx + st1], n); } else { /* A large problem. Solve it using divide and conquer. */ slasda_(&icmpq1, smlsiz, &nsize, &sqre, &d__[st], &e[st], & rwork[u + st1], n, &rwork[vt + st1], &iwork[k + st1], &rwork[difl + st1], &rwork[difr + st1], &rwork[z__ + st1], &rwork[poles + st1], &iwork[givptr + st1], & iwork[givcol + st1], n, &iwork[perm + st1], &rwork[ givnum + st1], &rwork[c__ + st1], &rwork[s + st1], & rwork[nrwork], &iwork[iwk], info); if (*info != 0) { return 0; } bxst = bx + st1; clalsa_(&icmpq2, smlsiz, &nsize, nrhs, &b[st + b_dim1], ldb, & work[bxst], n, &rwork[u + st1], n, &rwork[vt + st1], & iwork[k + st1], &rwork[difl + st1], &rwork[difr + st1] , &rwork[z__ + st1], &rwork[poles + st1], &iwork[ givptr + st1], &iwork[givcol + st1], n, &iwork[perm + st1], &rwork[givnum + st1], &rwork[c__ + st1], &rwork[ s + st1], &rwork[nrwork], &iwork[iwk], info); if (*info != 0) { return 0; } } st = i__ + 1; } /* L240: */ } /* Apply the singular values and treat the tiny ones as zero. */ tol = *rcond * (r__1 = d__[isamax_(n, &d__[1], &c__1)], dabs(r__1)); i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { /* Some of the elements in D can be negative because 1-by-1 subproblems were not solved explicitly. */ if ((r__1 = d__[i__], dabs(r__1)) <= tol) { claset_("A", &c__1, nrhs, &c_b55, &c_b55, &work[bx + i__ - 1], n); } else { ++(*rank); clascl_("G", &c__0, &c__0, &d__[i__], &c_b1011, &c__1, nrhs, & work[bx + i__ - 1], n, info); } d__[i__] = (r__1 = d__[i__], dabs(r__1)); /* L250: */ } /* Now apply back the right singular vectors. */ icmpq2 = 1; i__1 = nsub; for (i__ = 1; i__ <= i__1; ++i__) { st = iwork[i__]; st1 = st - 1; nsize = iwork[sizei + i__ - 1]; bxst = bx + st1; if (nsize == 1) { ccopy_(nrhs, &work[bxst], n, &b[st + b_dim1], ldb); } else if (nsize <= *smlsiz) { /* Since B and BX are complex, the following call to SGEMM is performed in two steps (real and imaginary parts). CALL SGEMM( 'T', 'N', NSIZE, NRHS, NSIZE, ONE, $ RWORK( VT+ST1 ), N, RWORK( BXST ), N, ZERO, $ B( ST, 1 ), LDB ) */ j = bxst - *n - 1; jreal = irwb - 1; i__2 = *nrhs; for (jcol = 1; jcol <= i__2; ++jcol) { j += *n; i__3 = nsize; for (jrow = 1; jrow <= i__3; ++jrow) { ++jreal; i__4 = j + jrow; rwork[jreal] = work[i__4].r; /* L260: */ } /* L270: */ } sgemm_("T", "N", &nsize, nrhs, &nsize, &c_b1011, &rwork[vt + st1], n, &rwork[irwb], &nsize, &c_b320, &rwork[irwrb], &nsize); j = bxst - *n - 1; jimag = irwb - 1; i__2 = *nrhs; for (jcol = 1; jcol <= i__2; ++jcol) { j += *n; i__3 = nsize; for (jrow = 1; jrow <= i__3; ++jrow) { ++jimag; rwork[jimag] = r_imag(&work[j + jrow]); /* L280: */ } /* L290: */ } sgemm_("T", "N", &nsize, nrhs, &nsize, &c_b1011, &rwork[vt + st1], n, &rwork[irwb], &nsize, &c_b320, &rwork[irwib], &nsize); jreal = irwrb - 1; jimag = irwib - 1; i__2 = *nrhs; for (jcol = 1; jcol <= i__2; ++jcol) { i__3 = st + nsize - 1; for (jrow = st; jrow <= i__3; ++jrow) { ++jreal; ++jimag; i__4 = jrow + jcol * b_dim1; i__5 = jreal; i__6 = jimag; q__1.r = rwork[i__5], q__1.i = rwork[i__6]; b[i__4].r = q__1.r, b[i__4].i = q__1.i; /* L300: */ } /* L310: */ } } else { clalsa_(&icmpq2, smlsiz, &nsize, nrhs, &work[bxst], n, &b[st + b_dim1], ldb, &rwork[u + st1], n, &rwork[vt + st1], & iwork[k + st1], &rwork[difl + st1], &rwork[difr + st1], & rwork[z__ + st1], &rwork[poles + st1], &iwork[givptr + st1], &iwork[givcol + st1], n, &iwork[perm + st1], &rwork[ givnum + st1], &rwork[c__ + st1], &rwork[s + st1], &rwork[ nrwork], &iwork[iwk], info); if (*info != 0) { return 0; } } /* L320: */ } /* Unscale and sort the singular values. */ slascl_("G", &c__0, &c__0, &c_b1011, &orgnrm, n, &c__1, &d__[1], n, info); slasrt_("D", n, &d__[1], info); clascl_("G", &c__0, &c__0, &orgnrm, &c_b1011, n, nrhs, &b[b_offset], ldb, info); return 0; /* End of CLALSD */ } /* clalsd_ */ doublereal clange_(char *norm, integer *m, integer *n, complex *a, integer * lda, real *work) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2; real ret_val, r__1, r__2; /* Builtin functions */ double c_abs(complex *), sqrt(doublereal); /* Local variables */ static integer i__, j; static real sum, scale; extern logical lsame_(char *, char *); static real value; extern /* Subroutine */ int classq_(integer *, complex *, integer *, real *, real *); /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University October 31, 1992 Purpose ======= CLANGE returns the value of the one norm, or the Frobenius norm, or the infinity norm, or the element of largest absolute value of a complex matrix A. Description =========== CLANGE returns the value CLANGE = ( max(abs(A(i,j))), NORM = 'M' or 'm' ( ( norm1(A), NORM = '1', 'O' or 'o' ( ( normI(A), NORM = 'I' or 'i' ( ( normF(A), NORM = 'F', 'f', 'E' or 'e' where norm1 denotes the one norm of a matrix (maximum column sum), normI denotes the infinity norm of a matrix (maximum row sum) and normF denotes the Frobenius norm of a matrix (square root of sum of squares). Note that max(abs(A(i,j))) is not a matrix norm. Arguments ========= NORM (input) CHARACTER*1 Specifies the value to be returned in CLANGE as described above. M (input) INTEGER The number of rows of the matrix A. M >= 0. When M = 0, CLANGE is set to zero. N (input) INTEGER The number of columns of the matrix A. N >= 0. When N = 0, CLANGE is set to zero. A (input) COMPLEX array, dimension (LDA,N) The m by n matrix A. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(M,1). WORK (workspace) REAL array, dimension (LWORK), where LWORK >= M when NORM = 'I'; otherwise, WORK is not referenced. ===================================================================== */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --work; /* Function Body */ if (min(*m,*n) == 0) { value = 0.f; } else if (lsame_(norm, "M")) { /* Find max(abs(A(i,j))). */ value = 0.f; i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { /* Computing MAX */ r__1 = value, r__2 = c_abs(&a[i__ + j * a_dim1]); value = dmax(r__1,r__2); /* L10: */ } /* L20: */ } } else if ((lsame_(norm, "O")) || (*(unsigned char * )norm == '1')) { /* Find norm1(A). */ value = 0.f; i__1 = *n; for (j = 1; j <= i__1; ++j) { sum = 0.f; i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { sum += c_abs(&a[i__ + j * a_dim1]); /* L30: */ } value = dmax(value,sum); /* L40: */ } } else if (lsame_(norm, "I")) { /* Find normI(A). */ i__1 = *m; for (i__ = 1; i__ <= i__1; ++i__) { work[i__] = 0.f; /* L50: */ } i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { work[i__] += c_abs(&a[i__ + j * a_dim1]); /* L60: */ } /* L70: */ } value = 0.f; i__1 = *m; for (i__ = 1; i__ <= i__1; ++i__) { /* Computing MAX */ r__1 = value, r__2 = work[i__]; value = dmax(r__1,r__2); /* L80: */ } } else if ((lsame_(norm, "F")) || (lsame_(norm, "E"))) { /* Find normF(A). */ scale = 0.f; sum = 1.f; i__1 = *n; for (j = 1; j <= i__1; ++j) { classq_(m, &a[j * a_dim1 + 1], &c__1, &scale, &sum); /* L90: */ } value = scale * sqrt(sum); } ret_val = value; return ret_val; /* End of CLANGE */ } /* clange_ */ doublereal clanhe_(char *norm, char *uplo, integer *n, complex *a, integer * lda, real *work) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2; real ret_val, r__1, r__2, r__3; /* Builtin functions */ double c_abs(complex *), sqrt(doublereal); /* Local variables */ static integer i__, j; static real sum, absa, scale; extern logical lsame_(char *, char *); static real value; extern /* Subroutine */ int classq_(integer *, complex *, integer *, real *, real *); /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University October 31, 1992 Purpose ======= CLANHE returns the value of the one norm, or the Frobenius norm, or the infinity norm, or the element of largest absolute value of a complex hermitian matrix A. Description =========== CLANHE returns the value CLANHE = ( max(abs(A(i,j))), NORM = 'M' or 'm' ( ( norm1(A), NORM = '1', 'O' or 'o' ( ( normI(A), NORM = 'I' or 'i' ( ( normF(A), NORM = 'F', 'f', 'E' or 'e' where norm1 denotes the one norm of a matrix (maximum column sum), normI denotes the infinity norm of a matrix (maximum row sum) and normF denotes the Frobenius norm of a matrix (square root of sum of squares). Note that max(abs(A(i,j))) is not a matrix norm. Arguments ========= NORM (input) CHARACTER*1 Specifies the value to be returned in CLANHE as described above. UPLO (input) CHARACTER*1 Specifies whether the upper or lower triangular part of the hermitian matrix A is to be referenced. = 'U': Upper triangular part of A is referenced = 'L': Lower triangular part of A is referenced N (input) INTEGER The order of the matrix A. N >= 0. When N = 0, CLANHE is set to zero. A (input) COMPLEX array, dimension (LDA,N) 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, and the strictly lower triangular part of A is not referenced. If UPLO = 'L', the leading n by n lower triangular part of A contains the lower triangular part of the matrix A, and the strictly upper triangular part of A is not referenced. Note that the imaginary parts of the diagonal elements need not be set and are assumed to be zero. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(N,1). WORK (workspace) REAL array, dimension (LWORK), where LWORK >= N when NORM = 'I' or '1' or 'O'; otherwise, WORK is not referenced. ===================================================================== */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --work; /* Function Body */ if (*n == 0) { value = 0.f; } else if (lsame_(norm, "M")) { /* Find max(abs(A(i,j))). */ value = 0.f; if (lsame_(uplo, "U")) { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = j - 1; for (i__ = 1; i__ <= i__2; ++i__) { /* Computing MAX */ r__1 = value, r__2 = c_abs(&a[i__ + j * a_dim1]); value = dmax(r__1,r__2); /* L10: */ } /* Computing MAX */ i__2 = j + j * a_dim1; r__2 = value, r__3 = (r__1 = a[i__2].r, dabs(r__1)); value = dmax(r__2,r__3); /* L20: */ } } else { i__1 = *n; for (j = 1; j <= i__1; ++j) { /* Computing MAX */ i__2 = j + j * a_dim1; r__2 = value, r__3 = (r__1 = a[i__2].r, dabs(r__1)); value = dmax(r__2,r__3); i__2 = *n; for (i__ = j + 1; i__ <= i__2; ++i__) { /* Computing MAX */ r__1 = value, r__2 = c_abs(&a[i__ + j * a_dim1]); value = dmax(r__1,r__2); /* L30: */ } /* L40: */ } } } else if (((lsame_(norm, "I")) || (lsame_(norm, "O"))) || (*(unsigned char *)norm == '1')) { /* Find normI(A) ( = norm1(A), since A is hermitian). */ value = 0.f; if (lsame_(uplo, "U")) { i__1 = *n; for (j = 1; j <= i__1; ++j) { sum = 0.f; i__2 = j - 1; for (i__ = 1; i__ <= i__2; ++i__) { absa = c_abs(&a[i__ + j * a_dim1]); sum += absa; work[i__] += absa; /* L50: */ } i__2 = j + j * a_dim1; work[j] = sum + (r__1 = a[i__2].r, dabs(r__1)); /* L60: */ } i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { /* Computing MAX */ r__1 = value, r__2 = work[i__]; value = dmax(r__1,r__2); /* L70: */ } } else { i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { work[i__] = 0.f; /* L80: */ } i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = j + j * a_dim1; sum = work[j] + (r__1 = a[i__2].r, dabs(r__1)); i__2 = *n; for (i__ = j + 1; i__ <= i__2; ++i__) { absa = c_abs(&a[i__ + j * a_dim1]); sum += absa; work[i__] += absa; /* L90: */ } value = dmax(value,sum); /* L100: */ } } } else if ((lsame_(norm, "F")) || (lsame_(norm, "E"))) { /* Find normF(A). */ scale = 0.f; sum = 1.f; if (lsame_(uplo, "U")) { i__1 = *n; for (j = 2; j <= i__1; ++j) { i__2 = j - 1; classq_(&i__2, &a[j * a_dim1 + 1], &c__1, &scale, &sum); /* L110: */ } } else { i__1 = *n - 1; for (j = 1; j <= i__1; ++j) { i__2 = *n - j; classq_(&i__2, &a[j + 1 + j * a_dim1], &c__1, &scale, &sum); /* L120: */ } } sum *= 2; i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = i__ + i__ * a_dim1; if (a[i__2].r != 0.f) { i__2 = i__ + i__ * a_dim1; absa = (r__1 = a[i__2].r, dabs(r__1)); if (scale < absa) { /* Computing 2nd power */ r__1 = scale / absa; sum = sum * (r__1 * r__1) + 1.f; scale = absa; } else { /* Computing 2nd power */ r__1 = absa / scale; sum += r__1 * r__1; } } /* L130: */ } value = scale * sqrt(sum); } ret_val = value; return ret_val; /* End of CLANHE */ } /* clanhe_ */ doublereal clanhs_(char *norm, integer *n, complex *a, integer *lda, real * work) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3, i__4; real ret_val, r__1, r__2; /* Builtin functions */ double c_abs(complex *), sqrt(doublereal); /* Local variables */ static integer i__, j; static real sum, scale; extern logical lsame_(char *, char *); static real value; extern /* Subroutine */ int classq_(integer *, complex *, integer *, real *, real *); /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University October 31, 1992 Purpose ======= CLANHS returns the value of the one norm, or the Frobenius norm, or the infinity norm, or the element of largest absolute value of a Hessenberg matrix A. Description =========== CLANHS returns the value CLANHS = ( max(abs(A(i,j))), NORM = 'M' or 'm' ( ( norm1(A), NORM = '1', 'O' or 'o' ( ( normI(A), NORM = 'I' or 'i' ( ( normF(A), NORM = 'F', 'f', 'E' or 'e' where norm1 denotes the one norm of a matrix (maximum column sum), normI denotes the infinity norm of a matrix (maximum row sum) and normF denotes the Frobenius norm of a matrix (square root of sum of squares). Note that max(abs(A(i,j))) is not a matrix norm. Arguments ========= NORM (input) CHARACTER*1 Specifies the value to be returned in CLANHS as described above. N (input) INTEGER The order of the matrix A. N >= 0. When N = 0, CLANHS is set to zero. A (input) COMPLEX array, dimension (LDA,N) The n by n upper Hessenberg matrix A; the part of A below the first sub-diagonal is not referenced. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(N,1). WORK (workspace) REAL array, dimension (LWORK), where LWORK >= N when NORM = 'I'; otherwise, WORK is not referenced. ===================================================================== */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --work; /* Function Body */ if (*n == 0) { value = 0.f; } else if (lsame_(norm, "M")) { /* Find max(abs(A(i,j))). */ value = 0.f; i__1 = *n; for (j = 1; j <= i__1; ++j) { /* Computing MIN */ i__3 = *n, i__4 = j + 1; i__2 = min(i__3,i__4); for (i__ = 1; i__ <= i__2; ++i__) { /* Computing MAX */ r__1 = value, r__2 = c_abs(&a[i__ + j * a_dim1]); value = dmax(r__1,r__2); /* L10: */ } /* L20: */ } } else if ((lsame_(norm, "O")) || (*(unsigned char * )norm == '1')) { /* Find norm1(A). */ value = 0.f; i__1 = *n; for (j = 1; j <= i__1; ++j) { sum = 0.f; /* Computing MIN */ i__3 = *n, i__4 = j + 1; i__2 = min(i__3,i__4); for (i__ = 1; i__ <= i__2; ++i__) { sum += c_abs(&a[i__ + j * a_dim1]); /* L30: */ } value = dmax(value,sum); /* L40: */ } } else if (lsame_(norm, "I")) { /* Find normI(A). */ i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { work[i__] = 0.f; /* L50: */ } i__1 = *n; for (j = 1; j <= i__1; ++j) { /* Computing MIN */ i__3 = *n, i__4 = j + 1; i__2 = min(i__3,i__4); for (i__ = 1; i__ <= i__2; ++i__) { work[i__] += c_abs(&a[i__ + j * a_dim1]); /* L60: */ } /* L70: */ } value = 0.f; i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { /* Computing MAX */ r__1 = value, r__2 = work[i__]; value = dmax(r__1,r__2); /* L80: */ } } else if ((lsame_(norm, "F")) || (lsame_(norm, "E"))) { /* Find normF(A). */ scale = 0.f; sum = 1.f; i__1 = *n; for (j = 1; j <= i__1; ++j) { /* Computing MIN */ i__3 = *n, i__4 = j + 1; i__2 = min(i__3,i__4); classq_(&i__2, &a[j * a_dim1 + 1], &c__1, &scale, &sum); /* L90: */ } value = scale * sqrt(sum); } ret_val = value; return ret_val; /* End of CLANHS */ } /* clanhs_ */ /* Subroutine */ int clarcm_(integer *m, integer *n, real *a, integer *lda, complex *b, integer *ldb, complex *c__, integer *ldc, real *rwork) { /* System generated locals */ integer a_dim1, a_offset, b_dim1, b_offset, c_dim1, c_offset, i__1, i__2, i__3, i__4, i__5; real r__1; complex q__1; /* Builtin functions */ double r_imag(complex *); /* Local variables */ static integer i__, j, l; extern /* Subroutine */ int sgemm_(char *, char *, integer *, integer *, integer *, real *, real *, integer *, real *, integer *, real *, real *, integer *); /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= CLARCM performs a very simple matrix-matrix multiplication: C := A * B, where A is M by M and real; B is M by N and complex; C is M by N and complex. Arguments ========= M (input) INTEGER The number of rows of the matrix A and of the matrix C. M >= 0. N (input) INTEGER The number of columns and rows of the matrix B and the number of columns of the matrix C. N >= 0. A (input) REAL array, dimension (LDA, M) A contains the M by M matrix A. LDA (input) INTEGER The leading dimension of the array A. LDA >=max(1,M). B (input) REAL array, dimension (LDB, N) B contains the M by N matrix B. LDB (input) INTEGER The leading dimension of the array B. LDB >=max(1,M). C (input) COMPLEX array, dimension (LDC, N) C contains the M by N matrix C. LDC (input) INTEGER The leading dimension of the array C. LDC >=max(1,M). RWORK (workspace) REAL array, dimension (2*M*N) ===================================================================== Quick return if possible. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; b_dim1 = *ldb; b_offset = 1 + b_dim1; b -= b_offset; c_dim1 = *ldc; c_offset = 1 + c_dim1; c__ -= c_offset; --rwork; /* Function Body */ if ((*m == 0) || (*n == 0)) { return 0; } i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * b_dim1; rwork[(j - 1) * *m + i__] = b[i__3].r; /* L10: */ } /* L20: */ } l = *m * *n + 1; sgemm_("N", "N", m, n, m, &c_b1011, &a[a_offset], lda, &rwork[1], m, & c_b320, &rwork[l], m); i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * c_dim1; i__4 = l + (j - 1) * *m + i__ - 1; c__[i__3].r = rwork[i__4], c__[i__3].i = 0.f; /* L30: */ } /* L40: */ } i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { rwork[(j - 1) * *m + i__] = r_imag(&b[i__ + j * b_dim1]); /* L50: */ } /* L60: */ } sgemm_("N", "N", m, n, m, &c_b1011, &a[a_offset], lda, &rwork[1], m, & c_b320, &rwork[l], m); i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * c_dim1; i__4 = i__ + j * c_dim1; r__1 = c__[i__4].r; i__5 = l + (j - 1) * *m + i__ - 1; q__1.r = r__1, q__1.i = rwork[i__5]; c__[i__3].r = q__1.r, c__[i__3].i = q__1.i; /* L70: */ } /* L80: */ } return 0; /* End of CLARCM */ } /* clarcm_ */ /* Subroutine */ int clarf_(char *side, integer *m, integer *n, complex *v, integer *incv, complex *tau, complex *c__, integer *ldc, complex * work) { /* System generated locals */ integer c_dim1, c_offset; complex q__1; /* Local variables */ extern /* Subroutine */ int cgerc_(integer *, integer *, complex *, complex *, integer *, complex *, integer *, complex *, integer *), cgemv_(char *, integer *, integer *, complex *, complex *, integer *, complex *, integer *, complex *, complex *, integer *); extern logical lsame_(char *, char *); /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University September 30, 1994 Purpose ======= CLARF applies a complex elementary reflector H to a complex M-by-N matrix C, from either the left or the right. H is represented in the form H = I - tau * v * v' where tau is a complex scalar and v is a complex vector. If tau = 0, then H is taken to be the unit matrix. To apply H' (the conjugate transpose of H), supply conjg(tau) instead tau. Arguments ========= SIDE (input) CHARACTER*1 = 'L': form H * C = 'R': form C * H M (input) INTEGER The number of rows of the matrix C. N (input) INTEGER The number of columns of the matrix C. V (input) COMPLEX array, dimension (1 + (M-1)*abs(INCV)) if SIDE = 'L' or (1 + (N-1)*abs(INCV)) if SIDE = 'R' The vector v in the representation of H. V is not used if TAU = 0. INCV (input) INTEGER The increment between elements of v. INCV <> 0. TAU (input) COMPLEX The value tau in the representation of H. C (input/output) COMPLEX array, dimension (LDC,N) On entry, the M-by-N matrix C. On exit, C is overwritten by the matrix H * C if SIDE = 'L', or C * H if SIDE = 'R'. LDC (input) INTEGER The leading dimension of the array C. LDC >= max(1,M). WORK (workspace) COMPLEX array, dimension (N) if SIDE = 'L' or (M) if SIDE = 'R' ===================================================================== */ /* Parameter adjustments */ --v; c_dim1 = *ldc; c_offset = 1 + c_dim1; c__ -= c_offset; --work; /* Function Body */ if (lsame_(side, "L")) { /* Form H * C */ if ((tau->r != 0.f) || (tau->i != 0.f)) { /* w := C' * v */ cgemv_("Conjugate transpose", m, n, &c_b56, &c__[c_offset], ldc, & v[1], incv, &c_b55, &work[1], &c__1); /* C := C - v * w' */ q__1.r = -tau->r, q__1.i = -tau->i; cgerc_(m, n, &q__1, &v[1], incv, &work[1], &c__1, &c__[c_offset], ldc); } } else { /* Form C * H */ if ((tau->r != 0.f) || (tau->i != 0.f)) { /* w := C * v */ cgemv_("No transpose", m, n, &c_b56, &c__[c_offset], ldc, &v[1], incv, &c_b55, &work[1], &c__1); /* C := C - w * v' */ q__1.r = -tau->r, q__1.i = -tau->i; cgerc_(m, n, &q__1, &work[1], &c__1, &v[1], incv, &c__[c_offset], ldc); } } return 0; /* End of CLARF */ } /* clarf_ */ /* Subroutine */ int clarfb_(char *side, char *trans, char *direct, char * storev, integer *m, integer *n, integer *k, complex *v, integer *ldv, complex *t, integer *ldt, complex *c__, integer *ldc, complex *work, integer *ldwork) { /* System generated locals */ integer c_dim1, c_offset, t_dim1, t_offset, v_dim1, v_offset, work_dim1, work_offset, i__1, i__2, i__3, i__4, i__5; complex q__1, q__2; /* Builtin functions */ void r_cnjg(complex *, complex *); /* Local variables */ static integer i__, j; extern /* Subroutine */ int cgemm_(char *, char *, integer *, integer *, integer *, complex *, complex *, integer *, complex *, integer *, complex *, complex *, integer *); extern logical lsame_(char *, char *); extern /* Subroutine */ int ccopy_(integer *, complex *, integer *, complex *, integer *), ctrmm_(char *, char *, char *, char *, integer *, integer *, complex *, complex *, integer *, complex *, integer *), clacgv_(integer *, complex *, integer *); static char transt[1]; /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University September 30, 1994 Purpose ======= CLARFB applies a complex block reflector H or its transpose H' to a complex M-by-N matrix C, from either the left or the right. Arguments ========= SIDE (input) CHARACTER*1 = 'L': apply H or H' from the Left = 'R': apply H or H' from the Right TRANS (input) CHARACTER*1 = 'N': apply H (No transpose) = 'C': apply H' (Conjugate transpose) DIRECT (input) CHARACTER*1 Indicates how H is formed from a product of elementary reflectors = 'F': H = H(1) H(2) . . . H(k) (Forward) = 'B': H = H(k) . . . H(2) H(1) (Backward) STOREV (input) CHARACTER*1 Indicates how the vectors which define the elementary reflectors are stored: = 'C': Columnwise = 'R': Rowwise M (input) INTEGER The number of rows of the matrix C. N (input) INTEGER The number of columns of the matrix C. K (input) INTEGER The order of the matrix T (= the number of elementary reflectors whose product defines the block reflector). V (input) COMPLEX array, dimension (LDV,K) if STOREV = 'C' (LDV,M) if STOREV = 'R' and SIDE = 'L' (LDV,N) if STOREV = 'R' and SIDE = 'R' The matrix V. See further details. LDV (input) INTEGER The leading dimension of the array V. If STOREV = 'C' and SIDE = 'L', LDV >= max(1,M); if STOREV = 'C' and SIDE = 'R', LDV >= max(1,N); if STOREV = 'R', LDV >= K. T (input) COMPLEX array, dimension (LDT,K) The triangular K-by-K matrix T in the representation of the block reflector. LDT (input) INTEGER The leading dimension of the array T. LDT >= K. C (input/output) COMPLEX array, dimension (LDC,N) On entry, the M-by-N matrix C. On exit, C is overwritten by H*C or H'*C or C*H or C*H'. LDC (input) INTEGER The leading dimension of the array C. LDC >= max(1,M). WORK (workspace) COMPLEX array, dimension (LDWORK,K) LDWORK (input) INTEGER The leading dimension of the array WORK. If SIDE = 'L', LDWORK >= max(1,N); if SIDE = 'R', LDWORK >= max(1,M). ===================================================================== Quick return if possible */ /* Parameter adjustments */ v_dim1 = *ldv; v_offset = 1 + v_dim1; v -= v_offset; t_dim1 = *ldt; t_offset = 1 + t_dim1; t -= t_offset; c_dim1 = *ldc; c_offset = 1 + c_dim1; c__ -= c_offset; work_dim1 = *ldwork; work_offset = 1 + work_dim1; work -= work_offset; /* Function Body */ if ((*m <= 0) || (*n <= 0)) { return 0; } if (lsame_(trans, "N")) { *(unsigned char *)transt = 'C'; } else { *(unsigned char *)transt = 'N'; } if (lsame_(storev, "C")) { if (lsame_(direct, "F")) { /* Let V = ( V1 ) (first K rows) ( V2 ) where V1 is unit lower triangular. */ if (lsame_(side, "L")) { /* Form H * C or H' * C where C = ( C1 ) ( C2 ) W := C' * V = (C1'*V1 + C2'*V2) (stored in WORK) W := C1' */ i__1 = *k; for (j = 1; j <= i__1; ++j) { ccopy_(n, &c__[j + c_dim1], ldc, &work[j * work_dim1 + 1], &c__1); clacgv_(n, &work[j * work_dim1 + 1], &c__1); /* L10: */ } /* W := W * V1 */ ctrmm_("Right", "Lower", "No transpose", "Unit", n, k, &c_b56, &v[v_offset], ldv, &work[work_offset], ldwork); if (*m > *k) { /* W := W + C2'*V2 */ i__1 = *m - *k; cgemm_("Conjugate transpose", "No transpose", n, k, &i__1, &c_b56, &c__[*k + 1 + c_dim1], ldc, &v[*k + 1 + v_dim1], ldv, &c_b56, &work[work_offset], ldwork); } /* W := W * T' or W * T */ ctrmm_("Right", "Upper", transt, "Non-unit", n, k, &c_b56, &t[ t_offset], ldt, &work[work_offset], ldwork); /* C := C - V * W' */ if (*m > *k) { /* C2 := C2 - V2 * W' */ i__1 = *m - *k; q__1.r = -1.f, q__1.i = -0.f; cgemm_("No transpose", "Conjugate transpose", &i__1, n, k, &q__1, &v[*k + 1 + v_dim1], ldv, &work[ work_offset], ldwork, &c_b56, &c__[*k + 1 + c_dim1], ldc); } /* W := W * V1' */ ctrmm_("Right", "Lower", "Conjugate transpose", "Unit", n, k, &c_b56, &v[v_offset], ldv, &work[work_offset], ldwork); /* C1 := C1 - W' */ i__1 = *k; for (j = 1; j <= i__1; ++j) { i__2 = *n; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = j + i__ * c_dim1; i__4 = j + i__ * c_dim1; r_cnjg(&q__2, &work[i__ + j * work_dim1]); q__1.r = c__[i__4].r - q__2.r, q__1.i = c__[i__4].i - q__2.i; c__[i__3].r = q__1.r, c__[i__3].i = q__1.i; /* L20: */ } /* L30: */ } } else if (lsame_(side, "R")) { /* Form C * H or C * H' where C = ( C1 C2 ) W := C * V = (C1*V1 + C2*V2) (stored in WORK) W := C1 */ i__1 = *k; for (j = 1; j <= i__1; ++j) { ccopy_(m, &c__[j * c_dim1 + 1], &c__1, &work[j * work_dim1 + 1], &c__1); /* L40: */ } /* W := W * V1 */ ctrmm_("Right", "Lower", "No transpose", "Unit", m, k, &c_b56, &v[v_offset], ldv, &work[work_offset], ldwork); if (*n > *k) { /* W := W + C2 * V2 */ i__1 = *n - *k; cgemm_("No transpose", "No transpose", m, k, &i__1, & c_b56, &c__[(*k + 1) * c_dim1 + 1], ldc, &v[*k + 1 + v_dim1], ldv, &c_b56, &work[work_offset], ldwork); } /* W := W * T or W * T' */ ctrmm_("Right", "Upper", trans, "Non-unit", m, k, &c_b56, &t[ t_offset], ldt, &work[work_offset], ldwork); /* C := C - W * V' */ if (*n > *k) { /* C2 := C2 - W * V2' */ i__1 = *n - *k; q__1.r = -1.f, q__1.i = -0.f; cgemm_("No transpose", "Conjugate transpose", m, &i__1, k, &q__1, &work[work_offset], ldwork, &v[*k + 1 + v_dim1], ldv, &c_b56, &c__[(*k + 1) * c_dim1 + 1], ldc); } /* W := W * V1' */ ctrmm_("Right", "Lower", "Conjugate transpose", "Unit", m, k, &c_b56, &v[v_offset], ldv, &work[work_offset], ldwork); /* C1 := C1 - W */ i__1 = *k; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * c_dim1; i__4 = i__ + j * c_dim1; i__5 = i__ + j * work_dim1; q__1.r = c__[i__4].r - work[i__5].r, q__1.i = c__[ i__4].i - work[i__5].i; c__[i__3].r = q__1.r, c__[i__3].i = q__1.i; /* L50: */ } /* L60: */ } } } else { /* Let V = ( V1 ) ( V2 ) (last K rows) where V2 is unit upper triangular. */ if (lsame_(side, "L")) { /* Form H * C or H' * C where C = ( C1 ) ( C2 ) W := C' * V = (C1'*V1 + C2'*V2) (stored in WORK) W := C2' */ i__1 = *k; for (j = 1; j <= i__1; ++j) { ccopy_(n, &c__[*m - *k + j + c_dim1], ldc, &work[j * work_dim1 + 1], &c__1); clacgv_(n, &work[j * work_dim1 + 1], &c__1); /* L70: */ } /* W := W * V2 */ ctrmm_("Right", "Upper", "No transpose", "Unit", n, k, &c_b56, &v[*m - *k + 1 + v_dim1], ldv, &work[work_offset], ldwork); if (*m > *k) { /* W := W + C1'*V1 */ i__1 = *m - *k; cgemm_("Conjugate transpose", "No transpose", n, k, &i__1, &c_b56, &c__[c_offset], ldc, &v[v_offset], ldv, & c_b56, &work[work_offset], ldwork); } /* W := W * T' or W * T */ ctrmm_("Right", "Lower", transt, "Non-unit", n, k, &c_b56, &t[ t_offset], ldt, &work[work_offset], ldwork); /* C := C - V * W' */ if (*m > *k) { /* C1 := C1 - V1 * W' */ i__1 = *m - *k; q__1.r = -1.f, q__1.i = -0.f; cgemm_("No transpose", "Conjugate transpose", &i__1, n, k, &q__1, &v[v_offset], ldv, &work[work_offset], ldwork, &c_b56, &c__[c_offset], ldc); } /* W := W * V2' */ ctrmm_("Right", "Upper", "Conjugate transpose", "Unit", n, k, &c_b56, &v[*m - *k + 1 + v_dim1], ldv, &work[ work_offset], ldwork); /* C2 := C2 - W' */ i__1 = *k; for (j = 1; j <= i__1; ++j) { i__2 = *n; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = *m - *k + j + i__ * c_dim1; i__4 = *m - *k + j + i__ * c_dim1; r_cnjg(&q__2, &work[i__ + j * work_dim1]); q__1.r = c__[i__4].r - q__2.r, q__1.i = c__[i__4].i - q__2.i; c__[i__3].r = q__1.r, c__[i__3].i = q__1.i; /* L80: */ } /* L90: */ } } else if (lsame_(side, "R")) { /* Form C * H or C * H' where C = ( C1 C2 ) W := C * V = (C1*V1 + C2*V2) (stored in WORK) W := C2 */ i__1 = *k; for (j = 1; j <= i__1; ++j) { ccopy_(m, &c__[(*n - *k + j) * c_dim1 + 1], &c__1, &work[ j * work_dim1 + 1], &c__1); /* L100: */ } /* W := W * V2 */ ctrmm_("Right", "Upper", "No transpose", "Unit", m, k, &c_b56, &v[*n - *k + 1 + v_dim1], ldv, &work[work_offset], ldwork); if (*n > *k) { /* W := W + C1 * V1 */ i__1 = *n - *k; cgemm_("No transpose", "No transpose", m, k, &i__1, & c_b56, &c__[c_offset], ldc, &v[v_offset], ldv, & c_b56, &work[work_offset], ldwork); } /* W := W * T or W * T' */ ctrmm_("Right", "Lower", trans, "Non-unit", m, k, &c_b56, &t[ t_offset], ldt, &work[work_offset], ldwork); /* C := C - W * V' */ if (*n > *k) { /* C1 := C1 - W * V1' */ i__1 = *n - *k; q__1.r = -1.f, q__1.i = -0.f; cgemm_("No transpose", "Conjugate transpose", m, &i__1, k, &q__1, &work[work_offset], ldwork, &v[v_offset], ldv, &c_b56, &c__[c_offset], ldc); } /* W := W * V2' */ ctrmm_("Right", "Upper", "Conjugate transpose", "Unit", m, k, &c_b56, &v[*n - *k + 1 + v_dim1], ldv, &work[ work_offset], ldwork); /* C2 := C2 - W */ i__1 = *k; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + (*n - *k + j) * c_dim1; i__4 = i__ + (*n - *k + j) * c_dim1; i__5 = i__ + j * work_dim1; q__1.r = c__[i__4].r - work[i__5].r, q__1.i = c__[ i__4].i - work[i__5].i; c__[i__3].r = q__1.r, c__[i__3].i = q__1.i; /* L110: */ } /* L120: */ } } } } else if (lsame_(storev, "R")) { if (lsame_(direct, "F")) { /* Let V = ( V1 V2 ) (V1: first K columns) where V1 is unit upper triangular. */ if (lsame_(side, "L")) { /* Form H * C or H' * C where C = ( C1 ) ( C2 ) W := C' * V' = (C1'*V1' + C2'*V2') (stored in WORK) W := C1' */ i__1 = *k; for (j = 1; j <= i__1; ++j) { ccopy_(n, &c__[j + c_dim1], ldc, &work[j * work_dim1 + 1], &c__1); clacgv_(n, &work[j * work_dim1 + 1], &c__1); /* L130: */ } /* W := W * V1' */ ctrmm_("Right", "Upper", "Conjugate transpose", "Unit", n, k, &c_b56, &v[v_offset], ldv, &work[work_offset], ldwork); if (*m > *k) { /* W := W + C2'*V2' */ i__1 = *m - *k; cgemm_("Conjugate transpose", "Conjugate transpose", n, k, &i__1, &c_b56, &c__[*k + 1 + c_dim1], ldc, &v[(* k + 1) * v_dim1 + 1], ldv, &c_b56, &work[ work_offset], ldwork); } /* W := W * T' or W * T */ ctrmm_("Right", "Upper", transt, "Non-unit", n, k, &c_b56, &t[ t_offset], ldt, &work[work_offset], ldwork); /* C := C - V' * W' */ if (*m > *k) { /* C2 := C2 - V2' * W' */ i__1 = *m - *k; q__1.r = -1.f, q__1.i = -0.f; cgemm_("Conjugate transpose", "Conjugate transpose", & i__1, n, k, &q__1, &v[(*k + 1) * v_dim1 + 1], ldv, &work[work_offset], ldwork, &c_b56, &c__[*k + 1 + c_dim1], ldc); } /* W := W * V1 */ ctrmm_("Right", "Upper", "No transpose", "Unit", n, k, &c_b56, &v[v_offset], ldv, &work[work_offset], ldwork); /* C1 := C1 - W' */ i__1 = *k; for (j = 1; j <= i__1; ++j) { i__2 = *n; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = j + i__ * c_dim1; i__4 = j + i__ * c_dim1; r_cnjg(&q__2, &work[i__ + j * work_dim1]); q__1.r = c__[i__4].r - q__2.r, q__1.i = c__[i__4].i - q__2.i; c__[i__3].r = q__1.r, c__[i__3].i = q__1.i; /* L140: */ } /* L150: */ } } else if (lsame_(side, "R")) { /* Form C * H or C * H' where C = ( C1 C2 ) W := C * V' = (C1*V1' + C2*V2') (stored in WORK) W := C1 */ i__1 = *k; for (j = 1; j <= i__1; ++j) { ccopy_(m, &c__[j * c_dim1 + 1], &c__1, &work[j * work_dim1 + 1], &c__1); /* L160: */ } /* W := W * V1' */ ctrmm_("Right", "Upper", "Conjugate transpose", "Unit", m, k, &c_b56, &v[v_offset], ldv, &work[work_offset], ldwork); if (*n > *k) { /* W := W + C2 * V2' */ i__1 = *n - *k; cgemm_("No transpose", "Conjugate transpose", m, k, &i__1, &c_b56, &c__[(*k + 1) * c_dim1 + 1], ldc, &v[(*k + 1) * v_dim1 + 1], ldv, &c_b56, &work[ work_offset], ldwork); } /* W := W * T or W * T' */ ctrmm_("Right", "Upper", trans, "Non-unit", m, k, &c_b56, &t[ t_offset], ldt, &work[work_offset], ldwork); /* C := C - W * V */ if (*n > *k) { /* C2 := C2 - W * V2 */ i__1 = *n - *k; q__1.r = -1.f, q__1.i = -0.f; cgemm_("No transpose", "No transpose", m, &i__1, k, &q__1, &work[work_offset], ldwork, &v[(*k + 1) * v_dim1 + 1], ldv, &c_b56, &c__[(*k + 1) * c_dim1 + 1], ldc); } /* W := W * V1 */ ctrmm_("Right", "Upper", "No transpose", "Unit", m, k, &c_b56, &v[v_offset], ldv, &work[work_offset], ldwork); /* C1 := C1 - W */ i__1 = *k; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * c_dim1; i__4 = i__ + j * c_dim1; i__5 = i__ + j * work_dim1; q__1.r = c__[i__4].r - work[i__5].r, q__1.i = c__[ i__4].i - work[i__5].i; c__[i__3].r = q__1.r, c__[i__3].i = q__1.i; /* L170: */ } /* L180: */ } } } else { /* Let V = ( V1 V2 ) (V2: last K columns) where V2 is unit lower triangular. */ if (lsame_(side, "L")) { /* Form H * C or H' * C where C = ( C1 ) ( C2 ) W := C' * V' = (C1'*V1' + C2'*V2') (stored in WORK) W := C2' */ i__1 = *k; for (j = 1; j <= i__1; ++j) { ccopy_(n, &c__[*m - *k + j + c_dim1], ldc, &work[j * work_dim1 + 1], &c__1); clacgv_(n, &work[j * work_dim1 + 1], &c__1); /* L190: */ } /* W := W * V2' */ ctrmm_("Right", "Lower", "Conjugate transpose", "Unit", n, k, &c_b56, &v[(*m - *k + 1) * v_dim1 + 1], ldv, &work[ work_offset], ldwork); if (*m > *k) { /* W := W + C1'*V1' */ i__1 = *m - *k; cgemm_("Conjugate transpose", "Conjugate transpose", n, k, &i__1, &c_b56, &c__[c_offset], ldc, &v[v_offset], ldv, &c_b56, &work[work_offset], ldwork); } /* W := W * T' or W * T */ ctrmm_("Right", "Lower", transt, "Non-unit", n, k, &c_b56, &t[ t_offset], ldt, &work[work_offset], ldwork); /* C := C - V' * W' */ if (*m > *k) { /* C1 := C1 - V1' * W' */ i__1 = *m - *k; q__1.r = -1.f, q__1.i = -0.f; cgemm_("Conjugate transpose", "Conjugate transpose", & i__1, n, k, &q__1, &v[v_offset], ldv, &work[ work_offset], ldwork, &c_b56, &c__[c_offset], ldc); } /* W := W * V2 */ ctrmm_("Right", "Lower", "No transpose", "Unit", n, k, &c_b56, &v[(*m - *k + 1) * v_dim1 + 1], ldv, &work[ work_offset], ldwork); /* C2 := C2 - W' */ i__1 = *k; for (j = 1; j <= i__1; ++j) { i__2 = *n; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = *m - *k + j + i__ * c_dim1; i__4 = *m - *k + j + i__ * c_dim1; r_cnjg(&q__2, &work[i__ + j * work_dim1]); q__1.r = c__[i__4].r - q__2.r, q__1.i = c__[i__4].i - q__2.i; c__[i__3].r = q__1.r, c__[i__3].i = q__1.i; /* L200: */ } /* L210: */ } } else if (lsame_(side, "R")) { /* Form C * H or C * H' where C = ( C1 C2 ) W := C * V' = (C1*V1' + C2*V2') (stored in WORK) W := C2 */ i__1 = *k; for (j = 1; j <= i__1; ++j) { ccopy_(m, &c__[(*n - *k + j) * c_dim1 + 1], &c__1, &work[ j * work_dim1 + 1], &c__1); /* L220: */ } /* W := W * V2' */ ctrmm_("Right", "Lower", "Conjugate transpose", "Unit", m, k, &c_b56, &v[(*n - *k + 1) * v_dim1 + 1], ldv, &work[ work_offset], ldwork); if (*n > *k) { /* W := W + C1 * V1' */ i__1 = *n - *k; cgemm_("No transpose", "Conjugate transpose", m, k, &i__1, &c_b56, &c__[c_offset], ldc, &v[v_offset], ldv, & c_b56, &work[work_offset], ldwork); } /* W := W * T or W * T' */ ctrmm_("Right", "Lower", trans, "Non-unit", m, k, &c_b56, &t[ t_offset], ldt, &work[work_offset], ldwork); /* C := C - W * V */ if (*n > *k) { /* C1 := C1 - W * V1 */ i__1 = *n - *k; q__1.r = -1.f, q__1.i = -0.f; cgemm_("No transpose", "No transpose", m, &i__1, k, &q__1, &work[work_offset], ldwork, &v[v_offset], ldv, & c_b56, &c__[c_offset], ldc); } /* W := W * V2 */ ctrmm_("Right", "Lower", "No transpose", "Unit", m, k, &c_b56, &v[(*n - *k + 1) * v_dim1 + 1], ldv, &work[ work_offset], ldwork); /* C1 := C1 - W */ i__1 = *k; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + (*n - *k + j) * c_dim1; i__4 = i__ + (*n - *k + j) * c_dim1; i__5 = i__ + j * work_dim1; q__1.r = c__[i__4].r - work[i__5].r, q__1.i = c__[ i__4].i - work[i__5].i; c__[i__3].r = q__1.r, c__[i__3].i = q__1.i; /* L230: */ } /* L240: */ } } } } return 0; /* End of CLARFB */ } /* clarfb_ */ /* Subroutine */ int clarfg_(integer *n, complex *alpha, complex *x, integer * incx, complex *tau) { /* System generated locals */ integer i__1; real r__1, r__2; complex q__1, q__2; /* Builtin functions */ double r_imag(complex *), r_sign(real *, real *); /* Local variables */ static integer j, knt; static real beta; extern /* Subroutine */ int cscal_(integer *, complex *, complex *, integer *); static real alphi, alphr, xnorm; extern doublereal scnrm2_(integer *, complex *, integer *), slapy3_(real * , real *, real *); extern /* Complex */ VOID cladiv_(complex *, complex *, complex *); extern doublereal slamch_(char *); extern /* Subroutine */ int csscal_(integer *, real *, complex *, integer *); static real safmin, rsafmn; /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University September 30, 1994 Purpose ======= CLARFG generates a complex elementary reflector H of order n, such that H' * ( alpha ) = ( beta ), H' * H = I. ( x ) ( 0 ) where alpha and beta are scalars, with beta real, and x is an (n-1)-element complex vector. H is represented in the form H = I - tau * ( 1 ) * ( 1 v' ) , ( v ) where tau is a complex scalar and v is a complex (n-1)-element vector. Note that H is not hermitian. If the elements of x are all zero and alpha is real, then tau = 0 and H is taken to be the unit matrix. Otherwise 1 <= real(tau) <= 2 and abs(tau-1) <= 1 . Arguments ========= N (input) INTEGER The order of the elementary reflector. ALPHA (input/output) COMPLEX On entry, the value alpha. On exit, it is overwritten with the value beta. X (input/output) COMPLEX array, dimension (1+(N-2)*abs(INCX)) On entry, the vector x. On exit, it is overwritten with the vector v. INCX (input) INTEGER The increment between elements of X. INCX > 0. TAU (output) COMPLEX The value tau. ===================================================================== */ /* Parameter adjustments */ --x; /* Function Body */ if (*n <= 0) { tau->r = 0.f, tau->i = 0.f; return 0; } i__1 = *n - 1; xnorm = scnrm2_(&i__1, &x[1], incx); alphr = alpha->r; alphi = r_imag(alpha); if (xnorm == 0.f && alphi == 0.f) { /* H = I */ tau->r = 0.f, tau->i = 0.f; } else { /* general case */ r__1 = slapy3_(&alphr, &alphi, &xnorm); beta = -r_sign(&r__1, &alphr); safmin = slamch_("S") / slamch_("E"); rsafmn = 1.f / safmin; if (dabs(beta) < safmin) { /* XNORM, BETA may be inaccurate; scale X and recompute them */ knt = 0; L10: ++knt; i__1 = *n - 1; csscal_(&i__1, &rsafmn, &x[1], incx); beta *= rsafmn; alphi *= rsafmn; alphr *= rsafmn; if (dabs(beta) < safmin) { goto L10; } /* New BETA is at most 1, at least SAFMIN */ i__1 = *n - 1; xnorm = scnrm2_(&i__1, &x[1], incx); q__1.r = alphr, q__1.i = alphi; alpha->r = q__1.r, alpha->i = q__1.i; r__1 = slapy3_(&alphr, &alphi, &xnorm); beta = -r_sign(&r__1, &alphr); r__1 = (beta - alphr) / beta; r__2 = -alphi / beta; q__1.r = r__1, q__1.i = r__2; tau->r = q__1.r, tau->i = q__1.i; q__2.r = alpha->r - beta, q__2.i = alpha->i; cladiv_(&q__1, &c_b56, &q__2); alpha->r = q__1.r, alpha->i = q__1.i; i__1 = *n - 1; cscal_(&i__1, alpha, &x[1], incx); /* If ALPHA is subnormal, it may lose relative accuracy */ alpha->r = beta, alpha->i = 0.f; i__1 = knt; for (j = 1; j <= i__1; ++j) { q__1.r = safmin * alpha->r, q__1.i = safmin * alpha->i; alpha->r = q__1.r, alpha->i = q__1.i; /* L20: */ } } else { r__1 = (beta - alphr) / beta; r__2 = -alphi / beta; q__1.r = r__1, q__1.i = r__2; tau->r = q__1.r, tau->i = q__1.i; q__2.r = alpha->r - beta, q__2.i = alpha->i; cladiv_(&q__1, &c_b56, &q__2); alpha->r = q__1.r, alpha->i = q__1.i; i__1 = *n - 1; cscal_(&i__1, alpha, &x[1], incx); alpha->r = beta, alpha->i = 0.f; } } return 0; /* End of CLARFG */ } /* clarfg_ */ /* Subroutine */ int clarft_(char *direct, char *storev, integer *n, integer * k, complex *v, integer *ldv, complex *tau, complex *t, integer *ldt) { /* System generated locals */ integer t_dim1, t_offset, v_dim1, v_offset, i__1, i__2, i__3, i__4; complex q__1; /* Local variables */ static integer i__, j; static complex vii; extern /* Subroutine */ int cgemv_(char *, integer *, integer *, complex * , complex *, integer *, complex *, integer *, complex *, complex * , integer *); extern logical lsame_(char *, char *); extern /* Subroutine */ int ctrmv_(char *, char *, char *, integer *, complex *, integer *, complex *, integer *), clacgv_(integer *, complex *, integer *); /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University September 30, 1994 Purpose ======= CLARFT forms the triangular factor T of a complex block reflector H of order n, which is defined as a product of k elementary reflectors. If DIRECT = 'F', H = H(1) H(2) . . . H(k) and T is upper triangular; If DIRECT = 'B', H = H(k) . . . H(2) H(1) and T is lower triangular. If STOREV = 'C', the vector which defines the elementary reflector H(i) is stored in the i-th column of the array V, and H = I - V * T * V' If STOREV = 'R', the vector which defines the elementary reflector H(i) is stored in the i-th row of the array V, and H = I - V' * T * V Arguments ========= DIRECT (input) CHARACTER*1 Specifies the order in which the elementary reflectors are multiplied to form the block reflector: = 'F': H = H(1) H(2) . . . H(k) (Forward) = 'B': H = H(k) . . . H(2) H(1) (Backward) STOREV (input) CHARACTER*1 Specifies how the vectors which define the elementary reflectors are stored (see also Further Details): = 'C': columnwise = 'R': rowwise N (input) INTEGER The order of the block reflector H. N >= 0. K (input) INTEGER The order of the triangular factor T (= the number of elementary reflectors). K >= 1. V (input/output) COMPLEX array, dimension (LDV,K) if STOREV = 'C' (LDV,N) if STOREV = 'R' The matrix V. See further details. LDV (input) INTEGER The leading dimension of the array V. If STOREV = 'C', LDV >= max(1,N); if STOREV = 'R', LDV >= K. TAU (input) COMPLEX array, dimension (K) TAU(i) must contain the scalar factor of the elementary reflector H(i). T (output) COMPLEX array, dimension (LDT,K) The k by k triangular factor T of the block reflector. If DIRECT = 'F', T is upper triangular; if DIRECT = 'B', T is lower triangular. The rest of the array is not used. LDT (input) INTEGER The leading dimension of the array T. LDT >= K. Further Details =============== The shape of the matrix V and the storage of the vectors which define the H(i) is best illustrated by the following example with n = 5 and k = 3. The elements equal to 1 are not stored; the corresponding array elements are modified but restored on exit. The rest of the array is not used. DIRECT = 'F' and STOREV = 'C': DIRECT = 'F' and STOREV = 'R': V = ( 1 ) V = ( 1 v1 v1 v1 v1 ) ( v1 1 ) ( 1 v2 v2 v2 ) ( v1 v2 1 ) ( 1 v3 v3 ) ( v1 v2 v3 ) ( v1 v2 v3 ) DIRECT = 'B' and STOREV = 'C': DIRECT = 'B' and STOREV = 'R': V = ( v1 v2 v3 ) V = ( v1 v1 1 ) ( v1 v2 v3 ) ( v2 v2 v2 1 ) ( 1 v2 v3 ) ( v3 v3 v3 v3 1 ) ( 1 v3 ) ( 1 ) ===================================================================== Quick return if possible */ /* Parameter adjustments */ v_dim1 = *ldv; v_offset = 1 + v_dim1; v -= v_offset; --tau; t_dim1 = *ldt; t_offset = 1 + t_dim1; t -= t_offset; /* Function Body */ if (*n == 0) { return 0; } if (lsame_(direct, "F")) { i__1 = *k; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = i__; if (tau[i__2].r == 0.f && tau[i__2].i == 0.f) { /* H(i) = I */ i__2 = i__; for (j = 1; j <= i__2; ++j) { i__3 = j + i__ * t_dim1; t[i__3].r = 0.f, t[i__3].i = 0.f; /* L10: */ } } else { /* general case */ i__2 = i__ + i__ * v_dim1; vii.r = v[i__2].r, vii.i = v[i__2].i; i__2 = i__ + i__ * v_dim1; v[i__2].r = 1.f, v[i__2].i = 0.f; if (lsame_(storev, "C")) { /* T(1:i-1,i) := - tau(i) * V(i:n,1:i-1)' * V(i:n,i) */ i__2 = *n - i__ + 1; i__3 = i__ - 1; i__4 = i__; q__1.r = -tau[i__4].r, q__1.i = -tau[i__4].i; cgemv_("Conjugate transpose", &i__2, &i__3, &q__1, &v[i__ + v_dim1], ldv, &v[i__ + i__ * v_dim1], &c__1, & c_b55, &t[i__ * t_dim1 + 1], &c__1); } else { /* T(1:i-1,i) := - tau(i) * V(1:i-1,i:n) * V(i,i:n)' */ if (i__ < *n) { i__2 = *n - i__; clacgv_(&i__2, &v[i__ + (i__ + 1) * v_dim1], ldv); } i__2 = i__ - 1; i__3 = *n - i__ + 1; i__4 = i__; q__1.r = -tau[i__4].r, q__1.i = -tau[i__4].i; cgemv_("No transpose", &i__2, &i__3, &q__1, &v[i__ * v_dim1 + 1], ldv, &v[i__ + i__ * v_dim1], ldv, & c_b55, &t[i__ * t_dim1 + 1], &c__1); if (i__ < *n) { i__2 = *n - i__; clacgv_(&i__2, &v[i__ + (i__ + 1) * v_dim1], ldv); } } i__2 = i__ + i__ * v_dim1; v[i__2].r = vii.r, v[i__2].i = vii.i; /* T(1:i-1,i) := T(1:i-1,1:i-1) * T(1:i-1,i) */ i__2 = i__ - 1; ctrmv_("Upper", "No transpose", "Non-unit", &i__2, &t[ t_offset], ldt, &t[i__ * t_dim1 + 1], &c__1); i__2 = i__ + i__ * t_dim1; i__3 = i__; t[i__2].r = tau[i__3].r, t[i__2].i = tau[i__3].i; } /* L20: */ } } else { for (i__ = *k; i__ >= 1; --i__) { i__1 = i__; if (tau[i__1].r == 0.f && tau[i__1].i == 0.f) { /* H(i) = I */ i__1 = *k; for (j = i__; j <= i__1; ++j) { i__2 = j + i__ * t_dim1; t[i__2].r = 0.f, t[i__2].i = 0.f; /* L30: */ } } else { /* general case */ if (i__ < *k) { if (lsame_(storev, "C")) { i__1 = *n - *k + i__ + i__ * v_dim1; vii.r = v[i__1].r, vii.i = v[i__1].i; i__1 = *n - *k + i__ + i__ * v_dim1; v[i__1].r = 1.f, v[i__1].i = 0.f; /* T(i+1:k,i) := - tau(i) * V(1:n-k+i,i+1:k)' * V(1:n-k+i,i) */ i__1 = *n - *k + i__; i__2 = *k - i__; i__3 = i__; q__1.r = -tau[i__3].r, q__1.i = -tau[i__3].i; cgemv_("Conjugate transpose", &i__1, &i__2, &q__1, &v[ (i__ + 1) * v_dim1 + 1], ldv, &v[i__ * v_dim1 + 1], &c__1, &c_b55, &t[i__ + 1 + i__ * t_dim1], &c__1); i__1 = *n - *k + i__ + i__ * v_dim1; v[i__1].r = vii.r, v[i__1].i = vii.i; } else { i__1 = i__ + (*n - *k + i__) * v_dim1; vii.r = v[i__1].r, vii.i = v[i__1].i; i__1 = i__ + (*n - *k + i__) * v_dim1; v[i__1].r = 1.f, v[i__1].i = 0.f; /* T(i+1:k,i) := - tau(i) * V(i+1:k,1:n-k+i) * V(i,1:n-k+i)' */ i__1 = *n - *k + i__ - 1; clacgv_(&i__1, &v[i__ + v_dim1], ldv); i__1 = *k - i__; i__2 = *n - *k + i__; i__3 = i__; q__1.r = -tau[i__3].r, q__1.i = -tau[i__3].i; cgemv_("No transpose", &i__1, &i__2, &q__1, &v[i__ + 1 + v_dim1], ldv, &v[i__ + v_dim1], ldv, & c_b55, &t[i__ + 1 + i__ * t_dim1], &c__1); i__1 = *n - *k + i__ - 1; clacgv_(&i__1, &v[i__ + v_dim1], ldv); i__1 = i__ + (*n - *k + i__) * v_dim1; v[i__1].r = vii.r, v[i__1].i = vii.i; } /* T(i+1:k,i) := T(i+1:k,i+1:k) * T(i+1:k,i) */ i__1 = *k - i__; ctrmv_("Lower", "No transpose", "Non-unit", &i__1, &t[i__ + 1 + (i__ + 1) * t_dim1], ldt, &t[i__ + 1 + i__ * t_dim1], &c__1) ; } i__1 = i__ + i__ * t_dim1; i__2 = i__; t[i__1].r = tau[i__2].r, t[i__1].i = tau[i__2].i; } /* L40: */ } } return 0; /* End of CLARFT */ } /* clarft_ */ /* Subroutine */ int clarfx_(char *side, integer *m, integer *n, complex *v, complex *tau, complex *c__, integer *ldc, complex *work) { /* System generated locals */ integer c_dim1, c_offset, i__1, i__2, i__3, i__4, i__5, i__6, i__7, i__8, i__9, i__10, i__11; complex q__1, q__2, q__3, q__4, q__5, q__6, q__7, q__8, q__9, q__10, q__11, q__12, q__13, q__14, q__15, q__16, q__17, q__18, q__19; /* Builtin functions */ void r_cnjg(complex *, complex *); /* Local variables */ static integer j; static complex t1, t2, t3, t4, t5, t6, t7, t8, t9, v1, v2, v3, v4, v5, v6, v7, v8, v9, t10, v10, sum; extern /* Subroutine */ int cgerc_(integer *, integer *, complex *, complex *, integer *, complex *, integer *, complex *, integer *); extern logical lsame_(char *, char *); extern /* Subroutine */ int cgemv_(char *, integer *, integer *, complex * , complex *, integer *, complex *, integer *, complex *, complex * , integer *); /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University September 30, 1994 Purpose ======= CLARFX applies a complex elementary reflector H to a complex m by n matrix C, from either the left or the right. H is represented in the form H = I - tau * v * v' where tau is a complex scalar and v is a complex vector. If tau = 0, then H is taken to be the unit matrix This version uses inline code if H has order < 11. Arguments ========= SIDE (input) CHARACTER*1 = 'L': form H * C = 'R': form C * H M (input) INTEGER The number of rows of the matrix C. N (input) INTEGER The number of columns of the matrix C. V (input) COMPLEX array, dimension (M) if SIDE = 'L' or (N) if SIDE = 'R' The vector v in the representation of H. TAU (input) COMPLEX The value tau in the representation of H. C (input/output) COMPLEX array, dimension (LDC,N) On entry, the m by n matrix C. On exit, C is overwritten by the matrix H * C if SIDE = 'L', or C * H if SIDE = 'R'. LDC (input) INTEGER The leading dimension of the array C. LDA >= max(1,M). WORK (workspace) COMPLEX array, dimension (N) if SIDE = 'L' or (M) if SIDE = 'R' WORK is not referenced if H has order < 11. ===================================================================== */ /* Parameter adjustments */ --v; c_dim1 = *ldc; c_offset = 1 + c_dim1; c__ -= c_offset; --work; /* Function Body */ if (tau->r == 0.f && tau->i == 0.f) { return 0; } if (lsame_(side, "L")) { /* Form H * C, where H has order m. */ switch (*m) { case 1: goto L10; case 2: goto L30; case 3: goto L50; case 4: goto L70; case 5: goto L90; case 6: goto L110; case 7: goto L130; case 8: goto L150; case 9: goto L170; case 10: goto L190; } /* Code for general M w := C'*v */ cgemv_("Conjugate transpose", m, n, &c_b56, &c__[c_offset], ldc, &v[1] , &c__1, &c_b55, &work[1], &c__1); /* C := C - tau * v * w' */ q__1.r = -tau->r, q__1.i = -tau->i; cgerc_(m, n, &q__1, &v[1], &c__1, &work[1], &c__1, &c__[c_offset], ldc); goto L410; L10: /* Special code for 1 x 1 Householder */ q__3.r = tau->r * v[1].r - tau->i * v[1].i, q__3.i = tau->r * v[1].i + tau->i * v[1].r; r_cnjg(&q__4, &v[1]); q__2.r = q__3.r * q__4.r - q__3.i * q__4.i, q__2.i = q__3.r * q__4.i + q__3.i * q__4.r; q__1.r = 1.f - q__2.r, q__1.i = 0.f - q__2.i; t1.r = q__1.r, t1.i = q__1.i; i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = j * c_dim1 + 1; i__3 = j * c_dim1 + 1; q__1.r = t1.r * c__[i__3].r - t1.i * c__[i__3].i, q__1.i = t1.r * c__[i__3].i + t1.i * c__[i__3].r; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; /* L20: */ } goto L410; L30: /* Special code for 2 x 2 Householder */ r_cnjg(&q__1, &v[1]); v1.r = q__1.r, v1.i = q__1.i; r_cnjg(&q__2, &v1); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t1.r = q__1.r, t1.i = q__1.i; r_cnjg(&q__1, &v[2]); v2.r = q__1.r, v2.i = q__1.i; r_cnjg(&q__2, &v2); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t2.r = q__1.r, t2.i = q__1.i; i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = j * c_dim1 + 1; q__2.r = v1.r * c__[i__2].r - v1.i * c__[i__2].i, q__2.i = v1.r * c__[i__2].i + v1.i * c__[i__2].r; i__3 = j * c_dim1 + 2; q__3.r = v2.r * c__[i__3].r - v2.i * c__[i__3].i, q__3.i = v2.r * c__[i__3].i + v2.i * c__[i__3].r; q__1.r = q__2.r + q__3.r, q__1.i = q__2.i + q__3.i; sum.r = q__1.r, sum.i = q__1.i; i__2 = j * c_dim1 + 1; i__3 = j * c_dim1 + 1; q__2.r = sum.r * t1.r - sum.i * t1.i, q__2.i = sum.r * t1.i + sum.i * t1.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; i__2 = j * c_dim1 + 2; i__3 = j * c_dim1 + 2; q__2.r = sum.r * t2.r - sum.i * t2.i, q__2.i = sum.r * t2.i + sum.i * t2.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; /* L40: */ } goto L410; L50: /* Special code for 3 x 3 Householder */ r_cnjg(&q__1, &v[1]); v1.r = q__1.r, v1.i = q__1.i; r_cnjg(&q__2, &v1); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t1.r = q__1.r, t1.i = q__1.i; r_cnjg(&q__1, &v[2]); v2.r = q__1.r, v2.i = q__1.i; r_cnjg(&q__2, &v2); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t2.r = q__1.r, t2.i = q__1.i; r_cnjg(&q__1, &v[3]); v3.r = q__1.r, v3.i = q__1.i; r_cnjg(&q__2, &v3); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t3.r = q__1.r, t3.i = q__1.i; i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = j * c_dim1 + 1; q__3.r = v1.r * c__[i__2].r - v1.i * c__[i__2].i, q__3.i = v1.r * c__[i__2].i + v1.i * c__[i__2].r; i__3 = j * c_dim1 + 2; q__4.r = v2.r * c__[i__3].r - v2.i * c__[i__3].i, q__4.i = v2.r * c__[i__3].i + v2.i * c__[i__3].r; q__2.r = q__3.r + q__4.r, q__2.i = q__3.i + q__4.i; i__4 = j * c_dim1 + 3; q__5.r = v3.r * c__[i__4].r - v3.i * c__[i__4].i, q__5.i = v3.r * c__[i__4].i + v3.i * c__[i__4].r; q__1.r = q__2.r + q__5.r, q__1.i = q__2.i + q__5.i; sum.r = q__1.r, sum.i = q__1.i; i__2 = j * c_dim1 + 1; i__3 = j * c_dim1 + 1; q__2.r = sum.r * t1.r - sum.i * t1.i, q__2.i = sum.r * t1.i + sum.i * t1.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; i__2 = j * c_dim1 + 2; i__3 = j * c_dim1 + 2; q__2.r = sum.r * t2.r - sum.i * t2.i, q__2.i = sum.r * t2.i + sum.i * t2.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; i__2 = j * c_dim1 + 3; i__3 = j * c_dim1 + 3; q__2.r = sum.r * t3.r - sum.i * t3.i, q__2.i = sum.r * t3.i + sum.i * t3.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; /* L60: */ } goto L410; L70: /* Special code for 4 x 4 Householder */ r_cnjg(&q__1, &v[1]); v1.r = q__1.r, v1.i = q__1.i; r_cnjg(&q__2, &v1); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t1.r = q__1.r, t1.i = q__1.i; r_cnjg(&q__1, &v[2]); v2.r = q__1.r, v2.i = q__1.i; r_cnjg(&q__2, &v2); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t2.r = q__1.r, t2.i = q__1.i; r_cnjg(&q__1, &v[3]); v3.r = q__1.r, v3.i = q__1.i; r_cnjg(&q__2, &v3); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t3.r = q__1.r, t3.i = q__1.i; r_cnjg(&q__1, &v[4]); v4.r = q__1.r, v4.i = q__1.i; r_cnjg(&q__2, &v4); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t4.r = q__1.r, t4.i = q__1.i; i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = j * c_dim1 + 1; q__4.r = v1.r * c__[i__2].r - v1.i * c__[i__2].i, q__4.i = v1.r * c__[i__2].i + v1.i * c__[i__2].r; i__3 = j * c_dim1 + 2; q__5.r = v2.r * c__[i__3].r - v2.i * c__[i__3].i, q__5.i = v2.r * c__[i__3].i + v2.i * c__[i__3].r; q__3.r = q__4.r + q__5.r, q__3.i = q__4.i + q__5.i; i__4 = j * c_dim1 + 3; q__6.r = v3.r * c__[i__4].r - v3.i * c__[i__4].i, q__6.i = v3.r * c__[i__4].i + v3.i * c__[i__4].r; q__2.r = q__3.r + q__6.r, q__2.i = q__3.i + q__6.i; i__5 = j * c_dim1 + 4; q__7.r = v4.r * c__[i__5].r - v4.i * c__[i__5].i, q__7.i = v4.r * c__[i__5].i + v4.i * c__[i__5].r; q__1.r = q__2.r + q__7.r, q__1.i = q__2.i + q__7.i; sum.r = q__1.r, sum.i = q__1.i; i__2 = j * c_dim1 + 1; i__3 = j * c_dim1 + 1; q__2.r = sum.r * t1.r - sum.i * t1.i, q__2.i = sum.r * t1.i + sum.i * t1.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; i__2 = j * c_dim1 + 2; i__3 = j * c_dim1 + 2; q__2.r = sum.r * t2.r - sum.i * t2.i, q__2.i = sum.r * t2.i + sum.i * t2.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; i__2 = j * c_dim1 + 3; i__3 = j * c_dim1 + 3; q__2.r = sum.r * t3.r - sum.i * t3.i, q__2.i = sum.r * t3.i + sum.i * t3.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; i__2 = j * c_dim1 + 4; i__3 = j * c_dim1 + 4; q__2.r = sum.r * t4.r - sum.i * t4.i, q__2.i = sum.r * t4.i + sum.i * t4.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; /* L80: */ } goto L410; L90: /* Special code for 5 x 5 Householder */ r_cnjg(&q__1, &v[1]); v1.r = q__1.r, v1.i = q__1.i; r_cnjg(&q__2, &v1); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t1.r = q__1.r, t1.i = q__1.i; r_cnjg(&q__1, &v[2]); v2.r = q__1.r, v2.i = q__1.i; r_cnjg(&q__2, &v2); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t2.r = q__1.r, t2.i = q__1.i; r_cnjg(&q__1, &v[3]); v3.r = q__1.r, v3.i = q__1.i; r_cnjg(&q__2, &v3); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t3.r = q__1.r, t3.i = q__1.i; r_cnjg(&q__1, &v[4]); v4.r = q__1.r, v4.i = q__1.i; r_cnjg(&q__2, &v4); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t4.r = q__1.r, t4.i = q__1.i; r_cnjg(&q__1, &v[5]); v5.r = q__1.r, v5.i = q__1.i; r_cnjg(&q__2, &v5); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t5.r = q__1.r, t5.i = q__1.i; i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = j * c_dim1 + 1; q__5.r = v1.r * c__[i__2].r - v1.i * c__[i__2].i, q__5.i = v1.r * c__[i__2].i + v1.i * c__[i__2].r; i__3 = j * c_dim1 + 2; q__6.r = v2.r * c__[i__3].r - v2.i * c__[i__3].i, q__6.i = v2.r * c__[i__3].i + v2.i * c__[i__3].r; q__4.r = q__5.r + q__6.r, q__4.i = q__5.i + q__6.i; i__4 = j * c_dim1 + 3; q__7.r = v3.r * c__[i__4].r - v3.i * c__[i__4].i, q__7.i = v3.r * c__[i__4].i + v3.i * c__[i__4].r; q__3.r = q__4.r + q__7.r, q__3.i = q__4.i + q__7.i; i__5 = j * c_dim1 + 4; q__8.r = v4.r * c__[i__5].r - v4.i * c__[i__5].i, q__8.i = v4.r * c__[i__5].i + v4.i * c__[i__5].r; q__2.r = q__3.r + q__8.r, q__2.i = q__3.i + q__8.i; i__6 = j * c_dim1 + 5; q__9.r = v5.r * c__[i__6].r - v5.i * c__[i__6].i, q__9.i = v5.r * c__[i__6].i + v5.i * c__[i__6].r; q__1.r = q__2.r + q__9.r, q__1.i = q__2.i + q__9.i; sum.r = q__1.r, sum.i = q__1.i; i__2 = j * c_dim1 + 1; i__3 = j * c_dim1 + 1; q__2.r = sum.r * t1.r - sum.i * t1.i, q__2.i = sum.r * t1.i + sum.i * t1.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; i__2 = j * c_dim1 + 2; i__3 = j * c_dim1 + 2; q__2.r = sum.r * t2.r - sum.i * t2.i, q__2.i = sum.r * t2.i + sum.i * t2.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; i__2 = j * c_dim1 + 3; i__3 = j * c_dim1 + 3; q__2.r = sum.r * t3.r - sum.i * t3.i, q__2.i = sum.r * t3.i + sum.i * t3.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; i__2 = j * c_dim1 + 4; i__3 = j * c_dim1 + 4; q__2.r = sum.r * t4.r - sum.i * t4.i, q__2.i = sum.r * t4.i + sum.i * t4.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; i__2 = j * c_dim1 + 5; i__3 = j * c_dim1 + 5; q__2.r = sum.r * t5.r - sum.i * t5.i, q__2.i = sum.r * t5.i + sum.i * t5.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; /* L100: */ } goto L410; L110: /* Special code for 6 x 6 Householder */ r_cnjg(&q__1, &v[1]); v1.r = q__1.r, v1.i = q__1.i; r_cnjg(&q__2, &v1); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t1.r = q__1.r, t1.i = q__1.i; r_cnjg(&q__1, &v[2]); v2.r = q__1.r, v2.i = q__1.i; r_cnjg(&q__2, &v2); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t2.r = q__1.r, t2.i = q__1.i; r_cnjg(&q__1, &v[3]); v3.r = q__1.r, v3.i = q__1.i; r_cnjg(&q__2, &v3); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t3.r = q__1.r, t3.i = q__1.i; r_cnjg(&q__1, &v[4]); v4.r = q__1.r, v4.i = q__1.i; r_cnjg(&q__2, &v4); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t4.r = q__1.r, t4.i = q__1.i; r_cnjg(&q__1, &v[5]); v5.r = q__1.r, v5.i = q__1.i; r_cnjg(&q__2, &v5); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t5.r = q__1.r, t5.i = q__1.i; r_cnjg(&q__1, &v[6]); v6.r = q__1.r, v6.i = q__1.i; r_cnjg(&q__2, &v6); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t6.r = q__1.r, t6.i = q__1.i; i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = j * c_dim1 + 1; q__6.r = v1.r * c__[i__2].r - v1.i * c__[i__2].i, q__6.i = v1.r * c__[i__2].i + v1.i * c__[i__2].r; i__3 = j * c_dim1 + 2; q__7.r = v2.r * c__[i__3].r - v2.i * c__[i__3].i, q__7.i = v2.r * c__[i__3].i + v2.i * c__[i__3].r; q__5.r = q__6.r + q__7.r, q__5.i = q__6.i + q__7.i; i__4 = j * c_dim1 + 3; q__8.r = v3.r * c__[i__4].r - v3.i * c__[i__4].i, q__8.i = v3.r * c__[i__4].i + v3.i * c__[i__4].r; q__4.r = q__5.r + q__8.r, q__4.i = q__5.i + q__8.i; i__5 = j * c_dim1 + 4; q__9.r = v4.r * c__[i__5].r - v4.i * c__[i__5].i, q__9.i = v4.r * c__[i__5].i + v4.i * c__[i__5].r; q__3.r = q__4.r + q__9.r, q__3.i = q__4.i + q__9.i; i__6 = j * c_dim1 + 5; q__10.r = v5.r * c__[i__6].r - v5.i * c__[i__6].i, q__10.i = v5.r * c__[i__6].i + v5.i * c__[i__6].r; q__2.r = q__3.r + q__10.r, q__2.i = q__3.i + q__10.i; i__7 = j * c_dim1 + 6; q__11.r = v6.r * c__[i__7].r - v6.i * c__[i__7].i, q__11.i = v6.r * c__[i__7].i + v6.i * c__[i__7].r; q__1.r = q__2.r + q__11.r, q__1.i = q__2.i + q__11.i; sum.r = q__1.r, sum.i = q__1.i; i__2 = j * c_dim1 + 1; i__3 = j * c_dim1 + 1; q__2.r = sum.r * t1.r - sum.i * t1.i, q__2.i = sum.r * t1.i + sum.i * t1.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; i__2 = j * c_dim1 + 2; i__3 = j * c_dim1 + 2; q__2.r = sum.r * t2.r - sum.i * t2.i, q__2.i = sum.r * t2.i + sum.i * t2.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; i__2 = j * c_dim1 + 3; i__3 = j * c_dim1 + 3; q__2.r = sum.r * t3.r - sum.i * t3.i, q__2.i = sum.r * t3.i + sum.i * t3.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; i__2 = j * c_dim1 + 4; i__3 = j * c_dim1 + 4; q__2.r = sum.r * t4.r - sum.i * t4.i, q__2.i = sum.r * t4.i + sum.i * t4.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; i__2 = j * c_dim1 + 5; i__3 = j * c_dim1 + 5; q__2.r = sum.r * t5.r - sum.i * t5.i, q__2.i = sum.r * t5.i + sum.i * t5.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; i__2 = j * c_dim1 + 6; i__3 = j * c_dim1 + 6; q__2.r = sum.r * t6.r - sum.i * t6.i, q__2.i = sum.r * t6.i + sum.i * t6.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; /* L120: */ } goto L410; L130: /* Special code for 7 x 7 Householder */ r_cnjg(&q__1, &v[1]); v1.r = q__1.r, v1.i = q__1.i; r_cnjg(&q__2, &v1); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t1.r = q__1.r, t1.i = q__1.i; r_cnjg(&q__1, &v[2]); v2.r = q__1.r, v2.i = q__1.i; r_cnjg(&q__2, &v2); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t2.r = q__1.r, t2.i = q__1.i; r_cnjg(&q__1, &v[3]); v3.r = q__1.r, v3.i = q__1.i; r_cnjg(&q__2, &v3); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t3.r = q__1.r, t3.i = q__1.i; r_cnjg(&q__1, &v[4]); v4.r = q__1.r, v4.i = q__1.i; r_cnjg(&q__2, &v4); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t4.r = q__1.r, t4.i = q__1.i; r_cnjg(&q__1, &v[5]); v5.r = q__1.r, v5.i = q__1.i; r_cnjg(&q__2, &v5); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t5.r = q__1.r, t5.i = q__1.i; r_cnjg(&q__1, &v[6]); v6.r = q__1.r, v6.i = q__1.i; r_cnjg(&q__2, &v6); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t6.r = q__1.r, t6.i = q__1.i; r_cnjg(&q__1, &v[7]); v7.r = q__1.r, v7.i = q__1.i; r_cnjg(&q__2, &v7); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t7.r = q__1.r, t7.i = q__1.i; i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = j * c_dim1 + 1; q__7.r = v1.r * c__[i__2].r - v1.i * c__[i__2].i, q__7.i = v1.r * c__[i__2].i + v1.i * c__[i__2].r; i__3 = j * c_dim1 + 2; q__8.r = v2.r * c__[i__3].r - v2.i * c__[i__3].i, q__8.i = v2.r * c__[i__3].i + v2.i * c__[i__3].r; q__6.r = q__7.r + q__8.r, q__6.i = q__7.i + q__8.i; i__4 = j * c_dim1 + 3; q__9.r = v3.r * c__[i__4].r - v3.i * c__[i__4].i, q__9.i = v3.r * c__[i__4].i + v3.i * c__[i__4].r; q__5.r = q__6.r + q__9.r, q__5.i = q__6.i + q__9.i; i__5 = j * c_dim1 + 4; q__10.r = v4.r * c__[i__5].r - v4.i * c__[i__5].i, q__10.i = v4.r * c__[i__5].i + v4.i * c__[i__5].r; q__4.r = q__5.r + q__10.r, q__4.i = q__5.i + q__10.i; i__6 = j * c_dim1 + 5; q__11.r = v5.r * c__[i__6].r - v5.i * c__[i__6].i, q__11.i = v5.r * c__[i__6].i + v5.i * c__[i__6].r; q__3.r = q__4.r + q__11.r, q__3.i = q__4.i + q__11.i; i__7 = j * c_dim1 + 6; q__12.r = v6.r * c__[i__7].r - v6.i * c__[i__7].i, q__12.i = v6.r * c__[i__7].i + v6.i * c__[i__7].r; q__2.r = q__3.r + q__12.r, q__2.i = q__3.i + q__12.i; i__8 = j * c_dim1 + 7; q__13.r = v7.r * c__[i__8].r - v7.i * c__[i__8].i, q__13.i = v7.r * c__[i__8].i + v7.i * c__[i__8].r; q__1.r = q__2.r + q__13.r, q__1.i = q__2.i + q__13.i; sum.r = q__1.r, sum.i = q__1.i; i__2 = j * c_dim1 + 1; i__3 = j * c_dim1 + 1; q__2.r = sum.r * t1.r - sum.i * t1.i, q__2.i = sum.r * t1.i + sum.i * t1.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; i__2 = j * c_dim1 + 2; i__3 = j * c_dim1 + 2; q__2.r = sum.r * t2.r - sum.i * t2.i, q__2.i = sum.r * t2.i + sum.i * t2.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; i__2 = j * c_dim1 + 3; i__3 = j * c_dim1 + 3; q__2.r = sum.r * t3.r - sum.i * t3.i, q__2.i = sum.r * t3.i + sum.i * t3.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; i__2 = j * c_dim1 + 4; i__3 = j * c_dim1 + 4; q__2.r = sum.r * t4.r - sum.i * t4.i, q__2.i = sum.r * t4.i + sum.i * t4.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; i__2 = j * c_dim1 + 5; i__3 = j * c_dim1 + 5; q__2.r = sum.r * t5.r - sum.i * t5.i, q__2.i = sum.r * t5.i + sum.i * t5.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; i__2 = j * c_dim1 + 6; i__3 = j * c_dim1 + 6; q__2.r = sum.r * t6.r - sum.i * t6.i, q__2.i = sum.r * t6.i + sum.i * t6.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; i__2 = j * c_dim1 + 7; i__3 = j * c_dim1 + 7; q__2.r = sum.r * t7.r - sum.i * t7.i, q__2.i = sum.r * t7.i + sum.i * t7.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; /* L140: */ } goto L410; L150: /* Special code for 8 x 8 Householder */ r_cnjg(&q__1, &v[1]); v1.r = q__1.r, v1.i = q__1.i; r_cnjg(&q__2, &v1); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t1.r = q__1.r, t1.i = q__1.i; r_cnjg(&q__1, &v[2]); v2.r = q__1.r, v2.i = q__1.i; r_cnjg(&q__2, &v2); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t2.r = q__1.r, t2.i = q__1.i; r_cnjg(&q__1, &v[3]); v3.r = q__1.r, v3.i = q__1.i; r_cnjg(&q__2, &v3); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t3.r = q__1.r, t3.i = q__1.i; r_cnjg(&q__1, &v[4]); v4.r = q__1.r, v4.i = q__1.i; r_cnjg(&q__2, &v4); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t4.r = q__1.r, t4.i = q__1.i; r_cnjg(&q__1, &v[5]); v5.r = q__1.r, v5.i = q__1.i; r_cnjg(&q__2, &v5); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t5.r = q__1.r, t5.i = q__1.i; r_cnjg(&q__1, &v[6]); v6.r = q__1.r, v6.i = q__1.i; r_cnjg(&q__2, &v6); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t6.r = q__1.r, t6.i = q__1.i; r_cnjg(&q__1, &v[7]); v7.r = q__1.r, v7.i = q__1.i; r_cnjg(&q__2, &v7); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t7.r = q__1.r, t7.i = q__1.i; r_cnjg(&q__1, &v[8]); v8.r = q__1.r, v8.i = q__1.i; r_cnjg(&q__2, &v8); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t8.r = q__1.r, t8.i = q__1.i; i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = j * c_dim1 + 1; q__8.r = v1.r * c__[i__2].r - v1.i * c__[i__2].i, q__8.i = v1.r * c__[i__2].i + v1.i * c__[i__2].r; i__3 = j * c_dim1 + 2; q__9.r = v2.r * c__[i__3].r - v2.i * c__[i__3].i, q__9.i = v2.r * c__[i__3].i + v2.i * c__[i__3].r; q__7.r = q__8.r + q__9.r, q__7.i = q__8.i + q__9.i; i__4 = j * c_dim1 + 3; q__10.r = v3.r * c__[i__4].r - v3.i * c__[i__4].i, q__10.i = v3.r * c__[i__4].i + v3.i * c__[i__4].r; q__6.r = q__7.r + q__10.r, q__6.i = q__7.i + q__10.i; i__5 = j * c_dim1 + 4; q__11.r = v4.r * c__[i__5].r - v4.i * c__[i__5].i, q__11.i = v4.r * c__[i__5].i + v4.i * c__[i__5].r; q__5.r = q__6.r + q__11.r, q__5.i = q__6.i + q__11.i; i__6 = j * c_dim1 + 5; q__12.r = v5.r * c__[i__6].r - v5.i * c__[i__6].i, q__12.i = v5.r * c__[i__6].i + v5.i * c__[i__6].r; q__4.r = q__5.r + q__12.r, q__4.i = q__5.i + q__12.i; i__7 = j * c_dim1 + 6; q__13.r = v6.r * c__[i__7].r - v6.i * c__[i__7].i, q__13.i = v6.r * c__[i__7].i + v6.i * c__[i__7].r; q__3.r = q__4.r + q__13.r, q__3.i = q__4.i + q__13.i; i__8 = j * c_dim1 + 7; q__14.r = v7.r * c__[i__8].r - v7.i * c__[i__8].i, q__14.i = v7.r * c__[i__8].i + v7.i * c__[i__8].r; q__2.r = q__3.r + q__14.r, q__2.i = q__3.i + q__14.i; i__9 = j * c_dim1 + 8; q__15.r = v8.r * c__[i__9].r - v8.i * c__[i__9].i, q__15.i = v8.r * c__[i__9].i + v8.i * c__[i__9].r; q__1.r = q__2.r + q__15.r, q__1.i = q__2.i + q__15.i; sum.r = q__1.r, sum.i = q__1.i; i__2 = j * c_dim1 + 1; i__3 = j * c_dim1 + 1; q__2.r = sum.r * t1.r - sum.i * t1.i, q__2.i = sum.r * t1.i + sum.i * t1.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; i__2 = j * c_dim1 + 2; i__3 = j * c_dim1 + 2; q__2.r = sum.r * t2.r - sum.i * t2.i, q__2.i = sum.r * t2.i + sum.i * t2.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; i__2 = j * c_dim1 + 3; i__3 = j * c_dim1 + 3; q__2.r = sum.r * t3.r - sum.i * t3.i, q__2.i = sum.r * t3.i + sum.i * t3.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; i__2 = j * c_dim1 + 4; i__3 = j * c_dim1 + 4; q__2.r = sum.r * t4.r - sum.i * t4.i, q__2.i = sum.r * t4.i + sum.i * t4.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; i__2 = j * c_dim1 + 5; i__3 = j * c_dim1 + 5; q__2.r = sum.r * t5.r - sum.i * t5.i, q__2.i = sum.r * t5.i + sum.i * t5.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; i__2 = j * c_dim1 + 6; i__3 = j * c_dim1 + 6; q__2.r = sum.r * t6.r - sum.i * t6.i, q__2.i = sum.r * t6.i + sum.i * t6.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; i__2 = j * c_dim1 + 7; i__3 = j * c_dim1 + 7; q__2.r = sum.r * t7.r - sum.i * t7.i, q__2.i = sum.r * t7.i + sum.i * t7.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; i__2 = j * c_dim1 + 8; i__3 = j * c_dim1 + 8; q__2.r = sum.r * t8.r - sum.i * t8.i, q__2.i = sum.r * t8.i + sum.i * t8.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; /* L160: */ } goto L410; L170: /* Special code for 9 x 9 Householder */ r_cnjg(&q__1, &v[1]); v1.r = q__1.r, v1.i = q__1.i; r_cnjg(&q__2, &v1); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t1.r = q__1.r, t1.i = q__1.i; r_cnjg(&q__1, &v[2]); v2.r = q__1.r, v2.i = q__1.i; r_cnjg(&q__2, &v2); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t2.r = q__1.r, t2.i = q__1.i; r_cnjg(&q__1, &v[3]); v3.r = q__1.r, v3.i = q__1.i; r_cnjg(&q__2, &v3); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t3.r = q__1.r, t3.i = q__1.i; r_cnjg(&q__1, &v[4]); v4.r = q__1.r, v4.i = q__1.i; r_cnjg(&q__2, &v4); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t4.r = q__1.r, t4.i = q__1.i; r_cnjg(&q__1, &v[5]); v5.r = q__1.r, v5.i = q__1.i; r_cnjg(&q__2, &v5); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t5.r = q__1.r, t5.i = q__1.i; r_cnjg(&q__1, &v[6]); v6.r = q__1.r, v6.i = q__1.i; r_cnjg(&q__2, &v6); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t6.r = q__1.r, t6.i = q__1.i; r_cnjg(&q__1, &v[7]); v7.r = q__1.r, v7.i = q__1.i; r_cnjg(&q__2, &v7); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t7.r = q__1.r, t7.i = q__1.i; r_cnjg(&q__1, &v[8]); v8.r = q__1.r, v8.i = q__1.i; r_cnjg(&q__2, &v8); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t8.r = q__1.r, t8.i = q__1.i; r_cnjg(&q__1, &v[9]); v9.r = q__1.r, v9.i = q__1.i; r_cnjg(&q__2, &v9); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t9.r = q__1.r, t9.i = q__1.i; i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = j * c_dim1 + 1; q__9.r = v1.r * c__[i__2].r - v1.i * c__[i__2].i, q__9.i = v1.r * c__[i__2].i + v1.i * c__[i__2].r; i__3 = j * c_dim1 + 2; q__10.r = v2.r * c__[i__3].r - v2.i * c__[i__3].i, q__10.i = v2.r * c__[i__3].i + v2.i * c__[i__3].r; q__8.r = q__9.r + q__10.r, q__8.i = q__9.i + q__10.i; i__4 = j * c_dim1 + 3; q__11.r = v3.r * c__[i__4].r - v3.i * c__[i__4].i, q__11.i = v3.r * c__[i__4].i + v3.i * c__[i__4].r; q__7.r = q__8.r + q__11.r, q__7.i = q__8.i + q__11.i; i__5 = j * c_dim1 + 4; q__12.r = v4.r * c__[i__5].r - v4.i * c__[i__5].i, q__12.i = v4.r * c__[i__5].i + v4.i * c__[i__5].r; q__6.r = q__7.r + q__12.r, q__6.i = q__7.i + q__12.i; i__6 = j * c_dim1 + 5; q__13.r = v5.r * c__[i__6].r - v5.i * c__[i__6].i, q__13.i = v5.r * c__[i__6].i + v5.i * c__[i__6].r; q__5.r = q__6.r + q__13.r, q__5.i = q__6.i + q__13.i; i__7 = j * c_dim1 + 6; q__14.r = v6.r * c__[i__7].r - v6.i * c__[i__7].i, q__14.i = v6.r * c__[i__7].i + v6.i * c__[i__7].r; q__4.r = q__5.r + q__14.r, q__4.i = q__5.i + q__14.i; i__8 = j * c_dim1 + 7; q__15.r = v7.r * c__[i__8].r - v7.i * c__[i__8].i, q__15.i = v7.r * c__[i__8].i + v7.i * c__[i__8].r; q__3.r = q__4.r + q__15.r, q__3.i = q__4.i + q__15.i; i__9 = j * c_dim1 + 8; q__16.r = v8.r * c__[i__9].r - v8.i * c__[i__9].i, q__16.i = v8.r * c__[i__9].i + v8.i * c__[i__9].r; q__2.r = q__3.r + q__16.r, q__2.i = q__3.i + q__16.i; i__10 = j * c_dim1 + 9; q__17.r = v9.r * c__[i__10].r - v9.i * c__[i__10].i, q__17.i = v9.r * c__[i__10].i + v9.i * c__[i__10].r; q__1.r = q__2.r + q__17.r, q__1.i = q__2.i + q__17.i; sum.r = q__1.r, sum.i = q__1.i; i__2 = j * c_dim1 + 1; i__3 = j * c_dim1 + 1; q__2.r = sum.r * t1.r - sum.i * t1.i, q__2.i = sum.r * t1.i + sum.i * t1.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; i__2 = j * c_dim1 + 2; i__3 = j * c_dim1 + 2; q__2.r = sum.r * t2.r - sum.i * t2.i, q__2.i = sum.r * t2.i + sum.i * t2.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; i__2 = j * c_dim1 + 3; i__3 = j * c_dim1 + 3; q__2.r = sum.r * t3.r - sum.i * t3.i, q__2.i = sum.r * t3.i + sum.i * t3.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; i__2 = j * c_dim1 + 4; i__3 = j * c_dim1 + 4; q__2.r = sum.r * t4.r - sum.i * t4.i, q__2.i = sum.r * t4.i + sum.i * t4.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; i__2 = j * c_dim1 + 5; i__3 = j * c_dim1 + 5; q__2.r = sum.r * t5.r - sum.i * t5.i, q__2.i = sum.r * t5.i + sum.i * t5.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; i__2 = j * c_dim1 + 6; i__3 = j * c_dim1 + 6; q__2.r = sum.r * t6.r - sum.i * t6.i, q__2.i = sum.r * t6.i + sum.i * t6.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; i__2 = j * c_dim1 + 7; i__3 = j * c_dim1 + 7; q__2.r = sum.r * t7.r - sum.i * t7.i, q__2.i = sum.r * t7.i + sum.i * t7.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; i__2 = j * c_dim1 + 8; i__3 = j * c_dim1 + 8; q__2.r = sum.r * t8.r - sum.i * t8.i, q__2.i = sum.r * t8.i + sum.i * t8.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; i__2 = j * c_dim1 + 9; i__3 = j * c_dim1 + 9; q__2.r = sum.r * t9.r - sum.i * t9.i, q__2.i = sum.r * t9.i + sum.i * t9.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; /* L180: */ } goto L410; L190: /* Special code for 10 x 10 Householder */ r_cnjg(&q__1, &v[1]); v1.r = q__1.r, v1.i = q__1.i; r_cnjg(&q__2, &v1); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t1.r = q__1.r, t1.i = q__1.i; r_cnjg(&q__1, &v[2]); v2.r = q__1.r, v2.i = q__1.i; r_cnjg(&q__2, &v2); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t2.r = q__1.r, t2.i = q__1.i; r_cnjg(&q__1, &v[3]); v3.r = q__1.r, v3.i = q__1.i; r_cnjg(&q__2, &v3); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t3.r = q__1.r, t3.i = q__1.i; r_cnjg(&q__1, &v[4]); v4.r = q__1.r, v4.i = q__1.i; r_cnjg(&q__2, &v4); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t4.r = q__1.r, t4.i = q__1.i; r_cnjg(&q__1, &v[5]); v5.r = q__1.r, v5.i = q__1.i; r_cnjg(&q__2, &v5); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t5.r = q__1.r, t5.i = q__1.i; r_cnjg(&q__1, &v[6]); v6.r = q__1.r, v6.i = q__1.i; r_cnjg(&q__2, &v6); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t6.r = q__1.r, t6.i = q__1.i; r_cnjg(&q__1, &v[7]); v7.r = q__1.r, v7.i = q__1.i; r_cnjg(&q__2, &v7); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t7.r = q__1.r, t7.i = q__1.i; r_cnjg(&q__1, &v[8]); v8.r = q__1.r, v8.i = q__1.i; r_cnjg(&q__2, &v8); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t8.r = q__1.r, t8.i = q__1.i; r_cnjg(&q__1, &v[9]); v9.r = q__1.r, v9.i = q__1.i; r_cnjg(&q__2, &v9); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t9.r = q__1.r, t9.i = q__1.i; r_cnjg(&q__1, &v[10]); v10.r = q__1.r, v10.i = q__1.i; r_cnjg(&q__2, &v10); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t10.r = q__1.r, t10.i = q__1.i; i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = j * c_dim1 + 1; q__10.r = v1.r * c__[i__2].r - v1.i * c__[i__2].i, q__10.i = v1.r * c__[i__2].i + v1.i * c__[i__2].r; i__3 = j * c_dim1 + 2; q__11.r = v2.r * c__[i__3].r - v2.i * c__[i__3].i, q__11.i = v2.r * c__[i__3].i + v2.i * c__[i__3].r; q__9.r = q__10.r + q__11.r, q__9.i = q__10.i + q__11.i; i__4 = j * c_dim1 + 3; q__12.r = v3.r * c__[i__4].r - v3.i * c__[i__4].i, q__12.i = v3.r * c__[i__4].i + v3.i * c__[i__4].r; q__8.r = q__9.r + q__12.r, q__8.i = q__9.i + q__12.i; i__5 = j * c_dim1 + 4; q__13.r = v4.r * c__[i__5].r - v4.i * c__[i__5].i, q__13.i = v4.r * c__[i__5].i + v4.i * c__[i__5].r; q__7.r = q__8.r + q__13.r, q__7.i = q__8.i + q__13.i; i__6 = j * c_dim1 + 5; q__14.r = v5.r * c__[i__6].r - v5.i * c__[i__6].i, q__14.i = v5.r * c__[i__6].i + v5.i * c__[i__6].r; q__6.r = q__7.r + q__14.r, q__6.i = q__7.i + q__14.i; i__7 = j * c_dim1 + 6; q__15.r = v6.r * c__[i__7].r - v6.i * c__[i__7].i, q__15.i = v6.r * c__[i__7].i + v6.i * c__[i__7].r; q__5.r = q__6.r + q__15.r, q__5.i = q__6.i + q__15.i; i__8 = j * c_dim1 + 7; q__16.r = v7.r * c__[i__8].r - v7.i * c__[i__8].i, q__16.i = v7.r * c__[i__8].i + v7.i * c__[i__8].r; q__4.r = q__5.r + q__16.r, q__4.i = q__5.i + q__16.i; i__9 = j * c_dim1 + 8; q__17.r = v8.r * c__[i__9].r - v8.i * c__[i__9].i, q__17.i = v8.r * c__[i__9].i + v8.i * c__[i__9].r; q__3.r = q__4.r + q__17.r, q__3.i = q__4.i + q__17.i; i__10 = j * c_dim1 + 9; q__18.r = v9.r * c__[i__10].r - v9.i * c__[i__10].i, q__18.i = v9.r * c__[i__10].i + v9.i * c__[i__10].r; q__2.r = q__3.r + q__18.r, q__2.i = q__3.i + q__18.i; i__11 = j * c_dim1 + 10; q__19.r = v10.r * c__[i__11].r - v10.i * c__[i__11].i, q__19.i = v10.r * c__[i__11].i + v10.i * c__[i__11].r; q__1.r = q__2.r + q__19.r, q__1.i = q__2.i + q__19.i; sum.r = q__1.r, sum.i = q__1.i; i__2 = j * c_dim1 + 1; i__3 = j * c_dim1 + 1; q__2.r = sum.r * t1.r - sum.i * t1.i, q__2.i = sum.r * t1.i + sum.i * t1.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; i__2 = j * c_dim1 + 2; i__3 = j * c_dim1 + 2; q__2.r = sum.r * t2.r - sum.i * t2.i, q__2.i = sum.r * t2.i + sum.i * t2.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; i__2 = j * c_dim1 + 3; i__3 = j * c_dim1 + 3; q__2.r = sum.r * t3.r - sum.i * t3.i, q__2.i = sum.r * t3.i + sum.i * t3.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; i__2 = j * c_dim1 + 4; i__3 = j * c_dim1 + 4; q__2.r = sum.r * t4.r - sum.i * t4.i, q__2.i = sum.r * t4.i + sum.i * t4.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; i__2 = j * c_dim1 + 5; i__3 = j * c_dim1 + 5; q__2.r = sum.r * t5.r - sum.i * t5.i, q__2.i = sum.r * t5.i + sum.i * t5.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; i__2 = j * c_dim1 + 6; i__3 = j * c_dim1 + 6; q__2.r = sum.r * t6.r - sum.i * t6.i, q__2.i = sum.r * t6.i + sum.i * t6.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; i__2 = j * c_dim1 + 7; i__3 = j * c_dim1 + 7; q__2.r = sum.r * t7.r - sum.i * t7.i, q__2.i = sum.r * t7.i + sum.i * t7.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; i__2 = j * c_dim1 + 8; i__3 = j * c_dim1 + 8; q__2.r = sum.r * t8.r - sum.i * t8.i, q__2.i = sum.r * t8.i + sum.i * t8.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; i__2 = j * c_dim1 + 9; i__3 = j * c_dim1 + 9; q__2.r = sum.r * t9.r - sum.i * t9.i, q__2.i = sum.r * t9.i + sum.i * t9.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; i__2 = j * c_dim1 + 10; i__3 = j * c_dim1 + 10; q__2.r = sum.r * t10.r - sum.i * t10.i, q__2.i = sum.r * t10.i + sum.i * t10.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; /* L200: */ } goto L410; } else { /* Form C * H, where H has order n. */ switch (*n) { case 1: goto L210; case 2: goto L230; case 3: goto L250; case 4: goto L270; case 5: goto L290; case 6: goto L310; case 7: goto L330; case 8: goto L350; case 9: goto L370; case 10: goto L390; } /* Code for general N w := C * v */ cgemv_("No transpose", m, n, &c_b56, &c__[c_offset], ldc, &v[1], & c__1, &c_b55, &work[1], &c__1); /* C := C - tau * w * v' */ q__1.r = -tau->r, q__1.i = -tau->i; cgerc_(m, n, &q__1, &work[1], &c__1, &v[1], &c__1, &c__[c_offset], ldc); goto L410; L210: /* Special code for 1 x 1 Householder */ q__3.r = tau->r * v[1].r - tau->i * v[1].i, q__3.i = tau->r * v[1].i + tau->i * v[1].r; r_cnjg(&q__4, &v[1]); q__2.r = q__3.r * q__4.r - q__3.i * q__4.i, q__2.i = q__3.r * q__4.i + q__3.i * q__4.r; q__1.r = 1.f - q__2.r, q__1.i = 0.f - q__2.i; t1.r = q__1.r, t1.i = q__1.i; i__1 = *m; for (j = 1; j <= i__1; ++j) { i__2 = j + c_dim1; i__3 = j + c_dim1; q__1.r = t1.r * c__[i__3].r - t1.i * c__[i__3].i, q__1.i = t1.r * c__[i__3].i + t1.i * c__[i__3].r; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; /* L220: */ } goto L410; L230: /* Special code for 2 x 2 Householder */ v1.r = v[1].r, v1.i = v[1].i; r_cnjg(&q__2, &v1); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t1.r = q__1.r, t1.i = q__1.i; v2.r = v[2].r, v2.i = v[2].i; r_cnjg(&q__2, &v2); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t2.r = q__1.r, t2.i = q__1.i; i__1 = *m; for (j = 1; j <= i__1; ++j) { i__2 = j + c_dim1; q__2.r = v1.r * c__[i__2].r - v1.i * c__[i__2].i, q__2.i = v1.r * c__[i__2].i + v1.i * c__[i__2].r; i__3 = j + ((c_dim1) << (1)); q__3.r = v2.r * c__[i__3].r - v2.i * c__[i__3].i, q__3.i = v2.r * c__[i__3].i + v2.i * c__[i__3].r; q__1.r = q__2.r + q__3.r, q__1.i = q__2.i + q__3.i; sum.r = q__1.r, sum.i = q__1.i; i__2 = j + c_dim1; i__3 = j + c_dim1; q__2.r = sum.r * t1.r - sum.i * t1.i, q__2.i = sum.r * t1.i + sum.i * t1.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; i__2 = j + ((c_dim1) << (1)); i__3 = j + ((c_dim1) << (1)); q__2.r = sum.r * t2.r - sum.i * t2.i, q__2.i = sum.r * t2.i + sum.i * t2.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; /* L240: */ } goto L410; L250: /* Special code for 3 x 3 Householder */ v1.r = v[1].r, v1.i = v[1].i; r_cnjg(&q__2, &v1); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t1.r = q__1.r, t1.i = q__1.i; v2.r = v[2].r, v2.i = v[2].i; r_cnjg(&q__2, &v2); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t2.r = q__1.r, t2.i = q__1.i; v3.r = v[3].r, v3.i = v[3].i; r_cnjg(&q__2, &v3); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t3.r = q__1.r, t3.i = q__1.i; i__1 = *m; for (j = 1; j <= i__1; ++j) { i__2 = j + c_dim1; q__3.r = v1.r * c__[i__2].r - v1.i * c__[i__2].i, q__3.i = v1.r * c__[i__2].i + v1.i * c__[i__2].r; i__3 = j + ((c_dim1) << (1)); q__4.r = v2.r * c__[i__3].r - v2.i * c__[i__3].i, q__4.i = v2.r * c__[i__3].i + v2.i * c__[i__3].r; q__2.r = q__3.r + q__4.r, q__2.i = q__3.i + q__4.i; i__4 = j + c_dim1 * 3; q__5.r = v3.r * c__[i__4].r - v3.i * c__[i__4].i, q__5.i = v3.r * c__[i__4].i + v3.i * c__[i__4].r; q__1.r = q__2.r + q__5.r, q__1.i = q__2.i + q__5.i; sum.r = q__1.r, sum.i = q__1.i; i__2 = j + c_dim1; i__3 = j + c_dim1; q__2.r = sum.r * t1.r - sum.i * t1.i, q__2.i = sum.r * t1.i + sum.i * t1.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; i__2 = j + ((c_dim1) << (1)); i__3 = j + ((c_dim1) << (1)); q__2.r = sum.r * t2.r - sum.i * t2.i, q__2.i = sum.r * t2.i + sum.i * t2.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; i__2 = j + c_dim1 * 3; i__3 = j + c_dim1 * 3; q__2.r = sum.r * t3.r - sum.i * t3.i, q__2.i = sum.r * t3.i + sum.i * t3.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; /* L260: */ } goto L410; L270: /* Special code for 4 x 4 Householder */ v1.r = v[1].r, v1.i = v[1].i; r_cnjg(&q__2, &v1); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t1.r = q__1.r, t1.i = q__1.i; v2.r = v[2].r, v2.i = v[2].i; r_cnjg(&q__2, &v2); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t2.r = q__1.r, t2.i = q__1.i; v3.r = v[3].r, v3.i = v[3].i; r_cnjg(&q__2, &v3); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t3.r = q__1.r, t3.i = q__1.i; v4.r = v[4].r, v4.i = v[4].i; r_cnjg(&q__2, &v4); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t4.r = q__1.r, t4.i = q__1.i; i__1 = *m; for (j = 1; j <= i__1; ++j) { i__2 = j + c_dim1; q__4.r = v1.r * c__[i__2].r - v1.i * c__[i__2].i, q__4.i = v1.r * c__[i__2].i + v1.i * c__[i__2].r; i__3 = j + ((c_dim1) << (1)); q__5.r = v2.r * c__[i__3].r - v2.i * c__[i__3].i, q__5.i = v2.r * c__[i__3].i + v2.i * c__[i__3].r; q__3.r = q__4.r + q__5.r, q__3.i = q__4.i + q__5.i; i__4 = j + c_dim1 * 3; q__6.r = v3.r * c__[i__4].r - v3.i * c__[i__4].i, q__6.i = v3.r * c__[i__4].i + v3.i * c__[i__4].r; q__2.r = q__3.r + q__6.r, q__2.i = q__3.i + q__6.i; i__5 = j + ((c_dim1) << (2)); q__7.r = v4.r * c__[i__5].r - v4.i * c__[i__5].i, q__7.i = v4.r * c__[i__5].i + v4.i * c__[i__5].r; q__1.r = q__2.r + q__7.r, q__1.i = q__2.i + q__7.i; sum.r = q__1.r, sum.i = q__1.i; i__2 = j + c_dim1; i__3 = j + c_dim1; q__2.r = sum.r * t1.r - sum.i * t1.i, q__2.i = sum.r * t1.i + sum.i * t1.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; i__2 = j + ((c_dim1) << (1)); i__3 = j + ((c_dim1) << (1)); q__2.r = sum.r * t2.r - sum.i * t2.i, q__2.i = sum.r * t2.i + sum.i * t2.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; i__2 = j + c_dim1 * 3; i__3 = j + c_dim1 * 3; q__2.r = sum.r * t3.r - sum.i * t3.i, q__2.i = sum.r * t3.i + sum.i * t3.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; i__2 = j + ((c_dim1) << (2)); i__3 = j + ((c_dim1) << (2)); q__2.r = sum.r * t4.r - sum.i * t4.i, q__2.i = sum.r * t4.i + sum.i * t4.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; /* L280: */ } goto L410; L290: /* Special code for 5 x 5 Householder */ v1.r = v[1].r, v1.i = v[1].i; r_cnjg(&q__2, &v1); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t1.r = q__1.r, t1.i = q__1.i; v2.r = v[2].r, v2.i = v[2].i; r_cnjg(&q__2, &v2); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t2.r = q__1.r, t2.i = q__1.i; v3.r = v[3].r, v3.i = v[3].i; r_cnjg(&q__2, &v3); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t3.r = q__1.r, t3.i = q__1.i; v4.r = v[4].r, v4.i = v[4].i; r_cnjg(&q__2, &v4); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t4.r = q__1.r, t4.i = q__1.i; v5.r = v[5].r, v5.i = v[5].i; r_cnjg(&q__2, &v5); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t5.r = q__1.r, t5.i = q__1.i; i__1 = *m; for (j = 1; j <= i__1; ++j) { i__2 = j + c_dim1; q__5.r = v1.r * c__[i__2].r - v1.i * c__[i__2].i, q__5.i = v1.r * c__[i__2].i + v1.i * c__[i__2].r; i__3 = j + ((c_dim1) << (1)); q__6.r = v2.r * c__[i__3].r - v2.i * c__[i__3].i, q__6.i = v2.r * c__[i__3].i + v2.i * c__[i__3].r; q__4.r = q__5.r + q__6.r, q__4.i = q__5.i + q__6.i; i__4 = j + c_dim1 * 3; q__7.r = v3.r * c__[i__4].r - v3.i * c__[i__4].i, q__7.i = v3.r * c__[i__4].i + v3.i * c__[i__4].r; q__3.r = q__4.r + q__7.r, q__3.i = q__4.i + q__7.i; i__5 = j + ((c_dim1) << (2)); q__8.r = v4.r * c__[i__5].r - v4.i * c__[i__5].i, q__8.i = v4.r * c__[i__5].i + v4.i * c__[i__5].r; q__2.r = q__3.r + q__8.r, q__2.i = q__3.i + q__8.i; i__6 = j + c_dim1 * 5; q__9.r = v5.r * c__[i__6].r - v5.i * c__[i__6].i, q__9.i = v5.r * c__[i__6].i + v5.i * c__[i__6].r; q__1.r = q__2.r + q__9.r, q__1.i = q__2.i + q__9.i; sum.r = q__1.r, sum.i = q__1.i; i__2 = j + c_dim1; i__3 = j + c_dim1; q__2.r = sum.r * t1.r - sum.i * t1.i, q__2.i = sum.r * t1.i + sum.i * t1.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; i__2 = j + ((c_dim1) << (1)); i__3 = j + ((c_dim1) << (1)); q__2.r = sum.r * t2.r - sum.i * t2.i, q__2.i = sum.r * t2.i + sum.i * t2.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; i__2 = j + c_dim1 * 3; i__3 = j + c_dim1 * 3; q__2.r = sum.r * t3.r - sum.i * t3.i, q__2.i = sum.r * t3.i + sum.i * t3.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; i__2 = j + ((c_dim1) << (2)); i__3 = j + ((c_dim1) << (2)); q__2.r = sum.r * t4.r - sum.i * t4.i, q__2.i = sum.r * t4.i + sum.i * t4.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; i__2 = j + c_dim1 * 5; i__3 = j + c_dim1 * 5; q__2.r = sum.r * t5.r - sum.i * t5.i, q__2.i = sum.r * t5.i + sum.i * t5.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; /* L300: */ } goto L410; L310: /* Special code for 6 x 6 Householder */ v1.r = v[1].r, v1.i = v[1].i; r_cnjg(&q__2, &v1); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t1.r = q__1.r, t1.i = q__1.i; v2.r = v[2].r, v2.i = v[2].i; r_cnjg(&q__2, &v2); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t2.r = q__1.r, t2.i = q__1.i; v3.r = v[3].r, v3.i = v[3].i; r_cnjg(&q__2, &v3); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t3.r = q__1.r, t3.i = q__1.i; v4.r = v[4].r, v4.i = v[4].i; r_cnjg(&q__2, &v4); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t4.r = q__1.r, t4.i = q__1.i; v5.r = v[5].r, v5.i = v[5].i; r_cnjg(&q__2, &v5); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t5.r = q__1.r, t5.i = q__1.i; v6.r = v[6].r, v6.i = v[6].i; r_cnjg(&q__2, &v6); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t6.r = q__1.r, t6.i = q__1.i; i__1 = *m; for (j = 1; j <= i__1; ++j) { i__2 = j + c_dim1; q__6.r = v1.r * c__[i__2].r - v1.i * c__[i__2].i, q__6.i = v1.r * c__[i__2].i + v1.i * c__[i__2].r; i__3 = j + ((c_dim1) << (1)); q__7.r = v2.r * c__[i__3].r - v2.i * c__[i__3].i, q__7.i = v2.r * c__[i__3].i + v2.i * c__[i__3].r; q__5.r = q__6.r + q__7.r, q__5.i = q__6.i + q__7.i; i__4 = j + c_dim1 * 3; q__8.r = v3.r * c__[i__4].r - v3.i * c__[i__4].i, q__8.i = v3.r * c__[i__4].i + v3.i * c__[i__4].r; q__4.r = q__5.r + q__8.r, q__4.i = q__5.i + q__8.i; i__5 = j + ((c_dim1) << (2)); q__9.r = v4.r * c__[i__5].r - v4.i * c__[i__5].i, q__9.i = v4.r * c__[i__5].i + v4.i * c__[i__5].r; q__3.r = q__4.r + q__9.r, q__3.i = q__4.i + q__9.i; i__6 = j + c_dim1 * 5; q__10.r = v5.r * c__[i__6].r - v5.i * c__[i__6].i, q__10.i = v5.r * c__[i__6].i + v5.i * c__[i__6].r; q__2.r = q__3.r + q__10.r, q__2.i = q__3.i + q__10.i; i__7 = j + c_dim1 * 6; q__11.r = v6.r * c__[i__7].r - v6.i * c__[i__7].i, q__11.i = v6.r * c__[i__7].i + v6.i * c__[i__7].r; q__1.r = q__2.r + q__11.r, q__1.i = q__2.i + q__11.i; sum.r = q__1.r, sum.i = q__1.i; i__2 = j + c_dim1; i__3 = j + c_dim1; q__2.r = sum.r * t1.r - sum.i * t1.i, q__2.i = sum.r * t1.i + sum.i * t1.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; i__2 = j + ((c_dim1) << (1)); i__3 = j + ((c_dim1) << (1)); q__2.r = sum.r * t2.r - sum.i * t2.i, q__2.i = sum.r * t2.i + sum.i * t2.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; i__2 = j + c_dim1 * 3; i__3 = j + c_dim1 * 3; q__2.r = sum.r * t3.r - sum.i * t3.i, q__2.i = sum.r * t3.i + sum.i * t3.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; i__2 = j + ((c_dim1) << (2)); i__3 = j + ((c_dim1) << (2)); q__2.r = sum.r * t4.r - sum.i * t4.i, q__2.i = sum.r * t4.i + sum.i * t4.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; i__2 = j + c_dim1 * 5; i__3 = j + c_dim1 * 5; q__2.r = sum.r * t5.r - sum.i * t5.i, q__2.i = sum.r * t5.i + sum.i * t5.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; i__2 = j + c_dim1 * 6; i__3 = j + c_dim1 * 6; q__2.r = sum.r * t6.r - sum.i * t6.i, q__2.i = sum.r * t6.i + sum.i * t6.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; /* L320: */ } goto L410; L330: /* Special code for 7 x 7 Householder */ v1.r = v[1].r, v1.i = v[1].i; r_cnjg(&q__2, &v1); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t1.r = q__1.r, t1.i = q__1.i; v2.r = v[2].r, v2.i = v[2].i; r_cnjg(&q__2, &v2); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t2.r = q__1.r, t2.i = q__1.i; v3.r = v[3].r, v3.i = v[3].i; r_cnjg(&q__2, &v3); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t3.r = q__1.r, t3.i = q__1.i; v4.r = v[4].r, v4.i = v[4].i; r_cnjg(&q__2, &v4); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t4.r = q__1.r, t4.i = q__1.i; v5.r = v[5].r, v5.i = v[5].i; r_cnjg(&q__2, &v5); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t5.r = q__1.r, t5.i = q__1.i; v6.r = v[6].r, v6.i = v[6].i; r_cnjg(&q__2, &v6); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t6.r = q__1.r, t6.i = q__1.i; v7.r = v[7].r, v7.i = v[7].i; r_cnjg(&q__2, &v7); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t7.r = q__1.r, t7.i = q__1.i; i__1 = *m; for (j = 1; j <= i__1; ++j) { i__2 = j + c_dim1; q__7.r = v1.r * c__[i__2].r - v1.i * c__[i__2].i, q__7.i = v1.r * c__[i__2].i + v1.i * c__[i__2].r; i__3 = j + ((c_dim1) << (1)); q__8.r = v2.r * c__[i__3].r - v2.i * c__[i__3].i, q__8.i = v2.r * c__[i__3].i + v2.i * c__[i__3].r; q__6.r = q__7.r + q__8.r, q__6.i = q__7.i + q__8.i; i__4 = j + c_dim1 * 3; q__9.r = v3.r * c__[i__4].r - v3.i * c__[i__4].i, q__9.i = v3.r * c__[i__4].i + v3.i * c__[i__4].r; q__5.r = q__6.r + q__9.r, q__5.i = q__6.i + q__9.i; i__5 = j + ((c_dim1) << (2)); q__10.r = v4.r * c__[i__5].r - v4.i * c__[i__5].i, q__10.i = v4.r * c__[i__5].i + v4.i * c__[i__5].r; q__4.r = q__5.r + q__10.r, q__4.i = q__5.i + q__10.i; i__6 = j + c_dim1 * 5; q__11.r = v5.r * c__[i__6].r - v5.i * c__[i__6].i, q__11.i = v5.r * c__[i__6].i + v5.i * c__[i__6].r; q__3.r = q__4.r + q__11.r, q__3.i = q__4.i + q__11.i; i__7 = j + c_dim1 * 6; q__12.r = v6.r * c__[i__7].r - v6.i * c__[i__7].i, q__12.i = v6.r * c__[i__7].i + v6.i * c__[i__7].r; q__2.r = q__3.r + q__12.r, q__2.i = q__3.i + q__12.i; i__8 = j + c_dim1 * 7; q__13.r = v7.r * c__[i__8].r - v7.i * c__[i__8].i, q__13.i = v7.r * c__[i__8].i + v7.i * c__[i__8].r; q__1.r = q__2.r + q__13.r, q__1.i = q__2.i + q__13.i; sum.r = q__1.r, sum.i = q__1.i; i__2 = j + c_dim1; i__3 = j + c_dim1; q__2.r = sum.r * t1.r - sum.i * t1.i, q__2.i = sum.r * t1.i + sum.i * t1.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; i__2 = j + ((c_dim1) << (1)); i__3 = j + ((c_dim1) << (1)); q__2.r = sum.r * t2.r - sum.i * t2.i, q__2.i = sum.r * t2.i + sum.i * t2.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; i__2 = j + c_dim1 * 3; i__3 = j + c_dim1 * 3; q__2.r = sum.r * t3.r - sum.i * t3.i, q__2.i = sum.r * t3.i + sum.i * t3.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; i__2 = j + ((c_dim1) << (2)); i__3 = j + ((c_dim1) << (2)); q__2.r = sum.r * t4.r - sum.i * t4.i, q__2.i = sum.r * t4.i + sum.i * t4.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; i__2 = j + c_dim1 * 5; i__3 = j + c_dim1 * 5; q__2.r = sum.r * t5.r - sum.i * t5.i, q__2.i = sum.r * t5.i + sum.i * t5.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; i__2 = j + c_dim1 * 6; i__3 = j + c_dim1 * 6; q__2.r = sum.r * t6.r - sum.i * t6.i, q__2.i = sum.r * t6.i + sum.i * t6.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; i__2 = j + c_dim1 * 7; i__3 = j + c_dim1 * 7; q__2.r = sum.r * t7.r - sum.i * t7.i, q__2.i = sum.r * t7.i + sum.i * t7.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; /* L340: */ } goto L410; L350: /* Special code for 8 x 8 Householder */ v1.r = v[1].r, v1.i = v[1].i; r_cnjg(&q__2, &v1); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t1.r = q__1.r, t1.i = q__1.i; v2.r = v[2].r, v2.i = v[2].i; r_cnjg(&q__2, &v2); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t2.r = q__1.r, t2.i = q__1.i; v3.r = v[3].r, v3.i = v[3].i; r_cnjg(&q__2, &v3); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t3.r = q__1.r, t3.i = q__1.i; v4.r = v[4].r, v4.i = v[4].i; r_cnjg(&q__2, &v4); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t4.r = q__1.r, t4.i = q__1.i; v5.r = v[5].r, v5.i = v[5].i; r_cnjg(&q__2, &v5); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t5.r = q__1.r, t5.i = q__1.i; v6.r = v[6].r, v6.i = v[6].i; r_cnjg(&q__2, &v6); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t6.r = q__1.r, t6.i = q__1.i; v7.r = v[7].r, v7.i = v[7].i; r_cnjg(&q__2, &v7); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t7.r = q__1.r, t7.i = q__1.i; v8.r = v[8].r, v8.i = v[8].i; r_cnjg(&q__2, &v8); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t8.r = q__1.r, t8.i = q__1.i; i__1 = *m; for (j = 1; j <= i__1; ++j) { i__2 = j + c_dim1; q__8.r = v1.r * c__[i__2].r - v1.i * c__[i__2].i, q__8.i = v1.r * c__[i__2].i + v1.i * c__[i__2].r; i__3 = j + ((c_dim1) << (1)); q__9.r = v2.r * c__[i__3].r - v2.i * c__[i__3].i, q__9.i = v2.r * c__[i__3].i + v2.i * c__[i__3].r; q__7.r = q__8.r + q__9.r, q__7.i = q__8.i + q__9.i; i__4 = j + c_dim1 * 3; q__10.r = v3.r * c__[i__4].r - v3.i * c__[i__4].i, q__10.i = v3.r * c__[i__4].i + v3.i * c__[i__4].r; q__6.r = q__7.r + q__10.r, q__6.i = q__7.i + q__10.i; i__5 = j + ((c_dim1) << (2)); q__11.r = v4.r * c__[i__5].r - v4.i * c__[i__5].i, q__11.i = v4.r * c__[i__5].i + v4.i * c__[i__5].r; q__5.r = q__6.r + q__11.r, q__5.i = q__6.i + q__11.i; i__6 = j + c_dim1 * 5; q__12.r = v5.r * c__[i__6].r - v5.i * c__[i__6].i, q__12.i = v5.r * c__[i__6].i + v5.i * c__[i__6].r; q__4.r = q__5.r + q__12.r, q__4.i = q__5.i + q__12.i; i__7 = j + c_dim1 * 6; q__13.r = v6.r * c__[i__7].r - v6.i * c__[i__7].i, q__13.i = v6.r * c__[i__7].i + v6.i * c__[i__7].r; q__3.r = q__4.r + q__13.r, q__3.i = q__4.i + q__13.i; i__8 = j + c_dim1 * 7; q__14.r = v7.r * c__[i__8].r - v7.i * c__[i__8].i, q__14.i = v7.r * c__[i__8].i + v7.i * c__[i__8].r; q__2.r = q__3.r + q__14.r, q__2.i = q__3.i + q__14.i; i__9 = j + ((c_dim1) << (3)); q__15.r = v8.r * c__[i__9].r - v8.i * c__[i__9].i, q__15.i = v8.r * c__[i__9].i + v8.i * c__[i__9].r; q__1.r = q__2.r + q__15.r, q__1.i = q__2.i + q__15.i; sum.r = q__1.r, sum.i = q__1.i; i__2 = j + c_dim1; i__3 = j + c_dim1; q__2.r = sum.r * t1.r - sum.i * t1.i, q__2.i = sum.r * t1.i + sum.i * t1.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; i__2 = j + ((c_dim1) << (1)); i__3 = j + ((c_dim1) << (1)); q__2.r = sum.r * t2.r - sum.i * t2.i, q__2.i = sum.r * t2.i + sum.i * t2.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; i__2 = j + c_dim1 * 3; i__3 = j + c_dim1 * 3; q__2.r = sum.r * t3.r - sum.i * t3.i, q__2.i = sum.r * t3.i + sum.i * t3.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; i__2 = j + ((c_dim1) << (2)); i__3 = j + ((c_dim1) << (2)); q__2.r = sum.r * t4.r - sum.i * t4.i, q__2.i = sum.r * t4.i + sum.i * t4.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; i__2 = j + c_dim1 * 5; i__3 = j + c_dim1 * 5; q__2.r = sum.r * t5.r - sum.i * t5.i, q__2.i = sum.r * t5.i + sum.i * t5.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; i__2 = j + c_dim1 * 6; i__3 = j + c_dim1 * 6; q__2.r = sum.r * t6.r - sum.i * t6.i, q__2.i = sum.r * t6.i + sum.i * t6.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; i__2 = j + c_dim1 * 7; i__3 = j + c_dim1 * 7; q__2.r = sum.r * t7.r - sum.i * t7.i, q__2.i = sum.r * t7.i + sum.i * t7.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; i__2 = j + ((c_dim1) << (3)); i__3 = j + ((c_dim1) << (3)); q__2.r = sum.r * t8.r - sum.i * t8.i, q__2.i = sum.r * t8.i + sum.i * t8.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; /* L360: */ } goto L410; L370: /* Special code for 9 x 9 Householder */ v1.r = v[1].r, v1.i = v[1].i; r_cnjg(&q__2, &v1); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t1.r = q__1.r, t1.i = q__1.i; v2.r = v[2].r, v2.i = v[2].i; r_cnjg(&q__2, &v2); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t2.r = q__1.r, t2.i = q__1.i; v3.r = v[3].r, v3.i = v[3].i; r_cnjg(&q__2, &v3); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t3.r = q__1.r, t3.i = q__1.i; v4.r = v[4].r, v4.i = v[4].i; r_cnjg(&q__2, &v4); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t4.r = q__1.r, t4.i = q__1.i; v5.r = v[5].r, v5.i = v[5].i; r_cnjg(&q__2, &v5); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t5.r = q__1.r, t5.i = q__1.i; v6.r = v[6].r, v6.i = v[6].i; r_cnjg(&q__2, &v6); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t6.r = q__1.r, t6.i = q__1.i; v7.r = v[7].r, v7.i = v[7].i; r_cnjg(&q__2, &v7); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t7.r = q__1.r, t7.i = q__1.i; v8.r = v[8].r, v8.i = v[8].i; r_cnjg(&q__2, &v8); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t8.r = q__1.r, t8.i = q__1.i; v9.r = v[9].r, v9.i = v[9].i; r_cnjg(&q__2, &v9); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t9.r = q__1.r, t9.i = q__1.i; i__1 = *m; for (j = 1; j <= i__1; ++j) { i__2 = j + c_dim1; q__9.r = v1.r * c__[i__2].r - v1.i * c__[i__2].i, q__9.i = v1.r * c__[i__2].i + v1.i * c__[i__2].r; i__3 = j + ((c_dim1) << (1)); q__10.r = v2.r * c__[i__3].r - v2.i * c__[i__3].i, q__10.i = v2.r * c__[i__3].i + v2.i * c__[i__3].r; q__8.r = q__9.r + q__10.r, q__8.i = q__9.i + q__10.i; i__4 = j + c_dim1 * 3; q__11.r = v3.r * c__[i__4].r - v3.i * c__[i__4].i, q__11.i = v3.r * c__[i__4].i + v3.i * c__[i__4].r; q__7.r = q__8.r + q__11.r, q__7.i = q__8.i + q__11.i; i__5 = j + ((c_dim1) << (2)); q__12.r = v4.r * c__[i__5].r - v4.i * c__[i__5].i, q__12.i = v4.r * c__[i__5].i + v4.i * c__[i__5].r; q__6.r = q__7.r + q__12.r, q__6.i = q__7.i + q__12.i; i__6 = j + c_dim1 * 5; q__13.r = v5.r * c__[i__6].r - v5.i * c__[i__6].i, q__13.i = v5.r * c__[i__6].i + v5.i * c__[i__6].r; q__5.r = q__6.r + q__13.r, q__5.i = q__6.i + q__13.i; i__7 = j + c_dim1 * 6; q__14.r = v6.r * c__[i__7].r - v6.i * c__[i__7].i, q__14.i = v6.r * c__[i__7].i + v6.i * c__[i__7].r; q__4.r = q__5.r + q__14.r, q__4.i = q__5.i + q__14.i; i__8 = j + c_dim1 * 7; q__15.r = v7.r * c__[i__8].r - v7.i * c__[i__8].i, q__15.i = v7.r * c__[i__8].i + v7.i * c__[i__8].r; q__3.r = q__4.r + q__15.r, q__3.i = q__4.i + q__15.i; i__9 = j + ((c_dim1) << (3)); q__16.r = v8.r * c__[i__9].r - v8.i * c__[i__9].i, q__16.i = v8.r * c__[i__9].i + v8.i * c__[i__9].r; q__2.r = q__3.r + q__16.r, q__2.i = q__3.i + q__16.i; i__10 = j + c_dim1 * 9; q__17.r = v9.r * c__[i__10].r - v9.i * c__[i__10].i, q__17.i = v9.r * c__[i__10].i + v9.i * c__[i__10].r; q__1.r = q__2.r + q__17.r, q__1.i = q__2.i + q__17.i; sum.r = q__1.r, sum.i = q__1.i; i__2 = j + c_dim1; i__3 = j + c_dim1; q__2.r = sum.r * t1.r - sum.i * t1.i, q__2.i = sum.r * t1.i + sum.i * t1.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; i__2 = j + ((c_dim1) << (1)); i__3 = j + ((c_dim1) << (1)); q__2.r = sum.r * t2.r - sum.i * t2.i, q__2.i = sum.r * t2.i + sum.i * t2.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; i__2 = j + c_dim1 * 3; i__3 = j + c_dim1 * 3; q__2.r = sum.r * t3.r - sum.i * t3.i, q__2.i = sum.r * t3.i + sum.i * t3.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; i__2 = j + ((c_dim1) << (2)); i__3 = j + ((c_dim1) << (2)); q__2.r = sum.r * t4.r - sum.i * t4.i, q__2.i = sum.r * t4.i + sum.i * t4.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; i__2 = j + c_dim1 * 5; i__3 = j + c_dim1 * 5; q__2.r = sum.r * t5.r - sum.i * t5.i, q__2.i = sum.r * t5.i + sum.i * t5.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; i__2 = j + c_dim1 * 6; i__3 = j + c_dim1 * 6; q__2.r = sum.r * t6.r - sum.i * t6.i, q__2.i = sum.r * t6.i + sum.i * t6.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; i__2 = j + c_dim1 * 7; i__3 = j + c_dim1 * 7; q__2.r = sum.r * t7.r - sum.i * t7.i, q__2.i = sum.r * t7.i + sum.i * t7.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; i__2 = j + ((c_dim1) << (3)); i__3 = j + ((c_dim1) << (3)); q__2.r = sum.r * t8.r - sum.i * t8.i, q__2.i = sum.r * t8.i + sum.i * t8.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; i__2 = j + c_dim1 * 9; i__3 = j + c_dim1 * 9; q__2.r = sum.r * t9.r - sum.i * t9.i, q__2.i = sum.r * t9.i + sum.i * t9.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; /* L380: */ } goto L410; L390: /* Special code for 10 x 10 Householder */ v1.r = v[1].r, v1.i = v[1].i; r_cnjg(&q__2, &v1); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t1.r = q__1.r, t1.i = q__1.i; v2.r = v[2].r, v2.i = v[2].i; r_cnjg(&q__2, &v2); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t2.r = q__1.r, t2.i = q__1.i; v3.r = v[3].r, v3.i = v[3].i; r_cnjg(&q__2, &v3); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t3.r = q__1.r, t3.i = q__1.i; v4.r = v[4].r, v4.i = v[4].i; r_cnjg(&q__2, &v4); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t4.r = q__1.r, t4.i = q__1.i; v5.r = v[5].r, v5.i = v[5].i; r_cnjg(&q__2, &v5); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t5.r = q__1.r, t5.i = q__1.i; v6.r = v[6].r, v6.i = v[6].i; r_cnjg(&q__2, &v6); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t6.r = q__1.r, t6.i = q__1.i; v7.r = v[7].r, v7.i = v[7].i; r_cnjg(&q__2, &v7); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t7.r = q__1.r, t7.i = q__1.i; v8.r = v[8].r, v8.i = v[8].i; r_cnjg(&q__2, &v8); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t8.r = q__1.r, t8.i = q__1.i; v9.r = v[9].r, v9.i = v[9].i; r_cnjg(&q__2, &v9); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t9.r = q__1.r, t9.i = q__1.i; v10.r = v[10].r, v10.i = v[10].i; r_cnjg(&q__2, &v10); q__1.r = tau->r * q__2.r - tau->i * q__2.i, q__1.i = tau->r * q__2.i + tau->i * q__2.r; t10.r = q__1.r, t10.i = q__1.i; i__1 = *m; for (j = 1; j <= i__1; ++j) { i__2 = j + c_dim1; q__10.r = v1.r * c__[i__2].r - v1.i * c__[i__2].i, q__10.i = v1.r * c__[i__2].i + v1.i * c__[i__2].r; i__3 = j + ((c_dim1) << (1)); q__11.r = v2.r * c__[i__3].r - v2.i * c__[i__3].i, q__11.i = v2.r * c__[i__3].i + v2.i * c__[i__3].r; q__9.r = q__10.r + q__11.r, q__9.i = q__10.i + q__11.i; i__4 = j + c_dim1 * 3; q__12.r = v3.r * c__[i__4].r - v3.i * c__[i__4].i, q__12.i = v3.r * c__[i__4].i + v3.i * c__[i__4].r; q__8.r = q__9.r + q__12.r, q__8.i = q__9.i + q__12.i; i__5 = j + ((c_dim1) << (2)); q__13.r = v4.r * c__[i__5].r - v4.i * c__[i__5].i, q__13.i = v4.r * c__[i__5].i + v4.i * c__[i__5].r; q__7.r = q__8.r + q__13.r, q__7.i = q__8.i + q__13.i; i__6 = j + c_dim1 * 5; q__14.r = v5.r * c__[i__6].r - v5.i * c__[i__6].i, q__14.i = v5.r * c__[i__6].i + v5.i * c__[i__6].r; q__6.r = q__7.r + q__14.r, q__6.i = q__7.i + q__14.i; i__7 = j + c_dim1 * 6; q__15.r = v6.r * c__[i__7].r - v6.i * c__[i__7].i, q__15.i = v6.r * c__[i__7].i + v6.i * c__[i__7].r; q__5.r = q__6.r + q__15.r, q__5.i = q__6.i + q__15.i; i__8 = j + c_dim1 * 7; q__16.r = v7.r * c__[i__8].r - v7.i * c__[i__8].i, q__16.i = v7.r * c__[i__8].i + v7.i * c__[i__8].r; q__4.r = q__5.r + q__16.r, q__4.i = q__5.i + q__16.i; i__9 = j + ((c_dim1) << (3)); q__17.r = v8.r * c__[i__9].r - v8.i * c__[i__9].i, q__17.i = v8.r * c__[i__9].i + v8.i * c__[i__9].r; q__3.r = q__4.r + q__17.r, q__3.i = q__4.i + q__17.i; i__10 = j + c_dim1 * 9; q__18.r = v9.r * c__[i__10].r - v9.i * c__[i__10].i, q__18.i = v9.r * c__[i__10].i + v9.i * c__[i__10].r; q__2.r = q__3.r + q__18.r, q__2.i = q__3.i + q__18.i; i__11 = j + c_dim1 * 10; q__19.r = v10.r * c__[i__11].r - v10.i * c__[i__11].i, q__19.i = v10.r * c__[i__11].i + v10.i * c__[i__11].r; q__1.r = q__2.r + q__19.r, q__1.i = q__2.i + q__19.i; sum.r = q__1.r, sum.i = q__1.i; i__2 = j + c_dim1; i__3 = j + c_dim1; q__2.r = sum.r * t1.r - sum.i * t1.i, q__2.i = sum.r * t1.i + sum.i * t1.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; i__2 = j + ((c_dim1) << (1)); i__3 = j + ((c_dim1) << (1)); q__2.r = sum.r * t2.r - sum.i * t2.i, q__2.i = sum.r * t2.i + sum.i * t2.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; i__2 = j + c_dim1 * 3; i__3 = j + c_dim1 * 3; q__2.r = sum.r * t3.r - sum.i * t3.i, q__2.i = sum.r * t3.i + sum.i * t3.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; i__2 = j + ((c_dim1) << (2)); i__3 = j + ((c_dim1) << (2)); q__2.r = sum.r * t4.r - sum.i * t4.i, q__2.i = sum.r * t4.i + sum.i * t4.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; i__2 = j + c_dim1 * 5; i__3 = j + c_dim1 * 5; q__2.r = sum.r * t5.r - sum.i * t5.i, q__2.i = sum.r * t5.i + sum.i * t5.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; i__2 = j + c_dim1 * 6; i__3 = j + c_dim1 * 6; q__2.r = sum.r * t6.r - sum.i * t6.i, q__2.i = sum.r * t6.i + sum.i * t6.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; i__2 = j + c_dim1 * 7; i__3 = j + c_dim1 * 7; q__2.r = sum.r * t7.r - sum.i * t7.i, q__2.i = sum.r * t7.i + sum.i * t7.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; i__2 = j + ((c_dim1) << (3)); i__3 = j + ((c_dim1) << (3)); q__2.r = sum.r * t8.r - sum.i * t8.i, q__2.i = sum.r * t8.i + sum.i * t8.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; i__2 = j + c_dim1 * 9; i__3 = j + c_dim1 * 9; q__2.r = sum.r * t9.r - sum.i * t9.i, q__2.i = sum.r * t9.i + sum.i * t9.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; i__2 = j + c_dim1 * 10; i__3 = j + c_dim1 * 10; q__2.r = sum.r * t10.r - sum.i * t10.i, q__2.i = sum.r * t10.i + sum.i * t10.r; q__1.r = c__[i__3].r - q__2.r, q__1.i = c__[i__3].i - q__2.i; c__[i__2].r = q__1.r, c__[i__2].i = q__1.i; /* L400: */ } goto L410; } L410: return 0; /* End of CLARFX */ } /* clarfx_ */ /* Subroutine */ int clascl_(char *type__, integer *kl, integer *ku, real * cfrom, real *cto, integer *m, integer *n, complex *a, integer *lda, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3, i__4, i__5; complex q__1; /* Local variables */ static integer i__, j, k1, k2, k3, k4; static real mul, cto1; static logical done; static real ctoc; extern logical lsame_(char *, char *); static integer itype; static real cfrom1; extern doublereal slamch_(char *); static real cfromc; extern /* Subroutine */ int xerbla_(char *, integer *); static real bignum, smlnum; /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University February 29, 1992 Purpose ======= CLASCL multiplies the M by N complex matrix A by the real scalar CTO/CFROM. This is done without over/underflow as long as the final result CTO*A(I,J)/CFROM does not over/underflow. TYPE specifies that A may be full, upper triangular, lower triangular, upper Hessenberg, or banded. Arguments ========= TYPE (input) CHARACTER*1 TYPE indices the storage type of the input matrix. = 'G': A is a full matrix. = 'L': A is a lower triangular matrix. = 'U': A is an upper triangular matrix. = 'H': A is an upper Hessenberg matrix. = 'B': A is a symmetric band matrix with lower bandwidth KL and upper bandwidth KU and with the only the lower half stored. = 'Q': A is a symmetric band matrix with lower bandwidth KL and upper bandwidth KU and with the only the upper half stored. = 'Z': A is a band matrix with lower bandwidth KL and upper bandwidth KU. KL (input) INTEGER The lower bandwidth of A. Referenced only if TYPE = 'B', 'Q' or 'Z'. KU (input) INTEGER The upper bandwidth of A. Referenced only if TYPE = 'B', 'Q' or 'Z'. CFROM (input) REAL CTO (input) REAL The matrix A is multiplied by CTO/CFROM. A(I,J) is computed without over/underflow if the final result CTO*A(I,J)/CFROM can be represented without over/underflow. CFROM must be nonzero. M (input) INTEGER The number of rows of the matrix A. M >= 0. N (input) INTEGER The number of columns of the matrix A. N >= 0. A (input/output) COMPLEX array, dimension (LDA,M) The matrix to be multiplied by CTO/CFROM. See TYPE for the storage type. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,M). INFO (output) INTEGER 0 - successful exit <0 - if INFO = -i, the i-th argument had an illegal value. ===================================================================== Test the input arguments */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; /* Function Body */ *info = 0; if (lsame_(type__, "G")) { itype = 0; } else if (lsame_(type__, "L")) { itype = 1; } else if (lsame_(type__, "U")) { itype = 2; } else if (lsame_(type__, "H")) { itype = 3; } else if (lsame_(type__, "B")) { itype = 4; } else if (lsame_(type__, "Q")) { itype = 5; } else if (lsame_(type__, "Z")) { itype = 6; } else { itype = -1; } if (itype == -1) { *info = -1; } else if (*cfrom == 0.f) { *info = -4; } else if (*m < 0) { *info = -6; } else if (((*n < 0) || (itype == 4 && *n != *m)) || (itype == 5 && *n != *m)) { *info = -7; } else if (itype <= 3 && *lda < max(1,*m)) { *info = -9; } else if (itype >= 4) { /* Computing MAX */ i__1 = *m - 1; if ((*kl < 0) || (*kl > max(i__1,0))) { *info = -2; } else /* if(complicated condition) */ { /* Computing MAX */ i__1 = *n - 1; if (((*ku < 0) || (*ku > max(i__1,0))) || (((itype == 4) || ( itype == 5)) && *kl != *ku)) { *info = -3; } else if (((itype == 4 && *lda < *kl + 1) || (itype == 5 && *lda < *ku + 1)) || (itype == 6 && *lda < ((*kl) << (1)) + *ku + 1)) { *info = -9; } } } if (*info != 0) { i__1 = -(*info); xerbla_("CLASCL", &i__1); return 0; } /* Quick return if possible */ if ((*n == 0) || (*m == 0)) { return 0; } /* Get machine parameters */ smlnum = slamch_("S"); bignum = 1.f / smlnum; cfromc = *cfrom; ctoc = *cto; L10: cfrom1 = cfromc * smlnum; cto1 = ctoc / bignum; if (dabs(cfrom1) > dabs(ctoc) && ctoc != 0.f) { mul = smlnum; done = FALSE_; cfromc = cfrom1; } else if (dabs(cto1) > dabs(cfromc)) { mul = bignum; done = FALSE_; ctoc = cto1; } else { mul = ctoc / cfromc; done = TRUE_; } if (itype == 0) { /* Full matrix */ i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * a_dim1; i__4 = i__ + j * a_dim1; q__1.r = mul * a[i__4].r, q__1.i = mul * a[i__4].i; a[i__3].r = q__1.r, a[i__3].i = q__1.i; /* L20: */ } /* L30: */ } } else if (itype == 1) { /* Lower triangular matrix */ i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = j; i__ <= i__2; ++i__) { i__3 = i__ + j * a_dim1; i__4 = i__ + j * a_dim1; q__1.r = mul * a[i__4].r, q__1.i = mul * a[i__4].i; a[i__3].r = q__1.r, a[i__3].i = q__1.i; /* L40: */ } /* L50: */ } } else if (itype == 2) { /* Upper triangular matrix */ i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = min(j,*m); for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * a_dim1; i__4 = i__ + j * a_dim1; q__1.r = mul * a[i__4].r, q__1.i = mul * a[i__4].i; a[i__3].r = q__1.r, a[i__3].i = q__1.i; /* L60: */ } /* L70: */ } } else if (itype == 3) { /* Upper Hessenberg matrix */ i__1 = *n; for (j = 1; j <= i__1; ++j) { /* Computing MIN */ i__3 = j + 1; i__2 = min(i__3,*m); for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * a_dim1; i__4 = i__ + j * a_dim1; q__1.r = mul * a[i__4].r, q__1.i = mul * a[i__4].i; a[i__3].r = q__1.r, a[i__3].i = q__1.i; /* L80: */ } /* L90: */ } } else if (itype == 4) { /* Lower half of a symmetric band matrix */ k3 = *kl + 1; k4 = *n + 1; i__1 = *n; for (j = 1; j <= i__1; ++j) { /* Computing MIN */ i__3 = k3, i__4 = k4 - j; i__2 = min(i__3,i__4); for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * a_dim1; i__4 = i__ + j * a_dim1; q__1.r = mul * a[i__4].r, q__1.i = mul * a[i__4].i; a[i__3].r = q__1.r, a[i__3].i = q__1.i; /* L100: */ } /* L110: */ } } else if (itype == 5) { /* Upper half of a symmetric band matrix */ k1 = *ku + 2; k3 = *ku + 1; i__1 = *n; for (j = 1; j <= i__1; ++j) { /* Computing MAX */ i__2 = k1 - j; i__3 = k3; for (i__ = max(i__2,1); i__ <= i__3; ++i__) { i__2 = i__ + j * a_dim1; i__4 = i__ + j * a_dim1; q__1.r = mul * a[i__4].r, q__1.i = mul * a[i__4].i; a[i__2].r = q__1.r, a[i__2].i = q__1.i; /* L120: */ } /* L130: */ } } else if (itype == 6) { /* Band matrix */ k1 = *kl + *ku + 2; k2 = *kl + 1; k3 = ((*kl) << (1)) + *ku + 1; k4 = *kl + *ku + 1 + *m; i__1 = *n; for (j = 1; j <= i__1; ++j) { /* Computing MAX */ i__3 = k1 - j; /* Computing MIN */ i__4 = k3, i__5 = k4 - j; i__2 = min(i__4,i__5); for (i__ = max(i__3,k2); i__ <= i__2; ++i__) { i__3 = i__ + j * a_dim1; i__4 = i__ + j * a_dim1; q__1.r = mul * a[i__4].r, q__1.i = mul * a[i__4].i; a[i__3].r = q__1.r, a[i__3].i = q__1.i; /* L140: */ } /* L150: */ } } if (! done) { goto L10; } return 0; /* End of CLASCL */ } /* clascl_ */ /* Subroutine */ int claset_(char *uplo, integer *m, integer *n, complex * alpha, complex *beta, complex *a, integer *lda) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3; /* Local variables */ static integer i__, j; extern logical lsame_(char *, char *); /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University October 31, 1992 Purpose ======= CLASET initializes a 2-D array A to BETA on the diagonal and ALPHA on the offdiagonals. Arguments ========= UPLO (input) CHARACTER*1 Specifies the part of the matrix A to be set. = 'U': Upper triangular part is set. The lower triangle is unchanged. = 'L': Lower triangular part is set. The upper triangle is unchanged. Otherwise: All of the matrix A is set. M (input) INTEGER On entry, M specifies the number of rows of A. N (input) INTEGER On entry, N specifies the number of columns of A. ALPHA (input) COMPLEX All the offdiagonal array elements are set to ALPHA. BETA (input) COMPLEX All the diagonal array elements are set to BETA. A (input/output) COMPLEX array, dimension (LDA,N) On entry, the m by n matrix A. On exit, A(i,j) = ALPHA, 1 <= i <= m, 1 <= j <= n, i.ne.j; A(i,i) = BETA , 1 <= i <= min(m,n) LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,M). ===================================================================== */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; /* Function Body */ if (lsame_(uplo, "U")) { /* Set the diagonal to BETA and the strictly upper triangular part of the array to ALPHA. */ i__1 = *n; for (j = 2; j <= i__1; ++j) { /* Computing MIN */ i__3 = j - 1; i__2 = min(i__3,*m); for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * a_dim1; a[i__3].r = alpha->r, a[i__3].i = alpha->i; /* L10: */ } /* L20: */ } i__1 = min(*n,*m); for (i__ = 1; i__ <= i__1; ++i__) { i__2 = i__ + i__ * a_dim1; a[i__2].r = beta->r, a[i__2].i = beta->i; /* L30: */ } } else if (lsame_(uplo, "L")) { /* Set the diagonal to BETA and the strictly lower triangular part of the array to ALPHA. */ i__1 = min(*m,*n); for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = j + 1; i__ <= i__2; ++i__) { i__3 = i__ + j * a_dim1; a[i__3].r = alpha->r, a[i__3].i = alpha->i; /* L40: */ } /* L50: */ } i__1 = min(*n,*m); for (i__ = 1; i__ <= i__1; ++i__) { i__2 = i__ + i__ * a_dim1; a[i__2].r = beta->r, a[i__2].i = beta->i; /* L60: */ } } else { /* Set the array to BETA on the diagonal and ALPHA on the offdiagonal. */ i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * a_dim1; a[i__3].r = alpha->r, a[i__3].i = alpha->i; /* L70: */ } /* L80: */ } i__1 = min(*m,*n); for (i__ = 1; i__ <= i__1; ++i__) { i__2 = i__ + i__ * a_dim1; a[i__2].r = beta->r, a[i__2].i = beta->i; /* L90: */ } } return 0; /* End of CLASET */ } /* claset_ */ /* Subroutine */ int clasr_(char *side, char *pivot, char *direct, integer *m, integer *n, real *c__, real *s, complex *a, integer *lda) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3, i__4; complex q__1, q__2, q__3; /* Local variables */ static integer i__, j, info; static complex temp; extern logical lsame_(char *, char *); static real ctemp, stemp; extern /* Subroutine */ int xerbla_(char *, integer *); /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University October 31, 1992 Purpose ======= CLASR performs the transformation A := P*A, when SIDE = 'L' or 'l' ( Left-hand side ) A := A*P', when SIDE = 'R' or 'r' ( Right-hand side ) where A is an m by n complex matrix and P is an orthogonal matrix, consisting of a sequence of plane rotations determined by the parameters PIVOT and DIRECT as follows ( z = m when SIDE = 'L' or 'l' and z = n when SIDE = 'R' or 'r' ): When DIRECT = 'F' or 'f' ( Forward sequence ) then P = P( z - 1 )*...*P( 2 )*P( 1 ), and when DIRECT = 'B' or 'b' ( Backward sequence ) then P = P( 1 )*P( 2 )*...*P( z - 1 ), where P( k ) is a plane rotation matrix for the following planes: when PIVOT = 'V' or 'v' ( Variable pivot ), the plane ( k, k + 1 ) when PIVOT = 'T' or 't' ( Top pivot ), the plane ( 1, k + 1 ) when PIVOT = 'B' or 'b' ( Bottom pivot ), the plane ( k, z ) c( k ) and s( k ) must contain the cosine and sine that define the matrix P( k ). The two by two plane rotation part of the matrix P( k ), R( k ), is assumed to be of the form R( k ) = ( c( k ) s( k ) ). ( -s( k ) c( k ) ) Arguments ========= SIDE (input) CHARACTER*1 Specifies whether the plane rotation matrix P is applied to A on the left or the right. = 'L': Left, compute A := P*A = 'R': Right, compute A:= A*P' DIRECT (input) CHARACTER*1 Specifies whether P is a forward or backward sequence of plane rotations. = 'F': Forward, P = P( z - 1 )*...*P( 2 )*P( 1 ) = 'B': Backward, P = P( 1 )*P( 2 )*...*P( z - 1 ) PIVOT (input) CHARACTER*1 Specifies the plane for which P(k) is a plane rotation matrix. = 'V': Variable pivot, the plane (k,k+1) = 'T': Top pivot, the plane (1,k+1) = 'B': Bottom pivot, the plane (k,z) M (input) INTEGER The number of rows of the matrix A. If m <= 1, an immediate return is effected. N (input) INTEGER The number of columns of the matrix A. If n <= 1, an immediate return is effected. C, S (input) REAL arrays, dimension (M-1) if SIDE = 'L' (N-1) if SIDE = 'R' c(k) and s(k) contain the cosine and sine that define the matrix P(k). The two by two plane rotation part of the matrix P(k), R(k), is assumed to be of the form R( k ) = ( c( k ) s( k ) ). ( -s( k ) c( k ) ) A (input/output) COMPLEX array, dimension (LDA,N) The m by n matrix A. On exit, A is overwritten by P*A if SIDE = 'R' or by A*P' if SIDE = 'L'. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,M). ===================================================================== Test the input parameters */ /* Parameter adjustments */ --c__; --s; a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; /* Function Body */ info = 0; if (! ((lsame_(side, "L")) || (lsame_(side, "R")))) { info = 1; } else if (! (((lsame_(pivot, "V")) || (lsame_( pivot, "T"))) || (lsame_(pivot, "B")))) { info = 2; } else if (! ((lsame_(direct, "F")) || (lsame_( direct, "B")))) { info = 3; } else if (*m < 0) { info = 4; } else if (*n < 0) { info = 5; } else if (*lda < max(1,*m)) { info = 9; } if (info != 0) { xerbla_("CLASR ", &info); return 0; } /* Quick return if possible */ if ((*m == 0) || (*n == 0)) { return 0; } if (lsame_(side, "L")) { /* Form P * A */ if (lsame_(pivot, "V")) { if (lsame_(direct, "F")) { i__1 = *m - 1; for (j = 1; j <= i__1; ++j) { ctemp = c__[j]; stemp = s[j]; if ((ctemp != 1.f) || (stemp != 0.f)) { i__2 = *n; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = j + 1 + i__ * a_dim1; temp.r = a[i__3].r, temp.i = a[i__3].i; i__3 = j + 1 + i__ * a_dim1; q__2.r = ctemp * temp.r, q__2.i = ctemp * temp.i; i__4 = j + i__ * a_dim1; q__3.r = stemp * a[i__4].r, q__3.i = stemp * a[ i__4].i; q__1.r = q__2.r - q__3.r, q__1.i = q__2.i - q__3.i; a[i__3].r = q__1.r, a[i__3].i = q__1.i; i__3 = j + i__ * a_dim1; q__2.r = stemp * temp.r, q__2.i = stemp * temp.i; i__4 = j + i__ * a_dim1; q__3.r = ctemp * a[i__4].r, q__3.i = ctemp * a[ i__4].i; q__1.r = q__2.r + q__3.r, q__1.i = q__2.i + q__3.i; a[i__3].r = q__1.r, a[i__3].i = q__1.i; /* L10: */ } } /* L20: */ } } else if (lsame_(direct, "B")) { for (j = *m - 1; j >= 1; --j) { ctemp = c__[j]; stemp = s[j]; if ((ctemp != 1.f) || (stemp != 0.f)) { i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = j + 1 + i__ * a_dim1; temp.r = a[i__2].r, temp.i = a[i__2].i; i__2 = j + 1 + i__ * a_dim1; q__2.r = ctemp * temp.r, q__2.i = ctemp * temp.i; i__3 = j + i__ * a_dim1; q__3.r = stemp * a[i__3].r, q__3.i = stemp * a[ i__3].i; q__1.r = q__2.r - q__3.r, q__1.i = q__2.i - q__3.i; a[i__2].r = q__1.r, a[i__2].i = q__1.i; i__2 = j + i__ * a_dim1; q__2.r = stemp * temp.r, q__2.i = stemp * temp.i; i__3 = j + i__ * a_dim1; q__3.r = ctemp * a[i__3].r, q__3.i = ctemp * a[ i__3].i; q__1.r = q__2.r + q__3.r, q__1.i = q__2.i + q__3.i; a[i__2].r = q__1.r, a[i__2].i = q__1.i; /* L30: */ } } /* L40: */ } } } else if (lsame_(pivot, "T")) { if (lsame_(direct, "F")) { i__1 = *m; for (j = 2; j <= i__1; ++j) { ctemp = c__[j - 1]; stemp = s[j - 1]; if ((ctemp != 1.f) || (stemp != 0.f)) { i__2 = *n; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = j + i__ * a_dim1; temp.r = a[i__3].r, temp.i = a[i__3].i; i__3 = j + i__ * a_dim1; q__2.r = ctemp * temp.r, q__2.i = ctemp * temp.i; i__4 = i__ * a_dim1 + 1; q__3.r = stemp * a[i__4].r, q__3.i = stemp * a[ i__4].i; q__1.r = q__2.r - q__3.r, q__1.i = q__2.i - q__3.i; a[i__3].r = q__1.r, a[i__3].i = q__1.i; i__3 = i__ * a_dim1 + 1; q__2.r = stemp * temp.r, q__2.i = stemp * temp.i; i__4 = i__ * a_dim1 + 1; q__3.r = ctemp * a[i__4].r, q__3.i = ctemp * a[ i__4].i; q__1.r = q__2.r + q__3.r, q__1.i = q__2.i + q__3.i; a[i__3].r = q__1.r, a[i__3].i = q__1.i; /* L50: */ } } /* L60: */ } } else if (lsame_(direct, "B")) { for (j = *m; j >= 2; --j) { ctemp = c__[j - 1]; stemp = s[j - 1]; if ((ctemp != 1.f) || (stemp != 0.f)) { i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = j + i__ * a_dim1; temp.r = a[i__2].r, temp.i = a[i__2].i; i__2 = j + i__ * a_dim1; q__2.r = ctemp * temp.r, q__2.i = ctemp * temp.i; i__3 = i__ * a_dim1 + 1; q__3.r = stemp * a[i__3].r, q__3.i = stemp * a[ i__3].i; q__1.r = q__2.r - q__3.r, q__1.i = q__2.i - q__3.i; a[i__2].r = q__1.r, a[i__2].i = q__1.i; i__2 = i__ * a_dim1 + 1; q__2.r = stemp * temp.r, q__2.i = stemp * temp.i; i__3 = i__ * a_dim1 + 1; q__3.r = ctemp * a[i__3].r, q__3.i = ctemp * a[ i__3].i; q__1.r = q__2.r + q__3.r, q__1.i = q__2.i + q__3.i; a[i__2].r = q__1.r, a[i__2].i = q__1.i; /* L70: */ } } /* L80: */ } } } else if (lsame_(pivot, "B")) { if (lsame_(direct, "F")) { i__1 = *m - 1; for (j = 1; j <= i__1; ++j) { ctemp = c__[j]; stemp = s[j]; if ((ctemp != 1.f) || (stemp != 0.f)) { i__2 = *n; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = j + i__ * a_dim1; temp.r = a[i__3].r, temp.i = a[i__3].i; i__3 = j + i__ * a_dim1; i__4 = *m + i__ * a_dim1; q__2.r = stemp * a[i__4].r, q__2.i = stemp * a[ i__4].i; q__3.r = ctemp * temp.r, q__3.i = ctemp * temp.i; q__1.r = q__2.r + q__3.r, q__1.i = q__2.i + q__3.i; a[i__3].r = q__1.r, a[i__3].i = q__1.i; i__3 = *m + i__ * a_dim1; i__4 = *m + i__ * a_dim1; q__2.r = ctemp * a[i__4].r, q__2.i = ctemp * a[ i__4].i; q__3.r = stemp * temp.r, q__3.i = stemp * temp.i; q__1.r = q__2.r - q__3.r, q__1.i = q__2.i - q__3.i; a[i__3].r = q__1.r, a[i__3].i = q__1.i; /* L90: */ } } /* L100: */ } } else if (lsame_(direct, "B")) { for (j = *m - 1; j >= 1; --j) { ctemp = c__[j]; stemp = s[j]; if ((ctemp != 1.f) || (stemp != 0.f)) { i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = j + i__ * a_dim1; temp.r = a[i__2].r, temp.i = a[i__2].i; i__2 = j + i__ * a_dim1; i__3 = *m + i__ * a_dim1; q__2.r = stemp * a[i__3].r, q__2.i = stemp * a[ i__3].i; q__3.r = ctemp * temp.r, q__3.i = ctemp * temp.i; q__1.r = q__2.r + q__3.r, q__1.i = q__2.i + q__3.i; a[i__2].r = q__1.r, a[i__2].i = q__1.i; i__2 = *m + i__ * a_dim1; i__3 = *m + i__ * a_dim1; q__2.r = ctemp * a[i__3].r, q__2.i = ctemp * a[ i__3].i; q__3.r = stemp * temp.r, q__3.i = stemp * temp.i; q__1.r = q__2.r - q__3.r, q__1.i = q__2.i - q__3.i; a[i__2].r = q__1.r, a[i__2].i = q__1.i; /* L110: */ } } /* L120: */ } } } } else if (lsame_(side, "R")) { /* Form A * P' */ if (lsame_(pivot, "V")) { if (lsame_(direct, "F")) { i__1 = *n - 1; for (j = 1; j <= i__1; ++j) { ctemp = c__[j]; stemp = s[j]; if ((ctemp != 1.f) || (stemp != 0.f)) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + (j + 1) * a_dim1; temp.r = a[i__3].r, temp.i = a[i__3].i; i__3 = i__ + (j + 1) * a_dim1; q__2.r = ctemp * temp.r, q__2.i = ctemp * temp.i; i__4 = i__ + j * a_dim1; q__3.r = stemp * a[i__4].r, q__3.i = stemp * a[ i__4].i; q__1.r = q__2.r - q__3.r, q__1.i = q__2.i - q__3.i; a[i__3].r = q__1.r, a[i__3].i = q__1.i; i__3 = i__ + j * a_dim1; q__2.r = stemp * temp.r, q__2.i = stemp * temp.i; i__4 = i__ + j * a_dim1; q__3.r = ctemp * a[i__4].r, q__3.i = ctemp * a[ i__4].i; q__1.r = q__2.r + q__3.r, q__1.i = q__2.i + q__3.i; a[i__3].r = q__1.r, a[i__3].i = q__1.i; /* L130: */ } } /* L140: */ } } else if (lsame_(direct, "B")) { for (j = *n - 1; j >= 1; --j) { ctemp = c__[j]; stemp = s[j]; if ((ctemp != 1.f) || (stemp != 0.f)) { i__1 = *m; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = i__ + (j + 1) * a_dim1; temp.r = a[i__2].r, temp.i = a[i__2].i; i__2 = i__ + (j + 1) * a_dim1; q__2.r = ctemp * temp.r, q__2.i = ctemp * temp.i; i__3 = i__ + j * a_dim1; q__3.r = stemp * a[i__3].r, q__3.i = stemp * a[ i__3].i; q__1.r = q__2.r - q__3.r, q__1.i = q__2.i - q__3.i; a[i__2].r = q__1.r, a[i__2].i = q__1.i; i__2 = i__ + j * a_dim1; q__2.r = stemp * temp.r, q__2.i = stemp * temp.i; i__3 = i__ + j * a_dim1; q__3.r = ctemp * a[i__3].r, q__3.i = ctemp * a[ i__3].i; q__1.r = q__2.r + q__3.r, q__1.i = q__2.i + q__3.i; a[i__2].r = q__1.r, a[i__2].i = q__1.i; /* L150: */ } } /* L160: */ } } } else if (lsame_(pivot, "T")) { if (lsame_(direct, "F")) { i__1 = *n; for (j = 2; j <= i__1; ++j) { ctemp = c__[j - 1]; stemp = s[j - 1]; if ((ctemp != 1.f) || (stemp != 0.f)) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * a_dim1; temp.r = a[i__3].r, temp.i = a[i__3].i; i__3 = i__ + j * a_dim1; q__2.r = ctemp * temp.r, q__2.i = ctemp * temp.i; i__4 = i__ + a_dim1; q__3.r = stemp * a[i__4].r, q__3.i = stemp * a[ i__4].i; q__1.r = q__2.r - q__3.r, q__1.i = q__2.i - q__3.i; a[i__3].r = q__1.r, a[i__3].i = q__1.i; i__3 = i__ + a_dim1; q__2.r = stemp * temp.r, q__2.i = stemp * temp.i; i__4 = i__ + a_dim1; q__3.r = ctemp * a[i__4].r, q__3.i = ctemp * a[ i__4].i; q__1.r = q__2.r + q__3.r, q__1.i = q__2.i + q__3.i; a[i__3].r = q__1.r, a[i__3].i = q__1.i; /* L170: */ } } /* L180: */ } } else if (lsame_(direct, "B")) { for (j = *n; j >= 2; --j) { ctemp = c__[j - 1]; stemp = s[j - 1]; if ((ctemp != 1.f) || (stemp != 0.f)) { i__1 = *m; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = i__ + j * a_dim1; temp.r = a[i__2].r, temp.i = a[i__2].i; i__2 = i__ + j * a_dim1; q__2.r = ctemp * temp.r, q__2.i = ctemp * temp.i; i__3 = i__ + a_dim1; q__3.r = stemp * a[i__3].r, q__3.i = stemp * a[ i__3].i; q__1.r = q__2.r - q__3.r, q__1.i = q__2.i - q__3.i; a[i__2].r = q__1.r, a[i__2].i = q__1.i; i__2 = i__ + a_dim1; q__2.r = stemp * temp.r, q__2.i = stemp * temp.i; i__3 = i__ + a_dim1; q__3.r = ctemp * a[i__3].r, q__3.i = ctemp * a[ i__3].i; q__1.r = q__2.r + q__3.r, q__1.i = q__2.i + q__3.i; a[i__2].r = q__1.r, a[i__2].i = q__1.i; /* L190: */ } } /* L200: */ } } } else if (lsame_(pivot, "B")) { if (lsame_(direct, "F")) { i__1 = *n - 1; for (j = 1; j <= i__1; ++j) { ctemp = c__[j]; stemp = s[j]; if ((ctemp != 1.f) || (stemp != 0.f)) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * a_dim1; temp.r = a[i__3].r, temp.i = a[i__3].i; i__3 = i__ + j * a_dim1; i__4 = i__ + *n * a_dim1; q__2.r = stemp * a[i__4].r, q__2.i = stemp * a[ i__4].i; q__3.r = ctemp * temp.r, q__3.i = ctemp * temp.i; q__1.r = q__2.r + q__3.r, q__1.i = q__2.i + q__3.i; a[i__3].r = q__1.r, a[i__3].i = q__1.i; i__3 = i__ + *n * a_dim1; i__4 = i__ + *n * a_dim1; q__2.r = ctemp * a[i__4].r, q__2.i = ctemp * a[ i__4].i; q__3.r = stemp * temp.r, q__3.i = stemp * temp.i; q__1.r = q__2.r - q__3.r, q__1.i = q__2.i - q__3.i; a[i__3].r = q__1.r, a[i__3].i = q__1.i; /* L210: */ } } /* L220: */ } } else if (lsame_(direct, "B")) { for (j = *n - 1; j >= 1; --j) { ctemp = c__[j]; stemp = s[j]; if ((ctemp != 1.f) || (stemp != 0.f)) { i__1 = *m; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = i__ + j * a_dim1; temp.r = a[i__2].r, temp.i = a[i__2].i; i__2 = i__ + j * a_dim1; i__3 = i__ + *n * a_dim1; q__2.r = stemp * a[i__3].r, q__2.i = stemp * a[ i__3].i; q__3.r = ctemp * temp.r, q__3.i = ctemp * temp.i; q__1.r = q__2.r + q__3.r, q__1.i = q__2.i + q__3.i; a[i__2].r = q__1.r, a[i__2].i = q__1.i; i__2 = i__ + *n * a_dim1; i__3 = i__ + *n * a_dim1; q__2.r = ctemp * a[i__3].r, q__2.i = ctemp * a[ i__3].i; q__3.r = stemp * temp.r, q__3.i = stemp * temp.i; q__1.r = q__2.r - q__3.r, q__1.i = q__2.i - q__3.i; a[i__2].r = q__1.r, a[i__2].i = q__1.i; /* L230: */ } } /* L240: */ } } } } return 0; /* End of CLASR */ } /* clasr_ */ /* Subroutine */ int classq_(integer *n, complex *x, integer *incx, real * scale, real *sumsq) { /* System generated locals */ integer i__1, i__2, i__3; real r__1; /* Builtin functions */ double r_imag(complex *); /* Local variables */ static integer ix; static real temp1; /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= CLASSQ returns the values scl and ssq such that ( scl**2 )*ssq = x( 1 )**2 +...+ x( n )**2 + ( scale**2 )*sumsq, where x( i ) = abs( X( 1 + ( i - 1 )*INCX ) ). The value of sumsq is assumed to be at least unity and the value of ssq will then satisfy 1.0 .le. ssq .le. ( sumsq + 2*n ). scale is assumed to be non-negative and scl returns the value scl = max( scale, abs( real( x( i ) ) ), abs( aimag( x( i ) ) ) ), i scale and sumsq must be supplied in SCALE and SUMSQ respectively. SCALE and SUMSQ are overwritten by scl and ssq respectively. The routine makes only one pass through the vector X. Arguments ========= N (input) INTEGER The number of elements to be used from the vector X. X (input) COMPLEX array, dimension (N) The vector x as described above. x( i ) = X( 1 + ( i - 1 )*INCX ), 1 <= i <= n. INCX (input) INTEGER The increment between successive values of the vector X. INCX > 0. SCALE (input/output) REAL On entry, the value scale in the equation above. On exit, SCALE is overwritten with the value scl . SUMSQ (input/output) REAL On entry, the value sumsq in the equation above. On exit, SUMSQ is overwritten with the value ssq . ===================================================================== */ /* Parameter adjustments */ --x; /* Function Body */ if (*n > 0) { i__1 = (*n - 1) * *incx + 1; i__2 = *incx; for (ix = 1; i__2 < 0 ? ix >= i__1 : ix <= i__1; ix += i__2) { i__3 = ix; if (x[i__3].r != 0.f) { i__3 = ix; temp1 = (r__1 = x[i__3].r, dabs(r__1)); if (*scale < temp1) { /* Computing 2nd power */ r__1 = *scale / temp1; *sumsq = *sumsq * (r__1 * r__1) + 1; *scale = temp1; } else { /* Computing 2nd power */ r__1 = temp1 / *scale; *sumsq += r__1 * r__1; } } if (r_imag(&x[ix]) != 0.f) { temp1 = (r__1 = r_imag(&x[ix]), dabs(r__1)); if (*scale < temp1) { /* Computing 2nd power */ r__1 = *scale / temp1; *sumsq = *sumsq * (r__1 * r__1) + 1; *scale = temp1; } else { /* Computing 2nd power */ r__1 = temp1 / *scale; *sumsq += r__1 * r__1; } } /* L10: */ } } return 0; /* End of CLASSQ */ } /* classq_ */ /* Subroutine */ int claswp_(integer *n, complex *a, integer *lda, integer * k1, integer *k2, integer *ipiv, integer *incx) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3, i__4, i__5, i__6; /* Local variables */ static integer i__, j, k, i1, i2, n32, ip, ix, ix0, inc; static complex temp; /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= CLASWP performs a series of row interchanges on the matrix A. One row interchange is initiated for each of rows K1 through K2 of A. Arguments ========= N (input) INTEGER The number of columns of the matrix A. A (input/output) COMPLEX array, dimension (LDA,N) On entry, the matrix of column dimension N to which the row interchanges will be applied. On exit, the permuted matrix. LDA (input) INTEGER The leading dimension of the array A. K1 (input) INTEGER The first element of IPIV for which a row interchange will be done. K2 (input) INTEGER The last element of IPIV for which a row interchange will be done. IPIV (input) INTEGER array, dimension (M*abs(INCX)) The vector of pivot indices. Only the elements in positions K1 through K2 of IPIV are accessed. IPIV(K) = L implies rows K and L are to be interchanged. INCX (input) INTEGER The increment between successive values of IPIV. If IPIV is negative, the pivots are applied in reverse order. Further Details =============== Modified by R. C. Whaley, Computer Science Dept., Univ. of Tenn., Knoxville, USA ===================================================================== Interchange row I with row IPIV(I) for each of rows K1 through K2. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --ipiv; /* Function Body */ if (*incx > 0) { ix0 = *k1; i1 = *k1; i2 = *k2; inc = 1; } else if (*incx < 0) { ix0 = (1 - *k2) * *incx + 1; i1 = *k2; i2 = *k1; inc = -1; } else { return 0; } n32 = (*n / 32) << (5); if (n32 != 0) { i__1 = n32; for (j = 1; j <= i__1; j += 32) { ix = ix0; i__2 = i2; i__3 = inc; for (i__ = i1; i__3 < 0 ? i__ >= i__2 : i__ <= i__2; i__ += i__3) { ip = ipiv[ix]; if (ip != i__) { i__4 = j + 31; for (k = j; k <= i__4; ++k) { i__5 = i__ + k * a_dim1; temp.r = a[i__5].r, temp.i = a[i__5].i; i__5 = i__ + k * a_dim1; i__6 = ip + k * a_dim1; a[i__5].r = a[i__6].r, a[i__5].i = a[i__6].i; i__5 = ip + k * a_dim1; a[i__5].r = temp.r, a[i__5].i = temp.i; /* L10: */ } } ix += *incx; /* L20: */ } /* L30: */ } } if (n32 != *n) { ++n32; ix = ix0; i__1 = i2; i__3 = inc; for (i__ = i1; i__3 < 0 ? i__ >= i__1 : i__ <= i__1; i__ += i__3) { ip = ipiv[ix]; if (ip != i__) { i__2 = *n; for (k = n32; k <= i__2; ++k) { i__4 = i__ + k * a_dim1; temp.r = a[i__4].r, temp.i = a[i__4].i; i__4 = i__ + k * a_dim1; i__5 = ip + k * a_dim1; a[i__4].r = a[i__5].r, a[i__4].i = a[i__5].i; i__4 = ip + k * a_dim1; a[i__4].r = temp.r, a[i__4].i = temp.i; /* L40: */ } } ix += *incx; /* L50: */ } } return 0; /* End of CLASWP */ } /* claswp_ */ /* Subroutine */ int clatrd_(char *uplo, integer *n, integer *nb, complex *a, integer *lda, real *e, complex *tau, complex *w, integer *ldw) { /* System generated locals */ integer a_dim1, a_offset, w_dim1, w_offset, i__1, i__2, i__3; real r__1; complex q__1, q__2, q__3, q__4; /* Local variables */ static integer i__, iw; static complex alpha; extern /* Subroutine */ int cscal_(integer *, complex *, complex *, integer *); extern /* Complex */ VOID cdotc_(complex *, integer *, complex *, integer *, complex *, integer *); extern /* Subroutine */ int cgemv_(char *, integer *, integer *, complex * , complex *, integer *, complex *, integer *, complex *, complex * , integer *), chemv_(char *, integer *, complex *, complex *, integer *, complex *, integer *, complex *, complex *, integer *); extern logical lsame_(char *, char *); extern /* Subroutine */ int caxpy_(integer *, complex *, complex *, integer *, complex *, integer *), clarfg_(integer *, complex *, complex *, integer *, complex *), clacgv_(integer *, complex *, integer *); /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University September 30, 1994 Purpose ======= CLATRD reduces NB rows and columns of a complex Hermitian matrix A to Hermitian tridiagonal form by a unitary similarity transformation Q' * A * Q, and returns the matrices V and W which are needed to apply the transformation to the unreduced part of A. If UPLO = 'U', CLATRD reduces the last NB rows and columns of a matrix, of which the upper triangle is supplied; if UPLO = 'L', CLATRD reduces the first NB rows and columns of a matrix, of which the lower triangle is supplied. This is an auxiliary routine called by CHETRD. Arguments ========= UPLO (input) CHARACTER Specifies whether the upper or lower triangular part of the Hermitian matrix A is stored: = 'U': Upper triangular = 'L': Lower triangular N (input) INTEGER The order of the matrix A. NB (input) INTEGER The number of rows and columns to be reduced. A (input/output) COMPLEX 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, and the strictly lower triangular part of A is not referenced. If UPLO = 'L', the leading n-by-n lower triangular part of A contains the lower triangular part of the matrix A, and the strictly upper triangular part of A is not referenced. On exit: if UPLO = 'U', the last NB columns have been reduced to tridiagonal form, with the diagonal elements overwriting the diagonal elements of A; the elements above the diagonal with the array TAU, represent the unitary matrix Q as a product of elementary reflectors; if UPLO = 'L', the first NB columns have been reduced to tridiagonal form, with the diagonal elements overwriting the diagonal elements of A; the elements below the diagonal with the array TAU, represent the unitary matrix Q as a product of elementary reflectors. See Further Details. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,N). E (output) REAL array, dimension (N-1) If UPLO = 'U', E(n-nb:n-1) contains the superdiagonal elements of the last NB columns of the reduced matrix; if UPLO = 'L', E(1:nb) contains the subdiagonal elements of the first NB columns of the reduced matrix. TAU (output) COMPLEX array, dimension (N-1) The scalar factors of the elementary reflectors, stored in TAU(n-nb:n-1) if UPLO = 'U', and in TAU(1:nb) if UPLO = 'L'. See Further Details. W (output) COMPLEX array, dimension (LDW,NB) The n-by-nb matrix W required to update the unreduced part of A. LDW (input) INTEGER The leading dimension of the array W. LDW >= max(1,N). Further Details =============== If UPLO = 'U', the matrix Q is represented as a product of elementary reflectors Q = H(n) H(n-1) . . . H(n-nb+1). Each H(i) has the form H(i) = I - tau * v * v' where tau is a complex scalar, and v is a complex vector with v(i:n) = 0 and v(i-1) = 1; v(1:i-1) is stored on exit in A(1:i-1,i), and tau in TAU(i-1). If UPLO = 'L', the matrix Q is represented as a product of elementary reflectors Q = H(1) H(2) . . . H(nb). Each H(i) has the form H(i) = I - tau * v * v' where tau is a complex scalar, and v is a complex vector with v(1:i) = 0 and v(i+1) = 1; v(i+1:n) is stored on exit in A(i+1:n,i), and tau in TAU(i). The elements of the vectors v together form the n-by-nb matrix V which is needed, with W, to apply the transformation to the unreduced part of the matrix, using a Hermitian rank-2k update of the form: A := A - V*W' - W*V'. The contents of A on exit are illustrated by the following examples with n = 5 and nb = 2: if UPLO = 'U': if UPLO = 'L': ( a a a v4 v5 ) ( d ) ( a a v4 v5 ) ( 1 d ) ( a 1 v5 ) ( v1 1 a ) ( d 1 ) ( v1 v2 a a ) ( d ) ( v1 v2 a a a ) where d denotes a diagonal element of the reduced matrix, a denotes an element of the original matrix that is unchanged, and vi denotes an element of the vector defining H(i). ===================================================================== Quick return if possible */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --e; --tau; w_dim1 = *ldw; w_offset = 1 + w_dim1; w -= w_offset; /* Function Body */ if (*n <= 0) { return 0; } if (lsame_(uplo, "U")) { /* Reduce last NB columns of upper triangle */ i__1 = *n - *nb + 1; for (i__ = *n; i__ >= i__1; --i__) { iw = i__ - *n + *nb; if (i__ < *n) { /* Update A(1:i,i) */ i__2 = i__ + i__ * a_dim1; i__3 = i__ + i__ * a_dim1; r__1 = a[i__3].r; a[i__2].r = r__1, a[i__2].i = 0.f; i__2 = *n - i__; clacgv_(&i__2, &w[i__ + (iw + 1) * w_dim1], ldw); i__2 = *n - i__; q__1.r = -1.f, q__1.i = -0.f; cgemv_("No transpose", &i__, &i__2, &q__1, &a[(i__ + 1) * a_dim1 + 1], lda, &w[i__ + (iw + 1) * w_dim1], ldw, & c_b56, &a[i__ * a_dim1 + 1], &c__1); i__2 = *n - i__; clacgv_(&i__2, &w[i__ + (iw + 1) * w_dim1], ldw); i__2 = *n - i__; clacgv_(&i__2, &a[i__ + (i__ + 1) * a_dim1], lda); i__2 = *n - i__; q__1.r = -1.f, q__1.i = -0.f; cgemv_("No transpose", &i__, &i__2, &q__1, &w[(iw + 1) * w_dim1 + 1], ldw, &a[i__ + (i__ + 1) * a_dim1], lda, & c_b56, &a[i__ * a_dim1 + 1], &c__1); i__2 = *n - i__; clacgv_(&i__2, &a[i__ + (i__ + 1) * a_dim1], lda); i__2 = i__ + i__ * a_dim1; i__3 = i__ + i__ * a_dim1; r__1 = a[i__3].r; a[i__2].r = r__1, a[i__2].i = 0.f; } if (i__ > 1) { /* Generate elementary reflector H(i) to annihilate A(1:i-2,i) */ i__2 = i__ - 1 + i__ * a_dim1; alpha.r = a[i__2].r, alpha.i = a[i__2].i; i__2 = i__ - 1; clarfg_(&i__2, &alpha, &a[i__ * a_dim1 + 1], &c__1, &tau[i__ - 1]); i__2 = i__ - 1; e[i__2] = alpha.r; i__2 = i__ - 1 + i__ * a_dim1; a[i__2].r = 1.f, a[i__2].i = 0.f; /* Compute W(1:i-1,i) */ i__2 = i__ - 1; chemv_("Upper", &i__2, &c_b56, &a[a_offset], lda, &a[i__ * a_dim1 + 1], &c__1, &c_b55, &w[iw * w_dim1 + 1], & c__1); if (i__ < *n) { i__2 = i__ - 1; i__3 = *n - i__; cgemv_("Conjugate transpose", &i__2, &i__3, &c_b56, &w[( iw + 1) * w_dim1 + 1], ldw, &a[i__ * a_dim1 + 1], &c__1, &c_b55, &w[i__ + 1 + iw * w_dim1], &c__1); i__2 = i__ - 1; i__3 = *n - i__; q__1.r = -1.f, q__1.i = -0.f; cgemv_("No transpose", &i__2, &i__3, &q__1, &a[(i__ + 1) * a_dim1 + 1], lda, &w[i__ + 1 + iw * w_dim1], & c__1, &c_b56, &w[iw * w_dim1 + 1], &c__1); i__2 = i__ - 1; i__3 = *n - i__; cgemv_("Conjugate transpose", &i__2, &i__3, &c_b56, &a[( i__ + 1) * a_dim1 + 1], lda, &a[i__ * a_dim1 + 1], &c__1, &c_b55, &w[i__ + 1 + iw * w_dim1], &c__1); i__2 = i__ - 1; i__3 = *n - i__; q__1.r = -1.f, q__1.i = -0.f; cgemv_("No transpose", &i__2, &i__3, &q__1, &w[(iw + 1) * w_dim1 + 1], ldw, &w[i__ + 1 + iw * w_dim1], & c__1, &c_b56, &w[iw * w_dim1 + 1], &c__1); } i__2 = i__ - 1; cscal_(&i__2, &tau[i__ - 1], &w[iw * w_dim1 + 1], &c__1); q__3.r = -.5f, q__3.i = -0.f; i__2 = i__ - 1; q__2.r = q__3.r * tau[i__2].r - q__3.i * tau[i__2].i, q__2.i = q__3.r * tau[i__2].i + q__3.i * tau[i__2].r; i__3 = i__ - 1; cdotc_(&q__4, &i__3, &w[iw * w_dim1 + 1], &c__1, &a[i__ * a_dim1 + 1], &c__1); q__1.r = q__2.r * q__4.r - q__2.i * q__4.i, q__1.i = q__2.r * q__4.i + q__2.i * q__4.r; alpha.r = q__1.r, alpha.i = q__1.i; i__2 = i__ - 1; caxpy_(&i__2, &alpha, &a[i__ * a_dim1 + 1], &c__1, &w[iw * w_dim1 + 1], &c__1); } /* L10: */ } } else { /* Reduce first NB columns of lower triangle */ i__1 = *nb; for (i__ = 1; i__ <= i__1; ++i__) { /* Update A(i:n,i) */ i__2 = i__ + i__ * a_dim1; i__3 = i__ + i__ * a_dim1; r__1 = a[i__3].r; a[i__2].r = r__1, a[i__2].i = 0.f; i__2 = i__ - 1; clacgv_(&i__2, &w[i__ + w_dim1], ldw); i__2 = *n - i__ + 1; i__3 = i__ - 1; q__1.r = -1.f, q__1.i = -0.f; cgemv_("No transpose", &i__2, &i__3, &q__1, &a[i__ + a_dim1], lda, &w[i__ + w_dim1], ldw, &c_b56, &a[i__ + i__ * a_dim1], & c__1); i__2 = i__ - 1; clacgv_(&i__2, &w[i__ + w_dim1], ldw); i__2 = i__ - 1; clacgv_(&i__2, &a[i__ + a_dim1], lda); i__2 = *n - i__ + 1; i__3 = i__ - 1; q__1.r = -1.f, q__1.i = -0.f; cgemv_("No transpose", &i__2, &i__3, &q__1, &w[i__ + w_dim1], ldw, &a[i__ + a_dim1], lda, &c_b56, &a[i__ + i__ * a_dim1], & c__1); i__2 = i__ - 1; clacgv_(&i__2, &a[i__ + a_dim1], lda); i__2 = i__ + i__ * a_dim1; i__3 = i__ + i__ * a_dim1; r__1 = a[i__3].r; a[i__2].r = r__1, a[i__2].i = 0.f; if (i__ < *n) { /* Generate elementary reflector H(i) to annihilate A(i+2:n,i) */ i__2 = i__ + 1 + i__ * a_dim1; alpha.r = a[i__2].r, alpha.i = a[i__2].i; i__2 = *n - i__; /* Computing MIN */ i__3 = i__ + 2; clarfg_(&i__2, &alpha, &a[min(i__3,*n) + i__ * a_dim1], &c__1, &tau[i__]); i__2 = i__; e[i__2] = alpha.r; i__2 = i__ + 1 + i__ * a_dim1; a[i__2].r = 1.f, a[i__2].i = 0.f; /* Compute W(i+1:n,i) */ i__2 = *n - i__; chemv_("Lower", &i__2, &c_b56, &a[i__ + 1 + (i__ + 1) * a_dim1], lda, &a[i__ + 1 + i__ * a_dim1], &c__1, & c_b55, &w[i__ + 1 + i__ * w_dim1], &c__1); i__2 = *n - i__; i__3 = i__ - 1; cgemv_("Conjugate transpose", &i__2, &i__3, &c_b56, &w[i__ + 1 + w_dim1], ldw, &a[i__ + 1 + i__ * a_dim1], &c__1, & c_b55, &w[i__ * w_dim1 + 1], &c__1); i__2 = *n - i__; i__3 = i__ - 1; q__1.r = -1.f, q__1.i = -0.f; cgemv_("No transpose", &i__2, &i__3, &q__1, &a[i__ + 1 + a_dim1], lda, &w[i__ * w_dim1 + 1], &c__1, &c_b56, &w[ i__ + 1 + i__ * w_dim1], &c__1); i__2 = *n - i__; i__3 = i__ - 1; cgemv_("Conjugate transpose", &i__2, &i__3, &c_b56, &a[i__ + 1 + a_dim1], lda, &a[i__ + 1 + i__ * a_dim1], &c__1, & c_b55, &w[i__ * w_dim1 + 1], &c__1); i__2 = *n - i__; i__3 = i__ - 1; q__1.r = -1.f, q__1.i = -0.f; cgemv_("No transpose", &i__2, &i__3, &q__1, &w[i__ + 1 + w_dim1], ldw, &w[i__ * w_dim1 + 1], &c__1, &c_b56, &w[ i__ + 1 + i__ * w_dim1], &c__1); i__2 = *n - i__; cscal_(&i__2, &tau[i__], &w[i__ + 1 + i__ * w_dim1], &c__1); q__3.r = -.5f, q__3.i = -0.f; i__2 = i__; q__2.r = q__3.r * tau[i__2].r - q__3.i * tau[i__2].i, q__2.i = q__3.r * tau[i__2].i + q__3.i * tau[i__2].r; i__3 = *n - i__; cdotc_(&q__4, &i__3, &w[i__ + 1 + i__ * w_dim1], &c__1, &a[ i__ + 1 + i__ * a_dim1], &c__1); q__1.r = q__2.r * q__4.r - q__2.i * q__4.i, q__1.i = q__2.r * q__4.i + q__2.i * q__4.r; alpha.r = q__1.r, alpha.i = q__1.i; i__2 = *n - i__; caxpy_(&i__2, &alpha, &a[i__ + 1 + i__ * a_dim1], &c__1, &w[ i__ + 1 + i__ * w_dim1], &c__1); } /* L20: */ } } return 0; /* End of CLATRD */ } /* clatrd_ */ /* Subroutine */ int clatrs_(char *uplo, char *trans, char *diag, char * normin, integer *n, complex *a, integer *lda, complex *x, real *scale, real *cnorm, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3, i__4, i__5; real r__1, r__2, r__3, r__4; complex q__1, q__2, q__3, q__4; /* Builtin functions */ double r_imag(complex *); void r_cnjg(complex *, complex *); /* Local variables */ static integer i__, j; static real xj, rec, tjj; static integer jinc; static real xbnd; static integer imax; static real tmax; static complex tjjs; static real xmax, grow; extern /* Complex */ VOID cdotc_(complex *, integer *, complex *, integer *, complex *, integer *); extern logical lsame_(char *, char *); extern /* Subroutine */ int sscal_(integer *, real *, real *, integer *); static real tscal; static complex uscal; static integer jlast; extern /* Complex */ VOID cdotu_(complex *, integer *, complex *, integer *, complex *, integer *); static complex csumj; extern /* Subroutine */ int caxpy_(integer *, complex *, complex *, integer *, complex *, integer *); static logical upper; extern /* Subroutine */ int ctrsv_(char *, char *, char *, integer *, complex *, integer *, complex *, integer *), slabad_(real *, real *); extern integer icamax_(integer *, complex *, integer *); extern /* Complex */ VOID cladiv_(complex *, complex *, complex *); extern doublereal slamch_(char *); extern /* Subroutine */ int csscal_(integer *, real *, complex *, integer *), xerbla_(char *, integer *); static real bignum; extern integer isamax_(integer *, real *, integer *); extern doublereal scasum_(integer *, complex *, integer *); static logical notran; static integer jfirst; static real smlnum; static logical nounit; /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1992 Purpose ======= CLATRS solves one of the triangular systems A * x = s*b, A**T * x = s*b, or A**H * x = s*b, with scaling to prevent overflow. Here A is an upper or lower triangular matrix, A**T denotes the transpose of A, A**H denotes the conjugate transpose of A, x and b are n-element vectors, and s is a scaling factor, usually less than or equal to 1, chosen so that the components of x will be less than the overflow threshold. If the unscaled problem will not cause overflow, the Level 2 BLAS routine CTRSV is called. If the matrix A is singular (A(j,j) = 0 for some j), then s is set to 0 and a non-trivial solution to A*x = 0 is returned. Arguments ========= UPLO (input) CHARACTER*1 Specifies whether the matrix A is upper or lower triangular. = 'U': Upper triangular = 'L': Lower triangular TRANS (input) CHARACTER*1 Specifies the operation applied to A. = 'N': Solve A * x = s*b (No transpose) = 'T': Solve A**T * x = s*b (Transpose) = 'C': Solve A**H * x = s*b (Conjugate transpose) DIAG (input) CHARACTER*1 Specifies whether or not the matrix A is unit triangular. = 'N': Non-unit triangular = 'U': Unit triangular NORMIN (input) CHARACTER*1 Specifies whether CNORM has been set or not. = 'Y': CNORM contains the column norms on entry = 'N': CNORM is not set on entry. On exit, the norms will be computed and stored in CNORM. N (input) INTEGER The order of the matrix A. N >= 0. A (input) COMPLEX array, dimension (LDA,N) The triangular matrix A. If UPLO = 'U', the leading n by n upper triangular part of the array A contains the upper triangular matrix, and the strictly lower triangular part of A is not referenced. If UPLO = 'L', the leading n by n lower triangular part of the array A contains the lower triangular matrix, and the strictly upper triangular part of A is not referenced. If DIAG = 'U', the diagonal elements of A are also not referenced and are assumed to be 1. LDA (input) INTEGER The leading dimension of the array A. LDA >= max (1,N). X (input/output) COMPLEX array, dimension (N) On entry, the right hand side b of the triangular system. On exit, X is overwritten by the solution vector x. SCALE (output) REAL The scaling factor s for the triangular system A * x = s*b, A**T * x = s*b, or A**H * x = s*b. If SCALE = 0, the matrix A is singular or badly scaled, and the vector x is an exact or approximate solution to A*x = 0. CNORM (input or output) REAL array, dimension (N) If NORMIN = 'Y', CNORM is an input argument and CNORM(j) contains the norm of the off-diagonal part of the j-th column of A. If TRANS = 'N', CNORM(j) must be greater than or equal to the infinity-norm, and if TRANS = 'T' or 'C', CNORM(j) must be greater than or equal to the 1-norm. If NORMIN = 'N', CNORM is an output argument and CNORM(j) returns the 1-norm of the offdiagonal part of the j-th column of A. INFO (output) INTEGER = 0: successful exit < 0: if INFO = -k, the k-th argument had an illegal value Further Details ======= ======= A rough bound on x is computed; if that is less than overflow, CTRSV is called, otherwise, specific code is used which checks for possible overflow or divide-by-zero at every operation. A columnwise scheme is used for solving A*x = b. The basic algorithm if A is lower triangular is x[1:n] := b[1:n] for j = 1, ..., n x(j) := x(j) / A(j,j) x[j+1:n] := x[j+1:n] - x(j) * A[j+1:n,j] end Define bounds on the components of x after j iterations of the loop: M(j) = bound on x[1:j] G(j) = bound on x[j+1:n] Initially, let M(0) = 0 and G(0) = max{x(i), i=1,...,n}. Then for iteration j+1 we have M(j+1) <= G(j) / | A(j+1,j+1) | G(j+1) <= G(j) + M(j+1) * | A[j+2:n,j+1] | <= G(j) ( 1 + CNORM(j+1) / | A(j+1,j+1) | ) where CNORM(j+1) is greater than or equal to the infinity-norm of column j+1 of A, not counting the diagonal. Hence G(j) <= G(0) product ( 1 + CNORM(i) / | A(i,i) | ) 1<=i<=j and |x(j)| <= ( G(0) / |A(j,j)| ) product ( 1 + CNORM(i) / |A(i,i)| ) 1<=i< j Since |x(j)| <= M(j), we use the Level 2 BLAS routine CTRSV if the reciprocal of the largest M(j), j=1,..,n, is larger than max(underflow, 1/overflow). The bound on x(j) is also used to determine when a step in the columnwise method can be performed without fear of overflow. If the computed bound is greater than a large constant, x is scaled to prevent overflow, but if the bound overflows, x is set to 0, x(j) to 1, and scale to 0, and a non-trivial solution to A*x = 0 is found. Similarly, a row-wise scheme is used to solve A**T *x = b or A**H *x = b. The basic algorithm for A upper triangular is for j = 1, ..., n x(j) := ( b(j) - A[1:j-1,j]' * x[1:j-1] ) / A(j,j) end We simultaneously compute two bounds G(j) = bound on ( b(i) - A[1:i-1,i]' * x[1:i-1] ), 1<=i<=j M(j) = bound on x(i), 1<=i<=j The initial values are G(0) = 0, M(0) = max{b(i), i=1,..,n}, and we add the constraint G(j) >= G(j-1) and M(j) >= M(j-1) for j >= 1. Then the bound on x(j) is M(j) <= M(j-1) * ( 1 + CNORM(j) ) / | A(j,j) | <= M(0) * product ( ( 1 + CNORM(i) ) / |A(i,i)| ) 1<=i<=j and we can safely call CTRSV if 1/M(n) and 1/G(n) are both greater than max(underflow, 1/overflow). ===================================================================== */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --x; --cnorm; /* Function Body */ *info = 0; upper = lsame_(uplo, "U"); notran = lsame_(trans, "N"); nounit = lsame_(diag, "N"); /* Test the input parameters. */ if (! upper && ! lsame_(uplo, "L")) { *info = -1; } else if (! notran && ! lsame_(trans, "T") && ! lsame_(trans, "C")) { *info = -2; } else if (! nounit && ! lsame_(diag, "U")) { *info = -3; } else if (! lsame_(normin, "Y") && ! lsame_(normin, "N")) { *info = -4; } else if (*n < 0) { *info = -5; } else if (*lda < max(1,*n)) { *info = -7; } if (*info != 0) { i__1 = -(*info); xerbla_("CLATRS", &i__1); return 0; } /* Quick return if possible */ if (*n == 0) { return 0; } /* Determine machine dependent parameters to control overflow. */ smlnum = slamch_("Safe minimum"); bignum = 1.f / smlnum; slabad_(&smlnum, &bignum); smlnum /= slamch_("Precision"); bignum = 1.f / smlnum; *scale = 1.f; if (lsame_(normin, "N")) { /* Compute the 1-norm of each column, not including the diagonal. */ if (upper) { /* A is upper triangular. */ i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = j - 1; cnorm[j] = scasum_(&i__2, &a[j * a_dim1 + 1], &c__1); /* L10: */ } } else { /* A is lower triangular. */ i__1 = *n - 1; for (j = 1; j <= i__1; ++j) { i__2 = *n - j; cnorm[j] = scasum_(&i__2, &a[j + 1 + j * a_dim1], &c__1); /* L20: */ } cnorm[*n] = 0.f; } } /* Scale the column norms by TSCAL if the maximum element in CNORM is greater than BIGNUM/2. */ imax = isamax_(n, &cnorm[1], &c__1); tmax = cnorm[imax]; if (tmax <= bignum * .5f) { tscal = 1.f; } else { tscal = .5f / (smlnum * tmax); sscal_(n, &tscal, &cnorm[1], &c__1); } /* Compute a bound on the computed solution vector to see if the Level 2 BLAS routine CTRSV can be used. */ xmax = 0.f; i__1 = *n; for (j = 1; j <= i__1; ++j) { /* Computing MAX */ i__2 = j; r__3 = xmax, r__4 = (r__1 = x[i__2].r / 2.f, dabs(r__1)) + (r__2 = r_imag(&x[j]) / 2.f, dabs(r__2)); xmax = dmax(r__3,r__4); /* L30: */ } xbnd = xmax; if (notran) { /* Compute the growth in A * x = b. */ if (upper) { jfirst = *n; jlast = 1; jinc = -1; } else { jfirst = 1; jlast = *n; jinc = 1; } if (tscal != 1.f) { grow = 0.f; goto L60; } if (nounit) { /* A is non-unit triangular. Compute GROW = 1/G(j) and XBND = 1/M(j). Initially, G(0) = max{x(i), i=1,...,n}. */ grow = .5f / dmax(xbnd,smlnum); xbnd = grow; i__1 = jlast; i__2 = jinc; for (j = jfirst; i__2 < 0 ? j >= i__1 : j <= i__1; j += i__2) { /* Exit the loop if the growth factor is too small. */ if (grow <= smlnum) { goto L60; } i__3 = j + j * a_dim1; tjjs.r = a[i__3].r, tjjs.i = a[i__3].i; tjj = (r__1 = tjjs.r, dabs(r__1)) + (r__2 = r_imag(&tjjs), dabs(r__2)); if (tjj >= smlnum) { /* M(j) = G(j-1) / abs(A(j,j)) Computing MIN */ r__1 = xbnd, r__2 = dmin(1.f,tjj) * grow; xbnd = dmin(r__1,r__2); } else { /* M(j) could overflow, set XBND to 0. */ xbnd = 0.f; } if (tjj + cnorm[j] >= smlnum) { /* G(j) = G(j-1)*( 1 + CNORM(j) / abs(A(j,j)) ) */ grow *= tjj / (tjj + cnorm[j]); } else { /* G(j) could overflow, set GROW to 0. */ grow = 0.f; } /* L40: */ } grow = xbnd; } else { /* A is unit triangular. Compute GROW = 1/G(j), where G(0) = max{x(i), i=1,...,n}. Computing MIN */ r__1 = 1.f, r__2 = .5f / dmax(xbnd,smlnum); grow = dmin(r__1,r__2); i__2 = jlast; i__1 = jinc; for (j = jfirst; i__1 < 0 ? j >= i__2 : j <= i__2; j += i__1) { /* Exit the loop if the growth factor is too small. */ if (grow <= smlnum) { goto L60; } /* G(j) = G(j-1)*( 1 + CNORM(j) ) */ grow *= 1.f / (cnorm[j] + 1.f); /* L50: */ } } L60: ; } else { /* Compute the growth in A**T * x = b or A**H * x = b. */ if (upper) { jfirst = 1; jlast = *n; jinc = 1; } else { jfirst = *n; jlast = 1; jinc = -1; } if (tscal != 1.f) { grow = 0.f; goto L90; } if (nounit) { /* A is non-unit triangular. Compute GROW = 1/G(j) and XBND = 1/M(j). Initially, M(0) = max{x(i), i=1,...,n}. */ grow = .5f / dmax(xbnd,smlnum); xbnd = grow; i__1 = jlast; i__2 = jinc; for (j = jfirst; i__2 < 0 ? j >= i__1 : j <= i__1; j += i__2) { /* Exit the loop if the growth factor is too small. */ if (grow <= smlnum) { goto L90; } /* G(j) = max( G(j-1), M(j-1)*( 1 + CNORM(j) ) ) */ xj = cnorm[j] + 1.f; /* Computing MIN */ r__1 = grow, r__2 = xbnd / xj; grow = dmin(r__1,r__2); i__3 = j + j * a_dim1; tjjs.r = a[i__3].r, tjjs.i = a[i__3].i; tjj = (r__1 = tjjs.r, dabs(r__1)) + (r__2 = r_imag(&tjjs), dabs(r__2)); if (tjj >= smlnum) { /* M(j) = M(j-1)*( 1 + CNORM(j) ) / abs(A(j,j)) */ if (xj > tjj) { xbnd *= tjj / xj; } } else { /* M(j) could overflow, set XBND to 0. */ xbnd = 0.f; } /* L70: */ } grow = dmin(grow,xbnd); } else { /* A is unit triangular. Compute GROW = 1/G(j), where G(0) = max{x(i), i=1,...,n}. Computing MIN */ r__1 = 1.f, r__2 = .5f / dmax(xbnd,smlnum); grow = dmin(r__1,r__2); i__2 = jlast; i__1 = jinc; for (j = jfirst; i__1 < 0 ? j >= i__2 : j <= i__2; j += i__1) { /* Exit the loop if the growth factor is too small. */ if (grow <= smlnum) { goto L90; } /* G(j) = ( 1 + CNORM(j) )*G(j-1) */ xj = cnorm[j] + 1.f; grow /= xj; /* L80: */ } } L90: ; } if (grow * tscal > smlnum) { /* Use the Level 2 BLAS solve if the reciprocal of the bound on elements of X is not too small. */ ctrsv_(uplo, trans, diag, n, &a[a_offset], lda, &x[1], &c__1); } else { /* Use a Level 1 BLAS solve, scaling intermediate results. */ if (xmax > bignum * .5f) { /* Scale X so that its components are less than or equal to BIGNUM in absolute value. */ *scale = bignum * .5f / xmax; csscal_(n, scale, &x[1], &c__1); xmax = bignum; } else { xmax *= 2.f; } if (notran) { /* Solve A * x = b */ i__1 = jlast; i__2 = jinc; for (j = jfirst; i__2 < 0 ? j >= i__1 : j <= i__1; j += i__2) { /* Compute x(j) = b(j) / A(j,j), scaling x if necessary. */ i__3 = j; xj = (r__1 = x[i__3].r, dabs(r__1)) + (r__2 = r_imag(&x[j]), dabs(r__2)); if (nounit) { i__3 = j + j * a_dim1; q__1.r = tscal * a[i__3].r, q__1.i = tscal * a[i__3].i; tjjs.r = q__1.r, tjjs.i = q__1.i; } else { tjjs.r = tscal, tjjs.i = 0.f; if (tscal == 1.f) { goto L105; } } tjj = (r__1 = tjjs.r, dabs(r__1)) + (r__2 = r_imag(&tjjs), dabs(r__2)); if (tjj > smlnum) { /* abs(A(j,j)) > SMLNUM: */ if (tjj < 1.f) { if (xj > tjj * bignum) { /* Scale x by 1/b(j). */ rec = 1.f / xj; csscal_(n, &rec, &x[1], &c__1); *scale *= rec; xmax *= rec; } } i__3 = j; cladiv_(&q__1, &x[j], &tjjs); x[i__3].r = q__1.r, x[i__3].i = q__1.i; i__3 = j; xj = (r__1 = x[i__3].r, dabs(r__1)) + (r__2 = r_imag(&x[j] ), dabs(r__2)); } else if (tjj > 0.f) { /* 0 < abs(A(j,j)) <= SMLNUM: */ if (xj > tjj * bignum) { /* Scale x by (1/abs(x(j)))*abs(A(j,j))*BIGNUM to avoid overflow when dividing by A(j,j). */ rec = tjj * bignum / xj; if (cnorm[j] > 1.f) { /* Scale by 1/CNORM(j) to avoid overflow when multiplying x(j) times column j. */ rec /= cnorm[j]; } csscal_(n, &rec, &x[1], &c__1); *scale *= rec; xmax *= rec; } i__3 = j; cladiv_(&q__1, &x[j], &tjjs); x[i__3].r = q__1.r, x[i__3].i = q__1.i; i__3 = j; xj = (r__1 = x[i__3].r, dabs(r__1)) + (r__2 = r_imag(&x[j] ), dabs(r__2)); } else { /* A(j,j) = 0: Set x(1:n) = 0, x(j) = 1, and scale = 0, and compute a solution to A*x = 0. */ i__3 = *n; for (i__ = 1; i__ <= i__3; ++i__) { i__4 = i__; x[i__4].r = 0.f, x[i__4].i = 0.f; /* L100: */ } i__3 = j; x[i__3].r = 1.f, x[i__3].i = 0.f; xj = 1.f; *scale = 0.f; xmax = 0.f; } L105: /* Scale x if necessary to avoid overflow when adding a multiple of column j of A. */ if (xj > 1.f) { rec = 1.f / xj; if (cnorm[j] > (bignum - xmax) * rec) { /* Scale x by 1/(2*abs(x(j))). */ rec *= .5f; csscal_(n, &rec, &x[1], &c__1); *scale *= rec; } } else if (xj * cnorm[j] > bignum - xmax) { /* Scale x by 1/2. */ csscal_(n, &c_b2206, &x[1], &c__1); *scale *= .5f; } if (upper) { if (j > 1) { /* Compute the update x(1:j-1) := x(1:j-1) - x(j) * A(1:j-1,j) */ i__3 = j - 1; i__4 = j; q__2.r = -x[i__4].r, q__2.i = -x[i__4].i; q__1.r = tscal * q__2.r, q__1.i = tscal * q__2.i; caxpy_(&i__3, &q__1, &a[j * a_dim1 + 1], &c__1, &x[1], &c__1); i__3 = j - 1; i__ = icamax_(&i__3, &x[1], &c__1); i__3 = i__; xmax = (r__1 = x[i__3].r, dabs(r__1)) + (r__2 = r_imag(&x[i__]), dabs(r__2)); } } else { if (j < *n) { /* Compute the update x(j+1:n) := x(j+1:n) - x(j) * A(j+1:n,j) */ i__3 = *n - j; i__4 = j; q__2.r = -x[i__4].r, q__2.i = -x[i__4].i; q__1.r = tscal * q__2.r, q__1.i = tscal * q__2.i; caxpy_(&i__3, &q__1, &a[j + 1 + j * a_dim1], &c__1, & x[j + 1], &c__1); i__3 = *n - j; i__ = j + icamax_(&i__3, &x[j + 1], &c__1); i__3 = i__; xmax = (r__1 = x[i__3].r, dabs(r__1)) + (r__2 = r_imag(&x[i__]), dabs(r__2)); } } /* L110: */ } } else if (lsame_(trans, "T")) { /* Solve A**T * x = b */ i__2 = jlast; i__1 = jinc; for (j = jfirst; i__1 < 0 ? j >= i__2 : j <= i__2; j += i__1) { /* Compute x(j) = b(j) - sum A(k,j)*x(k). k<>j */ i__3 = j; xj = (r__1 = x[i__3].r, dabs(r__1)) + (r__2 = r_imag(&x[j]), dabs(r__2)); uscal.r = tscal, uscal.i = 0.f; rec = 1.f / dmax(xmax,1.f); if (cnorm[j] > (bignum - xj) * rec) { /* If x(j) could overflow, scale x by 1/(2*XMAX). */ rec *= .5f; if (nounit) { i__3 = j + j * a_dim1; q__1.r = tscal * a[i__3].r, q__1.i = tscal * a[i__3] .i; tjjs.r = q__1.r, tjjs.i = q__1.i; } else { tjjs.r = tscal, tjjs.i = 0.f; } tjj = (r__1 = tjjs.r, dabs(r__1)) + (r__2 = r_imag(&tjjs), dabs(r__2)); if (tjj > 1.f) { /* Divide by A(j,j) when scaling x if A(j,j) > 1. Computing MIN */ r__1 = 1.f, r__2 = rec * tjj; rec = dmin(r__1,r__2); cladiv_(&q__1, &uscal, &tjjs); uscal.r = q__1.r, uscal.i = q__1.i; } if (rec < 1.f) { csscal_(n, &rec, &x[1], &c__1); *scale *= rec; xmax *= rec; } } csumj.r = 0.f, csumj.i = 0.f; if (uscal.r == 1.f && uscal.i == 0.f) { /* If the scaling needed for A in the dot product is 1, call CDOTU to perform the dot product. */ if (upper) { i__3 = j - 1; cdotu_(&q__1, &i__3, &a[j * a_dim1 + 1], &c__1, &x[1], &c__1); csumj.r = q__1.r, csumj.i = q__1.i; } else if (j < *n) { i__3 = *n - j; cdotu_(&q__1, &i__3, &a[j + 1 + j * a_dim1], &c__1, & x[j + 1], &c__1); csumj.r = q__1.r, csumj.i = q__1.i; } } else { /* Otherwise, use in-line code for the dot product. */ if (upper) { i__3 = j - 1; for (i__ = 1; i__ <= i__3; ++i__) { i__4 = i__ + j * a_dim1; q__3.r = a[i__4].r * uscal.r - a[i__4].i * uscal.i, q__3.i = a[i__4].r * uscal.i + a[ i__4].i * uscal.r; i__5 = i__; q__2.r = q__3.r * x[i__5].r - q__3.i * x[i__5].i, q__2.i = q__3.r * x[i__5].i + q__3.i * x[ i__5].r; q__1.r = csumj.r + q__2.r, q__1.i = csumj.i + q__2.i; csumj.r = q__1.r, csumj.i = q__1.i; /* L120: */ } } else if (j < *n) { i__3 = *n; for (i__ = j + 1; i__ <= i__3; ++i__) { i__4 = i__ + j * a_dim1; q__3.r = a[i__4].r * uscal.r - a[i__4].i * uscal.i, q__3.i = a[i__4].r * uscal.i + a[ i__4].i * uscal.r; i__5 = i__; q__2.r = q__3.r * x[i__5].r - q__3.i * x[i__5].i, q__2.i = q__3.r * x[i__5].i + q__3.i * x[ i__5].r; q__1.r = csumj.r + q__2.r, q__1.i = csumj.i + q__2.i; csumj.r = q__1.r, csumj.i = q__1.i; /* L130: */ } } } q__1.r = tscal, q__1.i = 0.f; if (uscal.r == q__1.r && uscal.i == q__1.i) { /* Compute x(j) := ( x(j) - CSUMJ ) / A(j,j) if 1/A(j,j) was not used to scale the dotproduct. */ i__3 = j; i__4 = j; q__1.r = x[i__4].r - csumj.r, q__1.i = x[i__4].i - csumj.i; x[i__3].r = q__1.r, x[i__3].i = q__1.i; i__3 = j; xj = (r__1 = x[i__3].r, dabs(r__1)) + (r__2 = r_imag(&x[j] ), dabs(r__2)); if (nounit) { i__3 = j + j * a_dim1; q__1.r = tscal * a[i__3].r, q__1.i = tscal * a[i__3] .i; tjjs.r = q__1.r, tjjs.i = q__1.i; } else { tjjs.r = tscal, tjjs.i = 0.f; if (tscal == 1.f) { goto L145; } } /* Compute x(j) = x(j) / A(j,j), scaling if necessary. */ tjj = (r__1 = tjjs.r, dabs(r__1)) + (r__2 = r_imag(&tjjs), dabs(r__2)); if (tjj > smlnum) { /* abs(A(j,j)) > SMLNUM: */ if (tjj < 1.f) { if (xj > tjj * bignum) { /* Scale X by 1/abs(x(j)). */ rec = 1.f / xj; csscal_(n, &rec, &x[1], &c__1); *scale *= rec; xmax *= rec; } } i__3 = j; cladiv_(&q__1, &x[j], &tjjs); x[i__3].r = q__1.r, x[i__3].i = q__1.i; } else if (tjj > 0.f) { /* 0 < abs(A(j,j)) <= SMLNUM: */ if (xj > tjj * bignum) { /* Scale x by (1/abs(x(j)))*abs(A(j,j))*BIGNUM. */ rec = tjj * bignum / xj; csscal_(n, &rec, &x[1], &c__1); *scale *= rec; xmax *= rec; } i__3 = j; cladiv_(&q__1, &x[j], &tjjs); x[i__3].r = q__1.r, x[i__3].i = q__1.i; } else { /* A(j,j) = 0: Set x(1:n) = 0, x(j) = 1, and scale = 0 and compute a solution to A**T *x = 0. */ i__3 = *n; for (i__ = 1; i__ <= i__3; ++i__) { i__4 = i__; x[i__4].r = 0.f, x[i__4].i = 0.f; /* L140: */ } i__3 = j; x[i__3].r = 1.f, x[i__3].i = 0.f; *scale = 0.f; xmax = 0.f; } L145: ; } else { /* Compute x(j) := x(j) / A(j,j) - CSUMJ if the dot product has already been divided by 1/A(j,j). */ i__3 = j; cladiv_(&q__2, &x[j], &tjjs); q__1.r = q__2.r - csumj.r, q__1.i = q__2.i - csumj.i; x[i__3].r = q__1.r, x[i__3].i = q__1.i; } /* Computing MAX */ i__3 = j; r__3 = xmax, r__4 = (r__1 = x[i__3].r, dabs(r__1)) + (r__2 = r_imag(&x[j]), dabs(r__2)); xmax = dmax(r__3,r__4); /* L150: */ } } else { /* Solve A**H * x = b */ i__1 = jlast; i__2 = jinc; for (j = jfirst; i__2 < 0 ? j >= i__1 : j <= i__1; j += i__2) { /* Compute x(j) = b(j) - sum A(k,j)*x(k). k<>j */ i__3 = j; xj = (r__1 = x[i__3].r, dabs(r__1)) + (r__2 = r_imag(&x[j]), dabs(r__2)); uscal.r = tscal, uscal.i = 0.f; rec = 1.f / dmax(xmax,1.f); if (cnorm[j] > (bignum - xj) * rec) { /* If x(j) could overflow, scale x by 1/(2*XMAX). */ rec *= .5f; if (nounit) { r_cnjg(&q__2, &a[j + j * a_dim1]); q__1.r = tscal * q__2.r, q__1.i = tscal * q__2.i; tjjs.r = q__1.r, tjjs.i = q__1.i; } else { tjjs.r = tscal, tjjs.i = 0.f; } tjj = (r__1 = tjjs.r, dabs(r__1)) + (r__2 = r_imag(&tjjs), dabs(r__2)); if (tjj > 1.f) { /* Divide by A(j,j) when scaling x if A(j,j) > 1. Computing MIN */ r__1 = 1.f, r__2 = rec * tjj; rec = dmin(r__1,r__2); cladiv_(&q__1, &uscal, &tjjs); uscal.r = q__1.r, uscal.i = q__1.i; } if (rec < 1.f) { csscal_(n, &rec, &x[1], &c__1); *scale *= rec; xmax *= rec; } } csumj.r = 0.f, csumj.i = 0.f; if (uscal.r == 1.f && uscal.i == 0.f) { /* If the scaling needed for A in the dot product is 1, call CDOTC to perform the dot product. */ if (upper) { i__3 = j - 1; cdotc_(&q__1, &i__3, &a[j * a_dim1 + 1], &c__1, &x[1], &c__1); csumj.r = q__1.r, csumj.i = q__1.i; } else if (j < *n) { i__3 = *n - j; cdotc_(&q__1, &i__3, &a[j + 1 + j * a_dim1], &c__1, & x[j + 1], &c__1); csumj.r = q__1.r, csumj.i = q__1.i; } } else { /* Otherwise, use in-line code for the dot product. */ if (upper) { i__3 = j - 1; for (i__ = 1; i__ <= i__3; ++i__) { r_cnjg(&q__4, &a[i__ + j * a_dim1]); q__3.r = q__4.r * uscal.r - q__4.i * uscal.i, q__3.i = q__4.r * uscal.i + q__4.i * uscal.r; i__4 = i__; q__2.r = q__3.r * x[i__4].r - q__3.i * x[i__4].i, q__2.i = q__3.r * x[i__4].i + q__3.i * x[ i__4].r; q__1.r = csumj.r + q__2.r, q__1.i = csumj.i + q__2.i; csumj.r = q__1.r, csumj.i = q__1.i; /* L160: */ } } else if (j < *n) { i__3 = *n; for (i__ = j + 1; i__ <= i__3; ++i__) { r_cnjg(&q__4, &a[i__ + j * a_dim1]); q__3.r = q__4.r * uscal.r - q__4.i * uscal.i, q__3.i = q__4.r * uscal.i + q__4.i * uscal.r; i__4 = i__; q__2.r = q__3.r * x[i__4].r - q__3.i * x[i__4].i, q__2.i = q__3.r * x[i__4].i + q__3.i * x[ i__4].r; q__1.r = csumj.r + q__2.r, q__1.i = csumj.i + q__2.i; csumj.r = q__1.r, csumj.i = q__1.i; /* L170: */ } } } q__1.r = tscal, q__1.i = 0.f; if (uscal.r == q__1.r && uscal.i == q__1.i) { /* Compute x(j) := ( x(j) - CSUMJ ) / A(j,j) if 1/A(j,j) was not used to scale the dotproduct. */ i__3 = j; i__4 = j; q__1.r = x[i__4].r - csumj.r, q__1.i = x[i__4].i - csumj.i; x[i__3].r = q__1.r, x[i__3].i = q__1.i; i__3 = j; xj = (r__1 = x[i__3].r, dabs(r__1)) + (r__2 = r_imag(&x[j] ), dabs(r__2)); if (nounit) { r_cnjg(&q__2, &a[j + j * a_dim1]); q__1.r = tscal * q__2.r, q__1.i = tscal * q__2.i; tjjs.r = q__1.r, tjjs.i = q__1.i; } else { tjjs.r = tscal, tjjs.i = 0.f; if (tscal == 1.f) { goto L185; } } /* Compute x(j) = x(j) / A(j,j), scaling if necessary. */ tjj = (r__1 = tjjs.r, dabs(r__1)) + (r__2 = r_imag(&tjjs), dabs(r__2)); if (tjj > smlnum) { /* abs(A(j,j)) > SMLNUM: */ if (tjj < 1.f) { if (xj > tjj * bignum) { /* Scale X by 1/abs(x(j)). */ rec = 1.f / xj; csscal_(n, &rec, &x[1], &c__1); *scale *= rec; xmax *= rec; } } i__3 = j; cladiv_(&q__1, &x[j], &tjjs); x[i__3].r = q__1.r, x[i__3].i = q__1.i; } else if (tjj > 0.f) { /* 0 < abs(A(j,j)) <= SMLNUM: */ if (xj > tjj * bignum) { /* Scale x by (1/abs(x(j)))*abs(A(j,j))*BIGNUM. */ rec = tjj * bignum / xj; csscal_(n, &rec, &x[1], &c__1); *scale *= rec; xmax *= rec; } i__3 = j; cladiv_(&q__1, &x[j], &tjjs); x[i__3].r = q__1.r, x[i__3].i = q__1.i; } else { /* A(j,j) = 0: Set x(1:n) = 0, x(j) = 1, and scale = 0 and compute a solution to A**H *x = 0. */ i__3 = *n; for (i__ = 1; i__ <= i__3; ++i__) { i__4 = i__; x[i__4].r = 0.f, x[i__4].i = 0.f; /* L180: */ } i__3 = j; x[i__3].r = 1.f, x[i__3].i = 0.f; *scale = 0.f; xmax = 0.f; } L185: ; } else { /* Compute x(j) := x(j) / A(j,j) - CSUMJ if the dot product has already been divided by 1/A(j,j). */ i__3 = j; cladiv_(&q__2, &x[j], &tjjs); q__1.r = q__2.r - csumj.r, q__1.i = q__2.i - csumj.i; x[i__3].r = q__1.r, x[i__3].i = q__1.i; } /* Computing MAX */ i__3 = j; r__3 = xmax, r__4 = (r__1 = x[i__3].r, dabs(r__1)) + (r__2 = r_imag(&x[j]), dabs(r__2)); xmax = dmax(r__3,r__4); /* L190: */ } } *scale /= tscal; } /* Scale the column norms by 1/TSCAL for return. */ if (tscal != 1.f) { r__1 = 1.f / tscal; sscal_(n, &r__1, &cnorm[1], &c__1); } return 0; /* End of CLATRS */ } /* clatrs_ */ /* Subroutine */ int clauu2_(char *uplo, integer *n, complex *a, integer *lda, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3; real r__1; complex q__1; /* Local variables */ static integer i__; static real aii; extern /* Complex */ VOID cdotc_(complex *, integer *, complex *, integer *, complex *, integer *); extern logical lsame_(char *, char *); extern /* Subroutine */ int cgemv_(char *, integer *, integer *, complex * , complex *, integer *, complex *, integer *, complex *, complex * , integer *); static logical upper; extern /* Subroutine */ int clacgv_(integer *, complex *, integer *), csscal_(integer *, real *, complex *, integer *), xerbla_(char *, integer *); /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University September 30, 1994 Purpose ======= CLAUU2 computes the product U * U' or L' * L, where the triangular factor U or L is stored in the upper or lower triangular part of the array A. If UPLO = 'U' or 'u' then the upper triangle of the result is stored, overwriting the factor U in A. If UPLO = 'L' or 'l' then the lower triangle of the result is stored, overwriting the factor L in A. This is the unblocked form of the algorithm, calling Level 2 BLAS. Arguments ========= UPLO (input) CHARACTER*1 Specifies whether the triangular factor stored in the array A is upper or lower triangular: = 'U': Upper triangular = 'L': Lower triangular N (input) INTEGER The order of the triangular factor U or L. N >= 0. A (input/output) COMPLEX array, dimension (LDA,N) On entry, the triangular factor U or L. On exit, if UPLO = 'U', the upper triangle of A is overwritten with the upper triangle of the product U * U'; if UPLO = 'L', the lower triangle of A is overwritten with the lower triangle of the product L' * L. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,N). INFO (output) INTEGER = 0: successful exit < 0: if INFO = -k, the k-th argument had an illegal value ===================================================================== Test the input parameters. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; /* Function Body */ *info = 0; upper = lsame_(uplo, "U"); if (! upper && ! lsame_(uplo, "L")) { *info = -1; } else if (*n < 0) { *info = -2; } else if (*lda < max(1,*n)) { *info = -4; } if (*info != 0) { i__1 = -(*info); xerbla_("CLAUU2", &i__1); return 0; } /* Quick return if possible */ if (*n == 0) { return 0; } if (upper) { /* Compute the product U * U'. */ i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = i__ + i__ * a_dim1; aii = a[i__2].r; if (i__ < *n) { i__2 = i__ + i__ * a_dim1; i__3 = *n - i__; cdotc_(&q__1, &i__3, &a[i__ + (i__ + 1) * a_dim1], lda, &a[ i__ + (i__ + 1) * a_dim1], lda); r__1 = aii * aii + q__1.r; a[i__2].r = r__1, a[i__2].i = 0.f; i__2 = *n - i__; clacgv_(&i__2, &a[i__ + (i__ + 1) * a_dim1], lda); i__2 = i__ - 1; i__3 = *n - i__; q__1.r = aii, q__1.i = 0.f; cgemv_("No transpose", &i__2, &i__3, &c_b56, &a[(i__ + 1) * a_dim1 + 1], lda, &a[i__ + (i__ + 1) * a_dim1], lda, & q__1, &a[i__ * a_dim1 + 1], &c__1); i__2 = *n - i__; clacgv_(&i__2, &a[i__ + (i__ + 1) * a_dim1], lda); } else { csscal_(&i__, &aii, &a[i__ * a_dim1 + 1], &c__1); } /* L10: */ } } else { /* Compute the product L' * L. */ i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = i__ + i__ * a_dim1; aii = a[i__2].r; if (i__ < *n) { i__2 = i__ + i__ * a_dim1; i__3 = *n - i__; cdotc_(&q__1, &i__3, &a[i__ + 1 + i__ * a_dim1], &c__1, &a[ i__ + 1 + i__ * a_dim1], &c__1); r__1 = aii * aii + q__1.r; a[i__2].r = r__1, a[i__2].i = 0.f; i__2 = i__ - 1; clacgv_(&i__2, &a[i__ + a_dim1], lda); i__2 = *n - i__; i__3 = i__ - 1; q__1.r = aii, q__1.i = 0.f; cgemv_("Conjugate transpose", &i__2, &i__3, &c_b56, &a[i__ + 1 + a_dim1], lda, &a[i__ + 1 + i__ * a_dim1], &c__1, & q__1, &a[i__ + a_dim1], lda); i__2 = i__ - 1; clacgv_(&i__2, &a[i__ + a_dim1], lda); } else { csscal_(&i__, &aii, &a[i__ + a_dim1], lda); } /* L20: */ } } return 0; /* End of CLAUU2 */ } /* clauu2_ */ /* Subroutine */ int clauum_(char *uplo, integer *n, complex *a, integer *lda, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3, i__4; /* Local variables */ static integer i__, ib, nb; extern /* Subroutine */ int cgemm_(char *, char *, integer *, integer *, integer *, complex *, complex *, integer *, complex *, integer *, complex *, complex *, integer *), cherk_(char *, char *, integer *, integer *, real *, complex *, integer *, real * , complex *, integer *); extern logical lsame_(char *, char *); extern /* Subroutine */ int ctrmm_(char *, char *, char *, char *, integer *, integer *, complex *, complex *, integer *, complex *, integer *); static logical upper; extern /* Subroutine */ int clauu2_(char *, integer *, complex *, integer *, integer *), xerbla_(char *, integer *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University September 30, 1994 Purpose ======= CLAUUM computes the product U * U' or L' * L, where the triangular factor U or L is stored in the upper or lower triangular part of the array A. If UPLO = 'U' or 'u' then the upper triangle of the result is stored, overwriting the factor U in A. If UPLO = 'L' or 'l' then the lower triangle of the result is stored, overwriting the factor L in A. This is the blocked form of the algorithm, calling Level 3 BLAS. Arguments ========= UPLO (input) CHARACTER*1 Specifies whether the triangular factor stored in the array A is upper or lower triangular: = 'U': Upper triangular = 'L': Lower triangular N (input) INTEGER The order of the triangular factor U or L. N >= 0. A (input/output) COMPLEX array, dimension (LDA,N) On entry, the triangular factor U or L. On exit, if UPLO = 'U', the upper triangle of A is overwritten with the upper triangle of the product U * U'; if UPLO = 'L', the lower triangle of A is overwritten with the lower triangle of the product L' * L. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,N). INFO (output) INTEGER = 0: successful exit < 0: if INFO = -k, the k-th argument had an illegal value ===================================================================== Test the input parameters. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; /* Function Body */ *info = 0; upper = lsame_(uplo, "U"); if (! upper && ! lsame_(uplo, "L")) { *info = -1; } else if (*n < 0) { *info = -2; } else if (*lda < max(1,*n)) { *info = -4; } if (*info != 0) { i__1 = -(*info); xerbla_("CLAUUM", &i__1); return 0; } /* Quick return if possible */ if (*n == 0) { return 0; } /* Determine the block size for this environment. */ nb = ilaenv_(&c__1, "CLAUUM", uplo, n, &c_n1, &c_n1, &c_n1, (ftnlen)6, ( ftnlen)1); if ((nb <= 1) || (nb >= *n)) { /* Use unblocked code */ clauu2_(uplo, n, &a[a_offset], lda, info); } else { /* Use blocked code */ if (upper) { /* Compute the product U * U'. */ i__1 = *n; i__2 = nb; for (i__ = 1; i__2 < 0 ? i__ >= i__1 : i__ <= i__1; i__ += i__2) { /* Computing MIN */ i__3 = nb, i__4 = *n - i__ + 1; ib = min(i__3,i__4); i__3 = i__ - 1; ctrmm_("Right", "Upper", "Conjugate transpose", "Non-unit", & i__3, &ib, &c_b56, &a[i__ + i__ * a_dim1], lda, &a[ i__ * a_dim1 + 1], lda); clauu2_("Upper", &ib, &a[i__ + i__ * a_dim1], lda, info); if (i__ + ib <= *n) { i__3 = i__ - 1; i__4 = *n - i__ - ib + 1; cgemm_("No transpose", "Conjugate transpose", &i__3, &ib, &i__4, &c_b56, &a[(i__ + ib) * a_dim1 + 1], lda, & a[i__ + (i__ + ib) * a_dim1], lda, &c_b56, &a[i__ * a_dim1 + 1], lda); i__3 = *n - i__ - ib + 1; cherk_("Upper", "No transpose", &ib, &i__3, &c_b1011, &a[ i__ + (i__ + ib) * a_dim1], lda, &c_b1011, &a[i__ + i__ * a_dim1], lda); } /* L10: */ } } else { /* Compute the product L' * L. */ i__2 = *n; i__1 = nb; for (i__ = 1; i__1 < 0 ? i__ >= i__2 : i__ <= i__2; i__ += i__1) { /* Computing MIN */ i__3 = nb, i__4 = *n - i__ + 1; ib = min(i__3,i__4); i__3 = i__ - 1; ctrmm_("Left", "Lower", "Conjugate transpose", "Non-unit", & ib, &i__3, &c_b56, &a[i__ + i__ * a_dim1], lda, &a[ i__ + a_dim1], lda); clauu2_("Lower", &ib, &a[i__ + i__ * a_dim1], lda, info); if (i__ + ib <= *n) { i__3 = i__ - 1; i__4 = *n - i__ - ib + 1; cgemm_("Conjugate transpose", "No transpose", &ib, &i__3, &i__4, &c_b56, &a[i__ + ib + i__ * a_dim1], lda, & a[i__ + ib + a_dim1], lda, &c_b56, &a[i__ + a_dim1], lda); i__3 = *n - i__ - ib + 1; cherk_("Lower", "Conjugate transpose", &ib, &i__3, & c_b1011, &a[i__ + ib + i__ * a_dim1], lda, & c_b1011, &a[i__ + i__ * a_dim1], lda); } /* L20: */ } } } return 0; /* End of CLAUUM */ } /* clauum_ */ /* Subroutine */ int cpotf2_(char *uplo, integer *n, complex *a, integer *lda, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3; real r__1; complex q__1, q__2; /* Builtin functions */ double sqrt(doublereal); /* Local variables */ static integer j; static real ajj; extern /* Complex */ VOID cdotc_(complex *, integer *, complex *, integer *, complex *, integer *); extern logical lsame_(char *, char *); extern /* Subroutine */ int cgemv_(char *, integer *, integer *, complex * , complex *, integer *, complex *, integer *, complex *, complex * , integer *); static logical upper; extern /* Subroutine */ int clacgv_(integer *, complex *, integer *), csscal_(integer *, real *, complex *, integer *), xerbla_(char *, integer *); /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University September 30, 1994 Purpose ======= CPOTF2 computes the Cholesky factorization of a complex Hermitian positive definite matrix A. The factorization has the form A = U' * U , if UPLO = 'U', or A = L * L', if UPLO = 'L', where U is an upper triangular matrix and L is lower triangular. This is the unblocked version of the algorithm, calling Level 2 BLAS. Arguments ========= UPLO (input) CHARACTER*1 Specifies whether the upper or lower triangular part of the Hermitian matrix A is stored. = 'U': Upper triangular = 'L': Lower triangular N (input) INTEGER The order of the matrix A. N >= 0. A (input/output) COMPLEX 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, and the strictly lower triangular part of A is not referenced. If UPLO = 'L', the leading n by n lower triangular part of A contains the lower triangular part of the matrix A, and the strictly upper triangular part of A is not referenced. On exit, if INFO = 0, the factor U or L from the Cholesky factorization A = U'*U or A = L*L'. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,N). INFO (output) INTEGER = 0: successful exit < 0: if INFO = -k, the k-th argument had an illegal value > 0: if INFO = k, the leading minor of order k is not positive definite, and the factorization could not be completed. ===================================================================== Test the input parameters. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; /* Function Body */ *info = 0; upper = lsame_(uplo, "U"); if (! upper && ! lsame_(uplo, "L")) { *info = -1; } else if (*n < 0) { *info = -2; } else if (*lda < max(1,*n)) { *info = -4; } if (*info != 0) { i__1 = -(*info); xerbla_("CPOTF2", &i__1); return 0; } /* Quick return if possible */ if (*n == 0) { return 0; } if (upper) { /* Compute the Cholesky factorization A = U'*U. */ i__1 = *n; for (j = 1; j <= i__1; ++j) { /* Compute U(J,J) and test for non-positive-definiteness. */ i__2 = j + j * a_dim1; r__1 = a[i__2].r; i__3 = j - 1; cdotc_(&q__2, &i__3, &a[j * a_dim1 + 1], &c__1, &a[j * a_dim1 + 1] , &c__1); q__1.r = r__1 - q__2.r, q__1.i = -q__2.i; ajj = q__1.r; if (ajj <= 0.f) { i__2 = j + j * a_dim1; a[i__2].r = ajj, a[i__2].i = 0.f; goto L30; } ajj = sqrt(ajj); i__2 = j + j * a_dim1; a[i__2].r = ajj, a[i__2].i = 0.f; /* Compute elements J+1:N of row J. */ if (j < *n) { i__2 = j - 1; clacgv_(&i__2, &a[j * a_dim1 + 1], &c__1); i__2 = j - 1; i__3 = *n - j; q__1.r = -1.f, q__1.i = -0.f; cgemv_("Transpose", &i__2, &i__3, &q__1, &a[(j + 1) * a_dim1 + 1], lda, &a[j * a_dim1 + 1], &c__1, &c_b56, &a[j + ( j + 1) * a_dim1], lda); i__2 = j - 1; clacgv_(&i__2, &a[j * a_dim1 + 1], &c__1); i__2 = *n - j; r__1 = 1.f / ajj; csscal_(&i__2, &r__1, &a[j + (j + 1) * a_dim1], lda); } /* L10: */ } } else { /* Compute the Cholesky factorization A = L*L'. */ i__1 = *n; for (j = 1; j <= i__1; ++j) { /* Compute L(J,J) and test for non-positive-definiteness. */ i__2 = j + j * a_dim1; r__1 = a[i__2].r; i__3 = j - 1; cdotc_(&q__2, &i__3, &a[j + a_dim1], lda, &a[j + a_dim1], lda); q__1.r = r__1 - q__2.r, q__1.i = -q__2.i; ajj = q__1.r; if (ajj <= 0.f) { i__2 = j + j * a_dim1; a[i__2].r = ajj, a[i__2].i = 0.f; goto L30; } ajj = sqrt(ajj); i__2 = j + j * a_dim1; a[i__2].r = ajj, a[i__2].i = 0.f; /* Compute elements J+1:N of column J. */ if (j < *n) { i__2 = j - 1; clacgv_(&i__2, &a[j + a_dim1], lda); i__2 = *n - j; i__3 = j - 1; q__1.r = -1.f, q__1.i = -0.f; cgemv_("No transpose", &i__2, &i__3, &q__1, &a[j + 1 + a_dim1] , lda, &a[j + a_dim1], lda, &c_b56, &a[j + 1 + j * a_dim1], &c__1); i__2 = j - 1; clacgv_(&i__2, &a[j + a_dim1], lda); i__2 = *n - j; r__1 = 1.f / ajj; csscal_(&i__2, &r__1, &a[j + 1 + j * a_dim1], &c__1); } /* L20: */ } } goto L40; L30: *info = j; L40: return 0; /* End of CPOTF2 */ } /* cpotf2_ */ /* Subroutine */ int cpotrf_(char *uplo, integer *n, complex *a, integer *lda, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3, i__4; complex q__1; /* Local variables */ static integer j, jb, nb; extern /* Subroutine */ int cgemm_(char *, char *, integer *, integer *, integer *, complex *, complex *, integer *, complex *, integer *, complex *, complex *, integer *), cherk_(char *, char *, integer *, integer *, real *, complex *, integer *, real * , complex *, integer *); extern logical lsame_(char *, char *); extern /* Subroutine */ int ctrsm_(char *, char *, char *, char *, integer *, integer *, complex *, complex *, integer *, complex *, integer *); static logical upper; extern /* Subroutine */ int cpotf2_(char *, integer *, complex *, integer *, integer *), xerbla_(char *, integer *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University September 30, 1994 Purpose ======= CPOTRF computes the Cholesky factorization of a complex Hermitian positive definite matrix A. The factorization has the form A = U**H * U, if UPLO = 'U', or A = L * L**H, if UPLO = 'L', where U is an upper triangular matrix and L is lower triangular. This is the block version of the algorithm, calling Level 3 BLAS. Arguments ========= UPLO (input) CHARACTER*1 = 'U': Upper triangle of A is stored; = 'L': Lower triangle of A is stored. N (input) INTEGER The order of the matrix A. N >= 0. A (input/output) COMPLEX 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, and the strictly lower triangular part of A is not referenced. If UPLO = 'L', the leading N-by-N lower triangular part of A contains the lower triangular part of the matrix A, and the strictly upper triangular part of A is not referenced. On exit, if INFO = 0, the factor U or L from the Cholesky factorization A = U**H*U or A = L*L**H. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,N). INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value > 0: if INFO = i, the leading minor of order i is not positive definite, and the factorization could not be completed. ===================================================================== Test the input parameters. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; /* Function Body */ *info = 0; upper = lsame_(uplo, "U"); if (! upper && ! lsame_(uplo, "L")) { *info = -1; } else if (*n < 0) { *info = -2; } else if (*lda < max(1,*n)) { *info = -4; } if (*info != 0) { i__1 = -(*info); xerbla_("CPOTRF", &i__1); return 0; } /* Quick return if possible */ if (*n == 0) { return 0; } /* Determine the block size for this environment. */ nb = ilaenv_(&c__1, "CPOTRF", uplo, n, &c_n1, &c_n1, &c_n1, (ftnlen)6, ( ftnlen)1); if ((nb <= 1) || (nb >= *n)) { /* Use unblocked code. */ cpotf2_(uplo, n, &a[a_offset], lda, info); } else { /* Use blocked code. */ if (upper) { /* Compute the Cholesky factorization A = U'*U. */ i__1 = *n; i__2 = nb; for (j = 1; i__2 < 0 ? j >= i__1 : j <= i__1; j += i__2) { /* Update and factorize the current diagonal block and test for non-positive-definiteness. Computing MIN */ i__3 = nb, i__4 = *n - j + 1; jb = min(i__3,i__4); i__3 = j - 1; cherk_("Upper", "Conjugate transpose", &jb, &i__3, &c_b1290, & a[j * a_dim1 + 1], lda, &c_b1011, &a[j + j * a_dim1], lda); cpotf2_("Upper", &jb, &a[j + j * a_dim1], lda, info); if (*info != 0) { goto L30; } if (j + jb <= *n) { /* Compute the current block row. */ i__3 = *n - j - jb + 1; i__4 = j - 1; q__1.r = -1.f, q__1.i = -0.f; cgemm_("Conjugate transpose", "No transpose", &jb, &i__3, &i__4, &q__1, &a[j * a_dim1 + 1], lda, &a[(j + jb) * a_dim1 + 1], lda, &c_b56, &a[j + (j + jb) * a_dim1], lda); i__3 = *n - j - jb + 1; ctrsm_("Left", "Upper", "Conjugate transpose", "Non-unit", &jb, &i__3, &c_b56, &a[j + j * a_dim1], lda, &a[ j + (j + jb) * a_dim1], lda); } /* L10: */ } } else { /* Compute the Cholesky factorization A = L*L'. */ i__2 = *n; i__1 = nb; for (j = 1; i__1 < 0 ? j >= i__2 : j <= i__2; j += i__1) { /* Update and factorize the current diagonal block and test for non-positive-definiteness. Computing MIN */ i__3 = nb, i__4 = *n - j + 1; jb = min(i__3,i__4); i__3 = j - 1; cherk_("Lower", "No transpose", &jb, &i__3, &c_b1290, &a[j + a_dim1], lda, &c_b1011, &a[j + j * a_dim1], lda); cpotf2_("Lower", &jb, &a[j + j * a_dim1], lda, info); if (*info != 0) { goto L30; } if (j + jb <= *n) { /* Compute the current block column. */ i__3 = *n - j - jb + 1; i__4 = j - 1; q__1.r = -1.f, q__1.i = -0.f; cgemm_("No transpose", "Conjugate transpose", &i__3, &jb, &i__4, &q__1, &a[j + jb + a_dim1], lda, &a[j + a_dim1], lda, &c_b56, &a[j + jb + j * a_dim1], lda); i__3 = *n - j - jb + 1; ctrsm_("Right", "Lower", "Conjugate transpose", "Non-unit" , &i__3, &jb, &c_b56, &a[j + j * a_dim1], lda, &a[ j + jb + j * a_dim1], lda); } /* L20: */ } } } goto L40; L30: *info = *info + j - 1; L40: return 0; /* End of CPOTRF */ } /* cpotrf_ */ /* Subroutine */ int cpotri_(char *uplo, integer *n, complex *a, integer *lda, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1; /* Local variables */ extern logical lsame_(char *, char *); extern /* Subroutine */ int xerbla_(char *, integer *), clauum_( char *, integer *, complex *, integer *, integer *), ctrtri_(char *, char *, integer *, complex *, integer *, integer * ); /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University March 31, 1993 Purpose ======= CPOTRI computes the inverse of a complex Hermitian positive definite matrix A using the Cholesky factorization A = U**H*U or A = L*L**H computed by CPOTRF. Arguments ========= UPLO (input) CHARACTER*1 = 'U': Upper triangle of A is stored; = 'L': Lower triangle of A is stored. N (input) INTEGER The order of the matrix A. N >= 0. A (input/output) COMPLEX array, dimension (LDA,N) On entry, the triangular factor U or L from the Cholesky factorization A = U**H*U or A = L*L**H, as computed by CPOTRF. On exit, the upper or lower triangle of the (Hermitian) inverse of A, overwriting the input factor U or L. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,N). INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value > 0: if INFO = i, the (i,i) element of the factor U or L is zero, and the inverse could not be computed. ===================================================================== Test the input parameters. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; /* Function Body */ *info = 0; if (! lsame_(uplo, "U") && ! lsame_(uplo, "L")) { *info = -1; } else if (*n < 0) { *info = -2; } else if (*lda < max(1,*n)) { *info = -4; } if (*info != 0) { i__1 = -(*info); xerbla_("CPOTRI", &i__1); return 0; } /* Quick return if possible */ if (*n == 0) { return 0; } /* Invert the triangular Cholesky factor U or L. */ ctrtri_(uplo, "Non-unit", n, &a[a_offset], lda, info); if (*info > 0) { return 0; } /* Form inv(U)*inv(U)' or inv(L)'*inv(L). */ clauum_(uplo, n, &a[a_offset], lda, info); return 0; /* End of CPOTRI */ } /* cpotri_ */ /* Subroutine */ int cpotrs_(char *uplo, integer *n, integer *nrhs, complex * a, integer *lda, complex *b, integer *ldb, integer *info) { /* System generated locals */ integer a_dim1, a_offset, b_dim1, b_offset, i__1; /* Local variables */ extern logical lsame_(char *, char *); extern /* Subroutine */ int ctrsm_(char *, char *, char *, char *, integer *, integer *, complex *, complex *, integer *, complex *, integer *); static logical upper; extern /* Subroutine */ int xerbla_(char *, integer *); /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University September 30, 1994 Purpose ======= CPOTRS solves a system of linear equations A*X = B with a Hermitian positive definite matrix A using the Cholesky factorization A = U**H*U or A = L*L**H computed by CPOTRF. Arguments ========= UPLO (input) CHARACTER*1 = 'U': Upper triangle of A is stored; = 'L': Lower triangle of A is stored. N (input) INTEGER The order of the matrix A. N >= 0. NRHS (input) INTEGER The number of right hand sides, i.e., the number of columns of the matrix B. NRHS >= 0. A (input) COMPLEX array, dimension (LDA,N) The triangular factor U or L from the Cholesky factorization A = U**H*U or A = L*L**H, as computed by CPOTRF. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,N). B (input/output) COMPLEX array, dimension (LDB,NRHS) On entry, the right hand side matrix B. On exit, the solution matrix X. LDB (input) INTEGER The leading dimension of the array B. LDB >= max(1,N). INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value ===================================================================== Test the input parameters. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; b_dim1 = *ldb; b_offset = 1 + b_dim1; b -= b_offset; /* Function Body */ *info = 0; upper = lsame_(uplo, "U"); if (! upper && ! lsame_(uplo, "L")) { *info = -1; } else if (*n < 0) { *info = -2; } else if (*nrhs < 0) { *info = -3; } else if (*lda < max(1,*n)) { *info = -5; } else if (*ldb < max(1,*n)) { *info = -7; } if (*info != 0) { i__1 = -(*info); xerbla_("CPOTRS", &i__1); return 0; } /* Quick return if possible */ if ((*n == 0) || (*nrhs == 0)) { return 0; } if (upper) { /* Solve A*X = B where A = U'*U. Solve U'*X = B, overwriting B with X. */ ctrsm_("Left", "Upper", "Conjugate transpose", "Non-unit", n, nrhs, & c_b56, &a[a_offset], lda, &b[b_offset], ldb); /* Solve U*X = B, overwriting B with X. */ ctrsm_("Left", "Upper", "No transpose", "Non-unit", n, nrhs, &c_b56, & a[a_offset], lda, &b[b_offset], ldb); } else { /* Solve A*X = B where A = L*L'. Solve L*X = B, overwriting B with X. */ ctrsm_("Left", "Lower", "No transpose", "Non-unit", n, nrhs, &c_b56, & a[a_offset], lda, &b[b_offset], ldb); /* Solve L'*X = B, overwriting B with X. */ ctrsm_("Left", "Lower", "Conjugate transpose", "Non-unit", n, nrhs, & c_b56, &a[a_offset], lda, &b[b_offset], ldb); } return 0; /* End of CPOTRS */ } /* cpotrs_ */ /* Subroutine */ int csrot_(integer *n, complex *cx, integer *incx, complex * cy, integer *incy, real *c__, real *s) { /* System generated locals */ integer i__1, i__2, i__3, i__4; complex q__1, q__2, q__3; /* Local variables */ static integer i__, ix, iy; static complex ctemp; /* applies a plane rotation, where the cos and sin (c and s) are real and the vectors cx and cy are complex. jack dongarra, linpack, 3/11/78. ===================================================================== */ /* Parameter adjustments */ --cy; --cx; /* Function Body */ if (*n <= 0) { return 0; } if (*incx == 1 && *incy == 1) { goto L20; } /* code for unequal increments or equal increments not equal to 1 */ ix = 1; iy = 1; if (*incx < 0) { ix = (-(*n) + 1) * *incx + 1; } if (*incy < 0) { iy = (-(*n) + 1) * *incy + 1; } i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = ix; q__2.r = *c__ * cx[i__2].r, q__2.i = *c__ * cx[i__2].i; i__3 = iy; q__3.r = *s * cy[i__3].r, q__3.i = *s * cy[i__3].i; q__1.r = q__2.r + q__3.r, q__1.i = q__2.i + q__3.i; ctemp.r = q__1.r, ctemp.i = q__1.i; i__2 = iy; i__3 = iy; q__2.r = *c__ * cy[i__3].r, q__2.i = *c__ * cy[i__3].i; i__4 = ix; q__3.r = *s * cx[i__4].r, q__3.i = *s * cx[i__4].i; q__1.r = q__2.r - q__3.r, q__1.i = q__2.i - q__3.i; cy[i__2].r = q__1.r, cy[i__2].i = q__1.i; i__2 = ix; cx[i__2].r = ctemp.r, cx[i__2].i = ctemp.i; ix += *incx; iy += *incy; /* L10: */ } return 0; /* code for both increments equal to 1 */ L20: i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = i__; q__2.r = *c__ * cx[i__2].r, q__2.i = *c__ * cx[i__2].i; i__3 = i__; q__3.r = *s * cy[i__3].r, q__3.i = *s * cy[i__3].i; q__1.r = q__2.r + q__3.r, q__1.i = q__2.i + q__3.i; ctemp.r = q__1.r, ctemp.i = q__1.i; i__2 = i__; i__3 = i__; q__2.r = *c__ * cy[i__3].r, q__2.i = *c__ * cy[i__3].i; i__4 = i__; q__3.r = *s * cx[i__4].r, q__3.i = *s * cx[i__4].i; q__1.r = q__2.r - q__3.r, q__1.i = q__2.i - q__3.i; cy[i__2].r = q__1.r, cy[i__2].i = q__1.i; i__2 = i__; cx[i__2].r = ctemp.r, cx[i__2].i = ctemp.i; /* L30: */ } return 0; } /* csrot_ */ /* Subroutine */ int cstedc_(char *compz, integer *n, real *d__, real *e, complex *z__, integer *ldz, complex *work, integer *lwork, real * rwork, integer *lrwork, integer *iwork, integer *liwork, integer * info) { /* System generated locals */ integer z_dim1, z_offset, i__1, i__2, i__3, i__4; real r__1, r__2; /* Builtin functions */ double log(doublereal); integer pow_ii(integer *, integer *); double sqrt(doublereal); /* Local variables */ static integer i__, j, k, m; static real p; static integer ii, ll, end, lgn; static real eps, tiny; extern logical lsame_(char *, char *); extern /* Subroutine */ int cswap_(integer *, complex *, integer *, complex *, integer *); static integer lwmin; extern /* Subroutine */ int claed0_(integer *, integer *, real *, real *, complex *, integer *, complex *, integer *, real *, integer *, integer *); static integer start; extern /* Subroutine */ int clacrm_(integer *, integer *, complex *, integer *, real *, integer *, complex *, integer *, real *); extern doublereal slamch_(char *); extern /* Subroutine */ int clacpy_(char *, integer *, integer *, complex *, integer *, complex *, integer *), xerbla_(char *, integer *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); extern /* Subroutine */ int slascl_(char *, integer *, integer *, real *, real *, integer *, integer *, real *, integer *, integer *), sstedc_(char *, integer *, real *, real *, real *, integer *, real *, integer *, integer *, integer *, integer *), slaset_(char *, integer *, integer *, real *, real *, real *, integer *); static integer liwmin, icompz; extern /* Subroutine */ int csteqr_(char *, integer *, real *, real *, complex *, integer *, real *, integer *); static real orgnrm; extern doublereal slanst_(char *, integer *, real *, real *); extern /* Subroutine */ int ssterf_(integer *, real *, real *, integer *); static integer lrwmin; static logical lquery; static integer smlsiz; extern /* Subroutine */ int ssteqr_(char *, integer *, real *, real *, real *, integer *, real *, integer *); /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= CSTEDC computes all eigenvalues and, optionally, eigenvectors of a symmetric tridiagonal matrix using the divide and conquer method. The eigenvectors of a full or band complex Hermitian matrix can also be found if CHETRD or CHPTRD or CHBTRD has been used to reduce this matrix to tridiagonal form. This code makes very mild assumptions about floating point arithmetic. It will work on machines with a guard digit in add/subtract, or on those binary machines without guard digits which subtract like the Cray X-MP, Cray Y-MP, Cray C-90, or Cray-2. It could conceivably fail on hexadecimal or decimal machines without guard digits, but we know of none. See SLAED3 for details. Arguments ========= COMPZ (input) CHARACTER*1 = 'N': Compute eigenvalues only. = 'I': Compute eigenvectors of tridiagonal matrix also. = 'V': Compute eigenvectors of original Hermitian matrix also. On entry, Z contains the unitary matrix used to reduce the original matrix to tridiagonal form. N (input) INTEGER The dimension of the symmetric tridiagonal matrix. N >= 0. D (input/output) REAL array, dimension (N) On entry, the diagonal elements of the tridiagonal matrix. On exit, if INFO = 0, the eigenvalues in ascending order. E (input/output) REAL array, dimension (N-1) On entry, the subdiagonal elements of the tridiagonal matrix. On exit, E has been destroyed. Z (input/output) COMPLEX array, dimension (LDZ,N) On entry, if COMPZ = 'V', then Z contains the unitary matrix used in the reduction to tridiagonal form. On exit, if INFO = 0, then if COMPZ = 'V', Z contains the orthonormal eigenvectors of the original Hermitian matrix, and if COMPZ = 'I', Z contains the orthonormal eigenvectors of the symmetric tridiagonal matrix. If COMPZ = 'N', then Z is not referenced. LDZ (input) INTEGER The leading dimension of the array Z. LDZ >= 1. If eigenvectors are desired, then LDZ >= max(1,N). WORK (workspace/output) COMPLEX array, dimension (LWORK) On exit, if INFO = 0, WORK(1) returns the optimal LWORK. LWORK (input) INTEGER The dimension of the array WORK. If COMPZ = 'N' or 'I', or N <= 1, LWORK must be at least 1. If COMPZ = 'V' and N > 1, LWORK must be at least N*N. If LWORK = -1, then a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued by XERBLA. RWORK (workspace/output) REAL array, dimension (LRWORK) On exit, if INFO = 0, RWORK(1) returns the optimal LRWORK. LRWORK (input) INTEGER The dimension of the array RWORK. If COMPZ = 'N' or N <= 1, LRWORK must be at least 1. If COMPZ = 'V' and N > 1, LRWORK must be at least 1 + 3*N + 2*N*lg N + 3*N**2 , where lg( N ) = smallest integer k such that 2**k >= N. If COMPZ = 'I' and N > 1, LRWORK must be at least 1 + 4*N + 2*N**2 . If LRWORK = -1, then a workspace query is assumed; the routine only calculates the optimal size of the RWORK array, returns this value as the first entry of the RWORK array, and no error message related to LRWORK is issued by XERBLA. IWORK (workspace/output) INTEGER array, dimension (LIWORK) On exit, if INFO = 0, IWORK(1) returns the optimal LIWORK. LIWORK (input) INTEGER The dimension of the array IWORK. If COMPZ = 'N' or N <= 1, LIWORK must be at least 1. If COMPZ = 'V' or N > 1, LIWORK must be at least 6 + 6*N + 5*N*lg N. If COMPZ = 'I' or N > 1, LIWORK must be at least 3 + 5*N . If LIWORK = -1, then a workspace query is assumed; the routine only calculates the optimal size of the IWORK array, returns this value as the first entry of the IWORK array, and no error message related to LIWORK is issued by XERBLA. INFO (output) INTEGER = 0: successful exit. < 0: if INFO = -i, the i-th argument had an illegal value. > 0: The algorithm failed to compute an eigenvalue while working on the submatrix lying in rows and columns INFO/(N+1) through mod(INFO,N+1). Further Details =============== Based on contributions by Jeff Rutter, Computer Science Division, University of California at Berkeley, USA ===================================================================== Test the input parameters. */ /* Parameter adjustments */ --d__; --e; z_dim1 = *ldz; z_offset = 1 + z_dim1; z__ -= z_offset; --work; --rwork; --iwork; /* Function Body */ *info = 0; lquery = ((*lwork == -1) || (*lrwork == -1)) || (*liwork == -1); if (lsame_(compz, "N")) { icompz = 0; } else if (lsame_(compz, "V")) { icompz = 1; } else if (lsame_(compz, "I")) { icompz = 2; } else { icompz = -1; } if ((*n <= 1) || (icompz <= 0)) { lwmin = 1; liwmin = 1; lrwmin = 1; } else { lgn = (integer) (log((real) (*n)) / log(2.f)); if (pow_ii(&c__2, &lgn) < *n) { ++lgn; } if (pow_ii(&c__2, &lgn) < *n) { ++lgn; } if (icompz == 1) { lwmin = *n * *n; /* Computing 2nd power */ i__1 = *n; lrwmin = *n * 3 + 1 + ((*n) << (1)) * lgn + i__1 * i__1 * 3; liwmin = *n * 6 + 6 + *n * 5 * lgn; } else if (icompz == 2) { lwmin = 1; /* Computing 2nd power */ i__1 = *n; lrwmin = ((*n) << (2)) + 1 + ((i__1 * i__1) << (1)); liwmin = *n * 5 + 3; } } if (icompz < 0) { *info = -1; } else if (*n < 0) { *info = -2; } else if ((*ldz < 1) || (icompz > 0 && *ldz < max(1,*n))) { *info = -6; } else if (*lwork < lwmin && ! lquery) { *info = -8; } else if (*lrwork < lrwmin && ! lquery) { *info = -10; } else if (*liwork < liwmin && ! lquery) { *info = -12; } if (*info == 0) { work[1].r = (real) lwmin, work[1].i = 0.f; rwork[1] = (real) lrwmin; iwork[1] = liwmin; } if (*info != 0) { i__1 = -(*info); xerbla_("CSTEDC", &i__1); return 0; } else if (lquery) { return 0; } /* Quick return if possible */ if (*n == 0) { return 0; } if (*n == 1) { if (icompz != 0) { i__1 = z_dim1 + 1; z__[i__1].r = 1.f, z__[i__1].i = 0.f; } return 0; } smlsiz = ilaenv_(&c__9, "CSTEDC", " ", &c__0, &c__0, &c__0, &c__0, ( ftnlen)6, (ftnlen)1); /* If the following conditional clause is removed, then the routine will use the Divide and Conquer routine to compute only the eigenvalues, which requires (3N + 3N**2) real workspace and (2 + 5N + 2N lg(N)) integer workspace. Since on many architectures SSTERF is much faster than any other algorithm for finding eigenvalues only, it is used here as the default. If COMPZ = 'N', use SSTERF to compute the eigenvalues. */ if (icompz == 0) { ssterf_(n, &d__[1], &e[1], info); return 0; } /* If N is smaller than the minimum divide size (SMLSIZ+1), then solve the problem with another solver. */ if (*n <= smlsiz) { if (icompz == 0) { ssterf_(n, &d__[1], &e[1], info); return 0; } else if (icompz == 2) { csteqr_("I", n, &d__[1], &e[1], &z__[z_offset], ldz, &rwork[1], info); return 0; } else { csteqr_("V", n, &d__[1], &e[1], &z__[z_offset], ldz, &rwork[1], info); return 0; } } /* If COMPZ = 'I', we simply call SSTEDC instead. */ if (icompz == 2) { slaset_("Full", n, n, &c_b320, &c_b1011, &rwork[1], n); ll = *n * *n + 1; i__1 = *lrwork - ll + 1; sstedc_("I", n, &d__[1], &e[1], &rwork[1], n, &rwork[ll], &i__1, & iwork[1], liwork, info); i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *n; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * z_dim1; i__4 = (j - 1) * *n + i__; z__[i__3].r = rwork[i__4], z__[i__3].i = 0.f; /* L10: */ } /* L20: */ } return 0; } /* From now on, only option left to be handled is COMPZ = 'V', i.e. ICOMPZ = 1. Scale. */ orgnrm = slanst_("M", n, &d__[1], &e[1]); if (orgnrm == 0.f) { return 0; } eps = slamch_("Epsilon"); start = 1; /* while ( START <= N ) */ L30: if (start <= *n) { /* Let END be the position of the next subdiagonal entry such that E( END ) <= TINY or END = N if no such subdiagonal exists. The matrix identified by the elements between START and END constitutes an independent sub-problem. */ end = start; L40: if (end < *n) { tiny = eps * sqrt((r__1 = d__[end], dabs(r__1))) * sqrt((r__2 = d__[end + 1], dabs(r__2))); if ((r__1 = e[end], dabs(r__1)) > tiny) { ++end; goto L40; } } /* (Sub) Problem determined. Compute its size and solve it. */ m = end - start + 1; if (m > smlsiz) { *info = smlsiz; /* Scale. */ orgnrm = slanst_("M", &m, &d__[start], &e[start]); slascl_("G", &c__0, &c__0, &orgnrm, &c_b1011, &m, &c__1, &d__[ start], &m, info); i__1 = m - 1; i__2 = m - 1; slascl_("G", &c__0, &c__0, &orgnrm, &c_b1011, &i__1, &c__1, &e[ start], &i__2, info); claed0_(n, &m, &d__[start], &e[start], &z__[start * z_dim1 + 1], ldz, &work[1], n, &rwork[1], &iwork[1], info); if (*info > 0) { *info = (*info / (m + 1) + start - 1) * (*n + 1) + *info % (m + 1) + start - 1; return 0; } /* Scale back. */ slascl_("G", &c__0, &c__0, &c_b1011, &orgnrm, &m, &c__1, &d__[ start], &m, info); } else { ssteqr_("I", &m, &d__[start], &e[start], &rwork[1], &m, &rwork[m * m + 1], info); clacrm_(n, &m, &z__[start * z_dim1 + 1], ldz, &rwork[1], &m, & work[1], n, &rwork[m * m + 1]); clacpy_("A", n, &m, &work[1], n, &z__[start * z_dim1 + 1], ldz); if (*info > 0) { *info = start * (*n + 1) + end; return 0; } } start = end + 1; goto L30; } /* endwhile If the problem split any number of times, then the eigenvalues will not be properly ordered. Here we permute the eigenvalues (and the associated eigenvectors) into ascending order. */ if (m != *n) { /* Use Selection Sort to minimize swaps of eigenvectors */ i__1 = *n; for (ii = 2; ii <= i__1; ++ii) { i__ = ii - 1; k = i__; p = d__[i__]; i__2 = *n; for (j = ii; j <= i__2; ++j) { if (d__[j] < p) { k = j; p = d__[j]; } /* L50: */ } if (k != i__) { d__[k] = d__[i__]; d__[i__] = p; cswap_(n, &z__[i__ * z_dim1 + 1], &c__1, &z__[k * z_dim1 + 1], &c__1); } /* L60: */ } } work[1].r = (real) lwmin, work[1].i = 0.f; rwork[1] = (real) lrwmin; iwork[1] = liwmin; return 0; /* End of CSTEDC */ } /* cstedc_ */ /* Subroutine */ int csteqr_(char *compz, integer *n, real *d__, real *e, complex *z__, integer *ldz, real *work, integer *info) { /* System generated locals */ integer z_dim1, z_offset, i__1, i__2; real r__1, r__2; /* Builtin functions */ double sqrt(doublereal), r_sign(real *, real *); /* Local variables */ static real b, c__, f, g; static integer i__, j, k, l, m; static real p, r__, s; static integer l1, ii, mm, lm1, mm1, nm1; static real rt1, rt2, eps; static integer lsv; static real tst, eps2; static integer lend, jtot; extern /* Subroutine */ int slae2_(real *, real *, real *, real *, real *) ; extern logical lsame_(char *, char *); extern /* Subroutine */ int clasr_(char *, char *, char *, integer *, integer *, real *, real *, complex *, integer *); static real anorm; extern /* Subroutine */ int cswap_(integer *, complex *, integer *, complex *, integer *); static integer lendm1, lendp1; extern /* Subroutine */ int slaev2_(real *, real *, real *, real *, real * , real *, real *); extern doublereal slapy2_(real *, real *); static integer iscale; extern doublereal slamch_(char *); extern /* Subroutine */ int claset_(char *, integer *, integer *, complex *, complex *, complex *, integer *); static real safmin; extern /* Subroutine */ int xerbla_(char *, integer *); static real safmax; extern /* Subroutine */ int slascl_(char *, integer *, integer *, real *, real *, integer *, integer *, real *, integer *, integer *); static integer lendsv; extern /* Subroutine */ int slartg_(real *, real *, real *, real *, real * ); static real ssfmin; static integer nmaxit, icompz; static real ssfmax; extern doublereal slanst_(char *, integer *, real *, real *); extern /* Subroutine */ int slasrt_(char *, integer *, real *, integer *); /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University September 30, 1994 Purpose ======= CSTEQR computes all eigenvalues and, optionally, eigenvectors of a symmetric tridiagonal matrix using the implicit QL or QR method. The eigenvectors of a full or band complex Hermitian matrix can also be found if CHETRD or CHPTRD or CHBTRD has been used to reduce this matrix to tridiagonal form. Arguments ========= COMPZ (input) CHARACTER*1 = 'N': Compute eigenvalues only. = 'V': Compute eigenvalues and eigenvectors of the original Hermitian matrix. On entry, Z must contain the unitary matrix used to reduce the original matrix to tridiagonal form. = 'I': Compute eigenvalues and eigenvectors of the tridiagonal matrix. Z is initialized to the identity matrix. N (input) INTEGER The order of the matrix. N >= 0. D (input/output) REAL array, dimension (N) On entry, the diagonal elements of the tridiagonal matrix. On exit, if INFO = 0, the eigenvalues in ascending order. E (input/output) REAL array, dimension (N-1) On entry, the (n-1) subdiagonal elements of the tridiagonal matrix. On exit, E has been destroyed. Z (input/output) COMPLEX array, dimension (LDZ, N) On entry, if COMPZ = 'V', then Z contains the unitary matrix used in the reduction to tridiagonal form. On exit, if INFO = 0, then if COMPZ = 'V', Z contains the orthonormal eigenvectors of the original Hermitian matrix, and if COMPZ = 'I', Z contains the orthonormal eigenvectors of the symmetric tridiagonal matrix. If COMPZ = 'N', then Z is not referenced. LDZ (input) INTEGER The leading dimension of the array Z. LDZ >= 1, and if eigenvectors are desired, then LDZ >= max(1,N). WORK (workspace) REAL array, dimension (max(1,2*N-2)) If COMPZ = 'N', then WORK is not referenced. INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value > 0: the algorithm has failed to find all the eigenvalues in a total of 30*N iterations; if INFO = i, then i elements of E have not converged to zero; on exit, D and E contain the elements of a symmetric tridiagonal matrix which is unitarily similar to the original matrix. ===================================================================== Test the input parameters. */ /* Parameter adjustments */ --d__; --e; z_dim1 = *ldz; z_offset = 1 + z_dim1; z__ -= z_offset; --work; /* Function Body */ *info = 0; if (lsame_(compz, "N")) { icompz = 0; } else if (lsame_(compz, "V")) { icompz = 1; } else if (lsame_(compz, "I")) { icompz = 2; } else { icompz = -1; } if (icompz < 0) { *info = -1; } else if (*n < 0) { *info = -2; } else if ((*ldz < 1) || (icompz > 0 && *ldz < max(1,*n))) { *info = -6; } if (*info != 0) { i__1 = -(*info); xerbla_("CSTEQR", &i__1); return 0; } /* Quick return if possible */ if (*n == 0) { return 0; } if (*n == 1) { if (icompz == 2) { i__1 = z_dim1 + 1; z__[i__1].r = 1.f, z__[i__1].i = 0.f; } return 0; } /* Determine the unit roundoff and over/underflow thresholds. */ eps = slamch_("E"); /* Computing 2nd power */ r__1 = eps; eps2 = r__1 * r__1; safmin = slamch_("S"); safmax = 1.f / safmin; ssfmax = sqrt(safmax) / 3.f; ssfmin = sqrt(safmin) / eps2; /* Compute the eigenvalues and eigenvectors of the tridiagonal matrix. */ if (icompz == 2) { claset_("Full", n, n, &c_b55, &c_b56, &z__[z_offset], ldz); } nmaxit = *n * 30; jtot = 0; /* Determine where the matrix splits and choose QL or QR iteration for each block, according to whether top or bottom diagonal element is smaller. */ l1 = 1; nm1 = *n - 1; L10: if (l1 > *n) { goto L160; } if (l1 > 1) { e[l1 - 1] = 0.f; } if (l1 <= nm1) { i__1 = nm1; for (m = l1; m <= i__1; ++m) { tst = (r__1 = e[m], dabs(r__1)); if (tst == 0.f) { goto L30; } if (tst <= sqrt((r__1 = d__[m], dabs(r__1))) * sqrt((r__2 = d__[m + 1], dabs(r__2))) * eps) { e[m] = 0.f; goto L30; } /* L20: */ } } m = *n; L30: l = l1; lsv = l; lend = m; lendsv = lend; l1 = m + 1; if (lend == l) { goto L10; } /* Scale submatrix in rows and columns L to LEND */ i__1 = lend - l + 1; anorm = slanst_("I", &i__1, &d__[l], &e[l]); iscale = 0; if (anorm == 0.f) { goto L10; } if (anorm > ssfmax) { iscale = 1; i__1 = lend - l + 1; slascl_("G", &c__0, &c__0, &anorm, &ssfmax, &i__1, &c__1, &d__[l], n, info); i__1 = lend - l; slascl_("G", &c__0, &c__0, &anorm, &ssfmax, &i__1, &c__1, &e[l], n, info); } else if (anorm < ssfmin) { iscale = 2; i__1 = lend - l + 1; slascl_("G", &c__0, &c__0, &anorm, &ssfmin, &i__1, &c__1, &d__[l], n, info); i__1 = lend - l; slascl_("G", &c__0, &c__0, &anorm, &ssfmin, &i__1, &c__1, &e[l], n, info); } /* Choose between QL and QR iteration */ if ((r__1 = d__[lend], dabs(r__1)) < (r__2 = d__[l], dabs(r__2))) { lend = lsv; l = lendsv; } if (lend > l) { /* QL Iteration Look for small subdiagonal element. */ L40: if (l != lend) { lendm1 = lend - 1; i__1 = lendm1; for (m = l; m <= i__1; ++m) { /* Computing 2nd power */ r__2 = (r__1 = e[m], dabs(r__1)); tst = r__2 * r__2; if (tst <= eps2 * (r__1 = d__[m], dabs(r__1)) * (r__2 = d__[m + 1], dabs(r__2)) + safmin) { goto L60; } /* L50: */ } } m = lend; L60: if (m < lend) { e[m] = 0.f; } p = d__[l]; if (m == l) { goto L80; } /* If remaining matrix is 2-by-2, use SLAE2 or SLAEV2 to compute its eigensystem. */ if (m == l + 1) { if (icompz > 0) { slaev2_(&d__[l], &e[l], &d__[l + 1], &rt1, &rt2, &c__, &s); work[l] = c__; work[*n - 1 + l] = s; clasr_("R", "V", "B", n, &c__2, &work[l], &work[*n - 1 + l], & z__[l * z_dim1 + 1], ldz); } else { slae2_(&d__[l], &e[l], &d__[l + 1], &rt1, &rt2); } d__[l] = rt1; d__[l + 1] = rt2; e[l] = 0.f; l += 2; if (l <= lend) { goto L40; } goto L140; } if (jtot == nmaxit) { goto L140; } ++jtot; /* Form shift. */ g = (d__[l + 1] - p) / (e[l] * 2.f); r__ = slapy2_(&g, &c_b1011); g = d__[m] - p + e[l] / (g + r_sign(&r__, &g)); s = 1.f; c__ = 1.f; p = 0.f; /* Inner loop */ mm1 = m - 1; i__1 = l; for (i__ = mm1; i__ >= i__1; --i__) { f = s * e[i__]; b = c__ * e[i__]; slartg_(&g, &f, &c__, &s, &r__); if (i__ != m - 1) { e[i__ + 1] = r__; } g = d__[i__ + 1] - p; r__ = (d__[i__] - g) * s + c__ * 2.f * b; p = s * r__; d__[i__ + 1] = g + p; g = c__ * r__ - b; /* If eigenvectors are desired, then save rotations. */ if (icompz > 0) { work[i__] = c__; work[*n - 1 + i__] = -s; } /* L70: */ } /* If eigenvectors are desired, then apply saved rotations. */ if (icompz > 0) { mm = m - l + 1; clasr_("R", "V", "B", n, &mm, &work[l], &work[*n - 1 + l], &z__[l * z_dim1 + 1], ldz); } d__[l] -= p; e[l] = g; goto L40; /* Eigenvalue found. */ L80: d__[l] = p; ++l; if (l <= lend) { goto L40; } goto L140; } else { /* QR Iteration Look for small superdiagonal element. */ L90: if (l != lend) { lendp1 = lend + 1; i__1 = lendp1; for (m = l; m >= i__1; --m) { /* Computing 2nd power */ r__2 = (r__1 = e[m - 1], dabs(r__1)); tst = r__2 * r__2; if (tst <= eps2 * (r__1 = d__[m], dabs(r__1)) * (r__2 = d__[m - 1], dabs(r__2)) + safmin) { goto L110; } /* L100: */ } } m = lend; L110: if (m > lend) { e[m - 1] = 0.f; } p = d__[l]; if (m == l) { goto L130; } /* If remaining matrix is 2-by-2, use SLAE2 or SLAEV2 to compute its eigensystem. */ if (m == l - 1) { if (icompz > 0) { slaev2_(&d__[l - 1], &e[l - 1], &d__[l], &rt1, &rt2, &c__, &s) ; work[m] = c__; work[*n - 1 + m] = s; clasr_("R", "V", "F", n, &c__2, &work[m], &work[*n - 1 + m], & z__[(l - 1) * z_dim1 + 1], ldz); } else { slae2_(&d__[l - 1], &e[l - 1], &d__[l], &rt1, &rt2); } d__[l - 1] = rt1; d__[l] = rt2; e[l - 1] = 0.f; l += -2; if (l >= lend) { goto L90; } goto L140; } if (jtot == nmaxit) { goto L140; } ++jtot; /* Form shift. */ g = (d__[l - 1] - p) / (e[l - 1] * 2.f); r__ = slapy2_(&g, &c_b1011); g = d__[m] - p + e[l - 1] / (g + r_sign(&r__, &g)); s = 1.f; c__ = 1.f; p = 0.f; /* Inner loop */ lm1 = l - 1; i__1 = lm1; for (i__ = m; i__ <= i__1; ++i__) { f = s * e[i__]; b = c__ * e[i__]; slartg_(&g, &f, &c__, &s, &r__); if (i__ != m) { e[i__ - 1] = r__; } g = d__[i__] - p; r__ = (d__[i__ + 1] - g) * s + c__ * 2.f * b; p = s * r__; d__[i__] = g + p; g = c__ * r__ - b; /* If eigenvectors are desired, then save rotations. */ if (icompz > 0) { work[i__] = c__; work[*n - 1 + i__] = s; } /* L120: */ } /* If eigenvectors are desired, then apply saved rotations. */ if (icompz > 0) { mm = l - m + 1; clasr_("R", "V", "F", n, &mm, &work[m], &work[*n - 1 + m], &z__[m * z_dim1 + 1], ldz); } d__[l] -= p; e[lm1] = g; goto L90; /* Eigenvalue found. */ L130: d__[l] = p; --l; if (l >= lend) { goto L90; } goto L140; } /* Undo scaling if necessary */ L140: if (iscale == 1) { i__1 = lendsv - lsv + 1; slascl_("G", &c__0, &c__0, &ssfmax, &anorm, &i__1, &c__1, &d__[lsv], n, info); i__1 = lendsv - lsv; slascl_("G", &c__0, &c__0, &ssfmax, &anorm, &i__1, &c__1, &e[lsv], n, info); } else if (iscale == 2) { i__1 = lendsv - lsv + 1; slascl_("G", &c__0, &c__0, &ssfmin, &anorm, &i__1, &c__1, &d__[lsv], n, info); i__1 = lendsv - lsv; slascl_("G", &c__0, &c__0, &ssfmin, &anorm, &i__1, &c__1, &e[lsv], n, info); } /* Check for no convergence to an eigenvalue after a total of N*MAXIT iterations. */ if (jtot == nmaxit) { i__1 = *n - 1; for (i__ = 1; i__ <= i__1; ++i__) { if (e[i__] != 0.f) { ++(*info); } /* L150: */ } return 0; } goto L10; /* Order eigenvalues and eigenvectors. */ L160: if (icompz == 0) { /* Use Quick Sort */ slasrt_("I", n, &d__[1], info); } else { /* Use Selection Sort to minimize swaps of eigenvectors */ i__1 = *n; for (ii = 2; ii <= i__1; ++ii) { i__ = ii - 1; k = i__; p = d__[i__]; i__2 = *n; for (j = ii; j <= i__2; ++j) { if (d__[j] < p) { k = j; p = d__[j]; } /* L170: */ } if (k != i__) { d__[k] = d__[i__]; d__[i__] = p; cswap_(n, &z__[i__ * z_dim1 + 1], &c__1, &z__[k * z_dim1 + 1], &c__1); } /* L180: */ } } return 0; /* End of CSTEQR */ } /* csteqr_ */ /* Subroutine */ int ctrevc_(char *side, char *howmny, logical *select, integer *n, complex *t, integer *ldt, complex *vl, integer *ldvl, complex *vr, integer *ldvr, integer *mm, integer *m, complex *work, real *rwork, integer *info) { /* System generated locals */ integer t_dim1, t_offset, vl_dim1, vl_offset, vr_dim1, vr_offset, i__1, i__2, i__3, i__4, i__5; real r__1, r__2, r__3; complex q__1, q__2; /* Builtin functions */ double r_imag(complex *); void r_cnjg(complex *, complex *); /* Local variables */ static integer i__, j, k, ii, ki, is; static real ulp; static logical allv; static real unfl, ovfl, smin; static logical over; static real scale; extern logical lsame_(char *, char *); extern /* Subroutine */ int cgemv_(char *, integer *, integer *, complex * , complex *, integer *, complex *, integer *, complex *, complex * , integer *); static real remax; extern /* Subroutine */ int ccopy_(integer *, complex *, integer *, complex *, integer *); static logical leftv, bothv, somev; extern /* Subroutine */ int slabad_(real *, real *); extern integer icamax_(integer *, complex *, integer *); extern doublereal slamch_(char *); extern /* Subroutine */ int csscal_(integer *, real *, complex *, integer *), xerbla_(char *, integer *), clatrs_(char *, char *, char *, char *, integer *, complex *, integer *, complex *, real * , real *, integer *); extern doublereal scasum_(integer *, complex *, integer *); static logical rightv; static real smlnum; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= CTREVC computes some or all of the right and/or left eigenvectors of a complex upper triangular matrix T. The right eigenvector x and the left eigenvector y of T corresponding to an eigenvalue w are defined by: T*x = w*x, y'*T = w*y' where y' denotes the conjugate transpose of the vector y. If all eigenvectors are requested, the routine may either return the matrices X and/or Y of right or left eigenvectors of T, or the products Q*X and/or Q*Y, where Q is an input unitary matrix. If T was obtained from the Schur factorization of an original matrix A = Q*T*Q', then Q*X and Q*Y are the matrices of right or left eigenvectors of A. Arguments ========= SIDE (input) CHARACTER*1 = 'R': compute right eigenvectors only; = 'L': compute left eigenvectors only; = 'B': compute both right and left eigenvectors. HOWMNY (input) CHARACTER*1 = 'A': compute all right and/or left eigenvectors; = 'B': compute all right and/or left eigenvectors, and backtransform them using the input matrices supplied in VR and/or VL; = 'S': compute selected right and/or left eigenvectors, specified by the logical array SELECT. SELECT (input) LOGICAL array, dimension (N) If HOWMNY = 'S', SELECT specifies the eigenvectors to be computed. If HOWMNY = 'A' or 'B', SELECT is not referenced. To select the eigenvector corresponding to the j-th eigenvalue, SELECT(j) must be set to .TRUE.. N (input) INTEGER The order of the matrix T. N >= 0. T (input/output) COMPLEX array, dimension (LDT,N) The upper triangular matrix T. T is modified, but restored on exit. LDT (input) INTEGER The leading dimension of the array T. LDT >= max(1,N). VL (input/output) COMPLEX array, dimension (LDVL,MM) On entry, if SIDE = 'L' or 'B' and HOWMNY = 'B', VL must contain an N-by-N matrix Q (usually the unitary matrix Q of Schur vectors returned by CHSEQR). On exit, if SIDE = 'L' or 'B', VL contains: if HOWMNY = 'A', the matrix Y of left eigenvectors of T; VL is lower triangular. The i-th column VL(i) of VL is the eigenvector corresponding to T(i,i). if HOWMNY = 'B', the matrix Q*Y; if HOWMNY = 'S', the left eigenvectors of T specified by SELECT, stored consecutively in the columns of VL, in the same order as their eigenvalues. If SIDE = 'R', VL is not referenced. LDVL (input) INTEGER The leading dimension of the array VL. LDVL >= max(1,N) if SIDE = 'L' or 'B'; LDVL >= 1 otherwise. VR (input/output) COMPLEX array, dimension (LDVR,MM) On entry, if SIDE = 'R' or 'B' and HOWMNY = 'B', VR must contain an N-by-N matrix Q (usually the unitary matrix Q of Schur vectors returned by CHSEQR). On exit, if SIDE = 'R' or 'B', VR contains: if HOWMNY = 'A', the matrix X of right eigenvectors of T; VR is upper triangular. The i-th column VR(i) of VR is the eigenvector corresponding to T(i,i). if HOWMNY = 'B', the matrix Q*X; if HOWMNY = 'S', the right eigenvectors of T specified by SELECT, stored consecutively in the columns of VR, in the same order as their eigenvalues. If SIDE = 'L', VR is not referenced. LDVR (input) INTEGER The leading dimension of the array VR. LDVR >= max(1,N) if SIDE = 'R' or 'B'; LDVR >= 1 otherwise. MM (input) INTEGER The number of columns in the arrays VL and/or VR. MM >= M. M (output) INTEGER The number of columns in the arrays VL and/or VR actually used to store the eigenvectors. If HOWMNY = 'A' or 'B', M is set to N. Each selected eigenvector occupies one column. WORK (workspace) COMPLEX array, dimension (2*N) RWORK (workspace) REAL array, dimension (N) INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value Further Details =============== The algorithm used in this program is basically backward (forward) substitution, with scaling to make the the code robust against possible overflow. Each eigenvector is normalized so that the element of largest magnitude has magnitude 1; here the magnitude of a complex number (x,y) is taken to be |x| + |y|. ===================================================================== Decode and test the input parameters */ /* Parameter adjustments */ --select; t_dim1 = *ldt; t_offset = 1 + t_dim1; t -= t_offset; vl_dim1 = *ldvl; vl_offset = 1 + vl_dim1; vl -= vl_offset; vr_dim1 = *ldvr; vr_offset = 1 + vr_dim1; vr -= vr_offset; --work; --rwork; /* Function Body */ bothv = lsame_(side, "B"); rightv = (lsame_(side, "R")) || (bothv); leftv = (lsame_(side, "L")) || (bothv); allv = lsame_(howmny, "A"); over = lsame_(howmny, "B"); somev = lsame_(howmny, "S"); /* Set M to the number of columns required to store the selected eigenvectors. */ if (somev) { *m = 0; i__1 = *n; for (j = 1; j <= i__1; ++j) { if (select[j]) { ++(*m); } /* L10: */ } } else { *m = *n; } *info = 0; if (! rightv && ! leftv) { *info = -1; } else if (! allv && ! over && ! somev) { *info = -2; } else if (*n < 0) { *info = -4; } else if (*ldt < max(1,*n)) { *info = -6; } else if ((*ldvl < 1) || (leftv && *ldvl < *n)) { *info = -8; } else if ((*ldvr < 1) || (rightv && *ldvr < *n)) { *info = -10; } else if (*mm < *m) { *info = -11; } if (*info != 0) { i__1 = -(*info); xerbla_("CTREVC", &i__1); return 0; } /* Quick return if possible. */ if (*n == 0) { return 0; } /* Set the constants to control overflow. */ unfl = slamch_("Safe minimum"); ovfl = 1.f / unfl; slabad_(&unfl, &ovfl); ulp = slamch_("Precision"); smlnum = unfl * (*n / ulp); /* Store the diagonal elements of T in working array WORK. */ i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = i__ + *n; i__3 = i__ + i__ * t_dim1; work[i__2].r = t[i__3].r, work[i__2].i = t[i__3].i; /* L20: */ } /* Compute 1-norm of each column of strictly upper triangular part of T to control overflow in triangular solver. */ rwork[1] = 0.f; i__1 = *n; for (j = 2; j <= i__1; ++j) { i__2 = j - 1; rwork[j] = scasum_(&i__2, &t[j * t_dim1 + 1], &c__1); /* L30: */ } if (rightv) { /* Compute right eigenvectors. */ is = *m; for (ki = *n; ki >= 1; --ki) { if (somev) { if (! select[ki]) { goto L80; } } /* Computing MAX */ i__1 = ki + ki * t_dim1; r__3 = ulp * ((r__1 = t[i__1].r, dabs(r__1)) + (r__2 = r_imag(&t[ ki + ki * t_dim1]), dabs(r__2))); smin = dmax(r__3,smlnum); work[1].r = 1.f, work[1].i = 0.f; /* Form right-hand side. */ i__1 = ki - 1; for (k = 1; k <= i__1; ++k) { i__2 = k; i__3 = k + ki * t_dim1; q__1.r = -t[i__3].r, q__1.i = -t[i__3].i; work[i__2].r = q__1.r, work[i__2].i = q__1.i; /* L40: */ } /* Solve the triangular system: (T(1:KI-1,1:KI-1) - T(KI,KI))*X = SCALE*WORK. */ i__1 = ki - 1; for (k = 1; k <= i__1; ++k) { i__2 = k + k * t_dim1; i__3 = k + k * t_dim1; i__4 = ki + ki * t_dim1; q__1.r = t[i__3].r - t[i__4].r, q__1.i = t[i__3].i - t[i__4] .i; t[i__2].r = q__1.r, t[i__2].i = q__1.i; i__2 = k + k * t_dim1; if ((r__1 = t[i__2].r, dabs(r__1)) + (r__2 = r_imag(&t[k + k * t_dim1]), dabs(r__2)) < smin) { i__3 = k + k * t_dim1; t[i__3].r = smin, t[i__3].i = 0.f; } /* L50: */ } if (ki > 1) { i__1 = ki - 1; clatrs_("Upper", "No transpose", "Non-unit", "Y", &i__1, &t[ t_offset], ldt, &work[1], &scale, &rwork[1], info); i__1 = ki; work[i__1].r = scale, work[i__1].i = 0.f; } /* Copy the vector x or Q*x to VR and normalize. */ if (! over) { ccopy_(&ki, &work[1], &c__1, &vr[is * vr_dim1 + 1], &c__1); ii = icamax_(&ki, &vr[is * vr_dim1 + 1], &c__1); i__1 = ii + is * vr_dim1; remax = 1.f / ((r__1 = vr[i__1].r, dabs(r__1)) + (r__2 = r_imag(&vr[ii + is * vr_dim1]), dabs(r__2))); csscal_(&ki, &remax, &vr[is * vr_dim1 + 1], &c__1); i__1 = *n; for (k = ki + 1; k <= i__1; ++k) { i__2 = k + is * vr_dim1; vr[i__2].r = 0.f, vr[i__2].i = 0.f; /* L60: */ } } else { if (ki > 1) { i__1 = ki - 1; q__1.r = scale, q__1.i = 0.f; cgemv_("N", n, &i__1, &c_b56, &vr[vr_offset], ldvr, &work[ 1], &c__1, &q__1, &vr[ki * vr_dim1 + 1], &c__1); } ii = icamax_(n, &vr[ki * vr_dim1 + 1], &c__1); i__1 = ii + ki * vr_dim1; remax = 1.f / ((r__1 = vr[i__1].r, dabs(r__1)) + (r__2 = r_imag(&vr[ii + ki * vr_dim1]), dabs(r__2))); csscal_(n, &remax, &vr[ki * vr_dim1 + 1], &c__1); } /* Set back the original diagonal elements of T. */ i__1 = ki - 1; for (k = 1; k <= i__1; ++k) { i__2 = k + k * t_dim1; i__3 = k + *n; t[i__2].r = work[i__3].r, t[i__2].i = work[i__3].i; /* L70: */ } --is; L80: ; } } if (leftv) { /* Compute left eigenvectors. */ is = 1; i__1 = *n; for (ki = 1; ki <= i__1; ++ki) { if (somev) { if (! select[ki]) { goto L130; } } /* Computing MAX */ i__2 = ki + ki * t_dim1; r__3 = ulp * ((r__1 = t[i__2].r, dabs(r__1)) + (r__2 = r_imag(&t[ ki + ki * t_dim1]), dabs(r__2))); smin = dmax(r__3,smlnum); i__2 = *n; work[i__2].r = 1.f, work[i__2].i = 0.f; /* Form right-hand side. */ i__2 = *n; for (k = ki + 1; k <= i__2; ++k) { i__3 = k; r_cnjg(&q__2, &t[ki + k * t_dim1]); q__1.r = -q__2.r, q__1.i = -q__2.i; work[i__3].r = q__1.r, work[i__3].i = q__1.i; /* L90: */ } /* Solve the triangular system: (T(KI+1:N,KI+1:N) - T(KI,KI))'*X = SCALE*WORK. */ i__2 = *n; for (k = ki + 1; k <= i__2; ++k) { i__3 = k + k * t_dim1; i__4 = k + k * t_dim1; i__5 = ki + ki * t_dim1; q__1.r = t[i__4].r - t[i__5].r, q__1.i = t[i__4].i - t[i__5] .i; t[i__3].r = q__1.r, t[i__3].i = q__1.i; i__3 = k + k * t_dim1; if ((r__1 = t[i__3].r, dabs(r__1)) + (r__2 = r_imag(&t[k + k * t_dim1]), dabs(r__2)) < smin) { i__4 = k + k * t_dim1; t[i__4].r = smin, t[i__4].i = 0.f; } /* L100: */ } if (ki < *n) { i__2 = *n - ki; clatrs_("Upper", "Conjugate transpose", "Non-unit", "Y", & i__2, &t[ki + 1 + (ki + 1) * t_dim1], ldt, &work[ki + 1], &scale, &rwork[1], info); i__2 = ki; work[i__2].r = scale, work[i__2].i = 0.f; } /* Copy the vector x or Q*x to VL and normalize. */ if (! over) { i__2 = *n - ki + 1; ccopy_(&i__2, &work[ki], &c__1, &vl[ki + is * vl_dim1], &c__1) ; i__2 = *n - ki + 1; ii = icamax_(&i__2, &vl[ki + is * vl_dim1], &c__1) + ki - 1; i__2 = ii + is * vl_dim1; remax = 1.f / ((r__1 = vl[i__2].r, dabs(r__1)) + (r__2 = r_imag(&vl[ii + is * vl_dim1]), dabs(r__2))); i__2 = *n - ki + 1; csscal_(&i__2, &remax, &vl[ki + is * vl_dim1], &c__1); i__2 = ki - 1; for (k = 1; k <= i__2; ++k) { i__3 = k + is * vl_dim1; vl[i__3].r = 0.f, vl[i__3].i = 0.f; /* L110: */ } } else { if (ki < *n) { i__2 = *n - ki; q__1.r = scale, q__1.i = 0.f; cgemv_("N", n, &i__2, &c_b56, &vl[(ki + 1) * vl_dim1 + 1], ldvl, &work[ki + 1], &c__1, &q__1, &vl[ki * vl_dim1 + 1], &c__1); } ii = icamax_(n, &vl[ki * vl_dim1 + 1], &c__1); i__2 = ii + ki * vl_dim1; remax = 1.f / ((r__1 = vl[i__2].r, dabs(r__1)) + (r__2 = r_imag(&vl[ii + ki * vl_dim1]), dabs(r__2))); csscal_(n, &remax, &vl[ki * vl_dim1 + 1], &c__1); } /* Set back the original diagonal elements of T. */ i__2 = *n; for (k = ki + 1; k <= i__2; ++k) { i__3 = k + k * t_dim1; i__4 = k + *n; t[i__3].r = work[i__4].r, t[i__3].i = work[i__4].i; /* L120: */ } ++is; L130: ; } } return 0; /* End of CTREVC */ } /* ctrevc_ */ /* Subroutine */ int ctrti2_(char *uplo, char *diag, integer *n, complex *a, integer *lda, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2; complex q__1; /* Builtin functions */ void c_div(complex *, complex *, complex *); /* Local variables */ static integer j; static complex ajj; extern /* Subroutine */ int cscal_(integer *, complex *, complex *, integer *); extern logical lsame_(char *, char *); static logical upper; extern /* Subroutine */ int ctrmv_(char *, char *, char *, integer *, complex *, integer *, complex *, integer *), xerbla_(char *, integer *); static logical nounit; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University September 30, 1994 Purpose ======= CTRTI2 computes the inverse of a complex upper or lower triangular matrix. This is the Level 2 BLAS version of the algorithm. Arguments ========= UPLO (input) CHARACTER*1 Specifies whether the matrix A is upper or lower triangular. = 'U': Upper triangular = 'L': Lower triangular DIAG (input) CHARACTER*1 Specifies whether or not the matrix A is unit triangular. = 'N': Non-unit triangular = 'U': Unit triangular N (input) INTEGER The order of the matrix A. N >= 0. A (input/output) COMPLEX array, dimension (LDA,N) On entry, the triangular matrix A. If UPLO = 'U', the leading n by n upper triangular part of the array A contains the upper triangular matrix, and the strictly lower triangular part of A is not referenced. If UPLO = 'L', the leading n by n lower triangular part of the array A contains the lower triangular matrix, and the strictly upper triangular part of A is not referenced. If DIAG = 'U', the diagonal elements of A are also not referenced and are assumed to be 1. On exit, the (triangular) inverse of the original matrix, in the same storage format. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,N). INFO (output) INTEGER = 0: successful exit < 0: if INFO = -k, the k-th argument had an illegal value ===================================================================== Test the input parameters. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; /* Function Body */ *info = 0; upper = lsame_(uplo, "U"); nounit = lsame_(diag, "N"); if (! upper && ! lsame_(uplo, "L")) { *info = -1; } else if (! nounit && ! lsame_(diag, "U")) { *info = -2; } else if (*n < 0) { *info = -3; } else if (*lda < max(1,*n)) { *info = -5; } if (*info != 0) { i__1 = -(*info); xerbla_("CTRTI2", &i__1); return 0; } if (upper) { /* Compute inverse of upper triangular matrix. */ i__1 = *n; for (j = 1; j <= i__1; ++j) { if (nounit) { i__2 = j + j * a_dim1; c_div(&q__1, &c_b56, &a[j + j * a_dim1]); a[i__2].r = q__1.r, a[i__2].i = q__1.i; i__2 = j + j * a_dim1; q__1.r = -a[i__2].r, q__1.i = -a[i__2].i; ajj.r = q__1.r, ajj.i = q__1.i; } else { q__1.r = -1.f, q__1.i = -0.f; ajj.r = q__1.r, ajj.i = q__1.i; } /* Compute elements 1:j-1 of j-th column. */ i__2 = j - 1; ctrmv_("Upper", "No transpose", diag, &i__2, &a[a_offset], lda, & a[j * a_dim1 + 1], &c__1); i__2 = j - 1; cscal_(&i__2, &ajj, &a[j * a_dim1 + 1], &c__1); /* L10: */ } } else { /* Compute inverse of lower triangular matrix. */ for (j = *n; j >= 1; --j) { if (nounit) { i__1 = j + j * a_dim1; c_div(&q__1, &c_b56, &a[j + j * a_dim1]); a[i__1].r = q__1.r, a[i__1].i = q__1.i; i__1 = j + j * a_dim1; q__1.r = -a[i__1].r, q__1.i = -a[i__1].i; ajj.r = q__1.r, ajj.i = q__1.i; } else { q__1.r = -1.f, q__1.i = -0.f; ajj.r = q__1.r, ajj.i = q__1.i; } if (j < *n) { /* Compute elements j+1:n of j-th column. */ i__1 = *n - j; ctrmv_("Lower", "No transpose", diag, &i__1, &a[j + 1 + (j + 1) * a_dim1], lda, &a[j + 1 + j * a_dim1], &c__1); i__1 = *n - j; cscal_(&i__1, &ajj, &a[j + 1 + j * a_dim1], &c__1); } /* L20: */ } } return 0; /* End of CTRTI2 */ } /* ctrti2_ */ /* Subroutine */ int ctrtri_(char *uplo, char *diag, integer *n, complex *a, integer *lda, integer *info) { /* System generated locals */ address a__1[2]; integer a_dim1, a_offset, i__1, i__2, i__3[2], i__4, i__5; complex q__1; char ch__1[2]; /* Builtin functions */ /* Subroutine */ int s_cat(char *, char **, integer *, integer *, ftnlen); /* Local variables */ static integer j, jb, nb, nn; extern logical lsame_(char *, char *); extern /* Subroutine */ int ctrmm_(char *, char *, char *, char *, integer *, integer *, complex *, complex *, integer *, complex *, integer *), ctrsm_(char *, char *, char *, char *, integer *, integer *, complex *, complex *, integer *, complex *, integer *); static logical upper; extern /* Subroutine */ int ctrti2_(char *, char *, integer *, complex *, integer *, integer *), xerbla_(char *, integer *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); static logical nounit; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University September 30, 1994 Purpose ======= CTRTRI computes the inverse of a complex upper or lower triangular matrix A. This is the Level 3 BLAS version of the algorithm. Arguments ========= UPLO (input) CHARACTER*1 = 'U': A is upper triangular; = 'L': A is lower triangular. DIAG (input) CHARACTER*1 = 'N': A is non-unit triangular; = 'U': A is unit triangular. N (input) INTEGER The order of the matrix A. N >= 0. A (input/output) COMPLEX array, dimension (LDA,N) On entry, the triangular matrix A. If UPLO = 'U', the leading N-by-N upper triangular part of the array A contains the upper triangular matrix, and the strictly lower triangular part of A is not referenced. If UPLO = 'L', the leading N-by-N lower triangular part of the array A contains the lower triangular matrix, and the strictly upper triangular part of A is not referenced. If DIAG = 'U', the diagonal elements of A are also not referenced and are assumed to be 1. On exit, the (triangular) inverse of the original matrix, in the same storage format. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,N). INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value > 0: if INFO = i, A(i,i) is exactly zero. The triangular matrix is singular and its inverse can not be computed. ===================================================================== Test the input parameters. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; /* Function Body */ *info = 0; upper = lsame_(uplo, "U"); nounit = lsame_(diag, "N"); if (! upper && ! lsame_(uplo, "L")) { *info = -1; } else if (! nounit && ! lsame_(diag, "U")) { *info = -2; } else if (*n < 0) { *info = -3; } else if (*lda < max(1,*n)) { *info = -5; } if (*info != 0) { i__1 = -(*info); xerbla_("CTRTRI", &i__1); return 0; } /* Quick return if possible */ if (*n == 0) { return 0; } /* Check for singularity if non-unit. */ if (nounit) { i__1 = *n; for (*info = 1; *info <= i__1; ++(*info)) { i__2 = *info + *info * a_dim1; if (a[i__2].r == 0.f && a[i__2].i == 0.f) { return 0; } /* L10: */ } *info = 0; } /* Determine the block size for this environment. Writing concatenation */ i__3[0] = 1, a__1[0] = uplo; i__3[1] = 1, a__1[1] = diag; s_cat(ch__1, a__1, i__3, &c__2, (ftnlen)2); nb = ilaenv_(&c__1, "CTRTRI", ch__1, n, &c_n1, &c_n1, &c_n1, (ftnlen)6, ( ftnlen)2); if ((nb <= 1) || (nb >= *n)) { /* Use unblocked code */ ctrti2_(uplo, diag, n, &a[a_offset], lda, info); } else { /* Use blocked code */ if (upper) { /* Compute inverse of upper triangular matrix */ i__1 = *n; i__2 = nb; for (j = 1; i__2 < 0 ? j >= i__1 : j <= i__1; j += i__2) { /* Computing MIN */ i__4 = nb, i__5 = *n - j + 1; jb = min(i__4,i__5); /* Compute rows 1:j-1 of current block column */ i__4 = j - 1; ctrmm_("Left", "Upper", "No transpose", diag, &i__4, &jb, & c_b56, &a[a_offset], lda, &a[j * a_dim1 + 1], lda); i__4 = j - 1; q__1.r = -1.f, q__1.i = -0.f; ctrsm_("Right", "Upper", "No transpose", diag, &i__4, &jb, & q__1, &a[j + j * a_dim1], lda, &a[j * a_dim1 + 1], lda); /* Compute inverse of current diagonal block */ ctrti2_("Upper", diag, &jb, &a[j + j * a_dim1], lda, info); /* L20: */ } } else { /* Compute inverse of lower triangular matrix */ nn = (*n - 1) / nb * nb + 1; i__2 = -nb; for (j = nn; i__2 < 0 ? j >= 1 : j <= 1; j += i__2) { /* Computing MIN */ i__1 = nb, i__4 = *n - j + 1; jb = min(i__1,i__4); if (j + jb <= *n) { /* Compute rows j+jb:n of current block column */ i__1 = *n - j - jb + 1; ctrmm_("Left", "Lower", "No transpose", diag, &i__1, &jb, &c_b56, &a[j + jb + (j + jb) * a_dim1], lda, &a[j + jb + j * a_dim1], lda); i__1 = *n - j - jb + 1; q__1.r = -1.f, q__1.i = -0.f; ctrsm_("Right", "Lower", "No transpose", diag, &i__1, &jb, &q__1, &a[j + j * a_dim1], lda, &a[j + jb + j * a_dim1], lda); } /* Compute inverse of current diagonal block */ ctrti2_("Lower", diag, &jb, &a[j + j * a_dim1], lda, info); /* L30: */ } } } return 0; /* End of CTRTRI */ } /* ctrtri_ */ /* Subroutine */ int cung2r_(integer *m, integer *n, integer *k, complex *a, integer *lda, complex *tau, complex *work, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3; complex q__1; /* Local variables */ static integer i__, j, l; extern /* Subroutine */ int cscal_(integer *, complex *, complex *, integer *), clarf_(char *, integer *, integer *, complex *, integer *, complex *, complex *, integer *, complex *), xerbla_(char *, integer *); /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University September 30, 1994 Purpose ======= CUNG2R generates an m by n complex matrix Q with orthonormal columns, which is defined as the first n columns of a product of k elementary reflectors of order m Q = H(1) H(2) . . . H(k) as returned by CGEQRF. Arguments ========= M (input) INTEGER The number of rows of the matrix Q. M >= 0. N (input) INTEGER The number of columns of the matrix Q. M >= N >= 0. K (input) INTEGER The number of elementary reflectors whose product defines the matrix Q. N >= K >= 0. A (input/output) COMPLEX array, dimension (LDA,N) On entry, the i-th column must contain the vector which defines the elementary reflector H(i), for i = 1,2,...,k, as returned by CGEQRF in the first k columns of its array argument A. On exit, the m by n matrix Q. LDA (input) INTEGER The first dimension of the array A. LDA >= max(1,M). TAU (input) COMPLEX array, dimension (K) TAU(i) must contain the scalar factor of the elementary reflector H(i), as returned by CGEQRF. WORK (workspace) COMPLEX array, dimension (N) INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument has an illegal value ===================================================================== Test the input arguments */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --tau; --work; /* Function Body */ *info = 0; if (*m < 0) { *info = -1; } else if ((*n < 0) || (*n > *m)) { *info = -2; } else if ((*k < 0) || (*k > *n)) { *info = -3; } else if (*lda < max(1,*m)) { *info = -5; } if (*info != 0) { i__1 = -(*info); xerbla_("CUNG2R", &i__1); return 0; } /* Quick return if possible */ if (*n <= 0) { return 0; } /* Initialise columns k+1:n to columns of the unit matrix */ i__1 = *n; for (j = *k + 1; j <= i__1; ++j) { i__2 = *m; for (l = 1; l <= i__2; ++l) { i__3 = l + j * a_dim1; a[i__3].r = 0.f, a[i__3].i = 0.f; /* L10: */ } i__2 = j + j * a_dim1; a[i__2].r = 1.f, a[i__2].i = 0.f; /* L20: */ } for (i__ = *k; i__ >= 1; --i__) { /* Apply H(i) to A(i:m,i:n) from the left */ if (i__ < *n) { i__1 = i__ + i__ * a_dim1; a[i__1].r = 1.f, a[i__1].i = 0.f; i__1 = *m - i__ + 1; i__2 = *n - i__; clarf_("Left", &i__1, &i__2, &a[i__ + i__ * a_dim1], &c__1, &tau[ i__], &a[i__ + (i__ + 1) * a_dim1], lda, &work[1]); } if (i__ < *m) { i__1 = *m - i__; i__2 = i__; q__1.r = -tau[i__2].r, q__1.i = -tau[i__2].i; cscal_(&i__1, &q__1, &a[i__ + 1 + i__ * a_dim1], &c__1); } i__1 = i__ + i__ * a_dim1; i__2 = i__; q__1.r = 1.f - tau[i__2].r, q__1.i = 0.f - tau[i__2].i; a[i__1].r = q__1.r, a[i__1].i = q__1.i; /* Set A(1:i-1,i) to zero */ i__1 = i__ - 1; for (l = 1; l <= i__1; ++l) { i__2 = l + i__ * a_dim1; a[i__2].r = 0.f, a[i__2].i = 0.f; /* L30: */ } /* L40: */ } return 0; /* End of CUNG2R */ } /* cung2r_ */ /* Subroutine */ int cungbr_(char *vect, integer *m, integer *n, integer *k, complex *a, integer *lda, complex *tau, complex *work, integer *lwork, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3; /* Local variables */ static integer i__, j, nb, mn; extern logical lsame_(char *, char *); static integer iinfo; static logical wantq; extern /* Subroutine */ int xerbla_(char *, integer *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); extern /* Subroutine */ int cunglq_(integer *, integer *, integer *, complex *, integer *, complex *, complex *, integer *, integer *), cungqr_(integer *, integer *, integer *, complex *, integer *, complex *, complex *, integer *, integer *); static integer lwkopt; static logical lquery; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= CUNGBR generates one of the complex unitary matrices Q or P**H determined by CGEBRD when reducing a complex matrix A to bidiagonal form: A = Q * B * P**H. Q and P**H are defined as products of elementary reflectors H(i) or G(i) respectively. If VECT = 'Q', A is assumed to have been an M-by-K matrix, and Q is of order M: if m >= k, Q = H(1) H(2) . . . H(k) and CUNGBR returns the first n columns of Q, where m >= n >= k; if m < k, Q = H(1) H(2) . . . H(m-1) and CUNGBR returns Q as an M-by-M matrix. If VECT = 'P', A is assumed to have been a K-by-N matrix, and P**H is of order N: if k < n, P**H = G(k) . . . G(2) G(1) and CUNGBR returns the first m rows of P**H, where n >= m >= k; if k >= n, P**H = G(n-1) . . . G(2) G(1) and CUNGBR returns P**H as an N-by-N matrix. Arguments ========= VECT (input) CHARACTER*1 Specifies whether the matrix Q or the matrix P**H is required, as defined in the transformation applied by CGEBRD: = 'Q': generate Q; = 'P': generate P**H. M (input) INTEGER The number of rows of the matrix Q or P**H to be returned. M >= 0. N (input) INTEGER The number of columns of the matrix Q or P**H to be returned. N >= 0. If VECT = 'Q', M >= N >= min(M,K); if VECT = 'P', N >= M >= min(N,K). K (input) INTEGER If VECT = 'Q', the number of columns in the original M-by-K matrix reduced by CGEBRD. If VECT = 'P', the number of rows in the original K-by-N matrix reduced by CGEBRD. K >= 0. A (input/output) COMPLEX array, dimension (LDA,N) On entry, the vectors which define the elementary reflectors, as returned by CGEBRD. On exit, the M-by-N matrix Q or P**H. LDA (input) INTEGER The leading dimension of the array A. LDA >= M. TAU (input) COMPLEX array, dimension (min(M,K)) if VECT = 'Q' (min(N,K)) if VECT = 'P' TAU(i) must contain the scalar factor of the elementary reflector H(i) or G(i), which determines Q or P**H, as returned by CGEBRD in its array argument TAUQ or TAUP. WORK (workspace/output) COMPLEX array, dimension (LWORK) On exit, if INFO = 0, WORK(1) returns the optimal LWORK. LWORK (input) INTEGER The dimension of the array WORK. LWORK >= max(1,min(M,N)). For optimum performance LWORK >= min(M,N)*NB, where NB is the optimal blocksize. If LWORK = -1, then a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued by XERBLA. INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value ===================================================================== Test the input arguments */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --tau; --work; /* Function Body */ *info = 0; wantq = lsame_(vect, "Q"); mn = min(*m,*n); lquery = *lwork == -1; if (! wantq && ! lsame_(vect, "P")) { *info = -1; } else if (*m < 0) { *info = -2; } else if (((*n < 0) || (wantq && ((*n > *m) || (*n < min(*m,*k))))) || (! wantq && ((*m > *n) || (*m < min(*n,*k))))) { *info = -3; } else if (*k < 0) { *info = -4; } else if (*lda < max(1,*m)) { *info = -6; } else if (*lwork < max(1,mn) && ! lquery) { *info = -9; } if (*info == 0) { if (wantq) { nb = ilaenv_(&c__1, "CUNGQR", " ", m, n, k, &c_n1, (ftnlen)6, ( ftnlen)1); } else { nb = ilaenv_(&c__1, "CUNGLQ", " ", m, n, k, &c_n1, (ftnlen)6, ( ftnlen)1); } lwkopt = max(1,mn) * nb; work[1].r = (real) lwkopt, work[1].i = 0.f; } if (*info != 0) { i__1 = -(*info); xerbla_("CUNGBR", &i__1); return 0; } else if (lquery) { return 0; } /* Quick return if possible */ if ((*m == 0) || (*n == 0)) { work[1].r = 1.f, work[1].i = 0.f; return 0; } if (wantq) { /* Form Q, determined by a call to CGEBRD to reduce an m-by-k matrix */ if (*m >= *k) { /* If m >= k, assume m >= n >= k */ cungqr_(m, n, k, &a[a_offset], lda, &tau[1], &work[1], lwork, & iinfo); } else { /* If m < k, assume m = n Shift the vectors which define the elementary reflectors one column to the right, and set the first row and column of Q to those of the unit matrix */ for (j = *m; j >= 2; --j) { i__1 = j * a_dim1 + 1; a[i__1].r = 0.f, a[i__1].i = 0.f; i__1 = *m; for (i__ = j + 1; i__ <= i__1; ++i__) { i__2 = i__ + j * a_dim1; i__3 = i__ + (j - 1) * a_dim1; a[i__2].r = a[i__3].r, a[i__2].i = a[i__3].i; /* L10: */ } /* L20: */ } i__1 = a_dim1 + 1; a[i__1].r = 1.f, a[i__1].i = 0.f; i__1 = *m; for (i__ = 2; i__ <= i__1; ++i__) { i__2 = i__ + a_dim1; a[i__2].r = 0.f, a[i__2].i = 0.f; /* L30: */ } if (*m > 1) { /* Form Q(2:m,2:m) */ i__1 = *m - 1; i__2 = *m - 1; i__3 = *m - 1; cungqr_(&i__1, &i__2, &i__3, &a[((a_dim1) << (1)) + 2], lda, & tau[1], &work[1], lwork, &iinfo); } } } else { /* Form P', determined by a call to CGEBRD to reduce a k-by-n matrix */ if (*k < *n) { /* If k < n, assume k <= m <= n */ cunglq_(m, n, k, &a[a_offset], lda, &tau[1], &work[1], lwork, & iinfo); } else { /* If k >= n, assume m = n Shift the vectors which define the elementary reflectors one row downward, and set the first row and column of P' to those of the unit matrix */ i__1 = a_dim1 + 1; a[i__1].r = 1.f, a[i__1].i = 0.f; i__1 = *n; for (i__ = 2; i__ <= i__1; ++i__) { i__2 = i__ + a_dim1; a[i__2].r = 0.f, a[i__2].i = 0.f; /* L40: */ } i__1 = *n; for (j = 2; j <= i__1; ++j) { for (i__ = j - 1; i__ >= 2; --i__) { i__2 = i__ + j * a_dim1; i__3 = i__ - 1 + j * a_dim1; a[i__2].r = a[i__3].r, a[i__2].i = a[i__3].i; /* L50: */ } i__2 = j * a_dim1 + 1; a[i__2].r = 0.f, a[i__2].i = 0.f; /* L60: */ } if (*n > 1) { /* Form P'(2:n,2:n) */ i__1 = *n - 1; i__2 = *n - 1; i__3 = *n - 1; cunglq_(&i__1, &i__2, &i__3, &a[((a_dim1) << (1)) + 2], lda, & tau[1], &work[1], lwork, &iinfo); } } } work[1].r = (real) lwkopt, work[1].i = 0.f; return 0; /* End of CUNGBR */ } /* cungbr_ */ /* Subroutine */ int cunghr_(integer *n, integer *ilo, integer *ihi, complex * a, integer *lda, complex *tau, complex *work, integer *lwork, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3, i__4; /* Local variables */ static integer i__, j, nb, nh, iinfo; extern /* Subroutine */ int xerbla_(char *, integer *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); extern /* Subroutine */ int cungqr_(integer *, integer *, integer *, complex *, integer *, complex *, complex *, integer *, integer *); static integer lwkopt; static logical lquery; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= CUNGHR generates a complex unitary matrix Q which is defined as the product of IHI-ILO elementary reflectors of order N, as returned by CGEHRD: Q = H(ilo) H(ilo+1) . . . H(ihi-1). Arguments ========= N (input) INTEGER The order of the matrix Q. N >= 0. ILO (input) INTEGER IHI (input) INTEGER ILO and IHI must have the same values as in the previous call of CGEHRD. Q is equal to the unit matrix except in the submatrix Q(ilo+1:ihi,ilo+1:ihi). 1 <= ILO <= IHI <= N, if N > 0; ILO=1 and IHI=0, if N=0. A (input/output) COMPLEX array, dimension (LDA,N) On entry, the vectors which define the elementary reflectors, as returned by CGEHRD. On exit, the N-by-N unitary matrix Q. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,N). TAU (input) COMPLEX array, dimension (N-1) TAU(i) must contain the scalar factor of the elementary reflector H(i), as returned by CGEHRD. WORK (workspace/output) COMPLEX array, dimension (LWORK) On exit, if INFO = 0, WORK(1) returns the optimal LWORK. LWORK (input) INTEGER The dimension of the array WORK. LWORK >= IHI-ILO. For optimum performance LWORK >= (IHI-ILO)*NB, where NB is the optimal blocksize. If LWORK = -1, then a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued by XERBLA. INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value ===================================================================== Test the input arguments */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --tau; --work; /* Function Body */ *info = 0; nh = *ihi - *ilo; lquery = *lwork == -1; if (*n < 0) { *info = -1; } else if ((*ilo < 1) || (*ilo > max(1,*n))) { *info = -2; } else if ((*ihi < min(*ilo,*n)) || (*ihi > *n)) { *info = -3; } else if (*lda < max(1,*n)) { *info = -5; } else if (*lwork < max(1,nh) && ! lquery) { *info = -8; } if (*info == 0) { nb = ilaenv_(&c__1, "CUNGQR", " ", &nh, &nh, &nh, &c_n1, (ftnlen)6, ( ftnlen)1); lwkopt = max(1,nh) * nb; work[1].r = (real) lwkopt, work[1].i = 0.f; } if (*info != 0) { i__1 = -(*info); xerbla_("CUNGHR", &i__1); return 0; } else if (lquery) { return 0; } /* Quick return if possible */ if (*n == 0) { work[1].r = 1.f, work[1].i = 0.f; return 0; } /* Shift the vectors which define the elementary reflectors one column to the right, and set the first ilo and the last n-ihi rows and columns to those of the unit matrix */ i__1 = *ilo + 1; for (j = *ihi; j >= i__1; --j) { i__2 = j - 1; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * a_dim1; a[i__3].r = 0.f, a[i__3].i = 0.f; /* L10: */ } i__2 = *ihi; for (i__ = j + 1; i__ <= i__2; ++i__) { i__3 = i__ + j * a_dim1; i__4 = i__ + (j - 1) * a_dim1; a[i__3].r = a[i__4].r, a[i__3].i = a[i__4].i; /* L20: */ } i__2 = *n; for (i__ = *ihi + 1; i__ <= i__2; ++i__) { i__3 = i__ + j * a_dim1; a[i__3].r = 0.f, a[i__3].i = 0.f; /* L30: */ } /* L40: */ } i__1 = *ilo; for (j = 1; j <= i__1; ++j) { i__2 = *n; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * a_dim1; a[i__3].r = 0.f, a[i__3].i = 0.f; /* L50: */ } i__2 = j + j * a_dim1; a[i__2].r = 1.f, a[i__2].i = 0.f; /* L60: */ } i__1 = *n; for (j = *ihi + 1; j <= i__1; ++j) { i__2 = *n; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * a_dim1; a[i__3].r = 0.f, a[i__3].i = 0.f; /* L70: */ } i__2 = j + j * a_dim1; a[i__2].r = 1.f, a[i__2].i = 0.f; /* L80: */ } if (nh > 0) { /* Generate Q(ilo+1:ihi,ilo+1:ihi) */ cungqr_(&nh, &nh, &nh, &a[*ilo + 1 + (*ilo + 1) * a_dim1], lda, &tau[* ilo], &work[1], lwork, &iinfo); } work[1].r = (real) lwkopt, work[1].i = 0.f; return 0; /* End of CUNGHR */ } /* cunghr_ */ /* Subroutine */ int cungl2_(integer *m, integer *n, integer *k, complex *a, integer *lda, complex *tau, complex *work, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3; complex q__1, q__2; /* Builtin functions */ void r_cnjg(complex *, complex *); /* Local variables */ static integer i__, j, l; extern /* Subroutine */ int cscal_(integer *, complex *, complex *, integer *), clarf_(char *, integer *, integer *, complex *, integer *, complex *, complex *, integer *, complex *), clacgv_(integer *, complex *, integer *), xerbla_(char *, integer *); /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= CUNGL2 generates an m-by-n complex matrix Q with orthonormal rows, which is defined as the first m rows of a product of k elementary reflectors of order n Q = H(k)' . . . H(2)' H(1)' as returned by CGELQF. Arguments ========= M (input) INTEGER The number of rows of the matrix Q. M >= 0. N (input) INTEGER The number of columns of the matrix Q. N >= M. K (input) INTEGER The number of elementary reflectors whose product defines the matrix Q. M >= K >= 0. A (input/output) COMPLEX array, dimension (LDA,N) On entry, the i-th row must contain the vector which defines the elementary reflector H(i), for i = 1,2,...,k, as returned by CGELQF in the first k rows of its array argument A. On exit, the m by n matrix Q. LDA (input) INTEGER The first dimension of the array A. LDA >= max(1,M). TAU (input) COMPLEX array, dimension (K) TAU(i) must contain the scalar factor of the elementary reflector H(i), as returned by CGELQF. WORK (workspace) COMPLEX array, dimension (M) INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument has an illegal value ===================================================================== Test the input arguments */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --tau; --work; /* Function Body */ *info = 0; if (*m < 0) { *info = -1; } else if (*n < *m) { *info = -2; } else if ((*k < 0) || (*k > *m)) { *info = -3; } else if (*lda < max(1,*m)) { *info = -5; } if (*info != 0) { i__1 = -(*info); xerbla_("CUNGL2", &i__1); return 0; } /* Quick return if possible */ if (*m <= 0) { return 0; } if (*k < *m) { /* Initialise rows k+1:m to rows of the unit matrix */ i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (l = *k + 1; l <= i__2; ++l) { i__3 = l + j * a_dim1; a[i__3].r = 0.f, a[i__3].i = 0.f; /* L10: */ } if (j > *k && j <= *m) { i__2 = j + j * a_dim1; a[i__2].r = 1.f, a[i__2].i = 0.f; } /* L20: */ } } for (i__ = *k; i__ >= 1; --i__) { /* Apply H(i)' to A(i:m,i:n) from the right */ if (i__ < *n) { i__1 = *n - i__; clacgv_(&i__1, &a[i__ + (i__ + 1) * a_dim1], lda); if (i__ < *m) { i__1 = i__ + i__ * a_dim1; a[i__1].r = 1.f, a[i__1].i = 0.f; i__1 = *m - i__; i__2 = *n - i__ + 1; r_cnjg(&q__1, &tau[i__]); clarf_("Right", &i__1, &i__2, &a[i__ + i__ * a_dim1], lda, & q__1, &a[i__ + 1 + i__ * a_dim1], lda, &work[1]); } i__1 = *n - i__; i__2 = i__; q__1.r = -tau[i__2].r, q__1.i = -tau[i__2].i; cscal_(&i__1, &q__1, &a[i__ + (i__ + 1) * a_dim1], lda); i__1 = *n - i__; clacgv_(&i__1, &a[i__ + (i__ + 1) * a_dim1], lda); } i__1 = i__ + i__ * a_dim1; r_cnjg(&q__2, &tau[i__]); q__1.r = 1.f - q__2.r, q__1.i = 0.f - q__2.i; a[i__1].r = q__1.r, a[i__1].i = q__1.i; /* Set A(i,1:i-1,i) to zero */ i__1 = i__ - 1; for (l = 1; l <= i__1; ++l) { i__2 = i__ + l * a_dim1; a[i__2].r = 0.f, a[i__2].i = 0.f; /* L30: */ } /* L40: */ } return 0; /* End of CUNGL2 */ } /* cungl2_ */ /* Subroutine */ int cunglq_(integer *m, integer *n, integer *k, complex *a, integer *lda, complex *tau, complex *work, integer *lwork, integer * info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3, i__4; /* Local variables */ static integer i__, j, l, ib, nb, ki, kk, nx, iws, nbmin, iinfo; extern /* Subroutine */ int cungl2_(integer *, integer *, integer *, complex *, integer *, complex *, complex *, integer *), clarfb_( char *, char *, char *, char *, integer *, integer *, integer *, complex *, integer *, complex *, integer *, complex *, integer *, complex *, integer *), clarft_( char *, char *, integer *, integer *, complex *, integer *, complex *, complex *, integer *), xerbla_(char *, integer *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); static integer ldwork, lwkopt; static logical lquery; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= CUNGLQ generates an M-by-N complex matrix Q with orthonormal rows, which is defined as the first M rows of a product of K elementary reflectors of order N Q = H(k)' . . . H(2)' H(1)' as returned by CGELQF. Arguments ========= M (input) INTEGER The number of rows of the matrix Q. M >= 0. N (input) INTEGER The number of columns of the matrix Q. N >= M. K (input) INTEGER The number of elementary reflectors whose product defines the matrix Q. M >= K >= 0. A (input/output) COMPLEX array, dimension (LDA,N) On entry, the i-th row must contain the vector which defines the elementary reflector H(i), for i = 1,2,...,k, as returned by CGELQF in the first k rows of its array argument A. On exit, the M-by-N matrix Q. LDA (input) INTEGER The first dimension of the array A. LDA >= max(1,M). TAU (input) COMPLEX array, dimension (K) TAU(i) must contain the scalar factor of the elementary reflector H(i), as returned by CGELQF. WORK (workspace/output) COMPLEX array, dimension (LWORK) On exit, if INFO = 0, WORK(1) returns the optimal LWORK. LWORK (input) INTEGER The dimension of the array WORK. LWORK >= max(1,M). For optimum performance LWORK >= M*NB, where NB is the optimal blocksize. If LWORK = -1, then a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued by XERBLA. INFO (output) INTEGER = 0: successful exit; < 0: if INFO = -i, the i-th argument has an illegal value ===================================================================== Test the input arguments */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --tau; --work; /* Function Body */ *info = 0; nb = ilaenv_(&c__1, "CUNGLQ", " ", m, n, k, &c_n1, (ftnlen)6, (ftnlen)1); lwkopt = max(1,*m) * nb; work[1].r = (real) lwkopt, work[1].i = 0.f; lquery = *lwork == -1; if (*m < 0) { *info = -1; } else if (*n < *m) { *info = -2; } else if ((*k < 0) || (*k > *m)) { *info = -3; } else if (*lda < max(1,*m)) { *info = -5; } else if (*lwork < max(1,*m) && ! lquery) { *info = -8; } if (*info != 0) { i__1 = -(*info); xerbla_("CUNGLQ", &i__1); return 0; } else if (lquery) { return 0; } /* Quick return if possible */ if (*m <= 0) { work[1].r = 1.f, work[1].i = 0.f; return 0; } nbmin = 2; nx = 0; iws = *m; if (nb > 1 && nb < *k) { /* Determine when to cross over from blocked to unblocked code. Computing MAX */ i__1 = 0, i__2 = ilaenv_(&c__3, "CUNGLQ", " ", m, n, k, &c_n1, ( ftnlen)6, (ftnlen)1); nx = max(i__1,i__2); if (nx < *k) { /* Determine if workspace is large enough for blocked code. */ ldwork = *m; iws = ldwork * nb; if (*lwork < iws) { /* Not enough workspace to use optimal NB: reduce NB and determine the minimum value of NB. */ nb = *lwork / ldwork; /* Computing MAX */ i__1 = 2, i__2 = ilaenv_(&c__2, "CUNGLQ", " ", m, n, k, &c_n1, (ftnlen)6, (ftnlen)1); nbmin = max(i__1,i__2); } } } if (nb >= nbmin && nb < *k && nx < *k) { /* Use blocked code after the last block. The first kk rows are handled by the block method. */ ki = (*k - nx - 1) / nb * nb; /* Computing MIN */ i__1 = *k, i__2 = ki + nb; kk = min(i__1,i__2); /* Set A(kk+1:m,1:kk) to zero. */ i__1 = kk; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = kk + 1; i__ <= i__2; ++i__) { i__3 = i__ + j * a_dim1; a[i__3].r = 0.f, a[i__3].i = 0.f; /* L10: */ } /* L20: */ } } else { kk = 0; } /* Use unblocked code for the last or only block. */ if (kk < *m) { i__1 = *m - kk; i__2 = *n - kk; i__3 = *k - kk; cungl2_(&i__1, &i__2, &i__3, &a[kk + 1 + (kk + 1) * a_dim1], lda, & tau[kk + 1], &work[1], &iinfo); } if (kk > 0) { /* Use blocked code */ i__1 = -nb; for (i__ = ki + 1; i__1 < 0 ? i__ >= 1 : i__ <= 1; i__ += i__1) { /* Computing MIN */ i__2 = nb, i__3 = *k - i__ + 1; ib = min(i__2,i__3); if (i__ + ib <= *m) { /* Form the triangular factor of the block reflector H = H(i) H(i+1) . . . H(i+ib-1) */ i__2 = *n - i__ + 1; clarft_("Forward", "Rowwise", &i__2, &ib, &a[i__ + i__ * a_dim1], lda, &tau[i__], &work[1], &ldwork); /* Apply H' to A(i+ib:m,i:n) from the right */ i__2 = *m - i__ - ib + 1; i__3 = *n - i__ + 1; clarfb_("Right", "Conjugate transpose", "Forward", "Rowwise", &i__2, &i__3, &ib, &a[i__ + i__ * a_dim1], lda, &work[ 1], &ldwork, &a[i__ + ib + i__ * a_dim1], lda, &work[ ib + 1], &ldwork); } /* Apply H' to columns i:n of current block */ i__2 = *n - i__ + 1; cungl2_(&ib, &i__2, &ib, &a[i__ + i__ * a_dim1], lda, &tau[i__], & work[1], &iinfo); /* Set columns 1:i-1 of current block to zero */ i__2 = i__ - 1; for (j = 1; j <= i__2; ++j) { i__3 = i__ + ib - 1; for (l = i__; l <= i__3; ++l) { i__4 = l + j * a_dim1; a[i__4].r = 0.f, a[i__4].i = 0.f; /* L30: */ } /* L40: */ } /* L50: */ } } work[1].r = (real) iws, work[1].i = 0.f; return 0; /* End of CUNGLQ */ } /* cunglq_ */ /* Subroutine */ int cungqr_(integer *m, integer *n, integer *k, complex *a, integer *lda, complex *tau, complex *work, integer *lwork, integer * info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3, i__4; /* Local variables */ static integer i__, j, l, ib, nb, ki, kk, nx, iws, nbmin, iinfo; extern /* Subroutine */ int cung2r_(integer *, integer *, integer *, complex *, integer *, complex *, complex *, integer *), clarfb_( char *, char *, char *, char *, integer *, integer *, integer *, complex *, integer *, complex *, integer *, complex *, integer *, complex *, integer *), clarft_( char *, char *, integer *, integer *, complex *, integer *, complex *, complex *, integer *), xerbla_(char *, integer *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); static integer ldwork, lwkopt; static logical lquery; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= CUNGQR generates an M-by-N complex matrix Q with orthonormal columns, which is defined as the first N columns of a product of K elementary reflectors of order M Q = H(1) H(2) . . . H(k) as returned by CGEQRF. Arguments ========= M (input) INTEGER The number of rows of the matrix Q. M >= 0. N (input) INTEGER The number of columns of the matrix Q. M >= N >= 0. K (input) INTEGER The number of elementary reflectors whose product defines the matrix Q. N >= K >= 0. A (input/output) COMPLEX array, dimension (LDA,N) On entry, the i-th column must contain the vector which defines the elementary reflector H(i), for i = 1,2,...,k, as returned by CGEQRF in the first k columns of its array argument A. On exit, the M-by-N matrix Q. LDA (input) INTEGER The first dimension of the array A. LDA >= max(1,M). TAU (input) COMPLEX array, dimension (K) TAU(i) must contain the scalar factor of the elementary reflector H(i), as returned by CGEQRF. WORK (workspace/output) COMPLEX array, dimension (LWORK) On exit, if INFO = 0, WORK(1) returns the optimal LWORK. LWORK (input) INTEGER The dimension of the array WORK. LWORK >= max(1,N). For optimum performance LWORK >= N*NB, where NB is the optimal blocksize. If LWORK = -1, then a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued by XERBLA. INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument has an illegal value ===================================================================== Test the input arguments */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --tau; --work; /* Function Body */ *info = 0; nb = ilaenv_(&c__1, "CUNGQR", " ", m, n, k, &c_n1, (ftnlen)6, (ftnlen)1); lwkopt = max(1,*n) * nb; work[1].r = (real) lwkopt, work[1].i = 0.f; lquery = *lwork == -1; if (*m < 0) { *info = -1; } else if ((*n < 0) || (*n > *m)) { *info = -2; } else if ((*k < 0) || (*k > *n)) { *info = -3; } else if (*lda < max(1,*m)) { *info = -5; } else if (*lwork < max(1,*n) && ! lquery) { *info = -8; } if (*info != 0) { i__1 = -(*info); xerbla_("CUNGQR", &i__1); return 0; } else if (lquery) { return 0; } /* Quick return if possible */ if (*n <= 0) { work[1].r = 1.f, work[1].i = 0.f; return 0; } nbmin = 2; nx = 0; iws = *n; if (nb > 1 && nb < *k) { /* Determine when to cross over from blocked to unblocked code. Computing MAX */ i__1 = 0, i__2 = ilaenv_(&c__3, "CUNGQR", " ", m, n, k, &c_n1, ( ftnlen)6, (ftnlen)1); nx = max(i__1,i__2); if (nx < *k) { /* Determine if workspace is large enough for blocked code. */ ldwork = *n; iws = ldwork * nb; if (*lwork < iws) { /* Not enough workspace to use optimal NB: reduce NB and determine the minimum value of NB. */ nb = *lwork / ldwork; /* Computing MAX */ i__1 = 2, i__2 = ilaenv_(&c__2, "CUNGQR", " ", m, n, k, &c_n1, (ftnlen)6, (ftnlen)1); nbmin = max(i__1,i__2); } } } if (nb >= nbmin && nb < *k && nx < *k) { /* Use blocked code after the last block. The first kk columns are handled by the block method. */ ki = (*k - nx - 1) / nb * nb; /* Computing MIN */ i__1 = *k, i__2 = ki + nb; kk = min(i__1,i__2); /* Set A(1:kk,kk+1:n) to zero. */ i__1 = *n; for (j = kk + 1; j <= i__1; ++j) { i__2 = kk; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * a_dim1; a[i__3].r = 0.f, a[i__3].i = 0.f; /* L10: */ } /* L20: */ } } else { kk = 0; } /* Use unblocked code for the last or only block. */ if (kk < *n) { i__1 = *m - kk; i__2 = *n - kk; i__3 = *k - kk; cung2r_(&i__1, &i__2, &i__3, &a[kk + 1 + (kk + 1) * a_dim1], lda, & tau[kk + 1], &work[1], &iinfo); } if (kk > 0) { /* Use blocked code */ i__1 = -nb; for (i__ = ki + 1; i__1 < 0 ? i__ >= 1 : i__ <= 1; i__ += i__1) { /* Computing MIN */ i__2 = nb, i__3 = *k - i__ + 1; ib = min(i__2,i__3); if (i__ + ib <= *n) { /* Form the triangular factor of the block reflector H = H(i) H(i+1) . . . H(i+ib-1) */ i__2 = *m - i__ + 1; clarft_("Forward", "Columnwise", &i__2, &ib, &a[i__ + i__ * a_dim1], lda, &tau[i__], &work[1], &ldwork); /* Apply H to A(i:m,i+ib:n) from the left */ i__2 = *m - i__ + 1; i__3 = *n - i__ - ib + 1; clarfb_("Left", "No transpose", "Forward", "Columnwise", & i__2, &i__3, &ib, &a[i__ + i__ * a_dim1], lda, &work[ 1], &ldwork, &a[i__ + (i__ + ib) * a_dim1], lda, & work[ib + 1], &ldwork); } /* Apply H to rows i:m of current block */ i__2 = *m - i__ + 1; cung2r_(&i__2, &ib, &ib, &a[i__ + i__ * a_dim1], lda, &tau[i__], & work[1], &iinfo); /* Set rows 1:i-1 of current block to zero */ i__2 = i__ + ib - 1; for (j = i__; j <= i__2; ++j) { i__3 = i__ - 1; for (l = 1; l <= i__3; ++l) { i__4 = l + j * a_dim1; a[i__4].r = 0.f, a[i__4].i = 0.f; /* L30: */ } /* L40: */ } /* L50: */ } } work[1].r = (real) iws, work[1].i = 0.f; return 0; /* End of CUNGQR */ } /* cungqr_ */ /* Subroutine */ int cunm2l_(char *side, char *trans, integer *m, integer *n, integer *k, complex *a, integer *lda, complex *tau, complex *c__, integer *ldc, complex *work, integer *info) { /* System generated locals */ integer a_dim1, a_offset, c_dim1, c_offset, i__1, i__2, i__3; complex q__1; /* Builtin functions */ void r_cnjg(complex *, complex *); /* Local variables */ static integer i__, i1, i2, i3, mi, ni, nq; static complex aii; static logical left; static complex taui; extern /* Subroutine */ int clarf_(char *, integer *, integer *, complex * , integer *, complex *, complex *, integer *, complex *); extern logical lsame_(char *, char *); extern /* Subroutine */ int xerbla_(char *, integer *); static logical notran; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University September 30, 1994 Purpose ======= CUNM2L overwrites the general complex m-by-n matrix C with Q * C if SIDE = 'L' and TRANS = 'N', or Q'* C if SIDE = 'L' and TRANS = 'C', or C * Q if SIDE = 'R' and TRANS = 'N', or C * Q' if SIDE = 'R' and TRANS = 'C', where Q is a complex unitary matrix defined as the product of k elementary reflectors Q = H(k) . . . H(2) H(1) as returned by CGEQLF. Q is of order m if SIDE = 'L' and of order n if SIDE = 'R'. Arguments ========= SIDE (input) CHARACTER*1 = 'L': apply Q or Q' from the Left = 'R': apply Q or Q' from the Right TRANS (input) CHARACTER*1 = 'N': apply Q (No transpose) = 'C': apply Q' (Conjugate transpose) M (input) INTEGER The number of rows of the matrix C. M >= 0. N (input) INTEGER The number of columns of the matrix C. N >= 0. K (input) INTEGER The number of elementary reflectors whose product defines the matrix Q. If SIDE = 'L', M >= K >= 0; if SIDE = 'R', N >= K >= 0. A (input) COMPLEX array, dimension (LDA,K) The i-th column must contain the vector which defines the elementary reflector H(i), for i = 1,2,...,k, as returned by CGEQLF in the last k columns of its array argument A. A is modified by the routine but restored on exit. LDA (input) INTEGER The leading dimension of the array A. If SIDE = 'L', LDA >= max(1,M); if SIDE = 'R', LDA >= max(1,N). TAU (input) COMPLEX array, dimension (K) TAU(i) must contain the scalar factor of the elementary reflector H(i), as returned by CGEQLF. C (input/output) COMPLEX array, dimension (LDC,N) On entry, the m-by-n matrix C. On exit, C is overwritten by Q*C or Q'*C or C*Q' or C*Q. LDC (input) INTEGER The leading dimension of the array C. LDC >= max(1,M). WORK (workspace) COMPLEX array, dimension (N) if SIDE = 'L', (M) if SIDE = 'R' INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value ===================================================================== Test the input arguments */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --tau; c_dim1 = *ldc; c_offset = 1 + c_dim1; c__ -= c_offset; --work; /* Function Body */ *info = 0; left = lsame_(side, "L"); notran = lsame_(trans, "N"); /* NQ is the order of Q */ if (left) { nq = *m; } else { nq = *n; } if (! left && ! lsame_(side, "R")) { *info = -1; } else if (! notran && ! lsame_(trans, "C")) { *info = -2; } else if (*m < 0) { *info = -3; } else if (*n < 0) { *info = -4; } else if ((*k < 0) || (*k > nq)) { *info = -5; } else if (*lda < max(1,nq)) { *info = -7; } else if (*ldc < max(1,*m)) { *info = -10; } if (*info != 0) { i__1 = -(*info); xerbla_("CUNM2L", &i__1); return 0; } /* Quick return if possible */ if (((*m == 0) || (*n == 0)) || (*k == 0)) { return 0; } if ((left && notran) || (! left && ! notran)) { i1 = 1; i2 = *k; i3 = 1; } else { i1 = *k; i2 = 1; i3 = -1; } if (left) { ni = *n; } else { mi = *m; } i__1 = i2; i__2 = i3; for (i__ = i1; i__2 < 0 ? i__ >= i__1 : i__ <= i__1; i__ += i__2) { if (left) { /* H(i) or H(i)' is applied to C(1:m-k+i,1:n) */ mi = *m - *k + i__; } else { /* H(i) or H(i)' is applied to C(1:m,1:n-k+i) */ ni = *n - *k + i__; } /* Apply H(i) or H(i)' */ if (notran) { i__3 = i__; taui.r = tau[i__3].r, taui.i = tau[i__3].i; } else { r_cnjg(&q__1, &tau[i__]); taui.r = q__1.r, taui.i = q__1.i; } i__3 = nq - *k + i__ + i__ * a_dim1; aii.r = a[i__3].r, aii.i = a[i__3].i; i__3 = nq - *k + i__ + i__ * a_dim1; a[i__3].r = 1.f, a[i__3].i = 0.f; clarf_(side, &mi, &ni, &a[i__ * a_dim1 + 1], &c__1, &taui, &c__[ c_offset], ldc, &work[1]); i__3 = nq - *k + i__ + i__ * a_dim1; a[i__3].r = aii.r, a[i__3].i = aii.i; /* L10: */ } return 0; /* End of CUNM2L */ } /* cunm2l_ */ /* Subroutine */ int cunm2r_(char *side, char *trans, integer *m, integer *n, integer *k, complex *a, integer *lda, complex *tau, complex *c__, integer *ldc, complex *work, integer *info) { /* System generated locals */ integer a_dim1, a_offset, c_dim1, c_offset, i__1, i__2, i__3; complex q__1; /* Builtin functions */ void r_cnjg(complex *, complex *); /* Local variables */ static integer i__, i1, i2, i3, ic, jc, mi, ni, nq; static complex aii; static logical left; static complex taui; extern /* Subroutine */ int clarf_(char *, integer *, integer *, complex * , integer *, complex *, complex *, integer *, complex *); extern logical lsame_(char *, char *); extern /* Subroutine */ int xerbla_(char *, integer *); static logical notran; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University September 30, 1994 Purpose ======= CUNM2R overwrites the general complex m-by-n matrix C with Q * C if SIDE = 'L' and TRANS = 'N', or Q'* C if SIDE = 'L' and TRANS = 'C', or C * Q if SIDE = 'R' and TRANS = 'N', or C * Q' if SIDE = 'R' and TRANS = 'C', where Q is a complex unitary matrix defined as the product of k elementary reflectors Q = H(1) H(2) . . . H(k) as returned by CGEQRF. Q is of order m if SIDE = 'L' and of order n if SIDE = 'R'. Arguments ========= SIDE (input) CHARACTER*1 = 'L': apply Q or Q' from the Left = 'R': apply Q or Q' from the Right TRANS (input) CHARACTER*1 = 'N': apply Q (No transpose) = 'C': apply Q' (Conjugate transpose) M (input) INTEGER The number of rows of the matrix C. M >= 0. N (input) INTEGER The number of columns of the matrix C. N >= 0. K (input) INTEGER The number of elementary reflectors whose product defines the matrix Q. If SIDE = 'L', M >= K >= 0; if SIDE = 'R', N >= K >= 0. A (input) COMPLEX array, dimension (LDA,K) The i-th column must contain the vector which defines the elementary reflector H(i), for i = 1,2,...,k, as returned by CGEQRF in the first k columns of its array argument A. A is modified by the routine but restored on exit. LDA (input) INTEGER The leading dimension of the array A. If SIDE = 'L', LDA >= max(1,M); if SIDE = 'R', LDA >= max(1,N). TAU (input) COMPLEX array, dimension (K) TAU(i) must contain the scalar factor of the elementary reflector H(i), as returned by CGEQRF. C (input/output) COMPLEX array, dimension (LDC,N) On entry, the m-by-n matrix C. On exit, C is overwritten by Q*C or Q'*C or C*Q' or C*Q. LDC (input) INTEGER The leading dimension of the array C. LDC >= max(1,M). WORK (workspace) COMPLEX array, dimension (N) if SIDE = 'L', (M) if SIDE = 'R' INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value ===================================================================== Test the input arguments */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --tau; c_dim1 = *ldc; c_offset = 1 + c_dim1; c__ -= c_offset; --work; /* Function Body */ *info = 0; left = lsame_(side, "L"); notran = lsame_(trans, "N"); /* NQ is the order of Q */ if (left) { nq = *m; } else { nq = *n; } if (! left && ! lsame_(side, "R")) { *info = -1; } else if (! notran && ! lsame_(trans, "C")) { *info = -2; } else if (*m < 0) { *info = -3; } else if (*n < 0) { *info = -4; } else if ((*k < 0) || (*k > nq)) { *info = -5; } else if (*lda < max(1,nq)) { *info = -7; } else if (*ldc < max(1,*m)) { *info = -10; } if (*info != 0) { i__1 = -(*info); xerbla_("CUNM2R", &i__1); return 0; } /* Quick return if possible */ if (((*m == 0) || (*n == 0)) || (*k == 0)) { return 0; } if ((left && ! notran) || (! left && notran)) { i1 = 1; i2 = *k; i3 = 1; } else { i1 = *k; i2 = 1; i3 = -1; } if (left) { ni = *n; jc = 1; } else { mi = *m; ic = 1; } i__1 = i2; i__2 = i3; for (i__ = i1; i__2 < 0 ? i__ >= i__1 : i__ <= i__1; i__ += i__2) { if (left) { /* H(i) or H(i)' is applied to C(i:m,1:n) */ mi = *m - i__ + 1; ic = i__; } else { /* H(i) or H(i)' is applied to C(1:m,i:n) */ ni = *n - i__ + 1; jc = i__; } /* Apply H(i) or H(i)' */ if (notran) { i__3 = i__; taui.r = tau[i__3].r, taui.i = tau[i__3].i; } else { r_cnjg(&q__1, &tau[i__]); taui.r = q__1.r, taui.i = q__1.i; } i__3 = i__ + i__ * a_dim1; aii.r = a[i__3].r, aii.i = a[i__3].i; i__3 = i__ + i__ * a_dim1; a[i__3].r = 1.f, a[i__3].i = 0.f; clarf_(side, &mi, &ni, &a[i__ + i__ * a_dim1], &c__1, &taui, &c__[ic + jc * c_dim1], ldc, &work[1]); i__3 = i__ + i__ * a_dim1; a[i__3].r = aii.r, a[i__3].i = aii.i; /* L10: */ } return 0; /* End of CUNM2R */ } /* cunm2r_ */ /* Subroutine */ int cunmbr_(char *vect, char *side, char *trans, integer *m, integer *n, integer *k, complex *a, integer *lda, complex *tau, complex *c__, integer *ldc, complex *work, integer *lwork, integer * info) { /* System generated locals */ address a__1[2]; integer a_dim1, a_offset, c_dim1, c_offset, i__1, i__2, i__3[2]; char ch__1[2]; /* Builtin functions */ /* Subroutine */ int s_cat(char *, char **, integer *, integer *, ftnlen); /* Local variables */ static integer i1, i2, nb, mi, ni, nq, nw; static logical left; extern logical lsame_(char *, char *); static integer iinfo; extern /* Subroutine */ int xerbla_(char *, integer *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); extern /* Subroutine */ int cunmlq_(char *, char *, integer *, integer *, integer *, complex *, integer *, complex *, complex *, integer *, complex *, integer *, integer *); static logical notran; extern /* Subroutine */ int cunmqr_(char *, char *, integer *, integer *, integer *, complex *, integer *, complex *, complex *, integer *, complex *, integer *, integer *); static logical applyq; static char transt[1]; static integer lwkopt; static logical lquery; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= If VECT = 'Q', CUNMBR overwrites the general complex M-by-N matrix C with SIDE = 'L' SIDE = 'R' TRANS = 'N': Q * C C * Q TRANS = 'C': Q**H * C C * Q**H If VECT = 'P', CUNMBR overwrites the general complex M-by-N matrix C with SIDE = 'L' SIDE = 'R' TRANS = 'N': P * C C * P TRANS = 'C': P**H * C C * P**H Here Q and P**H are the unitary matrices determined by CGEBRD when reducing a complex matrix A to bidiagonal form: A = Q * B * P**H. Q and P**H are defined as products of elementary reflectors H(i) and G(i) respectively. Let nq = m if SIDE = 'L' and nq = n if SIDE = 'R'. Thus nq is the order of the unitary matrix Q or P**H that is applied. If VECT = 'Q', A is assumed to have been an NQ-by-K matrix: if nq >= k, Q = H(1) H(2) . . . H(k); if nq < k, Q = H(1) H(2) . . . H(nq-1). If VECT = 'P', A is assumed to have been a K-by-NQ matrix: if k < nq, P = G(1) G(2) . . . G(k); if k >= nq, P = G(1) G(2) . . . G(nq-1). Arguments ========= VECT (input) CHARACTER*1 = 'Q': apply Q or Q**H; = 'P': apply P or P**H. SIDE (input) CHARACTER*1 = 'L': apply Q, Q**H, P or P**H from the Left; = 'R': apply Q, Q**H, P or P**H from the Right. TRANS (input) CHARACTER*1 = 'N': No transpose, apply Q or P; = 'C': Conjugate transpose, apply Q**H or P**H. M (input) INTEGER The number of rows of the matrix C. M >= 0. N (input) INTEGER The number of columns of the matrix C. N >= 0. K (input) INTEGER If VECT = 'Q', the number of columns in the original matrix reduced by CGEBRD. If VECT = 'P', the number of rows in the original matrix reduced by CGEBRD. K >= 0. A (input) COMPLEX array, dimension (LDA,min(nq,K)) if VECT = 'Q' (LDA,nq) if VECT = 'P' The vectors which define the elementary reflectors H(i) and G(i), whose products determine the matrices Q and P, as returned by CGEBRD. LDA (input) INTEGER The leading dimension of the array A. If VECT = 'Q', LDA >= max(1,nq); if VECT = 'P', LDA >= max(1,min(nq,K)). TAU (input) COMPLEX array, dimension (min(nq,K)) TAU(i) must contain the scalar factor of the elementary reflector H(i) or G(i) which determines Q or P, as returned by CGEBRD in the array argument TAUQ or TAUP. C (input/output) COMPLEX array, dimension (LDC,N) On entry, the M-by-N matrix C. On exit, C is overwritten by Q*C or Q**H*C or C*Q**H or C*Q or P*C or P**H*C or C*P or C*P**H. LDC (input) INTEGER The leading dimension of the array C. LDC >= max(1,M). WORK (workspace/output) COMPLEX array, dimension (LWORK) On exit, if INFO = 0, WORK(1) returns the optimal LWORK. LWORK (input) INTEGER The dimension of the array WORK. If SIDE = 'L', LWORK >= max(1,N); if SIDE = 'R', LWORK >= max(1,M). For optimum performance LWORK >= N*NB if SIDE = 'L', and LWORK >= M*NB if SIDE = 'R', where NB is the optimal blocksize. If LWORK = -1, then a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued by XERBLA. INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value ===================================================================== Test the input arguments */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --tau; c_dim1 = *ldc; c_offset = 1 + c_dim1; c__ -= c_offset; --work; /* Function Body */ *info = 0; applyq = lsame_(vect, "Q"); left = lsame_(side, "L"); notran = lsame_(trans, "N"); lquery = *lwork == -1; /* NQ is the order of Q or P and NW is the minimum dimension of WORK */ if (left) { nq = *m; nw = *n; } else { nq = *n; nw = *m; } if (! applyq && ! lsame_(vect, "P")) { *info = -1; } else if (! left && ! lsame_(side, "R")) { *info = -2; } else if (! notran && ! lsame_(trans, "C")) { *info = -3; } else if (*m < 0) { *info = -4; } else if (*n < 0) { *info = -5; } else if (*k < 0) { *info = -6; } else /* if(complicated condition) */ { /* Computing MAX */ i__1 = 1, i__2 = min(nq,*k); if ((applyq && *lda < max(1,nq)) || (! applyq && *lda < max(i__1,i__2) )) { *info = -8; } else if (*ldc < max(1,*m)) { *info = -11; } else if (*lwork < max(1,nw) && ! lquery) { *info = -13; } } if (*info == 0) { if (applyq) { if (left) { /* Writing concatenation */ i__3[0] = 1, a__1[0] = side; i__3[1] = 1, a__1[1] = trans; s_cat(ch__1, a__1, i__3, &c__2, (ftnlen)2); i__1 = *m - 1; i__2 = *m - 1; nb = ilaenv_(&c__1, "CUNMQR", ch__1, &i__1, n, &i__2, &c_n1, ( ftnlen)6, (ftnlen)2); } else { /* Writing concatenation */ i__3[0] = 1, a__1[0] = side; i__3[1] = 1, a__1[1] = trans; s_cat(ch__1, a__1, i__3, &c__2, (ftnlen)2); i__1 = *n - 1; i__2 = *n - 1; nb = ilaenv_(&c__1, "CUNMQR", ch__1, m, &i__1, &i__2, &c_n1, ( ftnlen)6, (ftnlen)2); } } else { if (left) { /* Writing concatenation */ i__3[0] = 1, a__1[0] = side; i__3[1] = 1, a__1[1] = trans; s_cat(ch__1, a__1, i__3, &c__2, (ftnlen)2); i__1 = *m - 1; i__2 = *m - 1; nb = ilaenv_(&c__1, "CUNMLQ", ch__1, &i__1, n, &i__2, &c_n1, ( ftnlen)6, (ftnlen)2); } else { /* Writing concatenation */ i__3[0] = 1, a__1[0] = side; i__3[1] = 1, a__1[1] = trans; s_cat(ch__1, a__1, i__3, &c__2, (ftnlen)2); i__1 = *n - 1; i__2 = *n - 1; nb = ilaenv_(&c__1, "CUNMLQ", ch__1, m, &i__1, &i__2, &c_n1, ( ftnlen)6, (ftnlen)2); } } lwkopt = max(1,nw) * nb; work[1].r = (real) lwkopt, work[1].i = 0.f; } if (*info != 0) { i__1 = -(*info); xerbla_("CUNMBR", &i__1); return 0; } else if (lquery) { } /* Quick return if possible */ work[1].r = 1.f, work[1].i = 0.f; if ((*m == 0) || (*n == 0)) { return 0; } if (applyq) { /* Apply Q */ if (nq >= *k) { /* Q was determined by a call to CGEBRD with nq >= k */ cunmqr_(side, trans, m, n, k, &a[a_offset], lda, &tau[1], &c__[ c_offset], ldc, &work[1], lwork, &iinfo); } else if (nq > 1) { /* Q was determined by a call to CGEBRD with nq < k */ if (left) { mi = *m - 1; ni = *n; i1 = 2; i2 = 1; } else { mi = *m; ni = *n - 1; i1 = 1; i2 = 2; } i__1 = nq - 1; cunmqr_(side, trans, &mi, &ni, &i__1, &a[a_dim1 + 2], lda, &tau[1] , &c__[i1 + i2 * c_dim1], ldc, &work[1], lwork, &iinfo); } } else { /* Apply P */ if (notran) { *(unsigned char *)transt = 'C'; } else { *(unsigned char *)transt = 'N'; } if (nq > *k) { /* P was determined by a call to CGEBRD with nq > k */ cunmlq_(side, transt, m, n, k, &a[a_offset], lda, &tau[1], &c__[ c_offset], ldc, &work[1], lwork, &iinfo); } else if (nq > 1) { /* P was determined by a call to CGEBRD with nq <= k */ if (left) { mi = *m - 1; ni = *n; i1 = 2; i2 = 1; } else { mi = *m; ni = *n - 1; i1 = 1; i2 = 2; } i__1 = nq - 1; cunmlq_(side, transt, &mi, &ni, &i__1, &a[((a_dim1) << (1)) + 1], lda, &tau[1], &c__[i1 + i2 * c_dim1], ldc, &work[1], lwork, &iinfo); } } work[1].r = (real) lwkopt, work[1].i = 0.f; return 0; /* End of CUNMBR */ } /* cunmbr_ */ /* Subroutine */ int cunml2_(char *side, char *trans, integer *m, integer *n, integer *k, complex *a, integer *lda, complex *tau, complex *c__, integer *ldc, complex *work, integer *info) { /* System generated locals */ integer a_dim1, a_offset, c_dim1, c_offset, i__1, i__2, i__3; complex q__1; /* Builtin functions */ void r_cnjg(complex *, complex *); /* Local variables */ static integer i__, i1, i2, i3, ic, jc, mi, ni, nq; static complex aii; static logical left; static complex taui; extern /* Subroutine */ int clarf_(char *, integer *, integer *, complex * , integer *, complex *, complex *, integer *, complex *); extern logical lsame_(char *, char *); extern /* Subroutine */ int clacgv_(integer *, complex *, integer *), xerbla_(char *, integer *); static logical notran; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University September 30, 1994 Purpose ======= CUNML2 overwrites the general complex m-by-n matrix C with Q * C if SIDE = 'L' and TRANS = 'N', or Q'* C if SIDE = 'L' and TRANS = 'C', or C * Q if SIDE = 'R' and TRANS = 'N', or C * Q' if SIDE = 'R' and TRANS = 'C', where Q is a complex unitary matrix defined as the product of k elementary reflectors Q = H(k)' . . . H(2)' H(1)' as returned by CGELQF. Q is of order m if SIDE = 'L' and of order n if SIDE = 'R'. Arguments ========= SIDE (input) CHARACTER*1 = 'L': apply Q or Q' from the Left = 'R': apply Q or Q' from the Right TRANS (input) CHARACTER*1 = 'N': apply Q (No transpose) = 'C': apply Q' (Conjugate transpose) M (input) INTEGER The number of rows of the matrix C. M >= 0. N (input) INTEGER The number of columns of the matrix C. N >= 0. K (input) INTEGER The number of elementary reflectors whose product defines the matrix Q. If SIDE = 'L', M >= K >= 0; if SIDE = 'R', N >= K >= 0. A (input) COMPLEX array, dimension (LDA,M) if SIDE = 'L', (LDA,N) if SIDE = 'R' The i-th row must contain the vector which defines the elementary reflector H(i), for i = 1,2,...,k, as returned by CGELQF in the first k rows of its array argument A. A is modified by the routine but restored on exit. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,K). TAU (input) COMPLEX array, dimension (K) TAU(i) must contain the scalar factor of the elementary reflector H(i), as returned by CGELQF. C (input/output) COMPLEX array, dimension (LDC,N) On entry, the m-by-n matrix C. On exit, C is overwritten by Q*C or Q'*C or C*Q' or C*Q. LDC (input) INTEGER The leading dimension of the array C. LDC >= max(1,M). WORK (workspace) COMPLEX array, dimension (N) if SIDE = 'L', (M) if SIDE = 'R' INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value ===================================================================== Test the input arguments */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --tau; c_dim1 = *ldc; c_offset = 1 + c_dim1; c__ -= c_offset; --work; /* Function Body */ *info = 0; left = lsame_(side, "L"); notran = lsame_(trans, "N"); /* NQ is the order of Q */ if (left) { nq = *m; } else { nq = *n; } if (! left && ! lsame_(side, "R")) { *info = -1; } else if (! notran && ! lsame_(trans, "C")) { *info = -2; } else if (*m < 0) { *info = -3; } else if (*n < 0) { *info = -4; } else if ((*k < 0) || (*k > nq)) { *info = -5; } else if (*lda < max(1,*k)) { *info = -7; } else if (*ldc < max(1,*m)) { *info = -10; } if (*info != 0) { i__1 = -(*info); xerbla_("CUNML2", &i__1); return 0; } /* Quick return if possible */ if (((*m == 0) || (*n == 0)) || (*k == 0)) { return 0; } if ((left && notran) || (! left && ! notran)) { i1 = 1; i2 = *k; i3 = 1; } else { i1 = *k; i2 = 1; i3 = -1; } if (left) { ni = *n; jc = 1; } else { mi = *m; ic = 1; } i__1 = i2; i__2 = i3; for (i__ = i1; i__2 < 0 ? i__ >= i__1 : i__ <= i__1; i__ += i__2) { if (left) { /* H(i) or H(i)' is applied to C(i:m,1:n) */ mi = *m - i__ + 1; ic = i__; } else { /* H(i) or H(i)' is applied to C(1:m,i:n) */ ni = *n - i__ + 1; jc = i__; } /* Apply H(i) or H(i)' */ if (notran) { r_cnjg(&q__1, &tau[i__]); taui.r = q__1.r, taui.i = q__1.i; } else { i__3 = i__; taui.r = tau[i__3].r, taui.i = tau[i__3].i; } if (i__ < nq) { i__3 = nq - i__; clacgv_(&i__3, &a[i__ + (i__ + 1) * a_dim1], lda); } i__3 = i__ + i__ * a_dim1; aii.r = a[i__3].r, aii.i = a[i__3].i; i__3 = i__ + i__ * a_dim1; a[i__3].r = 1.f, a[i__3].i = 0.f; clarf_(side, &mi, &ni, &a[i__ + i__ * a_dim1], lda, &taui, &c__[ic + jc * c_dim1], ldc, &work[1]); i__3 = i__ + i__ * a_dim1; a[i__3].r = aii.r, a[i__3].i = aii.i; if (i__ < nq) { i__3 = nq - i__; clacgv_(&i__3, &a[i__ + (i__ + 1) * a_dim1], lda); } /* L10: */ } return 0; /* End of CUNML2 */ } /* cunml2_ */ /* Subroutine */ int cunmlq_(char *side, char *trans, integer *m, integer *n, integer *k, complex *a, integer *lda, complex *tau, complex *c__, integer *ldc, complex *work, integer *lwork, integer *info) { /* System generated locals */ address a__1[2]; integer a_dim1, a_offset, c_dim1, c_offset, i__1, i__2, i__3[2], i__4, i__5; char ch__1[2]; /* Builtin functions */ /* Subroutine */ int s_cat(char *, char **, integer *, integer *, ftnlen); /* Local variables */ static integer i__; static complex t[4160] /* was [65][64] */; static integer i1, i2, i3, ib, ic, jc, nb, mi, ni, nq, nw, iws; static logical left; extern logical lsame_(char *, char *); static integer nbmin, iinfo; extern /* Subroutine */ int cunml2_(char *, char *, integer *, integer *, integer *, complex *, integer *, complex *, complex *, integer *, complex *, integer *), clarfb_(char *, char *, char *, char *, integer *, integer *, integer *, complex *, integer *, complex *, integer *, complex *, integer *, complex *, integer *), clarft_(char *, char * , integer *, integer *, complex *, integer *, complex *, complex * , integer *), xerbla_(char *, integer *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); static logical notran; static integer ldwork; static char transt[1]; static integer lwkopt; static logical lquery; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= CUNMLQ overwrites the general complex M-by-N matrix C with SIDE = 'L' SIDE = 'R' TRANS = 'N': Q * C C * Q TRANS = 'C': Q**H * C C * Q**H where Q is a complex unitary matrix defined as the product of k elementary reflectors Q = H(k)' . . . H(2)' H(1)' as returned by CGELQF. Q is of order M if SIDE = 'L' and of order N if SIDE = 'R'. Arguments ========= SIDE (input) CHARACTER*1 = 'L': apply Q or Q**H from the Left; = 'R': apply Q or Q**H from the Right. TRANS (input) CHARACTER*1 = 'N': No transpose, apply Q; = 'C': Conjugate transpose, apply Q**H. M (input) INTEGER The number of rows of the matrix C. M >= 0. N (input) INTEGER The number of columns of the matrix C. N >= 0. K (input) INTEGER The number of elementary reflectors whose product defines the matrix Q. If SIDE = 'L', M >= K >= 0; if SIDE = 'R', N >= K >= 0. A (input) COMPLEX array, dimension (LDA,M) if SIDE = 'L', (LDA,N) if SIDE = 'R' The i-th row must contain the vector which defines the elementary reflector H(i), for i = 1,2,...,k, as returned by CGELQF in the first k rows of its array argument A. A is modified by the routine but restored on exit. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,K). TAU (input) COMPLEX array, dimension (K) TAU(i) must contain the scalar factor of the elementary reflector H(i), as returned by CGELQF. C (input/output) COMPLEX array, dimension (LDC,N) On entry, the M-by-N matrix C. On exit, C is overwritten by Q*C or Q**H*C or C*Q**H or C*Q. LDC (input) INTEGER The leading dimension of the array C. LDC >= max(1,M). WORK (workspace/output) COMPLEX array, dimension (LWORK) On exit, if INFO = 0, WORK(1) returns the optimal LWORK. LWORK (input) INTEGER The dimension of the array WORK. If SIDE = 'L', LWORK >= max(1,N); if SIDE = 'R', LWORK >= max(1,M). For optimum performance LWORK >= N*NB if SIDE 'L', and LWORK >= M*NB if SIDE = 'R', where NB is the optimal blocksize. If LWORK = -1, then a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued by XERBLA. INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value ===================================================================== Test the input arguments */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --tau; c_dim1 = *ldc; c_offset = 1 + c_dim1; c__ -= c_offset; --work; /* Function Body */ *info = 0; left = lsame_(side, "L"); notran = lsame_(trans, "N"); lquery = *lwork == -1; /* NQ is the order of Q and NW is the minimum dimension of WORK */ if (left) { nq = *m; nw = *n; } else { nq = *n; nw = *m; } if (! left && ! lsame_(side, "R")) { *info = -1; } else if (! notran && ! lsame_(trans, "C")) { *info = -2; } else if (*m < 0) { *info = -3; } else if (*n < 0) { *info = -4; } else if ((*k < 0) || (*k > nq)) { *info = -5; } else if (*lda < max(1,*k)) { *info = -7; } else if (*ldc < max(1,*m)) { *info = -10; } else if (*lwork < max(1,nw) && ! lquery) { *info = -12; } if (*info == 0) { /* Determine the block size. NB may be at most NBMAX, where NBMAX is used to define the local array T. Computing MIN Writing concatenation */ i__3[0] = 1, a__1[0] = side; i__3[1] = 1, a__1[1] = trans; s_cat(ch__1, a__1, i__3, &c__2, (ftnlen)2); i__1 = 64, i__2 = ilaenv_(&c__1, "CUNMLQ", ch__1, m, n, k, &c_n1, ( ftnlen)6, (ftnlen)2); nb = min(i__1,i__2); lwkopt = max(1,nw) * nb; work[1].r = (real) lwkopt, work[1].i = 0.f; } if (*info != 0) { i__1 = -(*info); xerbla_("CUNMLQ", &i__1); return 0; } else if (lquery) { return 0; } /* Quick return if possible */ if (((*m == 0) || (*n == 0)) || (*k == 0)) { work[1].r = 1.f, work[1].i = 0.f; return 0; } nbmin = 2; ldwork = nw; if (nb > 1 && nb < *k) { iws = nw * nb; if (*lwork < iws) { nb = *lwork / ldwork; /* Computing MAX Writing concatenation */ i__3[0] = 1, a__1[0] = side; i__3[1] = 1, a__1[1] = trans; s_cat(ch__1, a__1, i__3, &c__2, (ftnlen)2); i__1 = 2, i__2 = ilaenv_(&c__2, "CUNMLQ", ch__1, m, n, k, &c_n1, ( ftnlen)6, (ftnlen)2); nbmin = max(i__1,i__2); } } else { iws = nw; } if ((nb < nbmin) || (nb >= *k)) { /* Use unblocked code */ cunml2_(side, trans, m, n, k, &a[a_offset], lda, &tau[1], &c__[ c_offset], ldc, &work[1], &iinfo); } else { /* Use blocked code */ if ((left && notran) || (! left && ! notran)) { i1 = 1; i2 = *k; i3 = nb; } else { i1 = (*k - 1) / nb * nb + 1; i2 = 1; i3 = -nb; } if (left) { ni = *n; jc = 1; } else { mi = *m; ic = 1; } if (notran) { *(unsigned char *)transt = 'C'; } else { *(unsigned char *)transt = 'N'; } i__1 = i2; i__2 = i3; for (i__ = i1; i__2 < 0 ? i__ >= i__1 : i__ <= i__1; i__ += i__2) { /* Computing MIN */ i__4 = nb, i__5 = *k - i__ + 1; ib = min(i__4,i__5); /* Form the triangular factor of the block reflector H = H(i) H(i+1) . . . H(i+ib-1) */ i__4 = nq - i__ + 1; clarft_("Forward", "Rowwise", &i__4, &ib, &a[i__ + i__ * a_dim1], lda, &tau[i__], t, &c__65); if (left) { /* H or H' is applied to C(i:m,1:n) */ mi = *m - i__ + 1; ic = i__; } else { /* H or H' is applied to C(1:m,i:n) */ ni = *n - i__ + 1; jc = i__; } /* Apply H or H' */ clarfb_(side, transt, "Forward", "Rowwise", &mi, &ni, &ib, &a[i__ + i__ * a_dim1], lda, t, &c__65, &c__[ic + jc * c_dim1], ldc, &work[1], &ldwork); /* L10: */ } } work[1].r = (real) lwkopt, work[1].i = 0.f; return 0; /* End of CUNMLQ */ } /* cunmlq_ */ /* Subroutine */ int cunmql_(char *side, char *trans, integer *m, integer *n, integer *k, complex *a, integer *lda, complex *tau, complex *c__, integer *ldc, complex *work, integer *lwork, integer *info) { /* System generated locals */ address a__1[2]; integer a_dim1, a_offset, c_dim1, c_offset, i__1, i__2, i__3[2], i__4, i__5; char ch__1[2]; /* Builtin functions */ /* Subroutine */ int s_cat(char *, char **, integer *, integer *, ftnlen); /* Local variables */ static integer i__; static complex t[4160] /* was [65][64] */; static integer i1, i2, i3, ib, nb, mi, ni, nq, nw, iws; static logical left; extern logical lsame_(char *, char *); static integer nbmin, iinfo; extern /* Subroutine */ int cunm2l_(char *, char *, integer *, integer *, integer *, complex *, integer *, complex *, complex *, integer *, complex *, integer *), clarfb_(char *, char *, char *, char *, integer *, integer *, integer *, complex *, integer *, complex *, integer *, complex *, integer *, complex *, integer *), clarft_(char *, char * , integer *, integer *, complex *, integer *, complex *, complex * , integer *), xerbla_(char *, integer *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); static logical notran; static integer ldwork, lwkopt; static logical lquery; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= CUNMQL overwrites the general complex M-by-N matrix C with SIDE = 'L' SIDE = 'R' TRANS = 'N': Q * C C * Q TRANS = 'C': Q**H * C C * Q**H where Q is a complex unitary matrix defined as the product of k elementary reflectors Q = H(k) . . . H(2) H(1) as returned by CGEQLF. Q is of order M if SIDE = 'L' and of order N if SIDE = 'R'. Arguments ========= SIDE (input) CHARACTER*1 = 'L': apply Q or Q**H from the Left; = 'R': apply Q or Q**H from the Right. TRANS (input) CHARACTER*1 = 'N': No transpose, apply Q; = 'C': Transpose, apply Q**H. M (input) INTEGER The number of rows of the matrix C. M >= 0. N (input) INTEGER The number of columns of the matrix C. N >= 0. K (input) INTEGER The number of elementary reflectors whose product defines the matrix Q. If SIDE = 'L', M >= K >= 0; if SIDE = 'R', N >= K >= 0. A (input) COMPLEX array, dimension (LDA,K) The i-th column must contain the vector which defines the elementary reflector H(i), for i = 1,2,...,k, as returned by CGEQLF in the last k columns of its array argument A. A is modified by the routine but restored on exit. LDA (input) INTEGER The leading dimension of the array A. If SIDE = 'L', LDA >= max(1,M); if SIDE = 'R', LDA >= max(1,N). TAU (input) COMPLEX array, dimension (K) TAU(i) must contain the scalar factor of the elementary reflector H(i), as returned by CGEQLF. C (input/output) COMPLEX array, dimension (LDC,N) On entry, the M-by-N matrix C. On exit, C is overwritten by Q*C or Q**H*C or C*Q**H or C*Q. LDC (input) INTEGER The leading dimension of the array C. LDC >= max(1,M). WORK (workspace/output) COMPLEX array, dimension (LWORK) On exit, if INFO = 0, WORK(1) returns the optimal LWORK. LWORK (input) INTEGER The dimension of the array WORK. If SIDE = 'L', LWORK >= max(1,N); if SIDE = 'R', LWORK >= max(1,M). For optimum performance LWORK >= N*NB if SIDE = 'L', and LWORK >= M*NB if SIDE = 'R', where NB is the optimal blocksize. If LWORK = -1, then a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued by XERBLA. INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value ===================================================================== Test the input arguments */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --tau; c_dim1 = *ldc; c_offset = 1 + c_dim1; c__ -= c_offset; --work; /* Function Body */ *info = 0; left = lsame_(side, "L"); notran = lsame_(trans, "N"); lquery = *lwork == -1; /* NQ is the order of Q and NW is the minimum dimension of WORK */ if (left) { nq = *m; nw = *n; } else { nq = *n; nw = *m; } if (! left && ! lsame_(side, "R")) { *info = -1; } else if (! notran && ! lsame_(trans, "C")) { *info = -2; } else if (*m < 0) { *info = -3; } else if (*n < 0) { *info = -4; } else if ((*k < 0) || (*k > nq)) { *info = -5; } else if (*lda < max(1,nq)) { *info = -7; } else if (*ldc < max(1,*m)) { *info = -10; } else if (*lwork < max(1,nw) && ! lquery) { *info = -12; } if (*info == 0) { /* Determine the block size. NB may be at most NBMAX, where NBMAX is used to define the local array T. Computing MIN Writing concatenation */ i__3[0] = 1, a__1[0] = side; i__3[1] = 1, a__1[1] = trans; s_cat(ch__1, a__1, i__3, &c__2, (ftnlen)2); i__1 = 64, i__2 = ilaenv_(&c__1, "CUNMQL", ch__1, m, n, k, &c_n1, ( ftnlen)6, (ftnlen)2); nb = min(i__1,i__2); lwkopt = max(1,nw) * nb; work[1].r = (real) lwkopt, work[1].i = 0.f; } if (*info != 0) { i__1 = -(*info); xerbla_("CUNMQL", &i__1); return 0; } else if (lquery) { return 0; } /* Quick return if possible */ if (((*m == 0) || (*n == 0)) || (*k == 0)) { work[1].r = 1.f, work[1].i = 0.f; return 0; } nbmin = 2; ldwork = nw; if (nb > 1 && nb < *k) { iws = nw * nb; if (*lwork < iws) { nb = *lwork / ldwork; /* Computing MAX Writing concatenation */ i__3[0] = 1, a__1[0] = side; i__3[1] = 1, a__1[1] = trans; s_cat(ch__1, a__1, i__3, &c__2, (ftnlen)2); i__1 = 2, i__2 = ilaenv_(&c__2, "CUNMQL", ch__1, m, n, k, &c_n1, ( ftnlen)6, (ftnlen)2); nbmin = max(i__1,i__2); } } else { iws = nw; } if ((nb < nbmin) || (nb >= *k)) { /* Use unblocked code */ cunm2l_(side, trans, m, n, k, &a[a_offset], lda, &tau[1], &c__[ c_offset], ldc, &work[1], &iinfo); } else { /* Use blocked code */ if ((left && notran) || (! left && ! notran)) { i1 = 1; i2 = *k; i3 = nb; } else { i1 = (*k - 1) / nb * nb + 1; i2 = 1; i3 = -nb; } if (left) { ni = *n; } else { mi = *m; } i__1 = i2; i__2 = i3; for (i__ = i1; i__2 < 0 ? i__ >= i__1 : i__ <= i__1; i__ += i__2) { /* Computing MIN */ i__4 = nb, i__5 = *k - i__ + 1; ib = min(i__4,i__5); /* Form the triangular factor of the block reflector H = H(i+ib-1) . . . H(i+1) H(i) */ i__4 = nq - *k + i__ + ib - 1; clarft_("Backward", "Columnwise", &i__4, &ib, &a[i__ * a_dim1 + 1] , lda, &tau[i__], t, &c__65); if (left) { /* H or H' is applied to C(1:m-k+i+ib-1,1:n) */ mi = *m - *k + i__ + ib - 1; } else { /* H or H' is applied to C(1:m,1:n-k+i+ib-1) */ ni = *n - *k + i__ + ib - 1; } /* Apply H or H' */ clarfb_(side, trans, "Backward", "Columnwise", &mi, &ni, &ib, &a[ i__ * a_dim1 + 1], lda, t, &c__65, &c__[c_offset], ldc, & work[1], &ldwork); /* L10: */ } } work[1].r = (real) lwkopt, work[1].i = 0.f; return 0; /* End of CUNMQL */ } /* cunmql_ */ /* Subroutine */ int cunmqr_(char *side, char *trans, integer *m, integer *n, integer *k, complex *a, integer *lda, complex *tau, complex *c__, integer *ldc, complex *work, integer *lwork, integer *info) { /* System generated locals */ address a__1[2]; integer a_dim1, a_offset, c_dim1, c_offset, i__1, i__2, i__3[2], i__4, i__5; char ch__1[2]; /* Builtin functions */ /* Subroutine */ int s_cat(char *, char **, integer *, integer *, ftnlen); /* Local variables */ static integer i__; static complex t[4160] /* was [65][64] */; static integer i1, i2, i3, ib, ic, jc, nb, mi, ni, nq, nw, iws; static logical left; extern logical lsame_(char *, char *); static integer nbmin, iinfo; extern /* Subroutine */ int cunm2r_(char *, char *, integer *, integer *, integer *, complex *, integer *, complex *, complex *, integer *, complex *, integer *), clarfb_(char *, char *, char *, char *, integer *, integer *, integer *, complex *, integer *, complex *, integer *, complex *, integer *, complex *, integer *), clarft_(char *, char * , integer *, integer *, complex *, integer *, complex *, complex * , integer *), xerbla_(char *, integer *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); static logical notran; static integer ldwork, lwkopt; static logical lquery; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= CUNMQR overwrites the general complex M-by-N matrix C with SIDE = 'L' SIDE = 'R' TRANS = 'N': Q * C C * Q TRANS = 'C': Q**H * C C * Q**H where Q is a complex unitary matrix defined as the product of k elementary reflectors Q = H(1) H(2) . . . H(k) as returned by CGEQRF. Q is of order M if SIDE = 'L' and of order N if SIDE = 'R'. Arguments ========= SIDE (input) CHARACTER*1 = 'L': apply Q or Q**H from the Left; = 'R': apply Q or Q**H from the Right. TRANS (input) CHARACTER*1 = 'N': No transpose, apply Q; = 'C': Conjugate transpose, apply Q**H. M (input) INTEGER The number of rows of the matrix C. M >= 0. N (input) INTEGER The number of columns of the matrix C. N >= 0. K (input) INTEGER The number of elementary reflectors whose product defines the matrix Q. If SIDE = 'L', M >= K >= 0; if SIDE = 'R', N >= K >= 0. A (input) COMPLEX array, dimension (LDA,K) The i-th column must contain the vector which defines the elementary reflector H(i), for i = 1,2,...,k, as returned by CGEQRF in the first k columns of its array argument A. A is modified by the routine but restored on exit. LDA (input) INTEGER The leading dimension of the array A. If SIDE = 'L', LDA >= max(1,M); if SIDE = 'R', LDA >= max(1,N). TAU (input) COMPLEX array, dimension (K) TAU(i) must contain the scalar factor of the elementary reflector H(i), as returned by CGEQRF. C (input/output) COMPLEX array, dimension (LDC,N) On entry, the M-by-N matrix C. On exit, C is overwritten by Q*C or Q**H*C or C*Q**H or C*Q. LDC (input) INTEGER The leading dimension of the array C. LDC >= max(1,M). WORK (workspace/output) COMPLEX array, dimension (LWORK) On exit, if INFO = 0, WORK(1) returns the optimal LWORK. LWORK (input) INTEGER The dimension of the array WORK. If SIDE = 'L', LWORK >= max(1,N); if SIDE = 'R', LWORK >= max(1,M). For optimum performance LWORK >= N*NB if SIDE = 'L', and LWORK >= M*NB if SIDE = 'R', where NB is the optimal blocksize. If LWORK = -1, then a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued by XERBLA. INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value ===================================================================== Test the input arguments */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --tau; c_dim1 = *ldc; c_offset = 1 + c_dim1; c__ -= c_offset; --work; /* Function Body */ *info = 0; left = lsame_(side, "L"); notran = lsame_(trans, "N"); lquery = *lwork == -1; /* NQ is the order of Q and NW is the minimum dimension of WORK */ if (left) { nq = *m; nw = *n; } else { nq = *n; nw = *m; } if (! left && ! lsame_(side, "R")) { *info = -1; } else if (! notran && ! lsame_(trans, "C")) { *info = -2; } else if (*m < 0) { *info = -3; } else if (*n < 0) { *info = -4; } else if ((*k < 0) || (*k > nq)) { *info = -5; } else if (*lda < max(1,nq)) { *info = -7; } else if (*ldc < max(1,*m)) { *info = -10; } else if (*lwork < max(1,nw) && ! lquery) { *info = -12; } if (*info == 0) { /* Determine the block size. NB may be at most NBMAX, where NBMAX is used to define the local array T. Computing MIN Writing concatenation */ i__3[0] = 1, a__1[0] = side; i__3[1] = 1, a__1[1] = trans; s_cat(ch__1, a__1, i__3, &c__2, (ftnlen)2); i__1 = 64, i__2 = ilaenv_(&c__1, "CUNMQR", ch__1, m, n, k, &c_n1, ( ftnlen)6, (ftnlen)2); nb = min(i__1,i__2); lwkopt = max(1,nw) * nb; work[1].r = (real) lwkopt, work[1].i = 0.f; } if (*info != 0) { i__1 = -(*info); xerbla_("CUNMQR", &i__1); return 0; } else if (lquery) { return 0; } /* Quick return if possible */ if (((*m == 0) || (*n == 0)) || (*k == 0)) { work[1].r = 1.f, work[1].i = 0.f; return 0; } nbmin = 2; ldwork = nw; if (nb > 1 && nb < *k) { iws = nw * nb; if (*lwork < iws) { nb = *lwork / ldwork; /* Computing MAX Writing concatenation */ i__3[0] = 1, a__1[0] = side; i__3[1] = 1, a__1[1] = trans; s_cat(ch__1, a__1, i__3, &c__2, (ftnlen)2); i__1 = 2, i__2 = ilaenv_(&c__2, "CUNMQR", ch__1, m, n, k, &c_n1, ( ftnlen)6, (ftnlen)2); nbmin = max(i__1,i__2); } } else { iws = nw; } if ((nb < nbmin) || (nb >= *k)) { /* Use unblocked code */ cunm2r_(side, trans, m, n, k, &a[a_offset], lda, &tau[1], &c__[ c_offset], ldc, &work[1], &iinfo); } else { /* Use blocked code */ if ((left && ! notran) || (! left && notran)) { i1 = 1; i2 = *k; i3 = nb; } else { i1 = (*k - 1) / nb * nb + 1; i2 = 1; i3 = -nb; } if (left) { ni = *n; jc = 1; } else { mi = *m; ic = 1; } i__1 = i2; i__2 = i3; for (i__ = i1; i__2 < 0 ? i__ >= i__1 : i__ <= i__1; i__ += i__2) { /* Computing MIN */ i__4 = nb, i__5 = *k - i__ + 1; ib = min(i__4,i__5); /* Form the triangular factor of the block reflector H = H(i) H(i+1) . . . H(i+ib-1) */ i__4 = nq - i__ + 1; clarft_("Forward", "Columnwise", &i__4, &ib, &a[i__ + i__ * a_dim1], lda, &tau[i__], t, &c__65) ; if (left) { /* H or H' is applied to C(i:m,1:n) */ mi = *m - i__ + 1; ic = i__; } else { /* H or H' is applied to C(1:m,i:n) */ ni = *n - i__ + 1; jc = i__; } /* Apply H or H' */ clarfb_(side, trans, "Forward", "Columnwise", &mi, &ni, &ib, &a[ i__ + i__ * a_dim1], lda, t, &c__65, &c__[ic + jc * c_dim1], ldc, &work[1], &ldwork); /* L10: */ } } work[1].r = (real) lwkopt, work[1].i = 0.f; return 0; /* End of CUNMQR */ } /* cunmqr_ */ /* Subroutine */ int cunmtr_(char *side, char *uplo, char *trans, integer *m, integer *n, complex *a, integer *lda, complex *tau, complex *c__, integer *ldc, complex *work, integer *lwork, integer *info) { /* System generated locals */ address a__1[2]; integer a_dim1, a_offset, c_dim1, c_offset, i__1[2], i__2, i__3; char ch__1[2]; /* Builtin functions */ /* Subroutine */ int s_cat(char *, char **, integer *, integer *, ftnlen); /* Local variables */ static integer i1, i2, nb, mi, ni, nq, nw; static logical left; extern logical lsame_(char *, char *); static integer iinfo; static logical upper; extern /* Subroutine */ int xerbla_(char *, integer *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); extern /* Subroutine */ int cunmql_(char *, char *, integer *, integer *, integer *, complex *, integer *, complex *, complex *, integer *, complex *, integer *, integer *), cunmqr_(char *, char *, integer *, integer *, integer *, complex *, integer *, complex *, complex *, integer *, complex *, integer *, integer *); static integer lwkopt; static logical lquery; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= CUNMTR overwrites the general complex M-by-N matrix C with SIDE = 'L' SIDE = 'R' TRANS = 'N': Q * C C * Q TRANS = 'C': Q**H * C C * Q**H where Q is a complex unitary matrix of order nq, with nq = m if SIDE = 'L' and nq = n if SIDE = 'R'. Q is defined as the product of nq-1 elementary reflectors, as returned by CHETRD: if UPLO = 'U', Q = H(nq-1) . . . H(2) H(1); if UPLO = 'L', Q = H(1) H(2) . . . H(nq-1). Arguments ========= SIDE (input) CHARACTER*1 = 'L': apply Q or Q**H from the Left; = 'R': apply Q or Q**H from the Right. UPLO (input) CHARACTER*1 = 'U': Upper triangle of A contains elementary reflectors from CHETRD; = 'L': Lower triangle of A contains elementary reflectors from CHETRD. TRANS (input) CHARACTER*1 = 'N': No transpose, apply Q; = 'C': Conjugate transpose, apply Q**H. M (input) INTEGER The number of rows of the matrix C. M >= 0. N (input) INTEGER The number of columns of the matrix C. N >= 0. A (input) COMPLEX array, dimension (LDA,M) if SIDE = 'L' (LDA,N) if SIDE = 'R' The vectors which define the elementary reflectors, as returned by CHETRD. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,M) if SIDE = 'L'; LDA >= max(1,N) if SIDE = 'R'. TAU (input) COMPLEX array, dimension (M-1) if SIDE = 'L' (N-1) if SIDE = 'R' TAU(i) must contain the scalar factor of the elementary reflector H(i), as returned by CHETRD. C (input/output) COMPLEX array, dimension (LDC,N) On entry, the M-by-N matrix C. On exit, C is overwritten by Q*C or Q**H*C or C*Q**H or C*Q. LDC (input) INTEGER The leading dimension of the array C. LDC >= max(1,M). WORK (workspace/output) COMPLEX array, dimension (LWORK) On exit, if INFO = 0, WORK(1) returns the optimal LWORK. LWORK (input) INTEGER The dimension of the array WORK. If SIDE = 'L', LWORK >= max(1,N); if SIDE = 'R', LWORK >= max(1,M). For optimum performance LWORK >= N*NB if SIDE = 'L', and LWORK >=M*NB if SIDE = 'R', where NB is the optimal blocksize. If LWORK = -1, then a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued by XERBLA. INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value ===================================================================== Test the input arguments */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --tau; c_dim1 = *ldc; c_offset = 1 + c_dim1; c__ -= c_offset; --work; /* Function Body */ *info = 0; left = lsame_(side, "L"); upper = lsame_(uplo, "U"); lquery = *lwork == -1; /* NQ is the order of Q and NW is the minimum dimension of WORK */ if (left) { nq = *m; nw = *n; } else { nq = *n; nw = *m; } if (! left && ! lsame_(side, "R")) { *info = -1; } else if (! upper && ! lsame_(uplo, "L")) { *info = -2; } else if (! lsame_(trans, "N") && ! lsame_(trans, "C")) { *info = -3; } else if (*m < 0) { *info = -4; } else if (*n < 0) { *info = -5; } else if (*lda < max(1,nq)) { *info = -7; } else if (*ldc < max(1,*m)) { *info = -10; } else if (*lwork < max(1,nw) && ! lquery) { *info = -12; } if (*info == 0) { if (upper) { if (left) { /* Writing concatenation */ i__1[0] = 1, a__1[0] = side; i__1[1] = 1, a__1[1] = trans; s_cat(ch__1, a__1, i__1, &c__2, (ftnlen)2); i__2 = *m - 1; i__3 = *m - 1; nb = ilaenv_(&c__1, "CUNMQL", ch__1, &i__2, n, &i__3, &c_n1, ( ftnlen)6, (ftnlen)2); } else { /* Writing concatenation */ i__1[0] = 1, a__1[0] = side; i__1[1] = 1, a__1[1] = trans; s_cat(ch__1, a__1, i__1, &c__2, (ftnlen)2); i__2 = *n - 1; i__3 = *n - 1; nb = ilaenv_(&c__1, "CUNMQL", ch__1, m, &i__2, &i__3, &c_n1, ( ftnlen)6, (ftnlen)2); } } else { if (left) { /* Writing concatenation */ i__1[0] = 1, a__1[0] = side; i__1[1] = 1, a__1[1] = trans; s_cat(ch__1, a__1, i__1, &c__2, (ftnlen)2); i__2 = *m - 1; i__3 = *m - 1; nb = ilaenv_(&c__1, "CUNMQR", ch__1, &i__2, n, &i__3, &c_n1, ( ftnlen)6, (ftnlen)2); } else { /* Writing concatenation */ i__1[0] = 1, a__1[0] = side; i__1[1] = 1, a__1[1] = trans; s_cat(ch__1, a__1, i__1, &c__2, (ftnlen)2); i__2 = *n - 1; i__3 = *n - 1; nb = ilaenv_(&c__1, "CUNMQR", ch__1, m, &i__2, &i__3, &c_n1, ( ftnlen)6, (ftnlen)2); } } lwkopt = max(1,nw) * nb; work[1].r = (real) lwkopt, work[1].i = 0.f; } if (*info != 0) { i__2 = -(*info); xerbla_("CUNMTR", &i__2); return 0; } else if (lquery) { return 0; } /* Quick return if possible */ if (((*m == 0) || (*n == 0)) || (nq == 1)) { work[1].r = 1.f, work[1].i = 0.f; return 0; } if (left) { mi = *m - 1; ni = *n; } else { mi = *m; ni = *n - 1; } if (upper) { /* Q was determined by a call to CHETRD with UPLO = 'U' */ i__2 = nq - 1; cunmql_(side, trans, &mi, &ni, &i__2, &a[((a_dim1) << (1)) + 1], lda, &tau[1], &c__[c_offset], ldc, &work[1], lwork, &iinfo); } else { /* Q was determined by a call to CHETRD with UPLO = 'L' */ if (left) { i1 = 2; i2 = 1; } else { i1 = 1; i2 = 2; } i__2 = nq - 1; cunmqr_(side, trans, &mi, &ni, &i__2, &a[a_dim1 + 2], lda, &tau[1], & c__[i1 + i2 * c_dim1], ldc, &work[1], lwork, &iinfo); } work[1].r = (real) lwkopt, work[1].i = 0.f; return 0; /* End of CUNMTR */ } /* cunmtr_ */ /* Subroutine */ int dbdsdc_(char *uplo, char *compq, integer *n, doublereal * d__, doublereal *e, doublereal *u, integer *ldu, doublereal *vt, integer *ldvt, doublereal *q, integer *iq, doublereal *work, integer * iwork, integer *info) { /* System generated locals */ integer u_dim1, u_offset, vt_dim1, vt_offset, i__1, i__2; doublereal d__1; /* Builtin functions */ double d_sign(doublereal *, doublereal *), log(doublereal); /* Local variables */ static integer i__, j, k; static doublereal p, r__; static integer z__, ic, ii, kk; static doublereal cs; static integer is, iu; static doublereal sn; static integer nm1; static doublereal eps; static integer ivt, difl, difr, ierr, perm, mlvl, sqre; extern logical lsame_(char *, char *); extern /* Subroutine */ int dlasr_(char *, char *, char *, integer *, integer *, doublereal *, doublereal *, doublereal *, integer *), dcopy_(integer *, doublereal *, integer * , doublereal *, integer *), dswap_(integer *, doublereal *, integer *, doublereal *, integer *); static integer poles, iuplo, nsize, start; extern /* Subroutine */ int dlasd0_(integer *, integer *, doublereal *, doublereal *, doublereal *, integer *, doublereal *, integer *, integer *, integer *, doublereal *, integer *); extern /* Subroutine */ int dlasda_(integer *, integer *, integer *, integer *, doublereal *, doublereal *, doublereal *, integer *, doublereal *, integer *, doublereal *, doublereal *, doublereal *, doublereal *, integer *, integer *, integer *, integer *, doublereal *, doublereal *, doublereal *, doublereal *, integer *, integer *), dlascl_(char *, integer *, integer *, doublereal *, doublereal *, integer *, integer *, doublereal *, integer *, integer *), dlasdq_(char *, integer *, integer *, integer *, integer *, integer *, doublereal *, doublereal *, doublereal *, integer *, doublereal *, integer *, doublereal *, integer *, doublereal *, integer *), dlaset_(char *, integer *, integer *, doublereal *, doublereal *, doublereal *, integer *), dlartg_(doublereal *, doublereal *, doublereal *, doublereal *, doublereal *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); extern /* Subroutine */ int xerbla_(char *, integer *); static integer givcol; extern doublereal dlanst_(char *, integer *, doublereal *, doublereal *); static integer icompq; static doublereal orgnrm; static integer givnum, givptr, qstart, smlsiz, wstart, smlszp; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University December 1, 1999 Purpose ======= DBDSDC computes the singular value decomposition (SVD) of a real N-by-N (upper or lower) bidiagonal matrix B: B = U * S * VT, using a divide and conquer method, where S is a diagonal matrix with non-negative diagonal elements (the singular values of B), and U and VT are orthogonal matrices of left and right singular vectors, respectively. DBDSDC can be used to compute all singular values, and optionally, singular vectors or singular vectors in compact form. This code makes very mild assumptions about floating point arithmetic. It will work on machines with a guard digit in add/subtract, or on those binary machines without guard digits which subtract like the Cray X-MP, Cray Y-MP, Cray C-90, or Cray-2. It could conceivably fail on hexadecimal or decimal machines without guard digits, but we know of none. See DLASD3 for details. The code currently call DLASDQ if singular values only are desired. However, it can be slightly modified to compute singular values using the divide and conquer method. Arguments ========= UPLO (input) CHARACTER*1 = 'U': B is upper bidiagonal. = 'L': B is lower bidiagonal. COMPQ (input) CHARACTER*1 Specifies whether singular vectors are to be computed as follows: = 'N': Compute singular values only; = 'P': Compute singular values and compute singular vectors in compact form; = 'I': Compute singular values and singular vectors. N (input) INTEGER The order of the matrix B. N >= 0. D (input/output) DOUBLE PRECISION array, dimension (N) On entry, the n diagonal elements of the bidiagonal matrix B. On exit, if INFO=0, the singular values of B. E (input/output) DOUBLE PRECISION array, dimension (N) On entry, the elements of E contain the offdiagonal elements of the bidiagonal matrix whose SVD is desired. On exit, E has been destroyed. U (output) DOUBLE PRECISION array, dimension (LDU,N) If COMPQ = 'I', then: On exit, if INFO = 0, U contains the left singular vectors of the bidiagonal matrix. For other values of COMPQ, U is not referenced. LDU (input) INTEGER The leading dimension of the array U. LDU >= 1. If singular vectors are desired, then LDU >= max( 1, N ). VT (output) DOUBLE PRECISION array, dimension (LDVT,N) If COMPQ = 'I', then: On exit, if INFO = 0, VT' contains the right singular vectors of the bidiagonal matrix. For other values of COMPQ, VT is not referenced. LDVT (input) INTEGER The leading dimension of the array VT. LDVT >= 1. If singular vectors are desired, then LDVT >= max( 1, N ). Q (output) DOUBLE PRECISION array, dimension (LDQ) If COMPQ = 'P', then: On exit, if INFO = 0, Q and IQ contain the left and right singular vectors in a compact form, requiring O(N log N) space instead of 2*N**2. In particular, Q contains all the DOUBLE PRECISION data in LDQ >= N*(11 + 2*SMLSIZ + 8*INT(LOG_2(N/(SMLSIZ+1)))) words of memory, where SMLSIZ is returned by ILAENV and is equal to the maximum size of the subproblems at the bottom of the computation tree (usually about 25). For other values of COMPQ, Q is not referenced. IQ (output) INTEGER array, dimension (LDIQ) If COMPQ = 'P', then: On exit, if INFO = 0, Q and IQ contain the left and right singular vectors in a compact form, requiring O(N log N) space instead of 2*N**2. In particular, IQ contains all INTEGER data in LDIQ >= N*(3 + 3*INT(LOG_2(N/(SMLSIZ+1)))) words of memory, where SMLSIZ is returned by ILAENV and is equal to the maximum size of the subproblems at the bottom of the computation tree (usually about 25). For other values of COMPQ, IQ is not referenced. WORK (workspace) DOUBLE PRECISION array, dimension (LWORK) If COMPQ = 'N' then LWORK >= (4 * N). If COMPQ = 'P' then LWORK >= (6 * N). If COMPQ = 'I' then LWORK >= (3 * N**2 + 4 * N). IWORK (workspace) INTEGER array, dimension (8*N) INFO (output) INTEGER = 0: successful exit. < 0: if INFO = -i, the i-th argument had an illegal value. > 0: The algorithm failed to compute an singular value. The update process of divide and conquer failed. Further Details =============== Based on contributions by Ming Gu and Huan Ren, Computer Science Division, University of California at Berkeley, USA ===================================================================== Test the input parameters. */ /* Parameter adjustments */ --d__; --e; u_dim1 = *ldu; u_offset = 1 + u_dim1; u -= u_offset; vt_dim1 = *ldvt; vt_offset = 1 + vt_dim1; vt -= vt_offset; --q; --iq; --work; --iwork; /* Function Body */ *info = 0; iuplo = 0; if (lsame_(uplo, "U")) { iuplo = 1; } if (lsame_(uplo, "L")) { iuplo = 2; } if (lsame_(compq, "N")) { icompq = 0; } else if (lsame_(compq, "P")) { icompq = 1; } else if (lsame_(compq, "I")) { icompq = 2; } else { icompq = -1; } if (iuplo == 0) { *info = -1; } else if (icompq < 0) { *info = -2; } else if (*n < 0) { *info = -3; } else if ((*ldu < 1) || (icompq == 2 && *ldu < *n)) { *info = -7; } else if ((*ldvt < 1) || (icompq == 2 && *ldvt < *n)) { *info = -9; } if (*info != 0) { i__1 = -(*info); xerbla_("DBDSDC", &i__1); return 0; } /* Quick return if possible */ if (*n == 0) { return 0; } smlsiz = ilaenv_(&c__9, "DBDSDC", " ", &c__0, &c__0, &c__0, &c__0, ( ftnlen)6, (ftnlen)1); if (*n == 1) { if (icompq == 1) { q[1] = d_sign(&c_b2865, &d__[1]); q[smlsiz * *n + 1] = 1.; } else if (icompq == 2) { u[u_dim1 + 1] = d_sign(&c_b2865, &d__[1]); vt[vt_dim1 + 1] = 1.; } d__[1] = abs(d__[1]); return 0; } nm1 = *n - 1; /* If matrix lower bidiagonal, rotate to be upper bidiagonal by applying Givens rotations on the left */ wstart = 1; qstart = 3; if (icompq == 1) { dcopy_(n, &d__[1], &c__1, &q[1], &c__1); i__1 = *n - 1; dcopy_(&i__1, &e[1], &c__1, &q[*n + 1], &c__1); } if (iuplo == 2) { qstart = 5; wstart = ((*n) << (1)) - 1; i__1 = *n - 1; for (i__ = 1; i__ <= i__1; ++i__) { dlartg_(&d__[i__], &e[i__], &cs, &sn, &r__); d__[i__] = r__; e[i__] = sn * d__[i__ + 1]; d__[i__ + 1] = cs * d__[i__ + 1]; if (icompq == 1) { q[i__ + ((*n) << (1))] = cs; q[i__ + *n * 3] = sn; } else if (icompq == 2) { work[i__] = cs; work[nm1 + i__] = -sn; } /* L10: */ } } /* If ICOMPQ = 0, use DLASDQ to compute the singular values. */ if (icompq == 0) { dlasdq_("U", &c__0, n, &c__0, &c__0, &c__0, &d__[1], &e[1], &vt[ vt_offset], ldvt, &u[u_offset], ldu, &u[u_offset], ldu, &work[ wstart], info); goto L40; } /* If N is smaller than the minimum divide size SMLSIZ, then solve the problem with another solver. */ if (*n <= smlsiz) { if (icompq == 2) { dlaset_("A", n, n, &c_b2879, &c_b2865, &u[u_offset], ldu); dlaset_("A", n, n, &c_b2879, &c_b2865, &vt[vt_offset], ldvt); dlasdq_("U", &c__0, n, n, n, &c__0, &d__[1], &e[1], &vt[vt_offset] , ldvt, &u[u_offset], ldu, &u[u_offset], ldu, &work[ wstart], info); } else if (icompq == 1) { iu = 1; ivt = iu + *n; dlaset_("A", n, n, &c_b2879, &c_b2865, &q[iu + (qstart - 1) * *n], n); dlaset_("A", n, n, &c_b2879, &c_b2865, &q[ivt + (qstart - 1) * *n] , n); dlasdq_("U", &c__0, n, n, n, &c__0, &d__[1], &e[1], &q[ivt + ( qstart - 1) * *n], n, &q[iu + (qstart - 1) * *n], n, &q[ iu + (qstart - 1) * *n], n, &work[wstart], info); } goto L40; } if (icompq == 2) { dlaset_("A", n, n, &c_b2879, &c_b2865, &u[u_offset], ldu); dlaset_("A", n, n, &c_b2879, &c_b2865, &vt[vt_offset], ldvt); } /* Scale. */ orgnrm = dlanst_("M", n, &d__[1], &e[1]); if (orgnrm == 0.) { return 0; } dlascl_("G", &c__0, &c__0, &orgnrm, &c_b2865, n, &c__1, &d__[1], n, &ierr); dlascl_("G", &c__0, &c__0, &orgnrm, &c_b2865, &nm1, &c__1, &e[1], &nm1, & ierr); eps = EPSILON; mlvl = (integer) (log((doublereal) (*n) / (doublereal) (smlsiz + 1)) / log(2.)) + 1; smlszp = smlsiz + 1; if (icompq == 1) { iu = 1; ivt = smlsiz + 1; difl = ivt + smlszp; difr = difl + mlvl; z__ = difr + ((mlvl) << (1)); ic = z__ + mlvl; is = ic + 1; poles = is + 1; givnum = poles + ((mlvl) << (1)); k = 1; givptr = 2; perm = 3; givcol = perm + mlvl; } i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { if ((d__1 = d__[i__], abs(d__1)) < eps) { d__[i__] = d_sign(&eps, &d__[i__]); } /* L20: */ } start = 1; sqre = 0; i__1 = nm1; for (i__ = 1; i__ <= i__1; ++i__) { if (((d__1 = e[i__], abs(d__1)) < eps) || (i__ == nm1)) { /* Subproblem found. First determine its size and then apply divide and conquer on it. */ if (i__ < nm1) { /* A subproblem with E(I) small for I < NM1. */ nsize = i__ - start + 1; } else if ((d__1 = e[i__], abs(d__1)) >= eps) { /* A subproblem with E(NM1) not too small but I = NM1. */ nsize = *n - start + 1; } else { /* A subproblem with E(NM1) small. This implies an 1-by-1 subproblem at D(N). Solve this 1-by-1 problem first. */ nsize = i__ - start + 1; if (icompq == 2) { u[*n + *n * u_dim1] = d_sign(&c_b2865, &d__[*n]); vt[*n + *n * vt_dim1] = 1.; } else if (icompq == 1) { q[*n + (qstart - 1) * *n] = d_sign(&c_b2865, &d__[*n]); q[*n + (smlsiz + qstart - 1) * *n] = 1.; } d__[*n] = (d__1 = d__[*n], abs(d__1)); } if (icompq == 2) { dlasd0_(&nsize, &sqre, &d__[start], &e[start], &u[start + start * u_dim1], ldu, &vt[start + start * vt_dim1], ldvt, &smlsiz, &iwork[1], &work[wstart], info); } else { dlasda_(&icompq, &smlsiz, &nsize, &sqre, &d__[start], &e[ start], &q[start + (iu + qstart - 2) * *n], n, &q[ start + (ivt + qstart - 2) * *n], &iq[start + k * *n], &q[start + (difl + qstart - 2) * *n], &q[start + ( difr + qstart - 2) * *n], &q[start + (z__ + qstart - 2) * *n], &q[start + (poles + qstart - 2) * *n], &iq[ start + givptr * *n], &iq[start + givcol * *n], n, & iq[start + perm * *n], &q[start + (givnum + qstart - 2) * *n], &q[start + (ic + qstart - 2) * *n], &q[ start + (is + qstart - 2) * *n], &work[wstart], & iwork[1], info); if (*info != 0) { return 0; } } start = i__ + 1; } /* L30: */ } /* Unscale */ dlascl_("G", &c__0, &c__0, &c_b2865, &orgnrm, n, &c__1, &d__[1], n, &ierr); L40: /* Use Selection Sort to minimize swaps of singular vectors */ i__1 = *n; for (ii = 2; ii <= i__1; ++ii) { i__ = ii - 1; kk = i__; p = d__[i__]; i__2 = *n; for (j = ii; j <= i__2; ++j) { if (d__[j] > p) { kk = j; p = d__[j]; } /* L50: */ } if (kk != i__) { d__[kk] = d__[i__]; d__[i__] = p; if (icompq == 1) { iq[i__] = kk; } else if (icompq == 2) { dswap_(n, &u[i__ * u_dim1 + 1], &c__1, &u[kk * u_dim1 + 1], & c__1); dswap_(n, &vt[i__ + vt_dim1], ldvt, &vt[kk + vt_dim1], ldvt); } } else if (icompq == 1) { iq[i__] = i__; } /* L60: */ } /* If ICOMPQ = 1, use IQ(N,1) as the indicator for UPLO */ if (icompq == 1) { if (iuplo == 1) { iq[*n] = 1; } else { iq[*n] = 0; } } /* If B is lower bidiagonal, update U by those Givens rotations which rotated B to be upper bidiagonal */ if (iuplo == 2 && icompq == 2) { dlasr_("L", "V", "B", n, n, &work[1], &work[*n], &u[u_offset], ldu); } return 0; /* End of DBDSDC */ } /* dbdsdc_ */ /* Subroutine */ int dbdsqr_(char *uplo, integer *n, integer *ncvt, integer * nru, integer *ncc, doublereal *d__, doublereal *e, doublereal *vt, integer *ldvt, doublereal *u, integer *ldu, doublereal *c__, integer * ldc, doublereal *work, integer *info) { /* System generated locals */ integer c_dim1, c_offset, u_dim1, u_offset, vt_dim1, vt_offset, i__1, i__2; doublereal d__1, d__2, d__3, d__4; /* Builtin functions */ double pow_dd(doublereal *, doublereal *), sqrt(doublereal), d_sign( doublereal *, doublereal *); /* Local variables */ static doublereal f, g, h__; static integer i__, j, m; static doublereal r__, cs; static integer ll; static doublereal sn, mu; static integer nm1, nm12, nm13, lll; static doublereal eps, sll, tol, abse; static integer idir; static doublereal abss; static integer oldm; static doublereal cosl; static integer isub, iter; static doublereal unfl, sinl, cosr, smin, smax, sinr; extern /* Subroutine */ int drot_(integer *, doublereal *, integer *, doublereal *, integer *, doublereal *, doublereal *), dlas2_( doublereal *, doublereal *, doublereal *, doublereal *, doublereal *), dscal_(integer *, doublereal *, doublereal *, integer *); extern logical lsame_(char *, char *); static doublereal oldcs; extern /* Subroutine */ int dlasr_(char *, char *, char *, integer *, integer *, doublereal *, doublereal *, doublereal *, integer *); static integer oldll; static doublereal shift, sigmn, oldsn; extern /* Subroutine */ int dswap_(integer *, doublereal *, integer *, doublereal *, integer *); static integer maxit; static doublereal sminl, sigmx; static logical lower; extern /* Subroutine */ int dlasq1_(integer *, doublereal *, doublereal *, doublereal *, integer *), dlasv2_(doublereal *, doublereal *, doublereal *, doublereal *, doublereal *, doublereal *, doublereal *, doublereal *, doublereal *); extern /* Subroutine */ int dlartg_(doublereal *, doublereal *, doublereal *, doublereal *, doublereal *), xerbla_(char *, integer *); static doublereal sminoa, thresh; static logical rotate; static doublereal sminlo, tolmul; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University October 31, 1999 Purpose ======= DBDSQR computes the singular value decomposition (SVD) of a real N-by-N (upper or lower) bidiagonal matrix B: B = Q * S * P' (P' denotes the transpose of P), where S is a diagonal matrix with non-negative diagonal elements (the singular values of B), and Q and P are orthogonal matrices. The routine computes S, and optionally computes U * Q, P' * VT, or Q' * C, for given real input matrices U, VT, and C. See "Computing Small Singular Values of Bidiagonal Matrices With Guaranteed High Relative Accuracy," by J. Demmel and W. Kahan, LAPACK Working Note #3 (or SIAM J. Sci. Statist. Comput. vol. 11, no. 5, pp. 873-912, Sept 1990) and "Accurate singular values and differential qd algorithms," by B. Parlett and V. Fernando, Technical Report CPAM-554, Mathematics Department, University of California at Berkeley, July 1992 for a detailed description of the algorithm. Arguments ========= UPLO (input) CHARACTER*1 = 'U': B is upper bidiagonal; = 'L': B is lower bidiagonal. N (input) INTEGER The order of the matrix B. N >= 0. NCVT (input) INTEGER The number of columns of the matrix VT. NCVT >= 0. NRU (input) INTEGER The number of rows of the matrix U. NRU >= 0. NCC (input) INTEGER The number of columns of the matrix C. NCC >= 0. D (input/output) DOUBLE PRECISION array, dimension (N) On entry, the n diagonal elements of the bidiagonal matrix B. On exit, if INFO=0, the singular values of B in decreasing order. E (input/output) DOUBLE PRECISION array, dimension (N) On entry, the elements of E contain the offdiagonal elements of the bidiagonal matrix whose SVD is desired. On normal exit (INFO = 0), E is destroyed. If the algorithm does not converge (INFO > 0), D and E will contain the diagonal and superdiagonal elements of a bidiagonal matrix orthogonally equivalent to the one given as input. E(N) is used for workspace. VT (input/output) DOUBLE PRECISION array, dimension (LDVT, NCVT) On entry, an N-by-NCVT matrix VT. On exit, VT is overwritten by P' * VT. VT is not referenced if NCVT = 0. LDVT (input) INTEGER The leading dimension of the array VT. LDVT >= max(1,N) if NCVT > 0; LDVT >= 1 if NCVT = 0. U (input/output) DOUBLE PRECISION array, dimension (LDU, N) On entry, an NRU-by-N matrix U. On exit, U is overwritten by U * Q. U is not referenced if NRU = 0. LDU (input) INTEGER The leading dimension of the array U. LDU >= max(1,NRU). C (input/output) DOUBLE PRECISION array, dimension (LDC, NCC) On entry, an N-by-NCC matrix C. On exit, C is overwritten by Q' * C. C is not referenced if NCC = 0. LDC (input) INTEGER The leading dimension of the array C. LDC >= max(1,N) if NCC > 0; LDC >=1 if NCC = 0. WORK (workspace) DOUBLE PRECISION array, dimension (4*N) INFO (output) INTEGER = 0: successful exit < 0: If INFO = -i, the i-th argument had an illegal value > 0: the algorithm did not converge; D and E contain the elements of a bidiagonal matrix which is orthogonally similar to the input matrix B; if INFO = i, i elements of E have not converged to zero. Internal Parameters =================== TOLMUL DOUBLE PRECISION, default = max(10,min(100,EPS**(-1/8))) TOLMUL controls the convergence criterion of the QR loop. If it is positive, TOLMUL*EPS is the desired relative precision in the computed singular values. If it is negative, abs(TOLMUL*EPS*sigma_max) is the desired absolute accuracy in the computed singular values (corresponds to relative accuracy abs(TOLMUL*EPS) in the largest singular value. abs(TOLMUL) should be between 1 and 1/EPS, and preferably between 10 (for fast convergence) and .1/EPS (for there to be some accuracy in the results). Default is to lose at either one eighth or 2 of the available decimal digits in each computed singular value (whichever is smaller). MAXITR INTEGER, default = 6 MAXITR controls the maximum number of passes of the algorithm through its inner loop. The algorithms stops (and so fails to converge) if the number of passes through the inner loop exceeds MAXITR*N**2. ===================================================================== Test the input parameters. */ /* Parameter adjustments */ --d__; --e; vt_dim1 = *ldvt; vt_offset = 1 + vt_dim1; vt -= vt_offset; u_dim1 = *ldu; u_offset = 1 + u_dim1; u -= u_offset; c_dim1 = *ldc; c_offset = 1 + c_dim1; c__ -= c_offset; --work; /* Function Body */ *info = 0; lower = lsame_(uplo, "L"); if (! lsame_(uplo, "U") && ! lower) { *info = -1; } else if (*n < 0) { *info = -2; } else if (*ncvt < 0) { *info = -3; } else if (*nru < 0) { *info = -4; } else if (*ncc < 0) { *info = -5; } else if ((*ncvt == 0 && *ldvt < 1) || (*ncvt > 0 && *ldvt < max(1,*n))) { *info = -9; } else if (*ldu < max(1,*nru)) { *info = -11; } else if ((*ncc == 0 && *ldc < 1) || (*ncc > 0 && *ldc < max(1,*n))) { *info = -13; } if (*info != 0) { i__1 = -(*info); xerbla_("DBDSQR", &i__1); return 0; } if (*n == 0) { return 0; } if (*n == 1) { goto L160; } /* ROTATE is true if any singular vectors desired, false otherwise */ rotate = ((*ncvt > 0) || (*nru > 0)) || (*ncc > 0); /* If no singular vectors desired, use qd algorithm */ if (! rotate) { dlasq1_(n, &d__[1], &e[1], &work[1], info); return 0; } nm1 = *n - 1; nm12 = nm1 + nm1; nm13 = nm12 + nm1; idir = 0; /* Get machine constants */ eps = EPSILON; unfl = SAFEMINIMUM; /* If matrix lower bidiagonal, rotate to be upper bidiagonal by applying Givens rotations on the left */ if (lower) { i__1 = *n - 1; for (i__ = 1; i__ <= i__1; ++i__) { dlartg_(&d__[i__], &e[i__], &cs, &sn, &r__); d__[i__] = r__; e[i__] = sn * d__[i__ + 1]; d__[i__ + 1] = cs * d__[i__ + 1]; work[i__] = cs; work[nm1 + i__] = sn; /* L10: */ } /* Update singular vectors if desired */ if (*nru > 0) { dlasr_("R", "V", "F", nru, n, &work[1], &work[*n], &u[u_offset], ldu); } if (*ncc > 0) { dlasr_("L", "V", "F", n, ncc, &work[1], &work[*n], &c__[c_offset], ldc); } } /* Compute singular values to relative accuracy TOL (By setting TOL to be negative, algorithm will compute singular values to absolute accuracy ABS(TOL)*norm(input matrix)) Computing MAX Computing MIN */ d__3 = 100., d__4 = pow_dd(&eps, &c_b2944); d__1 = 10., d__2 = min(d__3,d__4); tolmul = max(d__1,d__2); tol = tolmul * eps; /* Compute approximate maximum, minimum singular values */ smax = 0.; i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { /* Computing MAX */ d__2 = smax, d__3 = (d__1 = d__[i__], abs(d__1)); smax = max(d__2,d__3); /* L20: */ } i__1 = *n - 1; for (i__ = 1; i__ <= i__1; ++i__) { /* Computing MAX */ d__2 = smax, d__3 = (d__1 = e[i__], abs(d__1)); smax = max(d__2,d__3); /* L30: */ } sminl = 0.; if (tol >= 0.) { /* Relative accuracy desired */ sminoa = abs(d__[1]); if (sminoa == 0.) { goto L50; } mu = sminoa; i__1 = *n; for (i__ = 2; i__ <= i__1; ++i__) { mu = (d__2 = d__[i__], abs(d__2)) * (mu / (mu + (d__1 = e[i__ - 1] , abs(d__1)))); sminoa = min(sminoa,mu); if (sminoa == 0.) { goto L50; } /* L40: */ } L50: sminoa /= sqrt((doublereal) (*n)); /* Computing MAX */ d__1 = tol * sminoa, d__2 = *n * 6 * *n * unfl; thresh = max(d__1,d__2); } else { /* Absolute accuracy desired Computing MAX */ d__1 = abs(tol) * smax, d__2 = *n * 6 * *n * unfl; thresh = max(d__1,d__2); } /* Prepare for main iteration loop for the singular values (MAXIT is the maximum number of passes through the inner loop permitted before nonconvergence signalled.) */ maxit = *n * 6 * *n; iter = 0; oldll = -1; oldm = -1; /* M points to last element of unconverged part of matrix */ m = *n; /* Begin main iteration loop */ L60: /* Check for convergence or exceeding iteration count */ if (m <= 1) { goto L160; } if (iter > maxit) { goto L200; } /* Find diagonal block of matrix to work on */ if (tol < 0. && (d__1 = d__[m], abs(d__1)) <= thresh) { d__[m] = 0.; } smax = (d__1 = d__[m], abs(d__1)); smin = smax; i__1 = m - 1; for (lll = 1; lll <= i__1; ++lll) { ll = m - lll; abss = (d__1 = d__[ll], abs(d__1)); abse = (d__1 = e[ll], abs(d__1)); if (tol < 0. && abss <= thresh) { d__[ll] = 0.; } if (abse <= thresh) { goto L80; } smin = min(smin,abss); /* Computing MAX */ d__1 = max(smax,abss); smax = max(d__1,abse); /* L70: */ } ll = 0; goto L90; L80: e[ll] = 0.; /* Matrix splits since E(LL) = 0 */ if (ll == m - 1) { /* Convergence of bottom singular value, return to top of loop */ --m; goto L60; } L90: ++ll; /* E(LL) through E(M-1) are nonzero, E(LL-1) is zero */ if (ll == m - 1) { /* 2 by 2 block, handle separately */ dlasv2_(&d__[m - 1], &e[m - 1], &d__[m], &sigmn, &sigmx, &sinr, &cosr, &sinl, &cosl); d__[m - 1] = sigmx; e[m - 1] = 0.; d__[m] = sigmn; /* Compute singular vectors, if desired */ if (*ncvt > 0) { drot_(ncvt, &vt[m - 1 + vt_dim1], ldvt, &vt[m + vt_dim1], ldvt, & cosr, &sinr); } if (*nru > 0) { drot_(nru, &u[(m - 1) * u_dim1 + 1], &c__1, &u[m * u_dim1 + 1], & c__1, &cosl, &sinl); } if (*ncc > 0) { drot_(ncc, &c__[m - 1 + c_dim1], ldc, &c__[m + c_dim1], ldc, & cosl, &sinl); } m += -2; goto L60; } /* If working on new submatrix, choose shift direction (from larger end diagonal element towards smaller) */ if ((ll > oldm) || (m < oldll)) { if ((d__1 = d__[ll], abs(d__1)) >= (d__2 = d__[m], abs(d__2))) { /* Chase bulge from top (big end) to bottom (small end) */ idir = 1; } else { /* Chase bulge from bottom (big end) to top (small end) */ idir = 2; } } /* Apply convergence tests */ if (idir == 1) { /* Run convergence test in forward direction First apply standard test to bottom of matrix */ if (((d__2 = e[m - 1], abs(d__2)) <= abs(tol) * (d__1 = d__[m], abs( d__1))) || (tol < 0. && (d__3 = e[m - 1], abs(d__3)) <= thresh)) { e[m - 1] = 0.; goto L60; } if (tol >= 0.) { /* If relative accuracy desired, apply convergence criterion forward */ mu = (d__1 = d__[ll], abs(d__1)); sminl = mu; i__1 = m - 1; for (lll = ll; lll <= i__1; ++lll) { if ((d__1 = e[lll], abs(d__1)) <= tol * mu) { e[lll] = 0.; goto L60; } sminlo = sminl; mu = (d__2 = d__[lll + 1], abs(d__2)) * (mu / (mu + (d__1 = e[ lll], abs(d__1)))); sminl = min(sminl,mu); /* L100: */ } } } else { /* Run convergence test in backward direction First apply standard test to top of matrix */ if (((d__2 = e[ll], abs(d__2)) <= abs(tol) * (d__1 = d__[ll], abs( d__1))) || (tol < 0. && (d__3 = e[ll], abs(d__3)) <= thresh)) { e[ll] = 0.; goto L60; } if (tol >= 0.) { /* If relative accuracy desired, apply convergence criterion backward */ mu = (d__1 = d__[m], abs(d__1)); sminl = mu; i__1 = ll; for (lll = m - 1; lll >= i__1; --lll) { if ((d__1 = e[lll], abs(d__1)) <= tol * mu) { e[lll] = 0.; goto L60; } sminlo = sminl; mu = (d__2 = d__[lll], abs(d__2)) * (mu / (mu + (d__1 = e[lll] , abs(d__1)))); sminl = min(sminl,mu); /* L110: */ } } } oldll = ll; oldm = m; /* Compute shift. First, test if shifting would ruin relative accuracy, and if so set the shift to zero. Computing MAX */ d__1 = eps, d__2 = tol * .01; if (tol >= 0. && *n * tol * (sminl / smax) <= max(d__1,d__2)) { /* Use a zero shift to avoid loss of relative accuracy */ shift = 0.; } else { /* Compute the shift from 2-by-2 block at end of matrix */ if (idir == 1) { sll = (d__1 = d__[ll], abs(d__1)); dlas2_(&d__[m - 1], &e[m - 1], &d__[m], &shift, &r__); } else { sll = (d__1 = d__[m], abs(d__1)); dlas2_(&d__[ll], &e[ll], &d__[ll + 1], &shift, &r__); } /* Test if shift negligible, and if so set to zero */ if (sll > 0.) { /* Computing 2nd power */ d__1 = shift / sll; if (d__1 * d__1 < eps) { shift = 0.; } } } /* Increment iteration count */ iter = iter + m - ll; /* If SHIFT = 0, do simplified QR iteration */ if (shift == 0.) { if (idir == 1) { /* Chase bulge from top to bottom Save cosines and sines for later singular vector updates */ cs = 1.; oldcs = 1.; i__1 = m - 1; for (i__ = ll; i__ <= i__1; ++i__) { d__1 = d__[i__] * cs; dlartg_(&d__1, &e[i__], &cs, &sn, &r__); if (i__ > ll) { e[i__ - 1] = oldsn * r__; } d__1 = oldcs * r__; d__2 = d__[i__ + 1] * sn; dlartg_(&d__1, &d__2, &oldcs, &oldsn, &d__[i__]); work[i__ - ll + 1] = cs; work[i__ - ll + 1 + nm1] = sn; work[i__ - ll + 1 + nm12] = oldcs; work[i__ - ll + 1 + nm13] = oldsn; /* L120: */ } h__ = d__[m] * cs; d__[m] = h__ * oldcs; e[m - 1] = h__ * oldsn; /* Update singular vectors */ if (*ncvt > 0) { i__1 = m - ll + 1; dlasr_("L", "V", "F", &i__1, ncvt, &work[1], &work[*n], &vt[ ll + vt_dim1], ldvt); } if (*nru > 0) { i__1 = m - ll + 1; dlasr_("R", "V", "F", nru, &i__1, &work[nm12 + 1], &work[nm13 + 1], &u[ll * u_dim1 + 1], ldu); } if (*ncc > 0) { i__1 = m - ll + 1; dlasr_("L", "V", "F", &i__1, ncc, &work[nm12 + 1], &work[nm13 + 1], &c__[ll + c_dim1], ldc); } /* Test convergence */ if ((d__1 = e[m - 1], abs(d__1)) <= thresh) { e[m - 1] = 0.; } } else { /* Chase bulge from bottom to top Save cosines and sines for later singular vector updates */ cs = 1.; oldcs = 1.; i__1 = ll + 1; for (i__ = m; i__ >= i__1; --i__) { d__1 = d__[i__] * cs; dlartg_(&d__1, &e[i__ - 1], &cs, &sn, &r__); if (i__ < m) { e[i__] = oldsn * r__; } d__1 = oldcs * r__; d__2 = d__[i__ - 1] * sn; dlartg_(&d__1, &d__2, &oldcs, &oldsn, &d__[i__]); work[i__ - ll] = cs; work[i__ - ll + nm1] = -sn; work[i__ - ll + nm12] = oldcs; work[i__ - ll + nm13] = -oldsn; /* L130: */ } h__ = d__[ll] * cs; d__[ll] = h__ * oldcs; e[ll] = h__ * oldsn; /* Update singular vectors */ if (*ncvt > 0) { i__1 = m - ll + 1; dlasr_("L", "V", "B", &i__1, ncvt, &work[nm12 + 1], &work[ nm13 + 1], &vt[ll + vt_dim1], ldvt); } if (*nru > 0) { i__1 = m - ll + 1; dlasr_("R", "V", "B", nru, &i__1, &work[1], &work[*n], &u[ll * u_dim1 + 1], ldu); } if (*ncc > 0) { i__1 = m - ll + 1; dlasr_("L", "V", "B", &i__1, ncc, &work[1], &work[*n], &c__[ ll + c_dim1], ldc); } /* Test convergence */ if ((d__1 = e[ll], abs(d__1)) <= thresh) { e[ll] = 0.; } } } else { /* Use nonzero shift */ if (idir == 1) { /* Chase bulge from top to bottom Save cosines and sines for later singular vector updates */ f = ((d__1 = d__[ll], abs(d__1)) - shift) * (d_sign(&c_b2865, & d__[ll]) + shift / d__[ll]); g = e[ll]; i__1 = m - 1; for (i__ = ll; i__ <= i__1; ++i__) { dlartg_(&f, &g, &cosr, &sinr, &r__); if (i__ > ll) { e[i__ - 1] = r__; } f = cosr * d__[i__] + sinr * e[i__]; e[i__] = cosr * e[i__] - sinr * d__[i__]; g = sinr * d__[i__ + 1]; d__[i__ + 1] = cosr * d__[i__ + 1]; dlartg_(&f, &g, &cosl, &sinl, &r__); d__[i__] = r__; f = cosl * e[i__] + sinl * d__[i__ + 1]; d__[i__ + 1] = cosl * d__[i__ + 1] - sinl * e[i__]; if (i__ < m - 1) { g = sinl * e[i__ + 1]; e[i__ + 1] = cosl * e[i__ + 1]; } work[i__ - ll + 1] = cosr; work[i__ - ll + 1 + nm1] = sinr; work[i__ - ll + 1 + nm12] = cosl; work[i__ - ll + 1 + nm13] = sinl; /* L140: */ } e[m - 1] = f; /* Update singular vectors */ if (*ncvt > 0) { i__1 = m - ll + 1; dlasr_("L", "V", "F", &i__1, ncvt, &work[1], &work[*n], &vt[ ll + vt_dim1], ldvt); } if (*nru > 0) { i__1 = m - ll + 1; dlasr_("R", "V", "F", nru, &i__1, &work[nm12 + 1], &work[nm13 + 1], &u[ll * u_dim1 + 1], ldu); } if (*ncc > 0) { i__1 = m - ll + 1; dlasr_("L", "V", "F", &i__1, ncc, &work[nm12 + 1], &work[nm13 + 1], &c__[ll + c_dim1], ldc); } /* Test convergence */ if ((d__1 = e[m - 1], abs(d__1)) <= thresh) { e[m - 1] = 0.; } } else { /* Chase bulge from bottom to top Save cosines and sines for later singular vector updates */ f = ((d__1 = d__[m], abs(d__1)) - shift) * (d_sign(&c_b2865, &d__[ m]) + shift / d__[m]); g = e[m - 1]; i__1 = ll + 1; for (i__ = m; i__ >= i__1; --i__) { dlartg_(&f, &g, &cosr, &sinr, &r__); if (i__ < m) { e[i__] = r__; } f = cosr * d__[i__] + sinr * e[i__ - 1]; e[i__ - 1] = cosr * e[i__ - 1] - sinr * d__[i__]; g = sinr * d__[i__ - 1]; d__[i__ - 1] = cosr * d__[i__ - 1]; dlartg_(&f, &g, &cosl, &sinl, &r__); d__[i__] = r__; f = cosl * e[i__ - 1] + sinl * d__[i__ - 1]; d__[i__ - 1] = cosl * d__[i__ - 1] - sinl * e[i__ - 1]; if (i__ > ll + 1) { g = sinl * e[i__ - 2]; e[i__ - 2] = cosl * e[i__ - 2]; } work[i__ - ll] = cosr; work[i__ - ll + nm1] = -sinr; work[i__ - ll + nm12] = cosl; work[i__ - ll + nm13] = -sinl; /* L150: */ } e[ll] = f; /* Test convergence */ if ((d__1 = e[ll], abs(d__1)) <= thresh) { e[ll] = 0.; } /* Update singular vectors if desired */ if (*ncvt > 0) { i__1 = m - ll + 1; dlasr_("L", "V", "B", &i__1, ncvt, &work[nm12 + 1], &work[ nm13 + 1], &vt[ll + vt_dim1], ldvt); } if (*nru > 0) { i__1 = m - ll + 1; dlasr_("R", "V", "B", nru, &i__1, &work[1], &work[*n], &u[ll * u_dim1 + 1], ldu); } if (*ncc > 0) { i__1 = m - ll + 1; dlasr_("L", "V", "B", &i__1, ncc, &work[1], &work[*n], &c__[ ll + c_dim1], ldc); } } } /* QR iteration finished, go back and check convergence */ goto L60; /* All singular values converged, so make them positive */ L160: i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { if (d__[i__] < 0.) { d__[i__] = -d__[i__]; /* Change sign of singular vectors, if desired */ if (*ncvt > 0) { dscal_(ncvt, &c_b3001, &vt[i__ + vt_dim1], ldvt); } } /* L170: */ } /* Sort the singular values into decreasing order (insertion sort on singular values, but only one transposition per singular vector) */ i__1 = *n - 1; for (i__ = 1; i__ <= i__1; ++i__) { /* Scan for smallest D(I) */ isub = 1; smin = d__[1]; i__2 = *n + 1 - i__; for (j = 2; j <= i__2; ++j) { if (d__[j] <= smin) { isub = j; smin = d__[j]; } /* L180: */ } if (isub != *n + 1 - i__) { /* Swap singular values and vectors */ d__[isub] = d__[*n + 1 - i__]; d__[*n + 1 - i__] = smin; if (*ncvt > 0) { dswap_(ncvt, &vt[isub + vt_dim1], ldvt, &vt[*n + 1 - i__ + vt_dim1], ldvt); } if (*nru > 0) { dswap_(nru, &u[isub * u_dim1 + 1], &c__1, &u[(*n + 1 - i__) * u_dim1 + 1], &c__1); } if (*ncc > 0) { dswap_(ncc, &c__[isub + c_dim1], ldc, &c__[*n + 1 - i__ + c_dim1], ldc); } } /* L190: */ } goto L220; /* Maximum number of iterations exceeded, failure to converge */ L200: *info = 0; i__1 = *n - 1; for (i__ = 1; i__ <= i__1; ++i__) { if (e[i__] != 0.) { ++(*info); } /* L210: */ } L220: return 0; /* End of DBDSQR */ } /* dbdsqr_ */ /* Subroutine */ int dgebak_(char *job, char *side, integer *n, integer *ilo, integer *ihi, doublereal *scale, integer *m, doublereal *v, integer * ldv, integer *info) { /* System generated locals */ integer v_dim1, v_offset, i__1; /* Local variables */ static integer i__, k; static doublereal s; static integer ii; extern /* Subroutine */ int dscal_(integer *, doublereal *, doublereal *, integer *); extern logical lsame_(char *, char *); extern /* Subroutine */ int dswap_(integer *, doublereal *, integer *, doublereal *, integer *); static logical leftv; extern /* Subroutine */ int xerbla_(char *, integer *); static logical rightv; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University September 30, 1994 Purpose ======= DGEBAK forms the right or left eigenvectors of a real general matrix by backward transformation on the computed eigenvectors of the balanced matrix output by DGEBAL. Arguments ========= JOB (input) CHARACTER*1 Specifies the type of backward transformation required: = 'N', do nothing, return immediately; = 'P', do backward transformation for permutation only; = 'S', do backward transformation for scaling only; = 'B', do backward transformations for both permutation and scaling. JOB must be the same as the argument JOB supplied to DGEBAL. SIDE (input) CHARACTER*1 = 'R': V contains right eigenvectors; = 'L': V contains left eigenvectors. N (input) INTEGER The number of rows of the matrix V. N >= 0. ILO (input) INTEGER IHI (input) INTEGER The integers ILO and IHI determined by DGEBAL. 1 <= ILO <= IHI <= N, if N > 0; ILO=1 and IHI=0, if N=0. SCALE (input) DOUBLE PRECISION array, dimension (N) Details of the permutation and scaling factors, as returned by DGEBAL. M (input) INTEGER The number of columns of the matrix V. M >= 0. V (input/output) DOUBLE PRECISION array, dimension (LDV,M) On entry, the matrix of right or left eigenvectors to be transformed, as returned by DHSEIN or DTREVC. On exit, V is overwritten by the transformed eigenvectors. LDV (input) INTEGER The leading dimension of the array V. LDV >= max(1,N). INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value. ===================================================================== Decode and Test the input parameters */ /* Parameter adjustments */ --scale; v_dim1 = *ldv; v_offset = 1 + v_dim1; v -= v_offset; /* Function Body */ rightv = lsame_(side, "R"); leftv = lsame_(side, "L"); *info = 0; if (! lsame_(job, "N") && ! lsame_(job, "P") && ! lsame_(job, "S") && ! lsame_(job, "B")) { *info = -1; } else if (! rightv && ! leftv) { *info = -2; } else if (*n < 0) { *info = -3; } else if ((*ilo < 1) || (*ilo > max(1,*n))) { *info = -4; } else if ((*ihi < min(*ilo,*n)) || (*ihi > *n)) { *info = -5; } else if (*m < 0) { *info = -7; } else if (*ldv < max(1,*n)) { *info = -9; } if (*info != 0) { i__1 = -(*info); xerbla_("DGEBAK", &i__1); return 0; } /* Quick return if possible */ if (*n == 0) { return 0; } if (*m == 0) { return 0; } if (lsame_(job, "N")) { return 0; } if (*ilo == *ihi) { goto L30; } /* Backward balance */ if ((lsame_(job, "S")) || (lsame_(job, "B"))) { if (rightv) { i__1 = *ihi; for (i__ = *ilo; i__ <= i__1; ++i__) { s = scale[i__]; dscal_(m, &s, &v[i__ + v_dim1], ldv); /* L10: */ } } if (leftv) { i__1 = *ihi; for (i__ = *ilo; i__ <= i__1; ++i__) { s = 1. / scale[i__]; dscal_(m, &s, &v[i__ + v_dim1], ldv); /* L20: */ } } } /* Backward permutation For I = ILO-1 step -1 until 1, IHI+1 step 1 until N do -- */ L30: if ((lsame_(job, "P")) || (lsame_(job, "B"))) { if (rightv) { i__1 = *n; for (ii = 1; ii <= i__1; ++ii) { i__ = ii; if (i__ >= *ilo && i__ <= *ihi) { goto L40; } if (i__ < *ilo) { i__ = *ilo - ii; } k = (integer) scale[i__]; if (k == i__) { goto L40; } dswap_(m, &v[i__ + v_dim1], ldv, &v[k + v_dim1], ldv); L40: ; } } if (leftv) { i__1 = *n; for (ii = 1; ii <= i__1; ++ii) { i__ = ii; if (i__ >= *ilo && i__ <= *ihi) { goto L50; } if (i__ < *ilo) { i__ = *ilo - ii; } k = (integer) scale[i__]; if (k == i__) { goto L50; } dswap_(m, &v[i__ + v_dim1], ldv, &v[k + v_dim1], ldv); L50: ; } } } return 0; /* End of DGEBAK */ } /* dgebak_ */ /* Subroutine */ int dgebal_(char *job, integer *n, doublereal *a, integer * lda, integer *ilo, integer *ihi, doublereal *scale, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2; doublereal d__1, d__2; /* Local variables */ static doublereal c__, f, g; static integer i__, j, k, l, m; static doublereal r__, s, ca, ra; static integer ica, ira, iexc; extern /* Subroutine */ int dscal_(integer *, doublereal *, doublereal *, integer *); extern logical lsame_(char *, char *); extern /* Subroutine */ int dswap_(integer *, doublereal *, integer *, doublereal *, integer *); static doublereal sfmin1, sfmin2, sfmax1, sfmax2; extern integer idamax_(integer *, doublereal *, integer *); extern /* Subroutine */ int xerbla_(char *, integer *); static logical noconv; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= DGEBAL balances a general real matrix A. This involves, first, permuting A by a similarity transformation to isolate eigenvalues in the first 1 to ILO-1 and last IHI+1 to N elements on the diagonal; and second, applying a diagonal similarity transformation to rows and columns ILO to IHI to make the rows and columns as close in norm as possible. Both steps are optional. Balancing may reduce the 1-norm of the matrix, and improve the accuracy of the computed eigenvalues and/or eigenvectors. Arguments ========= JOB (input) CHARACTER*1 Specifies the operations to be performed on A: = 'N': none: simply set ILO = 1, IHI = N, SCALE(I) = 1.0 for i = 1,...,N; = 'P': permute only; = 'S': scale only; = 'B': both permute and scale. N (input) INTEGER The order of the matrix A. N >= 0. A (input/output) DOUBLE PRECISION array, dimension (LDA,N) On entry, the input matrix A. On exit, A is overwritten by the balanced matrix. If JOB = 'N', A is not referenced. See Further Details. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,N). ILO (output) INTEGER IHI (output) INTEGER ILO and IHI are set to integers such that on exit A(i,j) = 0 if i > j and j = 1,...,ILO-1 or I = IHI+1,...,N. If JOB = 'N' or 'S', ILO = 1 and IHI = N. SCALE (output) DOUBLE PRECISION array, dimension (N) Details of the permutations and scaling factors applied to A. If P(j) is the index of the row and column interchanged with row and column j and D(j) is the scaling factor applied to row and column j, then SCALE(j) = P(j) for j = 1,...,ILO-1 = D(j) for j = ILO,...,IHI = P(j) for j = IHI+1,...,N. The order in which the interchanges are made is N to IHI+1, then 1 to ILO-1. INFO (output) INTEGER = 0: successful exit. < 0: if INFO = -i, the i-th argument had an illegal value. Further Details =============== The permutations consist of row and column interchanges which put the matrix in the form ( T1 X Y ) P A P = ( 0 B Z ) ( 0 0 T2 ) where T1 and T2 are upper triangular matrices whose eigenvalues lie along the diagonal. The column indices ILO and IHI mark the starting and ending columns of the submatrix B. Balancing consists of applying a diagonal similarity transformation inv(D) * B * D to make the 1-norms of each row of B and its corresponding column nearly equal. The output matrix is ( T1 X*D Y ) ( 0 inv(D)*B*D inv(D)*Z ). ( 0 0 T2 ) Information about the permutations P and the diagonal matrix D is returned in the vector SCALE. This subroutine is based on the EISPACK routine BALANC. Modified by Tzu-Yi Chen, Computer Science Division, University of California at Berkeley, USA ===================================================================== Test the input parameters */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --scale; /* Function Body */ *info = 0; if (! lsame_(job, "N") && ! lsame_(job, "P") && ! lsame_(job, "S") && ! lsame_(job, "B")) { *info = -1; } else if (*n < 0) { *info = -2; } else if (*lda < max(1,*n)) { *info = -4; } if (*info != 0) { i__1 = -(*info); xerbla_("DGEBAL", &i__1); return 0; } k = 1; l = *n; if (*n == 0) { goto L210; } if (lsame_(job, "N")) { i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { scale[i__] = 1.; /* L10: */ } goto L210; } if (lsame_(job, "S")) { goto L120; } /* Permutation to isolate eigenvalues if possible */ goto L50; /* Row and column exchange. */ L20: scale[m] = (doublereal) j; if (j == m) { goto L30; } dswap_(&l, &a[j * a_dim1 + 1], &c__1, &a[m * a_dim1 + 1], &c__1); i__1 = *n - k + 1; dswap_(&i__1, &a[j + k * a_dim1], lda, &a[m + k * a_dim1], lda); L30: switch (iexc) { case 1: goto L40; case 2: goto L80; } /* Search for rows isolating an eigenvalue and push them down. */ L40: if (l == 1) { goto L210; } --l; L50: for (j = l; j >= 1; --j) { i__1 = l; for (i__ = 1; i__ <= i__1; ++i__) { if (i__ == j) { goto L60; } if (a[j + i__ * a_dim1] != 0.) { goto L70; } L60: ; } m = l; iexc = 1; goto L20; L70: ; } goto L90; /* Search for columns isolating an eigenvalue and push them left. */ L80: ++k; L90: i__1 = l; for (j = k; j <= i__1; ++j) { i__2 = l; for (i__ = k; i__ <= i__2; ++i__) { if (i__ == j) { goto L100; } if (a[i__ + j * a_dim1] != 0.) { goto L110; } L100: ; } m = k; iexc = 2; goto L20; L110: ; } L120: i__1 = l; for (i__ = k; i__ <= i__1; ++i__) { scale[i__] = 1.; /* L130: */ } if (lsame_(job, "P")) { goto L210; } /* Balance the submatrix in rows K to L. Iterative loop for norm reduction */ sfmin1 = SAFEMINIMUM / PRECISION; sfmax1 = 1. / sfmin1; sfmin2 = sfmin1 * 8.; sfmax2 = 1. / sfmin2; L140: noconv = FALSE_; i__1 = l; for (i__ = k; i__ <= i__1; ++i__) { c__ = 0.; r__ = 0.; i__2 = l; for (j = k; j <= i__2; ++j) { if (j == i__) { goto L150; } c__ += (d__1 = a[j + i__ * a_dim1], abs(d__1)); r__ += (d__1 = a[i__ + j * a_dim1], abs(d__1)); L150: ; } ica = idamax_(&l, &a[i__ * a_dim1 + 1], &c__1); ca = (d__1 = a[ica + i__ * a_dim1], abs(d__1)); i__2 = *n - k + 1; ira = idamax_(&i__2, &a[i__ + k * a_dim1], lda); ra = (d__1 = a[i__ + (ira + k - 1) * a_dim1], abs(d__1)); /* Guard against zero C or R due to underflow. */ if ((c__ == 0.) || (r__ == 0.)) { goto L200; } g = r__ / 8.; f = 1.; s = c__ + r__; L160: /* Computing MAX */ d__1 = max(f,c__); /* Computing MIN */ d__2 = min(r__,g); if (((c__ >= g) || (max(d__1,ca) >= sfmax2)) || (min(d__2,ra) <= sfmin2)) { goto L170; } f *= 8.; c__ *= 8.; ca *= 8.; r__ /= 8.; g /= 8.; ra /= 8.; goto L160; L170: g = c__ / 8.; L180: /* Computing MIN */ d__1 = min(f,c__), d__1 = min(d__1,g); if (((g < r__) || (max(r__,ra) >= sfmax2)) || (min(d__1,ca) <= sfmin2) ) { goto L190; } f /= 8.; c__ /= 8.; g /= 8.; ca /= 8.; r__ *= 8.; ra *= 8.; goto L180; /* Now balance. */ L190: if (c__ + r__ >= s * .95) { goto L200; } if (f < 1. && scale[i__] < 1.) { if (f * scale[i__] <= sfmin1) { goto L200; } } if (f > 1. && scale[i__] > 1.) { if (scale[i__] >= sfmax1 / f) { goto L200; } } g = 1. / f; scale[i__] *= f; noconv = TRUE_; i__2 = *n - k + 1; dscal_(&i__2, &g, &a[i__ + k * a_dim1], lda); dscal_(&l, &f, &a[i__ * a_dim1 + 1], &c__1); L200: ; } if (noconv) { goto L140; } L210: *ilo = k; *ihi = l; return 0; /* End of DGEBAL */ } /* dgebal_ */ /* Subroutine */ int dgebd2_(integer *m, integer *n, doublereal *a, integer * lda, doublereal *d__, doublereal *e, doublereal *tauq, doublereal * taup, doublereal *work, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3, i__4; /* Local variables */ static integer i__; extern /* Subroutine */ int dlarf_(char *, integer *, integer *, doublereal *, integer *, doublereal *, doublereal *, integer *, doublereal *), dlarfg_(integer *, doublereal *, doublereal *, integer *, doublereal *), xerbla_(char *, integer *); /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University February 29, 1992 Purpose ======= DGEBD2 reduces a real general m by n matrix A to upper or lower bidiagonal form B by an orthogonal transformation: Q' * A * P = B. If m >= n, B is upper bidiagonal; if m < n, B is lower bidiagonal. Arguments ========= M (input) INTEGER The number of rows in the matrix A. M >= 0. N (input) INTEGER The number of columns in the matrix A. N >= 0. A (input/output) DOUBLE PRECISION array, dimension (LDA,N) On entry, the m by n general matrix to be reduced. On exit, if m >= n, the diagonal and the first superdiagonal are overwritten with the upper bidiagonal matrix B; the elements below the diagonal, with the array TAUQ, represent the orthogonal matrix Q as a product of elementary reflectors, and the elements above the first superdiagonal, with the array TAUP, represent the orthogonal matrix P as a product of elementary reflectors; if m < n, the diagonal and the first subdiagonal are overwritten with the lower bidiagonal matrix B; the elements below the first subdiagonal, with the array TAUQ, represent the orthogonal matrix Q as a product of elementary reflectors, and the elements above the diagonal, with the array TAUP, represent the orthogonal matrix P as a product of elementary reflectors. See Further Details. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,M). D (output) DOUBLE PRECISION array, dimension (min(M,N)) The diagonal elements of the bidiagonal matrix B: D(i) = A(i,i). E (output) DOUBLE PRECISION array, dimension (min(M,N)-1) The off-diagonal elements of the bidiagonal matrix B: if m >= n, E(i) = A(i,i+1) for i = 1,2,...,n-1; if m < n, E(i) = A(i+1,i) for i = 1,2,...,m-1. TAUQ (output) DOUBLE PRECISION array dimension (min(M,N)) The scalar factors of the elementary reflectors which represent the orthogonal matrix Q. See Further Details. TAUP (output) DOUBLE PRECISION array, dimension (min(M,N)) The scalar factors of the elementary reflectors which represent the orthogonal matrix P. See Further Details. WORK (workspace) DOUBLE PRECISION array, dimension (max(M,N)) INFO (output) INTEGER = 0: successful exit. < 0: if INFO = -i, the i-th argument had an illegal value. Further Details =============== The matrices Q and P are represented as products of elementary reflectors: If m >= n, Q = H(1) H(2) . . . H(n) and P = G(1) G(2) . . . G(n-1) Each H(i) and G(i) has the form: H(i) = I - tauq * v * v' and G(i) = I - taup * u * u' where tauq and taup are real scalars, and v and u are real vectors; v(1:i-1) = 0, v(i) = 1, and v(i+1:m) is stored on exit in A(i+1:m,i); u(1:i) = 0, u(i+1) = 1, and u(i+2:n) is stored on exit in A(i,i+2:n); tauq is stored in TAUQ(i) and taup in TAUP(i). If m < n, Q = H(1) H(2) . . . H(m-1) and P = G(1) G(2) . . . G(m) Each H(i) and G(i) has the form: H(i) = I - tauq * v * v' and G(i) = I - taup * u * u' where tauq and taup are real scalars, and v and u are real vectors; v(1:i) = 0, v(i+1) = 1, and v(i+2:m) is stored on exit in A(i+2:m,i); u(1:i-1) = 0, u(i) = 1, and u(i+1:n) is stored on exit in A(i,i+1:n); tauq is stored in TAUQ(i) and taup in TAUP(i). The contents of A on exit are illustrated by the following examples: m = 6 and n = 5 (m > n): m = 5 and n = 6 (m < n): ( d e u1 u1 u1 ) ( d u1 u1 u1 u1 u1 ) ( v1 d e u2 u2 ) ( e d u2 u2 u2 u2 ) ( v1 v2 d e u3 ) ( v1 e d u3 u3 u3 ) ( v1 v2 v3 d e ) ( v1 v2 e d u4 u4 ) ( v1 v2 v3 v4 d ) ( v1 v2 v3 e d u5 ) ( v1 v2 v3 v4 v5 ) where d and e denote diagonal and off-diagonal elements of B, vi denotes an element of the vector defining H(i), and ui an element of the vector defining G(i). ===================================================================== Test the input parameters */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --d__; --e; --tauq; --taup; --work; /* Function Body */ *info = 0; if (*m < 0) { *info = -1; } else if (*n < 0) { *info = -2; } else if (*lda < max(1,*m)) { *info = -4; } if (*info < 0) { i__1 = -(*info); xerbla_("DGEBD2", &i__1); return 0; } if (*m >= *n) { /* Reduce to upper bidiagonal form */ i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { /* Generate elementary reflector H(i) to annihilate A(i+1:m,i) */ i__2 = *m - i__ + 1; /* Computing MIN */ i__3 = i__ + 1; dlarfg_(&i__2, &a[i__ + i__ * a_dim1], &a[min(i__3,*m) + i__ * a_dim1], &c__1, &tauq[i__]); d__[i__] = a[i__ + i__ * a_dim1]; a[i__ + i__ * a_dim1] = 1.; /* Apply H(i) to A(i:m,i+1:n) from the left */ i__2 = *m - i__ + 1; i__3 = *n - i__; dlarf_("Left", &i__2, &i__3, &a[i__ + i__ * a_dim1], &c__1, &tauq[ i__], &a[i__ + (i__ + 1) * a_dim1], lda, &work[1]); a[i__ + i__ * a_dim1] = d__[i__]; if (i__ < *n) { /* Generate elementary reflector G(i) to annihilate A(i,i+2:n) */ i__2 = *n - i__; /* Computing MIN */ i__3 = i__ + 2; dlarfg_(&i__2, &a[i__ + (i__ + 1) * a_dim1], &a[i__ + min( i__3,*n) * a_dim1], lda, &taup[i__]); e[i__] = a[i__ + (i__ + 1) * a_dim1]; a[i__ + (i__ + 1) * a_dim1] = 1.; /* Apply G(i) to A(i+1:m,i+1:n) from the right */ i__2 = *m - i__; i__3 = *n - i__; dlarf_("Right", &i__2, &i__3, &a[i__ + (i__ + 1) * a_dim1], lda, &taup[i__], &a[i__ + 1 + (i__ + 1) * a_dim1], lda, &work[1]); a[i__ + (i__ + 1) * a_dim1] = e[i__]; } else { taup[i__] = 0.; } /* L10: */ } } else { /* Reduce to lower bidiagonal form */ i__1 = *m; for (i__ = 1; i__ <= i__1; ++i__) { /* Generate elementary reflector G(i) to annihilate A(i,i+1:n) */ i__2 = *n - i__ + 1; /* Computing MIN */ i__3 = i__ + 1; dlarfg_(&i__2, &a[i__ + i__ * a_dim1], &a[i__ + min(i__3,*n) * a_dim1], lda, &taup[i__]); d__[i__] = a[i__ + i__ * a_dim1]; a[i__ + i__ * a_dim1] = 1.; /* Apply G(i) to A(i+1:m,i:n) from the right */ i__2 = *m - i__; i__3 = *n - i__ + 1; /* Computing MIN */ i__4 = i__ + 1; dlarf_("Right", &i__2, &i__3, &a[i__ + i__ * a_dim1], lda, &taup[ i__], &a[min(i__4,*m) + i__ * a_dim1], lda, &work[1]); a[i__ + i__ * a_dim1] = d__[i__]; if (i__ < *m) { /* Generate elementary reflector H(i) to annihilate A(i+2:m,i) */ i__2 = *m - i__; /* Computing MIN */ i__3 = i__ + 2; dlarfg_(&i__2, &a[i__ + 1 + i__ * a_dim1], &a[min(i__3,*m) + i__ * a_dim1], &c__1, &tauq[i__]); e[i__] = a[i__ + 1 + i__ * a_dim1]; a[i__ + 1 + i__ * a_dim1] = 1.; /* Apply H(i) to A(i+1:m,i+1:n) from the left */ i__2 = *m - i__; i__3 = *n - i__; dlarf_("Left", &i__2, &i__3, &a[i__ + 1 + i__ * a_dim1], & c__1, &tauq[i__], &a[i__ + 1 + (i__ + 1) * a_dim1], lda, &work[1]); a[i__ + 1 + i__ * a_dim1] = e[i__]; } else { tauq[i__] = 0.; } /* L20: */ } } return 0; /* End of DGEBD2 */ } /* dgebd2_ */ /* Subroutine */ int dgebrd_(integer *m, integer *n, doublereal *a, integer * lda, doublereal *d__, doublereal *e, doublereal *tauq, doublereal * taup, doublereal *work, integer *lwork, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3, i__4; /* Local variables */ static integer i__, j, nb, nx; static doublereal ws; extern /* Subroutine */ int dgemm_(char *, char *, integer *, integer *, integer *, doublereal *, doublereal *, integer *, doublereal *, integer *, doublereal *, doublereal *, integer *); static integer nbmin, iinfo, minmn; extern /* Subroutine */ int dgebd2_(integer *, integer *, doublereal *, integer *, doublereal *, doublereal *, doublereal *, doublereal *, doublereal *, integer *), dlabrd_(integer *, integer *, integer * , doublereal *, integer *, doublereal *, doublereal *, doublereal *, doublereal *, doublereal *, integer *, doublereal *, integer *) , xerbla_(char *, integer *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); static integer ldwrkx, ldwrky, lwkopt; static logical lquery; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= DGEBRD reduces a general real M-by-N matrix A to upper or lower bidiagonal form B by an orthogonal transformation: Q**T * A * P = B. If m >= n, B is upper bidiagonal; if m < n, B is lower bidiagonal. Arguments ========= M (input) INTEGER The number of rows in the matrix A. M >= 0. N (input) INTEGER The number of columns in the matrix A. N >= 0. A (input/output) DOUBLE PRECISION array, dimension (LDA,N) On entry, the M-by-N general matrix to be reduced. On exit, if m >= n, the diagonal and the first superdiagonal are overwritten with the upper bidiagonal matrix B; the elements below the diagonal, with the array TAUQ, represent the orthogonal matrix Q as a product of elementary reflectors, and the elements above the first superdiagonal, with the array TAUP, represent the orthogonal matrix P as a product of elementary reflectors; if m < n, the diagonal and the first subdiagonal are overwritten with the lower bidiagonal matrix B; the elements below the first subdiagonal, with the array TAUQ, represent the orthogonal matrix Q as a product of elementary reflectors, and the elements above the diagonal, with the array TAUP, represent the orthogonal matrix P as a product of elementary reflectors. See Further Details. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,M). D (output) DOUBLE PRECISION array, dimension (min(M,N)) The diagonal elements of the bidiagonal matrix B: D(i) = A(i,i). E (output) DOUBLE PRECISION array, dimension (min(M,N)-1) The off-diagonal elements of the bidiagonal matrix B: if m >= n, E(i) = A(i,i+1) for i = 1,2,...,n-1; if m < n, E(i) = A(i+1,i) for i = 1,2,...,m-1. TAUQ (output) DOUBLE PRECISION array dimension (min(M,N)) The scalar factors of the elementary reflectors which represent the orthogonal matrix Q. See Further Details. TAUP (output) DOUBLE PRECISION array, dimension (min(M,N)) The scalar factors of the elementary reflectors which represent the orthogonal matrix P. See Further Details. WORK (workspace/output) DOUBLE PRECISION array, dimension (LWORK) On exit, if INFO = 0, WORK(1) returns the optimal LWORK. LWORK (input) INTEGER The length of the array WORK. LWORK >= max(1,M,N). For optimum performance LWORK >= (M+N)*NB, where NB is the optimal blocksize. If LWORK = -1, then a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued by XERBLA. INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value. Further Details =============== The matrices Q and P are represented as products of elementary reflectors: If m >= n, Q = H(1) H(2) . . . H(n) and P = G(1) G(2) . . . G(n-1) Each H(i) and G(i) has the form: H(i) = I - tauq * v * v' and G(i) = I - taup * u * u' where tauq and taup are real scalars, and v and u are real vectors; v(1:i-1) = 0, v(i) = 1, and v(i+1:m) is stored on exit in A(i+1:m,i); u(1:i) = 0, u(i+1) = 1, and u(i+2:n) is stored on exit in A(i,i+2:n); tauq is stored in TAUQ(i) and taup in TAUP(i). If m < n, Q = H(1) H(2) . . . H(m-1) and P = G(1) G(2) . . . G(m) Each H(i) and G(i) has the form: H(i) = I - tauq * v * v' and G(i) = I - taup * u * u' where tauq and taup are real scalars, and v and u are real vectors; v(1:i) = 0, v(i+1) = 1, and v(i+2:m) is stored on exit in A(i+2:m,i); u(1:i-1) = 0, u(i) = 1, and u(i+1:n) is stored on exit in A(i,i+1:n); tauq is stored in TAUQ(i) and taup in TAUP(i). The contents of A on exit are illustrated by the following examples: m = 6 and n = 5 (m > n): m = 5 and n = 6 (m < n): ( d e u1 u1 u1 ) ( d u1 u1 u1 u1 u1 ) ( v1 d e u2 u2 ) ( e d u2 u2 u2 u2 ) ( v1 v2 d e u3 ) ( v1 e d u3 u3 u3 ) ( v1 v2 v3 d e ) ( v1 v2 e d u4 u4 ) ( v1 v2 v3 v4 d ) ( v1 v2 v3 e d u5 ) ( v1 v2 v3 v4 v5 ) where d and e denote diagonal and off-diagonal elements of B, vi denotes an element of the vector defining H(i), and ui an element of the vector defining G(i). ===================================================================== Test the input parameters */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --d__; --e; --tauq; --taup; --work; /* Function Body */ *info = 0; /* Computing MAX */ i__1 = 1, i__2 = ilaenv_(&c__1, "DGEBRD", " ", m, n, &c_n1, &c_n1, ( ftnlen)6, (ftnlen)1); nb = max(i__1,i__2); lwkopt = (*m + *n) * nb; work[1] = (doublereal) lwkopt; lquery = *lwork == -1; if (*m < 0) { *info = -1; } else if (*n < 0) { *info = -2; } else if (*lda < max(1,*m)) { *info = -4; } else /* if(complicated condition) */ { /* Computing MAX */ i__1 = max(1,*m); if (*lwork < max(i__1,*n) && ! lquery) { *info = -10; } } if (*info < 0) { i__1 = -(*info); xerbla_("DGEBRD", &i__1); return 0; } else if (lquery) { return 0; } /* Quick return if possible */ minmn = min(*m,*n); if (minmn == 0) { work[1] = 1.; return 0; } ws = (doublereal) max(*m,*n); ldwrkx = *m; ldwrky = *n; if (nb > 1 && nb < minmn) { /* Set the crossover point NX. Computing MAX */ i__1 = nb, i__2 = ilaenv_(&c__3, "DGEBRD", " ", m, n, &c_n1, &c_n1, ( ftnlen)6, (ftnlen)1); nx = max(i__1,i__2); /* Determine when to switch from blocked to unblocked code. */ if (nx < minmn) { ws = (doublereal) ((*m + *n) * nb); if ((doublereal) (*lwork) < ws) { /* Not enough work space for the optimal NB, consider using a smaller block size. */ nbmin = ilaenv_(&c__2, "DGEBRD", " ", m, n, &c_n1, &c_n1, ( ftnlen)6, (ftnlen)1); if (*lwork >= (*m + *n) * nbmin) { nb = *lwork / (*m + *n); } else { nb = 1; nx = minmn; } } } } else { nx = minmn; } i__1 = minmn - nx; i__2 = nb; for (i__ = 1; i__2 < 0 ? i__ >= i__1 : i__ <= i__1; i__ += i__2) { /* Reduce rows and columns i:i+nb-1 to bidiagonal form and return the matrices X and Y which are needed to update the unreduced part of the matrix */ i__3 = *m - i__ + 1; i__4 = *n - i__ + 1; dlabrd_(&i__3, &i__4, &nb, &a[i__ + i__ * a_dim1], lda, &d__[i__], &e[ i__], &tauq[i__], &taup[i__], &work[1], &ldwrkx, &work[ldwrkx * nb + 1], &ldwrky); /* Update the trailing submatrix A(i+nb:m,i+nb:n), using an update of the form A := A - V*Y' - X*U' */ i__3 = *m - i__ - nb + 1; i__4 = *n - i__ - nb + 1; dgemm_("No transpose", "Transpose", &i__3, &i__4, &nb, &c_b3001, &a[ i__ + nb + i__ * a_dim1], lda, &work[ldwrkx * nb + nb + 1], & ldwrky, &c_b2865, &a[i__ + nb + (i__ + nb) * a_dim1], lda); i__3 = *m - i__ - nb + 1; i__4 = *n - i__ - nb + 1; dgemm_("No transpose", "No transpose", &i__3, &i__4, &nb, &c_b3001, & work[nb + 1], &ldwrkx, &a[i__ + (i__ + nb) * a_dim1], lda, & c_b2865, &a[i__ + nb + (i__ + nb) * a_dim1], lda); /* Copy diagonal and off-diagonal elements of B back into A */ if (*m >= *n) { i__3 = i__ + nb - 1; for (j = i__; j <= i__3; ++j) { a[j + j * a_dim1] = d__[j]; a[j + (j + 1) * a_dim1] = e[j]; /* L10: */ } } else { i__3 = i__ + nb - 1; for (j = i__; j <= i__3; ++j) { a[j + j * a_dim1] = d__[j]; a[j + 1 + j * a_dim1] = e[j]; /* L20: */ } } /* L30: */ } /* Use unblocked code to reduce the remainder of the matrix */ i__2 = *m - i__ + 1; i__1 = *n - i__ + 1; dgebd2_(&i__2, &i__1, &a[i__ + i__ * a_dim1], lda, &d__[i__], &e[i__], & tauq[i__], &taup[i__], &work[1], &iinfo); work[1] = ws; return 0; /* End of DGEBRD */ } /* dgebrd_ */ /* Subroutine */ int dgeev_(char *jobvl, char *jobvr, integer *n, doublereal * a, integer *lda, doublereal *wr, doublereal *wi, doublereal *vl, integer *ldvl, doublereal *vr, integer *ldvr, doublereal *work, integer *lwork, integer *info) { /* System generated locals */ integer a_dim1, a_offset, vl_dim1, vl_offset, vr_dim1, vr_offset, i__1, i__2, i__3, i__4; doublereal d__1, d__2; /* Builtin functions */ double sqrt(doublereal); /* Local variables */ static integer i__, k; static doublereal r__, cs, sn; static integer ihi; static doublereal scl; static integer ilo; static doublereal dum[1], eps; static integer ibal; static char side[1]; static integer maxb; static doublereal anrm; static integer ierr, itau; extern /* Subroutine */ int drot_(integer *, doublereal *, integer *, doublereal *, integer *, doublereal *, doublereal *); static integer iwrk, nout; extern doublereal dnrm2_(integer *, doublereal *, integer *); extern /* Subroutine */ int dscal_(integer *, doublereal *, doublereal *, integer *); extern logical lsame_(char *, char *); extern doublereal dlapy2_(doublereal *, doublereal *); extern /* Subroutine */ int dlabad_(doublereal *, doublereal *), dgebak_( char *, char *, integer *, integer *, integer *, doublereal *, integer *, doublereal *, integer *, integer *), dgebal_(char *, integer *, doublereal *, integer *, integer *, integer *, doublereal *, integer *); static logical scalea; static doublereal cscale; extern doublereal dlange_(char *, integer *, integer *, doublereal *, integer *, doublereal *); extern /* Subroutine */ int dgehrd_(integer *, integer *, integer *, doublereal *, integer *, doublereal *, doublereal *, integer *, integer *), dlascl_(char *, integer *, integer *, doublereal *, doublereal *, integer *, integer *, doublereal *, integer *, integer *); extern integer idamax_(integer *, doublereal *, integer *); extern /* Subroutine */ int dlacpy_(char *, integer *, integer *, doublereal *, integer *, doublereal *, integer *), dlartg_(doublereal *, doublereal *, doublereal *, doublereal *, doublereal *), xerbla_(char *, integer *); static logical select[1]; extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); static doublereal bignum; extern /* Subroutine */ int dorghr_(integer *, integer *, integer *, doublereal *, integer *, doublereal *, doublereal *, integer *, integer *), dhseqr_(char *, char *, integer *, integer *, integer *, doublereal *, integer *, doublereal *, doublereal *, doublereal *, integer *, doublereal *, integer *, integer *), dtrevc_(char *, char *, logical *, integer *, doublereal *, integer *, doublereal *, integer *, doublereal *, integer *, integer *, integer *, doublereal *, integer *); static integer minwrk, maxwrk; static logical wantvl; static doublereal smlnum; static integer hswork; static logical lquery, wantvr; /* -- LAPACK driver routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University December 8, 1999 Purpose ======= DGEEV computes for an N-by-N real nonsymmetric matrix A, the eigenvalues and, optionally, the left and/or right eigenvectors. The right eigenvector v(j) of A satisfies A * v(j) = lambda(j) * v(j) where lambda(j) is its eigenvalue. The left eigenvector u(j) of A satisfies u(j)**H * A = lambda(j) * u(j)**H where u(j)**H denotes the conjugate transpose of u(j). The computed eigenvectors are normalized to have Euclidean norm equal to 1 and largest component real. Arguments ========= JOBVL (input) CHARACTER*1 = 'N': left eigenvectors of A are not computed; = 'V': left eigenvectors of A are computed. JOBVR (input) CHARACTER*1 = 'N': right eigenvectors of A are not computed; = 'V': right eigenvectors of A are computed. N (input) INTEGER The order of the matrix A. N >= 0. A (input/output) DOUBLE PRECISION array, dimension (LDA,N) On entry, the N-by-N matrix A. On exit, A has been overwritten. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,N). WR (output) DOUBLE PRECISION array, dimension (N) WI (output) DOUBLE PRECISION array, dimension (N) WR and WI contain the real and imaginary parts, respectively, of the computed eigenvalues. Complex conjugate pairs of eigenvalues appear consecutively with the eigenvalue having the positive imaginary part first. VL (output) DOUBLE PRECISION array, dimension (LDVL,N) If JOBVL = 'V', the left eigenvectors u(j) are stored one after another in the columns of VL, in the same order as their eigenvalues. If JOBVL = 'N', VL is not referenced. If the j-th eigenvalue is real, then u(j) = VL(:,j), the j-th column of VL. If the j-th and (j+1)-st eigenvalues form a complex conjugate pair, then u(j) = VL(:,j) + i*VL(:,j+1) and u(j+1) = VL(:,j) - i*VL(:,j+1). LDVL (input) INTEGER The leading dimension of the array VL. LDVL >= 1; if JOBVL = 'V', LDVL >= N. VR (output) DOUBLE PRECISION array, dimension (LDVR,N) If JOBVR = 'V', the right eigenvectors v(j) are stored one after another in the columns of VR, in the same order as their eigenvalues. If JOBVR = 'N', VR is not referenced. If the j-th eigenvalue is real, then v(j) = VR(:,j), the j-th column of VR. If the j-th and (j+1)-st eigenvalues form a complex conjugate pair, then v(j) = VR(:,j) + i*VR(:,j+1) and v(j+1) = VR(:,j) - i*VR(:,j+1). LDVR (input) INTEGER The leading dimension of the array VR. LDVR >= 1; if JOBVR = 'V', LDVR >= N. WORK (workspace/output) DOUBLE PRECISION array, dimension (LWORK) On exit, if INFO = 0, WORK(1) returns the optimal LWORK. LWORK (input) INTEGER The dimension of the array WORK. LWORK >= max(1,3*N), and if JOBVL = 'V' or JOBVR = 'V', LWORK >= 4*N. For good performance, LWORK must generally be larger. If LWORK = -1, then a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued by XERBLA. INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value. > 0: if INFO = i, the QR algorithm failed to compute all the eigenvalues, and no eigenvectors have been computed; elements i+1:N of WR and WI contain eigenvalues which have converged. ===================================================================== Test the input arguments */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --wr; --wi; vl_dim1 = *ldvl; vl_offset = 1 + vl_dim1; vl -= vl_offset; vr_dim1 = *ldvr; vr_offset = 1 + vr_dim1; vr -= vr_offset; --work; /* Function Body */ *info = 0; lquery = *lwork == -1; wantvl = lsame_(jobvl, "V"); wantvr = lsame_(jobvr, "V"); if (! wantvl && ! lsame_(jobvl, "N")) { *info = -1; } else if (! wantvr && ! lsame_(jobvr, "N")) { *info = -2; } else if (*n < 0) { *info = -3; } else if (*lda < max(1,*n)) { *info = -5; } else if ((*ldvl < 1) || (wantvl && *ldvl < *n)) { *info = -9; } else if ((*ldvr < 1) || (wantvr && *ldvr < *n)) { *info = -11; } /* Compute workspace (Note: Comments in the code beginning "Workspace:" describe the minimal amount of workspace needed at that point in the code, as well as the preferred amount for good performance. NB refers to the optimal block size for the immediately following subroutine, as returned by ILAENV. HSWORK refers to the workspace preferred by DHSEQR, as calculated below. HSWORK is computed assuming ILO=1 and IHI=N, the worst case.) */ minwrk = 1; if (*info == 0 && ((*lwork >= 1) || (lquery))) { maxwrk = ((*n) << (1)) + *n * ilaenv_(&c__1, "DGEHRD", " ", n, &c__1, n, &c__0, (ftnlen)6, (ftnlen)1); if (! wantvl && ! wantvr) { /* Computing MAX */ i__1 = 1, i__2 = *n * 3; minwrk = max(i__1,i__2); /* Computing MAX */ i__1 = ilaenv_(&c__8, "DHSEQR", "EN", n, &c__1, n, &c_n1, (ftnlen) 6, (ftnlen)2); maxb = max(i__1,2); /* Computing MIN Computing MAX */ i__3 = 2, i__4 = ilaenv_(&c__4, "DHSEQR", "EN", n, &c__1, n, & c_n1, (ftnlen)6, (ftnlen)2); i__1 = min(maxb,*n), i__2 = max(i__3,i__4); k = min(i__1,i__2); /* Computing MAX */ i__1 = k * (k + 2), i__2 = (*n) << (1); hswork = max(i__1,i__2); /* Computing MAX */ i__1 = maxwrk, i__2 = *n + 1, i__1 = max(i__1,i__2), i__2 = *n + hswork; maxwrk = max(i__1,i__2); } else { /* Computing MAX */ i__1 = 1, i__2 = (*n) << (2); minwrk = max(i__1,i__2); /* Computing MAX */ i__1 = maxwrk, i__2 = ((*n) << (1)) + (*n - 1) * ilaenv_(&c__1, "DORGHR", " ", n, &c__1, n, &c_n1, (ftnlen)6, (ftnlen)1); maxwrk = max(i__1,i__2); /* Computing MAX */ i__1 = ilaenv_(&c__8, "DHSEQR", "SV", n, &c__1, n, &c_n1, (ftnlen) 6, (ftnlen)2); maxb = max(i__1,2); /* Computing MIN Computing MAX */ i__3 = 2, i__4 = ilaenv_(&c__4, "DHSEQR", "SV", n, &c__1, n, & c_n1, (ftnlen)6, (ftnlen)2); i__1 = min(maxb,*n), i__2 = max(i__3,i__4); k = min(i__1,i__2); /* Computing MAX */ i__1 = k * (k + 2), i__2 = (*n) << (1); hswork = max(i__1,i__2); /* Computing MAX */ i__1 = maxwrk, i__2 = *n + 1, i__1 = max(i__1,i__2), i__2 = *n + hswork; maxwrk = max(i__1,i__2); /* Computing MAX */ i__1 = maxwrk, i__2 = (*n) << (2); maxwrk = max(i__1,i__2); } work[1] = (doublereal) maxwrk; } if (*lwork < minwrk && ! lquery) { *info = -13; } if (*info != 0) { i__1 = -(*info); xerbla_("DGEEV ", &i__1); return 0; } else if (lquery) { return 0; } /* Quick return if possible */ if (*n == 0) { return 0; } /* Get machine constants */ eps = PRECISION; smlnum = SAFEMINIMUM; bignum = 1. / smlnum; dlabad_(&smlnum, &bignum); smlnum = sqrt(smlnum) / eps; bignum = 1. / smlnum; /* Scale A if max element outside range [SMLNUM,BIGNUM] */ anrm = dlange_("M", n, n, &a[a_offset], lda, dum); scalea = FALSE_; if (anrm > 0. && anrm < smlnum) { scalea = TRUE_; cscale = smlnum; } else if (anrm > bignum) { scalea = TRUE_; cscale = bignum; } if (scalea) { dlascl_("G", &c__0, &c__0, &anrm, &cscale, n, n, &a[a_offset], lda, & ierr); } /* Balance the matrix (Workspace: need N) */ ibal = 1; dgebal_("B", n, &a[a_offset], lda, &ilo, &ihi, &work[ibal], &ierr); /* Reduce to upper Hessenberg form (Workspace: need 3*N, prefer 2*N+N*NB) */ itau = ibal + *n; iwrk = itau + *n; i__1 = *lwork - iwrk + 1; dgehrd_(n, &ilo, &ihi, &a[a_offset], lda, &work[itau], &work[iwrk], &i__1, &ierr); if (wantvl) { /* Want left eigenvectors Copy Householder vectors to VL */ *(unsigned char *)side = 'L'; dlacpy_("L", n, n, &a[a_offset], lda, &vl[vl_offset], ldvl) ; /* Generate orthogonal matrix in VL (Workspace: need 3*N-1, prefer 2*N+(N-1)*NB) */ i__1 = *lwork - iwrk + 1; dorghr_(n, &ilo, &ihi, &vl[vl_offset], ldvl, &work[itau], &work[iwrk], &i__1, &ierr); /* Perform QR iteration, accumulating Schur vectors in VL (Workspace: need N+1, prefer N+HSWORK (see comments) ) */ iwrk = itau; i__1 = *lwork - iwrk + 1; dhseqr_("S", "V", n, &ilo, &ihi, &a[a_offset], lda, &wr[1], &wi[1], & vl[vl_offset], ldvl, &work[iwrk], &i__1, info); if (wantvr) { /* Want left and right eigenvectors Copy Schur vectors to VR */ *(unsigned char *)side = 'B'; dlacpy_("F", n, n, &vl[vl_offset], ldvl, &vr[vr_offset], ldvr); } } else if (wantvr) { /* Want right eigenvectors Copy Householder vectors to VR */ *(unsigned char *)side = 'R'; dlacpy_("L", n, n, &a[a_offset], lda, &vr[vr_offset], ldvr) ; /* Generate orthogonal matrix in VR (Workspace: need 3*N-1, prefer 2*N+(N-1)*NB) */ i__1 = *lwork - iwrk + 1; dorghr_(n, &ilo, &ihi, &vr[vr_offset], ldvr, &work[itau], &work[iwrk], &i__1, &ierr); /* Perform QR iteration, accumulating Schur vectors in VR (Workspace: need N+1, prefer N+HSWORK (see comments) ) */ iwrk = itau; i__1 = *lwork - iwrk + 1; dhseqr_("S", "V", n, &ilo, &ihi, &a[a_offset], lda, &wr[1], &wi[1], & vr[vr_offset], ldvr, &work[iwrk], &i__1, info); } else { /* Compute eigenvalues only (Workspace: need N+1, prefer N+HSWORK (see comments) ) */ iwrk = itau; i__1 = *lwork - iwrk + 1; dhseqr_("E", "N", n, &ilo, &ihi, &a[a_offset], lda, &wr[1], &wi[1], & vr[vr_offset], ldvr, &work[iwrk], &i__1, info); } /* If INFO > 0 from DHSEQR, then quit */ if (*info > 0) { goto L50; } if ((wantvl) || (wantvr)) { /* Compute left and/or right eigenvectors (Workspace: need 4*N) */ dtrevc_(side, "B", select, n, &a[a_offset], lda, &vl[vl_offset], ldvl, &vr[vr_offset], ldvr, n, &nout, &work[iwrk], &ierr); } if (wantvl) { /* Undo balancing of left eigenvectors (Workspace: need N) */ dgebak_("B", "L", n, &ilo, &ihi, &work[ibal], n, &vl[vl_offset], ldvl, &ierr); /* Normalize left eigenvectors and make largest component real */ i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { if (wi[i__] == 0.) { scl = 1. / dnrm2_(n, &vl[i__ * vl_dim1 + 1], &c__1); dscal_(n, &scl, &vl[i__ * vl_dim1 + 1], &c__1); } else if (wi[i__] > 0.) { d__1 = dnrm2_(n, &vl[i__ * vl_dim1 + 1], &c__1); d__2 = dnrm2_(n, &vl[(i__ + 1) * vl_dim1 + 1], &c__1); scl = 1. / dlapy2_(&d__1, &d__2); dscal_(n, &scl, &vl[i__ * vl_dim1 + 1], &c__1); dscal_(n, &scl, &vl[(i__ + 1) * vl_dim1 + 1], &c__1); i__2 = *n; for (k = 1; k <= i__2; ++k) { /* Computing 2nd power */ d__1 = vl[k + i__ * vl_dim1]; /* Computing 2nd power */ d__2 = vl[k + (i__ + 1) * vl_dim1]; work[iwrk + k - 1] = d__1 * d__1 + d__2 * d__2; /* L10: */ } k = idamax_(n, &work[iwrk], &c__1); dlartg_(&vl[k + i__ * vl_dim1], &vl[k + (i__ + 1) * vl_dim1], &cs, &sn, &r__); drot_(n, &vl[i__ * vl_dim1 + 1], &c__1, &vl[(i__ + 1) * vl_dim1 + 1], &c__1, &cs, &sn); vl[k + (i__ + 1) * vl_dim1] = 0.; } /* L20: */ } } if (wantvr) { /* Undo balancing of right eigenvectors (Workspace: need N) */ dgebak_("B", "R", n, &ilo, &ihi, &work[ibal], n, &vr[vr_offset], ldvr, &ierr); /* Normalize right eigenvectors and make largest component real */ i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { if (wi[i__] == 0.) { scl = 1. / dnrm2_(n, &vr[i__ * vr_dim1 + 1], &c__1); dscal_(n, &scl, &vr[i__ * vr_dim1 + 1], &c__1); } else if (wi[i__] > 0.) { d__1 = dnrm2_(n, &vr[i__ * vr_dim1 + 1], &c__1); d__2 = dnrm2_(n, &vr[(i__ + 1) * vr_dim1 + 1], &c__1); scl = 1. / dlapy2_(&d__1, &d__2); dscal_(n, &scl, &vr[i__ * vr_dim1 + 1], &c__1); dscal_(n, &scl, &vr[(i__ + 1) * vr_dim1 + 1], &c__1); i__2 = *n; for (k = 1; k <= i__2; ++k) { /* Computing 2nd power */ d__1 = vr[k + i__ * vr_dim1]; /* Computing 2nd power */ d__2 = vr[k + (i__ + 1) * vr_dim1]; work[iwrk + k - 1] = d__1 * d__1 + d__2 * d__2; /* L30: */ } k = idamax_(n, &work[iwrk], &c__1); dlartg_(&vr[k + i__ * vr_dim1], &vr[k + (i__ + 1) * vr_dim1], &cs, &sn, &r__); drot_(n, &vr[i__ * vr_dim1 + 1], &c__1, &vr[(i__ + 1) * vr_dim1 + 1], &c__1, &cs, &sn); vr[k + (i__ + 1) * vr_dim1] = 0.; } /* L40: */ } } /* Undo scaling if necessary */ L50: if (scalea) { i__1 = *n - *info; /* Computing MAX */ i__3 = *n - *info; i__2 = max(i__3,1); dlascl_("G", &c__0, &c__0, &cscale, &anrm, &i__1, &c__1, &wr[*info + 1], &i__2, &ierr); i__1 = *n - *info; /* Computing MAX */ i__3 = *n - *info; i__2 = max(i__3,1); dlascl_("G", &c__0, &c__0, &cscale, &anrm, &i__1, &c__1, &wi[*info + 1], &i__2, &ierr); if (*info > 0) { i__1 = ilo - 1; dlascl_("G", &c__0, &c__0, &cscale, &anrm, &i__1, &c__1, &wr[1], n, &ierr); i__1 = ilo - 1; dlascl_("G", &c__0, &c__0, &cscale, &anrm, &i__1, &c__1, &wi[1], n, &ierr); } } work[1] = (doublereal) maxwrk; return 0; /* End of DGEEV */ } /* dgeev_ */ /* Subroutine */ int dgehd2_(integer *n, integer *ilo, integer *ihi, doublereal *a, integer *lda, doublereal *tau, doublereal *work, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3; /* Local variables */ static integer i__; static doublereal aii; extern /* Subroutine */ int dlarf_(char *, integer *, integer *, doublereal *, integer *, doublereal *, doublereal *, integer *, doublereal *), dlarfg_(integer *, doublereal *, doublereal *, integer *, doublereal *), xerbla_(char *, integer *); /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University October 31, 1992 Purpose ======= DGEHD2 reduces a real general matrix A to upper Hessenberg form H by an orthogonal similarity transformation: Q' * A * Q = H . Arguments ========= N (input) INTEGER The order of the matrix A. N >= 0. ILO (input) INTEGER IHI (input) INTEGER It is assumed that A is already upper triangular in rows and columns 1:ILO-1 and IHI+1:N. ILO and IHI are normally set by a previous call to DGEBAL; otherwise they should be set to 1 and N respectively. See Further Details. 1 <= ILO <= IHI <= max(1,N). A (input/output) DOUBLE PRECISION array, dimension (LDA,N) On entry, the n by n general matrix to be reduced. On exit, the upper triangle and the first subdiagonal of A are overwritten with the upper Hessenberg matrix H, and the elements below the first subdiagonal, with the array TAU, represent the orthogonal matrix Q as a product of elementary reflectors. See Further Details. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,N). TAU (output) DOUBLE PRECISION array, dimension (N-1) The scalar factors of the elementary reflectors (see Further Details). WORK (workspace) DOUBLE PRECISION array, dimension (N) INFO (output) INTEGER = 0: successful exit. < 0: if INFO = -i, the i-th argument had an illegal value. Further Details =============== The matrix Q is represented as a product of (ihi-ilo) elementary reflectors Q = H(ilo) H(ilo+1) . . . H(ihi-1). Each H(i) has the form H(i) = I - tau * v * v' where tau is a real scalar, and v is a real vector with v(1:i) = 0, v(i+1) = 1 and v(ihi+1:n) = 0; v(i+2:ihi) is stored on exit in A(i+2:ihi,i), and tau in TAU(i). The contents of A are illustrated by the following example, with n = 7, ilo = 2 and ihi = 6: on entry, on exit, ( a a a a a a a ) ( a a h h h h a ) ( a a a a a a ) ( a h h h h a ) ( a a a a a a ) ( h h h h h h ) ( a a a a a a ) ( v2 h h h h h ) ( a a a a a a ) ( v2 v3 h h h h ) ( a a a a a a ) ( v2 v3 v4 h h h ) ( a ) ( a ) where a denotes an element of the original matrix A, h denotes a modified element of the upper Hessenberg matrix H, and vi denotes an element of the vector defining H(i). ===================================================================== Test the input parameters */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --tau; --work; /* Function Body */ *info = 0; if (*n < 0) { *info = -1; } else if ((*ilo < 1) || (*ilo > max(1,*n))) { *info = -2; } else if ((*ihi < min(*ilo,*n)) || (*ihi > *n)) { *info = -3; } else if (*lda < max(1,*n)) { *info = -5; } if (*info != 0) { i__1 = -(*info); xerbla_("DGEHD2", &i__1); return 0; } i__1 = *ihi - 1; for (i__ = *ilo; i__ <= i__1; ++i__) { /* Compute elementary reflector H(i) to annihilate A(i+2:ihi,i) */ i__2 = *ihi - i__; /* Computing MIN */ i__3 = i__ + 2; dlarfg_(&i__2, &a[i__ + 1 + i__ * a_dim1], &a[min(i__3,*n) + i__ * a_dim1], &c__1, &tau[i__]); aii = a[i__ + 1 + i__ * a_dim1]; a[i__ + 1 + i__ * a_dim1] = 1.; /* Apply H(i) to A(1:ihi,i+1:ihi) from the right */ i__2 = *ihi - i__; dlarf_("Right", ihi, &i__2, &a[i__ + 1 + i__ * a_dim1], &c__1, &tau[ i__], &a[(i__ + 1) * a_dim1 + 1], lda, &work[1]); /* Apply H(i) to A(i+1:ihi,i+1:n) from the left */ i__2 = *ihi - i__; i__3 = *n - i__; dlarf_("Left", &i__2, &i__3, &a[i__ + 1 + i__ * a_dim1], &c__1, &tau[ i__], &a[i__ + 1 + (i__ + 1) * a_dim1], lda, &work[1]); a[i__ + 1 + i__ * a_dim1] = aii; /* L10: */ } return 0; /* End of DGEHD2 */ } /* dgehd2_ */ /* Subroutine */ int dgehrd_(integer *n, integer *ilo, integer *ihi, doublereal *a, integer *lda, doublereal *tau, doublereal *work, integer *lwork, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3, i__4; /* Local variables */ static integer i__; static doublereal t[4160] /* was [65][64] */; static integer ib; static doublereal ei; static integer nb, nh, nx, iws; extern /* Subroutine */ int dgemm_(char *, char *, integer *, integer *, integer *, doublereal *, doublereal *, integer *, doublereal *, integer *, doublereal *, doublereal *, integer *); static integer nbmin, iinfo; extern /* Subroutine */ int dgehd2_(integer *, integer *, integer *, doublereal *, integer *, doublereal *, doublereal *, integer *), dlarfb_(char *, char *, char *, char *, integer *, integer *, integer *, doublereal *, integer *, doublereal *, integer *, doublereal *, integer *, doublereal *, integer *), dlahrd_(integer *, integer *, integer *, doublereal *, integer *, doublereal *, doublereal *, integer *, doublereal *, integer *), xerbla_(char *, integer *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); static integer ldwork, lwkopt; static logical lquery; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= DGEHRD reduces a real general matrix A to upper Hessenberg form H by an orthogonal similarity transformation: Q' * A * Q = H . Arguments ========= N (input) INTEGER The order of the matrix A. N >= 0. ILO (input) INTEGER IHI (input) INTEGER It is assumed that A is already upper triangular in rows and columns 1:ILO-1 and IHI+1:N. ILO and IHI are normally set by a previous call to DGEBAL; otherwise they should be set to 1 and N respectively. See Further Details. 1 <= ILO <= IHI <= N, if N > 0; ILO=1 and IHI=0, if N=0. A (input/output) DOUBLE PRECISION array, dimension (LDA,N) On entry, the N-by-N general matrix to be reduced. On exit, the upper triangle and the first subdiagonal of A are overwritten with the upper Hessenberg matrix H, and the elements below the first subdiagonal, with the array TAU, represent the orthogonal matrix Q as a product of elementary reflectors. See Further Details. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,N). TAU (output) DOUBLE PRECISION array, dimension (N-1) The scalar factors of the elementary reflectors (see Further Details). Elements 1:ILO-1 and IHI:N-1 of TAU are set to zero. WORK (workspace/output) DOUBLE PRECISION array, dimension (LWORK) On exit, if INFO = 0, WORK(1) returns the optimal LWORK. LWORK (input) INTEGER The length of the array WORK. LWORK >= max(1,N). For optimum performance LWORK >= N*NB, where NB is the optimal blocksize. If LWORK = -1, then a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued by XERBLA. INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value. Further Details =============== The matrix Q is represented as a product of (ihi-ilo) elementary reflectors Q = H(ilo) H(ilo+1) . . . H(ihi-1). Each H(i) has the form H(i) = I - tau * v * v' where tau is a real scalar, and v is a real vector with v(1:i) = 0, v(i+1) = 1 and v(ihi+1:n) = 0; v(i+2:ihi) is stored on exit in A(i+2:ihi,i), and tau in TAU(i). The contents of A are illustrated by the following example, with n = 7, ilo = 2 and ihi = 6: on entry, on exit, ( a a a a a a a ) ( a a h h h h a ) ( a a a a a a ) ( a h h h h a ) ( a a a a a a ) ( h h h h h h ) ( a a a a a a ) ( v2 h h h h h ) ( a a a a a a ) ( v2 v3 h h h h ) ( a a a a a a ) ( v2 v3 v4 h h h ) ( a ) ( a ) where a denotes an element of the original matrix A, h denotes a modified element of the upper Hessenberg matrix H, and vi denotes an element of the vector defining H(i). ===================================================================== Test the input parameters */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --tau; --work; /* Function Body */ *info = 0; /* Computing MIN */ i__1 = 64, i__2 = ilaenv_(&c__1, "DGEHRD", " ", n, ilo, ihi, &c_n1, ( ftnlen)6, (ftnlen)1); nb = min(i__1,i__2); lwkopt = *n * nb; work[1] = (doublereal) lwkopt; lquery = *lwork == -1; if (*n < 0) { *info = -1; } else if ((*ilo < 1) || (*ilo > max(1,*n))) { *info = -2; } else if ((*ihi < min(*ilo,*n)) || (*ihi > *n)) { *info = -3; } else if (*lda < max(1,*n)) { *info = -5; } else if (*lwork < max(1,*n) && ! lquery) { *info = -8; } if (*info != 0) { i__1 = -(*info); xerbla_("DGEHRD", &i__1); return 0; } else if (lquery) { return 0; } /* Set elements 1:ILO-1 and IHI:N-1 of TAU to zero */ i__1 = *ilo - 1; for (i__ = 1; i__ <= i__1; ++i__) { tau[i__] = 0.; /* L10: */ } i__1 = *n - 1; for (i__ = max(1,*ihi); i__ <= i__1; ++i__) { tau[i__] = 0.; /* L20: */ } /* Quick return if possible */ nh = *ihi - *ilo + 1; if (nh <= 1) { work[1] = 1.; return 0; } /* Determine the block size. Computing MIN */ i__1 = 64, i__2 = ilaenv_(&c__1, "DGEHRD", " ", n, ilo, ihi, &c_n1, ( ftnlen)6, (ftnlen)1); nb = min(i__1,i__2); nbmin = 2; iws = 1; if (nb > 1 && nb < nh) { /* Determine when to cross over from blocked to unblocked code (last block is always handled by unblocked code). Computing MAX */ i__1 = nb, i__2 = ilaenv_(&c__3, "DGEHRD", " ", n, ilo, ihi, &c_n1, ( ftnlen)6, (ftnlen)1); nx = max(i__1,i__2); if (nx < nh) { /* Determine if workspace is large enough for blocked code. */ iws = *n * nb; if (*lwork < iws) { /* Not enough workspace to use optimal NB: determine the minimum value of NB, and reduce NB or force use of unblocked code. Computing MAX */ i__1 = 2, i__2 = ilaenv_(&c__2, "DGEHRD", " ", n, ilo, ihi, & c_n1, (ftnlen)6, (ftnlen)1); nbmin = max(i__1,i__2); if (*lwork >= *n * nbmin) { nb = *lwork / *n; } else { nb = 1; } } } } ldwork = *n; if ((nb < nbmin) || (nb >= nh)) { /* Use unblocked code below */ i__ = *ilo; } else { /* Use blocked code */ i__1 = *ihi - 1 - nx; i__2 = nb; for (i__ = *ilo; i__2 < 0 ? i__ >= i__1 : i__ <= i__1; i__ += i__2) { /* Computing MIN */ i__3 = nb, i__4 = *ihi - i__; ib = min(i__3,i__4); /* Reduce columns i:i+ib-1 to Hessenberg form, returning the matrices V and T of the block reflector H = I - V*T*V' which performs the reduction, and also the matrix Y = A*V*T */ dlahrd_(ihi, &i__, &ib, &a[i__ * a_dim1 + 1], lda, &tau[i__], t, & c__65, &work[1], &ldwork); /* Apply the block reflector H to A(1:ihi,i+ib:ihi) from the right, computing A := A - Y * V'. V(i+ib,ib-1) must be set to 1. */ ei = a[i__ + ib + (i__ + ib - 1) * a_dim1]; a[i__ + ib + (i__ + ib - 1) * a_dim1] = 1.; i__3 = *ihi - i__ - ib + 1; dgemm_("No transpose", "Transpose", ihi, &i__3, &ib, &c_b3001, & work[1], &ldwork, &a[i__ + ib + i__ * a_dim1], lda, & c_b2865, &a[(i__ + ib) * a_dim1 + 1], lda); a[i__ + ib + (i__ + ib - 1) * a_dim1] = ei; /* Apply the block reflector H to A(i+1:ihi,i+ib:n) from the left */ i__3 = *ihi - i__; i__4 = *n - i__ - ib + 1; dlarfb_("Left", "Transpose", "Forward", "Columnwise", &i__3, & i__4, &ib, &a[i__ + 1 + i__ * a_dim1], lda, t, &c__65, &a[ i__ + 1 + (i__ + ib) * a_dim1], lda, &work[1], &ldwork); /* L30: */ } } /* Use unblocked code to reduce the rest of the matrix */ dgehd2_(n, &i__, ihi, &a[a_offset], lda, &tau[1], &work[1], &iinfo); work[1] = (doublereal) iws; return 0; /* End of DGEHRD */ } /* dgehrd_ */ /* Subroutine */ int dgelq2_(integer *m, integer *n, doublereal *a, integer * lda, doublereal *tau, doublereal *work, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3; /* Local variables */ static integer i__, k; static doublereal aii; extern /* Subroutine */ int dlarf_(char *, integer *, integer *, doublereal *, integer *, doublereal *, doublereal *, integer *, doublereal *), dlarfg_(integer *, doublereal *, doublereal *, integer *, doublereal *), xerbla_(char *, integer *); /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University February 29, 1992 Purpose ======= DGELQ2 computes an LQ factorization of a real m by n matrix A: A = L * Q. Arguments ========= M (input) INTEGER The number of rows of the matrix A. M >= 0. N (input) INTEGER The number of columns of the matrix A. N >= 0. A (input/output) DOUBLE PRECISION array, dimension (LDA,N) On entry, the m by n matrix A. On exit, the elements on and below the diagonal of the array contain the m by min(m,n) lower trapezoidal matrix L (L is lower triangular if m <= n); the elements above the diagonal, with the array TAU, represent the orthogonal matrix Q as a product of elementary reflectors (see Further Details). LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,M). TAU (output) DOUBLE PRECISION array, dimension (min(M,N)) The scalar factors of the elementary reflectors (see Further Details). WORK (workspace) DOUBLE PRECISION array, dimension (M) INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value Further Details =============== The matrix Q is represented as a product of elementary reflectors Q = H(k) . . . H(2) H(1), where k = min(m,n). Each H(i) has the form H(i) = I - tau * v * v' where tau is a real scalar, and v is a real vector with v(1:i-1) = 0 and v(i) = 1; v(i+1:n) is stored on exit in A(i,i+1:n), and tau in TAU(i). ===================================================================== Test the input arguments */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --tau; --work; /* Function Body */ *info = 0; if (*m < 0) { *info = -1; } else if (*n < 0) { *info = -2; } else if (*lda < max(1,*m)) { *info = -4; } if (*info != 0) { i__1 = -(*info); xerbla_("DGELQ2", &i__1); return 0; } k = min(*m,*n); i__1 = k; for (i__ = 1; i__ <= i__1; ++i__) { /* Generate elementary reflector H(i) to annihilate A(i,i+1:n) */ i__2 = *n - i__ + 1; /* Computing MIN */ i__3 = i__ + 1; dlarfg_(&i__2, &a[i__ + i__ * a_dim1], &a[i__ + min(i__3,*n) * a_dim1] , lda, &tau[i__]); if (i__ < *m) { /* Apply H(i) to A(i+1:m,i:n) from the right */ aii = a[i__ + i__ * a_dim1]; a[i__ + i__ * a_dim1] = 1.; i__2 = *m - i__; i__3 = *n - i__ + 1; dlarf_("Right", &i__2, &i__3, &a[i__ + i__ * a_dim1], lda, &tau[ i__], &a[i__ + 1 + i__ * a_dim1], lda, &work[1]); a[i__ + i__ * a_dim1] = aii; } /* L10: */ } return 0; /* End of DGELQ2 */ } /* dgelq2_ */ /* Subroutine */ int dgelqf_(integer *m, integer *n, doublereal *a, integer * lda, doublereal *tau, doublereal *work, integer *lwork, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3, i__4; /* Local variables */ static integer i__, k, ib, nb, nx, iws, nbmin, iinfo; extern /* Subroutine */ int dgelq2_(integer *, integer *, doublereal *, integer *, doublereal *, doublereal *, integer *), dlarfb_(char *, char *, char *, char *, integer *, integer *, integer *, doublereal *, integer *, doublereal *, integer *, doublereal *, integer *, doublereal *, integer *), dlarft_(char *, char *, integer *, integer *, doublereal *, integer *, doublereal *, doublereal *, integer *), xerbla_(char *, integer *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); static integer ldwork, lwkopt; static logical lquery; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= DGELQF computes an LQ factorization of a real M-by-N matrix A: A = L * Q. Arguments ========= M (input) INTEGER The number of rows of the matrix A. M >= 0. N (input) INTEGER The number of columns of the matrix A. N >= 0. A (input/output) DOUBLE PRECISION array, dimension (LDA,N) On entry, the M-by-N matrix A. On exit, the elements on and below the diagonal of the array contain the m-by-min(m,n) lower trapezoidal matrix L (L is lower triangular if m <= n); the elements above the diagonal, with the array TAU, represent the orthogonal matrix Q as a product of elementary reflectors (see Further Details). LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,M). TAU (output) DOUBLE PRECISION array, dimension (min(M,N)) The scalar factors of the elementary reflectors (see Further Details). WORK (workspace/output) DOUBLE PRECISION array, dimension (LWORK) On exit, if INFO = 0, WORK(1) returns the optimal LWORK. LWORK (input) INTEGER The dimension of the array WORK. LWORK >= max(1,M). For optimum performance LWORK >= M*NB, where NB is the optimal blocksize. If LWORK = -1, then a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued by XERBLA. INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value Further Details =============== The matrix Q is represented as a product of elementary reflectors Q = H(k) . . . H(2) H(1), where k = min(m,n). Each H(i) has the form H(i) = I - tau * v * v' where tau is a real scalar, and v is a real vector with v(1:i-1) = 0 and v(i) = 1; v(i+1:n) is stored on exit in A(i,i+1:n), and tau in TAU(i). ===================================================================== Test the input arguments */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --tau; --work; /* Function Body */ *info = 0; nb = ilaenv_(&c__1, "DGELQF", " ", m, n, &c_n1, &c_n1, (ftnlen)6, (ftnlen) 1); lwkopt = *m * nb; work[1] = (doublereal) lwkopt; lquery = *lwork == -1; if (*m < 0) { *info = -1; } else if (*n < 0) { *info = -2; } else if (*lda < max(1,*m)) { *info = -4; } else if (*lwork < max(1,*m) && ! lquery) { *info = -7; } if (*info != 0) { i__1 = -(*info); xerbla_("DGELQF", &i__1); return 0; } else if (lquery) { return 0; } /* Quick return if possible */ k = min(*m,*n); if (k == 0) { work[1] = 1.; return 0; } nbmin = 2; nx = 0; iws = *m; if (nb > 1 && nb < k) { /* Determine when to cross over from blocked to unblocked code. Computing MAX */ i__1 = 0, i__2 = ilaenv_(&c__3, "DGELQF", " ", m, n, &c_n1, &c_n1, ( ftnlen)6, (ftnlen)1); nx = max(i__1,i__2); if (nx < k) { /* Determine if workspace is large enough for blocked code. */ ldwork = *m; iws = ldwork * nb; if (*lwork < iws) { /* Not enough workspace to use optimal NB: reduce NB and determine the minimum value of NB. */ nb = *lwork / ldwork; /* Computing MAX */ i__1 = 2, i__2 = ilaenv_(&c__2, "DGELQF", " ", m, n, &c_n1, & c_n1, (ftnlen)6, (ftnlen)1); nbmin = max(i__1,i__2); } } } if (nb >= nbmin && nb < k && nx < k) { /* Use blocked code initially */ i__1 = k - nx; i__2 = nb; for (i__ = 1; i__2 < 0 ? i__ >= i__1 : i__ <= i__1; i__ += i__2) { /* Computing MIN */ i__3 = k - i__ + 1; ib = min(i__3,nb); /* Compute the LQ factorization of the current block A(i:i+ib-1,i:n) */ i__3 = *n - i__ + 1; dgelq2_(&ib, &i__3, &a[i__ + i__ * a_dim1], lda, &tau[i__], &work[ 1], &iinfo); if (i__ + ib <= *m) { /* Form the triangular factor of the block reflector H = H(i) H(i+1) . . . H(i+ib-1) */ i__3 = *n - i__ + 1; dlarft_("Forward", "Rowwise", &i__3, &ib, &a[i__ + i__ * a_dim1], lda, &tau[i__], &work[1], &ldwork); /* Apply H to A(i+ib:m,i:n) from the right */ i__3 = *m - i__ - ib + 1; i__4 = *n - i__ + 1; dlarfb_("Right", "No transpose", "Forward", "Rowwise", &i__3, &i__4, &ib, &a[i__ + i__ * a_dim1], lda, &work[1], & ldwork, &a[i__ + ib + i__ * a_dim1], lda, &work[ib + 1], &ldwork); } /* L10: */ } } else { i__ = 1; } /* Use unblocked code to factor the last or only block. */ if (i__ <= k) { i__2 = *m - i__ + 1; i__1 = *n - i__ + 1; dgelq2_(&i__2, &i__1, &a[i__ + i__ * a_dim1], lda, &tau[i__], &work[1] , &iinfo); } work[1] = (doublereal) iws; return 0; /* End of DGELQF */ } /* dgelqf_ */ /* Subroutine */ int dgelsd_(integer *m, integer *n, integer *nrhs, doublereal *a, integer *lda, doublereal *b, integer *ldb, doublereal * s, doublereal *rcond, integer *rank, doublereal *work, integer *lwork, integer *iwork, integer *info) { /* System generated locals */ integer a_dim1, a_offset, b_dim1, b_offset, i__1, i__2, i__3, i__4; /* Builtin functions */ double log(doublereal); /* Local variables */ static integer ie, il, mm; static doublereal eps, anrm, bnrm; static integer itau, nlvl, iascl, ibscl; static doublereal sfmin; static integer minmn, maxmn, itaup, itauq, mnthr, nwork; extern /* Subroutine */ int dlabad_(doublereal *, doublereal *), dgebrd_( integer *, integer *, doublereal *, integer *, doublereal *, doublereal *, doublereal *, doublereal *, doublereal *, integer *, integer *); extern doublereal dlamch_(char *), dlange_(char *, integer *, integer *, doublereal *, integer *, doublereal *); extern /* Subroutine */ int dgelqf_(integer *, integer *, doublereal *, integer *, doublereal *, doublereal *, integer *, integer *), dlalsd_(char *, integer *, integer *, integer *, doublereal *, doublereal *, doublereal *, integer *, doublereal *, integer *, doublereal *, integer *, integer *), dlascl_(char *, integer *, integer *, doublereal *, doublereal *, integer *, integer *, doublereal *, integer *, integer *), dgeqrf_( integer *, integer *, doublereal *, integer *, doublereal *, doublereal *, integer *, integer *), dlacpy_(char *, integer *, integer *, doublereal *, integer *, doublereal *, integer *), dlaset_(char *, integer *, integer *, doublereal *, doublereal *, doublereal *, integer *), xerbla_(char *, integer *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); static doublereal bignum; extern /* Subroutine */ int dormbr_(char *, char *, char *, integer *, integer *, integer *, doublereal *, integer *, doublereal *, doublereal *, integer *, doublereal *, integer *, integer *); static integer wlalsd; extern /* Subroutine */ int dormlq_(char *, char *, integer *, integer *, integer *, doublereal *, integer *, doublereal *, doublereal *, integer *, doublereal *, integer *, integer *); static integer ldwork; extern /* Subroutine */ int dormqr_(char *, char *, integer *, integer *, integer *, doublereal *, integer *, doublereal *, doublereal *, integer *, doublereal *, integer *, integer *); static integer minwrk, maxwrk; static doublereal smlnum; static logical lquery; static integer smlsiz; /* -- LAPACK driver routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University October 31, 1999 Purpose ======= DGELSD computes the minimum-norm solution to a real linear least squares problem: minimize 2-norm(| b - A*x |) using the singular value decomposition (SVD) of A. A is an M-by-N matrix which may be rank-deficient. Several right hand side vectors b and solution vectors x can be handled in a single call; they are stored as the columns of the M-by-NRHS right hand side matrix B and the N-by-NRHS solution matrix X. The problem is solved in three steps: (1) Reduce the coefficient matrix A to bidiagonal form with Householder transformations, reducing the original problem into a "bidiagonal least squares problem" (BLS) (2) Solve the BLS using a divide and conquer approach. (3) Apply back all the Householder tranformations to solve the original least squares problem. The effective rank of A is determined by treating as zero those singular values which are less than RCOND times the largest singular value. The divide and conquer algorithm makes very mild assumptions about floating point arithmetic. It will work on machines with a guard digit in add/subtract, or on those binary machines without guard digits which subtract like the Cray X-MP, Cray Y-MP, Cray C-90, or Cray-2. It could conceivably fail on hexadecimal or decimal machines without guard digits, but we know of none. Arguments ========= M (input) INTEGER The number of rows of A. M >= 0. N (input) INTEGER The number of columns of A. N >= 0. NRHS (input) INTEGER The number of right hand sides, i.e., the number of columns of the matrices B and X. NRHS >= 0. A (input) DOUBLE PRECISION array, dimension (LDA,N) On entry, the M-by-N matrix A. On exit, A has been destroyed. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,M). B (input/output) DOUBLE PRECISION array, dimension (LDB,NRHS) On entry, the M-by-NRHS right hand side matrix B. On exit, B is overwritten by the N-by-NRHS solution matrix X. If m >= n and RANK = n, the residual sum-of-squares for the solution in the i-th column is given by the sum of squares of elements n+1:m in that column. LDB (input) INTEGER The leading dimension of the array B. LDB >= max(1,max(M,N)). S (output) DOUBLE PRECISION array, dimension (min(M,N)) The singular values of A in decreasing order. The condition number of A in the 2-norm = S(1)/S(min(m,n)). RCOND (input) DOUBLE PRECISION RCOND is used to determine the effective rank of A. Singular values S(i) <= RCOND*S(1) are treated as zero. If RCOND < 0, machine precision is used instead. RANK (output) INTEGER The effective rank of A, i.e., the number of singular values which are greater than RCOND*S(1). WORK (workspace/output) DOUBLE PRECISION array, dimension (LWORK) On exit, if INFO = 0, WORK(1) returns the optimal LWORK. LWORK (input) INTEGER The dimension of the array WORK. LWORK must be at least 1. The exact minimum amount of workspace needed depends on M, N and NRHS. As long as LWORK is at least 12*N + 2*N*SMLSIZ + 8*N*NLVL + N*NRHS + (SMLSIZ+1)**2, if M is greater than or equal to N or 12*M + 2*M*SMLSIZ + 8*M*NLVL + M*NRHS + (SMLSIZ+1)**2, if M is less than N, the code will execute correctly. SMLSIZ is returned by ILAENV and is equal to the maximum size of the subproblems at the bottom of the computation tree (usually about 25), and NLVL = MAX( 0, INT( LOG_2( MIN( M,N )/(SMLSIZ+1) ) ) + 1 ) For good performance, LWORK should generally be larger. If LWORK = -1, then a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued by XERBLA. IWORK (workspace) INTEGER array, dimension (LIWORK) LIWORK >= 3 * MINMN * NLVL + 11 * MINMN, where MINMN = MIN( M,N ). INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value. > 0: the algorithm for computing the SVD failed to converge; if INFO = i, i off-diagonal elements of an intermediate bidiagonal form did not converge to zero. Further Details =============== Based on contributions by Ming Gu and Ren-Cang Li, Computer Science Division, University of California at Berkeley, USA Osni Marques, LBNL/NERSC, USA ===================================================================== Test the input arguments. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; b_dim1 = *ldb; b_offset = 1 + b_dim1; b -= b_offset; --s; --work; --iwork; /* Function Body */ *info = 0; minmn = min(*m,*n); maxmn = max(*m,*n); mnthr = ilaenv_(&c__6, "DGELSD", " ", m, n, nrhs, &c_n1, (ftnlen)6, ( ftnlen)1); lquery = *lwork == -1; if (*m < 0) { *info = -1; } else if (*n < 0) { *info = -2; } else if (*nrhs < 0) { *info = -3; } else if (*lda < max(1,*m)) { *info = -5; } else if (*ldb < max(1,maxmn)) { *info = -7; } smlsiz = ilaenv_(&c__9, "DGELSD", " ", &c__0, &c__0, &c__0, &c__0, ( ftnlen)6, (ftnlen)1); /* Compute workspace. (Note: Comments in the code beginning "Workspace:" describe the minimal amount of workspace needed at that point in the code, as well as the preferred amount for good performance. NB refers to the optimal block size for the immediately following subroutine, as returned by ILAENV.) */ minwrk = 1; minmn = max(1,minmn); /* Computing MAX */ i__1 = (integer) (log((doublereal) minmn / (doublereal) (smlsiz + 1)) / log(2.)) + 1; nlvl = max(i__1,0); if (*info == 0) { maxwrk = 0; mm = *m; if (*m >= *n && *m >= mnthr) { /* Path 1a - overdetermined, with many more rows than columns. */ mm = *n; /* Computing MAX */ i__1 = maxwrk, i__2 = *n + *n * ilaenv_(&c__1, "DGEQRF", " ", m, n, &c_n1, &c_n1, (ftnlen)6, (ftnlen)1); maxwrk = max(i__1,i__2); /* Computing MAX */ i__1 = maxwrk, i__2 = *n + *nrhs * ilaenv_(&c__1, "DORMQR", "LT", m, nrhs, n, &c_n1, (ftnlen)6, (ftnlen)2); maxwrk = max(i__1,i__2); } if (*m >= *n) { /* Path 1 - overdetermined or exactly determined. Computing MAX */ i__1 = maxwrk, i__2 = *n * 3 + (mm + *n) * ilaenv_(&c__1, "DGEBRD" , " ", &mm, n, &c_n1, &c_n1, (ftnlen)6, (ftnlen)1); maxwrk = max(i__1,i__2); /* Computing MAX */ i__1 = maxwrk, i__2 = *n * 3 + *nrhs * ilaenv_(&c__1, "DORMBR", "QLT", &mm, nrhs, n, &c_n1, (ftnlen)6, (ftnlen)3); maxwrk = max(i__1,i__2); /* Computing MAX */ i__1 = maxwrk, i__2 = *n * 3 + (*n - 1) * ilaenv_(&c__1, "DORMBR", "PLN", n, nrhs, n, &c_n1, (ftnlen)6, (ftnlen)3); maxwrk = max(i__1,i__2); /* Computing 2nd power */ i__1 = smlsiz + 1; wlalsd = *n * 9 + ((*n) << (1)) * smlsiz + ((*n) << (3)) * nlvl + *n * *nrhs + i__1 * i__1; /* Computing MAX */ i__1 = maxwrk, i__2 = *n * 3 + wlalsd; maxwrk = max(i__1,i__2); /* Computing MAX */ i__1 = *n * 3 + mm, i__2 = *n * 3 + *nrhs, i__1 = max(i__1,i__2), i__2 = *n * 3 + wlalsd; minwrk = max(i__1,i__2); } if (*n > *m) { /* Computing 2nd power */ i__1 = smlsiz + 1; wlalsd = *m * 9 + ((*m) << (1)) * smlsiz + ((*m) << (3)) * nlvl + *m * *nrhs + i__1 * i__1; if (*n >= mnthr) { /* Path 2a - underdetermined, with many more columns than rows. */ maxwrk = *m + *m * ilaenv_(&c__1, "DGELQF", " ", m, n, &c_n1, &c_n1, (ftnlen)6, (ftnlen)1); /* Computing MAX */ i__1 = maxwrk, i__2 = *m * *m + ((*m) << (2)) + ((*m) << (1)) * ilaenv_(&c__1, "DGEBRD", " ", m, m, &c_n1, &c_n1, ( ftnlen)6, (ftnlen)1); maxwrk = max(i__1,i__2); /* Computing MAX */ i__1 = maxwrk, i__2 = *m * *m + ((*m) << (2)) + *nrhs * ilaenv_(&c__1, "DORMBR", "QLT", m, nrhs, m, &c_n1, ( ftnlen)6, (ftnlen)3); maxwrk = max(i__1,i__2); /* Computing MAX */ i__1 = maxwrk, i__2 = *m * *m + ((*m) << (2)) + (*m - 1) * ilaenv_(&c__1, "DORMBR", "PLN", m, nrhs, m, &c_n1, ( ftnlen)6, (ftnlen)3); maxwrk = max(i__1,i__2); if (*nrhs > 1) { /* Computing MAX */ i__1 = maxwrk, i__2 = *m * *m + *m + *m * *nrhs; maxwrk = max(i__1,i__2); } else { /* Computing MAX */ i__1 = maxwrk, i__2 = *m * *m + ((*m) << (1)); maxwrk = max(i__1,i__2); } /* Computing MAX */ i__1 = maxwrk, i__2 = *m + *nrhs * ilaenv_(&c__1, "DORMLQ", "LT", n, nrhs, m, &c_n1, (ftnlen)6, (ftnlen)2); maxwrk = max(i__1,i__2); /* Computing MAX */ i__1 = maxwrk, i__2 = *m * *m + ((*m) << (2)) + wlalsd; maxwrk = max(i__1,i__2); } else { /* Path 2 - remaining underdetermined cases. */ maxwrk = *m * 3 + (*n + *m) * ilaenv_(&c__1, "DGEBRD", " ", m, n, &c_n1, &c_n1, (ftnlen)6, (ftnlen)1); /* Computing MAX */ i__1 = maxwrk, i__2 = *m * 3 + *nrhs * ilaenv_(&c__1, "DORMBR" , "QLT", m, nrhs, n, &c_n1, (ftnlen)6, (ftnlen)3); maxwrk = max(i__1,i__2); /* Computing MAX */ i__1 = maxwrk, i__2 = *m * 3 + *m * ilaenv_(&c__1, "DORMBR", "PLN", n, nrhs, m, &c_n1, (ftnlen)6, (ftnlen)3); maxwrk = max(i__1,i__2); /* Computing MAX */ i__1 = maxwrk, i__2 = *m * 3 + wlalsd; maxwrk = max(i__1,i__2); } /* Computing MAX */ i__1 = *m * 3 + *nrhs, i__2 = *m * 3 + *m, i__1 = max(i__1,i__2), i__2 = *m * 3 + wlalsd; minwrk = max(i__1,i__2); } minwrk = min(minwrk,maxwrk); work[1] = (doublereal) maxwrk; if (*lwork < minwrk && ! lquery) { *info = -12; } } if (*info != 0) { i__1 = -(*info); xerbla_("DGELSD", &i__1); return 0; } else if (lquery) { goto L10; } /* Quick return if possible. */ if ((*m == 0) || (*n == 0)) { *rank = 0; return 0; } /* Get machine parameters. */ eps = PRECISION; sfmin = SAFEMINIMUM; smlnum = sfmin / eps; bignum = 1. / smlnum; dlabad_(&smlnum, &bignum); /* Scale A if max entry outside range [SMLNUM,BIGNUM]. */ anrm = dlange_("M", m, n, &a[a_offset], lda, &work[1]); iascl = 0; if (anrm > 0. && anrm < smlnum) { /* Scale matrix norm up to SMLNUM. */ dlascl_("G", &c__0, &c__0, &anrm, &smlnum, m, n, &a[a_offset], lda, info); iascl = 1; } else if (anrm > bignum) { /* Scale matrix norm down to BIGNUM. */ dlascl_("G", &c__0, &c__0, &anrm, &bignum, m, n, &a[a_offset], lda, info); iascl = 2; } else if (anrm == 0.) { /* Matrix all zero. Return zero solution. */ i__1 = max(*m,*n); dlaset_("F", &i__1, nrhs, &c_b2879, &c_b2879, &b[b_offset], ldb); dlaset_("F", &minmn, &c__1, &c_b2879, &c_b2879, &s[1], &c__1); *rank = 0; goto L10; } /* Scale B if max entry outside range [SMLNUM,BIGNUM]. */ bnrm = dlange_("M", m, nrhs, &b[b_offset], ldb, &work[1]); ibscl = 0; if (bnrm > 0. && bnrm < smlnum) { /* Scale matrix norm up to SMLNUM. */ dlascl_("G", &c__0, &c__0, &bnrm, &smlnum, m, nrhs, &b[b_offset], ldb, info); ibscl = 1; } else if (bnrm > bignum) { /* Scale matrix norm down to BIGNUM. */ dlascl_("G", &c__0, &c__0, &bnrm, &bignum, m, nrhs, &b[b_offset], ldb, info); ibscl = 2; } /* If M < N make sure certain entries of B are zero. */ if (*m < *n) { i__1 = *n - *m; dlaset_("F", &i__1, nrhs, &c_b2879, &c_b2879, &b[*m + 1 + b_dim1], ldb); } /* Overdetermined case. */ if (*m >= *n) { /* Path 1 - overdetermined or exactly determined. */ mm = *m; if (*m >= mnthr) { /* Path 1a - overdetermined, with many more rows than columns. */ mm = *n; itau = 1; nwork = itau + *n; /* Compute A=Q*R. (Workspace: need 2*N, prefer N+N*NB) */ i__1 = *lwork - nwork + 1; dgeqrf_(m, n, &a[a_offset], lda, &work[itau], &work[nwork], &i__1, info); /* Multiply B by transpose(Q). (Workspace: need N+NRHS, prefer N+NRHS*NB) */ i__1 = *lwork - nwork + 1; dormqr_("L", "T", m, nrhs, n, &a[a_offset], lda, &work[itau], &b[ b_offset], ldb, &work[nwork], &i__1, info); /* Zero out below R. */ if (*n > 1) { i__1 = *n - 1; i__2 = *n - 1; dlaset_("L", &i__1, &i__2, &c_b2879, &c_b2879, &a[a_dim1 + 2], lda); } } ie = 1; itauq = ie + *n; itaup = itauq + *n; nwork = itaup + *n; /* Bidiagonalize R in A. (Workspace: need 3*N+MM, prefer 3*N+(MM+N)*NB) */ i__1 = *lwork - nwork + 1; dgebrd_(&mm, n, &a[a_offset], lda, &s[1], &work[ie], &work[itauq], & work[itaup], &work[nwork], &i__1, info); /* Multiply B by transpose of left bidiagonalizing vectors of R. (Workspace: need 3*N+NRHS, prefer 3*N+NRHS*NB) */ i__1 = *lwork - nwork + 1; dormbr_("Q", "L", "T", &mm, nrhs, n, &a[a_offset], lda, &work[itauq], &b[b_offset], ldb, &work[nwork], &i__1, info); /* Solve the bidiagonal least squares problem. */ dlalsd_("U", &smlsiz, n, nrhs, &s[1], &work[ie], &b[b_offset], ldb, rcond, rank, &work[nwork], &iwork[1], info); if (*info != 0) { goto L10; } /* Multiply B by right bidiagonalizing vectors of R. */ i__1 = *lwork - nwork + 1; dormbr_("P", "L", "N", n, nrhs, n, &a[a_offset], lda, &work[itaup], & b[b_offset], ldb, &work[nwork], &i__1, info); } else /* if(complicated condition) */ { /* Computing MAX */ i__1 = *m, i__2 = ((*m) << (1)) - 4, i__1 = max(i__1,i__2), i__1 = max(i__1,*nrhs), i__2 = *n - *m * 3; if (*n >= mnthr && *lwork >= ((*m) << (2)) + *m * *m + max(i__1,i__2)) { /* Path 2a - underdetermined, with many more columns than rows and sufficient workspace for an efficient algorithm. */ ldwork = *m; /* Computing MAX Computing MAX */ i__3 = *m, i__4 = ((*m) << (1)) - 4, i__3 = max(i__3,i__4), i__3 = max(i__3,*nrhs), i__4 = *n - *m * 3; i__1 = ((*m) << (2)) + *m * *lda + max(i__3,i__4), i__2 = *m * * lda + *m + *m * *nrhs; if (*lwork >= max(i__1,i__2)) { ldwork = *lda; } itau = 1; nwork = *m + 1; /* Compute A=L*Q. (Workspace: need 2*M, prefer M+M*NB) */ i__1 = *lwork - nwork + 1; dgelqf_(m, n, &a[a_offset], lda, &work[itau], &work[nwork], &i__1, info); il = nwork; /* Copy L to WORK(IL), zeroing out above its diagonal. */ dlacpy_("L", m, m, &a[a_offset], lda, &work[il], &ldwork); i__1 = *m - 1; i__2 = *m - 1; dlaset_("U", &i__1, &i__2, &c_b2879, &c_b2879, &work[il + ldwork], &ldwork); ie = il + ldwork * *m; itauq = ie + *m; itaup = itauq + *m; nwork = itaup + *m; /* Bidiagonalize L in WORK(IL). (Workspace: need M*M+5*M, prefer M*M+4*M+2*M*NB) */ i__1 = *lwork - nwork + 1; dgebrd_(m, m, &work[il], &ldwork, &s[1], &work[ie], &work[itauq], &work[itaup], &work[nwork], &i__1, info); /* Multiply B by transpose of left bidiagonalizing vectors of L. (Workspace: need M*M+4*M+NRHS, prefer M*M+4*M+NRHS*NB) */ i__1 = *lwork - nwork + 1; dormbr_("Q", "L", "T", m, nrhs, m, &work[il], &ldwork, &work[ itauq], &b[b_offset], ldb, &work[nwork], &i__1, info); /* Solve the bidiagonal least squares problem. */ dlalsd_("U", &smlsiz, m, nrhs, &s[1], &work[ie], &b[b_offset], ldb, rcond, rank, &work[nwork], &iwork[1], info); if (*info != 0) { goto L10; } /* Multiply B by right bidiagonalizing vectors of L. */ i__1 = *lwork - nwork + 1; dormbr_("P", "L", "N", m, nrhs, m, &work[il], &ldwork, &work[ itaup], &b[b_offset], ldb, &work[nwork], &i__1, info); /* Zero out below first M rows of B. */ i__1 = *n - *m; dlaset_("F", &i__1, nrhs, &c_b2879, &c_b2879, &b[*m + 1 + b_dim1], ldb); nwork = itau + *m; /* Multiply transpose(Q) by B. (Workspace: need M+NRHS, prefer M+NRHS*NB) */ i__1 = *lwork - nwork + 1; dormlq_("L", "T", n, nrhs, m, &a[a_offset], lda, &work[itau], &b[ b_offset], ldb, &work[nwork], &i__1, info); } else { /* Path 2 - remaining underdetermined cases. */ ie = 1; itauq = ie + *m; itaup = itauq + *m; nwork = itaup + *m; /* Bidiagonalize A. (Workspace: need 3*M+N, prefer 3*M+(M+N)*NB) */ i__1 = *lwork - nwork + 1; dgebrd_(m, n, &a[a_offset], lda, &s[1], &work[ie], &work[itauq], & work[itaup], &work[nwork], &i__1, info); /* Multiply B by transpose of left bidiagonalizing vectors. (Workspace: need 3*M+NRHS, prefer 3*M+NRHS*NB) */ i__1 = *lwork - nwork + 1; dormbr_("Q", "L", "T", m, nrhs, n, &a[a_offset], lda, &work[itauq] , &b[b_offset], ldb, &work[nwork], &i__1, info); /* Solve the bidiagonal least squares problem. */ dlalsd_("L", &smlsiz, m, nrhs, &s[1], &work[ie], &b[b_offset], ldb, rcond, rank, &work[nwork], &iwork[1], info); if (*info != 0) { goto L10; } /* Multiply B by right bidiagonalizing vectors of A. */ i__1 = *lwork - nwork + 1; dormbr_("P", "L", "N", n, nrhs, m, &a[a_offset], lda, &work[itaup] , &b[b_offset], ldb, &work[nwork], &i__1, info); } } /* Undo scaling. */ if (iascl == 1) { dlascl_("G", &c__0, &c__0, &anrm, &smlnum, n, nrhs, &b[b_offset], ldb, info); dlascl_("G", &c__0, &c__0, &smlnum, &anrm, &minmn, &c__1, &s[1], & minmn, info); } else if (iascl == 2) { dlascl_("G", &c__0, &c__0, &anrm, &bignum, n, nrhs, &b[b_offset], ldb, info); dlascl_("G", &c__0, &c__0, &bignum, &anrm, &minmn, &c__1, &s[1], & minmn, info); } if (ibscl == 1) { dlascl_("G", &c__0, &c__0, &smlnum, &bnrm, n, nrhs, &b[b_offset], ldb, info); } else if (ibscl == 2) { dlascl_("G", &c__0, &c__0, &bignum, &bnrm, n, nrhs, &b[b_offset], ldb, info); } L10: work[1] = (doublereal) maxwrk; return 0; /* End of DGELSD */ } /* dgelsd_ */ /* Subroutine */ int dgeqr2_(integer *m, integer *n, doublereal *a, integer * lda, doublereal *tau, doublereal *work, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3; /* Local variables */ static integer i__, k; static doublereal aii; extern /* Subroutine */ int dlarf_(char *, integer *, integer *, doublereal *, integer *, doublereal *, doublereal *, integer *, doublereal *), dlarfg_(integer *, doublereal *, doublereal *, integer *, doublereal *), xerbla_(char *, integer *); /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University February 29, 1992 Purpose ======= DGEQR2 computes a QR factorization of a real m by n matrix A: A = Q * R. Arguments ========= M (input) INTEGER The number of rows of the matrix A. M >= 0. N (input) INTEGER The number of columns of the matrix A. N >= 0. A (input/output) DOUBLE PRECISION array, dimension (LDA,N) On entry, the m by n matrix A. On exit, the elements on and above the diagonal of the array contain the min(m,n) by n upper trapezoidal matrix R (R is upper triangular if m >= n); the elements below the diagonal, with the array TAU, represent the orthogonal matrix Q as a product of elementary reflectors (see Further Details). LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,M). TAU (output) DOUBLE PRECISION array, dimension (min(M,N)) The scalar factors of the elementary reflectors (see Further Details). WORK (workspace) DOUBLE PRECISION array, dimension (N) INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value Further Details =============== The matrix Q is represented as a product of elementary reflectors Q = H(1) H(2) . . . H(k), where k = min(m,n). Each H(i) has the form H(i) = I - tau * v * v' where tau is a real scalar, and v is a real vector with v(1:i-1) = 0 and v(i) = 1; v(i+1:m) is stored on exit in A(i+1:m,i), and tau in TAU(i). ===================================================================== Test the input arguments */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --tau; --work; /* Function Body */ *info = 0; if (*m < 0) { *info = -1; } else if (*n < 0) { *info = -2; } else if (*lda < max(1,*m)) { *info = -4; } if (*info != 0) { i__1 = -(*info); xerbla_("DGEQR2", &i__1); return 0; } k = min(*m,*n); i__1 = k; for (i__ = 1; i__ <= i__1; ++i__) { /* Generate elementary reflector H(i) to annihilate A(i+1:m,i) */ i__2 = *m - i__ + 1; /* Computing MIN */ i__3 = i__ + 1; dlarfg_(&i__2, &a[i__ + i__ * a_dim1], &a[min(i__3,*m) + i__ * a_dim1] , &c__1, &tau[i__]); if (i__ < *n) { /* Apply H(i) to A(i:m,i+1:n) from the left */ aii = a[i__ + i__ * a_dim1]; a[i__ + i__ * a_dim1] = 1.; i__2 = *m - i__ + 1; i__3 = *n - i__; dlarf_("Left", &i__2, &i__3, &a[i__ + i__ * a_dim1], &c__1, &tau[ i__], &a[i__ + (i__ + 1) * a_dim1], lda, &work[1]); a[i__ + i__ * a_dim1] = aii; } /* L10: */ } return 0; /* End of DGEQR2 */ } /* dgeqr2_ */ /* Subroutine */ int dgeqrf_(integer *m, integer *n, doublereal *a, integer * lda, doublereal *tau, doublereal *work, integer *lwork, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3, i__4; /* Local variables */ static integer i__, k, ib, nb, nx, iws, nbmin, iinfo; extern /* Subroutine */ int dgeqr2_(integer *, integer *, doublereal *, integer *, doublereal *, doublereal *, integer *), dlarfb_(char *, char *, char *, char *, integer *, integer *, integer *, doublereal *, integer *, doublereal *, integer *, doublereal *, integer *, doublereal *, integer *), dlarft_(char *, char *, integer *, integer *, doublereal *, integer *, doublereal *, doublereal *, integer *), xerbla_(char *, integer *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); static integer ldwork, lwkopt; static logical lquery; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= DGEQRF computes a QR factorization of a real M-by-N matrix A: A = Q * R. Arguments ========= M (input) INTEGER The number of rows of the matrix A. M >= 0. N (input) INTEGER The number of columns of the matrix A. N >= 0. A (input/output) DOUBLE PRECISION array, dimension (LDA,N) On entry, the M-by-N matrix A. On exit, the elements on and above the diagonal of the array contain the min(M,N)-by-N upper trapezoidal matrix R (R is upper triangular if m >= n); the elements below the diagonal, with the array TAU, represent the orthogonal matrix Q as a product of min(m,n) elementary reflectors (see Further Details). LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,M). TAU (output) DOUBLE PRECISION array, dimension (min(M,N)) The scalar factors of the elementary reflectors (see Further Details). WORK (workspace/output) DOUBLE PRECISION array, dimension (LWORK) On exit, if INFO = 0, WORK(1) returns the optimal LWORK. LWORK (input) INTEGER The dimension of the array WORK. LWORK >= max(1,N). For optimum performance LWORK >= N*NB, where NB is the optimal blocksize. If LWORK = -1, then a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued by XERBLA. INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value Further Details =============== The matrix Q is represented as a product of elementary reflectors Q = H(1) H(2) . . . H(k), where k = min(m,n). Each H(i) has the form H(i) = I - tau * v * v' where tau is a real scalar, and v is a real vector with v(1:i-1) = 0 and v(i) = 1; v(i+1:m) is stored on exit in A(i+1:m,i), and tau in TAU(i). ===================================================================== Test the input arguments */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --tau; --work; /* Function Body */ *info = 0; nb = ilaenv_(&c__1, "DGEQRF", " ", m, n, &c_n1, &c_n1, (ftnlen)6, (ftnlen) 1); lwkopt = *n * nb; work[1] = (doublereal) lwkopt; lquery = *lwork == -1; if (*m < 0) { *info = -1; } else if (*n < 0) { *info = -2; } else if (*lda < max(1,*m)) { *info = -4; } else if (*lwork < max(1,*n) && ! lquery) { *info = -7; } if (*info != 0) { i__1 = -(*info); xerbla_("DGEQRF", &i__1); return 0; } else if (lquery) { return 0; } /* Quick return if possible */ k = min(*m,*n); if (k == 0) { work[1] = 1.; return 0; } nbmin = 2; nx = 0; iws = *n; if (nb > 1 && nb < k) { /* Determine when to cross over from blocked to unblocked code. Computing MAX */ i__1 = 0, i__2 = ilaenv_(&c__3, "DGEQRF", " ", m, n, &c_n1, &c_n1, ( ftnlen)6, (ftnlen)1); nx = max(i__1,i__2); if (nx < k) { /* Determine if workspace is large enough for blocked code. */ ldwork = *n; iws = ldwork * nb; if (*lwork < iws) { /* Not enough workspace to use optimal NB: reduce NB and determine the minimum value of NB. */ nb = *lwork / ldwork; /* Computing MAX */ i__1 = 2, i__2 = ilaenv_(&c__2, "DGEQRF", " ", m, n, &c_n1, & c_n1, (ftnlen)6, (ftnlen)1); nbmin = max(i__1,i__2); } } } if (nb >= nbmin && nb < k && nx < k) { /* Use blocked code initially */ i__1 = k - nx; i__2 = nb; for (i__ = 1; i__2 < 0 ? i__ >= i__1 : i__ <= i__1; i__ += i__2) { /* Computing MIN */ i__3 = k - i__ + 1; ib = min(i__3,nb); /* Compute the QR factorization of the current block A(i:m,i:i+ib-1) */ i__3 = *m - i__ + 1; dgeqr2_(&i__3, &ib, &a[i__ + i__ * a_dim1], lda, &tau[i__], &work[ 1], &iinfo); if (i__ + ib <= *n) { /* Form the triangular factor of the block reflector H = H(i) H(i+1) . . . H(i+ib-1) */ i__3 = *m - i__ + 1; dlarft_("Forward", "Columnwise", &i__3, &ib, &a[i__ + i__ * a_dim1], lda, &tau[i__], &work[1], &ldwork); /* Apply H' to A(i:m,i+ib:n) from the left */ i__3 = *m - i__ + 1; i__4 = *n - i__ - ib + 1; dlarfb_("Left", "Transpose", "Forward", "Columnwise", &i__3, & i__4, &ib, &a[i__ + i__ * a_dim1], lda, &work[1], & ldwork, &a[i__ + (i__ + ib) * a_dim1], lda, &work[ib + 1], &ldwork); } /* L10: */ } } else { i__ = 1; } /* Use unblocked code to factor the last or only block. */ if (i__ <= k) { i__2 = *m - i__ + 1; i__1 = *n - i__ + 1; dgeqr2_(&i__2, &i__1, &a[i__ + i__ * a_dim1], lda, &tau[i__], &work[1] , &iinfo); } work[1] = (doublereal) iws; return 0; /* End of DGEQRF */ } /* dgeqrf_ */ /* Subroutine */ int dgesdd_(char *jobz, integer *m, integer *n, doublereal * a, integer *lda, doublereal *s, doublereal *u, integer *ldu, doublereal *vt, integer *ldvt, doublereal *work, integer *lwork, integer *iwork, integer *info) { /* System generated locals */ integer a_dim1, a_offset, u_dim1, u_offset, vt_dim1, vt_offset, i__1, i__2, i__3; /* Builtin functions */ double sqrt(doublereal); /* Local variables */ static integer i__, ie, il, ir, iu, blk; static doublereal dum[1], eps; static integer ivt, iscl; static doublereal anrm; static integer idum[1], ierr, itau; extern /* Subroutine */ int dgemm_(char *, char *, integer *, integer *, integer *, doublereal *, doublereal *, integer *, doublereal *, integer *, doublereal *, doublereal *, integer *); extern logical lsame_(char *, char *); static integer chunk, minmn, wrkbl, itaup, itauq, mnthr; static logical wntqa; static integer nwork; static logical wntqn, wntqo, wntqs; extern /* Subroutine */ int dbdsdc_(char *, char *, integer *, doublereal *, doublereal *, doublereal *, integer *, doublereal *, integer *, doublereal *, integer *, doublereal *, integer *, integer *), dgebrd_(integer *, integer *, doublereal *, integer *, doublereal *, doublereal *, doublereal *, doublereal *, doublereal *, integer *, integer *); extern doublereal dlamch_(char *), dlange_(char *, integer *, integer *, doublereal *, integer *, doublereal *); static integer bdspac; extern /* Subroutine */ int dgelqf_(integer *, integer *, doublereal *, integer *, doublereal *, doublereal *, integer *, integer *), dlascl_(char *, integer *, integer *, doublereal *, doublereal *, integer *, integer *, doublereal *, integer *, integer *), dgeqrf_(integer *, integer *, doublereal *, integer *, doublereal *, doublereal *, integer *, integer *), dlacpy_(char *, integer *, integer *, doublereal *, integer *, doublereal *, integer *), dlaset_(char *, integer *, integer *, doublereal *, doublereal *, doublereal *, integer *), xerbla_(char *, integer *), dorgbr_(char *, integer *, integer *, integer *, doublereal *, integer *, doublereal *, doublereal *, integer *, integer *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); static doublereal bignum; extern /* Subroutine */ int dormbr_(char *, char *, char *, integer *, integer *, integer *, doublereal *, integer *, doublereal *, doublereal *, integer *, doublereal *, integer *, integer *), dorglq_(integer *, integer *, integer *, doublereal *, integer *, doublereal *, doublereal *, integer *, integer *), dorgqr_(integer *, integer *, integer *, doublereal *, integer *, doublereal *, doublereal *, integer *, integer *); static integer ldwrkl, ldwrkr, minwrk, ldwrku, maxwrk, ldwkvt; static doublereal smlnum; static logical wntqas, lquery; /* -- LAPACK driver routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University October 31, 1999 Purpose ======= DGESDD computes the singular value decomposition (SVD) of a real M-by-N matrix A, optionally computing the left and right singular vectors. If singular vectors are desired, it uses a divide-and-conquer algorithm. The SVD is written A = U * SIGMA * transpose(V) where SIGMA is an M-by-N matrix which is zero except for its min(m,n) diagonal elements, U is an M-by-M orthogonal matrix, and V is an N-by-N orthogonal matrix. The diagonal elements of SIGMA are the singular values of A; they are real and non-negative, and are returned in descending order. The first min(m,n) columns of U and V are the left and right singular vectors of A. Note that the routine returns VT = V**T, not V. The divide and conquer algorithm makes very mild assumptions about floating point arithmetic. It will work on machines with a guard digit in add/subtract, or on those binary machines without guard digits which subtract like the Cray X-MP, Cray Y-MP, Cray C-90, or Cray-2. It could conceivably fail on hexadecimal or decimal machines without guard digits, but we know of none. Arguments ========= JOBZ (input) CHARACTER*1 Specifies options for computing all or part of the matrix U: = 'A': all M columns of U and all N rows of V**T are returned in the arrays U and VT; = 'S': the first min(M,N) columns of U and the first min(M,N) rows of V**T are returned in the arrays U and VT; = 'O': If M >= N, the first N columns of U are overwritten on the array A and all rows of V**T are returned in the array VT; otherwise, all columns of U are returned in the array U and the first M rows of V**T are overwritten in the array VT; = 'N': no columns of U or rows of V**T are computed. M (input) INTEGER The number of rows of the input matrix A. M >= 0. N (input) INTEGER The number of columns of the input matrix A. N >= 0. A (input/output) DOUBLE PRECISION array, dimension (LDA,N) On entry, the M-by-N matrix A. On exit, if JOBZ = 'O', A is overwritten with the first N columns of U (the left singular vectors, stored columnwise) if M >= N; A is overwritten with the first M rows of V**T (the right singular vectors, stored rowwise) otherwise. if JOBZ .ne. 'O', the contents of A are destroyed. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,M). S (output) DOUBLE PRECISION array, dimension (min(M,N)) The singular values of A, sorted so that S(i) >= S(i+1). U (output) DOUBLE PRECISION array, dimension (LDU,UCOL) UCOL = M if JOBZ = 'A' or JOBZ = 'O' and M < N; UCOL = min(M,N) if JOBZ = 'S'. If JOBZ = 'A' or JOBZ = 'O' and M < N, U contains the M-by-M orthogonal matrix U; if JOBZ = 'S', U contains the first min(M,N) columns of U (the left singular vectors, stored columnwise); if JOBZ = 'O' and M >= N, or JOBZ = 'N', U is not referenced. LDU (input) INTEGER The leading dimension of the array U. LDU >= 1; if JOBZ = 'S' or 'A' or JOBZ = 'O' and M < N, LDU >= M. VT (output) DOUBLE PRECISION array, dimension (LDVT,N) If JOBZ = 'A' or JOBZ = 'O' and M >= N, VT contains the N-by-N orthogonal matrix V**T; if JOBZ = 'S', VT contains the first min(M,N) rows of V**T (the right singular vectors, stored rowwise); if JOBZ = 'O' and M < N, or JOBZ = 'N', VT is not referenced. LDVT (input) INTEGER The leading dimension of the array VT. LDVT >= 1; if JOBZ = 'A' or JOBZ = 'O' and M >= N, LDVT >= N; if JOBZ = 'S', LDVT >= min(M,N). WORK (workspace/output) DOUBLE PRECISION array, dimension (LWORK) On exit, if INFO = 0, WORK(1) returns the optimal LWORK; LWORK (input) INTEGER The dimension of the array WORK. LWORK >= 1. If JOBZ = 'N', LWORK >= 3*min(M,N) + max(max(M,N),6*min(M,N)). If JOBZ = 'O', LWORK >= 3*min(M,N)*min(M,N) + max(max(M,N),5*min(M,N)*min(M,N)+4*min(M,N)). If JOBZ = 'S' or 'A' LWORK >= 3*min(M,N)*min(M,N) + max(max(M,N),4*min(M,N)*min(M,N)+4*min(M,N)). For good performance, LWORK should generally be larger. If LWORK < 0 but other input arguments are legal, WORK(1) returns the optimal LWORK. IWORK (workspace) INTEGER array, dimension (8*min(M,N)) INFO (output) INTEGER = 0: successful exit. < 0: if INFO = -i, the i-th argument had an illegal value. > 0: DBDSDC did not converge, updating process failed. Further Details =============== Based on contributions by Ming Gu and Huan Ren, Computer Science Division, University of California at Berkeley, USA ===================================================================== Test the input arguments */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --s; u_dim1 = *ldu; u_offset = 1 + u_dim1; u -= u_offset; vt_dim1 = *ldvt; vt_offset = 1 + vt_dim1; vt -= vt_offset; --work; --iwork; /* Function Body */ *info = 0; minmn = min(*m,*n); mnthr = (integer) (minmn * 11. / 6.); wntqa = lsame_(jobz, "A"); wntqs = lsame_(jobz, "S"); wntqas = (wntqa) || (wntqs); wntqo = lsame_(jobz, "O"); wntqn = lsame_(jobz, "N"); minwrk = 1; maxwrk = 1; lquery = *lwork == -1; if (! ((((wntqa) || (wntqs)) || (wntqo)) || (wntqn))) { *info = -1; } else if (*m < 0) { *info = -2; } else if (*n < 0) { *info = -3; } else if (*lda < max(1,*m)) { *info = -5; } else if (((*ldu < 1) || (wntqas && *ldu < *m)) || (wntqo && *m < *n && * ldu < *m)) { *info = -8; } else if ((((*ldvt < 1) || (wntqa && *ldvt < *n)) || (wntqs && *ldvt < minmn)) || (wntqo && *m >= *n && *ldvt < *n)) { *info = -10; } /* Compute workspace (Note: Comments in the code beginning "Workspace:" describe the minimal amount of workspace needed at that point in the code, as well as the preferred amount for good performance. NB refers to the optimal block size for the immediately following subroutine, as returned by ILAENV.) */ if (*info == 0 && *m > 0 && *n > 0) { if (*m >= *n) { /* Compute space needed for DBDSDC */ if (wntqn) { bdspac = *n * 7; } else { bdspac = *n * 3 * *n + ((*n) << (2)); } if (*m >= mnthr) { if (wntqn) { /* Path 1 (M much larger than N, JOBZ='N') */ wrkbl = *n + *n * ilaenv_(&c__1, "DGEQRF", " ", m, n, & c_n1, &c_n1, (ftnlen)6, (ftnlen)1); /* Computing MAX */ i__1 = wrkbl, i__2 = *n * 3 + ((*n) << (1)) * ilaenv_(& c__1, "DGEBRD", " ", n, n, &c_n1, &c_n1, (ftnlen) 6, (ftnlen)1); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = bdspac + *n; maxwrk = max(i__1,i__2); minwrk = bdspac + *n; } else if (wntqo) { /* Path 2 (M much larger than N, JOBZ='O') */ wrkbl = *n + *n * ilaenv_(&c__1, "DGEQRF", " ", m, n, & c_n1, &c_n1, (ftnlen)6, (ftnlen)1); /* Computing MAX */ i__1 = wrkbl, i__2 = *n + *n * ilaenv_(&c__1, "DORGQR", " ", m, n, n, &c_n1, (ftnlen)6, (ftnlen)1); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = *n * 3 + ((*n) << (1)) * ilaenv_(& c__1, "DGEBRD", " ", n, n, &c_n1, &c_n1, (ftnlen) 6, (ftnlen)1); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = *n * 3 + *n * ilaenv_(&c__1, "DORMBR" , "QLN", n, n, n, &c_n1, (ftnlen)6, (ftnlen)3); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = *n * 3 + *n * ilaenv_(&c__1, "DORMBR" , "PRT", n, n, n, &c_n1, (ftnlen)6, (ftnlen)3); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = bdspac + *n * 3; wrkbl = max(i__1,i__2); maxwrk = wrkbl + ((*n) << (1)) * *n; minwrk = bdspac + ((*n) << (1)) * *n + *n * 3; } else if (wntqs) { /* Path 3 (M much larger than N, JOBZ='S') */ wrkbl = *n + *n * ilaenv_(&c__1, "DGEQRF", " ", m, n, & c_n1, &c_n1, (ftnlen)6, (ftnlen)1); /* Computing MAX */ i__1 = wrkbl, i__2 = *n + *n * ilaenv_(&c__1, "DORGQR", " ", m, n, n, &c_n1, (ftnlen)6, (ftnlen)1); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = *n * 3 + ((*n) << (1)) * ilaenv_(& c__1, "DGEBRD", " ", n, n, &c_n1, &c_n1, (ftnlen) 6, (ftnlen)1); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = *n * 3 + *n * ilaenv_(&c__1, "DORMBR" , "QLN", n, n, n, &c_n1, (ftnlen)6, (ftnlen)3); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = *n * 3 + *n * ilaenv_(&c__1, "DORMBR" , "PRT", n, n, n, &c_n1, (ftnlen)6, (ftnlen)3); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = bdspac + *n * 3; wrkbl = max(i__1,i__2); maxwrk = wrkbl + *n * *n; minwrk = bdspac + *n * *n + *n * 3; } else if (wntqa) { /* Path 4 (M much larger than N, JOBZ='A') */ wrkbl = *n + *n * ilaenv_(&c__1, "DGEQRF", " ", m, n, & c_n1, &c_n1, (ftnlen)6, (ftnlen)1); /* Computing MAX */ i__1 = wrkbl, i__2 = *n + *m * ilaenv_(&c__1, "DORGQR", " ", m, m, n, &c_n1, (ftnlen)6, (ftnlen)1); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = *n * 3 + ((*n) << (1)) * ilaenv_(& c__1, "DGEBRD", " ", n, n, &c_n1, &c_n1, (ftnlen) 6, (ftnlen)1); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = *n * 3 + *n * ilaenv_(&c__1, "DORMBR" , "QLN", n, n, n, &c_n1, (ftnlen)6, (ftnlen)3); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = *n * 3 + *n * ilaenv_(&c__1, "DORMBR" , "PRT", n, n, n, &c_n1, (ftnlen)6, (ftnlen)3); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = bdspac + *n * 3; wrkbl = max(i__1,i__2); maxwrk = wrkbl + *n * *n; minwrk = bdspac + *n * *n + *n * 3; } } else { /* Path 5 (M at least N, but not much larger) */ wrkbl = *n * 3 + (*m + *n) * ilaenv_(&c__1, "DGEBRD", " ", m, n, &c_n1, &c_n1, (ftnlen)6, (ftnlen)1); if (wntqn) { /* Computing MAX */ i__1 = wrkbl, i__2 = bdspac + *n * 3; maxwrk = max(i__1,i__2); minwrk = *n * 3 + max(*m,bdspac); } else if (wntqo) { /* Computing MAX */ i__1 = wrkbl, i__2 = *n * 3 + *n * ilaenv_(&c__1, "DORMBR" , "QLN", m, n, n, &c_n1, (ftnlen)6, (ftnlen)3); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = *n * 3 + *n * ilaenv_(&c__1, "DORMBR" , "PRT", n, n, n, &c_n1, (ftnlen)6, (ftnlen)3); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = bdspac + *n * 3; wrkbl = max(i__1,i__2); maxwrk = wrkbl + *m * *n; /* Computing MAX */ i__1 = *m, i__2 = *n * *n + bdspac; minwrk = *n * 3 + max(i__1,i__2); } else if (wntqs) { /* Computing MAX */ i__1 = wrkbl, i__2 = *n * 3 + *n * ilaenv_(&c__1, "DORMBR" , "QLN", m, n, n, &c_n1, (ftnlen)6, (ftnlen)3); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = *n * 3 + *n * ilaenv_(&c__1, "DORMBR" , "PRT", n, n, n, &c_n1, (ftnlen)6, (ftnlen)3); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = bdspac + *n * 3; maxwrk = max(i__1,i__2); minwrk = *n * 3 + max(*m,bdspac); } else if (wntqa) { /* Computing MAX */ i__1 = wrkbl, i__2 = *n * 3 + *m * ilaenv_(&c__1, "DORMBR" , "QLN", m, m, n, &c_n1, (ftnlen)6, (ftnlen)3); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = *n * 3 + *n * ilaenv_(&c__1, "DORMBR" , "PRT", n, n, n, &c_n1, (ftnlen)6, (ftnlen)3); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = maxwrk, i__2 = bdspac + *n * 3; maxwrk = max(i__1,i__2); minwrk = *n * 3 + max(*m,bdspac); } } } else { /* Compute space needed for DBDSDC */ if (wntqn) { bdspac = *m * 7; } else { bdspac = *m * 3 * *m + ((*m) << (2)); } if (*n >= mnthr) { if (wntqn) { /* Path 1t (N much larger than M, JOBZ='N') */ wrkbl = *m + *m * ilaenv_(&c__1, "DGELQF", " ", m, n, & c_n1, &c_n1, (ftnlen)6, (ftnlen)1); /* Computing MAX */ i__1 = wrkbl, i__2 = *m * 3 + ((*m) << (1)) * ilaenv_(& c__1, "DGEBRD", " ", m, m, &c_n1, &c_n1, (ftnlen) 6, (ftnlen)1); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = bdspac + *m; maxwrk = max(i__1,i__2); minwrk = bdspac + *m; } else if (wntqo) { /* Path 2t (N much larger than M, JOBZ='O') */ wrkbl = *m + *m * ilaenv_(&c__1, "DGELQF", " ", m, n, & c_n1, &c_n1, (ftnlen)6, (ftnlen)1); /* Computing MAX */ i__1 = wrkbl, i__2 = *m + *m * ilaenv_(&c__1, "DORGLQ", " ", m, n, m, &c_n1, (ftnlen)6, (ftnlen)1); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = *m * 3 + ((*m) << (1)) * ilaenv_(& c__1, "DGEBRD", " ", m, m, &c_n1, &c_n1, (ftnlen) 6, (ftnlen)1); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = *m * 3 + *m * ilaenv_(&c__1, "DORMBR" , "QLN", m, m, m, &c_n1, (ftnlen)6, (ftnlen)3); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = *m * 3 + *m * ilaenv_(&c__1, "DORMBR" , "PRT", m, m, m, &c_n1, (ftnlen)6, (ftnlen)3); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = bdspac + *m * 3; wrkbl = max(i__1,i__2); maxwrk = wrkbl + ((*m) << (1)) * *m; minwrk = bdspac + ((*m) << (1)) * *m + *m * 3; } else if (wntqs) { /* Path 3t (N much larger than M, JOBZ='S') */ wrkbl = *m + *m * ilaenv_(&c__1, "DGELQF", " ", m, n, & c_n1, &c_n1, (ftnlen)6, (ftnlen)1); /* Computing MAX */ i__1 = wrkbl, i__2 = *m + *m * ilaenv_(&c__1, "DORGLQ", " ", m, n, m, &c_n1, (ftnlen)6, (ftnlen)1); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = *m * 3 + ((*m) << (1)) * ilaenv_(& c__1, "DGEBRD", " ", m, m, &c_n1, &c_n1, (ftnlen) 6, (ftnlen)1); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = *m * 3 + *m * ilaenv_(&c__1, "DORMBR" , "QLN", m, m, m, &c_n1, (ftnlen)6, (ftnlen)3); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = *m * 3 + *m * ilaenv_(&c__1, "DORMBR" , "PRT", m, m, m, &c_n1, (ftnlen)6, (ftnlen)3); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = bdspac + *m * 3; wrkbl = max(i__1,i__2); maxwrk = wrkbl + *m * *m; minwrk = bdspac + *m * *m + *m * 3; } else if (wntqa) { /* Path 4t (N much larger than M, JOBZ='A') */ wrkbl = *m + *m * ilaenv_(&c__1, "DGELQF", " ", m, n, & c_n1, &c_n1, (ftnlen)6, (ftnlen)1); /* Computing MAX */ i__1 = wrkbl, i__2 = *m + *n * ilaenv_(&c__1, "DORGLQ", " ", n, n, m, &c_n1, (ftnlen)6, (ftnlen)1); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = *m * 3 + ((*m) << (1)) * ilaenv_(& c__1, "DGEBRD", " ", m, m, &c_n1, &c_n1, (ftnlen) 6, (ftnlen)1); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = *m * 3 + *m * ilaenv_(&c__1, "DORMBR" , "QLN", m, m, m, &c_n1, (ftnlen)6, (ftnlen)3); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = *m * 3 + *m * ilaenv_(&c__1, "DORMBR" , "PRT", m, m, m, &c_n1, (ftnlen)6, (ftnlen)3); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = bdspac + *m * 3; wrkbl = max(i__1,i__2); maxwrk = wrkbl + *m * *m; minwrk = bdspac + *m * *m + *m * 3; } } else { /* Path 5t (N greater than M, but not much larger) */ wrkbl = *m * 3 + (*m + *n) * ilaenv_(&c__1, "DGEBRD", " ", m, n, &c_n1, &c_n1, (ftnlen)6, (ftnlen)1); if (wntqn) { /* Computing MAX */ i__1 = wrkbl, i__2 = bdspac + *m * 3; maxwrk = max(i__1,i__2); minwrk = *m * 3 + max(*n,bdspac); } else if (wntqo) { /* Computing MAX */ i__1 = wrkbl, i__2 = *m * 3 + *m * ilaenv_(&c__1, "DORMBR" , "QLN", m, m, n, &c_n1, (ftnlen)6, (ftnlen)3); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = *m * 3 + *m * ilaenv_(&c__1, "DORMBR" , "PRT", m, n, m, &c_n1, (ftnlen)6, (ftnlen)3); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = bdspac + *m * 3; wrkbl = max(i__1,i__2); maxwrk = wrkbl + *m * *n; /* Computing MAX */ i__1 = *n, i__2 = *m * *m + bdspac; minwrk = *m * 3 + max(i__1,i__2); } else if (wntqs) { /* Computing MAX */ i__1 = wrkbl, i__2 = *m * 3 + *m * ilaenv_(&c__1, "DORMBR" , "QLN", m, m, n, &c_n1, (ftnlen)6, (ftnlen)3); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = *m * 3 + *m * ilaenv_(&c__1, "DORMBR" , "PRT", m, n, m, &c_n1, (ftnlen)6, (ftnlen)3); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = bdspac + *m * 3; maxwrk = max(i__1,i__2); minwrk = *m * 3 + max(*n,bdspac); } else if (wntqa) { /* Computing MAX */ i__1 = wrkbl, i__2 = *m * 3 + *m * ilaenv_(&c__1, "DORMBR" , "QLN", m, m, n, &c_n1, (ftnlen)6, (ftnlen)3); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = *m * 3 + *m * ilaenv_(&c__1, "DORMBR" , "PRT", n, n, m, &c_n1, (ftnlen)6, (ftnlen)3); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = bdspac + *m * 3; maxwrk = max(i__1,i__2); minwrk = *m * 3 + max(*n,bdspac); } } } work[1] = (doublereal) maxwrk; } if (*lwork < minwrk && ! lquery) { *info = -12; } if (*info != 0) { i__1 = -(*info); xerbla_("DGESDD", &i__1); return 0; } else if (lquery) { return 0; } /* Quick return if possible */ if ((*m == 0) || (*n == 0)) { if (*lwork >= 1) { work[1] = 1.; } return 0; } /* Get machine constants */ eps = PRECISION; smlnum = sqrt(SAFEMINIMUM) / eps; bignum = 1. / smlnum; /* Scale A if max element outside range [SMLNUM,BIGNUM] */ anrm = dlange_("M", m, n, &a[a_offset], lda, dum); iscl = 0; if (anrm > 0. && anrm < smlnum) { iscl = 1; dlascl_("G", &c__0, &c__0, &anrm, &smlnum, m, n, &a[a_offset], lda, & ierr); } else if (anrm > bignum) { iscl = 1; dlascl_("G", &c__0, &c__0, &anrm, &bignum, m, n, &a[a_offset], lda, & ierr); } if (*m >= *n) { /* A has at least as many rows as columns. If A has sufficiently more rows than columns, first reduce using the QR decomposition (if sufficient workspace available) */ if (*m >= mnthr) { if (wntqn) { /* Path 1 (M much larger than N, JOBZ='N') No singular vectors to be computed */ itau = 1; nwork = itau + *n; /* Compute A=Q*R (Workspace: need 2*N, prefer N+N*NB) */ i__1 = *lwork - nwork + 1; dgeqrf_(m, n, &a[a_offset], lda, &work[itau], &work[nwork], & i__1, &ierr); /* Zero out below R */ i__1 = *n - 1; i__2 = *n - 1; dlaset_("L", &i__1, &i__2, &c_b2879, &c_b2879, &a[a_dim1 + 2], lda); ie = 1; itauq = ie + *n; itaup = itauq + *n; nwork = itaup + *n; /* Bidiagonalize R in A (Workspace: need 4*N, prefer 3*N+2*N*NB) */ i__1 = *lwork - nwork + 1; dgebrd_(n, n, &a[a_offset], lda, &s[1], &work[ie], &work[ itauq], &work[itaup], &work[nwork], &i__1, &ierr); nwork = ie + *n; /* Perform bidiagonal SVD, computing singular values only (Workspace: need N+BDSPAC) */ dbdsdc_("U", "N", n, &s[1], &work[ie], dum, &c__1, dum, &c__1, dum, idum, &work[nwork], &iwork[1], info); } else if (wntqo) { /* Path 2 (M much larger than N, JOBZ = 'O') N left singular vectors to be overwritten on A and N right singular vectors to be computed in VT */ ir = 1; /* WORK(IR) is LDWRKR by N */ if (*lwork >= *lda * *n + *n * *n + *n * 3 + bdspac) { ldwrkr = *lda; } else { ldwrkr = (*lwork - *n * *n - *n * 3 - bdspac) / *n; } itau = ir + ldwrkr * *n; nwork = itau + *n; /* Compute A=Q*R (Workspace: need N*N+2*N, prefer N*N+N+N*NB) */ i__1 = *lwork - nwork + 1; dgeqrf_(m, n, &a[a_offset], lda, &work[itau], &work[nwork], & i__1, &ierr); /* Copy R to WORK(IR), zeroing out below it */ dlacpy_("U", n, n, &a[a_offset], lda, &work[ir], &ldwrkr); i__1 = *n - 1; i__2 = *n - 1; dlaset_("L", &i__1, &i__2, &c_b2879, &c_b2879, &work[ir + 1], &ldwrkr); /* Generate Q in A (Workspace: need N*N+2*N, prefer N*N+N+N*NB) */ i__1 = *lwork - nwork + 1; dorgqr_(m, n, n, &a[a_offset], lda, &work[itau], &work[nwork], &i__1, &ierr); ie = itau; itauq = ie + *n; itaup = itauq + *n; nwork = itaup + *n; /* Bidiagonalize R in VT, copying result to WORK(IR) (Workspace: need N*N+4*N, prefer N*N+3*N+2*N*NB) */ i__1 = *lwork - nwork + 1; dgebrd_(n, n, &work[ir], &ldwrkr, &s[1], &work[ie], &work[ itauq], &work[itaup], &work[nwork], &i__1, &ierr); /* WORK(IU) is N by N */ iu = nwork; nwork = iu + *n * *n; /* Perform bidiagonal SVD, computing left singular vectors of bidiagonal matrix in WORK(IU) and computing right singular vectors of bidiagonal matrix in VT (Workspace: need N+N*N+BDSPAC) */ dbdsdc_("U", "I", n, &s[1], &work[ie], &work[iu], n, &vt[ vt_offset], ldvt, dum, idum, &work[nwork], &iwork[1], info); /* Overwrite WORK(IU) by left singular vectors of R and VT by right singular vectors of R (Workspace: need 2*N*N+3*N, prefer 2*N*N+2*N+N*NB) */ i__1 = *lwork - nwork + 1; dormbr_("Q", "L", "N", n, n, n, &work[ir], &ldwrkr, &work[ itauq], &work[iu], n, &work[nwork], &i__1, &ierr); i__1 = *lwork - nwork + 1; dormbr_("P", "R", "T", n, n, n, &work[ir], &ldwrkr, &work[ itaup], &vt[vt_offset], ldvt, &work[nwork], &i__1, & ierr); /* Multiply Q in A by left singular vectors of R in WORK(IU), storing result in WORK(IR) and copying to A (Workspace: need 2*N*N, prefer N*N+M*N) */ i__1 = *m; i__2 = ldwrkr; for (i__ = 1; i__2 < 0 ? i__ >= i__1 : i__ <= i__1; i__ += i__2) { /* Computing MIN */ i__3 = *m - i__ + 1; chunk = min(i__3,ldwrkr); dgemm_("N", "N", &chunk, n, n, &c_b2865, &a[i__ + a_dim1], lda, &work[iu], n, &c_b2879, &work[ir], &ldwrkr); dlacpy_("F", &chunk, n, &work[ir], &ldwrkr, &a[i__ + a_dim1], lda); /* L10: */ } } else if (wntqs) { /* Path 3 (M much larger than N, JOBZ='S') N left singular vectors to be computed in U and N right singular vectors to be computed in VT */ ir = 1; /* WORK(IR) is N by N */ ldwrkr = *n; itau = ir + ldwrkr * *n; nwork = itau + *n; /* Compute A=Q*R (Workspace: need N*N+2*N, prefer N*N+N+N*NB) */ i__2 = *lwork - nwork + 1; dgeqrf_(m, n, &a[a_offset], lda, &work[itau], &work[nwork], & i__2, &ierr); /* Copy R to WORK(IR), zeroing out below it */ dlacpy_("U", n, n, &a[a_offset], lda, &work[ir], &ldwrkr); i__2 = *n - 1; i__1 = *n - 1; dlaset_("L", &i__2, &i__1, &c_b2879, &c_b2879, &work[ir + 1], &ldwrkr); /* Generate Q in A (Workspace: need N*N+2*N, prefer N*N+N+N*NB) */ i__2 = *lwork - nwork + 1; dorgqr_(m, n, n, &a[a_offset], lda, &work[itau], &work[nwork], &i__2, &ierr); ie = itau; itauq = ie + *n; itaup = itauq + *n; nwork = itaup + *n; /* Bidiagonalize R in WORK(IR) (Workspace: need N*N+4*N, prefer N*N+3*N+2*N*NB) */ i__2 = *lwork - nwork + 1; dgebrd_(n, n, &work[ir], &ldwrkr, &s[1], &work[ie], &work[ itauq], &work[itaup], &work[nwork], &i__2, &ierr); /* Perform bidiagonal SVD, computing left singular vectors of bidiagoal matrix in U and computing right singular vectors of bidiagonal matrix in VT (Workspace: need N+BDSPAC) */ dbdsdc_("U", "I", n, &s[1], &work[ie], &u[u_offset], ldu, &vt[ vt_offset], ldvt, dum, idum, &work[nwork], &iwork[1], info); /* Overwrite U by left singular vectors of R and VT by right singular vectors of R (Workspace: need N*N+3*N, prefer N*N+2*N+N*NB) */ i__2 = *lwork - nwork + 1; dormbr_("Q", "L", "N", n, n, n, &work[ir], &ldwrkr, &work[ itauq], &u[u_offset], ldu, &work[nwork], &i__2, &ierr); i__2 = *lwork - nwork + 1; dormbr_("P", "R", "T", n, n, n, &work[ir], &ldwrkr, &work[ itaup], &vt[vt_offset], ldvt, &work[nwork], &i__2, & ierr); /* Multiply Q in A by left singular vectors of R in WORK(IR), storing result in U (Workspace: need N*N) */ dlacpy_("F", n, n, &u[u_offset], ldu, &work[ir], &ldwrkr); dgemm_("N", "N", m, n, n, &c_b2865, &a[a_offset], lda, &work[ ir], &ldwrkr, &c_b2879, &u[u_offset], ldu); } else if (wntqa) { /* Path 4 (M much larger than N, JOBZ='A') M left singular vectors to be computed in U and N right singular vectors to be computed in VT */ iu = 1; /* WORK(IU) is N by N */ ldwrku = *n; itau = iu + ldwrku * *n; nwork = itau + *n; /* Compute A=Q*R, copying result to U (Workspace: need N*N+2*N, prefer N*N+N+N*NB) */ i__2 = *lwork - nwork + 1; dgeqrf_(m, n, &a[a_offset], lda, &work[itau], &work[nwork], & i__2, &ierr); dlacpy_("L", m, n, &a[a_offset], lda, &u[u_offset], ldu); /* Generate Q in U (Workspace: need N*N+2*N, prefer N*N+N+N*NB) */ i__2 = *lwork - nwork + 1; dorgqr_(m, m, n, &u[u_offset], ldu, &work[itau], &work[nwork], &i__2, &ierr); /* Produce R in A, zeroing out other entries */ i__2 = *n - 1; i__1 = *n - 1; dlaset_("L", &i__2, &i__1, &c_b2879, &c_b2879, &a[a_dim1 + 2], lda); ie = itau; itauq = ie + *n; itaup = itauq + *n; nwork = itaup + *n; /* Bidiagonalize R in A (Workspace: need N*N+4*N, prefer N*N+3*N+2*N*NB) */ i__2 = *lwork - nwork + 1; dgebrd_(n, n, &a[a_offset], lda, &s[1], &work[ie], &work[ itauq], &work[itaup], &work[nwork], &i__2, &ierr); /* Perform bidiagonal SVD, computing left singular vectors of bidiagonal matrix in WORK(IU) and computing right singular vectors of bidiagonal matrix in VT (Workspace: need N+N*N+BDSPAC) */ dbdsdc_("U", "I", n, &s[1], &work[ie], &work[iu], n, &vt[ vt_offset], ldvt, dum, idum, &work[nwork], &iwork[1], info); /* Overwrite WORK(IU) by left singular vectors of R and VT by right singular vectors of R (Workspace: need N*N+3*N, prefer N*N+2*N+N*NB) */ i__2 = *lwork - nwork + 1; dormbr_("Q", "L", "N", n, n, n, &a[a_offset], lda, &work[ itauq], &work[iu], &ldwrku, &work[nwork], &i__2, & ierr); i__2 = *lwork - nwork + 1; dormbr_("P", "R", "T", n, n, n, &a[a_offset], lda, &work[ itaup], &vt[vt_offset], ldvt, &work[nwork], &i__2, & ierr); /* Multiply Q in U by left singular vectors of R in WORK(IU), storing result in A (Workspace: need N*N) */ dgemm_("N", "N", m, n, n, &c_b2865, &u[u_offset], ldu, &work[ iu], &ldwrku, &c_b2879, &a[a_offset], lda); /* Copy left singular vectors of A from A to U */ dlacpy_("F", m, n, &a[a_offset], lda, &u[u_offset], ldu); } } else { /* M .LT. MNTHR Path 5 (M at least N, but not much larger) Reduce to bidiagonal form without QR decomposition */ ie = 1; itauq = ie + *n; itaup = itauq + *n; nwork = itaup + *n; /* Bidiagonalize A (Workspace: need 3*N+M, prefer 3*N+(M+N)*NB) */ i__2 = *lwork - nwork + 1; dgebrd_(m, n, &a[a_offset], lda, &s[1], &work[ie], &work[itauq], & work[itaup], &work[nwork], &i__2, &ierr); if (wntqn) { /* Perform bidiagonal SVD, only computing singular values (Workspace: need N+BDSPAC) */ dbdsdc_("U", "N", n, &s[1], &work[ie], dum, &c__1, dum, &c__1, dum, idum, &work[nwork], &iwork[1], info); } else if (wntqo) { iu = nwork; if (*lwork >= *m * *n + *n * 3 + bdspac) { /* WORK( IU ) is M by N */ ldwrku = *m; nwork = iu + ldwrku * *n; dlaset_("F", m, n, &c_b2879, &c_b2879, &work[iu], &ldwrku); } else { /* WORK( IU ) is N by N */ ldwrku = *n; nwork = iu + ldwrku * *n; /* WORK(IR) is LDWRKR by N */ ir = nwork; ldwrkr = (*lwork - *n * *n - *n * 3) / *n; } nwork = iu + ldwrku * *n; /* Perform bidiagonal SVD, computing left singular vectors of bidiagonal matrix in WORK(IU) and computing right singular vectors of bidiagonal matrix in VT (Workspace: need N+N*N+BDSPAC) */ dbdsdc_("U", "I", n, &s[1], &work[ie], &work[iu], &ldwrku, & vt[vt_offset], ldvt, dum, idum, &work[nwork], &iwork[ 1], info); /* Overwrite VT by right singular vectors of A (Workspace: need N*N+2*N, prefer N*N+N+N*NB) */ i__2 = *lwork - nwork + 1; dormbr_("P", "R", "T", n, n, n, &a[a_offset], lda, &work[ itaup], &vt[vt_offset], ldvt, &work[nwork], &i__2, & ierr); if (*lwork >= *m * *n + *n * 3 + bdspac) { /* Overwrite WORK(IU) by left singular vectors of A (Workspace: need N*N+2*N, prefer N*N+N+N*NB) */ i__2 = *lwork - nwork + 1; dormbr_("Q", "L", "N", m, n, n, &a[a_offset], lda, &work[ itauq], &work[iu], &ldwrku, &work[nwork], &i__2, & ierr); /* Copy left singular vectors of A from WORK(IU) to A */ dlacpy_("F", m, n, &work[iu], &ldwrku, &a[a_offset], lda); } else { /* Generate Q in A (Workspace: need N*N+2*N, prefer N*N+N+N*NB) */ i__2 = *lwork - nwork + 1; dorgbr_("Q", m, n, n, &a[a_offset], lda, &work[itauq], & work[nwork], &i__2, &ierr); /* Multiply Q in A by left singular vectors of bidiagonal matrix in WORK(IU), storing result in WORK(IR) and copying to A (Workspace: need 2*N*N, prefer N*N+M*N) */ i__2 = *m; i__1 = ldwrkr; for (i__ = 1; i__1 < 0 ? i__ >= i__2 : i__ <= i__2; i__ += i__1) { /* Computing MIN */ i__3 = *m - i__ + 1; chunk = min(i__3,ldwrkr); dgemm_("N", "N", &chunk, n, n, &c_b2865, &a[i__ + a_dim1], lda, &work[iu], &ldwrku, &c_b2879, & work[ir], &ldwrkr); dlacpy_("F", &chunk, n, &work[ir], &ldwrkr, &a[i__ + a_dim1], lda); /* L20: */ } } } else if (wntqs) { /* Perform bidiagonal SVD, computing left singular vectors of bidiagonal matrix in U and computing right singular vectors of bidiagonal matrix in VT (Workspace: need N+BDSPAC) */ dlaset_("F", m, n, &c_b2879, &c_b2879, &u[u_offset], ldu); dbdsdc_("U", "I", n, &s[1], &work[ie], &u[u_offset], ldu, &vt[ vt_offset], ldvt, dum, idum, &work[nwork], &iwork[1], info); /* Overwrite U by left singular vectors of A and VT by right singular vectors of A (Workspace: need 3*N, prefer 2*N+N*NB) */ i__1 = *lwork - nwork + 1; dormbr_("Q", "L", "N", m, n, n, &a[a_offset], lda, &work[ itauq], &u[u_offset], ldu, &work[nwork], &i__1, &ierr); i__1 = *lwork - nwork + 1; dormbr_("P", "R", "T", n, n, n, &a[a_offset], lda, &work[ itaup], &vt[vt_offset], ldvt, &work[nwork], &i__1, & ierr); } else if (wntqa) { /* Perform bidiagonal SVD, computing left singular vectors of bidiagonal matrix in U and computing right singular vectors of bidiagonal matrix in VT (Workspace: need N+BDSPAC) */ dlaset_("F", m, m, &c_b2879, &c_b2879, &u[u_offset], ldu); dbdsdc_("U", "I", n, &s[1], &work[ie], &u[u_offset], ldu, &vt[ vt_offset], ldvt, dum, idum, &work[nwork], &iwork[1], info); /* Set the right corner of U to identity matrix */ i__1 = *m - *n; i__2 = *m - *n; dlaset_("F", &i__1, &i__2, &c_b2879, &c_b2865, &u[*n + 1 + (* n + 1) * u_dim1], ldu); /* Overwrite U by left singular vectors of A and VT by right singular vectors of A (Workspace: need N*N+2*N+M, prefer N*N+2*N+M*NB) */ i__1 = *lwork - nwork + 1; dormbr_("Q", "L", "N", m, m, n, &a[a_offset], lda, &work[ itauq], &u[u_offset], ldu, &work[nwork], &i__1, &ierr); i__1 = *lwork - nwork + 1; dormbr_("P", "R", "T", n, n, m, &a[a_offset], lda, &work[ itaup], &vt[vt_offset], ldvt, &work[nwork], &i__1, & ierr); } } } else { /* A has more columns than rows. If A has sufficiently more columns than rows, first reduce using the LQ decomposition (if sufficient workspace available) */ if (*n >= mnthr) { if (wntqn) { /* Path 1t (N much larger than M, JOBZ='N') No singular vectors to be computed */ itau = 1; nwork = itau + *m; /* Compute A=L*Q (Workspace: need 2*M, prefer M+M*NB) */ i__1 = *lwork - nwork + 1; dgelqf_(m, n, &a[a_offset], lda, &work[itau], &work[nwork], & i__1, &ierr); /* Zero out above L */ i__1 = *m - 1; i__2 = *m - 1; dlaset_("U", &i__1, &i__2, &c_b2879, &c_b2879, &a[((a_dim1) << (1)) + 1], lda); ie = 1; itauq = ie + *m; itaup = itauq + *m; nwork = itaup + *m; /* Bidiagonalize L in A (Workspace: need 4*M, prefer 3*M+2*M*NB) */ i__1 = *lwork - nwork + 1; dgebrd_(m, m, &a[a_offset], lda, &s[1], &work[ie], &work[ itauq], &work[itaup], &work[nwork], &i__1, &ierr); nwork = ie + *m; /* Perform bidiagonal SVD, computing singular values only (Workspace: need M+BDSPAC) */ dbdsdc_("U", "N", m, &s[1], &work[ie], dum, &c__1, dum, &c__1, dum, idum, &work[nwork], &iwork[1], info); } else if (wntqo) { /* Path 2t (N much larger than M, JOBZ='O') M right singular vectors to be overwritten on A and M left singular vectors to be computed in U */ ivt = 1; /* IVT is M by M */ il = ivt + *m * *m; if (*lwork >= *m * *n + *m * *m + *m * 3 + bdspac) { /* WORK(IL) is M by N */ ldwrkl = *m; chunk = *n; } else { ldwrkl = *m; chunk = (*lwork - *m * *m) / *m; } itau = il + ldwrkl * *m; nwork = itau + *m; /* Compute A=L*Q (Workspace: need M*M+2*M, prefer M*M+M+M*NB) */ i__1 = *lwork - nwork + 1; dgelqf_(m, n, &a[a_offset], lda, &work[itau], &work[nwork], & i__1, &ierr); /* Copy L to WORK(IL), zeroing about above it */ dlacpy_("L", m, m, &a[a_offset], lda, &work[il], &ldwrkl); i__1 = *m - 1; i__2 = *m - 1; dlaset_("U", &i__1, &i__2, &c_b2879, &c_b2879, &work[il + ldwrkl], &ldwrkl); /* Generate Q in A (Workspace: need M*M+2*M, prefer M*M+M+M*NB) */ i__1 = *lwork - nwork + 1; dorglq_(m, n, m, &a[a_offset], lda, &work[itau], &work[nwork], &i__1, &ierr); ie = itau; itauq = ie + *m; itaup = itauq + *m; nwork = itaup + *m; /* Bidiagonalize L in WORK(IL) (Workspace: need M*M+4*M, prefer M*M+3*M+2*M*NB) */ i__1 = *lwork - nwork + 1; dgebrd_(m, m, &work[il], &ldwrkl, &s[1], &work[ie], &work[ itauq], &work[itaup], &work[nwork], &i__1, &ierr); /* Perform bidiagonal SVD, computing left singular vectors of bidiagonal matrix in U, and computing right singular vectors of bidiagonal matrix in WORK(IVT) (Workspace: need M+M*M+BDSPAC) */ dbdsdc_("U", "I", m, &s[1], &work[ie], &u[u_offset], ldu, & work[ivt], m, dum, idum, &work[nwork], &iwork[1], info); /* Overwrite U by left singular vectors of L and WORK(IVT) by right singular vectors of L (Workspace: need 2*M*M+3*M, prefer 2*M*M+2*M+M*NB) */ i__1 = *lwork - nwork + 1; dormbr_("Q", "L", "N", m, m, m, &work[il], &ldwrkl, &work[ itauq], &u[u_offset], ldu, &work[nwork], &i__1, &ierr); i__1 = *lwork - nwork + 1; dormbr_("P", "R", "T", m, m, m, &work[il], &ldwrkl, &work[ itaup], &work[ivt], m, &work[nwork], &i__1, &ierr); /* Multiply right singular vectors of L in WORK(IVT) by Q in A, storing result in WORK(IL) and copying to A (Workspace: need 2*M*M, prefer M*M+M*N) */ i__1 = *n; i__2 = chunk; for (i__ = 1; i__2 < 0 ? i__ >= i__1 : i__ <= i__1; i__ += i__2) { /* Computing MIN */ i__3 = *n - i__ + 1; blk = min(i__3,chunk); dgemm_("N", "N", m, &blk, m, &c_b2865, &work[ivt], m, &a[ i__ * a_dim1 + 1], lda, &c_b2879, &work[il], & ldwrkl); dlacpy_("F", m, &blk, &work[il], &ldwrkl, &a[i__ * a_dim1 + 1], lda); /* L30: */ } } else if (wntqs) { /* Path 3t (N much larger than M, JOBZ='S') M right singular vectors to be computed in VT and M left singular vectors to be computed in U */ il = 1; /* WORK(IL) is M by M */ ldwrkl = *m; itau = il + ldwrkl * *m; nwork = itau + *m; /* Compute A=L*Q (Workspace: need M*M+2*M, prefer M*M+M+M*NB) */ i__2 = *lwork - nwork + 1; dgelqf_(m, n, &a[a_offset], lda, &work[itau], &work[nwork], & i__2, &ierr); /* Copy L to WORK(IL), zeroing out above it */ dlacpy_("L", m, m, &a[a_offset], lda, &work[il], &ldwrkl); i__2 = *m - 1; i__1 = *m - 1; dlaset_("U", &i__2, &i__1, &c_b2879, &c_b2879, &work[il + ldwrkl], &ldwrkl); /* Generate Q in A (Workspace: need M*M+2*M, prefer M*M+M+M*NB) */ i__2 = *lwork - nwork + 1; dorglq_(m, n, m, &a[a_offset], lda, &work[itau], &work[nwork], &i__2, &ierr); ie = itau; itauq = ie + *m; itaup = itauq + *m; nwork = itaup + *m; /* Bidiagonalize L in WORK(IU), copying result to U (Workspace: need M*M+4*M, prefer M*M+3*M+2*M*NB) */ i__2 = *lwork - nwork + 1; dgebrd_(m, m, &work[il], &ldwrkl, &s[1], &work[ie], &work[ itauq], &work[itaup], &work[nwork], &i__2, &ierr); /* Perform bidiagonal SVD, computing left singular vectors of bidiagonal matrix in U and computing right singular vectors of bidiagonal matrix in VT (Workspace: need M+BDSPAC) */ dbdsdc_("U", "I", m, &s[1], &work[ie], &u[u_offset], ldu, &vt[ vt_offset], ldvt, dum, idum, &work[nwork], &iwork[1], info); /* Overwrite U by left singular vectors of L and VT by right singular vectors of L (Workspace: need M*M+3*M, prefer M*M+2*M+M*NB) */ i__2 = *lwork - nwork + 1; dormbr_("Q", "L", "N", m, m, m, &work[il], &ldwrkl, &work[ itauq], &u[u_offset], ldu, &work[nwork], &i__2, &ierr); i__2 = *lwork - nwork + 1; dormbr_("P", "R", "T", m, m, m, &work[il], &ldwrkl, &work[ itaup], &vt[vt_offset], ldvt, &work[nwork], &i__2, & ierr); /* Multiply right singular vectors of L in WORK(IL) by Q in A, storing result in VT (Workspace: need M*M) */ dlacpy_("F", m, m, &vt[vt_offset], ldvt, &work[il], &ldwrkl); dgemm_("N", "N", m, n, m, &c_b2865, &work[il], &ldwrkl, &a[ a_offset], lda, &c_b2879, &vt[vt_offset], ldvt); } else if (wntqa) { /* Path 4t (N much larger than M, JOBZ='A') N right singular vectors to be computed in VT and M left singular vectors to be computed in U */ ivt = 1; /* WORK(IVT) is M by M */ ldwkvt = *m; itau = ivt + ldwkvt * *m; nwork = itau + *m; /* Compute A=L*Q, copying result to VT (Workspace: need M*M+2*M, prefer M*M+M+M*NB) */ i__2 = *lwork - nwork + 1; dgelqf_(m, n, &a[a_offset], lda, &work[itau], &work[nwork], & i__2, &ierr); dlacpy_("U", m, n, &a[a_offset], lda, &vt[vt_offset], ldvt); /* Generate Q in VT (Workspace: need M*M+2*M, prefer M*M+M+M*NB) */ i__2 = *lwork - nwork + 1; dorglq_(n, n, m, &vt[vt_offset], ldvt, &work[itau], &work[ nwork], &i__2, &ierr); /* Produce L in A, zeroing out other entries */ i__2 = *m - 1; i__1 = *m - 1; dlaset_("U", &i__2, &i__1, &c_b2879, &c_b2879, &a[((a_dim1) << (1)) + 1], lda); ie = itau; itauq = ie + *m; itaup = itauq + *m; nwork = itaup + *m; /* Bidiagonalize L in A (Workspace: need M*M+4*M, prefer M*M+3*M+2*M*NB) */ i__2 = *lwork - nwork + 1; dgebrd_(m, m, &a[a_offset], lda, &s[1], &work[ie], &work[ itauq], &work[itaup], &work[nwork], &i__2, &ierr); /* Perform bidiagonal SVD, computing left singular vectors of bidiagonal matrix in U and computing right singular vectors of bidiagonal matrix in WORK(IVT) (Workspace: need M+M*M+BDSPAC) */ dbdsdc_("U", "I", m, &s[1], &work[ie], &u[u_offset], ldu, & work[ivt], &ldwkvt, dum, idum, &work[nwork], &iwork[1] , info); /* Overwrite U by left singular vectors of L and WORK(IVT) by right singular vectors of L (Workspace: need M*M+3*M, prefer M*M+2*M+M*NB) */ i__2 = *lwork - nwork + 1; dormbr_("Q", "L", "N", m, m, m, &a[a_offset], lda, &work[ itauq], &u[u_offset], ldu, &work[nwork], &i__2, &ierr); i__2 = *lwork - nwork + 1; dormbr_("P", "R", "T", m, m, m, &a[a_offset], lda, &work[ itaup], &work[ivt], &ldwkvt, &work[nwork], &i__2, & ierr); /* Multiply right singular vectors of L in WORK(IVT) by Q in VT, storing result in A (Workspace: need M*M) */ dgemm_("N", "N", m, n, m, &c_b2865, &work[ivt], &ldwkvt, &vt[ vt_offset], ldvt, &c_b2879, &a[a_offset], lda); /* Copy right singular vectors of A from A to VT */ dlacpy_("F", m, n, &a[a_offset], lda, &vt[vt_offset], ldvt); } } else { /* N .LT. MNTHR Path 5t (N greater than M, but not much larger) Reduce to bidiagonal form without LQ decomposition */ ie = 1; itauq = ie + *m; itaup = itauq + *m; nwork = itaup + *m; /* Bidiagonalize A (Workspace: need 3*M+N, prefer 3*M+(M+N)*NB) */ i__2 = *lwork - nwork + 1; dgebrd_(m, n, &a[a_offset], lda, &s[1], &work[ie], &work[itauq], & work[itaup], &work[nwork], &i__2, &ierr); if (wntqn) { /* Perform bidiagonal SVD, only computing singular values (Workspace: need M+BDSPAC) */ dbdsdc_("L", "N", m, &s[1], &work[ie], dum, &c__1, dum, &c__1, dum, idum, &work[nwork], &iwork[1], info); } else if (wntqo) { ldwkvt = *m; ivt = nwork; if (*lwork >= *m * *n + *m * 3 + bdspac) { /* WORK( IVT ) is M by N */ dlaset_("F", m, n, &c_b2879, &c_b2879, &work[ivt], & ldwkvt); nwork = ivt + ldwkvt * *n; } else { /* WORK( IVT ) is M by M */ nwork = ivt + ldwkvt * *m; il = nwork; /* WORK(IL) is M by CHUNK */ chunk = (*lwork - *m * *m - *m * 3) / *m; } /* Perform bidiagonal SVD, computing left singular vectors of bidiagonal matrix in U and computing right singular vectors of bidiagonal matrix in WORK(IVT) (Workspace: need M*M+BDSPAC) */ dbdsdc_("L", "I", m, &s[1], &work[ie], &u[u_offset], ldu, & work[ivt], &ldwkvt, dum, idum, &work[nwork], &iwork[1] , info); /* Overwrite U by left singular vectors of A (Workspace: need M*M+2*M, prefer M*M+M+M*NB) */ i__2 = *lwork - nwork + 1; dormbr_("Q", "L", "N", m, m, n, &a[a_offset], lda, &work[ itauq], &u[u_offset], ldu, &work[nwork], &i__2, &ierr); if (*lwork >= *m * *n + *m * 3 + bdspac) { /* Overwrite WORK(IVT) by left singular vectors of A (Workspace: need M*M+2*M, prefer M*M+M+M*NB) */ i__2 = *lwork - nwork + 1; dormbr_("P", "R", "T", m, n, m, &a[a_offset], lda, &work[ itaup], &work[ivt], &ldwkvt, &work[nwork], &i__2, &ierr); /* Copy right singular vectors of A from WORK(IVT) to A */ dlacpy_("F", m, n, &work[ivt], &ldwkvt, &a[a_offset], lda); } else { /* Generate P**T in A (Workspace: need M*M+2*M, prefer M*M+M+M*NB) */ i__2 = *lwork - nwork + 1; dorgbr_("P", m, n, m, &a[a_offset], lda, &work[itaup], & work[nwork], &i__2, &ierr); /* Multiply Q in A by right singular vectors of bidiagonal matrix in WORK(IVT), storing result in WORK(IL) and copying to A (Workspace: need 2*M*M, prefer M*M+M*N) */ i__2 = *n; i__1 = chunk; for (i__ = 1; i__1 < 0 ? i__ >= i__2 : i__ <= i__2; i__ += i__1) { /* Computing MIN */ i__3 = *n - i__ + 1; blk = min(i__3,chunk); dgemm_("N", "N", m, &blk, m, &c_b2865, &work[ivt], & ldwkvt, &a[i__ * a_dim1 + 1], lda, &c_b2879, & work[il], m); dlacpy_("F", m, &blk, &work[il], m, &a[i__ * a_dim1 + 1], lda); /* L40: */ } } } else if (wntqs) { /* Perform bidiagonal SVD, computing left singular vectors of bidiagonal matrix in U and computing right singular vectors of bidiagonal matrix in VT (Workspace: need M+BDSPAC) */ dlaset_("F", m, n, &c_b2879, &c_b2879, &vt[vt_offset], ldvt); dbdsdc_("L", "I", m, &s[1], &work[ie], &u[u_offset], ldu, &vt[ vt_offset], ldvt, dum, idum, &work[nwork], &iwork[1], info); /* Overwrite U by left singular vectors of A and VT by right singular vectors of A (Workspace: need 3*M, prefer 2*M+M*NB) */ i__1 = *lwork - nwork + 1; dormbr_("Q", "L", "N", m, m, n, &a[a_offset], lda, &work[ itauq], &u[u_offset], ldu, &work[nwork], &i__1, &ierr); i__1 = *lwork - nwork + 1; dormbr_("P", "R", "T", m, n, m, &a[a_offset], lda, &work[ itaup], &vt[vt_offset], ldvt, &work[nwork], &i__1, & ierr); } else if (wntqa) { /* Perform bidiagonal SVD, computing left singular vectors of bidiagonal matrix in U and computing right singular vectors of bidiagonal matrix in VT (Workspace: need M+BDSPAC) */ dlaset_("F", n, n, &c_b2879, &c_b2879, &vt[vt_offset], ldvt); dbdsdc_("L", "I", m, &s[1], &work[ie], &u[u_offset], ldu, &vt[ vt_offset], ldvt, dum, idum, &work[nwork], &iwork[1], info); /* Set the right corner of VT to identity matrix */ i__1 = *n - *m; i__2 = *n - *m; dlaset_("F", &i__1, &i__2, &c_b2879, &c_b2865, &vt[*m + 1 + (* m + 1) * vt_dim1], ldvt); /* Overwrite U by left singular vectors of A and VT by right singular vectors of A (Workspace: need 2*M+N, prefer 2*M+N*NB) */ i__1 = *lwork - nwork + 1; dormbr_("Q", "L", "N", m, m, n, &a[a_offset], lda, &work[ itauq], &u[u_offset], ldu, &work[nwork], &i__1, &ierr); i__1 = *lwork - nwork + 1; dormbr_("P", "R", "T", n, n, m, &a[a_offset], lda, &work[ itaup], &vt[vt_offset], ldvt, &work[nwork], &i__1, & ierr); } } } /* Undo scaling if necessary */ if (iscl == 1) { if (anrm > bignum) { dlascl_("G", &c__0, &c__0, &bignum, &anrm, &minmn, &c__1, &s[1], & minmn, &ierr); } if (anrm < smlnum) { dlascl_("G", &c__0, &c__0, &smlnum, &anrm, &minmn, &c__1, &s[1], & minmn, &ierr); } } /* Return optimal workspace in WORK(1) */ work[1] = (doublereal) maxwrk; return 0; /* End of DGESDD */ } /* dgesdd_ */ /* Subroutine */ int dgesv_(integer *n, integer *nrhs, doublereal *a, integer *lda, integer *ipiv, doublereal *b, integer *ldb, integer *info) { /* System generated locals */ integer a_dim1, a_offset, b_dim1, b_offset, i__1; /* Local variables */ extern /* Subroutine */ int dgetrf_(integer *, integer *, doublereal *, integer *, integer *, integer *), xerbla_(char *, integer *), dgetrs_(char *, integer *, integer *, doublereal *, integer *, integer *, doublereal *, integer *, integer *); /* -- LAPACK driver routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University March 31, 1993 Purpose ======= DGESV computes the solution to a real system of linear equations A * X = B, where A is an N-by-N matrix and X and B are N-by-NRHS matrices. The LU decomposition with partial pivoting and row interchanges is used to factor A as A = P * L * U, where P is a permutation matrix, L is unit lower triangular, and U is upper triangular. The factored form of A is then used to solve the system of equations A * X = B. Arguments ========= N (input) INTEGER The number of linear equations, i.e., the order of the matrix A. N >= 0. NRHS (input) INTEGER The number of right hand sides, i.e., the number of columns of the matrix B. NRHS >= 0. A (input/output) DOUBLE PRECISION array, dimension (LDA,N) On entry, the N-by-N coefficient matrix A. On exit, the factors L and U from the factorization A = P*L*U; the unit diagonal elements of L are not stored. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,N). IPIV (output) INTEGER array, dimension (N) The pivot indices that define the permutation matrix P; row i of the matrix was interchanged with row IPIV(i). B (input/output) DOUBLE PRECISION array, dimension (LDB,NRHS) On entry, the N-by-NRHS matrix of right hand side matrix B. On exit, if INFO = 0, the N-by-NRHS solution matrix X. LDB (input) INTEGER The leading dimension of the array B. LDB >= max(1,N). INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value > 0: if INFO = i, U(i,i) is exactly zero. The factorization has been completed, but the factor U is exactly singular, so the solution could not be computed. ===================================================================== Test the input parameters. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --ipiv; b_dim1 = *ldb; b_offset = 1 + b_dim1; b -= b_offset; /* Function Body */ *info = 0; if (*n < 0) { *info = -1; } else if (*nrhs < 0) { *info = -2; } else if (*lda < max(1,*n)) { *info = -4; } else if (*ldb < max(1,*n)) { *info = -7; } if (*info != 0) { i__1 = -(*info); xerbla_("DGESV ", &i__1); return 0; } /* Compute the LU factorization of A. */ dgetrf_(n, n, &a[a_offset], lda, &ipiv[1], info); if (*info == 0) { /* Solve the system A*X = B, overwriting B with X. */ dgetrs_("No transpose", n, nrhs, &a[a_offset], lda, &ipiv[1], &b[ b_offset], ldb, info); } return 0; /* End of DGESV */ } /* dgesv_ */ /* Subroutine */ int dgetf2_(integer *m, integer *n, doublereal *a, integer * lda, integer *ipiv, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3; doublereal d__1; /* Local variables */ static integer j, jp; extern /* Subroutine */ int dger_(integer *, integer *, doublereal *, doublereal *, integer *, doublereal *, integer *, doublereal *, integer *), dscal_(integer *, doublereal *, doublereal *, integer *), dswap_(integer *, doublereal *, integer *, doublereal *, integer *); extern integer idamax_(integer *, doublereal *, integer *); extern /* Subroutine */ int xerbla_(char *, integer *); /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1992 Purpose ======= DGETF2 computes an LU factorization of a general m-by-n matrix A using partial pivoting with row interchanges. The factorization has the form A = P * L * U where P is a permutation matrix, L is lower triangular with unit diagonal elements (lower trapezoidal if m > n), and U is upper triangular (upper trapezoidal if m < n). This is the right-looking Level 2 BLAS version of the algorithm. Arguments ========= M (input) INTEGER The number of rows of the matrix A. M >= 0. N (input) INTEGER The number of columns of the matrix A. N >= 0. A (input/output) DOUBLE PRECISION array, dimension (LDA,N) On entry, the m by n matrix to be factored. On exit, the factors L and U from the factorization A = P*L*U; the unit diagonal elements of L are not stored. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,M). IPIV (output) INTEGER array, dimension (min(M,N)) The pivot indices; for 1 <= i <= min(M,N), row i of the matrix was interchanged with row IPIV(i). INFO (output) INTEGER = 0: successful exit < 0: if INFO = -k, the k-th argument had an illegal value > 0: if INFO = k, U(k,k) is exactly zero. The factorization has been completed, but the factor U is exactly singular, and division by zero will occur if it is used to solve a system of equations. ===================================================================== Test the input parameters. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --ipiv; /* Function Body */ *info = 0; if (*m < 0) { *info = -1; } else if (*n < 0) { *info = -2; } else if (*lda < max(1,*m)) { *info = -4; } if (*info != 0) { i__1 = -(*info); xerbla_("DGETF2", &i__1); return 0; } /* Quick return if possible */ if ((*m == 0) || (*n == 0)) { return 0; } i__1 = min(*m,*n); for (j = 1; j <= i__1; ++j) { /* Find pivot and test for singularity. */ i__2 = *m - j + 1; jp = j - 1 + idamax_(&i__2, &a[j + j * a_dim1], &c__1); ipiv[j] = jp; if (a[jp + j * a_dim1] != 0.) { /* Apply the interchange to columns 1:N. */ if (jp != j) { dswap_(n, &a[j + a_dim1], lda, &a[jp + a_dim1], lda); } /* Compute elements J+1:M of J-th column. */ if (j < *m) { i__2 = *m - j; d__1 = 1. / a[j + j * a_dim1]; dscal_(&i__2, &d__1, &a[j + 1 + j * a_dim1], &c__1); } } else if (*info == 0) { *info = j; } if (j < min(*m,*n)) { /* Update trailing submatrix. */ i__2 = *m - j; i__3 = *n - j; dger_(&i__2, &i__3, &c_b3001, &a[j + 1 + j * a_dim1], &c__1, &a[j + (j + 1) * a_dim1], lda, &a[j + 1 + (j + 1) * a_dim1], lda); } /* L10: */ } return 0; /* End of DGETF2 */ } /* dgetf2_ */ /* Subroutine */ int dgetrf_(integer *m, integer *n, doublereal *a, integer * lda, integer *ipiv, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3, i__4, i__5; /* Local variables */ static integer i__, j, jb, nb; extern /* Subroutine */ int dgemm_(char *, char *, integer *, integer *, integer *, doublereal *, doublereal *, integer *, doublereal *, integer *, doublereal *, doublereal *, integer *); static integer iinfo; extern /* Subroutine */ int dtrsm_(char *, char *, char *, char *, integer *, integer *, doublereal *, doublereal *, integer *, doublereal *, integer *), dgetf2_( integer *, integer *, doublereal *, integer *, integer *, integer *), xerbla_(char *, integer *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); extern /* Subroutine */ int dlaswp_(integer *, doublereal *, integer *, integer *, integer *, integer *, integer *); /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University March 31, 1993 Purpose ======= DGETRF computes an LU factorization of a general M-by-N matrix A using partial pivoting with row interchanges. The factorization has the form A = P * L * U where P is a permutation matrix, L is lower triangular with unit diagonal elements (lower trapezoidal if m > n), and U is upper triangular (upper trapezoidal if m < n). This is the right-looking Level 3 BLAS version of the algorithm. Arguments ========= M (input) INTEGER The number of rows of the matrix A. M >= 0. N (input) INTEGER The number of columns of the matrix A. N >= 0. A (input/output) DOUBLE PRECISION array, dimension (LDA,N) On entry, the M-by-N matrix to be factored. On exit, the factors L and U from the factorization A = P*L*U; the unit diagonal elements of L are not stored. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,M). IPIV (output) INTEGER array, dimension (min(M,N)) The pivot indices; for 1 <= i <= min(M,N), row i of the matrix was interchanged with row IPIV(i). INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value > 0: if INFO = i, U(i,i) is exactly zero. The factorization has been completed, but the factor U is exactly singular, and division by zero will occur if it is used to solve a system of equations. ===================================================================== Test the input parameters. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --ipiv; /* Function Body */ *info = 0; if (*m < 0) { *info = -1; } else if (*n < 0) { *info = -2; } else if (*lda < max(1,*m)) { *info = -4; } if (*info != 0) { i__1 = -(*info); xerbla_("DGETRF", &i__1); return 0; } /* Quick return if possible */ if ((*m == 0) || (*n == 0)) { return 0; } /* Determine the block size for this environment. */ nb = ilaenv_(&c__1, "DGETRF", " ", m, n, &c_n1, &c_n1, (ftnlen)6, (ftnlen) 1); if ((nb <= 1) || (nb >= min(*m,*n))) { /* Use unblocked code. */ dgetf2_(m, n, &a[a_offset], lda, &ipiv[1], info); } else { /* Use blocked code. */ i__1 = min(*m,*n); i__2 = nb; for (j = 1; i__2 < 0 ? j >= i__1 : j <= i__1; j += i__2) { /* Computing MIN */ i__3 = min(*m,*n) - j + 1; jb = min(i__3,nb); /* Factor diagonal and subdiagonal blocks and test for exact singularity. */ i__3 = *m - j + 1; dgetf2_(&i__3, &jb, &a[j + j * a_dim1], lda, &ipiv[j], &iinfo); /* Adjust INFO and the pivot indices. */ if (*info == 0 && iinfo > 0) { *info = iinfo + j - 1; } /* Computing MIN */ i__4 = *m, i__5 = j + jb - 1; i__3 = min(i__4,i__5); for (i__ = j; i__ <= i__3; ++i__) { ipiv[i__] = j - 1 + ipiv[i__]; /* L10: */ } /* Apply interchanges to columns 1:J-1. */ i__3 = j - 1; i__4 = j + jb - 1; dlaswp_(&i__3, &a[a_offset], lda, &j, &i__4, &ipiv[1], &c__1); if (j + jb <= *n) { /* Apply interchanges to columns J+JB:N. */ i__3 = *n - j - jb + 1; i__4 = j + jb - 1; dlaswp_(&i__3, &a[(j + jb) * a_dim1 + 1], lda, &j, &i__4, & ipiv[1], &c__1); /* Compute block row of U. */ i__3 = *n - j - jb + 1; dtrsm_("Left", "Lower", "No transpose", "Unit", &jb, &i__3, & c_b2865, &a[j + j * a_dim1], lda, &a[j + (j + jb) * a_dim1], lda); if (j + jb <= *m) { /* Update trailing submatrix. */ i__3 = *m - j - jb + 1; i__4 = *n - j - jb + 1; dgemm_("No transpose", "No transpose", &i__3, &i__4, &jb, &c_b3001, &a[j + jb + j * a_dim1], lda, &a[j + (j + jb) * a_dim1], lda, &c_b2865, &a[j + jb + (j + jb) * a_dim1], lda); } } /* L20: */ } } return 0; /* End of DGETRF */ } /* dgetrf_ */ /* Subroutine */ int dgetrs_(char *trans, integer *n, integer *nrhs, doublereal *a, integer *lda, integer *ipiv, doublereal *b, integer * ldb, integer *info) { /* System generated locals */ integer a_dim1, a_offset, b_dim1, b_offset, i__1; /* Local variables */ extern logical lsame_(char *, char *); extern /* Subroutine */ int dtrsm_(char *, char *, char *, char *, integer *, integer *, doublereal *, doublereal *, integer *, doublereal *, integer *), xerbla_( char *, integer *), dlaswp_(integer *, doublereal *, integer *, integer *, integer *, integer *, integer *); static logical notran; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University March 31, 1993 Purpose ======= DGETRS solves a system of linear equations A * X = B or A' * X = B with a general N-by-N matrix A using the LU factorization computed by DGETRF. Arguments ========= TRANS (input) CHARACTER*1 Specifies the form of the system of equations: = 'N': A * X = B (No transpose) = 'T': A'* X = B (Transpose) = 'C': A'* X = B (Conjugate transpose = Transpose) N (input) INTEGER The order of the matrix A. N >= 0. NRHS (input) INTEGER The number of right hand sides, i.e., the number of columns of the matrix B. NRHS >= 0. A (input) DOUBLE PRECISION array, dimension (LDA,N) The factors L and U from the factorization A = P*L*U as computed by DGETRF. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,N). IPIV (input) INTEGER array, dimension (N) The pivot indices from DGETRF; for 1<=i<=N, row i of the matrix was interchanged with row IPIV(i). B (input/output) DOUBLE PRECISION array, dimension (LDB,NRHS) On entry, the right hand side matrix B. On exit, the solution matrix X. LDB (input) INTEGER The leading dimension of the array B. LDB >= max(1,N). INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value ===================================================================== Test the input parameters. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --ipiv; b_dim1 = *ldb; b_offset = 1 + b_dim1; b -= b_offset; /* Function Body */ *info = 0; notran = lsame_(trans, "N"); if (! notran && ! lsame_(trans, "T") && ! lsame_( trans, "C")) { *info = -1; } else if (*n < 0) { *info = -2; } else if (*nrhs < 0) { *info = -3; } else if (*lda < max(1,*n)) { *info = -5; } else if (*ldb < max(1,*n)) { *info = -8; } if (*info != 0) { i__1 = -(*info); xerbla_("DGETRS", &i__1); return 0; } /* Quick return if possible */ if ((*n == 0) || (*nrhs == 0)) { return 0; } if (notran) { /* Solve A * X = B. Apply row interchanges to the right hand sides. */ dlaswp_(nrhs, &b[b_offset], ldb, &c__1, n, &ipiv[1], &c__1); /* Solve L*X = B, overwriting B with X. */ dtrsm_("Left", "Lower", "No transpose", "Unit", n, nrhs, &c_b2865, &a[ a_offset], lda, &b[b_offset], ldb); /* Solve U*X = B, overwriting B with X. */ dtrsm_("Left", "Upper", "No transpose", "Non-unit", n, nrhs, &c_b2865, &a[a_offset], lda, &b[b_offset], ldb); } else { /* Solve A' * X = B. Solve U'*X = B, overwriting B with X. */ dtrsm_("Left", "Upper", "Transpose", "Non-unit", n, nrhs, &c_b2865, & a[a_offset], lda, &b[b_offset], ldb); /* Solve L'*X = B, overwriting B with X. */ dtrsm_("Left", "Lower", "Transpose", "Unit", n, nrhs, &c_b2865, &a[ a_offset], lda, &b[b_offset], ldb); /* Apply row interchanges to the solution vectors. */ dlaswp_(nrhs, &b[b_offset], ldb, &c__1, n, &ipiv[1], &c_n1); } return 0; /* End of DGETRS */ } /* dgetrs_ */ /* Subroutine */ int dhseqr_(char *job, char *compz, integer *n, integer *ilo, integer *ihi, doublereal *h__, integer *ldh, doublereal *wr, doublereal *wi, doublereal *z__, integer *ldz, doublereal *work, integer *lwork, integer *info) { /* System generated locals */ address a__1[2]; integer h_dim1, h_offset, z_dim1, z_offset, i__1, i__2, i__3[2], i__4, i__5; doublereal d__1, d__2; char ch__1[2]; /* Builtin functions */ /* Subroutine */ int s_cat(char *, char **, integer *, integer *, ftnlen); /* Local variables */ static integer i__, j, k, l; static doublereal s[225] /* was [15][15] */, v[16]; static integer i1, i2, ii, nh, nr, ns, nv; static doublereal vv[16]; static integer itn; static doublereal tau; static integer its; static doublereal ulp, tst1; static integer maxb; static doublereal absw; static integer ierr; static doublereal unfl, temp, ovfl; extern /* Subroutine */ int dscal_(integer *, doublereal *, doublereal *, integer *); extern logical lsame_(char *, char *); extern /* Subroutine */ int dgemv_(char *, integer *, integer *, doublereal *, doublereal *, integer *, doublereal *, integer *, doublereal *, doublereal *, integer *); static integer itemp; extern /* Subroutine */ int dcopy_(integer *, doublereal *, integer *, doublereal *, integer *); static logical initz, wantt, wantz; extern doublereal dlapy2_(doublereal *, doublereal *); extern /* Subroutine */ int dlabad_(doublereal *, doublereal *); extern /* Subroutine */ int dlarfg_(integer *, doublereal *, doublereal *, integer *, doublereal *); extern integer idamax_(integer *, doublereal *, integer *); extern doublereal dlanhs_(char *, integer *, doublereal *, integer *, doublereal *); extern /* Subroutine */ int dlahqr_(logical *, logical *, integer *, integer *, integer *, doublereal *, integer *, doublereal *, doublereal *, integer *, integer *, doublereal *, integer *, integer *), dlacpy_(char *, integer *, integer *, doublereal *, integer *, doublereal *, integer *), dlaset_(char *, integer *, integer *, doublereal *, doublereal *, doublereal *, integer *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); extern /* Subroutine */ int xerbla_(char *, integer *), dlarfx_( char *, integer *, integer *, doublereal *, doublereal *, doublereal *, integer *, doublereal *); static doublereal smlnum; static logical lquery; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= DHSEQR computes the eigenvalues of a real upper Hessenberg matrix H and, optionally, the matrices T and Z from the Schur decomposition H = Z T Z**T, where T is an upper quasi-triangular matrix (the Schur form), and Z is the orthogonal matrix of Schur vectors. Optionally Z may be postmultiplied into an input orthogonal matrix Q, so that this routine can give the Schur factorization of a matrix A which has been reduced to the Hessenberg form H by the orthogonal matrix Q: A = Q*H*Q**T = (QZ)*T*(QZ)**T. Arguments ========= JOB (input) CHARACTER*1 = 'E': compute eigenvalues only; = 'S': compute eigenvalues and the Schur form T. COMPZ (input) CHARACTER*1 = 'N': no Schur vectors are computed; = 'I': Z is initialized to the unit matrix and the matrix Z of Schur vectors of H is returned; = 'V': Z must contain an orthogonal matrix Q on entry, and the product Q*Z is returned. N (input) INTEGER The order of the matrix H. N >= 0. ILO (input) INTEGER IHI (input) INTEGER It is assumed that H is already upper triangular in rows and columns 1:ILO-1 and IHI+1:N. ILO and IHI are normally set by a previous call to DGEBAL, and then passed to SGEHRD when the matrix output by DGEBAL is reduced to Hessenberg form. Otherwise ILO and IHI should be set to 1 and N respectively. 1 <= ILO <= IHI <= N, if N > 0; ILO=1 and IHI=0, if N=0. H (input/output) DOUBLE PRECISION array, dimension (LDH,N) On entry, the upper Hessenberg matrix H. On exit, if JOB = 'S', H contains the upper quasi-triangular matrix T from the Schur decomposition (the Schur form); 2-by-2 diagonal blocks (corresponding to complex conjugate pairs of eigenvalues) are returned in standard form, with H(i,i) = H(i+1,i+1) and H(i+1,i)*H(i,i+1) < 0. If JOB = 'E', the contents of H are unspecified on exit. LDH (input) INTEGER The leading dimension of the array H. LDH >= max(1,N). WR (output) DOUBLE PRECISION array, dimension (N) WI (output) DOUBLE PRECISION array, dimension (N) The real and imaginary parts, respectively, of the computed eigenvalues. If two eigenvalues are computed as a complex conjugate pair, they are stored in consecutive elements of WR and WI, say the i-th and (i+1)th, with WI(i) > 0 and WI(i+1) < 0. If JOB = 'S', the eigenvalues are stored in the same order as on the diagonal of the Schur form returned in H, with WR(i) = H(i,i) and, if H(i:i+1,i:i+1) is a 2-by-2 diagonal block, WI(i) = sqrt(H(i+1,i)*H(i,i+1)) and WI(i+1) = -WI(i). Z (input/output) DOUBLE PRECISION array, dimension (LDZ,N) If COMPZ = 'N': Z is not referenced. If COMPZ = 'I': on entry, Z need not be set, and on exit, Z contains the orthogonal matrix Z of the Schur vectors of H. If COMPZ = 'V': on entry Z must contain an N-by-N matrix Q, which is assumed to be equal to the unit matrix except for the submatrix Z(ILO:IHI,ILO:IHI); on exit Z contains Q*Z. Normally Q is the orthogonal matrix generated by DORGHR after the call to DGEHRD which formed the Hessenberg matrix H. LDZ (input) INTEGER The leading dimension of the array Z. LDZ >= max(1,N) if COMPZ = 'I' or 'V'; LDZ >= 1 otherwise. WORK (workspace/output) DOUBLE PRECISION array, dimension (LWORK) On exit, if INFO = 0, WORK(1) returns the optimal LWORK. LWORK (input) INTEGER The dimension of the array WORK. LWORK >= max(1,N). If LWORK = -1, then a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued by XERBLA. INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value > 0: if INFO = i, DHSEQR failed to compute all of the eigenvalues in a total of 30*(IHI-ILO+1) iterations; elements 1:ilo-1 and i+1:n of WR and WI contain those eigenvalues which have been successfully computed. ===================================================================== Decode and test the input parameters */ /* Parameter adjustments */ h_dim1 = *ldh; h_offset = 1 + h_dim1; h__ -= h_offset; --wr; --wi; z_dim1 = *ldz; z_offset = 1 + z_dim1; z__ -= z_offset; --work; /* Function Body */ wantt = lsame_(job, "S"); initz = lsame_(compz, "I"); wantz = (initz) || (lsame_(compz, "V")); *info = 0; work[1] = (doublereal) max(1,*n); lquery = *lwork == -1; if (! lsame_(job, "E") && ! wantt) { *info = -1; } else if (! lsame_(compz, "N") && ! wantz) { *info = -2; } else if (*n < 0) { *info = -3; } else if ((*ilo < 1) || (*ilo > max(1,*n))) { *info = -4; } else if ((*ihi < min(*ilo,*n)) || (*ihi > *n)) { *info = -5; } else if (*ldh < max(1,*n)) { *info = -7; } else if ((*ldz < 1) || (wantz && *ldz < max(1,*n))) { *info = -11; } else if (*lwork < max(1,*n) && ! lquery) { *info = -13; } if (*info != 0) { i__1 = -(*info); xerbla_("DHSEQR", &i__1); return 0; } else if (lquery) { return 0; } /* Initialize Z, if necessary */ if (initz) { dlaset_("Full", n, n, &c_b2879, &c_b2865, &z__[z_offset], ldz); } /* Store the eigenvalues isolated by DGEBAL. */ i__1 = *ilo - 1; for (i__ = 1; i__ <= i__1; ++i__) { wr[i__] = h__[i__ + i__ * h_dim1]; wi[i__] = 0.; /* L10: */ } i__1 = *n; for (i__ = *ihi + 1; i__ <= i__1; ++i__) { wr[i__] = h__[i__ + i__ * h_dim1]; wi[i__] = 0.; /* L20: */ } /* Quick return if possible. */ if (*n == 0) { return 0; } if (*ilo == *ihi) { wr[*ilo] = h__[*ilo + *ilo * h_dim1]; wi[*ilo] = 0.; return 0; } /* Set rows and columns ILO to IHI to zero below the first subdiagonal. */ i__1 = *ihi - 2; for (j = *ilo; j <= i__1; ++j) { i__2 = *n; for (i__ = j + 2; i__ <= i__2; ++i__) { h__[i__ + j * h_dim1] = 0.; /* L30: */ } /* L40: */ } nh = *ihi - *ilo + 1; /* Determine the order of the multi-shift QR algorithm to be used. Writing concatenation */ i__3[0] = 1, a__1[0] = job; i__3[1] = 1, a__1[1] = compz; s_cat(ch__1, a__1, i__3, &c__2, (ftnlen)2); ns = ilaenv_(&c__4, "DHSEQR", ch__1, n, ilo, ihi, &c_n1, (ftnlen)6, ( ftnlen)2); /* Writing concatenation */ i__3[0] = 1, a__1[0] = job; i__3[1] = 1, a__1[1] = compz; s_cat(ch__1, a__1, i__3, &c__2, (ftnlen)2); maxb = ilaenv_(&c__8, "DHSEQR", ch__1, n, ilo, ihi, &c_n1, (ftnlen)6, ( ftnlen)2); if (((ns <= 2) || (ns > nh)) || (maxb >= nh)) { /* Use the standard double-shift algorithm */ dlahqr_(&wantt, &wantz, n, ilo, ihi, &h__[h_offset], ldh, &wr[1], &wi[ 1], ilo, ihi, &z__[z_offset], ldz, info); return 0; } maxb = max(3,maxb); /* Computing MIN */ i__1 = min(ns,maxb); ns = min(i__1,15); /* Now 2 < NS <= MAXB < NH. Set machine-dependent constants for the stopping criterion. If norm(H) <= sqrt(OVFL), overflow should not occur. */ unfl = SAFEMINIMUM; ovfl = 1. / unfl; dlabad_(&unfl, &ovfl); ulp = PRECISION; smlnum = unfl * (nh / ulp); /* I1 and I2 are the indices of the first row and last column of H to which transformations must be applied. If eigenvalues only are being computed, I1 and I2 are set inside the main loop. */ if (wantt) { i1 = 1; i2 = *n; } /* ITN is the total number of multiple-shift QR iterations allowed. */ itn = nh * 30; /* The main loop begins here. I is the loop index and decreases from IHI to ILO in steps of at most MAXB. Each iteration of the loop works with the active submatrix in rows and columns L to I. Eigenvalues I+1 to IHI have already converged. Either L = ILO or H(L,L-1) is negligible so that the matrix splits. */ i__ = *ihi; L50: l = *ilo; if (i__ < *ilo) { goto L170; } /* Perform multiple-shift QR iterations on rows and columns ILO to I until a submatrix of order at most MAXB splits off at the bottom because a subdiagonal element has become negligible. */ i__1 = itn; for (its = 0; its <= i__1; ++its) { /* Look for a single small subdiagonal element. */ i__2 = l + 1; for (k = i__; k >= i__2; --k) { tst1 = (d__1 = h__[k - 1 + (k - 1) * h_dim1], abs(d__1)) + (d__2 = h__[k + k * h_dim1], abs(d__2)); if (tst1 == 0.) { i__4 = i__ - l + 1; tst1 = dlanhs_("1", &i__4, &h__[l + l * h_dim1], ldh, &work[1] ); } /* Computing MAX */ d__2 = ulp * tst1; if ((d__1 = h__[k + (k - 1) * h_dim1], abs(d__1)) <= max(d__2, smlnum)) { goto L70; } /* L60: */ } L70: l = k; if (l > *ilo) { /* H(L,L-1) is negligible. */ h__[l + (l - 1) * h_dim1] = 0.; } /* Exit from loop if a submatrix of order <= MAXB has split off. */ if (l >= i__ - maxb + 1) { goto L160; } /* Now the active submatrix is in rows and columns L to I. If eigenvalues only are being computed, only the active submatrix need be transformed. */ if (! wantt) { i1 = l; i2 = i__; } if ((its == 20) || (its == 30)) { /* Exceptional shifts. */ i__2 = i__; for (ii = i__ - ns + 1; ii <= i__2; ++ii) { wr[ii] = ((d__1 = h__[ii + (ii - 1) * h_dim1], abs(d__1)) + ( d__2 = h__[ii + ii * h_dim1], abs(d__2))) * 1.5; wi[ii] = 0.; /* L80: */ } } else { /* Use eigenvalues of trailing submatrix of order NS as shifts. */ dlacpy_("Full", &ns, &ns, &h__[i__ - ns + 1 + (i__ - ns + 1) * h_dim1], ldh, s, &c__15); dlahqr_(&c_false, &c_false, &ns, &c__1, &ns, s, &c__15, &wr[i__ - ns + 1], &wi[i__ - ns + 1], &c__1, &ns, &z__[z_offset], ldz, &ierr); if (ierr > 0) { /* If DLAHQR failed to compute all NS eigenvalues, use the unconverged diagonal elements as the remaining shifts. */ i__2 = ierr; for (ii = 1; ii <= i__2; ++ii) { wr[i__ - ns + ii] = s[ii + ii * 15 - 16]; wi[i__ - ns + ii] = 0.; /* L90: */ } } } /* Form the first column of (G-w(1)) (G-w(2)) . . . (G-w(ns)) where G is the Hessenberg submatrix H(L:I,L:I) and w is the vector of shifts (stored in WR and WI). The result is stored in the local array V. */ v[0] = 1.; i__2 = ns + 1; for (ii = 2; ii <= i__2; ++ii) { v[ii - 1] = 0.; /* L100: */ } nv = 1; i__2 = i__; for (j = i__ - ns + 1; j <= i__2; ++j) { if (wi[j] >= 0.) { if (wi[j] == 0.) { /* real shift */ i__4 = nv + 1; dcopy_(&i__4, v, &c__1, vv, &c__1); i__4 = nv + 1; d__1 = -wr[j]; dgemv_("No transpose", &i__4, &nv, &c_b2865, &h__[l + l * h_dim1], ldh, vv, &c__1, &d__1, v, &c__1); ++nv; } else if (wi[j] > 0.) { /* complex conjugate pair of shifts */ i__4 = nv + 1; dcopy_(&i__4, v, &c__1, vv, &c__1); i__4 = nv + 1; d__1 = wr[j] * -2.; dgemv_("No transpose", &i__4, &nv, &c_b2865, &h__[l + l * h_dim1], ldh, v, &c__1, &d__1, vv, &c__1); i__4 = nv + 1; itemp = idamax_(&i__4, vv, &c__1); /* Computing MAX */ d__2 = (d__1 = vv[itemp - 1], abs(d__1)); temp = 1. / max(d__2,smlnum); i__4 = nv + 1; dscal_(&i__4, &temp, vv, &c__1); absw = dlapy2_(&wr[j], &wi[j]); temp = temp * absw * absw; i__4 = nv + 2; i__5 = nv + 1; dgemv_("No transpose", &i__4, &i__5, &c_b2865, &h__[l + l * h_dim1], ldh, vv, &c__1, &temp, v, &c__1); nv += 2; } /* Scale V(1:NV) so that max(abs(V(i))) = 1. If V is zero, reset it to the unit vector. */ itemp = idamax_(&nv, v, &c__1); temp = (d__1 = v[itemp - 1], abs(d__1)); if (temp == 0.) { v[0] = 1.; i__4 = nv; for (ii = 2; ii <= i__4; ++ii) { v[ii - 1] = 0.; /* L110: */ } } else { temp = max(temp,smlnum); d__1 = 1. / temp; dscal_(&nv, &d__1, v, &c__1); } } /* L120: */ } /* Multiple-shift QR step */ i__2 = i__ - 1; for (k = l; k <= i__2; ++k) { /* The first iteration of this loop determines a reflection G from the vector V and applies it from left and right to H, thus creating a nonzero bulge below the subdiagonal. Each subsequent iteration determines a reflection G to restore the Hessenberg form in the (K-1)th column, and thus chases the bulge one step toward the bottom of the active submatrix. NR is the order of G. Computing MIN */ i__4 = ns + 1, i__5 = i__ - k + 1; nr = min(i__4,i__5); if (k > l) { dcopy_(&nr, &h__[k + (k - 1) * h_dim1], &c__1, v, &c__1); } dlarfg_(&nr, v, &v[1], &c__1, &tau); if (k > l) { h__[k + (k - 1) * h_dim1] = v[0]; i__4 = i__; for (ii = k + 1; ii <= i__4; ++ii) { h__[ii + (k - 1) * h_dim1] = 0.; /* L130: */ } } v[0] = 1.; /* Apply G from the left to transform the rows of the matrix in columns K to I2. */ i__4 = i2 - k + 1; dlarfx_("Left", &nr, &i__4, v, &tau, &h__[k + k * h_dim1], ldh, & work[1]); /* Apply G from the right to transform the columns of the matrix in rows I1 to min(K+NR,I). Computing MIN */ i__5 = k + nr; i__4 = min(i__5,i__) - i1 + 1; dlarfx_("Right", &i__4, &nr, v, &tau, &h__[i1 + k * h_dim1], ldh, &work[1]); if (wantz) { /* Accumulate transformations in the matrix Z */ dlarfx_("Right", &nh, &nr, v, &tau, &z__[*ilo + k * z_dim1], ldz, &work[1]); } /* L140: */ } /* L150: */ } /* Failure to converge in remaining number of iterations */ *info = i__; return 0; L160: /* A submatrix of order <= MAXB in rows and columns L to I has split off. Use the double-shift QR algorithm to handle it. */ dlahqr_(&wantt, &wantz, n, &l, &i__, &h__[h_offset], ldh, &wr[1], &wi[1], ilo, ihi, &z__[z_offset], ldz, info); if (*info > 0) { return 0; } /* Decrement number of remaining iterations, and return to start of the main loop with a new value of I. */ itn -= its; i__ = l - 1; goto L50; L170: work[1] = (doublereal) max(1,*n); return 0; /* End of DHSEQR */ } /* dhseqr_ */ /* Subroutine */ int dlabad_(doublereal *small, doublereal *large) { /* Builtin functions */ double d_lg10(doublereal *), sqrt(doublereal); /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University October 31, 1992 Purpose ======= DLABAD takes as input the values computed by DLAMCH for underflow and overflow, and returns the square root of each of these values if the log of LARGE is sufficiently large. This subroutine is intended to identify machines with a large exponent range, such as the Crays, and redefine the underflow and overflow limits to be the square roots of the values computed by DLAMCH. This subroutine is needed because DLAMCH does not compensate for poor arithmetic in the upper half of the exponent range, as is found on a Cray. Arguments ========= SMALL (input/output) DOUBLE PRECISION On entry, the underflow threshold as computed by DLAMCH. On exit, if LOG10(LARGE) is sufficiently large, the square root of SMALL, otherwise unchanged. LARGE (input/output) DOUBLE PRECISION On entry, the overflow threshold as computed by DLAMCH. On exit, if LOG10(LARGE) is sufficiently large, the square root of LARGE, otherwise unchanged. ===================================================================== If it looks like we're on a Cray, take the square root of SMALL and LARGE to avoid overflow and underflow problems. */ if (d_lg10(large) > 2e3) { *small = sqrt(*small); *large = sqrt(*large); } return 0; /* End of DLABAD */ } /* dlabad_ */ /* Subroutine */ int dlabrd_(integer *m, integer *n, integer *nb, doublereal * a, integer *lda, doublereal *d__, doublereal *e, doublereal *tauq, doublereal *taup, doublereal *x, integer *ldx, doublereal *y, integer *ldy) { /* System generated locals */ integer a_dim1, a_offset, x_dim1, x_offset, y_dim1, y_offset, i__1, i__2, i__3; /* Local variables */ static integer i__; extern /* Subroutine */ int dscal_(integer *, doublereal *, doublereal *, integer *), dgemv_(char *, integer *, integer *, doublereal *, doublereal *, integer *, doublereal *, integer *, doublereal *, doublereal *, integer *), dlarfg_(integer *, doublereal *, doublereal *, integer *, doublereal *); /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University February 29, 1992 Purpose ======= DLABRD reduces the first NB rows and columns of a real general m by n matrix A to upper or lower bidiagonal form by an orthogonal transformation Q' * A * P, and returns the matrices X and Y which are needed to apply the transformation to the unreduced part of A. If m >= n, A is reduced to upper bidiagonal form; if m < n, to lower bidiagonal form. This is an auxiliary routine called by DGEBRD Arguments ========= M (input) INTEGER The number of rows in the matrix A. N (input) INTEGER The number of columns in the matrix A. NB (input) INTEGER The number of leading rows and columns of A to be reduced. A (input/output) DOUBLE PRECISION array, dimension (LDA,N) On entry, the m by n general matrix to be reduced. On exit, the first NB rows and columns of the matrix are overwritten; the rest of the array is unchanged. If m >= n, elements on and below the diagonal in the first NB columns, with the array TAUQ, represent the orthogonal matrix Q as a product of elementary reflectors; and elements above the diagonal in the first NB rows, with the array TAUP, represent the orthogonal matrix P as a product of elementary reflectors. If m < n, elements below the diagonal in the first NB columns, with the array TAUQ, represent the orthogonal matrix Q as a product of elementary reflectors, and elements on and above the diagonal in the first NB rows, with the array TAUP, represent the orthogonal matrix P as a product of elementary reflectors. See Further Details. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,M). D (output) DOUBLE PRECISION array, dimension (NB) The diagonal elements of the first NB rows and columns of the reduced matrix. D(i) = A(i,i). E (output) DOUBLE PRECISION array, dimension (NB) The off-diagonal elements of the first NB rows and columns of the reduced matrix. TAUQ (output) DOUBLE PRECISION array dimension (NB) The scalar factors of the elementary reflectors which represent the orthogonal matrix Q. See Further Details. TAUP (output) DOUBLE PRECISION array, dimension (NB) The scalar factors of the elementary reflectors which represent the orthogonal matrix P. See Further Details. X (output) DOUBLE PRECISION array, dimension (LDX,NB) The m-by-nb matrix X required to update the unreduced part of A. LDX (input) INTEGER The leading dimension of the array X. LDX >= M. Y (output) DOUBLE PRECISION array, dimension (LDY,NB) The n-by-nb matrix Y required to update the unreduced part of A. LDY (output) INTEGER The leading dimension of the array Y. LDY >= N. Further Details =============== The matrices Q and P are represented as products of elementary reflectors: Q = H(1) H(2) . . . H(nb) and P = G(1) G(2) . . . G(nb) Each H(i) and G(i) has the form: H(i) = I - tauq * v * v' and G(i) = I - taup * u * u' where tauq and taup are real scalars, and v and u are real vectors. If m >= n, v(1:i-1) = 0, v(i) = 1, and v(i:m) is stored on exit in A(i:m,i); u(1:i) = 0, u(i+1) = 1, and u(i+1:n) is stored on exit in A(i,i+1:n); tauq is stored in TAUQ(i) and taup in TAUP(i). If m < n, v(1:i) = 0, v(i+1) = 1, and v(i+1:m) is stored on exit in A(i+2:m,i); u(1:i-1) = 0, u(i) = 1, and u(i:n) is stored on exit in A(i,i+1:n); tauq is stored in TAUQ(i) and taup in TAUP(i). The elements of the vectors v and u together form the m-by-nb matrix V and the nb-by-n matrix U' which are needed, with X and Y, to apply the transformation to the unreduced part of the matrix, using a block update of the form: A := A - V*Y' - X*U'. The contents of A on exit are illustrated by the following examples with nb = 2: m = 6 and n = 5 (m > n): m = 5 and n = 6 (m < n): ( 1 1 u1 u1 u1 ) ( 1 u1 u1 u1 u1 u1 ) ( v1 1 1 u2 u2 ) ( 1 1 u2 u2 u2 u2 ) ( v1 v2 a a a ) ( v1 1 a a a a ) ( v1 v2 a a a ) ( v1 v2 a a a a ) ( v1 v2 a a a ) ( v1 v2 a a a a ) ( v1 v2 a a a ) where a denotes an element of the original matrix which is unchanged, vi denotes an element of the vector defining H(i), and ui an element of the vector defining G(i). ===================================================================== Quick return if possible */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --d__; --e; --tauq; --taup; x_dim1 = *ldx; x_offset = 1 + x_dim1; x -= x_offset; y_dim1 = *ldy; y_offset = 1 + y_dim1; y -= y_offset; /* Function Body */ if ((*m <= 0) || (*n <= 0)) { return 0; } if (*m >= *n) { /* Reduce to upper bidiagonal form */ i__1 = *nb; for (i__ = 1; i__ <= i__1; ++i__) { /* Update A(i:m,i) */ i__2 = *m - i__ + 1; i__3 = i__ - 1; dgemv_("No transpose", &i__2, &i__3, &c_b3001, &a[i__ + a_dim1], lda, &y[i__ + y_dim1], ldy, &c_b2865, &a[i__ + i__ * a_dim1], &c__1); i__2 = *m - i__ + 1; i__3 = i__ - 1; dgemv_("No transpose", &i__2, &i__3, &c_b3001, &x[i__ + x_dim1], ldx, &a[i__ * a_dim1 + 1], &c__1, &c_b2865, &a[i__ + i__ * a_dim1], &c__1); /* Generate reflection Q(i) to annihilate A(i+1:m,i) */ i__2 = *m - i__ + 1; /* Computing MIN */ i__3 = i__ + 1; dlarfg_(&i__2, &a[i__ + i__ * a_dim1], &a[min(i__3,*m) + i__ * a_dim1], &c__1, &tauq[i__]); d__[i__] = a[i__ + i__ * a_dim1]; if (i__ < *n) { a[i__ + i__ * a_dim1] = 1.; /* Compute Y(i+1:n,i) */ i__2 = *m - i__ + 1; i__3 = *n - i__; dgemv_("Transpose", &i__2, &i__3, &c_b2865, &a[i__ + (i__ + 1) * a_dim1], lda, &a[i__ + i__ * a_dim1], &c__1, & c_b2879, &y[i__ + 1 + i__ * y_dim1], &c__1) ; i__2 = *m - i__ + 1; i__3 = i__ - 1; dgemv_("Transpose", &i__2, &i__3, &c_b2865, &a[i__ + a_dim1], lda, &a[i__ + i__ * a_dim1], &c__1, &c_b2879, &y[i__ * y_dim1 + 1], &c__1); i__2 = *n - i__; i__3 = i__ - 1; dgemv_("No transpose", &i__2, &i__3, &c_b3001, &y[i__ + 1 + y_dim1], ldy, &y[i__ * y_dim1 + 1], &c__1, &c_b2865, & y[i__ + 1 + i__ * y_dim1], &c__1); i__2 = *m - i__ + 1; i__3 = i__ - 1; dgemv_("Transpose", &i__2, &i__3, &c_b2865, &x[i__ + x_dim1], ldx, &a[i__ + i__ * a_dim1], &c__1, &c_b2879, &y[i__ * y_dim1 + 1], &c__1); i__2 = i__ - 1; i__3 = *n - i__; dgemv_("Transpose", &i__2, &i__3, &c_b3001, &a[(i__ + 1) * a_dim1 + 1], lda, &y[i__ * y_dim1 + 1], &c__1, & c_b2865, &y[i__ + 1 + i__ * y_dim1], &c__1) ; i__2 = *n - i__; dscal_(&i__2, &tauq[i__], &y[i__ + 1 + i__ * y_dim1], &c__1); /* Update A(i,i+1:n) */ i__2 = *n - i__; dgemv_("No transpose", &i__2, &i__, &c_b3001, &y[i__ + 1 + y_dim1], ldy, &a[i__ + a_dim1], lda, &c_b2865, &a[i__ + (i__ + 1) * a_dim1], lda); i__2 = i__ - 1; i__3 = *n - i__; dgemv_("Transpose", &i__2, &i__3, &c_b3001, &a[(i__ + 1) * a_dim1 + 1], lda, &x[i__ + x_dim1], ldx, &c_b2865, &a[ i__ + (i__ + 1) * a_dim1], lda); /* Generate reflection P(i) to annihilate A(i,i+2:n) */ i__2 = *n - i__; /* Computing MIN */ i__3 = i__ + 2; dlarfg_(&i__2, &a[i__ + (i__ + 1) * a_dim1], &a[i__ + min( i__3,*n) * a_dim1], lda, &taup[i__]); e[i__] = a[i__ + (i__ + 1) * a_dim1]; a[i__ + (i__ + 1) * a_dim1] = 1.; /* Compute X(i+1:m,i) */ i__2 = *m - i__; i__3 = *n - i__; dgemv_("No transpose", &i__2, &i__3, &c_b2865, &a[i__ + 1 + ( i__ + 1) * a_dim1], lda, &a[i__ + (i__ + 1) * a_dim1], lda, &c_b2879, &x[i__ + 1 + i__ * x_dim1], &c__1); i__2 = *n - i__; dgemv_("Transpose", &i__2, &i__, &c_b2865, &y[i__ + 1 + y_dim1], ldy, &a[i__ + (i__ + 1) * a_dim1], lda, & c_b2879, &x[i__ * x_dim1 + 1], &c__1); i__2 = *m - i__; dgemv_("No transpose", &i__2, &i__, &c_b3001, &a[i__ + 1 + a_dim1], lda, &x[i__ * x_dim1 + 1], &c__1, &c_b2865, & x[i__ + 1 + i__ * x_dim1], &c__1); i__2 = i__ - 1; i__3 = *n - i__; dgemv_("No transpose", &i__2, &i__3, &c_b2865, &a[(i__ + 1) * a_dim1 + 1], lda, &a[i__ + (i__ + 1) * a_dim1], lda, & c_b2879, &x[i__ * x_dim1 + 1], &c__1); i__2 = *m - i__; i__3 = i__ - 1; dgemv_("No transpose", &i__2, &i__3, &c_b3001, &x[i__ + 1 + x_dim1], ldx, &x[i__ * x_dim1 + 1], &c__1, &c_b2865, & x[i__ + 1 + i__ * x_dim1], &c__1); i__2 = *m - i__; dscal_(&i__2, &taup[i__], &x[i__ + 1 + i__ * x_dim1], &c__1); } /* L10: */ } } else { /* Reduce to lower bidiagonal form */ i__1 = *nb; for (i__ = 1; i__ <= i__1; ++i__) { /* Update A(i,i:n) */ i__2 = *n - i__ + 1; i__3 = i__ - 1; dgemv_("No transpose", &i__2, &i__3, &c_b3001, &y[i__ + y_dim1], ldy, &a[i__ + a_dim1], lda, &c_b2865, &a[i__ + i__ * a_dim1], lda); i__2 = i__ - 1; i__3 = *n - i__ + 1; dgemv_("Transpose", &i__2, &i__3, &c_b3001, &a[i__ * a_dim1 + 1], lda, &x[i__ + x_dim1], ldx, &c_b2865, &a[i__ + i__ * a_dim1], lda); /* Generate reflection P(i) to annihilate A(i,i+1:n) */ i__2 = *n - i__ + 1; /* Computing MIN */ i__3 = i__ + 1; dlarfg_(&i__2, &a[i__ + i__ * a_dim1], &a[i__ + min(i__3,*n) * a_dim1], lda, &taup[i__]); d__[i__] = a[i__ + i__ * a_dim1]; if (i__ < *m) { a[i__ + i__ * a_dim1] = 1.; /* Compute X(i+1:m,i) */ i__2 = *m - i__; i__3 = *n - i__ + 1; dgemv_("No transpose", &i__2, &i__3, &c_b2865, &a[i__ + 1 + i__ * a_dim1], lda, &a[i__ + i__ * a_dim1], lda, & c_b2879, &x[i__ + 1 + i__ * x_dim1], &c__1); i__2 = *n - i__ + 1; i__3 = i__ - 1; dgemv_("Transpose", &i__2, &i__3, &c_b2865, &y[i__ + y_dim1], ldy, &a[i__ + i__ * a_dim1], lda, &c_b2879, &x[i__ * x_dim1 + 1], &c__1); i__2 = *m - i__; i__3 = i__ - 1; dgemv_("No transpose", &i__2, &i__3, &c_b3001, &a[i__ + 1 + a_dim1], lda, &x[i__ * x_dim1 + 1], &c__1, &c_b2865, & x[i__ + 1 + i__ * x_dim1], &c__1); i__2 = i__ - 1; i__3 = *n - i__ + 1; dgemv_("No transpose", &i__2, &i__3, &c_b2865, &a[i__ * a_dim1 + 1], lda, &a[i__ + i__ * a_dim1], lda, & c_b2879, &x[i__ * x_dim1 + 1], &c__1); i__2 = *m - i__; i__3 = i__ - 1; dgemv_("No transpose", &i__2, &i__3, &c_b3001, &x[i__ + 1 + x_dim1], ldx, &x[i__ * x_dim1 + 1], &c__1, &c_b2865, & x[i__ + 1 + i__ * x_dim1], &c__1); i__2 = *m - i__; dscal_(&i__2, &taup[i__], &x[i__ + 1 + i__ * x_dim1], &c__1); /* Update A(i+1:m,i) */ i__2 = *m - i__; i__3 = i__ - 1; dgemv_("No transpose", &i__2, &i__3, &c_b3001, &a[i__ + 1 + a_dim1], lda, &y[i__ + y_dim1], ldy, &c_b2865, &a[i__ + 1 + i__ * a_dim1], &c__1); i__2 = *m - i__; dgemv_("No transpose", &i__2, &i__, &c_b3001, &x[i__ + 1 + x_dim1], ldx, &a[i__ * a_dim1 + 1], &c__1, &c_b2865, & a[i__ + 1 + i__ * a_dim1], &c__1); /* Generate reflection Q(i) to annihilate A(i+2:m,i) */ i__2 = *m - i__; /* Computing MIN */ i__3 = i__ + 2; dlarfg_(&i__2, &a[i__ + 1 + i__ * a_dim1], &a[min(i__3,*m) + i__ * a_dim1], &c__1, &tauq[i__]); e[i__] = a[i__ + 1 + i__ * a_dim1]; a[i__ + 1 + i__ * a_dim1] = 1.; /* Compute Y(i+1:n,i) */ i__2 = *m - i__; i__3 = *n - i__; dgemv_("Transpose", &i__2, &i__3, &c_b2865, &a[i__ + 1 + (i__ + 1) * a_dim1], lda, &a[i__ + 1 + i__ * a_dim1], & c__1, &c_b2879, &y[i__ + 1 + i__ * y_dim1], &c__1); i__2 = *m - i__; i__3 = i__ - 1; dgemv_("Transpose", &i__2, &i__3, &c_b2865, &a[i__ + 1 + a_dim1], lda, &a[i__ + 1 + i__ * a_dim1], &c__1, & c_b2879, &y[i__ * y_dim1 + 1], &c__1); i__2 = *n - i__; i__3 = i__ - 1; dgemv_("No transpose", &i__2, &i__3, &c_b3001, &y[i__ + 1 + y_dim1], ldy, &y[i__ * y_dim1 + 1], &c__1, &c_b2865, & y[i__ + 1 + i__ * y_dim1], &c__1); i__2 = *m - i__; dgemv_("Transpose", &i__2, &i__, &c_b2865, &x[i__ + 1 + x_dim1], ldx, &a[i__ + 1 + i__ * a_dim1], &c__1, & c_b2879, &y[i__ * y_dim1 + 1], &c__1); i__2 = *n - i__; dgemv_("Transpose", &i__, &i__2, &c_b3001, &a[(i__ + 1) * a_dim1 + 1], lda, &y[i__ * y_dim1 + 1], &c__1, & c_b2865, &y[i__ + 1 + i__ * y_dim1], &c__1) ; i__2 = *n - i__; dscal_(&i__2, &tauq[i__], &y[i__ + 1 + i__ * y_dim1], &c__1); } /* L20: */ } } return 0; /* End of DLABRD */ } /* dlabrd_ */ /* Subroutine */ int dlacpy_(char *uplo, integer *m, integer *n, doublereal * a, integer *lda, doublereal *b, integer *ldb) { /* System generated locals */ integer a_dim1, a_offset, b_dim1, b_offset, i__1, i__2; /* Local variables */ static integer i__, j; extern logical lsame_(char *, char *); /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University February 29, 1992 Purpose ======= DLACPY copies all or part of a two-dimensional matrix A to another matrix B. Arguments ========= UPLO (input) CHARACTER*1 Specifies the part of the matrix A to be copied to B. = 'U': Upper triangular part = 'L': Lower triangular part Otherwise: All of the matrix A M (input) INTEGER The number of rows of the matrix A. M >= 0. N (input) INTEGER The number of columns of the matrix A. N >= 0. A (input) DOUBLE PRECISION array, dimension (LDA,N) The m by n matrix A. If UPLO = 'U', only the upper triangle or trapezoid is accessed; if UPLO = 'L', only the lower triangle or trapezoid is accessed. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,M). B (output) DOUBLE PRECISION array, dimension (LDB,N) On exit, B = A in the locations specified by UPLO. LDB (input) INTEGER The leading dimension of the array B. LDB >= max(1,M). ===================================================================== */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; b_dim1 = *ldb; b_offset = 1 + b_dim1; b -= b_offset; /* Function Body */ if (lsame_(uplo, "U")) { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = min(j,*m); for (i__ = 1; i__ <= i__2; ++i__) { b[i__ + j * b_dim1] = a[i__ + j * a_dim1]; /* L10: */ } /* L20: */ } } else if (lsame_(uplo, "L")) { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = j; i__ <= i__2; ++i__) { b[i__ + j * b_dim1] = a[i__ + j * a_dim1]; /* L30: */ } /* L40: */ } } else { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { b[i__ + j * b_dim1] = a[i__ + j * a_dim1]; /* L50: */ } /* L60: */ } } return 0; /* End of DLACPY */ } /* dlacpy_ */ /* Subroutine */ int dladiv_(doublereal *a, doublereal *b, doublereal *c__, doublereal *d__, doublereal *p, doublereal *q) { static doublereal e, f; /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University October 31, 1992 Purpose ======= DLADIV performs complex division in real arithmetic a + i*b p + i*q = --------- c + i*d The algorithm is due to Robert L. Smith and can be found in D. Knuth, The art of Computer Programming, Vol.2, p.195 Arguments ========= A (input) DOUBLE PRECISION B (input) DOUBLE PRECISION C (input) DOUBLE PRECISION D (input) DOUBLE PRECISION The scalars a, b, c, and d in the above expression. P (output) DOUBLE PRECISION Q (output) DOUBLE PRECISION The scalars p and q in the above expression. ===================================================================== */ if (abs(*d__) < abs(*c__)) { e = *d__ / *c__; f = *c__ + *d__ * e; *p = (*a + *b * e) / f; *q = (*b - *a * e) / f; } else { e = *c__ / *d__; f = *d__ + *c__ * e; *p = (*b + *a * e) / f; *q = (-(*a) + *b * e) / f; } return 0; /* End of DLADIV */ } /* dladiv_ */ /* Subroutine */ int dlae2_(doublereal *a, doublereal *b, doublereal *c__, doublereal *rt1, doublereal *rt2) { /* System generated locals */ doublereal d__1; /* Builtin functions */ double sqrt(doublereal); /* Local variables */ static doublereal ab, df, tb, sm, rt, adf, acmn, acmx; /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University October 31, 1992 Purpose ======= DLAE2 computes the eigenvalues of a 2-by-2 symmetric matrix [ A B ] [ B C ]. On return, RT1 is the eigenvalue of larger absolute value, and RT2 is the eigenvalue of smaller absolute value. Arguments ========= A (input) DOUBLE PRECISION The (1,1) element of the 2-by-2 matrix. B (input) DOUBLE PRECISION The (1,2) and (2,1) elements of the 2-by-2 matrix. C (input) DOUBLE PRECISION The (2,2) element of the 2-by-2 matrix. RT1 (output) DOUBLE PRECISION The eigenvalue of larger absolute value. RT2 (output) DOUBLE PRECISION The eigenvalue of smaller absolute value. Further Details =============== RT1 is accurate to a few ulps barring over/underflow. RT2 may be inaccurate if there is massive cancellation in the determinant A*C-B*B; higher precision or correctly rounded or correctly truncated arithmetic would be needed to compute RT2 accurately in all cases. Overflow is possible only if RT1 is within a factor of 5 of overflow. Underflow is harmless if the input data is 0 or exceeds underflow_threshold / macheps. ===================================================================== Compute the eigenvalues */ sm = *a + *c__; df = *a - *c__; adf = abs(df); tb = *b + *b; ab = abs(tb); if (abs(*a) > abs(*c__)) { acmx = *a; acmn = *c__; } else { acmx = *c__; acmn = *a; } if (adf > ab) { /* Computing 2nd power */ d__1 = ab / adf; rt = adf * sqrt(d__1 * d__1 + 1.); } else if (adf < ab) { /* Computing 2nd power */ d__1 = adf / ab; rt = ab * sqrt(d__1 * d__1 + 1.); } else { /* Includes case AB=ADF=0 */ rt = ab * sqrt(2.); } if (sm < 0.) { *rt1 = (sm - rt) * .5; /* Order of execution important. To get fully accurate smaller eigenvalue, next line needs to be executed in higher precision. */ *rt2 = acmx / *rt1 * acmn - *b / *rt1 * *b; } else if (sm > 0.) { *rt1 = (sm + rt) * .5; /* Order of execution important. To get fully accurate smaller eigenvalue, next line needs to be executed in higher precision. */ *rt2 = acmx / *rt1 * acmn - *b / *rt1 * *b; } else { /* Includes case RT1 = RT2 = 0 */ *rt1 = rt * .5; *rt2 = rt * -.5; } return 0; /* End of DLAE2 */ } /* dlae2_ */ /* Subroutine */ int dlaed0_(integer *icompq, integer *qsiz, integer *n, doublereal *d__, doublereal *e, doublereal *q, integer *ldq, doublereal *qstore, integer *ldqs, doublereal *work, integer *iwork, integer *info) { /* System generated locals */ integer q_dim1, q_offset, qstore_dim1, qstore_offset, i__1, i__2; doublereal d__1; /* Builtin functions */ double log(doublereal); integer pow_ii(integer *, integer *); /* Local variables */ static integer i__, j, k, iq, lgn, msd2, smm1, spm1, spm2; static doublereal temp; static integer curr; extern /* Subroutine */ int dgemm_(char *, char *, integer *, integer *, integer *, doublereal *, doublereal *, integer *, doublereal *, integer *, doublereal *, doublereal *, integer *); static integer iperm; extern /* Subroutine */ int dcopy_(integer *, doublereal *, integer *, doublereal *, integer *); static integer indxq, iwrem; extern /* Subroutine */ int dlaed1_(integer *, doublereal *, doublereal *, integer *, integer *, doublereal *, integer *, doublereal *, integer *, integer *); static integer iqptr; extern /* Subroutine */ int dlaed7_(integer *, integer *, integer *, integer *, integer *, integer *, doublereal *, doublereal *, integer *, integer *, doublereal *, integer *, doublereal *, integer *, integer *, integer *, integer *, integer *, doublereal *, doublereal *, integer *, integer *); static integer tlvls; extern /* Subroutine */ int dlacpy_(char *, integer *, integer *, doublereal *, integer *, doublereal *, integer *); static integer igivcl; extern /* Subroutine */ int xerbla_(char *, integer *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); static integer igivnm, submat, curprb, subpbs, igivpt; extern /* Subroutine */ int dsteqr_(char *, integer *, doublereal *, doublereal *, doublereal *, integer *, doublereal *, integer *); static integer curlvl, matsiz, iprmpt, smlsiz; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= DLAED0 computes all eigenvalues and corresponding eigenvectors of a symmetric tridiagonal matrix using the divide and conquer method. Arguments ========= ICOMPQ (input) INTEGER = 0: Compute eigenvalues only. = 1: Compute eigenvectors of original dense symmetric matrix also. On entry, Q contains the orthogonal matrix used to reduce the original matrix to tridiagonal form. = 2: Compute eigenvalues and eigenvectors of tridiagonal matrix. QSIZ (input) INTEGER The dimension of the orthogonal matrix used to reduce the full matrix to tridiagonal form. QSIZ >= N if ICOMPQ = 1. N (input) INTEGER The dimension of the symmetric tridiagonal matrix. N >= 0. D (input/output) DOUBLE PRECISION array, dimension (N) On entry, the main diagonal of the tridiagonal matrix. On exit, its eigenvalues. E (input) DOUBLE PRECISION array, dimension (N-1) The off-diagonal elements of the tridiagonal matrix. On exit, E has been destroyed. Q (input/output) DOUBLE PRECISION array, dimension (LDQ, N) On entry, Q must contain an N-by-N orthogonal matrix. If ICOMPQ = 0 Q is not referenced. If ICOMPQ = 1 On entry, Q is a subset of the columns of the orthogonal matrix used to reduce the full matrix to tridiagonal form corresponding to the subset of the full matrix which is being decomposed at this time. If ICOMPQ = 2 On entry, Q will be the identity matrix. On exit, Q contains the eigenvectors of the tridiagonal matrix. LDQ (input) INTEGER The leading dimension of the array Q. If eigenvectors are desired, then LDQ >= max(1,N). In any case, LDQ >= 1. QSTORE (workspace) DOUBLE PRECISION array, dimension (LDQS, N) Referenced only when ICOMPQ = 1. Used to store parts of the eigenvector matrix when the updating matrix multiplies take place. LDQS (input) INTEGER The leading dimension of the array QSTORE. If ICOMPQ = 1, then LDQS >= max(1,N). In any case, LDQS >= 1. WORK (workspace) DOUBLE PRECISION array, If ICOMPQ = 0 or 1, the dimension of WORK must be at least 1 + 3*N + 2*N*lg N + 2*N**2 ( lg( N ) = smallest integer k such that 2^k >= N ) If ICOMPQ = 2, the dimension of WORK must be at least 4*N + N**2. IWORK (workspace) INTEGER array, If ICOMPQ = 0 or 1, the dimension of IWORK must be at least 6 + 6*N + 5*N*lg N. ( lg( N ) = smallest integer k such that 2^k >= N ) If ICOMPQ = 2, the dimension of IWORK must be at least 3 + 5*N. INFO (output) INTEGER = 0: successful exit. < 0: if INFO = -i, the i-th argument had an illegal value. > 0: The algorithm failed to compute an eigenvalue while working on the submatrix lying in rows and columns INFO/(N+1) through mod(INFO,N+1). Further Details =============== Based on contributions by Jeff Rutter, Computer Science Division, University of California at Berkeley, USA ===================================================================== Test the input parameters. */ /* Parameter adjustments */ --d__; --e; q_dim1 = *ldq; q_offset = 1 + q_dim1; q -= q_offset; qstore_dim1 = *ldqs; qstore_offset = 1 + qstore_dim1; qstore -= qstore_offset; --work; --iwork; /* Function Body */ *info = 0; if ((*icompq < 0) || (*icompq > 2)) { *info = -1; } else if (*icompq == 1 && *qsiz < max(0,*n)) { *info = -2; } else if (*n < 0) { *info = -3; } else if (*ldq < max(1,*n)) { *info = -7; } else if (*ldqs < max(1,*n)) { *info = -9; } if (*info != 0) { i__1 = -(*info); xerbla_("DLAED0", &i__1); return 0; } /* Quick return if possible */ if (*n == 0) { return 0; } smlsiz = ilaenv_(&c__9, "DLAED0", " ", &c__0, &c__0, &c__0, &c__0, ( ftnlen)6, (ftnlen)1); /* Determine the size and placement of the submatrices, and save in the leading elements of IWORK. */ iwork[1] = *n; subpbs = 1; tlvls = 0; L10: if (iwork[subpbs] > smlsiz) { for (j = subpbs; j >= 1; --j) { iwork[j * 2] = (iwork[j] + 1) / 2; iwork[((j) << (1)) - 1] = iwork[j] / 2; /* L20: */ } ++tlvls; subpbs <<= 1; goto L10; } i__1 = subpbs; for (j = 2; j <= i__1; ++j) { iwork[j] += iwork[j - 1]; /* L30: */ } /* Divide the matrix into SUBPBS submatrices of size at most SMLSIZ+1 using rank-1 modifications (cuts). */ spm1 = subpbs - 1; i__1 = spm1; for (i__ = 1; i__ <= i__1; ++i__) { submat = iwork[i__] + 1; smm1 = submat - 1; d__[smm1] -= (d__1 = e[smm1], abs(d__1)); d__[submat] -= (d__1 = e[smm1], abs(d__1)); /* L40: */ } indxq = ((*n) << (2)) + 3; if (*icompq != 2) { /* Set up workspaces for eigenvalues only/accumulate new vectors routine */ temp = log((doublereal) (*n)) / log(2.); lgn = (integer) temp; if (pow_ii(&c__2, &lgn) < *n) { ++lgn; } if (pow_ii(&c__2, &lgn) < *n) { ++lgn; } iprmpt = indxq + *n + 1; iperm = iprmpt + *n * lgn; iqptr = iperm + *n * lgn; igivpt = iqptr + *n + 2; igivcl = igivpt + *n * lgn; igivnm = 1; iq = igivnm + ((*n) << (1)) * lgn; /* Computing 2nd power */ i__1 = *n; iwrem = iq + i__1 * i__1 + 1; /* Initialize pointers */ i__1 = subpbs; for (i__ = 0; i__ <= i__1; ++i__) { iwork[iprmpt + i__] = 1; iwork[igivpt + i__] = 1; /* L50: */ } iwork[iqptr] = 1; } /* Solve each submatrix eigenproblem at the bottom of the divide and conquer tree. */ curr = 0; i__1 = spm1; for (i__ = 0; i__ <= i__1; ++i__) { if (i__ == 0) { submat = 1; matsiz = iwork[1]; } else { submat = iwork[i__] + 1; matsiz = iwork[i__ + 1] - iwork[i__]; } if (*icompq == 2) { dsteqr_("I", &matsiz, &d__[submat], &e[submat], &q[submat + submat * q_dim1], ldq, &work[1], info); if (*info != 0) { goto L130; } } else { dsteqr_("I", &matsiz, &d__[submat], &e[submat], &work[iq - 1 + iwork[iqptr + curr]], &matsiz, &work[1], info); if (*info != 0) { goto L130; } if (*icompq == 1) { dgemm_("N", "N", qsiz, &matsiz, &matsiz, &c_b2865, &q[submat * q_dim1 + 1], ldq, &work[iq - 1 + iwork[iqptr + curr]] , &matsiz, &c_b2879, &qstore[submat * qstore_dim1 + 1] , ldqs); } /* Computing 2nd power */ i__2 = matsiz; iwork[iqptr + curr + 1] = iwork[iqptr + curr] + i__2 * i__2; ++curr; } k = 1; i__2 = iwork[i__ + 1]; for (j = submat; j <= i__2; ++j) { iwork[indxq + j] = k; ++k; /* L60: */ } /* L70: */ } /* Successively merge eigensystems of adjacent submatrices into eigensystem for the corresponding larger matrix. while ( SUBPBS > 1 ) */ curlvl = 1; L80: if (subpbs > 1) { spm2 = subpbs - 2; i__1 = spm2; for (i__ = 0; i__ <= i__1; i__ += 2) { if (i__ == 0) { submat = 1; matsiz = iwork[2]; msd2 = iwork[1]; curprb = 0; } else { submat = iwork[i__] + 1; matsiz = iwork[i__ + 2] - iwork[i__]; msd2 = matsiz / 2; ++curprb; } /* Merge lower order eigensystems (of size MSD2 and MATSIZ - MSD2) into an eigensystem of size MATSIZ. DLAED1 is used only for the full eigensystem of a tridiagonal matrix. DLAED7 handles the cases in which eigenvalues only or eigenvalues and eigenvectors of a full symmetric matrix (which was reduced to tridiagonal form) are desired. */ if (*icompq == 2) { dlaed1_(&matsiz, &d__[submat], &q[submat + submat * q_dim1], ldq, &iwork[indxq + submat], &e[submat + msd2 - 1], & msd2, &work[1], &iwork[subpbs + 1], info); } else { dlaed7_(icompq, &matsiz, qsiz, &tlvls, &curlvl, &curprb, &d__[ submat], &qstore[submat * qstore_dim1 + 1], ldqs, & iwork[indxq + submat], &e[submat + msd2 - 1], &msd2, & work[iq], &iwork[iqptr], &iwork[iprmpt], &iwork[iperm] , &iwork[igivpt], &iwork[igivcl], &work[igivnm], & work[iwrem], &iwork[subpbs + 1], info); } if (*info != 0) { goto L130; } iwork[i__ / 2 + 1] = iwork[i__ + 2]; /* L90: */ } subpbs /= 2; ++curlvl; goto L80; } /* end while Re-merge the eigenvalues/vectors which were deflated at the final merge step. */ if (*icompq == 1) { i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { j = iwork[indxq + i__]; work[i__] = d__[j]; dcopy_(qsiz, &qstore[j * qstore_dim1 + 1], &c__1, &q[i__ * q_dim1 + 1], &c__1); /* L100: */ } dcopy_(n, &work[1], &c__1, &d__[1], &c__1); } else if (*icompq == 2) { i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { j = iwork[indxq + i__]; work[i__] = d__[j]; dcopy_(n, &q[j * q_dim1 + 1], &c__1, &work[*n * i__ + 1], &c__1); /* L110: */ } dcopy_(n, &work[1], &c__1, &d__[1], &c__1); dlacpy_("A", n, n, &work[*n + 1], n, &q[q_offset], ldq); } else { i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { j = iwork[indxq + i__]; work[i__] = d__[j]; /* L120: */ } dcopy_(n, &work[1], &c__1, &d__[1], &c__1); } goto L140; L130: *info = submat * (*n + 1) + submat + matsiz - 1; L140: return 0; /* End of DLAED0 */ } /* dlaed0_ */ /* Subroutine */ int dlaed1_(integer *n, doublereal *d__, doublereal *q, integer *ldq, integer *indxq, doublereal *rho, integer *cutpnt, doublereal *work, integer *iwork, integer *info) { /* System generated locals */ integer q_dim1, q_offset, i__1, i__2; /* Local variables */ static integer i__, k, n1, n2, is, iw, iz, iq2, zpp1, indx, indxc; extern /* Subroutine */ int dcopy_(integer *, doublereal *, integer *, doublereal *, integer *); static integer indxp; extern /* Subroutine */ int dlaed2_(integer *, integer *, integer *, doublereal *, doublereal *, integer *, integer *, doublereal *, doublereal *, doublereal *, doublereal *, doublereal *, integer *, integer *, integer *, integer *, integer *), dlaed3_(integer *, integer *, integer *, doublereal *, doublereal *, integer *, doublereal *, doublereal *, doublereal *, integer *, integer *, doublereal *, doublereal *, integer *); static integer idlmda; extern /* Subroutine */ int dlamrg_(integer *, integer *, doublereal *, integer *, integer *, integer *), xerbla_(char *, integer *); static integer coltyp; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= DLAED1 computes the updated eigensystem of a diagonal matrix after modification by a rank-one symmetric matrix. This routine is used only for the eigenproblem which requires all eigenvalues and eigenvectors of a tridiagonal matrix. DLAED7 handles the case in which eigenvalues only or eigenvalues and eigenvectors of a full symmetric matrix (which was reduced to tridiagonal form) are desired. T = Q(in) ( D(in) + RHO * Z*Z' ) Q'(in) = Q(out) * D(out) * Q'(out) where Z = Q'u, u is a vector of length N with ones in the CUTPNT and CUTPNT + 1 th elements and zeros elsewhere. The eigenvectors of the original matrix are stored in Q, and the eigenvalues are in D. The algorithm consists of three stages: The first stage consists of deflating the size of the problem when there are multiple eigenvalues or if there is a zero in the Z vector. For each such occurence the dimension of the secular equation problem is reduced by one. This stage is performed by the routine DLAED2. The second stage consists of calculating the updated eigenvalues. This is done by finding the roots of the secular equation via the routine DLAED4 (as called by DLAED3). This routine also calculates the eigenvectors of the current problem. The final stage consists of computing the updated eigenvectors directly using the updated eigenvalues. The eigenvectors for the current problem are multiplied with the eigenvectors from the overall problem. Arguments ========= N (input) INTEGER The dimension of the symmetric tridiagonal matrix. N >= 0. D (input/output) DOUBLE PRECISION array, dimension (N) On entry, the eigenvalues of the rank-1-perturbed matrix. On exit, the eigenvalues of the repaired matrix. Q (input/output) DOUBLE PRECISION array, dimension (LDQ,N) On entry, the eigenvectors of the rank-1-perturbed matrix. On exit, the eigenvectors of the repaired tridiagonal matrix. LDQ (input) INTEGER The leading dimension of the array Q. LDQ >= max(1,N). INDXQ (input/output) INTEGER array, dimension (N) On entry, the permutation which separately sorts the two subproblems in D into ascending order. On exit, the permutation which will reintegrate the subproblems back into sorted order, i.e. D( INDXQ( I = 1, N ) ) will be in ascending order. RHO (input) DOUBLE PRECISION The subdiagonal entry used to create the rank-1 modification. CUTPNT (input) INTEGER The location of the last eigenvalue in the leading sub-matrix. min(1,N) <= CUTPNT <= N/2. WORK (workspace) DOUBLE PRECISION array, dimension (4*N + N**2) IWORK (workspace) INTEGER array, dimension (4*N) INFO (output) INTEGER = 0: successful exit. < 0: if INFO = -i, the i-th argument had an illegal value. > 0: if INFO = 1, an eigenvalue did not converge Further Details =============== Based on contributions by Jeff Rutter, Computer Science Division, University of California at Berkeley, USA Modified by Francoise Tisseur, University of Tennessee. ===================================================================== Test the input parameters. */ /* Parameter adjustments */ --d__; q_dim1 = *ldq; q_offset = 1 + q_dim1; q -= q_offset; --indxq; --work; --iwork; /* Function Body */ *info = 0; if (*n < 0) { *info = -1; } else if (*ldq < max(1,*n)) { *info = -4; } else /* if(complicated condition) */ { /* Computing MIN */ i__1 = 1, i__2 = *n / 2; if ((min(i__1,i__2) > *cutpnt) || (*n / 2 < *cutpnt)) { *info = -7; } } if (*info != 0) { i__1 = -(*info); xerbla_("DLAED1", &i__1); return 0; } /* Quick return if possible */ if (*n == 0) { return 0; } /* The following values are integer pointers which indicate the portion of the workspace used by a particular array in DLAED2 and DLAED3. */ iz = 1; idlmda = iz + *n; iw = idlmda + *n; iq2 = iw + *n; indx = 1; indxc = indx + *n; coltyp = indxc + *n; indxp = coltyp + *n; /* Form the z-vector which consists of the last row of Q_1 and the first row of Q_2. */ dcopy_(cutpnt, &q[*cutpnt + q_dim1], ldq, &work[iz], &c__1); zpp1 = *cutpnt + 1; i__1 = *n - *cutpnt; dcopy_(&i__1, &q[zpp1 + zpp1 * q_dim1], ldq, &work[iz + *cutpnt], &c__1); /* Deflate eigenvalues. */ dlaed2_(&k, n, cutpnt, &d__[1], &q[q_offset], ldq, &indxq[1], rho, &work[ iz], &work[idlmda], &work[iw], &work[iq2], &iwork[indx], &iwork[ indxc], &iwork[indxp], &iwork[coltyp], info); if (*info != 0) { goto L20; } /* Solve Secular Equation. */ if (k != 0) { is = (iwork[coltyp] + iwork[coltyp + 1]) * *cutpnt + (iwork[coltyp + 1] + iwork[coltyp + 2]) * (*n - *cutpnt) + iq2; dlaed3_(&k, n, cutpnt, &d__[1], &q[q_offset], ldq, rho, &work[idlmda], &work[iq2], &iwork[indxc], &iwork[coltyp], &work[iw], &work[ is], info); if (*info != 0) { goto L20; } /* Prepare the INDXQ sorting permutation. */ n1 = k; n2 = *n - k; dlamrg_(&n1, &n2, &d__[1], &c__1, &c_n1, &indxq[1]); } else { i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { indxq[i__] = i__; /* L10: */ } } L20: return 0; /* End of DLAED1 */ } /* dlaed1_ */ /* Subroutine */ int dlaed2_(integer *k, integer *n, integer *n1, doublereal * d__, doublereal *q, integer *ldq, integer *indxq, doublereal *rho, doublereal *z__, doublereal *dlamda, doublereal *w, doublereal *q2, integer *indx, integer *indxc, integer *indxp, integer *coltyp, integer *info) { /* System generated locals */ integer q_dim1, q_offset, i__1, i__2; doublereal d__1, d__2, d__3, d__4; /* Builtin functions */ double sqrt(doublereal); /* Local variables */ static doublereal c__; static integer i__, j; static doublereal s, t; static integer k2, n2, ct, nj, pj, js, iq1, iq2, n1p1; static doublereal eps, tau, tol; static integer psm[4], imax, jmax; extern /* Subroutine */ int drot_(integer *, doublereal *, integer *, doublereal *, integer *, doublereal *, doublereal *); static integer ctot[4]; extern /* Subroutine */ int dscal_(integer *, doublereal *, doublereal *, integer *), dcopy_(integer *, doublereal *, integer *, doublereal *, integer *); extern integer idamax_(integer *, doublereal *, integer *); extern /* Subroutine */ int dlamrg_(integer *, integer *, doublereal *, integer *, integer *, integer *), dlacpy_(char *, integer *, integer *, doublereal *, integer *, doublereal *, integer *), xerbla_(char *, integer *); /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University October 31, 1999 Purpose ======= DLAED2 merges the two sets of eigenvalues together into a single sorted set. Then it tries to deflate the size of the problem. There are two ways in which deflation can occur: when two or more eigenvalues are close together or if there is a tiny entry in the Z vector. For each such occurrence the order of the related secular equation problem is reduced by one. Arguments ========= K (output) INTEGER The number of non-deflated eigenvalues, and the order of the related secular equation. 0 <= K <=N. N (input) INTEGER The dimension of the symmetric tridiagonal matrix. N >= 0. N1 (input) INTEGER The location of the last eigenvalue in the leading sub-matrix. min(1,N) <= N1 <= N/2. D (input/output) DOUBLE PRECISION array, dimension (N) On entry, D contains the eigenvalues of the two submatrices to be combined. On exit, D contains the trailing (N-K) updated eigenvalues (those which were deflated) sorted into increasing order. Q (input/output) DOUBLE PRECISION array, dimension (LDQ, N) On entry, Q contains the eigenvectors of two submatrices in the two square blocks with corners at (1,1), (N1,N1) and (N1+1, N1+1), (N,N). On exit, Q contains the trailing (N-K) updated eigenvectors (those which were deflated) in its last N-K columns. LDQ (input) INTEGER The leading dimension of the array Q. LDQ >= max(1,N). INDXQ (input/output) INTEGER array, dimension (N) The permutation which separately sorts the two sub-problems in D into ascending order. Note that elements in the second half of this permutation must first have N1 added to their values. Destroyed on exit. RHO (input/output) DOUBLE PRECISION On entry, the off-diagonal element associated with the rank-1 cut which originally split the two submatrices which are now being recombined. On exit, RHO has been modified to the value required by DLAED3. Z (input) DOUBLE PRECISION array, dimension (N) On entry, Z contains the updating vector (the last row of the first sub-eigenvector matrix and the first row of the second sub-eigenvector matrix). On exit, the contents of Z have been destroyed by the updating process. DLAMDA (output) DOUBLE PRECISION array, dimension (N) A copy of the first K eigenvalues which will be used by DLAED3 to form the secular equation. W (output) DOUBLE PRECISION array, dimension (N) The first k values of the final deflation-altered z-vector which will be passed to DLAED3. Q2 (output) DOUBLE PRECISION array, dimension (N1**2+(N-N1)**2) A copy of the first K eigenvectors which will be used by DLAED3 in a matrix multiply (DGEMM) to solve for the new eigenvectors. INDX (workspace) INTEGER array, dimension (N) The permutation used to sort the contents of DLAMDA into ascending order. INDXC (output) INTEGER array, dimension (N) The permutation used to arrange the columns of the deflated Q matrix into three groups: the first group contains non-zero elements only at and above N1, the second contains non-zero elements only below N1, and the third is dense. INDXP (workspace) INTEGER array, dimension (N) The permutation used to place deflated values of D at the end of the array. INDXP(1:K) points to the nondeflated D-values and INDXP(K+1:N) points to the deflated eigenvalues. COLTYP (workspace/output) INTEGER array, dimension (N) During execution, a label which will indicate which of the following types a column in the Q2 matrix is: 1 : non-zero in the upper half only; 2 : dense; 3 : non-zero in the lower half only; 4 : deflated. On exit, COLTYP(i) is the number of columns of type i, for i=1 to 4 only. INFO (output) INTEGER = 0: successful exit. < 0: if INFO = -i, the i-th argument had an illegal value. Further Details =============== Based on contributions by Jeff Rutter, Computer Science Division, University of California at Berkeley, USA Modified by Francoise Tisseur, University of Tennessee. ===================================================================== Test the input parameters. */ /* Parameter adjustments */ --d__; q_dim1 = *ldq; q_offset = 1 + q_dim1; q -= q_offset; --indxq; --z__; --dlamda; --w; --q2; --indx; --indxc; --indxp; --coltyp; /* Function Body */ *info = 0; if (*n < 0) { *info = -2; } else if (*ldq < max(1,*n)) { *info = -6; } else /* if(complicated condition) */ { /* Computing MIN */ i__1 = 1, i__2 = *n / 2; if ((min(i__1,i__2) > *n1) || (*n / 2 < *n1)) { *info = -3; } } if (*info != 0) { i__1 = -(*info); xerbla_("DLAED2", &i__1); return 0; } /* Quick return if possible */ if (*n == 0) { return 0; } n2 = *n - *n1; n1p1 = *n1 + 1; if (*rho < 0.) { dscal_(&n2, &c_b3001, &z__[n1p1], &c__1); } /* Normalize z so that norm(z) = 1. Since z is the concatenation of two normalized vectors, norm2(z) = sqrt(2). */ t = 1. / sqrt(2.); dscal_(n, &t, &z__[1], &c__1); /* RHO = ABS( norm(z)**2 * RHO ) */ *rho = (d__1 = *rho * 2., abs(d__1)); /* Sort the eigenvalues into increasing order */ i__1 = *n; for (i__ = n1p1; i__ <= i__1; ++i__) { indxq[i__] += *n1; /* L10: */ } /* re-integrate the deflated parts from the last pass */ i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { dlamda[i__] = d__[indxq[i__]]; /* L20: */ } dlamrg_(n1, &n2, &dlamda[1], &c__1, &c__1, &indxc[1]); i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { indx[i__] = indxq[indxc[i__]]; /* L30: */ } /* Calculate the allowable deflation tolerance */ imax = idamax_(n, &z__[1], &c__1); jmax = idamax_(n, &d__[1], &c__1); eps = EPSILON; /* Computing MAX */ d__3 = (d__1 = d__[jmax], abs(d__1)), d__4 = (d__2 = z__[imax], abs(d__2)) ; tol = eps * 8. * max(d__3,d__4); /* If the rank-1 modifier is small enough, no more needs to be done except to reorganize Q so that its columns correspond with the elements in D. */ if (*rho * (d__1 = z__[imax], abs(d__1)) <= tol) { *k = 0; iq2 = 1; i__1 = *n; for (j = 1; j <= i__1; ++j) { i__ = indx[j]; dcopy_(n, &q[i__ * q_dim1 + 1], &c__1, &q2[iq2], &c__1); dlamda[j] = d__[i__]; iq2 += *n; /* L40: */ } dlacpy_("A", n, n, &q2[1], n, &q[q_offset], ldq); dcopy_(n, &dlamda[1], &c__1, &d__[1], &c__1); goto L190; } /* If there are multiple eigenvalues then the problem deflates. Here the number of equal eigenvalues are found. As each equal eigenvalue is found, an elementary reflector is computed to rotate the corresponding eigensubspace so that the corresponding components of Z are zero in this new basis. */ i__1 = *n1; for (i__ = 1; i__ <= i__1; ++i__) { coltyp[i__] = 1; /* L50: */ } i__1 = *n; for (i__ = n1p1; i__ <= i__1; ++i__) { coltyp[i__] = 3; /* L60: */ } *k = 0; k2 = *n + 1; i__1 = *n; for (j = 1; j <= i__1; ++j) { nj = indx[j]; if (*rho * (d__1 = z__[nj], abs(d__1)) <= tol) { /* Deflate due to small z component. */ --k2; coltyp[nj] = 4; indxp[k2] = nj; if (j == *n) { goto L100; } } else { pj = nj; goto L80; } /* L70: */ } L80: ++j; nj = indx[j]; if (j > *n) { goto L100; } if (*rho * (d__1 = z__[nj], abs(d__1)) <= tol) { /* Deflate due to small z component. */ --k2; coltyp[nj] = 4; indxp[k2] = nj; } else { /* Check if eigenvalues are close enough to allow deflation. */ s = z__[pj]; c__ = z__[nj]; /* Find sqrt(a**2+b**2) without overflow or destructive underflow. */ tau = dlapy2_(&c__, &s); t = d__[nj] - d__[pj]; c__ /= tau; s = -s / tau; if ((d__1 = t * c__ * s, abs(d__1)) <= tol) { /* Deflation is possible. */ z__[nj] = tau; z__[pj] = 0.; if (coltyp[nj] != coltyp[pj]) { coltyp[nj] = 2; } coltyp[pj] = 4; drot_(n, &q[pj * q_dim1 + 1], &c__1, &q[nj * q_dim1 + 1], &c__1, & c__, &s); /* Computing 2nd power */ d__1 = c__; /* Computing 2nd power */ d__2 = s; t = d__[pj] * (d__1 * d__1) + d__[nj] * (d__2 * d__2); /* Computing 2nd power */ d__1 = s; /* Computing 2nd power */ d__2 = c__; d__[nj] = d__[pj] * (d__1 * d__1) + d__[nj] * (d__2 * d__2); d__[pj] = t; --k2; i__ = 1; L90: if (k2 + i__ <= *n) { if (d__[pj] < d__[indxp[k2 + i__]]) { indxp[k2 + i__ - 1] = indxp[k2 + i__]; indxp[k2 + i__] = pj; ++i__; goto L90; } else { indxp[k2 + i__ - 1] = pj; } } else { indxp[k2 + i__ - 1] = pj; } pj = nj; } else { ++(*k); dlamda[*k] = d__[pj]; w[*k] = z__[pj]; indxp[*k] = pj; pj = nj; } } goto L80; L100: /* Record the last eigenvalue. */ ++(*k); dlamda[*k] = d__[pj]; w[*k] = z__[pj]; indxp[*k] = pj; /* Count up the total number of the various types of columns, then form a permutation which positions the four column types into four uniform groups (although one or more of these groups may be empty). */ for (j = 1; j <= 4; ++j) { ctot[j - 1] = 0; /* L110: */ } i__1 = *n; for (j = 1; j <= i__1; ++j) { ct = coltyp[j]; ++ctot[ct - 1]; /* L120: */ } /* PSM(*) = Position in SubMatrix (of types 1 through 4) */ psm[0] = 1; psm[1] = ctot[0] + 1; psm[2] = psm[1] + ctot[1]; psm[3] = psm[2] + ctot[2]; *k = *n - ctot[3]; /* Fill out the INDXC array so that the permutation which it induces will place all type-1 columns first, all type-2 columns next, then all type-3's, and finally all type-4's. */ i__1 = *n; for (j = 1; j <= i__1; ++j) { js = indxp[j]; ct = coltyp[js]; indx[psm[ct - 1]] = js; indxc[psm[ct - 1]] = j; ++psm[ct - 1]; /* L130: */ } /* Sort the eigenvalues and corresponding eigenvectors into DLAMDA and Q2 respectively. The eigenvalues/vectors which were not deflated go into the first K slots of DLAMDA and Q2 respectively, while those which were deflated go into the last N - K slots. */ i__ = 1; iq1 = 1; iq2 = (ctot[0] + ctot[1]) * *n1 + 1; i__1 = ctot[0]; for (j = 1; j <= i__1; ++j) { js = indx[i__]; dcopy_(n1, &q[js * q_dim1 + 1], &c__1, &q2[iq1], &c__1); z__[i__] = d__[js]; ++i__; iq1 += *n1; /* L140: */ } i__1 = ctot[1]; for (j = 1; j <= i__1; ++j) { js = indx[i__]; dcopy_(n1, &q[js * q_dim1 + 1], &c__1, &q2[iq1], &c__1); dcopy_(&n2, &q[*n1 + 1 + js * q_dim1], &c__1, &q2[iq2], &c__1); z__[i__] = d__[js]; ++i__; iq1 += *n1; iq2 += n2; /* L150: */ } i__1 = ctot[2]; for (j = 1; j <= i__1; ++j) { js = indx[i__]; dcopy_(&n2, &q[*n1 + 1 + js * q_dim1], &c__1, &q2[iq2], &c__1); z__[i__] = d__[js]; ++i__; iq2 += n2; /* L160: */ } iq1 = iq2; i__1 = ctot[3]; for (j = 1; j <= i__1; ++j) { js = indx[i__]; dcopy_(n, &q[js * q_dim1 + 1], &c__1, &q2[iq2], &c__1); iq2 += *n; z__[i__] = d__[js]; ++i__; /* L170: */ } /* The deflated eigenvalues and their corresponding vectors go back into the last N - K slots of D and Q respectively. */ dlacpy_("A", n, &ctot[3], &q2[iq1], n, &q[(*k + 1) * q_dim1 + 1], ldq); i__1 = *n - *k; dcopy_(&i__1, &z__[*k + 1], &c__1, &d__[*k + 1], &c__1); /* Copy CTOT into COLTYP for referencing in DLAED3. */ for (j = 1; j <= 4; ++j) { coltyp[j] = ctot[j - 1]; /* L180: */ } L190: return 0; /* End of DLAED2 */ } /* dlaed2_ */ /* Subroutine */ int dlaed3_(integer *k, integer *n, integer *n1, doublereal * d__, doublereal *q, integer *ldq, doublereal *rho, doublereal *dlamda, doublereal *q2, integer *indx, integer *ctot, doublereal *w, doublereal *s, integer *info) { /* System generated locals */ integer q_dim1, q_offset, i__1, i__2; doublereal d__1; /* Builtin functions */ double sqrt(doublereal), d_sign(doublereal *, doublereal *); /* Local variables */ static integer i__, j, n2, n12, ii, n23, iq2; static doublereal temp; extern doublereal dnrm2_(integer *, doublereal *, integer *); extern /* Subroutine */ int dgemm_(char *, char *, integer *, integer *, integer *, doublereal *, doublereal *, integer *, doublereal *, integer *, doublereal *, doublereal *, integer *), dcopy_(integer *, doublereal *, integer *, doublereal *, integer *), dlaed4_(integer *, integer *, doublereal *, doublereal *, doublereal *, doublereal *, doublereal *, integer *); extern doublereal dlamc3_(doublereal *, doublereal *); extern /* Subroutine */ int dlacpy_(char *, integer *, integer *, doublereal *, integer *, doublereal *, integer *), dlaset_(char *, integer *, integer *, doublereal *, doublereal *, doublereal *, integer *), xerbla_(char *, integer *); /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Oak Ridge National Lab, Argonne National Lab, Courant Institute, NAG Ltd., and Rice University June 30, 1999 Purpose ======= DLAED3 finds the roots of the secular equation, as defined by the values in D, W, and RHO, between 1 and K. It makes the appropriate calls to DLAED4 and then updates the eigenvectors by multiplying the matrix of eigenvectors of the pair of eigensystems being combined by the matrix of eigenvectors of the K-by-K system which is solved here. This code makes very mild assumptions about floating point arithmetic. It will work on machines with a guard digit in add/subtract, or on those binary machines without guard digits which subtract like the Cray X-MP, Cray Y-MP, Cray C-90, or Cray-2. It could conceivably fail on hexadecimal or decimal machines without guard digits, but we know of none. Arguments ========= K (input) INTEGER The number of terms in the rational function to be solved by DLAED4. K >= 0. N (input) INTEGER The number of rows and columns in the Q matrix. N >= K (deflation may result in N>K). N1 (input) INTEGER The location of the last eigenvalue in the leading submatrix. min(1,N) <= N1 <= N/2. D (output) DOUBLE PRECISION array, dimension (N) D(I) contains the updated eigenvalues for 1 <= I <= K. Q (output) DOUBLE PRECISION array, dimension (LDQ,N) Initially the first K columns are used as workspace. On output the columns 1 to K contain the updated eigenvectors. LDQ (input) INTEGER The leading dimension of the array Q. LDQ >= max(1,N). RHO (input) DOUBLE PRECISION The value of the parameter in the rank one update equation. RHO >= 0 required. DLAMDA (input/output) DOUBLE PRECISION array, dimension (K) The first K elements of this array contain the old roots of the deflated updating problem. These are the poles of the secular equation. May be changed on output by having lowest order bit set to zero on Cray X-MP, Cray Y-MP, Cray-2, or Cray C-90, as described above. Q2 (input) DOUBLE PRECISION array, dimension (LDQ2, N) The first K columns of this matrix contain the non-deflated eigenvectors for the split problem. INDX (input) INTEGER array, dimension (N) The permutation used to arrange the columns of the deflated Q matrix into three groups (see DLAED2). The rows of the eigenvectors found by DLAED4 must be likewise permuted before the matrix multiply can take place. CTOT (input) INTEGER array, dimension (4) A count of the total number of the various types of columns in Q, as described in INDX. The fourth column type is any column which has been deflated. W (input/output) DOUBLE PRECISION array, dimension (K) The first K elements of this array contain the components of the deflation-adjusted updating vector. Destroyed on output. S (workspace) DOUBLE PRECISION array, dimension (N1 + 1)*K Will contain the eigenvectors of the repaired matrix which will be multiplied by the previously accumulated eigenvectors to update the system. LDS (input) INTEGER The leading dimension of S. LDS >= max(1,K). INFO (output) INTEGER = 0: successful exit. < 0: if INFO = -i, the i-th argument had an illegal value. > 0: if INFO = 1, an eigenvalue did not converge Further Details =============== Based on contributions by Jeff Rutter, Computer Science Division, University of California at Berkeley, USA Modified by Francoise Tisseur, University of Tennessee. ===================================================================== Test the input parameters. */ /* Parameter adjustments */ --d__; q_dim1 = *ldq; q_offset = 1 + q_dim1; q -= q_offset; --dlamda; --q2; --indx; --ctot; --w; --s; /* Function Body */ *info = 0; if (*k < 0) { *info = -1; } else if (*n < *k) { *info = -2; } else if (*ldq < max(1,*n)) { *info = -6; } if (*info != 0) { i__1 = -(*info); xerbla_("DLAED3", &i__1); return 0; } /* Quick return if possible */ if (*k == 0) { return 0; } /* Modify values DLAMDA(i) to make sure all DLAMDA(i)-DLAMDA(j) can be computed with high relative accuracy (barring over/underflow). This is a problem on machines without a guard digit in add/subtract (Cray XMP, Cray YMP, Cray C 90 and Cray 2). The following code replaces DLAMDA(I) by 2*DLAMDA(I)-DLAMDA(I), which on any of these machines zeros out the bottommost bit of DLAMDA(I) if it is 1; this makes the subsequent subtractions DLAMDA(I)-DLAMDA(J) unproblematic when cancellation occurs. On binary machines with a guard digit (almost all machines) it does not change DLAMDA(I) at all. On hexadecimal and decimal machines with a guard digit, it slightly changes the bottommost bits of DLAMDA(I). It does not account for hexadecimal or decimal machines without guard digits (we know of none). We use a subroutine call to compute 2*DLAMBDA(I) to prevent optimizing compilers from eliminating this code. */ i__1 = *k; for (i__ = 1; i__ <= i__1; ++i__) { dlamda[i__] = dlamc3_(&dlamda[i__], &dlamda[i__]) - dlamda[i__]; /* L10: */ } i__1 = *k; for (j = 1; j <= i__1; ++j) { dlaed4_(k, &j, &dlamda[1], &w[1], &q[j * q_dim1 + 1], rho, &d__[j], info); /* If the zero finder fails, the computation is terminated. */ if (*info != 0) { goto L120; } /* L20: */ } if (*k == 1) { goto L110; } if (*k == 2) { i__1 = *k; for (j = 1; j <= i__1; ++j) { w[1] = q[j * q_dim1 + 1]; w[2] = q[j * q_dim1 + 2]; ii = indx[1]; q[j * q_dim1 + 1] = w[ii]; ii = indx[2]; q[j * q_dim1 + 2] = w[ii]; /* L30: */ } goto L110; } /* Compute updated W. */ dcopy_(k, &w[1], &c__1, &s[1], &c__1); /* Initialize W(I) = Q(I,I) */ i__1 = *ldq + 1; dcopy_(k, &q[q_offset], &i__1, &w[1], &c__1); i__1 = *k; for (j = 1; j <= i__1; ++j) { i__2 = j - 1; for (i__ = 1; i__ <= i__2; ++i__) { w[i__] *= q[i__ + j * q_dim1] / (dlamda[i__] - dlamda[j]); /* L40: */ } i__2 = *k; for (i__ = j + 1; i__ <= i__2; ++i__) { w[i__] *= q[i__ + j * q_dim1] / (dlamda[i__] - dlamda[j]); /* L50: */ } /* L60: */ } i__1 = *k; for (i__ = 1; i__ <= i__1; ++i__) { d__1 = sqrt(-w[i__]); w[i__] = d_sign(&d__1, &s[i__]); /* L70: */ } /* Compute eigenvectors of the modified rank-1 modification. */ i__1 = *k; for (j = 1; j <= i__1; ++j) { i__2 = *k; for (i__ = 1; i__ <= i__2; ++i__) { s[i__] = w[i__] / q[i__ + j * q_dim1]; /* L80: */ } temp = dnrm2_(k, &s[1], &c__1); i__2 = *k; for (i__ = 1; i__ <= i__2; ++i__) { ii = indx[i__]; q[i__ + j * q_dim1] = s[ii] / temp; /* L90: */ } /* L100: */ } /* Compute the updated eigenvectors. */ L110: n2 = *n - *n1; n12 = ctot[1] + ctot[2]; n23 = ctot[2] + ctot[3]; dlacpy_("A", &n23, k, &q[ctot[1] + 1 + q_dim1], ldq, &s[1], &n23); iq2 = *n1 * n12 + 1; if (n23 != 0) { dgemm_("N", "N", &n2, k, &n23, &c_b2865, &q2[iq2], &n2, &s[1], &n23, & c_b2879, &q[*n1 + 1 + q_dim1], ldq); } else { dlaset_("A", &n2, k, &c_b2879, &c_b2879, &q[*n1 + 1 + q_dim1], ldq); } dlacpy_("A", &n12, k, &q[q_offset], ldq, &s[1], &n12); if (n12 != 0) { dgemm_("N", "N", n1, k, &n12, &c_b2865, &q2[1], n1, &s[1], &n12, & c_b2879, &q[q_offset], ldq); } else { dlaset_("A", n1, k, &c_b2879, &c_b2879, &q[q_dim1 + 1], ldq); } L120: return 0; /* End of DLAED3 */ } /* dlaed3_ */ /* Subroutine */ int dlaed4_(integer *n, integer *i__, doublereal *d__, doublereal *z__, doublereal *delta, doublereal *rho, doublereal *dlam, integer *info) { /* System generated locals */ integer i__1; doublereal d__1; /* Builtin functions */ double sqrt(doublereal); /* Local variables */ static doublereal a, b, c__; static integer j; static doublereal w; static integer ii; static doublereal dw, zz[3]; static integer ip1; static doublereal del, eta, phi, eps, tau, psi; static integer iim1, iip1; static doublereal dphi, dpsi; static integer iter; static doublereal temp, prew, temp1, dltlb, dltub, midpt; static integer niter; static logical swtch; extern /* Subroutine */ int dlaed5_(integer *, doublereal *, doublereal *, doublereal *, doublereal *, doublereal *), dlaed6_(integer *, logical *, doublereal *, doublereal *, doublereal *, doublereal *, doublereal *, integer *); static logical swtch3; static logical orgati; static doublereal erretm, rhoinv; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Oak Ridge National Lab, Argonne National Lab, Courant Institute, NAG Ltd., and Rice University December 23, 1999 Purpose ======= This subroutine computes the I-th updated eigenvalue of a symmetric rank-one modification to a diagonal matrix whose elements are given in the array d, and that D(i) < D(j) for i < j and that RHO > 0. This is arranged by the calling routine, and is no loss in generality. The rank-one modified system is thus diag( D ) + RHO * Z * Z_transpose. where we assume the Euclidean norm of Z is 1. The method consists of approximating the rational functions in the secular equation by simpler interpolating rational functions. Arguments ========= N (input) INTEGER The length of all arrays. I (input) INTEGER The index of the eigenvalue to be computed. 1 <= I <= N. D (input) DOUBLE PRECISION array, dimension (N) The original eigenvalues. It is assumed that they are in order, D(I) < D(J) for I < J. Z (input) DOUBLE PRECISION array, dimension (N) The components of the updating vector. DELTA (output) DOUBLE PRECISION array, dimension (N) If N .ne. 1, DELTA contains (D(j) - lambda_I) in its j-th component. If N = 1, then DELTA(1) = 1. The vector DELTA contains the information necessary to construct the eigenvectors. RHO (input) DOUBLE PRECISION The scalar in the symmetric updating formula. DLAM (output) DOUBLE PRECISION The computed lambda_I, the I-th updated eigenvalue. INFO (output) INTEGER = 0: successful exit > 0: if INFO = 1, the updating process failed. Internal Parameters =================== Logical variable ORGATI (origin-at-i?) is used for distinguishing whether D(i) or D(i+1) is treated as the origin. ORGATI = .true. origin at i ORGATI = .false. origin at i+1 Logical variable SWTCH3 (switch-for-3-poles?) is for noting if we are working with THREE poles! MAXIT is the maximum number of iterations allowed for each eigenvalue. Further Details =============== Based on contributions by Ren-Cang Li, Computer Science Division, University of California at Berkeley, USA ===================================================================== Since this routine is called in an inner loop, we do no argument checking. Quick return for N=1 and 2. */ /* Parameter adjustments */ --delta; --z__; --d__; /* Function Body */ *info = 0; if (*n == 1) { /* Presumably, I=1 upon entry */ *dlam = d__[1] + *rho * z__[1] * z__[1]; delta[1] = 1.; return 0; } if (*n == 2) { dlaed5_(i__, &d__[1], &z__[1], &delta[1], rho, dlam); return 0; } /* Compute machine epsilon */ eps = EPSILON; rhoinv = 1. / *rho; /* The case I = N */ if (*i__ == *n) { /* Initialize some basic variables */ ii = *n - 1; niter = 1; /* Calculate initial guess */ midpt = *rho / 2.; /* If ||Z||_2 is not one, then TEMP should be set to RHO * ||Z||_2^2 / TWO */ i__1 = *n; for (j = 1; j <= i__1; ++j) { delta[j] = d__[j] - d__[*i__] - midpt; /* L10: */ } psi = 0.; i__1 = *n - 2; for (j = 1; j <= i__1; ++j) { psi += z__[j] * z__[j] / delta[j]; /* L20: */ } c__ = rhoinv + psi; w = c__ + z__[ii] * z__[ii] / delta[ii] + z__[*n] * z__[*n] / delta[* n]; if (w <= 0.) { temp = z__[*n - 1] * z__[*n - 1] / (d__[*n] - d__[*n - 1] + *rho) + z__[*n] * z__[*n] / *rho; if (c__ <= temp) { tau = *rho; } else { del = d__[*n] - d__[*n - 1]; a = -c__ * del + z__[*n - 1] * z__[*n - 1] + z__[*n] * z__[*n] ; b = z__[*n] * z__[*n] * del; if (a < 0.) { tau = b * 2. / (sqrt(a * a + b * 4. * c__) - a); } else { tau = (a + sqrt(a * a + b * 4. * c__)) / (c__ * 2.); } } /* It can be proved that D(N)+RHO/2 <= LAMBDA(N) < D(N)+TAU <= D(N)+RHO */ dltlb = midpt; dltub = *rho; } else { del = d__[*n] - d__[*n - 1]; a = -c__ * del + z__[*n - 1] * z__[*n - 1] + z__[*n] * z__[*n]; b = z__[*n] * z__[*n] * del; if (a < 0.) { tau = b * 2. / (sqrt(a * a + b * 4. * c__) - a); } else { tau = (a + sqrt(a * a + b * 4. * c__)) / (c__ * 2.); } /* It can be proved that D(N) < D(N)+TAU < LAMBDA(N) < D(N)+RHO/2 */ dltlb = 0.; dltub = midpt; } i__1 = *n; for (j = 1; j <= i__1; ++j) { delta[j] = d__[j] - d__[*i__] - tau; /* L30: */ } /* Evaluate PSI and the derivative DPSI */ dpsi = 0.; psi = 0.; erretm = 0.; i__1 = ii; for (j = 1; j <= i__1; ++j) { temp = z__[j] / delta[j]; psi += z__[j] * temp; dpsi += temp * temp; erretm += psi; /* L40: */ } erretm = abs(erretm); /* Evaluate PHI and the derivative DPHI */ temp = z__[*n] / delta[*n]; phi = z__[*n] * temp; dphi = temp * temp; erretm = (-phi - psi) * 8. + erretm - phi + rhoinv + abs(tau) * (dpsi + dphi); w = rhoinv + phi + psi; /* Test for convergence */ if (abs(w) <= eps * erretm) { *dlam = d__[*i__] + tau; goto L250; } if (w <= 0.) { dltlb = max(dltlb,tau); } else { dltub = min(dltub,tau); } /* Calculate the new step */ ++niter; c__ = w - delta[*n - 1] * dpsi - delta[*n] * dphi; a = (delta[*n - 1] + delta[*n]) * w - delta[*n - 1] * delta[*n] * ( dpsi + dphi); b = delta[*n - 1] * delta[*n] * w; if (c__ < 0.) { c__ = abs(c__); } if (c__ == 0.) { /* ETA = B/A ETA = RHO - TAU */ eta = dltub - tau; } else if (a >= 0.) { eta = (a + sqrt((d__1 = a * a - b * 4. * c__, abs(d__1)))) / (c__ * 2.); } else { eta = b * 2. / (a - sqrt((d__1 = a * a - b * 4. * c__, abs(d__1))) ); } /* Note, eta should be positive if w is negative, and eta should be negative otherwise. However, if for some reason caused by roundoff, eta*w > 0, we simply use one Newton step instead. This way will guarantee eta*w < 0. */ if (w * eta > 0.) { eta = -w / (dpsi + dphi); } temp = tau + eta; if ((temp > dltub) || (temp < dltlb)) { if (w < 0.) { eta = (dltub - tau) / 2.; } else { eta = (dltlb - tau) / 2.; } } i__1 = *n; for (j = 1; j <= i__1; ++j) { delta[j] -= eta; /* L50: */ } tau += eta; /* Evaluate PSI and the derivative DPSI */ dpsi = 0.; psi = 0.; erretm = 0.; i__1 = ii; for (j = 1; j <= i__1; ++j) { temp = z__[j] / delta[j]; psi += z__[j] * temp; dpsi += temp * temp; erretm += psi; /* L60: */ } erretm = abs(erretm); /* Evaluate PHI and the derivative DPHI */ temp = z__[*n] / delta[*n]; phi = z__[*n] * temp; dphi = temp * temp; erretm = (-phi - psi) * 8. + erretm - phi + rhoinv + abs(tau) * (dpsi + dphi); w = rhoinv + phi + psi; /* Main loop to update the values of the array DELTA */ iter = niter + 1; for (niter = iter; niter <= 30; ++niter) { /* Test for convergence */ if (abs(w) <= eps * erretm) { *dlam = d__[*i__] + tau; goto L250; } if (w <= 0.) { dltlb = max(dltlb,tau); } else { dltub = min(dltub,tau); } /* Calculate the new step */ c__ = w - delta[*n - 1] * dpsi - delta[*n] * dphi; a = (delta[*n - 1] + delta[*n]) * w - delta[*n - 1] * delta[*n] * (dpsi + dphi); b = delta[*n - 1] * delta[*n] * w; if (a >= 0.) { eta = (a + sqrt((d__1 = a * a - b * 4. * c__, abs(d__1)))) / ( c__ * 2.); } else { eta = b * 2. / (a - sqrt((d__1 = a * a - b * 4. * c__, abs( d__1)))); } /* Note, eta should be positive if w is negative, and eta should be negative otherwise. However, if for some reason caused by roundoff, eta*w > 0, we simply use one Newton step instead. This way will guarantee eta*w < 0. */ if (w * eta > 0.) { eta = -w / (dpsi + dphi); } temp = tau + eta; if ((temp > dltub) || (temp < dltlb)) { if (w < 0.) { eta = (dltub - tau) / 2.; } else { eta = (dltlb - tau) / 2.; } } i__1 = *n; for (j = 1; j <= i__1; ++j) { delta[j] -= eta; /* L70: */ } tau += eta; /* Evaluate PSI and the derivative DPSI */ dpsi = 0.; psi = 0.; erretm = 0.; i__1 = ii; for (j = 1; j <= i__1; ++j) { temp = z__[j] / delta[j]; psi += z__[j] * temp; dpsi += temp * temp; erretm += psi; /* L80: */ } erretm = abs(erretm); /* Evaluate PHI and the derivative DPHI */ temp = z__[*n] / delta[*n]; phi = z__[*n] * temp; dphi = temp * temp; erretm = (-phi - psi) * 8. + erretm - phi + rhoinv + abs(tau) * ( dpsi + dphi); w = rhoinv + phi + psi; /* L90: */ } /* Return with INFO = 1, NITER = MAXIT and not converged */ *info = 1; *dlam = d__[*i__] + tau; goto L250; /* End for the case I = N */ } else { /* The case for I < N */ niter = 1; ip1 = *i__ + 1; /* Calculate initial guess */ del = d__[ip1] - d__[*i__]; midpt = del / 2.; i__1 = *n; for (j = 1; j <= i__1; ++j) { delta[j] = d__[j] - d__[*i__] - midpt; /* L100: */ } psi = 0.; i__1 = *i__ - 1; for (j = 1; j <= i__1; ++j) { psi += z__[j] * z__[j] / delta[j]; /* L110: */ } phi = 0.; i__1 = *i__ + 2; for (j = *n; j >= i__1; --j) { phi += z__[j] * z__[j] / delta[j]; /* L120: */ } c__ = rhoinv + psi + phi; w = c__ + z__[*i__] * z__[*i__] / delta[*i__] + z__[ip1] * z__[ip1] / delta[ip1]; if (w > 0.) { /* d(i)< the ith eigenvalue < (d(i)+d(i+1))/2 We choose d(i) as origin. */ orgati = TRUE_; a = c__ * del + z__[*i__] * z__[*i__] + z__[ip1] * z__[ip1]; b = z__[*i__] * z__[*i__] * del; if (a > 0.) { tau = b * 2. / (a + sqrt((d__1 = a * a - b * 4. * c__, abs( d__1)))); } else { tau = (a - sqrt((d__1 = a * a - b * 4. * c__, abs(d__1)))) / ( c__ * 2.); } dltlb = 0.; dltub = midpt; } else { /* (d(i)+d(i+1))/2 <= the ith eigenvalue < d(i+1) We choose d(i+1) as origin. */ orgati = FALSE_; a = c__ * del - z__[*i__] * z__[*i__] - z__[ip1] * z__[ip1]; b = z__[ip1] * z__[ip1] * del; if (a < 0.) { tau = b * 2. / (a - sqrt((d__1 = a * a + b * 4. * c__, abs( d__1)))); } else { tau = -(a + sqrt((d__1 = a * a + b * 4. * c__, abs(d__1)))) / (c__ * 2.); } dltlb = -midpt; dltub = 0.; } if (orgati) { i__1 = *n; for (j = 1; j <= i__1; ++j) { delta[j] = d__[j] - d__[*i__] - tau; /* L130: */ } } else { i__1 = *n; for (j = 1; j <= i__1; ++j) { delta[j] = d__[j] - d__[ip1] - tau; /* L140: */ } } if (orgati) { ii = *i__; } else { ii = *i__ + 1; } iim1 = ii - 1; iip1 = ii + 1; /* Evaluate PSI and the derivative DPSI */ dpsi = 0.; psi = 0.; erretm = 0.; i__1 = iim1; for (j = 1; j <= i__1; ++j) { temp = z__[j] / delta[j]; psi += z__[j] * temp; dpsi += temp * temp; erretm += psi; /* L150: */ } erretm = abs(erretm); /* Evaluate PHI and the derivative DPHI */ dphi = 0.; phi = 0.; i__1 = iip1; for (j = *n; j >= i__1; --j) { temp = z__[j] / delta[j]; phi += z__[j] * temp; dphi += temp * temp; erretm += phi; /* L160: */ } w = rhoinv + phi + psi; /* W is the value of the secular function with its ii-th element removed. */ swtch3 = FALSE_; if (orgati) { if (w < 0.) { swtch3 = TRUE_; } } else { if (w > 0.) { swtch3 = TRUE_; } } if ((ii == 1) || (ii == *n)) { swtch3 = FALSE_; } temp = z__[ii] / delta[ii]; dw = dpsi + dphi + temp * temp; temp = z__[ii] * temp; w += temp; erretm = (phi - psi) * 8. + erretm + rhoinv * 2. + abs(temp) * 3. + abs(tau) * dw; /* Test for convergence */ if (abs(w) <= eps * erretm) { if (orgati) { *dlam = d__[*i__] + tau; } else { *dlam = d__[ip1] + tau; } goto L250; } if (w <= 0.) { dltlb = max(dltlb,tau); } else { dltub = min(dltub,tau); } /* Calculate the new step */ ++niter; if (! swtch3) { if (orgati) { /* Computing 2nd power */ d__1 = z__[*i__] / delta[*i__]; c__ = w - delta[ip1] * dw - (d__[*i__] - d__[ip1]) * (d__1 * d__1); } else { /* Computing 2nd power */ d__1 = z__[ip1] / delta[ip1]; c__ = w - delta[*i__] * dw - (d__[ip1] - d__[*i__]) * (d__1 * d__1); } a = (delta[*i__] + delta[ip1]) * w - delta[*i__] * delta[ip1] * dw; b = delta[*i__] * delta[ip1] * w; if (c__ == 0.) { if (a == 0.) { if (orgati) { a = z__[*i__] * z__[*i__] + delta[ip1] * delta[ip1] * (dpsi + dphi); } else { a = z__[ip1] * z__[ip1] + delta[*i__] * delta[*i__] * (dpsi + dphi); } } eta = b / a; } else if (a <= 0.) { eta = (a - sqrt((d__1 = a * a - b * 4. * c__, abs(d__1)))) / ( c__ * 2.); } else { eta = b * 2. / (a + sqrt((d__1 = a * a - b * 4. * c__, abs( d__1)))); } } else { /* Interpolation using THREE most relevant poles */ temp = rhoinv + psi + phi; if (orgati) { temp1 = z__[iim1] / delta[iim1]; temp1 *= temp1; c__ = temp - delta[iip1] * (dpsi + dphi) - (d__[iim1] - d__[ iip1]) * temp1; zz[0] = z__[iim1] * z__[iim1]; zz[2] = delta[iip1] * delta[iip1] * (dpsi - temp1 + dphi); } else { temp1 = z__[iip1] / delta[iip1]; temp1 *= temp1; c__ = temp - delta[iim1] * (dpsi + dphi) - (d__[iip1] - d__[ iim1]) * temp1; zz[0] = delta[iim1] * delta[iim1] * (dpsi + (dphi - temp1)); zz[2] = z__[iip1] * z__[iip1]; } zz[1] = z__[ii] * z__[ii]; dlaed6_(&niter, &orgati, &c__, &delta[iim1], zz, &w, &eta, info); if (*info != 0) { goto L250; } } /* Note, eta should be positive if w is negative, and eta should be negative otherwise. However, if for some reason caused by roundoff, eta*w > 0, we simply use one Newton step instead. This way will guarantee eta*w < 0. */ if (w * eta >= 0.) { eta = -w / dw; } temp = tau + eta; if ((temp > dltub) || (temp < dltlb)) { if (w < 0.) { eta = (dltub - tau) / 2.; } else { eta = (dltlb - tau) / 2.; } } prew = w; /* L170: */ i__1 = *n; for (j = 1; j <= i__1; ++j) { delta[j] -= eta; /* L180: */ } /* Evaluate PSI and the derivative DPSI */ dpsi = 0.; psi = 0.; erretm = 0.; i__1 = iim1; for (j = 1; j <= i__1; ++j) { temp = z__[j] / delta[j]; psi += z__[j] * temp; dpsi += temp * temp; erretm += psi; /* L190: */ } erretm = abs(erretm); /* Evaluate PHI and the derivative DPHI */ dphi = 0.; phi = 0.; i__1 = iip1; for (j = *n; j >= i__1; --j) { temp = z__[j] / delta[j]; phi += z__[j] * temp; dphi += temp * temp; erretm += phi; /* L200: */ } temp = z__[ii] / delta[ii]; dw = dpsi + dphi + temp * temp; temp = z__[ii] * temp; w = rhoinv + phi + psi + temp; erretm = (phi - psi) * 8. + erretm + rhoinv * 2. + abs(temp) * 3. + ( d__1 = tau + eta, abs(d__1)) * dw; swtch = FALSE_; if (orgati) { if (-w > abs(prew) / 10.) { swtch = TRUE_; } } else { if (w > abs(prew) / 10.) { swtch = TRUE_; } } tau += eta; /* Main loop to update the values of the array DELTA */ iter = niter + 1; for (niter = iter; niter <= 30; ++niter) { /* Test for convergence */ if (abs(w) <= eps * erretm) { if (orgati) { *dlam = d__[*i__] + tau; } else { *dlam = d__[ip1] + tau; } goto L250; } if (w <= 0.) { dltlb = max(dltlb,tau); } else { dltub = min(dltub,tau); } /* Calculate the new step */ if (! swtch3) { if (! swtch) { if (orgati) { /* Computing 2nd power */ d__1 = z__[*i__] / delta[*i__]; c__ = w - delta[ip1] * dw - (d__[*i__] - d__[ip1]) * ( d__1 * d__1); } else { /* Computing 2nd power */ d__1 = z__[ip1] / delta[ip1]; c__ = w - delta[*i__] * dw - (d__[ip1] - d__[*i__]) * (d__1 * d__1); } } else { temp = z__[ii] / delta[ii]; if (orgati) { dpsi += temp * temp; } else { dphi += temp * temp; } c__ = w - delta[*i__] * dpsi - delta[ip1] * dphi; } a = (delta[*i__] + delta[ip1]) * w - delta[*i__] * delta[ip1] * dw; b = delta[*i__] * delta[ip1] * w; if (c__ == 0.) { if (a == 0.) { if (! swtch) { if (orgati) { a = z__[*i__] * z__[*i__] + delta[ip1] * delta[ip1] * (dpsi + dphi); } else { a = z__[ip1] * z__[ip1] + delta[*i__] * delta[ *i__] * (dpsi + dphi); } } else { a = delta[*i__] * delta[*i__] * dpsi + delta[ip1] * delta[ip1] * dphi; } } eta = b / a; } else if (a <= 0.) { eta = (a - sqrt((d__1 = a * a - b * 4. * c__, abs(d__1)))) / (c__ * 2.); } else { eta = b * 2. / (a + sqrt((d__1 = a * a - b * 4. * c__, abs(d__1)))); } } else { /* Interpolation using THREE most relevant poles */ temp = rhoinv + psi + phi; if (swtch) { c__ = temp - delta[iim1] * dpsi - delta[iip1] * dphi; zz[0] = delta[iim1] * delta[iim1] * dpsi; zz[2] = delta[iip1] * delta[iip1] * dphi; } else { if (orgati) { temp1 = z__[iim1] / delta[iim1]; temp1 *= temp1; c__ = temp - delta[iip1] * (dpsi + dphi) - (d__[iim1] - d__[iip1]) * temp1; zz[0] = z__[iim1] * z__[iim1]; zz[2] = delta[iip1] * delta[iip1] * (dpsi - temp1 + dphi); } else { temp1 = z__[iip1] / delta[iip1]; temp1 *= temp1; c__ = temp - delta[iim1] * (dpsi + dphi) - (d__[iip1] - d__[iim1]) * temp1; zz[0] = delta[iim1] * delta[iim1] * (dpsi + (dphi - temp1)); zz[2] = z__[iip1] * z__[iip1]; } } dlaed6_(&niter, &orgati, &c__, &delta[iim1], zz, &w, &eta, info); if (*info != 0) { goto L250; } } /* Note, eta should be positive if w is negative, and eta should be negative otherwise. However, if for some reason caused by roundoff, eta*w > 0, we simply use one Newton step instead. This way will guarantee eta*w < 0. */ if (w * eta >= 0.) { eta = -w / dw; } temp = tau + eta; if ((temp > dltub) || (temp < dltlb)) { if (w < 0.) { eta = (dltub - tau) / 2.; } else { eta = (dltlb - tau) / 2.; } } i__1 = *n; for (j = 1; j <= i__1; ++j) { delta[j] -= eta; /* L210: */ } tau += eta; prew = w; /* Evaluate PSI and the derivative DPSI */ dpsi = 0.; psi = 0.; erretm = 0.; i__1 = iim1; for (j = 1; j <= i__1; ++j) { temp = z__[j] / delta[j]; psi += z__[j] * temp; dpsi += temp * temp; erretm += psi; /* L220: */ } erretm = abs(erretm); /* Evaluate PHI and the derivative DPHI */ dphi = 0.; phi = 0.; i__1 = iip1; for (j = *n; j >= i__1; --j) { temp = z__[j] / delta[j]; phi += z__[j] * temp; dphi += temp * temp; erretm += phi; /* L230: */ } temp = z__[ii] / delta[ii]; dw = dpsi + dphi + temp * temp; temp = z__[ii] * temp; w = rhoinv + phi + psi + temp; erretm = (phi - psi) * 8. + erretm + rhoinv * 2. + abs(temp) * 3. + abs(tau) * dw; if (w * prew > 0. && abs(w) > abs(prew) / 10.) { swtch = ! swtch; } /* L240: */ } /* Return with INFO = 1, NITER = MAXIT and not converged */ *info = 1; if (orgati) { *dlam = d__[*i__] + tau; } else { *dlam = d__[ip1] + tau; } } L250: return 0; /* End of DLAED4 */ } /* dlaed4_ */ /* Subroutine */ int dlaed5_(integer *i__, doublereal *d__, doublereal *z__, doublereal *delta, doublereal *rho, doublereal *dlam) { /* System generated locals */ doublereal d__1; /* Builtin functions */ double sqrt(doublereal); /* Local variables */ static doublereal b, c__, w, del, tau, temp; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Oak Ridge National Lab, Argonne National Lab, Courant Institute, NAG Ltd., and Rice University September 30, 1994 Purpose ======= This subroutine computes the I-th eigenvalue of a symmetric rank-one modification of a 2-by-2 diagonal matrix diag( D ) + RHO * Z * transpose(Z) . The diagonal elements in the array D are assumed to satisfy D(i) < D(j) for i < j . We also assume RHO > 0 and that the Euclidean norm of the vector Z is one. Arguments ========= I (input) INTEGER The index of the eigenvalue to be computed. I = 1 or I = 2. D (input) DOUBLE PRECISION array, dimension (2) The original eigenvalues. We assume D(1) < D(2). Z (input) DOUBLE PRECISION array, dimension (2) The components of the updating vector. DELTA (output) DOUBLE PRECISION array, dimension (2) The vector DELTA contains the information necessary to construct the eigenvectors. RHO (input) DOUBLE PRECISION The scalar in the symmetric updating formula. DLAM (output) DOUBLE PRECISION The computed lambda_I, the I-th updated eigenvalue. Further Details =============== Based on contributions by Ren-Cang Li, Computer Science Division, University of California at Berkeley, USA ===================================================================== */ /* Parameter adjustments */ --delta; --z__; --d__; /* Function Body */ del = d__[2] - d__[1]; if (*i__ == 1) { w = *rho * 2. * (z__[2] * z__[2] - z__[1] * z__[1]) / del + 1.; if (w > 0.) { b = del + *rho * (z__[1] * z__[1] + z__[2] * z__[2]); c__ = *rho * z__[1] * z__[1] * del; /* B > ZERO, always */ tau = c__ * 2. / (b + sqrt((d__1 = b * b - c__ * 4., abs(d__1)))); *dlam = d__[1] + tau; delta[1] = -z__[1] / tau; delta[2] = z__[2] / (del - tau); } else { b = -del + *rho * (z__[1] * z__[1] + z__[2] * z__[2]); c__ = *rho * z__[2] * z__[2] * del; if (b > 0.) { tau = c__ * -2. / (b + sqrt(b * b + c__ * 4.)); } else { tau = (b - sqrt(b * b + c__ * 4.)) / 2.; } *dlam = d__[2] + tau; delta[1] = -z__[1] / (del + tau); delta[2] = -z__[2] / tau; } temp = sqrt(delta[1] * delta[1] + delta[2] * delta[2]); delta[1] /= temp; delta[2] /= temp; } else { /* Now I=2 */ b = -del + *rho * (z__[1] * z__[1] + z__[2] * z__[2]); c__ = *rho * z__[2] * z__[2] * del; if (b > 0.) { tau = (b + sqrt(b * b + c__ * 4.)) / 2.; } else { tau = c__ * 2. / (-b + sqrt(b * b + c__ * 4.)); } *dlam = d__[2] + tau; delta[1] = -z__[1] / (del + tau); delta[2] = -z__[2] / tau; temp = sqrt(delta[1] * delta[1] + delta[2] * delta[2]); delta[1] /= temp; delta[2] /= temp; } return 0; /* End OF DLAED5 */ } /* dlaed5_ */ /* Subroutine */ int dlaed6_(integer *kniter, logical *orgati, doublereal * rho, doublereal *d__, doublereal *z__, doublereal *finit, doublereal * tau, integer *info) { /* Initialized data */ static logical first = TRUE_; /* System generated locals */ integer i__1; doublereal d__1, d__2, d__3, d__4; /* Builtin functions */ double sqrt(doublereal), log(doublereal), pow_di(doublereal *, integer *); /* Local variables */ static doublereal a, b, c__, f; static integer i__; static doublereal fc, df, ddf, eta, eps, base; static integer iter; static doublereal temp, temp1, temp2, temp3, temp4; static logical scale; static integer niter; static doublereal small1, small2, sminv1, sminv2; static doublereal dscale[3], sclfac, zscale[3], erretm, sclinv; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Oak Ridge National Lab, Argonne National Lab, Courant Institute, NAG Ltd., and Rice University June 30, 1999 Purpose ======= DLAED6 computes the positive or negative root (closest to the origin) of z(1) z(2) z(3) f(x) = rho + --------- + ---------- + --------- d(1)-x d(2)-x d(3)-x It is assumed that if ORGATI = .true. the root is between d(2) and d(3); otherwise it is between d(1) and d(2) This routine will be called by DLAED4 when necessary. In most cases, the root sought is the smallest in magnitude, though it might not be in some extremely rare situations. Arguments ========= KNITER (input) INTEGER Refer to DLAED4 for its significance. ORGATI (input) LOGICAL If ORGATI is true, the needed root is between d(2) and d(3); otherwise it is between d(1) and d(2). See DLAED4 for further details. RHO (input) DOUBLE PRECISION Refer to the equation f(x) above. D (input) DOUBLE PRECISION array, dimension (3) D satisfies d(1) < d(2) < d(3). Z (input) DOUBLE PRECISION array, dimension (3) Each of the elements in z must be positive. FINIT (input) DOUBLE PRECISION The value of f at 0. It is more accurate than the one evaluated inside this routine (if someone wants to do so). TAU (output) DOUBLE PRECISION The root of the equation f(x). INFO (output) INTEGER = 0: successful exit > 0: if INFO = 1, failure to converge Further Details =============== Based on contributions by Ren-Cang Li, Computer Science Division, University of California at Berkeley, USA ===================================================================== */ /* Parameter adjustments */ --z__; --d__; /* Function Body */ *info = 0; niter = 1; *tau = 0.; if (*kniter == 2) { if (*orgati) { temp = (d__[3] - d__[2]) / 2.; c__ = *rho + z__[1] / (d__[1] - d__[2] - temp); a = c__ * (d__[2] + d__[3]) + z__[2] + z__[3]; b = c__ * d__[2] * d__[3] + z__[2] * d__[3] + z__[3] * d__[2]; } else { temp = (d__[1] - d__[2]) / 2.; c__ = *rho + z__[3] / (d__[3] - d__[2] - temp); a = c__ * (d__[1] + d__[2]) + z__[1] + z__[2]; b = c__ * d__[1] * d__[2] + z__[1] * d__[2] + z__[2] * d__[1]; } /* Computing MAX */ d__1 = abs(a), d__2 = abs(b), d__1 = max(d__1,d__2), d__2 = abs(c__); temp = max(d__1,d__2); a /= temp; b /= temp; c__ /= temp; if (c__ == 0.) { *tau = b / a; } else if (a <= 0.) { *tau = (a - sqrt((d__1 = a * a - b * 4. * c__, abs(d__1)))) / ( c__ * 2.); } else { *tau = b * 2. / (a + sqrt((d__1 = a * a - b * 4. * c__, abs(d__1)) )); } temp = *rho + z__[1] / (d__[1] - *tau) + z__[2] / (d__[2] - *tau) + z__[3] / (d__[3] - *tau); if (abs(*finit) <= abs(temp)) { *tau = 0.; } } /* On first call to routine, get machine parameters for possible scaling to avoid overflow */ if (first) { eps = EPSILON; base = BASE; i__1 = (integer) (log(SAFEMINIMUM) / log(base) / 3.); small1 = pow_di(&base, &i__1); sminv1 = 1. / small1; small2 = small1 * small1; sminv2 = sminv1 * sminv1; first = FALSE_; } /* Determine if scaling of inputs necessary to avoid overflow when computing 1/TEMP**3 */ if (*orgati) { /* Computing MIN */ d__3 = (d__1 = d__[2] - *tau, abs(d__1)), d__4 = (d__2 = d__[3] - * tau, abs(d__2)); temp = min(d__3,d__4); } else { /* Computing MIN */ d__3 = (d__1 = d__[1] - *tau, abs(d__1)), d__4 = (d__2 = d__[2] - * tau, abs(d__2)); temp = min(d__3,d__4); } scale = FALSE_; if (temp <= small1) { scale = TRUE_; if (temp <= small2) { /* Scale up by power of radix nearest 1/SAFMIN**(2/3) */ sclfac = sminv2; sclinv = small2; } else { /* Scale up by power of radix nearest 1/SAFMIN**(1/3) */ sclfac = sminv1; sclinv = small1; } /* Scaling up safe because D, Z, TAU scaled elsewhere to be O(1) */ for (i__ = 1; i__ <= 3; ++i__) { dscale[i__ - 1] = d__[i__] * sclfac; zscale[i__ - 1] = z__[i__] * sclfac; /* L10: */ } *tau *= sclfac; } else { /* Copy D and Z to DSCALE and ZSCALE */ for (i__ = 1; i__ <= 3; ++i__) { dscale[i__ - 1] = d__[i__]; zscale[i__ - 1] = z__[i__]; /* L20: */ } } fc = 0.; df = 0.; ddf = 0.; for (i__ = 1; i__ <= 3; ++i__) { temp = 1. / (dscale[i__ - 1] - *tau); temp1 = zscale[i__ - 1] * temp; temp2 = temp1 * temp; temp3 = temp2 * temp; fc += temp1 / dscale[i__ - 1]; df += temp2; ddf += temp3; /* L30: */ } f = *finit + *tau * fc; if (abs(f) <= 0.) { goto L60; } /* Iteration begins It is not hard to see that 1) Iterations will go up monotonically if FINIT < 0; 2) Iterations will go down monotonically if FINIT > 0. */ iter = niter + 1; for (niter = iter; niter <= 20; ++niter) { if (*orgati) { temp1 = dscale[1] - *tau; temp2 = dscale[2] - *tau; } else { temp1 = dscale[0] - *tau; temp2 = dscale[1] - *tau; } a = (temp1 + temp2) * f - temp1 * temp2 * df; b = temp1 * temp2 * f; c__ = f - (temp1 + temp2) * df + temp1 * temp2 * ddf; /* Computing MAX */ d__1 = abs(a), d__2 = abs(b), d__1 = max(d__1,d__2), d__2 = abs(c__); temp = max(d__1,d__2); a /= temp; b /= temp; c__ /= temp; if (c__ == 0.) { eta = b / a; } else if (a <= 0.) { eta = (a - sqrt((d__1 = a * a - b * 4. * c__, abs(d__1)))) / (c__ * 2.); } else { eta = b * 2. / (a + sqrt((d__1 = a * a - b * 4. * c__, abs(d__1))) ); } if (f * eta >= 0.) { eta = -f / df; } temp = eta + *tau; if (*orgati) { if (eta > 0. && temp >= dscale[2]) { eta = (dscale[2] - *tau) / 2.; } if (eta < 0. && temp <= dscale[1]) { eta = (dscale[1] - *tau) / 2.; } } else { if (eta > 0. && temp >= dscale[1]) { eta = (dscale[1] - *tau) / 2.; } if (eta < 0. && temp <= dscale[0]) { eta = (dscale[0] - *tau) / 2.; } } *tau += eta; fc = 0.; erretm = 0.; df = 0.; ddf = 0.; for (i__ = 1; i__ <= 3; ++i__) { temp = 1. / (dscale[i__ - 1] - *tau); temp1 = zscale[i__ - 1] * temp; temp2 = temp1 * temp; temp3 = temp2 * temp; temp4 = temp1 / dscale[i__ - 1]; fc += temp4; erretm += abs(temp4); df += temp2; ddf += temp3; /* L40: */ } f = *finit + *tau * fc; erretm = (abs(*finit) + abs(*tau) * erretm) * 8. + abs(*tau) * df; if (abs(f) <= eps * erretm) { goto L60; } /* L50: */ } *info = 1; L60: /* Undo scaling */ if (scale) { *tau *= sclinv; } return 0; /* End of DLAED6 */ } /* dlaed6_ */ /* Subroutine */ int dlaed7_(integer *icompq, integer *n, integer *qsiz, integer *tlvls, integer *curlvl, integer *curpbm, doublereal *d__, doublereal *q, integer *ldq, integer *indxq, doublereal *rho, integer *cutpnt, doublereal *qstore, integer *qptr, integer *prmptr, integer * perm, integer *givptr, integer *givcol, doublereal *givnum, doublereal *work, integer *iwork, integer *info) { /* System generated locals */ integer q_dim1, q_offset, i__1, i__2; /* Builtin functions */ integer pow_ii(integer *, integer *); /* Local variables */ static integer i__, k, n1, n2, is, iw, iz, iq2, ptr, ldq2, indx, curr; extern /* Subroutine */ int dgemm_(char *, char *, integer *, integer *, integer *, doublereal *, doublereal *, integer *, doublereal *, integer *, doublereal *, doublereal *, integer *); static integer indxc, indxp; extern /* Subroutine */ int dlaed8_(integer *, integer *, integer *, integer *, doublereal *, doublereal *, integer *, integer *, doublereal *, integer *, doublereal *, doublereal *, doublereal *, integer *, doublereal *, integer *, integer *, integer *, doublereal *, integer *, integer *, integer *), dlaed9_(integer *, integer *, integer *, integer *, doublereal *, doublereal *, integer *, doublereal *, doublereal *, doublereal *, doublereal *, integer *, integer *), dlaeda_(integer *, integer *, integer *, integer *, integer *, integer *, integer *, integer *, doublereal *, doublereal *, integer *, doublereal *, doublereal *, integer *) ; static integer idlmda; extern /* Subroutine */ int dlamrg_(integer *, integer *, doublereal *, integer *, integer *, integer *), xerbla_(char *, integer *); static integer coltyp; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University September 30, 1994 Purpose ======= DLAED7 computes the updated eigensystem of a diagonal matrix after modification by a rank-one symmetric matrix. This routine is used only for the eigenproblem which requires all eigenvalues and optionally eigenvectors of a dense symmetric matrix that has been reduced to tridiagonal form. DLAED1 handles the case in which all eigenvalues and eigenvectors of a symmetric tridiagonal matrix are desired. T = Q(in) ( D(in) + RHO * Z*Z' ) Q'(in) = Q(out) * D(out) * Q'(out) where Z = Q'u, u is a vector of length N with ones in the CUTPNT and CUTPNT + 1 th elements and zeros elsewhere. The eigenvectors of the original matrix are stored in Q, and the eigenvalues are in D. The algorithm consists of three stages: The first stage consists of deflating the size of the problem when there are multiple eigenvalues or if there is a zero in the Z vector. For each such occurence the dimension of the secular equation problem is reduced by one. This stage is performed by the routine DLAED8. The second stage consists of calculating the updated eigenvalues. This is done by finding the roots of the secular equation via the routine DLAED4 (as called by DLAED9). This routine also calculates the eigenvectors of the current problem. The final stage consists of computing the updated eigenvectors directly using the updated eigenvalues. The eigenvectors for the current problem are multiplied with the eigenvectors from the overall problem. Arguments ========= ICOMPQ (input) INTEGER = 0: Compute eigenvalues only. = 1: Compute eigenvectors of original dense symmetric matrix also. On entry, Q contains the orthogonal matrix used to reduce the original matrix to tridiagonal form. N (input) INTEGER The dimension of the symmetric tridiagonal matrix. N >= 0. QSIZ (input) INTEGER The dimension of the orthogonal matrix used to reduce the full matrix to tridiagonal form. QSIZ >= N if ICOMPQ = 1. TLVLS (input) INTEGER The total number of merging levels in the overall divide and conquer tree. CURLVL (input) INTEGER The current level in the overall merge routine, 0 <= CURLVL <= TLVLS. CURPBM (input) INTEGER The current problem in the current level in the overall merge routine (counting from upper left to lower right). D (input/output) DOUBLE PRECISION array, dimension (N) On entry, the eigenvalues of the rank-1-perturbed matrix. On exit, the eigenvalues of the repaired matrix. Q (input/output) DOUBLE PRECISION array, dimension (LDQ, N) On entry, the eigenvectors of the rank-1-perturbed matrix. On exit, the eigenvectors of the repaired tridiagonal matrix. LDQ (input) INTEGER The leading dimension of the array Q. LDQ >= max(1,N). INDXQ (output) INTEGER array, dimension (N) The permutation which will reintegrate the subproblem just solved back into sorted order, i.e., D( INDXQ( I = 1, N ) ) will be in ascending order. RHO (input) DOUBLE PRECISION The subdiagonal element used to create the rank-1 modification. CUTPNT (input) INTEGER Contains the location of the last eigenvalue in the leading sub-matrix. min(1,N) <= CUTPNT <= N. QSTORE (input/output) DOUBLE PRECISION array, dimension (N**2+1) Stores eigenvectors of submatrices encountered during divide and conquer, packed together. QPTR points to beginning of the submatrices. QPTR (input/output) INTEGER array, dimension (N+2) List of indices pointing to beginning of submatrices stored in QSTORE. The submatrices are numbered starting at the bottom left of the divide and conquer tree, from left to right and bottom to top. PRMPTR (input) INTEGER array, dimension (N lg N) Contains a list of pointers which indicate where in PERM a level's permutation is stored. PRMPTR(i+1) - PRMPTR(i) indicates the size of the permutation and also the size of the full, non-deflated problem. PERM (input) INTEGER array, dimension (N lg N) Contains the permutations (from deflation and sorting) to be applied to each eigenblock. GIVPTR (input) INTEGER array, dimension (N lg N) Contains a list of pointers which indicate where in GIVCOL a level's Givens rotations are stored. GIVPTR(i+1) - GIVPTR(i) indicates the number of Givens rotations. GIVCOL (input) INTEGER array, dimension (2, N lg N) Each pair of numbers indicates a pair of columns to take place in a Givens rotation. GIVNUM (input) DOUBLE PRECISION array, dimension (2, N lg N) Each number indicates the S value to be used in the corresponding Givens rotation. WORK (workspace) DOUBLE PRECISION array, dimension (3*N+QSIZ*N) IWORK (workspace) INTEGER array, dimension (4*N) INFO (output) INTEGER = 0: successful exit. < 0: if INFO = -i, the i-th argument had an illegal value. > 0: if INFO = 1, an eigenvalue did not converge Further Details =============== Based on contributions by Jeff Rutter, Computer Science Division, University of California at Berkeley, USA ===================================================================== Test the input parameters. */ /* Parameter adjustments */ --d__; q_dim1 = *ldq; q_offset = 1 + q_dim1; q -= q_offset; --indxq; --qstore; --qptr; --prmptr; --perm; --givptr; givcol -= 3; givnum -= 3; --work; --iwork; /* Function Body */ *info = 0; if ((*icompq < 0) || (*icompq > 1)) { *info = -1; } else if (*n < 0) { *info = -2; } else if (*icompq == 1 && *qsiz < *n) { *info = -4; } else if (*ldq < max(1,*n)) { *info = -9; } else if ((min(1,*n) > *cutpnt) || (*n < *cutpnt)) { *info = -12; } if (*info != 0) { i__1 = -(*info); xerbla_("DLAED7", &i__1); return 0; } /* Quick return if possible */ if (*n == 0) { return 0; } /* The following values are for bookkeeping purposes only. They are integer pointers which indicate the portion of the workspace used by a particular array in DLAED8 and DLAED9. */ if (*icompq == 1) { ldq2 = *qsiz; } else { ldq2 = *n; } iz = 1; idlmda = iz + *n; iw = idlmda + *n; iq2 = iw + *n; is = iq2 + *n * ldq2; indx = 1; indxc = indx + *n; coltyp = indxc + *n; indxp = coltyp + *n; /* Form the z-vector which consists of the last row of Q_1 and the first row of Q_2. */ ptr = pow_ii(&c__2, tlvls) + 1; i__1 = *curlvl - 1; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = *tlvls - i__; ptr += pow_ii(&c__2, &i__2); /* L10: */ } curr = ptr + *curpbm; dlaeda_(n, tlvls, curlvl, curpbm, &prmptr[1], &perm[1], &givptr[1], & givcol[3], &givnum[3], &qstore[1], &qptr[1], &work[iz], &work[iz + *n], info); /* When solving the final problem, we no longer need the stored data, so we will overwrite the data from this level onto the previously used storage space. */ if (*curlvl == *tlvls) { qptr[curr] = 1; prmptr[curr] = 1; givptr[curr] = 1; } /* Sort and Deflate eigenvalues. */ dlaed8_(icompq, &k, n, qsiz, &d__[1], &q[q_offset], ldq, &indxq[1], rho, cutpnt, &work[iz], &work[idlmda], &work[iq2], &ldq2, &work[iw], & perm[prmptr[curr]], &givptr[curr + 1], &givcol[((givptr[curr]) << (1)) + 1], &givnum[((givptr[curr]) << (1)) + 1], &iwork[indxp], & iwork[indx], info); prmptr[curr + 1] = prmptr[curr] + *n; givptr[curr + 1] += givptr[curr]; /* Solve Secular Equation. */ if (k != 0) { dlaed9_(&k, &c__1, &k, n, &d__[1], &work[is], &k, rho, &work[idlmda], &work[iw], &qstore[qptr[curr]], &k, info); if (*info != 0) { goto L30; } if (*icompq == 1) { dgemm_("N", "N", qsiz, &k, &k, &c_b2865, &work[iq2], &ldq2, & qstore[qptr[curr]], &k, &c_b2879, &q[q_offset], ldq); } /* Computing 2nd power */ i__1 = k; qptr[curr + 1] = qptr[curr] + i__1 * i__1; /* Prepare the INDXQ sorting permutation. */ n1 = k; n2 = *n - k; dlamrg_(&n1, &n2, &d__[1], &c__1, &c_n1, &indxq[1]); } else { qptr[curr + 1] = qptr[curr]; i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { indxq[i__] = i__; /* L20: */ } } L30: return 0; /* End of DLAED7 */ } /* dlaed7_ */ /* Subroutine */ int dlaed8_(integer *icompq, integer *k, integer *n, integer *qsiz, doublereal *d__, doublereal *q, integer *ldq, integer *indxq, doublereal *rho, integer *cutpnt, doublereal *z__, doublereal *dlamda, doublereal *q2, integer *ldq2, doublereal *w, integer *perm, integer *givptr, integer *givcol, doublereal *givnum, integer *indxp, integer *indx, integer *info) { /* System generated locals */ integer q_dim1, q_offset, q2_dim1, q2_offset, i__1; doublereal d__1; /* Builtin functions */ double sqrt(doublereal); /* Local variables */ static doublereal c__; static integer i__, j; static doublereal s, t; static integer k2, n1, n2, jp, n1p1; static doublereal eps, tau, tol; static integer jlam, imax, jmax; extern /* Subroutine */ int drot_(integer *, doublereal *, integer *, doublereal *, integer *, doublereal *, doublereal *), dscal_( integer *, doublereal *, doublereal *, integer *), dcopy_(integer *, doublereal *, integer *, doublereal *, integer *); extern integer idamax_(integer *, doublereal *, integer *); extern /* Subroutine */ int dlamrg_(integer *, integer *, doublereal *, integer *, integer *, integer *), dlacpy_(char *, integer *, integer *, doublereal *, integer *, doublereal *, integer *), xerbla_(char *, integer *); /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Oak Ridge National Lab, Argonne National Lab, Courant Institute, NAG Ltd., and Rice University September 30, 1994 Purpose ======= DLAED8 merges the two sets of eigenvalues together into a single sorted set. Then it tries to deflate the size of the problem. There are two ways in which deflation can occur: when two or more eigenvalues are close together or if there is a tiny element in the Z vector. For each such occurrence the order of the related secular equation problem is reduced by one. Arguments ========= ICOMPQ (input) INTEGER = 0: Compute eigenvalues only. = 1: Compute eigenvectors of original dense symmetric matrix also. On entry, Q contains the orthogonal matrix used to reduce the original matrix to tridiagonal form. K (output) INTEGER The number of non-deflated eigenvalues, and the order of the related secular equation. N (input) INTEGER The dimension of the symmetric tridiagonal matrix. N >= 0. QSIZ (input) INTEGER The dimension of the orthogonal matrix used to reduce the full matrix to tridiagonal form. QSIZ >= N if ICOMPQ = 1. D (input/output) DOUBLE PRECISION array, dimension (N) On entry, the eigenvalues of the two submatrices to be combined. On exit, the trailing (N-K) updated eigenvalues (those which were deflated) sorted into increasing order. Q (input/output) DOUBLE PRECISION array, dimension (LDQ,N) If ICOMPQ = 0, Q is not referenced. Otherwise, on entry, Q contains the eigenvectors of the partially solved system which has been previously updated in matrix multiplies with other partially solved eigensystems. On exit, Q contains the trailing (N-K) updated eigenvectors (those which were deflated) in its last N-K columns. LDQ (input) INTEGER The leading dimension of the array Q. LDQ >= max(1,N). INDXQ (input) INTEGER array, dimension (N) The permutation which separately sorts the two sub-problems in D into ascending order. Note that elements in the second half of this permutation must first have CUTPNT added to their values in order to be accurate. RHO (input/output) DOUBLE PRECISION On entry, the off-diagonal element associated with the rank-1 cut which originally split the two submatrices which are now being recombined. On exit, RHO has been modified to the value required by DLAED3. CUTPNT (input) INTEGER The location of the last eigenvalue in the leading sub-matrix. min(1,N) <= CUTPNT <= N. Z (input) DOUBLE PRECISION array, dimension (N) On entry, Z contains the updating vector (the last row of the first sub-eigenvector matrix and the first row of the second sub-eigenvector matrix). On exit, the contents of Z are destroyed by the updating process. DLAMDA (output) DOUBLE PRECISION array, dimension (N) A copy of the first K eigenvalues which will be used by DLAED3 to form the secular equation. Q2 (output) DOUBLE PRECISION array, dimension (LDQ2,N) If ICOMPQ = 0, Q2 is not referenced. Otherwise, a copy of the first K eigenvectors which will be used by DLAED7 in a matrix multiply (DGEMM) to update the new eigenvectors. LDQ2 (input) INTEGER The leading dimension of the array Q2. LDQ2 >= max(1,N). W (output) DOUBLE PRECISION array, dimension (N) The first k values of the final deflation-altered z-vector and will be passed to DLAED3. PERM (output) INTEGER array, dimension (N) The permutations (from deflation and sorting) to be applied to each eigenblock. GIVPTR (output) INTEGER The number of Givens rotations which took place in this subproblem. GIVCOL (output) INTEGER array, dimension (2, N) Each pair of numbers indicates a pair of columns to take place in a Givens rotation. GIVNUM (output) DOUBLE PRECISION array, dimension (2, N) Each number indicates the S value to be used in the corresponding Givens rotation. INDXP (workspace) INTEGER array, dimension (N) The permutation used to place deflated values of D at the end of the array. INDXP(1:K) points to the nondeflated D-values and INDXP(K+1:N) points to the deflated eigenvalues. INDX (workspace) INTEGER array, dimension (N) The permutation used to sort the contents of D into ascending order. INFO (output) INTEGER = 0: successful exit. < 0: if INFO = -i, the i-th argument had an illegal value. Further Details =============== Based on contributions by Jeff Rutter, Computer Science Division, University of California at Berkeley, USA ===================================================================== Test the input parameters. */ /* Parameter adjustments */ --d__; q_dim1 = *ldq; q_offset = 1 + q_dim1; q -= q_offset; --indxq; --z__; --dlamda; q2_dim1 = *ldq2; q2_offset = 1 + q2_dim1; q2 -= q2_offset; --w; --perm; givcol -= 3; givnum -= 3; --indxp; --indx; /* Function Body */ *info = 0; if ((*icompq < 0) || (*icompq > 1)) { *info = -1; } else if (*n < 0) { *info = -3; } else if (*icompq == 1 && *qsiz < *n) { *info = -4; } else if (*ldq < max(1,*n)) { *info = -7; } else if ((*cutpnt < min(1,*n)) || (*cutpnt > *n)) { *info = -10; } else if (*ldq2 < max(1,*n)) { *info = -14; } if (*info != 0) { i__1 = -(*info); xerbla_("DLAED8", &i__1); return 0; } /* Quick return if possible */ if (*n == 0) { return 0; } n1 = *cutpnt; n2 = *n - n1; n1p1 = n1 + 1; if (*rho < 0.) { dscal_(&n2, &c_b3001, &z__[n1p1], &c__1); } /* Normalize z so that norm(z) = 1 */ t = 1. / sqrt(2.); i__1 = *n; for (j = 1; j <= i__1; ++j) { indx[j] = j; /* L10: */ } dscal_(n, &t, &z__[1], &c__1); *rho = (d__1 = *rho * 2., abs(d__1)); /* Sort the eigenvalues into increasing order */ i__1 = *n; for (i__ = *cutpnt + 1; i__ <= i__1; ++i__) { indxq[i__] += *cutpnt; /* L20: */ } i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { dlamda[i__] = d__[indxq[i__]]; w[i__] = z__[indxq[i__]]; /* L30: */ } i__ = 1; j = *cutpnt + 1; dlamrg_(&n1, &n2, &dlamda[1], &c__1, &c__1, &indx[1]); i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { d__[i__] = dlamda[indx[i__]]; z__[i__] = w[indx[i__]]; /* L40: */ } /* Calculate the allowable deflation tolerence */ imax = idamax_(n, &z__[1], &c__1); jmax = idamax_(n, &d__[1], &c__1); eps = EPSILON; tol = eps * 8. * (d__1 = d__[jmax], abs(d__1)); /* If the rank-1 modifier is small enough, no more needs to be done except to reorganize Q so that its columns correspond with the elements in D. */ if (*rho * (d__1 = z__[imax], abs(d__1)) <= tol) { *k = 0; if (*icompq == 0) { i__1 = *n; for (j = 1; j <= i__1; ++j) { perm[j] = indxq[indx[j]]; /* L50: */ } } else { i__1 = *n; for (j = 1; j <= i__1; ++j) { perm[j] = indxq[indx[j]]; dcopy_(qsiz, &q[perm[j] * q_dim1 + 1], &c__1, &q2[j * q2_dim1 + 1], &c__1); /* L60: */ } dlacpy_("A", qsiz, n, &q2[q2_dim1 + 1], ldq2, &q[q_dim1 + 1], ldq); } return 0; } /* If there are multiple eigenvalues then the problem deflates. Here the number of equal eigenvalues are found. As each equal eigenvalue is found, an elementary reflector is computed to rotate the corresponding eigensubspace so that the corresponding components of Z are zero in this new basis. */ *k = 0; *givptr = 0; k2 = *n + 1; i__1 = *n; for (j = 1; j <= i__1; ++j) { if (*rho * (d__1 = z__[j], abs(d__1)) <= tol) { /* Deflate due to small z component. */ --k2; indxp[k2] = j; if (j == *n) { goto L110; } } else { jlam = j; goto L80; } /* L70: */ } L80: ++j; if (j > *n) { goto L100; } if (*rho * (d__1 = z__[j], abs(d__1)) <= tol) { /* Deflate due to small z component. */ --k2; indxp[k2] = j; } else { /* Check if eigenvalues are close enough to allow deflation. */ s = z__[jlam]; c__ = z__[j]; /* Find sqrt(a**2+b**2) without overflow or destructive underflow. */ tau = dlapy2_(&c__, &s); t = d__[j] - d__[jlam]; c__ /= tau; s = -s / tau; if ((d__1 = t * c__ * s, abs(d__1)) <= tol) { /* Deflation is possible. */ z__[j] = tau; z__[jlam] = 0.; /* Record the appropriate Givens rotation */ ++(*givptr); givcol[((*givptr) << (1)) + 1] = indxq[indx[jlam]]; givcol[((*givptr) << (1)) + 2] = indxq[indx[j]]; givnum[((*givptr) << (1)) + 1] = c__; givnum[((*givptr) << (1)) + 2] = s; if (*icompq == 1) { drot_(qsiz, &q[indxq[indx[jlam]] * q_dim1 + 1], &c__1, &q[ indxq[indx[j]] * q_dim1 + 1], &c__1, &c__, &s); } t = d__[jlam] * c__ * c__ + d__[j] * s * s; d__[j] = d__[jlam] * s * s + d__[j] * c__ * c__; d__[jlam] = t; --k2; i__ = 1; L90: if (k2 + i__ <= *n) { if (d__[jlam] < d__[indxp[k2 + i__]]) { indxp[k2 + i__ - 1] = indxp[k2 + i__]; indxp[k2 + i__] = jlam; ++i__; goto L90; } else { indxp[k2 + i__ - 1] = jlam; } } else { indxp[k2 + i__ - 1] = jlam; } jlam = j; } else { ++(*k); w[*k] = z__[jlam]; dlamda[*k] = d__[jlam]; indxp[*k] = jlam; jlam = j; } } goto L80; L100: /* Record the last eigenvalue. */ ++(*k); w[*k] = z__[jlam]; dlamda[*k] = d__[jlam]; indxp[*k] = jlam; L110: /* Sort the eigenvalues and corresponding eigenvectors into DLAMDA and Q2 respectively. The eigenvalues/vectors which were not deflated go into the first K slots of DLAMDA and Q2 respectively, while those which were deflated go into the last N - K slots. */ if (*icompq == 0) { i__1 = *n; for (j = 1; j <= i__1; ++j) { jp = indxp[j]; dlamda[j] = d__[jp]; perm[j] = indxq[indx[jp]]; /* L120: */ } } else { i__1 = *n; for (j = 1; j <= i__1; ++j) { jp = indxp[j]; dlamda[j] = d__[jp]; perm[j] = indxq[indx[jp]]; dcopy_(qsiz, &q[perm[j] * q_dim1 + 1], &c__1, &q2[j * q2_dim1 + 1] , &c__1); /* L130: */ } } /* The deflated eigenvalues and their corresponding vectors go back into the last N - K slots of D and Q respectively. */ if (*k < *n) { if (*icompq == 0) { i__1 = *n - *k; dcopy_(&i__1, &dlamda[*k + 1], &c__1, &d__[*k + 1], &c__1); } else { i__1 = *n - *k; dcopy_(&i__1, &dlamda[*k + 1], &c__1, &d__[*k + 1], &c__1); i__1 = *n - *k; dlacpy_("A", qsiz, &i__1, &q2[(*k + 1) * q2_dim1 + 1], ldq2, &q[(* k + 1) * q_dim1 + 1], ldq); } } return 0; /* End of DLAED8 */ } /* dlaed8_ */ /* Subroutine */ int dlaed9_(integer *k, integer *kstart, integer *kstop, integer *n, doublereal *d__, doublereal *q, integer *ldq, doublereal * rho, doublereal *dlamda, doublereal *w, doublereal *s, integer *lds, integer *info) { /* System generated locals */ integer q_dim1, q_offset, s_dim1, s_offset, i__1, i__2; doublereal d__1; /* Builtin functions */ double sqrt(doublereal), d_sign(doublereal *, doublereal *); /* Local variables */ static integer i__, j; static doublereal temp; extern doublereal dnrm2_(integer *, doublereal *, integer *); extern /* Subroutine */ int dcopy_(integer *, doublereal *, integer *, doublereal *, integer *), dlaed4_(integer *, integer *, doublereal *, doublereal *, doublereal *, doublereal *, doublereal *, integer *); extern doublereal dlamc3_(doublereal *, doublereal *); extern /* Subroutine */ int xerbla_(char *, integer *); /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Oak Ridge National Lab, Argonne National Lab, Courant Institute, NAG Ltd., and Rice University September 30, 1994 Purpose ======= DLAED9 finds the roots of the secular equation, as defined by the values in D, Z, and RHO, between KSTART and KSTOP. It makes the appropriate calls to DLAED4 and then stores the new matrix of eigenvectors for use in calculating the next level of Z vectors. Arguments ========= K (input) INTEGER The number of terms in the rational function to be solved by DLAED4. K >= 0. KSTART (input) INTEGER KSTOP (input) INTEGER The updated eigenvalues Lambda(I), KSTART <= I <= KSTOP are to be computed. 1 <= KSTART <= KSTOP <= K. N (input) INTEGER The number of rows and columns in the Q matrix. N >= K (delation may result in N > K). D (output) DOUBLE PRECISION array, dimension (N) D(I) contains the updated eigenvalues for KSTART <= I <= KSTOP. Q (workspace) DOUBLE PRECISION array, dimension (LDQ,N) LDQ (input) INTEGER The leading dimension of the array Q. LDQ >= max( 1, N ). RHO (input) DOUBLE PRECISION The value of the parameter in the rank one update equation. RHO >= 0 required. DLAMDA (input) DOUBLE PRECISION array, dimension (K) The first K elements of this array contain the old roots of the deflated updating problem. These are the poles of the secular equation. W (input) DOUBLE PRECISION array, dimension (K) The first K elements of this array contain the components of the deflation-adjusted updating vector. S (output) DOUBLE PRECISION array, dimension (LDS, K) Will contain the eigenvectors of the repaired matrix which will be stored for subsequent Z vector calculation and multiplied by the previously accumulated eigenvectors to update the system. LDS (input) INTEGER The leading dimension of S. LDS >= max( 1, K ). INFO (output) INTEGER = 0: successful exit. < 0: if INFO = -i, the i-th argument had an illegal value. > 0: if INFO = 1, an eigenvalue did not converge Further Details =============== Based on contributions by Jeff Rutter, Computer Science Division, University of California at Berkeley, USA ===================================================================== Test the input parameters. */ /* Parameter adjustments */ --d__; q_dim1 = *ldq; q_offset = 1 + q_dim1; q -= q_offset; --dlamda; --w; s_dim1 = *lds; s_offset = 1 + s_dim1; s -= s_offset; /* Function Body */ *info = 0; if (*k < 0) { *info = -1; } else if ((*kstart < 1) || (*kstart > max(1,*k))) { *info = -2; } else if ((max(1,*kstop) < *kstart) || (*kstop > max(1,*k))) { *info = -3; } else if (*n < *k) { *info = -4; } else if (*ldq < max(1,*k)) { *info = -7; } else if (*lds < max(1,*k)) { *info = -12; } if (*info != 0) { i__1 = -(*info); xerbla_("DLAED9", &i__1); return 0; } /* Quick return if possible */ if (*k == 0) { return 0; } /* Modify values DLAMDA(i) to make sure all DLAMDA(i)-DLAMDA(j) can be computed with high relative accuracy (barring over/underflow). This is a problem on machines without a guard digit in add/subtract (Cray XMP, Cray YMP, Cray C 90 and Cray 2). The following code replaces DLAMDA(I) by 2*DLAMDA(I)-DLAMDA(I), which on any of these machines zeros out the bottommost bit of DLAMDA(I) if it is 1; this makes the subsequent subtractions DLAMDA(I)-DLAMDA(J) unproblematic when cancellation occurs. On binary machines with a guard digit (almost all machines) it does not change DLAMDA(I) at all. On hexadecimal and decimal machines with a guard digit, it slightly changes the bottommost bits of DLAMDA(I). It does not account for hexadecimal or decimal machines without guard digits (we know of none). We use a subroutine call to compute 2*DLAMBDA(I) to prevent optimizing compilers from eliminating this code. */ i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { dlamda[i__] = dlamc3_(&dlamda[i__], &dlamda[i__]) - dlamda[i__]; /* L10: */ } i__1 = *kstop; for (j = *kstart; j <= i__1; ++j) { dlaed4_(k, &j, &dlamda[1], &w[1], &q[j * q_dim1 + 1], rho, &d__[j], info); /* If the zero finder fails, the computation is terminated. */ if (*info != 0) { goto L120; } /* L20: */ } if ((*k == 1) || (*k == 2)) { i__1 = *k; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = *k; for (j = 1; j <= i__2; ++j) { s[j + i__ * s_dim1] = q[j + i__ * q_dim1]; /* L30: */ } /* L40: */ } goto L120; } /* Compute updated W. */ dcopy_(k, &w[1], &c__1, &s[s_offset], &c__1); /* Initialize W(I) = Q(I,I) */ i__1 = *ldq + 1; dcopy_(k, &q[q_offset], &i__1, &w[1], &c__1); i__1 = *k; for (j = 1; j <= i__1; ++j) { i__2 = j - 1; for (i__ = 1; i__ <= i__2; ++i__) { w[i__] *= q[i__ + j * q_dim1] / (dlamda[i__] - dlamda[j]); /* L50: */ } i__2 = *k; for (i__ = j + 1; i__ <= i__2; ++i__) { w[i__] *= q[i__ + j * q_dim1] / (dlamda[i__] - dlamda[j]); /* L60: */ } /* L70: */ } i__1 = *k; for (i__ = 1; i__ <= i__1; ++i__) { d__1 = sqrt(-w[i__]); w[i__] = d_sign(&d__1, &s[i__ + s_dim1]); /* L80: */ } /* Compute eigenvectors of the modified rank-1 modification. */ i__1 = *k; for (j = 1; j <= i__1; ++j) { i__2 = *k; for (i__ = 1; i__ <= i__2; ++i__) { q[i__ + j * q_dim1] = w[i__] / q[i__ + j * q_dim1]; /* L90: */ } temp = dnrm2_(k, &q[j * q_dim1 + 1], &c__1); i__2 = *k; for (i__ = 1; i__ <= i__2; ++i__) { s[i__ + j * s_dim1] = q[i__ + j * q_dim1] / temp; /* L100: */ } /* L110: */ } L120: return 0; /* End of DLAED9 */ } /* dlaed9_ */ /* Subroutine */ int dlaeda_(integer *n, integer *tlvls, integer *curlvl, integer *curpbm, integer *prmptr, integer *perm, integer *givptr, integer *givcol, doublereal *givnum, doublereal *q, integer *qptr, doublereal *z__, doublereal *ztemp, integer *info) { /* System generated locals */ integer i__1, i__2, i__3; /* Builtin functions */ integer pow_ii(integer *, integer *); double sqrt(doublereal); /* Local variables */ static integer i__, k, mid, ptr; extern /* Subroutine */ int drot_(integer *, doublereal *, integer *, doublereal *, integer *, doublereal *, doublereal *); static integer curr, bsiz1, bsiz2, psiz1, psiz2, zptr1; extern /* Subroutine */ int dgemv_(char *, integer *, integer *, doublereal *, doublereal *, integer *, doublereal *, integer *, doublereal *, doublereal *, integer *), dcopy_(integer *, doublereal *, integer *, doublereal *, integer *), xerbla_(char *, integer *); /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University September 30, 1994 Purpose ======= DLAEDA computes the Z vector corresponding to the merge step in the CURLVLth step of the merge process with TLVLS steps for the CURPBMth problem. Arguments ========= N (input) INTEGER The dimension of the symmetric tridiagonal matrix. N >= 0. TLVLS (input) INTEGER The total number of merging levels in the overall divide and conquer tree. CURLVL (input) INTEGER The current level in the overall merge routine, 0 <= curlvl <= tlvls. CURPBM (input) INTEGER The current problem in the current level in the overall merge routine (counting from upper left to lower right). PRMPTR (input) INTEGER array, dimension (N lg N) Contains a list of pointers which indicate where in PERM a level's permutation is stored. PRMPTR(i+1) - PRMPTR(i) indicates the size of the permutation and incidentally the size of the full, non-deflated problem. PERM (input) INTEGER array, dimension (N lg N) Contains the permutations (from deflation and sorting) to be applied to each eigenblock. GIVPTR (input) INTEGER array, dimension (N lg N) Contains a list of pointers which indicate where in GIVCOL a level's Givens rotations are stored. GIVPTR(i+1) - GIVPTR(i) indicates the number of Givens rotations. GIVCOL (input) INTEGER array, dimension (2, N lg N) Each pair of numbers indicates a pair of columns to take place in a Givens rotation. GIVNUM (input) DOUBLE PRECISION array, dimension (2, N lg N) Each number indicates the S value to be used in the corresponding Givens rotation. Q (input) DOUBLE PRECISION array, dimension (N**2) Contains the square eigenblocks from previous levels, the starting positions for blocks are given by QPTR. QPTR (input) INTEGER array, dimension (N+2) Contains a list of pointers which indicate where in Q an eigenblock is stored. SQRT( QPTR(i+1) - QPTR(i) ) indicates the size of the block. Z (output) DOUBLE PRECISION array, dimension (N) On output this vector contains the updating vector (the last row of the first sub-eigenvector matrix and the first row of the second sub-eigenvector matrix). ZTEMP (workspace) DOUBLE PRECISION array, dimension (N) INFO (output) INTEGER = 0: successful exit. < 0: if INFO = -i, the i-th argument had an illegal value. Further Details =============== Based on contributions by Jeff Rutter, Computer Science Division, University of California at Berkeley, USA ===================================================================== Test the input parameters. */ /* Parameter adjustments */ --ztemp; --z__; --qptr; --q; givnum -= 3; givcol -= 3; --givptr; --perm; --prmptr; /* Function Body */ *info = 0; if (*n < 0) { *info = -1; } if (*info != 0) { i__1 = -(*info); xerbla_("DLAEDA", &i__1); return 0; } /* Quick return if possible */ if (*n == 0) { return 0; } /* Determine location of first number in second half. */ mid = *n / 2 + 1; /* Gather last/first rows of appropriate eigenblocks into center of Z */ ptr = 1; /* Determine location of lowest level subproblem in the full storage scheme */ i__1 = *curlvl - 1; curr = ptr + *curpbm * pow_ii(&c__2, curlvl) + pow_ii(&c__2, &i__1) - 1; /* Determine size of these matrices. We add HALF to the value of the SQRT in case the machine underestimates one of these square roots. */ bsiz1 = (integer) (sqrt((doublereal) (qptr[curr + 1] - qptr[curr])) + .5); bsiz2 = (integer) (sqrt((doublereal) (qptr[curr + 2] - qptr[curr + 1])) + .5); i__1 = mid - bsiz1 - 1; for (k = 1; k <= i__1; ++k) { z__[k] = 0.; /* L10: */ } dcopy_(&bsiz1, &q[qptr[curr] + bsiz1 - 1], &bsiz1, &z__[mid - bsiz1], & c__1); dcopy_(&bsiz2, &q[qptr[curr + 1]], &bsiz2, &z__[mid], &c__1); i__1 = *n; for (k = mid + bsiz2; k <= i__1; ++k) { z__[k] = 0.; /* L20: */ } /* Loop thru remaining levels 1 -> CURLVL applying the Givens rotations and permutation and then multiplying the center matrices against the current Z. */ ptr = pow_ii(&c__2, tlvls) + 1; i__1 = *curlvl - 1; for (k = 1; k <= i__1; ++k) { i__2 = *curlvl - k; i__3 = *curlvl - k - 1; curr = ptr + *curpbm * pow_ii(&c__2, &i__2) + pow_ii(&c__2, &i__3) - 1; psiz1 = prmptr[curr + 1] - prmptr[curr]; psiz2 = prmptr[curr + 2] - prmptr[curr + 1]; zptr1 = mid - psiz1; /* Apply Givens at CURR and CURR+1 */ i__2 = givptr[curr + 1] - 1; for (i__ = givptr[curr]; i__ <= i__2; ++i__) { drot_(&c__1, &z__[zptr1 + givcol[((i__) << (1)) + 1] - 1], &c__1, &z__[zptr1 + givcol[((i__) << (1)) + 2] - 1], &c__1, & givnum[((i__) << (1)) + 1], &givnum[((i__) << (1)) + 2]); /* L30: */ } i__2 = givptr[curr + 2] - 1; for (i__ = givptr[curr + 1]; i__ <= i__2; ++i__) { drot_(&c__1, &z__[mid - 1 + givcol[((i__) << (1)) + 1]], &c__1, & z__[mid - 1 + givcol[((i__) << (1)) + 2]], &c__1, &givnum[ ((i__) << (1)) + 1], &givnum[((i__) << (1)) + 2]); /* L40: */ } psiz1 = prmptr[curr + 1] - prmptr[curr]; psiz2 = prmptr[curr + 2] - prmptr[curr + 1]; i__2 = psiz1 - 1; for (i__ = 0; i__ <= i__2; ++i__) { ztemp[i__ + 1] = z__[zptr1 + perm[prmptr[curr] + i__] - 1]; /* L50: */ } i__2 = psiz2 - 1; for (i__ = 0; i__ <= i__2; ++i__) { ztemp[psiz1 + i__ + 1] = z__[mid + perm[prmptr[curr + 1] + i__] - 1]; /* L60: */ } /* Multiply Blocks at CURR and CURR+1 Determine size of these matrices. We add HALF to the value of the SQRT in case the machine underestimates one of these square roots. */ bsiz1 = (integer) (sqrt((doublereal) (qptr[curr + 1] - qptr[curr])) + .5); bsiz2 = (integer) (sqrt((doublereal) (qptr[curr + 2] - qptr[curr + 1]) ) + .5); if (bsiz1 > 0) { dgemv_("T", &bsiz1, &bsiz1, &c_b2865, &q[qptr[curr]], &bsiz1, & ztemp[1], &c__1, &c_b2879, &z__[zptr1], &c__1); } i__2 = psiz1 - bsiz1; dcopy_(&i__2, &ztemp[bsiz1 + 1], &c__1, &z__[zptr1 + bsiz1], &c__1); if (bsiz2 > 0) { dgemv_("T", &bsiz2, &bsiz2, &c_b2865, &q[qptr[curr + 1]], &bsiz2, &ztemp[psiz1 + 1], &c__1, &c_b2879, &z__[mid], &c__1); } i__2 = psiz2 - bsiz2; dcopy_(&i__2, &ztemp[psiz1 + bsiz2 + 1], &c__1, &z__[mid + bsiz2], & c__1); i__2 = *tlvls - k; ptr += pow_ii(&c__2, &i__2); /* L70: */ } return 0; /* End of DLAEDA */ } /* dlaeda_ */ /* Subroutine */ int dlaev2_(doublereal *a, doublereal *b, doublereal *c__, doublereal *rt1, doublereal *rt2, doublereal *cs1, doublereal *sn1) { /* System generated locals */ doublereal d__1; /* Builtin functions */ double sqrt(doublereal); /* Local variables */ static doublereal ab, df, cs, ct, tb, sm, tn, rt, adf, acs; static integer sgn1, sgn2; static doublereal acmn, acmx; /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University October 31, 1992 Purpose ======= DLAEV2 computes the eigendecomposition of a 2-by-2 symmetric matrix [ A B ] [ B C ]. On return, RT1 is the eigenvalue of larger absolute value, RT2 is the eigenvalue of smaller absolute value, and (CS1,SN1) is the unit right eigenvector for RT1, giving the decomposition [ CS1 SN1 ] [ A B ] [ CS1 -SN1 ] = [ RT1 0 ] [-SN1 CS1 ] [ B C ] [ SN1 CS1 ] [ 0 RT2 ]. Arguments ========= A (input) DOUBLE PRECISION The (1,1) element of the 2-by-2 matrix. B (input) DOUBLE PRECISION The (1,2) element and the conjugate of the (2,1) element of the 2-by-2 matrix. C (input) DOUBLE PRECISION The (2,2) element of the 2-by-2 matrix. RT1 (output) DOUBLE PRECISION The eigenvalue of larger absolute value. RT2 (output) DOUBLE PRECISION The eigenvalue of smaller absolute value. CS1 (output) DOUBLE PRECISION SN1 (output) DOUBLE PRECISION The vector (CS1, SN1) is a unit right eigenvector for RT1. Further Details =============== RT1 is accurate to a few ulps barring over/underflow. RT2 may be inaccurate if there is massive cancellation in the determinant A*C-B*B; higher precision or correctly rounded or correctly truncated arithmetic would be needed to compute RT2 accurately in all cases. CS1 and SN1 are accurate to a few ulps barring over/underflow. Overflow is possible only if RT1 is within a factor of 5 of overflow. Underflow is harmless if the input data is 0 or exceeds underflow_threshold / macheps. ===================================================================== Compute the eigenvalues */ sm = *a + *c__; df = *a - *c__; adf = abs(df); tb = *b + *b; ab = abs(tb); if (abs(*a) > abs(*c__)) { acmx = *a; acmn = *c__; } else { acmx = *c__; acmn = *a; } if (adf > ab) { /* Computing 2nd power */ d__1 = ab / adf; rt = adf * sqrt(d__1 * d__1 + 1.); } else if (adf < ab) { /* Computing 2nd power */ d__1 = adf / ab; rt = ab * sqrt(d__1 * d__1 + 1.); } else { /* Includes case AB=ADF=0 */ rt = ab * sqrt(2.); } if (sm < 0.) { *rt1 = (sm - rt) * .5; sgn1 = -1; /* Order of execution important. To get fully accurate smaller eigenvalue, next line needs to be executed in higher precision. */ *rt2 = acmx / *rt1 * acmn - *b / *rt1 * *b; } else if (sm > 0.) { *rt1 = (sm + rt) * .5; sgn1 = 1; /* Order of execution important. To get fully accurate smaller eigenvalue, next line needs to be executed in higher precision. */ *rt2 = acmx / *rt1 * acmn - *b / *rt1 * *b; } else { /* Includes case RT1 = RT2 = 0 */ *rt1 = rt * .5; *rt2 = rt * -.5; sgn1 = 1; } /* Compute the eigenvector */ if (df >= 0.) { cs = df + rt; sgn2 = 1; } else { cs = df - rt; sgn2 = -1; } acs = abs(cs); if (acs > ab) { ct = -tb / cs; *sn1 = 1. / sqrt(ct * ct + 1.); *cs1 = ct * *sn1; } else { if (ab == 0.) { *cs1 = 1.; *sn1 = 0.; } else { tn = -cs / tb; *cs1 = 1. / sqrt(tn * tn + 1.); *sn1 = tn * *cs1; } } if (sgn1 == sgn2) { tn = *cs1; *cs1 = -(*sn1); *sn1 = tn; } return 0; /* End of DLAEV2 */ } /* dlaev2_ */ /* Subroutine */ int dlahqr_(logical *wantt, logical *wantz, integer *n, integer *ilo, integer *ihi, doublereal *h__, integer *ldh, doublereal *wr, doublereal *wi, integer *iloz, integer *ihiz, doublereal *z__, integer *ldz, integer *info) { /* System generated locals */ integer h_dim1, h_offset, z_dim1, z_offset, i__1, i__2, i__3, i__4; doublereal d__1, d__2; /* Builtin functions */ double sqrt(doublereal), d_sign(doublereal *, doublereal *); /* Local variables */ static integer i__, j, k, l, m; static doublereal s, v[3]; static integer i1, i2; static doublereal t1, t2, t3, v1, v2, v3, h00, h10, h11, h12, h21, h22, h33, h44; static integer nh; static doublereal cs; static integer nr; static doublereal sn; static integer nz; static doublereal ave, h33s, h44s; static integer itn, its; static doublereal ulp, sum, tst1, h43h34, disc, unfl, ovfl; extern /* Subroutine */ int drot_(integer *, doublereal *, integer *, doublereal *, integer *, doublereal *, doublereal *); static doublereal work[1]; extern /* Subroutine */ int dcopy_(integer *, doublereal *, integer *, doublereal *, integer *), dlanv2_(doublereal *, doublereal *, doublereal *, doublereal *, doublereal *, doublereal *, doublereal *, doublereal *, doublereal *, doublereal *), dlabad_( doublereal *, doublereal *); extern /* Subroutine */ int dlarfg_(integer *, doublereal *, doublereal *, integer *, doublereal *); extern doublereal dlanhs_(char *, integer *, doublereal *, integer *, doublereal *); static doublereal smlnum; /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= DLAHQR is an auxiliary routine called by DHSEQR to update the eigenvalues and Schur decomposition already computed by DHSEQR, by dealing with the Hessenberg submatrix in rows and columns ILO to IHI. Arguments ========= WANTT (input) LOGICAL = .TRUE. : the full Schur form T is required; = .FALSE.: only eigenvalues are required. WANTZ (input) LOGICAL = .TRUE. : the matrix of Schur vectors Z is required; = .FALSE.: Schur vectors are not required. N (input) INTEGER The order of the matrix H. N >= 0. ILO (input) INTEGER IHI (input) INTEGER It is assumed that H is already upper quasi-triangular in rows and columns IHI+1:N, and that H(ILO,ILO-1) = 0 (unless ILO = 1). DLAHQR works primarily with the Hessenberg submatrix in rows and columns ILO to IHI, but applies transformations to all of H if WANTT is .TRUE.. 1 <= ILO <= max(1,IHI); IHI <= N. H (input/output) DOUBLE PRECISION array, dimension (LDH,N) On entry, the upper Hessenberg matrix H. On exit, if WANTT is .TRUE., H is upper quasi-triangular in rows and columns ILO:IHI, with any 2-by-2 diagonal blocks in standard form. If WANTT is .FALSE., the contents of H are unspecified on exit. LDH (input) INTEGER The leading dimension of the array H. LDH >= max(1,N). WR (output) DOUBLE PRECISION array, dimension (N) WI (output) DOUBLE PRECISION array, dimension (N) The real and imaginary parts, respectively, of the computed eigenvalues ILO to IHI are stored in the corresponding elements of WR and WI. If two eigenvalues are computed as a complex conjugate pair, they are stored in consecutive elements of WR and WI, say the i-th and (i+1)th, with WI(i) > 0 and WI(i+1) < 0. If WANTT is .TRUE., the eigenvalues are stored in the same order as on the diagonal of the Schur form returned in H, with WR(i) = H(i,i), and, if H(i:i+1,i:i+1) is a 2-by-2 diagonal block, WI(i) = sqrt(H(i+1,i)*H(i,i+1)) and WI(i+1) = -WI(i). ILOZ (input) INTEGER IHIZ (input) INTEGER Specify the rows of Z to which transformations must be applied if WANTZ is .TRUE.. 1 <= ILOZ <= ILO; IHI <= IHIZ <= N. Z (input/output) DOUBLE PRECISION array, dimension (LDZ,N) If WANTZ is .TRUE., on entry Z must contain the current matrix Z of transformations accumulated by DHSEQR, and on exit Z has been updated; transformations are applied only to the submatrix Z(ILOZ:IHIZ,ILO:IHI). If WANTZ is .FALSE., Z is not referenced. LDZ (input) INTEGER The leading dimension of the array Z. LDZ >= max(1,N). INFO (output) INTEGER = 0: successful exit > 0: DLAHQR failed to compute all the eigenvalues ILO to IHI in a total of 30*(IHI-ILO+1) iterations; if INFO = i, elements i+1:ihi of WR and WI contain those eigenvalues which have been successfully computed. Further Details =============== 2-96 Based on modifications by David Day, Sandia National Laboratory, USA ===================================================================== */ /* Parameter adjustments */ h_dim1 = *ldh; h_offset = 1 + h_dim1; h__ -= h_offset; --wr; --wi; z_dim1 = *ldz; z_offset = 1 + z_dim1; z__ -= z_offset; /* Function Body */ *info = 0; /* Quick return if possible */ if (*n == 0) { return 0; } if (*ilo == *ihi) { wr[*ilo] = h__[*ilo + *ilo * h_dim1]; wi[*ilo] = 0.; return 0; } nh = *ihi - *ilo + 1; nz = *ihiz - *iloz + 1; /* Set machine-dependent constants for the stopping criterion. If norm(H) <= sqrt(OVFL), overflow should not occur. */ unfl = SAFEMINIMUM; ovfl = 1. / unfl; dlabad_(&unfl, &ovfl); ulp = PRECISION; smlnum = unfl * (nh / ulp); /* I1 and I2 are the indices of the first row and last column of H to which transformations must be applied. If eigenvalues only are being computed, I1 and I2 are set inside the main loop. */ if (*wantt) { i1 = 1; i2 = *n; } /* ITN is the total number of QR iterations allowed. */ itn = nh * 30; /* The main loop begins here. I is the loop index and decreases from IHI to ILO in steps of 1 or 2. Each iteration of the loop works with the active submatrix in rows and columns L to I. Eigenvalues I+1 to IHI have already converged. Either L = ILO or H(L,L-1) is negligible so that the matrix splits. */ i__ = *ihi; L10: l = *ilo; if (i__ < *ilo) { goto L150; } /* Perform QR iterations on rows and columns ILO to I until a submatrix of order 1 or 2 splits off at the bottom because a subdiagonal element has become negligible. */ i__1 = itn; for (its = 0; its <= i__1; ++its) { /* Look for a single small subdiagonal element. */ i__2 = l + 1; for (k = i__; k >= i__2; --k) { tst1 = (d__1 = h__[k - 1 + (k - 1) * h_dim1], abs(d__1)) + (d__2 = h__[k + k * h_dim1], abs(d__2)); if (tst1 == 0.) { i__3 = i__ - l + 1; tst1 = dlanhs_("1", &i__3, &h__[l + l * h_dim1], ldh, work); } /* Computing MAX */ d__2 = ulp * tst1; if ((d__1 = h__[k + (k - 1) * h_dim1], abs(d__1)) <= max(d__2, smlnum)) { goto L30; } /* L20: */ } L30: l = k; if (l > *ilo) { /* H(L,L-1) is negligible */ h__[l + (l - 1) * h_dim1] = 0.; } /* Exit from loop if a submatrix of order 1 or 2 has split off. */ if (l >= i__ - 1) { goto L140; } /* Now the active submatrix is in rows and columns L to I. If eigenvalues only are being computed, only the active submatrix need be transformed. */ if (! (*wantt)) { i1 = l; i2 = i__; } if ((its == 10) || (its == 20)) { /* Exceptional shift. */ s = (d__1 = h__[i__ + (i__ - 1) * h_dim1], abs(d__1)) + (d__2 = h__[i__ - 1 + (i__ - 2) * h_dim1], abs(d__2)); h44 = s * .75 + h__[i__ + i__ * h_dim1]; h33 = h44; h43h34 = s * -.4375 * s; } else { /* Prepare to use Francis' double shift (i.e. 2nd degree generalized Rayleigh quotient) */ h44 = h__[i__ + i__ * h_dim1]; h33 = h__[i__ - 1 + (i__ - 1) * h_dim1]; h43h34 = h__[i__ + (i__ - 1) * h_dim1] * h__[i__ - 1 + i__ * h_dim1]; s = h__[i__ - 1 + (i__ - 2) * h_dim1] * h__[i__ - 1 + (i__ - 2) * h_dim1]; disc = (h33 - h44) * .5; disc = disc * disc + h43h34; if (disc > 0.) { /* Real roots: use Wilkinson's shift twice */ disc = sqrt(disc); ave = (h33 + h44) * .5; if (abs(h33) - abs(h44) > 0.) { h33 = h33 * h44 - h43h34; h44 = h33 / (d_sign(&disc, &ave) + ave); } else { h44 = d_sign(&disc, &ave) + ave; } h33 = h44; h43h34 = 0.; } } /* Look for two consecutive small subdiagonal elements. */ i__2 = l; for (m = i__ - 2; m >= i__2; --m) { /* Determine the effect of starting the double-shift QR iteration at row M, and see if this would make H(M,M-1) negligible. */ h11 = h__[m + m * h_dim1]; h22 = h__[m + 1 + (m + 1) * h_dim1]; h21 = h__[m + 1 + m * h_dim1]; h12 = h__[m + (m + 1) * h_dim1]; h44s = h44 - h11; h33s = h33 - h11; v1 = (h33s * h44s - h43h34) / h21 + h12; v2 = h22 - h11 - h33s - h44s; v3 = h__[m + 2 + (m + 1) * h_dim1]; s = abs(v1) + abs(v2) + abs(v3); v1 /= s; v2 /= s; v3 /= s; v[0] = v1; v[1] = v2; v[2] = v3; if (m == l) { goto L50; } h00 = h__[m - 1 + (m - 1) * h_dim1]; h10 = h__[m + (m - 1) * h_dim1]; tst1 = abs(v1) * (abs(h00) + abs(h11) + abs(h22)); if (abs(h10) * (abs(v2) + abs(v3)) <= ulp * tst1) { goto L50; } /* L40: */ } L50: /* Double-shift QR step */ i__2 = i__ - 1; for (k = m; k <= i__2; ++k) { /* The first iteration of this loop determines a reflection G from the vector V and applies it from left and right to H, thus creating a nonzero bulge below the subdiagonal. Each subsequent iteration determines a reflection G to restore the Hessenberg form in the (K-1)th column, and thus chases the bulge one step toward the bottom of the active submatrix. NR is the order of G. Computing MIN */ i__3 = 3, i__4 = i__ - k + 1; nr = min(i__3,i__4); if (k > m) { dcopy_(&nr, &h__[k + (k - 1) * h_dim1], &c__1, v, &c__1); } dlarfg_(&nr, v, &v[1], &c__1, &t1); if (k > m) { h__[k + (k - 1) * h_dim1] = v[0]; h__[k + 1 + (k - 1) * h_dim1] = 0.; if (k < i__ - 1) { h__[k + 2 + (k - 1) * h_dim1] = 0.; } } else if (m > l) { h__[k + (k - 1) * h_dim1] = -h__[k + (k - 1) * h_dim1]; } v2 = v[1]; t2 = t1 * v2; if (nr == 3) { v3 = v[2]; t3 = t1 * v3; /* Apply G from the left to transform the rows of the matrix in columns K to I2. */ i__3 = i2; for (j = k; j <= i__3; ++j) { sum = h__[k + j * h_dim1] + v2 * h__[k + 1 + j * h_dim1] + v3 * h__[k + 2 + j * h_dim1]; h__[k + j * h_dim1] -= sum * t1; h__[k + 1 + j * h_dim1] -= sum * t2; h__[k + 2 + j * h_dim1] -= sum * t3; /* L60: */ } /* Apply G from the right to transform the columns of the matrix in rows I1 to min(K+3,I). Computing MIN */ i__4 = k + 3; i__3 = min(i__4,i__); for (j = i1; j <= i__3; ++j) { sum = h__[j + k * h_dim1] + v2 * h__[j + (k + 1) * h_dim1] + v3 * h__[j + (k + 2) * h_dim1]; h__[j + k * h_dim1] -= sum * t1; h__[j + (k + 1) * h_dim1] -= sum * t2; h__[j + (k + 2) * h_dim1] -= sum * t3; /* L70: */ } if (*wantz) { /* Accumulate transformations in the matrix Z */ i__3 = *ihiz; for (j = *iloz; j <= i__3; ++j) { sum = z__[j + k * z_dim1] + v2 * z__[j + (k + 1) * z_dim1] + v3 * z__[j + (k + 2) * z_dim1]; z__[j + k * z_dim1] -= sum * t1; z__[j + (k + 1) * z_dim1] -= sum * t2; z__[j + (k + 2) * z_dim1] -= sum * t3; /* L80: */ } } } else if (nr == 2) { /* Apply G from the left to transform the rows of the matrix in columns K to I2. */ i__3 = i2; for (j = k; j <= i__3; ++j) { sum = h__[k + j * h_dim1] + v2 * h__[k + 1 + j * h_dim1]; h__[k + j * h_dim1] -= sum * t1; h__[k + 1 + j * h_dim1] -= sum * t2; /* L90: */ } /* Apply G from the right to transform the columns of the matrix in rows I1 to min(K+3,I). */ i__3 = i__; for (j = i1; j <= i__3; ++j) { sum = h__[j + k * h_dim1] + v2 * h__[j + (k + 1) * h_dim1] ; h__[j + k * h_dim1] -= sum * t1; h__[j + (k + 1) * h_dim1] -= sum * t2; /* L100: */ } if (*wantz) { /* Accumulate transformations in the matrix Z */ i__3 = *ihiz; for (j = *iloz; j <= i__3; ++j) { sum = z__[j + k * z_dim1] + v2 * z__[j + (k + 1) * z_dim1]; z__[j + k * z_dim1] -= sum * t1; z__[j + (k + 1) * z_dim1] -= sum * t2; /* L110: */ } } } /* L120: */ } /* L130: */ } /* Failure to converge in remaining number of iterations */ *info = i__; return 0; L140: if (l == i__) { /* H(I,I-1) is negligible: one eigenvalue has converged. */ wr[i__] = h__[i__ + i__ * h_dim1]; wi[i__] = 0.; } else if (l == i__ - 1) { /* H(I-1,I-2) is negligible: a pair of eigenvalues have converged. Transform the 2-by-2 submatrix to standard Schur form, and compute and store the eigenvalues. */ dlanv2_(&h__[i__ - 1 + (i__ - 1) * h_dim1], &h__[i__ - 1 + i__ * h_dim1], &h__[i__ + (i__ - 1) * h_dim1], &h__[i__ + i__ * h_dim1], &wr[i__ - 1], &wi[i__ - 1], &wr[i__], &wi[i__], &cs, &sn); if (*wantt) { /* Apply the transformation to the rest of H. */ if (i2 > i__) { i__1 = i2 - i__; drot_(&i__1, &h__[i__ - 1 + (i__ + 1) * h_dim1], ldh, &h__[ i__ + (i__ + 1) * h_dim1], ldh, &cs, &sn); } i__1 = i__ - i1 - 1; drot_(&i__1, &h__[i1 + (i__ - 1) * h_dim1], &c__1, &h__[i1 + i__ * h_dim1], &c__1, &cs, &sn); } if (*wantz) { /* Apply the transformation to Z. */ drot_(&nz, &z__[*iloz + (i__ - 1) * z_dim1], &c__1, &z__[*iloz + i__ * z_dim1], &c__1, &cs, &sn); } } /* Decrement number of remaining iterations, and return to start of the main loop with new value of I. */ itn -= its; i__ = l - 1; goto L10; L150: return 0; /* End of DLAHQR */ } /* dlahqr_ */ /* Subroutine */ int dlahrd_(integer *n, integer *k, integer *nb, doublereal * a, integer *lda, doublereal *tau, doublereal *t, integer *ldt, doublereal *y, integer *ldy) { /* System generated locals */ integer a_dim1, a_offset, t_dim1, t_offset, y_dim1, y_offset, i__1, i__2, i__3; doublereal d__1; /* Local variables */ static integer i__; static doublereal ei; extern /* Subroutine */ int dscal_(integer *, doublereal *, doublereal *, integer *), dgemv_(char *, integer *, integer *, doublereal *, doublereal *, integer *, doublereal *, integer *, doublereal *, doublereal *, integer *), dcopy_(integer *, doublereal *, integer *, doublereal *, integer *), daxpy_(integer *, doublereal *, doublereal *, integer *, doublereal *, integer *), dtrmv_(char *, char *, char *, integer *, doublereal *, integer *, doublereal *, integer *), dlarfg_(integer *, doublereal *, doublereal *, integer *, doublereal *); /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= DLAHRD reduces the first NB columns of a real general n-by-(n-k+1) matrix A so that elements below the k-th subdiagonal are zero. The reduction is performed by an orthogonal similarity transformation Q' * A * Q. The routine returns the matrices V and T which determine Q as a block reflector I - V*T*V', and also the matrix Y = A * V * T. This is an auxiliary routine called by DGEHRD. Arguments ========= N (input) INTEGER The order of the matrix A. K (input) INTEGER The offset for the reduction. Elements below the k-th subdiagonal in the first NB columns are reduced to zero. NB (input) INTEGER The number of columns to be reduced. A (input/output) DOUBLE PRECISION array, dimension (LDA,N-K+1) On entry, the n-by-(n-k+1) general matrix A. On exit, the elements on and above the k-th subdiagonal in the first NB columns are overwritten with the corresponding elements of the reduced matrix; the elements below the k-th subdiagonal, with the array TAU, represent the matrix Q as a product of elementary reflectors. The other columns of A are unchanged. See Further Details. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,N). TAU (output) DOUBLE PRECISION array, dimension (NB) The scalar factors of the elementary reflectors. See Further Details. T (output) DOUBLE PRECISION array, dimension (LDT,NB) The upper triangular matrix T. LDT (input) INTEGER The leading dimension of the array T. LDT >= NB. Y (output) DOUBLE PRECISION array, dimension (LDY,NB) The n-by-nb matrix Y. LDY (input) INTEGER The leading dimension of the array Y. LDY >= N. Further Details =============== The matrix Q is represented as a product of nb elementary reflectors Q = H(1) H(2) . . . H(nb). Each H(i) has the form H(i) = I - tau * v * v' where tau is a real scalar, and v is a real vector with v(1:i+k-1) = 0, v(i+k) = 1; v(i+k+1:n) is stored on exit in A(i+k+1:n,i), and tau in TAU(i). The elements of the vectors v together form the (n-k+1)-by-nb matrix V which is needed, with T and Y, to apply the transformation to the unreduced part of the matrix, using an update of the form: A := (I - V*T*V') * (A - Y*V'). The contents of A on exit are illustrated by the following example with n = 7, k = 3 and nb = 2: ( a h a a a ) ( a h a a a ) ( a h a a a ) ( h h a a a ) ( v1 h a a a ) ( v1 v2 a a a ) ( v1 v2 a a a ) where a denotes an element of the original matrix A, h denotes a modified element of the upper Hessenberg matrix H, and vi denotes an element of the vector defining H(i). ===================================================================== Quick return if possible */ /* Parameter adjustments */ --tau; a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; t_dim1 = *ldt; t_offset = 1 + t_dim1; t -= t_offset; y_dim1 = *ldy; y_offset = 1 + y_dim1; y -= y_offset; /* Function Body */ if (*n <= 1) { return 0; } i__1 = *nb; for (i__ = 1; i__ <= i__1; ++i__) { if (i__ > 1) { /* Update A(1:n,i) Compute i-th column of A - Y * V' */ i__2 = i__ - 1; dgemv_("No transpose", n, &i__2, &c_b3001, &y[y_offset], ldy, &a[* k + i__ - 1 + a_dim1], lda, &c_b2865, &a[i__ * a_dim1 + 1] , &c__1); /* Apply I - V * T' * V' to this column (call it b) from the left, using the last column of T as workspace Let V = ( V1 ) and b = ( b1 ) (first I-1 rows) ( V2 ) ( b2 ) where V1 is unit lower triangular w := V1' * b1 */ i__2 = i__ - 1; dcopy_(&i__2, &a[*k + 1 + i__ * a_dim1], &c__1, &t[*nb * t_dim1 + 1], &c__1); i__2 = i__ - 1; dtrmv_("Lower", "Transpose", "Unit", &i__2, &a[*k + 1 + a_dim1], lda, &t[*nb * t_dim1 + 1], &c__1); /* w := w + V2'*b2 */ i__2 = *n - *k - i__ + 1; i__3 = i__ - 1; dgemv_("Transpose", &i__2, &i__3, &c_b2865, &a[*k + i__ + a_dim1], lda, &a[*k + i__ + i__ * a_dim1], &c__1, &c_b2865, &t[* nb * t_dim1 + 1], &c__1); /* w := T'*w */ i__2 = i__ - 1; dtrmv_("Upper", "Transpose", "Non-unit", &i__2, &t[t_offset], ldt, &t[*nb * t_dim1 + 1], &c__1); /* b2 := b2 - V2*w */ i__2 = *n - *k - i__ + 1; i__3 = i__ - 1; dgemv_("No transpose", &i__2, &i__3, &c_b3001, &a[*k + i__ + a_dim1], lda, &t[*nb * t_dim1 + 1], &c__1, &c_b2865, &a[* k + i__ + i__ * a_dim1], &c__1); /* b1 := b1 - V1*w */ i__2 = i__ - 1; dtrmv_("Lower", "No transpose", "Unit", &i__2, &a[*k + 1 + a_dim1] , lda, &t[*nb * t_dim1 + 1], &c__1); i__2 = i__ - 1; daxpy_(&i__2, &c_b3001, &t[*nb * t_dim1 + 1], &c__1, &a[*k + 1 + i__ * a_dim1], &c__1); a[*k + i__ - 1 + (i__ - 1) * a_dim1] = ei; } /* Generate the elementary reflector H(i) to annihilate A(k+i+1:n,i) */ i__2 = *n - *k - i__ + 1; /* Computing MIN */ i__3 = *k + i__ + 1; dlarfg_(&i__2, &a[*k + i__ + i__ * a_dim1], &a[min(i__3,*n) + i__ * a_dim1], &c__1, &tau[i__]); ei = a[*k + i__ + i__ * a_dim1]; a[*k + i__ + i__ * a_dim1] = 1.; /* Compute Y(1:n,i) */ i__2 = *n - *k - i__ + 1; dgemv_("No transpose", n, &i__2, &c_b2865, &a[(i__ + 1) * a_dim1 + 1], lda, &a[*k + i__ + i__ * a_dim1], &c__1, &c_b2879, &y[i__ * y_dim1 + 1], &c__1); i__2 = *n - *k - i__ + 1; i__3 = i__ - 1; dgemv_("Transpose", &i__2, &i__3, &c_b2865, &a[*k + i__ + a_dim1], lda, &a[*k + i__ + i__ * a_dim1], &c__1, &c_b2879, &t[i__ * t_dim1 + 1], &c__1); i__2 = i__ - 1; dgemv_("No transpose", n, &i__2, &c_b3001, &y[y_offset], ldy, &t[i__ * t_dim1 + 1], &c__1, &c_b2865, &y[i__ * y_dim1 + 1], &c__1); dscal_(n, &tau[i__], &y[i__ * y_dim1 + 1], &c__1); /* Compute T(1:i,i) */ i__2 = i__ - 1; d__1 = -tau[i__]; dscal_(&i__2, &d__1, &t[i__ * t_dim1 + 1], &c__1); i__2 = i__ - 1; dtrmv_("Upper", "No transpose", "Non-unit", &i__2, &t[t_offset], ldt, &t[i__ * t_dim1 + 1], &c__1) ; t[i__ + i__ * t_dim1] = tau[i__]; /* L10: */ } a[*k + *nb + *nb * a_dim1] = ei; return 0; /* End of DLAHRD */ } /* dlahrd_ */ /* Subroutine */ int dlaln2_(logical *ltrans, integer *na, integer *nw, doublereal *smin, doublereal *ca, doublereal *a, integer *lda, doublereal *d1, doublereal *d2, doublereal *b, integer *ldb, doublereal *wr, doublereal *wi, doublereal *x, integer *ldx, doublereal *scale, doublereal *xnorm, integer *info) { /* Initialized data */ static logical zswap[4] = { FALSE_,FALSE_,TRUE_,TRUE_ }; static logical rswap[4] = { FALSE_,TRUE_,FALSE_,TRUE_ }; static integer ipivot[16] /* was [4][4] */ = { 1,2,3,4,2,1,4,3,3,4,1,2, 4,3,2,1 }; /* System generated locals */ integer a_dim1, a_offset, b_dim1, b_offset, x_dim1, x_offset; doublereal d__1, d__2, d__3, d__4, d__5, d__6; static doublereal equiv_0[4], equiv_1[4]; /* Local variables */ static integer j; #define ci (equiv_0) #define cr (equiv_1) static doublereal bi1, bi2, br1, br2, xi1, xi2, xr1, xr2, ci21, ci22, cr21, cr22, li21, csi, ui11, lr21, ui12, ui22; #define civ (equiv_0) static doublereal csr, ur11, ur12, ur22; #define crv (equiv_1) static doublereal bbnd, cmax, ui11r, ui12s, temp, ur11r, ur12s, u22abs; static integer icmax; static doublereal bnorm, cnorm, smini; extern /* Subroutine */ int dladiv_(doublereal *, doublereal *, doublereal *, doublereal *, doublereal *, doublereal *); static doublereal bignum, smlnum; /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University October 31, 1992 Purpose ======= DLALN2 solves a system of the form (ca A - w D ) X = s B or (ca A' - w D) X = s B with possible scaling ("s") and perturbation of A. (A' means A-transpose.) A is an NA x NA real matrix, ca is a real scalar, D is an NA x NA real diagonal matrix, w is a real or complex value, and X and B are NA x 1 matrices -- real if w is real, complex if w is complex. NA may be 1 or 2. If w is complex, X and B are represented as NA x 2 matrices, the first column of each being the real part and the second being the imaginary part. "s" is a scaling factor (.LE. 1), computed by DLALN2, which is so chosen that X can be computed without overflow. X is further scaled if necessary to assure that norm(ca A - w D)*norm(X) is less than overflow. If both singular values of (ca A - w D) are less than SMIN, SMIN*identity will be used instead of (ca A - w D). If only one singular value is less than SMIN, one element of (ca A - w D) will be perturbed enough to make the smallest singular value roughly SMIN. If both singular values are at least SMIN, (ca A - w D) will not be perturbed. In any case, the perturbation will be at most some small multiple of max( SMIN, ulp*norm(ca A - w D) ). The singular values are computed by infinity-norm approximations, and thus will only be correct to a factor of 2 or so. Note: all input quantities are assumed to be smaller than overflow by a reasonable factor. (See BIGNUM.) Arguments ========== LTRANS (input) LOGICAL =.TRUE.: A-transpose will be used. =.FALSE.: A will be used (not transposed.) NA (input) INTEGER The size of the matrix A. It may (only) be 1 or 2. NW (input) INTEGER 1 if "w" is real, 2 if "w" is complex. It may only be 1 or 2. SMIN (input) DOUBLE PRECISION The desired lower bound on the singular values of A. This should be a safe distance away from underflow or overflow, say, between (underflow/machine precision) and (machine precision * overflow ). (See BIGNUM and ULP.) CA (input) DOUBLE PRECISION The coefficient c, which A is multiplied by. A (input) DOUBLE PRECISION array, dimension (LDA,NA) The NA x NA matrix A. LDA (input) INTEGER The leading dimension of A. It must be at least NA. D1 (input) DOUBLE PRECISION The 1,1 element in the diagonal matrix D. D2 (input) DOUBLE PRECISION The 2,2 element in the diagonal matrix D. Not used if NW=1. B (input) DOUBLE PRECISION array, dimension (LDB,NW) The NA x NW matrix B (right-hand side). If NW=2 ("w" is complex), column 1 contains the real part of B and column 2 contains the imaginary part. LDB (input) INTEGER The leading dimension of B. It must be at least NA. WR (input) DOUBLE PRECISION The real part of the scalar "w". WI (input) DOUBLE PRECISION The imaginary part of the scalar "w". Not used if NW=1. X (output) DOUBLE PRECISION array, dimension (LDX,NW) The NA x NW matrix X (unknowns), as computed by DLALN2. If NW=2 ("w" is complex), on exit, column 1 will contain the real part of X and column 2 will contain the imaginary part. LDX (input) INTEGER The leading dimension of X. It must be at least NA. SCALE (output) DOUBLE PRECISION The scale factor that B must be multiplied by to insure that overflow does not occur when computing X. Thus, (ca A - w D) X will be SCALE*B, not B (ignoring perturbations of A.) It will be at most 1. XNORM (output) DOUBLE PRECISION The infinity-norm of X, when X is regarded as an NA x NW real matrix. INFO (output) INTEGER An error flag. It will be set to zero if no error occurs, a negative number if an argument is in error, or a positive number if ca A - w D had to be perturbed. The possible values are: = 0: No error occurred, and (ca A - w D) did not have to be perturbed. = 1: (ca A - w D) had to be perturbed to make its smallest (or only) singular value greater than SMIN. NOTE: In the interests of speed, this routine does not check the inputs for errors. ===================================================================== */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; b_dim1 = *ldb; b_offset = 1 + b_dim1; b -= b_offset; x_dim1 = *ldx; x_offset = 1 + x_dim1; x -= x_offset; /* Function Body */ /* Compute BIGNUM */ smlnum = 2. * SAFEMINIMUM; bignum = 1. / smlnum; smini = max(*smin,smlnum); /* Don't check for input errors */ *info = 0; /* Standard Initializations */ *scale = 1.; if (*na == 1) { /* 1 x 1 (i.e., scalar) system C X = B */ if (*nw == 1) { /* Real 1x1 system. C = ca A - w D */ csr = *ca * a[a_dim1 + 1] - *wr * *d1; cnorm = abs(csr); /* If | C | < SMINI, use C = SMINI */ if (cnorm < smini) { csr = smini; cnorm = smini; *info = 1; } /* Check scaling for X = B / C */ bnorm = (d__1 = b[b_dim1 + 1], abs(d__1)); if (cnorm < 1. && bnorm > 1.) { if (bnorm > bignum * cnorm) { *scale = 1. / bnorm; } } /* Compute X */ x[x_dim1 + 1] = b[b_dim1 + 1] * *scale / csr; *xnorm = (d__1 = x[x_dim1 + 1], abs(d__1)); } else { /* Complex 1x1 system (w is complex) C = ca A - w D */ csr = *ca * a[a_dim1 + 1] - *wr * *d1; csi = -(*wi) * *d1; cnorm = abs(csr) + abs(csi); /* If | C | < SMINI, use C = SMINI */ if (cnorm < smini) { csr = smini; csi = 0.; cnorm = smini; *info = 1; } /* Check scaling for X = B / C */ bnorm = (d__1 = b[b_dim1 + 1], abs(d__1)) + (d__2 = b[((b_dim1) << (1)) + 1], abs(d__2)); if (cnorm < 1. && bnorm > 1.) { if (bnorm > bignum * cnorm) { *scale = 1. / bnorm; } } /* Compute X */ d__1 = *scale * b[b_dim1 + 1]; d__2 = *scale * b[((b_dim1) << (1)) + 1]; dladiv_(&d__1, &d__2, &csr, &csi, &x[x_dim1 + 1], &x[((x_dim1) << (1)) + 1]); *xnorm = (d__1 = x[x_dim1 + 1], abs(d__1)) + (d__2 = x[((x_dim1) << (1)) + 1], abs(d__2)); } } else { /* 2x2 System Compute the real part of C = ca A - w D (or ca A' - w D ) */ cr[0] = *ca * a[a_dim1 + 1] - *wr * *d1; cr[3] = *ca * a[((a_dim1) << (1)) + 2] - *wr * *d2; if (*ltrans) { cr[2] = *ca * a[a_dim1 + 2]; cr[1] = *ca * a[((a_dim1) << (1)) + 1]; } else { cr[1] = *ca * a[a_dim1 + 2]; cr[2] = *ca * a[((a_dim1) << (1)) + 1]; } if (*nw == 1) { /* Real 2x2 system (w is real) Find the largest element in C */ cmax = 0.; icmax = 0; for (j = 1; j <= 4; ++j) { if ((d__1 = crv[j - 1], abs(d__1)) > cmax) { cmax = (d__1 = crv[j - 1], abs(d__1)); icmax = j; } /* L10: */ } /* If norm(C) < SMINI, use SMINI*identity. */ if (cmax < smini) { /* Computing MAX */ d__3 = (d__1 = b[b_dim1 + 1], abs(d__1)), d__4 = (d__2 = b[ b_dim1 + 2], abs(d__2)); bnorm = max(d__3,d__4); if (smini < 1. && bnorm > 1.) { if (bnorm > bignum * smini) { *scale = 1. / bnorm; } } temp = *scale / smini; x[x_dim1 + 1] = temp * b[b_dim1 + 1]; x[x_dim1 + 2] = temp * b[b_dim1 + 2]; *xnorm = temp * bnorm; *info = 1; return 0; } /* Gaussian elimination with complete pivoting. */ ur11 = crv[icmax - 1]; cr21 = crv[ipivot[((icmax) << (2)) - 3] - 1]; ur12 = crv[ipivot[((icmax) << (2)) - 2] - 1]; cr22 = crv[ipivot[((icmax) << (2)) - 1] - 1]; ur11r = 1. / ur11; lr21 = ur11r * cr21; ur22 = cr22 - ur12 * lr21; /* If smaller pivot < SMINI, use SMINI */ if (abs(ur22) < smini) { ur22 = smini; *info = 1; } if (rswap[icmax - 1]) { br1 = b[b_dim1 + 2]; br2 = b[b_dim1 + 1]; } else { br1 = b[b_dim1 + 1]; br2 = b[b_dim1 + 2]; } br2 -= lr21 * br1; /* Computing MAX */ d__2 = (d__1 = br1 * (ur22 * ur11r), abs(d__1)), d__3 = abs(br2); bbnd = max(d__2,d__3); if (bbnd > 1. && abs(ur22) < 1.) { if (bbnd >= bignum * abs(ur22)) { *scale = 1. / bbnd; } } xr2 = br2 * *scale / ur22; xr1 = *scale * br1 * ur11r - xr2 * (ur11r * ur12); if (zswap[icmax - 1]) { x[x_dim1 + 1] = xr2; x[x_dim1 + 2] = xr1; } else { x[x_dim1 + 1] = xr1; x[x_dim1 + 2] = xr2; } /* Computing MAX */ d__1 = abs(xr1), d__2 = abs(xr2); *xnorm = max(d__1,d__2); /* Further scaling if norm(A) norm(X) > overflow */ if (*xnorm > 1. && cmax > 1.) { if (*xnorm > bignum / cmax) { temp = cmax / bignum; x[x_dim1 + 1] = temp * x[x_dim1 + 1]; x[x_dim1 + 2] = temp * x[x_dim1 + 2]; *xnorm = temp * *xnorm; *scale = temp * *scale; } } } else { /* Complex 2x2 system (w is complex) Find the largest element in C */ ci[0] = -(*wi) * *d1; ci[1] = 0.; ci[2] = 0.; ci[3] = -(*wi) * *d2; cmax = 0.; icmax = 0; for (j = 1; j <= 4; ++j) { if ((d__1 = crv[j - 1], abs(d__1)) + (d__2 = civ[j - 1], abs( d__2)) > cmax) { cmax = (d__1 = crv[j - 1], abs(d__1)) + (d__2 = civ[j - 1] , abs(d__2)); icmax = j; } /* L20: */ } /* If norm(C) < SMINI, use SMINI*identity. */ if (cmax < smini) { /* Computing MAX */ d__5 = (d__1 = b[b_dim1 + 1], abs(d__1)) + (d__2 = b[((b_dim1) << (1)) + 1], abs(d__2)), d__6 = (d__3 = b[b_dim1 + 2], abs(d__3)) + (d__4 = b[((b_dim1) << (1)) + 2], abs(d__4)); bnorm = max(d__5,d__6); if (smini < 1. && bnorm > 1.) { if (bnorm > bignum * smini) { *scale = 1. / bnorm; } } temp = *scale / smini; x[x_dim1 + 1] = temp * b[b_dim1 + 1]; x[x_dim1 + 2] = temp * b[b_dim1 + 2]; x[((x_dim1) << (1)) + 1] = temp * b[((b_dim1) << (1)) + 1]; x[((x_dim1) << (1)) + 2] = temp * b[((b_dim1) << (1)) + 2]; *xnorm = temp * bnorm; *info = 1; return 0; } /* Gaussian elimination with complete pivoting. */ ur11 = crv[icmax - 1]; ui11 = civ[icmax - 1]; cr21 = crv[ipivot[((icmax) << (2)) - 3] - 1]; ci21 = civ[ipivot[((icmax) << (2)) - 3] - 1]; ur12 = crv[ipivot[((icmax) << (2)) - 2] - 1]; ui12 = civ[ipivot[((icmax) << (2)) - 2] - 1]; cr22 = crv[ipivot[((icmax) << (2)) - 1] - 1]; ci22 = civ[ipivot[((icmax) << (2)) - 1] - 1]; if ((icmax == 1) || (icmax == 4)) { /* Code when off-diagonals of pivoted C are real */ if (abs(ur11) > abs(ui11)) { temp = ui11 / ur11; /* Computing 2nd power */ d__1 = temp; ur11r = 1. / (ur11 * (d__1 * d__1 + 1.)); ui11r = -temp * ur11r; } else { temp = ur11 / ui11; /* Computing 2nd power */ d__1 = temp; ui11r = -1. / (ui11 * (d__1 * d__1 + 1.)); ur11r = -temp * ui11r; } lr21 = cr21 * ur11r; li21 = cr21 * ui11r; ur12s = ur12 * ur11r; ui12s = ur12 * ui11r; ur22 = cr22 - ur12 * lr21; ui22 = ci22 - ur12 * li21; } else { /* Code when diagonals of pivoted C are real */ ur11r = 1. / ur11; ui11r = 0.; lr21 = cr21 * ur11r; li21 = ci21 * ur11r; ur12s = ur12 * ur11r; ui12s = ui12 * ur11r; ur22 = cr22 - ur12 * lr21 + ui12 * li21; ui22 = -ur12 * li21 - ui12 * lr21; } u22abs = abs(ur22) + abs(ui22); /* If smaller pivot < SMINI, use SMINI */ if (u22abs < smini) { ur22 = smini; ui22 = 0.; *info = 1; } if (rswap[icmax - 1]) { br2 = b[b_dim1 + 1]; br1 = b[b_dim1 + 2]; bi2 = b[((b_dim1) << (1)) + 1]; bi1 = b[((b_dim1) << (1)) + 2]; } else { br1 = b[b_dim1 + 1]; br2 = b[b_dim1 + 2]; bi1 = b[((b_dim1) << (1)) + 1]; bi2 = b[((b_dim1) << (1)) + 2]; } br2 = br2 - lr21 * br1 + li21 * bi1; bi2 = bi2 - li21 * br1 - lr21 * bi1; /* Computing MAX */ d__1 = (abs(br1) + abs(bi1)) * (u22abs * (abs(ur11r) + abs(ui11r)) ), d__2 = abs(br2) + abs(bi2); bbnd = max(d__1,d__2); if (bbnd > 1. && u22abs < 1.) { if (bbnd >= bignum * u22abs) { *scale = 1. / bbnd; br1 = *scale * br1; bi1 = *scale * bi1; br2 = *scale * br2; bi2 = *scale * bi2; } } dladiv_(&br2, &bi2, &ur22, &ui22, &xr2, &xi2); xr1 = ur11r * br1 - ui11r * bi1 - ur12s * xr2 + ui12s * xi2; xi1 = ui11r * br1 + ur11r * bi1 - ui12s * xr2 - ur12s * xi2; if (zswap[icmax - 1]) { x[x_dim1 + 1] = xr2; x[x_dim1 + 2] = xr1; x[((x_dim1) << (1)) + 1] = xi2; x[((x_dim1) << (1)) + 2] = xi1; } else { x[x_dim1 + 1] = xr1; x[x_dim1 + 2] = xr2; x[((x_dim1) << (1)) + 1] = xi1; x[((x_dim1) << (1)) + 2] = xi2; } /* Computing MAX */ d__1 = abs(xr1) + abs(xi1), d__2 = abs(xr2) + abs(xi2); *xnorm = max(d__1,d__2); /* Further scaling if norm(A) norm(X) > overflow */ if (*xnorm > 1. && cmax > 1.) { if (*xnorm > bignum / cmax) { temp = cmax / bignum; x[x_dim1 + 1] = temp * x[x_dim1 + 1]; x[x_dim1 + 2] = temp * x[x_dim1 + 2]; x[((x_dim1) << (1)) + 1] = temp * x[((x_dim1) << (1)) + 1] ; x[((x_dim1) << (1)) + 2] = temp * x[((x_dim1) << (1)) + 2] ; *xnorm = temp * *xnorm; *scale = temp * *scale; } } } } return 0; /* End of DLALN2 */ } /* dlaln2_ */ #undef crv #undef civ #undef cr #undef ci /* Subroutine */ int dlals0_(integer *icompq, integer *nl, integer *nr, integer *sqre, integer *nrhs, doublereal *b, integer *ldb, doublereal *bx, integer *ldbx, integer *perm, integer *givptr, integer *givcol, integer *ldgcol, doublereal *givnum, integer *ldgnum, doublereal * poles, doublereal *difl, doublereal *difr, doublereal *z__, integer * k, doublereal *c__, doublereal *s, doublereal *work, integer *info) { /* System generated locals */ integer givcol_dim1, givcol_offset, b_dim1, b_offset, bx_dim1, bx_offset, difr_dim1, difr_offset, givnum_dim1, givnum_offset, poles_dim1, poles_offset, i__1, i__2; doublereal d__1; /* Local variables */ static integer i__, j, m, n; static doublereal dj; static integer nlp1; static doublereal temp; extern /* Subroutine */ int drot_(integer *, doublereal *, integer *, doublereal *, integer *, doublereal *, doublereal *); extern doublereal dnrm2_(integer *, doublereal *, integer *); extern /* Subroutine */ int dscal_(integer *, doublereal *, doublereal *, integer *); static doublereal diflj, difrj, dsigj; extern /* Subroutine */ int dgemv_(char *, integer *, integer *, doublereal *, doublereal *, integer *, doublereal *, integer *, doublereal *, doublereal *, integer *), dcopy_(integer *, doublereal *, integer *, doublereal *, integer *); extern doublereal dlamc3_(doublereal *, doublereal *); extern /* Subroutine */ int dlascl_(char *, integer *, integer *, doublereal *, doublereal *, integer *, integer *, doublereal *, integer *, integer *), dlacpy_(char *, integer *, integer *, doublereal *, integer *, doublereal *, integer *), xerbla_(char *, integer *); static doublereal dsigjp; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University December 1, 1999 Purpose ======= DLALS0 applies back the multiplying factors of either the left or the right singular vector matrix of a diagonal matrix appended by a row to the right hand side matrix B in solving the least squares problem using the divide-and-conquer SVD approach. For the left singular vector matrix, three types of orthogonal matrices are involved: (1L) Givens rotations: the number of such rotations is GIVPTR; the pairs of columns/rows they were applied to are stored in GIVCOL; and the C- and S-values of these rotations are stored in GIVNUM. (2L) Permutation. The (NL+1)-st row of B is to be moved to the first row, and for J=2:N, PERM(J)-th row of B is to be moved to the J-th row. (3L) The left singular vector matrix of the remaining matrix. For the right singular vector matrix, four types of orthogonal matrices are involved: (1R) The right singular vector matrix of the remaining matrix. (2R) If SQRE = 1, one extra Givens rotation to generate the right null space. (3R) The inverse transformation of (2L). (4R) The inverse transformation of (1L). Arguments ========= ICOMPQ (input) INTEGER Specifies whether singular vectors are to be computed in factored form: = 0: Left singular vector matrix. = 1: Right singular vector matrix. NL (input) INTEGER The row dimension of the upper block. NL >= 1. NR (input) INTEGER The row dimension of the lower block. NR >= 1. SQRE (input) INTEGER = 0: the lower block is an NR-by-NR square matrix. = 1: the lower block is an NR-by-(NR+1) rectangular matrix. The bidiagonal matrix has row dimension N = NL + NR + 1, and column dimension M = N + SQRE. NRHS (input) INTEGER The number of columns of B and BX. NRHS must be at least 1. B (input/output) DOUBLE PRECISION array, dimension ( LDB, NRHS ) On input, B contains the right hand sides of the least squares problem in rows 1 through M. On output, B contains the solution X in rows 1 through N. LDB (input) INTEGER The leading dimension of B. LDB must be at least max(1,MAX( M, N ) ). BX (workspace) DOUBLE PRECISION array, dimension ( LDBX, NRHS ) LDBX (input) INTEGER The leading dimension of BX. PERM (input) INTEGER array, dimension ( N ) The permutations (from deflation and sorting) applied to the two blocks. GIVPTR (input) INTEGER The number of Givens rotations which took place in this subproblem. GIVCOL (input) INTEGER array, dimension ( LDGCOL, 2 ) Each pair of numbers indicates a pair of rows/columns involved in a Givens rotation. LDGCOL (input) INTEGER The leading dimension of GIVCOL, must be at least N. GIVNUM (input) DOUBLE PRECISION array, dimension ( LDGNUM, 2 ) Each number indicates the C or S value used in the corresponding Givens rotation. LDGNUM (input) INTEGER The leading dimension of arrays DIFR, POLES and GIVNUM, must be at least K. POLES (input) DOUBLE PRECISION array, dimension ( LDGNUM, 2 ) On entry, POLES(1:K, 1) contains the new singular values obtained from solving the secular equation, and POLES(1:K, 2) is an array containing the poles in the secular equation. DIFL (input) DOUBLE PRECISION array, dimension ( K ). On entry, DIFL(I) is the distance between I-th updated (undeflated) singular value and the I-th (undeflated) old singular value. DIFR (input) DOUBLE PRECISION array, dimension ( LDGNUM, 2 ). On entry, DIFR(I, 1) contains the distances between I-th updated (undeflated) singular value and the I+1-th (undeflated) old singular value. And DIFR(I, 2) is the normalizing factor for the I-th right singular vector. Z (input) DOUBLE PRECISION array, dimension ( K ) Contain the components of the deflation-adjusted updating row vector. K (input) INTEGER Contains the dimension of the non-deflated matrix, This is the order of the related secular equation. 1 <= K <=N. C (input) DOUBLE PRECISION C contains garbage if SQRE =0 and the C-value of a Givens rotation related to the right null space if SQRE = 1. S (input) DOUBLE PRECISION S contains garbage if SQRE =0 and the S-value of a Givens rotation related to the right null space if SQRE = 1. WORK (workspace) DOUBLE PRECISION array, dimension ( K ) INFO (output) INTEGER = 0: successful exit. < 0: if INFO = -i, the i-th argument had an illegal value. Further Details =============== Based on contributions by Ming Gu and Ren-Cang Li, Computer Science Division, University of California at Berkeley, USA Osni Marques, LBNL/NERSC, USA ===================================================================== Test the input parameters. */ /* Parameter adjustments */ b_dim1 = *ldb; b_offset = 1 + b_dim1; b -= b_offset; bx_dim1 = *ldbx; bx_offset = 1 + bx_dim1; bx -= bx_offset; --perm; givcol_dim1 = *ldgcol; givcol_offset = 1 + givcol_dim1; givcol -= givcol_offset; difr_dim1 = *ldgnum; difr_offset = 1 + difr_dim1; difr -= difr_offset; poles_dim1 = *ldgnum; poles_offset = 1 + poles_dim1; poles -= poles_offset; givnum_dim1 = *ldgnum; givnum_offset = 1 + givnum_dim1; givnum -= givnum_offset; --difl; --z__; --work; /* Function Body */ *info = 0; if ((*icompq < 0) || (*icompq > 1)) { *info = -1; } else if (*nl < 1) { *info = -2; } else if (*nr < 1) { *info = -3; } else if ((*sqre < 0) || (*sqre > 1)) { *info = -4; } n = *nl + *nr + 1; if (*nrhs < 1) { *info = -5; } else if (*ldb < n) { *info = -7; } else if (*ldbx < n) { *info = -9; } else if (*givptr < 0) { *info = -11; } else if (*ldgcol < n) { *info = -13; } else if (*ldgnum < n) { *info = -15; } else if (*k < 1) { *info = -20; } if (*info != 0) { i__1 = -(*info); xerbla_("DLALS0", &i__1); return 0; } m = n + *sqre; nlp1 = *nl + 1; if (*icompq == 0) { /* Apply back orthogonal transformations from the left. Step (1L): apply back the Givens rotations performed. */ i__1 = *givptr; for (i__ = 1; i__ <= i__1; ++i__) { drot_(nrhs, &b[givcol[i__ + ((givcol_dim1) << (1))] + b_dim1], ldb, &b[givcol[i__ + givcol_dim1] + b_dim1], ldb, &givnum[ i__ + ((givnum_dim1) << (1))], &givnum[i__ + givnum_dim1]) ; /* L10: */ } /* Step (2L): permute rows of B. */ dcopy_(nrhs, &b[nlp1 + b_dim1], ldb, &bx[bx_dim1 + 1], ldbx); i__1 = n; for (i__ = 2; i__ <= i__1; ++i__) { dcopy_(nrhs, &b[perm[i__] + b_dim1], ldb, &bx[i__ + bx_dim1], ldbx); /* L20: */ } /* Step (3L): apply the inverse of the left singular vector matrix to BX. */ if (*k == 1) { dcopy_(nrhs, &bx[bx_offset], ldbx, &b[b_offset], ldb); if (z__[1] < 0.) { dscal_(nrhs, &c_b3001, &b[b_offset], ldb); } } else { i__1 = *k; for (j = 1; j <= i__1; ++j) { diflj = difl[j]; dj = poles[j + poles_dim1]; dsigj = -poles[j + ((poles_dim1) << (1))]; if (j < *k) { difrj = -difr[j + difr_dim1]; dsigjp = -poles[j + 1 + ((poles_dim1) << (1))]; } if ((z__[j] == 0.) || (poles[j + ((poles_dim1) << (1))] == 0.) ) { work[j] = 0.; } else { work[j] = -poles[j + ((poles_dim1) << (1))] * z__[j] / diflj / (poles[j + ((poles_dim1) << (1))] + dj); } i__2 = j - 1; for (i__ = 1; i__ <= i__2; ++i__) { if ((z__[i__] == 0.) || (poles[i__ + ((poles_dim1) << (1)) ] == 0.)) { work[i__] = 0.; } else { work[i__] = poles[i__ + ((poles_dim1) << (1))] * z__[ i__] / (dlamc3_(&poles[i__ + ((poles_dim1) << (1))], &dsigj) - diflj) / (poles[i__ + (( poles_dim1) << (1))] + dj); } /* L30: */ } i__2 = *k; for (i__ = j + 1; i__ <= i__2; ++i__) { if ((z__[i__] == 0.) || (poles[i__ + ((poles_dim1) << (1)) ] == 0.)) { work[i__] = 0.; } else { work[i__] = poles[i__ + ((poles_dim1) << (1))] * z__[ i__] / (dlamc3_(&poles[i__ + ((poles_dim1) << (1))], &dsigjp) + difrj) / (poles[i__ + (( poles_dim1) << (1))] + dj); } /* L40: */ } work[1] = -1.; temp = dnrm2_(k, &work[1], &c__1); dgemv_("T", k, nrhs, &c_b2865, &bx[bx_offset], ldbx, &work[1], &c__1, &c_b2879, &b[j + b_dim1], ldb); dlascl_("G", &c__0, &c__0, &temp, &c_b2865, &c__1, nrhs, &b[j + b_dim1], ldb, info); /* L50: */ } } /* Move the deflated rows of BX to B also. */ if (*k < max(m,n)) { i__1 = n - *k; dlacpy_("A", &i__1, nrhs, &bx[*k + 1 + bx_dim1], ldbx, &b[*k + 1 + b_dim1], ldb); } } else { /* Apply back the right orthogonal transformations. Step (1R): apply back the new right singular vector matrix to B. */ if (*k == 1) { dcopy_(nrhs, &b[b_offset], ldb, &bx[bx_offset], ldbx); } else { i__1 = *k; for (j = 1; j <= i__1; ++j) { dsigj = poles[j + ((poles_dim1) << (1))]; if (z__[j] == 0.) { work[j] = 0.; } else { work[j] = -z__[j] / difl[j] / (dsigj + poles[j + poles_dim1]) / difr[j + ((difr_dim1) << (1))]; } i__2 = j - 1; for (i__ = 1; i__ <= i__2; ++i__) { if (z__[j] == 0.) { work[i__] = 0.; } else { d__1 = -poles[i__ + 1 + ((poles_dim1) << (1))]; work[i__] = z__[j] / (dlamc3_(&dsigj, &d__1) - difr[ i__ + difr_dim1]) / (dsigj + poles[i__ + poles_dim1]) / difr[i__ + ((difr_dim1) << (1)) ]; } /* L60: */ } i__2 = *k; for (i__ = j + 1; i__ <= i__2; ++i__) { if (z__[j] == 0.) { work[i__] = 0.; } else { d__1 = -poles[i__ + ((poles_dim1) << (1))]; work[i__] = z__[j] / (dlamc3_(&dsigj, &d__1) - difl[ i__]) / (dsigj + poles[i__ + poles_dim1]) / difr[i__ + ((difr_dim1) << (1))]; } /* L70: */ } dgemv_("T", k, nrhs, &c_b2865, &b[b_offset], ldb, &work[1], & c__1, &c_b2879, &bx[j + bx_dim1], ldbx); /* L80: */ } } /* Step (2R): if SQRE = 1, apply back the rotation that is related to the right null space of the subproblem. */ if (*sqre == 1) { dcopy_(nrhs, &b[m + b_dim1], ldb, &bx[m + bx_dim1], ldbx); drot_(nrhs, &bx[bx_dim1 + 1], ldbx, &bx[m + bx_dim1], ldbx, c__, s); } if (*k < max(m,n)) { i__1 = n - *k; dlacpy_("A", &i__1, nrhs, &b[*k + 1 + b_dim1], ldb, &bx[*k + 1 + bx_dim1], ldbx); } /* Step (3R): permute rows of B. */ dcopy_(nrhs, &bx[bx_dim1 + 1], ldbx, &b[nlp1 + b_dim1], ldb); if (*sqre == 1) { dcopy_(nrhs, &bx[m + bx_dim1], ldbx, &b[m + b_dim1], ldb); } i__1 = n; for (i__ = 2; i__ <= i__1; ++i__) { dcopy_(nrhs, &bx[i__ + bx_dim1], ldbx, &b[perm[i__] + b_dim1], ldb); /* L90: */ } /* Step (4R): apply back the Givens rotations performed. */ for (i__ = *givptr; i__ >= 1; --i__) { d__1 = -givnum[i__ + givnum_dim1]; drot_(nrhs, &b[givcol[i__ + ((givcol_dim1) << (1))] + b_dim1], ldb, &b[givcol[i__ + givcol_dim1] + b_dim1], ldb, &givnum[ i__ + ((givnum_dim1) << (1))], &d__1); /* L100: */ } } return 0; /* End of DLALS0 */ } /* dlals0_ */ /* Subroutine */ int dlalsa_(integer *icompq, integer *smlsiz, integer *n, integer *nrhs, doublereal *b, integer *ldb, doublereal *bx, integer * ldbx, doublereal *u, integer *ldu, doublereal *vt, integer *k, doublereal *difl, doublereal *difr, doublereal *z__, doublereal * poles, integer *givptr, integer *givcol, integer *ldgcol, integer * perm, doublereal *givnum, doublereal *c__, doublereal *s, doublereal * work, integer *iwork, integer *info) { /* System generated locals */ integer givcol_dim1, givcol_offset, perm_dim1, perm_offset, b_dim1, b_offset, bx_dim1, bx_offset, difl_dim1, difl_offset, difr_dim1, difr_offset, givnum_dim1, givnum_offset, poles_dim1, poles_offset, u_dim1, u_offset, vt_dim1, vt_offset, z_dim1, z_offset, i__1, i__2; /* Builtin functions */ integer pow_ii(integer *, integer *); /* Local variables */ static integer i__, j, i1, ic, lf, nd, ll, nl, nr, im1, nlf, nrf, lvl, ndb1, nlp1, lvl2, nrp1, nlvl, sqre; extern /* Subroutine */ int dgemm_(char *, char *, integer *, integer *, integer *, doublereal *, doublereal *, integer *, doublereal *, integer *, doublereal *, doublereal *, integer *); static integer inode, ndiml, ndimr; extern /* Subroutine */ int dcopy_(integer *, doublereal *, integer *, doublereal *, integer *), dlals0_(integer *, integer *, integer *, integer *, integer *, doublereal *, integer *, doublereal *, integer *, integer *, integer *, integer *, integer *, doublereal *, integer *, doublereal *, doublereal *, doublereal *, doublereal *, integer *, doublereal *, doublereal *, doublereal *, integer *), dlasdt_(integer *, integer *, integer *, integer *, integer *, integer *, integer *), xerbla_(char *, integer *); /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= DLALSA is an itermediate step in solving the least squares problem by computing the SVD of the coefficient matrix in compact form (The singular vectors are computed as products of simple orthorgonal matrices.). If ICOMPQ = 0, DLALSA applies the inverse of the left singular vector matrix of an upper bidiagonal matrix to the right hand side; and if ICOMPQ = 1, DLALSA applies the right singular vector matrix to the right hand side. The singular vector matrices were generated in compact form by DLALSA. Arguments ========= ICOMPQ (input) INTEGER Specifies whether the left or the right singular vector matrix is involved. = 0: Left singular vector matrix = 1: Right singular vector matrix SMLSIZ (input) INTEGER The maximum size of the subproblems at the bottom of the computation tree. N (input) INTEGER The row and column dimensions of the upper bidiagonal matrix. NRHS (input) INTEGER The number of columns of B and BX. NRHS must be at least 1. B (input) DOUBLE PRECISION array, dimension ( LDB, NRHS ) On input, B contains the right hand sides of the least squares problem in rows 1 through M. On output, B contains the solution X in rows 1 through N. LDB (input) INTEGER The leading dimension of B in the calling subprogram. LDB must be at least max(1,MAX( M, N ) ). BX (output) DOUBLE PRECISION array, dimension ( LDBX, NRHS ) On exit, the result of applying the left or right singular vector matrix to B. LDBX (input) INTEGER The leading dimension of BX. U (input) DOUBLE PRECISION array, dimension ( LDU, SMLSIZ ). On entry, U contains the left singular vector matrices of all subproblems at the bottom level. LDU (input) INTEGER, LDU = > N. The leading dimension of arrays U, VT, DIFL, DIFR, POLES, GIVNUM, and Z. VT (input) DOUBLE PRECISION array, dimension ( LDU, SMLSIZ+1 ). On entry, VT' contains the right singular vector matrices of all subproblems at the bottom level. K (input) INTEGER array, dimension ( N ). DIFL (input) DOUBLE PRECISION array, dimension ( LDU, NLVL ). where NLVL = INT(log_2 (N/(SMLSIZ+1))) + 1. DIFR (input) DOUBLE PRECISION array, dimension ( LDU, 2 * NLVL ). On entry, DIFL(*, I) and DIFR(*, 2 * I -1) record distances between singular values on the I-th level and singular values on the (I -1)-th level, and DIFR(*, 2 * I) record the normalizing factors of the right singular vectors matrices of subproblems on I-th level. Z (input) DOUBLE PRECISION array, dimension ( LDU, NLVL ). On entry, Z(1, I) contains the components of the deflation- adjusted updating row vector for subproblems on the I-th level. POLES (input) DOUBLE PRECISION array, dimension ( LDU, 2 * NLVL ). On entry, POLES(*, 2 * I -1: 2 * I) contains the new and old singular values involved in the secular equations on the I-th level. GIVPTR (input) INTEGER array, dimension ( N ). On entry, GIVPTR( I ) records the number of Givens rotations performed on the I-th problem on the computation tree. GIVCOL (input) INTEGER array, dimension ( LDGCOL, 2 * NLVL ). On entry, for each I, GIVCOL(*, 2 * I - 1: 2 * I) records the locations of Givens rotations performed on the I-th level on the computation tree. LDGCOL (input) INTEGER, LDGCOL = > N. The leading dimension of arrays GIVCOL and PERM. PERM (input) INTEGER array, dimension ( LDGCOL, NLVL ). On entry, PERM(*, I) records permutations done on the I-th level of the computation tree. GIVNUM (input) DOUBLE PRECISION array, dimension ( LDU, 2 * NLVL ). On entry, GIVNUM(*, 2 *I -1 : 2 * I) records the C- and S- values of Givens rotations performed on the I-th level on the computation tree. C (input) DOUBLE PRECISION array, dimension ( N ). On entry, if the I-th subproblem is not square, C( I ) contains the C-value of a Givens rotation related to the right null space of the I-th subproblem. S (input) DOUBLE PRECISION array, dimension ( N ). On entry, if the I-th subproblem is not square, S( I ) contains the S-value of a Givens rotation related to the right null space of the I-th subproblem. WORK (workspace) DOUBLE PRECISION array. The dimension must be at least N. IWORK (workspace) INTEGER array. The dimension must be at least 3 * N INFO (output) INTEGER = 0: successful exit. < 0: if INFO = -i, the i-th argument had an illegal value. Further Details =============== Based on contributions by Ming Gu and Ren-Cang Li, Computer Science Division, University of California at Berkeley, USA Osni Marques, LBNL/NERSC, USA ===================================================================== Test the input parameters. */ /* Parameter adjustments */ b_dim1 = *ldb; b_offset = 1 + b_dim1; b -= b_offset; bx_dim1 = *ldbx; bx_offset = 1 + bx_dim1; bx -= bx_offset; givnum_dim1 = *ldu; givnum_offset = 1 + givnum_dim1; givnum -= givnum_offset; poles_dim1 = *ldu; poles_offset = 1 + poles_dim1; poles -= poles_offset; z_dim1 = *ldu; z_offset = 1 + z_dim1; z__ -= z_offset; difr_dim1 = *ldu; difr_offset = 1 + difr_dim1; difr -= difr_offset; difl_dim1 = *ldu; difl_offset = 1 + difl_dim1; difl -= difl_offset; vt_dim1 = *ldu; vt_offset = 1 + vt_dim1; vt -= vt_offset; u_dim1 = *ldu; u_offset = 1 + u_dim1; u -= u_offset; --k; --givptr; perm_dim1 = *ldgcol; perm_offset = 1 + perm_dim1; perm -= perm_offset; givcol_dim1 = *ldgcol; givcol_offset = 1 + givcol_dim1; givcol -= givcol_offset; --c__; --s; --work; --iwork; /* Function Body */ *info = 0; if ((*icompq < 0) || (*icompq > 1)) { *info = -1; } else if (*smlsiz < 3) { *info = -2; } else if (*n < *smlsiz) { *info = -3; } else if (*nrhs < 1) { *info = -4; } else if (*ldb < *n) { *info = -6; } else if (*ldbx < *n) { *info = -8; } else if (*ldu < *n) { *info = -10; } else if (*ldgcol < *n) { *info = -19; } if (*info != 0) { i__1 = -(*info); xerbla_("DLALSA", &i__1); return 0; } /* Book-keeping and setting up the computation tree. */ inode = 1; ndiml = inode + *n; ndimr = ndiml + *n; dlasdt_(n, &nlvl, &nd, &iwork[inode], &iwork[ndiml], &iwork[ndimr], smlsiz); /* The following code applies back the left singular vector factors. For applying back the right singular vector factors, go to 50. */ if (*icompq == 1) { goto L50; } /* The nodes on the bottom level of the tree were solved by DLASDQ. The corresponding left and right singular vector matrices are in explicit form. First apply back the left singular vector matrices. */ ndb1 = (nd + 1) / 2; i__1 = nd; for (i__ = ndb1; i__ <= i__1; ++i__) { /* IC : center row of each node NL : number of rows of left subproblem NR : number of rows of right subproblem NLF: starting row of the left subproblem NRF: starting row of the right subproblem */ i1 = i__ - 1; ic = iwork[inode + i1]; nl = iwork[ndiml + i1]; nr = iwork[ndimr + i1]; nlf = ic - nl; nrf = ic + 1; dgemm_("T", "N", &nl, nrhs, &nl, &c_b2865, &u[nlf + u_dim1], ldu, &b[ nlf + b_dim1], ldb, &c_b2879, &bx[nlf + bx_dim1], ldbx); dgemm_("T", "N", &nr, nrhs, &nr, &c_b2865, &u[nrf + u_dim1], ldu, &b[ nrf + b_dim1], ldb, &c_b2879, &bx[nrf + bx_dim1], ldbx); /* L10: */ } /* Next copy the rows of B that correspond to unchanged rows in the bidiagonal matrix to BX. */ i__1 = nd; for (i__ = 1; i__ <= i__1; ++i__) { ic = iwork[inode + i__ - 1]; dcopy_(nrhs, &b[ic + b_dim1], ldb, &bx[ic + bx_dim1], ldbx); /* L20: */ } /* Finally go through the left singular vector matrices of all the other subproblems bottom-up on the tree. */ j = pow_ii(&c__2, &nlvl); sqre = 0; for (lvl = nlvl; lvl >= 1; --lvl) { lvl2 = ((lvl) << (1)) - 1; /* find the first node LF and last node LL on the current level LVL */ if (lvl == 1) { lf = 1; ll = 1; } else { i__1 = lvl - 1; lf = pow_ii(&c__2, &i__1); ll = ((lf) << (1)) - 1; } i__1 = ll; for (i__ = lf; i__ <= i__1; ++i__) { im1 = i__ - 1; ic = iwork[inode + im1]; nl = iwork[ndiml + im1]; nr = iwork[ndimr + im1]; nlf = ic - nl; nrf = ic + 1; --j; dlals0_(icompq, &nl, &nr, &sqre, nrhs, &bx[nlf + bx_dim1], ldbx, & b[nlf + b_dim1], ldb, &perm[nlf + lvl * perm_dim1], & givptr[j], &givcol[nlf + lvl2 * givcol_dim1], ldgcol, & givnum[nlf + lvl2 * givnum_dim1], ldu, &poles[nlf + lvl2 * poles_dim1], &difl[nlf + lvl * difl_dim1], &difr[nlf + lvl2 * difr_dim1], &z__[nlf + lvl * z_dim1], &k[j], &c__[ j], &s[j], &work[1], info); /* L30: */ } /* L40: */ } goto L90; /* ICOMPQ = 1: applying back the right singular vector factors. */ L50: /* First now go through the right singular vector matrices of all the tree nodes top-down. */ j = 0; i__1 = nlvl; for (lvl = 1; lvl <= i__1; ++lvl) { lvl2 = ((lvl) << (1)) - 1; /* Find the first node LF and last node LL on the current level LVL. */ if (lvl == 1) { lf = 1; ll = 1; } else { i__2 = lvl - 1; lf = pow_ii(&c__2, &i__2); ll = ((lf) << (1)) - 1; } i__2 = lf; for (i__ = ll; i__ >= i__2; --i__) { im1 = i__ - 1; ic = iwork[inode + im1]; nl = iwork[ndiml + im1]; nr = iwork[ndimr + im1]; nlf = ic - nl; nrf = ic + 1; if (i__ == ll) { sqre = 0; } else { sqre = 1; } ++j; dlals0_(icompq, &nl, &nr, &sqre, nrhs, &b[nlf + b_dim1], ldb, &bx[ nlf + bx_dim1], ldbx, &perm[nlf + lvl * perm_dim1], & givptr[j], &givcol[nlf + lvl2 * givcol_dim1], ldgcol, & givnum[nlf + lvl2 * givnum_dim1], ldu, &poles[nlf + lvl2 * poles_dim1], &difl[nlf + lvl * difl_dim1], &difr[nlf + lvl2 * difr_dim1], &z__[nlf + lvl * z_dim1], &k[j], &c__[ j], &s[j], &work[1], info); /* L60: */ } /* L70: */ } /* The nodes on the bottom level of the tree were solved by DLASDQ. The corresponding right singular vector matrices are in explicit form. Apply them back. */ ndb1 = (nd + 1) / 2; i__1 = nd; for (i__ = ndb1; i__ <= i__1; ++i__) { i1 = i__ - 1; ic = iwork[inode + i1]; nl = iwork[ndiml + i1]; nr = iwork[ndimr + i1]; nlp1 = nl + 1; if (i__ == nd) { nrp1 = nr; } else { nrp1 = nr + 1; } nlf = ic - nl; nrf = ic + 1; dgemm_("T", "N", &nlp1, nrhs, &nlp1, &c_b2865, &vt[nlf + vt_dim1], ldu, &b[nlf + b_dim1], ldb, &c_b2879, &bx[nlf + bx_dim1], ldbx); dgemm_("T", "N", &nrp1, nrhs, &nrp1, &c_b2865, &vt[nrf + vt_dim1], ldu, &b[nrf + b_dim1], ldb, &c_b2879, &bx[nrf + bx_dim1], ldbx); /* L80: */ } L90: return 0; /* End of DLALSA */ } /* dlalsa_ */ /* Subroutine */ int dlalsd_(char *uplo, integer *smlsiz, integer *n, integer *nrhs, doublereal *d__, doublereal *e, doublereal *b, integer *ldb, doublereal *rcond, integer *rank, doublereal *work, integer *iwork, integer *info) { /* System generated locals */ integer b_dim1, b_offset, i__1, i__2; doublereal d__1; /* Builtin functions */ double log(doublereal), d_sign(doublereal *, doublereal *); /* Local variables */ static integer c__, i__, j, k; static doublereal r__; static integer s, u, z__; static doublereal cs; static integer bx; static doublereal sn; static integer st, vt, nm1, st1; static doublereal eps; static integer iwk; static doublereal tol; static integer difl, difr, perm, nsub; extern /* Subroutine */ int drot_(integer *, doublereal *, integer *, doublereal *, integer *, doublereal *, doublereal *); static integer nlvl, sqre, bxst; extern /* Subroutine */ int dgemm_(char *, char *, integer *, integer *, integer *, doublereal *, doublereal *, integer *, doublereal *, integer *, doublereal *, doublereal *, integer *), dcopy_(integer *, doublereal *, integer *, doublereal *, integer *); static integer poles, sizei, nsize, nwork, icmpq1, icmpq2; extern /* Subroutine */ int dlasda_(integer *, integer *, integer *, integer *, doublereal *, doublereal *, doublereal *, integer *, doublereal *, integer *, doublereal *, doublereal *, doublereal *, doublereal *, integer *, integer *, integer *, integer *, doublereal *, doublereal *, doublereal *, doublereal *, integer *, integer *), dlalsa_(integer *, integer *, integer *, integer *, doublereal *, integer *, doublereal *, integer *, doublereal *, integer *, doublereal *, integer *, doublereal *, doublereal *, doublereal *, doublereal *, integer *, integer *, integer *, integer *, doublereal *, doublereal *, doublereal *, doublereal *, integer *, integer *), dlascl_(char *, integer *, integer *, doublereal *, doublereal *, integer *, integer *, doublereal *, integer *, integer *); extern integer idamax_(integer *, doublereal *, integer *); extern /* Subroutine */ int dlasdq_(char *, integer *, integer *, integer *, integer *, integer *, doublereal *, doublereal *, doublereal *, integer *, doublereal *, integer *, doublereal *, integer *, doublereal *, integer *), dlacpy_(char *, integer *, integer *, doublereal *, integer *, doublereal *, integer *), dlartg_(doublereal *, doublereal *, doublereal *, doublereal *, doublereal *), dlaset_(char *, integer *, integer *, doublereal *, doublereal *, doublereal *, integer *), xerbla_(char *, integer *); static integer givcol; extern doublereal dlanst_(char *, integer *, doublereal *, doublereal *); extern /* Subroutine */ int dlasrt_(char *, integer *, doublereal *, integer *); static doublereal orgnrm; static integer givnum, givptr, smlszp; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University October 31, 1999 Purpose ======= DLALSD uses the singular value decomposition of A to solve the least squares problem of finding X to minimize the Euclidean norm of each column of A*X-B, where A is N-by-N upper bidiagonal, and X and B are N-by-NRHS. The solution X overwrites B. The singular values of A smaller than RCOND times the largest singular value are treated as zero in solving the least squares problem; in this case a minimum norm solution is returned. The actual singular values are returned in D in ascending order. This code makes very mild assumptions about floating point arithmetic. It will work on machines with a guard digit in add/subtract, or on those binary machines without guard digits which subtract like the Cray XMP, Cray YMP, Cray C 90, or Cray 2. It could conceivably fail on hexadecimal or decimal machines without guard digits, but we know of none. Arguments ========= UPLO (input) CHARACTER*1 = 'U': D and E define an upper bidiagonal matrix. = 'L': D and E define a lower bidiagonal matrix. SMLSIZ (input) INTEGER The maximum size of the subproblems at the bottom of the computation tree. N (input) INTEGER The dimension of the bidiagonal matrix. N >= 0. NRHS (input) INTEGER The number of columns of B. NRHS must be at least 1. D (input/output) DOUBLE PRECISION array, dimension (N) On entry D contains the main diagonal of the bidiagonal matrix. On exit, if INFO = 0, D contains its singular values. E (input) DOUBLE PRECISION array, dimension (N-1) Contains the super-diagonal entries of the bidiagonal matrix. On exit, E has been destroyed. B (input/output) DOUBLE PRECISION array, dimension (LDB,NRHS) On input, B contains the right hand sides of the least squares problem. On output, B contains the solution X. LDB (input) INTEGER The leading dimension of B in the calling subprogram. LDB must be at least max(1,N). RCOND (input) DOUBLE PRECISION The singular values of A less than or equal to RCOND times the largest singular value are treated as zero in solving the least squares problem. If RCOND is negative, machine precision is used instead. For example, if diag(S)*X=B were the least squares problem, where diag(S) is a diagonal matrix of singular values, the solution would be X(i) = B(i) / S(i) if S(i) is greater than RCOND*max(S), and X(i) = 0 if S(i) is less than or equal to RCOND*max(S). RANK (output) INTEGER The number of singular values of A greater than RCOND times the largest singular value. WORK (workspace) DOUBLE PRECISION array, dimension at least (9*N + 2*N*SMLSIZ + 8*N*NLVL + N*NRHS + (SMLSIZ+1)**2), where NLVL = max(0, INT(log_2 (N/(SMLSIZ+1))) + 1). IWORK (workspace) INTEGER array, dimension at least (3*N*NLVL + 11*N) INFO (output) INTEGER = 0: successful exit. < 0: if INFO = -i, the i-th argument had an illegal value. > 0: The algorithm failed to compute an singular value while working on the submatrix lying in rows and columns INFO/(N+1) through MOD(INFO,N+1). Further Details =============== Based on contributions by Ming Gu and Ren-Cang Li, Computer Science Division, University of California at Berkeley, USA Osni Marques, LBNL/NERSC, USA ===================================================================== Test the input parameters. */ /* Parameter adjustments */ --d__; --e; b_dim1 = *ldb; b_offset = 1 + b_dim1; b -= b_offset; --work; --iwork; /* Function Body */ *info = 0; if (*n < 0) { *info = -3; } else if (*nrhs < 1) { *info = -4; } else if ((*ldb < 1) || (*ldb < *n)) { *info = -8; } if (*info != 0) { i__1 = -(*info); xerbla_("DLALSD", &i__1); return 0; } eps = EPSILON; /* Set up the tolerance. */ if ((*rcond <= 0.) || (*rcond >= 1.)) { *rcond = eps; } *rank = 0; /* Quick return if possible. */ if (*n == 0) { return 0; } else if (*n == 1) { if (d__[1] == 0.) { dlaset_("A", &c__1, nrhs, &c_b2879, &c_b2879, &b[b_offset], ldb); } else { *rank = 1; dlascl_("G", &c__0, &c__0, &d__[1], &c_b2865, &c__1, nrhs, &b[ b_offset], ldb, info); d__[1] = abs(d__[1]); } return 0; } /* Rotate the matrix if it is lower bidiagonal. */ if (*(unsigned char *)uplo == 'L') { i__1 = *n - 1; for (i__ = 1; i__ <= i__1; ++i__) { dlartg_(&d__[i__], &e[i__], &cs, &sn, &r__); d__[i__] = r__; e[i__] = sn * d__[i__ + 1]; d__[i__ + 1] = cs * d__[i__ + 1]; if (*nrhs == 1) { drot_(&c__1, &b[i__ + b_dim1], &c__1, &b[i__ + 1 + b_dim1], & c__1, &cs, &sn); } else { work[((i__) << (1)) - 1] = cs; work[i__ * 2] = sn; } /* L10: */ } if (*nrhs > 1) { i__1 = *nrhs; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = *n - 1; for (j = 1; j <= i__2; ++j) { cs = work[((j) << (1)) - 1]; sn = work[j * 2]; drot_(&c__1, &b[j + i__ * b_dim1], &c__1, &b[j + 1 + i__ * b_dim1], &c__1, &cs, &sn); /* L20: */ } /* L30: */ } } } /* Scale. */ nm1 = *n - 1; orgnrm = dlanst_("M", n, &d__[1], &e[1]); if (orgnrm == 0.) { dlaset_("A", n, nrhs, &c_b2879, &c_b2879, &b[b_offset], ldb); return 0; } dlascl_("G", &c__0, &c__0, &orgnrm, &c_b2865, n, &c__1, &d__[1], n, info); dlascl_("G", &c__0, &c__0, &orgnrm, &c_b2865, &nm1, &c__1, &e[1], &nm1, info); /* If N is smaller than the minimum divide size SMLSIZ, then solve the problem with another solver. */ if (*n <= *smlsiz) { nwork = *n * *n + 1; dlaset_("A", n, n, &c_b2879, &c_b2865, &work[1], n); dlasdq_("U", &c__0, n, n, &c__0, nrhs, &d__[1], &e[1], &work[1], n, & work[1], n, &b[b_offset], ldb, &work[nwork], info); if (*info != 0) { return 0; } tol = *rcond * (d__1 = d__[idamax_(n, &d__[1], &c__1)], abs(d__1)); i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { if (d__[i__] <= tol) { dlaset_("A", &c__1, nrhs, &c_b2879, &c_b2879, &b[i__ + b_dim1] , ldb); } else { dlascl_("G", &c__0, &c__0, &d__[i__], &c_b2865, &c__1, nrhs, & b[i__ + b_dim1], ldb, info); ++(*rank); } /* L40: */ } dgemm_("T", "N", n, nrhs, n, &c_b2865, &work[1], n, &b[b_offset], ldb, &c_b2879, &work[nwork], n); dlacpy_("A", n, nrhs, &work[nwork], n, &b[b_offset], ldb); /* Unscale. */ dlascl_("G", &c__0, &c__0, &c_b2865, &orgnrm, n, &c__1, &d__[1], n, info); dlasrt_("D", n, &d__[1], info); dlascl_("G", &c__0, &c__0, &orgnrm, &c_b2865, n, nrhs, &b[b_offset], ldb, info); return 0; } /* Book-keeping and setting up some constants. */ nlvl = (integer) (log((doublereal) (*n) / (doublereal) (*smlsiz + 1)) / log(2.)) + 1; smlszp = *smlsiz + 1; u = 1; vt = *smlsiz * *n + 1; difl = vt + smlszp * *n; difr = difl + nlvl * *n; z__ = difr + ((nlvl * *n) << (1)); c__ = z__ + nlvl * *n; s = c__ + *n; poles = s + *n; givnum = poles + ((nlvl) << (1)) * *n; bx = givnum + ((nlvl) << (1)) * *n; nwork = bx + *n * *nrhs; sizei = *n + 1; k = sizei + *n; givptr = k + *n; perm = givptr + *n; givcol = perm + nlvl * *n; iwk = givcol + ((nlvl * *n) << (1)); st = 1; sqre = 0; icmpq1 = 1; icmpq2 = 0; nsub = 0; i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { if ((d__1 = d__[i__], abs(d__1)) < eps) { d__[i__] = d_sign(&eps, &d__[i__]); } /* L50: */ } i__1 = nm1; for (i__ = 1; i__ <= i__1; ++i__) { if (((d__1 = e[i__], abs(d__1)) < eps) || (i__ == nm1)) { ++nsub; iwork[nsub] = st; /* Subproblem found. First determine its size and then apply divide and conquer on it. */ if (i__ < nm1) { /* A subproblem with E(I) small for I < NM1. */ nsize = i__ - st + 1; iwork[sizei + nsub - 1] = nsize; } else if ((d__1 = e[i__], abs(d__1)) >= eps) { /* A subproblem with E(NM1) not too small but I = NM1. */ nsize = *n - st + 1; iwork[sizei + nsub - 1] = nsize; } else { /* A subproblem with E(NM1) small. This implies an 1-by-1 subproblem at D(N), which is not solved explicitly. */ nsize = i__ - st + 1; iwork[sizei + nsub - 1] = nsize; ++nsub; iwork[nsub] = *n; iwork[sizei + nsub - 1] = 1; dcopy_(nrhs, &b[*n + b_dim1], ldb, &work[bx + nm1], n); } st1 = st - 1; if (nsize == 1) { /* This is a 1-by-1 subproblem and is not solved explicitly. */ dcopy_(nrhs, &b[st + b_dim1], ldb, &work[bx + st1], n); } else if (nsize <= *smlsiz) { /* This is a small subproblem and is solved by DLASDQ. */ dlaset_("A", &nsize, &nsize, &c_b2879, &c_b2865, &work[vt + st1], n); dlasdq_("U", &c__0, &nsize, &nsize, &c__0, nrhs, &d__[st], &e[ st], &work[vt + st1], n, &work[nwork], n, &b[st + b_dim1], ldb, &work[nwork], info); if (*info != 0) { return 0; } dlacpy_("A", &nsize, nrhs, &b[st + b_dim1], ldb, &work[bx + st1], n); } else { /* A large problem. Solve it using divide and conquer. */ dlasda_(&icmpq1, smlsiz, &nsize, &sqre, &d__[st], &e[st], & work[u + st1], n, &work[vt + st1], &iwork[k + st1], & work[difl + st1], &work[difr + st1], &work[z__ + st1], &work[poles + st1], &iwork[givptr + st1], &iwork[ givcol + st1], n, &iwork[perm + st1], &work[givnum + st1], &work[c__ + st1], &work[s + st1], &work[nwork], &iwork[iwk], info); if (*info != 0) { return 0; } bxst = bx + st1; dlalsa_(&icmpq2, smlsiz, &nsize, nrhs, &b[st + b_dim1], ldb, & work[bxst], n, &work[u + st1], n, &work[vt + st1], & iwork[k + st1], &work[difl + st1], &work[difr + st1], &work[z__ + st1], &work[poles + st1], &iwork[givptr + st1], &iwork[givcol + st1], n, &iwork[perm + st1], & work[givnum + st1], &work[c__ + st1], &work[s + st1], &work[nwork], &iwork[iwk], info); if (*info != 0) { return 0; } } st = i__ + 1; } /* L60: */ } /* Apply the singular values and treat the tiny ones as zero. */ tol = *rcond * (d__1 = d__[idamax_(n, &d__[1], &c__1)], abs(d__1)); i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { /* Some of the elements in D can be negative because 1-by-1 subproblems were not solved explicitly. */ if ((d__1 = d__[i__], abs(d__1)) <= tol) { dlaset_("A", &c__1, nrhs, &c_b2879, &c_b2879, &work[bx + i__ - 1], n); } else { ++(*rank); dlascl_("G", &c__0, &c__0, &d__[i__], &c_b2865, &c__1, nrhs, & work[bx + i__ - 1], n, info); } d__[i__] = (d__1 = d__[i__], abs(d__1)); /* L70: */ } /* Now apply back the right singular vectors. */ icmpq2 = 1; i__1 = nsub; for (i__ = 1; i__ <= i__1; ++i__) { st = iwork[i__]; st1 = st - 1; nsize = iwork[sizei + i__ - 1]; bxst = bx + st1; if (nsize == 1) { dcopy_(nrhs, &work[bxst], n, &b[st + b_dim1], ldb); } else if (nsize <= *smlsiz) { dgemm_("T", "N", &nsize, nrhs, &nsize, &c_b2865, &work[vt + st1], n, &work[bxst], n, &c_b2879, &b[st + b_dim1], ldb); } else { dlalsa_(&icmpq2, smlsiz, &nsize, nrhs, &work[bxst], n, &b[st + b_dim1], ldb, &work[u + st1], n, &work[vt + st1], &iwork[ k + st1], &work[difl + st1], &work[difr + st1], &work[z__ + st1], &work[poles + st1], &iwork[givptr + st1], &iwork[ givcol + st1], n, &iwork[perm + st1], &work[givnum + st1], &work[c__ + st1], &work[s + st1], &work[nwork], &iwork[ iwk], info); if (*info != 0) { return 0; } } /* L80: */ } /* Unscale and sort the singular values. */ dlascl_("G", &c__0, &c__0, &c_b2865, &orgnrm, n, &c__1, &d__[1], n, info); dlasrt_("D", n, &d__[1], info); dlascl_("G", &c__0, &c__0, &orgnrm, &c_b2865, n, nrhs, &b[b_offset], ldb, info); return 0; /* End of DLALSD */ } /* dlalsd_ */ /* Subroutine */ int dlamrg_(integer *n1, integer *n2, doublereal *a, integer *dtrd1, integer *dtrd2, integer *index) { /* System generated locals */ integer i__1; /* Local variables */ static integer i__, ind1, ind2, n1sv, n2sv; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University September 30, 1994 Purpose ======= DLAMRG will create a permutation list which will merge the elements of A (which is composed of two independently sorted sets) into a single set which is sorted in ascending order. Arguments ========= N1 (input) INTEGER N2 (input) INTEGER These arguements contain the respective lengths of the two sorted lists to be merged. A (input) DOUBLE PRECISION array, dimension (N1+N2) The first N1 elements of A contain a list of numbers which are sorted in either ascending or descending order. Likewise for the final N2 elements. DTRD1 (input) INTEGER DTRD2 (input) INTEGER These are the strides to be taken through the array A. Allowable strides are 1 and -1. They indicate whether a subset of A is sorted in ascending (DTRDx = 1) or descending (DTRDx = -1) order. INDEX (output) INTEGER array, dimension (N1+N2) On exit this array will contain a permutation such that if B( I ) = A( INDEX( I ) ) for I=1,N1+N2, then B will be sorted in ascending order. ===================================================================== */ /* Parameter adjustments */ --index; --a; /* Function Body */ n1sv = *n1; n2sv = *n2; if (*dtrd1 > 0) { ind1 = 1; } else { ind1 = *n1; } if (*dtrd2 > 0) { ind2 = *n1 + 1; } else { ind2 = *n1 + *n2; } i__ = 1; /* while ( (N1SV > 0) & (N2SV > 0) ) */ L10: if (n1sv > 0 && n2sv > 0) { if (a[ind1] <= a[ind2]) { index[i__] = ind1; ++i__; ind1 += *dtrd1; --n1sv; } else { index[i__] = ind2; ++i__; ind2 += *dtrd2; --n2sv; } goto L10; } /* end while */ if (n1sv == 0) { i__1 = n2sv; for (n1sv = 1; n1sv <= i__1; ++n1sv) { index[i__] = ind2; ++i__; ind2 += *dtrd2; /* L20: */ } } else { /* N2SV .EQ. 0 */ i__1 = n1sv; for (n2sv = 1; n2sv <= i__1; ++n2sv) { index[i__] = ind1; ++i__; ind1 += *dtrd1; /* L30: */ } } return 0; /* End of DLAMRG */ } /* dlamrg_ */ doublereal dlange_(char *norm, integer *m, integer *n, doublereal *a, integer *lda, doublereal *work) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2; doublereal ret_val, d__1, d__2, d__3; /* Builtin functions */ double sqrt(doublereal); /* Local variables */ static integer i__, j; static doublereal sum, scale; extern logical lsame_(char *, char *); static doublereal value; extern /* Subroutine */ int dlassq_(integer *, doublereal *, integer *, doublereal *, doublereal *); /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University October 31, 1992 Purpose ======= DLANGE returns the value of the one norm, or the Frobenius norm, or the infinity norm, or the element of largest absolute value of a real matrix A. Description =========== DLANGE returns the value DLANGE = ( max(abs(A(i,j))), NORM = 'M' or 'm' ( ( norm1(A), NORM = '1', 'O' or 'o' ( ( normI(A), NORM = 'I' or 'i' ( ( normF(A), NORM = 'F', 'f', 'E' or 'e' where norm1 denotes the one norm of a matrix (maximum column sum), normI denotes the infinity norm of a matrix (maximum row sum) and normF denotes the Frobenius norm of a matrix (square root of sum of squares). Note that max(abs(A(i,j))) is not a matrix norm. Arguments ========= NORM (input) CHARACTER*1 Specifies the value to be returned in DLANGE as described above. M (input) INTEGER The number of rows of the matrix A. M >= 0. When M = 0, DLANGE is set to zero. N (input) INTEGER The number of columns of the matrix A. N >= 0. When N = 0, DLANGE is set to zero. A (input) DOUBLE PRECISION array, dimension (LDA,N) The m by n matrix A. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(M,1). WORK (workspace) DOUBLE PRECISION array, dimension (LWORK), where LWORK >= M when NORM = 'I'; otherwise, WORK is not referenced. ===================================================================== */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --work; /* Function Body */ if (min(*m,*n) == 0) { value = 0.; } else if (lsame_(norm, "M")) { /* Find max(abs(A(i,j))). */ value = 0.; i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { /* Computing MAX */ d__2 = value, d__3 = (d__1 = a[i__ + j * a_dim1], abs(d__1)); value = max(d__2,d__3); /* L10: */ } /* L20: */ } } else if ((lsame_(norm, "O")) || (*(unsigned char * )norm == '1')) { /* Find norm1(A). */ value = 0.; i__1 = *n; for (j = 1; j <= i__1; ++j) { sum = 0.; i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { sum += (d__1 = a[i__ + j * a_dim1], abs(d__1)); /* L30: */ } value = max(value,sum); /* L40: */ } } else if (lsame_(norm, "I")) { /* Find normI(A). */ i__1 = *m; for (i__ = 1; i__ <= i__1; ++i__) { work[i__] = 0.; /* L50: */ } i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { work[i__] += (d__1 = a[i__ + j * a_dim1], abs(d__1)); /* L60: */ } /* L70: */ } value = 0.; i__1 = *m; for (i__ = 1; i__ <= i__1; ++i__) { /* Computing MAX */ d__1 = value, d__2 = work[i__]; value = max(d__1,d__2); /* L80: */ } } else if ((lsame_(norm, "F")) || (lsame_(norm, "E"))) { /* Find normF(A). */ scale = 0.; sum = 1.; i__1 = *n; for (j = 1; j <= i__1; ++j) { dlassq_(m, &a[j * a_dim1 + 1], &c__1, &scale, &sum); /* L90: */ } value = scale * sqrt(sum); } ret_val = value; return ret_val; /* End of DLANGE */ } /* dlange_ */ doublereal dlanhs_(char *norm, integer *n, doublereal *a, integer *lda, doublereal *work) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3, i__4; doublereal ret_val, d__1, d__2, d__3; /* Builtin functions */ double sqrt(doublereal); /* Local variables */ static integer i__, j; static doublereal sum, scale; extern logical lsame_(char *, char *); static doublereal value; extern /* Subroutine */ int dlassq_(integer *, doublereal *, integer *, doublereal *, doublereal *); /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University October 31, 1992 Purpose ======= DLANHS returns the value of the one norm, or the Frobenius norm, or the infinity norm, or the element of largest absolute value of a Hessenberg matrix A. Description =========== DLANHS returns the value DLANHS = ( max(abs(A(i,j))), NORM = 'M' or 'm' ( ( norm1(A), NORM = '1', 'O' or 'o' ( ( normI(A), NORM = 'I' or 'i' ( ( normF(A), NORM = 'F', 'f', 'E' or 'e' where norm1 denotes the one norm of a matrix (maximum column sum), normI denotes the infinity norm of a matrix (maximum row sum) and normF denotes the Frobenius norm of a matrix (square root of sum of squares). Note that max(abs(A(i,j))) is not a matrix norm. Arguments ========= NORM (input) CHARACTER*1 Specifies the value to be returned in DLANHS as described above. N (input) INTEGER The order of the matrix A. N >= 0. When N = 0, DLANHS is set to zero. A (input) DOUBLE PRECISION array, dimension (LDA,N) The n by n upper Hessenberg matrix A; the part of A below the first sub-diagonal is not referenced. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(N,1). WORK (workspace) DOUBLE PRECISION array, dimension (LWORK), where LWORK >= N when NORM = 'I'; otherwise, WORK is not referenced. ===================================================================== */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --work; /* Function Body */ if (*n == 0) { value = 0.; } else if (lsame_(norm, "M")) { /* Find max(abs(A(i,j))). */ value = 0.; i__1 = *n; for (j = 1; j <= i__1; ++j) { /* Computing MIN */ i__3 = *n, i__4 = j + 1; i__2 = min(i__3,i__4); for (i__ = 1; i__ <= i__2; ++i__) { /* Computing MAX */ d__2 = value, d__3 = (d__1 = a[i__ + j * a_dim1], abs(d__1)); value = max(d__2,d__3); /* L10: */ } /* L20: */ } } else if ((lsame_(norm, "O")) || (*(unsigned char * )norm == '1')) { /* Find norm1(A). */ value = 0.; i__1 = *n; for (j = 1; j <= i__1; ++j) { sum = 0.; /* Computing MIN */ i__3 = *n, i__4 = j + 1; i__2 = min(i__3,i__4); for (i__ = 1; i__ <= i__2; ++i__) { sum += (d__1 = a[i__ + j * a_dim1], abs(d__1)); /* L30: */ } value = max(value,sum); /* L40: */ } } else if (lsame_(norm, "I")) { /* Find normI(A). */ i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { work[i__] = 0.; /* L50: */ } i__1 = *n; for (j = 1; j <= i__1; ++j) { /* Computing MIN */ i__3 = *n, i__4 = j + 1; i__2 = min(i__3,i__4); for (i__ = 1; i__ <= i__2; ++i__) { work[i__] += (d__1 = a[i__ + j * a_dim1], abs(d__1)); /* L60: */ } /* L70: */ } value = 0.; i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { /* Computing MAX */ d__1 = value, d__2 = work[i__]; value = max(d__1,d__2); /* L80: */ } } else if ((lsame_(norm, "F")) || (lsame_(norm, "E"))) { /* Find normF(A). */ scale = 0.; sum = 1.; i__1 = *n; for (j = 1; j <= i__1; ++j) { /* Computing MIN */ i__3 = *n, i__4 = j + 1; i__2 = min(i__3,i__4); dlassq_(&i__2, &a[j * a_dim1 + 1], &c__1, &scale, &sum); /* L90: */ } value = scale * sqrt(sum); } ret_val = value; return ret_val; /* End of DLANHS */ } /* dlanhs_ */ doublereal dlanst_(char *norm, integer *n, doublereal *d__, doublereal *e) { /* System generated locals */ integer i__1; doublereal ret_val, d__1, d__2, d__3, d__4, d__5; /* Builtin functions */ double sqrt(doublereal); /* Local variables */ static integer i__; static doublereal sum, scale; extern logical lsame_(char *, char *); static doublereal anorm; extern /* Subroutine */ int dlassq_(integer *, doublereal *, integer *, doublereal *, doublereal *); /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University February 29, 1992 Purpose ======= DLANST returns the value of the one norm, or the Frobenius norm, or the infinity norm, or the element of largest absolute value of a real symmetric tridiagonal matrix A. Description =========== DLANST returns the value DLANST = ( max(abs(A(i,j))), NORM = 'M' or 'm' ( ( norm1(A), NORM = '1', 'O' or 'o' ( ( normI(A), NORM = 'I' or 'i' ( ( normF(A), NORM = 'F', 'f', 'E' or 'e' where norm1 denotes the one norm of a matrix (maximum column sum), normI denotes the infinity norm of a matrix (maximum row sum) and normF denotes the Frobenius norm of a matrix (square root of sum of squares). Note that max(abs(A(i,j))) is not a matrix norm. Arguments ========= NORM (input) CHARACTER*1 Specifies the value to be returned in DLANST as described above. N (input) INTEGER The order of the matrix A. N >= 0. When N = 0, DLANST is set to zero. D (input) DOUBLE PRECISION array, dimension (N) The diagonal elements of A. E (input) DOUBLE PRECISION array, dimension (N-1) The (n-1) sub-diagonal or super-diagonal elements of A. ===================================================================== */ /* Parameter adjustments */ --e; --d__; /* Function Body */ if (*n <= 0) { anorm = 0.; } else if (lsame_(norm, "M")) { /* Find max(abs(A(i,j))). */ anorm = (d__1 = d__[*n], abs(d__1)); i__1 = *n - 1; for (i__ = 1; i__ <= i__1; ++i__) { /* Computing MAX */ d__2 = anorm, d__3 = (d__1 = d__[i__], abs(d__1)); anorm = max(d__2,d__3); /* Computing MAX */ d__2 = anorm, d__3 = (d__1 = e[i__], abs(d__1)); anorm = max(d__2,d__3); /* L10: */ } } else if (((lsame_(norm, "O")) || (*(unsigned char *)norm == '1')) || (lsame_(norm, "I"))) { /* Find norm1(A). */ if (*n == 1) { anorm = abs(d__[1]); } else { /* Computing MAX */ d__3 = abs(d__[1]) + abs(e[1]), d__4 = (d__1 = e[*n - 1], abs( d__1)) + (d__2 = d__[*n], abs(d__2)); anorm = max(d__3,d__4); i__1 = *n - 1; for (i__ = 2; i__ <= i__1; ++i__) { /* Computing MAX */ d__4 = anorm, d__5 = (d__1 = d__[i__], abs(d__1)) + (d__2 = e[ i__], abs(d__2)) + (d__3 = e[i__ - 1], abs(d__3)); anorm = max(d__4,d__5); /* L20: */ } } } else if ((lsame_(norm, "F")) || (lsame_(norm, "E"))) { /* Find normF(A). */ scale = 0.; sum = 1.; if (*n > 1) { i__1 = *n - 1; dlassq_(&i__1, &e[1], &c__1, &scale, &sum); sum *= 2; } dlassq_(n, &d__[1], &c__1, &scale, &sum); anorm = scale * sqrt(sum); } ret_val = anorm; return ret_val; /* End of DLANST */ } /* dlanst_ */ doublereal dlansy_(char *norm, char *uplo, integer *n, doublereal *a, integer *lda, doublereal *work) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2; doublereal ret_val, d__1, d__2, d__3; /* Builtin functions */ double sqrt(doublereal); /* Local variables */ static integer i__, j; static doublereal sum, absa, scale; extern logical lsame_(char *, char *); static doublereal value; extern /* Subroutine */ int dlassq_(integer *, doublereal *, integer *, doublereal *, doublereal *); /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University October 31, 1992 Purpose ======= DLANSY returns the value of the one norm, or the Frobenius norm, or the infinity norm, or the element of largest absolute value of a real symmetric matrix A. Description =========== DLANSY returns the value DLANSY = ( max(abs(A(i,j))), NORM = 'M' or 'm' ( ( norm1(A), NORM = '1', 'O' or 'o' ( ( normI(A), NORM = 'I' or 'i' ( ( normF(A), NORM = 'F', 'f', 'E' or 'e' where norm1 denotes the one norm of a matrix (maximum column sum), normI denotes the infinity norm of a matrix (maximum row sum) and normF denotes the Frobenius norm of a matrix (square root of sum of squares). Note that max(abs(A(i,j))) is not a matrix norm. Arguments ========= NORM (input) CHARACTER*1 Specifies the value to be returned in DLANSY as described above. UPLO (input) CHARACTER*1 Specifies whether the upper or lower triangular part of the symmetric matrix A is to be referenced. = 'U': Upper triangular part of A is referenced = 'L': Lower triangular part of A is referenced N (input) INTEGER The order of the matrix A. N >= 0. When N = 0, DLANSY is set to zero. A (input) DOUBLE PRECISION array, dimension (LDA,N) 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, and the strictly lower triangular part of A is not referenced. If UPLO = 'L', the leading n by n lower triangular part of A contains the lower triangular part of the matrix A, and the strictly upper triangular part of A is not referenced. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(N,1). WORK (workspace) DOUBLE PRECISION array, dimension (LWORK), where LWORK >= N when NORM = 'I' or '1' or 'O'; otherwise, WORK is not referenced. ===================================================================== */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --work; /* Function Body */ if (*n == 0) { value = 0.; } else if (lsame_(norm, "M")) { /* Find max(abs(A(i,j))). */ value = 0.; if (lsame_(uplo, "U")) { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = j; for (i__ = 1; i__ <= i__2; ++i__) { /* Computing MAX */ d__2 = value, d__3 = (d__1 = a[i__ + j * a_dim1], abs( d__1)); value = max(d__2,d__3); /* L10: */ } /* L20: */ } } else { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *n; for (i__ = j; i__ <= i__2; ++i__) { /* Computing MAX */ d__2 = value, d__3 = (d__1 = a[i__ + j * a_dim1], abs( d__1)); value = max(d__2,d__3); /* L30: */ } /* L40: */ } } } else if (((lsame_(norm, "I")) || (lsame_(norm, "O"))) || (*(unsigned char *)norm == '1')) { /* Find normI(A) ( = norm1(A), since A is symmetric). */ value = 0.; if (lsame_(uplo, "U")) { i__1 = *n; for (j = 1; j <= i__1; ++j) { sum = 0.; i__2 = j - 1; for (i__ = 1; i__ <= i__2; ++i__) { absa = (d__1 = a[i__ + j * a_dim1], abs(d__1)); sum += absa; work[i__] += absa; /* L50: */ } work[j] = sum + (d__1 = a[j + j * a_dim1], abs(d__1)); /* L60: */ } i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { /* Computing MAX */ d__1 = value, d__2 = work[i__]; value = max(d__1,d__2); /* L70: */ } } else { i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { work[i__] = 0.; /* L80: */ } i__1 = *n; for (j = 1; j <= i__1; ++j) { sum = work[j] + (d__1 = a[j + j * a_dim1], abs(d__1)); i__2 = *n; for (i__ = j + 1; i__ <= i__2; ++i__) { absa = (d__1 = a[i__ + j * a_dim1], abs(d__1)); sum += absa; work[i__] += absa; /* L90: */ } value = max(value,sum); /* L100: */ } } } else if ((lsame_(norm, "F")) || (lsame_(norm, "E"))) { /* Find normF(A). */ scale = 0.; sum = 1.; if (lsame_(uplo, "U")) { i__1 = *n; for (j = 2; j <= i__1; ++j) { i__2 = j - 1; dlassq_(&i__2, &a[j * a_dim1 + 1], &c__1, &scale, &sum); /* L110: */ } } else { i__1 = *n - 1; for (j = 1; j <= i__1; ++j) { i__2 = *n - j; dlassq_(&i__2, &a[j + 1 + j * a_dim1], &c__1, &scale, &sum); /* L120: */ } } sum *= 2; i__1 = *lda + 1; dlassq_(n, &a[a_offset], &i__1, &scale, &sum); value = scale * sqrt(sum); } ret_val = value; return ret_val; /* End of DLANSY */ } /* dlansy_ */ /* Subroutine */ int dlanv2_(doublereal *a, doublereal *b, doublereal *c__, doublereal *d__, doublereal *rt1r, doublereal *rt1i, doublereal *rt2r, doublereal *rt2i, doublereal *cs, doublereal *sn) { /* System generated locals */ doublereal d__1, d__2; /* Builtin functions */ double d_sign(doublereal *, doublereal *), sqrt(doublereal); /* Local variables */ static doublereal p, z__, aa, bb, cc, dd, cs1, sn1, sab, sac, eps, tau, temp, scale, bcmax, bcmis, sigma; /* -- LAPACK driver routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= DLANV2 computes the Schur factorization of a real 2-by-2 nonsymmetric matrix in standard form: [ A B ] = [ CS -SN ] [ AA BB ] [ CS SN ] [ C D ] [ SN CS ] [ CC DD ] [-SN CS ] where either 1) CC = 0 so that AA and DD are real eigenvalues of the matrix, or 2) AA = DD and BB*CC < 0, so that AA + or - sqrt(BB*CC) are complex conjugate eigenvalues. Arguments ========= A (input/output) DOUBLE PRECISION B (input/output) DOUBLE PRECISION C (input/output) DOUBLE PRECISION D (input/output) DOUBLE PRECISION On entry, the elements of the input matrix. On exit, they are overwritten by the elements of the standardised Schur form. RT1R (output) DOUBLE PRECISION RT1I (output) DOUBLE PRECISION RT2R (output) DOUBLE PRECISION RT2I (output) DOUBLE PRECISION The real and imaginary parts of the eigenvalues. If the eigenvalues are a complex conjugate pair, RT1I > 0. CS (output) DOUBLE PRECISION SN (output) DOUBLE PRECISION Parameters of the rotation matrix. Further Details =============== Modified by V. Sima, Research Institute for Informatics, Bucharest, Romania, to reduce the risk of cancellation errors, when computing real eigenvalues, and to ensure, if possible, that abs(RT1R) >= abs(RT2R). ===================================================================== */ eps = PRECISION; if (*c__ == 0.) { *cs = 1.; *sn = 0.; goto L10; } else if (*b == 0.) { /* Swap rows and columns */ *cs = 0.; *sn = 1.; temp = *d__; *d__ = *a; *a = temp; *b = -(*c__); *c__ = 0.; goto L10; } else if (*a - *d__ == 0. && d_sign(&c_b2865, b) != d_sign(&c_b2865, c__) ) { *cs = 1.; *sn = 0.; goto L10; } else { temp = *a - *d__; p = temp * .5; /* Computing MAX */ d__1 = abs(*b), d__2 = abs(*c__); bcmax = max(d__1,d__2); /* Computing MIN */ d__1 = abs(*b), d__2 = abs(*c__); bcmis = min(d__1,d__2) * d_sign(&c_b2865, b) * d_sign(&c_b2865, c__); /* Computing MAX */ d__1 = abs(p); scale = max(d__1,bcmax); z__ = p / scale * p + bcmax / scale * bcmis; /* If Z is of the order of the machine accuracy, postpone the decision on the nature of eigenvalues */ if (z__ >= eps * 4.) { /* Real eigenvalues. Compute A and D. */ d__1 = sqrt(scale) * sqrt(z__); z__ = p + d_sign(&d__1, &p); *a = *d__ + z__; *d__ -= bcmax / z__ * bcmis; /* Compute B and the rotation matrix */ tau = dlapy2_(c__, &z__); *cs = z__ / tau; *sn = *c__ / tau; *b -= *c__; *c__ = 0.; } else { /* Complex eigenvalues, or real (almost) equal eigenvalues. Make diagonal elements equal. */ sigma = *b + *c__; tau = dlapy2_(&sigma, &temp); *cs = sqrt((abs(sigma) / tau + 1.) * .5); *sn = -(p / (tau * *cs)) * d_sign(&c_b2865, &sigma); /* Compute [ AA BB ] = [ A B ] [ CS -SN ] [ CC DD ] [ C D ] [ SN CS ] */ aa = *a * *cs + *b * *sn; bb = -(*a) * *sn + *b * *cs; cc = *c__ * *cs + *d__ * *sn; dd = -(*c__) * *sn + *d__ * *cs; /* Compute [ A B ] = [ CS SN ] [ AA BB ] [ C D ] [-SN CS ] [ CC DD ] */ *a = aa * *cs + cc * *sn; *b = bb * *cs + dd * *sn; *c__ = -aa * *sn + cc * *cs; *d__ = -bb * *sn + dd * *cs; temp = (*a + *d__) * .5; *a = temp; *d__ = temp; if (*c__ != 0.) { if (*b != 0.) { if (d_sign(&c_b2865, b) == d_sign(&c_b2865, c__)) { /* Real eigenvalues: reduce to upper triangular form */ sab = sqrt((abs(*b))); sac = sqrt((abs(*c__))); d__1 = sab * sac; p = d_sign(&d__1, c__); tau = 1. / sqrt((d__1 = *b + *c__, abs(d__1))); *a = temp + p; *d__ = temp - p; *b -= *c__; *c__ = 0.; cs1 = sab * tau; sn1 = sac * tau; temp = *cs * cs1 - *sn * sn1; *sn = *cs * sn1 + *sn * cs1; *cs = temp; } } else { *b = -(*c__); *c__ = 0.; temp = *cs; *cs = -(*sn); *sn = temp; } } } } L10: /* Store eigenvalues in (RT1R,RT1I) and (RT2R,RT2I). */ *rt1r = *a; *rt2r = *d__; if (*c__ == 0.) { *rt1i = 0.; *rt2i = 0.; } else { *rt1i = sqrt((abs(*b))) * sqrt((abs(*c__))); *rt2i = -(*rt1i); } return 0; /* End of DLANV2 */ } /* dlanv2_ */ doublereal dlapy2_(doublereal *x, doublereal *y) { /* System generated locals */ doublereal ret_val, d__1; /* Builtin functions */ double sqrt(doublereal); /* Local variables */ static doublereal w, z__, xabs, yabs; /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University October 31, 1992 Purpose ======= DLAPY2 returns sqrt(x**2+y**2), taking care not to cause unnecessary overflow. Arguments ========= X (input) DOUBLE PRECISION Y (input) DOUBLE PRECISION X and Y specify the values x and y. ===================================================================== */ xabs = abs(*x); yabs = abs(*y); w = max(xabs,yabs); z__ = min(xabs,yabs); if (z__ == 0.) { ret_val = w; } else { /* Computing 2nd power */ d__1 = z__ / w; ret_val = w * sqrt(d__1 * d__1 + 1.); } return ret_val; /* End of DLAPY2 */ } /* dlapy2_ */ doublereal dlapy3_(doublereal *x, doublereal *y, doublereal *z__) { /* System generated locals */ doublereal ret_val, d__1, d__2, d__3; /* Builtin functions */ double sqrt(doublereal); /* Local variables */ static doublereal w, xabs, yabs, zabs; /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University October 31, 1992 Purpose ======= DLAPY3 returns sqrt(x**2+y**2+z**2), taking care not to cause unnecessary overflow. Arguments ========= X (input) DOUBLE PRECISION Y (input) DOUBLE PRECISION Z (input) DOUBLE PRECISION X, Y and Z specify the values x, y and z. ===================================================================== */ xabs = abs(*x); yabs = abs(*y); zabs = abs(*z__); /* Computing MAX */ d__1 = max(xabs,yabs); w = max(d__1,zabs); if (w == 0.) { ret_val = 0.; } else { /* Computing 2nd power */ d__1 = xabs / w; /* Computing 2nd power */ d__2 = yabs / w; /* Computing 2nd power */ d__3 = zabs / w; ret_val = w * sqrt(d__1 * d__1 + d__2 * d__2 + d__3 * d__3); } return ret_val; /* End of DLAPY3 */ } /* dlapy3_ */ /* Subroutine */ int dlarf_(char *side, integer *m, integer *n, doublereal *v, integer *incv, doublereal *tau, doublereal *c__, integer *ldc, doublereal *work) { /* System generated locals */ integer c_dim1, c_offset; doublereal d__1; /* Local variables */ extern /* Subroutine */ int dger_(integer *, integer *, doublereal *, doublereal *, integer *, doublereal *, integer *, doublereal *, integer *); extern logical lsame_(char *, char *); extern /* Subroutine */ int dgemv_(char *, integer *, integer *, doublereal *, doublereal *, integer *, doublereal *, integer *, doublereal *, doublereal *, integer *); /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University February 29, 1992 Purpose ======= DLARF applies a real elementary reflector H to a real m by n matrix C, from either the left or the right. H is represented in the form H = I - tau * v * v' where tau is a real scalar and v is a real vector. If tau = 0, then H is taken to be the unit matrix. Arguments ========= SIDE (input) CHARACTER*1 = 'L': form H * C = 'R': form C * H M (input) INTEGER The number of rows of the matrix C. N (input) INTEGER The number of columns of the matrix C. V (input) DOUBLE PRECISION array, dimension (1 + (M-1)*abs(INCV)) if SIDE = 'L' or (1 + (N-1)*abs(INCV)) if SIDE = 'R' The vector v in the representation of H. V is not used if TAU = 0. INCV (input) INTEGER The increment between elements of v. INCV <> 0. TAU (input) DOUBLE PRECISION The value tau in the representation of H. C (input/output) DOUBLE PRECISION array, dimension (LDC,N) On entry, the m by n matrix C. On exit, C is overwritten by the matrix H * C if SIDE = 'L', or C * H if SIDE = 'R'. LDC (input) INTEGER The leading dimension of the array C. LDC >= max(1,M). WORK (workspace) DOUBLE PRECISION array, dimension (N) if SIDE = 'L' or (M) if SIDE = 'R' ===================================================================== */ /* Parameter adjustments */ --v; c_dim1 = *ldc; c_offset = 1 + c_dim1; c__ -= c_offset; --work; /* Function Body */ if (lsame_(side, "L")) { /* Form H * C */ if (*tau != 0.) { /* w := C' * v */ dgemv_("Transpose", m, n, &c_b2865, &c__[c_offset], ldc, &v[1], incv, &c_b2879, &work[1], &c__1); /* C := C - v * w' */ d__1 = -(*tau); dger_(m, n, &d__1, &v[1], incv, &work[1], &c__1, &c__[c_offset], ldc); } } else { /* Form C * H */ if (*tau != 0.) { /* w := C * v */ dgemv_("No transpose", m, n, &c_b2865, &c__[c_offset], ldc, &v[1], incv, &c_b2879, &work[1], &c__1); /* C := C - w * v' */ d__1 = -(*tau); dger_(m, n, &d__1, &work[1], &c__1, &v[1], incv, &c__[c_offset], ldc); } } return 0; /* End of DLARF */ } /* dlarf_ */ /* Subroutine */ int dlarfb_(char *side, char *trans, char *direct, char * storev, integer *m, integer *n, integer *k, doublereal *v, integer * ldv, doublereal *t, integer *ldt, doublereal *c__, integer *ldc, doublereal *work, integer *ldwork) { /* System generated locals */ integer c_dim1, c_offset, t_dim1, t_offset, v_dim1, v_offset, work_dim1, work_offset, i__1, i__2; /* Local variables */ static integer i__, j; extern /* Subroutine */ int dgemm_(char *, char *, integer *, integer *, integer *, doublereal *, doublereal *, integer *, doublereal *, integer *, doublereal *, doublereal *, integer *); extern logical lsame_(char *, char *); extern /* Subroutine */ int dcopy_(integer *, doublereal *, integer *, doublereal *, integer *), dtrmm_(char *, char *, char *, char *, integer *, integer *, doublereal *, doublereal *, integer *, doublereal *, integer *); static char transt[1]; /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University February 29, 1992 Purpose ======= DLARFB applies a real block reflector H or its transpose H' to a real m by n matrix C, from either the left or the right. Arguments ========= SIDE (input) CHARACTER*1 = 'L': apply H or H' from the Left = 'R': apply H or H' from the Right TRANS (input) CHARACTER*1 = 'N': apply H (No transpose) = 'T': apply H' (Transpose) DIRECT (input) CHARACTER*1 Indicates how H is formed from a product of elementary reflectors = 'F': H = H(1) H(2) . . . H(k) (Forward) = 'B': H = H(k) . . . H(2) H(1) (Backward) STOREV (input) CHARACTER*1 Indicates how the vectors which define the elementary reflectors are stored: = 'C': Columnwise = 'R': Rowwise M (input) INTEGER The number of rows of the matrix C. N (input) INTEGER The number of columns of the matrix C. K (input) INTEGER The order of the matrix T (= the number of elementary reflectors whose product defines the block reflector). V (input) DOUBLE PRECISION array, dimension (LDV,K) if STOREV = 'C' (LDV,M) if STOREV = 'R' and SIDE = 'L' (LDV,N) if STOREV = 'R' and SIDE = 'R' The matrix V. See further details. LDV (input) INTEGER The leading dimension of the array V. If STOREV = 'C' and SIDE = 'L', LDV >= max(1,M); if STOREV = 'C' and SIDE = 'R', LDV >= max(1,N); if STOREV = 'R', LDV >= K. T (input) DOUBLE PRECISION array, dimension (LDT,K) The triangular k by k matrix T in the representation of the block reflector. LDT (input) INTEGER The leading dimension of the array T. LDT >= K. C (input/output) DOUBLE PRECISION array, dimension (LDC,N) On entry, the m by n matrix C. On exit, C is overwritten by H*C or H'*C or C*H or C*H'. LDC (input) INTEGER The leading dimension of the array C. LDA >= max(1,M). WORK (workspace) DOUBLE PRECISION array, dimension (LDWORK,K) LDWORK (input) INTEGER The leading dimension of the array WORK. If SIDE = 'L', LDWORK >= max(1,N); if SIDE = 'R', LDWORK >= max(1,M). ===================================================================== Quick return if possible */ /* Parameter adjustments */ v_dim1 = *ldv; v_offset = 1 + v_dim1; v -= v_offset; t_dim1 = *ldt; t_offset = 1 + t_dim1; t -= t_offset; c_dim1 = *ldc; c_offset = 1 + c_dim1; c__ -= c_offset; work_dim1 = *ldwork; work_offset = 1 + work_dim1; work -= work_offset; /* Function Body */ if ((*m <= 0) || (*n <= 0)) { return 0; } if (lsame_(trans, "N")) { *(unsigned char *)transt = 'T'; } else { *(unsigned char *)transt = 'N'; } if (lsame_(storev, "C")) { if (lsame_(direct, "F")) { /* Let V = ( V1 ) (first K rows) ( V2 ) where V1 is unit lower triangular. */ if (lsame_(side, "L")) { /* Form H * C or H' * C where C = ( C1 ) ( C2 ) W := C' * V = (C1'*V1 + C2'*V2) (stored in WORK) W := C1' */ i__1 = *k; for (j = 1; j <= i__1; ++j) { dcopy_(n, &c__[j + c_dim1], ldc, &work[j * work_dim1 + 1], &c__1); /* L10: */ } /* W := W * V1 */ dtrmm_("Right", "Lower", "No transpose", "Unit", n, k, & c_b2865, &v[v_offset], ldv, &work[work_offset], ldwork); if (*m > *k) { /* W := W + C2'*V2 */ i__1 = *m - *k; dgemm_("Transpose", "No transpose", n, k, &i__1, &c_b2865, &c__[*k + 1 + c_dim1], ldc, &v[*k + 1 + v_dim1], ldv, &c_b2865, &work[work_offset], ldwork); } /* W := W * T' or W * T */ dtrmm_("Right", "Upper", transt, "Non-unit", n, k, &c_b2865, & t[t_offset], ldt, &work[work_offset], ldwork); /* C := C - V * W' */ if (*m > *k) { /* C2 := C2 - V2 * W' */ i__1 = *m - *k; dgemm_("No transpose", "Transpose", &i__1, n, k, &c_b3001, &v[*k + 1 + v_dim1], ldv, &work[work_offset], ldwork, &c_b2865, &c__[*k + 1 + c_dim1], ldc); } /* W := W * V1' */ dtrmm_("Right", "Lower", "Transpose", "Unit", n, k, &c_b2865, &v[v_offset], ldv, &work[work_offset], ldwork); /* C1 := C1 - W' */ i__1 = *k; for (j = 1; j <= i__1; ++j) { i__2 = *n; for (i__ = 1; i__ <= i__2; ++i__) { c__[j + i__ * c_dim1] -= work[i__ + j * work_dim1]; /* L20: */ } /* L30: */ } } else if (lsame_(side, "R")) { /* Form C * H or C * H' where C = ( C1 C2 ) W := C * V = (C1*V1 + C2*V2) (stored in WORK) W := C1 */ i__1 = *k; for (j = 1; j <= i__1; ++j) { dcopy_(m, &c__[j * c_dim1 + 1], &c__1, &work[j * work_dim1 + 1], &c__1); /* L40: */ } /* W := W * V1 */ dtrmm_("Right", "Lower", "No transpose", "Unit", m, k, & c_b2865, &v[v_offset], ldv, &work[work_offset], ldwork); if (*n > *k) { /* W := W + C2 * V2 */ i__1 = *n - *k; dgemm_("No transpose", "No transpose", m, k, &i__1, & c_b2865, &c__[(*k + 1) * c_dim1 + 1], ldc, &v[*k + 1 + v_dim1], ldv, &c_b2865, &work[work_offset], ldwork); } /* W := W * T or W * T' */ dtrmm_("Right", "Upper", trans, "Non-unit", m, k, &c_b2865, & t[t_offset], ldt, &work[work_offset], ldwork); /* C := C - W * V' */ if (*n > *k) { /* C2 := C2 - W * V2' */ i__1 = *n - *k; dgemm_("No transpose", "Transpose", m, &i__1, k, &c_b3001, &work[work_offset], ldwork, &v[*k + 1 + v_dim1], ldv, &c_b2865, &c__[(*k + 1) * c_dim1 + 1], ldc); } /* W := W * V1' */ dtrmm_("Right", "Lower", "Transpose", "Unit", m, k, &c_b2865, &v[v_offset], ldv, &work[work_offset], ldwork); /* C1 := C1 - W */ i__1 = *k; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { c__[i__ + j * c_dim1] -= work[i__ + j * work_dim1]; /* L50: */ } /* L60: */ } } } else { /* Let V = ( V1 ) ( V2 ) (last K rows) where V2 is unit upper triangular. */ if (lsame_(side, "L")) { /* Form H * C or H' * C where C = ( C1 ) ( C2 ) W := C' * V = (C1'*V1 + C2'*V2) (stored in WORK) W := C2' */ i__1 = *k; for (j = 1; j <= i__1; ++j) { dcopy_(n, &c__[*m - *k + j + c_dim1], ldc, &work[j * work_dim1 + 1], &c__1); /* L70: */ } /* W := W * V2 */ dtrmm_("Right", "Upper", "No transpose", "Unit", n, k, & c_b2865, &v[*m - *k + 1 + v_dim1], ldv, &work[ work_offset], ldwork); if (*m > *k) { /* W := W + C1'*V1 */ i__1 = *m - *k; dgemm_("Transpose", "No transpose", n, k, &i__1, &c_b2865, &c__[c_offset], ldc, &v[v_offset], ldv, &c_b2865, &work[work_offset], ldwork); } /* W := W * T' or W * T */ dtrmm_("Right", "Lower", transt, "Non-unit", n, k, &c_b2865, & t[t_offset], ldt, &work[work_offset], ldwork); /* C := C - V * W' */ if (*m > *k) { /* C1 := C1 - V1 * W' */ i__1 = *m - *k; dgemm_("No transpose", "Transpose", &i__1, n, k, &c_b3001, &v[v_offset], ldv, &work[work_offset], ldwork, & c_b2865, &c__[c_offset], ldc); } /* W := W * V2' */ dtrmm_("Right", "Upper", "Transpose", "Unit", n, k, &c_b2865, &v[*m - *k + 1 + v_dim1], ldv, &work[work_offset], ldwork); /* C2 := C2 - W' */ i__1 = *k; for (j = 1; j <= i__1; ++j) { i__2 = *n; for (i__ = 1; i__ <= i__2; ++i__) { c__[*m - *k + j + i__ * c_dim1] -= work[i__ + j * work_dim1]; /* L80: */ } /* L90: */ } } else if (lsame_(side, "R")) { /* Form C * H or C * H' where C = ( C1 C2 ) W := C * V = (C1*V1 + C2*V2) (stored in WORK) W := C2 */ i__1 = *k; for (j = 1; j <= i__1; ++j) { dcopy_(m, &c__[(*n - *k + j) * c_dim1 + 1], &c__1, &work[ j * work_dim1 + 1], &c__1); /* L100: */ } /* W := W * V2 */ dtrmm_("Right", "Upper", "No transpose", "Unit", m, k, & c_b2865, &v[*n - *k + 1 + v_dim1], ldv, &work[ work_offset], ldwork); if (*n > *k) { /* W := W + C1 * V1 */ i__1 = *n - *k; dgemm_("No transpose", "No transpose", m, k, &i__1, & c_b2865, &c__[c_offset], ldc, &v[v_offset], ldv, & c_b2865, &work[work_offset], ldwork); } /* W := W * T or W * T' */ dtrmm_("Right", "Lower", trans, "Non-unit", m, k, &c_b2865, & t[t_offset], ldt, &work[work_offset], ldwork); /* C := C - W * V' */ if (*n > *k) { /* C1 := C1 - W * V1' */ i__1 = *n - *k; dgemm_("No transpose", "Transpose", m, &i__1, k, &c_b3001, &work[work_offset], ldwork, &v[v_offset], ldv, & c_b2865, &c__[c_offset], ldc); } /* W := W * V2' */ dtrmm_("Right", "Upper", "Transpose", "Unit", m, k, &c_b2865, &v[*n - *k + 1 + v_dim1], ldv, &work[work_offset], ldwork); /* C2 := C2 - W */ i__1 = *k; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { c__[i__ + (*n - *k + j) * c_dim1] -= work[i__ + j * work_dim1]; /* L110: */ } /* L120: */ } } } } else if (lsame_(storev, "R")) { if (lsame_(direct, "F")) { /* Let V = ( V1 V2 ) (V1: first K columns) where V1 is unit upper triangular. */ if (lsame_(side, "L")) { /* Form H * C or H' * C where C = ( C1 ) ( C2 ) W := C' * V' = (C1'*V1' + C2'*V2') (stored in WORK) W := C1' */ i__1 = *k; for (j = 1; j <= i__1; ++j) { dcopy_(n, &c__[j + c_dim1], ldc, &work[j * work_dim1 + 1], &c__1); /* L130: */ } /* W := W * V1' */ dtrmm_("Right", "Upper", "Transpose", "Unit", n, k, &c_b2865, &v[v_offset], ldv, &work[work_offset], ldwork); if (*m > *k) { /* W := W + C2'*V2' */ i__1 = *m - *k; dgemm_("Transpose", "Transpose", n, k, &i__1, &c_b2865, & c__[*k + 1 + c_dim1], ldc, &v[(*k + 1) * v_dim1 + 1], ldv, &c_b2865, &work[work_offset], ldwork); } /* W := W * T' or W * T */ dtrmm_("Right", "Upper", transt, "Non-unit", n, k, &c_b2865, & t[t_offset], ldt, &work[work_offset], ldwork); /* C := C - V' * W' */ if (*m > *k) { /* C2 := C2 - V2' * W' */ i__1 = *m - *k; dgemm_("Transpose", "Transpose", &i__1, n, k, &c_b3001, & v[(*k + 1) * v_dim1 + 1], ldv, &work[work_offset], ldwork, &c_b2865, &c__[*k + 1 + c_dim1], ldc); } /* W := W * V1 */ dtrmm_("Right", "Upper", "No transpose", "Unit", n, k, & c_b2865, &v[v_offset], ldv, &work[work_offset], ldwork); /* C1 := C1 - W' */ i__1 = *k; for (j = 1; j <= i__1; ++j) { i__2 = *n; for (i__ = 1; i__ <= i__2; ++i__) { c__[j + i__ * c_dim1] -= work[i__ + j * work_dim1]; /* L140: */ } /* L150: */ } } else if (lsame_(side, "R")) { /* Form C * H or C * H' where C = ( C1 C2 ) W := C * V' = (C1*V1' + C2*V2') (stored in WORK) W := C1 */ i__1 = *k; for (j = 1; j <= i__1; ++j) { dcopy_(m, &c__[j * c_dim1 + 1], &c__1, &work[j * work_dim1 + 1], &c__1); /* L160: */ } /* W := W * V1' */ dtrmm_("Right", "Upper", "Transpose", "Unit", m, k, &c_b2865, &v[v_offset], ldv, &work[work_offset], ldwork); if (*n > *k) { /* W := W + C2 * V2' */ i__1 = *n - *k; dgemm_("No transpose", "Transpose", m, k, &i__1, &c_b2865, &c__[(*k + 1) * c_dim1 + 1], ldc, &v[(*k + 1) * v_dim1 + 1], ldv, &c_b2865, &work[work_offset], ldwork); } /* W := W * T or W * T' */ dtrmm_("Right", "Upper", trans, "Non-unit", m, k, &c_b2865, & t[t_offset], ldt, &work[work_offset], ldwork); /* C := C - W * V */ if (*n > *k) { /* C2 := C2 - W * V2 */ i__1 = *n - *k; dgemm_("No transpose", "No transpose", m, &i__1, k, & c_b3001, &work[work_offset], ldwork, &v[(*k + 1) * v_dim1 + 1], ldv, &c_b2865, &c__[(*k + 1) * c_dim1 + 1], ldc); } /* W := W * V1 */ dtrmm_("Right", "Upper", "No transpose", "Unit", m, k, & c_b2865, &v[v_offset], ldv, &work[work_offset], ldwork); /* C1 := C1 - W */ i__1 = *k; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { c__[i__ + j * c_dim1] -= work[i__ + j * work_dim1]; /* L170: */ } /* L180: */ } } } else { /* Let V = ( V1 V2 ) (V2: last K columns) where V2 is unit lower triangular. */ if (lsame_(side, "L")) { /* Form H * C or H' * C where C = ( C1 ) ( C2 ) W := C' * V' = (C1'*V1' + C2'*V2') (stored in WORK) W := C2' */ i__1 = *k; for (j = 1; j <= i__1; ++j) { dcopy_(n, &c__[*m - *k + j + c_dim1], ldc, &work[j * work_dim1 + 1], &c__1); /* L190: */ } /* W := W * V2' */ dtrmm_("Right", "Lower", "Transpose", "Unit", n, k, &c_b2865, &v[(*m - *k + 1) * v_dim1 + 1], ldv, &work[ work_offset], ldwork); if (*m > *k) { /* W := W + C1'*V1' */ i__1 = *m - *k; dgemm_("Transpose", "Transpose", n, k, &i__1, &c_b2865, & c__[c_offset], ldc, &v[v_offset], ldv, &c_b2865, & work[work_offset], ldwork); } /* W := W * T' or W * T */ dtrmm_("Right", "Lower", transt, "Non-unit", n, k, &c_b2865, & t[t_offset], ldt, &work[work_offset], ldwork); /* C := C - V' * W' */ if (*m > *k) { /* C1 := C1 - V1' * W' */ i__1 = *m - *k; dgemm_("Transpose", "Transpose", &i__1, n, k, &c_b3001, & v[v_offset], ldv, &work[work_offset], ldwork, & c_b2865, &c__[c_offset], ldc); } /* W := W * V2 */ dtrmm_("Right", "Lower", "No transpose", "Unit", n, k, & c_b2865, &v[(*m - *k + 1) * v_dim1 + 1], ldv, &work[ work_offset], ldwork); /* C2 := C2 - W' */ i__1 = *k; for (j = 1; j <= i__1; ++j) { i__2 = *n; for (i__ = 1; i__ <= i__2; ++i__) { c__[*m - *k + j + i__ * c_dim1] -= work[i__ + j * work_dim1]; /* L200: */ } /* L210: */ } } else if (lsame_(side, "R")) { /* Form C * H or C * H' where C = ( C1 C2 ) W := C * V' = (C1*V1' + C2*V2') (stored in WORK) W := C2 */ i__1 = *k; for (j = 1; j <= i__1; ++j) { dcopy_(m, &c__[(*n - *k + j) * c_dim1 + 1], &c__1, &work[ j * work_dim1 + 1], &c__1); /* L220: */ } /* W := W * V2' */ dtrmm_("Right", "Lower", "Transpose", "Unit", m, k, &c_b2865, &v[(*n - *k + 1) * v_dim1 + 1], ldv, &work[ work_offset], ldwork); if (*n > *k) { /* W := W + C1 * V1' */ i__1 = *n - *k; dgemm_("No transpose", "Transpose", m, k, &i__1, &c_b2865, &c__[c_offset], ldc, &v[v_offset], ldv, &c_b2865, &work[work_offset], ldwork); } /* W := W * T or W * T' */ dtrmm_("Right", "Lower", trans, "Non-unit", m, k, &c_b2865, & t[t_offset], ldt, &work[work_offset], ldwork); /* C := C - W * V */ if (*n > *k) { /* C1 := C1 - W * V1 */ i__1 = *n - *k; dgemm_("No transpose", "No transpose", m, &i__1, k, & c_b3001, &work[work_offset], ldwork, &v[v_offset], ldv, &c_b2865, &c__[c_offset], ldc); } /* W := W * V2 */ dtrmm_("Right", "Lower", "No transpose", "Unit", m, k, & c_b2865, &v[(*n - *k + 1) * v_dim1 + 1], ldv, &work[ work_offset], ldwork); /* C1 := C1 - W */ i__1 = *k; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { c__[i__ + (*n - *k + j) * c_dim1] -= work[i__ + j * work_dim1]; /* L230: */ } /* L240: */ } } } } return 0; /* End of DLARFB */ } /* dlarfb_ */ /* Subroutine */ int dlarfg_(integer *n, doublereal *alpha, doublereal *x, integer *incx, doublereal *tau) { /* System generated locals */ integer i__1; doublereal d__1; /* Builtin functions */ double d_sign(doublereal *, doublereal *); /* Local variables */ static integer j, knt; static doublereal beta; extern doublereal dnrm2_(integer *, doublereal *, integer *); extern /* Subroutine */ int dscal_(integer *, doublereal *, doublereal *, integer *); static doublereal xnorm; static doublereal safmin, rsafmn; /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University September 30, 1994 Purpose ======= DLARFG generates a real elementary reflector H of order n, such that H * ( alpha ) = ( beta ), H' * H = I. ( x ) ( 0 ) where alpha and beta are scalars, and x is an (n-1)-element real vector. H is represented in the form H = I - tau * ( 1 ) * ( 1 v' ) , ( v ) where tau is a real scalar and v is a real (n-1)-element vector. If the elements of x are all zero, then tau = 0 and H is taken to be the unit matrix. Otherwise 1 <= tau <= 2. Arguments ========= N (input) INTEGER The order of the elementary reflector. ALPHA (input/output) DOUBLE PRECISION On entry, the value alpha. On exit, it is overwritten with the value beta. X (input/output) DOUBLE PRECISION array, dimension (1+(N-2)*abs(INCX)) On entry, the vector x. On exit, it is overwritten with the vector v. INCX (input) INTEGER The increment between elements of X. INCX > 0. TAU (output) DOUBLE PRECISION The value tau. ===================================================================== */ /* Parameter adjustments */ --x; /* Function Body */ if (*n <= 1) { *tau = 0.; return 0; } i__1 = *n - 1; xnorm = dnrm2_(&i__1, &x[1], incx); if (xnorm == 0.) { /* H = I */ *tau = 0.; } else { /* general case */ d__1 = dlapy2_(alpha, &xnorm); beta = -d_sign(&d__1, alpha); safmin = SAFEMINIMUM / EPSILON; if (abs(beta) < safmin) { /* XNORM, BETA may be inaccurate; scale X and recompute them */ rsafmn = 1. / safmin; knt = 0; L10: ++knt; i__1 = *n - 1; dscal_(&i__1, &rsafmn, &x[1], incx); beta *= rsafmn; *alpha *= rsafmn; if (abs(beta) < safmin) { goto L10; } /* New BETA is at most 1, at least SAFMIN */ i__1 = *n - 1; xnorm = dnrm2_(&i__1, &x[1], incx); d__1 = dlapy2_(alpha, &xnorm); beta = -d_sign(&d__1, alpha); *tau = (beta - *alpha) / beta; i__1 = *n - 1; d__1 = 1. / (*alpha - beta); dscal_(&i__1, &d__1, &x[1], incx); /* If ALPHA is subnormal, it may lose relative accuracy */ *alpha = beta; i__1 = knt; for (j = 1; j <= i__1; ++j) { *alpha *= safmin; /* L20: */ } } else { *tau = (beta - *alpha) / beta; i__1 = *n - 1; d__1 = 1. / (*alpha - beta); dscal_(&i__1, &d__1, &x[1], incx); *alpha = beta; } } return 0; /* End of DLARFG */ } /* dlarfg_ */ /* Subroutine */ int dlarft_(char *direct, char *storev, integer *n, integer * k, doublereal *v, integer *ldv, doublereal *tau, doublereal *t, integer *ldt) { /* System generated locals */ integer t_dim1, t_offset, v_dim1, v_offset, i__1, i__2, i__3; doublereal d__1; /* Local variables */ static integer i__, j; static doublereal vii; extern logical lsame_(char *, char *); extern /* Subroutine */ int dgemv_(char *, integer *, integer *, doublereal *, doublereal *, integer *, doublereal *, integer *, doublereal *, doublereal *, integer *), dtrmv_(char *, char *, char *, integer *, doublereal *, integer *, doublereal *, integer *); /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University February 29, 1992 Purpose ======= DLARFT forms the triangular factor T of a real block reflector H of order n, which is defined as a product of k elementary reflectors. If DIRECT = 'F', H = H(1) H(2) . . . H(k) and T is upper triangular; If DIRECT = 'B', H = H(k) . . . H(2) H(1) and T is lower triangular. If STOREV = 'C', the vector which defines the elementary reflector H(i) is stored in the i-th column of the array V, and H = I - V * T * V' If STOREV = 'R', the vector which defines the elementary reflector H(i) is stored in the i-th row of the array V, and H = I - V' * T * V Arguments ========= DIRECT (input) CHARACTER*1 Specifies the order in which the elementary reflectors are multiplied to form the block reflector: = 'F': H = H(1) H(2) . . . H(k) (Forward) = 'B': H = H(k) . . . H(2) H(1) (Backward) STOREV (input) CHARACTER*1 Specifies how the vectors which define the elementary reflectors are stored (see also Further Details): = 'C': columnwise = 'R': rowwise N (input) INTEGER The order of the block reflector H. N >= 0. K (input) INTEGER The order of the triangular factor T (= the number of elementary reflectors). K >= 1. V (input/output) DOUBLE PRECISION array, dimension (LDV,K) if STOREV = 'C' (LDV,N) if STOREV = 'R' The matrix V. See further details. LDV (input) INTEGER The leading dimension of the array V. If STOREV = 'C', LDV >= max(1,N); if STOREV = 'R', LDV >= K. TAU (input) DOUBLE PRECISION array, dimension (K) TAU(i) must contain the scalar factor of the elementary reflector H(i). T (output) DOUBLE PRECISION array, dimension (LDT,K) The k by k triangular factor T of the block reflector. If DIRECT = 'F', T is upper triangular; if DIRECT = 'B', T is lower triangular. The rest of the array is not used. LDT (input) INTEGER The leading dimension of the array T. LDT >= K. Further Details =============== The shape of the matrix V and the storage of the vectors which define the H(i) is best illustrated by the following example with n = 5 and k = 3. The elements equal to 1 are not stored; the corresponding array elements are modified but restored on exit. The rest of the array is not used. DIRECT = 'F' and STOREV = 'C': DIRECT = 'F' and STOREV = 'R': V = ( 1 ) V = ( 1 v1 v1 v1 v1 ) ( v1 1 ) ( 1 v2 v2 v2 ) ( v1 v2 1 ) ( 1 v3 v3 ) ( v1 v2 v3 ) ( v1 v2 v3 ) DIRECT = 'B' and STOREV = 'C': DIRECT = 'B' and STOREV = 'R': V = ( v1 v2 v3 ) V = ( v1 v1 1 ) ( v1 v2 v3 ) ( v2 v2 v2 1 ) ( 1 v2 v3 ) ( v3 v3 v3 v3 1 ) ( 1 v3 ) ( 1 ) ===================================================================== Quick return if possible */ /* Parameter adjustments */ v_dim1 = *ldv; v_offset = 1 + v_dim1; v -= v_offset; --tau; t_dim1 = *ldt; t_offset = 1 + t_dim1; t -= t_offset; /* Function Body */ if (*n == 0) { return 0; } if (lsame_(direct, "F")) { i__1 = *k; for (i__ = 1; i__ <= i__1; ++i__) { if (tau[i__] == 0.) { /* H(i) = I */ i__2 = i__; for (j = 1; j <= i__2; ++j) { t[j + i__ * t_dim1] = 0.; /* L10: */ } } else { /* general case */ vii = v[i__ + i__ * v_dim1]; v[i__ + i__ * v_dim1] = 1.; if (lsame_(storev, "C")) { /* T(1:i-1,i) := - tau(i) * V(i:n,1:i-1)' * V(i:n,i) */ i__2 = *n - i__ + 1; i__3 = i__ - 1; d__1 = -tau[i__]; dgemv_("Transpose", &i__2, &i__3, &d__1, &v[i__ + v_dim1], ldv, &v[i__ + i__ * v_dim1], &c__1, &c_b2879, &t[ i__ * t_dim1 + 1], &c__1); } else { /* T(1:i-1,i) := - tau(i) * V(1:i-1,i:n) * V(i,i:n)' */ i__2 = i__ - 1; i__3 = *n - i__ + 1; d__1 = -tau[i__]; dgemv_("No transpose", &i__2, &i__3, &d__1, &v[i__ * v_dim1 + 1], ldv, &v[i__ + i__ * v_dim1], ldv, & c_b2879, &t[i__ * t_dim1 + 1], &c__1); } v[i__ + i__ * v_dim1] = vii; /* T(1:i-1,i) := T(1:i-1,1:i-1) * T(1:i-1,i) */ i__2 = i__ - 1; dtrmv_("Upper", "No transpose", "Non-unit", &i__2, &t[ t_offset], ldt, &t[i__ * t_dim1 + 1], &c__1); t[i__ + i__ * t_dim1] = tau[i__]; } /* L20: */ } } else { for (i__ = *k; i__ >= 1; --i__) { if (tau[i__] == 0.) { /* H(i) = I */ i__1 = *k; for (j = i__; j <= i__1; ++j) { t[j + i__ * t_dim1] = 0.; /* L30: */ } } else { /* general case */ if (i__ < *k) { if (lsame_(storev, "C")) { vii = v[*n - *k + i__ + i__ * v_dim1]; v[*n - *k + i__ + i__ * v_dim1] = 1.; /* T(i+1:k,i) := - tau(i) * V(1:n-k+i,i+1:k)' * V(1:n-k+i,i) */ i__1 = *n - *k + i__; i__2 = *k - i__; d__1 = -tau[i__]; dgemv_("Transpose", &i__1, &i__2, &d__1, &v[(i__ + 1) * v_dim1 + 1], ldv, &v[i__ * v_dim1 + 1], & c__1, &c_b2879, &t[i__ + 1 + i__ * t_dim1], & c__1); v[*n - *k + i__ + i__ * v_dim1] = vii; } else { vii = v[i__ + (*n - *k + i__) * v_dim1]; v[i__ + (*n - *k + i__) * v_dim1] = 1.; /* T(i+1:k,i) := - tau(i) * V(i+1:k,1:n-k+i) * V(i,1:n-k+i)' */ i__1 = *k - i__; i__2 = *n - *k + i__; d__1 = -tau[i__]; dgemv_("No transpose", &i__1, &i__2, &d__1, &v[i__ + 1 + v_dim1], ldv, &v[i__ + v_dim1], ldv, & c_b2879, &t[i__ + 1 + i__ * t_dim1], &c__1); v[i__ + (*n - *k + i__) * v_dim1] = vii; } /* T(i+1:k,i) := T(i+1:k,i+1:k) * T(i+1:k,i) */ i__1 = *k - i__; dtrmv_("Lower", "No transpose", "Non-unit", &i__1, &t[i__ + 1 + (i__ + 1) * t_dim1], ldt, &t[i__ + 1 + i__ * t_dim1], &c__1) ; } t[i__ + i__ * t_dim1] = tau[i__]; } /* L40: */ } } return 0; /* End of DLARFT */ } /* dlarft_ */ /* Subroutine */ int dlarfx_(char *side, integer *m, integer *n, doublereal * v, doublereal *tau, doublereal *c__, integer *ldc, doublereal *work) { /* System generated locals */ integer c_dim1, c_offset, i__1; doublereal d__1; /* Local variables */ static integer j; static doublereal t1, t2, t3, t4, t5, t6, t7, t8, t9, v1, v2, v3, v4, v5, v6, v7, v8, v9, t10, v10, sum; extern /* Subroutine */ int dger_(integer *, integer *, doublereal *, doublereal *, integer *, doublereal *, integer *, doublereal *, integer *); extern logical lsame_(char *, char *); extern /* Subroutine */ int dgemv_(char *, integer *, integer *, doublereal *, doublereal *, integer *, doublereal *, integer *, doublereal *, doublereal *, integer *); /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University February 29, 1992 Purpose ======= DLARFX applies a real elementary reflector H to a real m by n matrix C, from either the left or the right. H is represented in the form H = I - tau * v * v' where tau is a real scalar and v is a real vector. If tau = 0, then H is taken to be the unit matrix This version uses inline code if H has order < 11. Arguments ========= SIDE (input) CHARACTER*1 = 'L': form H * C = 'R': form C * H M (input) INTEGER The number of rows of the matrix C. N (input) INTEGER The number of columns of the matrix C. V (input) DOUBLE PRECISION array, dimension (M) if SIDE = 'L' or (N) if SIDE = 'R' The vector v in the representation of H. TAU (input) DOUBLE PRECISION The value tau in the representation of H. C (input/output) DOUBLE PRECISION array, dimension (LDC,N) On entry, the m by n matrix C. On exit, C is overwritten by the matrix H * C if SIDE = 'L', or C * H if SIDE = 'R'. LDC (input) INTEGER The leading dimension of the array C. LDA >= (1,M). WORK (workspace) DOUBLE PRECISION array, dimension (N) if SIDE = 'L' or (M) if SIDE = 'R' WORK is not referenced if H has order < 11. ===================================================================== */ /* Parameter adjustments */ --v; c_dim1 = *ldc; c_offset = 1 + c_dim1; c__ -= c_offset; --work; /* Function Body */ if (*tau == 0.) { return 0; } if (lsame_(side, "L")) { /* Form H * C, where H has order m. */ switch (*m) { case 1: goto L10; case 2: goto L30; case 3: goto L50; case 4: goto L70; case 5: goto L90; case 6: goto L110; case 7: goto L130; case 8: goto L150; case 9: goto L170; case 10: goto L190; } /* Code for general M w := C'*v */ dgemv_("Transpose", m, n, &c_b2865, &c__[c_offset], ldc, &v[1], &c__1, &c_b2879, &work[1], &c__1); /* C := C - tau * v * w' */ d__1 = -(*tau); dger_(m, n, &d__1, &v[1], &c__1, &work[1], &c__1, &c__[c_offset], ldc) ; goto L410; L10: /* Special code for 1 x 1 Householder */ t1 = 1. - *tau * v[1] * v[1]; i__1 = *n; for (j = 1; j <= i__1; ++j) { c__[j * c_dim1 + 1] = t1 * c__[j * c_dim1 + 1]; /* L20: */ } goto L410; L30: /* Special code for 2 x 2 Householder */ v1 = v[1]; t1 = *tau * v1; v2 = v[2]; t2 = *tau * v2; i__1 = *n; for (j = 1; j <= i__1; ++j) { sum = v1 * c__[j * c_dim1 + 1] + v2 * c__[j * c_dim1 + 2]; c__[j * c_dim1 + 1] -= sum * t1; c__[j * c_dim1 + 2] -= sum * t2; /* L40: */ } goto L410; L50: /* Special code for 3 x 3 Householder */ v1 = v[1]; t1 = *tau * v1; v2 = v[2]; t2 = *tau * v2; v3 = v[3]; t3 = *tau * v3; i__1 = *n; for (j = 1; j <= i__1; ++j) { sum = v1 * c__[j * c_dim1 + 1] + v2 * c__[j * c_dim1 + 2] + v3 * c__[j * c_dim1 + 3]; c__[j * c_dim1 + 1] -= sum * t1; c__[j * c_dim1 + 2] -= sum * t2; c__[j * c_dim1 + 3] -= sum * t3; /* L60: */ } goto L410; L70: /* Special code for 4 x 4 Householder */ v1 = v[1]; t1 = *tau * v1; v2 = v[2]; t2 = *tau * v2; v3 = v[3]; t3 = *tau * v3; v4 = v[4]; t4 = *tau * v4; i__1 = *n; for (j = 1; j <= i__1; ++j) { sum = v1 * c__[j * c_dim1 + 1] + v2 * c__[j * c_dim1 + 2] + v3 * c__[j * c_dim1 + 3] + v4 * c__[j * c_dim1 + 4]; c__[j * c_dim1 + 1] -= sum * t1; c__[j * c_dim1 + 2] -= sum * t2; c__[j * c_dim1 + 3] -= sum * t3; c__[j * c_dim1 + 4] -= sum * t4; /* L80: */ } goto L410; L90: /* Special code for 5 x 5 Householder */ v1 = v[1]; t1 = *tau * v1; v2 = v[2]; t2 = *tau * v2; v3 = v[3]; t3 = *tau * v3; v4 = v[4]; t4 = *tau * v4; v5 = v[5]; t5 = *tau * v5; i__1 = *n; for (j = 1; j <= i__1; ++j) { sum = v1 * c__[j * c_dim1 + 1] + v2 * c__[j * c_dim1 + 2] + v3 * c__[j * c_dim1 + 3] + v4 * c__[j * c_dim1 + 4] + v5 * c__[ j * c_dim1 + 5]; c__[j * c_dim1 + 1] -= sum * t1; c__[j * c_dim1 + 2] -= sum * t2; c__[j * c_dim1 + 3] -= sum * t3; c__[j * c_dim1 + 4] -= sum * t4; c__[j * c_dim1 + 5] -= sum * t5; /* L100: */ } goto L410; L110: /* Special code for 6 x 6 Householder */ v1 = v[1]; t1 = *tau * v1; v2 = v[2]; t2 = *tau * v2; v3 = v[3]; t3 = *tau * v3; v4 = v[4]; t4 = *tau * v4; v5 = v[5]; t5 = *tau * v5; v6 = v[6]; t6 = *tau * v6; i__1 = *n; for (j = 1; j <= i__1; ++j) { sum = v1 * c__[j * c_dim1 + 1] + v2 * c__[j * c_dim1 + 2] + v3 * c__[j * c_dim1 + 3] + v4 * c__[j * c_dim1 + 4] + v5 * c__[ j * c_dim1 + 5] + v6 * c__[j * c_dim1 + 6]; c__[j * c_dim1 + 1] -= sum * t1; c__[j * c_dim1 + 2] -= sum * t2; c__[j * c_dim1 + 3] -= sum * t3; c__[j * c_dim1 + 4] -= sum * t4; c__[j * c_dim1 + 5] -= sum * t5; c__[j * c_dim1 + 6] -= sum * t6; /* L120: */ } goto L410; L130: /* Special code for 7 x 7 Householder */ v1 = v[1]; t1 = *tau * v1; v2 = v[2]; t2 = *tau * v2; v3 = v[3]; t3 = *tau * v3; v4 = v[4]; t4 = *tau * v4; v5 = v[5]; t5 = *tau * v5; v6 = v[6]; t6 = *tau * v6; v7 = v[7]; t7 = *tau * v7; i__1 = *n; for (j = 1; j <= i__1; ++j) { sum = v1 * c__[j * c_dim1 + 1] + v2 * c__[j * c_dim1 + 2] + v3 * c__[j * c_dim1 + 3] + v4 * c__[j * c_dim1 + 4] + v5 * c__[ j * c_dim1 + 5] + v6 * c__[j * c_dim1 + 6] + v7 * c__[j * c_dim1 + 7]; c__[j * c_dim1 + 1] -= sum * t1; c__[j * c_dim1 + 2] -= sum * t2; c__[j * c_dim1 + 3] -= sum * t3; c__[j * c_dim1 + 4] -= sum * t4; c__[j * c_dim1 + 5] -= sum * t5; c__[j * c_dim1 + 6] -= sum * t6; c__[j * c_dim1 + 7] -= sum * t7; /* L140: */ } goto L410; L150: /* Special code for 8 x 8 Householder */ v1 = v[1]; t1 = *tau * v1; v2 = v[2]; t2 = *tau * v2; v3 = v[3]; t3 = *tau * v3; v4 = v[4]; t4 = *tau * v4; v5 = v[5]; t5 = *tau * v5; v6 = v[6]; t6 = *tau * v6; v7 = v[7]; t7 = *tau * v7; v8 = v[8]; t8 = *tau * v8; i__1 = *n; for (j = 1; j <= i__1; ++j) { sum = v1 * c__[j * c_dim1 + 1] + v2 * c__[j * c_dim1 + 2] + v3 * c__[j * c_dim1 + 3] + v4 * c__[j * c_dim1 + 4] + v5 * c__[ j * c_dim1 + 5] + v6 * c__[j * c_dim1 + 6] + v7 * c__[j * c_dim1 + 7] + v8 * c__[j * c_dim1 + 8]; c__[j * c_dim1 + 1] -= sum * t1; c__[j * c_dim1 + 2] -= sum * t2; c__[j * c_dim1 + 3] -= sum * t3; c__[j * c_dim1 + 4] -= sum * t4; c__[j * c_dim1 + 5] -= sum * t5; c__[j * c_dim1 + 6] -= sum * t6; c__[j * c_dim1 + 7] -= sum * t7; c__[j * c_dim1 + 8] -= sum * t8; /* L160: */ } goto L410; L170: /* Special code for 9 x 9 Householder */ v1 = v[1]; t1 = *tau * v1; v2 = v[2]; t2 = *tau * v2; v3 = v[3]; t3 = *tau * v3; v4 = v[4]; t4 = *tau * v4; v5 = v[5]; t5 = *tau * v5; v6 = v[6]; t6 = *tau * v6; v7 = v[7]; t7 = *tau * v7; v8 = v[8]; t8 = *tau * v8; v9 = v[9]; t9 = *tau * v9; i__1 = *n; for (j = 1; j <= i__1; ++j) { sum = v1 * c__[j * c_dim1 + 1] + v2 * c__[j * c_dim1 + 2] + v3 * c__[j * c_dim1 + 3] + v4 * c__[j * c_dim1 + 4] + v5 * c__[ j * c_dim1 + 5] + v6 * c__[j * c_dim1 + 6] + v7 * c__[j * c_dim1 + 7] + v8 * c__[j * c_dim1 + 8] + v9 * c__[j * c_dim1 + 9]; c__[j * c_dim1 + 1] -= sum * t1; c__[j * c_dim1 + 2] -= sum * t2; c__[j * c_dim1 + 3] -= sum * t3; c__[j * c_dim1 + 4] -= sum * t4; c__[j * c_dim1 + 5] -= sum * t5; c__[j * c_dim1 + 6] -= sum * t6; c__[j * c_dim1 + 7] -= sum * t7; c__[j * c_dim1 + 8] -= sum * t8; c__[j * c_dim1 + 9] -= sum * t9; /* L180: */ } goto L410; L190: /* Special code for 10 x 10 Householder */ v1 = v[1]; t1 = *tau * v1; v2 = v[2]; t2 = *tau * v2; v3 = v[3]; t3 = *tau * v3; v4 = v[4]; t4 = *tau * v4; v5 = v[5]; t5 = *tau * v5; v6 = v[6]; t6 = *tau * v6; v7 = v[7]; t7 = *tau * v7; v8 = v[8]; t8 = *tau * v8; v9 = v[9]; t9 = *tau * v9; v10 = v[10]; t10 = *tau * v10; i__1 = *n; for (j = 1; j <= i__1; ++j) { sum = v1 * c__[j * c_dim1 + 1] + v2 * c__[j * c_dim1 + 2] + v3 * c__[j * c_dim1 + 3] + v4 * c__[j * c_dim1 + 4] + v5 * c__[ j * c_dim1 + 5] + v6 * c__[j * c_dim1 + 6] + v7 * c__[j * c_dim1 + 7] + v8 * c__[j * c_dim1 + 8] + v9 * c__[j * c_dim1 + 9] + v10 * c__[j * c_dim1 + 10]; c__[j * c_dim1 + 1] -= sum * t1; c__[j * c_dim1 + 2] -= sum * t2; c__[j * c_dim1 + 3] -= sum * t3; c__[j * c_dim1 + 4] -= sum * t4; c__[j * c_dim1 + 5] -= sum * t5; c__[j * c_dim1 + 6] -= sum * t6; c__[j * c_dim1 + 7] -= sum * t7; c__[j * c_dim1 + 8] -= sum * t8; c__[j * c_dim1 + 9] -= sum * t9; c__[j * c_dim1 + 10] -= sum * t10; /* L200: */ } goto L410; } else { /* Form C * H, where H has order n. */ switch (*n) { case 1: goto L210; case 2: goto L230; case 3: goto L250; case 4: goto L270; case 5: goto L290; case 6: goto L310; case 7: goto L330; case 8: goto L350; case 9: goto L370; case 10: goto L390; } /* Code for general N w := C * v */ dgemv_("No transpose", m, n, &c_b2865, &c__[c_offset], ldc, &v[1], & c__1, &c_b2879, &work[1], &c__1); /* C := C - tau * w * v' */ d__1 = -(*tau); dger_(m, n, &d__1, &work[1], &c__1, &v[1], &c__1, &c__[c_offset], ldc) ; goto L410; L210: /* Special code for 1 x 1 Householder */ t1 = 1. - *tau * v[1] * v[1]; i__1 = *m; for (j = 1; j <= i__1; ++j) { c__[j + c_dim1] = t1 * c__[j + c_dim1]; /* L220: */ } goto L410; L230: /* Special code for 2 x 2 Householder */ v1 = v[1]; t1 = *tau * v1; v2 = v[2]; t2 = *tau * v2; i__1 = *m; for (j = 1; j <= i__1; ++j) { sum = v1 * c__[j + c_dim1] + v2 * c__[j + ((c_dim1) << (1))]; c__[j + c_dim1] -= sum * t1; c__[j + ((c_dim1) << (1))] -= sum * t2; /* L240: */ } goto L410; L250: /* Special code for 3 x 3 Householder */ v1 = v[1]; t1 = *tau * v1; v2 = v[2]; t2 = *tau * v2; v3 = v[3]; t3 = *tau * v3; i__1 = *m; for (j = 1; j <= i__1; ++j) { sum = v1 * c__[j + c_dim1] + v2 * c__[j + ((c_dim1) << (1))] + v3 * c__[j + c_dim1 * 3]; c__[j + c_dim1] -= sum * t1; c__[j + ((c_dim1) << (1))] -= sum * t2; c__[j + c_dim1 * 3] -= sum * t3; /* L260: */ } goto L410; L270: /* Special code for 4 x 4 Householder */ v1 = v[1]; t1 = *tau * v1; v2 = v[2]; t2 = *tau * v2; v3 = v[3]; t3 = *tau * v3; v4 = v[4]; t4 = *tau * v4; i__1 = *m; for (j = 1; j <= i__1; ++j) { sum = v1 * c__[j + c_dim1] + v2 * c__[j + ((c_dim1) << (1))] + v3 * c__[j + c_dim1 * 3] + v4 * c__[j + ((c_dim1) << (2))]; c__[j + c_dim1] -= sum * t1; c__[j + ((c_dim1) << (1))] -= sum * t2; c__[j + c_dim1 * 3] -= sum * t3; c__[j + ((c_dim1) << (2))] -= sum * t4; /* L280: */ } goto L410; L290: /* Special code for 5 x 5 Householder */ v1 = v[1]; t1 = *tau * v1; v2 = v[2]; t2 = *tau * v2; v3 = v[3]; t3 = *tau * v3; v4 = v[4]; t4 = *tau * v4; v5 = v[5]; t5 = *tau * v5; i__1 = *m; for (j = 1; j <= i__1; ++j) { sum = v1 * c__[j + c_dim1] + v2 * c__[j + ((c_dim1) << (1))] + v3 * c__[j + c_dim1 * 3] + v4 * c__[j + ((c_dim1) << (2))] + v5 * c__[j + c_dim1 * 5]; c__[j + c_dim1] -= sum * t1; c__[j + ((c_dim1) << (1))] -= sum * t2; c__[j + c_dim1 * 3] -= sum * t3; c__[j + ((c_dim1) << (2))] -= sum * t4; c__[j + c_dim1 * 5] -= sum * t5; /* L300: */ } goto L410; L310: /* Special code for 6 x 6 Householder */ v1 = v[1]; t1 = *tau * v1; v2 = v[2]; t2 = *tau * v2; v3 = v[3]; t3 = *tau * v3; v4 = v[4]; t4 = *tau * v4; v5 = v[5]; t5 = *tau * v5; v6 = v[6]; t6 = *tau * v6; i__1 = *m; for (j = 1; j <= i__1; ++j) { sum = v1 * c__[j + c_dim1] + v2 * c__[j + ((c_dim1) << (1))] + v3 * c__[j + c_dim1 * 3] + v4 * c__[j + ((c_dim1) << (2))] + v5 * c__[j + c_dim1 * 5] + v6 * c__[j + c_dim1 * 6]; c__[j + c_dim1] -= sum * t1; c__[j + ((c_dim1) << (1))] -= sum * t2; c__[j + c_dim1 * 3] -= sum * t3; c__[j + ((c_dim1) << (2))] -= sum * t4; c__[j + c_dim1 * 5] -= sum * t5; c__[j + c_dim1 * 6] -= sum * t6; /* L320: */ } goto L410; L330: /* Special code for 7 x 7 Householder */ v1 = v[1]; t1 = *tau * v1; v2 = v[2]; t2 = *tau * v2; v3 = v[3]; t3 = *tau * v3; v4 = v[4]; t4 = *tau * v4; v5 = v[5]; t5 = *tau * v5; v6 = v[6]; t6 = *tau * v6; v7 = v[7]; t7 = *tau * v7; i__1 = *m; for (j = 1; j <= i__1; ++j) { sum = v1 * c__[j + c_dim1] + v2 * c__[j + ((c_dim1) << (1))] + v3 * c__[j + c_dim1 * 3] + v4 * c__[j + ((c_dim1) << (2))] + v5 * c__[j + c_dim1 * 5] + v6 * c__[j + c_dim1 * 6] + v7 * c__[j + c_dim1 * 7]; c__[j + c_dim1] -= sum * t1; c__[j + ((c_dim1) << (1))] -= sum * t2; c__[j + c_dim1 * 3] -= sum * t3; c__[j + ((c_dim1) << (2))] -= sum * t4; c__[j + c_dim1 * 5] -= sum * t5; c__[j + c_dim1 * 6] -= sum * t6; c__[j + c_dim1 * 7] -= sum * t7; /* L340: */ } goto L410; L350: /* Special code for 8 x 8 Householder */ v1 = v[1]; t1 = *tau * v1; v2 = v[2]; t2 = *tau * v2; v3 = v[3]; t3 = *tau * v3; v4 = v[4]; t4 = *tau * v4; v5 = v[5]; t5 = *tau * v5; v6 = v[6]; t6 = *tau * v6; v7 = v[7]; t7 = *tau * v7; v8 = v[8]; t8 = *tau * v8; i__1 = *m; for (j = 1; j <= i__1; ++j) { sum = v1 * c__[j + c_dim1] + v2 * c__[j + ((c_dim1) << (1))] + v3 * c__[j + c_dim1 * 3] + v4 * c__[j + ((c_dim1) << (2))] + v5 * c__[j + c_dim1 * 5] + v6 * c__[j + c_dim1 * 6] + v7 * c__[j + c_dim1 * 7] + v8 * c__[j + ((c_dim1) << (3))]; c__[j + c_dim1] -= sum * t1; c__[j + ((c_dim1) << (1))] -= sum * t2; c__[j + c_dim1 * 3] -= sum * t3; c__[j + ((c_dim1) << (2))] -= sum * t4; c__[j + c_dim1 * 5] -= sum * t5; c__[j + c_dim1 * 6] -= sum * t6; c__[j + c_dim1 * 7] -= sum * t7; c__[j + ((c_dim1) << (3))] -= sum * t8; /* L360: */ } goto L410; L370: /* Special code for 9 x 9 Householder */ v1 = v[1]; t1 = *tau * v1; v2 = v[2]; t2 = *tau * v2; v3 = v[3]; t3 = *tau * v3; v4 = v[4]; t4 = *tau * v4; v5 = v[5]; t5 = *tau * v5; v6 = v[6]; t6 = *tau * v6; v7 = v[7]; t7 = *tau * v7; v8 = v[8]; t8 = *tau * v8; v9 = v[9]; t9 = *tau * v9; i__1 = *m; for (j = 1; j <= i__1; ++j) { sum = v1 * c__[j + c_dim1] + v2 * c__[j + ((c_dim1) << (1))] + v3 * c__[j + c_dim1 * 3] + v4 * c__[j + ((c_dim1) << (2))] + v5 * c__[j + c_dim1 * 5] + v6 * c__[j + c_dim1 * 6] + v7 * c__[j + c_dim1 * 7] + v8 * c__[j + ((c_dim1) << (3))] + v9 * c__[j + c_dim1 * 9]; c__[j + c_dim1] -= sum * t1; c__[j + ((c_dim1) << (1))] -= sum * t2; c__[j + c_dim1 * 3] -= sum * t3; c__[j + ((c_dim1) << (2))] -= sum * t4; c__[j + c_dim1 * 5] -= sum * t5; c__[j + c_dim1 * 6] -= sum * t6; c__[j + c_dim1 * 7] -= sum * t7; c__[j + ((c_dim1) << (3))] -= sum * t8; c__[j + c_dim1 * 9] -= sum * t9; /* L380: */ } goto L410; L390: /* Special code for 10 x 10 Householder */ v1 = v[1]; t1 = *tau * v1; v2 = v[2]; t2 = *tau * v2; v3 = v[3]; t3 = *tau * v3; v4 = v[4]; t4 = *tau * v4; v5 = v[5]; t5 = *tau * v5; v6 = v[6]; t6 = *tau * v6; v7 = v[7]; t7 = *tau * v7; v8 = v[8]; t8 = *tau * v8; v9 = v[9]; t9 = *tau * v9; v10 = v[10]; t10 = *tau * v10; i__1 = *m; for (j = 1; j <= i__1; ++j) { sum = v1 * c__[j + c_dim1] + v2 * c__[j + ((c_dim1) << (1))] + v3 * c__[j + c_dim1 * 3] + v4 * c__[j + ((c_dim1) << (2))] + v5 * c__[j + c_dim1 * 5] + v6 * c__[j + c_dim1 * 6] + v7 * c__[j + c_dim1 * 7] + v8 * c__[j + ((c_dim1) << (3))] + v9 * c__[j + c_dim1 * 9] + v10 * c__[j + c_dim1 * 10]; c__[j + c_dim1] -= sum * t1; c__[j + ((c_dim1) << (1))] -= sum * t2; c__[j + c_dim1 * 3] -= sum * t3; c__[j + ((c_dim1) << (2))] -= sum * t4; c__[j + c_dim1 * 5] -= sum * t5; c__[j + c_dim1 * 6] -= sum * t6; c__[j + c_dim1 * 7] -= sum * t7; c__[j + ((c_dim1) << (3))] -= sum * t8; c__[j + c_dim1 * 9] -= sum * t9; c__[j + c_dim1 * 10] -= sum * t10; /* L400: */ } goto L410; } L410: return 0; /* End of DLARFX */ } /* dlarfx_ */ /* Subroutine */ int dlartg_(doublereal *f, doublereal *g, doublereal *cs, doublereal *sn, doublereal *r__) { /* Initialized data */ static logical first = TRUE_; /* System generated locals */ integer i__1; doublereal d__1, d__2; /* Builtin functions */ double log(doublereal), pow_di(doublereal *, integer *), sqrt(doublereal); /* Local variables */ static integer i__; static doublereal f1, g1, eps, scale; static integer count; static doublereal safmn2, safmx2; static doublereal safmin; /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University September 30, 1994 Purpose ======= DLARTG generate a plane rotation so that [ CS SN ] . [ F ] = [ R ] where CS**2 + SN**2 = 1. [ -SN CS ] [ G ] [ 0 ] This is a slower, more accurate version of the BLAS1 routine DROTG, with the following other differences: F and G are unchanged on return. If G=0, then CS=1 and SN=0. If F=0 and (G .ne. 0), then CS=0 and SN=1 without doing any floating point operations (saves work in DBDSQR when there are zeros on the diagonal). If F exceeds G in magnitude, CS will be positive. Arguments ========= F (input) DOUBLE PRECISION The first component of vector to be rotated. G (input) DOUBLE PRECISION The second component of vector to be rotated. CS (output) DOUBLE PRECISION The cosine of the rotation. SN (output) DOUBLE PRECISION The sine of the rotation. R (output) DOUBLE PRECISION The nonzero component of the rotated vector. ===================================================================== */ if (first) { first = FALSE_; safmin = SAFEMINIMUM; eps = EPSILON; d__1 = BASE; i__1 = (integer) (log(safmin / eps) / log(BASE) / 2.); safmn2 = pow_di(&d__1, &i__1); safmx2 = 1. / safmn2; } if (*g == 0.) { *cs = 1.; *sn = 0.; *r__ = *f; } else if (*f == 0.) { *cs = 0.; *sn = 1.; *r__ = *g; } else { f1 = *f; g1 = *g; /* Computing MAX */ d__1 = abs(f1), d__2 = abs(g1); scale = max(d__1,d__2); if (scale >= safmx2) { count = 0; L10: ++count; f1 *= safmn2; g1 *= safmn2; /* Computing MAX */ d__1 = abs(f1), d__2 = abs(g1); scale = max(d__1,d__2); if (scale >= safmx2) { goto L10; } /* Computing 2nd power */ d__1 = f1; /* Computing 2nd power */ d__2 = g1; *r__ = sqrt(d__1 * d__1 + d__2 * d__2); *cs = f1 / *r__; *sn = g1 / *r__; i__1 = count; for (i__ = 1; i__ <= i__1; ++i__) { *r__ *= safmx2; /* L20: */ } } else if (scale <= safmn2) { count = 0; L30: ++count; f1 *= safmx2; g1 *= safmx2; /* Computing MAX */ d__1 = abs(f1), d__2 = abs(g1); scale = max(d__1,d__2); if (scale <= safmn2) { goto L30; } /* Computing 2nd power */ d__1 = f1; /* Computing 2nd power */ d__2 = g1; *r__ = sqrt(d__1 * d__1 + d__2 * d__2); *cs = f1 / *r__; *sn = g1 / *r__; i__1 = count; for (i__ = 1; i__ <= i__1; ++i__) { *r__ *= safmn2; /* L40: */ } } else { /* Computing 2nd power */ d__1 = f1; /* Computing 2nd power */ d__2 = g1; *r__ = sqrt(d__1 * d__1 + d__2 * d__2); *cs = f1 / *r__; *sn = g1 / *r__; } if (abs(*f) > abs(*g) && *cs < 0.) { *cs = -(*cs); *sn = -(*sn); *r__ = -(*r__); } } return 0; /* End of DLARTG */ } /* dlartg_ */ /* Subroutine */ int dlas2_(doublereal *f, doublereal *g, doublereal *h__, doublereal *ssmin, doublereal *ssmax) { /* System generated locals */ doublereal d__1, d__2; /* Builtin functions */ double sqrt(doublereal); /* Local variables */ static doublereal c__, fa, ga, ha, as, at, au, fhmn, fhmx; /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University September 30, 1994 Purpose ======= DLAS2 computes the singular values of the 2-by-2 matrix [ F G ] [ 0 H ]. On return, SSMIN is the smaller singular value and SSMAX is the larger singular value. Arguments ========= F (input) DOUBLE PRECISION The (1,1) element of the 2-by-2 matrix. G (input) DOUBLE PRECISION The (1,2) element of the 2-by-2 matrix. H (input) DOUBLE PRECISION The (2,2) element of the 2-by-2 matrix. SSMIN (output) DOUBLE PRECISION The smaller singular value. SSMAX (output) DOUBLE PRECISION The larger singular value. Further Details =============== Barring over/underflow, all output quantities are correct to within a few units in the last place (ulps), even in the absence of a guard digit in addition/subtraction. In IEEE arithmetic, the code works correctly if one matrix element is infinite. Overflow will not occur unless the largest singular value itself overflows, or is within a few ulps of overflow. (On machines with partial overflow, like the Cray, overflow may occur if the largest singular value is within a factor of 2 of overflow.) Underflow is harmless if underflow is gradual. Otherwise, results may correspond to a matrix modified by perturbations of size near the underflow threshold. ==================================================================== */ fa = abs(*f); ga = abs(*g); ha = abs(*h__); fhmn = min(fa,ha); fhmx = max(fa,ha); if (fhmn == 0.) { *ssmin = 0.; if (fhmx == 0.) { *ssmax = ga; } else { /* Computing 2nd power */ d__1 = min(fhmx,ga) / max(fhmx,ga); *ssmax = max(fhmx,ga) * sqrt(d__1 * d__1 + 1.); } } else { if (ga < fhmx) { as = fhmn / fhmx + 1.; at = (fhmx - fhmn) / fhmx; /* Computing 2nd power */ d__1 = ga / fhmx; au = d__1 * d__1; c__ = 2. / (sqrt(as * as + au) + sqrt(at * at + au)); *ssmin = fhmn * c__; *ssmax = fhmx / c__; } else { au = fhmx / ga; if (au == 0.) { /* Avoid possible harmful underflow if exponent range asymmetric (true SSMIN may not underflow even if AU underflows) */ *ssmin = fhmn * fhmx / ga; *ssmax = ga; } else { as = fhmn / fhmx + 1.; at = (fhmx - fhmn) / fhmx; /* Computing 2nd power */ d__1 = as * au; /* Computing 2nd power */ d__2 = at * au; c__ = 1. / (sqrt(d__1 * d__1 + 1.) + sqrt(d__2 * d__2 + 1.)); *ssmin = fhmn * c__ * au; *ssmin += *ssmin; *ssmax = ga / (c__ + c__); } } } return 0; /* End of DLAS2 */ } /* dlas2_ */ /* Subroutine */ int dlascl_(char *type__, integer *kl, integer *ku, doublereal *cfrom, doublereal *cto, integer *m, integer *n, doublereal *a, integer *lda, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3, i__4, i__5; /* Local variables */ static integer i__, j, k1, k2, k3, k4; static doublereal mul, cto1; static logical done; static doublereal ctoc; extern logical lsame_(char *, char *); static integer itype; static doublereal cfrom1; static doublereal cfromc; extern /* Subroutine */ int xerbla_(char *, integer *); static doublereal bignum, smlnum; /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University February 29, 1992 Purpose ======= DLASCL multiplies the M by N real matrix A by the real scalar CTO/CFROM. This is done without over/underflow as long as the final result CTO*A(I,J)/CFROM does not over/underflow. TYPE specifies that A may be full, upper triangular, lower triangular, upper Hessenberg, or banded. Arguments ========= TYPE (input) CHARACTER*1 TYPE indices the storage type of the input matrix. = 'G': A is a full matrix. = 'L': A is a lower triangular matrix. = 'U': A is an upper triangular matrix. = 'H': A is an upper Hessenberg matrix. = 'B': A is a symmetric band matrix with lower bandwidth KL and upper bandwidth KU and with the only the lower half stored. = 'Q': A is a symmetric band matrix with lower bandwidth KL and upper bandwidth KU and with the only the upper half stored. = 'Z': A is a band matrix with lower bandwidth KL and upper bandwidth KU. KL (input) INTEGER The lower bandwidth of A. Referenced only if TYPE = 'B', 'Q' or 'Z'. KU (input) INTEGER The upper bandwidth of A. Referenced only if TYPE = 'B', 'Q' or 'Z'. CFROM (input) DOUBLE PRECISION CTO (input) DOUBLE PRECISION The matrix A is multiplied by CTO/CFROM. A(I,J) is computed without over/underflow if the final result CTO*A(I,J)/CFROM can be represented without over/underflow. CFROM must be nonzero. M (input) INTEGER The number of rows of the matrix A. M >= 0. N (input) INTEGER The number of columns of the matrix A. N >= 0. A (input/output) DOUBLE PRECISION array, dimension (LDA,M) The matrix to be multiplied by CTO/CFROM. See TYPE for the storage type. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,M). INFO (output) INTEGER 0 - successful exit <0 - if INFO = -i, the i-th argument had an illegal value. ===================================================================== Test the input arguments */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; /* Function Body */ *info = 0; if (lsame_(type__, "G")) { itype = 0; } else if (lsame_(type__, "L")) { itype = 1; } else if (lsame_(type__, "U")) { itype = 2; } else if (lsame_(type__, "H")) { itype = 3; } else if (lsame_(type__, "B")) { itype = 4; } else if (lsame_(type__, "Q")) { itype = 5; } else if (lsame_(type__, "Z")) { itype = 6; } else { itype = -1; } if (itype == -1) { *info = -1; } else if (*cfrom == 0.) { *info = -4; } else if (*m < 0) { *info = -6; } else if (((*n < 0) || (itype == 4 && *n != *m)) || (itype == 5 && *n != *m)) { *info = -7; } else if (itype <= 3 && *lda < max(1,*m)) { *info = -9; } else if (itype >= 4) { /* Computing MAX */ i__1 = *m - 1; if ((*kl < 0) || (*kl > max(i__1,0))) { *info = -2; } else /* if(complicated condition) */ { /* Computing MAX */ i__1 = *n - 1; if (((*ku < 0) || (*ku > max(i__1,0))) || (((itype == 4) || ( itype == 5)) && *kl != *ku)) { *info = -3; } else if (((itype == 4 && *lda < *kl + 1) || (itype == 5 && *lda < *ku + 1)) || (itype == 6 && *lda < ((*kl) << (1)) + *ku + 1)) { *info = -9; } } } if (*info != 0) { i__1 = -(*info); xerbla_("DLASCL", &i__1); return 0; } /* Quick return if possible */ if ((*n == 0) || (*m == 0)) { return 0; } /* Get machine parameters */ smlnum = SAFEMINIMUM; bignum = 1. / smlnum; cfromc = *cfrom; ctoc = *cto; L10: cfrom1 = cfromc * smlnum; cto1 = ctoc / bignum; if (abs(cfrom1) > abs(ctoc) && ctoc != 0.) { mul = smlnum; done = FALSE_; cfromc = cfrom1; } else if (abs(cto1) > abs(cfromc)) { mul = bignum; done = FALSE_; ctoc = cto1; } else { mul = ctoc / cfromc; done = TRUE_; } if (itype == 0) { /* Full matrix */ i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { a[i__ + j * a_dim1] *= mul; /* L20: */ } /* L30: */ } } else if (itype == 1) { /* Lower triangular matrix */ i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = j; i__ <= i__2; ++i__) { a[i__ + j * a_dim1] *= mul; /* L40: */ } /* L50: */ } } else if (itype == 2) { /* Upper triangular matrix */ i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = min(j,*m); for (i__ = 1; i__ <= i__2; ++i__) { a[i__ + j * a_dim1] *= mul; /* L60: */ } /* L70: */ } } else if (itype == 3) { /* Upper Hessenberg matrix */ i__1 = *n; for (j = 1; j <= i__1; ++j) { /* Computing MIN */ i__3 = j + 1; i__2 = min(i__3,*m); for (i__ = 1; i__ <= i__2; ++i__) { a[i__ + j * a_dim1] *= mul; /* L80: */ } /* L90: */ } } else if (itype == 4) { /* Lower half of a symmetric band matrix */ k3 = *kl + 1; k4 = *n + 1; i__1 = *n; for (j = 1; j <= i__1; ++j) { /* Computing MIN */ i__3 = k3, i__4 = k4 - j; i__2 = min(i__3,i__4); for (i__ = 1; i__ <= i__2; ++i__) { a[i__ + j * a_dim1] *= mul; /* L100: */ } /* L110: */ } } else if (itype == 5) { /* Upper half of a symmetric band matrix */ k1 = *ku + 2; k3 = *ku + 1; i__1 = *n; for (j = 1; j <= i__1; ++j) { /* Computing MAX */ i__2 = k1 - j; i__3 = k3; for (i__ = max(i__2,1); i__ <= i__3; ++i__) { a[i__ + j * a_dim1] *= mul; /* L120: */ } /* L130: */ } } else if (itype == 6) { /* Band matrix */ k1 = *kl + *ku + 2; k2 = *kl + 1; k3 = ((*kl) << (1)) + *ku + 1; k4 = *kl + *ku + 1 + *m; i__1 = *n; for (j = 1; j <= i__1; ++j) { /* Computing MAX */ i__3 = k1 - j; /* Computing MIN */ i__4 = k3, i__5 = k4 - j; i__2 = min(i__4,i__5); for (i__ = max(i__3,k2); i__ <= i__2; ++i__) { a[i__ + j * a_dim1] *= mul; /* L140: */ } /* L150: */ } } if (! done) { goto L10; } return 0; /* End of DLASCL */ } /* dlascl_ */ /* Subroutine */ int dlasd0_(integer *n, integer *sqre, doublereal *d__, doublereal *e, doublereal *u, integer *ldu, doublereal *vt, integer * ldvt, integer *smlsiz, integer *iwork, doublereal *work, integer * info) { /* System generated locals */ integer u_dim1, u_offset, vt_dim1, vt_offset, i__1, i__2; /* Builtin functions */ integer pow_ii(integer *, integer *); /* Local variables */ static integer i__, j, m, i1, ic, lf, nd, ll, nl, nr, im1, ncc, nlf, nrf, iwk, lvl, ndb1, nlp1, nrp1; static doublereal beta; static integer idxq, nlvl; static doublereal alpha; static integer inode, ndiml, idxqc, ndimr, itemp, sqrei; extern /* Subroutine */ int dlasd1_(integer *, integer *, integer *, doublereal *, doublereal *, doublereal *, doublereal *, integer *, doublereal *, integer *, integer *, integer *, doublereal *, integer *), dlasdq_(char *, integer *, integer *, integer *, integer *, integer *, doublereal *, doublereal *, doublereal *, integer *, doublereal *, integer *, doublereal *, integer *, doublereal *, integer *), dlasdt_(integer *, integer *, integer *, integer *, integer *, integer *, integer *), xerbla_( char *, integer *); /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= Using a divide and conquer approach, DLASD0 computes the singular value decomposition (SVD) of a real upper bidiagonal N-by-M matrix B with diagonal D and offdiagonal E, where M = N + SQRE. The algorithm computes orthogonal matrices U and VT such that B = U * S * VT. The singular values S are overwritten on D. A related subroutine, DLASDA, computes only the singular values, and optionally, the singular vectors in compact form. Arguments ========= N (input) INTEGER On entry, the row dimension of the upper bidiagonal matrix. This is also the dimension of the main diagonal array D. SQRE (input) INTEGER Specifies the column dimension of the bidiagonal matrix. = 0: The bidiagonal matrix has column dimension M = N; = 1: The bidiagonal matrix has column dimension M = N+1; D (input/output) DOUBLE PRECISION array, dimension (N) On entry D contains the main diagonal of the bidiagonal matrix. On exit D, if INFO = 0, contains its singular values. E (input) DOUBLE PRECISION array, dimension (M-1) Contains the subdiagonal entries of the bidiagonal matrix. On exit, E has been destroyed. U (output) DOUBLE PRECISION array, dimension at least (LDQ, N) On exit, U contains the left singular vectors. LDU (input) INTEGER On entry, leading dimension of U. VT (output) DOUBLE PRECISION array, dimension at least (LDVT, M) On exit, VT' contains the right singular vectors. LDVT (input) INTEGER On entry, leading dimension of VT. SMLSIZ (input) INTEGER On entry, maximum size of the subproblems at the bottom of the computation tree. IWORK INTEGER work array. Dimension must be at least (8 * N) WORK DOUBLE PRECISION work array. Dimension must be at least (3 * M**2 + 2 * M) INFO (output) INTEGER = 0: successful exit. < 0: if INFO = -i, the i-th argument had an illegal value. > 0: if INFO = 1, an singular value did not converge Further Details =============== Based on contributions by Ming Gu and Huan Ren, Computer Science Division, University of California at Berkeley, USA ===================================================================== Test the input parameters. */ /* Parameter adjustments */ --d__; --e; u_dim1 = *ldu; u_offset = 1 + u_dim1; u -= u_offset; vt_dim1 = *ldvt; vt_offset = 1 + vt_dim1; vt -= vt_offset; --iwork; --work; /* Function Body */ *info = 0; if (*n < 0) { *info = -1; } else if ((*sqre < 0) || (*sqre > 1)) { *info = -2; } m = *n + *sqre; if (*ldu < *n) { *info = -6; } else if (*ldvt < m) { *info = -8; } else if (*smlsiz < 3) { *info = -9; } if (*info != 0) { i__1 = -(*info); xerbla_("DLASD0", &i__1); return 0; } /* If the input matrix is too small, call DLASDQ to find the SVD. */ if (*n <= *smlsiz) { dlasdq_("U", sqre, n, &m, n, &c__0, &d__[1], &e[1], &vt[vt_offset], ldvt, &u[u_offset], ldu, &u[u_offset], ldu, &work[1], info); return 0; } /* Set up the computation tree. */ inode = 1; ndiml = inode + *n; ndimr = ndiml + *n; idxq = ndimr + *n; iwk = idxq + *n; dlasdt_(n, &nlvl, &nd, &iwork[inode], &iwork[ndiml], &iwork[ndimr], smlsiz); /* For the nodes on bottom level of the tree, solve their subproblems by DLASDQ. */ ndb1 = (nd + 1) / 2; ncc = 0; i__1 = nd; for (i__ = ndb1; i__ <= i__1; ++i__) { /* IC : center row of each node NL : number of rows of left subproblem NR : number of rows of right subproblem NLF: starting row of the left subproblem NRF: starting row of the right subproblem */ i1 = i__ - 1; ic = iwork[inode + i1]; nl = iwork[ndiml + i1]; nlp1 = nl + 1; nr = iwork[ndimr + i1]; nrp1 = nr + 1; nlf = ic - nl; nrf = ic + 1; sqrei = 1; dlasdq_("U", &sqrei, &nl, &nlp1, &nl, &ncc, &d__[nlf], &e[nlf], &vt[ nlf + nlf * vt_dim1], ldvt, &u[nlf + nlf * u_dim1], ldu, &u[ nlf + nlf * u_dim1], ldu, &work[1], info); if (*info != 0) { return 0; } itemp = idxq + nlf - 2; i__2 = nl; for (j = 1; j <= i__2; ++j) { iwork[itemp + j] = j; /* L10: */ } if (i__ == nd) { sqrei = *sqre; } else { sqrei = 1; } nrp1 = nr + sqrei; dlasdq_("U", &sqrei, &nr, &nrp1, &nr, &ncc, &d__[nrf], &e[nrf], &vt[ nrf + nrf * vt_dim1], ldvt, &u[nrf + nrf * u_dim1], ldu, &u[ nrf + nrf * u_dim1], ldu, &work[1], info); if (*info != 0) { return 0; } itemp = idxq + ic; i__2 = nr; for (j = 1; j <= i__2; ++j) { iwork[itemp + j - 1] = j; /* L20: */ } /* L30: */ } /* Now conquer each subproblem bottom-up. */ for (lvl = nlvl; lvl >= 1; --lvl) { /* Find the first node LF and last node LL on the current level LVL. */ if (lvl == 1) { lf = 1; ll = 1; } else { i__1 = lvl - 1; lf = pow_ii(&c__2, &i__1); ll = ((lf) << (1)) - 1; } i__1 = ll; for (i__ = lf; i__ <= i__1; ++i__) { im1 = i__ - 1; ic = iwork[inode + im1]; nl = iwork[ndiml + im1]; nr = iwork[ndimr + im1]; nlf = ic - nl; if (*sqre == 0 && i__ == ll) { sqrei = *sqre; } else { sqrei = 1; } idxqc = idxq + nlf - 1; alpha = d__[ic]; beta = e[ic]; dlasd1_(&nl, &nr, &sqrei, &d__[nlf], &alpha, &beta, &u[nlf + nlf * u_dim1], ldu, &vt[nlf + nlf * vt_dim1], ldvt, &iwork[ idxqc], &iwork[iwk], &work[1], info); if (*info != 0) { return 0; } /* L40: */ } /* L50: */ } return 0; /* End of DLASD0 */ } /* dlasd0_ */ /* Subroutine */ int dlasd1_(integer *nl, integer *nr, integer *sqre, doublereal *d__, doublereal *alpha, doublereal *beta, doublereal *u, integer *ldu, doublereal *vt, integer *ldvt, integer *idxq, integer * iwork, doublereal *work, integer *info) { /* System generated locals */ integer u_dim1, u_offset, vt_dim1, vt_offset, i__1; doublereal d__1, d__2; /* Local variables */ static integer i__, k, m, n, n1, n2, iq, iz, iu2, ldq, idx, ldu2, ivt2, idxc, idxp, ldvt2; extern /* Subroutine */ int dlasd2_(integer *, integer *, integer *, integer *, doublereal *, doublereal *, doublereal *, doublereal *, doublereal *, integer *, doublereal *, integer *, doublereal *, doublereal *, integer *, doublereal *, integer *, integer *, integer *, integer *, integer *, integer *, integer *), dlasd3_( integer *, integer *, integer *, integer *, doublereal *, doublereal *, integer *, doublereal *, doublereal *, integer *, doublereal *, integer *, doublereal *, integer *, doublereal *, integer *, integer *, integer *, doublereal *, integer *), dlascl_(char *, integer *, integer *, doublereal *, doublereal *, integer *, integer *, doublereal *, integer *, integer *), dlamrg_(integer *, integer *, doublereal *, integer *, integer *, integer *); static integer isigma; extern /* Subroutine */ int xerbla_(char *, integer *); static doublereal orgnrm; static integer coltyp; /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= DLASD1 computes the SVD of an upper bidiagonal N-by-M matrix B, where N = NL + NR + 1 and M = N + SQRE. DLASD1 is called from DLASD0. A related subroutine DLASD7 handles the case in which the singular values (and the singular vectors in factored form) are desired. DLASD1 computes the SVD as follows: ( D1(in) 0 0 0 ) B = U(in) * ( Z1' a Z2' b ) * VT(in) ( 0 0 D2(in) 0 ) = U(out) * ( D(out) 0) * VT(out) where Z' = (Z1' a Z2' b) = u' VT', and u is a vector of dimension M with ALPHA and BETA in the NL+1 and NL+2 th entries and zeros elsewhere; and the entry b is empty if SQRE = 0. The left singular vectors of the original matrix are stored in U, and the transpose of the right singular vectors are stored in VT, and the singular values are in D. The algorithm consists of three stages: The first stage consists of deflating the size of the problem when there are multiple singular values or when there are zeros in the Z vector. For each such occurence the dimension of the secular equation problem is reduced by one. This stage is performed by the routine DLASD2. The second stage consists of calculating the updated singular values. This is done by finding the square roots of the roots of the secular equation via the routine DLASD4 (as called by DLASD3). This routine also calculates the singular vectors of the current problem. The final stage consists of computing the updated singular vectors directly using the updated singular values. The singular vectors for the current problem are multiplied with the singular vectors from the overall problem. Arguments ========= NL (input) INTEGER The row dimension of the upper block. NL >= 1. NR (input) INTEGER The row dimension of the lower block. NR >= 1. SQRE (input) INTEGER = 0: the lower block is an NR-by-NR square matrix. = 1: the lower block is an NR-by-(NR+1) rectangular matrix. The bidiagonal matrix has row dimension N = NL + NR + 1, and column dimension M = N + SQRE. D (input/output) DOUBLE PRECISION array, dimension (N = NL+NR+1). On entry D(1:NL,1:NL) contains the singular values of the upper block; and D(NL+2:N) contains the singular values of the lower block. On exit D(1:N) contains the singular values of the modified matrix. ALPHA (input) DOUBLE PRECISION Contains the diagonal element associated with the added row. BETA (input) DOUBLE PRECISION Contains the off-diagonal element associated with the added row. U (input/output) DOUBLE PRECISION array, dimension(LDU,N) On entry U(1:NL, 1:NL) contains the left singular vectors of the upper block; U(NL+2:N, NL+2:N) contains the left singular vectors of the lower block. On exit U contains the left singular vectors of the bidiagonal matrix. LDU (input) INTEGER The leading dimension of the array U. LDU >= max( 1, N ). VT (input/output) DOUBLE PRECISION array, dimension(LDVT,M) where M = N + SQRE. On entry VT(1:NL+1, 1:NL+1)' contains the right singular vectors of the upper block; VT(NL+2:M, NL+2:M)' contains the right singular vectors of the lower block. On exit VT' contains the right singular vectors of the bidiagonal matrix. LDVT (input) INTEGER The leading dimension of the array VT. LDVT >= max( 1, M ). IDXQ (output) INTEGER array, dimension(N) This contains the permutation which will reintegrate the subproblem just solved back into sorted order, i.e. D( IDXQ( I = 1, N ) ) will be in ascending order. IWORK (workspace) INTEGER array, dimension( 4 * N ) WORK (workspace) DOUBLE PRECISION array, dimension( 3*M**2 + 2*M ) INFO (output) INTEGER = 0: successful exit. < 0: if INFO = -i, the i-th argument had an illegal value. > 0: if INFO = 1, an singular value did not converge Further Details =============== Based on contributions by Ming Gu and Huan Ren, Computer Science Division, University of California at Berkeley, USA ===================================================================== Test the input parameters. */ /* Parameter adjustments */ --d__; u_dim1 = *ldu; u_offset = 1 + u_dim1; u -= u_offset; vt_dim1 = *ldvt; vt_offset = 1 + vt_dim1; vt -= vt_offset; --idxq; --iwork; --work; /* Function Body */ *info = 0; if (*nl < 1) { *info = -1; } else if (*nr < 1) { *info = -2; } else if ((*sqre < 0) || (*sqre > 1)) { *info = -3; } if (*info != 0) { i__1 = -(*info); xerbla_("DLASD1", &i__1); return 0; } n = *nl + *nr + 1; m = n + *sqre; /* The following values are for bookkeeping purposes only. They are integer pointers which indicate the portion of the workspace used by a particular array in DLASD2 and DLASD3. */ ldu2 = n; ldvt2 = m; iz = 1; isigma = iz + m; iu2 = isigma + n; ivt2 = iu2 + ldu2 * n; iq = ivt2 + ldvt2 * m; idx = 1; idxc = idx + n; coltyp = idxc + n; idxp = coltyp + n; /* Scale. Computing MAX */ d__1 = abs(*alpha), d__2 = abs(*beta); orgnrm = max(d__1,d__2); d__[*nl + 1] = 0.; i__1 = n; for (i__ = 1; i__ <= i__1; ++i__) { if ((d__1 = d__[i__], abs(d__1)) > orgnrm) { orgnrm = (d__1 = d__[i__], abs(d__1)); } /* L10: */ } dlascl_("G", &c__0, &c__0, &orgnrm, &c_b2865, &n, &c__1, &d__[1], &n, info); *alpha /= orgnrm; *beta /= orgnrm; /* Deflate singular values. */ dlasd2_(nl, nr, sqre, &k, &d__[1], &work[iz], alpha, beta, &u[u_offset], ldu, &vt[vt_offset], ldvt, &work[isigma], &work[iu2], &ldu2, & work[ivt2], &ldvt2, &iwork[idxp], &iwork[idx], &iwork[idxc], & idxq[1], &iwork[coltyp], info); /* Solve Secular Equation and update singular vectors. */ ldq = k; dlasd3_(nl, nr, sqre, &k, &d__[1], &work[iq], &ldq, &work[isigma], &u[ u_offset], ldu, &work[iu2], &ldu2, &vt[vt_offset], ldvt, &work[ ivt2], &ldvt2, &iwork[idxc], &iwork[coltyp], &work[iz], info); if (*info != 0) { return 0; } /* Unscale. */ dlascl_("G", &c__0, &c__0, &c_b2865, &orgnrm, &n, &c__1, &d__[1], &n, info); /* Prepare the IDXQ sorting permutation. */ n1 = k; n2 = n - k; dlamrg_(&n1, &n2, &d__[1], &c__1, &c_n1, &idxq[1]); return 0; /* End of DLASD1 */ } /* dlasd1_ */ /* Subroutine */ int dlasd2_(integer *nl, integer *nr, integer *sqre, integer *k, doublereal *d__, doublereal *z__, doublereal *alpha, doublereal * beta, doublereal *u, integer *ldu, doublereal *vt, integer *ldvt, doublereal *dsigma, doublereal *u2, integer *ldu2, doublereal *vt2, integer *ldvt2, integer *idxp, integer *idx, integer *idxc, integer * idxq, integer *coltyp, integer *info) { /* System generated locals */ integer u_dim1, u_offset, u2_dim1, u2_offset, vt_dim1, vt_offset, vt2_dim1, vt2_offset, i__1; doublereal d__1, d__2; /* Local variables */ static doublereal c__; static integer i__, j, m, n; static doublereal s; static integer k2; static doublereal z1; static integer ct, jp; static doublereal eps, tau, tol; static integer psm[4], nlp1, nlp2, idxi, idxj; extern /* Subroutine */ int drot_(integer *, doublereal *, integer *, doublereal *, integer *, doublereal *, doublereal *); static integer ctot[4], idxjp; extern /* Subroutine */ int dcopy_(integer *, doublereal *, integer *, doublereal *, integer *); static integer jprev; extern /* Subroutine */ int dlamrg_(integer *, integer *, doublereal *, integer *, integer *, integer *), dlacpy_(char *, integer *, integer *, doublereal *, integer *, doublereal *, integer *), dlaset_(char *, integer *, integer *, doublereal *, doublereal *, doublereal *, integer *), xerbla_(char *, integer *); static doublereal hlftol; /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Oak Ridge National Lab, Argonne National Lab, Courant Institute, NAG Ltd., and Rice University October 31, 1999 Purpose ======= DLASD2 merges the two sets of singular values together into a single sorted set. Then it tries to deflate the size of the problem. There are two ways in which deflation can occur: when two or more singular values are close together or if there is a tiny entry in the Z vector. For each such occurrence the order of the related secular equation problem is reduced by one. DLASD2 is called from DLASD1. Arguments ========= NL (input) INTEGER The row dimension of the upper block. NL >= 1. NR (input) INTEGER The row dimension of the lower block. NR >= 1. SQRE (input) INTEGER = 0: the lower block is an NR-by-NR square matrix. = 1: the lower block is an NR-by-(NR+1) rectangular matrix. The bidiagonal matrix has N = NL + NR + 1 rows and M = N + SQRE >= N columns. K (output) INTEGER Contains the dimension of the non-deflated matrix, This is the order of the related secular equation. 1 <= K <=N. D (input/output) DOUBLE PRECISION array, dimension(N) On entry D contains the singular values of the two submatrices to be combined. On exit D contains the trailing (N-K) updated singular values (those which were deflated) sorted into increasing order. ALPHA (input) DOUBLE PRECISION Contains the diagonal element associated with the added row. BETA (input) DOUBLE PRECISION Contains the off-diagonal element associated with the added row. U (input/output) DOUBLE PRECISION array, dimension(LDU,N) On entry U contains the left singular vectors of two submatrices in the two square blocks with corners at (1,1), (NL, NL), and (NL+2, NL+2), (N,N). On exit U contains the trailing (N-K) updated left singular vectors (those which were deflated) in its last N-K columns. LDU (input) INTEGER The leading dimension of the array U. LDU >= N. Z (output) DOUBLE PRECISION array, dimension(N) On exit Z contains the updating row vector in the secular equation. DSIGMA (output) DOUBLE PRECISION array, dimension (N) Contains a copy of the diagonal elements (K-1 singular values and one zero) in the secular equation. U2 (output) DOUBLE PRECISION array, dimension(LDU2,N) Contains a copy of the first K-1 left singular vectors which will be used by DLASD3 in a matrix multiply (DGEMM) to solve for the new left singular vectors. U2 is arranged into four blocks. The first block contains a column with 1 at NL+1 and zero everywhere else; the second block contains non-zero entries only at and above NL; the third contains non-zero entries only below NL+1; and the fourth is dense. LDU2 (input) INTEGER The leading dimension of the array U2. LDU2 >= N. VT (input/output) DOUBLE PRECISION array, dimension(LDVT,M) On entry VT' contains the right singular vectors of two submatrices in the two square blocks with corners at (1,1), (NL+1, NL+1), and (NL+2, NL+2), (M,M). On exit VT' contains the trailing (N-K) updated right singular vectors (those which were deflated) in its last N-K columns. In case SQRE =1, the last row of VT spans the right null space. LDVT (input) INTEGER The leading dimension of the array VT. LDVT >= M. VT2 (output) DOUBLE PRECISION array, dimension(LDVT2,N) VT2' contains a copy of the first K right singular vectors which will be used by DLASD3 in a matrix multiply (DGEMM) to solve for the new right singular vectors. VT2 is arranged into three blocks. The first block contains a row that corresponds to the special 0 diagonal element in SIGMA; the second block contains non-zeros only at and before NL +1; the third block contains non-zeros only at and after NL +2. LDVT2 (input) INTEGER The leading dimension of the array VT2. LDVT2 >= M. IDXP (workspace) INTEGER array, dimension(N) This will contain the permutation used to place deflated values of D at the end of the array. On output IDXP(2:K) points to the nondeflated D-values and IDXP(K+1:N) points to the deflated singular values. IDX (workspace) INTEGER array, dimension(N) This will contain the permutation used to sort the contents of D into ascending order. IDXC (output) INTEGER array, dimension(N) This will contain the permutation used to arrange the columns of the deflated U matrix into three groups: the first group contains non-zero entries only at and above NL, the second contains non-zero entries only below NL+2, and the third is dense. COLTYP (workspace/output) INTEGER array, dimension(N) As workspace, this will contain a label which will indicate which of the following types a column in the U2 matrix or a row in the VT2 matrix is: 1 : non-zero in the upper half only 2 : non-zero in the lower half only 3 : dense 4 : deflated On exit, it is an array of dimension 4, with COLTYP(I) being the dimension of the I-th type columns. IDXQ (input) INTEGER array, dimension(N) This contains the permutation which separately sorts the two sub-problems in D into ascending order. Note that entries in the first hlaf of this permutation must first be moved one position backward; and entries in the second half must first have NL+1 added to their values. INFO (output) INTEGER = 0: successful exit. < 0: if INFO = -i, the i-th argument had an illegal value. Further Details =============== Based on contributions by Ming Gu and Huan Ren, Computer Science Division, University of California at Berkeley, USA ===================================================================== Test the input parameters. */ /* Parameter adjustments */ --d__; --z__; u_dim1 = *ldu; u_offset = 1 + u_dim1; u -= u_offset; vt_dim1 = *ldvt; vt_offset = 1 + vt_dim1; vt -= vt_offset; --dsigma; u2_dim1 = *ldu2; u2_offset = 1 + u2_dim1; u2 -= u2_offset; vt2_dim1 = *ldvt2; vt2_offset = 1 + vt2_dim1; vt2 -= vt2_offset; --idxp; --idx; --idxc; --idxq; --coltyp; /* Function Body */ *info = 0; if (*nl < 1) { *info = -1; } else if (*nr < 1) { *info = -2; } else if (*sqre != 1 && *sqre != 0) { *info = -3; } n = *nl + *nr + 1; m = n + *sqre; if (*ldu < n) { *info = -10; } else if (*ldvt < m) { *info = -12; } else if (*ldu2 < n) { *info = -15; } else if (*ldvt2 < m) { *info = -17; } if (*info != 0) { i__1 = -(*info); xerbla_("DLASD2", &i__1); return 0; } nlp1 = *nl + 1; nlp2 = *nl + 2; /* Generate the first part of the vector Z; and move the singular values in the first part of D one position backward. */ z1 = *alpha * vt[nlp1 + nlp1 * vt_dim1]; z__[1] = z1; for (i__ = *nl; i__ >= 1; --i__) { z__[i__ + 1] = *alpha * vt[i__ + nlp1 * vt_dim1]; d__[i__ + 1] = d__[i__]; idxq[i__ + 1] = idxq[i__] + 1; /* L10: */ } /* Generate the second part of the vector Z. */ i__1 = m; for (i__ = nlp2; i__ <= i__1; ++i__) { z__[i__] = *beta * vt[i__ + nlp2 * vt_dim1]; /* L20: */ } /* Initialize some reference arrays. */ i__1 = nlp1; for (i__ = 2; i__ <= i__1; ++i__) { coltyp[i__] = 1; /* L30: */ } i__1 = n; for (i__ = nlp2; i__ <= i__1; ++i__) { coltyp[i__] = 2; /* L40: */ } /* Sort the singular values into increasing order */ i__1 = n; for (i__ = nlp2; i__ <= i__1; ++i__) { idxq[i__] += nlp1; /* L50: */ } /* DSIGMA, IDXC, IDXC, and the first column of U2 are used as storage space. */ i__1 = n; for (i__ = 2; i__ <= i__1; ++i__) { dsigma[i__] = d__[idxq[i__]]; u2[i__ + u2_dim1] = z__[idxq[i__]]; idxc[i__] = coltyp[idxq[i__]]; /* L60: */ } dlamrg_(nl, nr, &dsigma[2], &c__1, &c__1, &idx[2]); i__1 = n; for (i__ = 2; i__ <= i__1; ++i__) { idxi = idx[i__] + 1; d__[i__] = dsigma[idxi]; z__[i__] = u2[idxi + u2_dim1]; coltyp[i__] = idxc[idxi]; /* L70: */ } /* Calculate the allowable deflation tolerance */ eps = EPSILON; /* Computing MAX */ d__1 = abs(*alpha), d__2 = abs(*beta); tol = max(d__1,d__2); /* Computing MAX */ d__2 = (d__1 = d__[n], abs(d__1)); tol = eps * 8. * max(d__2,tol); /* There are 2 kinds of deflation -- first a value in the z-vector is small, second two (or more) singular values are very close together (their difference is small). If the value in the z-vector is small, we simply permute the array so that the corresponding singular value is moved to the end. If two values in the D-vector are close, we perform a two-sided rotation designed to make one of the corresponding z-vector entries zero, and then permute the array so that the deflated singular value is moved to the end. If there are multiple singular values then the problem deflates. Here the number of equal singular values are found. As each equal singular value is found, an elementary reflector is computed to rotate the corresponding singular subspace so that the corresponding components of Z are zero in this new basis. */ *k = 1; k2 = n + 1; i__1 = n; for (j = 2; j <= i__1; ++j) { if ((d__1 = z__[j], abs(d__1)) <= tol) { /* Deflate due to small z component. */ --k2; idxp[k2] = j; coltyp[j] = 4; if (j == n) { goto L120; } } else { jprev = j; goto L90; } /* L80: */ } L90: j = jprev; L100: ++j; if (j > n) { goto L110; } if ((d__1 = z__[j], abs(d__1)) <= tol) { /* Deflate due to small z component. */ --k2; idxp[k2] = j; coltyp[j] = 4; } else { /* Check if singular values are close enough to allow deflation. */ if ((d__1 = d__[j] - d__[jprev], abs(d__1)) <= tol) { /* Deflation is possible. */ s = z__[jprev]; c__ = z__[j]; /* Find sqrt(a**2+b**2) without overflow or destructive underflow. */ tau = dlapy2_(&c__, &s); c__ /= tau; s = -s / tau; z__[j] = tau; z__[jprev] = 0.; /* Apply back the Givens rotation to the left and right singular vector matrices. */ idxjp = idxq[idx[jprev] + 1]; idxj = idxq[idx[j] + 1]; if (idxjp <= nlp1) { --idxjp; } if (idxj <= nlp1) { --idxj; } drot_(&n, &u[idxjp * u_dim1 + 1], &c__1, &u[idxj * u_dim1 + 1], & c__1, &c__, &s); drot_(&m, &vt[idxjp + vt_dim1], ldvt, &vt[idxj + vt_dim1], ldvt, & c__, &s); if (coltyp[j] != coltyp[jprev]) { coltyp[j] = 3; } coltyp[jprev] = 4; --k2; idxp[k2] = jprev; jprev = j; } else { ++(*k); u2[*k + u2_dim1] = z__[jprev]; dsigma[*k] = d__[jprev]; idxp[*k] = jprev; jprev = j; } } goto L100; L110: /* Record the last singular value. */ ++(*k); u2[*k + u2_dim1] = z__[jprev]; dsigma[*k] = d__[jprev]; idxp[*k] = jprev; L120: /* Count up the total number of the various types of columns, then form a permutation which positions the four column types into four groups of uniform structure (although one or more of these groups may be empty). */ for (j = 1; j <= 4; ++j) { ctot[j - 1] = 0; /* L130: */ } i__1 = n; for (j = 2; j <= i__1; ++j) { ct = coltyp[j]; ++ctot[ct - 1]; /* L140: */ } /* PSM(*) = Position in SubMatrix (of types 1 through 4) */ psm[0] = 2; psm[1] = ctot[0] + 2; psm[2] = psm[1] + ctot[1]; psm[3] = psm[2] + ctot[2]; /* Fill out the IDXC array so that the permutation which it induces will place all type-1 columns first, all type-2 columns next, then all type-3's, and finally all type-4's, starting from the second column. This applies similarly to the rows of VT. */ i__1 = n; for (j = 2; j <= i__1; ++j) { jp = idxp[j]; ct = coltyp[jp]; idxc[psm[ct - 1]] = j; ++psm[ct - 1]; /* L150: */ } /* Sort the singular values and corresponding singular vectors into DSIGMA, U2, and VT2 respectively. The singular values/vectors which were not deflated go into the first K slots of DSIGMA, U2, and VT2 respectively, while those which were deflated go into the last N - K slots, except that the first column/row will be treated separately. */ i__1 = n; for (j = 2; j <= i__1; ++j) { jp = idxp[j]; dsigma[j] = d__[jp]; idxj = idxq[idx[idxp[idxc[j]]] + 1]; if (idxj <= nlp1) { --idxj; } dcopy_(&n, &u[idxj * u_dim1 + 1], &c__1, &u2[j * u2_dim1 + 1], &c__1); dcopy_(&m, &vt[idxj + vt_dim1], ldvt, &vt2[j + vt2_dim1], ldvt2); /* L160: */ } /* Determine DSIGMA(1), DSIGMA(2) and Z(1) */ dsigma[1] = 0.; hlftol = tol / 2.; if (abs(dsigma[2]) <= hlftol) { dsigma[2] = hlftol; } if (m > n) { z__[1] = dlapy2_(&z1, &z__[m]); if (z__[1] <= tol) { c__ = 1.; s = 0.; z__[1] = tol; } else { c__ = z1 / z__[1]; s = z__[m] / z__[1]; } } else { if (abs(z1) <= tol) { z__[1] = tol; } else { z__[1] = z1; } } /* Move the rest of the updating row to Z. */ i__1 = *k - 1; dcopy_(&i__1, &u2[u2_dim1 + 2], &c__1, &z__[2], &c__1); /* Determine the first column of U2, the first row of VT2 and the last row of VT. */ dlaset_("A", &n, &c__1, &c_b2879, &c_b2879, &u2[u2_offset], ldu2); u2[nlp1 + u2_dim1] = 1.; if (m > n) { i__1 = nlp1; for (i__ = 1; i__ <= i__1; ++i__) { vt[m + i__ * vt_dim1] = -s * vt[nlp1 + i__ * vt_dim1]; vt2[i__ * vt2_dim1 + 1] = c__ * vt[nlp1 + i__ * vt_dim1]; /* L170: */ } i__1 = m; for (i__ = nlp2; i__ <= i__1; ++i__) { vt2[i__ * vt2_dim1 + 1] = s * vt[m + i__ * vt_dim1]; vt[m + i__ * vt_dim1] = c__ * vt[m + i__ * vt_dim1]; /* L180: */ } } else { dcopy_(&m, &vt[nlp1 + vt_dim1], ldvt, &vt2[vt2_dim1 + 1], ldvt2); } if (m > n) { dcopy_(&m, &vt[m + vt_dim1], ldvt, &vt2[m + vt2_dim1], ldvt2); } /* The deflated singular values and their corresponding vectors go into the back of D, U, and V respectively. */ if (n > *k) { i__1 = n - *k; dcopy_(&i__1, &dsigma[*k + 1], &c__1, &d__[*k + 1], &c__1); i__1 = n - *k; dlacpy_("A", &n, &i__1, &u2[(*k + 1) * u2_dim1 + 1], ldu2, &u[(*k + 1) * u_dim1 + 1], ldu); i__1 = n - *k; dlacpy_("A", &i__1, &m, &vt2[*k + 1 + vt2_dim1], ldvt2, &vt[*k + 1 + vt_dim1], ldvt); } /* Copy CTOT into COLTYP for referencing in DLASD3. */ for (j = 1; j <= 4; ++j) { coltyp[j] = ctot[j - 1]; /* L190: */ } return 0; /* End of DLASD2 */ } /* dlasd2_ */ /* Subroutine */ int dlasd3_(integer *nl, integer *nr, integer *sqre, integer *k, doublereal *d__, doublereal *q, integer *ldq, doublereal *dsigma, doublereal *u, integer *ldu, doublereal *u2, integer *ldu2, doublereal *vt, integer *ldvt, doublereal *vt2, integer *ldvt2, integer *idxc, integer *ctot, doublereal *z__, integer *info) { /* System generated locals */ integer q_dim1, q_offset, u_dim1, u_offset, u2_dim1, u2_offset, vt_dim1, vt_offset, vt2_dim1, vt2_offset, i__1, i__2; doublereal d__1, d__2; /* Builtin functions */ double sqrt(doublereal), d_sign(doublereal *, doublereal *); /* Local variables */ static integer i__, j, m, n, jc; static doublereal rho; static integer nlp1, nlp2, nrp1; static doublereal temp; extern doublereal dnrm2_(integer *, doublereal *, integer *); extern /* Subroutine */ int dgemm_(char *, char *, integer *, integer *, integer *, doublereal *, doublereal *, integer *, doublereal *, integer *, doublereal *, doublereal *, integer *); static integer ctemp; extern /* Subroutine */ int dcopy_(integer *, doublereal *, integer *, doublereal *, integer *); static integer ktemp; extern doublereal dlamc3_(doublereal *, doublereal *); extern /* Subroutine */ int dlasd4_(integer *, integer *, doublereal *, doublereal *, doublereal *, doublereal *, doublereal *, doublereal *, integer *), dlascl_(char *, integer *, integer *, doublereal *, doublereal *, integer *, integer *, doublereal *, integer *, integer *), dlacpy_(char *, integer *, integer *, doublereal *, integer *, doublereal *, integer *), xerbla_(char *, integer *); /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Oak Ridge National Lab, Argonne National Lab, Courant Institute, NAG Ltd., and Rice University October 31, 1999 Purpose ======= DLASD3 finds all the square roots of the roots of the secular equation, as defined by the values in D and Z. It makes the appropriate calls to DLASD4 and then updates the singular vectors by matrix multiplication. This code makes very mild assumptions about floating point arithmetic. It will work on machines with a guard digit in add/subtract, or on those binary machines without guard digits which subtract like the Cray XMP, Cray YMP, Cray C 90, or Cray 2. It could conceivably fail on hexadecimal or decimal machines without guard digits, but we know of none. DLASD3 is called from DLASD1. Arguments ========= NL (input) INTEGER The row dimension of the upper block. NL >= 1. NR (input) INTEGER The row dimension of the lower block. NR >= 1. SQRE (input) INTEGER = 0: the lower block is an NR-by-NR square matrix. = 1: the lower block is an NR-by-(NR+1) rectangular matrix. The bidiagonal matrix has N = NL + NR + 1 rows and M = N + SQRE >= N columns. K (input) INTEGER The size of the secular equation, 1 =< K = < N. D (output) DOUBLE PRECISION array, dimension(K) On exit the square roots of the roots of the secular equation, in ascending order. Q (workspace) DOUBLE PRECISION array, dimension at least (LDQ,K). LDQ (input) INTEGER The leading dimension of the array Q. LDQ >= K. DSIGMA (input) DOUBLE PRECISION array, dimension(K) The first K elements of this array contain the old roots of the deflated updating problem. These are the poles of the secular equation. U (input) DOUBLE PRECISION array, dimension (LDU, N) The last N - K columns of this matrix contain the deflated left singular vectors. LDU (input) INTEGER The leading dimension of the array U. LDU >= N. U2 (input) DOUBLE PRECISION array, dimension (LDU2, N) The first K columns of this matrix contain the non-deflated left singular vectors for the split problem. LDU2 (input) INTEGER The leading dimension of the array U2. LDU2 >= N. VT (input) DOUBLE PRECISION array, dimension (LDVT, M) The last M - K columns of VT' contain the deflated right singular vectors. LDVT (input) INTEGER The leading dimension of the array VT. LDVT >= N. VT2 (input) DOUBLE PRECISION array, dimension (LDVT2, N) The first K columns of VT2' contain the non-deflated right singular vectors for the split problem. LDVT2 (input) INTEGER The leading dimension of the array VT2. LDVT2 >= N. IDXC (input) INTEGER array, dimension ( N ) The permutation used to arrange the columns of U (and rows of VT) into three groups: the first group contains non-zero entries only at and above (or before) NL +1; the second contains non-zero entries only at and below (or after) NL+2; and the third is dense. The first column of U and the row of VT are treated separately, however. The rows of the singular vectors found by DLASD4 must be likewise permuted before the matrix multiplies can take place. CTOT (input) INTEGER array, dimension ( 4 ) A count of the total number of the various types of columns in U (or rows in VT), as described in IDXC. The fourth column type is any column which has been deflated. Z (input) DOUBLE PRECISION array, dimension (K) The first K elements of this array contain the components of the deflation-adjusted updating row vector. INFO (output) INTEGER = 0: successful exit. < 0: if INFO = -i, the i-th argument had an illegal value. > 0: if INFO = 1, an singular value did not converge Further Details =============== Based on contributions by Ming Gu and Huan Ren, Computer Science Division, University of California at Berkeley, USA ===================================================================== Test the input parameters. */ /* Parameter adjustments */ --d__; q_dim1 = *ldq; q_offset = 1 + q_dim1; q -= q_offset; --dsigma; u_dim1 = *ldu; u_offset = 1 + u_dim1; u -= u_offset; u2_dim1 = *ldu2; u2_offset = 1 + u2_dim1; u2 -= u2_offset; vt_dim1 = *ldvt; vt_offset = 1 + vt_dim1; vt -= vt_offset; vt2_dim1 = *ldvt2; vt2_offset = 1 + vt2_dim1; vt2 -= vt2_offset; --idxc; --ctot; --z__; /* Function Body */ *info = 0; if (*nl < 1) { *info = -1; } else if (*nr < 1) { *info = -2; } else if (*sqre != 1 && *sqre != 0) { *info = -3; } n = *nl + *nr + 1; m = n + *sqre; nlp1 = *nl + 1; nlp2 = *nl + 2; if ((*k < 1) || (*k > n)) { *info = -4; } else if (*ldq < *k) { *info = -7; } else if (*ldu < n) { *info = -10; } else if (*ldu2 < n) { *info = -12; } else if (*ldvt < m) { *info = -14; } else if (*ldvt2 < m) { *info = -16; } if (*info != 0) { i__1 = -(*info); xerbla_("DLASD3", &i__1); return 0; } /* Quick return if possible */ if (*k == 1) { d__[1] = abs(z__[1]); dcopy_(&m, &vt2[vt2_dim1 + 1], ldvt2, &vt[vt_dim1 + 1], ldvt); if (z__[1] > 0.) { dcopy_(&n, &u2[u2_dim1 + 1], &c__1, &u[u_dim1 + 1], &c__1); } else { i__1 = n; for (i__ = 1; i__ <= i__1; ++i__) { u[i__ + u_dim1] = -u2[i__ + u2_dim1]; /* L10: */ } } return 0; } /* Modify values DSIGMA(i) to make sure all DSIGMA(i)-DSIGMA(j) can be computed with high relative accuracy (barring over/underflow). This is a problem on machines without a guard digit in add/subtract (Cray XMP, Cray YMP, Cray C 90 and Cray 2). The following code replaces DSIGMA(I) by 2*DSIGMA(I)-DSIGMA(I), which on any of these machines zeros out the bottommost bit of DSIGMA(I) if it is 1; this makes the subsequent subtractions DSIGMA(I)-DSIGMA(J) unproblematic when cancellation occurs. On binary machines with a guard digit (almost all machines) it does not change DSIGMA(I) at all. On hexadecimal and decimal machines with a guard digit, it slightly changes the bottommost bits of DSIGMA(I). It does not account for hexadecimal or decimal machines without guard digits (we know of none). We use a subroutine call to compute 2*DLAMBDA(I) to prevent optimizing compilers from eliminating this code. */ i__1 = *k; for (i__ = 1; i__ <= i__1; ++i__) { dsigma[i__] = dlamc3_(&dsigma[i__], &dsigma[i__]) - dsigma[i__]; /* L20: */ } /* Keep a copy of Z. */ dcopy_(k, &z__[1], &c__1, &q[q_offset], &c__1); /* Normalize Z. */ rho = dnrm2_(k, &z__[1], &c__1); dlascl_("G", &c__0, &c__0, &rho, &c_b2865, k, &c__1, &z__[1], k, info); rho *= rho; /* Find the new singular values. */ i__1 = *k; for (j = 1; j <= i__1; ++j) { dlasd4_(k, &j, &dsigma[1], &z__[1], &u[j * u_dim1 + 1], &rho, &d__[j], &vt[j * vt_dim1 + 1], info); /* If the zero finder fails, the computation is terminated. */ if (*info != 0) { return 0; } /* L30: */ } /* Compute updated Z. */ i__1 = *k; for (i__ = 1; i__ <= i__1; ++i__) { z__[i__] = u[i__ + *k * u_dim1] * vt[i__ + *k * vt_dim1]; i__2 = i__ - 1; for (j = 1; j <= i__2; ++j) { z__[i__] *= u[i__ + j * u_dim1] * vt[i__ + j * vt_dim1] / (dsigma[ i__] - dsigma[j]) / (dsigma[i__] + dsigma[j]); /* L40: */ } i__2 = *k - 1; for (j = i__; j <= i__2; ++j) { z__[i__] *= u[i__ + j * u_dim1] * vt[i__ + j * vt_dim1] / (dsigma[ i__] - dsigma[j + 1]) / (dsigma[i__] + dsigma[j + 1]); /* L50: */ } d__2 = sqrt((d__1 = z__[i__], abs(d__1))); z__[i__] = d_sign(&d__2, &q[i__ + q_dim1]); /* L60: */ } /* Compute left singular vectors of the modified diagonal matrix, and store related information for the right singular vectors. */ i__1 = *k; for (i__ = 1; i__ <= i__1; ++i__) { vt[i__ * vt_dim1 + 1] = z__[1] / u[i__ * u_dim1 + 1] / vt[i__ * vt_dim1 + 1]; u[i__ * u_dim1 + 1] = -1.; i__2 = *k; for (j = 2; j <= i__2; ++j) { vt[j + i__ * vt_dim1] = z__[j] / u[j + i__ * u_dim1] / vt[j + i__ * vt_dim1]; u[j + i__ * u_dim1] = dsigma[j] * vt[j + i__ * vt_dim1]; /* L70: */ } temp = dnrm2_(k, &u[i__ * u_dim1 + 1], &c__1); q[i__ * q_dim1 + 1] = u[i__ * u_dim1 + 1] / temp; i__2 = *k; for (j = 2; j <= i__2; ++j) { jc = idxc[j]; q[j + i__ * q_dim1] = u[jc + i__ * u_dim1] / temp; /* L80: */ } /* L90: */ } /* Update the left singular vector matrix. */ if (*k == 2) { dgemm_("N", "N", &n, k, k, &c_b2865, &u2[u2_offset], ldu2, &q[ q_offset], ldq, &c_b2879, &u[u_offset], ldu); goto L100; } if (ctot[1] > 0) { dgemm_("N", "N", nl, k, &ctot[1], &c_b2865, &u2[((u2_dim1) << (1)) + 1], ldu2, &q[q_dim1 + 2], ldq, &c_b2879, &u[u_dim1 + 1], ldu); if (ctot[3] > 0) { ktemp = ctot[1] + 2 + ctot[2]; dgemm_("N", "N", nl, k, &ctot[3], &c_b2865, &u2[ktemp * u2_dim1 + 1], ldu2, &q[ktemp + q_dim1], ldq, &c_b2865, &u[u_dim1 + 1], ldu); } } else if (ctot[3] > 0) { ktemp = ctot[1] + 2 + ctot[2]; dgemm_("N", "N", nl, k, &ctot[3], &c_b2865, &u2[ktemp * u2_dim1 + 1], ldu2, &q[ktemp + q_dim1], ldq, &c_b2879, &u[u_dim1 + 1], ldu); } else { dlacpy_("F", nl, k, &u2[u2_offset], ldu2, &u[u_offset], ldu); } dcopy_(k, &q[q_dim1 + 1], ldq, &u[nlp1 + u_dim1], ldu); ktemp = ctot[1] + 2; ctemp = ctot[2] + ctot[3]; dgemm_("N", "N", nr, k, &ctemp, &c_b2865, &u2[nlp2 + ktemp * u2_dim1], ldu2, &q[ktemp + q_dim1], ldq, &c_b2879, &u[nlp2 + u_dim1], ldu); /* Generate the right singular vectors. */ L100: i__1 = *k; for (i__ = 1; i__ <= i__1; ++i__) { temp = dnrm2_(k, &vt[i__ * vt_dim1 + 1], &c__1); q[i__ + q_dim1] = vt[i__ * vt_dim1 + 1] / temp; i__2 = *k; for (j = 2; j <= i__2; ++j) { jc = idxc[j]; q[i__ + j * q_dim1] = vt[jc + i__ * vt_dim1] / temp; /* L110: */ } /* L120: */ } /* Update the right singular vector matrix. */ if (*k == 2) { dgemm_("N", "N", k, &m, k, &c_b2865, &q[q_offset], ldq, &vt2[ vt2_offset], ldvt2, &c_b2879, &vt[vt_offset], ldvt); return 0; } ktemp = ctot[1] + 1; dgemm_("N", "N", k, &nlp1, &ktemp, &c_b2865, &q[q_dim1 + 1], ldq, &vt2[ vt2_dim1 + 1], ldvt2, &c_b2879, &vt[vt_dim1 + 1], ldvt); ktemp = ctot[1] + 2 + ctot[2]; if (ktemp <= *ldvt2) { dgemm_("N", "N", k, &nlp1, &ctot[3], &c_b2865, &q[ktemp * q_dim1 + 1], ldq, &vt2[ktemp + vt2_dim1], ldvt2, &c_b2865, &vt[vt_dim1 + 1], ldvt); } ktemp = ctot[1] + 1; nrp1 = *nr + *sqre; if (ktemp > 1) { i__1 = *k; for (i__ = 1; i__ <= i__1; ++i__) { q[i__ + ktemp * q_dim1] = q[i__ + q_dim1]; /* L130: */ } i__1 = m; for (i__ = nlp2; i__ <= i__1; ++i__) { vt2[ktemp + i__ * vt2_dim1] = vt2[i__ * vt2_dim1 + 1]; /* L140: */ } } ctemp = ctot[2] + 1 + ctot[3]; dgemm_("N", "N", k, &nrp1, &ctemp, &c_b2865, &q[ktemp * q_dim1 + 1], ldq, &vt2[ktemp + nlp2 * vt2_dim1], ldvt2, &c_b2879, &vt[nlp2 * vt_dim1 + 1], ldvt); return 0; /* End of DLASD3 */ } /* dlasd3_ */ /* Subroutine */ int dlasd4_(integer *n, integer *i__, doublereal *d__, doublereal *z__, doublereal *delta, doublereal *rho, doublereal * sigma, doublereal *work, integer *info) { /* System generated locals */ integer i__1; doublereal d__1; /* Builtin functions */ double sqrt(doublereal); /* Local variables */ static doublereal a, b, c__; static integer j; static doublereal w, dd[3]; static integer ii; static doublereal dw, zz[3]; static integer ip1; static doublereal eta, phi, eps, tau, psi; static integer iim1, iip1; static doublereal dphi, dpsi; static integer iter; static doublereal temp, prew, sg2lb, sg2ub, temp1, temp2, dtiim, delsq, dtiip; static integer niter; static doublereal dtisq; static logical swtch; static doublereal dtnsq; extern /* Subroutine */ int dlaed6_(integer *, logical *, doublereal *, doublereal *, doublereal *, doublereal *, doublereal *, integer *) , dlasd5_(integer *, doublereal *, doublereal *, doublereal *, doublereal *, doublereal *, doublereal *); static doublereal delsq2, dtnsq1; static logical swtch3; static logical orgati; static doublereal erretm, dtipsq, rhoinv; /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Oak Ridge National Lab, Argonne National Lab, Courant Institute, NAG Ltd., and Rice University October 31, 1999 Purpose ======= This subroutine computes the square root of the I-th updated eigenvalue of a positive symmetric rank-one modification to a positive diagonal matrix whose entries are given as the squares of the corresponding entries in the array d, and that 0 <= D(i) < D(j) for i < j and that RHO > 0. This is arranged by the calling routine, and is no loss in generality. The rank-one modified system is thus diag( D ) * diag( D ) + RHO * Z * Z_transpose. where we assume the Euclidean norm of Z is 1. The method consists of approximating the rational functions in the secular equation by simpler interpolating rational functions. Arguments ========= N (input) INTEGER The length of all arrays. I (input) INTEGER The index of the eigenvalue to be computed. 1 <= I <= N. D (input) DOUBLE PRECISION array, dimension ( N ) The original eigenvalues. It is assumed that they are in order, 0 <= D(I) < D(J) for I < J. Z (input) DOUBLE PRECISION array, dimension ( N ) The components of the updating vector. DELTA (output) DOUBLE PRECISION array, dimension ( N ) If N .ne. 1, DELTA contains (D(j) - sigma_I) in its j-th component. If N = 1, then DELTA(1) = 1. The vector DELTA contains the information necessary to construct the (singular) eigenvectors. RHO (input) DOUBLE PRECISION The scalar in the symmetric updating formula. SIGMA (output) DOUBLE PRECISION The computed lambda_I, the I-th updated eigenvalue. WORK (workspace) DOUBLE PRECISION array, dimension ( N ) If N .ne. 1, WORK contains (D(j) + sigma_I) in its j-th component. If N = 1, then WORK( 1 ) = 1. INFO (output) INTEGER = 0: successful exit > 0: if INFO = 1, the updating process failed. Internal Parameters =================== Logical variable ORGATI (origin-at-i?) is used for distinguishing whether D(i) or D(i+1) is treated as the origin. ORGATI = .true. origin at i ORGATI = .false. origin at i+1 Logical variable SWTCH3 (switch-for-3-poles?) is for noting if we are working with THREE poles! MAXIT is the maximum number of iterations allowed for each eigenvalue. Further Details =============== Based on contributions by Ren-Cang Li, Computer Science Division, University of California at Berkeley, USA ===================================================================== Since this routine is called in an inner loop, we do no argument checking. Quick return for N=1 and 2. */ /* Parameter adjustments */ --work; --delta; --z__; --d__; /* Function Body */ *info = 0; if (*n == 1) { /* Presumably, I=1 upon entry */ *sigma = sqrt(d__[1] * d__[1] + *rho * z__[1] * z__[1]); delta[1] = 1.; work[1] = 1.; return 0; } if (*n == 2) { dlasd5_(i__, &d__[1], &z__[1], &delta[1], rho, sigma, &work[1]); return 0; } /* Compute machine epsilon */ eps = EPSILON; rhoinv = 1. / *rho; /* The case I = N */ if (*i__ == *n) { /* Initialize some basic variables */ ii = *n - 1; niter = 1; /* Calculate initial guess */ temp = *rho / 2.; /* If ||Z||_2 is not one, then TEMP should be set to RHO * ||Z||_2^2 / TWO */ temp1 = temp / (d__[*n] + sqrt(d__[*n] * d__[*n] + temp)); i__1 = *n; for (j = 1; j <= i__1; ++j) { work[j] = d__[j] + d__[*n] + temp1; delta[j] = d__[j] - d__[*n] - temp1; /* L10: */ } psi = 0.; i__1 = *n - 2; for (j = 1; j <= i__1; ++j) { psi += z__[j] * z__[j] / (delta[j] * work[j]); /* L20: */ } c__ = rhoinv + psi; w = c__ + z__[ii] * z__[ii] / (delta[ii] * work[ii]) + z__[*n] * z__[* n] / (delta[*n] * work[*n]); if (w <= 0.) { temp1 = sqrt(d__[*n] * d__[*n] + *rho); temp = z__[*n - 1] * z__[*n - 1] / ((d__[*n - 1] + temp1) * (d__[* n] - d__[*n - 1] + *rho / (d__[*n] + temp1))) + z__[*n] * z__[*n] / *rho; /* The following TAU is to approximate SIGMA_n^2 - D( N )*D( N ) */ if (c__ <= temp) { tau = *rho; } else { delsq = (d__[*n] - d__[*n - 1]) * (d__[*n] + d__[*n - 1]); a = -c__ * delsq + z__[*n - 1] * z__[*n - 1] + z__[*n] * z__[* n]; b = z__[*n] * z__[*n] * delsq; if (a < 0.) { tau = b * 2. / (sqrt(a * a + b * 4. * c__) - a); } else { tau = (a + sqrt(a * a + b * 4. * c__)) / (c__ * 2.); } } /* It can be proved that D(N)^2+RHO/2 <= SIGMA_n^2 < D(N)^2+TAU <= D(N)^2+RHO */ } else { delsq = (d__[*n] - d__[*n - 1]) * (d__[*n] + d__[*n - 1]); a = -c__ * delsq + z__[*n - 1] * z__[*n - 1] + z__[*n] * z__[*n]; b = z__[*n] * z__[*n] * delsq; /* The following TAU is to approximate SIGMA_n^2 - D( N )*D( N ) */ if (a < 0.) { tau = b * 2. / (sqrt(a * a + b * 4. * c__) - a); } else { tau = (a + sqrt(a * a + b * 4. * c__)) / (c__ * 2.); } /* It can be proved that D(N)^2 < D(N)^2+TAU < SIGMA(N)^2 < D(N)^2+RHO/2 */ } /* The following ETA is to approximate SIGMA_n - D( N ) */ eta = tau / (d__[*n] + sqrt(d__[*n] * d__[*n] + tau)); *sigma = d__[*n] + eta; i__1 = *n; for (j = 1; j <= i__1; ++j) { delta[j] = d__[j] - d__[*i__] - eta; work[j] = d__[j] + d__[*i__] + eta; /* L30: */ } /* Evaluate PSI and the derivative DPSI */ dpsi = 0.; psi = 0.; erretm = 0.; i__1 = ii; for (j = 1; j <= i__1; ++j) { temp = z__[j] / (delta[j] * work[j]); psi += z__[j] * temp; dpsi += temp * temp; erretm += psi; /* L40: */ } erretm = abs(erretm); /* Evaluate PHI and the derivative DPHI */ temp = z__[*n] / (delta[*n] * work[*n]); phi = z__[*n] * temp; dphi = temp * temp; erretm = (-phi - psi) * 8. + erretm - phi + rhoinv + abs(tau) * (dpsi + dphi); w = rhoinv + phi + psi; /* Test for convergence */ if (abs(w) <= eps * erretm) { goto L240; } /* Calculate the new step */ ++niter; dtnsq1 = work[*n - 1] * delta[*n - 1]; dtnsq = work[*n] * delta[*n]; c__ = w - dtnsq1 * dpsi - dtnsq * dphi; a = (dtnsq + dtnsq1) * w - dtnsq * dtnsq1 * (dpsi + dphi); b = dtnsq * dtnsq1 * w; if (c__ < 0.) { c__ = abs(c__); } if (c__ == 0.) { eta = *rho - *sigma * *sigma; } else if (a >= 0.) { eta = (a + sqrt((d__1 = a * a - b * 4. * c__, abs(d__1)))) / (c__ * 2.); } else { eta = b * 2. / (a - sqrt((d__1 = a * a - b * 4. * c__, abs(d__1))) ); } /* Note, eta should be positive if w is negative, and eta should be negative otherwise. However, if for some reason caused by roundoff, eta*w > 0, we simply use one Newton step instead. This way will guarantee eta*w < 0. */ if (w * eta > 0.) { eta = -w / (dpsi + dphi); } temp = eta - dtnsq; if (temp > *rho) { eta = *rho + dtnsq; } tau += eta; eta /= *sigma + sqrt(eta + *sigma * *sigma); i__1 = *n; for (j = 1; j <= i__1; ++j) { delta[j] -= eta; work[j] += eta; /* L50: */ } *sigma += eta; /* Evaluate PSI and the derivative DPSI */ dpsi = 0.; psi = 0.; erretm = 0.; i__1 = ii; for (j = 1; j <= i__1; ++j) { temp = z__[j] / (work[j] * delta[j]); psi += z__[j] * temp; dpsi += temp * temp; erretm += psi; /* L60: */ } erretm = abs(erretm); /* Evaluate PHI and the derivative DPHI */ temp = z__[*n] / (work[*n] * delta[*n]); phi = z__[*n] * temp; dphi = temp * temp; erretm = (-phi - psi) * 8. + erretm - phi + rhoinv + abs(tau) * (dpsi + dphi); w = rhoinv + phi + psi; /* Main loop to update the values of the array DELTA */ iter = niter + 1; for (niter = iter; niter <= 20; ++niter) { /* Test for convergence */ if (abs(w) <= eps * erretm) { goto L240; } /* Calculate the new step */ dtnsq1 = work[*n - 1] * delta[*n - 1]; dtnsq = work[*n] * delta[*n]; c__ = w - dtnsq1 * dpsi - dtnsq * dphi; a = (dtnsq + dtnsq1) * w - dtnsq1 * dtnsq * (dpsi + dphi); b = dtnsq1 * dtnsq * w; if (a >= 0.) { eta = (a + sqrt((d__1 = a * a - b * 4. * c__, abs(d__1)))) / ( c__ * 2.); } else { eta = b * 2. / (a - sqrt((d__1 = a * a - b * 4. * c__, abs( d__1)))); } /* Note, eta should be positive if w is negative, and eta should be negative otherwise. However, if for some reason caused by roundoff, eta*w > 0, we simply use one Newton step instead. This way will guarantee eta*w < 0. */ if (w * eta > 0.) { eta = -w / (dpsi + dphi); } temp = eta - dtnsq; if (temp <= 0.) { eta /= 2.; } tau += eta; eta /= *sigma + sqrt(eta + *sigma * *sigma); i__1 = *n; for (j = 1; j <= i__1; ++j) { delta[j] -= eta; work[j] += eta; /* L70: */ } *sigma += eta; /* Evaluate PSI and the derivative DPSI */ dpsi = 0.; psi = 0.; erretm = 0.; i__1 = ii; for (j = 1; j <= i__1; ++j) { temp = z__[j] / (work[j] * delta[j]); psi += z__[j] * temp; dpsi += temp * temp; erretm += psi; /* L80: */ } erretm = abs(erretm); /* Evaluate PHI and the derivative DPHI */ temp = z__[*n] / (work[*n] * delta[*n]); phi = z__[*n] * temp; dphi = temp * temp; erretm = (-phi - psi) * 8. + erretm - phi + rhoinv + abs(tau) * ( dpsi + dphi); w = rhoinv + phi + psi; /* L90: */ } /* Return with INFO = 1, NITER = MAXIT and not converged */ *info = 1; goto L240; /* End for the case I = N */ } else { /* The case for I < N */ niter = 1; ip1 = *i__ + 1; /* Calculate initial guess */ delsq = (d__[ip1] - d__[*i__]) * (d__[ip1] + d__[*i__]); delsq2 = delsq / 2.; temp = delsq2 / (d__[*i__] + sqrt(d__[*i__] * d__[*i__] + delsq2)); i__1 = *n; for (j = 1; j <= i__1; ++j) { work[j] = d__[j] + d__[*i__] + temp; delta[j] = d__[j] - d__[*i__] - temp; /* L100: */ } psi = 0.; i__1 = *i__ - 1; for (j = 1; j <= i__1; ++j) { psi += z__[j] * z__[j] / (work[j] * delta[j]); /* L110: */ } phi = 0.; i__1 = *i__ + 2; for (j = *n; j >= i__1; --j) { phi += z__[j] * z__[j] / (work[j] * delta[j]); /* L120: */ } c__ = rhoinv + psi + phi; w = c__ + z__[*i__] * z__[*i__] / (work[*i__] * delta[*i__]) + z__[ ip1] * z__[ip1] / (work[ip1] * delta[ip1]); if (w > 0.) { /* d(i)^2 < the ith sigma^2 < (d(i)^2+d(i+1)^2)/2 We choose d(i) as origin. */ orgati = TRUE_; sg2lb = 0.; sg2ub = delsq2; a = c__ * delsq + z__[*i__] * z__[*i__] + z__[ip1] * z__[ip1]; b = z__[*i__] * z__[*i__] * delsq; if (a > 0.) { tau = b * 2. / (a + sqrt((d__1 = a * a - b * 4. * c__, abs( d__1)))); } else { tau = (a - sqrt((d__1 = a * a - b * 4. * c__, abs(d__1)))) / ( c__ * 2.); } /* TAU now is an estimation of SIGMA^2 - D( I )^2. The following, however, is the corresponding estimation of SIGMA - D( I ). */ eta = tau / (d__[*i__] + sqrt(d__[*i__] * d__[*i__] + tau)); } else { /* (d(i)^2+d(i+1)^2)/2 <= the ith sigma^2 < d(i+1)^2/2 We choose d(i+1) as origin. */ orgati = FALSE_; sg2lb = -delsq2; sg2ub = 0.; a = c__ * delsq - z__[*i__] * z__[*i__] - z__[ip1] * z__[ip1]; b = z__[ip1] * z__[ip1] * delsq; if (a < 0.) { tau = b * 2. / (a - sqrt((d__1 = a * a + b * 4. * c__, abs( d__1)))); } else { tau = -(a + sqrt((d__1 = a * a + b * 4. * c__, abs(d__1)))) / (c__ * 2.); } /* TAU now is an estimation of SIGMA^2 - D( IP1 )^2. The following, however, is the corresponding estimation of SIGMA - D( IP1 ). */ eta = tau / (d__[ip1] + sqrt((d__1 = d__[ip1] * d__[ip1] + tau, abs(d__1)))); } if (orgati) { ii = *i__; *sigma = d__[*i__] + eta; i__1 = *n; for (j = 1; j <= i__1; ++j) { work[j] = d__[j] + d__[*i__] + eta; delta[j] = d__[j] - d__[*i__] - eta; /* L130: */ } } else { ii = *i__ + 1; *sigma = d__[ip1] + eta; i__1 = *n; for (j = 1; j <= i__1; ++j) { work[j] = d__[j] + d__[ip1] + eta; delta[j] = d__[j] - d__[ip1] - eta; /* L140: */ } } iim1 = ii - 1; iip1 = ii + 1; /* Evaluate PSI and the derivative DPSI */ dpsi = 0.; psi = 0.; erretm = 0.; i__1 = iim1; for (j = 1; j <= i__1; ++j) { temp = z__[j] / (work[j] * delta[j]); psi += z__[j] * temp; dpsi += temp * temp; erretm += psi; /* L150: */ } erretm = abs(erretm); /* Evaluate PHI and the derivative DPHI */ dphi = 0.; phi = 0.; i__1 = iip1; for (j = *n; j >= i__1; --j) { temp = z__[j] / (work[j] * delta[j]); phi += z__[j] * temp; dphi += temp * temp; erretm += phi; /* L160: */ } w = rhoinv + phi + psi; /* W is the value of the secular function with its ii-th element removed. */ swtch3 = FALSE_; if (orgati) { if (w < 0.) { swtch3 = TRUE_; } } else { if (w > 0.) { swtch3 = TRUE_; } } if ((ii == 1) || (ii == *n)) { swtch3 = FALSE_; } temp = z__[ii] / (work[ii] * delta[ii]); dw = dpsi + dphi + temp * temp; temp = z__[ii] * temp; w += temp; erretm = (phi - psi) * 8. + erretm + rhoinv * 2. + abs(temp) * 3. + abs(tau) * dw; /* Test for convergence */ if (abs(w) <= eps * erretm) { goto L240; } if (w <= 0.) { sg2lb = max(sg2lb,tau); } else { sg2ub = min(sg2ub,tau); } /* Calculate the new step */ ++niter; if (! swtch3) { dtipsq = work[ip1] * delta[ip1]; dtisq = work[*i__] * delta[*i__]; if (orgati) { /* Computing 2nd power */ d__1 = z__[*i__] / dtisq; c__ = w - dtipsq * dw + delsq * (d__1 * d__1); } else { /* Computing 2nd power */ d__1 = z__[ip1] / dtipsq; c__ = w - dtisq * dw - delsq * (d__1 * d__1); } a = (dtipsq + dtisq) * w - dtipsq * dtisq * dw; b = dtipsq * dtisq * w; if (c__ == 0.) { if (a == 0.) { if (orgati) { a = z__[*i__] * z__[*i__] + dtipsq * dtipsq * (dpsi + dphi); } else { a = z__[ip1] * z__[ip1] + dtisq * dtisq * (dpsi + dphi); } } eta = b / a; } else if (a <= 0.) { eta = (a - sqrt((d__1 = a * a - b * 4. * c__, abs(d__1)))) / ( c__ * 2.); } else { eta = b * 2. / (a + sqrt((d__1 = a * a - b * 4. * c__, abs( d__1)))); } } else { /* Interpolation using THREE most relevant poles */ dtiim = work[iim1] * delta[iim1]; dtiip = work[iip1] * delta[iip1]; temp = rhoinv + psi + phi; if (orgati) { temp1 = z__[iim1] / dtiim; temp1 *= temp1; c__ = temp - dtiip * (dpsi + dphi) - (d__[iim1] - d__[iip1]) * (d__[iim1] + d__[iip1]) * temp1; zz[0] = z__[iim1] * z__[iim1]; if (dpsi < temp1) { zz[2] = dtiip * dtiip * dphi; } else { zz[2] = dtiip * dtiip * (dpsi - temp1 + dphi); } } else { temp1 = z__[iip1] / dtiip; temp1 *= temp1; c__ = temp - dtiim * (dpsi + dphi) - (d__[iip1] - d__[iim1]) * (d__[iim1] + d__[iip1]) * temp1; if (dphi < temp1) { zz[0] = dtiim * dtiim * dpsi; } else { zz[0] = dtiim * dtiim * (dpsi + (dphi - temp1)); } zz[2] = z__[iip1] * z__[iip1]; } zz[1] = z__[ii] * z__[ii]; dd[0] = dtiim; dd[1] = delta[ii] * work[ii]; dd[2] = dtiip; dlaed6_(&niter, &orgati, &c__, dd, zz, &w, &eta, info); if (*info != 0) { goto L240; } } /* Note, eta should be positive if w is negative, and eta should be negative otherwise. However, if for some reason caused by roundoff, eta*w > 0, we simply use one Newton step instead. This way will guarantee eta*w < 0. */ if (w * eta >= 0.) { eta = -w / dw; } if (orgati) { temp1 = work[*i__] * delta[*i__]; temp = eta - temp1; } else { temp1 = work[ip1] * delta[ip1]; temp = eta - temp1; } if ((temp > sg2ub) || (temp < sg2lb)) { if (w < 0.) { eta = (sg2ub - tau) / 2.; } else { eta = (sg2lb - tau) / 2.; } } tau += eta; eta /= *sigma + sqrt(*sigma * *sigma + eta); prew = w; *sigma += eta; i__1 = *n; for (j = 1; j <= i__1; ++j) { work[j] += eta; delta[j] -= eta; /* L170: */ } /* Evaluate PSI and the derivative DPSI */ dpsi = 0.; psi = 0.; erretm = 0.; i__1 = iim1; for (j = 1; j <= i__1; ++j) { temp = z__[j] / (work[j] * delta[j]); psi += z__[j] * temp; dpsi += temp * temp; erretm += psi; /* L180: */ } erretm = abs(erretm); /* Evaluate PHI and the derivative DPHI */ dphi = 0.; phi = 0.; i__1 = iip1; for (j = *n; j >= i__1; --j) { temp = z__[j] / (work[j] * delta[j]); phi += z__[j] * temp; dphi += temp * temp; erretm += phi; /* L190: */ } temp = z__[ii] / (work[ii] * delta[ii]); dw = dpsi + dphi + temp * temp; temp = z__[ii] * temp; w = rhoinv + phi + psi + temp; erretm = (phi - psi) * 8. + erretm + rhoinv * 2. + abs(temp) * 3. + abs(tau) * dw; if (w <= 0.) { sg2lb = max(sg2lb,tau); } else { sg2ub = min(sg2ub,tau); } swtch = FALSE_; if (orgati) { if (-w > abs(prew) / 10.) { swtch = TRUE_; } } else { if (w > abs(prew) / 10.) { swtch = TRUE_; } } /* Main loop to update the values of the array DELTA and WORK */ iter = niter + 1; for (niter = iter; niter <= 20; ++niter) { /* Test for convergence */ if (abs(w) <= eps * erretm) { goto L240; } /* Calculate the new step */ if (! swtch3) { dtipsq = work[ip1] * delta[ip1]; dtisq = work[*i__] * delta[*i__]; if (! swtch) { if (orgati) { /* Computing 2nd power */ d__1 = z__[*i__] / dtisq; c__ = w - dtipsq * dw + delsq * (d__1 * d__1); } else { /* Computing 2nd power */ d__1 = z__[ip1] / dtipsq; c__ = w - dtisq * dw - delsq * (d__1 * d__1); } } else { temp = z__[ii] / (work[ii] * delta[ii]); if (orgati) { dpsi += temp * temp; } else { dphi += temp * temp; } c__ = w - dtisq * dpsi - dtipsq * dphi; } a = (dtipsq + dtisq) * w - dtipsq * dtisq * dw; b = dtipsq * dtisq * w; if (c__ == 0.) { if (a == 0.) { if (! swtch) { if (orgati) { a = z__[*i__] * z__[*i__] + dtipsq * dtipsq * (dpsi + dphi); } else { a = z__[ip1] * z__[ip1] + dtisq * dtisq * ( dpsi + dphi); } } else { a = dtisq * dtisq * dpsi + dtipsq * dtipsq * dphi; } } eta = b / a; } else if (a <= 0.) { eta = (a - sqrt((d__1 = a * a - b * 4. * c__, abs(d__1)))) / (c__ * 2.); } else { eta = b * 2. / (a + sqrt((d__1 = a * a - b * 4. * c__, abs(d__1)))); } } else { /* Interpolation using THREE most relevant poles */ dtiim = work[iim1] * delta[iim1]; dtiip = work[iip1] * delta[iip1]; temp = rhoinv + psi + phi; if (swtch) { c__ = temp - dtiim * dpsi - dtiip * dphi; zz[0] = dtiim * dtiim * dpsi; zz[2] = dtiip * dtiip * dphi; } else { if (orgati) { temp1 = z__[iim1] / dtiim; temp1 *= temp1; temp2 = (d__[iim1] - d__[iip1]) * (d__[iim1] + d__[ iip1]) * temp1; c__ = temp - dtiip * (dpsi + dphi) - temp2; zz[0] = z__[iim1] * z__[iim1]; if (dpsi < temp1) { zz[2] = dtiip * dtiip * dphi; } else { zz[2] = dtiip * dtiip * (dpsi - temp1 + dphi); } } else { temp1 = z__[iip1] / dtiip; temp1 *= temp1; temp2 = (d__[iip1] - d__[iim1]) * (d__[iim1] + d__[ iip1]) * temp1; c__ = temp - dtiim * (dpsi + dphi) - temp2; if (dphi < temp1) { zz[0] = dtiim * dtiim * dpsi; } else { zz[0] = dtiim * dtiim * (dpsi + (dphi - temp1)); } zz[2] = z__[iip1] * z__[iip1]; } } dd[0] = dtiim; dd[1] = delta[ii] * work[ii]; dd[2] = dtiip; dlaed6_(&niter, &orgati, &c__, dd, zz, &w, &eta, info); if (*info != 0) { goto L240; } } /* Note, eta should be positive if w is negative, and eta should be negative otherwise. However, if for some reason caused by roundoff, eta*w > 0, we simply use one Newton step instead. This way will guarantee eta*w < 0. */ if (w * eta >= 0.) { eta = -w / dw; } if (orgati) { temp1 = work[*i__] * delta[*i__]; temp = eta - temp1; } else { temp1 = work[ip1] * delta[ip1]; temp = eta - temp1; } if ((temp > sg2ub) || (temp < sg2lb)) { if (w < 0.) { eta = (sg2ub - tau) / 2.; } else { eta = (sg2lb - tau) / 2.; } } tau += eta; eta /= *sigma + sqrt(*sigma * *sigma + eta); *sigma += eta; i__1 = *n; for (j = 1; j <= i__1; ++j) { work[j] += eta; delta[j] -= eta; /* L200: */ } prew = w; /* Evaluate PSI and the derivative DPSI */ dpsi = 0.; psi = 0.; erretm = 0.; i__1 = iim1; for (j = 1; j <= i__1; ++j) { temp = z__[j] / (work[j] * delta[j]); psi += z__[j] * temp; dpsi += temp * temp; erretm += psi; /* L210: */ } erretm = abs(erretm); /* Evaluate PHI and the derivative DPHI */ dphi = 0.; phi = 0.; i__1 = iip1; for (j = *n; j >= i__1; --j) { temp = z__[j] / (work[j] * delta[j]); phi += z__[j] * temp; dphi += temp * temp; erretm += phi; /* L220: */ } temp = z__[ii] / (work[ii] * delta[ii]); dw = dpsi + dphi + temp * temp; temp = z__[ii] * temp; w = rhoinv + phi + psi + temp; erretm = (phi - psi) * 8. + erretm + rhoinv * 2. + abs(temp) * 3. + abs(tau) * dw; if (w * prew > 0. && abs(w) > abs(prew) / 10.) { swtch = ! swtch; } if (w <= 0.) { sg2lb = max(sg2lb,tau); } else { sg2ub = min(sg2ub,tau); } /* L230: */ } /* Return with INFO = 1, NITER = MAXIT and not converged */ *info = 1; } L240: return 0; /* End of DLASD4 */ } /* dlasd4_ */ /* Subroutine */ int dlasd5_(integer *i__, doublereal *d__, doublereal *z__, doublereal *delta, doublereal *rho, doublereal *dsigma, doublereal * work) { /* System generated locals */ doublereal d__1; /* Builtin functions */ double sqrt(doublereal); /* Local variables */ static doublereal b, c__, w, del, tau, delsq; /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Oak Ridge National Lab, Argonne National Lab, Courant Institute, NAG Ltd., and Rice University June 30, 1999 Purpose ======= This subroutine computes the square root of the I-th eigenvalue of a positive symmetric rank-one modification of a 2-by-2 diagonal matrix diag( D ) * diag( D ) + RHO * Z * transpose(Z) . The diagonal entries in the array D are assumed to satisfy 0 <= D(i) < D(j) for i < j . We also assume RHO > 0 and that the Euclidean norm of the vector Z is one. Arguments ========= I (input) INTEGER The index of the eigenvalue to be computed. I = 1 or I = 2. D (input) DOUBLE PRECISION array, dimension ( 2 ) The original eigenvalues. We assume 0 <= D(1) < D(2). Z (input) DOUBLE PRECISION array, dimension ( 2 ) The components of the updating vector. DELTA (output) DOUBLE PRECISION array, dimension ( 2 ) Contains (D(j) - lambda_I) in its j-th component. The vector DELTA contains the information necessary to construct the eigenvectors. RHO (input) DOUBLE PRECISION The scalar in the symmetric updating formula. DSIGMA (output) DOUBLE PRECISION The computed lambda_I, the I-th updated eigenvalue. WORK (workspace) DOUBLE PRECISION array, dimension ( 2 ) WORK contains (D(j) + sigma_I) in its j-th component. Further Details =============== Based on contributions by Ren-Cang Li, Computer Science Division, University of California at Berkeley, USA ===================================================================== */ /* Parameter adjustments */ --work; --delta; --z__; --d__; /* Function Body */ del = d__[2] - d__[1]; delsq = del * (d__[2] + d__[1]); if (*i__ == 1) { w = *rho * 4. * (z__[2] * z__[2] / (d__[1] + d__[2] * 3.) - z__[1] * z__[1] / (d__[1] * 3. + d__[2])) / del + 1.; if (w > 0.) { b = delsq + *rho * (z__[1] * z__[1] + z__[2] * z__[2]); c__ = *rho * z__[1] * z__[1] * delsq; /* B > ZERO, always The following TAU is DSIGMA * DSIGMA - D( 1 ) * D( 1 ) */ tau = c__ * 2. / (b + sqrt((d__1 = b * b - c__ * 4., abs(d__1)))); /* The following TAU is DSIGMA - D( 1 ) */ tau /= d__[1] + sqrt(d__[1] * d__[1] + tau); *dsigma = d__[1] + tau; delta[1] = -tau; delta[2] = del - tau; work[1] = d__[1] * 2. + tau; work[2] = d__[1] + tau + d__[2]; /* DELTA( 1 ) = -Z( 1 ) / TAU DELTA( 2 ) = Z( 2 ) / ( DEL-TAU ) */ } else { b = -delsq + *rho * (z__[1] * z__[1] + z__[2] * z__[2]); c__ = *rho * z__[2] * z__[2] * delsq; /* The following TAU is DSIGMA * DSIGMA - D( 2 ) * D( 2 ) */ if (b > 0.) { tau = c__ * -2. / (b + sqrt(b * b + c__ * 4.)); } else { tau = (b - sqrt(b * b + c__ * 4.)) / 2.; } /* The following TAU is DSIGMA - D( 2 ) */ tau /= d__[2] + sqrt((d__1 = d__[2] * d__[2] + tau, abs(d__1))); *dsigma = d__[2] + tau; delta[1] = -(del + tau); delta[2] = -tau; work[1] = d__[1] + tau + d__[2]; work[2] = d__[2] * 2. + tau; /* DELTA( 1 ) = -Z( 1 ) / ( DEL+TAU ) DELTA( 2 ) = -Z( 2 ) / TAU */ } /* TEMP = SQRT( DELTA( 1 )*DELTA( 1 )+DELTA( 2 )*DELTA( 2 ) ) DELTA( 1 ) = DELTA( 1 ) / TEMP DELTA( 2 ) = DELTA( 2 ) / TEMP */ } else { /* Now I=2 */ b = -delsq + *rho * (z__[1] * z__[1] + z__[2] * z__[2]); c__ = *rho * z__[2] * z__[2] * delsq; /* The following TAU is DSIGMA * DSIGMA - D( 2 ) * D( 2 ) */ if (b > 0.) { tau = (b + sqrt(b * b + c__ * 4.)) / 2.; } else { tau = c__ * 2. / (-b + sqrt(b * b + c__ * 4.)); } /* The following TAU is DSIGMA - D( 2 ) */ tau /= d__[2] + sqrt(d__[2] * d__[2] + tau); *dsigma = d__[2] + tau; delta[1] = -(del + tau); delta[2] = -tau; work[1] = d__[1] + tau + d__[2]; work[2] = d__[2] * 2. + tau; /* DELTA( 1 ) = -Z( 1 ) / ( DEL+TAU ) DELTA( 2 ) = -Z( 2 ) / TAU TEMP = SQRT( DELTA( 1 )*DELTA( 1 )+DELTA( 2 )*DELTA( 2 ) ) DELTA( 1 ) = DELTA( 1 ) / TEMP DELTA( 2 ) = DELTA( 2 ) / TEMP */ } return 0; /* End of DLASD5 */ } /* dlasd5_ */ /* Subroutine */ int dlasd6_(integer *icompq, integer *nl, integer *nr, integer *sqre, doublereal *d__, doublereal *vf, doublereal *vl, doublereal *alpha, doublereal *beta, integer *idxq, integer *perm, integer *givptr, integer *givcol, integer *ldgcol, doublereal *givnum, integer *ldgnum, doublereal *poles, doublereal *difl, doublereal * difr, doublereal *z__, integer *k, doublereal *c__, doublereal *s, doublereal *work, integer *iwork, integer *info) { /* System generated locals */ integer givcol_dim1, givcol_offset, givnum_dim1, givnum_offset, poles_dim1, poles_offset, i__1; doublereal d__1, d__2; /* Local variables */ static integer i__, m, n, n1, n2, iw, idx, idxc, idxp, ivfw, ivlw; extern /* Subroutine */ int dcopy_(integer *, doublereal *, integer *, doublereal *, integer *), dlasd7_(integer *, integer *, integer *, integer *, integer *, doublereal *, doublereal *, doublereal *, doublereal *, doublereal *, doublereal *, doublereal *, doublereal *, doublereal *, doublereal *, integer *, integer *, integer *, integer *, integer *, integer *, integer *, doublereal *, integer *, doublereal *, doublereal *, integer *), dlasd8_( integer *, integer *, doublereal *, doublereal *, doublereal *, doublereal *, doublereal *, doublereal *, integer *, doublereal *, doublereal *, integer *), dlascl_(char *, integer *, integer *, doublereal *, doublereal *, integer *, integer *, doublereal *, integer *, integer *), dlamrg_(integer *, integer *, doublereal *, integer *, integer *, integer *); static integer isigma; extern /* Subroutine */ int xerbla_(char *, integer *); static doublereal orgnrm; /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= DLASD6 computes the SVD of an updated upper bidiagonal matrix B obtained by merging two smaller ones by appending a row. This routine is used only for the problem which requires all singular values and optionally singular vector matrices in factored form. B is an N-by-M matrix with N = NL + NR + 1 and M = N + SQRE. A related subroutine, DLASD1, handles the case in which all singular values and singular vectors of the bidiagonal matrix are desired. DLASD6 computes the SVD as follows: ( D1(in) 0 0 0 ) B = U(in) * ( Z1' a Z2' b ) * VT(in) ( 0 0 D2(in) 0 ) = U(out) * ( D(out) 0) * VT(out) where Z' = (Z1' a Z2' b) = u' VT', and u is a vector of dimension M with ALPHA and BETA in the NL+1 and NL+2 th entries and zeros elsewhere; and the entry b is empty if SQRE = 0. The singular values of B can be computed using D1, D2, the first components of all the right singular vectors of the lower block, and the last components of all the right singular vectors of the upper block. These components are stored and updated in VF and VL, respectively, in DLASD6. Hence U and VT are not explicitly referenced. The singular values are stored in D. The algorithm consists of two stages: The first stage consists of deflating the size of the problem when there are multiple singular values or if there is a zero in the Z vector. For each such occurence the dimension of the secular equation problem is reduced by one. This stage is performed by the routine DLASD7. The second stage consists of calculating the updated singular values. This is done by finding the roots of the secular equation via the routine DLASD4 (as called by DLASD8). This routine also updates VF and VL and computes the distances between the updated singular values and the old singular values. DLASD6 is called from DLASDA. Arguments ========= ICOMPQ (input) INTEGER Specifies whether singular vectors are to be computed in factored form: = 0: Compute singular values only. = 1: Compute singular vectors in factored form as well. NL (input) INTEGER The row dimension of the upper block. NL >= 1. NR (input) INTEGER The row dimension of the lower block. NR >= 1. SQRE (input) INTEGER = 0: the lower block is an NR-by-NR square matrix. = 1: the lower block is an NR-by-(NR+1) rectangular matrix. The bidiagonal matrix has row dimension N = NL + NR + 1, and column dimension M = N + SQRE. D (input/output) DOUBLE PRECISION array, dimension ( NL+NR+1 ). On entry D(1:NL,1:NL) contains the singular values of the upper block, and D(NL+2:N) contains the singular values of the lower block. On exit D(1:N) contains the singular values of the modified matrix. VF (input/output) DOUBLE PRECISION array, dimension ( M ) On entry, VF(1:NL+1) contains the first components of all right singular vectors of the upper block; and VF(NL+2:M) contains the first components of all right singular vectors of the lower block. On exit, VF contains the first components of all right singular vectors of the bidiagonal matrix. VL (input/output) DOUBLE PRECISION array, dimension ( M ) On entry, VL(1:NL+1) contains the last components of all right singular vectors of the upper block; and VL(NL+2:M) contains the last components of all right singular vectors of the lower block. On exit, VL contains the last components of all right singular vectors of the bidiagonal matrix. ALPHA (input) DOUBLE PRECISION Contains the diagonal element associated with the added row. BETA (input) DOUBLE PRECISION Contains the off-diagonal element associated with the added row. IDXQ (output) INTEGER array, dimension ( N ) This contains the permutation which will reintegrate the subproblem just solved back into sorted order, i.e. D( IDXQ( I = 1, N ) ) will be in ascending order. PERM (output) INTEGER array, dimension ( N ) The permutations (from deflation and sorting) to be applied to each block. Not referenced if ICOMPQ = 0. GIVPTR (output) INTEGER The number of Givens rotations which took place in this subproblem. Not referenced if ICOMPQ = 0. GIVCOL (output) INTEGER array, dimension ( LDGCOL, 2 ) Each pair of numbers indicates a pair of columns to take place in a Givens rotation. Not referenced if ICOMPQ = 0. LDGCOL (input) INTEGER leading dimension of GIVCOL, must be at least N. GIVNUM (output) DOUBLE PRECISION array, dimension ( LDGNUM, 2 ) Each number indicates the C or S value to be used in the corresponding Givens rotation. Not referenced if ICOMPQ = 0. LDGNUM (input) INTEGER The leading dimension of GIVNUM and POLES, must be at least N. POLES (output) DOUBLE PRECISION array, dimension ( LDGNUM, 2 ) On exit, POLES(1,*) is an array containing the new singular values obtained from solving the secular equation, and POLES(2,*) is an array containing the poles in the secular equation. Not referenced if ICOMPQ = 0. DIFL (output) DOUBLE PRECISION array, dimension ( N ) On exit, DIFL(I) is the distance between I-th updated (undeflated) singular value and the I-th (undeflated) old singular value. DIFR (output) DOUBLE PRECISION array, dimension ( LDGNUM, 2 ) if ICOMPQ = 1 and dimension ( N ) if ICOMPQ = 0. On exit, DIFR(I, 1) is the distance between I-th updated (undeflated) singular value and the I+1-th (undeflated) old singular value. If ICOMPQ = 1, DIFR(1:K,2) is an array containing the normalizing factors for the right singular vector matrix. See DLASD8 for details on DIFL and DIFR. Z (output) DOUBLE PRECISION array, dimension ( M ) The first elements of this array contain the components of the deflation-adjusted updating row vector. K (output) INTEGER Contains the dimension of the non-deflated matrix, This is the order of the related secular equation. 1 <= K <=N. C (output) DOUBLE PRECISION C contains garbage if SQRE =0 and the C-value of a Givens rotation related to the right null space if SQRE = 1. S (output) DOUBLE PRECISION S contains garbage if SQRE =0 and the S-value of a Givens rotation related to the right null space if SQRE = 1. WORK (workspace) DOUBLE PRECISION array, dimension ( 4 * M ) IWORK (workspace) INTEGER array, dimension ( 3 * N ) INFO (output) INTEGER = 0: successful exit. < 0: if INFO = -i, the i-th argument had an illegal value. > 0: if INFO = 1, an singular value did not converge Further Details =============== Based on contributions by Ming Gu and Huan Ren, Computer Science Division, University of California at Berkeley, USA ===================================================================== Test the input parameters. */ /* Parameter adjustments */ --d__; --vf; --vl; --idxq; --perm; givcol_dim1 = *ldgcol; givcol_offset = 1 + givcol_dim1; givcol -= givcol_offset; poles_dim1 = *ldgnum; poles_offset = 1 + poles_dim1; poles -= poles_offset; givnum_dim1 = *ldgnum; givnum_offset = 1 + givnum_dim1; givnum -= givnum_offset; --difl; --difr; --z__; --work; --iwork; /* Function Body */ *info = 0; n = *nl + *nr + 1; m = n + *sqre; if ((*icompq < 0) || (*icompq > 1)) { *info = -1; } else if (*nl < 1) { *info = -2; } else if (*nr < 1) { *info = -3; } else if ((*sqre < 0) || (*sqre > 1)) { *info = -4; } else if (*ldgcol < n) { *info = -14; } else if (*ldgnum < n) { *info = -16; } if (*info != 0) { i__1 = -(*info); xerbla_("DLASD6", &i__1); return 0; } /* The following values are for bookkeeping purposes only. They are integer pointers which indicate the portion of the workspace used by a particular array in DLASD7 and DLASD8. */ isigma = 1; iw = isigma + n; ivfw = iw + m; ivlw = ivfw + m; idx = 1; idxc = idx + n; idxp = idxc + n; /* Scale. Computing MAX */ d__1 = abs(*alpha), d__2 = abs(*beta); orgnrm = max(d__1,d__2); d__[*nl + 1] = 0.; i__1 = n; for (i__ = 1; i__ <= i__1; ++i__) { if ((d__1 = d__[i__], abs(d__1)) > orgnrm) { orgnrm = (d__1 = d__[i__], abs(d__1)); } /* L10: */ } dlascl_("G", &c__0, &c__0, &orgnrm, &c_b2865, &n, &c__1, &d__[1], &n, info); *alpha /= orgnrm; *beta /= orgnrm; /* Sort and Deflate singular values. */ dlasd7_(icompq, nl, nr, sqre, k, &d__[1], &z__[1], &work[iw], &vf[1], & work[ivfw], &vl[1], &work[ivlw], alpha, beta, &work[isigma], & iwork[idx], &iwork[idxp], &idxq[1], &perm[1], givptr, &givcol[ givcol_offset], ldgcol, &givnum[givnum_offset], ldgnum, c__, s, info); /* Solve Secular Equation, compute DIFL, DIFR, and update VF, VL. */ dlasd8_(icompq, k, &d__[1], &z__[1], &vf[1], &vl[1], &difl[1], &difr[1], ldgnum, &work[isigma], &work[iw], info); /* Save the poles if ICOMPQ = 1. */ if (*icompq == 1) { dcopy_(k, &d__[1], &c__1, &poles[poles_dim1 + 1], &c__1); dcopy_(k, &work[isigma], &c__1, &poles[((poles_dim1) << (1)) + 1], & c__1); } /* Unscale. */ dlascl_("G", &c__0, &c__0, &c_b2865, &orgnrm, &n, &c__1, &d__[1], &n, info); /* Prepare the IDXQ sorting permutation. */ n1 = *k; n2 = n - *k; dlamrg_(&n1, &n2, &d__[1], &c__1, &c_n1, &idxq[1]); return 0; /* End of DLASD6 */ } /* dlasd6_ */ /* Subroutine */ int dlasd7_(integer *icompq, integer *nl, integer *nr, integer *sqre, integer *k, doublereal *d__, doublereal *z__, doublereal *zw, doublereal *vf, doublereal *vfw, doublereal *vl, doublereal *vlw, doublereal *alpha, doublereal *beta, doublereal * dsigma, integer *idx, integer *idxp, integer *idxq, integer *perm, integer *givptr, integer *givcol, integer *ldgcol, doublereal *givnum, integer *ldgnum, doublereal *c__, doublereal *s, integer *info) { /* System generated locals */ integer givcol_dim1, givcol_offset, givnum_dim1, givnum_offset, i__1; doublereal d__1, d__2; /* Local variables */ static integer i__, j, m, n, k2; static doublereal z1; static integer jp; static doublereal eps, tau, tol; static integer nlp1, nlp2, idxi, idxj; extern /* Subroutine */ int drot_(integer *, doublereal *, integer *, doublereal *, integer *, doublereal *, doublereal *); static integer idxjp; extern /* Subroutine */ int dcopy_(integer *, doublereal *, integer *, doublereal *, integer *); static integer jprev; extern /* Subroutine */ int dlamrg_(integer *, integer *, doublereal *, integer *, integer *, integer *), xerbla_(char *, integer *); static doublereal hlftol; /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Oak Ridge National Lab, Argonne National Lab, Courant Institute, NAG Ltd., and Rice University June 30, 1999 Purpose ======= DLASD7 merges the two sets of singular values together into a single sorted set. Then it tries to deflate the size of the problem. There are two ways in which deflation can occur: when two or more singular values are close together or if there is a tiny entry in the Z vector. For each such occurrence the order of the related secular equation problem is reduced by one. DLASD7 is called from DLASD6. Arguments ========= ICOMPQ (input) INTEGER Specifies whether singular vectors are to be computed in compact form, as follows: = 0: Compute singular values only. = 1: Compute singular vectors of upper bidiagonal matrix in compact form. NL (input) INTEGER The row dimension of the upper block. NL >= 1. NR (input) INTEGER The row dimension of the lower block. NR >= 1. SQRE (input) INTEGER = 0: the lower block is an NR-by-NR square matrix. = 1: the lower block is an NR-by-(NR+1) rectangular matrix. The bidiagonal matrix has N = NL + NR + 1 rows and M = N + SQRE >= N columns. K (output) INTEGER Contains the dimension of the non-deflated matrix, this is the order of the related secular equation. 1 <= K <=N. D (input/output) DOUBLE PRECISION array, dimension ( N ) On entry D contains the singular values of the two submatrices to be combined. On exit D contains the trailing (N-K) updated singular values (those which were deflated) sorted into increasing order. Z (output) DOUBLE PRECISION array, dimension ( M ) On exit Z contains the updating row vector in the secular equation. ZW (workspace) DOUBLE PRECISION array, dimension ( M ) Workspace for Z. VF (input/output) DOUBLE PRECISION array, dimension ( M ) On entry, VF(1:NL+1) contains the first components of all right singular vectors of the upper block; and VF(NL+2:M) contains the first components of all right singular vectors of the lower block. On exit, VF contains the first components of all right singular vectors of the bidiagonal matrix. VFW (workspace) DOUBLE PRECISION array, dimension ( M ) Workspace for VF. VL (input/output) DOUBLE PRECISION array, dimension ( M ) On entry, VL(1:NL+1) contains the last components of all right singular vectors of the upper block; and VL(NL+2:M) contains the last components of all right singular vectors of the lower block. On exit, VL contains the last components of all right singular vectors of the bidiagonal matrix. VLW (workspace) DOUBLE PRECISION array, dimension ( M ) Workspace for VL. ALPHA (input) DOUBLE PRECISION Contains the diagonal element associated with the added row. BETA (input) DOUBLE PRECISION Contains the off-diagonal element associated with the added row. DSIGMA (output) DOUBLE PRECISION array, dimension ( N ) Contains a copy of the diagonal elements (K-1 singular values and one zero) in the secular equation. IDX (workspace) INTEGER array, dimension ( N ) This will contain the permutation used to sort the contents of D into ascending order. IDXP (workspace) INTEGER array, dimension ( N ) This will contain the permutation used to place deflated values of D at the end of the array. On output IDXP(2:K) points to the nondeflated D-values and IDXP(K+1:N) points to the deflated singular values. IDXQ (input) INTEGER array, dimension ( N ) This contains the permutation which separately sorts the two sub-problems in D into ascending order. Note that entries in the first half of this permutation must first be moved one position backward; and entries in the second half must first have NL+1 added to their values. PERM (output) INTEGER array, dimension ( N ) The permutations (from deflation and sorting) to be applied to each singular block. Not referenced if ICOMPQ = 0. GIVPTR (output) INTEGER The number of Givens rotations which took place in this subproblem. Not referenced if ICOMPQ = 0. GIVCOL (output) INTEGER array, dimension ( LDGCOL, 2 ) Each pair of numbers indicates a pair of columns to take place in a Givens rotation. Not referenced if ICOMPQ = 0. LDGCOL (input) INTEGER The leading dimension of GIVCOL, must be at least N. GIVNUM (output) DOUBLE PRECISION array, dimension ( LDGNUM, 2 ) Each number indicates the C or S value to be used in the corresponding Givens rotation. Not referenced if ICOMPQ = 0. LDGNUM (input) INTEGER The leading dimension of GIVNUM, must be at least N. C (output) DOUBLE PRECISION C contains garbage if SQRE =0 and the C-value of a Givens rotation related to the right null space if SQRE = 1. S (output) DOUBLE PRECISION S contains garbage if SQRE =0 and the S-value of a Givens rotation related to the right null space if SQRE = 1. INFO (output) INTEGER = 0: successful exit. < 0: if INFO = -i, the i-th argument had an illegal value. Further Details =============== Based on contributions by Ming Gu and Huan Ren, Computer Science Division, University of California at Berkeley, USA ===================================================================== Test the input parameters. */ /* Parameter adjustments */ --d__; --z__; --zw; --vf; --vfw; --vl; --vlw; --dsigma; --idx; --idxp; --idxq; --perm; givcol_dim1 = *ldgcol; givcol_offset = 1 + givcol_dim1; givcol -= givcol_offset; givnum_dim1 = *ldgnum; givnum_offset = 1 + givnum_dim1; givnum -= givnum_offset; /* Function Body */ *info = 0; n = *nl + *nr + 1; m = n + *sqre; if ((*icompq < 0) || (*icompq > 1)) { *info = -1; } else if (*nl < 1) { *info = -2; } else if (*nr < 1) { *info = -3; } else if ((*sqre < 0) || (*sqre > 1)) { *info = -4; } else if (*ldgcol < n) { *info = -22; } else if (*ldgnum < n) { *info = -24; } if (*info != 0) { i__1 = -(*info); xerbla_("DLASD7", &i__1); return 0; } nlp1 = *nl + 1; nlp2 = *nl + 2; if (*icompq == 1) { *givptr = 0; } /* Generate the first part of the vector Z and move the singular values in the first part of D one position backward. */ z1 = *alpha * vl[nlp1]; vl[nlp1] = 0.; tau = vf[nlp1]; for (i__ = *nl; i__ >= 1; --i__) { z__[i__ + 1] = *alpha * vl[i__]; vl[i__] = 0.; vf[i__ + 1] = vf[i__]; d__[i__ + 1] = d__[i__]; idxq[i__ + 1] = idxq[i__] + 1; /* L10: */ } vf[1] = tau; /* Generate the second part of the vector Z. */ i__1 = m; for (i__ = nlp2; i__ <= i__1; ++i__) { z__[i__] = *beta * vf[i__]; vf[i__] = 0.; /* L20: */ } /* Sort the singular values into increasing order */ i__1 = n; for (i__ = nlp2; i__ <= i__1; ++i__) { idxq[i__] += nlp1; /* L30: */ } /* DSIGMA, IDXC, IDXC, and ZW are used as storage space. */ i__1 = n; for (i__ = 2; i__ <= i__1; ++i__) { dsigma[i__] = d__[idxq[i__]]; zw[i__] = z__[idxq[i__]]; vfw[i__] = vf[idxq[i__]]; vlw[i__] = vl[idxq[i__]]; /* L40: */ } dlamrg_(nl, nr, &dsigma[2], &c__1, &c__1, &idx[2]); i__1 = n; for (i__ = 2; i__ <= i__1; ++i__) { idxi = idx[i__] + 1; d__[i__] = dsigma[idxi]; z__[i__] = zw[idxi]; vf[i__] = vfw[idxi]; vl[i__] = vlw[idxi]; /* L50: */ } /* Calculate the allowable deflation tolerence */ eps = EPSILON; /* Computing MAX */ d__1 = abs(*alpha), d__2 = abs(*beta); tol = max(d__1,d__2); /* Computing MAX */ d__2 = (d__1 = d__[n], abs(d__1)); tol = eps * 64. * max(d__2,tol); /* There are 2 kinds of deflation -- first a value in the z-vector is small, second two (or more) singular values are very close together (their difference is small). If the value in the z-vector is small, we simply permute the array so that the corresponding singular value is moved to the end. If two values in the D-vector are close, we perform a two-sided rotation designed to make one of the corresponding z-vector entries zero, and then permute the array so that the deflated singular value is moved to the end. If there are multiple singular values then the problem deflates. Here the number of equal singular values are found. As each equal singular value is found, an elementary reflector is computed to rotate the corresponding singular subspace so that the corresponding components of Z are zero in this new basis. */ *k = 1; k2 = n + 1; i__1 = n; for (j = 2; j <= i__1; ++j) { if ((d__1 = z__[j], abs(d__1)) <= tol) { /* Deflate due to small z component. */ --k2; idxp[k2] = j; if (j == n) { goto L100; } } else { jprev = j; goto L70; } /* L60: */ } L70: j = jprev; L80: ++j; if (j > n) { goto L90; } if ((d__1 = z__[j], abs(d__1)) <= tol) { /* Deflate due to small z component. */ --k2; idxp[k2] = j; } else { /* Check if singular values are close enough to allow deflation. */ if ((d__1 = d__[j] - d__[jprev], abs(d__1)) <= tol) { /* Deflation is possible. */ *s = z__[jprev]; *c__ = z__[j]; /* Find sqrt(a**2+b**2) without overflow or destructive underflow. */ tau = dlapy2_(c__, s); z__[j] = tau; z__[jprev] = 0.; *c__ /= tau; *s = -(*s) / tau; /* Record the appropriate Givens rotation */ if (*icompq == 1) { ++(*givptr); idxjp = idxq[idx[jprev] + 1]; idxj = idxq[idx[j] + 1]; if (idxjp <= nlp1) { --idxjp; } if (idxj <= nlp1) { --idxj; } givcol[*givptr + ((givcol_dim1) << (1))] = idxjp; givcol[*givptr + givcol_dim1] = idxj; givnum[*givptr + ((givnum_dim1) << (1))] = *c__; givnum[*givptr + givnum_dim1] = *s; } drot_(&c__1, &vf[jprev], &c__1, &vf[j], &c__1, c__, s); drot_(&c__1, &vl[jprev], &c__1, &vl[j], &c__1, c__, s); --k2; idxp[k2] = jprev; jprev = j; } else { ++(*k); zw[*k] = z__[jprev]; dsigma[*k] = d__[jprev]; idxp[*k] = jprev; jprev = j; } } goto L80; L90: /* Record the last singular value. */ ++(*k); zw[*k] = z__[jprev]; dsigma[*k] = d__[jprev]; idxp[*k] = jprev; L100: /* Sort the singular values into DSIGMA. The singular values which were not deflated go into the first K slots of DSIGMA, except that DSIGMA(1) is treated separately. */ i__1 = n; for (j = 2; j <= i__1; ++j) { jp = idxp[j]; dsigma[j] = d__[jp]; vfw[j] = vf[jp]; vlw[j] = vl[jp]; /* L110: */ } if (*icompq == 1) { i__1 = n; for (j = 2; j <= i__1; ++j) { jp = idxp[j]; perm[j] = idxq[idx[jp] + 1]; if (perm[j] <= nlp1) { --perm[j]; } /* L120: */ } } /* The deflated singular values go back into the last N - K slots of D. */ i__1 = n - *k; dcopy_(&i__1, &dsigma[*k + 1], &c__1, &d__[*k + 1], &c__1); /* Determine DSIGMA(1), DSIGMA(2), Z(1), VF(1), VL(1), VF(M), and VL(M). */ dsigma[1] = 0.; hlftol = tol / 2.; if (abs(dsigma[2]) <= hlftol) { dsigma[2] = hlftol; } if (m > n) { z__[1] = dlapy2_(&z1, &z__[m]); if (z__[1] <= tol) { *c__ = 1.; *s = 0.; z__[1] = tol; } else { *c__ = z1 / z__[1]; *s = -z__[m] / z__[1]; } drot_(&c__1, &vf[m], &c__1, &vf[1], &c__1, c__, s); drot_(&c__1, &vl[m], &c__1, &vl[1], &c__1, c__, s); } else { if (abs(z1) <= tol) { z__[1] = tol; } else { z__[1] = z1; } } /* Restore Z, VF, and VL. */ i__1 = *k - 1; dcopy_(&i__1, &zw[2], &c__1, &z__[2], &c__1); i__1 = n - 1; dcopy_(&i__1, &vfw[2], &c__1, &vf[2], &c__1); i__1 = n - 1; dcopy_(&i__1, &vlw[2], &c__1, &vl[2], &c__1); return 0; /* End of DLASD7 */ } /* dlasd7_ */ /* Subroutine */ int dlasd8_(integer *icompq, integer *k, doublereal *d__, doublereal *z__, doublereal *vf, doublereal *vl, doublereal *difl, doublereal *difr, integer *lddifr, doublereal *dsigma, doublereal * work, integer *info) { /* System generated locals */ integer difr_dim1, difr_offset, i__1, i__2; doublereal d__1, d__2; /* Builtin functions */ double sqrt(doublereal), d_sign(doublereal *, doublereal *); /* Local variables */ static integer i__, j; static doublereal dj, rho; static integer iwk1, iwk2, iwk3; extern doublereal ddot_(integer *, doublereal *, integer *, doublereal *, integer *); static doublereal temp; extern doublereal dnrm2_(integer *, doublereal *, integer *); static integer iwk2i, iwk3i; static doublereal diflj, difrj, dsigj; extern /* Subroutine */ int dcopy_(integer *, doublereal *, integer *, doublereal *, integer *); extern doublereal dlamc3_(doublereal *, doublereal *); extern /* Subroutine */ int dlasd4_(integer *, integer *, doublereal *, doublereal *, doublereal *, doublereal *, doublereal *, doublereal *, integer *), dlascl_(char *, integer *, integer *, doublereal *, doublereal *, integer *, integer *, doublereal *, integer *, integer *), dlaset_(char *, integer *, integer *, doublereal *, doublereal *, doublereal *, integer *), xerbla_(char *, integer *); static doublereal dsigjp; /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Oak Ridge National Lab, Argonne National Lab, Courant Institute, NAG Ltd., and Rice University June 30, 1999 Purpose ======= DLASD8 finds the square roots of the roots of the secular equation, as defined by the values in DSIGMA and Z. It makes the appropriate calls to DLASD4, and stores, for each element in D, the distance to its two nearest poles (elements in DSIGMA). It also updates the arrays VF and VL, the first and last components of all the right singular vectors of the original bidiagonal matrix. DLASD8 is called from DLASD6. Arguments ========= ICOMPQ (input) INTEGER Specifies whether singular vectors are to be computed in factored form in the calling routine: = 0: Compute singular values only. = 1: Compute singular vectors in factored form as well. K (input) INTEGER The number of terms in the rational function to be solved by DLASD4. K >= 1. D (output) DOUBLE PRECISION array, dimension ( K ) On output, D contains the updated singular values. Z (input) DOUBLE PRECISION array, dimension ( K ) The first K elements of this array contain the components of the deflation-adjusted updating row vector. VF (input/output) DOUBLE PRECISION array, dimension ( K ) On entry, VF contains information passed through DBEDE8. On exit, VF contains the first K components of the first components of all right singular vectors of the bidiagonal matrix. VL (input/output) DOUBLE PRECISION array, dimension ( K ) On entry, VL contains information passed through DBEDE8. On exit, VL contains the first K components of the last components of all right singular vectors of the bidiagonal matrix. DIFL (output) DOUBLE PRECISION array, dimension ( K ) On exit, DIFL(I) = D(I) - DSIGMA(I). DIFR (output) DOUBLE PRECISION array, dimension ( LDDIFR, 2 ) if ICOMPQ = 1 and dimension ( K ) if ICOMPQ = 0. On exit, DIFR(I,1) = D(I) - DSIGMA(I+1), DIFR(K,1) is not defined and will not be referenced. If ICOMPQ = 1, DIFR(1:K,2) is an array containing the normalizing factors for the right singular vector matrix. LDDIFR (input) INTEGER The leading dimension of DIFR, must be at least K. DSIGMA (input) DOUBLE PRECISION array, dimension ( K ) The first K elements of this array contain the old roots of the deflated updating problem. These are the poles of the secular equation. WORK (workspace) DOUBLE PRECISION array, dimension at least 3 * K INFO (output) INTEGER = 0: successful exit. < 0: if INFO = -i, the i-th argument had an illegal value. > 0: if INFO = 1, an singular value did not converge Further Details =============== Based on contributions by Ming Gu and Huan Ren, Computer Science Division, University of California at Berkeley, USA ===================================================================== Test the input parameters. */ /* Parameter adjustments */ --d__; --z__; --vf; --vl; --difl; difr_dim1 = *lddifr; difr_offset = 1 + difr_dim1; difr -= difr_offset; --dsigma; --work; /* Function Body */ *info = 0; if ((*icompq < 0) || (*icompq > 1)) { *info = -1; } else if (*k < 1) { *info = -2; } else if (*lddifr < *k) { *info = -9; } if (*info != 0) { i__1 = -(*info); xerbla_("DLASD8", &i__1); return 0; } /* Quick return if possible */ if (*k == 1) { d__[1] = abs(z__[1]); difl[1] = d__[1]; if (*icompq == 1) { difl[2] = 1.; difr[((difr_dim1) << (1)) + 1] = 1.; } return 0; } /* Modify values DSIGMA(i) to make sure all DSIGMA(i)-DSIGMA(j) can be computed with high relative accuracy (barring over/underflow). This is a problem on machines without a guard digit in add/subtract (Cray XMP, Cray YMP, Cray C 90 and Cray 2). The following code replaces DSIGMA(I) by 2*DSIGMA(I)-DSIGMA(I), which on any of these machines zeros out the bottommost bit of DSIGMA(I) if it is 1; this makes the subsequent subtractions DSIGMA(I)-DSIGMA(J) unproblematic when cancellation occurs. On binary machines with a guard digit (almost all machines) it does not change DSIGMA(I) at all. On hexadecimal and decimal machines with a guard digit, it slightly changes the bottommost bits of DSIGMA(I). It does not account for hexadecimal or decimal machines without guard digits (we know of none). We use a subroutine call to compute 2*DLAMBDA(I) to prevent optimizing compilers from eliminating this code. */ i__1 = *k; for (i__ = 1; i__ <= i__1; ++i__) { dsigma[i__] = dlamc3_(&dsigma[i__], &dsigma[i__]) - dsigma[i__]; /* L10: */ } /* Book keeping. */ iwk1 = 1; iwk2 = iwk1 + *k; iwk3 = iwk2 + *k; iwk2i = iwk2 - 1; iwk3i = iwk3 - 1; /* Normalize Z. */ rho = dnrm2_(k, &z__[1], &c__1); dlascl_("G", &c__0, &c__0, &rho, &c_b2865, k, &c__1, &z__[1], k, info); rho *= rho; /* Initialize WORK(IWK3). */ dlaset_("A", k, &c__1, &c_b2865, &c_b2865, &work[iwk3], k); /* Compute the updated singular values, the arrays DIFL, DIFR, and the updated Z. */ i__1 = *k; for (j = 1; j <= i__1; ++j) { dlasd4_(k, &j, &dsigma[1], &z__[1], &work[iwk1], &rho, &d__[j], &work[ iwk2], info); /* If the root finder fails, the computation is terminated. */ if (*info != 0) { return 0; } work[iwk3i + j] = work[iwk3i + j] * work[j] * work[iwk2i + j]; difl[j] = -work[j]; difr[j + difr_dim1] = -work[j + 1]; i__2 = j - 1; for (i__ = 1; i__ <= i__2; ++i__) { work[iwk3i + i__] = work[iwk3i + i__] * work[i__] * work[iwk2i + i__] / (dsigma[i__] - dsigma[j]) / (dsigma[i__] + dsigma[ j]); /* L20: */ } i__2 = *k; for (i__ = j + 1; i__ <= i__2; ++i__) { work[iwk3i + i__] = work[iwk3i + i__] * work[i__] * work[iwk2i + i__] / (dsigma[i__] - dsigma[j]) / (dsigma[i__] + dsigma[ j]); /* L30: */ } /* L40: */ } /* Compute updated Z. */ i__1 = *k; for (i__ = 1; i__ <= i__1; ++i__) { d__2 = sqrt((d__1 = work[iwk3i + i__], abs(d__1))); z__[i__] = d_sign(&d__2, &z__[i__]); /* L50: */ } /* Update VF and VL. */ i__1 = *k; for (j = 1; j <= i__1; ++j) { diflj = difl[j]; dj = d__[j]; dsigj = -dsigma[j]; if (j < *k) { difrj = -difr[j + difr_dim1]; dsigjp = -dsigma[j + 1]; } work[j] = -z__[j] / diflj / (dsigma[j] + dj); i__2 = j - 1; for (i__ = 1; i__ <= i__2; ++i__) { work[i__] = z__[i__] / (dlamc3_(&dsigma[i__], &dsigj) - diflj) / ( dsigma[i__] + dj); /* L60: */ } i__2 = *k; for (i__ = j + 1; i__ <= i__2; ++i__) { work[i__] = z__[i__] / (dlamc3_(&dsigma[i__], &dsigjp) + difrj) / (dsigma[i__] + dj); /* L70: */ } temp = dnrm2_(k, &work[1], &c__1); work[iwk2i + j] = ddot_(k, &work[1], &c__1, &vf[1], &c__1) / temp; work[iwk3i + j] = ddot_(k, &work[1], &c__1, &vl[1], &c__1) / temp; if (*icompq == 1) { difr[j + ((difr_dim1) << (1))] = temp; } /* L80: */ } dcopy_(k, &work[iwk2], &c__1, &vf[1], &c__1); dcopy_(k, &work[iwk3], &c__1, &vl[1], &c__1); return 0; /* End of DLASD8 */ } /* dlasd8_ */ /* Subroutine */ int dlasda_(integer *icompq, integer *smlsiz, integer *n, integer *sqre, doublereal *d__, doublereal *e, doublereal *u, integer *ldu, doublereal *vt, integer *k, doublereal *difl, doublereal *difr, doublereal *z__, doublereal *poles, integer *givptr, integer *givcol, integer *ldgcol, integer *perm, doublereal *givnum, doublereal *c__, doublereal *s, doublereal *work, integer *iwork, integer *info) { /* System generated locals */ integer givcol_dim1, givcol_offset, perm_dim1, perm_offset, difl_dim1, difl_offset, difr_dim1, difr_offset, givnum_dim1, givnum_offset, poles_dim1, poles_offset, u_dim1, u_offset, vt_dim1, vt_offset, z_dim1, z_offset, i__1, i__2; /* Builtin functions */ integer pow_ii(integer *, integer *); /* Local variables */ static integer i__, j, m, i1, ic, lf, nd, ll, nl, vf, nr, vl, im1, ncc, nlf, nrf, vfi, iwk, vli, lvl, nru, ndb1, nlp1, lvl2, nrp1; static doublereal beta; static integer idxq, nlvl; static doublereal alpha; static integer inode, ndiml, ndimr, idxqi, itemp; extern /* Subroutine */ int dcopy_(integer *, doublereal *, integer *, doublereal *, integer *); static integer sqrei; extern /* Subroutine */ int dlasd6_(integer *, integer *, integer *, integer *, doublereal *, doublereal *, doublereal *, doublereal *, doublereal *, integer *, integer *, integer *, integer *, integer *, doublereal *, integer *, doublereal *, doublereal *, doublereal *, doublereal *, integer *, doublereal *, doublereal *, doublereal *, integer *, integer *); static integer nwork1, nwork2; extern /* Subroutine */ int dlasdq_(char *, integer *, integer *, integer *, integer *, integer *, doublereal *, doublereal *, doublereal *, integer *, doublereal *, integer *, doublereal *, integer *, doublereal *, integer *), dlasdt_(integer *, integer *, integer *, integer *, integer *, integer *, integer *), dlaset_( char *, integer *, integer *, doublereal *, doublereal *, doublereal *, integer *), xerbla_(char *, integer *); static integer smlszp; /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University October 31, 1999 Purpose ======= Using a divide and conquer approach, DLASDA computes the singular value decomposition (SVD) of a real upper bidiagonal N-by-M matrix B with diagonal D and offdiagonal E, where M = N + SQRE. The algorithm computes the singular values in the SVD B = U * S * VT. The orthogonal matrices U and VT are optionally computed in compact form. A related subroutine, DLASD0, computes the singular values and the singular vectors in explicit form. Arguments ========= ICOMPQ (input) INTEGER Specifies whether singular vectors are to be computed in compact form, as follows = 0: Compute singular values only. = 1: Compute singular vectors of upper bidiagonal matrix in compact form. SMLSIZ (input) INTEGER The maximum size of the subproblems at the bottom of the computation tree. N (input) INTEGER The row dimension of the upper bidiagonal matrix. This is also the dimension of the main diagonal array D. SQRE (input) INTEGER Specifies the column dimension of the bidiagonal matrix. = 0: The bidiagonal matrix has column dimension M = N; = 1: The bidiagonal matrix has column dimension M = N + 1. D (input/output) DOUBLE PRECISION array, dimension ( N ) On entry D contains the main diagonal of the bidiagonal matrix. On exit D, if INFO = 0, contains its singular values. E (input) DOUBLE PRECISION array, dimension ( M-1 ) Contains the subdiagonal entries of the bidiagonal matrix. On exit, E has been destroyed. U (output) DOUBLE PRECISION array, dimension ( LDU, SMLSIZ ) if ICOMPQ = 1, and not referenced if ICOMPQ = 0. If ICOMPQ = 1, on exit, U contains the left singular vector matrices of all subproblems at the bottom level. LDU (input) INTEGER, LDU = > N. The leading dimension of arrays U, VT, DIFL, DIFR, POLES, GIVNUM, and Z. VT (output) DOUBLE PRECISION array, dimension ( LDU, SMLSIZ+1 ) if ICOMPQ = 1, and not referenced if ICOMPQ = 0. If ICOMPQ = 1, on exit, VT' contains the right singular vector matrices of all subproblems at the bottom level. K (output) INTEGER array, dimension ( N ) if ICOMPQ = 1 and dimension 1 if ICOMPQ = 0. If ICOMPQ = 1, on exit, K(I) is the dimension of the I-th secular equation on the computation tree. DIFL (output) DOUBLE PRECISION array, dimension ( LDU, NLVL ), where NLVL = floor(log_2 (N/SMLSIZ))). DIFR (output) DOUBLE PRECISION array, dimension ( LDU, 2 * NLVL ) if ICOMPQ = 1 and dimension ( N ) if ICOMPQ = 0. If ICOMPQ = 1, on exit, DIFL(1:N, I) and DIFR(1:N, 2 * I - 1) record distances between singular values on the I-th level and singular values on the (I -1)-th level, and DIFR(1:N, 2 * I ) contains the normalizing factors for the right singular vector matrix. See DLASD8 for details. Z (output) DOUBLE PRECISION array, dimension ( LDU, NLVL ) if ICOMPQ = 1 and dimension ( N ) if ICOMPQ = 0. The first K elements of Z(1, I) contain the components of the deflation-adjusted updating row vector for subproblems on the I-th level. POLES (output) DOUBLE PRECISION array, dimension ( LDU, 2 * NLVL ) if ICOMPQ = 1, and not referenced if ICOMPQ = 0. If ICOMPQ = 1, on exit, POLES(1, 2*I - 1) and POLES(1, 2*I) contain the new and old singular values involved in the secular equations on the I-th level. GIVPTR (output) INTEGER array, dimension ( N ) if ICOMPQ = 1, and not referenced if ICOMPQ = 0. If ICOMPQ = 1, on exit, GIVPTR( I ) records the number of Givens rotations performed on the I-th problem on the computation tree. GIVCOL (output) INTEGER array, dimension ( LDGCOL, 2 * NLVL ) if ICOMPQ = 1, and not referenced if ICOMPQ = 0. If ICOMPQ = 1, on exit, for each I, GIVCOL(1, 2 *I - 1) and GIVCOL(1, 2 *I) record the locations of Givens rotations performed on the I-th level on the computation tree. LDGCOL (input) INTEGER, LDGCOL = > N. The leading dimension of arrays GIVCOL and PERM. PERM (output) INTEGER array, dimension ( LDGCOL, NLVL ) if ICOMPQ = 1, and not referenced if ICOMPQ = 0. If ICOMPQ = 1, on exit, PERM(1, I) records permutations done on the I-th level of the computation tree. GIVNUM (output) DOUBLE PRECISION array, dimension ( LDU, 2 * NLVL ) if ICOMPQ = 1, and not referenced if ICOMPQ = 0. If ICOMPQ = 1, on exit, for each I, GIVNUM(1, 2 *I - 1) and GIVNUM(1, 2 *I) record the C- and S- values of Givens rotations performed on the I-th level on the computation tree. C (output) DOUBLE PRECISION array, dimension ( N ) if ICOMPQ = 1, and dimension 1 if ICOMPQ = 0. If ICOMPQ = 1 and the I-th subproblem is not square, on exit, C( I ) contains the C-value of a Givens rotation related to the right null space of the I-th subproblem. S (output) DOUBLE PRECISION array, dimension ( N ) if ICOMPQ = 1, and dimension 1 if ICOMPQ = 0. If ICOMPQ = 1 and the I-th subproblem is not square, on exit, S( I ) contains the S-value of a Givens rotation related to the right null space of the I-th subproblem. WORK (workspace) DOUBLE PRECISION array, dimension (6 * N + (SMLSIZ + 1)*(SMLSIZ + 1)). IWORK (workspace) INTEGER array. Dimension must be at least (7 * N). INFO (output) INTEGER = 0: successful exit. < 0: if INFO = -i, the i-th argument had an illegal value. > 0: if INFO = 1, an singular value did not converge Further Details =============== Based on contributions by Ming Gu and Huan Ren, Computer Science Division, University of California at Berkeley, USA ===================================================================== Test the input parameters. */ /* Parameter adjustments */ --d__; --e; givnum_dim1 = *ldu; givnum_offset = 1 + givnum_dim1; givnum -= givnum_offset; poles_dim1 = *ldu; poles_offset = 1 + poles_dim1; poles -= poles_offset; z_dim1 = *ldu; z_offset = 1 + z_dim1; z__ -= z_offset; difr_dim1 = *ldu; difr_offset = 1 + difr_dim1; difr -= difr_offset; difl_dim1 = *ldu; difl_offset = 1 + difl_dim1; difl -= difl_offset; vt_dim1 = *ldu; vt_offset = 1 + vt_dim1; vt -= vt_offset; u_dim1 = *ldu; u_offset = 1 + u_dim1; u -= u_offset; --k; --givptr; perm_dim1 = *ldgcol; perm_offset = 1 + perm_dim1; perm -= perm_offset; givcol_dim1 = *ldgcol; givcol_offset = 1 + givcol_dim1; givcol -= givcol_offset; --c__; --s; --work; --iwork; /* Function Body */ *info = 0; if ((*icompq < 0) || (*icompq > 1)) { *info = -1; } else if (*smlsiz < 3) { *info = -2; } else if (*n < 0) { *info = -3; } else if ((*sqre < 0) || (*sqre > 1)) { *info = -4; } else if (*ldu < *n + *sqre) { *info = -8; } else if (*ldgcol < *n) { *info = -17; } if (*info != 0) { i__1 = -(*info); xerbla_("DLASDA", &i__1); return 0; } m = *n + *sqre; /* If the input matrix is too small, call DLASDQ to find the SVD. */ if (*n <= *smlsiz) { if (*icompq == 0) { dlasdq_("U", sqre, n, &c__0, &c__0, &c__0, &d__[1], &e[1], &vt[ vt_offset], ldu, &u[u_offset], ldu, &u[u_offset], ldu, & work[1], info); } else { dlasdq_("U", sqre, n, &m, n, &c__0, &d__[1], &e[1], &vt[vt_offset] , ldu, &u[u_offset], ldu, &u[u_offset], ldu, &work[1], info); } return 0; } /* Book-keeping and set up the computation tree. */ inode = 1; ndiml = inode + *n; ndimr = ndiml + *n; idxq = ndimr + *n; iwk = idxq + *n; ncc = 0; nru = 0; smlszp = *smlsiz + 1; vf = 1; vl = vf + m; nwork1 = vl + m; nwork2 = nwork1 + smlszp * smlszp; dlasdt_(n, &nlvl, &nd, &iwork[inode], &iwork[ndiml], &iwork[ndimr], smlsiz); /* for the nodes on bottom level of the tree, solve their subproblems by DLASDQ. */ ndb1 = (nd + 1) / 2; i__1 = nd; for (i__ = ndb1; i__ <= i__1; ++i__) { /* IC : center row of each node NL : number of rows of left subproblem NR : number of rows of right subproblem NLF: starting row of the left subproblem NRF: starting row of the right subproblem */ i1 = i__ - 1; ic = iwork[inode + i1]; nl = iwork[ndiml + i1]; nlp1 = nl + 1; nr = iwork[ndimr + i1]; nlf = ic - nl; nrf = ic + 1; idxqi = idxq + nlf - 2; vfi = vf + nlf - 1; vli = vl + nlf - 1; sqrei = 1; if (*icompq == 0) { dlaset_("A", &nlp1, &nlp1, &c_b2879, &c_b2865, &work[nwork1], & smlszp); dlasdq_("U", &sqrei, &nl, &nlp1, &nru, &ncc, &d__[nlf], &e[nlf], & work[nwork1], &smlszp, &work[nwork2], &nl, &work[nwork2], &nl, &work[nwork2], info); itemp = nwork1 + nl * smlszp; dcopy_(&nlp1, &work[nwork1], &c__1, &work[vfi], &c__1); dcopy_(&nlp1, &work[itemp], &c__1, &work[vli], &c__1); } else { dlaset_("A", &nl, &nl, &c_b2879, &c_b2865, &u[nlf + u_dim1], ldu); dlaset_("A", &nlp1, &nlp1, &c_b2879, &c_b2865, &vt[nlf + vt_dim1], ldu); dlasdq_("U", &sqrei, &nl, &nlp1, &nl, &ncc, &d__[nlf], &e[nlf], & vt[nlf + vt_dim1], ldu, &u[nlf + u_dim1], ldu, &u[nlf + u_dim1], ldu, &work[nwork1], info); dcopy_(&nlp1, &vt[nlf + vt_dim1], &c__1, &work[vfi], &c__1); dcopy_(&nlp1, &vt[nlf + nlp1 * vt_dim1], &c__1, &work[vli], &c__1) ; } if (*info != 0) { return 0; } i__2 = nl; for (j = 1; j <= i__2; ++j) { iwork[idxqi + j] = j; /* L10: */ } if (i__ == nd && *sqre == 0) { sqrei = 0; } else { sqrei = 1; } idxqi += nlp1; vfi += nlp1; vli += nlp1; nrp1 = nr + sqrei; if (*icompq == 0) { dlaset_("A", &nrp1, &nrp1, &c_b2879, &c_b2865, &work[nwork1], & smlszp); dlasdq_("U", &sqrei, &nr, &nrp1, &nru, &ncc, &d__[nrf], &e[nrf], & work[nwork1], &smlszp, &work[nwork2], &nr, &work[nwork2], &nr, &work[nwork2], info); itemp = nwork1 + (nrp1 - 1) * smlszp; dcopy_(&nrp1, &work[nwork1], &c__1, &work[vfi], &c__1); dcopy_(&nrp1, &work[itemp], &c__1, &work[vli], &c__1); } else { dlaset_("A", &nr, &nr, &c_b2879, &c_b2865, &u[nrf + u_dim1], ldu); dlaset_("A", &nrp1, &nrp1, &c_b2879, &c_b2865, &vt[nrf + vt_dim1], ldu); dlasdq_("U", &sqrei, &nr, &nrp1, &nr, &ncc, &d__[nrf], &e[nrf], & vt[nrf + vt_dim1], ldu, &u[nrf + u_dim1], ldu, &u[nrf + u_dim1], ldu, &work[nwork1], info); dcopy_(&nrp1, &vt[nrf + vt_dim1], &c__1, &work[vfi], &c__1); dcopy_(&nrp1, &vt[nrf + nrp1 * vt_dim1], &c__1, &work[vli], &c__1) ; } if (*info != 0) { return 0; } i__2 = nr; for (j = 1; j <= i__2; ++j) { iwork[idxqi + j] = j; /* L20: */ } /* L30: */ } /* Now conquer each subproblem bottom-up. */ j = pow_ii(&c__2, &nlvl); for (lvl = nlvl; lvl >= 1; --lvl) { lvl2 = ((lvl) << (1)) - 1; /* Find the first node LF and last node LL on the current level LVL. */ if (lvl == 1) { lf = 1; ll = 1; } else { i__1 = lvl - 1; lf = pow_ii(&c__2, &i__1); ll = ((lf) << (1)) - 1; } i__1 = ll; for (i__ = lf; i__ <= i__1; ++i__) { im1 = i__ - 1; ic = iwork[inode + im1]; nl = iwork[ndiml + im1]; nr = iwork[ndimr + im1]; nlf = ic - nl; nrf = ic + 1; if (i__ == ll) { sqrei = *sqre; } else { sqrei = 1; } vfi = vf + nlf - 1; vli = vl + nlf - 1; idxqi = idxq + nlf - 1; alpha = d__[ic]; beta = e[ic]; if (*icompq == 0) { dlasd6_(icompq, &nl, &nr, &sqrei, &d__[nlf], &work[vfi], & work[vli], &alpha, &beta, &iwork[idxqi], &perm[ perm_offset], &givptr[1], &givcol[givcol_offset], ldgcol, &givnum[givnum_offset], ldu, &poles[ poles_offset], &difl[difl_offset], &difr[difr_offset], &z__[z_offset], &k[1], &c__[1], &s[1], &work[nwork1], &iwork[iwk], info); } else { --j; dlasd6_(icompq, &nl, &nr, &sqrei, &d__[nlf], &work[vfi], & work[vli], &alpha, &beta, &iwork[idxqi], &perm[nlf + lvl * perm_dim1], &givptr[j], &givcol[nlf + lvl2 * givcol_dim1], ldgcol, &givnum[nlf + lvl2 * givnum_dim1], ldu, &poles[nlf + lvl2 * poles_dim1], & difl[nlf + lvl * difl_dim1], &difr[nlf + lvl2 * difr_dim1], &z__[nlf + lvl * z_dim1], &k[j], &c__[j], &s[j], &work[nwork1], &iwork[iwk], info); } if (*info != 0) { return 0; } /* L40: */ } /* L50: */ } return 0; /* End of DLASDA */ } /* dlasda_ */ /* Subroutine */ int dlasdq_(char *uplo, integer *sqre, integer *n, integer * ncvt, integer *nru, integer *ncc, doublereal *d__, doublereal *e, doublereal *vt, integer *ldvt, doublereal *u, integer *ldu, doublereal *c__, integer *ldc, doublereal *work, integer *info) { /* System generated locals */ integer c_dim1, c_offset, u_dim1, u_offset, vt_dim1, vt_offset, i__1, i__2; /* Local variables */ static integer i__, j; static doublereal r__, cs, sn; static integer np1, isub; static doublereal smin; static integer sqre1; extern logical lsame_(char *, char *); extern /* Subroutine */ int dlasr_(char *, char *, char *, integer *, integer *, doublereal *, doublereal *, doublereal *, integer *), dswap_(integer *, doublereal *, integer * , doublereal *, integer *); static integer iuplo; extern /* Subroutine */ int dlartg_(doublereal *, doublereal *, doublereal *, doublereal *, doublereal *), xerbla_(char *, integer *), dbdsqr_(char *, integer *, integer *, integer *, integer *, doublereal *, doublereal *, doublereal *, integer *, doublereal *, integer *, doublereal *, integer *, doublereal *, integer *); static logical rotate; /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University October 31, 1999 Purpose ======= DLASDQ computes the singular value decomposition (SVD) of a real (upper or lower) bidiagonal matrix with diagonal D and offdiagonal E, accumulating the transformations if desired. Letting B denote the input bidiagonal matrix, the algorithm computes orthogonal matrices Q and P such that B = Q * S * P' (P' denotes the transpose of P). The singular values S are overwritten on D. The input matrix U is changed to U * Q if desired. The input matrix VT is changed to P' * VT if desired. The input matrix C is changed to Q' * C if desired. See "Computing Small Singular Values of Bidiagonal Matrices With Guaranteed High Relative Accuracy," by J. Demmel and W. Kahan, LAPACK Working Note #3, for a detailed description of the algorithm. Arguments ========= UPLO (input) CHARACTER*1 On entry, UPLO specifies whether the input bidiagonal matrix is upper or lower bidiagonal, and wether it is square are not. UPLO = 'U' or 'u' B is upper bidiagonal. UPLO = 'L' or 'l' B is lower bidiagonal. SQRE (input) INTEGER = 0: then the input matrix is N-by-N. = 1: then the input matrix is N-by-(N+1) if UPLU = 'U' and (N+1)-by-N if UPLU = 'L'. The bidiagonal matrix has N = NL + NR + 1 rows and M = N + SQRE >= N columns. N (input) INTEGER On entry, N specifies the number of rows and columns in the matrix. N must be at least 0. NCVT (input) INTEGER On entry, NCVT specifies the number of columns of the matrix VT. NCVT must be at least 0. NRU (input) INTEGER On entry, NRU specifies the number of rows of the matrix U. NRU must be at least 0. NCC (input) INTEGER On entry, NCC specifies the number of columns of the matrix C. NCC must be at least 0. D (input/output) DOUBLE PRECISION array, dimension (N) On entry, D contains the diagonal entries of the bidiagonal matrix whose SVD is desired. On normal exit, D contains the singular values in ascending order. E (input/output) DOUBLE PRECISION array. dimension is (N-1) if SQRE = 0 and N if SQRE = 1. On entry, the entries of E contain the offdiagonal entries of the bidiagonal matrix whose SVD is desired. On normal exit, E will contain 0. If the algorithm does not converge, D and E will contain the diagonal and superdiagonal entries of a bidiagonal matrix orthogonally equivalent to the one given as input. VT (input/output) DOUBLE PRECISION array, dimension (LDVT, NCVT) On entry, contains a matrix which on exit has been premultiplied by P', dimension N-by-NCVT if SQRE = 0 and (N+1)-by-NCVT if SQRE = 1 (not referenced if NCVT=0). LDVT (input) INTEGER On entry, LDVT specifies the leading dimension of VT as declared in the calling (sub) program. LDVT must be at least 1. If NCVT is nonzero LDVT must also be at least N. U (input/output) DOUBLE PRECISION array, dimension (LDU, N) On entry, contains a matrix which on exit has been postmultiplied by Q, dimension NRU-by-N if SQRE = 0 and NRU-by-(N+1) if SQRE = 1 (not referenced if NRU=0). LDU (input) INTEGER On entry, LDU specifies the leading dimension of U as declared in the calling (sub) program. LDU must be at least max( 1, NRU ) . C (input/output) DOUBLE PRECISION array, dimension (LDC, NCC) On entry, contains an N-by-NCC matrix which on exit has been premultiplied by Q' dimension N-by-NCC if SQRE = 0 and (N+1)-by-NCC if SQRE = 1 (not referenced if NCC=0). LDC (input) INTEGER On entry, LDC specifies the leading dimension of C as declared in the calling (sub) program. LDC must be at least 1. If NCC is nonzero, LDC must also be at least N. WORK (workspace) DOUBLE PRECISION array, dimension (4*N) Workspace. Only referenced if one of NCVT, NRU, or NCC is nonzero, and if N is at least 2. INFO (output) INTEGER On exit, a value of 0 indicates a successful exit. If INFO < 0, argument number -INFO is illegal. If INFO > 0, the algorithm did not converge, and INFO specifies how many superdiagonals did not converge. Further Details =============== Based on contributions by Ming Gu and Huan Ren, Computer Science Division, University of California at Berkeley, USA ===================================================================== Test the input parameters. */ /* Parameter adjustments */ --d__; --e; vt_dim1 = *ldvt; vt_offset = 1 + vt_dim1; vt -= vt_offset; u_dim1 = *ldu; u_offset = 1 + u_dim1; u -= u_offset; c_dim1 = *ldc; c_offset = 1 + c_dim1; c__ -= c_offset; --work; /* Function Body */ *info = 0; iuplo = 0; if (lsame_(uplo, "U")) { iuplo = 1; } if (lsame_(uplo, "L")) { iuplo = 2; } if (iuplo == 0) { *info = -1; } else if ((*sqre < 0) || (*sqre > 1)) { *info = -2; } else if (*n < 0) { *info = -3; } else if (*ncvt < 0) { *info = -4; } else if (*nru < 0) { *info = -5; } else if (*ncc < 0) { *info = -6; } else if ((*ncvt == 0 && *ldvt < 1) || (*ncvt > 0 && *ldvt < max(1,*n))) { *info = -10; } else if (*ldu < max(1,*nru)) { *info = -12; } else if ((*ncc == 0 && *ldc < 1) || (*ncc > 0 && *ldc < max(1,*n))) { *info = -14; } if (*info != 0) { i__1 = -(*info); xerbla_("DLASDQ", &i__1); return 0; } if (*n == 0) { return 0; } /* ROTATE is true if any singular vectors desired, false otherwise */ rotate = ((*ncvt > 0) || (*nru > 0)) || (*ncc > 0); np1 = *n + 1; sqre1 = *sqre; /* If matrix non-square upper bidiagonal, rotate to be lower bidiagonal. The rotations are on the right. */ if (iuplo == 1 && sqre1 == 1) { i__1 = *n - 1; for (i__ = 1; i__ <= i__1; ++i__) { dlartg_(&d__[i__], &e[i__], &cs, &sn, &r__); d__[i__] = r__; e[i__] = sn * d__[i__ + 1]; d__[i__ + 1] = cs * d__[i__ + 1]; if (rotate) { work[i__] = cs; work[*n + i__] = sn; } /* L10: */ } dlartg_(&d__[*n], &e[*n], &cs, &sn, &r__); d__[*n] = r__; e[*n] = 0.; if (rotate) { work[*n] = cs; work[*n + *n] = sn; } iuplo = 2; sqre1 = 0; /* Update singular vectors if desired. */ if (*ncvt > 0) { dlasr_("L", "V", "F", &np1, ncvt, &work[1], &work[np1], &vt[ vt_offset], ldvt); } } /* If matrix lower bidiagonal, rotate to be upper bidiagonal by applying Givens rotations on the left. */ if (iuplo == 2) { i__1 = *n - 1; for (i__ = 1; i__ <= i__1; ++i__) { dlartg_(&d__[i__], &e[i__], &cs, &sn, &r__); d__[i__] = r__; e[i__] = sn * d__[i__ + 1]; d__[i__ + 1] = cs * d__[i__ + 1]; if (rotate) { work[i__] = cs; work[*n + i__] = sn; } /* L20: */ } /* If matrix (N+1)-by-N lower bidiagonal, one additional rotation is needed. */ if (sqre1 == 1) { dlartg_(&d__[*n], &e[*n], &cs, &sn, &r__); d__[*n] = r__; if (rotate) { work[*n] = cs; work[*n + *n] = sn; } } /* Update singular vectors if desired. */ if (*nru > 0) { if (sqre1 == 0) { dlasr_("R", "V", "F", nru, n, &work[1], &work[np1], &u[ u_offset], ldu); } else { dlasr_("R", "V", "F", nru, &np1, &work[1], &work[np1], &u[ u_offset], ldu); } } if (*ncc > 0) { if (sqre1 == 0) { dlasr_("L", "V", "F", n, ncc, &work[1], &work[np1], &c__[ c_offset], ldc); } else { dlasr_("L", "V", "F", &np1, ncc, &work[1], &work[np1], &c__[ c_offset], ldc); } } } /* Call DBDSQR to compute the SVD of the reduced real N-by-N upper bidiagonal matrix. */ dbdsqr_("U", n, ncvt, nru, ncc, &d__[1], &e[1], &vt[vt_offset], ldvt, &u[ u_offset], ldu, &c__[c_offset], ldc, &work[1], info); /* Sort the singular values into ascending order (insertion sort on singular values, but only one transposition per singular vector) */ i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { /* Scan for smallest D(I). */ isub = i__; smin = d__[i__]; i__2 = *n; for (j = i__ + 1; j <= i__2; ++j) { if (d__[j] < smin) { isub = j; smin = d__[j]; } /* L30: */ } if (isub != i__) { /* Swap singular values and vectors. */ d__[isub] = d__[i__]; d__[i__] = smin; if (*ncvt > 0) { dswap_(ncvt, &vt[isub + vt_dim1], ldvt, &vt[i__ + vt_dim1], ldvt); } if (*nru > 0) { dswap_(nru, &u[isub * u_dim1 + 1], &c__1, &u[i__ * u_dim1 + 1] , &c__1); } if (*ncc > 0) { dswap_(ncc, &c__[isub + c_dim1], ldc, &c__[i__ + c_dim1], ldc) ; } } /* L40: */ } return 0; /* End of DLASDQ */ } /* dlasdq_ */ /* Subroutine */ int dlasdt_(integer *n, integer *lvl, integer *nd, integer * inode, integer *ndiml, integer *ndimr, integer *msub) { /* System generated locals */ integer i__1, i__2; /* Builtin functions */ double log(doublereal); /* Local variables */ static integer i__, il, ir, maxn; static doublereal temp; static integer nlvl, llst, ncrnt; /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= DLASDT creates a tree of subproblems for bidiagonal divide and conquer. Arguments ========= N (input) INTEGER On entry, the number of diagonal elements of the bidiagonal matrix. LVL (output) INTEGER On exit, the number of levels on the computation tree. ND (output) INTEGER On exit, the number of nodes on the tree. INODE (output) INTEGER array, dimension ( N ) On exit, centers of subproblems. NDIML (output) INTEGER array, dimension ( N ) On exit, row dimensions of left children. NDIMR (output) INTEGER array, dimension ( N ) On exit, row dimensions of right children. MSUB (input) INTEGER. On entry, the maximum row dimension each subproblem at the bottom of the tree can be of. Further Details =============== Based on contributions by Ming Gu and Huan Ren, Computer Science Division, University of California at Berkeley, USA ===================================================================== Find the number of levels on the tree. */ /* Parameter adjustments */ --ndimr; --ndiml; --inode; /* Function Body */ maxn = max(1,*n); temp = log((doublereal) maxn / (doublereal) (*msub + 1)) / log(2.); *lvl = (integer) temp + 1; i__ = *n / 2; inode[1] = i__ + 1; ndiml[1] = i__; ndimr[1] = *n - i__ - 1; il = 0; ir = 1; llst = 1; i__1 = *lvl - 1; for (nlvl = 1; nlvl <= i__1; ++nlvl) { /* Constructing the tree at (NLVL+1)-st level. The number of nodes created on this level is LLST * 2. */ i__2 = llst - 1; for (i__ = 0; i__ <= i__2; ++i__) { il += 2; ir += 2; ncrnt = llst + i__; ndiml[il] = ndiml[ncrnt] / 2; ndimr[il] = ndiml[ncrnt] - ndiml[il] - 1; inode[il] = inode[ncrnt] - ndimr[il] - 1; ndiml[ir] = ndimr[ncrnt] / 2; ndimr[ir] = ndimr[ncrnt] - ndiml[ir] - 1; inode[ir] = inode[ncrnt] + ndiml[ir] + 1; /* L10: */ } llst <<= 1; /* L20: */ } *nd = ((llst) << (1)) - 1; return 0; /* End of DLASDT */ } /* dlasdt_ */ /* Subroutine */ int dlaset_(char *uplo, integer *m, integer *n, doublereal * alpha, doublereal *beta, doublereal *a, integer *lda) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3; /* Local variables */ static integer i__, j; extern logical lsame_(char *, char *); /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University October 31, 1992 Purpose ======= DLASET initializes an m-by-n matrix A to BETA on the diagonal and ALPHA on the offdiagonals. Arguments ========= UPLO (input) CHARACTER*1 Specifies the part of the matrix A to be set. = 'U': Upper triangular part is set; the strictly lower triangular part of A is not changed. = 'L': Lower triangular part is set; the strictly upper triangular part of A is not changed. Otherwise: All of the matrix A is set. M (input) INTEGER The number of rows of the matrix A. M >= 0. N (input) INTEGER The number of columns of the matrix A. N >= 0. ALPHA (input) DOUBLE PRECISION The constant to which the offdiagonal elements are to be set. BETA (input) DOUBLE PRECISION The constant to which the diagonal elements are to be set. A (input/output) DOUBLE PRECISION array, dimension (LDA,N) On exit, the leading m-by-n submatrix of A is set as follows: if UPLO = 'U', A(i,j) = ALPHA, 1<=i<=j-1, 1<=j<=n, if UPLO = 'L', A(i,j) = ALPHA, j+1<=i<=m, 1<=j<=n, otherwise, A(i,j) = ALPHA, 1<=i<=m, 1<=j<=n, i.ne.j, and, for all UPLO, A(i,i) = BETA, 1<=i<=min(m,n). LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,M). ===================================================================== */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; /* Function Body */ if (lsame_(uplo, "U")) { /* Set the strictly upper triangular or trapezoidal part of the array to ALPHA. */ i__1 = *n; for (j = 2; j <= i__1; ++j) { /* Computing MIN */ i__3 = j - 1; i__2 = min(i__3,*m); for (i__ = 1; i__ <= i__2; ++i__) { a[i__ + j * a_dim1] = *alpha; /* L10: */ } /* L20: */ } } else if (lsame_(uplo, "L")) { /* Set the strictly lower triangular or trapezoidal part of the array to ALPHA. */ i__1 = min(*m,*n); for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = j + 1; i__ <= i__2; ++i__) { a[i__ + j * a_dim1] = *alpha; /* L30: */ } /* L40: */ } } else { /* Set the leading m-by-n submatrix to ALPHA. */ i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { a[i__ + j * a_dim1] = *alpha; /* L50: */ } /* L60: */ } } /* Set the first min(M,N) diagonal elements to BETA. */ i__1 = min(*m,*n); for (i__ = 1; i__ <= i__1; ++i__) { a[i__ + i__ * a_dim1] = *beta; /* L70: */ } return 0; /* End of DLASET */ } /* dlaset_ */ /* Subroutine */ int dlasq1_(integer *n, doublereal *d__, doublereal *e, doublereal *work, integer *info) { /* System generated locals */ integer i__1, i__2; doublereal d__1, d__2, d__3; /* Builtin functions */ double sqrt(doublereal); /* Local variables */ static integer i__; static doublereal eps; extern /* Subroutine */ int dlas2_(doublereal *, doublereal *, doublereal *, doublereal *, doublereal *); static doublereal scale; static integer iinfo; static doublereal sigmn; extern /* Subroutine */ int dcopy_(integer *, doublereal *, integer *, doublereal *, integer *); static doublereal sigmx; extern /* Subroutine */ int dlasq2_(integer *, doublereal *, integer *); extern /* Subroutine */ int dlascl_(char *, integer *, integer *, doublereal *, doublereal *, integer *, integer *, doublereal *, integer *, integer *); static doublereal safmin; extern /* Subroutine */ int xerbla_(char *, integer *), dlasrt_( char *, integer *, doublereal *, integer *); /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University October 31, 1999 Purpose ======= DLASQ1 computes the singular values of a real N-by-N bidiagonal matrix with diagonal D and off-diagonal E. The singular values are computed to high relative accuracy, in the absence of denormalization, underflow and overflow. The algorithm was first presented in "Accurate singular values and differential qd algorithms" by K. V. Fernando and B. N. Parlett, Numer. Math., Vol-67, No. 2, pp. 191-230, 1994, and the present implementation is described in "An implementation of the dqds Algorithm (Positive Case)", LAPACK Working Note. Arguments ========= N (input) INTEGER The number of rows and columns in the matrix. N >= 0. D (input/output) DOUBLE PRECISION array, dimension (N) On entry, D contains the diagonal elements of the bidiagonal matrix whose SVD is desired. On normal exit, D contains the singular values in decreasing order. E (input/output) DOUBLE PRECISION array, dimension (N) On entry, elements E(1:N-1) contain the off-diagonal elements of the bidiagonal matrix whose SVD is desired. On exit, E is overwritten. WORK (workspace) DOUBLE PRECISION array, dimension (4*N) INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value > 0: the algorithm failed = 1, a split was marked by a positive value in E = 2, current block of Z not diagonalized after 30*N iterations (in inner while loop) = 3, termination criterion of outer while loop not met (program created more than N unreduced blocks) ===================================================================== */ /* Parameter adjustments */ --work; --e; --d__; /* Function Body */ *info = 0; if (*n < 0) { *info = -2; i__1 = -(*info); xerbla_("DLASQ1", &i__1); return 0; } else if (*n == 0) { return 0; } else if (*n == 1) { d__[1] = abs(d__[1]); return 0; } else if (*n == 2) { dlas2_(&d__[1], &e[1], &d__[2], &sigmn, &sigmx); d__[1] = sigmx; d__[2] = sigmn; return 0; } /* Estimate the largest singular value. */ sigmx = 0.; i__1 = *n - 1; for (i__ = 1; i__ <= i__1; ++i__) { d__[i__] = (d__1 = d__[i__], abs(d__1)); /* Computing MAX */ d__2 = sigmx, d__3 = (d__1 = e[i__], abs(d__1)); sigmx = max(d__2,d__3); /* L10: */ } d__[*n] = (d__1 = d__[*n], abs(d__1)); /* Early return if SIGMX is zero (matrix is already diagonal). */ if (sigmx == 0.) { dlasrt_("D", n, &d__[1], &iinfo); return 0; } i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { /* Computing MAX */ d__1 = sigmx, d__2 = d__[i__]; sigmx = max(d__1,d__2); /* L20: */ } /* Copy D and E into WORK (in the Z format) and scale (squaring the input data makes scaling by a power of the radix pointless). */ eps = PRECISION; safmin = SAFEMINIMUM; scale = sqrt(eps / safmin); dcopy_(n, &d__[1], &c__1, &work[1], &c__2); i__1 = *n - 1; dcopy_(&i__1, &e[1], &c__1, &work[2], &c__2); i__1 = ((*n) << (1)) - 1; i__2 = ((*n) << (1)) - 1; dlascl_("G", &c__0, &c__0, &sigmx, &scale, &i__1, &c__1, &work[1], &i__2, &iinfo); /* Compute the q's and e's. */ i__1 = ((*n) << (1)) - 1; for (i__ = 1; i__ <= i__1; ++i__) { /* Computing 2nd power */ d__1 = work[i__]; work[i__] = d__1 * d__1; /* L30: */ } work[*n * 2] = 0.; dlasq2_(n, &work[1], info); if (*info == 0) { i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { d__[i__] = sqrt(work[i__]); /* L40: */ } dlascl_("G", &c__0, &c__0, &scale, &sigmx, n, &c__1, &d__[1], n, & iinfo); } return 0; /* End of DLASQ1 */ } /* dlasq1_ */ /* Subroutine */ int dlasq2_(integer *n, doublereal *z__, integer *info) { /* System generated locals */ integer i__1, i__2, i__3; doublereal d__1, d__2; /* Builtin functions */ double sqrt(doublereal); /* Local variables */ static doublereal d__, e; static integer k; static doublereal s, t; static integer i0, i4, n0, pp; static doublereal eps, tol; static integer ipn4; static doublereal tol2; static logical ieee; static integer nbig; static doublereal dmin__, emin, emax; static integer ndiv, iter; static doublereal qmin, temp, qmax, zmax; static integer splt, nfail; static doublereal desig, trace, sigma; static integer iinfo; extern /* Subroutine */ int dlasq3_(integer *, integer *, doublereal *, integer *, doublereal *, doublereal *, doublereal *, doublereal *, integer *, integer *, integer *, logical *); static integer iwhila, iwhilb; static doublereal oldemn, safmin; extern /* Subroutine */ int xerbla_(char *, integer *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); extern /* Subroutine */ int dlasrt_(char *, integer *, doublereal *, integer *); /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University October 31, 1999 Purpose ======= DLASQ2 computes all the eigenvalues of the symmetric positive definite tridiagonal matrix associated with the qd array Z to high relative accuracy are computed to high relative accuracy, in the absence of denormalization, underflow and overflow. To see the relation of Z to the tridiagonal matrix, let L be a unit lower bidiagonal matrix with subdiagonals Z(2,4,6,,..) and let U be an upper bidiagonal matrix with 1's above and diagonal Z(1,3,5,,..). The tridiagonal is L*U or, if you prefer, the symmetric tridiagonal to which it is similar. Note : DLASQ2 defines a logical variable, IEEE, which is true on machines which follow ieee-754 floating-point standard in their handling of infinities and NaNs, and false otherwise. This variable is passed to DLASQ3. Arguments ========= N (input) INTEGER The number of rows and columns in the matrix. N >= 0. Z (workspace) DOUBLE PRECISION array, dimension ( 4*N ) On entry Z holds the qd array. On exit, entries 1 to N hold the eigenvalues in decreasing order, Z( 2*N+1 ) holds the trace, and Z( 2*N+2 ) holds the sum of the eigenvalues. If N > 2, then Z( 2*N+3 ) holds the iteration count, Z( 2*N+4 ) holds NDIVS/NIN^2, and Z( 2*N+5 ) holds the percentage of shifts that failed. INFO (output) INTEGER = 0: successful exit < 0: if the i-th argument is a scalar and had an illegal value, then INFO = -i, if the i-th argument is an array and the j-entry had an illegal value, then INFO = -(i*100+j) > 0: the algorithm failed = 1, a split was marked by a positive value in E = 2, current block of Z not diagonalized after 30*N iterations (in inner while loop) = 3, termination criterion of outer while loop not met (program created more than N unreduced blocks) Further Details =============== Local Variables: I0:N0 defines a current unreduced segment of Z. The shifts are accumulated in SIGMA. Iteration count is in ITER. Ping-pong is controlled by PP (alternates between 0 and 1). ===================================================================== Test the input arguments. (in case DLASQ2 is not called by DLASQ1) */ /* Parameter adjustments */ --z__; /* Function Body */ *info = 0; eps = PRECISION; safmin = SAFEMINIMUM; tol = eps * 100.; /* Computing 2nd power */ d__1 = tol; tol2 = d__1 * d__1; if (*n < 0) { *info = -1; xerbla_("DLASQ2", &c__1); return 0; } else if (*n == 0) { return 0; } else if (*n == 1) { /* 1-by-1 case. */ if (z__[1] < 0.) { *info = -201; xerbla_("DLASQ2", &c__2); } return 0; } else if (*n == 2) { /* 2-by-2 case. */ if ((z__[2] < 0.) || (z__[3] < 0.)) { *info = -2; xerbla_("DLASQ2", &c__2); return 0; } else if (z__[3] > z__[1]) { d__ = z__[3]; z__[3] = z__[1]; z__[1] = d__; } z__[5] = z__[1] + z__[2] + z__[3]; if (z__[2] > z__[3] * tol2) { t = (z__[1] - z__[3] + z__[2]) * .5; s = z__[3] * (z__[2] / t); if (s <= t) { s = z__[3] * (z__[2] / (t * (sqrt(s / t + 1.) + 1.))); } else { s = z__[3] * (z__[2] / (t + sqrt(t) * sqrt(t + s))); } t = z__[1] + (s + z__[2]); z__[3] *= z__[1] / t; z__[1] = t; } z__[2] = z__[3]; z__[6] = z__[2] + z__[1]; return 0; } /* Check for negative data and compute sums of q's and e's. */ z__[*n * 2] = 0.; emin = z__[2]; qmax = 0.; zmax = 0.; d__ = 0.; e = 0.; i__1 = (*n - 1) << (1); for (k = 1; k <= i__1; k += 2) { if (z__[k] < 0.) { *info = -(k + 200); xerbla_("DLASQ2", &c__2); return 0; } else if (z__[k + 1] < 0.) { *info = -(k + 201); xerbla_("DLASQ2", &c__2); return 0; } d__ += z__[k]; e += z__[k + 1]; /* Computing MAX */ d__1 = qmax, d__2 = z__[k]; qmax = max(d__1,d__2); /* Computing MIN */ d__1 = emin, d__2 = z__[k + 1]; emin = min(d__1,d__2); /* Computing MAX */ d__1 = max(qmax,zmax), d__2 = z__[k + 1]; zmax = max(d__1,d__2); /* L10: */ } if (z__[((*n) << (1)) - 1] < 0.) { *info = -(((*n) << (1)) + 199); xerbla_("DLASQ2", &c__2); return 0; } d__ += z__[((*n) << (1)) - 1]; /* Computing MAX */ d__1 = qmax, d__2 = z__[((*n) << (1)) - 1]; qmax = max(d__1,d__2); zmax = max(qmax,zmax); /* Check for diagonality. */ if (e == 0.) { i__1 = *n; for (k = 2; k <= i__1; ++k) { z__[k] = z__[((k) << (1)) - 1]; /* L20: */ } dlasrt_("D", n, &z__[1], &iinfo); z__[((*n) << (1)) - 1] = d__; return 0; } trace = d__ + e; /* Check for zero data. */ if (trace == 0.) { z__[((*n) << (1)) - 1] = 0.; return 0; } /* Check whether the machine is IEEE conformable. */ ieee = ilaenv_(&c__10, "DLASQ2", "N", &c__1, &c__2, &c__3, &c__4, (ftnlen) 6, (ftnlen)1) == 1 && ilaenv_(&c__11, "DLASQ2", "N", &c__1, &c__2, &c__3, &c__4, (ftnlen)6, (ftnlen)1) == 1; /* Rearrange data for locality: Z=(q1,qq1,e1,ee1,q2,qq2,e2,ee2,...). */ for (k = (*n) << (1); k >= 2; k += -2) { z__[k * 2] = 0.; z__[((k) << (1)) - 1] = z__[k]; z__[((k) << (1)) - 2] = 0.; z__[((k) << (1)) - 3] = z__[k - 1]; /* L30: */ } i0 = 1; n0 = *n; /* Reverse the qd-array, if warranted. */ if (z__[((i0) << (2)) - 3] * 1.5 < z__[((n0) << (2)) - 3]) { ipn4 = (i0 + n0) << (2); i__1 = (i0 + n0 - 1) << (1); for (i4 = (i0) << (2); i4 <= i__1; i4 += 4) { temp = z__[i4 - 3]; z__[i4 - 3] = z__[ipn4 - i4 - 3]; z__[ipn4 - i4 - 3] = temp; temp = z__[i4 - 1]; z__[i4 - 1] = z__[ipn4 - i4 - 5]; z__[ipn4 - i4 - 5] = temp; /* L40: */ } } /* Initial split checking via dqd and Li's test. */ pp = 0; for (k = 1; k <= 2; ++k) { d__ = z__[((n0) << (2)) + pp - 3]; i__1 = ((i0) << (2)) + pp; for (i4 = ((n0 - 1) << (2)) + pp; i4 >= i__1; i4 += -4) { if (z__[i4 - 1] <= tol2 * d__) { z__[i4 - 1] = -0.; d__ = z__[i4 - 3]; } else { d__ = z__[i4 - 3] * (d__ / (d__ + z__[i4 - 1])); } /* L50: */ } /* dqd maps Z to ZZ plus Li's test. */ emin = z__[((i0) << (2)) + pp + 1]; d__ = z__[((i0) << (2)) + pp - 3]; i__1 = ((n0 - 1) << (2)) + pp; for (i4 = ((i0) << (2)) + pp; i4 <= i__1; i4 += 4) { z__[i4 - ((pp) << (1)) - 2] = d__ + z__[i4 - 1]; if (z__[i4 - 1] <= tol2 * d__) { z__[i4 - 1] = -0.; z__[i4 - ((pp) << (1)) - 2] = d__; z__[i4 - ((pp) << (1))] = 0.; d__ = z__[i4 + 1]; } else if (safmin * z__[i4 + 1] < z__[i4 - ((pp) << (1)) - 2] && safmin * z__[i4 - ((pp) << (1)) - 2] < z__[i4 + 1]) { temp = z__[i4 + 1] / z__[i4 - ((pp) << (1)) - 2]; z__[i4 - ((pp) << (1))] = z__[i4 - 1] * temp; d__ *= temp; } else { z__[i4 - ((pp) << (1))] = z__[i4 + 1] * (z__[i4 - 1] / z__[i4 - ((pp) << (1)) - 2]); d__ = z__[i4 + 1] * (d__ / z__[i4 - ((pp) << (1)) - 2]); } /* Computing MIN */ d__1 = emin, d__2 = z__[i4 - ((pp) << (1))]; emin = min(d__1,d__2); /* L60: */ } z__[((n0) << (2)) - pp - 2] = d__; /* Now find qmax. */ qmax = z__[((i0) << (2)) - pp - 2]; i__1 = ((n0) << (2)) - pp - 2; for (i4 = ((i0) << (2)) - pp + 2; i4 <= i__1; i4 += 4) { /* Computing MAX */ d__1 = qmax, d__2 = z__[i4]; qmax = max(d__1,d__2); /* L70: */ } /* Prepare for the next iteration on K. */ pp = 1 - pp; /* L80: */ } iter = 2; nfail = 0; ndiv = (n0 - i0) << (1); i__1 = *n + 1; for (iwhila = 1; iwhila <= i__1; ++iwhila) { if (n0 < 1) { goto L150; } /* While array unfinished do E(N0) holds the value of SIGMA when submatrix in I0:N0 splits from the rest of the array, but is negated. */ desig = 0.; if (n0 == *n) { sigma = 0.; } else { sigma = -z__[((n0) << (2)) - 1]; } if (sigma < 0.) { *info = 1; return 0; } /* Find last unreduced submatrix's top index I0, find QMAX and EMIN. Find Gershgorin-type bound if Q's much greater than E's. */ emax = 0.; if (n0 > i0) { emin = (d__1 = z__[((n0) << (2)) - 5], abs(d__1)); } else { emin = 0.; } qmin = z__[((n0) << (2)) - 3]; qmax = qmin; for (i4 = (n0) << (2); i4 >= 8; i4 += -4) { if (z__[i4 - 5] <= 0.) { goto L100; } if (qmin >= emax * 4.) { /* Computing MIN */ d__1 = qmin, d__2 = z__[i4 - 3]; qmin = min(d__1,d__2); /* Computing MAX */ d__1 = emax, d__2 = z__[i4 - 5]; emax = max(d__1,d__2); } /* Computing MAX */ d__1 = qmax, d__2 = z__[i4 - 7] + z__[i4 - 5]; qmax = max(d__1,d__2); /* Computing MIN */ d__1 = emin, d__2 = z__[i4 - 5]; emin = min(d__1,d__2); /* L90: */ } i4 = 4; L100: i0 = i4 / 4; /* Store EMIN for passing to DLASQ3. */ z__[((n0) << (2)) - 1] = emin; /* Put -(initial shift) into DMIN. Computing MAX */ d__1 = 0., d__2 = qmin - sqrt(qmin) * 2. * sqrt(emax); dmin__ = -max(d__1,d__2); /* Now I0:N0 is unreduced. PP = 0 for ping, PP = 1 for pong. */ pp = 0; nbig = (n0 - i0 + 1) * 30; i__2 = nbig; for (iwhilb = 1; iwhilb <= i__2; ++iwhilb) { if (i0 > n0) { goto L130; } /* While submatrix unfinished take a good dqds step. */ dlasq3_(&i0, &n0, &z__[1], &pp, &dmin__, &sigma, &desig, &qmax, & nfail, &iter, &ndiv, &ieee); pp = 1 - pp; /* When EMIN is very small check for splits. */ if (pp == 0 && n0 - i0 >= 3) { if ((z__[n0 * 4] <= tol2 * qmax) || (z__[((n0) << (2)) - 1] <= tol2 * sigma)) { splt = i0 - 1; qmax = z__[((i0) << (2)) - 3]; emin = z__[((i0) << (2)) - 1]; oldemn = z__[i0 * 4]; i__3 = (n0 - 3) << (2); for (i4 = (i0) << (2); i4 <= i__3; i4 += 4) { if ((z__[i4] <= tol2 * z__[i4 - 3]) || (z__[i4 - 1] <= tol2 * sigma)) { z__[i4 - 1] = -sigma; splt = i4 / 4; qmax = 0.; emin = z__[i4 + 3]; oldemn = z__[i4 + 4]; } else { /* Computing MAX */ d__1 = qmax, d__2 = z__[i4 + 1]; qmax = max(d__1,d__2); /* Computing MIN */ d__1 = emin, d__2 = z__[i4 - 1]; emin = min(d__1,d__2); /* Computing MIN */ d__1 = oldemn, d__2 = z__[i4]; oldemn = min(d__1,d__2); } /* L110: */ } z__[((n0) << (2)) - 1] = emin; z__[n0 * 4] = oldemn; i0 = splt + 1; } } /* L120: */ } *info = 2; return 0; /* end IWHILB */ L130: /* L140: */ ; } *info = 3; return 0; /* end IWHILA */ L150: /* Move q's to the front. */ i__1 = *n; for (k = 2; k <= i__1; ++k) { z__[k] = z__[((k) << (2)) - 3]; /* L160: */ } /* Sort and compute sum of eigenvalues. */ dlasrt_("D", n, &z__[1], &iinfo); e = 0.; for (k = *n; k >= 1; --k) { e += z__[k]; /* L170: */ } /* Store trace, sum(eigenvalues) and information on performance. */ z__[((*n) << (1)) + 1] = trace; z__[((*n) << (1)) + 2] = e; z__[((*n) << (1)) + 3] = (doublereal) iter; /* Computing 2nd power */ i__1 = *n; z__[((*n) << (1)) + 4] = (doublereal) ndiv / (doublereal) (i__1 * i__1); z__[((*n) << (1)) + 5] = nfail * 100. / (doublereal) iter; return 0; /* End of DLASQ2 */ } /* dlasq2_ */ /* Subroutine */ int dlasq3_(integer *i0, integer *n0, doublereal *z__, integer *pp, doublereal *dmin__, doublereal *sigma, doublereal *desig, doublereal *qmax, integer *nfail, integer *iter, integer *ndiv, logical *ieee) { /* Initialized data */ static integer ttype = 0; static doublereal dmin1 = 0.; static doublereal dmin2 = 0.; static doublereal dn = 0.; static doublereal dn1 = 0.; static doublereal dn2 = 0.; static doublereal tau = 0.; /* System generated locals */ integer i__1; doublereal d__1, d__2; /* Builtin functions */ double sqrt(doublereal); /* Local variables */ static doublereal s, t; static integer j4, nn; static doublereal eps, tol; static integer n0in, ipn4; static doublereal tol2, temp; extern /* Subroutine */ int dlasq4_(integer *, integer *, doublereal *, integer *, integer *, doublereal *, doublereal *, doublereal *, doublereal *, doublereal *, doublereal *, doublereal *, integer *) , dlasq5_(integer *, integer *, doublereal *, integer *, doublereal *, doublereal *, doublereal *, doublereal *, doublereal *, doublereal *, doublereal *, logical *), dlasq6_( integer *, integer *, doublereal *, integer *, doublereal *, doublereal *, doublereal *, doublereal *, doublereal *, doublereal *); static doublereal safmin; /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University May 17, 2000 Purpose ======= DLASQ3 checks for deflation, computes a shift (TAU) and calls dqds. In case of failure it changes shifts, and tries again until output is positive. Arguments ========= I0 (input) INTEGER First index. N0 (input) INTEGER Last index. Z (input) DOUBLE PRECISION array, dimension ( 4*N ) Z holds the qd array. PP (input) INTEGER PP=0 for ping, PP=1 for pong. DMIN (output) DOUBLE PRECISION Minimum value of d. SIGMA (output) DOUBLE PRECISION Sum of shifts used in current segment. DESIG (input/output) DOUBLE PRECISION Lower order part of SIGMA QMAX (input) DOUBLE PRECISION Maximum value of q. NFAIL (output) INTEGER Number of times shift was too big. ITER (output) INTEGER Number of iterations. NDIV (output) INTEGER Number of divisions. TTYPE (output) INTEGER Shift type. IEEE (input) LOGICAL Flag for IEEE or non IEEE arithmetic (passed to DLASQ5). ===================================================================== */ /* Parameter adjustments */ --z__; /* Function Body */ n0in = *n0; eps = PRECISION; safmin = SAFEMINIMUM; tol = eps * 100.; /* Computing 2nd power */ d__1 = tol; tol2 = d__1 * d__1; /* Check for deflation. */ L10: if (*n0 < *i0) { return 0; } if (*n0 == *i0) { goto L20; } nn = ((*n0) << (2)) + *pp; if (*n0 == *i0 + 1) { goto L40; } /* Check whether E(N0-1) is negligible, 1 eigenvalue. */ if (z__[nn - 5] > tol2 * (*sigma + z__[nn - 3]) && z__[nn - ((*pp) << (1)) - 4] > tol2 * z__[nn - 7]) { goto L30; } L20: z__[((*n0) << (2)) - 3] = z__[((*n0) << (2)) + *pp - 3] + *sigma; --(*n0); goto L10; /* Check whether E(N0-2) is negligible, 2 eigenvalues. */ L30: if (z__[nn - 9] > tol2 * *sigma && z__[nn - ((*pp) << (1)) - 8] > tol2 * z__[nn - 11]) { goto L50; } L40: if (z__[nn - 3] > z__[nn - 7]) { s = z__[nn - 3]; z__[nn - 3] = z__[nn - 7]; z__[nn - 7] = s; } if (z__[nn - 5] > z__[nn - 3] * tol2) { t = (z__[nn - 7] - z__[nn - 3] + z__[nn - 5]) * .5; s = z__[nn - 3] * (z__[nn - 5] / t); if (s <= t) { s = z__[nn - 3] * (z__[nn - 5] / (t * (sqrt(s / t + 1.) + 1.))); } else { s = z__[nn - 3] * (z__[nn - 5] / (t + sqrt(t) * sqrt(t + s))); } t = z__[nn - 7] + (s + z__[nn - 5]); z__[nn - 3] *= z__[nn - 7] / t; z__[nn - 7] = t; } z__[((*n0) << (2)) - 7] = z__[nn - 7] + *sigma; z__[((*n0) << (2)) - 3] = z__[nn - 3] + *sigma; *n0 += -2; goto L10; L50: /* Reverse the qd-array, if warranted. */ if ((*dmin__ <= 0.) || (*n0 < n0in)) { if (z__[((*i0) << (2)) + *pp - 3] * 1.5 < z__[((*n0) << (2)) + *pp - 3]) { ipn4 = (*i0 + *n0) << (2); i__1 = (*i0 + *n0 - 1) << (1); for (j4 = (*i0) << (2); j4 <= i__1; j4 += 4) { temp = z__[j4 - 3]; z__[j4 - 3] = z__[ipn4 - j4 - 3]; z__[ipn4 - j4 - 3] = temp; temp = z__[j4 - 2]; z__[j4 - 2] = z__[ipn4 - j4 - 2]; z__[ipn4 - j4 - 2] = temp; temp = z__[j4 - 1]; z__[j4 - 1] = z__[ipn4 - j4 - 5]; z__[ipn4 - j4 - 5] = temp; temp = z__[j4]; z__[j4] = z__[ipn4 - j4 - 4]; z__[ipn4 - j4 - 4] = temp; /* L60: */ } if (*n0 - *i0 <= 4) { z__[((*n0) << (2)) + *pp - 1] = z__[((*i0) << (2)) + *pp - 1]; z__[((*n0) << (2)) - *pp] = z__[((*i0) << (2)) - *pp]; } /* Computing MIN */ d__1 = dmin2, d__2 = z__[((*n0) << (2)) + *pp - 1]; dmin2 = min(d__1,d__2); /* Computing MIN */ d__1 = z__[((*n0) << (2)) + *pp - 1], d__2 = z__[((*i0) << (2)) + *pp - 1], d__1 = min(d__1,d__2), d__2 = z__[((*i0) << (2)) + *pp + 3]; z__[((*n0) << (2)) + *pp - 1] = min(d__1,d__2); /* Computing MIN */ d__1 = z__[((*n0) << (2)) - *pp], d__2 = z__[((*i0) << (2)) - *pp] , d__1 = min(d__1,d__2), d__2 = z__[((*i0) << (2)) - *pp + 4]; z__[((*n0) << (2)) - *pp] = min(d__1,d__2); /* Computing MAX */ d__1 = *qmax, d__2 = z__[((*i0) << (2)) + *pp - 3], d__1 = max( d__1,d__2), d__2 = z__[((*i0) << (2)) + *pp + 1]; *qmax = max(d__1,d__2); *dmin__ = -0.; } } /* L70: Computing MIN */ d__1 = z__[((*n0) << (2)) + *pp - 1], d__2 = z__[((*n0) << (2)) + *pp - 9] , d__1 = min(d__1,d__2), d__2 = dmin2 + z__[((*n0) << (2)) - *pp]; if ((*dmin__ < 0.) || (safmin * *qmax < min(d__1,d__2))) { /* Choose a shift. */ dlasq4_(i0, n0, &z__[1], pp, &n0in, dmin__, &dmin1, &dmin2, &dn, &dn1, &dn2, &tau, &ttype); /* Call dqds until DMIN > 0. */ L80: dlasq5_(i0, n0, &z__[1], pp, &tau, dmin__, &dmin1, &dmin2, &dn, &dn1, &dn2, ieee); *ndiv += *n0 - *i0 + 2; ++(*iter); /* Check status. */ if (*dmin__ >= 0. && dmin1 > 0.) { /* Success. */ goto L100; } else if (*dmin__ < 0. && dmin1 > 0. && z__[((*n0 - 1) << (2)) - *pp] < tol * (*sigma + dn1) && abs(dn) < tol * *sigma) { /* Convergence hidden by negative DN. */ z__[((*n0 - 1) << (2)) - *pp + 2] = 0.; *dmin__ = 0.; goto L100; } else if (*dmin__ < 0.) { /* TAU too big. Select new TAU and try again. */ ++(*nfail); if (ttype < -22) { /* Failed twice. Play it safe. */ tau = 0.; } else if (dmin1 > 0.) { /* Late failure. Gives excellent shift. */ tau = (tau + *dmin__) * (1. - eps * 2.); ttype += -11; } else { /* Early failure. Divide by 4. */ tau *= .25; ttype += -12; } goto L80; } else if (*dmin__ != *dmin__) { /* NaN. */ tau = 0.; goto L80; } else { /* Possible underflow. Play it safe. */ goto L90; } } /* Risk of underflow. */ L90: dlasq6_(i0, n0, &z__[1], pp, dmin__, &dmin1, &dmin2, &dn, &dn1, &dn2); *ndiv += *n0 - *i0 + 2; ++(*iter); tau = 0.; L100: if (tau < *sigma) { *desig += tau; t = *sigma + *desig; *desig -= t - *sigma; } else { t = *sigma + tau; *desig = *sigma - (t - tau) + *desig; } *sigma = t; return 0; /* End of DLASQ3 */ } /* dlasq3_ */ /* Subroutine */ int dlasq4_(integer *i0, integer *n0, doublereal *z__, integer *pp, integer *n0in, doublereal *dmin__, doublereal *dmin1, doublereal *dmin2, doublereal *dn, doublereal *dn1, doublereal *dn2, doublereal *tau, integer *ttype) { /* Initialized data */ static doublereal g = 0.; /* System generated locals */ integer i__1; doublereal d__1, d__2; /* Builtin functions */ double sqrt(doublereal); /* Local variables */ static doublereal s, a2, b1, b2; static integer i4, nn, np; static doublereal gam, gap1, gap2; /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University October 31, 1999 Purpose ======= DLASQ4 computes an approximation TAU to the smallest eigenvalue using values of d from the previous transform. I0 (input) INTEGER First index. N0 (input) INTEGER Last index. Z (input) DOUBLE PRECISION array, dimension ( 4*N ) Z holds the qd array. PP (input) INTEGER PP=0 for ping, PP=1 for pong. NOIN (input) INTEGER The value of N0 at start of EIGTEST. DMIN (input) DOUBLE PRECISION Minimum value of d. DMIN1 (input) DOUBLE PRECISION Minimum value of d, excluding D( N0 ). DMIN2 (input) DOUBLE PRECISION Minimum value of d, excluding D( N0 ) and D( N0-1 ). DN (input) DOUBLE PRECISION d(N) DN1 (input) DOUBLE PRECISION d(N-1) DN2 (input) DOUBLE PRECISION d(N-2) TAU (output) DOUBLE PRECISION This is the shift. TTYPE (output) INTEGER Shift type. Further Details =============== CNST1 = 9/16 ===================================================================== */ /* Parameter adjustments */ --z__; /* Function Body */ /* A negative DMIN forces the shift to take that absolute value TTYPE records the type of shift. */ if (*dmin__ <= 0.) { *tau = -(*dmin__); *ttype = -1; return 0; } nn = ((*n0) << (2)) + *pp; if (*n0in == *n0) { /* No eigenvalues deflated. */ if ((*dmin__ == *dn) || (*dmin__ == *dn1)) { b1 = sqrt(z__[nn - 3]) * sqrt(z__[nn - 5]); b2 = sqrt(z__[nn - 7]) * sqrt(z__[nn - 9]); a2 = z__[nn - 7] + z__[nn - 5]; /* Cases 2 and 3. */ if (*dmin__ == *dn && *dmin1 == *dn1) { gap2 = *dmin2 - a2 - *dmin2 * .25; if (gap2 > 0. && gap2 > b2) { gap1 = a2 - *dn - b2 / gap2 * b2; } else { gap1 = a2 - *dn - (b1 + b2); } if (gap1 > 0. && gap1 > b1) { /* Computing MAX */ d__1 = *dn - b1 / gap1 * b1, d__2 = *dmin__ * .5; s = max(d__1,d__2); *ttype = -2; } else { s = 0.; if (*dn > b1) { s = *dn - b1; } if (a2 > b1 + b2) { /* Computing MIN */ d__1 = s, d__2 = a2 - (b1 + b2); s = min(d__1,d__2); } /* Computing MAX */ d__1 = s, d__2 = *dmin__ * .333; s = max(d__1,d__2); *ttype = -3; } } else { /* Case 4. */ *ttype = -4; s = *dmin__ * .25; if (*dmin__ == *dn) { gam = *dn; a2 = 0.; if (z__[nn - 5] > z__[nn - 7]) { return 0; } b2 = z__[nn - 5] / z__[nn - 7]; np = nn - 9; } else { np = nn - ((*pp) << (1)); b2 = z__[np - 2]; gam = *dn1; if (z__[np - 4] > z__[np - 2]) { return 0; } a2 = z__[np - 4] / z__[np - 2]; if (z__[nn - 9] > z__[nn - 11]) { return 0; } b2 = z__[nn - 9] / z__[nn - 11]; np = nn - 13; } /* Approximate contribution to norm squared from I < NN-1. */ a2 += b2; i__1 = ((*i0) << (2)) - 1 + *pp; for (i4 = np; i4 >= i__1; i4 += -4) { if (b2 == 0.) { goto L20; } b1 = b2; if (z__[i4] > z__[i4 - 2]) { return 0; } b2 *= z__[i4] / z__[i4 - 2]; a2 += b2; if ((max(b2,b1) * 100. < a2) || (.563 < a2)) { goto L20; } /* L10: */ } L20: a2 *= 1.05; /* Rayleigh quotient residual bound. */ if (a2 < .563) { s = gam * (1. - sqrt(a2)) / (a2 + 1.); } } } else if (*dmin__ == *dn2) { /* Case 5. */ *ttype = -5; s = *dmin__ * .25; /* Compute contribution to norm squared from I > NN-2. */ np = nn - ((*pp) << (1)); b1 = z__[np - 2]; b2 = z__[np - 6]; gam = *dn2; if ((z__[np - 8] > b2) || (z__[np - 4] > b1)) { return 0; } a2 = z__[np - 8] / b2 * (z__[np - 4] / b1 + 1.); /* Approximate contribution to norm squared from I < NN-2. */ if (*n0 - *i0 > 2) { b2 = z__[nn - 13] / z__[nn - 15]; a2 += b2; i__1 = ((*i0) << (2)) - 1 + *pp; for (i4 = nn - 17; i4 >= i__1; i4 += -4) { if (b2 == 0.) { goto L40; } b1 = b2; if (z__[i4] > z__[i4 - 2]) { return 0; } b2 *= z__[i4] / z__[i4 - 2]; a2 += b2; if ((max(b2,b1) * 100. < a2) || (.563 < a2)) { goto L40; } /* L30: */ } L40: a2 *= 1.05; } if (a2 < .563) { s = gam * (1. - sqrt(a2)) / (a2 + 1.); } } else { /* Case 6, no information to guide us. */ if (*ttype == -6) { g += (1. - g) * .333; } else if (*ttype == -18) { g = .083250000000000005; } else { g = .25; } s = g * *dmin__; *ttype = -6; } } else if (*n0in == *n0 + 1) { /* One eigenvalue just deflated. Use DMIN1, DN1 for DMIN and DN. */ if (*dmin1 == *dn1 && *dmin2 == *dn2) { /* Cases 7 and 8. */ *ttype = -7; s = *dmin1 * .333; if (z__[nn - 5] > z__[nn - 7]) { return 0; } b1 = z__[nn - 5] / z__[nn - 7]; b2 = b1; if (b2 == 0.) { goto L60; } i__1 = ((*i0) << (2)) - 1 + *pp; for (i4 = ((*n0) << (2)) - 9 + *pp; i4 >= i__1; i4 += -4) { a2 = b1; if (z__[i4] > z__[i4 - 2]) { return 0; } b1 *= z__[i4] / z__[i4 - 2]; b2 += b1; if (max(b1,a2) * 100. < b2) { goto L60; } /* L50: */ } L60: b2 = sqrt(b2 * 1.05); /* Computing 2nd power */ d__1 = b2; a2 = *dmin1 / (d__1 * d__1 + 1.); gap2 = *dmin2 * .5 - a2; if (gap2 > 0. && gap2 > b2 * a2) { /* Computing MAX */ d__1 = s, d__2 = a2 * (1. - a2 * 1.01 * (b2 / gap2) * b2); s = max(d__1,d__2); } else { /* Computing MAX */ d__1 = s, d__2 = a2 * (1. - b2 * 1.01); s = max(d__1,d__2); *ttype = -8; } } else { /* Case 9. */ s = *dmin1 * .25; if (*dmin1 == *dn1) { s = *dmin1 * .5; } *ttype = -9; } } else if (*n0in == *n0 + 2) { /* Two eigenvalues deflated. Use DMIN2, DN2 for DMIN and DN. Cases 10 and 11. */ if (*dmin2 == *dn2 && z__[nn - 5] * 2. < z__[nn - 7]) { *ttype = -10; s = *dmin2 * .333; if (z__[nn - 5] > z__[nn - 7]) { return 0; } b1 = z__[nn - 5] / z__[nn - 7]; b2 = b1; if (b2 == 0.) { goto L80; } i__1 = ((*i0) << (2)) - 1 + *pp; for (i4 = ((*n0) << (2)) - 9 + *pp; i4 >= i__1; i4 += -4) { if (z__[i4] > z__[i4 - 2]) { return 0; } b1 *= z__[i4] / z__[i4 - 2]; b2 += b1; if (b1 * 100. < b2) { goto L80; } /* L70: */ } L80: b2 = sqrt(b2 * 1.05); /* Computing 2nd power */ d__1 = b2; a2 = *dmin2 / (d__1 * d__1 + 1.); gap2 = z__[nn - 7] + z__[nn - 9] - sqrt(z__[nn - 11]) * sqrt(z__[ nn - 9]) - a2; if (gap2 > 0. && gap2 > b2 * a2) { /* Computing MAX */ d__1 = s, d__2 = a2 * (1. - a2 * 1.01 * (b2 / gap2) * b2); s = max(d__1,d__2); } else { /* Computing MAX */ d__1 = s, d__2 = a2 * (1. - b2 * 1.01); s = max(d__1,d__2); } } else { s = *dmin2 * .25; *ttype = -11; } } else if (*n0in > *n0 + 2) { /* Case 12, more than two eigenvalues deflated. No information. */ s = 0.; *ttype = -12; } *tau = s; return 0; /* End of DLASQ4 */ } /* dlasq4_ */ /* Subroutine */ int dlasq5_(integer *i0, integer *n0, doublereal *z__, integer *pp, doublereal *tau, doublereal *dmin__, doublereal *dmin1, doublereal *dmin2, doublereal *dn, doublereal *dnm1, doublereal *dnm2, logical *ieee) { /* System generated locals */ integer i__1; doublereal d__1, d__2; /* Local variables */ static doublereal d__; static integer j4, j4p2; static doublereal emin, temp; /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University May 17, 2000 Purpose ======= DLASQ5 computes one dqds transform in ping-pong form, one version for IEEE machines another for non IEEE machines. Arguments ========= I0 (input) INTEGER First index. N0 (input) INTEGER Last index. Z (input) DOUBLE PRECISION array, dimension ( 4*N ) Z holds the qd array. EMIN is stored in Z(4*N0) to avoid an extra argument. PP (input) INTEGER PP=0 for ping, PP=1 for pong. TAU (input) DOUBLE PRECISION This is the shift. DMIN (output) DOUBLE PRECISION Minimum value of d. DMIN1 (output) DOUBLE PRECISION Minimum value of d, excluding D( N0 ). DMIN2 (output) DOUBLE PRECISION Minimum value of d, excluding D( N0 ) and D( N0-1 ). DN (output) DOUBLE PRECISION d(N0), the last value of d. DNM1 (output) DOUBLE PRECISION d(N0-1). DNM2 (output) DOUBLE PRECISION d(N0-2). IEEE (input) LOGICAL Flag for IEEE or non IEEE arithmetic. ===================================================================== */ /* Parameter adjustments */ --z__; /* Function Body */ if (*n0 - *i0 - 1 <= 0) { return 0; } j4 = ((*i0) << (2)) + *pp - 3; emin = z__[j4 + 4]; d__ = z__[j4] - *tau; *dmin__ = d__; *dmin1 = -z__[j4]; if (*ieee) { /* Code for IEEE arithmetic. */ if (*pp == 0) { i__1 = (*n0 - 3) << (2); for (j4 = (*i0) << (2); j4 <= i__1; j4 += 4) { z__[j4 - 2] = d__ + z__[j4 - 1]; temp = z__[j4 + 1] / z__[j4 - 2]; d__ = d__ * temp - *tau; *dmin__ = min(*dmin__,d__); z__[j4] = z__[j4 - 1] * temp; /* Computing MIN */ d__1 = z__[j4]; emin = min(d__1,emin); /* L10: */ } } else { i__1 = (*n0 - 3) << (2); for (j4 = (*i0) << (2); j4 <= i__1; j4 += 4) { z__[j4 - 3] = d__ + z__[j4]; temp = z__[j4 + 2] / z__[j4 - 3]; d__ = d__ * temp - *tau; *dmin__ = min(*dmin__,d__); z__[j4 - 1] = z__[j4] * temp; /* Computing MIN */ d__1 = z__[j4 - 1]; emin = min(d__1,emin); /* L20: */ } } /* Unroll last two steps. */ *dnm2 = d__; *dmin2 = *dmin__; j4 = ((*n0 - 2) << (2)) - *pp; j4p2 = j4 + ((*pp) << (1)) - 1; z__[j4 - 2] = *dnm2 + z__[j4p2]; z__[j4] = z__[j4p2 + 2] * (z__[j4p2] / z__[j4 - 2]); *dnm1 = z__[j4p2 + 2] * (*dnm2 / z__[j4 - 2]) - *tau; *dmin__ = min(*dmin__,*dnm1); *dmin1 = *dmin__; j4 += 4; j4p2 = j4 + ((*pp) << (1)) - 1; z__[j4 - 2] = *dnm1 + z__[j4p2]; z__[j4] = z__[j4p2 + 2] * (z__[j4p2] / z__[j4 - 2]); *dn = z__[j4p2 + 2] * (*dnm1 / z__[j4 - 2]) - *tau; *dmin__ = min(*dmin__,*dn); } else { /* Code for non IEEE arithmetic. */ if (*pp == 0) { i__1 = (*n0 - 3) << (2); for (j4 = (*i0) << (2); j4 <= i__1; j4 += 4) { z__[j4 - 2] = d__ + z__[j4 - 1]; if (d__ < 0.) { return 0; } else { z__[j4] = z__[j4 + 1] * (z__[j4 - 1] / z__[j4 - 2]); d__ = z__[j4 + 1] * (d__ / z__[j4 - 2]) - *tau; } *dmin__ = min(*dmin__,d__); /* Computing MIN */ d__1 = emin, d__2 = z__[j4]; emin = min(d__1,d__2); /* L30: */ } } else { i__1 = (*n0 - 3) << (2); for (j4 = (*i0) << (2); j4 <= i__1; j4 += 4) { z__[j4 - 3] = d__ + z__[j4]; if (d__ < 0.) { return 0; } else { z__[j4 - 1] = z__[j4 + 2] * (z__[j4] / z__[j4 - 3]); d__ = z__[j4 + 2] * (d__ / z__[j4 - 3]) - *tau; } *dmin__ = min(*dmin__,d__); /* Computing MIN */ d__1 = emin, d__2 = z__[j4 - 1]; emin = min(d__1,d__2); /* L40: */ } } /* Unroll last two steps. */ *dnm2 = d__; *dmin2 = *dmin__; j4 = ((*n0 - 2) << (2)) - *pp; j4p2 = j4 + ((*pp) << (1)) - 1; z__[j4 - 2] = *dnm2 + z__[j4p2]; if (*dnm2 < 0.) { return 0; } else { z__[j4] = z__[j4p2 + 2] * (z__[j4p2] / z__[j4 - 2]); *dnm1 = z__[j4p2 + 2] * (*dnm2 / z__[j4 - 2]) - *tau; } *dmin__ = min(*dmin__,*dnm1); *dmin1 = *dmin__; j4 += 4; j4p2 = j4 + ((*pp) << (1)) - 1; z__[j4 - 2] = *dnm1 + z__[j4p2]; if (*dnm1 < 0.) { return 0; } else { z__[j4] = z__[j4p2 + 2] * (z__[j4p2] / z__[j4 - 2]); *dn = z__[j4p2 + 2] * (*dnm1 / z__[j4 - 2]) - *tau; } *dmin__ = min(*dmin__,*dn); } z__[j4 + 2] = *dn; z__[((*n0) << (2)) - *pp] = emin; return 0; /* End of DLASQ5 */ } /* dlasq5_ */ /* Subroutine */ int dlasq6_(integer *i0, integer *n0, doublereal *z__, integer *pp, doublereal *dmin__, doublereal *dmin1, doublereal *dmin2, doublereal *dn, doublereal *dnm1, doublereal *dnm2) { /* System generated locals */ integer i__1; doublereal d__1, d__2; /* Local variables */ static doublereal d__; static integer j4, j4p2; static doublereal emin, temp; static doublereal safmin; /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University October 31, 1999 Purpose ======= DLASQ6 computes one dqd (shift equal to zero) transform in ping-pong form, with protection against underflow and overflow. Arguments ========= I0 (input) INTEGER First index. N0 (input) INTEGER Last index. Z (input) DOUBLE PRECISION array, dimension ( 4*N ) Z holds the qd array. EMIN is stored in Z(4*N0) to avoid an extra argument. PP (input) INTEGER PP=0 for ping, PP=1 for pong. DMIN (output) DOUBLE PRECISION Minimum value of d. DMIN1 (output) DOUBLE PRECISION Minimum value of d, excluding D( N0 ). DMIN2 (output) DOUBLE PRECISION Minimum value of d, excluding D( N0 ) and D( N0-1 ). DN (output) DOUBLE PRECISION d(N0), the last value of d. DNM1 (output) DOUBLE PRECISION d(N0-1). DNM2 (output) DOUBLE PRECISION d(N0-2). ===================================================================== */ /* Parameter adjustments */ --z__; /* Function Body */ if (*n0 - *i0 - 1 <= 0) { return 0; } safmin = SAFEMINIMUM; j4 = ((*i0) << (2)) + *pp - 3; emin = z__[j4 + 4]; d__ = z__[j4]; *dmin__ = d__; if (*pp == 0) { i__1 = (*n0 - 3) << (2); for (j4 = (*i0) << (2); j4 <= i__1; j4 += 4) { z__[j4 - 2] = d__ + z__[j4 - 1]; if (z__[j4 - 2] == 0.) { z__[j4] = 0.; d__ = z__[j4 + 1]; *dmin__ = d__; emin = 0.; } else if (safmin * z__[j4 + 1] < z__[j4 - 2] && safmin * z__[j4 - 2] < z__[j4 + 1]) { temp = z__[j4 + 1] / z__[j4 - 2]; z__[j4] = z__[j4 - 1] * temp; d__ *= temp; } else { z__[j4] = z__[j4 + 1] * (z__[j4 - 1] / z__[j4 - 2]); d__ = z__[j4 + 1] * (d__ / z__[j4 - 2]); } *dmin__ = min(*dmin__,d__); /* Computing MIN */ d__1 = emin, d__2 = z__[j4]; emin = min(d__1,d__2); /* L10: */ } } else { i__1 = (*n0 - 3) << (2); for (j4 = (*i0) << (2); j4 <= i__1; j4 += 4) { z__[j4 - 3] = d__ + z__[j4]; if (z__[j4 - 3] == 0.) { z__[j4 - 1] = 0.; d__ = z__[j4 + 2]; *dmin__ = d__; emin = 0.; } else if (safmin * z__[j4 + 2] < z__[j4 - 3] && safmin * z__[j4 - 3] < z__[j4 + 2]) { temp = z__[j4 + 2] / z__[j4 - 3]; z__[j4 - 1] = z__[j4] * temp; d__ *= temp; } else { z__[j4 - 1] = z__[j4 + 2] * (z__[j4] / z__[j4 - 3]); d__ = z__[j4 + 2] * (d__ / z__[j4 - 3]); } *dmin__ = min(*dmin__,d__); /* Computing MIN */ d__1 = emin, d__2 = z__[j4 - 1]; emin = min(d__1,d__2); /* L20: */ } } /* Unroll last two steps. */ *dnm2 = d__; *dmin2 = *dmin__; j4 = ((*n0 - 2) << (2)) - *pp; j4p2 = j4 + ((*pp) << (1)) - 1; z__[j4 - 2] = *dnm2 + z__[j4p2]; if (z__[j4 - 2] == 0.) { z__[j4] = 0.; *dnm1 = z__[j4p2 + 2]; *dmin__ = *dnm1; emin = 0.; } else if (safmin * z__[j4p2 + 2] < z__[j4 - 2] && safmin * z__[j4 - 2] < z__[j4p2 + 2]) { temp = z__[j4p2 + 2] / z__[j4 - 2]; z__[j4] = z__[j4p2] * temp; *dnm1 = *dnm2 * temp; } else { z__[j4] = z__[j4p2 + 2] * (z__[j4p2] / z__[j4 - 2]); *dnm1 = z__[j4p2 + 2] * (*dnm2 / z__[j4 - 2]); } *dmin__ = min(*dmin__,*dnm1); *dmin1 = *dmin__; j4 += 4; j4p2 = j4 + ((*pp) << (1)) - 1; z__[j4 - 2] = *dnm1 + z__[j4p2]; if (z__[j4 - 2] == 0.) { z__[j4] = 0.; *dn = z__[j4p2 + 2]; *dmin__ = *dn; emin = 0.; } else if (safmin * z__[j4p2 + 2] < z__[j4 - 2] && safmin * z__[j4 - 2] < z__[j4p2 + 2]) { temp = z__[j4p2 + 2] / z__[j4 - 2]; z__[j4] = z__[j4p2] * temp; *dn = *dnm1 * temp; } else { z__[j4] = z__[j4p2 + 2] * (z__[j4p2] / z__[j4 - 2]); *dn = z__[j4p2 + 2] * (*dnm1 / z__[j4 - 2]); } *dmin__ = min(*dmin__,*dn); z__[j4 + 2] = *dn; z__[((*n0) << (2)) - *pp] = emin; return 0; /* End of DLASQ6 */ } /* dlasq6_ */ /* Subroutine */ int dlasr_(char *side, char *pivot, char *direct, integer *m, integer *n, doublereal *c__, doublereal *s, doublereal *a, integer * lda) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2; /* Local variables */ static integer i__, j, info; static doublereal temp; extern logical lsame_(char *, char *); static doublereal ctemp, stemp; extern /* Subroutine */ int xerbla_(char *, integer *); /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University October 31, 1992 Purpose ======= DLASR performs the transformation A := P*A, when SIDE = 'L' or 'l' ( Left-hand side ) A := A*P', when SIDE = 'R' or 'r' ( Right-hand side ) where A is an m by n real matrix and P is an orthogonal matrix, consisting of a sequence of plane rotations determined by the parameters PIVOT and DIRECT as follows ( z = m when SIDE = 'L' or 'l' and z = n when SIDE = 'R' or 'r' ): When DIRECT = 'F' or 'f' ( Forward sequence ) then P = P( z - 1 )*...*P( 2 )*P( 1 ), and when DIRECT = 'B' or 'b' ( Backward sequence ) then P = P( 1 )*P( 2 )*...*P( z - 1 ), where P( k ) is a plane rotation matrix for the following planes: when PIVOT = 'V' or 'v' ( Variable pivot ), the plane ( k, k + 1 ) when PIVOT = 'T' or 't' ( Top pivot ), the plane ( 1, k + 1 ) when PIVOT = 'B' or 'b' ( Bottom pivot ), the plane ( k, z ) c( k ) and s( k ) must contain the cosine and sine that define the matrix P( k ). The two by two plane rotation part of the matrix P( k ), R( k ), is assumed to be of the form R( k ) = ( c( k ) s( k ) ). ( -s( k ) c( k ) ) This version vectorises across rows of the array A when SIDE = 'L'. Arguments ========= SIDE (input) CHARACTER*1 Specifies whether the plane rotation matrix P is applied to A on the left or the right. = 'L': Left, compute A := P*A = 'R': Right, compute A:= A*P' DIRECT (input) CHARACTER*1 Specifies whether P is a forward or backward sequence of plane rotations. = 'F': Forward, P = P( z - 1 )*...*P( 2 )*P( 1 ) = 'B': Backward, P = P( 1 )*P( 2 )*...*P( z - 1 ) PIVOT (input) CHARACTER*1 Specifies the plane for which P(k) is a plane rotation matrix. = 'V': Variable pivot, the plane (k,k+1) = 'T': Top pivot, the plane (1,k+1) = 'B': Bottom pivot, the plane (k,z) M (input) INTEGER The number of rows of the matrix A. If m <= 1, an immediate return is effected. N (input) INTEGER The number of columns of the matrix A. If n <= 1, an immediate return is effected. C, S (input) DOUBLE PRECISION arrays, dimension (M-1) if SIDE = 'L' (N-1) if SIDE = 'R' c(k) and s(k) contain the cosine and sine that define the matrix P(k). The two by two plane rotation part of the matrix P(k), R(k), is assumed to be of the form R( k ) = ( c( k ) s( k ) ). ( -s( k ) c( k ) ) A (input/output) DOUBLE PRECISION array, dimension (LDA,N) The m by n matrix A. On exit, A is overwritten by P*A if SIDE = 'R' or by A*P' if SIDE = 'L'. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,M). ===================================================================== Test the input parameters */ /* Parameter adjustments */ --c__; --s; a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; /* Function Body */ info = 0; if (! ((lsame_(side, "L")) || (lsame_(side, "R")))) { info = 1; } else if (! (((lsame_(pivot, "V")) || (lsame_( pivot, "T"))) || (lsame_(pivot, "B")))) { info = 2; } else if (! ((lsame_(direct, "F")) || (lsame_( direct, "B")))) { info = 3; } else if (*m < 0) { info = 4; } else if (*n < 0) { info = 5; } else if (*lda < max(1,*m)) { info = 9; } if (info != 0) { xerbla_("DLASR ", &info); return 0; } /* Quick return if possible */ if ((*m == 0) || (*n == 0)) { return 0; } if (lsame_(side, "L")) { /* Form P * A */ if (lsame_(pivot, "V")) { if (lsame_(direct, "F")) { i__1 = *m - 1; for (j = 1; j <= i__1; ++j) { ctemp = c__[j]; stemp = s[j]; if ((ctemp != 1.) || (stemp != 0.)) { i__2 = *n; for (i__ = 1; i__ <= i__2; ++i__) { temp = a[j + 1 + i__ * a_dim1]; a[j + 1 + i__ * a_dim1] = ctemp * temp - stemp * a[j + i__ * a_dim1]; a[j + i__ * a_dim1] = stemp * temp + ctemp * a[j + i__ * a_dim1]; /* L10: */ } } /* L20: */ } } else if (lsame_(direct, "B")) { for (j = *m - 1; j >= 1; --j) { ctemp = c__[j]; stemp = s[j]; if ((ctemp != 1.) || (stemp != 0.)) { i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { temp = a[j + 1 + i__ * a_dim1]; a[j + 1 + i__ * a_dim1] = ctemp * temp - stemp * a[j + i__ * a_dim1]; a[j + i__ * a_dim1] = stemp * temp + ctemp * a[j + i__ * a_dim1]; /* L30: */ } } /* L40: */ } } } else if (lsame_(pivot, "T")) { if (lsame_(direct, "F")) { i__1 = *m; for (j = 2; j <= i__1; ++j) { ctemp = c__[j - 1]; stemp = s[j - 1]; if ((ctemp != 1.) || (stemp != 0.)) { i__2 = *n; for (i__ = 1; i__ <= i__2; ++i__) { temp = a[j + i__ * a_dim1]; a[j + i__ * a_dim1] = ctemp * temp - stemp * a[ i__ * a_dim1 + 1]; a[i__ * a_dim1 + 1] = stemp * temp + ctemp * a[ i__ * a_dim1 + 1]; /* L50: */ } } /* L60: */ } } else if (lsame_(direct, "B")) { for (j = *m; j >= 2; --j) { ctemp = c__[j - 1]; stemp = s[j - 1]; if ((ctemp != 1.) || (stemp != 0.)) { i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { temp = a[j + i__ * a_dim1]; a[j + i__ * a_dim1] = ctemp * temp - stemp * a[ i__ * a_dim1 + 1]; a[i__ * a_dim1 + 1] = stemp * temp + ctemp * a[ i__ * a_dim1 + 1]; /* L70: */ } } /* L80: */ } } } else if (lsame_(pivot, "B")) { if (lsame_(direct, "F")) { i__1 = *m - 1; for (j = 1; j <= i__1; ++j) { ctemp = c__[j]; stemp = s[j]; if ((ctemp != 1.) || (stemp != 0.)) { i__2 = *n; for (i__ = 1; i__ <= i__2; ++i__) { temp = a[j + i__ * a_dim1]; a[j + i__ * a_dim1] = stemp * a[*m + i__ * a_dim1] + ctemp * temp; a[*m + i__ * a_dim1] = ctemp * a[*m + i__ * a_dim1] - stemp * temp; /* L90: */ } } /* L100: */ } } else if (lsame_(direct, "B")) { for (j = *m - 1; j >= 1; --j) { ctemp = c__[j]; stemp = s[j]; if ((ctemp != 1.) || (stemp != 0.)) { i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { temp = a[j + i__ * a_dim1]; a[j + i__ * a_dim1] = stemp * a[*m + i__ * a_dim1] + ctemp * temp; a[*m + i__ * a_dim1] = ctemp * a[*m + i__ * a_dim1] - stemp * temp; /* L110: */ } } /* L120: */ } } } } else if (lsame_(side, "R")) { /* Form A * P' */ if (lsame_(pivot, "V")) { if (lsame_(direct, "F")) { i__1 = *n - 1; for (j = 1; j <= i__1; ++j) { ctemp = c__[j]; stemp = s[j]; if ((ctemp != 1.) || (stemp != 0.)) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { temp = a[i__ + (j + 1) * a_dim1]; a[i__ + (j + 1) * a_dim1] = ctemp * temp - stemp * a[i__ + j * a_dim1]; a[i__ + j * a_dim1] = stemp * temp + ctemp * a[ i__ + j * a_dim1]; /* L130: */ } } /* L140: */ } } else if (lsame_(direct, "B")) { for (j = *n - 1; j >= 1; --j) { ctemp = c__[j]; stemp = s[j]; if ((ctemp != 1.) || (stemp != 0.)) { i__1 = *m; for (i__ = 1; i__ <= i__1; ++i__) { temp = a[i__ + (j + 1) * a_dim1]; a[i__ + (j + 1) * a_dim1] = ctemp * temp - stemp * a[i__ + j * a_dim1]; a[i__ + j * a_dim1] = stemp * temp + ctemp * a[ i__ + j * a_dim1]; /* L150: */ } } /* L160: */ } } } else if (lsame_(pivot, "T")) { if (lsame_(direct, "F")) { i__1 = *n; for (j = 2; j <= i__1; ++j) { ctemp = c__[j - 1]; stemp = s[j - 1]; if ((ctemp != 1.) || (stemp != 0.)) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { temp = a[i__ + j * a_dim1]; a[i__ + j * a_dim1] = ctemp * temp - stemp * a[ i__ + a_dim1]; a[i__ + a_dim1] = stemp * temp + ctemp * a[i__ + a_dim1]; /* L170: */ } } /* L180: */ } } else if (lsame_(direct, "B")) { for (j = *n; j >= 2; --j) { ctemp = c__[j - 1]; stemp = s[j - 1]; if ((ctemp != 1.) || (stemp != 0.)) { i__1 = *m; for (i__ = 1; i__ <= i__1; ++i__) { temp = a[i__ + j * a_dim1]; a[i__ + j * a_dim1] = ctemp * temp - stemp * a[ i__ + a_dim1]; a[i__ + a_dim1] = stemp * temp + ctemp * a[i__ + a_dim1]; /* L190: */ } } /* L200: */ } } } else if (lsame_(pivot, "B")) { if (lsame_(direct, "F")) { i__1 = *n - 1; for (j = 1; j <= i__1; ++j) { ctemp = c__[j]; stemp = s[j]; if ((ctemp != 1.) || (stemp != 0.)) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { temp = a[i__ + j * a_dim1]; a[i__ + j * a_dim1] = stemp * a[i__ + *n * a_dim1] + ctemp * temp; a[i__ + *n * a_dim1] = ctemp * a[i__ + *n * a_dim1] - stemp * temp; /* L210: */ } } /* L220: */ } } else if (lsame_(direct, "B")) { for (j = *n - 1; j >= 1; --j) { ctemp = c__[j]; stemp = s[j]; if ((ctemp != 1.) || (stemp != 0.)) { i__1 = *m; for (i__ = 1; i__ <= i__1; ++i__) { temp = a[i__ + j * a_dim1]; a[i__ + j * a_dim1] = stemp * a[i__ + *n * a_dim1] + ctemp * temp; a[i__ + *n * a_dim1] = ctemp * a[i__ + *n * a_dim1] - stemp * temp; /* L230: */ } } /* L240: */ } } } } return 0; /* End of DLASR */ } /* dlasr_ */ /* Subroutine */ int dlasrt_(char *id, integer *n, doublereal *d__, integer * info) { /* System generated locals */ integer i__1, i__2; /* Local variables */ static integer i__, j; static doublereal d1, d2, d3; static integer dir; static doublereal tmp; static integer endd; extern logical lsame_(char *, char *); static integer stack[64] /* was [2][32] */; static doublereal dmnmx; static integer start; extern /* Subroutine */ int xerbla_(char *, integer *); static integer stkpnt; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University September 30, 1994 Purpose ======= Sort the numbers in D in increasing order (if ID = 'I') or in decreasing order (if ID = 'D' ). Use Quick Sort, reverting to Insertion sort on arrays of size <= 20. Dimension of STACK limits N to about 2**32. Arguments ========= ID (input) CHARACTER*1 = 'I': sort D in increasing order; = 'D': sort D in decreasing order. N (input) INTEGER The length of the array D. D (input/output) DOUBLE PRECISION array, dimension (N) On entry, the array to be sorted. On exit, D has been sorted into increasing order (D(1) <= ... <= D(N) ) or into decreasing order (D(1) >= ... >= D(N) ), depending on ID. INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value ===================================================================== Test the input paramters. */ /* Parameter adjustments */ --d__; /* Function Body */ *info = 0; dir = -1; if (lsame_(id, "D")) { dir = 0; } else if (lsame_(id, "I")) { dir = 1; } if (dir == -1) { *info = -1; } else if (*n < 0) { *info = -2; } if (*info != 0) { i__1 = -(*info); xerbla_("DLASRT", &i__1); return 0; } /* Quick return if possible */ if (*n <= 1) { return 0; } stkpnt = 1; stack[0] = 1; stack[1] = *n; L10: start = stack[((stkpnt) << (1)) - 2]; endd = stack[((stkpnt) << (1)) - 1]; --stkpnt; if (endd - start <= 20 && endd - start > 0) { /* Do Insertion sort on D( START:ENDD ) */ if (dir == 0) { /* Sort into decreasing order */ i__1 = endd; for (i__ = start + 1; i__ <= i__1; ++i__) { i__2 = start + 1; for (j = i__; j >= i__2; --j) { if (d__[j] > d__[j - 1]) { dmnmx = d__[j]; d__[j] = d__[j - 1]; d__[j - 1] = dmnmx; } else { goto L30; } /* L20: */ } L30: ; } } else { /* Sort into increasing order */ i__1 = endd; for (i__ = start + 1; i__ <= i__1; ++i__) { i__2 = start + 1; for (j = i__; j >= i__2; --j) { if (d__[j] < d__[j - 1]) { dmnmx = d__[j]; d__[j] = d__[j - 1]; d__[j - 1] = dmnmx; } else { goto L50; } /* L40: */ } L50: ; } } } else if (endd - start > 20) { /* Partition D( START:ENDD ) and stack parts, largest one first Choose partition entry as median of 3 */ d1 = d__[start]; d2 = d__[endd]; i__ = (start + endd) / 2; d3 = d__[i__]; if (d1 < d2) { if (d3 < d1) { dmnmx = d1; } else if (d3 < d2) { dmnmx = d3; } else { dmnmx = d2; } } else { if (d3 < d2) { dmnmx = d2; } else if (d3 < d1) { dmnmx = d3; } else { dmnmx = d1; } } if (dir == 0) { /* Sort into decreasing order */ i__ = start - 1; j = endd + 1; L60: L70: --j; if (d__[j] < dmnmx) { goto L70; } L80: ++i__; if (d__[i__] > dmnmx) { goto L80; } if (i__ < j) { tmp = d__[i__]; d__[i__] = d__[j]; d__[j] = tmp; goto L60; } if (j - start > endd - j - 1) { ++stkpnt; stack[((stkpnt) << (1)) - 2] = start; stack[((stkpnt) << (1)) - 1] = j; ++stkpnt; stack[((stkpnt) << (1)) - 2] = j + 1; stack[((stkpnt) << (1)) - 1] = endd; } else { ++stkpnt; stack[((stkpnt) << (1)) - 2] = j + 1; stack[((stkpnt) << (1)) - 1] = endd; ++stkpnt; stack[((stkpnt) << (1)) - 2] = start; stack[((stkpnt) << (1)) - 1] = j; } } else { /* Sort into increasing order */ i__ = start - 1; j = endd + 1; L90: L100: --j; if (d__[j] > dmnmx) { goto L100; } L110: ++i__; if (d__[i__] < dmnmx) { goto L110; } if (i__ < j) { tmp = d__[i__]; d__[i__] = d__[j]; d__[j] = tmp; goto L90; } if (j - start > endd - j - 1) { ++stkpnt; stack[((stkpnt) << (1)) - 2] = start; stack[((stkpnt) << (1)) - 1] = j; ++stkpnt; stack[((stkpnt) << (1)) - 2] = j + 1; stack[((stkpnt) << (1)) - 1] = endd; } else { ++stkpnt; stack[((stkpnt) << (1)) - 2] = j + 1; stack[((stkpnt) << (1)) - 1] = endd; ++stkpnt; stack[((stkpnt) << (1)) - 2] = start; stack[((stkpnt) << (1)) - 1] = j; } } } if (stkpnt > 0) { goto L10; } return 0; /* End of DLASRT */ } /* dlasrt_ */ /* Subroutine */ int dlassq_(integer *n, doublereal *x, integer *incx, doublereal *scale, doublereal *sumsq) { /* System generated locals */ integer i__1, i__2; doublereal d__1; /* Local variables */ static integer ix; static doublereal absxi; /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= DLASSQ returns the values scl and smsq such that ( scl**2 )*smsq = x( 1 )**2 +...+ x( n )**2 + ( scale**2 )*sumsq, where x( i ) = X( 1 + ( i - 1 )*INCX ). The value of sumsq is assumed to be non-negative and scl returns the value scl = max( scale, abs( x( i ) ) ). scale and sumsq must be supplied in SCALE and SUMSQ and scl and smsq are overwritten on SCALE and SUMSQ respectively. The routine makes only one pass through the vector x. Arguments ========= N (input) INTEGER The number of elements to be used from the vector X. X (input) DOUBLE PRECISION array, dimension (N) The vector for which a scaled sum of squares is computed. x( i ) = X( 1 + ( i - 1 )*INCX ), 1 <= i <= n. INCX (input) INTEGER The increment between successive values of the vector X. INCX > 0. SCALE (input/output) DOUBLE PRECISION On entry, the value scale in the equation above. On exit, SCALE is overwritten with scl , the scaling factor for the sum of squares. SUMSQ (input/output) DOUBLE PRECISION On entry, the value sumsq in the equation above. On exit, SUMSQ is overwritten with smsq , the basic sum of squares from which scl has been factored out. ===================================================================== */ /* Parameter adjustments */ --x; /* Function Body */ if (*n > 0) { i__1 = (*n - 1) * *incx + 1; i__2 = *incx; for (ix = 1; i__2 < 0 ? ix >= i__1 : ix <= i__1; ix += i__2) { if (x[ix] != 0.) { absxi = (d__1 = x[ix], abs(d__1)); if (*scale < absxi) { /* Computing 2nd power */ d__1 = *scale / absxi; *sumsq = *sumsq * (d__1 * d__1) + 1; *scale = absxi; } else { /* Computing 2nd power */ d__1 = absxi / *scale; *sumsq += d__1 * d__1; } } /* L10: */ } } return 0; /* End of DLASSQ */ } /* dlassq_ */ /* Subroutine */ int dlasv2_(doublereal *f, doublereal *g, doublereal *h__, doublereal *ssmin, doublereal *ssmax, doublereal *snr, doublereal * csr, doublereal *snl, doublereal *csl) { /* System generated locals */ doublereal d__1; /* Builtin functions */ double sqrt(doublereal), d_sign(doublereal *, doublereal *); /* Local variables */ static doublereal a, d__, l, m, r__, s, t, fa, ga, ha, ft, gt, ht, mm, tt, clt, crt, slt, srt; static integer pmax; static doublereal temp; static logical swap; static doublereal tsign; static logical gasmal; /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University October 31, 1992 Purpose ======= DLASV2 computes the singular value decomposition of a 2-by-2 triangular matrix [ F G ] [ 0 H ]. On return, abs(SSMAX) is the larger singular value, abs(SSMIN) is the smaller singular value, and (CSL,SNL) and (CSR,SNR) are the left and right singular vectors for abs(SSMAX), giving the decomposition [ CSL SNL ] [ F G ] [ CSR -SNR ] = [ SSMAX 0 ] [-SNL CSL ] [ 0 H ] [ SNR CSR ] [ 0 SSMIN ]. Arguments ========= F (input) DOUBLE PRECISION The (1,1) element of the 2-by-2 matrix. G (input) DOUBLE PRECISION The (1,2) element of the 2-by-2 matrix. H (input) DOUBLE PRECISION The (2,2) element of the 2-by-2 matrix. SSMIN (output) DOUBLE PRECISION abs(SSMIN) is the smaller singular value. SSMAX (output) DOUBLE PRECISION abs(SSMAX) is the larger singular value. SNL (output) DOUBLE PRECISION CSL (output) DOUBLE PRECISION The vector (CSL, SNL) is a unit left singular vector for the singular value abs(SSMAX). SNR (output) DOUBLE PRECISION CSR (output) DOUBLE PRECISION The vector (CSR, SNR) is a unit right singular vector for the singular value abs(SSMAX). Further Details =============== Any input parameter may be aliased with any output parameter. Barring over/underflow and assuming a guard digit in subtraction, all output quantities are correct to within a few units in the last place (ulps). In IEEE arithmetic, the code works correctly if one matrix element is infinite. Overflow will not occur unless the largest singular value itself overflows or is within a few ulps of overflow. (On machines with partial overflow, like the Cray, overflow may occur if the largest singular value is within a factor of 2 of overflow.) Underflow is harmless if underflow is gradual. Otherwise, results may correspond to a matrix modified by perturbations of size near the underflow threshold. ===================================================================== */ ft = *f; fa = abs(ft); ht = *h__; ha = abs(*h__); /* PMAX points to the maximum absolute element of matrix PMAX = 1 if F largest in absolute values PMAX = 2 if G largest in absolute values PMAX = 3 if H largest in absolute values */ pmax = 1; swap = ha > fa; if (swap) { pmax = 3; temp = ft; ft = ht; ht = temp; temp = fa; fa = ha; ha = temp; /* Now FA .ge. HA */ } gt = *g; ga = abs(gt); if (ga == 0.) { /* Diagonal matrix */ *ssmin = ha; *ssmax = fa; clt = 1.; crt = 1.; slt = 0.; srt = 0.; } else { gasmal = TRUE_; if (ga > fa) { pmax = 2; if (fa / ga < EPSILON) { /* Case of very large GA */ gasmal = FALSE_; *ssmax = ga; if (ha > 1.) { *ssmin = fa / (ga / ha); } else { *ssmin = fa / ga * ha; } clt = 1.; slt = ht / gt; srt = 1.; crt = ft / gt; } } if (gasmal) { /* Normal case */ d__ = fa - ha; if (d__ == fa) { /* Copes with infinite F or H */ l = 1.; } else { l = d__ / fa; } /* Note that 0 .le. L .le. 1 */ m = gt / ft; /* Note that abs(M) .le. 1/macheps */ t = 2. - l; /* Note that T .ge. 1 */ mm = m * m; tt = t * t; s = sqrt(tt + mm); /* Note that 1 .le. S .le. 1 + 1/macheps */ if (l == 0.) { r__ = abs(m); } else { r__ = sqrt(l * l + mm); } /* Note that 0 .le. R .le. 1 + 1/macheps */ a = (s + r__) * .5; /* Note that 1 .le. A .le. 1 + abs(M) */ *ssmin = ha / a; *ssmax = fa * a; if (mm == 0.) { /* Note that M is very tiny */ if (l == 0.) { t = d_sign(&c_b5654, &ft) * d_sign(&c_b2865, >); } else { t = gt / d_sign(&d__, &ft) + m / t; } } else { t = (m / (s + t) + m / (r__ + l)) * (a + 1.); } l = sqrt(t * t + 4.); crt = 2. / l; srt = t / l; clt = (crt + srt * m) / a; slt = ht / ft * srt / a; } } if (swap) { *csl = srt; *snl = crt; *csr = slt; *snr = clt; } else { *csl = clt; *snl = slt; *csr = crt; *snr = srt; } /* Correct signs of SSMAX and SSMIN */ if (pmax == 1) { tsign = d_sign(&c_b2865, csr) * d_sign(&c_b2865, csl) * d_sign(& c_b2865, f); } if (pmax == 2) { tsign = d_sign(&c_b2865, snr) * d_sign(&c_b2865, csl) * d_sign(& c_b2865, g); } if (pmax == 3) { tsign = d_sign(&c_b2865, snr) * d_sign(&c_b2865, snl) * d_sign(& c_b2865, h__); } *ssmax = d_sign(ssmax, &tsign); d__1 = tsign * d_sign(&c_b2865, f) * d_sign(&c_b2865, h__); *ssmin = d_sign(ssmin, &d__1); return 0; /* End of DLASV2 */ } /* dlasv2_ */ /* Subroutine */ int dlaswp_(integer *n, doublereal *a, integer *lda, integer *k1, integer *k2, integer *ipiv, integer *incx) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3, i__4; /* Local variables */ static integer i__, j, k, i1, i2, n32, ip, ix, ix0, inc; static doublereal temp; /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= DLASWP performs a series of row interchanges on the matrix A. One row interchange is initiated for each of rows K1 through K2 of A. Arguments ========= N (input) INTEGER The number of columns of the matrix A. A (input/output) DOUBLE PRECISION array, dimension (LDA,N) On entry, the matrix of column dimension N to which the row interchanges will be applied. On exit, the permuted matrix. LDA (input) INTEGER The leading dimension of the array A. K1 (input) INTEGER The first element of IPIV for which a row interchange will be done. K2 (input) INTEGER The last element of IPIV for which a row interchange will be done. IPIV (input) INTEGER array, dimension (M*abs(INCX)) The vector of pivot indices. Only the elements in positions K1 through K2 of IPIV are accessed. IPIV(K) = L implies rows K and L are to be interchanged. INCX (input) INTEGER The increment between successive values of IPIV. If IPIV is negative, the pivots are applied in reverse order. Further Details =============== Modified by R. C. Whaley, Computer Science Dept., Univ. of Tenn., Knoxville, USA ===================================================================== Interchange row I with row IPIV(I) for each of rows K1 through K2. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --ipiv; /* Function Body */ if (*incx > 0) { ix0 = *k1; i1 = *k1; i2 = *k2; inc = 1; } else if (*incx < 0) { ix0 = (1 - *k2) * *incx + 1; i1 = *k2; i2 = *k1; inc = -1; } else { return 0; } n32 = (*n / 32) << (5); if (n32 != 0) { i__1 = n32; for (j = 1; j <= i__1; j += 32) { ix = ix0; i__2 = i2; i__3 = inc; for (i__ = i1; i__3 < 0 ? i__ >= i__2 : i__ <= i__2; i__ += i__3) { ip = ipiv[ix]; if (ip != i__) { i__4 = j + 31; for (k = j; k <= i__4; ++k) { temp = a[i__ + k * a_dim1]; a[i__ + k * a_dim1] = a[ip + k * a_dim1]; a[ip + k * a_dim1] = temp; /* L10: */ } } ix += *incx; /* L20: */ } /* L30: */ } } if (n32 != *n) { ++n32; ix = ix0; i__1 = i2; i__3 = inc; for (i__ = i1; i__3 < 0 ? i__ >= i__1 : i__ <= i__1; i__ += i__3) { ip = ipiv[ix]; if (ip != i__) { i__2 = *n; for (k = n32; k <= i__2; ++k) { temp = a[i__ + k * a_dim1]; a[i__ + k * a_dim1] = a[ip + k * a_dim1]; a[ip + k * a_dim1] = temp; /* L40: */ } } ix += *incx; /* L50: */ } } return 0; /* End of DLASWP */ } /* dlaswp_ */ /* Subroutine */ int dlatrd_(char *uplo, integer *n, integer *nb, doublereal * a, integer *lda, doublereal *e, doublereal *tau, doublereal *w, integer *ldw) { /* System generated locals */ integer a_dim1, a_offset, w_dim1, w_offset, i__1, i__2, i__3; /* Local variables */ static integer i__, iw; extern doublereal ddot_(integer *, doublereal *, integer *, doublereal *, integer *); static doublereal alpha; extern /* Subroutine */ int dscal_(integer *, doublereal *, doublereal *, integer *); extern logical lsame_(char *, char *); extern /* Subroutine */ int dgemv_(char *, integer *, integer *, doublereal *, doublereal *, integer *, doublereal *, integer *, doublereal *, doublereal *, integer *), daxpy_(integer *, doublereal *, doublereal *, integer *, doublereal *, integer *), dsymv_(char *, integer *, doublereal *, doublereal *, integer *, doublereal *, integer *, doublereal *, doublereal *, integer *), dlarfg_(integer *, doublereal *, doublereal *, integer *, doublereal *); /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University October 31, 1992 Purpose ======= DLATRD reduces NB rows and columns of a real symmetric matrix A to symmetric tridiagonal form by an orthogonal similarity transformation Q' * A * Q, and returns the matrices V and W which are needed to apply the transformation to the unreduced part of A. If UPLO = 'U', DLATRD reduces the last NB rows and columns of a matrix, of which the upper triangle is supplied; if UPLO = 'L', DLATRD reduces the first NB rows and columns of a matrix, of which the lower triangle is supplied. This is an auxiliary routine called by DSYTRD. Arguments ========= UPLO (input) CHARACTER Specifies whether the upper or lower triangular part of the symmetric matrix A is stored: = 'U': Upper triangular = 'L': Lower triangular N (input) INTEGER The order of the matrix A. NB (input) INTEGER The number of rows and columns to be reduced. 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, and the strictly lower triangular part of A is not referenced. If UPLO = 'L', the leading n-by-n lower triangular part of A contains the lower triangular part of the matrix A, and the strictly upper triangular part of A is not referenced. On exit: if UPLO = 'U', the last NB columns have been reduced to tridiagonal form, with the diagonal elements overwriting the diagonal elements of A; the elements above the diagonal with the array TAU, represent the orthogonal matrix Q as a product of elementary reflectors; if UPLO = 'L', the first NB columns have been reduced to tridiagonal form, with the diagonal elements overwriting the diagonal elements of A; the elements below the diagonal with the array TAU, represent the orthogonal matrix Q as a product of elementary reflectors. See Further Details. LDA (input) INTEGER The leading dimension of the array A. LDA >= (1,N). E (output) DOUBLE PRECISION array, dimension (N-1) If UPLO = 'U', E(n-nb:n-1) contains the superdiagonal elements of the last NB columns of the reduced matrix; if UPLO = 'L', E(1:nb) contains the subdiagonal elements of the first NB columns of the reduced matrix. TAU (output) DOUBLE PRECISION array, dimension (N-1) The scalar factors of the elementary reflectors, stored in TAU(n-nb:n-1) if UPLO = 'U', and in TAU(1:nb) if UPLO = 'L'. See Further Details. W (output) DOUBLE PRECISION array, dimension (LDW,NB) The n-by-nb matrix W required to update the unreduced part of A. LDW (input) INTEGER The leading dimension of the array W. LDW >= max(1,N). Further Details =============== If UPLO = 'U', the matrix Q is represented as a product of elementary reflectors Q = H(n) H(n-1) . . . H(n-nb+1). Each H(i) has the form H(i) = I - tau * v * v' where tau is a real scalar, and v is a real vector with v(i:n) = 0 and v(i-1) = 1; v(1:i-1) is stored on exit in A(1:i-1,i), and tau in TAU(i-1). If UPLO = 'L', the matrix Q is represented as a product of elementary reflectors Q = H(1) H(2) . . . H(nb). Each H(i) has the form H(i) = I - tau * v * v' where tau is a real scalar, and v is a real vector with v(1:i) = 0 and v(i+1) = 1; v(i+1:n) is stored on exit in A(i+1:n,i), and tau in TAU(i). The elements of the vectors v together form the n-by-nb matrix V which is needed, with W, to apply the transformation to the unreduced part of the matrix, using a symmetric rank-2k update of the form: A := A - V*W' - W*V'. The contents of A on exit are illustrated by the following examples with n = 5 and nb = 2: if UPLO = 'U': if UPLO = 'L': ( a a a v4 v5 ) ( d ) ( a a v4 v5 ) ( 1 d ) ( a 1 v5 ) ( v1 1 a ) ( d 1 ) ( v1 v2 a a ) ( d ) ( v1 v2 a a a ) where d denotes a diagonal element of the reduced matrix, a denotes an element of the original matrix that is unchanged, and vi denotes an element of the vector defining H(i). ===================================================================== Quick return if possible */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --e; --tau; w_dim1 = *ldw; w_offset = 1 + w_dim1; w -= w_offset; /* Function Body */ if (*n <= 0) { return 0; } if (lsame_(uplo, "U")) { /* Reduce last NB columns of upper triangle */ i__1 = *n - *nb + 1; for (i__ = *n; i__ >= i__1; --i__) { iw = i__ - *n + *nb; if (i__ < *n) { /* Update A(1:i,i) */ i__2 = *n - i__; dgemv_("No transpose", &i__, &i__2, &c_b3001, &a[(i__ + 1) * a_dim1 + 1], lda, &w[i__ + (iw + 1) * w_dim1], ldw, & c_b2865, &a[i__ * a_dim1 + 1], &c__1); i__2 = *n - i__; dgemv_("No transpose", &i__, &i__2, &c_b3001, &w[(iw + 1) * w_dim1 + 1], ldw, &a[i__ + (i__ + 1) * a_dim1], lda, & c_b2865, &a[i__ * a_dim1 + 1], &c__1); } if (i__ > 1) { /* Generate elementary reflector H(i) to annihilate A(1:i-2,i) */ i__2 = i__ - 1; dlarfg_(&i__2, &a[i__ - 1 + i__ * a_dim1], &a[i__ * a_dim1 + 1], &c__1, &tau[i__ - 1]); e[i__ - 1] = a[i__ - 1 + i__ * a_dim1]; a[i__ - 1 + i__ * a_dim1] = 1.; /* Compute W(1:i-1,i) */ i__2 = i__ - 1; dsymv_("Upper", &i__2, &c_b2865, &a[a_offset], lda, &a[i__ * a_dim1 + 1], &c__1, &c_b2879, &w[iw * w_dim1 + 1], & c__1); if (i__ < *n) { i__2 = i__ - 1; i__3 = *n - i__; dgemv_("Transpose", &i__2, &i__3, &c_b2865, &w[(iw + 1) * w_dim1 + 1], ldw, &a[i__ * a_dim1 + 1], &c__1, & c_b2879, &w[i__ + 1 + iw * w_dim1], &c__1); i__2 = i__ - 1; i__3 = *n - i__; dgemv_("No transpose", &i__2, &i__3, &c_b3001, &a[(i__ + 1) * a_dim1 + 1], lda, &w[i__ + 1 + iw * w_dim1], &c__1, &c_b2865, &w[iw * w_dim1 + 1], &c__1); i__2 = i__ - 1; i__3 = *n - i__; dgemv_("Transpose", &i__2, &i__3, &c_b2865, &a[(i__ + 1) * a_dim1 + 1], lda, &a[i__ * a_dim1 + 1], &c__1, & c_b2879, &w[i__ + 1 + iw * w_dim1], &c__1); i__2 = i__ - 1; i__3 = *n - i__; dgemv_("No transpose", &i__2, &i__3, &c_b3001, &w[(iw + 1) * w_dim1 + 1], ldw, &w[i__ + 1 + iw * w_dim1], & c__1, &c_b2865, &w[iw * w_dim1 + 1], &c__1); } i__2 = i__ - 1; dscal_(&i__2, &tau[i__ - 1], &w[iw * w_dim1 + 1], &c__1); i__2 = i__ - 1; alpha = tau[i__ - 1] * -.5 * ddot_(&i__2, &w[iw * w_dim1 + 1], &c__1, &a[i__ * a_dim1 + 1], &c__1); i__2 = i__ - 1; daxpy_(&i__2, &alpha, &a[i__ * a_dim1 + 1], &c__1, &w[iw * w_dim1 + 1], &c__1); } /* L10: */ } } else { /* Reduce first NB columns of lower triangle */ i__1 = *nb; for (i__ = 1; i__ <= i__1; ++i__) { /* Update A(i:n,i) */ i__2 = *n - i__ + 1; i__3 = i__ - 1; dgemv_("No transpose", &i__2, &i__3, &c_b3001, &a[i__ + a_dim1], lda, &w[i__ + w_dim1], ldw, &c_b2865, &a[i__ + i__ * a_dim1], &c__1); i__2 = *n - i__ + 1; i__3 = i__ - 1; dgemv_("No transpose", &i__2, &i__3, &c_b3001, &w[i__ + w_dim1], ldw, &a[i__ + a_dim1], lda, &c_b2865, &a[i__ + i__ * a_dim1], &c__1); if (i__ < *n) { /* Generate elementary reflector H(i) to annihilate A(i+2:n,i) */ i__2 = *n - i__; /* Computing MIN */ i__3 = i__ + 2; dlarfg_(&i__2, &a[i__ + 1 + i__ * a_dim1], &a[min(i__3,*n) + i__ * a_dim1], &c__1, &tau[i__]); e[i__] = a[i__ + 1 + i__ * a_dim1]; a[i__ + 1 + i__ * a_dim1] = 1.; /* Compute W(i+1:n,i) */ i__2 = *n - i__; dsymv_("Lower", &i__2, &c_b2865, &a[i__ + 1 + (i__ + 1) * a_dim1], lda, &a[i__ + 1 + i__ * a_dim1], &c__1, & c_b2879, &w[i__ + 1 + i__ * w_dim1], &c__1) ; i__2 = *n - i__; i__3 = i__ - 1; dgemv_("Transpose", &i__2, &i__3, &c_b2865, &w[i__ + 1 + w_dim1], ldw, &a[i__ + 1 + i__ * a_dim1], &c__1, & c_b2879, &w[i__ * w_dim1 + 1], &c__1); i__2 = *n - i__; i__3 = i__ - 1; dgemv_("No transpose", &i__2, &i__3, &c_b3001, &a[i__ + 1 + a_dim1], lda, &w[i__ * w_dim1 + 1], &c__1, &c_b2865, & w[i__ + 1 + i__ * w_dim1], &c__1); i__2 = *n - i__; i__3 = i__ - 1; dgemv_("Transpose", &i__2, &i__3, &c_b2865, &a[i__ + 1 + a_dim1], lda, &a[i__ + 1 + i__ * a_dim1], &c__1, & c_b2879, &w[i__ * w_dim1 + 1], &c__1); i__2 = *n - i__; i__3 = i__ - 1; dgemv_("No transpose", &i__2, &i__3, &c_b3001, &w[i__ + 1 + w_dim1], ldw, &w[i__ * w_dim1 + 1], &c__1, &c_b2865, & w[i__ + 1 + i__ * w_dim1], &c__1); i__2 = *n - i__; dscal_(&i__2, &tau[i__], &w[i__ + 1 + i__ * w_dim1], &c__1); i__2 = *n - i__; alpha = tau[i__] * -.5 * ddot_(&i__2, &w[i__ + 1 + i__ * w_dim1], &c__1, &a[i__ + 1 + i__ * a_dim1], &c__1); i__2 = *n - i__; daxpy_(&i__2, &alpha, &a[i__ + 1 + i__ * a_dim1], &c__1, &w[ i__ + 1 + i__ * w_dim1], &c__1); } /* L20: */ } } return 0; /* End of DLATRD */ } /* dlatrd_ */ /* Subroutine */ int dlauu2_(char *uplo, integer *n, doublereal *a, integer * lda, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3; /* Local variables */ static integer i__; static doublereal aii; extern doublereal ddot_(integer *, doublereal *, integer *, doublereal *, integer *); extern /* Subroutine */ int dscal_(integer *, doublereal *, doublereal *, integer *); extern logical lsame_(char *, char *); extern /* Subroutine */ int dgemv_(char *, integer *, integer *, doublereal *, doublereal *, integer *, doublereal *, integer *, doublereal *, doublereal *, integer *); static logical upper; extern /* Subroutine */ int xerbla_(char *, integer *); /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University February 29, 1992 Purpose ======= DLAUU2 computes the product U * U' or L' * L, where the triangular factor U or L is stored in the upper or lower triangular part of the array A. If UPLO = 'U' or 'u' then the upper triangle of the result is stored, overwriting the factor U in A. If UPLO = 'L' or 'l' then the lower triangle of the result is stored, overwriting the factor L in A. This is the unblocked form of the algorithm, calling Level 2 BLAS. Arguments ========= UPLO (input) CHARACTER*1 Specifies whether the triangular factor stored in the array A is upper or lower triangular: = 'U': Upper triangular = 'L': Lower triangular N (input) INTEGER The order of the triangular factor U or L. N >= 0. A (input/output) DOUBLE PRECISION array, dimension (LDA,N) On entry, the triangular factor U or L. On exit, if UPLO = 'U', the upper triangle of A is overwritten with the upper triangle of the product U * U'; if UPLO = 'L', the lower triangle of A is overwritten with the lower triangle of the product L' * L. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,N). INFO (output) INTEGER = 0: successful exit < 0: if INFO = -k, the k-th argument had an illegal value ===================================================================== Test the input parameters. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; /* Function Body */ *info = 0; upper = lsame_(uplo, "U"); if (! upper && ! lsame_(uplo, "L")) { *info = -1; } else if (*n < 0) { *info = -2; } else if (*lda < max(1,*n)) { *info = -4; } if (*info != 0) { i__1 = -(*info); xerbla_("DLAUU2", &i__1); return 0; } /* Quick return if possible */ if (*n == 0) { return 0; } if (upper) { /* Compute the product U * U'. */ i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { aii = a[i__ + i__ * a_dim1]; if (i__ < *n) { i__2 = *n - i__ + 1; a[i__ + i__ * a_dim1] = ddot_(&i__2, &a[i__ + i__ * a_dim1], lda, &a[i__ + i__ * a_dim1], lda); i__2 = i__ - 1; i__3 = *n - i__; dgemv_("No transpose", &i__2, &i__3, &c_b2865, &a[(i__ + 1) * a_dim1 + 1], lda, &a[i__ + (i__ + 1) * a_dim1], lda, & aii, &a[i__ * a_dim1 + 1], &c__1); } else { dscal_(&i__, &aii, &a[i__ * a_dim1 + 1], &c__1); } /* L10: */ } } else { /* Compute the product L' * L. */ i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { aii = a[i__ + i__ * a_dim1]; if (i__ < *n) { i__2 = *n - i__ + 1; a[i__ + i__ * a_dim1] = ddot_(&i__2, &a[i__ + i__ * a_dim1], & c__1, &a[i__ + i__ * a_dim1], &c__1); i__2 = *n - i__; i__3 = i__ - 1; dgemv_("Transpose", &i__2, &i__3, &c_b2865, &a[i__ + 1 + a_dim1], lda, &a[i__ + 1 + i__ * a_dim1], &c__1, &aii, &a[i__ + a_dim1], lda); } else { dscal_(&i__, &aii, &a[i__ + a_dim1], lda); } /* L20: */ } } return 0; /* End of DLAUU2 */ } /* dlauu2_ */ /* Subroutine */ int dlauum_(char *uplo, integer *n, doublereal *a, integer * lda, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3, i__4; /* Local variables */ static integer i__, ib, nb; extern /* Subroutine */ int dgemm_(char *, char *, integer *, integer *, integer *, doublereal *, doublereal *, integer *, doublereal *, integer *, doublereal *, doublereal *, integer *); extern logical lsame_(char *, char *); extern /* Subroutine */ int dtrmm_(char *, char *, char *, char *, integer *, integer *, doublereal *, doublereal *, integer *, doublereal *, integer *); static logical upper; extern /* Subroutine */ int dsyrk_(char *, char *, integer *, integer *, doublereal *, doublereal *, integer *, doublereal *, doublereal *, integer *), dlauu2_(char *, integer *, doublereal *, integer *, integer *), xerbla_(char *, integer *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University February 29, 1992 Purpose ======= DLAUUM computes the product U * U' or L' * L, where the triangular factor U or L is stored in the upper or lower triangular part of the array A. If UPLO = 'U' or 'u' then the upper triangle of the result is stored, overwriting the factor U in A. If UPLO = 'L' or 'l' then the lower triangle of the result is stored, overwriting the factor L in A. This is the blocked form of the algorithm, calling Level 3 BLAS. Arguments ========= UPLO (input) CHARACTER*1 Specifies whether the triangular factor stored in the array A is upper or lower triangular: = 'U': Upper triangular = 'L': Lower triangular N (input) INTEGER The order of the triangular factor U or L. N >= 0. A (input/output) DOUBLE PRECISION array, dimension (LDA,N) On entry, the triangular factor U or L. On exit, if UPLO = 'U', the upper triangle of A is overwritten with the upper triangle of the product U * U'; if UPLO = 'L', the lower triangle of A is overwritten with the lower triangle of the product L' * L. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,N). INFO (output) INTEGER = 0: successful exit < 0: if INFO = -k, the k-th argument had an illegal value ===================================================================== Test the input parameters. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; /* Function Body */ *info = 0; upper = lsame_(uplo, "U"); if (! upper && ! lsame_(uplo, "L")) { *info = -1; } else if (*n < 0) { *info = -2; } else if (*lda < max(1,*n)) { *info = -4; } if (*info != 0) { i__1 = -(*info); xerbla_("DLAUUM", &i__1); return 0; } /* Quick return if possible */ if (*n == 0) { return 0; } /* Determine the block size for this environment. */ nb = ilaenv_(&c__1, "DLAUUM", uplo, n, &c_n1, &c_n1, &c_n1, (ftnlen)6, ( ftnlen)1); if ((nb <= 1) || (nb >= *n)) { /* Use unblocked code */ dlauu2_(uplo, n, &a[a_offset], lda, info); } else { /* Use blocked code */ if (upper) { /* Compute the product U * U'. */ i__1 = *n; i__2 = nb; for (i__ = 1; i__2 < 0 ? i__ >= i__1 : i__ <= i__1; i__ += i__2) { /* Computing MIN */ i__3 = nb, i__4 = *n - i__ + 1; ib = min(i__3,i__4); i__3 = i__ - 1; dtrmm_("Right", "Upper", "Transpose", "Non-unit", &i__3, &ib, &c_b2865, &a[i__ + i__ * a_dim1], lda, &a[i__ * a_dim1 + 1], lda); dlauu2_("Upper", &ib, &a[i__ + i__ * a_dim1], lda, info); if (i__ + ib <= *n) { i__3 = i__ - 1; i__4 = *n - i__ - ib + 1; dgemm_("No transpose", "Transpose", &i__3, &ib, &i__4, & c_b2865, &a[(i__ + ib) * a_dim1 + 1], lda, &a[i__ + (i__ + ib) * a_dim1], lda, &c_b2865, &a[i__ * a_dim1 + 1], lda); i__3 = *n - i__ - ib + 1; dsyrk_("Upper", "No transpose", &ib, &i__3, &c_b2865, &a[ i__ + (i__ + ib) * a_dim1], lda, &c_b2865, &a[i__ + i__ * a_dim1], lda); } /* L10: */ } } else { /* Compute the product L' * L. */ i__2 = *n; i__1 = nb; for (i__ = 1; i__1 < 0 ? i__ >= i__2 : i__ <= i__2; i__ += i__1) { /* Computing MIN */ i__3 = nb, i__4 = *n - i__ + 1; ib = min(i__3,i__4); i__3 = i__ - 1; dtrmm_("Left", "Lower", "Transpose", "Non-unit", &ib, &i__3, & c_b2865, &a[i__ + i__ * a_dim1], lda, &a[i__ + a_dim1] , lda); dlauu2_("Lower", &ib, &a[i__ + i__ * a_dim1], lda, info); if (i__ + ib <= *n) { i__3 = i__ - 1; i__4 = *n - i__ - ib + 1; dgemm_("Transpose", "No transpose", &ib, &i__3, &i__4, & c_b2865, &a[i__ + ib + i__ * a_dim1], lda, &a[i__ + ib + a_dim1], lda, &c_b2865, &a[i__ + a_dim1], lda); i__3 = *n - i__ - ib + 1; dsyrk_("Lower", "Transpose", &ib, &i__3, &c_b2865, &a[i__ + ib + i__ * a_dim1], lda, &c_b2865, &a[i__ + i__ * a_dim1], lda); } /* L20: */ } } } return 0; /* End of DLAUUM */ } /* dlauum_ */ /* Subroutine */ int dorg2r_(integer *m, integer *n, integer *k, doublereal * a, integer *lda, doublereal *tau, doublereal *work, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2; doublereal d__1; /* Local variables */ static integer i__, j, l; extern /* Subroutine */ int dscal_(integer *, doublereal *, doublereal *, integer *), dlarf_(char *, integer *, integer *, doublereal *, integer *, doublereal *, doublereal *, integer *, doublereal *), xerbla_(char *, integer *); /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University February 29, 1992 Purpose ======= DORG2R generates an m by n real matrix Q with orthonormal columns, which is defined as the first n columns of a product of k elementary reflectors of order m Q = H(1) H(2) . . . H(k) as returned by DGEQRF. Arguments ========= M (input) INTEGER The number of rows of the matrix Q. M >= 0. N (input) INTEGER The number of columns of the matrix Q. M >= N >= 0. K (input) INTEGER The number of elementary reflectors whose product defines the matrix Q. N >= K >= 0. A (input/output) DOUBLE PRECISION array, dimension (LDA,N) On entry, the i-th column must contain the vector which defines the elementary reflector H(i), for i = 1,2,...,k, as returned by DGEQRF in the first k columns of its array argument A. On exit, the m-by-n matrix Q. LDA (input) INTEGER The first dimension of the array A. LDA >= max(1,M). TAU (input) DOUBLE PRECISION array, dimension (K) TAU(i) must contain the scalar factor of the elementary reflector H(i), as returned by DGEQRF. WORK (workspace) DOUBLE PRECISION array, dimension (N) INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument has an illegal value ===================================================================== Test the input arguments */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --tau; --work; /* Function Body */ *info = 0; if (*m < 0) { *info = -1; } else if ((*n < 0) || (*n > *m)) { *info = -2; } else if ((*k < 0) || (*k > *n)) { *info = -3; } else if (*lda < max(1,*m)) { *info = -5; } if (*info != 0) { i__1 = -(*info); xerbla_("DORG2R", &i__1); return 0; } /* Quick return if possible */ if (*n <= 0) { return 0; } /* Initialise columns k+1:n to columns of the unit matrix */ i__1 = *n; for (j = *k + 1; j <= i__1; ++j) { i__2 = *m; for (l = 1; l <= i__2; ++l) { a[l + j * a_dim1] = 0.; /* L10: */ } a[j + j * a_dim1] = 1.; /* L20: */ } for (i__ = *k; i__ >= 1; --i__) { /* Apply H(i) to A(i:m,i:n) from the left */ if (i__ < *n) { a[i__ + i__ * a_dim1] = 1.; i__1 = *m - i__ + 1; i__2 = *n - i__; dlarf_("Left", &i__1, &i__2, &a[i__ + i__ * a_dim1], &c__1, &tau[ i__], &a[i__ + (i__ + 1) * a_dim1], lda, &work[1]); } if (i__ < *m) { i__1 = *m - i__; d__1 = -tau[i__]; dscal_(&i__1, &d__1, &a[i__ + 1 + i__ * a_dim1], &c__1); } a[i__ + i__ * a_dim1] = 1. - tau[i__]; /* Set A(1:i-1,i) to zero */ i__1 = i__ - 1; for (l = 1; l <= i__1; ++l) { a[l + i__ * a_dim1] = 0.; /* L30: */ } /* L40: */ } return 0; /* End of DORG2R */ } /* dorg2r_ */ /* Subroutine */ int dorgbr_(char *vect, integer *m, integer *n, integer *k, doublereal *a, integer *lda, doublereal *tau, doublereal *work, integer *lwork, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3; /* Local variables */ static integer i__, j, nb, mn; extern logical lsame_(char *, char *); static integer iinfo; static logical wantq; extern /* Subroutine */ int xerbla_(char *, integer *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); extern /* Subroutine */ int dorglq_(integer *, integer *, integer *, doublereal *, integer *, doublereal *, doublereal *, integer *, integer *), dorgqr_(integer *, integer *, integer *, doublereal *, integer *, doublereal *, doublereal *, integer *, integer *); static integer lwkopt; static logical lquery; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= DORGBR generates one of the real orthogonal matrices Q or P**T determined by DGEBRD when reducing a real matrix A to bidiagonal form: A = Q * B * P**T. Q and P**T are defined as products of elementary reflectors H(i) or G(i) respectively. If VECT = 'Q', A is assumed to have been an M-by-K matrix, and Q is of order M: if m >= k, Q = H(1) H(2) . . . H(k) and DORGBR returns the first n columns of Q, where m >= n >= k; if m < k, Q = H(1) H(2) . . . H(m-1) and DORGBR returns Q as an M-by-M matrix. If VECT = 'P', A is assumed to have been a K-by-N matrix, and P**T is of order N: if k < n, P**T = G(k) . . . G(2) G(1) and DORGBR returns the first m rows of P**T, where n >= m >= k; if k >= n, P**T = G(n-1) . . . G(2) G(1) and DORGBR returns P**T as an N-by-N matrix. Arguments ========= VECT (input) CHARACTER*1 Specifies whether the matrix Q or the matrix P**T is required, as defined in the transformation applied by DGEBRD: = 'Q': generate Q; = 'P': generate P**T. M (input) INTEGER The number of rows of the matrix Q or P**T to be returned. M >= 0. N (input) INTEGER The number of columns of the matrix Q or P**T to be returned. N >= 0. If VECT = 'Q', M >= N >= min(M,K); if VECT = 'P', N >= M >= min(N,K). K (input) INTEGER If VECT = 'Q', the number of columns in the original M-by-K matrix reduced by DGEBRD. If VECT = 'P', the number of rows in the original K-by-N matrix reduced by DGEBRD. K >= 0. A (input/output) DOUBLE PRECISION array, dimension (LDA,N) On entry, the vectors which define the elementary reflectors, as returned by DGEBRD. On exit, the M-by-N matrix Q or P**T. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,M). TAU (input) DOUBLE PRECISION array, dimension (min(M,K)) if VECT = 'Q' (min(N,K)) if VECT = 'P' TAU(i) must contain the scalar factor of the elementary reflector H(i) or G(i), which determines Q or P**T, as returned by DGEBRD in its array argument TAUQ or TAUP. WORK (workspace/output) DOUBLE PRECISION array, dimension (LWORK) On exit, if INFO = 0, WORK(1) returns the optimal LWORK. LWORK (input) INTEGER The dimension of the array WORK. LWORK >= max(1,min(M,N)). For optimum performance LWORK >= min(M,N)*NB, where NB is the optimal blocksize. If LWORK = -1, then a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued by XERBLA. INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value ===================================================================== Test the input arguments */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --tau; --work; /* Function Body */ *info = 0; wantq = lsame_(vect, "Q"); mn = min(*m,*n); lquery = *lwork == -1; if (! wantq && ! lsame_(vect, "P")) { *info = -1; } else if (*m < 0) { *info = -2; } else if (((*n < 0) || (wantq && ((*n > *m) || (*n < min(*m,*k))))) || (! wantq && ((*m > *n) || (*m < min(*n,*k))))) { *info = -3; } else if (*k < 0) { *info = -4; } else if (*lda < max(1,*m)) { *info = -6; } else if (*lwork < max(1,mn) && ! lquery) { *info = -9; } if (*info == 0) { if (wantq) { nb = ilaenv_(&c__1, "DORGQR", " ", m, n, k, &c_n1, (ftnlen)6, ( ftnlen)1); } else { nb = ilaenv_(&c__1, "DORGLQ", " ", m, n, k, &c_n1, (ftnlen)6, ( ftnlen)1); } lwkopt = max(1,mn) * nb; work[1] = (doublereal) lwkopt; } if (*info != 0) { i__1 = -(*info); xerbla_("DORGBR", &i__1); return 0; } else if (lquery) { return 0; } /* Quick return if possible */ if ((*m == 0) || (*n == 0)) { work[1] = 1.; return 0; } if (wantq) { /* Form Q, determined by a call to DGEBRD to reduce an m-by-k matrix */ if (*m >= *k) { /* If m >= k, assume m >= n >= k */ dorgqr_(m, n, k, &a[a_offset], lda, &tau[1], &work[1], lwork, & iinfo); } else { /* If m < k, assume m = n Shift the vectors which define the elementary reflectors one column to the right, and set the first row and column of Q to those of the unit matrix */ for (j = *m; j >= 2; --j) { a[j * a_dim1 + 1] = 0.; i__1 = *m; for (i__ = j + 1; i__ <= i__1; ++i__) { a[i__ + j * a_dim1] = a[i__ + (j - 1) * a_dim1]; /* L10: */ } /* L20: */ } a[a_dim1 + 1] = 1.; i__1 = *m; for (i__ = 2; i__ <= i__1; ++i__) { a[i__ + a_dim1] = 0.; /* L30: */ } if (*m > 1) { /* Form Q(2:m,2:m) */ i__1 = *m - 1; i__2 = *m - 1; i__3 = *m - 1; dorgqr_(&i__1, &i__2, &i__3, &a[((a_dim1) << (1)) + 2], lda, & tau[1], &work[1], lwork, &iinfo); } } } else { /* Form P', determined by a call to DGEBRD to reduce a k-by-n matrix */ if (*k < *n) { /* If k < n, assume k <= m <= n */ dorglq_(m, n, k, &a[a_offset], lda, &tau[1], &work[1], lwork, & iinfo); } else { /* If k >= n, assume m = n Shift the vectors which define the elementary reflectors one row downward, and set the first row and column of P' to those of the unit matrix */ a[a_dim1 + 1] = 1.; i__1 = *n; for (i__ = 2; i__ <= i__1; ++i__) { a[i__ + a_dim1] = 0.; /* L40: */ } i__1 = *n; for (j = 2; j <= i__1; ++j) { for (i__ = j - 1; i__ >= 2; --i__) { a[i__ + j * a_dim1] = a[i__ - 1 + j * a_dim1]; /* L50: */ } a[j * a_dim1 + 1] = 0.; /* L60: */ } if (*n > 1) { /* Form P'(2:n,2:n) */ i__1 = *n - 1; i__2 = *n - 1; i__3 = *n - 1; dorglq_(&i__1, &i__2, &i__3, &a[((a_dim1) << (1)) + 2], lda, & tau[1], &work[1], lwork, &iinfo); } } } work[1] = (doublereal) lwkopt; return 0; /* End of DORGBR */ } /* dorgbr_ */ /* Subroutine */ int dorghr_(integer *n, integer *ilo, integer *ihi, doublereal *a, integer *lda, doublereal *tau, doublereal *work, integer *lwork, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2; /* Local variables */ static integer i__, j, nb, nh, iinfo; extern /* Subroutine */ int xerbla_(char *, integer *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); extern /* Subroutine */ int dorgqr_(integer *, integer *, integer *, doublereal *, integer *, doublereal *, doublereal *, integer *, integer *); static integer lwkopt; static logical lquery; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= DORGHR generates a real orthogonal matrix Q which is defined as the product of IHI-ILO elementary reflectors of order N, as returned by DGEHRD: Q = H(ilo) H(ilo+1) . . . H(ihi-1). Arguments ========= N (input) INTEGER The order of the matrix Q. N >= 0. ILO (input) INTEGER IHI (input) INTEGER ILO and IHI must have the same values as in the previous call of DGEHRD. Q is equal to the unit matrix except in the submatrix Q(ilo+1:ihi,ilo+1:ihi). 1 <= ILO <= IHI <= N, if N > 0; ILO=1 and IHI=0, if N=0. A (input/output) DOUBLE PRECISION array, dimension (LDA,N) On entry, the vectors which define the elementary reflectors, as returned by DGEHRD. On exit, the N-by-N orthogonal matrix Q. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,N). TAU (input) DOUBLE PRECISION array, dimension (N-1) TAU(i) must contain the scalar factor of the elementary reflector H(i), as returned by DGEHRD. WORK (workspace/output) DOUBLE PRECISION array, dimension (LWORK) On exit, if INFO = 0, WORK(1) returns the optimal LWORK. LWORK (input) INTEGER The dimension of the array WORK. LWORK >= IHI-ILO. For optimum performance LWORK >= (IHI-ILO)*NB, where NB is the optimal blocksize. If LWORK = -1, then a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued by XERBLA. INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value ===================================================================== Test the input arguments */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --tau; --work; /* Function Body */ *info = 0; nh = *ihi - *ilo; lquery = *lwork == -1; if (*n < 0) { *info = -1; } else if ((*ilo < 1) || (*ilo > max(1,*n))) { *info = -2; } else if ((*ihi < min(*ilo,*n)) || (*ihi > *n)) { *info = -3; } else if (*lda < max(1,*n)) { *info = -5; } else if (*lwork < max(1,nh) && ! lquery) { *info = -8; } if (*info == 0) { nb = ilaenv_(&c__1, "DORGQR", " ", &nh, &nh, &nh, &c_n1, (ftnlen)6, ( ftnlen)1); lwkopt = max(1,nh) * nb; work[1] = (doublereal) lwkopt; } if (*info != 0) { i__1 = -(*info); xerbla_("DORGHR", &i__1); return 0; } else if (lquery) { return 0; } /* Quick return if possible */ if (*n == 0) { work[1] = 1.; return 0; } /* Shift the vectors which define the elementary reflectors one column to the right, and set the first ilo and the last n-ihi rows and columns to those of the unit matrix */ i__1 = *ilo + 1; for (j = *ihi; j >= i__1; --j) { i__2 = j - 1; for (i__ = 1; i__ <= i__2; ++i__) { a[i__ + j * a_dim1] = 0.; /* L10: */ } i__2 = *ihi; for (i__ = j + 1; i__ <= i__2; ++i__) { a[i__ + j * a_dim1] = a[i__ + (j - 1) * a_dim1]; /* L20: */ } i__2 = *n; for (i__ = *ihi + 1; i__ <= i__2; ++i__) { a[i__ + j * a_dim1] = 0.; /* L30: */ } /* L40: */ } i__1 = *ilo; for (j = 1; j <= i__1; ++j) { i__2 = *n; for (i__ = 1; i__ <= i__2; ++i__) { a[i__ + j * a_dim1] = 0.; /* L50: */ } a[j + j * a_dim1] = 1.; /* L60: */ } i__1 = *n; for (j = *ihi + 1; j <= i__1; ++j) { i__2 = *n; for (i__ = 1; i__ <= i__2; ++i__) { a[i__ + j * a_dim1] = 0.; /* L70: */ } a[j + j * a_dim1] = 1.; /* L80: */ } if (nh > 0) { /* Generate Q(ilo+1:ihi,ilo+1:ihi) */ dorgqr_(&nh, &nh, &nh, &a[*ilo + 1 + (*ilo + 1) * a_dim1], lda, &tau[* ilo], &work[1], lwork, &iinfo); } work[1] = (doublereal) lwkopt; return 0; /* End of DORGHR */ } /* dorghr_ */ /* Subroutine */ int dorgl2_(integer *m, integer *n, integer *k, doublereal * a, integer *lda, doublereal *tau, doublereal *work, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2; doublereal d__1; /* Local variables */ static integer i__, j, l; extern /* Subroutine */ int dscal_(integer *, doublereal *, doublereal *, integer *), dlarf_(char *, integer *, integer *, doublereal *, integer *, doublereal *, doublereal *, integer *, doublereal *), xerbla_(char *, integer *); /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= DORGL2 generates an m by n real matrix Q with orthonormal rows, which is defined as the first m rows of a product of k elementary reflectors of order n Q = H(k) . . . H(2) H(1) as returned by DGELQF. Arguments ========= M (input) INTEGER The number of rows of the matrix Q. M >= 0. N (input) INTEGER The number of columns of the matrix Q. N >= M. K (input) INTEGER The number of elementary reflectors whose product defines the matrix Q. M >= K >= 0. A (input/output) DOUBLE PRECISION array, dimension (LDA,N) On entry, the i-th row must contain the vector which defines the elementary reflector H(i), for i = 1,2,...,k, as returned by DGELQF in the first k rows of its array argument A. On exit, the m-by-n matrix Q. LDA (input) INTEGER The first dimension of the array A. LDA >= max(1,M). TAU (input) DOUBLE PRECISION array, dimension (K) TAU(i) must contain the scalar factor of the elementary reflector H(i), as returned by DGELQF. WORK (workspace) DOUBLE PRECISION array, dimension (M) INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument has an illegal value ===================================================================== Test the input arguments */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --tau; --work; /* Function Body */ *info = 0; if (*m < 0) { *info = -1; } else if (*n < *m) { *info = -2; } else if ((*k < 0) || (*k > *m)) { *info = -3; } else if (*lda < max(1,*m)) { *info = -5; } if (*info != 0) { i__1 = -(*info); xerbla_("DORGL2", &i__1); return 0; } /* Quick return if possible */ if (*m <= 0) { return 0; } if (*k < *m) { /* Initialise rows k+1:m to rows of the unit matrix */ i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (l = *k + 1; l <= i__2; ++l) { a[l + j * a_dim1] = 0.; /* L10: */ } if (j > *k && j <= *m) { a[j + j * a_dim1] = 1.; } /* L20: */ } } for (i__ = *k; i__ >= 1; --i__) { /* Apply H(i) to A(i:m,i:n) from the right */ if (i__ < *n) { if (i__ < *m) { a[i__ + i__ * a_dim1] = 1.; i__1 = *m - i__; i__2 = *n - i__ + 1; dlarf_("Right", &i__1, &i__2, &a[i__ + i__ * a_dim1], lda, & tau[i__], &a[i__ + 1 + i__ * a_dim1], lda, &work[1]); } i__1 = *n - i__; d__1 = -tau[i__]; dscal_(&i__1, &d__1, &a[i__ + (i__ + 1) * a_dim1], lda); } a[i__ + i__ * a_dim1] = 1. - tau[i__]; /* Set A(i,1:i-1) to zero */ i__1 = i__ - 1; for (l = 1; l <= i__1; ++l) { a[i__ + l * a_dim1] = 0.; /* L30: */ } /* L40: */ } return 0; /* End of DORGL2 */ } /* dorgl2_ */ /* Subroutine */ int dorglq_(integer *m, integer *n, integer *k, doublereal * a, integer *lda, doublereal *tau, doublereal *work, integer *lwork, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3; /* Local variables */ static integer i__, j, l, ib, nb, ki, kk, nx, iws, nbmin, iinfo; extern /* Subroutine */ int dorgl2_(integer *, integer *, integer *, doublereal *, integer *, doublereal *, doublereal *, integer *), dlarfb_(char *, char *, char *, char *, integer *, integer *, integer *, doublereal *, integer *, doublereal *, integer *, doublereal *, integer *, doublereal *, integer *), dlarft_(char *, char *, integer *, integer *, doublereal *, integer *, doublereal *, doublereal *, integer *), xerbla_(char *, integer *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); static integer ldwork, lwkopt; static logical lquery; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= DORGLQ generates an M-by-N real matrix Q with orthonormal rows, which is defined as the first M rows of a product of K elementary reflectors of order N Q = H(k) . . . H(2) H(1) as returned by DGELQF. Arguments ========= M (input) INTEGER The number of rows of the matrix Q. M >= 0. N (input) INTEGER The number of columns of the matrix Q. N >= M. K (input) INTEGER The number of elementary reflectors whose product defines the matrix Q. M >= K >= 0. A (input/output) DOUBLE PRECISION array, dimension (LDA,N) On entry, the i-th row must contain the vector which defines the elementary reflector H(i), for i = 1,2,...,k, as returned by DGELQF in the first k rows of its array argument A. On exit, the M-by-N matrix Q. LDA (input) INTEGER The first dimension of the array A. LDA >= max(1,M). TAU (input) DOUBLE PRECISION array, dimension (K) TAU(i) must contain the scalar factor of the elementary reflector H(i), as returned by DGELQF. WORK (workspace/output) DOUBLE PRECISION array, dimension (LWORK) On exit, if INFO = 0, WORK(1) returns the optimal LWORK. LWORK (input) INTEGER The dimension of the array WORK. LWORK >= max(1,M). For optimum performance LWORK >= M*NB, where NB is the optimal blocksize. If LWORK = -1, then a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued by XERBLA. INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument has an illegal value ===================================================================== Test the input arguments */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --tau; --work; /* Function Body */ *info = 0; nb = ilaenv_(&c__1, "DORGLQ", " ", m, n, k, &c_n1, (ftnlen)6, (ftnlen)1); lwkopt = max(1,*m) * nb; work[1] = (doublereal) lwkopt; lquery = *lwork == -1; if (*m < 0) { *info = -1; } else if (*n < *m) { *info = -2; } else if ((*k < 0) || (*k > *m)) { *info = -3; } else if (*lda < max(1,*m)) { *info = -5; } else if (*lwork < max(1,*m) && ! lquery) { *info = -8; } if (*info != 0) { i__1 = -(*info); xerbla_("DORGLQ", &i__1); return 0; } else if (lquery) { return 0; } /* Quick return if possible */ if (*m <= 0) { work[1] = 1.; return 0; } nbmin = 2; nx = 0; iws = *m; if (nb > 1 && nb < *k) { /* Determine when to cross over from blocked to unblocked code. Computing MAX */ i__1 = 0, i__2 = ilaenv_(&c__3, "DORGLQ", " ", m, n, k, &c_n1, ( ftnlen)6, (ftnlen)1); nx = max(i__1,i__2); if (nx < *k) { /* Determine if workspace is large enough for blocked code. */ ldwork = *m; iws = ldwork * nb; if (*lwork < iws) { /* Not enough workspace to use optimal NB: reduce NB and determine the minimum value of NB. */ nb = *lwork / ldwork; /* Computing MAX */ i__1 = 2, i__2 = ilaenv_(&c__2, "DORGLQ", " ", m, n, k, &c_n1, (ftnlen)6, (ftnlen)1); nbmin = max(i__1,i__2); } } } if (nb >= nbmin && nb < *k && nx < *k) { /* Use blocked code after the last block. The first kk rows are handled by the block method. */ ki = (*k - nx - 1) / nb * nb; /* Computing MIN */ i__1 = *k, i__2 = ki + nb; kk = min(i__1,i__2); /* Set A(kk+1:m,1:kk) to zero. */ i__1 = kk; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = kk + 1; i__ <= i__2; ++i__) { a[i__ + j * a_dim1] = 0.; /* L10: */ } /* L20: */ } } else { kk = 0; } /* Use unblocked code for the last or only block. */ if (kk < *m) { i__1 = *m - kk; i__2 = *n - kk; i__3 = *k - kk; dorgl2_(&i__1, &i__2, &i__3, &a[kk + 1 + (kk + 1) * a_dim1], lda, & tau[kk + 1], &work[1], &iinfo); } if (kk > 0) { /* Use blocked code */ i__1 = -nb; for (i__ = ki + 1; i__1 < 0 ? i__ >= 1 : i__ <= 1; i__ += i__1) { /* Computing MIN */ i__2 = nb, i__3 = *k - i__ + 1; ib = min(i__2,i__3); if (i__ + ib <= *m) { /* Form the triangular factor of the block reflector H = H(i) H(i+1) . . . H(i+ib-1) */ i__2 = *n - i__ + 1; dlarft_("Forward", "Rowwise", &i__2, &ib, &a[i__ + i__ * a_dim1], lda, &tau[i__], &work[1], &ldwork); /* Apply H' to A(i+ib:m,i:n) from the right */ i__2 = *m - i__ - ib + 1; i__3 = *n - i__ + 1; dlarfb_("Right", "Transpose", "Forward", "Rowwise", &i__2, & i__3, &ib, &a[i__ + i__ * a_dim1], lda, &work[1], & ldwork, &a[i__ + ib + i__ * a_dim1], lda, &work[ib + 1], &ldwork); } /* Apply H' to columns i:n of current block */ i__2 = *n - i__ + 1; dorgl2_(&ib, &i__2, &ib, &a[i__ + i__ * a_dim1], lda, &tau[i__], & work[1], &iinfo); /* Set columns 1:i-1 of current block to zero */ i__2 = i__ - 1; for (j = 1; j <= i__2; ++j) { i__3 = i__ + ib - 1; for (l = i__; l <= i__3; ++l) { a[l + j * a_dim1] = 0.; /* L30: */ } /* L40: */ } /* L50: */ } } work[1] = (doublereal) iws; return 0; /* End of DORGLQ */ } /* dorglq_ */ /* Subroutine */ int dorgqr_(integer *m, integer *n, integer *k, doublereal * a, integer *lda, doublereal *tau, doublereal *work, integer *lwork, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3; /* Local variables */ static integer i__, j, l, ib, nb, ki, kk, nx, iws, nbmin, iinfo; extern /* Subroutine */ int dorg2r_(integer *, integer *, integer *, doublereal *, integer *, doublereal *, doublereal *, integer *), dlarfb_(char *, char *, char *, char *, integer *, integer *, integer *, doublereal *, integer *, doublereal *, integer *, doublereal *, integer *, doublereal *, integer *), dlarft_(char *, char *, integer *, integer *, doublereal *, integer *, doublereal *, doublereal *, integer *), xerbla_(char *, integer *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); static integer ldwork, lwkopt; static logical lquery; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= DORGQR generates an M-by-N real matrix Q with orthonormal columns, which is defined as the first N columns of a product of K elementary reflectors of order M Q = H(1) H(2) . . . H(k) as returned by DGEQRF. Arguments ========= M (input) INTEGER The number of rows of the matrix Q. M >= 0. N (input) INTEGER The number of columns of the matrix Q. M >= N >= 0. K (input) INTEGER The number of elementary reflectors whose product defines the matrix Q. N >= K >= 0. A (input/output) DOUBLE PRECISION array, dimension (LDA,N) On entry, the i-th column must contain the vector which defines the elementary reflector H(i), for i = 1,2,...,k, as returned by DGEQRF in the first k columns of its array argument A. On exit, the M-by-N matrix Q. LDA (input) INTEGER The first dimension of the array A. LDA >= max(1,M). TAU (input) DOUBLE PRECISION array, dimension (K) TAU(i) must contain the scalar factor of the elementary reflector H(i), as returned by DGEQRF. WORK (workspace/output) DOUBLE PRECISION array, dimension (LWORK) On exit, if INFO = 0, WORK(1) returns the optimal LWORK. LWORK (input) INTEGER The dimension of the array WORK. LWORK >= max(1,N). For optimum performance LWORK >= N*NB, where NB is the optimal blocksize. If LWORK = -1, then a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued by XERBLA. INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument has an illegal value ===================================================================== Test the input arguments */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --tau; --work; /* Function Body */ *info = 0; nb = ilaenv_(&c__1, "DORGQR", " ", m, n, k, &c_n1, (ftnlen)6, (ftnlen)1); lwkopt = max(1,*n) * nb; work[1] = (doublereal) lwkopt; lquery = *lwork == -1; if (*m < 0) { *info = -1; } else if ((*n < 0) || (*n > *m)) { *info = -2; } else if ((*k < 0) || (*k > *n)) { *info = -3; } else if (*lda < max(1,*m)) { *info = -5; } else if (*lwork < max(1,*n) && ! lquery) { *info = -8; } if (*info != 0) { i__1 = -(*info); xerbla_("DORGQR", &i__1); return 0; } else if (lquery) { return 0; } /* Quick return if possible */ if (*n <= 0) { work[1] = 1.; return 0; } nbmin = 2; nx = 0; iws = *n; if (nb > 1 && nb < *k) { /* Determine when to cross over from blocked to unblocked code. Computing MAX */ i__1 = 0, i__2 = ilaenv_(&c__3, "DORGQR", " ", m, n, k, &c_n1, ( ftnlen)6, (ftnlen)1); nx = max(i__1,i__2); if (nx < *k) { /* Determine if workspace is large enough for blocked code. */ ldwork = *n; iws = ldwork * nb; if (*lwork < iws) { /* Not enough workspace to use optimal NB: reduce NB and determine the minimum value of NB. */ nb = *lwork / ldwork; /* Computing MAX */ i__1 = 2, i__2 = ilaenv_(&c__2, "DORGQR", " ", m, n, k, &c_n1, (ftnlen)6, (ftnlen)1); nbmin = max(i__1,i__2); } } } if (nb >= nbmin && nb < *k && nx < *k) { /* Use blocked code after the last block. The first kk columns are handled by the block method. */ ki = (*k - nx - 1) / nb * nb; /* Computing MIN */ i__1 = *k, i__2 = ki + nb; kk = min(i__1,i__2); /* Set A(1:kk,kk+1:n) to zero. */ i__1 = *n; for (j = kk + 1; j <= i__1; ++j) { i__2 = kk; for (i__ = 1; i__ <= i__2; ++i__) { a[i__ + j * a_dim1] = 0.; /* L10: */ } /* L20: */ } } else { kk = 0; } /* Use unblocked code for the last or only block. */ if (kk < *n) { i__1 = *m - kk; i__2 = *n - kk; i__3 = *k - kk; dorg2r_(&i__1, &i__2, &i__3, &a[kk + 1 + (kk + 1) * a_dim1], lda, & tau[kk + 1], &work[1], &iinfo); } if (kk > 0) { /* Use blocked code */ i__1 = -nb; for (i__ = ki + 1; i__1 < 0 ? i__ >= 1 : i__ <= 1; i__ += i__1) { /* Computing MIN */ i__2 = nb, i__3 = *k - i__ + 1; ib = min(i__2,i__3); if (i__ + ib <= *n) { /* Form the triangular factor of the block reflector H = H(i) H(i+1) . . . H(i+ib-1) */ i__2 = *m - i__ + 1; dlarft_("Forward", "Columnwise", &i__2, &ib, &a[i__ + i__ * a_dim1], lda, &tau[i__], &work[1], &ldwork); /* Apply H to A(i:m,i+ib:n) from the left */ i__2 = *m - i__ + 1; i__3 = *n - i__ - ib + 1; dlarfb_("Left", "No transpose", "Forward", "Columnwise", & i__2, &i__3, &ib, &a[i__ + i__ * a_dim1], lda, &work[ 1], &ldwork, &a[i__ + (i__ + ib) * a_dim1], lda, & work[ib + 1], &ldwork); } /* Apply H to rows i:m of current block */ i__2 = *m - i__ + 1; dorg2r_(&i__2, &ib, &ib, &a[i__ + i__ * a_dim1], lda, &tau[i__], & work[1], &iinfo); /* Set rows 1:i-1 of current block to zero */ i__2 = i__ + ib - 1; for (j = i__; j <= i__2; ++j) { i__3 = i__ - 1; for (l = 1; l <= i__3; ++l) { a[l + j * a_dim1] = 0.; /* L30: */ } /* L40: */ } /* L50: */ } } work[1] = (doublereal) iws; return 0; /* End of DORGQR */ } /* dorgqr_ */ /* Subroutine */ int dorm2l_(char *side, char *trans, integer *m, integer *n, integer *k, doublereal *a, integer *lda, doublereal *tau, doublereal * c__, integer *ldc, doublereal *work, integer *info) { /* System generated locals */ integer a_dim1, a_offset, c_dim1, c_offset, i__1, i__2; /* Local variables */ static integer i__, i1, i2, i3, mi, ni, nq; static doublereal aii; static logical left; extern /* Subroutine */ int dlarf_(char *, integer *, integer *, doublereal *, integer *, doublereal *, doublereal *, integer *, doublereal *); extern logical lsame_(char *, char *); extern /* Subroutine */ int xerbla_(char *, integer *); static logical notran; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University February 29, 1992 Purpose ======= DORM2L overwrites the general real m by n matrix C with Q * C if SIDE = 'L' and TRANS = 'N', or Q'* C if SIDE = 'L' and TRANS = 'T', or C * Q if SIDE = 'R' and TRANS = 'N', or C * Q' if SIDE = 'R' and TRANS = 'T', where Q is a real orthogonal matrix defined as the product of k elementary reflectors Q = H(k) . . . H(2) H(1) as returned by DGEQLF. Q is of order m if SIDE = 'L' and of order n if SIDE = 'R'. Arguments ========= SIDE (input) CHARACTER*1 = 'L': apply Q or Q' from the Left = 'R': apply Q or Q' from the Right TRANS (input) CHARACTER*1 = 'N': apply Q (No transpose) = 'T': apply Q' (Transpose) M (input) INTEGER The number of rows of the matrix C. M >= 0. N (input) INTEGER The number of columns of the matrix C. N >= 0. K (input) INTEGER The number of elementary reflectors whose product defines the matrix Q. If SIDE = 'L', M >= K >= 0; if SIDE = 'R', N >= K >= 0. A (input) DOUBLE PRECISION array, dimension (LDA,K) The i-th column must contain the vector which defines the elementary reflector H(i), for i = 1,2,...,k, as returned by DGEQLF in the last k columns of its array argument A. A is modified by the routine but restored on exit. LDA (input) INTEGER The leading dimension of the array A. If SIDE = 'L', LDA >= max(1,M); if SIDE = 'R', LDA >= max(1,N). TAU (input) DOUBLE PRECISION array, dimension (K) TAU(i) must contain the scalar factor of the elementary reflector H(i), as returned by DGEQLF. C (input/output) DOUBLE PRECISION array, dimension (LDC,N) On entry, the m by n matrix C. On exit, C is overwritten by Q*C or Q'*C or C*Q' or C*Q. LDC (input) INTEGER The leading dimension of the array C. LDC >= max(1,M). WORK (workspace) DOUBLE PRECISION array, dimension (N) if SIDE = 'L', (M) if SIDE = 'R' INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value ===================================================================== Test the input arguments */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --tau; c_dim1 = *ldc; c_offset = 1 + c_dim1; c__ -= c_offset; --work; /* Function Body */ *info = 0; left = lsame_(side, "L"); notran = lsame_(trans, "N"); /* NQ is the order of Q */ if (left) { nq = *m; } else { nq = *n; } if (! left && ! lsame_(side, "R")) { *info = -1; } else if (! notran && ! lsame_(trans, "T")) { *info = -2; } else if (*m < 0) { *info = -3; } else if (*n < 0) { *info = -4; } else if ((*k < 0) || (*k > nq)) { *info = -5; } else if (*lda < max(1,nq)) { *info = -7; } else if (*ldc < max(1,*m)) { *info = -10; } if (*info != 0) { i__1 = -(*info); xerbla_("DORM2L", &i__1); return 0; } /* Quick return if possible */ if (((*m == 0) || (*n == 0)) || (*k == 0)) { return 0; } if ((left && notran) || (! left && ! notran)) { i1 = 1; i2 = *k; i3 = 1; } else { i1 = *k; i2 = 1; i3 = -1; } if (left) { ni = *n; } else { mi = *m; } i__1 = i2; i__2 = i3; for (i__ = i1; i__2 < 0 ? i__ >= i__1 : i__ <= i__1; i__ += i__2) { if (left) { /* H(i) is applied to C(1:m-k+i,1:n) */ mi = *m - *k + i__; } else { /* H(i) is applied to C(1:m,1:n-k+i) */ ni = *n - *k + i__; } /* Apply H(i) */ aii = a[nq - *k + i__ + i__ * a_dim1]; a[nq - *k + i__ + i__ * a_dim1] = 1.; dlarf_(side, &mi, &ni, &a[i__ * a_dim1 + 1], &c__1, &tau[i__], &c__[ c_offset], ldc, &work[1]); a[nq - *k + i__ + i__ * a_dim1] = aii; /* L10: */ } return 0; /* End of DORM2L */ } /* dorm2l_ */ /* Subroutine */ int dorm2r_(char *side, char *trans, integer *m, integer *n, integer *k, doublereal *a, integer *lda, doublereal *tau, doublereal * c__, integer *ldc, doublereal *work, integer *info) { /* System generated locals */ integer a_dim1, a_offset, c_dim1, c_offset, i__1, i__2; /* Local variables */ static integer i__, i1, i2, i3, ic, jc, mi, ni, nq; static doublereal aii; static logical left; extern /* Subroutine */ int dlarf_(char *, integer *, integer *, doublereal *, integer *, doublereal *, doublereal *, integer *, doublereal *); extern logical lsame_(char *, char *); extern /* Subroutine */ int xerbla_(char *, integer *); static logical notran; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University February 29, 1992 Purpose ======= DORM2R overwrites the general real m by n matrix C with Q * C if SIDE = 'L' and TRANS = 'N', or Q'* C if SIDE = 'L' and TRANS = 'T', or C * Q if SIDE = 'R' and TRANS = 'N', or C * Q' if SIDE = 'R' and TRANS = 'T', where Q is a real orthogonal matrix defined as the product of k elementary reflectors Q = H(1) H(2) . . . H(k) as returned by DGEQRF. Q is of order m if SIDE = 'L' and of order n if SIDE = 'R'. Arguments ========= SIDE (input) CHARACTER*1 = 'L': apply Q or Q' from the Left = 'R': apply Q or Q' from the Right TRANS (input) CHARACTER*1 = 'N': apply Q (No transpose) = 'T': apply Q' (Transpose) M (input) INTEGER The number of rows of the matrix C. M >= 0. N (input) INTEGER The number of columns of the matrix C. N >= 0. K (input) INTEGER The number of elementary reflectors whose product defines the matrix Q. If SIDE = 'L', M >= K >= 0; if SIDE = 'R', N >= K >= 0. A (input) DOUBLE PRECISION array, dimension (LDA,K) The i-th column must contain the vector which defines the elementary reflector H(i), for i = 1,2,...,k, as returned by DGEQRF in the first k columns of its array argument A. A is modified by the routine but restored on exit. LDA (input) INTEGER The leading dimension of the array A. If SIDE = 'L', LDA >= max(1,M); if SIDE = 'R', LDA >= max(1,N). TAU (input) DOUBLE PRECISION array, dimension (K) TAU(i) must contain the scalar factor of the elementary reflector H(i), as returned by DGEQRF. C (input/output) DOUBLE PRECISION array, dimension (LDC,N) On entry, the m by n matrix C. On exit, C is overwritten by Q*C or Q'*C or C*Q' or C*Q. LDC (input) INTEGER The leading dimension of the array C. LDC >= max(1,M). WORK (workspace) DOUBLE PRECISION array, dimension (N) if SIDE = 'L', (M) if SIDE = 'R' INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value ===================================================================== Test the input arguments */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --tau; c_dim1 = *ldc; c_offset = 1 + c_dim1; c__ -= c_offset; --work; /* Function Body */ *info = 0; left = lsame_(side, "L"); notran = lsame_(trans, "N"); /* NQ is the order of Q */ if (left) { nq = *m; } else { nq = *n; } if (! left && ! lsame_(side, "R")) { *info = -1; } else if (! notran && ! lsame_(trans, "T")) { *info = -2; } else if (*m < 0) { *info = -3; } else if (*n < 0) { *info = -4; } else if ((*k < 0) || (*k > nq)) { *info = -5; } else if (*lda < max(1,nq)) { *info = -7; } else if (*ldc < max(1,*m)) { *info = -10; } if (*info != 0) { i__1 = -(*info); xerbla_("DORM2R", &i__1); return 0; } /* Quick return if possible */ if (((*m == 0) || (*n == 0)) || (*k == 0)) { return 0; } if ((left && ! notran) || (! left && notran)) { i1 = 1; i2 = *k; i3 = 1; } else { i1 = *k; i2 = 1; i3 = -1; } if (left) { ni = *n; jc = 1; } else { mi = *m; ic = 1; } i__1 = i2; i__2 = i3; for (i__ = i1; i__2 < 0 ? i__ >= i__1 : i__ <= i__1; i__ += i__2) { if (left) { /* H(i) is applied to C(i:m,1:n) */ mi = *m - i__ + 1; ic = i__; } else { /* H(i) is applied to C(1:m,i:n) */ ni = *n - i__ + 1; jc = i__; } /* Apply H(i) */ aii = a[i__ + i__ * a_dim1]; a[i__ + i__ * a_dim1] = 1.; dlarf_(side, &mi, &ni, &a[i__ + i__ * a_dim1], &c__1, &tau[i__], &c__[ ic + jc * c_dim1], ldc, &work[1]); a[i__ + i__ * a_dim1] = aii; /* L10: */ } return 0; /* End of DORM2R */ } /* dorm2r_ */ /* Subroutine */ int dormbr_(char *vect, char *side, char *trans, integer *m, integer *n, integer *k, doublereal *a, integer *lda, doublereal *tau, doublereal *c__, integer *ldc, doublereal *work, integer *lwork, integer *info) { /* System generated locals */ address a__1[2]; integer a_dim1, a_offset, c_dim1, c_offset, i__1, i__2, i__3[2]; char ch__1[2]; /* Builtin functions */ /* Subroutine */ int s_cat(char *, char **, integer *, integer *, ftnlen); /* Local variables */ static integer i1, i2, nb, mi, ni, nq, nw; static logical left; extern logical lsame_(char *, char *); static integer iinfo; extern /* Subroutine */ int xerbla_(char *, integer *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); extern /* Subroutine */ int dormlq_(char *, char *, integer *, integer *, integer *, doublereal *, integer *, doublereal *, doublereal *, integer *, doublereal *, integer *, integer *); static logical notran; extern /* Subroutine */ int dormqr_(char *, char *, integer *, integer *, integer *, doublereal *, integer *, doublereal *, doublereal *, integer *, doublereal *, integer *, integer *); static logical applyq; static char transt[1]; static integer lwkopt; static logical lquery; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= If VECT = 'Q', DORMBR overwrites the general real M-by-N matrix C with SIDE = 'L' SIDE = 'R' TRANS = 'N': Q * C C * Q TRANS = 'T': Q**T * C C * Q**T If VECT = 'P', DORMBR overwrites the general real M-by-N matrix C with SIDE = 'L' SIDE = 'R' TRANS = 'N': P * C C * P TRANS = 'T': P**T * C C * P**T Here Q and P**T are the orthogonal matrices determined by DGEBRD when reducing a real matrix A to bidiagonal form: A = Q * B * P**T. Q and P**T are defined as products of elementary reflectors H(i) and G(i) respectively. Let nq = m if SIDE = 'L' and nq = n if SIDE = 'R'. Thus nq is the order of the orthogonal matrix Q or P**T that is applied. If VECT = 'Q', A is assumed to have been an NQ-by-K matrix: if nq >= k, Q = H(1) H(2) . . . H(k); if nq < k, Q = H(1) H(2) . . . H(nq-1). If VECT = 'P', A is assumed to have been a K-by-NQ matrix: if k < nq, P = G(1) G(2) . . . G(k); if k >= nq, P = G(1) G(2) . . . G(nq-1). Arguments ========= VECT (input) CHARACTER*1 = 'Q': apply Q or Q**T; = 'P': apply P or P**T. SIDE (input) CHARACTER*1 = 'L': apply Q, Q**T, P or P**T from the Left; = 'R': apply Q, Q**T, P or P**T from the Right. TRANS (input) CHARACTER*1 = 'N': No transpose, apply Q or P; = 'T': Transpose, apply Q**T or P**T. M (input) INTEGER The number of rows of the matrix C. M >= 0. N (input) INTEGER The number of columns of the matrix C. N >= 0. K (input) INTEGER If VECT = 'Q', the number of columns in the original matrix reduced by DGEBRD. If VECT = 'P', the number of rows in the original matrix reduced by DGEBRD. K >= 0. A (input) DOUBLE PRECISION array, dimension (LDA,min(nq,K)) if VECT = 'Q' (LDA,nq) if VECT = 'P' The vectors which define the elementary reflectors H(i) and G(i), whose products determine the matrices Q and P, as returned by DGEBRD. LDA (input) INTEGER The leading dimension of the array A. If VECT = 'Q', LDA >= max(1,nq); if VECT = 'P', LDA >= max(1,min(nq,K)). TAU (input) DOUBLE PRECISION array, dimension (min(nq,K)) TAU(i) must contain the scalar factor of the elementary reflector H(i) or G(i) which determines Q or P, as returned by DGEBRD in the array argument TAUQ or TAUP. C (input/output) DOUBLE PRECISION array, dimension (LDC,N) On entry, the M-by-N matrix C. On exit, C is overwritten by Q*C or Q**T*C or C*Q**T or C*Q or P*C or P**T*C or C*P or C*P**T. LDC (input) INTEGER The leading dimension of the array C. LDC >= max(1,M). WORK (workspace/output) DOUBLE PRECISION array, dimension (LWORK) On exit, if INFO = 0, WORK(1) returns the optimal LWORK. LWORK (input) INTEGER The dimension of the array WORK. If SIDE = 'L', LWORK >= max(1,N); if SIDE = 'R', LWORK >= max(1,M). For optimum performance LWORK >= N*NB if SIDE = 'L', and LWORK >= M*NB if SIDE = 'R', where NB is the optimal blocksize. If LWORK = -1, then a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued by XERBLA. INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value ===================================================================== Test the input arguments */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --tau; c_dim1 = *ldc; c_offset = 1 + c_dim1; c__ -= c_offset; --work; /* Function Body */ *info = 0; applyq = lsame_(vect, "Q"); left = lsame_(side, "L"); notran = lsame_(trans, "N"); lquery = *lwork == -1; /* NQ is the order of Q or P and NW is the minimum dimension of WORK */ if (left) { nq = *m; nw = *n; } else { nq = *n; nw = *m; } if (! applyq && ! lsame_(vect, "P")) { *info = -1; } else if (! left && ! lsame_(side, "R")) { *info = -2; } else if (! notran && ! lsame_(trans, "T")) { *info = -3; } else if (*m < 0) { *info = -4; } else if (*n < 0) { *info = -5; } else if (*k < 0) { *info = -6; } else /* if(complicated condition) */ { /* Computing MAX */ i__1 = 1, i__2 = min(nq,*k); if ((applyq && *lda < max(1,nq)) || (! applyq && *lda < max(i__1,i__2) )) { *info = -8; } else if (*ldc < max(1,*m)) { *info = -11; } else if (*lwork < max(1,nw) && ! lquery) { *info = -13; } } if (*info == 0) { if (applyq) { if (left) { /* Writing concatenation */ i__3[0] = 1, a__1[0] = side; i__3[1] = 1, a__1[1] = trans; s_cat(ch__1, a__1, i__3, &c__2, (ftnlen)2); i__1 = *m - 1; i__2 = *m - 1; nb = ilaenv_(&c__1, "DORMQR", ch__1, &i__1, n, &i__2, &c_n1, ( ftnlen)6, (ftnlen)2); } else { /* Writing concatenation */ i__3[0] = 1, a__1[0] = side; i__3[1] = 1, a__1[1] = trans; s_cat(ch__1, a__1, i__3, &c__2, (ftnlen)2); i__1 = *n - 1; i__2 = *n - 1; nb = ilaenv_(&c__1, "DORMQR", ch__1, m, &i__1, &i__2, &c_n1, ( ftnlen)6, (ftnlen)2); } } else { if (left) { /* Writing concatenation */ i__3[0] = 1, a__1[0] = side; i__3[1] = 1, a__1[1] = trans; s_cat(ch__1, a__1, i__3, &c__2, (ftnlen)2); i__1 = *m - 1; i__2 = *m - 1; nb = ilaenv_(&c__1, "DORMLQ", ch__1, &i__1, n, &i__2, &c_n1, ( ftnlen)6, (ftnlen)2); } else { /* Writing concatenation */ i__3[0] = 1, a__1[0] = side; i__3[1] = 1, a__1[1] = trans; s_cat(ch__1, a__1, i__3, &c__2, (ftnlen)2); i__1 = *n - 1; i__2 = *n - 1; nb = ilaenv_(&c__1, "DORMLQ", ch__1, m, &i__1, &i__2, &c_n1, ( ftnlen)6, (ftnlen)2); } } lwkopt = max(1,nw) * nb; work[1] = (doublereal) lwkopt; } if (*info != 0) { i__1 = -(*info); xerbla_("DORMBR", &i__1); return 0; } else if (lquery) { return 0; } /* Quick return if possible */ work[1] = 1.; if ((*m == 0) || (*n == 0)) { return 0; } if (applyq) { /* Apply Q */ if (nq >= *k) { /* Q was determined by a call to DGEBRD with nq >= k */ dormqr_(side, trans, m, n, k, &a[a_offset], lda, &tau[1], &c__[ c_offset], ldc, &work[1], lwork, &iinfo); } else if (nq > 1) { /* Q was determined by a call to DGEBRD with nq < k */ if (left) { mi = *m - 1; ni = *n; i1 = 2; i2 = 1; } else { mi = *m; ni = *n - 1; i1 = 1; i2 = 2; } i__1 = nq - 1; dormqr_(side, trans, &mi, &ni, &i__1, &a[a_dim1 + 2], lda, &tau[1] , &c__[i1 + i2 * c_dim1], ldc, &work[1], lwork, &iinfo); } } else { /* Apply P */ if (notran) { *(unsigned char *)transt = 'T'; } else { *(unsigned char *)transt = 'N'; } if (nq > *k) { /* P was determined by a call to DGEBRD with nq > k */ dormlq_(side, transt, m, n, k, &a[a_offset], lda, &tau[1], &c__[ c_offset], ldc, &work[1], lwork, &iinfo); } else if (nq > 1) { /* P was determined by a call to DGEBRD with nq <= k */ if (left) { mi = *m - 1; ni = *n; i1 = 2; i2 = 1; } else { mi = *m; ni = *n - 1; i1 = 1; i2 = 2; } i__1 = nq - 1; dormlq_(side, transt, &mi, &ni, &i__1, &a[((a_dim1) << (1)) + 1], lda, &tau[1], &c__[i1 + i2 * c_dim1], ldc, &work[1], lwork, &iinfo); } } work[1] = (doublereal) lwkopt; return 0; /* End of DORMBR */ } /* dormbr_ */ /* Subroutine */ int dorml2_(char *side, char *trans, integer *m, integer *n, integer *k, doublereal *a, integer *lda, doublereal *tau, doublereal * c__, integer *ldc, doublereal *work, integer *info) { /* System generated locals */ integer a_dim1, a_offset, c_dim1, c_offset, i__1, i__2; /* Local variables */ static integer i__, i1, i2, i3, ic, jc, mi, ni, nq; static doublereal aii; static logical left; extern /* Subroutine */ int dlarf_(char *, integer *, integer *, doublereal *, integer *, doublereal *, doublereal *, integer *, doublereal *); extern logical lsame_(char *, char *); extern /* Subroutine */ int xerbla_(char *, integer *); static logical notran; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University February 29, 1992 Purpose ======= DORML2 overwrites the general real m by n matrix C with Q * C if SIDE = 'L' and TRANS = 'N', or Q'* C if SIDE = 'L' and TRANS = 'T', or C * Q if SIDE = 'R' and TRANS = 'N', or C * Q' if SIDE = 'R' and TRANS = 'T', where Q is a real orthogonal matrix defined as the product of k elementary reflectors Q = H(k) . . . H(2) H(1) as returned by DGELQF. Q is of order m if SIDE = 'L' and of order n if SIDE = 'R'. Arguments ========= SIDE (input) CHARACTER*1 = 'L': apply Q or Q' from the Left = 'R': apply Q or Q' from the Right TRANS (input) CHARACTER*1 = 'N': apply Q (No transpose) = 'T': apply Q' (Transpose) M (input) INTEGER The number of rows of the matrix C. M >= 0. N (input) INTEGER The number of columns of the matrix C. N >= 0. K (input) INTEGER The number of elementary reflectors whose product defines the matrix Q. If SIDE = 'L', M >= K >= 0; if SIDE = 'R', N >= K >= 0. A (input) DOUBLE PRECISION array, dimension (LDA,M) if SIDE = 'L', (LDA,N) if SIDE = 'R' The i-th row must contain the vector which defines the elementary reflector H(i), for i = 1,2,...,k, as returned by DGELQF in the first k rows of its array argument A. A is modified by the routine but restored on exit. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,K). TAU (input) DOUBLE PRECISION array, dimension (K) TAU(i) must contain the scalar factor of the elementary reflector H(i), as returned by DGELQF. C (input/output) DOUBLE PRECISION array, dimension (LDC,N) On entry, the m by n matrix C. On exit, C is overwritten by Q*C or Q'*C or C*Q' or C*Q. LDC (input) INTEGER The leading dimension of the array C. LDC >= max(1,M). WORK (workspace) DOUBLE PRECISION array, dimension (N) if SIDE = 'L', (M) if SIDE = 'R' INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value ===================================================================== Test the input arguments */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --tau; c_dim1 = *ldc; c_offset = 1 + c_dim1; c__ -= c_offset; --work; /* Function Body */ *info = 0; left = lsame_(side, "L"); notran = lsame_(trans, "N"); /* NQ is the order of Q */ if (left) { nq = *m; } else { nq = *n; } if (! left && ! lsame_(side, "R")) { *info = -1; } else if (! notran && ! lsame_(trans, "T")) { *info = -2; } else if (*m < 0) { *info = -3; } else if (*n < 0) { *info = -4; } else if ((*k < 0) || (*k > nq)) { *info = -5; } else if (*lda < max(1,*k)) { *info = -7; } else if (*ldc < max(1,*m)) { *info = -10; } if (*info != 0) { i__1 = -(*info); xerbla_("DORML2", &i__1); return 0; } /* Quick return if possible */ if (((*m == 0) || (*n == 0)) || (*k == 0)) { return 0; } if ((left && notran) || (! left && ! notran)) { i1 = 1; i2 = *k; i3 = 1; } else { i1 = *k; i2 = 1; i3 = -1; } if (left) { ni = *n; jc = 1; } else { mi = *m; ic = 1; } i__1 = i2; i__2 = i3; for (i__ = i1; i__2 < 0 ? i__ >= i__1 : i__ <= i__1; i__ += i__2) { if (left) { /* H(i) is applied to C(i:m,1:n) */ mi = *m - i__ + 1; ic = i__; } else { /* H(i) is applied to C(1:m,i:n) */ ni = *n - i__ + 1; jc = i__; } /* Apply H(i) */ aii = a[i__ + i__ * a_dim1]; a[i__ + i__ * a_dim1] = 1.; dlarf_(side, &mi, &ni, &a[i__ + i__ * a_dim1], lda, &tau[i__], &c__[ ic + jc * c_dim1], ldc, &work[1]); a[i__ + i__ * a_dim1] = aii; /* L10: */ } return 0; /* End of DORML2 */ } /* dorml2_ */ /* Subroutine */ int dormlq_(char *side, char *trans, integer *m, integer *n, integer *k, doublereal *a, integer *lda, doublereal *tau, doublereal * c__, integer *ldc, doublereal *work, integer *lwork, integer *info) { /* System generated locals */ address a__1[2]; integer a_dim1, a_offset, c_dim1, c_offset, i__1, i__2, i__3[2], i__4, i__5; char ch__1[2]; /* Builtin functions */ /* Subroutine */ int s_cat(char *, char **, integer *, integer *, ftnlen); /* Local variables */ static integer i__; static doublereal t[4160] /* was [65][64] */; static integer i1, i2, i3, ib, ic, jc, nb, mi, ni, nq, nw, iws; static logical left; extern logical lsame_(char *, char *); static integer nbmin, iinfo; extern /* Subroutine */ int dorml2_(char *, char *, integer *, integer *, integer *, doublereal *, integer *, doublereal *, doublereal *, integer *, doublereal *, integer *), dlarfb_(char *, char *, char *, char *, integer *, integer *, integer *, doublereal *, integer *, doublereal *, integer *, doublereal *, integer *, doublereal *, integer *), dlarft_(char *, char *, integer *, integer *, doublereal *, integer *, doublereal *, doublereal *, integer *), xerbla_(char *, integer *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); static logical notran; static integer ldwork; static char transt[1]; static integer lwkopt; static logical lquery; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= DORMLQ overwrites the general real M-by-N matrix C with SIDE = 'L' SIDE = 'R' TRANS = 'N': Q * C C * Q TRANS = 'T': Q**T * C C * Q**T where Q is a real orthogonal matrix defined as the product of k elementary reflectors Q = H(k) . . . H(2) H(1) as returned by DGELQF. Q is of order M if SIDE = 'L' and of order N if SIDE = 'R'. Arguments ========= SIDE (input) CHARACTER*1 = 'L': apply Q or Q**T from the Left; = 'R': apply Q or Q**T from the Right. TRANS (input) CHARACTER*1 = 'N': No transpose, apply Q; = 'T': Transpose, apply Q**T. M (input) INTEGER The number of rows of the matrix C. M >= 0. N (input) INTEGER The number of columns of the matrix C. N >= 0. K (input) INTEGER The number of elementary reflectors whose product defines the matrix Q. If SIDE = 'L', M >= K >= 0; if SIDE = 'R', N >= K >= 0. A (input) DOUBLE PRECISION array, dimension (LDA,M) if SIDE = 'L', (LDA,N) if SIDE = 'R' The i-th row must contain the vector which defines the elementary reflector H(i), for i = 1,2,...,k, as returned by DGELQF in the first k rows of its array argument A. A is modified by the routine but restored on exit. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,K). TAU (input) DOUBLE PRECISION array, dimension (K) TAU(i) must contain the scalar factor of the elementary reflector H(i), as returned by DGELQF. C (input/output) DOUBLE PRECISION array, dimension (LDC,N) On entry, the M-by-N matrix C. On exit, C is overwritten by Q*C or Q**T*C or C*Q**T or C*Q. LDC (input) INTEGER The leading dimension of the array C. LDC >= max(1,M). WORK (workspace/output) DOUBLE PRECISION array, dimension (LWORK) On exit, if INFO = 0, WORK(1) returns the optimal LWORK. LWORK (input) INTEGER The dimension of the array WORK. If SIDE = 'L', LWORK >= max(1,N); if SIDE = 'R', LWORK >= max(1,M). For optimum performance LWORK >= N*NB if SIDE = 'L', and LWORK >= M*NB if SIDE = 'R', where NB is the optimal blocksize. If LWORK = -1, then a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued by XERBLA. INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value ===================================================================== Test the input arguments */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --tau; c_dim1 = *ldc; c_offset = 1 + c_dim1; c__ -= c_offset; --work; /* Function Body */ *info = 0; left = lsame_(side, "L"); notran = lsame_(trans, "N"); lquery = *lwork == -1; /* NQ is the order of Q and NW is the minimum dimension of WORK */ if (left) { nq = *m; nw = *n; } else { nq = *n; nw = *m; } if (! left && ! lsame_(side, "R")) { *info = -1; } else if (! notran && ! lsame_(trans, "T")) { *info = -2; } else if (*m < 0) { *info = -3; } else if (*n < 0) { *info = -4; } else if ((*k < 0) || (*k > nq)) { *info = -5; } else if (*lda < max(1,*k)) { *info = -7; } else if (*ldc < max(1,*m)) { *info = -10; } else if (*lwork < max(1,nw) && ! lquery) { *info = -12; } if (*info == 0) { /* Determine the block size. NB may be at most NBMAX, where NBMAX is used to define the local array T. Computing MIN Writing concatenation */ i__3[0] = 1, a__1[0] = side; i__3[1] = 1, a__1[1] = trans; s_cat(ch__1, a__1, i__3, &c__2, (ftnlen)2); i__1 = 64, i__2 = ilaenv_(&c__1, "DORMLQ", ch__1, m, n, k, &c_n1, ( ftnlen)6, (ftnlen)2); nb = min(i__1,i__2); lwkopt = max(1,nw) * nb; work[1] = (doublereal) lwkopt; } if (*info != 0) { i__1 = -(*info); xerbla_("DORMLQ", &i__1); return 0; } else if (lquery) { return 0; } /* Quick return if possible */ if (((*m == 0) || (*n == 0)) || (*k == 0)) { work[1] = 1.; return 0; } nbmin = 2; ldwork = nw; if (nb > 1 && nb < *k) { iws = nw * nb; if (*lwork < iws) { nb = *lwork / ldwork; /* Computing MAX Writing concatenation */ i__3[0] = 1, a__1[0] = side; i__3[1] = 1, a__1[1] = trans; s_cat(ch__1, a__1, i__3, &c__2, (ftnlen)2); i__1 = 2, i__2 = ilaenv_(&c__2, "DORMLQ", ch__1, m, n, k, &c_n1, ( ftnlen)6, (ftnlen)2); nbmin = max(i__1,i__2); } } else { iws = nw; } if ((nb < nbmin) || (nb >= *k)) { /* Use unblocked code */ dorml2_(side, trans, m, n, k, &a[a_offset], lda, &tau[1], &c__[ c_offset], ldc, &work[1], &iinfo); } else { /* Use blocked code */ if ((left && notran) || (! left && ! notran)) { i1 = 1; i2 = *k; i3 = nb; } else { i1 = (*k - 1) / nb * nb + 1; i2 = 1; i3 = -nb; } if (left) { ni = *n; jc = 1; } else { mi = *m; ic = 1; } if (notran) { *(unsigned char *)transt = 'T'; } else { *(unsigned char *)transt = 'N'; } i__1 = i2; i__2 = i3; for (i__ = i1; i__2 < 0 ? i__ >= i__1 : i__ <= i__1; i__ += i__2) { /* Computing MIN */ i__4 = nb, i__5 = *k - i__ + 1; ib = min(i__4,i__5); /* Form the triangular factor of the block reflector H = H(i) H(i+1) . . . H(i+ib-1) */ i__4 = nq - i__ + 1; dlarft_("Forward", "Rowwise", &i__4, &ib, &a[i__ + i__ * a_dim1], lda, &tau[i__], t, &c__65); if (left) { /* H or H' is applied to C(i:m,1:n) */ mi = *m - i__ + 1; ic = i__; } else { /* H or H' is applied to C(1:m,i:n) */ ni = *n - i__ + 1; jc = i__; } /* Apply H or H' */ dlarfb_(side, transt, "Forward", "Rowwise", &mi, &ni, &ib, &a[i__ + i__ * a_dim1], lda, t, &c__65, &c__[ic + jc * c_dim1], ldc, &work[1], &ldwork); /* L10: */ } } work[1] = (doublereal) lwkopt; return 0; /* End of DORMLQ */ } /* dormlq_ */ /* Subroutine */ int dormql_(char *side, char *trans, integer *m, integer *n, integer *k, doublereal *a, integer *lda, doublereal *tau, doublereal * c__, integer *ldc, doublereal *work, integer *lwork, integer *info) { /* System generated locals */ address a__1[2]; integer a_dim1, a_offset, c_dim1, c_offset, i__1, i__2, i__3[2], i__4, i__5; char ch__1[2]; /* Builtin functions */ /* Subroutine */ int s_cat(char *, char **, integer *, integer *, ftnlen); /* Local variables */ static integer i__; static doublereal t[4160] /* was [65][64] */; static integer i1, i2, i3, ib, nb, mi, ni, nq, nw, iws; static logical left; extern logical lsame_(char *, char *); static integer nbmin, iinfo; extern /* Subroutine */ int dorm2l_(char *, char *, integer *, integer *, integer *, doublereal *, integer *, doublereal *, doublereal *, integer *, doublereal *, integer *), dlarfb_(char *, char *, char *, char *, integer *, integer *, integer *, doublereal *, integer *, doublereal *, integer *, doublereal *, integer *, doublereal *, integer *), dlarft_(char *, char *, integer *, integer *, doublereal *, integer *, doublereal *, doublereal *, integer *), xerbla_(char *, integer *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); static logical notran; static integer ldwork, lwkopt; static logical lquery; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= DORMQL overwrites the general real M-by-N matrix C with SIDE = 'L' SIDE = 'R' TRANS = 'N': Q * C C * Q TRANS = 'T': Q**T * C C * Q**T where Q is a real orthogonal matrix defined as the product of k elementary reflectors Q = H(k) . . . H(2) H(1) as returned by DGEQLF. Q is of order M if SIDE = 'L' and of order N if SIDE = 'R'. Arguments ========= SIDE (input) CHARACTER*1 = 'L': apply Q or Q**T from the Left; = 'R': apply Q or Q**T from the Right. TRANS (input) CHARACTER*1 = 'N': No transpose, apply Q; = 'T': Transpose, apply Q**T. M (input) INTEGER The number of rows of the matrix C. M >= 0. N (input) INTEGER The number of columns of the matrix C. N >= 0. K (input) INTEGER The number of elementary reflectors whose product defines the matrix Q. If SIDE = 'L', M >= K >= 0; if SIDE = 'R', N >= K >= 0. A (input) DOUBLE PRECISION array, dimension (LDA,K) The i-th column must contain the vector which defines the elementary reflector H(i), for i = 1,2,...,k, as returned by DGEQLF in the last k columns of its array argument A. A is modified by the routine but restored on exit. LDA (input) INTEGER The leading dimension of the array A. If SIDE = 'L', LDA >= max(1,M); if SIDE = 'R', LDA >= max(1,N). TAU (input) DOUBLE PRECISION array, dimension (K) TAU(i) must contain the scalar factor of the elementary reflector H(i), as returned by DGEQLF. C (input/output) DOUBLE PRECISION array, dimension (LDC,N) On entry, the M-by-N matrix C. On exit, C is overwritten by Q*C or Q**T*C or C*Q**T or C*Q. LDC (input) INTEGER The leading dimension of the array C. LDC >= max(1,M). WORK (workspace/output) DOUBLE PRECISION array, dimension (LWORK) On exit, if INFO = 0, WORK(1) returns the optimal LWORK. LWORK (input) INTEGER The dimension of the array WORK. If SIDE = 'L', LWORK >= max(1,N); if SIDE = 'R', LWORK >= max(1,M). For optimum performance LWORK >= N*NB if SIDE = 'L', and LWORK >= M*NB if SIDE = 'R', where NB is the optimal blocksize. If LWORK = -1, then a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued by XERBLA. INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value ===================================================================== Test the input arguments */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --tau; c_dim1 = *ldc; c_offset = 1 + c_dim1; c__ -= c_offset; --work; /* Function Body */ *info = 0; left = lsame_(side, "L"); notran = lsame_(trans, "N"); lquery = *lwork == -1; /* NQ is the order of Q and NW is the minimum dimension of WORK */ if (left) { nq = *m; nw = *n; } else { nq = *n; nw = *m; } if (! left && ! lsame_(side, "R")) { *info = -1; } else if (! notran && ! lsame_(trans, "T")) { *info = -2; } else if (*m < 0) { *info = -3; } else if (*n < 0) { *info = -4; } else if ((*k < 0) || (*k > nq)) { *info = -5; } else if (*lda < max(1,nq)) { *info = -7; } else if (*ldc < max(1,*m)) { *info = -10; } else if (*lwork < max(1,nw) && ! lquery) { *info = -12; } if (*info == 0) { /* Determine the block size. NB may be at most NBMAX, where NBMAX is used to define the local array T. Computing MIN Writing concatenation */ i__3[0] = 1, a__1[0] = side; i__3[1] = 1, a__1[1] = trans; s_cat(ch__1, a__1, i__3, &c__2, (ftnlen)2); i__1 = 64, i__2 = ilaenv_(&c__1, "DORMQL", ch__1, m, n, k, &c_n1, ( ftnlen)6, (ftnlen)2); nb = min(i__1,i__2); lwkopt = max(1,nw) * nb; work[1] = (doublereal) lwkopt; } if (*info != 0) { i__1 = -(*info); xerbla_("DORMQL", &i__1); return 0; } else if (lquery) { return 0; } /* Quick return if possible */ if (((*m == 0) || (*n == 0)) || (*k == 0)) { work[1] = 1.; return 0; } nbmin = 2; ldwork = nw; if (nb > 1 && nb < *k) { iws = nw * nb; if (*lwork < iws) { nb = *lwork / ldwork; /* Computing MAX Writing concatenation */ i__3[0] = 1, a__1[0] = side; i__3[1] = 1, a__1[1] = trans; s_cat(ch__1, a__1, i__3, &c__2, (ftnlen)2); i__1 = 2, i__2 = ilaenv_(&c__2, "DORMQL", ch__1, m, n, k, &c_n1, ( ftnlen)6, (ftnlen)2); nbmin = max(i__1,i__2); } } else { iws = nw; } if ((nb < nbmin) || (nb >= *k)) { /* Use unblocked code */ dorm2l_(side, trans, m, n, k, &a[a_offset], lda, &tau[1], &c__[ c_offset], ldc, &work[1], &iinfo); } else { /* Use blocked code */ if ((left && notran) || (! left && ! notran)) { i1 = 1; i2 = *k; i3 = nb; } else { i1 = (*k - 1) / nb * nb + 1; i2 = 1; i3 = -nb; } if (left) { ni = *n; } else { mi = *m; } i__1 = i2; i__2 = i3; for (i__ = i1; i__2 < 0 ? i__ >= i__1 : i__ <= i__1; i__ += i__2) { /* Computing MIN */ i__4 = nb, i__5 = *k - i__ + 1; ib = min(i__4,i__5); /* Form the triangular factor of the block reflector H = H(i+ib-1) . . . H(i+1) H(i) */ i__4 = nq - *k + i__ + ib - 1; dlarft_("Backward", "Columnwise", &i__4, &ib, &a[i__ * a_dim1 + 1] , lda, &tau[i__], t, &c__65); if (left) { /* H or H' is applied to C(1:m-k+i+ib-1,1:n) */ mi = *m - *k + i__ + ib - 1; } else { /* H or H' is applied to C(1:m,1:n-k+i+ib-1) */ ni = *n - *k + i__ + ib - 1; } /* Apply H or H' */ dlarfb_(side, trans, "Backward", "Columnwise", &mi, &ni, &ib, &a[ i__ * a_dim1 + 1], lda, t, &c__65, &c__[c_offset], ldc, & work[1], &ldwork); /* L10: */ } } work[1] = (doublereal) lwkopt; return 0; /* End of DORMQL */ } /* dormql_ */ /* Subroutine */ int dormqr_(char *side, char *trans, integer *m, integer *n, integer *k, doublereal *a, integer *lda, doublereal *tau, doublereal * c__, integer *ldc, doublereal *work, integer *lwork, integer *info) { /* System generated locals */ address a__1[2]; integer a_dim1, a_offset, c_dim1, c_offset, i__1, i__2, i__3[2], i__4, i__5; char ch__1[2]; /* Builtin functions */ /* Subroutine */ int s_cat(char *, char **, integer *, integer *, ftnlen); /* Local variables */ static integer i__; static doublereal t[4160] /* was [65][64] */; static integer i1, i2, i3, ib, ic, jc, nb, mi, ni, nq, nw, iws; static logical left; extern logical lsame_(char *, char *); static integer nbmin, iinfo; extern /* Subroutine */ int dorm2r_(char *, char *, integer *, integer *, integer *, doublereal *, integer *, doublereal *, doublereal *, integer *, doublereal *, integer *), dlarfb_(char *, char *, char *, char *, integer *, integer *, integer *, doublereal *, integer *, doublereal *, integer *, doublereal *, integer *, doublereal *, integer *), dlarft_(char *, char *, integer *, integer *, doublereal *, integer *, doublereal *, doublereal *, integer *), xerbla_(char *, integer *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); static logical notran; static integer ldwork, lwkopt; static logical lquery; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= DORMQR overwrites the general real M-by-N matrix C with SIDE = 'L' SIDE = 'R' TRANS = 'N': Q * C C * Q TRANS = 'T': Q**T * C C * Q**T where Q is a real orthogonal matrix defined as the product of k elementary reflectors Q = H(1) H(2) . . . H(k) as returned by DGEQRF. Q is of order M if SIDE = 'L' and of order N if SIDE = 'R'. Arguments ========= SIDE (input) CHARACTER*1 = 'L': apply Q or Q**T from the Left; = 'R': apply Q or Q**T from the Right. TRANS (input) CHARACTER*1 = 'N': No transpose, apply Q; = 'T': Transpose, apply Q**T. M (input) INTEGER The number of rows of the matrix C. M >= 0. N (input) INTEGER The number of columns of the matrix C. N >= 0. K (input) INTEGER The number of elementary reflectors whose product defines the matrix Q. If SIDE = 'L', M >= K >= 0; if SIDE = 'R', N >= K >= 0. A (input) DOUBLE PRECISION array, dimension (LDA,K) The i-th column must contain the vector which defines the elementary reflector H(i), for i = 1,2,...,k, as returned by DGEQRF in the first k columns of its array argument A. A is modified by the routine but restored on exit. LDA (input) INTEGER The leading dimension of the array A. If SIDE = 'L', LDA >= max(1,M); if SIDE = 'R', LDA >= max(1,N). TAU (input) DOUBLE PRECISION array, dimension (K) TAU(i) must contain the scalar factor of the elementary reflector H(i), as returned by DGEQRF. C (input/output) DOUBLE PRECISION array, dimension (LDC,N) On entry, the M-by-N matrix C. On exit, C is overwritten by Q*C or Q**T*C or C*Q**T or C*Q. LDC (input) INTEGER The leading dimension of the array C. LDC >= max(1,M). WORK (workspace/output) DOUBLE PRECISION array, dimension (LWORK) On exit, if INFO = 0, WORK(1) returns the optimal LWORK. LWORK (input) INTEGER The dimension of the array WORK. If SIDE = 'L', LWORK >= max(1,N); if SIDE = 'R', LWORK >= max(1,M). For optimum performance LWORK >= N*NB if SIDE = 'L', and LWORK >= M*NB if SIDE = 'R', where NB is the optimal blocksize. If LWORK = -1, then a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued by XERBLA. INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value ===================================================================== Test the input arguments */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --tau; c_dim1 = *ldc; c_offset = 1 + c_dim1; c__ -= c_offset; --work; /* Function Body */ *info = 0; left = lsame_(side, "L"); notran = lsame_(trans, "N"); lquery = *lwork == -1; /* NQ is the order of Q and NW is the minimum dimension of WORK */ if (left) { nq = *m; nw = *n; } else { nq = *n; nw = *m; } if (! left && ! lsame_(side, "R")) { *info = -1; } else if (! notran && ! lsame_(trans, "T")) { *info = -2; } else if (*m < 0) { *info = -3; } else if (*n < 0) { *info = -4; } else if ((*k < 0) || (*k > nq)) { *info = -5; } else if (*lda < max(1,nq)) { *info = -7; } else if (*ldc < max(1,*m)) { *info = -10; } else if (*lwork < max(1,nw) && ! lquery) { *info = -12; } if (*info == 0) { /* Determine the block size. NB may be at most NBMAX, where NBMAX is used to define the local array T. Computing MIN Writing concatenation */ i__3[0] = 1, a__1[0] = side; i__3[1] = 1, a__1[1] = trans; s_cat(ch__1, a__1, i__3, &c__2, (ftnlen)2); i__1 = 64, i__2 = ilaenv_(&c__1, "DORMQR", ch__1, m, n, k, &c_n1, ( ftnlen)6, (ftnlen)2); nb = min(i__1,i__2); lwkopt = max(1,nw) * nb; work[1] = (doublereal) lwkopt; } if (*info != 0) { i__1 = -(*info); xerbla_("DORMQR", &i__1); return 0; } else if (lquery) { return 0; } /* Quick return if possible */ if (((*m == 0) || (*n == 0)) || (*k == 0)) { work[1] = 1.; return 0; } nbmin = 2; ldwork = nw; if (nb > 1 && nb < *k) { iws = nw * nb; if (*lwork < iws) { nb = *lwork / ldwork; /* Computing MAX Writing concatenation */ i__3[0] = 1, a__1[0] = side; i__3[1] = 1, a__1[1] = trans; s_cat(ch__1, a__1, i__3, &c__2, (ftnlen)2); i__1 = 2, i__2 = ilaenv_(&c__2, "DORMQR", ch__1, m, n, k, &c_n1, ( ftnlen)6, (ftnlen)2); nbmin = max(i__1,i__2); } } else { iws = nw; } if ((nb < nbmin) || (nb >= *k)) { /* Use unblocked code */ dorm2r_(side, trans, m, n, k, &a[a_offset], lda, &tau[1], &c__[ c_offset], ldc, &work[1], &iinfo); } else { /* Use blocked code */ if ((left && ! notran) || (! left && notran)) { i1 = 1; i2 = *k; i3 = nb; } else { i1 = (*k - 1) / nb * nb + 1; i2 = 1; i3 = -nb; } if (left) { ni = *n; jc = 1; } else { mi = *m; ic = 1; } i__1 = i2; i__2 = i3; for (i__ = i1; i__2 < 0 ? i__ >= i__1 : i__ <= i__1; i__ += i__2) { /* Computing MIN */ i__4 = nb, i__5 = *k - i__ + 1; ib = min(i__4,i__5); /* Form the triangular factor of the block reflector H = H(i) H(i+1) . . . H(i+ib-1) */ i__4 = nq - i__ + 1; dlarft_("Forward", "Columnwise", &i__4, &ib, &a[i__ + i__ * a_dim1], lda, &tau[i__], t, &c__65) ; if (left) { /* H or H' is applied to C(i:m,1:n) */ mi = *m - i__ + 1; ic = i__; } else { /* H or H' is applied to C(1:m,i:n) */ ni = *n - i__ + 1; jc = i__; } /* Apply H or H' */ dlarfb_(side, trans, "Forward", "Columnwise", &mi, &ni, &ib, &a[ i__ + i__ * a_dim1], lda, t, &c__65, &c__[ic + jc * c_dim1], ldc, &work[1], &ldwork); /* L10: */ } } work[1] = (doublereal) lwkopt; return 0; /* End of DORMQR */ } /* dormqr_ */ /* Subroutine */ int dormtr_(char *side, char *uplo, char *trans, integer *m, integer *n, doublereal *a, integer *lda, doublereal *tau, doublereal * c__, integer *ldc, doublereal *work, integer *lwork, integer *info) { /* System generated locals */ address a__1[2]; integer a_dim1, a_offset, c_dim1, c_offset, i__1[2], i__2, i__3; char ch__1[2]; /* Builtin functions */ /* Subroutine */ int s_cat(char *, char **, integer *, integer *, ftnlen); /* Local variables */ static integer i1, i2, nb, mi, ni, nq, nw; static logical left; extern logical lsame_(char *, char *); static integer iinfo; static logical upper; extern /* Subroutine */ int xerbla_(char *, integer *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); extern /* Subroutine */ int dormql_(char *, char *, integer *, integer *, integer *, doublereal *, integer *, doublereal *, doublereal *, integer *, doublereal *, integer *, integer *), dormqr_(char *, char *, integer *, integer *, integer *, doublereal *, integer *, doublereal *, doublereal *, integer *, doublereal *, integer *, integer *); static integer lwkopt; static logical lquery; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= DORMTR overwrites the general real M-by-N matrix C with SIDE = 'L' SIDE = 'R' TRANS = 'N': Q * C C * Q TRANS = 'T': Q**T * C C * Q**T where Q is a real orthogonal matrix of order nq, with nq = m if SIDE = 'L' and nq = n if SIDE = 'R'. Q is defined as the product of nq-1 elementary reflectors, as returned by DSYTRD: if UPLO = 'U', Q = H(nq-1) . . . H(2) H(1); if UPLO = 'L', Q = H(1) H(2) . . . H(nq-1). Arguments ========= SIDE (input) CHARACTER*1 = 'L': apply Q or Q**T from the Left; = 'R': apply Q or Q**T from the Right. UPLO (input) CHARACTER*1 = 'U': Upper triangle of A contains elementary reflectors from DSYTRD; = 'L': Lower triangle of A contains elementary reflectors from DSYTRD. TRANS (input) CHARACTER*1 = 'N': No transpose, apply Q; = 'T': Transpose, apply Q**T. M (input) INTEGER The number of rows of the matrix C. M >= 0. N (input) INTEGER The number of columns of the matrix C. N >= 0. A (input) DOUBLE PRECISION array, dimension (LDA,M) if SIDE = 'L' (LDA,N) if SIDE = 'R' The vectors which define the elementary reflectors, as returned by DSYTRD. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,M) if SIDE = 'L'; LDA >= max(1,N) if SIDE = 'R'. TAU (input) DOUBLE PRECISION array, dimension (M-1) if SIDE = 'L' (N-1) if SIDE = 'R' TAU(i) must contain the scalar factor of the elementary reflector H(i), as returned by DSYTRD. C (input/output) DOUBLE PRECISION array, dimension (LDC,N) On entry, the M-by-N matrix C. On exit, C is overwritten by Q*C or Q**T*C or C*Q**T or C*Q. LDC (input) INTEGER The leading dimension of the array C. LDC >= max(1,M). WORK (workspace/output) DOUBLE PRECISION array, dimension (LWORK) On exit, if INFO = 0, WORK(1) returns the optimal LWORK. LWORK (input) INTEGER The dimension of the array WORK. If SIDE = 'L', LWORK >= max(1,N); if SIDE = 'R', LWORK >= max(1,M). For optimum performance LWORK >= N*NB if SIDE = 'L', and LWORK >= M*NB if SIDE = 'R', where NB is the optimal blocksize. If LWORK = -1, then a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued by XERBLA. INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value ===================================================================== Test the input arguments */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --tau; c_dim1 = *ldc; c_offset = 1 + c_dim1; c__ -= c_offset; --work; /* Function Body */ *info = 0; left = lsame_(side, "L"); upper = lsame_(uplo, "U"); lquery = *lwork == -1; /* NQ is the order of Q and NW is the minimum dimension of WORK */ if (left) { nq = *m; nw = *n; } else { nq = *n; nw = *m; } if (! left && ! lsame_(side, "R")) { *info = -1; } else if (! upper && ! lsame_(uplo, "L")) { *info = -2; } else if (! lsame_(trans, "N") && ! lsame_(trans, "T")) { *info = -3; } else if (*m < 0) { *info = -4; } else if (*n < 0) { *info = -5; } else if (*lda < max(1,nq)) { *info = -7; } else if (*ldc < max(1,*m)) { *info = -10; } else if (*lwork < max(1,nw) && ! lquery) { *info = -12; } if (*info == 0) { if (upper) { if (left) { /* Writing concatenation */ i__1[0] = 1, a__1[0] = side; i__1[1] = 1, a__1[1] = trans; s_cat(ch__1, a__1, i__1, &c__2, (ftnlen)2); i__2 = *m - 1; i__3 = *m - 1; nb = ilaenv_(&c__1, "DORMQL", ch__1, &i__2, n, &i__3, &c_n1, ( ftnlen)6, (ftnlen)2); } else { /* Writing concatenation */ i__1[0] = 1, a__1[0] = side; i__1[1] = 1, a__1[1] = trans; s_cat(ch__1, a__1, i__1, &c__2, (ftnlen)2); i__2 = *n - 1; i__3 = *n - 1; nb = ilaenv_(&c__1, "DORMQL", ch__1, m, &i__2, &i__3, &c_n1, ( ftnlen)6, (ftnlen)2); } } else { if (left) { /* Writing concatenation */ i__1[0] = 1, a__1[0] = side; i__1[1] = 1, a__1[1] = trans; s_cat(ch__1, a__1, i__1, &c__2, (ftnlen)2); i__2 = *m - 1; i__3 = *m - 1; nb = ilaenv_(&c__1, "DORMQR", ch__1, &i__2, n, &i__3, &c_n1, ( ftnlen)6, (ftnlen)2); } else { /* Writing concatenation */ i__1[0] = 1, a__1[0] = side; i__1[1] = 1, a__1[1] = trans; s_cat(ch__1, a__1, i__1, &c__2, (ftnlen)2); i__2 = *n - 1; i__3 = *n - 1; nb = ilaenv_(&c__1, "DORMQR", ch__1, m, &i__2, &i__3, &c_n1, ( ftnlen)6, (ftnlen)2); } } lwkopt = max(1,nw) * nb; work[1] = (doublereal) lwkopt; } if (*info != 0) { i__2 = -(*info); xerbla_("DORMTR", &i__2); return 0; } else if (lquery) { return 0; } /* Quick return if possible */ if (((*m == 0) || (*n == 0)) || (nq == 1)) { work[1] = 1.; return 0; } if (left) { mi = *m - 1; ni = *n; } else { mi = *m; ni = *n - 1; } if (upper) { /* Q was determined by a call to DSYTRD with UPLO = 'U' */ i__2 = nq - 1; dormql_(side, trans, &mi, &ni, &i__2, &a[((a_dim1) << (1)) + 1], lda, &tau[1], &c__[c_offset], ldc, &work[1], lwork, &iinfo); } else { /* Q was determined by a call to DSYTRD with UPLO = 'L' */ if (left) { i1 = 2; i2 = 1; } else { i1 = 1; i2 = 2; } i__2 = nq - 1; dormqr_(side, trans, &mi, &ni, &i__2, &a[a_dim1 + 2], lda, &tau[1], & c__[i1 + i2 * c_dim1], ldc, &work[1], lwork, &iinfo); } work[1] = (doublereal) lwkopt; return 0; /* End of DORMTR */ } /* dormtr_ */ /* Subroutine */ int dpotf2_(char *uplo, integer *n, doublereal *a, integer * lda, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3; doublereal d__1; /* Builtin functions */ double sqrt(doublereal); /* Local variables */ static integer j; static doublereal ajj; extern doublereal ddot_(integer *, doublereal *, integer *, doublereal *, integer *); extern /* Subroutine */ int dscal_(integer *, doublereal *, doublereal *, integer *); extern logical lsame_(char *, char *); extern /* Subroutine */ int dgemv_(char *, integer *, integer *, doublereal *, doublereal *, integer *, doublereal *, integer *, doublereal *, doublereal *, integer *); static logical upper; extern /* Subroutine */ int xerbla_(char *, integer *); /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University February 29, 1992 Purpose ======= DPOTF2 computes the Cholesky factorization of a real symmetric positive definite matrix A. The factorization has the form A = U' * U , if UPLO = 'U', or A = L * L', if UPLO = 'L', where U is an upper triangular matrix and L is lower triangular. This is the unblocked version of the algorithm, calling Level 2 BLAS. Arguments ========= UPLO (input) CHARACTER*1 Specifies whether the upper or lower triangular part of the symmetric matrix A is stored. = 'U': Upper triangular = 'L': Lower triangular N (input) INTEGER The order of the matrix A. N >= 0. 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, and the strictly lower triangular part of A is not referenced. If UPLO = 'L', the leading n by n lower triangular part of A contains the lower triangular part of the matrix A, and the strictly upper triangular part of A is not referenced. On exit, if INFO = 0, the factor U or L from the Cholesky factorization A = U'*U or A = L*L'. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,N). INFO (output) INTEGER = 0: successful exit < 0: if INFO = -k, the k-th argument had an illegal value > 0: if INFO = k, the leading minor of order k is not positive definite, and the factorization could not be completed. ===================================================================== Test the input parameters. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; /* Function Body */ *info = 0; upper = lsame_(uplo, "U"); if (! upper && ! lsame_(uplo, "L")) { *info = -1; } else if (*n < 0) { *info = -2; } else if (*lda < max(1,*n)) { *info = -4; } if (*info != 0) { i__1 = -(*info); xerbla_("DPOTF2", &i__1); return 0; } /* Quick return if possible */ if (*n == 0) { return 0; } if (upper) { /* Compute the Cholesky factorization A = U'*U. */ i__1 = *n; for (j = 1; j <= i__1; ++j) { /* Compute U(J,J) and test for non-positive-definiteness. */ i__2 = j - 1; ajj = a[j + j * a_dim1] - ddot_(&i__2, &a[j * a_dim1 + 1], &c__1, &a[j * a_dim1 + 1], &c__1); if (ajj <= 0.) { a[j + j * a_dim1] = ajj; goto L30; } ajj = sqrt(ajj); a[j + j * a_dim1] = ajj; /* Compute elements J+1:N of row J. */ if (j < *n) { i__2 = j - 1; i__3 = *n - j; dgemv_("Transpose", &i__2, &i__3, &c_b3001, &a[(j + 1) * a_dim1 + 1], lda, &a[j * a_dim1 + 1], &c__1, &c_b2865, &a[j + (j + 1) * a_dim1], lda); i__2 = *n - j; d__1 = 1. / ajj; dscal_(&i__2, &d__1, &a[j + (j + 1) * a_dim1], lda); } /* L10: */ } } else { /* Compute the Cholesky factorization A = L*L'. */ i__1 = *n; for (j = 1; j <= i__1; ++j) { /* Compute L(J,J) and test for non-positive-definiteness. */ i__2 = j - 1; ajj = a[j + j * a_dim1] - ddot_(&i__2, &a[j + a_dim1], lda, &a[j + a_dim1], lda); if (ajj <= 0.) { a[j + j * a_dim1] = ajj; goto L30; } ajj = sqrt(ajj); a[j + j * a_dim1] = ajj; /* Compute elements J+1:N of column J. */ if (j < *n) { i__2 = *n - j; i__3 = j - 1; dgemv_("No transpose", &i__2, &i__3, &c_b3001, &a[j + 1 + a_dim1], lda, &a[j + a_dim1], lda, &c_b2865, &a[j + 1 + j * a_dim1], &c__1); i__2 = *n - j; d__1 = 1. / ajj; dscal_(&i__2, &d__1, &a[j + 1 + j * a_dim1], &c__1); } /* L20: */ } } goto L40; L30: *info = j; L40: return 0; /* End of DPOTF2 */ } /* dpotf2_ */ /* Subroutine */ int dpotrf_(char *uplo, integer *n, doublereal *a, integer * lda, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3, i__4; /* Local variables */ static integer j, jb, nb; extern /* Subroutine */ int dgemm_(char *, char *, integer *, integer *, integer *, doublereal *, doublereal *, integer *, doublereal *, integer *, doublereal *, doublereal *, integer *); extern logical lsame_(char *, char *); extern /* Subroutine */ int dtrsm_(char *, char *, char *, char *, integer *, integer *, doublereal *, doublereal *, integer *, doublereal *, integer *); static logical upper; extern /* Subroutine */ int dsyrk_(char *, char *, integer *, integer *, doublereal *, doublereal *, integer *, doublereal *, doublereal *, integer *), dpotf2_(char *, integer *, doublereal *, integer *, integer *), xerbla_(char *, integer *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University March 31, 1993 Purpose ======= DPOTRF computes the Cholesky factorization of a real symmetric positive definite matrix A. The factorization has the form A = U**T * U, if UPLO = 'U', or A = L * L**T, if UPLO = 'L', where U is an upper triangular matrix and L is lower triangular. This is the block version of the algorithm, calling Level 3 BLAS. Arguments ========= UPLO (input) CHARACTER*1 = 'U': Upper triangle of A is stored; = 'L': Lower triangle of A is stored. N (input) INTEGER The order of the matrix A. N >= 0. 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, and the strictly lower triangular part of A is not referenced. If UPLO = 'L', the leading N-by-N lower triangular part of A contains the lower triangular part of the matrix A, and the strictly upper triangular part of A is not referenced. On exit, if INFO = 0, the factor U or L from the Cholesky factorization A = U**T*U or A = L*L**T. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,N). INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value > 0: if INFO = i, the leading minor of order i is not positive definite, and the factorization could not be completed. ===================================================================== Test the input parameters. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; /* Function Body */ *info = 0; upper = lsame_(uplo, "U"); if (! upper && ! lsame_(uplo, "L")) { *info = -1; } else if (*n < 0) { *info = -2; } else if (*lda < max(1,*n)) { *info = -4; } if (*info != 0) { i__1 = -(*info); xerbla_("DPOTRF", &i__1); return 0; } /* Quick return if possible */ if (*n == 0) { return 0; } /* Determine the block size for this environment. */ nb = ilaenv_(&c__1, "DPOTRF", uplo, n, &c_n1, &c_n1, &c_n1, (ftnlen)6, ( ftnlen)1); if ((nb <= 1) || (nb >= *n)) { /* Use unblocked code. */ dpotf2_(uplo, n, &a[a_offset], lda, info); } else { /* Use blocked code. */ if (upper) { /* Compute the Cholesky factorization A = U'*U. */ i__1 = *n; i__2 = nb; for (j = 1; i__2 < 0 ? j >= i__1 : j <= i__1; j += i__2) { /* Update and factorize the current diagonal block and test for non-positive-definiteness. Computing MIN */ i__3 = nb, i__4 = *n - j + 1; jb = min(i__3,i__4); i__3 = j - 1; dsyrk_("Upper", "Transpose", &jb, &i__3, &c_b3001, &a[j * a_dim1 + 1], lda, &c_b2865, &a[j + j * a_dim1], lda); dpotf2_("Upper", &jb, &a[j + j * a_dim1], lda, info); if (*info != 0) { goto L30; } if (j + jb <= *n) { /* Compute the current block row. */ i__3 = *n - j - jb + 1; i__4 = j - 1; dgemm_("Transpose", "No transpose", &jb, &i__3, &i__4, & c_b3001, &a[j * a_dim1 + 1], lda, &a[(j + jb) * a_dim1 + 1], lda, &c_b2865, &a[j + (j + jb) * a_dim1], lda); i__3 = *n - j - jb + 1; dtrsm_("Left", "Upper", "Transpose", "Non-unit", &jb, & i__3, &c_b2865, &a[j + j * a_dim1], lda, &a[j + ( j + jb) * a_dim1], lda); } /* L10: */ } } else { /* Compute the Cholesky factorization A = L*L'. */ i__2 = *n; i__1 = nb; for (j = 1; i__1 < 0 ? j >= i__2 : j <= i__2; j += i__1) { /* Update and factorize the current diagonal block and test for non-positive-definiteness. Computing MIN */ i__3 = nb, i__4 = *n - j + 1; jb = min(i__3,i__4); i__3 = j - 1; dsyrk_("Lower", "No transpose", &jb, &i__3, &c_b3001, &a[j + a_dim1], lda, &c_b2865, &a[j + j * a_dim1], lda); dpotf2_("Lower", &jb, &a[j + j * a_dim1], lda, info); if (*info != 0) { goto L30; } if (j + jb <= *n) { /* Compute the current block column. */ i__3 = *n - j - jb + 1; i__4 = j - 1; dgemm_("No transpose", "Transpose", &i__3, &jb, &i__4, & c_b3001, &a[j + jb + a_dim1], lda, &a[j + a_dim1], lda, &c_b2865, &a[j + jb + j * a_dim1], lda); i__3 = *n - j - jb + 1; dtrsm_("Right", "Lower", "Transpose", "Non-unit", &i__3, & jb, &c_b2865, &a[j + j * a_dim1], lda, &a[j + jb + j * a_dim1], lda); } /* L20: */ } } } goto L40; L30: *info = *info + j - 1; L40: return 0; /* End of DPOTRF */ } /* dpotrf_ */ /* Subroutine */ int dpotri_(char *uplo, integer *n, doublereal *a, integer * lda, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1; /* Local variables */ extern logical lsame_(char *, char *); extern /* Subroutine */ int xerbla_(char *, integer *), dlauum_( char *, integer *, doublereal *, integer *, integer *), dtrtri_(char *, char *, integer *, doublereal *, integer *, integer *); /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University March 31, 1993 Purpose ======= DPOTRI computes the inverse of a real symmetric positive definite matrix A using the Cholesky factorization A = U**T*U or A = L*L**T computed by DPOTRF. Arguments ========= UPLO (input) CHARACTER*1 = 'U': Upper triangle of A is stored; = 'L': Lower triangle of A is stored. N (input) INTEGER The order of the matrix A. N >= 0. A (input/output) DOUBLE PRECISION array, dimension (LDA,N) On entry, the triangular factor U or L from the Cholesky factorization A = U**T*U or A = L*L**T, as computed by DPOTRF. On exit, the upper or lower triangle of the (symmetric) inverse of A, overwriting the input factor U or L. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,N). INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value > 0: if INFO = i, the (i,i) element of the factor U or L is zero, and the inverse could not be computed. ===================================================================== Test the input parameters. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; /* Function Body */ *info = 0; if (! lsame_(uplo, "U") && ! lsame_(uplo, "L")) { *info = -1; } else if (*n < 0) { *info = -2; } else if (*lda < max(1,*n)) { *info = -4; } if (*info != 0) { i__1 = -(*info); xerbla_("DPOTRI", &i__1); return 0; } /* Quick return if possible */ if (*n == 0) { return 0; } /* Invert the triangular Cholesky factor U or L. */ dtrtri_(uplo, "Non-unit", n, &a[a_offset], lda, info); if (*info > 0) { return 0; } /* Form inv(U)*inv(U)' or inv(L)'*inv(L). */ dlauum_(uplo, n, &a[a_offset], lda, info); return 0; /* End of DPOTRI */ } /* dpotri_ */ /* Subroutine */ int dpotrs_(char *uplo, integer *n, integer *nrhs, doublereal *a, integer *lda, doublereal *b, integer *ldb, integer * info) { /* System generated locals */ integer a_dim1, a_offset, b_dim1, b_offset, i__1; /* Local variables */ extern logical lsame_(char *, char *); extern /* Subroutine */ int dtrsm_(char *, char *, char *, char *, integer *, integer *, doublereal *, doublereal *, integer *, doublereal *, integer *); static logical upper; extern /* Subroutine */ int xerbla_(char *, integer *); /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University March 31, 1993 Purpose ======= DPOTRS solves a system of linear equations A*X = B with a symmetric positive definite matrix A using the Cholesky factorization A = U**T*U or A = L*L**T computed by DPOTRF. Arguments ========= UPLO (input) CHARACTER*1 = 'U': Upper triangle of A is stored; = 'L': Lower triangle of A is stored. N (input) INTEGER The order of the matrix A. N >= 0. NRHS (input) INTEGER The number of right hand sides, i.e., the number of columns of the matrix B. NRHS >= 0. A (input) DOUBLE PRECISION array, dimension (LDA,N) The triangular factor U or L from the Cholesky factorization A = U**T*U or A = L*L**T, as computed by DPOTRF. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,N). B (input/output) DOUBLE PRECISION array, dimension (LDB,NRHS) On entry, the right hand side matrix B. On exit, the solution matrix X. LDB (input) INTEGER The leading dimension of the array B. LDB >= max(1,N). INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value ===================================================================== Test the input parameters. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; b_dim1 = *ldb; b_offset = 1 + b_dim1; b -= b_offset; /* Function Body */ *info = 0; upper = lsame_(uplo, "U"); if (! upper && ! lsame_(uplo, "L")) { *info = -1; } else if (*n < 0) { *info = -2; } else if (*nrhs < 0) { *info = -3; } else if (*lda < max(1,*n)) { *info = -5; } else if (*ldb < max(1,*n)) { *info = -7; } if (*info != 0) { i__1 = -(*info); xerbla_("DPOTRS", &i__1); return 0; } /* Quick return if possible */ if ((*n == 0) || (*nrhs == 0)) { return 0; } if (upper) { /* Solve A*X = B where A = U'*U. Solve U'*X = B, overwriting B with X. */ dtrsm_("Left", "Upper", "Transpose", "Non-unit", n, nrhs, &c_b2865, & a[a_offset], lda, &b[b_offset], ldb); /* Solve U*X = B, overwriting B with X. */ dtrsm_("Left", "Upper", "No transpose", "Non-unit", n, nrhs, &c_b2865, &a[a_offset], lda, &b[b_offset], ldb); } else { /* Solve A*X = B where A = L*L'. Solve L*X = B, overwriting B with X. */ dtrsm_("Left", "Lower", "No transpose", "Non-unit", n, nrhs, &c_b2865, &a[a_offset], lda, &b[b_offset], ldb); /* Solve L'*X = B, overwriting B with X. */ dtrsm_("Left", "Lower", "Transpose", "Non-unit", n, nrhs, &c_b2865, & a[a_offset], lda, &b[b_offset], ldb); } return 0; /* End of DPOTRS */ } /* dpotrs_ */ /* Subroutine */ int dstedc_(char *compz, integer *n, doublereal *d__, doublereal *e, doublereal *z__, integer *ldz, doublereal *work, integer *lwork, integer *iwork, integer *liwork, integer *info) { /* System generated locals */ integer z_dim1, z_offset, i__1, i__2; doublereal d__1, d__2; /* Builtin functions */ double log(doublereal); integer pow_ii(integer *, integer *); double sqrt(doublereal); /* Local variables */ static integer i__, j, k, m; static doublereal p; static integer ii, end, lgn; static doublereal eps, tiny; extern /* Subroutine */ int dgemm_(char *, char *, integer *, integer *, integer *, doublereal *, doublereal *, integer *, doublereal *, integer *, doublereal *, doublereal *, integer *); extern logical lsame_(char *, char *); extern /* Subroutine */ int dswap_(integer *, doublereal *, integer *, doublereal *, integer *); static integer lwmin; extern /* Subroutine */ int dlaed0_(integer *, integer *, integer *, doublereal *, doublereal *, doublereal *, integer *, doublereal *, integer *, doublereal *, integer *, integer *); static integer start; extern /* Subroutine */ int dlascl_(char *, integer *, integer *, doublereal *, doublereal *, integer *, integer *, doublereal *, integer *, integer *), dlacpy_(char *, integer *, integer *, doublereal *, integer *, doublereal *, integer *), dlaset_(char *, integer *, integer *, doublereal *, doublereal *, doublereal *, integer *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); extern /* Subroutine */ int xerbla_(char *, integer *); extern doublereal dlanst_(char *, integer *, doublereal *, doublereal *); extern /* Subroutine */ int dsterf_(integer *, doublereal *, doublereal *, integer *), dlasrt_(char *, integer *, doublereal *, integer *); static integer liwmin, icompz; extern /* Subroutine */ int dsteqr_(char *, integer *, doublereal *, doublereal *, doublereal *, integer *, doublereal *, integer *); static doublereal orgnrm; static logical lquery; static integer smlsiz, dtrtrw, storez; /* -- LAPACK driver routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= DSTEDC computes all eigenvalues and, optionally, eigenvectors of a symmetric tridiagonal matrix using the divide and conquer method. The eigenvectors of a full or band real symmetric matrix can also be found if DSYTRD or DSPTRD or DSBTRD has been used to reduce this matrix to tridiagonal form. This code makes very mild assumptions about floating point arithmetic. It will work on machines with a guard digit in add/subtract, or on those binary machines without guard digits which subtract like the Cray X-MP, Cray Y-MP, Cray C-90, or Cray-2. It could conceivably fail on hexadecimal or decimal machines without guard digits, but we know of none. See DLAED3 for details. Arguments ========= COMPZ (input) CHARACTER*1 = 'N': Compute eigenvalues only. = 'I': Compute eigenvectors of tridiagonal matrix also. = 'V': Compute eigenvectors of original dense symmetric matrix also. On entry, Z contains the orthogonal matrix used to reduce the original matrix to tridiagonal form. N (input) INTEGER The dimension of the symmetric tridiagonal matrix. N >= 0. D (input/output) DOUBLE PRECISION array, dimension (N) On entry, the diagonal elements of the tridiagonal matrix. On exit, if INFO = 0, the eigenvalues in ascending order. E (input/output) DOUBLE PRECISION array, dimension (N-1) On entry, the subdiagonal elements of the tridiagonal matrix. On exit, E has been destroyed. Z (input/output) DOUBLE PRECISION array, dimension (LDZ,N) On entry, if COMPZ = 'V', then Z contains the orthogonal matrix used in the reduction to tridiagonal form. On exit, if INFO = 0, then if COMPZ = 'V', Z contains the orthonormal eigenvectors of the original symmetric matrix, and if COMPZ = 'I', Z contains the orthonormal eigenvectors of the symmetric tridiagonal matrix. If COMPZ = 'N', then Z is not referenced. LDZ (input) INTEGER The leading dimension of the array Z. LDZ >= 1. If eigenvectors are desired, then LDZ >= max(1,N). WORK (workspace/output) DOUBLE PRECISION array, dimension (LWORK) On exit, if INFO = 0, WORK(1) returns the optimal LWORK. LWORK (input) INTEGER The dimension of the array WORK. If COMPZ = 'N' or N <= 1 then LWORK must be at least 1. If COMPZ = 'V' and N > 1 then LWORK must be at least ( 1 + 3*N + 2*N*lg N + 3*N**2 ), where lg( N ) = smallest integer k such that 2**k >= N. If COMPZ = 'I' and N > 1 then LWORK must be at least ( 1 + 4*N + N**2 ). If LWORK = -1, then a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued by XERBLA. IWORK (workspace/output) INTEGER array, dimension (LIWORK) On exit, if INFO = 0, IWORK(1) returns the optimal LIWORK. LIWORK (input) INTEGER The dimension of the array IWORK. If COMPZ = 'N' or N <= 1 then LIWORK must be at least 1. If COMPZ = 'V' and N > 1 then LIWORK must be at least ( 6 + 6*N + 5*N*lg N ). If COMPZ = 'I' and N > 1 then LIWORK must be at least ( 3 + 5*N ). If LIWORK = -1, then a workspace query is assumed; the routine only calculates the optimal size of the IWORK array, returns this value as the first entry of the IWORK array, and no error message related to LIWORK is issued by XERBLA. INFO (output) INTEGER = 0: successful exit. < 0: if INFO = -i, the i-th argument had an illegal value. > 0: The algorithm failed to compute an eigenvalue while working on the submatrix lying in rows and columns INFO/(N+1) through mod(INFO,N+1). Further Details =============== Based on contributions by Jeff Rutter, Computer Science Division, University of California at Berkeley, USA Modified by Francoise Tisseur, University of Tennessee. ===================================================================== Test the input parameters. */ /* Parameter adjustments */ --d__; --e; z_dim1 = *ldz; z_offset = 1 + z_dim1; z__ -= z_offset; --work; --iwork; /* Function Body */ *info = 0; lquery = (*lwork == -1) || (*liwork == -1); if (lsame_(compz, "N")) { icompz = 0; } else if (lsame_(compz, "V")) { icompz = 1; } else if (lsame_(compz, "I")) { icompz = 2; } else { icompz = -1; } if ((*n <= 1) || (icompz <= 0)) { liwmin = 1; lwmin = 1; } else { lgn = (integer) (log((doublereal) (*n)) / log(2.)); if (pow_ii(&c__2, &lgn) < *n) { ++lgn; } if (pow_ii(&c__2, &lgn) < *n) { ++lgn; } if (icompz == 1) { /* Computing 2nd power */ i__1 = *n; lwmin = *n * 3 + 1 + ((*n) << (1)) * lgn + i__1 * i__1 * 3; liwmin = *n * 6 + 6 + *n * 5 * lgn; } else if (icompz == 2) { /* Computing 2nd power */ i__1 = *n; lwmin = ((*n) << (2)) + 1 + i__1 * i__1; liwmin = *n * 5 + 3; } } if (icompz < 0) { *info = -1; } else if (*n < 0) { *info = -2; } else if ((*ldz < 1) || (icompz > 0 && *ldz < max(1,*n))) { *info = -6; } else if (*lwork < lwmin && ! lquery) { *info = -8; } else if (*liwork < liwmin && ! lquery) { *info = -10; } if (*info == 0) { work[1] = (doublereal) lwmin; iwork[1] = liwmin; } if (*info != 0) { i__1 = -(*info); xerbla_("DSTEDC", &i__1); return 0; } else if (lquery) { return 0; } /* Quick return if possible */ if (*n == 0) { return 0; } if (*n == 1) { if (icompz != 0) { z__[z_dim1 + 1] = 1.; } return 0; } smlsiz = ilaenv_(&c__9, "DSTEDC", " ", &c__0, &c__0, &c__0, &c__0, ( ftnlen)6, (ftnlen)1); /* If the following conditional clause is removed, then the routine will use the Divide and Conquer routine to compute only the eigenvalues, which requires (3N + 3N**2) real workspace and (2 + 5N + 2N lg(N)) integer workspace. Since on many architectures DSTERF is much faster than any other algorithm for finding eigenvalues only, it is used here as the default. If COMPZ = 'N', use DSTERF to compute the eigenvalues. */ if (icompz == 0) { dsterf_(n, &d__[1], &e[1], info); return 0; } /* If N is smaller than the minimum divide size (SMLSIZ+1), then solve the problem with another solver. */ if (*n <= smlsiz) { if (icompz == 0) { dsterf_(n, &d__[1], &e[1], info); return 0; } else if (icompz == 2) { dsteqr_("I", n, &d__[1], &e[1], &z__[z_offset], ldz, &work[1], info); return 0; } else { dsteqr_("V", n, &d__[1], &e[1], &z__[z_offset], ldz, &work[1], info); return 0; } } /* If COMPZ = 'V', the Z matrix must be stored elsewhere for later use. */ if (icompz == 1) { storez = *n * *n + 1; } else { storez = 1; } if (icompz == 2) { dlaset_("Full", n, n, &c_b2879, &c_b2865, &z__[z_offset], ldz); } /* Scale. */ orgnrm = dlanst_("M", n, &d__[1], &e[1]); if (orgnrm == 0.) { return 0; } eps = EPSILON; start = 1; /* while ( START <= N ) */ L10: if (start <= *n) { /* Let END be the position of the next subdiagonal entry such that E( END ) <= TINY or END = N if no such subdiagonal exists. The matrix identified by the elements between START and END constitutes an independent sub-problem. */ end = start; L20: if (end < *n) { tiny = eps * sqrt((d__1 = d__[end], abs(d__1))) * sqrt((d__2 = d__[end + 1], abs(d__2))); if ((d__1 = e[end], abs(d__1)) > tiny) { ++end; goto L20; } } /* (Sub) Problem determined. Compute its size and solve it. */ m = end - start + 1; if (m == 1) { start = end + 1; goto L10; } if (m > smlsiz) { *info = smlsiz; /* Scale. */ orgnrm = dlanst_("M", &m, &d__[start], &e[start]); dlascl_("G", &c__0, &c__0, &orgnrm, &c_b2865, &m, &c__1, &d__[ start], &m, info); i__1 = m - 1; i__2 = m - 1; dlascl_("G", &c__0, &c__0, &orgnrm, &c_b2865, &i__1, &c__1, &e[ start], &i__2, info); if (icompz == 1) { dtrtrw = 1; } else { dtrtrw = start; } dlaed0_(&icompz, n, &m, &d__[start], &e[start], &z__[dtrtrw + start * z_dim1], ldz, &work[1], n, &work[storez], &iwork[ 1], info); if (*info != 0) { *info = (*info / (m + 1) + start - 1) * (*n + 1) + *info % (m + 1) + start - 1; return 0; } /* Scale back. */ dlascl_("G", &c__0, &c__0, &c_b2865, &orgnrm, &m, &c__1, &d__[ start], &m, info); } else { if (icompz == 1) { /* Since QR won't update a Z matrix which is larger than the length of D, we must solve the sub-problem in a workspace and then multiply back into Z. */ dsteqr_("I", &m, &d__[start], &e[start], &work[1], &m, &work[ m * m + 1], info); dlacpy_("A", n, &m, &z__[start * z_dim1 + 1], ldz, &work[ storez], n); dgemm_("N", "N", n, &m, &m, &c_b2865, &work[storez], ldz, & work[1], &m, &c_b2879, &z__[start * z_dim1 + 1], ldz); } else if (icompz == 2) { dsteqr_("I", &m, &d__[start], &e[start], &z__[start + start * z_dim1], ldz, &work[1], info); } else { dsterf_(&m, &d__[start], &e[start], info); } if (*info != 0) { *info = start * (*n + 1) + end; return 0; } } start = end + 1; goto L10; } /* endwhile If the problem split any number of times, then the eigenvalues will not be properly ordered. Here we permute the eigenvalues (and the associated eigenvectors) into ascending order. */ if (m != *n) { if (icompz == 0) { /* Use Quick Sort */ dlasrt_("I", n, &d__[1], info); } else { /* Use Selection Sort to minimize swaps of eigenvectors */ i__1 = *n; for (ii = 2; ii <= i__1; ++ii) { i__ = ii - 1; k = i__; p = d__[i__]; i__2 = *n; for (j = ii; j <= i__2; ++j) { if (d__[j] < p) { k = j; p = d__[j]; } /* L30: */ } if (k != i__) { d__[k] = d__[i__]; d__[i__] = p; dswap_(n, &z__[i__ * z_dim1 + 1], &c__1, &z__[k * z_dim1 + 1], &c__1); } /* L40: */ } } } work[1] = (doublereal) lwmin; iwork[1] = liwmin; return 0; /* End of DSTEDC */ } /* dstedc_ */ /* Subroutine */ int dsteqr_(char *compz, integer *n, doublereal *d__, doublereal *e, doublereal *z__, integer *ldz, doublereal *work, integer *info) { /* System generated locals */ integer z_dim1, z_offset, i__1, i__2; doublereal d__1, d__2; /* Builtin functions */ double sqrt(doublereal), d_sign(doublereal *, doublereal *); /* Local variables */ static doublereal b, c__, f, g; static integer i__, j, k, l, m; static doublereal p, r__, s; static integer l1, ii, mm, lm1, mm1, nm1; static doublereal rt1, rt2, eps; static integer lsv; static doublereal tst, eps2; static integer lend, jtot; extern /* Subroutine */ int dlae2_(doublereal *, doublereal *, doublereal *, doublereal *, doublereal *); extern logical lsame_(char *, char *); extern /* Subroutine */ int dlasr_(char *, char *, char *, integer *, integer *, doublereal *, doublereal *, doublereal *, integer *); static doublereal anorm; extern /* Subroutine */ int dswap_(integer *, doublereal *, integer *, doublereal *, integer *), dlaev2_(doublereal *, doublereal *, doublereal *, doublereal *, doublereal *, doublereal *, doublereal *); static integer lendm1, lendp1; static integer iscale; extern /* Subroutine */ int dlascl_(char *, integer *, integer *, doublereal *, doublereal *, integer *, integer *, doublereal *, integer *, integer *), dlaset_(char *, integer *, integer *, doublereal *, doublereal *, doublereal *, integer *); static doublereal safmin; extern /* Subroutine */ int dlartg_(doublereal *, doublereal *, doublereal *, doublereal *, doublereal *); static doublereal safmax; extern /* Subroutine */ int xerbla_(char *, integer *); extern doublereal dlanst_(char *, integer *, doublereal *, doublereal *); extern /* Subroutine */ int dlasrt_(char *, integer *, doublereal *, integer *); static integer lendsv; static doublereal ssfmin; static integer nmaxit, icompz; static doublereal ssfmax; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University September 30, 1994 Purpose ======= DSTEQR computes all eigenvalues and, optionally, eigenvectors of a symmetric tridiagonal matrix using the implicit QL or QR method. The eigenvectors of a full or band symmetric matrix can also be found if DSYTRD or DSPTRD or DSBTRD has been used to reduce this matrix to tridiagonal form. Arguments ========= COMPZ (input) CHARACTER*1 = 'N': Compute eigenvalues only. = 'V': Compute eigenvalues and eigenvectors of the original symmetric matrix. On entry, Z must contain the orthogonal matrix used to reduce the original matrix to tridiagonal form. = 'I': Compute eigenvalues and eigenvectors of the tridiagonal matrix. Z is initialized to the identity matrix. N (input) INTEGER The order of the matrix. N >= 0. D (input/output) DOUBLE PRECISION array, dimension (N) On entry, the diagonal elements of the tridiagonal matrix. On exit, if INFO = 0, the eigenvalues in ascending order. E (input/output) DOUBLE PRECISION array, dimension (N-1) On entry, the (n-1) subdiagonal elements of the tridiagonal matrix. On exit, E has been destroyed. Z (input/output) DOUBLE PRECISION array, dimension (LDZ, N) On entry, if COMPZ = 'V', then Z contains the orthogonal matrix used in the reduction to tridiagonal form. On exit, if INFO = 0, then if COMPZ = 'V', Z contains the orthonormal eigenvectors of the original symmetric matrix, and if COMPZ = 'I', Z contains the orthonormal eigenvectors of the symmetric tridiagonal matrix. If COMPZ = 'N', then Z is not referenced. LDZ (input) INTEGER The leading dimension of the array Z. LDZ >= 1, and if eigenvectors are desired, then LDZ >= max(1,N). WORK (workspace) DOUBLE PRECISION array, dimension (max(1,2*N-2)) If COMPZ = 'N', then WORK is not referenced. INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value > 0: the algorithm has failed to find all the eigenvalues in a total of 30*N iterations; if INFO = i, then i elements of E have not converged to zero; on exit, D and E contain the elements of a symmetric tridiagonal matrix which is orthogonally similar to the original matrix. ===================================================================== Test the input parameters. */ /* Parameter adjustments */ --d__; --e; z_dim1 = *ldz; z_offset = 1 + z_dim1; z__ -= z_offset; --work; /* Function Body */ *info = 0; if (lsame_(compz, "N")) { icompz = 0; } else if (lsame_(compz, "V")) { icompz = 1; } else if (lsame_(compz, "I")) { icompz = 2; } else { icompz = -1; } if (icompz < 0) { *info = -1; } else if (*n < 0) { *info = -2; } else if ((*ldz < 1) || (icompz > 0 && *ldz < max(1,*n))) { *info = -6; } if (*info != 0) { i__1 = -(*info); xerbla_("DSTEQR", &i__1); return 0; } /* Quick return if possible */ if (*n == 0) { return 0; } if (*n == 1) { if (icompz == 2) { z__[z_dim1 + 1] = 1.; } return 0; } /* Determine the unit roundoff and over/underflow thresholds. */ eps = EPSILON; /* Computing 2nd power */ d__1 = eps; eps2 = d__1 * d__1; safmin = SAFEMINIMUM; safmax = 1. / safmin; ssfmax = sqrt(safmax) / 3.; ssfmin = sqrt(safmin) / eps2; /* Compute the eigenvalues and eigenvectors of the tridiagonal matrix. */ if (icompz == 2) { dlaset_("Full", n, n, &c_b2879, &c_b2865, &z__[z_offset], ldz); } nmaxit = *n * 30; jtot = 0; /* Determine where the matrix splits and choose QL or QR iteration for each block, according to whether top or bottom diagonal element is smaller. */ l1 = 1; nm1 = *n - 1; L10: if (l1 > *n) { goto L160; } if (l1 > 1) { e[l1 - 1] = 0.; } if (l1 <= nm1) { i__1 = nm1; for (m = l1; m <= i__1; ++m) { tst = (d__1 = e[m], abs(d__1)); if (tst == 0.) { goto L30; } if (tst <= sqrt((d__1 = d__[m], abs(d__1))) * sqrt((d__2 = d__[m + 1], abs(d__2))) * eps) { e[m] = 0.; goto L30; } /* L20: */ } } m = *n; L30: l = l1; lsv = l; lend = m; lendsv = lend; l1 = m + 1; if (lend == l) { goto L10; } /* Scale submatrix in rows and columns L to LEND */ i__1 = lend - l + 1; anorm = dlanst_("I", &i__1, &d__[l], &e[l]); iscale = 0; if (anorm == 0.) { goto L10; } if (anorm > ssfmax) { iscale = 1; i__1 = lend - l + 1; dlascl_("G", &c__0, &c__0, &anorm, &ssfmax, &i__1, &c__1, &d__[l], n, info); i__1 = lend - l; dlascl_("G", &c__0, &c__0, &anorm, &ssfmax, &i__1, &c__1, &e[l], n, info); } else if (anorm < ssfmin) { iscale = 2; i__1 = lend - l + 1; dlascl_("G", &c__0, &c__0, &anorm, &ssfmin, &i__1, &c__1, &d__[l], n, info); i__1 = lend - l; dlascl_("G", &c__0, &c__0, &anorm, &ssfmin, &i__1, &c__1, &e[l], n, info); } /* Choose between QL and QR iteration */ if ((d__1 = d__[lend], abs(d__1)) < (d__2 = d__[l], abs(d__2))) { lend = lsv; l = lendsv; } if (lend > l) { /* QL Iteration Look for small subdiagonal element. */ L40: if (l != lend) { lendm1 = lend - 1; i__1 = lendm1; for (m = l; m <= i__1; ++m) { /* Computing 2nd power */ d__2 = (d__1 = e[m], abs(d__1)); tst = d__2 * d__2; if (tst <= eps2 * (d__1 = d__[m], abs(d__1)) * (d__2 = d__[m + 1], abs(d__2)) + safmin) { goto L60; } /* L50: */ } } m = lend; L60: if (m < lend) { e[m] = 0.; } p = d__[l]; if (m == l) { goto L80; } /* If remaining matrix is 2-by-2, use DLAE2 or SLAEV2 to compute its eigensystem. */ if (m == l + 1) { if (icompz > 0) { dlaev2_(&d__[l], &e[l], &d__[l + 1], &rt1, &rt2, &c__, &s); work[l] = c__; work[*n - 1 + l] = s; dlasr_("R", "V", "B", n, &c__2, &work[l], &work[*n - 1 + l], & z__[l * z_dim1 + 1], ldz); } else { dlae2_(&d__[l], &e[l], &d__[l + 1], &rt1, &rt2); } d__[l] = rt1; d__[l + 1] = rt2; e[l] = 0.; l += 2; if (l <= lend) { goto L40; } goto L140; } if (jtot == nmaxit) { goto L140; } ++jtot; /* Form shift. */ g = (d__[l + 1] - p) / (e[l] * 2.); r__ = dlapy2_(&g, &c_b2865); g = d__[m] - p + e[l] / (g + d_sign(&r__, &g)); s = 1.; c__ = 1.; p = 0.; /* Inner loop */ mm1 = m - 1; i__1 = l; for (i__ = mm1; i__ >= i__1; --i__) { f = s * e[i__]; b = c__ * e[i__]; dlartg_(&g, &f, &c__, &s, &r__); if (i__ != m - 1) { e[i__ + 1] = r__; } g = d__[i__ + 1] - p; r__ = (d__[i__] - g) * s + c__ * 2. * b; p = s * r__; d__[i__ + 1] = g + p; g = c__ * r__ - b; /* If eigenvectors are desired, then save rotations. */ if (icompz > 0) { work[i__] = c__; work[*n - 1 + i__] = -s; } /* L70: */ } /* If eigenvectors are desired, then apply saved rotations. */ if (icompz > 0) { mm = m - l + 1; dlasr_("R", "V", "B", n, &mm, &work[l], &work[*n - 1 + l], &z__[l * z_dim1 + 1], ldz); } d__[l] -= p; e[l] = g; goto L40; /* Eigenvalue found. */ L80: d__[l] = p; ++l; if (l <= lend) { goto L40; } goto L140; } else { /* QR Iteration Look for small superdiagonal element. */ L90: if (l != lend) { lendp1 = lend + 1; i__1 = lendp1; for (m = l; m >= i__1; --m) { /* Computing 2nd power */ d__2 = (d__1 = e[m - 1], abs(d__1)); tst = d__2 * d__2; if (tst <= eps2 * (d__1 = d__[m], abs(d__1)) * (d__2 = d__[m - 1], abs(d__2)) + safmin) { goto L110; } /* L100: */ } } m = lend; L110: if (m > lend) { e[m - 1] = 0.; } p = d__[l]; if (m == l) { goto L130; } /* If remaining matrix is 2-by-2, use DLAE2 or SLAEV2 to compute its eigensystem. */ if (m == l - 1) { if (icompz > 0) { dlaev2_(&d__[l - 1], &e[l - 1], &d__[l], &rt1, &rt2, &c__, &s) ; work[m] = c__; work[*n - 1 + m] = s; dlasr_("R", "V", "F", n, &c__2, &work[m], &work[*n - 1 + m], & z__[(l - 1) * z_dim1 + 1], ldz); } else { dlae2_(&d__[l - 1], &e[l - 1], &d__[l], &rt1, &rt2); } d__[l - 1] = rt1; d__[l] = rt2; e[l - 1] = 0.; l += -2; if (l >= lend) { goto L90; } goto L140; } if (jtot == nmaxit) { goto L140; } ++jtot; /* Form shift. */ g = (d__[l - 1] - p) / (e[l - 1] * 2.); r__ = dlapy2_(&g, &c_b2865); g = d__[m] - p + e[l - 1] / (g + d_sign(&r__, &g)); s = 1.; c__ = 1.; p = 0.; /* Inner loop */ lm1 = l - 1; i__1 = lm1; for (i__ = m; i__ <= i__1; ++i__) { f = s * e[i__]; b = c__ * e[i__]; dlartg_(&g, &f, &c__, &s, &r__); if (i__ != m) { e[i__ - 1] = r__; } g = d__[i__] - p; r__ = (d__[i__ + 1] - g) * s + c__ * 2. * b; p = s * r__; d__[i__] = g + p; g = c__ * r__ - b; /* If eigenvectors are desired, then save rotations. */ if (icompz > 0) { work[i__] = c__; work[*n - 1 + i__] = s; } /* L120: */ } /* If eigenvectors are desired, then apply saved rotations. */ if (icompz > 0) { mm = l - m + 1; dlasr_("R", "V", "F", n, &mm, &work[m], &work[*n - 1 + m], &z__[m * z_dim1 + 1], ldz); } d__[l] -= p; e[lm1] = g; goto L90; /* Eigenvalue found. */ L130: d__[l] = p; --l; if (l >= lend) { goto L90; } goto L140; } /* Undo scaling if necessary */ L140: if (iscale == 1) { i__1 = lendsv - lsv + 1; dlascl_("G", &c__0, &c__0, &ssfmax, &anorm, &i__1, &c__1, &d__[lsv], n, info); i__1 = lendsv - lsv; dlascl_("G", &c__0, &c__0, &ssfmax, &anorm, &i__1, &c__1, &e[lsv], n, info); } else if (iscale == 2) { i__1 = lendsv - lsv + 1; dlascl_("G", &c__0, &c__0, &ssfmin, &anorm, &i__1, &c__1, &d__[lsv], n, info); i__1 = lendsv - lsv; dlascl_("G", &c__0, &c__0, &ssfmin, &anorm, &i__1, &c__1, &e[lsv], n, info); } /* Check for no convergence to an eigenvalue after a total of N*MAXIT iterations. */ if (jtot < nmaxit) { goto L10; } i__1 = *n - 1; for (i__ = 1; i__ <= i__1; ++i__) { if (e[i__] != 0.) { ++(*info); } /* L150: */ } goto L190; /* Order eigenvalues and eigenvectors. */ L160: if (icompz == 0) { /* Use Quick Sort */ dlasrt_("I", n, &d__[1], info); } else { /* Use Selection Sort to minimize swaps of eigenvectors */ i__1 = *n; for (ii = 2; ii <= i__1; ++ii) { i__ = ii - 1; k = i__; p = d__[i__]; i__2 = *n; for (j = ii; j <= i__2; ++j) { if (d__[j] < p) { k = j; p = d__[j]; } /* L170: */ } if (k != i__) { d__[k] = d__[i__]; d__[i__] = p; dswap_(n, &z__[i__ * z_dim1 + 1], &c__1, &z__[k * z_dim1 + 1], &c__1); } /* L180: */ } } L190: return 0; /* End of DSTEQR */ } /* dsteqr_ */ /* Subroutine */ int dsterf_(integer *n, doublereal *d__, doublereal *e, integer *info) { /* System generated locals */ integer i__1; doublereal d__1, d__2, d__3; /* Builtin functions */ double sqrt(doublereal), d_sign(doublereal *, doublereal *); /* Local variables */ static doublereal c__; static integer i__, l, m; static doublereal p, r__, s; static integer l1; static doublereal bb, rt1, rt2, eps, rte; static integer lsv; static doublereal eps2, oldc; static integer lend, jtot; extern /* Subroutine */ int dlae2_(doublereal *, doublereal *, doublereal *, doublereal *, doublereal *); static doublereal gamma, alpha, sigma, anorm; static integer iscale; extern /* Subroutine */ int dlascl_(char *, integer *, integer *, doublereal *, doublereal *, integer *, integer *, doublereal *, integer *, integer *); static doublereal oldgam, safmin; extern /* Subroutine */ int xerbla_(char *, integer *); static doublereal safmax; extern doublereal dlanst_(char *, integer *, doublereal *, doublereal *); extern /* Subroutine */ int dlasrt_(char *, integer *, doublereal *, integer *); static integer lendsv; static doublereal ssfmin; static integer nmaxit; static doublereal ssfmax; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= DSTERF computes all eigenvalues of a symmetric tridiagonal matrix using the Pal-Walker-Kahan variant of the QL or QR algorithm. Arguments ========= N (input) INTEGER The order of the matrix. N >= 0. D (input/output) DOUBLE PRECISION array, dimension (N) On entry, the n diagonal elements of the tridiagonal matrix. On exit, if INFO = 0, the eigenvalues in ascending order. E (input/output) DOUBLE PRECISION array, dimension (N-1) On entry, the (n-1) subdiagonal elements of the tridiagonal matrix. On exit, E has been destroyed. INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value > 0: the algorithm failed to find all of the eigenvalues in a total of 30*N iterations; if INFO = i, then i elements of E have not converged to zero. ===================================================================== Test the input parameters. */ /* Parameter adjustments */ --e; --d__; /* Function Body */ *info = 0; /* Quick return if possible */ if (*n < 0) { *info = -1; i__1 = -(*info); xerbla_("DSTERF", &i__1); return 0; } if (*n <= 1) { return 0; } /* Determine the unit roundoff for this environment. */ eps = EPSILON; /* Computing 2nd power */ d__1 = eps; eps2 = d__1 * d__1; safmin = SAFEMINIMUM; safmax = 1. / safmin; ssfmax = sqrt(safmax) / 3.; ssfmin = sqrt(safmin) / eps2; /* Compute the eigenvalues of the tridiagonal matrix. */ nmaxit = *n * 30; sigma = 0.; jtot = 0; /* Determine where the matrix splits and choose QL or QR iteration for each block, according to whether top or bottom diagonal element is smaller. */ l1 = 1; L10: if (l1 > *n) { goto L170; } if (l1 > 1) { e[l1 - 1] = 0.; } i__1 = *n - 1; for (m = l1; m <= i__1; ++m) { if ((d__3 = e[m], abs(d__3)) <= sqrt((d__1 = d__[m], abs(d__1))) * sqrt((d__2 = d__[m + 1], abs(d__2))) * eps) { e[m] = 0.; goto L30; } /* L20: */ } m = *n; L30: l = l1; lsv = l; lend = m; lendsv = lend; l1 = m + 1; if (lend == l) { goto L10; } /* Scale submatrix in rows and columns L to LEND */ i__1 = lend - l + 1; anorm = dlanst_("I", &i__1, &d__[l], &e[l]); iscale = 0; if (anorm > ssfmax) { iscale = 1; i__1 = lend - l + 1; dlascl_("G", &c__0, &c__0, &anorm, &ssfmax, &i__1, &c__1, &d__[l], n, info); i__1 = lend - l; dlascl_("G", &c__0, &c__0, &anorm, &ssfmax, &i__1, &c__1, &e[l], n, info); } else if (anorm < ssfmin) { iscale = 2; i__1 = lend - l + 1; dlascl_("G", &c__0, &c__0, &anorm, &ssfmin, &i__1, &c__1, &d__[l], n, info); i__1 = lend - l; dlascl_("G", &c__0, &c__0, &anorm, &ssfmin, &i__1, &c__1, &e[l], n, info); } i__1 = lend - 1; for (i__ = l; i__ <= i__1; ++i__) { /* Computing 2nd power */ d__1 = e[i__]; e[i__] = d__1 * d__1; /* L40: */ } /* Choose between QL and QR iteration */ if ((d__1 = d__[lend], abs(d__1)) < (d__2 = d__[l], abs(d__2))) { lend = lsv; l = lendsv; } if (lend >= l) { /* QL Iteration Look for small subdiagonal element. */ L50: if (l != lend) { i__1 = lend - 1; for (m = l; m <= i__1; ++m) { if ((d__2 = e[m], abs(d__2)) <= eps2 * (d__1 = d__[m] * d__[m + 1], abs(d__1))) { goto L70; } /* L60: */ } } m = lend; L70: if (m < lend) { e[m] = 0.; } p = d__[l]; if (m == l) { goto L90; } /* If remaining matrix is 2 by 2, use DLAE2 to compute its eigenvalues. */ if (m == l + 1) { rte = sqrt(e[l]); dlae2_(&d__[l], &rte, &d__[l + 1], &rt1, &rt2); d__[l] = rt1; d__[l + 1] = rt2; e[l] = 0.; l += 2; if (l <= lend) { goto L50; } goto L150; } if (jtot == nmaxit) { goto L150; } ++jtot; /* Form shift. */ rte = sqrt(e[l]); sigma = (d__[l + 1] - p) / (rte * 2.); r__ = dlapy2_(&sigma, &c_b2865); sigma = p - rte / (sigma + d_sign(&r__, &sigma)); c__ = 1.; s = 0.; gamma = d__[m] - sigma; p = gamma * gamma; /* Inner loop */ i__1 = l; for (i__ = m - 1; i__ >= i__1; --i__) { bb = e[i__]; r__ = p + bb; if (i__ != m - 1) { e[i__ + 1] = s * r__; } oldc = c__; c__ = p / r__; s = bb / r__; oldgam = gamma; alpha = d__[i__]; gamma = c__ * (alpha - sigma) - s * oldgam; d__[i__ + 1] = oldgam + (alpha - gamma); if (c__ != 0.) { p = gamma * gamma / c__; } else { p = oldc * bb; } /* L80: */ } e[l] = s * p; d__[l] = sigma + gamma; goto L50; /* Eigenvalue found. */ L90: d__[l] = p; ++l; if (l <= lend) { goto L50; } goto L150; } else { /* QR Iteration Look for small superdiagonal element. */ L100: i__1 = lend + 1; for (m = l; m >= i__1; --m) { if ((d__2 = e[m - 1], abs(d__2)) <= eps2 * (d__1 = d__[m] * d__[m - 1], abs(d__1))) { goto L120; } /* L110: */ } m = lend; L120: if (m > lend) { e[m - 1] = 0.; } p = d__[l]; if (m == l) { goto L140; } /* If remaining matrix is 2 by 2, use DLAE2 to compute its eigenvalues. */ if (m == l - 1) { rte = sqrt(e[l - 1]); dlae2_(&d__[l], &rte, &d__[l - 1], &rt1, &rt2); d__[l] = rt1; d__[l - 1] = rt2; e[l - 1] = 0.; l += -2; if (l >= lend) { goto L100; } goto L150; } if (jtot == nmaxit) { goto L150; } ++jtot; /* Form shift. */ rte = sqrt(e[l - 1]); sigma = (d__[l - 1] - p) / (rte * 2.); r__ = dlapy2_(&sigma, &c_b2865); sigma = p - rte / (sigma + d_sign(&r__, &sigma)); c__ = 1.; s = 0.; gamma = d__[m] - sigma; p = gamma * gamma; /* Inner loop */ i__1 = l - 1; for (i__ = m; i__ <= i__1; ++i__) { bb = e[i__]; r__ = p + bb; if (i__ != m) { e[i__ - 1] = s * r__; } oldc = c__; c__ = p / r__; s = bb / r__; oldgam = gamma; alpha = d__[i__ + 1]; gamma = c__ * (alpha - sigma) - s * oldgam; d__[i__] = oldgam + (alpha - gamma); if (c__ != 0.) { p = gamma * gamma / c__; } else { p = oldc * bb; } /* L130: */ } e[l - 1] = s * p; d__[l] = sigma + gamma; goto L100; /* Eigenvalue found. */ L140: d__[l] = p; --l; if (l >= lend) { goto L100; } goto L150; } /* Undo scaling if necessary */ L150: if (iscale == 1) { i__1 = lendsv - lsv + 1; dlascl_("G", &c__0, &c__0, &ssfmax, &anorm, &i__1, &c__1, &d__[lsv], n, info); } if (iscale == 2) { i__1 = lendsv - lsv + 1; dlascl_("G", &c__0, &c__0, &ssfmin, &anorm, &i__1, &c__1, &d__[lsv], n, info); } /* Check for no convergence to an eigenvalue after a total of N*MAXIT iterations. */ if (jtot < nmaxit) { goto L10; } i__1 = *n - 1; for (i__ = 1; i__ <= i__1; ++i__) { if (e[i__] != 0.) { ++(*info); } /* L160: */ } goto L180; /* Sort eigenvalues in increasing order. */ L170: dlasrt_("I", n, &d__[1], info); L180: return 0; /* End of DSTERF */ } /* dsterf_ */ /* Subroutine */ int dsyevd_(char *jobz, char *uplo, integer *n, doublereal * a, integer *lda, doublereal *w, doublereal *work, integer *lwork, integer *iwork, integer *liwork, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3; doublereal d__1; /* Builtin functions */ double sqrt(doublereal); /* Local variables */ static doublereal eps; static integer inde; static doublereal anrm, rmin, rmax; static integer lopt; extern /* Subroutine */ int dscal_(integer *, doublereal *, doublereal *, integer *); static doublereal sigma; extern logical lsame_(char *, char *); static integer iinfo, lwmin, liopt; static logical lower, wantz; static integer indwk2, llwrk2; static integer iscale; extern /* Subroutine */ int dlascl_(char *, integer *, integer *, doublereal *, doublereal *, integer *, integer *, doublereal *, integer *, integer *), dstedc_(char *, integer *, doublereal *, doublereal *, doublereal *, integer *, doublereal *, integer *, integer *, integer *, integer *), dlacpy_( char *, integer *, integer *, doublereal *, integer *, doublereal *, integer *); static doublereal safmin; extern /* Subroutine */ int xerbla_(char *, integer *); static doublereal bignum; static integer indtau; extern /* Subroutine */ int dsterf_(integer *, doublereal *, doublereal *, integer *); extern doublereal dlansy_(char *, char *, integer *, doublereal *, integer *, doublereal *); static integer indwrk, liwmin; extern /* Subroutine */ int dormtr_(char *, char *, char *, integer *, integer *, doublereal *, integer *, doublereal *, doublereal *, integer *, doublereal *, integer *, integer *), dsytrd_(char *, integer *, doublereal *, integer *, doublereal *, doublereal *, doublereal *, doublereal *, integer *, integer *); static integer llwork; static doublereal smlnum; static logical lquery; /* -- LAPACK driver routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= DSYEVD computes all eigenvalues and, optionally, eigenvectors of a real symmetric matrix A. If eigenvectors are desired, it uses a divide and conquer algorithm. The divide and conquer algorithm makes very mild assumptions about floating point arithmetic. It will work on machines with a guard digit in add/subtract, or on those binary machines without guard digits which subtract like the Cray X-MP, Cray Y-MP, Cray C-90, or Cray-2. It could conceivably fail on hexadecimal or decimal machines without guard digits, but we know of none. Because of large use of BLAS of level 3, DSYEVD needs N**2 more workspace than DSYEVX. Arguments ========= JOBZ (input) CHARACTER*1 = 'N': Compute eigenvalues only; = 'V': Compute eigenvalues and eigenvectors. UPLO (input) CHARACTER*1 = 'U': Upper triangle of A is stored; = 'L': Lower triangle of A is stored. N (input) INTEGER The order of the matrix A. N >= 0. 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. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,N). W (output) DOUBLE PRECISION array, dimension (N) If INFO = 0, the eigenvalues in ascending order. WORK (workspace/output) DOUBLE PRECISION array, dimension (LWORK) On exit, if INFO = 0, WORK(1) returns the optimal LWORK. LWORK (input) INTEGER The dimension of the array WORK. If N <= 1, LWORK must be at least 1. If JOBZ = 'N' and N > 1, LWORK must be at least 2*N+1. If JOBZ = 'V' and N > 1, LWORK must be at least 1 + 6*N + 2*N**2. If LWORK = -1, then a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued by XERBLA. IWORK (workspace/output) INTEGER array, dimension (LIWORK) On exit, if INFO = 0, IWORK(1) returns the optimal LIWORK. LIWORK (input) INTEGER The dimension of the array IWORK. If N <= 1, LIWORK must be at least 1. If JOBZ = 'N' and N > 1, LIWORK must be at least 1. If JOBZ = 'V' and N > 1, LIWORK must be at least 3 + 5*N. If LIWORK = -1, then a workspace query is assumed; the routine only calculates the optimal size of the IWORK array, returns this value as the first entry of the IWORK array, and no error message related to LIWORK is issued by XERBLA. 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. Further Details =============== Based on contributions by Jeff Rutter, Computer Science Division, University of California at Berkeley, USA Modified by Francoise Tisseur, University of Tennessee. ===================================================================== Test the input parameters. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --w; --work; --iwork; /* Function Body */ wantz = lsame_(jobz, "V"); lower = lsame_(uplo, "L"); lquery = (*lwork == -1) || (*liwork == -1); *info = 0; if (*n <= 1) { liwmin = 1; lwmin = 1; lopt = lwmin; liopt = liwmin; } else { if (wantz) { liwmin = *n * 5 + 3; /* Computing 2nd power */ i__1 = *n; lwmin = *n * 6 + 1 + ((i__1 * i__1) << (1)); } else { liwmin = 1; lwmin = ((*n) << (1)) + 1; } lopt = lwmin; liopt = liwmin; } if (! ((wantz) || (lsame_(jobz, "N")))) { *info = -1; } else if (! ((lower) || (lsame_(uplo, "U")))) { *info = -2; } else if (*n < 0) { *info = -3; } else if (*lda < max(1,*n)) { *info = -5; } else if (*lwork < lwmin && ! lquery) { *info = -8; } else if (*liwork < liwmin && ! lquery) { *info = -10; } if (*info == 0) { work[1] = (doublereal) lopt; iwork[1] = liopt; } if (*info != 0) { i__1 = -(*info); xerbla_("DSYEVD", &i__1); return 0; } else if (lquery) { return 0; } /* Quick return if possible */ if (*n == 0) { return 0; } if (*n == 1) { w[1] = a[a_dim1 + 1]; if (wantz) { a[a_dim1 + 1] = 1.; } return 0; } /* Get machine constants. */ safmin = SAFEMINIMUM; eps = PRECISION; smlnum = safmin / eps; bignum = 1. / smlnum; rmin = sqrt(smlnum); rmax = sqrt(bignum); /* Scale matrix to allowable range, if necessary. */ anrm = dlansy_("M", uplo, n, &a[a_offset], lda, &work[1]); iscale = 0; if (anrm > 0. && anrm < rmin) { iscale = 1; sigma = rmin / anrm; } else if (anrm > rmax) { iscale = 1; sigma = rmax / anrm; } if (iscale == 1) { dlascl_(uplo, &c__0, &c__0, &c_b2865, &sigma, n, n, &a[a_offset], lda, info); } /* Call DSYTRD to reduce symmetric matrix to tridiagonal form. */ inde = 1; indtau = inde + *n; indwrk = indtau + *n; llwork = *lwork - indwrk + 1; indwk2 = indwrk + *n * *n; llwrk2 = *lwork - indwk2 + 1; dsytrd_(uplo, n, &a[a_offset], lda, &w[1], &work[inde], &work[indtau], & work[indwrk], &llwork, &iinfo); lopt = (integer) (((*n) << (1)) + work[indwrk]); /* For eigenvalues only, call DSTERF. For eigenvectors, first call DSTEDC to generate the eigenvector matrix, WORK(INDWRK), of the tridiagonal matrix, then call DORMTR to multiply it by the Householder transformations stored in A. */ if (! wantz) { dsterf_(n, &w[1], &work[inde], info); } else { dstedc_("I", n, &w[1], &work[inde], &work[indwrk], n, &work[indwk2], & llwrk2, &iwork[1], liwork, info); dormtr_("L", uplo, "N", n, n, &a[a_offset], lda, &work[indtau], &work[ indwrk], n, &work[indwk2], &llwrk2, &iinfo); dlacpy_("A", n, n, &work[indwrk], n, &a[a_offset], lda); /* Computing MAX Computing 2nd power */ i__3 = *n; i__1 = lopt, i__2 = *n * 6 + 1 + ((i__3 * i__3) << (1)); lopt = max(i__1,i__2); } /* If matrix was scaled, then rescale eigenvalues appropriately. */ if (iscale == 1) { d__1 = 1. / sigma; dscal_(n, &d__1, &w[1], &c__1); } work[1] = (doublereal) lopt; iwork[1] = liopt; return 0; /* End of DSYEVD */ } /* dsyevd_ */ /* Subroutine */ int dsytd2_(char *uplo, integer *n, doublereal *a, integer * lda, doublereal *d__, doublereal *e, doublereal *tau, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3; /* Local variables */ static integer i__; extern doublereal ddot_(integer *, doublereal *, integer *, doublereal *, integer *); static doublereal taui; extern /* Subroutine */ int dsyr2_(char *, integer *, doublereal *, doublereal *, integer *, doublereal *, integer *, doublereal *, integer *); static doublereal alpha; extern logical lsame_(char *, char *); extern /* Subroutine */ int daxpy_(integer *, doublereal *, doublereal *, integer *, doublereal *, integer *); static logical upper; extern /* Subroutine */ int dsymv_(char *, integer *, doublereal *, doublereal *, integer *, doublereal *, integer *, doublereal *, doublereal *, integer *), dlarfg_(integer *, doublereal *, doublereal *, integer *, doublereal *), xerbla_(char *, integer * ); /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University October 31, 1992 Purpose ======= DSYTD2 reduces a real symmetric matrix A to symmetric tridiagonal form T by an orthogonal similarity transformation: Q' * A * Q = T. Arguments ========= UPLO (input) CHARACTER*1 Specifies whether the upper or lower triangular part of the symmetric matrix A is stored: = 'U': Upper triangular = 'L': Lower triangular N (input) INTEGER The order of the matrix A. N >= 0. 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, and the strictly lower triangular part of A is not referenced. If UPLO = 'L', the leading n-by-n lower triangular part of A contains the lower triangular part of the matrix A, and the strictly upper triangular part of A is not referenced. On exit, if UPLO = 'U', the diagonal and first superdiagonal of A are overwritten by the corresponding elements of the tridiagonal matrix T, and the elements above the first superdiagonal, with the array TAU, represent the orthogonal matrix Q as a product of elementary reflectors; if UPLO = 'L', the diagonal and first subdiagonal of A are over- written by the corresponding elements of the tridiagonal matrix T, and the elements below the first subdiagonal, with the array TAU, represent the orthogonal matrix Q as a product of elementary reflectors. See Further Details. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,N). D (output) DOUBLE PRECISION array, dimension (N) The diagonal elements of the tridiagonal matrix T: D(i) = A(i,i). E (output) DOUBLE PRECISION array, dimension (N-1) The off-diagonal elements of the tridiagonal matrix T: E(i) = A(i,i+1) if UPLO = 'U', E(i) = A(i+1,i) if UPLO = 'L'. TAU (output) DOUBLE PRECISION array, dimension (N-1) The scalar factors of the elementary reflectors (see Further Details). INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value. Further Details =============== If UPLO = 'U', the matrix Q is represented as a product of elementary reflectors Q = H(n-1) . . . H(2) H(1). Each H(i) has the form H(i) = I - tau * v * v' where tau is a real scalar, and v is a real vector with v(i+1:n) = 0 and v(i) = 1; v(1:i-1) is stored on exit in A(1:i-1,i+1), and tau in TAU(i). If UPLO = 'L', the matrix Q is represented as a product of elementary reflectors Q = H(1) H(2) . . . H(n-1). Each H(i) has the form H(i) = I - tau * v * v' where tau is a real scalar, and v is a real vector with v(1:i) = 0 and v(i+1) = 1; v(i+2:n) is stored on exit in A(i+2:n,i), and tau in TAU(i). The contents of A on exit are illustrated by the following examples with n = 5: if UPLO = 'U': if UPLO = 'L': ( d e v2 v3 v4 ) ( d ) ( d e v3 v4 ) ( e d ) ( d e v4 ) ( v1 e d ) ( d e ) ( v1 v2 e d ) ( d ) ( v1 v2 v3 e d ) where d and e denote diagonal and off-diagonal elements of T, and vi denotes an element of the vector defining H(i). ===================================================================== Test the input parameters */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --d__; --e; --tau; /* Function Body */ *info = 0; upper = lsame_(uplo, "U"); if (! upper && ! lsame_(uplo, "L")) { *info = -1; } else if (*n < 0) { *info = -2; } else if (*lda < max(1,*n)) { *info = -4; } if (*info != 0) { i__1 = -(*info); xerbla_("DSYTD2", &i__1); return 0; } /* Quick return if possible */ if (*n <= 0) { return 0; } if (upper) { /* Reduce the upper triangle of A */ for (i__ = *n - 1; i__ >= 1; --i__) { /* Generate elementary reflector H(i) = I - tau * v * v' to annihilate A(1:i-1,i+1) */ dlarfg_(&i__, &a[i__ + (i__ + 1) * a_dim1], &a[(i__ + 1) * a_dim1 + 1], &c__1, &taui); e[i__] = a[i__ + (i__ + 1) * a_dim1]; if (taui != 0.) { /* Apply H(i) from both sides to A(1:i,1:i) */ a[i__ + (i__ + 1) * a_dim1] = 1.; /* Compute x := tau * A * v storing x in TAU(1:i) */ dsymv_(uplo, &i__, &taui, &a[a_offset], lda, &a[(i__ + 1) * a_dim1 + 1], &c__1, &c_b2879, &tau[1], &c__1); /* Compute w := x - 1/2 * tau * (x'*v) * v */ alpha = taui * -.5 * ddot_(&i__, &tau[1], &c__1, &a[(i__ + 1) * a_dim1 + 1], &c__1); daxpy_(&i__, &alpha, &a[(i__ + 1) * a_dim1 + 1], &c__1, &tau[ 1], &c__1); /* Apply the transformation as a rank-2 update: A := A - v * w' - w * v' */ dsyr2_(uplo, &i__, &c_b3001, &a[(i__ + 1) * a_dim1 + 1], & c__1, &tau[1], &c__1, &a[a_offset], lda); a[i__ + (i__ + 1) * a_dim1] = e[i__]; } d__[i__ + 1] = a[i__ + 1 + (i__ + 1) * a_dim1]; tau[i__] = taui; /* L10: */ } d__[1] = a[a_dim1 + 1]; } else { /* Reduce the lower triangle of A */ i__1 = *n - 1; for (i__ = 1; i__ <= i__1; ++i__) { /* Generate elementary reflector H(i) = I - tau * v * v' to annihilate A(i+2:n,i) */ i__2 = *n - i__; /* Computing MIN */ i__3 = i__ + 2; dlarfg_(&i__2, &a[i__ + 1 + i__ * a_dim1], &a[min(i__3,*n) + i__ * a_dim1], &c__1, &taui); e[i__] = a[i__ + 1 + i__ * a_dim1]; if (taui != 0.) { /* Apply H(i) from both sides to A(i+1:n,i+1:n) */ a[i__ + 1 + i__ * a_dim1] = 1.; /* Compute x := tau * A * v storing y in TAU(i:n-1) */ i__2 = *n - i__; dsymv_(uplo, &i__2, &taui, &a[i__ + 1 + (i__ + 1) * a_dim1], lda, &a[i__ + 1 + i__ * a_dim1], &c__1, &c_b2879, & tau[i__], &c__1); /* Compute w := x - 1/2 * tau * (x'*v) * v */ i__2 = *n - i__; alpha = taui * -.5 * ddot_(&i__2, &tau[i__], &c__1, &a[i__ + 1 + i__ * a_dim1], &c__1); i__2 = *n - i__; daxpy_(&i__2, &alpha, &a[i__ + 1 + i__ * a_dim1], &c__1, &tau[ i__], &c__1); /* Apply the transformation as a rank-2 update: A := A - v * w' - w * v' */ i__2 = *n - i__; dsyr2_(uplo, &i__2, &c_b3001, &a[i__ + 1 + i__ * a_dim1], & c__1, &tau[i__], &c__1, &a[i__ + 1 + (i__ + 1) * a_dim1], lda); a[i__ + 1 + i__ * a_dim1] = e[i__]; } d__[i__] = a[i__ + i__ * a_dim1]; tau[i__] = taui; /* L20: */ } d__[*n] = a[*n + *n * a_dim1]; } return 0; /* End of DSYTD2 */ } /* dsytd2_ */ /* Subroutine */ int dsytrd_(char *uplo, integer *n, doublereal *a, integer * lda, doublereal *d__, doublereal *e, doublereal *tau, doublereal * work, integer *lwork, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3; /* Local variables */ static integer i__, j, nb, kk, nx, iws; extern logical lsame_(char *, char *); static integer nbmin, iinfo; static logical upper; extern /* Subroutine */ int dsytd2_(char *, integer *, doublereal *, integer *, doublereal *, doublereal *, doublereal *, integer *), dsyr2k_(char *, char *, integer *, integer *, doublereal *, doublereal *, integer *, doublereal *, integer *, doublereal *, doublereal *, integer *), dlatrd_(char *, integer *, integer *, doublereal *, integer *, doublereal *, doublereal *, doublereal *, integer *), xerbla_(char *, integer *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); static integer ldwork, lwkopt; static logical lquery; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= DSYTRD reduces a real symmetric matrix A to real symmetric tridiagonal form T by an orthogonal similarity transformation: Q**T * A * Q = T. Arguments ========= UPLO (input) CHARACTER*1 = 'U': Upper triangle of A is stored; = 'L': Lower triangle of A is stored. N (input) INTEGER The order of the matrix A. N >= 0. 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, and the strictly lower triangular part of A is not referenced. If UPLO = 'L', the leading N-by-N lower triangular part of A contains the lower triangular part of the matrix A, and the strictly upper triangular part of A is not referenced. On exit, if UPLO = 'U', the diagonal and first superdiagonal of A are overwritten by the corresponding elements of the tridiagonal matrix T, and the elements above the first superdiagonal, with the array TAU, represent the orthogonal matrix Q as a product of elementary reflectors; if UPLO = 'L', the diagonal and first subdiagonal of A are over- written by the corresponding elements of the tridiagonal matrix T, and the elements below the first subdiagonal, with the array TAU, represent the orthogonal matrix Q as a product of elementary reflectors. See Further Details. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,N). D (output) DOUBLE PRECISION array, dimension (N) The diagonal elements of the tridiagonal matrix T: D(i) = A(i,i). E (output) DOUBLE PRECISION array, dimension (N-1) The off-diagonal elements of the tridiagonal matrix T: E(i) = A(i,i+1) if UPLO = 'U', E(i) = A(i+1,i) if UPLO = 'L'. TAU (output) DOUBLE PRECISION array, dimension (N-1) The scalar factors of the elementary reflectors (see Further Details). WORK (workspace/output) DOUBLE PRECISION array, dimension (LWORK) On exit, if INFO = 0, WORK(1) returns the optimal LWORK. LWORK (input) INTEGER The dimension of the array WORK. LWORK >= 1. For optimum performance LWORK >= N*NB, where NB is the optimal blocksize. If LWORK = -1, then a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued by XERBLA. INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value Further Details =============== If UPLO = 'U', the matrix Q is represented as a product of elementary reflectors Q = H(n-1) . . . H(2) H(1). Each H(i) has the form H(i) = I - tau * v * v' where tau is a real scalar, and v is a real vector with v(i+1:n) = 0 and v(i) = 1; v(1:i-1) is stored on exit in A(1:i-1,i+1), and tau in TAU(i). If UPLO = 'L', the matrix Q is represented as a product of elementary reflectors Q = H(1) H(2) . . . H(n-1). Each H(i) has the form H(i) = I - tau * v * v' where tau is a real scalar, and v is a real vector with v(1:i) = 0 and v(i+1) = 1; v(i+2:n) is stored on exit in A(i+2:n,i), and tau in TAU(i). The contents of A on exit are illustrated by the following examples with n = 5: if UPLO = 'U': if UPLO = 'L': ( d e v2 v3 v4 ) ( d ) ( d e v3 v4 ) ( e d ) ( d e v4 ) ( v1 e d ) ( d e ) ( v1 v2 e d ) ( d ) ( v1 v2 v3 e d ) where d and e denote diagonal and off-diagonal elements of T, and vi denotes an element of the vector defining H(i). ===================================================================== Test the input parameters */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --d__; --e; --tau; --work; /* Function Body */ *info = 0; upper = lsame_(uplo, "U"); lquery = *lwork == -1; if (! upper && ! lsame_(uplo, "L")) { *info = -1; } else if (*n < 0) { *info = -2; } else if (*lda < max(1,*n)) { *info = -4; } else if (*lwork < 1 && ! lquery) { *info = -9; } if (*info == 0) { /* Determine the block size. */ nb = ilaenv_(&c__1, "DSYTRD", uplo, n, &c_n1, &c_n1, &c_n1, (ftnlen)6, (ftnlen)1); lwkopt = *n * nb; work[1] = (doublereal) lwkopt; } if (*info != 0) { i__1 = -(*info); xerbla_("DSYTRD", &i__1); return 0; } else if (lquery) { return 0; } /* Quick return if possible */ if (*n == 0) { work[1] = 1.; return 0; } nx = *n; iws = 1; if (nb > 1 && nb < *n) { /* Determine when to cross over from blocked to unblocked code (last block is always handled by unblocked code). Computing MAX */ i__1 = nb, i__2 = ilaenv_(&c__3, "DSYTRD", uplo, n, &c_n1, &c_n1, & c_n1, (ftnlen)6, (ftnlen)1); nx = max(i__1,i__2); if (nx < *n) { /* Determine if workspace is large enough for blocked code. */ ldwork = *n; iws = ldwork * nb; if (*lwork < iws) { /* Not enough workspace to use optimal NB: determine the minimum value of NB, and reduce NB or force use of unblocked code by setting NX = N. Computing MAX */ i__1 = *lwork / ldwork; nb = max(i__1,1); nbmin = ilaenv_(&c__2, "DSYTRD", uplo, n, &c_n1, &c_n1, &c_n1, (ftnlen)6, (ftnlen)1); if (nb < nbmin) { nx = *n; } } } else { nx = *n; } } else { nb = 1; } if (upper) { /* Reduce the upper triangle of A. Columns 1:kk are handled by the unblocked method. */ kk = *n - (*n - nx + nb - 1) / nb * nb; i__1 = kk + 1; i__2 = -nb; for (i__ = *n - nb + 1; i__2 < 0 ? i__ >= i__1 : i__ <= i__1; i__ += i__2) { /* Reduce columns i:i+nb-1 to tridiagonal form and form the matrix W which is needed to update the unreduced part of the matrix */ i__3 = i__ + nb - 1; dlatrd_(uplo, &i__3, &nb, &a[a_offset], lda, &e[1], &tau[1], & work[1], &ldwork); /* Update the unreduced submatrix A(1:i-1,1:i-1), using an update of the form: A := A - V*W' - W*V' */ i__3 = i__ - 1; dsyr2k_(uplo, "No transpose", &i__3, &nb, &c_b3001, &a[i__ * a_dim1 + 1], lda, &work[1], &ldwork, &c_b2865, &a[ a_offset], lda); /* Copy superdiagonal elements back into A, and diagonal elements into D */ i__3 = i__ + nb - 1; for (j = i__; j <= i__3; ++j) { a[j - 1 + j * a_dim1] = e[j - 1]; d__[j] = a[j + j * a_dim1]; /* L10: */ } /* L20: */ } /* Use unblocked code to reduce the last or only block */ dsytd2_(uplo, &kk, &a[a_offset], lda, &d__[1], &e[1], &tau[1], &iinfo); } else { /* Reduce the lower triangle of A */ i__2 = *n - nx; i__1 = nb; for (i__ = 1; i__1 < 0 ? i__ >= i__2 : i__ <= i__2; i__ += i__1) { /* Reduce columns i:i+nb-1 to tridiagonal form and form the matrix W which is needed to update the unreduced part of the matrix */ i__3 = *n - i__ + 1; dlatrd_(uplo, &i__3, &nb, &a[i__ + i__ * a_dim1], lda, &e[i__], & tau[i__], &work[1], &ldwork); /* Update the unreduced submatrix A(i+ib:n,i+ib:n), using an update of the form: A := A - V*W' - W*V' */ i__3 = *n - i__ - nb + 1; dsyr2k_(uplo, "No transpose", &i__3, &nb, &c_b3001, &a[i__ + nb + i__ * a_dim1], lda, &work[nb + 1], &ldwork, &c_b2865, &a[ i__ + nb + (i__ + nb) * a_dim1], lda); /* Copy subdiagonal elements back into A, and diagonal elements into D */ i__3 = i__ + nb - 1; for (j = i__; j <= i__3; ++j) { a[j + 1 + j * a_dim1] = e[j]; d__[j] = a[j + j * a_dim1]; /* L30: */ } /* L40: */ } /* Use unblocked code to reduce the last or only block */ i__1 = *n - i__ + 1; dsytd2_(uplo, &i__1, &a[i__ + i__ * a_dim1], lda, &d__[i__], &e[i__], &tau[i__], &iinfo); } work[1] = (doublereal) lwkopt; return 0; /* End of DSYTRD */ } /* dsytrd_ */ /* Subroutine */ int dtrevc_(char *side, char *howmny, logical *select, integer *n, doublereal *t, integer *ldt, doublereal *vl, integer * ldvl, doublereal *vr, integer *ldvr, integer *mm, integer *m, doublereal *work, integer *info) { /* System generated locals */ integer t_dim1, t_offset, vl_dim1, vl_offset, vr_dim1, vr_offset, i__1, i__2, i__3; doublereal d__1, d__2, d__3, d__4; /* Builtin functions */ double sqrt(doublereal); /* Local variables */ static integer i__, j, k; static doublereal x[4] /* was [2][2] */; static integer j1, j2, n2, ii, ki, ip, is; static doublereal wi, wr, rec, ulp, beta, emax; static logical pair; extern doublereal ddot_(integer *, doublereal *, integer *, doublereal *, integer *); static logical allv; static integer ierr; static doublereal unfl, ovfl, smin; static logical over; static doublereal vmax; static integer jnxt; extern /* Subroutine */ int dscal_(integer *, doublereal *, doublereal *, integer *); static doublereal scale; extern logical lsame_(char *, char *); extern /* Subroutine */ int dgemv_(char *, integer *, integer *, doublereal *, doublereal *, integer *, doublereal *, integer *, doublereal *, doublereal *, integer *); static doublereal remax; extern /* Subroutine */ int dcopy_(integer *, doublereal *, integer *, doublereal *, integer *); static logical leftv, bothv; extern /* Subroutine */ int daxpy_(integer *, doublereal *, doublereal *, integer *, doublereal *, integer *); static doublereal vcrit; static logical somev; static doublereal xnorm; extern /* Subroutine */ int dlaln2_(logical *, integer *, integer *, doublereal *, doublereal *, doublereal *, integer *, doublereal *, doublereal *, doublereal *, integer *, doublereal *, doublereal * , doublereal *, integer *, doublereal *, doublereal *, integer *), dlabad_(doublereal *, doublereal *); extern integer idamax_(integer *, doublereal *, integer *); extern /* Subroutine */ int xerbla_(char *, integer *); static doublereal bignum; static logical rightv; static doublereal smlnum; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= DTREVC computes some or all of the right and/or left eigenvectors of a real upper quasi-triangular matrix T. The right eigenvector x and the left eigenvector y of T corresponding to an eigenvalue w are defined by: T*x = w*x, y'*T = w*y' where y' denotes the conjugate transpose of the vector y. If all eigenvectors are requested, the routine may either return the matrices X and/or Y of right or left eigenvectors of T, or the products Q*X and/or Q*Y, where Q is an input orthogonal matrix. If T was obtained from the real-Schur factorization of an original matrix A = Q*T*Q', then Q*X and Q*Y are the matrices of right or left eigenvectors of A. T must be in Schur canonical form (as returned by DHSEQR), that is, block upper triangular with 1-by-1 and 2-by-2 diagonal blocks; each 2-by-2 diagonal block has its diagonal elements equal and its off-diagonal elements of opposite sign. Corresponding to each 2-by-2 diagonal block is a complex conjugate pair of eigenvalues and eigenvectors; only one eigenvector of the pair is computed, namely the one corresponding to the eigenvalue with positive imaginary part. Arguments ========= SIDE (input) CHARACTER*1 = 'R': compute right eigenvectors only; = 'L': compute left eigenvectors only; = 'B': compute both right and left eigenvectors. HOWMNY (input) CHARACTER*1 = 'A': compute all right and/or left eigenvectors; = 'B': compute all right and/or left eigenvectors, and backtransform them using the input matrices supplied in VR and/or VL; = 'S': compute selected right and/or left eigenvectors, specified by the logical array SELECT. SELECT (input/output) LOGICAL array, dimension (N) If HOWMNY = 'S', SELECT specifies the eigenvectors to be computed. If HOWMNY = 'A' or 'B', SELECT is not referenced. To select the real eigenvector corresponding to a real eigenvalue w(j), SELECT(j) must be set to .TRUE.. To select the complex eigenvector corresponding to a complex conjugate pair w(j) and w(j+1), either SELECT(j) or SELECT(j+1) must be set to .TRUE.; then on exit SELECT(j) is .TRUE. and SELECT(j+1) is .FALSE.. N (input) INTEGER The order of the matrix T. N >= 0. T (input) DOUBLE PRECISION array, dimension (LDT,N) The upper quasi-triangular matrix T in Schur canonical form. LDT (input) INTEGER The leading dimension of the array T. LDT >= max(1,N). VL (input/output) DOUBLE PRECISION array, dimension (LDVL,MM) On entry, if SIDE = 'L' or 'B' and HOWMNY = 'B', VL must contain an N-by-N matrix Q (usually the orthogonal matrix Q of Schur vectors returned by DHSEQR). On exit, if SIDE = 'L' or 'B', VL contains: if HOWMNY = 'A', the matrix Y of left eigenvectors of T; VL has the same quasi-lower triangular form as T'. If T(i,i) is a real eigenvalue, then the i-th column VL(i) of VL is its corresponding eigenvector. If T(i:i+1,i:i+1) is a 2-by-2 block whose eigenvalues are complex-conjugate eigenvalues of T, then VL(i)+sqrt(-1)*VL(i+1) is the complex eigenvector corresponding to the eigenvalue with positive real part. if HOWMNY = 'B', the matrix Q*Y; if HOWMNY = 'S', the left eigenvectors of T specified by SELECT, stored consecutively in the columns of VL, in the same order as their eigenvalues. A complex eigenvector corresponding to a complex eigenvalue is stored in two consecutive columns, the first holding the real part, and the second the imaginary part. If SIDE = 'R', VL is not referenced. LDVL (input) INTEGER The leading dimension of the array VL. LDVL >= max(1,N) if SIDE = 'L' or 'B'; LDVL >= 1 otherwise. VR (input/output) DOUBLE PRECISION array, dimension (LDVR,MM) On entry, if SIDE = 'R' or 'B' and HOWMNY = 'B', VR must contain an N-by-N matrix Q (usually the orthogonal matrix Q of Schur vectors returned by DHSEQR). On exit, if SIDE = 'R' or 'B', VR contains: if HOWMNY = 'A', the matrix X of right eigenvectors of T; VR has the same quasi-upper triangular form as T. If T(i,i) is a real eigenvalue, then the i-th column VR(i) of VR is its corresponding eigenvector. If T(i:i+1,i:i+1) is a 2-by-2 block whose eigenvalues are complex-conjugate eigenvalues of T, then VR(i)+sqrt(-1)*VR(i+1) is the complex eigenvector corresponding to the eigenvalue with positive real part. if HOWMNY = 'B', the matrix Q*X; if HOWMNY = 'S', the right eigenvectors of T specified by SELECT, stored consecutively in the columns of VR, in the same order as their eigenvalues. A complex eigenvector corresponding to a complex eigenvalue is stored in two consecutive columns, the first holding the real part and the second the imaginary part. If SIDE = 'L', VR is not referenced. LDVR (input) INTEGER The leading dimension of the array VR. LDVR >= max(1,N) if SIDE = 'R' or 'B'; LDVR >= 1 otherwise. MM (input) INTEGER The number of columns in the arrays VL and/or VR. MM >= M. M (output) INTEGER The number of columns in the arrays VL and/or VR actually used to store the eigenvectors. If HOWMNY = 'A' or 'B', M is set to N. Each selected real eigenvector occupies one column and each selected complex eigenvector occupies two columns. WORK (workspace) DOUBLE PRECISION array, dimension (3*N) INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value Further Details =============== The algorithm used in this program is basically backward (forward) substitution, with scaling to make the the code robust against possible overflow. Each eigenvector is normalized so that the element of largest magnitude has magnitude 1; here the magnitude of a complex number (x,y) is taken to be |x| + |y|. ===================================================================== Decode and test the input parameters */ /* Parameter adjustments */ --select; t_dim1 = *ldt; t_offset = 1 + t_dim1; t -= t_offset; vl_dim1 = *ldvl; vl_offset = 1 + vl_dim1; vl -= vl_offset; vr_dim1 = *ldvr; vr_offset = 1 + vr_dim1; vr -= vr_offset; --work; /* Function Body */ bothv = lsame_(side, "B"); rightv = (lsame_(side, "R")) || (bothv); leftv = (lsame_(side, "L")) || (bothv); allv = lsame_(howmny, "A"); over = lsame_(howmny, "B"); somev = lsame_(howmny, "S"); *info = 0; if (! rightv && ! leftv) { *info = -1; } else if (! allv && ! over && ! somev) { *info = -2; } else if (*n < 0) { *info = -4; } else if (*ldt < max(1,*n)) { *info = -6; } else if ((*ldvl < 1) || (leftv && *ldvl < *n)) { *info = -8; } else if ((*ldvr < 1) || (rightv && *ldvr < *n)) { *info = -10; } else { /* Set M to the number of columns required to store the selected eigenvectors, standardize the array SELECT if necessary, and test MM. */ if (somev) { *m = 0; pair = FALSE_; i__1 = *n; for (j = 1; j <= i__1; ++j) { if (pair) { pair = FALSE_; select[j] = FALSE_; } else { if (j < *n) { if (t[j + 1 + j * t_dim1] == 0.) { if (select[j]) { ++(*m); } } else { pair = TRUE_; if ((select[j]) || (select[j + 1])) { select[j] = TRUE_; *m += 2; } } } else { if (select[*n]) { ++(*m); } } } /* L10: */ } } else { *m = *n; } if (*mm < *m) { *info = -11; } } if (*info != 0) { i__1 = -(*info); xerbla_("DTREVC", &i__1); return 0; } /* Quick return if possible. */ if (*n == 0) { return 0; } /* Set the constants to control overflow. */ unfl = SAFEMINIMUM; ovfl = 1. / unfl; dlabad_(&unfl, &ovfl); ulp = PRECISION; smlnum = unfl * (*n / ulp); bignum = (1. - ulp) / smlnum; /* Compute 1-norm of each column of strictly upper triangular part of T to control overflow in triangular solver. */ work[1] = 0.; i__1 = *n; for (j = 2; j <= i__1; ++j) { work[j] = 0.; i__2 = j - 1; for (i__ = 1; i__ <= i__2; ++i__) { work[j] += (d__1 = t[i__ + j * t_dim1], abs(d__1)); /* L20: */ } /* L30: */ } /* Index IP is used to specify the real or complex eigenvalue: IP = 0, real eigenvalue, 1, first of conjugate complex pair: (wr,wi) -1, second of conjugate complex pair: (wr,wi) */ n2 = (*n) << (1); if (rightv) { /* Compute right eigenvectors. */ ip = 0; is = *m; for (ki = *n; ki >= 1; --ki) { if (ip == 1) { goto L130; } if (ki == 1) { goto L40; } if (t[ki + (ki - 1) * t_dim1] == 0.) { goto L40; } ip = -1; L40: if (somev) { if (ip == 0) { if (! select[ki]) { goto L130; } } else { if (! select[ki - 1]) { goto L130; } } } /* Compute the KI-th eigenvalue (WR,WI). */ wr = t[ki + ki * t_dim1]; wi = 0.; if (ip != 0) { wi = sqrt((d__1 = t[ki + (ki - 1) * t_dim1], abs(d__1))) * sqrt((d__2 = t[ki - 1 + ki * t_dim1], abs(d__2))); } /* Computing MAX */ d__1 = ulp * (abs(wr) + abs(wi)); smin = max(d__1,smlnum); if (ip == 0) { /* Real right eigenvector */ work[ki + *n] = 1.; /* Form right-hand side */ i__1 = ki - 1; for (k = 1; k <= i__1; ++k) { work[k + *n] = -t[k + ki * t_dim1]; /* L50: */ } /* Solve the upper quasi-triangular system: (T(1:KI-1,1:KI-1) - WR)*X = SCALE*WORK. */ jnxt = ki - 1; for (j = ki - 1; j >= 1; --j) { if (j > jnxt) { goto L60; } j1 = j; j2 = j; jnxt = j - 1; if (j > 1) { if (t[j + (j - 1) * t_dim1] != 0.) { j1 = j - 1; jnxt = j - 2; } } if (j1 == j2) { /* 1-by-1 diagonal block */ dlaln2_(&c_false, &c__1, &c__1, &smin, &c_b2865, &t[j + j * t_dim1], ldt, &c_b2865, &c_b2865, &work[ j + *n], n, &wr, &c_b2879, x, &c__2, &scale, & xnorm, &ierr); /* Scale X(1,1) to avoid overflow when updating the right-hand side. */ if (xnorm > 1.) { if (work[j] > bignum / xnorm) { x[0] /= xnorm; scale /= xnorm; } } /* Scale if necessary */ if (scale != 1.) { dscal_(&ki, &scale, &work[*n + 1], &c__1); } work[j + *n] = x[0]; /* Update right-hand side */ i__1 = j - 1; d__1 = -x[0]; daxpy_(&i__1, &d__1, &t[j * t_dim1 + 1], &c__1, &work[ *n + 1], &c__1); } else { /* 2-by-2 diagonal block */ dlaln2_(&c_false, &c__2, &c__1, &smin, &c_b2865, &t[j - 1 + (j - 1) * t_dim1], ldt, &c_b2865, & c_b2865, &work[j - 1 + *n], n, &wr, &c_b2879, x, &c__2, &scale, &xnorm, &ierr); /* Scale X(1,1) and X(2,1) to avoid overflow when updating the right-hand side. */ if (xnorm > 1.) { /* Computing MAX */ d__1 = work[j - 1], d__2 = work[j]; beta = max(d__1,d__2); if (beta > bignum / xnorm) { x[0] /= xnorm; x[1] /= xnorm; scale /= xnorm; } } /* Scale if necessary */ if (scale != 1.) { dscal_(&ki, &scale, &work[*n + 1], &c__1); } work[j - 1 + *n] = x[0]; work[j + *n] = x[1]; /* Update right-hand side */ i__1 = j - 2; d__1 = -x[0]; daxpy_(&i__1, &d__1, &t[(j - 1) * t_dim1 + 1], &c__1, &work[*n + 1], &c__1); i__1 = j - 2; d__1 = -x[1]; daxpy_(&i__1, &d__1, &t[j * t_dim1 + 1], &c__1, &work[ *n + 1], &c__1); } L60: ; } /* Copy the vector x or Q*x to VR and normalize. */ if (! over) { dcopy_(&ki, &work[*n + 1], &c__1, &vr[is * vr_dim1 + 1], & c__1); ii = idamax_(&ki, &vr[is * vr_dim1 + 1], &c__1); remax = 1. / (d__1 = vr[ii + is * vr_dim1], abs(d__1)); dscal_(&ki, &remax, &vr[is * vr_dim1 + 1], &c__1); i__1 = *n; for (k = ki + 1; k <= i__1; ++k) { vr[k + is * vr_dim1] = 0.; /* L70: */ } } else { if (ki > 1) { i__1 = ki - 1; dgemv_("N", n, &i__1, &c_b2865, &vr[vr_offset], ldvr, &work[*n + 1], &c__1, &work[ki + *n], &vr[ki * vr_dim1 + 1], &c__1); } ii = idamax_(n, &vr[ki * vr_dim1 + 1], &c__1); remax = 1. / (d__1 = vr[ii + ki * vr_dim1], abs(d__1)); dscal_(n, &remax, &vr[ki * vr_dim1 + 1], &c__1); } } else { /* Complex right eigenvector. Initial solve [ (T(KI-1,KI-1) T(KI-1,KI) ) - (WR + I* WI)]*X = 0. [ (T(KI,KI-1) T(KI,KI) ) ] */ if ((d__1 = t[ki - 1 + ki * t_dim1], abs(d__1)) >= (d__2 = t[ ki + (ki - 1) * t_dim1], abs(d__2))) { work[ki - 1 + *n] = 1.; work[ki + n2] = wi / t[ki - 1 + ki * t_dim1]; } else { work[ki - 1 + *n] = -wi / t[ki + (ki - 1) * t_dim1]; work[ki + n2] = 1.; } work[ki + *n] = 0.; work[ki - 1 + n2] = 0.; /* Form right-hand side */ i__1 = ki - 2; for (k = 1; k <= i__1; ++k) { work[k + *n] = -work[ki - 1 + *n] * t[k + (ki - 1) * t_dim1]; work[k + n2] = -work[ki + n2] * t[k + ki * t_dim1]; /* L80: */ } /* Solve upper quasi-triangular system: (T(1:KI-2,1:KI-2) - (WR+i*WI))*X = SCALE*(WORK+i*WORK2) */ jnxt = ki - 2; for (j = ki - 2; j >= 1; --j) { if (j > jnxt) { goto L90; } j1 = j; j2 = j; jnxt = j - 1; if (j > 1) { if (t[j + (j - 1) * t_dim1] != 0.) { j1 = j - 1; jnxt = j - 2; } } if (j1 == j2) { /* 1-by-1 diagonal block */ dlaln2_(&c_false, &c__1, &c__2, &smin, &c_b2865, &t[j + j * t_dim1], ldt, &c_b2865, &c_b2865, &work[ j + *n], n, &wr, &wi, x, &c__2, &scale, & xnorm, &ierr); /* Scale X(1,1) and X(1,2) to avoid overflow when updating the right-hand side. */ if (xnorm > 1.) { if (work[j] > bignum / xnorm) { x[0] /= xnorm; x[2] /= xnorm; scale /= xnorm; } } /* Scale if necessary */ if (scale != 1.) { dscal_(&ki, &scale, &work[*n + 1], &c__1); dscal_(&ki, &scale, &work[n2 + 1], &c__1); } work[j + *n] = x[0]; work[j + n2] = x[2]; /* Update the right-hand side */ i__1 = j - 1; d__1 = -x[0]; daxpy_(&i__1, &d__1, &t[j * t_dim1 + 1], &c__1, &work[ *n + 1], &c__1); i__1 = j - 1; d__1 = -x[2]; daxpy_(&i__1, &d__1, &t[j * t_dim1 + 1], &c__1, &work[ n2 + 1], &c__1); } else { /* 2-by-2 diagonal block */ dlaln2_(&c_false, &c__2, &c__2, &smin, &c_b2865, &t[j - 1 + (j - 1) * t_dim1], ldt, &c_b2865, & c_b2865, &work[j - 1 + *n], n, &wr, &wi, x, & c__2, &scale, &xnorm, &ierr); /* Scale X to avoid overflow when updating the right-hand side. */ if (xnorm > 1.) { /* Computing MAX */ d__1 = work[j - 1], d__2 = work[j]; beta = max(d__1,d__2); if (beta > bignum / xnorm) { rec = 1. / xnorm; x[0] *= rec; x[2] *= rec; x[1] *= rec; x[3] *= rec; scale *= rec; } } /* Scale if necessary */ if (scale != 1.) { dscal_(&ki, &scale, &work[*n + 1], &c__1); dscal_(&ki, &scale, &work[n2 + 1], &c__1); } work[j - 1 + *n] = x[0]; work[j + *n] = x[1]; work[j - 1 + n2] = x[2]; work[j + n2] = x[3]; /* Update the right-hand side */ i__1 = j - 2; d__1 = -x[0]; daxpy_(&i__1, &d__1, &t[(j - 1) * t_dim1 + 1], &c__1, &work[*n + 1], &c__1); i__1 = j - 2; d__1 = -x[1]; daxpy_(&i__1, &d__1, &t[j * t_dim1 + 1], &c__1, &work[ *n + 1], &c__1); i__1 = j - 2; d__1 = -x[2]; daxpy_(&i__1, &d__1, &t[(j - 1) * t_dim1 + 1], &c__1, &work[n2 + 1], &c__1); i__1 = j - 2; d__1 = -x[3]; daxpy_(&i__1, &d__1, &t[j * t_dim1 + 1], &c__1, &work[ n2 + 1], &c__1); } L90: ; } /* Copy the vector x or Q*x to VR and normalize. */ if (! over) { dcopy_(&ki, &work[*n + 1], &c__1, &vr[(is - 1) * vr_dim1 + 1], &c__1); dcopy_(&ki, &work[n2 + 1], &c__1, &vr[is * vr_dim1 + 1], & c__1); emax = 0.; i__1 = ki; for (k = 1; k <= i__1; ++k) { /* Computing MAX */ d__3 = emax, d__4 = (d__1 = vr[k + (is - 1) * vr_dim1] , abs(d__1)) + (d__2 = vr[k + is * vr_dim1], abs(d__2)); emax = max(d__3,d__4); /* L100: */ } remax = 1. / emax; dscal_(&ki, &remax, &vr[(is - 1) * vr_dim1 + 1], &c__1); dscal_(&ki, &remax, &vr[is * vr_dim1 + 1], &c__1); i__1 = *n; for (k = ki + 1; k <= i__1; ++k) { vr[k + (is - 1) * vr_dim1] = 0.; vr[k + is * vr_dim1] = 0.; /* L110: */ } } else { if (ki > 2) { i__1 = ki - 2; dgemv_("N", n, &i__1, &c_b2865, &vr[vr_offset], ldvr, &work[*n + 1], &c__1, &work[ki - 1 + *n], &vr[ (ki - 1) * vr_dim1 + 1], &c__1); i__1 = ki - 2; dgemv_("N", n, &i__1, &c_b2865, &vr[vr_offset], ldvr, &work[n2 + 1], &c__1, &work[ki + n2], &vr[ki * vr_dim1 + 1], &c__1); } else { dscal_(n, &work[ki - 1 + *n], &vr[(ki - 1) * vr_dim1 + 1], &c__1); dscal_(n, &work[ki + n2], &vr[ki * vr_dim1 + 1], & c__1); } emax = 0.; i__1 = *n; for (k = 1; k <= i__1; ++k) { /* Computing MAX */ d__3 = emax, d__4 = (d__1 = vr[k + (ki - 1) * vr_dim1] , abs(d__1)) + (d__2 = vr[k + ki * vr_dim1], abs(d__2)); emax = max(d__3,d__4); /* L120: */ } remax = 1. / emax; dscal_(n, &remax, &vr[(ki - 1) * vr_dim1 + 1], &c__1); dscal_(n, &remax, &vr[ki * vr_dim1 + 1], &c__1); } } --is; if (ip != 0) { --is; } L130: if (ip == 1) { ip = 0; } if (ip == -1) { ip = 1; } /* L140: */ } } if (leftv) { /* Compute left eigenvectors. */ ip = 0; is = 1; i__1 = *n; for (ki = 1; ki <= i__1; ++ki) { if (ip == -1) { goto L250; } if (ki == *n) { goto L150; } if (t[ki + 1 + ki * t_dim1] == 0.) { goto L150; } ip = 1; L150: if (somev) { if (! select[ki]) { goto L250; } } /* Compute the KI-th eigenvalue (WR,WI). */ wr = t[ki + ki * t_dim1]; wi = 0.; if (ip != 0) { wi = sqrt((d__1 = t[ki + (ki + 1) * t_dim1], abs(d__1))) * sqrt((d__2 = t[ki + 1 + ki * t_dim1], abs(d__2))); } /* Computing MAX */ d__1 = ulp * (abs(wr) + abs(wi)); smin = max(d__1,smlnum); if (ip == 0) { /* Real left eigenvector. */ work[ki + *n] = 1.; /* Form right-hand side */ i__2 = *n; for (k = ki + 1; k <= i__2; ++k) { work[k + *n] = -t[ki + k * t_dim1]; /* L160: */ } /* Solve the quasi-triangular system: (T(KI+1:N,KI+1:N) - WR)'*X = SCALE*WORK */ vmax = 1.; vcrit = bignum; jnxt = ki + 1; i__2 = *n; for (j = ki + 1; j <= i__2; ++j) { if (j < jnxt) { goto L170; } j1 = j; j2 = j; jnxt = j + 1; if (j < *n) { if (t[j + 1 + j * t_dim1] != 0.) { j2 = j + 1; jnxt = j + 2; } } if (j1 == j2) { /* 1-by-1 diagonal block Scale if necessary to avoid overflow when forming the right-hand side. */ if (work[j] > vcrit) { rec = 1. / vmax; i__3 = *n - ki + 1; dscal_(&i__3, &rec, &work[ki + *n], &c__1); vmax = 1.; vcrit = bignum; } i__3 = j - ki - 1; work[j + *n] -= ddot_(&i__3, &t[ki + 1 + j * t_dim1], &c__1, &work[ki + 1 + *n], &c__1); /* Solve (T(J,J)-WR)'*X = WORK */ dlaln2_(&c_false, &c__1, &c__1, &smin, &c_b2865, &t[j + j * t_dim1], ldt, &c_b2865, &c_b2865, &work[ j + *n], n, &wr, &c_b2879, x, &c__2, &scale, & xnorm, &ierr); /* Scale if necessary */ if (scale != 1.) { i__3 = *n - ki + 1; dscal_(&i__3, &scale, &work[ki + *n], &c__1); } work[j + *n] = x[0]; /* Computing MAX */ d__2 = (d__1 = work[j + *n], abs(d__1)); vmax = max(d__2,vmax); vcrit = bignum / vmax; } else { /* 2-by-2 diagonal block Scale if necessary to avoid overflow when forming the right-hand side. Computing MAX */ d__1 = work[j], d__2 = work[j + 1]; beta = max(d__1,d__2); if (beta > vcrit) { rec = 1. / vmax; i__3 = *n - ki + 1; dscal_(&i__3, &rec, &work[ki + *n], &c__1); vmax = 1.; vcrit = bignum; } i__3 = j - ki - 1; work[j + *n] -= ddot_(&i__3, &t[ki + 1 + j * t_dim1], &c__1, &work[ki + 1 + *n], &c__1); i__3 = j - ki - 1; work[j + 1 + *n] -= ddot_(&i__3, &t[ki + 1 + (j + 1) * t_dim1], &c__1, &work[ki + 1 + *n], &c__1); /* Solve [T(J,J)-WR T(J,J+1) ]'* X = SCALE*( WORK1 ) [T(J+1,J) T(J+1,J+1)-WR] ( WORK2 ) */ dlaln2_(&c_true, &c__2, &c__1, &smin, &c_b2865, &t[j + j * t_dim1], ldt, &c_b2865, &c_b2865, &work[ j + *n], n, &wr, &c_b2879, x, &c__2, &scale, & xnorm, &ierr); /* Scale if necessary */ if (scale != 1.) { i__3 = *n - ki + 1; dscal_(&i__3, &scale, &work[ki + *n], &c__1); } work[j + *n] = x[0]; work[j + 1 + *n] = x[1]; /* Computing MAX */ d__3 = (d__1 = work[j + *n], abs(d__1)), d__4 = (d__2 = work[j + 1 + *n], abs(d__2)), d__3 = max( d__3,d__4); vmax = max(d__3,vmax); vcrit = bignum / vmax; } L170: ; } /* Copy the vector x or Q*x to VL and normalize. */ if (! over) { i__2 = *n - ki + 1; dcopy_(&i__2, &work[ki + *n], &c__1, &vl[ki + is * vl_dim1], &c__1); i__2 = *n - ki + 1; ii = idamax_(&i__2, &vl[ki + is * vl_dim1], &c__1) + ki - 1; remax = 1. / (d__1 = vl[ii + is * vl_dim1], abs(d__1)); i__2 = *n - ki + 1; dscal_(&i__2, &remax, &vl[ki + is * vl_dim1], &c__1); i__2 = ki - 1; for (k = 1; k <= i__2; ++k) { vl[k + is * vl_dim1] = 0.; /* L180: */ } } else { if (ki < *n) { i__2 = *n - ki; dgemv_("N", n, &i__2, &c_b2865, &vl[(ki + 1) * vl_dim1 + 1], ldvl, &work[ki + 1 + *n], &c__1, &work[ki + *n], &vl[ki * vl_dim1 + 1], &c__1); } ii = idamax_(n, &vl[ki * vl_dim1 + 1], &c__1); remax = 1. / (d__1 = vl[ii + ki * vl_dim1], abs(d__1)); dscal_(n, &remax, &vl[ki * vl_dim1 + 1], &c__1); } } else { /* Complex left eigenvector. Initial solve: ((T(KI,KI) T(KI,KI+1) )' - (WR - I* WI))*X = 0. ((T(KI+1,KI) T(KI+1,KI+1)) ) */ if ((d__1 = t[ki + (ki + 1) * t_dim1], abs(d__1)) >= (d__2 = t[ki + 1 + ki * t_dim1], abs(d__2))) { work[ki + *n] = wi / t[ki + (ki + 1) * t_dim1]; work[ki + 1 + n2] = 1.; } else { work[ki + *n] = 1.; work[ki + 1 + n2] = -wi / t[ki + 1 + ki * t_dim1]; } work[ki + 1 + *n] = 0.; work[ki + n2] = 0.; /* Form right-hand side */ i__2 = *n; for (k = ki + 2; k <= i__2; ++k) { work[k + *n] = -work[ki + *n] * t[ki + k * t_dim1]; work[k + n2] = -work[ki + 1 + n2] * t[ki + 1 + k * t_dim1] ; /* L190: */ } /* Solve complex quasi-triangular system: ( T(KI+2,N:KI+2,N) - (WR-i*WI) )*X = WORK1+i*WORK2 */ vmax = 1.; vcrit = bignum; jnxt = ki + 2; i__2 = *n; for (j = ki + 2; j <= i__2; ++j) { if (j < jnxt) { goto L200; } j1 = j; j2 = j; jnxt = j + 1; if (j < *n) { if (t[j + 1 + j * t_dim1] != 0.) { j2 = j + 1; jnxt = j + 2; } } if (j1 == j2) { /* 1-by-1 diagonal block Scale if necessary to avoid overflow when forming the right-hand side elements. */ if (work[j] > vcrit) { rec = 1. / vmax; i__3 = *n - ki + 1; dscal_(&i__3, &rec, &work[ki + *n], &c__1); i__3 = *n - ki + 1; dscal_(&i__3, &rec, &work[ki + n2], &c__1); vmax = 1.; vcrit = bignum; } i__3 = j - ki - 2; work[j + *n] -= ddot_(&i__3, &t[ki + 2 + j * t_dim1], &c__1, &work[ki + 2 + *n], &c__1); i__3 = j - ki - 2; work[j + n2] -= ddot_(&i__3, &t[ki + 2 + j * t_dim1], &c__1, &work[ki + 2 + n2], &c__1); /* Solve (T(J,J)-(WR-i*WI))*(X11+i*X12)= WK+I*WK2 */ d__1 = -wi; dlaln2_(&c_false, &c__1, &c__2, &smin, &c_b2865, &t[j + j * t_dim1], ldt, &c_b2865, &c_b2865, &work[ j + *n], n, &wr, &d__1, x, &c__2, &scale, & xnorm, &ierr); /* Scale if necessary */ if (scale != 1.) { i__3 = *n - ki + 1; dscal_(&i__3, &scale, &work[ki + *n], &c__1); i__3 = *n - ki + 1; dscal_(&i__3, &scale, &work[ki + n2], &c__1); } work[j + *n] = x[0]; work[j + n2] = x[2]; /* Computing MAX */ d__3 = (d__1 = work[j + *n], abs(d__1)), d__4 = (d__2 = work[j + n2], abs(d__2)), d__3 = max(d__3, d__4); vmax = max(d__3,vmax); vcrit = bignum / vmax; } else { /* 2-by-2 diagonal block Scale if necessary to avoid overflow when forming the right-hand side elements. Computing MAX */ d__1 = work[j], d__2 = work[j + 1]; beta = max(d__1,d__2); if (beta > vcrit) { rec = 1. / vmax; i__3 = *n - ki + 1; dscal_(&i__3, &rec, &work[ki + *n], &c__1); i__3 = *n - ki + 1; dscal_(&i__3, &rec, &work[ki + n2], &c__1); vmax = 1.; vcrit = bignum; } i__3 = j - ki - 2; work[j + *n] -= ddot_(&i__3, &t[ki + 2 + j * t_dim1], &c__1, &work[ki + 2 + *n], &c__1); i__3 = j - ki - 2; work[j + n2] -= ddot_(&i__3, &t[ki + 2 + j * t_dim1], &c__1, &work[ki + 2 + n2], &c__1); i__3 = j - ki - 2; work[j + 1 + *n] -= ddot_(&i__3, &t[ki + 2 + (j + 1) * t_dim1], &c__1, &work[ki + 2 + *n], &c__1); i__3 = j - ki - 2; work[j + 1 + n2] -= ddot_(&i__3, &t[ki + 2 + (j + 1) * t_dim1], &c__1, &work[ki + 2 + n2], &c__1); /* Solve 2-by-2 complex linear equation ([T(j,j) T(j,j+1) ]'-(wr-i*wi)*I)*X = SCALE*B ([T(j+1,j) T(j+1,j+1)] ) */ d__1 = -wi; dlaln2_(&c_true, &c__2, &c__2, &smin, &c_b2865, &t[j + j * t_dim1], ldt, &c_b2865, &c_b2865, &work[ j + *n], n, &wr, &d__1, x, &c__2, &scale, & xnorm, &ierr); /* Scale if necessary */ if (scale != 1.) { i__3 = *n - ki + 1; dscal_(&i__3, &scale, &work[ki + *n], &c__1); i__3 = *n - ki + 1; dscal_(&i__3, &scale, &work[ki + n2], &c__1); } work[j + *n] = x[0]; work[j + n2] = x[2]; work[j + 1 + *n] = x[1]; work[j + 1 + n2] = x[3]; /* Computing MAX */ d__1 = abs(x[0]), d__2 = abs(x[2]), d__1 = max(d__1, d__2), d__2 = abs(x[1]), d__1 = max(d__1,d__2) , d__2 = abs(x[3]), d__1 = max(d__1,d__2); vmax = max(d__1,vmax); vcrit = bignum / vmax; } L200: ; } /* Copy the vector x or Q*x to VL and normalize. L210: */ if (! over) { i__2 = *n - ki + 1; dcopy_(&i__2, &work[ki + *n], &c__1, &vl[ki + is * vl_dim1], &c__1); i__2 = *n - ki + 1; dcopy_(&i__2, &work[ki + n2], &c__1, &vl[ki + (is + 1) * vl_dim1], &c__1); emax = 0.; i__2 = *n; for (k = ki; k <= i__2; ++k) { /* Computing MAX */ d__3 = emax, d__4 = (d__1 = vl[k + is * vl_dim1], abs( d__1)) + (d__2 = vl[k + (is + 1) * vl_dim1], abs(d__2)); emax = max(d__3,d__4); /* L220: */ } remax = 1. / emax; i__2 = *n - ki + 1; dscal_(&i__2, &remax, &vl[ki + is * vl_dim1], &c__1); i__2 = *n - ki + 1; dscal_(&i__2, &remax, &vl[ki + (is + 1) * vl_dim1], &c__1) ; i__2 = ki - 1; for (k = 1; k <= i__2; ++k) { vl[k + is * vl_dim1] = 0.; vl[k + (is + 1) * vl_dim1] = 0.; /* L230: */ } } else { if (ki < *n - 1) { i__2 = *n - ki - 1; dgemv_("N", n, &i__2, &c_b2865, &vl[(ki + 2) * vl_dim1 + 1], ldvl, &work[ki + 2 + *n], &c__1, &work[ki + *n], &vl[ki * vl_dim1 + 1], &c__1); i__2 = *n - ki - 1; dgemv_("N", n, &i__2, &c_b2865, &vl[(ki + 2) * vl_dim1 + 1], ldvl, &work[ki + 2 + n2], &c__1, &work[ki + 1 + n2], &vl[(ki + 1) * vl_dim1 + 1], &c__1); } else { dscal_(n, &work[ki + *n], &vl[ki * vl_dim1 + 1], & c__1); dscal_(n, &work[ki + 1 + n2], &vl[(ki + 1) * vl_dim1 + 1], &c__1); } emax = 0.; i__2 = *n; for (k = 1; k <= i__2; ++k) { /* Computing MAX */ d__3 = emax, d__4 = (d__1 = vl[k + ki * vl_dim1], abs( d__1)) + (d__2 = vl[k + (ki + 1) * vl_dim1], abs(d__2)); emax = max(d__3,d__4); /* L240: */ } remax = 1. / emax; dscal_(n, &remax, &vl[ki * vl_dim1 + 1], &c__1); dscal_(n, &remax, &vl[(ki + 1) * vl_dim1 + 1], &c__1); } } ++is; if (ip != 0) { ++is; } L250: if (ip == -1) { ip = 0; } if (ip == 1) { ip = -1; } /* L260: */ } } return 0; /* End of DTREVC */ } /* dtrevc_ */ /* Subroutine */ int dtrti2_(char *uplo, char *diag, integer *n, doublereal * a, integer *lda, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2; /* Local variables */ static integer j; static doublereal ajj; extern /* Subroutine */ int dscal_(integer *, doublereal *, doublereal *, integer *); extern logical lsame_(char *, char *); static logical upper; extern /* Subroutine */ int dtrmv_(char *, char *, char *, integer *, doublereal *, integer *, doublereal *, integer *), xerbla_(char *, integer *); static logical nounit; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University February 29, 1992 Purpose ======= DTRTI2 computes the inverse of a real upper or lower triangular matrix. This is the Level 2 BLAS version of the algorithm. Arguments ========= UPLO (input) CHARACTER*1 Specifies whether the matrix A is upper or lower triangular. = 'U': Upper triangular = 'L': Lower triangular DIAG (input) CHARACTER*1 Specifies whether or not the matrix A is unit triangular. = 'N': Non-unit triangular = 'U': Unit triangular N (input) INTEGER The order of the matrix A. N >= 0. A (input/output) DOUBLE PRECISION array, dimension (LDA,N) On entry, the triangular matrix A. If UPLO = 'U', the leading n by n upper triangular part of the array A contains the upper triangular matrix, and the strictly lower triangular part of A is not referenced. If UPLO = 'L', the leading n by n lower triangular part of the array A contains the lower triangular matrix, and the strictly upper triangular part of A is not referenced. If DIAG = 'U', the diagonal elements of A are also not referenced and are assumed to be 1. On exit, the (triangular) inverse of the original matrix, in the same storage format. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,N). INFO (output) INTEGER = 0: successful exit < 0: if INFO = -k, the k-th argument had an illegal value ===================================================================== Test the input parameters. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; /* Function Body */ *info = 0; upper = lsame_(uplo, "U"); nounit = lsame_(diag, "N"); if (! upper && ! lsame_(uplo, "L")) { *info = -1; } else if (! nounit && ! lsame_(diag, "U")) { *info = -2; } else if (*n < 0) { *info = -3; } else if (*lda < max(1,*n)) { *info = -5; } if (*info != 0) { i__1 = -(*info); xerbla_("DTRTI2", &i__1); return 0; } if (upper) { /* Compute inverse of upper triangular matrix. */ i__1 = *n; for (j = 1; j <= i__1; ++j) { if (nounit) { a[j + j * a_dim1] = 1. / a[j + j * a_dim1]; ajj = -a[j + j * a_dim1]; } else { ajj = -1.; } /* Compute elements 1:j-1 of j-th column. */ i__2 = j - 1; dtrmv_("Upper", "No transpose", diag, &i__2, &a[a_offset], lda, & a[j * a_dim1 + 1], &c__1); i__2 = j - 1; dscal_(&i__2, &ajj, &a[j * a_dim1 + 1], &c__1); /* L10: */ } } else { /* Compute inverse of lower triangular matrix. */ for (j = *n; j >= 1; --j) { if (nounit) { a[j + j * a_dim1] = 1. / a[j + j * a_dim1]; ajj = -a[j + j * a_dim1]; } else { ajj = -1.; } if (j < *n) { /* Compute elements j+1:n of j-th column. */ i__1 = *n - j; dtrmv_("Lower", "No transpose", diag, &i__1, &a[j + 1 + (j + 1) * a_dim1], lda, &a[j + 1 + j * a_dim1], &c__1); i__1 = *n - j; dscal_(&i__1, &ajj, &a[j + 1 + j * a_dim1], &c__1); } /* L20: */ } } return 0; /* End of DTRTI2 */ } /* dtrti2_ */ /* Subroutine */ int dtrtri_(char *uplo, char *diag, integer *n, doublereal * a, integer *lda, integer *info) { /* System generated locals */ address a__1[2]; integer a_dim1, a_offset, i__1, i__2[2], i__3, i__4, i__5; char ch__1[2]; /* Builtin functions */ /* Subroutine */ int s_cat(char *, char **, integer *, integer *, ftnlen); /* Local variables */ static integer j, jb, nb, nn; extern logical lsame_(char *, char *); extern /* Subroutine */ int dtrmm_(char *, char *, char *, char *, integer *, integer *, doublereal *, doublereal *, integer *, doublereal *, integer *), dtrsm_( char *, char *, char *, char *, integer *, integer *, doublereal * , doublereal *, integer *, doublereal *, integer *); static logical upper; extern /* Subroutine */ int dtrti2_(char *, char *, integer *, doublereal *, integer *, integer *), xerbla_(char *, integer *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); static logical nounit; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University March 31, 1993 Purpose ======= DTRTRI computes the inverse of a real upper or lower triangular matrix A. This is the Level 3 BLAS version of the algorithm. Arguments ========= UPLO (input) CHARACTER*1 = 'U': A is upper triangular; = 'L': A is lower triangular. DIAG (input) CHARACTER*1 = 'N': A is non-unit triangular; = 'U': A is unit triangular. N (input) INTEGER The order of the matrix A. N >= 0. A (input/output) DOUBLE PRECISION array, dimension (LDA,N) On entry, the triangular matrix A. If UPLO = 'U', the leading N-by-N upper triangular part of the array A contains the upper triangular matrix, and the strictly lower triangular part of A is not referenced. If UPLO = 'L', the leading N-by-N lower triangular part of the array A contains the lower triangular matrix, and the strictly upper triangular part of A is not referenced. If DIAG = 'U', the diagonal elements of A are also not referenced and are assumed to be 1. On exit, the (triangular) inverse of the original matrix, in the same storage format. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,N). INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value > 0: if INFO = i, A(i,i) is exactly zero. The triangular matrix is singular and its inverse can not be computed. ===================================================================== Test the input parameters. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; /* Function Body */ *info = 0; upper = lsame_(uplo, "U"); nounit = lsame_(diag, "N"); if (! upper && ! lsame_(uplo, "L")) { *info = -1; } else if (! nounit && ! lsame_(diag, "U")) { *info = -2; } else if (*n < 0) { *info = -3; } else if (*lda < max(1,*n)) { *info = -5; } if (*info != 0) { i__1 = -(*info); xerbla_("DTRTRI", &i__1); return 0; } /* Quick return if possible */ if (*n == 0) { return 0; } /* Check for singularity if non-unit. */ if (nounit) { i__1 = *n; for (*info = 1; *info <= i__1; ++(*info)) { if (a[*info + *info * a_dim1] == 0.) { return 0; } /* L10: */ } *info = 0; } /* Determine the block size for this environment. Writing concatenation */ i__2[0] = 1, a__1[0] = uplo; i__2[1] = 1, a__1[1] = diag; s_cat(ch__1, a__1, i__2, &c__2, (ftnlen)2); nb = ilaenv_(&c__1, "DTRTRI", ch__1, n, &c_n1, &c_n1, &c_n1, (ftnlen)6, ( ftnlen)2); if ((nb <= 1) || (nb >= *n)) { /* Use unblocked code */ dtrti2_(uplo, diag, n, &a[a_offset], lda, info); } else { /* Use blocked code */ if (upper) { /* Compute inverse of upper triangular matrix */ i__1 = *n; i__3 = nb; for (j = 1; i__3 < 0 ? j >= i__1 : j <= i__1; j += i__3) { /* Computing MIN */ i__4 = nb, i__5 = *n - j + 1; jb = min(i__4,i__5); /* Compute rows 1:j-1 of current block column */ i__4 = j - 1; dtrmm_("Left", "Upper", "No transpose", diag, &i__4, &jb, & c_b2865, &a[a_offset], lda, &a[j * a_dim1 + 1], lda); i__4 = j - 1; dtrsm_("Right", "Upper", "No transpose", diag, &i__4, &jb, & c_b3001, &a[j + j * a_dim1], lda, &a[j * a_dim1 + 1], lda); /* Compute inverse of current diagonal block */ dtrti2_("Upper", diag, &jb, &a[j + j * a_dim1], lda, info); /* L20: */ } } else { /* Compute inverse of lower triangular matrix */ nn = (*n - 1) / nb * nb + 1; i__3 = -nb; for (j = nn; i__3 < 0 ? j >= 1 : j <= 1; j += i__3) { /* Computing MIN */ i__1 = nb, i__4 = *n - j + 1; jb = min(i__1,i__4); if (j + jb <= *n) { /* Compute rows j+jb:n of current block column */ i__1 = *n - j - jb + 1; dtrmm_("Left", "Lower", "No transpose", diag, &i__1, &jb, &c_b2865, &a[j + jb + (j + jb) * a_dim1], lda, &a[ j + jb + j * a_dim1], lda); i__1 = *n - j - jb + 1; dtrsm_("Right", "Lower", "No transpose", diag, &i__1, &jb, &c_b3001, &a[j + j * a_dim1], lda, &a[j + jb + j * a_dim1], lda); } /* Compute inverse of current diagonal block */ dtrti2_("Lower", diag, &jb, &a[j + j * a_dim1], lda, info); /* L30: */ } } } return 0; /* End of DTRTRI */ } /* dtrtri_ */ integer ieeeck_(integer *ispec, real *zero, real *one) { /* System generated locals */ integer ret_val; /* Local variables */ static real nan1, nan2, nan3, nan4, nan5, nan6, neginf, posinf, negzro, newzro; /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1998 Purpose ======= IEEECK is called from the ILAENV to verify that Infinity and possibly NaN arithmetic is safe (i.e. will not trap). Arguments ========= ISPEC (input) INTEGER Specifies whether to test just for inifinity arithmetic or whether to test for infinity and NaN arithmetic. = 0: Verify infinity arithmetic only. = 1: Verify infinity and NaN arithmetic. ZERO (input) REAL Must contain the value 0.0 This is passed to prevent the compiler from optimizing away this code. ONE (input) REAL Must contain the value 1.0 This is passed to prevent the compiler from optimizing away this code. RETURN VALUE: INTEGER = 0: Arithmetic failed to produce the correct answers = 1: Arithmetic produced the correct answers */ ret_val = 1; posinf = *one / *zero; if (posinf <= *one) { ret_val = 0; return ret_val; } neginf = -(*one) / *zero; if (neginf >= *zero) { ret_val = 0; return ret_val; } negzro = *one / (neginf + *one); if (negzro != *zero) { ret_val = 0; return ret_val; } neginf = *one / negzro; if (neginf >= *zero) { ret_val = 0; return ret_val; } newzro = negzro + *zero; if (newzro != *zero) { ret_val = 0; return ret_val; } posinf = *one / newzro; if (posinf <= *one) { ret_val = 0; return ret_val; } neginf *= posinf; if (neginf >= *zero) { ret_val = 0; return ret_val; } posinf *= posinf; if (posinf <= *one) { ret_val = 0; return ret_val; } /* Return if we were only asked to check infinity arithmetic */ if (*ispec == 0) { return ret_val; } nan1 = posinf + neginf; nan2 = posinf / neginf; nan3 = posinf / posinf; nan4 = posinf * *zero; nan5 = neginf * negzro; nan6 = nan5 * 0.f; if (nan1 == nan1) { ret_val = 0; return ret_val; } if (nan2 == nan2) { ret_val = 0; return ret_val; } if (nan3 == nan3) { ret_val = 0; return ret_val; } if (nan4 == nan4) { ret_val = 0; return ret_val; } if (nan5 == nan5) { ret_val = 0; return ret_val; } if (nan6 == nan6) { ret_val = 0; return ret_val; } return ret_val; } /* ieeeck_ */ integer ilaenv_(integer *ispec, char *name__, char *opts, integer *n1, integer *n2, integer *n3, integer *n4, ftnlen name_len, ftnlen opts_len) { /* System generated locals */ integer ret_val; /* Builtin functions */ /* Subroutine */ int s_copy(char *, char *, ftnlen, ftnlen); integer s_cmp(char *, char *, ftnlen, ftnlen); /* Local variables */ static integer i__; static char c1[1], c2[2], c3[3], c4[2]; static integer ic, nb, iz, nx; static logical cname, sname; static integer nbmin; extern integer ieeeck_(integer *, real *, real *); static char subnam[6]; /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= ILAENV is called from the LAPACK routines to choose problem-dependent parameters for the local environment. See ISPEC for a description of the parameters. This version provides a set of parameters which should give good, but not optimal, performance on many of the currently available computers. Users are encouraged to modify this subroutine to set the tuning parameters for their particular machine using the option and problem size information in the arguments. This routine will not function correctly if it is converted to all lower case. Converting it to all upper case is allowed. Arguments ========= ISPEC (input) INTEGER Specifies the parameter to be returned as the value of ILAENV. = 1: the optimal blocksize; if this value is 1, an unblocked algorithm will give the best performance. = 2: the minimum block size for which the block routine should be used; if the usable block size is less than this value, an unblocked routine should be used. = 3: the crossover point (in a block routine, for N less than this value, an unblocked routine should be used) = 4: the number of shifts, used in the nonsymmetric eigenvalue routines = 5: the minimum column dimension for blocking to be used; rectangular blocks must have dimension at least k by m, where k is given by ILAENV(2,...) and m by ILAENV(5,...) = 6: the crossover point for the SVD (when reducing an m by n matrix to bidiagonal form, if max(m,n)/min(m,n) exceeds this value, a QR factorization is used first to reduce the matrix to a triangular form.) = 7: the number of processors = 8: the crossover point for the multishift QR and QZ methods for nonsymmetric eigenvalue problems. = 9: maximum size of the subproblems at the bottom of the computation tree in the divide-and-conquer algorithm (used by xGELSD and xGESDD) =10: ieee NaN arithmetic can be trusted not to trap =11: infinity arithmetic can be trusted not to trap NAME (input) CHARACTER*(*) The name of the calling subroutine, in either upper case or lower case. OPTS (input) CHARACTER*(*) The character options to the subroutine NAME, concatenated into a single character string. For example, UPLO = 'U', TRANS = 'T', and DIAG = 'N' for a triangular routine would be specified as OPTS = 'UTN'. N1 (input) INTEGER N2 (input) INTEGER N3 (input) INTEGER N4 (input) INTEGER Problem dimensions for the subroutine NAME; these may not all be required. (ILAENV) (output) INTEGER >= 0: the value of the parameter specified by ISPEC < 0: if ILAENV = -k, the k-th argument had an illegal value. Further Details =============== The following conventions have been used when calling ILAENV from the LAPACK routines: 1) OPTS is a concatenation of all of the character options to subroutine NAME, in the same order that they appear in the argument list for NAME, even if they are not used in determining the value of the parameter specified by ISPEC. 2) The problem dimensions N1, N2, N3, N4 are specified in the order that they appear in the argument list for NAME. N1 is used first, N2 second, and so on, and unused problem dimensions are passed a value of -1. 3) The parameter value returned by ILAENV is checked for validity in the calling subroutine. For example, ILAENV is used to retrieve the optimal blocksize for STRTRI as follows: NB = ILAENV( 1, 'STRTRI', UPLO // DIAG, N, -1, -1, -1 ) IF( NB.LE.1 ) NB = MAX( 1, N ) ===================================================================== */ switch (*ispec) { case 1: goto L100; case 2: goto L100; case 3: goto L100; case 4: goto L400; case 5: goto L500; case 6: goto L600; case 7: goto L700; case 8: goto L800; case 9: goto L900; case 10: goto L1000; case 11: goto L1100; } /* Invalid value for ISPEC */ ret_val = -1; return ret_val; L100: /* Convert NAME to upper case if the first character is lower case. */ ret_val = 1; s_copy(subnam, name__, (ftnlen)6, name_len); ic = *(unsigned char *)subnam; iz = 'Z'; if ((iz == 90) || (iz == 122)) { /* ASCII character set */ if (ic >= 97 && ic <= 122) { *(unsigned char *)subnam = (char) (ic - 32); for (i__ = 2; i__ <= 6; ++i__) { ic = *(unsigned char *)&subnam[i__ - 1]; if (ic >= 97 && ic <= 122) { *(unsigned char *)&subnam[i__ - 1] = (char) (ic - 32); } /* L10: */ } } } else if ((iz == 233) || (iz == 169)) { /* EBCDIC character set */ if (((ic >= 129 && ic <= 137) || (ic >= 145 && ic <= 153)) || (ic >= 162 && ic <= 169)) { *(unsigned char *)subnam = (char) (ic + 64); for (i__ = 2; i__ <= 6; ++i__) { ic = *(unsigned char *)&subnam[i__ - 1]; if (((ic >= 129 && ic <= 137) || (ic >= 145 && ic <= 153)) || (ic >= 162 && ic <= 169)) { *(unsigned char *)&subnam[i__ - 1] = (char) (ic + 64); } /* L20: */ } } } else if ((iz == 218) || (iz == 250)) { /* Prime machines: ASCII+128 */ if (ic >= 225 && ic <= 250) { *(unsigned char *)subnam = (char) (ic - 32); for (i__ = 2; i__ <= 6; ++i__) { ic = *(unsigned char *)&subnam[i__ - 1]; if (ic >= 225 && ic <= 250) { *(unsigned char *)&subnam[i__ - 1] = (char) (ic - 32); } /* L30: */ } } } *(unsigned char *)c1 = *(unsigned char *)subnam; sname = (*(unsigned char *)c1 == 'S') || (*(unsigned char *)c1 == 'D'); cname = (*(unsigned char *)c1 == 'C') || (*(unsigned char *)c1 == 'Z'); if (! ((cname) || (sname))) { return ret_val; } s_copy(c2, subnam + 1, (ftnlen)2, (ftnlen)2); s_copy(c3, subnam + 3, (ftnlen)3, (ftnlen)3); s_copy(c4, c3 + 1, (ftnlen)2, (ftnlen)2); switch (*ispec) { case 1: goto L110; case 2: goto L200; case 3: goto L300; } L110: /* ISPEC = 1: block size In these examples, separate code is provided for setting NB for real and complex. We assume that NB will take the same value in single or double precision. */ nb = 1; if (s_cmp(c2, "GE", (ftnlen)2, (ftnlen)2) == 0) { if (s_cmp(c3, "TRF", (ftnlen)3, (ftnlen)3) == 0) { if (sname) { nb = 64; } else { nb = 64; } } else if ((((s_cmp(c3, "QRF", (ftnlen)3, (ftnlen)3) == 0) || (s_cmp( c3, "RQF", (ftnlen)3, (ftnlen)3) == 0)) || (s_cmp(c3, "LQF", ( ftnlen)3, (ftnlen)3) == 0)) || (s_cmp(c3, "QLF", (ftnlen)3, ( ftnlen)3) == 0)) { if (sname) { nb = 32; } else { nb = 32; } } else if (s_cmp(c3, "HRD", (ftnlen)3, (ftnlen)3) == 0) { if (sname) { nb = 32; } else { nb = 32; } } else if (s_cmp(c3, "BRD", (ftnlen)3, (ftnlen)3) == 0) { if (sname) { nb = 32; } else { nb = 32; } } else if (s_cmp(c3, "TRI", (ftnlen)3, (ftnlen)3) == 0) { if (sname) { nb = 64; } else { nb = 64; } } } else if (s_cmp(c2, "PO", (ftnlen)2, (ftnlen)2) == 0) { if (s_cmp(c3, "TRF", (ftnlen)3, (ftnlen)3) == 0) { if (sname) { nb = 64; } else { nb = 64; } } } else if (s_cmp(c2, "SY", (ftnlen)2, (ftnlen)2) == 0) { if (s_cmp(c3, "TRF", (ftnlen)3, (ftnlen)3) == 0) { if (sname) { nb = 64; } else { nb = 64; } } else if (sname && s_cmp(c3, "TRD", (ftnlen)3, (ftnlen)3) == 0) { nb = 32; } else if (sname && s_cmp(c3, "GST", (ftnlen)3, (ftnlen)3) == 0) { nb = 64; } } else if (cname && s_cmp(c2, "HE", (ftnlen)2, (ftnlen)2) == 0) { if (s_cmp(c3, "TRF", (ftnlen)3, (ftnlen)3) == 0) { nb = 64; } else if (s_cmp(c3, "TRD", (ftnlen)3, (ftnlen)3) == 0) { nb = 32; } else if (s_cmp(c3, "GST", (ftnlen)3, (ftnlen)3) == 0) { nb = 64; } } else if (sname && s_cmp(c2, "OR", (ftnlen)2, (ftnlen)2) == 0) { if (*(unsigned char *)c3 == 'G') { if (((((((s_cmp(c4, "QR", (ftnlen)2, (ftnlen)2) == 0) || (s_cmp( c4, "RQ", (ftnlen)2, (ftnlen)2) == 0)) || (s_cmp(c4, "LQ", (ftnlen)2, (ftnlen)2) == 0)) || (s_cmp(c4, "QL", ( ftnlen)2, (ftnlen)2) == 0)) || (s_cmp(c4, "HR", (ftnlen)2, (ftnlen)2) == 0)) || (s_cmp(c4, "TR", (ftnlen)2, (ftnlen) 2) == 0)) || (s_cmp(c4, "BR", (ftnlen)2, (ftnlen)2) == 0)) { nb = 32; } } else if (*(unsigned char *)c3 == 'M') { if (((((((s_cmp(c4, "QR", (ftnlen)2, (ftnlen)2) == 0) || (s_cmp( c4, "RQ", (ftnlen)2, (ftnlen)2) == 0)) || (s_cmp(c4, "LQ", (ftnlen)2, (ftnlen)2) == 0)) || (s_cmp(c4, "QL", ( ftnlen)2, (ftnlen)2) == 0)) || (s_cmp(c4, "HR", (ftnlen)2, (ftnlen)2) == 0)) || (s_cmp(c4, "TR", (ftnlen)2, (ftnlen) 2) == 0)) || (s_cmp(c4, "BR", (ftnlen)2, (ftnlen)2) == 0)) { nb = 32; } } } else if (cname && s_cmp(c2, "UN", (ftnlen)2, (ftnlen)2) == 0) { if (*(unsigned char *)c3 == 'G') { if (((((((s_cmp(c4, "QR", (ftnlen)2, (ftnlen)2) == 0) || (s_cmp( c4, "RQ", (ftnlen)2, (ftnlen)2) == 0)) || (s_cmp(c4, "LQ", (ftnlen)2, (ftnlen)2) == 0)) || (s_cmp(c4, "QL", ( ftnlen)2, (ftnlen)2) == 0)) || (s_cmp(c4, "HR", (ftnlen)2, (ftnlen)2) == 0)) || (s_cmp(c4, "TR", (ftnlen)2, (ftnlen) 2) == 0)) || (s_cmp(c4, "BR", (ftnlen)2, (ftnlen)2) == 0)) { nb = 32; } } else if (*(unsigned char *)c3 == 'M') { if (((((((s_cmp(c4, "QR", (ftnlen)2, (ftnlen)2) == 0) || (s_cmp( c4, "RQ", (ftnlen)2, (ftnlen)2) == 0)) || (s_cmp(c4, "LQ", (ftnlen)2, (ftnlen)2) == 0)) || (s_cmp(c4, "QL", ( ftnlen)2, (ftnlen)2) == 0)) || (s_cmp(c4, "HR", (ftnlen)2, (ftnlen)2) == 0)) || (s_cmp(c4, "TR", (ftnlen)2, (ftnlen) 2) == 0)) || (s_cmp(c4, "BR", (ftnlen)2, (ftnlen)2) == 0)) { nb = 32; } } } else if (s_cmp(c2, "GB", (ftnlen)2, (ftnlen)2) == 0) { if (s_cmp(c3, "TRF", (ftnlen)3, (ftnlen)3) == 0) { if (sname) { if (*n4 <= 64) { nb = 1; } else { nb = 32; } } else { if (*n4 <= 64) { nb = 1; } else { nb = 32; } } } } else if (s_cmp(c2, "PB", (ftnlen)2, (ftnlen)2) == 0) { if (s_cmp(c3, "TRF", (ftnlen)3, (ftnlen)3) == 0) { if (sname) { if (*n2 <= 64) { nb = 1; } else { nb = 32; } } else { if (*n2 <= 64) { nb = 1; } else { nb = 32; } } } } else if (s_cmp(c2, "TR", (ftnlen)2, (ftnlen)2) == 0) { if (s_cmp(c3, "TRI", (ftnlen)3, (ftnlen)3) == 0) { if (sname) { nb = 64; } else { nb = 64; } } } else if (s_cmp(c2, "LA", (ftnlen)2, (ftnlen)2) == 0) { if (s_cmp(c3, "UUM", (ftnlen)3, (ftnlen)3) == 0) { if (sname) { nb = 64; } else { nb = 64; } } } else if (sname && s_cmp(c2, "ST", (ftnlen)2, (ftnlen)2) == 0) { if (s_cmp(c3, "EBZ", (ftnlen)3, (ftnlen)3) == 0) { nb = 1; } } ret_val = nb; return ret_val; L200: /* ISPEC = 2: minimum block size */ nbmin = 2; if (s_cmp(c2, "GE", (ftnlen)2, (ftnlen)2) == 0) { if ((((s_cmp(c3, "QRF", (ftnlen)3, (ftnlen)3) == 0) || (s_cmp(c3, "RQF", (ftnlen)3, (ftnlen)3) == 0)) || (s_cmp(c3, "LQF", ( ftnlen)3, (ftnlen)3) == 0)) || (s_cmp(c3, "QLF", (ftnlen)3, ( ftnlen)3) == 0)) { if (sname) { nbmin = 2; } else { nbmin = 2; } } else if (s_cmp(c3, "HRD", (ftnlen)3, (ftnlen)3) == 0) { if (sname) { nbmin = 2; } else { nbmin = 2; } } else if (s_cmp(c3, "BRD", (ftnlen)3, (ftnlen)3) == 0) { if (sname) { nbmin = 2; } else { nbmin = 2; } } else if (s_cmp(c3, "TRI", (ftnlen)3, (ftnlen)3) == 0) { if (sname) { nbmin = 2; } else { nbmin = 2; } } } else if (s_cmp(c2, "SY", (ftnlen)2, (ftnlen)2) == 0) { if (s_cmp(c3, "TRF", (ftnlen)3, (ftnlen)3) == 0) { if (sname) { nbmin = 8; } else { nbmin = 8; } } else if (sname && s_cmp(c3, "TRD", (ftnlen)3, (ftnlen)3) == 0) { nbmin = 2; } } else if (cname && s_cmp(c2, "HE", (ftnlen)2, (ftnlen)2) == 0) { if (s_cmp(c3, "TRD", (ftnlen)3, (ftnlen)3) == 0) { nbmin = 2; } } else if (sname && s_cmp(c2, "OR", (ftnlen)2, (ftnlen)2) == 0) { if (*(unsigned char *)c3 == 'G') { if (((((((s_cmp(c4, "QR", (ftnlen)2, (ftnlen)2) == 0) || (s_cmp( c4, "RQ", (ftnlen)2, (ftnlen)2) == 0)) || (s_cmp(c4, "LQ", (ftnlen)2, (ftnlen)2) == 0)) || (s_cmp(c4, "QL", ( ftnlen)2, (ftnlen)2) == 0)) || (s_cmp(c4, "HR", (ftnlen)2, (ftnlen)2) == 0)) || (s_cmp(c4, "TR", (ftnlen)2, (ftnlen) 2) == 0)) || (s_cmp(c4, "BR", (ftnlen)2, (ftnlen)2) == 0)) { nbmin = 2; } } else if (*(unsigned char *)c3 == 'M') { if (((((((s_cmp(c4, "QR", (ftnlen)2, (ftnlen)2) == 0) || (s_cmp( c4, "RQ", (ftnlen)2, (ftnlen)2) == 0)) || (s_cmp(c4, "LQ", (ftnlen)2, (ftnlen)2) == 0)) || (s_cmp(c4, "QL", ( ftnlen)2, (ftnlen)2) == 0)) || (s_cmp(c4, "HR", (ftnlen)2, (ftnlen)2) == 0)) || (s_cmp(c4, "TR", (ftnlen)2, (ftnlen) 2) == 0)) || (s_cmp(c4, "BR", (ftnlen)2, (ftnlen)2) == 0)) { nbmin = 2; } } } else if (cname && s_cmp(c2, "UN", (ftnlen)2, (ftnlen)2) == 0) { if (*(unsigned char *)c3 == 'G') { if (((((((s_cmp(c4, "QR", (ftnlen)2, (ftnlen)2) == 0) || (s_cmp( c4, "RQ", (ftnlen)2, (ftnlen)2) == 0)) || (s_cmp(c4, "LQ", (ftnlen)2, (ftnlen)2) == 0)) || (s_cmp(c4, "QL", ( ftnlen)2, (ftnlen)2) == 0)) || (s_cmp(c4, "HR", (ftnlen)2, (ftnlen)2) == 0)) || (s_cmp(c4, "TR", (ftnlen)2, (ftnlen) 2) == 0)) || (s_cmp(c4, "BR", (ftnlen)2, (ftnlen)2) == 0)) { nbmin = 2; } } else if (*(unsigned char *)c3 == 'M') { if (((((((s_cmp(c4, "QR", (ftnlen)2, (ftnlen)2) == 0) || (s_cmp( c4, "RQ", (ftnlen)2, (ftnlen)2) == 0)) || (s_cmp(c4, "LQ", (ftnlen)2, (ftnlen)2) == 0)) || (s_cmp(c4, "QL", ( ftnlen)2, (ftnlen)2) == 0)) || (s_cmp(c4, "HR", (ftnlen)2, (ftnlen)2) == 0)) || (s_cmp(c4, "TR", (ftnlen)2, (ftnlen) 2) == 0)) || (s_cmp(c4, "BR", (ftnlen)2, (ftnlen)2) == 0)) { nbmin = 2; } } } ret_val = nbmin; return ret_val; L300: /* ISPEC = 3: crossover point */ nx = 0; if (s_cmp(c2, "GE", (ftnlen)2, (ftnlen)2) == 0) { if ((((s_cmp(c3, "QRF", (ftnlen)3, (ftnlen)3) == 0) || (s_cmp(c3, "RQF", (ftnlen)3, (ftnlen)3) == 0)) || (s_cmp(c3, "LQF", ( ftnlen)3, (ftnlen)3) == 0)) || (s_cmp(c3, "QLF", (ftnlen)3, ( ftnlen)3) == 0)) { if (sname) { nx = 128; } else { nx = 128; } } else if (s_cmp(c3, "HRD", (ftnlen)3, (ftnlen)3) == 0) { if (sname) { nx = 128; } else { nx = 128; } } else if (s_cmp(c3, "BRD", (ftnlen)3, (ftnlen)3) == 0) { if (sname) { nx = 128; } else { nx = 128; } } } else if (s_cmp(c2, "SY", (ftnlen)2, (ftnlen)2) == 0) { if (sname && s_cmp(c3, "TRD", (ftnlen)3, (ftnlen)3) == 0) { nx = 32; } } else if (cname && s_cmp(c2, "HE", (ftnlen)2, (ftnlen)2) == 0) { if (s_cmp(c3, "TRD", (ftnlen)3, (ftnlen)3) == 0) { nx = 32; } } else if (sname && s_cmp(c2, "OR", (ftnlen)2, (ftnlen)2) == 0) { if (*(unsigned char *)c3 == 'G') { if (((((((s_cmp(c4, "QR", (ftnlen)2, (ftnlen)2) == 0) || (s_cmp( c4, "RQ", (ftnlen)2, (ftnlen)2) == 0)) || (s_cmp(c4, "LQ", (ftnlen)2, (ftnlen)2) == 0)) || (s_cmp(c4, "QL", ( ftnlen)2, (ftnlen)2) == 0)) || (s_cmp(c4, "HR", (ftnlen)2, (ftnlen)2) == 0)) || (s_cmp(c4, "TR", (ftnlen)2, (ftnlen) 2) == 0)) || (s_cmp(c4, "BR", (ftnlen)2, (ftnlen)2) == 0)) { nx = 128; } } } else if (cname && s_cmp(c2, "UN", (ftnlen)2, (ftnlen)2) == 0) { if (*(unsigned char *)c3 == 'G') { if (((((((s_cmp(c4, "QR", (ftnlen)2, (ftnlen)2) == 0) || (s_cmp( c4, "RQ", (ftnlen)2, (ftnlen)2) == 0)) || (s_cmp(c4, "LQ", (ftnlen)2, (ftnlen)2) == 0)) || (s_cmp(c4, "QL", ( ftnlen)2, (ftnlen)2) == 0)) || (s_cmp(c4, "HR", (ftnlen)2, (ftnlen)2) == 0)) || (s_cmp(c4, "TR", (ftnlen)2, (ftnlen) 2) == 0)) || (s_cmp(c4, "BR", (ftnlen)2, (ftnlen)2) == 0)) { nx = 128; } } } ret_val = nx; return ret_val; L400: /* ISPEC = 4: number of shifts (used by xHSEQR) */ ret_val = 6; return ret_val; L500: /* ISPEC = 5: minimum column dimension (not used) */ ret_val = 2; return ret_val; L600: /* ISPEC = 6: crossover point for SVD (used by xGELSS and xGESVD) */ ret_val = (integer) ((real) min(*n1,*n2) * 1.6f); return ret_val; L700: /* ISPEC = 7: number of processors (not used) */ ret_val = 1; return ret_val; L800: /* ISPEC = 8: crossover point for multishift (used by xHSEQR) */ ret_val = 50; return ret_val; L900: /* ISPEC = 9: maximum size of the subproblems at the bottom of the computation tree in the divide-and-conquer algorithm (used by xGELSD and xGESDD) */ ret_val = 25; return ret_val; L1000: /* ISPEC = 10: ieee NaN arithmetic can be trusted not to trap ILAENV = 0 */ ret_val = 1; if (ret_val == 1) { ret_val = ieeeck_(&c__0, &c_b320, &c_b1011); } return ret_val; L1100: /* ISPEC = 11: infinity arithmetic can be trusted not to trap ILAENV = 0 */ ret_val = 1; if (ret_val == 1) { ret_val = ieeeck_(&c__1, &c_b320, &c_b1011); } return ret_val; /* End of ILAENV */ } /* ilaenv_ */ /* Subroutine */ int sbdsdc_(char *uplo, char *compq, integer *n, real *d__, real *e, real *u, integer *ldu, real *vt, integer *ldvt, real *q, integer *iq, real *work, integer *iwork, integer *info) { /* System generated locals */ integer u_dim1, u_offset, vt_dim1, vt_offset, i__1, i__2; real r__1; /* Builtin functions */ double r_sign(real *, real *), log(doublereal); /* Local variables */ static integer i__, j, k; static real p, r__; static integer z__, ic, ii, kk; static real cs; static integer is, iu; static real sn; static integer nm1; static real eps; static integer ivt, difl, difr, ierr, perm, mlvl, sqre; extern logical lsame_(char *, char *); static integer poles; extern /* Subroutine */ int slasr_(char *, char *, char *, integer *, integer *, real *, real *, real *, integer *); static integer iuplo, nsize, start; extern /* Subroutine */ int scopy_(integer *, real *, integer *, real *, integer *), sswap_(integer *, real *, integer *, real *, integer * ), slasd0_(integer *, integer *, real *, real *, real *, integer * , real *, integer *, integer *, integer *, real *, integer *); extern doublereal slamch_(char *); extern /* Subroutine */ int slasda_(integer *, integer *, integer *, integer *, real *, real *, real *, integer *, real *, integer *, real *, real *, real *, real *, integer *, integer *, integer *, integer *, real *, real *, real *, real *, integer *, integer *), xerbla_(char *, integer *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); extern /* Subroutine */ int slascl_(char *, integer *, integer *, real *, real *, integer *, integer *, real *, integer *, integer *); static integer givcol; extern /* Subroutine */ int slasdq_(char *, integer *, integer *, integer *, integer *, integer *, real *, real *, real *, integer *, real * , integer *, real *, integer *, real *, integer *); static integer icompq; extern /* Subroutine */ int slaset_(char *, integer *, integer *, real *, real *, real *, integer *), slartg_(real *, real *, real * , real *, real *); static real orgnrm; static integer givnum; extern doublereal slanst_(char *, integer *, real *, real *); static integer givptr, qstart, smlsiz, wstart, smlszp; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University December 1, 1999 Purpose ======= SBDSDC computes the singular value decomposition (SVD) of a real N-by-N (upper or lower) bidiagonal matrix B: B = U * S * VT, using a divide and conquer method, where S is a diagonal matrix with non-negative diagonal elements (the singular values of B), and U and VT are orthogonal matrices of left and right singular vectors, respectively. SBDSDC can be used to compute all singular values, and optionally, singular vectors or singular vectors in compact form. This code makes very mild assumptions about floating point arithmetic. It will work on machines with a guard digit in add/subtract, or on those binary machines without guard digits which subtract like the Cray X-MP, Cray Y-MP, Cray C-90, or Cray-2. It could conceivably fail on hexadecimal or decimal machines without guard digits, but we know of none. See SLASD3 for details. The code currently call SLASDQ if singular values only are desired. However, it can be slightly modified to compute singular values using the divide and conquer method. Arguments ========= UPLO (input) CHARACTER*1 = 'U': B is upper bidiagonal. = 'L': B is lower bidiagonal. COMPQ (input) CHARACTER*1 Specifies whether singular vectors are to be computed as follows: = 'N': Compute singular values only; = 'P': Compute singular values and compute singular vectors in compact form; = 'I': Compute singular values and singular vectors. N (input) INTEGER The order of the matrix B. N >= 0. D (input/output) REAL array, dimension (N) On entry, the n diagonal elements of the bidiagonal matrix B. On exit, if INFO=0, the singular values of B. E (input/output) REAL array, dimension (N) On entry, the elements of E contain the offdiagonal elements of the bidiagonal matrix whose SVD is desired. On exit, E has been destroyed. U (output) REAL array, dimension (LDU,N) If COMPQ = 'I', then: On exit, if INFO = 0, U contains the left singular vectors of the bidiagonal matrix. For other values of COMPQ, U is not referenced. LDU (input) INTEGER The leading dimension of the array U. LDU >= 1. If singular vectors are desired, then LDU >= max( 1, N ). VT (output) REAL array, dimension (LDVT,N) If COMPQ = 'I', then: On exit, if INFO = 0, VT' contains the right singular vectors of the bidiagonal matrix. For other values of COMPQ, VT is not referenced. LDVT (input) INTEGER The leading dimension of the array VT. LDVT >= 1. If singular vectors are desired, then LDVT >= max( 1, N ). Q (output) REAL array, dimension (LDQ) If COMPQ = 'P', then: On exit, if INFO = 0, Q and IQ contain the left and right singular vectors in a compact form, requiring O(N log N) space instead of 2*N**2. In particular, Q contains all the REAL data in LDQ >= N*(11 + 2*SMLSIZ + 8*INT(LOG_2(N/(SMLSIZ+1)))) words of memory, where SMLSIZ is returned by ILAENV and is equal to the maximum size of the subproblems at the bottom of the computation tree (usually about 25). For other values of COMPQ, Q is not referenced. IQ (output) INTEGER array, dimension (LDIQ) If COMPQ = 'P', then: On exit, if INFO = 0, Q and IQ contain the left and right singular vectors in a compact form, requiring O(N log N) space instead of 2*N**2. In particular, IQ contains all INTEGER data in LDIQ >= N*(3 + 3*INT(LOG_2(N/(SMLSIZ+1)))) words of memory, where SMLSIZ is returned by ILAENV and is equal to the maximum size of the subproblems at the bottom of the computation tree (usually about 25). For other values of COMPQ, IQ is not referenced. WORK (workspace) REAL array, dimension (LWORK) If COMPQ = 'N' then LWORK >= (4 * N). If COMPQ = 'P' then LWORK >= (6 * N). If COMPQ = 'I' then LWORK >= (3 * N**2 + 4 * N). IWORK (workspace) INTEGER array, dimension (8*N) INFO (output) INTEGER = 0: successful exit. < 0: if INFO = -i, the i-th argument had an illegal value. > 0: The algorithm failed to compute an singular value. The update process of divide and conquer failed. Further Details =============== Based on contributions by Ming Gu and Huan Ren, Computer Science Division, University of California at Berkeley, USA ===================================================================== Test the input parameters. */ /* Parameter adjustments */ --d__; --e; u_dim1 = *ldu; u_offset = 1 + u_dim1; u -= u_offset; vt_dim1 = *ldvt; vt_offset = 1 + vt_dim1; vt -= vt_offset; --q; --iq; --work; --iwork; /* Function Body */ *info = 0; iuplo = 0; if (lsame_(uplo, "U")) { iuplo = 1; } if (lsame_(uplo, "L")) { iuplo = 2; } if (lsame_(compq, "N")) { icompq = 0; } else if (lsame_(compq, "P")) { icompq = 1; } else if (lsame_(compq, "I")) { icompq = 2; } else { icompq = -1; } if (iuplo == 0) { *info = -1; } else if (icompq < 0) { *info = -2; } else if (*n < 0) { *info = -3; } else if ((*ldu < 1) || (icompq == 2 && *ldu < *n)) { *info = -7; } else if ((*ldvt < 1) || (icompq == 2 && *ldvt < *n)) { *info = -9; } if (*info != 0) { i__1 = -(*info); xerbla_("SBDSDC", &i__1); return 0; } /* Quick return if possible */ if (*n == 0) { return 0; } smlsiz = ilaenv_(&c__9, "SBDSDC", " ", &c__0, &c__0, &c__0, &c__0, ( ftnlen)6, (ftnlen)1); if (*n == 1) { if (icompq == 1) { q[1] = r_sign(&c_b1011, &d__[1]); q[smlsiz * *n + 1] = 1.f; } else if (icompq == 2) { u[u_dim1 + 1] = r_sign(&c_b1011, &d__[1]); vt[vt_dim1 + 1] = 1.f; } d__[1] = dabs(d__[1]); return 0; } nm1 = *n - 1; /* If matrix lower bidiagonal, rotate to be upper bidiagonal by applying Givens rotations on the left */ wstart = 1; qstart = 3; if (icompq == 1) { scopy_(n, &d__[1], &c__1, &q[1], &c__1); i__1 = *n - 1; scopy_(&i__1, &e[1], &c__1, &q[*n + 1], &c__1); } if (iuplo == 2) { qstart = 5; wstart = ((*n) << (1)) - 1; i__1 = *n - 1; for (i__ = 1; i__ <= i__1; ++i__) { slartg_(&d__[i__], &e[i__], &cs, &sn, &r__); d__[i__] = r__; e[i__] = sn * d__[i__ + 1]; d__[i__ + 1] = cs * d__[i__ + 1]; if (icompq == 1) { q[i__ + ((*n) << (1))] = cs; q[i__ + *n * 3] = sn; } else if (icompq == 2) { work[i__] = cs; work[nm1 + i__] = -sn; } /* L10: */ } } /* If ICOMPQ = 0, use SLASDQ to compute the singular values. */ if (icompq == 0) { slasdq_("U", &c__0, n, &c__0, &c__0, &c__0, &d__[1], &e[1], &vt[ vt_offset], ldvt, &u[u_offset], ldu, &u[u_offset], ldu, &work[ wstart], info); goto L40; } /* If N is smaller than the minimum divide size SMLSIZ, then solve the problem with another solver. */ if (*n <= smlsiz) { if (icompq == 2) { slaset_("A", n, n, &c_b320, &c_b1011, &u[u_offset], ldu); slaset_("A", n, n, &c_b320, &c_b1011, &vt[vt_offset], ldvt); slasdq_("U", &c__0, n, n, n, &c__0, &d__[1], &e[1], &vt[vt_offset] , ldvt, &u[u_offset], ldu, &u[u_offset], ldu, &work[ wstart], info); } else if (icompq == 1) { iu = 1; ivt = iu + *n; slaset_("A", n, n, &c_b320, &c_b1011, &q[iu + (qstart - 1) * *n], n); slaset_("A", n, n, &c_b320, &c_b1011, &q[ivt + (qstart - 1) * *n], n); slasdq_("U", &c__0, n, n, n, &c__0, &d__[1], &e[1], &q[ivt + ( qstart - 1) * *n], n, &q[iu + (qstart - 1) * *n], n, &q[ iu + (qstart - 1) * *n], n, &work[wstart], info); } goto L40; } if (icompq == 2) { slaset_("A", n, n, &c_b320, &c_b1011, &u[u_offset], ldu); slaset_("A", n, n, &c_b320, &c_b1011, &vt[vt_offset], ldvt) ; } /* Scale. */ orgnrm = slanst_("M", n, &d__[1], &e[1]); if (orgnrm == 0.f) { return 0; } slascl_("G", &c__0, &c__0, &orgnrm, &c_b1011, n, &c__1, &d__[1], n, &ierr); slascl_("G", &c__0, &c__0, &orgnrm, &c_b1011, &nm1, &c__1, &e[1], &nm1, & ierr); eps = slamch_("Epsilon"); mlvl = (integer) (log((real) (*n) / (real) (smlsiz + 1)) / log(2.f)) + 1; smlszp = smlsiz + 1; if (icompq == 1) { iu = 1; ivt = smlsiz + 1; difl = ivt + smlszp; difr = difl + mlvl; z__ = difr + ((mlvl) << (1)); ic = z__ + mlvl; is = ic + 1; poles = is + 1; givnum = poles + ((mlvl) << (1)); k = 1; givptr = 2; perm = 3; givcol = perm + mlvl; } i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { if ((r__1 = d__[i__], dabs(r__1)) < eps) { d__[i__] = r_sign(&eps, &d__[i__]); } /* L20: */ } start = 1; sqre = 0; i__1 = nm1; for (i__ = 1; i__ <= i__1; ++i__) { if (((r__1 = e[i__], dabs(r__1)) < eps) || (i__ == nm1)) { /* Subproblem found. First determine its size and then apply divide and conquer on it. */ if (i__ < nm1) { /* A subproblem with E(I) small for I < NM1. */ nsize = i__ - start + 1; } else if ((r__1 = e[i__], dabs(r__1)) >= eps) { /* A subproblem with E(NM1) not too small but I = NM1. */ nsize = *n - start + 1; } else { /* A subproblem with E(NM1) small. This implies an 1-by-1 subproblem at D(N). Solve this 1-by-1 problem first. */ nsize = i__ - start + 1; if (icompq == 2) { u[*n + *n * u_dim1] = r_sign(&c_b1011, &d__[*n]); vt[*n + *n * vt_dim1] = 1.f; } else if (icompq == 1) { q[*n + (qstart - 1) * *n] = r_sign(&c_b1011, &d__[*n]); q[*n + (smlsiz + qstart - 1) * *n] = 1.f; } d__[*n] = (r__1 = d__[*n], dabs(r__1)); } if (icompq == 2) { slasd0_(&nsize, &sqre, &d__[start], &e[start], &u[start + start * u_dim1], ldu, &vt[start + start * vt_dim1], ldvt, &smlsiz, &iwork[1], &work[wstart], info); } else { slasda_(&icompq, &smlsiz, &nsize, &sqre, &d__[start], &e[ start], &q[start + (iu + qstart - 2) * *n], n, &q[ start + (ivt + qstart - 2) * *n], &iq[start + k * *n], &q[start + (difl + qstart - 2) * *n], &q[start + ( difr + qstart - 2) * *n], &q[start + (z__ + qstart - 2) * *n], &q[start + (poles + qstart - 2) * *n], &iq[ start + givptr * *n], &iq[start + givcol * *n], n, & iq[start + perm * *n], &q[start + (givnum + qstart - 2) * *n], &q[start + (ic + qstart - 2) * *n], &q[ start + (is + qstart - 2) * *n], &work[wstart], & iwork[1], info); if (*info != 0) { return 0; } } start = i__ + 1; } /* L30: */ } /* Unscale */ slascl_("G", &c__0, &c__0, &c_b1011, &orgnrm, n, &c__1, &d__[1], n, &ierr); L40: /* Use Selection Sort to minimize swaps of singular vectors */ i__1 = *n; for (ii = 2; ii <= i__1; ++ii) { i__ = ii - 1; kk = i__; p = d__[i__]; i__2 = *n; for (j = ii; j <= i__2; ++j) { if (d__[j] > p) { kk = j; p = d__[j]; } /* L50: */ } if (kk != i__) { d__[kk] = d__[i__]; d__[i__] = p; if (icompq == 1) { iq[i__] = kk; } else if (icompq == 2) { sswap_(n, &u[i__ * u_dim1 + 1], &c__1, &u[kk * u_dim1 + 1], & c__1); sswap_(n, &vt[i__ + vt_dim1], ldvt, &vt[kk + vt_dim1], ldvt); } } else if (icompq == 1) { iq[i__] = i__; } /* L60: */ } /* If ICOMPQ = 1, use IQ(N,1) as the indicator for UPLO */ if (icompq == 1) { if (iuplo == 1) { iq[*n] = 1; } else { iq[*n] = 0; } } /* If B is lower bidiagonal, update U by those Givens rotations which rotated B to be upper bidiagonal */ if (iuplo == 2 && icompq == 2) { slasr_("L", "V", "B", n, n, &work[1], &work[*n], &u[u_offset], ldu); } return 0; /* End of SBDSDC */ } /* sbdsdc_ */ /* Subroutine */ int sbdsqr_(char *uplo, integer *n, integer *ncvt, integer * nru, integer *ncc, real *d__, real *e, real *vt, integer *ldvt, real * u, integer *ldu, real *c__, integer *ldc, real *work, integer *info) { /* System generated locals */ integer c_dim1, c_offset, u_dim1, u_offset, vt_dim1, vt_offset, i__1, i__2; real r__1, r__2, r__3, r__4; doublereal d__1; /* Builtin functions */ double pow_dd(doublereal *, doublereal *), sqrt(doublereal), r_sign(real * , real *); /* Local variables */ static real f, g, h__; static integer i__, j, m; static real r__, cs; static integer ll; static real sn, mu; static integer nm1, nm12, nm13, lll; static real eps, sll, tol, abse; static integer idir; static real abss; static integer oldm; static real cosl; static integer isub, iter; static real unfl, sinl, cosr, smin, smax, sinr; extern /* Subroutine */ int srot_(integer *, real *, integer *, real *, integer *, real *, real *), slas2_(real *, real *, real *, real *, real *); extern logical lsame_(char *, char *); static real oldcs; extern /* Subroutine */ int sscal_(integer *, real *, real *, integer *); static integer oldll; static real shift, sigmn, oldsn; static integer maxit; static real sminl; extern /* Subroutine */ int slasr_(char *, char *, char *, integer *, integer *, real *, real *, real *, integer *); static real sigmx; static logical lower; extern /* Subroutine */ int sswap_(integer *, real *, integer *, real *, integer *), slasq1_(integer *, real *, real *, real *, integer *), slasv2_(real *, real *, real *, real *, real *, real *, real *, real *, real *); extern doublereal slamch_(char *); extern /* Subroutine */ int xerbla_(char *, integer *); static real sminoa; extern /* Subroutine */ int slartg_(real *, real *, real *, real *, real * ); static real thresh; static logical rotate; static real sminlo, tolmul; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University October 31, 1999 Purpose ======= SBDSQR computes the singular value decomposition (SVD) of a real N-by-N (upper or lower) bidiagonal matrix B: B = Q * S * P' (P' denotes the transpose of P), where S is a diagonal matrix with non-negative diagonal elements (the singular values of B), and Q and P are orthogonal matrices. The routine computes S, and optionally computes U * Q, P' * VT, or Q' * C, for given real input matrices U, VT, and C. See "Computing Small Singular Values of Bidiagonal Matrices With Guaranteed High Relative Accuracy," by J. Demmel and W. Kahan, LAPACK Working Note #3 (or SIAM J. Sci. Statist. Comput. vol. 11, no. 5, pp. 873-912, Sept 1990) and "Accurate singular values and differential qd algorithms," by B. Parlett and V. Fernando, Technical Report CPAM-554, Mathematics Department, University of California at Berkeley, July 1992 for a detailed description of the algorithm. Arguments ========= UPLO (input) CHARACTER*1 = 'U': B is upper bidiagonal; = 'L': B is lower bidiagonal. N (input) INTEGER The order of the matrix B. N >= 0. NCVT (input) INTEGER The number of columns of the matrix VT. NCVT >= 0. NRU (input) INTEGER The number of rows of the matrix U. NRU >= 0. NCC (input) INTEGER The number of columns of the matrix C. NCC >= 0. D (input/output) REAL array, dimension (N) On entry, the n diagonal elements of the bidiagonal matrix B. On exit, if INFO=0, the singular values of B in decreasing order. E (input/output) REAL array, dimension (N) On entry, the elements of E contain the offdiagonal elements of the bidiagonal matrix whose SVD is desired. On normal exit (INFO = 0), E is destroyed. If the algorithm does not converge (INFO > 0), D and E will contain the diagonal and superdiagonal elements of a bidiagonal matrix orthogonally equivalent to the one given as input. E(N) is used for workspace. VT (input/output) REAL array, dimension (LDVT, NCVT) On entry, an N-by-NCVT matrix VT. On exit, VT is overwritten by P' * VT. VT is not referenced if NCVT = 0. LDVT (input) INTEGER The leading dimension of the array VT. LDVT >= max(1,N) if NCVT > 0; LDVT >= 1 if NCVT = 0. U (input/output) REAL array, dimension (LDU, N) On entry, an NRU-by-N matrix U. On exit, U is overwritten by U * Q. U is not referenced if NRU = 0. LDU (input) INTEGER The leading dimension of the array U. LDU >= max(1,NRU). C (input/output) REAL array, dimension (LDC, NCC) On entry, an N-by-NCC matrix C. On exit, C is overwritten by Q' * C. C is not referenced if NCC = 0. LDC (input) INTEGER The leading dimension of the array C. LDC >= max(1,N) if NCC > 0; LDC >=1 if NCC = 0. WORK (workspace) REAL array, dimension (4*N) INFO (output) INTEGER = 0: successful exit < 0: If INFO = -i, the i-th argument had an illegal value > 0: the algorithm did not converge; D and E contain the elements of a bidiagonal matrix which is orthogonally similar to the input matrix B; if INFO = i, i elements of E have not converged to zero. Internal Parameters =================== TOLMUL REAL, default = max(10,min(100,EPS**(-1/8))) TOLMUL controls the convergence criterion of the QR loop. If it is positive, TOLMUL*EPS is the desired relative precision in the computed singular values. If it is negative, abs(TOLMUL*EPS*sigma_max) is the desired absolute accuracy in the computed singular values (corresponds to relative accuracy abs(TOLMUL*EPS) in the largest singular value. abs(TOLMUL) should be between 1 and 1/EPS, and preferably between 10 (for fast convergence) and .1/EPS (for there to be some accuracy in the results). Default is to lose at either one eighth or 2 of the available decimal digits in each computed singular value (whichever is smaller). MAXITR INTEGER, default = 6 MAXITR controls the maximum number of passes of the algorithm through its inner loop. The algorithms stops (and so fails to converge) if the number of passes through the inner loop exceeds MAXITR*N**2. ===================================================================== Test the input parameters. */ /* Parameter adjustments */ --d__; --e; vt_dim1 = *ldvt; vt_offset = 1 + vt_dim1; vt -= vt_offset; u_dim1 = *ldu; u_offset = 1 + u_dim1; u -= u_offset; c_dim1 = *ldc; c_offset = 1 + c_dim1; c__ -= c_offset; --work; /* Function Body */ *info = 0; lower = lsame_(uplo, "L"); if (! lsame_(uplo, "U") && ! lower) { *info = -1; } else if (*n < 0) { *info = -2; } else if (*ncvt < 0) { *info = -3; } else if (*nru < 0) { *info = -4; } else if (*ncc < 0) { *info = -5; } else if ((*ncvt == 0 && *ldvt < 1) || (*ncvt > 0 && *ldvt < max(1,*n))) { *info = -9; } else if (*ldu < max(1,*nru)) { *info = -11; } else if ((*ncc == 0 && *ldc < 1) || (*ncc > 0 && *ldc < max(1,*n))) { *info = -13; } if (*info != 0) { i__1 = -(*info); xerbla_("SBDSQR", &i__1); return 0; } if (*n == 0) { return 0; } if (*n == 1) { goto L160; } /* ROTATE is true if any singular vectors desired, false otherwise */ rotate = ((*ncvt > 0) || (*nru > 0)) || (*ncc > 0); /* If no singular vectors desired, use qd algorithm */ if (! rotate) { slasq1_(n, &d__[1], &e[1], &work[1], info); return 0; } nm1 = *n - 1; nm12 = nm1 + nm1; nm13 = nm12 + nm1; idir = 0; /* Get machine constants */ eps = slamch_("Epsilon"); unfl = slamch_("Safe minimum"); /* If matrix lower bidiagonal, rotate to be upper bidiagonal by applying Givens rotations on the left */ if (lower) { i__1 = *n - 1; for (i__ = 1; i__ <= i__1; ++i__) { slartg_(&d__[i__], &e[i__], &cs, &sn, &r__); d__[i__] = r__; e[i__] = sn * d__[i__ + 1]; d__[i__ + 1] = cs * d__[i__ + 1]; work[i__] = cs; work[nm1 + i__] = sn; /* L10: */ } /* Update singular vectors if desired */ if (*nru > 0) { slasr_("R", "V", "F", nru, n, &work[1], &work[*n], &u[u_offset], ldu); } if (*ncc > 0) { slasr_("L", "V", "F", n, ncc, &work[1], &work[*n], &c__[c_offset], ldc); } } /* Compute singular values to relative accuracy TOL (By setting TOL to be negative, algorithm will compute singular values to absolute accuracy ABS(TOL)*norm(input matrix)) Computing MAX Computing MIN */ d__1 = (doublereal) eps; r__3 = 100.f, r__4 = pow_dd(&d__1, &c_b2944); r__1 = 10.f, r__2 = dmin(r__3,r__4); tolmul = dmax(r__1,r__2); tol = tolmul * eps; /* Compute approximate maximum, minimum singular values */ smax = 0.f; i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { /* Computing MAX */ r__2 = smax, r__3 = (r__1 = d__[i__], dabs(r__1)); smax = dmax(r__2,r__3); /* L20: */ } i__1 = *n - 1; for (i__ = 1; i__ <= i__1; ++i__) { /* Computing MAX */ r__2 = smax, r__3 = (r__1 = e[i__], dabs(r__1)); smax = dmax(r__2,r__3); /* L30: */ } sminl = 0.f; if (tol >= 0.f) { /* Relative accuracy desired */ sminoa = dabs(d__[1]); if (sminoa == 0.f) { goto L50; } mu = sminoa; i__1 = *n; for (i__ = 2; i__ <= i__1; ++i__) { mu = (r__2 = d__[i__], dabs(r__2)) * (mu / (mu + (r__1 = e[i__ - 1], dabs(r__1)))); sminoa = dmin(sminoa,mu); if (sminoa == 0.f) { goto L50; } /* L40: */ } L50: sminoa /= sqrt((real) (*n)); /* Computing MAX */ r__1 = tol * sminoa, r__2 = *n * 6 * *n * unfl; thresh = dmax(r__1,r__2); } else { /* Absolute accuracy desired Computing MAX */ r__1 = dabs(tol) * smax, r__2 = *n * 6 * *n * unfl; thresh = dmax(r__1,r__2); } /* Prepare for main iteration loop for the singular values (MAXIT is the maximum number of passes through the inner loop permitted before nonconvergence signalled.) */ maxit = *n * 6 * *n; iter = 0; oldll = -1; oldm = -1; /* M points to last element of unconverged part of matrix */ m = *n; /* Begin main iteration loop */ L60: /* Check for convergence or exceeding iteration count */ if (m <= 1) { goto L160; } if (iter > maxit) { goto L200; } /* Find diagonal block of matrix to work on */ if (tol < 0.f && (r__1 = d__[m], dabs(r__1)) <= thresh) { d__[m] = 0.f; } smax = (r__1 = d__[m], dabs(r__1)); smin = smax; i__1 = m - 1; for (lll = 1; lll <= i__1; ++lll) { ll = m - lll; abss = (r__1 = d__[ll], dabs(r__1)); abse = (r__1 = e[ll], dabs(r__1)); if (tol < 0.f && abss <= thresh) { d__[ll] = 0.f; } if (abse <= thresh) { goto L80; } smin = dmin(smin,abss); /* Computing MAX */ r__1 = max(smax,abss); smax = dmax(r__1,abse); /* L70: */ } ll = 0; goto L90; L80: e[ll] = 0.f; /* Matrix splits since E(LL) = 0 */ if (ll == m - 1) { /* Convergence of bottom singular value, return to top of loop */ --m; goto L60; } L90: ++ll; /* E(LL) through E(M-1) are nonzero, E(LL-1) is zero */ if (ll == m - 1) { /* 2 by 2 block, handle separately */ slasv2_(&d__[m - 1], &e[m - 1], &d__[m], &sigmn, &sigmx, &sinr, &cosr, &sinl, &cosl); d__[m - 1] = sigmx; e[m - 1] = 0.f; d__[m] = sigmn; /* Compute singular vectors, if desired */ if (*ncvt > 0) { srot_(ncvt, &vt[m - 1 + vt_dim1], ldvt, &vt[m + vt_dim1], ldvt, & cosr, &sinr); } if (*nru > 0) { srot_(nru, &u[(m - 1) * u_dim1 + 1], &c__1, &u[m * u_dim1 + 1], & c__1, &cosl, &sinl); } if (*ncc > 0) { srot_(ncc, &c__[m - 1 + c_dim1], ldc, &c__[m + c_dim1], ldc, & cosl, &sinl); } m += -2; goto L60; } /* If working on new submatrix, choose shift direction (from larger end diagonal element towards smaller) */ if ((ll > oldm) || (m < oldll)) { if ((r__1 = d__[ll], dabs(r__1)) >= (r__2 = d__[m], dabs(r__2))) { /* Chase bulge from top (big end) to bottom (small end) */ idir = 1; } else { /* Chase bulge from bottom (big end) to top (small end) */ idir = 2; } } /* Apply convergence tests */ if (idir == 1) { /* Run convergence test in forward direction First apply standard test to bottom of matrix */ if (((r__2 = e[m - 1], dabs(r__2)) <= dabs(tol) * (r__1 = d__[m], dabs(r__1))) || (tol < 0.f && (r__3 = e[m - 1], dabs(r__3)) <= thresh)) { e[m - 1] = 0.f; goto L60; } if (tol >= 0.f) { /* If relative accuracy desired, apply convergence criterion forward */ mu = (r__1 = d__[ll], dabs(r__1)); sminl = mu; i__1 = m - 1; for (lll = ll; lll <= i__1; ++lll) { if ((r__1 = e[lll], dabs(r__1)) <= tol * mu) { e[lll] = 0.f; goto L60; } sminlo = sminl; mu = (r__2 = d__[lll + 1], dabs(r__2)) * (mu / (mu + (r__1 = e[lll], dabs(r__1)))); sminl = dmin(sminl,mu); /* L100: */ } } } else { /* Run convergence test in backward direction First apply standard test to top of matrix */ if (((r__2 = e[ll], dabs(r__2)) <= dabs(tol) * (r__1 = d__[ll], dabs( r__1))) || (tol < 0.f && (r__3 = e[ll], dabs(r__3)) <= thresh) ) { e[ll] = 0.f; goto L60; } if (tol >= 0.f) { /* If relative accuracy desired, apply convergence criterion backward */ mu = (r__1 = d__[m], dabs(r__1)); sminl = mu; i__1 = ll; for (lll = m - 1; lll >= i__1; --lll) { if ((r__1 = e[lll], dabs(r__1)) <= tol * mu) { e[lll] = 0.f; goto L60; } sminlo = sminl; mu = (r__2 = d__[lll], dabs(r__2)) * (mu / (mu + (r__1 = e[ lll], dabs(r__1)))); sminl = dmin(sminl,mu); /* L110: */ } } } oldll = ll; oldm = m; /* Compute shift. First, test if shifting would ruin relative accuracy, and if so set the shift to zero. Computing MAX */ r__1 = eps, r__2 = tol * .01f; if (tol >= 0.f && *n * tol * (sminl / smax) <= dmax(r__1,r__2)) { /* Use a zero shift to avoid loss of relative accuracy */ shift = 0.f; } else { /* Compute the shift from 2-by-2 block at end of matrix */ if (idir == 1) { sll = (r__1 = d__[ll], dabs(r__1)); slas2_(&d__[m - 1], &e[m - 1], &d__[m], &shift, &r__); } else { sll = (r__1 = d__[m], dabs(r__1)); slas2_(&d__[ll], &e[ll], &d__[ll + 1], &shift, &r__); } /* Test if shift negligible, and if so set to zero */ if (sll > 0.f) { /* Computing 2nd power */ r__1 = shift / sll; if (r__1 * r__1 < eps) { shift = 0.f; } } } /* Increment iteration count */ iter = iter + m - ll; /* If SHIFT = 0, do simplified QR iteration */ if (shift == 0.f) { if (idir == 1) { /* Chase bulge from top to bottom Save cosines and sines for later singular vector updates */ cs = 1.f; oldcs = 1.f; i__1 = m - 1; for (i__ = ll; i__ <= i__1; ++i__) { r__1 = d__[i__] * cs; slartg_(&r__1, &e[i__], &cs, &sn, &r__); if (i__ > ll) { e[i__ - 1] = oldsn * r__; } r__1 = oldcs * r__; r__2 = d__[i__ + 1] * sn; slartg_(&r__1, &r__2, &oldcs, &oldsn, &d__[i__]); work[i__ - ll + 1] = cs; work[i__ - ll + 1 + nm1] = sn; work[i__ - ll + 1 + nm12] = oldcs; work[i__ - ll + 1 + nm13] = oldsn; /* L120: */ } h__ = d__[m] * cs; d__[m] = h__ * oldcs; e[m - 1] = h__ * oldsn; /* Update singular vectors */ if (*ncvt > 0) { i__1 = m - ll + 1; slasr_("L", "V", "F", &i__1, ncvt, &work[1], &work[*n], &vt[ ll + vt_dim1], ldvt); } if (*nru > 0) { i__1 = m - ll + 1; slasr_("R", "V", "F", nru, &i__1, &work[nm12 + 1], &work[nm13 + 1], &u[ll * u_dim1 + 1], ldu); } if (*ncc > 0) { i__1 = m - ll + 1; slasr_("L", "V", "F", &i__1, ncc, &work[nm12 + 1], &work[nm13 + 1], &c__[ll + c_dim1], ldc); } /* Test convergence */ if ((r__1 = e[m - 1], dabs(r__1)) <= thresh) { e[m - 1] = 0.f; } } else { /* Chase bulge from bottom to top Save cosines and sines for later singular vector updates */ cs = 1.f; oldcs = 1.f; i__1 = ll + 1; for (i__ = m; i__ >= i__1; --i__) { r__1 = d__[i__] * cs; slartg_(&r__1, &e[i__ - 1], &cs, &sn, &r__); if (i__ < m) { e[i__] = oldsn * r__; } r__1 = oldcs * r__; r__2 = d__[i__ - 1] * sn; slartg_(&r__1, &r__2, &oldcs, &oldsn, &d__[i__]); work[i__ - ll] = cs; work[i__ - ll + nm1] = -sn; work[i__ - ll + nm12] = oldcs; work[i__ - ll + nm13] = -oldsn; /* L130: */ } h__ = d__[ll] * cs; d__[ll] = h__ * oldcs; e[ll] = h__ * oldsn; /* Update singular vectors */ if (*ncvt > 0) { i__1 = m - ll + 1; slasr_("L", "V", "B", &i__1, ncvt, &work[nm12 + 1], &work[ nm13 + 1], &vt[ll + vt_dim1], ldvt); } if (*nru > 0) { i__1 = m - ll + 1; slasr_("R", "V", "B", nru, &i__1, &work[1], &work[*n], &u[ll * u_dim1 + 1], ldu); } if (*ncc > 0) { i__1 = m - ll + 1; slasr_("L", "V", "B", &i__1, ncc, &work[1], &work[*n], &c__[ ll + c_dim1], ldc); } /* Test convergence */ if ((r__1 = e[ll], dabs(r__1)) <= thresh) { e[ll] = 0.f; } } } else { /* Use nonzero shift */ if (idir == 1) { /* Chase bulge from top to bottom Save cosines and sines for later singular vector updates */ f = ((r__1 = d__[ll], dabs(r__1)) - shift) * (r_sign(&c_b1011, & d__[ll]) + shift / d__[ll]); g = e[ll]; i__1 = m - 1; for (i__ = ll; i__ <= i__1; ++i__) { slartg_(&f, &g, &cosr, &sinr, &r__); if (i__ > ll) { e[i__ - 1] = r__; } f = cosr * d__[i__] + sinr * e[i__]; e[i__] = cosr * e[i__] - sinr * d__[i__]; g = sinr * d__[i__ + 1]; d__[i__ + 1] = cosr * d__[i__ + 1]; slartg_(&f, &g, &cosl, &sinl, &r__); d__[i__] = r__; f = cosl * e[i__] + sinl * d__[i__ + 1]; d__[i__ + 1] = cosl * d__[i__ + 1] - sinl * e[i__]; if (i__ < m - 1) { g = sinl * e[i__ + 1]; e[i__ + 1] = cosl * e[i__ + 1]; } work[i__ - ll + 1] = cosr; work[i__ - ll + 1 + nm1] = sinr; work[i__ - ll + 1 + nm12] = cosl; work[i__ - ll + 1 + nm13] = sinl; /* L140: */ } e[m - 1] = f; /* Update singular vectors */ if (*ncvt > 0) { i__1 = m - ll + 1; slasr_("L", "V", "F", &i__1, ncvt, &work[1], &work[*n], &vt[ ll + vt_dim1], ldvt); } if (*nru > 0) { i__1 = m - ll + 1; slasr_("R", "V", "F", nru, &i__1, &work[nm12 + 1], &work[nm13 + 1], &u[ll * u_dim1 + 1], ldu); } if (*ncc > 0) { i__1 = m - ll + 1; slasr_("L", "V", "F", &i__1, ncc, &work[nm12 + 1], &work[nm13 + 1], &c__[ll + c_dim1], ldc); } /* Test convergence */ if ((r__1 = e[m - 1], dabs(r__1)) <= thresh) { e[m - 1] = 0.f; } } else { /* Chase bulge from bottom to top Save cosines and sines for later singular vector updates */ f = ((r__1 = d__[m], dabs(r__1)) - shift) * (r_sign(&c_b1011, & d__[m]) + shift / d__[m]); g = e[m - 1]; i__1 = ll + 1; for (i__ = m; i__ >= i__1; --i__) { slartg_(&f, &g, &cosr, &sinr, &r__); if (i__ < m) { e[i__] = r__; } f = cosr * d__[i__] + sinr * e[i__ - 1]; e[i__ - 1] = cosr * e[i__ - 1] - sinr * d__[i__]; g = sinr * d__[i__ - 1]; d__[i__ - 1] = cosr * d__[i__ - 1]; slartg_(&f, &g, &cosl, &sinl, &r__); d__[i__] = r__; f = cosl * e[i__ - 1] + sinl * d__[i__ - 1]; d__[i__ - 1] = cosl * d__[i__ - 1] - sinl * e[i__ - 1]; if (i__ > ll + 1) { g = sinl * e[i__ - 2]; e[i__ - 2] = cosl * e[i__ - 2]; } work[i__ - ll] = cosr; work[i__ - ll + nm1] = -sinr; work[i__ - ll + nm12] = cosl; work[i__ - ll + nm13] = -sinl; /* L150: */ } e[ll] = f; /* Test convergence */ if ((r__1 = e[ll], dabs(r__1)) <= thresh) { e[ll] = 0.f; } /* Update singular vectors if desired */ if (*ncvt > 0) { i__1 = m - ll + 1; slasr_("L", "V", "B", &i__1, ncvt, &work[nm12 + 1], &work[ nm13 + 1], &vt[ll + vt_dim1], ldvt); } if (*nru > 0) { i__1 = m - ll + 1; slasr_("R", "V", "B", nru, &i__1, &work[1], &work[*n], &u[ll * u_dim1 + 1], ldu); } if (*ncc > 0) { i__1 = m - ll + 1; slasr_("L", "V", "B", &i__1, ncc, &work[1], &work[*n], &c__[ ll + c_dim1], ldc); } } } /* QR iteration finished, go back and check convergence */ goto L60; /* All singular values converged, so make them positive */ L160: i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { if (d__[i__] < 0.f) { d__[i__] = -d__[i__]; /* Change sign of singular vectors, if desired */ if (*ncvt > 0) { sscal_(ncvt, &c_b1290, &vt[i__ + vt_dim1], ldvt); } } /* L170: */ } /* Sort the singular values into decreasing order (insertion sort on singular values, but only one transposition per singular vector) */ i__1 = *n - 1; for (i__ = 1; i__ <= i__1; ++i__) { /* Scan for smallest D(I) */ isub = 1; smin = d__[1]; i__2 = *n + 1 - i__; for (j = 2; j <= i__2; ++j) { if (d__[j] <= smin) { isub = j; smin = d__[j]; } /* L180: */ } if (isub != *n + 1 - i__) { /* Swap singular values and vectors */ d__[isub] = d__[*n + 1 - i__]; d__[*n + 1 - i__] = smin; if (*ncvt > 0) { sswap_(ncvt, &vt[isub + vt_dim1], ldvt, &vt[*n + 1 - i__ + vt_dim1], ldvt); } if (*nru > 0) { sswap_(nru, &u[isub * u_dim1 + 1], &c__1, &u[(*n + 1 - i__) * u_dim1 + 1], &c__1); } if (*ncc > 0) { sswap_(ncc, &c__[isub + c_dim1], ldc, &c__[*n + 1 - i__ + c_dim1], ldc); } } /* L190: */ } goto L220; /* Maximum number of iterations exceeded, failure to converge */ L200: *info = 0; i__1 = *n - 1; for (i__ = 1; i__ <= i__1; ++i__) { if (e[i__] != 0.f) { ++(*info); } /* L210: */ } L220: return 0; /* End of SBDSQR */ } /* sbdsqr_ */ /* Subroutine */ int sgebak_(char *job, char *side, integer *n, integer *ilo, integer *ihi, real *scale, integer *m, real *v, integer *ldv, integer *info) { /* System generated locals */ integer v_dim1, v_offset, i__1; /* Local variables */ static integer i__, k; static real s; static integer ii; extern logical lsame_(char *, char *); extern /* Subroutine */ int sscal_(integer *, real *, real *, integer *); static logical leftv; extern /* Subroutine */ int sswap_(integer *, real *, integer *, real *, integer *), xerbla_(char *, integer *); static logical rightv; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University September 30, 1994 Purpose ======= SGEBAK forms the right or left eigenvectors of a real general matrix by backward transformation on the computed eigenvectors of the balanced matrix output by SGEBAL. Arguments ========= JOB (input) CHARACTER*1 Specifies the type of backward transformation required: = 'N', do nothing, return immediately; = 'P', do backward transformation for permutation only; = 'S', do backward transformation for scaling only; = 'B', do backward transformations for both permutation and scaling. JOB must be the same as the argument JOB supplied to SGEBAL. SIDE (input) CHARACTER*1 = 'R': V contains right eigenvectors; = 'L': V contains left eigenvectors. N (input) INTEGER The number of rows of the matrix V. N >= 0. ILO (input) INTEGER IHI (input) INTEGER The integers ILO and IHI determined by SGEBAL. 1 <= ILO <= IHI <= N, if N > 0; ILO=1 and IHI=0, if N=0. SCALE (input) REAL array, dimension (N) Details of the permutation and scaling factors, as returned by SGEBAL. M (input) INTEGER The number of columns of the matrix V. M >= 0. V (input/output) REAL array, dimension (LDV,M) On entry, the matrix of right or left eigenvectors to be transformed, as returned by SHSEIN or STREVC. On exit, V is overwritten by the transformed eigenvectors. LDV (input) INTEGER The leading dimension of the array V. LDV >= max(1,N). INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value. ===================================================================== Decode and Test the input parameters */ /* Parameter adjustments */ --scale; v_dim1 = *ldv; v_offset = 1 + v_dim1; v -= v_offset; /* Function Body */ rightv = lsame_(side, "R"); leftv = lsame_(side, "L"); *info = 0; if (! lsame_(job, "N") && ! lsame_(job, "P") && ! lsame_(job, "S") && ! lsame_(job, "B")) { *info = -1; } else if (! rightv && ! leftv) { *info = -2; } else if (*n < 0) { *info = -3; } else if ((*ilo < 1) || (*ilo > max(1,*n))) { *info = -4; } else if ((*ihi < min(*ilo,*n)) || (*ihi > *n)) { *info = -5; } else if (*m < 0) { *info = -7; } else if (*ldv < max(1,*n)) { *info = -9; } if (*info != 0) { i__1 = -(*info); xerbla_("SGEBAK", &i__1); return 0; } /* Quick return if possible */ if (*n == 0) { return 0; } if (*m == 0) { return 0; } if (lsame_(job, "N")) { return 0; } if (*ilo == *ihi) { goto L30; } /* Backward balance */ if ((lsame_(job, "S")) || (lsame_(job, "B"))) { if (rightv) { i__1 = *ihi; for (i__ = *ilo; i__ <= i__1; ++i__) { s = scale[i__]; sscal_(m, &s, &v[i__ + v_dim1], ldv); /* L10: */ } } if (leftv) { i__1 = *ihi; for (i__ = *ilo; i__ <= i__1; ++i__) { s = 1.f / scale[i__]; sscal_(m, &s, &v[i__ + v_dim1], ldv); /* L20: */ } } } /* Backward permutation For I = ILO-1 step -1 until 1, IHI+1 step 1 until N do -- */ L30: if ((lsame_(job, "P")) || (lsame_(job, "B"))) { if (rightv) { i__1 = *n; for (ii = 1; ii <= i__1; ++ii) { i__ = ii; if (i__ >= *ilo && i__ <= *ihi) { goto L40; } if (i__ < *ilo) { i__ = *ilo - ii; } k = scale[i__]; if (k == i__) { goto L40; } sswap_(m, &v[i__ + v_dim1], ldv, &v[k + v_dim1], ldv); L40: ; } } if (leftv) { i__1 = *n; for (ii = 1; ii <= i__1; ++ii) { i__ = ii; if (i__ >= *ilo && i__ <= *ihi) { goto L50; } if (i__ < *ilo) { i__ = *ilo - ii; } k = scale[i__]; if (k == i__) { goto L50; } sswap_(m, &v[i__ + v_dim1], ldv, &v[k + v_dim1], ldv); L50: ; } } } return 0; /* End of SGEBAK */ } /* sgebak_ */ /* Subroutine */ int sgebal_(char *job, integer *n, real *a, integer *lda, integer *ilo, integer *ihi, real *scale, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2; real r__1, r__2; /* Local variables */ static real c__, f, g; static integer i__, j, k, l, m; static real r__, s, ca, ra; static integer ica, ira, iexc; extern logical lsame_(char *, char *); extern /* Subroutine */ int sscal_(integer *, real *, real *, integer *), sswap_(integer *, real *, integer *, real *, integer *); static real sfmin1, sfmin2, sfmax1, sfmax2; extern doublereal slamch_(char *); extern /* Subroutine */ int xerbla_(char *, integer *); extern integer isamax_(integer *, real *, integer *); static logical noconv; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= SGEBAL balances a general real matrix A. This involves, first, permuting A by a similarity transformation to isolate eigenvalues in the first 1 to ILO-1 and last IHI+1 to N elements on the diagonal; and second, applying a diagonal similarity transformation to rows and columns ILO to IHI to make the rows and columns as close in norm as possible. Both steps are optional. Balancing may reduce the 1-norm of the matrix, and improve the accuracy of the computed eigenvalues and/or eigenvectors. Arguments ========= JOB (input) CHARACTER*1 Specifies the operations to be performed on A: = 'N': none: simply set ILO = 1, IHI = N, SCALE(I) = 1.0 for i = 1,...,N; = 'P': permute only; = 'S': scale only; = 'B': both permute and scale. N (input) INTEGER The order of the matrix A. N >= 0. A (input/output) REAL array, dimension (LDA,N) On entry, the input matrix A. On exit, A is overwritten by the balanced matrix. If JOB = 'N', A is not referenced. See Further Details. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,N). ILO (output) INTEGER IHI (output) INTEGER ILO and IHI are set to integers such that on exit A(i,j) = 0 if i > j and j = 1,...,ILO-1 or I = IHI+1,...,N. If JOB = 'N' or 'S', ILO = 1 and IHI = N. SCALE (output) REAL array, dimension (N) Details of the permutations and scaling factors applied to A. If P(j) is the index of the row and column interchanged with row and column j and D(j) is the scaling factor applied to row and column j, then SCALE(j) = P(j) for j = 1,...,ILO-1 = D(j) for j = ILO,...,IHI = P(j) for j = IHI+1,...,N. The order in which the interchanges are made is N to IHI+1, then 1 to ILO-1. INFO (output) INTEGER = 0: successful exit. < 0: if INFO = -i, the i-th argument had an illegal value. Further Details =============== The permutations consist of row and column interchanges which put the matrix in the form ( T1 X Y ) P A P = ( 0 B Z ) ( 0 0 T2 ) where T1 and T2 are upper triangular matrices whose eigenvalues lie along the diagonal. The column indices ILO and IHI mark the starting and ending columns of the submatrix B. Balancing consists of applying a diagonal similarity transformation inv(D) * B * D to make the 1-norms of each row of B and its corresponding column nearly equal. The output matrix is ( T1 X*D Y ) ( 0 inv(D)*B*D inv(D)*Z ). ( 0 0 T2 ) Information about the permutations P and the diagonal matrix D is returned in the vector SCALE. This subroutine is based on the EISPACK routine BALANC. Modified by Tzu-Yi Chen, Computer Science Division, University of California at Berkeley, USA ===================================================================== Test the input parameters */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --scale; /* Function Body */ *info = 0; if (! lsame_(job, "N") && ! lsame_(job, "P") && ! lsame_(job, "S") && ! lsame_(job, "B")) { *info = -1; } else if (*n < 0) { *info = -2; } else if (*lda < max(1,*n)) { *info = -4; } if (*info != 0) { i__1 = -(*info); xerbla_("SGEBAL", &i__1); return 0; } k = 1; l = *n; if (*n == 0) { goto L210; } if (lsame_(job, "N")) { i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { scale[i__] = 1.f; /* L10: */ } goto L210; } if (lsame_(job, "S")) { goto L120; } /* Permutation to isolate eigenvalues if possible */ goto L50; /* Row and column exchange. */ L20: scale[m] = (real) j; if (j == m) { goto L30; } sswap_(&l, &a[j * a_dim1 + 1], &c__1, &a[m * a_dim1 + 1], &c__1); i__1 = *n - k + 1; sswap_(&i__1, &a[j + k * a_dim1], lda, &a[m + k * a_dim1], lda); L30: switch (iexc) { case 1: goto L40; case 2: goto L80; } /* Search for rows isolating an eigenvalue and push them down. */ L40: if (l == 1) { goto L210; } --l; L50: for (j = l; j >= 1; --j) { i__1 = l; for (i__ = 1; i__ <= i__1; ++i__) { if (i__ == j) { goto L60; } if (a[j + i__ * a_dim1] != 0.f) { goto L70; } L60: ; } m = l; iexc = 1; goto L20; L70: ; } goto L90; /* Search for columns isolating an eigenvalue and push them left. */ L80: ++k; L90: i__1 = l; for (j = k; j <= i__1; ++j) { i__2 = l; for (i__ = k; i__ <= i__2; ++i__) { if (i__ == j) { goto L100; } if (a[i__ + j * a_dim1] != 0.f) { goto L110; } L100: ; } m = k; iexc = 2; goto L20; L110: ; } L120: i__1 = l; for (i__ = k; i__ <= i__1; ++i__) { scale[i__] = 1.f; /* L130: */ } if (lsame_(job, "P")) { goto L210; } /* Balance the submatrix in rows K to L. Iterative loop for norm reduction */ sfmin1 = slamch_("S") / slamch_("P"); sfmax1 = 1.f / sfmin1; sfmin2 = sfmin1 * 8.f; sfmax2 = 1.f / sfmin2; L140: noconv = FALSE_; i__1 = l; for (i__ = k; i__ <= i__1; ++i__) { c__ = 0.f; r__ = 0.f; i__2 = l; for (j = k; j <= i__2; ++j) { if (j == i__) { goto L150; } c__ += (r__1 = a[j + i__ * a_dim1], dabs(r__1)); r__ += (r__1 = a[i__ + j * a_dim1], dabs(r__1)); L150: ; } ica = isamax_(&l, &a[i__ * a_dim1 + 1], &c__1); ca = (r__1 = a[ica + i__ * a_dim1], dabs(r__1)); i__2 = *n - k + 1; ira = isamax_(&i__2, &a[i__ + k * a_dim1], lda); ra = (r__1 = a[i__ + (ira + k - 1) * a_dim1], dabs(r__1)); /* Guard against zero C or R due to underflow. */ if ((c__ == 0.f) || (r__ == 0.f)) { goto L200; } g = r__ / 8.f; f = 1.f; s = c__ + r__; L160: /* Computing MAX */ r__1 = max(f,c__); /* Computing MIN */ r__2 = min(r__,g); if (((c__ >= g) || (dmax(r__1,ca) >= sfmax2)) || (dmin(r__2,ra) <= sfmin2)) { goto L170; } f *= 8.f; c__ *= 8.f; ca *= 8.f; r__ /= 8.f; g /= 8.f; ra /= 8.f; goto L160; L170: g = c__ / 8.f; L180: /* Computing MIN */ r__1 = min(f,c__), r__1 = min(r__1,g); if (((g < r__) || (dmax(r__,ra) >= sfmax2)) || (dmin(r__1,ca) <= sfmin2)) { goto L190; } f /= 8.f; c__ /= 8.f; g /= 8.f; ca /= 8.f; r__ *= 8.f; ra *= 8.f; goto L180; /* Now balance. */ L190: if (c__ + r__ >= s * .95f) { goto L200; } if (f < 1.f && scale[i__] < 1.f) { if (f * scale[i__] <= sfmin1) { goto L200; } } if (f > 1.f && scale[i__] > 1.f) { if (scale[i__] >= sfmax1 / f) { goto L200; } } g = 1.f / f; scale[i__] *= f; noconv = TRUE_; i__2 = *n - k + 1; sscal_(&i__2, &g, &a[i__ + k * a_dim1], lda); sscal_(&l, &f, &a[i__ * a_dim1 + 1], &c__1); L200: ; } if (noconv) { goto L140; } L210: *ilo = k; *ihi = l; return 0; /* End of SGEBAL */ } /* sgebal_ */ /* Subroutine */ int sgebd2_(integer *m, integer *n, real *a, integer *lda, real *d__, real *e, real *tauq, real *taup, real *work, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3, i__4; /* Local variables */ static integer i__; extern /* Subroutine */ int slarf_(char *, integer *, integer *, real *, integer *, real *, real *, integer *, real *), xerbla_( char *, integer *), slarfg_(integer *, real *, real *, integer *, real *); /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University February 29, 1992 Purpose ======= SGEBD2 reduces a real general m by n matrix A to upper or lower bidiagonal form B by an orthogonal transformation: Q' * A * P = B. If m >= n, B is upper bidiagonal; if m < n, B is lower bidiagonal. Arguments ========= M (input) INTEGER The number of rows in the matrix A. M >= 0. N (input) INTEGER The number of columns in the matrix A. N >= 0. A (input/output) REAL array, dimension (LDA,N) On entry, the m by n general matrix to be reduced. On exit, if m >= n, the diagonal and the first superdiagonal are overwritten with the upper bidiagonal matrix B; the elements below the diagonal, with the array TAUQ, represent the orthogonal matrix Q as a product of elementary reflectors, and the elements above the first superdiagonal, with the array TAUP, represent the orthogonal matrix P as a product of elementary reflectors; if m < n, the diagonal and the first subdiagonal are overwritten with the lower bidiagonal matrix B; the elements below the first subdiagonal, with the array TAUQ, represent the orthogonal matrix Q as a product of elementary reflectors, and the elements above the diagonal, with the array TAUP, represent the orthogonal matrix P as a product of elementary reflectors. See Further Details. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,M). D (output) REAL array, dimension (min(M,N)) The diagonal elements of the bidiagonal matrix B: D(i) = A(i,i). E (output) REAL array, dimension (min(M,N)-1) The off-diagonal elements of the bidiagonal matrix B: if m >= n, E(i) = A(i,i+1) for i = 1,2,...,n-1; if m < n, E(i) = A(i+1,i) for i = 1,2,...,m-1. TAUQ (output) REAL array dimension (min(M,N)) The scalar factors of the elementary reflectors which represent the orthogonal matrix Q. See Further Details. TAUP (output) REAL array, dimension (min(M,N)) The scalar factors of the elementary reflectors which represent the orthogonal matrix P. See Further Details. WORK (workspace) REAL array, dimension (max(M,N)) INFO (output) INTEGER = 0: successful exit. < 0: if INFO = -i, the i-th argument had an illegal value. Further Details =============== The matrices Q and P are represented as products of elementary reflectors: If m >= n, Q = H(1) H(2) . . . H(n) and P = G(1) G(2) . . . G(n-1) Each H(i) and G(i) has the form: H(i) = I - tauq * v * v' and G(i) = I - taup * u * u' where tauq and taup are real scalars, and v and u are real vectors; v(1:i-1) = 0, v(i) = 1, and v(i+1:m) is stored on exit in A(i+1:m,i); u(1:i) = 0, u(i+1) = 1, and u(i+2:n) is stored on exit in A(i,i+2:n); tauq is stored in TAUQ(i) and taup in TAUP(i). If m < n, Q = H(1) H(2) . . . H(m-1) and P = G(1) G(2) . . . G(m) Each H(i) and G(i) has the form: H(i) = I - tauq * v * v' and G(i) = I - taup * u * u' where tauq and taup are real scalars, and v and u are real vectors; v(1:i) = 0, v(i+1) = 1, and v(i+2:m) is stored on exit in A(i+2:m,i); u(1:i-1) = 0, u(i) = 1, and u(i+1:n) is stored on exit in A(i,i+1:n); tauq is stored in TAUQ(i) and taup in TAUP(i). The contents of A on exit are illustrated by the following examples: m = 6 and n = 5 (m > n): m = 5 and n = 6 (m < n): ( d e u1 u1 u1 ) ( d u1 u1 u1 u1 u1 ) ( v1 d e u2 u2 ) ( e d u2 u2 u2 u2 ) ( v1 v2 d e u3 ) ( v1 e d u3 u3 u3 ) ( v1 v2 v3 d e ) ( v1 v2 e d u4 u4 ) ( v1 v2 v3 v4 d ) ( v1 v2 v3 e d u5 ) ( v1 v2 v3 v4 v5 ) where d and e denote diagonal and off-diagonal elements of B, vi denotes an element of the vector defining H(i), and ui an element of the vector defining G(i). ===================================================================== Test the input parameters */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --d__; --e; --tauq; --taup; --work; /* Function Body */ *info = 0; if (*m < 0) { *info = -1; } else if (*n < 0) { *info = -2; } else if (*lda < max(1,*m)) { *info = -4; } if (*info < 0) { i__1 = -(*info); xerbla_("SGEBD2", &i__1); return 0; } if (*m >= *n) { /* Reduce to upper bidiagonal form */ i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { /* Generate elementary reflector H(i) to annihilate A(i+1:m,i) */ i__2 = *m - i__ + 1; /* Computing MIN */ i__3 = i__ + 1; slarfg_(&i__2, &a[i__ + i__ * a_dim1], &a[min(i__3,*m) + i__ * a_dim1], &c__1, &tauq[i__]); d__[i__] = a[i__ + i__ * a_dim1]; a[i__ + i__ * a_dim1] = 1.f; /* Apply H(i) to A(i:m,i+1:n) from the left */ i__2 = *m - i__ + 1; i__3 = *n - i__; slarf_("Left", &i__2, &i__3, &a[i__ + i__ * a_dim1], &c__1, &tauq[ i__], &a[i__ + (i__ + 1) * a_dim1], lda, &work[1]); a[i__ + i__ * a_dim1] = d__[i__]; if (i__ < *n) { /* Generate elementary reflector G(i) to annihilate A(i,i+2:n) */ i__2 = *n - i__; /* Computing MIN */ i__3 = i__ + 2; slarfg_(&i__2, &a[i__ + (i__ + 1) * a_dim1], &a[i__ + min( i__3,*n) * a_dim1], lda, &taup[i__]); e[i__] = a[i__ + (i__ + 1) * a_dim1]; a[i__ + (i__ + 1) * a_dim1] = 1.f; /* Apply G(i) to A(i+1:m,i+1:n) from the right */ i__2 = *m - i__; i__3 = *n - i__; slarf_("Right", &i__2, &i__3, &a[i__ + (i__ + 1) * a_dim1], lda, &taup[i__], &a[i__ + 1 + (i__ + 1) * a_dim1], lda, &work[1]); a[i__ + (i__ + 1) * a_dim1] = e[i__]; } else { taup[i__] = 0.f; } /* L10: */ } } else { /* Reduce to lower bidiagonal form */ i__1 = *m; for (i__ = 1; i__ <= i__1; ++i__) { /* Generate elementary reflector G(i) to annihilate A(i,i+1:n) */ i__2 = *n - i__ + 1; /* Computing MIN */ i__3 = i__ + 1; slarfg_(&i__2, &a[i__ + i__ * a_dim1], &a[i__ + min(i__3,*n) * a_dim1], lda, &taup[i__]); d__[i__] = a[i__ + i__ * a_dim1]; a[i__ + i__ * a_dim1] = 1.f; /* Apply G(i) to A(i+1:m,i:n) from the right */ i__2 = *m - i__; i__3 = *n - i__ + 1; /* Computing MIN */ i__4 = i__ + 1; slarf_("Right", &i__2, &i__3, &a[i__ + i__ * a_dim1], lda, &taup[ i__], &a[min(i__4,*m) + i__ * a_dim1], lda, &work[1]); a[i__ + i__ * a_dim1] = d__[i__]; if (i__ < *m) { /* Generate elementary reflector H(i) to annihilate A(i+2:m,i) */ i__2 = *m - i__; /* Computing MIN */ i__3 = i__ + 2; slarfg_(&i__2, &a[i__ + 1 + i__ * a_dim1], &a[min(i__3,*m) + i__ * a_dim1], &c__1, &tauq[i__]); e[i__] = a[i__ + 1 + i__ * a_dim1]; a[i__ + 1 + i__ * a_dim1] = 1.f; /* Apply H(i) to A(i+1:m,i+1:n) from the left */ i__2 = *m - i__; i__3 = *n - i__; slarf_("Left", &i__2, &i__3, &a[i__ + 1 + i__ * a_dim1], & c__1, &tauq[i__], &a[i__ + 1 + (i__ + 1) * a_dim1], lda, &work[1]); a[i__ + 1 + i__ * a_dim1] = e[i__]; } else { tauq[i__] = 0.f; } /* L20: */ } } return 0; /* End of SGEBD2 */ } /* sgebd2_ */ /* Subroutine */ int sgebrd_(integer *m, integer *n, real *a, integer *lda, real *d__, real *e, real *tauq, real *taup, real *work, integer * lwork, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3, i__4; /* Local variables */ static integer i__, j, nb, nx; static real ws; static integer nbmin, iinfo; extern /* Subroutine */ int sgemm_(char *, char *, integer *, integer *, integer *, real *, real *, integer *, real *, integer *, real *, real *, integer *); static integer minmn; extern /* Subroutine */ int sgebd2_(integer *, integer *, real *, integer *, real *, real *, real *, real *, real *, integer *), slabrd_( integer *, integer *, integer *, real *, integer *, real *, real * , real *, real *, real *, integer *, real *, integer *), xerbla_( char *, integer *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); static integer ldwrkx, ldwrky, lwkopt; static logical lquery; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= SGEBRD reduces a general real M-by-N matrix A to upper or lower bidiagonal form B by an orthogonal transformation: Q**T * A * P = B. If m >= n, B is upper bidiagonal; if m < n, B is lower bidiagonal. Arguments ========= M (input) INTEGER The number of rows in the matrix A. M >= 0. N (input) INTEGER The number of columns in the matrix A. N >= 0. A (input/output) REAL array, dimension (LDA,N) On entry, the M-by-N general matrix to be reduced. On exit, if m >= n, the diagonal and the first superdiagonal are overwritten with the upper bidiagonal matrix B; the elements below the diagonal, with the array TAUQ, represent the orthogonal matrix Q as a product of elementary reflectors, and the elements above the first superdiagonal, with the array TAUP, represent the orthogonal matrix P as a product of elementary reflectors; if m < n, the diagonal and the first subdiagonal are overwritten with the lower bidiagonal matrix B; the elements below the first subdiagonal, with the array TAUQ, represent the orthogonal matrix Q as a product of elementary reflectors, and the elements above the diagonal, with the array TAUP, represent the orthogonal matrix P as a product of elementary reflectors. See Further Details. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,M). D (output) REAL array, dimension (min(M,N)) The diagonal elements of the bidiagonal matrix B: D(i) = A(i,i). E (output) REAL array, dimension (min(M,N)-1) The off-diagonal elements of the bidiagonal matrix B: if m >= n, E(i) = A(i,i+1) for i = 1,2,...,n-1; if m < n, E(i) = A(i+1,i) for i = 1,2,...,m-1. TAUQ (output) REAL array dimension (min(M,N)) The scalar factors of the elementary reflectors which represent the orthogonal matrix Q. See Further Details. TAUP (output) REAL array, dimension (min(M,N)) The scalar factors of the elementary reflectors which represent the orthogonal matrix P. See Further Details. WORK (workspace/output) REAL array, dimension (LWORK) On exit, if INFO = 0, WORK(1) returns the optimal LWORK. LWORK (input) INTEGER The length of the array WORK. LWORK >= max(1,M,N). For optimum performance LWORK >= (M+N)*NB, where NB is the optimal blocksize. If LWORK = -1, then a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued by XERBLA. INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value. Further Details =============== The matrices Q and P are represented as products of elementary reflectors: If m >= n, Q = H(1) H(2) . . . H(n) and P = G(1) G(2) . . . G(n-1) Each H(i) and G(i) has the form: H(i) = I - tauq * v * v' and G(i) = I - taup * u * u' where tauq and taup are real scalars, and v and u are real vectors; v(1:i-1) = 0, v(i) = 1, and v(i+1:m) is stored on exit in A(i+1:m,i); u(1:i) = 0, u(i+1) = 1, and u(i+2:n) is stored on exit in A(i,i+2:n); tauq is stored in TAUQ(i) and taup in TAUP(i). If m < n, Q = H(1) H(2) . . . H(m-1) and P = G(1) G(2) . . . G(m) Each H(i) and G(i) has the form: H(i) = I - tauq * v * v' and G(i) = I - taup * u * u' where tauq and taup are real scalars, and v and u are real vectors; v(1:i) = 0, v(i+1) = 1, and v(i+2:m) is stored on exit in A(i+2:m,i); u(1:i-1) = 0, u(i) = 1, and u(i+1:n) is stored on exit in A(i,i+1:n); tauq is stored in TAUQ(i) and taup in TAUP(i). The contents of A on exit are illustrated by the following examples: m = 6 and n = 5 (m > n): m = 5 and n = 6 (m < n): ( d e u1 u1 u1 ) ( d u1 u1 u1 u1 u1 ) ( v1 d e u2 u2 ) ( e d u2 u2 u2 u2 ) ( v1 v2 d e u3 ) ( v1 e d u3 u3 u3 ) ( v1 v2 v3 d e ) ( v1 v2 e d u4 u4 ) ( v1 v2 v3 v4 d ) ( v1 v2 v3 e d u5 ) ( v1 v2 v3 v4 v5 ) where d and e denote diagonal and off-diagonal elements of B, vi denotes an element of the vector defining H(i), and ui an element of the vector defining G(i). ===================================================================== Test the input parameters */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --d__; --e; --tauq; --taup; --work; /* Function Body */ *info = 0; /* Computing MAX */ i__1 = 1, i__2 = ilaenv_(&c__1, "SGEBRD", " ", m, n, &c_n1, &c_n1, ( ftnlen)6, (ftnlen)1); nb = max(i__1,i__2); lwkopt = (*m + *n) * nb; work[1] = (real) lwkopt; lquery = *lwork == -1; if (*m < 0) { *info = -1; } else if (*n < 0) { *info = -2; } else if (*lda < max(1,*m)) { *info = -4; } else /* if(complicated condition) */ { /* Computing MAX */ i__1 = max(1,*m); if (*lwork < max(i__1,*n) && ! lquery) { *info = -10; } } if (*info < 0) { i__1 = -(*info); xerbla_("SGEBRD", &i__1); return 0; } else if (lquery) { return 0; } /* Quick return if possible */ minmn = min(*m,*n); if (minmn == 0) { work[1] = 1.f; return 0; } ws = (real) max(*m,*n); ldwrkx = *m; ldwrky = *n; if (nb > 1 && nb < minmn) { /* Set the crossover point NX. Computing MAX */ i__1 = nb, i__2 = ilaenv_(&c__3, "SGEBRD", " ", m, n, &c_n1, &c_n1, ( ftnlen)6, (ftnlen)1); nx = max(i__1,i__2); /* Determine when to switch from blocked to unblocked code. */ if (nx < minmn) { ws = (real) ((*m + *n) * nb); if ((real) (*lwork) < ws) { /* Not enough work space for the optimal NB, consider using a smaller block size. */ nbmin = ilaenv_(&c__2, "SGEBRD", " ", m, n, &c_n1, &c_n1, ( ftnlen)6, (ftnlen)1); if (*lwork >= (*m + *n) * nbmin) { nb = *lwork / (*m + *n); } else { nb = 1; nx = minmn; } } } } else { nx = minmn; } i__1 = minmn - nx; i__2 = nb; for (i__ = 1; i__2 < 0 ? i__ >= i__1 : i__ <= i__1; i__ += i__2) { /* Reduce rows and columns i:i+nb-1 to bidiagonal form and return the matrices X and Y which are needed to update the unreduced part of the matrix */ i__3 = *m - i__ + 1; i__4 = *n - i__ + 1; slabrd_(&i__3, &i__4, &nb, &a[i__ + i__ * a_dim1], lda, &d__[i__], &e[ i__], &tauq[i__], &taup[i__], &work[1], &ldwrkx, &work[ldwrkx * nb + 1], &ldwrky); /* Update the trailing submatrix A(i+nb:m,i+nb:n), using an update of the form A := A - V*Y' - X*U' */ i__3 = *m - i__ - nb + 1; i__4 = *n - i__ - nb + 1; sgemm_("No transpose", "Transpose", &i__3, &i__4, &nb, &c_b1290, &a[ i__ + nb + i__ * a_dim1], lda, &work[ldwrkx * nb + nb + 1], & ldwrky, &c_b1011, &a[i__ + nb + (i__ + nb) * a_dim1], lda); i__3 = *m - i__ - nb + 1; i__4 = *n - i__ - nb + 1; sgemm_("No transpose", "No transpose", &i__3, &i__4, &nb, &c_b1290, & work[nb + 1], &ldwrkx, &a[i__ + (i__ + nb) * a_dim1], lda, & c_b1011, &a[i__ + nb + (i__ + nb) * a_dim1], lda); /* Copy diagonal and off-diagonal elements of B back into A */ if (*m >= *n) { i__3 = i__ + nb - 1; for (j = i__; j <= i__3; ++j) { a[j + j * a_dim1] = d__[j]; a[j + (j + 1) * a_dim1] = e[j]; /* L10: */ } } else { i__3 = i__ + nb - 1; for (j = i__; j <= i__3; ++j) { a[j + j * a_dim1] = d__[j]; a[j + 1 + j * a_dim1] = e[j]; /* L20: */ } } /* L30: */ } /* Use unblocked code to reduce the remainder of the matrix */ i__2 = *m - i__ + 1; i__1 = *n - i__ + 1; sgebd2_(&i__2, &i__1, &a[i__ + i__ * a_dim1], lda, &d__[i__], &e[i__], & tauq[i__], &taup[i__], &work[1], &iinfo); work[1] = ws; return 0; /* End of SGEBRD */ } /* sgebrd_ */ /* Subroutine */ int sgeev_(char *jobvl, char *jobvr, integer *n, real *a, integer *lda, real *wr, real *wi, real *vl, integer *ldvl, real *vr, integer *ldvr, real *work, integer *lwork, integer *info) { /* System generated locals */ integer a_dim1, a_offset, vl_dim1, vl_offset, vr_dim1, vr_offset, i__1, i__2, i__3, i__4; real r__1, r__2; /* Builtin functions */ double sqrt(doublereal); /* Local variables */ static integer i__, k; static real r__, cs, sn; static integer ihi; static real scl; static integer ilo; static real dum[1], eps; static integer ibal; static char side[1]; static integer maxb; static real anrm; static integer ierr, itau, iwrk, nout; extern /* Subroutine */ int srot_(integer *, real *, integer *, real *, integer *, real *, real *); extern doublereal snrm2_(integer *, real *, integer *); extern logical lsame_(char *, char *); extern /* Subroutine */ int sscal_(integer *, real *, real *, integer *); extern doublereal slapy2_(real *, real *); extern /* Subroutine */ int slabad_(real *, real *); static logical scalea; static real cscale; extern /* Subroutine */ int sgebak_(char *, char *, integer *, integer *, integer *, real *, integer *, real *, integer *, integer *), sgebal_(char *, integer *, real *, integer *, integer *, integer *, real *, integer *); extern doublereal slamch_(char *), slange_(char *, integer *, integer *, real *, integer *, real *); extern /* Subroutine */ int sgehrd_(integer *, integer *, integer *, real *, integer *, real *, real *, integer *, integer *), xerbla_(char *, integer *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); static logical select[1]; static real bignum; extern /* Subroutine */ int slascl_(char *, integer *, integer *, real *, real *, integer *, integer *, real *, integer *, integer *); extern integer isamax_(integer *, real *, integer *); extern /* Subroutine */ int slacpy_(char *, integer *, integer *, real *, integer *, real *, integer *), slartg_(real *, real *, real *, real *, real *), sorghr_(integer *, integer *, integer *, real *, integer *, real *, real *, integer *, integer *), shseqr_( char *, char *, integer *, integer *, integer *, real *, integer * , real *, real *, real *, integer *, real *, integer *, integer *), strevc_(char *, char *, logical *, integer *, real *, integer *, real *, integer *, real *, integer *, integer * , integer *, real *, integer *); static integer minwrk, maxwrk; static logical wantvl; static real smlnum; static integer hswork; static logical lquery, wantvr; /* -- LAPACK driver routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University December 8, 1999 Purpose ======= SGEEV computes for an N-by-N real nonsymmetric matrix A, the eigenvalues and, optionally, the left and/or right eigenvectors. The right eigenvector v(j) of A satisfies A * v(j) = lambda(j) * v(j) where lambda(j) is its eigenvalue. The left eigenvector u(j) of A satisfies u(j)**H * A = lambda(j) * u(j)**H where u(j)**H denotes the conjugate transpose of u(j). The computed eigenvectors are normalized to have Euclidean norm equal to 1 and largest component real. Arguments ========= JOBVL (input) CHARACTER*1 = 'N': left eigenvectors of A are not computed; = 'V': left eigenvectors of A are computed. JOBVR (input) CHARACTER*1 = 'N': right eigenvectors of A are not computed; = 'V': right eigenvectors of A are computed. N (input) INTEGER The order of the matrix A. N >= 0. A (input/output) REAL array, dimension (LDA,N) On entry, the N-by-N matrix A. On exit, A has been overwritten. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,N). WR (output) REAL array, dimension (N) WI (output) REAL array, dimension (N) WR and WI contain the real and imaginary parts, respectively, of the computed eigenvalues. Complex conjugate pairs of eigenvalues appear consecutively with the eigenvalue having the positive imaginary part first. VL (output) REAL array, dimension (LDVL,N) If JOBVL = 'V', the left eigenvectors u(j) are stored one after another in the columns of VL, in the same order as their eigenvalues. If JOBVL = 'N', VL is not referenced. If the j-th eigenvalue is real, then u(j) = VL(:,j), the j-th column of VL. If the j-th and (j+1)-st eigenvalues form a complex conjugate pair, then u(j) = VL(:,j) + i*VL(:,j+1) and u(j+1) = VL(:,j) - i*VL(:,j+1). LDVL (input) INTEGER The leading dimension of the array VL. LDVL >= 1; if JOBVL = 'V', LDVL >= N. VR (output) REAL array, dimension (LDVR,N) If JOBVR = 'V', the right eigenvectors v(j) are stored one after another in the columns of VR, in the same order as their eigenvalues. If JOBVR = 'N', VR is not referenced. If the j-th eigenvalue is real, then v(j) = VR(:,j), the j-th column of VR. If the j-th and (j+1)-st eigenvalues form a complex conjugate pair, then v(j) = VR(:,j) + i*VR(:,j+1) and v(j+1) = VR(:,j) - i*VR(:,j+1). LDVR (input) INTEGER The leading dimension of the array VR. LDVR >= 1; if JOBVR = 'V', LDVR >= N. WORK (workspace/output) REAL array, dimension (LWORK) On exit, if INFO = 0, WORK(1) returns the optimal LWORK. LWORK (input) INTEGER The dimension of the array WORK. LWORK >= max(1,3*N), and if JOBVL = 'V' or JOBVR = 'V', LWORK >= 4*N. For good performance, LWORK must generally be larger. If LWORK = -1, then a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued by XERBLA. INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value. > 0: if INFO = i, the QR algorithm failed to compute all the eigenvalues, and no eigenvectors have been computed; elements i+1:N of WR and WI contain eigenvalues which have converged. ===================================================================== Test the input arguments */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --wr; --wi; vl_dim1 = *ldvl; vl_offset = 1 + vl_dim1; vl -= vl_offset; vr_dim1 = *ldvr; vr_offset = 1 + vr_dim1; vr -= vr_offset; --work; /* Function Body */ *info = 0; lquery = *lwork == -1; wantvl = lsame_(jobvl, "V"); wantvr = lsame_(jobvr, "V"); if (! wantvl && ! lsame_(jobvl, "N")) { *info = -1; } else if (! wantvr && ! lsame_(jobvr, "N")) { *info = -2; } else if (*n < 0) { *info = -3; } else if (*lda < max(1,*n)) { *info = -5; } else if ((*ldvl < 1) || (wantvl && *ldvl < *n)) { *info = -9; } else if ((*ldvr < 1) || (wantvr && *ldvr < *n)) { *info = -11; } /* Compute workspace (Note: Comments in the code beginning "Workspace:" describe the minimal amount of workspace needed at that point in the code, as well as the preferred amount for good performance. NB refers to the optimal block size for the immediately following subroutine, as returned by ILAENV. HSWORK refers to the workspace preferred by SHSEQR, as calculated below. HSWORK is computed assuming ILO=1 and IHI=N, the worst case.) */ minwrk = 1; if (*info == 0 && ((*lwork >= 1) || (lquery))) { maxwrk = ((*n) << (1)) + *n * ilaenv_(&c__1, "SGEHRD", " ", n, &c__1, n, &c__0, (ftnlen)6, (ftnlen)1); if (! wantvl && ! wantvr) { /* Computing MAX */ i__1 = 1, i__2 = *n * 3; minwrk = max(i__1,i__2); /* Computing MAX */ i__1 = ilaenv_(&c__8, "SHSEQR", "EN", n, &c__1, n, &c_n1, (ftnlen) 6, (ftnlen)2); maxb = max(i__1,2); /* Computing MIN Computing MAX */ i__3 = 2, i__4 = ilaenv_(&c__4, "SHSEQR", "EN", n, &c__1, n, & c_n1, (ftnlen)6, (ftnlen)2); i__1 = min(maxb,*n), i__2 = max(i__3,i__4); k = min(i__1,i__2); /* Computing MAX */ i__1 = k * (k + 2), i__2 = (*n) << (1); hswork = max(i__1,i__2); /* Computing MAX */ i__1 = maxwrk, i__2 = *n + 1, i__1 = max(i__1,i__2), i__2 = *n + hswork; maxwrk = max(i__1,i__2); } else { /* Computing MAX */ i__1 = 1, i__2 = (*n) << (2); minwrk = max(i__1,i__2); /* Computing MAX */ i__1 = maxwrk, i__2 = ((*n) << (1)) + (*n - 1) * ilaenv_(&c__1, "SORGHR", " ", n, &c__1, n, &c_n1, (ftnlen)6, (ftnlen)1); maxwrk = max(i__1,i__2); /* Computing MAX */ i__1 = ilaenv_(&c__8, "SHSEQR", "SV", n, &c__1, n, &c_n1, (ftnlen) 6, (ftnlen)2); maxb = max(i__1,2); /* Computing MIN Computing MAX */ i__3 = 2, i__4 = ilaenv_(&c__4, "SHSEQR", "SV", n, &c__1, n, & c_n1, (ftnlen)6, (ftnlen)2); i__1 = min(maxb,*n), i__2 = max(i__3,i__4); k = min(i__1,i__2); /* Computing MAX */ i__1 = k * (k + 2), i__2 = (*n) << (1); hswork = max(i__1,i__2); /* Computing MAX */ i__1 = maxwrk, i__2 = *n + 1, i__1 = max(i__1,i__2), i__2 = *n + hswork; maxwrk = max(i__1,i__2); /* Computing MAX */ i__1 = maxwrk, i__2 = (*n) << (2); maxwrk = max(i__1,i__2); } work[1] = (real) maxwrk; } if (*lwork < minwrk && ! lquery) { *info = -13; } if (*info != 0) { i__1 = -(*info); xerbla_("SGEEV ", &i__1); return 0; } else if (lquery) { return 0; } /* Quick return if possible */ if (*n == 0) { return 0; } /* Get machine constants */ eps = slamch_("P"); smlnum = slamch_("S"); bignum = 1.f / smlnum; slabad_(&smlnum, &bignum); smlnum = sqrt(smlnum) / eps; bignum = 1.f / smlnum; /* Scale A if max element outside range [SMLNUM,BIGNUM] */ anrm = slange_("M", n, n, &a[a_offset], lda, dum); scalea = FALSE_; if (anrm > 0.f && anrm < smlnum) { scalea = TRUE_; cscale = smlnum; } else if (anrm > bignum) { scalea = TRUE_; cscale = bignum; } if (scalea) { slascl_("G", &c__0, &c__0, &anrm, &cscale, n, n, &a[a_offset], lda, & ierr); } /* Balance the matrix (Workspace: need N) */ ibal = 1; sgebal_("B", n, &a[a_offset], lda, &ilo, &ihi, &work[ibal], &ierr); /* Reduce to upper Hessenberg form (Workspace: need 3*N, prefer 2*N+N*NB) */ itau = ibal + *n; iwrk = itau + *n; i__1 = *lwork - iwrk + 1; sgehrd_(n, &ilo, &ihi, &a[a_offset], lda, &work[itau], &work[iwrk], &i__1, &ierr); if (wantvl) { /* Want left eigenvectors Copy Householder vectors to VL */ *(unsigned char *)side = 'L'; slacpy_("L", n, n, &a[a_offset], lda, &vl[vl_offset], ldvl) ; /* Generate orthogonal matrix in VL (Workspace: need 3*N-1, prefer 2*N+(N-1)*NB) */ i__1 = *lwork - iwrk + 1; sorghr_(n, &ilo, &ihi, &vl[vl_offset], ldvl, &work[itau], &work[iwrk], &i__1, &ierr); /* Perform QR iteration, accumulating Schur vectors in VL (Workspace: need N+1, prefer N+HSWORK (see comments) ) */ iwrk = itau; i__1 = *lwork - iwrk + 1; shseqr_("S", "V", n, &ilo, &ihi, &a[a_offset], lda, &wr[1], &wi[1], & vl[vl_offset], ldvl, &work[iwrk], &i__1, info); if (wantvr) { /* Want left and right eigenvectors Copy Schur vectors to VR */ *(unsigned char *)side = 'B'; slacpy_("F", n, n, &vl[vl_offset], ldvl, &vr[vr_offset], ldvr); } } else if (wantvr) { /* Want right eigenvectors Copy Householder vectors to VR */ *(unsigned char *)side = 'R'; slacpy_("L", n, n, &a[a_offset], lda, &vr[vr_offset], ldvr) ; /* Generate orthogonal matrix in VR (Workspace: need 3*N-1, prefer 2*N+(N-1)*NB) */ i__1 = *lwork - iwrk + 1; sorghr_(n, &ilo, &ihi, &vr[vr_offset], ldvr, &work[itau], &work[iwrk], &i__1, &ierr); /* Perform QR iteration, accumulating Schur vectors in VR (Workspace: need N+1, prefer N+HSWORK (see comments) ) */ iwrk = itau; i__1 = *lwork - iwrk + 1; shseqr_("S", "V", n, &ilo, &ihi, &a[a_offset], lda, &wr[1], &wi[1], & vr[vr_offset], ldvr, &work[iwrk], &i__1, info); } else { /* Compute eigenvalues only (Workspace: need N+1, prefer N+HSWORK (see comments) ) */ iwrk = itau; i__1 = *lwork - iwrk + 1; shseqr_("E", "N", n, &ilo, &ihi, &a[a_offset], lda, &wr[1], &wi[1], & vr[vr_offset], ldvr, &work[iwrk], &i__1, info); } /* If INFO > 0 from SHSEQR, then quit */ if (*info > 0) { goto L50; } if ((wantvl) || (wantvr)) { /* Compute left and/or right eigenvectors (Workspace: need 4*N) */ strevc_(side, "B", select, n, &a[a_offset], lda, &vl[vl_offset], ldvl, &vr[vr_offset], ldvr, n, &nout, &work[iwrk], &ierr); } if (wantvl) { /* Undo balancing of left eigenvectors (Workspace: need N) */ sgebak_("B", "L", n, &ilo, &ihi, &work[ibal], n, &vl[vl_offset], ldvl, &ierr); /* Normalize left eigenvectors and make largest component real */ i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { if (wi[i__] == 0.f) { scl = 1.f / snrm2_(n, &vl[i__ * vl_dim1 + 1], &c__1); sscal_(n, &scl, &vl[i__ * vl_dim1 + 1], &c__1); } else if (wi[i__] > 0.f) { r__1 = snrm2_(n, &vl[i__ * vl_dim1 + 1], &c__1); r__2 = snrm2_(n, &vl[(i__ + 1) * vl_dim1 + 1], &c__1); scl = 1.f / slapy2_(&r__1, &r__2); sscal_(n, &scl, &vl[i__ * vl_dim1 + 1], &c__1); sscal_(n, &scl, &vl[(i__ + 1) * vl_dim1 + 1], &c__1); i__2 = *n; for (k = 1; k <= i__2; ++k) { /* Computing 2nd power */ r__1 = vl[k + i__ * vl_dim1]; /* Computing 2nd power */ r__2 = vl[k + (i__ + 1) * vl_dim1]; work[iwrk + k - 1] = r__1 * r__1 + r__2 * r__2; /* L10: */ } k = isamax_(n, &work[iwrk], &c__1); slartg_(&vl[k + i__ * vl_dim1], &vl[k + (i__ + 1) * vl_dim1], &cs, &sn, &r__); srot_(n, &vl[i__ * vl_dim1 + 1], &c__1, &vl[(i__ + 1) * vl_dim1 + 1], &c__1, &cs, &sn); vl[k + (i__ + 1) * vl_dim1] = 0.f; } /* L20: */ } } if (wantvr) { /* Undo balancing of right eigenvectors (Workspace: need N) */ sgebak_("B", "R", n, &ilo, &ihi, &work[ibal], n, &vr[vr_offset], ldvr, &ierr); /* Normalize right eigenvectors and make largest component real */ i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { if (wi[i__] == 0.f) { scl = 1.f / snrm2_(n, &vr[i__ * vr_dim1 + 1], &c__1); sscal_(n, &scl, &vr[i__ * vr_dim1 + 1], &c__1); } else if (wi[i__] > 0.f) { r__1 = snrm2_(n, &vr[i__ * vr_dim1 + 1], &c__1); r__2 = snrm2_(n, &vr[(i__ + 1) * vr_dim1 + 1], &c__1); scl = 1.f / slapy2_(&r__1, &r__2); sscal_(n, &scl, &vr[i__ * vr_dim1 + 1], &c__1); sscal_(n, &scl, &vr[(i__ + 1) * vr_dim1 + 1], &c__1); i__2 = *n; for (k = 1; k <= i__2; ++k) { /* Computing 2nd power */ r__1 = vr[k + i__ * vr_dim1]; /* Computing 2nd power */ r__2 = vr[k + (i__ + 1) * vr_dim1]; work[iwrk + k - 1] = r__1 * r__1 + r__2 * r__2; /* L30: */ } k = isamax_(n, &work[iwrk], &c__1); slartg_(&vr[k + i__ * vr_dim1], &vr[k + (i__ + 1) * vr_dim1], &cs, &sn, &r__); srot_(n, &vr[i__ * vr_dim1 + 1], &c__1, &vr[(i__ + 1) * vr_dim1 + 1], &c__1, &cs, &sn); vr[k + (i__ + 1) * vr_dim1] = 0.f; } /* L40: */ } } /* Undo scaling if necessary */ L50: if (scalea) { i__1 = *n - *info; /* Computing MAX */ i__3 = *n - *info; i__2 = max(i__3,1); slascl_("G", &c__0, &c__0, &cscale, &anrm, &i__1, &c__1, &wr[*info + 1], &i__2, &ierr); i__1 = *n - *info; /* Computing MAX */ i__3 = *n - *info; i__2 = max(i__3,1); slascl_("G", &c__0, &c__0, &cscale, &anrm, &i__1, &c__1, &wi[*info + 1], &i__2, &ierr); if (*info > 0) { i__1 = ilo - 1; slascl_("G", &c__0, &c__0, &cscale, &anrm, &i__1, &c__1, &wr[1], n, &ierr); i__1 = ilo - 1; slascl_("G", &c__0, &c__0, &cscale, &anrm, &i__1, &c__1, &wi[1], n, &ierr); } } work[1] = (real) maxwrk; return 0; /* End of SGEEV */ } /* sgeev_ */ /* Subroutine */ int sgehd2_(integer *n, integer *ilo, integer *ihi, real *a, integer *lda, real *tau, real *work, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3; /* Local variables */ static integer i__; static real aii; extern /* Subroutine */ int slarf_(char *, integer *, integer *, real *, integer *, real *, real *, integer *, real *), xerbla_( char *, integer *), slarfg_(integer *, real *, real *, integer *, real *); /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University October 31, 1992 Purpose ======= SGEHD2 reduces a real general matrix A to upper Hessenberg form H by an orthogonal similarity transformation: Q' * A * Q = H . Arguments ========= N (input) INTEGER The order of the matrix A. N >= 0. ILO (input) INTEGER IHI (input) INTEGER It is assumed that A is already upper triangular in rows and columns 1:ILO-1 and IHI+1:N. ILO and IHI are normally set by a previous call to SGEBAL; otherwise they should be set to 1 and N respectively. See Further Details. 1 <= ILO <= IHI <= max(1,N). A (input/output) REAL array, dimension (LDA,N) On entry, the n by n general matrix to be reduced. On exit, the upper triangle and the first subdiagonal of A are overwritten with the upper Hessenberg matrix H, and the elements below the first subdiagonal, with the array TAU, represent the orthogonal matrix Q as a product of elementary reflectors. See Further Details. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,N). TAU (output) REAL array, dimension (N-1) The scalar factors of the elementary reflectors (see Further Details). WORK (workspace) REAL array, dimension (N) INFO (output) INTEGER = 0: successful exit. < 0: if INFO = -i, the i-th argument had an illegal value. Further Details =============== The matrix Q is represented as a product of (ihi-ilo) elementary reflectors Q = H(ilo) H(ilo+1) . . . H(ihi-1). Each H(i) has the form H(i) = I - tau * v * v' where tau is a real scalar, and v is a real vector with v(1:i) = 0, v(i+1) = 1 and v(ihi+1:n) = 0; v(i+2:ihi) is stored on exit in A(i+2:ihi,i), and tau in TAU(i). The contents of A are illustrated by the following example, with n = 7, ilo = 2 and ihi = 6: on entry, on exit, ( a a a a a a a ) ( a a h h h h a ) ( a a a a a a ) ( a h h h h a ) ( a a a a a a ) ( h h h h h h ) ( a a a a a a ) ( v2 h h h h h ) ( a a a a a a ) ( v2 v3 h h h h ) ( a a a a a a ) ( v2 v3 v4 h h h ) ( a ) ( a ) where a denotes an element of the original matrix A, h denotes a modified element of the upper Hessenberg matrix H, and vi denotes an element of the vector defining H(i). ===================================================================== Test the input parameters */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --tau; --work; /* Function Body */ *info = 0; if (*n < 0) { *info = -1; } else if ((*ilo < 1) || (*ilo > max(1,*n))) { *info = -2; } else if ((*ihi < min(*ilo,*n)) || (*ihi > *n)) { *info = -3; } else if (*lda < max(1,*n)) { *info = -5; } if (*info != 0) { i__1 = -(*info); xerbla_("SGEHD2", &i__1); return 0; } i__1 = *ihi - 1; for (i__ = *ilo; i__ <= i__1; ++i__) { /* Compute elementary reflector H(i) to annihilate A(i+2:ihi,i) */ i__2 = *ihi - i__; /* Computing MIN */ i__3 = i__ + 2; slarfg_(&i__2, &a[i__ + 1 + i__ * a_dim1], &a[min(i__3,*n) + i__ * a_dim1], &c__1, &tau[i__]); aii = a[i__ + 1 + i__ * a_dim1]; a[i__ + 1 + i__ * a_dim1] = 1.f; /* Apply H(i) to A(1:ihi,i+1:ihi) from the right */ i__2 = *ihi - i__; slarf_("Right", ihi, &i__2, &a[i__ + 1 + i__ * a_dim1], &c__1, &tau[ i__], &a[(i__ + 1) * a_dim1 + 1], lda, &work[1]); /* Apply H(i) to A(i+1:ihi,i+1:n) from the left */ i__2 = *ihi - i__; i__3 = *n - i__; slarf_("Left", &i__2, &i__3, &a[i__ + 1 + i__ * a_dim1], &c__1, &tau[ i__], &a[i__ + 1 + (i__ + 1) * a_dim1], lda, &work[1]); a[i__ + 1 + i__ * a_dim1] = aii; /* L10: */ } return 0; /* End of SGEHD2 */ } /* sgehd2_ */ /* Subroutine */ int sgehrd_(integer *n, integer *ilo, integer *ihi, real *a, integer *lda, real *tau, real *work, integer *lwork, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3, i__4; /* Local variables */ static integer i__; static real t[4160] /* was [65][64] */; static integer ib; static real ei; static integer nb, nh, nx, iws, nbmin, iinfo; extern /* Subroutine */ int sgemm_(char *, char *, integer *, integer *, integer *, real *, real *, integer *, real *, integer *, real *, real *, integer *), sgehd2_(integer *, integer *, integer *, real *, integer *, real *, real *, integer *), slarfb_( char *, char *, char *, char *, integer *, integer *, integer *, real *, integer *, real *, integer *, real *, integer *, real *, integer *), slahrd_(integer *, integer *, integer *, real *, integer *, real *, real *, integer * , real *, integer *), xerbla_(char *, integer *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); static integer ldwork, lwkopt; static logical lquery; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= SGEHRD reduces a real general matrix A to upper Hessenberg form H by an orthogonal similarity transformation: Q' * A * Q = H . Arguments ========= N (input) INTEGER The order of the matrix A. N >= 0. ILO (input) INTEGER IHI (input) INTEGER It is assumed that A is already upper triangular in rows and columns 1:ILO-1 and IHI+1:N. ILO and IHI are normally set by a previous call to SGEBAL; otherwise they should be set to 1 and N respectively. See Further Details. 1 <= ILO <= IHI <= N, if N > 0; ILO=1 and IHI=0, if N=0. A (input/output) REAL array, dimension (LDA,N) On entry, the N-by-N general matrix to be reduced. On exit, the upper triangle and the first subdiagonal of A are overwritten with the upper Hessenberg matrix H, and the elements below the first subdiagonal, with the array TAU, represent the orthogonal matrix Q as a product of elementary reflectors. See Further Details. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,N). TAU (output) REAL array, dimension (N-1) The scalar factors of the elementary reflectors (see Further Details). Elements 1:ILO-1 and IHI:N-1 of TAU are set to zero. WORK (workspace/output) REAL array, dimension (LWORK) On exit, if INFO = 0, WORK(1) returns the optimal LWORK. LWORK (input) INTEGER The length of the array WORK. LWORK >= max(1,N). For optimum performance LWORK >= N*NB, where NB is the optimal blocksize. If LWORK = -1, then a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued by XERBLA. INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value. Further Details =============== The matrix Q is represented as a product of (ihi-ilo) elementary reflectors Q = H(ilo) H(ilo+1) . . . H(ihi-1). Each H(i) has the form H(i) = I - tau * v * v' where tau is a real scalar, and v is a real vector with v(1:i) = 0, v(i+1) = 1 and v(ihi+1:n) = 0; v(i+2:ihi) is stored on exit in A(i+2:ihi,i), and tau in TAU(i). The contents of A are illustrated by the following example, with n = 7, ilo = 2 and ihi = 6: on entry, on exit, ( a a a a a a a ) ( a a h h h h a ) ( a a a a a a ) ( a h h h h a ) ( a a a a a a ) ( h h h h h h ) ( a a a a a a ) ( v2 h h h h h ) ( a a a a a a ) ( v2 v3 h h h h ) ( a a a a a a ) ( v2 v3 v4 h h h ) ( a ) ( a ) where a denotes an element of the original matrix A, h denotes a modified element of the upper Hessenberg matrix H, and vi denotes an element of the vector defining H(i). ===================================================================== Test the input parameters */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --tau; --work; /* Function Body */ *info = 0; /* Computing MIN */ i__1 = 64, i__2 = ilaenv_(&c__1, "SGEHRD", " ", n, ilo, ihi, &c_n1, ( ftnlen)6, (ftnlen)1); nb = min(i__1,i__2); lwkopt = *n * nb; work[1] = (real) lwkopt; lquery = *lwork == -1; if (*n < 0) { *info = -1; } else if ((*ilo < 1) || (*ilo > max(1,*n))) { *info = -2; } else if ((*ihi < min(*ilo,*n)) || (*ihi > *n)) { *info = -3; } else if (*lda < max(1,*n)) { *info = -5; } else if (*lwork < max(1,*n) && ! lquery) { *info = -8; } if (*info != 0) { i__1 = -(*info); xerbla_("SGEHRD", &i__1); return 0; } else if (lquery) { return 0; } /* Set elements 1:ILO-1 and IHI:N-1 of TAU to zero */ i__1 = *ilo - 1; for (i__ = 1; i__ <= i__1; ++i__) { tau[i__] = 0.f; /* L10: */ } i__1 = *n - 1; for (i__ = max(1,*ihi); i__ <= i__1; ++i__) { tau[i__] = 0.f; /* L20: */ } /* Quick return if possible */ nh = *ihi - *ilo + 1; if (nh <= 1) { work[1] = 1.f; return 0; } /* Determine the block size. Computing MIN */ i__1 = 64, i__2 = ilaenv_(&c__1, "SGEHRD", " ", n, ilo, ihi, &c_n1, ( ftnlen)6, (ftnlen)1); nb = min(i__1,i__2); nbmin = 2; iws = 1; if (nb > 1 && nb < nh) { /* Determine when to cross over from blocked to unblocked code (last block is always handled by unblocked code). Computing MAX */ i__1 = nb, i__2 = ilaenv_(&c__3, "SGEHRD", " ", n, ilo, ihi, &c_n1, ( ftnlen)6, (ftnlen)1); nx = max(i__1,i__2); if (nx < nh) { /* Determine if workspace is large enough for blocked code. */ iws = *n * nb; if (*lwork < iws) { /* Not enough workspace to use optimal NB: determine the minimum value of NB, and reduce NB or force use of unblocked code. Computing MAX */ i__1 = 2, i__2 = ilaenv_(&c__2, "SGEHRD", " ", n, ilo, ihi, & c_n1, (ftnlen)6, (ftnlen)1); nbmin = max(i__1,i__2); if (*lwork >= *n * nbmin) { nb = *lwork / *n; } else { nb = 1; } } } } ldwork = *n; if ((nb < nbmin) || (nb >= nh)) { /* Use unblocked code below */ i__ = *ilo; } else { /* Use blocked code */ i__1 = *ihi - 1 - nx; i__2 = nb; for (i__ = *ilo; i__2 < 0 ? i__ >= i__1 : i__ <= i__1; i__ += i__2) { /* Computing MIN */ i__3 = nb, i__4 = *ihi - i__; ib = min(i__3,i__4); /* Reduce columns i:i+ib-1 to Hessenberg form, returning the matrices V and T of the block reflector H = I - V*T*V' which performs the reduction, and also the matrix Y = A*V*T */ slahrd_(ihi, &i__, &ib, &a[i__ * a_dim1 + 1], lda, &tau[i__], t, & c__65, &work[1], &ldwork); /* Apply the block reflector H to A(1:ihi,i+ib:ihi) from the right, computing A := A - Y * V'. V(i+ib,ib-1) must be set to 1. */ ei = a[i__ + ib + (i__ + ib - 1) * a_dim1]; a[i__ + ib + (i__ + ib - 1) * a_dim1] = 1.f; i__3 = *ihi - i__ - ib + 1; sgemm_("No transpose", "Transpose", ihi, &i__3, &ib, &c_b1290, & work[1], &ldwork, &a[i__ + ib + i__ * a_dim1], lda, & c_b1011, &a[(i__ + ib) * a_dim1 + 1], lda); a[i__ + ib + (i__ + ib - 1) * a_dim1] = ei; /* Apply the block reflector H to A(i+1:ihi,i+ib:n) from the left */ i__3 = *ihi - i__; i__4 = *n - i__ - ib + 1; slarfb_("Left", "Transpose", "Forward", "Columnwise", &i__3, & i__4, &ib, &a[i__ + 1 + i__ * a_dim1], lda, t, &c__65, &a[ i__ + 1 + (i__ + ib) * a_dim1], lda, &work[1], &ldwork); /* L30: */ } } /* Use unblocked code to reduce the rest of the matrix */ sgehd2_(n, &i__, ihi, &a[a_offset], lda, &tau[1], &work[1], &iinfo); work[1] = (real) iws; return 0; /* End of SGEHRD */ } /* sgehrd_ */ /* Subroutine */ int sgelq2_(integer *m, integer *n, real *a, integer *lda, real *tau, real *work, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3; /* Local variables */ static integer i__, k; static real aii; extern /* Subroutine */ int slarf_(char *, integer *, integer *, real *, integer *, real *, real *, integer *, real *), xerbla_( char *, integer *), slarfg_(integer *, real *, real *, integer *, real *); /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University February 29, 1992 Purpose ======= SGELQ2 computes an LQ factorization of a real m by n matrix A: A = L * Q. Arguments ========= M (input) INTEGER The number of rows of the matrix A. M >= 0. N (input) INTEGER The number of columns of the matrix A. N >= 0. A (input/output) REAL array, dimension (LDA,N) On entry, the m by n matrix A. On exit, the elements on and below the diagonal of the array contain the m by min(m,n) lower trapezoidal matrix L (L is lower triangular if m <= n); the elements above the diagonal, with the array TAU, represent the orthogonal matrix Q as a product of elementary reflectors (see Further Details). LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,M). TAU (output) REAL array, dimension (min(M,N)) The scalar factors of the elementary reflectors (see Further Details). WORK (workspace) REAL array, dimension (M) INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value Further Details =============== The matrix Q is represented as a product of elementary reflectors Q = H(k) . . . H(2) H(1), where k = min(m,n). Each H(i) has the form H(i) = I - tau * v * v' where tau is a real scalar, and v is a real vector with v(1:i-1) = 0 and v(i) = 1; v(i+1:n) is stored on exit in A(i,i+1:n), and tau in TAU(i). ===================================================================== Test the input arguments */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --tau; --work; /* Function Body */ *info = 0; if (*m < 0) { *info = -1; } else if (*n < 0) { *info = -2; } else if (*lda < max(1,*m)) { *info = -4; } if (*info != 0) { i__1 = -(*info); xerbla_("SGELQ2", &i__1); return 0; } k = min(*m,*n); i__1 = k; for (i__ = 1; i__ <= i__1; ++i__) { /* Generate elementary reflector H(i) to annihilate A(i,i+1:n) */ i__2 = *n - i__ + 1; /* Computing MIN */ i__3 = i__ + 1; slarfg_(&i__2, &a[i__ + i__ * a_dim1], &a[i__ + min(i__3,*n) * a_dim1] , lda, &tau[i__]); if (i__ < *m) { /* Apply H(i) to A(i+1:m,i:n) from the right */ aii = a[i__ + i__ * a_dim1]; a[i__ + i__ * a_dim1] = 1.f; i__2 = *m - i__; i__3 = *n - i__ + 1; slarf_("Right", &i__2, &i__3, &a[i__ + i__ * a_dim1], lda, &tau[ i__], &a[i__ + 1 + i__ * a_dim1], lda, &work[1]); a[i__ + i__ * a_dim1] = aii; } /* L10: */ } return 0; /* End of SGELQ2 */ } /* sgelq2_ */ /* Subroutine */ int sgelqf_(integer *m, integer *n, real *a, integer *lda, real *tau, real *work, integer *lwork, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3, i__4; /* Local variables */ static integer i__, k, ib, nb, nx, iws, nbmin, iinfo; extern /* Subroutine */ int sgelq2_(integer *, integer *, real *, integer *, real *, real *, integer *), slarfb_(char *, char *, char *, char *, integer *, integer *, integer *, real *, integer *, real * , integer *, real *, integer *, real *, integer *), xerbla_(char *, integer *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); extern /* Subroutine */ int slarft_(char *, char *, integer *, integer *, real *, integer *, real *, real *, integer *); static integer ldwork, lwkopt; static logical lquery; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= SGELQF computes an LQ factorization of a real M-by-N matrix A: A = L * Q. Arguments ========= M (input) INTEGER The number of rows of the matrix A. M >= 0. N (input) INTEGER The number of columns of the matrix A. N >= 0. A (input/output) REAL array, dimension (LDA,N) On entry, the M-by-N matrix A. On exit, the elements on and below the diagonal of the array contain the m-by-min(m,n) lower trapezoidal matrix L (L is lower triangular if m <= n); the elements above the diagonal, with the array TAU, represent the orthogonal matrix Q as a product of elementary reflectors (see Further Details). LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,M). TAU (output) REAL array, dimension (min(M,N)) The scalar factors of the elementary reflectors (see Further Details). WORK (workspace/output) REAL array, dimension (LWORK) On exit, if INFO = 0, WORK(1) returns the optimal LWORK. LWORK (input) INTEGER The dimension of the array WORK. LWORK >= max(1,M). For optimum performance LWORK >= M*NB, where NB is the optimal blocksize. If LWORK = -1, then a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued by XERBLA. INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value Further Details =============== The matrix Q is represented as a product of elementary reflectors Q = H(k) . . . H(2) H(1), where k = min(m,n). Each H(i) has the form H(i) = I - tau * v * v' where tau is a real scalar, and v is a real vector with v(1:i-1) = 0 and v(i) = 1; v(i+1:n) is stored on exit in A(i,i+1:n), and tau in TAU(i). ===================================================================== Test the input arguments */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --tau; --work; /* Function Body */ *info = 0; nb = ilaenv_(&c__1, "SGELQF", " ", m, n, &c_n1, &c_n1, (ftnlen)6, (ftnlen) 1); lwkopt = *m * nb; work[1] = (real) lwkopt; lquery = *lwork == -1; if (*m < 0) { *info = -1; } else if (*n < 0) { *info = -2; } else if (*lda < max(1,*m)) { *info = -4; } else if (*lwork < max(1,*m) && ! lquery) { *info = -7; } if (*info != 0) { i__1 = -(*info); xerbla_("SGELQF", &i__1); return 0; } else if (lquery) { return 0; } /* Quick return if possible */ k = min(*m,*n); if (k == 0) { work[1] = 1.f; return 0; } nbmin = 2; nx = 0; iws = *m; if (nb > 1 && nb < k) { /* Determine when to cross over from blocked to unblocked code. Computing MAX */ i__1 = 0, i__2 = ilaenv_(&c__3, "SGELQF", " ", m, n, &c_n1, &c_n1, ( ftnlen)6, (ftnlen)1); nx = max(i__1,i__2); if (nx < k) { /* Determine if workspace is large enough for blocked code. */ ldwork = *m; iws = ldwork * nb; if (*lwork < iws) { /* Not enough workspace to use optimal NB: reduce NB and determine the minimum value of NB. */ nb = *lwork / ldwork; /* Computing MAX */ i__1 = 2, i__2 = ilaenv_(&c__2, "SGELQF", " ", m, n, &c_n1, & c_n1, (ftnlen)6, (ftnlen)1); nbmin = max(i__1,i__2); } } } if (nb >= nbmin && nb < k && nx < k) { /* Use blocked code initially */ i__1 = k - nx; i__2 = nb; for (i__ = 1; i__2 < 0 ? i__ >= i__1 : i__ <= i__1; i__ += i__2) { /* Computing MIN */ i__3 = k - i__ + 1; ib = min(i__3,nb); /* Compute the LQ factorization of the current block A(i:i+ib-1,i:n) */ i__3 = *n - i__ + 1; sgelq2_(&ib, &i__3, &a[i__ + i__ * a_dim1], lda, &tau[i__], &work[ 1], &iinfo); if (i__ + ib <= *m) { /* Form the triangular factor of the block reflector H = H(i) H(i+1) . . . H(i+ib-1) */ i__3 = *n - i__ + 1; slarft_("Forward", "Rowwise", &i__3, &ib, &a[i__ + i__ * a_dim1], lda, &tau[i__], &work[1], &ldwork); /* Apply H to A(i+ib:m,i:n) from the right */ i__3 = *m - i__ - ib + 1; i__4 = *n - i__ + 1; slarfb_("Right", "No transpose", "Forward", "Rowwise", &i__3, &i__4, &ib, &a[i__ + i__ * a_dim1], lda, &work[1], & ldwork, &a[i__ + ib + i__ * a_dim1], lda, &work[ib + 1], &ldwork); } /* L10: */ } } else { i__ = 1; } /* Use unblocked code to factor the last or only block. */ if (i__ <= k) { i__2 = *m - i__ + 1; i__1 = *n - i__ + 1; sgelq2_(&i__2, &i__1, &a[i__ + i__ * a_dim1], lda, &tau[i__], &work[1] , &iinfo); } work[1] = (real) iws; return 0; /* End of SGELQF */ } /* sgelqf_ */ /* Subroutine */ int sgelsd_(integer *m, integer *n, integer *nrhs, real *a, integer *lda, real *b, integer *ldb, real *s, real *rcond, integer * rank, real *work, integer *lwork, integer *iwork, integer *info) { /* System generated locals */ integer a_dim1, a_offset, b_dim1, b_offset, i__1, i__2, i__3, i__4; /* Builtin functions */ double log(doublereal); /* Local variables */ static integer ie, il, mm; static real eps, anrm, bnrm; static integer itau, nlvl, iascl, ibscl; static real sfmin; static integer minmn, maxmn, itaup, itauq, mnthr, nwork; extern /* Subroutine */ int slabad_(real *, real *), sgebrd_(integer *, integer *, real *, integer *, real *, real *, real *, real *, real *, integer *, integer *); extern doublereal slamch_(char *), slange_(char *, integer *, integer *, real *, integer *, real *); extern /* Subroutine */ int xerbla_(char *, integer *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); static real bignum; extern /* Subroutine */ int sgelqf_(integer *, integer *, real *, integer *, real *, real *, integer *, integer *), slalsd_(char *, integer *, integer *, integer *, real *, real *, real *, integer *, real * , integer *, real *, integer *, integer *), slascl_(char * , integer *, integer *, real *, real *, integer *, integer *, real *, integer *, integer *); static integer wlalsd; extern /* Subroutine */ int sgeqrf_(integer *, integer *, real *, integer *, real *, real *, integer *, integer *), slacpy_(char *, integer *, integer *, real *, integer *, real *, integer *), slaset_(char *, integer *, integer *, real *, real *, real *, integer *); static integer ldwork; extern /* Subroutine */ int sormbr_(char *, char *, char *, integer *, integer *, integer *, real *, integer *, real *, real *, integer * , real *, integer *, integer *); static integer minwrk, maxwrk; static real smlnum; extern /* Subroutine */ int sormlq_(char *, char *, integer *, integer *, integer *, real *, integer *, real *, real *, integer *, real *, integer *, integer *); static logical lquery; static integer smlsiz; extern /* Subroutine */ int sormqr_(char *, char *, integer *, integer *, integer *, real *, integer *, real *, real *, integer *, real *, integer *, integer *); /* -- LAPACK driver routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University October 31, 1999 Purpose ======= SGELSD computes the minimum-norm solution to a real linear least squares problem: minimize 2-norm(| b - A*x |) using the singular value decomposition (SVD) of A. A is an M-by-N matrix which may be rank-deficient. Several right hand side vectors b and solution vectors x can be handled in a single call; they are stored as the columns of the M-by-NRHS right hand side matrix B and the N-by-NRHS solution matrix X. The problem is solved in three steps: (1) Reduce the coefficient matrix A to bidiagonal form with Householder transformations, reducing the original problem into a "bidiagonal least squares problem" (BLS) (2) Solve the BLS using a divide and conquer approach. (3) Apply back all the Householder tranformations to solve the original least squares problem. The effective rank of A is determined by treating as zero those singular values which are less than RCOND times the largest singular value. The divide and conquer algorithm makes very mild assumptions about floating point arithmetic. It will work on machines with a guard digit in add/subtract, or on those binary machines without guard digits which subtract like the Cray X-MP, Cray Y-MP, Cray C-90, or Cray-2. It could conceivably fail on hexadecimal or decimal machines without guard digits, but we know of none. Arguments ========= M (input) INTEGER The number of rows of A. M >= 0. N (input) INTEGER The number of columns of A. N >= 0. NRHS (input) INTEGER The number of right hand sides, i.e., the number of columns of the matrices B and X. NRHS >= 0. A (input) REAL array, dimension (LDA,N) On entry, the M-by-N matrix A. On exit, A has been destroyed. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,M). B (input/output) REAL array, dimension (LDB,NRHS) On entry, the M-by-NRHS right hand side matrix B. On exit, B is overwritten by the N-by-NRHS solution matrix X. If m >= n and RANK = n, the residual sum-of-squares for the solution in the i-th column is given by the sum of squares of elements n+1:m in that column. LDB (input) INTEGER The leading dimension of the array B. LDB >= max(1,max(M,N)). S (output) REAL array, dimension (min(M,N)) The singular values of A in decreasing order. The condition number of A in the 2-norm = S(1)/S(min(m,n)). RCOND (input) REAL RCOND is used to determine the effective rank of A. Singular values S(i) <= RCOND*S(1) are treated as zero. If RCOND < 0, machine precision is used instead. RANK (output) INTEGER The effective rank of A, i.e., the number of singular values which are greater than RCOND*S(1). WORK (workspace/output) REAL array, dimension (LWORK) On exit, if INFO = 0, WORK(1) returns the optimal LWORK. LWORK (input) INTEGER The dimension of the array WORK. LWORK must be at least 1. The exact minimum amount of workspace needed depends on M, N and NRHS. As long as LWORK is at least 12*N + 2*N*SMLSIZ + 8*N*NLVL + N*NRHS + (SMLSIZ+1)**2, if M is greater than or equal to N or 12*M + 2*M*SMLSIZ + 8*M*NLVL + M*NRHS + (SMLSIZ+1)**2, if M is less than N, the code will execute correctly. SMLSIZ is returned by ILAENV and is equal to the maximum size of the subproblems at the bottom of the computation tree (usually about 25), and NLVL = MAX( 0, INT( LOG_2( MIN( M,N )/(SMLSIZ+1) ) ) + 1 ) For good performance, LWORK should generally be larger. If LWORK = -1, then a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued by XERBLA. IWORK (workspace) INTEGER array, dimension (LIWORK) LIWORK >= 3 * MINMN * NLVL + 11 * MINMN, where MINMN = MIN( M,N ). INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value. > 0: the algorithm for computing the SVD failed to converge; if INFO = i, i off-diagonal elements of an intermediate bidiagonal form did not converge to zero. Further Details =============== Based on contributions by Ming Gu and Ren-Cang Li, Computer Science Division, University of California at Berkeley, USA Osni Marques, LBNL/NERSC, USA ===================================================================== Test the input arguments. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; b_dim1 = *ldb; b_offset = 1 + b_dim1; b -= b_offset; --s; --work; --iwork; /* Function Body */ *info = 0; minmn = min(*m,*n); maxmn = max(*m,*n); mnthr = ilaenv_(&c__6, "SGELSD", " ", m, n, nrhs, &c_n1, (ftnlen)6, ( ftnlen)1); lquery = *lwork == -1; if (*m < 0) { *info = -1; } else if (*n < 0) { *info = -2; } else if (*nrhs < 0) { *info = -3; } else if (*lda < max(1,*m)) { *info = -5; } else if (*ldb < max(1,maxmn)) { *info = -7; } smlsiz = ilaenv_(&c__9, "SGELSD", " ", &c__0, &c__0, &c__0, &c__0, ( ftnlen)6, (ftnlen)1); /* Compute workspace. (Note: Comments in the code beginning "Workspace:" describe the minimal amount of workspace needed at that point in the code, as well as the preferred amount for good performance. NB refers to the optimal block size for the immediately following subroutine, as returned by ILAENV.) */ minwrk = 1; minmn = max(1,minmn); /* Computing MAX */ i__1 = (integer) (log((real) minmn / (real) (smlsiz + 1)) / log(2.f)) + 1; nlvl = max(i__1,0); if (*info == 0) { maxwrk = 0; mm = *m; if (*m >= *n && *m >= mnthr) { /* Path 1a - overdetermined, with many more rows than columns. */ mm = *n; /* Computing MAX */ i__1 = maxwrk, i__2 = *n + *n * ilaenv_(&c__1, "SGEQRF", " ", m, n, &c_n1, &c_n1, (ftnlen)6, (ftnlen)1); maxwrk = max(i__1,i__2); /* Computing MAX */ i__1 = maxwrk, i__2 = *n + *nrhs * ilaenv_(&c__1, "SORMQR", "LT", m, nrhs, n, &c_n1, (ftnlen)6, (ftnlen)2); maxwrk = max(i__1,i__2); } if (*m >= *n) { /* Path 1 - overdetermined or exactly determined. Computing MAX */ i__1 = maxwrk, i__2 = *n * 3 + (mm + *n) * ilaenv_(&c__1, "SGEBRD" , " ", &mm, n, &c_n1, &c_n1, (ftnlen)6, (ftnlen)1); maxwrk = max(i__1,i__2); /* Computing MAX */ i__1 = maxwrk, i__2 = *n * 3 + *nrhs * ilaenv_(&c__1, "SORMBR", "QLT", &mm, nrhs, n, &c_n1, (ftnlen)6, (ftnlen)3); maxwrk = max(i__1,i__2); /* Computing MAX */ i__1 = maxwrk, i__2 = *n * 3 + (*n - 1) * ilaenv_(&c__1, "SORMBR", "PLN", n, nrhs, n, &c_n1, (ftnlen)6, (ftnlen)3); maxwrk = max(i__1,i__2); /* Computing 2nd power */ i__1 = smlsiz + 1; wlalsd = *n * 9 + ((*n) << (1)) * smlsiz + ((*n) << (3)) * nlvl + *n * *nrhs + i__1 * i__1; /* Computing MAX */ i__1 = maxwrk, i__2 = *n * 3 + wlalsd; maxwrk = max(i__1,i__2); /* Computing MAX */ i__1 = *n * 3 + mm, i__2 = *n * 3 + *nrhs, i__1 = max(i__1,i__2), i__2 = *n * 3 + wlalsd; minwrk = max(i__1,i__2); } if (*n > *m) { /* Computing 2nd power */ i__1 = smlsiz + 1; wlalsd = *m * 9 + ((*m) << (1)) * smlsiz + ((*m) << (3)) * nlvl + *m * *nrhs + i__1 * i__1; if (*n >= mnthr) { /* Path 2a - underdetermined, with many more columns than rows. */ maxwrk = *m + *m * ilaenv_(&c__1, "SGELQF", " ", m, n, &c_n1, &c_n1, (ftnlen)6, (ftnlen)1); /* Computing MAX */ i__1 = maxwrk, i__2 = *m * *m + ((*m) << (2)) + ((*m) << (1)) * ilaenv_(&c__1, "SGEBRD", " ", m, m, &c_n1, &c_n1, ( ftnlen)6, (ftnlen)1); maxwrk = max(i__1,i__2); /* Computing MAX */ i__1 = maxwrk, i__2 = *m * *m + ((*m) << (2)) + *nrhs * ilaenv_(&c__1, "SORMBR", "QLT", m, nrhs, m, &c_n1, ( ftnlen)6, (ftnlen)3); maxwrk = max(i__1,i__2); /* Computing MAX */ i__1 = maxwrk, i__2 = *m * *m + ((*m) << (2)) + (*m - 1) * ilaenv_(&c__1, "SORMBR", "PLN", m, nrhs, m, &c_n1, ( ftnlen)6, (ftnlen)3); maxwrk = max(i__1,i__2); if (*nrhs > 1) { /* Computing MAX */ i__1 = maxwrk, i__2 = *m * *m + *m + *m * *nrhs; maxwrk = max(i__1,i__2); } else { /* Computing MAX */ i__1 = maxwrk, i__2 = *m * *m + ((*m) << (1)); maxwrk = max(i__1,i__2); } /* Computing MAX */ i__1 = maxwrk, i__2 = *m + *nrhs * ilaenv_(&c__1, "SORMLQ", "LT", n, nrhs, m, &c_n1, (ftnlen)6, (ftnlen)2); maxwrk = max(i__1,i__2); /* Computing MAX */ i__1 = maxwrk, i__2 = *m * *m + ((*m) << (2)) + wlalsd; maxwrk = max(i__1,i__2); } else { /* Path 2 - remaining underdetermined cases. */ maxwrk = *m * 3 + (*n + *m) * ilaenv_(&c__1, "SGEBRD", " ", m, n, &c_n1, &c_n1, (ftnlen)6, (ftnlen)1); /* Computing MAX */ i__1 = maxwrk, i__2 = *m * 3 + *nrhs * ilaenv_(&c__1, "SORMBR" , "QLT", m, nrhs, n, &c_n1, (ftnlen)6, (ftnlen)3); maxwrk = max(i__1,i__2); /* Computing MAX */ i__1 = maxwrk, i__2 = *m * 3 + *m * ilaenv_(&c__1, "SORMBR", "PLN", n, nrhs, m, &c_n1, (ftnlen)6, (ftnlen)3); maxwrk = max(i__1,i__2); /* Computing MAX */ i__1 = maxwrk, i__2 = *m * 3 + wlalsd; maxwrk = max(i__1,i__2); } /* Computing MAX */ i__1 = *m * 3 + *nrhs, i__2 = *m * 3 + *m, i__1 = max(i__1,i__2), i__2 = *m * 3 + wlalsd; minwrk = max(i__1,i__2); } minwrk = min(minwrk,maxwrk); work[1] = (real) maxwrk; if (*lwork < minwrk && ! lquery) { *info = -12; } } if (*info != 0) { i__1 = -(*info); xerbla_("SGELSD", &i__1); return 0; } else if (lquery) { goto L10; } /* Quick return if possible. */ if ((*m == 0) || (*n == 0)) { *rank = 0; return 0; } /* Get machine parameters. */ eps = slamch_("P"); sfmin = slamch_("S"); smlnum = sfmin / eps; bignum = 1.f / smlnum; slabad_(&smlnum, &bignum); /* Scale A if max entry outside range [SMLNUM,BIGNUM]. */ anrm = slange_("M", m, n, &a[a_offset], lda, &work[1]); iascl = 0; if (anrm > 0.f && anrm < smlnum) { /* Scale matrix norm up to SMLNUM. */ slascl_("G", &c__0, &c__0, &anrm, &smlnum, m, n, &a[a_offset], lda, info); iascl = 1; } else if (anrm > bignum) { /* Scale matrix norm down to BIGNUM. */ slascl_("G", &c__0, &c__0, &anrm, &bignum, m, n, &a[a_offset], lda, info); iascl = 2; } else if (anrm == 0.f) { /* Matrix all zero. Return zero solution. */ i__1 = max(*m,*n); slaset_("F", &i__1, nrhs, &c_b320, &c_b320, &b[b_offset], ldb); slaset_("F", &minmn, &c__1, &c_b320, &c_b320, &s[1], &c__1) ; *rank = 0; goto L10; } /* Scale B if max entry outside range [SMLNUM,BIGNUM]. */ bnrm = slange_("M", m, nrhs, &b[b_offset], ldb, &work[1]); ibscl = 0; if (bnrm > 0.f && bnrm < smlnum) { /* Scale matrix norm up to SMLNUM. */ slascl_("G", &c__0, &c__0, &bnrm, &smlnum, m, nrhs, &b[b_offset], ldb, info); ibscl = 1; } else if (bnrm > bignum) { /* Scale matrix norm down to BIGNUM. */ slascl_("G", &c__0, &c__0, &bnrm, &bignum, m, nrhs, &b[b_offset], ldb, info); ibscl = 2; } /* If M < N make sure certain entries of B are zero. */ if (*m < *n) { i__1 = *n - *m; slaset_("F", &i__1, nrhs, &c_b320, &c_b320, &b[*m + 1 + b_dim1], ldb); } /* Overdetermined case. */ if (*m >= *n) { /* Path 1 - overdetermined or exactly determined. */ mm = *m; if (*m >= mnthr) { /* Path 1a - overdetermined, with many more rows than columns. */ mm = *n; itau = 1; nwork = itau + *n; /* Compute A=Q*R. (Workspace: need 2*N, prefer N+N*NB) */ i__1 = *lwork - nwork + 1; sgeqrf_(m, n, &a[a_offset], lda, &work[itau], &work[nwork], &i__1, info); /* Multiply B by transpose(Q). (Workspace: need N+NRHS, prefer N+NRHS*NB) */ i__1 = *lwork - nwork + 1; sormqr_("L", "T", m, nrhs, n, &a[a_offset], lda, &work[itau], &b[ b_offset], ldb, &work[nwork], &i__1, info); /* Zero out below R. */ if (*n > 1) { i__1 = *n - 1; i__2 = *n - 1; slaset_("L", &i__1, &i__2, &c_b320, &c_b320, &a[a_dim1 + 2], lda); } } ie = 1; itauq = ie + *n; itaup = itauq + *n; nwork = itaup + *n; /* Bidiagonalize R in A. (Workspace: need 3*N+MM, prefer 3*N+(MM+N)*NB) */ i__1 = *lwork - nwork + 1; sgebrd_(&mm, n, &a[a_offset], lda, &s[1], &work[ie], &work[itauq], & work[itaup], &work[nwork], &i__1, info); /* Multiply B by transpose of left bidiagonalizing vectors of R. (Workspace: need 3*N+NRHS, prefer 3*N+NRHS*NB) */ i__1 = *lwork - nwork + 1; sormbr_("Q", "L", "T", &mm, nrhs, n, &a[a_offset], lda, &work[itauq], &b[b_offset], ldb, &work[nwork], &i__1, info); /* Solve the bidiagonal least squares problem. */ slalsd_("U", &smlsiz, n, nrhs, &s[1], &work[ie], &b[b_offset], ldb, rcond, rank, &work[nwork], &iwork[1], info); if (*info != 0) { goto L10; } /* Multiply B by right bidiagonalizing vectors of R. */ i__1 = *lwork - nwork + 1; sormbr_("P", "L", "N", n, nrhs, n, &a[a_offset], lda, &work[itaup], & b[b_offset], ldb, &work[nwork], &i__1, info); } else /* if(complicated condition) */ { /* Computing MAX */ i__1 = *m, i__2 = ((*m) << (1)) - 4, i__1 = max(i__1,i__2), i__1 = max(i__1,*nrhs), i__2 = *n - *m * 3; if (*n >= mnthr && *lwork >= ((*m) << (2)) + *m * *m + max(i__1,i__2)) { /* Path 2a - underdetermined, with many more columns than rows and sufficient workspace for an efficient algorithm. */ ldwork = *m; /* Computing MAX Computing MAX */ i__3 = *m, i__4 = ((*m) << (1)) - 4, i__3 = max(i__3,i__4), i__3 = max(i__3,*nrhs), i__4 = *n - *m * 3; i__1 = ((*m) << (2)) + *m * *lda + max(i__3,i__4), i__2 = *m * * lda + *m + *m * *nrhs; if (*lwork >= max(i__1,i__2)) { ldwork = *lda; } itau = 1; nwork = *m + 1; /* Compute A=L*Q. (Workspace: need 2*M, prefer M+M*NB) */ i__1 = *lwork - nwork + 1; sgelqf_(m, n, &a[a_offset], lda, &work[itau], &work[nwork], &i__1, info); il = nwork; /* Copy L to WORK(IL), zeroing out above its diagonal. */ slacpy_("L", m, m, &a[a_offset], lda, &work[il], &ldwork); i__1 = *m - 1; i__2 = *m - 1; slaset_("U", &i__1, &i__2, &c_b320, &c_b320, &work[il + ldwork], & ldwork); ie = il + ldwork * *m; itauq = ie + *m; itaup = itauq + *m; nwork = itaup + *m; /* Bidiagonalize L in WORK(IL). (Workspace: need M*M+5*M, prefer M*M+4*M+2*M*NB) */ i__1 = *lwork - nwork + 1; sgebrd_(m, m, &work[il], &ldwork, &s[1], &work[ie], &work[itauq], &work[itaup], &work[nwork], &i__1, info); /* Multiply B by transpose of left bidiagonalizing vectors of L. (Workspace: need M*M+4*M+NRHS, prefer M*M+4*M+NRHS*NB) */ i__1 = *lwork - nwork + 1; sormbr_("Q", "L", "T", m, nrhs, m, &work[il], &ldwork, &work[ itauq], &b[b_offset], ldb, &work[nwork], &i__1, info); /* Solve the bidiagonal least squares problem. */ slalsd_("U", &smlsiz, m, nrhs, &s[1], &work[ie], &b[b_offset], ldb, rcond, rank, &work[nwork], &iwork[1], info); if (*info != 0) { goto L10; } /* Multiply B by right bidiagonalizing vectors of L. */ i__1 = *lwork - nwork + 1; sormbr_("P", "L", "N", m, nrhs, m, &work[il], &ldwork, &work[ itaup], &b[b_offset], ldb, &work[nwork], &i__1, info); /* Zero out below first M rows of B. */ i__1 = *n - *m; slaset_("F", &i__1, nrhs, &c_b320, &c_b320, &b[*m + 1 + b_dim1], ldb); nwork = itau + *m; /* Multiply transpose(Q) by B. (Workspace: need M+NRHS, prefer M+NRHS*NB) */ i__1 = *lwork - nwork + 1; sormlq_("L", "T", n, nrhs, m, &a[a_offset], lda, &work[itau], &b[ b_offset], ldb, &work[nwork], &i__1, info); } else { /* Path 2 - remaining underdetermined cases. */ ie = 1; itauq = ie + *m; itaup = itauq + *m; nwork = itaup + *m; /* Bidiagonalize A. (Workspace: need 3*M+N, prefer 3*M+(M+N)*NB) */ i__1 = *lwork - nwork + 1; sgebrd_(m, n, &a[a_offset], lda, &s[1], &work[ie], &work[itauq], & work[itaup], &work[nwork], &i__1, info); /* Multiply B by transpose of left bidiagonalizing vectors. (Workspace: need 3*M+NRHS, prefer 3*M+NRHS*NB) */ i__1 = *lwork - nwork + 1; sormbr_("Q", "L", "T", m, nrhs, n, &a[a_offset], lda, &work[itauq] , &b[b_offset], ldb, &work[nwork], &i__1, info); /* Solve the bidiagonal least squares problem. */ slalsd_("L", &smlsiz, m, nrhs, &s[1], &work[ie], &b[b_offset], ldb, rcond, rank, &work[nwork], &iwork[1], info); if (*info != 0) { goto L10; } /* Multiply B by right bidiagonalizing vectors of A. */ i__1 = *lwork - nwork + 1; sormbr_("P", "L", "N", n, nrhs, m, &a[a_offset], lda, &work[itaup] , &b[b_offset], ldb, &work[nwork], &i__1, info); } } /* Undo scaling. */ if (iascl == 1) { slascl_("G", &c__0, &c__0, &anrm, &smlnum, n, nrhs, &b[b_offset], ldb, info); slascl_("G", &c__0, &c__0, &smlnum, &anrm, &minmn, &c__1, &s[1], & minmn, info); } else if (iascl == 2) { slascl_("G", &c__0, &c__0, &anrm, &bignum, n, nrhs, &b[b_offset], ldb, info); slascl_("G", &c__0, &c__0, &bignum, &anrm, &minmn, &c__1, &s[1], & minmn, info); } if (ibscl == 1) { slascl_("G", &c__0, &c__0, &smlnum, &bnrm, n, nrhs, &b[b_offset], ldb, info); } else if (ibscl == 2) { slascl_("G", &c__0, &c__0, &bignum, &bnrm, n, nrhs, &b[b_offset], ldb, info); } L10: work[1] = (real) maxwrk; return 0; /* End of SGELSD */ } /* sgelsd_ */ /* Subroutine */ int sgeqr2_(integer *m, integer *n, real *a, integer *lda, real *tau, real *work, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3; /* Local variables */ static integer i__, k; static real aii; extern /* Subroutine */ int slarf_(char *, integer *, integer *, real *, integer *, real *, real *, integer *, real *), xerbla_( char *, integer *), slarfg_(integer *, real *, real *, integer *, real *); /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University February 29, 1992 Purpose ======= SGEQR2 computes a QR factorization of a real m by n matrix A: A = Q * R. Arguments ========= M (input) INTEGER The number of rows of the matrix A. M >= 0. N (input) INTEGER The number of columns of the matrix A. N >= 0. A (input/output) REAL array, dimension (LDA,N) On entry, the m by n matrix A. On exit, the elements on and above the diagonal of the array contain the min(m,n) by n upper trapezoidal matrix R (R is upper triangular if m >= n); the elements below the diagonal, with the array TAU, represent the orthogonal matrix Q as a product of elementary reflectors (see Further Details). LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,M). TAU (output) REAL array, dimension (min(M,N)) The scalar factors of the elementary reflectors (see Further Details). WORK (workspace) REAL array, dimension (N) INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value Further Details =============== The matrix Q is represented as a product of elementary reflectors Q = H(1) H(2) . . . H(k), where k = min(m,n). Each H(i) has the form H(i) = I - tau * v * v' where tau is a real scalar, and v is a real vector with v(1:i-1) = 0 and v(i) = 1; v(i+1:m) is stored on exit in A(i+1:m,i), and tau in TAU(i). ===================================================================== Test the input arguments */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --tau; --work; /* Function Body */ *info = 0; if (*m < 0) { *info = -1; } else if (*n < 0) { *info = -2; } else if (*lda < max(1,*m)) { *info = -4; } if (*info != 0) { i__1 = -(*info); xerbla_("SGEQR2", &i__1); return 0; } k = min(*m,*n); i__1 = k; for (i__ = 1; i__ <= i__1; ++i__) { /* Generate elementary reflector H(i) to annihilate A(i+1:m,i) */ i__2 = *m - i__ + 1; /* Computing MIN */ i__3 = i__ + 1; slarfg_(&i__2, &a[i__ + i__ * a_dim1], &a[min(i__3,*m) + i__ * a_dim1] , &c__1, &tau[i__]); if (i__ < *n) { /* Apply H(i) to A(i:m,i+1:n) from the left */ aii = a[i__ + i__ * a_dim1]; a[i__ + i__ * a_dim1] = 1.f; i__2 = *m - i__ + 1; i__3 = *n - i__; slarf_("Left", &i__2, &i__3, &a[i__ + i__ * a_dim1], &c__1, &tau[ i__], &a[i__ + (i__ + 1) * a_dim1], lda, &work[1]); a[i__ + i__ * a_dim1] = aii; } /* L10: */ } return 0; /* End of SGEQR2 */ } /* sgeqr2_ */ /* Subroutine */ int sgeqrf_(integer *m, integer *n, real *a, integer *lda, real *tau, real *work, integer *lwork, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3, i__4; /* Local variables */ static integer i__, k, ib, nb, nx, iws, nbmin, iinfo; extern /* Subroutine */ int sgeqr2_(integer *, integer *, real *, integer *, real *, real *, integer *), slarfb_(char *, char *, char *, char *, integer *, integer *, integer *, real *, integer *, real * , integer *, real *, integer *, real *, integer *), xerbla_(char *, integer *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); extern /* Subroutine */ int slarft_(char *, char *, integer *, integer *, real *, integer *, real *, real *, integer *); static integer ldwork, lwkopt; static logical lquery; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= SGEQRF computes a QR factorization of a real M-by-N matrix A: A = Q * R. Arguments ========= M (input) INTEGER The number of rows of the matrix A. M >= 0. N (input) INTEGER The number of columns of the matrix A. N >= 0. A (input/output) REAL array, dimension (LDA,N) On entry, the M-by-N matrix A. On exit, the elements on and above the diagonal of the array contain the min(M,N)-by-N upper trapezoidal matrix R (R is upper triangular if m >= n); the elements below the diagonal, with the array TAU, represent the orthogonal matrix Q as a product of min(m,n) elementary reflectors (see Further Details). LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,M). TAU (output) REAL array, dimension (min(M,N)) The scalar factors of the elementary reflectors (see Further Details). WORK (workspace/output) REAL array, dimension (LWORK) On exit, if INFO = 0, WORK(1) returns the optimal LWORK. LWORK (input) INTEGER The dimension of the array WORK. LWORK >= max(1,N). For optimum performance LWORK >= N*NB, where NB is the optimal blocksize. If LWORK = -1, then a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued by XERBLA. INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value Further Details =============== The matrix Q is represented as a product of elementary reflectors Q = H(1) H(2) . . . H(k), where k = min(m,n). Each H(i) has the form H(i) = I - tau * v * v' where tau is a real scalar, and v is a real vector with v(1:i-1) = 0 and v(i) = 1; v(i+1:m) is stored on exit in A(i+1:m,i), and tau in TAU(i). ===================================================================== Test the input arguments */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --tau; --work; /* Function Body */ *info = 0; nb = ilaenv_(&c__1, "SGEQRF", " ", m, n, &c_n1, &c_n1, (ftnlen)6, (ftnlen) 1); lwkopt = *n * nb; work[1] = (real) lwkopt; lquery = *lwork == -1; if (*m < 0) { *info = -1; } else if (*n < 0) { *info = -2; } else if (*lda < max(1,*m)) { *info = -4; } else if (*lwork < max(1,*n) && ! lquery) { *info = -7; } if (*info != 0) { i__1 = -(*info); xerbla_("SGEQRF", &i__1); return 0; } else if (lquery) { return 0; } /* Quick return if possible */ k = min(*m,*n); if (k == 0) { work[1] = 1.f; return 0; } nbmin = 2; nx = 0; iws = *n; if (nb > 1 && nb < k) { /* Determine when to cross over from blocked to unblocked code. Computing MAX */ i__1 = 0, i__2 = ilaenv_(&c__3, "SGEQRF", " ", m, n, &c_n1, &c_n1, ( ftnlen)6, (ftnlen)1); nx = max(i__1,i__2); if (nx < k) { /* Determine if workspace is large enough for blocked code. */ ldwork = *n; iws = ldwork * nb; if (*lwork < iws) { /* Not enough workspace to use optimal NB: reduce NB and determine the minimum value of NB. */ nb = *lwork / ldwork; /* Computing MAX */ i__1 = 2, i__2 = ilaenv_(&c__2, "SGEQRF", " ", m, n, &c_n1, & c_n1, (ftnlen)6, (ftnlen)1); nbmin = max(i__1,i__2); } } } if (nb >= nbmin && nb < k && nx < k) { /* Use blocked code initially */ i__1 = k - nx; i__2 = nb; for (i__ = 1; i__2 < 0 ? i__ >= i__1 : i__ <= i__1; i__ += i__2) { /* Computing MIN */ i__3 = k - i__ + 1; ib = min(i__3,nb); /* Compute the QR factorization of the current block A(i:m,i:i+ib-1) */ i__3 = *m - i__ + 1; sgeqr2_(&i__3, &ib, &a[i__ + i__ * a_dim1], lda, &tau[i__], &work[ 1], &iinfo); if (i__ + ib <= *n) { /* Form the triangular factor of the block reflector H = H(i) H(i+1) . . . H(i+ib-1) */ i__3 = *m - i__ + 1; slarft_("Forward", "Columnwise", &i__3, &ib, &a[i__ + i__ * a_dim1], lda, &tau[i__], &work[1], &ldwork); /* Apply H' to A(i:m,i+ib:n) from the left */ i__3 = *m - i__ + 1; i__4 = *n - i__ - ib + 1; slarfb_("Left", "Transpose", "Forward", "Columnwise", &i__3, & i__4, &ib, &a[i__ + i__ * a_dim1], lda, &work[1], & ldwork, &a[i__ + (i__ + ib) * a_dim1], lda, &work[ib + 1], &ldwork); } /* L10: */ } } else { i__ = 1; } /* Use unblocked code to factor the last or only block. */ if (i__ <= k) { i__2 = *m - i__ + 1; i__1 = *n - i__ + 1; sgeqr2_(&i__2, &i__1, &a[i__ + i__ * a_dim1], lda, &tau[i__], &work[1] , &iinfo); } work[1] = (real) iws; return 0; /* End of SGEQRF */ } /* sgeqrf_ */ /* Subroutine */ int sgesdd_(char *jobz, integer *m, integer *n, real *a, integer *lda, real *s, real *u, integer *ldu, real *vt, integer *ldvt, real *work, integer *lwork, integer *iwork, integer *info) { /* System generated locals */ integer a_dim1, a_offset, u_dim1, u_offset, vt_dim1, vt_offset, i__1, i__2, i__3; /* Builtin functions */ double sqrt(doublereal); /* Local variables */ static integer i__, ie, il, ir, iu, blk; static real dum[1], eps; static integer ivt, iscl; static real anrm; static integer idum[1], ierr, itau; extern logical lsame_(char *, char *); static integer chunk; extern /* Subroutine */ int sgemm_(char *, char *, integer *, integer *, integer *, real *, real *, integer *, real *, integer *, real *, real *, integer *); static integer minmn, wrkbl, itaup, itauq, mnthr; static logical wntqa; static integer nwork; static logical wntqn, wntqo, wntqs; static integer bdspac; extern /* Subroutine */ int sbdsdc_(char *, char *, integer *, real *, real *, real *, integer *, real *, integer *, real *, integer *, real *, integer *, integer *), sgebrd_(integer *, integer *, real *, integer *, real *, real *, real *, real *, real *, integer *, integer *); extern doublereal slamch_(char *), slange_(char *, integer *, integer *, real *, integer *, real *); extern /* Subroutine */ int xerbla_(char *, integer *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); static real bignum; extern /* Subroutine */ int sgelqf_(integer *, integer *, real *, integer *, real *, real *, integer *, integer *), slascl_(char *, integer *, integer *, real *, real *, integer *, integer *, real *, integer *, integer *), sgeqrf_(integer *, integer *, real *, integer *, real *, real *, integer *, integer *), slacpy_(char *, integer *, integer *, real *, integer *, real *, integer *), slaset_(char *, integer *, integer *, real *, real *, real *, integer *), sorgbr_(char *, integer *, integer *, integer *, real *, integer *, real *, real *, integer *, integer * ); static integer ldwrkl; extern /* Subroutine */ int sormbr_(char *, char *, char *, integer *, integer *, integer *, real *, integer *, real *, real *, integer * , real *, integer *, integer *); static integer ldwrkr, minwrk, ldwrku, maxwrk; extern /* Subroutine */ int sorglq_(integer *, integer *, integer *, real *, integer *, real *, real *, integer *, integer *); static integer ldwkvt; static real smlnum; static logical wntqas; extern /* Subroutine */ int sorgqr_(integer *, integer *, integer *, real *, integer *, real *, real *, integer *, integer *); static logical lquery; /* -- LAPACK driver routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University October 31, 1999 Purpose ======= SGESDD computes the singular value decomposition (SVD) of a real M-by-N matrix A, optionally computing the left and right singular vectors. If singular vectors are desired, it uses a divide-and-conquer algorithm. The SVD is written A = U * SIGMA * transpose(V) where SIGMA is an M-by-N matrix which is zero except for its min(m,n) diagonal elements, U is an M-by-M orthogonal matrix, and V is an N-by-N orthogonal matrix. The diagonal elements of SIGMA are the singular values of A; they are real and non-negative, and are returned in descending order. The first min(m,n) columns of U and V are the left and right singular vectors of A. Note that the routine returns VT = V**T, not V. The divide and conquer algorithm makes very mild assumptions about floating point arithmetic. It will work on machines with a guard digit in add/subtract, or on those binary machines without guard digits which subtract like the Cray X-MP, Cray Y-MP, Cray C-90, or Cray-2. It could conceivably fail on hexadecimal or decimal machines without guard digits, but we know of none. Arguments ========= JOBZ (input) CHARACTER*1 Specifies options for computing all or part of the matrix U: = 'A': all M columns of U and all N rows of V**T are returned in the arrays U and VT; = 'S': the first min(M,N) columns of U and the first min(M,N) rows of V**T are returned in the arrays U and VT; = 'O': If M >= N, the first N columns of U are overwritten on the array A and all rows of V**T are returned in the array VT; otherwise, all columns of U are returned in the array U and the first M rows of V**T are overwritten in the array VT; = 'N': no columns of U or rows of V**T are computed. M (input) INTEGER The number of rows of the input matrix A. M >= 0. N (input) INTEGER The number of columns of the input matrix A. N >= 0. A (input/output) REAL array, dimension (LDA,N) On entry, the M-by-N matrix A. On exit, if JOBZ = 'O', A is overwritten with the first N columns of U (the left singular vectors, stored columnwise) if M >= N; A is overwritten with the first M rows of V**T (the right singular vectors, stored rowwise) otherwise. if JOBZ .ne. 'O', the contents of A are destroyed. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,M). S (output) REAL array, dimension (min(M,N)) The singular values of A, sorted so that S(i) >= S(i+1). U (output) REAL array, dimension (LDU,UCOL) UCOL = M if JOBZ = 'A' or JOBZ = 'O' and M < N; UCOL = min(M,N) if JOBZ = 'S'. If JOBZ = 'A' or JOBZ = 'O' and M < N, U contains the M-by-M orthogonal matrix U; if JOBZ = 'S', U contains the first min(M,N) columns of U (the left singular vectors, stored columnwise); if JOBZ = 'O' and M >= N, or JOBZ = 'N', U is not referenced. LDU (input) INTEGER The leading dimension of the array U. LDU >= 1; if JOBZ = 'S' or 'A' or JOBZ = 'O' and M < N, LDU >= M. VT (output) REAL array, dimension (LDVT,N) If JOBZ = 'A' or JOBZ = 'O' and M >= N, VT contains the N-by-N orthogonal matrix V**T; if JOBZ = 'S', VT contains the first min(M,N) rows of V**T (the right singular vectors, stored rowwise); if JOBZ = 'O' and M < N, or JOBZ = 'N', VT is not referenced. LDVT (input) INTEGER The leading dimension of the array VT. LDVT >= 1; if JOBZ = 'A' or JOBZ = 'O' and M >= N, LDVT >= N; if JOBZ = 'S', LDVT >= min(M,N). WORK (workspace/output) REAL array, dimension (LWORK) On exit, if INFO = 0, WORK(1) returns the optimal LWORK; LWORK (input) INTEGER The dimension of the array WORK. LWORK >= 1. If JOBZ = 'N', LWORK >= 3*min(M,N) + max(max(M,N),6*min(M,N)). If JOBZ = 'O', LWORK >= 3*min(M,N)*min(M,N) + max(max(M,N),5*min(M,N)*min(M,N)+4*min(M,N)). If JOBZ = 'S' or 'A' LWORK >= 3*min(M,N)*min(M,N) + max(max(M,N),4*min(M,N)*min(M,N)+4*min(M,N)). For good performance, LWORK should generally be larger. If LWORK < 0 but other input arguments are legal, WORK(1) returns the optimal LWORK. IWORK (workspace) INTEGER array, dimension (8*min(M,N)) INFO (output) INTEGER = 0: successful exit. < 0: if INFO = -i, the i-th argument had an illegal value. > 0: SBDSDC did not converge, updating process failed. Further Details =============== Based on contributions by Ming Gu and Huan Ren, Computer Science Division, University of California at Berkeley, USA ===================================================================== Test the input arguments */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --s; u_dim1 = *ldu; u_offset = 1 + u_dim1; u -= u_offset; vt_dim1 = *ldvt; vt_offset = 1 + vt_dim1; vt -= vt_offset; --work; --iwork; /* Function Body */ *info = 0; minmn = min(*m,*n); mnthr = (integer) (minmn * 11.f / 6.f); wntqa = lsame_(jobz, "A"); wntqs = lsame_(jobz, "S"); wntqas = (wntqa) || (wntqs); wntqo = lsame_(jobz, "O"); wntqn = lsame_(jobz, "N"); minwrk = 1; maxwrk = 1; lquery = *lwork == -1; if (! ((((wntqa) || (wntqs)) || (wntqo)) || (wntqn))) { *info = -1; } else if (*m < 0) { *info = -2; } else if (*n < 0) { *info = -3; } else if (*lda < max(1,*m)) { *info = -5; } else if (((*ldu < 1) || (wntqas && *ldu < *m)) || (wntqo && *m < *n && * ldu < *m)) { *info = -8; } else if ((((*ldvt < 1) || (wntqa && *ldvt < *n)) || (wntqs && *ldvt < minmn)) || (wntqo && *m >= *n && *ldvt < *n)) { *info = -10; } /* Compute workspace (Note: Comments in the code beginning "Workspace:" describe the minimal amount of workspace needed at that point in the code, as well as the preferred amount for good performance. NB refers to the optimal block size for the immediately following subroutine, as returned by ILAENV.) */ if (*info == 0 && *m > 0 && *n > 0) { if (*m >= *n) { /* Compute space needed for SBDSDC */ if (wntqn) { bdspac = *n * 7; } else { bdspac = *n * 3 * *n + ((*n) << (2)); } if (*m >= mnthr) { if (wntqn) { /* Path 1 (M much larger than N, JOBZ='N') */ wrkbl = *n + *n * ilaenv_(&c__1, "SGEQRF", " ", m, n, & c_n1, &c_n1, (ftnlen)6, (ftnlen)1); /* Computing MAX */ i__1 = wrkbl, i__2 = *n * 3 + ((*n) << (1)) * ilaenv_(& c__1, "SGEBRD", " ", n, n, &c_n1, &c_n1, (ftnlen) 6, (ftnlen)1); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = bdspac + *n; maxwrk = max(i__1,i__2); minwrk = bdspac + *n; } else if (wntqo) { /* Path 2 (M much larger than N, JOBZ='O') */ wrkbl = *n + *n * ilaenv_(&c__1, "SGEQRF", " ", m, n, & c_n1, &c_n1, (ftnlen)6, (ftnlen)1); /* Computing MAX */ i__1 = wrkbl, i__2 = *n + *n * ilaenv_(&c__1, "SORGQR", " ", m, n, n, &c_n1, (ftnlen)6, (ftnlen)1); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = *n * 3 + ((*n) << (1)) * ilaenv_(& c__1, "SGEBRD", " ", n, n, &c_n1, &c_n1, (ftnlen) 6, (ftnlen)1); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = *n * 3 + *n * ilaenv_(&c__1, "SORMBR" , "QLN", n, n, n, &c_n1, (ftnlen)6, (ftnlen)3); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = *n * 3 + *n * ilaenv_(&c__1, "SORMBR" , "PRT", n, n, n, &c_n1, (ftnlen)6, (ftnlen)3); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = bdspac + *n * 3; wrkbl = max(i__1,i__2); maxwrk = wrkbl + ((*n) << (1)) * *n; minwrk = bdspac + ((*n) << (1)) * *n + *n * 3; } else if (wntqs) { /* Path 3 (M much larger than N, JOBZ='S') */ wrkbl = *n + *n * ilaenv_(&c__1, "SGEQRF", " ", m, n, & c_n1, &c_n1, (ftnlen)6, (ftnlen)1); /* Computing MAX */ i__1 = wrkbl, i__2 = *n + *n * ilaenv_(&c__1, "SORGQR", " ", m, n, n, &c_n1, (ftnlen)6, (ftnlen)1); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = *n * 3 + ((*n) << (1)) * ilaenv_(& c__1, "SGEBRD", " ", n, n, &c_n1, &c_n1, (ftnlen) 6, (ftnlen)1); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = *n * 3 + *n * ilaenv_(&c__1, "SORMBR" , "QLN", n, n, n, &c_n1, (ftnlen)6, (ftnlen)3); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = *n * 3 + *n * ilaenv_(&c__1, "SORMBR" , "PRT", n, n, n, &c_n1, (ftnlen)6, (ftnlen)3); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = bdspac + *n * 3; wrkbl = max(i__1,i__2); maxwrk = wrkbl + *n * *n; minwrk = bdspac + *n * *n + *n * 3; } else if (wntqa) { /* Path 4 (M much larger than N, JOBZ='A') */ wrkbl = *n + *n * ilaenv_(&c__1, "SGEQRF", " ", m, n, & c_n1, &c_n1, (ftnlen)6, (ftnlen)1); /* Computing MAX */ i__1 = wrkbl, i__2 = *n + *m * ilaenv_(&c__1, "SORGQR", " ", m, m, n, &c_n1, (ftnlen)6, (ftnlen)1); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = *n * 3 + ((*n) << (1)) * ilaenv_(& c__1, "SGEBRD", " ", n, n, &c_n1, &c_n1, (ftnlen) 6, (ftnlen)1); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = *n * 3 + *n * ilaenv_(&c__1, "SORMBR" , "QLN", n, n, n, &c_n1, (ftnlen)6, (ftnlen)3); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = *n * 3 + *n * ilaenv_(&c__1, "SORMBR" , "PRT", n, n, n, &c_n1, (ftnlen)6, (ftnlen)3); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = bdspac + *n * 3; wrkbl = max(i__1,i__2); maxwrk = wrkbl + *n * *n; minwrk = bdspac + *n * *n + *n * 3; } } else { /* Path 5 (M at least N, but not much larger) */ wrkbl = *n * 3 + (*m + *n) * ilaenv_(&c__1, "SGEBRD", " ", m, n, &c_n1, &c_n1, (ftnlen)6, (ftnlen)1); if (wntqn) { /* Computing MAX */ i__1 = wrkbl, i__2 = bdspac + *n * 3; maxwrk = max(i__1,i__2); minwrk = *n * 3 + max(*m,bdspac); } else if (wntqo) { /* Computing MAX */ i__1 = wrkbl, i__2 = *n * 3 + *n * ilaenv_(&c__1, "SORMBR" , "QLN", m, n, n, &c_n1, (ftnlen)6, (ftnlen)3); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = *n * 3 + *n * ilaenv_(&c__1, "SORMBR" , "PRT", n, n, n, &c_n1, (ftnlen)6, (ftnlen)3); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = bdspac + *n * 3; wrkbl = max(i__1,i__2); maxwrk = wrkbl + *m * *n; /* Computing MAX */ i__1 = *m, i__2 = *n * *n + bdspac; minwrk = *n * 3 + max(i__1,i__2); } else if (wntqs) { /* Computing MAX */ i__1 = wrkbl, i__2 = *n * 3 + *n * ilaenv_(&c__1, "SORMBR" , "QLN", m, n, n, &c_n1, (ftnlen)6, (ftnlen)3); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = *n * 3 + *n * ilaenv_(&c__1, "SORMBR" , "PRT", n, n, n, &c_n1, (ftnlen)6, (ftnlen)3); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = bdspac + *n * 3; maxwrk = max(i__1,i__2); minwrk = *n * 3 + max(*m,bdspac); } else if (wntqa) { /* Computing MAX */ i__1 = wrkbl, i__2 = *n * 3 + *m * ilaenv_(&c__1, "SORMBR" , "QLN", m, m, n, &c_n1, (ftnlen)6, (ftnlen)3); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = *n * 3 + *n * ilaenv_(&c__1, "SORMBR" , "PRT", n, n, n, &c_n1, (ftnlen)6, (ftnlen)3); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = maxwrk, i__2 = bdspac + *n * 3; maxwrk = max(i__1,i__2); minwrk = *n * 3 + max(*m,bdspac); } } } else { /* Compute space needed for SBDSDC */ if (wntqn) { bdspac = *m * 7; } else { bdspac = *m * 3 * *m + ((*m) << (2)); } if (*n >= mnthr) { if (wntqn) { /* Path 1t (N much larger than M, JOBZ='N') */ wrkbl = *m + *m * ilaenv_(&c__1, "SGELQF", " ", m, n, & c_n1, &c_n1, (ftnlen)6, (ftnlen)1); /* Computing MAX */ i__1 = wrkbl, i__2 = *m * 3 + ((*m) << (1)) * ilaenv_(& c__1, "SGEBRD", " ", m, m, &c_n1, &c_n1, (ftnlen) 6, (ftnlen)1); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = bdspac + *m; maxwrk = max(i__1,i__2); minwrk = bdspac + *m; } else if (wntqo) { /* Path 2t (N much larger than M, JOBZ='O') */ wrkbl = *m + *m * ilaenv_(&c__1, "SGELQF", " ", m, n, & c_n1, &c_n1, (ftnlen)6, (ftnlen)1); /* Computing MAX */ i__1 = wrkbl, i__2 = *m + *m * ilaenv_(&c__1, "SORGLQ", " ", m, n, m, &c_n1, (ftnlen)6, (ftnlen)1); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = *m * 3 + ((*m) << (1)) * ilaenv_(& c__1, "SGEBRD", " ", m, m, &c_n1, &c_n1, (ftnlen) 6, (ftnlen)1); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = *m * 3 + *m * ilaenv_(&c__1, "SORMBR" , "QLN", m, m, m, &c_n1, (ftnlen)6, (ftnlen)3); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = *m * 3 + *m * ilaenv_(&c__1, "SORMBR" , "PRT", m, m, m, &c_n1, (ftnlen)6, (ftnlen)3); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = bdspac + *m * 3; wrkbl = max(i__1,i__2); maxwrk = wrkbl + ((*m) << (1)) * *m; minwrk = bdspac + ((*m) << (1)) * *m + *m * 3; } else if (wntqs) { /* Path 3t (N much larger than M, JOBZ='S') */ wrkbl = *m + *m * ilaenv_(&c__1, "SGELQF", " ", m, n, & c_n1, &c_n1, (ftnlen)6, (ftnlen)1); /* Computing MAX */ i__1 = wrkbl, i__2 = *m + *m * ilaenv_(&c__1, "SORGLQ", " ", m, n, m, &c_n1, (ftnlen)6, (ftnlen)1); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = *m * 3 + ((*m) << (1)) * ilaenv_(& c__1, "SGEBRD", " ", m, m, &c_n1, &c_n1, (ftnlen) 6, (ftnlen)1); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = *m * 3 + *m * ilaenv_(&c__1, "SORMBR" , "QLN", m, m, m, &c_n1, (ftnlen)6, (ftnlen)3); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = *m * 3 + *m * ilaenv_(&c__1, "SORMBR" , "PRT", m, m, m, &c_n1, (ftnlen)6, (ftnlen)3); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = bdspac + *m * 3; wrkbl = max(i__1,i__2); maxwrk = wrkbl + *m * *m; minwrk = bdspac + *m * *m + *m * 3; } else if (wntqa) { /* Path 4t (N much larger than M, JOBZ='A') */ wrkbl = *m + *m * ilaenv_(&c__1, "SGELQF", " ", m, n, & c_n1, &c_n1, (ftnlen)6, (ftnlen)1); /* Computing MAX */ i__1 = wrkbl, i__2 = *m + *n * ilaenv_(&c__1, "SORGLQ", " ", n, n, m, &c_n1, (ftnlen)6, (ftnlen)1); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = *m * 3 + ((*m) << (1)) * ilaenv_(& c__1, "SGEBRD", " ", m, m, &c_n1, &c_n1, (ftnlen) 6, (ftnlen)1); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = *m * 3 + *m * ilaenv_(&c__1, "SORMBR" , "QLN", m, m, m, &c_n1, (ftnlen)6, (ftnlen)3); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = *m * 3 + *m * ilaenv_(&c__1, "SORMBR" , "PRT", m, m, m, &c_n1, (ftnlen)6, (ftnlen)3); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = bdspac + *m * 3; wrkbl = max(i__1,i__2); maxwrk = wrkbl + *m * *m; minwrk = bdspac + *m * *m + *m * 3; } } else { /* Path 5t (N greater than M, but not much larger) */ wrkbl = *m * 3 + (*m + *n) * ilaenv_(&c__1, "SGEBRD", " ", m, n, &c_n1, &c_n1, (ftnlen)6, (ftnlen)1); if (wntqn) { /* Computing MAX */ i__1 = wrkbl, i__2 = bdspac + *m * 3; maxwrk = max(i__1,i__2); minwrk = *m * 3 + max(*n,bdspac); } else if (wntqo) { /* Computing MAX */ i__1 = wrkbl, i__2 = *m * 3 + *m * ilaenv_(&c__1, "SORMBR" , "QLN", m, m, n, &c_n1, (ftnlen)6, (ftnlen)3); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = *m * 3 + *m * ilaenv_(&c__1, "SORMBR" , "PRT", m, n, m, &c_n1, (ftnlen)6, (ftnlen)3); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = bdspac + *m * 3; wrkbl = max(i__1,i__2); maxwrk = wrkbl + *m * *n; /* Computing MAX */ i__1 = *n, i__2 = *m * *m + bdspac; minwrk = *m * 3 + max(i__1,i__2); } else if (wntqs) { /* Computing MAX */ i__1 = wrkbl, i__2 = *m * 3 + *m * ilaenv_(&c__1, "SORMBR" , "QLN", m, m, n, &c_n1, (ftnlen)6, (ftnlen)3); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = *m * 3 + *m * ilaenv_(&c__1, "SORMBR" , "PRT", m, n, m, &c_n1, (ftnlen)6, (ftnlen)3); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = bdspac + *m * 3; maxwrk = max(i__1,i__2); minwrk = *m * 3 + max(*n,bdspac); } else if (wntqa) { /* Computing MAX */ i__1 = wrkbl, i__2 = *m * 3 + *m * ilaenv_(&c__1, "SORMBR" , "QLN", m, m, n, &c_n1, (ftnlen)6, (ftnlen)3); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = *m * 3 + *m * ilaenv_(&c__1, "SORMBR" , "PRT", n, n, m, &c_n1, (ftnlen)6, (ftnlen)3); wrkbl = max(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = bdspac + *m * 3; maxwrk = max(i__1,i__2); minwrk = *m * 3 + max(*n,bdspac); } } } work[1] = (real) maxwrk; } if (*lwork < minwrk && ! lquery) { *info = -12; } if (*info != 0) { i__1 = -(*info); xerbla_("SGESDD", &i__1); return 0; } else if (lquery) { return 0; } /* Quick return if possible */ if ((*m == 0) || (*n == 0)) { if (*lwork >= 1) { work[1] = 1.f; } return 0; } /* Get machine constants */ eps = slamch_("P"); smlnum = sqrt(slamch_("S")) / eps; bignum = 1.f / smlnum; /* Scale A if max element outside range [SMLNUM,BIGNUM] */ anrm = slange_("M", m, n, &a[a_offset], lda, dum); iscl = 0; if (anrm > 0.f && anrm < smlnum) { iscl = 1; slascl_("G", &c__0, &c__0, &anrm, &smlnum, m, n, &a[a_offset], lda, & ierr); } else if (anrm > bignum) { iscl = 1; slascl_("G", &c__0, &c__0, &anrm, &bignum, m, n, &a[a_offset], lda, & ierr); } if (*m >= *n) { /* A has at least as many rows as columns. If A has sufficiently more rows than columns, first reduce using the QR decomposition (if sufficient workspace available) */ if (*m >= mnthr) { if (wntqn) { /* Path 1 (M much larger than N, JOBZ='N') No singular vectors to be computed */ itau = 1; nwork = itau + *n; /* Compute A=Q*R (Workspace: need 2*N, prefer N+N*NB) */ i__1 = *lwork - nwork + 1; sgeqrf_(m, n, &a[a_offset], lda, &work[itau], &work[nwork], & i__1, &ierr); /* Zero out below R */ i__1 = *n - 1; i__2 = *n - 1; slaset_("L", &i__1, &i__2, &c_b320, &c_b320, &a[a_dim1 + 2], lda); ie = 1; itauq = ie + *n; itaup = itauq + *n; nwork = itaup + *n; /* Bidiagonalize R in A (Workspace: need 4*N, prefer 3*N+2*N*NB) */ i__1 = *lwork - nwork + 1; sgebrd_(n, n, &a[a_offset], lda, &s[1], &work[ie], &work[ itauq], &work[itaup], &work[nwork], &i__1, &ierr); nwork = ie + *n; /* Perform bidiagonal SVD, computing singular values only (Workspace: need N+BDSPAC) */ sbdsdc_("U", "N", n, &s[1], &work[ie], dum, &c__1, dum, &c__1, dum, idum, &work[nwork], &iwork[1], info); } else if (wntqo) { /* Path 2 (M much larger than N, JOBZ = 'O') N left singular vectors to be overwritten on A and N right singular vectors to be computed in VT */ ir = 1; /* WORK(IR) is LDWRKR by N */ if (*lwork >= *lda * *n + *n * *n + *n * 3 + bdspac) { ldwrkr = *lda; } else { ldwrkr = (*lwork - *n * *n - *n * 3 - bdspac) / *n; } itau = ir + ldwrkr * *n; nwork = itau + *n; /* Compute A=Q*R (Workspace: need N*N+2*N, prefer N*N+N+N*NB) */ i__1 = *lwork - nwork + 1; sgeqrf_(m, n, &a[a_offset], lda, &work[itau], &work[nwork], & i__1, &ierr); /* Copy R to WORK(IR), zeroing out below it */ slacpy_("U", n, n, &a[a_offset], lda, &work[ir], &ldwrkr); i__1 = *n - 1; i__2 = *n - 1; slaset_("L", &i__1, &i__2, &c_b320, &c_b320, &work[ir + 1], & ldwrkr); /* Generate Q in A (Workspace: need N*N+2*N, prefer N*N+N+N*NB) */ i__1 = *lwork - nwork + 1; sorgqr_(m, n, n, &a[a_offset], lda, &work[itau], &work[nwork], &i__1, &ierr); ie = itau; itauq = ie + *n; itaup = itauq + *n; nwork = itaup + *n; /* Bidiagonalize R in VT, copying result to WORK(IR) (Workspace: need N*N+4*N, prefer N*N+3*N+2*N*NB) */ i__1 = *lwork - nwork + 1; sgebrd_(n, n, &work[ir], &ldwrkr, &s[1], &work[ie], &work[ itauq], &work[itaup], &work[nwork], &i__1, &ierr); /* WORK(IU) is N by N */ iu = nwork; nwork = iu + *n * *n; /* Perform bidiagonal SVD, computing left singular vectors of bidiagonal matrix in WORK(IU) and computing right singular vectors of bidiagonal matrix in VT (Workspace: need N+N*N+BDSPAC) */ sbdsdc_("U", "I", n, &s[1], &work[ie], &work[iu], n, &vt[ vt_offset], ldvt, dum, idum, &work[nwork], &iwork[1], info); /* Overwrite WORK(IU) by left singular vectors of R and VT by right singular vectors of R (Workspace: need 2*N*N+3*N, prefer 2*N*N+2*N+N*NB) */ i__1 = *lwork - nwork + 1; sormbr_("Q", "L", "N", n, n, n, &work[ir], &ldwrkr, &work[ itauq], &work[iu], n, &work[nwork], &i__1, &ierr); i__1 = *lwork - nwork + 1; sormbr_("P", "R", "T", n, n, n, &work[ir], &ldwrkr, &work[ itaup], &vt[vt_offset], ldvt, &work[nwork], &i__1, & ierr); /* Multiply Q in A by left singular vectors of R in WORK(IU), storing result in WORK(IR) and copying to A (Workspace: need 2*N*N, prefer N*N+M*N) */ i__1 = *m; i__2 = ldwrkr; for (i__ = 1; i__2 < 0 ? i__ >= i__1 : i__ <= i__1; i__ += i__2) { /* Computing MIN */ i__3 = *m - i__ + 1; chunk = min(i__3,ldwrkr); sgemm_("N", "N", &chunk, n, n, &c_b1011, &a[i__ + a_dim1], lda, &work[iu], n, &c_b320, &work[ir], &ldwrkr); slacpy_("F", &chunk, n, &work[ir], &ldwrkr, &a[i__ + a_dim1], lda); /* L10: */ } } else if (wntqs) { /* Path 3 (M much larger than N, JOBZ='S') N left singular vectors to be computed in U and N right singular vectors to be computed in VT */ ir = 1; /* WORK(IR) is N by N */ ldwrkr = *n; itau = ir + ldwrkr * *n; nwork = itau + *n; /* Compute A=Q*R (Workspace: need N*N+2*N, prefer N*N+N+N*NB) */ i__2 = *lwork - nwork + 1; sgeqrf_(m, n, &a[a_offset], lda, &work[itau], &work[nwork], & i__2, &ierr); /* Copy R to WORK(IR), zeroing out below it */ slacpy_("U", n, n, &a[a_offset], lda, &work[ir], &ldwrkr); i__2 = *n - 1; i__1 = *n - 1; slaset_("L", &i__2, &i__1, &c_b320, &c_b320, &work[ir + 1], & ldwrkr); /* Generate Q in A (Workspace: need N*N+2*N, prefer N*N+N+N*NB) */ i__2 = *lwork - nwork + 1; sorgqr_(m, n, n, &a[a_offset], lda, &work[itau], &work[nwork], &i__2, &ierr); ie = itau; itauq = ie + *n; itaup = itauq + *n; nwork = itaup + *n; /* Bidiagonalize R in WORK(IR) (Workspace: need N*N+4*N, prefer N*N+3*N+2*N*NB) */ i__2 = *lwork - nwork + 1; sgebrd_(n, n, &work[ir], &ldwrkr, &s[1], &work[ie], &work[ itauq], &work[itaup], &work[nwork], &i__2, &ierr); /* Perform bidiagonal SVD, computing left singular vectors of bidiagoal matrix in U and computing right singular vectors of bidiagonal matrix in VT (Workspace: need N+BDSPAC) */ sbdsdc_("U", "I", n, &s[1], &work[ie], &u[u_offset], ldu, &vt[ vt_offset], ldvt, dum, idum, &work[nwork], &iwork[1], info); /* Overwrite U by left singular vectors of R and VT by right singular vectors of R (Workspace: need N*N+3*N, prefer N*N+2*N+N*NB) */ i__2 = *lwork - nwork + 1; sormbr_("Q", "L", "N", n, n, n, &work[ir], &ldwrkr, &work[ itauq], &u[u_offset], ldu, &work[nwork], &i__2, &ierr); i__2 = *lwork - nwork + 1; sormbr_("P", "R", "T", n, n, n, &work[ir], &ldwrkr, &work[ itaup], &vt[vt_offset], ldvt, &work[nwork], &i__2, & ierr); /* Multiply Q in A by left singular vectors of R in WORK(IR), storing result in U (Workspace: need N*N) */ slacpy_("F", n, n, &u[u_offset], ldu, &work[ir], &ldwrkr); sgemm_("N", "N", m, n, n, &c_b1011, &a[a_offset], lda, &work[ ir], &ldwrkr, &c_b320, &u[u_offset], ldu); } else if (wntqa) { /* Path 4 (M much larger than N, JOBZ='A') M left singular vectors to be computed in U and N right singular vectors to be computed in VT */ iu = 1; /* WORK(IU) is N by N */ ldwrku = *n; itau = iu + ldwrku * *n; nwork = itau + *n; /* Compute A=Q*R, copying result to U (Workspace: need N*N+2*N, prefer N*N+N+N*NB) */ i__2 = *lwork - nwork + 1; sgeqrf_(m, n, &a[a_offset], lda, &work[itau], &work[nwork], & i__2, &ierr); slacpy_("L", m, n, &a[a_offset], lda, &u[u_offset], ldu); /* Generate Q in U (Workspace: need N*N+2*N, prefer N*N+N+N*NB) */ i__2 = *lwork - nwork + 1; sorgqr_(m, m, n, &u[u_offset], ldu, &work[itau], &work[nwork], &i__2, &ierr); /* Produce R in A, zeroing out other entries */ i__2 = *n - 1; i__1 = *n - 1; slaset_("L", &i__2, &i__1, &c_b320, &c_b320, &a[a_dim1 + 2], lda); ie = itau; itauq = ie + *n; itaup = itauq + *n; nwork = itaup + *n; /* Bidiagonalize R in A (Workspace: need N*N+4*N, prefer N*N+3*N+2*N*NB) */ i__2 = *lwork - nwork + 1; sgebrd_(n, n, &a[a_offset], lda, &s[1], &work[ie], &work[ itauq], &work[itaup], &work[nwork], &i__2, &ierr); /* Perform bidiagonal SVD, computing left singular vectors of bidiagonal matrix in WORK(IU) and computing right singular vectors of bidiagonal matrix in VT (Workspace: need N+N*N+BDSPAC) */ sbdsdc_("U", "I", n, &s[1], &work[ie], &work[iu], n, &vt[ vt_offset], ldvt, dum, idum, &work[nwork], &iwork[1], info); /* Overwrite WORK(IU) by left singular vectors of R and VT by right singular vectors of R (Workspace: need N*N+3*N, prefer N*N+2*N+N*NB) */ i__2 = *lwork - nwork + 1; sormbr_("Q", "L", "N", n, n, n, &a[a_offset], lda, &work[ itauq], &work[iu], &ldwrku, &work[nwork], &i__2, & ierr); i__2 = *lwork - nwork + 1; sormbr_("P", "R", "T", n, n, n, &a[a_offset], lda, &work[ itaup], &vt[vt_offset], ldvt, &work[nwork], &i__2, & ierr); /* Multiply Q in U by left singular vectors of R in WORK(IU), storing result in A (Workspace: need N*N) */ sgemm_("N", "N", m, n, n, &c_b1011, &u[u_offset], ldu, &work[ iu], &ldwrku, &c_b320, &a[a_offset], lda); /* Copy left singular vectors of A from A to U */ slacpy_("F", m, n, &a[a_offset], lda, &u[u_offset], ldu); } } else { /* M .LT. MNTHR Path 5 (M at least N, but not much larger) Reduce to bidiagonal form without QR decomposition */ ie = 1; itauq = ie + *n; itaup = itauq + *n; nwork = itaup + *n; /* Bidiagonalize A (Workspace: need 3*N+M, prefer 3*N+(M+N)*NB) */ i__2 = *lwork - nwork + 1; sgebrd_(m, n, &a[a_offset], lda, &s[1], &work[ie], &work[itauq], & work[itaup], &work[nwork], &i__2, &ierr); if (wntqn) { /* Perform bidiagonal SVD, only computing singular values (Workspace: need N+BDSPAC) */ sbdsdc_("U", "N", n, &s[1], &work[ie], dum, &c__1, dum, &c__1, dum, idum, &work[nwork], &iwork[1], info); } else if (wntqo) { iu = nwork; if (*lwork >= *m * *n + *n * 3 + bdspac) { /* WORK( IU ) is M by N */ ldwrku = *m; nwork = iu + ldwrku * *n; slaset_("F", m, n, &c_b320, &c_b320, &work[iu], &ldwrku); } else { /* WORK( IU ) is N by N */ ldwrku = *n; nwork = iu + ldwrku * *n; /* WORK(IR) is LDWRKR by N */ ir = nwork; ldwrkr = (*lwork - *n * *n - *n * 3) / *n; } nwork = iu + ldwrku * *n; /* Perform bidiagonal SVD, computing left singular vectors of bidiagonal matrix in WORK(IU) and computing right singular vectors of bidiagonal matrix in VT (Workspace: need N+N*N+BDSPAC) */ sbdsdc_("U", "I", n, &s[1], &work[ie], &work[iu], &ldwrku, & vt[vt_offset], ldvt, dum, idum, &work[nwork], &iwork[ 1], info); /* Overwrite VT by right singular vectors of A (Workspace: need N*N+2*N, prefer N*N+N+N*NB) */ i__2 = *lwork - nwork + 1; sormbr_("P", "R", "T", n, n, n, &a[a_offset], lda, &work[ itaup], &vt[vt_offset], ldvt, &work[nwork], &i__2, & ierr); if (*lwork >= *m * *n + *n * 3 + bdspac) { /* Overwrite WORK(IU) by left singular vectors of A (Workspace: need N*N+2*N, prefer N*N+N+N*NB) */ i__2 = *lwork - nwork + 1; sormbr_("Q", "L", "N", m, n, n, &a[a_offset], lda, &work[ itauq], &work[iu], &ldwrku, &work[nwork], &i__2, & ierr); /* Copy left singular vectors of A from WORK(IU) to A */ slacpy_("F", m, n, &work[iu], &ldwrku, &a[a_offset], lda); } else { /* Generate Q in A (Workspace: need N*N+2*N, prefer N*N+N+N*NB) */ i__2 = *lwork - nwork + 1; sorgbr_("Q", m, n, n, &a[a_offset], lda, &work[itauq], & work[nwork], &i__2, &ierr); /* Multiply Q in A by left singular vectors of bidiagonal matrix in WORK(IU), storing result in WORK(IR) and copying to A (Workspace: need 2*N*N, prefer N*N+M*N) */ i__2 = *m; i__1 = ldwrkr; for (i__ = 1; i__1 < 0 ? i__ >= i__2 : i__ <= i__2; i__ += i__1) { /* Computing MIN */ i__3 = *m - i__ + 1; chunk = min(i__3,ldwrkr); sgemm_("N", "N", &chunk, n, n, &c_b1011, &a[i__ + a_dim1], lda, &work[iu], &ldwrku, &c_b320, & work[ir], &ldwrkr); slacpy_("F", &chunk, n, &work[ir], &ldwrkr, &a[i__ + a_dim1], lda); /* L20: */ } } } else if (wntqs) { /* Perform bidiagonal SVD, computing left singular vectors of bidiagonal matrix in U and computing right singular vectors of bidiagonal matrix in VT (Workspace: need N+BDSPAC) */ slaset_("F", m, n, &c_b320, &c_b320, &u[u_offset], ldu); sbdsdc_("U", "I", n, &s[1], &work[ie], &u[u_offset], ldu, &vt[ vt_offset], ldvt, dum, idum, &work[nwork], &iwork[1], info); /* Overwrite U by left singular vectors of A and VT by right singular vectors of A (Workspace: need 3*N, prefer 2*N+N*NB) */ i__1 = *lwork - nwork + 1; sormbr_("Q", "L", "N", m, n, n, &a[a_offset], lda, &work[ itauq], &u[u_offset], ldu, &work[nwork], &i__1, &ierr); i__1 = *lwork - nwork + 1; sormbr_("P", "R", "T", n, n, n, &a[a_offset], lda, &work[ itaup], &vt[vt_offset], ldvt, &work[nwork], &i__1, & ierr); } else if (wntqa) { /* Perform bidiagonal SVD, computing left singular vectors of bidiagonal matrix in U and computing right singular vectors of bidiagonal matrix in VT (Workspace: need N+BDSPAC) */ slaset_("F", m, m, &c_b320, &c_b320, &u[u_offset], ldu); sbdsdc_("U", "I", n, &s[1], &work[ie], &u[u_offset], ldu, &vt[ vt_offset], ldvt, dum, idum, &work[nwork], &iwork[1], info); /* Set the right corner of U to identity matrix */ i__1 = *m - *n; i__2 = *m - *n; slaset_("F", &i__1, &i__2, &c_b320, &c_b1011, &u[*n + 1 + (*n + 1) * u_dim1], ldu); /* Overwrite U by left singular vectors of A and VT by right singular vectors of A (Workspace: need N*N+2*N+M, prefer N*N+2*N+M*NB) */ i__1 = *lwork - nwork + 1; sormbr_("Q", "L", "N", m, m, n, &a[a_offset], lda, &work[ itauq], &u[u_offset], ldu, &work[nwork], &i__1, &ierr); i__1 = *lwork - nwork + 1; sormbr_("P", "R", "T", n, n, m, &a[a_offset], lda, &work[ itaup], &vt[vt_offset], ldvt, &work[nwork], &i__1, & ierr); } } } else { /* A has more columns than rows. If A has sufficiently more columns than rows, first reduce using the LQ decomposition (if sufficient workspace available) */ if (*n >= mnthr) { if (wntqn) { /* Path 1t (N much larger than M, JOBZ='N') No singular vectors to be computed */ itau = 1; nwork = itau + *m; /* Compute A=L*Q (Workspace: need 2*M, prefer M+M*NB) */ i__1 = *lwork - nwork + 1; sgelqf_(m, n, &a[a_offset], lda, &work[itau], &work[nwork], & i__1, &ierr); /* Zero out above L */ i__1 = *m - 1; i__2 = *m - 1; slaset_("U", &i__1, &i__2, &c_b320, &c_b320, &a[((a_dim1) << ( 1)) + 1], lda); ie = 1; itauq = ie + *m; itaup = itauq + *m; nwork = itaup + *m; /* Bidiagonalize L in A (Workspace: need 4*M, prefer 3*M+2*M*NB) */ i__1 = *lwork - nwork + 1; sgebrd_(m, m, &a[a_offset], lda, &s[1], &work[ie], &work[ itauq], &work[itaup], &work[nwork], &i__1, &ierr); nwork = ie + *m; /* Perform bidiagonal SVD, computing singular values only (Workspace: need M+BDSPAC) */ sbdsdc_("U", "N", m, &s[1], &work[ie], dum, &c__1, dum, &c__1, dum, idum, &work[nwork], &iwork[1], info); } else if (wntqo) { /* Path 2t (N much larger than M, JOBZ='O') M right singular vectors to be overwritten on A and M left singular vectors to be computed in U */ ivt = 1; /* IVT is M by M */ il = ivt + *m * *m; if (*lwork >= *m * *n + *m * *m + *m * 3 + bdspac) { /* WORK(IL) is M by N */ ldwrkl = *m; chunk = *n; } else { ldwrkl = *m; chunk = (*lwork - *m * *m) / *m; } itau = il + ldwrkl * *m; nwork = itau + *m; /* Compute A=L*Q (Workspace: need M*M+2*M, prefer M*M+M+M*NB) */ i__1 = *lwork - nwork + 1; sgelqf_(m, n, &a[a_offset], lda, &work[itau], &work[nwork], & i__1, &ierr); /* Copy L to WORK(IL), zeroing about above it */ slacpy_("L", m, m, &a[a_offset], lda, &work[il], &ldwrkl); i__1 = *m - 1; i__2 = *m - 1; slaset_("U", &i__1, &i__2, &c_b320, &c_b320, &work[il + ldwrkl], &ldwrkl); /* Generate Q in A (Workspace: need M*M+2*M, prefer M*M+M+M*NB) */ i__1 = *lwork - nwork + 1; sorglq_(m, n, m, &a[a_offset], lda, &work[itau], &work[nwork], &i__1, &ierr); ie = itau; itauq = ie + *m; itaup = itauq + *m; nwork = itaup + *m; /* Bidiagonalize L in WORK(IL) (Workspace: need M*M+4*M, prefer M*M+3*M+2*M*NB) */ i__1 = *lwork - nwork + 1; sgebrd_(m, m, &work[il], &ldwrkl, &s[1], &work[ie], &work[ itauq], &work[itaup], &work[nwork], &i__1, &ierr); /* Perform bidiagonal SVD, computing left singular vectors of bidiagonal matrix in U, and computing right singular vectors of bidiagonal matrix in WORK(IVT) (Workspace: need M+M*M+BDSPAC) */ sbdsdc_("U", "I", m, &s[1], &work[ie], &u[u_offset], ldu, & work[ivt], m, dum, idum, &work[nwork], &iwork[1], info); /* Overwrite U by left singular vectors of L and WORK(IVT) by right singular vectors of L (Workspace: need 2*M*M+3*M, prefer 2*M*M+2*M+M*NB) */ i__1 = *lwork - nwork + 1; sormbr_("Q", "L", "N", m, m, m, &work[il], &ldwrkl, &work[ itauq], &u[u_offset], ldu, &work[nwork], &i__1, &ierr); i__1 = *lwork - nwork + 1; sormbr_("P", "R", "T", m, m, m, &work[il], &ldwrkl, &work[ itaup], &work[ivt], m, &work[nwork], &i__1, &ierr); /* Multiply right singular vectors of L in WORK(IVT) by Q in A, storing result in WORK(IL) and copying to A (Workspace: need 2*M*M, prefer M*M+M*N) */ i__1 = *n; i__2 = chunk; for (i__ = 1; i__2 < 0 ? i__ >= i__1 : i__ <= i__1; i__ += i__2) { /* Computing MIN */ i__3 = *n - i__ + 1; blk = min(i__3,chunk); sgemm_("N", "N", m, &blk, m, &c_b1011, &work[ivt], m, &a[ i__ * a_dim1 + 1], lda, &c_b320, &work[il], & ldwrkl); slacpy_("F", m, &blk, &work[il], &ldwrkl, &a[i__ * a_dim1 + 1], lda); /* L30: */ } } else if (wntqs) { /* Path 3t (N much larger than M, JOBZ='S') M right singular vectors to be computed in VT and M left singular vectors to be computed in U */ il = 1; /* WORK(IL) is M by M */ ldwrkl = *m; itau = il + ldwrkl * *m; nwork = itau + *m; /* Compute A=L*Q (Workspace: need M*M+2*M, prefer M*M+M+M*NB) */ i__2 = *lwork - nwork + 1; sgelqf_(m, n, &a[a_offset], lda, &work[itau], &work[nwork], & i__2, &ierr); /* Copy L to WORK(IL), zeroing out above it */ slacpy_("L", m, m, &a[a_offset], lda, &work[il], &ldwrkl); i__2 = *m - 1; i__1 = *m - 1; slaset_("U", &i__2, &i__1, &c_b320, &c_b320, &work[il + ldwrkl], &ldwrkl); /* Generate Q in A (Workspace: need M*M+2*M, prefer M*M+M+M*NB) */ i__2 = *lwork - nwork + 1; sorglq_(m, n, m, &a[a_offset], lda, &work[itau], &work[nwork], &i__2, &ierr); ie = itau; itauq = ie + *m; itaup = itauq + *m; nwork = itaup + *m; /* Bidiagonalize L in WORK(IU), copying result to U (Workspace: need M*M+4*M, prefer M*M+3*M+2*M*NB) */ i__2 = *lwork - nwork + 1; sgebrd_(m, m, &work[il], &ldwrkl, &s[1], &work[ie], &work[ itauq], &work[itaup], &work[nwork], &i__2, &ierr); /* Perform bidiagonal SVD, computing left singular vectors of bidiagonal matrix in U and computing right singular vectors of bidiagonal matrix in VT (Workspace: need M+BDSPAC) */ sbdsdc_("U", "I", m, &s[1], &work[ie], &u[u_offset], ldu, &vt[ vt_offset], ldvt, dum, idum, &work[nwork], &iwork[1], info); /* Overwrite U by left singular vectors of L and VT by right singular vectors of L (Workspace: need M*M+3*M, prefer M*M+2*M+M*NB) */ i__2 = *lwork - nwork + 1; sormbr_("Q", "L", "N", m, m, m, &work[il], &ldwrkl, &work[ itauq], &u[u_offset], ldu, &work[nwork], &i__2, &ierr); i__2 = *lwork - nwork + 1; sormbr_("P", "R", "T", m, m, m, &work[il], &ldwrkl, &work[ itaup], &vt[vt_offset], ldvt, &work[nwork], &i__2, & ierr); /* Multiply right singular vectors of L in WORK(IL) by Q in A, storing result in VT (Workspace: need M*M) */ slacpy_("F", m, m, &vt[vt_offset], ldvt, &work[il], &ldwrkl); sgemm_("N", "N", m, n, m, &c_b1011, &work[il], &ldwrkl, &a[ a_offset], lda, &c_b320, &vt[vt_offset], ldvt); } else if (wntqa) { /* Path 4t (N much larger than M, JOBZ='A') N right singular vectors to be computed in VT and M left singular vectors to be computed in U */ ivt = 1; /* WORK(IVT) is M by M */ ldwkvt = *m; itau = ivt + ldwkvt * *m; nwork = itau + *m; /* Compute A=L*Q, copying result to VT (Workspace: need M*M+2*M, prefer M*M+M+M*NB) */ i__2 = *lwork - nwork + 1; sgelqf_(m, n, &a[a_offset], lda, &work[itau], &work[nwork], & i__2, &ierr); slacpy_("U", m, n, &a[a_offset], lda, &vt[vt_offset], ldvt); /* Generate Q in VT (Workspace: need M*M+2*M, prefer M*M+M+M*NB) */ i__2 = *lwork - nwork + 1; sorglq_(n, n, m, &vt[vt_offset], ldvt, &work[itau], &work[ nwork], &i__2, &ierr); /* Produce L in A, zeroing out other entries */ i__2 = *m - 1; i__1 = *m - 1; slaset_("U", &i__2, &i__1, &c_b320, &c_b320, &a[((a_dim1) << ( 1)) + 1], lda); ie = itau; itauq = ie + *m; itaup = itauq + *m; nwork = itaup + *m; /* Bidiagonalize L in A (Workspace: need M*M+4*M, prefer M*M+3*M+2*M*NB) */ i__2 = *lwork - nwork + 1; sgebrd_(m, m, &a[a_offset], lda, &s[1], &work[ie], &work[ itauq], &work[itaup], &work[nwork], &i__2, &ierr); /* Perform bidiagonal SVD, computing left singular vectors of bidiagonal matrix in U and computing right singular vectors of bidiagonal matrix in WORK(IVT) (Workspace: need M+M*M+BDSPAC) */ sbdsdc_("U", "I", m, &s[1], &work[ie], &u[u_offset], ldu, & work[ivt], &ldwkvt, dum, idum, &work[nwork], &iwork[1] , info); /* Overwrite U by left singular vectors of L and WORK(IVT) by right singular vectors of L (Workspace: need M*M+3*M, prefer M*M+2*M+M*NB) */ i__2 = *lwork - nwork + 1; sormbr_("Q", "L", "N", m, m, m, &a[a_offset], lda, &work[ itauq], &u[u_offset], ldu, &work[nwork], &i__2, &ierr); i__2 = *lwork - nwork + 1; sormbr_("P", "R", "T", m, m, m, &a[a_offset], lda, &work[ itaup], &work[ivt], &ldwkvt, &work[nwork], &i__2, & ierr); /* Multiply right singular vectors of L in WORK(IVT) by Q in VT, storing result in A (Workspace: need M*M) */ sgemm_("N", "N", m, n, m, &c_b1011, &work[ivt], &ldwkvt, &vt[ vt_offset], ldvt, &c_b320, &a[a_offset], lda); /* Copy right singular vectors of A from A to VT */ slacpy_("F", m, n, &a[a_offset], lda, &vt[vt_offset], ldvt); } } else { /* N .LT. MNTHR Path 5t (N greater than M, but not much larger) Reduce to bidiagonal form without LQ decomposition */ ie = 1; itauq = ie + *m; itaup = itauq + *m; nwork = itaup + *m; /* Bidiagonalize A (Workspace: need 3*M+N, prefer 3*M+(M+N)*NB) */ i__2 = *lwork - nwork + 1; sgebrd_(m, n, &a[a_offset], lda, &s[1], &work[ie], &work[itauq], & work[itaup], &work[nwork], &i__2, &ierr); if (wntqn) { /* Perform bidiagonal SVD, only computing singular values (Workspace: need M+BDSPAC) */ sbdsdc_("L", "N", m, &s[1], &work[ie], dum, &c__1, dum, &c__1, dum, idum, &work[nwork], &iwork[1], info); } else if (wntqo) { ldwkvt = *m; ivt = nwork; if (*lwork >= *m * *n + *m * 3 + bdspac) { /* WORK( IVT ) is M by N */ slaset_("F", m, n, &c_b320, &c_b320, &work[ivt], &ldwkvt); nwork = ivt + ldwkvt * *n; } else { /* WORK( IVT ) is M by M */ nwork = ivt + ldwkvt * *m; il = nwork; /* WORK(IL) is M by CHUNK */ chunk = (*lwork - *m * *m - *m * 3) / *m; } /* Perform bidiagonal SVD, computing left singular vectors of bidiagonal matrix in U and computing right singular vectors of bidiagonal matrix in WORK(IVT) (Workspace: need M*M+BDSPAC) */ sbdsdc_("L", "I", m, &s[1], &work[ie], &u[u_offset], ldu, & work[ivt], &ldwkvt, dum, idum, &work[nwork], &iwork[1] , info); /* Overwrite U by left singular vectors of A (Workspace: need M*M+2*M, prefer M*M+M+M*NB) */ i__2 = *lwork - nwork + 1; sormbr_("Q", "L", "N", m, m, n, &a[a_offset], lda, &work[ itauq], &u[u_offset], ldu, &work[nwork], &i__2, &ierr); if (*lwork >= *m * *n + *m * 3 + bdspac) { /* Overwrite WORK(IVT) by left singular vectors of A (Workspace: need M*M+2*M, prefer M*M+M+M*NB) */ i__2 = *lwork - nwork + 1; sormbr_("P", "R", "T", m, n, m, &a[a_offset], lda, &work[ itaup], &work[ivt], &ldwkvt, &work[nwork], &i__2, &ierr); /* Copy right singular vectors of A from WORK(IVT) to A */ slacpy_("F", m, n, &work[ivt], &ldwkvt, &a[a_offset], lda); } else { /* Generate P**T in A (Workspace: need M*M+2*M, prefer M*M+M+M*NB) */ i__2 = *lwork - nwork + 1; sorgbr_("P", m, n, m, &a[a_offset], lda, &work[itaup], & work[nwork], &i__2, &ierr); /* Multiply Q in A by right singular vectors of bidiagonal matrix in WORK(IVT), storing result in WORK(IL) and copying to A (Workspace: need 2*M*M, prefer M*M+M*N) */ i__2 = *n; i__1 = chunk; for (i__ = 1; i__1 < 0 ? i__ >= i__2 : i__ <= i__2; i__ += i__1) { /* Computing MIN */ i__3 = *n - i__ + 1; blk = min(i__3,chunk); sgemm_("N", "N", m, &blk, m, &c_b1011, &work[ivt], & ldwkvt, &a[i__ * a_dim1 + 1], lda, &c_b320, & work[il], m); slacpy_("F", m, &blk, &work[il], m, &a[i__ * a_dim1 + 1], lda); /* L40: */ } } } else if (wntqs) { /* Perform bidiagonal SVD, computing left singular vectors of bidiagonal matrix in U and computing right singular vectors of bidiagonal matrix in VT (Workspace: need M+BDSPAC) */ slaset_("F", m, n, &c_b320, &c_b320, &vt[vt_offset], ldvt); sbdsdc_("L", "I", m, &s[1], &work[ie], &u[u_offset], ldu, &vt[ vt_offset], ldvt, dum, idum, &work[nwork], &iwork[1], info); /* Overwrite U by left singular vectors of A and VT by right singular vectors of A (Workspace: need 3*M, prefer 2*M+M*NB) */ i__1 = *lwork - nwork + 1; sormbr_("Q", "L", "N", m, m, n, &a[a_offset], lda, &work[ itauq], &u[u_offset], ldu, &work[nwork], &i__1, &ierr); i__1 = *lwork - nwork + 1; sormbr_("P", "R", "T", m, n, m, &a[a_offset], lda, &work[ itaup], &vt[vt_offset], ldvt, &work[nwork], &i__1, & ierr); } else if (wntqa) { /* Perform bidiagonal SVD, computing left singular vectors of bidiagonal matrix in U and computing right singular vectors of bidiagonal matrix in VT (Workspace: need M+BDSPAC) */ slaset_("F", n, n, &c_b320, &c_b320, &vt[vt_offset], ldvt); sbdsdc_("L", "I", m, &s[1], &work[ie], &u[u_offset], ldu, &vt[ vt_offset], ldvt, dum, idum, &work[nwork], &iwork[1], info); /* Set the right corner of VT to identity matrix */ i__1 = *n - *m; i__2 = *n - *m; slaset_("F", &i__1, &i__2, &c_b320, &c_b1011, &vt[*m + 1 + (* m + 1) * vt_dim1], ldvt); /* Overwrite U by left singular vectors of A and VT by right singular vectors of A (Workspace: need 2*M+N, prefer 2*M+N*NB) */ i__1 = *lwork - nwork + 1; sormbr_("Q", "L", "N", m, m, n, &a[a_offset], lda, &work[ itauq], &u[u_offset], ldu, &work[nwork], &i__1, &ierr); i__1 = *lwork - nwork + 1; sormbr_("P", "R", "T", n, n, m, &a[a_offset], lda, &work[ itaup], &vt[vt_offset], ldvt, &work[nwork], &i__1, & ierr); } } } /* Undo scaling if necessary */ if (iscl == 1) { if (anrm > bignum) { slascl_("G", &c__0, &c__0, &bignum, &anrm, &minmn, &c__1, &s[1], & minmn, &ierr); } if (anrm < smlnum) { slascl_("G", &c__0, &c__0, &smlnum, &anrm, &minmn, &c__1, &s[1], & minmn, &ierr); } } /* Return optimal workspace in WORK(1) */ work[1] = (real) maxwrk; return 0; /* End of SGESDD */ } /* sgesdd_ */ /* Subroutine */ int sgesv_(integer *n, integer *nrhs, real *a, integer *lda, integer *ipiv, real *b, integer *ldb, integer *info) { /* System generated locals */ integer a_dim1, a_offset, b_dim1, b_offset, i__1; /* Local variables */ extern /* Subroutine */ int xerbla_(char *, integer *), sgetrf_( integer *, integer *, real *, integer *, integer *, integer *), sgetrs_(char *, integer *, integer *, real *, integer *, integer * , real *, integer *, integer *); /* -- LAPACK driver routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University March 31, 1993 Purpose ======= SGESV computes the solution to a real system of linear equations A * X = B, where A is an N-by-N matrix and X and B are N-by-NRHS matrices. The LU decomposition with partial pivoting and row interchanges is used to factor A as A = P * L * U, where P is a permutation matrix, L is unit lower triangular, and U is upper triangular. The factored form of A is then used to solve the system of equations A * X = B. Arguments ========= N (input) INTEGER The number of linear equations, i.e., the order of the matrix A. N >= 0. NRHS (input) INTEGER The number of right hand sides, i.e., the number of columns of the matrix B. NRHS >= 0. A (input/output) REAL array, dimension (LDA,N) On entry, the N-by-N coefficient matrix A. On exit, the factors L and U from the factorization A = P*L*U; the unit diagonal elements of L are not stored. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,N). IPIV (output) INTEGER array, dimension (N) The pivot indices that define the permutation matrix P; row i of the matrix was interchanged with row IPIV(i). B (input/output) REAL array, dimension (LDB,NRHS) On entry, the N-by-NRHS matrix of right hand side matrix B. On exit, if INFO = 0, the N-by-NRHS solution matrix X. LDB (input) INTEGER The leading dimension of the array B. LDB >= max(1,N). INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value > 0: if INFO = i, U(i,i) is exactly zero. The factorization has been completed, but the factor U is exactly singular, so the solution could not be computed. ===================================================================== Test the input parameters. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --ipiv; b_dim1 = *ldb; b_offset = 1 + b_dim1; b -= b_offset; /* Function Body */ *info = 0; if (*n < 0) { *info = -1; } else if (*nrhs < 0) { *info = -2; } else if (*lda < max(1,*n)) { *info = -4; } else if (*ldb < max(1,*n)) { *info = -7; } if (*info != 0) { i__1 = -(*info); xerbla_("SGESV ", &i__1); return 0; } /* Compute the LU factorization of A. */ sgetrf_(n, n, &a[a_offset], lda, &ipiv[1], info); if (*info == 0) { /* Solve the system A*X = B, overwriting B with X. */ sgetrs_("No transpose", n, nrhs, &a[a_offset], lda, &ipiv[1], &b[ b_offset], ldb, info); } return 0; /* End of SGESV */ } /* sgesv_ */ /* Subroutine */ int sgetf2_(integer *m, integer *n, real *a, integer *lda, integer *ipiv, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3; real r__1; /* Local variables */ static integer j, jp; extern /* Subroutine */ int sger_(integer *, integer *, real *, real *, integer *, real *, integer *, real *, integer *), sscal_(integer * , real *, real *, integer *), sswap_(integer *, real *, integer *, real *, integer *), xerbla_(char *, integer *); extern integer isamax_(integer *, real *, integer *); /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1992 Purpose ======= SGETF2 computes an LU factorization of a general m-by-n matrix A using partial pivoting with row interchanges. The factorization has the form A = P * L * U where P is a permutation matrix, L is lower triangular with unit diagonal elements (lower trapezoidal if m > n), and U is upper triangular (upper trapezoidal if m < n). This is the right-looking Level 2 BLAS version of the algorithm. Arguments ========= M (input) INTEGER The number of rows of the matrix A. M >= 0. N (input) INTEGER The number of columns of the matrix A. N >= 0. A (input/output) REAL array, dimension (LDA,N) On entry, the m by n matrix to be factored. On exit, the factors L and U from the factorization A = P*L*U; the unit diagonal elements of L are not stored. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,M). IPIV (output) INTEGER array, dimension (min(M,N)) The pivot indices; for 1 <= i <= min(M,N), row i of the matrix was interchanged with row IPIV(i). INFO (output) INTEGER = 0: successful exit < 0: if INFO = -k, the k-th argument had an illegal value > 0: if INFO = k, U(k,k) is exactly zero. The factorization has been completed, but the factor U is exactly singular, and division by zero will occur if it is used to solve a system of equations. ===================================================================== Test the input parameters. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --ipiv; /* Function Body */ *info = 0; if (*m < 0) { *info = -1; } else if (*n < 0) { *info = -2; } else if (*lda < max(1,*m)) { *info = -4; } if (*info != 0) { i__1 = -(*info); xerbla_("SGETF2", &i__1); return 0; } /* Quick return if possible */ if ((*m == 0) || (*n == 0)) { return 0; } i__1 = min(*m,*n); for (j = 1; j <= i__1; ++j) { /* Find pivot and test for singularity. */ i__2 = *m - j + 1; jp = j - 1 + isamax_(&i__2, &a[j + j * a_dim1], &c__1); ipiv[j] = jp; if (a[jp + j * a_dim1] != 0.f) { /* Apply the interchange to columns 1:N. */ if (jp != j) { sswap_(n, &a[j + a_dim1], lda, &a[jp + a_dim1], lda); } /* Compute elements J+1:M of J-th column. */ if (j < *m) { i__2 = *m - j; r__1 = 1.f / a[j + j * a_dim1]; sscal_(&i__2, &r__1, &a[j + 1 + j * a_dim1], &c__1); } } else if (*info == 0) { *info = j; } if (j < min(*m,*n)) { /* Update trailing submatrix. */ i__2 = *m - j; i__3 = *n - j; sger_(&i__2, &i__3, &c_b1290, &a[j + 1 + j * a_dim1], &c__1, &a[j + (j + 1) * a_dim1], lda, &a[j + 1 + (j + 1) * a_dim1], lda); } /* L10: */ } return 0; /* End of SGETF2 */ } /* sgetf2_ */ /* Subroutine */ int sgetrf_(integer *m, integer *n, real *a, integer *lda, integer *ipiv, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3, i__4, i__5; /* Local variables */ static integer i__, j, jb, nb, iinfo; extern /* Subroutine */ int sgemm_(char *, char *, integer *, integer *, integer *, real *, real *, integer *, real *, integer *, real *, real *, integer *), strsm_(char *, char *, char *, char *, integer *, integer *, real *, real *, integer *, real *, integer *), sgetf2_(integer *, integer *, real *, integer *, integer *, integer *), xerbla_(char *, integer *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); extern /* Subroutine */ int slaswp_(integer *, real *, integer *, integer *, integer *, integer *, integer *); /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University March 31, 1993 Purpose ======= SGETRF computes an LU factorization of a general M-by-N matrix A using partial pivoting with row interchanges. The factorization has the form A = P * L * U where P is a permutation matrix, L is lower triangular with unit diagonal elements (lower trapezoidal if m > n), and U is upper triangular (upper trapezoidal if m < n). This is the right-looking Level 3 BLAS version of the algorithm. Arguments ========= M (input) INTEGER The number of rows of the matrix A. M >= 0. N (input) INTEGER The number of columns of the matrix A. N >= 0. A (input/output) REAL array, dimension (LDA,N) On entry, the M-by-N matrix to be factored. On exit, the factors L and U from the factorization A = P*L*U; the unit diagonal elements of L are not stored. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,M). IPIV (output) INTEGER array, dimension (min(M,N)) The pivot indices; for 1 <= i <= min(M,N), row i of the matrix was interchanged with row IPIV(i). INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value > 0: if INFO = i, U(i,i) is exactly zero. The factorization has been completed, but the factor U is exactly singular, and division by zero will occur if it is used to solve a system of equations. ===================================================================== Test the input parameters. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --ipiv; /* Function Body */ *info = 0; if (*m < 0) { *info = -1; } else if (*n < 0) { *info = -2; } else if (*lda < max(1,*m)) { *info = -4; } if (*info != 0) { i__1 = -(*info); xerbla_("SGETRF", &i__1); return 0; } /* Quick return if possible */ if ((*m == 0) || (*n == 0)) { return 0; } /* Determine the block size for this environment. */ nb = ilaenv_(&c__1, "SGETRF", " ", m, n, &c_n1, &c_n1, (ftnlen)6, (ftnlen) 1); if ((nb <= 1) || (nb >= min(*m,*n))) { /* Use unblocked code. */ sgetf2_(m, n, &a[a_offset], lda, &ipiv[1], info); } else { /* Use blocked code. */ i__1 = min(*m,*n); i__2 = nb; for (j = 1; i__2 < 0 ? j >= i__1 : j <= i__1; j += i__2) { /* Computing MIN */ i__3 = min(*m,*n) - j + 1; jb = min(i__3,nb); /* Factor diagonal and subdiagonal blocks and test for exact singularity. */ i__3 = *m - j + 1; sgetf2_(&i__3, &jb, &a[j + j * a_dim1], lda, &ipiv[j], &iinfo); /* Adjust INFO and the pivot indices. */ if (*info == 0 && iinfo > 0) { *info = iinfo + j - 1; } /* Computing MIN */ i__4 = *m, i__5 = j + jb - 1; i__3 = min(i__4,i__5); for (i__ = j; i__ <= i__3; ++i__) { ipiv[i__] = j - 1 + ipiv[i__]; /* L10: */ } /* Apply interchanges to columns 1:J-1. */ i__3 = j - 1; i__4 = j + jb - 1; slaswp_(&i__3, &a[a_offset], lda, &j, &i__4, &ipiv[1], &c__1); if (j + jb <= *n) { /* Apply interchanges to columns J+JB:N. */ i__3 = *n - j - jb + 1; i__4 = j + jb - 1; slaswp_(&i__3, &a[(j + jb) * a_dim1 + 1], lda, &j, &i__4, & ipiv[1], &c__1); /* Compute block row of U. */ i__3 = *n - j - jb + 1; strsm_("Left", "Lower", "No transpose", "Unit", &jb, &i__3, & c_b1011, &a[j + j * a_dim1], lda, &a[j + (j + jb) * a_dim1], lda); if (j + jb <= *m) { /* Update trailing submatrix. */ i__3 = *m - j - jb + 1; i__4 = *n - j - jb + 1; sgemm_("No transpose", "No transpose", &i__3, &i__4, &jb, &c_b1290, &a[j + jb + j * a_dim1], lda, &a[j + (j + jb) * a_dim1], lda, &c_b1011, &a[j + jb + (j + jb) * a_dim1], lda); } } /* L20: */ } } return 0; /* End of SGETRF */ } /* sgetrf_ */ /* Subroutine */ int sgetrs_(char *trans, integer *n, integer *nrhs, real *a, integer *lda, integer *ipiv, real *b, integer *ldb, integer *info) { /* System generated locals */ integer a_dim1, a_offset, b_dim1, b_offset, i__1; /* Local variables */ extern logical lsame_(char *, char *); extern /* Subroutine */ int strsm_(char *, char *, char *, char *, integer *, integer *, real *, real *, integer *, real *, integer * ), xerbla_(char *, integer *); static logical notran; extern /* Subroutine */ int slaswp_(integer *, real *, integer *, integer *, integer *, integer *, integer *); /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University March 31, 1993 Purpose ======= SGETRS solves a system of linear equations A * X = B or A' * X = B with a general N-by-N matrix A using the LU factorization computed by SGETRF. Arguments ========= TRANS (input) CHARACTER*1 Specifies the form of the system of equations: = 'N': A * X = B (No transpose) = 'T': A'* X = B (Transpose) = 'C': A'* X = B (Conjugate transpose = Transpose) N (input) INTEGER The order of the matrix A. N >= 0. NRHS (input) INTEGER The number of right hand sides, i.e., the number of columns of the matrix B. NRHS >= 0. A (input) REAL array, dimension (LDA,N) The factors L and U from the factorization A = P*L*U as computed by SGETRF. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,N). IPIV (input) INTEGER array, dimension (N) The pivot indices from SGETRF; for 1<=i<=N, row i of the matrix was interchanged with row IPIV(i). B (input/output) REAL array, dimension (LDB,NRHS) On entry, the right hand side matrix B. On exit, the solution matrix X. LDB (input) INTEGER The leading dimension of the array B. LDB >= max(1,N). INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value ===================================================================== Test the input parameters. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --ipiv; b_dim1 = *ldb; b_offset = 1 + b_dim1; b -= b_offset; /* Function Body */ *info = 0; notran = lsame_(trans, "N"); if (! notran && ! lsame_(trans, "T") && ! lsame_( trans, "C")) { *info = -1; } else if (*n < 0) { *info = -2; } else if (*nrhs < 0) { *info = -3; } else if (*lda < max(1,*n)) { *info = -5; } else if (*ldb < max(1,*n)) { *info = -8; } if (*info != 0) { i__1 = -(*info); xerbla_("SGETRS", &i__1); return 0; } /* Quick return if possible */ if ((*n == 0) || (*nrhs == 0)) { return 0; } if (notran) { /* Solve A * X = B. Apply row interchanges to the right hand sides. */ slaswp_(nrhs, &b[b_offset], ldb, &c__1, n, &ipiv[1], &c__1); /* Solve L*X = B, overwriting B with X. */ strsm_("Left", "Lower", "No transpose", "Unit", n, nrhs, &c_b1011, &a[ a_offset], lda, &b[b_offset], ldb); /* Solve U*X = B, overwriting B with X. */ strsm_("Left", "Upper", "No transpose", "Non-unit", n, nrhs, &c_b1011, &a[a_offset], lda, &b[b_offset], ldb); } else { /* Solve A' * X = B. Solve U'*X = B, overwriting B with X. */ strsm_("Left", "Upper", "Transpose", "Non-unit", n, nrhs, &c_b1011, & a[a_offset], lda, &b[b_offset], ldb); /* Solve L'*X = B, overwriting B with X. */ strsm_("Left", "Lower", "Transpose", "Unit", n, nrhs, &c_b1011, &a[ a_offset], lda, &b[b_offset], ldb); /* Apply row interchanges to the solution vectors. */ slaswp_(nrhs, &b[b_offset], ldb, &c__1, n, &ipiv[1], &c_n1); } return 0; /* End of SGETRS */ } /* sgetrs_ */ /* Subroutine */ int shseqr_(char *job, char *compz, integer *n, integer *ilo, integer *ihi, real *h__, integer *ldh, real *wr, real *wi, real *z__, integer *ldz, real *work, integer *lwork, integer *info) { /* System generated locals */ address a__1[2]; integer h_dim1, h_offset, z_dim1, z_offset, i__1, i__2, i__3[2], i__4, i__5; real r__1, r__2; char ch__1[2]; /* Builtin functions */ /* Subroutine */ int s_cat(char *, char **, integer *, integer *, ftnlen); /* Local variables */ static integer i__, j, k, l; static real s[225] /* was [15][15] */, v[16]; static integer i1, i2, ii, nh, nr, ns, nv; static real vv[16]; static integer itn; static real tau; static integer its; static real ulp, tst1; static integer maxb; static real absw; static integer ierr; static real unfl, temp, ovfl; extern logical lsame_(char *, char *); extern /* Subroutine */ int sscal_(integer *, real *, real *, integer *); static integer itemp; extern /* Subroutine */ int sgemv_(char *, integer *, integer *, real *, real *, integer *, real *, integer *, real *, real *, integer *); static logical initz, wantt; extern /* Subroutine */ int scopy_(integer *, real *, integer *, real *, integer *); static logical wantz; extern doublereal slapy2_(real *, real *); extern /* Subroutine */ int slabad_(real *, real *); extern doublereal slamch_(char *); extern /* Subroutine */ int xerbla_(char *, integer *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); extern /* Subroutine */ int slarfg_(integer *, real *, real *, integer *, real *); extern integer isamax_(integer *, real *, integer *); extern doublereal slanhs_(char *, integer *, real *, integer *, real *); extern /* Subroutine */ int slahqr_(logical *, logical *, integer *, integer *, integer *, real *, integer *, real *, real *, integer * , integer *, real *, integer *, integer *), slacpy_(char *, integer *, integer *, real *, integer *, real *, integer *), slaset_(char *, integer *, integer *, real *, real *, real *, integer *), slarfx_(char *, integer *, integer *, real *, real *, real *, integer *, real *); static real smlnum; static logical lquery; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= SHSEQR computes the eigenvalues of a real upper Hessenberg matrix H and, optionally, the matrices T and Z from the Schur decomposition H = Z T Z**T, where T is an upper quasi-triangular matrix (the Schur form), and Z is the orthogonal matrix of Schur vectors. Optionally Z may be postmultiplied into an input orthogonal matrix Q, so that this routine can give the Schur factorization of a matrix A which has been reduced to the Hessenberg form H by the orthogonal matrix Q: A = Q*H*Q**T = (QZ)*T*(QZ)**T. Arguments ========= JOB (input) CHARACTER*1 = 'E': compute eigenvalues only; = 'S': compute eigenvalues and the Schur form T. COMPZ (input) CHARACTER*1 = 'N': no Schur vectors are computed; = 'I': Z is initialized to the unit matrix and the matrix Z of Schur vectors of H is returned; = 'V': Z must contain an orthogonal matrix Q on entry, and the product Q*Z is returned. N (input) INTEGER The order of the matrix H. N >= 0. ILO (input) INTEGER IHI (input) INTEGER It is assumed that H is already upper triangular in rows and columns 1:ILO-1 and IHI+1:N. ILO and IHI are normally set by a previous call to SGEBAL, and then passed to SGEHRD when the matrix output by SGEBAL is reduced to Hessenberg form. Otherwise ILO and IHI should be set to 1 and N respectively. 1 <= ILO <= IHI <= N, if N > 0; ILO=1 and IHI=0, if N=0. H (input/output) REAL array, dimension (LDH,N) On entry, the upper Hessenberg matrix H. On exit, if JOB = 'S', H contains the upper quasi-triangular matrix T from the Schur decomposition (the Schur form); 2-by-2 diagonal blocks (corresponding to complex conjugate pairs of eigenvalues) are returned in standard form, with H(i,i) = H(i+1,i+1) and H(i+1,i)*H(i,i+1) < 0. If JOB = 'E', the contents of H are unspecified on exit. LDH (input) INTEGER The leading dimension of the array H. LDH >= max(1,N). WR (output) REAL array, dimension (N) WI (output) REAL array, dimension (N) The real and imaginary parts, respectively, of the computed eigenvalues. If two eigenvalues are computed as a complex conjugate pair, they are stored in consecutive elements of WR and WI, say the i-th and (i+1)th, with WI(i) > 0 and WI(i+1) < 0. If JOB = 'S', the eigenvalues are stored in the same order as on the diagonal of the Schur form returned in H, with WR(i) = H(i,i) and, if H(i:i+1,i:i+1) is a 2-by-2 diagonal block, WI(i) = sqrt(H(i+1,i)*H(i,i+1)) and WI(i+1) = -WI(i). Z (input/output) REAL array, dimension (LDZ,N) If COMPZ = 'N': Z is not referenced. If COMPZ = 'I': on entry, Z need not be set, and on exit, Z contains the orthogonal matrix Z of the Schur vectors of H. If COMPZ = 'V': on entry Z must contain an N-by-N matrix Q, which is assumed to be equal to the unit matrix except for the submatrix Z(ILO:IHI,ILO:IHI); on exit Z contains Q*Z. Normally Q is the orthogonal matrix generated by SORGHR after the call to SGEHRD which formed the Hessenberg matrix H. LDZ (input) INTEGER The leading dimension of the array Z. LDZ >= max(1,N) if COMPZ = 'I' or 'V'; LDZ >= 1 otherwise. WORK (workspace/output) REAL array, dimension (LWORK) On exit, if INFO = 0, WORK(1) returns the optimal LWORK. LWORK (input) INTEGER The dimension of the array WORK. LWORK >= max(1,N). If LWORK = -1, then a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued by XERBLA. INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value > 0: if INFO = i, SHSEQR failed to compute all of the eigenvalues in a total of 30*(IHI-ILO+1) iterations; elements 1:ilo-1 and i+1:n of WR and WI contain those eigenvalues which have been successfully computed. ===================================================================== Decode and test the input parameters */ /* Parameter adjustments */ h_dim1 = *ldh; h_offset = 1 + h_dim1; h__ -= h_offset; --wr; --wi; z_dim1 = *ldz; z_offset = 1 + z_dim1; z__ -= z_offset; --work; /* Function Body */ wantt = lsame_(job, "S"); initz = lsame_(compz, "I"); wantz = (initz) || (lsame_(compz, "V")); *info = 0; work[1] = (real) max(1,*n); lquery = *lwork == -1; if (! lsame_(job, "E") && ! wantt) { *info = -1; } else if (! lsame_(compz, "N") && ! wantz) { *info = -2; } else if (*n < 0) { *info = -3; } else if ((*ilo < 1) || (*ilo > max(1,*n))) { *info = -4; } else if ((*ihi < min(*ilo,*n)) || (*ihi > *n)) { *info = -5; } else if (*ldh < max(1,*n)) { *info = -7; } else if ((*ldz < 1) || (wantz && *ldz < max(1,*n))) { *info = -11; } else if (*lwork < max(1,*n) && ! lquery) { *info = -13; } if (*info != 0) { i__1 = -(*info); xerbla_("SHSEQR", &i__1); return 0; } else if (lquery) { return 0; } /* Initialize Z, if necessary */ if (initz) { slaset_("Full", n, n, &c_b320, &c_b1011, &z__[z_offset], ldz); } /* Store the eigenvalues isolated by SGEBAL. */ i__1 = *ilo - 1; for (i__ = 1; i__ <= i__1; ++i__) { wr[i__] = h__[i__ + i__ * h_dim1]; wi[i__] = 0.f; /* L10: */ } i__1 = *n; for (i__ = *ihi + 1; i__ <= i__1; ++i__) { wr[i__] = h__[i__ + i__ * h_dim1]; wi[i__] = 0.f; /* L20: */ } /* Quick return if possible. */ if (*n == 0) { return 0; } if (*ilo == *ihi) { wr[*ilo] = h__[*ilo + *ilo * h_dim1]; wi[*ilo] = 0.f; return 0; } /* Set rows and columns ILO to IHI to zero below the first subdiagonal. */ i__1 = *ihi - 2; for (j = *ilo; j <= i__1; ++j) { i__2 = *n; for (i__ = j + 2; i__ <= i__2; ++i__) { h__[i__ + j * h_dim1] = 0.f; /* L30: */ } /* L40: */ } nh = *ihi - *ilo + 1; /* Determine the order of the multi-shift QR algorithm to be used. Writing concatenation */ i__3[0] = 1, a__1[0] = job; i__3[1] = 1, a__1[1] = compz; s_cat(ch__1, a__1, i__3, &c__2, (ftnlen)2); ns = ilaenv_(&c__4, "SHSEQR", ch__1, n, ilo, ihi, &c_n1, (ftnlen)6, ( ftnlen)2); /* Writing concatenation */ i__3[0] = 1, a__1[0] = job; i__3[1] = 1, a__1[1] = compz; s_cat(ch__1, a__1, i__3, &c__2, (ftnlen)2); maxb = ilaenv_(&c__8, "SHSEQR", ch__1, n, ilo, ihi, &c_n1, (ftnlen)6, ( ftnlen)2); if (((ns <= 2) || (ns > nh)) || (maxb >= nh)) { /* Use the standard double-shift algorithm */ slahqr_(&wantt, &wantz, n, ilo, ihi, &h__[h_offset], ldh, &wr[1], &wi[ 1], ilo, ihi, &z__[z_offset], ldz, info); return 0; } maxb = max(3,maxb); /* Computing MIN */ i__1 = min(ns,maxb); ns = min(i__1,15); /* Now 2 < NS <= MAXB < NH. Set machine-dependent constants for the stopping criterion. If norm(H) <= sqrt(OVFL), overflow should not occur. */ unfl = slamch_("Safe minimum"); ovfl = 1.f / unfl; slabad_(&unfl, &ovfl); ulp = slamch_("Precision"); smlnum = unfl * (nh / ulp); /* I1 and I2 are the indices of the first row and last column of H to which transformations must be applied. If eigenvalues only are being computed, I1 and I2 are set inside the main loop. */ if (wantt) { i1 = 1; i2 = *n; } /* ITN is the total number of multiple-shift QR iterations allowed. */ itn = nh * 30; /* The main loop begins here. I is the loop index and decreases from IHI to ILO in steps of at most MAXB. Each iteration of the loop works with the active submatrix in rows and columns L to I. Eigenvalues I+1 to IHI have already converged. Either L = ILO or H(L,L-1) is negligible so that the matrix splits. */ i__ = *ihi; L50: l = *ilo; if (i__ < *ilo) { goto L170; } /* Perform multiple-shift QR iterations on rows and columns ILO to I until a submatrix of order at most MAXB splits off at the bottom because a subdiagonal element has become negligible. */ i__1 = itn; for (its = 0; its <= i__1; ++its) { /* Look for a single small subdiagonal element. */ i__2 = l + 1; for (k = i__; k >= i__2; --k) { tst1 = (r__1 = h__[k - 1 + (k - 1) * h_dim1], dabs(r__1)) + (r__2 = h__[k + k * h_dim1], dabs(r__2)); if (tst1 == 0.f) { i__4 = i__ - l + 1; tst1 = slanhs_("1", &i__4, &h__[l + l * h_dim1], ldh, &work[1] ); } /* Computing MAX */ r__2 = ulp * tst1; if ((r__1 = h__[k + (k - 1) * h_dim1], dabs(r__1)) <= dmax(r__2, smlnum)) { goto L70; } /* L60: */ } L70: l = k; if (l > *ilo) { /* H(L,L-1) is negligible. */ h__[l + (l - 1) * h_dim1] = 0.f; } /* Exit from loop if a submatrix of order <= MAXB has split off. */ if (l >= i__ - maxb + 1) { goto L160; } /* Now the active submatrix is in rows and columns L to I. If eigenvalues only are being computed, only the active submatrix need be transformed. */ if (! wantt) { i1 = l; i2 = i__; } if ((its == 20) || (its == 30)) { /* Exceptional shifts. */ i__2 = i__; for (ii = i__ - ns + 1; ii <= i__2; ++ii) { wr[ii] = ((r__1 = h__[ii + (ii - 1) * h_dim1], dabs(r__1)) + ( r__2 = h__[ii + ii * h_dim1], dabs(r__2))) * 1.5f; wi[ii] = 0.f; /* L80: */ } } else { /* Use eigenvalues of trailing submatrix of order NS as shifts. */ slacpy_("Full", &ns, &ns, &h__[i__ - ns + 1 + (i__ - ns + 1) * h_dim1], ldh, s, &c__15); slahqr_(&c_false, &c_false, &ns, &c__1, &ns, s, &c__15, &wr[i__ - ns + 1], &wi[i__ - ns + 1], &c__1, &ns, &z__[z_offset], ldz, &ierr); if (ierr > 0) { /* If SLAHQR failed to compute all NS eigenvalues, use the unconverged diagonal elements as the remaining shifts. */ i__2 = ierr; for (ii = 1; ii <= i__2; ++ii) { wr[i__ - ns + ii] = s[ii + ii * 15 - 16]; wi[i__ - ns + ii] = 0.f; /* L90: */ } } } /* Form the first column of (G-w(1)) (G-w(2)) . . . (G-w(ns)) where G is the Hessenberg submatrix H(L:I,L:I) and w is the vector of shifts (stored in WR and WI). The result is stored in the local array V. */ v[0] = 1.f; i__2 = ns + 1; for (ii = 2; ii <= i__2; ++ii) { v[ii - 1] = 0.f; /* L100: */ } nv = 1; i__2 = i__; for (j = i__ - ns + 1; j <= i__2; ++j) { if (wi[j] >= 0.f) { if (wi[j] == 0.f) { /* real shift */ i__4 = nv + 1; scopy_(&i__4, v, &c__1, vv, &c__1); i__4 = nv + 1; r__1 = -wr[j]; sgemv_("No transpose", &i__4, &nv, &c_b1011, &h__[l + l * h_dim1], ldh, vv, &c__1, &r__1, v, &c__1); ++nv; } else if (wi[j] > 0.f) { /* complex conjugate pair of shifts */ i__4 = nv + 1; scopy_(&i__4, v, &c__1, vv, &c__1); i__4 = nv + 1; r__1 = wr[j] * -2.f; sgemv_("No transpose", &i__4, &nv, &c_b1011, &h__[l + l * h_dim1], ldh, v, &c__1, &r__1, vv, &c__1); i__4 = nv + 1; itemp = isamax_(&i__4, vv, &c__1); /* Computing MAX */ r__2 = (r__1 = vv[itemp - 1], dabs(r__1)); temp = 1.f / dmax(r__2,smlnum); i__4 = nv + 1; sscal_(&i__4, &temp, vv, &c__1); absw = slapy2_(&wr[j], &wi[j]); temp = temp * absw * absw; i__4 = nv + 2; i__5 = nv + 1; sgemv_("No transpose", &i__4, &i__5, &c_b1011, &h__[l + l * h_dim1], ldh, vv, &c__1, &temp, v, &c__1); nv += 2; } /* Scale V(1:NV) so that max(abs(V(i))) = 1. If V is zero, reset it to the unit vector. */ itemp = isamax_(&nv, v, &c__1); temp = (r__1 = v[itemp - 1], dabs(r__1)); if (temp == 0.f) { v[0] = 1.f; i__4 = nv; for (ii = 2; ii <= i__4; ++ii) { v[ii - 1] = 0.f; /* L110: */ } } else { temp = dmax(temp,smlnum); r__1 = 1.f / temp; sscal_(&nv, &r__1, v, &c__1); } } /* L120: */ } /* Multiple-shift QR step */ i__2 = i__ - 1; for (k = l; k <= i__2; ++k) { /* The first iteration of this loop determines a reflection G from the vector V and applies it from left and right to H, thus creating a nonzero bulge below the subdiagonal. Each subsequent iteration determines a reflection G to restore the Hessenberg form in the (K-1)th column, and thus chases the bulge one step toward the bottom of the active submatrix. NR is the order of G. Computing MIN */ i__4 = ns + 1, i__5 = i__ - k + 1; nr = min(i__4,i__5); if (k > l) { scopy_(&nr, &h__[k + (k - 1) * h_dim1], &c__1, v, &c__1); } slarfg_(&nr, v, &v[1], &c__1, &tau); if (k > l) { h__[k + (k - 1) * h_dim1] = v[0]; i__4 = i__; for (ii = k + 1; ii <= i__4; ++ii) { h__[ii + (k - 1) * h_dim1] = 0.f; /* L130: */ } } v[0] = 1.f; /* Apply G from the left to transform the rows of the matrix in columns K to I2. */ i__4 = i2 - k + 1; slarfx_("Left", &nr, &i__4, v, &tau, &h__[k + k * h_dim1], ldh, & work[1]); /* Apply G from the right to transform the columns of the matrix in rows I1 to min(K+NR,I). Computing MIN */ i__5 = k + nr; i__4 = min(i__5,i__) - i1 + 1; slarfx_("Right", &i__4, &nr, v, &tau, &h__[i1 + k * h_dim1], ldh, &work[1]); if (wantz) { /* Accumulate transformations in the matrix Z */ slarfx_("Right", &nh, &nr, v, &tau, &z__[*ilo + k * z_dim1], ldz, &work[1]); } /* L140: */ } /* L150: */ } /* Failure to converge in remaining number of iterations */ *info = i__; return 0; L160: /* A submatrix of order <= MAXB in rows and columns L to I has split off. Use the double-shift QR algorithm to handle it. */ slahqr_(&wantt, &wantz, n, &l, &i__, &h__[h_offset], ldh, &wr[1], &wi[1], ilo, ihi, &z__[z_offset], ldz, info); if (*info > 0) { return 0; } /* Decrement number of remaining iterations, and return to start of the main loop with a new value of I. */ itn -= its; i__ = l - 1; goto L50; L170: work[1] = (real) max(1,*n); return 0; /* End of SHSEQR */ } /* shseqr_ */ /* Subroutine */ int slabad_(real *small, real *large) { /* Builtin functions */ double r_lg10(real *), sqrt(doublereal); /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University October 31, 1992 Purpose ======= SLABAD takes as input the values computed by SLAMCH for underflow and overflow, and returns the square root of each of these values if the log of LARGE is sufficiently large. This subroutine is intended to identify machines with a large exponent range, such as the Crays, and redefine the underflow and overflow limits to be the square roots of the values computed by SLAMCH. This subroutine is needed because SLAMCH does not compensate for poor arithmetic in the upper half of the exponent range, as is found on a Cray. Arguments ========= SMALL (input/output) REAL On entry, the underflow threshold as computed by SLAMCH. On exit, if LOG10(LARGE) is sufficiently large, the square root of SMALL, otherwise unchanged. LARGE (input/output) REAL On entry, the overflow threshold as computed by SLAMCH. On exit, if LOG10(LARGE) is sufficiently large, the square root of LARGE, otherwise unchanged. ===================================================================== If it looks like we're on a Cray, take the square root of SMALL and LARGE to avoid overflow and underflow problems. */ if (r_lg10(large) > 2e3f) { *small = sqrt(*small); *large = sqrt(*large); } return 0; /* End of SLABAD */ } /* slabad_ */ /* Subroutine */ int slabrd_(integer *m, integer *n, integer *nb, real *a, integer *lda, real *d__, real *e, real *tauq, real *taup, real *x, integer *ldx, real *y, integer *ldy) { /* System generated locals */ integer a_dim1, a_offset, x_dim1, x_offset, y_dim1, y_offset, i__1, i__2, i__3; /* Local variables */ static integer i__; extern /* Subroutine */ int sscal_(integer *, real *, real *, integer *), sgemv_(char *, integer *, integer *, real *, real *, integer *, real *, integer *, real *, real *, integer *), slarfg_( integer *, real *, real *, integer *, real *); /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University February 29, 1992 Purpose ======= SLABRD reduces the first NB rows and columns of a real general m by n matrix A to upper or lower bidiagonal form by an orthogonal transformation Q' * A * P, and returns the matrices X and Y which are needed to apply the transformation to the unreduced part of A. If m >= n, A is reduced to upper bidiagonal form; if m < n, to lower bidiagonal form. This is an auxiliary routine called by SGEBRD Arguments ========= M (input) INTEGER The number of rows in the matrix A. N (input) INTEGER The number of columns in the matrix A. NB (input) INTEGER The number of leading rows and columns of A to be reduced. A (input/output) REAL array, dimension (LDA,N) On entry, the m by n general matrix to be reduced. On exit, the first NB rows and columns of the matrix are overwritten; the rest of the array is unchanged. If m >= n, elements on and below the diagonal in the first NB columns, with the array TAUQ, represent the orthogonal matrix Q as a product of elementary reflectors; and elements above the diagonal in the first NB rows, with the array TAUP, represent the orthogonal matrix P as a product of elementary reflectors. If m < n, elements below the diagonal in the first NB columns, with the array TAUQ, represent the orthogonal matrix Q as a product of elementary reflectors, and elements on and above the diagonal in the first NB rows, with the array TAUP, represent the orthogonal matrix P as a product of elementary reflectors. See Further Details. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,M). D (output) REAL array, dimension (NB) The diagonal elements of the first NB rows and columns of the reduced matrix. D(i) = A(i,i). E (output) REAL array, dimension (NB) The off-diagonal elements of the first NB rows and columns of the reduced matrix. TAUQ (output) REAL array dimension (NB) The scalar factors of the elementary reflectors which represent the orthogonal matrix Q. See Further Details. TAUP (output) REAL array, dimension (NB) The scalar factors of the elementary reflectors which represent the orthogonal matrix P. See Further Details. X (output) REAL array, dimension (LDX,NB) The m-by-nb matrix X required to update the unreduced part of A. LDX (input) INTEGER The leading dimension of the array X. LDX >= M. Y (output) REAL array, dimension (LDY,NB) The n-by-nb matrix Y required to update the unreduced part of A. LDY (output) INTEGER The leading dimension of the array Y. LDY >= N. Further Details =============== The matrices Q and P are represented as products of elementary reflectors: Q = H(1) H(2) . . . H(nb) and P = G(1) G(2) . . . G(nb) Each H(i) and G(i) has the form: H(i) = I - tauq * v * v' and G(i) = I - taup * u * u' where tauq and taup are real scalars, and v and u are real vectors. If m >= n, v(1:i-1) = 0, v(i) = 1, and v(i:m) is stored on exit in A(i:m,i); u(1:i) = 0, u(i+1) = 1, and u(i+1:n) is stored on exit in A(i,i+1:n); tauq is stored in TAUQ(i) and taup in TAUP(i). If m < n, v(1:i) = 0, v(i+1) = 1, and v(i+1:m) is stored on exit in A(i+2:m,i); u(1:i-1) = 0, u(i) = 1, and u(i:n) is stored on exit in A(i,i+1:n); tauq is stored in TAUQ(i) and taup in TAUP(i). The elements of the vectors v and u together form the m-by-nb matrix V and the nb-by-n matrix U' which are needed, with X and Y, to apply the transformation to the unreduced part of the matrix, using a block update of the form: A := A - V*Y' - X*U'. The contents of A on exit are illustrated by the following examples with nb = 2: m = 6 and n = 5 (m > n): m = 5 and n = 6 (m < n): ( 1 1 u1 u1 u1 ) ( 1 u1 u1 u1 u1 u1 ) ( v1 1 1 u2 u2 ) ( 1 1 u2 u2 u2 u2 ) ( v1 v2 a a a ) ( v1 1 a a a a ) ( v1 v2 a a a ) ( v1 v2 a a a a ) ( v1 v2 a a a ) ( v1 v2 a a a a ) ( v1 v2 a a a ) where a denotes an element of the original matrix which is unchanged, vi denotes an element of the vector defining H(i), and ui an element of the vector defining G(i). ===================================================================== Quick return if possible */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --d__; --e; --tauq; --taup; x_dim1 = *ldx; x_offset = 1 + x_dim1; x -= x_offset; y_dim1 = *ldy; y_offset = 1 + y_dim1; y -= y_offset; /* Function Body */ if ((*m <= 0) || (*n <= 0)) { return 0; } if (*m >= *n) { /* Reduce to upper bidiagonal form */ i__1 = *nb; for (i__ = 1; i__ <= i__1; ++i__) { /* Update A(i:m,i) */ i__2 = *m - i__ + 1; i__3 = i__ - 1; sgemv_("No transpose", &i__2, &i__3, &c_b1290, &a[i__ + a_dim1], lda, &y[i__ + y_dim1], ldy, &c_b1011, &a[i__ + i__ * a_dim1], &c__1); i__2 = *m - i__ + 1; i__3 = i__ - 1; sgemv_("No transpose", &i__2, &i__3, &c_b1290, &x[i__ + x_dim1], ldx, &a[i__ * a_dim1 + 1], &c__1, &c_b1011, &a[i__ + i__ * a_dim1], &c__1); /* Generate reflection Q(i) to annihilate A(i+1:m,i) */ i__2 = *m - i__ + 1; /* Computing MIN */ i__3 = i__ + 1; slarfg_(&i__2, &a[i__ + i__ * a_dim1], &a[min(i__3,*m) + i__ * a_dim1], &c__1, &tauq[i__]); d__[i__] = a[i__ + i__ * a_dim1]; if (i__ < *n) { a[i__ + i__ * a_dim1] = 1.f; /* Compute Y(i+1:n,i) */ i__2 = *m - i__ + 1; i__3 = *n - i__; sgemv_("Transpose", &i__2, &i__3, &c_b1011, &a[i__ + (i__ + 1) * a_dim1], lda, &a[i__ + i__ * a_dim1], &c__1, & c_b320, &y[i__ + 1 + i__ * y_dim1], &c__1); i__2 = *m - i__ + 1; i__3 = i__ - 1; sgemv_("Transpose", &i__2, &i__3, &c_b1011, &a[i__ + a_dim1], lda, &a[i__ + i__ * a_dim1], &c__1, &c_b320, &y[i__ * y_dim1 + 1], &c__1); i__2 = *n - i__; i__3 = i__ - 1; sgemv_("No transpose", &i__2, &i__3, &c_b1290, &y[i__ + 1 + y_dim1], ldy, &y[i__ * y_dim1 + 1], &c__1, &c_b1011, & y[i__ + 1 + i__ * y_dim1], &c__1); i__2 = *m - i__ + 1; i__3 = i__ - 1; sgemv_("Transpose", &i__2, &i__3, &c_b1011, &x[i__ + x_dim1], ldx, &a[i__ + i__ * a_dim1], &c__1, &c_b320, &y[i__ * y_dim1 + 1], &c__1); i__2 = i__ - 1; i__3 = *n - i__; sgemv_("Transpose", &i__2, &i__3, &c_b1290, &a[(i__ + 1) * a_dim1 + 1], lda, &y[i__ * y_dim1 + 1], &c__1, & c_b1011, &y[i__ + 1 + i__ * y_dim1], &c__1) ; i__2 = *n - i__; sscal_(&i__2, &tauq[i__], &y[i__ + 1 + i__ * y_dim1], &c__1); /* Update A(i,i+1:n) */ i__2 = *n - i__; sgemv_("No transpose", &i__2, &i__, &c_b1290, &y[i__ + 1 + y_dim1], ldy, &a[i__ + a_dim1], lda, &c_b1011, &a[i__ + (i__ + 1) * a_dim1], lda); i__2 = i__ - 1; i__3 = *n - i__; sgemv_("Transpose", &i__2, &i__3, &c_b1290, &a[(i__ + 1) * a_dim1 + 1], lda, &x[i__ + x_dim1], ldx, &c_b1011, &a[ i__ + (i__ + 1) * a_dim1], lda); /* Generate reflection P(i) to annihilate A(i,i+2:n) */ i__2 = *n - i__; /* Computing MIN */ i__3 = i__ + 2; slarfg_(&i__2, &a[i__ + (i__ + 1) * a_dim1], &a[i__ + min( i__3,*n) * a_dim1], lda, &taup[i__]); e[i__] = a[i__ + (i__ + 1) * a_dim1]; a[i__ + (i__ + 1) * a_dim1] = 1.f; /* Compute X(i+1:m,i) */ i__2 = *m - i__; i__3 = *n - i__; sgemv_("No transpose", &i__2, &i__3, &c_b1011, &a[i__ + 1 + ( i__ + 1) * a_dim1], lda, &a[i__ + (i__ + 1) * a_dim1], lda, &c_b320, &x[i__ + 1 + i__ * x_dim1], &c__1); i__2 = *n - i__; sgemv_("Transpose", &i__2, &i__, &c_b1011, &y[i__ + 1 + y_dim1], ldy, &a[i__ + (i__ + 1) * a_dim1], lda, & c_b320, &x[i__ * x_dim1 + 1], &c__1); i__2 = *m - i__; sgemv_("No transpose", &i__2, &i__, &c_b1290, &a[i__ + 1 + a_dim1], lda, &x[i__ * x_dim1 + 1], &c__1, &c_b1011, & x[i__ + 1 + i__ * x_dim1], &c__1); i__2 = i__ - 1; i__3 = *n - i__; sgemv_("No transpose", &i__2, &i__3, &c_b1011, &a[(i__ + 1) * a_dim1 + 1], lda, &a[i__ + (i__ + 1) * a_dim1], lda, & c_b320, &x[i__ * x_dim1 + 1], &c__1); i__2 = *m - i__; i__3 = i__ - 1; sgemv_("No transpose", &i__2, &i__3, &c_b1290, &x[i__ + 1 + x_dim1], ldx, &x[i__ * x_dim1 + 1], &c__1, &c_b1011, & x[i__ + 1 + i__ * x_dim1], &c__1); i__2 = *m - i__; sscal_(&i__2, &taup[i__], &x[i__ + 1 + i__ * x_dim1], &c__1); } /* L10: */ } } else { /* Reduce to lower bidiagonal form */ i__1 = *nb; for (i__ = 1; i__ <= i__1; ++i__) { /* Update A(i,i:n) */ i__2 = *n - i__ + 1; i__3 = i__ - 1; sgemv_("No transpose", &i__2, &i__3, &c_b1290, &y[i__ + y_dim1], ldy, &a[i__ + a_dim1], lda, &c_b1011, &a[i__ + i__ * a_dim1], lda); i__2 = i__ - 1; i__3 = *n - i__ + 1; sgemv_("Transpose", &i__2, &i__3, &c_b1290, &a[i__ * a_dim1 + 1], lda, &x[i__ + x_dim1], ldx, &c_b1011, &a[i__ + i__ * a_dim1], lda); /* Generate reflection P(i) to annihilate A(i,i+1:n) */ i__2 = *n - i__ + 1; /* Computing MIN */ i__3 = i__ + 1; slarfg_(&i__2, &a[i__ + i__ * a_dim1], &a[i__ + min(i__3,*n) * a_dim1], lda, &taup[i__]); d__[i__] = a[i__ + i__ * a_dim1]; if (i__ < *m) { a[i__ + i__ * a_dim1] = 1.f; /* Compute X(i+1:m,i) */ i__2 = *m - i__; i__3 = *n - i__ + 1; sgemv_("No transpose", &i__2, &i__3, &c_b1011, &a[i__ + 1 + i__ * a_dim1], lda, &a[i__ + i__ * a_dim1], lda, & c_b320, &x[i__ + 1 + i__ * x_dim1], &c__1) ; i__2 = *n - i__ + 1; i__3 = i__ - 1; sgemv_("Transpose", &i__2, &i__3, &c_b1011, &y[i__ + y_dim1], ldy, &a[i__ + i__ * a_dim1], lda, &c_b320, &x[i__ * x_dim1 + 1], &c__1); i__2 = *m - i__; i__3 = i__ - 1; sgemv_("No transpose", &i__2, &i__3, &c_b1290, &a[i__ + 1 + a_dim1], lda, &x[i__ * x_dim1 + 1], &c__1, &c_b1011, & x[i__ + 1 + i__ * x_dim1], &c__1); i__2 = i__ - 1; i__3 = *n - i__ + 1; sgemv_("No transpose", &i__2, &i__3, &c_b1011, &a[i__ * a_dim1 + 1], lda, &a[i__ + i__ * a_dim1], lda, & c_b320, &x[i__ * x_dim1 + 1], &c__1); i__2 = *m - i__; i__3 = i__ - 1; sgemv_("No transpose", &i__2, &i__3, &c_b1290, &x[i__ + 1 + x_dim1], ldx, &x[i__ * x_dim1 + 1], &c__1, &c_b1011, & x[i__ + 1 + i__ * x_dim1], &c__1); i__2 = *m - i__; sscal_(&i__2, &taup[i__], &x[i__ + 1 + i__ * x_dim1], &c__1); /* Update A(i+1:m,i) */ i__2 = *m - i__; i__3 = i__ - 1; sgemv_("No transpose", &i__2, &i__3, &c_b1290, &a[i__ + 1 + a_dim1], lda, &y[i__ + y_dim1], ldy, &c_b1011, &a[i__ + 1 + i__ * a_dim1], &c__1); i__2 = *m - i__; sgemv_("No transpose", &i__2, &i__, &c_b1290, &x[i__ + 1 + x_dim1], ldx, &a[i__ * a_dim1 + 1], &c__1, &c_b1011, & a[i__ + 1 + i__ * a_dim1], &c__1); /* Generate reflection Q(i) to annihilate A(i+2:m,i) */ i__2 = *m - i__; /* Computing MIN */ i__3 = i__ + 2; slarfg_(&i__2, &a[i__ + 1 + i__ * a_dim1], &a[min(i__3,*m) + i__ * a_dim1], &c__1, &tauq[i__]); e[i__] = a[i__ + 1 + i__ * a_dim1]; a[i__ + 1 + i__ * a_dim1] = 1.f; /* Compute Y(i+1:n,i) */ i__2 = *m - i__; i__3 = *n - i__; sgemv_("Transpose", &i__2, &i__3, &c_b1011, &a[i__ + 1 + (i__ + 1) * a_dim1], lda, &a[i__ + 1 + i__ * a_dim1], & c__1, &c_b320, &y[i__ + 1 + i__ * y_dim1], &c__1); i__2 = *m - i__; i__3 = i__ - 1; sgemv_("Transpose", &i__2, &i__3, &c_b1011, &a[i__ + 1 + a_dim1], lda, &a[i__ + 1 + i__ * a_dim1], &c__1, & c_b320, &y[i__ * y_dim1 + 1], &c__1); i__2 = *n - i__; i__3 = i__ - 1; sgemv_("No transpose", &i__2, &i__3, &c_b1290, &y[i__ + 1 + y_dim1], ldy, &y[i__ * y_dim1 + 1], &c__1, &c_b1011, & y[i__ + 1 + i__ * y_dim1], &c__1); i__2 = *m - i__; sgemv_("Transpose", &i__2, &i__, &c_b1011, &x[i__ + 1 + x_dim1], ldx, &a[i__ + 1 + i__ * a_dim1], &c__1, & c_b320, &y[i__ * y_dim1 + 1], &c__1); i__2 = *n - i__; sgemv_("Transpose", &i__, &i__2, &c_b1290, &a[(i__ + 1) * a_dim1 + 1], lda, &y[i__ * y_dim1 + 1], &c__1, & c_b1011, &y[i__ + 1 + i__ * y_dim1], &c__1) ; i__2 = *n - i__; sscal_(&i__2, &tauq[i__], &y[i__ + 1 + i__ * y_dim1], &c__1); } /* L20: */ } } return 0; /* End of SLABRD */ } /* slabrd_ */ /* Subroutine */ int slacpy_(char *uplo, integer *m, integer *n, real *a, integer *lda, real *b, integer *ldb) { /* System generated locals */ integer a_dim1, a_offset, b_dim1, b_offset, i__1, i__2; /* Local variables */ static integer i__, j; extern logical lsame_(char *, char *); /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University February 29, 1992 Purpose ======= SLACPY copies all or part of a two-dimensional matrix A to another matrix B. Arguments ========= UPLO (input) CHARACTER*1 Specifies the part of the matrix A to be copied to B. = 'U': Upper triangular part = 'L': Lower triangular part Otherwise: All of the matrix A M (input) INTEGER The number of rows of the matrix A. M >= 0. N (input) INTEGER The number of columns of the matrix A. N >= 0. A (input) REAL array, dimension (LDA,N) The m by n matrix A. If UPLO = 'U', only the upper triangle or trapezoid is accessed; if UPLO = 'L', only the lower triangle or trapezoid is accessed. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,M). B (output) REAL array, dimension (LDB,N) On exit, B = A in the locations specified by UPLO. LDB (input) INTEGER The leading dimension of the array B. LDB >= max(1,M). ===================================================================== */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; b_dim1 = *ldb; b_offset = 1 + b_dim1; b -= b_offset; /* Function Body */ if (lsame_(uplo, "U")) { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = min(j,*m); for (i__ = 1; i__ <= i__2; ++i__) { b[i__ + j * b_dim1] = a[i__ + j * a_dim1]; /* L10: */ } /* L20: */ } } else if (lsame_(uplo, "L")) { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = j; i__ <= i__2; ++i__) { b[i__ + j * b_dim1] = a[i__ + j * a_dim1]; /* L30: */ } /* L40: */ } } else { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { b[i__ + j * b_dim1] = a[i__ + j * a_dim1]; /* L50: */ } /* L60: */ } } return 0; /* End of SLACPY */ } /* slacpy_ */ /* Subroutine */ int sladiv_(real *a, real *b, real *c__, real *d__, real *p, real *q) { static real e, f; /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University October 31, 1992 Purpose ======= SLADIV performs complex division in real arithmetic a + i*b p + i*q = --------- c + i*d The algorithm is due to Robert L. Smith and can be found in D. Knuth, The art of Computer Programming, Vol.2, p.195 Arguments ========= A (input) REAL B (input) REAL C (input) REAL D (input) REAL The scalars a, b, c, and d in the above expression. P (output) REAL Q (output) REAL The scalars p and q in the above expression. ===================================================================== */ if (dabs(*d__) < dabs(*c__)) { e = *d__ / *c__; f = *c__ + *d__ * e; *p = (*a + *b * e) / f; *q = (*b - *a * e) / f; } else { e = *c__ / *d__; f = *d__ + *c__ * e; *p = (*b + *a * e) / f; *q = (-(*a) + *b * e) / f; } return 0; /* End of SLADIV */ } /* sladiv_ */ /* Subroutine */ int slae2_(real *a, real *b, real *c__, real *rt1, real *rt2) { /* System generated locals */ real r__1; /* Builtin functions */ double sqrt(doublereal); /* Local variables */ static real ab, df, tb, sm, rt, adf, acmn, acmx; /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University October 31, 1992 Purpose ======= SLAE2 computes the eigenvalues of a 2-by-2 symmetric matrix [ A B ] [ B C ]. On return, RT1 is the eigenvalue of larger absolute value, and RT2 is the eigenvalue of smaller absolute value. Arguments ========= A (input) REAL The (1,1) element of the 2-by-2 matrix. B (input) REAL The (1,2) and (2,1) elements of the 2-by-2 matrix. C (input) REAL The (2,2) element of the 2-by-2 matrix. RT1 (output) REAL The eigenvalue of larger absolute value. RT2 (output) REAL The eigenvalue of smaller absolute value. Further Details =============== RT1 is accurate to a few ulps barring over/underflow. RT2 may be inaccurate if there is massive cancellation in the determinant A*C-B*B; higher precision or correctly rounded or correctly truncated arithmetic would be needed to compute RT2 accurately in all cases. Overflow is possible only if RT1 is within a factor of 5 of overflow. Underflow is harmless if the input data is 0 or exceeds underflow_threshold / macheps. ===================================================================== Compute the eigenvalues */ sm = *a + *c__; df = *a - *c__; adf = dabs(df); tb = *b + *b; ab = dabs(tb); if (dabs(*a) > dabs(*c__)) { acmx = *a; acmn = *c__; } else { acmx = *c__; acmn = *a; } if (adf > ab) { /* Computing 2nd power */ r__1 = ab / adf; rt = adf * sqrt(r__1 * r__1 + 1.f); } else if (adf < ab) { /* Computing 2nd power */ r__1 = adf / ab; rt = ab * sqrt(r__1 * r__1 + 1.f); } else { /* Includes case AB=ADF=0 */ rt = ab * sqrt(2.f); } if (sm < 0.f) { *rt1 = (sm - rt) * .5f; /* Order of execution important. To get fully accurate smaller eigenvalue, next line needs to be executed in higher precision. */ *rt2 = acmx / *rt1 * acmn - *b / *rt1 * *b; } else if (sm > 0.f) { *rt1 = (sm + rt) * .5f; /* Order of execution important. To get fully accurate smaller eigenvalue, next line needs to be executed in higher precision. */ *rt2 = acmx / *rt1 * acmn - *b / *rt1 * *b; } else { /* Includes case RT1 = RT2 = 0 */ *rt1 = rt * .5f; *rt2 = rt * -.5f; } return 0; /* End of SLAE2 */ } /* slae2_ */ /* Subroutine */ int slaed0_(integer *icompq, integer *qsiz, integer *n, real *d__, real *e, real *q, integer *ldq, real *qstore, integer *ldqs, real *work, integer *iwork, integer *info) { /* System generated locals */ integer q_dim1, q_offset, qstore_dim1, qstore_offset, i__1, i__2; real r__1; /* Builtin functions */ double log(doublereal); integer pow_ii(integer *, integer *); /* Local variables */ static integer i__, j, k, iq, lgn, msd2, smm1, spm1, spm2; static real temp; static integer curr; extern /* Subroutine */ int sgemm_(char *, char *, integer *, integer *, integer *, real *, real *, integer *, real *, integer *, real *, real *, integer *); static integer iperm, indxq, iwrem; extern /* Subroutine */ int scopy_(integer *, real *, integer *, real *, integer *); static integer iqptr, tlvls; extern /* Subroutine */ int slaed1_(integer *, real *, real *, integer *, integer *, real *, integer *, real *, integer *, integer *), slaed7_(integer *, integer *, integer *, integer *, integer *, integer *, real *, real *, integer *, integer *, real *, integer * , real *, integer *, integer *, integer *, integer *, integer *, real *, real *, integer *, integer *); static integer igivcl; extern /* Subroutine */ int xerbla_(char *, integer *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); static integer igivnm, submat; extern /* Subroutine */ int slacpy_(char *, integer *, integer *, real *, integer *, real *, integer *); static integer curprb, subpbs, igivpt, curlvl, matsiz, iprmpt, smlsiz; extern /* Subroutine */ int ssteqr_(char *, integer *, real *, real *, real *, integer *, real *, integer *); /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= SLAED0 computes all eigenvalues and corresponding eigenvectors of a symmetric tridiagonal matrix using the divide and conquer method. Arguments ========= ICOMPQ (input) INTEGER = 0: Compute eigenvalues only. = 1: Compute eigenvectors of original dense symmetric matrix also. On entry, Q contains the orthogonal matrix used to reduce the original matrix to tridiagonal form. = 2: Compute eigenvalues and eigenvectors of tridiagonal matrix. QSIZ (input) INTEGER The dimension of the orthogonal matrix used to reduce the full matrix to tridiagonal form. QSIZ >= N if ICOMPQ = 1. N (input) INTEGER The dimension of the symmetric tridiagonal matrix. N >= 0. D (input/output) REAL array, dimension (N) On entry, the main diagonal of the tridiagonal matrix. On exit, its eigenvalues. E (input) REAL array, dimension (N-1) The off-diagonal elements of the tridiagonal matrix. On exit, E has been destroyed. Q (input/output) REAL array, dimension (LDQ, N) On entry, Q must contain an N-by-N orthogonal matrix. If ICOMPQ = 0 Q is not referenced. If ICOMPQ = 1 On entry, Q is a subset of the columns of the orthogonal matrix used to reduce the full matrix to tridiagonal form corresponding to the subset of the full matrix which is being decomposed at this time. If ICOMPQ = 2 On entry, Q will be the identity matrix. On exit, Q contains the eigenvectors of the tridiagonal matrix. LDQ (input) INTEGER The leading dimension of the array Q. If eigenvectors are desired, then LDQ >= max(1,N). In any case, LDQ >= 1. QSTORE (workspace) REAL array, dimension (LDQS, N) Referenced only when ICOMPQ = 1. Used to store parts of the eigenvector matrix when the updating matrix multiplies take place. LDQS (input) INTEGER The leading dimension of the array QSTORE. If ICOMPQ = 1, then LDQS >= max(1,N). In any case, LDQS >= 1. WORK (workspace) REAL array, If ICOMPQ = 0 or 1, the dimension of WORK must be at least 1 + 3*N + 2*N*lg N + 2*N**2 ( lg( N ) = smallest integer k such that 2^k >= N ) If ICOMPQ = 2, the dimension of WORK must be at least 4*N + N**2. IWORK (workspace) INTEGER array, If ICOMPQ = 0 or 1, the dimension of IWORK must be at least 6 + 6*N + 5*N*lg N. ( lg( N ) = smallest integer k such that 2^k >= N ) If ICOMPQ = 2, the dimension of IWORK must be at least 3 + 5*N. INFO (output) INTEGER = 0: successful exit. < 0: if INFO = -i, the i-th argument had an illegal value. > 0: The algorithm failed to compute an eigenvalue while working on the submatrix lying in rows and columns INFO/(N+1) through mod(INFO,N+1). Further Details =============== Based on contributions by Jeff Rutter, Computer Science Division, University of California at Berkeley, USA ===================================================================== Test the input parameters. */ /* Parameter adjustments */ --d__; --e; q_dim1 = *ldq; q_offset = 1 + q_dim1; q -= q_offset; qstore_dim1 = *ldqs; qstore_offset = 1 + qstore_dim1; qstore -= qstore_offset; --work; --iwork; /* Function Body */ *info = 0; if ((*icompq < 0) || (*icompq > 2)) { *info = -1; } else if (*icompq == 1 && *qsiz < max(0,*n)) { *info = -2; } else if (*n < 0) { *info = -3; } else if (*ldq < max(1,*n)) { *info = -7; } else if (*ldqs < max(1,*n)) { *info = -9; } if (*info != 0) { i__1 = -(*info); xerbla_("SLAED0", &i__1); return 0; } /* Quick return if possible */ if (*n == 0) { return 0; } smlsiz = ilaenv_(&c__9, "SLAED0", " ", &c__0, &c__0, &c__0, &c__0, ( ftnlen)6, (ftnlen)1); /* Determine the size and placement of the submatrices, and save in the leading elements of IWORK. */ iwork[1] = *n; subpbs = 1; tlvls = 0; L10: if (iwork[subpbs] > smlsiz) { for (j = subpbs; j >= 1; --j) { iwork[j * 2] = (iwork[j] + 1) / 2; iwork[((j) << (1)) - 1] = iwork[j] / 2; /* L20: */ } ++tlvls; subpbs <<= 1; goto L10; } i__1 = subpbs; for (j = 2; j <= i__1; ++j) { iwork[j] += iwork[j - 1]; /* L30: */ } /* Divide the matrix into SUBPBS submatrices of size at most SMLSIZ+1 using rank-1 modifications (cuts). */ spm1 = subpbs - 1; i__1 = spm1; for (i__ = 1; i__ <= i__1; ++i__) { submat = iwork[i__] + 1; smm1 = submat - 1; d__[smm1] -= (r__1 = e[smm1], dabs(r__1)); d__[submat] -= (r__1 = e[smm1], dabs(r__1)); /* L40: */ } indxq = ((*n) << (2)) + 3; if (*icompq != 2) { /* Set up workspaces for eigenvalues only/accumulate new vectors routine */ temp = log((real) (*n)) / log(2.f); lgn = (integer) temp; if (pow_ii(&c__2, &lgn) < *n) { ++lgn; } if (pow_ii(&c__2, &lgn) < *n) { ++lgn; } iprmpt = indxq + *n + 1; iperm = iprmpt + *n * lgn; iqptr = iperm + *n * lgn; igivpt = iqptr + *n + 2; igivcl = igivpt + *n * lgn; igivnm = 1; iq = igivnm + ((*n) << (1)) * lgn; /* Computing 2nd power */ i__1 = *n; iwrem = iq + i__1 * i__1 + 1; /* Initialize pointers */ i__1 = subpbs; for (i__ = 0; i__ <= i__1; ++i__) { iwork[iprmpt + i__] = 1; iwork[igivpt + i__] = 1; /* L50: */ } iwork[iqptr] = 1; } /* Solve each submatrix eigenproblem at the bottom of the divide and conquer tree. */ curr = 0; i__1 = spm1; for (i__ = 0; i__ <= i__1; ++i__) { if (i__ == 0) { submat = 1; matsiz = iwork[1]; } else { submat = iwork[i__] + 1; matsiz = iwork[i__ + 1] - iwork[i__]; } if (*icompq == 2) { ssteqr_("I", &matsiz, &d__[submat], &e[submat], &q[submat + submat * q_dim1], ldq, &work[1], info); if (*info != 0) { goto L130; } } else { ssteqr_("I", &matsiz, &d__[submat], &e[submat], &work[iq - 1 + iwork[iqptr + curr]], &matsiz, &work[1], info); if (*info != 0) { goto L130; } if (*icompq == 1) { sgemm_("N", "N", qsiz, &matsiz, &matsiz, &c_b1011, &q[submat * q_dim1 + 1], ldq, &work[iq - 1 + iwork[iqptr + curr]] , &matsiz, &c_b320, &qstore[submat * qstore_dim1 + 1], ldqs); } /* Computing 2nd power */ i__2 = matsiz; iwork[iqptr + curr + 1] = iwork[iqptr + curr] + i__2 * i__2; ++curr; } k = 1; i__2 = iwork[i__ + 1]; for (j = submat; j <= i__2; ++j) { iwork[indxq + j] = k; ++k; /* L60: */ } /* L70: */ } /* Successively merge eigensystems of adjacent submatrices into eigensystem for the corresponding larger matrix. while ( SUBPBS > 1 ) */ curlvl = 1; L80: if (subpbs > 1) { spm2 = subpbs - 2; i__1 = spm2; for (i__ = 0; i__ <= i__1; i__ += 2) { if (i__ == 0) { submat = 1; matsiz = iwork[2]; msd2 = iwork[1]; curprb = 0; } else { submat = iwork[i__] + 1; matsiz = iwork[i__ + 2] - iwork[i__]; msd2 = matsiz / 2; ++curprb; } /* Merge lower order eigensystems (of size MSD2 and MATSIZ - MSD2) into an eigensystem of size MATSIZ. SLAED1 is used only for the full eigensystem of a tridiagonal matrix. SLAED7 handles the cases in which eigenvalues only or eigenvalues and eigenvectors of a full symmetric matrix (which was reduced to tridiagonal form) are desired. */ if (*icompq == 2) { slaed1_(&matsiz, &d__[submat], &q[submat + submat * q_dim1], ldq, &iwork[indxq + submat], &e[submat + msd2 - 1], & msd2, &work[1], &iwork[subpbs + 1], info); } else { slaed7_(icompq, &matsiz, qsiz, &tlvls, &curlvl, &curprb, &d__[ submat], &qstore[submat * qstore_dim1 + 1], ldqs, & iwork[indxq + submat], &e[submat + msd2 - 1], &msd2, & work[iq], &iwork[iqptr], &iwork[iprmpt], &iwork[iperm] , &iwork[igivpt], &iwork[igivcl], &work[igivnm], & work[iwrem], &iwork[subpbs + 1], info); } if (*info != 0) { goto L130; } iwork[i__ / 2 + 1] = iwork[i__ + 2]; /* L90: */ } subpbs /= 2; ++curlvl; goto L80; } /* end while Re-merge the eigenvalues/vectors which were deflated at the final merge step. */ if (*icompq == 1) { i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { j = iwork[indxq + i__]; work[i__] = d__[j]; scopy_(qsiz, &qstore[j * qstore_dim1 + 1], &c__1, &q[i__ * q_dim1 + 1], &c__1); /* L100: */ } scopy_(n, &work[1], &c__1, &d__[1], &c__1); } else if (*icompq == 2) { i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { j = iwork[indxq + i__]; work[i__] = d__[j]; scopy_(n, &q[j * q_dim1 + 1], &c__1, &work[*n * i__ + 1], &c__1); /* L110: */ } scopy_(n, &work[1], &c__1, &d__[1], &c__1); slacpy_("A", n, n, &work[*n + 1], n, &q[q_offset], ldq); } else { i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { j = iwork[indxq + i__]; work[i__] = d__[j]; /* L120: */ } scopy_(n, &work[1], &c__1, &d__[1], &c__1); } goto L140; L130: *info = submat * (*n + 1) + submat + matsiz - 1; L140: return 0; /* End of SLAED0 */ } /* slaed0_ */ /* Subroutine */ int slaed1_(integer *n, real *d__, real *q, integer *ldq, integer *indxq, real *rho, integer *cutpnt, real *work, integer * iwork, integer *info) { /* System generated locals */ integer q_dim1, q_offset, i__1, i__2; /* Local variables */ static integer i__, k, n1, n2, is, iw, iz, iq2, cpp1, indx, indxc, indxp; extern /* Subroutine */ int scopy_(integer *, real *, integer *, real *, integer *), slaed2_(integer *, integer *, integer *, real *, real *, integer *, integer *, real *, real *, real *, real *, real *, integer *, integer *, integer *, integer *, integer *), slaed3_( integer *, integer *, integer *, real *, real *, integer *, real * , real *, real *, integer *, integer *, real *, real *, integer *) ; static integer idlmda; extern /* Subroutine */ int xerbla_(char *, integer *), slamrg_( integer *, integer *, real *, integer *, integer *, integer *); static integer coltyp; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= SLAED1 computes the updated eigensystem of a diagonal matrix after modification by a rank-one symmetric matrix. This routine is used only for the eigenproblem which requires all eigenvalues and eigenvectors of a tridiagonal matrix. SLAED7 handles the case in which eigenvalues only or eigenvalues and eigenvectors of a full symmetric matrix (which was reduced to tridiagonal form) are desired. T = Q(in) ( D(in) + RHO * Z*Z' ) Q'(in) = Q(out) * D(out) * Q'(out) where Z = Q'u, u is a vector of length N with ones in the CUTPNT and CUTPNT + 1 th elements and zeros elsewhere. The eigenvectors of the original matrix are stored in Q, and the eigenvalues are in D. The algorithm consists of three stages: The first stage consists of deflating the size of the problem when there are multiple eigenvalues or if there is a zero in the Z vector. For each such occurence the dimension of the secular equation problem is reduced by one. This stage is performed by the routine SLAED2. The second stage consists of calculating the updated eigenvalues. This is done by finding the roots of the secular equation via the routine SLAED4 (as called by SLAED3). This routine also calculates the eigenvectors of the current problem. The final stage consists of computing the updated eigenvectors directly using the updated eigenvalues. The eigenvectors for the current problem are multiplied with the eigenvectors from the overall problem. Arguments ========= N (input) INTEGER The dimension of the symmetric tridiagonal matrix. N >= 0. D (input/output) REAL array, dimension (N) On entry, the eigenvalues of the rank-1-perturbed matrix. On exit, the eigenvalues of the repaired matrix. Q (input/output) REAL array, dimension (LDQ,N) On entry, the eigenvectors of the rank-1-perturbed matrix. On exit, the eigenvectors of the repaired tridiagonal matrix. LDQ (input) INTEGER The leading dimension of the array Q. LDQ >= max(1,N). INDXQ (input/output) INTEGER array, dimension (N) On entry, the permutation which separately sorts the two subproblems in D into ascending order. On exit, the permutation which will reintegrate the subproblems back into sorted order, i.e. D( INDXQ( I = 1, N ) ) will be in ascending order. RHO (input) REAL The subdiagonal entry used to create the rank-1 modification. CUTPNT (input) INTEGER The location of the last eigenvalue in the leading sub-matrix. min(1,N) <= CUTPNT <= N/2. WORK (workspace) REAL array, dimension (4*N + N**2) IWORK (workspace) INTEGER array, dimension (4*N) INFO (output) INTEGER = 0: successful exit. < 0: if INFO = -i, the i-th argument had an illegal value. > 0: if INFO = 1, an eigenvalue did not converge Further Details =============== Based on contributions by Jeff Rutter, Computer Science Division, University of California at Berkeley, USA Modified by Francoise Tisseur, University of Tennessee. ===================================================================== Test the input parameters. */ /* Parameter adjustments */ --d__; q_dim1 = *ldq; q_offset = 1 + q_dim1; q -= q_offset; --indxq; --work; --iwork; /* Function Body */ *info = 0; if (*n < 0) { *info = -1; } else if (*ldq < max(1,*n)) { *info = -4; } else /* if(complicated condition) */ { /* Computing MIN */ i__1 = 1, i__2 = *n / 2; if ((min(i__1,i__2) > *cutpnt) || (*n / 2 < *cutpnt)) { *info = -7; } } if (*info != 0) { i__1 = -(*info); xerbla_("SLAED1", &i__1); return 0; } /* Quick return if possible */ if (*n == 0) { return 0; } /* The following values are integer pointers which indicate the portion of the workspace used by a particular array in SLAED2 and SLAED3. */ iz = 1; idlmda = iz + *n; iw = idlmda + *n; iq2 = iw + *n; indx = 1; indxc = indx + *n; coltyp = indxc + *n; indxp = coltyp + *n; /* Form the z-vector which consists of the last row of Q_1 and the first row of Q_2. */ scopy_(cutpnt, &q[*cutpnt + q_dim1], ldq, &work[iz], &c__1); cpp1 = *cutpnt + 1; i__1 = *n - *cutpnt; scopy_(&i__1, &q[cpp1 + cpp1 * q_dim1], ldq, &work[iz + *cutpnt], &c__1); /* Deflate eigenvalues. */ slaed2_(&k, n, cutpnt, &d__[1], &q[q_offset], ldq, &indxq[1], rho, &work[ iz], &work[idlmda], &work[iw], &work[iq2], &iwork[indx], &iwork[ indxc], &iwork[indxp], &iwork[coltyp], info); if (*info != 0) { goto L20; } /* Solve Secular Equation. */ if (k != 0) { is = (iwork[coltyp] + iwork[coltyp + 1]) * *cutpnt + (iwork[coltyp + 1] + iwork[coltyp + 2]) * (*n - *cutpnt) + iq2; slaed3_(&k, n, cutpnt, &d__[1], &q[q_offset], ldq, rho, &work[idlmda], &work[iq2], &iwork[indxc], &iwork[coltyp], &work[iw], &work[ is], info); if (*info != 0) { goto L20; } /* Prepare the INDXQ sorting permutation. */ n1 = k; n2 = *n - k; slamrg_(&n1, &n2, &d__[1], &c__1, &c_n1, &indxq[1]); } else { i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { indxq[i__] = i__; /* L10: */ } } L20: return 0; /* End of SLAED1 */ } /* slaed1_ */ /* Subroutine */ int slaed2_(integer *k, integer *n, integer *n1, real *d__, real *q, integer *ldq, integer *indxq, real *rho, real *z__, real * dlamda, real *w, real *q2, integer *indx, integer *indxc, integer * indxp, integer *coltyp, integer *info) { /* System generated locals */ integer q_dim1, q_offset, i__1, i__2; real r__1, r__2, r__3, r__4; /* Builtin functions */ double sqrt(doublereal); /* Local variables */ static real c__; static integer i__, j; static real s, t; static integer k2, n2, ct, nj, pj, js, iq1, iq2, n1p1; static real eps, tau, tol; static integer psm[4], imax, jmax, ctot[4]; extern /* Subroutine */ int srot_(integer *, real *, integer *, real *, integer *, real *, real *), sscal_(integer *, real *, real *, integer *), scopy_(integer *, real *, integer *, real *, integer * ); extern doublereal slapy2_(real *, real *), slamch_(char *); extern /* Subroutine */ int xerbla_(char *, integer *); extern integer isamax_(integer *, real *, integer *); extern /* Subroutine */ int slamrg_(integer *, integer *, real *, integer *, integer *, integer *), slacpy_(char *, integer *, integer *, real *, integer *, real *, integer *); /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University October 31, 1999 Purpose ======= SLAED2 merges the two sets of eigenvalues together into a single sorted set. Then it tries to deflate the size of the problem. There are two ways in which deflation can occur: when two or more eigenvalues are close together or if there is a tiny entry in the Z vector. For each such occurrence the order of the related secular equation problem is reduced by one. Arguments ========= K (output) INTEGER The number of non-deflated eigenvalues, and the order of the related secular equation. 0 <= K <=N. N (input) INTEGER The dimension of the symmetric tridiagonal matrix. N >= 0. N1 (input) INTEGER The location of the last eigenvalue in the leading sub-matrix. min(1,N) <= N1 <= N/2. D (input/output) REAL array, dimension (N) On entry, D contains the eigenvalues of the two submatrices to be combined. On exit, D contains the trailing (N-K) updated eigenvalues (those which were deflated) sorted into increasing order. Q (input/output) REAL array, dimension (LDQ, N) On entry, Q contains the eigenvectors of two submatrices in the two square blocks with corners at (1,1), (N1,N1) and (N1+1, N1+1), (N,N). On exit, Q contains the trailing (N-K) updated eigenvectors (those which were deflated) in its last N-K columns. LDQ (input) INTEGER The leading dimension of the array Q. LDQ >= max(1,N). INDXQ (input/output) INTEGER array, dimension (N) The permutation which separately sorts the two sub-problems in D into ascending order. Note that elements in the second half of this permutation must first have N1 added to their values. Destroyed on exit. RHO (input/output) REAL On entry, the off-diagonal element associated with the rank-1 cut which originally split the two submatrices which are now being recombined. On exit, RHO has been modified to the value required by SLAED3. Z (input) REAL array, dimension (N) On entry, Z contains the updating vector (the last row of the first sub-eigenvector matrix and the first row of the second sub-eigenvector matrix). On exit, the contents of Z have been destroyed by the updating process. DLAMDA (output) REAL array, dimension (N) A copy of the first K eigenvalues which will be used by SLAED3 to form the secular equation. W (output) REAL array, dimension (N) The first k values of the final deflation-altered z-vector which will be passed to SLAED3. Q2 (output) REAL array, dimension (N1**2+(N-N1)**2) A copy of the first K eigenvectors which will be used by SLAED3 in a matrix multiply (SGEMM) to solve for the new eigenvectors. INDX (workspace) INTEGER array, dimension (N) The permutation used to sort the contents of DLAMDA into ascending order. INDXC (output) INTEGER array, dimension (N) The permutation used to arrange the columns of the deflated Q matrix into three groups: the first group contains non-zero elements only at and above N1, the second contains non-zero elements only below N1, and the third is dense. INDXP (workspace) INTEGER array, dimension (N) The permutation used to place deflated values of D at the end of the array. INDXP(1:K) points to the nondeflated D-values and INDXP(K+1:N) points to the deflated eigenvalues. COLTYP (workspace/output) INTEGER array, dimension (N) During execution, a label which will indicate which of the following types a column in the Q2 matrix is: 1 : non-zero in the upper half only; 2 : dense; 3 : non-zero in the lower half only; 4 : deflated. On exit, COLTYP(i) is the number of columns of type i, for i=1 to 4 only. INFO (output) INTEGER = 0: successful exit. < 0: if INFO = -i, the i-th argument had an illegal value. Further Details =============== Based on contributions by Jeff Rutter, Computer Science Division, University of California at Berkeley, USA Modified by Francoise Tisseur, University of Tennessee. ===================================================================== Test the input parameters. */ /* Parameter adjustments */ --d__; q_dim1 = *ldq; q_offset = 1 + q_dim1; q -= q_offset; --indxq; --z__; --dlamda; --w; --q2; --indx; --indxc; --indxp; --coltyp; /* Function Body */ *info = 0; if (*n < 0) { *info = -2; } else if (*ldq < max(1,*n)) { *info = -6; } else /* if(complicated condition) */ { /* Computing MIN */ i__1 = 1, i__2 = *n / 2; if ((min(i__1,i__2) > *n1) || (*n / 2 < *n1)) { *info = -3; } } if (*info != 0) { i__1 = -(*info); xerbla_("SLAED2", &i__1); return 0; } /* Quick return if possible */ if (*n == 0) { return 0; } n2 = *n - *n1; n1p1 = *n1 + 1; if (*rho < 0.f) { sscal_(&n2, &c_b1290, &z__[n1p1], &c__1); } /* Normalize z so that norm(z) = 1. Since z is the concatenation of two normalized vectors, norm2(z) = sqrt(2). */ t = 1.f / sqrt(2.f); sscal_(n, &t, &z__[1], &c__1); /* RHO = ABS( norm(z)**2 * RHO ) */ *rho = (r__1 = *rho * 2.f, dabs(r__1)); /* Sort the eigenvalues into increasing order */ i__1 = *n; for (i__ = n1p1; i__ <= i__1; ++i__) { indxq[i__] += *n1; /* L10: */ } /* re-integrate the deflated parts from the last pass */ i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { dlamda[i__] = d__[indxq[i__]]; /* L20: */ } slamrg_(n1, &n2, &dlamda[1], &c__1, &c__1, &indxc[1]); i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { indx[i__] = indxq[indxc[i__]]; /* L30: */ } /* Calculate the allowable deflation tolerance */ imax = isamax_(n, &z__[1], &c__1); jmax = isamax_(n, &d__[1], &c__1); eps = slamch_("Epsilon"); /* Computing MAX */ r__3 = (r__1 = d__[jmax], dabs(r__1)), r__4 = (r__2 = z__[imax], dabs( r__2)); tol = eps * 8.f * dmax(r__3,r__4); /* If the rank-1 modifier is small enough, no more needs to be done except to reorganize Q so that its columns correspond with the elements in D. */ if (*rho * (r__1 = z__[imax], dabs(r__1)) <= tol) { *k = 0; iq2 = 1; i__1 = *n; for (j = 1; j <= i__1; ++j) { i__ = indx[j]; scopy_(n, &q[i__ * q_dim1 + 1], &c__1, &q2[iq2], &c__1); dlamda[j] = d__[i__]; iq2 += *n; /* L40: */ } slacpy_("A", n, n, &q2[1], n, &q[q_offset], ldq); scopy_(n, &dlamda[1], &c__1, &d__[1], &c__1); goto L190; } /* If there are multiple eigenvalues then the problem deflates. Here the number of equal eigenvalues are found. As each equal eigenvalue is found, an elementary reflector is computed to rotate the corresponding eigensubspace so that the corresponding components of Z are zero in this new basis. */ i__1 = *n1; for (i__ = 1; i__ <= i__1; ++i__) { coltyp[i__] = 1; /* L50: */ } i__1 = *n; for (i__ = n1p1; i__ <= i__1; ++i__) { coltyp[i__] = 3; /* L60: */ } *k = 0; k2 = *n + 1; i__1 = *n; for (j = 1; j <= i__1; ++j) { nj = indx[j]; if (*rho * (r__1 = z__[nj], dabs(r__1)) <= tol) { /* Deflate due to small z component. */ --k2; coltyp[nj] = 4; indxp[k2] = nj; if (j == *n) { goto L100; } } else { pj = nj; goto L80; } /* L70: */ } L80: ++j; nj = indx[j]; if (j > *n) { goto L100; } if (*rho * (r__1 = z__[nj], dabs(r__1)) <= tol) { /* Deflate due to small z component. */ --k2; coltyp[nj] = 4; indxp[k2] = nj; } else { /* Check if eigenvalues are close enough to allow deflation. */ s = z__[pj]; c__ = z__[nj]; /* Find sqrt(a**2+b**2) without overflow or destructive underflow. */ tau = slapy2_(&c__, &s); t = d__[nj] - d__[pj]; c__ /= tau; s = -s / tau; if ((r__1 = t * c__ * s, dabs(r__1)) <= tol) { /* Deflation is possible. */ z__[nj] = tau; z__[pj] = 0.f; if (coltyp[nj] != coltyp[pj]) { coltyp[nj] = 2; } coltyp[pj] = 4; srot_(n, &q[pj * q_dim1 + 1], &c__1, &q[nj * q_dim1 + 1], &c__1, & c__, &s); /* Computing 2nd power */ r__1 = c__; /* Computing 2nd power */ r__2 = s; t = d__[pj] * (r__1 * r__1) + d__[nj] * (r__2 * r__2); /* Computing 2nd power */ r__1 = s; /* Computing 2nd power */ r__2 = c__; d__[nj] = d__[pj] * (r__1 * r__1) + d__[nj] * (r__2 * r__2); d__[pj] = t; --k2; i__ = 1; L90: if (k2 + i__ <= *n) { if (d__[pj] < d__[indxp[k2 + i__]]) { indxp[k2 + i__ - 1] = indxp[k2 + i__]; indxp[k2 + i__] = pj; ++i__; goto L90; } else { indxp[k2 + i__ - 1] = pj; } } else { indxp[k2 + i__ - 1] = pj; } pj = nj; } else { ++(*k); dlamda[*k] = d__[pj]; w[*k] = z__[pj]; indxp[*k] = pj; pj = nj; } } goto L80; L100: /* Record the last eigenvalue. */ ++(*k); dlamda[*k] = d__[pj]; w[*k] = z__[pj]; indxp[*k] = pj; /* Count up the total number of the various types of columns, then form a permutation which positions the four column types into four uniform groups (although one or more of these groups may be empty). */ for (j = 1; j <= 4; ++j) { ctot[j - 1] = 0; /* L110: */ } i__1 = *n; for (j = 1; j <= i__1; ++j) { ct = coltyp[j]; ++ctot[ct - 1]; /* L120: */ } /* PSM(*) = Position in SubMatrix (of types 1 through 4) */ psm[0] = 1; psm[1] = ctot[0] + 1; psm[2] = psm[1] + ctot[1]; psm[3] = psm[2] + ctot[2]; *k = *n - ctot[3]; /* Fill out the INDXC array so that the permutation which it induces will place all type-1 columns first, all type-2 columns next, then all type-3's, and finally all type-4's. */ i__1 = *n; for (j = 1; j <= i__1; ++j) { js = indxp[j]; ct = coltyp[js]; indx[psm[ct - 1]] = js; indxc[psm[ct - 1]] = j; ++psm[ct - 1]; /* L130: */ } /* Sort the eigenvalues and corresponding eigenvectors into DLAMDA and Q2 respectively. The eigenvalues/vectors which were not deflated go into the first K slots of DLAMDA and Q2 respectively, while those which were deflated go into the last N - K slots. */ i__ = 1; iq1 = 1; iq2 = (ctot[0] + ctot[1]) * *n1 + 1; i__1 = ctot[0]; for (j = 1; j <= i__1; ++j) { js = indx[i__]; scopy_(n1, &q[js * q_dim1 + 1], &c__1, &q2[iq1], &c__1); z__[i__] = d__[js]; ++i__; iq1 += *n1; /* L140: */ } i__1 = ctot[1]; for (j = 1; j <= i__1; ++j) { js = indx[i__]; scopy_(n1, &q[js * q_dim1 + 1], &c__1, &q2[iq1], &c__1); scopy_(&n2, &q[*n1 + 1 + js * q_dim1], &c__1, &q2[iq2], &c__1); z__[i__] = d__[js]; ++i__; iq1 += *n1; iq2 += n2; /* L150: */ } i__1 = ctot[2]; for (j = 1; j <= i__1; ++j) { js = indx[i__]; scopy_(&n2, &q[*n1 + 1 + js * q_dim1], &c__1, &q2[iq2], &c__1); z__[i__] = d__[js]; ++i__; iq2 += n2; /* L160: */ } iq1 = iq2; i__1 = ctot[3]; for (j = 1; j <= i__1; ++j) { js = indx[i__]; scopy_(n, &q[js * q_dim1 + 1], &c__1, &q2[iq2], &c__1); iq2 += *n; z__[i__] = d__[js]; ++i__; /* L170: */ } /* The deflated eigenvalues and their corresponding vectors go back into the last N - K slots of D and Q respectively. */ slacpy_("A", n, &ctot[3], &q2[iq1], n, &q[(*k + 1) * q_dim1 + 1], ldq); i__1 = *n - *k; scopy_(&i__1, &z__[*k + 1], &c__1, &d__[*k + 1], &c__1); /* Copy CTOT into COLTYP for referencing in SLAED3. */ for (j = 1; j <= 4; ++j) { coltyp[j] = ctot[j - 1]; /* L180: */ } L190: return 0; /* End of SLAED2 */ } /* slaed2_ */ /* Subroutine */ int slaed3_(integer *k, integer *n, integer *n1, real *d__, real *q, integer *ldq, real *rho, real *dlamda, real *q2, integer * indx, integer *ctot, real *w, real *s, integer *info) { /* System generated locals */ integer q_dim1, q_offset, i__1, i__2; real r__1; /* Builtin functions */ double sqrt(doublereal), r_sign(real *, real *); /* Local variables */ static integer i__, j, n2, n12, ii, n23, iq2; static real temp; extern doublereal snrm2_(integer *, real *, integer *); extern /* Subroutine */ int sgemm_(char *, char *, integer *, integer *, integer *, real *, real *, integer *, real *, integer *, real *, real *, integer *), scopy_(integer *, real *, integer *, real *, integer *), slaed4_(integer *, integer *, real *, real *, real *, real *, real *, integer *); extern doublereal slamc3_(real *, real *); extern /* Subroutine */ int xerbla_(char *, integer *), slacpy_( char *, integer *, integer *, real *, integer *, real *, integer * ), slaset_(char *, integer *, integer *, real *, real *, real *, integer *); /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Oak Ridge National Lab, Argonne National Lab, Courant Institute, NAG Ltd., and Rice University June 30, 1999 Purpose ======= SLAED3 finds the roots of the secular equation, as defined by the values in D, W, and RHO, between 1 and K. It makes the appropriate calls to SLAED4 and then updates the eigenvectors by multiplying the matrix of eigenvectors of the pair of eigensystems being combined by the matrix of eigenvectors of the K-by-K system which is solved here. This code makes very mild assumptions about floating point arithmetic. It will work on machines with a guard digit in add/subtract, or on those binary machines without guard digits which subtract like the Cray X-MP, Cray Y-MP, Cray C-90, or Cray-2. It could conceivably fail on hexadecimal or decimal machines without guard digits, but we know of none. Arguments ========= K (input) INTEGER The number of terms in the rational function to be solved by SLAED4. K >= 0. N (input) INTEGER The number of rows and columns in the Q matrix. N >= K (deflation may result in N>K). N1 (input) INTEGER The location of the last eigenvalue in the leading submatrix. min(1,N) <= N1 <= N/2. D (output) REAL array, dimension (N) D(I) contains the updated eigenvalues for 1 <= I <= K. Q (output) REAL array, dimension (LDQ,N) Initially the first K columns are used as workspace. On output the columns 1 to K contain the updated eigenvectors. LDQ (input) INTEGER The leading dimension of the array Q. LDQ >= max(1,N). RHO (input) REAL The value of the parameter in the rank one update equation. RHO >= 0 required. DLAMDA (input/output) REAL array, dimension (K) The first K elements of this array contain the old roots of the deflated updating problem. These are the poles of the secular equation. May be changed on output by having lowest order bit set to zero on Cray X-MP, Cray Y-MP, Cray-2, or Cray C-90, as described above. Q2 (input) REAL array, dimension (LDQ2, N) The first K columns of this matrix contain the non-deflated eigenvectors for the split problem. INDX (input) INTEGER array, dimension (N) The permutation used to arrange the columns of the deflated Q matrix into three groups (see SLAED2). The rows of the eigenvectors found by SLAED4 must be likewise permuted before the matrix multiply can take place. CTOT (input) INTEGER array, dimension (4) A count of the total number of the various types of columns in Q, as described in INDX. The fourth column type is any column which has been deflated. W (input/output) REAL array, dimension (K) The first K elements of this array contain the components of the deflation-adjusted updating vector. Destroyed on output. S (workspace) REAL array, dimension (N1 + 1)*K Will contain the eigenvectors of the repaired matrix which will be multiplied by the previously accumulated eigenvectors to update the system. LDS (input) INTEGER The leading dimension of S. LDS >= max(1,K). INFO (output) INTEGER = 0: successful exit. < 0: if INFO = -i, the i-th argument had an illegal value. > 0: if INFO = 1, an eigenvalue did not converge Further Details =============== Based on contributions by Jeff Rutter, Computer Science Division, University of California at Berkeley, USA Modified by Francoise Tisseur, University of Tennessee. ===================================================================== Test the input parameters. */ /* Parameter adjustments */ --d__; q_dim1 = *ldq; q_offset = 1 + q_dim1; q -= q_offset; --dlamda; --q2; --indx; --ctot; --w; --s; /* Function Body */ *info = 0; if (*k < 0) { *info = -1; } else if (*n < *k) { *info = -2; } else if (*ldq < max(1,*n)) { *info = -6; } if (*info != 0) { i__1 = -(*info); xerbla_("SLAED3", &i__1); return 0; } /* Quick return if possible */ if (*k == 0) { return 0; } /* Modify values DLAMDA(i) to make sure all DLAMDA(i)-DLAMDA(j) can be computed with high relative accuracy (barring over/underflow). This is a problem on machines without a guard digit in add/subtract (Cray XMP, Cray YMP, Cray C 90 and Cray 2). The following code replaces DLAMDA(I) by 2*DLAMDA(I)-DLAMDA(I), which on any of these machines zeros out the bottommost bit of DLAMDA(I) if it is 1; this makes the subsequent subtractions DLAMDA(I)-DLAMDA(J) unproblematic when cancellation occurs. On binary machines with a guard digit (almost all machines) it does not change DLAMDA(I) at all. On hexadecimal and decimal machines with a guard digit, it slightly changes the bottommost bits of DLAMDA(I). It does not account for hexadecimal or decimal machines without guard digits (we know of none). We use a subroutine call to compute 2*DLAMBDA(I) to prevent optimizing compilers from eliminating this code. */ i__1 = *k; for (i__ = 1; i__ <= i__1; ++i__) { dlamda[i__] = slamc3_(&dlamda[i__], &dlamda[i__]) - dlamda[i__]; /* L10: */ } i__1 = *k; for (j = 1; j <= i__1; ++j) { slaed4_(k, &j, &dlamda[1], &w[1], &q[j * q_dim1 + 1], rho, &d__[j], info); /* If the zero finder fails, the computation is terminated. */ if (*info != 0) { goto L120; } /* L20: */ } if (*k == 1) { goto L110; } if (*k == 2) { i__1 = *k; for (j = 1; j <= i__1; ++j) { w[1] = q[j * q_dim1 + 1]; w[2] = q[j * q_dim1 + 2]; ii = indx[1]; q[j * q_dim1 + 1] = w[ii]; ii = indx[2]; q[j * q_dim1 + 2] = w[ii]; /* L30: */ } goto L110; } /* Compute updated W. */ scopy_(k, &w[1], &c__1, &s[1], &c__1); /* Initialize W(I) = Q(I,I) */ i__1 = *ldq + 1; scopy_(k, &q[q_offset], &i__1, &w[1], &c__1); i__1 = *k; for (j = 1; j <= i__1; ++j) { i__2 = j - 1; for (i__ = 1; i__ <= i__2; ++i__) { w[i__] *= q[i__ + j * q_dim1] / (dlamda[i__] - dlamda[j]); /* L40: */ } i__2 = *k; for (i__ = j + 1; i__ <= i__2; ++i__) { w[i__] *= q[i__ + j * q_dim1] / (dlamda[i__] - dlamda[j]); /* L50: */ } /* L60: */ } i__1 = *k; for (i__ = 1; i__ <= i__1; ++i__) { r__1 = sqrt(-w[i__]); w[i__] = r_sign(&r__1, &s[i__]); /* L70: */ } /* Compute eigenvectors of the modified rank-1 modification. */ i__1 = *k; for (j = 1; j <= i__1; ++j) { i__2 = *k; for (i__ = 1; i__ <= i__2; ++i__) { s[i__] = w[i__] / q[i__ + j * q_dim1]; /* L80: */ } temp = snrm2_(k, &s[1], &c__1); i__2 = *k; for (i__ = 1; i__ <= i__2; ++i__) { ii = indx[i__]; q[i__ + j * q_dim1] = s[ii] / temp; /* L90: */ } /* L100: */ } /* Compute the updated eigenvectors. */ L110: n2 = *n - *n1; n12 = ctot[1] + ctot[2]; n23 = ctot[2] + ctot[3]; slacpy_("A", &n23, k, &q[ctot[1] + 1 + q_dim1], ldq, &s[1], &n23); iq2 = *n1 * n12 + 1; if (n23 != 0) { sgemm_("N", "N", &n2, k, &n23, &c_b1011, &q2[iq2], &n2, &s[1], &n23, & c_b320, &q[*n1 + 1 + q_dim1], ldq); } else { slaset_("A", &n2, k, &c_b320, &c_b320, &q[*n1 + 1 + q_dim1], ldq); } slacpy_("A", &n12, k, &q[q_offset], ldq, &s[1], &n12); if (n12 != 0) { sgemm_("N", "N", n1, k, &n12, &c_b1011, &q2[1], n1, &s[1], &n12, & c_b320, &q[q_offset], ldq); } else { slaset_("A", n1, k, &c_b320, &c_b320, &q[q_dim1 + 1], ldq); } L120: return 0; /* End of SLAED3 */ } /* slaed3_ */ /* Subroutine */ int slaed4_(integer *n, integer *i__, real *d__, real *z__, real *delta, real *rho, real *dlam, integer *info) { /* System generated locals */ integer i__1; real r__1; /* Builtin functions */ double sqrt(doublereal); /* Local variables */ static real a, b, c__; static integer j; static real w; static integer ii; static real dw, zz[3]; static integer ip1; static real del, eta, phi, eps, tau, psi; static integer iim1, iip1; static real dphi, dpsi; static integer iter; static real temp, prew, temp1, dltlb, dltub, midpt; static integer niter; static logical swtch; extern /* Subroutine */ int slaed5_(integer *, real *, real *, real *, real *, real *), slaed6_(integer *, logical *, real *, real *, real *, real *, real *, integer *); static logical swtch3; extern doublereal slamch_(char *); static logical orgati; static real erretm, rhoinv; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Oak Ridge National Lab, Argonne National Lab, Courant Institute, NAG Ltd., and Rice University December 23, 1999 Purpose ======= This subroutine computes the I-th updated eigenvalue of a symmetric rank-one modification to a diagonal matrix whose elements are given in the array d, and that D(i) < D(j) for i < j and that RHO > 0. This is arranged by the calling routine, and is no loss in generality. The rank-one modified system is thus diag( D ) + RHO * Z * Z_transpose. where we assume the Euclidean norm of Z is 1. The method consists of approximating the rational functions in the secular equation by simpler interpolating rational functions. Arguments ========= N (input) INTEGER The length of all arrays. I (input) INTEGER The index of the eigenvalue to be computed. 1 <= I <= N. D (input) REAL array, dimension (N) The original eigenvalues. It is assumed that they are in order, D(I) < D(J) for I < J. Z (input) REAL array, dimension (N) The components of the updating vector. DELTA (output) REAL array, dimension (N) If N .ne. 1, DELTA contains (D(j) - lambda_I) in its j-th component. If N = 1, then DELTA(1) = 1. The vector DELTA contains the information necessary to construct the eigenvectors. RHO (input) REAL The scalar in the symmetric updating formula. DLAM (output) REAL The computed lambda_I, the I-th updated eigenvalue. INFO (output) INTEGER = 0: successful exit > 0: if INFO = 1, the updating process failed. Internal Parameters =================== Logical variable ORGATI (origin-at-i?) is used for distinguishing whether D(i) or D(i+1) is treated as the origin. ORGATI = .true. origin at i ORGATI = .false. origin at i+1 Logical variable SWTCH3 (switch-for-3-poles?) is for noting if we are working with THREE poles! MAXIT is the maximum number of iterations allowed for each eigenvalue. Further Details =============== Based on contributions by Ren-Cang Li, Computer Science Division, University of California at Berkeley, USA ===================================================================== Since this routine is called in an inner loop, we do no argument checking. Quick return for N=1 and 2. */ /* Parameter adjustments */ --delta; --z__; --d__; /* Function Body */ *info = 0; if (*n == 1) { /* Presumably, I=1 upon entry */ *dlam = d__[1] + *rho * z__[1] * z__[1]; delta[1] = 1.f; return 0; } if (*n == 2) { slaed5_(i__, &d__[1], &z__[1], &delta[1], rho, dlam); return 0; } /* Compute machine epsilon */ eps = slamch_("Epsilon"); rhoinv = 1.f / *rho; /* The case I = N */ if (*i__ == *n) { /* Initialize some basic variables */ ii = *n - 1; niter = 1; /* Calculate initial guess */ midpt = *rho / 2.f; /* If ||Z||_2 is not one, then TEMP should be set to RHO * ||Z||_2^2 / TWO */ i__1 = *n; for (j = 1; j <= i__1; ++j) { delta[j] = d__[j] - d__[*i__] - midpt; /* L10: */ } psi = 0.f; i__1 = *n - 2; for (j = 1; j <= i__1; ++j) { psi += z__[j] * z__[j] / delta[j]; /* L20: */ } c__ = rhoinv + psi; w = c__ + z__[ii] * z__[ii] / delta[ii] + z__[*n] * z__[*n] / delta[* n]; if (w <= 0.f) { temp = z__[*n - 1] * z__[*n - 1] / (d__[*n] - d__[*n - 1] + *rho) + z__[*n] * z__[*n] / *rho; if (c__ <= temp) { tau = *rho; } else { del = d__[*n] - d__[*n - 1]; a = -c__ * del + z__[*n - 1] * z__[*n - 1] + z__[*n] * z__[*n] ; b = z__[*n] * z__[*n] * del; if (a < 0.f) { tau = b * 2.f / (sqrt(a * a + b * 4.f * c__) - a); } else { tau = (a + sqrt(a * a + b * 4.f * c__)) / (c__ * 2.f); } } /* It can be proved that D(N)+RHO/2 <= LAMBDA(N) < D(N)+TAU <= D(N)+RHO */ dltlb = midpt; dltub = *rho; } else { del = d__[*n] - d__[*n - 1]; a = -c__ * del + z__[*n - 1] * z__[*n - 1] + z__[*n] * z__[*n]; b = z__[*n] * z__[*n] * del; if (a < 0.f) { tau = b * 2.f / (sqrt(a * a + b * 4.f * c__) - a); } else { tau = (a + sqrt(a * a + b * 4.f * c__)) / (c__ * 2.f); } /* It can be proved that D(N) < D(N)+TAU < LAMBDA(N) < D(N)+RHO/2 */ dltlb = 0.f; dltub = midpt; } i__1 = *n; for (j = 1; j <= i__1; ++j) { delta[j] = d__[j] - d__[*i__] - tau; /* L30: */ } /* Evaluate PSI and the derivative DPSI */ dpsi = 0.f; psi = 0.f; erretm = 0.f; i__1 = ii; for (j = 1; j <= i__1; ++j) { temp = z__[j] / delta[j]; psi += z__[j] * temp; dpsi += temp * temp; erretm += psi; /* L40: */ } erretm = dabs(erretm); /* Evaluate PHI and the derivative DPHI */ temp = z__[*n] / delta[*n]; phi = z__[*n] * temp; dphi = temp * temp; erretm = (-phi - psi) * 8.f + erretm - phi + rhoinv + dabs(tau) * ( dpsi + dphi); w = rhoinv + phi + psi; /* Test for convergence */ if (dabs(w) <= eps * erretm) { *dlam = d__[*i__] + tau; goto L250; } if (w <= 0.f) { dltlb = dmax(dltlb,tau); } else { dltub = dmin(dltub,tau); } /* Calculate the new step */ ++niter; c__ = w - delta[*n - 1] * dpsi - delta[*n] * dphi; a = (delta[*n - 1] + delta[*n]) * w - delta[*n - 1] * delta[*n] * ( dpsi + dphi); b = delta[*n - 1] * delta[*n] * w; if (c__ < 0.f) { c__ = dabs(c__); } if (c__ == 0.f) { /* ETA = B/A ETA = RHO - TAU */ eta = dltub - tau; } else if (a >= 0.f) { eta = (a + sqrt((r__1 = a * a - b * 4.f * c__, dabs(r__1)))) / ( c__ * 2.f); } else { eta = b * 2.f / (a - sqrt((r__1 = a * a - b * 4.f * c__, dabs( r__1)))); } /* Note, eta should be positive if w is negative, and eta should be negative otherwise. However, if for some reason caused by roundoff, eta*w > 0, we simply use one Newton step instead. This way will guarantee eta*w < 0. */ if (w * eta > 0.f) { eta = -w / (dpsi + dphi); } temp = tau + eta; if ((temp > dltub) || (temp < dltlb)) { if (w < 0.f) { eta = (dltub - tau) / 2.f; } else { eta = (dltlb - tau) / 2.f; } } i__1 = *n; for (j = 1; j <= i__1; ++j) { delta[j] -= eta; /* L50: */ } tau += eta; /* Evaluate PSI and the derivative DPSI */ dpsi = 0.f; psi = 0.f; erretm = 0.f; i__1 = ii; for (j = 1; j <= i__1; ++j) { temp = z__[j] / delta[j]; psi += z__[j] * temp; dpsi += temp * temp; erretm += psi; /* L60: */ } erretm = dabs(erretm); /* Evaluate PHI and the derivative DPHI */ temp = z__[*n] / delta[*n]; phi = z__[*n] * temp; dphi = temp * temp; erretm = (-phi - psi) * 8.f + erretm - phi + rhoinv + dabs(tau) * ( dpsi + dphi); w = rhoinv + phi + psi; /* Main loop to update the values of the array DELTA */ iter = niter + 1; for (niter = iter; niter <= 30; ++niter) { /* Test for convergence */ if (dabs(w) <= eps * erretm) { *dlam = d__[*i__] + tau; goto L250; } if (w <= 0.f) { dltlb = dmax(dltlb,tau); } else { dltub = dmin(dltub,tau); } /* Calculate the new step */ c__ = w - delta[*n - 1] * dpsi - delta[*n] * dphi; a = (delta[*n - 1] + delta[*n]) * w - delta[*n - 1] * delta[*n] * (dpsi + dphi); b = delta[*n - 1] * delta[*n] * w; if (a >= 0.f) { eta = (a + sqrt((r__1 = a * a - b * 4.f * c__, dabs(r__1)))) / (c__ * 2.f); } else { eta = b * 2.f / (a - sqrt((r__1 = a * a - b * 4.f * c__, dabs( r__1)))); } /* Note, eta should be positive if w is negative, and eta should be negative otherwise. However, if for some reason caused by roundoff, eta*w > 0, we simply use one Newton step instead. This way will guarantee eta*w < 0. */ if (w * eta > 0.f) { eta = -w / (dpsi + dphi); } temp = tau + eta; if ((temp > dltub) || (temp < dltlb)) { if (w < 0.f) { eta = (dltub - tau) / 2.f; } else { eta = (dltlb - tau) / 2.f; } } i__1 = *n; for (j = 1; j <= i__1; ++j) { delta[j] -= eta; /* L70: */ } tau += eta; /* Evaluate PSI and the derivative DPSI */ dpsi = 0.f; psi = 0.f; erretm = 0.f; i__1 = ii; for (j = 1; j <= i__1; ++j) { temp = z__[j] / delta[j]; psi += z__[j] * temp; dpsi += temp * temp; erretm += psi; /* L80: */ } erretm = dabs(erretm); /* Evaluate PHI and the derivative DPHI */ temp = z__[*n] / delta[*n]; phi = z__[*n] * temp; dphi = temp * temp; erretm = (-phi - psi) * 8.f + erretm - phi + rhoinv + dabs(tau) * (dpsi + dphi); w = rhoinv + phi + psi; /* L90: */ } /* Return with INFO = 1, NITER = MAXIT and not converged */ *info = 1; *dlam = d__[*i__] + tau; goto L250; /* End for the case I = N */ } else { /* The case for I < N */ niter = 1; ip1 = *i__ + 1; /* Calculate initial guess */ del = d__[ip1] - d__[*i__]; midpt = del / 2.f; i__1 = *n; for (j = 1; j <= i__1; ++j) { delta[j] = d__[j] - d__[*i__] - midpt; /* L100: */ } psi = 0.f; i__1 = *i__ - 1; for (j = 1; j <= i__1; ++j) { psi += z__[j] * z__[j] / delta[j]; /* L110: */ } phi = 0.f; i__1 = *i__ + 2; for (j = *n; j >= i__1; --j) { phi += z__[j] * z__[j] / delta[j]; /* L120: */ } c__ = rhoinv + psi + phi; w = c__ + z__[*i__] * z__[*i__] / delta[*i__] + z__[ip1] * z__[ip1] / delta[ip1]; if (w > 0.f) { /* d(i)< the ith eigenvalue < (d(i)+d(i+1))/2 We choose d(i) as origin. */ orgati = TRUE_; a = c__ * del + z__[*i__] * z__[*i__] + z__[ip1] * z__[ip1]; b = z__[*i__] * z__[*i__] * del; if (a > 0.f) { tau = b * 2.f / (a + sqrt((r__1 = a * a - b * 4.f * c__, dabs( r__1)))); } else { tau = (a - sqrt((r__1 = a * a - b * 4.f * c__, dabs(r__1)))) / (c__ * 2.f); } dltlb = 0.f; dltub = midpt; } else { /* (d(i)+d(i+1))/2 <= the ith eigenvalue < d(i+1) We choose d(i+1) as origin. */ orgati = FALSE_; a = c__ * del - z__[*i__] * z__[*i__] - z__[ip1] * z__[ip1]; b = z__[ip1] * z__[ip1] * del; if (a < 0.f) { tau = b * 2.f / (a - sqrt((r__1 = a * a + b * 4.f * c__, dabs( r__1)))); } else { tau = -(a + sqrt((r__1 = a * a + b * 4.f * c__, dabs(r__1)))) / (c__ * 2.f); } dltlb = -midpt; dltub = 0.f; } if (orgati) { i__1 = *n; for (j = 1; j <= i__1; ++j) { delta[j] = d__[j] - d__[*i__] - tau; /* L130: */ } } else { i__1 = *n; for (j = 1; j <= i__1; ++j) { delta[j] = d__[j] - d__[ip1] - tau; /* L140: */ } } if (orgati) { ii = *i__; } else { ii = *i__ + 1; } iim1 = ii - 1; iip1 = ii + 1; /* Evaluate PSI and the derivative DPSI */ dpsi = 0.f; psi = 0.f; erretm = 0.f; i__1 = iim1; for (j = 1; j <= i__1; ++j) { temp = z__[j] / delta[j]; psi += z__[j] * temp; dpsi += temp * temp; erretm += psi; /* L150: */ } erretm = dabs(erretm); /* Evaluate PHI and the derivative DPHI */ dphi = 0.f; phi = 0.f; i__1 = iip1; for (j = *n; j >= i__1; --j) { temp = z__[j] / delta[j]; phi += z__[j] * temp; dphi += temp * temp; erretm += phi; /* L160: */ } w = rhoinv + phi + psi; /* W is the value of the secular function with its ii-th element removed. */ swtch3 = FALSE_; if (orgati) { if (w < 0.f) { swtch3 = TRUE_; } } else { if (w > 0.f) { swtch3 = TRUE_; } } if ((ii == 1) || (ii == *n)) { swtch3 = FALSE_; } temp = z__[ii] / delta[ii]; dw = dpsi + dphi + temp * temp; temp = z__[ii] * temp; w += temp; erretm = (phi - psi) * 8.f + erretm + rhoinv * 2.f + dabs(temp) * 3.f + dabs(tau) * dw; /* Test for convergence */ if (dabs(w) <= eps * erretm) { if (orgati) { *dlam = d__[*i__] + tau; } else { *dlam = d__[ip1] + tau; } goto L250; } if (w <= 0.f) { dltlb = dmax(dltlb,tau); } else { dltub = dmin(dltub,tau); } /* Calculate the new step */ ++niter; if (! swtch3) { if (orgati) { /* Computing 2nd power */ r__1 = z__[*i__] / delta[*i__]; c__ = w - delta[ip1] * dw - (d__[*i__] - d__[ip1]) * (r__1 * r__1); } else { /* Computing 2nd power */ r__1 = z__[ip1] / delta[ip1]; c__ = w - delta[*i__] * dw - (d__[ip1] - d__[*i__]) * (r__1 * r__1); } a = (delta[*i__] + delta[ip1]) * w - delta[*i__] * delta[ip1] * dw; b = delta[*i__] * delta[ip1] * w; if (c__ == 0.f) { if (a == 0.f) { if (orgati) { a = z__[*i__] * z__[*i__] + delta[ip1] * delta[ip1] * (dpsi + dphi); } else { a = z__[ip1] * z__[ip1] + delta[*i__] * delta[*i__] * (dpsi + dphi); } } eta = b / a; } else if (a <= 0.f) { eta = (a - sqrt((r__1 = a * a - b * 4.f * c__, dabs(r__1)))) / (c__ * 2.f); } else { eta = b * 2.f / (a + sqrt((r__1 = a * a - b * 4.f * c__, dabs( r__1)))); } } else { /* Interpolation using THREE most relevant poles */ temp = rhoinv + psi + phi; if (orgati) { temp1 = z__[iim1] / delta[iim1]; temp1 *= temp1; c__ = temp - delta[iip1] * (dpsi + dphi) - (d__[iim1] - d__[ iip1]) * temp1; zz[0] = z__[iim1] * z__[iim1]; zz[2] = delta[iip1] * delta[iip1] * (dpsi - temp1 + dphi); } else { temp1 = z__[iip1] / delta[iip1]; temp1 *= temp1; c__ = temp - delta[iim1] * (dpsi + dphi) - (d__[iip1] - d__[ iim1]) * temp1; zz[0] = delta[iim1] * delta[iim1] * (dpsi + (dphi - temp1)); zz[2] = z__[iip1] * z__[iip1]; } zz[1] = z__[ii] * z__[ii]; slaed6_(&niter, &orgati, &c__, &delta[iim1], zz, &w, &eta, info); if (*info != 0) { goto L250; } } /* Note, eta should be positive if w is negative, and eta should be negative otherwise. However, if for some reason caused by roundoff, eta*w > 0, we simply use one Newton step instead. This way will guarantee eta*w < 0. */ if (w * eta >= 0.f) { eta = -w / dw; } temp = tau + eta; if ((temp > dltub) || (temp < dltlb)) { if (w < 0.f) { eta = (dltub - tau) / 2.f; } else { eta = (dltlb - tau) / 2.f; } } prew = w; /* L170: */ i__1 = *n; for (j = 1; j <= i__1; ++j) { delta[j] -= eta; /* L180: */ } /* Evaluate PSI and the derivative DPSI */ dpsi = 0.f; psi = 0.f; erretm = 0.f; i__1 = iim1; for (j = 1; j <= i__1; ++j) { temp = z__[j] / delta[j]; psi += z__[j] * temp; dpsi += temp * temp; erretm += psi; /* L190: */ } erretm = dabs(erretm); /* Evaluate PHI and the derivative DPHI */ dphi = 0.f; phi = 0.f; i__1 = iip1; for (j = *n; j >= i__1; --j) { temp = z__[j] / delta[j]; phi += z__[j] * temp; dphi += temp * temp; erretm += phi; /* L200: */ } temp = z__[ii] / delta[ii]; dw = dpsi + dphi + temp * temp; temp = z__[ii] * temp; w = rhoinv + phi + psi + temp; erretm = (phi - psi) * 8.f + erretm + rhoinv * 2.f + dabs(temp) * 3.f + (r__1 = tau + eta, dabs(r__1)) * dw; swtch = FALSE_; if (orgati) { if (-w > dabs(prew) / 10.f) { swtch = TRUE_; } } else { if (w > dabs(prew) / 10.f) { swtch = TRUE_; } } tau += eta; /* Main loop to update the values of the array DELTA */ iter = niter + 1; for (niter = iter; niter <= 30; ++niter) { /* Test for convergence */ if (dabs(w) <= eps * erretm) { if (orgati) { *dlam = d__[*i__] + tau; } else { *dlam = d__[ip1] + tau; } goto L250; } if (w <= 0.f) { dltlb = dmax(dltlb,tau); } else { dltub = dmin(dltub,tau); } /* Calculate the new step */ if (! swtch3) { if (! swtch) { if (orgati) { /* Computing 2nd power */ r__1 = z__[*i__] / delta[*i__]; c__ = w - delta[ip1] * dw - (d__[*i__] - d__[ip1]) * ( r__1 * r__1); } else { /* Computing 2nd power */ r__1 = z__[ip1] / delta[ip1]; c__ = w - delta[*i__] * dw - (d__[ip1] - d__[*i__]) * (r__1 * r__1); } } else { temp = z__[ii] / delta[ii]; if (orgati) { dpsi += temp * temp; } else { dphi += temp * temp; } c__ = w - delta[*i__] * dpsi - delta[ip1] * dphi; } a = (delta[*i__] + delta[ip1]) * w - delta[*i__] * delta[ip1] * dw; b = delta[*i__] * delta[ip1] * w; if (c__ == 0.f) { if (a == 0.f) { if (! swtch) { if (orgati) { a = z__[*i__] * z__[*i__] + delta[ip1] * delta[ip1] * (dpsi + dphi); } else { a = z__[ip1] * z__[ip1] + delta[*i__] * delta[ *i__] * (dpsi + dphi); } } else { a = delta[*i__] * delta[*i__] * dpsi + delta[ip1] * delta[ip1] * dphi; } } eta = b / a; } else if (a <= 0.f) { eta = (a - sqrt((r__1 = a * a - b * 4.f * c__, dabs(r__1)) )) / (c__ * 2.f); } else { eta = b * 2.f / (a + sqrt((r__1 = a * a - b * 4.f * c__, dabs(r__1)))); } } else { /* Interpolation using THREE most relevant poles */ temp = rhoinv + psi + phi; if (swtch) { c__ = temp - delta[iim1] * dpsi - delta[iip1] * dphi; zz[0] = delta[iim1] * delta[iim1] * dpsi; zz[2] = delta[iip1] * delta[iip1] * dphi; } else { if (orgati) { temp1 = z__[iim1] / delta[iim1]; temp1 *= temp1; c__ = temp - delta[iip1] * (dpsi + dphi) - (d__[iim1] - d__[iip1]) * temp1; zz[0] = z__[iim1] * z__[iim1]; zz[2] = delta[iip1] * delta[iip1] * (dpsi - temp1 + dphi); } else { temp1 = z__[iip1] / delta[iip1]; temp1 *= temp1; c__ = temp - delta[iim1] * (dpsi + dphi) - (d__[iip1] - d__[iim1]) * temp1; zz[0] = delta[iim1] * delta[iim1] * (dpsi + (dphi - temp1)); zz[2] = z__[iip1] * z__[iip1]; } } slaed6_(&niter, &orgati, &c__, &delta[iim1], zz, &w, &eta, info); if (*info != 0) { goto L250; } } /* Note, eta should be positive if w is negative, and eta should be negative otherwise. However, if for some reason caused by roundoff, eta*w > 0, we simply use one Newton step instead. This way will guarantee eta*w < 0. */ if (w * eta >= 0.f) { eta = -w / dw; } temp = tau + eta; if ((temp > dltub) || (temp < dltlb)) { if (w < 0.f) { eta = (dltub - tau) / 2.f; } else { eta = (dltlb - tau) / 2.f; } } i__1 = *n; for (j = 1; j <= i__1; ++j) { delta[j] -= eta; /* L210: */ } tau += eta; prew = w; /* Evaluate PSI and the derivative DPSI */ dpsi = 0.f; psi = 0.f; erretm = 0.f; i__1 = iim1; for (j = 1; j <= i__1; ++j) { temp = z__[j] / delta[j]; psi += z__[j] * temp; dpsi += temp * temp; erretm += psi; /* L220: */ } erretm = dabs(erretm); /* Evaluate PHI and the derivative DPHI */ dphi = 0.f; phi = 0.f; i__1 = iip1; for (j = *n; j >= i__1; --j) { temp = z__[j] / delta[j]; phi += z__[j] * temp; dphi += temp * temp; erretm += phi; /* L230: */ } temp = z__[ii] / delta[ii]; dw = dpsi + dphi + temp * temp; temp = z__[ii] * temp; w = rhoinv + phi + psi + temp; erretm = (phi - psi) * 8.f + erretm + rhoinv * 2.f + dabs(temp) * 3.f + dabs(tau) * dw; if (w * prew > 0.f && dabs(w) > dabs(prew) / 10.f) { swtch = ! swtch; } /* L240: */ } /* Return with INFO = 1, NITER = MAXIT and not converged */ *info = 1; if (orgati) { *dlam = d__[*i__] + tau; } else { *dlam = d__[ip1] + tau; } } L250: return 0; /* End of SLAED4 */ } /* slaed4_ */ /* Subroutine */ int slaed5_(integer *i__, real *d__, real *z__, real *delta, real *rho, real *dlam) { /* System generated locals */ real r__1; /* Builtin functions */ double sqrt(doublereal); /* Local variables */ static real b, c__, w, del, tau, temp; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Oak Ridge National Lab, Argonne National Lab, Courant Institute, NAG Ltd., and Rice University September 30, 1994 Purpose ======= This subroutine computes the I-th eigenvalue of a symmetric rank-one modification of a 2-by-2 diagonal matrix diag( D ) + RHO * Z * transpose(Z) . The diagonal elements in the array D are assumed to satisfy D(i) < D(j) for i < j . We also assume RHO > 0 and that the Euclidean norm of the vector Z is one. Arguments ========= I (input) INTEGER The index of the eigenvalue to be computed. I = 1 or I = 2. D (input) REAL array, dimension (2) The original eigenvalues. We assume D(1) < D(2). Z (input) REAL array, dimension (2) The components of the updating vector. DELTA (output) REAL array, dimension (2) The vector DELTA contains the information necessary to construct the eigenvectors. RHO (input) REAL The scalar in the symmetric updating formula. DLAM (output) REAL The computed lambda_I, the I-th updated eigenvalue. Further Details =============== Based on contributions by Ren-Cang Li, Computer Science Division, University of California at Berkeley, USA ===================================================================== */ /* Parameter adjustments */ --delta; --z__; --d__; /* Function Body */ del = d__[2] - d__[1]; if (*i__ == 1) { w = *rho * 2.f * (z__[2] * z__[2] - z__[1] * z__[1]) / del + 1.f; if (w > 0.f) { b = del + *rho * (z__[1] * z__[1] + z__[2] * z__[2]); c__ = *rho * z__[1] * z__[1] * del; /* B > ZERO, always */ tau = c__ * 2.f / (b + sqrt((r__1 = b * b - c__ * 4.f, dabs(r__1)) )); *dlam = d__[1] + tau; delta[1] = -z__[1] / tau; delta[2] = z__[2] / (del - tau); } else { b = -del + *rho * (z__[1] * z__[1] + z__[2] * z__[2]); c__ = *rho * z__[2] * z__[2] * del; if (b > 0.f) { tau = c__ * -2.f / (b + sqrt(b * b + c__ * 4.f)); } else { tau = (b - sqrt(b * b + c__ * 4.f)) / 2.f; } *dlam = d__[2] + tau; delta[1] = -z__[1] / (del + tau); delta[2] = -z__[2] / tau; } temp = sqrt(delta[1] * delta[1] + delta[2] * delta[2]); delta[1] /= temp; delta[2] /= temp; } else { /* Now I=2 */ b = -del + *rho * (z__[1] * z__[1] + z__[2] * z__[2]); c__ = *rho * z__[2] * z__[2] * del; if (b > 0.f) { tau = (b + sqrt(b * b + c__ * 4.f)) / 2.f; } else { tau = c__ * 2.f / (-b + sqrt(b * b + c__ * 4.f)); } *dlam = d__[2] + tau; delta[1] = -z__[1] / (del + tau); delta[2] = -z__[2] / tau; temp = sqrt(delta[1] * delta[1] + delta[2] * delta[2]); delta[1] /= temp; delta[2] /= temp; } return 0; /* End OF SLAED5 */ } /* slaed5_ */ /* Subroutine */ int slaed6_(integer *kniter, logical *orgati, real *rho, real *d__, real *z__, real *finit, real *tau, integer *info) { /* Initialized data */ static logical first = TRUE_; /* System generated locals */ integer i__1; real r__1, r__2, r__3, r__4; /* Builtin functions */ double sqrt(doublereal), log(doublereal), pow_ri(real *, integer *); /* Local variables */ static real a, b, c__, f; static integer i__; static real fc, df, ddf, eta, eps, base; static integer iter; static real temp, temp1, temp2, temp3, temp4; static logical scale; static integer niter; static real small1, small2, sminv1, sminv2, dscale[3], sclfac; extern doublereal slamch_(char *); static real zscale[3], erretm, sclinv; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Oak Ridge National Lab, Argonne National Lab, Courant Institute, NAG Ltd., and Rice University June 30, 1999 Purpose ======= SLAED6 computes the positive or negative root (closest to the origin) of z(1) z(2) z(3) f(x) = rho + --------- + ---------- + --------- d(1)-x d(2)-x d(3)-x It is assumed that if ORGATI = .true. the root is between d(2) and d(3); otherwise it is between d(1) and d(2) This routine will be called by SLAED4 when necessary. In most cases, the root sought is the smallest in magnitude, though it might not be in some extremely rare situations. Arguments ========= KNITER (input) INTEGER Refer to SLAED4 for its significance. ORGATI (input) LOGICAL If ORGATI is true, the needed root is between d(2) and d(3); otherwise it is between d(1) and d(2). See SLAED4 for further details. RHO (input) REAL Refer to the equation f(x) above. D (input) REAL array, dimension (3) D satisfies d(1) < d(2) < d(3). Z (input) REAL array, dimension (3) Each of the elements in z must be positive. FINIT (input) REAL The value of f at 0. It is more accurate than the one evaluated inside this routine (if someone wants to do so). TAU (output) REAL The root of the equation f(x). INFO (output) INTEGER = 0: successful exit > 0: if INFO = 1, failure to converge Further Details =============== Based on contributions by Ren-Cang Li, Computer Science Division, University of California at Berkeley, USA ===================================================================== */ /* Parameter adjustments */ --z__; --d__; /* Function Body */ *info = 0; niter = 1; *tau = 0.f; if (*kniter == 2) { if (*orgati) { temp = (d__[3] - d__[2]) / 2.f; c__ = *rho + z__[1] / (d__[1] - d__[2] - temp); a = c__ * (d__[2] + d__[3]) + z__[2] + z__[3]; b = c__ * d__[2] * d__[3] + z__[2] * d__[3] + z__[3] * d__[2]; } else { temp = (d__[1] - d__[2]) / 2.f; c__ = *rho + z__[3] / (d__[3] - d__[2] - temp); a = c__ * (d__[1] + d__[2]) + z__[1] + z__[2]; b = c__ * d__[1] * d__[2] + z__[1] * d__[2] + z__[2] * d__[1]; } /* Computing MAX */ r__1 = dabs(a), r__2 = dabs(b), r__1 = max(r__1,r__2), r__2 = dabs( c__); temp = dmax(r__1,r__2); a /= temp; b /= temp; c__ /= temp; if (c__ == 0.f) { *tau = b / a; } else if (a <= 0.f) { *tau = (a - sqrt((r__1 = a * a - b * 4.f * c__, dabs(r__1)))) / ( c__ * 2.f); } else { *tau = b * 2.f / (a + sqrt((r__1 = a * a - b * 4.f * c__, dabs( r__1)))); } temp = *rho + z__[1] / (d__[1] - *tau) + z__[2] / (d__[2] - *tau) + z__[3] / (d__[3] - *tau); if (dabs(*finit) <= dabs(temp)) { *tau = 0.f; } } /* On first call to routine, get machine parameters for possible scaling to avoid overflow */ if (first) { eps = slamch_("Epsilon"); base = slamch_("Base"); i__1 = (integer) (log(slamch_("SafMin")) / log(base) / 3.f) ; small1 = pow_ri(&base, &i__1); sminv1 = 1.f / small1; small2 = small1 * small1; sminv2 = sminv1 * sminv1; first = FALSE_; } /* Determine if scaling of inputs necessary to avoid overflow when computing 1/TEMP**3 */ if (*orgati) { /* Computing MIN */ r__3 = (r__1 = d__[2] - *tau, dabs(r__1)), r__4 = (r__2 = d__[3] - * tau, dabs(r__2)); temp = dmin(r__3,r__4); } else { /* Computing MIN */ r__3 = (r__1 = d__[1] - *tau, dabs(r__1)), r__4 = (r__2 = d__[2] - * tau, dabs(r__2)); temp = dmin(r__3,r__4); } scale = FALSE_; if (temp <= small1) { scale = TRUE_; if (temp <= small2) { /* Scale up by power of radix nearest 1/SAFMIN**(2/3) */ sclfac = sminv2; sclinv = small2; } else { /* Scale up by power of radix nearest 1/SAFMIN**(1/3) */ sclfac = sminv1; sclinv = small1; } /* Scaling up safe because D, Z, TAU scaled elsewhere to be O(1) */ for (i__ = 1; i__ <= 3; ++i__) { dscale[i__ - 1] = d__[i__] * sclfac; zscale[i__ - 1] = z__[i__] * sclfac; /* L10: */ } *tau *= sclfac; } else { /* Copy D and Z to DSCALE and ZSCALE */ for (i__ = 1; i__ <= 3; ++i__) { dscale[i__ - 1] = d__[i__]; zscale[i__ - 1] = z__[i__]; /* L20: */ } } fc = 0.f; df = 0.f; ddf = 0.f; for (i__ = 1; i__ <= 3; ++i__) { temp = 1.f / (dscale[i__ - 1] - *tau); temp1 = zscale[i__ - 1] * temp; temp2 = temp1 * temp; temp3 = temp2 * temp; fc += temp1 / dscale[i__ - 1]; df += temp2; ddf += temp3; /* L30: */ } f = *finit + *tau * fc; if (dabs(f) <= 0.f) { goto L60; } /* Iteration begins It is not hard to see that 1) Iterations will go up monotonically if FINIT < 0; 2) Iterations will go down monotonically if FINIT > 0. */ iter = niter + 1; for (niter = iter; niter <= 20; ++niter) { if (*orgati) { temp1 = dscale[1] - *tau; temp2 = dscale[2] - *tau; } else { temp1 = dscale[0] - *tau; temp2 = dscale[1] - *tau; } a = (temp1 + temp2) * f - temp1 * temp2 * df; b = temp1 * temp2 * f; c__ = f - (temp1 + temp2) * df + temp1 * temp2 * ddf; /* Computing MAX */ r__1 = dabs(a), r__2 = dabs(b), r__1 = max(r__1,r__2), r__2 = dabs( c__); temp = dmax(r__1,r__2); a /= temp; b /= temp; c__ /= temp; if (c__ == 0.f) { eta = b / a; } else if (a <= 0.f) { eta = (a - sqrt((r__1 = a * a - b * 4.f * c__, dabs(r__1)))) / ( c__ * 2.f); } else { eta = b * 2.f / (a + sqrt((r__1 = a * a - b * 4.f * c__, dabs( r__1)))); } if (f * eta >= 0.f) { eta = -f / df; } temp = eta + *tau; if (*orgati) { if (eta > 0.f && temp >= dscale[2]) { eta = (dscale[2] - *tau) / 2.f; } if (eta < 0.f && temp <= dscale[1]) { eta = (dscale[1] - *tau) / 2.f; } } else { if (eta > 0.f && temp >= dscale[1]) { eta = (dscale[1] - *tau) / 2.f; } if (eta < 0.f && temp <= dscale[0]) { eta = (dscale[0] - *tau) / 2.f; } } *tau += eta; fc = 0.f; erretm = 0.f; df = 0.f; ddf = 0.f; for (i__ = 1; i__ <= 3; ++i__) { temp = 1.f / (dscale[i__ - 1] - *tau); temp1 = zscale[i__ - 1] * temp; temp2 = temp1 * temp; temp3 = temp2 * temp; temp4 = temp1 / dscale[i__ - 1]; fc += temp4; erretm += dabs(temp4); df += temp2; ddf += temp3; /* L40: */ } f = *finit + *tau * fc; erretm = (dabs(*finit) + dabs(*tau) * erretm) * 8.f + dabs(*tau) * df; if (dabs(f) <= eps * erretm) { goto L60; } /* L50: */ } *info = 1; L60: /* Undo scaling */ if (scale) { *tau *= sclinv; } return 0; /* End of SLAED6 */ } /* slaed6_ */ /* Subroutine */ int slaed7_(integer *icompq, integer *n, integer *qsiz, integer *tlvls, integer *curlvl, integer *curpbm, real *d__, real *q, integer *ldq, integer *indxq, real *rho, integer *cutpnt, real * qstore, integer *qptr, integer *prmptr, integer *perm, integer * givptr, integer *givcol, real *givnum, real *work, integer *iwork, integer *info) { /* System generated locals */ integer q_dim1, q_offset, i__1, i__2; /* Builtin functions */ integer pow_ii(integer *, integer *); /* Local variables */ static integer i__, k, n1, n2, is, iw, iz, iq2, ptr, ldq2, indx, curr, indxc; extern /* Subroutine */ int sgemm_(char *, char *, integer *, integer *, integer *, real *, real *, integer *, real *, integer *, real *, real *, integer *); static integer indxp; extern /* Subroutine */ int slaed8_(integer *, integer *, integer *, integer *, real *, real *, integer *, integer *, real *, integer * , real *, real *, real *, integer *, real *, integer *, integer *, integer *, real *, integer *, integer *, integer *), slaed9_( integer *, integer *, integer *, integer *, real *, real *, integer *, real *, real *, real *, real *, integer *, integer *), slaeda_(integer *, integer *, integer *, integer *, integer *, integer *, integer *, integer *, real *, real *, integer *, real * , real *, integer *); static integer idlmda; extern /* Subroutine */ int xerbla_(char *, integer *), slamrg_( integer *, integer *, real *, integer *, integer *, integer *); static integer coltyp; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University September 30, 1994 Purpose ======= SLAED7 computes the updated eigensystem of a diagonal matrix after modification by a rank-one symmetric matrix. This routine is used only for the eigenproblem which requires all eigenvalues and optionally eigenvectors of a dense symmetric matrix that has been reduced to tridiagonal form. SLAED1 handles the case in which all eigenvalues and eigenvectors of a symmetric tridiagonal matrix are desired. T = Q(in) ( D(in) + RHO * Z*Z' ) Q'(in) = Q(out) * D(out) * Q'(out) where Z = Q'u, u is a vector of length N with ones in the CUTPNT and CUTPNT + 1 th elements and zeros elsewhere. The eigenvectors of the original matrix are stored in Q, and the eigenvalues are in D. The algorithm consists of three stages: The first stage consists of deflating the size of the problem when there are multiple eigenvalues or if there is a zero in the Z vector. For each such occurence the dimension of the secular equation problem is reduced by one. This stage is performed by the routine SLAED8. The second stage consists of calculating the updated eigenvalues. This is done by finding the roots of the secular equation via the routine SLAED4 (as called by SLAED9). This routine also calculates the eigenvectors of the current problem. The final stage consists of computing the updated eigenvectors directly using the updated eigenvalues. The eigenvectors for the current problem are multiplied with the eigenvectors from the overall problem. Arguments ========= ICOMPQ (input) INTEGER = 0: Compute eigenvalues only. = 1: Compute eigenvectors of original dense symmetric matrix also. On entry, Q contains the orthogonal matrix used to reduce the original matrix to tridiagonal form. N (input) INTEGER The dimension of the symmetric tridiagonal matrix. N >= 0. QSIZ (input) INTEGER The dimension of the orthogonal matrix used to reduce the full matrix to tridiagonal form. QSIZ >= N if ICOMPQ = 1. TLVLS (input) INTEGER The total number of merging levels in the overall divide and conquer tree. CURLVL (input) INTEGER The current level in the overall merge routine, 0 <= CURLVL <= TLVLS. CURPBM (input) INTEGER The current problem in the current level in the overall merge routine (counting from upper left to lower right). D (input/output) REAL array, dimension (N) On entry, the eigenvalues of the rank-1-perturbed matrix. On exit, the eigenvalues of the repaired matrix. Q (input/output) REAL array, dimension (LDQ, N) On entry, the eigenvectors of the rank-1-perturbed matrix. On exit, the eigenvectors of the repaired tridiagonal matrix. LDQ (input) INTEGER The leading dimension of the array Q. LDQ >= max(1,N). INDXQ (output) INTEGER array, dimension (N) The permutation which will reintegrate the subproblem just solved back into sorted order, i.e., D( INDXQ( I = 1, N ) ) will be in ascending order. RHO (input) REAL The subdiagonal element used to create the rank-1 modification. CUTPNT (input) INTEGER Contains the location of the last eigenvalue in the leading sub-matrix. min(1,N) <= CUTPNT <= N. QSTORE (input/output) REAL array, dimension (N**2+1) Stores eigenvectors of submatrices encountered during divide and conquer, packed together. QPTR points to beginning of the submatrices. QPTR (input/output) INTEGER array, dimension (N+2) List of indices pointing to beginning of submatrices stored in QSTORE. The submatrices are numbered starting at the bottom left of the divide and conquer tree, from left to right and bottom to top. PRMPTR (input) INTEGER array, dimension (N lg N) Contains a list of pointers which indicate where in PERM a level's permutation is stored. PRMPTR(i+1) - PRMPTR(i) indicates the size of the permutation and also the size of the full, non-deflated problem. PERM (input) INTEGER array, dimension (N lg N) Contains the permutations (from deflation and sorting) to be applied to each eigenblock. GIVPTR (input) INTEGER array, dimension (N lg N) Contains a list of pointers which indicate where in GIVCOL a level's Givens rotations are stored. GIVPTR(i+1) - GIVPTR(i) indicates the number of Givens rotations. GIVCOL (input) INTEGER array, dimension (2, N lg N) Each pair of numbers indicates a pair of columns to take place in a Givens rotation. GIVNUM (input) REAL array, dimension (2, N lg N) Each number indicates the S value to be used in the corresponding Givens rotation. WORK (workspace) REAL array, dimension (3*N+QSIZ*N) IWORK (workspace) INTEGER array, dimension (4*N) INFO (output) INTEGER = 0: successful exit. < 0: if INFO = -i, the i-th argument had an illegal value. > 0: if INFO = 1, an eigenvalue did not converge Further Details =============== Based on contributions by Jeff Rutter, Computer Science Division, University of California at Berkeley, USA ===================================================================== Test the input parameters. */ /* Parameter adjustments */ --d__; q_dim1 = *ldq; q_offset = 1 + q_dim1; q -= q_offset; --indxq; --qstore; --qptr; --prmptr; --perm; --givptr; givcol -= 3; givnum -= 3; --work; --iwork; /* Function Body */ *info = 0; if ((*icompq < 0) || (*icompq > 1)) { *info = -1; } else if (*n < 0) { *info = -2; } else if (*icompq == 1 && *qsiz < *n) { *info = -4; } else if (*ldq < max(1,*n)) { *info = -9; } else if ((min(1,*n) > *cutpnt) || (*n < *cutpnt)) { *info = -12; } if (*info != 0) { i__1 = -(*info); xerbla_("SLAED7", &i__1); return 0; } /* Quick return if possible */ if (*n == 0) { return 0; } /* The following values are for bookkeeping purposes only. They are integer pointers which indicate the portion of the workspace used by a particular array in SLAED8 and SLAED9. */ if (*icompq == 1) { ldq2 = *qsiz; } else { ldq2 = *n; } iz = 1; idlmda = iz + *n; iw = idlmda + *n; iq2 = iw + *n; is = iq2 + *n * ldq2; indx = 1; indxc = indx + *n; coltyp = indxc + *n; indxp = coltyp + *n; /* Form the z-vector which consists of the last row of Q_1 and the first row of Q_2. */ ptr = pow_ii(&c__2, tlvls) + 1; i__1 = *curlvl - 1; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = *tlvls - i__; ptr += pow_ii(&c__2, &i__2); /* L10: */ } curr = ptr + *curpbm; slaeda_(n, tlvls, curlvl, curpbm, &prmptr[1], &perm[1], &givptr[1], & givcol[3], &givnum[3], &qstore[1], &qptr[1], &work[iz], &work[iz + *n], info); /* When solving the final problem, we no longer need the stored data, so we will overwrite the data from this level onto the previously used storage space. */ if (*curlvl == *tlvls) { qptr[curr] = 1; prmptr[curr] = 1; givptr[curr] = 1; } /* Sort and Deflate eigenvalues. */ slaed8_(icompq, &k, n, qsiz, &d__[1], &q[q_offset], ldq, &indxq[1], rho, cutpnt, &work[iz], &work[idlmda], &work[iq2], &ldq2, &work[iw], & perm[prmptr[curr]], &givptr[curr + 1], &givcol[((givptr[curr]) << (1)) + 1], &givnum[((givptr[curr]) << (1)) + 1], &iwork[indxp], & iwork[indx], info); prmptr[curr + 1] = prmptr[curr] + *n; givptr[curr + 1] += givptr[curr]; /* Solve Secular Equation. */ if (k != 0) { slaed9_(&k, &c__1, &k, n, &d__[1], &work[is], &k, rho, &work[idlmda], &work[iw], &qstore[qptr[curr]], &k, info); if (*info != 0) { goto L30; } if (*icompq == 1) { sgemm_("N", "N", qsiz, &k, &k, &c_b1011, &work[iq2], &ldq2, & qstore[qptr[curr]], &k, &c_b320, &q[q_offset], ldq); } /* Computing 2nd power */ i__1 = k; qptr[curr + 1] = qptr[curr] + i__1 * i__1; /* Prepare the INDXQ sorting permutation. */ n1 = k; n2 = *n - k; slamrg_(&n1, &n2, &d__[1], &c__1, &c_n1, &indxq[1]); } else { qptr[curr + 1] = qptr[curr]; i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { indxq[i__] = i__; /* L20: */ } } L30: return 0; /* End of SLAED7 */ } /* slaed7_ */ /* Subroutine */ int slaed8_(integer *icompq, integer *k, integer *n, integer *qsiz, real *d__, real *q, integer *ldq, integer *indxq, real *rho, integer *cutpnt, real *z__, real *dlamda, real *q2, integer *ldq2, real *w, integer *perm, integer *givptr, integer *givcol, real * givnum, integer *indxp, integer *indx, integer *info) { /* System generated locals */ integer q_dim1, q_offset, q2_dim1, q2_offset, i__1; real r__1; /* Builtin functions */ double sqrt(doublereal); /* Local variables */ static real c__; static integer i__, j; static real s, t; static integer k2, n1, n2, jp, n1p1; static real eps, tau, tol; static integer jlam, imax, jmax; extern /* Subroutine */ int srot_(integer *, real *, integer *, real *, integer *, real *, real *), sscal_(integer *, real *, real *, integer *), scopy_(integer *, real *, integer *, real *, integer * ); extern doublereal slapy2_(real *, real *), slamch_(char *); extern /* Subroutine */ int xerbla_(char *, integer *); extern integer isamax_(integer *, real *, integer *); extern /* Subroutine */ int slamrg_(integer *, integer *, real *, integer *, integer *, integer *), slacpy_(char *, integer *, integer *, real *, integer *, real *, integer *); /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Oak Ridge National Lab, Argonne National Lab, Courant Institute, NAG Ltd., and Rice University September 30, 1994 Purpose ======= SLAED8 merges the two sets of eigenvalues together into a single sorted set. Then it tries to deflate the size of the problem. There are two ways in which deflation can occur: when two or more eigenvalues are close together or if there is a tiny element in the Z vector. For each such occurrence the order of the related secular equation problem is reduced by one. Arguments ========= ICOMPQ (input) INTEGER = 0: Compute eigenvalues only. = 1: Compute eigenvectors of original dense symmetric matrix also. On entry, Q contains the orthogonal matrix used to reduce the original matrix to tridiagonal form. K (output) INTEGER The number of non-deflated eigenvalues, and the order of the related secular equation. N (input) INTEGER The dimension of the symmetric tridiagonal matrix. N >= 0. QSIZ (input) INTEGER The dimension of the orthogonal matrix used to reduce the full matrix to tridiagonal form. QSIZ >= N if ICOMPQ = 1. D (input/output) REAL array, dimension (N) On entry, the eigenvalues of the two submatrices to be combined. On exit, the trailing (N-K) updated eigenvalues (those which were deflated) sorted into increasing order. Q (input/output) REAL array, dimension (LDQ,N) If ICOMPQ = 0, Q is not referenced. Otherwise, on entry, Q contains the eigenvectors of the partially solved system which has been previously updated in matrix multiplies with other partially solved eigensystems. On exit, Q contains the trailing (N-K) updated eigenvectors (those which were deflated) in its last N-K columns. LDQ (input) INTEGER The leading dimension of the array Q. LDQ >= max(1,N). INDXQ (input) INTEGER array, dimension (N) The permutation which separately sorts the two sub-problems in D into ascending order. Note that elements in the second half of this permutation must first have CUTPNT added to their values in order to be accurate. RHO (input/output) REAL On entry, the off-diagonal element associated with the rank-1 cut which originally split the two submatrices which are now being recombined. On exit, RHO has been modified to the value required by SLAED3. CUTPNT (input) INTEGER The location of the last eigenvalue in the leading sub-matrix. min(1,N) <= CUTPNT <= N. Z (input) REAL array, dimension (N) On entry, Z contains the updating vector (the last row of the first sub-eigenvector matrix and the first row of the second sub-eigenvector matrix). On exit, the contents of Z are destroyed by the updating process. DLAMDA (output) REAL array, dimension (N) A copy of the first K eigenvalues which will be used by SLAED3 to form the secular equation. Q2 (output) REAL array, dimension (LDQ2,N) If ICOMPQ = 0, Q2 is not referenced. Otherwise, a copy of the first K eigenvectors which will be used by SLAED7 in a matrix multiply (SGEMM) to update the new eigenvectors. LDQ2 (input) INTEGER The leading dimension of the array Q2. LDQ2 >= max(1,N). W (output) REAL array, dimension (N) The first k values of the final deflation-altered z-vector and will be passed to SLAED3. PERM (output) INTEGER array, dimension (N) The permutations (from deflation and sorting) to be applied to each eigenblock. GIVPTR (output) INTEGER The number of Givens rotations which took place in this subproblem. GIVCOL (output) INTEGER array, dimension (2, N) Each pair of numbers indicates a pair of columns to take place in a Givens rotation. GIVNUM (output) REAL array, dimension (2, N) Each number indicates the S value to be used in the corresponding Givens rotation. INDXP (workspace) INTEGER array, dimension (N) The permutation used to place deflated values of D at the end of the array. INDXP(1:K) points to the nondeflated D-values and INDXP(K+1:N) points to the deflated eigenvalues. INDX (workspace) INTEGER array, dimension (N) The permutation used to sort the contents of D into ascending order. INFO (output) INTEGER = 0: successful exit. < 0: if INFO = -i, the i-th argument had an illegal value. Further Details =============== Based on contributions by Jeff Rutter, Computer Science Division, University of California at Berkeley, USA ===================================================================== Test the input parameters. */ /* Parameter adjustments */ --d__; q_dim1 = *ldq; q_offset = 1 + q_dim1; q -= q_offset; --indxq; --z__; --dlamda; q2_dim1 = *ldq2; q2_offset = 1 + q2_dim1; q2 -= q2_offset; --w; --perm; givcol -= 3; givnum -= 3; --indxp; --indx; /* Function Body */ *info = 0; if ((*icompq < 0) || (*icompq > 1)) { *info = -1; } else if (*n < 0) { *info = -3; } else if (*icompq == 1 && *qsiz < *n) { *info = -4; } else if (*ldq < max(1,*n)) { *info = -7; } else if ((*cutpnt < min(1,*n)) || (*cutpnt > *n)) { *info = -10; } else if (*ldq2 < max(1,*n)) { *info = -14; } if (*info != 0) { i__1 = -(*info); xerbla_("SLAED8", &i__1); return 0; } /* Quick return if possible */ if (*n == 0) { return 0; } n1 = *cutpnt; n2 = *n - n1; n1p1 = n1 + 1; if (*rho < 0.f) { sscal_(&n2, &c_b1290, &z__[n1p1], &c__1); } /* Normalize z so that norm(z) = 1 */ t = 1.f / sqrt(2.f); i__1 = *n; for (j = 1; j <= i__1; ++j) { indx[j] = j; /* L10: */ } sscal_(n, &t, &z__[1], &c__1); *rho = (r__1 = *rho * 2.f, dabs(r__1)); /* Sort the eigenvalues into increasing order */ i__1 = *n; for (i__ = *cutpnt + 1; i__ <= i__1; ++i__) { indxq[i__] += *cutpnt; /* L20: */ } i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { dlamda[i__] = d__[indxq[i__]]; w[i__] = z__[indxq[i__]]; /* L30: */ } i__ = 1; j = *cutpnt + 1; slamrg_(&n1, &n2, &dlamda[1], &c__1, &c__1, &indx[1]); i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { d__[i__] = dlamda[indx[i__]]; z__[i__] = w[indx[i__]]; /* L40: */ } /* Calculate the allowable deflation tolerence */ imax = isamax_(n, &z__[1], &c__1); jmax = isamax_(n, &d__[1], &c__1); eps = slamch_("Epsilon"); tol = eps * 8.f * (r__1 = d__[jmax], dabs(r__1)); /* If the rank-1 modifier is small enough, no more needs to be done except to reorganize Q so that its columns correspond with the elements in D. */ if (*rho * (r__1 = z__[imax], dabs(r__1)) <= tol) { *k = 0; if (*icompq == 0) { i__1 = *n; for (j = 1; j <= i__1; ++j) { perm[j] = indxq[indx[j]]; /* L50: */ } } else { i__1 = *n; for (j = 1; j <= i__1; ++j) { perm[j] = indxq[indx[j]]; scopy_(qsiz, &q[perm[j] * q_dim1 + 1], &c__1, &q2[j * q2_dim1 + 1], &c__1); /* L60: */ } slacpy_("A", qsiz, n, &q2[q2_dim1 + 1], ldq2, &q[q_dim1 + 1], ldq); } return 0; } /* If there are multiple eigenvalues then the problem deflates. Here the number of equal eigenvalues are found. As each equal eigenvalue is found, an elementary reflector is computed to rotate the corresponding eigensubspace so that the corresponding components of Z are zero in this new basis. */ *k = 0; *givptr = 0; k2 = *n + 1; i__1 = *n; for (j = 1; j <= i__1; ++j) { if (*rho * (r__1 = z__[j], dabs(r__1)) <= tol) { /* Deflate due to small z component. */ --k2; indxp[k2] = j; if (j == *n) { goto L110; } } else { jlam = j; goto L80; } /* L70: */ } L80: ++j; if (j > *n) { goto L100; } if (*rho * (r__1 = z__[j], dabs(r__1)) <= tol) { /* Deflate due to small z component. */ --k2; indxp[k2] = j; } else { /* Check if eigenvalues are close enough to allow deflation. */ s = z__[jlam]; c__ = z__[j]; /* Find sqrt(a**2+b**2) without overflow or destructive underflow. */ tau = slapy2_(&c__, &s); t = d__[j] - d__[jlam]; c__ /= tau; s = -s / tau; if ((r__1 = t * c__ * s, dabs(r__1)) <= tol) { /* Deflation is possible. */ z__[j] = tau; z__[jlam] = 0.f; /* Record the appropriate Givens rotation */ ++(*givptr); givcol[((*givptr) << (1)) + 1] = indxq[indx[jlam]]; givcol[((*givptr) << (1)) + 2] = indxq[indx[j]]; givnum[((*givptr) << (1)) + 1] = c__; givnum[((*givptr) << (1)) + 2] = s; if (*icompq == 1) { srot_(qsiz, &q[indxq[indx[jlam]] * q_dim1 + 1], &c__1, &q[ indxq[indx[j]] * q_dim1 + 1], &c__1, &c__, &s); } t = d__[jlam] * c__ * c__ + d__[j] * s * s; d__[j] = d__[jlam] * s * s + d__[j] * c__ * c__; d__[jlam] = t; --k2; i__ = 1; L90: if (k2 + i__ <= *n) { if (d__[jlam] < d__[indxp[k2 + i__]]) { indxp[k2 + i__ - 1] = indxp[k2 + i__]; indxp[k2 + i__] = jlam; ++i__; goto L90; } else { indxp[k2 + i__ - 1] = jlam; } } else { indxp[k2 + i__ - 1] = jlam; } jlam = j; } else { ++(*k); w[*k] = z__[jlam]; dlamda[*k] = d__[jlam]; indxp[*k] = jlam; jlam = j; } } goto L80; L100: /* Record the last eigenvalue. */ ++(*k); w[*k] = z__[jlam]; dlamda[*k] = d__[jlam]; indxp[*k] = jlam; L110: /* Sort the eigenvalues and corresponding eigenvectors into DLAMDA and Q2 respectively. The eigenvalues/vectors which were not deflated go into the first K slots of DLAMDA and Q2 respectively, while those which were deflated go into the last N - K slots. */ if (*icompq == 0) { i__1 = *n; for (j = 1; j <= i__1; ++j) { jp = indxp[j]; dlamda[j] = d__[jp]; perm[j] = indxq[indx[jp]]; /* L120: */ } } else { i__1 = *n; for (j = 1; j <= i__1; ++j) { jp = indxp[j]; dlamda[j] = d__[jp]; perm[j] = indxq[indx[jp]]; scopy_(qsiz, &q[perm[j] * q_dim1 + 1], &c__1, &q2[j * q2_dim1 + 1] , &c__1); /* L130: */ } } /* The deflated eigenvalues and their corresponding vectors go back into the last N - K slots of D and Q respectively. */ if (*k < *n) { if (*icompq == 0) { i__1 = *n - *k; scopy_(&i__1, &dlamda[*k + 1], &c__1, &d__[*k + 1], &c__1); } else { i__1 = *n - *k; scopy_(&i__1, &dlamda[*k + 1], &c__1, &d__[*k + 1], &c__1); i__1 = *n - *k; slacpy_("A", qsiz, &i__1, &q2[(*k + 1) * q2_dim1 + 1], ldq2, &q[(* k + 1) * q_dim1 + 1], ldq); } } return 0; /* End of SLAED8 */ } /* slaed8_ */ /* Subroutine */ int slaed9_(integer *k, integer *kstart, integer *kstop, integer *n, real *d__, real *q, integer *ldq, real *rho, real *dlamda, real *w, real *s, integer *lds, integer *info) { /* System generated locals */ integer q_dim1, q_offset, s_dim1, s_offset, i__1, i__2; real r__1; /* Builtin functions */ double sqrt(doublereal), r_sign(real *, real *); /* Local variables */ static integer i__, j; static real temp; extern doublereal snrm2_(integer *, real *, integer *); extern /* Subroutine */ int scopy_(integer *, real *, integer *, real *, integer *), slaed4_(integer *, integer *, real *, real *, real *, real *, real *, integer *); extern doublereal slamc3_(real *, real *); extern /* Subroutine */ int xerbla_(char *, integer *); /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Oak Ridge National Lab, Argonne National Lab, Courant Institute, NAG Ltd., and Rice University September 30, 1994 Purpose ======= SLAED9 finds the roots of the secular equation, as defined by the values in D, Z, and RHO, between KSTART and KSTOP. It makes the appropriate calls to SLAED4 and then stores the new matrix of eigenvectors for use in calculating the next level of Z vectors. Arguments ========= K (input) INTEGER The number of terms in the rational function to be solved by SLAED4. K >= 0. KSTART (input) INTEGER KSTOP (input) INTEGER The updated eigenvalues Lambda(I), KSTART <= I <= KSTOP are to be computed. 1 <= KSTART <= KSTOP <= K. N (input) INTEGER The number of rows and columns in the Q matrix. N >= K (delation may result in N > K). D (output) REAL array, dimension (N) D(I) contains the updated eigenvalues for KSTART <= I <= KSTOP. Q (workspace) REAL array, dimension (LDQ,N) LDQ (input) INTEGER The leading dimension of the array Q. LDQ >= max( 1, N ). RHO (input) REAL The value of the parameter in the rank one update equation. RHO >= 0 required. DLAMDA (input) REAL array, dimension (K) The first K elements of this array contain the old roots of the deflated updating problem. These are the poles of the secular equation. W (input) REAL array, dimension (K) The first K elements of this array contain the components of the deflation-adjusted updating vector. S (output) REAL array, dimension (LDS, K) Will contain the eigenvectors of the repaired matrix which will be stored for subsequent Z vector calculation and multiplied by the previously accumulated eigenvectors to update the system. LDS (input) INTEGER The leading dimension of S. LDS >= max( 1, K ). INFO (output) INTEGER = 0: successful exit. < 0: if INFO = -i, the i-th argument had an illegal value. > 0: if INFO = 1, an eigenvalue did not converge Further Details =============== Based on contributions by Jeff Rutter, Computer Science Division, University of California at Berkeley, USA ===================================================================== Test the input parameters. */ /* Parameter adjustments */ --d__; q_dim1 = *ldq; q_offset = 1 + q_dim1; q -= q_offset; --dlamda; --w; s_dim1 = *lds; s_offset = 1 + s_dim1; s -= s_offset; /* Function Body */ *info = 0; if (*k < 0) { *info = -1; } else if ((*kstart < 1) || (*kstart > max(1,*k))) { *info = -2; } else if ((max(1,*kstop) < *kstart) || (*kstop > max(1,*k))) { *info = -3; } else if (*n < *k) { *info = -4; } else if (*ldq < max(1,*k)) { *info = -7; } else if (*lds < max(1,*k)) { *info = -12; } if (*info != 0) { i__1 = -(*info); xerbla_("SLAED9", &i__1); return 0; } /* Quick return if possible */ if (*k == 0) { return 0; } /* Modify values DLAMDA(i) to make sure all DLAMDA(i)-DLAMDA(j) can be computed with high relative accuracy (barring over/underflow). This is a problem on machines without a guard digit in add/subtract (Cray XMP, Cray YMP, Cray C 90 and Cray 2). The following code replaces DLAMDA(I) by 2*DLAMDA(I)-DLAMDA(I), which on any of these machines zeros out the bottommost bit of DLAMDA(I) if it is 1; this makes the subsequent subtractions DLAMDA(I)-DLAMDA(J) unproblematic when cancellation occurs. On binary machines with a guard digit (almost all machines) it does not change DLAMDA(I) at all. On hexadecimal and decimal machines with a guard digit, it slightly changes the bottommost bits of DLAMDA(I). It does not account for hexadecimal or decimal machines without guard digits (we know of none). We use a subroutine call to compute 2*DLAMBDA(I) to prevent optimizing compilers from eliminating this code. */ i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { dlamda[i__] = slamc3_(&dlamda[i__], &dlamda[i__]) - dlamda[i__]; /* L10: */ } i__1 = *kstop; for (j = *kstart; j <= i__1; ++j) { slaed4_(k, &j, &dlamda[1], &w[1], &q[j * q_dim1 + 1], rho, &d__[j], info); /* If the zero finder fails, the computation is terminated. */ if (*info != 0) { goto L120; } /* L20: */ } if ((*k == 1) || (*k == 2)) { i__1 = *k; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = *k; for (j = 1; j <= i__2; ++j) { s[j + i__ * s_dim1] = q[j + i__ * q_dim1]; /* L30: */ } /* L40: */ } goto L120; } /* Compute updated W. */ scopy_(k, &w[1], &c__1, &s[s_offset], &c__1); /* Initialize W(I) = Q(I,I) */ i__1 = *ldq + 1; scopy_(k, &q[q_offset], &i__1, &w[1], &c__1); i__1 = *k; for (j = 1; j <= i__1; ++j) { i__2 = j - 1; for (i__ = 1; i__ <= i__2; ++i__) { w[i__] *= q[i__ + j * q_dim1] / (dlamda[i__] - dlamda[j]); /* L50: */ } i__2 = *k; for (i__ = j + 1; i__ <= i__2; ++i__) { w[i__] *= q[i__ + j * q_dim1] / (dlamda[i__] - dlamda[j]); /* L60: */ } /* L70: */ } i__1 = *k; for (i__ = 1; i__ <= i__1; ++i__) { r__1 = sqrt(-w[i__]); w[i__] = r_sign(&r__1, &s[i__ + s_dim1]); /* L80: */ } /* Compute eigenvectors of the modified rank-1 modification. */ i__1 = *k; for (j = 1; j <= i__1; ++j) { i__2 = *k; for (i__ = 1; i__ <= i__2; ++i__) { q[i__ + j * q_dim1] = w[i__] / q[i__ + j * q_dim1]; /* L90: */ } temp = snrm2_(k, &q[j * q_dim1 + 1], &c__1); i__2 = *k; for (i__ = 1; i__ <= i__2; ++i__) { s[i__ + j * s_dim1] = q[i__ + j * q_dim1] / temp; /* L100: */ } /* L110: */ } L120: return 0; /* End of SLAED9 */ } /* slaed9_ */ /* Subroutine */ int slaeda_(integer *n, integer *tlvls, integer *curlvl, integer *curpbm, integer *prmptr, integer *perm, integer *givptr, integer *givcol, real *givnum, real *q, integer *qptr, real *z__, real *ztemp, integer *info) { /* System generated locals */ integer i__1, i__2, i__3; /* Builtin functions */ integer pow_ii(integer *, integer *); double sqrt(doublereal); /* Local variables */ static integer i__, k, mid, ptr, curr; extern /* Subroutine */ int srot_(integer *, real *, integer *, real *, integer *, real *, real *); static integer bsiz1, bsiz2, psiz1, psiz2, zptr1; extern /* Subroutine */ int sgemv_(char *, integer *, integer *, real *, real *, integer *, real *, integer *, real *, real *, integer *), scopy_(integer *, real *, integer *, real *, integer *), xerbla_(char *, integer *); /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University September 30, 1994 Purpose ======= SLAEDA computes the Z vector corresponding to the merge step in the CURLVLth step of the merge process with TLVLS steps for the CURPBMth problem. Arguments ========= N (input) INTEGER The dimension of the symmetric tridiagonal matrix. N >= 0. TLVLS (input) INTEGER The total number of merging levels in the overall divide and conquer tree. CURLVL (input) INTEGER The current level in the overall merge routine, 0 <= curlvl <= tlvls. CURPBM (input) INTEGER The current problem in the current level in the overall merge routine (counting from upper left to lower right). PRMPTR (input) INTEGER array, dimension (N lg N) Contains a list of pointers which indicate where in PERM a level's permutation is stored. PRMPTR(i+1) - PRMPTR(i) indicates the size of the permutation and incidentally the size of the full, non-deflated problem. PERM (input) INTEGER array, dimension (N lg N) Contains the permutations (from deflation and sorting) to be applied to each eigenblock. GIVPTR (input) INTEGER array, dimension (N lg N) Contains a list of pointers which indicate where in GIVCOL a level's Givens rotations are stored. GIVPTR(i+1) - GIVPTR(i) indicates the number of Givens rotations. GIVCOL (input) INTEGER array, dimension (2, N lg N) Each pair of numbers indicates a pair of columns to take place in a Givens rotation. GIVNUM (input) REAL array, dimension (2, N lg N) Each number indicates the S value to be used in the corresponding Givens rotation. Q (input) REAL array, dimension (N**2) Contains the square eigenblocks from previous levels, the starting positions for blocks are given by QPTR. QPTR (input) INTEGER array, dimension (N+2) Contains a list of pointers which indicate where in Q an eigenblock is stored. SQRT( QPTR(i+1) - QPTR(i) ) indicates the size of the block. Z (output) REAL array, dimension (N) On output this vector contains the updating vector (the last row of the first sub-eigenvector matrix and the first row of the second sub-eigenvector matrix). ZTEMP (workspace) REAL array, dimension (N) INFO (output) INTEGER = 0: successful exit. < 0: if INFO = -i, the i-th argument had an illegal value. Further Details =============== Based on contributions by Jeff Rutter, Computer Science Division, University of California at Berkeley, USA ===================================================================== Test the input parameters. */ /* Parameter adjustments */ --ztemp; --z__; --qptr; --q; givnum -= 3; givcol -= 3; --givptr; --perm; --prmptr; /* Function Body */ *info = 0; if (*n < 0) { *info = -1; } if (*info != 0) { i__1 = -(*info); xerbla_("SLAEDA", &i__1); return 0; } /* Quick return if possible */ if (*n == 0) { return 0; } /* Determine location of first number in second half. */ mid = *n / 2 + 1; /* Gather last/first rows of appropriate eigenblocks into center of Z */ ptr = 1; /* Determine location of lowest level subproblem in the full storage scheme */ i__1 = *curlvl - 1; curr = ptr + *curpbm * pow_ii(&c__2, curlvl) + pow_ii(&c__2, &i__1) - 1; /* Determine size of these matrices. We add HALF to the value of the SQRT in case the machine underestimates one of these square roots. */ bsiz1 = (integer) (sqrt((real) (qptr[curr + 1] - qptr[curr])) + .5f); bsiz2 = (integer) (sqrt((real) (qptr[curr + 2] - qptr[curr + 1])) + .5f); i__1 = mid - bsiz1 - 1; for (k = 1; k <= i__1; ++k) { z__[k] = 0.f; /* L10: */ } scopy_(&bsiz1, &q[qptr[curr] + bsiz1 - 1], &bsiz1, &z__[mid - bsiz1], & c__1); scopy_(&bsiz2, &q[qptr[curr + 1]], &bsiz2, &z__[mid], &c__1); i__1 = *n; for (k = mid + bsiz2; k <= i__1; ++k) { z__[k] = 0.f; /* L20: */ } /* Loop thru remaining levels 1 -> CURLVL applying the Givens rotations and permutation and then multiplying the center matrices against the current Z. */ ptr = pow_ii(&c__2, tlvls) + 1; i__1 = *curlvl - 1; for (k = 1; k <= i__1; ++k) { i__2 = *curlvl - k; i__3 = *curlvl - k - 1; curr = ptr + *curpbm * pow_ii(&c__2, &i__2) + pow_ii(&c__2, &i__3) - 1; psiz1 = prmptr[curr + 1] - prmptr[curr]; psiz2 = prmptr[curr + 2] - prmptr[curr + 1]; zptr1 = mid - psiz1; /* Apply Givens at CURR and CURR+1 */ i__2 = givptr[curr + 1] - 1; for (i__ = givptr[curr]; i__ <= i__2; ++i__) { srot_(&c__1, &z__[zptr1 + givcol[((i__) << (1)) + 1] - 1], &c__1, &z__[zptr1 + givcol[((i__) << (1)) + 2] - 1], &c__1, & givnum[((i__) << (1)) + 1], &givnum[((i__) << (1)) + 2]); /* L30: */ } i__2 = givptr[curr + 2] - 1; for (i__ = givptr[curr + 1]; i__ <= i__2; ++i__) { srot_(&c__1, &z__[mid - 1 + givcol[((i__) << (1)) + 1]], &c__1, & z__[mid - 1 + givcol[((i__) << (1)) + 2]], &c__1, &givnum[ ((i__) << (1)) + 1], &givnum[((i__) << (1)) + 2]); /* L40: */ } psiz1 = prmptr[curr + 1] - prmptr[curr]; psiz2 = prmptr[curr + 2] - prmptr[curr + 1]; i__2 = psiz1 - 1; for (i__ = 0; i__ <= i__2; ++i__) { ztemp[i__ + 1] = z__[zptr1 + perm[prmptr[curr] + i__] - 1]; /* L50: */ } i__2 = psiz2 - 1; for (i__ = 0; i__ <= i__2; ++i__) { ztemp[psiz1 + i__ + 1] = z__[mid + perm[prmptr[curr + 1] + i__] - 1]; /* L60: */ } /* Multiply Blocks at CURR and CURR+1 Determine size of these matrices. We add HALF to the value of the SQRT in case the machine underestimates one of these square roots. */ bsiz1 = (integer) (sqrt((real) (qptr[curr + 1] - qptr[curr])) + .5f); bsiz2 = (integer) (sqrt((real) (qptr[curr + 2] - qptr[curr + 1])) + .5f); if (bsiz1 > 0) { sgemv_("T", &bsiz1, &bsiz1, &c_b1011, &q[qptr[curr]], &bsiz1, & ztemp[1], &c__1, &c_b320, &z__[zptr1], &c__1); } i__2 = psiz1 - bsiz1; scopy_(&i__2, &ztemp[bsiz1 + 1], &c__1, &z__[zptr1 + bsiz1], &c__1); if (bsiz2 > 0) { sgemv_("T", &bsiz2, &bsiz2, &c_b1011, &q[qptr[curr + 1]], &bsiz2, &ztemp[psiz1 + 1], &c__1, &c_b320, &z__[mid], &c__1); } i__2 = psiz2 - bsiz2; scopy_(&i__2, &ztemp[psiz1 + bsiz2 + 1], &c__1, &z__[mid + bsiz2], & c__1); i__2 = *tlvls - k; ptr += pow_ii(&c__2, &i__2); /* L70: */ } return 0; /* End of SLAEDA */ } /* slaeda_ */ /* Subroutine */ int slaev2_(real *a, real *b, real *c__, real *rt1, real * rt2, real *cs1, real *sn1) { /* System generated locals */ real r__1; /* Builtin functions */ double sqrt(doublereal); /* Local variables */ static real ab, df, cs, ct, tb, sm, tn, rt, adf, acs; static integer sgn1, sgn2; static real acmn, acmx; /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University October 31, 1992 Purpose ======= SLAEV2 computes the eigendecomposition of a 2-by-2 symmetric matrix [ A B ] [ B C ]. On return, RT1 is the eigenvalue of larger absolute value, RT2 is the eigenvalue of smaller absolute value, and (CS1,SN1) is the unit right eigenvector for RT1, giving the decomposition [ CS1 SN1 ] [ A B ] [ CS1 -SN1 ] = [ RT1 0 ] [-SN1 CS1 ] [ B C ] [ SN1 CS1 ] [ 0 RT2 ]. Arguments ========= A (input) REAL The (1,1) element of the 2-by-2 matrix. B (input) REAL The (1,2) element and the conjugate of the (2,1) element of the 2-by-2 matrix. C (input) REAL The (2,2) element of the 2-by-2 matrix. RT1 (output) REAL The eigenvalue of larger absolute value. RT2 (output) REAL The eigenvalue of smaller absolute value. CS1 (output) REAL SN1 (output) REAL The vector (CS1, SN1) is a unit right eigenvector for RT1. Further Details =============== RT1 is accurate to a few ulps barring over/underflow. RT2 may be inaccurate if there is massive cancellation in the determinant A*C-B*B; higher precision or correctly rounded or correctly truncated arithmetic would be needed to compute RT2 accurately in all cases. CS1 and SN1 are accurate to a few ulps barring over/underflow. Overflow is possible only if RT1 is within a factor of 5 of overflow. Underflow is harmless if the input data is 0 or exceeds underflow_threshold / macheps. ===================================================================== Compute the eigenvalues */ sm = *a + *c__; df = *a - *c__; adf = dabs(df); tb = *b + *b; ab = dabs(tb); if (dabs(*a) > dabs(*c__)) { acmx = *a; acmn = *c__; } else { acmx = *c__; acmn = *a; } if (adf > ab) { /* Computing 2nd power */ r__1 = ab / adf; rt = adf * sqrt(r__1 * r__1 + 1.f); } else if (adf < ab) { /* Computing 2nd power */ r__1 = adf / ab; rt = ab * sqrt(r__1 * r__1 + 1.f); } else { /* Includes case AB=ADF=0 */ rt = ab * sqrt(2.f); } if (sm < 0.f) { *rt1 = (sm - rt) * .5f; sgn1 = -1; /* Order of execution important. To get fully accurate smaller eigenvalue, next line needs to be executed in higher precision. */ *rt2 = acmx / *rt1 * acmn - *b / *rt1 * *b; } else if (sm > 0.f) { *rt1 = (sm + rt) * .5f; sgn1 = 1; /* Order of execution important. To get fully accurate smaller eigenvalue, next line needs to be executed in higher precision. */ *rt2 = acmx / *rt1 * acmn - *b / *rt1 * *b; } else { /* Includes case RT1 = RT2 = 0 */ *rt1 = rt * .5f; *rt2 = rt * -.5f; sgn1 = 1; } /* Compute the eigenvector */ if (df >= 0.f) { cs = df + rt; sgn2 = 1; } else { cs = df - rt; sgn2 = -1; } acs = dabs(cs); if (acs > ab) { ct = -tb / cs; *sn1 = 1.f / sqrt(ct * ct + 1.f); *cs1 = ct * *sn1; } else { if (ab == 0.f) { *cs1 = 1.f; *sn1 = 0.f; } else { tn = -cs / tb; *cs1 = 1.f / sqrt(tn * tn + 1.f); *sn1 = tn * *cs1; } } if (sgn1 == sgn2) { tn = *cs1; *cs1 = -(*sn1); *sn1 = tn; } return 0; /* End of SLAEV2 */ } /* slaev2_ */ /* Subroutine */ int slahqr_(logical *wantt, logical *wantz, integer *n, integer *ilo, integer *ihi, real *h__, integer *ldh, real *wr, real * wi, integer *iloz, integer *ihiz, real *z__, integer *ldz, integer * info) { /* System generated locals */ integer h_dim1, h_offset, z_dim1, z_offset, i__1, i__2, i__3, i__4; real r__1, r__2; /* Builtin functions */ double sqrt(doublereal), r_sign(real *, real *); /* Local variables */ static integer i__, j, k, l, m; static real s, v[3]; static integer i1, i2; static real t1, t2, t3, v1, v2, v3, h00, h10, h11, h12, h21, h22, h33, h44; static integer nh; static real cs; static integer nr; static real sn; static integer nz; static real ave, h33s, h44s; static integer itn, its; static real ulp, sum, tst1, h43h34, disc, unfl, ovfl, work[1]; extern /* Subroutine */ int srot_(integer *, real *, integer *, real *, integer *, real *, real *), scopy_(integer *, real *, integer *, real *, integer *), slanv2_(real *, real *, real *, real *, real * , real *, real *, real *, real *, real *), slabad_(real *, real *) ; extern doublereal slamch_(char *); extern /* Subroutine */ int slarfg_(integer *, real *, real *, integer *, real *); extern doublereal slanhs_(char *, integer *, real *, integer *, real *); static real smlnum; /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= SLAHQR is an auxiliary routine called by SHSEQR to update the eigenvalues and Schur decomposition already computed by SHSEQR, by dealing with the Hessenberg submatrix in rows and columns ILO to IHI. Arguments ========= WANTT (input) LOGICAL = .TRUE. : the full Schur form T is required; = .FALSE.: only eigenvalues are required. WANTZ (input) LOGICAL = .TRUE. : the matrix of Schur vectors Z is required; = .FALSE.: Schur vectors are not required. N (input) INTEGER The order of the matrix H. N >= 0. ILO (input) INTEGER IHI (input) INTEGER It is assumed that H is already upper quasi-triangular in rows and columns IHI+1:N, and that H(ILO,ILO-1) = 0 (unless ILO = 1). SLAHQR works primarily with the Hessenberg submatrix in rows and columns ILO to IHI, but applies transformations to all of H if WANTT is .TRUE.. 1 <= ILO <= max(1,IHI); IHI <= N. H (input/output) REAL array, dimension (LDH,N) On entry, the upper Hessenberg matrix H. On exit, if WANTT is .TRUE., H is upper quasi-triangular in rows and columns ILO:IHI, with any 2-by-2 diagonal blocks in standard form. If WANTT is .FALSE., the contents of H are unspecified on exit. LDH (input) INTEGER The leading dimension of the array H. LDH >= max(1,N). WR (output) REAL array, dimension (N) WI (output) REAL array, dimension (N) The real and imaginary parts, respectively, of the computed eigenvalues ILO to IHI are stored in the corresponding elements of WR and WI. If two eigenvalues are computed as a complex conjugate pair, they are stored in consecutive elements of WR and WI, say the i-th and (i+1)th, with WI(i) > 0 and WI(i+1) < 0. If WANTT is .TRUE., the eigenvalues are stored in the same order as on the diagonal of the Schur form returned in H, with WR(i) = H(i,i), and, if H(i:i+1,i:i+1) is a 2-by-2 diagonal block, WI(i) = sqrt(H(i+1,i)*H(i,i+1)) and WI(i+1) = -WI(i). ILOZ (input) INTEGER IHIZ (input) INTEGER Specify the rows of Z to which transformations must be applied if WANTZ is .TRUE.. 1 <= ILOZ <= ILO; IHI <= IHIZ <= N. Z (input/output) REAL array, dimension (LDZ,N) If WANTZ is .TRUE., on entry Z must contain the current matrix Z of transformations accumulated by SHSEQR, and on exit Z has been updated; transformations are applied only to the submatrix Z(ILOZ:IHIZ,ILO:IHI). If WANTZ is .FALSE., Z is not referenced. LDZ (input) INTEGER The leading dimension of the array Z. LDZ >= max(1,N). INFO (output) INTEGER = 0: successful exit > 0: SLAHQR failed to compute all the eigenvalues ILO to IHI in a total of 30*(IHI-ILO+1) iterations; if INFO = i, elements i+1:ihi of WR and WI contain those eigenvalues which have been successfully computed. Further Details =============== 2-96 Based on modifications by David Day, Sandia National Laboratory, USA ===================================================================== */ /* Parameter adjustments */ h_dim1 = *ldh; h_offset = 1 + h_dim1; h__ -= h_offset; --wr; --wi; z_dim1 = *ldz; z_offset = 1 + z_dim1; z__ -= z_offset; /* Function Body */ *info = 0; /* Quick return if possible */ if (*n == 0) { return 0; } if (*ilo == *ihi) { wr[*ilo] = h__[*ilo + *ilo * h_dim1]; wi[*ilo] = 0.f; return 0; } nh = *ihi - *ilo + 1; nz = *ihiz - *iloz + 1; /* Set machine-dependent constants for the stopping criterion. If norm(H) <= sqrt(OVFL), overflow should not occur. */ unfl = slamch_("Safe minimum"); ovfl = 1.f / unfl; slabad_(&unfl, &ovfl); ulp = slamch_("Precision"); smlnum = unfl * (nh / ulp); /* I1 and I2 are the indices of the first row and last column of H to which transformations must be applied. If eigenvalues only are being computed, I1 and I2 are set inside the main loop. */ if (*wantt) { i1 = 1; i2 = *n; } /* ITN is the total number of QR iterations allowed. */ itn = nh * 30; /* The main loop begins here. I is the loop index and decreases from IHI to ILO in steps of 1 or 2. Each iteration of the loop works with the active submatrix in rows and columns L to I. Eigenvalues I+1 to IHI have already converged. Either L = ILO or H(L,L-1) is negligible so that the matrix splits. */ i__ = *ihi; L10: l = *ilo; if (i__ < *ilo) { goto L150; } /* Perform QR iterations on rows and columns ILO to I until a submatrix of order 1 or 2 splits off at the bottom because a subdiagonal element has become negligible. */ i__1 = itn; for (its = 0; its <= i__1; ++its) { /* Look for a single small subdiagonal element. */ i__2 = l + 1; for (k = i__; k >= i__2; --k) { tst1 = (r__1 = h__[k - 1 + (k - 1) * h_dim1], dabs(r__1)) + (r__2 = h__[k + k * h_dim1], dabs(r__2)); if (tst1 == 0.f) { i__3 = i__ - l + 1; tst1 = slanhs_("1", &i__3, &h__[l + l * h_dim1], ldh, work); } /* Computing MAX */ r__2 = ulp * tst1; if ((r__1 = h__[k + (k - 1) * h_dim1], dabs(r__1)) <= dmax(r__2, smlnum)) { goto L30; } /* L20: */ } L30: l = k; if (l > *ilo) { /* H(L,L-1) is negligible */ h__[l + (l - 1) * h_dim1] = 0.f; } /* Exit from loop if a submatrix of order 1 or 2 has split off. */ if (l >= i__ - 1) { goto L140; } /* Now the active submatrix is in rows and columns L to I. If eigenvalues only are being computed, only the active submatrix need be transformed. */ if (! (*wantt)) { i1 = l; i2 = i__; } if ((its == 10) || (its == 20)) { /* Exceptional shift. */ s = (r__1 = h__[i__ + (i__ - 1) * h_dim1], dabs(r__1)) + (r__2 = h__[i__ - 1 + (i__ - 2) * h_dim1], dabs(r__2)); h44 = s * .75f + h__[i__ + i__ * h_dim1]; h33 = h44; h43h34 = s * -.4375f * s; } else { /* Prepare to use Francis' double shift (i.e. 2nd degree generalized Rayleigh quotient) */ h44 = h__[i__ + i__ * h_dim1]; h33 = h__[i__ - 1 + (i__ - 1) * h_dim1]; h43h34 = h__[i__ + (i__ - 1) * h_dim1] * h__[i__ - 1 + i__ * h_dim1]; s = h__[i__ - 1 + (i__ - 2) * h_dim1] * h__[i__ - 1 + (i__ - 2) * h_dim1]; disc = (h33 - h44) * .5f; disc = disc * disc + h43h34; if (disc > 0.f) { /* Real roots: use Wilkinson's shift twice */ disc = sqrt(disc); ave = (h33 + h44) * .5f; if (dabs(h33) - dabs(h44) > 0.f) { h33 = h33 * h44 - h43h34; h44 = h33 / (r_sign(&disc, &ave) + ave); } else { h44 = r_sign(&disc, &ave) + ave; } h33 = h44; h43h34 = 0.f; } } /* Look for two consecutive small subdiagonal elements. */ i__2 = l; for (m = i__ - 2; m >= i__2; --m) { /* Determine the effect of starting the double-shift QR iteration at row M, and see if this would make H(M,M-1) negligible. */ h11 = h__[m + m * h_dim1]; h22 = h__[m + 1 + (m + 1) * h_dim1]; h21 = h__[m + 1 + m * h_dim1]; h12 = h__[m + (m + 1) * h_dim1]; h44s = h44 - h11; h33s = h33 - h11; v1 = (h33s * h44s - h43h34) / h21 + h12; v2 = h22 - h11 - h33s - h44s; v3 = h__[m + 2 + (m + 1) * h_dim1]; s = dabs(v1) + dabs(v2) + dabs(v3); v1 /= s; v2 /= s; v3 /= s; v[0] = v1; v[1] = v2; v[2] = v3; if (m == l) { goto L50; } h00 = h__[m - 1 + (m - 1) * h_dim1]; h10 = h__[m + (m - 1) * h_dim1]; tst1 = dabs(v1) * (dabs(h00) + dabs(h11) + dabs(h22)); if (dabs(h10) * (dabs(v2) + dabs(v3)) <= ulp * tst1) { goto L50; } /* L40: */ } L50: /* Double-shift QR step */ i__2 = i__ - 1; for (k = m; k <= i__2; ++k) { /* The first iteration of this loop determines a reflection G from the vector V and applies it from left and right to H, thus creating a nonzero bulge below the subdiagonal. Each subsequent iteration determines a reflection G to restore the Hessenberg form in the (K-1)th column, and thus chases the bulge one step toward the bottom of the active submatrix. NR is the order of G. Computing MIN */ i__3 = 3, i__4 = i__ - k + 1; nr = min(i__3,i__4); if (k > m) { scopy_(&nr, &h__[k + (k - 1) * h_dim1], &c__1, v, &c__1); } slarfg_(&nr, v, &v[1], &c__1, &t1); if (k > m) { h__[k + (k - 1) * h_dim1] = v[0]; h__[k + 1 + (k - 1) * h_dim1] = 0.f; if (k < i__ - 1) { h__[k + 2 + (k - 1) * h_dim1] = 0.f; } } else if (m > l) { h__[k + (k - 1) * h_dim1] = -h__[k + (k - 1) * h_dim1]; } v2 = v[1]; t2 = t1 * v2; if (nr == 3) { v3 = v[2]; t3 = t1 * v3; /* Apply G from the left to transform the rows of the matrix in columns K to I2. */ i__3 = i2; for (j = k; j <= i__3; ++j) { sum = h__[k + j * h_dim1] + v2 * h__[k + 1 + j * h_dim1] + v3 * h__[k + 2 + j * h_dim1]; h__[k + j * h_dim1] -= sum * t1; h__[k + 1 + j * h_dim1] -= sum * t2; h__[k + 2 + j * h_dim1] -= sum * t3; /* L60: */ } /* Apply G from the right to transform the columns of the matrix in rows I1 to min(K+3,I). Computing MIN */ i__4 = k + 3; i__3 = min(i__4,i__); for (j = i1; j <= i__3; ++j) { sum = h__[j + k * h_dim1] + v2 * h__[j + (k + 1) * h_dim1] + v3 * h__[j + (k + 2) * h_dim1]; h__[j + k * h_dim1] -= sum * t1; h__[j + (k + 1) * h_dim1] -= sum * t2; h__[j + (k + 2) * h_dim1] -= sum * t3; /* L70: */ } if (*wantz) { /* Accumulate transformations in the matrix Z */ i__3 = *ihiz; for (j = *iloz; j <= i__3; ++j) { sum = z__[j + k * z_dim1] + v2 * z__[j + (k + 1) * z_dim1] + v3 * z__[j + (k + 2) * z_dim1]; z__[j + k * z_dim1] -= sum * t1; z__[j + (k + 1) * z_dim1] -= sum * t2; z__[j + (k + 2) * z_dim1] -= sum * t3; /* L80: */ } } } else if (nr == 2) { /* Apply G from the left to transform the rows of the matrix in columns K to I2. */ i__3 = i2; for (j = k; j <= i__3; ++j) { sum = h__[k + j * h_dim1] + v2 * h__[k + 1 + j * h_dim1]; h__[k + j * h_dim1] -= sum * t1; h__[k + 1 + j * h_dim1] -= sum * t2; /* L90: */ } /* Apply G from the right to transform the columns of the matrix in rows I1 to min(K+3,I). */ i__3 = i__; for (j = i1; j <= i__3; ++j) { sum = h__[j + k * h_dim1] + v2 * h__[j + (k + 1) * h_dim1] ; h__[j + k * h_dim1] -= sum * t1; h__[j + (k + 1) * h_dim1] -= sum * t2; /* L100: */ } if (*wantz) { /* Accumulate transformations in the matrix Z */ i__3 = *ihiz; for (j = *iloz; j <= i__3; ++j) { sum = z__[j + k * z_dim1] + v2 * z__[j + (k + 1) * z_dim1]; z__[j + k * z_dim1] -= sum * t1; z__[j + (k + 1) * z_dim1] -= sum * t2; /* L110: */ } } } /* L120: */ } /* L130: */ } /* Failure to converge in remaining number of iterations */ *info = i__; return 0; L140: if (l == i__) { /* H(I,I-1) is negligible: one eigenvalue has converged. */ wr[i__] = h__[i__ + i__ * h_dim1]; wi[i__] = 0.f; } else if (l == i__ - 1) { /* H(I-1,I-2) is negligible: a pair of eigenvalues have converged. Transform the 2-by-2 submatrix to standard Schur form, and compute and store the eigenvalues. */ slanv2_(&h__[i__ - 1 + (i__ - 1) * h_dim1], &h__[i__ - 1 + i__ * h_dim1], &h__[i__ + (i__ - 1) * h_dim1], &h__[i__ + i__ * h_dim1], &wr[i__ - 1], &wi[i__ - 1], &wr[i__], &wi[i__], &cs, &sn); if (*wantt) { /* Apply the transformation to the rest of H. */ if (i2 > i__) { i__1 = i2 - i__; srot_(&i__1, &h__[i__ - 1 + (i__ + 1) * h_dim1], ldh, &h__[ i__ + (i__ + 1) * h_dim1], ldh, &cs, &sn); } i__1 = i__ - i1 - 1; srot_(&i__1, &h__[i1 + (i__ - 1) * h_dim1], &c__1, &h__[i1 + i__ * h_dim1], &c__1, &cs, &sn); } if (*wantz) { /* Apply the transformation to Z. */ srot_(&nz, &z__[*iloz + (i__ - 1) * z_dim1], &c__1, &z__[*iloz + i__ * z_dim1], &c__1, &cs, &sn); } } /* Decrement number of remaining iterations, and return to start of the main loop with new value of I. */ itn -= its; i__ = l - 1; goto L10; L150: return 0; /* End of SLAHQR */ } /* slahqr_ */ /* Subroutine */ int slahrd_(integer *n, integer *k, integer *nb, real *a, integer *lda, real *tau, real *t, integer *ldt, real *y, integer *ldy) { /* System generated locals */ integer a_dim1, a_offset, t_dim1, t_offset, y_dim1, y_offset, i__1, i__2, i__3; real r__1; /* Local variables */ static integer i__; static real ei; extern /* Subroutine */ int sscal_(integer *, real *, real *, integer *), sgemv_(char *, integer *, integer *, real *, real *, integer *, real *, integer *, real *, real *, integer *), scopy_( integer *, real *, integer *, real *, integer *), saxpy_(integer * , real *, real *, integer *, real *, integer *), strmv_(char *, char *, char *, integer *, real *, integer *, real *, integer *), slarfg_(integer *, real *, real *, integer *, real *); /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= SLAHRD reduces the first NB columns of a real general n-by-(n-k+1) matrix A so that elements below the k-th subdiagonal are zero. The reduction is performed by an orthogonal similarity transformation Q' * A * Q. The routine returns the matrices V and T which determine Q as a block reflector I - V*T*V', and also the matrix Y = A * V * T. This is an auxiliary routine called by SGEHRD. Arguments ========= N (input) INTEGER The order of the matrix A. K (input) INTEGER The offset for the reduction. Elements below the k-th subdiagonal in the first NB columns are reduced to zero. NB (input) INTEGER The number of columns to be reduced. A (input/output) REAL array, dimension (LDA,N-K+1) On entry, the n-by-(n-k+1) general matrix A. On exit, the elements on and above the k-th subdiagonal in the first NB columns are overwritten with the corresponding elements of the reduced matrix; the elements below the k-th subdiagonal, with the array TAU, represent the matrix Q as a product of elementary reflectors. The other columns of A are unchanged. See Further Details. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,N). TAU (output) REAL array, dimension (NB) The scalar factors of the elementary reflectors. See Further Details. T (output) REAL array, dimension (LDT,NB) The upper triangular matrix T. LDT (input) INTEGER The leading dimension of the array T. LDT >= NB. Y (output) REAL array, dimension (LDY,NB) The n-by-nb matrix Y. LDY (input) INTEGER The leading dimension of the array Y. LDY >= N. Further Details =============== The matrix Q is represented as a product of nb elementary reflectors Q = H(1) H(2) . . . H(nb). Each H(i) has the form H(i) = I - tau * v * v' where tau is a real scalar, and v is a real vector with v(1:i+k-1) = 0, v(i+k) = 1; v(i+k+1:n) is stored on exit in A(i+k+1:n,i), and tau in TAU(i). The elements of the vectors v together form the (n-k+1)-by-nb matrix V which is needed, with T and Y, to apply the transformation to the unreduced part of the matrix, using an update of the form: A := (I - V*T*V') * (A - Y*V'). The contents of A on exit are illustrated by the following example with n = 7, k = 3 and nb = 2: ( a h a a a ) ( a h a a a ) ( a h a a a ) ( h h a a a ) ( v1 h a a a ) ( v1 v2 a a a ) ( v1 v2 a a a ) where a denotes an element of the original matrix A, h denotes a modified element of the upper Hessenberg matrix H, and vi denotes an element of the vector defining H(i). ===================================================================== Quick return if possible */ /* Parameter adjustments */ --tau; a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; t_dim1 = *ldt; t_offset = 1 + t_dim1; t -= t_offset; y_dim1 = *ldy; y_offset = 1 + y_dim1; y -= y_offset; /* Function Body */ if (*n <= 1) { return 0; } i__1 = *nb; for (i__ = 1; i__ <= i__1; ++i__) { if (i__ > 1) { /* Update A(1:n,i) Compute i-th column of A - Y * V' */ i__2 = i__ - 1; sgemv_("No transpose", n, &i__2, &c_b1290, &y[y_offset], ldy, &a[* k + i__ - 1 + a_dim1], lda, &c_b1011, &a[i__ * a_dim1 + 1] , &c__1); /* Apply I - V * T' * V' to this column (call it b) from the left, using the last column of T as workspace Let V = ( V1 ) and b = ( b1 ) (first I-1 rows) ( V2 ) ( b2 ) where V1 is unit lower triangular w := V1' * b1 */ i__2 = i__ - 1; scopy_(&i__2, &a[*k + 1 + i__ * a_dim1], &c__1, &t[*nb * t_dim1 + 1], &c__1); i__2 = i__ - 1; strmv_("Lower", "Transpose", "Unit", &i__2, &a[*k + 1 + a_dim1], lda, &t[*nb * t_dim1 + 1], &c__1); /* w := w + V2'*b2 */ i__2 = *n - *k - i__ + 1; i__3 = i__ - 1; sgemv_("Transpose", &i__2, &i__3, &c_b1011, &a[*k + i__ + a_dim1], lda, &a[*k + i__ + i__ * a_dim1], &c__1, &c_b1011, &t[* nb * t_dim1 + 1], &c__1); /* w := T'*w */ i__2 = i__ - 1; strmv_("Upper", "Transpose", "Non-unit", &i__2, &t[t_offset], ldt, &t[*nb * t_dim1 + 1], &c__1); /* b2 := b2 - V2*w */ i__2 = *n - *k - i__ + 1; i__3 = i__ - 1; sgemv_("No transpose", &i__2, &i__3, &c_b1290, &a[*k + i__ + a_dim1], lda, &t[*nb * t_dim1 + 1], &c__1, &c_b1011, &a[* k + i__ + i__ * a_dim1], &c__1); /* b1 := b1 - V1*w */ i__2 = i__ - 1; strmv_("Lower", "No transpose", "Unit", &i__2, &a[*k + 1 + a_dim1] , lda, &t[*nb * t_dim1 + 1], &c__1); i__2 = i__ - 1; saxpy_(&i__2, &c_b1290, &t[*nb * t_dim1 + 1], &c__1, &a[*k + 1 + i__ * a_dim1], &c__1); a[*k + i__ - 1 + (i__ - 1) * a_dim1] = ei; } /* Generate the elementary reflector H(i) to annihilate A(k+i+1:n,i) */ i__2 = *n - *k - i__ + 1; /* Computing MIN */ i__3 = *k + i__ + 1; slarfg_(&i__2, &a[*k + i__ + i__ * a_dim1], &a[min(i__3,*n) + i__ * a_dim1], &c__1, &tau[i__]); ei = a[*k + i__ + i__ * a_dim1]; a[*k + i__ + i__ * a_dim1] = 1.f; /* Compute Y(1:n,i) */ i__2 = *n - *k - i__ + 1; sgemv_("No transpose", n, &i__2, &c_b1011, &a[(i__ + 1) * a_dim1 + 1], lda, &a[*k + i__ + i__ * a_dim1], &c__1, &c_b320, &y[i__ * y_dim1 + 1], &c__1); i__2 = *n - *k - i__ + 1; i__3 = i__ - 1; sgemv_("Transpose", &i__2, &i__3, &c_b1011, &a[*k + i__ + a_dim1], lda, &a[*k + i__ + i__ * a_dim1], &c__1, &c_b320, &t[i__ * t_dim1 + 1], &c__1); i__2 = i__ - 1; sgemv_("No transpose", n, &i__2, &c_b1290, &y[y_offset], ldy, &t[i__ * t_dim1 + 1], &c__1, &c_b1011, &y[i__ * y_dim1 + 1], &c__1); sscal_(n, &tau[i__], &y[i__ * y_dim1 + 1], &c__1); /* Compute T(1:i,i) */ i__2 = i__ - 1; r__1 = -tau[i__]; sscal_(&i__2, &r__1, &t[i__ * t_dim1 + 1], &c__1); i__2 = i__ - 1; strmv_("Upper", "No transpose", "Non-unit", &i__2, &t[t_offset], ldt, &t[i__ * t_dim1 + 1], &c__1) ; t[i__ + i__ * t_dim1] = tau[i__]; /* L10: */ } a[*k + *nb + *nb * a_dim1] = ei; return 0; /* End of SLAHRD */ } /* slahrd_ */ /* Subroutine */ int slaln2_(logical *ltrans, integer *na, integer *nw, real * smin, real *ca, real *a, integer *lda, real *d1, real *d2, real *b, integer *ldb, real *wr, real *wi, real *x, integer *ldx, real *scale, real *xnorm, integer *info) { /* Initialized data */ static logical cswap[4] = { FALSE_,FALSE_,TRUE_,TRUE_ }; static logical rswap[4] = { FALSE_,TRUE_,FALSE_,TRUE_ }; static integer ipivot[16] /* was [4][4] */ = { 1,2,3,4,2,1,4,3,3,4,1,2, 4,3,2,1 }; /* System generated locals */ integer a_dim1, a_offset, b_dim1, b_offset, x_dim1, x_offset; real r__1, r__2, r__3, r__4, r__5, r__6; static real equiv_0[4], equiv_1[4]; /* Local variables */ static integer j; #define ci (equiv_0) #define cr (equiv_1) static real bi1, bi2, br1, br2, xi1, xi2, xr1, xr2, ci21, ci22, cr21, cr22, li21, csi, ui11, lr21, ui12, ui22; #define civ (equiv_0) static real csr, ur11, ur12, ur22; #define crv (equiv_1) static real bbnd, cmax, ui11r, ui12s, temp, ur11r, ur12s, u22abs; static integer icmax; static real bnorm, cnorm, smini; extern doublereal slamch_(char *); static real bignum; extern /* Subroutine */ int sladiv_(real *, real *, real *, real *, real * , real *); static real smlnum; /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University October 31, 1992 Purpose ======= SLALN2 solves a system of the form (ca A - w D ) X = s B or (ca A' - w D) X = s B with possible scaling ("s") and perturbation of A. (A' means A-transpose.) A is an NA x NA real matrix, ca is a real scalar, D is an NA x NA real diagonal matrix, w is a real or complex value, and X and B are NA x 1 matrices -- real if w is real, complex if w is complex. NA may be 1 or 2. If w is complex, X and B are represented as NA x 2 matrices, the first column of each being the real part and the second being the imaginary part. "s" is a scaling factor (.LE. 1), computed by SLALN2, which is so chosen that X can be computed without overflow. X is further scaled if necessary to assure that norm(ca A - w D)*norm(X) is less than overflow. If both singular values of (ca A - w D) are less than SMIN, SMIN*identity will be used instead of (ca A - w D). If only one singular value is less than SMIN, one element of (ca A - w D) will be perturbed enough to make the smallest singular value roughly SMIN. If both singular values are at least SMIN, (ca A - w D) will not be perturbed. In any case, the perturbation will be at most some small multiple of max( SMIN, ulp*norm(ca A - w D) ). The singular values are computed by infinity-norm approximations, and thus will only be correct to a factor of 2 or so. Note: all input quantities are assumed to be smaller than overflow by a reasonable factor. (See BIGNUM.) Arguments ========== LTRANS (input) LOGICAL =.TRUE.: A-transpose will be used. =.FALSE.: A will be used (not transposed.) NA (input) INTEGER The size of the matrix A. It may (only) be 1 or 2. NW (input) INTEGER 1 if "w" is real, 2 if "w" is complex. It may only be 1 or 2. SMIN (input) REAL The desired lower bound on the singular values of A. This should be a safe distance away from underflow or overflow, say, between (underflow/machine precision) and (machine precision * overflow ). (See BIGNUM and ULP.) CA (input) REAL The coefficient c, which A is multiplied by. A (input) REAL array, dimension (LDA,NA) The NA x NA matrix A. LDA (input) INTEGER The leading dimension of A. It must be at least NA. D1 (input) REAL The 1,1 element in the diagonal matrix D. D2 (input) REAL The 2,2 element in the diagonal matrix D. Not used if NW=1. B (input) REAL array, dimension (LDB,NW) The NA x NW matrix B (right-hand side). If NW=2 ("w" is complex), column 1 contains the real part of B and column 2 contains the imaginary part. LDB (input) INTEGER The leading dimension of B. It must be at least NA. WR (input) REAL The real part of the scalar "w". WI (input) REAL The imaginary part of the scalar "w". Not used if NW=1. X (output) REAL array, dimension (LDX,NW) The NA x NW matrix X (unknowns), as computed by SLALN2. If NW=2 ("w" is complex), on exit, column 1 will contain the real part of X and column 2 will contain the imaginary part. LDX (input) INTEGER The leading dimension of X. It must be at least NA. SCALE (output) REAL The scale factor that B must be multiplied by to insure that overflow does not occur when computing X. Thus, (ca A - w D) X will be SCALE*B, not B (ignoring perturbations of A.) It will be at most 1. XNORM (output) REAL The infinity-norm of X, when X is regarded as an NA x NW real matrix. INFO (output) INTEGER An error flag. It will be set to zero if no error occurs, a negative number if an argument is in error, or a positive number if ca A - w D had to be perturbed. The possible values are: = 0: No error occurred, and (ca A - w D) did not have to be perturbed. = 1: (ca A - w D) had to be perturbed to make its smallest (or only) singular value greater than SMIN. NOTE: In the interests of speed, this routine does not check the inputs for errors. ===================================================================== */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; b_dim1 = *ldb; b_offset = 1 + b_dim1; b -= b_offset; x_dim1 = *ldx; x_offset = 1 + x_dim1; x -= x_offset; /* Function Body */ /* Compute BIGNUM */ smlnum = 2.f * slamch_("Safe minimum"); bignum = 1.f / smlnum; smini = dmax(*smin,smlnum); /* Don't check for input errors */ *info = 0; /* Standard Initializations */ *scale = 1.f; if (*na == 1) { /* 1 x 1 (i.e., scalar) system C X = B */ if (*nw == 1) { /* Real 1x1 system. C = ca A - w D */ csr = *ca * a[a_dim1 + 1] - *wr * *d1; cnorm = dabs(csr); /* If | C | < SMINI, use C = SMINI */ if (cnorm < smini) { csr = smini; cnorm = smini; *info = 1; } /* Check scaling for X = B / C */ bnorm = (r__1 = b[b_dim1 + 1], dabs(r__1)); if (cnorm < 1.f && bnorm > 1.f) { if (bnorm > bignum * cnorm) { *scale = 1.f / bnorm; } } /* Compute X */ x[x_dim1 + 1] = b[b_dim1 + 1] * *scale / csr; *xnorm = (r__1 = x[x_dim1 + 1], dabs(r__1)); } else { /* Complex 1x1 system (w is complex) C = ca A - w D */ csr = *ca * a[a_dim1 + 1] - *wr * *d1; csi = -(*wi) * *d1; cnorm = dabs(csr) + dabs(csi); /* If | C | < SMINI, use C = SMINI */ if (cnorm < smini) { csr = smini; csi = 0.f; cnorm = smini; *info = 1; } /* Check scaling for X = B / C */ bnorm = (r__1 = b[b_dim1 + 1], dabs(r__1)) + (r__2 = b[((b_dim1) << (1)) + 1], dabs(r__2)); if (cnorm < 1.f && bnorm > 1.f) { if (bnorm > bignum * cnorm) { *scale = 1.f / bnorm; } } /* Compute X */ r__1 = *scale * b[b_dim1 + 1]; r__2 = *scale * b[((b_dim1) << (1)) + 1]; sladiv_(&r__1, &r__2, &csr, &csi, &x[x_dim1 + 1], &x[((x_dim1) << (1)) + 1]); *xnorm = (r__1 = x[x_dim1 + 1], dabs(r__1)) + (r__2 = x[((x_dim1) << (1)) + 1], dabs(r__2)); } } else { /* 2x2 System Compute the real part of C = ca A - w D (or ca A' - w D ) */ cr[0] = *ca * a[a_dim1 + 1] - *wr * *d1; cr[3] = *ca * a[((a_dim1) << (1)) + 2] - *wr * *d2; if (*ltrans) { cr[2] = *ca * a[a_dim1 + 2]; cr[1] = *ca * a[((a_dim1) << (1)) + 1]; } else { cr[1] = *ca * a[a_dim1 + 2]; cr[2] = *ca * a[((a_dim1) << (1)) + 1]; } if (*nw == 1) { /* Real 2x2 system (w is real) Find the largest element in C */ cmax = 0.f; icmax = 0; for (j = 1; j <= 4; ++j) { if ((r__1 = crv[j - 1], dabs(r__1)) > cmax) { cmax = (r__1 = crv[j - 1], dabs(r__1)); icmax = j; } /* L10: */ } /* If norm(C) < SMINI, use SMINI*identity. */ if (cmax < smini) { /* Computing MAX */ r__3 = (r__1 = b[b_dim1 + 1], dabs(r__1)), r__4 = (r__2 = b[ b_dim1 + 2], dabs(r__2)); bnorm = dmax(r__3,r__4); if (smini < 1.f && bnorm > 1.f) { if (bnorm > bignum * smini) { *scale = 1.f / bnorm; } } temp = *scale / smini; x[x_dim1 + 1] = temp * b[b_dim1 + 1]; x[x_dim1 + 2] = temp * b[b_dim1 + 2]; *xnorm = temp * bnorm; *info = 1; return 0; } /* Gaussian elimination with complete pivoting. */ ur11 = crv[icmax - 1]; cr21 = crv[ipivot[((icmax) << (2)) - 3] - 1]; ur12 = crv[ipivot[((icmax) << (2)) - 2] - 1]; cr22 = crv[ipivot[((icmax) << (2)) - 1] - 1]; ur11r = 1.f / ur11; lr21 = ur11r * cr21; ur22 = cr22 - ur12 * lr21; /* If smaller pivot < SMINI, use SMINI */ if (dabs(ur22) < smini) { ur22 = smini; *info = 1; } if (rswap[icmax - 1]) { br1 = b[b_dim1 + 2]; br2 = b[b_dim1 + 1]; } else { br1 = b[b_dim1 + 1]; br2 = b[b_dim1 + 2]; } br2 -= lr21 * br1; /* Computing MAX */ r__2 = (r__1 = br1 * (ur22 * ur11r), dabs(r__1)), r__3 = dabs(br2) ; bbnd = dmax(r__2,r__3); if (bbnd > 1.f && dabs(ur22) < 1.f) { if (bbnd >= bignum * dabs(ur22)) { *scale = 1.f / bbnd; } } xr2 = br2 * *scale / ur22; xr1 = *scale * br1 * ur11r - xr2 * (ur11r * ur12); if (cswap[icmax - 1]) { x[x_dim1 + 1] = xr2; x[x_dim1 + 2] = xr1; } else { x[x_dim1 + 1] = xr1; x[x_dim1 + 2] = xr2; } /* Computing MAX */ r__1 = dabs(xr1), r__2 = dabs(xr2); *xnorm = dmax(r__1,r__2); /* Further scaling if norm(A) norm(X) > overflow */ if (*xnorm > 1.f && cmax > 1.f) { if (*xnorm > bignum / cmax) { temp = cmax / bignum; x[x_dim1 + 1] = temp * x[x_dim1 + 1]; x[x_dim1 + 2] = temp * x[x_dim1 + 2]; *xnorm = temp * *xnorm; *scale = temp * *scale; } } } else { /* Complex 2x2 system (w is complex) Find the largest element in C */ ci[0] = -(*wi) * *d1; ci[1] = 0.f; ci[2] = 0.f; ci[3] = -(*wi) * *d2; cmax = 0.f; icmax = 0; for (j = 1; j <= 4; ++j) { if ((r__1 = crv[j - 1], dabs(r__1)) + (r__2 = civ[j - 1], dabs(r__2)) > cmax) { cmax = (r__1 = crv[j - 1], dabs(r__1)) + (r__2 = civ[j - 1], dabs(r__2)); icmax = j; } /* L20: */ } /* If norm(C) < SMINI, use SMINI*identity. */ if (cmax < smini) { /* Computing MAX */ r__5 = (r__1 = b[b_dim1 + 1], dabs(r__1)) + (r__2 = b[(( b_dim1) << (1)) + 1], dabs(r__2)), r__6 = (r__3 = b[ b_dim1 + 2], dabs(r__3)) + (r__4 = b[((b_dim1) << (1)) + 2], dabs(r__4)); bnorm = dmax(r__5,r__6); if (smini < 1.f && bnorm > 1.f) { if (bnorm > bignum * smini) { *scale = 1.f / bnorm; } } temp = *scale / smini; x[x_dim1 + 1] = temp * b[b_dim1 + 1]; x[x_dim1 + 2] = temp * b[b_dim1 + 2]; x[((x_dim1) << (1)) + 1] = temp * b[((b_dim1) << (1)) + 1]; x[((x_dim1) << (1)) + 2] = temp * b[((b_dim1) << (1)) + 2]; *xnorm = temp * bnorm; *info = 1; return 0; } /* Gaussian elimination with complete pivoting. */ ur11 = crv[icmax - 1]; ui11 = civ[icmax - 1]; cr21 = crv[ipivot[((icmax) << (2)) - 3] - 1]; ci21 = civ[ipivot[((icmax) << (2)) - 3] - 1]; ur12 = crv[ipivot[((icmax) << (2)) - 2] - 1]; ui12 = civ[ipivot[((icmax) << (2)) - 2] - 1]; cr22 = crv[ipivot[((icmax) << (2)) - 1] - 1]; ci22 = civ[ipivot[((icmax) << (2)) - 1] - 1]; if ((icmax == 1) || (icmax == 4)) { /* Code when off-diagonals of pivoted C are real */ if (dabs(ur11) > dabs(ui11)) { temp = ui11 / ur11; /* Computing 2nd power */ r__1 = temp; ur11r = 1.f / (ur11 * (r__1 * r__1 + 1.f)); ui11r = -temp * ur11r; } else { temp = ur11 / ui11; /* Computing 2nd power */ r__1 = temp; ui11r = -1.f / (ui11 * (r__1 * r__1 + 1.f)); ur11r = -temp * ui11r; } lr21 = cr21 * ur11r; li21 = cr21 * ui11r; ur12s = ur12 * ur11r; ui12s = ur12 * ui11r; ur22 = cr22 - ur12 * lr21; ui22 = ci22 - ur12 * li21; } else { /* Code when diagonals of pivoted C are real */ ur11r = 1.f / ur11; ui11r = 0.f; lr21 = cr21 * ur11r; li21 = ci21 * ur11r; ur12s = ur12 * ur11r; ui12s = ui12 * ur11r; ur22 = cr22 - ur12 * lr21 + ui12 * li21; ui22 = -ur12 * li21 - ui12 * lr21; } u22abs = dabs(ur22) + dabs(ui22); /* If smaller pivot < SMINI, use SMINI */ if (u22abs < smini) { ur22 = smini; ui22 = 0.f; *info = 1; } if (rswap[icmax - 1]) { br2 = b[b_dim1 + 1]; br1 = b[b_dim1 + 2]; bi2 = b[((b_dim1) << (1)) + 1]; bi1 = b[((b_dim1) << (1)) + 2]; } else { br1 = b[b_dim1 + 1]; br2 = b[b_dim1 + 2]; bi1 = b[((b_dim1) << (1)) + 1]; bi2 = b[((b_dim1) << (1)) + 2]; } br2 = br2 - lr21 * br1 + li21 * bi1; bi2 = bi2 - li21 * br1 - lr21 * bi1; /* Computing MAX */ r__1 = (dabs(br1) + dabs(bi1)) * (u22abs * (dabs(ur11r) + dabs( ui11r))), r__2 = dabs(br2) + dabs(bi2); bbnd = dmax(r__1,r__2); if (bbnd > 1.f && u22abs < 1.f) { if (bbnd >= bignum * u22abs) { *scale = 1.f / bbnd; br1 = *scale * br1; bi1 = *scale * bi1; br2 = *scale * br2; bi2 = *scale * bi2; } } sladiv_(&br2, &bi2, &ur22, &ui22, &xr2, &xi2); xr1 = ur11r * br1 - ui11r * bi1 - ur12s * xr2 + ui12s * xi2; xi1 = ui11r * br1 + ur11r * bi1 - ui12s * xr2 - ur12s * xi2; if (cswap[icmax - 1]) { x[x_dim1 + 1] = xr2; x[x_dim1 + 2] = xr1; x[((x_dim1) << (1)) + 1] = xi2; x[((x_dim1) << (1)) + 2] = xi1; } else { x[x_dim1 + 1] = xr1; x[x_dim1 + 2] = xr2; x[((x_dim1) << (1)) + 1] = xi1; x[((x_dim1) << (1)) + 2] = xi2; } /* Computing MAX */ r__1 = dabs(xr1) + dabs(xi1), r__2 = dabs(xr2) + dabs(xi2); *xnorm = dmax(r__1,r__2); /* Further scaling if norm(A) norm(X) > overflow */ if (*xnorm > 1.f && cmax > 1.f) { if (*xnorm > bignum / cmax) { temp = cmax / bignum; x[x_dim1 + 1] = temp * x[x_dim1 + 1]; x[x_dim1 + 2] = temp * x[x_dim1 + 2]; x[((x_dim1) << (1)) + 1] = temp * x[((x_dim1) << (1)) + 1] ; x[((x_dim1) << (1)) + 2] = temp * x[((x_dim1) << (1)) + 2] ; *xnorm = temp * *xnorm; *scale = temp * *scale; } } } } return 0; /* End of SLALN2 */ } /* slaln2_ */ #undef crv #undef civ #undef cr #undef ci /* Subroutine */ int slals0_(integer *icompq, integer *nl, integer *nr, integer *sqre, integer *nrhs, real *b, integer *ldb, real *bx, integer *ldbx, integer *perm, integer *givptr, integer *givcol, integer *ldgcol, real *givnum, integer *ldgnum, real *poles, real * difl, real *difr, real *z__, integer *k, real *c__, real *s, real * work, integer *info) { /* System generated locals */ integer givcol_dim1, givcol_offset, b_dim1, b_offset, bx_dim1, bx_offset, difr_dim1, difr_offset, givnum_dim1, givnum_offset, poles_dim1, poles_offset, i__1, i__2; real r__1; /* Local variables */ static integer i__, j, m, n; static real dj; static integer nlp1; static real temp; extern /* Subroutine */ int srot_(integer *, real *, integer *, real *, integer *, real *, real *); extern doublereal snrm2_(integer *, real *, integer *); static real diflj, difrj, dsigj; extern /* Subroutine */ int sscal_(integer *, real *, real *, integer *), sgemv_(char *, integer *, integer *, real *, real *, integer *, real *, integer *, real *, real *, integer *), scopy_( integer *, real *, integer *, real *, integer *); extern doublereal slamc3_(real *, real *); extern /* Subroutine */ int xerbla_(char *, integer *); static real dsigjp; extern /* Subroutine */ int slascl_(char *, integer *, integer *, real *, real *, integer *, integer *, real *, integer *, integer *), slacpy_(char *, integer *, integer *, real *, integer *, real *, integer *); /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University December 1, 1999 Purpose ======= SLALS0 applies back the multiplying factors of either the left or the right singular vector matrix of a diagonal matrix appended by a row to the right hand side matrix B in solving the least squares problem using the divide-and-conquer SVD approach. For the left singular vector matrix, three types of orthogonal matrices are involved: (1L) Givens rotations: the number of such rotations is GIVPTR; the pairs of columns/rows they were applied to are stored in GIVCOL; and the C- and S-values of these rotations are stored in GIVNUM. (2L) Permutation. The (NL+1)-st row of B is to be moved to the first row, and for J=2:N, PERM(J)-th row of B is to be moved to the J-th row. (3L) The left singular vector matrix of the remaining matrix. For the right singular vector matrix, four types of orthogonal matrices are involved: (1R) The right singular vector matrix of the remaining matrix. (2R) If SQRE = 1, one extra Givens rotation to generate the right null space. (3R) The inverse transformation of (2L). (4R) The inverse transformation of (1L). Arguments ========= ICOMPQ (input) INTEGER Specifies whether singular vectors are to be computed in factored form: = 0: Left singular vector matrix. = 1: Right singular vector matrix. NL (input) INTEGER The row dimension of the upper block. NL >= 1. NR (input) INTEGER The row dimension of the lower block. NR >= 1. SQRE (input) INTEGER = 0: the lower block is an NR-by-NR square matrix. = 1: the lower block is an NR-by-(NR+1) rectangular matrix. The bidiagonal matrix has row dimension N = NL + NR + 1, and column dimension M = N + SQRE. NRHS (input) INTEGER The number of columns of B and BX. NRHS must be at least 1. B (input/output) REAL array, dimension ( LDB, NRHS ) On input, B contains the right hand sides of the least squares problem in rows 1 through M. On output, B contains the solution X in rows 1 through N. LDB (input) INTEGER The leading dimension of B. LDB must be at least max(1,MAX( M, N ) ). BX (workspace) REAL array, dimension ( LDBX, NRHS ) LDBX (input) INTEGER The leading dimension of BX. PERM (input) INTEGER array, dimension ( N ) The permutations (from deflation and sorting) applied to the two blocks. GIVPTR (input) INTEGER The number of Givens rotations which took place in this subproblem. GIVCOL (input) INTEGER array, dimension ( LDGCOL, 2 ) Each pair of numbers indicates a pair of rows/columns involved in a Givens rotation. LDGCOL (input) INTEGER The leading dimension of GIVCOL, must be at least N. GIVNUM (input) REAL array, dimension ( LDGNUM, 2 ) Each number indicates the C or S value used in the corresponding Givens rotation. LDGNUM (input) INTEGER The leading dimension of arrays DIFR, POLES and GIVNUM, must be at least K. POLES (input) REAL array, dimension ( LDGNUM, 2 ) On entry, POLES(1:K, 1) contains the new singular values obtained from solving the secular equation, and POLES(1:K, 2) is an array containing the poles in the secular equation. DIFL (input) REAL array, dimension ( K ). On entry, DIFL(I) is the distance between I-th updated (undeflated) singular value and the I-th (undeflated) old singular value. DIFR (input) REAL array, dimension ( LDGNUM, 2 ). On entry, DIFR(I, 1) contains the distances between I-th updated (undeflated) singular value and the I+1-th (undeflated) old singular value. And DIFR(I, 2) is the normalizing factor for the I-th right singular vector. Z (input) REAL array, dimension ( K ) Contain the components of the deflation-adjusted updating row vector. K (input) INTEGER Contains the dimension of the non-deflated matrix, This is the order of the related secular equation. 1 <= K <=N. C (input) REAL C contains garbage if SQRE =0 and the C-value of a Givens rotation related to the right null space if SQRE = 1. S (input) REAL S contains garbage if SQRE =0 and the S-value of a Givens rotation related to the right null space if SQRE = 1. WORK (workspace) REAL array, dimension ( K ) INFO (output) INTEGER = 0: successful exit. < 0: if INFO = -i, the i-th argument had an illegal value. Further Details =============== Based on contributions by Ming Gu and Ren-Cang Li, Computer Science Division, University of California at Berkeley, USA Osni Marques, LBNL/NERSC, USA ===================================================================== Test the input parameters. */ /* Parameter adjustments */ b_dim1 = *ldb; b_offset = 1 + b_dim1; b -= b_offset; bx_dim1 = *ldbx; bx_offset = 1 + bx_dim1; bx -= bx_offset; --perm; givcol_dim1 = *ldgcol; givcol_offset = 1 + givcol_dim1; givcol -= givcol_offset; difr_dim1 = *ldgnum; difr_offset = 1 + difr_dim1; difr -= difr_offset; poles_dim1 = *ldgnum; poles_offset = 1 + poles_dim1; poles -= poles_offset; givnum_dim1 = *ldgnum; givnum_offset = 1 + givnum_dim1; givnum -= givnum_offset; --difl; --z__; --work; /* Function Body */ *info = 0; if ((*icompq < 0) || (*icompq > 1)) { *info = -1; } else if (*nl < 1) { *info = -2; } else if (*nr < 1) { *info = -3; } else if ((*sqre < 0) || (*sqre > 1)) { *info = -4; } n = *nl + *nr + 1; if (*nrhs < 1) { *info = -5; } else if (*ldb < n) { *info = -7; } else if (*ldbx < n) { *info = -9; } else if (*givptr < 0) { *info = -11; } else if (*ldgcol < n) { *info = -13; } else if (*ldgnum < n) { *info = -15; } else if (*k < 1) { *info = -20; } if (*info != 0) { i__1 = -(*info); xerbla_("SLALS0", &i__1); return 0; } m = n + *sqre; nlp1 = *nl + 1; if (*icompq == 0) { /* Apply back orthogonal transformations from the left. Step (1L): apply back the Givens rotations performed. */ i__1 = *givptr; for (i__ = 1; i__ <= i__1; ++i__) { srot_(nrhs, &b[givcol[i__ + ((givcol_dim1) << (1))] + b_dim1], ldb, &b[givcol[i__ + givcol_dim1] + b_dim1], ldb, &givnum[ i__ + ((givnum_dim1) << (1))], &givnum[i__ + givnum_dim1]) ; /* L10: */ } /* Step (2L): permute rows of B. */ scopy_(nrhs, &b[nlp1 + b_dim1], ldb, &bx[bx_dim1 + 1], ldbx); i__1 = n; for (i__ = 2; i__ <= i__1; ++i__) { scopy_(nrhs, &b[perm[i__] + b_dim1], ldb, &bx[i__ + bx_dim1], ldbx); /* L20: */ } /* Step (3L): apply the inverse of the left singular vector matrix to BX. */ if (*k == 1) { scopy_(nrhs, &bx[bx_offset], ldbx, &b[b_offset], ldb); if (z__[1] < 0.f) { sscal_(nrhs, &c_b1290, &b[b_offset], ldb); } } else { i__1 = *k; for (j = 1; j <= i__1; ++j) { diflj = difl[j]; dj = poles[j + poles_dim1]; dsigj = -poles[j + ((poles_dim1) << (1))]; if (j < *k) { difrj = -difr[j + difr_dim1]; dsigjp = -poles[j + 1 + ((poles_dim1) << (1))]; } if ((z__[j] == 0.f) || (poles[j + ((poles_dim1) << (1))] == 0.f)) { work[j] = 0.f; } else { work[j] = -poles[j + ((poles_dim1) << (1))] * z__[j] / diflj / (poles[j + ((poles_dim1) << (1))] + dj); } i__2 = j - 1; for (i__ = 1; i__ <= i__2; ++i__) { if ((z__[i__] == 0.f) || (poles[i__ + ((poles_dim1) << (1) )] == 0.f)) { work[i__] = 0.f; } else { work[i__] = poles[i__ + ((poles_dim1) << (1))] * z__[ i__] / (slamc3_(&poles[i__ + ((poles_dim1) << (1))], &dsigj) - diflj) / (poles[i__ + (( poles_dim1) << (1))] + dj); } /* L30: */ } i__2 = *k; for (i__ = j + 1; i__ <= i__2; ++i__) { if ((z__[i__] == 0.f) || (poles[i__ + ((poles_dim1) << (1) )] == 0.f)) { work[i__] = 0.f; } else { work[i__] = poles[i__ + ((poles_dim1) << (1))] * z__[ i__] / (slamc3_(&poles[i__ + ((poles_dim1) << (1))], &dsigjp) + difrj) / (poles[i__ + (( poles_dim1) << (1))] + dj); } /* L40: */ } work[1] = -1.f; temp = snrm2_(k, &work[1], &c__1); sgemv_("T", k, nrhs, &c_b1011, &bx[bx_offset], ldbx, &work[1], &c__1, &c_b320, &b[j + b_dim1], ldb); slascl_("G", &c__0, &c__0, &temp, &c_b1011, &c__1, nrhs, &b[j + b_dim1], ldb, info); /* L50: */ } } /* Move the deflated rows of BX to B also. */ if (*k < max(m,n)) { i__1 = n - *k; slacpy_("A", &i__1, nrhs, &bx[*k + 1 + bx_dim1], ldbx, &b[*k + 1 + b_dim1], ldb); } } else { /* Apply back the right orthogonal transformations. Step (1R): apply back the new right singular vector matrix to B. */ if (*k == 1) { scopy_(nrhs, &b[b_offset], ldb, &bx[bx_offset], ldbx); } else { i__1 = *k; for (j = 1; j <= i__1; ++j) { dsigj = poles[j + ((poles_dim1) << (1))]; if (z__[j] == 0.f) { work[j] = 0.f; } else { work[j] = -z__[j] / difl[j] / (dsigj + poles[j + poles_dim1]) / difr[j + ((difr_dim1) << (1))]; } i__2 = j - 1; for (i__ = 1; i__ <= i__2; ++i__) { if (z__[j] == 0.f) { work[i__] = 0.f; } else { r__1 = -poles[i__ + 1 + ((poles_dim1) << (1))]; work[i__] = z__[j] / (slamc3_(&dsigj, &r__1) - difr[ i__ + difr_dim1]) / (dsigj + poles[i__ + poles_dim1]) / difr[i__ + ((difr_dim1) << (1)) ]; } /* L60: */ } i__2 = *k; for (i__ = j + 1; i__ <= i__2; ++i__) { if (z__[j] == 0.f) { work[i__] = 0.f; } else { r__1 = -poles[i__ + ((poles_dim1) << (1))]; work[i__] = z__[j] / (slamc3_(&dsigj, &r__1) - difl[ i__]) / (dsigj + poles[i__ + poles_dim1]) / difr[i__ + ((difr_dim1) << (1))]; } /* L70: */ } sgemv_("T", k, nrhs, &c_b1011, &b[b_offset], ldb, &work[1], & c__1, &c_b320, &bx[j + bx_dim1], ldbx); /* L80: */ } } /* Step (2R): if SQRE = 1, apply back the rotation that is related to the right null space of the subproblem. */ if (*sqre == 1) { scopy_(nrhs, &b[m + b_dim1], ldb, &bx[m + bx_dim1], ldbx); srot_(nrhs, &bx[bx_dim1 + 1], ldbx, &bx[m + bx_dim1], ldbx, c__, s); } if (*k < max(m,n)) { i__1 = n - *k; slacpy_("A", &i__1, nrhs, &b[*k + 1 + b_dim1], ldb, &bx[*k + 1 + bx_dim1], ldbx); } /* Step (3R): permute rows of B. */ scopy_(nrhs, &bx[bx_dim1 + 1], ldbx, &b[nlp1 + b_dim1], ldb); if (*sqre == 1) { scopy_(nrhs, &bx[m + bx_dim1], ldbx, &b[m + b_dim1], ldb); } i__1 = n; for (i__ = 2; i__ <= i__1; ++i__) { scopy_(nrhs, &bx[i__ + bx_dim1], ldbx, &b[perm[i__] + b_dim1], ldb); /* L90: */ } /* Step (4R): apply back the Givens rotations performed. */ for (i__ = *givptr; i__ >= 1; --i__) { r__1 = -givnum[i__ + givnum_dim1]; srot_(nrhs, &b[givcol[i__ + ((givcol_dim1) << (1))] + b_dim1], ldb, &b[givcol[i__ + givcol_dim1] + b_dim1], ldb, &givnum[ i__ + ((givnum_dim1) << (1))], &r__1); /* L100: */ } } return 0; /* End of SLALS0 */ } /* slals0_ */ /* Subroutine */ int slalsa_(integer *icompq, integer *smlsiz, integer *n, integer *nrhs, real *b, integer *ldb, real *bx, integer *ldbx, real * u, integer *ldu, real *vt, integer *k, real *difl, real *difr, real * z__, real *poles, integer *givptr, integer *givcol, integer *ldgcol, integer *perm, real *givnum, real *c__, real *s, real *work, integer * iwork, integer *info) { /* System generated locals */ integer givcol_dim1, givcol_offset, perm_dim1, perm_offset, b_dim1, b_offset, bx_dim1, bx_offset, difl_dim1, difl_offset, difr_dim1, difr_offset, givnum_dim1, givnum_offset, poles_dim1, poles_offset, u_dim1, u_offset, vt_dim1, vt_offset, z_dim1, z_offset, i__1, i__2; /* Builtin functions */ integer pow_ii(integer *, integer *); /* Local variables */ static integer i__, j, i1, ic, lf, nd, ll, nl, nr, im1, nlf, nrf, lvl, ndb1, nlp1, lvl2, nrp1, nlvl, sqre, inode, ndiml; extern /* Subroutine */ int sgemm_(char *, char *, integer *, integer *, integer *, real *, real *, integer *, real *, integer *, real *, real *, integer *); static integer ndimr; extern /* Subroutine */ int scopy_(integer *, real *, integer *, real *, integer *), slals0_(integer *, integer *, integer *, integer *, integer *, real *, integer *, real *, integer *, integer *, integer *, integer *, integer *, real *, integer *, real *, real * , real *, real *, integer *, real *, real *, real *, integer *), xerbla_(char *, integer *), slasdt_(integer *, integer *, integer *, integer *, integer *, integer *, integer *); /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= SLALSA is an itermediate step in solving the least squares problem by computing the SVD of the coefficient matrix in compact form (The singular vectors are computed as products of simple orthorgonal matrices.). If ICOMPQ = 0, SLALSA applies the inverse of the left singular vector matrix of an upper bidiagonal matrix to the right hand side; and if ICOMPQ = 1, SLALSA applies the right singular vector matrix to the right hand side. The singular vector matrices were generated in compact form by SLALSA. Arguments ========= ICOMPQ (input) INTEGER Specifies whether the left or the right singular vector matrix is involved. = 0: Left singular vector matrix = 1: Right singular vector matrix SMLSIZ (input) INTEGER The maximum size of the subproblems at the bottom of the computation tree. N (input) INTEGER The row and column dimensions of the upper bidiagonal matrix. NRHS (input) INTEGER The number of columns of B and BX. NRHS must be at least 1. B (input) REAL array, dimension ( LDB, NRHS ) On input, B contains the right hand sides of the least squares problem in rows 1 through M. On output, B contains the solution X in rows 1 through N. LDB (input) INTEGER The leading dimension of B in the calling subprogram. LDB must be at least max(1,MAX( M, N ) ). BX (output) REAL array, dimension ( LDBX, NRHS ) On exit, the result of applying the left or right singular vector matrix to B. LDBX (input) INTEGER The leading dimension of BX. U (input) REAL array, dimension ( LDU, SMLSIZ ). On entry, U contains the left singular vector matrices of all subproblems at the bottom level. LDU (input) INTEGER, LDU = > N. The leading dimension of arrays U, VT, DIFL, DIFR, POLES, GIVNUM, and Z. VT (input) REAL array, dimension ( LDU, SMLSIZ+1 ). On entry, VT' contains the right singular vector matrices of all subproblems at the bottom level. K (input) INTEGER array, dimension ( N ). DIFL (input) REAL array, dimension ( LDU, NLVL ). where NLVL = INT(log_2 (N/(SMLSIZ+1))) + 1. DIFR (input) REAL array, dimension ( LDU, 2 * NLVL ). On entry, DIFL(*, I) and DIFR(*, 2 * I -1) record distances between singular values on the I-th level and singular values on the (I -1)-th level, and DIFR(*, 2 * I) record the normalizing factors of the right singular vectors matrices of subproblems on I-th level. Z (input) REAL array, dimension ( LDU, NLVL ). On entry, Z(1, I) contains the components of the deflation- adjusted updating row vector for subproblems on the I-th level. POLES (input) REAL array, dimension ( LDU, 2 * NLVL ). On entry, POLES(*, 2 * I -1: 2 * I) contains the new and old singular values involved in the secular equations on the I-th level. GIVPTR (input) INTEGER array, dimension ( N ). On entry, GIVPTR( I ) records the number of Givens rotations performed on the I-th problem on the computation tree. GIVCOL (input) INTEGER array, dimension ( LDGCOL, 2 * NLVL ). On entry, for each I, GIVCOL(*, 2 * I - 1: 2 * I) records the locations of Givens rotations performed on the I-th level on the computation tree. LDGCOL (input) INTEGER, LDGCOL = > N. The leading dimension of arrays GIVCOL and PERM. PERM (input) INTEGER array, dimension ( LDGCOL, NLVL ). On entry, PERM(*, I) records permutations done on the I-th level of the computation tree. GIVNUM (input) REAL array, dimension ( LDU, 2 * NLVL ). On entry, GIVNUM(*, 2 *I -1 : 2 * I) records the C- and S- values of Givens rotations performed on the I-th level on the computation tree. C (input) REAL array, dimension ( N ). On entry, if the I-th subproblem is not square, C( I ) contains the C-value of a Givens rotation related to the right null space of the I-th subproblem. S (input) REAL array, dimension ( N ). On entry, if the I-th subproblem is not square, S( I ) contains the S-value of a Givens rotation related to the right null space of the I-th subproblem. WORK (workspace) REAL array. The dimension must be at least N. IWORK (workspace) INTEGER array. The dimension must be at least 3 * N INFO (output) INTEGER = 0: successful exit. < 0: if INFO = -i, the i-th argument had an illegal value. Further Details =============== Based on contributions by Ming Gu and Ren-Cang Li, Computer Science Division, University of California at Berkeley, USA Osni Marques, LBNL/NERSC, USA ===================================================================== Test the input parameters. */ /* Parameter adjustments */ b_dim1 = *ldb; b_offset = 1 + b_dim1; b -= b_offset; bx_dim1 = *ldbx; bx_offset = 1 + bx_dim1; bx -= bx_offset; givnum_dim1 = *ldu; givnum_offset = 1 + givnum_dim1; givnum -= givnum_offset; poles_dim1 = *ldu; poles_offset = 1 + poles_dim1; poles -= poles_offset; z_dim1 = *ldu; z_offset = 1 + z_dim1; z__ -= z_offset; difr_dim1 = *ldu; difr_offset = 1 + difr_dim1; difr -= difr_offset; difl_dim1 = *ldu; difl_offset = 1 + difl_dim1; difl -= difl_offset; vt_dim1 = *ldu; vt_offset = 1 + vt_dim1; vt -= vt_offset; u_dim1 = *ldu; u_offset = 1 + u_dim1; u -= u_offset; --k; --givptr; perm_dim1 = *ldgcol; perm_offset = 1 + perm_dim1; perm -= perm_offset; givcol_dim1 = *ldgcol; givcol_offset = 1 + givcol_dim1; givcol -= givcol_offset; --c__; --s; --work; --iwork; /* Function Body */ *info = 0; if ((*icompq < 0) || (*icompq > 1)) { *info = -1; } else if (*smlsiz < 3) { *info = -2; } else if (*n < *smlsiz) { *info = -3; } else if (*nrhs < 1) { *info = -4; } else if (*ldb < *n) { *info = -6; } else if (*ldbx < *n) { *info = -8; } else if (*ldu < *n) { *info = -10; } else if (*ldgcol < *n) { *info = -19; } if (*info != 0) { i__1 = -(*info); xerbla_("SLALSA", &i__1); return 0; } /* Book-keeping and setting up the computation tree. */ inode = 1; ndiml = inode + *n; ndimr = ndiml + *n; slasdt_(n, &nlvl, &nd, &iwork[inode], &iwork[ndiml], &iwork[ndimr], smlsiz); /* The following code applies back the left singular vector factors. For applying back the right singular vector factors, go to 50. */ if (*icompq == 1) { goto L50; } /* The nodes on the bottom level of the tree were solved by SLASDQ. The corresponding left and right singular vector matrices are in explicit form. First apply back the left singular vector matrices. */ ndb1 = (nd + 1) / 2; i__1 = nd; for (i__ = ndb1; i__ <= i__1; ++i__) { /* IC : center row of each node NL : number of rows of left subproblem NR : number of rows of right subproblem NLF: starting row of the left subproblem NRF: starting row of the right subproblem */ i1 = i__ - 1; ic = iwork[inode + i1]; nl = iwork[ndiml + i1]; nr = iwork[ndimr + i1]; nlf = ic - nl; nrf = ic + 1; sgemm_("T", "N", &nl, nrhs, &nl, &c_b1011, &u[nlf + u_dim1], ldu, &b[ nlf + b_dim1], ldb, &c_b320, &bx[nlf + bx_dim1], ldbx); sgemm_("T", "N", &nr, nrhs, &nr, &c_b1011, &u[nrf + u_dim1], ldu, &b[ nrf + b_dim1], ldb, &c_b320, &bx[nrf + bx_dim1], ldbx); /* L10: */ } /* Next copy the rows of B that correspond to unchanged rows in the bidiagonal matrix to BX. */ i__1 = nd; for (i__ = 1; i__ <= i__1; ++i__) { ic = iwork[inode + i__ - 1]; scopy_(nrhs, &b[ic + b_dim1], ldb, &bx[ic + bx_dim1], ldbx); /* L20: */ } /* Finally go through the left singular vector matrices of all the other subproblems bottom-up on the tree. */ j = pow_ii(&c__2, &nlvl); sqre = 0; for (lvl = nlvl; lvl >= 1; --lvl) { lvl2 = ((lvl) << (1)) - 1; /* find the first node LF and last node LL on the current level LVL */ if (lvl == 1) { lf = 1; ll = 1; } else { i__1 = lvl - 1; lf = pow_ii(&c__2, &i__1); ll = ((lf) << (1)) - 1; } i__1 = ll; for (i__ = lf; i__ <= i__1; ++i__) { im1 = i__ - 1; ic = iwork[inode + im1]; nl = iwork[ndiml + im1]; nr = iwork[ndimr + im1]; nlf = ic - nl; nrf = ic + 1; --j; slals0_(icompq, &nl, &nr, &sqre, nrhs, &bx[nlf + bx_dim1], ldbx, & b[nlf + b_dim1], ldb, &perm[nlf + lvl * perm_dim1], & givptr[j], &givcol[nlf + lvl2 * givcol_dim1], ldgcol, & givnum[nlf + lvl2 * givnum_dim1], ldu, &poles[nlf + lvl2 * poles_dim1], &difl[nlf + lvl * difl_dim1], &difr[nlf + lvl2 * difr_dim1], &z__[nlf + lvl * z_dim1], &k[j], &c__[ j], &s[j], &work[1], info); /* L30: */ } /* L40: */ } goto L90; /* ICOMPQ = 1: applying back the right singular vector factors. */ L50: /* First now go through the right singular vector matrices of all the tree nodes top-down. */ j = 0; i__1 = nlvl; for (lvl = 1; lvl <= i__1; ++lvl) { lvl2 = ((lvl) << (1)) - 1; /* Find the first node LF and last node LL on the current level LVL. */ if (lvl == 1) { lf = 1; ll = 1; } else { i__2 = lvl - 1; lf = pow_ii(&c__2, &i__2); ll = ((lf) << (1)) - 1; } i__2 = lf; for (i__ = ll; i__ >= i__2; --i__) { im1 = i__ - 1; ic = iwork[inode + im1]; nl = iwork[ndiml + im1]; nr = iwork[ndimr + im1]; nlf = ic - nl; nrf = ic + 1; if (i__ == ll) { sqre = 0; } else { sqre = 1; } ++j; slals0_(icompq, &nl, &nr, &sqre, nrhs, &b[nlf + b_dim1], ldb, &bx[ nlf + bx_dim1], ldbx, &perm[nlf + lvl * perm_dim1], & givptr[j], &givcol[nlf + lvl2 * givcol_dim1], ldgcol, & givnum[nlf + lvl2 * givnum_dim1], ldu, &poles[nlf + lvl2 * poles_dim1], &difl[nlf + lvl * difl_dim1], &difr[nlf + lvl2 * difr_dim1], &z__[nlf + lvl * z_dim1], &k[j], &c__[ j], &s[j], &work[1], info); /* L60: */ } /* L70: */ } /* The nodes on the bottom level of the tree were solved by SLASDQ. The corresponding right singular vector matrices are in explicit form. Apply them back. */ ndb1 = (nd + 1) / 2; i__1 = nd; for (i__ = ndb1; i__ <= i__1; ++i__) { i1 = i__ - 1; ic = iwork[inode + i1]; nl = iwork[ndiml + i1]; nr = iwork[ndimr + i1]; nlp1 = nl + 1; if (i__ == nd) { nrp1 = nr; } else { nrp1 = nr + 1; } nlf = ic - nl; nrf = ic + 1; sgemm_("T", "N", &nlp1, nrhs, &nlp1, &c_b1011, &vt[nlf + vt_dim1], ldu, &b[nlf + b_dim1], ldb, &c_b320, &bx[nlf + bx_dim1], ldbx); sgemm_("T", "N", &nrp1, nrhs, &nrp1, &c_b1011, &vt[nrf + vt_dim1], ldu, &b[nrf + b_dim1], ldb, &c_b320, &bx[nrf + bx_dim1], ldbx); /* L80: */ } L90: return 0; /* End of SLALSA */ } /* slalsa_ */ /* Subroutine */ int slalsd_(char *uplo, integer *smlsiz, integer *n, integer *nrhs, real *d__, real *e, real *b, integer *ldb, real *rcond, integer *rank, real *work, integer *iwork, integer *info) { /* System generated locals */ integer b_dim1, b_offset, i__1, i__2; real r__1; /* Builtin functions */ double log(doublereal), r_sign(real *, real *); /* Local variables */ static integer c__, i__, j, k; static real r__; static integer s, u, z__; static real cs; static integer bx; static real sn; static integer st, vt, nm1, st1; static real eps; static integer iwk; static real tol; static integer difl, difr, perm, nsub, nlvl, sqre, bxst; extern /* Subroutine */ int srot_(integer *, real *, integer *, real *, integer *, real *, real *), sgemm_(char *, char *, integer *, integer *, integer *, real *, real *, integer *, real *, integer * , real *, real *, integer *); static integer poles, sizei, nsize; extern /* Subroutine */ int scopy_(integer *, real *, integer *, real *, integer *); static integer nwork, icmpq1, icmpq2; extern doublereal slamch_(char *); extern /* Subroutine */ int slasda_(integer *, integer *, integer *, integer *, real *, real *, real *, integer *, real *, integer *, real *, real *, real *, real *, integer *, integer *, integer *, integer *, real *, real *, real *, real *, integer *, integer *), xerbla_(char *, integer *), slalsa_(integer *, integer *, integer *, integer *, real *, integer *, real *, integer *, real * , integer *, real *, integer *, real *, real *, real *, real *, integer *, integer *, integer *, integer *, real *, real *, real * , real *, integer *, integer *), slascl_(char *, integer *, integer *, real *, real *, integer *, integer *, real *, integer * , integer *); static integer givcol; extern integer isamax_(integer *, real *, integer *); extern /* Subroutine */ int slasdq_(char *, integer *, integer *, integer *, integer *, integer *, real *, real *, real *, integer *, real * , integer *, real *, integer *, real *, integer *), slacpy_(char *, integer *, integer *, real *, integer *, real *, integer *), slartg_(real *, real *, real *, real *, real * ), slaset_(char *, integer *, integer *, real *, real *, real *, integer *); static real orgnrm; static integer givnum; extern doublereal slanst_(char *, integer *, real *, real *); extern /* Subroutine */ int slasrt_(char *, integer *, real *, integer *); static integer givptr, smlszp; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University October 31, 1999 Purpose ======= SLALSD uses the singular value decomposition of A to solve the least squares problem of finding X to minimize the Euclidean norm of each column of A*X-B, where A is N-by-N upper bidiagonal, and X and B are N-by-NRHS. The solution X overwrites B. The singular values of A smaller than RCOND times the largest singular value are treated as zero in solving the least squares problem; in this case a minimum norm solution is returned. The actual singular values are returned in D in ascending order. This code makes very mild assumptions about floating point arithmetic. It will work on machines with a guard digit in add/subtract, or on those binary machines without guard digits which subtract like the Cray XMP, Cray YMP, Cray C 90, or Cray 2. It could conceivably fail on hexadecimal or decimal machines without guard digits, but we know of none. Arguments ========= UPLO (input) CHARACTER*1 = 'U': D and E define an upper bidiagonal matrix. = 'L': D and E define a lower bidiagonal matrix. SMLSIZ (input) INTEGER The maximum size of the subproblems at the bottom of the computation tree. N (input) INTEGER The dimension of the bidiagonal matrix. N >= 0. NRHS (input) INTEGER The number of columns of B. NRHS must be at least 1. D (input/output) REAL array, dimension (N) On entry D contains the main diagonal of the bidiagonal matrix. On exit, if INFO = 0, D contains its singular values. E (input) REAL array, dimension (N-1) Contains the super-diagonal entries of the bidiagonal matrix. On exit, E has been destroyed. B (input/output) REAL array, dimension (LDB,NRHS) On input, B contains the right hand sides of the least squares problem. On output, B contains the solution X. LDB (input) INTEGER The leading dimension of B in the calling subprogram. LDB must be at least max(1,N). RCOND (input) REAL The singular values of A less than or equal to RCOND times the largest singular value are treated as zero in solving the least squares problem. If RCOND is negative, machine precision is used instead. For example, if diag(S)*X=B were the least squares problem, where diag(S) is a diagonal matrix of singular values, the solution would be X(i) = B(i) / S(i) if S(i) is greater than RCOND*max(S), and X(i) = 0 if S(i) is less than or equal to RCOND*max(S). RANK (output) INTEGER The number of singular values of A greater than RCOND times the largest singular value. WORK (workspace) REAL array, dimension at least (9*N + 2*N*SMLSIZ + 8*N*NLVL + N*NRHS + (SMLSIZ+1)**2), where NLVL = max(0, INT(log_2 (N/(SMLSIZ+1))) + 1). IWORK (workspace) INTEGER array, dimension at least (3*N*NLVL + 11*N) INFO (output) INTEGER = 0: successful exit. < 0: if INFO = -i, the i-th argument had an illegal value. > 0: The algorithm failed to compute an singular value while working on the submatrix lying in rows and columns INFO/(N+1) through MOD(INFO,N+1). Further Details =============== Based on contributions by Ming Gu and Ren-Cang Li, Computer Science Division, University of California at Berkeley, USA Osni Marques, LBNL/NERSC, USA ===================================================================== Test the input parameters. */ /* Parameter adjustments */ --d__; --e; b_dim1 = *ldb; b_offset = 1 + b_dim1; b -= b_offset; --work; --iwork; /* Function Body */ *info = 0; if (*n < 0) { *info = -3; } else if (*nrhs < 1) { *info = -4; } else if ((*ldb < 1) || (*ldb < *n)) { *info = -8; } if (*info != 0) { i__1 = -(*info); xerbla_("SLALSD", &i__1); return 0; } eps = slamch_("Epsilon"); /* Set up the tolerance. */ if ((*rcond <= 0.f) || (*rcond >= 1.f)) { *rcond = eps; } *rank = 0; /* Quick return if possible. */ if (*n == 0) { return 0; } else if (*n == 1) { if (d__[1] == 0.f) { slaset_("A", &c__1, nrhs, &c_b320, &c_b320, &b[b_offset], ldb); } else { *rank = 1; slascl_("G", &c__0, &c__0, &d__[1], &c_b1011, &c__1, nrhs, &b[ b_offset], ldb, info); d__[1] = dabs(d__[1]); } return 0; } /* Rotate the matrix if it is lower bidiagonal. */ if (*(unsigned char *)uplo == 'L') { i__1 = *n - 1; for (i__ = 1; i__ <= i__1; ++i__) { slartg_(&d__[i__], &e[i__], &cs, &sn, &r__); d__[i__] = r__; e[i__] = sn * d__[i__ + 1]; d__[i__ + 1] = cs * d__[i__ + 1]; if (*nrhs == 1) { srot_(&c__1, &b[i__ + b_dim1], &c__1, &b[i__ + 1 + b_dim1], & c__1, &cs, &sn); } else { work[((i__) << (1)) - 1] = cs; work[i__ * 2] = sn; } /* L10: */ } if (*nrhs > 1) { i__1 = *nrhs; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = *n - 1; for (j = 1; j <= i__2; ++j) { cs = work[((j) << (1)) - 1]; sn = work[j * 2]; srot_(&c__1, &b[j + i__ * b_dim1], &c__1, &b[j + 1 + i__ * b_dim1], &c__1, &cs, &sn); /* L20: */ } /* L30: */ } } } /* Scale. */ nm1 = *n - 1; orgnrm = slanst_("M", n, &d__[1], &e[1]); if (orgnrm == 0.f) { slaset_("A", n, nrhs, &c_b320, &c_b320, &b[b_offset], ldb); return 0; } slascl_("G", &c__0, &c__0, &orgnrm, &c_b1011, n, &c__1, &d__[1], n, info); slascl_("G", &c__0, &c__0, &orgnrm, &c_b1011, &nm1, &c__1, &e[1], &nm1, info); /* If N is smaller than the minimum divide size SMLSIZ, then solve the problem with another solver. */ if (*n <= *smlsiz) { nwork = *n * *n + 1; slaset_("A", n, n, &c_b320, &c_b1011, &work[1], n); slasdq_("U", &c__0, n, n, &c__0, nrhs, &d__[1], &e[1], &work[1], n, & work[1], n, &b[b_offset], ldb, &work[nwork], info); if (*info != 0) { return 0; } tol = *rcond * (r__1 = d__[isamax_(n, &d__[1], &c__1)], dabs(r__1)); i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { if (d__[i__] <= tol) { slaset_("A", &c__1, nrhs, &c_b320, &c_b320, &b[i__ + b_dim1], ldb); } else { slascl_("G", &c__0, &c__0, &d__[i__], &c_b1011, &c__1, nrhs, & b[i__ + b_dim1], ldb, info); ++(*rank); } /* L40: */ } sgemm_("T", "N", n, nrhs, n, &c_b1011, &work[1], n, &b[b_offset], ldb, &c_b320, &work[nwork], n); slacpy_("A", n, nrhs, &work[nwork], n, &b[b_offset], ldb); /* Unscale. */ slascl_("G", &c__0, &c__0, &c_b1011, &orgnrm, n, &c__1, &d__[1], n, info); slasrt_("D", n, &d__[1], info); slascl_("G", &c__0, &c__0, &orgnrm, &c_b1011, n, nrhs, &b[b_offset], ldb, info); return 0; } /* Book-keeping and setting up some constants. */ nlvl = (integer) (log((real) (*n) / (real) (*smlsiz + 1)) / log(2.f)) + 1; smlszp = *smlsiz + 1; u = 1; vt = *smlsiz * *n + 1; difl = vt + smlszp * *n; difr = difl + nlvl * *n; z__ = difr + ((nlvl * *n) << (1)); c__ = z__ + nlvl * *n; s = c__ + *n; poles = s + *n; givnum = poles + ((nlvl) << (1)) * *n; bx = givnum + ((nlvl) << (1)) * *n; nwork = bx + *n * *nrhs; sizei = *n + 1; k = sizei + *n; givptr = k + *n; perm = givptr + *n; givcol = perm + nlvl * *n; iwk = givcol + ((nlvl * *n) << (1)); st = 1; sqre = 0; icmpq1 = 1; icmpq2 = 0; nsub = 0; i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { if ((r__1 = d__[i__], dabs(r__1)) < eps) { d__[i__] = r_sign(&eps, &d__[i__]); } /* L50: */ } i__1 = nm1; for (i__ = 1; i__ <= i__1; ++i__) { if (((r__1 = e[i__], dabs(r__1)) < eps) || (i__ == nm1)) { ++nsub; iwork[nsub] = st; /* Subproblem found. First determine its size and then apply divide and conquer on it. */ if (i__ < nm1) { /* A subproblem with E(I) small for I < NM1. */ nsize = i__ - st + 1; iwork[sizei + nsub - 1] = nsize; } else if ((r__1 = e[i__], dabs(r__1)) >= eps) { /* A subproblem with E(NM1) not too small but I = NM1. */ nsize = *n - st + 1; iwork[sizei + nsub - 1] = nsize; } else { /* A subproblem with E(NM1) small. This implies an 1-by-1 subproblem at D(N), which is not solved explicitly. */ nsize = i__ - st + 1; iwork[sizei + nsub - 1] = nsize; ++nsub; iwork[nsub] = *n; iwork[sizei + nsub - 1] = 1; scopy_(nrhs, &b[*n + b_dim1], ldb, &work[bx + nm1], n); } st1 = st - 1; if (nsize == 1) { /* This is a 1-by-1 subproblem and is not solved explicitly. */ scopy_(nrhs, &b[st + b_dim1], ldb, &work[bx + st1], n); } else if (nsize <= *smlsiz) { /* This is a small subproblem and is solved by SLASDQ. */ slaset_("A", &nsize, &nsize, &c_b320, &c_b1011, &work[vt + st1], n); slasdq_("U", &c__0, &nsize, &nsize, &c__0, nrhs, &d__[st], &e[ st], &work[vt + st1], n, &work[nwork], n, &b[st + b_dim1], ldb, &work[nwork], info); if (*info != 0) { return 0; } slacpy_("A", &nsize, nrhs, &b[st + b_dim1], ldb, &work[bx + st1], n); } else { /* A large problem. Solve it using divide and conquer. */ slasda_(&icmpq1, smlsiz, &nsize, &sqre, &d__[st], &e[st], & work[u + st1], n, &work[vt + st1], &iwork[k + st1], & work[difl + st1], &work[difr + st1], &work[z__ + st1], &work[poles + st1], &iwork[givptr + st1], &iwork[ givcol + st1], n, &iwork[perm + st1], &work[givnum + st1], &work[c__ + st1], &work[s + st1], &work[nwork], &iwork[iwk], info); if (*info != 0) { return 0; } bxst = bx + st1; slalsa_(&icmpq2, smlsiz, &nsize, nrhs, &b[st + b_dim1], ldb, & work[bxst], n, &work[u + st1], n, &work[vt + st1], & iwork[k + st1], &work[difl + st1], &work[difr + st1], &work[z__ + st1], &work[poles + st1], &iwork[givptr + st1], &iwork[givcol + st1], n, &iwork[perm + st1], & work[givnum + st1], &work[c__ + st1], &work[s + st1], &work[nwork], &iwork[iwk], info); if (*info != 0) { return 0; } } st = i__ + 1; } /* L60: */ } /* Apply the singular values and treat the tiny ones as zero. */ tol = *rcond * (r__1 = d__[isamax_(n, &d__[1], &c__1)], dabs(r__1)); i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { /* Some of the elements in D can be negative because 1-by-1 subproblems were not solved explicitly. */ if ((r__1 = d__[i__], dabs(r__1)) <= tol) { slaset_("A", &c__1, nrhs, &c_b320, &c_b320, &work[bx + i__ - 1], n); } else { ++(*rank); slascl_("G", &c__0, &c__0, &d__[i__], &c_b1011, &c__1, nrhs, & work[bx + i__ - 1], n, info); } d__[i__] = (r__1 = d__[i__], dabs(r__1)); /* L70: */ } /* Now apply back the right singular vectors. */ icmpq2 = 1; i__1 = nsub; for (i__ = 1; i__ <= i__1; ++i__) { st = iwork[i__]; st1 = st - 1; nsize = iwork[sizei + i__ - 1]; bxst = bx + st1; if (nsize == 1) { scopy_(nrhs, &work[bxst], n, &b[st + b_dim1], ldb); } else if (nsize <= *smlsiz) { sgemm_("T", "N", &nsize, nrhs, &nsize, &c_b1011, &work[vt + st1], n, &work[bxst], n, &c_b320, &b[st + b_dim1], ldb); } else { slalsa_(&icmpq2, smlsiz, &nsize, nrhs, &work[bxst], n, &b[st + b_dim1], ldb, &work[u + st1], n, &work[vt + st1], &iwork[ k + st1], &work[difl + st1], &work[difr + st1], &work[z__ + st1], &work[poles + st1], &iwork[givptr + st1], &iwork[ givcol + st1], n, &iwork[perm + st1], &work[givnum + st1], &work[c__ + st1], &work[s + st1], &work[nwork], &iwork[ iwk], info); if (*info != 0) { return 0; } } /* L80: */ } /* Unscale and sort the singular values. */ slascl_("G", &c__0, &c__0, &c_b1011, &orgnrm, n, &c__1, &d__[1], n, info); slasrt_("D", n, &d__[1], info); slascl_("G", &c__0, &c__0, &orgnrm, &c_b1011, n, nrhs, &b[b_offset], ldb, info); return 0; /* End of SLALSD */ } /* slalsd_ */ doublereal slamch_(char *cmach) { /* Initialized data */ static logical first = TRUE_; /* System generated locals */ integer i__1; real ret_val; /* Builtin functions */ double pow_ri(real *, integer *); /* Local variables */ static real t; static integer it; static real rnd, eps, base; static integer beta; static real emin, prec, emax; static integer imin, imax; static logical lrnd; static real rmin, rmax, rmach; extern logical lsame_(char *, char *); static real small, sfmin; extern /* Subroutine */ int slamc2_(integer *, integer *, logical *, real *, integer *, real *, integer *, real *); /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University October 31, 1992 Purpose ======= SLAMCH determines single precision machine parameters. Arguments ========= CMACH (input) CHARACTER*1 Specifies the value to be returned by SLAMCH: = 'E' or 'e', SLAMCH := eps = 'S' or 's , SLAMCH := sfmin = 'B' or 'b', SLAMCH := base = 'P' or 'p', SLAMCH := eps*base = 'N' or 'n', SLAMCH := t = 'R' or 'r', SLAMCH := rnd = 'M' or 'm', SLAMCH := emin = 'U' or 'u', SLAMCH := rmin = 'L' or 'l', SLAMCH := emax = 'O' or 'o', SLAMCH := rmax where eps = relative machine precision sfmin = safe minimum, such that 1/sfmin does not overflow base = base of the machine prec = eps*base t = number of (base) digits in the mantissa rnd = 1.0 when rounding occurs in addition, 0.0 otherwise emin = minimum exponent before (gradual) underflow rmin = underflow threshold - base**(emin-1) emax = largest exponent before overflow rmax = overflow threshold - (base**emax)*(1-eps) ===================================================================== */ if (first) { first = FALSE_; slamc2_(&beta, &it, &lrnd, &eps, &imin, &rmin, &imax, &rmax); base = (real) beta; t = (real) it; if (lrnd) { rnd = 1.f; i__1 = 1 - it; eps = pow_ri(&base, &i__1) / 2; } else { rnd = 0.f; i__1 = 1 - it; eps = pow_ri(&base, &i__1); } prec = eps * base; emin = (real) imin; emax = (real) imax; sfmin = rmin; small = 1.f / rmax; if (small >= sfmin) { /* Use SMALL plus a bit, to avoid the possibility of rounding causing overflow when computing 1/sfmin. */ sfmin = small * (eps + 1.f); } } if (lsame_(cmach, "E")) { rmach = eps; } else if (lsame_(cmach, "S")) { rmach = sfmin; } else if (lsame_(cmach, "B")) { rmach = base; } else if (lsame_(cmach, "P")) { rmach = prec; } else if (lsame_(cmach, "N")) { rmach = t; } else if (lsame_(cmach, "R")) { rmach = rnd; } else if (lsame_(cmach, "M")) { rmach = emin; } else if (lsame_(cmach, "U")) { rmach = rmin; } else if (lsame_(cmach, "L")) { rmach = emax; } else if (lsame_(cmach, "O")) { rmach = rmax; } ret_val = rmach; return ret_val; /* End of SLAMCH */ } /* slamch_ */ /* *********************************************************************** */ /* Subroutine */ int slamc1_(integer *beta, integer *t, logical *rnd, logical *ieee1) { /* Initialized data */ static logical first = TRUE_; /* System generated locals */ real r__1, r__2; /* Local variables */ static real a, b, c__, f, t1, t2; static integer lt; static real one, qtr; static logical lrnd; static integer lbeta; static real savec; static logical lieee1; extern doublereal slamc3_(real *, real *); /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University October 31, 1992 Purpose ======= SLAMC1 determines the machine parameters given by BETA, T, RND, and IEEE1. Arguments ========= BETA (output) INTEGER The base of the machine. T (output) INTEGER The number of ( BETA ) digits in the mantissa. RND (output) LOGICAL Specifies whether proper rounding ( RND = .TRUE. ) or chopping ( RND = .FALSE. ) occurs in addition. This may not be a reliable guide to the way in which the machine performs its arithmetic. IEEE1 (output) LOGICAL Specifies whether rounding appears to be done in the IEEE 'round to nearest' style. Further Details =============== The routine is based on the routine ENVRON by Malcolm and incorporates suggestions by Gentleman and Marovich. See Malcolm M. A. (1972) Algorithms to reveal properties of floating-point arithmetic. Comms. of the ACM, 15, 949-951. Gentleman W. M. and Marovich S. B. (1974) More on algorithms that reveal properties of floating point arithmetic units. Comms. of the ACM, 17, 276-277. ===================================================================== */ if (first) { first = FALSE_; one = 1.f; /* LBETA, LIEEE1, LT and LRND are the local values of BETA, IEEE1, T and RND. Throughout this routine we use the function SLAMC3 to ensure that relevant values are stored and not held in registers, or are not affected by optimizers. Compute a = 2.0**m with the smallest positive integer m such that fl( a + 1.0 ) = a. */ a = 1.f; c__ = 1.f; /* + WHILE( C.EQ.ONE )LOOP */ L10: if (c__ == one) { a *= 2; c__ = slamc3_(&a, &one); r__1 = -a; c__ = slamc3_(&c__, &r__1); goto L10; } /* + END WHILE Now compute b = 2.0**m with the smallest positive integer m such that fl( a + b ) .gt. a. */ b = 1.f; c__ = slamc3_(&a, &b); /* + WHILE( C.EQ.A )LOOP */ L20: if (c__ == a) { b *= 2; c__ = slamc3_(&a, &b); goto L20; } /* + END WHILE Now compute the base. a and c are neighbouring floating point numbers in the interval ( beta**t, beta**( t + 1 ) ) and so their difference is beta. Adding 0.25 to c is to ensure that it is truncated to beta and not ( beta - 1 ). */ qtr = one / 4; savec = c__; r__1 = -a; c__ = slamc3_(&c__, &r__1); lbeta = c__ + qtr; /* Now determine whether rounding or chopping occurs, by adding a bit less than beta/2 and a bit more than beta/2 to a. */ b = (real) lbeta; r__1 = b / 2; r__2 = -b / 100; f = slamc3_(&r__1, &r__2); c__ = slamc3_(&f, &a); if (c__ == a) { lrnd = TRUE_; } else { lrnd = FALSE_; } r__1 = b / 2; r__2 = b / 100; f = slamc3_(&r__1, &r__2); c__ = slamc3_(&f, &a); if (lrnd && c__ == a) { lrnd = FALSE_; } /* Try and decide whether rounding is done in the IEEE 'round to nearest' style. B/2 is half a unit in the last place of the two numbers A and SAVEC. Furthermore, A is even, i.e. has last bit zero, and SAVEC is odd. Thus adding B/2 to A should not change A, but adding B/2 to SAVEC should change SAVEC. */ r__1 = b / 2; t1 = slamc3_(&r__1, &a); r__1 = b / 2; t2 = slamc3_(&r__1, &savec); lieee1 = t1 == a && t2 > savec && lrnd; /* Now find the mantissa, t. It should be the integer part of log to the base beta of a, however it is safer to determine t by powering. So we find t as the smallest positive integer for which fl( beta**t + 1.0 ) = 1.0. */ lt = 0; a = 1.f; c__ = 1.f; /* + WHILE( C.EQ.ONE )LOOP */ L30: if (c__ == one) { ++lt; a *= lbeta; c__ = slamc3_(&a, &one); r__1 = -a; c__ = slamc3_(&c__, &r__1); goto L30; } /* + END WHILE */ } *beta = lbeta; *t = lt; *rnd = lrnd; *ieee1 = lieee1; return 0; /* End of SLAMC1 */ } /* slamc1_ */ /* *********************************************************************** */ /* Subroutine */ int slamc2_(integer *beta, integer *t, logical *rnd, real * eps, integer *emin, real *rmin, integer *emax, real *rmax) { /* Initialized data */ static logical first = TRUE_; static logical iwarn = FALSE_; /* Format strings */ static char fmt_9999[] = "(//\002 WARNING. The value EMIN may be incorre" "ct:-\002,\002 EMIN = \002,i8,/\002 If, after inspection, the va" "lue EMIN looks\002,\002 acceptable please comment out \002,/\002" " the IF block as marked within the code of routine\002,\002 SLAM" "C2,\002,/\002 otherwise supply EMIN explicitly.\002,/)"; /* System generated locals */ integer i__1; real r__1, r__2, r__3, r__4, r__5; /* Builtin functions */ double pow_ri(real *, integer *); integer s_wsfe(cilist *), do_fio(integer *, char *, ftnlen), e_wsfe(void); /* Local variables */ static real a, b, c__; static integer i__, lt; static real one, two; static logical ieee; static real half; static logical lrnd; static real leps, zero; static integer lbeta; static real rbase; static integer lemin, lemax, gnmin; static real small; static integer gpmin; static real third, lrmin, lrmax, sixth; static logical lieee1; extern /* Subroutine */ int slamc1_(integer *, integer *, logical *, logical *); extern doublereal slamc3_(real *, real *); extern /* Subroutine */ int slamc4_(integer *, real *, integer *), slamc5_(integer *, integer *, integer *, logical *, integer *, real *); static integer ngnmin, ngpmin; /* Fortran I/O blocks */ static cilist io___3081 = { 0, 6, 0, fmt_9999, 0 }; /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University October 31, 1992 Purpose ======= SLAMC2 determines the machine parameters specified in its argument list. Arguments ========= BETA (output) INTEGER The base of the machine. T (output) INTEGER The number of ( BETA ) digits in the mantissa. RND (output) LOGICAL Specifies whether proper rounding ( RND = .TRUE. ) or chopping ( RND = .FALSE. ) occurs in addition. This may not be a reliable guide to the way in which the machine performs its arithmetic. EPS (output) REAL The smallest positive number such that fl( 1.0 - EPS ) .LT. 1.0, where fl denotes the computed value. EMIN (output) INTEGER The minimum exponent before (gradual) underflow occurs. RMIN (output) REAL The smallest normalized number for the machine, given by BASE**( EMIN - 1 ), where BASE is the floating point value of BETA. EMAX (output) INTEGER The maximum exponent before overflow occurs. RMAX (output) REAL The largest positive number for the machine, given by BASE**EMAX * ( 1 - EPS ), where BASE is the floating point value of BETA. Further Details =============== The computation of EPS is based on a routine PARANOIA by W. Kahan of the University of California at Berkeley. ===================================================================== */ if (first) { first = FALSE_; zero = 0.f; one = 1.f; two = 2.f; /* LBETA, LT, LRND, LEPS, LEMIN and LRMIN are the local values of BETA, T, RND, EPS, EMIN and RMIN. Throughout this routine we use the function SLAMC3 to ensure that relevant values are stored and not held in registers, or are not affected by optimizers. SLAMC1 returns the parameters LBETA, LT, LRND and LIEEE1. */ slamc1_(&lbeta, <, &lrnd, &lieee1); /* Start to find EPS. */ b = (real) lbeta; i__1 = -lt; a = pow_ri(&b, &i__1); leps = a; /* Try some tricks to see whether or not this is the correct EPS. */ b = two / 3; half = one / 2; r__1 = -half; sixth = slamc3_(&b, &r__1); third = slamc3_(&sixth, &sixth); r__1 = -half; b = slamc3_(&third, &r__1); b = slamc3_(&b, &sixth); b = dabs(b); if (b < leps) { b = leps; } leps = 1.f; /* + WHILE( ( LEPS.GT.B ).AND.( B.GT.ZERO ) )LOOP */ L10: if (leps > b && b > zero) { leps = b; r__1 = half * leps; /* Computing 5th power */ r__3 = two, r__4 = r__3, r__3 *= r__3; /* Computing 2nd power */ r__5 = leps; r__2 = r__4 * (r__3 * r__3) * (r__5 * r__5); c__ = slamc3_(&r__1, &r__2); r__1 = -c__; c__ = slamc3_(&half, &r__1); b = slamc3_(&half, &c__); r__1 = -b; c__ = slamc3_(&half, &r__1); b = slamc3_(&half, &c__); goto L10; } /* + END WHILE */ if (a < leps) { leps = a; } /* Computation of EPS complete. Now find EMIN. Let A = + or - 1, and + or - (1 + BASE**(-3)). Keep dividing A by BETA until (gradual) underflow occurs. This is detected when we cannot recover the previous A. */ rbase = one / lbeta; small = one; for (i__ = 1; i__ <= 3; ++i__) { r__1 = small * rbase; small = slamc3_(&r__1, &zero); /* L20: */ } a = slamc3_(&one, &small); slamc4_(&ngpmin, &one, &lbeta); r__1 = -one; slamc4_(&ngnmin, &r__1, &lbeta); slamc4_(&gpmin, &a, &lbeta); r__1 = -a; slamc4_(&gnmin, &r__1, &lbeta); ieee = FALSE_; if (ngpmin == ngnmin && gpmin == gnmin) { if (ngpmin == gpmin) { lemin = ngpmin; /* ( Non twos-complement machines, no gradual underflow; e.g., VAX ) */ } else if (gpmin - ngpmin == 3) { lemin = ngpmin - 1 + lt; ieee = TRUE_; /* ( Non twos-complement machines, with gradual underflow; e.g., IEEE standard followers ) */ } else { lemin = min(ngpmin,gpmin); /* ( A guess; no known machine ) */ iwarn = TRUE_; } } else if (ngpmin == gpmin && ngnmin == gnmin) { if ((i__1 = ngpmin - ngnmin, abs(i__1)) == 1) { lemin = max(ngpmin,ngnmin); /* ( Twos-complement machines, no gradual underflow; e.g., CYBER 205 ) */ } else { lemin = min(ngpmin,ngnmin); /* ( A guess; no known machine ) */ iwarn = TRUE_; } } else if ((i__1 = ngpmin - ngnmin, abs(i__1)) == 1 && gpmin == gnmin) { if (gpmin - min(ngpmin,ngnmin) == 3) { lemin = max(ngpmin,ngnmin) - 1 + lt; /* ( Twos-complement machines with gradual underflow; no known machine ) */ } else { lemin = min(ngpmin,ngnmin); /* ( A guess; no known machine ) */ iwarn = TRUE_; } } else { /* Computing MIN */ i__1 = min(ngpmin,ngnmin), i__1 = min(i__1,gpmin); lemin = min(i__1,gnmin); /* ( A guess; no known machine ) */ iwarn = TRUE_; } /* ** Comment out this if block if EMIN is ok */ if (iwarn) { first = TRUE_; s_wsfe(&io___3081); do_fio(&c__1, (char *)&lemin, (ftnlen)sizeof(integer)); e_wsfe(); } /* ** Assume IEEE arithmetic if we found denormalised numbers above, or if arithmetic seems to round in the IEEE style, determined in routine SLAMC1. A true IEEE machine should have both things true; however, faulty machines may have one or the other. */ ieee = (ieee) || (lieee1); /* Compute RMIN by successive division by BETA. We could compute RMIN as BASE**( EMIN - 1 ), but some machines underflow during this computation. */ lrmin = 1.f; i__1 = 1 - lemin; for (i__ = 1; i__ <= i__1; ++i__) { r__1 = lrmin * rbase; lrmin = slamc3_(&r__1, &zero); /* L30: */ } /* Finally, call SLAMC5 to compute EMAX and RMAX. */ slamc5_(&lbeta, <, &lemin, &ieee, &lemax, &lrmax); } *beta = lbeta; *t = lt; *rnd = lrnd; *eps = leps; *emin = lemin; *rmin = lrmin; *emax = lemax; *rmax = lrmax; return 0; /* End of SLAMC2 */ } /* slamc2_ */ /* *********************************************************************** */ doublereal slamc3_(real *a, real *b) { /* System generated locals */ real ret_val; /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University October 31, 1992 Purpose ======= SLAMC3 is intended to force A and B to be stored prior to doing the addition of A and B , for use in situations where optimizers might hold one of these in a register. Arguments ========= A, B (input) REAL The values A and B. ===================================================================== */ ret_val = *a + *b; return ret_val; /* End of SLAMC3 */ } /* slamc3_ */ /* *********************************************************************** */ /* Subroutine */ int slamc4_(integer *emin, real *start, integer *base) { /* System generated locals */ integer i__1; real r__1; /* Local variables */ static real a; static integer i__; static real b1, b2, c1, c2, d1, d2, one, zero, rbase; extern doublereal slamc3_(real *, real *); /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University October 31, 1992 Purpose ======= SLAMC4 is a service routine for SLAMC2. Arguments ========= EMIN (output) EMIN The minimum exponent before (gradual) underflow, computed by setting A = START and dividing by BASE until the previous A can not be recovered. START (input) REAL The starting point for determining EMIN. BASE (input) INTEGER The base of the machine. ===================================================================== */ a = *start; one = 1.f; rbase = one / *base; zero = 0.f; *emin = 1; r__1 = a * rbase; b1 = slamc3_(&r__1, &zero); c1 = a; c2 = a; d1 = a; d2 = a; /* + WHILE( ( C1.EQ.A ).AND.( C2.EQ.A ).AND. $ ( D1.EQ.A ).AND.( D2.EQ.A ) )LOOP */ L10: if (c1 == a && c2 == a && d1 == a && d2 == a) { --(*emin); a = b1; r__1 = a / *base; b1 = slamc3_(&r__1, &zero); r__1 = b1 * *base; c1 = slamc3_(&r__1, &zero); d1 = zero; i__1 = *base; for (i__ = 1; i__ <= i__1; ++i__) { d1 += b1; /* L20: */ } r__1 = a * rbase; b2 = slamc3_(&r__1, &zero); r__1 = b2 / rbase; c2 = slamc3_(&r__1, &zero); d2 = zero; i__1 = *base; for (i__ = 1; i__ <= i__1; ++i__) { d2 += b2; /* L30: */ } goto L10; } /* + END WHILE */ return 0; /* End of SLAMC4 */ } /* slamc4_ */ /* *********************************************************************** */ /* Subroutine */ int slamc5_(integer *beta, integer *p, integer *emin, logical *ieee, integer *emax, real *rmax) { /* System generated locals */ integer i__1; real r__1; /* Local variables */ static integer i__; static real y, z__; static integer try__, lexp; static real oldy; static integer uexp, nbits; extern doublereal slamc3_(real *, real *); static real recbas; static integer exbits, expsum; /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University October 31, 1992 Purpose ======= SLAMC5 attempts to compute RMAX, the largest machine floating-point number, without overflow. It assumes that EMAX + abs(EMIN) sum approximately to a power of 2. It will fail on machines where this assumption does not hold, for example, the Cyber 205 (EMIN = -28625, EMAX = 28718). It will also fail if the value supplied for EMIN is too large (i.e. too close to zero), probably with overflow. Arguments ========= BETA (input) INTEGER The base of floating-point arithmetic. P (input) INTEGER The number of base BETA digits in the mantissa of a floating-point value. EMIN (input) INTEGER The minimum exponent before (gradual) underflow. IEEE (input) LOGICAL A logical flag specifying whether or not the arithmetic system is thought to comply with the IEEE standard. EMAX (output) INTEGER The largest exponent before overflow RMAX (output) REAL The largest machine floating-point number. ===================================================================== First compute LEXP and UEXP, two powers of 2 that bound abs(EMIN). We then assume that EMAX + abs(EMIN) will sum approximately to the bound that is closest to abs(EMIN). (EMAX is the exponent of the required number RMAX). */ lexp = 1; exbits = 1; L10: try__ = (lexp) << (1); if (try__ <= -(*emin)) { lexp = try__; ++exbits; goto L10; } if (lexp == -(*emin)) { uexp = lexp; } else { uexp = try__; ++exbits; } /* Now -LEXP is less than or equal to EMIN, and -UEXP is greater than or equal to EMIN. EXBITS is the number of bits needed to store the exponent. */ if (uexp + *emin > -lexp - *emin) { expsum = (lexp) << (1); } else { expsum = (uexp) << (1); } /* EXPSUM is the exponent range, approximately equal to EMAX - EMIN + 1 . */ *emax = expsum + *emin - 1; nbits = exbits + 1 + *p; /* NBITS is the total number of bits needed to store a floating-point number. */ if (nbits % 2 == 1 && *beta == 2) { /* Either there are an odd number of bits used to store a floating-point number, which is unlikely, or some bits are not used in the representation of numbers, which is possible, (e.g. Cray machines) or the mantissa has an implicit bit, (e.g. IEEE machines, Dec Vax machines), which is perhaps the most likely. We have to assume the last alternative. If this is true, then we need to reduce EMAX by one because there must be some way of representing zero in an implicit-bit system. On machines like Cray, we are reducing EMAX by one unnecessarily. */ --(*emax); } if (*ieee) { /* Assume we are on an IEEE machine which reserves one exponent for infinity and NaN. */ --(*emax); } /* Now create RMAX, the largest machine number, which should be equal to (1.0 - BETA**(-P)) * BETA**EMAX . First compute 1.0 - BETA**(-P), being careful that the result is less than 1.0 . */ recbas = 1.f / *beta; z__ = *beta - 1.f; y = 0.f; i__1 = *p; for (i__ = 1; i__ <= i__1; ++i__) { z__ *= recbas; if (y < 1.f) { oldy = y; } y = slamc3_(&y, &z__); /* L20: */ } if (y >= 1.f) { y = oldy; } /* Now multiply by BETA**EMAX to get RMAX. */ i__1 = *emax; for (i__ = 1; i__ <= i__1; ++i__) { r__1 = y * *beta; y = slamc3_(&r__1, &c_b320); /* L30: */ } *rmax = y; return 0; /* End of SLAMC5 */ } /* slamc5_ */ /* Subroutine */ int slamrg_(integer *n1, integer *n2, real *a, integer * strd1, integer *strd2, integer *index) { /* System generated locals */ integer i__1; /* Local variables */ static integer i__, ind1, ind2, n1sv, n2sv; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University September 30, 1994 Purpose ======= SLAMRG will create a permutation list which will merge the elements of A (which is composed of two independently sorted sets) into a single set which is sorted in ascending order. Arguments ========= N1 (input) INTEGER N2 (input) INTEGER These arguements contain the respective lengths of the two sorted lists to be merged. A (input) REAL array, dimension (N1+N2) The first N1 elements of A contain a list of numbers which are sorted in either ascending or descending order. Likewise for the final N2 elements. STRD1 (input) INTEGER STRD2 (input) INTEGER These are the strides to be taken through the array A. Allowable strides are 1 and -1. They indicate whether a subset of A is sorted in ascending (STRDx = 1) or descending (STRDx = -1) order. INDEX (output) INTEGER array, dimension (N1+N2) On exit this array will contain a permutation such that if B( I ) = A( INDEX( I ) ) for I=1,N1+N2, then B will be sorted in ascending order. ===================================================================== */ /* Parameter adjustments */ --index; --a; /* Function Body */ n1sv = *n1; n2sv = *n2; if (*strd1 > 0) { ind1 = 1; } else { ind1 = *n1; } if (*strd2 > 0) { ind2 = *n1 + 1; } else { ind2 = *n1 + *n2; } i__ = 1; /* while ( (N1SV > 0) & (N2SV > 0) ) */ L10: if (n1sv > 0 && n2sv > 0) { if (a[ind1] <= a[ind2]) { index[i__] = ind1; ++i__; ind1 += *strd1; --n1sv; } else { index[i__] = ind2; ++i__; ind2 += *strd2; --n2sv; } goto L10; } /* end while */ if (n1sv == 0) { i__1 = n2sv; for (n1sv = 1; n1sv <= i__1; ++n1sv) { index[i__] = ind2; ++i__; ind2 += *strd2; /* L20: */ } } else { /* N2SV .EQ. 0 */ i__1 = n1sv; for (n2sv = 1; n2sv <= i__1; ++n2sv) { index[i__] = ind1; ++i__; ind1 += *strd1; /* L30: */ } } return 0; /* End of SLAMRG */ } /* slamrg_ */ doublereal slange_(char *norm, integer *m, integer *n, real *a, integer *lda, real *work) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2; real ret_val, r__1, r__2, r__3; /* Builtin functions */ double sqrt(doublereal); /* Local variables */ static integer i__, j; static real sum, scale; extern logical lsame_(char *, char *); static real value; extern /* Subroutine */ int slassq_(integer *, real *, integer *, real *, real *); /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University October 31, 1992 Purpose ======= SLANGE returns the value of the one norm, or the Frobenius norm, or the infinity norm, or the element of largest absolute value of a real matrix A. Description =========== SLANGE returns the value SLANGE = ( max(abs(A(i,j))), NORM = 'M' or 'm' ( ( norm1(A), NORM = '1', 'O' or 'o' ( ( normI(A), NORM = 'I' or 'i' ( ( normF(A), NORM = 'F', 'f', 'E' or 'e' where norm1 denotes the one norm of a matrix (maximum column sum), normI denotes the infinity norm of a matrix (maximum row sum) and normF denotes the Frobenius norm of a matrix (square root of sum of squares). Note that max(abs(A(i,j))) is not a matrix norm. Arguments ========= NORM (input) CHARACTER*1 Specifies the value to be returned in SLANGE as described above. M (input) INTEGER The number of rows of the matrix A. M >= 0. When M = 0, SLANGE is set to zero. N (input) INTEGER The number of columns of the matrix A. N >= 0. When N = 0, SLANGE is set to zero. A (input) REAL array, dimension (LDA,N) The m by n matrix A. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(M,1). WORK (workspace) REAL array, dimension (LWORK), where LWORK >= M when NORM = 'I'; otherwise, WORK is not referenced. ===================================================================== */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --work; /* Function Body */ if (min(*m,*n) == 0) { value = 0.f; } else if (lsame_(norm, "M")) { /* Find max(abs(A(i,j))). */ value = 0.f; i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { /* Computing MAX */ r__2 = value, r__3 = (r__1 = a[i__ + j * a_dim1], dabs(r__1)); value = dmax(r__2,r__3); /* L10: */ } /* L20: */ } } else if ((lsame_(norm, "O")) || (*(unsigned char * )norm == '1')) { /* Find norm1(A). */ value = 0.f; i__1 = *n; for (j = 1; j <= i__1; ++j) { sum = 0.f; i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { sum += (r__1 = a[i__ + j * a_dim1], dabs(r__1)); /* L30: */ } value = dmax(value,sum); /* L40: */ } } else if (lsame_(norm, "I")) { /* Find normI(A). */ i__1 = *m; for (i__ = 1; i__ <= i__1; ++i__) { work[i__] = 0.f; /* L50: */ } i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { work[i__] += (r__1 = a[i__ + j * a_dim1], dabs(r__1)); /* L60: */ } /* L70: */ } value = 0.f; i__1 = *m; for (i__ = 1; i__ <= i__1; ++i__) { /* Computing MAX */ r__1 = value, r__2 = work[i__]; value = dmax(r__1,r__2); /* L80: */ } } else if ((lsame_(norm, "F")) || (lsame_(norm, "E"))) { /* Find normF(A). */ scale = 0.f; sum = 1.f; i__1 = *n; for (j = 1; j <= i__1; ++j) { slassq_(m, &a[j * a_dim1 + 1], &c__1, &scale, &sum); /* L90: */ } value = scale * sqrt(sum); } ret_val = value; return ret_val; /* End of SLANGE */ } /* slange_ */ doublereal slanhs_(char *norm, integer *n, real *a, integer *lda, real *work) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3, i__4; real ret_val, r__1, r__2, r__3; /* Builtin functions */ double sqrt(doublereal); /* Local variables */ static integer i__, j; static real sum, scale; extern logical lsame_(char *, char *); static real value; extern /* Subroutine */ int slassq_(integer *, real *, integer *, real *, real *); /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University October 31, 1992 Purpose ======= SLANHS returns the value of the one norm, or the Frobenius norm, or the infinity norm, or the element of largest absolute value of a Hessenberg matrix A. Description =========== SLANHS returns the value SLANHS = ( max(abs(A(i,j))), NORM = 'M' or 'm' ( ( norm1(A), NORM = '1', 'O' or 'o' ( ( normI(A), NORM = 'I' or 'i' ( ( normF(A), NORM = 'F', 'f', 'E' or 'e' where norm1 denotes the one norm of a matrix (maximum column sum), normI denotes the infinity norm of a matrix (maximum row sum) and normF denotes the Frobenius norm of a matrix (square root of sum of squares). Note that max(abs(A(i,j))) is not a matrix norm. Arguments ========= NORM (input) CHARACTER*1 Specifies the value to be returned in SLANHS as described above. N (input) INTEGER The order of the matrix A. N >= 0. When N = 0, SLANHS is set to zero. A (input) REAL array, dimension (LDA,N) The n by n upper Hessenberg matrix A; the part of A below the first sub-diagonal is not referenced. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(N,1). WORK (workspace) REAL array, dimension (LWORK), where LWORK >= N when NORM = 'I'; otherwise, WORK is not referenced. ===================================================================== */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --work; /* Function Body */ if (*n == 0) { value = 0.f; } else if (lsame_(norm, "M")) { /* Find max(abs(A(i,j))). */ value = 0.f; i__1 = *n; for (j = 1; j <= i__1; ++j) { /* Computing MIN */ i__3 = *n, i__4 = j + 1; i__2 = min(i__3,i__4); for (i__ = 1; i__ <= i__2; ++i__) { /* Computing MAX */ r__2 = value, r__3 = (r__1 = a[i__ + j * a_dim1], dabs(r__1)); value = dmax(r__2,r__3); /* L10: */ } /* L20: */ } } else if ((lsame_(norm, "O")) || (*(unsigned char * )norm == '1')) { /* Find norm1(A). */ value = 0.f; i__1 = *n; for (j = 1; j <= i__1; ++j) { sum = 0.f; /* Computing MIN */ i__3 = *n, i__4 = j + 1; i__2 = min(i__3,i__4); for (i__ = 1; i__ <= i__2; ++i__) { sum += (r__1 = a[i__ + j * a_dim1], dabs(r__1)); /* L30: */ } value = dmax(value,sum); /* L40: */ } } else if (lsame_(norm, "I")) { /* Find normI(A). */ i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { work[i__] = 0.f; /* L50: */ } i__1 = *n; for (j = 1; j <= i__1; ++j) { /* Computing MIN */ i__3 = *n, i__4 = j + 1; i__2 = min(i__3,i__4); for (i__ = 1; i__ <= i__2; ++i__) { work[i__] += (r__1 = a[i__ + j * a_dim1], dabs(r__1)); /* L60: */ } /* L70: */ } value = 0.f; i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { /* Computing MAX */ r__1 = value, r__2 = work[i__]; value = dmax(r__1,r__2); /* L80: */ } } else if ((lsame_(norm, "F")) || (lsame_(norm, "E"))) { /* Find normF(A). */ scale = 0.f; sum = 1.f; i__1 = *n; for (j = 1; j <= i__1; ++j) { /* Computing MIN */ i__3 = *n, i__4 = j + 1; i__2 = min(i__3,i__4); slassq_(&i__2, &a[j * a_dim1 + 1], &c__1, &scale, &sum); /* L90: */ } value = scale * sqrt(sum); } ret_val = value; return ret_val; /* End of SLANHS */ } /* slanhs_ */ doublereal slanst_(char *norm, integer *n, real *d__, real *e) { /* System generated locals */ integer i__1; real ret_val, r__1, r__2, r__3, r__4, r__5; /* Builtin functions */ double sqrt(doublereal); /* Local variables */ static integer i__; static real sum, scale; extern logical lsame_(char *, char *); static real anorm; extern /* Subroutine */ int slassq_(integer *, real *, integer *, real *, real *); /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University February 29, 1992 Purpose ======= SLANST returns the value of the one norm, or the Frobenius norm, or the infinity norm, or the element of largest absolute value of a real symmetric tridiagonal matrix A. Description =========== SLANST returns the value SLANST = ( max(abs(A(i,j))), NORM = 'M' or 'm' ( ( norm1(A), NORM = '1', 'O' or 'o' ( ( normI(A), NORM = 'I' or 'i' ( ( normF(A), NORM = 'F', 'f', 'E' or 'e' where norm1 denotes the one norm of a matrix (maximum column sum), normI denotes the infinity norm of a matrix (maximum row sum) and normF denotes the Frobenius norm of a matrix (square root of sum of squares). Note that max(abs(A(i,j))) is not a matrix norm. Arguments ========= NORM (input) CHARACTER*1 Specifies the value to be returned in SLANST as described above. N (input) INTEGER The order of the matrix A. N >= 0. When N = 0, SLANST is set to zero. D (input) REAL array, dimension (N) The diagonal elements of A. E (input) REAL array, dimension (N-1) The (n-1) sub-diagonal or super-diagonal elements of A. ===================================================================== */ /* Parameter adjustments */ --e; --d__; /* Function Body */ if (*n <= 0) { anorm = 0.f; } else if (lsame_(norm, "M")) { /* Find max(abs(A(i,j))). */ anorm = (r__1 = d__[*n], dabs(r__1)); i__1 = *n - 1; for (i__ = 1; i__ <= i__1; ++i__) { /* Computing MAX */ r__2 = anorm, r__3 = (r__1 = d__[i__], dabs(r__1)); anorm = dmax(r__2,r__3); /* Computing MAX */ r__2 = anorm, r__3 = (r__1 = e[i__], dabs(r__1)); anorm = dmax(r__2,r__3); /* L10: */ } } else if (((lsame_(norm, "O")) || (*(unsigned char *)norm == '1')) || (lsame_(norm, "I"))) { /* Find norm1(A). */ if (*n == 1) { anorm = dabs(d__[1]); } else { /* Computing MAX */ r__3 = dabs(d__[1]) + dabs(e[1]), r__4 = (r__1 = e[*n - 1], dabs( r__1)) + (r__2 = d__[*n], dabs(r__2)); anorm = dmax(r__3,r__4); i__1 = *n - 1; for (i__ = 2; i__ <= i__1; ++i__) { /* Computing MAX */ r__4 = anorm, r__5 = (r__1 = d__[i__], dabs(r__1)) + (r__2 = e[i__], dabs(r__2)) + (r__3 = e[i__ - 1], dabs(r__3)); anorm = dmax(r__4,r__5); /* L20: */ } } } else if ((lsame_(norm, "F")) || (lsame_(norm, "E"))) { /* Find normF(A). */ scale = 0.f; sum = 1.f; if (*n > 1) { i__1 = *n - 1; slassq_(&i__1, &e[1], &c__1, &scale, &sum); sum *= 2; } slassq_(n, &d__[1], &c__1, &scale, &sum); anorm = scale * sqrt(sum); } ret_val = anorm; return ret_val; /* End of SLANST */ } /* slanst_ */ doublereal slansy_(char *norm, char *uplo, integer *n, real *a, integer *lda, real *work) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2; real ret_val, r__1, r__2, r__3; /* Builtin functions */ double sqrt(doublereal); /* Local variables */ static integer i__, j; static real sum, absa, scale; extern logical lsame_(char *, char *); static real value; extern /* Subroutine */ int slassq_(integer *, real *, integer *, real *, real *); /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University October 31, 1992 Purpose ======= SLANSY returns the value of the one norm, or the Frobenius norm, or the infinity norm, or the element of largest absolute value of a real symmetric matrix A. Description =========== SLANSY returns the value SLANSY = ( max(abs(A(i,j))), NORM = 'M' or 'm' ( ( norm1(A), NORM = '1', 'O' or 'o' ( ( normI(A), NORM = 'I' or 'i' ( ( normF(A), NORM = 'F', 'f', 'E' or 'e' where norm1 denotes the one norm of a matrix (maximum column sum), normI denotes the infinity norm of a matrix (maximum row sum) and normF denotes the Frobenius norm of a matrix (square root of sum of squares). Note that max(abs(A(i,j))) is not a matrix norm. Arguments ========= NORM (input) CHARACTER*1 Specifies the value to be returned in SLANSY as described above. UPLO (input) CHARACTER*1 Specifies whether the upper or lower triangular part of the symmetric matrix A is to be referenced. = 'U': Upper triangular part of A is referenced = 'L': Lower triangular part of A is referenced N (input) INTEGER The order of the matrix A. N >= 0. When N = 0, SLANSY is set to zero. A (input) REAL array, dimension (LDA,N) 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, and the strictly lower triangular part of A is not referenced. If UPLO = 'L', the leading n by n lower triangular part of A contains the lower triangular part of the matrix A, and the strictly upper triangular part of A is not referenced. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(N,1). WORK (workspace) REAL array, dimension (LWORK), where LWORK >= N when NORM = 'I' or '1' or 'O'; otherwise, WORK is not referenced. ===================================================================== */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --work; /* Function Body */ if (*n == 0) { value = 0.f; } else if (lsame_(norm, "M")) { /* Find max(abs(A(i,j))). */ value = 0.f; if (lsame_(uplo, "U")) { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = j; for (i__ = 1; i__ <= i__2; ++i__) { /* Computing MAX */ r__2 = value, r__3 = (r__1 = a[i__ + j * a_dim1], dabs( r__1)); value = dmax(r__2,r__3); /* L10: */ } /* L20: */ } } else { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *n; for (i__ = j; i__ <= i__2; ++i__) { /* Computing MAX */ r__2 = value, r__3 = (r__1 = a[i__ + j * a_dim1], dabs( r__1)); value = dmax(r__2,r__3); /* L30: */ } /* L40: */ } } } else if (((lsame_(norm, "I")) || (lsame_(norm, "O"))) || (*(unsigned char *)norm == '1')) { /* Find normI(A) ( = norm1(A), since A is symmetric). */ value = 0.f; if (lsame_(uplo, "U")) { i__1 = *n; for (j = 1; j <= i__1; ++j) { sum = 0.f; i__2 = j - 1; for (i__ = 1; i__ <= i__2; ++i__) { absa = (r__1 = a[i__ + j * a_dim1], dabs(r__1)); sum += absa; work[i__] += absa; /* L50: */ } work[j] = sum + (r__1 = a[j + j * a_dim1], dabs(r__1)); /* L60: */ } i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { /* Computing MAX */ r__1 = value, r__2 = work[i__]; value = dmax(r__1,r__2); /* L70: */ } } else { i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { work[i__] = 0.f; /* L80: */ } i__1 = *n; for (j = 1; j <= i__1; ++j) { sum = work[j] + (r__1 = a[j + j * a_dim1], dabs(r__1)); i__2 = *n; for (i__ = j + 1; i__ <= i__2; ++i__) { absa = (r__1 = a[i__ + j * a_dim1], dabs(r__1)); sum += absa; work[i__] += absa; /* L90: */ } value = dmax(value,sum); /* L100: */ } } } else if ((lsame_(norm, "F")) || (lsame_(norm, "E"))) { /* Find normF(A). */ scale = 0.f; sum = 1.f; if (lsame_(uplo, "U")) { i__1 = *n; for (j = 2; j <= i__1; ++j) { i__2 = j - 1; slassq_(&i__2, &a[j * a_dim1 + 1], &c__1, &scale, &sum); /* L110: */ } } else { i__1 = *n - 1; for (j = 1; j <= i__1; ++j) { i__2 = *n - j; slassq_(&i__2, &a[j + 1 + j * a_dim1], &c__1, &scale, &sum); /* L120: */ } } sum *= 2; i__1 = *lda + 1; slassq_(n, &a[a_offset], &i__1, &scale, &sum); value = scale * sqrt(sum); } ret_val = value; return ret_val; /* End of SLANSY */ } /* slansy_ */ /* Subroutine */ int slanv2_(real *a, real *b, real *c__, real *d__, real * rt1r, real *rt1i, real *rt2r, real *rt2i, real *cs, real *sn) { /* System generated locals */ real r__1, r__2; /* Builtin functions */ double r_sign(real *, real *), sqrt(doublereal); /* Local variables */ static real p, z__, aa, bb, cc, dd, cs1, sn1, sab, sac, eps, tau, temp, scale, bcmax, bcmis, sigma; extern doublereal slapy2_(real *, real *), slamch_(char *); /* -- LAPACK driver routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= SLANV2 computes the Schur factorization of a real 2-by-2 nonsymmetric matrix in standard form: [ A B ] = [ CS -SN ] [ AA BB ] [ CS SN ] [ C D ] [ SN CS ] [ CC DD ] [-SN CS ] where either 1) CC = 0 so that AA and DD are real eigenvalues of the matrix, or 2) AA = DD and BB*CC < 0, so that AA + or - sqrt(BB*CC) are complex conjugate eigenvalues. Arguments ========= A (input/output) REAL B (input/output) REAL C (input/output) REAL D (input/output) REAL On entry, the elements of the input matrix. On exit, they are overwritten by the elements of the standardised Schur form. RT1R (output) REAL RT1I (output) REAL RT2R (output) REAL RT2I (output) REAL The real and imaginary parts of the eigenvalues. If the eigenvalues are a complex conjugate pair, RT1I > 0. CS (output) REAL SN (output) REAL Parameters of the rotation matrix. Further Details =============== Modified by V. Sima, Research Institute for Informatics, Bucharest, Romania, to reduce the risk of cancellation errors, when computing real eigenvalues, and to ensure, if possible, that abs(RT1R) >= abs(RT2R). ===================================================================== */ eps = slamch_("P"); if (*c__ == 0.f) { *cs = 1.f; *sn = 0.f; goto L10; } else if (*b == 0.f) { /* Swap rows and columns */ *cs = 0.f; *sn = 1.f; temp = *d__; *d__ = *a; *a = temp; *b = -(*c__); *c__ = 0.f; goto L10; } else if (*a - *d__ == 0.f && r_sign(&c_b1011, b) != r_sign(&c_b1011, c__)) { *cs = 1.f; *sn = 0.f; goto L10; } else { temp = *a - *d__; p = temp * .5f; /* Computing MAX */ r__1 = dabs(*b), r__2 = dabs(*c__); bcmax = dmax(r__1,r__2); /* Computing MIN */ r__1 = dabs(*b), r__2 = dabs(*c__); bcmis = dmin(r__1,r__2) * r_sign(&c_b1011, b) * r_sign(&c_b1011, c__); /* Computing MAX */ r__1 = dabs(p); scale = dmax(r__1,bcmax); z__ = p / scale * p + bcmax / scale * bcmis; /* If Z is of the order of the machine accuracy, postpone the decision on the nature of eigenvalues */ if (z__ >= eps * 4.f) { /* Real eigenvalues. Compute A and D. */ r__1 = sqrt(scale) * sqrt(z__); z__ = p + r_sign(&r__1, &p); *a = *d__ + z__; *d__ -= bcmax / z__ * bcmis; /* Compute B and the rotation matrix */ tau = slapy2_(c__, &z__); *cs = z__ / tau; *sn = *c__ / tau; *b -= *c__; *c__ = 0.f; } else { /* Complex eigenvalues, or real (almost) equal eigenvalues. Make diagonal elements equal. */ sigma = *b + *c__; tau = slapy2_(&sigma, &temp); *cs = sqrt((dabs(sigma) / tau + 1.f) * .5f); *sn = -(p / (tau * *cs)) * r_sign(&c_b1011, &sigma); /* Compute [ AA BB ] = [ A B ] [ CS -SN ] [ CC DD ] [ C D ] [ SN CS ] */ aa = *a * *cs + *b * *sn; bb = -(*a) * *sn + *b * *cs; cc = *c__ * *cs + *d__ * *sn; dd = -(*c__) * *sn + *d__ * *cs; /* Compute [ A B ] = [ CS SN ] [ AA BB ] [ C D ] [-SN CS ] [ CC DD ] */ *a = aa * *cs + cc * *sn; *b = bb * *cs + dd * *sn; *c__ = -aa * *sn + cc * *cs; *d__ = -bb * *sn + dd * *cs; temp = (*a + *d__) * .5f; *a = temp; *d__ = temp; if (*c__ != 0.f) { if (*b != 0.f) { if (r_sign(&c_b1011, b) == r_sign(&c_b1011, c__)) { /* Real eigenvalues: reduce to upper triangular form */ sab = sqrt((dabs(*b))); sac = sqrt((dabs(*c__))); r__1 = sab * sac; p = r_sign(&r__1, c__); tau = 1.f / sqrt((r__1 = *b + *c__, dabs(r__1))); *a = temp + p; *d__ = temp - p; *b -= *c__; *c__ = 0.f; cs1 = sab * tau; sn1 = sac * tau; temp = *cs * cs1 - *sn * sn1; *sn = *cs * sn1 + *sn * cs1; *cs = temp; } } else { *b = -(*c__); *c__ = 0.f; temp = *cs; *cs = -(*sn); *sn = temp; } } } } L10: /* Store eigenvalues in (RT1R,RT1I) and (RT2R,RT2I). */ *rt1r = *a; *rt2r = *d__; if (*c__ == 0.f) { *rt1i = 0.f; *rt2i = 0.f; } else { *rt1i = sqrt((dabs(*b))) * sqrt((dabs(*c__))); *rt2i = -(*rt1i); } return 0; /* End of SLANV2 */ } /* slanv2_ */ doublereal slapy2_(real *x, real *y) { /* System generated locals */ real ret_val, r__1; /* Builtin functions */ double sqrt(doublereal); /* Local variables */ static real w, z__, xabs, yabs; /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University October 31, 1992 Purpose ======= SLAPY2 returns sqrt(x**2+y**2), taking care not to cause unnecessary overflow. Arguments ========= X (input) REAL Y (input) REAL X and Y specify the values x and y. ===================================================================== */ xabs = dabs(*x); yabs = dabs(*y); w = dmax(xabs,yabs); z__ = dmin(xabs,yabs); if (z__ == 0.f) { ret_val = w; } else { /* Computing 2nd power */ r__1 = z__ / w; ret_val = w * sqrt(r__1 * r__1 + 1.f); } return ret_val; /* End of SLAPY2 */ } /* slapy2_ */ doublereal slapy3_(real *x, real *y, real *z__) { /* System generated locals */ real ret_val, r__1, r__2, r__3; /* Builtin functions */ double sqrt(doublereal); /* Local variables */ static real w, xabs, yabs, zabs; /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University October 31, 1992 Purpose ======= SLAPY3 returns sqrt(x**2+y**2+z**2), taking care not to cause unnecessary overflow. Arguments ========= X (input) REAL Y (input) REAL Z (input) REAL X, Y and Z specify the values x, y and z. ===================================================================== */ xabs = dabs(*x); yabs = dabs(*y); zabs = dabs(*z__); /* Computing MAX */ r__1 = max(xabs,yabs); w = dmax(r__1,zabs); if (w == 0.f) { ret_val = 0.f; } else { /* Computing 2nd power */ r__1 = xabs / w; /* Computing 2nd power */ r__2 = yabs / w; /* Computing 2nd power */ r__3 = zabs / w; ret_val = w * sqrt(r__1 * r__1 + r__2 * r__2 + r__3 * r__3); } return ret_val; /* End of SLAPY3 */ } /* slapy3_ */ /* Subroutine */ int slarf_(char *side, integer *m, integer *n, real *v, integer *incv, real *tau, real *c__, integer *ldc, real *work) { /* System generated locals */ integer c_dim1, c_offset; real r__1; /* Local variables */ extern /* Subroutine */ int sger_(integer *, integer *, real *, real *, integer *, real *, integer *, real *, integer *); extern logical lsame_(char *, char *); extern /* Subroutine */ int sgemv_(char *, integer *, integer *, real *, real *, integer *, real *, integer *, real *, real *, integer *); /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University February 29, 1992 Purpose ======= SLARF applies a real elementary reflector H to a real m by n matrix C, from either the left or the right. H is represented in the form H = I - tau * v * v' where tau is a real scalar and v is a real vector. If tau = 0, then H is taken to be the unit matrix. Arguments ========= SIDE (input) CHARACTER*1 = 'L': form H * C = 'R': form C * H M (input) INTEGER The number of rows of the matrix C. N (input) INTEGER The number of columns of the matrix C. V (input) REAL array, dimension (1 + (M-1)*abs(INCV)) if SIDE = 'L' or (1 + (N-1)*abs(INCV)) if SIDE = 'R' The vector v in the representation of H. V is not used if TAU = 0. INCV (input) INTEGER The increment between elements of v. INCV <> 0. TAU (input) REAL The value tau in the representation of H. C (input/output) REAL array, dimension (LDC,N) On entry, the m by n matrix C. On exit, C is overwritten by the matrix H * C if SIDE = 'L', or C * H if SIDE = 'R'. LDC (input) INTEGER The leading dimension of the array C. LDC >= max(1,M). WORK (workspace) REAL array, dimension (N) if SIDE = 'L' or (M) if SIDE = 'R' ===================================================================== */ /* Parameter adjustments */ --v; c_dim1 = *ldc; c_offset = 1 + c_dim1; c__ -= c_offset; --work; /* Function Body */ if (lsame_(side, "L")) { /* Form H * C */ if (*tau != 0.f) { /* w := C' * v */ sgemv_("Transpose", m, n, &c_b1011, &c__[c_offset], ldc, &v[1], incv, &c_b320, &work[1], &c__1); /* C := C - v * w' */ r__1 = -(*tau); sger_(m, n, &r__1, &v[1], incv, &work[1], &c__1, &c__[c_offset], ldc); } } else { /* Form C * H */ if (*tau != 0.f) { /* w := C * v */ sgemv_("No transpose", m, n, &c_b1011, &c__[c_offset], ldc, &v[1], incv, &c_b320, &work[1], &c__1); /* C := C - w * v' */ r__1 = -(*tau); sger_(m, n, &r__1, &work[1], &c__1, &v[1], incv, &c__[c_offset], ldc); } } return 0; /* End of SLARF */ } /* slarf_ */ /* Subroutine */ int slarfb_(char *side, char *trans, char *direct, char * storev, integer *m, integer *n, integer *k, real *v, integer *ldv, real *t, integer *ldt, real *c__, integer *ldc, real *work, integer * ldwork) { /* System generated locals */ integer c_dim1, c_offset, t_dim1, t_offset, v_dim1, v_offset, work_dim1, work_offset, i__1, i__2; /* Local variables */ static integer i__, j; extern logical lsame_(char *, char *); extern /* Subroutine */ int sgemm_(char *, char *, integer *, integer *, integer *, real *, real *, integer *, real *, integer *, real *, real *, integer *), scopy_(integer *, real *, integer *, real *, integer *), strmm_(char *, char *, char *, char *, integer *, integer *, real *, real *, integer *, real *, integer *); static char transt[1]; /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University February 29, 1992 Purpose ======= SLARFB applies a real block reflector H or its transpose H' to a real m by n matrix C, from either the left or the right. Arguments ========= SIDE (input) CHARACTER*1 = 'L': apply H or H' from the Left = 'R': apply H or H' from the Right TRANS (input) CHARACTER*1 = 'N': apply H (No transpose) = 'T': apply H' (Transpose) DIRECT (input) CHARACTER*1 Indicates how H is formed from a product of elementary reflectors = 'F': H = H(1) H(2) . . . H(k) (Forward) = 'B': H = H(k) . . . H(2) H(1) (Backward) STOREV (input) CHARACTER*1 Indicates how the vectors which define the elementary reflectors are stored: = 'C': Columnwise = 'R': Rowwise M (input) INTEGER The number of rows of the matrix C. N (input) INTEGER The number of columns of the matrix C. K (input) INTEGER The order of the matrix T (= the number of elementary reflectors whose product defines the block reflector). V (input) REAL array, dimension (LDV,K) if STOREV = 'C' (LDV,M) if STOREV = 'R' and SIDE = 'L' (LDV,N) if STOREV = 'R' and SIDE = 'R' The matrix V. See further details. LDV (input) INTEGER The leading dimension of the array V. If STOREV = 'C' and SIDE = 'L', LDV >= max(1,M); if STOREV = 'C' and SIDE = 'R', LDV >= max(1,N); if STOREV = 'R', LDV >= K. T (input) REAL array, dimension (LDT,K) The triangular k by k matrix T in the representation of the block reflector. LDT (input) INTEGER The leading dimension of the array T. LDT >= K. C (input/output) REAL array, dimension (LDC,N) On entry, the m by n matrix C. On exit, C is overwritten by H*C or H'*C or C*H or C*H'. LDC (input) INTEGER The leading dimension of the array C. LDA >= max(1,M). WORK (workspace) REAL array, dimension (LDWORK,K) LDWORK (input) INTEGER The leading dimension of the array WORK. If SIDE = 'L', LDWORK >= max(1,N); if SIDE = 'R', LDWORK >= max(1,M). ===================================================================== Quick return if possible */ /* Parameter adjustments */ v_dim1 = *ldv; v_offset = 1 + v_dim1; v -= v_offset; t_dim1 = *ldt; t_offset = 1 + t_dim1; t -= t_offset; c_dim1 = *ldc; c_offset = 1 + c_dim1; c__ -= c_offset; work_dim1 = *ldwork; work_offset = 1 + work_dim1; work -= work_offset; /* Function Body */ if ((*m <= 0) || (*n <= 0)) { return 0; } if (lsame_(trans, "N")) { *(unsigned char *)transt = 'T'; } else { *(unsigned char *)transt = 'N'; } if (lsame_(storev, "C")) { if (lsame_(direct, "F")) { /* Let V = ( V1 ) (first K rows) ( V2 ) where V1 is unit lower triangular. */ if (lsame_(side, "L")) { /* Form H * C or H' * C where C = ( C1 ) ( C2 ) W := C' * V = (C1'*V1 + C2'*V2) (stored in WORK) W := C1' */ i__1 = *k; for (j = 1; j <= i__1; ++j) { scopy_(n, &c__[j + c_dim1], ldc, &work[j * work_dim1 + 1], &c__1); /* L10: */ } /* W := W * V1 */ strmm_("Right", "Lower", "No transpose", "Unit", n, k, & c_b1011, &v[v_offset], ldv, &work[work_offset], ldwork); if (*m > *k) { /* W := W + C2'*V2 */ i__1 = *m - *k; sgemm_("Transpose", "No transpose", n, k, &i__1, &c_b1011, &c__[*k + 1 + c_dim1], ldc, &v[*k + 1 + v_dim1], ldv, &c_b1011, &work[work_offset], ldwork); } /* W := W * T' or W * T */ strmm_("Right", "Upper", transt, "Non-unit", n, k, &c_b1011, & t[t_offset], ldt, &work[work_offset], ldwork); /* C := C - V * W' */ if (*m > *k) { /* C2 := C2 - V2 * W' */ i__1 = *m - *k; sgemm_("No transpose", "Transpose", &i__1, n, k, &c_b1290, &v[*k + 1 + v_dim1], ldv, &work[work_offset], ldwork, &c_b1011, &c__[*k + 1 + c_dim1], ldc); } /* W := W * V1' */ strmm_("Right", "Lower", "Transpose", "Unit", n, k, &c_b1011, &v[v_offset], ldv, &work[work_offset], ldwork); /* C1 := C1 - W' */ i__1 = *k; for (j = 1; j <= i__1; ++j) { i__2 = *n; for (i__ = 1; i__ <= i__2; ++i__) { c__[j + i__ * c_dim1] -= work[i__ + j * work_dim1]; /* L20: */ } /* L30: */ } } else if (lsame_(side, "R")) { /* Form C * H or C * H' where C = ( C1 C2 ) W := C * V = (C1*V1 + C2*V2) (stored in WORK) W := C1 */ i__1 = *k; for (j = 1; j <= i__1; ++j) { scopy_(m, &c__[j * c_dim1 + 1], &c__1, &work[j * work_dim1 + 1], &c__1); /* L40: */ } /* W := W * V1 */ strmm_("Right", "Lower", "No transpose", "Unit", m, k, & c_b1011, &v[v_offset], ldv, &work[work_offset], ldwork); if (*n > *k) { /* W := W + C2 * V2 */ i__1 = *n - *k; sgemm_("No transpose", "No transpose", m, k, &i__1, & c_b1011, &c__[(*k + 1) * c_dim1 + 1], ldc, &v[*k + 1 + v_dim1], ldv, &c_b1011, &work[work_offset], ldwork); } /* W := W * T or W * T' */ strmm_("Right", "Upper", trans, "Non-unit", m, k, &c_b1011, & t[t_offset], ldt, &work[work_offset], ldwork); /* C := C - W * V' */ if (*n > *k) { /* C2 := C2 - W * V2' */ i__1 = *n - *k; sgemm_("No transpose", "Transpose", m, &i__1, k, &c_b1290, &work[work_offset], ldwork, &v[*k + 1 + v_dim1], ldv, &c_b1011, &c__[(*k + 1) * c_dim1 + 1], ldc); } /* W := W * V1' */ strmm_("Right", "Lower", "Transpose", "Unit", m, k, &c_b1011, &v[v_offset], ldv, &work[work_offset], ldwork); /* C1 := C1 - W */ i__1 = *k; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { c__[i__ + j * c_dim1] -= work[i__ + j * work_dim1]; /* L50: */ } /* L60: */ } } } else { /* Let V = ( V1 ) ( V2 ) (last K rows) where V2 is unit upper triangular. */ if (lsame_(side, "L")) { /* Form H * C or H' * C where C = ( C1 ) ( C2 ) W := C' * V = (C1'*V1 + C2'*V2) (stored in WORK) W := C2' */ i__1 = *k; for (j = 1; j <= i__1; ++j) { scopy_(n, &c__[*m - *k + j + c_dim1], ldc, &work[j * work_dim1 + 1], &c__1); /* L70: */ } /* W := W * V2 */ strmm_("Right", "Upper", "No transpose", "Unit", n, k, & c_b1011, &v[*m - *k + 1 + v_dim1], ldv, &work[ work_offset], ldwork); if (*m > *k) { /* W := W + C1'*V1 */ i__1 = *m - *k; sgemm_("Transpose", "No transpose", n, k, &i__1, &c_b1011, &c__[c_offset], ldc, &v[v_offset], ldv, &c_b1011, &work[work_offset], ldwork); } /* W := W * T' or W * T */ strmm_("Right", "Lower", transt, "Non-unit", n, k, &c_b1011, & t[t_offset], ldt, &work[work_offset], ldwork); /* C := C - V * W' */ if (*m > *k) { /* C1 := C1 - V1 * W' */ i__1 = *m - *k; sgemm_("No transpose", "Transpose", &i__1, n, k, &c_b1290, &v[v_offset], ldv, &work[work_offset], ldwork, & c_b1011, &c__[c_offset], ldc); } /* W := W * V2' */ strmm_("Right", "Upper", "Transpose", "Unit", n, k, &c_b1011, &v[*m - *k + 1 + v_dim1], ldv, &work[work_offset], ldwork); /* C2 := C2 - W' */ i__1 = *k; for (j = 1; j <= i__1; ++j) { i__2 = *n; for (i__ = 1; i__ <= i__2; ++i__) { c__[*m - *k + j + i__ * c_dim1] -= work[i__ + j * work_dim1]; /* L80: */ } /* L90: */ } } else if (lsame_(side, "R")) { /* Form C * H or C * H' where C = ( C1 C2 ) W := C * V = (C1*V1 + C2*V2) (stored in WORK) W := C2 */ i__1 = *k; for (j = 1; j <= i__1; ++j) { scopy_(m, &c__[(*n - *k + j) * c_dim1 + 1], &c__1, &work[ j * work_dim1 + 1], &c__1); /* L100: */ } /* W := W * V2 */ strmm_("Right", "Upper", "No transpose", "Unit", m, k, & c_b1011, &v[*n - *k + 1 + v_dim1], ldv, &work[ work_offset], ldwork); if (*n > *k) { /* W := W + C1 * V1 */ i__1 = *n - *k; sgemm_("No transpose", "No transpose", m, k, &i__1, & c_b1011, &c__[c_offset], ldc, &v[v_offset], ldv, & c_b1011, &work[work_offset], ldwork); } /* W := W * T or W * T' */ strmm_("Right", "Lower", trans, "Non-unit", m, k, &c_b1011, & t[t_offset], ldt, &work[work_offset], ldwork); /* C := C - W * V' */ if (*n > *k) { /* C1 := C1 - W * V1' */ i__1 = *n - *k; sgemm_("No transpose", "Transpose", m, &i__1, k, &c_b1290, &work[work_offset], ldwork, &v[v_offset], ldv, & c_b1011, &c__[c_offset], ldc); } /* W := W * V2' */ strmm_("Right", "Upper", "Transpose", "Unit", m, k, &c_b1011, &v[*n - *k + 1 + v_dim1], ldv, &work[work_offset], ldwork); /* C2 := C2 - W */ i__1 = *k; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { c__[i__ + (*n - *k + j) * c_dim1] -= work[i__ + j * work_dim1]; /* L110: */ } /* L120: */ } } } } else if (lsame_(storev, "R")) { if (lsame_(direct, "F")) { /* Let V = ( V1 V2 ) (V1: first K columns) where V1 is unit upper triangular. */ if (lsame_(side, "L")) { /* Form H * C or H' * C where C = ( C1 ) ( C2 ) W := C' * V' = (C1'*V1' + C2'*V2') (stored in WORK) W := C1' */ i__1 = *k; for (j = 1; j <= i__1; ++j) { scopy_(n, &c__[j + c_dim1], ldc, &work[j * work_dim1 + 1], &c__1); /* L130: */ } /* W := W * V1' */ strmm_("Right", "Upper", "Transpose", "Unit", n, k, &c_b1011, &v[v_offset], ldv, &work[work_offset], ldwork); if (*m > *k) { /* W := W + C2'*V2' */ i__1 = *m - *k; sgemm_("Transpose", "Transpose", n, k, &i__1, &c_b1011, & c__[*k + 1 + c_dim1], ldc, &v[(*k + 1) * v_dim1 + 1], ldv, &c_b1011, &work[work_offset], ldwork); } /* W := W * T' or W * T */ strmm_("Right", "Upper", transt, "Non-unit", n, k, &c_b1011, & t[t_offset], ldt, &work[work_offset], ldwork); /* C := C - V' * W' */ if (*m > *k) { /* C2 := C2 - V2' * W' */ i__1 = *m - *k; sgemm_("Transpose", "Transpose", &i__1, n, k, &c_b1290, & v[(*k + 1) * v_dim1 + 1], ldv, &work[work_offset], ldwork, &c_b1011, &c__[*k + 1 + c_dim1], ldc); } /* W := W * V1 */ strmm_("Right", "Upper", "No transpose", "Unit", n, k, & c_b1011, &v[v_offset], ldv, &work[work_offset], ldwork); /* C1 := C1 - W' */ i__1 = *k; for (j = 1; j <= i__1; ++j) { i__2 = *n; for (i__ = 1; i__ <= i__2; ++i__) { c__[j + i__ * c_dim1] -= work[i__ + j * work_dim1]; /* L140: */ } /* L150: */ } } else if (lsame_(side, "R")) { /* Form C * H or C * H' where C = ( C1 C2 ) W := C * V' = (C1*V1' + C2*V2') (stored in WORK) W := C1 */ i__1 = *k; for (j = 1; j <= i__1; ++j) { scopy_(m, &c__[j * c_dim1 + 1], &c__1, &work[j * work_dim1 + 1], &c__1); /* L160: */ } /* W := W * V1' */ strmm_("Right", "Upper", "Transpose", "Unit", m, k, &c_b1011, &v[v_offset], ldv, &work[work_offset], ldwork); if (*n > *k) { /* W := W + C2 * V2' */ i__1 = *n - *k; sgemm_("No transpose", "Transpose", m, k, &i__1, &c_b1011, &c__[(*k + 1) * c_dim1 + 1], ldc, &v[(*k + 1) * v_dim1 + 1], ldv, &c_b1011, &work[work_offset], ldwork); } /* W := W * T or W * T' */ strmm_("Right", "Upper", trans, "Non-unit", m, k, &c_b1011, & t[t_offset], ldt, &work[work_offset], ldwork); /* C := C - W * V */ if (*n > *k) { /* C2 := C2 - W * V2 */ i__1 = *n - *k; sgemm_("No transpose", "No transpose", m, &i__1, k, & c_b1290, &work[work_offset], ldwork, &v[(*k + 1) * v_dim1 + 1], ldv, &c_b1011, &c__[(*k + 1) * c_dim1 + 1], ldc); } /* W := W * V1 */ strmm_("Right", "Upper", "No transpose", "Unit", m, k, & c_b1011, &v[v_offset], ldv, &work[work_offset], ldwork); /* C1 := C1 - W */ i__1 = *k; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { c__[i__ + j * c_dim1] -= work[i__ + j * work_dim1]; /* L170: */ } /* L180: */ } } } else { /* Let V = ( V1 V2 ) (V2: last K columns) where V2 is unit lower triangular. */ if (lsame_(side, "L")) { /* Form H * C or H' * C where C = ( C1 ) ( C2 ) W := C' * V' = (C1'*V1' + C2'*V2') (stored in WORK) W := C2' */ i__1 = *k; for (j = 1; j <= i__1; ++j) { scopy_(n, &c__[*m - *k + j + c_dim1], ldc, &work[j * work_dim1 + 1], &c__1); /* L190: */ } /* W := W * V2' */ strmm_("Right", "Lower", "Transpose", "Unit", n, k, &c_b1011, &v[(*m - *k + 1) * v_dim1 + 1], ldv, &work[ work_offset], ldwork); if (*m > *k) { /* W := W + C1'*V1' */ i__1 = *m - *k; sgemm_("Transpose", "Transpose", n, k, &i__1, &c_b1011, & c__[c_offset], ldc, &v[v_offset], ldv, &c_b1011, & work[work_offset], ldwork); } /* W := W * T' or W * T */ strmm_("Right", "Lower", transt, "Non-unit", n, k, &c_b1011, & t[t_offset], ldt, &work[work_offset], ldwork); /* C := C - V' * W' */ if (*m > *k) { /* C1 := C1 - V1' * W' */ i__1 = *m - *k; sgemm_("Transpose", "Transpose", &i__1, n, k, &c_b1290, & v[v_offset], ldv, &work[work_offset], ldwork, & c_b1011, &c__[c_offset], ldc); } /* W := W * V2 */ strmm_("Right", "Lower", "No transpose", "Unit", n, k, & c_b1011, &v[(*m - *k + 1) * v_dim1 + 1], ldv, &work[ work_offset], ldwork); /* C2 := C2 - W' */ i__1 = *k; for (j = 1; j <= i__1; ++j) { i__2 = *n; for (i__ = 1; i__ <= i__2; ++i__) { c__[*m - *k + j + i__ * c_dim1] -= work[i__ + j * work_dim1]; /* L200: */ } /* L210: */ } } else if (lsame_(side, "R")) { /* Form C * H or C * H' where C = ( C1 C2 ) W := C * V' = (C1*V1' + C2*V2') (stored in WORK) W := C2 */ i__1 = *k; for (j = 1; j <= i__1; ++j) { scopy_(m, &c__[(*n - *k + j) * c_dim1 + 1], &c__1, &work[ j * work_dim1 + 1], &c__1); /* L220: */ } /* W := W * V2' */ strmm_("Right", "Lower", "Transpose", "Unit", m, k, &c_b1011, &v[(*n - *k + 1) * v_dim1 + 1], ldv, &work[ work_offset], ldwork); if (*n > *k) { /* W := W + C1 * V1' */ i__1 = *n - *k; sgemm_("No transpose", "Transpose", m, k, &i__1, &c_b1011, &c__[c_offset], ldc, &v[v_offset], ldv, &c_b1011, &work[work_offset], ldwork); } /* W := W * T or W * T' */ strmm_("Right", "Lower", trans, "Non-unit", m, k, &c_b1011, & t[t_offset], ldt, &work[work_offset], ldwork); /* C := C - W * V */ if (*n > *k) { /* C1 := C1 - W * V1 */ i__1 = *n - *k; sgemm_("No transpose", "No transpose", m, &i__1, k, & c_b1290, &work[work_offset], ldwork, &v[v_offset], ldv, &c_b1011, &c__[c_offset], ldc); } /* W := W * V2 */ strmm_("Right", "Lower", "No transpose", "Unit", m, k, & c_b1011, &v[(*n - *k + 1) * v_dim1 + 1], ldv, &work[ work_offset], ldwork); /* C1 := C1 - W */ i__1 = *k; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { c__[i__ + (*n - *k + j) * c_dim1] -= work[i__ + j * work_dim1]; /* L230: */ } /* L240: */ } } } } return 0; /* End of SLARFB */ } /* slarfb_ */ /* Subroutine */ int slarfg_(integer *n, real *alpha, real *x, integer *incx, real *tau) { /* System generated locals */ integer i__1; real r__1; /* Builtin functions */ double r_sign(real *, real *); /* Local variables */ static integer j, knt; static real beta; extern doublereal snrm2_(integer *, real *, integer *); extern /* Subroutine */ int sscal_(integer *, real *, real *, integer *); static real xnorm; extern doublereal slapy2_(real *, real *), slamch_(char *); static real safmin, rsafmn; /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University September 30, 1994 Purpose ======= SLARFG generates a real elementary reflector H of order n, such that H * ( alpha ) = ( beta ), H' * H = I. ( x ) ( 0 ) where alpha and beta are scalars, and x is an (n-1)-element real vector. H is represented in the form H = I - tau * ( 1 ) * ( 1 v' ) , ( v ) where tau is a real scalar and v is a real (n-1)-element vector. If the elements of x are all zero, then tau = 0 and H is taken to be the unit matrix. Otherwise 1 <= tau <= 2. Arguments ========= N (input) INTEGER The order of the elementary reflector. ALPHA (input/output) REAL On entry, the value alpha. On exit, it is overwritten with the value beta. X (input/output) REAL array, dimension (1+(N-2)*abs(INCX)) On entry, the vector x. On exit, it is overwritten with the vector v. INCX (input) INTEGER The increment between elements of X. INCX > 0. TAU (output) REAL The value tau. ===================================================================== */ /* Parameter adjustments */ --x; /* Function Body */ if (*n <= 1) { *tau = 0.f; return 0; } i__1 = *n - 1; xnorm = snrm2_(&i__1, &x[1], incx); if (xnorm == 0.f) { /* H = I */ *tau = 0.f; } else { /* general case */ r__1 = slapy2_(alpha, &xnorm); beta = -r_sign(&r__1, alpha); safmin = slamch_("S") / slamch_("E"); if (dabs(beta) < safmin) { /* XNORM, BETA may be inaccurate; scale X and recompute them */ rsafmn = 1.f / safmin; knt = 0; L10: ++knt; i__1 = *n - 1; sscal_(&i__1, &rsafmn, &x[1], incx); beta *= rsafmn; *alpha *= rsafmn; if (dabs(beta) < safmin) { goto L10; } /* New BETA is at most 1, at least SAFMIN */ i__1 = *n - 1; xnorm = snrm2_(&i__1, &x[1], incx); r__1 = slapy2_(alpha, &xnorm); beta = -r_sign(&r__1, alpha); *tau = (beta - *alpha) / beta; i__1 = *n - 1; r__1 = 1.f / (*alpha - beta); sscal_(&i__1, &r__1, &x[1], incx); /* If ALPHA is subnormal, it may lose relative accuracy */ *alpha = beta; i__1 = knt; for (j = 1; j <= i__1; ++j) { *alpha *= safmin; /* L20: */ } } else { *tau = (beta - *alpha) / beta; i__1 = *n - 1; r__1 = 1.f / (*alpha - beta); sscal_(&i__1, &r__1, &x[1], incx); *alpha = beta; } } return 0; /* End of SLARFG */ } /* slarfg_ */ /* Subroutine */ int slarft_(char *direct, char *storev, integer *n, integer * k, real *v, integer *ldv, real *tau, real *t, integer *ldt) { /* System generated locals */ integer t_dim1, t_offset, v_dim1, v_offset, i__1, i__2, i__3; real r__1; /* Local variables */ static integer i__, j; static real vii; extern logical lsame_(char *, char *); extern /* Subroutine */ int sgemv_(char *, integer *, integer *, real *, real *, integer *, real *, integer *, real *, real *, integer *), strmv_(char *, char *, char *, integer *, real *, integer *, real *, integer *); /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University February 29, 1992 Purpose ======= SLARFT forms the triangular factor T of a real block reflector H of order n, which is defined as a product of k elementary reflectors. If DIRECT = 'F', H = H(1) H(2) . . . H(k) and T is upper triangular; If DIRECT = 'B', H = H(k) . . . H(2) H(1) and T is lower triangular. If STOREV = 'C', the vector which defines the elementary reflector H(i) is stored in the i-th column of the array V, and H = I - V * T * V' If STOREV = 'R', the vector which defines the elementary reflector H(i) is stored in the i-th row of the array V, and H = I - V' * T * V Arguments ========= DIRECT (input) CHARACTER*1 Specifies the order in which the elementary reflectors are multiplied to form the block reflector: = 'F': H = H(1) H(2) . . . H(k) (Forward) = 'B': H = H(k) . . . H(2) H(1) (Backward) STOREV (input) CHARACTER*1 Specifies how the vectors which define the elementary reflectors are stored (see also Further Details): = 'C': columnwise = 'R': rowwise N (input) INTEGER The order of the block reflector H. N >= 0. K (input) INTEGER The order of the triangular factor T (= the number of elementary reflectors). K >= 1. V (input/output) REAL array, dimension (LDV,K) if STOREV = 'C' (LDV,N) if STOREV = 'R' The matrix V. See further details. LDV (input) INTEGER The leading dimension of the array V. If STOREV = 'C', LDV >= max(1,N); if STOREV = 'R', LDV >= K. TAU (input) REAL array, dimension (K) TAU(i) must contain the scalar factor of the elementary reflector H(i). T (output) REAL array, dimension (LDT,K) The k by k triangular factor T of the block reflector. If DIRECT = 'F', T is upper triangular; if DIRECT = 'B', T is lower triangular. The rest of the array is not used. LDT (input) INTEGER The leading dimension of the array T. LDT >= K. Further Details =============== The shape of the matrix V and the storage of the vectors which define the H(i) is best illustrated by the following example with n = 5 and k = 3. The elements equal to 1 are not stored; the corresponding array elements are modified but restored on exit. The rest of the array is not used. DIRECT = 'F' and STOREV = 'C': DIRECT = 'F' and STOREV = 'R': V = ( 1 ) V = ( 1 v1 v1 v1 v1 ) ( v1 1 ) ( 1 v2 v2 v2 ) ( v1 v2 1 ) ( 1 v3 v3 ) ( v1 v2 v3 ) ( v1 v2 v3 ) DIRECT = 'B' and STOREV = 'C': DIRECT = 'B' and STOREV = 'R': V = ( v1 v2 v3 ) V = ( v1 v1 1 ) ( v1 v2 v3 ) ( v2 v2 v2 1 ) ( 1 v2 v3 ) ( v3 v3 v3 v3 1 ) ( 1 v3 ) ( 1 ) ===================================================================== Quick return if possible */ /* Parameter adjustments */ v_dim1 = *ldv; v_offset = 1 + v_dim1; v -= v_offset; --tau; t_dim1 = *ldt; t_offset = 1 + t_dim1; t -= t_offset; /* Function Body */ if (*n == 0) { return 0; } if (lsame_(direct, "F")) { i__1 = *k; for (i__ = 1; i__ <= i__1; ++i__) { if (tau[i__] == 0.f) { /* H(i) = I */ i__2 = i__; for (j = 1; j <= i__2; ++j) { t[j + i__ * t_dim1] = 0.f; /* L10: */ } } else { /* general case */ vii = v[i__ + i__ * v_dim1]; v[i__ + i__ * v_dim1] = 1.f; if (lsame_(storev, "C")) { /* T(1:i-1,i) := - tau(i) * V(i:n,1:i-1)' * V(i:n,i) */ i__2 = *n - i__ + 1; i__3 = i__ - 1; r__1 = -tau[i__]; sgemv_("Transpose", &i__2, &i__3, &r__1, &v[i__ + v_dim1], ldv, &v[i__ + i__ * v_dim1], &c__1, &c_b320, &t[ i__ * t_dim1 + 1], &c__1); } else { /* T(1:i-1,i) := - tau(i) * V(1:i-1,i:n) * V(i,i:n)' */ i__2 = i__ - 1; i__3 = *n - i__ + 1; r__1 = -tau[i__]; sgemv_("No transpose", &i__2, &i__3, &r__1, &v[i__ * v_dim1 + 1], ldv, &v[i__ + i__ * v_dim1], ldv, & c_b320, &t[i__ * t_dim1 + 1], &c__1); } v[i__ + i__ * v_dim1] = vii; /* T(1:i-1,i) := T(1:i-1,1:i-1) * T(1:i-1,i) */ i__2 = i__ - 1; strmv_("Upper", "No transpose", "Non-unit", &i__2, &t[ t_offset], ldt, &t[i__ * t_dim1 + 1], &c__1); t[i__ + i__ * t_dim1] = tau[i__]; } /* L20: */ } } else { for (i__ = *k; i__ >= 1; --i__) { if (tau[i__] == 0.f) { /* H(i) = I */ i__1 = *k; for (j = i__; j <= i__1; ++j) { t[j + i__ * t_dim1] = 0.f; /* L30: */ } } else { /* general case */ if (i__ < *k) { if (lsame_(storev, "C")) { vii = v[*n - *k + i__ + i__ * v_dim1]; v[*n - *k + i__ + i__ * v_dim1] = 1.f; /* T(i+1:k,i) := - tau(i) * V(1:n-k+i,i+1:k)' * V(1:n-k+i,i) */ i__1 = *n - *k + i__; i__2 = *k - i__; r__1 = -tau[i__]; sgemv_("Transpose", &i__1, &i__2, &r__1, &v[(i__ + 1) * v_dim1 + 1], ldv, &v[i__ * v_dim1 + 1], & c__1, &c_b320, &t[i__ + 1 + i__ * t_dim1], & c__1); v[*n - *k + i__ + i__ * v_dim1] = vii; } else { vii = v[i__ + (*n - *k + i__) * v_dim1]; v[i__ + (*n - *k + i__) * v_dim1] = 1.f; /* T(i+1:k,i) := - tau(i) * V(i+1:k,1:n-k+i) * V(i,1:n-k+i)' */ i__1 = *k - i__; i__2 = *n - *k + i__; r__1 = -tau[i__]; sgemv_("No transpose", &i__1, &i__2, &r__1, &v[i__ + 1 + v_dim1], ldv, &v[i__ + v_dim1], ldv, & c_b320, &t[i__ + 1 + i__ * t_dim1], &c__1); v[i__ + (*n - *k + i__) * v_dim1] = vii; } /* T(i+1:k,i) := T(i+1:k,i+1:k) * T(i+1:k,i) */ i__1 = *k - i__; strmv_("Lower", "No transpose", "Non-unit", &i__1, &t[i__ + 1 + (i__ + 1) * t_dim1], ldt, &t[i__ + 1 + i__ * t_dim1], &c__1) ; } t[i__ + i__ * t_dim1] = tau[i__]; } /* L40: */ } } return 0; /* End of SLARFT */ } /* slarft_ */ /* Subroutine */ int slarfx_(char *side, integer *m, integer *n, real *v, real *tau, real *c__, integer *ldc, real *work) { /* System generated locals */ integer c_dim1, c_offset, i__1; real r__1; /* Local variables */ static integer j; static real t1, t2, t3, t4, t5, t6, t7, t8, t9, v1, v2, v3, v4, v5, v6, v7, v8, v9, t10, v10, sum; extern /* Subroutine */ int sger_(integer *, integer *, real *, real *, integer *, real *, integer *, real *, integer *); extern logical lsame_(char *, char *); extern /* Subroutine */ int sgemv_(char *, integer *, integer *, real *, real *, integer *, real *, integer *, real *, real *, integer *); /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University February 29, 1992 Purpose ======= SLARFX applies a real elementary reflector H to a real m by n matrix C, from either the left or the right. H is represented in the form H = I - tau * v * v' where tau is a real scalar and v is a real vector. If tau = 0, then H is taken to be the unit matrix This version uses inline code if H has order < 11. Arguments ========= SIDE (input) CHARACTER*1 = 'L': form H * C = 'R': form C * H M (input) INTEGER The number of rows of the matrix C. N (input) INTEGER The number of columns of the matrix C. V (input) REAL array, dimension (M) if SIDE = 'L' or (N) if SIDE = 'R' The vector v in the representation of H. TAU (input) REAL The value tau in the representation of H. C (input/output) REAL array, dimension (LDC,N) On entry, the m by n matrix C. On exit, C is overwritten by the matrix H * C if SIDE = 'L', or C * H if SIDE = 'R'. LDC (input) INTEGER The leading dimension of the array C. LDA >= (1,M). WORK (workspace) REAL array, dimension (N) if SIDE = 'L' or (M) if SIDE = 'R' WORK is not referenced if H has order < 11. ===================================================================== */ /* Parameter adjustments */ --v; c_dim1 = *ldc; c_offset = 1 + c_dim1; c__ -= c_offset; --work; /* Function Body */ if (*tau == 0.f) { return 0; } if (lsame_(side, "L")) { /* Form H * C, where H has order m. */ switch (*m) { case 1: goto L10; case 2: goto L30; case 3: goto L50; case 4: goto L70; case 5: goto L90; case 6: goto L110; case 7: goto L130; case 8: goto L150; case 9: goto L170; case 10: goto L190; } /* Code for general M w := C'*v */ sgemv_("Transpose", m, n, &c_b1011, &c__[c_offset], ldc, &v[1], &c__1, &c_b320, &work[1], &c__1); /* C := C - tau * v * w' */ r__1 = -(*tau); sger_(m, n, &r__1, &v[1], &c__1, &work[1], &c__1, &c__[c_offset], ldc) ; goto L410; L10: /* Special code for 1 x 1 Householder */ t1 = 1.f - *tau * v[1] * v[1]; i__1 = *n; for (j = 1; j <= i__1; ++j) { c__[j * c_dim1 + 1] = t1 * c__[j * c_dim1 + 1]; /* L20: */ } goto L410; L30: /* Special code for 2 x 2 Householder */ v1 = v[1]; t1 = *tau * v1; v2 = v[2]; t2 = *tau * v2; i__1 = *n; for (j = 1; j <= i__1; ++j) { sum = v1 * c__[j * c_dim1 + 1] + v2 * c__[j * c_dim1 + 2]; c__[j * c_dim1 + 1] -= sum * t1; c__[j * c_dim1 + 2] -= sum * t2; /* L40: */ } goto L410; L50: /* Special code for 3 x 3 Householder */ v1 = v[1]; t1 = *tau * v1; v2 = v[2]; t2 = *tau * v2; v3 = v[3]; t3 = *tau * v3; i__1 = *n; for (j = 1; j <= i__1; ++j) { sum = v1 * c__[j * c_dim1 + 1] + v2 * c__[j * c_dim1 + 2] + v3 * c__[j * c_dim1 + 3]; c__[j * c_dim1 + 1] -= sum * t1; c__[j * c_dim1 + 2] -= sum * t2; c__[j * c_dim1 + 3] -= sum * t3; /* L60: */ } goto L410; L70: /* Special code for 4 x 4 Householder */ v1 = v[1]; t1 = *tau * v1; v2 = v[2]; t2 = *tau * v2; v3 = v[3]; t3 = *tau * v3; v4 = v[4]; t4 = *tau * v4; i__1 = *n; for (j = 1; j <= i__1; ++j) { sum = v1 * c__[j * c_dim1 + 1] + v2 * c__[j * c_dim1 + 2] + v3 * c__[j * c_dim1 + 3] + v4 * c__[j * c_dim1 + 4]; c__[j * c_dim1 + 1] -= sum * t1; c__[j * c_dim1 + 2] -= sum * t2; c__[j * c_dim1 + 3] -= sum * t3; c__[j * c_dim1 + 4] -= sum * t4; /* L80: */ } goto L410; L90: /* Special code for 5 x 5 Householder */ v1 = v[1]; t1 = *tau * v1; v2 = v[2]; t2 = *tau * v2; v3 = v[3]; t3 = *tau * v3; v4 = v[4]; t4 = *tau * v4; v5 = v[5]; t5 = *tau * v5; i__1 = *n; for (j = 1; j <= i__1; ++j) { sum = v1 * c__[j * c_dim1 + 1] + v2 * c__[j * c_dim1 + 2] + v3 * c__[j * c_dim1 + 3] + v4 * c__[j * c_dim1 + 4] + v5 * c__[ j * c_dim1 + 5]; c__[j * c_dim1 + 1] -= sum * t1; c__[j * c_dim1 + 2] -= sum * t2; c__[j * c_dim1 + 3] -= sum * t3; c__[j * c_dim1 + 4] -= sum * t4; c__[j * c_dim1 + 5] -= sum * t5; /* L100: */ } goto L410; L110: /* Special code for 6 x 6 Householder */ v1 = v[1]; t1 = *tau * v1; v2 = v[2]; t2 = *tau * v2; v3 = v[3]; t3 = *tau * v3; v4 = v[4]; t4 = *tau * v4; v5 = v[5]; t5 = *tau * v5; v6 = v[6]; t6 = *tau * v6; i__1 = *n; for (j = 1; j <= i__1; ++j) { sum = v1 * c__[j * c_dim1 + 1] + v2 * c__[j * c_dim1 + 2] + v3 * c__[j * c_dim1 + 3] + v4 * c__[j * c_dim1 + 4] + v5 * c__[ j * c_dim1 + 5] + v6 * c__[j * c_dim1 + 6]; c__[j * c_dim1 + 1] -= sum * t1; c__[j * c_dim1 + 2] -= sum * t2; c__[j * c_dim1 + 3] -= sum * t3; c__[j * c_dim1 + 4] -= sum * t4; c__[j * c_dim1 + 5] -= sum * t5; c__[j * c_dim1 + 6] -= sum * t6; /* L120: */ } goto L410; L130: /* Special code for 7 x 7 Householder */ v1 = v[1]; t1 = *tau * v1; v2 = v[2]; t2 = *tau * v2; v3 = v[3]; t3 = *tau * v3; v4 = v[4]; t4 = *tau * v4; v5 = v[5]; t5 = *tau * v5; v6 = v[6]; t6 = *tau * v6; v7 = v[7]; t7 = *tau * v7; i__1 = *n; for (j = 1; j <= i__1; ++j) { sum = v1 * c__[j * c_dim1 + 1] + v2 * c__[j * c_dim1 + 2] + v3 * c__[j * c_dim1 + 3] + v4 * c__[j * c_dim1 + 4] + v5 * c__[ j * c_dim1 + 5] + v6 * c__[j * c_dim1 + 6] + v7 * c__[j * c_dim1 + 7]; c__[j * c_dim1 + 1] -= sum * t1; c__[j * c_dim1 + 2] -= sum * t2; c__[j * c_dim1 + 3] -= sum * t3; c__[j * c_dim1 + 4] -= sum * t4; c__[j * c_dim1 + 5] -= sum * t5; c__[j * c_dim1 + 6] -= sum * t6; c__[j * c_dim1 + 7] -= sum * t7; /* L140: */ } goto L410; L150: /* Special code for 8 x 8 Householder */ v1 = v[1]; t1 = *tau * v1; v2 = v[2]; t2 = *tau * v2; v3 = v[3]; t3 = *tau * v3; v4 = v[4]; t4 = *tau * v4; v5 = v[5]; t5 = *tau * v5; v6 = v[6]; t6 = *tau * v6; v7 = v[7]; t7 = *tau * v7; v8 = v[8]; t8 = *tau * v8; i__1 = *n; for (j = 1; j <= i__1; ++j) { sum = v1 * c__[j * c_dim1 + 1] + v2 * c__[j * c_dim1 + 2] + v3 * c__[j * c_dim1 + 3] + v4 * c__[j * c_dim1 + 4] + v5 * c__[ j * c_dim1 + 5] + v6 * c__[j * c_dim1 + 6] + v7 * c__[j * c_dim1 + 7] + v8 * c__[j * c_dim1 + 8]; c__[j * c_dim1 + 1] -= sum * t1; c__[j * c_dim1 + 2] -= sum * t2; c__[j * c_dim1 + 3] -= sum * t3; c__[j * c_dim1 + 4] -= sum * t4; c__[j * c_dim1 + 5] -= sum * t5; c__[j * c_dim1 + 6] -= sum * t6; c__[j * c_dim1 + 7] -= sum * t7; c__[j * c_dim1 + 8] -= sum * t8; /* L160: */ } goto L410; L170: /* Special code for 9 x 9 Householder */ v1 = v[1]; t1 = *tau * v1; v2 = v[2]; t2 = *tau * v2; v3 = v[3]; t3 = *tau * v3; v4 = v[4]; t4 = *tau * v4; v5 = v[5]; t5 = *tau * v5; v6 = v[6]; t6 = *tau * v6; v7 = v[7]; t7 = *tau * v7; v8 = v[8]; t8 = *tau * v8; v9 = v[9]; t9 = *tau * v9; i__1 = *n; for (j = 1; j <= i__1; ++j) { sum = v1 * c__[j * c_dim1 + 1] + v2 * c__[j * c_dim1 + 2] + v3 * c__[j * c_dim1 + 3] + v4 * c__[j * c_dim1 + 4] + v5 * c__[ j * c_dim1 + 5] + v6 * c__[j * c_dim1 + 6] + v7 * c__[j * c_dim1 + 7] + v8 * c__[j * c_dim1 + 8] + v9 * c__[j * c_dim1 + 9]; c__[j * c_dim1 + 1] -= sum * t1; c__[j * c_dim1 + 2] -= sum * t2; c__[j * c_dim1 + 3] -= sum * t3; c__[j * c_dim1 + 4] -= sum * t4; c__[j * c_dim1 + 5] -= sum * t5; c__[j * c_dim1 + 6] -= sum * t6; c__[j * c_dim1 + 7] -= sum * t7; c__[j * c_dim1 + 8] -= sum * t8; c__[j * c_dim1 + 9] -= sum * t9; /* L180: */ } goto L410; L190: /* Special code for 10 x 10 Householder */ v1 = v[1]; t1 = *tau * v1; v2 = v[2]; t2 = *tau * v2; v3 = v[3]; t3 = *tau * v3; v4 = v[4]; t4 = *tau * v4; v5 = v[5]; t5 = *tau * v5; v6 = v[6]; t6 = *tau * v6; v7 = v[7]; t7 = *tau * v7; v8 = v[8]; t8 = *tau * v8; v9 = v[9]; t9 = *tau * v9; v10 = v[10]; t10 = *tau * v10; i__1 = *n; for (j = 1; j <= i__1; ++j) { sum = v1 * c__[j * c_dim1 + 1] + v2 * c__[j * c_dim1 + 2] + v3 * c__[j * c_dim1 + 3] + v4 * c__[j * c_dim1 + 4] + v5 * c__[ j * c_dim1 + 5] + v6 * c__[j * c_dim1 + 6] + v7 * c__[j * c_dim1 + 7] + v8 * c__[j * c_dim1 + 8] + v9 * c__[j * c_dim1 + 9] + v10 * c__[j * c_dim1 + 10]; c__[j * c_dim1 + 1] -= sum * t1; c__[j * c_dim1 + 2] -= sum * t2; c__[j * c_dim1 + 3] -= sum * t3; c__[j * c_dim1 + 4] -= sum * t4; c__[j * c_dim1 + 5] -= sum * t5; c__[j * c_dim1 + 6] -= sum * t6; c__[j * c_dim1 + 7] -= sum * t7; c__[j * c_dim1 + 8] -= sum * t8; c__[j * c_dim1 + 9] -= sum * t9; c__[j * c_dim1 + 10] -= sum * t10; /* L200: */ } goto L410; } else { /* Form C * H, where H has order n. */ switch (*n) { case 1: goto L210; case 2: goto L230; case 3: goto L250; case 4: goto L270; case 5: goto L290; case 6: goto L310; case 7: goto L330; case 8: goto L350; case 9: goto L370; case 10: goto L390; } /* Code for general N w := C * v */ sgemv_("No transpose", m, n, &c_b1011, &c__[c_offset], ldc, &v[1], & c__1, &c_b320, &work[1], &c__1); /* C := C - tau * w * v' */ r__1 = -(*tau); sger_(m, n, &r__1, &work[1], &c__1, &v[1], &c__1, &c__[c_offset], ldc) ; goto L410; L210: /* Special code for 1 x 1 Householder */ t1 = 1.f - *tau * v[1] * v[1]; i__1 = *m; for (j = 1; j <= i__1; ++j) { c__[j + c_dim1] = t1 * c__[j + c_dim1]; /* L220: */ } goto L410; L230: /* Special code for 2 x 2 Householder */ v1 = v[1]; t1 = *tau * v1; v2 = v[2]; t2 = *tau * v2; i__1 = *m; for (j = 1; j <= i__1; ++j) { sum = v1 * c__[j + c_dim1] + v2 * c__[j + ((c_dim1) << (1))]; c__[j + c_dim1] -= sum * t1; c__[j + ((c_dim1) << (1))] -= sum * t2; /* L240: */ } goto L410; L250: /* Special code for 3 x 3 Householder */ v1 = v[1]; t1 = *tau * v1; v2 = v[2]; t2 = *tau * v2; v3 = v[3]; t3 = *tau * v3; i__1 = *m; for (j = 1; j <= i__1; ++j) { sum = v1 * c__[j + c_dim1] + v2 * c__[j + ((c_dim1) << (1))] + v3 * c__[j + c_dim1 * 3]; c__[j + c_dim1] -= sum * t1; c__[j + ((c_dim1) << (1))] -= sum * t2; c__[j + c_dim1 * 3] -= sum * t3; /* L260: */ } goto L410; L270: /* Special code for 4 x 4 Householder */ v1 = v[1]; t1 = *tau * v1; v2 = v[2]; t2 = *tau * v2; v3 = v[3]; t3 = *tau * v3; v4 = v[4]; t4 = *tau * v4; i__1 = *m; for (j = 1; j <= i__1; ++j) { sum = v1 * c__[j + c_dim1] + v2 * c__[j + ((c_dim1) << (1))] + v3 * c__[j + c_dim1 * 3] + v4 * c__[j + ((c_dim1) << (2))]; c__[j + c_dim1] -= sum * t1; c__[j + ((c_dim1) << (1))] -= sum * t2; c__[j + c_dim1 * 3] -= sum * t3; c__[j + ((c_dim1) << (2))] -= sum * t4; /* L280: */ } goto L410; L290: /* Special code for 5 x 5 Householder */ v1 = v[1]; t1 = *tau * v1; v2 = v[2]; t2 = *tau * v2; v3 = v[3]; t3 = *tau * v3; v4 = v[4]; t4 = *tau * v4; v5 = v[5]; t5 = *tau * v5; i__1 = *m; for (j = 1; j <= i__1; ++j) { sum = v1 * c__[j + c_dim1] + v2 * c__[j + ((c_dim1) << (1))] + v3 * c__[j + c_dim1 * 3] + v4 * c__[j + ((c_dim1) << (2))] + v5 * c__[j + c_dim1 * 5]; c__[j + c_dim1] -= sum * t1; c__[j + ((c_dim1) << (1))] -= sum * t2; c__[j + c_dim1 * 3] -= sum * t3; c__[j + ((c_dim1) << (2))] -= sum * t4; c__[j + c_dim1 * 5] -= sum * t5; /* L300: */ } goto L410; L310: /* Special code for 6 x 6 Householder */ v1 = v[1]; t1 = *tau * v1; v2 = v[2]; t2 = *tau * v2; v3 = v[3]; t3 = *tau * v3; v4 = v[4]; t4 = *tau * v4; v5 = v[5]; t5 = *tau * v5; v6 = v[6]; t6 = *tau * v6; i__1 = *m; for (j = 1; j <= i__1; ++j) { sum = v1 * c__[j + c_dim1] + v2 * c__[j + ((c_dim1) << (1))] + v3 * c__[j + c_dim1 * 3] + v4 * c__[j + ((c_dim1) << (2))] + v5 * c__[j + c_dim1 * 5] + v6 * c__[j + c_dim1 * 6]; c__[j + c_dim1] -= sum * t1; c__[j + ((c_dim1) << (1))] -= sum * t2; c__[j + c_dim1 * 3] -= sum * t3; c__[j + ((c_dim1) << (2))] -= sum * t4; c__[j + c_dim1 * 5] -= sum * t5; c__[j + c_dim1 * 6] -= sum * t6; /* L320: */ } goto L410; L330: /* Special code for 7 x 7 Householder */ v1 = v[1]; t1 = *tau * v1; v2 = v[2]; t2 = *tau * v2; v3 = v[3]; t3 = *tau * v3; v4 = v[4]; t4 = *tau * v4; v5 = v[5]; t5 = *tau * v5; v6 = v[6]; t6 = *tau * v6; v7 = v[7]; t7 = *tau * v7; i__1 = *m; for (j = 1; j <= i__1; ++j) { sum = v1 * c__[j + c_dim1] + v2 * c__[j + ((c_dim1) << (1))] + v3 * c__[j + c_dim1 * 3] + v4 * c__[j + ((c_dim1) << (2))] + v5 * c__[j + c_dim1 * 5] + v6 * c__[j + c_dim1 * 6] + v7 * c__[j + c_dim1 * 7]; c__[j + c_dim1] -= sum * t1; c__[j + ((c_dim1) << (1))] -= sum * t2; c__[j + c_dim1 * 3] -= sum * t3; c__[j + ((c_dim1) << (2))] -= sum * t4; c__[j + c_dim1 * 5] -= sum * t5; c__[j + c_dim1 * 6] -= sum * t6; c__[j + c_dim1 * 7] -= sum * t7; /* L340: */ } goto L410; L350: /* Special code for 8 x 8 Householder */ v1 = v[1]; t1 = *tau * v1; v2 = v[2]; t2 = *tau * v2; v3 = v[3]; t3 = *tau * v3; v4 = v[4]; t4 = *tau * v4; v5 = v[5]; t5 = *tau * v5; v6 = v[6]; t6 = *tau * v6; v7 = v[7]; t7 = *tau * v7; v8 = v[8]; t8 = *tau * v8; i__1 = *m; for (j = 1; j <= i__1; ++j) { sum = v1 * c__[j + c_dim1] + v2 * c__[j + ((c_dim1) << (1))] + v3 * c__[j + c_dim1 * 3] + v4 * c__[j + ((c_dim1) << (2))] + v5 * c__[j + c_dim1 * 5] + v6 * c__[j + c_dim1 * 6] + v7 * c__[j + c_dim1 * 7] + v8 * c__[j + ((c_dim1) << (3))]; c__[j + c_dim1] -= sum * t1; c__[j + ((c_dim1) << (1))] -= sum * t2; c__[j + c_dim1 * 3] -= sum * t3; c__[j + ((c_dim1) << (2))] -= sum * t4; c__[j + c_dim1 * 5] -= sum * t5; c__[j + c_dim1 * 6] -= sum * t6; c__[j + c_dim1 * 7] -= sum * t7; c__[j + ((c_dim1) << (3))] -= sum * t8; /* L360: */ } goto L410; L370: /* Special code for 9 x 9 Householder */ v1 = v[1]; t1 = *tau * v1; v2 = v[2]; t2 = *tau * v2; v3 = v[3]; t3 = *tau * v3; v4 = v[4]; t4 = *tau * v4; v5 = v[5]; t5 = *tau * v5; v6 = v[6]; t6 = *tau * v6; v7 = v[7]; t7 = *tau * v7; v8 = v[8]; t8 = *tau * v8; v9 = v[9]; t9 = *tau * v9; i__1 = *m; for (j = 1; j <= i__1; ++j) { sum = v1 * c__[j + c_dim1] + v2 * c__[j + ((c_dim1) << (1))] + v3 * c__[j + c_dim1 * 3] + v4 * c__[j + ((c_dim1) << (2))] + v5 * c__[j + c_dim1 * 5] + v6 * c__[j + c_dim1 * 6] + v7 * c__[j + c_dim1 * 7] + v8 * c__[j + ((c_dim1) << (3))] + v9 * c__[j + c_dim1 * 9]; c__[j + c_dim1] -= sum * t1; c__[j + ((c_dim1) << (1))] -= sum * t2; c__[j + c_dim1 * 3] -= sum * t3; c__[j + ((c_dim1) << (2))] -= sum * t4; c__[j + c_dim1 * 5] -= sum * t5; c__[j + c_dim1 * 6] -= sum * t6; c__[j + c_dim1 * 7] -= sum * t7; c__[j + ((c_dim1) << (3))] -= sum * t8; c__[j + c_dim1 * 9] -= sum * t9; /* L380: */ } goto L410; L390: /* Special code for 10 x 10 Householder */ v1 = v[1]; t1 = *tau * v1; v2 = v[2]; t2 = *tau * v2; v3 = v[3]; t3 = *tau * v3; v4 = v[4]; t4 = *tau * v4; v5 = v[5]; t5 = *tau * v5; v6 = v[6]; t6 = *tau * v6; v7 = v[7]; t7 = *tau * v7; v8 = v[8]; t8 = *tau * v8; v9 = v[9]; t9 = *tau * v9; v10 = v[10]; t10 = *tau * v10; i__1 = *m; for (j = 1; j <= i__1; ++j) { sum = v1 * c__[j + c_dim1] + v2 * c__[j + ((c_dim1) << (1))] + v3 * c__[j + c_dim1 * 3] + v4 * c__[j + ((c_dim1) << (2))] + v5 * c__[j + c_dim1 * 5] + v6 * c__[j + c_dim1 * 6] + v7 * c__[j + c_dim1 * 7] + v8 * c__[j + ((c_dim1) << (3))] + v9 * c__[j + c_dim1 * 9] + v10 * c__[j + c_dim1 * 10]; c__[j + c_dim1] -= sum * t1; c__[j + ((c_dim1) << (1))] -= sum * t2; c__[j + c_dim1 * 3] -= sum * t3; c__[j + ((c_dim1) << (2))] -= sum * t4; c__[j + c_dim1 * 5] -= sum * t5; c__[j + c_dim1 * 6] -= sum * t6; c__[j + c_dim1 * 7] -= sum * t7; c__[j + ((c_dim1) << (3))] -= sum * t8; c__[j + c_dim1 * 9] -= sum * t9; c__[j + c_dim1 * 10] -= sum * t10; /* L400: */ } goto L410; } L410: return 0; /* End of SLARFX */ } /* slarfx_ */ /* Subroutine */ int slartg_(real *f, real *g, real *cs, real *sn, real *r__) { /* Initialized data */ static logical first = TRUE_; /* System generated locals */ integer i__1; real r__1, r__2; /* Builtin functions */ double log(doublereal), pow_ri(real *, integer *), sqrt(doublereal); /* Local variables */ static integer i__; static real f1, g1, eps, scale; static integer count; static real safmn2, safmx2; extern doublereal slamch_(char *); static real safmin; /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University September 30, 1994 Purpose ======= SLARTG generate a plane rotation so that [ CS SN ] . [ F ] = [ R ] where CS**2 + SN**2 = 1. [ -SN CS ] [ G ] [ 0 ] This is a slower, more accurate version of the BLAS1 routine SROTG, with the following other differences: F and G are unchanged on return. If G=0, then CS=1 and SN=0. If F=0 and (G .ne. 0), then CS=0 and SN=1 without doing any floating point operations (saves work in SBDSQR when there are zeros on the diagonal). If F exceeds G in magnitude, CS will be positive. Arguments ========= F (input) REAL The first component of vector to be rotated. G (input) REAL The second component of vector to be rotated. CS (output) REAL The cosine of the rotation. SN (output) REAL The sine of the rotation. R (output) REAL The nonzero component of the rotated vector. ===================================================================== */ if (first) { first = FALSE_; safmin = slamch_("S"); eps = slamch_("E"); r__1 = slamch_("B"); i__1 = (integer) (log(safmin / eps) / log(slamch_("B")) / 2.f); safmn2 = pow_ri(&r__1, &i__1); safmx2 = 1.f / safmn2; } if (*g == 0.f) { *cs = 1.f; *sn = 0.f; *r__ = *f; } else if (*f == 0.f) { *cs = 0.f; *sn = 1.f; *r__ = *g; } else { f1 = *f; g1 = *g; /* Computing MAX */ r__1 = dabs(f1), r__2 = dabs(g1); scale = dmax(r__1,r__2); if (scale >= safmx2) { count = 0; L10: ++count; f1 *= safmn2; g1 *= safmn2; /* Computing MAX */ r__1 = dabs(f1), r__2 = dabs(g1); scale = dmax(r__1,r__2); if (scale >= safmx2) { goto L10; } /* Computing 2nd power */ r__1 = f1; /* Computing 2nd power */ r__2 = g1; *r__ = sqrt(r__1 * r__1 + r__2 * r__2); *cs = f1 / *r__; *sn = g1 / *r__; i__1 = count; for (i__ = 1; i__ <= i__1; ++i__) { *r__ *= safmx2; /* L20: */ } } else if (scale <= safmn2) { count = 0; L30: ++count; f1 *= safmx2; g1 *= safmx2; /* Computing MAX */ r__1 = dabs(f1), r__2 = dabs(g1); scale = dmax(r__1,r__2); if (scale <= safmn2) { goto L30; } /* Computing 2nd power */ r__1 = f1; /* Computing 2nd power */ r__2 = g1; *r__ = sqrt(r__1 * r__1 + r__2 * r__2); *cs = f1 / *r__; *sn = g1 / *r__; i__1 = count; for (i__ = 1; i__ <= i__1; ++i__) { *r__ *= safmn2; /* L40: */ } } else { /* Computing 2nd power */ r__1 = f1; /* Computing 2nd power */ r__2 = g1; *r__ = sqrt(r__1 * r__1 + r__2 * r__2); *cs = f1 / *r__; *sn = g1 / *r__; } if (dabs(*f) > dabs(*g) && *cs < 0.f) { *cs = -(*cs); *sn = -(*sn); *r__ = -(*r__); } } return 0; /* End of SLARTG */ } /* slartg_ */ /* Subroutine */ int slas2_(real *f, real *g, real *h__, real *ssmin, real * ssmax) { /* System generated locals */ real r__1, r__2; /* Builtin functions */ double sqrt(doublereal); /* Local variables */ static real c__, fa, ga, ha, as, at, au, fhmn, fhmx; /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University September 30, 1994 Purpose ======= SLAS2 computes the singular values of the 2-by-2 matrix [ F G ] [ 0 H ]. On return, SSMIN is the smaller singular value and SSMAX is the larger singular value. Arguments ========= F (input) REAL The (1,1) element of the 2-by-2 matrix. G (input) REAL The (1,2) element of the 2-by-2 matrix. H (input) REAL The (2,2) element of the 2-by-2 matrix. SSMIN (output) REAL The smaller singular value. SSMAX (output) REAL The larger singular value. Further Details =============== Barring over/underflow, all output quantities are correct to within a few units in the last place (ulps), even in the absence of a guard digit in addition/subtraction. In IEEE arithmetic, the code works correctly if one matrix element is infinite. Overflow will not occur unless the largest singular value itself overflows, or is within a few ulps of overflow. (On machines with partial overflow, like the Cray, overflow may occur if the largest singular value is within a factor of 2 of overflow.) Underflow is harmless if underflow is gradual. Otherwise, results may correspond to a matrix modified by perturbations of size near the underflow threshold. ==================================================================== */ fa = dabs(*f); ga = dabs(*g); ha = dabs(*h__); fhmn = dmin(fa,ha); fhmx = dmax(fa,ha); if (fhmn == 0.f) { *ssmin = 0.f; if (fhmx == 0.f) { *ssmax = ga; } else { /* Computing 2nd power */ r__1 = dmin(fhmx,ga) / dmax(fhmx,ga); *ssmax = dmax(fhmx,ga) * sqrt(r__1 * r__1 + 1.f); } } else { if (ga < fhmx) { as = fhmn / fhmx + 1.f; at = (fhmx - fhmn) / fhmx; /* Computing 2nd power */ r__1 = ga / fhmx; au = r__1 * r__1; c__ = 2.f / (sqrt(as * as + au) + sqrt(at * at + au)); *ssmin = fhmn * c__; *ssmax = fhmx / c__; } else { au = fhmx / ga; if (au == 0.f) { /* Avoid possible harmful underflow if exponent range asymmetric (true SSMIN may not underflow even if AU underflows) */ *ssmin = fhmn * fhmx / ga; *ssmax = ga; } else { as = fhmn / fhmx + 1.f; at = (fhmx - fhmn) / fhmx; /* Computing 2nd power */ r__1 = as * au; /* Computing 2nd power */ r__2 = at * au; c__ = 1.f / (sqrt(r__1 * r__1 + 1.f) + sqrt(r__2 * r__2 + 1.f) ); *ssmin = fhmn * c__ * au; *ssmin += *ssmin; *ssmax = ga / (c__ + c__); } } } return 0; /* End of SLAS2 */ } /* slas2_ */ /* Subroutine */ int slascl_(char *type__, integer *kl, integer *ku, real * cfrom, real *cto, integer *m, integer *n, real *a, integer *lda, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3, i__4, i__5; /* Local variables */ static integer i__, j, k1, k2, k3, k4; static real mul, cto1; static logical done; static real ctoc; extern logical lsame_(char *, char *); static integer itype; static real cfrom1; extern doublereal slamch_(char *); static real cfromc; extern /* Subroutine */ int xerbla_(char *, integer *); static real bignum, smlnum; /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University February 29, 1992 Purpose ======= SLASCL multiplies the M by N real matrix A by the real scalar CTO/CFROM. This is done without over/underflow as long as the final result CTO*A(I,J)/CFROM does not over/underflow. TYPE specifies that A may be full, upper triangular, lower triangular, upper Hessenberg, or banded. Arguments ========= TYPE (input) CHARACTER*1 TYPE indices the storage type of the input matrix. = 'G': A is a full matrix. = 'L': A is a lower triangular matrix. = 'U': A is an upper triangular matrix. = 'H': A is an upper Hessenberg matrix. = 'B': A is a symmetric band matrix with lower bandwidth KL and upper bandwidth KU and with the only the lower half stored. = 'Q': A is a symmetric band matrix with lower bandwidth KL and upper bandwidth KU and with the only the upper half stored. = 'Z': A is a band matrix with lower bandwidth KL and upper bandwidth KU. KL (input) INTEGER The lower bandwidth of A. Referenced only if TYPE = 'B', 'Q' or 'Z'. KU (input) INTEGER The upper bandwidth of A. Referenced only if TYPE = 'B', 'Q' or 'Z'. CFROM (input) REAL CTO (input) REAL The matrix A is multiplied by CTO/CFROM. A(I,J) is computed without over/underflow if the final result CTO*A(I,J)/CFROM can be represented without over/underflow. CFROM must be nonzero. M (input) INTEGER The number of rows of the matrix A. M >= 0. N (input) INTEGER The number of columns of the matrix A. N >= 0. A (input/output) REAL array, dimension (LDA,M) The matrix to be multiplied by CTO/CFROM. See TYPE for the storage type. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,M). INFO (output) INTEGER 0 - successful exit <0 - if INFO = -i, the i-th argument had an illegal value. ===================================================================== Test the input arguments */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; /* Function Body */ *info = 0; if (lsame_(type__, "G")) { itype = 0; } else if (lsame_(type__, "L")) { itype = 1; } else if (lsame_(type__, "U")) { itype = 2; } else if (lsame_(type__, "H")) { itype = 3; } else if (lsame_(type__, "B")) { itype = 4; } else if (lsame_(type__, "Q")) { itype = 5; } else if (lsame_(type__, "Z")) { itype = 6; } else { itype = -1; } if (itype == -1) { *info = -1; } else if (*cfrom == 0.f) { *info = -4; } else if (*m < 0) { *info = -6; } else if (((*n < 0) || (itype == 4 && *n != *m)) || (itype == 5 && *n != *m)) { *info = -7; } else if (itype <= 3 && *lda < max(1,*m)) { *info = -9; } else if (itype >= 4) { /* Computing MAX */ i__1 = *m - 1; if ((*kl < 0) || (*kl > max(i__1,0))) { *info = -2; } else /* if(complicated condition) */ { /* Computing MAX */ i__1 = *n - 1; if (((*ku < 0) || (*ku > max(i__1,0))) || (((itype == 4) || ( itype == 5)) && *kl != *ku)) { *info = -3; } else if (((itype == 4 && *lda < *kl + 1) || (itype == 5 && *lda < *ku + 1)) || (itype == 6 && *lda < ((*kl) << (1)) + *ku + 1)) { *info = -9; } } } if (*info != 0) { i__1 = -(*info); xerbla_("SLASCL", &i__1); return 0; } /* Quick return if possible */ if ((*n == 0) || (*m == 0)) { return 0; } /* Get machine parameters */ smlnum = slamch_("S"); bignum = 1.f / smlnum; cfromc = *cfrom; ctoc = *cto; L10: cfrom1 = cfromc * smlnum; cto1 = ctoc / bignum; if (dabs(cfrom1) > dabs(ctoc) && ctoc != 0.f) { mul = smlnum; done = FALSE_; cfromc = cfrom1; } else if (dabs(cto1) > dabs(cfromc)) { mul = bignum; done = FALSE_; ctoc = cto1; } else { mul = ctoc / cfromc; done = TRUE_; } if (itype == 0) { /* Full matrix */ i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { a[i__ + j * a_dim1] *= mul; /* L20: */ } /* L30: */ } } else if (itype == 1) { /* Lower triangular matrix */ i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = j; i__ <= i__2; ++i__) { a[i__ + j * a_dim1] *= mul; /* L40: */ } /* L50: */ } } else if (itype == 2) { /* Upper triangular matrix */ i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = min(j,*m); for (i__ = 1; i__ <= i__2; ++i__) { a[i__ + j * a_dim1] *= mul; /* L60: */ } /* L70: */ } } else if (itype == 3) { /* Upper Hessenberg matrix */ i__1 = *n; for (j = 1; j <= i__1; ++j) { /* Computing MIN */ i__3 = j + 1; i__2 = min(i__3,*m); for (i__ = 1; i__ <= i__2; ++i__) { a[i__ + j * a_dim1] *= mul; /* L80: */ } /* L90: */ } } else if (itype == 4) { /* Lower half of a symmetric band matrix */ k3 = *kl + 1; k4 = *n + 1; i__1 = *n; for (j = 1; j <= i__1; ++j) { /* Computing MIN */ i__3 = k3, i__4 = k4 - j; i__2 = min(i__3,i__4); for (i__ = 1; i__ <= i__2; ++i__) { a[i__ + j * a_dim1] *= mul; /* L100: */ } /* L110: */ } } else if (itype == 5) { /* Upper half of a symmetric band matrix */ k1 = *ku + 2; k3 = *ku + 1; i__1 = *n; for (j = 1; j <= i__1; ++j) { /* Computing MAX */ i__2 = k1 - j; i__3 = k3; for (i__ = max(i__2,1); i__ <= i__3; ++i__) { a[i__ + j * a_dim1] *= mul; /* L120: */ } /* L130: */ } } else if (itype == 6) { /* Band matrix */ k1 = *kl + *ku + 2; k2 = *kl + 1; k3 = ((*kl) << (1)) + *ku + 1; k4 = *kl + *ku + 1 + *m; i__1 = *n; for (j = 1; j <= i__1; ++j) { /* Computing MAX */ i__3 = k1 - j; /* Computing MIN */ i__4 = k3, i__5 = k4 - j; i__2 = min(i__4,i__5); for (i__ = max(i__3,k2); i__ <= i__2; ++i__) { a[i__ + j * a_dim1] *= mul; /* L140: */ } /* L150: */ } } if (! done) { goto L10; } return 0; /* End of SLASCL */ } /* slascl_ */ /* Subroutine */ int slasd0_(integer *n, integer *sqre, real *d__, real *e, real *u, integer *ldu, real *vt, integer *ldvt, integer *smlsiz, integer *iwork, real *work, integer *info) { /* System generated locals */ integer u_dim1, u_offset, vt_dim1, vt_offset, i__1, i__2; /* Builtin functions */ integer pow_ii(integer *, integer *); /* Local variables */ static integer i__, j, m, i1, ic, lf, nd, ll, nl, nr, im1, ncc, nlf, nrf, iwk, lvl, ndb1, nlp1, nrp1; static real beta; static integer idxq, nlvl; static real alpha; static integer inode, ndiml, idxqc, ndimr, itemp, sqrei; extern /* Subroutine */ int slasd1_(integer *, integer *, integer *, real *, real *, real *, real *, integer *, real *, integer *, integer * , integer *, real *, integer *), xerbla_(char *, integer *), slasdq_(char *, integer *, integer *, integer *, integer *, integer *, real *, real *, real *, integer *, real *, integer * , real *, integer *, real *, integer *), slasdt_(integer * , integer *, integer *, integer *, integer *, integer *, integer * ); /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= Using a divide and conquer approach, SLASD0 computes the singular value decomposition (SVD) of a real upper bidiagonal N-by-M matrix B with diagonal D and offdiagonal E, where M = N + SQRE. The algorithm computes orthogonal matrices U and VT such that B = U * S * VT. The singular values S are overwritten on D. A related subroutine, SLASDA, computes only the singular values, and optionally, the singular vectors in compact form. Arguments ========= N (input) INTEGER On entry, the row dimension of the upper bidiagonal matrix. This is also the dimension of the main diagonal array D. SQRE (input) INTEGER Specifies the column dimension of the bidiagonal matrix. = 0: The bidiagonal matrix has column dimension M = N; = 1: The bidiagonal matrix has column dimension M = N+1; D (input/output) REAL array, dimension (N) On entry D contains the main diagonal of the bidiagonal matrix. On exit D, if INFO = 0, contains its singular values. E (input) REAL array, dimension (M-1) Contains the subdiagonal entries of the bidiagonal matrix. On exit, E has been destroyed. U (output) REAL array, dimension at least (LDQ, N) On exit, U contains the left singular vectors. LDU (input) INTEGER On entry, leading dimension of U. VT (output) REAL array, dimension at least (LDVT, M) On exit, VT' contains the right singular vectors. LDVT (input) INTEGER On entry, leading dimension of VT. SMLSIZ (input) INTEGER On entry, maximum size of the subproblems at the bottom of the computation tree. IWORK INTEGER work array. Dimension must be at least (8 * N) WORK REAL work array. Dimension must be at least (3 * M**2 + 2 * M) INFO (output) INTEGER = 0: successful exit. < 0: if INFO = -i, the i-th argument had an illegal value. > 0: if INFO = 1, an singular value did not converge Further Details =============== Based on contributions by Ming Gu and Huan Ren, Computer Science Division, University of California at Berkeley, USA ===================================================================== Test the input parameters. */ /* Parameter adjustments */ --d__; --e; u_dim1 = *ldu; u_offset = 1 + u_dim1; u -= u_offset; vt_dim1 = *ldvt; vt_offset = 1 + vt_dim1; vt -= vt_offset; --iwork; --work; /* Function Body */ *info = 0; if (*n < 0) { *info = -1; } else if ((*sqre < 0) || (*sqre > 1)) { *info = -2; } m = *n + *sqre; if (*ldu < *n) { *info = -6; } else if (*ldvt < m) { *info = -8; } else if (*smlsiz < 3) { *info = -9; } if (*info != 0) { i__1 = -(*info); xerbla_("SLASD0", &i__1); return 0; } /* If the input matrix is too small, call SLASDQ to find the SVD. */ if (*n <= *smlsiz) { slasdq_("U", sqre, n, &m, n, &c__0, &d__[1], &e[1], &vt[vt_offset], ldvt, &u[u_offset], ldu, &u[u_offset], ldu, &work[1], info); return 0; } /* Set up the computation tree. */ inode = 1; ndiml = inode + *n; ndimr = ndiml + *n; idxq = ndimr + *n; iwk = idxq + *n; slasdt_(n, &nlvl, &nd, &iwork[inode], &iwork[ndiml], &iwork[ndimr], smlsiz); /* For the nodes on bottom level of the tree, solve their subproblems by SLASDQ. */ ndb1 = (nd + 1) / 2; ncc = 0; i__1 = nd; for (i__ = ndb1; i__ <= i__1; ++i__) { /* IC : center row of each node NL : number of rows of left subproblem NR : number of rows of right subproblem NLF: starting row of the left subproblem NRF: starting row of the right subproblem */ i1 = i__ - 1; ic = iwork[inode + i1]; nl = iwork[ndiml + i1]; nlp1 = nl + 1; nr = iwork[ndimr + i1]; nrp1 = nr + 1; nlf = ic - nl; nrf = ic + 1; sqrei = 1; slasdq_("U", &sqrei, &nl, &nlp1, &nl, &ncc, &d__[nlf], &e[nlf], &vt[ nlf + nlf * vt_dim1], ldvt, &u[nlf + nlf * u_dim1], ldu, &u[ nlf + nlf * u_dim1], ldu, &work[1], info); if (*info != 0) { return 0; } itemp = idxq + nlf - 2; i__2 = nl; for (j = 1; j <= i__2; ++j) { iwork[itemp + j] = j; /* L10: */ } if (i__ == nd) { sqrei = *sqre; } else { sqrei = 1; } nrp1 = nr + sqrei; slasdq_("U", &sqrei, &nr, &nrp1, &nr, &ncc, &d__[nrf], &e[nrf], &vt[ nrf + nrf * vt_dim1], ldvt, &u[nrf + nrf * u_dim1], ldu, &u[ nrf + nrf * u_dim1], ldu, &work[1], info); if (*info != 0) { return 0; } itemp = idxq + ic; i__2 = nr; for (j = 1; j <= i__2; ++j) { iwork[itemp + j - 1] = j; /* L20: */ } /* L30: */ } /* Now conquer each subproblem bottom-up. */ for (lvl = nlvl; lvl >= 1; --lvl) { /* Find the first node LF and last node LL on the current level LVL. */ if (lvl == 1) { lf = 1; ll = 1; } else { i__1 = lvl - 1; lf = pow_ii(&c__2, &i__1); ll = ((lf) << (1)) - 1; } i__1 = ll; for (i__ = lf; i__ <= i__1; ++i__) { im1 = i__ - 1; ic = iwork[inode + im1]; nl = iwork[ndiml + im1]; nr = iwork[ndimr + im1]; nlf = ic - nl; if (*sqre == 0 && i__ == ll) { sqrei = *sqre; } else { sqrei = 1; } idxqc = idxq + nlf - 1; alpha = d__[ic]; beta = e[ic]; slasd1_(&nl, &nr, &sqrei, &d__[nlf], &alpha, &beta, &u[nlf + nlf * u_dim1], ldu, &vt[nlf + nlf * vt_dim1], ldvt, &iwork[ idxqc], &iwork[iwk], &work[1], info); if (*info != 0) { return 0; } /* L40: */ } /* L50: */ } return 0; /* End of SLASD0 */ } /* slasd0_ */ /* Subroutine */ int slasd1_(integer *nl, integer *nr, integer *sqre, real * d__, real *alpha, real *beta, real *u, integer *ldu, real *vt, integer *ldvt, integer *idxq, integer *iwork, real *work, integer * info) { /* System generated locals */ integer u_dim1, u_offset, vt_dim1, vt_offset, i__1; real r__1, r__2; /* Local variables */ static integer i__, k, m, n, n1, n2, iq, iz, iu2, ldq, idx, ldu2, ivt2, idxc, idxp, ldvt2; extern /* Subroutine */ int slasd2_(integer *, integer *, integer *, integer *, real *, real *, real *, real *, real *, integer *, real *, integer *, real *, real *, integer *, real *, integer *, integer *, integer *, integer *, integer *, integer *, integer *), slasd3_(integer *, integer *, integer *, integer *, real *, real *, integer *, real *, real *, integer *, real *, integer *, real * , integer *, real *, integer *, integer *, integer *, real *, integer *); static integer isigma; extern /* Subroutine */ int xerbla_(char *, integer *), slascl_( char *, integer *, integer *, real *, real *, integer *, integer * , real *, integer *, integer *), slamrg_(integer *, integer *, real *, integer *, integer *, integer *); static real orgnrm; static integer coltyp; /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= SLASD1 computes the SVD of an upper bidiagonal N-by-M matrix B, where N = NL + NR + 1 and M = N + SQRE. SLASD1 is called from SLASD0. A related subroutine SLASD7 handles the case in which the singular values (and the singular vectors in factored form) are desired. SLASD1 computes the SVD as follows: ( D1(in) 0 0 0 ) B = U(in) * ( Z1' a Z2' b ) * VT(in) ( 0 0 D2(in) 0 ) = U(out) * ( D(out) 0) * VT(out) where Z' = (Z1' a Z2' b) = u' VT', and u is a vector of dimension M with ALPHA and BETA in the NL+1 and NL+2 th entries and zeros elsewhere; and the entry b is empty if SQRE = 0. The left singular vectors of the original matrix are stored in U, and the transpose of the right singular vectors are stored in VT, and the singular values are in D. The algorithm consists of three stages: The first stage consists of deflating the size of the problem when there are multiple singular values or when there are zeros in the Z vector. For each such occurence the dimension of the secular equation problem is reduced by one. This stage is performed by the routine SLASD2. The second stage consists of calculating the updated singular values. This is done by finding the square roots of the roots of the secular equation via the routine SLASD4 (as called by SLASD3). This routine also calculates the singular vectors of the current problem. The final stage consists of computing the updated singular vectors directly using the updated singular values. The singular vectors for the current problem are multiplied with the singular vectors from the overall problem. Arguments ========= NL (input) INTEGER The row dimension of the upper block. NL >= 1. NR (input) INTEGER The row dimension of the lower block. NR >= 1. SQRE (input) INTEGER = 0: the lower block is an NR-by-NR square matrix. = 1: the lower block is an NR-by-(NR+1) rectangular matrix. The bidiagonal matrix has row dimension N = NL + NR + 1, and column dimension M = N + SQRE. D (input/output) REAL array, dimension (N = NL+NR+1). On entry D(1:NL,1:NL) contains the singular values of the upper block; and D(NL+2:N) contains the singular values of the lower block. On exit D(1:N) contains the singular values of the modified matrix. ALPHA (input) REAL Contains the diagonal element associated with the added row. BETA (input) REAL Contains the off-diagonal element associated with the added row. U (input/output) REAL array, dimension(LDU,N) On entry U(1:NL, 1:NL) contains the left singular vectors of the upper block; U(NL+2:N, NL+2:N) contains the left singular vectors of the lower block. On exit U contains the left singular vectors of the bidiagonal matrix. LDU (input) INTEGER The leading dimension of the array U. LDU >= max( 1, N ). VT (input/output) REAL array, dimension(LDVT,M) where M = N + SQRE. On entry VT(1:NL+1, 1:NL+1)' contains the right singular vectors of the upper block; VT(NL+2:M, NL+2:M)' contains the right singular vectors of the lower block. On exit VT' contains the right singular vectors of the bidiagonal matrix. LDVT (input) INTEGER The leading dimension of the array VT. LDVT >= max( 1, M ). IDXQ (output) INTEGER array, dimension(N) This contains the permutation which will reintegrate the subproblem just solved back into sorted order, i.e. D( IDXQ( I = 1, N ) ) will be in ascending order. IWORK (workspace) INTEGER array, dimension( 4 * N ) WORK (workspace) REAL array, dimension( 3*M**2 + 2*M ) INFO (output) INTEGER = 0: successful exit. < 0: if INFO = -i, the i-th argument had an illegal value. > 0: if INFO = 1, an singular value did not converge Further Details =============== Based on contributions by Ming Gu and Huan Ren, Computer Science Division, University of California at Berkeley, USA ===================================================================== Test the input parameters. */ /* Parameter adjustments */ --d__; u_dim1 = *ldu; u_offset = 1 + u_dim1; u -= u_offset; vt_dim1 = *ldvt; vt_offset = 1 + vt_dim1; vt -= vt_offset; --idxq; --iwork; --work; /* Function Body */ *info = 0; if (*nl < 1) { *info = -1; } else if (*nr < 1) { *info = -2; } else if ((*sqre < 0) || (*sqre > 1)) { *info = -3; } if (*info != 0) { i__1 = -(*info); xerbla_("SLASD1", &i__1); return 0; } n = *nl + *nr + 1; m = n + *sqre; /* The following values are for bookkeeping purposes only. They are integer pointers which indicate the portion of the workspace used by a particular array in SLASD2 and SLASD3. */ ldu2 = n; ldvt2 = m; iz = 1; isigma = iz + m; iu2 = isigma + n; ivt2 = iu2 + ldu2 * n; iq = ivt2 + ldvt2 * m; idx = 1; idxc = idx + n; coltyp = idxc + n; idxp = coltyp + n; /* Scale. Computing MAX */ r__1 = dabs(*alpha), r__2 = dabs(*beta); orgnrm = dmax(r__1,r__2); d__[*nl + 1] = 0.f; i__1 = n; for (i__ = 1; i__ <= i__1; ++i__) { if ((r__1 = d__[i__], dabs(r__1)) > orgnrm) { orgnrm = (r__1 = d__[i__], dabs(r__1)); } /* L10: */ } slascl_("G", &c__0, &c__0, &orgnrm, &c_b1011, &n, &c__1, &d__[1], &n, info); *alpha /= orgnrm; *beta /= orgnrm; /* Deflate singular values. */ slasd2_(nl, nr, sqre, &k, &d__[1], &work[iz], alpha, beta, &u[u_offset], ldu, &vt[vt_offset], ldvt, &work[isigma], &work[iu2], &ldu2, & work[ivt2], &ldvt2, &iwork[idxp], &iwork[idx], &iwork[idxc], & idxq[1], &iwork[coltyp], info); /* Solve Secular Equation and update singular vectors. */ ldq = k; slasd3_(nl, nr, sqre, &k, &d__[1], &work[iq], &ldq, &work[isigma], &u[ u_offset], ldu, &work[iu2], &ldu2, &vt[vt_offset], ldvt, &work[ ivt2], &ldvt2, &iwork[idxc], &iwork[coltyp], &work[iz], info); if (*info != 0) { return 0; } /* Unscale. */ slascl_("G", &c__0, &c__0, &c_b1011, &orgnrm, &n, &c__1, &d__[1], &n, info); /* Prepare the IDXQ sorting permutation. */ n1 = k; n2 = n - k; slamrg_(&n1, &n2, &d__[1], &c__1, &c_n1, &idxq[1]); return 0; /* End of SLASD1 */ } /* slasd1_ */ /* Subroutine */ int slasd2_(integer *nl, integer *nr, integer *sqre, integer *k, real *d__, real *z__, real *alpha, real *beta, real *u, integer * ldu, real *vt, integer *ldvt, real *dsigma, real *u2, integer *ldu2, real *vt2, integer *ldvt2, integer *idxp, integer *idx, integer *idxc, integer *idxq, integer *coltyp, integer *info) { /* System generated locals */ integer u_dim1, u_offset, u2_dim1, u2_offset, vt_dim1, vt_offset, vt2_dim1, vt2_offset, i__1; real r__1, r__2; /* Local variables */ static real c__; static integer i__, j, m, n; static real s; static integer k2; static real z1; static integer ct, jp; static real eps, tau, tol; static integer psm[4], nlp1, nlp2, idxi, idxj, ctot[4]; extern /* Subroutine */ int srot_(integer *, real *, integer *, real *, integer *, real *, real *); static integer idxjp, jprev; extern /* Subroutine */ int scopy_(integer *, real *, integer *, real *, integer *); extern doublereal slapy2_(real *, real *), slamch_(char *); extern /* Subroutine */ int xerbla_(char *, integer *), slamrg_( integer *, integer *, real *, integer *, integer *, integer *); static real hlftol; extern /* Subroutine */ int slacpy_(char *, integer *, integer *, real *, integer *, real *, integer *), slaset_(char *, integer *, integer *, real *, real *, real *, integer *); /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Oak Ridge National Lab, Argonne National Lab, Courant Institute, NAG Ltd., and Rice University October 31, 1999 Purpose ======= SLASD2 merges the two sets of singular values together into a single sorted set. Then it tries to deflate the size of the problem. There are two ways in which deflation can occur: when two or more singular values are close together or if there is a tiny entry in the Z vector. For each such occurrence the order of the related secular equation problem is reduced by one. SLASD2 is called from SLASD1. Arguments ========= NL (input) INTEGER The row dimension of the upper block. NL >= 1. NR (input) INTEGER The row dimension of the lower block. NR >= 1. SQRE (input) INTEGER = 0: the lower block is an NR-by-NR square matrix. = 1: the lower block is an NR-by-(NR+1) rectangular matrix. The bidiagonal matrix has N = NL + NR + 1 rows and M = N + SQRE >= N columns. K (output) INTEGER Contains the dimension of the non-deflated matrix, This is the order of the related secular equation. 1 <= K <=N. D (input/output) REAL array, dimension(N) On entry D contains the singular values of the two submatrices to be combined. On exit D contains the trailing (N-K) updated singular values (those which were deflated) sorted into increasing order. ALPHA (input) REAL Contains the diagonal element associated with the added row. BETA (input) REAL Contains the off-diagonal element associated with the added row. U (input/output) REAL array, dimension(LDU,N) On entry U contains the left singular vectors of two submatrices in the two square blocks with corners at (1,1), (NL, NL), and (NL+2, NL+2), (N,N). On exit U contains the trailing (N-K) updated left singular vectors (those which were deflated) in its last N-K columns. LDU (input) INTEGER The leading dimension of the array U. LDU >= N. Z (output) REAL array, dimension(N) On exit Z contains the updating row vector in the secular equation. DSIGMA (output) REAL array, dimension (N) Contains a copy of the diagonal elements (K-1 singular values and one zero) in the secular equation. U2 (output) REAL array, dimension(LDU2,N) Contains a copy of the first K-1 left singular vectors which will be used by SLASD3 in a matrix multiply (SGEMM) to solve for the new left singular vectors. U2 is arranged into four blocks. The first block contains a column with 1 at NL+1 and zero everywhere else; the second block contains non-zero entries only at and above NL; the third contains non-zero entries only below NL+1; and the fourth is dense. LDU2 (input) INTEGER The leading dimension of the array U2. LDU2 >= N. VT (input/output) REAL array, dimension(LDVT,M) On entry VT' contains the right singular vectors of two submatrices in the two square blocks with corners at (1,1), (NL+1, NL+1), and (NL+2, NL+2), (M,M). On exit VT' contains the trailing (N-K) updated right singular vectors (those which were deflated) in its last N-K columns. In case SQRE =1, the last row of VT spans the right null space. LDVT (input) INTEGER The leading dimension of the array VT. LDVT >= M. VT2 (output) REAL array, dimension(LDVT2,N) VT2' contains a copy of the first K right singular vectors which will be used by SLASD3 in a matrix multiply (SGEMM) to solve for the new right singular vectors. VT2 is arranged into three blocks. The first block contains a row that corresponds to the special 0 diagonal element in SIGMA; the second block contains non-zeros only at and before NL +1; the third block contains non-zeros only at and after NL +2. LDVT2 (input) INTEGER The leading dimension of the array VT2. LDVT2 >= M. IDXP (workspace) INTEGER array, dimension(N) This will contain the permutation used to place deflated values of D at the end of the array. On output IDXP(2:K) points to the nondeflated D-values and IDXP(K+1:N) points to the deflated singular values. IDX (workspace) INTEGER array, dimension(N) This will contain the permutation used to sort the contents of D into ascending order. IDXC (output) INTEGER array, dimension(N) This will contain the permutation used to arrange the columns of the deflated U matrix into three groups: the first group contains non-zero entries only at and above NL, the second contains non-zero entries only below NL+2, and the third is dense. COLTYP (workspace/output) INTEGER array, dimension(N) As workspace, this will contain a label which will indicate which of the following types a column in the U2 matrix or a row in the VT2 matrix is: 1 : non-zero in the upper half only 2 : non-zero in the lower half only 3 : dense 4 : deflated On exit, it is an array of dimension 4, with COLTYP(I) being the dimension of the I-th type columns. IDXQ (input) INTEGER array, dimension(N) This contains the permutation which separately sorts the two sub-problems in D into ascending order. Note that entries in the first hlaf of this permutation must first be moved one position backward; and entries in the second half must first have NL+1 added to their values. INFO (output) INTEGER = 0: successful exit. < 0: if INFO = -i, the i-th argument had an illegal value. Further Details =============== Based on contributions by Ming Gu and Huan Ren, Computer Science Division, University of California at Berkeley, USA ===================================================================== Test the input parameters. */ /* Parameter adjustments */ --d__; --z__; u_dim1 = *ldu; u_offset = 1 + u_dim1; u -= u_offset; vt_dim1 = *ldvt; vt_offset = 1 + vt_dim1; vt -= vt_offset; --dsigma; u2_dim1 = *ldu2; u2_offset = 1 + u2_dim1; u2 -= u2_offset; vt2_dim1 = *ldvt2; vt2_offset = 1 + vt2_dim1; vt2 -= vt2_offset; --idxp; --idx; --idxc; --idxq; --coltyp; /* Function Body */ *info = 0; if (*nl < 1) { *info = -1; } else if (*nr < 1) { *info = -2; } else if (*sqre != 1 && *sqre != 0) { *info = -3; } n = *nl + *nr + 1; m = n + *sqre; if (*ldu < n) { *info = -10; } else if (*ldvt < m) { *info = -12; } else if (*ldu2 < n) { *info = -15; } else if (*ldvt2 < m) { *info = -17; } if (*info != 0) { i__1 = -(*info); xerbla_("SLASD2", &i__1); return 0; } nlp1 = *nl + 1; nlp2 = *nl + 2; /* Generate the first part of the vector Z; and move the singular values in the first part of D one position backward. */ z1 = *alpha * vt[nlp1 + nlp1 * vt_dim1]; z__[1] = z1; for (i__ = *nl; i__ >= 1; --i__) { z__[i__ + 1] = *alpha * vt[i__ + nlp1 * vt_dim1]; d__[i__ + 1] = d__[i__]; idxq[i__ + 1] = idxq[i__] + 1; /* L10: */ } /* Generate the second part of the vector Z. */ i__1 = m; for (i__ = nlp2; i__ <= i__1; ++i__) { z__[i__] = *beta * vt[i__ + nlp2 * vt_dim1]; /* L20: */ } /* Initialize some reference arrays. */ i__1 = nlp1; for (i__ = 2; i__ <= i__1; ++i__) { coltyp[i__] = 1; /* L30: */ } i__1 = n; for (i__ = nlp2; i__ <= i__1; ++i__) { coltyp[i__] = 2; /* L40: */ } /* Sort the singular values into increasing order */ i__1 = n; for (i__ = nlp2; i__ <= i__1; ++i__) { idxq[i__] += nlp1; /* L50: */ } /* DSIGMA, IDXC, IDXC, and the first column of U2 are used as storage space. */ i__1 = n; for (i__ = 2; i__ <= i__1; ++i__) { dsigma[i__] = d__[idxq[i__]]; u2[i__ + u2_dim1] = z__[idxq[i__]]; idxc[i__] = coltyp[idxq[i__]]; /* L60: */ } slamrg_(nl, nr, &dsigma[2], &c__1, &c__1, &idx[2]); i__1 = n; for (i__ = 2; i__ <= i__1; ++i__) { idxi = idx[i__] + 1; d__[i__] = dsigma[idxi]; z__[i__] = u2[idxi + u2_dim1]; coltyp[i__] = idxc[idxi]; /* L70: */ } /* Calculate the allowable deflation tolerance */ eps = slamch_("Epsilon"); /* Computing MAX */ r__1 = dabs(*alpha), r__2 = dabs(*beta); tol = dmax(r__1,r__2); /* Computing MAX */ r__2 = (r__1 = d__[n], dabs(r__1)); tol = eps * 8.f * dmax(r__2,tol); /* There are 2 kinds of deflation -- first a value in the z-vector is small, second two (or more) singular values are very close together (their difference is small). If the value in the z-vector is small, we simply permute the array so that the corresponding singular value is moved to the end. If two values in the D-vector are close, we perform a two-sided rotation designed to make one of the corresponding z-vector entries zero, and then permute the array so that the deflated singular value is moved to the end. If there are multiple singular values then the problem deflates. Here the number of equal singular values are found. As each equal singular value is found, an elementary reflector is computed to rotate the corresponding singular subspace so that the corresponding components of Z are zero in this new basis. */ *k = 1; k2 = n + 1; i__1 = n; for (j = 2; j <= i__1; ++j) { if ((r__1 = z__[j], dabs(r__1)) <= tol) { /* Deflate due to small z component. */ --k2; idxp[k2] = j; coltyp[j] = 4; if (j == n) { goto L120; } } else { jprev = j; goto L90; } /* L80: */ } L90: j = jprev; L100: ++j; if (j > n) { goto L110; } if ((r__1 = z__[j], dabs(r__1)) <= tol) { /* Deflate due to small z component. */ --k2; idxp[k2] = j; coltyp[j] = 4; } else { /* Check if singular values are close enough to allow deflation. */ if ((r__1 = d__[j] - d__[jprev], dabs(r__1)) <= tol) { /* Deflation is possible. */ s = z__[jprev]; c__ = z__[j]; /* Find sqrt(a**2+b**2) without overflow or destructive underflow. */ tau = slapy2_(&c__, &s); c__ /= tau; s = -s / tau; z__[j] = tau; z__[jprev] = 0.f; /* Apply back the Givens rotation to the left and right singular vector matrices. */ idxjp = idxq[idx[jprev] + 1]; idxj = idxq[idx[j] + 1]; if (idxjp <= nlp1) { --idxjp; } if (idxj <= nlp1) { --idxj; } srot_(&n, &u[idxjp * u_dim1 + 1], &c__1, &u[idxj * u_dim1 + 1], & c__1, &c__, &s); srot_(&m, &vt[idxjp + vt_dim1], ldvt, &vt[idxj + vt_dim1], ldvt, & c__, &s); if (coltyp[j] != coltyp[jprev]) { coltyp[j] = 3; } coltyp[jprev] = 4; --k2; idxp[k2] = jprev; jprev = j; } else { ++(*k); u2[*k + u2_dim1] = z__[jprev]; dsigma[*k] = d__[jprev]; idxp[*k] = jprev; jprev = j; } } goto L100; L110: /* Record the last singular value. */ ++(*k); u2[*k + u2_dim1] = z__[jprev]; dsigma[*k] = d__[jprev]; idxp[*k] = jprev; L120: /* Count up the total number of the various types of columns, then form a permutation which positions the four column types into four groups of uniform structure (although one or more of these groups may be empty). */ for (j = 1; j <= 4; ++j) { ctot[j - 1] = 0; /* L130: */ } i__1 = n; for (j = 2; j <= i__1; ++j) { ct = coltyp[j]; ++ctot[ct - 1]; /* L140: */ } /* PSM(*) = Position in SubMatrix (of types 1 through 4) */ psm[0] = 2; psm[1] = ctot[0] + 2; psm[2] = psm[1] + ctot[1]; psm[3] = psm[2] + ctot[2]; /* Fill out the IDXC array so that the permutation which it induces will place all type-1 columns first, all type-2 columns next, then all type-3's, and finally all type-4's, starting from the second column. This applies similarly to the rows of VT. */ i__1 = n; for (j = 2; j <= i__1; ++j) { jp = idxp[j]; ct = coltyp[jp]; idxc[psm[ct - 1]] = j; ++psm[ct - 1]; /* L150: */ } /* Sort the singular values and corresponding singular vectors into DSIGMA, U2, and VT2 respectively. The singular values/vectors which were not deflated go into the first K slots of DSIGMA, U2, and VT2 respectively, while those which were deflated go into the last N - K slots, except that the first column/row will be treated separately. */ i__1 = n; for (j = 2; j <= i__1; ++j) { jp = idxp[j]; dsigma[j] = d__[jp]; idxj = idxq[idx[idxp[idxc[j]]] + 1]; if (idxj <= nlp1) { --idxj; } scopy_(&n, &u[idxj * u_dim1 + 1], &c__1, &u2[j * u2_dim1 + 1], &c__1); scopy_(&m, &vt[idxj + vt_dim1], ldvt, &vt2[j + vt2_dim1], ldvt2); /* L160: */ } /* Determine DSIGMA(1), DSIGMA(2) and Z(1) */ dsigma[1] = 0.f; hlftol = tol / 2.f; if (dabs(dsigma[2]) <= hlftol) { dsigma[2] = hlftol; } if (m > n) { z__[1] = slapy2_(&z1, &z__[m]); if (z__[1] <= tol) { c__ = 1.f; s = 0.f; z__[1] = tol; } else { c__ = z1 / z__[1]; s = z__[m] / z__[1]; } } else { if (dabs(z1) <= tol) { z__[1] = tol; } else { z__[1] = z1; } } /* Move the rest of the updating row to Z. */ i__1 = *k - 1; scopy_(&i__1, &u2[u2_dim1 + 2], &c__1, &z__[2], &c__1); /* Determine the first column of U2, the first row of VT2 and the last row of VT. */ slaset_("A", &n, &c__1, &c_b320, &c_b320, &u2[u2_offset], ldu2) ; u2[nlp1 + u2_dim1] = 1.f; if (m > n) { i__1 = nlp1; for (i__ = 1; i__ <= i__1; ++i__) { vt[m + i__ * vt_dim1] = -s * vt[nlp1 + i__ * vt_dim1]; vt2[i__ * vt2_dim1 + 1] = c__ * vt[nlp1 + i__ * vt_dim1]; /* L170: */ } i__1 = m; for (i__ = nlp2; i__ <= i__1; ++i__) { vt2[i__ * vt2_dim1 + 1] = s * vt[m + i__ * vt_dim1]; vt[m + i__ * vt_dim1] = c__ * vt[m + i__ * vt_dim1]; /* L180: */ } } else { scopy_(&m, &vt[nlp1 + vt_dim1], ldvt, &vt2[vt2_dim1 + 1], ldvt2); } if (m > n) { scopy_(&m, &vt[m + vt_dim1], ldvt, &vt2[m + vt2_dim1], ldvt2); } /* The deflated singular values and their corresponding vectors go into the back of D, U, and V respectively. */ if (n > *k) { i__1 = n - *k; scopy_(&i__1, &dsigma[*k + 1], &c__1, &d__[*k + 1], &c__1); i__1 = n - *k; slacpy_("A", &n, &i__1, &u2[(*k + 1) * u2_dim1 + 1], ldu2, &u[(*k + 1) * u_dim1 + 1], ldu); i__1 = n - *k; slacpy_("A", &i__1, &m, &vt2[*k + 1 + vt2_dim1], ldvt2, &vt[*k + 1 + vt_dim1], ldvt); } /* Copy CTOT into COLTYP for referencing in SLASD3. */ for (j = 1; j <= 4; ++j) { coltyp[j] = ctot[j - 1]; /* L190: */ } return 0; /* End of SLASD2 */ } /* slasd2_ */ /* Subroutine */ int slasd3_(integer *nl, integer *nr, integer *sqre, integer *k, real *d__, real *q, integer *ldq, real *dsigma, real *u, integer * ldu, real *u2, integer *ldu2, real *vt, integer *ldvt, real *vt2, integer *ldvt2, integer *idxc, integer *ctot, real *z__, integer * info) { /* System generated locals */ integer q_dim1, q_offset, u_dim1, u_offset, u2_dim1, u2_offset, vt_dim1, vt_offset, vt2_dim1, vt2_offset, i__1, i__2; real r__1, r__2; /* Builtin functions */ double sqrt(doublereal), r_sign(real *, real *); /* Local variables */ static integer i__, j, m, n, jc; static real rho; static integer nlp1, nlp2, nrp1; static real temp; extern doublereal snrm2_(integer *, real *, integer *); static integer ctemp; extern /* Subroutine */ int sgemm_(char *, char *, integer *, integer *, integer *, real *, real *, integer *, real *, integer *, real *, real *, integer *); static integer ktemp; extern /* Subroutine */ int scopy_(integer *, real *, integer *, real *, integer *); extern doublereal slamc3_(real *, real *); extern /* Subroutine */ int slasd4_(integer *, integer *, real *, real *, real *, real *, real *, real *, integer *), xerbla_(char *, integer *), slascl_(char *, integer *, integer *, real *, real *, integer *, integer *, real *, integer *, integer *), slacpy_(char *, integer *, integer *, real *, integer *, real *, integer *); /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Oak Ridge National Lab, Argonne National Lab, Courant Institute, NAG Ltd., and Rice University October 31, 1999 Purpose ======= SLASD3 finds all the square roots of the roots of the secular equation, as defined by the values in D and Z. It makes the appropriate calls to SLASD4 and then updates the singular vectors by matrix multiplication. This code makes very mild assumptions about floating point arithmetic. It will work on machines with a guard digit in add/subtract, or on those binary machines without guard digits which subtract like the Cray XMP, Cray YMP, Cray C 90, or Cray 2. It could conceivably fail on hexadecimal or decimal machines without guard digits, but we know of none. SLASD3 is called from SLASD1. Arguments ========= NL (input) INTEGER The row dimension of the upper block. NL >= 1. NR (input) INTEGER The row dimension of the lower block. NR >= 1. SQRE (input) INTEGER = 0: the lower block is an NR-by-NR square matrix. = 1: the lower block is an NR-by-(NR+1) rectangular matrix. The bidiagonal matrix has N = NL + NR + 1 rows and M = N + SQRE >= N columns. K (input) INTEGER The size of the secular equation, 1 =< K = < N. D (output) REAL array, dimension(K) On exit the square roots of the roots of the secular equation, in ascending order. Q (workspace) REAL array, dimension at least (LDQ,K). LDQ (input) INTEGER The leading dimension of the array Q. LDQ >= K. DSIGMA (input) REAL array, dimension(K) The first K elements of this array contain the old roots of the deflated updating problem. These are the poles of the secular equation. U (input) REAL array, dimension (LDU, N) The last N - K columns of this matrix contain the deflated left singular vectors. LDU (input) INTEGER The leading dimension of the array U. LDU >= N. U2 (input) REAL array, dimension (LDU2, N) The first K columns of this matrix contain the non-deflated left singular vectors for the split problem. LDU2 (input) INTEGER The leading dimension of the array U2. LDU2 >= N. VT (input) REAL array, dimension (LDVT, M) The last M - K columns of VT' contain the deflated right singular vectors. LDVT (input) INTEGER The leading dimension of the array VT. LDVT >= N. VT2 (input) REAL array, dimension (LDVT2, N) The first K columns of VT2' contain the non-deflated right singular vectors for the split problem. LDVT2 (input) INTEGER The leading dimension of the array VT2. LDVT2 >= N. IDXC (input) INTEGER array, dimension ( N ) The permutation used to arrange the columns of U (and rows of VT) into three groups: the first group contains non-zero entries only at and above (or before) NL +1; the second contains non-zero entries only at and below (or after) NL+2; and the third is dense. The first column of U and the row of VT are treated separately, however. The rows of the singular vectors found by SLASD4 must be likewise permuted before the matrix multiplies can take place. CTOT (input) INTEGER array, dimension ( 4 ) A count of the total number of the various types of columns in U (or rows in VT), as described in IDXC. The fourth column type is any column which has been deflated. Z (input) REAL array, dimension (K) The first K elements of this array contain the components of the deflation-adjusted updating row vector. INFO (output) INTEGER = 0: successful exit. < 0: if INFO = -i, the i-th argument had an illegal value. > 0: if INFO = 1, an singular value did not converge Further Details =============== Based on contributions by Ming Gu and Huan Ren, Computer Science Division, University of California at Berkeley, USA ===================================================================== Test the input parameters. */ /* Parameter adjustments */ --d__; q_dim1 = *ldq; q_offset = 1 + q_dim1; q -= q_offset; --dsigma; u_dim1 = *ldu; u_offset = 1 + u_dim1; u -= u_offset; u2_dim1 = *ldu2; u2_offset = 1 + u2_dim1; u2 -= u2_offset; vt_dim1 = *ldvt; vt_offset = 1 + vt_dim1; vt -= vt_offset; vt2_dim1 = *ldvt2; vt2_offset = 1 + vt2_dim1; vt2 -= vt2_offset; --idxc; --ctot; --z__; /* Function Body */ *info = 0; if (*nl < 1) { *info = -1; } else if (*nr < 1) { *info = -2; } else if (*sqre != 1 && *sqre != 0) { *info = -3; } n = *nl + *nr + 1; m = n + *sqre; nlp1 = *nl + 1; nlp2 = *nl + 2; if ((*k < 1) || (*k > n)) { *info = -4; } else if (*ldq < *k) { *info = -7; } else if (*ldu < n) { *info = -10; } else if (*ldu2 < n) { *info = -12; } else if (*ldvt < m) { *info = -14; } else if (*ldvt2 < m) { *info = -16; } if (*info != 0) { i__1 = -(*info); xerbla_("SLASD3", &i__1); return 0; } /* Quick return if possible */ if (*k == 1) { d__[1] = dabs(z__[1]); scopy_(&m, &vt2[vt2_dim1 + 1], ldvt2, &vt[vt_dim1 + 1], ldvt); if (z__[1] > 0.f) { scopy_(&n, &u2[u2_dim1 + 1], &c__1, &u[u_dim1 + 1], &c__1); } else { i__1 = n; for (i__ = 1; i__ <= i__1; ++i__) { u[i__ + u_dim1] = -u2[i__ + u2_dim1]; /* L10: */ } } return 0; } /* Modify values DSIGMA(i) to make sure all DSIGMA(i)-DSIGMA(j) can be computed with high relative accuracy (barring over/underflow). This is a problem on machines without a guard digit in add/subtract (Cray XMP, Cray YMP, Cray C 90 and Cray 2). The following code replaces DSIGMA(I) by 2*DSIGMA(I)-DSIGMA(I), which on any of these machines zeros out the bottommost bit of DSIGMA(I) if it is 1; this makes the subsequent subtractions DSIGMA(I)-DSIGMA(J) unproblematic when cancellation occurs. On binary machines with a guard digit (almost all machines) it does not change DSIGMA(I) at all. On hexadecimal and decimal machines with a guard digit, it slightly changes the bottommost bits of DSIGMA(I). It does not account for hexadecimal or decimal machines without guard digits (we know of none). We use a subroutine call to compute 2*DLAMBDA(I) to prevent optimizing compilers from eliminating this code. */ i__1 = *k; for (i__ = 1; i__ <= i__1; ++i__) { dsigma[i__] = slamc3_(&dsigma[i__], &dsigma[i__]) - dsigma[i__]; /* L20: */ } /* Keep a copy of Z. */ scopy_(k, &z__[1], &c__1, &q[q_offset], &c__1); /* Normalize Z. */ rho = snrm2_(k, &z__[1], &c__1); slascl_("G", &c__0, &c__0, &rho, &c_b1011, k, &c__1, &z__[1], k, info); rho *= rho; /* Find the new singular values. */ i__1 = *k; for (j = 1; j <= i__1; ++j) { slasd4_(k, &j, &dsigma[1], &z__[1], &u[j * u_dim1 + 1], &rho, &d__[j], &vt[j * vt_dim1 + 1], info); /* If the zero finder fails, the computation is terminated. */ if (*info != 0) { return 0; } /* L30: */ } /* Compute updated Z. */ i__1 = *k; for (i__ = 1; i__ <= i__1; ++i__) { z__[i__] = u[i__ + *k * u_dim1] * vt[i__ + *k * vt_dim1]; i__2 = i__ - 1; for (j = 1; j <= i__2; ++j) { z__[i__] *= u[i__ + j * u_dim1] * vt[i__ + j * vt_dim1] / (dsigma[ i__] - dsigma[j]) / (dsigma[i__] + dsigma[j]); /* L40: */ } i__2 = *k - 1; for (j = i__; j <= i__2; ++j) { z__[i__] *= u[i__ + j * u_dim1] * vt[i__ + j * vt_dim1] / (dsigma[ i__] - dsigma[j + 1]) / (dsigma[i__] + dsigma[j + 1]); /* L50: */ } r__2 = sqrt((r__1 = z__[i__], dabs(r__1))); z__[i__] = r_sign(&r__2, &q[i__ + q_dim1]); /* L60: */ } /* Compute left singular vectors of the modified diagonal matrix, and store related information for the right singular vectors. */ i__1 = *k; for (i__ = 1; i__ <= i__1; ++i__) { vt[i__ * vt_dim1 + 1] = z__[1] / u[i__ * u_dim1 + 1] / vt[i__ * vt_dim1 + 1]; u[i__ * u_dim1 + 1] = -1.f; i__2 = *k; for (j = 2; j <= i__2; ++j) { vt[j + i__ * vt_dim1] = z__[j] / u[j + i__ * u_dim1] / vt[j + i__ * vt_dim1]; u[j + i__ * u_dim1] = dsigma[j] * vt[j + i__ * vt_dim1]; /* L70: */ } temp = snrm2_(k, &u[i__ * u_dim1 + 1], &c__1); q[i__ * q_dim1 + 1] = u[i__ * u_dim1 + 1] / temp; i__2 = *k; for (j = 2; j <= i__2; ++j) { jc = idxc[j]; q[j + i__ * q_dim1] = u[jc + i__ * u_dim1] / temp; /* L80: */ } /* L90: */ } /* Update the left singular vector matrix. */ if (*k == 2) { sgemm_("N", "N", &n, k, k, &c_b1011, &u2[u2_offset], ldu2, &q[ q_offset], ldq, &c_b320, &u[u_offset], ldu); goto L100; } if (ctot[1] > 0) { sgemm_("N", "N", nl, k, &ctot[1], &c_b1011, &u2[((u2_dim1) << (1)) + 1], ldu2, &q[q_dim1 + 2], ldq, &c_b320, &u[u_dim1 + 1], ldu); if (ctot[3] > 0) { ktemp = ctot[1] + 2 + ctot[2]; sgemm_("N", "N", nl, k, &ctot[3], &c_b1011, &u2[ktemp * u2_dim1 + 1], ldu2, &q[ktemp + q_dim1], ldq, &c_b1011, &u[u_dim1 + 1], ldu); } } else if (ctot[3] > 0) { ktemp = ctot[1] + 2 + ctot[2]; sgemm_("N", "N", nl, k, &ctot[3], &c_b1011, &u2[ktemp * u2_dim1 + 1], ldu2, &q[ktemp + q_dim1], ldq, &c_b320, &u[u_dim1 + 1], ldu); } else { slacpy_("F", nl, k, &u2[u2_offset], ldu2, &u[u_offset], ldu); } scopy_(k, &q[q_dim1 + 1], ldq, &u[nlp1 + u_dim1], ldu); ktemp = ctot[1] + 2; ctemp = ctot[2] + ctot[3]; sgemm_("N", "N", nr, k, &ctemp, &c_b1011, &u2[nlp2 + ktemp * u2_dim1], ldu2, &q[ktemp + q_dim1], ldq, &c_b320, &u[nlp2 + u_dim1], ldu); /* Generate the right singular vectors. */ L100: i__1 = *k; for (i__ = 1; i__ <= i__1; ++i__) { temp = snrm2_(k, &vt[i__ * vt_dim1 + 1], &c__1); q[i__ + q_dim1] = vt[i__ * vt_dim1 + 1] / temp; i__2 = *k; for (j = 2; j <= i__2; ++j) { jc = idxc[j]; q[i__ + j * q_dim1] = vt[jc + i__ * vt_dim1] / temp; /* L110: */ } /* L120: */ } /* Update the right singular vector matrix. */ if (*k == 2) { sgemm_("N", "N", k, &m, k, &c_b1011, &q[q_offset], ldq, &vt2[ vt2_offset], ldvt2, &c_b320, &vt[vt_offset], ldvt); return 0; } ktemp = ctot[1] + 1; sgemm_("N", "N", k, &nlp1, &ktemp, &c_b1011, &q[q_dim1 + 1], ldq, &vt2[ vt2_dim1 + 1], ldvt2, &c_b320, &vt[vt_dim1 + 1], ldvt); ktemp = ctot[1] + 2 + ctot[2]; if (ktemp <= *ldvt2) { sgemm_("N", "N", k, &nlp1, &ctot[3], &c_b1011, &q[ktemp * q_dim1 + 1], ldq, &vt2[ktemp + vt2_dim1], ldvt2, &c_b1011, &vt[vt_dim1 + 1], ldvt); } ktemp = ctot[1] + 1; nrp1 = *nr + *sqre; if (ktemp > 1) { i__1 = *k; for (i__ = 1; i__ <= i__1; ++i__) { q[i__ + ktemp * q_dim1] = q[i__ + q_dim1]; /* L130: */ } i__1 = m; for (i__ = nlp2; i__ <= i__1; ++i__) { vt2[ktemp + i__ * vt2_dim1] = vt2[i__ * vt2_dim1 + 1]; /* L140: */ } } ctemp = ctot[2] + 1 + ctot[3]; sgemm_("N", "N", k, &nrp1, &ctemp, &c_b1011, &q[ktemp * q_dim1 + 1], ldq, &vt2[ktemp + nlp2 * vt2_dim1], ldvt2, &c_b320, &vt[nlp2 * vt_dim1 + 1], ldvt); return 0; /* End of SLASD3 */ } /* slasd3_ */ /* Subroutine */ int slasd4_(integer *n, integer *i__, real *d__, real *z__, real *delta, real *rho, real *sigma, real *work, integer *info) { /* System generated locals */ integer i__1; real r__1; /* Builtin functions */ double sqrt(doublereal); /* Local variables */ static real a, b, c__; static integer j; static real w, dd[3]; static integer ii; static real dw, zz[3]; static integer ip1; static real eta, phi, eps, tau, psi; static integer iim1, iip1; static real dphi, dpsi; static integer iter; static real temp, prew, sg2lb, sg2ub, temp1, temp2, dtiim, delsq, dtiip; static integer niter; static real dtisq; static logical swtch; static real dtnsq; extern /* Subroutine */ int slaed6_(integer *, logical *, real *, real *, real *, real *, real *, integer *); static real delsq2; extern /* Subroutine */ int slasd5_(integer *, real *, real *, real *, real *, real *, real *); static real dtnsq1; static logical swtch3; extern doublereal slamch_(char *); static logical orgati; static real erretm, dtipsq, rhoinv; /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Oak Ridge National Lab, Argonne National Lab, Courant Institute, NAG Ltd., and Rice University October 31, 1999 Purpose ======= This subroutine computes the square root of the I-th updated eigenvalue of a positive symmetric rank-one modification to a positive diagonal matrix whose entries are given as the squares of the corresponding entries in the array d, and that 0 <= D(i) < D(j) for i < j and that RHO > 0. This is arranged by the calling routine, and is no loss in generality. The rank-one modified system is thus diag( D ) * diag( D ) + RHO * Z * Z_transpose. where we assume the Euclidean norm of Z is 1. The method consists of approximating the rational functions in the secular equation by simpler interpolating rational functions. Arguments ========= N (input) INTEGER The length of all arrays. I (input) INTEGER The index of the eigenvalue to be computed. 1 <= I <= N. D (input) REAL array, dimension ( N ) The original eigenvalues. It is assumed that they are in order, 0 <= D(I) < D(J) for I < J. Z (input) REAL array, dimension ( N ) The components of the updating vector. DELTA (output) REAL array, dimension ( N ) If N .ne. 1, DELTA contains (D(j) - sigma_I) in its j-th component. If N = 1, then DELTA(1) = 1. The vector DELTA contains the information necessary to construct the (singular) eigenvectors. RHO (input) REAL The scalar in the symmetric updating formula. SIGMA (output) REAL The computed lambda_I, the I-th updated eigenvalue. WORK (workspace) REAL array, dimension ( N ) If N .ne. 1, WORK contains (D(j) + sigma_I) in its j-th component. If N = 1, then WORK( 1 ) = 1. INFO (output) INTEGER = 0: successful exit > 0: if INFO = 1, the updating process failed. Internal Parameters =================== Logical variable ORGATI (origin-at-i?) is used for distinguishing whether D(i) or D(i+1) is treated as the origin. ORGATI = .true. origin at i ORGATI = .false. origin at i+1 Logical variable SWTCH3 (switch-for-3-poles?) is for noting if we are working with THREE poles! MAXIT is the maximum number of iterations allowed for each eigenvalue. Further Details =============== Based on contributions by Ren-Cang Li, Computer Science Division, University of California at Berkeley, USA ===================================================================== Since this routine is called in an inner loop, we do no argument checking. Quick return for N=1 and 2. */ /* Parameter adjustments */ --work; --delta; --z__; --d__; /* Function Body */ *info = 0; if (*n == 1) { /* Presumably, I=1 upon entry */ *sigma = sqrt(d__[1] * d__[1] + *rho * z__[1] * z__[1]); delta[1] = 1.f; work[1] = 1.f; return 0; } if (*n == 2) { slasd5_(i__, &d__[1], &z__[1], &delta[1], rho, sigma, &work[1]); return 0; } /* Compute machine epsilon */ eps = slamch_("Epsilon"); rhoinv = 1.f / *rho; /* The case I = N */ if (*i__ == *n) { /* Initialize some basic variables */ ii = *n - 1; niter = 1; /* Calculate initial guess */ temp = *rho / 2.f; /* If ||Z||_2 is not one, then TEMP should be set to RHO * ||Z||_2^2 / TWO */ temp1 = temp / (d__[*n] + sqrt(d__[*n] * d__[*n] + temp)); i__1 = *n; for (j = 1; j <= i__1; ++j) { work[j] = d__[j] + d__[*n] + temp1; delta[j] = d__[j] - d__[*n] - temp1; /* L10: */ } psi = 0.f; i__1 = *n - 2; for (j = 1; j <= i__1; ++j) { psi += z__[j] * z__[j] / (delta[j] * work[j]); /* L20: */ } c__ = rhoinv + psi; w = c__ + z__[ii] * z__[ii] / (delta[ii] * work[ii]) + z__[*n] * z__[* n] / (delta[*n] * work[*n]); if (w <= 0.f) { temp1 = sqrt(d__[*n] * d__[*n] + *rho); temp = z__[*n - 1] * z__[*n - 1] / ((d__[*n - 1] + temp1) * (d__[* n] - d__[*n - 1] + *rho / (d__[*n] + temp1))) + z__[*n] * z__[*n] / *rho; /* The following TAU is to approximate SIGMA_n^2 - D( N )*D( N ) */ if (c__ <= temp) { tau = *rho; } else { delsq = (d__[*n] - d__[*n - 1]) * (d__[*n] + d__[*n - 1]); a = -c__ * delsq + z__[*n - 1] * z__[*n - 1] + z__[*n] * z__[* n]; b = z__[*n] * z__[*n] * delsq; if (a < 0.f) { tau = b * 2.f / (sqrt(a * a + b * 4.f * c__) - a); } else { tau = (a + sqrt(a * a + b * 4.f * c__)) / (c__ * 2.f); } } /* It can be proved that D(N)^2+RHO/2 <= SIGMA_n^2 < D(N)^2+TAU <= D(N)^2+RHO */ } else { delsq = (d__[*n] - d__[*n - 1]) * (d__[*n] + d__[*n - 1]); a = -c__ * delsq + z__[*n - 1] * z__[*n - 1] + z__[*n] * z__[*n]; b = z__[*n] * z__[*n] * delsq; /* The following TAU is to approximate SIGMA_n^2 - D( N )*D( N ) */ if (a < 0.f) { tau = b * 2.f / (sqrt(a * a + b * 4.f * c__) - a); } else { tau = (a + sqrt(a * a + b * 4.f * c__)) / (c__ * 2.f); } /* It can be proved that D(N)^2 < D(N)^2+TAU < SIGMA(N)^2 < D(N)^2+RHO/2 */ } /* The following ETA is to approximate SIGMA_n - D( N ) */ eta = tau / (d__[*n] + sqrt(d__[*n] * d__[*n] + tau)); *sigma = d__[*n] + eta; i__1 = *n; for (j = 1; j <= i__1; ++j) { delta[j] = d__[j] - d__[*i__] - eta; work[j] = d__[j] + d__[*i__] + eta; /* L30: */ } /* Evaluate PSI and the derivative DPSI */ dpsi = 0.f; psi = 0.f; erretm = 0.f; i__1 = ii; for (j = 1; j <= i__1; ++j) { temp = z__[j] / (delta[j] * work[j]); psi += z__[j] * temp; dpsi += temp * temp; erretm += psi; /* L40: */ } erretm = dabs(erretm); /* Evaluate PHI and the derivative DPHI */ temp = z__[*n] / (delta[*n] * work[*n]); phi = z__[*n] * temp; dphi = temp * temp; erretm = (-phi - psi) * 8.f + erretm - phi + rhoinv + dabs(tau) * ( dpsi + dphi); w = rhoinv + phi + psi; /* Test for convergence */ if (dabs(w) <= eps * erretm) { goto L240; } /* Calculate the new step */ ++niter; dtnsq1 = work[*n - 1] * delta[*n - 1]; dtnsq = work[*n] * delta[*n]; c__ = w - dtnsq1 * dpsi - dtnsq * dphi; a = (dtnsq + dtnsq1) * w - dtnsq * dtnsq1 * (dpsi + dphi); b = dtnsq * dtnsq1 * w; if (c__ < 0.f) { c__ = dabs(c__); } if (c__ == 0.f) { eta = *rho - *sigma * *sigma; } else if (a >= 0.f) { eta = (a + sqrt((r__1 = a * a - b * 4.f * c__, dabs(r__1)))) / ( c__ * 2.f); } else { eta = b * 2.f / (a - sqrt((r__1 = a * a - b * 4.f * c__, dabs( r__1)))); } /* Note, eta should be positive if w is negative, and eta should be negative otherwise. However, if for some reason caused by roundoff, eta*w > 0, we simply use one Newton step instead. This way will guarantee eta*w < 0. */ if (w * eta > 0.f) { eta = -w / (dpsi + dphi); } temp = eta - dtnsq; if (temp > *rho) { eta = *rho + dtnsq; } tau += eta; eta /= *sigma + sqrt(eta + *sigma * *sigma); i__1 = *n; for (j = 1; j <= i__1; ++j) { delta[j] -= eta; work[j] += eta; /* L50: */ } *sigma += eta; /* Evaluate PSI and the derivative DPSI */ dpsi = 0.f; psi = 0.f; erretm = 0.f; i__1 = ii; for (j = 1; j <= i__1; ++j) { temp = z__[j] / (work[j] * delta[j]); psi += z__[j] * temp; dpsi += temp * temp; erretm += psi; /* L60: */ } erretm = dabs(erretm); /* Evaluate PHI and the derivative DPHI */ temp = z__[*n] / (work[*n] * delta[*n]); phi = z__[*n] * temp; dphi = temp * temp; erretm = (-phi - psi) * 8.f + erretm - phi + rhoinv + dabs(tau) * ( dpsi + dphi); w = rhoinv + phi + psi; /* Main loop to update the values of the array DELTA */ iter = niter + 1; for (niter = iter; niter <= 20; ++niter) { /* Test for convergence */ if (dabs(w) <= eps * erretm) { goto L240; } /* Calculate the new step */ dtnsq1 = work[*n - 1] * delta[*n - 1]; dtnsq = work[*n] * delta[*n]; c__ = w - dtnsq1 * dpsi - dtnsq * dphi; a = (dtnsq + dtnsq1) * w - dtnsq1 * dtnsq * (dpsi + dphi); b = dtnsq1 * dtnsq * w; if (a >= 0.f) { eta = (a + sqrt((r__1 = a * a - b * 4.f * c__, dabs(r__1)))) / (c__ * 2.f); } else { eta = b * 2.f / (a - sqrt((r__1 = a * a - b * 4.f * c__, dabs( r__1)))); } /* Note, eta should be positive if w is negative, and eta should be negative otherwise. However, if for some reason caused by roundoff, eta*w > 0, we simply use one Newton step instead. This way will guarantee eta*w < 0. */ if (w * eta > 0.f) { eta = -w / (dpsi + dphi); } temp = eta - dtnsq; if (temp <= 0.f) { eta /= 2.f; } tau += eta; eta /= *sigma + sqrt(eta + *sigma * *sigma); i__1 = *n; for (j = 1; j <= i__1; ++j) { delta[j] -= eta; work[j] += eta; /* L70: */ } *sigma += eta; /* Evaluate PSI and the derivative DPSI */ dpsi = 0.f; psi = 0.f; erretm = 0.f; i__1 = ii; for (j = 1; j <= i__1; ++j) { temp = z__[j] / (work[j] * delta[j]); psi += z__[j] * temp; dpsi += temp * temp; erretm += psi; /* L80: */ } erretm = dabs(erretm); /* Evaluate PHI and the derivative DPHI */ temp = z__[*n] / (work[*n] * delta[*n]); phi = z__[*n] * temp; dphi = temp * temp; erretm = (-phi - psi) * 8.f + erretm - phi + rhoinv + dabs(tau) * (dpsi + dphi); w = rhoinv + phi + psi; /* L90: */ } /* Return with INFO = 1, NITER = MAXIT and not converged */ *info = 1; goto L240; /* End for the case I = N */ } else { /* The case for I < N */ niter = 1; ip1 = *i__ + 1; /* Calculate initial guess */ delsq = (d__[ip1] - d__[*i__]) * (d__[ip1] + d__[*i__]); delsq2 = delsq / 2.f; temp = delsq2 / (d__[*i__] + sqrt(d__[*i__] * d__[*i__] + delsq2)); i__1 = *n; for (j = 1; j <= i__1; ++j) { work[j] = d__[j] + d__[*i__] + temp; delta[j] = d__[j] - d__[*i__] - temp; /* L100: */ } psi = 0.f; i__1 = *i__ - 1; for (j = 1; j <= i__1; ++j) { psi += z__[j] * z__[j] / (work[j] * delta[j]); /* L110: */ } phi = 0.f; i__1 = *i__ + 2; for (j = *n; j >= i__1; --j) { phi += z__[j] * z__[j] / (work[j] * delta[j]); /* L120: */ } c__ = rhoinv + psi + phi; w = c__ + z__[*i__] * z__[*i__] / (work[*i__] * delta[*i__]) + z__[ ip1] * z__[ip1] / (work[ip1] * delta[ip1]); if (w > 0.f) { /* d(i)^2 < the ith sigma^2 < (d(i)^2+d(i+1)^2)/2 We choose d(i) as origin. */ orgati = TRUE_; sg2lb = 0.f; sg2ub = delsq2; a = c__ * delsq + z__[*i__] * z__[*i__] + z__[ip1] * z__[ip1]; b = z__[*i__] * z__[*i__] * delsq; if (a > 0.f) { tau = b * 2.f / (a + sqrt((r__1 = a * a - b * 4.f * c__, dabs( r__1)))); } else { tau = (a - sqrt((r__1 = a * a - b * 4.f * c__, dabs(r__1)))) / (c__ * 2.f); } /* TAU now is an estimation of SIGMA^2 - D( I )^2. The following, however, is the corresponding estimation of SIGMA - D( I ). */ eta = tau / (d__[*i__] + sqrt(d__[*i__] * d__[*i__] + tau)); } else { /* (d(i)^2+d(i+1)^2)/2 <= the ith sigma^2 < d(i+1)^2/2 We choose d(i+1) as origin. */ orgati = FALSE_; sg2lb = -delsq2; sg2ub = 0.f; a = c__ * delsq - z__[*i__] * z__[*i__] - z__[ip1] * z__[ip1]; b = z__[ip1] * z__[ip1] * delsq; if (a < 0.f) { tau = b * 2.f / (a - sqrt((r__1 = a * a + b * 4.f * c__, dabs( r__1)))); } else { tau = -(a + sqrt((r__1 = a * a + b * 4.f * c__, dabs(r__1)))) / (c__ * 2.f); } /* TAU now is an estimation of SIGMA^2 - D( IP1 )^2. The following, however, is the corresponding estimation of SIGMA - D( IP1 ). */ eta = tau / (d__[ip1] + sqrt((r__1 = d__[ip1] * d__[ip1] + tau, dabs(r__1)))); } if (orgati) { ii = *i__; *sigma = d__[*i__] + eta; i__1 = *n; for (j = 1; j <= i__1; ++j) { work[j] = d__[j] + d__[*i__] + eta; delta[j] = d__[j] - d__[*i__] - eta; /* L130: */ } } else { ii = *i__ + 1; *sigma = d__[ip1] + eta; i__1 = *n; for (j = 1; j <= i__1; ++j) { work[j] = d__[j] + d__[ip1] + eta; delta[j] = d__[j] - d__[ip1] - eta; /* L140: */ } } iim1 = ii - 1; iip1 = ii + 1; /* Evaluate PSI and the derivative DPSI */ dpsi = 0.f; psi = 0.f; erretm = 0.f; i__1 = iim1; for (j = 1; j <= i__1; ++j) { temp = z__[j] / (work[j] * delta[j]); psi += z__[j] * temp; dpsi += temp * temp; erretm += psi; /* L150: */ } erretm = dabs(erretm); /* Evaluate PHI and the derivative DPHI */ dphi = 0.f; phi = 0.f; i__1 = iip1; for (j = *n; j >= i__1; --j) { temp = z__[j] / (work[j] * delta[j]); phi += z__[j] * temp; dphi += temp * temp; erretm += phi; /* L160: */ } w = rhoinv + phi + psi; /* W is the value of the secular function with its ii-th element removed. */ swtch3 = FALSE_; if (orgati) { if (w < 0.f) { swtch3 = TRUE_; } } else { if (w > 0.f) { swtch3 = TRUE_; } } if ((ii == 1) || (ii == *n)) { swtch3 = FALSE_; } temp = z__[ii] / (work[ii] * delta[ii]); dw = dpsi + dphi + temp * temp; temp = z__[ii] * temp; w += temp; erretm = (phi - psi) * 8.f + erretm + rhoinv * 2.f + dabs(temp) * 3.f + dabs(tau) * dw; /* Test for convergence */ if (dabs(w) <= eps * erretm) { goto L240; } if (w <= 0.f) { sg2lb = dmax(sg2lb,tau); } else { sg2ub = dmin(sg2ub,tau); } /* Calculate the new step */ ++niter; if (! swtch3) { dtipsq = work[ip1] * delta[ip1]; dtisq = work[*i__] * delta[*i__]; if (orgati) { /* Computing 2nd power */ r__1 = z__[*i__] / dtisq; c__ = w - dtipsq * dw + delsq * (r__1 * r__1); } else { /* Computing 2nd power */ r__1 = z__[ip1] / dtipsq; c__ = w - dtisq * dw - delsq * (r__1 * r__1); } a = (dtipsq + dtisq) * w - dtipsq * dtisq * dw; b = dtipsq * dtisq * w; if (c__ == 0.f) { if (a == 0.f) { if (orgati) { a = z__[*i__] * z__[*i__] + dtipsq * dtipsq * (dpsi + dphi); } else { a = z__[ip1] * z__[ip1] + dtisq * dtisq * (dpsi + dphi); } } eta = b / a; } else if (a <= 0.f) { eta = (a - sqrt((r__1 = a * a - b * 4.f * c__, dabs(r__1)))) / (c__ * 2.f); } else { eta = b * 2.f / (a + sqrt((r__1 = a * a - b * 4.f * c__, dabs( r__1)))); } } else { /* Interpolation using THREE most relevant poles */ dtiim = work[iim1] * delta[iim1]; dtiip = work[iip1] * delta[iip1]; temp = rhoinv + psi + phi; if (orgati) { temp1 = z__[iim1] / dtiim; temp1 *= temp1; c__ = temp - dtiip * (dpsi + dphi) - (d__[iim1] - d__[iip1]) * (d__[iim1] + d__[iip1]) * temp1; zz[0] = z__[iim1] * z__[iim1]; if (dpsi < temp1) { zz[2] = dtiip * dtiip * dphi; } else { zz[2] = dtiip * dtiip * (dpsi - temp1 + dphi); } } else { temp1 = z__[iip1] / dtiip; temp1 *= temp1; c__ = temp - dtiim * (dpsi + dphi) - (d__[iip1] - d__[iim1]) * (d__[iim1] + d__[iip1]) * temp1; if (dphi < temp1) { zz[0] = dtiim * dtiim * dpsi; } else { zz[0] = dtiim * dtiim * (dpsi + (dphi - temp1)); } zz[2] = z__[iip1] * z__[iip1]; } zz[1] = z__[ii] * z__[ii]; dd[0] = dtiim; dd[1] = delta[ii] * work[ii]; dd[2] = dtiip; slaed6_(&niter, &orgati, &c__, dd, zz, &w, &eta, info); if (*info != 0) { goto L240; } } /* Note, eta should be positive if w is negative, and eta should be negative otherwise. However, if for some reason caused by roundoff, eta*w > 0, we simply use one Newton step instead. This way will guarantee eta*w < 0. */ if (w * eta >= 0.f) { eta = -w / dw; } if (orgati) { temp1 = work[*i__] * delta[*i__]; temp = eta - temp1; } else { temp1 = work[ip1] * delta[ip1]; temp = eta - temp1; } if ((temp > sg2ub) || (temp < sg2lb)) { if (w < 0.f) { eta = (sg2ub - tau) / 2.f; } else { eta = (sg2lb - tau) / 2.f; } } tau += eta; eta /= *sigma + sqrt(*sigma * *sigma + eta); prew = w; *sigma += eta; i__1 = *n; for (j = 1; j <= i__1; ++j) { work[j] += eta; delta[j] -= eta; /* L170: */ } /* Evaluate PSI and the derivative DPSI */ dpsi = 0.f; psi = 0.f; erretm = 0.f; i__1 = iim1; for (j = 1; j <= i__1; ++j) { temp = z__[j] / (work[j] * delta[j]); psi += z__[j] * temp; dpsi += temp * temp; erretm += psi; /* L180: */ } erretm = dabs(erretm); /* Evaluate PHI and the derivative DPHI */ dphi = 0.f; phi = 0.f; i__1 = iip1; for (j = *n; j >= i__1; --j) { temp = z__[j] / (work[j] * delta[j]); phi += z__[j] * temp; dphi += temp * temp; erretm += phi; /* L190: */ } temp = z__[ii] / (work[ii] * delta[ii]); dw = dpsi + dphi + temp * temp; temp = z__[ii] * temp; w = rhoinv + phi + psi + temp; erretm = (phi - psi) * 8.f + erretm + rhoinv * 2.f + dabs(temp) * 3.f + dabs(tau) * dw; if (w <= 0.f) { sg2lb = dmax(sg2lb,tau); } else { sg2ub = dmin(sg2ub,tau); } swtch = FALSE_; if (orgati) { if (-w > dabs(prew) / 10.f) { swtch = TRUE_; } } else { if (w > dabs(prew) / 10.f) { swtch = TRUE_; } } /* Main loop to update the values of the array DELTA and WORK */ iter = niter + 1; for (niter = iter; niter <= 20; ++niter) { /* Test for convergence */ if (dabs(w) <= eps * erretm) { goto L240; } /* Calculate the new step */ if (! swtch3) { dtipsq = work[ip1] * delta[ip1]; dtisq = work[*i__] * delta[*i__]; if (! swtch) { if (orgati) { /* Computing 2nd power */ r__1 = z__[*i__] / dtisq; c__ = w - dtipsq * dw + delsq * (r__1 * r__1); } else { /* Computing 2nd power */ r__1 = z__[ip1] / dtipsq; c__ = w - dtisq * dw - delsq * (r__1 * r__1); } } else { temp = z__[ii] / (work[ii] * delta[ii]); if (orgati) { dpsi += temp * temp; } else { dphi += temp * temp; } c__ = w - dtisq * dpsi - dtipsq * dphi; } a = (dtipsq + dtisq) * w - dtipsq * dtisq * dw; b = dtipsq * dtisq * w; if (c__ == 0.f) { if (a == 0.f) { if (! swtch) { if (orgati) { a = z__[*i__] * z__[*i__] + dtipsq * dtipsq * (dpsi + dphi); } else { a = z__[ip1] * z__[ip1] + dtisq * dtisq * ( dpsi + dphi); } } else { a = dtisq * dtisq * dpsi + dtipsq * dtipsq * dphi; } } eta = b / a; } else if (a <= 0.f) { eta = (a - sqrt((r__1 = a * a - b * 4.f * c__, dabs(r__1)) )) / (c__ * 2.f); } else { eta = b * 2.f / (a + sqrt((r__1 = a * a - b * 4.f * c__, dabs(r__1)))); } } else { /* Interpolation using THREE most relevant poles */ dtiim = work[iim1] * delta[iim1]; dtiip = work[iip1] * delta[iip1]; temp = rhoinv + psi + phi; if (swtch) { c__ = temp - dtiim * dpsi - dtiip * dphi; zz[0] = dtiim * dtiim * dpsi; zz[2] = dtiip * dtiip * dphi; } else { if (orgati) { temp1 = z__[iim1] / dtiim; temp1 *= temp1; temp2 = (d__[iim1] - d__[iip1]) * (d__[iim1] + d__[ iip1]) * temp1; c__ = temp - dtiip * (dpsi + dphi) - temp2; zz[0] = z__[iim1] * z__[iim1]; if (dpsi < temp1) { zz[2] = dtiip * dtiip * dphi; } else { zz[2] = dtiip * dtiip * (dpsi - temp1 + dphi); } } else { temp1 = z__[iip1] / dtiip; temp1 *= temp1; temp2 = (d__[iip1] - d__[iim1]) * (d__[iim1] + d__[ iip1]) * temp1; c__ = temp - dtiim * (dpsi + dphi) - temp2; if (dphi < temp1) { zz[0] = dtiim * dtiim * dpsi; } else { zz[0] = dtiim * dtiim * (dpsi + (dphi - temp1)); } zz[2] = z__[iip1] * z__[iip1]; } } dd[0] = dtiim; dd[1] = delta[ii] * work[ii]; dd[2] = dtiip; slaed6_(&niter, &orgati, &c__, dd, zz, &w, &eta, info); if (*info != 0) { goto L240; } } /* Note, eta should be positive if w is negative, and eta should be negative otherwise. However, if for some reason caused by roundoff, eta*w > 0, we simply use one Newton step instead. This way will guarantee eta*w < 0. */ if (w * eta >= 0.f) { eta = -w / dw; } if (orgati) { temp1 = work[*i__] * delta[*i__]; temp = eta - temp1; } else { temp1 = work[ip1] * delta[ip1]; temp = eta - temp1; } if ((temp > sg2ub) || (temp < sg2lb)) { if (w < 0.f) { eta = (sg2ub - tau) / 2.f; } else { eta = (sg2lb - tau) / 2.f; } } tau += eta; eta /= *sigma + sqrt(*sigma * *sigma + eta); *sigma += eta; i__1 = *n; for (j = 1; j <= i__1; ++j) { work[j] += eta; delta[j] -= eta; /* L200: */ } prew = w; /* Evaluate PSI and the derivative DPSI */ dpsi = 0.f; psi = 0.f; erretm = 0.f; i__1 = iim1; for (j = 1; j <= i__1; ++j) { temp = z__[j] / (work[j] * delta[j]); psi += z__[j] * temp; dpsi += temp * temp; erretm += psi; /* L210: */ } erretm = dabs(erretm); /* Evaluate PHI and the derivative DPHI */ dphi = 0.f; phi = 0.f; i__1 = iip1; for (j = *n; j >= i__1; --j) { temp = z__[j] / (work[j] * delta[j]); phi += z__[j] * temp; dphi += temp * temp; erretm += phi; /* L220: */ } temp = z__[ii] / (work[ii] * delta[ii]); dw = dpsi + dphi + temp * temp; temp = z__[ii] * temp; w = rhoinv + phi + psi + temp; erretm = (phi - psi) * 8.f + erretm + rhoinv * 2.f + dabs(temp) * 3.f + dabs(tau) * dw; if (w * prew > 0.f && dabs(w) > dabs(prew) / 10.f) { swtch = ! swtch; } if (w <= 0.f) { sg2lb = dmax(sg2lb,tau); } else { sg2ub = dmin(sg2ub,tau); } /* L230: */ } /* Return with INFO = 1, NITER = MAXIT and not converged */ *info = 1; } L240: return 0; /* End of SLASD4 */ } /* slasd4_ */ /* Subroutine */ int slasd5_(integer *i__, real *d__, real *z__, real *delta, real *rho, real *dsigma, real *work) { /* System generated locals */ real r__1; /* Builtin functions */ double sqrt(doublereal); /* Local variables */ static real b, c__, w, del, tau, delsq; /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Oak Ridge National Lab, Argonne National Lab, Courant Institute, NAG Ltd., and Rice University June 30, 1999 Purpose ======= This subroutine computes the square root of the I-th eigenvalue of a positive symmetric rank-one modification of a 2-by-2 diagonal matrix diag( D ) * diag( D ) + RHO * Z * transpose(Z) . The diagonal entries in the array D are assumed to satisfy 0 <= D(i) < D(j) for i < j . We also assume RHO > 0 and that the Euclidean norm of the vector Z is one. Arguments ========= I (input) INTEGER The index of the eigenvalue to be computed. I = 1 or I = 2. D (input) REAL array, dimension ( 2 ) The original eigenvalues. We assume 0 <= D(1) < D(2). Z (input) REAL array, dimension ( 2 ) The components of the updating vector. DELTA (output) REAL array, dimension ( 2 ) Contains (D(j) - lambda_I) in its j-th component. The vector DELTA contains the information necessary to construct the eigenvectors. RHO (input) REAL The scalar in the symmetric updating formula. DSIGMA (output) REAL The computed lambda_I, the I-th updated eigenvalue. WORK (workspace) REAL array, dimension ( 2 ) WORK contains (D(j) + sigma_I) in its j-th component. Further Details =============== Based on contributions by Ren-Cang Li, Computer Science Division, University of California at Berkeley, USA ===================================================================== */ /* Parameter adjustments */ --work; --delta; --z__; --d__; /* Function Body */ del = d__[2] - d__[1]; delsq = del * (d__[2] + d__[1]); if (*i__ == 1) { w = *rho * 4.f * (z__[2] * z__[2] / (d__[1] + d__[2] * 3.f) - z__[1] * z__[1] / (d__[1] * 3.f + d__[2])) / del + 1.f; if (w > 0.f) { b = delsq + *rho * (z__[1] * z__[1] + z__[2] * z__[2]); c__ = *rho * z__[1] * z__[1] * delsq; /* B > ZERO, always The following TAU is DSIGMA * DSIGMA - D( 1 ) * D( 1 ) */ tau = c__ * 2.f / (b + sqrt((r__1 = b * b - c__ * 4.f, dabs(r__1)) )); /* The following TAU is DSIGMA - D( 1 ) */ tau /= d__[1] + sqrt(d__[1] * d__[1] + tau); *dsigma = d__[1] + tau; delta[1] = -tau; delta[2] = del - tau; work[1] = d__[1] * 2.f + tau; work[2] = d__[1] + tau + d__[2]; /* DELTA( 1 ) = -Z( 1 ) / TAU DELTA( 2 ) = Z( 2 ) / ( DEL-TAU ) */ } else { b = -delsq + *rho * (z__[1] * z__[1] + z__[2] * z__[2]); c__ = *rho * z__[2] * z__[2] * delsq; /* The following TAU is DSIGMA * DSIGMA - D( 2 ) * D( 2 ) */ if (b > 0.f) { tau = c__ * -2.f / (b + sqrt(b * b + c__ * 4.f)); } else { tau = (b - sqrt(b * b + c__ * 4.f)) / 2.f; } /* The following TAU is DSIGMA - D( 2 ) */ tau /= d__[2] + sqrt((r__1 = d__[2] * d__[2] + tau, dabs(r__1))); *dsigma = d__[2] + tau; delta[1] = -(del + tau); delta[2] = -tau; work[1] = d__[1] + tau + d__[2]; work[2] = d__[2] * 2.f + tau; /* DELTA( 1 ) = -Z( 1 ) / ( DEL+TAU ) DELTA( 2 ) = -Z( 2 ) / TAU */ } /* TEMP = SQRT( DELTA( 1 )*DELTA( 1 )+DELTA( 2 )*DELTA( 2 ) ) DELTA( 1 ) = DELTA( 1 ) / TEMP DELTA( 2 ) = DELTA( 2 ) / TEMP */ } else { /* Now I=2 */ b = -delsq + *rho * (z__[1] * z__[1] + z__[2] * z__[2]); c__ = *rho * z__[2] * z__[2] * delsq; /* The following TAU is DSIGMA * DSIGMA - D( 2 ) * D( 2 ) */ if (b > 0.f) { tau = (b + sqrt(b * b + c__ * 4.f)) / 2.f; } else { tau = c__ * 2.f / (-b + sqrt(b * b + c__ * 4.f)); } /* The following TAU is DSIGMA - D( 2 ) */ tau /= d__[2] + sqrt(d__[2] * d__[2] + tau); *dsigma = d__[2] + tau; delta[1] = -(del + tau); delta[2] = -tau; work[1] = d__[1] + tau + d__[2]; work[2] = d__[2] * 2.f + tau; /* DELTA( 1 ) = -Z( 1 ) / ( DEL+TAU ) DELTA( 2 ) = -Z( 2 ) / TAU TEMP = SQRT( DELTA( 1 )*DELTA( 1 )+DELTA( 2 )*DELTA( 2 ) ) DELTA( 1 ) = DELTA( 1 ) / TEMP DELTA( 2 ) = DELTA( 2 ) / TEMP */ } return 0; /* End of SLASD5 */ } /* slasd5_ */ /* Subroutine */ int slasd6_(integer *icompq, integer *nl, integer *nr, integer *sqre, real *d__, real *vf, real *vl, real *alpha, real *beta, integer *idxq, integer *perm, integer *givptr, integer *givcol, integer *ldgcol, real *givnum, integer *ldgnum, real *poles, real * difl, real *difr, real *z__, integer *k, real *c__, real *s, real * work, integer *iwork, integer *info) { /* System generated locals */ integer givcol_dim1, givcol_offset, givnum_dim1, givnum_offset, poles_dim1, poles_offset, i__1; real r__1, r__2; /* Local variables */ static integer i__, m, n, n1, n2, iw, idx, idxc, idxp, ivfw, ivlw; extern /* Subroutine */ int scopy_(integer *, real *, integer *, real *, integer *), slasd7_(integer *, integer *, integer *, integer *, integer *, real *, real *, real *, real *, real *, real *, real *, real *, real *, real *, integer *, integer *, integer *, integer *, integer *, integer *, integer *, real *, integer *, real *, real *, integer *), slasd8_(integer *, integer *, real *, real *, real *, real *, real *, real *, integer *, real *, real *, integer *); static integer isigma; extern /* Subroutine */ int xerbla_(char *, integer *), slascl_( char *, integer *, integer *, real *, real *, integer *, integer * , real *, integer *, integer *), slamrg_(integer *, integer *, real *, integer *, integer *, integer *); static real orgnrm; /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= SLASD6 computes the SVD of an updated upper bidiagonal matrix B obtained by merging two smaller ones by appending a row. This routine is used only for the problem which requires all singular values and optionally singular vector matrices in factored form. B is an N-by-M matrix with N = NL + NR + 1 and M = N + SQRE. A related subroutine, SLASD1, handles the case in which all singular values and singular vectors of the bidiagonal matrix are desired. SLASD6 computes the SVD as follows: ( D1(in) 0 0 0 ) B = U(in) * ( Z1' a Z2' b ) * VT(in) ( 0 0 D2(in) 0 ) = U(out) * ( D(out) 0) * VT(out) where Z' = (Z1' a Z2' b) = u' VT', and u is a vector of dimension M with ALPHA and BETA in the NL+1 and NL+2 th entries and zeros elsewhere; and the entry b is empty if SQRE = 0. The singular values of B can be computed using D1, D2, the first components of all the right singular vectors of the lower block, and the last components of all the right singular vectors of the upper block. These components are stored and updated in VF and VL, respectively, in SLASD6. Hence U and VT are not explicitly referenced. The singular values are stored in D. The algorithm consists of two stages: The first stage consists of deflating the size of the problem when there are multiple singular values or if there is a zero in the Z vector. For each such occurence the dimension of the secular equation problem is reduced by one. This stage is performed by the routine SLASD7. The second stage consists of calculating the updated singular values. This is done by finding the roots of the secular equation via the routine SLASD4 (as called by SLASD8). This routine also updates VF and VL and computes the distances between the updated singular values and the old singular values. SLASD6 is called from SLASDA. Arguments ========= ICOMPQ (input) INTEGER Specifies whether singular vectors are to be computed in factored form: = 0: Compute singular values only. = 1: Compute singular vectors in factored form as well. NL (input) INTEGER The row dimension of the upper block. NL >= 1. NR (input) INTEGER The row dimension of the lower block. NR >= 1. SQRE (input) INTEGER = 0: the lower block is an NR-by-NR square matrix. = 1: the lower block is an NR-by-(NR+1) rectangular matrix. The bidiagonal matrix has row dimension N = NL + NR + 1, and column dimension M = N + SQRE. D (input/output) REAL array, dimension ( NL+NR+1 ). On entry D(1:NL,1:NL) contains the singular values of the upper block, and D(NL+2:N) contains the singular values of the lower block. On exit D(1:N) contains the singular values of the modified matrix. VF (input/output) REAL array, dimension ( M ) On entry, VF(1:NL+1) contains the first components of all right singular vectors of the upper block; and VF(NL+2:M) contains the first components of all right singular vectors of the lower block. On exit, VF contains the first components of all right singular vectors of the bidiagonal matrix. VL (input/output) REAL array, dimension ( M ) On entry, VL(1:NL+1) contains the last components of all right singular vectors of the upper block; and VL(NL+2:M) contains the last components of all right singular vectors of the lower block. On exit, VL contains the last components of all right singular vectors of the bidiagonal matrix. ALPHA (input) REAL Contains the diagonal element associated with the added row. BETA (input) REAL Contains the off-diagonal element associated with the added row. IDXQ (output) INTEGER array, dimension ( N ) This contains the permutation which will reintegrate the subproblem just solved back into sorted order, i.e. D( IDXQ( I = 1, N ) ) will be in ascending order. PERM (output) INTEGER array, dimension ( N ) The permutations (from deflation and sorting) to be applied to each block. Not referenced if ICOMPQ = 0. GIVPTR (output) INTEGER The number of Givens rotations which took place in this subproblem. Not referenced if ICOMPQ = 0. GIVCOL (output) INTEGER array, dimension ( LDGCOL, 2 ) Each pair of numbers indicates a pair of columns to take place in a Givens rotation. Not referenced if ICOMPQ = 0. LDGCOL (input) INTEGER leading dimension of GIVCOL, must be at least N. GIVNUM (output) REAL array, dimension ( LDGNUM, 2 ) Each number indicates the C or S value to be used in the corresponding Givens rotation. Not referenced if ICOMPQ = 0. LDGNUM (input) INTEGER The leading dimension of GIVNUM and POLES, must be at least N. POLES (output) REAL array, dimension ( LDGNUM, 2 ) On exit, POLES(1,*) is an array containing the new singular values obtained from solving the secular equation, and POLES(2,*) is an array containing the poles in the secular equation. Not referenced if ICOMPQ = 0. DIFL (output) REAL array, dimension ( N ) On exit, DIFL(I) is the distance between I-th updated (undeflated) singular value and the I-th (undeflated) old singular value. DIFR (output) REAL array, dimension ( LDGNUM, 2 ) if ICOMPQ = 1 and dimension ( N ) if ICOMPQ = 0. On exit, DIFR(I, 1) is the distance between I-th updated (undeflated) singular value and the I+1-th (undeflated) old singular value. If ICOMPQ = 1, DIFR(1:K,2) is an array containing the normalizing factors for the right singular vector matrix. See SLASD8 for details on DIFL and DIFR. Z (output) REAL array, dimension ( M ) The first elements of this array contain the components of the deflation-adjusted updating row vector. K (output) INTEGER Contains the dimension of the non-deflated matrix, This is the order of the related secular equation. 1 <= K <=N. C (output) REAL C contains garbage if SQRE =0 and the C-value of a Givens rotation related to the right null space if SQRE = 1. S (output) REAL S contains garbage if SQRE =0 and the S-value of a Givens rotation related to the right null space if SQRE = 1. WORK (workspace) REAL array, dimension ( 4 * M ) IWORK (workspace) INTEGER array, dimension ( 3 * N ) INFO (output) INTEGER = 0: successful exit. < 0: if INFO = -i, the i-th argument had an illegal value. > 0: if INFO = 1, an singular value did not converge Further Details =============== Based on contributions by Ming Gu and Huan Ren, Computer Science Division, University of California at Berkeley, USA ===================================================================== Test the input parameters. */ /* Parameter adjustments */ --d__; --vf; --vl; --idxq; --perm; givcol_dim1 = *ldgcol; givcol_offset = 1 + givcol_dim1; givcol -= givcol_offset; poles_dim1 = *ldgnum; poles_offset = 1 + poles_dim1; poles -= poles_offset; givnum_dim1 = *ldgnum; givnum_offset = 1 + givnum_dim1; givnum -= givnum_offset; --difl; --difr; --z__; --work; --iwork; /* Function Body */ *info = 0; n = *nl + *nr + 1; m = n + *sqre; if ((*icompq < 0) || (*icompq > 1)) { *info = -1; } else if (*nl < 1) { *info = -2; } else if (*nr < 1) { *info = -3; } else if ((*sqre < 0) || (*sqre > 1)) { *info = -4; } else if (*ldgcol < n) { *info = -14; } else if (*ldgnum < n) { *info = -16; } if (*info != 0) { i__1 = -(*info); xerbla_("SLASD6", &i__1); return 0; } /* The following values are for bookkeeping purposes only. They are integer pointers which indicate the portion of the workspace used by a particular array in SLASD7 and SLASD8. */ isigma = 1; iw = isigma + n; ivfw = iw + m; ivlw = ivfw + m; idx = 1; idxc = idx + n; idxp = idxc + n; /* Scale. Computing MAX */ r__1 = dabs(*alpha), r__2 = dabs(*beta); orgnrm = dmax(r__1,r__2); d__[*nl + 1] = 0.f; i__1 = n; for (i__ = 1; i__ <= i__1; ++i__) { if ((r__1 = d__[i__], dabs(r__1)) > orgnrm) { orgnrm = (r__1 = d__[i__], dabs(r__1)); } /* L10: */ } slascl_("G", &c__0, &c__0, &orgnrm, &c_b1011, &n, &c__1, &d__[1], &n, info); *alpha /= orgnrm; *beta /= orgnrm; /* Sort and Deflate singular values. */ slasd7_(icompq, nl, nr, sqre, k, &d__[1], &z__[1], &work[iw], &vf[1], & work[ivfw], &vl[1], &work[ivlw], alpha, beta, &work[isigma], & iwork[idx], &iwork[idxp], &idxq[1], &perm[1], givptr, &givcol[ givcol_offset], ldgcol, &givnum[givnum_offset], ldgnum, c__, s, info); /* Solve Secular Equation, compute DIFL, DIFR, and update VF, VL. */ slasd8_(icompq, k, &d__[1], &z__[1], &vf[1], &vl[1], &difl[1], &difr[1], ldgnum, &work[isigma], &work[iw], info); /* Save the poles if ICOMPQ = 1. */ if (*icompq == 1) { scopy_(k, &d__[1], &c__1, &poles[poles_dim1 + 1], &c__1); scopy_(k, &work[isigma], &c__1, &poles[((poles_dim1) << (1)) + 1], & c__1); } /* Unscale. */ slascl_("G", &c__0, &c__0, &c_b1011, &orgnrm, &n, &c__1, &d__[1], &n, info); /* Prepare the IDXQ sorting permutation. */ n1 = *k; n2 = n - *k; slamrg_(&n1, &n2, &d__[1], &c__1, &c_n1, &idxq[1]); return 0; /* End of SLASD6 */ } /* slasd6_ */ /* Subroutine */ int slasd7_(integer *icompq, integer *nl, integer *nr, integer *sqre, integer *k, real *d__, real *z__, real *zw, real *vf, real *vfw, real *vl, real *vlw, real *alpha, real *beta, real *dsigma, integer *idx, integer *idxp, integer *idxq, integer *perm, integer * givptr, integer *givcol, integer *ldgcol, real *givnum, integer * ldgnum, real *c__, real *s, integer *info) { /* System generated locals */ integer givcol_dim1, givcol_offset, givnum_dim1, givnum_offset, i__1; real r__1, r__2; /* Local variables */ static integer i__, j, m, n, k2; static real z1; static integer jp; static real eps, tau, tol; static integer nlp1, nlp2, idxi, idxj; extern /* Subroutine */ int srot_(integer *, real *, integer *, real *, integer *, real *, real *); static integer idxjp, jprev; extern /* Subroutine */ int scopy_(integer *, real *, integer *, real *, integer *); extern doublereal slapy2_(real *, real *), slamch_(char *); extern /* Subroutine */ int xerbla_(char *, integer *), slamrg_( integer *, integer *, real *, integer *, integer *, integer *); static real hlftol; /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Oak Ridge National Lab, Argonne National Lab, Courant Institute, NAG Ltd., and Rice University June 30, 1999 Purpose ======= SLASD7 merges the two sets of singular values together into a single sorted set. Then it tries to deflate the size of the problem. There are two ways in which deflation can occur: when two or more singular values are close together or if there is a tiny entry in the Z vector. For each such occurrence the order of the related secular equation problem is reduced by one. SLASD7 is called from SLASD6. Arguments ========= ICOMPQ (input) INTEGER Specifies whether singular vectors are to be computed in compact form, as follows: = 0: Compute singular values only. = 1: Compute singular vectors of upper bidiagonal matrix in compact form. NL (input) INTEGER The row dimension of the upper block. NL >= 1. NR (input) INTEGER The row dimension of the lower block. NR >= 1. SQRE (input) INTEGER = 0: the lower block is an NR-by-NR square matrix. = 1: the lower block is an NR-by-(NR+1) rectangular matrix. The bidiagonal matrix has N = NL + NR + 1 rows and M = N + SQRE >= N columns. K (output) INTEGER Contains the dimension of the non-deflated matrix, this is the order of the related secular equation. 1 <= K <=N. D (input/output) REAL array, dimension ( N ) On entry D contains the singular values of the two submatrices to be combined. On exit D contains the trailing (N-K) updated singular values (those which were deflated) sorted into increasing order. Z (output) REAL array, dimension ( M ) On exit Z contains the updating row vector in the secular equation. ZW (workspace) REAL array, dimension ( M ) Workspace for Z. VF (input/output) REAL array, dimension ( M ) On entry, VF(1:NL+1) contains the first components of all right singular vectors of the upper block; and VF(NL+2:M) contains the first components of all right singular vectors of the lower block. On exit, VF contains the first components of all right singular vectors of the bidiagonal matrix. VFW (workspace) REAL array, dimension ( M ) Workspace for VF. VL (input/output) REAL array, dimension ( M ) On entry, VL(1:NL+1) contains the last components of all right singular vectors of the upper block; and VL(NL+2:M) contains the last components of all right singular vectors of the lower block. On exit, VL contains the last components of all right singular vectors of the bidiagonal matrix. VLW (workspace) REAL array, dimension ( M ) Workspace for VL. ALPHA (input) REAL Contains the diagonal element associated with the added row. BETA (input) REAL Contains the off-diagonal element associated with the added row. DSIGMA (output) REAL array, dimension ( N ) Contains a copy of the diagonal elements (K-1 singular values and one zero) in the secular equation. IDX (workspace) INTEGER array, dimension ( N ) This will contain the permutation used to sort the contents of D into ascending order. IDXP (workspace) INTEGER array, dimension ( N ) This will contain the permutation used to place deflated values of D at the end of the array. On output IDXP(2:K) points to the nondeflated D-values and IDXP(K+1:N) points to the deflated singular values. IDXQ (input) INTEGER array, dimension ( N ) This contains the permutation which separately sorts the two sub-problems in D into ascending order. Note that entries in the first half of this permutation must first be moved one position backward; and entries in the second half must first have NL+1 added to their values. PERM (output) INTEGER array, dimension ( N ) The permutations (from deflation and sorting) to be applied to each singular block. Not referenced if ICOMPQ = 0. GIVPTR (output) INTEGER The number of Givens rotations which took place in this subproblem. Not referenced if ICOMPQ = 0. GIVCOL (output) INTEGER array, dimension ( LDGCOL, 2 ) Each pair of numbers indicates a pair of columns to take place in a Givens rotation. Not referenced if ICOMPQ = 0. LDGCOL (input) INTEGER The leading dimension of GIVCOL, must be at least N. GIVNUM (output) REAL array, dimension ( LDGNUM, 2 ) Each number indicates the C or S value to be used in the corresponding Givens rotation. Not referenced if ICOMPQ = 0. LDGNUM (input) INTEGER The leading dimension of GIVNUM, must be at least N. C (output) REAL C contains garbage if SQRE =0 and the C-value of a Givens rotation related to the right null space if SQRE = 1. S (output) REAL S contains garbage if SQRE =0 and the S-value of a Givens rotation related to the right null space if SQRE = 1. INFO (output) INTEGER = 0: successful exit. < 0: if INFO = -i, the i-th argument had an illegal value. Further Details =============== Based on contributions by Ming Gu and Huan Ren, Computer Science Division, University of California at Berkeley, USA ===================================================================== Test the input parameters. */ /* Parameter adjustments */ --d__; --z__; --zw; --vf; --vfw; --vl; --vlw; --dsigma; --idx; --idxp; --idxq; --perm; givcol_dim1 = *ldgcol; givcol_offset = 1 + givcol_dim1; givcol -= givcol_offset; givnum_dim1 = *ldgnum; givnum_offset = 1 + givnum_dim1; givnum -= givnum_offset; /* Function Body */ *info = 0; n = *nl + *nr + 1; m = n + *sqre; if ((*icompq < 0) || (*icompq > 1)) { *info = -1; } else if (*nl < 1) { *info = -2; } else if (*nr < 1) { *info = -3; } else if ((*sqre < 0) || (*sqre > 1)) { *info = -4; } else if (*ldgcol < n) { *info = -22; } else if (*ldgnum < n) { *info = -24; } if (*info != 0) { i__1 = -(*info); xerbla_("SLASD7", &i__1); return 0; } nlp1 = *nl + 1; nlp2 = *nl + 2; if (*icompq == 1) { *givptr = 0; } /* Generate the first part of the vector Z and move the singular values in the first part of D one position backward. */ z1 = *alpha * vl[nlp1]; vl[nlp1] = 0.f; tau = vf[nlp1]; for (i__ = *nl; i__ >= 1; --i__) { z__[i__ + 1] = *alpha * vl[i__]; vl[i__] = 0.f; vf[i__ + 1] = vf[i__]; d__[i__ + 1] = d__[i__]; idxq[i__ + 1] = idxq[i__] + 1; /* L10: */ } vf[1] = tau; /* Generate the second part of the vector Z. */ i__1 = m; for (i__ = nlp2; i__ <= i__1; ++i__) { z__[i__] = *beta * vf[i__]; vf[i__] = 0.f; /* L20: */ } /* Sort the singular values into increasing order */ i__1 = n; for (i__ = nlp2; i__ <= i__1; ++i__) { idxq[i__] += nlp1; /* L30: */ } /* DSIGMA, IDXC, IDXC, and ZW are used as storage space. */ i__1 = n; for (i__ = 2; i__ <= i__1; ++i__) { dsigma[i__] = d__[idxq[i__]]; zw[i__] = z__[idxq[i__]]; vfw[i__] = vf[idxq[i__]]; vlw[i__] = vl[idxq[i__]]; /* L40: */ } slamrg_(nl, nr, &dsigma[2], &c__1, &c__1, &idx[2]); i__1 = n; for (i__ = 2; i__ <= i__1; ++i__) { idxi = idx[i__] + 1; d__[i__] = dsigma[idxi]; z__[i__] = zw[idxi]; vf[i__] = vfw[idxi]; vl[i__] = vlw[idxi]; /* L50: */ } /* Calculate the allowable deflation tolerence */ eps = slamch_("Epsilon"); /* Computing MAX */ r__1 = dabs(*alpha), r__2 = dabs(*beta); tol = dmax(r__1,r__2); /* Computing MAX */ r__2 = (r__1 = d__[n], dabs(r__1)); tol = eps * 64.f * dmax(r__2,tol); /* There are 2 kinds of deflation -- first a value in the z-vector is small, second two (or more) singular values are very close together (their difference is small). If the value in the z-vector is small, we simply permute the array so that the corresponding singular value is moved to the end. If two values in the D-vector are close, we perform a two-sided rotation designed to make one of the corresponding z-vector entries zero, and then permute the array so that the deflated singular value is moved to the end. If there are multiple singular values then the problem deflates. Here the number of equal singular values are found. As each equal singular value is found, an elementary reflector is computed to rotate the corresponding singular subspace so that the corresponding components of Z are zero in this new basis. */ *k = 1; k2 = n + 1; i__1 = n; for (j = 2; j <= i__1; ++j) { if ((r__1 = z__[j], dabs(r__1)) <= tol) { /* Deflate due to small z component. */ --k2; idxp[k2] = j; if (j == n) { goto L100; } } else { jprev = j; goto L70; } /* L60: */ } L70: j = jprev; L80: ++j; if (j > n) { goto L90; } if ((r__1 = z__[j], dabs(r__1)) <= tol) { /* Deflate due to small z component. */ --k2; idxp[k2] = j; } else { /* Check if singular values are close enough to allow deflation. */ if ((r__1 = d__[j] - d__[jprev], dabs(r__1)) <= tol) { /* Deflation is possible. */ *s = z__[jprev]; *c__ = z__[j]; /* Find sqrt(a**2+b**2) without overflow or destructive underflow. */ tau = slapy2_(c__, s); z__[j] = tau; z__[jprev] = 0.f; *c__ /= tau; *s = -(*s) / tau; /* Record the appropriate Givens rotation */ if (*icompq == 1) { ++(*givptr); idxjp = idxq[idx[jprev] + 1]; idxj = idxq[idx[j] + 1]; if (idxjp <= nlp1) { --idxjp; } if (idxj <= nlp1) { --idxj; } givcol[*givptr + ((givcol_dim1) << (1))] = idxjp; givcol[*givptr + givcol_dim1] = idxj; givnum[*givptr + ((givnum_dim1) << (1))] = *c__; givnum[*givptr + givnum_dim1] = *s; } srot_(&c__1, &vf[jprev], &c__1, &vf[j], &c__1, c__, s); srot_(&c__1, &vl[jprev], &c__1, &vl[j], &c__1, c__, s); --k2; idxp[k2] = jprev; jprev = j; } else { ++(*k); zw[*k] = z__[jprev]; dsigma[*k] = d__[jprev]; idxp[*k] = jprev; jprev = j; } } goto L80; L90: /* Record the last singular value. */ ++(*k); zw[*k] = z__[jprev]; dsigma[*k] = d__[jprev]; idxp[*k] = jprev; L100: /* Sort the singular values into DSIGMA. The singular values which were not deflated go into the first K slots of DSIGMA, except that DSIGMA(1) is treated separately. */ i__1 = n; for (j = 2; j <= i__1; ++j) { jp = idxp[j]; dsigma[j] = d__[jp]; vfw[j] = vf[jp]; vlw[j] = vl[jp]; /* L110: */ } if (*icompq == 1) { i__1 = n; for (j = 2; j <= i__1; ++j) { jp = idxp[j]; perm[j] = idxq[idx[jp] + 1]; if (perm[j] <= nlp1) { --perm[j]; } /* L120: */ } } /* The deflated singular values go back into the last N - K slots of D. */ i__1 = n - *k; scopy_(&i__1, &dsigma[*k + 1], &c__1, &d__[*k + 1], &c__1); /* Determine DSIGMA(1), DSIGMA(2), Z(1), VF(1), VL(1), VF(M), and VL(M). */ dsigma[1] = 0.f; hlftol = tol / 2.f; if (dabs(dsigma[2]) <= hlftol) { dsigma[2] = hlftol; } if (m > n) { z__[1] = slapy2_(&z1, &z__[m]); if (z__[1] <= tol) { *c__ = 1.f; *s = 0.f; z__[1] = tol; } else { *c__ = z1 / z__[1]; *s = -z__[m] / z__[1]; } srot_(&c__1, &vf[m], &c__1, &vf[1], &c__1, c__, s); srot_(&c__1, &vl[m], &c__1, &vl[1], &c__1, c__, s); } else { if (dabs(z1) <= tol) { z__[1] = tol; } else { z__[1] = z1; } } /* Restore Z, VF, and VL. */ i__1 = *k - 1; scopy_(&i__1, &zw[2], &c__1, &z__[2], &c__1); i__1 = n - 1; scopy_(&i__1, &vfw[2], &c__1, &vf[2], &c__1); i__1 = n - 1; scopy_(&i__1, &vlw[2], &c__1, &vl[2], &c__1); return 0; /* End of SLASD7 */ } /* slasd7_ */ /* Subroutine */ int slasd8_(integer *icompq, integer *k, real *d__, real * z__, real *vf, real *vl, real *difl, real *difr, integer *lddifr, real *dsigma, real *work, integer *info) { /* System generated locals */ integer difr_dim1, difr_offset, i__1, i__2; real r__1, r__2; /* Builtin functions */ double sqrt(doublereal), r_sign(real *, real *); /* Local variables */ static integer i__, j; static real dj, rho; static integer iwk1, iwk2, iwk3; static real temp; extern doublereal sdot_(integer *, real *, integer *, real *, integer *); static integer iwk2i, iwk3i; extern doublereal snrm2_(integer *, real *, integer *); static real diflj, difrj, dsigj; extern /* Subroutine */ int scopy_(integer *, real *, integer *, real *, integer *); extern doublereal slamc3_(real *, real *); extern /* Subroutine */ int slasd4_(integer *, integer *, real *, real *, real *, real *, real *, real *, integer *), xerbla_(char *, integer *); static real dsigjp; extern /* Subroutine */ int slascl_(char *, integer *, integer *, real *, real *, integer *, integer *, real *, integer *, integer *), slaset_(char *, integer *, integer *, real *, real *, real *, integer *); /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Oak Ridge National Lab, Argonne National Lab, Courant Institute, NAG Ltd., and Rice University June 30, 1999 Purpose ======= SLASD8 finds the square roots of the roots of the secular equation, as defined by the values in DSIGMA and Z. It makes the appropriate calls to SLASD4, and stores, for each element in D, the distance to its two nearest poles (elements in DSIGMA). It also updates the arrays VF and VL, the first and last components of all the right singular vectors of the original bidiagonal matrix. SLASD8 is called from SLASD6. Arguments ========= ICOMPQ (input) INTEGER Specifies whether singular vectors are to be computed in factored form in the calling routine: = 0: Compute singular values only. = 1: Compute singular vectors in factored form as well. K (input) INTEGER The number of terms in the rational function to be solved by SLASD4. K >= 1. D (output) REAL array, dimension ( K ) On output, D contains the updated singular values. Z (input) REAL array, dimension ( K ) The first K elements of this array contain the components of the deflation-adjusted updating row vector. VF (input/output) REAL array, dimension ( K ) On entry, VF contains information passed through DBEDE8. On exit, VF contains the first K components of the first components of all right singular vectors of the bidiagonal matrix. VL (input/output) REAL array, dimension ( K ) On entry, VL contains information passed through DBEDE8. On exit, VL contains the first K components of the last components of all right singular vectors of the bidiagonal matrix. DIFL (output) REAL array, dimension ( K ) On exit, DIFL(I) = D(I) - DSIGMA(I). DIFR (output) REAL array, dimension ( LDDIFR, 2 ) if ICOMPQ = 1 and dimension ( K ) if ICOMPQ = 0. On exit, DIFR(I,1) = D(I) - DSIGMA(I+1), DIFR(K,1) is not defined and will not be referenced. If ICOMPQ = 1, DIFR(1:K,2) is an array containing the normalizing factors for the right singular vector matrix. LDDIFR (input) INTEGER The leading dimension of DIFR, must be at least K. DSIGMA (input) REAL array, dimension ( K ) The first K elements of this array contain the old roots of the deflated updating problem. These are the poles of the secular equation. WORK (workspace) REAL array, dimension at least 3 * K INFO (output) INTEGER = 0: successful exit. < 0: if INFO = -i, the i-th argument had an illegal value. > 0: if INFO = 1, an singular value did not converge Further Details =============== Based on contributions by Ming Gu and Huan Ren, Computer Science Division, University of California at Berkeley, USA ===================================================================== Test the input parameters. */ /* Parameter adjustments */ --d__; --z__; --vf; --vl; --difl; difr_dim1 = *lddifr; difr_offset = 1 + difr_dim1; difr -= difr_offset; --dsigma; --work; /* Function Body */ *info = 0; if ((*icompq < 0) || (*icompq > 1)) { *info = -1; } else if (*k < 1) { *info = -2; } else if (*lddifr < *k) { *info = -9; } if (*info != 0) { i__1 = -(*info); xerbla_("SLASD8", &i__1); return 0; } /* Quick return if possible */ if (*k == 1) { d__[1] = dabs(z__[1]); difl[1] = d__[1]; if (*icompq == 1) { difl[2] = 1.f; difr[((difr_dim1) << (1)) + 1] = 1.f; } return 0; } /* Modify values DSIGMA(i) to make sure all DSIGMA(i)-DSIGMA(j) can be computed with high relative accuracy (barring over/underflow). This is a problem on machines without a guard digit in add/subtract (Cray XMP, Cray YMP, Cray C 90 and Cray 2). The following code replaces DSIGMA(I) by 2*DSIGMA(I)-DSIGMA(I), which on any of these machines zeros out the bottommost bit of DSIGMA(I) if it is 1; this makes the subsequent subtractions DSIGMA(I)-DSIGMA(J) unproblematic when cancellation occurs. On binary machines with a guard digit (almost all machines) it does not change DSIGMA(I) at all. On hexadecimal and decimal machines with a guard digit, it slightly changes the bottommost bits of DSIGMA(I). It does not account for hexadecimal or decimal machines without guard digits (we know of none). We use a subroutine call to compute 2*DLAMBDA(I) to prevent optimizing compilers from eliminating this code. */ i__1 = *k; for (i__ = 1; i__ <= i__1; ++i__) { dsigma[i__] = slamc3_(&dsigma[i__], &dsigma[i__]) - dsigma[i__]; /* L10: */ } /* Book keeping. */ iwk1 = 1; iwk2 = iwk1 + *k; iwk3 = iwk2 + *k; iwk2i = iwk2 - 1; iwk3i = iwk3 - 1; /* Normalize Z. */ rho = snrm2_(k, &z__[1], &c__1); slascl_("G", &c__0, &c__0, &rho, &c_b1011, k, &c__1, &z__[1], k, info); rho *= rho; /* Initialize WORK(IWK3). */ slaset_("A", k, &c__1, &c_b1011, &c_b1011, &work[iwk3], k); /* Compute the updated singular values, the arrays DIFL, DIFR, and the updated Z. */ i__1 = *k; for (j = 1; j <= i__1; ++j) { slasd4_(k, &j, &dsigma[1], &z__[1], &work[iwk1], &rho, &d__[j], &work[ iwk2], info); /* If the root finder fails, the computation is terminated. */ if (*info != 0) { return 0; } work[iwk3i + j] = work[iwk3i + j] * work[j] * work[iwk2i + j]; difl[j] = -work[j]; difr[j + difr_dim1] = -work[j + 1]; i__2 = j - 1; for (i__ = 1; i__ <= i__2; ++i__) { work[iwk3i + i__] = work[iwk3i + i__] * work[i__] * work[iwk2i + i__] / (dsigma[i__] - dsigma[j]) / (dsigma[i__] + dsigma[ j]); /* L20: */ } i__2 = *k; for (i__ = j + 1; i__ <= i__2; ++i__) { work[iwk3i + i__] = work[iwk3i + i__] * work[i__] * work[iwk2i + i__] / (dsigma[i__] - dsigma[j]) / (dsigma[i__] + dsigma[ j]); /* L30: */ } /* L40: */ } /* Compute updated Z. */ i__1 = *k; for (i__ = 1; i__ <= i__1; ++i__) { r__2 = sqrt((r__1 = work[iwk3i + i__], dabs(r__1))); z__[i__] = r_sign(&r__2, &z__[i__]); /* L50: */ } /* Update VF and VL. */ i__1 = *k; for (j = 1; j <= i__1; ++j) { diflj = difl[j]; dj = d__[j]; dsigj = -dsigma[j]; if (j < *k) { difrj = -difr[j + difr_dim1]; dsigjp = -dsigma[j + 1]; } work[j] = -z__[j] / diflj / (dsigma[j] + dj); i__2 = j - 1; for (i__ = 1; i__ <= i__2; ++i__) { work[i__] = z__[i__] / (slamc3_(&dsigma[i__], &dsigj) - diflj) / ( dsigma[i__] + dj); /* L60: */ } i__2 = *k; for (i__ = j + 1; i__ <= i__2; ++i__) { work[i__] = z__[i__] / (slamc3_(&dsigma[i__], &dsigjp) + difrj) / (dsigma[i__] + dj); /* L70: */ } temp = snrm2_(k, &work[1], &c__1); work[iwk2i + j] = sdot_(k, &work[1], &c__1, &vf[1], &c__1) / temp; work[iwk3i + j] = sdot_(k, &work[1], &c__1, &vl[1], &c__1) / temp; if (*icompq == 1) { difr[j + ((difr_dim1) << (1))] = temp; } /* L80: */ } scopy_(k, &work[iwk2], &c__1, &vf[1], &c__1); scopy_(k, &work[iwk3], &c__1, &vl[1], &c__1); return 0; /* End of SLASD8 */ } /* slasd8_ */ /* Subroutine */ int slasda_(integer *icompq, integer *smlsiz, integer *n, integer *sqre, real *d__, real *e, real *u, integer *ldu, real *vt, integer *k, real *difl, real *difr, real *z__, real *poles, integer * givptr, integer *givcol, integer *ldgcol, integer *perm, real *givnum, real *c__, real *s, real *work, integer *iwork, integer *info) { /* System generated locals */ integer givcol_dim1, givcol_offset, perm_dim1, perm_offset, difl_dim1, difl_offset, difr_dim1, difr_offset, givnum_dim1, givnum_offset, poles_dim1, poles_offset, u_dim1, u_offset, vt_dim1, vt_offset, z_dim1, z_offset, i__1, i__2; /* Builtin functions */ integer pow_ii(integer *, integer *); /* Local variables */ static integer i__, j, m, i1, ic, lf, nd, ll, nl, vf, nr, vl, im1, ncc, nlf, nrf, vfi, iwk, vli, lvl, nru, ndb1, nlp1, lvl2, nrp1; static real beta; static integer idxq, nlvl; static real alpha; static integer inode, ndiml, ndimr, idxqi, itemp, sqrei; extern /* Subroutine */ int scopy_(integer *, real *, integer *, real *, integer *), slasd6_(integer *, integer *, integer *, integer *, real *, real *, real *, real *, real *, integer *, integer *, integer *, integer *, integer *, real *, integer *, real *, real * , real *, real *, integer *, real *, real *, real *, integer *, integer *); static integer nwork1, nwork2; extern /* Subroutine */ int xerbla_(char *, integer *), slasdq_( char *, integer *, integer *, integer *, integer *, integer *, real *, real *, real *, integer *, real *, integer *, real *, integer *, real *, integer *), slasdt_(integer *, integer *, integer *, integer *, integer *, integer *, integer *), slaset_(char *, integer *, integer *, real *, real *, real *, integer *); static integer smlszp; /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University October 31, 1999 Purpose ======= Using a divide and conquer approach, SLASDA computes the singular value decomposition (SVD) of a real upper bidiagonal N-by-M matrix B with diagonal D and offdiagonal E, where M = N + SQRE. The algorithm computes the singular values in the SVD B = U * S * VT. The orthogonal matrices U and VT are optionally computed in compact form. A related subroutine, SLASD0, computes the singular values and the singular vectors in explicit form. Arguments ========= ICOMPQ (input) INTEGER Specifies whether singular vectors are to be computed in compact form, as follows = 0: Compute singular values only. = 1: Compute singular vectors of upper bidiagonal matrix in compact form. SMLSIZ (input) INTEGER The maximum size of the subproblems at the bottom of the computation tree. N (input) INTEGER The row dimension of the upper bidiagonal matrix. This is also the dimension of the main diagonal array D. SQRE (input) INTEGER Specifies the column dimension of the bidiagonal matrix. = 0: The bidiagonal matrix has column dimension M = N; = 1: The bidiagonal matrix has column dimension M = N + 1. D (input/output) REAL array, dimension ( N ) On entry D contains the main diagonal of the bidiagonal matrix. On exit D, if INFO = 0, contains its singular values. E (input) REAL array, dimension ( M-1 ) Contains the subdiagonal entries of the bidiagonal matrix. On exit, E has been destroyed. U (output) REAL array, dimension ( LDU, SMLSIZ ) if ICOMPQ = 1, and not referenced if ICOMPQ = 0. If ICOMPQ = 1, on exit, U contains the left singular vector matrices of all subproblems at the bottom level. LDU (input) INTEGER, LDU = > N. The leading dimension of arrays U, VT, DIFL, DIFR, POLES, GIVNUM, and Z. VT (output) REAL array, dimension ( LDU, SMLSIZ+1 ) if ICOMPQ = 1, and not referenced if ICOMPQ = 0. If ICOMPQ = 1, on exit, VT' contains the right singular vector matrices of all subproblems at the bottom level. K (output) INTEGER array, dimension ( N ) if ICOMPQ = 1 and dimension 1 if ICOMPQ = 0. If ICOMPQ = 1, on exit, K(I) is the dimension of the I-th secular equation on the computation tree. DIFL (output) REAL array, dimension ( LDU, NLVL ), where NLVL = floor(log_2 (N/SMLSIZ))). DIFR (output) REAL array, dimension ( LDU, 2 * NLVL ) if ICOMPQ = 1 and dimension ( N ) if ICOMPQ = 0. If ICOMPQ = 1, on exit, DIFL(1:N, I) and DIFR(1:N, 2 * I - 1) record distances between singular values on the I-th level and singular values on the (I -1)-th level, and DIFR(1:N, 2 * I ) contains the normalizing factors for the right singular vector matrix. See SLASD8 for details. Z (output) REAL array, dimension ( LDU, NLVL ) if ICOMPQ = 1 and dimension ( N ) if ICOMPQ = 0. The first K elements of Z(1, I) contain the components of the deflation-adjusted updating row vector for subproblems on the I-th level. POLES (output) REAL array, dimension ( LDU, 2 * NLVL ) if ICOMPQ = 1, and not referenced if ICOMPQ = 0. If ICOMPQ = 1, on exit, POLES(1, 2*I - 1) and POLES(1, 2*I) contain the new and old singular values involved in the secular equations on the I-th level. GIVPTR (output) INTEGER array, dimension ( N ) if ICOMPQ = 1, and not referenced if ICOMPQ = 0. If ICOMPQ = 1, on exit, GIVPTR( I ) records the number of Givens rotations performed on the I-th problem on the computation tree. GIVCOL (output) INTEGER array, dimension ( LDGCOL, 2 * NLVL ) if ICOMPQ = 1, and not referenced if ICOMPQ = 0. If ICOMPQ = 1, on exit, for each I, GIVCOL(1, 2 *I - 1) and GIVCOL(1, 2 *I) record the locations of Givens rotations performed on the I-th level on the computation tree. LDGCOL (input) INTEGER, LDGCOL = > N. The leading dimension of arrays GIVCOL and PERM. PERM (output) INTEGER array, dimension ( LDGCOL, NLVL ) if ICOMPQ = 1, and not referenced if ICOMPQ = 0. If ICOMPQ = 1, on exit, PERM(1, I) records permutations done on the I-th level of the computation tree. GIVNUM (output) REAL array, dimension ( LDU, 2 * NLVL ) if ICOMPQ = 1, and not referenced if ICOMPQ = 0. If ICOMPQ = 1, on exit, for each I, GIVNUM(1, 2 *I - 1) and GIVNUM(1, 2 *I) record the C- and S- values of Givens rotations performed on the I-th level on the computation tree. C (output) REAL array, dimension ( N ) if ICOMPQ = 1, and dimension 1 if ICOMPQ = 0. If ICOMPQ = 1 and the I-th subproblem is not square, on exit, C( I ) contains the C-value of a Givens rotation related to the right null space of the I-th subproblem. S (output) REAL array, dimension ( N ) if ICOMPQ = 1, and dimension 1 if ICOMPQ = 0. If ICOMPQ = 1 and the I-th subproblem is not square, on exit, S( I ) contains the S-value of a Givens rotation related to the right null space of the I-th subproblem. WORK (workspace) REAL array, dimension (6 * N + (SMLSIZ + 1)*(SMLSIZ + 1)). IWORK (workspace) INTEGER array. Dimension must be at least (7 * N). INFO (output) INTEGER = 0: successful exit. < 0: if INFO = -i, the i-th argument had an illegal value. > 0: if INFO = 1, an singular value did not converge Further Details =============== Based on contributions by Ming Gu and Huan Ren, Computer Science Division, University of California at Berkeley, USA ===================================================================== Test the input parameters. */ /* Parameter adjustments */ --d__; --e; givnum_dim1 = *ldu; givnum_offset = 1 + givnum_dim1; givnum -= givnum_offset; poles_dim1 = *ldu; poles_offset = 1 + poles_dim1; poles -= poles_offset; z_dim1 = *ldu; z_offset = 1 + z_dim1; z__ -= z_offset; difr_dim1 = *ldu; difr_offset = 1 + difr_dim1; difr -= difr_offset; difl_dim1 = *ldu; difl_offset = 1 + difl_dim1; difl -= difl_offset; vt_dim1 = *ldu; vt_offset = 1 + vt_dim1; vt -= vt_offset; u_dim1 = *ldu; u_offset = 1 + u_dim1; u -= u_offset; --k; --givptr; perm_dim1 = *ldgcol; perm_offset = 1 + perm_dim1; perm -= perm_offset; givcol_dim1 = *ldgcol; givcol_offset = 1 + givcol_dim1; givcol -= givcol_offset; --c__; --s; --work; --iwork; /* Function Body */ *info = 0; if ((*icompq < 0) || (*icompq > 1)) { *info = -1; } else if (*smlsiz < 3) { *info = -2; } else if (*n < 0) { *info = -3; } else if ((*sqre < 0) || (*sqre > 1)) { *info = -4; } else if (*ldu < *n + *sqre) { *info = -8; } else if (*ldgcol < *n) { *info = -17; } if (*info != 0) { i__1 = -(*info); xerbla_("SLASDA", &i__1); return 0; } m = *n + *sqre; /* If the input matrix is too small, call SLASDQ to find the SVD. */ if (*n <= *smlsiz) { if (*icompq == 0) { slasdq_("U", sqre, n, &c__0, &c__0, &c__0, &d__[1], &e[1], &vt[ vt_offset], ldu, &u[u_offset], ldu, &u[u_offset], ldu, & work[1], info); } else { slasdq_("U", sqre, n, &m, n, &c__0, &d__[1], &e[1], &vt[vt_offset] , ldu, &u[u_offset], ldu, &u[u_offset], ldu, &work[1], info); } return 0; } /* Book-keeping and set up the computation tree. */ inode = 1; ndiml = inode + *n; ndimr = ndiml + *n; idxq = ndimr + *n; iwk = idxq + *n; ncc = 0; nru = 0; smlszp = *smlsiz + 1; vf = 1; vl = vf + m; nwork1 = vl + m; nwork2 = nwork1 + smlszp * smlszp; slasdt_(n, &nlvl, &nd, &iwork[inode], &iwork[ndiml], &iwork[ndimr], smlsiz); /* for the nodes on bottom level of the tree, solve their subproblems by SLASDQ. */ ndb1 = (nd + 1) / 2; i__1 = nd; for (i__ = ndb1; i__ <= i__1; ++i__) { /* IC : center row of each node NL : number of rows of left subproblem NR : number of rows of right subproblem NLF: starting row of the left subproblem NRF: starting row of the right subproblem */ i1 = i__ - 1; ic = iwork[inode + i1]; nl = iwork[ndiml + i1]; nlp1 = nl + 1; nr = iwork[ndimr + i1]; nlf = ic - nl; nrf = ic + 1; idxqi = idxq + nlf - 2; vfi = vf + nlf - 1; vli = vl + nlf - 1; sqrei = 1; if (*icompq == 0) { slaset_("A", &nlp1, &nlp1, &c_b320, &c_b1011, &work[nwork1], & smlszp); slasdq_("U", &sqrei, &nl, &nlp1, &nru, &ncc, &d__[nlf], &e[nlf], & work[nwork1], &smlszp, &work[nwork2], &nl, &work[nwork2], &nl, &work[nwork2], info); itemp = nwork1 + nl * smlszp; scopy_(&nlp1, &work[nwork1], &c__1, &work[vfi], &c__1); scopy_(&nlp1, &work[itemp], &c__1, &work[vli], &c__1); } else { slaset_("A", &nl, &nl, &c_b320, &c_b1011, &u[nlf + u_dim1], ldu); slaset_("A", &nlp1, &nlp1, &c_b320, &c_b1011, &vt[nlf + vt_dim1], ldu); slasdq_("U", &sqrei, &nl, &nlp1, &nl, &ncc, &d__[nlf], &e[nlf], & vt[nlf + vt_dim1], ldu, &u[nlf + u_dim1], ldu, &u[nlf + u_dim1], ldu, &work[nwork1], info); scopy_(&nlp1, &vt[nlf + vt_dim1], &c__1, &work[vfi], &c__1); scopy_(&nlp1, &vt[nlf + nlp1 * vt_dim1], &c__1, &work[vli], &c__1) ; } if (*info != 0) { return 0; } i__2 = nl; for (j = 1; j <= i__2; ++j) { iwork[idxqi + j] = j; /* L10: */ } if (i__ == nd && *sqre == 0) { sqrei = 0; } else { sqrei = 1; } idxqi += nlp1; vfi += nlp1; vli += nlp1; nrp1 = nr + sqrei; if (*icompq == 0) { slaset_("A", &nrp1, &nrp1, &c_b320, &c_b1011, &work[nwork1], & smlszp); slasdq_("U", &sqrei, &nr, &nrp1, &nru, &ncc, &d__[nrf], &e[nrf], & work[nwork1], &smlszp, &work[nwork2], &nr, &work[nwork2], &nr, &work[nwork2], info); itemp = nwork1 + (nrp1 - 1) * smlszp; scopy_(&nrp1, &work[nwork1], &c__1, &work[vfi], &c__1); scopy_(&nrp1, &work[itemp], &c__1, &work[vli], &c__1); } else { slaset_("A", &nr, &nr, &c_b320, &c_b1011, &u[nrf + u_dim1], ldu); slaset_("A", &nrp1, &nrp1, &c_b320, &c_b1011, &vt[nrf + vt_dim1], ldu); slasdq_("U", &sqrei, &nr, &nrp1, &nr, &ncc, &d__[nrf], &e[nrf], & vt[nrf + vt_dim1], ldu, &u[nrf + u_dim1], ldu, &u[nrf + u_dim1], ldu, &work[nwork1], info); scopy_(&nrp1, &vt[nrf + vt_dim1], &c__1, &work[vfi], &c__1); scopy_(&nrp1, &vt[nrf + nrp1 * vt_dim1], &c__1, &work[vli], &c__1) ; } if (*info != 0) { return 0; } i__2 = nr; for (j = 1; j <= i__2; ++j) { iwork[idxqi + j] = j; /* L20: */ } /* L30: */ } /* Now conquer each subproblem bottom-up. */ j = pow_ii(&c__2, &nlvl); for (lvl = nlvl; lvl >= 1; --lvl) { lvl2 = ((lvl) << (1)) - 1; /* Find the first node LF and last node LL on the current level LVL. */ if (lvl == 1) { lf = 1; ll = 1; } else { i__1 = lvl - 1; lf = pow_ii(&c__2, &i__1); ll = ((lf) << (1)) - 1; } i__1 = ll; for (i__ = lf; i__ <= i__1; ++i__) { im1 = i__ - 1; ic = iwork[inode + im1]; nl = iwork[ndiml + im1]; nr = iwork[ndimr + im1]; nlf = ic - nl; nrf = ic + 1; if (i__ == ll) { sqrei = *sqre; } else { sqrei = 1; } vfi = vf + nlf - 1; vli = vl + nlf - 1; idxqi = idxq + nlf - 1; alpha = d__[ic]; beta = e[ic]; if (*icompq == 0) { slasd6_(icompq, &nl, &nr, &sqrei, &d__[nlf], &work[vfi], & work[vli], &alpha, &beta, &iwork[idxqi], &perm[ perm_offset], &givptr[1], &givcol[givcol_offset], ldgcol, &givnum[givnum_offset], ldu, &poles[ poles_offset], &difl[difl_offset], &difr[difr_offset], &z__[z_offset], &k[1], &c__[1], &s[1], &work[nwork1], &iwork[iwk], info); } else { --j; slasd6_(icompq, &nl, &nr, &sqrei, &d__[nlf], &work[vfi], & work[vli], &alpha, &beta, &iwork[idxqi], &perm[nlf + lvl * perm_dim1], &givptr[j], &givcol[nlf + lvl2 * givcol_dim1], ldgcol, &givnum[nlf + lvl2 * givnum_dim1], ldu, &poles[nlf + lvl2 * poles_dim1], & difl[nlf + lvl * difl_dim1], &difr[nlf + lvl2 * difr_dim1], &z__[nlf + lvl * z_dim1], &k[j], &c__[j], &s[j], &work[nwork1], &iwork[iwk], info); } if (*info != 0) { return 0; } /* L40: */ } /* L50: */ } return 0; /* End of SLASDA */ } /* slasda_ */ /* Subroutine */ int slasdq_(char *uplo, integer *sqre, integer *n, integer * ncvt, integer *nru, integer *ncc, real *d__, real *e, real *vt, integer *ldvt, real *u, integer *ldu, real *c__, integer *ldc, real * work, integer *info) { /* System generated locals */ integer c_dim1, c_offset, u_dim1, u_offset, vt_dim1, vt_offset, i__1, i__2; /* Local variables */ static integer i__, j; static real r__, cs, sn; static integer np1, isub; static real smin; static integer sqre1; extern logical lsame_(char *, char *); extern /* Subroutine */ int slasr_(char *, char *, char *, integer *, integer *, real *, real *, real *, integer *); static integer iuplo; extern /* Subroutine */ int sswap_(integer *, real *, integer *, real *, integer *), xerbla_(char *, integer *), slartg_(real *, real *, real *, real *, real *); static logical rotate; extern /* Subroutine */ int sbdsqr_(char *, integer *, integer *, integer *, integer *, real *, real *, real *, integer *, real *, integer * , real *, integer *, real *, integer *); /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University October 31, 1999 Purpose ======= SLASDQ computes the singular value decomposition (SVD) of a real (upper or lower) bidiagonal matrix with diagonal D and offdiagonal E, accumulating the transformations if desired. Letting B denote the input bidiagonal matrix, the algorithm computes orthogonal matrices Q and P such that B = Q * S * P' (P' denotes the transpose of P). The singular values S are overwritten on D. The input matrix U is changed to U * Q if desired. The input matrix VT is changed to P' * VT if desired. The input matrix C is changed to Q' * C if desired. See "Computing Small Singular Values of Bidiagonal Matrices With Guaranteed High Relative Accuracy," by J. Demmel and W. Kahan, LAPACK Working Note #3, for a detailed description of the algorithm. Arguments ========= UPLO (input) CHARACTER*1 On entry, UPLO specifies whether the input bidiagonal matrix is upper or lower bidiagonal, and wether it is square are not. UPLO = 'U' or 'u' B is upper bidiagonal. UPLO = 'L' or 'l' B is lower bidiagonal. SQRE (input) INTEGER = 0: then the input matrix is N-by-N. = 1: then the input matrix is N-by-(N+1) if UPLU = 'U' and (N+1)-by-N if UPLU = 'L'. The bidiagonal matrix has N = NL + NR + 1 rows and M = N + SQRE >= N columns. N (input) INTEGER On entry, N specifies the number of rows and columns in the matrix. N must be at least 0. NCVT (input) INTEGER On entry, NCVT specifies the number of columns of the matrix VT. NCVT must be at least 0. NRU (input) INTEGER On entry, NRU specifies the number of rows of the matrix U. NRU must be at least 0. NCC (input) INTEGER On entry, NCC specifies the number of columns of the matrix C. NCC must be at least 0. D (input/output) REAL array, dimension (N) On entry, D contains the diagonal entries of the bidiagonal matrix whose SVD is desired. On normal exit, D contains the singular values in ascending order. E (input/output) REAL array. dimension is (N-1) if SQRE = 0 and N if SQRE = 1. On entry, the entries of E contain the offdiagonal entries of the bidiagonal matrix whose SVD is desired. On normal exit, E will contain 0. If the algorithm does not converge, D and E will contain the diagonal and superdiagonal entries of a bidiagonal matrix orthogonally equivalent to the one given as input. VT (input/output) REAL array, dimension (LDVT, NCVT) On entry, contains a matrix which on exit has been premultiplied by P', dimension N-by-NCVT if SQRE = 0 and (N+1)-by-NCVT if SQRE = 1 (not referenced if NCVT=0). LDVT (input) INTEGER On entry, LDVT specifies the leading dimension of VT as declared in the calling (sub) program. LDVT must be at least 1. If NCVT is nonzero LDVT must also be at least N. U (input/output) REAL array, dimension (LDU, N) On entry, contains a matrix which on exit has been postmultiplied by Q, dimension NRU-by-N if SQRE = 0 and NRU-by-(N+1) if SQRE = 1 (not referenced if NRU=0). LDU (input) INTEGER On entry, LDU specifies the leading dimension of U as declared in the calling (sub) program. LDU must be at least max( 1, NRU ) . C (input/output) REAL array, dimension (LDC, NCC) On entry, contains an N-by-NCC matrix which on exit has been premultiplied by Q' dimension N-by-NCC if SQRE = 0 and (N+1)-by-NCC if SQRE = 1 (not referenced if NCC=0). LDC (input) INTEGER On entry, LDC specifies the leading dimension of C as declared in the calling (sub) program. LDC must be at least 1. If NCC is nonzero, LDC must also be at least N. WORK (workspace) REAL array, dimension (4*N) Workspace. Only referenced if one of NCVT, NRU, or NCC is nonzero, and if N is at least 2. INFO (output) INTEGER On exit, a value of 0 indicates a successful exit. If INFO < 0, argument number -INFO is illegal. If INFO > 0, the algorithm did not converge, and INFO specifies how many superdiagonals did not converge. Further Details =============== Based on contributions by Ming Gu and Huan Ren, Computer Science Division, University of California at Berkeley, USA ===================================================================== Test the input parameters. */ /* Parameter adjustments */ --d__; --e; vt_dim1 = *ldvt; vt_offset = 1 + vt_dim1; vt -= vt_offset; u_dim1 = *ldu; u_offset = 1 + u_dim1; u -= u_offset; c_dim1 = *ldc; c_offset = 1 + c_dim1; c__ -= c_offset; --work; /* Function Body */ *info = 0; iuplo = 0; if (lsame_(uplo, "U")) { iuplo = 1; } if (lsame_(uplo, "L")) { iuplo = 2; } if (iuplo == 0) { *info = -1; } else if ((*sqre < 0) || (*sqre > 1)) { *info = -2; } else if (*n < 0) { *info = -3; } else if (*ncvt < 0) { *info = -4; } else if (*nru < 0) { *info = -5; } else if (*ncc < 0) { *info = -6; } else if ((*ncvt == 0 && *ldvt < 1) || (*ncvt > 0 && *ldvt < max(1,*n))) { *info = -10; } else if (*ldu < max(1,*nru)) { *info = -12; } else if ((*ncc == 0 && *ldc < 1) || (*ncc > 0 && *ldc < max(1,*n))) { *info = -14; } if (*info != 0) { i__1 = -(*info); xerbla_("SLASDQ", &i__1); return 0; } if (*n == 0) { return 0; } /* ROTATE is true if any singular vectors desired, false otherwise */ rotate = ((*ncvt > 0) || (*nru > 0)) || (*ncc > 0); np1 = *n + 1; sqre1 = *sqre; /* If matrix non-square upper bidiagonal, rotate to be lower bidiagonal. The rotations are on the right. */ if (iuplo == 1 && sqre1 == 1) { i__1 = *n - 1; for (i__ = 1; i__ <= i__1; ++i__) { slartg_(&d__[i__], &e[i__], &cs, &sn, &r__); d__[i__] = r__; e[i__] = sn * d__[i__ + 1]; d__[i__ + 1] = cs * d__[i__ + 1]; if (rotate) { work[i__] = cs; work[*n + i__] = sn; } /* L10: */ } slartg_(&d__[*n], &e[*n], &cs, &sn, &r__); d__[*n] = r__; e[*n] = 0.f; if (rotate) { work[*n] = cs; work[*n + *n] = sn; } iuplo = 2; sqre1 = 0; /* Update singular vectors if desired. */ if (*ncvt > 0) { slasr_("L", "V", "F", &np1, ncvt, &work[1], &work[np1], &vt[ vt_offset], ldvt); } } /* If matrix lower bidiagonal, rotate to be upper bidiagonal by applying Givens rotations on the left. */ if (iuplo == 2) { i__1 = *n - 1; for (i__ = 1; i__ <= i__1; ++i__) { slartg_(&d__[i__], &e[i__], &cs, &sn, &r__); d__[i__] = r__; e[i__] = sn * d__[i__ + 1]; d__[i__ + 1] = cs * d__[i__ + 1]; if (rotate) { work[i__] = cs; work[*n + i__] = sn; } /* L20: */ } /* If matrix (N+1)-by-N lower bidiagonal, one additional rotation is needed. */ if (sqre1 == 1) { slartg_(&d__[*n], &e[*n], &cs, &sn, &r__); d__[*n] = r__; if (rotate) { work[*n] = cs; work[*n + *n] = sn; } } /* Update singular vectors if desired. */ if (*nru > 0) { if (sqre1 == 0) { slasr_("R", "V", "F", nru, n, &work[1], &work[np1], &u[ u_offset], ldu); } else { slasr_("R", "V", "F", nru, &np1, &work[1], &work[np1], &u[ u_offset], ldu); } } if (*ncc > 0) { if (sqre1 == 0) { slasr_("L", "V", "F", n, ncc, &work[1], &work[np1], &c__[ c_offset], ldc); } else { slasr_("L", "V", "F", &np1, ncc, &work[1], &work[np1], &c__[ c_offset], ldc); } } } /* Call SBDSQR to compute the SVD of the reduced real N-by-N upper bidiagonal matrix. */ sbdsqr_("U", n, ncvt, nru, ncc, &d__[1], &e[1], &vt[vt_offset], ldvt, &u[ u_offset], ldu, &c__[c_offset], ldc, &work[1], info); /* Sort the singular values into ascending order (insertion sort on singular values, but only one transposition per singular vector) */ i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { /* Scan for smallest D(I). */ isub = i__; smin = d__[i__]; i__2 = *n; for (j = i__ + 1; j <= i__2; ++j) { if (d__[j] < smin) { isub = j; smin = d__[j]; } /* L30: */ } if (isub != i__) { /* Swap singular values and vectors. */ d__[isub] = d__[i__]; d__[i__] = smin; if (*ncvt > 0) { sswap_(ncvt, &vt[isub + vt_dim1], ldvt, &vt[i__ + vt_dim1], ldvt); } if (*nru > 0) { sswap_(nru, &u[isub * u_dim1 + 1], &c__1, &u[i__ * u_dim1 + 1] , &c__1); } if (*ncc > 0) { sswap_(ncc, &c__[isub + c_dim1], ldc, &c__[i__ + c_dim1], ldc) ; } } /* L40: */ } return 0; /* End of SLASDQ */ } /* slasdq_ */ /* Subroutine */ int slasdt_(integer *n, integer *lvl, integer *nd, integer * inode, integer *ndiml, integer *ndimr, integer *msub) { /* System generated locals */ integer i__1, i__2; /* Builtin functions */ double log(doublereal); /* Local variables */ static integer i__, il, ir, maxn; static real temp; static integer nlvl, llst, ncrnt; /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University October 31, 1999 Purpose ======= SLASDT creates a tree of subproblems for bidiagonal divide and conquer. Arguments ========= N (input) INTEGER On entry, the number of diagonal elements of the bidiagonal matrix. LVL (output) INTEGER On exit, the number of levels on the computation tree. ND (output) INTEGER On exit, the number of nodes on the tree. INODE (output) INTEGER array, dimension ( N ) On exit, centers of subproblems. NDIML (output) INTEGER array, dimension ( N ) On exit, row dimensions of left children. NDIMR (output) INTEGER array, dimension ( N ) On exit, row dimensions of right children. MSUB (input) INTEGER. On entry, the maximum row dimension each subproblem at the bottom of the tree can be of. Further Details =============== Based on contributions by Ming Gu and Huan Ren, Computer Science Division, University of California at Berkeley, USA ===================================================================== Find the number of levels on the tree. */ /* Parameter adjustments */ --ndimr; --ndiml; --inode; /* Function Body */ maxn = max(1,*n); temp = log((real) maxn / (real) (*msub + 1)) / log(2.f); *lvl = (integer) temp + 1; i__ = *n / 2; inode[1] = i__ + 1; ndiml[1] = i__; ndimr[1] = *n - i__ - 1; il = 0; ir = 1; llst = 1; i__1 = *lvl - 1; for (nlvl = 1; nlvl <= i__1; ++nlvl) { /* Constructing the tree at (NLVL+1)-st level. The number of nodes created on this level is LLST * 2. */ i__2 = llst - 1; for (i__ = 0; i__ <= i__2; ++i__) { il += 2; ir += 2; ncrnt = llst + i__; ndiml[il] = ndiml[ncrnt] / 2; ndimr[il] = ndiml[ncrnt] - ndiml[il] - 1; inode[il] = inode[ncrnt] - ndimr[il] - 1; ndiml[ir] = ndimr[ncrnt] / 2; ndimr[ir] = ndimr[ncrnt] - ndiml[ir] - 1; inode[ir] = inode[ncrnt] + ndiml[ir] + 1; /* L10: */ } llst <<= 1; /* L20: */ } *nd = ((llst) << (1)) - 1; return 0; /* End of SLASDT */ } /* slasdt_ */ /* Subroutine */ int slaset_(char *uplo, integer *m, integer *n, real *alpha, real *beta, real *a, integer *lda) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3; /* Local variables */ static integer i__, j; extern logical lsame_(char *, char *); /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University October 31, 1992 Purpose ======= SLASET initializes an m-by-n matrix A to BETA on the diagonal and ALPHA on the offdiagonals. Arguments ========= UPLO (input) CHARACTER*1 Specifies the part of the matrix A to be set. = 'U': Upper triangular part is set; the strictly lower triangular part of A is not changed. = 'L': Lower triangular part is set; the strictly upper triangular part of A is not changed. Otherwise: All of the matrix A is set. M (input) INTEGER The number of rows of the matrix A. M >= 0. N (input) INTEGER The number of columns of the matrix A. N >= 0. ALPHA (input) REAL The constant to which the offdiagonal elements are to be set. BETA (input) REAL The constant to which the diagonal elements are to be set. A (input/output) REAL array, dimension (LDA,N) On exit, the leading m-by-n submatrix of A is set as follows: if UPLO = 'U', A(i,j) = ALPHA, 1<=i<=j-1, 1<=j<=n, if UPLO = 'L', A(i,j) = ALPHA, j+1<=i<=m, 1<=j<=n, otherwise, A(i,j) = ALPHA, 1<=i<=m, 1<=j<=n, i.ne.j, and, for all UPLO, A(i,i) = BETA, 1<=i<=min(m,n). LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,M). ===================================================================== */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; /* Function Body */ if (lsame_(uplo, "U")) { /* Set the strictly upper triangular or trapezoidal part of the array to ALPHA. */ i__1 = *n; for (j = 2; j <= i__1; ++j) { /* Computing MIN */ i__3 = j - 1; i__2 = min(i__3,*m); for (i__ = 1; i__ <= i__2; ++i__) { a[i__ + j * a_dim1] = *alpha; /* L10: */ } /* L20: */ } } else if (lsame_(uplo, "L")) { /* Set the strictly lower triangular or trapezoidal part of the array to ALPHA. */ i__1 = min(*m,*n); for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = j + 1; i__ <= i__2; ++i__) { a[i__ + j * a_dim1] = *alpha; /* L30: */ } /* L40: */ } } else { /* Set the leading m-by-n submatrix to ALPHA. */ i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { a[i__ + j * a_dim1] = *alpha; /* L50: */ } /* L60: */ } } /* Set the first min(M,N) diagonal elements to BETA. */ i__1 = min(*m,*n); for (i__ = 1; i__ <= i__1; ++i__) { a[i__ + i__ * a_dim1] = *beta; /* L70: */ } return 0; /* End of SLASET */ } /* slaset_ */ /* Subroutine */ int slasq1_(integer *n, real *d__, real *e, real *work, integer *info) { /* System generated locals */ integer i__1, i__2; real r__1, r__2, r__3; /* Builtin functions */ double sqrt(doublereal); /* Local variables */ static integer i__; static real eps; extern /* Subroutine */ int slas2_(real *, real *, real *, real *, real *) ; static real scale; static integer iinfo; static real sigmn, sigmx; extern /* Subroutine */ int scopy_(integer *, real *, integer *, real *, integer *), slasq2_(integer *, real *, integer *); extern doublereal slamch_(char *); static real safmin; extern /* Subroutine */ int xerbla_(char *, integer *), slascl_( char *, integer *, integer *, real *, real *, integer *, integer * , real *, integer *, integer *), slasrt_(char *, integer * , real *, integer *); /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University October 31, 1999 Purpose ======= SLASQ1 computes the singular values of a real N-by-N bidiagonal matrix with diagonal D and off-diagonal E. The singular values are computed to high relative accuracy, in the absence of denormalization, underflow and overflow. The algorithm was first presented in "Accurate singular values and differential qd algorithms" by K. V. Fernando and B. N. Parlett, Numer. Math., Vol-67, No. 2, pp. 191-230, 1994, and the present implementation is described in "An implementation of the dqds Algorithm (Positive Case)", LAPACK Working Note. Arguments ========= N (input) INTEGER The number of rows and columns in the matrix. N >= 0. D (input/output) REAL array, dimension (N) On entry, D contains the diagonal elements of the bidiagonal matrix whose SVD is desired. On normal exit, D contains the singular values in decreasing order. E (input/output) REAL array, dimension (N) On entry, elements E(1:N-1) contain the off-diagonal elements of the bidiagonal matrix whose SVD is desired. On exit, E is overwritten. WORK (workspace) REAL array, dimension (4*N) INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value > 0: the algorithm failed = 1, a split was marked by a positive value in E = 2, current block of Z not diagonalized after 30*N iterations (in inner while loop) = 3, termination criterion of outer while loop not met (program created more than N unreduced blocks) ===================================================================== */ /* Parameter adjustments */ --work; --e; --d__; /* Function Body */ *info = 0; if (*n < 0) { *info = -2; i__1 = -(*info); xerbla_("SLASQ1", &i__1); return 0; } else if (*n == 0) { return 0; } else if (*n == 1) { d__[1] = dabs(d__[1]); return 0; } else if (*n == 2) { slas2_(&d__[1], &e[1], &d__[2], &sigmn, &sigmx); d__[1] = sigmx; d__[2] = sigmn; return 0; } /* Estimate the largest singular value. */ sigmx = 0.f; i__1 = *n - 1; for (i__ = 1; i__ <= i__1; ++i__) { d__[i__] = (r__1 = d__[i__], dabs(r__1)); /* Computing MAX */ r__2 = sigmx, r__3 = (r__1 = e[i__], dabs(r__1)); sigmx = dmax(r__2,r__3); /* L10: */ } d__[*n] = (r__1 = d__[*n], dabs(r__1)); /* Early return if SIGMX is zero (matrix is already diagonal). */ if (sigmx == 0.f) { slasrt_("D", n, &d__[1], &iinfo); return 0; } i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { /* Computing MAX */ r__1 = sigmx, r__2 = d__[i__]; sigmx = dmax(r__1,r__2); /* L20: */ } /* Copy D and E into WORK (in the Z format) and scale (squaring the input data makes scaling by a power of the radix pointless). */ eps = slamch_("Precision"); safmin = slamch_("Safe minimum"); scale = sqrt(eps / safmin); scopy_(n, &d__[1], &c__1, &work[1], &c__2); i__1 = *n - 1; scopy_(&i__1, &e[1], &c__1, &work[2], &c__2); i__1 = ((*n) << (1)) - 1; i__2 = ((*n) << (1)) - 1; slascl_("G", &c__0, &c__0, &sigmx, &scale, &i__1, &c__1, &work[1], &i__2, &iinfo); /* Compute the q's and e's. */ i__1 = ((*n) << (1)) - 1; for (i__ = 1; i__ <= i__1; ++i__) { /* Computing 2nd power */ r__1 = work[i__]; work[i__] = r__1 * r__1; /* L30: */ } work[*n * 2] = 0.f; slasq2_(n, &work[1], info); if (*info == 0) { i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { d__[i__] = sqrt(work[i__]); /* L40: */ } slascl_("G", &c__0, &c__0, &scale, &sigmx, n, &c__1, &d__[1], n, & iinfo); } return 0; /* End of SLASQ1 */ } /* slasq1_ */ /* Subroutine */ int slasq2_(integer *n, real *z__, integer *info) { /* System generated locals */ integer i__1, i__2, i__3; real r__1, r__2; /* Builtin functions */ double sqrt(doublereal); /* Local variables */ static real d__, e; static integer k; static real s, t; static integer i0, i4, n0, pp; static real eps, tol; static integer ipn4; static real tol2; static logical ieee; static integer nbig; static real dmin__, emin, emax; static integer ndiv, iter; static real qmin, temp, qmax, zmax; static integer splt, nfail; static real desig, trace, sigma; static integer iinfo; extern /* Subroutine */ int slasq3_(integer *, integer *, real *, integer *, real *, real *, real *, real *, integer *, integer *, integer * , logical *); extern doublereal slamch_(char *); static integer iwhila, iwhilb; static real oldemn, safmin; extern /* Subroutine */ int xerbla_(char *, integer *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); extern /* Subroutine */ int slasrt_(char *, integer *, real *, integer *); /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University October 31, 1999 Purpose ======= SLASQ2 computes all the eigenvalues of the symmetric positive definite tridiagonal matrix associated with the qd array Z to high relative accuracy are computed to high relative accuracy, in the absence of denormalization, underflow and overflow. To see the relation of Z to the tridiagonal matrix, let L be a unit lower bidiagonal matrix with subdiagonals Z(2,4,6,,..) and let U be an upper bidiagonal matrix with 1's above and diagonal Z(1,3,5,,..). The tridiagonal is L*U or, if you prefer, the symmetric tridiagonal to which it is similar. Note : SLASQ2 defines a logical variable, IEEE, which is true on machines which follow ieee-754 floating-point standard in their handling of infinities and NaNs, and false otherwise. This variable is passed to SLASQ3. Arguments ========= N (input) INTEGER The number of rows and columns in the matrix. N >= 0. Z (workspace) REAL array, dimension ( 4*N ) On entry Z holds the qd array. On exit, entries 1 to N hold the eigenvalues in decreasing order, Z( 2*N+1 ) holds the trace, and Z( 2*N+2 ) holds the sum of the eigenvalues. If N > 2, then Z( 2*N+3 ) holds the iteration count, Z( 2*N+4 ) holds NDIVS/NIN^2, and Z( 2*N+5 ) holds the percentage of shifts that failed. INFO (output) INTEGER = 0: successful exit < 0: if the i-th argument is a scalar and had an illegal value, then INFO = -i, if the i-th argument is an array and the j-entry had an illegal value, then INFO = -(i*100+j) > 0: the algorithm failed = 1, a split was marked by a positive value in E = 2, current block of Z not diagonalized after 30*N iterations (in inner while loop) = 3, termination criterion of outer while loop not met (program created more than N unreduced blocks) Further Details =============== Local Variables: I0:N0 defines a current unreduced segment of Z. The shifts are accumulated in SIGMA. Iteration count is in ITER. Ping-pong is controlled by PP (alternates between 0 and 1). ===================================================================== Test the input arguments. (in case SLASQ2 is not called by SLASQ1) */ /* Parameter adjustments */ --z__; /* Function Body */ *info = 0; eps = slamch_("Precision"); safmin = slamch_("Safe minimum"); tol = eps * 100.f; /* Computing 2nd power */ r__1 = tol; tol2 = r__1 * r__1; if (*n < 0) { *info = -1; xerbla_("SLASQ2", &c__1); return 0; } else if (*n == 0) { return 0; } else if (*n == 1) { /* 1-by-1 case. */ if (z__[1] < 0.f) { *info = -201; xerbla_("SLASQ2", &c__2); } return 0; } else if (*n == 2) { /* 2-by-2 case. */ if ((z__[2] < 0.f) || (z__[3] < 0.f)) { *info = -2; xerbla_("SLASQ2", &c__2); return 0; } else if (z__[3] > z__[1]) { d__ = z__[3]; z__[3] = z__[1]; z__[1] = d__; } z__[5] = z__[1] + z__[2] + z__[3]; if (z__[2] > z__[3] * tol2) { t = (z__[1] - z__[3] + z__[2]) * .5f; s = z__[3] * (z__[2] / t); if (s <= t) { s = z__[3] * (z__[2] / (t * (sqrt(s / t + 1.f) + 1.f))); } else { s = z__[3] * (z__[2] / (t + sqrt(t) * sqrt(t + s))); } t = z__[1] + (s + z__[2]); z__[3] *= z__[1] / t; z__[1] = t; } z__[2] = z__[3]; z__[6] = z__[2] + z__[1]; return 0; } /* Check for negative data and compute sums of q's and e's. */ z__[*n * 2] = 0.f; emin = z__[2]; qmax = 0.f; zmax = 0.f; d__ = 0.f; e = 0.f; i__1 = (*n - 1) << (1); for (k = 1; k <= i__1; k += 2) { if (z__[k] < 0.f) { *info = -(k + 200); xerbla_("SLASQ2", &c__2); return 0; } else if (z__[k + 1] < 0.f) { *info = -(k + 201); xerbla_("SLASQ2", &c__2); return 0; } d__ += z__[k]; e += z__[k + 1]; /* Computing MAX */ r__1 = qmax, r__2 = z__[k]; qmax = dmax(r__1,r__2); /* Computing MIN */ r__1 = emin, r__2 = z__[k + 1]; emin = dmin(r__1,r__2); /* Computing MAX */ r__1 = max(qmax,zmax), r__2 = z__[k + 1]; zmax = dmax(r__1,r__2); /* L10: */ } if (z__[((*n) << (1)) - 1] < 0.f) { *info = -(((*n) << (1)) + 199); xerbla_("SLASQ2", &c__2); return 0; } d__ += z__[((*n) << (1)) - 1]; /* Computing MAX */ r__1 = qmax, r__2 = z__[((*n) << (1)) - 1]; qmax = dmax(r__1,r__2); zmax = dmax(qmax,zmax); /* Check for diagonality. */ if (e == 0.f) { i__1 = *n; for (k = 2; k <= i__1; ++k) { z__[k] = z__[((k) << (1)) - 1]; /* L20: */ } slasrt_("D", n, &z__[1], &iinfo); z__[((*n) << (1)) - 1] = d__; return 0; } trace = d__ + e; /* Check for zero data. */ if (trace == 0.f) { z__[((*n) << (1)) - 1] = 0.f; return 0; } /* Check whether the machine is IEEE conformable. */ ieee = ilaenv_(&c__10, "SLASQ2", "N", &c__1, &c__2, &c__3, &c__4, (ftnlen) 6, (ftnlen)1) == 1 && ilaenv_(&c__11, "SLASQ2", "N", &c__1, &c__2, &c__3, &c__4, (ftnlen)6, (ftnlen)1) == 1; /* Rearrange data for locality: Z=(q1,qq1,e1,ee1,q2,qq2,e2,ee2,...). */ for (k = (*n) << (1); k >= 2; k += -2) { z__[k * 2] = 0.f; z__[((k) << (1)) - 1] = z__[k]; z__[((k) << (1)) - 2] = 0.f; z__[((k) << (1)) - 3] = z__[k - 1]; /* L30: */ } i0 = 1; n0 = *n; /* Reverse the qd-array, if warranted. */ if (z__[((i0) << (2)) - 3] * 1.5f < z__[((n0) << (2)) - 3]) { ipn4 = (i0 + n0) << (2); i__1 = (i0 + n0 - 1) << (1); for (i4 = (i0) << (2); i4 <= i__1; i4 += 4) { temp = z__[i4 - 3]; z__[i4 - 3] = z__[ipn4 - i4 - 3]; z__[ipn4 - i4 - 3] = temp; temp = z__[i4 - 1]; z__[i4 - 1] = z__[ipn4 - i4 - 5]; z__[ipn4 - i4 - 5] = temp; /* L40: */ } } /* Initial split checking via dqd and Li's test. */ pp = 0; for (k = 1; k <= 2; ++k) { d__ = z__[((n0) << (2)) + pp - 3]; i__1 = ((i0) << (2)) + pp; for (i4 = ((n0 - 1) << (2)) + pp; i4 >= i__1; i4 += -4) { if (z__[i4 - 1] <= tol2 * d__) { z__[i4 - 1] = -0.f; d__ = z__[i4 - 3]; } else { d__ = z__[i4 - 3] * (d__ / (d__ + z__[i4 - 1])); } /* L50: */ } /* dqd maps Z to ZZ plus Li's test. */ emin = z__[((i0) << (2)) + pp + 1]; d__ = z__[((i0) << (2)) + pp - 3]; i__1 = ((n0 - 1) << (2)) + pp; for (i4 = ((i0) << (2)) + pp; i4 <= i__1; i4 += 4) { z__[i4 - ((pp) << (1)) - 2] = d__ + z__[i4 - 1]; if (z__[i4 - 1] <= tol2 * d__) { z__[i4 - 1] = -0.f; z__[i4 - ((pp) << (1)) - 2] = d__; z__[i4 - ((pp) << (1))] = 0.f; d__ = z__[i4 + 1]; } else if (safmin * z__[i4 + 1] < z__[i4 - ((pp) << (1)) - 2] && safmin * z__[i4 - ((pp) << (1)) - 2] < z__[i4 + 1]) { temp = z__[i4 + 1] / z__[i4 - ((pp) << (1)) - 2]; z__[i4 - ((pp) << (1))] = z__[i4 - 1] * temp; d__ *= temp; } else { z__[i4 - ((pp) << (1))] = z__[i4 + 1] * (z__[i4 - 1] / z__[i4 - ((pp) << (1)) - 2]); d__ = z__[i4 + 1] * (d__ / z__[i4 - ((pp) << (1)) - 2]); } /* Computing MIN */ r__1 = emin, r__2 = z__[i4 - ((pp) << (1))]; emin = dmin(r__1,r__2); /* L60: */ } z__[((n0) << (2)) - pp - 2] = d__; /* Now find qmax. */ qmax = z__[((i0) << (2)) - pp - 2]; i__1 = ((n0) << (2)) - pp - 2; for (i4 = ((i0) << (2)) - pp + 2; i4 <= i__1; i4 += 4) { /* Computing MAX */ r__1 = qmax, r__2 = z__[i4]; qmax = dmax(r__1,r__2); /* L70: */ } /* Prepare for the next iteration on K. */ pp = 1 - pp; /* L80: */ } iter = 2; nfail = 0; ndiv = (n0 - i0) << (1); i__1 = *n + 1; for (iwhila = 1; iwhila <= i__1; ++iwhila) { if (n0 < 1) { goto L150; } /* While array unfinished do E(N0) holds the value of SIGMA when submatrix in I0:N0 splits from the rest of the array, but is negated. */ desig = 0.f; if (n0 == *n) { sigma = 0.f; } else { sigma = -z__[((n0) << (2)) - 1]; } if (sigma < 0.f) { *info = 1; return 0; } /* Find last unreduced submatrix's top index I0, find QMAX and EMIN. Find Gershgorin-type bound if Q's much greater than E's. */ emax = 0.f; if (n0 > i0) { emin = (r__1 = z__[((n0) << (2)) - 5], dabs(r__1)); } else { emin = 0.f; } qmin = z__[((n0) << (2)) - 3]; qmax = qmin; for (i4 = (n0) << (2); i4 >= 8; i4 += -4) { if (z__[i4 - 5] <= 0.f) { goto L100; } if (qmin >= emax * 4.f) { /* Computing MIN */ r__1 = qmin, r__2 = z__[i4 - 3]; qmin = dmin(r__1,r__2); /* Computing MAX */ r__1 = emax, r__2 = z__[i4 - 5]; emax = dmax(r__1,r__2); } /* Computing MAX */ r__1 = qmax, r__2 = z__[i4 - 7] + z__[i4 - 5]; qmax = dmax(r__1,r__2); /* Computing MIN */ r__1 = emin, r__2 = z__[i4 - 5]; emin = dmin(r__1,r__2); /* L90: */ } i4 = 4; L100: i0 = i4 / 4; /* Store EMIN for passing to SLASQ3. */ z__[((n0) << (2)) - 1] = emin; /* Put -(initial shift) into DMIN. Computing MAX */ r__1 = 0.f, r__2 = qmin - sqrt(qmin) * 2.f * sqrt(emax); dmin__ = -dmax(r__1,r__2); /* Now I0:N0 is unreduced. PP = 0 for ping, PP = 1 for pong. */ pp = 0; nbig = (n0 - i0 + 1) * 30; i__2 = nbig; for (iwhilb = 1; iwhilb <= i__2; ++iwhilb) { if (i0 > n0) { goto L130; } /* While submatrix unfinished take a good dqds step. */ slasq3_(&i0, &n0, &z__[1], &pp, &dmin__, &sigma, &desig, &qmax, & nfail, &iter, &ndiv, &ieee); pp = 1 - pp; /* When EMIN is very small check for splits. */ if (pp == 0 && n0 - i0 >= 3) { if ((z__[n0 * 4] <= tol2 * qmax) || (z__[((n0) << (2)) - 1] <= tol2 * sigma)) { splt = i0 - 1; qmax = z__[((i0) << (2)) - 3]; emin = z__[((i0) << (2)) - 1]; oldemn = z__[i0 * 4]; i__3 = (n0 - 3) << (2); for (i4 = (i0) << (2); i4 <= i__3; i4 += 4) { if ((z__[i4] <= tol2 * z__[i4 - 3]) || (z__[i4 - 1] <= tol2 * sigma)) { z__[i4 - 1] = -sigma; splt = i4 / 4; qmax = 0.f; emin = z__[i4 + 3]; oldemn = z__[i4 + 4]; } else { /* Computing MAX */ r__1 = qmax, r__2 = z__[i4 + 1]; qmax = dmax(r__1,r__2); /* Computing MIN */ r__1 = emin, r__2 = z__[i4 - 1]; emin = dmin(r__1,r__2); /* Computing MIN */ r__1 = oldemn, r__2 = z__[i4]; oldemn = dmin(r__1,r__2); } /* L110: */ } z__[((n0) << (2)) - 1] = emin; z__[n0 * 4] = oldemn; i0 = splt + 1; } } /* L120: */ } *info = 2; return 0; /* end IWHILB */ L130: /* L140: */ ; } *info = 3; return 0; /* end IWHILA */ L150: /* Move q's to the front. */ i__1 = *n; for (k = 2; k <= i__1; ++k) { z__[k] = z__[((k) << (2)) - 3]; /* L160: */ } /* Sort and compute sum of eigenvalues. */ slasrt_("D", n, &z__[1], &iinfo); e = 0.f; for (k = *n; k >= 1; --k) { e += z__[k]; /* L170: */ } /* Store trace, sum(eigenvalues) and information on performance. */ z__[((*n) << (1)) + 1] = trace; z__[((*n) << (1)) + 2] = e; z__[((*n) << (1)) + 3] = (real) iter; /* Computing 2nd power */ i__1 = *n; z__[((*n) << (1)) + 4] = (real) ndiv / (real) (i__1 * i__1); z__[((*n) << (1)) + 5] = nfail * 100.f / (real) iter; return 0; /* End of SLASQ2 */ } /* slasq2_ */ /* Subroutine */ int slasq3_(integer *i0, integer *n0, real *z__, integer *pp, real *dmin__, real *sigma, real *desig, real *qmax, integer *nfail, integer *iter, integer *ndiv, logical *ieee) { /* Initialized data */ static integer ttype = 0; static real dmin1 = 0.f; static real dmin2 = 0.f; static real dn = 0.f; static real dn1 = 0.f; static real dn2 = 0.f; static real tau = 0.f; /* System generated locals */ integer i__1; real r__1, r__2; /* Builtin functions */ double sqrt(doublereal); /* Local variables */ static real s, t; static integer j4, nn; static real eps, tol; static integer n0in, ipn4; static real tol2, temp; extern /* Subroutine */ int slasq4_(integer *, integer *, real *, integer *, integer *, real *, real *, real *, real *, real *, real *, real *, integer *), slasq5_(integer *, integer *, real *, integer *, real *, real *, real *, real *, real *, real *, real *, logical *), slasq6_(integer *, integer *, real *, integer *, real *, real *, real *, real *, real *, real *); extern doublereal slamch_(char *); static real safmin; /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University May 17, 2000 Purpose ======= SLASQ3 checks for deflation, computes a shift (TAU) and calls dqds. In case of failure it changes shifts, and tries again until output is positive. Arguments ========= I0 (input) INTEGER First index. N0 (input) INTEGER Last index. Z (input) REAL array, dimension ( 4*N ) Z holds the qd array. PP (input) INTEGER PP=0 for ping, PP=1 for pong. DMIN (output) REAL Minimum value of d. SIGMA (output) REAL Sum of shifts used in current segment. DESIG (input/output) REAL Lower order part of SIGMA QMAX (input) REAL Maximum value of q. NFAIL (output) INTEGER Number of times shift was too big. ITER (output) INTEGER Number of iterations. NDIV (output) INTEGER Number of divisions. TTYPE (output) INTEGER Shift type. IEEE (input) LOGICAL Flag for IEEE or non IEEE arithmetic (passed to SLASQ5). ===================================================================== */ /* Parameter adjustments */ --z__; /* Function Body */ n0in = *n0; eps = slamch_("Precision"); safmin = slamch_("Safe minimum"); tol = eps * 100.f; /* Computing 2nd power */ r__1 = tol; tol2 = r__1 * r__1; /* Check for deflation. */ L10: if (*n0 < *i0) { return 0; } if (*n0 == *i0) { goto L20; } nn = ((*n0) << (2)) + *pp; if (*n0 == *i0 + 1) { goto L40; } /* Check whether E(N0-1) is negligible, 1 eigenvalue. */ if (z__[nn - 5] > tol2 * (*sigma + z__[nn - 3]) && z__[nn - ((*pp) << (1)) - 4] > tol2 * z__[nn - 7]) { goto L30; } L20: z__[((*n0) << (2)) - 3] = z__[((*n0) << (2)) + *pp - 3] + *sigma; --(*n0); goto L10; /* Check whether E(N0-2) is negligible, 2 eigenvalues. */ L30: if (z__[nn - 9] > tol2 * *sigma && z__[nn - ((*pp) << (1)) - 8] > tol2 * z__[nn - 11]) { goto L50; } L40: if (z__[nn - 3] > z__[nn - 7]) { s = z__[nn - 3]; z__[nn - 3] = z__[nn - 7]; z__[nn - 7] = s; } if (z__[nn - 5] > z__[nn - 3] * tol2) { t = (z__[nn - 7] - z__[nn - 3] + z__[nn - 5]) * .5f; s = z__[nn - 3] * (z__[nn - 5] / t); if (s <= t) { s = z__[nn - 3] * (z__[nn - 5] / (t * (sqrt(s / t + 1.f) + 1.f))); } else { s = z__[nn - 3] * (z__[nn - 5] / (t + sqrt(t) * sqrt(t + s))); } t = z__[nn - 7] + (s + z__[nn - 5]); z__[nn - 3] *= z__[nn - 7] / t; z__[nn - 7] = t; } z__[((*n0) << (2)) - 7] = z__[nn - 7] + *sigma; z__[((*n0) << (2)) - 3] = z__[nn - 3] + *sigma; *n0 += -2; goto L10; L50: /* Reverse the qd-array, if warranted. */ if ((*dmin__ <= 0.f) || (*n0 < n0in)) { if (z__[((*i0) << (2)) + *pp - 3] * 1.5f < z__[((*n0) << (2)) + *pp - 3]) { ipn4 = (*i0 + *n0) << (2); i__1 = (*i0 + *n0 - 1) << (1); for (j4 = (*i0) << (2); j4 <= i__1; j4 += 4) { temp = z__[j4 - 3]; z__[j4 - 3] = z__[ipn4 - j4 - 3]; z__[ipn4 - j4 - 3] = temp; temp = z__[j4 - 2]; z__[j4 - 2] = z__[ipn4 - j4 - 2]; z__[ipn4 - j4 - 2] = temp; temp = z__[j4 - 1]; z__[j4 - 1] = z__[ipn4 - j4 - 5]; z__[ipn4 - j4 - 5] = temp; temp = z__[j4]; z__[j4] = z__[ipn4 - j4 - 4]; z__[ipn4 - j4 - 4] = temp; /* L60: */ } if (*n0 - *i0 <= 4) { z__[((*n0) << (2)) + *pp - 1] = z__[((*i0) << (2)) + *pp - 1]; z__[((*n0) << (2)) - *pp] = z__[((*i0) << (2)) - *pp]; } /* Computing MIN */ r__1 = dmin2, r__2 = z__[((*n0) << (2)) + *pp - 1]; dmin2 = dmin(r__1,r__2); /* Computing MIN */ r__1 = z__[((*n0) << (2)) + *pp - 1], r__2 = z__[((*i0) << (2)) + *pp - 1], r__1 = min(r__1,r__2), r__2 = z__[((*i0) << (2)) + *pp + 3]; z__[((*n0) << (2)) + *pp - 1] = dmin(r__1,r__2); /* Computing MIN */ r__1 = z__[((*n0) << (2)) - *pp], r__2 = z__[((*i0) << (2)) - *pp] , r__1 = min(r__1,r__2), r__2 = z__[((*i0) << (2)) - *pp + 4]; z__[((*n0) << (2)) - *pp] = dmin(r__1,r__2); /* Computing MAX */ r__1 = *qmax, r__2 = z__[((*i0) << (2)) + *pp - 3], r__1 = max( r__1,r__2), r__2 = z__[((*i0) << (2)) + *pp + 1]; *qmax = dmax(r__1,r__2); *dmin__ = -0.f; } } /* L70: Computing MIN */ r__1 = z__[((*n0) << (2)) + *pp - 1], r__2 = z__[((*n0) << (2)) + *pp - 9] , r__1 = min(r__1,r__2), r__2 = dmin2 + z__[((*n0) << (2)) - *pp]; if ((*dmin__ < 0.f) || (safmin * *qmax < dmin(r__1,r__2))) { /* Choose a shift. */ slasq4_(i0, n0, &z__[1], pp, &n0in, dmin__, &dmin1, &dmin2, &dn, &dn1, &dn2, &tau, &ttype); /* Call dqds until DMIN > 0. */ L80: slasq5_(i0, n0, &z__[1], pp, &tau, dmin__, &dmin1, &dmin2, &dn, &dn1, &dn2, ieee); *ndiv += *n0 - *i0 + 2; ++(*iter); /* Check status. */ if (*dmin__ >= 0.f && dmin1 > 0.f) { /* Success. */ goto L100; } else if (*dmin__ < 0.f && dmin1 > 0.f && z__[((*n0 - 1) << (2)) - * pp] < tol * (*sigma + dn1) && dabs(dn) < tol * *sigma) { /* Convergence hidden by negative DN. */ z__[((*n0 - 1) << (2)) - *pp + 2] = 0.f; *dmin__ = 0.f; goto L100; } else if (*dmin__ < 0.f) { /* TAU too big. Select new TAU and try again. */ ++(*nfail); if (ttype < -22) { /* Failed twice. Play it safe. */ tau = 0.f; } else if (dmin1 > 0.f) { /* Late failure. Gives excellent shift. */ tau = (tau + *dmin__) * (1.f - eps * 2.f); ttype += -11; } else { /* Early failure. Divide by 4. */ tau *= .25f; ttype += -12; } goto L80; } else if (*dmin__ != *dmin__) { /* NaN. */ tau = 0.f; goto L80; } else { /* Possible underflow. Play it safe. */ goto L90; } } /* Risk of underflow. */ L90: slasq6_(i0, n0, &z__[1], pp, dmin__, &dmin1, &dmin2, &dn, &dn1, &dn2); *ndiv += *n0 - *i0 + 2; ++(*iter); tau = 0.f; L100: if (tau < *sigma) { *desig += tau; t = *sigma + *desig; *desig -= t - *sigma; } else { t = *sigma + tau; *desig = *sigma - (t - tau) + *desig; } *sigma = t; return 0; /* End of SLASQ3 */ } /* slasq3_ */ /* Subroutine */ int slasq4_(integer *i0, integer *n0, real *z__, integer *pp, integer *n0in, real *dmin__, real *dmin1, real *dmin2, real *dn, real *dn1, real *dn2, real *tau, integer *ttype) { /* Initialized data */ static real g = 0.f; /* System generated locals */ integer i__1; real r__1, r__2; /* Builtin functions */ double sqrt(doublereal); /* Local variables */ static real s, a2, b1, b2; static integer i4, nn, np; static real gam, gap1, gap2; /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University October 31, 1999 Purpose ======= SLASQ4 computes an approximation TAU to the smallest eigenvalue using values of d from the previous transform. I0 (input) INTEGER First index. N0 (input) INTEGER Last index. Z (input) REAL array, dimension ( 4*N ) Z holds the qd array. PP (input) INTEGER PP=0 for ping, PP=1 for pong. NOIN (input) INTEGER The value of N0 at start of EIGTEST. DMIN (input) REAL Minimum value of d. DMIN1 (input) REAL Minimum value of d, excluding D( N0 ). DMIN2 (input) REAL Minimum value of d, excluding D( N0 ) and D( N0-1 ). DN (input) REAL d(N) DN1 (input) REAL d(N-1) DN2 (input) REAL d(N-2) TAU (output) REAL This is the shift. TTYPE (output) INTEGER Shift type. Further Details =============== CNST1 = 9/16 ===================================================================== */ /* Parameter adjustments */ --z__; /* Function Body */ /* A negative DMIN forces the shift to take that absolute value TTYPE records the type of shift. */ if (*dmin__ <= 0.f) { *tau = -(*dmin__); *ttype = -1; return 0; } nn = ((*n0) << (2)) + *pp; if (*n0in == *n0) { /* No eigenvalues deflated. */ if ((*dmin__ == *dn) || (*dmin__ == *dn1)) { b1 = sqrt(z__[nn - 3]) * sqrt(z__[nn - 5]); b2 = sqrt(z__[nn - 7]) * sqrt(z__[nn - 9]); a2 = z__[nn - 7] + z__[nn - 5]; /* Cases 2 and 3. */ if (*dmin__ == *dn && *dmin1 == *dn1) { gap2 = *dmin2 - a2 - *dmin2 * .25f; if (gap2 > 0.f && gap2 > b2) { gap1 = a2 - *dn - b2 / gap2 * b2; } else { gap1 = a2 - *dn - (b1 + b2); } if (gap1 > 0.f && gap1 > b1) { /* Computing MAX */ r__1 = *dn - b1 / gap1 * b1, r__2 = *dmin__ * .5f; s = dmax(r__1,r__2); *ttype = -2; } else { s = 0.f; if (*dn > b1) { s = *dn - b1; } if (a2 > b1 + b2) { /* Computing MIN */ r__1 = s, r__2 = a2 - (b1 + b2); s = dmin(r__1,r__2); } /* Computing MAX */ r__1 = s, r__2 = *dmin__ * .333f; s = dmax(r__1,r__2); *ttype = -3; } } else { /* Case 4. */ *ttype = -4; s = *dmin__ * .25f; if (*dmin__ == *dn) { gam = *dn; a2 = 0.f; if (z__[nn - 5] > z__[nn - 7]) { return 0; } b2 = z__[nn - 5] / z__[nn - 7]; np = nn - 9; } else { np = nn - ((*pp) << (1)); b2 = z__[np - 2]; gam = *dn1; if (z__[np - 4] > z__[np - 2]) { return 0; } a2 = z__[np - 4] / z__[np - 2]; if (z__[nn - 9] > z__[nn - 11]) { return 0; } b2 = z__[nn - 9] / z__[nn - 11]; np = nn - 13; } /* Approximate contribution to norm squared from I < NN-1. */ a2 += b2; i__1 = ((*i0) << (2)) - 1 + *pp; for (i4 = np; i4 >= i__1; i4 += -4) { if (b2 == 0.f) { goto L20; } b1 = b2; if (z__[i4] > z__[i4 - 2]) { return 0; } b2 *= z__[i4] / z__[i4 - 2]; a2 += b2; if ((dmax(b2,b1) * 100.f < a2) || (.563f < a2)) { goto L20; } /* L10: */ } L20: a2 *= 1.05f; /* Rayleigh quotient residual bound. */ if (a2 < .563f) { s = gam * (1.f - sqrt(a2)) / (a2 + 1.f); } } } else if (*dmin__ == *dn2) { /* Case 5. */ *ttype = -5; s = *dmin__ * .25f; /* Compute contribution to norm squared from I > NN-2. */ np = nn - ((*pp) << (1)); b1 = z__[np - 2]; b2 = z__[np - 6]; gam = *dn2; if ((z__[np - 8] > b2) || (z__[np - 4] > b1)) { return 0; } a2 = z__[np - 8] / b2 * (z__[np - 4] / b1 + 1.f); /* Approximate contribution to norm squared from I < NN-2. */ if (*n0 - *i0 > 2) { b2 = z__[nn - 13] / z__[nn - 15]; a2 += b2; i__1 = ((*i0) << (2)) - 1 + *pp; for (i4 = nn - 17; i4 >= i__1; i4 += -4) { if (b2 == 0.f) { goto L40; } b1 = b2; if (z__[i4] > z__[i4 - 2]) { return 0; } b2 *= z__[i4] / z__[i4 - 2]; a2 += b2; if ((dmax(b2,b1) * 100.f < a2) || (.563f < a2)) { goto L40; } /* L30: */ } L40: a2 *= 1.05f; } if (a2 < .563f) { s = gam * (1.f - sqrt(a2)) / (a2 + 1.f); } } else { /* Case 6, no information to guide us. */ if (*ttype == -6) { g += (1.f - g) * .333f; } else if (*ttype == -18) { g = .083250000000000005f; } else { g = .25f; } s = g * *dmin__; *ttype = -6; } } else if (*n0in == *n0 + 1) { /* One eigenvalue just deflated. Use DMIN1, DN1 for DMIN and DN. */ if (*dmin1 == *dn1 && *dmin2 == *dn2) { /* Cases 7 and 8. */ *ttype = -7; s = *dmin1 * .333f; if (z__[nn - 5] > z__[nn - 7]) { return 0; } b1 = z__[nn - 5] / z__[nn - 7]; b2 = b1; if (b2 == 0.f) { goto L60; } i__1 = ((*i0) << (2)) - 1 + *pp; for (i4 = ((*n0) << (2)) - 9 + *pp; i4 >= i__1; i4 += -4) { a2 = b1; if (z__[i4] > z__[i4 - 2]) { return 0; } b1 *= z__[i4] / z__[i4 - 2]; b2 += b1; if (dmax(b1,a2) * 100.f < b2) { goto L60; } /* L50: */ } L60: b2 = sqrt(b2 * 1.05f); /* Computing 2nd power */ r__1 = b2; a2 = *dmin1 / (r__1 * r__1 + 1.f); gap2 = *dmin2 * .5f - a2; if (gap2 > 0.f && gap2 > b2 * a2) { /* Computing MAX */ r__1 = s, r__2 = a2 * (1.f - a2 * 1.01f * (b2 / gap2) * b2); s = dmax(r__1,r__2); } else { /* Computing MAX */ r__1 = s, r__2 = a2 * (1.f - b2 * 1.01f); s = dmax(r__1,r__2); *ttype = -8; } } else { /* Case 9. */ s = *dmin1 * .25f; if (*dmin1 == *dn1) { s = *dmin1 * .5f; } *ttype = -9; } } else if (*n0in == *n0 + 2) { /* Two eigenvalues deflated. Use DMIN2, DN2 for DMIN and DN. Cases 10 and 11. */ if (*dmin2 == *dn2 && z__[nn - 5] * 2.f < z__[nn - 7]) { *ttype = -10; s = *dmin2 * .333f; if (z__[nn - 5] > z__[nn - 7]) { return 0; } b1 = z__[nn - 5] / z__[nn - 7]; b2 = b1; if (b2 == 0.f) { goto L80; } i__1 = ((*i0) << (2)) - 1 + *pp; for (i4 = ((*n0) << (2)) - 9 + *pp; i4 >= i__1; i4 += -4) { if (z__[i4] > z__[i4 - 2]) { return 0; } b1 *= z__[i4] / z__[i4 - 2]; b2 += b1; if (b1 * 100.f < b2) { goto L80; } /* L70: */ } L80: b2 = sqrt(b2 * 1.05f); /* Computing 2nd power */ r__1 = b2; a2 = *dmin2 / (r__1 * r__1 + 1.f); gap2 = z__[nn - 7] + z__[nn - 9] - sqrt(z__[nn - 11]) * sqrt(z__[ nn - 9]) - a2; if (gap2 > 0.f && gap2 > b2 * a2) { /* Computing MAX */ r__1 = s, r__2 = a2 * (1.f - a2 * 1.01f * (b2 / gap2) * b2); s = dmax(r__1,r__2); } else { /* Computing MAX */ r__1 = s, r__2 = a2 * (1.f - b2 * 1.01f); s = dmax(r__1,r__2); } } else { s = *dmin2 * .25f; *ttype = -11; } } else if (*n0in > *n0 + 2) { /* Case 12, more than two eigenvalues deflated. No information. */ s = 0.f; *ttype = -12; } *tau = s; return 0; /* End of SLASQ4 */ } /* slasq4_ */ /* Subroutine */ int slasq5_(integer *i0, integer *n0, real *z__, integer *pp, real *tau, real *dmin__, real *dmin1, real *dmin2, real *dn, real * dnm1, real *dnm2, logical *ieee) { /* System generated locals */ integer i__1; real r__1, r__2; /* Local variables */ static real d__; static integer j4, j4p2; static real emin, temp; /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University May 17, 2000 Purpose ======= SLASQ5 computes one dqds transform in ping-pong form, one version for IEEE machines another for non IEEE machines. Arguments ========= I0 (input) INTEGER First index. N0 (input) INTEGER Last index. Z (input) REAL array, dimension ( 4*N ) Z holds the qd array. EMIN is stored in Z(4*N0) to avoid an extra argument. PP (input) INTEGER PP=0 for ping, PP=1 for pong. TAU (input) REAL This is the shift. DMIN (output) REAL Minimum value of d. DMIN1 (output) REAL Minimum value of d, excluding D( N0 ). DMIN2 (output) REAL Minimum value of d, excluding D( N0 ) and D( N0-1 ). DN (output) REAL d(N0), the last value of d. DNM1 (output) REAL d(N0-1). DNM2 (output) REAL d(N0-2). IEEE (input) LOGICAL Flag for IEEE or non IEEE arithmetic. ===================================================================== */ /* Parameter adjustments */ --z__; /* Function Body */ if (*n0 - *i0 - 1 <= 0) { return 0; } j4 = ((*i0) << (2)) + *pp - 3; emin = z__[j4 + 4]; d__ = z__[j4] - *tau; *dmin__ = d__; *dmin1 = -z__[j4]; if (*ieee) { /* Code for IEEE arithmetic. */ if (*pp == 0) { i__1 = (*n0 - 3) << (2); for (j4 = (*i0) << (2); j4 <= i__1; j4 += 4) { z__[j4 - 2] = d__ + z__[j4 - 1]; temp = z__[j4 + 1] / z__[j4 - 2]; d__ = d__ * temp - *tau; *dmin__ = dmin(*dmin__,d__); z__[j4] = z__[j4 - 1] * temp; /* Computing MIN */ r__1 = z__[j4]; emin = dmin(r__1,emin); /* L10: */ } } else { i__1 = (*n0 - 3) << (2); for (j4 = (*i0) << (2); j4 <= i__1; j4 += 4) { z__[j4 - 3] = d__ + z__[j4]; temp = z__[j4 + 2] / z__[j4 - 3]; d__ = d__ * temp - *tau; *dmin__ = dmin(*dmin__,d__); z__[j4 - 1] = z__[j4] * temp; /* Computing MIN */ r__1 = z__[j4 - 1]; emin = dmin(r__1,emin); /* L20: */ } } /* Unroll last two steps. */ *dnm2 = d__; *dmin2 = *dmin__; j4 = ((*n0 - 2) << (2)) - *pp; j4p2 = j4 + ((*pp) << (1)) - 1; z__[j4 - 2] = *dnm2 + z__[j4p2]; z__[j4] = z__[j4p2 + 2] * (z__[j4p2] / z__[j4 - 2]); *dnm1 = z__[j4p2 + 2] * (*dnm2 / z__[j4 - 2]) - *tau; *dmin__ = dmin(*dmin__,*dnm1); *dmin1 = *dmin__; j4 += 4; j4p2 = j4 + ((*pp) << (1)) - 1; z__[j4 - 2] = *dnm1 + z__[j4p2]; z__[j4] = z__[j4p2 + 2] * (z__[j4p2] / z__[j4 - 2]); *dn = z__[j4p2 + 2] * (*dnm1 / z__[j4 - 2]) - *tau; *dmin__ = dmin(*dmin__,*dn); } else { /* Code for non IEEE arithmetic. */ if (*pp == 0) { i__1 = (*n0 - 3) << (2); for (j4 = (*i0) << (2); j4 <= i__1; j4 += 4) { z__[j4 - 2] = d__ + z__[j4 - 1]; if (d__ < 0.f) { return 0; } else { z__[j4] = z__[j4 + 1] * (z__[j4 - 1] / z__[j4 - 2]); d__ = z__[j4 + 1] * (d__ / z__[j4 - 2]) - *tau; } *dmin__ = dmin(*dmin__,d__); /* Computing MIN */ r__1 = emin, r__2 = z__[j4]; emin = dmin(r__1,r__2); /* L30: */ } } else { i__1 = (*n0 - 3) << (2); for (j4 = (*i0) << (2); j4 <= i__1; j4 += 4) { z__[j4 - 3] = d__ + z__[j4]; if (d__ < 0.f) { return 0; } else { z__[j4 - 1] = z__[j4 + 2] * (z__[j4] / z__[j4 - 3]); d__ = z__[j4 + 2] * (d__ / z__[j4 - 3]) - *tau; } *dmin__ = dmin(*dmin__,d__); /* Computing MIN */ r__1 = emin, r__2 = z__[j4 - 1]; emin = dmin(r__1,r__2); /* L40: */ } } /* Unroll last two steps. */ *dnm2 = d__; *dmin2 = *dmin__; j4 = ((*n0 - 2) << (2)) - *pp; j4p2 = j4 + ((*pp) << (1)) - 1; z__[j4 - 2] = *dnm2 + z__[j4p2]; if (*dnm2 < 0.f) { return 0; } else { z__[j4] = z__[j4p2 + 2] * (z__[j4p2] / z__[j4 - 2]); *dnm1 = z__[j4p2 + 2] * (*dnm2 / z__[j4 - 2]) - *tau; } *dmin__ = dmin(*dmin__,*dnm1); *dmin1 = *dmin__; j4 += 4; j4p2 = j4 + ((*pp) << (1)) - 1; z__[j4 - 2] = *dnm1 + z__[j4p2]; if (*dnm1 < 0.f) { return 0; } else { z__[j4] = z__[j4p2 + 2] * (z__[j4p2] / z__[j4 - 2]); *dn = z__[j4p2 + 2] * (*dnm1 / z__[j4 - 2]) - *tau; } *dmin__ = dmin(*dmin__,*dn); } z__[j4 + 2] = *dn; z__[((*n0) << (2)) - *pp] = emin; return 0; /* End of SLASQ5 */ } /* slasq5_ */ /* Subroutine */ int slasq6_(integer *i0, integer *n0, real *z__, integer *pp, real *dmin__, real *dmin1, real *dmin2, real *dn, real *dnm1, real * dnm2) { /* System generated locals */ integer i__1; real r__1, r__2; /* Local variables */ static real d__; static integer j4, j4p2; static real emin, temp; extern doublereal slamch_(char *); static real safmin; /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University October 31, 1999 Purpose ======= SLASQ6 computes one dqd (shift equal to zero) transform in ping-pong form, with protection against underflow and overflow. Arguments ========= I0 (input) INTEGER First index. N0 (input) INTEGER Last index. Z (input) REAL array, dimension ( 4*N ) Z holds the qd array. EMIN is stored in Z(4*N0) to avoid an extra argument. PP (input) INTEGER PP=0 for ping, PP=1 for pong. DMIN (output) REAL Minimum value of d. DMIN1 (output) REAL Minimum value of d, excluding D( N0 ). DMIN2 (output) REAL Minimum value of d, excluding D( N0 ) and D( N0-1 ). DN (output) REAL d(N0), the last value of d. DNM1 (output) REAL d(N0-1). DNM2 (output) REAL d(N0-2). ===================================================================== */ /* Parameter adjustments */ --z__; /* Function Body */ if (*n0 - *i0 - 1 <= 0) { return 0; } safmin = slamch_("Safe minimum"); j4 = ((*i0) << (2)) + *pp - 3; emin = z__[j4 + 4]; d__ = z__[j4]; *dmin__ = d__; if (*pp == 0) { i__1 = (*n0 - 3) << (2); for (j4 = (*i0) << (2); j4 <= i__1; j4 += 4) { z__[j4 - 2] = d__ + z__[j4 - 1]; if (z__[j4 - 2] == 0.f) { z__[j4] = 0.f; d__ = z__[j4 + 1]; *dmin__ = d__; emin = 0.f; } else if (safmin * z__[j4 + 1] < z__[j4 - 2] && safmin * z__[j4 - 2] < z__[j4 + 1]) { temp = z__[j4 + 1] / z__[j4 - 2]; z__[j4] = z__[j4 - 1] * temp; d__ *= temp; } else { z__[j4] = z__[j4 + 1] * (z__[j4 - 1] / z__[j4 - 2]); d__ = z__[j4 + 1] * (d__ / z__[j4 - 2]); } *dmin__ = dmin(*dmin__,d__); /* Computing MIN */ r__1 = emin, r__2 = z__[j4]; emin = dmin(r__1,r__2); /* L10: */ } } else { i__1 = (*n0 - 3) << (2); for (j4 = (*i0) << (2); j4 <= i__1; j4 += 4) { z__[j4 - 3] = d__ + z__[j4]; if (z__[j4 - 3] == 0.f) { z__[j4 - 1] = 0.f; d__ = z__[j4 + 2]; *dmin__ = d__; emin = 0.f; } else if (safmin * z__[j4 + 2] < z__[j4 - 3] && safmin * z__[j4 - 3] < z__[j4 + 2]) { temp = z__[j4 + 2] / z__[j4 - 3]; z__[j4 - 1] = z__[j4] * temp; d__ *= temp; } else { z__[j4 - 1] = z__[j4 + 2] * (z__[j4] / z__[j4 - 3]); d__ = z__[j4 + 2] * (d__ / z__[j4 - 3]); } *dmin__ = dmin(*dmin__,d__); /* Computing MIN */ r__1 = emin, r__2 = z__[j4 - 1]; emin = dmin(r__1,r__2); /* L20: */ } } /* Unroll last two steps. */ *dnm2 = d__; *dmin2 = *dmin__; j4 = ((*n0 - 2) << (2)) - *pp; j4p2 = j4 + ((*pp) << (1)) - 1; z__[j4 - 2] = *dnm2 + z__[j4p2]; if (z__[j4 - 2] == 0.f) { z__[j4] = 0.f; *dnm1 = z__[j4p2 + 2]; *dmin__ = *dnm1; emin = 0.f; } else if (safmin * z__[j4p2 + 2] < z__[j4 - 2] && safmin * z__[j4 - 2] < z__[j4p2 + 2]) { temp = z__[j4p2 + 2] / z__[j4 - 2]; z__[j4] = z__[j4p2] * temp; *dnm1 = *dnm2 * temp; } else { z__[j4] = z__[j4p2 + 2] * (z__[j4p2] / z__[j4 - 2]); *dnm1 = z__[j4p2 + 2] * (*dnm2 / z__[j4 - 2]); } *dmin__ = dmin(*dmin__,*dnm1); *dmin1 = *dmin__; j4 += 4; j4p2 = j4 + ((*pp) << (1)) - 1; z__[j4 - 2] = *dnm1 + z__[j4p2]; if (z__[j4 - 2] == 0.f) { z__[j4] = 0.f; *dn = z__[j4p2 + 2]; *dmin__ = *dn; emin = 0.f; } else if (safmin * z__[j4p2 + 2] < z__[j4 - 2] && safmin * z__[j4 - 2] < z__[j4p2 + 2]) { temp = z__[j4p2 + 2] / z__[j4 - 2]; z__[j4] = z__[j4p2] * temp; *dn = *dnm1 * temp; } else { z__[j4] = z__[j4p2 + 2] * (z__[j4p2] / z__[j4 - 2]); *dn = z__[j4p2 + 2] * (*dnm1 / z__[j4 - 2]); } *dmin__ = dmin(*dmin__,*dn); z__[j4 + 2] = *dn; z__[((*n0) << (2)) - *pp] = emin; return 0; /* End of SLASQ6 */ } /* slasq6_ */ /* Subroutine */ int slasr_(char *side, char *pivot, char *direct, integer *m, integer *n, real *c__, real *s, real *a, integer *lda) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2; /* Local variables */ static integer i__, j, info; static real temp; extern logical lsame_(char *, char *); static real ctemp, stemp; extern /* Subroutine */ int xerbla_(char *, integer *); /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University October 31, 1992 Purpose ======= SLASR performs the transformation A := P*A, when SIDE = 'L' or 'l' ( Left-hand side ) A := A*P', when SIDE = 'R' or 'r' ( Right-hand side ) where A is an m by n real matrix and P is an orthogonal matrix, consisting of a sequence of plane rotations determined by the parameters PIVOT and DIRECT as follows ( z = m when SIDE = 'L' or 'l' and z = n when SIDE = 'R' or 'r' ): When DIRECT = 'F' or 'f' ( Forward sequence ) then P = P( z - 1 )*...*P( 2 )*P( 1 ), and when DIRECT = 'B' or 'b' ( Backward sequence ) then P = P( 1 )*P( 2 )*...*P( z - 1 ), where P( k ) is a plane rotation matrix for the following planes: when PIVOT = 'V' or 'v' ( Variable pivot ), the plane ( k, k + 1 ) when PIVOT = 'T' or 't' ( Top pivot ), the plane ( 1, k + 1 ) when PIVOT = 'B' or 'b' ( Bottom pivot ), the plane ( k, z ) c( k ) and s( k ) must contain the cosine and sine that define the matrix P( k ). The two by two plane rotation part of the matrix P( k ), R( k ), is assumed to be of the form R( k ) = ( c( k ) s( k ) ). ( -s( k ) c( k ) ) This version vectorises across rows of the array A when SIDE = 'L'. Arguments ========= SIDE (input) CHARACTER*1 Specifies whether the plane rotation matrix P is applied to A on the left or the right. = 'L': Left, compute A := P*A = 'R': Right, compute A:= A*P' DIRECT (input) CHARACTER*1 Specifies whether P is a forward or backward sequence of plane rotations. = 'F': Forward, P = P( z - 1 )*...*P( 2 )*P( 1 ) = 'B': Backward, P = P( 1 )*P( 2 )*...*P( z - 1 ) PIVOT (input) CHARACTER*1 Specifies the plane for which P(k) is a plane rotation matrix. = 'V': Variable pivot, the plane (k,k+1) = 'T': Top pivot, the plane (1,k+1) = 'B': Bottom pivot, the plane (k,z) M (input) INTEGER The number of rows of the matrix A. If m <= 1, an immediate return is effected. N (input) INTEGER The number of columns of the matrix A. If n <= 1, an immediate return is effected. C, S (input) REAL arrays, dimension (M-1) if SIDE = 'L' (N-1) if SIDE = 'R' c(k) and s(k) contain the cosine and sine that define the matrix P(k). The two by two plane rotation part of the matrix P(k), R(k), is assumed to be of the form R( k ) = ( c( k ) s( k ) ). ( -s( k ) c( k ) ) A (input/output) REAL array, dimension (LDA,N) The m by n matrix A. On exit, A is overwritten by P*A if SIDE = 'R' or by A*P' if SIDE = 'L'. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,M). ===================================================================== Test the input parameters */ /* Parameter adjustments */ --c__; --s; a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; /* Function Body */ info = 0; if (! ((lsame_(side, "L")) || (lsame_(side, "R")))) { info = 1; } else if (! (((lsame_(pivot, "V")) || (lsame_( pivot, "T"))) || (lsame_(pivot, "B")))) { info = 2; } else if (! ((lsame_(direct, "F")) || (lsame_( direct, "B")))) { info = 3; } else if (*m < 0) { info = 4; } else if (*n < 0) { info = 5; } else if (*lda < max(1,*m)) { info = 9; } if (info != 0) { xerbla_("SLASR ", &info); return 0; } /* Quick return if possible */ if ((*m == 0) || (*n == 0)) { return 0; } if (lsame_(side, "L")) { /* Form P * A */ if (lsame_(pivot, "V")) { if (lsame_(direct, "F")) { i__1 = *m - 1; for (j = 1; j <= i__1; ++j) { ctemp = c__[j]; stemp = s[j]; if ((ctemp != 1.f) || (stemp != 0.f)) { i__2 = *n; for (i__ = 1; i__ <= i__2; ++i__) { temp = a[j + 1 + i__ * a_dim1]; a[j + 1 + i__ * a_dim1] = ctemp * temp - stemp * a[j + i__ * a_dim1]; a[j + i__ * a_dim1] = stemp * temp + ctemp * a[j + i__ * a_dim1]; /* L10: */ } } /* L20: */ } } else if (lsame_(direct, "B")) { for (j = *m - 1; j >= 1; --j) { ctemp = c__[j]; stemp = s[j]; if ((ctemp != 1.f) || (stemp != 0.f)) { i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { temp = a[j + 1 + i__ * a_dim1]; a[j + 1 + i__ * a_dim1] = ctemp * temp - stemp * a[j + i__ * a_dim1]; a[j + i__ * a_dim1] = stemp * temp + ctemp * a[j + i__ * a_dim1]; /* L30: */ } } /* L40: */ } } } else if (lsame_(pivot, "T")) { if (lsame_(direct, "F")) { i__1 = *m; for (j = 2; j <= i__1; ++j) { ctemp = c__[j - 1]; stemp = s[j - 1]; if ((ctemp != 1.f) || (stemp != 0.f)) { i__2 = *n; for (i__ = 1; i__ <= i__2; ++i__) { temp = a[j + i__ * a_dim1]; a[j + i__ * a_dim1] = ctemp * temp - stemp * a[ i__ * a_dim1 + 1]; a[i__ * a_dim1 + 1] = stemp * temp + ctemp * a[ i__ * a_dim1 + 1]; /* L50: */ } } /* L60: */ } } else if (lsame_(direct, "B")) { for (j = *m; j >= 2; --j) { ctemp = c__[j - 1]; stemp = s[j - 1]; if ((ctemp != 1.f) || (stemp != 0.f)) { i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { temp = a[j + i__ * a_dim1]; a[j + i__ * a_dim1] = ctemp * temp - stemp * a[ i__ * a_dim1 + 1]; a[i__ * a_dim1 + 1] = stemp * temp + ctemp * a[ i__ * a_dim1 + 1]; /* L70: */ } } /* L80: */ } } } else if (lsame_(pivot, "B")) { if (lsame_(direct, "F")) { i__1 = *m - 1; for (j = 1; j <= i__1; ++j) { ctemp = c__[j]; stemp = s[j]; if ((ctemp != 1.f) || (stemp != 0.f)) { i__2 = *n; for (i__ = 1; i__ <= i__2; ++i__) { temp = a[j + i__ * a_dim1]; a[j + i__ * a_dim1] = stemp * a[*m + i__ * a_dim1] + ctemp * temp; a[*m + i__ * a_dim1] = ctemp * a[*m + i__ * a_dim1] - stemp * temp; /* L90: */ } } /* L100: */ } } else if (lsame_(direct, "B")) { for (j = *m - 1; j >= 1; --j) { ctemp = c__[j]; stemp = s[j]; if ((ctemp != 1.f) || (stemp != 0.f)) { i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { temp = a[j + i__ * a_dim1]; a[j + i__ * a_dim1] = stemp * a[*m + i__ * a_dim1] + ctemp * temp; a[*m + i__ * a_dim1] = ctemp * a[*m + i__ * a_dim1] - stemp * temp; /* L110: */ } } /* L120: */ } } } } else if (lsame_(side, "R")) { /* Form A * P' */ if (lsame_(pivot, "V")) { if (lsame_(direct, "F")) { i__1 = *n - 1; for (j = 1; j <= i__1; ++j) { ctemp = c__[j]; stemp = s[j]; if ((ctemp != 1.f) || (stemp != 0.f)) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { temp = a[i__ + (j + 1) * a_dim1]; a[i__ + (j + 1) * a_dim1] = ctemp * temp - stemp * a[i__ + j * a_dim1]; a[i__ + j * a_dim1] = stemp * temp + ctemp * a[ i__ + j * a_dim1]; /* L130: */ } } /* L140: */ } } else if (lsame_(direct, "B")) { for (j = *n - 1; j >= 1; --j) { ctemp = c__[j]; stemp = s[j]; if ((ctemp != 1.f) || (stemp != 0.f)) { i__1 = *m; for (i__ = 1; i__ <= i__1; ++i__) { temp = a[i__ + (j + 1) * a_dim1]; a[i__ + (j + 1) * a_dim1] = ctemp * temp - stemp * a[i__ + j * a_dim1]; a[i__ + j * a_dim1] = stemp * temp + ctemp * a[ i__ + j * a_dim1]; /* L150: */ } } /* L160: */ } } } else if (lsame_(pivot, "T")) { if (lsame_(direct, "F")) { i__1 = *n; for (j = 2; j <= i__1; ++j) { ctemp = c__[j - 1]; stemp = s[j - 1]; if ((ctemp != 1.f) || (stemp != 0.f)) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { temp = a[i__ + j * a_dim1]; a[i__ + j * a_dim1] = ctemp * temp - stemp * a[ i__ + a_dim1]; a[i__ + a_dim1] = stemp * temp + ctemp * a[i__ + a_dim1]; /* L170: */ } } /* L180: */ } } else if (lsame_(direct, "B")) { for (j = *n; j >= 2; --j) { ctemp = c__[j - 1]; stemp = s[j - 1]; if ((ctemp != 1.f) || (stemp != 0.f)) { i__1 = *m; for (i__ = 1; i__ <= i__1; ++i__) { temp = a[i__ + j * a_dim1]; a[i__ + j * a_dim1] = ctemp * temp - stemp * a[ i__ + a_dim1]; a[i__ + a_dim1] = stemp * temp + ctemp * a[i__ + a_dim1]; /* L190: */ } } /* L200: */ } } } else if (lsame_(pivot, "B")) { if (lsame_(direct, "F")) { i__1 = *n - 1; for (j = 1; j <= i__1; ++j) { ctemp = c__[j]; stemp = s[j]; if ((ctemp != 1.f) || (stemp != 0.f)) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { temp = a[i__ + j * a_dim1]; a[i__ + j * a_dim1] = stemp * a[i__ + *n * a_dim1] + ctemp * temp; a[i__ + *n * a_dim1] = ctemp * a[i__ + *n * a_dim1] - stemp * temp; /* L210: */ } } /* L220: */ } } else if (lsame_(direct, "B")) { for (j = *n - 1; j >= 1; --j) { ctemp = c__[j]; stemp = s[j]; if ((ctemp != 1.f) || (stemp != 0.f)) { i__1 = *m; for (i__ = 1; i__ <= i__1; ++i__) { temp = a[i__ + j * a_dim1]; a[i__ + j * a_dim1] = stemp * a[i__ + *n * a_dim1] + ctemp * temp; a[i__ + *n * a_dim1] = ctemp * a[i__ + *n * a_dim1] - stemp * temp; /* L230: */ } } /* L240: */ } } } } return 0; /* End of SLASR */ } /* slasr_ */ /* Subroutine */ int slasrt_(char *id, integer *n, real *d__, integer *info) { /* System generated locals */ integer i__1, i__2; /* Local variables */ static integer i__, j; static real d1, d2, d3; static integer dir; static real tmp; static integer endd; extern logical lsame_(char *, char *); static integer stack[64] /* was [2][32] */; static real dmnmx; static integer start; extern /* Subroutine */ int xerbla_(char *, integer *); static integer stkpnt; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University September 30, 1994 Purpose ======= Sort the numbers in D in increasing order (if ID = 'I') or in decreasing order (if ID = 'D' ). Use Quick Sort, reverting to Insertion sort on arrays of size <= 20. Dimension of STACK limits N to about 2**32. Arguments ========= ID (input) CHARACTER*1 = 'I': sort D in increasing order; = 'D': sort D in decreasing order. N (input) INTEGER The length of the array D. D (input/output) REAL array, dimension (N) On entry, the array to be sorted. On exit, D has been sorted into increasing order (D(1) <= ... <= D(N) ) or into decreasing order (D(1) >= ... >= D(N) ), depending on ID. INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value ===================================================================== Test the input paramters. */ /* Parameter adjustments */ --d__; /* Function Body */ *info = 0; dir = -1; if (lsame_(id, "D")) { dir = 0; } else if (lsame_(id, "I")) { dir = 1; } if (dir == -1) { *info = -1; } else if (*n < 0) { *info = -2; } if (*info != 0) { i__1 = -(*info); xerbla_("SLASRT", &i__1); return 0; } /* Quick return if possible */ if (*n <= 1) { return 0; } stkpnt = 1; stack[0] = 1; stack[1] = *n; L10: start = stack[((stkpnt) << (1)) - 2]; endd = stack[((stkpnt) << (1)) - 1]; --stkpnt; if (endd - start <= 20 && endd - start > 0) { /* Do Insertion sort on D( START:ENDD ) */ if (dir == 0) { /* Sort into decreasing order */ i__1 = endd; for (i__ = start + 1; i__ <= i__1; ++i__) { i__2 = start + 1; for (j = i__; j >= i__2; --j) { if (d__[j] > d__[j - 1]) { dmnmx = d__[j]; d__[j] = d__[j - 1]; d__[j - 1] = dmnmx; } else { goto L30; } /* L20: */ } L30: ; } } else { /* Sort into increasing order */ i__1 = endd; for (i__ = start + 1; i__ <= i__1; ++i__) { i__2 = start + 1; for (j = i__; j >= i__2; --j) { if (d__[j] < d__[j - 1]) { dmnmx = d__[j]; d__[j] = d__[j - 1]; d__[j - 1] = dmnmx; } else { goto L50; } /* L40: */ } L50: ; } } } else if (endd - start > 20) { /* Partition D( START:ENDD ) and stack parts, largest one first Choose partition entry as median of 3 */ d1 = d__[start]; d2 = d__[endd]; i__ = (start + endd) / 2; d3 = d__[i__]; if (d1 < d2) { if (d3 < d1) { dmnmx = d1; } else if (d3 < d2) { dmnmx = d3; } else { dmnmx = d2; } } else { if (d3 < d2) { dmnmx = d2; } else if (d3 < d1) { dmnmx = d3; } else { dmnmx = d1; } } if (dir == 0) { /* Sort into decreasing order */ i__ = start - 1; j = endd + 1; L60: L70: --j; if (d__[j] < dmnmx) { goto L70; } L80: ++i__; if (d__[i__] > dmnmx) { goto L80; } if (i__ < j) { tmp = d__[i__]; d__[i__] = d__[j]; d__[j] = tmp; goto L60; } if (j - start > endd - j - 1) { ++stkpnt; stack[((stkpnt) << (1)) - 2] = start; stack[((stkpnt) << (1)) - 1] = j; ++stkpnt; stack[((stkpnt) << (1)) - 2] = j + 1; stack[((stkpnt) << (1)) - 1] = endd; } else { ++stkpnt; stack[((stkpnt) << (1)) - 2] = j + 1; stack[((stkpnt) << (1)) - 1] = endd; ++stkpnt; stack[((stkpnt) << (1)) - 2] = start; stack[((stkpnt) << (1)) - 1] = j; } } else { /* Sort into increasing order */ i__ = start - 1; j = endd + 1; L90: L100: --j; if (d__[j] > dmnmx) { goto L100; } L110: ++i__; if (d__[i__] < dmnmx) { goto L110; } if (i__ < j) { tmp = d__[i__]; d__[i__] = d__[j]; d__[j] = tmp; goto L90; } if (j - start > endd - j - 1) { ++stkpnt; stack[((stkpnt) << (1)) - 2] = start; stack[((stkpnt) << (1)) - 1] = j; ++stkpnt; stack[((stkpnt) << (1)) - 2] = j + 1; stack[((stkpnt) << (1)) - 1] = endd; } else { ++stkpnt; stack[((stkpnt) << (1)) - 2] = j + 1; stack[((stkpnt) << (1)) - 1] = endd; ++stkpnt; stack[((stkpnt) << (1)) - 2] = start; stack[((stkpnt) << (1)) - 1] = j; } } } if (stkpnt > 0) { goto L10; } return 0; /* End of SLASRT */ } /* slasrt_ */ /* Subroutine */ int slassq_(integer *n, real *x, integer *incx, real *scale, real *sumsq) { /* System generated locals */ integer i__1, i__2; real r__1; /* Local variables */ static integer ix; static real absxi; /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= SLASSQ returns the values scl and smsq such that ( scl**2 )*smsq = x( 1 )**2 +...+ x( n )**2 + ( scale**2 )*sumsq, where x( i ) = X( 1 + ( i - 1 )*INCX ). The value of sumsq is assumed to be non-negative and scl returns the value scl = max( scale, abs( x( i ) ) ). scale and sumsq must be supplied in SCALE and SUMSQ and scl and smsq are overwritten on SCALE and SUMSQ respectively. The routine makes only one pass through the vector x. Arguments ========= N (input) INTEGER The number of elements to be used from the vector X. X (input) REAL array, dimension (N) The vector for which a scaled sum of squares is computed. x( i ) = X( 1 + ( i - 1 )*INCX ), 1 <= i <= n. INCX (input) INTEGER The increment between successive values of the vector X. INCX > 0. SCALE (input/output) REAL On entry, the value scale in the equation above. On exit, SCALE is overwritten with scl , the scaling factor for the sum of squares. SUMSQ (input/output) REAL On entry, the value sumsq in the equation above. On exit, SUMSQ is overwritten with smsq , the basic sum of squares from which scl has been factored out. ===================================================================== */ /* Parameter adjustments */ --x; /* Function Body */ if (*n > 0) { i__1 = (*n - 1) * *incx + 1; i__2 = *incx; for (ix = 1; i__2 < 0 ? ix >= i__1 : ix <= i__1; ix += i__2) { if (x[ix] != 0.f) { absxi = (r__1 = x[ix], dabs(r__1)); if (*scale < absxi) { /* Computing 2nd power */ r__1 = *scale / absxi; *sumsq = *sumsq * (r__1 * r__1) + 1; *scale = absxi; } else { /* Computing 2nd power */ r__1 = absxi / *scale; *sumsq += r__1 * r__1; } } /* L10: */ } } return 0; /* End of SLASSQ */ } /* slassq_ */ /* Subroutine */ int slasv2_(real *f, real *g, real *h__, real *ssmin, real * ssmax, real *snr, real *csr, real *snl, real *csl) { /* System generated locals */ real r__1; /* Builtin functions */ double sqrt(doublereal), r_sign(real *, real *); /* Local variables */ static real a, d__, l, m, r__, s, t, fa, ga, ha, ft, gt, ht, mm, tt, clt, crt, slt, srt; static integer pmax; static real temp; static logical swap; static real tsign; static logical gasmal; extern doublereal slamch_(char *); /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University October 31, 1992 Purpose ======= SLASV2 computes the singular value decomposition of a 2-by-2 triangular matrix [ F G ] [ 0 H ]. On return, abs(SSMAX) is the larger singular value, abs(SSMIN) is the smaller singular value, and (CSL,SNL) and (CSR,SNR) are the left and right singular vectors for abs(SSMAX), giving the decomposition [ CSL SNL ] [ F G ] [ CSR -SNR ] = [ SSMAX 0 ] [-SNL CSL ] [ 0 H ] [ SNR CSR ] [ 0 SSMIN ]. Arguments ========= F (input) REAL The (1,1) element of the 2-by-2 matrix. G (input) REAL The (1,2) element of the 2-by-2 matrix. H (input) REAL The (2,2) element of the 2-by-2 matrix. SSMIN (output) REAL abs(SSMIN) is the smaller singular value. SSMAX (output) REAL abs(SSMAX) is the larger singular value. SNL (output) REAL CSL (output) REAL The vector (CSL, SNL) is a unit left singular vector for the singular value abs(SSMAX). SNR (output) REAL CSR (output) REAL The vector (CSR, SNR) is a unit right singular vector for the singular value abs(SSMAX). Further Details =============== Any input parameter may be aliased with any output parameter. Barring over/underflow and assuming a guard digit in subtraction, all output quantities are correct to within a few units in the last place (ulps). In IEEE arithmetic, the code works correctly if one matrix element is infinite. Overflow will not occur unless the largest singular value itself overflows or is within a few ulps of overflow. (On machines with partial overflow, like the Cray, overflow may occur if the largest singular value is within a factor of 2 of overflow.) Underflow is harmless if underflow is gradual. Otherwise, results may correspond to a matrix modified by perturbations of size near the underflow threshold. ===================================================================== */ ft = *f; fa = dabs(ft); ht = *h__; ha = dabs(*h__); /* PMAX points to the maximum absolute element of matrix PMAX = 1 if F largest in absolute values PMAX = 2 if G largest in absolute values PMAX = 3 if H largest in absolute values */ pmax = 1; swap = ha > fa; if (swap) { pmax = 3; temp = ft; ft = ht; ht = temp; temp = fa; fa = ha; ha = temp; /* Now FA .ge. HA */ } gt = *g; ga = dabs(gt); if (ga == 0.f) { /* Diagonal matrix */ *ssmin = ha; *ssmax = fa; clt = 1.f; crt = 1.f; slt = 0.f; srt = 0.f; } else { gasmal = TRUE_; if (ga > fa) { pmax = 2; if (fa / ga < slamch_("EPS")) { /* Case of very large GA */ gasmal = FALSE_; *ssmax = ga; if (ha > 1.f) { *ssmin = fa / (ga / ha); } else { *ssmin = fa / ga * ha; } clt = 1.f; slt = ht / gt; srt = 1.f; crt = ft / gt; } } if (gasmal) { /* Normal case */ d__ = fa - ha; if (d__ == fa) { /* Copes with infinite F or H */ l = 1.f; } else { l = d__ / fa; } /* Note that 0 .le. L .le. 1 */ m = gt / ft; /* Note that abs(M) .le. 1/macheps */ t = 2.f - l; /* Note that T .ge. 1 */ mm = m * m; tt = t * t; s = sqrt(tt + mm); /* Note that 1 .le. S .le. 1 + 1/macheps */ if (l == 0.f) { r__ = dabs(m); } else { r__ = sqrt(l * l + mm); } /* Note that 0 .le. R .le. 1 + 1/macheps */ a = (s + r__) * .5f; /* Note that 1 .le. A .le. 1 + abs(M) */ *ssmin = ha / a; *ssmax = fa * a; if (mm == 0.f) { /* Note that M is very tiny */ if (l == 0.f) { t = r_sign(&c_b9647, &ft) * r_sign(&c_b1011, >); } else { t = gt / r_sign(&d__, &ft) + m / t; } } else { t = (m / (s + t) + m / (r__ + l)) * (a + 1.f); } l = sqrt(t * t + 4.f); crt = 2.f / l; srt = t / l; clt = (crt + srt * m) / a; slt = ht / ft * srt / a; } } if (swap) { *csl = srt; *snl = crt; *csr = slt; *snr = clt; } else { *csl = clt; *snl = slt; *csr = crt; *snr = srt; } /* Correct signs of SSMAX and SSMIN */ if (pmax == 1) { tsign = r_sign(&c_b1011, csr) * r_sign(&c_b1011, csl) * r_sign(& c_b1011, f); } if (pmax == 2) { tsign = r_sign(&c_b1011, snr) * r_sign(&c_b1011, csl) * r_sign(& c_b1011, g); } if (pmax == 3) { tsign = r_sign(&c_b1011, snr) * r_sign(&c_b1011, snl) * r_sign(& c_b1011, h__); } *ssmax = r_sign(ssmax, &tsign); r__1 = tsign * r_sign(&c_b1011, f) * r_sign(&c_b1011, h__); *ssmin = r_sign(ssmin, &r__1); return 0; /* End of SLASV2 */ } /* slasv2_ */ /* Subroutine */ int slaswp_(integer *n, real *a, integer *lda, integer *k1, integer *k2, integer *ipiv, integer *incx) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3, i__4; /* Local variables */ static integer i__, j, k, i1, i2, n32, ip, ix, ix0, inc; static real temp; /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= SLASWP performs a series of row interchanges on the matrix A. One row interchange is initiated for each of rows K1 through K2 of A. Arguments ========= N (input) INTEGER The number of columns of the matrix A. A (input/output) REAL array, dimension (LDA,N) On entry, the matrix of column dimension N to which the row interchanges will be applied. On exit, the permuted matrix. LDA (input) INTEGER The leading dimension of the array A. K1 (input) INTEGER The first element of IPIV for which a row interchange will be done. K2 (input) INTEGER The last element of IPIV for which a row interchange will be done. IPIV (input) INTEGER array, dimension (M*abs(INCX)) The vector of pivot indices. Only the elements in positions K1 through K2 of IPIV are accessed. IPIV(K) = L implies rows K and L are to be interchanged. INCX (input) INTEGER The increment between successive values of IPIV. If IPIV is negative, the pivots are applied in reverse order. Further Details =============== Modified by R. C. Whaley, Computer Science Dept., Univ. of Tenn., Knoxville, USA ===================================================================== Interchange row I with row IPIV(I) for each of rows K1 through K2. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --ipiv; /* Function Body */ if (*incx > 0) { ix0 = *k1; i1 = *k1; i2 = *k2; inc = 1; } else if (*incx < 0) { ix0 = (1 - *k2) * *incx + 1; i1 = *k2; i2 = *k1; inc = -1; } else { return 0; } n32 = (*n / 32) << (5); if (n32 != 0) { i__1 = n32; for (j = 1; j <= i__1; j += 32) { ix = ix0; i__2 = i2; i__3 = inc; for (i__ = i1; i__3 < 0 ? i__ >= i__2 : i__ <= i__2; i__ += i__3) { ip = ipiv[ix]; if (ip != i__) { i__4 = j + 31; for (k = j; k <= i__4; ++k) { temp = a[i__ + k * a_dim1]; a[i__ + k * a_dim1] = a[ip + k * a_dim1]; a[ip + k * a_dim1] = temp; /* L10: */ } } ix += *incx; /* L20: */ } /* L30: */ } } if (n32 != *n) { ++n32; ix = ix0; i__1 = i2; i__3 = inc; for (i__ = i1; i__3 < 0 ? i__ >= i__1 : i__ <= i__1; i__ += i__3) { ip = ipiv[ix]; if (ip != i__) { i__2 = *n; for (k = n32; k <= i__2; ++k) { temp = a[i__ + k * a_dim1]; a[i__ + k * a_dim1] = a[ip + k * a_dim1]; a[ip + k * a_dim1] = temp; /* L40: */ } } ix += *incx; /* L50: */ } } return 0; /* End of SLASWP */ } /* slaswp_ */ /* Subroutine */ int slatrd_(char *uplo, integer *n, integer *nb, real *a, integer *lda, real *e, real *tau, real *w, integer *ldw) { /* System generated locals */ integer a_dim1, a_offset, w_dim1, w_offset, i__1, i__2, i__3; /* Local variables */ static integer i__, iw; extern doublereal sdot_(integer *, real *, integer *, real *, integer *); static real alpha; extern logical lsame_(char *, char *); extern /* Subroutine */ int sscal_(integer *, real *, real *, integer *), sgemv_(char *, integer *, integer *, real *, real *, integer *, real *, integer *, real *, real *, integer *), saxpy_( integer *, real *, real *, integer *, real *, integer *), ssymv_( char *, integer *, real *, real *, integer *, real *, integer *, real *, real *, integer *), slarfg_(integer *, real *, real *, integer *, real *); /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University October 31, 1992 Purpose ======= SLATRD reduces NB rows and columns of a real symmetric matrix A to symmetric tridiagonal form by an orthogonal similarity transformation Q' * A * Q, and returns the matrices V and W which are needed to apply the transformation to the unreduced part of A. If UPLO = 'U', SLATRD reduces the last NB rows and columns of a matrix, of which the upper triangle is supplied; if UPLO = 'L', SLATRD reduces the first NB rows and columns of a matrix, of which the lower triangle is supplied. This is an auxiliary routine called by SSYTRD. Arguments ========= UPLO (input) CHARACTER Specifies whether the upper or lower triangular part of the symmetric matrix A is stored: = 'U': Upper triangular = 'L': Lower triangular N (input) INTEGER The order of the matrix A. NB (input) INTEGER The number of rows and columns to be reduced. A (input/output) REAL 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, and the strictly lower triangular part of A is not referenced. If UPLO = 'L', the leading n-by-n lower triangular part of A contains the lower triangular part of the matrix A, and the strictly upper triangular part of A is not referenced. On exit: if UPLO = 'U', the last NB columns have been reduced to tridiagonal form, with the diagonal elements overwriting the diagonal elements of A; the elements above the diagonal with the array TAU, represent the orthogonal matrix Q as a product of elementary reflectors; if UPLO = 'L', the first NB columns have been reduced to tridiagonal form, with the diagonal elements overwriting the diagonal elements of A; the elements below the diagonal with the array TAU, represent the orthogonal matrix Q as a product of elementary reflectors. See Further Details. LDA (input) INTEGER The leading dimension of the array A. LDA >= (1,N). E (output) REAL array, dimension (N-1) If UPLO = 'U', E(n-nb:n-1) contains the superdiagonal elements of the last NB columns of the reduced matrix; if UPLO = 'L', E(1:nb) contains the subdiagonal elements of the first NB columns of the reduced matrix. TAU (output) REAL array, dimension (N-1) The scalar factors of the elementary reflectors, stored in TAU(n-nb:n-1) if UPLO = 'U', and in TAU(1:nb) if UPLO = 'L'. See Further Details. W (output) REAL array, dimension (LDW,NB) The n-by-nb matrix W required to update the unreduced part of A. LDW (input) INTEGER The leading dimension of the array W. LDW >= max(1,N). Further Details =============== If UPLO = 'U', the matrix Q is represented as a product of elementary reflectors Q = H(n) H(n-1) . . . H(n-nb+1). Each H(i) has the form H(i) = I - tau * v * v' where tau is a real scalar, and v is a real vector with v(i:n) = 0 and v(i-1) = 1; v(1:i-1) is stored on exit in A(1:i-1,i), and tau in TAU(i-1). If UPLO = 'L', the matrix Q is represented as a product of elementary reflectors Q = H(1) H(2) . . . H(nb). Each H(i) has the form H(i) = I - tau * v * v' where tau is a real scalar, and v is a real vector with v(1:i) = 0 and v(i+1) = 1; v(i+1:n) is stored on exit in A(i+1:n,i), and tau in TAU(i). The elements of the vectors v together form the n-by-nb matrix V which is needed, with W, to apply the transformation to the unreduced part of the matrix, using a symmetric rank-2k update of the form: A := A - V*W' - W*V'. The contents of A on exit are illustrated by the following examples with n = 5 and nb = 2: if UPLO = 'U': if UPLO = 'L': ( a a a v4 v5 ) ( d ) ( a a v4 v5 ) ( 1 d ) ( a 1 v5 ) ( v1 1 a ) ( d 1 ) ( v1 v2 a a ) ( d ) ( v1 v2 a a a ) where d denotes a diagonal element of the reduced matrix, a denotes an element of the original matrix that is unchanged, and vi denotes an element of the vector defining H(i). ===================================================================== Quick return if possible */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --e; --tau; w_dim1 = *ldw; w_offset = 1 + w_dim1; w -= w_offset; /* Function Body */ if (*n <= 0) { return 0; } if (lsame_(uplo, "U")) { /* Reduce last NB columns of upper triangle */ i__1 = *n - *nb + 1; for (i__ = *n; i__ >= i__1; --i__) { iw = i__ - *n + *nb; if (i__ < *n) { /* Update A(1:i,i) */ i__2 = *n - i__; sgemv_("No transpose", &i__, &i__2, &c_b1290, &a[(i__ + 1) * a_dim1 + 1], lda, &w[i__ + (iw + 1) * w_dim1], ldw, & c_b1011, &a[i__ * a_dim1 + 1], &c__1); i__2 = *n - i__; sgemv_("No transpose", &i__, &i__2, &c_b1290, &w[(iw + 1) * w_dim1 + 1], ldw, &a[i__ + (i__ + 1) * a_dim1], lda, & c_b1011, &a[i__ * a_dim1 + 1], &c__1); } if (i__ > 1) { /* Generate elementary reflector H(i) to annihilate A(1:i-2,i) */ i__2 = i__ - 1; slarfg_(&i__2, &a[i__ - 1 + i__ * a_dim1], &a[i__ * a_dim1 + 1], &c__1, &tau[i__ - 1]); e[i__ - 1] = a[i__ - 1 + i__ * a_dim1]; a[i__ - 1 + i__ * a_dim1] = 1.f; /* Compute W(1:i-1,i) */ i__2 = i__ - 1; ssymv_("Upper", &i__2, &c_b1011, &a[a_offset], lda, &a[i__ * a_dim1 + 1], &c__1, &c_b320, &w[iw * w_dim1 + 1], & c__1); if (i__ < *n) { i__2 = i__ - 1; i__3 = *n - i__; sgemv_("Transpose", &i__2, &i__3, &c_b1011, &w[(iw + 1) * w_dim1 + 1], ldw, &a[i__ * a_dim1 + 1], &c__1, & c_b320, &w[i__ + 1 + iw * w_dim1], &c__1); i__2 = i__ - 1; i__3 = *n - i__; sgemv_("No transpose", &i__2, &i__3, &c_b1290, &a[(i__ + 1) * a_dim1 + 1], lda, &w[i__ + 1 + iw * w_dim1], &c__1, &c_b1011, &w[iw * w_dim1 + 1], &c__1); i__2 = i__ - 1; i__3 = *n - i__; sgemv_("Transpose", &i__2, &i__3, &c_b1011, &a[(i__ + 1) * a_dim1 + 1], lda, &a[i__ * a_dim1 + 1], &c__1, & c_b320, &w[i__ + 1 + iw * w_dim1], &c__1); i__2 = i__ - 1; i__3 = *n - i__; sgemv_("No transpose", &i__2, &i__3, &c_b1290, &w[(iw + 1) * w_dim1 + 1], ldw, &w[i__ + 1 + iw * w_dim1], & c__1, &c_b1011, &w[iw * w_dim1 + 1], &c__1); } i__2 = i__ - 1; sscal_(&i__2, &tau[i__ - 1], &w[iw * w_dim1 + 1], &c__1); i__2 = i__ - 1; alpha = tau[i__ - 1] * -.5f * sdot_(&i__2, &w[iw * w_dim1 + 1] , &c__1, &a[i__ * a_dim1 + 1], &c__1); i__2 = i__ - 1; saxpy_(&i__2, &alpha, &a[i__ * a_dim1 + 1], &c__1, &w[iw * w_dim1 + 1], &c__1); } /* L10: */ } } else { /* Reduce first NB columns of lower triangle */ i__1 = *nb; for (i__ = 1; i__ <= i__1; ++i__) { /* Update A(i:n,i) */ i__2 = *n - i__ + 1; i__3 = i__ - 1; sgemv_("No transpose", &i__2, &i__3, &c_b1290, &a[i__ + a_dim1], lda, &w[i__ + w_dim1], ldw, &c_b1011, &a[i__ + i__ * a_dim1], &c__1); i__2 = *n - i__ + 1; i__3 = i__ - 1; sgemv_("No transpose", &i__2, &i__3, &c_b1290, &w[i__ + w_dim1], ldw, &a[i__ + a_dim1], lda, &c_b1011, &a[i__ + i__ * a_dim1], &c__1); if (i__ < *n) { /* Generate elementary reflector H(i) to annihilate A(i+2:n,i) */ i__2 = *n - i__; /* Computing MIN */ i__3 = i__ + 2; slarfg_(&i__2, &a[i__ + 1 + i__ * a_dim1], &a[min(i__3,*n) + i__ * a_dim1], &c__1, &tau[i__]); e[i__] = a[i__ + 1 + i__ * a_dim1]; a[i__ + 1 + i__ * a_dim1] = 1.f; /* Compute W(i+1:n,i) */ i__2 = *n - i__; ssymv_("Lower", &i__2, &c_b1011, &a[i__ + 1 + (i__ + 1) * a_dim1], lda, &a[i__ + 1 + i__ * a_dim1], &c__1, & c_b320, &w[i__ + 1 + i__ * w_dim1], &c__1); i__2 = *n - i__; i__3 = i__ - 1; sgemv_("Transpose", &i__2, &i__3, &c_b1011, &w[i__ + 1 + w_dim1], ldw, &a[i__ + 1 + i__ * a_dim1], &c__1, & c_b320, &w[i__ * w_dim1 + 1], &c__1); i__2 = *n - i__; i__3 = i__ - 1; sgemv_("No transpose", &i__2, &i__3, &c_b1290, &a[i__ + 1 + a_dim1], lda, &w[i__ * w_dim1 + 1], &c__1, &c_b1011, & w[i__ + 1 + i__ * w_dim1], &c__1); i__2 = *n - i__; i__3 = i__ - 1; sgemv_("Transpose", &i__2, &i__3, &c_b1011, &a[i__ + 1 + a_dim1], lda, &a[i__ + 1 + i__ * a_dim1], &c__1, & c_b320, &w[i__ * w_dim1 + 1], &c__1); i__2 = *n - i__; i__3 = i__ - 1; sgemv_("No transpose", &i__2, &i__3, &c_b1290, &w[i__ + 1 + w_dim1], ldw, &w[i__ * w_dim1 + 1], &c__1, &c_b1011, & w[i__ + 1 + i__ * w_dim1], &c__1); i__2 = *n - i__; sscal_(&i__2, &tau[i__], &w[i__ + 1 + i__ * w_dim1], &c__1); i__2 = *n - i__; alpha = tau[i__] * -.5f * sdot_(&i__2, &w[i__ + 1 + i__ * w_dim1], &c__1, &a[i__ + 1 + i__ * a_dim1], &c__1); i__2 = *n - i__; saxpy_(&i__2, &alpha, &a[i__ + 1 + i__ * a_dim1], &c__1, &w[ i__ + 1 + i__ * w_dim1], &c__1); } /* L20: */ } } return 0; /* End of SLATRD */ } /* slatrd_ */ /* Subroutine */ int slauu2_(char *uplo, integer *n, real *a, integer *lda, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3; /* Local variables */ static integer i__; static real aii; extern doublereal sdot_(integer *, real *, integer *, real *, integer *); extern logical lsame_(char *, char *); extern /* Subroutine */ int sscal_(integer *, real *, real *, integer *), sgemv_(char *, integer *, integer *, real *, real *, integer *, real *, integer *, real *, real *, integer *); static logical upper; extern /* Subroutine */ int xerbla_(char *, integer *); /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University February 29, 1992 Purpose ======= SLAUU2 computes the product U * U' or L' * L, where the triangular factor U or L is stored in the upper or lower triangular part of the array A. If UPLO = 'U' or 'u' then the upper triangle of the result is stored, overwriting the factor U in A. If UPLO = 'L' or 'l' then the lower triangle of the result is stored, overwriting the factor L in A. This is the unblocked form of the algorithm, calling Level 2 BLAS. Arguments ========= UPLO (input) CHARACTER*1 Specifies whether the triangular factor stored in the array A is upper or lower triangular: = 'U': Upper triangular = 'L': Lower triangular N (input) INTEGER The order of the triangular factor U or L. N >= 0. A (input/output) REAL array, dimension (LDA,N) On entry, the triangular factor U or L. On exit, if UPLO = 'U', the upper triangle of A is overwritten with the upper triangle of the product U * U'; if UPLO = 'L', the lower triangle of A is overwritten with the lower triangle of the product L' * L. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,N). INFO (output) INTEGER = 0: successful exit < 0: if INFO = -k, the k-th argument had an illegal value ===================================================================== Test the input parameters. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; /* Function Body */ *info = 0; upper = lsame_(uplo, "U"); if (! upper && ! lsame_(uplo, "L")) { *info = -1; } else if (*n < 0) { *info = -2; } else if (*lda < max(1,*n)) { *info = -4; } if (*info != 0) { i__1 = -(*info); xerbla_("SLAUU2", &i__1); return 0; } /* Quick return if possible */ if (*n == 0) { return 0; } if (upper) { /* Compute the product U * U'. */ i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { aii = a[i__ + i__ * a_dim1]; if (i__ < *n) { i__2 = *n - i__ + 1; a[i__ + i__ * a_dim1] = sdot_(&i__2, &a[i__ + i__ * a_dim1], lda, &a[i__ + i__ * a_dim1], lda); i__2 = i__ - 1; i__3 = *n - i__; sgemv_("No transpose", &i__2, &i__3, &c_b1011, &a[(i__ + 1) * a_dim1 + 1], lda, &a[i__ + (i__ + 1) * a_dim1], lda, & aii, &a[i__ * a_dim1 + 1], &c__1); } else { sscal_(&i__, &aii, &a[i__ * a_dim1 + 1], &c__1); } /* L10: */ } } else { /* Compute the product L' * L. */ i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { aii = a[i__ + i__ * a_dim1]; if (i__ < *n) { i__2 = *n - i__ + 1; a[i__ + i__ * a_dim1] = sdot_(&i__2, &a[i__ + i__ * a_dim1], & c__1, &a[i__ + i__ * a_dim1], &c__1); i__2 = *n - i__; i__3 = i__ - 1; sgemv_("Transpose", &i__2, &i__3, &c_b1011, &a[i__ + 1 + a_dim1], lda, &a[i__ + 1 + i__ * a_dim1], &c__1, &aii, &a[i__ + a_dim1], lda); } else { sscal_(&i__, &aii, &a[i__ + a_dim1], lda); } /* L20: */ } } return 0; /* End of SLAUU2 */ } /* slauu2_ */ /* Subroutine */ int slauum_(char *uplo, integer *n, real *a, integer *lda, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3, i__4; /* Local variables */ static integer i__, ib, nb; extern logical lsame_(char *, char *); extern /* Subroutine */ int sgemm_(char *, char *, integer *, integer *, integer *, real *, real *, integer *, real *, integer *, real *, real *, integer *); static logical upper; extern /* Subroutine */ int strmm_(char *, char *, char *, char *, integer *, integer *, real *, real *, integer *, real *, integer * ), ssyrk_(char *, char *, integer *, integer *, real *, real *, integer *, real *, real *, integer * ), slauu2_(char *, integer *, real *, integer *, integer *), xerbla_(char *, integer *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University February 29, 1992 Purpose ======= SLAUUM computes the product U * U' or L' * L, where the triangular factor U or L is stored in the upper or lower triangular part of the array A. If UPLO = 'U' or 'u' then the upper triangle of the result is stored, overwriting the factor U in A. If UPLO = 'L' or 'l' then the lower triangle of the result is stored, overwriting the factor L in A. This is the blocked form of the algorithm, calling Level 3 BLAS. Arguments ========= UPLO (input) CHARACTER*1 Specifies whether the triangular factor stored in the array A is upper or lower triangular: = 'U': Upper triangular = 'L': Lower triangular N (input) INTEGER The order of the triangular factor U or L. N >= 0. A (input/output) REAL array, dimension (LDA,N) On entry, the triangular factor U or L. On exit, if UPLO = 'U', the upper triangle of A is overwritten with the upper triangle of the product U * U'; if UPLO = 'L', the lower triangle of A is overwritten with the lower triangle of the product L' * L. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,N). INFO (output) INTEGER = 0: successful exit < 0: if INFO = -k, the k-th argument had an illegal value ===================================================================== Test the input parameters. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; /* Function Body */ *info = 0; upper = lsame_(uplo, "U"); if (! upper && ! lsame_(uplo, "L")) { *info = -1; } else if (*n < 0) { *info = -2; } else if (*lda < max(1,*n)) { *info = -4; } if (*info != 0) { i__1 = -(*info); xerbla_("SLAUUM", &i__1); return 0; } /* Quick return if possible */ if (*n == 0) { return 0; } /* Determine the block size for this environment. */ nb = ilaenv_(&c__1, "SLAUUM", uplo, n, &c_n1, &c_n1, &c_n1, (ftnlen)6, ( ftnlen)1); if ((nb <= 1) || (nb >= *n)) { /* Use unblocked code */ slauu2_(uplo, n, &a[a_offset], lda, info); } else { /* Use blocked code */ if (upper) { /* Compute the product U * U'. */ i__1 = *n; i__2 = nb; for (i__ = 1; i__2 < 0 ? i__ >= i__1 : i__ <= i__1; i__ += i__2) { /* Computing MIN */ i__3 = nb, i__4 = *n - i__ + 1; ib = min(i__3,i__4); i__3 = i__ - 1; strmm_("Right", "Upper", "Transpose", "Non-unit", &i__3, &ib, &c_b1011, &a[i__ + i__ * a_dim1], lda, &a[i__ * a_dim1 + 1], lda); slauu2_("Upper", &ib, &a[i__ + i__ * a_dim1], lda, info); if (i__ + ib <= *n) { i__3 = i__ - 1; i__4 = *n - i__ - ib + 1; sgemm_("No transpose", "Transpose", &i__3, &ib, &i__4, & c_b1011, &a[(i__ + ib) * a_dim1 + 1], lda, &a[i__ + (i__ + ib) * a_dim1], lda, &c_b1011, &a[i__ * a_dim1 + 1], lda); i__3 = *n - i__ - ib + 1; ssyrk_("Upper", "No transpose", &ib, &i__3, &c_b1011, &a[ i__ + (i__ + ib) * a_dim1], lda, &c_b1011, &a[i__ + i__ * a_dim1], lda); } /* L10: */ } } else { /* Compute the product L' * L. */ i__2 = *n; i__1 = nb; for (i__ = 1; i__1 < 0 ? i__ >= i__2 : i__ <= i__2; i__ += i__1) { /* Computing MIN */ i__3 = nb, i__4 = *n - i__ + 1; ib = min(i__3,i__4); i__3 = i__ - 1; strmm_("Left", "Lower", "Transpose", "Non-unit", &ib, &i__3, & c_b1011, &a[i__ + i__ * a_dim1], lda, &a[i__ + a_dim1] , lda); slauu2_("Lower", &ib, &a[i__ + i__ * a_dim1], lda, info); if (i__ + ib <= *n) { i__3 = i__ - 1; i__4 = *n - i__ - ib + 1; sgemm_("Transpose", "No transpose", &ib, &i__3, &i__4, & c_b1011, &a[i__ + ib + i__ * a_dim1], lda, &a[i__ + ib + a_dim1], lda, &c_b1011, &a[i__ + a_dim1], lda); i__3 = *n - i__ - ib + 1; ssyrk_("Lower", "Transpose", &ib, &i__3, &c_b1011, &a[i__ + ib + i__ * a_dim1], lda, &c_b1011, &a[i__ + i__ * a_dim1], lda); } /* L20: */ } } } return 0; /* End of SLAUUM */ } /* slauum_ */ /* Subroutine */ int sorg2r_(integer *m, integer *n, integer *k, real *a, integer *lda, real *tau, real *work, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2; real r__1; /* Local variables */ static integer i__, j, l; extern /* Subroutine */ int sscal_(integer *, real *, real *, integer *), slarf_(char *, integer *, integer *, real *, integer *, real *, real *, integer *, real *), xerbla_(char *, integer *); /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University February 29, 1992 Purpose ======= SORG2R generates an m by n real matrix Q with orthonormal columns, which is defined as the first n columns of a product of k elementary reflectors of order m Q = H(1) H(2) . . . H(k) as returned by SGEQRF. Arguments ========= M (input) INTEGER The number of rows of the matrix Q. M >= 0. N (input) INTEGER The number of columns of the matrix Q. M >= N >= 0. K (input) INTEGER The number of elementary reflectors whose product defines the matrix Q. N >= K >= 0. A (input/output) REAL array, dimension (LDA,N) On entry, the i-th column must contain the vector which defines the elementary reflector H(i), for i = 1,2,...,k, as returned by SGEQRF in the first k columns of its array argument A. On exit, the m-by-n matrix Q. LDA (input) INTEGER The first dimension of the array A. LDA >= max(1,M). TAU (input) REAL array, dimension (K) TAU(i) must contain the scalar factor of the elementary reflector H(i), as returned by SGEQRF. WORK (workspace) REAL array, dimension (N) INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument has an illegal value ===================================================================== Test the input arguments */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --tau; --work; /* Function Body */ *info = 0; if (*m < 0) { *info = -1; } else if ((*n < 0) || (*n > *m)) { *info = -2; } else if ((*k < 0) || (*k > *n)) { *info = -3; } else if (*lda < max(1,*m)) { *info = -5; } if (*info != 0) { i__1 = -(*info); xerbla_("SORG2R", &i__1); return 0; } /* Quick return if possible */ if (*n <= 0) { return 0; } /* Initialise columns k+1:n to columns of the unit matrix */ i__1 = *n; for (j = *k + 1; j <= i__1; ++j) { i__2 = *m; for (l = 1; l <= i__2; ++l) { a[l + j * a_dim1] = 0.f; /* L10: */ } a[j + j * a_dim1] = 1.f; /* L20: */ } for (i__ = *k; i__ >= 1; --i__) { /* Apply H(i) to A(i:m,i:n) from the left */ if (i__ < *n) { a[i__ + i__ * a_dim1] = 1.f; i__1 = *m - i__ + 1; i__2 = *n - i__; slarf_("Left", &i__1, &i__2, &a[i__ + i__ * a_dim1], &c__1, &tau[ i__], &a[i__ + (i__ + 1) * a_dim1], lda, &work[1]); } if (i__ < *m) { i__1 = *m - i__; r__1 = -tau[i__]; sscal_(&i__1, &r__1, &a[i__ + 1 + i__ * a_dim1], &c__1); } a[i__ + i__ * a_dim1] = 1.f - tau[i__]; /* Set A(1:i-1,i) to zero */ i__1 = i__ - 1; for (l = 1; l <= i__1; ++l) { a[l + i__ * a_dim1] = 0.f; /* L30: */ } /* L40: */ } return 0; /* End of SORG2R */ } /* sorg2r_ */ /* Subroutine */ int sorgbr_(char *vect, integer *m, integer *n, integer *k, real *a, integer *lda, real *tau, real *work, integer *lwork, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3; /* Local variables */ static integer i__, j, nb, mn; extern logical lsame_(char *, char *); static integer iinfo; static logical wantq; extern /* Subroutine */ int xerbla_(char *, integer *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); extern /* Subroutine */ int sorglq_(integer *, integer *, integer *, real *, integer *, real *, real *, integer *, integer *), sorgqr_( integer *, integer *, integer *, real *, integer *, real *, real * , integer *, integer *); static integer lwkopt; static logical lquery; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= SORGBR generates one of the real orthogonal matrices Q or P**T determined by SGEBRD when reducing a real matrix A to bidiagonal form: A = Q * B * P**T. Q and P**T are defined as products of elementary reflectors H(i) or G(i) respectively. If VECT = 'Q', A is assumed to have been an M-by-K matrix, and Q is of order M: if m >= k, Q = H(1) H(2) . . . H(k) and SORGBR returns the first n columns of Q, where m >= n >= k; if m < k, Q = H(1) H(2) . . . H(m-1) and SORGBR returns Q as an M-by-M matrix. If VECT = 'P', A is assumed to have been a K-by-N matrix, and P**T is of order N: if k < n, P**T = G(k) . . . G(2) G(1) and SORGBR returns the first m rows of P**T, where n >= m >= k; if k >= n, P**T = G(n-1) . . . G(2) G(1) and SORGBR returns P**T as an N-by-N matrix. Arguments ========= VECT (input) CHARACTER*1 Specifies whether the matrix Q or the matrix P**T is required, as defined in the transformation applied by SGEBRD: = 'Q': generate Q; = 'P': generate P**T. M (input) INTEGER The number of rows of the matrix Q or P**T to be returned. M >= 0. N (input) INTEGER The number of columns of the matrix Q or P**T to be returned. N >= 0. If VECT = 'Q', M >= N >= min(M,K); if VECT = 'P', N >= M >= min(N,K). K (input) INTEGER If VECT = 'Q', the number of columns in the original M-by-K matrix reduced by SGEBRD. If VECT = 'P', the number of rows in the original K-by-N matrix reduced by SGEBRD. K >= 0. A (input/output) REAL array, dimension (LDA,N) On entry, the vectors which define the elementary reflectors, as returned by SGEBRD. On exit, the M-by-N matrix Q or P**T. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,M). TAU (input) REAL array, dimension (min(M,K)) if VECT = 'Q' (min(N,K)) if VECT = 'P' TAU(i) must contain the scalar factor of the elementary reflector H(i) or G(i), which determines Q or P**T, as returned by SGEBRD in its array argument TAUQ or TAUP. WORK (workspace/output) REAL array, dimension (LWORK) On exit, if INFO = 0, WORK(1) returns the optimal LWORK. LWORK (input) INTEGER The dimension of the array WORK. LWORK >= max(1,min(M,N)). For optimum performance LWORK >= min(M,N)*NB, where NB is the optimal blocksize. If LWORK = -1, then a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued by XERBLA. INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value ===================================================================== Test the input arguments */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --tau; --work; /* Function Body */ *info = 0; wantq = lsame_(vect, "Q"); mn = min(*m,*n); lquery = *lwork == -1; if (! wantq && ! lsame_(vect, "P")) { *info = -1; } else if (*m < 0) { *info = -2; } else if (((*n < 0) || (wantq && ((*n > *m) || (*n < min(*m,*k))))) || (! wantq && ((*m > *n) || (*m < min(*n,*k))))) { *info = -3; } else if (*k < 0) { *info = -4; } else if (*lda < max(1,*m)) { *info = -6; } else if (*lwork < max(1,mn) && ! lquery) { *info = -9; } if (*info == 0) { if (wantq) { nb = ilaenv_(&c__1, "SORGQR", " ", m, n, k, &c_n1, (ftnlen)6, ( ftnlen)1); } else { nb = ilaenv_(&c__1, "SORGLQ", " ", m, n, k, &c_n1, (ftnlen)6, ( ftnlen)1); } lwkopt = max(1,mn) * nb; work[1] = (real) lwkopt; } if (*info != 0) { i__1 = -(*info); xerbla_("SORGBR", &i__1); return 0; } else if (lquery) { return 0; } /* Quick return if possible */ if ((*m == 0) || (*n == 0)) { work[1] = 1.f; return 0; } if (wantq) { /* Form Q, determined by a call to SGEBRD to reduce an m-by-k matrix */ if (*m >= *k) { /* If m >= k, assume m >= n >= k */ sorgqr_(m, n, k, &a[a_offset], lda, &tau[1], &work[1], lwork, & iinfo); } else { /* If m < k, assume m = n Shift the vectors which define the elementary reflectors one column to the right, and set the first row and column of Q to those of the unit matrix */ for (j = *m; j >= 2; --j) { a[j * a_dim1 + 1] = 0.f; i__1 = *m; for (i__ = j + 1; i__ <= i__1; ++i__) { a[i__ + j * a_dim1] = a[i__ + (j - 1) * a_dim1]; /* L10: */ } /* L20: */ } a[a_dim1 + 1] = 1.f; i__1 = *m; for (i__ = 2; i__ <= i__1; ++i__) { a[i__ + a_dim1] = 0.f; /* L30: */ } if (*m > 1) { /* Form Q(2:m,2:m) */ i__1 = *m - 1; i__2 = *m - 1; i__3 = *m - 1; sorgqr_(&i__1, &i__2, &i__3, &a[((a_dim1) << (1)) + 2], lda, & tau[1], &work[1], lwork, &iinfo); } } } else { /* Form P', determined by a call to SGEBRD to reduce a k-by-n matrix */ if (*k < *n) { /* If k < n, assume k <= m <= n */ sorglq_(m, n, k, &a[a_offset], lda, &tau[1], &work[1], lwork, & iinfo); } else { /* If k >= n, assume m = n Shift the vectors which define the elementary reflectors one row downward, and set the first row and column of P' to those of the unit matrix */ a[a_dim1 + 1] = 1.f; i__1 = *n; for (i__ = 2; i__ <= i__1; ++i__) { a[i__ + a_dim1] = 0.f; /* L40: */ } i__1 = *n; for (j = 2; j <= i__1; ++j) { for (i__ = j - 1; i__ >= 2; --i__) { a[i__ + j * a_dim1] = a[i__ - 1 + j * a_dim1]; /* L50: */ } a[j * a_dim1 + 1] = 0.f; /* L60: */ } if (*n > 1) { /* Form P'(2:n,2:n) */ i__1 = *n - 1; i__2 = *n - 1; i__3 = *n - 1; sorglq_(&i__1, &i__2, &i__3, &a[((a_dim1) << (1)) + 2], lda, & tau[1], &work[1], lwork, &iinfo); } } } work[1] = (real) lwkopt; return 0; /* End of SORGBR */ } /* sorgbr_ */ /* Subroutine */ int sorghr_(integer *n, integer *ilo, integer *ihi, real *a, integer *lda, real *tau, real *work, integer *lwork, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2; /* Local variables */ static integer i__, j, nb, nh, iinfo; extern /* Subroutine */ int xerbla_(char *, integer *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); extern /* Subroutine */ int sorgqr_(integer *, integer *, integer *, real *, integer *, real *, real *, integer *, integer *); static integer lwkopt; static logical lquery; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= SORGHR generates a real orthogonal matrix Q which is defined as the product of IHI-ILO elementary reflectors of order N, as returned by SGEHRD: Q = H(ilo) H(ilo+1) . . . H(ihi-1). Arguments ========= N (input) INTEGER The order of the matrix Q. N >= 0. ILO (input) INTEGER IHI (input) INTEGER ILO and IHI must have the same values as in the previous call of SGEHRD. Q is equal to the unit matrix except in the submatrix Q(ilo+1:ihi,ilo+1:ihi). 1 <= ILO <= IHI <= N, if N > 0; ILO=1 and IHI=0, if N=0. A (input/output) REAL array, dimension (LDA,N) On entry, the vectors which define the elementary reflectors, as returned by SGEHRD. On exit, the N-by-N orthogonal matrix Q. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,N). TAU (input) REAL array, dimension (N-1) TAU(i) must contain the scalar factor of the elementary reflector H(i), as returned by SGEHRD. WORK (workspace/output) REAL array, dimension (LWORK) On exit, if INFO = 0, WORK(1) returns the optimal LWORK. LWORK (input) INTEGER The dimension of the array WORK. LWORK >= IHI-ILO. For optimum performance LWORK >= (IHI-ILO)*NB, where NB is the optimal blocksize. If LWORK = -1, then a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued by XERBLA. INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value ===================================================================== Test the input arguments */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --tau; --work; /* Function Body */ *info = 0; nh = *ihi - *ilo; lquery = *lwork == -1; if (*n < 0) { *info = -1; } else if ((*ilo < 1) || (*ilo > max(1,*n))) { *info = -2; } else if ((*ihi < min(*ilo,*n)) || (*ihi > *n)) { *info = -3; } else if (*lda < max(1,*n)) { *info = -5; } else if (*lwork < max(1,nh) && ! lquery) { *info = -8; } if (*info == 0) { nb = ilaenv_(&c__1, "SORGQR", " ", &nh, &nh, &nh, &c_n1, (ftnlen)6, ( ftnlen)1); lwkopt = max(1,nh) * nb; work[1] = (real) lwkopt; } if (*info != 0) { i__1 = -(*info); xerbla_("SORGHR", &i__1); return 0; } else if (lquery) { return 0; } /* Quick return if possible */ if (*n == 0) { work[1] = 1.f; return 0; } /* Shift the vectors which define the elementary reflectors one column to the right, and set the first ilo and the last n-ihi rows and columns to those of the unit matrix */ i__1 = *ilo + 1; for (j = *ihi; j >= i__1; --j) { i__2 = j - 1; for (i__ = 1; i__ <= i__2; ++i__) { a[i__ + j * a_dim1] = 0.f; /* L10: */ } i__2 = *ihi; for (i__ = j + 1; i__ <= i__2; ++i__) { a[i__ + j * a_dim1] = a[i__ + (j - 1) * a_dim1]; /* L20: */ } i__2 = *n; for (i__ = *ihi + 1; i__ <= i__2; ++i__) { a[i__ + j * a_dim1] = 0.f; /* L30: */ } /* L40: */ } i__1 = *ilo; for (j = 1; j <= i__1; ++j) { i__2 = *n; for (i__ = 1; i__ <= i__2; ++i__) { a[i__ + j * a_dim1] = 0.f; /* L50: */ } a[j + j * a_dim1] = 1.f; /* L60: */ } i__1 = *n; for (j = *ihi + 1; j <= i__1; ++j) { i__2 = *n; for (i__ = 1; i__ <= i__2; ++i__) { a[i__ + j * a_dim1] = 0.f; /* L70: */ } a[j + j * a_dim1] = 1.f; /* L80: */ } if (nh > 0) { /* Generate Q(ilo+1:ihi,ilo+1:ihi) */ sorgqr_(&nh, &nh, &nh, &a[*ilo + 1 + (*ilo + 1) * a_dim1], lda, &tau[* ilo], &work[1], lwork, &iinfo); } work[1] = (real) lwkopt; return 0; /* End of SORGHR */ } /* sorghr_ */ /* Subroutine */ int sorgl2_(integer *m, integer *n, integer *k, real *a, integer *lda, real *tau, real *work, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2; real r__1; /* Local variables */ static integer i__, j, l; extern /* Subroutine */ int sscal_(integer *, real *, real *, integer *), slarf_(char *, integer *, integer *, real *, integer *, real *, real *, integer *, real *), xerbla_(char *, integer *); /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= SORGL2 generates an m by n real matrix Q with orthonormal rows, which is defined as the first m rows of a product of k elementary reflectors of order n Q = H(k) . . . H(2) H(1) as returned by SGELQF. Arguments ========= M (input) INTEGER The number of rows of the matrix Q. M >= 0. N (input) INTEGER The number of columns of the matrix Q. N >= M. K (input) INTEGER The number of elementary reflectors whose product defines the matrix Q. M >= K >= 0. A (input/output) REAL array, dimension (LDA,N) On entry, the i-th row must contain the vector which defines the elementary reflector H(i), for i = 1,2,...,k, as returned by SGELQF in the first k rows of its array argument A. On exit, the m-by-n matrix Q. LDA (input) INTEGER The first dimension of the array A. LDA >= max(1,M). TAU (input) REAL array, dimension (K) TAU(i) must contain the scalar factor of the elementary reflector H(i), as returned by SGELQF. WORK (workspace) REAL array, dimension (M) INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument has an illegal value ===================================================================== Test the input arguments */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --tau; --work; /* Function Body */ *info = 0; if (*m < 0) { *info = -1; } else if (*n < *m) { *info = -2; } else if ((*k < 0) || (*k > *m)) { *info = -3; } else if (*lda < max(1,*m)) { *info = -5; } if (*info != 0) { i__1 = -(*info); xerbla_("SORGL2", &i__1); return 0; } /* Quick return if possible */ if (*m <= 0) { return 0; } if (*k < *m) { /* Initialise rows k+1:m to rows of the unit matrix */ i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (l = *k + 1; l <= i__2; ++l) { a[l + j * a_dim1] = 0.f; /* L10: */ } if (j > *k && j <= *m) { a[j + j * a_dim1] = 1.f; } /* L20: */ } } for (i__ = *k; i__ >= 1; --i__) { /* Apply H(i) to A(i:m,i:n) from the right */ if (i__ < *n) { if (i__ < *m) { a[i__ + i__ * a_dim1] = 1.f; i__1 = *m - i__; i__2 = *n - i__ + 1; slarf_("Right", &i__1, &i__2, &a[i__ + i__ * a_dim1], lda, & tau[i__], &a[i__ + 1 + i__ * a_dim1], lda, &work[1]); } i__1 = *n - i__; r__1 = -tau[i__]; sscal_(&i__1, &r__1, &a[i__ + (i__ + 1) * a_dim1], lda); } a[i__ + i__ * a_dim1] = 1.f - tau[i__]; /* Set A(i,1:i-1) to zero */ i__1 = i__ - 1; for (l = 1; l <= i__1; ++l) { a[i__ + l * a_dim1] = 0.f; /* L30: */ } /* L40: */ } return 0; /* End of SORGL2 */ } /* sorgl2_ */ /* Subroutine */ int sorglq_(integer *m, integer *n, integer *k, real *a, integer *lda, real *tau, real *work, integer *lwork, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3; /* Local variables */ static integer i__, j, l, ib, nb, ki, kk, nx, iws, nbmin, iinfo; extern /* Subroutine */ int sorgl2_(integer *, integer *, integer *, real *, integer *, real *, real *, integer *), slarfb_(char *, char *, char *, char *, integer *, integer *, integer *, real *, integer * , real *, integer *, real *, integer *, real *, integer *), xerbla_(char *, integer *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); extern /* Subroutine */ int slarft_(char *, char *, integer *, integer *, real *, integer *, real *, real *, integer *); static integer ldwork, lwkopt; static logical lquery; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= SORGLQ generates an M-by-N real matrix Q with orthonormal rows, which is defined as the first M rows of a product of K elementary reflectors of order N Q = H(k) . . . H(2) H(1) as returned by SGELQF. Arguments ========= M (input) INTEGER The number of rows of the matrix Q. M >= 0. N (input) INTEGER The number of columns of the matrix Q. N >= M. K (input) INTEGER The number of elementary reflectors whose product defines the matrix Q. M >= K >= 0. A (input/output) REAL array, dimension (LDA,N) On entry, the i-th row must contain the vector which defines the elementary reflector H(i), for i = 1,2,...,k, as returned by SGELQF in the first k rows of its array argument A. On exit, the M-by-N matrix Q. LDA (input) INTEGER The first dimension of the array A. LDA >= max(1,M). TAU (input) REAL array, dimension (K) TAU(i) must contain the scalar factor of the elementary reflector H(i), as returned by SGELQF. WORK (workspace/output) REAL array, dimension (LWORK) On exit, if INFO = 0, WORK(1) returns the optimal LWORK. LWORK (input) INTEGER The dimension of the array WORK. LWORK >= max(1,M). For optimum performance LWORK >= M*NB, where NB is the optimal blocksize. If LWORK = -1, then a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued by XERBLA. INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument has an illegal value ===================================================================== Test the input arguments */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --tau; --work; /* Function Body */ *info = 0; nb = ilaenv_(&c__1, "SORGLQ", " ", m, n, k, &c_n1, (ftnlen)6, (ftnlen)1); lwkopt = max(1,*m) * nb; work[1] = (real) lwkopt; lquery = *lwork == -1; if (*m < 0) { *info = -1; } else if (*n < *m) { *info = -2; } else if ((*k < 0) || (*k > *m)) { *info = -3; } else if (*lda < max(1,*m)) { *info = -5; } else if (*lwork < max(1,*m) && ! lquery) { *info = -8; } if (*info != 0) { i__1 = -(*info); xerbla_("SORGLQ", &i__1); return 0; } else if (lquery) { return 0; } /* Quick return if possible */ if (*m <= 0) { work[1] = 1.f; return 0; } nbmin = 2; nx = 0; iws = *m; if (nb > 1 && nb < *k) { /* Determine when to cross over from blocked to unblocked code. Computing MAX */ i__1 = 0, i__2 = ilaenv_(&c__3, "SORGLQ", " ", m, n, k, &c_n1, ( ftnlen)6, (ftnlen)1); nx = max(i__1,i__2); if (nx < *k) { /* Determine if workspace is large enough for blocked code. */ ldwork = *m; iws = ldwork * nb; if (*lwork < iws) { /* Not enough workspace to use optimal NB: reduce NB and determine the minimum value of NB. */ nb = *lwork / ldwork; /* Computing MAX */ i__1 = 2, i__2 = ilaenv_(&c__2, "SORGLQ", " ", m, n, k, &c_n1, (ftnlen)6, (ftnlen)1); nbmin = max(i__1,i__2); } } } if (nb >= nbmin && nb < *k && nx < *k) { /* Use blocked code after the last block. The first kk rows are handled by the block method. */ ki = (*k - nx - 1) / nb * nb; /* Computing MIN */ i__1 = *k, i__2 = ki + nb; kk = min(i__1,i__2); /* Set A(kk+1:m,1:kk) to zero. */ i__1 = kk; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = kk + 1; i__ <= i__2; ++i__) { a[i__ + j * a_dim1] = 0.f; /* L10: */ } /* L20: */ } } else { kk = 0; } /* Use unblocked code for the last or only block. */ if (kk < *m) { i__1 = *m - kk; i__2 = *n - kk; i__3 = *k - kk; sorgl2_(&i__1, &i__2, &i__3, &a[kk + 1 + (kk + 1) * a_dim1], lda, & tau[kk + 1], &work[1], &iinfo); } if (kk > 0) { /* Use blocked code */ i__1 = -nb; for (i__ = ki + 1; i__1 < 0 ? i__ >= 1 : i__ <= 1; i__ += i__1) { /* Computing MIN */ i__2 = nb, i__3 = *k - i__ + 1; ib = min(i__2,i__3); if (i__ + ib <= *m) { /* Form the triangular factor of the block reflector H = H(i) H(i+1) . . . H(i+ib-1) */ i__2 = *n - i__ + 1; slarft_("Forward", "Rowwise", &i__2, &ib, &a[i__ + i__ * a_dim1], lda, &tau[i__], &work[1], &ldwork); /* Apply H' to A(i+ib:m,i:n) from the right */ i__2 = *m - i__ - ib + 1; i__3 = *n - i__ + 1; slarfb_("Right", "Transpose", "Forward", "Rowwise", &i__2, & i__3, &ib, &a[i__ + i__ * a_dim1], lda, &work[1], & ldwork, &a[i__ + ib + i__ * a_dim1], lda, &work[ib + 1], &ldwork); } /* Apply H' to columns i:n of current block */ i__2 = *n - i__ + 1; sorgl2_(&ib, &i__2, &ib, &a[i__ + i__ * a_dim1], lda, &tau[i__], & work[1], &iinfo); /* Set columns 1:i-1 of current block to zero */ i__2 = i__ - 1; for (j = 1; j <= i__2; ++j) { i__3 = i__ + ib - 1; for (l = i__; l <= i__3; ++l) { a[l + j * a_dim1] = 0.f; /* L30: */ } /* L40: */ } /* L50: */ } } work[1] = (real) iws; return 0; /* End of SORGLQ */ } /* sorglq_ */ /* Subroutine */ int sorgqr_(integer *m, integer *n, integer *k, real *a, integer *lda, real *tau, real *work, integer *lwork, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3; /* Local variables */ static integer i__, j, l, ib, nb, ki, kk, nx, iws, nbmin, iinfo; extern /* Subroutine */ int sorg2r_(integer *, integer *, integer *, real *, integer *, real *, real *, integer *), slarfb_(char *, char *, char *, char *, integer *, integer *, integer *, real *, integer * , real *, integer *, real *, integer *, real *, integer *), xerbla_(char *, integer *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); extern /* Subroutine */ int slarft_(char *, char *, integer *, integer *, real *, integer *, real *, real *, integer *); static integer ldwork, lwkopt; static logical lquery; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= SORGQR generates an M-by-N real matrix Q with orthonormal columns, which is defined as the first N columns of a product of K elementary reflectors of order M Q = H(1) H(2) . . . H(k) as returned by SGEQRF. Arguments ========= M (input) INTEGER The number of rows of the matrix Q. M >= 0. N (input) INTEGER The number of columns of the matrix Q. M >= N >= 0. K (input) INTEGER The number of elementary reflectors whose product defines the matrix Q. N >= K >= 0. A (input/output) REAL array, dimension (LDA,N) On entry, the i-th column must contain the vector which defines the elementary reflector H(i), for i = 1,2,...,k, as returned by SGEQRF in the first k columns of its array argument A. On exit, the M-by-N matrix Q. LDA (input) INTEGER The first dimension of the array A. LDA >= max(1,M). TAU (input) REAL array, dimension (K) TAU(i) must contain the scalar factor of the elementary reflector H(i), as returned by SGEQRF. WORK (workspace/output) REAL array, dimension (LWORK) On exit, if INFO = 0, WORK(1) returns the optimal LWORK. LWORK (input) INTEGER The dimension of the array WORK. LWORK >= max(1,N). For optimum performance LWORK >= N*NB, where NB is the optimal blocksize. If LWORK = -1, then a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued by XERBLA. INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument has an illegal value ===================================================================== Test the input arguments */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --tau; --work; /* Function Body */ *info = 0; nb = ilaenv_(&c__1, "SORGQR", " ", m, n, k, &c_n1, (ftnlen)6, (ftnlen)1); lwkopt = max(1,*n) * nb; work[1] = (real) lwkopt; lquery = *lwork == -1; if (*m < 0) { *info = -1; } else if ((*n < 0) || (*n > *m)) { *info = -2; } else if ((*k < 0) || (*k > *n)) { *info = -3; } else if (*lda < max(1,*m)) { *info = -5; } else if (*lwork < max(1,*n) && ! lquery) { *info = -8; } if (*info != 0) { i__1 = -(*info); xerbla_("SORGQR", &i__1); return 0; } else if (lquery) { return 0; } /* Quick return if possible */ if (*n <= 0) { work[1] = 1.f; return 0; } nbmin = 2; nx = 0; iws = *n; if (nb > 1 && nb < *k) { /* Determine when to cross over from blocked to unblocked code. Computing MAX */ i__1 = 0, i__2 = ilaenv_(&c__3, "SORGQR", " ", m, n, k, &c_n1, ( ftnlen)6, (ftnlen)1); nx = max(i__1,i__2); if (nx < *k) { /* Determine if workspace is large enough for blocked code. */ ldwork = *n; iws = ldwork * nb; if (*lwork < iws) { /* Not enough workspace to use optimal NB: reduce NB and determine the minimum value of NB. */ nb = *lwork / ldwork; /* Computing MAX */ i__1 = 2, i__2 = ilaenv_(&c__2, "SORGQR", " ", m, n, k, &c_n1, (ftnlen)6, (ftnlen)1); nbmin = max(i__1,i__2); } } } if (nb >= nbmin && nb < *k && nx < *k) { /* Use blocked code after the last block. The first kk columns are handled by the block method. */ ki = (*k - nx - 1) / nb * nb; /* Computing MIN */ i__1 = *k, i__2 = ki + nb; kk = min(i__1,i__2); /* Set A(1:kk,kk+1:n) to zero. */ i__1 = *n; for (j = kk + 1; j <= i__1; ++j) { i__2 = kk; for (i__ = 1; i__ <= i__2; ++i__) { a[i__ + j * a_dim1] = 0.f; /* L10: */ } /* L20: */ } } else { kk = 0; } /* Use unblocked code for the last or only block. */ if (kk < *n) { i__1 = *m - kk; i__2 = *n - kk; i__3 = *k - kk; sorg2r_(&i__1, &i__2, &i__3, &a[kk + 1 + (kk + 1) * a_dim1], lda, & tau[kk + 1], &work[1], &iinfo); } if (kk > 0) { /* Use blocked code */ i__1 = -nb; for (i__ = ki + 1; i__1 < 0 ? i__ >= 1 : i__ <= 1; i__ += i__1) { /* Computing MIN */ i__2 = nb, i__3 = *k - i__ + 1; ib = min(i__2,i__3); if (i__ + ib <= *n) { /* Form the triangular factor of the block reflector H = H(i) H(i+1) . . . H(i+ib-1) */ i__2 = *m - i__ + 1; slarft_("Forward", "Columnwise", &i__2, &ib, &a[i__ + i__ * a_dim1], lda, &tau[i__], &work[1], &ldwork); /* Apply H to A(i:m,i+ib:n) from the left */ i__2 = *m - i__ + 1; i__3 = *n - i__ - ib + 1; slarfb_("Left", "No transpose", "Forward", "Columnwise", & i__2, &i__3, &ib, &a[i__ + i__ * a_dim1], lda, &work[ 1], &ldwork, &a[i__ + (i__ + ib) * a_dim1], lda, & work[ib + 1], &ldwork); } /* Apply H to rows i:m of current block */ i__2 = *m - i__ + 1; sorg2r_(&i__2, &ib, &ib, &a[i__ + i__ * a_dim1], lda, &tau[i__], & work[1], &iinfo); /* Set rows 1:i-1 of current block to zero */ i__2 = i__ + ib - 1; for (j = i__; j <= i__2; ++j) { i__3 = i__ - 1; for (l = 1; l <= i__3; ++l) { a[l + j * a_dim1] = 0.f; /* L30: */ } /* L40: */ } /* L50: */ } } work[1] = (real) iws; return 0; /* End of SORGQR */ } /* sorgqr_ */ /* Subroutine */ int sorm2l_(char *side, char *trans, integer *m, integer *n, integer *k, real *a, integer *lda, real *tau, real *c__, integer *ldc, real *work, integer *info) { /* System generated locals */ integer a_dim1, a_offset, c_dim1, c_offset, i__1, i__2; /* Local variables */ static integer i__, i1, i2, i3, mi, ni, nq; static real aii; static logical left; extern logical lsame_(char *, char *); extern /* Subroutine */ int slarf_(char *, integer *, integer *, real *, integer *, real *, real *, integer *, real *), xerbla_( char *, integer *); static logical notran; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University February 29, 1992 Purpose ======= SORM2L overwrites the general real m by n matrix C with Q * C if SIDE = 'L' and TRANS = 'N', or Q'* C if SIDE = 'L' and TRANS = 'T', or C * Q if SIDE = 'R' and TRANS = 'N', or C * Q' if SIDE = 'R' and TRANS = 'T', where Q is a real orthogonal matrix defined as the product of k elementary reflectors Q = H(k) . . . H(2) H(1) as returned by SGEQLF. Q is of order m if SIDE = 'L' and of order n if SIDE = 'R'. Arguments ========= SIDE (input) CHARACTER*1 = 'L': apply Q or Q' from the Left = 'R': apply Q or Q' from the Right TRANS (input) CHARACTER*1 = 'N': apply Q (No transpose) = 'T': apply Q' (Transpose) M (input) INTEGER The number of rows of the matrix C. M >= 0. N (input) INTEGER The number of columns of the matrix C. N >= 0. K (input) INTEGER The number of elementary reflectors whose product defines the matrix Q. If SIDE = 'L', M >= K >= 0; if SIDE = 'R', N >= K >= 0. A (input) REAL array, dimension (LDA,K) The i-th column must contain the vector which defines the elementary reflector H(i), for i = 1,2,...,k, as returned by SGEQLF in the last k columns of its array argument A. A is modified by the routine but restored on exit. LDA (input) INTEGER The leading dimension of the array A. If SIDE = 'L', LDA >= max(1,M); if SIDE = 'R', LDA >= max(1,N). TAU (input) REAL array, dimension (K) TAU(i) must contain the scalar factor of the elementary reflector H(i), as returned by SGEQLF. C (input/output) REAL array, dimension (LDC,N) On entry, the m by n matrix C. On exit, C is overwritten by Q*C or Q'*C or C*Q' or C*Q. LDC (input) INTEGER The leading dimension of the array C. LDC >= max(1,M). WORK (workspace) REAL array, dimension (N) if SIDE = 'L', (M) if SIDE = 'R' INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value ===================================================================== Test the input arguments */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --tau; c_dim1 = *ldc; c_offset = 1 + c_dim1; c__ -= c_offset; --work; /* Function Body */ *info = 0; left = lsame_(side, "L"); notran = lsame_(trans, "N"); /* NQ is the order of Q */ if (left) { nq = *m; } else { nq = *n; } if (! left && ! lsame_(side, "R")) { *info = -1; } else if (! notran && ! lsame_(trans, "T")) { *info = -2; } else if (*m < 0) { *info = -3; } else if (*n < 0) { *info = -4; } else if ((*k < 0) || (*k > nq)) { *info = -5; } else if (*lda < max(1,nq)) { *info = -7; } else if (*ldc < max(1,*m)) { *info = -10; } if (*info != 0) { i__1 = -(*info); xerbla_("SORM2L", &i__1); return 0; } /* Quick return if possible */ if (((*m == 0) || (*n == 0)) || (*k == 0)) { return 0; } if ((left && notran) || (! left && ! notran)) { i1 = 1; i2 = *k; i3 = 1; } else { i1 = *k; i2 = 1; i3 = -1; } if (left) { ni = *n; } else { mi = *m; } i__1 = i2; i__2 = i3; for (i__ = i1; i__2 < 0 ? i__ >= i__1 : i__ <= i__1; i__ += i__2) { if (left) { /* H(i) is applied to C(1:m-k+i,1:n) */ mi = *m - *k + i__; } else { /* H(i) is applied to C(1:m,1:n-k+i) */ ni = *n - *k + i__; } /* Apply H(i) */ aii = a[nq - *k + i__ + i__ * a_dim1]; a[nq - *k + i__ + i__ * a_dim1] = 1.f; slarf_(side, &mi, &ni, &a[i__ * a_dim1 + 1], &c__1, &tau[i__], &c__[ c_offset], ldc, &work[1]); a[nq - *k + i__ + i__ * a_dim1] = aii; /* L10: */ } return 0; /* End of SORM2L */ } /* sorm2l_ */ /* Subroutine */ int sorm2r_(char *side, char *trans, integer *m, integer *n, integer *k, real *a, integer *lda, real *tau, real *c__, integer *ldc, real *work, integer *info) { /* System generated locals */ integer a_dim1, a_offset, c_dim1, c_offset, i__1, i__2; /* Local variables */ static integer i__, i1, i2, i3, ic, jc, mi, ni, nq; static real aii; static logical left; extern logical lsame_(char *, char *); extern /* Subroutine */ int slarf_(char *, integer *, integer *, real *, integer *, real *, real *, integer *, real *), xerbla_( char *, integer *); static logical notran; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University February 29, 1992 Purpose ======= SORM2R overwrites the general real m by n matrix C with Q * C if SIDE = 'L' and TRANS = 'N', or Q'* C if SIDE = 'L' and TRANS = 'T', or C * Q if SIDE = 'R' and TRANS = 'N', or C * Q' if SIDE = 'R' and TRANS = 'T', where Q is a real orthogonal matrix defined as the product of k elementary reflectors Q = H(1) H(2) . . . H(k) as returned by SGEQRF. Q is of order m if SIDE = 'L' and of order n if SIDE = 'R'. Arguments ========= SIDE (input) CHARACTER*1 = 'L': apply Q or Q' from the Left = 'R': apply Q or Q' from the Right TRANS (input) CHARACTER*1 = 'N': apply Q (No transpose) = 'T': apply Q' (Transpose) M (input) INTEGER The number of rows of the matrix C. M >= 0. N (input) INTEGER The number of columns of the matrix C. N >= 0. K (input) INTEGER The number of elementary reflectors whose product defines the matrix Q. If SIDE = 'L', M >= K >= 0; if SIDE = 'R', N >= K >= 0. A (input) REAL array, dimension (LDA,K) The i-th column must contain the vector which defines the elementary reflector H(i), for i = 1,2,...,k, as returned by SGEQRF in the first k columns of its array argument A. A is modified by the routine but restored on exit. LDA (input) INTEGER The leading dimension of the array A. If SIDE = 'L', LDA >= max(1,M); if SIDE = 'R', LDA >= max(1,N). TAU (input) REAL array, dimension (K) TAU(i) must contain the scalar factor of the elementary reflector H(i), as returned by SGEQRF. C (input/output) REAL array, dimension (LDC,N) On entry, the m by n matrix C. On exit, C is overwritten by Q*C or Q'*C or C*Q' or C*Q. LDC (input) INTEGER The leading dimension of the array C. LDC >= max(1,M). WORK (workspace) REAL array, dimension (N) if SIDE = 'L', (M) if SIDE = 'R' INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value ===================================================================== Test the input arguments */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --tau; c_dim1 = *ldc; c_offset = 1 + c_dim1; c__ -= c_offset; --work; /* Function Body */ *info = 0; left = lsame_(side, "L"); notran = lsame_(trans, "N"); /* NQ is the order of Q */ if (left) { nq = *m; } else { nq = *n; } if (! left && ! lsame_(side, "R")) { *info = -1; } else if (! notran && ! lsame_(trans, "T")) { *info = -2; } else if (*m < 0) { *info = -3; } else if (*n < 0) { *info = -4; } else if ((*k < 0) || (*k > nq)) { *info = -5; } else if (*lda < max(1,nq)) { *info = -7; } else if (*ldc < max(1,*m)) { *info = -10; } if (*info != 0) { i__1 = -(*info); xerbla_("SORM2R", &i__1); return 0; } /* Quick return if possible */ if (((*m == 0) || (*n == 0)) || (*k == 0)) { return 0; } if ((left && ! notran) || (! left && notran)) { i1 = 1; i2 = *k; i3 = 1; } else { i1 = *k; i2 = 1; i3 = -1; } if (left) { ni = *n; jc = 1; } else { mi = *m; ic = 1; } i__1 = i2; i__2 = i3; for (i__ = i1; i__2 < 0 ? i__ >= i__1 : i__ <= i__1; i__ += i__2) { if (left) { /* H(i) is applied to C(i:m,1:n) */ mi = *m - i__ + 1; ic = i__; } else { /* H(i) is applied to C(1:m,i:n) */ ni = *n - i__ + 1; jc = i__; } /* Apply H(i) */ aii = a[i__ + i__ * a_dim1]; a[i__ + i__ * a_dim1] = 1.f; slarf_(side, &mi, &ni, &a[i__ + i__ * a_dim1], &c__1, &tau[i__], &c__[ ic + jc * c_dim1], ldc, &work[1]); a[i__ + i__ * a_dim1] = aii; /* L10: */ } return 0; /* End of SORM2R */ } /* sorm2r_ */ /* Subroutine */ int sormbr_(char *vect, char *side, char *trans, integer *m, integer *n, integer *k, real *a, integer *lda, real *tau, real *c__, integer *ldc, real *work, integer *lwork, integer *info) { /* System generated locals */ address a__1[2]; integer a_dim1, a_offset, c_dim1, c_offset, i__1, i__2, i__3[2]; char ch__1[2]; /* Builtin functions */ /* Subroutine */ int s_cat(char *, char **, integer *, integer *, ftnlen); /* Local variables */ static integer i1, i2, nb, mi, ni, nq, nw; static logical left; extern logical lsame_(char *, char *); static integer iinfo; extern /* Subroutine */ int xerbla_(char *, integer *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); static logical notran, applyq; static char transt[1]; extern /* Subroutine */ int sormlq_(char *, char *, integer *, integer *, integer *, real *, integer *, real *, real *, integer *, real *, integer *, integer *); static integer lwkopt; static logical lquery; extern /* Subroutine */ int sormqr_(char *, char *, integer *, integer *, integer *, real *, integer *, real *, real *, integer *, real *, integer *, integer *); /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= If VECT = 'Q', SORMBR overwrites the general real M-by-N matrix C with SIDE = 'L' SIDE = 'R' TRANS = 'N': Q * C C * Q TRANS = 'T': Q**T * C C * Q**T If VECT = 'P', SORMBR overwrites the general real M-by-N matrix C with SIDE = 'L' SIDE = 'R' TRANS = 'N': P * C C * P TRANS = 'T': P**T * C C * P**T Here Q and P**T are the orthogonal matrices determined by SGEBRD when reducing a real matrix A to bidiagonal form: A = Q * B * P**T. Q and P**T are defined as products of elementary reflectors H(i) and G(i) respectively. Let nq = m if SIDE = 'L' and nq = n if SIDE = 'R'. Thus nq is the order of the orthogonal matrix Q or P**T that is applied. If VECT = 'Q', A is assumed to have been an NQ-by-K matrix: if nq >= k, Q = H(1) H(2) . . . H(k); if nq < k, Q = H(1) H(2) . . . H(nq-1). If VECT = 'P', A is assumed to have been a K-by-NQ matrix: if k < nq, P = G(1) G(2) . . . G(k); if k >= nq, P = G(1) G(2) . . . G(nq-1). Arguments ========= VECT (input) CHARACTER*1 = 'Q': apply Q or Q**T; = 'P': apply P or P**T. SIDE (input) CHARACTER*1 = 'L': apply Q, Q**T, P or P**T from the Left; = 'R': apply Q, Q**T, P or P**T from the Right. TRANS (input) CHARACTER*1 = 'N': No transpose, apply Q or P; = 'T': Transpose, apply Q**T or P**T. M (input) INTEGER The number of rows of the matrix C. M >= 0. N (input) INTEGER The number of columns of the matrix C. N >= 0. K (input) INTEGER If VECT = 'Q', the number of columns in the original matrix reduced by SGEBRD. If VECT = 'P', the number of rows in the original matrix reduced by SGEBRD. K >= 0. A (input) REAL array, dimension (LDA,min(nq,K)) if VECT = 'Q' (LDA,nq) if VECT = 'P' The vectors which define the elementary reflectors H(i) and G(i), whose products determine the matrices Q and P, as returned by SGEBRD. LDA (input) INTEGER The leading dimension of the array A. If VECT = 'Q', LDA >= max(1,nq); if VECT = 'P', LDA >= max(1,min(nq,K)). TAU (input) REAL array, dimension (min(nq,K)) TAU(i) must contain the scalar factor of the elementary reflector H(i) or G(i) which determines Q or P, as returned by SGEBRD in the array argument TAUQ or TAUP. C (input/output) REAL array, dimension (LDC,N) On entry, the M-by-N matrix C. On exit, C is overwritten by Q*C or Q**T*C or C*Q**T or C*Q or P*C or P**T*C or C*P or C*P**T. LDC (input) INTEGER The leading dimension of the array C. LDC >= max(1,M). WORK (workspace/output) REAL array, dimension (LWORK) On exit, if INFO = 0, WORK(1) returns the optimal LWORK. LWORK (input) INTEGER The dimension of the array WORK. If SIDE = 'L', LWORK >= max(1,N); if SIDE = 'R', LWORK >= max(1,M). For optimum performance LWORK >= N*NB if SIDE = 'L', and LWORK >= M*NB if SIDE = 'R', where NB is the optimal blocksize. If LWORK = -1, then a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued by XERBLA. INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value ===================================================================== Test the input arguments */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --tau; c_dim1 = *ldc; c_offset = 1 + c_dim1; c__ -= c_offset; --work; /* Function Body */ *info = 0; applyq = lsame_(vect, "Q"); left = lsame_(side, "L"); notran = lsame_(trans, "N"); lquery = *lwork == -1; /* NQ is the order of Q or P and NW is the minimum dimension of WORK */ if (left) { nq = *m; nw = *n; } else { nq = *n; nw = *m; } if (! applyq && ! lsame_(vect, "P")) { *info = -1; } else if (! left && ! lsame_(side, "R")) { *info = -2; } else if (! notran && ! lsame_(trans, "T")) { *info = -3; } else if (*m < 0) { *info = -4; } else if (*n < 0) { *info = -5; } else if (*k < 0) { *info = -6; } else /* if(complicated condition) */ { /* Computing MAX */ i__1 = 1, i__2 = min(nq,*k); if ((applyq && *lda < max(1,nq)) || (! applyq && *lda < max(i__1,i__2) )) { *info = -8; } else if (*ldc < max(1,*m)) { *info = -11; } else if (*lwork < max(1,nw) && ! lquery) { *info = -13; } } if (*info == 0) { if (applyq) { if (left) { /* Writing concatenation */ i__3[0] = 1, a__1[0] = side; i__3[1] = 1, a__1[1] = trans; s_cat(ch__1, a__1, i__3, &c__2, (ftnlen)2); i__1 = *m - 1; i__2 = *m - 1; nb = ilaenv_(&c__1, "SORMQR", ch__1, &i__1, n, &i__2, &c_n1, ( ftnlen)6, (ftnlen)2); } else { /* Writing concatenation */ i__3[0] = 1, a__1[0] = side; i__3[1] = 1, a__1[1] = trans; s_cat(ch__1, a__1, i__3, &c__2, (ftnlen)2); i__1 = *n - 1; i__2 = *n - 1; nb = ilaenv_(&c__1, "SORMQR", ch__1, m, &i__1, &i__2, &c_n1, ( ftnlen)6, (ftnlen)2); } } else { if (left) { /* Writing concatenation */ i__3[0] = 1, a__1[0] = side; i__3[1] = 1, a__1[1] = trans; s_cat(ch__1, a__1, i__3, &c__2, (ftnlen)2); i__1 = *m - 1; i__2 = *m - 1; nb = ilaenv_(&c__1, "SORMLQ", ch__1, &i__1, n, &i__2, &c_n1, ( ftnlen)6, (ftnlen)2); } else { /* Writing concatenation */ i__3[0] = 1, a__1[0] = side; i__3[1] = 1, a__1[1] = trans; s_cat(ch__1, a__1, i__3, &c__2, (ftnlen)2); i__1 = *n - 1; i__2 = *n - 1; nb = ilaenv_(&c__1, "SORMLQ", ch__1, m, &i__1, &i__2, &c_n1, ( ftnlen)6, (ftnlen)2); } } lwkopt = max(1,nw) * nb; work[1] = (real) lwkopt; } if (*info != 0) { i__1 = -(*info); xerbla_("SORMBR", &i__1); return 0; } else if (lquery) { return 0; } /* Quick return if possible */ work[1] = 1.f; if ((*m == 0) || (*n == 0)) { return 0; } if (applyq) { /* Apply Q */ if (nq >= *k) { /* Q was determined by a call to SGEBRD with nq >= k */ sormqr_(side, trans, m, n, k, &a[a_offset], lda, &tau[1], &c__[ c_offset], ldc, &work[1], lwork, &iinfo); } else if (nq > 1) { /* Q was determined by a call to SGEBRD with nq < k */ if (left) { mi = *m - 1; ni = *n; i1 = 2; i2 = 1; } else { mi = *m; ni = *n - 1; i1 = 1; i2 = 2; } i__1 = nq - 1; sormqr_(side, trans, &mi, &ni, &i__1, &a[a_dim1 + 2], lda, &tau[1] , &c__[i1 + i2 * c_dim1], ldc, &work[1], lwork, &iinfo); } } else { /* Apply P */ if (notran) { *(unsigned char *)transt = 'T'; } else { *(unsigned char *)transt = 'N'; } if (nq > *k) { /* P was determined by a call to SGEBRD with nq > k */ sormlq_(side, transt, m, n, k, &a[a_offset], lda, &tau[1], &c__[ c_offset], ldc, &work[1], lwork, &iinfo); } else if (nq > 1) { /* P was determined by a call to SGEBRD with nq <= k */ if (left) { mi = *m - 1; ni = *n; i1 = 2; i2 = 1; } else { mi = *m; ni = *n - 1; i1 = 1; i2 = 2; } i__1 = nq - 1; sormlq_(side, transt, &mi, &ni, &i__1, &a[((a_dim1) << (1)) + 1], lda, &tau[1], &c__[i1 + i2 * c_dim1], ldc, &work[1], lwork, &iinfo); } } work[1] = (real) lwkopt; return 0; /* End of SORMBR */ } /* sormbr_ */ /* Subroutine */ int sorml2_(char *side, char *trans, integer *m, integer *n, integer *k, real *a, integer *lda, real *tau, real *c__, integer *ldc, real *work, integer *info) { /* System generated locals */ integer a_dim1, a_offset, c_dim1, c_offset, i__1, i__2; /* Local variables */ static integer i__, i1, i2, i3, ic, jc, mi, ni, nq; static real aii; static logical left; extern logical lsame_(char *, char *); extern /* Subroutine */ int slarf_(char *, integer *, integer *, real *, integer *, real *, real *, integer *, real *), xerbla_( char *, integer *); static logical notran; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University February 29, 1992 Purpose ======= SORML2 overwrites the general real m by n matrix C with Q * C if SIDE = 'L' and TRANS = 'N', or Q'* C if SIDE = 'L' and TRANS = 'T', or C * Q if SIDE = 'R' and TRANS = 'N', or C * Q' if SIDE = 'R' and TRANS = 'T', where Q is a real orthogonal matrix defined as the product of k elementary reflectors Q = H(k) . . . H(2) H(1) as returned by SGELQF. Q is of order m if SIDE = 'L' and of order n if SIDE = 'R'. Arguments ========= SIDE (input) CHARACTER*1 = 'L': apply Q or Q' from the Left = 'R': apply Q or Q' from the Right TRANS (input) CHARACTER*1 = 'N': apply Q (No transpose) = 'T': apply Q' (Transpose) M (input) INTEGER The number of rows of the matrix C. M >= 0. N (input) INTEGER The number of columns of the matrix C. N >= 0. K (input) INTEGER The number of elementary reflectors whose product defines the matrix Q. If SIDE = 'L', M >= K >= 0; if SIDE = 'R', N >= K >= 0. A (input) REAL array, dimension (LDA,M) if SIDE = 'L', (LDA,N) if SIDE = 'R' The i-th row must contain the vector which defines the elementary reflector H(i), for i = 1,2,...,k, as returned by SGELQF in the first k rows of its array argument A. A is modified by the routine but restored on exit. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,K). TAU (input) REAL array, dimension (K) TAU(i) must contain the scalar factor of the elementary reflector H(i), as returned by SGELQF. C (input/output) REAL array, dimension (LDC,N) On entry, the m by n matrix C. On exit, C is overwritten by Q*C or Q'*C or C*Q' or C*Q. LDC (input) INTEGER The leading dimension of the array C. LDC >= max(1,M). WORK (workspace) REAL array, dimension (N) if SIDE = 'L', (M) if SIDE = 'R' INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value ===================================================================== Test the input arguments */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --tau; c_dim1 = *ldc; c_offset = 1 + c_dim1; c__ -= c_offset; --work; /* Function Body */ *info = 0; left = lsame_(side, "L"); notran = lsame_(trans, "N"); /* NQ is the order of Q */ if (left) { nq = *m; } else { nq = *n; } if (! left && ! lsame_(side, "R")) { *info = -1; } else if (! notran && ! lsame_(trans, "T")) { *info = -2; } else if (*m < 0) { *info = -3; } else if (*n < 0) { *info = -4; } else if ((*k < 0) || (*k > nq)) { *info = -5; } else if (*lda < max(1,*k)) { *info = -7; } else if (*ldc < max(1,*m)) { *info = -10; } if (*info != 0) { i__1 = -(*info); xerbla_("SORML2", &i__1); return 0; } /* Quick return if possible */ if (((*m == 0) || (*n == 0)) || (*k == 0)) { return 0; } if ((left && notran) || (! left && ! notran)) { i1 = 1; i2 = *k; i3 = 1; } else { i1 = *k; i2 = 1; i3 = -1; } if (left) { ni = *n; jc = 1; } else { mi = *m; ic = 1; } i__1 = i2; i__2 = i3; for (i__ = i1; i__2 < 0 ? i__ >= i__1 : i__ <= i__1; i__ += i__2) { if (left) { /* H(i) is applied to C(i:m,1:n) */ mi = *m - i__ + 1; ic = i__; } else { /* H(i) is applied to C(1:m,i:n) */ ni = *n - i__ + 1; jc = i__; } /* Apply H(i) */ aii = a[i__ + i__ * a_dim1]; a[i__ + i__ * a_dim1] = 1.f; slarf_(side, &mi, &ni, &a[i__ + i__ * a_dim1], lda, &tau[i__], &c__[ ic + jc * c_dim1], ldc, &work[1]); a[i__ + i__ * a_dim1] = aii; /* L10: */ } return 0; /* End of SORML2 */ } /* sorml2_ */ /* Subroutine */ int sormlq_(char *side, char *trans, integer *m, integer *n, integer *k, real *a, integer *lda, real *tau, real *c__, integer *ldc, real *work, integer *lwork, integer *info) { /* System generated locals */ address a__1[2]; integer a_dim1, a_offset, c_dim1, c_offset, i__1, i__2, i__3[2], i__4, i__5; char ch__1[2]; /* Builtin functions */ /* Subroutine */ int s_cat(char *, char **, integer *, integer *, ftnlen); /* Local variables */ static integer i__; static real t[4160] /* was [65][64] */; static integer i1, i2, i3, ib, ic, jc, nb, mi, ni, nq, nw, iws; static logical left; extern logical lsame_(char *, char *); static integer nbmin, iinfo; extern /* Subroutine */ int sorml2_(char *, char *, integer *, integer *, integer *, real *, integer *, real *, real *, integer *, real *, integer *), slarfb_(char *, char *, char *, char * , integer *, integer *, integer *, real *, integer *, real *, integer *, real *, integer *, real *, integer *), xerbla_(char *, integer *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); extern /* Subroutine */ int slarft_(char *, char *, integer *, integer *, real *, integer *, real *, real *, integer *); static logical notran; static integer ldwork; static char transt[1]; static integer lwkopt; static logical lquery; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= SORMLQ overwrites the general real M-by-N matrix C with SIDE = 'L' SIDE = 'R' TRANS = 'N': Q * C C * Q TRANS = 'T': Q**T * C C * Q**T where Q is a real orthogonal matrix defined as the product of k elementary reflectors Q = H(k) . . . H(2) H(1) as returned by SGELQF. Q is of order M if SIDE = 'L' and of order N if SIDE = 'R'. Arguments ========= SIDE (input) CHARACTER*1 = 'L': apply Q or Q**T from the Left; = 'R': apply Q or Q**T from the Right. TRANS (input) CHARACTER*1 = 'N': No transpose, apply Q; = 'T': Transpose, apply Q**T. M (input) INTEGER The number of rows of the matrix C. M >= 0. N (input) INTEGER The number of columns of the matrix C. N >= 0. K (input) INTEGER The number of elementary reflectors whose product defines the matrix Q. If SIDE = 'L', M >= K >= 0; if SIDE = 'R', N >= K >= 0. A (input) REAL array, dimension (LDA,M) if SIDE = 'L', (LDA,N) if SIDE = 'R' The i-th row must contain the vector which defines the elementary reflector H(i), for i = 1,2,...,k, as returned by SGELQF in the first k rows of its array argument A. A is modified by the routine but restored on exit. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,K). TAU (input) REAL array, dimension (K) TAU(i) must contain the scalar factor of the elementary reflector H(i), as returned by SGELQF. C (input/output) REAL array, dimension (LDC,N) On entry, the M-by-N matrix C. On exit, C is overwritten by Q*C or Q**T*C or C*Q**T or C*Q. LDC (input) INTEGER The leading dimension of the array C. LDC >= max(1,M). WORK (workspace/output) REAL array, dimension (LWORK) On exit, if INFO = 0, WORK(1) returns the optimal LWORK. LWORK (input) INTEGER The dimension of the array WORK. If SIDE = 'L', LWORK >= max(1,N); if SIDE = 'R', LWORK >= max(1,M). For optimum performance LWORK >= N*NB if SIDE = 'L', and LWORK >= M*NB if SIDE = 'R', where NB is the optimal blocksize. If LWORK = -1, then a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued by XERBLA. INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value ===================================================================== Test the input arguments */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --tau; c_dim1 = *ldc; c_offset = 1 + c_dim1; c__ -= c_offset; --work; /* Function Body */ *info = 0; left = lsame_(side, "L"); notran = lsame_(trans, "N"); lquery = *lwork == -1; /* NQ is the order of Q and NW is the minimum dimension of WORK */ if (left) { nq = *m; nw = *n; } else { nq = *n; nw = *m; } if (! left && ! lsame_(side, "R")) { *info = -1; } else if (! notran && ! lsame_(trans, "T")) { *info = -2; } else if (*m < 0) { *info = -3; } else if (*n < 0) { *info = -4; } else if ((*k < 0) || (*k > nq)) { *info = -5; } else if (*lda < max(1,*k)) { *info = -7; } else if (*ldc < max(1,*m)) { *info = -10; } else if (*lwork < max(1,nw) && ! lquery) { *info = -12; } if (*info == 0) { /* Determine the block size. NB may be at most NBMAX, where NBMAX is used to define the local array T. Computing MIN Writing concatenation */ i__3[0] = 1, a__1[0] = side; i__3[1] = 1, a__1[1] = trans; s_cat(ch__1, a__1, i__3, &c__2, (ftnlen)2); i__1 = 64, i__2 = ilaenv_(&c__1, "SORMLQ", ch__1, m, n, k, &c_n1, ( ftnlen)6, (ftnlen)2); nb = min(i__1,i__2); lwkopt = max(1,nw) * nb; work[1] = (real) lwkopt; } if (*info != 0) { i__1 = -(*info); xerbla_("SORMLQ", &i__1); return 0; } else if (lquery) { return 0; } /* Quick return if possible */ if (((*m == 0) || (*n == 0)) || (*k == 0)) { work[1] = 1.f; return 0; } nbmin = 2; ldwork = nw; if (nb > 1 && nb < *k) { iws = nw * nb; if (*lwork < iws) { nb = *lwork / ldwork; /* Computing MAX Writing concatenation */ i__3[0] = 1, a__1[0] = side; i__3[1] = 1, a__1[1] = trans; s_cat(ch__1, a__1, i__3, &c__2, (ftnlen)2); i__1 = 2, i__2 = ilaenv_(&c__2, "SORMLQ", ch__1, m, n, k, &c_n1, ( ftnlen)6, (ftnlen)2); nbmin = max(i__1,i__2); } } else { iws = nw; } if ((nb < nbmin) || (nb >= *k)) { /* Use unblocked code */ sorml2_(side, trans, m, n, k, &a[a_offset], lda, &tau[1], &c__[ c_offset], ldc, &work[1], &iinfo); } else { /* Use blocked code */ if ((left && notran) || (! left && ! notran)) { i1 = 1; i2 = *k; i3 = nb; } else { i1 = (*k - 1) / nb * nb + 1; i2 = 1; i3 = -nb; } if (left) { ni = *n; jc = 1; } else { mi = *m; ic = 1; } if (notran) { *(unsigned char *)transt = 'T'; } else { *(unsigned char *)transt = 'N'; } i__1 = i2; i__2 = i3; for (i__ = i1; i__2 < 0 ? i__ >= i__1 : i__ <= i__1; i__ += i__2) { /* Computing MIN */ i__4 = nb, i__5 = *k - i__ + 1; ib = min(i__4,i__5); /* Form the triangular factor of the block reflector H = H(i) H(i+1) . . . H(i+ib-1) */ i__4 = nq - i__ + 1; slarft_("Forward", "Rowwise", &i__4, &ib, &a[i__ + i__ * a_dim1], lda, &tau[i__], t, &c__65); if (left) { /* H or H' is applied to C(i:m,1:n) */ mi = *m - i__ + 1; ic = i__; } else { /* H or H' is applied to C(1:m,i:n) */ ni = *n - i__ + 1; jc = i__; } /* Apply H or H' */ slarfb_(side, transt, "Forward", "Rowwise", &mi, &ni, &ib, &a[i__ + i__ * a_dim1], lda, t, &c__65, &c__[ic + jc * c_dim1], ldc, &work[1], &ldwork); /* L10: */ } } work[1] = (real) lwkopt; return 0; /* End of SORMLQ */ } /* sormlq_ */ /* Subroutine */ int sormql_(char *side, char *trans, integer *m, integer *n, integer *k, real *a, integer *lda, real *tau, real *c__, integer *ldc, real *work, integer *lwork, integer *info) { /* System generated locals */ address a__1[2]; integer a_dim1, a_offset, c_dim1, c_offset, i__1, i__2, i__3[2], i__4, i__5; char ch__1[2]; /* Builtin functions */ /* Subroutine */ int s_cat(char *, char **, integer *, integer *, ftnlen); /* Local variables */ static integer i__; static real t[4160] /* was [65][64] */; static integer i1, i2, i3, ib, nb, mi, ni, nq, nw, iws; static logical left; extern logical lsame_(char *, char *); static integer nbmin, iinfo; extern /* Subroutine */ int sorm2l_(char *, char *, integer *, integer *, integer *, real *, integer *, real *, real *, integer *, real *, integer *), slarfb_(char *, char *, char *, char * , integer *, integer *, integer *, real *, integer *, real *, integer *, real *, integer *, real *, integer *), xerbla_(char *, integer *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); extern /* Subroutine */ int slarft_(char *, char *, integer *, integer *, real *, integer *, real *, real *, integer *); static logical notran; static integer ldwork, lwkopt; static logical lquery; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= SORMQL overwrites the general real M-by-N matrix C with SIDE = 'L' SIDE = 'R' TRANS = 'N': Q * C C * Q TRANS = 'T': Q**T * C C * Q**T where Q is a real orthogonal matrix defined as the product of k elementary reflectors Q = H(k) . . . H(2) H(1) as returned by SGEQLF. Q is of order M if SIDE = 'L' and of order N if SIDE = 'R'. Arguments ========= SIDE (input) CHARACTER*1 = 'L': apply Q or Q**T from the Left; = 'R': apply Q or Q**T from the Right. TRANS (input) CHARACTER*1 = 'N': No transpose, apply Q; = 'T': Transpose, apply Q**T. M (input) INTEGER The number of rows of the matrix C. M >= 0. N (input) INTEGER The number of columns of the matrix C. N >= 0. K (input) INTEGER The number of elementary reflectors whose product defines the matrix Q. If SIDE = 'L', M >= K >= 0; if SIDE = 'R', N >= K >= 0. A (input) REAL array, dimension (LDA,K) The i-th column must contain the vector which defines the elementary reflector H(i), for i = 1,2,...,k, as returned by SGEQLF in the last k columns of its array argument A. A is modified by the routine but restored on exit. LDA (input) INTEGER The leading dimension of the array A. If SIDE = 'L', LDA >= max(1,M); if SIDE = 'R', LDA >= max(1,N). TAU (input) REAL array, dimension (K) TAU(i) must contain the scalar factor of the elementary reflector H(i), as returned by SGEQLF. C (input/output) REAL array, dimension (LDC,N) On entry, the M-by-N matrix C. On exit, C is overwritten by Q*C or Q**T*C or C*Q**T or C*Q. LDC (input) INTEGER The leading dimension of the array C. LDC >= max(1,M). WORK (workspace/output) REAL array, dimension (LWORK) On exit, if INFO = 0, WORK(1) returns the optimal LWORK. LWORK (input) INTEGER The dimension of the array WORK. If SIDE = 'L', LWORK >= max(1,N); if SIDE = 'R', LWORK >= max(1,M). For optimum performance LWORK >= N*NB if SIDE = 'L', and LWORK >= M*NB if SIDE = 'R', where NB is the optimal blocksize. If LWORK = -1, then a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued by XERBLA. INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value ===================================================================== Test the input arguments */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --tau; c_dim1 = *ldc; c_offset = 1 + c_dim1; c__ -= c_offset; --work; /* Function Body */ *info = 0; left = lsame_(side, "L"); notran = lsame_(trans, "N"); lquery = *lwork == -1; /* NQ is the order of Q and NW is the minimum dimension of WORK */ if (left) { nq = *m; nw = *n; } else { nq = *n; nw = *m; } if (! left && ! lsame_(side, "R")) { *info = -1; } else if (! notran && ! lsame_(trans, "T")) { *info = -2; } else if (*m < 0) { *info = -3; } else if (*n < 0) { *info = -4; } else if ((*k < 0) || (*k > nq)) { *info = -5; } else if (*lda < max(1,nq)) { *info = -7; } else if (*ldc < max(1,*m)) { *info = -10; } else if (*lwork < max(1,nw) && ! lquery) { *info = -12; } if (*info == 0) { /* Determine the block size. NB may be at most NBMAX, where NBMAX is used to define the local array T. Computing MIN Writing concatenation */ i__3[0] = 1, a__1[0] = side; i__3[1] = 1, a__1[1] = trans; s_cat(ch__1, a__1, i__3, &c__2, (ftnlen)2); i__1 = 64, i__2 = ilaenv_(&c__1, "SORMQL", ch__1, m, n, k, &c_n1, ( ftnlen)6, (ftnlen)2); nb = min(i__1,i__2); lwkopt = max(1,nw) * nb; work[1] = (real) lwkopt; } if (*info != 0) { i__1 = -(*info); xerbla_("SORMQL", &i__1); return 0; } else if (lquery) { return 0; } /* Quick return if possible */ if (((*m == 0) || (*n == 0)) || (*k == 0)) { work[1] = 1.f; return 0; } nbmin = 2; ldwork = nw; if (nb > 1 && nb < *k) { iws = nw * nb; if (*lwork < iws) { nb = *lwork / ldwork; /* Computing MAX Writing concatenation */ i__3[0] = 1, a__1[0] = side; i__3[1] = 1, a__1[1] = trans; s_cat(ch__1, a__1, i__3, &c__2, (ftnlen)2); i__1 = 2, i__2 = ilaenv_(&c__2, "SORMQL", ch__1, m, n, k, &c_n1, ( ftnlen)6, (ftnlen)2); nbmin = max(i__1,i__2); } } else { iws = nw; } if ((nb < nbmin) || (nb >= *k)) { /* Use unblocked code */ sorm2l_(side, trans, m, n, k, &a[a_offset], lda, &tau[1], &c__[ c_offset], ldc, &work[1], &iinfo); } else { /* Use blocked code */ if ((left && notran) || (! left && ! notran)) { i1 = 1; i2 = *k; i3 = nb; } else { i1 = (*k - 1) / nb * nb + 1; i2 = 1; i3 = -nb; } if (left) { ni = *n; } else { mi = *m; } i__1 = i2; i__2 = i3; for (i__ = i1; i__2 < 0 ? i__ >= i__1 : i__ <= i__1; i__ += i__2) { /* Computing MIN */ i__4 = nb, i__5 = *k - i__ + 1; ib = min(i__4,i__5); /* Form the triangular factor of the block reflector H = H(i+ib-1) . . . H(i+1) H(i) */ i__4 = nq - *k + i__ + ib - 1; slarft_("Backward", "Columnwise", &i__4, &ib, &a[i__ * a_dim1 + 1] , lda, &tau[i__], t, &c__65); if (left) { /* H or H' is applied to C(1:m-k+i+ib-1,1:n) */ mi = *m - *k + i__ + ib - 1; } else { /* H or H' is applied to C(1:m,1:n-k+i+ib-1) */ ni = *n - *k + i__ + ib - 1; } /* Apply H or H' */ slarfb_(side, trans, "Backward", "Columnwise", &mi, &ni, &ib, &a[ i__ * a_dim1 + 1], lda, t, &c__65, &c__[c_offset], ldc, & work[1], &ldwork); /* L10: */ } } work[1] = (real) lwkopt; return 0; /* End of SORMQL */ } /* sormql_ */ /* Subroutine */ int sormqr_(char *side, char *trans, integer *m, integer *n, integer *k, real *a, integer *lda, real *tau, real *c__, integer *ldc, real *work, integer *lwork, integer *info) { /* System generated locals */ address a__1[2]; integer a_dim1, a_offset, c_dim1, c_offset, i__1, i__2, i__3[2], i__4, i__5; char ch__1[2]; /* Builtin functions */ /* Subroutine */ int s_cat(char *, char **, integer *, integer *, ftnlen); /* Local variables */ static integer i__; static real t[4160] /* was [65][64] */; static integer i1, i2, i3, ib, ic, jc, nb, mi, ni, nq, nw, iws; static logical left; extern logical lsame_(char *, char *); static integer nbmin, iinfo; extern /* Subroutine */ int sorm2r_(char *, char *, integer *, integer *, integer *, real *, integer *, real *, real *, integer *, real *, integer *), slarfb_(char *, char *, char *, char * , integer *, integer *, integer *, real *, integer *, real *, integer *, real *, integer *, real *, integer *), xerbla_(char *, integer *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); extern /* Subroutine */ int slarft_(char *, char *, integer *, integer *, real *, integer *, real *, real *, integer *); static logical notran; static integer ldwork, lwkopt; static logical lquery; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= SORMQR overwrites the general real M-by-N matrix C with SIDE = 'L' SIDE = 'R' TRANS = 'N': Q * C C * Q TRANS = 'T': Q**T * C C * Q**T where Q is a real orthogonal matrix defined as the product of k elementary reflectors Q = H(1) H(2) . . . H(k) as returned by SGEQRF. Q is of order M if SIDE = 'L' and of order N if SIDE = 'R'. Arguments ========= SIDE (input) CHARACTER*1 = 'L': apply Q or Q**T from the Left; = 'R': apply Q or Q**T from the Right. TRANS (input) CHARACTER*1 = 'N': No transpose, apply Q; = 'T': Transpose, apply Q**T. M (input) INTEGER The number of rows of the matrix C. M >= 0. N (input) INTEGER The number of columns of the matrix C. N >= 0. K (input) INTEGER The number of elementary reflectors whose product defines the matrix Q. If SIDE = 'L', M >= K >= 0; if SIDE = 'R', N >= K >= 0. A (input) REAL array, dimension (LDA,K) The i-th column must contain the vector which defines the elementary reflector H(i), for i = 1,2,...,k, as returned by SGEQRF in the first k columns of its array argument A. A is modified by the routine but restored on exit. LDA (input) INTEGER The leading dimension of the array A. If SIDE = 'L', LDA >= max(1,M); if SIDE = 'R', LDA >= max(1,N). TAU (input) REAL array, dimension (K) TAU(i) must contain the scalar factor of the elementary reflector H(i), as returned by SGEQRF. C (input/output) REAL array, dimension (LDC,N) On entry, the M-by-N matrix C. On exit, C is overwritten by Q*C or Q**T*C or C*Q**T or C*Q. LDC (input) INTEGER The leading dimension of the array C. LDC >= max(1,M). WORK (workspace/output) REAL array, dimension (LWORK) On exit, if INFO = 0, WORK(1) returns the optimal LWORK. LWORK (input) INTEGER The dimension of the array WORK. If SIDE = 'L', LWORK >= max(1,N); if SIDE = 'R', LWORK >= max(1,M). For optimum performance LWORK >= N*NB if SIDE = 'L', and LWORK >= M*NB if SIDE = 'R', where NB is the optimal blocksize. If LWORK = -1, then a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued by XERBLA. INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value ===================================================================== Test the input arguments */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --tau; c_dim1 = *ldc; c_offset = 1 + c_dim1; c__ -= c_offset; --work; /* Function Body */ *info = 0; left = lsame_(side, "L"); notran = lsame_(trans, "N"); lquery = *lwork == -1; /* NQ is the order of Q and NW is the minimum dimension of WORK */ if (left) { nq = *m; nw = *n; } else { nq = *n; nw = *m; } if (! left && ! lsame_(side, "R")) { *info = -1; } else if (! notran && ! lsame_(trans, "T")) { *info = -2; } else if (*m < 0) { *info = -3; } else if (*n < 0) { *info = -4; } else if ((*k < 0) || (*k > nq)) { *info = -5; } else if (*lda < max(1,nq)) { *info = -7; } else if (*ldc < max(1,*m)) { *info = -10; } else if (*lwork < max(1,nw) && ! lquery) { *info = -12; } if (*info == 0) { /* Determine the block size. NB may be at most NBMAX, where NBMAX is used to define the local array T. Computing MIN Writing concatenation */ i__3[0] = 1, a__1[0] = side; i__3[1] = 1, a__1[1] = trans; s_cat(ch__1, a__1, i__3, &c__2, (ftnlen)2); i__1 = 64, i__2 = ilaenv_(&c__1, "SORMQR", ch__1, m, n, k, &c_n1, ( ftnlen)6, (ftnlen)2); nb = min(i__1,i__2); lwkopt = max(1,nw) * nb; work[1] = (real) lwkopt; } if (*info != 0) { i__1 = -(*info); xerbla_("SORMQR", &i__1); return 0; } else if (lquery) { return 0; } /* Quick return if possible */ if (((*m == 0) || (*n == 0)) || (*k == 0)) { work[1] = 1.f; return 0; } nbmin = 2; ldwork = nw; if (nb > 1 && nb < *k) { iws = nw * nb; if (*lwork < iws) { nb = *lwork / ldwork; /* Computing MAX Writing concatenation */ i__3[0] = 1, a__1[0] = side; i__3[1] = 1, a__1[1] = trans; s_cat(ch__1, a__1, i__3, &c__2, (ftnlen)2); i__1 = 2, i__2 = ilaenv_(&c__2, "SORMQR", ch__1, m, n, k, &c_n1, ( ftnlen)6, (ftnlen)2); nbmin = max(i__1,i__2); } } else { iws = nw; } if ((nb < nbmin) || (nb >= *k)) { /* Use unblocked code */ sorm2r_(side, trans, m, n, k, &a[a_offset], lda, &tau[1], &c__[ c_offset], ldc, &work[1], &iinfo); } else { /* Use blocked code */ if ((left && ! notran) || (! left && notran)) { i1 = 1; i2 = *k; i3 = nb; } else { i1 = (*k - 1) / nb * nb + 1; i2 = 1; i3 = -nb; } if (left) { ni = *n; jc = 1; } else { mi = *m; ic = 1; } i__1 = i2; i__2 = i3; for (i__ = i1; i__2 < 0 ? i__ >= i__1 : i__ <= i__1; i__ += i__2) { /* Computing MIN */ i__4 = nb, i__5 = *k - i__ + 1; ib = min(i__4,i__5); /* Form the triangular factor of the block reflector H = H(i) H(i+1) . . . H(i+ib-1) */ i__4 = nq - i__ + 1; slarft_("Forward", "Columnwise", &i__4, &ib, &a[i__ + i__ * a_dim1], lda, &tau[i__], t, &c__65) ; if (left) { /* H or H' is applied to C(i:m,1:n) */ mi = *m - i__ + 1; ic = i__; } else { /* H or H' is applied to C(1:m,i:n) */ ni = *n - i__ + 1; jc = i__; } /* Apply H or H' */ slarfb_(side, trans, "Forward", "Columnwise", &mi, &ni, &ib, &a[ i__ + i__ * a_dim1], lda, t, &c__65, &c__[ic + jc * c_dim1], ldc, &work[1], &ldwork); /* L10: */ } } work[1] = (real) lwkopt; return 0; /* End of SORMQR */ } /* sormqr_ */ /* Subroutine */ int sormtr_(char *side, char *uplo, char *trans, integer *m, integer *n, real *a, integer *lda, real *tau, real *c__, integer *ldc, real *work, integer *lwork, integer *info) { /* System generated locals */ address a__1[2]; integer a_dim1, a_offset, c_dim1, c_offset, i__1[2], i__2, i__3; char ch__1[2]; /* Builtin functions */ /* Subroutine */ int s_cat(char *, char **, integer *, integer *, ftnlen); /* Local variables */ static integer i1, i2, nb, mi, ni, nq, nw; static logical left; extern logical lsame_(char *, char *); static integer iinfo; static logical upper; extern /* Subroutine */ int xerbla_(char *, integer *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); extern /* Subroutine */ int sormql_(char *, char *, integer *, integer *, integer *, real *, integer *, real *, real *, integer *, real *, integer *, integer *); static integer lwkopt; static logical lquery; extern /* Subroutine */ int sormqr_(char *, char *, integer *, integer *, integer *, real *, integer *, real *, real *, integer *, real *, integer *, integer *); /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= SORMTR overwrites the general real M-by-N matrix C with SIDE = 'L' SIDE = 'R' TRANS = 'N': Q * C C * Q TRANS = 'T': Q**T * C C * Q**T where Q is a real orthogonal matrix of order nq, with nq = m if SIDE = 'L' and nq = n if SIDE = 'R'. Q is defined as the product of nq-1 elementary reflectors, as returned by SSYTRD: if UPLO = 'U', Q = H(nq-1) . . . H(2) H(1); if UPLO = 'L', Q = H(1) H(2) . . . H(nq-1). Arguments ========= SIDE (input) CHARACTER*1 = 'L': apply Q or Q**T from the Left; = 'R': apply Q or Q**T from the Right. UPLO (input) CHARACTER*1 = 'U': Upper triangle of A contains elementary reflectors from SSYTRD; = 'L': Lower triangle of A contains elementary reflectors from SSYTRD. TRANS (input) CHARACTER*1 = 'N': No transpose, apply Q; = 'T': Transpose, apply Q**T. M (input) INTEGER The number of rows of the matrix C. M >= 0. N (input) INTEGER The number of columns of the matrix C. N >= 0. A (input) REAL array, dimension (LDA,M) if SIDE = 'L' (LDA,N) if SIDE = 'R' The vectors which define the elementary reflectors, as returned by SSYTRD. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,M) if SIDE = 'L'; LDA >= max(1,N) if SIDE = 'R'. TAU (input) REAL array, dimension (M-1) if SIDE = 'L' (N-1) if SIDE = 'R' TAU(i) must contain the scalar factor of the elementary reflector H(i), as returned by SSYTRD. C (input/output) REAL array, dimension (LDC,N) On entry, the M-by-N matrix C. On exit, C is overwritten by Q*C or Q**T*C or C*Q**T or C*Q. LDC (input) INTEGER The leading dimension of the array C. LDC >= max(1,M). WORK (workspace/output) REAL array, dimension (LWORK) On exit, if INFO = 0, WORK(1) returns the optimal LWORK. LWORK (input) INTEGER The dimension of the array WORK. If SIDE = 'L', LWORK >= max(1,N); if SIDE = 'R', LWORK >= max(1,M). For optimum performance LWORK >= N*NB if SIDE = 'L', and LWORK >= M*NB if SIDE = 'R', where NB is the optimal blocksize. If LWORK = -1, then a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued by XERBLA. INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value ===================================================================== Test the input arguments */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --tau; c_dim1 = *ldc; c_offset = 1 + c_dim1; c__ -= c_offset; --work; /* Function Body */ *info = 0; left = lsame_(side, "L"); upper = lsame_(uplo, "U"); lquery = *lwork == -1; /* NQ is the order of Q and NW is the minimum dimension of WORK */ if (left) { nq = *m; nw = *n; } else { nq = *n; nw = *m; } if (! left && ! lsame_(side, "R")) { *info = -1; } else if (! upper && ! lsame_(uplo, "L")) { *info = -2; } else if (! lsame_(trans, "N") && ! lsame_(trans, "T")) { *info = -3; } else if (*m < 0) { *info = -4; } else if (*n < 0) { *info = -5; } else if (*lda < max(1,nq)) { *info = -7; } else if (*ldc < max(1,*m)) { *info = -10; } else if (*lwork < max(1,nw) && ! lquery) { *info = -12; } if (*info == 0) { if (upper) { if (left) { /* Writing concatenation */ i__1[0] = 1, a__1[0] = side; i__1[1] = 1, a__1[1] = trans; s_cat(ch__1, a__1, i__1, &c__2, (ftnlen)2); i__2 = *m - 1; i__3 = *m - 1; nb = ilaenv_(&c__1, "SORMQL", ch__1, &i__2, n, &i__3, &c_n1, ( ftnlen)6, (ftnlen)2); } else { /* Writing concatenation */ i__1[0] = 1, a__1[0] = side; i__1[1] = 1, a__1[1] = trans; s_cat(ch__1, a__1, i__1, &c__2, (ftnlen)2); i__2 = *n - 1; i__3 = *n - 1; nb = ilaenv_(&c__1, "SORMQL", ch__1, m, &i__2, &i__3, &c_n1, ( ftnlen)6, (ftnlen)2); } } else { if (left) { /* Writing concatenation */ i__1[0] = 1, a__1[0] = side; i__1[1] = 1, a__1[1] = trans; s_cat(ch__1, a__1, i__1, &c__2, (ftnlen)2); i__2 = *m - 1; i__3 = *m - 1; nb = ilaenv_(&c__1, "SORMQR", ch__1, &i__2, n, &i__3, &c_n1, ( ftnlen)6, (ftnlen)2); } else { /* Writing concatenation */ i__1[0] = 1, a__1[0] = side; i__1[1] = 1, a__1[1] = trans; s_cat(ch__1, a__1, i__1, &c__2, (ftnlen)2); i__2 = *n - 1; i__3 = *n - 1; nb = ilaenv_(&c__1, "SORMQR", ch__1, m, &i__2, &i__3, &c_n1, ( ftnlen)6, (ftnlen)2); } } lwkopt = max(1,nw) * nb; work[1] = (real) lwkopt; } if (*info != 0) { i__2 = -(*info); xerbla_("SORMTR", &i__2); return 0; } else if (lquery) { return 0; } /* Quick return if possible */ if (((*m == 0) || (*n == 0)) || (nq == 1)) { work[1] = 1.f; return 0; } if (left) { mi = *m - 1; ni = *n; } else { mi = *m; ni = *n - 1; } if (upper) { /* Q was determined by a call to SSYTRD with UPLO = 'U' */ i__2 = nq - 1; sormql_(side, trans, &mi, &ni, &i__2, &a[((a_dim1) << (1)) + 1], lda, &tau[1], &c__[c_offset], ldc, &work[1], lwork, &iinfo); } else { /* Q was determined by a call to SSYTRD with UPLO = 'L' */ if (left) { i1 = 2; i2 = 1; } else { i1 = 1; i2 = 2; } i__2 = nq - 1; sormqr_(side, trans, &mi, &ni, &i__2, &a[a_dim1 + 2], lda, &tau[1], & c__[i1 + i2 * c_dim1], ldc, &work[1], lwork, &iinfo); } work[1] = (real) lwkopt; return 0; /* End of SORMTR */ } /* sormtr_ */ /* Subroutine */ int spotf2_(char *uplo, integer *n, real *a, integer *lda, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3; real r__1; /* Builtin functions */ double sqrt(doublereal); /* Local variables */ static integer j; static real ajj; extern doublereal sdot_(integer *, real *, integer *, real *, integer *); extern logical lsame_(char *, char *); extern /* Subroutine */ int sscal_(integer *, real *, real *, integer *), sgemv_(char *, integer *, integer *, real *, real *, integer *, real *, integer *, real *, real *, integer *); static logical upper; extern /* Subroutine */ int xerbla_(char *, integer *); /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University February 29, 1992 Purpose ======= SPOTF2 computes the Cholesky factorization of a real symmetric positive definite matrix A. The factorization has the form A = U' * U , if UPLO = 'U', or A = L * L', if UPLO = 'L', where U is an upper triangular matrix and L is lower triangular. This is the unblocked version of the algorithm, calling Level 2 BLAS. Arguments ========= UPLO (input) CHARACTER*1 Specifies whether the upper or lower triangular part of the symmetric matrix A is stored. = 'U': Upper triangular = 'L': Lower triangular N (input) INTEGER The order of the matrix A. N >= 0. A (input/output) REAL 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, and the strictly lower triangular part of A is not referenced. If UPLO = 'L', the leading n by n lower triangular part of A contains the lower triangular part of the matrix A, and the strictly upper triangular part of A is not referenced. On exit, if INFO = 0, the factor U or L from the Cholesky factorization A = U'*U or A = L*L'. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,N). INFO (output) INTEGER = 0: successful exit < 0: if INFO = -k, the k-th argument had an illegal value > 0: if INFO = k, the leading minor of order k is not positive definite, and the factorization could not be completed. ===================================================================== Test the input parameters. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; /* Function Body */ *info = 0; upper = lsame_(uplo, "U"); if (! upper && ! lsame_(uplo, "L")) { *info = -1; } else if (*n < 0) { *info = -2; } else if (*lda < max(1,*n)) { *info = -4; } if (*info != 0) { i__1 = -(*info); xerbla_("SPOTF2", &i__1); return 0; } /* Quick return if possible */ if (*n == 0) { return 0; } if (upper) { /* Compute the Cholesky factorization A = U'*U. */ i__1 = *n; for (j = 1; j <= i__1; ++j) { /* Compute U(J,J) and test for non-positive-definiteness. */ i__2 = j - 1; ajj = a[j + j * a_dim1] - sdot_(&i__2, &a[j * a_dim1 + 1], &c__1, &a[j * a_dim1 + 1], &c__1); if (ajj <= 0.f) { a[j + j * a_dim1] = ajj; goto L30; } ajj = sqrt(ajj); a[j + j * a_dim1] = ajj; /* Compute elements J+1:N of row J. */ if (j < *n) { i__2 = j - 1; i__3 = *n - j; sgemv_("Transpose", &i__2, &i__3, &c_b1290, &a[(j + 1) * a_dim1 + 1], lda, &a[j * a_dim1 + 1], &c__1, &c_b1011, &a[j + (j + 1) * a_dim1], lda); i__2 = *n - j; r__1 = 1.f / ajj; sscal_(&i__2, &r__1, &a[j + (j + 1) * a_dim1], lda); } /* L10: */ } } else { /* Compute the Cholesky factorization A = L*L'. */ i__1 = *n; for (j = 1; j <= i__1; ++j) { /* Compute L(J,J) and test for non-positive-definiteness. */ i__2 = j - 1; ajj = a[j + j * a_dim1] - sdot_(&i__2, &a[j + a_dim1], lda, &a[j + a_dim1], lda); if (ajj <= 0.f) { a[j + j * a_dim1] = ajj; goto L30; } ajj = sqrt(ajj); a[j + j * a_dim1] = ajj; /* Compute elements J+1:N of column J. */ if (j < *n) { i__2 = *n - j; i__3 = j - 1; sgemv_("No transpose", &i__2, &i__3, &c_b1290, &a[j + 1 + a_dim1], lda, &a[j + a_dim1], lda, &c_b1011, &a[j + 1 + j * a_dim1], &c__1); i__2 = *n - j; r__1 = 1.f / ajj; sscal_(&i__2, &r__1, &a[j + 1 + j * a_dim1], &c__1); } /* L20: */ } } goto L40; L30: *info = j; L40: return 0; /* End of SPOTF2 */ } /* spotf2_ */ /* Subroutine */ int spotrf_(char *uplo, integer *n, real *a, integer *lda, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3, i__4; /* Local variables */ static integer j, jb, nb; extern logical lsame_(char *, char *); extern /* Subroutine */ int sgemm_(char *, char *, integer *, integer *, integer *, real *, real *, integer *, real *, integer *, real *, real *, integer *); static logical upper; extern /* Subroutine */ int strsm_(char *, char *, char *, char *, integer *, integer *, real *, real *, integer *, real *, integer * ), ssyrk_(char *, char *, integer *, integer *, real *, real *, integer *, real *, real *, integer * ), spotf2_(char *, integer *, real *, integer *, integer *), xerbla_(char *, integer *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University March 31, 1993 Purpose ======= SPOTRF computes the Cholesky factorization of a real symmetric positive definite matrix A. The factorization has the form A = U**T * U, if UPLO = 'U', or A = L * L**T, if UPLO = 'L', where U is an upper triangular matrix and L is lower triangular. This is the block version of the algorithm, calling Level 3 BLAS. Arguments ========= UPLO (input) CHARACTER*1 = 'U': Upper triangle of A is stored; = 'L': Lower triangle of A is stored. N (input) INTEGER The order of the matrix A. N >= 0. A (input/output) REAL 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, and the strictly lower triangular part of A is not referenced. If UPLO = 'L', the leading N-by-N lower triangular part of A contains the lower triangular part of the matrix A, and the strictly upper triangular part of A is not referenced. On exit, if INFO = 0, the factor U or L from the Cholesky factorization A = U**T*U or A = L*L**T. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,N). INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value > 0: if INFO = i, the leading minor of order i is not positive definite, and the factorization could not be completed. ===================================================================== Test the input parameters. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; /* Function Body */ *info = 0; upper = lsame_(uplo, "U"); if (! upper && ! lsame_(uplo, "L")) { *info = -1; } else if (*n < 0) { *info = -2; } else if (*lda < max(1,*n)) { *info = -4; } if (*info != 0) { i__1 = -(*info); xerbla_("SPOTRF", &i__1); return 0; } /* Quick return if possible */ if (*n == 0) { return 0; } /* Determine the block size for this environment. */ nb = ilaenv_(&c__1, "SPOTRF", uplo, n, &c_n1, &c_n1, &c_n1, (ftnlen)6, ( ftnlen)1); if ((nb <= 1) || (nb >= *n)) { /* Use unblocked code. */ spotf2_(uplo, n, &a[a_offset], lda, info); } else { /* Use blocked code. */ if (upper) { /* Compute the Cholesky factorization A = U'*U. */ i__1 = *n; i__2 = nb; for (j = 1; i__2 < 0 ? j >= i__1 : j <= i__1; j += i__2) { /* Update and factorize the current diagonal block and test for non-positive-definiteness. Computing MIN */ i__3 = nb, i__4 = *n - j + 1; jb = min(i__3,i__4); i__3 = j - 1; ssyrk_("Upper", "Transpose", &jb, &i__3, &c_b1290, &a[j * a_dim1 + 1], lda, &c_b1011, &a[j + j * a_dim1], lda); spotf2_("Upper", &jb, &a[j + j * a_dim1], lda, info); if (*info != 0) { goto L30; } if (j + jb <= *n) { /* Compute the current block row. */ i__3 = *n - j - jb + 1; i__4 = j - 1; sgemm_("Transpose", "No transpose", &jb, &i__3, &i__4, & c_b1290, &a[j * a_dim1 + 1], lda, &a[(j + jb) * a_dim1 + 1], lda, &c_b1011, &a[j + (j + jb) * a_dim1], lda); i__3 = *n - j - jb + 1; strsm_("Left", "Upper", "Transpose", "Non-unit", &jb, & i__3, &c_b1011, &a[j + j * a_dim1], lda, &a[j + ( j + jb) * a_dim1], lda); } /* L10: */ } } else { /* Compute the Cholesky factorization A = L*L'. */ i__2 = *n; i__1 = nb; for (j = 1; i__1 < 0 ? j >= i__2 : j <= i__2; j += i__1) { /* Update and factorize the current diagonal block and test for non-positive-definiteness. Computing MIN */ i__3 = nb, i__4 = *n - j + 1; jb = min(i__3,i__4); i__3 = j - 1; ssyrk_("Lower", "No transpose", &jb, &i__3, &c_b1290, &a[j + a_dim1], lda, &c_b1011, &a[j + j * a_dim1], lda); spotf2_("Lower", &jb, &a[j + j * a_dim1], lda, info); if (*info != 0) { goto L30; } if (j + jb <= *n) { /* Compute the current block column. */ i__3 = *n - j - jb + 1; i__4 = j - 1; sgemm_("No transpose", "Transpose", &i__3, &jb, &i__4, & c_b1290, &a[j + jb + a_dim1], lda, &a[j + a_dim1], lda, &c_b1011, &a[j + jb + j * a_dim1], lda); i__3 = *n - j - jb + 1; strsm_("Right", "Lower", "Transpose", "Non-unit", &i__3, & jb, &c_b1011, &a[j + j * a_dim1], lda, &a[j + jb + j * a_dim1], lda); } /* L20: */ } } } goto L40; L30: *info = *info + j - 1; L40: return 0; /* End of SPOTRF */ } /* spotrf_ */ /* Subroutine */ int spotri_(char *uplo, integer *n, real *a, integer *lda, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1; /* Local variables */ extern logical lsame_(char *, char *); extern /* Subroutine */ int xerbla_(char *, integer *), slauum_( char *, integer *, real *, integer *, integer *), strtri_( char *, char *, integer *, real *, integer *, integer *); /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University March 31, 1993 Purpose ======= SPOTRI computes the inverse of a real symmetric positive definite matrix A using the Cholesky factorization A = U**T*U or A = L*L**T computed by SPOTRF. Arguments ========= UPLO (input) CHARACTER*1 = 'U': Upper triangle of A is stored; = 'L': Lower triangle of A is stored. N (input) INTEGER The order of the matrix A. N >= 0. A (input/output) REAL array, dimension (LDA,N) On entry, the triangular factor U or L from the Cholesky factorization A = U**T*U or A = L*L**T, as computed by SPOTRF. On exit, the upper or lower triangle of the (symmetric) inverse of A, overwriting the input factor U or L. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,N). INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value > 0: if INFO = i, the (i,i) element of the factor U or L is zero, and the inverse could not be computed. ===================================================================== Test the input parameters. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; /* Function Body */ *info = 0; if (! lsame_(uplo, "U") && ! lsame_(uplo, "L")) { *info = -1; } else if (*n < 0) { *info = -2; } else if (*lda < max(1,*n)) { *info = -4; } if (*info != 0) { i__1 = -(*info); xerbla_("SPOTRI", &i__1); return 0; } /* Quick return if possible */ if (*n == 0) { return 0; } /* Invert the triangular Cholesky factor U or L. */ strtri_(uplo, "Non-unit", n, &a[a_offset], lda, info); if (*info > 0) { return 0; } /* Form inv(U)*inv(U)' or inv(L)'*inv(L). */ slauum_(uplo, n, &a[a_offset], lda, info); return 0; /* End of SPOTRI */ } /* spotri_ */ /* Subroutine */ int spotrs_(char *uplo, integer *n, integer *nrhs, real *a, integer *lda, real *b, integer *ldb, integer *info) { /* System generated locals */ integer a_dim1, a_offset, b_dim1, b_offset, i__1; /* Local variables */ extern logical lsame_(char *, char *); static logical upper; extern /* Subroutine */ int strsm_(char *, char *, char *, char *, integer *, integer *, real *, real *, integer *, real *, integer * ), xerbla_(char *, integer *); /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University March 31, 1993 Purpose ======= SPOTRS solves a system of linear equations A*X = B with a symmetric positive definite matrix A using the Cholesky factorization A = U**T*U or A = L*L**T computed by SPOTRF. Arguments ========= UPLO (input) CHARACTER*1 = 'U': Upper triangle of A is stored; = 'L': Lower triangle of A is stored. N (input) INTEGER The order of the matrix A. N >= 0. NRHS (input) INTEGER The number of right hand sides, i.e., the number of columns of the matrix B. NRHS >= 0. A (input) REAL array, dimension (LDA,N) The triangular factor U or L from the Cholesky factorization A = U**T*U or A = L*L**T, as computed by SPOTRF. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,N). B (input/output) REAL array, dimension (LDB,NRHS) On entry, the right hand side matrix B. On exit, the solution matrix X. LDB (input) INTEGER The leading dimension of the array B. LDB >= max(1,N). INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value ===================================================================== Test the input parameters. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; b_dim1 = *ldb; b_offset = 1 + b_dim1; b -= b_offset; /* Function Body */ *info = 0; upper = lsame_(uplo, "U"); if (! upper && ! lsame_(uplo, "L")) { *info = -1; } else if (*n < 0) { *info = -2; } else if (*nrhs < 0) { *info = -3; } else if (*lda < max(1,*n)) { *info = -5; } else if (*ldb < max(1,*n)) { *info = -7; } if (*info != 0) { i__1 = -(*info); xerbla_("SPOTRS", &i__1); return 0; } /* Quick return if possible */ if ((*n == 0) || (*nrhs == 0)) { return 0; } if (upper) { /* Solve A*X = B where A = U'*U. Solve U'*X = B, overwriting B with X. */ strsm_("Left", "Upper", "Transpose", "Non-unit", n, nrhs, &c_b1011, & a[a_offset], lda, &b[b_offset], ldb); /* Solve U*X = B, overwriting B with X. */ strsm_("Left", "Upper", "No transpose", "Non-unit", n, nrhs, &c_b1011, &a[a_offset], lda, &b[b_offset], ldb); } else { /* Solve A*X = B where A = L*L'. Solve L*X = B, overwriting B with X. */ strsm_("Left", "Lower", "No transpose", "Non-unit", n, nrhs, &c_b1011, &a[a_offset], lda, &b[b_offset], ldb); /* Solve L'*X = B, overwriting B with X. */ strsm_("Left", "Lower", "Transpose", "Non-unit", n, nrhs, &c_b1011, & a[a_offset], lda, &b[b_offset], ldb); } return 0; /* End of SPOTRS */ } /* spotrs_ */ /* Subroutine */ int sstedc_(char *compz, integer *n, real *d__, real *e, real *z__, integer *ldz, real *work, integer *lwork, integer *iwork, integer *liwork, integer *info) { /* System generated locals */ integer z_dim1, z_offset, i__1, i__2; real r__1, r__2; /* Builtin functions */ double log(doublereal); integer pow_ii(integer *, integer *); double sqrt(doublereal); /* Local variables */ static integer i__, j, k, m; static real p; static integer ii, end, lgn; static real eps, tiny; extern logical lsame_(char *, char *); extern /* Subroutine */ int sgemm_(char *, char *, integer *, integer *, integer *, real *, real *, integer *, real *, integer *, real *, real *, integer *); static integer lwmin, start; extern /* Subroutine */ int sswap_(integer *, real *, integer *, real *, integer *), slaed0_(integer *, integer *, integer *, real *, real *, real *, integer *, real *, integer *, real *, integer *, integer *); extern doublereal slamch_(char *); extern /* Subroutine */ int xerbla_(char *, integer *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); extern /* Subroutine */ int slascl_(char *, integer *, integer *, real *, real *, integer *, integer *, real *, integer *, integer *), slacpy_(char *, integer *, integer *, real *, integer *, real *, integer *), slaset_(char *, integer *, integer *, real *, real *, real *, integer *); static integer liwmin, icompz; static real orgnrm; extern doublereal slanst_(char *, integer *, real *, real *); extern /* Subroutine */ int ssterf_(integer *, real *, real *, integer *), slasrt_(char *, integer *, real *, integer *); static logical lquery; static integer smlsiz; extern /* Subroutine */ int ssteqr_(char *, integer *, real *, real *, real *, integer *, real *, integer *); static integer storez, strtrw; /* -- LAPACK driver routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= SSTEDC computes all eigenvalues and, optionally, eigenvectors of a symmetric tridiagonal matrix using the divide and conquer method. The eigenvectors of a full or band real symmetric matrix can also be found if SSYTRD or SSPTRD or SSBTRD has been used to reduce this matrix to tridiagonal form. This code makes very mild assumptions about floating point arithmetic. It will work on machines with a guard digit in add/subtract, or on those binary machines without guard digits which subtract like the Cray X-MP, Cray Y-MP, Cray C-90, or Cray-2. It could conceivably fail on hexadecimal or decimal machines without guard digits, but we know of none. See SLAED3 for details. Arguments ========= COMPZ (input) CHARACTER*1 = 'N': Compute eigenvalues only. = 'I': Compute eigenvectors of tridiagonal matrix also. = 'V': Compute eigenvectors of original dense symmetric matrix also. On entry, Z contains the orthogonal matrix used to reduce the original matrix to tridiagonal form. N (input) INTEGER The dimension of the symmetric tridiagonal matrix. N >= 0. D (input/output) REAL array, dimension (N) On entry, the diagonal elements of the tridiagonal matrix. On exit, if INFO = 0, the eigenvalues in ascending order. E (input/output) REAL array, dimension (N-1) On entry, the subdiagonal elements of the tridiagonal matrix. On exit, E has been destroyed. Z (input/output) REAL array, dimension (LDZ,N) On entry, if COMPZ = 'V', then Z contains the orthogonal matrix used in the reduction to tridiagonal form. On exit, if INFO = 0, then if COMPZ = 'V', Z contains the orthonormal eigenvectors of the original symmetric matrix, and if COMPZ = 'I', Z contains the orthonormal eigenvectors of the symmetric tridiagonal matrix. If COMPZ = 'N', then Z is not referenced. LDZ (input) INTEGER The leading dimension of the array Z. LDZ >= 1. If eigenvectors are desired, then LDZ >= max(1,N). WORK (workspace/output) REAL array, dimension (LWORK) On exit, if INFO = 0, WORK(1) returns the optimal LWORK. LWORK (input) INTEGER The dimension of the array WORK. If COMPZ = 'N' or N <= 1 then LWORK must be at least 1. If COMPZ = 'V' and N > 1 then LWORK must be at least ( 1 + 3*N + 2*N*lg N + 3*N**2 ), where lg( N ) = smallest integer k such that 2**k >= N. If COMPZ = 'I' and N > 1 then LWORK must be at least ( 1 + 4*N + N**2 ). If LWORK = -1, then a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued by XERBLA. IWORK (workspace/output) INTEGER array, dimension (LIWORK) On exit, if INFO = 0, IWORK(1) returns the optimal LIWORK. LIWORK (input) INTEGER The dimension of the array IWORK. If COMPZ = 'N' or N <= 1 then LIWORK must be at least 1. If COMPZ = 'V' and N > 1 then LIWORK must be at least ( 6 + 6*N + 5*N*lg N ). If COMPZ = 'I' and N > 1 then LIWORK must be at least ( 3 + 5*N ). If LIWORK = -1, then a workspace query is assumed; the routine only calculates the optimal size of the IWORK array, returns this value as the first entry of the IWORK array, and no error message related to LIWORK is issued by XERBLA. INFO (output) INTEGER = 0: successful exit. < 0: if INFO = -i, the i-th argument had an illegal value. > 0: The algorithm failed to compute an eigenvalue while working on the submatrix lying in rows and columns INFO/(N+1) through mod(INFO,N+1). Further Details =============== Based on contributions by Jeff Rutter, Computer Science Division, University of California at Berkeley, USA Modified by Francoise Tisseur, University of Tennessee. ===================================================================== Test the input parameters. */ /* Parameter adjustments */ --d__; --e; z_dim1 = *ldz; z_offset = 1 + z_dim1; z__ -= z_offset; --work; --iwork; /* Function Body */ *info = 0; lquery = (*lwork == -1) || (*liwork == -1); if (lsame_(compz, "N")) { icompz = 0; } else if (lsame_(compz, "V")) { icompz = 1; } else if (lsame_(compz, "I")) { icompz = 2; } else { icompz = -1; } if ((*n <= 1) || (icompz <= 0)) { liwmin = 1; lwmin = 1; } else { lgn = (integer) (log((real) (*n)) / log(2.f)); if (pow_ii(&c__2, &lgn) < *n) { ++lgn; } if (pow_ii(&c__2, &lgn) < *n) { ++lgn; } if (icompz == 1) { /* Computing 2nd power */ i__1 = *n; lwmin = *n * 3 + 1 + ((*n) << (1)) * lgn + i__1 * i__1 * 3; liwmin = *n * 6 + 6 + *n * 5 * lgn; } else if (icompz == 2) { /* Computing 2nd power */ i__1 = *n; lwmin = ((*n) << (2)) + 1 + i__1 * i__1; liwmin = *n * 5 + 3; } } if (icompz < 0) { *info = -1; } else if (*n < 0) { *info = -2; } else if ((*ldz < 1) || (icompz > 0 && *ldz < max(1,*n))) { *info = -6; } else if (*lwork < lwmin && ! lquery) { *info = -8; } else if (*liwork < liwmin && ! lquery) { *info = -10; } if (*info == 0) { work[1] = (real) lwmin; iwork[1] = liwmin; } if (*info != 0) { i__1 = -(*info); xerbla_("SSTEDC", &i__1); return 0; } else if (lquery) { return 0; } /* Quick return if possible */ if (*n == 0) { return 0; } if (*n == 1) { if (icompz != 0) { z__[z_dim1 + 1] = 1.f; } return 0; } smlsiz = ilaenv_(&c__9, "SSTEDC", " ", &c__0, &c__0, &c__0, &c__0, ( ftnlen)6, (ftnlen)1); /* If the following conditional clause is removed, then the routine will use the Divide and Conquer routine to compute only the eigenvalues, which requires (3N + 3N**2) real workspace and (2 + 5N + 2N lg(N)) integer workspace. Since on many architectures SSTERF is much faster than any other algorithm for finding eigenvalues only, it is used here as the default. If COMPZ = 'N', use SSTERF to compute the eigenvalues. */ if (icompz == 0) { ssterf_(n, &d__[1], &e[1], info); return 0; } /* If N is smaller than the minimum divide size (SMLSIZ+1), then solve the problem with another solver. */ if (*n <= smlsiz) { if (icompz == 0) { ssterf_(n, &d__[1], &e[1], info); return 0; } else if (icompz == 2) { ssteqr_("I", n, &d__[1], &e[1], &z__[z_offset], ldz, &work[1], info); return 0; } else { ssteqr_("V", n, &d__[1], &e[1], &z__[z_offset], ldz, &work[1], info); return 0; } } /* If COMPZ = 'V', the Z matrix must be stored elsewhere for later use. */ if (icompz == 1) { storez = *n * *n + 1; } else { storez = 1; } if (icompz == 2) { slaset_("Full", n, n, &c_b320, &c_b1011, &z__[z_offset], ldz); } /* Scale. */ orgnrm = slanst_("M", n, &d__[1], &e[1]); if (orgnrm == 0.f) { return 0; } eps = slamch_("Epsilon"); start = 1; /* while ( START <= N ) */ L10: if (start <= *n) { /* Let END be the position of the next subdiagonal entry such that E( END ) <= TINY or END = N if no such subdiagonal exists. The matrix identified by the elements between START and END constitutes an independent sub-problem. */ end = start; L20: if (end < *n) { tiny = eps * sqrt((r__1 = d__[end], dabs(r__1))) * sqrt((r__2 = d__[end + 1], dabs(r__2))); if ((r__1 = e[end], dabs(r__1)) > tiny) { ++end; goto L20; } } /* (Sub) Problem determined. Compute its size and solve it. */ m = end - start + 1; if (m == 1) { start = end + 1; goto L10; } if (m > smlsiz) { *info = smlsiz; /* Scale. */ orgnrm = slanst_("M", &m, &d__[start], &e[start]); slascl_("G", &c__0, &c__0, &orgnrm, &c_b1011, &m, &c__1, &d__[ start], &m, info); i__1 = m - 1; i__2 = m - 1; slascl_("G", &c__0, &c__0, &orgnrm, &c_b1011, &i__1, &c__1, &e[ start], &i__2, info); if (icompz == 1) { strtrw = 1; } else { strtrw = start; } slaed0_(&icompz, n, &m, &d__[start], &e[start], &z__[strtrw + start * z_dim1], ldz, &work[1], n, &work[storez], &iwork[ 1], info); if (*info != 0) { *info = (*info / (m + 1) + start - 1) * (*n + 1) + *info % (m + 1) + start - 1; return 0; } /* Scale back. */ slascl_("G", &c__0, &c__0, &c_b1011, &orgnrm, &m, &c__1, &d__[ start], &m, info); } else { if (icompz == 1) { /* Since QR won't update a Z matrix which is larger than the length of D, we must solve the sub-problem in a workspace and then multiply back into Z. */ ssteqr_("I", &m, &d__[start], &e[start], &work[1], &m, &work[ m * m + 1], info); slacpy_("A", n, &m, &z__[start * z_dim1 + 1], ldz, &work[ storez], n); sgemm_("N", "N", n, &m, &m, &c_b1011, &work[storez], ldz, & work[1], &m, &c_b320, &z__[start * z_dim1 + 1], ldz); } else if (icompz == 2) { ssteqr_("I", &m, &d__[start], &e[start], &z__[start + start * z_dim1], ldz, &work[1], info); } else { ssterf_(&m, &d__[start], &e[start], info); } if (*info != 0) { *info = start * (*n + 1) + end; return 0; } } start = end + 1; goto L10; } /* endwhile If the problem split any number of times, then the eigenvalues will not be properly ordered. Here we permute the eigenvalues (and the associated eigenvectors) into ascending order. */ if (m != *n) { if (icompz == 0) { /* Use Quick Sort */ slasrt_("I", n, &d__[1], info); } else { /* Use Selection Sort to minimize swaps of eigenvectors */ i__1 = *n; for (ii = 2; ii <= i__1; ++ii) { i__ = ii - 1; k = i__; p = d__[i__]; i__2 = *n; for (j = ii; j <= i__2; ++j) { if (d__[j] < p) { k = j; p = d__[j]; } /* L30: */ } if (k != i__) { d__[k] = d__[i__]; d__[i__] = p; sswap_(n, &z__[i__ * z_dim1 + 1], &c__1, &z__[k * z_dim1 + 1], &c__1); } /* L40: */ } } } work[1] = (real) lwmin; iwork[1] = liwmin; return 0; /* End of SSTEDC */ } /* sstedc_ */ /* Subroutine */ int ssteqr_(char *compz, integer *n, real *d__, real *e, real *z__, integer *ldz, real *work, integer *info) { /* System generated locals */ integer z_dim1, z_offset, i__1, i__2; real r__1, r__2; /* Builtin functions */ double sqrt(doublereal), r_sign(real *, real *); /* Local variables */ static real b, c__, f, g; static integer i__, j, k, l, m; static real p, r__, s; static integer l1, ii, mm, lm1, mm1, nm1; static real rt1, rt2, eps; static integer lsv; static real tst, eps2; static integer lend, jtot; extern /* Subroutine */ int slae2_(real *, real *, real *, real *, real *) ; extern logical lsame_(char *, char *); static real anorm; extern /* Subroutine */ int slasr_(char *, char *, char *, integer *, integer *, real *, real *, real *, integer *), sswap_(integer *, real *, integer *, real *, integer *); static integer lendm1, lendp1; extern /* Subroutine */ int slaev2_(real *, real *, real *, real *, real * , real *, real *); extern doublereal slapy2_(real *, real *); static integer iscale; extern doublereal slamch_(char *); static real safmin; extern /* Subroutine */ int xerbla_(char *, integer *); static real safmax; extern /* Subroutine */ int slascl_(char *, integer *, integer *, real *, real *, integer *, integer *, real *, integer *, integer *); static integer lendsv; extern /* Subroutine */ int slartg_(real *, real *, real *, real *, real * ), slaset_(char *, integer *, integer *, real *, real *, real *, integer *); static real ssfmin; static integer nmaxit, icompz; static real ssfmax; extern doublereal slanst_(char *, integer *, real *, real *); extern /* Subroutine */ int slasrt_(char *, integer *, real *, integer *); /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University September 30, 1994 Purpose ======= SSTEQR computes all eigenvalues and, optionally, eigenvectors of a symmetric tridiagonal matrix using the implicit QL or QR method. The eigenvectors of a full or band symmetric matrix can also be found if SSYTRD or SSPTRD or SSBTRD has been used to reduce this matrix to tridiagonal form. Arguments ========= COMPZ (input) CHARACTER*1 = 'N': Compute eigenvalues only. = 'V': Compute eigenvalues and eigenvectors of the original symmetric matrix. On entry, Z must contain the orthogonal matrix used to reduce the original matrix to tridiagonal form. = 'I': Compute eigenvalues and eigenvectors of the tridiagonal matrix. Z is initialized to the identity matrix. N (input) INTEGER The order of the matrix. N >= 0. D (input/output) REAL array, dimension (N) On entry, the diagonal elements of the tridiagonal matrix. On exit, if INFO = 0, the eigenvalues in ascending order. E (input/output) REAL array, dimension (N-1) On entry, the (n-1) subdiagonal elements of the tridiagonal matrix. On exit, E has been destroyed. Z (input/output) REAL array, dimension (LDZ, N) On entry, if COMPZ = 'V', then Z contains the orthogonal matrix used in the reduction to tridiagonal form. On exit, if INFO = 0, then if COMPZ = 'V', Z contains the orthonormal eigenvectors of the original symmetric matrix, and if COMPZ = 'I', Z contains the orthonormal eigenvectors of the symmetric tridiagonal matrix. If COMPZ = 'N', then Z is not referenced. LDZ (input) INTEGER The leading dimension of the array Z. LDZ >= 1, and if eigenvectors are desired, then LDZ >= max(1,N). WORK (workspace) REAL array, dimension (max(1,2*N-2)) If COMPZ = 'N', then WORK is not referenced. INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value > 0: the algorithm has failed to find all the eigenvalues in a total of 30*N iterations; if INFO = i, then i elements of E have not converged to zero; on exit, D and E contain the elements of a symmetric tridiagonal matrix which is orthogonally similar to the original matrix. ===================================================================== Test the input parameters. */ /* Parameter adjustments */ --d__; --e; z_dim1 = *ldz; z_offset = 1 + z_dim1; z__ -= z_offset; --work; /* Function Body */ *info = 0; if (lsame_(compz, "N")) { icompz = 0; } else if (lsame_(compz, "V")) { icompz = 1; } else if (lsame_(compz, "I")) { icompz = 2; } else { icompz = -1; } if (icompz < 0) { *info = -1; } else if (*n < 0) { *info = -2; } else if ((*ldz < 1) || (icompz > 0 && *ldz < max(1,*n))) { *info = -6; } if (*info != 0) { i__1 = -(*info); xerbla_("SSTEQR", &i__1); return 0; } /* Quick return if possible */ if (*n == 0) { return 0; } if (*n == 1) { if (icompz == 2) { z__[z_dim1 + 1] = 1.f; } return 0; } /* Determine the unit roundoff and over/underflow thresholds. */ eps = slamch_("E"); /* Computing 2nd power */ r__1 = eps; eps2 = r__1 * r__1; safmin = slamch_("S"); safmax = 1.f / safmin; ssfmax = sqrt(safmax) / 3.f; ssfmin = sqrt(safmin) / eps2; /* Compute the eigenvalues and eigenvectors of the tridiagonal matrix. */ if (icompz == 2) { slaset_("Full", n, n, &c_b320, &c_b1011, &z__[z_offset], ldz); } nmaxit = *n * 30; jtot = 0; /* Determine where the matrix splits and choose QL or QR iteration for each block, according to whether top or bottom diagonal element is smaller. */ l1 = 1; nm1 = *n - 1; L10: if (l1 > *n) { goto L160; } if (l1 > 1) { e[l1 - 1] = 0.f; } if (l1 <= nm1) { i__1 = nm1; for (m = l1; m <= i__1; ++m) { tst = (r__1 = e[m], dabs(r__1)); if (tst == 0.f) { goto L30; } if (tst <= sqrt((r__1 = d__[m], dabs(r__1))) * sqrt((r__2 = d__[m + 1], dabs(r__2))) * eps) { e[m] = 0.f; goto L30; } /* L20: */ } } m = *n; L30: l = l1; lsv = l; lend = m; lendsv = lend; l1 = m + 1; if (lend == l) { goto L10; } /* Scale submatrix in rows and columns L to LEND */ i__1 = lend - l + 1; anorm = slanst_("I", &i__1, &d__[l], &e[l]); iscale = 0; if (anorm == 0.f) { goto L10; } if (anorm > ssfmax) { iscale = 1; i__1 = lend - l + 1; slascl_("G", &c__0, &c__0, &anorm, &ssfmax, &i__1, &c__1, &d__[l], n, info); i__1 = lend - l; slascl_("G", &c__0, &c__0, &anorm, &ssfmax, &i__1, &c__1, &e[l], n, info); } else if (anorm < ssfmin) { iscale = 2; i__1 = lend - l + 1; slascl_("G", &c__0, &c__0, &anorm, &ssfmin, &i__1, &c__1, &d__[l], n, info); i__1 = lend - l; slascl_("G", &c__0, &c__0, &anorm, &ssfmin, &i__1, &c__1, &e[l], n, info); } /* Choose between QL and QR iteration */ if ((r__1 = d__[lend], dabs(r__1)) < (r__2 = d__[l], dabs(r__2))) { lend = lsv; l = lendsv; } if (lend > l) { /* QL Iteration Look for small subdiagonal element. */ L40: if (l != lend) { lendm1 = lend - 1; i__1 = lendm1; for (m = l; m <= i__1; ++m) { /* Computing 2nd power */ r__2 = (r__1 = e[m], dabs(r__1)); tst = r__2 * r__2; if (tst <= eps2 * (r__1 = d__[m], dabs(r__1)) * (r__2 = d__[m + 1], dabs(r__2)) + safmin) { goto L60; } /* L50: */ } } m = lend; L60: if (m < lend) { e[m] = 0.f; } p = d__[l]; if (m == l) { goto L80; } /* If remaining matrix is 2-by-2, use SLAE2 or SLAEV2 to compute its eigensystem. */ if (m == l + 1) { if (icompz > 0) { slaev2_(&d__[l], &e[l], &d__[l + 1], &rt1, &rt2, &c__, &s); work[l] = c__; work[*n - 1 + l] = s; slasr_("R", "V", "B", n, &c__2, &work[l], &work[*n - 1 + l], & z__[l * z_dim1 + 1], ldz); } else { slae2_(&d__[l], &e[l], &d__[l + 1], &rt1, &rt2); } d__[l] = rt1; d__[l + 1] = rt2; e[l] = 0.f; l += 2; if (l <= lend) { goto L40; } goto L140; } if (jtot == nmaxit) { goto L140; } ++jtot; /* Form shift. */ g = (d__[l + 1] - p) / (e[l] * 2.f); r__ = slapy2_(&g, &c_b1011); g = d__[m] - p + e[l] / (g + r_sign(&r__, &g)); s = 1.f; c__ = 1.f; p = 0.f; /* Inner loop */ mm1 = m - 1; i__1 = l; for (i__ = mm1; i__ >= i__1; --i__) { f = s * e[i__]; b = c__ * e[i__]; slartg_(&g, &f, &c__, &s, &r__); if (i__ != m - 1) { e[i__ + 1] = r__; } g = d__[i__ + 1] - p; r__ = (d__[i__] - g) * s + c__ * 2.f * b; p = s * r__; d__[i__ + 1] = g + p; g = c__ * r__ - b; /* If eigenvectors are desired, then save rotations. */ if (icompz > 0) { work[i__] = c__; work[*n - 1 + i__] = -s; } /* L70: */ } /* If eigenvectors are desired, then apply saved rotations. */ if (icompz > 0) { mm = m - l + 1; slasr_("R", "V", "B", n, &mm, &work[l], &work[*n - 1 + l], &z__[l * z_dim1 + 1], ldz); } d__[l] -= p; e[l] = g; goto L40; /* Eigenvalue found. */ L80: d__[l] = p; ++l; if (l <= lend) { goto L40; } goto L140; } else { /* QR Iteration Look for small superdiagonal element. */ L90: if (l != lend) { lendp1 = lend + 1; i__1 = lendp1; for (m = l; m >= i__1; --m) { /* Computing 2nd power */ r__2 = (r__1 = e[m - 1], dabs(r__1)); tst = r__2 * r__2; if (tst <= eps2 * (r__1 = d__[m], dabs(r__1)) * (r__2 = d__[m - 1], dabs(r__2)) + safmin) { goto L110; } /* L100: */ } } m = lend; L110: if (m > lend) { e[m - 1] = 0.f; } p = d__[l]; if (m == l) { goto L130; } /* If remaining matrix is 2-by-2, use SLAE2 or SLAEV2 to compute its eigensystem. */ if (m == l - 1) { if (icompz > 0) { slaev2_(&d__[l - 1], &e[l - 1], &d__[l], &rt1, &rt2, &c__, &s) ; work[m] = c__; work[*n - 1 + m] = s; slasr_("R", "V", "F", n, &c__2, &work[m], &work[*n - 1 + m], & z__[(l - 1) * z_dim1 + 1], ldz); } else { slae2_(&d__[l - 1], &e[l - 1], &d__[l], &rt1, &rt2); } d__[l - 1] = rt1; d__[l] = rt2; e[l - 1] = 0.f; l += -2; if (l >= lend) { goto L90; } goto L140; } if (jtot == nmaxit) { goto L140; } ++jtot; /* Form shift. */ g = (d__[l - 1] - p) / (e[l - 1] * 2.f); r__ = slapy2_(&g, &c_b1011); g = d__[m] - p + e[l - 1] / (g + r_sign(&r__, &g)); s = 1.f; c__ = 1.f; p = 0.f; /* Inner loop */ lm1 = l - 1; i__1 = lm1; for (i__ = m; i__ <= i__1; ++i__) { f = s * e[i__]; b = c__ * e[i__]; slartg_(&g, &f, &c__, &s, &r__); if (i__ != m) { e[i__ - 1] = r__; } g = d__[i__] - p; r__ = (d__[i__ + 1] - g) * s + c__ * 2.f * b; p = s * r__; d__[i__] = g + p; g = c__ * r__ - b; /* If eigenvectors are desired, then save rotations. */ if (icompz > 0) { work[i__] = c__; work[*n - 1 + i__] = s; } /* L120: */ } /* If eigenvectors are desired, then apply saved rotations. */ if (icompz > 0) { mm = l - m + 1; slasr_("R", "V", "F", n, &mm, &work[m], &work[*n - 1 + m], &z__[m * z_dim1 + 1], ldz); } d__[l] -= p; e[lm1] = g; goto L90; /* Eigenvalue found. */ L130: d__[l] = p; --l; if (l >= lend) { goto L90; } goto L140; } /* Undo scaling if necessary */ L140: if (iscale == 1) { i__1 = lendsv - lsv + 1; slascl_("G", &c__0, &c__0, &ssfmax, &anorm, &i__1, &c__1, &d__[lsv], n, info); i__1 = lendsv - lsv; slascl_("G", &c__0, &c__0, &ssfmax, &anorm, &i__1, &c__1, &e[lsv], n, info); } else if (iscale == 2) { i__1 = lendsv - lsv + 1; slascl_("G", &c__0, &c__0, &ssfmin, &anorm, &i__1, &c__1, &d__[lsv], n, info); i__1 = lendsv - lsv; slascl_("G", &c__0, &c__0, &ssfmin, &anorm, &i__1, &c__1, &e[lsv], n, info); } /* Check for no convergence to an eigenvalue after a total of N*MAXIT iterations. */ if (jtot < nmaxit) { goto L10; } i__1 = *n - 1; for (i__ = 1; i__ <= i__1; ++i__) { if (e[i__] != 0.f) { ++(*info); } /* L150: */ } goto L190; /* Order eigenvalues and eigenvectors. */ L160: if (icompz == 0) { /* Use Quick Sort */ slasrt_("I", n, &d__[1], info); } else { /* Use Selection Sort to minimize swaps of eigenvectors */ i__1 = *n; for (ii = 2; ii <= i__1; ++ii) { i__ = ii - 1; k = i__; p = d__[i__]; i__2 = *n; for (j = ii; j <= i__2; ++j) { if (d__[j] < p) { k = j; p = d__[j]; } /* L170: */ } if (k != i__) { d__[k] = d__[i__]; d__[i__] = p; sswap_(n, &z__[i__ * z_dim1 + 1], &c__1, &z__[k * z_dim1 + 1], &c__1); } /* L180: */ } } L190: return 0; /* End of SSTEQR */ } /* ssteqr_ */ /* Subroutine */ int ssterf_(integer *n, real *d__, real *e, integer *info) { /* System generated locals */ integer i__1; real r__1, r__2, r__3; /* Builtin functions */ double sqrt(doublereal), r_sign(real *, real *); /* Local variables */ static real c__; static integer i__, l, m; static real p, r__, s; static integer l1; static real bb, rt1, rt2, eps, rte; static integer lsv; static real eps2, oldc; static integer lend, jtot; extern /* Subroutine */ int slae2_(real *, real *, real *, real *, real *) ; static real gamma, alpha, sigma, anorm; extern doublereal slapy2_(real *, real *); static integer iscale; static real oldgam; extern doublereal slamch_(char *); static real safmin; extern /* Subroutine */ int xerbla_(char *, integer *); static real safmax; extern /* Subroutine */ int slascl_(char *, integer *, integer *, real *, real *, integer *, integer *, real *, integer *, integer *); static integer lendsv; static real ssfmin; static integer nmaxit; static real ssfmax; extern doublereal slanst_(char *, integer *, real *, real *); extern /* Subroutine */ int slasrt_(char *, integer *, real *, integer *); /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= SSTERF computes all eigenvalues of a symmetric tridiagonal matrix using the Pal-Walker-Kahan variant of the QL or QR algorithm. Arguments ========= N (input) INTEGER The order of the matrix. N >= 0. D (input/output) REAL array, dimension (N) On entry, the n diagonal elements of the tridiagonal matrix. On exit, if INFO = 0, the eigenvalues in ascending order. E (input/output) REAL array, dimension (N-1) On entry, the (n-1) subdiagonal elements of the tridiagonal matrix. On exit, E has been destroyed. INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value > 0: the algorithm failed to find all of the eigenvalues in a total of 30*N iterations; if INFO = i, then i elements of E have not converged to zero. ===================================================================== Test the input parameters. */ /* Parameter adjustments */ --e; --d__; /* Function Body */ *info = 0; /* Quick return if possible */ if (*n < 0) { *info = -1; i__1 = -(*info); xerbla_("SSTERF", &i__1); return 0; } if (*n <= 1) { return 0; } /* Determine the unit roundoff for this environment. */ eps = slamch_("E"); /* Computing 2nd power */ r__1 = eps; eps2 = r__1 * r__1; safmin = slamch_("S"); safmax = 1.f / safmin; ssfmax = sqrt(safmax) / 3.f; ssfmin = sqrt(safmin) / eps2; /* Compute the eigenvalues of the tridiagonal matrix. */ nmaxit = *n * 30; sigma = 0.f; jtot = 0; /* Determine where the matrix splits and choose QL or QR iteration for each block, according to whether top or bottom diagonal element is smaller. */ l1 = 1; L10: if (l1 > *n) { goto L170; } if (l1 > 1) { e[l1 - 1] = 0.f; } i__1 = *n - 1; for (m = l1; m <= i__1; ++m) { if ((r__3 = e[m], dabs(r__3)) <= sqrt((r__1 = d__[m], dabs(r__1))) * sqrt((r__2 = d__[m + 1], dabs(r__2))) * eps) { e[m] = 0.f; goto L30; } /* L20: */ } m = *n; L30: l = l1; lsv = l; lend = m; lendsv = lend; l1 = m + 1; if (lend == l) { goto L10; } /* Scale submatrix in rows and columns L to LEND */ i__1 = lend - l + 1; anorm = slanst_("I", &i__1, &d__[l], &e[l]); iscale = 0; if (anorm > ssfmax) { iscale = 1; i__1 = lend - l + 1; slascl_("G", &c__0, &c__0, &anorm, &ssfmax, &i__1, &c__1, &d__[l], n, info); i__1 = lend - l; slascl_("G", &c__0, &c__0, &anorm, &ssfmax, &i__1, &c__1, &e[l], n, info); } else if (anorm < ssfmin) { iscale = 2; i__1 = lend - l + 1; slascl_("G", &c__0, &c__0, &anorm, &ssfmin, &i__1, &c__1, &d__[l], n, info); i__1 = lend - l; slascl_("G", &c__0, &c__0, &anorm, &ssfmin, &i__1, &c__1, &e[l], n, info); } i__1 = lend - 1; for (i__ = l; i__ <= i__1; ++i__) { /* Computing 2nd power */ r__1 = e[i__]; e[i__] = r__1 * r__1; /* L40: */ } /* Choose between QL and QR iteration */ if ((r__1 = d__[lend], dabs(r__1)) < (r__2 = d__[l], dabs(r__2))) { lend = lsv; l = lendsv; } if (lend >= l) { /* QL Iteration Look for small subdiagonal element. */ L50: if (l != lend) { i__1 = lend - 1; for (m = l; m <= i__1; ++m) { if ((r__2 = e[m], dabs(r__2)) <= eps2 * (r__1 = d__[m] * d__[ m + 1], dabs(r__1))) { goto L70; } /* L60: */ } } m = lend; L70: if (m < lend) { e[m] = 0.f; } p = d__[l]; if (m == l) { goto L90; } /* If remaining matrix is 2 by 2, use SLAE2 to compute its eigenvalues. */ if (m == l + 1) { rte = sqrt(e[l]); slae2_(&d__[l], &rte, &d__[l + 1], &rt1, &rt2); d__[l] = rt1; d__[l + 1] = rt2; e[l] = 0.f; l += 2; if (l <= lend) { goto L50; } goto L150; } if (jtot == nmaxit) { goto L150; } ++jtot; /* Form shift. */ rte = sqrt(e[l]); sigma = (d__[l + 1] - p) / (rte * 2.f); r__ = slapy2_(&sigma, &c_b1011); sigma = p - rte / (sigma + r_sign(&r__, &sigma)); c__ = 1.f; s = 0.f; gamma = d__[m] - sigma; p = gamma * gamma; /* Inner loop */ i__1 = l; for (i__ = m - 1; i__ >= i__1; --i__) { bb = e[i__]; r__ = p + bb; if (i__ != m - 1) { e[i__ + 1] = s * r__; } oldc = c__; c__ = p / r__; s = bb / r__; oldgam = gamma; alpha = d__[i__]; gamma = c__ * (alpha - sigma) - s * oldgam; d__[i__ + 1] = oldgam + (alpha - gamma); if (c__ != 0.f) { p = gamma * gamma / c__; } else { p = oldc * bb; } /* L80: */ } e[l] = s * p; d__[l] = sigma + gamma; goto L50; /* Eigenvalue found. */ L90: d__[l] = p; ++l; if (l <= lend) { goto L50; } goto L150; } else { /* QR Iteration Look for small superdiagonal element. */ L100: i__1 = lend + 1; for (m = l; m >= i__1; --m) { if ((r__2 = e[m - 1], dabs(r__2)) <= eps2 * (r__1 = d__[m] * d__[ m - 1], dabs(r__1))) { goto L120; } /* L110: */ } m = lend; L120: if (m > lend) { e[m - 1] = 0.f; } p = d__[l]; if (m == l) { goto L140; } /* If remaining matrix is 2 by 2, use SLAE2 to compute its eigenvalues. */ if (m == l - 1) { rte = sqrt(e[l - 1]); slae2_(&d__[l], &rte, &d__[l - 1], &rt1, &rt2); d__[l] = rt1; d__[l - 1] = rt2; e[l - 1] = 0.f; l += -2; if (l >= lend) { goto L100; } goto L150; } if (jtot == nmaxit) { goto L150; } ++jtot; /* Form shift. */ rte = sqrt(e[l - 1]); sigma = (d__[l - 1] - p) / (rte * 2.f); r__ = slapy2_(&sigma, &c_b1011); sigma = p - rte / (sigma + r_sign(&r__, &sigma)); c__ = 1.f; s = 0.f; gamma = d__[m] - sigma; p = gamma * gamma; /* Inner loop */ i__1 = l - 1; for (i__ = m; i__ <= i__1; ++i__) { bb = e[i__]; r__ = p + bb; if (i__ != m) { e[i__ - 1] = s * r__; } oldc = c__; c__ = p / r__; s = bb / r__; oldgam = gamma; alpha = d__[i__ + 1]; gamma = c__ * (alpha - sigma) - s * oldgam; d__[i__] = oldgam + (alpha - gamma); if (c__ != 0.f) { p = gamma * gamma / c__; } else { p = oldc * bb; } /* L130: */ } e[l - 1] = s * p; d__[l] = sigma + gamma; goto L100; /* Eigenvalue found. */ L140: d__[l] = p; --l; if (l >= lend) { goto L100; } goto L150; } /* Undo scaling if necessary */ L150: if (iscale == 1) { i__1 = lendsv - lsv + 1; slascl_("G", &c__0, &c__0, &ssfmax, &anorm, &i__1, &c__1, &d__[lsv], n, info); } if (iscale == 2) { i__1 = lendsv - lsv + 1; slascl_("G", &c__0, &c__0, &ssfmin, &anorm, &i__1, &c__1, &d__[lsv], n, info); } /* Check for no convergence to an eigenvalue after a total of N*MAXIT iterations. */ if (jtot < nmaxit) { goto L10; } i__1 = *n - 1; for (i__ = 1; i__ <= i__1; ++i__) { if (e[i__] != 0.f) { ++(*info); } /* L160: */ } goto L180; /* Sort eigenvalues in increasing order. */ L170: slasrt_("I", n, &d__[1], info); L180: return 0; /* End of SSTERF */ } /* ssterf_ */ /* Subroutine */ int ssyevd_(char *jobz, char *uplo, integer *n, real *a, integer *lda, real *w, real *work, integer *lwork, integer *iwork, integer *liwork, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3; real r__1; /* Builtin functions */ double sqrt(doublereal); /* Local variables */ static real eps; static integer inde; static real anrm, rmin, rmax; static integer lopt; static real sigma; extern logical lsame_(char *, char *); static integer iinfo; extern /* Subroutine */ int sscal_(integer *, real *, real *, integer *); static integer lwmin, liopt; static logical lower, wantz; static integer indwk2, llwrk2, iscale; extern doublereal slamch_(char *); static real safmin; extern /* Subroutine */ int xerbla_(char *, integer *); static real bignum; extern /* Subroutine */ int slascl_(char *, integer *, integer *, real *, real *, integer *, integer *, real *, integer *, integer *); static integer indtau; extern /* Subroutine */ int sstedc_(char *, integer *, real *, real *, real *, integer *, real *, integer *, integer *, integer *, integer *), slacpy_(char *, integer *, integer *, real *, integer *, real *, integer *); static integer indwrk, liwmin; extern /* Subroutine */ int ssterf_(integer *, real *, real *, integer *); extern doublereal slansy_(char *, char *, integer *, real *, integer *, real *); static integer llwork; static real smlnum; static logical lquery; extern /* Subroutine */ int sormtr_(char *, char *, char *, integer *, integer *, real *, integer *, real *, real *, integer *, real *, integer *, integer *), ssytrd_(char *, integer *, real *, integer *, real *, real *, real *, real *, integer *, integer *); /* -- LAPACK driver routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= SSYEVD computes all eigenvalues and, optionally, eigenvectors of a real symmetric matrix A. If eigenvectors are desired, it uses a divide and conquer algorithm. The divide and conquer algorithm makes very mild assumptions about floating point arithmetic. It will work on machines with a guard digit in add/subtract, or on those binary machines without guard digits which subtract like the Cray X-MP, Cray Y-MP, Cray C-90, or Cray-2. It could conceivably fail on hexadecimal or decimal machines without guard digits, but we know of none. Because of large use of BLAS of level 3, SSYEVD needs N**2 more workspace than SSYEVX. Arguments ========= JOBZ (input) CHARACTER*1 = 'N': Compute eigenvalues only; = 'V': Compute eigenvalues and eigenvectors. UPLO (input) CHARACTER*1 = 'U': Upper triangle of A is stored; = 'L': Lower triangle of A is stored. N (input) INTEGER The order of the matrix A. N >= 0. A (input/output) REAL 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. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,N). W (output) REAL array, dimension (N) If INFO = 0, the eigenvalues in ascending order. WORK (workspace/output) REAL array, dimension (LWORK) On exit, if INFO = 0, WORK(1) returns the optimal LWORK. LWORK (input) INTEGER The dimension of the array WORK. If N <= 1, LWORK must be at least 1. If JOBZ = 'N' and N > 1, LWORK must be at least 2*N+1. If JOBZ = 'V' and N > 1, LWORK must be at least 1 + 6*N + 2*N**2. If LWORK = -1, then a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued by XERBLA. IWORK (workspace/output) INTEGER array, dimension (LIWORK) On exit, if INFO = 0, IWORK(1) returns the optimal LIWORK. LIWORK (input) INTEGER The dimension of the array IWORK. If N <= 1, LIWORK must be at least 1. If JOBZ = 'N' and N > 1, LIWORK must be at least 1. If JOBZ = 'V' and N > 1, LIWORK must be at least 3 + 5*N. If LIWORK = -1, then a workspace query is assumed; the routine only calculates the optimal size of the IWORK array, returns this value as the first entry of the IWORK array, and no error message related to LIWORK is issued by XERBLA. 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. Further Details =============== Based on contributions by Jeff Rutter, Computer Science Division, University of California at Berkeley, USA Modified by Francoise Tisseur, University of Tennessee. ===================================================================== Test the input parameters. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --w; --work; --iwork; /* Function Body */ wantz = lsame_(jobz, "V"); lower = lsame_(uplo, "L"); lquery = (*lwork == -1) || (*liwork == -1); *info = 0; if (*n <= 1) { liwmin = 1; lwmin = 1; lopt = lwmin; liopt = liwmin; } else { if (wantz) { liwmin = *n * 5 + 3; /* Computing 2nd power */ i__1 = *n; lwmin = *n * 6 + 1 + ((i__1 * i__1) << (1)); } else { liwmin = 1; lwmin = ((*n) << (1)) + 1; } lopt = lwmin; liopt = liwmin; } if (! ((wantz) || (lsame_(jobz, "N")))) { *info = -1; } else if (! ((lower) || (lsame_(uplo, "U")))) { *info = -2; } else if (*n < 0) { *info = -3; } else if (*lda < max(1,*n)) { *info = -5; } else if (*lwork < lwmin && ! lquery) { *info = -8; } else if (*liwork < liwmin && ! lquery) { *info = -10; } if (*info == 0) { work[1] = (real) lopt; iwork[1] = liopt; } if (*info != 0) { i__1 = -(*info); xerbla_("SSYEVD", &i__1); return 0; } else if (lquery) { return 0; } /* Quick return if possible */ if (*n == 0) { return 0; } if (*n == 1) { w[1] = a[a_dim1 + 1]; if (wantz) { a[a_dim1 + 1] = 1.f; } return 0; } /* Get machine constants. */ safmin = slamch_("Safe minimum"); eps = slamch_("Precision"); smlnum = safmin / eps; bignum = 1.f / smlnum; rmin = sqrt(smlnum); rmax = sqrt(bignum); /* Scale matrix to allowable range, if necessary. */ anrm = slansy_("M", uplo, n, &a[a_offset], lda, &work[1]); iscale = 0; if (anrm > 0.f && anrm < rmin) { iscale = 1; sigma = rmin / anrm; } else if (anrm > rmax) { iscale = 1; sigma = rmax / anrm; } if (iscale == 1) { slascl_(uplo, &c__0, &c__0, &c_b1011, &sigma, n, n, &a[a_offset], lda, info); } /* Call SSYTRD to reduce symmetric matrix to tridiagonal form. */ inde = 1; indtau = inde + *n; indwrk = indtau + *n; llwork = *lwork - indwrk + 1; indwk2 = indwrk + *n * *n; llwrk2 = *lwork - indwk2 + 1; ssytrd_(uplo, n, &a[a_offset], lda, &w[1], &work[inde], &work[indtau], & work[indwrk], &llwork, &iinfo); lopt = ((*n) << (1)) + work[indwrk]; /* For eigenvalues only, call SSTERF. For eigenvectors, first call SSTEDC to generate the eigenvector matrix, WORK(INDWRK), of the tridiagonal matrix, then call SORMTR to multiply it by the Householder transformations stored in A. */ if (! wantz) { ssterf_(n, &w[1], &work[inde], info); } else { sstedc_("I", n, &w[1], &work[inde], &work[indwrk], n, &work[indwk2], & llwrk2, &iwork[1], liwork, info); sormtr_("L", uplo, "N", n, n, &a[a_offset], lda, &work[indtau], &work[ indwrk], n, &work[indwk2], &llwrk2, &iinfo); slacpy_("A", n, n, &work[indwrk], n, &a[a_offset], lda); /* Computing MAX Computing 2nd power */ i__3 = *n; i__1 = lopt, i__2 = *n * 6 + 1 + ((i__3 * i__3) << (1)); lopt = max(i__1,i__2); } /* If matrix was scaled, then rescale eigenvalues appropriately. */ if (iscale == 1) { r__1 = 1.f / sigma; sscal_(n, &r__1, &w[1], &c__1); } work[1] = (real) lopt; iwork[1] = liopt; return 0; /* End of SSYEVD */ } /* ssyevd_ */ /* Subroutine */ int ssytd2_(char *uplo, integer *n, real *a, integer *lda, real *d__, real *e, real *tau, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3; /* Local variables */ static integer i__; static real taui; extern doublereal sdot_(integer *, real *, integer *, real *, integer *); extern /* Subroutine */ int ssyr2_(char *, integer *, real *, real *, integer *, real *, integer *, real *, integer *); static real alpha; extern logical lsame_(char *, char *); static logical upper; extern /* Subroutine */ int saxpy_(integer *, real *, real *, integer *, real *, integer *), ssymv_(char *, integer *, real *, real *, integer *, real *, integer *, real *, real *, integer *), xerbla_(char *, integer *), slarfg_(integer *, real *, real *, integer *, real *); /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University October 31, 1992 Purpose ======= SSYTD2 reduces a real symmetric matrix A to symmetric tridiagonal form T by an orthogonal similarity transformation: Q' * A * Q = T. Arguments ========= UPLO (input) CHARACTER*1 Specifies whether the upper or lower triangular part of the symmetric matrix A is stored: = 'U': Upper triangular = 'L': Lower triangular N (input) INTEGER The order of the matrix A. N >= 0. A (input/output) REAL 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, and the strictly lower triangular part of A is not referenced. If UPLO = 'L', the leading n-by-n lower triangular part of A contains the lower triangular part of the matrix A, and the strictly upper triangular part of A is not referenced. On exit, if UPLO = 'U', the diagonal and first superdiagonal of A are overwritten by the corresponding elements of the tridiagonal matrix T, and the elements above the first superdiagonal, with the array TAU, represent the orthogonal matrix Q as a product of elementary reflectors; if UPLO = 'L', the diagonal and first subdiagonal of A are over- written by the corresponding elements of the tridiagonal matrix T, and the elements below the first subdiagonal, with the array TAU, represent the orthogonal matrix Q as a product of elementary reflectors. See Further Details. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,N). D (output) REAL array, dimension (N) The diagonal elements of the tridiagonal matrix T: D(i) = A(i,i). E (output) REAL array, dimension (N-1) The off-diagonal elements of the tridiagonal matrix T: E(i) = A(i,i+1) if UPLO = 'U', E(i) = A(i+1,i) if UPLO = 'L'. TAU (output) REAL array, dimension (N-1) The scalar factors of the elementary reflectors (see Further Details). INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value. Further Details =============== If UPLO = 'U', the matrix Q is represented as a product of elementary reflectors Q = H(n-1) . . . H(2) H(1). Each H(i) has the form H(i) = I - tau * v * v' where tau is a real scalar, and v is a real vector with v(i+1:n) = 0 and v(i) = 1; v(1:i-1) is stored on exit in A(1:i-1,i+1), and tau in TAU(i). If UPLO = 'L', the matrix Q is represented as a product of elementary reflectors Q = H(1) H(2) . . . H(n-1). Each H(i) has the form H(i) = I - tau * v * v' where tau is a real scalar, and v is a real vector with v(1:i) = 0 and v(i+1) = 1; v(i+2:n) is stored on exit in A(i+2:n,i), and tau in TAU(i). The contents of A on exit are illustrated by the following examples with n = 5: if UPLO = 'U': if UPLO = 'L': ( d e v2 v3 v4 ) ( d ) ( d e v3 v4 ) ( e d ) ( d e v4 ) ( v1 e d ) ( d e ) ( v1 v2 e d ) ( d ) ( v1 v2 v3 e d ) where d and e denote diagonal and off-diagonal elements of T, and vi denotes an element of the vector defining H(i). ===================================================================== Test the input parameters */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --d__; --e; --tau; /* Function Body */ *info = 0; upper = lsame_(uplo, "U"); if (! upper && ! lsame_(uplo, "L")) { *info = -1; } else if (*n < 0) { *info = -2; } else if (*lda < max(1,*n)) { *info = -4; } if (*info != 0) { i__1 = -(*info); xerbla_("SSYTD2", &i__1); return 0; } /* Quick return if possible */ if (*n <= 0) { return 0; } if (upper) { /* Reduce the upper triangle of A */ for (i__ = *n - 1; i__ >= 1; --i__) { /* Generate elementary reflector H(i) = I - tau * v * v' to annihilate A(1:i-1,i+1) */ slarfg_(&i__, &a[i__ + (i__ + 1) * a_dim1], &a[(i__ + 1) * a_dim1 + 1], &c__1, &taui); e[i__] = a[i__ + (i__ + 1) * a_dim1]; if (taui != 0.f) { /* Apply H(i) from both sides to A(1:i,1:i) */ a[i__ + (i__ + 1) * a_dim1] = 1.f; /* Compute x := tau * A * v storing x in TAU(1:i) */ ssymv_(uplo, &i__, &taui, &a[a_offset], lda, &a[(i__ + 1) * a_dim1 + 1], &c__1, &c_b320, &tau[1], &c__1); /* Compute w := x - 1/2 * tau * (x'*v) * v */ alpha = taui * -.5f * sdot_(&i__, &tau[1], &c__1, &a[(i__ + 1) * a_dim1 + 1], &c__1); saxpy_(&i__, &alpha, &a[(i__ + 1) * a_dim1 + 1], &c__1, &tau[ 1], &c__1); /* Apply the transformation as a rank-2 update: A := A - v * w' - w * v' */ ssyr2_(uplo, &i__, &c_b1290, &a[(i__ + 1) * a_dim1 + 1], & c__1, &tau[1], &c__1, &a[a_offset], lda); a[i__ + (i__ + 1) * a_dim1] = e[i__]; } d__[i__ + 1] = a[i__ + 1 + (i__ + 1) * a_dim1]; tau[i__] = taui; /* L10: */ } d__[1] = a[a_dim1 + 1]; } else { /* Reduce the lower triangle of A */ i__1 = *n - 1; for (i__ = 1; i__ <= i__1; ++i__) { /* Generate elementary reflector H(i) = I - tau * v * v' to annihilate A(i+2:n,i) */ i__2 = *n - i__; /* Computing MIN */ i__3 = i__ + 2; slarfg_(&i__2, &a[i__ + 1 + i__ * a_dim1], &a[min(i__3,*n) + i__ * a_dim1], &c__1, &taui); e[i__] = a[i__ + 1 + i__ * a_dim1]; if (taui != 0.f) { /* Apply H(i) from both sides to A(i+1:n,i+1:n) */ a[i__ + 1 + i__ * a_dim1] = 1.f; /* Compute x := tau * A * v storing y in TAU(i:n-1) */ i__2 = *n - i__; ssymv_(uplo, &i__2, &taui, &a[i__ + 1 + (i__ + 1) * a_dim1], lda, &a[i__ + 1 + i__ * a_dim1], &c__1, &c_b320, &tau[ i__], &c__1); /* Compute w := x - 1/2 * tau * (x'*v) * v */ i__2 = *n - i__; alpha = taui * -.5f * sdot_(&i__2, &tau[i__], &c__1, &a[i__ + 1 + i__ * a_dim1], &c__1); i__2 = *n - i__; saxpy_(&i__2, &alpha, &a[i__ + 1 + i__ * a_dim1], &c__1, &tau[ i__], &c__1); /* Apply the transformation as a rank-2 update: A := A - v * w' - w * v' */ i__2 = *n - i__; ssyr2_(uplo, &i__2, &c_b1290, &a[i__ + 1 + i__ * a_dim1], & c__1, &tau[i__], &c__1, &a[i__ + 1 + (i__ + 1) * a_dim1], lda); a[i__ + 1 + i__ * a_dim1] = e[i__]; } d__[i__] = a[i__ + i__ * a_dim1]; tau[i__] = taui; /* L20: */ } d__[*n] = a[*n + *n * a_dim1]; } return 0; /* End of SSYTD2 */ } /* ssytd2_ */ /* Subroutine */ int ssytrd_(char *uplo, integer *n, real *a, integer *lda, real *d__, real *e, real *tau, real *work, integer *lwork, integer * info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3; /* Local variables */ static integer i__, j, nb, kk, nx, iws; extern logical lsame_(char *, char *); static integer nbmin, iinfo; static logical upper; extern /* Subroutine */ int ssytd2_(char *, integer *, real *, integer *, real *, real *, real *, integer *), ssyr2k_(char *, char * , integer *, integer *, real *, real *, integer *, real *, integer *, real *, real *, integer *), xerbla_( char *, integer *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); extern /* Subroutine */ int slatrd_(char *, integer *, integer *, real *, integer *, real *, real *, real *, integer *); static integer ldwork, lwkopt; static logical lquery; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= SSYTRD reduces a real symmetric matrix A to real symmetric tridiagonal form T by an orthogonal similarity transformation: Q**T * A * Q = T. Arguments ========= UPLO (input) CHARACTER*1 = 'U': Upper triangle of A is stored; = 'L': Lower triangle of A is stored. N (input) INTEGER The order of the matrix A. N >= 0. A (input/output) REAL 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, and the strictly lower triangular part of A is not referenced. If UPLO = 'L', the leading N-by-N lower triangular part of A contains the lower triangular part of the matrix A, and the strictly upper triangular part of A is not referenced. On exit, if UPLO = 'U', the diagonal and first superdiagonal of A are overwritten by the corresponding elements of the tridiagonal matrix T, and the elements above the first superdiagonal, with the array TAU, represent the orthogonal matrix Q as a product of elementary reflectors; if UPLO = 'L', the diagonal and first subdiagonal of A are over- written by the corresponding elements of the tridiagonal matrix T, and the elements below the first subdiagonal, with the array TAU, represent the orthogonal matrix Q as a product of elementary reflectors. See Further Details. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,N). D (output) REAL array, dimension (N) The diagonal elements of the tridiagonal matrix T: D(i) = A(i,i). E (output) REAL array, dimension (N-1) The off-diagonal elements of the tridiagonal matrix T: E(i) = A(i,i+1) if UPLO = 'U', E(i) = A(i+1,i) if UPLO = 'L'. TAU (output) REAL array, dimension (N-1) The scalar factors of the elementary reflectors (see Further Details). WORK (workspace/output) REAL array, dimension (LWORK) On exit, if INFO = 0, WORK(1) returns the optimal LWORK. LWORK (input) INTEGER The dimension of the array WORK. LWORK >= 1. For optimum performance LWORK >= N*NB, where NB is the optimal blocksize. If LWORK = -1, then a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued by XERBLA. INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value Further Details =============== If UPLO = 'U', the matrix Q is represented as a product of elementary reflectors Q = H(n-1) . . . H(2) H(1). Each H(i) has the form H(i) = I - tau * v * v' where tau is a real scalar, and v is a real vector with v(i+1:n) = 0 and v(i) = 1; v(1:i-1) is stored on exit in A(1:i-1,i+1), and tau in TAU(i). If UPLO = 'L', the matrix Q is represented as a product of elementary reflectors Q = H(1) H(2) . . . H(n-1). Each H(i) has the form H(i) = I - tau * v * v' where tau is a real scalar, and v is a real vector with v(1:i) = 0 and v(i+1) = 1; v(i+2:n) is stored on exit in A(i+2:n,i), and tau in TAU(i). The contents of A on exit are illustrated by the following examples with n = 5: if UPLO = 'U': if UPLO = 'L': ( d e v2 v3 v4 ) ( d ) ( d e v3 v4 ) ( e d ) ( d e v4 ) ( v1 e d ) ( d e ) ( v1 v2 e d ) ( d ) ( v1 v2 v3 e d ) where d and e denote diagonal and off-diagonal elements of T, and vi denotes an element of the vector defining H(i). ===================================================================== Test the input parameters */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --d__; --e; --tau; --work; /* Function Body */ *info = 0; upper = lsame_(uplo, "U"); lquery = *lwork == -1; if (! upper && ! lsame_(uplo, "L")) { *info = -1; } else if (*n < 0) { *info = -2; } else if (*lda < max(1,*n)) { *info = -4; } else if (*lwork < 1 && ! lquery) { *info = -9; } if (*info == 0) { /* Determine the block size. */ nb = ilaenv_(&c__1, "SSYTRD", uplo, n, &c_n1, &c_n1, &c_n1, (ftnlen)6, (ftnlen)1); lwkopt = *n * nb; work[1] = (real) lwkopt; } if (*info != 0) { i__1 = -(*info); xerbla_("SSYTRD", &i__1); return 0; } else if (lquery) { return 0; } /* Quick return if possible */ if (*n == 0) { work[1] = 1.f; return 0; } nx = *n; iws = 1; if (nb > 1 && nb < *n) { /* Determine when to cross over from blocked to unblocked code (last block is always handled by unblocked code). Computing MAX */ i__1 = nb, i__2 = ilaenv_(&c__3, "SSYTRD", uplo, n, &c_n1, &c_n1, & c_n1, (ftnlen)6, (ftnlen)1); nx = max(i__1,i__2); if (nx < *n) { /* Determine if workspace is large enough for blocked code. */ ldwork = *n; iws = ldwork * nb; if (*lwork < iws) { /* Not enough workspace to use optimal NB: determine the minimum value of NB, and reduce NB or force use of unblocked code by setting NX = N. Computing MAX */ i__1 = *lwork / ldwork; nb = max(i__1,1); nbmin = ilaenv_(&c__2, "SSYTRD", uplo, n, &c_n1, &c_n1, &c_n1, (ftnlen)6, (ftnlen)1); if (nb < nbmin) { nx = *n; } } } else { nx = *n; } } else { nb = 1; } if (upper) { /* Reduce the upper triangle of A. Columns 1:kk are handled by the unblocked method. */ kk = *n - (*n - nx + nb - 1) / nb * nb; i__1 = kk + 1; i__2 = -nb; for (i__ = *n - nb + 1; i__2 < 0 ? i__ >= i__1 : i__ <= i__1; i__ += i__2) { /* Reduce columns i:i+nb-1 to tridiagonal form and form the matrix W which is needed to update the unreduced part of the matrix */ i__3 = i__ + nb - 1; slatrd_(uplo, &i__3, &nb, &a[a_offset], lda, &e[1], &tau[1], & work[1], &ldwork); /* Update the unreduced submatrix A(1:i-1,1:i-1), using an update of the form: A := A - V*W' - W*V' */ i__3 = i__ - 1; ssyr2k_(uplo, "No transpose", &i__3, &nb, &c_b1290, &a[i__ * a_dim1 + 1], lda, &work[1], &ldwork, &c_b1011, &a[ a_offset], lda); /* Copy superdiagonal elements back into A, and diagonal elements into D */ i__3 = i__ + nb - 1; for (j = i__; j <= i__3; ++j) { a[j - 1 + j * a_dim1] = e[j - 1]; d__[j] = a[j + j * a_dim1]; /* L10: */ } /* L20: */ } /* Use unblocked code to reduce the last or only block */ ssytd2_(uplo, &kk, &a[a_offset], lda, &d__[1], &e[1], &tau[1], &iinfo); } else { /* Reduce the lower triangle of A */ i__2 = *n - nx; i__1 = nb; for (i__ = 1; i__1 < 0 ? i__ >= i__2 : i__ <= i__2; i__ += i__1) { /* Reduce columns i:i+nb-1 to tridiagonal form and form the matrix W which is needed to update the unreduced part of the matrix */ i__3 = *n - i__ + 1; slatrd_(uplo, &i__3, &nb, &a[i__ + i__ * a_dim1], lda, &e[i__], & tau[i__], &work[1], &ldwork); /* Update the unreduced submatrix A(i+ib:n,i+ib:n), using an update of the form: A := A - V*W' - W*V' */ i__3 = *n - i__ - nb + 1; ssyr2k_(uplo, "No transpose", &i__3, &nb, &c_b1290, &a[i__ + nb + i__ * a_dim1], lda, &work[nb + 1], &ldwork, &c_b1011, &a[ i__ + nb + (i__ + nb) * a_dim1], lda); /* Copy subdiagonal elements back into A, and diagonal elements into D */ i__3 = i__ + nb - 1; for (j = i__; j <= i__3; ++j) { a[j + 1 + j * a_dim1] = e[j]; d__[j] = a[j + j * a_dim1]; /* L30: */ } /* L40: */ } /* Use unblocked code to reduce the last or only block */ i__1 = *n - i__ + 1; ssytd2_(uplo, &i__1, &a[i__ + i__ * a_dim1], lda, &d__[i__], &e[i__], &tau[i__], &iinfo); } work[1] = (real) lwkopt; return 0; /* End of SSYTRD */ } /* ssytrd_ */ /* Subroutine */ int strevc_(char *side, char *howmny, logical *select, integer *n, real *t, integer *ldt, real *vl, integer *ldvl, real *vr, integer *ldvr, integer *mm, integer *m, real *work, integer *info) { /* System generated locals */ integer t_dim1, t_offset, vl_dim1, vl_offset, vr_dim1, vr_offset, i__1, i__2, i__3; real r__1, r__2, r__3, r__4; /* Builtin functions */ double sqrt(doublereal); /* Local variables */ static integer i__, j, k; static real x[4] /* was [2][2] */; static integer j1, j2, n2, ii, ki, ip, is; static real wi, wr, rec, ulp, beta, emax; static logical pair, allv; static integer ierr; static real unfl, ovfl, smin; extern doublereal sdot_(integer *, real *, integer *, real *, integer *); static logical over; static real vmax; static integer jnxt; static real scale; extern logical lsame_(char *, char *); extern /* Subroutine */ int sscal_(integer *, real *, real *, integer *); static real remax; static logical leftv; extern /* Subroutine */ int sgemv_(char *, integer *, integer *, real *, real *, integer *, real *, integer *, real *, real *, integer *); static logical bothv; static real vcrit; static logical somev; extern /* Subroutine */ int scopy_(integer *, real *, integer *, real *, integer *); static real xnorm; extern /* Subroutine */ int saxpy_(integer *, real *, real *, integer *, real *, integer *), slaln2_(logical *, integer *, integer *, real *, real *, real *, integer *, real *, real *, real *, integer *, real *, real *, real *, integer *, real *, real *, integer *), slabad_(real *, real *); extern doublereal slamch_(char *); extern /* Subroutine */ int xerbla_(char *, integer *); static real bignum; extern integer isamax_(integer *, real *, integer *); static logical rightv; static real smlnum; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1999 Purpose ======= STREVC computes some or all of the right and/or left eigenvectors of a real upper quasi-triangular matrix T. The right eigenvector x and the left eigenvector y of T corresponding to an eigenvalue w are defined by: T*x = w*x, y'*T = w*y' where y' denotes the conjugate transpose of the vector y. If all eigenvectors are requested, the routine may either return the matrices X and/or Y of right or left eigenvectors of T, or the products Q*X and/or Q*Y, where Q is an input orthogonal matrix. If T was obtained from the real-Schur factorization of an original matrix A = Q*T*Q', then Q*X and Q*Y are the matrices of right or left eigenvectors of A. T must be in Schur canonical form (as returned by SHSEQR), that is, block upper triangular with 1-by-1 and 2-by-2 diagonal blocks; each 2-by-2 diagonal block has its diagonal elements equal and its off-diagonal elements of opposite sign. Corresponding to each 2-by-2 diagonal block is a complex conjugate pair of eigenvalues and eigenvectors; only one eigenvector of the pair is computed, namely the one corresponding to the eigenvalue with positive imaginary part. Arguments ========= SIDE (input) CHARACTER*1 = 'R': compute right eigenvectors only; = 'L': compute left eigenvectors only; = 'B': compute both right and left eigenvectors. HOWMNY (input) CHARACTER*1 = 'A': compute all right and/or left eigenvectors; = 'B': compute all right and/or left eigenvectors, and backtransform them using the input matrices supplied in VR and/or VL; = 'S': compute selected right and/or left eigenvectors, specified by the logical array SELECT. SELECT (input/output) LOGICAL array, dimension (N) If HOWMNY = 'S', SELECT specifies the eigenvectors to be computed. If HOWMNY = 'A' or 'B', SELECT is not referenced. To select the real eigenvector corresponding to a real eigenvalue w(j), SELECT(j) must be set to .TRUE.. To select the complex eigenvector corresponding to a complex conjugate pair w(j) and w(j+1), either SELECT(j) or SELECT(j+1) must be set to .TRUE.; then on exit SELECT(j) is .TRUE. and SELECT(j+1) is .FALSE.. N (input) INTEGER The order of the matrix T. N >= 0. T (input) REAL array, dimension (LDT,N) The upper quasi-triangular matrix T in Schur canonical form. LDT (input) INTEGER The leading dimension of the array T. LDT >= max(1,N). VL (input/output) REAL array, dimension (LDVL,MM) On entry, if SIDE = 'L' or 'B' and HOWMNY = 'B', VL must contain an N-by-N matrix Q (usually the orthogonal matrix Q of Schur vectors returned by SHSEQR). On exit, if SIDE = 'L' or 'B', VL contains: if HOWMNY = 'A', the matrix Y of left eigenvectors of T; VL has the same quasi-lower triangular form as T'. If T(i,i) is a real eigenvalue, then the i-th column VL(i) of VL is its corresponding eigenvector. If T(i:i+1,i:i+1) is a 2-by-2 block whose eigenvalues are complex-conjugate eigenvalues of T, then VL(i)+sqrt(-1)*VL(i+1) is the complex eigenvector corresponding to the eigenvalue with positive real part. if HOWMNY = 'B', the matrix Q*Y; if HOWMNY = 'S', the left eigenvectors of T specified by SELECT, stored consecutively in the columns of VL, in the same order as their eigenvalues. A complex eigenvector corresponding to a complex eigenvalue is stored in two consecutive columns, the first holding the real part, and the second the imaginary part. If SIDE = 'R', VL is not referenced. LDVL (input) INTEGER The leading dimension of the array VL. LDVL >= max(1,N) if SIDE = 'L' or 'B'; LDVL >= 1 otherwise. VR (input/output) REAL array, dimension (LDVR,MM) On entry, if SIDE = 'R' or 'B' and HOWMNY = 'B', VR must contain an N-by-N matrix Q (usually the orthogonal matrix Q of Schur vectors returned by SHSEQR). On exit, if SIDE = 'R' or 'B', VR contains: if HOWMNY = 'A', the matrix X of right eigenvectors of T; VR has the same quasi-upper triangular form as T. If T(i,i) is a real eigenvalue, then the i-th column VR(i) of VR is its corresponding eigenvector. If T(i:i+1,i:i+1) is a 2-by-2 block whose eigenvalues are complex-conjugate eigenvalues of T, then VR(i)+sqrt(-1)*VR(i+1) is the complex eigenvector corresponding to the eigenvalue with positive real part. if HOWMNY = 'B', the matrix Q*X; if HOWMNY = 'S', the right eigenvectors of T specified by SELECT, stored consecutively in the columns of VR, in the same order as their eigenvalues. A complex eigenvector corresponding to a complex eigenvalue is stored in two consecutive columns, the first holding the real part and the second the imaginary part. If SIDE = 'L', VR is not referenced. LDVR (input) INTEGER The leading dimension of the array VR. LDVR >= max(1,N) if SIDE = 'R' or 'B'; LDVR >= 1 otherwise. MM (input) INTEGER The number of columns in the arrays VL and/or VR. MM >= M. M (output) INTEGER The number of columns in the arrays VL and/or VR actually used to store the eigenvectors. If HOWMNY = 'A' or 'B', M is set to N. Each selected real eigenvector occupies one column and each selected complex eigenvector occupies two columns. WORK (workspace) REAL array, dimension (3*N) INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value Further Details =============== The algorithm used in this program is basically backward (forward) substitution, with scaling to make the the code robust against possible overflow. Each eigenvector is normalized so that the element of largest magnitude has magnitude 1; here the magnitude of a complex number (x,y) is taken to be |x| + |y|. ===================================================================== Decode and test the input parameters */ /* Parameter adjustments */ --select; t_dim1 = *ldt; t_offset = 1 + t_dim1; t -= t_offset; vl_dim1 = *ldvl; vl_offset = 1 + vl_dim1; vl -= vl_offset; vr_dim1 = *ldvr; vr_offset = 1 + vr_dim1; vr -= vr_offset; --work; /* Function Body */ bothv = lsame_(side, "B"); rightv = (lsame_(side, "R")) || (bothv); leftv = (lsame_(side, "L")) || (bothv); allv = lsame_(howmny, "A"); over = lsame_(howmny, "B"); somev = lsame_(howmny, "S"); *info = 0; if (! rightv && ! leftv) { *info = -1; } else if (! allv && ! over && ! somev) { *info = -2; } else if (*n < 0) { *info = -4; } else if (*ldt < max(1,*n)) { *info = -6; } else if ((*ldvl < 1) || (leftv && *ldvl < *n)) { *info = -8; } else if ((*ldvr < 1) || (rightv && *ldvr < *n)) { *info = -10; } else { /* Set M to the number of columns required to store the selected eigenvectors, standardize the array SELECT if necessary, and test MM. */ if (somev) { *m = 0; pair = FALSE_; i__1 = *n; for (j = 1; j <= i__1; ++j) { if (pair) { pair = FALSE_; select[j] = FALSE_; } else { if (j < *n) { if (t[j + 1 + j * t_dim1] == 0.f) { if (select[j]) { ++(*m); } } else { pair = TRUE_; if ((select[j]) || (select[j + 1])) { select[j] = TRUE_; *m += 2; } } } else { if (select[*n]) { ++(*m); } } } /* L10: */ } } else { *m = *n; } if (*mm < *m) { *info = -11; } } if (*info != 0) { i__1 = -(*info); xerbla_("STREVC", &i__1); return 0; } /* Quick return if possible. */ if (*n == 0) { return 0; } /* Set the constants to control overflow. */ unfl = slamch_("Safe minimum"); ovfl = 1.f / unfl; slabad_(&unfl, &ovfl); ulp = slamch_("Precision"); smlnum = unfl * (*n / ulp); bignum = (1.f - ulp) / smlnum; /* Compute 1-norm of each column of strictly upper triangular part of T to control overflow in triangular solver. */ work[1] = 0.f; i__1 = *n; for (j = 2; j <= i__1; ++j) { work[j] = 0.f; i__2 = j - 1; for (i__ = 1; i__ <= i__2; ++i__) { work[j] += (r__1 = t[i__ + j * t_dim1], dabs(r__1)); /* L20: */ } /* L30: */ } /* Index IP is used to specify the real or complex eigenvalue: IP = 0, real eigenvalue, 1, first of conjugate complex pair: (wr,wi) -1, second of conjugate complex pair: (wr,wi) */ n2 = (*n) << (1); if (rightv) { /* Compute right eigenvectors. */ ip = 0; is = *m; for (ki = *n; ki >= 1; --ki) { if (ip == 1) { goto L130; } if (ki == 1) { goto L40; } if (t[ki + (ki - 1) * t_dim1] == 0.f) { goto L40; } ip = -1; L40: if (somev) { if (ip == 0) { if (! select[ki]) { goto L130; } } else { if (! select[ki - 1]) { goto L130; } } } /* Compute the KI-th eigenvalue (WR,WI). */ wr = t[ki + ki * t_dim1]; wi = 0.f; if (ip != 0) { wi = sqrt((r__1 = t[ki + (ki - 1) * t_dim1], dabs(r__1))) * sqrt((r__2 = t[ki - 1 + ki * t_dim1], dabs(r__2))); } /* Computing MAX */ r__1 = ulp * (dabs(wr) + dabs(wi)); smin = dmax(r__1,smlnum); if (ip == 0) { /* Real right eigenvector */ work[ki + *n] = 1.f; /* Form right-hand side */ i__1 = ki - 1; for (k = 1; k <= i__1; ++k) { work[k + *n] = -t[k + ki * t_dim1]; /* L50: */ } /* Solve the upper quasi-triangular system: (T(1:KI-1,1:KI-1) - WR)*X = SCALE*WORK. */ jnxt = ki - 1; for (j = ki - 1; j >= 1; --j) { if (j > jnxt) { goto L60; } j1 = j; j2 = j; jnxt = j - 1; if (j > 1) { if (t[j + (j - 1) * t_dim1] != 0.f) { j1 = j - 1; jnxt = j - 2; } } if (j1 == j2) { /* 1-by-1 diagonal block */ slaln2_(&c_false, &c__1, &c__1, &smin, &c_b1011, &t[j + j * t_dim1], ldt, &c_b1011, &c_b1011, &work[ j + *n], n, &wr, &c_b320, x, &c__2, &scale, & xnorm, &ierr); /* Scale X(1,1) to avoid overflow when updating the right-hand side. */ if (xnorm > 1.f) { if (work[j] > bignum / xnorm) { x[0] /= xnorm; scale /= xnorm; } } /* Scale if necessary */ if (scale != 1.f) { sscal_(&ki, &scale, &work[*n + 1], &c__1); } work[j + *n] = x[0]; /* Update right-hand side */ i__1 = j - 1; r__1 = -x[0]; saxpy_(&i__1, &r__1, &t[j * t_dim1 + 1], &c__1, &work[ *n + 1], &c__1); } else { /* 2-by-2 diagonal block */ slaln2_(&c_false, &c__2, &c__1, &smin, &c_b1011, &t[j - 1 + (j - 1) * t_dim1], ldt, &c_b1011, & c_b1011, &work[j - 1 + *n], n, &wr, &c_b320, x, &c__2, &scale, &xnorm, &ierr); /* Scale X(1,1) and X(2,1) to avoid overflow when updating the right-hand side. */ if (xnorm > 1.f) { /* Computing MAX */ r__1 = work[j - 1], r__2 = work[j]; beta = dmax(r__1,r__2); if (beta > bignum / xnorm) { x[0] /= xnorm; x[1] /= xnorm; scale /= xnorm; } } /* Scale if necessary */ if (scale != 1.f) { sscal_(&ki, &scale, &work[*n + 1], &c__1); } work[j - 1 + *n] = x[0]; work[j + *n] = x[1]; /* Update right-hand side */ i__1 = j - 2; r__1 = -x[0]; saxpy_(&i__1, &r__1, &t[(j - 1) * t_dim1 + 1], &c__1, &work[*n + 1], &c__1); i__1 = j - 2; r__1 = -x[1]; saxpy_(&i__1, &r__1, &t[j * t_dim1 + 1], &c__1, &work[ *n + 1], &c__1); } L60: ; } /* Copy the vector x or Q*x to VR and normalize. */ if (! over) { scopy_(&ki, &work[*n + 1], &c__1, &vr[is * vr_dim1 + 1], & c__1); ii = isamax_(&ki, &vr[is * vr_dim1 + 1], &c__1); remax = 1.f / (r__1 = vr[ii + is * vr_dim1], dabs(r__1)); sscal_(&ki, &remax, &vr[is * vr_dim1 + 1], &c__1); i__1 = *n; for (k = ki + 1; k <= i__1; ++k) { vr[k + is * vr_dim1] = 0.f; /* L70: */ } } else { if (ki > 1) { i__1 = ki - 1; sgemv_("N", n, &i__1, &c_b1011, &vr[vr_offset], ldvr, &work[*n + 1], &c__1, &work[ki + *n], &vr[ki * vr_dim1 + 1], &c__1); } ii = isamax_(n, &vr[ki * vr_dim1 + 1], &c__1); remax = 1.f / (r__1 = vr[ii + ki * vr_dim1], dabs(r__1)); sscal_(n, &remax, &vr[ki * vr_dim1 + 1], &c__1); } } else { /* Complex right eigenvector. Initial solve [ (T(KI-1,KI-1) T(KI-1,KI) ) - (WR + I* WI)]*X = 0. [ (T(KI,KI-1) T(KI,KI) ) ] */ if ((r__1 = t[ki - 1 + ki * t_dim1], dabs(r__1)) >= (r__2 = t[ ki + (ki - 1) * t_dim1], dabs(r__2))) { work[ki - 1 + *n] = 1.f; work[ki + n2] = wi / t[ki - 1 + ki * t_dim1]; } else { work[ki - 1 + *n] = -wi / t[ki + (ki - 1) * t_dim1]; work[ki + n2] = 1.f; } work[ki + *n] = 0.f; work[ki - 1 + n2] = 0.f; /* Form right-hand side */ i__1 = ki - 2; for (k = 1; k <= i__1; ++k) { work[k + *n] = -work[ki - 1 + *n] * t[k + (ki - 1) * t_dim1]; work[k + n2] = -work[ki + n2] * t[k + ki * t_dim1]; /* L80: */ } /* Solve upper quasi-triangular system: (T(1:KI-2,1:KI-2) - (WR+i*WI))*X = SCALE*(WORK+i*WORK2) */ jnxt = ki - 2; for (j = ki - 2; j >= 1; --j) { if (j > jnxt) { goto L90; } j1 = j; j2 = j; jnxt = j - 1; if (j > 1) { if (t[j + (j - 1) * t_dim1] != 0.f) { j1 = j - 1; jnxt = j - 2; } } if (j1 == j2) { /* 1-by-1 diagonal block */ slaln2_(&c_false, &c__1, &c__2, &smin, &c_b1011, &t[j + j * t_dim1], ldt, &c_b1011, &c_b1011, &work[ j + *n], n, &wr, &wi, x, &c__2, &scale, & xnorm, &ierr); /* Scale X(1,1) and X(1,2) to avoid overflow when updating the right-hand side. */ if (xnorm > 1.f) { if (work[j] > bignum / xnorm) { x[0] /= xnorm; x[2] /= xnorm; scale /= xnorm; } } /* Scale if necessary */ if (scale != 1.f) { sscal_(&ki, &scale, &work[*n + 1], &c__1); sscal_(&ki, &scale, &work[n2 + 1], &c__1); } work[j + *n] = x[0]; work[j + n2] = x[2]; /* Update the right-hand side */ i__1 = j - 1; r__1 = -x[0]; saxpy_(&i__1, &r__1, &t[j * t_dim1 + 1], &c__1, &work[ *n + 1], &c__1); i__1 = j - 1; r__1 = -x[2]; saxpy_(&i__1, &r__1, &t[j * t_dim1 + 1], &c__1, &work[ n2 + 1], &c__1); } else { /* 2-by-2 diagonal block */ slaln2_(&c_false, &c__2, &c__2, &smin, &c_b1011, &t[j - 1 + (j - 1) * t_dim1], ldt, &c_b1011, & c_b1011, &work[j - 1 + *n], n, &wr, &wi, x, & c__2, &scale, &xnorm, &ierr); /* Scale X to avoid overflow when updating the right-hand side. */ if (xnorm > 1.f) { /* Computing MAX */ r__1 = work[j - 1], r__2 = work[j]; beta = dmax(r__1,r__2); if (beta > bignum / xnorm) { rec = 1.f / xnorm; x[0] *= rec; x[2] *= rec; x[1] *= rec; x[3] *= rec; scale *= rec; } } /* Scale if necessary */ if (scale != 1.f) { sscal_(&ki, &scale, &work[*n + 1], &c__1); sscal_(&ki, &scale, &work[n2 + 1], &c__1); } work[j - 1 + *n] = x[0]; work[j + *n] = x[1]; work[j - 1 + n2] = x[2]; work[j + n2] = x[3]; /* Update the right-hand side */ i__1 = j - 2; r__1 = -x[0]; saxpy_(&i__1, &r__1, &t[(j - 1) * t_dim1 + 1], &c__1, &work[*n + 1], &c__1); i__1 = j - 2; r__1 = -x[1]; saxpy_(&i__1, &r__1, &t[j * t_dim1 + 1], &c__1, &work[ *n + 1], &c__1); i__1 = j - 2; r__1 = -x[2]; saxpy_(&i__1, &r__1, &t[(j - 1) * t_dim1 + 1], &c__1, &work[n2 + 1], &c__1); i__1 = j - 2; r__1 = -x[3]; saxpy_(&i__1, &r__1, &t[j * t_dim1 + 1], &c__1, &work[ n2 + 1], &c__1); } L90: ; } /* Copy the vector x or Q*x to VR and normalize. */ if (! over) { scopy_(&ki, &work[*n + 1], &c__1, &vr[(is - 1) * vr_dim1 + 1], &c__1); scopy_(&ki, &work[n2 + 1], &c__1, &vr[is * vr_dim1 + 1], & c__1); emax = 0.f; i__1 = ki; for (k = 1; k <= i__1; ++k) { /* Computing MAX */ r__3 = emax, r__4 = (r__1 = vr[k + (is - 1) * vr_dim1] , dabs(r__1)) + (r__2 = vr[k + is * vr_dim1], dabs(r__2)); emax = dmax(r__3,r__4); /* L100: */ } remax = 1.f / emax; sscal_(&ki, &remax, &vr[(is - 1) * vr_dim1 + 1], &c__1); sscal_(&ki, &remax, &vr[is * vr_dim1 + 1], &c__1); i__1 = *n; for (k = ki + 1; k <= i__1; ++k) { vr[k + (is - 1) * vr_dim1] = 0.f; vr[k + is * vr_dim1] = 0.f; /* L110: */ } } else { if (ki > 2) { i__1 = ki - 2; sgemv_("N", n, &i__1, &c_b1011, &vr[vr_offset], ldvr, &work[*n + 1], &c__1, &work[ki - 1 + *n], &vr[ (ki - 1) * vr_dim1 + 1], &c__1); i__1 = ki - 2; sgemv_("N", n, &i__1, &c_b1011, &vr[vr_offset], ldvr, &work[n2 + 1], &c__1, &work[ki + n2], &vr[ki * vr_dim1 + 1], &c__1); } else { sscal_(n, &work[ki - 1 + *n], &vr[(ki - 1) * vr_dim1 + 1], &c__1); sscal_(n, &work[ki + n2], &vr[ki * vr_dim1 + 1], & c__1); } emax = 0.f; i__1 = *n; for (k = 1; k <= i__1; ++k) { /* Computing MAX */ r__3 = emax, r__4 = (r__1 = vr[k + (ki - 1) * vr_dim1] , dabs(r__1)) + (r__2 = vr[k + ki * vr_dim1], dabs(r__2)); emax = dmax(r__3,r__4); /* L120: */ } remax = 1.f / emax; sscal_(n, &remax, &vr[(ki - 1) * vr_dim1 + 1], &c__1); sscal_(n, &remax, &vr[ki * vr_dim1 + 1], &c__1); } } --is; if (ip != 0) { --is; } L130: if (ip == 1) { ip = 0; } if (ip == -1) { ip = 1; } /* L140: */ } } if (leftv) { /* Compute left eigenvectors. */ ip = 0; is = 1; i__1 = *n; for (ki = 1; ki <= i__1; ++ki) { if (ip == -1) { goto L250; } if (ki == *n) { goto L150; } if (t[ki + 1 + ki * t_dim1] == 0.f) { goto L150; } ip = 1; L150: if (somev) { if (! select[ki]) { goto L250; } } /* Compute the KI-th eigenvalue (WR,WI). */ wr = t[ki + ki * t_dim1]; wi = 0.f; if (ip != 0) { wi = sqrt((r__1 = t[ki + (ki + 1) * t_dim1], dabs(r__1))) * sqrt((r__2 = t[ki + 1 + ki * t_dim1], dabs(r__2))); } /* Computing MAX */ r__1 = ulp * (dabs(wr) + dabs(wi)); smin = dmax(r__1,smlnum); if (ip == 0) { /* Real left eigenvector. */ work[ki + *n] = 1.f; /* Form right-hand side */ i__2 = *n; for (k = ki + 1; k <= i__2; ++k) { work[k + *n] = -t[ki + k * t_dim1]; /* L160: */ } /* Solve the quasi-triangular system: (T(KI+1:N,KI+1:N) - WR)'*X = SCALE*WORK */ vmax = 1.f; vcrit = bignum; jnxt = ki + 1; i__2 = *n; for (j = ki + 1; j <= i__2; ++j) { if (j < jnxt) { goto L170; } j1 = j; j2 = j; jnxt = j + 1; if (j < *n) { if (t[j + 1 + j * t_dim1] != 0.f) { j2 = j + 1; jnxt = j + 2; } } if (j1 == j2) { /* 1-by-1 diagonal block Scale if necessary to avoid overflow when forming the right-hand side. */ if (work[j] > vcrit) { rec = 1.f / vmax; i__3 = *n - ki + 1; sscal_(&i__3, &rec, &work[ki + *n], &c__1); vmax = 1.f; vcrit = bignum; } i__3 = j - ki - 1; work[j + *n] -= sdot_(&i__3, &t[ki + 1 + j * t_dim1], &c__1, &work[ki + 1 + *n], &c__1); /* Solve (T(J,J)-WR)'*X = WORK */ slaln2_(&c_false, &c__1, &c__1, &smin, &c_b1011, &t[j + j * t_dim1], ldt, &c_b1011, &c_b1011, &work[ j + *n], n, &wr, &c_b320, x, &c__2, &scale, & xnorm, &ierr); /* Scale if necessary */ if (scale != 1.f) { i__3 = *n - ki + 1; sscal_(&i__3, &scale, &work[ki + *n], &c__1); } work[j + *n] = x[0]; /* Computing MAX */ r__2 = (r__1 = work[j + *n], dabs(r__1)); vmax = dmax(r__2,vmax); vcrit = bignum / vmax; } else { /* 2-by-2 diagonal block Scale if necessary to avoid overflow when forming the right-hand side. Computing MAX */ r__1 = work[j], r__2 = work[j + 1]; beta = dmax(r__1,r__2); if (beta > vcrit) { rec = 1.f / vmax; i__3 = *n - ki + 1; sscal_(&i__3, &rec, &work[ki + *n], &c__1); vmax = 1.f; vcrit = bignum; } i__3 = j - ki - 1; work[j + *n] -= sdot_(&i__3, &t[ki + 1 + j * t_dim1], &c__1, &work[ki + 1 + *n], &c__1); i__3 = j - ki - 1; work[j + 1 + *n] -= sdot_(&i__3, &t[ki + 1 + (j + 1) * t_dim1], &c__1, &work[ki + 1 + *n], &c__1); /* Solve [T(J,J)-WR T(J,J+1) ]'* X = SCALE*( WORK1 ) [T(J+1,J) T(J+1,J+1)-WR] ( WORK2 ) */ slaln2_(&c_true, &c__2, &c__1, &smin, &c_b1011, &t[j + j * t_dim1], ldt, &c_b1011, &c_b1011, &work[ j + *n], n, &wr, &c_b320, x, &c__2, &scale, & xnorm, &ierr); /* Scale if necessary */ if (scale != 1.f) { i__3 = *n - ki + 1; sscal_(&i__3, &scale, &work[ki + *n], &c__1); } work[j + *n] = x[0]; work[j + 1 + *n] = x[1]; /* Computing MAX */ r__3 = (r__1 = work[j + *n], dabs(r__1)), r__4 = ( r__2 = work[j + 1 + *n], dabs(r__2)), r__3 = max(r__3,r__4); vmax = dmax(r__3,vmax); vcrit = bignum / vmax; } L170: ; } /* Copy the vector x or Q*x to VL and normalize. */ if (! over) { i__2 = *n - ki + 1; scopy_(&i__2, &work[ki + *n], &c__1, &vl[ki + is * vl_dim1], &c__1); i__2 = *n - ki + 1; ii = isamax_(&i__2, &vl[ki + is * vl_dim1], &c__1) + ki - 1; remax = 1.f / (r__1 = vl[ii + is * vl_dim1], dabs(r__1)); i__2 = *n - ki + 1; sscal_(&i__2, &remax, &vl[ki + is * vl_dim1], &c__1); i__2 = ki - 1; for (k = 1; k <= i__2; ++k) { vl[k + is * vl_dim1] = 0.f; /* L180: */ } } else { if (ki < *n) { i__2 = *n - ki; sgemv_("N", n, &i__2, &c_b1011, &vl[(ki + 1) * vl_dim1 + 1], ldvl, &work[ki + 1 + *n], &c__1, &work[ki + *n], &vl[ki * vl_dim1 + 1], &c__1); } ii = isamax_(n, &vl[ki * vl_dim1 + 1], &c__1); remax = 1.f / (r__1 = vl[ii + ki * vl_dim1], dabs(r__1)); sscal_(n, &remax, &vl[ki * vl_dim1 + 1], &c__1); } } else { /* Complex left eigenvector. Initial solve: ((T(KI,KI) T(KI,KI+1) )' - (WR - I* WI))*X = 0. ((T(KI+1,KI) T(KI+1,KI+1)) ) */ if ((r__1 = t[ki + (ki + 1) * t_dim1], dabs(r__1)) >= (r__2 = t[ki + 1 + ki * t_dim1], dabs(r__2))) { work[ki + *n] = wi / t[ki + (ki + 1) * t_dim1]; work[ki + 1 + n2] = 1.f; } else { work[ki + *n] = 1.f; work[ki + 1 + n2] = -wi / t[ki + 1 + ki * t_dim1]; } work[ki + 1 + *n] = 0.f; work[ki + n2] = 0.f; /* Form right-hand side */ i__2 = *n; for (k = ki + 2; k <= i__2; ++k) { work[k + *n] = -work[ki + *n] * t[ki + k * t_dim1]; work[k + n2] = -work[ki + 1 + n2] * t[ki + 1 + k * t_dim1] ; /* L190: */ } /* Solve complex quasi-triangular system: ( T(KI+2,N:KI+2,N) - (WR-i*WI) )*X = WORK1+i*WORK2 */ vmax = 1.f; vcrit = bignum; jnxt = ki + 2; i__2 = *n; for (j = ki + 2; j <= i__2; ++j) { if (j < jnxt) { goto L200; } j1 = j; j2 = j; jnxt = j + 1; if (j < *n) { if (t[j + 1 + j * t_dim1] != 0.f) { j2 = j + 1; jnxt = j + 2; } } if (j1 == j2) { /* 1-by-1 diagonal block Scale if necessary to avoid overflow when forming the right-hand side elements. */ if (work[j] > vcrit) { rec = 1.f / vmax; i__3 = *n - ki + 1; sscal_(&i__3, &rec, &work[ki + *n], &c__1); i__3 = *n - ki + 1; sscal_(&i__3, &rec, &work[ki + n2], &c__1); vmax = 1.f; vcrit = bignum; } i__3 = j - ki - 2; work[j + *n] -= sdot_(&i__3, &t[ki + 2 + j * t_dim1], &c__1, &work[ki + 2 + *n], &c__1); i__3 = j - ki - 2; work[j + n2] -= sdot_(&i__3, &t[ki + 2 + j * t_dim1], &c__1, &work[ki + 2 + n2], &c__1); /* Solve (T(J,J)-(WR-i*WI))*(X11+i*X12)= WK+I*WK2 */ r__1 = -wi; slaln2_(&c_false, &c__1, &c__2, &smin, &c_b1011, &t[j + j * t_dim1], ldt, &c_b1011, &c_b1011, &work[ j + *n], n, &wr, &r__1, x, &c__2, &scale, & xnorm, &ierr); /* Scale if necessary */ if (scale != 1.f) { i__3 = *n - ki + 1; sscal_(&i__3, &scale, &work[ki + *n], &c__1); i__3 = *n - ki + 1; sscal_(&i__3, &scale, &work[ki + n2], &c__1); } work[j + *n] = x[0]; work[j + n2] = x[2]; /* Computing MAX */ r__3 = (r__1 = work[j + *n], dabs(r__1)), r__4 = ( r__2 = work[j + n2], dabs(r__2)), r__3 = max( r__3,r__4); vmax = dmax(r__3,vmax); vcrit = bignum / vmax; } else { /* 2-by-2 diagonal block Scale if necessary to avoid overflow when forming the right-hand side elements. Computing MAX */ r__1 = work[j], r__2 = work[j + 1]; beta = dmax(r__1,r__2); if (beta > vcrit) { rec = 1.f / vmax; i__3 = *n - ki + 1; sscal_(&i__3, &rec, &work[ki + *n], &c__1); i__3 = *n - ki + 1; sscal_(&i__3, &rec, &work[ki + n2], &c__1); vmax = 1.f; vcrit = bignum; } i__3 = j - ki - 2; work[j + *n] -= sdot_(&i__3, &t[ki + 2 + j * t_dim1], &c__1, &work[ki + 2 + *n], &c__1); i__3 = j - ki - 2; work[j + n2] -= sdot_(&i__3, &t[ki + 2 + j * t_dim1], &c__1, &work[ki + 2 + n2], &c__1); i__3 = j - ki - 2; work[j + 1 + *n] -= sdot_(&i__3, &t[ki + 2 + (j + 1) * t_dim1], &c__1, &work[ki + 2 + *n], &c__1); i__3 = j - ki - 2; work[j + 1 + n2] -= sdot_(&i__3, &t[ki + 2 + (j + 1) * t_dim1], &c__1, &work[ki + 2 + n2], &c__1); /* Solve 2-by-2 complex linear equation ([T(j,j) T(j,j+1) ]'-(wr-i*wi)*I)*X = SCALE*B ([T(j+1,j) T(j+1,j+1)] ) */ r__1 = -wi; slaln2_(&c_true, &c__2, &c__2, &smin, &c_b1011, &t[j + j * t_dim1], ldt, &c_b1011, &c_b1011, &work[ j + *n], n, &wr, &r__1, x, &c__2, &scale, & xnorm, &ierr); /* Scale if necessary */ if (scale != 1.f) { i__3 = *n - ki + 1; sscal_(&i__3, &scale, &work[ki + *n], &c__1); i__3 = *n - ki + 1; sscal_(&i__3, &scale, &work[ki + n2], &c__1); } work[j + *n] = x[0]; work[j + n2] = x[2]; work[j + 1 + *n] = x[1]; work[j + 1 + n2] = x[3]; /* Computing MAX */ r__1 = dabs(x[0]), r__2 = dabs(x[2]), r__1 = max(r__1, r__2), r__2 = dabs(x[1]), r__1 = max(r__1, r__2), r__2 = dabs(x[3]), r__1 = max(r__1, r__2); vmax = dmax(r__1,vmax); vcrit = bignum / vmax; } L200: ; } /* Copy the vector x or Q*x to VL and normalize. L210: */ if (! over) { i__2 = *n - ki + 1; scopy_(&i__2, &work[ki + *n], &c__1, &vl[ki + is * vl_dim1], &c__1); i__2 = *n - ki + 1; scopy_(&i__2, &work[ki + n2], &c__1, &vl[ki + (is + 1) * vl_dim1], &c__1); emax = 0.f; i__2 = *n; for (k = ki; k <= i__2; ++k) { /* Computing MAX */ r__3 = emax, r__4 = (r__1 = vl[k + is * vl_dim1], dabs(r__1)) + (r__2 = vl[k + (is + 1) * vl_dim1], dabs(r__2)); emax = dmax(r__3,r__4); /* L220: */ } remax = 1.f / emax; i__2 = *n - ki + 1; sscal_(&i__2, &remax, &vl[ki + is * vl_dim1], &c__1); i__2 = *n - ki + 1; sscal_(&i__2, &remax, &vl[ki + (is + 1) * vl_dim1], &c__1) ; i__2 = ki - 1; for (k = 1; k <= i__2; ++k) { vl[k + is * vl_dim1] = 0.f; vl[k + (is + 1) * vl_dim1] = 0.f; /* L230: */ } } else { if (ki < *n - 1) { i__2 = *n - ki - 1; sgemv_("N", n, &i__2, &c_b1011, &vl[(ki + 2) * vl_dim1 + 1], ldvl, &work[ki + 2 + *n], &c__1, &work[ki + *n], &vl[ki * vl_dim1 + 1], &c__1); i__2 = *n - ki - 1; sgemv_("N", n, &i__2, &c_b1011, &vl[(ki + 2) * vl_dim1 + 1], ldvl, &work[ki + 2 + n2], &c__1, &work[ki + 1 + n2], &vl[(ki + 1) * vl_dim1 + 1], &c__1); } else { sscal_(n, &work[ki + *n], &vl[ki * vl_dim1 + 1], & c__1); sscal_(n, &work[ki + 1 + n2], &vl[(ki + 1) * vl_dim1 + 1], &c__1); } emax = 0.f; i__2 = *n; for (k = 1; k <= i__2; ++k) { /* Computing MAX */ r__3 = emax, r__4 = (r__1 = vl[k + ki * vl_dim1], dabs(r__1)) + (r__2 = vl[k + (ki + 1) * vl_dim1], dabs(r__2)); emax = dmax(r__3,r__4); /* L240: */ } remax = 1.f / emax; sscal_(n, &remax, &vl[ki * vl_dim1 + 1], &c__1); sscal_(n, &remax, &vl[(ki + 1) * vl_dim1 + 1], &c__1); } } ++is; if (ip != 0) { ++is; } L250: if (ip == -1) { ip = 0; } if (ip == 1) { ip = -1; } /* L260: */ } } return 0; /* End of STREVC */ } /* strevc_ */ /* Subroutine */ int strti2_(char *uplo, char *diag, integer *n, real *a, integer *lda, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2; /* Local variables */ static integer j; static real ajj; extern logical lsame_(char *, char *); extern /* Subroutine */ int sscal_(integer *, real *, real *, integer *); static logical upper; extern /* Subroutine */ int strmv_(char *, char *, char *, integer *, real *, integer *, real *, integer *), xerbla_(char *, integer *); static logical nounit; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University February 29, 1992 Purpose ======= STRTI2 computes the inverse of a real upper or lower triangular matrix. This is the Level 2 BLAS version of the algorithm. Arguments ========= UPLO (input) CHARACTER*1 Specifies whether the matrix A is upper or lower triangular. = 'U': Upper triangular = 'L': Lower triangular DIAG (input) CHARACTER*1 Specifies whether or not the matrix A is unit triangular. = 'N': Non-unit triangular = 'U': Unit triangular N (input) INTEGER The order of the matrix A. N >= 0. A (input/output) REAL array, dimension (LDA,N) On entry, the triangular matrix A. If UPLO = 'U', the leading n by n upper triangular part of the array A contains the upper triangular matrix, and the strictly lower triangular part of A is not referenced. If UPLO = 'L', the leading n by n lower triangular part of the array A contains the lower triangular matrix, and the strictly upper triangular part of A is not referenced. If DIAG = 'U', the diagonal elements of A are also not referenced and are assumed to be 1. On exit, the (triangular) inverse of the original matrix, in the same storage format. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,N). INFO (output) INTEGER = 0: successful exit < 0: if INFO = -k, the k-th argument had an illegal value ===================================================================== Test the input parameters. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; /* Function Body */ *info = 0; upper = lsame_(uplo, "U"); nounit = lsame_(diag, "N"); if (! upper && ! lsame_(uplo, "L")) { *info = -1; } else if (! nounit && ! lsame_(diag, "U")) { *info = -2; } else if (*n < 0) { *info = -3; } else if (*lda < max(1,*n)) { *info = -5; } if (*info != 0) { i__1 = -(*info); xerbla_("STRTI2", &i__1); return 0; } if (upper) { /* Compute inverse of upper triangular matrix. */ i__1 = *n; for (j = 1; j <= i__1; ++j) { if (nounit) { a[j + j * a_dim1] = 1.f / a[j + j * a_dim1]; ajj = -a[j + j * a_dim1]; } else { ajj = -1.f; } /* Compute elements 1:j-1 of j-th column. */ i__2 = j - 1; strmv_("Upper", "No transpose", diag, &i__2, &a[a_offset], lda, & a[j * a_dim1 + 1], &c__1); i__2 = j - 1; sscal_(&i__2, &ajj, &a[j * a_dim1 + 1], &c__1); /* L10: */ } } else { /* Compute inverse of lower triangular matrix. */ for (j = *n; j >= 1; --j) { if (nounit) { a[j + j * a_dim1] = 1.f / a[j + j * a_dim1]; ajj = -a[j + j * a_dim1]; } else { ajj = -1.f; } if (j < *n) { /* Compute elements j+1:n of j-th column. */ i__1 = *n - j; strmv_("Lower", "No transpose", diag, &i__1, &a[j + 1 + (j + 1) * a_dim1], lda, &a[j + 1 + j * a_dim1], &c__1); i__1 = *n - j; sscal_(&i__1, &ajj, &a[j + 1 + j * a_dim1], &c__1); } /* L20: */ } } return 0; /* End of STRTI2 */ } /* strti2_ */ /* Subroutine */ int strtri_(char *uplo, char *diag, integer *n, real *a, integer *lda, integer *info) { /* System generated locals */ address a__1[2]; integer a_dim1, a_offset, i__1, i__2[2], i__3, i__4, i__5; char ch__1[2]; /* Builtin functions */ /* Subroutine */ int s_cat(char *, char **, integer *, integer *, ftnlen); /* Local variables */ static integer j, jb, nb, nn; extern logical lsame_(char *, char *); static logical upper; extern /* Subroutine */ int strmm_(char *, char *, char *, char *, integer *, integer *, real *, real *, integer *, real *, integer * ), strsm_(char *, char *, char *, char *, integer *, integer *, real *, real *, integer *, real *, integer *), strti2_(char *, char * , integer *, real *, integer *, integer *), xerbla_(char *, integer *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); static logical nounit; /* -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University March 31, 1993 Purpose ======= STRTRI computes the inverse of a real upper or lower triangular matrix A. This is the Level 3 BLAS version of the algorithm. Arguments ========= UPLO (input) CHARACTER*1 = 'U': A is upper triangular; = 'L': A is lower triangular. DIAG (input) CHARACTER*1 = 'N': A is non-unit triangular; = 'U': A is unit triangular. N (input) INTEGER The order of the matrix A. N >= 0. A (input/output) REAL array, dimension (LDA,N) On entry, the triangular matrix A. If UPLO = 'U', the leading N-by-N upper triangular part of the array A contains the upper triangular matrix, and the strictly lower triangular part of A is not referenced. If UPLO = 'L', the leading N-by-N lower triangular part of the array A contains the lower triangular matrix, and the strictly upper triangular part of A is not referenced. If DIAG = 'U', the diagonal elements of A are also not referenced and are assumed to be 1. On exit, the (triangular) inverse of the original matrix, in the same storage format. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,N). INFO (output) INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value > 0: if INFO = i, A(i,i) is exactly zero. The triangular matrix is singular and its inverse can not be computed. ===================================================================== Test the input parameters. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; /* Function Body */ *info = 0; upper = lsame_(uplo, "U"); nounit = lsame_(diag, "N"); if (! upper && ! lsame_(uplo, "L")) { *info = -1; } else if (! nounit && ! lsame_(diag, "U")) { *info = -2; } else if (*n < 0) { *info = -3; } else if (*lda < max(1,*n)) { *info = -5; } if (*info != 0) { i__1 = -(*info); xerbla_("STRTRI", &i__1); return 0; } /* Quick return if possible */ if (*n == 0) { return 0; } /* Check for singularity if non-unit. */ if (nounit) { i__1 = *n; for (*info = 1; *info <= i__1; ++(*info)) { if (a[*info + *info * a_dim1] == 0.f) { return 0; } /* L10: */ } *info = 0; } /* Determine the block size for this environment. Writing concatenation */ i__2[0] = 1, a__1[0] = uplo; i__2[1] = 1, a__1[1] = diag; s_cat(ch__1, a__1, i__2, &c__2, (ftnlen)2); nb = ilaenv_(&c__1, "STRTRI", ch__1, n, &c_n1, &c_n1, &c_n1, (ftnlen)6, ( ftnlen)2); if ((nb <= 1) || (nb >= *n)) { /* Use unblocked code */ strti2_(uplo, diag, n, &a[a_offset], lda, info); } else { /* Use blocked code */ if (upper) { /* Compute inverse of upper triangular matrix */ i__1 = *n; i__3 = nb; for (j = 1; i__3 < 0 ? j >= i__1 : j <= i__1; j += i__3) { /* Computing MIN */ i__4 = nb, i__5 = *n - j + 1; jb = min(i__4,i__5); /* Compute rows 1:j-1 of current block column */ i__4 = j - 1; strmm_("Left", "Upper", "No transpose", diag, &i__4, &jb, & c_b1011, &a[a_offset], lda, &a[j * a_dim1 + 1], lda); i__4 = j - 1; strsm_("Right", "Upper", "No transpose", diag, &i__4, &jb, & c_b1290, &a[j + j * a_dim1], lda, &a[j * a_dim1 + 1], lda); /* Compute inverse of current diagonal block */ strti2_("Upper", diag, &jb, &a[j + j * a_dim1], lda, info); /* L20: */ } } else { /* Compute inverse of lower triangular matrix */ nn = (*n - 1) / nb * nb + 1; i__3 = -nb; for (j = nn; i__3 < 0 ? j >= 1 : j <= 1; j += i__3) { /* Computing MIN */ i__1 = nb, i__4 = *n - j + 1; jb = min(i__1,i__4); if (j + jb <= *n) { /* Compute rows j+jb:n of current block column */ i__1 = *n - j - jb + 1; strmm_("Left", "Lower", "No transpose", diag, &i__1, &jb, &c_b1011, &a[j + jb + (j + jb) * a_dim1], lda, &a[ j + jb + j * a_dim1], lda); i__1 = *n - j - jb + 1; strsm_("Right", "Lower", "No transpose", diag, &i__1, &jb, &c_b1290, &a[j + j * a_dim1], lda, &a[j + jb + j * a_dim1], lda); } /* Compute inverse of current diagonal block */ strti2_("Lower", diag, &jb, &a[j + j * a_dim1], lda, info); /* L30: */ } } } return 0; /* End of STRTRI */ } /* strtri_ */ numpy-1.8.2/numpy/linalg/lapack_lite/blas_lite.c0000664000175100017510000206217212370216242023025 0ustar vagrantvagrant00000000000000/* NOTE: This is generated code. Look in Misc/lapack_lite for information on remaking this file. */ #include "f2c.h" #ifdef HAVE_CONFIG #include "config.h" #else extern doublereal dlamch_(char *); #define EPSILON dlamch_("Epsilon") #define SAFEMINIMUM dlamch_("Safe minimum") #define PRECISION dlamch_("Precision") #define BASE dlamch_("Base") #endif extern doublereal dlapy2_(doublereal *x, doublereal *y); /* Table of constant values */ static complex c_b21 = {1.f,0.f}; static integer c__1 = 1; static doublecomplex c_b1077 = {1.,0.}; /* Subroutine */ int caxpy_(integer *n, complex *ca, complex *cx, integer * incx, complex *cy, integer *incy) { /* System generated locals */ integer i__1, i__2, i__3, i__4; real r__1, r__2; complex q__1, q__2; /* Builtin functions */ double r_imag(complex *); /* Local variables */ static integer i__, ix, iy; /* constant times a vector plus a vector. jack dongarra, linpack, 3/11/78. modified 12/3/93, array(1) declarations changed to array(*) */ /* Parameter adjustments */ --cy; --cx; /* Function Body */ if (*n <= 0) { return 0; } if ((r__1 = ca->r, dabs(r__1)) + (r__2 = r_imag(ca), dabs(r__2)) == 0.f) { return 0; } if (*incx == 1 && *incy == 1) { goto L20; } /* code for unequal increments or equal increments not equal to 1 */ ix = 1; iy = 1; if (*incx < 0) { ix = (-(*n) + 1) * *incx + 1; } if (*incy < 0) { iy = (-(*n) + 1) * *incy + 1; } i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = iy; i__3 = iy; i__4 = ix; q__2.r = ca->r * cx[i__4].r - ca->i * cx[i__4].i, q__2.i = ca->r * cx[ i__4].i + ca->i * cx[i__4].r; q__1.r = cy[i__3].r + q__2.r, q__1.i = cy[i__3].i + q__2.i; cy[i__2].r = q__1.r, cy[i__2].i = q__1.i; ix += *incx; iy += *incy; /* L10: */ } return 0; /* code for both increments equal to 1 */ L20: i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = i__; i__3 = i__; i__4 = i__; q__2.r = ca->r * cx[i__4].r - ca->i * cx[i__4].i, q__2.i = ca->r * cx[ i__4].i + ca->i * cx[i__4].r; q__1.r = cy[i__3].r + q__2.r, q__1.i = cy[i__3].i + q__2.i; cy[i__2].r = q__1.r, cy[i__2].i = q__1.i; /* L30: */ } return 0; } /* caxpy_ */ /* Subroutine */ int ccopy_(integer *n, complex *cx, integer *incx, complex * cy, integer *incy) { /* System generated locals */ integer i__1, i__2, i__3; /* Local variables */ static integer i__, ix, iy; /* copies a vector, x, to a vector, y. jack dongarra, linpack, 3/11/78. modified 12/3/93, array(1) declarations changed to array(*) */ /* Parameter adjustments */ --cy; --cx; /* Function Body */ if (*n <= 0) { return 0; } if (*incx == 1 && *incy == 1) { goto L20; } /* code for unequal increments or equal increments not equal to 1 */ ix = 1; iy = 1; if (*incx < 0) { ix = (-(*n) + 1) * *incx + 1; } if (*incy < 0) { iy = (-(*n) + 1) * *incy + 1; } i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = iy; i__3 = ix; cy[i__2].r = cx[i__3].r, cy[i__2].i = cx[i__3].i; ix += *incx; iy += *incy; /* L10: */ } return 0; /* code for both increments equal to 1 */ L20: i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = i__; i__3 = i__; cy[i__2].r = cx[i__3].r, cy[i__2].i = cx[i__3].i; /* L30: */ } return 0; } /* ccopy_ */ /* Complex */ VOID cdotc_(complex * ret_val, integer *n, complex *cx, integer *incx, complex *cy, integer *incy) { /* System generated locals */ integer i__1, i__2; complex q__1, q__2, q__3; /* Builtin functions */ void r_cnjg(complex *, complex *); /* Local variables */ static integer i__, ix, iy; static complex ctemp; /* forms the dot product of two vectors, conjugating the first vector. jack dongarra, linpack, 3/11/78. modified 12/3/93, array(1) declarations changed to array(*) */ /* Parameter adjustments */ --cy; --cx; /* Function Body */ ctemp.r = 0.f, ctemp.i = 0.f; ret_val->r = 0.f, ret_val->i = 0.f; if (*n <= 0) { return ; } if (*incx == 1 && *incy == 1) { goto L20; } /* code for unequal increments or equal increments not equal to 1 */ ix = 1; iy = 1; if (*incx < 0) { ix = (-(*n) + 1) * *incx + 1; } if (*incy < 0) { iy = (-(*n) + 1) * *incy + 1; } i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { r_cnjg(&q__3, &cx[ix]); i__2 = iy; q__2.r = q__3.r * cy[i__2].r - q__3.i * cy[i__2].i, q__2.i = q__3.r * cy[i__2].i + q__3.i * cy[i__2].r; q__1.r = ctemp.r + q__2.r, q__1.i = ctemp.i + q__2.i; ctemp.r = q__1.r, ctemp.i = q__1.i; ix += *incx; iy += *incy; /* L10: */ } ret_val->r = ctemp.r, ret_val->i = ctemp.i; return ; /* code for both increments equal to 1 */ L20: i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { r_cnjg(&q__3, &cx[i__]); i__2 = i__; q__2.r = q__3.r * cy[i__2].r - q__3.i * cy[i__2].i, q__2.i = q__3.r * cy[i__2].i + q__3.i * cy[i__2].r; q__1.r = ctemp.r + q__2.r, q__1.i = ctemp.i + q__2.i; ctemp.r = q__1.r, ctemp.i = q__1.i; /* L30: */ } ret_val->r = ctemp.r, ret_val->i = ctemp.i; return ; } /* cdotc_ */ /* Complex */ VOID cdotu_(complex * ret_val, integer *n, complex *cx, integer *incx, complex *cy, integer *incy) { /* System generated locals */ integer i__1, i__2, i__3; complex q__1, q__2; /* Local variables */ static integer i__, ix, iy; static complex ctemp; /* forms the dot product of two vectors. jack dongarra, linpack, 3/11/78. modified 12/3/93, array(1) declarations changed to array(*) */ /* Parameter adjustments */ --cy; --cx; /* Function Body */ ctemp.r = 0.f, ctemp.i = 0.f; ret_val->r = 0.f, ret_val->i = 0.f; if (*n <= 0) { return ; } if (*incx == 1 && *incy == 1) { goto L20; } /* code for unequal increments or equal increments not equal to 1 */ ix = 1; iy = 1; if (*incx < 0) { ix = (-(*n) + 1) * *incx + 1; } if (*incy < 0) { iy = (-(*n) + 1) * *incy + 1; } i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = ix; i__3 = iy; q__2.r = cx[i__2].r * cy[i__3].r - cx[i__2].i * cy[i__3].i, q__2.i = cx[i__2].r * cy[i__3].i + cx[i__2].i * cy[i__3].r; q__1.r = ctemp.r + q__2.r, q__1.i = ctemp.i + q__2.i; ctemp.r = q__1.r, ctemp.i = q__1.i; ix += *incx; iy += *incy; /* L10: */ } ret_val->r = ctemp.r, ret_val->i = ctemp.i; return ; /* code for both increments equal to 1 */ L20: i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = i__; i__3 = i__; q__2.r = cx[i__2].r * cy[i__3].r - cx[i__2].i * cy[i__3].i, q__2.i = cx[i__2].r * cy[i__3].i + cx[i__2].i * cy[i__3].r; q__1.r = ctemp.r + q__2.r, q__1.i = ctemp.i + q__2.i; ctemp.r = q__1.r, ctemp.i = q__1.i; /* L30: */ } ret_val->r = ctemp.r, ret_val->i = ctemp.i; return ; } /* cdotu_ */ /* Subroutine */ int cgemm_(char *transa, char *transb, integer *m, integer * n, integer *k, complex *alpha, complex *a, integer *lda, complex *b, integer *ldb, complex *beta, complex *c__, integer *ldc) { /* System generated locals */ integer a_dim1, a_offset, b_dim1, b_offset, c_dim1, c_offset, i__1, i__2, i__3, i__4, i__5, i__6; complex q__1, q__2, q__3, q__4; /* Builtin functions */ void r_cnjg(complex *, complex *); /* Local variables */ static integer i__, j, l, info; static logical nota, notb; static complex temp; static logical conja, conjb; static integer ncola; extern logical lsame_(char *, char *); static integer nrowa, nrowb; extern /* Subroutine */ int xerbla_(char *, integer *); /* Purpose ======= CGEMM performs one of the matrix-matrix operations C := alpha*op( A )*op( B ) + beta*C, where op( X ) is one of op( X ) = X or op( X ) = X' or op( X ) = conjg( X' ), alpha and beta are scalars, and A, B and C are matrices, with op( A ) an m by k matrix, op( B ) a k by n matrix and C an m by n matrix. Parameters ========== TRANSA - CHARACTER*1. On entry, TRANSA specifies the form of op( A ) to be used in the matrix multiplication as follows: TRANSA = 'N' or 'n', op( A ) = A. TRANSA = 'T' or 't', op( A ) = A'. TRANSA = 'C' or 'c', op( A ) = conjg( A' ). Unchanged on exit. TRANSB - CHARACTER*1. On entry, TRANSB specifies the form of op( B ) to be used in the matrix multiplication as follows: TRANSB = 'N' or 'n', op( B ) = B. TRANSB = 'T' or 't', op( B ) = B'. TRANSB = 'C' or 'c', op( B ) = conjg( B' ). Unchanged on exit. M - INTEGER. On entry, M specifies the number of rows of the matrix op( A ) and of the matrix C. M must be at least zero. Unchanged on exit. N - INTEGER. On entry, N specifies the number of columns of the matrix op( B ) and the number of columns of the matrix C. N must be at least zero. Unchanged on exit. K - INTEGER. On entry, K specifies the number of columns of the matrix op( A ) and the number of rows of the matrix op( B ). K must be at least zero. Unchanged on exit. ALPHA - COMPLEX . On entry, ALPHA specifies the scalar alpha. Unchanged on exit. A - COMPLEX array of DIMENSION ( LDA, ka ), where ka is k when TRANSA = 'N' or 'n', and is m otherwise. Before entry with TRANSA = 'N' or 'n', the leading m by k part of the array A must contain the matrix A, otherwise the leading k by m part of the array A must contain the matrix A. Unchanged on exit. LDA - INTEGER. On entry, LDA specifies the first dimension of A as declared in the calling (sub) program. When TRANSA = 'N' or 'n' then LDA must be at least max( 1, m ), otherwise LDA must be at least max( 1, k ). Unchanged on exit. B - COMPLEX array of DIMENSION ( LDB, kb ), where kb is n when TRANSB = 'N' or 'n', and is k otherwise. Before entry with TRANSB = 'N' or 'n', the leading k by n part of the array B must contain the matrix B, otherwise the leading n by k part of the array B must contain the matrix B. Unchanged on exit. LDB - INTEGER. On entry, LDB specifies the first dimension of B as declared in the calling (sub) program. When TRANSB = 'N' or 'n' then LDB must be at least max( 1, k ), otherwise LDB must be at least max( 1, n ). Unchanged on exit. BETA - COMPLEX . On entry, BETA specifies the scalar beta. When BETA is supplied as zero then C need not be set on input. Unchanged on exit. C - COMPLEX array of DIMENSION ( LDC, n ). Before entry, the leading m by n part of the array C must contain the matrix C, except when beta is zero, in which case C need not be set on entry. On exit, the array C is overwritten by the m by n matrix ( alpha*op( A )*op( B ) + beta*C ). LDC - INTEGER. On entry, LDC specifies the first dimension of C as declared in the calling (sub) program. LDC must be at least max( 1, m ). Unchanged on exit. Level 3 Blas routine. -- Written on 8-February-1989. Jack Dongarra, Argonne National Laboratory. Iain Duff, AERE Harwell. Jeremy Du Croz, Numerical Algorithms Group Ltd. Sven Hammarling, Numerical Algorithms Group Ltd. Set NOTA and NOTB as true if A and B respectively are not conjugated or transposed, set CONJA and CONJB as true if A and B respectively are to be transposed but not conjugated and set NROWA, NCOLA and NROWB as the number of rows and columns of A and the number of rows of B respectively. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; b_dim1 = *ldb; b_offset = 1 + b_dim1; b -= b_offset; c_dim1 = *ldc; c_offset = 1 + c_dim1; c__ -= c_offset; /* Function Body */ nota = lsame_(transa, "N"); notb = lsame_(transb, "N"); conja = lsame_(transa, "C"); conjb = lsame_(transb, "C"); if (nota) { nrowa = *m; ncola = *k; } else { nrowa = *k; ncola = *m; } if (notb) { nrowb = *k; } else { nrowb = *n; } /* Test the input parameters. */ info = 0; if (! nota && ! conja && ! lsame_(transa, "T")) { info = 1; } else if (! notb && ! conjb && ! lsame_(transb, "T")) { info = 2; } else if (*m < 0) { info = 3; } else if (*n < 0) { info = 4; } else if (*k < 0) { info = 5; } else if (*lda < max(1,nrowa)) { info = 8; } else if (*ldb < max(1,nrowb)) { info = 10; } else if (*ldc < max(1,*m)) { info = 13; } if (info != 0) { xerbla_("CGEMM ", &info); return 0; } /* Quick return if possible. */ if (((*m == 0) || (*n == 0)) || (((alpha->r == 0.f && alpha->i == 0.f) || (*k == 0)) && (beta->r == 1.f && beta->i == 0.f))) { return 0; } /* And when alpha.eq.zero. */ if (alpha->r == 0.f && alpha->i == 0.f) { if (beta->r == 0.f && beta->i == 0.f) { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * c_dim1; c__[i__3].r = 0.f, c__[i__3].i = 0.f; /* L10: */ } /* L20: */ } } else { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * c_dim1; i__4 = i__ + j * c_dim1; q__1.r = beta->r * c__[i__4].r - beta->i * c__[i__4].i, q__1.i = beta->r * c__[i__4].i + beta->i * c__[ i__4].r; c__[i__3].r = q__1.r, c__[i__3].i = q__1.i; /* L30: */ } /* L40: */ } } return 0; } /* Start the operations. */ if (notb) { if (nota) { /* Form C := alpha*A*B + beta*C. */ i__1 = *n; for (j = 1; j <= i__1; ++j) { if (beta->r == 0.f && beta->i == 0.f) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * c_dim1; c__[i__3].r = 0.f, c__[i__3].i = 0.f; /* L50: */ } } else if ((beta->r != 1.f) || (beta->i != 0.f)) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * c_dim1; i__4 = i__ + j * c_dim1; q__1.r = beta->r * c__[i__4].r - beta->i * c__[i__4] .i, q__1.i = beta->r * c__[i__4].i + beta->i * c__[i__4].r; c__[i__3].r = q__1.r, c__[i__3].i = q__1.i; /* L60: */ } } i__2 = *k; for (l = 1; l <= i__2; ++l) { i__3 = l + j * b_dim1; if ((b[i__3].r != 0.f) || (b[i__3].i != 0.f)) { i__3 = l + j * b_dim1; q__1.r = alpha->r * b[i__3].r - alpha->i * b[i__3].i, q__1.i = alpha->r * b[i__3].i + alpha->i * b[ i__3].r; temp.r = q__1.r, temp.i = q__1.i; i__3 = *m; for (i__ = 1; i__ <= i__3; ++i__) { i__4 = i__ + j * c_dim1; i__5 = i__ + j * c_dim1; i__6 = i__ + l * a_dim1; q__2.r = temp.r * a[i__6].r - temp.i * a[i__6].i, q__2.i = temp.r * a[i__6].i + temp.i * a[ i__6].r; q__1.r = c__[i__5].r + q__2.r, q__1.i = c__[i__5] .i + q__2.i; c__[i__4].r = q__1.r, c__[i__4].i = q__1.i; /* L70: */ } } /* L80: */ } /* L90: */ } } else if (conja) { /* Form C := alpha*conjg( A' )*B + beta*C. */ i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { temp.r = 0.f, temp.i = 0.f; i__3 = *k; for (l = 1; l <= i__3; ++l) { r_cnjg(&q__3, &a[l + i__ * a_dim1]); i__4 = l + j * b_dim1; q__2.r = q__3.r * b[i__4].r - q__3.i * b[i__4].i, q__2.i = q__3.r * b[i__4].i + q__3.i * b[i__4] .r; q__1.r = temp.r + q__2.r, q__1.i = temp.i + q__2.i; temp.r = q__1.r, temp.i = q__1.i; /* L100: */ } if (beta->r == 0.f && beta->i == 0.f) { i__3 = i__ + j * c_dim1; q__1.r = alpha->r * temp.r - alpha->i * temp.i, q__1.i = alpha->r * temp.i + alpha->i * temp.r; c__[i__3].r = q__1.r, c__[i__3].i = q__1.i; } else { i__3 = i__ + j * c_dim1; q__2.r = alpha->r * temp.r - alpha->i * temp.i, q__2.i = alpha->r * temp.i + alpha->i * temp.r; i__4 = i__ + j * c_dim1; q__3.r = beta->r * c__[i__4].r - beta->i * c__[i__4] .i, q__3.i = beta->r * c__[i__4].i + beta->i * c__[i__4].r; q__1.r = q__2.r + q__3.r, q__1.i = q__2.i + q__3.i; c__[i__3].r = q__1.r, c__[i__3].i = q__1.i; } /* L110: */ } /* L120: */ } } else { /* Form C := alpha*A'*B + beta*C */ i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { temp.r = 0.f, temp.i = 0.f; i__3 = *k; for (l = 1; l <= i__3; ++l) { i__4 = l + i__ * a_dim1; i__5 = l + j * b_dim1; q__2.r = a[i__4].r * b[i__5].r - a[i__4].i * b[i__5] .i, q__2.i = a[i__4].r * b[i__5].i + a[i__4] .i * b[i__5].r; q__1.r = temp.r + q__2.r, q__1.i = temp.i + q__2.i; temp.r = q__1.r, temp.i = q__1.i; /* L130: */ } if (beta->r == 0.f && beta->i == 0.f) { i__3 = i__ + j * c_dim1; q__1.r = alpha->r * temp.r - alpha->i * temp.i, q__1.i = alpha->r * temp.i + alpha->i * temp.r; c__[i__3].r = q__1.r, c__[i__3].i = q__1.i; } else { i__3 = i__ + j * c_dim1; q__2.r = alpha->r * temp.r - alpha->i * temp.i, q__2.i = alpha->r * temp.i + alpha->i * temp.r; i__4 = i__ + j * c_dim1; q__3.r = beta->r * c__[i__4].r - beta->i * c__[i__4] .i, q__3.i = beta->r * c__[i__4].i + beta->i * c__[i__4].r; q__1.r = q__2.r + q__3.r, q__1.i = q__2.i + q__3.i; c__[i__3].r = q__1.r, c__[i__3].i = q__1.i; } /* L140: */ } /* L150: */ } } } else if (nota) { if (conjb) { /* Form C := alpha*A*conjg( B' ) + beta*C. */ i__1 = *n; for (j = 1; j <= i__1; ++j) { if (beta->r == 0.f && beta->i == 0.f) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * c_dim1; c__[i__3].r = 0.f, c__[i__3].i = 0.f; /* L160: */ } } else if ((beta->r != 1.f) || (beta->i != 0.f)) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * c_dim1; i__4 = i__ + j * c_dim1; q__1.r = beta->r * c__[i__4].r - beta->i * c__[i__4] .i, q__1.i = beta->r * c__[i__4].i + beta->i * c__[i__4].r; c__[i__3].r = q__1.r, c__[i__3].i = q__1.i; /* L170: */ } } i__2 = *k; for (l = 1; l <= i__2; ++l) { i__3 = j + l * b_dim1; if ((b[i__3].r != 0.f) || (b[i__3].i != 0.f)) { r_cnjg(&q__2, &b[j + l * b_dim1]); q__1.r = alpha->r * q__2.r - alpha->i * q__2.i, q__1.i = alpha->r * q__2.i + alpha->i * q__2.r; temp.r = q__1.r, temp.i = q__1.i; i__3 = *m; for (i__ = 1; i__ <= i__3; ++i__) { i__4 = i__ + j * c_dim1; i__5 = i__ + j * c_dim1; i__6 = i__ + l * a_dim1; q__2.r = temp.r * a[i__6].r - temp.i * a[i__6].i, q__2.i = temp.r * a[i__6].i + temp.i * a[ i__6].r; q__1.r = c__[i__5].r + q__2.r, q__1.i = c__[i__5] .i + q__2.i; c__[i__4].r = q__1.r, c__[i__4].i = q__1.i; /* L180: */ } } /* L190: */ } /* L200: */ } } else { /* Form C := alpha*A*B' + beta*C */ i__1 = *n; for (j = 1; j <= i__1; ++j) { if (beta->r == 0.f && beta->i == 0.f) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * c_dim1; c__[i__3].r = 0.f, c__[i__3].i = 0.f; /* L210: */ } } else if ((beta->r != 1.f) || (beta->i != 0.f)) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * c_dim1; i__4 = i__ + j * c_dim1; q__1.r = beta->r * c__[i__4].r - beta->i * c__[i__4] .i, q__1.i = beta->r * c__[i__4].i + beta->i * c__[i__4].r; c__[i__3].r = q__1.r, c__[i__3].i = q__1.i; /* L220: */ } } i__2 = *k; for (l = 1; l <= i__2; ++l) { i__3 = j + l * b_dim1; if ((b[i__3].r != 0.f) || (b[i__3].i != 0.f)) { i__3 = j + l * b_dim1; q__1.r = alpha->r * b[i__3].r - alpha->i * b[i__3].i, q__1.i = alpha->r * b[i__3].i + alpha->i * b[ i__3].r; temp.r = q__1.r, temp.i = q__1.i; i__3 = *m; for (i__ = 1; i__ <= i__3; ++i__) { i__4 = i__ + j * c_dim1; i__5 = i__ + j * c_dim1; i__6 = i__ + l * a_dim1; q__2.r = temp.r * a[i__6].r - temp.i * a[i__6].i, q__2.i = temp.r * a[i__6].i + temp.i * a[ i__6].r; q__1.r = c__[i__5].r + q__2.r, q__1.i = c__[i__5] .i + q__2.i; c__[i__4].r = q__1.r, c__[i__4].i = q__1.i; /* L230: */ } } /* L240: */ } /* L250: */ } } } else if (conja) { if (conjb) { /* Form C := alpha*conjg( A' )*conjg( B' ) + beta*C. */ i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { temp.r = 0.f, temp.i = 0.f; i__3 = *k; for (l = 1; l <= i__3; ++l) { r_cnjg(&q__3, &a[l + i__ * a_dim1]); r_cnjg(&q__4, &b[j + l * b_dim1]); q__2.r = q__3.r * q__4.r - q__3.i * q__4.i, q__2.i = q__3.r * q__4.i + q__3.i * q__4.r; q__1.r = temp.r + q__2.r, q__1.i = temp.i + q__2.i; temp.r = q__1.r, temp.i = q__1.i; /* L260: */ } if (beta->r == 0.f && beta->i == 0.f) { i__3 = i__ + j * c_dim1; q__1.r = alpha->r * temp.r - alpha->i * temp.i, q__1.i = alpha->r * temp.i + alpha->i * temp.r; c__[i__3].r = q__1.r, c__[i__3].i = q__1.i; } else { i__3 = i__ + j * c_dim1; q__2.r = alpha->r * temp.r - alpha->i * temp.i, q__2.i = alpha->r * temp.i + alpha->i * temp.r; i__4 = i__ + j * c_dim1; q__3.r = beta->r * c__[i__4].r - beta->i * c__[i__4] .i, q__3.i = beta->r * c__[i__4].i + beta->i * c__[i__4].r; q__1.r = q__2.r + q__3.r, q__1.i = q__2.i + q__3.i; c__[i__3].r = q__1.r, c__[i__3].i = q__1.i; } /* L270: */ } /* L280: */ } } else { /* Form C := alpha*conjg( A' )*B' + beta*C */ i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { temp.r = 0.f, temp.i = 0.f; i__3 = *k; for (l = 1; l <= i__3; ++l) { r_cnjg(&q__3, &a[l + i__ * a_dim1]); i__4 = j + l * b_dim1; q__2.r = q__3.r * b[i__4].r - q__3.i * b[i__4].i, q__2.i = q__3.r * b[i__4].i + q__3.i * b[i__4] .r; q__1.r = temp.r + q__2.r, q__1.i = temp.i + q__2.i; temp.r = q__1.r, temp.i = q__1.i; /* L290: */ } if (beta->r == 0.f && beta->i == 0.f) { i__3 = i__ + j * c_dim1; q__1.r = alpha->r * temp.r - alpha->i * temp.i, q__1.i = alpha->r * temp.i + alpha->i * temp.r; c__[i__3].r = q__1.r, c__[i__3].i = q__1.i; } else { i__3 = i__ + j * c_dim1; q__2.r = alpha->r * temp.r - alpha->i * temp.i, q__2.i = alpha->r * temp.i + alpha->i * temp.r; i__4 = i__ + j * c_dim1; q__3.r = beta->r * c__[i__4].r - beta->i * c__[i__4] .i, q__3.i = beta->r * c__[i__4].i + beta->i * c__[i__4].r; q__1.r = q__2.r + q__3.r, q__1.i = q__2.i + q__3.i; c__[i__3].r = q__1.r, c__[i__3].i = q__1.i; } /* L300: */ } /* L310: */ } } } else { if (conjb) { /* Form C := alpha*A'*conjg( B' ) + beta*C */ i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { temp.r = 0.f, temp.i = 0.f; i__3 = *k; for (l = 1; l <= i__3; ++l) { i__4 = l + i__ * a_dim1; r_cnjg(&q__3, &b[j + l * b_dim1]); q__2.r = a[i__4].r * q__3.r - a[i__4].i * q__3.i, q__2.i = a[i__4].r * q__3.i + a[i__4].i * q__3.r; q__1.r = temp.r + q__2.r, q__1.i = temp.i + q__2.i; temp.r = q__1.r, temp.i = q__1.i; /* L320: */ } if (beta->r == 0.f && beta->i == 0.f) { i__3 = i__ + j * c_dim1; q__1.r = alpha->r * temp.r - alpha->i * temp.i, q__1.i = alpha->r * temp.i + alpha->i * temp.r; c__[i__3].r = q__1.r, c__[i__3].i = q__1.i; } else { i__3 = i__ + j * c_dim1; q__2.r = alpha->r * temp.r - alpha->i * temp.i, q__2.i = alpha->r * temp.i + alpha->i * temp.r; i__4 = i__ + j * c_dim1; q__3.r = beta->r * c__[i__4].r - beta->i * c__[i__4] .i, q__3.i = beta->r * c__[i__4].i + beta->i * c__[i__4].r; q__1.r = q__2.r + q__3.r, q__1.i = q__2.i + q__3.i; c__[i__3].r = q__1.r, c__[i__3].i = q__1.i; } /* L330: */ } /* L340: */ } } else { /* Form C := alpha*A'*B' + beta*C */ i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { temp.r = 0.f, temp.i = 0.f; i__3 = *k; for (l = 1; l <= i__3; ++l) { i__4 = l + i__ * a_dim1; i__5 = j + l * b_dim1; q__2.r = a[i__4].r * b[i__5].r - a[i__4].i * b[i__5] .i, q__2.i = a[i__4].r * b[i__5].i + a[i__4] .i * b[i__5].r; q__1.r = temp.r + q__2.r, q__1.i = temp.i + q__2.i; temp.r = q__1.r, temp.i = q__1.i; /* L350: */ } if (beta->r == 0.f && beta->i == 0.f) { i__3 = i__ + j * c_dim1; q__1.r = alpha->r * temp.r - alpha->i * temp.i, q__1.i = alpha->r * temp.i + alpha->i * temp.r; c__[i__3].r = q__1.r, c__[i__3].i = q__1.i; } else { i__3 = i__ + j * c_dim1; q__2.r = alpha->r * temp.r - alpha->i * temp.i, q__2.i = alpha->r * temp.i + alpha->i * temp.r; i__4 = i__ + j * c_dim1; q__3.r = beta->r * c__[i__4].r - beta->i * c__[i__4] .i, q__3.i = beta->r * c__[i__4].i + beta->i * c__[i__4].r; q__1.r = q__2.r + q__3.r, q__1.i = q__2.i + q__3.i; c__[i__3].r = q__1.r, c__[i__3].i = q__1.i; } /* L360: */ } /* L370: */ } } } return 0; /* End of CGEMM . */ } /* cgemm_ */ /* Subroutine */ int cgemv_(char *trans, integer *m, integer *n, complex * alpha, complex *a, integer *lda, complex *x, integer *incx, complex * beta, complex *y, integer *incy) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3, i__4, i__5; complex q__1, q__2, q__3; /* Builtin functions */ void r_cnjg(complex *, complex *); /* Local variables */ static integer i__, j, ix, iy, jx, jy, kx, ky, info; static complex temp; static integer lenx, leny; extern logical lsame_(char *, char *); extern /* Subroutine */ int xerbla_(char *, integer *); static logical noconj; /* Purpose ======= CGEMV performs one of the matrix-vector operations y := alpha*A*x + beta*y, or y := alpha*A'*x + beta*y, or y := alpha*conjg( A' )*x + beta*y, where alpha and beta are scalars, x and y are vectors and A is an m by n matrix. Parameters ========== TRANS - CHARACTER*1. On entry, TRANS specifies the operation to be performed as follows: TRANS = 'N' or 'n' y := alpha*A*x + beta*y. TRANS = 'T' or 't' y := alpha*A'*x + beta*y. TRANS = 'C' or 'c' y := alpha*conjg( A' )*x + beta*y. Unchanged on exit. M - INTEGER. On entry, M specifies the number of rows of the matrix A. M must be at least zero. Unchanged on exit. N - INTEGER. On entry, N specifies the number of columns of the matrix A. N must be at least zero. Unchanged on exit. ALPHA - COMPLEX . On entry, ALPHA specifies the scalar alpha. Unchanged on exit. A - COMPLEX array of DIMENSION ( LDA, n ). Before entry, the leading m by n part of the array A must contain the matrix of coefficients. Unchanged on exit. LDA - INTEGER. On entry, LDA specifies the first dimension of A as declared in the calling (sub) program. LDA must be at least max( 1, m ). Unchanged on exit. X - COMPLEX array of DIMENSION at least ( 1 + ( n - 1 )*abs( INCX ) ) when TRANS = 'N' or 'n' and at least ( 1 + ( m - 1 )*abs( INCX ) ) otherwise. Before entry, the incremented array X must contain the vector x. Unchanged on exit. INCX - INTEGER. On entry, INCX specifies the increment for the elements of X. INCX must not be zero. Unchanged on exit. BETA - COMPLEX . On entry, BETA specifies the scalar beta. When BETA is supplied as zero then Y need not be set on input. Unchanged on exit. Y - COMPLEX array of DIMENSION at least ( 1 + ( m - 1 )*abs( INCY ) ) when TRANS = 'N' or 'n' and at least ( 1 + ( n - 1 )*abs( INCY ) ) otherwise. Before entry with BETA non-zero, the incremented array Y must contain the vector y. On exit, Y is overwritten by the updated vector y. INCY - INTEGER. On entry, INCY specifies the increment for the elements of Y. INCY must not be zero. Unchanged on exit. Level 2 Blas routine. -- Written on 22-October-1986. Jack Dongarra, Argonne National Lab. Jeremy Du Croz, Nag Central Office. Sven Hammarling, Nag Central Office. Richard Hanson, Sandia National Labs. Test the input parameters. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --x; --y; /* Function Body */ info = 0; if (! lsame_(trans, "N") && ! lsame_(trans, "T") && ! lsame_(trans, "C") ) { info = 1; } else if (*m < 0) { info = 2; } else if (*n < 0) { info = 3; } else if (*lda < max(1,*m)) { info = 6; } else if (*incx == 0) { info = 8; } else if (*incy == 0) { info = 11; } if (info != 0) { xerbla_("CGEMV ", &info); return 0; } /* Quick return if possible. */ if (((*m == 0) || (*n == 0)) || (alpha->r == 0.f && alpha->i == 0.f && ( beta->r == 1.f && beta->i == 0.f))) { return 0; } noconj = lsame_(trans, "T"); /* Set LENX and LENY, the lengths of the vectors x and y, and set up the start points in X and Y. */ if (lsame_(trans, "N")) { lenx = *n; leny = *m; } else { lenx = *m; leny = *n; } if (*incx > 0) { kx = 1; } else { kx = 1 - (lenx - 1) * *incx; } if (*incy > 0) { ky = 1; } else { ky = 1 - (leny - 1) * *incy; } /* Start the operations. In this version the elements of A are accessed sequentially with one pass through A. First form y := beta*y. */ if ((beta->r != 1.f) || (beta->i != 0.f)) { if (*incy == 1) { if (beta->r == 0.f && beta->i == 0.f) { i__1 = leny; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = i__; y[i__2].r = 0.f, y[i__2].i = 0.f; /* L10: */ } } else { i__1 = leny; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = i__; i__3 = i__; q__1.r = beta->r * y[i__3].r - beta->i * y[i__3].i, q__1.i = beta->r * y[i__3].i + beta->i * y[i__3] .r; y[i__2].r = q__1.r, y[i__2].i = q__1.i; /* L20: */ } } } else { iy = ky; if (beta->r == 0.f && beta->i == 0.f) { i__1 = leny; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = iy; y[i__2].r = 0.f, y[i__2].i = 0.f; iy += *incy; /* L30: */ } } else { i__1 = leny; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = iy; i__3 = iy; q__1.r = beta->r * y[i__3].r - beta->i * y[i__3].i, q__1.i = beta->r * y[i__3].i + beta->i * y[i__3] .r; y[i__2].r = q__1.r, y[i__2].i = q__1.i; iy += *incy; /* L40: */ } } } } if (alpha->r == 0.f && alpha->i == 0.f) { return 0; } if (lsame_(trans, "N")) { /* Form y := alpha*A*x + y. */ jx = kx; if (*incy == 1) { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = jx; if ((x[i__2].r != 0.f) || (x[i__2].i != 0.f)) { i__2 = jx; q__1.r = alpha->r * x[i__2].r - alpha->i * x[i__2].i, q__1.i = alpha->r * x[i__2].i + alpha->i * x[i__2] .r; temp.r = q__1.r, temp.i = q__1.i; i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__; i__4 = i__; i__5 = i__ + j * a_dim1; q__2.r = temp.r * a[i__5].r - temp.i * a[i__5].i, q__2.i = temp.r * a[i__5].i + temp.i * a[i__5] .r; q__1.r = y[i__4].r + q__2.r, q__1.i = y[i__4].i + q__2.i; y[i__3].r = q__1.r, y[i__3].i = q__1.i; /* L50: */ } } jx += *incx; /* L60: */ } } else { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = jx; if ((x[i__2].r != 0.f) || (x[i__2].i != 0.f)) { i__2 = jx; q__1.r = alpha->r * x[i__2].r - alpha->i * x[i__2].i, q__1.i = alpha->r * x[i__2].i + alpha->i * x[i__2] .r; temp.r = q__1.r, temp.i = q__1.i; iy = ky; i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = iy; i__4 = iy; i__5 = i__ + j * a_dim1; q__2.r = temp.r * a[i__5].r - temp.i * a[i__5].i, q__2.i = temp.r * a[i__5].i + temp.i * a[i__5] .r; q__1.r = y[i__4].r + q__2.r, q__1.i = y[i__4].i + q__2.i; y[i__3].r = q__1.r, y[i__3].i = q__1.i; iy += *incy; /* L70: */ } } jx += *incx; /* L80: */ } } } else { /* Form y := alpha*A'*x + y or y := alpha*conjg( A' )*x + y. */ jy = ky; if (*incx == 1) { i__1 = *n; for (j = 1; j <= i__1; ++j) { temp.r = 0.f, temp.i = 0.f; if (noconj) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * a_dim1; i__4 = i__; q__2.r = a[i__3].r * x[i__4].r - a[i__3].i * x[i__4] .i, q__2.i = a[i__3].r * x[i__4].i + a[i__3] .i * x[i__4].r; q__1.r = temp.r + q__2.r, q__1.i = temp.i + q__2.i; temp.r = q__1.r, temp.i = q__1.i; /* L90: */ } } else { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { r_cnjg(&q__3, &a[i__ + j * a_dim1]); i__3 = i__; q__2.r = q__3.r * x[i__3].r - q__3.i * x[i__3].i, q__2.i = q__3.r * x[i__3].i + q__3.i * x[i__3] .r; q__1.r = temp.r + q__2.r, q__1.i = temp.i + q__2.i; temp.r = q__1.r, temp.i = q__1.i; /* L100: */ } } i__2 = jy; i__3 = jy; q__2.r = alpha->r * temp.r - alpha->i * temp.i, q__2.i = alpha->r * temp.i + alpha->i * temp.r; q__1.r = y[i__3].r + q__2.r, q__1.i = y[i__3].i + q__2.i; y[i__2].r = q__1.r, y[i__2].i = q__1.i; jy += *incy; /* L110: */ } } else { i__1 = *n; for (j = 1; j <= i__1; ++j) { temp.r = 0.f, temp.i = 0.f; ix = kx; if (noconj) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * a_dim1; i__4 = ix; q__2.r = a[i__3].r * x[i__4].r - a[i__3].i * x[i__4] .i, q__2.i = a[i__3].r * x[i__4].i + a[i__3] .i * x[i__4].r; q__1.r = temp.r + q__2.r, q__1.i = temp.i + q__2.i; temp.r = q__1.r, temp.i = q__1.i; ix += *incx; /* L120: */ } } else { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { r_cnjg(&q__3, &a[i__ + j * a_dim1]); i__3 = ix; q__2.r = q__3.r * x[i__3].r - q__3.i * x[i__3].i, q__2.i = q__3.r * x[i__3].i + q__3.i * x[i__3] .r; q__1.r = temp.r + q__2.r, q__1.i = temp.i + q__2.i; temp.r = q__1.r, temp.i = q__1.i; ix += *incx; /* L130: */ } } i__2 = jy; i__3 = jy; q__2.r = alpha->r * temp.r - alpha->i * temp.i, q__2.i = alpha->r * temp.i + alpha->i * temp.r; q__1.r = y[i__3].r + q__2.r, q__1.i = y[i__3].i + q__2.i; y[i__2].r = q__1.r, y[i__2].i = q__1.i; jy += *incy; /* L140: */ } } } return 0; /* End of CGEMV . */ } /* cgemv_ */ /* Subroutine */ int cgerc_(integer *m, integer *n, complex *alpha, complex * x, integer *incx, complex *y, integer *incy, complex *a, integer *lda) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3, i__4, i__5; complex q__1, q__2; /* Builtin functions */ void r_cnjg(complex *, complex *); /* Local variables */ static integer i__, j, ix, jy, kx, info; static complex temp; extern /* Subroutine */ int xerbla_(char *, integer *); /* Purpose ======= CGERC performs the rank 1 operation A := alpha*x*conjg( y' ) + A, where alpha is a scalar, x is an m element vector, y is an n element vector and A is an m by n matrix. Parameters ========== M - INTEGER. On entry, M specifies the number of rows of the matrix A. M must be at least zero. Unchanged on exit. N - INTEGER. On entry, N specifies the number of columns of the matrix A. N must be at least zero. Unchanged on exit. ALPHA - COMPLEX . On entry, ALPHA specifies the scalar alpha. Unchanged on exit. X - COMPLEX array of dimension at least ( 1 + ( m - 1 )*abs( INCX ) ). Before entry, the incremented array X must contain the m element vector x. Unchanged on exit. INCX - INTEGER. On entry, INCX specifies the increment for the elements of X. INCX must not be zero. Unchanged on exit. Y - COMPLEX array of dimension at least ( 1 + ( n - 1 )*abs( INCY ) ). Before entry, the incremented array Y must contain the n element vector y. Unchanged on exit. INCY - INTEGER. On entry, INCY specifies the increment for the elements of Y. INCY must not be zero. Unchanged on exit. A - COMPLEX array of DIMENSION ( LDA, n ). Before entry, the leading m by n part of the array A must contain the matrix of coefficients. On exit, A is overwritten by the updated matrix. LDA - INTEGER. On entry, LDA specifies the first dimension of A as declared in the calling (sub) program. LDA must be at least max( 1, m ). Unchanged on exit. Level 2 Blas routine. -- Written on 22-October-1986. Jack Dongarra, Argonne National Lab. Jeremy Du Croz, Nag Central Office. Sven Hammarling, Nag Central Office. Richard Hanson, Sandia National Labs. Test the input parameters. */ /* Parameter adjustments */ --x; --y; a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; /* Function Body */ info = 0; if (*m < 0) { info = 1; } else if (*n < 0) { info = 2; } else if (*incx == 0) { info = 5; } else if (*incy == 0) { info = 7; } else if (*lda < max(1,*m)) { info = 9; } if (info != 0) { xerbla_("CGERC ", &info); return 0; } /* Quick return if possible. */ if (((*m == 0) || (*n == 0)) || (alpha->r == 0.f && alpha->i == 0.f)) { return 0; } /* Start the operations. In this version the elements of A are accessed sequentially with one pass through A. */ if (*incy > 0) { jy = 1; } else { jy = 1 - (*n - 1) * *incy; } if (*incx == 1) { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = jy; if ((y[i__2].r != 0.f) || (y[i__2].i != 0.f)) { r_cnjg(&q__2, &y[jy]); q__1.r = alpha->r * q__2.r - alpha->i * q__2.i, q__1.i = alpha->r * q__2.i + alpha->i * q__2.r; temp.r = q__1.r, temp.i = q__1.i; i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * a_dim1; i__4 = i__ + j * a_dim1; i__5 = i__; q__2.r = x[i__5].r * temp.r - x[i__5].i * temp.i, q__2.i = x[i__5].r * temp.i + x[i__5].i * temp.r; q__1.r = a[i__4].r + q__2.r, q__1.i = a[i__4].i + q__2.i; a[i__3].r = q__1.r, a[i__3].i = q__1.i; /* L10: */ } } jy += *incy; /* L20: */ } } else { if (*incx > 0) { kx = 1; } else { kx = 1 - (*m - 1) * *incx; } i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = jy; if ((y[i__2].r != 0.f) || (y[i__2].i != 0.f)) { r_cnjg(&q__2, &y[jy]); q__1.r = alpha->r * q__2.r - alpha->i * q__2.i, q__1.i = alpha->r * q__2.i + alpha->i * q__2.r; temp.r = q__1.r, temp.i = q__1.i; ix = kx; i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * a_dim1; i__4 = i__ + j * a_dim1; i__5 = ix; q__2.r = x[i__5].r * temp.r - x[i__5].i * temp.i, q__2.i = x[i__5].r * temp.i + x[i__5].i * temp.r; q__1.r = a[i__4].r + q__2.r, q__1.i = a[i__4].i + q__2.i; a[i__3].r = q__1.r, a[i__3].i = q__1.i; ix += *incx; /* L30: */ } } jy += *incy; /* L40: */ } } return 0; /* End of CGERC . */ } /* cgerc_ */ /* Subroutine */ int cgeru_(integer *m, integer *n, complex *alpha, complex * x, integer *incx, complex *y, integer *incy, complex *a, integer *lda) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3, i__4, i__5; complex q__1, q__2; /* Local variables */ static integer i__, j, ix, jy, kx, info; static complex temp; extern /* Subroutine */ int xerbla_(char *, integer *); /* Purpose ======= CGERU performs the rank 1 operation A := alpha*x*y' + A, where alpha is a scalar, x is an m element vector, y is an n element vector and A is an m by n matrix. Parameters ========== M - INTEGER. On entry, M specifies the number of rows of the matrix A. M must be at least zero. Unchanged on exit. N - INTEGER. On entry, N specifies the number of columns of the matrix A. N must be at least zero. Unchanged on exit. ALPHA - COMPLEX . On entry, ALPHA specifies the scalar alpha. Unchanged on exit. X - COMPLEX array of dimension at least ( 1 + ( m - 1 )*abs( INCX ) ). Before entry, the incremented array X must contain the m element vector x. Unchanged on exit. INCX - INTEGER. On entry, INCX specifies the increment for the elements of X. INCX must not be zero. Unchanged on exit. Y - COMPLEX array of dimension at least ( 1 + ( n - 1 )*abs( INCY ) ). Before entry, the incremented array Y must contain the n element vector y. Unchanged on exit. INCY - INTEGER. On entry, INCY specifies the increment for the elements of Y. INCY must not be zero. Unchanged on exit. A - COMPLEX array of DIMENSION ( LDA, n ). Before entry, the leading m by n part of the array A must contain the matrix of coefficients. On exit, A is overwritten by the updated matrix. LDA - INTEGER. On entry, LDA specifies the first dimension of A as declared in the calling (sub) program. LDA must be at least max( 1, m ). Unchanged on exit. Level 2 Blas routine. -- Written on 22-October-1986. Jack Dongarra, Argonne National Lab. Jeremy Du Croz, Nag Central Office. Sven Hammarling, Nag Central Office. Richard Hanson, Sandia National Labs. Test the input parameters. */ /* Parameter adjustments */ --x; --y; a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; /* Function Body */ info = 0; if (*m < 0) { info = 1; } else if (*n < 0) { info = 2; } else if (*incx == 0) { info = 5; } else if (*incy == 0) { info = 7; } else if (*lda < max(1,*m)) { info = 9; } if (info != 0) { xerbla_("CGERU ", &info); return 0; } /* Quick return if possible. */ if (((*m == 0) || (*n == 0)) || (alpha->r == 0.f && alpha->i == 0.f)) { return 0; } /* Start the operations. In this version the elements of A are accessed sequentially with one pass through A. */ if (*incy > 0) { jy = 1; } else { jy = 1 - (*n - 1) * *incy; } if (*incx == 1) { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = jy; if ((y[i__2].r != 0.f) || (y[i__2].i != 0.f)) { i__2 = jy; q__1.r = alpha->r * y[i__2].r - alpha->i * y[i__2].i, q__1.i = alpha->r * y[i__2].i + alpha->i * y[i__2].r; temp.r = q__1.r, temp.i = q__1.i; i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * a_dim1; i__4 = i__ + j * a_dim1; i__5 = i__; q__2.r = x[i__5].r * temp.r - x[i__5].i * temp.i, q__2.i = x[i__5].r * temp.i + x[i__5].i * temp.r; q__1.r = a[i__4].r + q__2.r, q__1.i = a[i__4].i + q__2.i; a[i__3].r = q__1.r, a[i__3].i = q__1.i; /* L10: */ } } jy += *incy; /* L20: */ } } else { if (*incx > 0) { kx = 1; } else { kx = 1 - (*m - 1) * *incx; } i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = jy; if ((y[i__2].r != 0.f) || (y[i__2].i != 0.f)) { i__2 = jy; q__1.r = alpha->r * y[i__2].r - alpha->i * y[i__2].i, q__1.i = alpha->r * y[i__2].i + alpha->i * y[i__2].r; temp.r = q__1.r, temp.i = q__1.i; ix = kx; i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * a_dim1; i__4 = i__ + j * a_dim1; i__5 = ix; q__2.r = x[i__5].r * temp.r - x[i__5].i * temp.i, q__2.i = x[i__5].r * temp.i + x[i__5].i * temp.r; q__1.r = a[i__4].r + q__2.r, q__1.i = a[i__4].i + q__2.i; a[i__3].r = q__1.r, a[i__3].i = q__1.i; ix += *incx; /* L30: */ } } jy += *incy; /* L40: */ } } return 0; /* End of CGERU . */ } /* cgeru_ */ /* Subroutine */ int chemv_(char *uplo, integer *n, complex *alpha, complex * a, integer *lda, complex *x, integer *incx, complex *beta, complex *y, integer *incy) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3, i__4, i__5; real r__1; complex q__1, q__2, q__3, q__4; /* Builtin functions */ void r_cnjg(complex *, complex *); /* Local variables */ static integer i__, j, ix, iy, jx, jy, kx, ky, info; static complex temp1, temp2; extern logical lsame_(char *, char *); extern /* Subroutine */ int xerbla_(char *, integer *); /* Purpose ======= CHEMV performs the matrix-vector operation y := alpha*A*x + beta*y, where alpha and beta are scalars, x and y are n element vectors and A is an n by n hermitian matrix. Parameters ========== UPLO - CHARACTER*1. On entry, UPLO specifies whether the upper or lower triangular part of the array A is to be referenced as follows: UPLO = 'U' or 'u' Only the upper triangular part of A is to be referenced. UPLO = 'L' or 'l' Only the lower triangular part of A is to be referenced. Unchanged on exit. N - INTEGER. On entry, N specifies the order of the matrix A. N must be at least zero. Unchanged on exit. ALPHA - COMPLEX . On entry, ALPHA specifies the scalar alpha. Unchanged on exit. A - COMPLEX array of DIMENSION ( LDA, n ). Before entry with UPLO = 'U' or 'u', the leading n by n upper triangular part of the array A must contain the upper triangular part of the hermitian matrix and the strictly lower triangular part of A is not referenced. Before entry with UPLO = 'L' or 'l', the leading n by n lower triangular part of the array A must contain the lower triangular part of the hermitian matrix and the strictly upper triangular part of A is not referenced. Note that the imaginary parts of the diagonal elements need not be set and are assumed to be zero. Unchanged on exit. LDA - INTEGER. On entry, LDA specifies the first dimension of A as declared in the calling (sub) program. LDA must be at least max( 1, n ). Unchanged on exit. X - COMPLEX array of dimension at least ( 1 + ( n - 1 )*abs( INCX ) ). Before entry, the incremented array X must contain the n element vector x. Unchanged on exit. INCX - INTEGER. On entry, INCX specifies the increment for the elements of X. INCX must not be zero. Unchanged on exit. BETA - COMPLEX . On entry, BETA specifies the scalar beta. When BETA is supplied as zero then Y need not be set on input. Unchanged on exit. Y - COMPLEX array of dimension at least ( 1 + ( n - 1 )*abs( INCY ) ). Before entry, the incremented array Y must contain the n element vector y. On exit, Y is overwritten by the updated vector y. INCY - INTEGER. On entry, INCY specifies the increment for the elements of Y. INCY must not be zero. Unchanged on exit. Level 2 Blas routine. -- Written on 22-October-1986. Jack Dongarra, Argonne National Lab. Jeremy Du Croz, Nag Central Office. Sven Hammarling, Nag Central Office. Richard Hanson, Sandia National Labs. Test the input parameters. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --x; --y; /* Function Body */ info = 0; if (! lsame_(uplo, "U") && ! lsame_(uplo, "L")) { info = 1; } else if (*n < 0) { info = 2; } else if (*lda < max(1,*n)) { info = 5; } else if (*incx == 0) { info = 7; } else if (*incy == 0) { info = 10; } if (info != 0) { xerbla_("CHEMV ", &info); return 0; } /* Quick return if possible. */ if ((*n == 0) || (alpha->r == 0.f && alpha->i == 0.f && (beta->r == 1.f && beta->i == 0.f))) { return 0; } /* Set up the start points in X and Y. */ if (*incx > 0) { kx = 1; } else { kx = 1 - (*n - 1) * *incx; } if (*incy > 0) { ky = 1; } else { ky = 1 - (*n - 1) * *incy; } /* Start the operations. In this version the elements of A are accessed sequentially with one pass through the triangular part of A. First form y := beta*y. */ if ((beta->r != 1.f) || (beta->i != 0.f)) { if (*incy == 1) { if (beta->r == 0.f && beta->i == 0.f) { i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = i__; y[i__2].r = 0.f, y[i__2].i = 0.f; /* L10: */ } } else { i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = i__; i__3 = i__; q__1.r = beta->r * y[i__3].r - beta->i * y[i__3].i, q__1.i = beta->r * y[i__3].i + beta->i * y[i__3] .r; y[i__2].r = q__1.r, y[i__2].i = q__1.i; /* L20: */ } } } else { iy = ky; if (beta->r == 0.f && beta->i == 0.f) { i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = iy; y[i__2].r = 0.f, y[i__2].i = 0.f; iy += *incy; /* L30: */ } } else { i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = iy; i__3 = iy; q__1.r = beta->r * y[i__3].r - beta->i * y[i__3].i, q__1.i = beta->r * y[i__3].i + beta->i * y[i__3] .r; y[i__2].r = q__1.r, y[i__2].i = q__1.i; iy += *incy; /* L40: */ } } } } if (alpha->r == 0.f && alpha->i == 0.f) { return 0; } if (lsame_(uplo, "U")) { /* Form y when A is stored in upper triangle. */ if (*incx == 1 && *incy == 1) { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = j; q__1.r = alpha->r * x[i__2].r - alpha->i * x[i__2].i, q__1.i = alpha->r * x[i__2].i + alpha->i * x[i__2].r; temp1.r = q__1.r, temp1.i = q__1.i; temp2.r = 0.f, temp2.i = 0.f; i__2 = j - 1; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__; i__4 = i__; i__5 = i__ + j * a_dim1; q__2.r = temp1.r * a[i__5].r - temp1.i * a[i__5].i, q__2.i = temp1.r * a[i__5].i + temp1.i * a[i__5] .r; q__1.r = y[i__4].r + q__2.r, q__1.i = y[i__4].i + q__2.i; y[i__3].r = q__1.r, y[i__3].i = q__1.i; r_cnjg(&q__3, &a[i__ + j * a_dim1]); i__3 = i__; q__2.r = q__3.r * x[i__3].r - q__3.i * x[i__3].i, q__2.i = q__3.r * x[i__3].i + q__3.i * x[i__3].r; q__1.r = temp2.r + q__2.r, q__1.i = temp2.i + q__2.i; temp2.r = q__1.r, temp2.i = q__1.i; /* L50: */ } i__2 = j; i__3 = j; i__4 = j + j * a_dim1; r__1 = a[i__4].r; q__3.r = r__1 * temp1.r, q__3.i = r__1 * temp1.i; q__2.r = y[i__3].r + q__3.r, q__2.i = y[i__3].i + q__3.i; q__4.r = alpha->r * temp2.r - alpha->i * temp2.i, q__4.i = alpha->r * temp2.i + alpha->i * temp2.r; q__1.r = q__2.r + q__4.r, q__1.i = q__2.i + q__4.i; y[i__2].r = q__1.r, y[i__2].i = q__1.i; /* L60: */ } } else { jx = kx; jy = ky; i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = jx; q__1.r = alpha->r * x[i__2].r - alpha->i * x[i__2].i, q__1.i = alpha->r * x[i__2].i + alpha->i * x[i__2].r; temp1.r = q__1.r, temp1.i = q__1.i; temp2.r = 0.f, temp2.i = 0.f; ix = kx; iy = ky; i__2 = j - 1; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = iy; i__4 = iy; i__5 = i__ + j * a_dim1; q__2.r = temp1.r * a[i__5].r - temp1.i * a[i__5].i, q__2.i = temp1.r * a[i__5].i + temp1.i * a[i__5] .r; q__1.r = y[i__4].r + q__2.r, q__1.i = y[i__4].i + q__2.i; y[i__3].r = q__1.r, y[i__3].i = q__1.i; r_cnjg(&q__3, &a[i__ + j * a_dim1]); i__3 = ix; q__2.r = q__3.r * x[i__3].r - q__3.i * x[i__3].i, q__2.i = q__3.r * x[i__3].i + q__3.i * x[i__3].r; q__1.r = temp2.r + q__2.r, q__1.i = temp2.i + q__2.i; temp2.r = q__1.r, temp2.i = q__1.i; ix += *incx; iy += *incy; /* L70: */ } i__2 = jy; i__3 = jy; i__4 = j + j * a_dim1; r__1 = a[i__4].r; q__3.r = r__1 * temp1.r, q__3.i = r__1 * temp1.i; q__2.r = y[i__3].r + q__3.r, q__2.i = y[i__3].i + q__3.i; q__4.r = alpha->r * temp2.r - alpha->i * temp2.i, q__4.i = alpha->r * temp2.i + alpha->i * temp2.r; q__1.r = q__2.r + q__4.r, q__1.i = q__2.i + q__4.i; y[i__2].r = q__1.r, y[i__2].i = q__1.i; jx += *incx; jy += *incy; /* L80: */ } } } else { /* Form y when A is stored in lower triangle. */ if (*incx == 1 && *incy == 1) { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = j; q__1.r = alpha->r * x[i__2].r - alpha->i * x[i__2].i, q__1.i = alpha->r * x[i__2].i + alpha->i * x[i__2].r; temp1.r = q__1.r, temp1.i = q__1.i; temp2.r = 0.f, temp2.i = 0.f; i__2 = j; i__3 = j; i__4 = j + j * a_dim1; r__1 = a[i__4].r; q__2.r = r__1 * temp1.r, q__2.i = r__1 * temp1.i; q__1.r = y[i__3].r + q__2.r, q__1.i = y[i__3].i + q__2.i; y[i__2].r = q__1.r, y[i__2].i = q__1.i; i__2 = *n; for (i__ = j + 1; i__ <= i__2; ++i__) { i__3 = i__; i__4 = i__; i__5 = i__ + j * a_dim1; q__2.r = temp1.r * a[i__5].r - temp1.i * a[i__5].i, q__2.i = temp1.r * a[i__5].i + temp1.i * a[i__5] .r; q__1.r = y[i__4].r + q__2.r, q__1.i = y[i__4].i + q__2.i; y[i__3].r = q__1.r, y[i__3].i = q__1.i; r_cnjg(&q__3, &a[i__ + j * a_dim1]); i__3 = i__; q__2.r = q__3.r * x[i__3].r - q__3.i * x[i__3].i, q__2.i = q__3.r * x[i__3].i + q__3.i * x[i__3].r; q__1.r = temp2.r + q__2.r, q__1.i = temp2.i + q__2.i; temp2.r = q__1.r, temp2.i = q__1.i; /* L90: */ } i__2 = j; i__3 = j; q__2.r = alpha->r * temp2.r - alpha->i * temp2.i, q__2.i = alpha->r * temp2.i + alpha->i * temp2.r; q__1.r = y[i__3].r + q__2.r, q__1.i = y[i__3].i + q__2.i; y[i__2].r = q__1.r, y[i__2].i = q__1.i; /* L100: */ } } else { jx = kx; jy = ky; i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = jx; q__1.r = alpha->r * x[i__2].r - alpha->i * x[i__2].i, q__1.i = alpha->r * x[i__2].i + alpha->i * x[i__2].r; temp1.r = q__1.r, temp1.i = q__1.i; temp2.r = 0.f, temp2.i = 0.f; i__2 = jy; i__3 = jy; i__4 = j + j * a_dim1; r__1 = a[i__4].r; q__2.r = r__1 * temp1.r, q__2.i = r__1 * temp1.i; q__1.r = y[i__3].r + q__2.r, q__1.i = y[i__3].i + q__2.i; y[i__2].r = q__1.r, y[i__2].i = q__1.i; ix = jx; iy = jy; i__2 = *n; for (i__ = j + 1; i__ <= i__2; ++i__) { ix += *incx; iy += *incy; i__3 = iy; i__4 = iy; i__5 = i__ + j * a_dim1; q__2.r = temp1.r * a[i__5].r - temp1.i * a[i__5].i, q__2.i = temp1.r * a[i__5].i + temp1.i * a[i__5] .r; q__1.r = y[i__4].r + q__2.r, q__1.i = y[i__4].i + q__2.i; y[i__3].r = q__1.r, y[i__3].i = q__1.i; r_cnjg(&q__3, &a[i__ + j * a_dim1]); i__3 = ix; q__2.r = q__3.r * x[i__3].r - q__3.i * x[i__3].i, q__2.i = q__3.r * x[i__3].i + q__3.i * x[i__3].r; q__1.r = temp2.r + q__2.r, q__1.i = temp2.i + q__2.i; temp2.r = q__1.r, temp2.i = q__1.i; /* L110: */ } i__2 = jy; i__3 = jy; q__2.r = alpha->r * temp2.r - alpha->i * temp2.i, q__2.i = alpha->r * temp2.i + alpha->i * temp2.r; q__1.r = y[i__3].r + q__2.r, q__1.i = y[i__3].i + q__2.i; y[i__2].r = q__1.r, y[i__2].i = q__1.i; jx += *incx; jy += *incy; /* L120: */ } } } return 0; /* End of CHEMV . */ } /* chemv_ */ /* Subroutine */ int cher2_(char *uplo, integer *n, complex *alpha, complex * x, integer *incx, complex *y, integer *incy, complex *a, integer *lda) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3, i__4, i__5, i__6; real r__1; complex q__1, q__2, q__3, q__4; /* Builtin functions */ void r_cnjg(complex *, complex *); /* Local variables */ static integer i__, j, ix, iy, jx, jy, kx, ky, info; static complex temp1, temp2; extern logical lsame_(char *, char *); extern /* Subroutine */ int xerbla_(char *, integer *); /* Purpose ======= CHER2 performs the hermitian rank 2 operation A := alpha*x*conjg( y' ) + conjg( alpha )*y*conjg( x' ) + A, where alpha is a scalar, x and y are n element vectors and A is an n by n hermitian matrix. Parameters ========== UPLO - CHARACTER*1. On entry, UPLO specifies whether the upper or lower triangular part of the array A is to be referenced as follows: UPLO = 'U' or 'u' Only the upper triangular part of A is to be referenced. UPLO = 'L' or 'l' Only the lower triangular part of A is to be referenced. Unchanged on exit. N - INTEGER. On entry, N specifies the order of the matrix A. N must be at least zero. Unchanged on exit. ALPHA - COMPLEX . On entry, ALPHA specifies the scalar alpha. Unchanged on exit. X - COMPLEX array of dimension at least ( 1 + ( n - 1 )*abs( INCX ) ). Before entry, the incremented array X must contain the n element vector x. Unchanged on exit. INCX - INTEGER. On entry, INCX specifies the increment for the elements of X. INCX must not be zero. Unchanged on exit. Y - COMPLEX array of dimension at least ( 1 + ( n - 1 )*abs( INCY ) ). Before entry, the incremented array Y must contain the n element vector y. Unchanged on exit. INCY - INTEGER. On entry, INCY specifies the increment for the elements of Y. INCY must not be zero. Unchanged on exit. A - COMPLEX array of DIMENSION ( LDA, n ). Before entry with UPLO = 'U' or 'u', the leading n by n upper triangular part of the array A must contain the upper triangular part of the hermitian matrix and the strictly lower triangular part of A is not referenced. On exit, the upper triangular part of the array A is overwritten by the upper triangular part of the updated matrix. Before entry with UPLO = 'L' or 'l', the leading n by n lower triangular part of the array A must contain the lower triangular part of the hermitian matrix and the strictly upper triangular part of A is not referenced. On exit, the lower triangular part of the array A is overwritten by the lower triangular part of the updated matrix. Note that the imaginary parts of the diagonal elements need not be set, they are assumed to be zero, and on exit they are set to zero. LDA - INTEGER. On entry, LDA specifies the first dimension of A as declared in the calling (sub) program. LDA must be at least max( 1, n ). Unchanged on exit. Level 2 Blas routine. -- Written on 22-October-1986. Jack Dongarra, Argonne National Lab. Jeremy Du Croz, Nag Central Office. Sven Hammarling, Nag Central Office. Richard Hanson, Sandia National Labs. Test the input parameters. */ /* Parameter adjustments */ --x; --y; a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; /* Function Body */ info = 0; if (! lsame_(uplo, "U") && ! lsame_(uplo, "L")) { info = 1; } else if (*n < 0) { info = 2; } else if (*incx == 0) { info = 5; } else if (*incy == 0) { info = 7; } else if (*lda < max(1,*n)) { info = 9; } if (info != 0) { xerbla_("CHER2 ", &info); return 0; } /* Quick return if possible. */ if ((*n == 0) || (alpha->r == 0.f && alpha->i == 0.f)) { return 0; } /* Set up the start points in X and Y if the increments are not both unity. */ if ((*incx != 1) || (*incy != 1)) { if (*incx > 0) { kx = 1; } else { kx = 1 - (*n - 1) * *incx; } if (*incy > 0) { ky = 1; } else { ky = 1 - (*n - 1) * *incy; } jx = kx; jy = ky; } /* Start the operations. In this version the elements of A are accessed sequentially with one pass through the triangular part of A. */ if (lsame_(uplo, "U")) { /* Form A when A is stored in the upper triangle. */ if (*incx == 1 && *incy == 1) { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = j; i__3 = j; if (((x[i__2].r != 0.f) || (x[i__2].i != 0.f)) || (((y[i__3] .r != 0.f) || (y[i__3].i != 0.f)))) { r_cnjg(&q__2, &y[j]); q__1.r = alpha->r * q__2.r - alpha->i * q__2.i, q__1.i = alpha->r * q__2.i + alpha->i * q__2.r; temp1.r = q__1.r, temp1.i = q__1.i; i__2 = j; q__2.r = alpha->r * x[i__2].r - alpha->i * x[i__2].i, q__2.i = alpha->r * x[i__2].i + alpha->i * x[i__2] .r; r_cnjg(&q__1, &q__2); temp2.r = q__1.r, temp2.i = q__1.i; i__2 = j - 1; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * a_dim1; i__4 = i__ + j * a_dim1; i__5 = i__; q__3.r = x[i__5].r * temp1.r - x[i__5].i * temp1.i, q__3.i = x[i__5].r * temp1.i + x[i__5].i * temp1.r; q__2.r = a[i__4].r + q__3.r, q__2.i = a[i__4].i + q__3.i; i__6 = i__; q__4.r = y[i__6].r * temp2.r - y[i__6].i * temp2.i, q__4.i = y[i__6].r * temp2.i + y[i__6].i * temp2.r; q__1.r = q__2.r + q__4.r, q__1.i = q__2.i + q__4.i; a[i__3].r = q__1.r, a[i__3].i = q__1.i; /* L10: */ } i__2 = j + j * a_dim1; i__3 = j + j * a_dim1; i__4 = j; q__2.r = x[i__4].r * temp1.r - x[i__4].i * temp1.i, q__2.i = x[i__4].r * temp1.i + x[i__4].i * temp1.r; i__5 = j; q__3.r = y[i__5].r * temp2.r - y[i__5].i * temp2.i, q__3.i = y[i__5].r * temp2.i + y[i__5].i * temp2.r; q__1.r = q__2.r + q__3.r, q__1.i = q__2.i + q__3.i; r__1 = a[i__3].r + q__1.r; a[i__2].r = r__1, a[i__2].i = 0.f; } else { i__2 = j + j * a_dim1; i__3 = j + j * a_dim1; r__1 = a[i__3].r; a[i__2].r = r__1, a[i__2].i = 0.f; } /* L20: */ } } else { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = jx; i__3 = jy; if (((x[i__2].r != 0.f) || (x[i__2].i != 0.f)) || (((y[i__3] .r != 0.f) || (y[i__3].i != 0.f)))) { r_cnjg(&q__2, &y[jy]); q__1.r = alpha->r * q__2.r - alpha->i * q__2.i, q__1.i = alpha->r * q__2.i + alpha->i * q__2.r; temp1.r = q__1.r, temp1.i = q__1.i; i__2 = jx; q__2.r = alpha->r * x[i__2].r - alpha->i * x[i__2].i, q__2.i = alpha->r * x[i__2].i + alpha->i * x[i__2] .r; r_cnjg(&q__1, &q__2); temp2.r = q__1.r, temp2.i = q__1.i; ix = kx; iy = ky; i__2 = j - 1; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * a_dim1; i__4 = i__ + j * a_dim1; i__5 = ix; q__3.r = x[i__5].r * temp1.r - x[i__5].i * temp1.i, q__3.i = x[i__5].r * temp1.i + x[i__5].i * temp1.r; q__2.r = a[i__4].r + q__3.r, q__2.i = a[i__4].i + q__3.i; i__6 = iy; q__4.r = y[i__6].r * temp2.r - y[i__6].i * temp2.i, q__4.i = y[i__6].r * temp2.i + y[i__6].i * temp2.r; q__1.r = q__2.r + q__4.r, q__1.i = q__2.i + q__4.i; a[i__3].r = q__1.r, a[i__3].i = q__1.i; ix += *incx; iy += *incy; /* L30: */ } i__2 = j + j * a_dim1; i__3 = j + j * a_dim1; i__4 = jx; q__2.r = x[i__4].r * temp1.r - x[i__4].i * temp1.i, q__2.i = x[i__4].r * temp1.i + x[i__4].i * temp1.r; i__5 = jy; q__3.r = y[i__5].r * temp2.r - y[i__5].i * temp2.i, q__3.i = y[i__5].r * temp2.i + y[i__5].i * temp2.r; q__1.r = q__2.r + q__3.r, q__1.i = q__2.i + q__3.i; r__1 = a[i__3].r + q__1.r; a[i__2].r = r__1, a[i__2].i = 0.f; } else { i__2 = j + j * a_dim1; i__3 = j + j * a_dim1; r__1 = a[i__3].r; a[i__2].r = r__1, a[i__2].i = 0.f; } jx += *incx; jy += *incy; /* L40: */ } } } else { /* Form A when A is stored in the lower triangle. */ if (*incx == 1 && *incy == 1) { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = j; i__3 = j; if (((x[i__2].r != 0.f) || (x[i__2].i != 0.f)) || (((y[i__3] .r != 0.f) || (y[i__3].i != 0.f)))) { r_cnjg(&q__2, &y[j]); q__1.r = alpha->r * q__2.r - alpha->i * q__2.i, q__1.i = alpha->r * q__2.i + alpha->i * q__2.r; temp1.r = q__1.r, temp1.i = q__1.i; i__2 = j; q__2.r = alpha->r * x[i__2].r - alpha->i * x[i__2].i, q__2.i = alpha->r * x[i__2].i + alpha->i * x[i__2] .r; r_cnjg(&q__1, &q__2); temp2.r = q__1.r, temp2.i = q__1.i; i__2 = j + j * a_dim1; i__3 = j + j * a_dim1; i__4 = j; q__2.r = x[i__4].r * temp1.r - x[i__4].i * temp1.i, q__2.i = x[i__4].r * temp1.i + x[i__4].i * temp1.r; i__5 = j; q__3.r = y[i__5].r * temp2.r - y[i__5].i * temp2.i, q__3.i = y[i__5].r * temp2.i + y[i__5].i * temp2.r; q__1.r = q__2.r + q__3.r, q__1.i = q__2.i + q__3.i; r__1 = a[i__3].r + q__1.r; a[i__2].r = r__1, a[i__2].i = 0.f; i__2 = *n; for (i__ = j + 1; i__ <= i__2; ++i__) { i__3 = i__ + j * a_dim1; i__4 = i__ + j * a_dim1; i__5 = i__; q__3.r = x[i__5].r * temp1.r - x[i__5].i * temp1.i, q__3.i = x[i__5].r * temp1.i + x[i__5].i * temp1.r; q__2.r = a[i__4].r + q__3.r, q__2.i = a[i__4].i + q__3.i; i__6 = i__; q__4.r = y[i__6].r * temp2.r - y[i__6].i * temp2.i, q__4.i = y[i__6].r * temp2.i + y[i__6].i * temp2.r; q__1.r = q__2.r + q__4.r, q__1.i = q__2.i + q__4.i; a[i__3].r = q__1.r, a[i__3].i = q__1.i; /* L50: */ } } else { i__2 = j + j * a_dim1; i__3 = j + j * a_dim1; r__1 = a[i__3].r; a[i__2].r = r__1, a[i__2].i = 0.f; } /* L60: */ } } else { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = jx; i__3 = jy; if (((x[i__2].r != 0.f) || (x[i__2].i != 0.f)) || (((y[i__3] .r != 0.f) || (y[i__3].i != 0.f)))) { r_cnjg(&q__2, &y[jy]); q__1.r = alpha->r * q__2.r - alpha->i * q__2.i, q__1.i = alpha->r * q__2.i + alpha->i * q__2.r; temp1.r = q__1.r, temp1.i = q__1.i; i__2 = jx; q__2.r = alpha->r * x[i__2].r - alpha->i * x[i__2].i, q__2.i = alpha->r * x[i__2].i + alpha->i * x[i__2] .r; r_cnjg(&q__1, &q__2); temp2.r = q__1.r, temp2.i = q__1.i; i__2 = j + j * a_dim1; i__3 = j + j * a_dim1; i__4 = jx; q__2.r = x[i__4].r * temp1.r - x[i__4].i * temp1.i, q__2.i = x[i__4].r * temp1.i + x[i__4].i * temp1.r; i__5 = jy; q__3.r = y[i__5].r * temp2.r - y[i__5].i * temp2.i, q__3.i = y[i__5].r * temp2.i + y[i__5].i * temp2.r; q__1.r = q__2.r + q__3.r, q__1.i = q__2.i + q__3.i; r__1 = a[i__3].r + q__1.r; a[i__2].r = r__1, a[i__2].i = 0.f; ix = jx; iy = jy; i__2 = *n; for (i__ = j + 1; i__ <= i__2; ++i__) { ix += *incx; iy += *incy; i__3 = i__ + j * a_dim1; i__4 = i__ + j * a_dim1; i__5 = ix; q__3.r = x[i__5].r * temp1.r - x[i__5].i * temp1.i, q__3.i = x[i__5].r * temp1.i + x[i__5].i * temp1.r; q__2.r = a[i__4].r + q__3.r, q__2.i = a[i__4].i + q__3.i; i__6 = iy; q__4.r = y[i__6].r * temp2.r - y[i__6].i * temp2.i, q__4.i = y[i__6].r * temp2.i + y[i__6].i * temp2.r; q__1.r = q__2.r + q__4.r, q__1.i = q__2.i + q__4.i; a[i__3].r = q__1.r, a[i__3].i = q__1.i; /* L70: */ } } else { i__2 = j + j * a_dim1; i__3 = j + j * a_dim1; r__1 = a[i__3].r; a[i__2].r = r__1, a[i__2].i = 0.f; } jx += *incx; jy += *incy; /* L80: */ } } } return 0; /* End of CHER2 . */ } /* cher2_ */ /* Subroutine */ int cher2k_(char *uplo, char *trans, integer *n, integer *k, complex *alpha, complex *a, integer *lda, complex *b, integer *ldb, real *beta, complex *c__, integer *ldc) { /* System generated locals */ integer a_dim1, a_offset, b_dim1, b_offset, c_dim1, c_offset, i__1, i__2, i__3, i__4, i__5, i__6, i__7; real r__1; complex q__1, q__2, q__3, q__4, q__5, q__6; /* Builtin functions */ void r_cnjg(complex *, complex *); /* Local variables */ static integer i__, j, l, info; static complex temp1, temp2; extern logical lsame_(char *, char *); static integer nrowa; static logical upper; extern /* Subroutine */ int xerbla_(char *, integer *); /* Purpose ======= CHER2K performs one of the hermitian rank 2k operations C := alpha*A*conjg( B' ) + conjg( alpha )*B*conjg( A' ) + beta*C, or C := alpha*conjg( A' )*B + conjg( alpha )*conjg( B' )*A + beta*C, where alpha and beta are scalars with beta real, C is an n by n hermitian matrix and A and B are n by k matrices in the first case and k by n matrices in the second case. Parameters ========== UPLO - CHARACTER*1. On entry, UPLO specifies whether the upper or lower triangular part of the array C is to be referenced as follows: UPLO = 'U' or 'u' Only the upper triangular part of C is to be referenced. UPLO = 'L' or 'l' Only the lower triangular part of C is to be referenced. Unchanged on exit. TRANS - CHARACTER*1. On entry, TRANS specifies the operation to be performed as follows: TRANS = 'N' or 'n' C := alpha*A*conjg( B' ) + conjg( alpha )*B*conjg( A' ) + beta*C. TRANS = 'C' or 'c' C := alpha*conjg( A' )*B + conjg( alpha )*conjg( B' )*A + beta*C. Unchanged on exit. N - INTEGER. On entry, N specifies the order of the matrix C. N must be at least zero. Unchanged on exit. K - INTEGER. On entry with TRANS = 'N' or 'n', K specifies the number of columns of the matrices A and B, and on entry with TRANS = 'C' or 'c', K specifies the number of rows of the matrices A and B. K must be at least zero. Unchanged on exit. ALPHA - COMPLEX . On entry, ALPHA specifies the scalar alpha. Unchanged on exit. A - COMPLEX array of DIMENSION ( LDA, ka ), where ka is k when TRANS = 'N' or 'n', and is n otherwise. Before entry with TRANS = 'N' or 'n', the leading n by k part of the array A must contain the matrix A, otherwise the leading k by n part of the array A must contain the matrix A. Unchanged on exit. LDA - INTEGER. On entry, LDA specifies the first dimension of A as declared in the calling (sub) program. When TRANS = 'N' or 'n' then LDA must be at least max( 1, n ), otherwise LDA must be at least max( 1, k ). Unchanged on exit. B - COMPLEX array of DIMENSION ( LDB, kb ), where kb is k when TRANS = 'N' or 'n', and is n otherwise. Before entry with TRANS = 'N' or 'n', the leading n by k part of the array B must contain the matrix B, otherwise the leading k by n part of the array B must contain the matrix B. Unchanged on exit. LDB - INTEGER. On entry, LDB specifies the first dimension of B as declared in the calling (sub) program. When TRANS = 'N' or 'n' then LDB must be at least max( 1, n ), otherwise LDB must be at least max( 1, k ). Unchanged on exit. BETA - REAL . On entry, BETA specifies the scalar beta. Unchanged on exit. C - COMPLEX array of DIMENSION ( LDC, n ). Before entry with UPLO = 'U' or 'u', the leading n by n upper triangular part of the array C must contain the upper triangular part of the hermitian matrix and the strictly lower triangular part of C is not referenced. On exit, the upper triangular part of the array C is overwritten by the upper triangular part of the updated matrix. Before entry with UPLO = 'L' or 'l', the leading n by n lower triangular part of the array C must contain the lower triangular part of the hermitian matrix and the strictly upper triangular part of C is not referenced. On exit, the lower triangular part of the array C is overwritten by the lower triangular part of the updated matrix. Note that the imaginary parts of the diagonal elements need not be set, they are assumed to be zero, and on exit they are set to zero. LDC - INTEGER. On entry, LDC specifies the first dimension of C as declared in the calling (sub) program. LDC must be at least max( 1, n ). Unchanged on exit. Level 3 Blas routine. -- Written on 8-February-1989. Jack Dongarra, Argonne National Laboratory. Iain Duff, AERE Harwell. Jeremy Du Croz, Numerical Algorithms Group Ltd. Sven Hammarling, Numerical Algorithms Group Ltd. -- Modified 8-Nov-93 to set C(J,J) to REAL( C(J,J) ) when BETA = 1. Ed Anderson, Cray Research Inc. Test the input parameters. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; b_dim1 = *ldb; b_offset = 1 + b_dim1; b -= b_offset; c_dim1 = *ldc; c_offset = 1 + c_dim1; c__ -= c_offset; /* Function Body */ if (lsame_(trans, "N")) { nrowa = *n; } else { nrowa = *k; } upper = lsame_(uplo, "U"); info = 0; if (! upper && ! lsame_(uplo, "L")) { info = 1; } else if (! lsame_(trans, "N") && ! lsame_(trans, "C")) { info = 2; } else if (*n < 0) { info = 3; } else if (*k < 0) { info = 4; } else if (*lda < max(1,nrowa)) { info = 7; } else if (*ldb < max(1,nrowa)) { info = 9; } else if (*ldc < max(1,*n)) { info = 12; } if (info != 0) { xerbla_("CHER2K", &info); return 0; } /* Quick return if possible. */ if ((*n == 0) || (((alpha->r == 0.f && alpha->i == 0.f) || (*k == 0)) && * beta == 1.f)) { return 0; } /* And when alpha.eq.zero. */ if (alpha->r == 0.f && alpha->i == 0.f) { if (upper) { if (*beta == 0.f) { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = j; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * c_dim1; c__[i__3].r = 0.f, c__[i__3].i = 0.f; /* L10: */ } /* L20: */ } } else { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = j - 1; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * c_dim1; i__4 = i__ + j * c_dim1; q__1.r = *beta * c__[i__4].r, q__1.i = *beta * c__[ i__4].i; c__[i__3].r = q__1.r, c__[i__3].i = q__1.i; /* L30: */ } i__2 = j + j * c_dim1; i__3 = j + j * c_dim1; r__1 = *beta * c__[i__3].r; c__[i__2].r = r__1, c__[i__2].i = 0.f; /* L40: */ } } } else { if (*beta == 0.f) { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *n; for (i__ = j; i__ <= i__2; ++i__) { i__3 = i__ + j * c_dim1; c__[i__3].r = 0.f, c__[i__3].i = 0.f; /* L50: */ } /* L60: */ } } else { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = j + j * c_dim1; i__3 = j + j * c_dim1; r__1 = *beta * c__[i__3].r; c__[i__2].r = r__1, c__[i__2].i = 0.f; i__2 = *n; for (i__ = j + 1; i__ <= i__2; ++i__) { i__3 = i__ + j * c_dim1; i__4 = i__ + j * c_dim1; q__1.r = *beta * c__[i__4].r, q__1.i = *beta * c__[ i__4].i; c__[i__3].r = q__1.r, c__[i__3].i = q__1.i; /* L70: */ } /* L80: */ } } } return 0; } /* Start the operations. */ if (lsame_(trans, "N")) { /* Form C := alpha*A*conjg( B' ) + conjg( alpha )*B*conjg( A' ) + C. */ if (upper) { i__1 = *n; for (j = 1; j <= i__1; ++j) { if (*beta == 0.f) { i__2 = j; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * c_dim1; c__[i__3].r = 0.f, c__[i__3].i = 0.f; /* L90: */ } } else if (*beta != 1.f) { i__2 = j - 1; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * c_dim1; i__4 = i__ + j * c_dim1; q__1.r = *beta * c__[i__4].r, q__1.i = *beta * c__[ i__4].i; c__[i__3].r = q__1.r, c__[i__3].i = q__1.i; /* L100: */ } i__2 = j + j * c_dim1; i__3 = j + j * c_dim1; r__1 = *beta * c__[i__3].r; c__[i__2].r = r__1, c__[i__2].i = 0.f; } else { i__2 = j + j * c_dim1; i__3 = j + j * c_dim1; r__1 = c__[i__3].r; c__[i__2].r = r__1, c__[i__2].i = 0.f; } i__2 = *k; for (l = 1; l <= i__2; ++l) { i__3 = j + l * a_dim1; i__4 = j + l * b_dim1; if (((a[i__3].r != 0.f) || (a[i__3].i != 0.f)) || (((b[ i__4].r != 0.f) || (b[i__4].i != 0.f)))) { r_cnjg(&q__2, &b[j + l * b_dim1]); q__1.r = alpha->r * q__2.r - alpha->i * q__2.i, q__1.i = alpha->r * q__2.i + alpha->i * q__2.r; temp1.r = q__1.r, temp1.i = q__1.i; i__3 = j + l * a_dim1; q__2.r = alpha->r * a[i__3].r - alpha->i * a[i__3].i, q__2.i = alpha->r * a[i__3].i + alpha->i * a[ i__3].r; r_cnjg(&q__1, &q__2); temp2.r = q__1.r, temp2.i = q__1.i; i__3 = j - 1; for (i__ = 1; i__ <= i__3; ++i__) { i__4 = i__ + j * c_dim1; i__5 = i__ + j * c_dim1; i__6 = i__ + l * a_dim1; q__3.r = a[i__6].r * temp1.r - a[i__6].i * temp1.i, q__3.i = a[i__6].r * temp1.i + a[ i__6].i * temp1.r; q__2.r = c__[i__5].r + q__3.r, q__2.i = c__[i__5] .i + q__3.i; i__7 = i__ + l * b_dim1; q__4.r = b[i__7].r * temp2.r - b[i__7].i * temp2.i, q__4.i = b[i__7].r * temp2.i + b[ i__7].i * temp2.r; q__1.r = q__2.r + q__4.r, q__1.i = q__2.i + q__4.i; c__[i__4].r = q__1.r, c__[i__4].i = q__1.i; /* L110: */ } i__3 = j + j * c_dim1; i__4 = j + j * c_dim1; i__5 = j + l * a_dim1; q__2.r = a[i__5].r * temp1.r - a[i__5].i * temp1.i, q__2.i = a[i__5].r * temp1.i + a[i__5].i * temp1.r; i__6 = j + l * b_dim1; q__3.r = b[i__6].r * temp2.r - b[i__6].i * temp2.i, q__3.i = b[i__6].r * temp2.i + b[i__6].i * temp2.r; q__1.r = q__2.r + q__3.r, q__1.i = q__2.i + q__3.i; r__1 = c__[i__4].r + q__1.r; c__[i__3].r = r__1, c__[i__3].i = 0.f; } /* L120: */ } /* L130: */ } } else { i__1 = *n; for (j = 1; j <= i__1; ++j) { if (*beta == 0.f) { i__2 = *n; for (i__ = j; i__ <= i__2; ++i__) { i__3 = i__ + j * c_dim1; c__[i__3].r = 0.f, c__[i__3].i = 0.f; /* L140: */ } } else if (*beta != 1.f) { i__2 = *n; for (i__ = j + 1; i__ <= i__2; ++i__) { i__3 = i__ + j * c_dim1; i__4 = i__ + j * c_dim1; q__1.r = *beta * c__[i__4].r, q__1.i = *beta * c__[ i__4].i; c__[i__3].r = q__1.r, c__[i__3].i = q__1.i; /* L150: */ } i__2 = j + j * c_dim1; i__3 = j + j * c_dim1; r__1 = *beta * c__[i__3].r; c__[i__2].r = r__1, c__[i__2].i = 0.f; } else { i__2 = j + j * c_dim1; i__3 = j + j * c_dim1; r__1 = c__[i__3].r; c__[i__2].r = r__1, c__[i__2].i = 0.f; } i__2 = *k; for (l = 1; l <= i__2; ++l) { i__3 = j + l * a_dim1; i__4 = j + l * b_dim1; if (((a[i__3].r != 0.f) || (a[i__3].i != 0.f)) || (((b[ i__4].r != 0.f) || (b[i__4].i != 0.f)))) { r_cnjg(&q__2, &b[j + l * b_dim1]); q__1.r = alpha->r * q__2.r - alpha->i * q__2.i, q__1.i = alpha->r * q__2.i + alpha->i * q__2.r; temp1.r = q__1.r, temp1.i = q__1.i; i__3 = j + l * a_dim1; q__2.r = alpha->r * a[i__3].r - alpha->i * a[i__3].i, q__2.i = alpha->r * a[i__3].i + alpha->i * a[ i__3].r; r_cnjg(&q__1, &q__2); temp2.r = q__1.r, temp2.i = q__1.i; i__3 = *n; for (i__ = j + 1; i__ <= i__3; ++i__) { i__4 = i__ + j * c_dim1; i__5 = i__ + j * c_dim1; i__6 = i__ + l * a_dim1; q__3.r = a[i__6].r * temp1.r - a[i__6].i * temp1.i, q__3.i = a[i__6].r * temp1.i + a[ i__6].i * temp1.r; q__2.r = c__[i__5].r + q__3.r, q__2.i = c__[i__5] .i + q__3.i; i__7 = i__ + l * b_dim1; q__4.r = b[i__7].r * temp2.r - b[i__7].i * temp2.i, q__4.i = b[i__7].r * temp2.i + b[ i__7].i * temp2.r; q__1.r = q__2.r + q__4.r, q__1.i = q__2.i + q__4.i; c__[i__4].r = q__1.r, c__[i__4].i = q__1.i; /* L160: */ } i__3 = j + j * c_dim1; i__4 = j + j * c_dim1; i__5 = j + l * a_dim1; q__2.r = a[i__5].r * temp1.r - a[i__5].i * temp1.i, q__2.i = a[i__5].r * temp1.i + a[i__5].i * temp1.r; i__6 = j + l * b_dim1; q__3.r = b[i__6].r * temp2.r - b[i__6].i * temp2.i, q__3.i = b[i__6].r * temp2.i + b[i__6].i * temp2.r; q__1.r = q__2.r + q__3.r, q__1.i = q__2.i + q__3.i; r__1 = c__[i__4].r + q__1.r; c__[i__3].r = r__1, c__[i__3].i = 0.f; } /* L170: */ } /* L180: */ } } } else { /* Form C := alpha*conjg( A' )*B + conjg( alpha )*conjg( B' )*A + C. */ if (upper) { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = j; for (i__ = 1; i__ <= i__2; ++i__) { temp1.r = 0.f, temp1.i = 0.f; temp2.r = 0.f, temp2.i = 0.f; i__3 = *k; for (l = 1; l <= i__3; ++l) { r_cnjg(&q__3, &a[l + i__ * a_dim1]); i__4 = l + j * b_dim1; q__2.r = q__3.r * b[i__4].r - q__3.i * b[i__4].i, q__2.i = q__3.r * b[i__4].i + q__3.i * b[i__4] .r; q__1.r = temp1.r + q__2.r, q__1.i = temp1.i + q__2.i; temp1.r = q__1.r, temp1.i = q__1.i; r_cnjg(&q__3, &b[l + i__ * b_dim1]); i__4 = l + j * a_dim1; q__2.r = q__3.r * a[i__4].r - q__3.i * a[i__4].i, q__2.i = q__3.r * a[i__4].i + q__3.i * a[i__4] .r; q__1.r = temp2.r + q__2.r, q__1.i = temp2.i + q__2.i; temp2.r = q__1.r, temp2.i = q__1.i; /* L190: */ } if (i__ == j) { if (*beta == 0.f) { i__3 = j + j * c_dim1; q__2.r = alpha->r * temp1.r - alpha->i * temp1.i, q__2.i = alpha->r * temp1.i + alpha->i * temp1.r; r_cnjg(&q__4, alpha); q__3.r = q__4.r * temp2.r - q__4.i * temp2.i, q__3.i = q__4.r * temp2.i + q__4.i * temp2.r; q__1.r = q__2.r + q__3.r, q__1.i = q__2.i + q__3.i; r__1 = q__1.r; c__[i__3].r = r__1, c__[i__3].i = 0.f; } else { i__3 = j + j * c_dim1; i__4 = j + j * c_dim1; q__2.r = alpha->r * temp1.r - alpha->i * temp1.i, q__2.i = alpha->r * temp1.i + alpha->i * temp1.r; r_cnjg(&q__4, alpha); q__3.r = q__4.r * temp2.r - q__4.i * temp2.i, q__3.i = q__4.r * temp2.i + q__4.i * temp2.r; q__1.r = q__2.r + q__3.r, q__1.i = q__2.i + q__3.i; r__1 = *beta * c__[i__4].r + q__1.r; c__[i__3].r = r__1, c__[i__3].i = 0.f; } } else { if (*beta == 0.f) { i__3 = i__ + j * c_dim1; q__2.r = alpha->r * temp1.r - alpha->i * temp1.i, q__2.i = alpha->r * temp1.i + alpha->i * temp1.r; r_cnjg(&q__4, alpha); q__3.r = q__4.r * temp2.r - q__4.i * temp2.i, q__3.i = q__4.r * temp2.i + q__4.i * temp2.r; q__1.r = q__2.r + q__3.r, q__1.i = q__2.i + q__3.i; c__[i__3].r = q__1.r, c__[i__3].i = q__1.i; } else { i__3 = i__ + j * c_dim1; i__4 = i__ + j * c_dim1; q__3.r = *beta * c__[i__4].r, q__3.i = *beta * c__[i__4].i; q__4.r = alpha->r * temp1.r - alpha->i * temp1.i, q__4.i = alpha->r * temp1.i + alpha->i * temp1.r; q__2.r = q__3.r + q__4.r, q__2.i = q__3.i + q__4.i; r_cnjg(&q__6, alpha); q__5.r = q__6.r * temp2.r - q__6.i * temp2.i, q__5.i = q__6.r * temp2.i + q__6.i * temp2.r; q__1.r = q__2.r + q__5.r, q__1.i = q__2.i + q__5.i; c__[i__3].r = q__1.r, c__[i__3].i = q__1.i; } } /* L200: */ } /* L210: */ } } else { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *n; for (i__ = j; i__ <= i__2; ++i__) { temp1.r = 0.f, temp1.i = 0.f; temp2.r = 0.f, temp2.i = 0.f; i__3 = *k; for (l = 1; l <= i__3; ++l) { r_cnjg(&q__3, &a[l + i__ * a_dim1]); i__4 = l + j * b_dim1; q__2.r = q__3.r * b[i__4].r - q__3.i * b[i__4].i, q__2.i = q__3.r * b[i__4].i + q__3.i * b[i__4] .r; q__1.r = temp1.r + q__2.r, q__1.i = temp1.i + q__2.i; temp1.r = q__1.r, temp1.i = q__1.i; r_cnjg(&q__3, &b[l + i__ * b_dim1]); i__4 = l + j * a_dim1; q__2.r = q__3.r * a[i__4].r - q__3.i * a[i__4].i, q__2.i = q__3.r * a[i__4].i + q__3.i * a[i__4] .r; q__1.r = temp2.r + q__2.r, q__1.i = temp2.i + q__2.i; temp2.r = q__1.r, temp2.i = q__1.i; /* L220: */ } if (i__ == j) { if (*beta == 0.f) { i__3 = j + j * c_dim1; q__2.r = alpha->r * temp1.r - alpha->i * temp1.i, q__2.i = alpha->r * temp1.i + alpha->i * temp1.r; r_cnjg(&q__4, alpha); q__3.r = q__4.r * temp2.r - q__4.i * temp2.i, q__3.i = q__4.r * temp2.i + q__4.i * temp2.r; q__1.r = q__2.r + q__3.r, q__1.i = q__2.i + q__3.i; r__1 = q__1.r; c__[i__3].r = r__1, c__[i__3].i = 0.f; } else { i__3 = j + j * c_dim1; i__4 = j + j * c_dim1; q__2.r = alpha->r * temp1.r - alpha->i * temp1.i, q__2.i = alpha->r * temp1.i + alpha->i * temp1.r; r_cnjg(&q__4, alpha); q__3.r = q__4.r * temp2.r - q__4.i * temp2.i, q__3.i = q__4.r * temp2.i + q__4.i * temp2.r; q__1.r = q__2.r + q__3.r, q__1.i = q__2.i + q__3.i; r__1 = *beta * c__[i__4].r + q__1.r; c__[i__3].r = r__1, c__[i__3].i = 0.f; } } else { if (*beta == 0.f) { i__3 = i__ + j * c_dim1; q__2.r = alpha->r * temp1.r - alpha->i * temp1.i, q__2.i = alpha->r * temp1.i + alpha->i * temp1.r; r_cnjg(&q__4, alpha); q__3.r = q__4.r * temp2.r - q__4.i * temp2.i, q__3.i = q__4.r * temp2.i + q__4.i * temp2.r; q__1.r = q__2.r + q__3.r, q__1.i = q__2.i + q__3.i; c__[i__3].r = q__1.r, c__[i__3].i = q__1.i; } else { i__3 = i__ + j * c_dim1; i__4 = i__ + j * c_dim1; q__3.r = *beta * c__[i__4].r, q__3.i = *beta * c__[i__4].i; q__4.r = alpha->r * temp1.r - alpha->i * temp1.i, q__4.i = alpha->r * temp1.i + alpha->i * temp1.r; q__2.r = q__3.r + q__4.r, q__2.i = q__3.i + q__4.i; r_cnjg(&q__6, alpha); q__5.r = q__6.r * temp2.r - q__6.i * temp2.i, q__5.i = q__6.r * temp2.i + q__6.i * temp2.r; q__1.r = q__2.r + q__5.r, q__1.i = q__2.i + q__5.i; c__[i__3].r = q__1.r, c__[i__3].i = q__1.i; } } /* L230: */ } /* L240: */ } } } return 0; /* End of CHER2K. */ } /* cher2k_ */ /* Subroutine */ int cherk_(char *uplo, char *trans, integer *n, integer *k, real *alpha, complex *a, integer *lda, real *beta, complex *c__, integer *ldc) { /* System generated locals */ integer a_dim1, a_offset, c_dim1, c_offset, i__1, i__2, i__3, i__4, i__5, i__6; real r__1; complex q__1, q__2, q__3; /* Builtin functions */ void r_cnjg(complex *, complex *); /* Local variables */ static integer i__, j, l, info; static complex temp; extern logical lsame_(char *, char *); static integer nrowa; static real rtemp; static logical upper; extern /* Subroutine */ int xerbla_(char *, integer *); /* Purpose ======= CHERK performs one of the hermitian rank k operations C := alpha*A*conjg( A' ) + beta*C, or C := alpha*conjg( A' )*A + beta*C, where alpha and beta are real scalars, C is an n by n hermitian matrix and A is an n by k matrix in the first case and a k by n matrix in the second case. Parameters ========== UPLO - CHARACTER*1. On entry, UPLO specifies whether the upper or lower triangular part of the array C is to be referenced as follows: UPLO = 'U' or 'u' Only the upper triangular part of C is to be referenced. UPLO = 'L' or 'l' Only the lower triangular part of C is to be referenced. Unchanged on exit. TRANS - CHARACTER*1. On entry, TRANS specifies the operation to be performed as follows: TRANS = 'N' or 'n' C := alpha*A*conjg( A' ) + beta*C. TRANS = 'C' or 'c' C := alpha*conjg( A' )*A + beta*C. Unchanged on exit. N - INTEGER. On entry, N specifies the order of the matrix C. N must be at least zero. Unchanged on exit. K - INTEGER. On entry with TRANS = 'N' or 'n', K specifies the number of columns of the matrix A, and on entry with TRANS = 'C' or 'c', K specifies the number of rows of the matrix A. K must be at least zero. Unchanged on exit. ALPHA - REAL . On entry, ALPHA specifies the scalar alpha. Unchanged on exit. A - COMPLEX array of DIMENSION ( LDA, ka ), where ka is k when TRANS = 'N' or 'n', and is n otherwise. Before entry with TRANS = 'N' or 'n', the leading n by k part of the array A must contain the matrix A, otherwise the leading k by n part of the array A must contain the matrix A. Unchanged on exit. LDA - INTEGER. On entry, LDA specifies the first dimension of A as declared in the calling (sub) program. When TRANS = 'N' or 'n' then LDA must be at least max( 1, n ), otherwise LDA must be at least max( 1, k ). Unchanged on exit. BETA - REAL . On entry, BETA specifies the scalar beta. Unchanged on exit. C - COMPLEX array of DIMENSION ( LDC, n ). Before entry with UPLO = 'U' or 'u', the leading n by n upper triangular part of the array C must contain the upper triangular part of the hermitian matrix and the strictly lower triangular part of C is not referenced. On exit, the upper triangular part of the array C is overwritten by the upper triangular part of the updated matrix. Before entry with UPLO = 'L' or 'l', the leading n by n lower triangular part of the array C must contain the lower triangular part of the hermitian matrix and the strictly upper triangular part of C is not referenced. On exit, the lower triangular part of the array C is overwritten by the lower triangular part of the updated matrix. Note that the imaginary parts of the diagonal elements need not be set, they are assumed to be zero, and on exit they are set to zero. LDC - INTEGER. On entry, LDC specifies the first dimension of C as declared in the calling (sub) program. LDC must be at least max( 1, n ). Unchanged on exit. Level 3 Blas routine. -- Written on 8-February-1989. Jack Dongarra, Argonne National Laboratory. Iain Duff, AERE Harwell. Jeremy Du Croz, Numerical Algorithms Group Ltd. Sven Hammarling, Numerical Algorithms Group Ltd. -- Modified 8-Nov-93 to set C(J,J) to REAL( C(J,J) ) when BETA = 1. Ed Anderson, Cray Research Inc. Test the input parameters. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; c_dim1 = *ldc; c_offset = 1 + c_dim1; c__ -= c_offset; /* Function Body */ if (lsame_(trans, "N")) { nrowa = *n; } else { nrowa = *k; } upper = lsame_(uplo, "U"); info = 0; if (! upper && ! lsame_(uplo, "L")) { info = 1; } else if (! lsame_(trans, "N") && ! lsame_(trans, "C")) { info = 2; } else if (*n < 0) { info = 3; } else if (*k < 0) { info = 4; } else if (*lda < max(1,nrowa)) { info = 7; } else if (*ldc < max(1,*n)) { info = 10; } if (info != 0) { xerbla_("CHERK ", &info); return 0; } /* Quick return if possible. */ if ((*n == 0) || (((*alpha == 0.f) || (*k == 0)) && *beta == 1.f)) { return 0; } /* And when alpha.eq.zero. */ if (*alpha == 0.f) { if (upper) { if (*beta == 0.f) { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = j; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * c_dim1; c__[i__3].r = 0.f, c__[i__3].i = 0.f; /* L10: */ } /* L20: */ } } else { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = j - 1; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * c_dim1; i__4 = i__ + j * c_dim1; q__1.r = *beta * c__[i__4].r, q__1.i = *beta * c__[ i__4].i; c__[i__3].r = q__1.r, c__[i__3].i = q__1.i; /* L30: */ } i__2 = j + j * c_dim1; i__3 = j + j * c_dim1; r__1 = *beta * c__[i__3].r; c__[i__2].r = r__1, c__[i__2].i = 0.f; /* L40: */ } } } else { if (*beta == 0.f) { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *n; for (i__ = j; i__ <= i__2; ++i__) { i__3 = i__ + j * c_dim1; c__[i__3].r = 0.f, c__[i__3].i = 0.f; /* L50: */ } /* L60: */ } } else { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = j + j * c_dim1; i__3 = j + j * c_dim1; r__1 = *beta * c__[i__3].r; c__[i__2].r = r__1, c__[i__2].i = 0.f; i__2 = *n; for (i__ = j + 1; i__ <= i__2; ++i__) { i__3 = i__ + j * c_dim1; i__4 = i__ + j * c_dim1; q__1.r = *beta * c__[i__4].r, q__1.i = *beta * c__[ i__4].i; c__[i__3].r = q__1.r, c__[i__3].i = q__1.i; /* L70: */ } /* L80: */ } } } return 0; } /* Start the operations. */ if (lsame_(trans, "N")) { /* Form C := alpha*A*conjg( A' ) + beta*C. */ if (upper) { i__1 = *n; for (j = 1; j <= i__1; ++j) { if (*beta == 0.f) { i__2 = j; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * c_dim1; c__[i__3].r = 0.f, c__[i__3].i = 0.f; /* L90: */ } } else if (*beta != 1.f) { i__2 = j - 1; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * c_dim1; i__4 = i__ + j * c_dim1; q__1.r = *beta * c__[i__4].r, q__1.i = *beta * c__[ i__4].i; c__[i__3].r = q__1.r, c__[i__3].i = q__1.i; /* L100: */ } i__2 = j + j * c_dim1; i__3 = j + j * c_dim1; r__1 = *beta * c__[i__3].r; c__[i__2].r = r__1, c__[i__2].i = 0.f; } else { i__2 = j + j * c_dim1; i__3 = j + j * c_dim1; r__1 = c__[i__3].r; c__[i__2].r = r__1, c__[i__2].i = 0.f; } i__2 = *k; for (l = 1; l <= i__2; ++l) { i__3 = j + l * a_dim1; if ((a[i__3].r != 0.f) || (a[i__3].i != 0.f)) { r_cnjg(&q__2, &a[j + l * a_dim1]); q__1.r = *alpha * q__2.r, q__1.i = *alpha * q__2.i; temp.r = q__1.r, temp.i = q__1.i; i__3 = j - 1; for (i__ = 1; i__ <= i__3; ++i__) { i__4 = i__ + j * c_dim1; i__5 = i__ + j * c_dim1; i__6 = i__ + l * a_dim1; q__2.r = temp.r * a[i__6].r - temp.i * a[i__6].i, q__2.i = temp.r * a[i__6].i + temp.i * a[ i__6].r; q__1.r = c__[i__5].r + q__2.r, q__1.i = c__[i__5] .i + q__2.i; c__[i__4].r = q__1.r, c__[i__4].i = q__1.i; /* L110: */ } i__3 = j + j * c_dim1; i__4 = j + j * c_dim1; i__5 = i__ + l * a_dim1; q__1.r = temp.r * a[i__5].r - temp.i * a[i__5].i, q__1.i = temp.r * a[i__5].i + temp.i * a[i__5] .r; r__1 = c__[i__4].r + q__1.r; c__[i__3].r = r__1, c__[i__3].i = 0.f; } /* L120: */ } /* L130: */ } } else { i__1 = *n; for (j = 1; j <= i__1; ++j) { if (*beta == 0.f) { i__2 = *n; for (i__ = j; i__ <= i__2; ++i__) { i__3 = i__ + j * c_dim1; c__[i__3].r = 0.f, c__[i__3].i = 0.f; /* L140: */ } } else if (*beta != 1.f) { i__2 = j + j * c_dim1; i__3 = j + j * c_dim1; r__1 = *beta * c__[i__3].r; c__[i__2].r = r__1, c__[i__2].i = 0.f; i__2 = *n; for (i__ = j + 1; i__ <= i__2; ++i__) { i__3 = i__ + j * c_dim1; i__4 = i__ + j * c_dim1; q__1.r = *beta * c__[i__4].r, q__1.i = *beta * c__[ i__4].i; c__[i__3].r = q__1.r, c__[i__3].i = q__1.i; /* L150: */ } } else { i__2 = j + j * c_dim1; i__3 = j + j * c_dim1; r__1 = c__[i__3].r; c__[i__2].r = r__1, c__[i__2].i = 0.f; } i__2 = *k; for (l = 1; l <= i__2; ++l) { i__3 = j + l * a_dim1; if ((a[i__3].r != 0.f) || (a[i__3].i != 0.f)) { r_cnjg(&q__2, &a[j + l * a_dim1]); q__1.r = *alpha * q__2.r, q__1.i = *alpha * q__2.i; temp.r = q__1.r, temp.i = q__1.i; i__3 = j + j * c_dim1; i__4 = j + j * c_dim1; i__5 = j + l * a_dim1; q__1.r = temp.r * a[i__5].r - temp.i * a[i__5].i, q__1.i = temp.r * a[i__5].i + temp.i * a[i__5] .r; r__1 = c__[i__4].r + q__1.r; c__[i__3].r = r__1, c__[i__3].i = 0.f; i__3 = *n; for (i__ = j + 1; i__ <= i__3; ++i__) { i__4 = i__ + j * c_dim1; i__5 = i__ + j * c_dim1; i__6 = i__ + l * a_dim1; q__2.r = temp.r * a[i__6].r - temp.i * a[i__6].i, q__2.i = temp.r * a[i__6].i + temp.i * a[ i__6].r; q__1.r = c__[i__5].r + q__2.r, q__1.i = c__[i__5] .i + q__2.i; c__[i__4].r = q__1.r, c__[i__4].i = q__1.i; /* L160: */ } } /* L170: */ } /* L180: */ } } } else { /* Form C := alpha*conjg( A' )*A + beta*C. */ if (upper) { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = j - 1; for (i__ = 1; i__ <= i__2; ++i__) { temp.r = 0.f, temp.i = 0.f; i__3 = *k; for (l = 1; l <= i__3; ++l) { r_cnjg(&q__3, &a[l + i__ * a_dim1]); i__4 = l + j * a_dim1; q__2.r = q__3.r * a[i__4].r - q__3.i * a[i__4].i, q__2.i = q__3.r * a[i__4].i + q__3.i * a[i__4] .r; q__1.r = temp.r + q__2.r, q__1.i = temp.i + q__2.i; temp.r = q__1.r, temp.i = q__1.i; /* L190: */ } if (*beta == 0.f) { i__3 = i__ + j * c_dim1; q__1.r = *alpha * temp.r, q__1.i = *alpha * temp.i; c__[i__3].r = q__1.r, c__[i__3].i = q__1.i; } else { i__3 = i__ + j * c_dim1; q__2.r = *alpha * temp.r, q__2.i = *alpha * temp.i; i__4 = i__ + j * c_dim1; q__3.r = *beta * c__[i__4].r, q__3.i = *beta * c__[ i__4].i; q__1.r = q__2.r + q__3.r, q__1.i = q__2.i + q__3.i; c__[i__3].r = q__1.r, c__[i__3].i = q__1.i; } /* L200: */ } rtemp = 0.f; i__2 = *k; for (l = 1; l <= i__2; ++l) { r_cnjg(&q__3, &a[l + j * a_dim1]); i__3 = l + j * a_dim1; q__2.r = q__3.r * a[i__3].r - q__3.i * a[i__3].i, q__2.i = q__3.r * a[i__3].i + q__3.i * a[i__3].r; q__1.r = rtemp + q__2.r, q__1.i = q__2.i; rtemp = q__1.r; /* L210: */ } if (*beta == 0.f) { i__2 = j + j * c_dim1; r__1 = *alpha * rtemp; c__[i__2].r = r__1, c__[i__2].i = 0.f; } else { i__2 = j + j * c_dim1; i__3 = j + j * c_dim1; r__1 = *alpha * rtemp + *beta * c__[i__3].r; c__[i__2].r = r__1, c__[i__2].i = 0.f; } /* L220: */ } } else { i__1 = *n; for (j = 1; j <= i__1; ++j) { rtemp = 0.f; i__2 = *k; for (l = 1; l <= i__2; ++l) { r_cnjg(&q__3, &a[l + j * a_dim1]); i__3 = l + j * a_dim1; q__2.r = q__3.r * a[i__3].r - q__3.i * a[i__3].i, q__2.i = q__3.r * a[i__3].i + q__3.i * a[i__3].r; q__1.r = rtemp + q__2.r, q__1.i = q__2.i; rtemp = q__1.r; /* L230: */ } if (*beta == 0.f) { i__2 = j + j * c_dim1; r__1 = *alpha * rtemp; c__[i__2].r = r__1, c__[i__2].i = 0.f; } else { i__2 = j + j * c_dim1; i__3 = j + j * c_dim1; r__1 = *alpha * rtemp + *beta * c__[i__3].r; c__[i__2].r = r__1, c__[i__2].i = 0.f; } i__2 = *n; for (i__ = j + 1; i__ <= i__2; ++i__) { temp.r = 0.f, temp.i = 0.f; i__3 = *k; for (l = 1; l <= i__3; ++l) { r_cnjg(&q__3, &a[l + i__ * a_dim1]); i__4 = l + j * a_dim1; q__2.r = q__3.r * a[i__4].r - q__3.i * a[i__4].i, q__2.i = q__3.r * a[i__4].i + q__3.i * a[i__4] .r; q__1.r = temp.r + q__2.r, q__1.i = temp.i + q__2.i; temp.r = q__1.r, temp.i = q__1.i; /* L240: */ } if (*beta == 0.f) { i__3 = i__ + j * c_dim1; q__1.r = *alpha * temp.r, q__1.i = *alpha * temp.i; c__[i__3].r = q__1.r, c__[i__3].i = q__1.i; } else { i__3 = i__ + j * c_dim1; q__2.r = *alpha * temp.r, q__2.i = *alpha * temp.i; i__4 = i__ + j * c_dim1; q__3.r = *beta * c__[i__4].r, q__3.i = *beta * c__[ i__4].i; q__1.r = q__2.r + q__3.r, q__1.i = q__2.i + q__3.i; c__[i__3].r = q__1.r, c__[i__3].i = q__1.i; } /* L250: */ } /* L260: */ } } } return 0; /* End of CHERK . */ } /* cherk_ */ /* Subroutine */ int cscal_(integer *n, complex *ca, complex *cx, integer * incx) { /* System generated locals */ integer i__1, i__2, i__3, i__4; complex q__1; /* Local variables */ static integer i__, nincx; /* scales a vector by a constant. jack dongarra, linpack, 3/11/78. modified 3/93 to return if incx .le. 0. modified 12/3/93, array(1) declarations changed to array(*) */ /* Parameter adjustments */ --cx; /* Function Body */ if ((*n <= 0) || (*incx <= 0)) { return 0; } if (*incx == 1) { goto L20; } /* code for increment not equal to 1 */ nincx = *n * *incx; i__1 = nincx; i__2 = *incx; for (i__ = 1; i__2 < 0 ? i__ >= i__1 : i__ <= i__1; i__ += i__2) { i__3 = i__; i__4 = i__; q__1.r = ca->r * cx[i__4].r - ca->i * cx[i__4].i, q__1.i = ca->r * cx[ i__4].i + ca->i * cx[i__4].r; cx[i__3].r = q__1.r, cx[i__3].i = q__1.i; /* L10: */ } return 0; /* code for increment equal to 1 */ L20: i__2 = *n; for (i__ = 1; i__ <= i__2; ++i__) { i__1 = i__; i__3 = i__; q__1.r = ca->r * cx[i__3].r - ca->i * cx[i__3].i, q__1.i = ca->r * cx[ i__3].i + ca->i * cx[i__3].r; cx[i__1].r = q__1.r, cx[i__1].i = q__1.i; /* L30: */ } return 0; } /* cscal_ */ /* Subroutine */ int csscal_(integer *n, real *sa, complex *cx, integer *incx) { /* System generated locals */ integer i__1, i__2, i__3, i__4; real r__1, r__2; complex q__1; /* Builtin functions */ double r_imag(complex *); /* Local variables */ static integer i__, nincx; /* scales a complex vector by a real constant. jack dongarra, linpack, 3/11/78. modified 3/93 to return if incx .le. 0. modified 12/3/93, array(1) declarations changed to array(*) */ /* Parameter adjustments */ --cx; /* Function Body */ if ((*n <= 0) || (*incx <= 0)) { return 0; } if (*incx == 1) { goto L20; } /* code for increment not equal to 1 */ nincx = *n * *incx; i__1 = nincx; i__2 = *incx; for (i__ = 1; i__2 < 0 ? i__ >= i__1 : i__ <= i__1; i__ += i__2) { i__3 = i__; i__4 = i__; r__1 = *sa * cx[i__4].r; r__2 = *sa * r_imag(&cx[i__]); q__1.r = r__1, q__1.i = r__2; cx[i__3].r = q__1.r, cx[i__3].i = q__1.i; /* L10: */ } return 0; /* code for increment equal to 1 */ L20: i__2 = *n; for (i__ = 1; i__ <= i__2; ++i__) { i__1 = i__; i__3 = i__; r__1 = *sa * cx[i__3].r; r__2 = *sa * r_imag(&cx[i__]); q__1.r = r__1, q__1.i = r__2; cx[i__1].r = q__1.r, cx[i__1].i = q__1.i; /* L30: */ } return 0; } /* csscal_ */ /* Subroutine */ int cswap_(integer *n, complex *cx, integer *incx, complex * cy, integer *incy) { /* System generated locals */ integer i__1, i__2, i__3; /* Local variables */ static integer i__, ix, iy; static complex ctemp; /* interchanges two vectors. jack dongarra, linpack, 3/11/78. modified 12/3/93, array(1) declarations changed to array(*) */ /* Parameter adjustments */ --cy; --cx; /* Function Body */ if (*n <= 0) { return 0; } if (*incx == 1 && *incy == 1) { goto L20; } /* code for unequal increments or equal increments not equal to 1 */ ix = 1; iy = 1; if (*incx < 0) { ix = (-(*n) + 1) * *incx + 1; } if (*incy < 0) { iy = (-(*n) + 1) * *incy + 1; } i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = ix; ctemp.r = cx[i__2].r, ctemp.i = cx[i__2].i; i__2 = ix; i__3 = iy; cx[i__2].r = cy[i__3].r, cx[i__2].i = cy[i__3].i; i__2 = iy; cy[i__2].r = ctemp.r, cy[i__2].i = ctemp.i; ix += *incx; iy += *incy; /* L10: */ } return 0; /* code for both increments equal to 1 */ L20: i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = i__; ctemp.r = cx[i__2].r, ctemp.i = cx[i__2].i; i__2 = i__; i__3 = i__; cx[i__2].r = cy[i__3].r, cx[i__2].i = cy[i__3].i; i__2 = i__; cy[i__2].r = ctemp.r, cy[i__2].i = ctemp.i; /* L30: */ } return 0; } /* cswap_ */ /* Subroutine */ int ctrmm_(char *side, char *uplo, char *transa, char *diag, integer *m, integer *n, complex *alpha, complex *a, integer *lda, complex *b, integer *ldb) { /* System generated locals */ integer a_dim1, a_offset, b_dim1, b_offset, i__1, i__2, i__3, i__4, i__5, i__6; complex q__1, q__2, q__3; /* Builtin functions */ void r_cnjg(complex *, complex *); /* Local variables */ static integer i__, j, k, info; static complex temp; extern logical lsame_(char *, char *); static logical lside; static integer nrowa; static logical upper; extern /* Subroutine */ int xerbla_(char *, integer *); static logical noconj, nounit; /* Purpose ======= CTRMM performs one of the matrix-matrix operations B := alpha*op( A )*B, or B := alpha*B*op( A ) where alpha is a scalar, B is an m by n matrix, A is a unit, or non-unit, upper or lower triangular matrix and op( A ) is one of op( A ) = A or op( A ) = A' or op( A ) = conjg( A' ). Parameters ========== SIDE - CHARACTER*1. On entry, SIDE specifies whether op( A ) multiplies B from the left or right as follows: SIDE = 'L' or 'l' B := alpha*op( A )*B. SIDE = 'R' or 'r' B := alpha*B*op( A ). Unchanged on exit. UPLO - CHARACTER*1. On entry, UPLO specifies whether the matrix A is an upper or lower triangular matrix as follows: UPLO = 'U' or 'u' A is an upper triangular matrix. UPLO = 'L' or 'l' A is a lower triangular matrix. Unchanged on exit. TRANSA - CHARACTER*1. On entry, TRANSA specifies the form of op( A ) to be used in the matrix multiplication as follows: TRANSA = 'N' or 'n' op( A ) = A. TRANSA = 'T' or 't' op( A ) = A'. TRANSA = 'C' or 'c' op( A ) = conjg( A' ). Unchanged on exit. DIAG - CHARACTER*1. On entry, DIAG specifies whether or not A is unit triangular as follows: DIAG = 'U' or 'u' A is assumed to be unit triangular. DIAG = 'N' or 'n' A is not assumed to be unit triangular. Unchanged on exit. M - INTEGER. On entry, M specifies the number of rows of B. M must be at least zero. Unchanged on exit. N - INTEGER. On entry, N specifies the number of columns of B. N must be at least zero. Unchanged on exit. ALPHA - COMPLEX . On entry, ALPHA specifies the scalar alpha. When alpha is zero then A is not referenced and B need not be set before entry. Unchanged on exit. A - COMPLEX array of DIMENSION ( LDA, k ), where k is m when SIDE = 'L' or 'l' and is n when SIDE = 'R' or 'r'. Before entry with UPLO = 'U' or 'u', the leading k by k upper triangular part of the array A must contain the upper triangular matrix and the strictly lower triangular part of A is not referenced. Before entry with UPLO = 'L' or 'l', the leading k by k lower triangular part of the array A must contain the lower triangular matrix and the strictly upper triangular part of A is not referenced. Note that when DIAG = 'U' or 'u', the diagonal elements of A are not referenced either, but are assumed to be unity. Unchanged on exit. LDA - INTEGER. On entry, LDA specifies the first dimension of A as declared in the calling (sub) program. When SIDE = 'L' or 'l' then LDA must be at least max( 1, m ), when SIDE = 'R' or 'r' then LDA must be at least max( 1, n ). Unchanged on exit. B - COMPLEX array of DIMENSION ( LDB, n ). Before entry, the leading m by n part of the array B must contain the matrix B, and on exit is overwritten by the transformed matrix. LDB - INTEGER. On entry, LDB specifies the first dimension of B as declared in the calling (sub) program. LDB must be at least max( 1, m ). Unchanged on exit. Level 3 Blas routine. -- Written on 8-February-1989. Jack Dongarra, Argonne National Laboratory. Iain Duff, AERE Harwell. Jeremy Du Croz, Numerical Algorithms Group Ltd. Sven Hammarling, Numerical Algorithms Group Ltd. Test the input parameters. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; b_dim1 = *ldb; b_offset = 1 + b_dim1; b -= b_offset; /* Function Body */ lside = lsame_(side, "L"); if (lside) { nrowa = *m; } else { nrowa = *n; } noconj = lsame_(transa, "T"); nounit = lsame_(diag, "N"); upper = lsame_(uplo, "U"); info = 0; if (! lside && ! lsame_(side, "R")) { info = 1; } else if (! upper && ! lsame_(uplo, "L")) { info = 2; } else if (! lsame_(transa, "N") && ! lsame_(transa, "T") && ! lsame_(transa, "C")) { info = 3; } else if (! lsame_(diag, "U") && ! lsame_(diag, "N")) { info = 4; } else if (*m < 0) { info = 5; } else if (*n < 0) { info = 6; } else if (*lda < max(1,nrowa)) { info = 9; } else if (*ldb < max(1,*m)) { info = 11; } if (info != 0) { xerbla_("CTRMM ", &info); return 0; } /* Quick return if possible. */ if (*n == 0) { return 0; } /* And when alpha.eq.zero. */ if (alpha->r == 0.f && alpha->i == 0.f) { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * b_dim1; b[i__3].r = 0.f, b[i__3].i = 0.f; /* L10: */ } /* L20: */ } return 0; } /* Start the operations. */ if (lside) { if (lsame_(transa, "N")) { /* Form B := alpha*A*B. */ if (upper) { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (k = 1; k <= i__2; ++k) { i__3 = k + j * b_dim1; if ((b[i__3].r != 0.f) || (b[i__3].i != 0.f)) { i__3 = k + j * b_dim1; q__1.r = alpha->r * b[i__3].r - alpha->i * b[i__3] .i, q__1.i = alpha->r * b[i__3].i + alpha->i * b[i__3].r; temp.r = q__1.r, temp.i = q__1.i; i__3 = k - 1; for (i__ = 1; i__ <= i__3; ++i__) { i__4 = i__ + j * b_dim1; i__5 = i__ + j * b_dim1; i__6 = i__ + k * a_dim1; q__2.r = temp.r * a[i__6].r - temp.i * a[i__6] .i, q__2.i = temp.r * a[i__6].i + temp.i * a[i__6].r; q__1.r = b[i__5].r + q__2.r, q__1.i = b[i__5] .i + q__2.i; b[i__4].r = q__1.r, b[i__4].i = q__1.i; /* L30: */ } if (nounit) { i__3 = k + k * a_dim1; q__1.r = temp.r * a[i__3].r - temp.i * a[i__3] .i, q__1.i = temp.r * a[i__3].i + temp.i * a[i__3].r; temp.r = q__1.r, temp.i = q__1.i; } i__3 = k + j * b_dim1; b[i__3].r = temp.r, b[i__3].i = temp.i; } /* L40: */ } /* L50: */ } } else { i__1 = *n; for (j = 1; j <= i__1; ++j) { for (k = *m; k >= 1; --k) { i__2 = k + j * b_dim1; if ((b[i__2].r != 0.f) || (b[i__2].i != 0.f)) { i__2 = k + j * b_dim1; q__1.r = alpha->r * b[i__2].r - alpha->i * b[i__2] .i, q__1.i = alpha->r * b[i__2].i + alpha->i * b[i__2].r; temp.r = q__1.r, temp.i = q__1.i; i__2 = k + j * b_dim1; b[i__2].r = temp.r, b[i__2].i = temp.i; if (nounit) { i__2 = k + j * b_dim1; i__3 = k + j * b_dim1; i__4 = k + k * a_dim1; q__1.r = b[i__3].r * a[i__4].r - b[i__3].i * a[i__4].i, q__1.i = b[i__3].r * a[ i__4].i + b[i__3].i * a[i__4].r; b[i__2].r = q__1.r, b[i__2].i = q__1.i; } i__2 = *m; for (i__ = k + 1; i__ <= i__2; ++i__) { i__3 = i__ + j * b_dim1; i__4 = i__ + j * b_dim1; i__5 = i__ + k * a_dim1; q__2.r = temp.r * a[i__5].r - temp.i * a[i__5] .i, q__2.i = temp.r * a[i__5].i + temp.i * a[i__5].r; q__1.r = b[i__4].r + q__2.r, q__1.i = b[i__4] .i + q__2.i; b[i__3].r = q__1.r, b[i__3].i = q__1.i; /* L60: */ } } /* L70: */ } /* L80: */ } } } else { /* Form B := alpha*A'*B or B := alpha*conjg( A' )*B. */ if (upper) { i__1 = *n; for (j = 1; j <= i__1; ++j) { for (i__ = *m; i__ >= 1; --i__) { i__2 = i__ + j * b_dim1; temp.r = b[i__2].r, temp.i = b[i__2].i; if (noconj) { if (nounit) { i__2 = i__ + i__ * a_dim1; q__1.r = temp.r * a[i__2].r - temp.i * a[i__2] .i, q__1.i = temp.r * a[i__2].i + temp.i * a[i__2].r; temp.r = q__1.r, temp.i = q__1.i; } i__2 = i__ - 1; for (k = 1; k <= i__2; ++k) { i__3 = k + i__ * a_dim1; i__4 = k + j * b_dim1; q__2.r = a[i__3].r * b[i__4].r - a[i__3].i * b[i__4].i, q__2.i = a[i__3].r * b[ i__4].i + a[i__3].i * b[i__4].r; q__1.r = temp.r + q__2.r, q__1.i = temp.i + q__2.i; temp.r = q__1.r, temp.i = q__1.i; /* L90: */ } } else { if (nounit) { r_cnjg(&q__2, &a[i__ + i__ * a_dim1]); q__1.r = temp.r * q__2.r - temp.i * q__2.i, q__1.i = temp.r * q__2.i + temp.i * q__2.r; temp.r = q__1.r, temp.i = q__1.i; } i__2 = i__ - 1; for (k = 1; k <= i__2; ++k) { r_cnjg(&q__3, &a[k + i__ * a_dim1]); i__3 = k + j * b_dim1; q__2.r = q__3.r * b[i__3].r - q__3.i * b[i__3] .i, q__2.i = q__3.r * b[i__3].i + q__3.i * b[i__3].r; q__1.r = temp.r + q__2.r, q__1.i = temp.i + q__2.i; temp.r = q__1.r, temp.i = q__1.i; /* L100: */ } } i__2 = i__ + j * b_dim1; q__1.r = alpha->r * temp.r - alpha->i * temp.i, q__1.i = alpha->r * temp.i + alpha->i * temp.r; b[i__2].r = q__1.r, b[i__2].i = q__1.i; /* L110: */ } /* L120: */ } } else { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * b_dim1; temp.r = b[i__3].r, temp.i = b[i__3].i; if (noconj) { if (nounit) { i__3 = i__ + i__ * a_dim1; q__1.r = temp.r * a[i__3].r - temp.i * a[i__3] .i, q__1.i = temp.r * a[i__3].i + temp.i * a[i__3].r; temp.r = q__1.r, temp.i = q__1.i; } i__3 = *m; for (k = i__ + 1; k <= i__3; ++k) { i__4 = k + i__ * a_dim1; i__5 = k + j * b_dim1; q__2.r = a[i__4].r * b[i__5].r - a[i__4].i * b[i__5].i, q__2.i = a[i__4].r * b[ i__5].i + a[i__4].i * b[i__5].r; q__1.r = temp.r + q__2.r, q__1.i = temp.i + q__2.i; temp.r = q__1.r, temp.i = q__1.i; /* L130: */ } } else { if (nounit) { r_cnjg(&q__2, &a[i__ + i__ * a_dim1]); q__1.r = temp.r * q__2.r - temp.i * q__2.i, q__1.i = temp.r * q__2.i + temp.i * q__2.r; temp.r = q__1.r, temp.i = q__1.i; } i__3 = *m; for (k = i__ + 1; k <= i__3; ++k) { r_cnjg(&q__3, &a[k + i__ * a_dim1]); i__4 = k + j * b_dim1; q__2.r = q__3.r * b[i__4].r - q__3.i * b[i__4] .i, q__2.i = q__3.r * b[i__4].i + q__3.i * b[i__4].r; q__1.r = temp.r + q__2.r, q__1.i = temp.i + q__2.i; temp.r = q__1.r, temp.i = q__1.i; /* L140: */ } } i__3 = i__ + j * b_dim1; q__1.r = alpha->r * temp.r - alpha->i * temp.i, q__1.i = alpha->r * temp.i + alpha->i * temp.r; b[i__3].r = q__1.r, b[i__3].i = q__1.i; /* L150: */ } /* L160: */ } } } } else { if (lsame_(transa, "N")) { /* Form B := alpha*B*A. */ if (upper) { for (j = *n; j >= 1; --j) { temp.r = alpha->r, temp.i = alpha->i; if (nounit) { i__1 = j + j * a_dim1; q__1.r = temp.r * a[i__1].r - temp.i * a[i__1].i, q__1.i = temp.r * a[i__1].i + temp.i * a[i__1] .r; temp.r = q__1.r, temp.i = q__1.i; } i__1 = *m; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = i__ + j * b_dim1; i__3 = i__ + j * b_dim1; q__1.r = temp.r * b[i__3].r - temp.i * b[i__3].i, q__1.i = temp.r * b[i__3].i + temp.i * b[i__3] .r; b[i__2].r = q__1.r, b[i__2].i = q__1.i; /* L170: */ } i__1 = j - 1; for (k = 1; k <= i__1; ++k) { i__2 = k + j * a_dim1; if ((a[i__2].r != 0.f) || (a[i__2].i != 0.f)) { i__2 = k + j * a_dim1; q__1.r = alpha->r * a[i__2].r - alpha->i * a[i__2] .i, q__1.i = alpha->r * a[i__2].i + alpha->i * a[i__2].r; temp.r = q__1.r, temp.i = q__1.i; i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * b_dim1; i__4 = i__ + j * b_dim1; i__5 = i__ + k * b_dim1; q__2.r = temp.r * b[i__5].r - temp.i * b[i__5] .i, q__2.i = temp.r * b[i__5].i + temp.i * b[i__5].r; q__1.r = b[i__4].r + q__2.r, q__1.i = b[i__4] .i + q__2.i; b[i__3].r = q__1.r, b[i__3].i = q__1.i; /* L180: */ } } /* L190: */ } /* L200: */ } } else { i__1 = *n; for (j = 1; j <= i__1; ++j) { temp.r = alpha->r, temp.i = alpha->i; if (nounit) { i__2 = j + j * a_dim1; q__1.r = temp.r * a[i__2].r - temp.i * a[i__2].i, q__1.i = temp.r * a[i__2].i + temp.i * a[i__2] .r; temp.r = q__1.r, temp.i = q__1.i; } i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * b_dim1; i__4 = i__ + j * b_dim1; q__1.r = temp.r * b[i__4].r - temp.i * b[i__4].i, q__1.i = temp.r * b[i__4].i + temp.i * b[i__4] .r; b[i__3].r = q__1.r, b[i__3].i = q__1.i; /* L210: */ } i__2 = *n; for (k = j + 1; k <= i__2; ++k) { i__3 = k + j * a_dim1; if ((a[i__3].r != 0.f) || (a[i__3].i != 0.f)) { i__3 = k + j * a_dim1; q__1.r = alpha->r * a[i__3].r - alpha->i * a[i__3] .i, q__1.i = alpha->r * a[i__3].i + alpha->i * a[i__3].r; temp.r = q__1.r, temp.i = q__1.i; i__3 = *m; for (i__ = 1; i__ <= i__3; ++i__) { i__4 = i__ + j * b_dim1; i__5 = i__ + j * b_dim1; i__6 = i__ + k * b_dim1; q__2.r = temp.r * b[i__6].r - temp.i * b[i__6] .i, q__2.i = temp.r * b[i__6].i + temp.i * b[i__6].r; q__1.r = b[i__5].r + q__2.r, q__1.i = b[i__5] .i + q__2.i; b[i__4].r = q__1.r, b[i__4].i = q__1.i; /* L220: */ } } /* L230: */ } /* L240: */ } } } else { /* Form B := alpha*B*A' or B := alpha*B*conjg( A' ). */ if (upper) { i__1 = *n; for (k = 1; k <= i__1; ++k) { i__2 = k - 1; for (j = 1; j <= i__2; ++j) { i__3 = j + k * a_dim1; if ((a[i__3].r != 0.f) || (a[i__3].i != 0.f)) { if (noconj) { i__3 = j + k * a_dim1; q__1.r = alpha->r * a[i__3].r - alpha->i * a[ i__3].i, q__1.i = alpha->r * a[i__3] .i + alpha->i * a[i__3].r; temp.r = q__1.r, temp.i = q__1.i; } else { r_cnjg(&q__2, &a[j + k * a_dim1]); q__1.r = alpha->r * q__2.r - alpha->i * q__2.i, q__1.i = alpha->r * q__2.i + alpha->i * q__2.r; temp.r = q__1.r, temp.i = q__1.i; } i__3 = *m; for (i__ = 1; i__ <= i__3; ++i__) { i__4 = i__ + j * b_dim1; i__5 = i__ + j * b_dim1; i__6 = i__ + k * b_dim1; q__2.r = temp.r * b[i__6].r - temp.i * b[i__6] .i, q__2.i = temp.r * b[i__6].i + temp.i * b[i__6].r; q__1.r = b[i__5].r + q__2.r, q__1.i = b[i__5] .i + q__2.i; b[i__4].r = q__1.r, b[i__4].i = q__1.i; /* L250: */ } } /* L260: */ } temp.r = alpha->r, temp.i = alpha->i; if (nounit) { if (noconj) { i__2 = k + k * a_dim1; q__1.r = temp.r * a[i__2].r - temp.i * a[i__2].i, q__1.i = temp.r * a[i__2].i + temp.i * a[ i__2].r; temp.r = q__1.r, temp.i = q__1.i; } else { r_cnjg(&q__2, &a[k + k * a_dim1]); q__1.r = temp.r * q__2.r - temp.i * q__2.i, q__1.i = temp.r * q__2.i + temp.i * q__2.r; temp.r = q__1.r, temp.i = q__1.i; } } if ((temp.r != 1.f) || (temp.i != 0.f)) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + k * b_dim1; i__4 = i__ + k * b_dim1; q__1.r = temp.r * b[i__4].r - temp.i * b[i__4].i, q__1.i = temp.r * b[i__4].i + temp.i * b[ i__4].r; b[i__3].r = q__1.r, b[i__3].i = q__1.i; /* L270: */ } } /* L280: */ } } else { for (k = *n; k >= 1; --k) { i__1 = *n; for (j = k + 1; j <= i__1; ++j) { i__2 = j + k * a_dim1; if ((a[i__2].r != 0.f) || (a[i__2].i != 0.f)) { if (noconj) { i__2 = j + k * a_dim1; q__1.r = alpha->r * a[i__2].r - alpha->i * a[ i__2].i, q__1.i = alpha->r * a[i__2] .i + alpha->i * a[i__2].r; temp.r = q__1.r, temp.i = q__1.i; } else { r_cnjg(&q__2, &a[j + k * a_dim1]); q__1.r = alpha->r * q__2.r - alpha->i * q__2.i, q__1.i = alpha->r * q__2.i + alpha->i * q__2.r; temp.r = q__1.r, temp.i = q__1.i; } i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * b_dim1; i__4 = i__ + j * b_dim1; i__5 = i__ + k * b_dim1; q__2.r = temp.r * b[i__5].r - temp.i * b[i__5] .i, q__2.i = temp.r * b[i__5].i + temp.i * b[i__5].r; q__1.r = b[i__4].r + q__2.r, q__1.i = b[i__4] .i + q__2.i; b[i__3].r = q__1.r, b[i__3].i = q__1.i; /* L290: */ } } /* L300: */ } temp.r = alpha->r, temp.i = alpha->i; if (nounit) { if (noconj) { i__1 = k + k * a_dim1; q__1.r = temp.r * a[i__1].r - temp.i * a[i__1].i, q__1.i = temp.r * a[i__1].i + temp.i * a[ i__1].r; temp.r = q__1.r, temp.i = q__1.i; } else { r_cnjg(&q__2, &a[k + k * a_dim1]); q__1.r = temp.r * q__2.r - temp.i * q__2.i, q__1.i = temp.r * q__2.i + temp.i * q__2.r; temp.r = q__1.r, temp.i = q__1.i; } } if ((temp.r != 1.f) || (temp.i != 0.f)) { i__1 = *m; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = i__ + k * b_dim1; i__3 = i__ + k * b_dim1; q__1.r = temp.r * b[i__3].r - temp.i * b[i__3].i, q__1.i = temp.r * b[i__3].i + temp.i * b[ i__3].r; b[i__2].r = q__1.r, b[i__2].i = q__1.i; /* L310: */ } } /* L320: */ } } } } return 0; /* End of CTRMM . */ } /* ctrmm_ */ /* Subroutine */ int ctrmv_(char *uplo, char *trans, char *diag, integer *n, complex *a, integer *lda, complex *x, integer *incx) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3, i__4, i__5; complex q__1, q__2, q__3; /* Builtin functions */ void r_cnjg(complex *, complex *); /* Local variables */ static integer i__, j, ix, jx, kx, info; static complex temp; extern logical lsame_(char *, char *); extern /* Subroutine */ int xerbla_(char *, integer *); static logical noconj, nounit; /* Purpose ======= CTRMV performs one of the matrix-vector operations x := A*x, or x := A'*x, or x := conjg( A' )*x, where x is an n element vector and A is an n by n unit, or non-unit, upper or lower triangular matrix. Parameters ========== UPLO - CHARACTER*1. On entry, UPLO specifies whether the matrix is an upper or lower triangular matrix as follows: UPLO = 'U' or 'u' A is an upper triangular matrix. UPLO = 'L' or 'l' A is a lower triangular matrix. Unchanged on exit. TRANS - CHARACTER*1. On entry, TRANS specifies the operation to be performed as follows: TRANS = 'N' or 'n' x := A*x. TRANS = 'T' or 't' x := A'*x. TRANS = 'C' or 'c' x := conjg( A' )*x. Unchanged on exit. DIAG - CHARACTER*1. On entry, DIAG specifies whether or not A is unit triangular as follows: DIAG = 'U' or 'u' A is assumed to be unit triangular. DIAG = 'N' or 'n' A is not assumed to be unit triangular. Unchanged on exit. N - INTEGER. On entry, N specifies the order of the matrix A. N must be at least zero. Unchanged on exit. A - COMPLEX array of DIMENSION ( LDA, n ). Before entry with UPLO = 'U' or 'u', the leading n by n upper triangular part of the array A must contain the upper triangular matrix and the strictly lower triangular part of A is not referenced. Before entry with UPLO = 'L' or 'l', the leading n by n lower triangular part of the array A must contain the lower triangular matrix and the strictly upper triangular part of A is not referenced. Note that when DIAG = 'U' or 'u', the diagonal elements of A are not referenced either, but are assumed to be unity. Unchanged on exit. LDA - INTEGER. On entry, LDA specifies the first dimension of A as declared in the calling (sub) program. LDA must be at least max( 1, n ). Unchanged on exit. X - COMPLEX array of dimension at least ( 1 + ( n - 1 )*abs( INCX ) ). Before entry, the incremented array X must contain the n element vector x. On exit, X is overwritten with the tranformed vector x. INCX - INTEGER. On entry, INCX specifies the increment for the elements of X. INCX must not be zero. Unchanged on exit. Level 2 Blas routine. -- Written on 22-October-1986. Jack Dongarra, Argonne National Lab. Jeremy Du Croz, Nag Central Office. Sven Hammarling, Nag Central Office. Richard Hanson, Sandia National Labs. Test the input parameters. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --x; /* Function Body */ info = 0; if (! lsame_(uplo, "U") && ! lsame_(uplo, "L")) { info = 1; } else if (! lsame_(trans, "N") && ! lsame_(trans, "T") && ! lsame_(trans, "C")) { info = 2; } else if (! lsame_(diag, "U") && ! lsame_(diag, "N")) { info = 3; } else if (*n < 0) { info = 4; } else if (*lda < max(1,*n)) { info = 6; } else if (*incx == 0) { info = 8; } if (info != 0) { xerbla_("CTRMV ", &info); return 0; } /* Quick return if possible. */ if (*n == 0) { return 0; } noconj = lsame_(trans, "T"); nounit = lsame_(diag, "N"); /* Set up the start point in X if the increment is not unity. This will be ( N - 1 )*INCX too small for descending loops. */ if (*incx <= 0) { kx = 1 - (*n - 1) * *incx; } else if (*incx != 1) { kx = 1; } /* Start the operations. In this version the elements of A are accessed sequentially with one pass through A. */ if (lsame_(trans, "N")) { /* Form x := A*x. */ if (lsame_(uplo, "U")) { if (*incx == 1) { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = j; if ((x[i__2].r != 0.f) || (x[i__2].i != 0.f)) { i__2 = j; temp.r = x[i__2].r, temp.i = x[i__2].i; i__2 = j - 1; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__; i__4 = i__; i__5 = i__ + j * a_dim1; q__2.r = temp.r * a[i__5].r - temp.i * a[i__5].i, q__2.i = temp.r * a[i__5].i + temp.i * a[ i__5].r; q__1.r = x[i__4].r + q__2.r, q__1.i = x[i__4].i + q__2.i; x[i__3].r = q__1.r, x[i__3].i = q__1.i; /* L10: */ } if (nounit) { i__2 = j; i__3 = j; i__4 = j + j * a_dim1; q__1.r = x[i__3].r * a[i__4].r - x[i__3].i * a[ i__4].i, q__1.i = x[i__3].r * a[i__4].i + x[i__3].i * a[i__4].r; x[i__2].r = q__1.r, x[i__2].i = q__1.i; } } /* L20: */ } } else { jx = kx; i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = jx; if ((x[i__2].r != 0.f) || (x[i__2].i != 0.f)) { i__2 = jx; temp.r = x[i__2].r, temp.i = x[i__2].i; ix = kx; i__2 = j - 1; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = ix; i__4 = ix; i__5 = i__ + j * a_dim1; q__2.r = temp.r * a[i__5].r - temp.i * a[i__5].i, q__2.i = temp.r * a[i__5].i + temp.i * a[ i__5].r; q__1.r = x[i__4].r + q__2.r, q__1.i = x[i__4].i + q__2.i; x[i__3].r = q__1.r, x[i__3].i = q__1.i; ix += *incx; /* L30: */ } if (nounit) { i__2 = jx; i__3 = jx; i__4 = j + j * a_dim1; q__1.r = x[i__3].r * a[i__4].r - x[i__3].i * a[ i__4].i, q__1.i = x[i__3].r * a[i__4].i + x[i__3].i * a[i__4].r; x[i__2].r = q__1.r, x[i__2].i = q__1.i; } } jx += *incx; /* L40: */ } } } else { if (*incx == 1) { for (j = *n; j >= 1; --j) { i__1 = j; if ((x[i__1].r != 0.f) || (x[i__1].i != 0.f)) { i__1 = j; temp.r = x[i__1].r, temp.i = x[i__1].i; i__1 = j + 1; for (i__ = *n; i__ >= i__1; --i__) { i__2 = i__; i__3 = i__; i__4 = i__ + j * a_dim1; q__2.r = temp.r * a[i__4].r - temp.i * a[i__4].i, q__2.i = temp.r * a[i__4].i + temp.i * a[ i__4].r; q__1.r = x[i__3].r + q__2.r, q__1.i = x[i__3].i + q__2.i; x[i__2].r = q__1.r, x[i__2].i = q__1.i; /* L50: */ } if (nounit) { i__1 = j; i__2 = j; i__3 = j + j * a_dim1; q__1.r = x[i__2].r * a[i__3].r - x[i__2].i * a[ i__3].i, q__1.i = x[i__2].r * a[i__3].i + x[i__2].i * a[i__3].r; x[i__1].r = q__1.r, x[i__1].i = q__1.i; } } /* L60: */ } } else { kx += (*n - 1) * *incx; jx = kx; for (j = *n; j >= 1; --j) { i__1 = jx; if ((x[i__1].r != 0.f) || (x[i__1].i != 0.f)) { i__1 = jx; temp.r = x[i__1].r, temp.i = x[i__1].i; ix = kx; i__1 = j + 1; for (i__ = *n; i__ >= i__1; --i__) { i__2 = ix; i__3 = ix; i__4 = i__ + j * a_dim1; q__2.r = temp.r * a[i__4].r - temp.i * a[i__4].i, q__2.i = temp.r * a[i__4].i + temp.i * a[ i__4].r; q__1.r = x[i__3].r + q__2.r, q__1.i = x[i__3].i + q__2.i; x[i__2].r = q__1.r, x[i__2].i = q__1.i; ix -= *incx; /* L70: */ } if (nounit) { i__1 = jx; i__2 = jx; i__3 = j + j * a_dim1; q__1.r = x[i__2].r * a[i__3].r - x[i__2].i * a[ i__3].i, q__1.i = x[i__2].r * a[i__3].i + x[i__2].i * a[i__3].r; x[i__1].r = q__1.r, x[i__1].i = q__1.i; } } jx -= *incx; /* L80: */ } } } } else { /* Form x := A'*x or x := conjg( A' )*x. */ if (lsame_(uplo, "U")) { if (*incx == 1) { for (j = *n; j >= 1; --j) { i__1 = j; temp.r = x[i__1].r, temp.i = x[i__1].i; if (noconj) { if (nounit) { i__1 = j + j * a_dim1; q__1.r = temp.r * a[i__1].r - temp.i * a[i__1].i, q__1.i = temp.r * a[i__1].i + temp.i * a[ i__1].r; temp.r = q__1.r, temp.i = q__1.i; } for (i__ = j - 1; i__ >= 1; --i__) { i__1 = i__ + j * a_dim1; i__2 = i__; q__2.r = a[i__1].r * x[i__2].r - a[i__1].i * x[ i__2].i, q__2.i = a[i__1].r * x[i__2].i + a[i__1].i * x[i__2].r; q__1.r = temp.r + q__2.r, q__1.i = temp.i + q__2.i; temp.r = q__1.r, temp.i = q__1.i; /* L90: */ } } else { if (nounit) { r_cnjg(&q__2, &a[j + j * a_dim1]); q__1.r = temp.r * q__2.r - temp.i * q__2.i, q__1.i = temp.r * q__2.i + temp.i * q__2.r; temp.r = q__1.r, temp.i = q__1.i; } for (i__ = j - 1; i__ >= 1; --i__) { r_cnjg(&q__3, &a[i__ + j * a_dim1]); i__1 = i__; q__2.r = q__3.r * x[i__1].r - q__3.i * x[i__1].i, q__2.i = q__3.r * x[i__1].i + q__3.i * x[ i__1].r; q__1.r = temp.r + q__2.r, q__1.i = temp.i + q__2.i; temp.r = q__1.r, temp.i = q__1.i; /* L100: */ } } i__1 = j; x[i__1].r = temp.r, x[i__1].i = temp.i; /* L110: */ } } else { jx = kx + (*n - 1) * *incx; for (j = *n; j >= 1; --j) { i__1 = jx; temp.r = x[i__1].r, temp.i = x[i__1].i; ix = jx; if (noconj) { if (nounit) { i__1 = j + j * a_dim1; q__1.r = temp.r * a[i__1].r - temp.i * a[i__1].i, q__1.i = temp.r * a[i__1].i + temp.i * a[ i__1].r; temp.r = q__1.r, temp.i = q__1.i; } for (i__ = j - 1; i__ >= 1; --i__) { ix -= *incx; i__1 = i__ + j * a_dim1; i__2 = ix; q__2.r = a[i__1].r * x[i__2].r - a[i__1].i * x[ i__2].i, q__2.i = a[i__1].r * x[i__2].i + a[i__1].i * x[i__2].r; q__1.r = temp.r + q__2.r, q__1.i = temp.i + q__2.i; temp.r = q__1.r, temp.i = q__1.i; /* L120: */ } } else { if (nounit) { r_cnjg(&q__2, &a[j + j * a_dim1]); q__1.r = temp.r * q__2.r - temp.i * q__2.i, q__1.i = temp.r * q__2.i + temp.i * q__2.r; temp.r = q__1.r, temp.i = q__1.i; } for (i__ = j - 1; i__ >= 1; --i__) { ix -= *incx; r_cnjg(&q__3, &a[i__ + j * a_dim1]); i__1 = ix; q__2.r = q__3.r * x[i__1].r - q__3.i * x[i__1].i, q__2.i = q__3.r * x[i__1].i + q__3.i * x[ i__1].r; q__1.r = temp.r + q__2.r, q__1.i = temp.i + q__2.i; temp.r = q__1.r, temp.i = q__1.i; /* L130: */ } } i__1 = jx; x[i__1].r = temp.r, x[i__1].i = temp.i; jx -= *incx; /* L140: */ } } } else { if (*incx == 1) { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = j; temp.r = x[i__2].r, temp.i = x[i__2].i; if (noconj) { if (nounit) { i__2 = j + j * a_dim1; q__1.r = temp.r * a[i__2].r - temp.i * a[i__2].i, q__1.i = temp.r * a[i__2].i + temp.i * a[ i__2].r; temp.r = q__1.r, temp.i = q__1.i; } i__2 = *n; for (i__ = j + 1; i__ <= i__2; ++i__) { i__3 = i__ + j * a_dim1; i__4 = i__; q__2.r = a[i__3].r * x[i__4].r - a[i__3].i * x[ i__4].i, q__2.i = a[i__3].r * x[i__4].i + a[i__3].i * x[i__4].r; q__1.r = temp.r + q__2.r, q__1.i = temp.i + q__2.i; temp.r = q__1.r, temp.i = q__1.i; /* L150: */ } } else { if (nounit) { r_cnjg(&q__2, &a[j + j * a_dim1]); q__1.r = temp.r * q__2.r - temp.i * q__2.i, q__1.i = temp.r * q__2.i + temp.i * q__2.r; temp.r = q__1.r, temp.i = q__1.i; } i__2 = *n; for (i__ = j + 1; i__ <= i__2; ++i__) { r_cnjg(&q__3, &a[i__ + j * a_dim1]); i__3 = i__; q__2.r = q__3.r * x[i__3].r - q__3.i * x[i__3].i, q__2.i = q__3.r * x[i__3].i + q__3.i * x[ i__3].r; q__1.r = temp.r + q__2.r, q__1.i = temp.i + q__2.i; temp.r = q__1.r, temp.i = q__1.i; /* L160: */ } } i__2 = j; x[i__2].r = temp.r, x[i__2].i = temp.i; /* L170: */ } } else { jx = kx; i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = jx; temp.r = x[i__2].r, temp.i = x[i__2].i; ix = jx; if (noconj) { if (nounit) { i__2 = j + j * a_dim1; q__1.r = temp.r * a[i__2].r - temp.i * a[i__2].i, q__1.i = temp.r * a[i__2].i + temp.i * a[ i__2].r; temp.r = q__1.r, temp.i = q__1.i; } i__2 = *n; for (i__ = j + 1; i__ <= i__2; ++i__) { ix += *incx; i__3 = i__ + j * a_dim1; i__4 = ix; q__2.r = a[i__3].r * x[i__4].r - a[i__3].i * x[ i__4].i, q__2.i = a[i__3].r * x[i__4].i + a[i__3].i * x[i__4].r; q__1.r = temp.r + q__2.r, q__1.i = temp.i + q__2.i; temp.r = q__1.r, temp.i = q__1.i; /* L180: */ } } else { if (nounit) { r_cnjg(&q__2, &a[j + j * a_dim1]); q__1.r = temp.r * q__2.r - temp.i * q__2.i, q__1.i = temp.r * q__2.i + temp.i * q__2.r; temp.r = q__1.r, temp.i = q__1.i; } i__2 = *n; for (i__ = j + 1; i__ <= i__2; ++i__) { ix += *incx; r_cnjg(&q__3, &a[i__ + j * a_dim1]); i__3 = ix; q__2.r = q__3.r * x[i__3].r - q__3.i * x[i__3].i, q__2.i = q__3.r * x[i__3].i + q__3.i * x[ i__3].r; q__1.r = temp.r + q__2.r, q__1.i = temp.i + q__2.i; temp.r = q__1.r, temp.i = q__1.i; /* L190: */ } } i__2 = jx; x[i__2].r = temp.r, x[i__2].i = temp.i; jx += *incx; /* L200: */ } } } } return 0; /* End of CTRMV . */ } /* ctrmv_ */ /* Subroutine */ int ctrsm_(char *side, char *uplo, char *transa, char *diag, integer *m, integer *n, complex *alpha, complex *a, integer *lda, complex *b, integer *ldb) { /* System generated locals */ integer a_dim1, a_offset, b_dim1, b_offset, i__1, i__2, i__3, i__4, i__5, i__6, i__7; complex q__1, q__2, q__3; /* Builtin functions */ void c_div(complex *, complex *, complex *), r_cnjg(complex *, complex *); /* Local variables */ static integer i__, j, k, info; static complex temp; extern logical lsame_(char *, char *); static logical lside; static integer nrowa; static logical upper; extern /* Subroutine */ int xerbla_(char *, integer *); static logical noconj, nounit; /* Purpose ======= CTRSM solves one of the matrix equations op( A )*X = alpha*B, or X*op( A ) = alpha*B, where alpha is a scalar, X and B are m by n matrices, A is a unit, or non-unit, upper or lower triangular matrix and op( A ) is one of op( A ) = A or op( A ) = A' or op( A ) = conjg( A' ). The matrix X is overwritten on B. Parameters ========== SIDE - CHARACTER*1. On entry, SIDE specifies whether op( A ) appears on the left or right of X as follows: SIDE = 'L' or 'l' op( A )*X = alpha*B. SIDE = 'R' or 'r' X*op( A ) = alpha*B. Unchanged on exit. UPLO - CHARACTER*1. On entry, UPLO specifies whether the matrix A is an upper or lower triangular matrix as follows: UPLO = 'U' or 'u' A is an upper triangular matrix. UPLO = 'L' or 'l' A is a lower triangular matrix. Unchanged on exit. TRANSA - CHARACTER*1. On entry, TRANSA specifies the form of op( A ) to be used in the matrix multiplication as follows: TRANSA = 'N' or 'n' op( A ) = A. TRANSA = 'T' or 't' op( A ) = A'. TRANSA = 'C' or 'c' op( A ) = conjg( A' ). Unchanged on exit. DIAG - CHARACTER*1. On entry, DIAG specifies whether or not A is unit triangular as follows: DIAG = 'U' or 'u' A is assumed to be unit triangular. DIAG = 'N' or 'n' A is not assumed to be unit triangular. Unchanged on exit. M - INTEGER. On entry, M specifies the number of rows of B. M must be at least zero. Unchanged on exit. N - INTEGER. On entry, N specifies the number of columns of B. N must be at least zero. Unchanged on exit. ALPHA - COMPLEX . On entry, ALPHA specifies the scalar alpha. When alpha is zero then A is not referenced and B need not be set before entry. Unchanged on exit. A - COMPLEX array of DIMENSION ( LDA, k ), where k is m when SIDE = 'L' or 'l' and is n when SIDE = 'R' or 'r'. Before entry with UPLO = 'U' or 'u', the leading k by k upper triangular part of the array A must contain the upper triangular matrix and the strictly lower triangular part of A is not referenced. Before entry with UPLO = 'L' or 'l', the leading k by k lower triangular part of the array A must contain the lower triangular matrix and the strictly upper triangular part of A is not referenced. Note that when DIAG = 'U' or 'u', the diagonal elements of A are not referenced either, but are assumed to be unity. Unchanged on exit. LDA - INTEGER. On entry, LDA specifies the first dimension of A as declared in the calling (sub) program. When SIDE = 'L' or 'l' then LDA must be at least max( 1, m ), when SIDE = 'R' or 'r' then LDA must be at least max( 1, n ). Unchanged on exit. B - COMPLEX array of DIMENSION ( LDB, n ). Before entry, the leading m by n part of the array B must contain the right-hand side matrix B, and on exit is overwritten by the solution matrix X. LDB - INTEGER. On entry, LDB specifies the first dimension of B as declared in the calling (sub) program. LDB must be at least max( 1, m ). Unchanged on exit. Level 3 Blas routine. -- Written on 8-February-1989. Jack Dongarra, Argonne National Laboratory. Iain Duff, AERE Harwell. Jeremy Du Croz, Numerical Algorithms Group Ltd. Sven Hammarling, Numerical Algorithms Group Ltd. Test the input parameters. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; b_dim1 = *ldb; b_offset = 1 + b_dim1; b -= b_offset; /* Function Body */ lside = lsame_(side, "L"); if (lside) { nrowa = *m; } else { nrowa = *n; } noconj = lsame_(transa, "T"); nounit = lsame_(diag, "N"); upper = lsame_(uplo, "U"); info = 0; if (! lside && ! lsame_(side, "R")) { info = 1; } else if (! upper && ! lsame_(uplo, "L")) { info = 2; } else if (! lsame_(transa, "N") && ! lsame_(transa, "T") && ! lsame_(transa, "C")) { info = 3; } else if (! lsame_(diag, "U") && ! lsame_(diag, "N")) { info = 4; } else if (*m < 0) { info = 5; } else if (*n < 0) { info = 6; } else if (*lda < max(1,nrowa)) { info = 9; } else if (*ldb < max(1,*m)) { info = 11; } if (info != 0) { xerbla_("CTRSM ", &info); return 0; } /* Quick return if possible. */ if (*n == 0) { return 0; } /* And when alpha.eq.zero. */ if (alpha->r == 0.f && alpha->i == 0.f) { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * b_dim1; b[i__3].r = 0.f, b[i__3].i = 0.f; /* L10: */ } /* L20: */ } return 0; } /* Start the operations. */ if (lside) { if (lsame_(transa, "N")) { /* Form B := alpha*inv( A )*B. */ if (upper) { i__1 = *n; for (j = 1; j <= i__1; ++j) { if ((alpha->r != 1.f) || (alpha->i != 0.f)) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * b_dim1; i__4 = i__ + j * b_dim1; q__1.r = alpha->r * b[i__4].r - alpha->i * b[i__4] .i, q__1.i = alpha->r * b[i__4].i + alpha->i * b[i__4].r; b[i__3].r = q__1.r, b[i__3].i = q__1.i; /* L30: */ } } for (k = *m; k >= 1; --k) { i__2 = k + j * b_dim1; if ((b[i__2].r != 0.f) || (b[i__2].i != 0.f)) { if (nounit) { i__2 = k + j * b_dim1; c_div(&q__1, &b[k + j * b_dim1], &a[k + k * a_dim1]); b[i__2].r = q__1.r, b[i__2].i = q__1.i; } i__2 = k - 1; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * b_dim1; i__4 = i__ + j * b_dim1; i__5 = k + j * b_dim1; i__6 = i__ + k * a_dim1; q__2.r = b[i__5].r * a[i__6].r - b[i__5].i * a[i__6].i, q__2.i = b[i__5].r * a[ i__6].i + b[i__5].i * a[i__6].r; q__1.r = b[i__4].r - q__2.r, q__1.i = b[i__4] .i - q__2.i; b[i__3].r = q__1.r, b[i__3].i = q__1.i; /* L40: */ } } /* L50: */ } /* L60: */ } } else { i__1 = *n; for (j = 1; j <= i__1; ++j) { if ((alpha->r != 1.f) || (alpha->i != 0.f)) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * b_dim1; i__4 = i__ + j * b_dim1; q__1.r = alpha->r * b[i__4].r - alpha->i * b[i__4] .i, q__1.i = alpha->r * b[i__4].i + alpha->i * b[i__4].r; b[i__3].r = q__1.r, b[i__3].i = q__1.i; /* L70: */ } } i__2 = *m; for (k = 1; k <= i__2; ++k) { i__3 = k + j * b_dim1; if ((b[i__3].r != 0.f) || (b[i__3].i != 0.f)) { if (nounit) { i__3 = k + j * b_dim1; c_div(&q__1, &b[k + j * b_dim1], &a[k + k * a_dim1]); b[i__3].r = q__1.r, b[i__3].i = q__1.i; } i__3 = *m; for (i__ = k + 1; i__ <= i__3; ++i__) { i__4 = i__ + j * b_dim1; i__5 = i__ + j * b_dim1; i__6 = k + j * b_dim1; i__7 = i__ + k * a_dim1; q__2.r = b[i__6].r * a[i__7].r - b[i__6].i * a[i__7].i, q__2.i = b[i__6].r * a[ i__7].i + b[i__6].i * a[i__7].r; q__1.r = b[i__5].r - q__2.r, q__1.i = b[i__5] .i - q__2.i; b[i__4].r = q__1.r, b[i__4].i = q__1.i; /* L80: */ } } /* L90: */ } /* L100: */ } } } else { /* Form B := alpha*inv( A' )*B or B := alpha*inv( conjg( A' ) )*B. */ if (upper) { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * b_dim1; q__1.r = alpha->r * b[i__3].r - alpha->i * b[i__3].i, q__1.i = alpha->r * b[i__3].i + alpha->i * b[ i__3].r; temp.r = q__1.r, temp.i = q__1.i; if (noconj) { i__3 = i__ - 1; for (k = 1; k <= i__3; ++k) { i__4 = k + i__ * a_dim1; i__5 = k + j * b_dim1; q__2.r = a[i__4].r * b[i__5].r - a[i__4].i * b[i__5].i, q__2.i = a[i__4].r * b[ i__5].i + a[i__4].i * b[i__5].r; q__1.r = temp.r - q__2.r, q__1.i = temp.i - q__2.i; temp.r = q__1.r, temp.i = q__1.i; /* L110: */ } if (nounit) { c_div(&q__1, &temp, &a[i__ + i__ * a_dim1]); temp.r = q__1.r, temp.i = q__1.i; } } else { i__3 = i__ - 1; for (k = 1; k <= i__3; ++k) { r_cnjg(&q__3, &a[k + i__ * a_dim1]); i__4 = k + j * b_dim1; q__2.r = q__3.r * b[i__4].r - q__3.i * b[i__4] .i, q__2.i = q__3.r * b[i__4].i + q__3.i * b[i__4].r; q__1.r = temp.r - q__2.r, q__1.i = temp.i - q__2.i; temp.r = q__1.r, temp.i = q__1.i; /* L120: */ } if (nounit) { r_cnjg(&q__2, &a[i__ + i__ * a_dim1]); c_div(&q__1, &temp, &q__2); temp.r = q__1.r, temp.i = q__1.i; } } i__3 = i__ + j * b_dim1; b[i__3].r = temp.r, b[i__3].i = temp.i; /* L130: */ } /* L140: */ } } else { i__1 = *n; for (j = 1; j <= i__1; ++j) { for (i__ = *m; i__ >= 1; --i__) { i__2 = i__ + j * b_dim1; q__1.r = alpha->r * b[i__2].r - alpha->i * b[i__2].i, q__1.i = alpha->r * b[i__2].i + alpha->i * b[ i__2].r; temp.r = q__1.r, temp.i = q__1.i; if (noconj) { i__2 = *m; for (k = i__ + 1; k <= i__2; ++k) { i__3 = k + i__ * a_dim1; i__4 = k + j * b_dim1; q__2.r = a[i__3].r * b[i__4].r - a[i__3].i * b[i__4].i, q__2.i = a[i__3].r * b[ i__4].i + a[i__3].i * b[i__4].r; q__1.r = temp.r - q__2.r, q__1.i = temp.i - q__2.i; temp.r = q__1.r, temp.i = q__1.i; /* L150: */ } if (nounit) { c_div(&q__1, &temp, &a[i__ + i__ * a_dim1]); temp.r = q__1.r, temp.i = q__1.i; } } else { i__2 = *m; for (k = i__ + 1; k <= i__2; ++k) { r_cnjg(&q__3, &a[k + i__ * a_dim1]); i__3 = k + j * b_dim1; q__2.r = q__3.r * b[i__3].r - q__3.i * b[i__3] .i, q__2.i = q__3.r * b[i__3].i + q__3.i * b[i__3].r; q__1.r = temp.r - q__2.r, q__1.i = temp.i - q__2.i; temp.r = q__1.r, temp.i = q__1.i; /* L160: */ } if (nounit) { r_cnjg(&q__2, &a[i__ + i__ * a_dim1]); c_div(&q__1, &temp, &q__2); temp.r = q__1.r, temp.i = q__1.i; } } i__2 = i__ + j * b_dim1; b[i__2].r = temp.r, b[i__2].i = temp.i; /* L170: */ } /* L180: */ } } } } else { if (lsame_(transa, "N")) { /* Form B := alpha*B*inv( A ). */ if (upper) { i__1 = *n; for (j = 1; j <= i__1; ++j) { if ((alpha->r != 1.f) || (alpha->i != 0.f)) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * b_dim1; i__4 = i__ + j * b_dim1; q__1.r = alpha->r * b[i__4].r - alpha->i * b[i__4] .i, q__1.i = alpha->r * b[i__4].i + alpha->i * b[i__4].r; b[i__3].r = q__1.r, b[i__3].i = q__1.i; /* L190: */ } } i__2 = j - 1; for (k = 1; k <= i__2; ++k) { i__3 = k + j * a_dim1; if ((a[i__3].r != 0.f) || (a[i__3].i != 0.f)) { i__3 = *m; for (i__ = 1; i__ <= i__3; ++i__) { i__4 = i__ + j * b_dim1; i__5 = i__ + j * b_dim1; i__6 = k + j * a_dim1; i__7 = i__ + k * b_dim1; q__2.r = a[i__6].r * b[i__7].r - a[i__6].i * b[i__7].i, q__2.i = a[i__6].r * b[ i__7].i + a[i__6].i * b[i__7].r; q__1.r = b[i__5].r - q__2.r, q__1.i = b[i__5] .i - q__2.i; b[i__4].r = q__1.r, b[i__4].i = q__1.i; /* L200: */ } } /* L210: */ } if (nounit) { c_div(&q__1, &c_b21, &a[j + j * a_dim1]); temp.r = q__1.r, temp.i = q__1.i; i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * b_dim1; i__4 = i__ + j * b_dim1; q__1.r = temp.r * b[i__4].r - temp.i * b[i__4].i, q__1.i = temp.r * b[i__4].i + temp.i * b[ i__4].r; b[i__3].r = q__1.r, b[i__3].i = q__1.i; /* L220: */ } } /* L230: */ } } else { for (j = *n; j >= 1; --j) { if ((alpha->r != 1.f) || (alpha->i != 0.f)) { i__1 = *m; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = i__ + j * b_dim1; i__3 = i__ + j * b_dim1; q__1.r = alpha->r * b[i__3].r - alpha->i * b[i__3] .i, q__1.i = alpha->r * b[i__3].i + alpha->i * b[i__3].r; b[i__2].r = q__1.r, b[i__2].i = q__1.i; /* L240: */ } } i__1 = *n; for (k = j + 1; k <= i__1; ++k) { i__2 = k + j * a_dim1; if ((a[i__2].r != 0.f) || (a[i__2].i != 0.f)) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * b_dim1; i__4 = i__ + j * b_dim1; i__5 = k + j * a_dim1; i__6 = i__ + k * b_dim1; q__2.r = a[i__5].r * b[i__6].r - a[i__5].i * b[i__6].i, q__2.i = a[i__5].r * b[ i__6].i + a[i__5].i * b[i__6].r; q__1.r = b[i__4].r - q__2.r, q__1.i = b[i__4] .i - q__2.i; b[i__3].r = q__1.r, b[i__3].i = q__1.i; /* L250: */ } } /* L260: */ } if (nounit) { c_div(&q__1, &c_b21, &a[j + j * a_dim1]); temp.r = q__1.r, temp.i = q__1.i; i__1 = *m; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = i__ + j * b_dim1; i__3 = i__ + j * b_dim1; q__1.r = temp.r * b[i__3].r - temp.i * b[i__3].i, q__1.i = temp.r * b[i__3].i + temp.i * b[ i__3].r; b[i__2].r = q__1.r, b[i__2].i = q__1.i; /* L270: */ } } /* L280: */ } } } else { /* Form B := alpha*B*inv( A' ) or B := alpha*B*inv( conjg( A' ) ). */ if (upper) { for (k = *n; k >= 1; --k) { if (nounit) { if (noconj) { c_div(&q__1, &c_b21, &a[k + k * a_dim1]); temp.r = q__1.r, temp.i = q__1.i; } else { r_cnjg(&q__2, &a[k + k * a_dim1]); c_div(&q__1, &c_b21, &q__2); temp.r = q__1.r, temp.i = q__1.i; } i__1 = *m; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = i__ + k * b_dim1; i__3 = i__ + k * b_dim1; q__1.r = temp.r * b[i__3].r - temp.i * b[i__3].i, q__1.i = temp.r * b[i__3].i + temp.i * b[ i__3].r; b[i__2].r = q__1.r, b[i__2].i = q__1.i; /* L290: */ } } i__1 = k - 1; for (j = 1; j <= i__1; ++j) { i__2 = j + k * a_dim1; if ((a[i__2].r != 0.f) || (a[i__2].i != 0.f)) { if (noconj) { i__2 = j + k * a_dim1; temp.r = a[i__2].r, temp.i = a[i__2].i; } else { r_cnjg(&q__1, &a[j + k * a_dim1]); temp.r = q__1.r, temp.i = q__1.i; } i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * b_dim1; i__4 = i__ + j * b_dim1; i__5 = i__ + k * b_dim1; q__2.r = temp.r * b[i__5].r - temp.i * b[i__5] .i, q__2.i = temp.r * b[i__5].i + temp.i * b[i__5].r; q__1.r = b[i__4].r - q__2.r, q__1.i = b[i__4] .i - q__2.i; b[i__3].r = q__1.r, b[i__3].i = q__1.i; /* L300: */ } } /* L310: */ } if ((alpha->r != 1.f) || (alpha->i != 0.f)) { i__1 = *m; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = i__ + k * b_dim1; i__3 = i__ + k * b_dim1; q__1.r = alpha->r * b[i__3].r - alpha->i * b[i__3] .i, q__1.i = alpha->r * b[i__3].i + alpha->i * b[i__3].r; b[i__2].r = q__1.r, b[i__2].i = q__1.i; /* L320: */ } } /* L330: */ } } else { i__1 = *n; for (k = 1; k <= i__1; ++k) { if (nounit) { if (noconj) { c_div(&q__1, &c_b21, &a[k + k * a_dim1]); temp.r = q__1.r, temp.i = q__1.i; } else { r_cnjg(&q__2, &a[k + k * a_dim1]); c_div(&q__1, &c_b21, &q__2); temp.r = q__1.r, temp.i = q__1.i; } i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + k * b_dim1; i__4 = i__ + k * b_dim1; q__1.r = temp.r * b[i__4].r - temp.i * b[i__4].i, q__1.i = temp.r * b[i__4].i + temp.i * b[ i__4].r; b[i__3].r = q__1.r, b[i__3].i = q__1.i; /* L340: */ } } i__2 = *n; for (j = k + 1; j <= i__2; ++j) { i__3 = j + k * a_dim1; if ((a[i__3].r != 0.f) || (a[i__3].i != 0.f)) { if (noconj) { i__3 = j + k * a_dim1; temp.r = a[i__3].r, temp.i = a[i__3].i; } else { r_cnjg(&q__1, &a[j + k * a_dim1]); temp.r = q__1.r, temp.i = q__1.i; } i__3 = *m; for (i__ = 1; i__ <= i__3; ++i__) { i__4 = i__ + j * b_dim1; i__5 = i__ + j * b_dim1; i__6 = i__ + k * b_dim1; q__2.r = temp.r * b[i__6].r - temp.i * b[i__6] .i, q__2.i = temp.r * b[i__6].i + temp.i * b[i__6].r; q__1.r = b[i__5].r - q__2.r, q__1.i = b[i__5] .i - q__2.i; b[i__4].r = q__1.r, b[i__4].i = q__1.i; /* L350: */ } } /* L360: */ } if ((alpha->r != 1.f) || (alpha->i != 0.f)) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + k * b_dim1; i__4 = i__ + k * b_dim1; q__1.r = alpha->r * b[i__4].r - alpha->i * b[i__4] .i, q__1.i = alpha->r * b[i__4].i + alpha->i * b[i__4].r; b[i__3].r = q__1.r, b[i__3].i = q__1.i; /* L370: */ } } /* L380: */ } } } } return 0; /* End of CTRSM . */ } /* ctrsm_ */ /* Subroutine */ int ctrsv_(char *uplo, char *trans, char *diag, integer *n, complex *a, integer *lda, complex *x, integer *incx) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3, i__4, i__5; complex q__1, q__2, q__3; /* Builtin functions */ void c_div(complex *, complex *, complex *), r_cnjg(complex *, complex *); /* Local variables */ static integer i__, j, ix, jx, kx, info; static complex temp; extern logical lsame_(char *, char *); extern /* Subroutine */ int xerbla_(char *, integer *); static logical noconj, nounit; /* Purpose ======= CTRSV solves one of the systems of equations A*x = b, or A'*x = b, or conjg( A' )*x = b, where b and x are n element vectors and A is an n by n unit, or non-unit, upper or lower triangular matrix. No test for singularity or near-singularity is included in this routine. Such tests must be performed before calling this routine. Parameters ========== UPLO - CHARACTER*1. On entry, UPLO specifies whether the matrix is an upper or lower triangular matrix as follows: UPLO = 'U' or 'u' A is an upper triangular matrix. UPLO = 'L' or 'l' A is a lower triangular matrix. Unchanged on exit. TRANS - CHARACTER*1. On entry, TRANS specifies the equations to be solved as follows: TRANS = 'N' or 'n' A*x = b. TRANS = 'T' or 't' A'*x = b. TRANS = 'C' or 'c' conjg( A' )*x = b. Unchanged on exit. DIAG - CHARACTER*1. On entry, DIAG specifies whether or not A is unit triangular as follows: DIAG = 'U' or 'u' A is assumed to be unit triangular. DIAG = 'N' or 'n' A is not assumed to be unit triangular. Unchanged on exit. N - INTEGER. On entry, N specifies the order of the matrix A. N must be at least zero. Unchanged on exit. A - COMPLEX array of DIMENSION ( LDA, n ). Before entry with UPLO = 'U' or 'u', the leading n by n upper triangular part of the array A must contain the upper triangular matrix and the strictly lower triangular part of A is not referenced. Before entry with UPLO = 'L' or 'l', the leading n by n lower triangular part of the array A must contain the lower triangular matrix and the strictly upper triangular part of A is not referenced. Note that when DIAG = 'U' or 'u', the diagonal elements of A are not referenced either, but are assumed to be unity. Unchanged on exit. LDA - INTEGER. On entry, LDA specifies the first dimension of A as declared in the calling (sub) program. LDA must be at least max( 1, n ). Unchanged on exit. X - COMPLEX array of dimension at least ( 1 + ( n - 1 )*abs( INCX ) ). Before entry, the incremented array X must contain the n element right-hand side vector b. On exit, X is overwritten with the solution vector x. INCX - INTEGER. On entry, INCX specifies the increment for the elements of X. INCX must not be zero. Unchanged on exit. Level 2 Blas routine. -- Written on 22-October-1986. Jack Dongarra, Argonne National Lab. Jeremy Du Croz, Nag Central Office. Sven Hammarling, Nag Central Office. Richard Hanson, Sandia National Labs. Test the input parameters. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --x; /* Function Body */ info = 0; if (! lsame_(uplo, "U") && ! lsame_(uplo, "L")) { info = 1; } else if (! lsame_(trans, "N") && ! lsame_(trans, "T") && ! lsame_(trans, "C")) { info = 2; } else if (! lsame_(diag, "U") && ! lsame_(diag, "N")) { info = 3; } else if (*n < 0) { info = 4; } else if (*lda < max(1,*n)) { info = 6; } else if (*incx == 0) { info = 8; } if (info != 0) { xerbla_("CTRSV ", &info); return 0; } /* Quick return if possible. */ if (*n == 0) { return 0; } noconj = lsame_(trans, "T"); nounit = lsame_(diag, "N"); /* Set up the start point in X if the increment is not unity. This will be ( N - 1 )*INCX too small for descending loops. */ if (*incx <= 0) { kx = 1 - (*n - 1) * *incx; } else if (*incx != 1) { kx = 1; } /* Start the operations. In this version the elements of A are accessed sequentially with one pass through A. */ if (lsame_(trans, "N")) { /* Form x := inv( A )*x. */ if (lsame_(uplo, "U")) { if (*incx == 1) { for (j = *n; j >= 1; --j) { i__1 = j; if ((x[i__1].r != 0.f) || (x[i__1].i != 0.f)) { if (nounit) { i__1 = j; c_div(&q__1, &x[j], &a[j + j * a_dim1]); x[i__1].r = q__1.r, x[i__1].i = q__1.i; } i__1 = j; temp.r = x[i__1].r, temp.i = x[i__1].i; for (i__ = j - 1; i__ >= 1; --i__) { i__1 = i__; i__2 = i__; i__3 = i__ + j * a_dim1; q__2.r = temp.r * a[i__3].r - temp.i * a[i__3].i, q__2.i = temp.r * a[i__3].i + temp.i * a[ i__3].r; q__1.r = x[i__2].r - q__2.r, q__1.i = x[i__2].i - q__2.i; x[i__1].r = q__1.r, x[i__1].i = q__1.i; /* L10: */ } } /* L20: */ } } else { jx = kx + (*n - 1) * *incx; for (j = *n; j >= 1; --j) { i__1 = jx; if ((x[i__1].r != 0.f) || (x[i__1].i != 0.f)) { if (nounit) { i__1 = jx; c_div(&q__1, &x[jx], &a[j + j * a_dim1]); x[i__1].r = q__1.r, x[i__1].i = q__1.i; } i__1 = jx; temp.r = x[i__1].r, temp.i = x[i__1].i; ix = jx; for (i__ = j - 1; i__ >= 1; --i__) { ix -= *incx; i__1 = ix; i__2 = ix; i__3 = i__ + j * a_dim1; q__2.r = temp.r * a[i__3].r - temp.i * a[i__3].i, q__2.i = temp.r * a[i__3].i + temp.i * a[ i__3].r; q__1.r = x[i__2].r - q__2.r, q__1.i = x[i__2].i - q__2.i; x[i__1].r = q__1.r, x[i__1].i = q__1.i; /* L30: */ } } jx -= *incx; /* L40: */ } } } else { if (*incx == 1) { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = j; if ((x[i__2].r != 0.f) || (x[i__2].i != 0.f)) { if (nounit) { i__2 = j; c_div(&q__1, &x[j], &a[j + j * a_dim1]); x[i__2].r = q__1.r, x[i__2].i = q__1.i; } i__2 = j; temp.r = x[i__2].r, temp.i = x[i__2].i; i__2 = *n; for (i__ = j + 1; i__ <= i__2; ++i__) { i__3 = i__; i__4 = i__; i__5 = i__ + j * a_dim1; q__2.r = temp.r * a[i__5].r - temp.i * a[i__5].i, q__2.i = temp.r * a[i__5].i + temp.i * a[ i__5].r; q__1.r = x[i__4].r - q__2.r, q__1.i = x[i__4].i - q__2.i; x[i__3].r = q__1.r, x[i__3].i = q__1.i; /* L50: */ } } /* L60: */ } } else { jx = kx; i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = jx; if ((x[i__2].r != 0.f) || (x[i__2].i != 0.f)) { if (nounit) { i__2 = jx; c_div(&q__1, &x[jx], &a[j + j * a_dim1]); x[i__2].r = q__1.r, x[i__2].i = q__1.i; } i__2 = jx; temp.r = x[i__2].r, temp.i = x[i__2].i; ix = jx; i__2 = *n; for (i__ = j + 1; i__ <= i__2; ++i__) { ix += *incx; i__3 = ix; i__4 = ix; i__5 = i__ + j * a_dim1; q__2.r = temp.r * a[i__5].r - temp.i * a[i__5].i, q__2.i = temp.r * a[i__5].i + temp.i * a[ i__5].r; q__1.r = x[i__4].r - q__2.r, q__1.i = x[i__4].i - q__2.i; x[i__3].r = q__1.r, x[i__3].i = q__1.i; /* L70: */ } } jx += *incx; /* L80: */ } } } } else { /* Form x := inv( A' )*x or x := inv( conjg( A' ) )*x. */ if (lsame_(uplo, "U")) { if (*incx == 1) { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = j; temp.r = x[i__2].r, temp.i = x[i__2].i; if (noconj) { i__2 = j - 1; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * a_dim1; i__4 = i__; q__2.r = a[i__3].r * x[i__4].r - a[i__3].i * x[ i__4].i, q__2.i = a[i__3].r * x[i__4].i + a[i__3].i * x[i__4].r; q__1.r = temp.r - q__2.r, q__1.i = temp.i - q__2.i; temp.r = q__1.r, temp.i = q__1.i; /* L90: */ } if (nounit) { c_div(&q__1, &temp, &a[j + j * a_dim1]); temp.r = q__1.r, temp.i = q__1.i; } } else { i__2 = j - 1; for (i__ = 1; i__ <= i__2; ++i__) { r_cnjg(&q__3, &a[i__ + j * a_dim1]); i__3 = i__; q__2.r = q__3.r * x[i__3].r - q__3.i * x[i__3].i, q__2.i = q__3.r * x[i__3].i + q__3.i * x[ i__3].r; q__1.r = temp.r - q__2.r, q__1.i = temp.i - q__2.i; temp.r = q__1.r, temp.i = q__1.i; /* L100: */ } if (nounit) { r_cnjg(&q__2, &a[j + j * a_dim1]); c_div(&q__1, &temp, &q__2); temp.r = q__1.r, temp.i = q__1.i; } } i__2 = j; x[i__2].r = temp.r, x[i__2].i = temp.i; /* L110: */ } } else { jx = kx; i__1 = *n; for (j = 1; j <= i__1; ++j) { ix = kx; i__2 = jx; temp.r = x[i__2].r, temp.i = x[i__2].i; if (noconj) { i__2 = j - 1; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * a_dim1; i__4 = ix; q__2.r = a[i__3].r * x[i__4].r - a[i__3].i * x[ i__4].i, q__2.i = a[i__3].r * x[i__4].i + a[i__3].i * x[i__4].r; q__1.r = temp.r - q__2.r, q__1.i = temp.i - q__2.i; temp.r = q__1.r, temp.i = q__1.i; ix += *incx; /* L120: */ } if (nounit) { c_div(&q__1, &temp, &a[j + j * a_dim1]); temp.r = q__1.r, temp.i = q__1.i; } } else { i__2 = j - 1; for (i__ = 1; i__ <= i__2; ++i__) { r_cnjg(&q__3, &a[i__ + j * a_dim1]); i__3 = ix; q__2.r = q__3.r * x[i__3].r - q__3.i * x[i__3].i, q__2.i = q__3.r * x[i__3].i + q__3.i * x[ i__3].r; q__1.r = temp.r - q__2.r, q__1.i = temp.i - q__2.i; temp.r = q__1.r, temp.i = q__1.i; ix += *incx; /* L130: */ } if (nounit) { r_cnjg(&q__2, &a[j + j * a_dim1]); c_div(&q__1, &temp, &q__2); temp.r = q__1.r, temp.i = q__1.i; } } i__2 = jx; x[i__2].r = temp.r, x[i__2].i = temp.i; jx += *incx; /* L140: */ } } } else { if (*incx == 1) { for (j = *n; j >= 1; --j) { i__1 = j; temp.r = x[i__1].r, temp.i = x[i__1].i; if (noconj) { i__1 = j + 1; for (i__ = *n; i__ >= i__1; --i__) { i__2 = i__ + j * a_dim1; i__3 = i__; q__2.r = a[i__2].r * x[i__3].r - a[i__2].i * x[ i__3].i, q__2.i = a[i__2].r * x[i__3].i + a[i__2].i * x[i__3].r; q__1.r = temp.r - q__2.r, q__1.i = temp.i - q__2.i; temp.r = q__1.r, temp.i = q__1.i; /* L150: */ } if (nounit) { c_div(&q__1, &temp, &a[j + j * a_dim1]); temp.r = q__1.r, temp.i = q__1.i; } } else { i__1 = j + 1; for (i__ = *n; i__ >= i__1; --i__) { r_cnjg(&q__3, &a[i__ + j * a_dim1]); i__2 = i__; q__2.r = q__3.r * x[i__2].r - q__3.i * x[i__2].i, q__2.i = q__3.r * x[i__2].i + q__3.i * x[ i__2].r; q__1.r = temp.r - q__2.r, q__1.i = temp.i - q__2.i; temp.r = q__1.r, temp.i = q__1.i; /* L160: */ } if (nounit) { r_cnjg(&q__2, &a[j + j * a_dim1]); c_div(&q__1, &temp, &q__2); temp.r = q__1.r, temp.i = q__1.i; } } i__1 = j; x[i__1].r = temp.r, x[i__1].i = temp.i; /* L170: */ } } else { kx += (*n - 1) * *incx; jx = kx; for (j = *n; j >= 1; --j) { ix = kx; i__1 = jx; temp.r = x[i__1].r, temp.i = x[i__1].i; if (noconj) { i__1 = j + 1; for (i__ = *n; i__ >= i__1; --i__) { i__2 = i__ + j * a_dim1; i__3 = ix; q__2.r = a[i__2].r * x[i__3].r - a[i__2].i * x[ i__3].i, q__2.i = a[i__2].r * x[i__3].i + a[i__2].i * x[i__3].r; q__1.r = temp.r - q__2.r, q__1.i = temp.i - q__2.i; temp.r = q__1.r, temp.i = q__1.i; ix -= *incx; /* L180: */ } if (nounit) { c_div(&q__1, &temp, &a[j + j * a_dim1]); temp.r = q__1.r, temp.i = q__1.i; } } else { i__1 = j + 1; for (i__ = *n; i__ >= i__1; --i__) { r_cnjg(&q__3, &a[i__ + j * a_dim1]); i__2 = ix; q__2.r = q__3.r * x[i__2].r - q__3.i * x[i__2].i, q__2.i = q__3.r * x[i__2].i + q__3.i * x[ i__2].r; q__1.r = temp.r - q__2.r, q__1.i = temp.i - q__2.i; temp.r = q__1.r, temp.i = q__1.i; ix -= *incx; /* L190: */ } if (nounit) { r_cnjg(&q__2, &a[j + j * a_dim1]); c_div(&q__1, &temp, &q__2); temp.r = q__1.r, temp.i = q__1.i; } } i__1 = jx; x[i__1].r = temp.r, x[i__1].i = temp.i; jx -= *incx; /* L200: */ } } } } return 0; /* End of CTRSV . */ } /* ctrsv_ */ /* Subroutine */ int daxpy_(integer *n, doublereal *da, doublereal *dx, integer *incx, doublereal *dy, integer *incy) { /* System generated locals */ integer i__1; /* Local variables */ static integer i__, m, ix, iy, mp1; /* constant times a vector plus a vector. uses unrolled loops for increments equal to one. jack dongarra, linpack, 3/11/78. modified 12/3/93, array(1) declarations changed to array(*) */ /* Parameter adjustments */ --dy; --dx; /* Function Body */ if (*n <= 0) { return 0; } if (*da == 0.) { return 0; } if (*incx == 1 && *incy == 1) { goto L20; } /* code for unequal increments or equal increments not equal to 1 */ ix = 1; iy = 1; if (*incx < 0) { ix = (-(*n) + 1) * *incx + 1; } if (*incy < 0) { iy = (-(*n) + 1) * *incy + 1; } i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { dy[iy] += *da * dx[ix]; ix += *incx; iy += *incy; /* L10: */ } return 0; /* code for both increments equal to 1 clean-up loop */ L20: m = *n % 4; if (m == 0) { goto L40; } i__1 = m; for (i__ = 1; i__ <= i__1; ++i__) { dy[i__] += *da * dx[i__]; /* L30: */ } if (*n < 4) { return 0; } L40: mp1 = m + 1; i__1 = *n; for (i__ = mp1; i__ <= i__1; i__ += 4) { dy[i__] += *da * dx[i__]; dy[i__ + 1] += *da * dx[i__ + 1]; dy[i__ + 2] += *da * dx[i__ + 2]; dy[i__ + 3] += *da * dx[i__ + 3]; /* L50: */ } return 0; } /* daxpy_ */ doublereal dcabs1_(doublecomplex *z__) { /* System generated locals */ doublereal ret_val; static doublecomplex equiv_0[1]; /* Local variables */ #define t ((doublereal *)equiv_0) #define zz (equiv_0) zz->r = z__->r, zz->i = z__->i; ret_val = abs(t[0]) + abs(t[1]); return ret_val; } /* dcabs1_ */ #undef zz #undef t /* Subroutine */ int dcopy_(integer *n, doublereal *dx, integer *incx, doublereal *dy, integer *incy) { /* System generated locals */ integer i__1; /* Local variables */ static integer i__, m, ix, iy, mp1; /* copies a vector, x, to a vector, y. uses unrolled loops for increments equal to one. jack dongarra, linpack, 3/11/78. modified 12/3/93, array(1) declarations changed to array(*) */ /* Parameter adjustments */ --dy; --dx; /* Function Body */ if (*n <= 0) { return 0; } if (*incx == 1 && *incy == 1) { goto L20; } /* code for unequal increments or equal increments not equal to 1 */ ix = 1; iy = 1; if (*incx < 0) { ix = (-(*n) + 1) * *incx + 1; } if (*incy < 0) { iy = (-(*n) + 1) * *incy + 1; } i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { dy[iy] = dx[ix]; ix += *incx; iy += *incy; /* L10: */ } return 0; /* code for both increments equal to 1 clean-up loop */ L20: m = *n % 7; if (m == 0) { goto L40; } i__1 = m; for (i__ = 1; i__ <= i__1; ++i__) { dy[i__] = dx[i__]; /* L30: */ } if (*n < 7) { return 0; } L40: mp1 = m + 1; i__1 = *n; for (i__ = mp1; i__ <= i__1; i__ += 7) { dy[i__] = dx[i__]; dy[i__ + 1] = dx[i__ + 1]; dy[i__ + 2] = dx[i__ + 2]; dy[i__ + 3] = dx[i__ + 3]; dy[i__ + 4] = dx[i__ + 4]; dy[i__ + 5] = dx[i__ + 5]; dy[i__ + 6] = dx[i__ + 6]; /* L50: */ } return 0; } /* dcopy_ */ doublereal ddot_(integer *n, doublereal *dx, integer *incx, doublereal *dy, integer *incy) { /* System generated locals */ integer i__1; doublereal ret_val; /* Local variables */ static integer i__, m, ix, iy, mp1; static doublereal dtemp; /* forms the dot product of two vectors. uses unrolled loops for increments equal to one. jack dongarra, linpack, 3/11/78. modified 12/3/93, array(1) declarations changed to array(*) */ /* Parameter adjustments */ --dy; --dx; /* Function Body */ ret_val = 0.; dtemp = 0.; if (*n <= 0) { return ret_val; } if (*incx == 1 && *incy == 1) { goto L20; } /* code for unequal increments or equal increments not equal to 1 */ ix = 1; iy = 1; if (*incx < 0) { ix = (-(*n) + 1) * *incx + 1; } if (*incy < 0) { iy = (-(*n) + 1) * *incy + 1; } i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { dtemp += dx[ix] * dy[iy]; ix += *incx; iy += *incy; /* L10: */ } ret_val = dtemp; return ret_val; /* code for both increments equal to 1 clean-up loop */ L20: m = *n % 5; if (m == 0) { goto L40; } i__1 = m; for (i__ = 1; i__ <= i__1; ++i__) { dtemp += dx[i__] * dy[i__]; /* L30: */ } if (*n < 5) { goto L60; } L40: mp1 = m + 1; i__1 = *n; for (i__ = mp1; i__ <= i__1; i__ += 5) { dtemp = dtemp + dx[i__] * dy[i__] + dx[i__ + 1] * dy[i__ + 1] + dx[ i__ + 2] * dy[i__ + 2] + dx[i__ + 3] * dy[i__ + 3] + dx[i__ + 4] * dy[i__ + 4]; /* L50: */ } L60: ret_val = dtemp; return ret_val; } /* ddot_ */ /* Subroutine */ int dgemm_(char *transa, char *transb, integer *m, integer * n, integer *k, doublereal *alpha, doublereal *a, integer *lda, doublereal *b, integer *ldb, doublereal *beta, doublereal *c__, integer *ldc) { /* System generated locals */ integer a_dim1, a_offset, b_dim1, b_offset, c_dim1, c_offset, i__1, i__2, i__3; /* Local variables */ static integer i__, j, l, info; static logical nota, notb; static doublereal temp; static integer ncola; extern logical lsame_(char *, char *); static integer nrowa, nrowb; extern /* Subroutine */ int xerbla_(char *, integer *); /* Purpose ======= DGEMM performs one of the matrix-matrix operations C := alpha*op( A )*op( B ) + beta*C, where op( X ) is one of op( X ) = X or op( X ) = X', alpha and beta are scalars, and A, B and C are matrices, with op( A ) an m by k matrix, op( B ) a k by n matrix and C an m by n matrix. Parameters ========== TRANSA - CHARACTER*1. On entry, TRANSA specifies the form of op( A ) to be used in the matrix multiplication as follows: TRANSA = 'N' or 'n', op( A ) = A. TRANSA = 'T' or 't', op( A ) = A'. TRANSA = 'C' or 'c', op( A ) = A'. Unchanged on exit. TRANSB - CHARACTER*1. On entry, TRANSB specifies the form of op( B ) to be used in the matrix multiplication as follows: TRANSB = 'N' or 'n', op( B ) = B. TRANSB = 'T' or 't', op( B ) = B'. TRANSB = 'C' or 'c', op( B ) = B'. Unchanged on exit. M - INTEGER. On entry, M specifies the number of rows of the matrix op( A ) and of the matrix C. M must be at least zero. Unchanged on exit. N - INTEGER. On entry, N specifies the number of columns of the matrix op( B ) and the number of columns of the matrix C. N must be at least zero. Unchanged on exit. K - INTEGER. On entry, K specifies the number of columns of the matrix op( A ) and the number of rows of the matrix op( B ). K must be at least zero. Unchanged on exit. ALPHA - DOUBLE PRECISION. On entry, ALPHA specifies the scalar alpha. Unchanged on exit. A - DOUBLE PRECISION array of DIMENSION ( LDA, ka ), where ka is k when TRANSA = 'N' or 'n', and is m otherwise. Before entry with TRANSA = 'N' or 'n', the leading m by k part of the array A must contain the matrix A, otherwise the leading k by m part of the array A must contain the matrix A. Unchanged on exit. LDA - INTEGER. On entry, LDA specifies the first dimension of A as declared in the calling (sub) program. When TRANSA = 'N' or 'n' then LDA must be at least max( 1, m ), otherwise LDA must be at least max( 1, k ). Unchanged on exit. B - DOUBLE PRECISION array of DIMENSION ( LDB, kb ), where kb is n when TRANSB = 'N' or 'n', and is k otherwise. Before entry with TRANSB = 'N' or 'n', the leading k by n part of the array B must contain the matrix B, otherwise the leading n by k part of the array B must contain the matrix B. Unchanged on exit. LDB - INTEGER. On entry, LDB specifies the first dimension of B as declared in the calling (sub) program. When TRANSB = 'N' or 'n' then LDB must be at least max( 1, k ), otherwise LDB must be at least max( 1, n ). Unchanged on exit. BETA - DOUBLE PRECISION. On entry, BETA specifies the scalar beta. When BETA is supplied as zero then C need not be set on input. Unchanged on exit. C - DOUBLE PRECISION array of DIMENSION ( LDC, n ). Before entry, the leading m by n part of the array C must contain the matrix C, except when beta is zero, in which case C need not be set on entry. On exit, the array C is overwritten by the m by n matrix ( alpha*op( A )*op( B ) + beta*C ). LDC - INTEGER. On entry, LDC specifies the first dimension of C as declared in the calling (sub) program. LDC must be at least max( 1, m ). Unchanged on exit. Level 3 Blas routine. -- Written on 8-February-1989. Jack Dongarra, Argonne National Laboratory. Iain Duff, AERE Harwell. Jeremy Du Croz, Numerical Algorithms Group Ltd. Sven Hammarling, Numerical Algorithms Group Ltd. Set NOTA and NOTB as true if A and B respectively are not transposed and set NROWA, NCOLA and NROWB as the number of rows and columns of A and the number of rows of B respectively. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; b_dim1 = *ldb; b_offset = 1 + b_dim1; b -= b_offset; c_dim1 = *ldc; c_offset = 1 + c_dim1; c__ -= c_offset; /* Function Body */ nota = lsame_(transa, "N"); notb = lsame_(transb, "N"); if (nota) { nrowa = *m; ncola = *k; } else { nrowa = *k; ncola = *m; } if (notb) { nrowb = *k; } else { nrowb = *n; } /* Test the input parameters. */ info = 0; if (! nota && ! lsame_(transa, "C") && ! lsame_( transa, "T")) { info = 1; } else if (! notb && ! lsame_(transb, "C") && ! lsame_(transb, "T")) { info = 2; } else if (*m < 0) { info = 3; } else if (*n < 0) { info = 4; } else if (*k < 0) { info = 5; } else if (*lda < max(1,nrowa)) { info = 8; } else if (*ldb < max(1,nrowb)) { info = 10; } else if (*ldc < max(1,*m)) { info = 13; } if (info != 0) { xerbla_("DGEMM ", &info); return 0; } /* Quick return if possible. */ if (((*m == 0) || (*n == 0)) || (((*alpha == 0.) || (*k == 0)) && *beta == 1.)) { return 0; } /* And if alpha.eq.zero. */ if (*alpha == 0.) { if (*beta == 0.) { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { c__[i__ + j * c_dim1] = 0.; /* L10: */ } /* L20: */ } } else { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { c__[i__ + j * c_dim1] = *beta * c__[i__ + j * c_dim1]; /* L30: */ } /* L40: */ } } return 0; } /* Start the operations. */ if (notb) { if (nota) { /* Form C := alpha*A*B + beta*C. */ i__1 = *n; for (j = 1; j <= i__1; ++j) { if (*beta == 0.) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { c__[i__ + j * c_dim1] = 0.; /* L50: */ } } else if (*beta != 1.) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { c__[i__ + j * c_dim1] = *beta * c__[i__ + j * c_dim1]; /* L60: */ } } i__2 = *k; for (l = 1; l <= i__2; ++l) { if (b[l + j * b_dim1] != 0.) { temp = *alpha * b[l + j * b_dim1]; i__3 = *m; for (i__ = 1; i__ <= i__3; ++i__) { c__[i__ + j * c_dim1] += temp * a[i__ + l * a_dim1]; /* L70: */ } } /* L80: */ } /* L90: */ } } else { /* Form C := alpha*A'*B + beta*C */ i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { temp = 0.; i__3 = *k; for (l = 1; l <= i__3; ++l) { temp += a[l + i__ * a_dim1] * b[l + j * b_dim1]; /* L100: */ } if (*beta == 0.) { c__[i__ + j * c_dim1] = *alpha * temp; } else { c__[i__ + j * c_dim1] = *alpha * temp + *beta * c__[ i__ + j * c_dim1]; } /* L110: */ } /* L120: */ } } } else { if (nota) { /* Form C := alpha*A*B' + beta*C */ i__1 = *n; for (j = 1; j <= i__1; ++j) { if (*beta == 0.) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { c__[i__ + j * c_dim1] = 0.; /* L130: */ } } else if (*beta != 1.) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { c__[i__ + j * c_dim1] = *beta * c__[i__ + j * c_dim1]; /* L140: */ } } i__2 = *k; for (l = 1; l <= i__2; ++l) { if (b[j + l * b_dim1] != 0.) { temp = *alpha * b[j + l * b_dim1]; i__3 = *m; for (i__ = 1; i__ <= i__3; ++i__) { c__[i__ + j * c_dim1] += temp * a[i__ + l * a_dim1]; /* L150: */ } } /* L160: */ } /* L170: */ } } else { /* Form C := alpha*A'*B' + beta*C */ i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { temp = 0.; i__3 = *k; for (l = 1; l <= i__3; ++l) { temp += a[l + i__ * a_dim1] * b[j + l * b_dim1]; /* L180: */ } if (*beta == 0.) { c__[i__ + j * c_dim1] = *alpha * temp; } else { c__[i__ + j * c_dim1] = *alpha * temp + *beta * c__[ i__ + j * c_dim1]; } /* L190: */ } /* L200: */ } } } return 0; /* End of DGEMM . */ } /* dgemm_ */ /* Subroutine */ int dgemv_(char *trans, integer *m, integer *n, doublereal * alpha, doublereal *a, integer *lda, doublereal *x, integer *incx, doublereal *beta, doublereal *y, integer *incy) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2; /* Local variables */ static integer i__, j, ix, iy, jx, jy, kx, ky, info; static doublereal temp; static integer lenx, leny; extern logical lsame_(char *, char *); extern /* Subroutine */ int xerbla_(char *, integer *); /* Purpose ======= DGEMV performs one of the matrix-vector operations y := alpha*A*x + beta*y, or y := alpha*A'*x + beta*y, where alpha and beta are scalars, x and y are vectors and A is an m by n matrix. Parameters ========== TRANS - CHARACTER*1. On entry, TRANS specifies the operation to be performed as follows: TRANS = 'N' or 'n' y := alpha*A*x + beta*y. TRANS = 'T' or 't' y := alpha*A'*x + beta*y. TRANS = 'C' or 'c' y := alpha*A'*x + beta*y. Unchanged on exit. M - INTEGER. On entry, M specifies the number of rows of the matrix A. M must be at least zero. Unchanged on exit. N - INTEGER. On entry, N specifies the number of columns of the matrix A. N must be at least zero. Unchanged on exit. ALPHA - DOUBLE PRECISION. On entry, ALPHA specifies the scalar alpha. Unchanged on exit. A - DOUBLE PRECISION array of DIMENSION ( LDA, n ). Before entry, the leading m by n part of the array A must contain the matrix of coefficients. Unchanged on exit. LDA - INTEGER. On entry, LDA specifies the first dimension of A as declared in the calling (sub) program. LDA must be at least max( 1, m ). Unchanged on exit. X - DOUBLE PRECISION array of DIMENSION at least ( 1 + ( n - 1 )*abs( INCX ) ) when TRANS = 'N' or 'n' and at least ( 1 + ( m - 1 )*abs( INCX ) ) otherwise. Before entry, the incremented array X must contain the vector x. Unchanged on exit. INCX - INTEGER. On entry, INCX specifies the increment for the elements of X. INCX must not be zero. Unchanged on exit. BETA - DOUBLE PRECISION. On entry, BETA specifies the scalar beta. When BETA is supplied as zero then Y need not be set on input. Unchanged on exit. Y - DOUBLE PRECISION array of DIMENSION at least ( 1 + ( m - 1 )*abs( INCY ) ) when TRANS = 'N' or 'n' and at least ( 1 + ( n - 1 )*abs( INCY ) ) otherwise. Before entry with BETA non-zero, the incremented array Y must contain the vector y. On exit, Y is overwritten by the updated vector y. INCY - INTEGER. On entry, INCY specifies the increment for the elements of Y. INCY must not be zero. Unchanged on exit. Level 2 Blas routine. -- Written on 22-October-1986. Jack Dongarra, Argonne National Lab. Jeremy Du Croz, Nag Central Office. Sven Hammarling, Nag Central Office. Richard Hanson, Sandia National Labs. Test the input parameters. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --x; --y; /* Function Body */ info = 0; if (! lsame_(trans, "N") && ! lsame_(trans, "T") && ! lsame_(trans, "C") ) { info = 1; } else if (*m < 0) { info = 2; } else if (*n < 0) { info = 3; } else if (*lda < max(1,*m)) { info = 6; } else if (*incx == 0) { info = 8; } else if (*incy == 0) { info = 11; } if (info != 0) { xerbla_("DGEMV ", &info); return 0; } /* Quick return if possible. */ if (((*m == 0) || (*n == 0)) || (*alpha == 0. && *beta == 1.)) { return 0; } /* Set LENX and LENY, the lengths of the vectors x and y, and set up the start points in X and Y. */ if (lsame_(trans, "N")) { lenx = *n; leny = *m; } else { lenx = *m; leny = *n; } if (*incx > 0) { kx = 1; } else { kx = 1 - (lenx - 1) * *incx; } if (*incy > 0) { ky = 1; } else { ky = 1 - (leny - 1) * *incy; } /* Start the operations. In this version the elements of A are accessed sequentially with one pass through A. First form y := beta*y. */ if (*beta != 1.) { if (*incy == 1) { if (*beta == 0.) { i__1 = leny; for (i__ = 1; i__ <= i__1; ++i__) { y[i__] = 0.; /* L10: */ } } else { i__1 = leny; for (i__ = 1; i__ <= i__1; ++i__) { y[i__] = *beta * y[i__]; /* L20: */ } } } else { iy = ky; if (*beta == 0.) { i__1 = leny; for (i__ = 1; i__ <= i__1; ++i__) { y[iy] = 0.; iy += *incy; /* L30: */ } } else { i__1 = leny; for (i__ = 1; i__ <= i__1; ++i__) { y[iy] = *beta * y[iy]; iy += *incy; /* L40: */ } } } } if (*alpha == 0.) { return 0; } if (lsame_(trans, "N")) { /* Form y := alpha*A*x + y. */ jx = kx; if (*incy == 1) { i__1 = *n; for (j = 1; j <= i__1; ++j) { if (x[jx] != 0.) { temp = *alpha * x[jx]; i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { y[i__] += temp * a[i__ + j * a_dim1]; /* L50: */ } } jx += *incx; /* L60: */ } } else { i__1 = *n; for (j = 1; j <= i__1; ++j) { if (x[jx] != 0.) { temp = *alpha * x[jx]; iy = ky; i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { y[iy] += temp * a[i__ + j * a_dim1]; iy += *incy; /* L70: */ } } jx += *incx; /* L80: */ } } } else { /* Form y := alpha*A'*x + y. */ jy = ky; if (*incx == 1) { i__1 = *n; for (j = 1; j <= i__1; ++j) { temp = 0.; i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { temp += a[i__ + j * a_dim1] * x[i__]; /* L90: */ } y[jy] += *alpha * temp; jy += *incy; /* L100: */ } } else { i__1 = *n; for (j = 1; j <= i__1; ++j) { temp = 0.; ix = kx; i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { temp += a[i__ + j * a_dim1] * x[ix]; ix += *incx; /* L110: */ } y[jy] += *alpha * temp; jy += *incy; /* L120: */ } } } return 0; /* End of DGEMV . */ } /* dgemv_ */ /* Subroutine */ int dger_(integer *m, integer *n, doublereal *alpha, doublereal *x, integer *incx, doublereal *y, integer *incy, doublereal *a, integer *lda) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2; /* Local variables */ static integer i__, j, ix, jy, kx, info; static doublereal temp; extern /* Subroutine */ int xerbla_(char *, integer *); /* Purpose ======= DGER performs the rank 1 operation A := alpha*x*y' + A, where alpha is a scalar, x is an m element vector, y is an n element vector and A is an m by n matrix. Parameters ========== M - INTEGER. On entry, M specifies the number of rows of the matrix A. M must be at least zero. Unchanged on exit. N - INTEGER. On entry, N specifies the number of columns of the matrix A. N must be at least zero. Unchanged on exit. ALPHA - DOUBLE PRECISION. On entry, ALPHA specifies the scalar alpha. Unchanged on exit. X - DOUBLE PRECISION array of dimension at least ( 1 + ( m - 1 )*abs( INCX ) ). Before entry, the incremented array X must contain the m element vector x. Unchanged on exit. INCX - INTEGER. On entry, INCX specifies the increment for the elements of X. INCX must not be zero. Unchanged on exit. Y - DOUBLE PRECISION array of dimension at least ( 1 + ( n - 1 )*abs( INCY ) ). Before entry, the incremented array Y must contain the n element vector y. Unchanged on exit. INCY - INTEGER. On entry, INCY specifies the increment for the elements of Y. INCY must not be zero. Unchanged on exit. A - DOUBLE PRECISION array of DIMENSION ( LDA, n ). Before entry, the leading m by n part of the array A must contain the matrix of coefficients. On exit, A is overwritten by the updated matrix. LDA - INTEGER. On entry, LDA specifies the first dimension of A as declared in the calling (sub) program. LDA must be at least max( 1, m ). Unchanged on exit. Level 2 Blas routine. -- Written on 22-October-1986. Jack Dongarra, Argonne National Lab. Jeremy Du Croz, Nag Central Office. Sven Hammarling, Nag Central Office. Richard Hanson, Sandia National Labs. Test the input parameters. */ /* Parameter adjustments */ --x; --y; a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; /* Function Body */ info = 0; if (*m < 0) { info = 1; } else if (*n < 0) { info = 2; } else if (*incx == 0) { info = 5; } else if (*incy == 0) { info = 7; } else if (*lda < max(1,*m)) { info = 9; } if (info != 0) { xerbla_("DGER ", &info); return 0; } /* Quick return if possible. */ if (((*m == 0) || (*n == 0)) || (*alpha == 0.)) { return 0; } /* Start the operations. In this version the elements of A are accessed sequentially with one pass through A. */ if (*incy > 0) { jy = 1; } else { jy = 1 - (*n - 1) * *incy; } if (*incx == 1) { i__1 = *n; for (j = 1; j <= i__1; ++j) { if (y[jy] != 0.) { temp = *alpha * y[jy]; i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { a[i__ + j * a_dim1] += x[i__] * temp; /* L10: */ } } jy += *incy; /* L20: */ } } else { if (*incx > 0) { kx = 1; } else { kx = 1 - (*m - 1) * *incx; } i__1 = *n; for (j = 1; j <= i__1; ++j) { if (y[jy] != 0.) { temp = *alpha * y[jy]; ix = kx; i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { a[i__ + j * a_dim1] += x[ix] * temp; ix += *incx; /* L30: */ } } jy += *incy; /* L40: */ } } return 0; /* End of DGER . */ } /* dger_ */ doublereal dnrm2_(integer *n, doublereal *x, integer *incx) { /* System generated locals */ integer i__1, i__2; doublereal ret_val, d__1; /* Builtin functions */ double sqrt(doublereal); /* Local variables */ static integer ix; static doublereal ssq, norm, scale, absxi; /* DNRM2 returns the euclidean norm of a vector via the function name, so that DNRM2 := sqrt( x'*x ) -- This version written on 25-October-1982. Modified on 14-October-1993 to inline the call to DLASSQ. Sven Hammarling, Nag Ltd. */ /* Parameter adjustments */ --x; /* Function Body */ if ((*n < 1) || (*incx < 1)) { norm = 0.; } else if (*n == 1) { norm = abs(x[1]); } else { scale = 0.; ssq = 1.; /* The following loop is equivalent to this call to the LAPACK auxiliary routine: CALL DLASSQ( N, X, INCX, SCALE, SSQ ) */ i__1 = (*n - 1) * *incx + 1; i__2 = *incx; for (ix = 1; i__2 < 0 ? ix >= i__1 : ix <= i__1; ix += i__2) { if (x[ix] != 0.) { absxi = (d__1 = x[ix], abs(d__1)); if (scale < absxi) { /* Computing 2nd power */ d__1 = scale / absxi; ssq = ssq * (d__1 * d__1) + 1.; scale = absxi; } else { /* Computing 2nd power */ d__1 = absxi / scale; ssq += d__1 * d__1; } } /* L10: */ } norm = scale * sqrt(ssq); } ret_val = norm; return ret_val; /* End of DNRM2. */ } /* dnrm2_ */ /* Subroutine */ int drot_(integer *n, doublereal *dx, integer *incx, doublereal *dy, integer *incy, doublereal *c__, doublereal *s) { /* System generated locals */ integer i__1; /* Local variables */ static integer i__, ix, iy; static doublereal dtemp; /* applies a plane rotation. jack dongarra, linpack, 3/11/78. modified 12/3/93, array(1) declarations changed to array(*) */ /* Parameter adjustments */ --dy; --dx; /* Function Body */ if (*n <= 0) { return 0; } if (*incx == 1 && *incy == 1) { goto L20; } /* code for unequal increments or equal increments not equal to 1 */ ix = 1; iy = 1; if (*incx < 0) { ix = (-(*n) + 1) * *incx + 1; } if (*incy < 0) { iy = (-(*n) + 1) * *incy + 1; } i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { dtemp = *c__ * dx[ix] + *s * dy[iy]; dy[iy] = *c__ * dy[iy] - *s * dx[ix]; dx[ix] = dtemp; ix += *incx; iy += *incy; /* L10: */ } return 0; /* code for both increments equal to 1 */ L20: i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { dtemp = *c__ * dx[i__] + *s * dy[i__]; dy[i__] = *c__ * dy[i__] - *s * dx[i__]; dx[i__] = dtemp; /* L30: */ } return 0; } /* drot_ */ /* Subroutine */ int dscal_(integer *n, doublereal *da, doublereal *dx, integer *incx) { /* System generated locals */ integer i__1, i__2; /* Local variables */ static integer i__, m, mp1, nincx; /* scales a vector by a constant. uses unrolled loops for increment equal to one. jack dongarra, linpack, 3/11/78. modified 3/93 to return if incx .le. 0. modified 12/3/93, array(1) declarations changed to array(*) */ /* Parameter adjustments */ --dx; /* Function Body */ if ((*n <= 0) || (*incx <= 0)) { return 0; } if (*incx == 1) { goto L20; } /* code for increment not equal to 1 */ nincx = *n * *incx; i__1 = nincx; i__2 = *incx; for (i__ = 1; i__2 < 0 ? i__ >= i__1 : i__ <= i__1; i__ += i__2) { dx[i__] = *da * dx[i__]; /* L10: */ } return 0; /* code for increment equal to 1 clean-up loop */ L20: m = *n % 5; if (m == 0) { goto L40; } i__2 = m; for (i__ = 1; i__ <= i__2; ++i__) { dx[i__] = *da * dx[i__]; /* L30: */ } if (*n < 5) { return 0; } L40: mp1 = m + 1; i__2 = *n; for (i__ = mp1; i__ <= i__2; i__ += 5) { dx[i__] = *da * dx[i__]; dx[i__ + 1] = *da * dx[i__ + 1]; dx[i__ + 2] = *da * dx[i__ + 2]; dx[i__ + 3] = *da * dx[i__ + 3]; dx[i__ + 4] = *da * dx[i__ + 4]; /* L50: */ } return 0; } /* dscal_ */ /* Subroutine */ int dswap_(integer *n, doublereal *dx, integer *incx, doublereal *dy, integer *incy) { /* System generated locals */ integer i__1; /* Local variables */ static integer i__, m, ix, iy, mp1; static doublereal dtemp; /* interchanges two vectors. uses unrolled loops for increments equal one. jack dongarra, linpack, 3/11/78. modified 12/3/93, array(1) declarations changed to array(*) */ /* Parameter adjustments */ --dy; --dx; /* Function Body */ if (*n <= 0) { return 0; } if (*incx == 1 && *incy == 1) { goto L20; } /* code for unequal increments or equal increments not equal to 1 */ ix = 1; iy = 1; if (*incx < 0) { ix = (-(*n) + 1) * *incx + 1; } if (*incy < 0) { iy = (-(*n) + 1) * *incy + 1; } i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { dtemp = dx[ix]; dx[ix] = dy[iy]; dy[iy] = dtemp; ix += *incx; iy += *incy; /* L10: */ } return 0; /* code for both increments equal to 1 clean-up loop */ L20: m = *n % 3; if (m == 0) { goto L40; } i__1 = m; for (i__ = 1; i__ <= i__1; ++i__) { dtemp = dx[i__]; dx[i__] = dy[i__]; dy[i__] = dtemp; /* L30: */ } if (*n < 3) { return 0; } L40: mp1 = m + 1; i__1 = *n; for (i__ = mp1; i__ <= i__1; i__ += 3) { dtemp = dx[i__]; dx[i__] = dy[i__]; dy[i__] = dtemp; dtemp = dx[i__ + 1]; dx[i__ + 1] = dy[i__ + 1]; dy[i__ + 1] = dtemp; dtemp = dx[i__ + 2]; dx[i__ + 2] = dy[i__ + 2]; dy[i__ + 2] = dtemp; /* L50: */ } return 0; } /* dswap_ */ /* Subroutine */ int dsymv_(char *uplo, integer *n, doublereal *alpha, doublereal *a, integer *lda, doublereal *x, integer *incx, doublereal *beta, doublereal *y, integer *incy) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2; /* Local variables */ static integer i__, j, ix, iy, jx, jy, kx, ky, info; static doublereal temp1, temp2; extern logical lsame_(char *, char *); extern /* Subroutine */ int xerbla_(char *, integer *); /* Purpose ======= DSYMV performs the matrix-vector operation y := alpha*A*x + beta*y, where alpha and beta are scalars, x and y are n element vectors and A is an n by n symmetric matrix. Parameters ========== UPLO - CHARACTER*1. On entry, UPLO specifies whether the upper or lower triangular part of the array A is to be referenced as follows: UPLO = 'U' or 'u' Only the upper triangular part of A is to be referenced. UPLO = 'L' or 'l' Only the lower triangular part of A is to be referenced. Unchanged on exit. N - INTEGER. On entry, N specifies the order of the matrix A. N must be at least zero. Unchanged on exit. ALPHA - DOUBLE PRECISION. On entry, ALPHA specifies the scalar alpha. Unchanged on exit. A - DOUBLE PRECISION array of DIMENSION ( LDA, n ). Before entry with UPLO = 'U' or 'u', the leading n by n upper triangular part of the array A must contain the upper triangular part of the symmetric matrix and the strictly lower triangular part of A is not referenced. Before entry with UPLO = 'L' or 'l', the leading n by n lower triangular part of the array A must contain the lower triangular part of the symmetric matrix and the strictly upper triangular part of A is not referenced. Unchanged on exit. LDA - INTEGER. On entry, LDA specifies the first dimension of A as declared in the calling (sub) program. LDA must be at least max( 1, n ). Unchanged on exit. X - DOUBLE PRECISION array of dimension at least ( 1 + ( n - 1 )*abs( INCX ) ). Before entry, the incremented array X must contain the n element vector x. Unchanged on exit. INCX - INTEGER. On entry, INCX specifies the increment for the elements of X. INCX must not be zero. Unchanged on exit. BETA - DOUBLE PRECISION. On entry, BETA specifies the scalar beta. When BETA is supplied as zero then Y need not be set on input. Unchanged on exit. Y - DOUBLE PRECISION array of dimension at least ( 1 + ( n - 1 )*abs( INCY ) ). Before entry, the incremented array Y must contain the n element vector y. On exit, Y is overwritten by the updated vector y. INCY - INTEGER. On entry, INCY specifies the increment for the elements of Y. INCY must not be zero. Unchanged on exit. Level 2 Blas routine. -- Written on 22-October-1986. Jack Dongarra, Argonne National Lab. Jeremy Du Croz, Nag Central Office. Sven Hammarling, Nag Central Office. Richard Hanson, Sandia National Labs. Test the input parameters. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --x; --y; /* Function Body */ info = 0; if (! lsame_(uplo, "U") && ! lsame_(uplo, "L")) { info = 1; } else if (*n < 0) { info = 2; } else if (*lda < max(1,*n)) { info = 5; } else if (*incx == 0) { info = 7; } else if (*incy == 0) { info = 10; } if (info != 0) { xerbla_("DSYMV ", &info); return 0; } /* Quick return if possible. */ if ((*n == 0) || (*alpha == 0. && *beta == 1.)) { return 0; } /* Set up the start points in X and Y. */ if (*incx > 0) { kx = 1; } else { kx = 1 - (*n - 1) * *incx; } if (*incy > 0) { ky = 1; } else { ky = 1 - (*n - 1) * *incy; } /* Start the operations. In this version the elements of A are accessed sequentially with one pass through the triangular part of A. First form y := beta*y. */ if (*beta != 1.) { if (*incy == 1) { if (*beta == 0.) { i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { y[i__] = 0.; /* L10: */ } } else { i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { y[i__] = *beta * y[i__]; /* L20: */ } } } else { iy = ky; if (*beta == 0.) { i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { y[iy] = 0.; iy += *incy; /* L30: */ } } else { i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { y[iy] = *beta * y[iy]; iy += *incy; /* L40: */ } } } } if (*alpha == 0.) { return 0; } if (lsame_(uplo, "U")) { /* Form y when A is stored in upper triangle. */ if (*incx == 1 && *incy == 1) { i__1 = *n; for (j = 1; j <= i__1; ++j) { temp1 = *alpha * x[j]; temp2 = 0.; i__2 = j - 1; for (i__ = 1; i__ <= i__2; ++i__) { y[i__] += temp1 * a[i__ + j * a_dim1]; temp2 += a[i__ + j * a_dim1] * x[i__]; /* L50: */ } y[j] = y[j] + temp1 * a[j + j * a_dim1] + *alpha * temp2; /* L60: */ } } else { jx = kx; jy = ky; i__1 = *n; for (j = 1; j <= i__1; ++j) { temp1 = *alpha * x[jx]; temp2 = 0.; ix = kx; iy = ky; i__2 = j - 1; for (i__ = 1; i__ <= i__2; ++i__) { y[iy] += temp1 * a[i__ + j * a_dim1]; temp2 += a[i__ + j * a_dim1] * x[ix]; ix += *incx; iy += *incy; /* L70: */ } y[jy] = y[jy] + temp1 * a[j + j * a_dim1] + *alpha * temp2; jx += *incx; jy += *incy; /* L80: */ } } } else { /* Form y when A is stored in lower triangle. */ if (*incx == 1 && *incy == 1) { i__1 = *n; for (j = 1; j <= i__1; ++j) { temp1 = *alpha * x[j]; temp2 = 0.; y[j] += temp1 * a[j + j * a_dim1]; i__2 = *n; for (i__ = j + 1; i__ <= i__2; ++i__) { y[i__] += temp1 * a[i__ + j * a_dim1]; temp2 += a[i__ + j * a_dim1] * x[i__]; /* L90: */ } y[j] += *alpha * temp2; /* L100: */ } } else { jx = kx; jy = ky; i__1 = *n; for (j = 1; j <= i__1; ++j) { temp1 = *alpha * x[jx]; temp2 = 0.; y[jy] += temp1 * a[j + j * a_dim1]; ix = jx; iy = jy; i__2 = *n; for (i__ = j + 1; i__ <= i__2; ++i__) { ix += *incx; iy += *incy; y[iy] += temp1 * a[i__ + j * a_dim1]; temp2 += a[i__ + j * a_dim1] * x[ix]; /* L110: */ } y[jy] += *alpha * temp2; jx += *incx; jy += *incy; /* L120: */ } } } return 0; /* End of DSYMV . */ } /* dsymv_ */ /* Subroutine */ int dsyr2_(char *uplo, integer *n, doublereal *alpha, doublereal *x, integer *incx, doublereal *y, integer *incy, doublereal *a, integer *lda) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2; /* Local variables */ static integer i__, j, ix, iy, jx, jy, kx, ky, info; static doublereal temp1, temp2; extern logical lsame_(char *, char *); extern /* Subroutine */ int xerbla_(char *, integer *); /* Purpose ======= DSYR2 performs the symmetric rank 2 operation A := alpha*x*y' + alpha*y*x' + A, where alpha is a scalar, x and y are n element vectors and A is an n by n symmetric matrix. Parameters ========== UPLO - CHARACTER*1. On entry, UPLO specifies whether the upper or lower triangular part of the array A is to be referenced as follows: UPLO = 'U' or 'u' Only the upper triangular part of A is to be referenced. UPLO = 'L' or 'l' Only the lower triangular part of A is to be referenced. Unchanged on exit. N - INTEGER. On entry, N specifies the order of the matrix A. N must be at least zero. Unchanged on exit. ALPHA - DOUBLE PRECISION. On entry, ALPHA specifies the scalar alpha. Unchanged on exit. X - DOUBLE PRECISION array of dimension at least ( 1 + ( n - 1 )*abs( INCX ) ). Before entry, the incremented array X must contain the n element vector x. Unchanged on exit. INCX - INTEGER. On entry, INCX specifies the increment for the elements of X. INCX must not be zero. Unchanged on exit. Y - DOUBLE PRECISION array of dimension at least ( 1 + ( n - 1 )*abs( INCY ) ). Before entry, the incremented array Y must contain the n element vector y. Unchanged on exit. INCY - INTEGER. On entry, INCY specifies the increment for the elements of Y. INCY must not be zero. Unchanged on exit. A - DOUBLE PRECISION array of DIMENSION ( LDA, n ). Before entry with UPLO = 'U' or 'u', the leading n by n upper triangular part of the array A must contain the upper triangular part of the symmetric matrix and the strictly lower triangular part of A is not referenced. On exit, the upper triangular part of the array A is overwritten by the upper triangular part of the updated matrix. Before entry with UPLO = 'L' or 'l', the leading n by n lower triangular part of the array A must contain the lower triangular part of the symmetric matrix and the strictly upper triangular part of A is not referenced. On exit, the lower triangular part of the array A is overwritten by the lower triangular part of the updated matrix. LDA - INTEGER. On entry, LDA specifies the first dimension of A as declared in the calling (sub) program. LDA must be at least max( 1, n ). Unchanged on exit. Level 2 Blas routine. -- Written on 22-October-1986. Jack Dongarra, Argonne National Lab. Jeremy Du Croz, Nag Central Office. Sven Hammarling, Nag Central Office. Richard Hanson, Sandia National Labs. Test the input parameters. */ /* Parameter adjustments */ --x; --y; a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; /* Function Body */ info = 0; if (! lsame_(uplo, "U") && ! lsame_(uplo, "L")) { info = 1; } else if (*n < 0) { info = 2; } else if (*incx == 0) { info = 5; } else if (*incy == 0) { info = 7; } else if (*lda < max(1,*n)) { info = 9; } if (info != 0) { xerbla_("DSYR2 ", &info); return 0; } /* Quick return if possible. */ if ((*n == 0) || (*alpha == 0.)) { return 0; } /* Set up the start points in X and Y if the increments are not both unity. */ if ((*incx != 1) || (*incy != 1)) { if (*incx > 0) { kx = 1; } else { kx = 1 - (*n - 1) * *incx; } if (*incy > 0) { ky = 1; } else { ky = 1 - (*n - 1) * *incy; } jx = kx; jy = ky; } /* Start the operations. In this version the elements of A are accessed sequentially with one pass through the triangular part of A. */ if (lsame_(uplo, "U")) { /* Form A when A is stored in the upper triangle. */ if (*incx == 1 && *incy == 1) { i__1 = *n; for (j = 1; j <= i__1; ++j) { if ((x[j] != 0.) || (y[j] != 0.)) { temp1 = *alpha * y[j]; temp2 = *alpha * x[j]; i__2 = j; for (i__ = 1; i__ <= i__2; ++i__) { a[i__ + j * a_dim1] = a[i__ + j * a_dim1] + x[i__] * temp1 + y[i__] * temp2; /* L10: */ } } /* L20: */ } } else { i__1 = *n; for (j = 1; j <= i__1; ++j) { if ((x[jx] != 0.) || (y[jy] != 0.)) { temp1 = *alpha * y[jy]; temp2 = *alpha * x[jx]; ix = kx; iy = ky; i__2 = j; for (i__ = 1; i__ <= i__2; ++i__) { a[i__ + j * a_dim1] = a[i__ + j * a_dim1] + x[ix] * temp1 + y[iy] * temp2; ix += *incx; iy += *incy; /* L30: */ } } jx += *incx; jy += *incy; /* L40: */ } } } else { /* Form A when A is stored in the lower triangle. */ if (*incx == 1 && *incy == 1) { i__1 = *n; for (j = 1; j <= i__1; ++j) { if ((x[j] != 0.) || (y[j] != 0.)) { temp1 = *alpha * y[j]; temp2 = *alpha * x[j]; i__2 = *n; for (i__ = j; i__ <= i__2; ++i__) { a[i__ + j * a_dim1] = a[i__ + j * a_dim1] + x[i__] * temp1 + y[i__] * temp2; /* L50: */ } } /* L60: */ } } else { i__1 = *n; for (j = 1; j <= i__1; ++j) { if ((x[jx] != 0.) || (y[jy] != 0.)) { temp1 = *alpha * y[jy]; temp2 = *alpha * x[jx]; ix = jx; iy = jy; i__2 = *n; for (i__ = j; i__ <= i__2; ++i__) { a[i__ + j * a_dim1] = a[i__ + j * a_dim1] + x[ix] * temp1 + y[iy] * temp2; ix += *incx; iy += *incy; /* L70: */ } } jx += *incx; jy += *incy; /* L80: */ } } } return 0; /* End of DSYR2 . */ } /* dsyr2_ */ /* Subroutine */ int dsyr2k_(char *uplo, char *trans, integer *n, integer *k, doublereal *alpha, doublereal *a, integer *lda, doublereal *b, integer *ldb, doublereal *beta, doublereal *c__, integer *ldc) { /* System generated locals */ integer a_dim1, a_offset, b_dim1, b_offset, c_dim1, c_offset, i__1, i__2, i__3; /* Local variables */ static integer i__, j, l, info; static doublereal temp1, temp2; extern logical lsame_(char *, char *); static integer nrowa; static logical upper; extern /* Subroutine */ int xerbla_(char *, integer *); /* Purpose ======= DSYR2K performs one of the symmetric rank 2k operations C := alpha*A*B' + alpha*B*A' + beta*C, or C := alpha*A'*B + alpha*B'*A + beta*C, where alpha and beta are scalars, C is an n by n symmetric matrix and A and B are n by k matrices in the first case and k by n matrices in the second case. Parameters ========== UPLO - CHARACTER*1. On entry, UPLO specifies whether the upper or lower triangular part of the array C is to be referenced as follows: UPLO = 'U' or 'u' Only the upper triangular part of C is to be referenced. UPLO = 'L' or 'l' Only the lower triangular part of C is to be referenced. Unchanged on exit. TRANS - CHARACTER*1. On entry, TRANS specifies the operation to be performed as follows: TRANS = 'N' or 'n' C := alpha*A*B' + alpha*B*A' + beta*C. TRANS = 'T' or 't' C := alpha*A'*B + alpha*B'*A + beta*C. TRANS = 'C' or 'c' C := alpha*A'*B + alpha*B'*A + beta*C. Unchanged on exit. N - INTEGER. On entry, N specifies the order of the matrix C. N must be at least zero. Unchanged on exit. K - INTEGER. On entry with TRANS = 'N' or 'n', K specifies the number of columns of the matrices A and B, and on entry with TRANS = 'T' or 't' or 'C' or 'c', K specifies the number of rows of the matrices A and B. K must be at least zero. Unchanged on exit. ALPHA - DOUBLE PRECISION. On entry, ALPHA specifies the scalar alpha. Unchanged on exit. A - DOUBLE PRECISION array of DIMENSION ( LDA, ka ), where ka is k when TRANS = 'N' or 'n', and is n otherwise. Before entry with TRANS = 'N' or 'n', the leading n by k part of the array A must contain the matrix A, otherwise the leading k by n part of the array A must contain the matrix A. Unchanged on exit. LDA - INTEGER. On entry, LDA specifies the first dimension of A as declared in the calling (sub) program. When TRANS = 'N' or 'n' then LDA must be at least max( 1, n ), otherwise LDA must be at least max( 1, k ). Unchanged on exit. B - DOUBLE PRECISION array of DIMENSION ( LDB, kb ), where kb is k when TRANS = 'N' or 'n', and is n otherwise. Before entry with TRANS = 'N' or 'n', the leading n by k part of the array B must contain the matrix B, otherwise the leading k by n part of the array B must contain the matrix B. Unchanged on exit. LDB - INTEGER. On entry, LDB specifies the first dimension of B as declared in the calling (sub) program. When TRANS = 'N' or 'n' then LDB must be at least max( 1, n ), otherwise LDB must be at least max( 1, k ). Unchanged on exit. BETA - DOUBLE PRECISION. On entry, BETA specifies the scalar beta. Unchanged on exit. C - DOUBLE PRECISION array of DIMENSION ( LDC, n ). Before entry with UPLO = 'U' or 'u', the leading n by n upper triangular part of the array C must contain the upper triangular part of the symmetric matrix and the strictly lower triangular part of C is not referenced. On exit, the upper triangular part of the array C is overwritten by the upper triangular part of the updated matrix. Before entry with UPLO = 'L' or 'l', the leading n by n lower triangular part of the array C must contain the lower triangular part of the symmetric matrix and the strictly upper triangular part of C is not referenced. On exit, the lower triangular part of the array C is overwritten by the lower triangular part of the updated matrix. LDC - INTEGER. On entry, LDC specifies the first dimension of C as declared in the calling (sub) program. LDC must be at least max( 1, n ). Unchanged on exit. Level 3 Blas routine. -- Written on 8-February-1989. Jack Dongarra, Argonne National Laboratory. Iain Duff, AERE Harwell. Jeremy Du Croz, Numerical Algorithms Group Ltd. Sven Hammarling, Numerical Algorithms Group Ltd. Test the input parameters. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; b_dim1 = *ldb; b_offset = 1 + b_dim1; b -= b_offset; c_dim1 = *ldc; c_offset = 1 + c_dim1; c__ -= c_offset; /* Function Body */ if (lsame_(trans, "N")) { nrowa = *n; } else { nrowa = *k; } upper = lsame_(uplo, "U"); info = 0; if (! upper && ! lsame_(uplo, "L")) { info = 1; } else if (! lsame_(trans, "N") && ! lsame_(trans, "T") && ! lsame_(trans, "C")) { info = 2; } else if (*n < 0) { info = 3; } else if (*k < 0) { info = 4; } else if (*lda < max(1,nrowa)) { info = 7; } else if (*ldb < max(1,nrowa)) { info = 9; } else if (*ldc < max(1,*n)) { info = 12; } if (info != 0) { xerbla_("DSYR2K", &info); return 0; } /* Quick return if possible. */ if ((*n == 0) || (((*alpha == 0.) || (*k == 0)) && *beta == 1.)) { return 0; } /* And when alpha.eq.zero. */ if (*alpha == 0.) { if (upper) { if (*beta == 0.) { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = j; for (i__ = 1; i__ <= i__2; ++i__) { c__[i__ + j * c_dim1] = 0.; /* L10: */ } /* L20: */ } } else { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = j; for (i__ = 1; i__ <= i__2; ++i__) { c__[i__ + j * c_dim1] = *beta * c__[i__ + j * c_dim1]; /* L30: */ } /* L40: */ } } } else { if (*beta == 0.) { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *n; for (i__ = j; i__ <= i__2; ++i__) { c__[i__ + j * c_dim1] = 0.; /* L50: */ } /* L60: */ } } else { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *n; for (i__ = j; i__ <= i__2; ++i__) { c__[i__ + j * c_dim1] = *beta * c__[i__ + j * c_dim1]; /* L70: */ } /* L80: */ } } } return 0; } /* Start the operations. */ if (lsame_(trans, "N")) { /* Form C := alpha*A*B' + alpha*B*A' + C. */ if (upper) { i__1 = *n; for (j = 1; j <= i__1; ++j) { if (*beta == 0.) { i__2 = j; for (i__ = 1; i__ <= i__2; ++i__) { c__[i__ + j * c_dim1] = 0.; /* L90: */ } } else if (*beta != 1.) { i__2 = j; for (i__ = 1; i__ <= i__2; ++i__) { c__[i__ + j * c_dim1] = *beta * c__[i__ + j * c_dim1]; /* L100: */ } } i__2 = *k; for (l = 1; l <= i__2; ++l) { if ((a[j + l * a_dim1] != 0.) || (b[j + l * b_dim1] != 0.) ) { temp1 = *alpha * b[j + l * b_dim1]; temp2 = *alpha * a[j + l * a_dim1]; i__3 = j; for (i__ = 1; i__ <= i__3; ++i__) { c__[i__ + j * c_dim1] = c__[i__ + j * c_dim1] + a[ i__ + l * a_dim1] * temp1 + b[i__ + l * b_dim1] * temp2; /* L110: */ } } /* L120: */ } /* L130: */ } } else { i__1 = *n; for (j = 1; j <= i__1; ++j) { if (*beta == 0.) { i__2 = *n; for (i__ = j; i__ <= i__2; ++i__) { c__[i__ + j * c_dim1] = 0.; /* L140: */ } } else if (*beta != 1.) { i__2 = *n; for (i__ = j; i__ <= i__2; ++i__) { c__[i__ + j * c_dim1] = *beta * c__[i__ + j * c_dim1]; /* L150: */ } } i__2 = *k; for (l = 1; l <= i__2; ++l) { if ((a[j + l * a_dim1] != 0.) || (b[j + l * b_dim1] != 0.) ) { temp1 = *alpha * b[j + l * b_dim1]; temp2 = *alpha * a[j + l * a_dim1]; i__3 = *n; for (i__ = j; i__ <= i__3; ++i__) { c__[i__ + j * c_dim1] = c__[i__ + j * c_dim1] + a[ i__ + l * a_dim1] * temp1 + b[i__ + l * b_dim1] * temp2; /* L160: */ } } /* L170: */ } /* L180: */ } } } else { /* Form C := alpha*A'*B + alpha*B'*A + C. */ if (upper) { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = j; for (i__ = 1; i__ <= i__2; ++i__) { temp1 = 0.; temp2 = 0.; i__3 = *k; for (l = 1; l <= i__3; ++l) { temp1 += a[l + i__ * a_dim1] * b[l + j * b_dim1]; temp2 += b[l + i__ * b_dim1] * a[l + j * a_dim1]; /* L190: */ } if (*beta == 0.) { c__[i__ + j * c_dim1] = *alpha * temp1 + *alpha * temp2; } else { c__[i__ + j * c_dim1] = *beta * c__[i__ + j * c_dim1] + *alpha * temp1 + *alpha * temp2; } /* L200: */ } /* L210: */ } } else { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *n; for (i__ = j; i__ <= i__2; ++i__) { temp1 = 0.; temp2 = 0.; i__3 = *k; for (l = 1; l <= i__3; ++l) { temp1 += a[l + i__ * a_dim1] * b[l + j * b_dim1]; temp2 += b[l + i__ * b_dim1] * a[l + j * a_dim1]; /* L220: */ } if (*beta == 0.) { c__[i__ + j * c_dim1] = *alpha * temp1 + *alpha * temp2; } else { c__[i__ + j * c_dim1] = *beta * c__[i__ + j * c_dim1] + *alpha * temp1 + *alpha * temp2; } /* L230: */ } /* L240: */ } } } return 0; /* End of DSYR2K. */ } /* dsyr2k_ */ /* Subroutine */ int dsyrk_(char *uplo, char *trans, integer *n, integer *k, doublereal *alpha, doublereal *a, integer *lda, doublereal *beta, doublereal *c__, integer *ldc) { /* System generated locals */ integer a_dim1, a_offset, c_dim1, c_offset, i__1, i__2, i__3; /* Local variables */ static integer i__, j, l, info; static doublereal temp; extern logical lsame_(char *, char *); static integer nrowa; static logical upper; extern /* Subroutine */ int xerbla_(char *, integer *); /* Purpose ======= DSYRK performs one of the symmetric rank k operations C := alpha*A*A' + beta*C, or C := alpha*A'*A + beta*C, where alpha and beta are scalars, C is an n by n symmetric matrix and A is an n by k matrix in the first case and a k by n matrix in the second case. Parameters ========== UPLO - CHARACTER*1. On entry, UPLO specifies whether the upper or lower triangular part of the array C is to be referenced as follows: UPLO = 'U' or 'u' Only the upper triangular part of C is to be referenced. UPLO = 'L' or 'l' Only the lower triangular part of C is to be referenced. Unchanged on exit. TRANS - CHARACTER*1. On entry, TRANS specifies the operation to be performed as follows: TRANS = 'N' or 'n' C := alpha*A*A' + beta*C. TRANS = 'T' or 't' C := alpha*A'*A + beta*C. TRANS = 'C' or 'c' C := alpha*A'*A + beta*C. Unchanged on exit. N - INTEGER. On entry, N specifies the order of the matrix C. N must be at least zero. Unchanged on exit. K - INTEGER. On entry with TRANS = 'N' or 'n', K specifies the number of columns of the matrix A, and on entry with TRANS = 'T' or 't' or 'C' or 'c', K specifies the number of rows of the matrix A. K must be at least zero. Unchanged on exit. ALPHA - DOUBLE PRECISION. On entry, ALPHA specifies the scalar alpha. Unchanged on exit. A - DOUBLE PRECISION array of DIMENSION ( LDA, ka ), where ka is k when TRANS = 'N' or 'n', and is n otherwise. Before entry with TRANS = 'N' or 'n', the leading n by k part of the array A must contain the matrix A, otherwise the leading k by n part of the array A must contain the matrix A. Unchanged on exit. LDA - INTEGER. On entry, LDA specifies the first dimension of A as declared in the calling (sub) program. When TRANS = 'N' or 'n' then LDA must be at least max( 1, n ), otherwise LDA must be at least max( 1, k ). Unchanged on exit. BETA - DOUBLE PRECISION. On entry, BETA specifies the scalar beta. Unchanged on exit. C - DOUBLE PRECISION array of DIMENSION ( LDC, n ). Before entry with UPLO = 'U' or 'u', the leading n by n upper triangular part of the array C must contain the upper triangular part of the symmetric matrix and the strictly lower triangular part of C is not referenced. On exit, the upper triangular part of the array C is overwritten by the upper triangular part of the updated matrix. Before entry with UPLO = 'L' or 'l', the leading n by n lower triangular part of the array C must contain the lower triangular part of the symmetric matrix and the strictly upper triangular part of C is not referenced. On exit, the lower triangular part of the array C is overwritten by the lower triangular part of the updated matrix. LDC - INTEGER. On entry, LDC specifies the first dimension of C as declared in the calling (sub) program. LDC must be at least max( 1, n ). Unchanged on exit. Level 3 Blas routine. -- Written on 8-February-1989. Jack Dongarra, Argonne National Laboratory. Iain Duff, AERE Harwell. Jeremy Du Croz, Numerical Algorithms Group Ltd. Sven Hammarling, Numerical Algorithms Group Ltd. Test the input parameters. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; c_dim1 = *ldc; c_offset = 1 + c_dim1; c__ -= c_offset; /* Function Body */ if (lsame_(trans, "N")) { nrowa = *n; } else { nrowa = *k; } upper = lsame_(uplo, "U"); info = 0; if (! upper && ! lsame_(uplo, "L")) { info = 1; } else if (! lsame_(trans, "N") && ! lsame_(trans, "T") && ! lsame_(trans, "C")) { info = 2; } else if (*n < 0) { info = 3; } else if (*k < 0) { info = 4; } else if (*lda < max(1,nrowa)) { info = 7; } else if (*ldc < max(1,*n)) { info = 10; } if (info != 0) { xerbla_("DSYRK ", &info); return 0; } /* Quick return if possible. */ if ((*n == 0) || (((*alpha == 0.) || (*k == 0)) && *beta == 1.)) { return 0; } /* And when alpha.eq.zero. */ if (*alpha == 0.) { if (upper) { if (*beta == 0.) { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = j; for (i__ = 1; i__ <= i__2; ++i__) { c__[i__ + j * c_dim1] = 0.; /* L10: */ } /* L20: */ } } else { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = j; for (i__ = 1; i__ <= i__2; ++i__) { c__[i__ + j * c_dim1] = *beta * c__[i__ + j * c_dim1]; /* L30: */ } /* L40: */ } } } else { if (*beta == 0.) { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *n; for (i__ = j; i__ <= i__2; ++i__) { c__[i__ + j * c_dim1] = 0.; /* L50: */ } /* L60: */ } } else { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *n; for (i__ = j; i__ <= i__2; ++i__) { c__[i__ + j * c_dim1] = *beta * c__[i__ + j * c_dim1]; /* L70: */ } /* L80: */ } } } return 0; } /* Start the operations. */ if (lsame_(trans, "N")) { /* Form C := alpha*A*A' + beta*C. */ if (upper) { i__1 = *n; for (j = 1; j <= i__1; ++j) { if (*beta == 0.) { i__2 = j; for (i__ = 1; i__ <= i__2; ++i__) { c__[i__ + j * c_dim1] = 0.; /* L90: */ } } else if (*beta != 1.) { i__2 = j; for (i__ = 1; i__ <= i__2; ++i__) { c__[i__ + j * c_dim1] = *beta * c__[i__ + j * c_dim1]; /* L100: */ } } i__2 = *k; for (l = 1; l <= i__2; ++l) { if (a[j + l * a_dim1] != 0.) { temp = *alpha * a[j + l * a_dim1]; i__3 = j; for (i__ = 1; i__ <= i__3; ++i__) { c__[i__ + j * c_dim1] += temp * a[i__ + l * a_dim1]; /* L110: */ } } /* L120: */ } /* L130: */ } } else { i__1 = *n; for (j = 1; j <= i__1; ++j) { if (*beta == 0.) { i__2 = *n; for (i__ = j; i__ <= i__2; ++i__) { c__[i__ + j * c_dim1] = 0.; /* L140: */ } } else if (*beta != 1.) { i__2 = *n; for (i__ = j; i__ <= i__2; ++i__) { c__[i__ + j * c_dim1] = *beta * c__[i__ + j * c_dim1]; /* L150: */ } } i__2 = *k; for (l = 1; l <= i__2; ++l) { if (a[j + l * a_dim1] != 0.) { temp = *alpha * a[j + l * a_dim1]; i__3 = *n; for (i__ = j; i__ <= i__3; ++i__) { c__[i__ + j * c_dim1] += temp * a[i__ + l * a_dim1]; /* L160: */ } } /* L170: */ } /* L180: */ } } } else { /* Form C := alpha*A'*A + beta*C. */ if (upper) { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = j; for (i__ = 1; i__ <= i__2; ++i__) { temp = 0.; i__3 = *k; for (l = 1; l <= i__3; ++l) { temp += a[l + i__ * a_dim1] * a[l + j * a_dim1]; /* L190: */ } if (*beta == 0.) { c__[i__ + j * c_dim1] = *alpha * temp; } else { c__[i__ + j * c_dim1] = *alpha * temp + *beta * c__[ i__ + j * c_dim1]; } /* L200: */ } /* L210: */ } } else { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *n; for (i__ = j; i__ <= i__2; ++i__) { temp = 0.; i__3 = *k; for (l = 1; l <= i__3; ++l) { temp += a[l + i__ * a_dim1] * a[l + j * a_dim1]; /* L220: */ } if (*beta == 0.) { c__[i__ + j * c_dim1] = *alpha * temp; } else { c__[i__ + j * c_dim1] = *alpha * temp + *beta * c__[ i__ + j * c_dim1]; } /* L230: */ } /* L240: */ } } } return 0; /* End of DSYRK . */ } /* dsyrk_ */ /* Subroutine */ int dtrmm_(char *side, char *uplo, char *transa, char *diag, integer *m, integer *n, doublereal *alpha, doublereal *a, integer * lda, doublereal *b, integer *ldb) { /* System generated locals */ integer a_dim1, a_offset, b_dim1, b_offset, i__1, i__2, i__3; /* Local variables */ static integer i__, j, k, info; static doublereal temp; static logical lside; extern logical lsame_(char *, char *); static integer nrowa; static logical upper; extern /* Subroutine */ int xerbla_(char *, integer *); static logical nounit; /* Purpose ======= DTRMM performs one of the matrix-matrix operations B := alpha*op( A )*B, or B := alpha*B*op( A ), where alpha is a scalar, B is an m by n matrix, A is a unit, or non-unit, upper or lower triangular matrix and op( A ) is one of op( A ) = A or op( A ) = A'. Parameters ========== SIDE - CHARACTER*1. On entry, SIDE specifies whether op( A ) multiplies B from the left or right as follows: SIDE = 'L' or 'l' B := alpha*op( A )*B. SIDE = 'R' or 'r' B := alpha*B*op( A ). Unchanged on exit. UPLO - CHARACTER*1. On entry, UPLO specifies whether the matrix A is an upper or lower triangular matrix as follows: UPLO = 'U' or 'u' A is an upper triangular matrix. UPLO = 'L' or 'l' A is a lower triangular matrix. Unchanged on exit. TRANSA - CHARACTER*1. On entry, TRANSA specifies the form of op( A ) to be used in the matrix multiplication as follows: TRANSA = 'N' or 'n' op( A ) = A. TRANSA = 'T' or 't' op( A ) = A'. TRANSA = 'C' or 'c' op( A ) = A'. Unchanged on exit. DIAG - CHARACTER*1. On entry, DIAG specifies whether or not A is unit triangular as follows: DIAG = 'U' or 'u' A is assumed to be unit triangular. DIAG = 'N' or 'n' A is not assumed to be unit triangular. Unchanged on exit. M - INTEGER. On entry, M specifies the number of rows of B. M must be at least zero. Unchanged on exit. N - INTEGER. On entry, N specifies the number of columns of B. N must be at least zero. Unchanged on exit. ALPHA - DOUBLE PRECISION. On entry, ALPHA specifies the scalar alpha. When alpha is zero then A is not referenced and B need not be set before entry. Unchanged on exit. A - DOUBLE PRECISION array of DIMENSION ( LDA, k ), where k is m when SIDE = 'L' or 'l' and is n when SIDE = 'R' or 'r'. Before entry with UPLO = 'U' or 'u', the leading k by k upper triangular part of the array A must contain the upper triangular matrix and the strictly lower triangular part of A is not referenced. Before entry with UPLO = 'L' or 'l', the leading k by k lower triangular part of the array A must contain the lower triangular matrix and the strictly upper triangular part of A is not referenced. Note that when DIAG = 'U' or 'u', the diagonal elements of A are not referenced either, but are assumed to be unity. Unchanged on exit. LDA - INTEGER. On entry, LDA specifies the first dimension of A as declared in the calling (sub) program. When SIDE = 'L' or 'l' then LDA must be at least max( 1, m ), when SIDE = 'R' or 'r' then LDA must be at least max( 1, n ). Unchanged on exit. B - DOUBLE PRECISION array of DIMENSION ( LDB, n ). Before entry, the leading m by n part of the array B must contain the matrix B, and on exit is overwritten by the transformed matrix. LDB - INTEGER. On entry, LDB specifies the first dimension of B as declared in the calling (sub) program. LDB must be at least max( 1, m ). Unchanged on exit. Level 3 Blas routine. -- Written on 8-February-1989. Jack Dongarra, Argonne National Laboratory. Iain Duff, AERE Harwell. Jeremy Du Croz, Numerical Algorithms Group Ltd. Sven Hammarling, Numerical Algorithms Group Ltd. Test the input parameters. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; b_dim1 = *ldb; b_offset = 1 + b_dim1; b -= b_offset; /* Function Body */ lside = lsame_(side, "L"); if (lside) { nrowa = *m; } else { nrowa = *n; } nounit = lsame_(diag, "N"); upper = lsame_(uplo, "U"); info = 0; if (! lside && ! lsame_(side, "R")) { info = 1; } else if (! upper && ! lsame_(uplo, "L")) { info = 2; } else if (! lsame_(transa, "N") && ! lsame_(transa, "T") && ! lsame_(transa, "C")) { info = 3; } else if (! lsame_(diag, "U") && ! lsame_(diag, "N")) { info = 4; } else if (*m < 0) { info = 5; } else if (*n < 0) { info = 6; } else if (*lda < max(1,nrowa)) { info = 9; } else if (*ldb < max(1,*m)) { info = 11; } if (info != 0) { xerbla_("DTRMM ", &info); return 0; } /* Quick return if possible. */ if (*n == 0) { return 0; } /* And when alpha.eq.zero. */ if (*alpha == 0.) { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { b[i__ + j * b_dim1] = 0.; /* L10: */ } /* L20: */ } return 0; } /* Start the operations. */ if (lside) { if (lsame_(transa, "N")) { /* Form B := alpha*A*B. */ if (upper) { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (k = 1; k <= i__2; ++k) { if (b[k + j * b_dim1] != 0.) { temp = *alpha * b[k + j * b_dim1]; i__3 = k - 1; for (i__ = 1; i__ <= i__3; ++i__) { b[i__ + j * b_dim1] += temp * a[i__ + k * a_dim1]; /* L30: */ } if (nounit) { temp *= a[k + k * a_dim1]; } b[k + j * b_dim1] = temp; } /* L40: */ } /* L50: */ } } else { i__1 = *n; for (j = 1; j <= i__1; ++j) { for (k = *m; k >= 1; --k) { if (b[k + j * b_dim1] != 0.) { temp = *alpha * b[k + j * b_dim1]; b[k + j * b_dim1] = temp; if (nounit) { b[k + j * b_dim1] *= a[k + k * a_dim1]; } i__2 = *m; for (i__ = k + 1; i__ <= i__2; ++i__) { b[i__ + j * b_dim1] += temp * a[i__ + k * a_dim1]; /* L60: */ } } /* L70: */ } /* L80: */ } } } else { /* Form B := alpha*A'*B. */ if (upper) { i__1 = *n; for (j = 1; j <= i__1; ++j) { for (i__ = *m; i__ >= 1; --i__) { temp = b[i__ + j * b_dim1]; if (nounit) { temp *= a[i__ + i__ * a_dim1]; } i__2 = i__ - 1; for (k = 1; k <= i__2; ++k) { temp += a[k + i__ * a_dim1] * b[k + j * b_dim1]; /* L90: */ } b[i__ + j * b_dim1] = *alpha * temp; /* L100: */ } /* L110: */ } } else { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { temp = b[i__ + j * b_dim1]; if (nounit) { temp *= a[i__ + i__ * a_dim1]; } i__3 = *m; for (k = i__ + 1; k <= i__3; ++k) { temp += a[k + i__ * a_dim1] * b[k + j * b_dim1]; /* L120: */ } b[i__ + j * b_dim1] = *alpha * temp; /* L130: */ } /* L140: */ } } } } else { if (lsame_(transa, "N")) { /* Form B := alpha*B*A. */ if (upper) { for (j = *n; j >= 1; --j) { temp = *alpha; if (nounit) { temp *= a[j + j * a_dim1]; } i__1 = *m; for (i__ = 1; i__ <= i__1; ++i__) { b[i__ + j * b_dim1] = temp * b[i__ + j * b_dim1]; /* L150: */ } i__1 = j - 1; for (k = 1; k <= i__1; ++k) { if (a[k + j * a_dim1] != 0.) { temp = *alpha * a[k + j * a_dim1]; i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { b[i__ + j * b_dim1] += temp * b[i__ + k * b_dim1]; /* L160: */ } } /* L170: */ } /* L180: */ } } else { i__1 = *n; for (j = 1; j <= i__1; ++j) { temp = *alpha; if (nounit) { temp *= a[j + j * a_dim1]; } i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { b[i__ + j * b_dim1] = temp * b[i__ + j * b_dim1]; /* L190: */ } i__2 = *n; for (k = j + 1; k <= i__2; ++k) { if (a[k + j * a_dim1] != 0.) { temp = *alpha * a[k + j * a_dim1]; i__3 = *m; for (i__ = 1; i__ <= i__3; ++i__) { b[i__ + j * b_dim1] += temp * b[i__ + k * b_dim1]; /* L200: */ } } /* L210: */ } /* L220: */ } } } else { /* Form B := alpha*B*A'. */ if (upper) { i__1 = *n; for (k = 1; k <= i__1; ++k) { i__2 = k - 1; for (j = 1; j <= i__2; ++j) { if (a[j + k * a_dim1] != 0.) { temp = *alpha * a[j + k * a_dim1]; i__3 = *m; for (i__ = 1; i__ <= i__3; ++i__) { b[i__ + j * b_dim1] += temp * b[i__ + k * b_dim1]; /* L230: */ } } /* L240: */ } temp = *alpha; if (nounit) { temp *= a[k + k * a_dim1]; } if (temp != 1.) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { b[i__ + k * b_dim1] = temp * b[i__ + k * b_dim1]; /* L250: */ } } /* L260: */ } } else { for (k = *n; k >= 1; --k) { i__1 = *n; for (j = k + 1; j <= i__1; ++j) { if (a[j + k * a_dim1] != 0.) { temp = *alpha * a[j + k * a_dim1]; i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { b[i__ + j * b_dim1] += temp * b[i__ + k * b_dim1]; /* L270: */ } } /* L280: */ } temp = *alpha; if (nounit) { temp *= a[k + k * a_dim1]; } if (temp != 1.) { i__1 = *m; for (i__ = 1; i__ <= i__1; ++i__) { b[i__ + k * b_dim1] = temp * b[i__ + k * b_dim1]; /* L290: */ } } /* L300: */ } } } } return 0; /* End of DTRMM . */ } /* dtrmm_ */ /* Subroutine */ int dtrmv_(char *uplo, char *trans, char *diag, integer *n, doublereal *a, integer *lda, doublereal *x, integer *incx) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2; /* Local variables */ static integer i__, j, ix, jx, kx, info; static doublereal temp; extern logical lsame_(char *, char *); extern /* Subroutine */ int xerbla_(char *, integer *); static logical nounit; /* Purpose ======= DTRMV performs one of the matrix-vector operations x := A*x, or x := A'*x, where x is an n element vector and A is an n by n unit, or non-unit, upper or lower triangular matrix. Parameters ========== UPLO - CHARACTER*1. On entry, UPLO specifies whether the matrix is an upper or lower triangular matrix as follows: UPLO = 'U' or 'u' A is an upper triangular matrix. UPLO = 'L' or 'l' A is a lower triangular matrix. Unchanged on exit. TRANS - CHARACTER*1. On entry, TRANS specifies the operation to be performed as follows: TRANS = 'N' or 'n' x := A*x. TRANS = 'T' or 't' x := A'*x. TRANS = 'C' or 'c' x := A'*x. Unchanged on exit. DIAG - CHARACTER*1. On entry, DIAG specifies whether or not A is unit triangular as follows: DIAG = 'U' or 'u' A is assumed to be unit triangular. DIAG = 'N' or 'n' A is not assumed to be unit triangular. Unchanged on exit. N - INTEGER. On entry, N specifies the order of the matrix A. N must be at least zero. Unchanged on exit. A - DOUBLE PRECISION array of DIMENSION ( LDA, n ). Before entry with UPLO = 'U' or 'u', the leading n by n upper triangular part of the array A must contain the upper triangular matrix and the strictly lower triangular part of A is not referenced. Before entry with UPLO = 'L' or 'l', the leading n by n lower triangular part of the array A must contain the lower triangular matrix and the strictly upper triangular part of A is not referenced. Note that when DIAG = 'U' or 'u', the diagonal elements of A are not referenced either, but are assumed to be unity. Unchanged on exit. LDA - INTEGER. On entry, LDA specifies the first dimension of A as declared in the calling (sub) program. LDA must be at least max( 1, n ). Unchanged on exit. X - DOUBLE PRECISION array of dimension at least ( 1 + ( n - 1 )*abs( INCX ) ). Before entry, the incremented array X must contain the n element vector x. On exit, X is overwritten with the tranformed vector x. INCX - INTEGER. On entry, INCX specifies the increment for the elements of X. INCX must not be zero. Unchanged on exit. Level 2 Blas routine. -- Written on 22-October-1986. Jack Dongarra, Argonne National Lab. Jeremy Du Croz, Nag Central Office. Sven Hammarling, Nag Central Office. Richard Hanson, Sandia National Labs. Test the input parameters. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --x; /* Function Body */ info = 0; if (! lsame_(uplo, "U") && ! lsame_(uplo, "L")) { info = 1; } else if (! lsame_(trans, "N") && ! lsame_(trans, "T") && ! lsame_(trans, "C")) { info = 2; } else if (! lsame_(diag, "U") && ! lsame_(diag, "N")) { info = 3; } else if (*n < 0) { info = 4; } else if (*lda < max(1,*n)) { info = 6; } else if (*incx == 0) { info = 8; } if (info != 0) { xerbla_("DTRMV ", &info); return 0; } /* Quick return if possible. */ if (*n == 0) { return 0; } nounit = lsame_(diag, "N"); /* Set up the start point in X if the increment is not unity. This will be ( N - 1 )*INCX too small for descending loops. */ if (*incx <= 0) { kx = 1 - (*n - 1) * *incx; } else if (*incx != 1) { kx = 1; } /* Start the operations. In this version the elements of A are accessed sequentially with one pass through A. */ if (lsame_(trans, "N")) { /* Form x := A*x. */ if (lsame_(uplo, "U")) { if (*incx == 1) { i__1 = *n; for (j = 1; j <= i__1; ++j) { if (x[j] != 0.) { temp = x[j]; i__2 = j - 1; for (i__ = 1; i__ <= i__2; ++i__) { x[i__] += temp * a[i__ + j * a_dim1]; /* L10: */ } if (nounit) { x[j] *= a[j + j * a_dim1]; } } /* L20: */ } } else { jx = kx; i__1 = *n; for (j = 1; j <= i__1; ++j) { if (x[jx] != 0.) { temp = x[jx]; ix = kx; i__2 = j - 1; for (i__ = 1; i__ <= i__2; ++i__) { x[ix] += temp * a[i__ + j * a_dim1]; ix += *incx; /* L30: */ } if (nounit) { x[jx] *= a[j + j * a_dim1]; } } jx += *incx; /* L40: */ } } } else { if (*incx == 1) { for (j = *n; j >= 1; --j) { if (x[j] != 0.) { temp = x[j]; i__1 = j + 1; for (i__ = *n; i__ >= i__1; --i__) { x[i__] += temp * a[i__ + j * a_dim1]; /* L50: */ } if (nounit) { x[j] *= a[j + j * a_dim1]; } } /* L60: */ } } else { kx += (*n - 1) * *incx; jx = kx; for (j = *n; j >= 1; --j) { if (x[jx] != 0.) { temp = x[jx]; ix = kx; i__1 = j + 1; for (i__ = *n; i__ >= i__1; --i__) { x[ix] += temp * a[i__ + j * a_dim1]; ix -= *incx; /* L70: */ } if (nounit) { x[jx] *= a[j + j * a_dim1]; } } jx -= *incx; /* L80: */ } } } } else { /* Form x := A'*x. */ if (lsame_(uplo, "U")) { if (*incx == 1) { for (j = *n; j >= 1; --j) { temp = x[j]; if (nounit) { temp *= a[j + j * a_dim1]; } for (i__ = j - 1; i__ >= 1; --i__) { temp += a[i__ + j * a_dim1] * x[i__]; /* L90: */ } x[j] = temp; /* L100: */ } } else { jx = kx + (*n - 1) * *incx; for (j = *n; j >= 1; --j) { temp = x[jx]; ix = jx; if (nounit) { temp *= a[j + j * a_dim1]; } for (i__ = j - 1; i__ >= 1; --i__) { ix -= *incx; temp += a[i__ + j * a_dim1] * x[ix]; /* L110: */ } x[jx] = temp; jx -= *incx; /* L120: */ } } } else { if (*incx == 1) { i__1 = *n; for (j = 1; j <= i__1; ++j) { temp = x[j]; if (nounit) { temp *= a[j + j * a_dim1]; } i__2 = *n; for (i__ = j + 1; i__ <= i__2; ++i__) { temp += a[i__ + j * a_dim1] * x[i__]; /* L130: */ } x[j] = temp; /* L140: */ } } else { jx = kx; i__1 = *n; for (j = 1; j <= i__1; ++j) { temp = x[jx]; ix = jx; if (nounit) { temp *= a[j + j * a_dim1]; } i__2 = *n; for (i__ = j + 1; i__ <= i__2; ++i__) { ix += *incx; temp += a[i__ + j * a_dim1] * x[ix]; /* L150: */ } x[jx] = temp; jx += *incx; /* L160: */ } } } } return 0; /* End of DTRMV . */ } /* dtrmv_ */ /* Subroutine */ int dtrsm_(char *side, char *uplo, char *transa, char *diag, integer *m, integer *n, doublereal *alpha, doublereal *a, integer * lda, doublereal *b, integer *ldb) { /* System generated locals */ integer a_dim1, a_offset, b_dim1, b_offset, i__1, i__2, i__3; /* Local variables */ static integer i__, j, k, info; static doublereal temp; static logical lside; extern logical lsame_(char *, char *); static integer nrowa; static logical upper; extern /* Subroutine */ int xerbla_(char *, integer *); static logical nounit; /* Purpose ======= DTRSM solves one of the matrix equations op( A )*X = alpha*B, or X*op( A ) = alpha*B, where alpha is a scalar, X and B are m by n matrices, A is a unit, or non-unit, upper or lower triangular matrix and op( A ) is one of op( A ) = A or op( A ) = A'. The matrix X is overwritten on B. Parameters ========== SIDE - CHARACTER*1. On entry, SIDE specifies whether op( A ) appears on the left or right of X as follows: SIDE = 'L' or 'l' op( A )*X = alpha*B. SIDE = 'R' or 'r' X*op( A ) = alpha*B. Unchanged on exit. UPLO - CHARACTER*1. On entry, UPLO specifies whether the matrix A is an upper or lower triangular matrix as follows: UPLO = 'U' or 'u' A is an upper triangular matrix. UPLO = 'L' or 'l' A is a lower triangular matrix. Unchanged on exit. TRANSA - CHARACTER*1. On entry, TRANSA specifies the form of op( A ) to be used in the matrix multiplication as follows: TRANSA = 'N' or 'n' op( A ) = A. TRANSA = 'T' or 't' op( A ) = A'. TRANSA = 'C' or 'c' op( A ) = A'. Unchanged on exit. DIAG - CHARACTER*1. On entry, DIAG specifies whether or not A is unit triangular as follows: DIAG = 'U' or 'u' A is assumed to be unit triangular. DIAG = 'N' or 'n' A is not assumed to be unit triangular. Unchanged on exit. M - INTEGER. On entry, M specifies the number of rows of B. M must be at least zero. Unchanged on exit. N - INTEGER. On entry, N specifies the number of columns of B. N must be at least zero. Unchanged on exit. ALPHA - DOUBLE PRECISION. On entry, ALPHA specifies the scalar alpha. When alpha is zero then A is not referenced and B need not be set before entry. Unchanged on exit. A - DOUBLE PRECISION array of DIMENSION ( LDA, k ), where k is m when SIDE = 'L' or 'l' and is n when SIDE = 'R' or 'r'. Before entry with UPLO = 'U' or 'u', the leading k by k upper triangular part of the array A must contain the upper triangular matrix and the strictly lower triangular part of A is not referenced. Before entry with UPLO = 'L' or 'l', the leading k by k lower triangular part of the array A must contain the lower triangular matrix and the strictly upper triangular part of A is not referenced. Note that when DIAG = 'U' or 'u', the diagonal elements of A are not referenced either, but are assumed to be unity. Unchanged on exit. LDA - INTEGER. On entry, LDA specifies the first dimension of A as declared in the calling (sub) program. When SIDE = 'L' or 'l' then LDA must be at least max( 1, m ), when SIDE = 'R' or 'r' then LDA must be at least max( 1, n ). Unchanged on exit. B - DOUBLE PRECISION array of DIMENSION ( LDB, n ). Before entry, the leading m by n part of the array B must contain the right-hand side matrix B, and on exit is overwritten by the solution matrix X. LDB - INTEGER. On entry, LDB specifies the first dimension of B as declared in the calling (sub) program. LDB must be at least max( 1, m ). Unchanged on exit. Level 3 Blas routine. -- Written on 8-February-1989. Jack Dongarra, Argonne National Laboratory. Iain Duff, AERE Harwell. Jeremy Du Croz, Numerical Algorithms Group Ltd. Sven Hammarling, Numerical Algorithms Group Ltd. Test the input parameters. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; b_dim1 = *ldb; b_offset = 1 + b_dim1; b -= b_offset; /* Function Body */ lside = lsame_(side, "L"); if (lside) { nrowa = *m; } else { nrowa = *n; } nounit = lsame_(diag, "N"); upper = lsame_(uplo, "U"); info = 0; if (! lside && ! lsame_(side, "R")) { info = 1; } else if (! upper && ! lsame_(uplo, "L")) { info = 2; } else if (! lsame_(transa, "N") && ! lsame_(transa, "T") && ! lsame_(transa, "C")) { info = 3; } else if (! lsame_(diag, "U") && ! lsame_(diag, "N")) { info = 4; } else if (*m < 0) { info = 5; } else if (*n < 0) { info = 6; } else if (*lda < max(1,nrowa)) { info = 9; } else if (*ldb < max(1,*m)) { info = 11; } if (info != 0) { xerbla_("DTRSM ", &info); return 0; } /* Quick return if possible. */ if (*n == 0) { return 0; } /* And when alpha.eq.zero. */ if (*alpha == 0.) { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { b[i__ + j * b_dim1] = 0.; /* L10: */ } /* L20: */ } return 0; } /* Start the operations. */ if (lside) { if (lsame_(transa, "N")) { /* Form B := alpha*inv( A )*B. */ if (upper) { i__1 = *n; for (j = 1; j <= i__1; ++j) { if (*alpha != 1.) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { b[i__ + j * b_dim1] = *alpha * b[i__ + j * b_dim1] ; /* L30: */ } } for (k = *m; k >= 1; --k) { if (b[k + j * b_dim1] != 0.) { if (nounit) { b[k + j * b_dim1] /= a[k + k * a_dim1]; } i__2 = k - 1; for (i__ = 1; i__ <= i__2; ++i__) { b[i__ + j * b_dim1] -= b[k + j * b_dim1] * a[ i__ + k * a_dim1]; /* L40: */ } } /* L50: */ } /* L60: */ } } else { i__1 = *n; for (j = 1; j <= i__1; ++j) { if (*alpha != 1.) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { b[i__ + j * b_dim1] = *alpha * b[i__ + j * b_dim1] ; /* L70: */ } } i__2 = *m; for (k = 1; k <= i__2; ++k) { if (b[k + j * b_dim1] != 0.) { if (nounit) { b[k + j * b_dim1] /= a[k + k * a_dim1]; } i__3 = *m; for (i__ = k + 1; i__ <= i__3; ++i__) { b[i__ + j * b_dim1] -= b[k + j * b_dim1] * a[ i__ + k * a_dim1]; /* L80: */ } } /* L90: */ } /* L100: */ } } } else { /* Form B := alpha*inv( A' )*B. */ if (upper) { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { temp = *alpha * b[i__ + j * b_dim1]; i__3 = i__ - 1; for (k = 1; k <= i__3; ++k) { temp -= a[k + i__ * a_dim1] * b[k + j * b_dim1]; /* L110: */ } if (nounit) { temp /= a[i__ + i__ * a_dim1]; } b[i__ + j * b_dim1] = temp; /* L120: */ } /* L130: */ } } else { i__1 = *n; for (j = 1; j <= i__1; ++j) { for (i__ = *m; i__ >= 1; --i__) { temp = *alpha * b[i__ + j * b_dim1]; i__2 = *m; for (k = i__ + 1; k <= i__2; ++k) { temp -= a[k + i__ * a_dim1] * b[k + j * b_dim1]; /* L140: */ } if (nounit) { temp /= a[i__ + i__ * a_dim1]; } b[i__ + j * b_dim1] = temp; /* L150: */ } /* L160: */ } } } } else { if (lsame_(transa, "N")) { /* Form B := alpha*B*inv( A ). */ if (upper) { i__1 = *n; for (j = 1; j <= i__1; ++j) { if (*alpha != 1.) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { b[i__ + j * b_dim1] = *alpha * b[i__ + j * b_dim1] ; /* L170: */ } } i__2 = j - 1; for (k = 1; k <= i__2; ++k) { if (a[k + j * a_dim1] != 0.) { i__3 = *m; for (i__ = 1; i__ <= i__3; ++i__) { b[i__ + j * b_dim1] -= a[k + j * a_dim1] * b[ i__ + k * b_dim1]; /* L180: */ } } /* L190: */ } if (nounit) { temp = 1. / a[j + j * a_dim1]; i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { b[i__ + j * b_dim1] = temp * b[i__ + j * b_dim1]; /* L200: */ } } /* L210: */ } } else { for (j = *n; j >= 1; --j) { if (*alpha != 1.) { i__1 = *m; for (i__ = 1; i__ <= i__1; ++i__) { b[i__ + j * b_dim1] = *alpha * b[i__ + j * b_dim1] ; /* L220: */ } } i__1 = *n; for (k = j + 1; k <= i__1; ++k) { if (a[k + j * a_dim1] != 0.) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { b[i__ + j * b_dim1] -= a[k + j * a_dim1] * b[ i__ + k * b_dim1]; /* L230: */ } } /* L240: */ } if (nounit) { temp = 1. / a[j + j * a_dim1]; i__1 = *m; for (i__ = 1; i__ <= i__1; ++i__) { b[i__ + j * b_dim1] = temp * b[i__ + j * b_dim1]; /* L250: */ } } /* L260: */ } } } else { /* Form B := alpha*B*inv( A' ). */ if (upper) { for (k = *n; k >= 1; --k) { if (nounit) { temp = 1. / a[k + k * a_dim1]; i__1 = *m; for (i__ = 1; i__ <= i__1; ++i__) { b[i__ + k * b_dim1] = temp * b[i__ + k * b_dim1]; /* L270: */ } } i__1 = k - 1; for (j = 1; j <= i__1; ++j) { if (a[j + k * a_dim1] != 0.) { temp = a[j + k * a_dim1]; i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { b[i__ + j * b_dim1] -= temp * b[i__ + k * b_dim1]; /* L280: */ } } /* L290: */ } if (*alpha != 1.) { i__1 = *m; for (i__ = 1; i__ <= i__1; ++i__) { b[i__ + k * b_dim1] = *alpha * b[i__ + k * b_dim1] ; /* L300: */ } } /* L310: */ } } else { i__1 = *n; for (k = 1; k <= i__1; ++k) { if (nounit) { temp = 1. / a[k + k * a_dim1]; i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { b[i__ + k * b_dim1] = temp * b[i__ + k * b_dim1]; /* L320: */ } } i__2 = *n; for (j = k + 1; j <= i__2; ++j) { if (a[j + k * a_dim1] != 0.) { temp = a[j + k * a_dim1]; i__3 = *m; for (i__ = 1; i__ <= i__3; ++i__) { b[i__ + j * b_dim1] -= temp * b[i__ + k * b_dim1]; /* L330: */ } } /* L340: */ } if (*alpha != 1.) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { b[i__ + k * b_dim1] = *alpha * b[i__ + k * b_dim1] ; /* L350: */ } } /* L360: */ } } } } return 0; /* End of DTRSM . */ } /* dtrsm_ */ doublereal dzasum_(integer *n, doublecomplex *zx, integer *incx) { /* System generated locals */ integer i__1; doublereal ret_val; /* Local variables */ static integer i__, ix; static doublereal stemp; extern doublereal dcabs1_(doublecomplex *); /* takes the sum of the absolute values. jack dongarra, 3/11/78. modified 3/93 to return if incx .le. 0. modified 12/3/93, array(1) declarations changed to array(*) */ /* Parameter adjustments */ --zx; /* Function Body */ ret_val = 0.; stemp = 0.; if ((*n <= 0) || (*incx <= 0)) { return ret_val; } if (*incx == 1) { goto L20; } /* code for increment not equal to 1 */ ix = 1; i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { stemp += dcabs1_(&zx[ix]); ix += *incx; /* L10: */ } ret_val = stemp; return ret_val; /* code for increment equal to 1 */ L20: i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { stemp += dcabs1_(&zx[i__]); /* L30: */ } ret_val = stemp; return ret_val; } /* dzasum_ */ doublereal dznrm2_(integer *n, doublecomplex *x, integer *incx) { /* System generated locals */ integer i__1, i__2, i__3; doublereal ret_val, d__1; /* Builtin functions */ double d_imag(doublecomplex *), sqrt(doublereal); /* Local variables */ static integer ix; static doublereal ssq, temp, norm, scale; /* DZNRM2 returns the euclidean norm of a vector via the function name, so that DZNRM2 := sqrt( conjg( x' )*x ) -- This version written on 25-October-1982. Modified on 14-October-1993 to inline the call to ZLASSQ. Sven Hammarling, Nag Ltd. */ /* Parameter adjustments */ --x; /* Function Body */ if ((*n < 1) || (*incx < 1)) { norm = 0.; } else { scale = 0.; ssq = 1.; /* The following loop is equivalent to this call to the LAPACK auxiliary routine: CALL ZLASSQ( N, X, INCX, SCALE, SSQ ) */ i__1 = (*n - 1) * *incx + 1; i__2 = *incx; for (ix = 1; i__2 < 0 ? ix >= i__1 : ix <= i__1; ix += i__2) { i__3 = ix; if (x[i__3].r != 0.) { i__3 = ix; temp = (d__1 = x[i__3].r, abs(d__1)); if (scale < temp) { /* Computing 2nd power */ d__1 = scale / temp; ssq = ssq * (d__1 * d__1) + 1.; scale = temp; } else { /* Computing 2nd power */ d__1 = temp / scale; ssq += d__1 * d__1; } } if (d_imag(&x[ix]) != 0.) { temp = (d__1 = d_imag(&x[ix]), abs(d__1)); if (scale < temp) { /* Computing 2nd power */ d__1 = scale / temp; ssq = ssq * (d__1 * d__1) + 1.; scale = temp; } else { /* Computing 2nd power */ d__1 = temp / scale; ssq += d__1 * d__1; } } /* L10: */ } norm = scale * sqrt(ssq); } ret_val = norm; return ret_val; /* End of DZNRM2. */ } /* dznrm2_ */ integer icamax_(integer *n, complex *cx, integer *incx) { /* System generated locals */ integer ret_val, i__1, i__2; real r__1, r__2; /* Builtin functions */ double r_imag(complex *); /* Local variables */ static integer i__, ix; static real smax; /* finds the index of element having max. absolute value. jack dongarra, linpack, 3/11/78. modified 3/93 to return if incx .le. 0. modified 12/3/93, array(1) declarations changed to array(*) */ /* Parameter adjustments */ --cx; /* Function Body */ ret_val = 0; if ((*n < 1) || (*incx <= 0)) { return ret_val; } ret_val = 1; if (*n == 1) { return ret_val; } if (*incx == 1) { goto L20; } /* code for increment not equal to 1 */ ix = 1; smax = (r__1 = cx[1].r, dabs(r__1)) + (r__2 = r_imag(&cx[1]), dabs(r__2)); ix += *incx; i__1 = *n; for (i__ = 2; i__ <= i__1; ++i__) { i__2 = ix; if ((r__1 = cx[i__2].r, dabs(r__1)) + (r__2 = r_imag(&cx[ix]), dabs( r__2)) <= smax) { goto L5; } ret_val = i__; i__2 = ix; smax = (r__1 = cx[i__2].r, dabs(r__1)) + (r__2 = r_imag(&cx[ix]), dabs(r__2)); L5: ix += *incx; /* L10: */ } return ret_val; /* code for increment equal to 1 */ L20: smax = (r__1 = cx[1].r, dabs(r__1)) + (r__2 = r_imag(&cx[1]), dabs(r__2)); i__1 = *n; for (i__ = 2; i__ <= i__1; ++i__) { i__2 = i__; if ((r__1 = cx[i__2].r, dabs(r__1)) + (r__2 = r_imag(&cx[i__]), dabs( r__2)) <= smax) { goto L30; } ret_val = i__; i__2 = i__; smax = (r__1 = cx[i__2].r, dabs(r__1)) + (r__2 = r_imag(&cx[i__]), dabs(r__2)); L30: ; } return ret_val; } /* icamax_ */ integer idamax_(integer *n, doublereal *dx, integer *incx) { /* System generated locals */ integer ret_val, i__1; doublereal d__1; /* Local variables */ static integer i__, ix; static doublereal dmax__; /* finds the index of element having max. absolute value. jack dongarra, linpack, 3/11/78. modified 3/93 to return if incx .le. 0. modified 12/3/93, array(1) declarations changed to array(*) */ /* Parameter adjustments */ --dx; /* Function Body */ ret_val = 0; if ((*n < 1) || (*incx <= 0)) { return ret_val; } ret_val = 1; if (*n == 1) { return ret_val; } if (*incx == 1) { goto L20; } /* code for increment not equal to 1 */ ix = 1; dmax__ = abs(dx[1]); ix += *incx; i__1 = *n; for (i__ = 2; i__ <= i__1; ++i__) { if ((d__1 = dx[ix], abs(d__1)) <= dmax__) { goto L5; } ret_val = i__; dmax__ = (d__1 = dx[ix], abs(d__1)); L5: ix += *incx; /* L10: */ } return ret_val; /* code for increment equal to 1 */ L20: dmax__ = abs(dx[1]); i__1 = *n; for (i__ = 2; i__ <= i__1; ++i__) { if ((d__1 = dx[i__], abs(d__1)) <= dmax__) { goto L30; } ret_val = i__; dmax__ = (d__1 = dx[i__], abs(d__1)); L30: ; } return ret_val; } /* idamax_ */ integer isamax_(integer *n, real *sx, integer *incx) { /* System generated locals */ integer ret_val, i__1; real r__1; /* Local variables */ static integer i__, ix; static real smax; /* finds the index of element having max. absolute value. jack dongarra, linpack, 3/11/78. modified 3/93 to return if incx .le. 0. modified 12/3/93, array(1) declarations changed to array(*) */ /* Parameter adjustments */ --sx; /* Function Body */ ret_val = 0; if ((*n < 1) || (*incx <= 0)) { return ret_val; } ret_val = 1; if (*n == 1) { return ret_val; } if (*incx == 1) { goto L20; } /* code for increment not equal to 1 */ ix = 1; smax = dabs(sx[1]); ix += *incx; i__1 = *n; for (i__ = 2; i__ <= i__1; ++i__) { if ((r__1 = sx[ix], dabs(r__1)) <= smax) { goto L5; } ret_val = i__; smax = (r__1 = sx[ix], dabs(r__1)); L5: ix += *incx; /* L10: */ } return ret_val; /* code for increment equal to 1 */ L20: smax = dabs(sx[1]); i__1 = *n; for (i__ = 2; i__ <= i__1; ++i__) { if ((r__1 = sx[i__], dabs(r__1)) <= smax) { goto L30; } ret_val = i__; smax = (r__1 = sx[i__], dabs(r__1)); L30: ; } return ret_val; } /* isamax_ */ integer izamax_(integer *n, doublecomplex *zx, integer *incx) { /* System generated locals */ integer ret_val, i__1; /* Local variables */ static integer i__, ix; static doublereal smax; extern doublereal dcabs1_(doublecomplex *); /* finds the index of element having max. absolute value. jack dongarra, 1/15/85. modified 3/93 to return if incx .le. 0. modified 12/3/93, array(1) declarations changed to array(*) */ /* Parameter adjustments */ --zx; /* Function Body */ ret_val = 0; if ((*n < 1) || (*incx <= 0)) { return ret_val; } ret_val = 1; if (*n == 1) { return ret_val; } if (*incx == 1) { goto L20; } /* code for increment not equal to 1 */ ix = 1; smax = dcabs1_(&zx[1]); ix += *incx; i__1 = *n; for (i__ = 2; i__ <= i__1; ++i__) { if (dcabs1_(&zx[ix]) <= smax) { goto L5; } ret_val = i__; smax = dcabs1_(&zx[ix]); L5: ix += *incx; /* L10: */ } return ret_val; /* code for increment equal to 1 */ L20: smax = dcabs1_(&zx[1]); i__1 = *n; for (i__ = 2; i__ <= i__1; ++i__) { if (dcabs1_(&zx[i__]) <= smax) { goto L30; } ret_val = i__; smax = dcabs1_(&zx[i__]); L30: ; } return ret_val; } /* izamax_ */ logical lsame_(char *ca, char *cb) { /* System generated locals */ logical ret_val; /* Local variables */ static integer inta, intb, zcode; /* -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University September 30, 1994 Purpose ======= LSAME returns .TRUE. if CA is the same letter as CB regardless of case. Arguments ========= CA (input) CHARACTER*1 CB (input) CHARACTER*1 CA and CB specify the single characters to be compared. ===================================================================== Test if the characters are equal */ ret_val = *(unsigned char *)ca == *(unsigned char *)cb; if (ret_val) { return ret_val; } /* Now test for equivalence if both characters are alphabetic. */ zcode = 'Z'; /* Use 'Z' rather than 'A' so that ASCII can be detected on Prime machines, on which ICHAR returns a value with bit 8 set. ICHAR('A') on Prime machines returns 193 which is the same as ICHAR('A') on an EBCDIC machine. */ inta = *(unsigned char *)ca; intb = *(unsigned char *)cb; if ((zcode == 90) || (zcode == 122)) { /* ASCII is assumed - ZCODE is the ASCII code of either lower or upper case 'Z'. */ if (inta >= 97 && inta <= 122) { inta += -32; } if (intb >= 97 && intb <= 122) { intb += -32; } } else if ((zcode == 233) || (zcode == 169)) { /* EBCDIC is assumed - ZCODE is the EBCDIC code of either lower or upper case 'Z'. */ if (((inta >= 129 && inta <= 137) || (inta >= 145 && inta <= 153)) || (inta >= 162 && inta <= 169)) { inta += 64; } if (((intb >= 129 && intb <= 137) || (intb >= 145 && intb <= 153)) || (intb >= 162 && intb <= 169)) { intb += 64; } } else if ((zcode == 218) || (zcode == 250)) { /* ASCII is assumed, on Prime machines - ZCODE is the ASCII code plus 128 of either lower or upper case 'Z'. */ if (inta >= 225 && inta <= 250) { inta += -32; } if (intb >= 225 && intb <= 250) { intb += -32; } } ret_val = inta == intb; /* RETURN End of LSAME */ return ret_val; } /* lsame_ */ /* Subroutine */ int saxpy_(integer *n, real *sa, real *sx, integer *incx, real *sy, integer *incy) { /* System generated locals */ integer i__1; /* Local variables */ static integer i__, m, ix, iy, mp1; /* constant times a vector plus a vector. uses unrolled loop for increments equal to one. jack dongarra, linpack, 3/11/78. modified 12/3/93, array(1) declarations changed to array(*) */ /* Parameter adjustments */ --sy; --sx; /* Function Body */ if (*n <= 0) { return 0; } if (*sa == 0.f) { return 0; } if (*incx == 1 && *incy == 1) { goto L20; } /* code for unequal increments or equal increments not equal to 1 */ ix = 1; iy = 1; if (*incx < 0) { ix = (-(*n) + 1) * *incx + 1; } if (*incy < 0) { iy = (-(*n) + 1) * *incy + 1; } i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { sy[iy] += *sa * sx[ix]; ix += *incx; iy += *incy; /* L10: */ } return 0; /* code for both increments equal to 1 clean-up loop */ L20: m = *n % 4; if (m == 0) { goto L40; } i__1 = m; for (i__ = 1; i__ <= i__1; ++i__) { sy[i__] += *sa * sx[i__]; /* L30: */ } if (*n < 4) { return 0; } L40: mp1 = m + 1; i__1 = *n; for (i__ = mp1; i__ <= i__1; i__ += 4) { sy[i__] += *sa * sx[i__]; sy[i__ + 1] += *sa * sx[i__ + 1]; sy[i__ + 2] += *sa * sx[i__ + 2]; sy[i__ + 3] += *sa * sx[i__ + 3]; /* L50: */ } return 0; } /* saxpy_ */ doublereal scasum_(integer *n, complex *cx, integer *incx) { /* System generated locals */ integer i__1, i__2, i__3; real ret_val, r__1, r__2; /* Builtin functions */ double r_imag(complex *); /* Local variables */ static integer i__, nincx; static real stemp; /* takes the sum of the absolute values of a complex vector and returns a single precision result. jack dongarra, linpack, 3/11/78. modified 3/93 to return if incx .le. 0. modified 12/3/93, array(1) declarations changed to array(*) */ /* Parameter adjustments */ --cx; /* Function Body */ ret_val = 0.f; stemp = 0.f; if ((*n <= 0) || (*incx <= 0)) { return ret_val; } if (*incx == 1) { goto L20; } /* code for increment not equal to 1 */ nincx = *n * *incx; i__1 = nincx; i__2 = *incx; for (i__ = 1; i__2 < 0 ? i__ >= i__1 : i__ <= i__1; i__ += i__2) { i__3 = i__; stemp = stemp + (r__1 = cx[i__3].r, dabs(r__1)) + (r__2 = r_imag(&cx[ i__]), dabs(r__2)); /* L10: */ } ret_val = stemp; return ret_val; /* code for increment equal to 1 */ L20: i__2 = *n; for (i__ = 1; i__ <= i__2; ++i__) { i__1 = i__; stemp = stemp + (r__1 = cx[i__1].r, dabs(r__1)) + (r__2 = r_imag(&cx[ i__]), dabs(r__2)); /* L30: */ } ret_val = stemp; return ret_val; } /* scasum_ */ doublereal scnrm2_(integer *n, complex *x, integer *incx) { /* System generated locals */ integer i__1, i__2, i__3; real ret_val, r__1; /* Builtin functions */ double r_imag(complex *), sqrt(doublereal); /* Local variables */ static integer ix; static real ssq, temp, norm, scale; /* SCNRM2 returns the euclidean norm of a vector via the function name, so that SCNRM2 := sqrt( conjg( x' )*x ) -- This version written on 25-October-1982. Modified on 14-October-1993 to inline the call to CLASSQ. Sven Hammarling, Nag Ltd. */ /* Parameter adjustments */ --x; /* Function Body */ if ((*n < 1) || (*incx < 1)) { norm = 0.f; } else { scale = 0.f; ssq = 1.f; /* The following loop is equivalent to this call to the LAPACK auxiliary routine: CALL CLASSQ( N, X, INCX, SCALE, SSQ ) */ i__1 = (*n - 1) * *incx + 1; i__2 = *incx; for (ix = 1; i__2 < 0 ? ix >= i__1 : ix <= i__1; ix += i__2) { i__3 = ix; if (x[i__3].r != 0.f) { i__3 = ix; temp = (r__1 = x[i__3].r, dabs(r__1)); if (scale < temp) { /* Computing 2nd power */ r__1 = scale / temp; ssq = ssq * (r__1 * r__1) + 1.f; scale = temp; } else { /* Computing 2nd power */ r__1 = temp / scale; ssq += r__1 * r__1; } } if (r_imag(&x[ix]) != 0.f) { temp = (r__1 = r_imag(&x[ix]), dabs(r__1)); if (scale < temp) { /* Computing 2nd power */ r__1 = scale / temp; ssq = ssq * (r__1 * r__1) + 1.f; scale = temp; } else { /* Computing 2nd power */ r__1 = temp / scale; ssq += r__1 * r__1; } } /* L10: */ } norm = scale * sqrt(ssq); } ret_val = norm; return ret_val; /* End of SCNRM2. */ } /* scnrm2_ */ /* Subroutine */ int scopy_(integer *n, real *sx, integer *incx, real *sy, integer *incy) { /* System generated locals */ integer i__1; /* Local variables */ static integer i__, m, ix, iy, mp1; /* copies a vector, x, to a vector, y. uses unrolled loops for increments equal to 1. jack dongarra, linpack, 3/11/78. modified 12/3/93, array(1) declarations changed to array(*) */ /* Parameter adjustments */ --sy; --sx; /* Function Body */ if (*n <= 0) { return 0; } if (*incx == 1 && *incy == 1) { goto L20; } /* code for unequal increments or equal increments not equal to 1 */ ix = 1; iy = 1; if (*incx < 0) { ix = (-(*n) + 1) * *incx + 1; } if (*incy < 0) { iy = (-(*n) + 1) * *incy + 1; } i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { sy[iy] = sx[ix]; ix += *incx; iy += *incy; /* L10: */ } return 0; /* code for both increments equal to 1 clean-up loop */ L20: m = *n % 7; if (m == 0) { goto L40; } i__1 = m; for (i__ = 1; i__ <= i__1; ++i__) { sy[i__] = sx[i__]; /* L30: */ } if (*n < 7) { return 0; } L40: mp1 = m + 1; i__1 = *n; for (i__ = mp1; i__ <= i__1; i__ += 7) { sy[i__] = sx[i__]; sy[i__ + 1] = sx[i__ + 1]; sy[i__ + 2] = sx[i__ + 2]; sy[i__ + 3] = sx[i__ + 3]; sy[i__ + 4] = sx[i__ + 4]; sy[i__ + 5] = sx[i__ + 5]; sy[i__ + 6] = sx[i__ + 6]; /* L50: */ } return 0; } /* scopy_ */ doublereal sdot_(integer *n, real *sx, integer *incx, real *sy, integer *incy) { /* System generated locals */ integer i__1; real ret_val; /* Local variables */ static integer i__, m, ix, iy, mp1; static real stemp; /* forms the dot product of two vectors. uses unrolled loops for increments equal to one. jack dongarra, linpack, 3/11/78. modified 12/3/93, array(1) declarations changed to array(*) */ /* Parameter adjustments */ --sy; --sx; /* Function Body */ stemp = 0.f; ret_val = 0.f; if (*n <= 0) { return ret_val; } if (*incx == 1 && *incy == 1) { goto L20; } /* code for unequal increments or equal increments not equal to 1 */ ix = 1; iy = 1; if (*incx < 0) { ix = (-(*n) + 1) * *incx + 1; } if (*incy < 0) { iy = (-(*n) + 1) * *incy + 1; } i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { stemp += sx[ix] * sy[iy]; ix += *incx; iy += *incy; /* L10: */ } ret_val = stemp; return ret_val; /* code for both increments equal to 1 clean-up loop */ L20: m = *n % 5; if (m == 0) { goto L40; } i__1 = m; for (i__ = 1; i__ <= i__1; ++i__) { stemp += sx[i__] * sy[i__]; /* L30: */ } if (*n < 5) { goto L60; } L40: mp1 = m + 1; i__1 = *n; for (i__ = mp1; i__ <= i__1; i__ += 5) { stemp = stemp + sx[i__] * sy[i__] + sx[i__ + 1] * sy[i__ + 1] + sx[ i__ + 2] * sy[i__ + 2] + sx[i__ + 3] * sy[i__ + 3] + sx[i__ + 4] * sy[i__ + 4]; /* L50: */ } L60: ret_val = stemp; return ret_val; } /* sdot_ */ /* Subroutine */ int sgemm_(char *transa, char *transb, integer *m, integer * n, integer *k, real *alpha, real *a, integer *lda, real *b, integer * ldb, real *beta, real *c__, integer *ldc) { /* System generated locals */ integer a_dim1, a_offset, b_dim1, b_offset, c_dim1, c_offset, i__1, i__2, i__3; /* Local variables */ static integer i__, j, l, info; static logical nota, notb; static real temp; static integer ncola; extern logical lsame_(char *, char *); static integer nrowa, nrowb; extern /* Subroutine */ int xerbla_(char *, integer *); /* Purpose ======= SGEMM performs one of the matrix-matrix operations C := alpha*op( A )*op( B ) + beta*C, where op( X ) is one of op( X ) = X or op( X ) = X', alpha and beta are scalars, and A, B and C are matrices, with op( A ) an m by k matrix, op( B ) a k by n matrix and C an m by n matrix. Parameters ========== TRANSA - CHARACTER*1. On entry, TRANSA specifies the form of op( A ) to be used in the matrix multiplication as follows: TRANSA = 'N' or 'n', op( A ) = A. TRANSA = 'T' or 't', op( A ) = A'. TRANSA = 'C' or 'c', op( A ) = A'. Unchanged on exit. TRANSB - CHARACTER*1. On entry, TRANSB specifies the form of op( B ) to be used in the matrix multiplication as follows: TRANSB = 'N' or 'n', op( B ) = B. TRANSB = 'T' or 't', op( B ) = B'. TRANSB = 'C' or 'c', op( B ) = B'. Unchanged on exit. M - INTEGER. On entry, M specifies the number of rows of the matrix op( A ) and of the matrix C. M must be at least zero. Unchanged on exit. N - INTEGER. On entry, N specifies the number of columns of the matrix op( B ) and the number of columns of the matrix C. N must be at least zero. Unchanged on exit. K - INTEGER. On entry, K specifies the number of columns of the matrix op( A ) and the number of rows of the matrix op( B ). K must be at least zero. Unchanged on exit. ALPHA - REAL . On entry, ALPHA specifies the scalar alpha. Unchanged on exit. A - REAL array of DIMENSION ( LDA, ka ), where ka is k when TRANSA = 'N' or 'n', and is m otherwise. Before entry with TRANSA = 'N' or 'n', the leading m by k part of the array A must contain the matrix A, otherwise the leading k by m part of the array A must contain the matrix A. Unchanged on exit. LDA - INTEGER. On entry, LDA specifies the first dimension of A as declared in the calling (sub) program. When TRANSA = 'N' or 'n' then LDA must be at least max( 1, m ), otherwise LDA must be at least max( 1, k ). Unchanged on exit. B - REAL array of DIMENSION ( LDB, kb ), where kb is n when TRANSB = 'N' or 'n', and is k otherwise. Before entry with TRANSB = 'N' or 'n', the leading k by n part of the array B must contain the matrix B, otherwise the leading n by k part of the array B must contain the matrix B. Unchanged on exit. LDB - INTEGER. On entry, LDB specifies the first dimension of B as declared in the calling (sub) program. When TRANSB = 'N' or 'n' then LDB must be at least max( 1, k ), otherwise LDB must be at least max( 1, n ). Unchanged on exit. BETA - REAL . On entry, BETA specifies the scalar beta. When BETA is supplied as zero then C need not be set on input. Unchanged on exit. C - REAL array of DIMENSION ( LDC, n ). Before entry, the leading m by n part of the array C must contain the matrix C, except when beta is zero, in which case C need not be set on entry. On exit, the array C is overwritten by the m by n matrix ( alpha*op( A )*op( B ) + beta*C ). LDC - INTEGER. On entry, LDC specifies the first dimension of C as declared in the calling (sub) program. LDC must be at least max( 1, m ). Unchanged on exit. Level 3 Blas routine. -- Written on 8-February-1989. Jack Dongarra, Argonne National Laboratory. Iain Duff, AERE Harwell. Jeremy Du Croz, Numerical Algorithms Group Ltd. Sven Hammarling, Numerical Algorithms Group Ltd. Set NOTA and NOTB as true if A and B respectively are not transposed and set NROWA, NCOLA and NROWB as the number of rows and columns of A and the number of rows of B respectively. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; b_dim1 = *ldb; b_offset = 1 + b_dim1; b -= b_offset; c_dim1 = *ldc; c_offset = 1 + c_dim1; c__ -= c_offset; /* Function Body */ nota = lsame_(transa, "N"); notb = lsame_(transb, "N"); if (nota) { nrowa = *m; ncola = *k; } else { nrowa = *k; ncola = *m; } if (notb) { nrowb = *k; } else { nrowb = *n; } /* Test the input parameters. */ info = 0; if (! nota && ! lsame_(transa, "C") && ! lsame_( transa, "T")) { info = 1; } else if (! notb && ! lsame_(transb, "C") && ! lsame_(transb, "T")) { info = 2; } else if (*m < 0) { info = 3; } else if (*n < 0) { info = 4; } else if (*k < 0) { info = 5; } else if (*lda < max(1,nrowa)) { info = 8; } else if (*ldb < max(1,nrowb)) { info = 10; } else if (*ldc < max(1,*m)) { info = 13; } if (info != 0) { xerbla_("SGEMM ", &info); return 0; } /* Quick return if possible. */ if (((*m == 0) || (*n == 0)) || (((*alpha == 0.f) || (*k == 0)) && *beta == 1.f)) { return 0; } /* And if alpha.eq.zero. */ if (*alpha == 0.f) { if (*beta == 0.f) { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { c__[i__ + j * c_dim1] = 0.f; /* L10: */ } /* L20: */ } } else { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { c__[i__ + j * c_dim1] = *beta * c__[i__ + j * c_dim1]; /* L30: */ } /* L40: */ } } return 0; } /* Start the operations. */ if (notb) { if (nota) { /* Form C := alpha*A*B + beta*C. */ i__1 = *n; for (j = 1; j <= i__1; ++j) { if (*beta == 0.f) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { c__[i__ + j * c_dim1] = 0.f; /* L50: */ } } else if (*beta != 1.f) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { c__[i__ + j * c_dim1] = *beta * c__[i__ + j * c_dim1]; /* L60: */ } } i__2 = *k; for (l = 1; l <= i__2; ++l) { if (b[l + j * b_dim1] != 0.f) { temp = *alpha * b[l + j * b_dim1]; i__3 = *m; for (i__ = 1; i__ <= i__3; ++i__) { c__[i__ + j * c_dim1] += temp * a[i__ + l * a_dim1]; /* L70: */ } } /* L80: */ } /* L90: */ } } else { /* Form C := alpha*A'*B + beta*C */ i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { temp = 0.f; i__3 = *k; for (l = 1; l <= i__3; ++l) { temp += a[l + i__ * a_dim1] * b[l + j * b_dim1]; /* L100: */ } if (*beta == 0.f) { c__[i__ + j * c_dim1] = *alpha * temp; } else { c__[i__ + j * c_dim1] = *alpha * temp + *beta * c__[ i__ + j * c_dim1]; } /* L110: */ } /* L120: */ } } } else { if (nota) { /* Form C := alpha*A*B' + beta*C */ i__1 = *n; for (j = 1; j <= i__1; ++j) { if (*beta == 0.f) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { c__[i__ + j * c_dim1] = 0.f; /* L130: */ } } else if (*beta != 1.f) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { c__[i__ + j * c_dim1] = *beta * c__[i__ + j * c_dim1]; /* L140: */ } } i__2 = *k; for (l = 1; l <= i__2; ++l) { if (b[j + l * b_dim1] != 0.f) { temp = *alpha * b[j + l * b_dim1]; i__3 = *m; for (i__ = 1; i__ <= i__3; ++i__) { c__[i__ + j * c_dim1] += temp * a[i__ + l * a_dim1]; /* L150: */ } } /* L160: */ } /* L170: */ } } else { /* Form C := alpha*A'*B' + beta*C */ i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { temp = 0.f; i__3 = *k; for (l = 1; l <= i__3; ++l) { temp += a[l + i__ * a_dim1] * b[j + l * b_dim1]; /* L180: */ } if (*beta == 0.f) { c__[i__ + j * c_dim1] = *alpha * temp; } else { c__[i__ + j * c_dim1] = *alpha * temp + *beta * c__[ i__ + j * c_dim1]; } /* L190: */ } /* L200: */ } } } return 0; /* End of SGEMM . */ } /* sgemm_ */ /* Subroutine */ int sgemv_(char *trans, integer *m, integer *n, real *alpha, real *a, integer *lda, real *x, integer *incx, real *beta, real *y, integer *incy) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2; /* Local variables */ static integer i__, j, ix, iy, jx, jy, kx, ky, info; static real temp; static integer lenx, leny; extern logical lsame_(char *, char *); extern /* Subroutine */ int xerbla_(char *, integer *); /* Purpose ======= SGEMV performs one of the matrix-vector operations y := alpha*A*x + beta*y, or y := alpha*A'*x + beta*y, where alpha and beta are scalars, x and y are vectors and A is an m by n matrix. Parameters ========== TRANS - CHARACTER*1. On entry, TRANS specifies the operation to be performed as follows: TRANS = 'N' or 'n' y := alpha*A*x + beta*y. TRANS = 'T' or 't' y := alpha*A'*x + beta*y. TRANS = 'C' or 'c' y := alpha*A'*x + beta*y. Unchanged on exit. M - INTEGER. On entry, M specifies the number of rows of the matrix A. M must be at least zero. Unchanged on exit. N - INTEGER. On entry, N specifies the number of columns of the matrix A. N must be at least zero. Unchanged on exit. ALPHA - REAL . On entry, ALPHA specifies the scalar alpha. Unchanged on exit. A - REAL array of DIMENSION ( LDA, n ). Before entry, the leading m by n part of the array A must contain the matrix of coefficients. Unchanged on exit. LDA - INTEGER. On entry, LDA specifies the first dimension of A as declared in the calling (sub) program. LDA must be at least max( 1, m ). Unchanged on exit. X - REAL array of DIMENSION at least ( 1 + ( n - 1 )*abs( INCX ) ) when TRANS = 'N' or 'n' and at least ( 1 + ( m - 1 )*abs( INCX ) ) otherwise. Before entry, the incremented array X must contain the vector x. Unchanged on exit. INCX - INTEGER. On entry, INCX specifies the increment for the elements of X. INCX must not be zero. Unchanged on exit. BETA - REAL . On entry, BETA specifies the scalar beta. When BETA is supplied as zero then Y need not be set on input. Unchanged on exit. Y - REAL array of DIMENSION at least ( 1 + ( m - 1 )*abs( INCY ) ) when TRANS = 'N' or 'n' and at least ( 1 + ( n - 1 )*abs( INCY ) ) otherwise. Before entry with BETA non-zero, the incremented array Y must contain the vector y. On exit, Y is overwritten by the updated vector y. INCY - INTEGER. On entry, INCY specifies the increment for the elements of Y. INCY must not be zero. Unchanged on exit. Level 2 Blas routine. -- Written on 22-October-1986. Jack Dongarra, Argonne National Lab. Jeremy Du Croz, Nag Central Office. Sven Hammarling, Nag Central Office. Richard Hanson, Sandia National Labs. Test the input parameters. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --x; --y; /* Function Body */ info = 0; if (! lsame_(trans, "N") && ! lsame_(trans, "T") && ! lsame_(trans, "C") ) { info = 1; } else if (*m < 0) { info = 2; } else if (*n < 0) { info = 3; } else if (*lda < max(1,*m)) { info = 6; } else if (*incx == 0) { info = 8; } else if (*incy == 0) { info = 11; } if (info != 0) { xerbla_("SGEMV ", &info); return 0; } /* Quick return if possible. */ if (((*m == 0) || (*n == 0)) || (*alpha == 0.f && *beta == 1.f)) { return 0; } /* Set LENX and LENY, the lengths of the vectors x and y, and set up the start points in X and Y. */ if (lsame_(trans, "N")) { lenx = *n; leny = *m; } else { lenx = *m; leny = *n; } if (*incx > 0) { kx = 1; } else { kx = 1 - (lenx - 1) * *incx; } if (*incy > 0) { ky = 1; } else { ky = 1 - (leny - 1) * *incy; } /* Start the operations. In this version the elements of A are accessed sequentially with one pass through A. First form y := beta*y. */ if (*beta != 1.f) { if (*incy == 1) { if (*beta == 0.f) { i__1 = leny; for (i__ = 1; i__ <= i__1; ++i__) { y[i__] = 0.f; /* L10: */ } } else { i__1 = leny; for (i__ = 1; i__ <= i__1; ++i__) { y[i__] = *beta * y[i__]; /* L20: */ } } } else { iy = ky; if (*beta == 0.f) { i__1 = leny; for (i__ = 1; i__ <= i__1; ++i__) { y[iy] = 0.f; iy += *incy; /* L30: */ } } else { i__1 = leny; for (i__ = 1; i__ <= i__1; ++i__) { y[iy] = *beta * y[iy]; iy += *incy; /* L40: */ } } } } if (*alpha == 0.f) { return 0; } if (lsame_(trans, "N")) { /* Form y := alpha*A*x + y. */ jx = kx; if (*incy == 1) { i__1 = *n; for (j = 1; j <= i__1; ++j) { if (x[jx] != 0.f) { temp = *alpha * x[jx]; i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { y[i__] += temp * a[i__ + j * a_dim1]; /* L50: */ } } jx += *incx; /* L60: */ } } else { i__1 = *n; for (j = 1; j <= i__1; ++j) { if (x[jx] != 0.f) { temp = *alpha * x[jx]; iy = ky; i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { y[iy] += temp * a[i__ + j * a_dim1]; iy += *incy; /* L70: */ } } jx += *incx; /* L80: */ } } } else { /* Form y := alpha*A'*x + y. */ jy = ky; if (*incx == 1) { i__1 = *n; for (j = 1; j <= i__1; ++j) { temp = 0.f; i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { temp += a[i__ + j * a_dim1] * x[i__]; /* L90: */ } y[jy] += *alpha * temp; jy += *incy; /* L100: */ } } else { i__1 = *n; for (j = 1; j <= i__1; ++j) { temp = 0.f; ix = kx; i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { temp += a[i__ + j * a_dim1] * x[ix]; ix += *incx; /* L110: */ } y[jy] += *alpha * temp; jy += *incy; /* L120: */ } } } return 0; /* End of SGEMV . */ } /* sgemv_ */ /* Subroutine */ int sger_(integer *m, integer *n, real *alpha, real *x, integer *incx, real *y, integer *incy, real *a, integer *lda) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2; /* Local variables */ static integer i__, j, ix, jy, kx, info; static real temp; extern /* Subroutine */ int xerbla_(char *, integer *); /* Purpose ======= SGER performs the rank 1 operation A := alpha*x*y' + A, where alpha is a scalar, x is an m element vector, y is an n element vector and A is an m by n matrix. Parameters ========== M - INTEGER. On entry, M specifies the number of rows of the matrix A. M must be at least zero. Unchanged on exit. N - INTEGER. On entry, N specifies the number of columns of the matrix A. N must be at least zero. Unchanged on exit. ALPHA - REAL . On entry, ALPHA specifies the scalar alpha. Unchanged on exit. X - REAL array of dimension at least ( 1 + ( m - 1 )*abs( INCX ) ). Before entry, the incremented array X must contain the m element vector x. Unchanged on exit. INCX - INTEGER. On entry, INCX specifies the increment for the elements of X. INCX must not be zero. Unchanged on exit. Y - REAL array of dimension at least ( 1 + ( n - 1 )*abs( INCY ) ). Before entry, the incremented array Y must contain the n element vector y. Unchanged on exit. INCY - INTEGER. On entry, INCY specifies the increment for the elements of Y. INCY must not be zero. Unchanged on exit. A - REAL array of DIMENSION ( LDA, n ). Before entry, the leading m by n part of the array A must contain the matrix of coefficients. On exit, A is overwritten by the updated matrix. LDA - INTEGER. On entry, LDA specifies the first dimension of A as declared in the calling (sub) program. LDA must be at least max( 1, m ). Unchanged on exit. Level 2 Blas routine. -- Written on 22-October-1986. Jack Dongarra, Argonne National Lab. Jeremy Du Croz, Nag Central Office. Sven Hammarling, Nag Central Office. Richard Hanson, Sandia National Labs. Test the input parameters. */ /* Parameter adjustments */ --x; --y; a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; /* Function Body */ info = 0; if (*m < 0) { info = 1; } else if (*n < 0) { info = 2; } else if (*incx == 0) { info = 5; } else if (*incy == 0) { info = 7; } else if (*lda < max(1,*m)) { info = 9; } if (info != 0) { xerbla_("SGER ", &info); return 0; } /* Quick return if possible. */ if (((*m == 0) || (*n == 0)) || (*alpha == 0.f)) { return 0; } /* Start the operations. In this version the elements of A are accessed sequentially with one pass through A. */ if (*incy > 0) { jy = 1; } else { jy = 1 - (*n - 1) * *incy; } if (*incx == 1) { i__1 = *n; for (j = 1; j <= i__1; ++j) { if (y[jy] != 0.f) { temp = *alpha * y[jy]; i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { a[i__ + j * a_dim1] += x[i__] * temp; /* L10: */ } } jy += *incy; /* L20: */ } } else { if (*incx > 0) { kx = 1; } else { kx = 1 - (*m - 1) * *incx; } i__1 = *n; for (j = 1; j <= i__1; ++j) { if (y[jy] != 0.f) { temp = *alpha * y[jy]; ix = kx; i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { a[i__ + j * a_dim1] += x[ix] * temp; ix += *incx; /* L30: */ } } jy += *incy; /* L40: */ } } return 0; /* End of SGER . */ } /* sger_ */ doublereal snrm2_(integer *n, real *x, integer *incx) { /* System generated locals */ integer i__1, i__2; real ret_val, r__1; /* Builtin functions */ double sqrt(doublereal); /* Local variables */ static integer ix; static real ssq, norm, scale, absxi; /* SNRM2 returns the euclidean norm of a vector via the function name, so that SNRM2 := sqrt( x'*x ) -- This version written on 25-October-1982. Modified on 14-October-1993 to inline the call to SLASSQ. Sven Hammarling, Nag Ltd. */ /* Parameter adjustments */ --x; /* Function Body */ if ((*n < 1) || (*incx < 1)) { norm = 0.f; } else if (*n == 1) { norm = dabs(x[1]); } else { scale = 0.f; ssq = 1.f; /* The following loop is equivalent to this call to the LAPACK auxiliary routine: CALL SLASSQ( N, X, INCX, SCALE, SSQ ) */ i__1 = (*n - 1) * *incx + 1; i__2 = *incx; for (ix = 1; i__2 < 0 ? ix >= i__1 : ix <= i__1; ix += i__2) { if (x[ix] != 0.f) { absxi = (r__1 = x[ix], dabs(r__1)); if (scale < absxi) { /* Computing 2nd power */ r__1 = scale / absxi; ssq = ssq * (r__1 * r__1) + 1.f; scale = absxi; } else { /* Computing 2nd power */ r__1 = absxi / scale; ssq += r__1 * r__1; } } /* L10: */ } norm = scale * sqrt(ssq); } ret_val = norm; return ret_val; /* End of SNRM2. */ } /* snrm2_ */ /* Subroutine */ int srot_(integer *n, real *sx, integer *incx, real *sy, integer *incy, real *c__, real *s) { /* System generated locals */ integer i__1; /* Local variables */ static integer i__, ix, iy; static real stemp; /* applies a plane rotation. jack dongarra, linpack, 3/11/78. modified 12/3/93, array(1) declarations changed to array(*) */ /* Parameter adjustments */ --sy; --sx; /* Function Body */ if (*n <= 0) { return 0; } if (*incx == 1 && *incy == 1) { goto L20; } /* code for unequal increments or equal increments not equal to 1 */ ix = 1; iy = 1; if (*incx < 0) { ix = (-(*n) + 1) * *incx + 1; } if (*incy < 0) { iy = (-(*n) + 1) * *incy + 1; } i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { stemp = *c__ * sx[ix] + *s * sy[iy]; sy[iy] = *c__ * sy[iy] - *s * sx[ix]; sx[ix] = stemp; ix += *incx; iy += *incy; /* L10: */ } return 0; /* code for both increments equal to 1 */ L20: i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { stemp = *c__ * sx[i__] + *s * sy[i__]; sy[i__] = *c__ * sy[i__] - *s * sx[i__]; sx[i__] = stemp; /* L30: */ } return 0; } /* srot_ */ /* Subroutine */ int sscal_(integer *n, real *sa, real *sx, integer *incx) { /* System generated locals */ integer i__1, i__2; /* Local variables */ static integer i__, m, mp1, nincx; /* scales a vector by a constant. uses unrolled loops for increment equal to 1. jack dongarra, linpack, 3/11/78. modified 3/93 to return if incx .le. 0. modified 12/3/93, array(1) declarations changed to array(*) */ /* Parameter adjustments */ --sx; /* Function Body */ if ((*n <= 0) || (*incx <= 0)) { return 0; } if (*incx == 1) { goto L20; } /* code for increment not equal to 1 */ nincx = *n * *incx; i__1 = nincx; i__2 = *incx; for (i__ = 1; i__2 < 0 ? i__ >= i__1 : i__ <= i__1; i__ += i__2) { sx[i__] = *sa * sx[i__]; /* L10: */ } return 0; /* code for increment equal to 1 clean-up loop */ L20: m = *n % 5; if (m == 0) { goto L40; } i__2 = m; for (i__ = 1; i__ <= i__2; ++i__) { sx[i__] = *sa * sx[i__]; /* L30: */ } if (*n < 5) { return 0; } L40: mp1 = m + 1; i__2 = *n; for (i__ = mp1; i__ <= i__2; i__ += 5) { sx[i__] = *sa * sx[i__]; sx[i__ + 1] = *sa * sx[i__ + 1]; sx[i__ + 2] = *sa * sx[i__ + 2]; sx[i__ + 3] = *sa * sx[i__ + 3]; sx[i__ + 4] = *sa * sx[i__ + 4]; /* L50: */ } return 0; } /* sscal_ */ /* Subroutine */ int sswap_(integer *n, real *sx, integer *incx, real *sy, integer *incy) { /* System generated locals */ integer i__1; /* Local variables */ static integer i__, m, ix, iy, mp1; static real stemp; /* interchanges two vectors. uses unrolled loops for increments equal to 1. jack dongarra, linpack, 3/11/78. modified 12/3/93, array(1) declarations changed to array(*) */ /* Parameter adjustments */ --sy; --sx; /* Function Body */ if (*n <= 0) { return 0; } if (*incx == 1 && *incy == 1) { goto L20; } /* code for unequal increments or equal increments not equal to 1 */ ix = 1; iy = 1; if (*incx < 0) { ix = (-(*n) + 1) * *incx + 1; } if (*incy < 0) { iy = (-(*n) + 1) * *incy + 1; } i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { stemp = sx[ix]; sx[ix] = sy[iy]; sy[iy] = stemp; ix += *incx; iy += *incy; /* L10: */ } return 0; /* code for both increments equal to 1 clean-up loop */ L20: m = *n % 3; if (m == 0) { goto L40; } i__1 = m; for (i__ = 1; i__ <= i__1; ++i__) { stemp = sx[i__]; sx[i__] = sy[i__]; sy[i__] = stemp; /* L30: */ } if (*n < 3) { return 0; } L40: mp1 = m + 1; i__1 = *n; for (i__ = mp1; i__ <= i__1; i__ += 3) { stemp = sx[i__]; sx[i__] = sy[i__]; sy[i__] = stemp; stemp = sx[i__ + 1]; sx[i__ + 1] = sy[i__ + 1]; sy[i__ + 1] = stemp; stemp = sx[i__ + 2]; sx[i__ + 2] = sy[i__ + 2]; sy[i__ + 2] = stemp; /* L50: */ } return 0; } /* sswap_ */ /* Subroutine */ int ssymv_(char *uplo, integer *n, real *alpha, real *a, integer *lda, real *x, integer *incx, real *beta, real *y, integer * incy) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2; /* Local variables */ static integer i__, j, ix, iy, jx, jy, kx, ky, info; static real temp1, temp2; extern logical lsame_(char *, char *); extern /* Subroutine */ int xerbla_(char *, integer *); /* Purpose ======= SSYMV performs the matrix-vector operation y := alpha*A*x + beta*y, where alpha and beta are scalars, x and y are n element vectors and A is an n by n symmetric matrix. Parameters ========== UPLO - CHARACTER*1. On entry, UPLO specifies whether the upper or lower triangular part of the array A is to be referenced as follows: UPLO = 'U' or 'u' Only the upper triangular part of A is to be referenced. UPLO = 'L' or 'l' Only the lower triangular part of A is to be referenced. Unchanged on exit. N - INTEGER. On entry, N specifies the order of the matrix A. N must be at least zero. Unchanged on exit. ALPHA - REAL . On entry, ALPHA specifies the scalar alpha. Unchanged on exit. A - REAL array of DIMENSION ( LDA, n ). Before entry with UPLO = 'U' or 'u', the leading n by n upper triangular part of the array A must contain the upper triangular part of the symmetric matrix and the strictly lower triangular part of A is not referenced. Before entry with UPLO = 'L' or 'l', the leading n by n lower triangular part of the array A must contain the lower triangular part of the symmetric matrix and the strictly upper triangular part of A is not referenced. Unchanged on exit. LDA - INTEGER. On entry, LDA specifies the first dimension of A as declared in the calling (sub) program. LDA must be at least max( 1, n ). Unchanged on exit. X - REAL array of dimension at least ( 1 + ( n - 1 )*abs( INCX ) ). Before entry, the incremented array X must contain the n element vector x. Unchanged on exit. INCX - INTEGER. On entry, INCX specifies the increment for the elements of X. INCX must not be zero. Unchanged on exit. BETA - REAL . On entry, BETA specifies the scalar beta. When BETA is supplied as zero then Y need not be set on input. Unchanged on exit. Y - REAL array of dimension at least ( 1 + ( n - 1 )*abs( INCY ) ). Before entry, the incremented array Y must contain the n element vector y. On exit, Y is overwritten by the updated vector y. INCY - INTEGER. On entry, INCY specifies the increment for the elements of Y. INCY must not be zero. Unchanged on exit. Level 2 Blas routine. -- Written on 22-October-1986. Jack Dongarra, Argonne National Lab. Jeremy Du Croz, Nag Central Office. Sven Hammarling, Nag Central Office. Richard Hanson, Sandia National Labs. Test the input parameters. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --x; --y; /* Function Body */ info = 0; if (! lsame_(uplo, "U") && ! lsame_(uplo, "L")) { info = 1; } else if (*n < 0) { info = 2; } else if (*lda < max(1,*n)) { info = 5; } else if (*incx == 0) { info = 7; } else if (*incy == 0) { info = 10; } if (info != 0) { xerbla_("SSYMV ", &info); return 0; } /* Quick return if possible. */ if ((*n == 0) || (*alpha == 0.f && *beta == 1.f)) { return 0; } /* Set up the start points in X and Y. */ if (*incx > 0) { kx = 1; } else { kx = 1 - (*n - 1) * *incx; } if (*incy > 0) { ky = 1; } else { ky = 1 - (*n - 1) * *incy; } /* Start the operations. In this version the elements of A are accessed sequentially with one pass through the triangular part of A. First form y := beta*y. */ if (*beta != 1.f) { if (*incy == 1) { if (*beta == 0.f) { i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { y[i__] = 0.f; /* L10: */ } } else { i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { y[i__] = *beta * y[i__]; /* L20: */ } } } else { iy = ky; if (*beta == 0.f) { i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { y[iy] = 0.f; iy += *incy; /* L30: */ } } else { i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { y[iy] = *beta * y[iy]; iy += *incy; /* L40: */ } } } } if (*alpha == 0.f) { return 0; } if (lsame_(uplo, "U")) { /* Form y when A is stored in upper triangle. */ if (*incx == 1 && *incy == 1) { i__1 = *n; for (j = 1; j <= i__1; ++j) { temp1 = *alpha * x[j]; temp2 = 0.f; i__2 = j - 1; for (i__ = 1; i__ <= i__2; ++i__) { y[i__] += temp1 * a[i__ + j * a_dim1]; temp2 += a[i__ + j * a_dim1] * x[i__]; /* L50: */ } y[j] = y[j] + temp1 * a[j + j * a_dim1] + *alpha * temp2; /* L60: */ } } else { jx = kx; jy = ky; i__1 = *n; for (j = 1; j <= i__1; ++j) { temp1 = *alpha * x[jx]; temp2 = 0.f; ix = kx; iy = ky; i__2 = j - 1; for (i__ = 1; i__ <= i__2; ++i__) { y[iy] += temp1 * a[i__ + j * a_dim1]; temp2 += a[i__ + j * a_dim1] * x[ix]; ix += *incx; iy += *incy; /* L70: */ } y[jy] = y[jy] + temp1 * a[j + j * a_dim1] + *alpha * temp2; jx += *incx; jy += *incy; /* L80: */ } } } else { /* Form y when A is stored in lower triangle. */ if (*incx == 1 && *incy == 1) { i__1 = *n; for (j = 1; j <= i__1; ++j) { temp1 = *alpha * x[j]; temp2 = 0.f; y[j] += temp1 * a[j + j * a_dim1]; i__2 = *n; for (i__ = j + 1; i__ <= i__2; ++i__) { y[i__] += temp1 * a[i__ + j * a_dim1]; temp2 += a[i__ + j * a_dim1] * x[i__]; /* L90: */ } y[j] += *alpha * temp2; /* L100: */ } } else { jx = kx; jy = ky; i__1 = *n; for (j = 1; j <= i__1; ++j) { temp1 = *alpha * x[jx]; temp2 = 0.f; y[jy] += temp1 * a[j + j * a_dim1]; ix = jx; iy = jy; i__2 = *n; for (i__ = j + 1; i__ <= i__2; ++i__) { ix += *incx; iy += *incy; y[iy] += temp1 * a[i__ + j * a_dim1]; temp2 += a[i__ + j * a_dim1] * x[ix]; /* L110: */ } y[jy] += *alpha * temp2; jx += *incx; jy += *incy; /* L120: */ } } } return 0; /* End of SSYMV . */ } /* ssymv_ */ /* Subroutine */ int ssyr2_(char *uplo, integer *n, real *alpha, real *x, integer *incx, real *y, integer *incy, real *a, integer *lda) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2; /* Local variables */ static integer i__, j, ix, iy, jx, jy, kx, ky, info; static real temp1, temp2; extern logical lsame_(char *, char *); extern /* Subroutine */ int xerbla_(char *, integer *); /* Purpose ======= SSYR2 performs the symmetric rank 2 operation A := alpha*x*y' + alpha*y*x' + A, where alpha is a scalar, x and y are n element vectors and A is an n by n symmetric matrix. Parameters ========== UPLO - CHARACTER*1. On entry, UPLO specifies whether the upper or lower triangular part of the array A is to be referenced as follows: UPLO = 'U' or 'u' Only the upper triangular part of A is to be referenced. UPLO = 'L' or 'l' Only the lower triangular part of A is to be referenced. Unchanged on exit. N - INTEGER. On entry, N specifies the order of the matrix A. N must be at least zero. Unchanged on exit. ALPHA - REAL . On entry, ALPHA specifies the scalar alpha. Unchanged on exit. X - REAL array of dimension at least ( 1 + ( n - 1 )*abs( INCX ) ). Before entry, the incremented array X must contain the n element vector x. Unchanged on exit. INCX - INTEGER. On entry, INCX specifies the increment for the elements of X. INCX must not be zero. Unchanged on exit. Y - REAL array of dimension at least ( 1 + ( n - 1 )*abs( INCY ) ). Before entry, the incremented array Y must contain the n element vector y. Unchanged on exit. INCY - INTEGER. On entry, INCY specifies the increment for the elements of Y. INCY must not be zero. Unchanged on exit. A - REAL array of DIMENSION ( LDA, n ). Before entry with UPLO = 'U' or 'u', the leading n by n upper triangular part of the array A must contain the upper triangular part of the symmetric matrix and the strictly lower triangular part of A is not referenced. On exit, the upper triangular part of the array A is overwritten by the upper triangular part of the updated matrix. Before entry with UPLO = 'L' or 'l', the leading n by n lower triangular part of the array A must contain the lower triangular part of the symmetric matrix and the strictly upper triangular part of A is not referenced. On exit, the lower triangular part of the array A is overwritten by the lower triangular part of the updated matrix. LDA - INTEGER. On entry, LDA specifies the first dimension of A as declared in the calling (sub) program. LDA must be at least max( 1, n ). Unchanged on exit. Level 2 Blas routine. -- Written on 22-October-1986. Jack Dongarra, Argonne National Lab. Jeremy Du Croz, Nag Central Office. Sven Hammarling, Nag Central Office. Richard Hanson, Sandia National Labs. Test the input parameters. */ /* Parameter adjustments */ --x; --y; a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; /* Function Body */ info = 0; if (! lsame_(uplo, "U") && ! lsame_(uplo, "L")) { info = 1; } else if (*n < 0) { info = 2; } else if (*incx == 0) { info = 5; } else if (*incy == 0) { info = 7; } else if (*lda < max(1,*n)) { info = 9; } if (info != 0) { xerbla_("SSYR2 ", &info); return 0; } /* Quick return if possible. */ if ((*n == 0) || (*alpha == 0.f)) { return 0; } /* Set up the start points in X and Y if the increments are not both unity. */ if ((*incx != 1) || (*incy != 1)) { if (*incx > 0) { kx = 1; } else { kx = 1 - (*n - 1) * *incx; } if (*incy > 0) { ky = 1; } else { ky = 1 - (*n - 1) * *incy; } jx = kx; jy = ky; } /* Start the operations. In this version the elements of A are accessed sequentially with one pass through the triangular part of A. */ if (lsame_(uplo, "U")) { /* Form A when A is stored in the upper triangle. */ if (*incx == 1 && *incy == 1) { i__1 = *n; for (j = 1; j <= i__1; ++j) { if ((x[j] != 0.f) || (y[j] != 0.f)) { temp1 = *alpha * y[j]; temp2 = *alpha * x[j]; i__2 = j; for (i__ = 1; i__ <= i__2; ++i__) { a[i__ + j * a_dim1] = a[i__ + j * a_dim1] + x[i__] * temp1 + y[i__] * temp2; /* L10: */ } } /* L20: */ } } else { i__1 = *n; for (j = 1; j <= i__1; ++j) { if ((x[jx] != 0.f) || (y[jy] != 0.f)) { temp1 = *alpha * y[jy]; temp2 = *alpha * x[jx]; ix = kx; iy = ky; i__2 = j; for (i__ = 1; i__ <= i__2; ++i__) { a[i__ + j * a_dim1] = a[i__ + j * a_dim1] + x[ix] * temp1 + y[iy] * temp2; ix += *incx; iy += *incy; /* L30: */ } } jx += *incx; jy += *incy; /* L40: */ } } } else { /* Form A when A is stored in the lower triangle. */ if (*incx == 1 && *incy == 1) { i__1 = *n; for (j = 1; j <= i__1; ++j) { if ((x[j] != 0.f) || (y[j] != 0.f)) { temp1 = *alpha * y[j]; temp2 = *alpha * x[j]; i__2 = *n; for (i__ = j; i__ <= i__2; ++i__) { a[i__ + j * a_dim1] = a[i__ + j * a_dim1] + x[i__] * temp1 + y[i__] * temp2; /* L50: */ } } /* L60: */ } } else { i__1 = *n; for (j = 1; j <= i__1; ++j) { if ((x[jx] != 0.f) || (y[jy] != 0.f)) { temp1 = *alpha * y[jy]; temp2 = *alpha * x[jx]; ix = jx; iy = jy; i__2 = *n; for (i__ = j; i__ <= i__2; ++i__) { a[i__ + j * a_dim1] = a[i__ + j * a_dim1] + x[ix] * temp1 + y[iy] * temp2; ix += *incx; iy += *incy; /* L70: */ } } jx += *incx; jy += *incy; /* L80: */ } } } return 0; /* End of SSYR2 . */ } /* ssyr2_ */ /* Subroutine */ int ssyr2k_(char *uplo, char *trans, integer *n, integer *k, real *alpha, real *a, integer *lda, real *b, integer *ldb, real *beta, real *c__, integer *ldc) { /* System generated locals */ integer a_dim1, a_offset, b_dim1, b_offset, c_dim1, c_offset, i__1, i__2, i__3; /* Local variables */ static integer i__, j, l, info; static real temp1, temp2; extern logical lsame_(char *, char *); static integer nrowa; static logical upper; extern /* Subroutine */ int xerbla_(char *, integer *); /* Purpose ======= SSYR2K performs one of the symmetric rank 2k operations C := alpha*A*B' + alpha*B*A' + beta*C, or C := alpha*A'*B + alpha*B'*A + beta*C, where alpha and beta are scalars, C is an n by n symmetric matrix and A and B are n by k matrices in the first case and k by n matrices in the second case. Parameters ========== UPLO - CHARACTER*1. On entry, UPLO specifies whether the upper or lower triangular part of the array C is to be referenced as follows: UPLO = 'U' or 'u' Only the upper triangular part of C is to be referenced. UPLO = 'L' or 'l' Only the lower triangular part of C is to be referenced. Unchanged on exit. TRANS - CHARACTER*1. On entry, TRANS specifies the operation to be performed as follows: TRANS = 'N' or 'n' C := alpha*A*B' + alpha*B*A' + beta*C. TRANS = 'T' or 't' C := alpha*A'*B + alpha*B'*A + beta*C. TRANS = 'C' or 'c' C := alpha*A'*B + alpha*B'*A + beta*C. Unchanged on exit. N - INTEGER. On entry, N specifies the order of the matrix C. N must be at least zero. Unchanged on exit. K - INTEGER. On entry with TRANS = 'N' or 'n', K specifies the number of columns of the matrices A and B, and on entry with TRANS = 'T' or 't' or 'C' or 'c', K specifies the number of rows of the matrices A and B. K must be at least zero. Unchanged on exit. ALPHA - REAL . On entry, ALPHA specifies the scalar alpha. Unchanged on exit. A - REAL array of DIMENSION ( LDA, ka ), where ka is k when TRANS = 'N' or 'n', and is n otherwise. Before entry with TRANS = 'N' or 'n', the leading n by k part of the array A must contain the matrix A, otherwise the leading k by n part of the array A must contain the matrix A. Unchanged on exit. LDA - INTEGER. On entry, LDA specifies the first dimension of A as declared in the calling (sub) program. When TRANS = 'N' or 'n' then LDA must be at least max( 1, n ), otherwise LDA must be at least max( 1, k ). Unchanged on exit. B - REAL array of DIMENSION ( LDB, kb ), where kb is k when TRANS = 'N' or 'n', and is n otherwise. Before entry with TRANS = 'N' or 'n', the leading n by k part of the array B must contain the matrix B, otherwise the leading k by n part of the array B must contain the matrix B. Unchanged on exit. LDB - INTEGER. On entry, LDB specifies the first dimension of B as declared in the calling (sub) program. When TRANS = 'N' or 'n' then LDB must be at least max( 1, n ), otherwise LDB must be at least max( 1, k ). Unchanged on exit. BETA - REAL . On entry, BETA specifies the scalar beta. Unchanged on exit. C - REAL array of DIMENSION ( LDC, n ). Before entry with UPLO = 'U' or 'u', the leading n by n upper triangular part of the array C must contain the upper triangular part of the symmetric matrix and the strictly lower triangular part of C is not referenced. On exit, the upper triangular part of the array C is overwritten by the upper triangular part of the updated matrix. Before entry with UPLO = 'L' or 'l', the leading n by n lower triangular part of the array C must contain the lower triangular part of the symmetric matrix and the strictly upper triangular part of C is not referenced. On exit, the lower triangular part of the array C is overwritten by the lower triangular part of the updated matrix. LDC - INTEGER. On entry, LDC specifies the first dimension of C as declared in the calling (sub) program. LDC must be at least max( 1, n ). Unchanged on exit. Level 3 Blas routine. -- Written on 8-February-1989. Jack Dongarra, Argonne National Laboratory. Iain Duff, AERE Harwell. Jeremy Du Croz, Numerical Algorithms Group Ltd. Sven Hammarling, Numerical Algorithms Group Ltd. Test the input parameters. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; b_dim1 = *ldb; b_offset = 1 + b_dim1; b -= b_offset; c_dim1 = *ldc; c_offset = 1 + c_dim1; c__ -= c_offset; /* Function Body */ if (lsame_(trans, "N")) { nrowa = *n; } else { nrowa = *k; } upper = lsame_(uplo, "U"); info = 0; if (! upper && ! lsame_(uplo, "L")) { info = 1; } else if (! lsame_(trans, "N") && ! lsame_(trans, "T") && ! lsame_(trans, "C")) { info = 2; } else if (*n < 0) { info = 3; } else if (*k < 0) { info = 4; } else if (*lda < max(1,nrowa)) { info = 7; } else if (*ldb < max(1,nrowa)) { info = 9; } else if (*ldc < max(1,*n)) { info = 12; } if (info != 0) { xerbla_("SSYR2K", &info); return 0; } /* Quick return if possible. */ if ((*n == 0) || (((*alpha == 0.f) || (*k == 0)) && *beta == 1.f)) { return 0; } /* And when alpha.eq.zero. */ if (*alpha == 0.f) { if (upper) { if (*beta == 0.f) { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = j; for (i__ = 1; i__ <= i__2; ++i__) { c__[i__ + j * c_dim1] = 0.f; /* L10: */ } /* L20: */ } } else { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = j; for (i__ = 1; i__ <= i__2; ++i__) { c__[i__ + j * c_dim1] = *beta * c__[i__ + j * c_dim1]; /* L30: */ } /* L40: */ } } } else { if (*beta == 0.f) { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *n; for (i__ = j; i__ <= i__2; ++i__) { c__[i__ + j * c_dim1] = 0.f; /* L50: */ } /* L60: */ } } else { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *n; for (i__ = j; i__ <= i__2; ++i__) { c__[i__ + j * c_dim1] = *beta * c__[i__ + j * c_dim1]; /* L70: */ } /* L80: */ } } } return 0; } /* Start the operations. */ if (lsame_(trans, "N")) { /* Form C := alpha*A*B' + alpha*B*A' + C. */ if (upper) { i__1 = *n; for (j = 1; j <= i__1; ++j) { if (*beta == 0.f) { i__2 = j; for (i__ = 1; i__ <= i__2; ++i__) { c__[i__ + j * c_dim1] = 0.f; /* L90: */ } } else if (*beta != 1.f) { i__2 = j; for (i__ = 1; i__ <= i__2; ++i__) { c__[i__ + j * c_dim1] = *beta * c__[i__ + j * c_dim1]; /* L100: */ } } i__2 = *k; for (l = 1; l <= i__2; ++l) { if ((a[j + l * a_dim1] != 0.f) || (b[j + l * b_dim1] != 0.f)) { temp1 = *alpha * b[j + l * b_dim1]; temp2 = *alpha * a[j + l * a_dim1]; i__3 = j; for (i__ = 1; i__ <= i__3; ++i__) { c__[i__ + j * c_dim1] = c__[i__ + j * c_dim1] + a[ i__ + l * a_dim1] * temp1 + b[i__ + l * b_dim1] * temp2; /* L110: */ } } /* L120: */ } /* L130: */ } } else { i__1 = *n; for (j = 1; j <= i__1; ++j) { if (*beta == 0.f) { i__2 = *n; for (i__ = j; i__ <= i__2; ++i__) { c__[i__ + j * c_dim1] = 0.f; /* L140: */ } } else if (*beta != 1.f) { i__2 = *n; for (i__ = j; i__ <= i__2; ++i__) { c__[i__ + j * c_dim1] = *beta * c__[i__ + j * c_dim1]; /* L150: */ } } i__2 = *k; for (l = 1; l <= i__2; ++l) { if ((a[j + l * a_dim1] != 0.f) || (b[j + l * b_dim1] != 0.f)) { temp1 = *alpha * b[j + l * b_dim1]; temp2 = *alpha * a[j + l * a_dim1]; i__3 = *n; for (i__ = j; i__ <= i__3; ++i__) { c__[i__ + j * c_dim1] = c__[i__ + j * c_dim1] + a[ i__ + l * a_dim1] * temp1 + b[i__ + l * b_dim1] * temp2; /* L160: */ } } /* L170: */ } /* L180: */ } } } else { /* Form C := alpha*A'*B + alpha*B'*A + C. */ if (upper) { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = j; for (i__ = 1; i__ <= i__2; ++i__) { temp1 = 0.f; temp2 = 0.f; i__3 = *k; for (l = 1; l <= i__3; ++l) { temp1 += a[l + i__ * a_dim1] * b[l + j * b_dim1]; temp2 += b[l + i__ * b_dim1] * a[l + j * a_dim1]; /* L190: */ } if (*beta == 0.f) { c__[i__ + j * c_dim1] = *alpha * temp1 + *alpha * temp2; } else { c__[i__ + j * c_dim1] = *beta * c__[i__ + j * c_dim1] + *alpha * temp1 + *alpha * temp2; } /* L200: */ } /* L210: */ } } else { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *n; for (i__ = j; i__ <= i__2; ++i__) { temp1 = 0.f; temp2 = 0.f; i__3 = *k; for (l = 1; l <= i__3; ++l) { temp1 += a[l + i__ * a_dim1] * b[l + j * b_dim1]; temp2 += b[l + i__ * b_dim1] * a[l + j * a_dim1]; /* L220: */ } if (*beta == 0.f) { c__[i__ + j * c_dim1] = *alpha * temp1 + *alpha * temp2; } else { c__[i__ + j * c_dim1] = *beta * c__[i__ + j * c_dim1] + *alpha * temp1 + *alpha * temp2; } /* L230: */ } /* L240: */ } } } return 0; /* End of SSYR2K. */ } /* ssyr2k_ */ /* Subroutine */ int ssyrk_(char *uplo, char *trans, integer *n, integer *k, real *alpha, real *a, integer *lda, real *beta, real *c__, integer * ldc) { /* System generated locals */ integer a_dim1, a_offset, c_dim1, c_offset, i__1, i__2, i__3; /* Local variables */ static integer i__, j, l, info; static real temp; extern logical lsame_(char *, char *); static integer nrowa; static logical upper; extern /* Subroutine */ int xerbla_(char *, integer *); /* Purpose ======= SSYRK performs one of the symmetric rank k operations C := alpha*A*A' + beta*C, or C := alpha*A'*A + beta*C, where alpha and beta are scalars, C is an n by n symmetric matrix and A is an n by k matrix in the first case and a k by n matrix in the second case. Parameters ========== UPLO - CHARACTER*1. On entry, UPLO specifies whether the upper or lower triangular part of the array C is to be referenced as follows: UPLO = 'U' or 'u' Only the upper triangular part of C is to be referenced. UPLO = 'L' or 'l' Only the lower triangular part of C is to be referenced. Unchanged on exit. TRANS - CHARACTER*1. On entry, TRANS specifies the operation to be performed as follows: TRANS = 'N' or 'n' C := alpha*A*A' + beta*C. TRANS = 'T' or 't' C := alpha*A'*A + beta*C. TRANS = 'C' or 'c' C := alpha*A'*A + beta*C. Unchanged on exit. N - INTEGER. On entry, N specifies the order of the matrix C. N must be at least zero. Unchanged on exit. K - INTEGER. On entry with TRANS = 'N' or 'n', K specifies the number of columns of the matrix A, and on entry with TRANS = 'T' or 't' or 'C' or 'c', K specifies the number of rows of the matrix A. K must be at least zero. Unchanged on exit. ALPHA - REAL . On entry, ALPHA specifies the scalar alpha. Unchanged on exit. A - REAL array of DIMENSION ( LDA, ka ), where ka is k when TRANS = 'N' or 'n', and is n otherwise. Before entry with TRANS = 'N' or 'n', the leading n by k part of the array A must contain the matrix A, otherwise the leading k by n part of the array A must contain the matrix A. Unchanged on exit. LDA - INTEGER. On entry, LDA specifies the first dimension of A as declared in the calling (sub) program. When TRANS = 'N' or 'n' then LDA must be at least max( 1, n ), otherwise LDA must be at least max( 1, k ). Unchanged on exit. BETA - REAL . On entry, BETA specifies the scalar beta. Unchanged on exit. C - REAL array of DIMENSION ( LDC, n ). Before entry with UPLO = 'U' or 'u', the leading n by n upper triangular part of the array C must contain the upper triangular part of the symmetric matrix and the strictly lower triangular part of C is not referenced. On exit, the upper triangular part of the array C is overwritten by the upper triangular part of the updated matrix. Before entry with UPLO = 'L' or 'l', the leading n by n lower triangular part of the array C must contain the lower triangular part of the symmetric matrix and the strictly upper triangular part of C is not referenced. On exit, the lower triangular part of the array C is overwritten by the lower triangular part of the updated matrix. LDC - INTEGER. On entry, LDC specifies the first dimension of C as declared in the calling (sub) program. LDC must be at least max( 1, n ). Unchanged on exit. Level 3 Blas routine. -- Written on 8-February-1989. Jack Dongarra, Argonne National Laboratory. Iain Duff, AERE Harwell. Jeremy Du Croz, Numerical Algorithms Group Ltd. Sven Hammarling, Numerical Algorithms Group Ltd. Test the input parameters. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; c_dim1 = *ldc; c_offset = 1 + c_dim1; c__ -= c_offset; /* Function Body */ if (lsame_(trans, "N")) { nrowa = *n; } else { nrowa = *k; } upper = lsame_(uplo, "U"); info = 0; if (! upper && ! lsame_(uplo, "L")) { info = 1; } else if (! lsame_(trans, "N") && ! lsame_(trans, "T") && ! lsame_(trans, "C")) { info = 2; } else if (*n < 0) { info = 3; } else if (*k < 0) { info = 4; } else if (*lda < max(1,nrowa)) { info = 7; } else if (*ldc < max(1,*n)) { info = 10; } if (info != 0) { xerbla_("SSYRK ", &info); return 0; } /* Quick return if possible. */ if ((*n == 0) || (((*alpha == 0.f) || (*k == 0)) && *beta == 1.f)) { return 0; } /* And when alpha.eq.zero. */ if (*alpha == 0.f) { if (upper) { if (*beta == 0.f) { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = j; for (i__ = 1; i__ <= i__2; ++i__) { c__[i__ + j * c_dim1] = 0.f; /* L10: */ } /* L20: */ } } else { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = j; for (i__ = 1; i__ <= i__2; ++i__) { c__[i__ + j * c_dim1] = *beta * c__[i__ + j * c_dim1]; /* L30: */ } /* L40: */ } } } else { if (*beta == 0.f) { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *n; for (i__ = j; i__ <= i__2; ++i__) { c__[i__ + j * c_dim1] = 0.f; /* L50: */ } /* L60: */ } } else { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *n; for (i__ = j; i__ <= i__2; ++i__) { c__[i__ + j * c_dim1] = *beta * c__[i__ + j * c_dim1]; /* L70: */ } /* L80: */ } } } return 0; } /* Start the operations. */ if (lsame_(trans, "N")) { /* Form C := alpha*A*A' + beta*C. */ if (upper) { i__1 = *n; for (j = 1; j <= i__1; ++j) { if (*beta == 0.f) { i__2 = j; for (i__ = 1; i__ <= i__2; ++i__) { c__[i__ + j * c_dim1] = 0.f; /* L90: */ } } else if (*beta != 1.f) { i__2 = j; for (i__ = 1; i__ <= i__2; ++i__) { c__[i__ + j * c_dim1] = *beta * c__[i__ + j * c_dim1]; /* L100: */ } } i__2 = *k; for (l = 1; l <= i__2; ++l) { if (a[j + l * a_dim1] != 0.f) { temp = *alpha * a[j + l * a_dim1]; i__3 = j; for (i__ = 1; i__ <= i__3; ++i__) { c__[i__ + j * c_dim1] += temp * a[i__ + l * a_dim1]; /* L110: */ } } /* L120: */ } /* L130: */ } } else { i__1 = *n; for (j = 1; j <= i__1; ++j) { if (*beta == 0.f) { i__2 = *n; for (i__ = j; i__ <= i__2; ++i__) { c__[i__ + j * c_dim1] = 0.f; /* L140: */ } } else if (*beta != 1.f) { i__2 = *n; for (i__ = j; i__ <= i__2; ++i__) { c__[i__ + j * c_dim1] = *beta * c__[i__ + j * c_dim1]; /* L150: */ } } i__2 = *k; for (l = 1; l <= i__2; ++l) { if (a[j + l * a_dim1] != 0.f) { temp = *alpha * a[j + l * a_dim1]; i__3 = *n; for (i__ = j; i__ <= i__3; ++i__) { c__[i__ + j * c_dim1] += temp * a[i__ + l * a_dim1]; /* L160: */ } } /* L170: */ } /* L180: */ } } } else { /* Form C := alpha*A'*A + beta*C. */ if (upper) { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = j; for (i__ = 1; i__ <= i__2; ++i__) { temp = 0.f; i__3 = *k; for (l = 1; l <= i__3; ++l) { temp += a[l + i__ * a_dim1] * a[l + j * a_dim1]; /* L190: */ } if (*beta == 0.f) { c__[i__ + j * c_dim1] = *alpha * temp; } else { c__[i__ + j * c_dim1] = *alpha * temp + *beta * c__[ i__ + j * c_dim1]; } /* L200: */ } /* L210: */ } } else { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *n; for (i__ = j; i__ <= i__2; ++i__) { temp = 0.f; i__3 = *k; for (l = 1; l <= i__3; ++l) { temp += a[l + i__ * a_dim1] * a[l + j * a_dim1]; /* L220: */ } if (*beta == 0.f) { c__[i__ + j * c_dim1] = *alpha * temp; } else { c__[i__ + j * c_dim1] = *alpha * temp + *beta * c__[ i__ + j * c_dim1]; } /* L230: */ } /* L240: */ } } } return 0; /* End of SSYRK . */ } /* ssyrk_ */ /* Subroutine */ int strmm_(char *side, char *uplo, char *transa, char *diag, integer *m, integer *n, real *alpha, real *a, integer *lda, real *b, integer *ldb) { /* System generated locals */ integer a_dim1, a_offset, b_dim1, b_offset, i__1, i__2, i__3; /* Local variables */ static integer i__, j, k, info; static real temp; static logical lside; extern logical lsame_(char *, char *); static integer nrowa; static logical upper; extern /* Subroutine */ int xerbla_(char *, integer *); static logical nounit; /* Purpose ======= STRMM performs one of the matrix-matrix operations B := alpha*op( A )*B, or B := alpha*B*op( A ), where alpha is a scalar, B is an m by n matrix, A is a unit, or non-unit, upper or lower triangular matrix and op( A ) is one of op( A ) = A or op( A ) = A'. Parameters ========== SIDE - CHARACTER*1. On entry, SIDE specifies whether op( A ) multiplies B from the left or right as follows: SIDE = 'L' or 'l' B := alpha*op( A )*B. SIDE = 'R' or 'r' B := alpha*B*op( A ). Unchanged on exit. UPLO - CHARACTER*1. On entry, UPLO specifies whether the matrix A is an upper or lower triangular matrix as follows: UPLO = 'U' or 'u' A is an upper triangular matrix. UPLO = 'L' or 'l' A is a lower triangular matrix. Unchanged on exit. TRANSA - CHARACTER*1. On entry, TRANSA specifies the form of op( A ) to be used in the matrix multiplication as follows: TRANSA = 'N' or 'n' op( A ) = A. TRANSA = 'T' or 't' op( A ) = A'. TRANSA = 'C' or 'c' op( A ) = A'. Unchanged on exit. DIAG - CHARACTER*1. On entry, DIAG specifies whether or not A is unit triangular as follows: DIAG = 'U' or 'u' A is assumed to be unit triangular. DIAG = 'N' or 'n' A is not assumed to be unit triangular. Unchanged on exit. M - INTEGER. On entry, M specifies the number of rows of B. M must be at least zero. Unchanged on exit. N - INTEGER. On entry, N specifies the number of columns of B. N must be at least zero. Unchanged on exit. ALPHA - REAL . On entry, ALPHA specifies the scalar alpha. When alpha is zero then A is not referenced and B need not be set before entry. Unchanged on exit. A - REAL array of DIMENSION ( LDA, k ), where k is m when SIDE = 'L' or 'l' and is n when SIDE = 'R' or 'r'. Before entry with UPLO = 'U' or 'u', the leading k by k upper triangular part of the array A must contain the upper triangular matrix and the strictly lower triangular part of A is not referenced. Before entry with UPLO = 'L' or 'l', the leading k by k lower triangular part of the array A must contain the lower triangular matrix and the strictly upper triangular part of A is not referenced. Note that when DIAG = 'U' or 'u', the diagonal elements of A are not referenced either, but are assumed to be unity. Unchanged on exit. LDA - INTEGER. On entry, LDA specifies the first dimension of A as declared in the calling (sub) program. When SIDE = 'L' or 'l' then LDA must be at least max( 1, m ), when SIDE = 'R' or 'r' then LDA must be at least max( 1, n ). Unchanged on exit. B - REAL array of DIMENSION ( LDB, n ). Before entry, the leading m by n part of the array B must contain the matrix B, and on exit is overwritten by the transformed matrix. LDB - INTEGER. On entry, LDB specifies the first dimension of B as declared in the calling (sub) program. LDB must be at least max( 1, m ). Unchanged on exit. Level 3 Blas routine. -- Written on 8-February-1989. Jack Dongarra, Argonne National Laboratory. Iain Duff, AERE Harwell. Jeremy Du Croz, Numerical Algorithms Group Ltd. Sven Hammarling, Numerical Algorithms Group Ltd. Test the input parameters. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; b_dim1 = *ldb; b_offset = 1 + b_dim1; b -= b_offset; /* Function Body */ lside = lsame_(side, "L"); if (lside) { nrowa = *m; } else { nrowa = *n; } nounit = lsame_(diag, "N"); upper = lsame_(uplo, "U"); info = 0; if (! lside && ! lsame_(side, "R")) { info = 1; } else if (! upper && ! lsame_(uplo, "L")) { info = 2; } else if (! lsame_(transa, "N") && ! lsame_(transa, "T") && ! lsame_(transa, "C")) { info = 3; } else if (! lsame_(diag, "U") && ! lsame_(diag, "N")) { info = 4; } else if (*m < 0) { info = 5; } else if (*n < 0) { info = 6; } else if (*lda < max(1,nrowa)) { info = 9; } else if (*ldb < max(1,*m)) { info = 11; } if (info != 0) { xerbla_("STRMM ", &info); return 0; } /* Quick return if possible. */ if (*n == 0) { return 0; } /* And when alpha.eq.zero. */ if (*alpha == 0.f) { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { b[i__ + j * b_dim1] = 0.f; /* L10: */ } /* L20: */ } return 0; } /* Start the operations. */ if (lside) { if (lsame_(transa, "N")) { /* Form B := alpha*A*B. */ if (upper) { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (k = 1; k <= i__2; ++k) { if (b[k + j * b_dim1] != 0.f) { temp = *alpha * b[k + j * b_dim1]; i__3 = k - 1; for (i__ = 1; i__ <= i__3; ++i__) { b[i__ + j * b_dim1] += temp * a[i__ + k * a_dim1]; /* L30: */ } if (nounit) { temp *= a[k + k * a_dim1]; } b[k + j * b_dim1] = temp; } /* L40: */ } /* L50: */ } } else { i__1 = *n; for (j = 1; j <= i__1; ++j) { for (k = *m; k >= 1; --k) { if (b[k + j * b_dim1] != 0.f) { temp = *alpha * b[k + j * b_dim1]; b[k + j * b_dim1] = temp; if (nounit) { b[k + j * b_dim1] *= a[k + k * a_dim1]; } i__2 = *m; for (i__ = k + 1; i__ <= i__2; ++i__) { b[i__ + j * b_dim1] += temp * a[i__ + k * a_dim1]; /* L60: */ } } /* L70: */ } /* L80: */ } } } else { /* Form B := alpha*A'*B. */ if (upper) { i__1 = *n; for (j = 1; j <= i__1; ++j) { for (i__ = *m; i__ >= 1; --i__) { temp = b[i__ + j * b_dim1]; if (nounit) { temp *= a[i__ + i__ * a_dim1]; } i__2 = i__ - 1; for (k = 1; k <= i__2; ++k) { temp += a[k + i__ * a_dim1] * b[k + j * b_dim1]; /* L90: */ } b[i__ + j * b_dim1] = *alpha * temp; /* L100: */ } /* L110: */ } } else { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { temp = b[i__ + j * b_dim1]; if (nounit) { temp *= a[i__ + i__ * a_dim1]; } i__3 = *m; for (k = i__ + 1; k <= i__3; ++k) { temp += a[k + i__ * a_dim1] * b[k + j * b_dim1]; /* L120: */ } b[i__ + j * b_dim1] = *alpha * temp; /* L130: */ } /* L140: */ } } } } else { if (lsame_(transa, "N")) { /* Form B := alpha*B*A. */ if (upper) { for (j = *n; j >= 1; --j) { temp = *alpha; if (nounit) { temp *= a[j + j * a_dim1]; } i__1 = *m; for (i__ = 1; i__ <= i__1; ++i__) { b[i__ + j * b_dim1] = temp * b[i__ + j * b_dim1]; /* L150: */ } i__1 = j - 1; for (k = 1; k <= i__1; ++k) { if (a[k + j * a_dim1] != 0.f) { temp = *alpha * a[k + j * a_dim1]; i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { b[i__ + j * b_dim1] += temp * b[i__ + k * b_dim1]; /* L160: */ } } /* L170: */ } /* L180: */ } } else { i__1 = *n; for (j = 1; j <= i__1; ++j) { temp = *alpha; if (nounit) { temp *= a[j + j * a_dim1]; } i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { b[i__ + j * b_dim1] = temp * b[i__ + j * b_dim1]; /* L190: */ } i__2 = *n; for (k = j + 1; k <= i__2; ++k) { if (a[k + j * a_dim1] != 0.f) { temp = *alpha * a[k + j * a_dim1]; i__3 = *m; for (i__ = 1; i__ <= i__3; ++i__) { b[i__ + j * b_dim1] += temp * b[i__ + k * b_dim1]; /* L200: */ } } /* L210: */ } /* L220: */ } } } else { /* Form B := alpha*B*A'. */ if (upper) { i__1 = *n; for (k = 1; k <= i__1; ++k) { i__2 = k - 1; for (j = 1; j <= i__2; ++j) { if (a[j + k * a_dim1] != 0.f) { temp = *alpha * a[j + k * a_dim1]; i__3 = *m; for (i__ = 1; i__ <= i__3; ++i__) { b[i__ + j * b_dim1] += temp * b[i__ + k * b_dim1]; /* L230: */ } } /* L240: */ } temp = *alpha; if (nounit) { temp *= a[k + k * a_dim1]; } if (temp != 1.f) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { b[i__ + k * b_dim1] = temp * b[i__ + k * b_dim1]; /* L250: */ } } /* L260: */ } } else { for (k = *n; k >= 1; --k) { i__1 = *n; for (j = k + 1; j <= i__1; ++j) { if (a[j + k * a_dim1] != 0.f) { temp = *alpha * a[j + k * a_dim1]; i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { b[i__ + j * b_dim1] += temp * b[i__ + k * b_dim1]; /* L270: */ } } /* L280: */ } temp = *alpha; if (nounit) { temp *= a[k + k * a_dim1]; } if (temp != 1.f) { i__1 = *m; for (i__ = 1; i__ <= i__1; ++i__) { b[i__ + k * b_dim1] = temp * b[i__ + k * b_dim1]; /* L290: */ } } /* L300: */ } } } } return 0; /* End of STRMM . */ } /* strmm_ */ /* Subroutine */ int strmv_(char *uplo, char *trans, char *diag, integer *n, real *a, integer *lda, real *x, integer *incx) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2; /* Local variables */ static integer i__, j, ix, jx, kx, info; static real temp; extern logical lsame_(char *, char *); extern /* Subroutine */ int xerbla_(char *, integer *); static logical nounit; /* Purpose ======= STRMV performs one of the matrix-vector operations x := A*x, or x := A'*x, where x is an n element vector and A is an n by n unit, or non-unit, upper or lower triangular matrix. Parameters ========== UPLO - CHARACTER*1. On entry, UPLO specifies whether the matrix is an upper or lower triangular matrix as follows: UPLO = 'U' or 'u' A is an upper triangular matrix. UPLO = 'L' or 'l' A is a lower triangular matrix. Unchanged on exit. TRANS - CHARACTER*1. On entry, TRANS specifies the operation to be performed as follows: TRANS = 'N' or 'n' x := A*x. TRANS = 'T' or 't' x := A'*x. TRANS = 'C' or 'c' x := A'*x. Unchanged on exit. DIAG - CHARACTER*1. On entry, DIAG specifies whether or not A is unit triangular as follows: DIAG = 'U' or 'u' A is assumed to be unit triangular. DIAG = 'N' or 'n' A is not assumed to be unit triangular. Unchanged on exit. N - INTEGER. On entry, N specifies the order of the matrix A. N must be at least zero. Unchanged on exit. A - REAL array of DIMENSION ( LDA, n ). Before entry with UPLO = 'U' or 'u', the leading n by n upper triangular part of the array A must contain the upper triangular matrix and the strictly lower triangular part of A is not referenced. Before entry with UPLO = 'L' or 'l', the leading n by n lower triangular part of the array A must contain the lower triangular matrix and the strictly upper triangular part of A is not referenced. Note that when DIAG = 'U' or 'u', the diagonal elements of A are not referenced either, but are assumed to be unity. Unchanged on exit. LDA - INTEGER. On entry, LDA specifies the first dimension of A as declared in the calling (sub) program. LDA must be at least max( 1, n ). Unchanged on exit. X - REAL array of dimension at least ( 1 + ( n - 1 )*abs( INCX ) ). Before entry, the incremented array X must contain the n element vector x. On exit, X is overwritten with the tranformed vector x. INCX - INTEGER. On entry, INCX specifies the increment for the elements of X. INCX must not be zero. Unchanged on exit. Level 2 Blas routine. -- Written on 22-October-1986. Jack Dongarra, Argonne National Lab. Jeremy Du Croz, Nag Central Office. Sven Hammarling, Nag Central Office. Richard Hanson, Sandia National Labs. Test the input parameters. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --x; /* Function Body */ info = 0; if (! lsame_(uplo, "U") && ! lsame_(uplo, "L")) { info = 1; } else if (! lsame_(trans, "N") && ! lsame_(trans, "T") && ! lsame_(trans, "C")) { info = 2; } else if (! lsame_(diag, "U") && ! lsame_(diag, "N")) { info = 3; } else if (*n < 0) { info = 4; } else if (*lda < max(1,*n)) { info = 6; } else if (*incx == 0) { info = 8; } if (info != 0) { xerbla_("STRMV ", &info); return 0; } /* Quick return if possible. */ if (*n == 0) { return 0; } nounit = lsame_(diag, "N"); /* Set up the start point in X if the increment is not unity. This will be ( N - 1 )*INCX too small for descending loops. */ if (*incx <= 0) { kx = 1 - (*n - 1) * *incx; } else if (*incx != 1) { kx = 1; } /* Start the operations. In this version the elements of A are accessed sequentially with one pass through A. */ if (lsame_(trans, "N")) { /* Form x := A*x. */ if (lsame_(uplo, "U")) { if (*incx == 1) { i__1 = *n; for (j = 1; j <= i__1; ++j) { if (x[j] != 0.f) { temp = x[j]; i__2 = j - 1; for (i__ = 1; i__ <= i__2; ++i__) { x[i__] += temp * a[i__ + j * a_dim1]; /* L10: */ } if (nounit) { x[j] *= a[j + j * a_dim1]; } } /* L20: */ } } else { jx = kx; i__1 = *n; for (j = 1; j <= i__1; ++j) { if (x[jx] != 0.f) { temp = x[jx]; ix = kx; i__2 = j - 1; for (i__ = 1; i__ <= i__2; ++i__) { x[ix] += temp * a[i__ + j * a_dim1]; ix += *incx; /* L30: */ } if (nounit) { x[jx] *= a[j + j * a_dim1]; } } jx += *incx; /* L40: */ } } } else { if (*incx == 1) { for (j = *n; j >= 1; --j) { if (x[j] != 0.f) { temp = x[j]; i__1 = j + 1; for (i__ = *n; i__ >= i__1; --i__) { x[i__] += temp * a[i__ + j * a_dim1]; /* L50: */ } if (nounit) { x[j] *= a[j + j * a_dim1]; } } /* L60: */ } } else { kx += (*n - 1) * *incx; jx = kx; for (j = *n; j >= 1; --j) { if (x[jx] != 0.f) { temp = x[jx]; ix = kx; i__1 = j + 1; for (i__ = *n; i__ >= i__1; --i__) { x[ix] += temp * a[i__ + j * a_dim1]; ix -= *incx; /* L70: */ } if (nounit) { x[jx] *= a[j + j * a_dim1]; } } jx -= *incx; /* L80: */ } } } } else { /* Form x := A'*x. */ if (lsame_(uplo, "U")) { if (*incx == 1) { for (j = *n; j >= 1; --j) { temp = x[j]; if (nounit) { temp *= a[j + j * a_dim1]; } for (i__ = j - 1; i__ >= 1; --i__) { temp += a[i__ + j * a_dim1] * x[i__]; /* L90: */ } x[j] = temp; /* L100: */ } } else { jx = kx + (*n - 1) * *incx; for (j = *n; j >= 1; --j) { temp = x[jx]; ix = jx; if (nounit) { temp *= a[j + j * a_dim1]; } for (i__ = j - 1; i__ >= 1; --i__) { ix -= *incx; temp += a[i__ + j * a_dim1] * x[ix]; /* L110: */ } x[jx] = temp; jx -= *incx; /* L120: */ } } } else { if (*incx == 1) { i__1 = *n; for (j = 1; j <= i__1; ++j) { temp = x[j]; if (nounit) { temp *= a[j + j * a_dim1]; } i__2 = *n; for (i__ = j + 1; i__ <= i__2; ++i__) { temp += a[i__ + j * a_dim1] * x[i__]; /* L130: */ } x[j] = temp; /* L140: */ } } else { jx = kx; i__1 = *n; for (j = 1; j <= i__1; ++j) { temp = x[jx]; ix = jx; if (nounit) { temp *= a[j + j * a_dim1]; } i__2 = *n; for (i__ = j + 1; i__ <= i__2; ++i__) { ix += *incx; temp += a[i__ + j * a_dim1] * x[ix]; /* L150: */ } x[jx] = temp; jx += *incx; /* L160: */ } } } } return 0; /* End of STRMV . */ } /* strmv_ */ /* Subroutine */ int strsm_(char *side, char *uplo, char *transa, char *diag, integer *m, integer *n, real *alpha, real *a, integer *lda, real *b, integer *ldb) { /* System generated locals */ integer a_dim1, a_offset, b_dim1, b_offset, i__1, i__2, i__3; /* Local variables */ static integer i__, j, k, info; static real temp; static logical lside; extern logical lsame_(char *, char *); static integer nrowa; static logical upper; extern /* Subroutine */ int xerbla_(char *, integer *); static logical nounit; /* Purpose ======= STRSM solves one of the matrix equations op( A )*X = alpha*B, or X*op( A ) = alpha*B, where alpha is a scalar, X and B are m by n matrices, A is a unit, or non-unit, upper or lower triangular matrix and op( A ) is one of op( A ) = A or op( A ) = A'. The matrix X is overwritten on B. Parameters ========== SIDE - CHARACTER*1. On entry, SIDE specifies whether op( A ) appears on the left or right of X as follows: SIDE = 'L' or 'l' op( A )*X = alpha*B. SIDE = 'R' or 'r' X*op( A ) = alpha*B. Unchanged on exit. UPLO - CHARACTER*1. On entry, UPLO specifies whether the matrix A is an upper or lower triangular matrix as follows: UPLO = 'U' or 'u' A is an upper triangular matrix. UPLO = 'L' or 'l' A is a lower triangular matrix. Unchanged on exit. TRANSA - CHARACTER*1. On entry, TRANSA specifies the form of op( A ) to be used in the matrix multiplication as follows: TRANSA = 'N' or 'n' op( A ) = A. TRANSA = 'T' or 't' op( A ) = A'. TRANSA = 'C' or 'c' op( A ) = A'. Unchanged on exit. DIAG - CHARACTER*1. On entry, DIAG specifies whether or not A is unit triangular as follows: DIAG = 'U' or 'u' A is assumed to be unit triangular. DIAG = 'N' or 'n' A is not assumed to be unit triangular. Unchanged on exit. M - INTEGER. On entry, M specifies the number of rows of B. M must be at least zero. Unchanged on exit. N - INTEGER. On entry, N specifies the number of columns of B. N must be at least zero. Unchanged on exit. ALPHA - REAL . On entry, ALPHA specifies the scalar alpha. When alpha is zero then A is not referenced and B need not be set before entry. Unchanged on exit. A - REAL array of DIMENSION ( LDA, k ), where k is m when SIDE = 'L' or 'l' and is n when SIDE = 'R' or 'r'. Before entry with UPLO = 'U' or 'u', the leading k by k upper triangular part of the array A must contain the upper triangular matrix and the strictly lower triangular part of A is not referenced. Before entry with UPLO = 'L' or 'l', the leading k by k lower triangular part of the array A must contain the lower triangular matrix and the strictly upper triangular part of A is not referenced. Note that when DIAG = 'U' or 'u', the diagonal elements of A are not referenced either, but are assumed to be unity. Unchanged on exit. LDA - INTEGER. On entry, LDA specifies the first dimension of A as declared in the calling (sub) program. When SIDE = 'L' or 'l' then LDA must be at least max( 1, m ), when SIDE = 'R' or 'r' then LDA must be at least max( 1, n ). Unchanged on exit. B - REAL array of DIMENSION ( LDB, n ). Before entry, the leading m by n part of the array B must contain the right-hand side matrix B, and on exit is overwritten by the solution matrix X. LDB - INTEGER. On entry, LDB specifies the first dimension of B as declared in the calling (sub) program. LDB must be at least max( 1, m ). Unchanged on exit. Level 3 Blas routine. -- Written on 8-February-1989. Jack Dongarra, Argonne National Laboratory. Iain Duff, AERE Harwell. Jeremy Du Croz, Numerical Algorithms Group Ltd. Sven Hammarling, Numerical Algorithms Group Ltd. Test the input parameters. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; b_dim1 = *ldb; b_offset = 1 + b_dim1; b -= b_offset; /* Function Body */ lside = lsame_(side, "L"); if (lside) { nrowa = *m; } else { nrowa = *n; } nounit = lsame_(diag, "N"); upper = lsame_(uplo, "U"); info = 0; if (! lside && ! lsame_(side, "R")) { info = 1; } else if (! upper && ! lsame_(uplo, "L")) { info = 2; } else if (! lsame_(transa, "N") && ! lsame_(transa, "T") && ! lsame_(transa, "C")) { info = 3; } else if (! lsame_(diag, "U") && ! lsame_(diag, "N")) { info = 4; } else if (*m < 0) { info = 5; } else if (*n < 0) { info = 6; } else if (*lda < max(1,nrowa)) { info = 9; } else if (*ldb < max(1,*m)) { info = 11; } if (info != 0) { xerbla_("STRSM ", &info); return 0; } /* Quick return if possible. */ if (*n == 0) { return 0; } /* And when alpha.eq.zero. */ if (*alpha == 0.f) { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { b[i__ + j * b_dim1] = 0.f; /* L10: */ } /* L20: */ } return 0; } /* Start the operations. */ if (lside) { if (lsame_(transa, "N")) { /* Form B := alpha*inv( A )*B. */ if (upper) { i__1 = *n; for (j = 1; j <= i__1; ++j) { if (*alpha != 1.f) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { b[i__ + j * b_dim1] = *alpha * b[i__ + j * b_dim1] ; /* L30: */ } } for (k = *m; k >= 1; --k) { if (b[k + j * b_dim1] != 0.f) { if (nounit) { b[k + j * b_dim1] /= a[k + k * a_dim1]; } i__2 = k - 1; for (i__ = 1; i__ <= i__2; ++i__) { b[i__ + j * b_dim1] -= b[k + j * b_dim1] * a[ i__ + k * a_dim1]; /* L40: */ } } /* L50: */ } /* L60: */ } } else { i__1 = *n; for (j = 1; j <= i__1; ++j) { if (*alpha != 1.f) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { b[i__ + j * b_dim1] = *alpha * b[i__ + j * b_dim1] ; /* L70: */ } } i__2 = *m; for (k = 1; k <= i__2; ++k) { if (b[k + j * b_dim1] != 0.f) { if (nounit) { b[k + j * b_dim1] /= a[k + k * a_dim1]; } i__3 = *m; for (i__ = k + 1; i__ <= i__3; ++i__) { b[i__ + j * b_dim1] -= b[k + j * b_dim1] * a[ i__ + k * a_dim1]; /* L80: */ } } /* L90: */ } /* L100: */ } } } else { /* Form B := alpha*inv( A' )*B. */ if (upper) { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { temp = *alpha * b[i__ + j * b_dim1]; i__3 = i__ - 1; for (k = 1; k <= i__3; ++k) { temp -= a[k + i__ * a_dim1] * b[k + j * b_dim1]; /* L110: */ } if (nounit) { temp /= a[i__ + i__ * a_dim1]; } b[i__ + j * b_dim1] = temp; /* L120: */ } /* L130: */ } } else { i__1 = *n; for (j = 1; j <= i__1; ++j) { for (i__ = *m; i__ >= 1; --i__) { temp = *alpha * b[i__ + j * b_dim1]; i__2 = *m; for (k = i__ + 1; k <= i__2; ++k) { temp -= a[k + i__ * a_dim1] * b[k + j * b_dim1]; /* L140: */ } if (nounit) { temp /= a[i__ + i__ * a_dim1]; } b[i__ + j * b_dim1] = temp; /* L150: */ } /* L160: */ } } } } else { if (lsame_(transa, "N")) { /* Form B := alpha*B*inv( A ). */ if (upper) { i__1 = *n; for (j = 1; j <= i__1; ++j) { if (*alpha != 1.f) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { b[i__ + j * b_dim1] = *alpha * b[i__ + j * b_dim1] ; /* L170: */ } } i__2 = j - 1; for (k = 1; k <= i__2; ++k) { if (a[k + j * a_dim1] != 0.f) { i__3 = *m; for (i__ = 1; i__ <= i__3; ++i__) { b[i__ + j * b_dim1] -= a[k + j * a_dim1] * b[ i__ + k * b_dim1]; /* L180: */ } } /* L190: */ } if (nounit) { temp = 1.f / a[j + j * a_dim1]; i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { b[i__ + j * b_dim1] = temp * b[i__ + j * b_dim1]; /* L200: */ } } /* L210: */ } } else { for (j = *n; j >= 1; --j) { if (*alpha != 1.f) { i__1 = *m; for (i__ = 1; i__ <= i__1; ++i__) { b[i__ + j * b_dim1] = *alpha * b[i__ + j * b_dim1] ; /* L220: */ } } i__1 = *n; for (k = j + 1; k <= i__1; ++k) { if (a[k + j * a_dim1] != 0.f) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { b[i__ + j * b_dim1] -= a[k + j * a_dim1] * b[ i__ + k * b_dim1]; /* L230: */ } } /* L240: */ } if (nounit) { temp = 1.f / a[j + j * a_dim1]; i__1 = *m; for (i__ = 1; i__ <= i__1; ++i__) { b[i__ + j * b_dim1] = temp * b[i__ + j * b_dim1]; /* L250: */ } } /* L260: */ } } } else { /* Form B := alpha*B*inv( A' ). */ if (upper) { for (k = *n; k >= 1; --k) { if (nounit) { temp = 1.f / a[k + k * a_dim1]; i__1 = *m; for (i__ = 1; i__ <= i__1; ++i__) { b[i__ + k * b_dim1] = temp * b[i__ + k * b_dim1]; /* L270: */ } } i__1 = k - 1; for (j = 1; j <= i__1; ++j) { if (a[j + k * a_dim1] != 0.f) { temp = a[j + k * a_dim1]; i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { b[i__ + j * b_dim1] -= temp * b[i__ + k * b_dim1]; /* L280: */ } } /* L290: */ } if (*alpha != 1.f) { i__1 = *m; for (i__ = 1; i__ <= i__1; ++i__) { b[i__ + k * b_dim1] = *alpha * b[i__ + k * b_dim1] ; /* L300: */ } } /* L310: */ } } else { i__1 = *n; for (k = 1; k <= i__1; ++k) { if (nounit) { temp = 1.f / a[k + k * a_dim1]; i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { b[i__ + k * b_dim1] = temp * b[i__ + k * b_dim1]; /* L320: */ } } i__2 = *n; for (j = k + 1; j <= i__2; ++j) { if (a[j + k * a_dim1] != 0.f) { temp = a[j + k * a_dim1]; i__3 = *m; for (i__ = 1; i__ <= i__3; ++i__) { b[i__ + j * b_dim1] -= temp * b[i__ + k * b_dim1]; /* L330: */ } } /* L340: */ } if (*alpha != 1.f) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { b[i__ + k * b_dim1] = *alpha * b[i__ + k * b_dim1] ; /* L350: */ } } /* L360: */ } } } } return 0; /* End of STRSM . */ } /* strsm_ */ #if 0 /* Subroutine */ int xerbla_(char *srname, integer *info) { /* Format strings */ static char fmt_9999[] = "(\002 ** On entry to \002,a6,\002 parameter nu" "mber \002,i2,\002 had \002,\002an illegal value\002)"; /* Builtin functions */ integer s_wsfe(cilist *), do_fio(integer *, char *, ftnlen), e_wsfe(void); /* Subroutine */ int s_stop(char *, ftnlen); /* Fortran I/O blocks */ static cilist io___425 = { 0, 6, 0, fmt_9999, 0 }; /* -- LAPACK auxiliary routine (preliminary version) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University February 29, 1992 Purpose ======= XERBLA is an error handler for the LAPACK routines. It is called by an LAPACK routine if an input parameter has an invalid value. A message is printed and execution stops. Installers may consider modifying the STOP statement in order to call system-specific exception-handling facilities. Arguments ========= SRNAME (input) CHARACTER*6 The name of the routine which called XERBLA. INFO (input) INTEGER The position of the invalid parameter in the parameter list of the calling routine. */ s_wsfe(&io___425); do_fio(&c__1, srname, (ftnlen)6); do_fio(&c__1, (char *)&(*info), (ftnlen)sizeof(integer)); e_wsfe(); s_stop("", (ftnlen)0); /* End of XERBLA */ return 0; } /* xerbla_ */ #endif /* Subroutine */ int zaxpy_(integer *n, doublecomplex *za, doublecomplex *zx, integer *incx, doublecomplex *zy, integer *incy) { /* System generated locals */ integer i__1, i__2, i__3, i__4; doublecomplex z__1, z__2; /* Local variables */ static integer i__, ix, iy; extern doublereal dcabs1_(doublecomplex *); /* constant times a vector plus a vector. jack dongarra, 3/11/78. modified 12/3/93, array(1) declarations changed to array(*) */ /* Parameter adjustments */ --zy; --zx; /* Function Body */ if (*n <= 0) { return 0; } if (dcabs1_(za) == 0.) { return 0; } if (*incx == 1 && *incy == 1) { goto L20; } /* code for unequal increments or equal increments not equal to 1 */ ix = 1; iy = 1; if (*incx < 0) { ix = (-(*n) + 1) * *incx + 1; } if (*incy < 0) { iy = (-(*n) + 1) * *incy + 1; } i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = iy; i__3 = iy; i__4 = ix; z__2.r = za->r * zx[i__4].r - za->i * zx[i__4].i, z__2.i = za->r * zx[ i__4].i + za->i * zx[i__4].r; z__1.r = zy[i__3].r + z__2.r, z__1.i = zy[i__3].i + z__2.i; zy[i__2].r = z__1.r, zy[i__2].i = z__1.i; ix += *incx; iy += *incy; /* L10: */ } return 0; /* code for both increments equal to 1 */ L20: i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = i__; i__3 = i__; i__4 = i__; z__2.r = za->r * zx[i__4].r - za->i * zx[i__4].i, z__2.i = za->r * zx[ i__4].i + za->i * zx[i__4].r; z__1.r = zy[i__3].r + z__2.r, z__1.i = zy[i__3].i + z__2.i; zy[i__2].r = z__1.r, zy[i__2].i = z__1.i; /* L30: */ } return 0; } /* zaxpy_ */ /* Subroutine */ int zcopy_(integer *n, doublecomplex *zx, integer *incx, doublecomplex *zy, integer *incy) { /* System generated locals */ integer i__1, i__2, i__3; /* Local variables */ static integer i__, ix, iy; /* copies a vector, x, to a vector, y. jack dongarra, linpack, 4/11/78. modified 12/3/93, array(1) declarations changed to array(*) */ /* Parameter adjustments */ --zy; --zx; /* Function Body */ if (*n <= 0) { return 0; } if (*incx == 1 && *incy == 1) { goto L20; } /* code for unequal increments or equal increments not equal to 1 */ ix = 1; iy = 1; if (*incx < 0) { ix = (-(*n) + 1) * *incx + 1; } if (*incy < 0) { iy = (-(*n) + 1) * *incy + 1; } i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = iy; i__3 = ix; zy[i__2].r = zx[i__3].r, zy[i__2].i = zx[i__3].i; ix += *incx; iy += *incy; /* L10: */ } return 0; /* code for both increments equal to 1 */ L20: i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = i__; i__3 = i__; zy[i__2].r = zx[i__3].r, zy[i__2].i = zx[i__3].i; /* L30: */ } return 0; } /* zcopy_ */ /* Double Complex */ VOID zdotc_(doublecomplex * ret_val, integer *n, doublecomplex *zx, integer *incx, doublecomplex *zy, integer *incy) { /* System generated locals */ integer i__1, i__2; doublecomplex z__1, z__2, z__3; /* Builtin functions */ void d_cnjg(doublecomplex *, doublecomplex *); /* Local variables */ static integer i__, ix, iy; static doublecomplex ztemp; /* forms the dot product of a vector. jack dongarra, 3/11/78. modified 12/3/93, array(1) declarations changed to array(*) */ /* Parameter adjustments */ --zy; --zx; /* Function Body */ ztemp.r = 0., ztemp.i = 0.; ret_val->r = 0., ret_val->i = 0.; if (*n <= 0) { return ; } if (*incx == 1 && *incy == 1) { goto L20; } /* code for unequal increments or equal increments not equal to 1 */ ix = 1; iy = 1; if (*incx < 0) { ix = (-(*n) + 1) * *incx + 1; } if (*incy < 0) { iy = (-(*n) + 1) * *incy + 1; } i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { d_cnjg(&z__3, &zx[ix]); i__2 = iy; z__2.r = z__3.r * zy[i__2].r - z__3.i * zy[i__2].i, z__2.i = z__3.r * zy[i__2].i + z__3.i * zy[i__2].r; z__1.r = ztemp.r + z__2.r, z__1.i = ztemp.i + z__2.i; ztemp.r = z__1.r, ztemp.i = z__1.i; ix += *incx; iy += *incy; /* L10: */ } ret_val->r = ztemp.r, ret_val->i = ztemp.i; return ; /* code for both increments equal to 1 */ L20: i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { d_cnjg(&z__3, &zx[i__]); i__2 = i__; z__2.r = z__3.r * zy[i__2].r - z__3.i * zy[i__2].i, z__2.i = z__3.r * zy[i__2].i + z__3.i * zy[i__2].r; z__1.r = ztemp.r + z__2.r, z__1.i = ztemp.i + z__2.i; ztemp.r = z__1.r, ztemp.i = z__1.i; /* L30: */ } ret_val->r = ztemp.r, ret_val->i = ztemp.i; return ; } /* zdotc_ */ /* Double Complex */ VOID zdotu_(doublecomplex * ret_val, integer *n, doublecomplex *zx, integer *incx, doublecomplex *zy, integer *incy) { /* System generated locals */ integer i__1, i__2, i__3; doublecomplex z__1, z__2; /* Local variables */ static integer i__, ix, iy; static doublecomplex ztemp; /* forms the dot product of two vectors. jack dongarra, 3/11/78. modified 12/3/93, array(1) declarations changed to array(*) */ /* Parameter adjustments */ --zy; --zx; /* Function Body */ ztemp.r = 0., ztemp.i = 0.; ret_val->r = 0., ret_val->i = 0.; if (*n <= 0) { return ; } if (*incx == 1 && *incy == 1) { goto L20; } /* code for unequal increments or equal increments not equal to 1 */ ix = 1; iy = 1; if (*incx < 0) { ix = (-(*n) + 1) * *incx + 1; } if (*incy < 0) { iy = (-(*n) + 1) * *incy + 1; } i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = ix; i__3 = iy; z__2.r = zx[i__2].r * zy[i__3].r - zx[i__2].i * zy[i__3].i, z__2.i = zx[i__2].r * zy[i__3].i + zx[i__2].i * zy[i__3].r; z__1.r = ztemp.r + z__2.r, z__1.i = ztemp.i + z__2.i; ztemp.r = z__1.r, ztemp.i = z__1.i; ix += *incx; iy += *incy; /* L10: */ } ret_val->r = ztemp.r, ret_val->i = ztemp.i; return ; /* code for both increments equal to 1 */ L20: i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = i__; i__3 = i__; z__2.r = zx[i__2].r * zy[i__3].r - zx[i__2].i * zy[i__3].i, z__2.i = zx[i__2].r * zy[i__3].i + zx[i__2].i * zy[i__3].r; z__1.r = ztemp.r + z__2.r, z__1.i = ztemp.i + z__2.i; ztemp.r = z__1.r, ztemp.i = z__1.i; /* L30: */ } ret_val->r = ztemp.r, ret_val->i = ztemp.i; return ; } /* zdotu_ */ /* Subroutine */ int zdscal_(integer *n, doublereal *da, doublecomplex *zx, integer *incx) { /* System generated locals */ integer i__1, i__2, i__3; doublecomplex z__1, z__2; /* Local variables */ static integer i__, ix; /* scales a vector by a constant. jack dongarra, 3/11/78. modified 3/93 to return if incx .le. 0. modified 12/3/93, array(1) declarations changed to array(*) */ /* Parameter adjustments */ --zx; /* Function Body */ if ((*n <= 0) || (*incx <= 0)) { return 0; } if (*incx == 1) { goto L20; } /* code for increment not equal to 1 */ ix = 1; i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = ix; z__2.r = *da, z__2.i = 0.; i__3 = ix; z__1.r = z__2.r * zx[i__3].r - z__2.i * zx[i__3].i, z__1.i = z__2.r * zx[i__3].i + z__2.i * zx[i__3].r; zx[i__2].r = z__1.r, zx[i__2].i = z__1.i; ix += *incx; /* L10: */ } return 0; /* code for increment equal to 1 */ L20: i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = i__; z__2.r = *da, z__2.i = 0.; i__3 = i__; z__1.r = z__2.r * zx[i__3].r - z__2.i * zx[i__3].i, z__1.i = z__2.r * zx[i__3].i + z__2.i * zx[i__3].r; zx[i__2].r = z__1.r, zx[i__2].i = z__1.i; /* L30: */ } return 0; } /* zdscal_ */ /* Subroutine */ int zgemm_(char *transa, char *transb, integer *m, integer * n, integer *k, doublecomplex *alpha, doublecomplex *a, integer *lda, doublecomplex *b, integer *ldb, doublecomplex *beta, doublecomplex * c__, integer *ldc) { /* System generated locals */ integer a_dim1, a_offset, b_dim1, b_offset, c_dim1, c_offset, i__1, i__2, i__3, i__4, i__5, i__6; doublecomplex z__1, z__2, z__3, z__4; /* Builtin functions */ void d_cnjg(doublecomplex *, doublecomplex *); /* Local variables */ static integer i__, j, l, info; static logical nota, notb; static doublecomplex temp; static logical conja, conjb; static integer ncola; extern logical lsame_(char *, char *); static integer nrowa, nrowb; extern /* Subroutine */ int xerbla_(char *, integer *); /* Purpose ======= ZGEMM performs one of the matrix-matrix operations C := alpha*op( A )*op( B ) + beta*C, where op( X ) is one of op( X ) = X or op( X ) = X' or op( X ) = conjg( X' ), alpha and beta are scalars, and A, B and C are matrices, with op( A ) an m by k matrix, op( B ) a k by n matrix and C an m by n matrix. Parameters ========== TRANSA - CHARACTER*1. On entry, TRANSA specifies the form of op( A ) to be used in the matrix multiplication as follows: TRANSA = 'N' or 'n', op( A ) = A. TRANSA = 'T' or 't', op( A ) = A'. TRANSA = 'C' or 'c', op( A ) = conjg( A' ). Unchanged on exit. TRANSB - CHARACTER*1. On entry, TRANSB specifies the form of op( B ) to be used in the matrix multiplication as follows: TRANSB = 'N' or 'n', op( B ) = B. TRANSB = 'T' or 't', op( B ) = B'. TRANSB = 'C' or 'c', op( B ) = conjg( B' ). Unchanged on exit. M - INTEGER. On entry, M specifies the number of rows of the matrix op( A ) and of the matrix C. M must be at least zero. Unchanged on exit. N - INTEGER. On entry, N specifies the number of columns of the matrix op( B ) and the number of columns of the matrix C. N must be at least zero. Unchanged on exit. K - INTEGER. On entry, K specifies the number of columns of the matrix op( A ) and the number of rows of the matrix op( B ). K must be at least zero. Unchanged on exit. ALPHA - COMPLEX*16 . On entry, ALPHA specifies the scalar alpha. Unchanged on exit. A - COMPLEX*16 array of DIMENSION ( LDA, ka ), where ka is k when TRANSA = 'N' or 'n', and is m otherwise. Before entry with TRANSA = 'N' or 'n', the leading m by k part of the array A must contain the matrix A, otherwise the leading k by m part of the array A must contain the matrix A. Unchanged on exit. LDA - INTEGER. On entry, LDA specifies the first dimension of A as declared in the calling (sub) program. When TRANSA = 'N' or 'n' then LDA must be at least max( 1, m ), otherwise LDA must be at least max( 1, k ). Unchanged on exit. B - COMPLEX*16 array of DIMENSION ( LDB, kb ), where kb is n when TRANSB = 'N' or 'n', and is k otherwise. Before entry with TRANSB = 'N' or 'n', the leading k by n part of the array B must contain the matrix B, otherwise the leading n by k part of the array B must contain the matrix B. Unchanged on exit. LDB - INTEGER. On entry, LDB specifies the first dimension of B as declared in the calling (sub) program. When TRANSB = 'N' or 'n' then LDB must be at least max( 1, k ), otherwise LDB must be at least max( 1, n ). Unchanged on exit. BETA - COMPLEX*16 . On entry, BETA specifies the scalar beta. When BETA is supplied as zero then C need not be set on input. Unchanged on exit. C - COMPLEX*16 array of DIMENSION ( LDC, n ). Before entry, the leading m by n part of the array C must contain the matrix C, except when beta is zero, in which case C need not be set on entry. On exit, the array C is overwritten by the m by n matrix ( alpha*op( A )*op( B ) + beta*C ). LDC - INTEGER. On entry, LDC specifies the first dimension of C as declared in the calling (sub) program. LDC must be at least max( 1, m ). Unchanged on exit. Level 3 Blas routine. -- Written on 8-February-1989. Jack Dongarra, Argonne National Laboratory. Iain Duff, AERE Harwell. Jeremy Du Croz, Numerical Algorithms Group Ltd. Sven Hammarling, Numerical Algorithms Group Ltd. Set NOTA and NOTB as true if A and B respectively are not conjugated or transposed, set CONJA and CONJB as true if A and B respectively are to be transposed but not conjugated and set NROWA, NCOLA and NROWB as the number of rows and columns of A and the number of rows of B respectively. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; b_dim1 = *ldb; b_offset = 1 + b_dim1; b -= b_offset; c_dim1 = *ldc; c_offset = 1 + c_dim1; c__ -= c_offset; /* Function Body */ nota = lsame_(transa, "N"); notb = lsame_(transb, "N"); conja = lsame_(transa, "C"); conjb = lsame_(transb, "C"); if (nota) { nrowa = *m; ncola = *k; } else { nrowa = *k; ncola = *m; } if (notb) { nrowb = *k; } else { nrowb = *n; } /* Test the input parameters. */ info = 0; if (! nota && ! conja && ! lsame_(transa, "T")) { info = 1; } else if (! notb && ! conjb && ! lsame_(transb, "T")) { info = 2; } else if (*m < 0) { info = 3; } else if (*n < 0) { info = 4; } else if (*k < 0) { info = 5; } else if (*lda < max(1,nrowa)) { info = 8; } else if (*ldb < max(1,nrowb)) { info = 10; } else if (*ldc < max(1,*m)) { info = 13; } if (info != 0) { xerbla_("ZGEMM ", &info); return 0; } /* Quick return if possible. */ if (((*m == 0) || (*n == 0)) || (((alpha->r == 0. && alpha->i == 0.) || (* k == 0)) && (beta->r == 1. && beta->i == 0.))) { return 0; } /* And when alpha.eq.zero. */ if (alpha->r == 0. && alpha->i == 0.) { if (beta->r == 0. && beta->i == 0.) { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * c_dim1; c__[i__3].r = 0., c__[i__3].i = 0.; /* L10: */ } /* L20: */ } } else { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * c_dim1; i__4 = i__ + j * c_dim1; z__1.r = beta->r * c__[i__4].r - beta->i * c__[i__4].i, z__1.i = beta->r * c__[i__4].i + beta->i * c__[ i__4].r; c__[i__3].r = z__1.r, c__[i__3].i = z__1.i; /* L30: */ } /* L40: */ } } return 0; } /* Start the operations. */ if (notb) { if (nota) { /* Form C := alpha*A*B + beta*C. */ i__1 = *n; for (j = 1; j <= i__1; ++j) { if (beta->r == 0. && beta->i == 0.) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * c_dim1; c__[i__3].r = 0., c__[i__3].i = 0.; /* L50: */ } } else if ((beta->r != 1.) || (beta->i != 0.)) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * c_dim1; i__4 = i__ + j * c_dim1; z__1.r = beta->r * c__[i__4].r - beta->i * c__[i__4] .i, z__1.i = beta->r * c__[i__4].i + beta->i * c__[i__4].r; c__[i__3].r = z__1.r, c__[i__3].i = z__1.i; /* L60: */ } } i__2 = *k; for (l = 1; l <= i__2; ++l) { i__3 = l + j * b_dim1; if ((b[i__3].r != 0.) || (b[i__3].i != 0.)) { i__3 = l + j * b_dim1; z__1.r = alpha->r * b[i__3].r - alpha->i * b[i__3].i, z__1.i = alpha->r * b[i__3].i + alpha->i * b[ i__3].r; temp.r = z__1.r, temp.i = z__1.i; i__3 = *m; for (i__ = 1; i__ <= i__3; ++i__) { i__4 = i__ + j * c_dim1; i__5 = i__ + j * c_dim1; i__6 = i__ + l * a_dim1; z__2.r = temp.r * a[i__6].r - temp.i * a[i__6].i, z__2.i = temp.r * a[i__6].i + temp.i * a[ i__6].r; z__1.r = c__[i__5].r + z__2.r, z__1.i = c__[i__5] .i + z__2.i; c__[i__4].r = z__1.r, c__[i__4].i = z__1.i; /* L70: */ } } /* L80: */ } /* L90: */ } } else if (conja) { /* Form C := alpha*conjg( A' )*B + beta*C. */ i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { temp.r = 0., temp.i = 0.; i__3 = *k; for (l = 1; l <= i__3; ++l) { d_cnjg(&z__3, &a[l + i__ * a_dim1]); i__4 = l + j * b_dim1; z__2.r = z__3.r * b[i__4].r - z__3.i * b[i__4].i, z__2.i = z__3.r * b[i__4].i + z__3.i * b[i__4] .r; z__1.r = temp.r + z__2.r, z__1.i = temp.i + z__2.i; temp.r = z__1.r, temp.i = z__1.i; /* L100: */ } if (beta->r == 0. && beta->i == 0.) { i__3 = i__ + j * c_dim1; z__1.r = alpha->r * temp.r - alpha->i * temp.i, z__1.i = alpha->r * temp.i + alpha->i * temp.r; c__[i__3].r = z__1.r, c__[i__3].i = z__1.i; } else { i__3 = i__ + j * c_dim1; z__2.r = alpha->r * temp.r - alpha->i * temp.i, z__2.i = alpha->r * temp.i + alpha->i * temp.r; i__4 = i__ + j * c_dim1; z__3.r = beta->r * c__[i__4].r - beta->i * c__[i__4] .i, z__3.i = beta->r * c__[i__4].i + beta->i * c__[i__4].r; z__1.r = z__2.r + z__3.r, z__1.i = z__2.i + z__3.i; c__[i__3].r = z__1.r, c__[i__3].i = z__1.i; } /* L110: */ } /* L120: */ } } else { /* Form C := alpha*A'*B + beta*C */ i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { temp.r = 0., temp.i = 0.; i__3 = *k; for (l = 1; l <= i__3; ++l) { i__4 = l + i__ * a_dim1; i__5 = l + j * b_dim1; z__2.r = a[i__4].r * b[i__5].r - a[i__4].i * b[i__5] .i, z__2.i = a[i__4].r * b[i__5].i + a[i__4] .i * b[i__5].r; z__1.r = temp.r + z__2.r, z__1.i = temp.i + z__2.i; temp.r = z__1.r, temp.i = z__1.i; /* L130: */ } if (beta->r == 0. && beta->i == 0.) { i__3 = i__ + j * c_dim1; z__1.r = alpha->r * temp.r - alpha->i * temp.i, z__1.i = alpha->r * temp.i + alpha->i * temp.r; c__[i__3].r = z__1.r, c__[i__3].i = z__1.i; } else { i__3 = i__ + j * c_dim1; z__2.r = alpha->r * temp.r - alpha->i * temp.i, z__2.i = alpha->r * temp.i + alpha->i * temp.r; i__4 = i__ + j * c_dim1; z__3.r = beta->r * c__[i__4].r - beta->i * c__[i__4] .i, z__3.i = beta->r * c__[i__4].i + beta->i * c__[i__4].r; z__1.r = z__2.r + z__3.r, z__1.i = z__2.i + z__3.i; c__[i__3].r = z__1.r, c__[i__3].i = z__1.i; } /* L140: */ } /* L150: */ } } } else if (nota) { if (conjb) { /* Form C := alpha*A*conjg( B' ) + beta*C. */ i__1 = *n; for (j = 1; j <= i__1; ++j) { if (beta->r == 0. && beta->i == 0.) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * c_dim1; c__[i__3].r = 0., c__[i__3].i = 0.; /* L160: */ } } else if ((beta->r != 1.) || (beta->i != 0.)) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * c_dim1; i__4 = i__ + j * c_dim1; z__1.r = beta->r * c__[i__4].r - beta->i * c__[i__4] .i, z__1.i = beta->r * c__[i__4].i + beta->i * c__[i__4].r; c__[i__3].r = z__1.r, c__[i__3].i = z__1.i; /* L170: */ } } i__2 = *k; for (l = 1; l <= i__2; ++l) { i__3 = j + l * b_dim1; if ((b[i__3].r != 0.) || (b[i__3].i != 0.)) { d_cnjg(&z__2, &b[j + l * b_dim1]); z__1.r = alpha->r * z__2.r - alpha->i * z__2.i, z__1.i = alpha->r * z__2.i + alpha->i * z__2.r; temp.r = z__1.r, temp.i = z__1.i; i__3 = *m; for (i__ = 1; i__ <= i__3; ++i__) { i__4 = i__ + j * c_dim1; i__5 = i__ + j * c_dim1; i__6 = i__ + l * a_dim1; z__2.r = temp.r * a[i__6].r - temp.i * a[i__6].i, z__2.i = temp.r * a[i__6].i + temp.i * a[ i__6].r; z__1.r = c__[i__5].r + z__2.r, z__1.i = c__[i__5] .i + z__2.i; c__[i__4].r = z__1.r, c__[i__4].i = z__1.i; /* L180: */ } } /* L190: */ } /* L200: */ } } else { /* Form C := alpha*A*B' + beta*C */ i__1 = *n; for (j = 1; j <= i__1; ++j) { if (beta->r == 0. && beta->i == 0.) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * c_dim1; c__[i__3].r = 0., c__[i__3].i = 0.; /* L210: */ } } else if ((beta->r != 1.) || (beta->i != 0.)) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * c_dim1; i__4 = i__ + j * c_dim1; z__1.r = beta->r * c__[i__4].r - beta->i * c__[i__4] .i, z__1.i = beta->r * c__[i__4].i + beta->i * c__[i__4].r; c__[i__3].r = z__1.r, c__[i__3].i = z__1.i; /* L220: */ } } i__2 = *k; for (l = 1; l <= i__2; ++l) { i__3 = j + l * b_dim1; if ((b[i__3].r != 0.) || (b[i__3].i != 0.)) { i__3 = j + l * b_dim1; z__1.r = alpha->r * b[i__3].r - alpha->i * b[i__3].i, z__1.i = alpha->r * b[i__3].i + alpha->i * b[ i__3].r; temp.r = z__1.r, temp.i = z__1.i; i__3 = *m; for (i__ = 1; i__ <= i__3; ++i__) { i__4 = i__ + j * c_dim1; i__5 = i__ + j * c_dim1; i__6 = i__ + l * a_dim1; z__2.r = temp.r * a[i__6].r - temp.i * a[i__6].i, z__2.i = temp.r * a[i__6].i + temp.i * a[ i__6].r; z__1.r = c__[i__5].r + z__2.r, z__1.i = c__[i__5] .i + z__2.i; c__[i__4].r = z__1.r, c__[i__4].i = z__1.i; /* L230: */ } } /* L240: */ } /* L250: */ } } } else if (conja) { if (conjb) { /* Form C := alpha*conjg( A' )*conjg( B' ) + beta*C. */ i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { temp.r = 0., temp.i = 0.; i__3 = *k; for (l = 1; l <= i__3; ++l) { d_cnjg(&z__3, &a[l + i__ * a_dim1]); d_cnjg(&z__4, &b[j + l * b_dim1]); z__2.r = z__3.r * z__4.r - z__3.i * z__4.i, z__2.i = z__3.r * z__4.i + z__3.i * z__4.r; z__1.r = temp.r + z__2.r, z__1.i = temp.i + z__2.i; temp.r = z__1.r, temp.i = z__1.i; /* L260: */ } if (beta->r == 0. && beta->i == 0.) { i__3 = i__ + j * c_dim1; z__1.r = alpha->r * temp.r - alpha->i * temp.i, z__1.i = alpha->r * temp.i + alpha->i * temp.r; c__[i__3].r = z__1.r, c__[i__3].i = z__1.i; } else { i__3 = i__ + j * c_dim1; z__2.r = alpha->r * temp.r - alpha->i * temp.i, z__2.i = alpha->r * temp.i + alpha->i * temp.r; i__4 = i__ + j * c_dim1; z__3.r = beta->r * c__[i__4].r - beta->i * c__[i__4] .i, z__3.i = beta->r * c__[i__4].i + beta->i * c__[i__4].r; z__1.r = z__2.r + z__3.r, z__1.i = z__2.i + z__3.i; c__[i__3].r = z__1.r, c__[i__3].i = z__1.i; } /* L270: */ } /* L280: */ } } else { /* Form C := alpha*conjg( A' )*B' + beta*C */ i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { temp.r = 0., temp.i = 0.; i__3 = *k; for (l = 1; l <= i__3; ++l) { d_cnjg(&z__3, &a[l + i__ * a_dim1]); i__4 = j + l * b_dim1; z__2.r = z__3.r * b[i__4].r - z__3.i * b[i__4].i, z__2.i = z__3.r * b[i__4].i + z__3.i * b[i__4] .r; z__1.r = temp.r + z__2.r, z__1.i = temp.i + z__2.i; temp.r = z__1.r, temp.i = z__1.i; /* L290: */ } if (beta->r == 0. && beta->i == 0.) { i__3 = i__ + j * c_dim1; z__1.r = alpha->r * temp.r - alpha->i * temp.i, z__1.i = alpha->r * temp.i + alpha->i * temp.r; c__[i__3].r = z__1.r, c__[i__3].i = z__1.i; } else { i__3 = i__ + j * c_dim1; z__2.r = alpha->r * temp.r - alpha->i * temp.i, z__2.i = alpha->r * temp.i + alpha->i * temp.r; i__4 = i__ + j * c_dim1; z__3.r = beta->r * c__[i__4].r - beta->i * c__[i__4] .i, z__3.i = beta->r * c__[i__4].i + beta->i * c__[i__4].r; z__1.r = z__2.r + z__3.r, z__1.i = z__2.i + z__3.i; c__[i__3].r = z__1.r, c__[i__3].i = z__1.i; } /* L300: */ } /* L310: */ } } } else { if (conjb) { /* Form C := alpha*A'*conjg( B' ) + beta*C */ i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { temp.r = 0., temp.i = 0.; i__3 = *k; for (l = 1; l <= i__3; ++l) { i__4 = l + i__ * a_dim1; d_cnjg(&z__3, &b[j + l * b_dim1]); z__2.r = a[i__4].r * z__3.r - a[i__4].i * z__3.i, z__2.i = a[i__4].r * z__3.i + a[i__4].i * z__3.r; z__1.r = temp.r + z__2.r, z__1.i = temp.i + z__2.i; temp.r = z__1.r, temp.i = z__1.i; /* L320: */ } if (beta->r == 0. && beta->i == 0.) { i__3 = i__ + j * c_dim1; z__1.r = alpha->r * temp.r - alpha->i * temp.i, z__1.i = alpha->r * temp.i + alpha->i * temp.r; c__[i__3].r = z__1.r, c__[i__3].i = z__1.i; } else { i__3 = i__ + j * c_dim1; z__2.r = alpha->r * temp.r - alpha->i * temp.i, z__2.i = alpha->r * temp.i + alpha->i * temp.r; i__4 = i__ + j * c_dim1; z__3.r = beta->r * c__[i__4].r - beta->i * c__[i__4] .i, z__3.i = beta->r * c__[i__4].i + beta->i * c__[i__4].r; z__1.r = z__2.r + z__3.r, z__1.i = z__2.i + z__3.i; c__[i__3].r = z__1.r, c__[i__3].i = z__1.i; } /* L330: */ } /* L340: */ } } else { /* Form C := alpha*A'*B' + beta*C */ i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { temp.r = 0., temp.i = 0.; i__3 = *k; for (l = 1; l <= i__3; ++l) { i__4 = l + i__ * a_dim1; i__5 = j + l * b_dim1; z__2.r = a[i__4].r * b[i__5].r - a[i__4].i * b[i__5] .i, z__2.i = a[i__4].r * b[i__5].i + a[i__4] .i * b[i__5].r; z__1.r = temp.r + z__2.r, z__1.i = temp.i + z__2.i; temp.r = z__1.r, temp.i = z__1.i; /* L350: */ } if (beta->r == 0. && beta->i == 0.) { i__3 = i__ + j * c_dim1; z__1.r = alpha->r * temp.r - alpha->i * temp.i, z__1.i = alpha->r * temp.i + alpha->i * temp.r; c__[i__3].r = z__1.r, c__[i__3].i = z__1.i; } else { i__3 = i__ + j * c_dim1; z__2.r = alpha->r * temp.r - alpha->i * temp.i, z__2.i = alpha->r * temp.i + alpha->i * temp.r; i__4 = i__ + j * c_dim1; z__3.r = beta->r * c__[i__4].r - beta->i * c__[i__4] .i, z__3.i = beta->r * c__[i__4].i + beta->i * c__[i__4].r; z__1.r = z__2.r + z__3.r, z__1.i = z__2.i + z__3.i; c__[i__3].r = z__1.r, c__[i__3].i = z__1.i; } /* L360: */ } /* L370: */ } } } return 0; /* End of ZGEMM . */ } /* zgemm_ */ /* Subroutine */ int zgemv_(char *trans, integer *m, integer *n, doublecomplex *alpha, doublecomplex *a, integer *lda, doublecomplex * x, integer *incx, doublecomplex *beta, doublecomplex *y, integer * incy) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3, i__4, i__5; doublecomplex z__1, z__2, z__3; /* Builtin functions */ void d_cnjg(doublecomplex *, doublecomplex *); /* Local variables */ static integer i__, j, ix, iy, jx, jy, kx, ky, info; static doublecomplex temp; static integer lenx, leny; extern logical lsame_(char *, char *); extern /* Subroutine */ int xerbla_(char *, integer *); static logical noconj; /* Purpose ======= ZGEMV performs one of the matrix-vector operations y := alpha*A*x + beta*y, or y := alpha*A'*x + beta*y, or y := alpha*conjg( A' )*x + beta*y, where alpha and beta are scalars, x and y are vectors and A is an m by n matrix. Parameters ========== TRANS - CHARACTER*1. On entry, TRANS specifies the operation to be performed as follows: TRANS = 'N' or 'n' y := alpha*A*x + beta*y. TRANS = 'T' or 't' y := alpha*A'*x + beta*y. TRANS = 'C' or 'c' y := alpha*conjg( A' )*x + beta*y. Unchanged on exit. M - INTEGER. On entry, M specifies the number of rows of the matrix A. M must be at least zero. Unchanged on exit. N - INTEGER. On entry, N specifies the number of columns of the matrix A. N must be at least zero. Unchanged on exit. ALPHA - COMPLEX*16 . On entry, ALPHA specifies the scalar alpha. Unchanged on exit. A - COMPLEX*16 array of DIMENSION ( LDA, n ). Before entry, the leading m by n part of the array A must contain the matrix of coefficients. Unchanged on exit. LDA - INTEGER. On entry, LDA specifies the first dimension of A as declared in the calling (sub) program. LDA must be at least max( 1, m ). Unchanged on exit. X - COMPLEX*16 array of DIMENSION at least ( 1 + ( n - 1 )*abs( INCX ) ) when TRANS = 'N' or 'n' and at least ( 1 + ( m - 1 )*abs( INCX ) ) otherwise. Before entry, the incremented array X must contain the vector x. Unchanged on exit. INCX - INTEGER. On entry, INCX specifies the increment for the elements of X. INCX must not be zero. Unchanged on exit. BETA - COMPLEX*16 . On entry, BETA specifies the scalar beta. When BETA is supplied as zero then Y need not be set on input. Unchanged on exit. Y - COMPLEX*16 array of DIMENSION at least ( 1 + ( m - 1 )*abs( INCY ) ) when TRANS = 'N' or 'n' and at least ( 1 + ( n - 1 )*abs( INCY ) ) otherwise. Before entry with BETA non-zero, the incremented array Y must contain the vector y. On exit, Y is overwritten by the updated vector y. INCY - INTEGER. On entry, INCY specifies the increment for the elements of Y. INCY must not be zero. Unchanged on exit. Level 2 Blas routine. -- Written on 22-October-1986. Jack Dongarra, Argonne National Lab. Jeremy Du Croz, Nag Central Office. Sven Hammarling, Nag Central Office. Richard Hanson, Sandia National Labs. Test the input parameters. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --x; --y; /* Function Body */ info = 0; if (! lsame_(trans, "N") && ! lsame_(trans, "T") && ! lsame_(trans, "C") ) { info = 1; } else if (*m < 0) { info = 2; } else if (*n < 0) { info = 3; } else if (*lda < max(1,*m)) { info = 6; } else if (*incx == 0) { info = 8; } else if (*incy == 0) { info = 11; } if (info != 0) { xerbla_("ZGEMV ", &info); return 0; } /* Quick return if possible. */ if (((*m == 0) || (*n == 0)) || (alpha->r == 0. && alpha->i == 0. && ( beta->r == 1. && beta->i == 0.))) { return 0; } noconj = lsame_(trans, "T"); /* Set LENX and LENY, the lengths of the vectors x and y, and set up the start points in X and Y. */ if (lsame_(trans, "N")) { lenx = *n; leny = *m; } else { lenx = *m; leny = *n; } if (*incx > 0) { kx = 1; } else { kx = 1 - (lenx - 1) * *incx; } if (*incy > 0) { ky = 1; } else { ky = 1 - (leny - 1) * *incy; } /* Start the operations. In this version the elements of A are accessed sequentially with one pass through A. First form y := beta*y. */ if ((beta->r != 1.) || (beta->i != 0.)) { if (*incy == 1) { if (beta->r == 0. && beta->i == 0.) { i__1 = leny; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = i__; y[i__2].r = 0., y[i__2].i = 0.; /* L10: */ } } else { i__1 = leny; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = i__; i__3 = i__; z__1.r = beta->r * y[i__3].r - beta->i * y[i__3].i, z__1.i = beta->r * y[i__3].i + beta->i * y[i__3] .r; y[i__2].r = z__1.r, y[i__2].i = z__1.i; /* L20: */ } } } else { iy = ky; if (beta->r == 0. && beta->i == 0.) { i__1 = leny; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = iy; y[i__2].r = 0., y[i__2].i = 0.; iy += *incy; /* L30: */ } } else { i__1 = leny; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = iy; i__3 = iy; z__1.r = beta->r * y[i__3].r - beta->i * y[i__3].i, z__1.i = beta->r * y[i__3].i + beta->i * y[i__3] .r; y[i__2].r = z__1.r, y[i__2].i = z__1.i; iy += *incy; /* L40: */ } } } } if (alpha->r == 0. && alpha->i == 0.) { return 0; } if (lsame_(trans, "N")) { /* Form y := alpha*A*x + y. */ jx = kx; if (*incy == 1) { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = jx; if ((x[i__2].r != 0.) || (x[i__2].i != 0.)) { i__2 = jx; z__1.r = alpha->r * x[i__2].r - alpha->i * x[i__2].i, z__1.i = alpha->r * x[i__2].i + alpha->i * x[i__2] .r; temp.r = z__1.r, temp.i = z__1.i; i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__; i__4 = i__; i__5 = i__ + j * a_dim1; z__2.r = temp.r * a[i__5].r - temp.i * a[i__5].i, z__2.i = temp.r * a[i__5].i + temp.i * a[i__5] .r; z__1.r = y[i__4].r + z__2.r, z__1.i = y[i__4].i + z__2.i; y[i__3].r = z__1.r, y[i__3].i = z__1.i; /* L50: */ } } jx += *incx; /* L60: */ } } else { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = jx; if ((x[i__2].r != 0.) || (x[i__2].i != 0.)) { i__2 = jx; z__1.r = alpha->r * x[i__2].r - alpha->i * x[i__2].i, z__1.i = alpha->r * x[i__2].i + alpha->i * x[i__2] .r; temp.r = z__1.r, temp.i = z__1.i; iy = ky; i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = iy; i__4 = iy; i__5 = i__ + j * a_dim1; z__2.r = temp.r * a[i__5].r - temp.i * a[i__5].i, z__2.i = temp.r * a[i__5].i + temp.i * a[i__5] .r; z__1.r = y[i__4].r + z__2.r, z__1.i = y[i__4].i + z__2.i; y[i__3].r = z__1.r, y[i__3].i = z__1.i; iy += *incy; /* L70: */ } } jx += *incx; /* L80: */ } } } else { /* Form y := alpha*A'*x + y or y := alpha*conjg( A' )*x + y. */ jy = ky; if (*incx == 1) { i__1 = *n; for (j = 1; j <= i__1; ++j) { temp.r = 0., temp.i = 0.; if (noconj) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * a_dim1; i__4 = i__; z__2.r = a[i__3].r * x[i__4].r - a[i__3].i * x[i__4] .i, z__2.i = a[i__3].r * x[i__4].i + a[i__3] .i * x[i__4].r; z__1.r = temp.r + z__2.r, z__1.i = temp.i + z__2.i; temp.r = z__1.r, temp.i = z__1.i; /* L90: */ } } else { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { d_cnjg(&z__3, &a[i__ + j * a_dim1]); i__3 = i__; z__2.r = z__3.r * x[i__3].r - z__3.i * x[i__3].i, z__2.i = z__3.r * x[i__3].i + z__3.i * x[i__3] .r; z__1.r = temp.r + z__2.r, z__1.i = temp.i + z__2.i; temp.r = z__1.r, temp.i = z__1.i; /* L100: */ } } i__2 = jy; i__3 = jy; z__2.r = alpha->r * temp.r - alpha->i * temp.i, z__2.i = alpha->r * temp.i + alpha->i * temp.r; z__1.r = y[i__3].r + z__2.r, z__1.i = y[i__3].i + z__2.i; y[i__2].r = z__1.r, y[i__2].i = z__1.i; jy += *incy; /* L110: */ } } else { i__1 = *n; for (j = 1; j <= i__1; ++j) { temp.r = 0., temp.i = 0.; ix = kx; if (noconj) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * a_dim1; i__4 = ix; z__2.r = a[i__3].r * x[i__4].r - a[i__3].i * x[i__4] .i, z__2.i = a[i__3].r * x[i__4].i + a[i__3] .i * x[i__4].r; z__1.r = temp.r + z__2.r, z__1.i = temp.i + z__2.i; temp.r = z__1.r, temp.i = z__1.i; ix += *incx; /* L120: */ } } else { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { d_cnjg(&z__3, &a[i__ + j * a_dim1]); i__3 = ix; z__2.r = z__3.r * x[i__3].r - z__3.i * x[i__3].i, z__2.i = z__3.r * x[i__3].i + z__3.i * x[i__3] .r; z__1.r = temp.r + z__2.r, z__1.i = temp.i + z__2.i; temp.r = z__1.r, temp.i = z__1.i; ix += *incx; /* L130: */ } } i__2 = jy; i__3 = jy; z__2.r = alpha->r * temp.r - alpha->i * temp.i, z__2.i = alpha->r * temp.i + alpha->i * temp.r; z__1.r = y[i__3].r + z__2.r, z__1.i = y[i__3].i + z__2.i; y[i__2].r = z__1.r, y[i__2].i = z__1.i; jy += *incy; /* L140: */ } } } return 0; /* End of ZGEMV . */ } /* zgemv_ */ /* Subroutine */ int zgerc_(integer *m, integer *n, doublecomplex *alpha, doublecomplex *x, integer *incx, doublecomplex *y, integer *incy, doublecomplex *a, integer *lda) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3, i__4, i__5; doublecomplex z__1, z__2; /* Builtin functions */ void d_cnjg(doublecomplex *, doublecomplex *); /* Local variables */ static integer i__, j, ix, jy, kx, info; static doublecomplex temp; extern /* Subroutine */ int xerbla_(char *, integer *); /* Purpose ======= ZGERC performs the rank 1 operation A := alpha*x*conjg( y' ) + A, where alpha is a scalar, x is an m element vector, y is an n element vector and A is an m by n matrix. Parameters ========== M - INTEGER. On entry, M specifies the number of rows of the matrix A. M must be at least zero. Unchanged on exit. N - INTEGER. On entry, N specifies the number of columns of the matrix A. N must be at least zero. Unchanged on exit. ALPHA - COMPLEX*16 . On entry, ALPHA specifies the scalar alpha. Unchanged on exit. X - COMPLEX*16 array of dimension at least ( 1 + ( m - 1 )*abs( INCX ) ). Before entry, the incremented array X must contain the m element vector x. Unchanged on exit. INCX - INTEGER. On entry, INCX specifies the increment for the elements of X. INCX must not be zero. Unchanged on exit. Y - COMPLEX*16 array of dimension at least ( 1 + ( n - 1 )*abs( INCY ) ). Before entry, the incremented array Y must contain the n element vector y. Unchanged on exit. INCY - INTEGER. On entry, INCY specifies the increment for the elements of Y. INCY must not be zero. Unchanged on exit. A - COMPLEX*16 array of DIMENSION ( LDA, n ). Before entry, the leading m by n part of the array A must contain the matrix of coefficients. On exit, A is overwritten by the updated matrix. LDA - INTEGER. On entry, LDA specifies the first dimension of A as declared in the calling (sub) program. LDA must be at least max( 1, m ). Unchanged on exit. Level 2 Blas routine. -- Written on 22-October-1986. Jack Dongarra, Argonne National Lab. Jeremy Du Croz, Nag Central Office. Sven Hammarling, Nag Central Office. Richard Hanson, Sandia National Labs. Test the input parameters. */ /* Parameter adjustments */ --x; --y; a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; /* Function Body */ info = 0; if (*m < 0) { info = 1; } else if (*n < 0) { info = 2; } else if (*incx == 0) { info = 5; } else if (*incy == 0) { info = 7; } else if (*lda < max(1,*m)) { info = 9; } if (info != 0) { xerbla_("ZGERC ", &info); return 0; } /* Quick return if possible. */ if (((*m == 0) || (*n == 0)) || (alpha->r == 0. && alpha->i == 0.)) { return 0; } /* Start the operations. In this version the elements of A are accessed sequentially with one pass through A. */ if (*incy > 0) { jy = 1; } else { jy = 1 - (*n - 1) * *incy; } if (*incx == 1) { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = jy; if ((y[i__2].r != 0.) || (y[i__2].i != 0.)) { d_cnjg(&z__2, &y[jy]); z__1.r = alpha->r * z__2.r - alpha->i * z__2.i, z__1.i = alpha->r * z__2.i + alpha->i * z__2.r; temp.r = z__1.r, temp.i = z__1.i; i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * a_dim1; i__4 = i__ + j * a_dim1; i__5 = i__; z__2.r = x[i__5].r * temp.r - x[i__5].i * temp.i, z__2.i = x[i__5].r * temp.i + x[i__5].i * temp.r; z__1.r = a[i__4].r + z__2.r, z__1.i = a[i__4].i + z__2.i; a[i__3].r = z__1.r, a[i__3].i = z__1.i; /* L10: */ } } jy += *incy; /* L20: */ } } else { if (*incx > 0) { kx = 1; } else { kx = 1 - (*m - 1) * *incx; } i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = jy; if ((y[i__2].r != 0.) || (y[i__2].i != 0.)) { d_cnjg(&z__2, &y[jy]); z__1.r = alpha->r * z__2.r - alpha->i * z__2.i, z__1.i = alpha->r * z__2.i + alpha->i * z__2.r; temp.r = z__1.r, temp.i = z__1.i; ix = kx; i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * a_dim1; i__4 = i__ + j * a_dim1; i__5 = ix; z__2.r = x[i__5].r * temp.r - x[i__5].i * temp.i, z__2.i = x[i__5].r * temp.i + x[i__5].i * temp.r; z__1.r = a[i__4].r + z__2.r, z__1.i = a[i__4].i + z__2.i; a[i__3].r = z__1.r, a[i__3].i = z__1.i; ix += *incx; /* L30: */ } } jy += *incy; /* L40: */ } } return 0; /* End of ZGERC . */ } /* zgerc_ */ /* Subroutine */ int zgeru_(integer *m, integer *n, doublecomplex *alpha, doublecomplex *x, integer *incx, doublecomplex *y, integer *incy, doublecomplex *a, integer *lda) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3, i__4, i__5; doublecomplex z__1, z__2; /* Local variables */ static integer i__, j, ix, jy, kx, info; static doublecomplex temp; extern /* Subroutine */ int xerbla_(char *, integer *); /* Purpose ======= ZGERU performs the rank 1 operation A := alpha*x*y' + A, where alpha is a scalar, x is an m element vector, y is an n element vector and A is an m by n matrix. Parameters ========== M - INTEGER. On entry, M specifies the number of rows of the matrix A. M must be at least zero. Unchanged on exit. N - INTEGER. On entry, N specifies the number of columns of the matrix A. N must be at least zero. Unchanged on exit. ALPHA - COMPLEX*16 . On entry, ALPHA specifies the scalar alpha. Unchanged on exit. X - COMPLEX*16 array of dimension at least ( 1 + ( m - 1 )*abs( INCX ) ). Before entry, the incremented array X must contain the m element vector x. Unchanged on exit. INCX - INTEGER. On entry, INCX specifies the increment for the elements of X. INCX must not be zero. Unchanged on exit. Y - COMPLEX*16 array of dimension at least ( 1 + ( n - 1 )*abs( INCY ) ). Before entry, the incremented array Y must contain the n element vector y. Unchanged on exit. INCY - INTEGER. On entry, INCY specifies the increment for the elements of Y. INCY must not be zero. Unchanged on exit. A - COMPLEX*16 array of DIMENSION ( LDA, n ). Before entry, the leading m by n part of the array A must contain the matrix of coefficients. On exit, A is overwritten by the updated matrix. LDA - INTEGER. On entry, LDA specifies the first dimension of A as declared in the calling (sub) program. LDA must be at least max( 1, m ). Unchanged on exit. Level 2 Blas routine. -- Written on 22-October-1986. Jack Dongarra, Argonne National Lab. Jeremy Du Croz, Nag Central Office. Sven Hammarling, Nag Central Office. Richard Hanson, Sandia National Labs. Test the input parameters. */ /* Parameter adjustments */ --x; --y; a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; /* Function Body */ info = 0; if (*m < 0) { info = 1; } else if (*n < 0) { info = 2; } else if (*incx == 0) { info = 5; } else if (*incy == 0) { info = 7; } else if (*lda < max(1,*m)) { info = 9; } if (info != 0) { xerbla_("ZGERU ", &info); return 0; } /* Quick return if possible. */ if (((*m == 0) || (*n == 0)) || (alpha->r == 0. && alpha->i == 0.)) { return 0; } /* Start the operations. In this version the elements of A are accessed sequentially with one pass through A. */ if (*incy > 0) { jy = 1; } else { jy = 1 - (*n - 1) * *incy; } if (*incx == 1) { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = jy; if ((y[i__2].r != 0.) || (y[i__2].i != 0.)) { i__2 = jy; z__1.r = alpha->r * y[i__2].r - alpha->i * y[i__2].i, z__1.i = alpha->r * y[i__2].i + alpha->i * y[i__2].r; temp.r = z__1.r, temp.i = z__1.i; i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * a_dim1; i__4 = i__ + j * a_dim1; i__5 = i__; z__2.r = x[i__5].r * temp.r - x[i__5].i * temp.i, z__2.i = x[i__5].r * temp.i + x[i__5].i * temp.r; z__1.r = a[i__4].r + z__2.r, z__1.i = a[i__4].i + z__2.i; a[i__3].r = z__1.r, a[i__3].i = z__1.i; /* L10: */ } } jy += *incy; /* L20: */ } } else { if (*incx > 0) { kx = 1; } else { kx = 1 - (*m - 1) * *incx; } i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = jy; if ((y[i__2].r != 0.) || (y[i__2].i != 0.)) { i__2 = jy; z__1.r = alpha->r * y[i__2].r - alpha->i * y[i__2].i, z__1.i = alpha->r * y[i__2].i + alpha->i * y[i__2].r; temp.r = z__1.r, temp.i = z__1.i; ix = kx; i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * a_dim1; i__4 = i__ + j * a_dim1; i__5 = ix; z__2.r = x[i__5].r * temp.r - x[i__5].i * temp.i, z__2.i = x[i__5].r * temp.i + x[i__5].i * temp.r; z__1.r = a[i__4].r + z__2.r, z__1.i = a[i__4].i + z__2.i; a[i__3].r = z__1.r, a[i__3].i = z__1.i; ix += *incx; /* L30: */ } } jy += *incy; /* L40: */ } } return 0; /* End of ZGERU . */ } /* zgeru_ */ /* Subroutine */ int zhemv_(char *uplo, integer *n, doublecomplex *alpha, doublecomplex *a, integer *lda, doublecomplex *x, integer *incx, doublecomplex *beta, doublecomplex *y, integer *incy) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3, i__4, i__5; doublereal d__1; doublecomplex z__1, z__2, z__3, z__4; /* Builtin functions */ void d_cnjg(doublecomplex *, doublecomplex *); /* Local variables */ static integer i__, j, ix, iy, jx, jy, kx, ky, info; static doublecomplex temp1, temp2; extern logical lsame_(char *, char *); extern /* Subroutine */ int xerbla_(char *, integer *); /* Purpose ======= ZHEMV performs the matrix-vector operation y := alpha*A*x + beta*y, where alpha and beta are scalars, x and y are n element vectors and A is an n by n hermitian matrix. Parameters ========== UPLO - CHARACTER*1. On entry, UPLO specifies whether the upper or lower triangular part of the array A is to be referenced as follows: UPLO = 'U' or 'u' Only the upper triangular part of A is to be referenced. UPLO = 'L' or 'l' Only the lower triangular part of A is to be referenced. Unchanged on exit. N - INTEGER. On entry, N specifies the order of the matrix A. N must be at least zero. Unchanged on exit. ALPHA - COMPLEX*16 . On entry, ALPHA specifies the scalar alpha. Unchanged on exit. A - COMPLEX*16 array of DIMENSION ( LDA, n ). Before entry with UPLO = 'U' or 'u', the leading n by n upper triangular part of the array A must contain the upper triangular part of the hermitian matrix and the strictly lower triangular part of A is not referenced. Before entry with UPLO = 'L' or 'l', the leading n by n lower triangular part of the array A must contain the lower triangular part of the hermitian matrix and the strictly upper triangular part of A is not referenced. Note that the imaginary parts of the diagonal elements need not be set and are assumed to be zero. Unchanged on exit. LDA - INTEGER. On entry, LDA specifies the first dimension of A as declared in the calling (sub) program. LDA must be at least max( 1, n ). Unchanged on exit. X - COMPLEX*16 array of dimension at least ( 1 + ( n - 1 )*abs( INCX ) ). Before entry, the incremented array X must contain the n element vector x. Unchanged on exit. INCX - INTEGER. On entry, INCX specifies the increment for the elements of X. INCX must not be zero. Unchanged on exit. BETA - COMPLEX*16 . On entry, BETA specifies the scalar beta. When BETA is supplied as zero then Y need not be set on input. Unchanged on exit. Y - COMPLEX*16 array of dimension at least ( 1 + ( n - 1 )*abs( INCY ) ). Before entry, the incremented array Y must contain the n element vector y. On exit, Y is overwritten by the updated vector y. INCY - INTEGER. On entry, INCY specifies the increment for the elements of Y. INCY must not be zero. Unchanged on exit. Level 2 Blas routine. -- Written on 22-October-1986. Jack Dongarra, Argonne National Lab. Jeremy Du Croz, Nag Central Office. Sven Hammarling, Nag Central Office. Richard Hanson, Sandia National Labs. Test the input parameters. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --x; --y; /* Function Body */ info = 0; if (! lsame_(uplo, "U") && ! lsame_(uplo, "L")) { info = 1; } else if (*n < 0) { info = 2; } else if (*lda < max(1,*n)) { info = 5; } else if (*incx == 0) { info = 7; } else if (*incy == 0) { info = 10; } if (info != 0) { xerbla_("ZHEMV ", &info); return 0; } /* Quick return if possible. */ if ((*n == 0) || (alpha->r == 0. && alpha->i == 0. && (beta->r == 1. && beta->i == 0.))) { return 0; } /* Set up the start points in X and Y. */ if (*incx > 0) { kx = 1; } else { kx = 1 - (*n - 1) * *incx; } if (*incy > 0) { ky = 1; } else { ky = 1 - (*n - 1) * *incy; } /* Start the operations. In this version the elements of A are accessed sequentially with one pass through the triangular part of A. First form y := beta*y. */ if ((beta->r != 1.) || (beta->i != 0.)) { if (*incy == 1) { if (beta->r == 0. && beta->i == 0.) { i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = i__; y[i__2].r = 0., y[i__2].i = 0.; /* L10: */ } } else { i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = i__; i__3 = i__; z__1.r = beta->r * y[i__3].r - beta->i * y[i__3].i, z__1.i = beta->r * y[i__3].i + beta->i * y[i__3] .r; y[i__2].r = z__1.r, y[i__2].i = z__1.i; /* L20: */ } } } else { iy = ky; if (beta->r == 0. && beta->i == 0.) { i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = iy; y[i__2].r = 0., y[i__2].i = 0.; iy += *incy; /* L30: */ } } else { i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = iy; i__3 = iy; z__1.r = beta->r * y[i__3].r - beta->i * y[i__3].i, z__1.i = beta->r * y[i__3].i + beta->i * y[i__3] .r; y[i__2].r = z__1.r, y[i__2].i = z__1.i; iy += *incy; /* L40: */ } } } } if (alpha->r == 0. && alpha->i == 0.) { return 0; } if (lsame_(uplo, "U")) { /* Form y when A is stored in upper triangle. */ if (*incx == 1 && *incy == 1) { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = j; z__1.r = alpha->r * x[i__2].r - alpha->i * x[i__2].i, z__1.i = alpha->r * x[i__2].i + alpha->i * x[i__2].r; temp1.r = z__1.r, temp1.i = z__1.i; temp2.r = 0., temp2.i = 0.; i__2 = j - 1; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__; i__4 = i__; i__5 = i__ + j * a_dim1; z__2.r = temp1.r * a[i__5].r - temp1.i * a[i__5].i, z__2.i = temp1.r * a[i__5].i + temp1.i * a[i__5] .r; z__1.r = y[i__4].r + z__2.r, z__1.i = y[i__4].i + z__2.i; y[i__3].r = z__1.r, y[i__3].i = z__1.i; d_cnjg(&z__3, &a[i__ + j * a_dim1]); i__3 = i__; z__2.r = z__3.r * x[i__3].r - z__3.i * x[i__3].i, z__2.i = z__3.r * x[i__3].i + z__3.i * x[i__3].r; z__1.r = temp2.r + z__2.r, z__1.i = temp2.i + z__2.i; temp2.r = z__1.r, temp2.i = z__1.i; /* L50: */ } i__2 = j; i__3 = j; i__4 = j + j * a_dim1; d__1 = a[i__4].r; z__3.r = d__1 * temp1.r, z__3.i = d__1 * temp1.i; z__2.r = y[i__3].r + z__3.r, z__2.i = y[i__3].i + z__3.i; z__4.r = alpha->r * temp2.r - alpha->i * temp2.i, z__4.i = alpha->r * temp2.i + alpha->i * temp2.r; z__1.r = z__2.r + z__4.r, z__1.i = z__2.i + z__4.i; y[i__2].r = z__1.r, y[i__2].i = z__1.i; /* L60: */ } } else { jx = kx; jy = ky; i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = jx; z__1.r = alpha->r * x[i__2].r - alpha->i * x[i__2].i, z__1.i = alpha->r * x[i__2].i + alpha->i * x[i__2].r; temp1.r = z__1.r, temp1.i = z__1.i; temp2.r = 0., temp2.i = 0.; ix = kx; iy = ky; i__2 = j - 1; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = iy; i__4 = iy; i__5 = i__ + j * a_dim1; z__2.r = temp1.r * a[i__5].r - temp1.i * a[i__5].i, z__2.i = temp1.r * a[i__5].i + temp1.i * a[i__5] .r; z__1.r = y[i__4].r + z__2.r, z__1.i = y[i__4].i + z__2.i; y[i__3].r = z__1.r, y[i__3].i = z__1.i; d_cnjg(&z__3, &a[i__ + j * a_dim1]); i__3 = ix; z__2.r = z__3.r * x[i__3].r - z__3.i * x[i__3].i, z__2.i = z__3.r * x[i__3].i + z__3.i * x[i__3].r; z__1.r = temp2.r + z__2.r, z__1.i = temp2.i + z__2.i; temp2.r = z__1.r, temp2.i = z__1.i; ix += *incx; iy += *incy; /* L70: */ } i__2 = jy; i__3 = jy; i__4 = j + j * a_dim1; d__1 = a[i__4].r; z__3.r = d__1 * temp1.r, z__3.i = d__1 * temp1.i; z__2.r = y[i__3].r + z__3.r, z__2.i = y[i__3].i + z__3.i; z__4.r = alpha->r * temp2.r - alpha->i * temp2.i, z__4.i = alpha->r * temp2.i + alpha->i * temp2.r; z__1.r = z__2.r + z__4.r, z__1.i = z__2.i + z__4.i; y[i__2].r = z__1.r, y[i__2].i = z__1.i; jx += *incx; jy += *incy; /* L80: */ } } } else { /* Form y when A is stored in lower triangle. */ if (*incx == 1 && *incy == 1) { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = j; z__1.r = alpha->r * x[i__2].r - alpha->i * x[i__2].i, z__1.i = alpha->r * x[i__2].i + alpha->i * x[i__2].r; temp1.r = z__1.r, temp1.i = z__1.i; temp2.r = 0., temp2.i = 0.; i__2 = j; i__3 = j; i__4 = j + j * a_dim1; d__1 = a[i__4].r; z__2.r = d__1 * temp1.r, z__2.i = d__1 * temp1.i; z__1.r = y[i__3].r + z__2.r, z__1.i = y[i__3].i + z__2.i; y[i__2].r = z__1.r, y[i__2].i = z__1.i; i__2 = *n; for (i__ = j + 1; i__ <= i__2; ++i__) { i__3 = i__; i__4 = i__; i__5 = i__ + j * a_dim1; z__2.r = temp1.r * a[i__5].r - temp1.i * a[i__5].i, z__2.i = temp1.r * a[i__5].i + temp1.i * a[i__5] .r; z__1.r = y[i__4].r + z__2.r, z__1.i = y[i__4].i + z__2.i; y[i__3].r = z__1.r, y[i__3].i = z__1.i; d_cnjg(&z__3, &a[i__ + j * a_dim1]); i__3 = i__; z__2.r = z__3.r * x[i__3].r - z__3.i * x[i__3].i, z__2.i = z__3.r * x[i__3].i + z__3.i * x[i__3].r; z__1.r = temp2.r + z__2.r, z__1.i = temp2.i + z__2.i; temp2.r = z__1.r, temp2.i = z__1.i; /* L90: */ } i__2 = j; i__3 = j; z__2.r = alpha->r * temp2.r - alpha->i * temp2.i, z__2.i = alpha->r * temp2.i + alpha->i * temp2.r; z__1.r = y[i__3].r + z__2.r, z__1.i = y[i__3].i + z__2.i; y[i__2].r = z__1.r, y[i__2].i = z__1.i; /* L100: */ } } else { jx = kx; jy = ky; i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = jx; z__1.r = alpha->r * x[i__2].r - alpha->i * x[i__2].i, z__1.i = alpha->r * x[i__2].i + alpha->i * x[i__2].r; temp1.r = z__1.r, temp1.i = z__1.i; temp2.r = 0., temp2.i = 0.; i__2 = jy; i__3 = jy; i__4 = j + j * a_dim1; d__1 = a[i__4].r; z__2.r = d__1 * temp1.r, z__2.i = d__1 * temp1.i; z__1.r = y[i__3].r + z__2.r, z__1.i = y[i__3].i + z__2.i; y[i__2].r = z__1.r, y[i__2].i = z__1.i; ix = jx; iy = jy; i__2 = *n; for (i__ = j + 1; i__ <= i__2; ++i__) { ix += *incx; iy += *incy; i__3 = iy; i__4 = iy; i__5 = i__ + j * a_dim1; z__2.r = temp1.r * a[i__5].r - temp1.i * a[i__5].i, z__2.i = temp1.r * a[i__5].i + temp1.i * a[i__5] .r; z__1.r = y[i__4].r + z__2.r, z__1.i = y[i__4].i + z__2.i; y[i__3].r = z__1.r, y[i__3].i = z__1.i; d_cnjg(&z__3, &a[i__ + j * a_dim1]); i__3 = ix; z__2.r = z__3.r * x[i__3].r - z__3.i * x[i__3].i, z__2.i = z__3.r * x[i__3].i + z__3.i * x[i__3].r; z__1.r = temp2.r + z__2.r, z__1.i = temp2.i + z__2.i; temp2.r = z__1.r, temp2.i = z__1.i; /* L110: */ } i__2 = jy; i__3 = jy; z__2.r = alpha->r * temp2.r - alpha->i * temp2.i, z__2.i = alpha->r * temp2.i + alpha->i * temp2.r; z__1.r = y[i__3].r + z__2.r, z__1.i = y[i__3].i + z__2.i; y[i__2].r = z__1.r, y[i__2].i = z__1.i; jx += *incx; jy += *incy; /* L120: */ } } } return 0; /* End of ZHEMV . */ } /* zhemv_ */ /* Subroutine */ int zher2_(char *uplo, integer *n, doublecomplex *alpha, doublecomplex *x, integer *incx, doublecomplex *y, integer *incy, doublecomplex *a, integer *lda) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3, i__4, i__5, i__6; doublereal d__1; doublecomplex z__1, z__2, z__3, z__4; /* Builtin functions */ void d_cnjg(doublecomplex *, doublecomplex *); /* Local variables */ static integer i__, j, ix, iy, jx, jy, kx, ky, info; static doublecomplex temp1, temp2; extern logical lsame_(char *, char *); extern /* Subroutine */ int xerbla_(char *, integer *); /* Purpose ======= ZHER2 performs the hermitian rank 2 operation A := alpha*x*conjg( y' ) + conjg( alpha )*y*conjg( x' ) + A, where alpha is a scalar, x and y are n element vectors and A is an n by n hermitian matrix. Parameters ========== UPLO - CHARACTER*1. On entry, UPLO specifies whether the upper or lower triangular part of the array A is to be referenced as follows: UPLO = 'U' or 'u' Only the upper triangular part of A is to be referenced. UPLO = 'L' or 'l' Only the lower triangular part of A is to be referenced. Unchanged on exit. N - INTEGER. On entry, N specifies the order of the matrix A. N must be at least zero. Unchanged on exit. ALPHA - COMPLEX*16 . On entry, ALPHA specifies the scalar alpha. Unchanged on exit. X - COMPLEX*16 array of dimension at least ( 1 + ( n - 1 )*abs( INCX ) ). Before entry, the incremented array X must contain the n element vector x. Unchanged on exit. INCX - INTEGER. On entry, INCX specifies the increment for the elements of X. INCX must not be zero. Unchanged on exit. Y - COMPLEX*16 array of dimension at least ( 1 + ( n - 1 )*abs( INCY ) ). Before entry, the incremented array Y must contain the n element vector y. Unchanged on exit. INCY - INTEGER. On entry, INCY specifies the increment for the elements of Y. INCY must not be zero. Unchanged on exit. A - COMPLEX*16 array of DIMENSION ( LDA, n ). Before entry with UPLO = 'U' or 'u', the leading n by n upper triangular part of the array A must contain the upper triangular part of the hermitian matrix and the strictly lower triangular part of A is not referenced. On exit, the upper triangular part of the array A is overwritten by the upper triangular part of the updated matrix. Before entry with UPLO = 'L' or 'l', the leading n by n lower triangular part of the array A must contain the lower triangular part of the hermitian matrix and the strictly upper triangular part of A is not referenced. On exit, the lower triangular part of the array A is overwritten by the lower triangular part of the updated matrix. Note that the imaginary parts of the diagonal elements need not be set, they are assumed to be zero, and on exit they are set to zero. LDA - INTEGER. On entry, LDA specifies the first dimension of A as declared in the calling (sub) program. LDA must be at least max( 1, n ). Unchanged on exit. Level 2 Blas routine. -- Written on 22-October-1986. Jack Dongarra, Argonne National Lab. Jeremy Du Croz, Nag Central Office. Sven Hammarling, Nag Central Office. Richard Hanson, Sandia National Labs. Test the input parameters. */ /* Parameter adjustments */ --x; --y; a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; /* Function Body */ info = 0; if (! lsame_(uplo, "U") && ! lsame_(uplo, "L")) { info = 1; } else if (*n < 0) { info = 2; } else if (*incx == 0) { info = 5; } else if (*incy == 0) { info = 7; } else if (*lda < max(1,*n)) { info = 9; } if (info != 0) { xerbla_("ZHER2 ", &info); return 0; } /* Quick return if possible. */ if ((*n == 0) || (alpha->r == 0. && alpha->i == 0.)) { return 0; } /* Set up the start points in X and Y if the increments are not both unity. */ if ((*incx != 1) || (*incy != 1)) { if (*incx > 0) { kx = 1; } else { kx = 1 - (*n - 1) * *incx; } if (*incy > 0) { ky = 1; } else { ky = 1 - (*n - 1) * *incy; } jx = kx; jy = ky; } /* Start the operations. In this version the elements of A are accessed sequentially with one pass through the triangular part of A. */ if (lsame_(uplo, "U")) { /* Form A when A is stored in the upper triangle. */ if (*incx == 1 && *incy == 1) { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = j; i__3 = j; if (((x[i__2].r != 0.) || (x[i__2].i != 0.)) || (((y[i__3].r != 0.) || (y[i__3].i != 0.)))) { d_cnjg(&z__2, &y[j]); z__1.r = alpha->r * z__2.r - alpha->i * z__2.i, z__1.i = alpha->r * z__2.i + alpha->i * z__2.r; temp1.r = z__1.r, temp1.i = z__1.i; i__2 = j; z__2.r = alpha->r * x[i__2].r - alpha->i * x[i__2].i, z__2.i = alpha->r * x[i__2].i + alpha->i * x[i__2] .r; d_cnjg(&z__1, &z__2); temp2.r = z__1.r, temp2.i = z__1.i; i__2 = j - 1; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * a_dim1; i__4 = i__ + j * a_dim1; i__5 = i__; z__3.r = x[i__5].r * temp1.r - x[i__5].i * temp1.i, z__3.i = x[i__5].r * temp1.i + x[i__5].i * temp1.r; z__2.r = a[i__4].r + z__3.r, z__2.i = a[i__4].i + z__3.i; i__6 = i__; z__4.r = y[i__6].r * temp2.r - y[i__6].i * temp2.i, z__4.i = y[i__6].r * temp2.i + y[i__6].i * temp2.r; z__1.r = z__2.r + z__4.r, z__1.i = z__2.i + z__4.i; a[i__3].r = z__1.r, a[i__3].i = z__1.i; /* L10: */ } i__2 = j + j * a_dim1; i__3 = j + j * a_dim1; i__4 = j; z__2.r = x[i__4].r * temp1.r - x[i__4].i * temp1.i, z__2.i = x[i__4].r * temp1.i + x[i__4].i * temp1.r; i__5 = j; z__3.r = y[i__5].r * temp2.r - y[i__5].i * temp2.i, z__3.i = y[i__5].r * temp2.i + y[i__5].i * temp2.r; z__1.r = z__2.r + z__3.r, z__1.i = z__2.i + z__3.i; d__1 = a[i__3].r + z__1.r; a[i__2].r = d__1, a[i__2].i = 0.; } else { i__2 = j + j * a_dim1; i__3 = j + j * a_dim1; d__1 = a[i__3].r; a[i__2].r = d__1, a[i__2].i = 0.; } /* L20: */ } } else { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = jx; i__3 = jy; if (((x[i__2].r != 0.) || (x[i__2].i != 0.)) || (((y[i__3].r != 0.) || (y[i__3].i != 0.)))) { d_cnjg(&z__2, &y[jy]); z__1.r = alpha->r * z__2.r - alpha->i * z__2.i, z__1.i = alpha->r * z__2.i + alpha->i * z__2.r; temp1.r = z__1.r, temp1.i = z__1.i; i__2 = jx; z__2.r = alpha->r * x[i__2].r - alpha->i * x[i__2].i, z__2.i = alpha->r * x[i__2].i + alpha->i * x[i__2] .r; d_cnjg(&z__1, &z__2); temp2.r = z__1.r, temp2.i = z__1.i; ix = kx; iy = ky; i__2 = j - 1; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * a_dim1; i__4 = i__ + j * a_dim1; i__5 = ix; z__3.r = x[i__5].r * temp1.r - x[i__5].i * temp1.i, z__3.i = x[i__5].r * temp1.i + x[i__5].i * temp1.r; z__2.r = a[i__4].r + z__3.r, z__2.i = a[i__4].i + z__3.i; i__6 = iy; z__4.r = y[i__6].r * temp2.r - y[i__6].i * temp2.i, z__4.i = y[i__6].r * temp2.i + y[i__6].i * temp2.r; z__1.r = z__2.r + z__4.r, z__1.i = z__2.i + z__4.i; a[i__3].r = z__1.r, a[i__3].i = z__1.i; ix += *incx; iy += *incy; /* L30: */ } i__2 = j + j * a_dim1; i__3 = j + j * a_dim1; i__4 = jx; z__2.r = x[i__4].r * temp1.r - x[i__4].i * temp1.i, z__2.i = x[i__4].r * temp1.i + x[i__4].i * temp1.r; i__5 = jy; z__3.r = y[i__5].r * temp2.r - y[i__5].i * temp2.i, z__3.i = y[i__5].r * temp2.i + y[i__5].i * temp2.r; z__1.r = z__2.r + z__3.r, z__1.i = z__2.i + z__3.i; d__1 = a[i__3].r + z__1.r; a[i__2].r = d__1, a[i__2].i = 0.; } else { i__2 = j + j * a_dim1; i__3 = j + j * a_dim1; d__1 = a[i__3].r; a[i__2].r = d__1, a[i__2].i = 0.; } jx += *incx; jy += *incy; /* L40: */ } } } else { /* Form A when A is stored in the lower triangle. */ if (*incx == 1 && *incy == 1) { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = j; i__3 = j; if (((x[i__2].r != 0.) || (x[i__2].i != 0.)) || (((y[i__3].r != 0.) || (y[i__3].i != 0.)))) { d_cnjg(&z__2, &y[j]); z__1.r = alpha->r * z__2.r - alpha->i * z__2.i, z__1.i = alpha->r * z__2.i + alpha->i * z__2.r; temp1.r = z__1.r, temp1.i = z__1.i; i__2 = j; z__2.r = alpha->r * x[i__2].r - alpha->i * x[i__2].i, z__2.i = alpha->r * x[i__2].i + alpha->i * x[i__2] .r; d_cnjg(&z__1, &z__2); temp2.r = z__1.r, temp2.i = z__1.i; i__2 = j + j * a_dim1; i__3 = j + j * a_dim1; i__4 = j; z__2.r = x[i__4].r * temp1.r - x[i__4].i * temp1.i, z__2.i = x[i__4].r * temp1.i + x[i__4].i * temp1.r; i__5 = j; z__3.r = y[i__5].r * temp2.r - y[i__5].i * temp2.i, z__3.i = y[i__5].r * temp2.i + y[i__5].i * temp2.r; z__1.r = z__2.r + z__3.r, z__1.i = z__2.i + z__3.i; d__1 = a[i__3].r + z__1.r; a[i__2].r = d__1, a[i__2].i = 0.; i__2 = *n; for (i__ = j + 1; i__ <= i__2; ++i__) { i__3 = i__ + j * a_dim1; i__4 = i__ + j * a_dim1; i__5 = i__; z__3.r = x[i__5].r * temp1.r - x[i__5].i * temp1.i, z__3.i = x[i__5].r * temp1.i + x[i__5].i * temp1.r; z__2.r = a[i__4].r + z__3.r, z__2.i = a[i__4].i + z__3.i; i__6 = i__; z__4.r = y[i__6].r * temp2.r - y[i__6].i * temp2.i, z__4.i = y[i__6].r * temp2.i + y[i__6].i * temp2.r; z__1.r = z__2.r + z__4.r, z__1.i = z__2.i + z__4.i; a[i__3].r = z__1.r, a[i__3].i = z__1.i; /* L50: */ } } else { i__2 = j + j * a_dim1; i__3 = j + j * a_dim1; d__1 = a[i__3].r; a[i__2].r = d__1, a[i__2].i = 0.; } /* L60: */ } } else { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = jx; i__3 = jy; if (((x[i__2].r != 0.) || (x[i__2].i != 0.)) || (((y[i__3].r != 0.) || (y[i__3].i != 0.)))) { d_cnjg(&z__2, &y[jy]); z__1.r = alpha->r * z__2.r - alpha->i * z__2.i, z__1.i = alpha->r * z__2.i + alpha->i * z__2.r; temp1.r = z__1.r, temp1.i = z__1.i; i__2 = jx; z__2.r = alpha->r * x[i__2].r - alpha->i * x[i__2].i, z__2.i = alpha->r * x[i__2].i + alpha->i * x[i__2] .r; d_cnjg(&z__1, &z__2); temp2.r = z__1.r, temp2.i = z__1.i; i__2 = j + j * a_dim1; i__3 = j + j * a_dim1; i__4 = jx; z__2.r = x[i__4].r * temp1.r - x[i__4].i * temp1.i, z__2.i = x[i__4].r * temp1.i + x[i__4].i * temp1.r; i__5 = jy; z__3.r = y[i__5].r * temp2.r - y[i__5].i * temp2.i, z__3.i = y[i__5].r * temp2.i + y[i__5].i * temp2.r; z__1.r = z__2.r + z__3.r, z__1.i = z__2.i + z__3.i; d__1 = a[i__3].r + z__1.r; a[i__2].r = d__1, a[i__2].i = 0.; ix = jx; iy = jy; i__2 = *n; for (i__ = j + 1; i__ <= i__2; ++i__) { ix += *incx; iy += *incy; i__3 = i__ + j * a_dim1; i__4 = i__ + j * a_dim1; i__5 = ix; z__3.r = x[i__5].r * temp1.r - x[i__5].i * temp1.i, z__3.i = x[i__5].r * temp1.i + x[i__5].i * temp1.r; z__2.r = a[i__4].r + z__3.r, z__2.i = a[i__4].i + z__3.i; i__6 = iy; z__4.r = y[i__6].r * temp2.r - y[i__6].i * temp2.i, z__4.i = y[i__6].r * temp2.i + y[i__6].i * temp2.r; z__1.r = z__2.r + z__4.r, z__1.i = z__2.i + z__4.i; a[i__3].r = z__1.r, a[i__3].i = z__1.i; /* L70: */ } } else { i__2 = j + j * a_dim1; i__3 = j + j * a_dim1; d__1 = a[i__3].r; a[i__2].r = d__1, a[i__2].i = 0.; } jx += *incx; jy += *incy; /* L80: */ } } } return 0; /* End of ZHER2 . */ } /* zher2_ */ /* Subroutine */ int zher2k_(char *uplo, char *trans, integer *n, integer *k, doublecomplex *alpha, doublecomplex *a, integer *lda, doublecomplex * b, integer *ldb, doublereal *beta, doublecomplex *c__, integer *ldc) { /* System generated locals */ integer a_dim1, a_offset, b_dim1, b_offset, c_dim1, c_offset, i__1, i__2, i__3, i__4, i__5, i__6, i__7; doublereal d__1; doublecomplex z__1, z__2, z__3, z__4, z__5, z__6; /* Builtin functions */ void d_cnjg(doublecomplex *, doublecomplex *); /* Local variables */ static integer i__, j, l, info; static doublecomplex temp1, temp2; extern logical lsame_(char *, char *); static integer nrowa; static logical upper; extern /* Subroutine */ int xerbla_(char *, integer *); /* Purpose ======= ZHER2K performs one of the hermitian rank 2k operations C := alpha*A*conjg( B' ) + conjg( alpha )*B*conjg( A' ) + beta*C, or C := alpha*conjg( A' )*B + conjg( alpha )*conjg( B' )*A + beta*C, where alpha and beta are scalars with beta real, C is an n by n hermitian matrix and A and B are n by k matrices in the first case and k by n matrices in the second case. Parameters ========== UPLO - CHARACTER*1. On entry, UPLO specifies whether the upper or lower triangular part of the array C is to be referenced as follows: UPLO = 'U' or 'u' Only the upper triangular part of C is to be referenced. UPLO = 'L' or 'l' Only the lower triangular part of C is to be referenced. Unchanged on exit. TRANS - CHARACTER*1. On entry, TRANS specifies the operation to be performed as follows: TRANS = 'N' or 'n' C := alpha*A*conjg( B' ) + conjg( alpha )*B*conjg( A' ) + beta*C. TRANS = 'C' or 'c' C := alpha*conjg( A' )*B + conjg( alpha )*conjg( B' )*A + beta*C. Unchanged on exit. N - INTEGER. On entry, N specifies the order of the matrix C. N must be at least zero. Unchanged on exit. K - INTEGER. On entry with TRANS = 'N' or 'n', K specifies the number of columns of the matrices A and B, and on entry with TRANS = 'C' or 'c', K specifies the number of rows of the matrices A and B. K must be at least zero. Unchanged on exit. ALPHA - COMPLEX*16 . On entry, ALPHA specifies the scalar alpha. Unchanged on exit. A - COMPLEX*16 array of DIMENSION ( LDA, ka ), where ka is k when TRANS = 'N' or 'n', and is n otherwise. Before entry with TRANS = 'N' or 'n', the leading n by k part of the array A must contain the matrix A, otherwise the leading k by n part of the array A must contain the matrix A. Unchanged on exit. LDA - INTEGER. On entry, LDA specifies the first dimension of A as declared in the calling (sub) program. When TRANS = 'N' or 'n' then LDA must be at least max( 1, n ), otherwise LDA must be at least max( 1, k ). Unchanged on exit. B - COMPLEX*16 array of DIMENSION ( LDB, kb ), where kb is k when TRANS = 'N' or 'n', and is n otherwise. Before entry with TRANS = 'N' or 'n', the leading n by k part of the array B must contain the matrix B, otherwise the leading k by n part of the array B must contain the matrix B. Unchanged on exit. LDB - INTEGER. On entry, LDB specifies the first dimension of B as declared in the calling (sub) program. When TRANS = 'N' or 'n' then LDB must be at least max( 1, n ), otherwise LDB must be at least max( 1, k ). Unchanged on exit. BETA - DOUBLE PRECISION . On entry, BETA specifies the scalar beta. Unchanged on exit. C - COMPLEX*16 array of DIMENSION ( LDC, n ). Before entry with UPLO = 'U' or 'u', the leading n by n upper triangular part of the array C must contain the upper triangular part of the hermitian matrix and the strictly lower triangular part of C is not referenced. On exit, the upper triangular part of the array C is overwritten by the upper triangular part of the updated matrix. Before entry with UPLO = 'L' or 'l', the leading n by n lower triangular part of the array C must contain the lower triangular part of the hermitian matrix and the strictly upper triangular part of C is not referenced. On exit, the lower triangular part of the array C is overwritten by the lower triangular part of the updated matrix. Note that the imaginary parts of the diagonal elements need not be set, they are assumed to be zero, and on exit they are set to zero. LDC - INTEGER. On entry, LDC specifies the first dimension of C as declared in the calling (sub) program. LDC must be at least max( 1, n ). Unchanged on exit. Level 3 Blas routine. -- Written on 8-February-1989. Jack Dongarra, Argonne National Laboratory. Iain Duff, AERE Harwell. Jeremy Du Croz, Numerical Algorithms Group Ltd. Sven Hammarling, Numerical Algorithms Group Ltd. -- Modified 8-Nov-93 to set C(J,J) to DBLE( C(J,J) ) when BETA = 1. Ed Anderson, Cray Research Inc. Test the input parameters. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; b_dim1 = *ldb; b_offset = 1 + b_dim1; b -= b_offset; c_dim1 = *ldc; c_offset = 1 + c_dim1; c__ -= c_offset; /* Function Body */ if (lsame_(trans, "N")) { nrowa = *n; } else { nrowa = *k; } upper = lsame_(uplo, "U"); info = 0; if (! upper && ! lsame_(uplo, "L")) { info = 1; } else if (! lsame_(trans, "N") && ! lsame_(trans, "C")) { info = 2; } else if (*n < 0) { info = 3; } else if (*k < 0) { info = 4; } else if (*lda < max(1,nrowa)) { info = 7; } else if (*ldb < max(1,nrowa)) { info = 9; } else if (*ldc < max(1,*n)) { info = 12; } if (info != 0) { xerbla_("ZHER2K", &info); return 0; } /* Quick return if possible. */ if ((*n == 0) || (((alpha->r == 0. && alpha->i == 0.) || (*k == 0)) && * beta == 1.)) { return 0; } /* And when alpha.eq.zero. */ if (alpha->r == 0. && alpha->i == 0.) { if (upper) { if (*beta == 0.) { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = j; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * c_dim1; c__[i__3].r = 0., c__[i__3].i = 0.; /* L10: */ } /* L20: */ } } else { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = j - 1; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * c_dim1; i__4 = i__ + j * c_dim1; z__1.r = *beta * c__[i__4].r, z__1.i = *beta * c__[ i__4].i; c__[i__3].r = z__1.r, c__[i__3].i = z__1.i; /* L30: */ } i__2 = j + j * c_dim1; i__3 = j + j * c_dim1; d__1 = *beta * c__[i__3].r; c__[i__2].r = d__1, c__[i__2].i = 0.; /* L40: */ } } } else { if (*beta == 0.) { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *n; for (i__ = j; i__ <= i__2; ++i__) { i__3 = i__ + j * c_dim1; c__[i__3].r = 0., c__[i__3].i = 0.; /* L50: */ } /* L60: */ } } else { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = j + j * c_dim1; i__3 = j + j * c_dim1; d__1 = *beta * c__[i__3].r; c__[i__2].r = d__1, c__[i__2].i = 0.; i__2 = *n; for (i__ = j + 1; i__ <= i__2; ++i__) { i__3 = i__ + j * c_dim1; i__4 = i__ + j * c_dim1; z__1.r = *beta * c__[i__4].r, z__1.i = *beta * c__[ i__4].i; c__[i__3].r = z__1.r, c__[i__3].i = z__1.i; /* L70: */ } /* L80: */ } } } return 0; } /* Start the operations. */ if (lsame_(trans, "N")) { /* Form C := alpha*A*conjg( B' ) + conjg( alpha )*B*conjg( A' ) + C. */ if (upper) { i__1 = *n; for (j = 1; j <= i__1; ++j) { if (*beta == 0.) { i__2 = j; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * c_dim1; c__[i__3].r = 0., c__[i__3].i = 0.; /* L90: */ } } else if (*beta != 1.) { i__2 = j - 1; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * c_dim1; i__4 = i__ + j * c_dim1; z__1.r = *beta * c__[i__4].r, z__1.i = *beta * c__[ i__4].i; c__[i__3].r = z__1.r, c__[i__3].i = z__1.i; /* L100: */ } i__2 = j + j * c_dim1; i__3 = j + j * c_dim1; d__1 = *beta * c__[i__3].r; c__[i__2].r = d__1, c__[i__2].i = 0.; } else { i__2 = j + j * c_dim1; i__3 = j + j * c_dim1; d__1 = c__[i__3].r; c__[i__2].r = d__1, c__[i__2].i = 0.; } i__2 = *k; for (l = 1; l <= i__2; ++l) { i__3 = j + l * a_dim1; i__4 = j + l * b_dim1; if (((a[i__3].r != 0.) || (a[i__3].i != 0.)) || (((b[i__4] .r != 0.) || (b[i__4].i != 0.)))) { d_cnjg(&z__2, &b[j + l * b_dim1]); z__1.r = alpha->r * z__2.r - alpha->i * z__2.i, z__1.i = alpha->r * z__2.i + alpha->i * z__2.r; temp1.r = z__1.r, temp1.i = z__1.i; i__3 = j + l * a_dim1; z__2.r = alpha->r * a[i__3].r - alpha->i * a[i__3].i, z__2.i = alpha->r * a[i__3].i + alpha->i * a[ i__3].r; d_cnjg(&z__1, &z__2); temp2.r = z__1.r, temp2.i = z__1.i; i__3 = j - 1; for (i__ = 1; i__ <= i__3; ++i__) { i__4 = i__ + j * c_dim1; i__5 = i__ + j * c_dim1; i__6 = i__ + l * a_dim1; z__3.r = a[i__6].r * temp1.r - a[i__6].i * temp1.i, z__3.i = a[i__6].r * temp1.i + a[ i__6].i * temp1.r; z__2.r = c__[i__5].r + z__3.r, z__2.i = c__[i__5] .i + z__3.i; i__7 = i__ + l * b_dim1; z__4.r = b[i__7].r * temp2.r - b[i__7].i * temp2.i, z__4.i = b[i__7].r * temp2.i + b[ i__7].i * temp2.r; z__1.r = z__2.r + z__4.r, z__1.i = z__2.i + z__4.i; c__[i__4].r = z__1.r, c__[i__4].i = z__1.i; /* L110: */ } i__3 = j + j * c_dim1; i__4 = j + j * c_dim1; i__5 = j + l * a_dim1; z__2.r = a[i__5].r * temp1.r - a[i__5].i * temp1.i, z__2.i = a[i__5].r * temp1.i + a[i__5].i * temp1.r; i__6 = j + l * b_dim1; z__3.r = b[i__6].r * temp2.r - b[i__6].i * temp2.i, z__3.i = b[i__6].r * temp2.i + b[i__6].i * temp2.r; z__1.r = z__2.r + z__3.r, z__1.i = z__2.i + z__3.i; d__1 = c__[i__4].r + z__1.r; c__[i__3].r = d__1, c__[i__3].i = 0.; } /* L120: */ } /* L130: */ } } else { i__1 = *n; for (j = 1; j <= i__1; ++j) { if (*beta == 0.) { i__2 = *n; for (i__ = j; i__ <= i__2; ++i__) { i__3 = i__ + j * c_dim1; c__[i__3].r = 0., c__[i__3].i = 0.; /* L140: */ } } else if (*beta != 1.) { i__2 = *n; for (i__ = j + 1; i__ <= i__2; ++i__) { i__3 = i__ + j * c_dim1; i__4 = i__ + j * c_dim1; z__1.r = *beta * c__[i__4].r, z__1.i = *beta * c__[ i__4].i; c__[i__3].r = z__1.r, c__[i__3].i = z__1.i; /* L150: */ } i__2 = j + j * c_dim1; i__3 = j + j * c_dim1; d__1 = *beta * c__[i__3].r; c__[i__2].r = d__1, c__[i__2].i = 0.; } else { i__2 = j + j * c_dim1; i__3 = j + j * c_dim1; d__1 = c__[i__3].r; c__[i__2].r = d__1, c__[i__2].i = 0.; } i__2 = *k; for (l = 1; l <= i__2; ++l) { i__3 = j + l * a_dim1; i__4 = j + l * b_dim1; if (((a[i__3].r != 0.) || (a[i__3].i != 0.)) || (((b[i__4] .r != 0.) || (b[i__4].i != 0.)))) { d_cnjg(&z__2, &b[j + l * b_dim1]); z__1.r = alpha->r * z__2.r - alpha->i * z__2.i, z__1.i = alpha->r * z__2.i + alpha->i * z__2.r; temp1.r = z__1.r, temp1.i = z__1.i; i__3 = j + l * a_dim1; z__2.r = alpha->r * a[i__3].r - alpha->i * a[i__3].i, z__2.i = alpha->r * a[i__3].i + alpha->i * a[ i__3].r; d_cnjg(&z__1, &z__2); temp2.r = z__1.r, temp2.i = z__1.i; i__3 = *n; for (i__ = j + 1; i__ <= i__3; ++i__) { i__4 = i__ + j * c_dim1; i__5 = i__ + j * c_dim1; i__6 = i__ + l * a_dim1; z__3.r = a[i__6].r * temp1.r - a[i__6].i * temp1.i, z__3.i = a[i__6].r * temp1.i + a[ i__6].i * temp1.r; z__2.r = c__[i__5].r + z__3.r, z__2.i = c__[i__5] .i + z__3.i; i__7 = i__ + l * b_dim1; z__4.r = b[i__7].r * temp2.r - b[i__7].i * temp2.i, z__4.i = b[i__7].r * temp2.i + b[ i__7].i * temp2.r; z__1.r = z__2.r + z__4.r, z__1.i = z__2.i + z__4.i; c__[i__4].r = z__1.r, c__[i__4].i = z__1.i; /* L160: */ } i__3 = j + j * c_dim1; i__4 = j + j * c_dim1; i__5 = j + l * a_dim1; z__2.r = a[i__5].r * temp1.r - a[i__5].i * temp1.i, z__2.i = a[i__5].r * temp1.i + a[i__5].i * temp1.r; i__6 = j + l * b_dim1; z__3.r = b[i__6].r * temp2.r - b[i__6].i * temp2.i, z__3.i = b[i__6].r * temp2.i + b[i__6].i * temp2.r; z__1.r = z__2.r + z__3.r, z__1.i = z__2.i + z__3.i; d__1 = c__[i__4].r + z__1.r; c__[i__3].r = d__1, c__[i__3].i = 0.; } /* L170: */ } /* L180: */ } } } else { /* Form C := alpha*conjg( A' )*B + conjg( alpha )*conjg( B' )*A + C. */ if (upper) { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = j; for (i__ = 1; i__ <= i__2; ++i__) { temp1.r = 0., temp1.i = 0.; temp2.r = 0., temp2.i = 0.; i__3 = *k; for (l = 1; l <= i__3; ++l) { d_cnjg(&z__3, &a[l + i__ * a_dim1]); i__4 = l + j * b_dim1; z__2.r = z__3.r * b[i__4].r - z__3.i * b[i__4].i, z__2.i = z__3.r * b[i__4].i + z__3.i * b[i__4] .r; z__1.r = temp1.r + z__2.r, z__1.i = temp1.i + z__2.i; temp1.r = z__1.r, temp1.i = z__1.i; d_cnjg(&z__3, &b[l + i__ * b_dim1]); i__4 = l + j * a_dim1; z__2.r = z__3.r * a[i__4].r - z__3.i * a[i__4].i, z__2.i = z__3.r * a[i__4].i + z__3.i * a[i__4] .r; z__1.r = temp2.r + z__2.r, z__1.i = temp2.i + z__2.i; temp2.r = z__1.r, temp2.i = z__1.i; /* L190: */ } if (i__ == j) { if (*beta == 0.) { i__3 = j + j * c_dim1; z__2.r = alpha->r * temp1.r - alpha->i * temp1.i, z__2.i = alpha->r * temp1.i + alpha->i * temp1.r; d_cnjg(&z__4, alpha); z__3.r = z__4.r * temp2.r - z__4.i * temp2.i, z__3.i = z__4.r * temp2.i + z__4.i * temp2.r; z__1.r = z__2.r + z__3.r, z__1.i = z__2.i + z__3.i; d__1 = z__1.r; c__[i__3].r = d__1, c__[i__3].i = 0.; } else { i__3 = j + j * c_dim1; i__4 = j + j * c_dim1; z__2.r = alpha->r * temp1.r - alpha->i * temp1.i, z__2.i = alpha->r * temp1.i + alpha->i * temp1.r; d_cnjg(&z__4, alpha); z__3.r = z__4.r * temp2.r - z__4.i * temp2.i, z__3.i = z__4.r * temp2.i + z__4.i * temp2.r; z__1.r = z__2.r + z__3.r, z__1.i = z__2.i + z__3.i; d__1 = *beta * c__[i__4].r + z__1.r; c__[i__3].r = d__1, c__[i__3].i = 0.; } } else { if (*beta == 0.) { i__3 = i__ + j * c_dim1; z__2.r = alpha->r * temp1.r - alpha->i * temp1.i, z__2.i = alpha->r * temp1.i + alpha->i * temp1.r; d_cnjg(&z__4, alpha); z__3.r = z__4.r * temp2.r - z__4.i * temp2.i, z__3.i = z__4.r * temp2.i + z__4.i * temp2.r; z__1.r = z__2.r + z__3.r, z__1.i = z__2.i + z__3.i; c__[i__3].r = z__1.r, c__[i__3].i = z__1.i; } else { i__3 = i__ + j * c_dim1; i__4 = i__ + j * c_dim1; z__3.r = *beta * c__[i__4].r, z__3.i = *beta * c__[i__4].i; z__4.r = alpha->r * temp1.r - alpha->i * temp1.i, z__4.i = alpha->r * temp1.i + alpha->i * temp1.r; z__2.r = z__3.r + z__4.r, z__2.i = z__3.i + z__4.i; d_cnjg(&z__6, alpha); z__5.r = z__6.r * temp2.r - z__6.i * temp2.i, z__5.i = z__6.r * temp2.i + z__6.i * temp2.r; z__1.r = z__2.r + z__5.r, z__1.i = z__2.i + z__5.i; c__[i__3].r = z__1.r, c__[i__3].i = z__1.i; } } /* L200: */ } /* L210: */ } } else { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *n; for (i__ = j; i__ <= i__2; ++i__) { temp1.r = 0., temp1.i = 0.; temp2.r = 0., temp2.i = 0.; i__3 = *k; for (l = 1; l <= i__3; ++l) { d_cnjg(&z__3, &a[l + i__ * a_dim1]); i__4 = l + j * b_dim1; z__2.r = z__3.r * b[i__4].r - z__3.i * b[i__4].i, z__2.i = z__3.r * b[i__4].i + z__3.i * b[i__4] .r; z__1.r = temp1.r + z__2.r, z__1.i = temp1.i + z__2.i; temp1.r = z__1.r, temp1.i = z__1.i; d_cnjg(&z__3, &b[l + i__ * b_dim1]); i__4 = l + j * a_dim1; z__2.r = z__3.r * a[i__4].r - z__3.i * a[i__4].i, z__2.i = z__3.r * a[i__4].i + z__3.i * a[i__4] .r; z__1.r = temp2.r + z__2.r, z__1.i = temp2.i + z__2.i; temp2.r = z__1.r, temp2.i = z__1.i; /* L220: */ } if (i__ == j) { if (*beta == 0.) { i__3 = j + j * c_dim1; z__2.r = alpha->r * temp1.r - alpha->i * temp1.i, z__2.i = alpha->r * temp1.i + alpha->i * temp1.r; d_cnjg(&z__4, alpha); z__3.r = z__4.r * temp2.r - z__4.i * temp2.i, z__3.i = z__4.r * temp2.i + z__4.i * temp2.r; z__1.r = z__2.r + z__3.r, z__1.i = z__2.i + z__3.i; d__1 = z__1.r; c__[i__3].r = d__1, c__[i__3].i = 0.; } else { i__3 = j + j * c_dim1; i__4 = j + j * c_dim1; z__2.r = alpha->r * temp1.r - alpha->i * temp1.i, z__2.i = alpha->r * temp1.i + alpha->i * temp1.r; d_cnjg(&z__4, alpha); z__3.r = z__4.r * temp2.r - z__4.i * temp2.i, z__3.i = z__4.r * temp2.i + z__4.i * temp2.r; z__1.r = z__2.r + z__3.r, z__1.i = z__2.i + z__3.i; d__1 = *beta * c__[i__4].r + z__1.r; c__[i__3].r = d__1, c__[i__3].i = 0.; } } else { if (*beta == 0.) { i__3 = i__ + j * c_dim1; z__2.r = alpha->r * temp1.r - alpha->i * temp1.i, z__2.i = alpha->r * temp1.i + alpha->i * temp1.r; d_cnjg(&z__4, alpha); z__3.r = z__4.r * temp2.r - z__4.i * temp2.i, z__3.i = z__4.r * temp2.i + z__4.i * temp2.r; z__1.r = z__2.r + z__3.r, z__1.i = z__2.i + z__3.i; c__[i__3].r = z__1.r, c__[i__3].i = z__1.i; } else { i__3 = i__ + j * c_dim1; i__4 = i__ + j * c_dim1; z__3.r = *beta * c__[i__4].r, z__3.i = *beta * c__[i__4].i; z__4.r = alpha->r * temp1.r - alpha->i * temp1.i, z__4.i = alpha->r * temp1.i + alpha->i * temp1.r; z__2.r = z__3.r + z__4.r, z__2.i = z__3.i + z__4.i; d_cnjg(&z__6, alpha); z__5.r = z__6.r * temp2.r - z__6.i * temp2.i, z__5.i = z__6.r * temp2.i + z__6.i * temp2.r; z__1.r = z__2.r + z__5.r, z__1.i = z__2.i + z__5.i; c__[i__3].r = z__1.r, c__[i__3].i = z__1.i; } } /* L230: */ } /* L240: */ } } } return 0; /* End of ZHER2K. */ } /* zher2k_ */ /* Subroutine */ int zherk_(char *uplo, char *trans, integer *n, integer *k, doublereal *alpha, doublecomplex *a, integer *lda, doublereal *beta, doublecomplex *c__, integer *ldc) { /* System generated locals */ integer a_dim1, a_offset, c_dim1, c_offset, i__1, i__2, i__3, i__4, i__5, i__6; doublereal d__1; doublecomplex z__1, z__2, z__3; /* Builtin functions */ void d_cnjg(doublecomplex *, doublecomplex *); /* Local variables */ static integer i__, j, l, info; static doublecomplex temp; extern logical lsame_(char *, char *); static integer nrowa; static doublereal rtemp; static logical upper; extern /* Subroutine */ int xerbla_(char *, integer *); /* Purpose ======= ZHERK performs one of the hermitian rank k operations C := alpha*A*conjg( A' ) + beta*C, or C := alpha*conjg( A' )*A + beta*C, where alpha and beta are real scalars, C is an n by n hermitian matrix and A is an n by k matrix in the first case and a k by n matrix in the second case. Parameters ========== UPLO - CHARACTER*1. On entry, UPLO specifies whether the upper or lower triangular part of the array C is to be referenced as follows: UPLO = 'U' or 'u' Only the upper triangular part of C is to be referenced. UPLO = 'L' or 'l' Only the lower triangular part of C is to be referenced. Unchanged on exit. TRANS - CHARACTER*1. On entry, TRANS specifies the operation to be performed as follows: TRANS = 'N' or 'n' C := alpha*A*conjg( A' ) + beta*C. TRANS = 'C' or 'c' C := alpha*conjg( A' )*A + beta*C. Unchanged on exit. N - INTEGER. On entry, N specifies the order of the matrix C. N must be at least zero. Unchanged on exit. K - INTEGER. On entry with TRANS = 'N' or 'n', K specifies the number of columns of the matrix A, and on entry with TRANS = 'C' or 'c', K specifies the number of rows of the matrix A. K must be at least zero. Unchanged on exit. ALPHA - DOUBLE PRECISION . On entry, ALPHA specifies the scalar alpha. Unchanged on exit. A - COMPLEX*16 array of DIMENSION ( LDA, ka ), where ka is k when TRANS = 'N' or 'n', and is n otherwise. Before entry with TRANS = 'N' or 'n', the leading n by k part of the array A must contain the matrix A, otherwise the leading k by n part of the array A must contain the matrix A. Unchanged on exit. LDA - INTEGER. On entry, LDA specifies the first dimension of A as declared in the calling (sub) program. When TRANS = 'N' or 'n' then LDA must be at least max( 1, n ), otherwise LDA must be at least max( 1, k ). Unchanged on exit. BETA - DOUBLE PRECISION. On entry, BETA specifies the scalar beta. Unchanged on exit. C - COMPLEX*16 array of DIMENSION ( LDC, n ). Before entry with UPLO = 'U' or 'u', the leading n by n upper triangular part of the array C must contain the upper triangular part of the hermitian matrix and the strictly lower triangular part of C is not referenced. On exit, the upper triangular part of the array C is overwritten by the upper triangular part of the updated matrix. Before entry with UPLO = 'L' or 'l', the leading n by n lower triangular part of the array C must contain the lower triangular part of the hermitian matrix and the strictly upper triangular part of C is not referenced. On exit, the lower triangular part of the array C is overwritten by the lower triangular part of the updated matrix. Note that the imaginary parts of the diagonal elements need not be set, they are assumed to be zero, and on exit they are set to zero. LDC - INTEGER. On entry, LDC specifies the first dimension of C as declared in the calling (sub) program. LDC must be at least max( 1, n ). Unchanged on exit. Level 3 Blas routine. -- Written on 8-February-1989. Jack Dongarra, Argonne National Laboratory. Iain Duff, AERE Harwell. Jeremy Du Croz, Numerical Algorithms Group Ltd. Sven Hammarling, Numerical Algorithms Group Ltd. -- Modified 8-Nov-93 to set C(J,J) to DBLE( C(J,J) ) when BETA = 1. Ed Anderson, Cray Research Inc. Test the input parameters. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; c_dim1 = *ldc; c_offset = 1 + c_dim1; c__ -= c_offset; /* Function Body */ if (lsame_(trans, "N")) { nrowa = *n; } else { nrowa = *k; } upper = lsame_(uplo, "U"); info = 0; if (! upper && ! lsame_(uplo, "L")) { info = 1; } else if (! lsame_(trans, "N") && ! lsame_(trans, "C")) { info = 2; } else if (*n < 0) { info = 3; } else if (*k < 0) { info = 4; } else if (*lda < max(1,nrowa)) { info = 7; } else if (*ldc < max(1,*n)) { info = 10; } if (info != 0) { xerbla_("ZHERK ", &info); return 0; } /* Quick return if possible. */ if ((*n == 0) || (((*alpha == 0.) || (*k == 0)) && *beta == 1.)) { return 0; } /* And when alpha.eq.zero. */ if (*alpha == 0.) { if (upper) { if (*beta == 0.) { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = j; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * c_dim1; c__[i__3].r = 0., c__[i__3].i = 0.; /* L10: */ } /* L20: */ } } else { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = j - 1; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * c_dim1; i__4 = i__ + j * c_dim1; z__1.r = *beta * c__[i__4].r, z__1.i = *beta * c__[ i__4].i; c__[i__3].r = z__1.r, c__[i__3].i = z__1.i; /* L30: */ } i__2 = j + j * c_dim1; i__3 = j + j * c_dim1; d__1 = *beta * c__[i__3].r; c__[i__2].r = d__1, c__[i__2].i = 0.; /* L40: */ } } } else { if (*beta == 0.) { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *n; for (i__ = j; i__ <= i__2; ++i__) { i__3 = i__ + j * c_dim1; c__[i__3].r = 0., c__[i__3].i = 0.; /* L50: */ } /* L60: */ } } else { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = j + j * c_dim1; i__3 = j + j * c_dim1; d__1 = *beta * c__[i__3].r; c__[i__2].r = d__1, c__[i__2].i = 0.; i__2 = *n; for (i__ = j + 1; i__ <= i__2; ++i__) { i__3 = i__ + j * c_dim1; i__4 = i__ + j * c_dim1; z__1.r = *beta * c__[i__4].r, z__1.i = *beta * c__[ i__4].i; c__[i__3].r = z__1.r, c__[i__3].i = z__1.i; /* L70: */ } /* L80: */ } } } return 0; } /* Start the operations. */ if (lsame_(trans, "N")) { /* Form C := alpha*A*conjg( A' ) + beta*C. */ if (upper) { i__1 = *n; for (j = 1; j <= i__1; ++j) { if (*beta == 0.) { i__2 = j; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * c_dim1; c__[i__3].r = 0., c__[i__3].i = 0.; /* L90: */ } } else if (*beta != 1.) { i__2 = j - 1; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * c_dim1; i__4 = i__ + j * c_dim1; z__1.r = *beta * c__[i__4].r, z__1.i = *beta * c__[ i__4].i; c__[i__3].r = z__1.r, c__[i__3].i = z__1.i; /* L100: */ } i__2 = j + j * c_dim1; i__3 = j + j * c_dim1; d__1 = *beta * c__[i__3].r; c__[i__2].r = d__1, c__[i__2].i = 0.; } else { i__2 = j + j * c_dim1; i__3 = j + j * c_dim1; d__1 = c__[i__3].r; c__[i__2].r = d__1, c__[i__2].i = 0.; } i__2 = *k; for (l = 1; l <= i__2; ++l) { i__3 = j + l * a_dim1; if ((a[i__3].r != 0.) || (a[i__3].i != 0.)) { d_cnjg(&z__2, &a[j + l * a_dim1]); z__1.r = *alpha * z__2.r, z__1.i = *alpha * z__2.i; temp.r = z__1.r, temp.i = z__1.i; i__3 = j - 1; for (i__ = 1; i__ <= i__3; ++i__) { i__4 = i__ + j * c_dim1; i__5 = i__ + j * c_dim1; i__6 = i__ + l * a_dim1; z__2.r = temp.r * a[i__6].r - temp.i * a[i__6].i, z__2.i = temp.r * a[i__6].i + temp.i * a[ i__6].r; z__1.r = c__[i__5].r + z__2.r, z__1.i = c__[i__5] .i + z__2.i; c__[i__4].r = z__1.r, c__[i__4].i = z__1.i; /* L110: */ } i__3 = j + j * c_dim1; i__4 = j + j * c_dim1; i__5 = i__ + l * a_dim1; z__1.r = temp.r * a[i__5].r - temp.i * a[i__5].i, z__1.i = temp.r * a[i__5].i + temp.i * a[i__5] .r; d__1 = c__[i__4].r + z__1.r; c__[i__3].r = d__1, c__[i__3].i = 0.; } /* L120: */ } /* L130: */ } } else { i__1 = *n; for (j = 1; j <= i__1; ++j) { if (*beta == 0.) { i__2 = *n; for (i__ = j; i__ <= i__2; ++i__) { i__3 = i__ + j * c_dim1; c__[i__3].r = 0., c__[i__3].i = 0.; /* L140: */ } } else if (*beta != 1.) { i__2 = j + j * c_dim1; i__3 = j + j * c_dim1; d__1 = *beta * c__[i__3].r; c__[i__2].r = d__1, c__[i__2].i = 0.; i__2 = *n; for (i__ = j + 1; i__ <= i__2; ++i__) { i__3 = i__ + j * c_dim1; i__4 = i__ + j * c_dim1; z__1.r = *beta * c__[i__4].r, z__1.i = *beta * c__[ i__4].i; c__[i__3].r = z__1.r, c__[i__3].i = z__1.i; /* L150: */ } } else { i__2 = j + j * c_dim1; i__3 = j + j * c_dim1; d__1 = c__[i__3].r; c__[i__2].r = d__1, c__[i__2].i = 0.; } i__2 = *k; for (l = 1; l <= i__2; ++l) { i__3 = j + l * a_dim1; if ((a[i__3].r != 0.) || (a[i__3].i != 0.)) { d_cnjg(&z__2, &a[j + l * a_dim1]); z__1.r = *alpha * z__2.r, z__1.i = *alpha * z__2.i; temp.r = z__1.r, temp.i = z__1.i; i__3 = j + j * c_dim1; i__4 = j + j * c_dim1; i__5 = j + l * a_dim1; z__1.r = temp.r * a[i__5].r - temp.i * a[i__5].i, z__1.i = temp.r * a[i__5].i + temp.i * a[i__5] .r; d__1 = c__[i__4].r + z__1.r; c__[i__3].r = d__1, c__[i__3].i = 0.; i__3 = *n; for (i__ = j + 1; i__ <= i__3; ++i__) { i__4 = i__ + j * c_dim1; i__5 = i__ + j * c_dim1; i__6 = i__ + l * a_dim1; z__2.r = temp.r * a[i__6].r - temp.i * a[i__6].i, z__2.i = temp.r * a[i__6].i + temp.i * a[ i__6].r; z__1.r = c__[i__5].r + z__2.r, z__1.i = c__[i__5] .i + z__2.i; c__[i__4].r = z__1.r, c__[i__4].i = z__1.i; /* L160: */ } } /* L170: */ } /* L180: */ } } } else { /* Form C := alpha*conjg( A' )*A + beta*C. */ if (upper) { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = j - 1; for (i__ = 1; i__ <= i__2; ++i__) { temp.r = 0., temp.i = 0.; i__3 = *k; for (l = 1; l <= i__3; ++l) { d_cnjg(&z__3, &a[l + i__ * a_dim1]); i__4 = l + j * a_dim1; z__2.r = z__3.r * a[i__4].r - z__3.i * a[i__4].i, z__2.i = z__3.r * a[i__4].i + z__3.i * a[i__4] .r; z__1.r = temp.r + z__2.r, z__1.i = temp.i + z__2.i; temp.r = z__1.r, temp.i = z__1.i; /* L190: */ } if (*beta == 0.) { i__3 = i__ + j * c_dim1; z__1.r = *alpha * temp.r, z__1.i = *alpha * temp.i; c__[i__3].r = z__1.r, c__[i__3].i = z__1.i; } else { i__3 = i__ + j * c_dim1; z__2.r = *alpha * temp.r, z__2.i = *alpha * temp.i; i__4 = i__ + j * c_dim1; z__3.r = *beta * c__[i__4].r, z__3.i = *beta * c__[ i__4].i; z__1.r = z__2.r + z__3.r, z__1.i = z__2.i + z__3.i; c__[i__3].r = z__1.r, c__[i__3].i = z__1.i; } /* L200: */ } rtemp = 0.; i__2 = *k; for (l = 1; l <= i__2; ++l) { d_cnjg(&z__3, &a[l + j * a_dim1]); i__3 = l + j * a_dim1; z__2.r = z__3.r * a[i__3].r - z__3.i * a[i__3].i, z__2.i = z__3.r * a[i__3].i + z__3.i * a[i__3].r; z__1.r = rtemp + z__2.r, z__1.i = z__2.i; rtemp = z__1.r; /* L210: */ } if (*beta == 0.) { i__2 = j + j * c_dim1; d__1 = *alpha * rtemp; c__[i__2].r = d__1, c__[i__2].i = 0.; } else { i__2 = j + j * c_dim1; i__3 = j + j * c_dim1; d__1 = *alpha * rtemp + *beta * c__[i__3].r; c__[i__2].r = d__1, c__[i__2].i = 0.; } /* L220: */ } } else { i__1 = *n; for (j = 1; j <= i__1; ++j) { rtemp = 0.; i__2 = *k; for (l = 1; l <= i__2; ++l) { d_cnjg(&z__3, &a[l + j * a_dim1]); i__3 = l + j * a_dim1; z__2.r = z__3.r * a[i__3].r - z__3.i * a[i__3].i, z__2.i = z__3.r * a[i__3].i + z__3.i * a[i__3].r; z__1.r = rtemp + z__2.r, z__1.i = z__2.i; rtemp = z__1.r; /* L230: */ } if (*beta == 0.) { i__2 = j + j * c_dim1; d__1 = *alpha * rtemp; c__[i__2].r = d__1, c__[i__2].i = 0.; } else { i__2 = j + j * c_dim1; i__3 = j + j * c_dim1; d__1 = *alpha * rtemp + *beta * c__[i__3].r; c__[i__2].r = d__1, c__[i__2].i = 0.; } i__2 = *n; for (i__ = j + 1; i__ <= i__2; ++i__) { temp.r = 0., temp.i = 0.; i__3 = *k; for (l = 1; l <= i__3; ++l) { d_cnjg(&z__3, &a[l + i__ * a_dim1]); i__4 = l + j * a_dim1; z__2.r = z__3.r * a[i__4].r - z__3.i * a[i__4].i, z__2.i = z__3.r * a[i__4].i + z__3.i * a[i__4] .r; z__1.r = temp.r + z__2.r, z__1.i = temp.i + z__2.i; temp.r = z__1.r, temp.i = z__1.i; /* L240: */ } if (*beta == 0.) { i__3 = i__ + j * c_dim1; z__1.r = *alpha * temp.r, z__1.i = *alpha * temp.i; c__[i__3].r = z__1.r, c__[i__3].i = z__1.i; } else { i__3 = i__ + j * c_dim1; z__2.r = *alpha * temp.r, z__2.i = *alpha * temp.i; i__4 = i__ + j * c_dim1; z__3.r = *beta * c__[i__4].r, z__3.i = *beta * c__[ i__4].i; z__1.r = z__2.r + z__3.r, z__1.i = z__2.i + z__3.i; c__[i__3].r = z__1.r, c__[i__3].i = z__1.i; } /* L250: */ } /* L260: */ } } } return 0; /* End of ZHERK . */ } /* zherk_ */ /* Subroutine */ int zscal_(integer *n, doublecomplex *za, doublecomplex *zx, integer *incx) { /* System generated locals */ integer i__1, i__2, i__3; doublecomplex z__1; /* Local variables */ static integer i__, ix; /* scales a vector by a constant. jack dongarra, 3/11/78. modified 3/93 to return if incx .le. 0. modified 12/3/93, array(1) declarations changed to array(*) */ /* Parameter adjustments */ --zx; /* Function Body */ if ((*n <= 0) || (*incx <= 0)) { return 0; } if (*incx == 1) { goto L20; } /* code for increment not equal to 1 */ ix = 1; i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = ix; i__3 = ix; z__1.r = za->r * zx[i__3].r - za->i * zx[i__3].i, z__1.i = za->r * zx[ i__3].i + za->i * zx[i__3].r; zx[i__2].r = z__1.r, zx[i__2].i = z__1.i; ix += *incx; /* L10: */ } return 0; /* code for increment equal to 1 */ L20: i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = i__; i__3 = i__; z__1.r = za->r * zx[i__3].r - za->i * zx[i__3].i, z__1.i = za->r * zx[ i__3].i + za->i * zx[i__3].r; zx[i__2].r = z__1.r, zx[i__2].i = z__1.i; /* L30: */ } return 0; } /* zscal_ */ /* Subroutine */ int zswap_(integer *n, doublecomplex *zx, integer *incx, doublecomplex *zy, integer *incy) { /* System generated locals */ integer i__1, i__2, i__3; /* Local variables */ static integer i__, ix, iy; static doublecomplex ztemp; /* interchanges two vectors. jack dongarra, 3/11/78. modified 12/3/93, array(1) declarations changed to array(*) */ /* Parameter adjustments */ --zy; --zx; /* Function Body */ if (*n <= 0) { return 0; } if (*incx == 1 && *incy == 1) { goto L20; } /* code for unequal increments or equal increments not equal to 1 */ ix = 1; iy = 1; if (*incx < 0) { ix = (-(*n) + 1) * *incx + 1; } if (*incy < 0) { iy = (-(*n) + 1) * *incy + 1; } i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = ix; ztemp.r = zx[i__2].r, ztemp.i = zx[i__2].i; i__2 = ix; i__3 = iy; zx[i__2].r = zy[i__3].r, zx[i__2].i = zy[i__3].i; i__2 = iy; zy[i__2].r = ztemp.r, zy[i__2].i = ztemp.i; ix += *incx; iy += *incy; /* L10: */ } return 0; /* code for both increments equal to 1 */ L20: i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = i__; ztemp.r = zx[i__2].r, ztemp.i = zx[i__2].i; i__2 = i__; i__3 = i__; zx[i__2].r = zy[i__3].r, zx[i__2].i = zy[i__3].i; i__2 = i__; zy[i__2].r = ztemp.r, zy[i__2].i = ztemp.i; /* L30: */ } return 0; } /* zswap_ */ /* Subroutine */ int ztrmm_(char *side, char *uplo, char *transa, char *diag, integer *m, integer *n, doublecomplex *alpha, doublecomplex *a, integer *lda, doublecomplex *b, integer *ldb) { /* System generated locals */ integer a_dim1, a_offset, b_dim1, b_offset, i__1, i__2, i__3, i__4, i__5, i__6; doublecomplex z__1, z__2, z__3; /* Builtin functions */ void d_cnjg(doublecomplex *, doublecomplex *); /* Local variables */ static integer i__, j, k, info; static doublecomplex temp; static logical lside; extern logical lsame_(char *, char *); static integer nrowa; static logical upper; extern /* Subroutine */ int xerbla_(char *, integer *); static logical noconj, nounit; /* Purpose ======= ZTRMM performs one of the matrix-matrix operations B := alpha*op( A )*B, or B := alpha*B*op( A ) where alpha is a scalar, B is an m by n matrix, A is a unit, or non-unit, upper or lower triangular matrix and op( A ) is one of op( A ) = A or op( A ) = A' or op( A ) = conjg( A' ). Parameters ========== SIDE - CHARACTER*1. On entry, SIDE specifies whether op( A ) multiplies B from the left or right as follows: SIDE = 'L' or 'l' B := alpha*op( A )*B. SIDE = 'R' or 'r' B := alpha*B*op( A ). Unchanged on exit. UPLO - CHARACTER*1. On entry, UPLO specifies whether the matrix A is an upper or lower triangular matrix as follows: UPLO = 'U' or 'u' A is an upper triangular matrix. UPLO = 'L' or 'l' A is a lower triangular matrix. Unchanged on exit. TRANSA - CHARACTER*1. On entry, TRANSA specifies the form of op( A ) to be used in the matrix multiplication as follows: TRANSA = 'N' or 'n' op( A ) = A. TRANSA = 'T' or 't' op( A ) = A'. TRANSA = 'C' or 'c' op( A ) = conjg( A' ). Unchanged on exit. DIAG - CHARACTER*1. On entry, DIAG specifies whether or not A is unit triangular as follows: DIAG = 'U' or 'u' A is assumed to be unit triangular. DIAG = 'N' or 'n' A is not assumed to be unit triangular. Unchanged on exit. M - INTEGER. On entry, M specifies the number of rows of B. M must be at least zero. Unchanged on exit. N - INTEGER. On entry, N specifies the number of columns of B. N must be at least zero. Unchanged on exit. ALPHA - COMPLEX*16 . On entry, ALPHA specifies the scalar alpha. When alpha is zero then A is not referenced and B need not be set before entry. Unchanged on exit. A - COMPLEX*16 array of DIMENSION ( LDA, k ), where k is m when SIDE = 'L' or 'l' and is n when SIDE = 'R' or 'r'. Before entry with UPLO = 'U' or 'u', the leading k by k upper triangular part of the array A must contain the upper triangular matrix and the strictly lower triangular part of A is not referenced. Before entry with UPLO = 'L' or 'l', the leading k by k lower triangular part of the array A must contain the lower triangular matrix and the strictly upper triangular part of A is not referenced. Note that when DIAG = 'U' or 'u', the diagonal elements of A are not referenced either, but are assumed to be unity. Unchanged on exit. LDA - INTEGER. On entry, LDA specifies the first dimension of A as declared in the calling (sub) program. When SIDE = 'L' or 'l' then LDA must be at least max( 1, m ), when SIDE = 'R' or 'r' then LDA must be at least max( 1, n ). Unchanged on exit. B - COMPLEX*16 array of DIMENSION ( LDB, n ). Before entry, the leading m by n part of the array B must contain the matrix B, and on exit is overwritten by the transformed matrix. LDB - INTEGER. On entry, LDB specifies the first dimension of B as declared in the calling (sub) program. LDB must be at least max( 1, m ). Unchanged on exit. Level 3 Blas routine. -- Written on 8-February-1989. Jack Dongarra, Argonne National Laboratory. Iain Duff, AERE Harwell. Jeremy Du Croz, Numerical Algorithms Group Ltd. Sven Hammarling, Numerical Algorithms Group Ltd. Test the input parameters. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; b_dim1 = *ldb; b_offset = 1 + b_dim1; b -= b_offset; /* Function Body */ lside = lsame_(side, "L"); if (lside) { nrowa = *m; } else { nrowa = *n; } noconj = lsame_(transa, "T"); nounit = lsame_(diag, "N"); upper = lsame_(uplo, "U"); info = 0; if (! lside && ! lsame_(side, "R")) { info = 1; } else if (! upper && ! lsame_(uplo, "L")) { info = 2; } else if (! lsame_(transa, "N") && ! lsame_(transa, "T") && ! lsame_(transa, "C")) { info = 3; } else if (! lsame_(diag, "U") && ! lsame_(diag, "N")) { info = 4; } else if (*m < 0) { info = 5; } else if (*n < 0) { info = 6; } else if (*lda < max(1,nrowa)) { info = 9; } else if (*ldb < max(1,*m)) { info = 11; } if (info != 0) { xerbla_("ZTRMM ", &info); return 0; } /* Quick return if possible. */ if (*n == 0) { return 0; } /* And when alpha.eq.zero. */ if (alpha->r == 0. && alpha->i == 0.) { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * b_dim1; b[i__3].r = 0., b[i__3].i = 0.; /* L10: */ } /* L20: */ } return 0; } /* Start the operations. */ if (lside) { if (lsame_(transa, "N")) { /* Form B := alpha*A*B. */ if (upper) { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (k = 1; k <= i__2; ++k) { i__3 = k + j * b_dim1; if ((b[i__3].r != 0.) || (b[i__3].i != 0.)) { i__3 = k + j * b_dim1; z__1.r = alpha->r * b[i__3].r - alpha->i * b[i__3] .i, z__1.i = alpha->r * b[i__3].i + alpha->i * b[i__3].r; temp.r = z__1.r, temp.i = z__1.i; i__3 = k - 1; for (i__ = 1; i__ <= i__3; ++i__) { i__4 = i__ + j * b_dim1; i__5 = i__ + j * b_dim1; i__6 = i__ + k * a_dim1; z__2.r = temp.r * a[i__6].r - temp.i * a[i__6] .i, z__2.i = temp.r * a[i__6].i + temp.i * a[i__6].r; z__1.r = b[i__5].r + z__2.r, z__1.i = b[i__5] .i + z__2.i; b[i__4].r = z__1.r, b[i__4].i = z__1.i; /* L30: */ } if (nounit) { i__3 = k + k * a_dim1; z__1.r = temp.r * a[i__3].r - temp.i * a[i__3] .i, z__1.i = temp.r * a[i__3].i + temp.i * a[i__3].r; temp.r = z__1.r, temp.i = z__1.i; } i__3 = k + j * b_dim1; b[i__3].r = temp.r, b[i__3].i = temp.i; } /* L40: */ } /* L50: */ } } else { i__1 = *n; for (j = 1; j <= i__1; ++j) { for (k = *m; k >= 1; --k) { i__2 = k + j * b_dim1; if ((b[i__2].r != 0.) || (b[i__2].i != 0.)) { i__2 = k + j * b_dim1; z__1.r = alpha->r * b[i__2].r - alpha->i * b[i__2] .i, z__1.i = alpha->r * b[i__2].i + alpha->i * b[i__2].r; temp.r = z__1.r, temp.i = z__1.i; i__2 = k + j * b_dim1; b[i__2].r = temp.r, b[i__2].i = temp.i; if (nounit) { i__2 = k + j * b_dim1; i__3 = k + j * b_dim1; i__4 = k + k * a_dim1; z__1.r = b[i__3].r * a[i__4].r - b[i__3].i * a[i__4].i, z__1.i = b[i__3].r * a[ i__4].i + b[i__3].i * a[i__4].r; b[i__2].r = z__1.r, b[i__2].i = z__1.i; } i__2 = *m; for (i__ = k + 1; i__ <= i__2; ++i__) { i__3 = i__ + j * b_dim1; i__4 = i__ + j * b_dim1; i__5 = i__ + k * a_dim1; z__2.r = temp.r * a[i__5].r - temp.i * a[i__5] .i, z__2.i = temp.r * a[i__5].i + temp.i * a[i__5].r; z__1.r = b[i__4].r + z__2.r, z__1.i = b[i__4] .i + z__2.i; b[i__3].r = z__1.r, b[i__3].i = z__1.i; /* L60: */ } } /* L70: */ } /* L80: */ } } } else { /* Form B := alpha*A'*B or B := alpha*conjg( A' )*B. */ if (upper) { i__1 = *n; for (j = 1; j <= i__1; ++j) { for (i__ = *m; i__ >= 1; --i__) { i__2 = i__ + j * b_dim1; temp.r = b[i__2].r, temp.i = b[i__2].i; if (noconj) { if (nounit) { i__2 = i__ + i__ * a_dim1; z__1.r = temp.r * a[i__2].r - temp.i * a[i__2] .i, z__1.i = temp.r * a[i__2].i + temp.i * a[i__2].r; temp.r = z__1.r, temp.i = z__1.i; } i__2 = i__ - 1; for (k = 1; k <= i__2; ++k) { i__3 = k + i__ * a_dim1; i__4 = k + j * b_dim1; z__2.r = a[i__3].r * b[i__4].r - a[i__3].i * b[i__4].i, z__2.i = a[i__3].r * b[ i__4].i + a[i__3].i * b[i__4].r; z__1.r = temp.r + z__2.r, z__1.i = temp.i + z__2.i; temp.r = z__1.r, temp.i = z__1.i; /* L90: */ } } else { if (nounit) { d_cnjg(&z__2, &a[i__ + i__ * a_dim1]); z__1.r = temp.r * z__2.r - temp.i * z__2.i, z__1.i = temp.r * z__2.i + temp.i * z__2.r; temp.r = z__1.r, temp.i = z__1.i; } i__2 = i__ - 1; for (k = 1; k <= i__2; ++k) { d_cnjg(&z__3, &a[k + i__ * a_dim1]); i__3 = k + j * b_dim1; z__2.r = z__3.r * b[i__3].r - z__3.i * b[i__3] .i, z__2.i = z__3.r * b[i__3].i + z__3.i * b[i__3].r; z__1.r = temp.r + z__2.r, z__1.i = temp.i + z__2.i; temp.r = z__1.r, temp.i = z__1.i; /* L100: */ } } i__2 = i__ + j * b_dim1; z__1.r = alpha->r * temp.r - alpha->i * temp.i, z__1.i = alpha->r * temp.i + alpha->i * temp.r; b[i__2].r = z__1.r, b[i__2].i = z__1.i; /* L110: */ } /* L120: */ } } else { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * b_dim1; temp.r = b[i__3].r, temp.i = b[i__3].i; if (noconj) { if (nounit) { i__3 = i__ + i__ * a_dim1; z__1.r = temp.r * a[i__3].r - temp.i * a[i__3] .i, z__1.i = temp.r * a[i__3].i + temp.i * a[i__3].r; temp.r = z__1.r, temp.i = z__1.i; } i__3 = *m; for (k = i__ + 1; k <= i__3; ++k) { i__4 = k + i__ * a_dim1; i__5 = k + j * b_dim1; z__2.r = a[i__4].r * b[i__5].r - a[i__4].i * b[i__5].i, z__2.i = a[i__4].r * b[ i__5].i + a[i__4].i * b[i__5].r; z__1.r = temp.r + z__2.r, z__1.i = temp.i + z__2.i; temp.r = z__1.r, temp.i = z__1.i; /* L130: */ } } else { if (nounit) { d_cnjg(&z__2, &a[i__ + i__ * a_dim1]); z__1.r = temp.r * z__2.r - temp.i * z__2.i, z__1.i = temp.r * z__2.i + temp.i * z__2.r; temp.r = z__1.r, temp.i = z__1.i; } i__3 = *m; for (k = i__ + 1; k <= i__3; ++k) { d_cnjg(&z__3, &a[k + i__ * a_dim1]); i__4 = k + j * b_dim1; z__2.r = z__3.r * b[i__4].r - z__3.i * b[i__4] .i, z__2.i = z__3.r * b[i__4].i + z__3.i * b[i__4].r; z__1.r = temp.r + z__2.r, z__1.i = temp.i + z__2.i; temp.r = z__1.r, temp.i = z__1.i; /* L140: */ } } i__3 = i__ + j * b_dim1; z__1.r = alpha->r * temp.r - alpha->i * temp.i, z__1.i = alpha->r * temp.i + alpha->i * temp.r; b[i__3].r = z__1.r, b[i__3].i = z__1.i; /* L150: */ } /* L160: */ } } } } else { if (lsame_(transa, "N")) { /* Form B := alpha*B*A. */ if (upper) { for (j = *n; j >= 1; --j) { temp.r = alpha->r, temp.i = alpha->i; if (nounit) { i__1 = j + j * a_dim1; z__1.r = temp.r * a[i__1].r - temp.i * a[i__1].i, z__1.i = temp.r * a[i__1].i + temp.i * a[i__1] .r; temp.r = z__1.r, temp.i = z__1.i; } i__1 = *m; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = i__ + j * b_dim1; i__3 = i__ + j * b_dim1; z__1.r = temp.r * b[i__3].r - temp.i * b[i__3].i, z__1.i = temp.r * b[i__3].i + temp.i * b[i__3] .r; b[i__2].r = z__1.r, b[i__2].i = z__1.i; /* L170: */ } i__1 = j - 1; for (k = 1; k <= i__1; ++k) { i__2 = k + j * a_dim1; if ((a[i__2].r != 0.) || (a[i__2].i != 0.)) { i__2 = k + j * a_dim1; z__1.r = alpha->r * a[i__2].r - alpha->i * a[i__2] .i, z__1.i = alpha->r * a[i__2].i + alpha->i * a[i__2].r; temp.r = z__1.r, temp.i = z__1.i; i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * b_dim1; i__4 = i__ + j * b_dim1; i__5 = i__ + k * b_dim1; z__2.r = temp.r * b[i__5].r - temp.i * b[i__5] .i, z__2.i = temp.r * b[i__5].i + temp.i * b[i__5].r; z__1.r = b[i__4].r + z__2.r, z__1.i = b[i__4] .i + z__2.i; b[i__3].r = z__1.r, b[i__3].i = z__1.i; /* L180: */ } } /* L190: */ } /* L200: */ } } else { i__1 = *n; for (j = 1; j <= i__1; ++j) { temp.r = alpha->r, temp.i = alpha->i; if (nounit) { i__2 = j + j * a_dim1; z__1.r = temp.r * a[i__2].r - temp.i * a[i__2].i, z__1.i = temp.r * a[i__2].i + temp.i * a[i__2] .r; temp.r = z__1.r, temp.i = z__1.i; } i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * b_dim1; i__4 = i__ + j * b_dim1; z__1.r = temp.r * b[i__4].r - temp.i * b[i__4].i, z__1.i = temp.r * b[i__4].i + temp.i * b[i__4] .r; b[i__3].r = z__1.r, b[i__3].i = z__1.i; /* L210: */ } i__2 = *n; for (k = j + 1; k <= i__2; ++k) { i__3 = k + j * a_dim1; if ((a[i__3].r != 0.) || (a[i__3].i != 0.)) { i__3 = k + j * a_dim1; z__1.r = alpha->r * a[i__3].r - alpha->i * a[i__3] .i, z__1.i = alpha->r * a[i__3].i + alpha->i * a[i__3].r; temp.r = z__1.r, temp.i = z__1.i; i__3 = *m; for (i__ = 1; i__ <= i__3; ++i__) { i__4 = i__ + j * b_dim1; i__5 = i__ + j * b_dim1; i__6 = i__ + k * b_dim1; z__2.r = temp.r * b[i__6].r - temp.i * b[i__6] .i, z__2.i = temp.r * b[i__6].i + temp.i * b[i__6].r; z__1.r = b[i__5].r + z__2.r, z__1.i = b[i__5] .i + z__2.i; b[i__4].r = z__1.r, b[i__4].i = z__1.i; /* L220: */ } } /* L230: */ } /* L240: */ } } } else { /* Form B := alpha*B*A' or B := alpha*B*conjg( A' ). */ if (upper) { i__1 = *n; for (k = 1; k <= i__1; ++k) { i__2 = k - 1; for (j = 1; j <= i__2; ++j) { i__3 = j + k * a_dim1; if ((a[i__3].r != 0.) || (a[i__3].i != 0.)) { if (noconj) { i__3 = j + k * a_dim1; z__1.r = alpha->r * a[i__3].r - alpha->i * a[ i__3].i, z__1.i = alpha->r * a[i__3] .i + alpha->i * a[i__3].r; temp.r = z__1.r, temp.i = z__1.i; } else { d_cnjg(&z__2, &a[j + k * a_dim1]); z__1.r = alpha->r * z__2.r - alpha->i * z__2.i, z__1.i = alpha->r * z__2.i + alpha->i * z__2.r; temp.r = z__1.r, temp.i = z__1.i; } i__3 = *m; for (i__ = 1; i__ <= i__3; ++i__) { i__4 = i__ + j * b_dim1; i__5 = i__ + j * b_dim1; i__6 = i__ + k * b_dim1; z__2.r = temp.r * b[i__6].r - temp.i * b[i__6] .i, z__2.i = temp.r * b[i__6].i + temp.i * b[i__6].r; z__1.r = b[i__5].r + z__2.r, z__1.i = b[i__5] .i + z__2.i; b[i__4].r = z__1.r, b[i__4].i = z__1.i; /* L250: */ } } /* L260: */ } temp.r = alpha->r, temp.i = alpha->i; if (nounit) { if (noconj) { i__2 = k + k * a_dim1; z__1.r = temp.r * a[i__2].r - temp.i * a[i__2].i, z__1.i = temp.r * a[i__2].i + temp.i * a[ i__2].r; temp.r = z__1.r, temp.i = z__1.i; } else { d_cnjg(&z__2, &a[k + k * a_dim1]); z__1.r = temp.r * z__2.r - temp.i * z__2.i, z__1.i = temp.r * z__2.i + temp.i * z__2.r; temp.r = z__1.r, temp.i = z__1.i; } } if ((temp.r != 1.) || (temp.i != 0.)) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + k * b_dim1; i__4 = i__ + k * b_dim1; z__1.r = temp.r * b[i__4].r - temp.i * b[i__4].i, z__1.i = temp.r * b[i__4].i + temp.i * b[ i__4].r; b[i__3].r = z__1.r, b[i__3].i = z__1.i; /* L270: */ } } /* L280: */ } } else { for (k = *n; k >= 1; --k) { i__1 = *n; for (j = k + 1; j <= i__1; ++j) { i__2 = j + k * a_dim1; if ((a[i__2].r != 0.) || (a[i__2].i != 0.)) { if (noconj) { i__2 = j + k * a_dim1; z__1.r = alpha->r * a[i__2].r - alpha->i * a[ i__2].i, z__1.i = alpha->r * a[i__2] .i + alpha->i * a[i__2].r; temp.r = z__1.r, temp.i = z__1.i; } else { d_cnjg(&z__2, &a[j + k * a_dim1]); z__1.r = alpha->r * z__2.r - alpha->i * z__2.i, z__1.i = alpha->r * z__2.i + alpha->i * z__2.r; temp.r = z__1.r, temp.i = z__1.i; } i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * b_dim1; i__4 = i__ + j * b_dim1; i__5 = i__ + k * b_dim1; z__2.r = temp.r * b[i__5].r - temp.i * b[i__5] .i, z__2.i = temp.r * b[i__5].i + temp.i * b[i__5].r; z__1.r = b[i__4].r + z__2.r, z__1.i = b[i__4] .i + z__2.i; b[i__3].r = z__1.r, b[i__3].i = z__1.i; /* L290: */ } } /* L300: */ } temp.r = alpha->r, temp.i = alpha->i; if (nounit) { if (noconj) { i__1 = k + k * a_dim1; z__1.r = temp.r * a[i__1].r - temp.i * a[i__1].i, z__1.i = temp.r * a[i__1].i + temp.i * a[ i__1].r; temp.r = z__1.r, temp.i = z__1.i; } else { d_cnjg(&z__2, &a[k + k * a_dim1]); z__1.r = temp.r * z__2.r - temp.i * z__2.i, z__1.i = temp.r * z__2.i + temp.i * z__2.r; temp.r = z__1.r, temp.i = z__1.i; } } if ((temp.r != 1.) || (temp.i != 0.)) { i__1 = *m; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = i__ + k * b_dim1; i__3 = i__ + k * b_dim1; z__1.r = temp.r * b[i__3].r - temp.i * b[i__3].i, z__1.i = temp.r * b[i__3].i + temp.i * b[ i__3].r; b[i__2].r = z__1.r, b[i__2].i = z__1.i; /* L310: */ } } /* L320: */ } } } } return 0; /* End of ZTRMM . */ } /* ztrmm_ */ /* Subroutine */ int ztrmv_(char *uplo, char *trans, char *diag, integer *n, doublecomplex *a, integer *lda, doublecomplex *x, integer *incx) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3, i__4, i__5; doublecomplex z__1, z__2, z__3; /* Builtin functions */ void d_cnjg(doublecomplex *, doublecomplex *); /* Local variables */ static integer i__, j, ix, jx, kx, info; static doublecomplex temp; extern logical lsame_(char *, char *); extern /* Subroutine */ int xerbla_(char *, integer *); static logical noconj, nounit; /* Purpose ======= ZTRMV performs one of the matrix-vector operations x := A*x, or x := A'*x, or x := conjg( A' )*x, where x is an n element vector and A is an n by n unit, or non-unit, upper or lower triangular matrix. Parameters ========== UPLO - CHARACTER*1. On entry, UPLO specifies whether the matrix is an upper or lower triangular matrix as follows: UPLO = 'U' or 'u' A is an upper triangular matrix. UPLO = 'L' or 'l' A is a lower triangular matrix. Unchanged on exit. TRANS - CHARACTER*1. On entry, TRANS specifies the operation to be performed as follows: TRANS = 'N' or 'n' x := A*x. TRANS = 'T' or 't' x := A'*x. TRANS = 'C' or 'c' x := conjg( A' )*x. Unchanged on exit. DIAG - CHARACTER*1. On entry, DIAG specifies whether or not A is unit triangular as follows: DIAG = 'U' or 'u' A is assumed to be unit triangular. DIAG = 'N' or 'n' A is not assumed to be unit triangular. Unchanged on exit. N - INTEGER. On entry, N specifies the order of the matrix A. N must be at least zero. Unchanged on exit. A - COMPLEX*16 array of DIMENSION ( LDA, n ). Before entry with UPLO = 'U' or 'u', the leading n by n upper triangular part of the array A must contain the upper triangular matrix and the strictly lower triangular part of A is not referenced. Before entry with UPLO = 'L' or 'l', the leading n by n lower triangular part of the array A must contain the lower triangular matrix and the strictly upper triangular part of A is not referenced. Note that when DIAG = 'U' or 'u', the diagonal elements of A are not referenced either, but are assumed to be unity. Unchanged on exit. LDA - INTEGER. On entry, LDA specifies the first dimension of A as declared in the calling (sub) program. LDA must be at least max( 1, n ). Unchanged on exit. X - COMPLEX*16 array of dimension at least ( 1 + ( n - 1 )*abs( INCX ) ). Before entry, the incremented array X must contain the n element vector x. On exit, X is overwritten with the tranformed vector x. INCX - INTEGER. On entry, INCX specifies the increment for the elements of X. INCX must not be zero. Unchanged on exit. Level 2 Blas routine. -- Written on 22-October-1986. Jack Dongarra, Argonne National Lab. Jeremy Du Croz, Nag Central Office. Sven Hammarling, Nag Central Office. Richard Hanson, Sandia National Labs. Test the input parameters. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --x; /* Function Body */ info = 0; if (! lsame_(uplo, "U") && ! lsame_(uplo, "L")) { info = 1; } else if (! lsame_(trans, "N") && ! lsame_(trans, "T") && ! lsame_(trans, "C")) { info = 2; } else if (! lsame_(diag, "U") && ! lsame_(diag, "N")) { info = 3; } else if (*n < 0) { info = 4; } else if (*lda < max(1,*n)) { info = 6; } else if (*incx == 0) { info = 8; } if (info != 0) { xerbla_("ZTRMV ", &info); return 0; } /* Quick return if possible. */ if (*n == 0) { return 0; } noconj = lsame_(trans, "T"); nounit = lsame_(diag, "N"); /* Set up the start point in X if the increment is not unity. This will be ( N - 1 )*INCX too small for descending loops. */ if (*incx <= 0) { kx = 1 - (*n - 1) * *incx; } else if (*incx != 1) { kx = 1; } /* Start the operations. In this version the elements of A are accessed sequentially with one pass through A. */ if (lsame_(trans, "N")) { /* Form x := A*x. */ if (lsame_(uplo, "U")) { if (*incx == 1) { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = j; if ((x[i__2].r != 0.) || (x[i__2].i != 0.)) { i__2 = j; temp.r = x[i__2].r, temp.i = x[i__2].i; i__2 = j - 1; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__; i__4 = i__; i__5 = i__ + j * a_dim1; z__2.r = temp.r * a[i__5].r - temp.i * a[i__5].i, z__2.i = temp.r * a[i__5].i + temp.i * a[ i__5].r; z__1.r = x[i__4].r + z__2.r, z__1.i = x[i__4].i + z__2.i; x[i__3].r = z__1.r, x[i__3].i = z__1.i; /* L10: */ } if (nounit) { i__2 = j; i__3 = j; i__4 = j + j * a_dim1; z__1.r = x[i__3].r * a[i__4].r - x[i__3].i * a[ i__4].i, z__1.i = x[i__3].r * a[i__4].i + x[i__3].i * a[i__4].r; x[i__2].r = z__1.r, x[i__2].i = z__1.i; } } /* L20: */ } } else { jx = kx; i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = jx; if ((x[i__2].r != 0.) || (x[i__2].i != 0.)) { i__2 = jx; temp.r = x[i__2].r, temp.i = x[i__2].i; ix = kx; i__2 = j - 1; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = ix; i__4 = ix; i__5 = i__ + j * a_dim1; z__2.r = temp.r * a[i__5].r - temp.i * a[i__5].i, z__2.i = temp.r * a[i__5].i + temp.i * a[ i__5].r; z__1.r = x[i__4].r + z__2.r, z__1.i = x[i__4].i + z__2.i; x[i__3].r = z__1.r, x[i__3].i = z__1.i; ix += *incx; /* L30: */ } if (nounit) { i__2 = jx; i__3 = jx; i__4 = j + j * a_dim1; z__1.r = x[i__3].r * a[i__4].r - x[i__3].i * a[ i__4].i, z__1.i = x[i__3].r * a[i__4].i + x[i__3].i * a[i__4].r; x[i__2].r = z__1.r, x[i__2].i = z__1.i; } } jx += *incx; /* L40: */ } } } else { if (*incx == 1) { for (j = *n; j >= 1; --j) { i__1 = j; if ((x[i__1].r != 0.) || (x[i__1].i != 0.)) { i__1 = j; temp.r = x[i__1].r, temp.i = x[i__1].i; i__1 = j + 1; for (i__ = *n; i__ >= i__1; --i__) { i__2 = i__; i__3 = i__; i__4 = i__ + j * a_dim1; z__2.r = temp.r * a[i__4].r - temp.i * a[i__4].i, z__2.i = temp.r * a[i__4].i + temp.i * a[ i__4].r; z__1.r = x[i__3].r + z__2.r, z__1.i = x[i__3].i + z__2.i; x[i__2].r = z__1.r, x[i__2].i = z__1.i; /* L50: */ } if (nounit) { i__1 = j; i__2 = j; i__3 = j + j * a_dim1; z__1.r = x[i__2].r * a[i__3].r - x[i__2].i * a[ i__3].i, z__1.i = x[i__2].r * a[i__3].i + x[i__2].i * a[i__3].r; x[i__1].r = z__1.r, x[i__1].i = z__1.i; } } /* L60: */ } } else { kx += (*n - 1) * *incx; jx = kx; for (j = *n; j >= 1; --j) { i__1 = jx; if ((x[i__1].r != 0.) || (x[i__1].i != 0.)) { i__1 = jx; temp.r = x[i__1].r, temp.i = x[i__1].i; ix = kx; i__1 = j + 1; for (i__ = *n; i__ >= i__1; --i__) { i__2 = ix; i__3 = ix; i__4 = i__ + j * a_dim1; z__2.r = temp.r * a[i__4].r - temp.i * a[i__4].i, z__2.i = temp.r * a[i__4].i + temp.i * a[ i__4].r; z__1.r = x[i__3].r + z__2.r, z__1.i = x[i__3].i + z__2.i; x[i__2].r = z__1.r, x[i__2].i = z__1.i; ix -= *incx; /* L70: */ } if (nounit) { i__1 = jx; i__2 = jx; i__3 = j + j * a_dim1; z__1.r = x[i__2].r * a[i__3].r - x[i__2].i * a[ i__3].i, z__1.i = x[i__2].r * a[i__3].i + x[i__2].i * a[i__3].r; x[i__1].r = z__1.r, x[i__1].i = z__1.i; } } jx -= *incx; /* L80: */ } } } } else { /* Form x := A'*x or x := conjg( A' )*x. */ if (lsame_(uplo, "U")) { if (*incx == 1) { for (j = *n; j >= 1; --j) { i__1 = j; temp.r = x[i__1].r, temp.i = x[i__1].i; if (noconj) { if (nounit) { i__1 = j + j * a_dim1; z__1.r = temp.r * a[i__1].r - temp.i * a[i__1].i, z__1.i = temp.r * a[i__1].i + temp.i * a[ i__1].r; temp.r = z__1.r, temp.i = z__1.i; } for (i__ = j - 1; i__ >= 1; --i__) { i__1 = i__ + j * a_dim1; i__2 = i__; z__2.r = a[i__1].r * x[i__2].r - a[i__1].i * x[ i__2].i, z__2.i = a[i__1].r * x[i__2].i + a[i__1].i * x[i__2].r; z__1.r = temp.r + z__2.r, z__1.i = temp.i + z__2.i; temp.r = z__1.r, temp.i = z__1.i; /* L90: */ } } else { if (nounit) { d_cnjg(&z__2, &a[j + j * a_dim1]); z__1.r = temp.r * z__2.r - temp.i * z__2.i, z__1.i = temp.r * z__2.i + temp.i * z__2.r; temp.r = z__1.r, temp.i = z__1.i; } for (i__ = j - 1; i__ >= 1; --i__) { d_cnjg(&z__3, &a[i__ + j * a_dim1]); i__1 = i__; z__2.r = z__3.r * x[i__1].r - z__3.i * x[i__1].i, z__2.i = z__3.r * x[i__1].i + z__3.i * x[ i__1].r; z__1.r = temp.r + z__2.r, z__1.i = temp.i + z__2.i; temp.r = z__1.r, temp.i = z__1.i; /* L100: */ } } i__1 = j; x[i__1].r = temp.r, x[i__1].i = temp.i; /* L110: */ } } else { jx = kx + (*n - 1) * *incx; for (j = *n; j >= 1; --j) { i__1 = jx; temp.r = x[i__1].r, temp.i = x[i__1].i; ix = jx; if (noconj) { if (nounit) { i__1 = j + j * a_dim1; z__1.r = temp.r * a[i__1].r - temp.i * a[i__1].i, z__1.i = temp.r * a[i__1].i + temp.i * a[ i__1].r; temp.r = z__1.r, temp.i = z__1.i; } for (i__ = j - 1; i__ >= 1; --i__) { ix -= *incx; i__1 = i__ + j * a_dim1; i__2 = ix; z__2.r = a[i__1].r * x[i__2].r - a[i__1].i * x[ i__2].i, z__2.i = a[i__1].r * x[i__2].i + a[i__1].i * x[i__2].r; z__1.r = temp.r + z__2.r, z__1.i = temp.i + z__2.i; temp.r = z__1.r, temp.i = z__1.i; /* L120: */ } } else { if (nounit) { d_cnjg(&z__2, &a[j + j * a_dim1]); z__1.r = temp.r * z__2.r - temp.i * z__2.i, z__1.i = temp.r * z__2.i + temp.i * z__2.r; temp.r = z__1.r, temp.i = z__1.i; } for (i__ = j - 1; i__ >= 1; --i__) { ix -= *incx; d_cnjg(&z__3, &a[i__ + j * a_dim1]); i__1 = ix; z__2.r = z__3.r * x[i__1].r - z__3.i * x[i__1].i, z__2.i = z__3.r * x[i__1].i + z__3.i * x[ i__1].r; z__1.r = temp.r + z__2.r, z__1.i = temp.i + z__2.i; temp.r = z__1.r, temp.i = z__1.i; /* L130: */ } } i__1 = jx; x[i__1].r = temp.r, x[i__1].i = temp.i; jx -= *incx; /* L140: */ } } } else { if (*incx == 1) { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = j; temp.r = x[i__2].r, temp.i = x[i__2].i; if (noconj) { if (nounit) { i__2 = j + j * a_dim1; z__1.r = temp.r * a[i__2].r - temp.i * a[i__2].i, z__1.i = temp.r * a[i__2].i + temp.i * a[ i__2].r; temp.r = z__1.r, temp.i = z__1.i; } i__2 = *n; for (i__ = j + 1; i__ <= i__2; ++i__) { i__3 = i__ + j * a_dim1; i__4 = i__; z__2.r = a[i__3].r * x[i__4].r - a[i__3].i * x[ i__4].i, z__2.i = a[i__3].r * x[i__4].i + a[i__3].i * x[i__4].r; z__1.r = temp.r + z__2.r, z__1.i = temp.i + z__2.i; temp.r = z__1.r, temp.i = z__1.i; /* L150: */ } } else { if (nounit) { d_cnjg(&z__2, &a[j + j * a_dim1]); z__1.r = temp.r * z__2.r - temp.i * z__2.i, z__1.i = temp.r * z__2.i + temp.i * z__2.r; temp.r = z__1.r, temp.i = z__1.i; } i__2 = *n; for (i__ = j + 1; i__ <= i__2; ++i__) { d_cnjg(&z__3, &a[i__ + j * a_dim1]); i__3 = i__; z__2.r = z__3.r * x[i__3].r - z__3.i * x[i__3].i, z__2.i = z__3.r * x[i__3].i + z__3.i * x[ i__3].r; z__1.r = temp.r + z__2.r, z__1.i = temp.i + z__2.i; temp.r = z__1.r, temp.i = z__1.i; /* L160: */ } } i__2 = j; x[i__2].r = temp.r, x[i__2].i = temp.i; /* L170: */ } } else { jx = kx; i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = jx; temp.r = x[i__2].r, temp.i = x[i__2].i; ix = jx; if (noconj) { if (nounit) { i__2 = j + j * a_dim1; z__1.r = temp.r * a[i__2].r - temp.i * a[i__2].i, z__1.i = temp.r * a[i__2].i + temp.i * a[ i__2].r; temp.r = z__1.r, temp.i = z__1.i; } i__2 = *n; for (i__ = j + 1; i__ <= i__2; ++i__) { ix += *incx; i__3 = i__ + j * a_dim1; i__4 = ix; z__2.r = a[i__3].r * x[i__4].r - a[i__3].i * x[ i__4].i, z__2.i = a[i__3].r * x[i__4].i + a[i__3].i * x[i__4].r; z__1.r = temp.r + z__2.r, z__1.i = temp.i + z__2.i; temp.r = z__1.r, temp.i = z__1.i; /* L180: */ } } else { if (nounit) { d_cnjg(&z__2, &a[j + j * a_dim1]); z__1.r = temp.r * z__2.r - temp.i * z__2.i, z__1.i = temp.r * z__2.i + temp.i * z__2.r; temp.r = z__1.r, temp.i = z__1.i; } i__2 = *n; for (i__ = j + 1; i__ <= i__2; ++i__) { ix += *incx; d_cnjg(&z__3, &a[i__ + j * a_dim1]); i__3 = ix; z__2.r = z__3.r * x[i__3].r - z__3.i * x[i__3].i, z__2.i = z__3.r * x[i__3].i + z__3.i * x[ i__3].r; z__1.r = temp.r + z__2.r, z__1.i = temp.i + z__2.i; temp.r = z__1.r, temp.i = z__1.i; /* L190: */ } } i__2 = jx; x[i__2].r = temp.r, x[i__2].i = temp.i; jx += *incx; /* L200: */ } } } } return 0; /* End of ZTRMV . */ } /* ztrmv_ */ /* Subroutine */ int ztrsm_(char *side, char *uplo, char *transa, char *diag, integer *m, integer *n, doublecomplex *alpha, doublecomplex *a, integer *lda, doublecomplex *b, integer *ldb) { /* System generated locals */ integer a_dim1, a_offset, b_dim1, b_offset, i__1, i__2, i__3, i__4, i__5, i__6, i__7; doublecomplex z__1, z__2, z__3; /* Builtin functions */ void z_div(doublecomplex *, doublecomplex *, doublecomplex *), d_cnjg( doublecomplex *, doublecomplex *); /* Local variables */ static integer i__, j, k, info; static doublecomplex temp; static logical lside; extern logical lsame_(char *, char *); static integer nrowa; static logical upper; extern /* Subroutine */ int xerbla_(char *, integer *); static logical noconj, nounit; /* Purpose ======= ZTRSM solves one of the matrix equations op( A )*X = alpha*B, or X*op( A ) = alpha*B, where alpha is a scalar, X and B are m by n matrices, A is a unit, or non-unit, upper or lower triangular matrix and op( A ) is one of op( A ) = A or op( A ) = A' or op( A ) = conjg( A' ). The matrix X is overwritten on B. Parameters ========== SIDE - CHARACTER*1. On entry, SIDE specifies whether op( A ) appears on the left or right of X as follows: SIDE = 'L' or 'l' op( A )*X = alpha*B. SIDE = 'R' or 'r' X*op( A ) = alpha*B. Unchanged on exit. UPLO - CHARACTER*1. On entry, UPLO specifies whether the matrix A is an upper or lower triangular matrix as follows: UPLO = 'U' or 'u' A is an upper triangular matrix. UPLO = 'L' or 'l' A is a lower triangular matrix. Unchanged on exit. TRANSA - CHARACTER*1. On entry, TRANSA specifies the form of op( A ) to be used in the matrix multiplication as follows: TRANSA = 'N' or 'n' op( A ) = A. TRANSA = 'T' or 't' op( A ) = A'. TRANSA = 'C' or 'c' op( A ) = conjg( A' ). Unchanged on exit. DIAG - CHARACTER*1. On entry, DIAG specifies whether or not A is unit triangular as follows: DIAG = 'U' or 'u' A is assumed to be unit triangular. DIAG = 'N' or 'n' A is not assumed to be unit triangular. Unchanged on exit. M - INTEGER. On entry, M specifies the number of rows of B. M must be at least zero. Unchanged on exit. N - INTEGER. On entry, N specifies the number of columns of B. N must be at least zero. Unchanged on exit. ALPHA - COMPLEX*16 . On entry, ALPHA specifies the scalar alpha. When alpha is zero then A is not referenced and B need not be set before entry. Unchanged on exit. A - COMPLEX*16 array of DIMENSION ( LDA, k ), where k is m when SIDE = 'L' or 'l' and is n when SIDE = 'R' or 'r'. Before entry with UPLO = 'U' or 'u', the leading k by k upper triangular part of the array A must contain the upper triangular matrix and the strictly lower triangular part of A is not referenced. Before entry with UPLO = 'L' or 'l', the leading k by k lower triangular part of the array A must contain the lower triangular matrix and the strictly upper triangular part of A is not referenced. Note that when DIAG = 'U' or 'u', the diagonal elements of A are not referenced either, but are assumed to be unity. Unchanged on exit. LDA - INTEGER. On entry, LDA specifies the first dimension of A as declared in the calling (sub) program. When SIDE = 'L' or 'l' then LDA must be at least max( 1, m ), when SIDE = 'R' or 'r' then LDA must be at least max( 1, n ). Unchanged on exit. B - COMPLEX*16 array of DIMENSION ( LDB, n ). Before entry, the leading m by n part of the array B must contain the right-hand side matrix B, and on exit is overwritten by the solution matrix X. LDB - INTEGER. On entry, LDB specifies the first dimension of B as declared in the calling (sub) program. LDB must be at least max( 1, m ). Unchanged on exit. Level 3 Blas routine. -- Written on 8-February-1989. Jack Dongarra, Argonne National Laboratory. Iain Duff, AERE Harwell. Jeremy Du Croz, Numerical Algorithms Group Ltd. Sven Hammarling, Numerical Algorithms Group Ltd. Test the input parameters. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; b_dim1 = *ldb; b_offset = 1 + b_dim1; b -= b_offset; /* Function Body */ lside = lsame_(side, "L"); if (lside) { nrowa = *m; } else { nrowa = *n; } noconj = lsame_(transa, "T"); nounit = lsame_(diag, "N"); upper = lsame_(uplo, "U"); info = 0; if (! lside && ! lsame_(side, "R")) { info = 1; } else if (! upper && ! lsame_(uplo, "L")) { info = 2; } else if (! lsame_(transa, "N") && ! lsame_(transa, "T") && ! lsame_(transa, "C")) { info = 3; } else if (! lsame_(diag, "U") && ! lsame_(diag, "N")) { info = 4; } else if (*m < 0) { info = 5; } else if (*n < 0) { info = 6; } else if (*lda < max(1,nrowa)) { info = 9; } else if (*ldb < max(1,*m)) { info = 11; } if (info != 0) { xerbla_("ZTRSM ", &info); return 0; } /* Quick return if possible. */ if (*n == 0) { return 0; } /* And when alpha.eq.zero. */ if (alpha->r == 0. && alpha->i == 0.) { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * b_dim1; b[i__3].r = 0., b[i__3].i = 0.; /* L10: */ } /* L20: */ } return 0; } /* Start the operations. */ if (lside) { if (lsame_(transa, "N")) { /* Form B := alpha*inv( A )*B. */ if (upper) { i__1 = *n; for (j = 1; j <= i__1; ++j) { if ((alpha->r != 1.) || (alpha->i != 0.)) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * b_dim1; i__4 = i__ + j * b_dim1; z__1.r = alpha->r * b[i__4].r - alpha->i * b[i__4] .i, z__1.i = alpha->r * b[i__4].i + alpha->i * b[i__4].r; b[i__3].r = z__1.r, b[i__3].i = z__1.i; /* L30: */ } } for (k = *m; k >= 1; --k) { i__2 = k + j * b_dim1; if ((b[i__2].r != 0.) || (b[i__2].i != 0.)) { if (nounit) { i__2 = k + j * b_dim1; z_div(&z__1, &b[k + j * b_dim1], &a[k + k * a_dim1]); b[i__2].r = z__1.r, b[i__2].i = z__1.i; } i__2 = k - 1; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * b_dim1; i__4 = i__ + j * b_dim1; i__5 = k + j * b_dim1; i__6 = i__ + k * a_dim1; z__2.r = b[i__5].r * a[i__6].r - b[i__5].i * a[i__6].i, z__2.i = b[i__5].r * a[ i__6].i + b[i__5].i * a[i__6].r; z__1.r = b[i__4].r - z__2.r, z__1.i = b[i__4] .i - z__2.i; b[i__3].r = z__1.r, b[i__3].i = z__1.i; /* L40: */ } } /* L50: */ } /* L60: */ } } else { i__1 = *n; for (j = 1; j <= i__1; ++j) { if ((alpha->r != 1.) || (alpha->i != 0.)) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * b_dim1; i__4 = i__ + j * b_dim1; z__1.r = alpha->r * b[i__4].r - alpha->i * b[i__4] .i, z__1.i = alpha->r * b[i__4].i + alpha->i * b[i__4].r; b[i__3].r = z__1.r, b[i__3].i = z__1.i; /* L70: */ } } i__2 = *m; for (k = 1; k <= i__2; ++k) { i__3 = k + j * b_dim1; if ((b[i__3].r != 0.) || (b[i__3].i != 0.)) { if (nounit) { i__3 = k + j * b_dim1; z_div(&z__1, &b[k + j * b_dim1], &a[k + k * a_dim1]); b[i__3].r = z__1.r, b[i__3].i = z__1.i; } i__3 = *m; for (i__ = k + 1; i__ <= i__3; ++i__) { i__4 = i__ + j * b_dim1; i__5 = i__ + j * b_dim1; i__6 = k + j * b_dim1; i__7 = i__ + k * a_dim1; z__2.r = b[i__6].r * a[i__7].r - b[i__6].i * a[i__7].i, z__2.i = b[i__6].r * a[ i__7].i + b[i__6].i * a[i__7].r; z__1.r = b[i__5].r - z__2.r, z__1.i = b[i__5] .i - z__2.i; b[i__4].r = z__1.r, b[i__4].i = z__1.i; /* L80: */ } } /* L90: */ } /* L100: */ } } } else { /* Form B := alpha*inv( A' )*B or B := alpha*inv( conjg( A' ) )*B. */ if (upper) { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * b_dim1; z__1.r = alpha->r * b[i__3].r - alpha->i * b[i__3].i, z__1.i = alpha->r * b[i__3].i + alpha->i * b[ i__3].r; temp.r = z__1.r, temp.i = z__1.i; if (noconj) { i__3 = i__ - 1; for (k = 1; k <= i__3; ++k) { i__4 = k + i__ * a_dim1; i__5 = k + j * b_dim1; z__2.r = a[i__4].r * b[i__5].r - a[i__4].i * b[i__5].i, z__2.i = a[i__4].r * b[ i__5].i + a[i__4].i * b[i__5].r; z__1.r = temp.r - z__2.r, z__1.i = temp.i - z__2.i; temp.r = z__1.r, temp.i = z__1.i; /* L110: */ } if (nounit) { z_div(&z__1, &temp, &a[i__ + i__ * a_dim1]); temp.r = z__1.r, temp.i = z__1.i; } } else { i__3 = i__ - 1; for (k = 1; k <= i__3; ++k) { d_cnjg(&z__3, &a[k + i__ * a_dim1]); i__4 = k + j * b_dim1; z__2.r = z__3.r * b[i__4].r - z__3.i * b[i__4] .i, z__2.i = z__3.r * b[i__4].i + z__3.i * b[i__4].r; z__1.r = temp.r - z__2.r, z__1.i = temp.i - z__2.i; temp.r = z__1.r, temp.i = z__1.i; /* L120: */ } if (nounit) { d_cnjg(&z__2, &a[i__ + i__ * a_dim1]); z_div(&z__1, &temp, &z__2); temp.r = z__1.r, temp.i = z__1.i; } } i__3 = i__ + j * b_dim1; b[i__3].r = temp.r, b[i__3].i = temp.i; /* L130: */ } /* L140: */ } } else { i__1 = *n; for (j = 1; j <= i__1; ++j) { for (i__ = *m; i__ >= 1; --i__) { i__2 = i__ + j * b_dim1; z__1.r = alpha->r * b[i__2].r - alpha->i * b[i__2].i, z__1.i = alpha->r * b[i__2].i + alpha->i * b[ i__2].r; temp.r = z__1.r, temp.i = z__1.i; if (noconj) { i__2 = *m; for (k = i__ + 1; k <= i__2; ++k) { i__3 = k + i__ * a_dim1; i__4 = k + j * b_dim1; z__2.r = a[i__3].r * b[i__4].r - a[i__3].i * b[i__4].i, z__2.i = a[i__3].r * b[ i__4].i + a[i__3].i * b[i__4].r; z__1.r = temp.r - z__2.r, z__1.i = temp.i - z__2.i; temp.r = z__1.r, temp.i = z__1.i; /* L150: */ } if (nounit) { z_div(&z__1, &temp, &a[i__ + i__ * a_dim1]); temp.r = z__1.r, temp.i = z__1.i; } } else { i__2 = *m; for (k = i__ + 1; k <= i__2; ++k) { d_cnjg(&z__3, &a[k + i__ * a_dim1]); i__3 = k + j * b_dim1; z__2.r = z__3.r * b[i__3].r - z__3.i * b[i__3] .i, z__2.i = z__3.r * b[i__3].i + z__3.i * b[i__3].r; z__1.r = temp.r - z__2.r, z__1.i = temp.i - z__2.i; temp.r = z__1.r, temp.i = z__1.i; /* L160: */ } if (nounit) { d_cnjg(&z__2, &a[i__ + i__ * a_dim1]); z_div(&z__1, &temp, &z__2); temp.r = z__1.r, temp.i = z__1.i; } } i__2 = i__ + j * b_dim1; b[i__2].r = temp.r, b[i__2].i = temp.i; /* L170: */ } /* L180: */ } } } } else { if (lsame_(transa, "N")) { /* Form B := alpha*B*inv( A ). */ if (upper) { i__1 = *n; for (j = 1; j <= i__1; ++j) { if ((alpha->r != 1.) || (alpha->i != 0.)) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * b_dim1; i__4 = i__ + j * b_dim1; z__1.r = alpha->r * b[i__4].r - alpha->i * b[i__4] .i, z__1.i = alpha->r * b[i__4].i + alpha->i * b[i__4].r; b[i__3].r = z__1.r, b[i__3].i = z__1.i; /* L190: */ } } i__2 = j - 1; for (k = 1; k <= i__2; ++k) { i__3 = k + j * a_dim1; if ((a[i__3].r != 0.) || (a[i__3].i != 0.)) { i__3 = *m; for (i__ = 1; i__ <= i__3; ++i__) { i__4 = i__ + j * b_dim1; i__5 = i__ + j * b_dim1; i__6 = k + j * a_dim1; i__7 = i__ + k * b_dim1; z__2.r = a[i__6].r * b[i__7].r - a[i__6].i * b[i__7].i, z__2.i = a[i__6].r * b[ i__7].i + a[i__6].i * b[i__7].r; z__1.r = b[i__5].r - z__2.r, z__1.i = b[i__5] .i - z__2.i; b[i__4].r = z__1.r, b[i__4].i = z__1.i; /* L200: */ } } /* L210: */ } if (nounit) { z_div(&z__1, &c_b1077, &a[j + j * a_dim1]); temp.r = z__1.r, temp.i = z__1.i; i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * b_dim1; i__4 = i__ + j * b_dim1; z__1.r = temp.r * b[i__4].r - temp.i * b[i__4].i, z__1.i = temp.r * b[i__4].i + temp.i * b[ i__4].r; b[i__3].r = z__1.r, b[i__3].i = z__1.i; /* L220: */ } } /* L230: */ } } else { for (j = *n; j >= 1; --j) { if ((alpha->r != 1.) || (alpha->i != 0.)) { i__1 = *m; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = i__ + j * b_dim1; i__3 = i__ + j * b_dim1; z__1.r = alpha->r * b[i__3].r - alpha->i * b[i__3] .i, z__1.i = alpha->r * b[i__3].i + alpha->i * b[i__3].r; b[i__2].r = z__1.r, b[i__2].i = z__1.i; /* L240: */ } } i__1 = *n; for (k = j + 1; k <= i__1; ++k) { i__2 = k + j * a_dim1; if ((a[i__2].r != 0.) || (a[i__2].i != 0.)) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * b_dim1; i__4 = i__ + j * b_dim1; i__5 = k + j * a_dim1; i__6 = i__ + k * b_dim1; z__2.r = a[i__5].r * b[i__6].r - a[i__5].i * b[i__6].i, z__2.i = a[i__5].r * b[ i__6].i + a[i__5].i * b[i__6].r; z__1.r = b[i__4].r - z__2.r, z__1.i = b[i__4] .i - z__2.i; b[i__3].r = z__1.r, b[i__3].i = z__1.i; /* L250: */ } } /* L260: */ } if (nounit) { z_div(&z__1, &c_b1077, &a[j + j * a_dim1]); temp.r = z__1.r, temp.i = z__1.i; i__1 = *m; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = i__ + j * b_dim1; i__3 = i__ + j * b_dim1; z__1.r = temp.r * b[i__3].r - temp.i * b[i__3].i, z__1.i = temp.r * b[i__3].i + temp.i * b[ i__3].r; b[i__2].r = z__1.r, b[i__2].i = z__1.i; /* L270: */ } } /* L280: */ } } } else { /* Form B := alpha*B*inv( A' ) or B := alpha*B*inv( conjg( A' ) ). */ if (upper) { for (k = *n; k >= 1; --k) { if (nounit) { if (noconj) { z_div(&z__1, &c_b1077, &a[k + k * a_dim1]); temp.r = z__1.r, temp.i = z__1.i; } else { d_cnjg(&z__2, &a[k + k * a_dim1]); z_div(&z__1, &c_b1077, &z__2); temp.r = z__1.r, temp.i = z__1.i; } i__1 = *m; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = i__ + k * b_dim1; i__3 = i__ + k * b_dim1; z__1.r = temp.r * b[i__3].r - temp.i * b[i__3].i, z__1.i = temp.r * b[i__3].i + temp.i * b[ i__3].r; b[i__2].r = z__1.r, b[i__2].i = z__1.i; /* L290: */ } } i__1 = k - 1; for (j = 1; j <= i__1; ++j) { i__2 = j + k * a_dim1; if ((a[i__2].r != 0.) || (a[i__2].i != 0.)) { if (noconj) { i__2 = j + k * a_dim1; temp.r = a[i__2].r, temp.i = a[i__2].i; } else { d_cnjg(&z__1, &a[j + k * a_dim1]); temp.r = z__1.r, temp.i = z__1.i; } i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * b_dim1; i__4 = i__ + j * b_dim1; i__5 = i__ + k * b_dim1; z__2.r = temp.r * b[i__5].r - temp.i * b[i__5] .i, z__2.i = temp.r * b[i__5].i + temp.i * b[i__5].r; z__1.r = b[i__4].r - z__2.r, z__1.i = b[i__4] .i - z__2.i; b[i__3].r = z__1.r, b[i__3].i = z__1.i; /* L300: */ } } /* L310: */ } if ((alpha->r != 1.) || (alpha->i != 0.)) { i__1 = *m; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = i__ + k * b_dim1; i__3 = i__ + k * b_dim1; z__1.r = alpha->r * b[i__3].r - alpha->i * b[i__3] .i, z__1.i = alpha->r * b[i__3].i + alpha->i * b[i__3].r; b[i__2].r = z__1.r, b[i__2].i = z__1.i; /* L320: */ } } /* L330: */ } } else { i__1 = *n; for (k = 1; k <= i__1; ++k) { if (nounit) { if (noconj) { z_div(&z__1, &c_b1077, &a[k + k * a_dim1]); temp.r = z__1.r, temp.i = z__1.i; } else { d_cnjg(&z__2, &a[k + k * a_dim1]); z_div(&z__1, &c_b1077, &z__2); temp.r = z__1.r, temp.i = z__1.i; } i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + k * b_dim1; i__4 = i__ + k * b_dim1; z__1.r = temp.r * b[i__4].r - temp.i * b[i__4].i, z__1.i = temp.r * b[i__4].i + temp.i * b[ i__4].r; b[i__3].r = z__1.r, b[i__3].i = z__1.i; /* L340: */ } } i__2 = *n; for (j = k + 1; j <= i__2; ++j) { i__3 = j + k * a_dim1; if ((a[i__3].r != 0.) || (a[i__3].i != 0.)) { if (noconj) { i__3 = j + k * a_dim1; temp.r = a[i__3].r, temp.i = a[i__3].i; } else { d_cnjg(&z__1, &a[j + k * a_dim1]); temp.r = z__1.r, temp.i = z__1.i; } i__3 = *m; for (i__ = 1; i__ <= i__3; ++i__) { i__4 = i__ + j * b_dim1; i__5 = i__ + j * b_dim1; i__6 = i__ + k * b_dim1; z__2.r = temp.r * b[i__6].r - temp.i * b[i__6] .i, z__2.i = temp.r * b[i__6].i + temp.i * b[i__6].r; z__1.r = b[i__5].r - z__2.r, z__1.i = b[i__5] .i - z__2.i; b[i__4].r = z__1.r, b[i__4].i = z__1.i; /* L350: */ } } /* L360: */ } if ((alpha->r != 1.) || (alpha->i != 0.)) { i__2 = *m; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + k * b_dim1; i__4 = i__ + k * b_dim1; z__1.r = alpha->r * b[i__4].r - alpha->i * b[i__4] .i, z__1.i = alpha->r * b[i__4].i + alpha->i * b[i__4].r; b[i__3].r = z__1.r, b[i__3].i = z__1.i; /* L370: */ } } /* L380: */ } } } } return 0; /* End of ZTRSM . */ } /* ztrsm_ */ /* Subroutine */ int ztrsv_(char *uplo, char *trans, char *diag, integer *n, doublecomplex *a, integer *lda, doublecomplex *x, integer *incx) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3, i__4, i__5; doublecomplex z__1, z__2, z__3; /* Builtin functions */ void z_div(doublecomplex *, doublecomplex *, doublecomplex *), d_cnjg( doublecomplex *, doublecomplex *); /* Local variables */ static integer i__, j, ix, jx, kx, info; static doublecomplex temp; extern logical lsame_(char *, char *); extern /* Subroutine */ int xerbla_(char *, integer *); static logical noconj, nounit; /* Purpose ======= ZTRSV solves one of the systems of equations A*x = b, or A'*x = b, or conjg( A' )*x = b, where b and x are n element vectors and A is an n by n unit, or non-unit, upper or lower triangular matrix. No test for singularity or near-singularity is included in this routine. Such tests must be performed before calling this routine. Parameters ========== UPLO - CHARACTER*1. On entry, UPLO specifies whether the matrix is an upper or lower triangular matrix as follows: UPLO = 'U' or 'u' A is an upper triangular matrix. UPLO = 'L' or 'l' A is a lower triangular matrix. Unchanged on exit. TRANS - CHARACTER*1. On entry, TRANS specifies the equations to be solved as follows: TRANS = 'N' or 'n' A*x = b. TRANS = 'T' or 't' A'*x = b. TRANS = 'C' or 'c' conjg( A' )*x = b. Unchanged on exit. DIAG - CHARACTER*1. On entry, DIAG specifies whether or not A is unit triangular as follows: DIAG = 'U' or 'u' A is assumed to be unit triangular. DIAG = 'N' or 'n' A is not assumed to be unit triangular. Unchanged on exit. N - INTEGER. On entry, N specifies the order of the matrix A. N must be at least zero. Unchanged on exit. A - COMPLEX*16 array of DIMENSION ( LDA, n ). Before entry with UPLO = 'U' or 'u', the leading n by n upper triangular part of the array A must contain the upper triangular matrix and the strictly lower triangular part of A is not referenced. Before entry with UPLO = 'L' or 'l', the leading n by n lower triangular part of the array A must contain the lower triangular matrix and the strictly upper triangular part of A is not referenced. Note that when DIAG = 'U' or 'u', the diagonal elements of A are not referenced either, but are assumed to be unity. Unchanged on exit. LDA - INTEGER. On entry, LDA specifies the first dimension of A as declared in the calling (sub) program. LDA must be at least max( 1, n ). Unchanged on exit. X - COMPLEX*16 array of dimension at least ( 1 + ( n - 1 )*abs( INCX ) ). Before entry, the incremented array X must contain the n element right-hand side vector b. On exit, X is overwritten with the solution vector x. INCX - INTEGER. On entry, INCX specifies the increment for the elements of X. INCX must not be zero. Unchanged on exit. Level 2 Blas routine. -- Written on 22-October-1986. Jack Dongarra, Argonne National Lab. Jeremy Du Croz, Nag Central Office. Sven Hammarling, Nag Central Office. Richard Hanson, Sandia National Labs. Test the input parameters. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --x; /* Function Body */ info = 0; if (! lsame_(uplo, "U") && ! lsame_(uplo, "L")) { info = 1; } else if (! lsame_(trans, "N") && ! lsame_(trans, "T") && ! lsame_(trans, "C")) { info = 2; } else if (! lsame_(diag, "U") && ! lsame_(diag, "N")) { info = 3; } else if (*n < 0) { info = 4; } else if (*lda < max(1,*n)) { info = 6; } else if (*incx == 0) { info = 8; } if (info != 0) { xerbla_("ZTRSV ", &info); return 0; } /* Quick return if possible. */ if (*n == 0) { return 0; } noconj = lsame_(trans, "T"); nounit = lsame_(diag, "N"); /* Set up the start point in X if the increment is not unity. This will be ( N - 1 )*INCX too small for descending loops. */ if (*incx <= 0) { kx = 1 - (*n - 1) * *incx; } else if (*incx != 1) { kx = 1; } /* Start the operations. In this version the elements of A are accessed sequentially with one pass through A. */ if (lsame_(trans, "N")) { /* Form x := inv( A )*x. */ if (lsame_(uplo, "U")) { if (*incx == 1) { for (j = *n; j >= 1; --j) { i__1 = j; if ((x[i__1].r != 0.) || (x[i__1].i != 0.)) { if (nounit) { i__1 = j; z_div(&z__1, &x[j], &a[j + j * a_dim1]); x[i__1].r = z__1.r, x[i__1].i = z__1.i; } i__1 = j; temp.r = x[i__1].r, temp.i = x[i__1].i; for (i__ = j - 1; i__ >= 1; --i__) { i__1 = i__; i__2 = i__; i__3 = i__ + j * a_dim1; z__2.r = temp.r * a[i__3].r - temp.i * a[i__3].i, z__2.i = temp.r * a[i__3].i + temp.i * a[ i__3].r; z__1.r = x[i__2].r - z__2.r, z__1.i = x[i__2].i - z__2.i; x[i__1].r = z__1.r, x[i__1].i = z__1.i; /* L10: */ } } /* L20: */ } } else { jx = kx + (*n - 1) * *incx; for (j = *n; j >= 1; --j) { i__1 = jx; if ((x[i__1].r != 0.) || (x[i__1].i != 0.)) { if (nounit) { i__1 = jx; z_div(&z__1, &x[jx], &a[j + j * a_dim1]); x[i__1].r = z__1.r, x[i__1].i = z__1.i; } i__1 = jx; temp.r = x[i__1].r, temp.i = x[i__1].i; ix = jx; for (i__ = j - 1; i__ >= 1; --i__) { ix -= *incx; i__1 = ix; i__2 = ix; i__3 = i__ + j * a_dim1; z__2.r = temp.r * a[i__3].r - temp.i * a[i__3].i, z__2.i = temp.r * a[i__3].i + temp.i * a[ i__3].r; z__1.r = x[i__2].r - z__2.r, z__1.i = x[i__2].i - z__2.i; x[i__1].r = z__1.r, x[i__1].i = z__1.i; /* L30: */ } } jx -= *incx; /* L40: */ } } } else { if (*incx == 1) { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = j; if ((x[i__2].r != 0.) || (x[i__2].i != 0.)) { if (nounit) { i__2 = j; z_div(&z__1, &x[j], &a[j + j * a_dim1]); x[i__2].r = z__1.r, x[i__2].i = z__1.i; } i__2 = j; temp.r = x[i__2].r, temp.i = x[i__2].i; i__2 = *n; for (i__ = j + 1; i__ <= i__2; ++i__) { i__3 = i__; i__4 = i__; i__5 = i__ + j * a_dim1; z__2.r = temp.r * a[i__5].r - temp.i * a[i__5].i, z__2.i = temp.r * a[i__5].i + temp.i * a[ i__5].r; z__1.r = x[i__4].r - z__2.r, z__1.i = x[i__4].i - z__2.i; x[i__3].r = z__1.r, x[i__3].i = z__1.i; /* L50: */ } } /* L60: */ } } else { jx = kx; i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = jx; if ((x[i__2].r != 0.) || (x[i__2].i != 0.)) { if (nounit) { i__2 = jx; z_div(&z__1, &x[jx], &a[j + j * a_dim1]); x[i__2].r = z__1.r, x[i__2].i = z__1.i; } i__2 = jx; temp.r = x[i__2].r, temp.i = x[i__2].i; ix = jx; i__2 = *n; for (i__ = j + 1; i__ <= i__2; ++i__) { ix += *incx; i__3 = ix; i__4 = ix; i__5 = i__ + j * a_dim1; z__2.r = temp.r * a[i__5].r - temp.i * a[i__5].i, z__2.i = temp.r * a[i__5].i + temp.i * a[ i__5].r; z__1.r = x[i__4].r - z__2.r, z__1.i = x[i__4].i - z__2.i; x[i__3].r = z__1.r, x[i__3].i = z__1.i; /* L70: */ } } jx += *incx; /* L80: */ } } } } else { /* Form x := inv( A' )*x or x := inv( conjg( A' ) )*x. */ if (lsame_(uplo, "U")) { if (*incx == 1) { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = j; temp.r = x[i__2].r, temp.i = x[i__2].i; if (noconj) { i__2 = j - 1; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * a_dim1; i__4 = i__; z__2.r = a[i__3].r * x[i__4].r - a[i__3].i * x[ i__4].i, z__2.i = a[i__3].r * x[i__4].i + a[i__3].i * x[i__4].r; z__1.r = temp.r - z__2.r, z__1.i = temp.i - z__2.i; temp.r = z__1.r, temp.i = z__1.i; /* L90: */ } if (nounit) { z_div(&z__1, &temp, &a[j + j * a_dim1]); temp.r = z__1.r, temp.i = z__1.i; } } else { i__2 = j - 1; for (i__ = 1; i__ <= i__2; ++i__) { d_cnjg(&z__3, &a[i__ + j * a_dim1]); i__3 = i__; z__2.r = z__3.r * x[i__3].r - z__3.i * x[i__3].i, z__2.i = z__3.r * x[i__3].i + z__3.i * x[ i__3].r; z__1.r = temp.r - z__2.r, z__1.i = temp.i - z__2.i; temp.r = z__1.r, temp.i = z__1.i; /* L100: */ } if (nounit) { d_cnjg(&z__2, &a[j + j * a_dim1]); z_div(&z__1, &temp, &z__2); temp.r = z__1.r, temp.i = z__1.i; } } i__2 = j; x[i__2].r = temp.r, x[i__2].i = temp.i; /* L110: */ } } else { jx = kx; i__1 = *n; for (j = 1; j <= i__1; ++j) { ix = kx; i__2 = jx; temp.r = x[i__2].r, temp.i = x[i__2].i; if (noconj) { i__2 = j - 1; for (i__ = 1; i__ <= i__2; ++i__) { i__3 = i__ + j * a_dim1; i__4 = ix; z__2.r = a[i__3].r * x[i__4].r - a[i__3].i * x[ i__4].i, z__2.i = a[i__3].r * x[i__4].i + a[i__3].i * x[i__4].r; z__1.r = temp.r - z__2.r, z__1.i = temp.i - z__2.i; temp.r = z__1.r, temp.i = z__1.i; ix += *incx; /* L120: */ } if (nounit) { z_div(&z__1, &temp, &a[j + j * a_dim1]); temp.r = z__1.r, temp.i = z__1.i; } } else { i__2 = j - 1; for (i__ = 1; i__ <= i__2; ++i__) { d_cnjg(&z__3, &a[i__ + j * a_dim1]); i__3 = ix; z__2.r = z__3.r * x[i__3].r - z__3.i * x[i__3].i, z__2.i = z__3.r * x[i__3].i + z__3.i * x[ i__3].r; z__1.r = temp.r - z__2.r, z__1.i = temp.i - z__2.i; temp.r = z__1.r, temp.i = z__1.i; ix += *incx; /* L130: */ } if (nounit) { d_cnjg(&z__2, &a[j + j * a_dim1]); z_div(&z__1, &temp, &z__2); temp.r = z__1.r, temp.i = z__1.i; } } i__2 = jx; x[i__2].r = temp.r, x[i__2].i = temp.i; jx += *incx; /* L140: */ } } } else { if (*incx == 1) { for (j = *n; j >= 1; --j) { i__1 = j; temp.r = x[i__1].r, temp.i = x[i__1].i; if (noconj) { i__1 = j + 1; for (i__ = *n; i__ >= i__1; --i__) { i__2 = i__ + j * a_dim1; i__3 = i__; z__2.r = a[i__2].r * x[i__3].r - a[i__2].i * x[ i__3].i, z__2.i = a[i__2].r * x[i__3].i + a[i__2].i * x[i__3].r; z__1.r = temp.r - z__2.r, z__1.i = temp.i - z__2.i; temp.r = z__1.r, temp.i = z__1.i; /* L150: */ } if (nounit) { z_div(&z__1, &temp, &a[j + j * a_dim1]); temp.r = z__1.r, temp.i = z__1.i; } } else { i__1 = j + 1; for (i__ = *n; i__ >= i__1; --i__) { d_cnjg(&z__3, &a[i__ + j * a_dim1]); i__2 = i__; z__2.r = z__3.r * x[i__2].r - z__3.i * x[i__2].i, z__2.i = z__3.r * x[i__2].i + z__3.i * x[ i__2].r; z__1.r = temp.r - z__2.r, z__1.i = temp.i - z__2.i; temp.r = z__1.r, temp.i = z__1.i; /* L160: */ } if (nounit) { d_cnjg(&z__2, &a[j + j * a_dim1]); z_div(&z__1, &temp, &z__2); temp.r = z__1.r, temp.i = z__1.i; } } i__1 = j; x[i__1].r = temp.r, x[i__1].i = temp.i; /* L170: */ } } else { kx += (*n - 1) * *incx; jx = kx; for (j = *n; j >= 1; --j) { ix = kx; i__1 = jx; temp.r = x[i__1].r, temp.i = x[i__1].i; if (noconj) { i__1 = j + 1; for (i__ = *n; i__ >= i__1; --i__) { i__2 = i__ + j * a_dim1; i__3 = ix; z__2.r = a[i__2].r * x[i__3].r - a[i__2].i * x[ i__3].i, z__2.i = a[i__2].r * x[i__3].i + a[i__2].i * x[i__3].r; z__1.r = temp.r - z__2.r, z__1.i = temp.i - z__2.i; temp.r = z__1.r, temp.i = z__1.i; ix -= *incx; /* L180: */ } if (nounit) { z_div(&z__1, &temp, &a[j + j * a_dim1]); temp.r = z__1.r, temp.i = z__1.i; } } else { i__1 = j + 1; for (i__ = *n; i__ >= i__1; --i__) { d_cnjg(&z__3, &a[i__ + j * a_dim1]); i__2 = ix; z__2.r = z__3.r * x[i__2].r - z__3.i * x[i__2].i, z__2.i = z__3.r * x[i__2].i + z__3.i * x[ i__2].r; z__1.r = temp.r - z__2.r, z__1.i = temp.i - z__2.i; temp.r = z__1.r, temp.i = z__1.i; ix -= *incx; /* L190: */ } if (nounit) { d_cnjg(&z__2, &a[j + j * a_dim1]); z_div(&z__1, &temp, &z__2); temp.r = z__1.r, temp.i = z__1.i; } } i__1 = jx; x[i__1].r = temp.r, x[i__1].i = temp.i; jx -= *incx; /* L200: */ } } } } return 0; /* End of ZTRSV . */ } /* ztrsv_ */ numpy-1.8.2/numpy/linalg/lapack_lite/python_xerbla.c0000664000175100017510000000250712370216242023737 0ustar vagrantvagrant00000000000000#include "Python.h" #include "f2c.h" /* From the original manpage: -------------------------- XERBLA is an error handler for the LAPACK routines. It is called by an LAPACK routine if an input parameter has an invalid value. A message is printed and execution stops. Instead of printing a message and stopping the execution, a ValueError is raised with the message. Parameters: ----------- srname: Subroutine name to use in error message, maximum six characters. Spaces at the end are skipped. info: Number of the invalid parameter. */ int xerbla_(char *srname, integer *info) { const char* format = "On entry to %.*s" \ " parameter number %d had an illegal value"; char buf[57 + 6 + 4]; /* 57 for strlen(format), 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--; #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; } numpy-1.8.2/numpy/linalg/umath_linalg.c.src0000664000175100017510000026007612370216243022053 0ustar vagrantvagrant00000000000000/* -*- c -*- */ /* ***************************************************************************** ** INCLUDES ** ***************************************************************************** */ #define NPY_NO_DEPRECATED_API NPY_API_VERSION #include "Python.h" #include "numpy/arrayobject.h" #include "numpy/ufuncobject.h" #include "npy_pycompat.h" #include "npy_config.h" #include #include #include #include static const char* umath_linalg_version_string = "0.1.4"; /* **************************************************************************** * Debugging support * **************************************************************************** */ #define TRACE_TXT(...) do { fprintf (stderr, __VA_ARGS__); } while (0) #define STACK_TRACE do {} while (0) #define TRACE\ do { \ fprintf (stderr, \ "%s:%d:%s\n", \ __FILE__, \ __LINE__, \ __FUNCTION__); \ STACK_TRACE; \ } while (0) #if 0 #include void dbg_stack_trace() { void *trace[32]; size_t size; size = backtrace(trace, sizeof(trace)/sizeof(trace[0])); backtrace_symbols_fd(trace, size, 1); } #undef STACK_TRACE #define STACK_TRACE do { dbg_stack_trace(); } while (0) #endif /* ***************************************************************************** * BLAS/LAPACK calling macros * ***************************************************************************** */ #ifdef NO_APPEND_FORTRAN # define FNAME(x) x #else # define FNAME(x) x##_ #endif typedef struct { float r, i; } f2c_complex; typedef struct { double r, i; } f2c_doublecomplex; /* typedef long int (*L_fp)(); */ extern int FNAME(sgeev)(char *jobvl, char *jobvr, int *n, float a[], int *lda, float wr[], float wi[], float vl[], int *ldvl, float vr[], int *ldvr, float work[], int lwork[], int *info); 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(cgeev)(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(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(ssyevd)(char *jobz, char *uplo, int *n, float a[], int *lda, float w[], float work[], int *lwork, int iwork[], int *liwork, 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(cheevd)(char *jobz, char *uplo, int *n, f2c_complex a[], int *lda, float w[], f2c_complex work[], int *lwork, float rwork[], int *lrwork, 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, double s[], double *rcond, int *rank, f2c_doublecomplex work[], int *lwork, double rwork[], int iwork[], int *info); extern int FNAME(sgesv)(int *n, int *nrhs, float a[], int *lda, int ipiv[], float b[], int *ldb, 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(cgesv)(int *n, int *nrhs, f2c_complex a[], int *lda, int ipiv[], f2c_complex 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(sgetrf)(int *m, int *n, float a[], int *lda, int ipiv[], int *info); extern int FNAME(dgetrf)(int *m, int *n, double a[], int *lda, int ipiv[], int *info); extern int FNAME(cgetrf)(int *m, int *n, f2c_complex 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(spotrf)(char *uplo, int *n, float a[], int *lda, int *info); extern int FNAME(dpotrf)(char *uplo, int *n, double a[], int *lda, int *info); extern int FNAME(cpotrf)(char *uplo, int *n, f2c_complex a[], int *lda, int *info); extern int FNAME(zpotrf)(char *uplo, int *n, f2c_doublecomplex a[], int *lda, int *info); extern int FNAME(sgesdd)(char *jobz, int *m, int *n, float a[], int *lda, float s[], float u[], int *ldu, float vt[], int *ldvt, float work[], int *lwork, int iwork[], 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(cgesdd)(char *jobz, int *m, int *n, f2c_complex a[], int *lda, float s[], f2c_complex u[], int *ldu, f2c_complex vt[], int *ldvt, f2c_complex work[], int *lwork, float rwork[], 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(spotrs)(char *uplo, int *n, int *nrhs, float a[], int *lda, float b[], int *ldb, int *info); extern int FNAME(dpotrs)(char *uplo, int *n, int *nrhs, double a[], int *lda, double b[], int *ldb, int *info); extern int FNAME(cpotrs)(char *uplo, int *n, int *nrhs, f2c_complex a[], int *lda, f2c_complex b[], int *ldb, int *info); extern int FNAME(zpotrs)(char *uplo, int *n, int *nrhs, f2c_doublecomplex a[], int *lda, f2c_doublecomplex b[], int *ldb, int *info); extern int FNAME(spotri)(char *uplo, int *n, float a[], int *lda, int *info); extern int FNAME(dpotri)(char *uplo, int *n, double a[], int *lda, int *info); extern int FNAME(cpotri)(char *uplo, int *n, f2c_complex a[], int *lda, int *info); extern int FNAME(zpotri)(char *uplo, int *n, f2c_doublecomplex a[], int *lda, int *info); extern int FNAME(scopy)(int *n, float *sx, int *incx, float *sy, int *incy); extern int FNAME(dcopy)(int *n, double *sx, int *incx, double *sy, int *incy); extern int FNAME(ccopy)(int *n, f2c_complex *sx, int *incx, f2c_complex *sy, int *incy); extern int FNAME(zcopy)(int *n, f2c_doublecomplex *sx, int *incx, f2c_doublecomplex *sy, int *incy); extern float FNAME(sdot)(int *n, float *sx, int *incx, float *sy, int *incy); extern double FNAME(ddot)(int *n, double *sx, int *incx, double *sy, int *incy); extern f2c_complex FNAME(cdotu)(int *n, f2c_complex *sx, int *incx, f2c_complex *sy, int *incy); extern f2c_doublecomplex FNAME(zdotu)(int *n, f2c_doublecomplex *sx, int *incx, f2c_doublecomplex *sy, int *incy); extern f2c_complex FNAME(cdotc)(int *n, f2c_complex *sx, int *incx, f2c_complex *sy, int *incy); extern f2c_doublecomplex FNAME(zdotc)(int *n, f2c_doublecomplex *sx, int *incx, f2c_doublecomplex *sy, int *incy); extern int FNAME(sgemm)(char *transa, char *transb, int *m, int *n, int *k, float *alpha, float *a, int *lda, float *b, int *ldb, float *beta, float *c, int *ldc); extern int FNAME(dgemm)(char *transa, char *transb, int *m, int *n, int *k, double *alpha, double *a, int *lda, double *b, int *ldb, double *beta, double *c, int *ldc); extern int FNAME(cgemm)(char *transa, char *transb, int *m, int *n, int *k, f2c_complex *alpha, f2c_complex *a, int *lda, f2c_complex *b, int *ldb, f2c_complex *beta, f2c_complex *c, int *ldc); extern int FNAME(zgemm)(char *transa, char *transb, int *m, int *n, int *k, f2c_doublecomplex *alpha, f2c_doublecomplex *a, int *lda, f2c_doublecomplex *b, int *ldb, f2c_doublecomplex *beta, f2c_doublecomplex *c, int *ldc); #define LAPACK_T(FUNC) \ TRACE_TXT("Calling LAPACK ( " # FUNC " )\n"); \ FNAME(FUNC) #define BLAS(FUNC) \ FNAME(FUNC) #define LAPACK(FUNC) \ FNAME(FUNC) typedef int fortran_int; typedef float fortran_real; typedef double fortran_doublereal; typedef f2c_complex fortran_complex; typedef f2c_doublecomplex fortran_doublecomplex; /* ***************************************************************************** ** Some handy functions ** ***************************************************************************** */ static inline void * offset_ptr(void* ptr, ptrdiff_t offset) { return (void*)((npy_uint8*)ptr + offset); } static inline int get_fp_invalid_and_clear(void) { int status; status = PyUFunc_getfperr(); return !!(status & UFUNC_FPE_INVALID); } static inline void set_fp_invalid_or_clear(int error_occurred) { if (error_occurred) { npy_set_floatstatus_invalid(); } else { PyUFunc_getfperr(); } } /* ***************************************************************************** ** Some handy constants ** ***************************************************************************** */ #define UMATH_LINALG_MODULE_NAME "_umath_linalg" typedef union { fortran_complex f; npy_cfloat npy; float array[2]; } COMPLEX_t; typedef union { fortran_doublecomplex f; npy_cdouble npy; double array[2]; } DOUBLECOMPLEX_t; static float s_one; static float s_zero; static float s_minus_one; static float s_ninf; static float s_nan; static double d_one; static double d_zero; static double d_minus_one; static double d_ninf; static double d_nan; static COMPLEX_t c_one; static COMPLEX_t c_zero; static COMPLEX_t c_minus_one; static COMPLEX_t c_ninf; static COMPLEX_t c_nan; static DOUBLECOMPLEX_t z_one; static DOUBLECOMPLEX_t z_zero; static DOUBLECOMPLEX_t z_minus_one; static DOUBLECOMPLEX_t z_ninf; static DOUBLECOMPLEX_t z_nan; static void init_constants(void) { /* this is needed as NPY_INFINITY and NPY_NAN macros can't be used as initializers. I prefer to just set all the constants the same way. */ s_one = 1.0f; s_zero = 0.0f; s_minus_one = -1.0f; s_ninf = -NPY_INFINITYF; s_nan = NPY_NANF; d_one = 1.0; d_zero = 0.0; d_minus_one = -1.0; d_ninf = -NPY_INFINITY; d_nan = NPY_NAN; c_one.array[0] = 1.0f; c_one.array[1] = 0.0f; c_zero.array[0] = 0.0f; c_zero.array[1] = 0.0f; c_minus_one.array[0] = -1.0f; c_minus_one.array[1] = 0.0f; c_ninf.array[0] = -NPY_INFINITYF; c_ninf.array[1] = 0.0f; c_nan.array[0] = NPY_NANF; c_nan.array[1] = NPY_NANF; z_one.array[0] = 1.0; z_one.array[1] = 0.0; z_zero.array[0] = 0.0; z_zero.array[1] = 0.0; z_minus_one.array[0] = -1.0; z_minus_one.array[1] = 0.0; z_ninf.array[0] = -NPY_INFINITY; z_ninf.array[1] = 0.0; z_nan.array[0] = NPY_NAN; z_nan.array[1] = NPY_NAN; } /* ***************************************************************************** ** Structs used for data rearrangement ** ***************************************************************************** */ /* this struct contains information about how to linearize in a local buffer a matrix so that it can be used by blas functions. All strides are specified in number of elements (similar to what blas expects) dst_row_strides: number of elements between different row. Matrix is considered row-major dst_column_strides: number of elements between differnt columns in the destination buffer rows: number of rows of the matrix columns: number of columns of the matrix src_row_strides: strides needed to access the next row in the source matrix src_column_strides: strides needed to access the next column in the source matrix */ typedef struct linearize_data_struct { size_t rows; size_t columns; ptrdiff_t row_strides; ptrdiff_t column_strides; } LINEARIZE_DATA_t; static inline void init_linearize_data(LINEARIZE_DATA_t *lin_data, int rows, int columns, ptrdiff_t row_strides, ptrdiff_t column_strides) { lin_data->rows = rows; lin_data->columns = columns; lin_data->row_strides = row_strides; lin_data->column_strides = column_strides; } static inline void dump_ufunc_object(PyUFuncObject* ufunc) { TRACE_TXT("\n\n%s '%s' (%d input(s), %d output(s), %d specialization(s).\n", ufunc->core_enabled? "generalized ufunc" : "scalar ufunc", ufunc->name, ufunc->nin, ufunc->nout, ufunc->ntypes); if (ufunc->core_enabled) { int arg; int dim; TRACE_TXT("\t%s (%d dimension(s) detected).\n", ufunc->core_signature, ufunc->core_num_dim_ix); for (arg = 0; arg < ufunc->nargs; arg++){ int * arg_dim_ix = ufunc->core_dim_ixs + ufunc->core_offsets[arg]; TRACE_TXT("\t\targ %d (%s) has %d dimension(s): (", arg, arg < ufunc->nin? "INPUT" : "OUTPUT", ufunc->core_num_dims[arg]); for (dim = 0; dim < ufunc->core_num_dims[arg]; dim ++) { TRACE_TXT(" %d", arg_dim_ix[dim]); } TRACE_TXT(" )\n"); } } } static inline void dump_linearize_data(const char* name, const LINEARIZE_DATA_t* params) { TRACE_TXT("\n\t%s rows: %zd columns: %zd"\ "\n\t\trow_strides: %td column_strides: %td"\ "\n", name, params->rows, params->columns, params->row_strides, params->column_strides); } static inline float FLOAT_add(float op1, float op2) { return op1 + op2; } static inline double DOUBLE_add(double op1, double op2) { return op1 + op2; } static inline COMPLEX_t CFLOAT_add(COMPLEX_t op1, COMPLEX_t op2) { COMPLEX_t result; result.array[0] = op1.array[0] + op2.array[0]; result.array[1] = op1.array[1] + op2.array[1]; return result; } static inline DOUBLECOMPLEX_t CDOUBLE_add(DOUBLECOMPLEX_t op1, DOUBLECOMPLEX_t op2) { DOUBLECOMPLEX_t result; result.array[0] = op1.array[0] + op2.array[0]; result.array[1] = op1.array[1] + op2.array[1]; return result; } static inline float FLOAT_mul(float op1, float op2) { return op1*op2; } static inline double DOUBLE_mul(double op1, double op2) { return op1*op2; } static inline COMPLEX_t CFLOAT_mul(COMPLEX_t op1, COMPLEX_t op2) { COMPLEX_t result; result.array[0] = op1.array[0]*op2.array[0] - op1.array[1]*op2.array[1]; result.array[1] = op1.array[1]*op2.array[0] + op1.array[0]*op2.array[1]; return result; } static inline DOUBLECOMPLEX_t CDOUBLE_mul(DOUBLECOMPLEX_t op1, DOUBLECOMPLEX_t op2) { DOUBLECOMPLEX_t result; result.array[0] = op1.array[0]*op2.array[0] - op1.array[1]*op2.array[1]; result.array[1] = op1.array[1]*op2.array[0] + op1.array[0]*op2.array[1]; return result; } static inline float FLOAT_mulc(float op1, float op2) { return op1*op2; } static inline double DOUBLE_mulc(float op1, float op2) { return op1*op2; } static inline COMPLEX_t CFLOAT_mulc(COMPLEX_t op1, COMPLEX_t op2) { COMPLEX_t result; result.array[0] = op1.array[0]*op2.array[0] + op1.array[1]*op2.array[1]; result.array[1] = op1.array[0]*op2.array[1] - op1.array[1]*op2.array[0]; return result; } static inline DOUBLECOMPLEX_t CDOUBLE_mulc(DOUBLECOMPLEX_t op1, DOUBLECOMPLEX_t op2) { DOUBLECOMPLEX_t result; result.array[0] = op1.array[0]*op2.array[0] + op1.array[1]*op2.array[1]; result.array[1] = op1.array[0]*op2.array[1] - op1.array[1]*op2.array[0]; return result; } static inline void print_FLOAT(npy_float s) { TRACE_TXT(" %8.4f", s); } static inline void print_DOUBLE(npy_double d) { TRACE_TXT(" %10.6f", d); } static inline void print_CFLOAT(npy_cfloat c) { float* c_parts = (float*)&c; TRACE_TXT("(%8.4f, %8.4fj)", c_parts[0], c_parts[1]); } static inline void print_CDOUBLE(npy_cdouble z) { double* z_parts = (double*)&z; TRACE_TXT("(%8.4f, %8.4fj)", z_parts[0], z_parts[1]); } /**begin repeat #TYPE=FLOAT,DOUBLE,CFLOAT,CDOUBLE# #typ=npy_float,npy_double,npy_cfloat,npy_cdouble# */ static inline void dump_@TYPE@_matrix(const char* name, size_t rows, size_t columns, const @typ@* ptr) { size_t i,j; TRACE_TXT("\n%s %p (%zd, %zd)\n", name, ptr, rows, columns); for (i=0; icolumns; fortran_int column_strides = (fortran_int)(data->column_strides/sizeof(@typ@)); fortran_int one = 1; for (i=0; i< data->rows; i++) { if (column_strides > 0) { FNAME(@copy@)(&columns, (void*)src, &column_strides, (void*)dst, &one); } else if (column_strides < 0) { FNAME(@copy@)(&columns, (void*)((@typ@*)src + (columns-1)*column_strides), &column_strides, (void*)dst, &one); } else { /* * Zero stride has undefined behavior in some BLAS * implementations (e.g. OSX Accelerate), so do it * manually */ for (j = 0; j < columns; ++j) { memcpy((@typ@*)dst + j, (@typ@*)src, sizeof(@typ@)); } } src += data->row_strides/sizeof(@typ@); dst += data->columns; } return rv; } else { return src; } } static inline void * delinearize_@TYPE@_matrix(void *dst_in, void *src_in, const LINEARIZE_DATA_t* data) { @typ@ *src = (@typ@ *) src_in; @typ@ *dst = (@typ@ *) dst_in; if (src) { int i; @typ@ *rv = src; fortran_int columns = (fortran_int)data->columns; fortran_int column_strides = (fortran_int)(data->column_strides/sizeof(@typ@)); fortran_int one = 1; for (i=0; i < data->rows; i++) { if (column_strides > 0) { FNAME(@copy@)(&columns, (void*)src, &one, (void*)dst, &column_strides); } else if (column_strides < 0) { FNAME(@copy@)(&columns, (void*)src, &one, (void*)((@typ@*)dst + (columns-1)*column_strides), &column_strides); } else { /* * Zero stride has undefined behavior in some BLAS * implementations (e.g. OSX Accelerate), so do it * manually */ if (columns > 0) { memcpy((@typ@*)dst, (@typ@*)src + (columns-1), sizeof(@typ@)); } } src += data->columns; dst += data->row_strides/sizeof(@typ@); } return rv; } else { return src; } } static inline void nan_@TYPE@_matrix(void *dst_in, const LINEARIZE_DATA_t* data) { @typ@ *dst = (@typ@ *) dst_in; int i,j; for (i=0; i < data->rows; i++) { @typ@ *cp = dst; ptrdiff_t cs = data->column_strides/sizeof(@typ@); for (j=0; j< data->columns; ++j) { *cp = @nan@; cp += cs; } dst += data->row_strides/sizeof(@typ@); } } /**end repeat**/ /* identity square matrix generation */ /**begin repeat #TYPE=FLOAT,DOUBLE,CFLOAT,CDOUBLE# #typ=float,double,COMPLEX_t,DOUBLECOMPLEX_t# #cblas_type=s,d,c,z# */ static inline void identity_@TYPE@_matrix(void *ptr, size_t n) { size_t i; @typ@ *matrix = (@typ@*) ptr; /* in IEEE floating point, zeroes are represented as bitwise 0 */ memset(matrix, 0, n*n*sizeof(@typ@)); for (i = 0; i < n; ++i) { *matrix = @cblas_type@_one; matrix += n+1; } } /**end repeat**/ /* lower/upper triangular matrix using blas (in place) */ /**begin repeat #TYPE=FLOAT,DOUBLE,CFLOAT,CDOUBLE# #typ=float,double,COMPLEX_t,DOUBLECOMPLEX_t# #cblas_type=s,d,c,z# */ static inline void triu_@TYPE@_matrix(void *ptr, size_t n) { size_t i,j; @typ@ *matrix = (@typ@*)ptr; matrix += n; for (i=1; i < n; ++i) { for (j=0; jA = a; params->W = w; params->WORK = work; params->RWORK = NULL; /* unused */ params->IWORK = iwork; params->N = N; params->LWORK = lwork; params->LRWORK = 0; /* unused */ params->LIWORK = liwork; params->JOBZ = JOBZ; params->UPLO = UPLO; return 1; error: /* something failed */ memset(params, 0, sizeof(*params)); free(mem_buff2); free(mem_buff); return 0; } static inline fortran_int call_@lapack_func@(EIGH_PARAMS_t *params) { fortran_int rv; LAPACK(@lapack_func@)(¶ms->JOBZ, ¶ms->UPLO, ¶ms->N, params->A, ¶ms->N, params->W, params->WORK, ¶ms->LWORK, params->IWORK, ¶ms->LIWORK, &rv); return rv; } /**end repeat**/ /**begin repeat #TYPE=CFLOAT,CDOUBLE# #typ=npy_cfloat,npy_cdouble# #basetyp=npy_float,npy_double# #ftyp=fortran_complex,fortran_doublecomplex# #fbasetyp=fortran_real,fortran_doublereal# #lapack_func=cheevd,zheevd# */ /* * Initialize the parameters to use in for the lapack function _heev * Handles buffer allocation */ static inline int init_@lapack_func@(EIGH_PARAMS_t *params, char JOBZ, char UPLO, fortran_int N) { npy_uint8 *mem_buff = NULL; npy_uint8 *mem_buff2 = NULL; @ftyp@ query_work_size; @fbasetyp@ query_rwork_size; fortran_int query_iwork_size; fortran_int lwork = -1; fortran_int lrwork = -1; fortran_int liwork = -1; npy_uint8 *a, *w, *work, *rwork, *iwork; fortran_int info; mem_buff = malloc(N*N*sizeof(@typ@)+N*sizeof(@basetyp@)); if (!mem_buff) goto error; a = mem_buff; w = mem_buff+N*N*sizeof(@typ@); LAPACK(@lapack_func@)(&JOBZ, &UPLO, &N, (@ftyp@*)a, &N, (@fbasetyp@*)w, &query_work_size, &lwork, &query_rwork_size, &lrwork, &query_iwork_size, &liwork, &info); if (info != 0) goto error; lwork = (fortran_int)*(@fbasetyp@*)&query_work_size; lrwork = (fortran_int)query_rwork_size; liwork = query_iwork_size; mem_buff2 = malloc(lwork*sizeof(@typ@) + lrwork*sizeof(@basetyp@) + liwork*sizeof(fortran_int)); if (!mem_buff2) goto error; work = mem_buff2; rwork = work + lwork*sizeof(@typ@); iwork = rwork + lrwork*sizeof(@basetyp@); params->A = a; params->W = w; params->WORK = work; params->RWORK = rwork; params->IWORK = iwork; params->N = N; params->LWORK = lwork; params->LRWORK = lrwork; params->LIWORK = liwork; params->JOBZ = JOBZ; params->UPLO = UPLO; return 1; /* something failed */ error: memset(params, 0, sizeof(*params)); free(mem_buff2); free(mem_buff); return 0; } static inline fortran_int call_@lapack_func@(EIGH_PARAMS_t *params) { fortran_int rv; LAPACK(@lapack_func@)(¶ms->JOBZ, ¶ms->UPLO, ¶ms->N, params->A, ¶ms->N, params->W, params->WORK, ¶ms->LWORK, params->RWORK, ¶ms->LRWORK, params->IWORK, ¶ms->LIWORK, &rv); return rv; } /**end repeat**/ /**begin repeat #TYPE=FLOAT,DOUBLE,CFLOAT,CDOUBLE# #BASETYPE=FLOAT,DOUBLE,FLOAT,DOUBLE# #typ=npy_float,npy_double,npy_cfloat,npy_cdouble# #basetyp=npy_float,npy_double,npy_float,npy_double# #lapack_func=ssyevd,dsyevd,cheevd,zheevd# **/ /* * (M,M)->(M,)(M,M) * dimensions[1] -> M * args[0] -> A[in] * args[1] -> W * args[2] -> A[out] */ static inline void release_@lapack_func@(EIGH_PARAMS_t *params) { /* allocated memory in A and WORK */ free(params->A); free(params->WORK); memset(params, 0, sizeof(*params)); } static inline void @TYPE@_eigh_wrapper(char JOBZ, char UPLO, char**args, npy_intp* dimensions, npy_intp* steps) { ptrdiff_t outer_steps[3]; size_t iter; size_t outer_dim = *dimensions++; size_t op_count = (JOBZ=='N')?2:3; EIGH_PARAMS_t eigh_params; int error_occurred = get_fp_invalid_and_clear(); for (iter=0; iter < op_count; ++iter) { outer_steps[iter] = (ptrdiff_t) steps[iter]; } steps += op_count; if (init_@lapack_func@(&eigh_params, JOBZ, UPLO, (fortran_int)dimensions[0])) { LINEARIZE_DATA_t matrix_in_ld; LINEARIZE_DATA_t eigenvectors_out_ld; LINEARIZE_DATA_t eigenvalues_out_ld; init_linearize_data(&matrix_in_ld, eigh_params.N, eigh_params.N, steps[1], steps[0]); init_linearize_data(&eigenvalues_out_ld, 1, eigh_params.N, 0, steps[2]); if ('V' == eigh_params.JOBZ) { init_linearize_data(&eigenvectors_out_ld, eigh_params.N, eigh_params.N, steps[4], steps[3]); } for (iter = 0; iter < outer_dim; ++iter) { int not_ok; /* copy the matrix in */ linearize_@TYPE@_matrix(eigh_params.A, args[0], &matrix_in_ld); not_ok = call_@lapack_func@(&eigh_params); if (!not_ok) { /* lapack ok, copy result out */ delinearize_@BASETYPE@_matrix(args[1], eigh_params.W, &eigenvalues_out_ld); if ('V' == eigh_params.JOBZ) { delinearize_@TYPE@_matrix(args[2], eigh_params.A, &eigenvectors_out_ld); } } else { /* lapack fail, set result to nan */ error_occurred = 1; nan_@BASETYPE@_matrix(args[1], &eigenvalues_out_ld); if ('V' == eigh_params.JOBZ) { nan_@TYPE@_matrix(args[2], &eigenvectors_out_ld); } } update_pointers((npy_uint8**)args, outer_steps, op_count); } release_@lapack_func@(&eigh_params); } set_fp_invalid_or_clear(error_occurred); } /**end repeat**/ /**begin repeat #TYPE=FLOAT,DOUBLE,CFLOAT,CDOUBLE# */ static void @TYPE@_eighlo(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { @TYPE@_eigh_wrapper('V', 'L', args, dimensions, steps); } static void @TYPE@_eighup(char **args, npy_intp *dimensions, npy_intp *steps, void* NPY_UNUSED(func)) { @TYPE@_eigh_wrapper('V', 'U', args, dimensions, steps); } static void @TYPE@_eigvalshlo(char **args, npy_intp *dimensions, npy_intp *steps, void* NPY_UNUSED(func)) { @TYPE@_eigh_wrapper('N', 'L', args, dimensions, steps); } static void @TYPE@_eigvalshup(char **args, npy_intp *dimensions, npy_intp *steps, void* NPY_UNUSED(func)) { @TYPE@_eigh_wrapper('N', 'U', args, dimensions, steps); } /**end repeat**/ /* -------------------------------------------------------------------------- */ /* Solve family (includes inv) */ typedef struct gesv_params_struct { void *A; /* A is (N,N) of base type */ void *B; /* B is (N,NRHS) of base type */ fortran_int * IPIV; /* IPIV is (N) */ fortran_int N; fortran_int NRHS; fortran_int LDA; fortran_int LDB; } GESV_PARAMS_t; /**begin repeat #TYPE=FLOAT,DOUBLE,CFLOAT,CDOUBLE# #typ=npy_float,npy_double,npy_cfloat,npy_cdouble# #ftyp=fortran_real,fortran_doublereal,fortran_complex,fortran_doublecomplex# #lapack_func=sgesv,dgesv,cgesv,zgesv# */ /* * Initialize the parameters to use in for the lapack function _heev * Handles buffer allocation */ static inline int init_@lapack_func@(GESV_PARAMS_t *params, fortran_int N, fortran_int NRHS) { npy_uint8 *mem_buff = NULL; npy_uint8 *a, *b, *ipiv; mem_buff = malloc(N*N*sizeof(@ftyp@) + N*NRHS*sizeof(@ftyp@) + N*sizeof(fortran_int)); if (!mem_buff) goto error; a = mem_buff; b = a + N*N*sizeof(@ftyp@); ipiv = b + N*NRHS*sizeof(@ftyp@); params->A = a; params->B = b; params->IPIV = (fortran_int*)ipiv; params->N = N; params->NRHS = NRHS; params->LDA = N; params->LDB = N; return 1; error: free(mem_buff); memset(params, 0, sizeof(*params)); return 0; } static inline void release_@lapack_func@(GESV_PARAMS_t *params) { /* memory block base is in A */ free(params->A); memset(params, 0, sizeof(*params)); } static inline fortran_int call_@lapack_func@(GESV_PARAMS_t *params) { fortran_int rv; LAPACK(@lapack_func@)(¶ms->N, ¶ms->NRHS, params->A, ¶ms->LDA, params->IPIV, params->B, ¶ms->LDB, &rv); return rv; } static void @TYPE@_solve(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { GESV_PARAMS_t params; fortran_int n, nrhs; int error_occurred = get_fp_invalid_and_clear(); INIT_OUTER_LOOP_3 n = (fortran_int)dimensions[0]; nrhs = (fortran_int)dimensions[1]; if (init_@lapack_func@(¶ms, n, nrhs)) { LINEARIZE_DATA_t a_in, b_in, r_out; init_linearize_data(&a_in, n, n, steps[1], steps[0]); init_linearize_data(&b_in, nrhs, n, steps[3], steps[2]); init_linearize_data(&r_out, nrhs, n, steps[5], steps[4]); BEGIN_OUTER_LOOP_3 int not_ok; linearize_@TYPE@_matrix(params.A, args[0], &a_in); linearize_@TYPE@_matrix(params.B, args[1], &b_in); not_ok =call_@lapack_func@(¶ms); if (!not_ok) { delinearize_@TYPE@_matrix(args[2], params.B, &r_out); } else { error_occurred = 1; nan_@TYPE@_matrix(args[2], &r_out); } END_OUTER_LOOP release_@lapack_func@(¶ms); } set_fp_invalid_or_clear(error_occurred); } static void @TYPE@_solve1(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { GESV_PARAMS_t params; int error_occurred = get_fp_invalid_and_clear(); fortran_int n; INIT_OUTER_LOOP_3 n = (fortran_int)dimensions[0]; if (init_@lapack_func@(¶ms, n, 1)) { LINEARIZE_DATA_t a_in, b_in, r_out; init_linearize_data(&a_in, n, n, steps[1], steps[0]); init_linearize_data(&b_in, 1, n, 1, steps[2]); init_linearize_data(&r_out, 1, n, 1, steps[3]); BEGIN_OUTER_LOOP_3 int not_ok; linearize_@TYPE@_matrix(params.A, args[0], &a_in); linearize_@TYPE@_matrix(params.B, args[1], &b_in); not_ok = call_@lapack_func@(¶ms); if (!not_ok) { delinearize_@TYPE@_matrix(args[2], params.B, &r_out); } else { error_occurred = 1; nan_@TYPE@_matrix(args[2], &r_out); } END_OUTER_LOOP release_@lapack_func@(¶ms); } set_fp_invalid_or_clear(error_occurred); } static void @TYPE@_inv(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { GESV_PARAMS_t params; fortran_int n; int error_occurred = get_fp_invalid_and_clear(); INIT_OUTER_LOOP_2 n = (fortran_int)dimensions[0]; if (init_@lapack_func@(¶ms, n, n)) { LINEARIZE_DATA_t a_in, r_out; init_linearize_data(&a_in, n, n, steps[1], steps[0]); init_linearize_data(&r_out, n, n, steps[3], steps[2]); BEGIN_OUTER_LOOP_2 int not_ok; linearize_@TYPE@_matrix(params.A, args[0], &a_in); identity_@TYPE@_matrix(params.B, n); not_ok = call_@lapack_func@(¶ms); if (!not_ok) { delinearize_@TYPE@_matrix(args[1], params.B, &r_out); } else { error_occurred = 1; nan_@TYPE@_matrix(args[1], &r_out); } END_OUTER_LOOP release_@lapack_func@(¶ms); } set_fp_invalid_or_clear(error_occurred); } /**end repeat**/ /* -------------------------------------------------------------------------- */ /* Cholesky decomposition */ typedef struct potr_params_struct { void *A; fortran_int N; fortran_int LDA; char UPLO; } POTR_PARAMS_t; /**begin repeat #TYPE=FLOAT,DOUBLE,CFLOAT,CDOUBLE# #ftyp=fortran_real, fortran_doublereal, fortran_complex, fortran_doublecomplex# #lapack_func=spotrf,dpotrf,cpotrf,zpotrf# */ static inline int init_@lapack_func@(POTR_PARAMS_t *params, char UPLO, fortran_int N) { npy_uint8 *mem_buff = NULL; npy_uint8 *a; mem_buff = malloc(N*N*sizeof(@ftyp@)); if (!mem_buff) goto error; a = mem_buff; params->A = a; params->N = N; params->LDA = N; params->UPLO = UPLO; return 1; error: free(mem_buff); memset(params, 0, sizeof(*params)); return 0; } static inline void release_@lapack_func@(POTR_PARAMS_t *params) { /* memory block base in A */ free(params->A); memset(params, 0, sizeof(*params)); } static inline fortran_int call_@lapack_func@(POTR_PARAMS_t *params) { fortran_int rv; LAPACK(@lapack_func@)(¶ms->UPLO, ¶ms->N, params->A, ¶ms->LDA, &rv); return rv; } static void @TYPE@_cholesky(char uplo, char **args, npy_intp *dimensions, npy_intp *steps) { POTR_PARAMS_t params; int error_occurred = get_fp_invalid_and_clear(); fortran_int n; INIT_OUTER_LOOP_2 assert(uplo == 'L'); n = (fortran_int)dimensions[0]; if (init_@lapack_func@(¶ms, uplo, n)) { LINEARIZE_DATA_t a_in, r_out; init_linearize_data(&a_in, n, n, steps[1], steps[0]); init_linearize_data(&r_out, n, n, steps[3], steps[2]); BEGIN_OUTER_LOOP_2 int not_ok; linearize_@TYPE@_matrix(params.A, args[0], &a_in); not_ok = call_@lapack_func@(¶ms); if (!not_ok) { triu_@TYPE@_matrix(params.A, params.N); delinearize_@TYPE@_matrix(args[1], params.A, &r_out); } else { error_occurred = 1; nan_@TYPE@_matrix(args[1], &r_out); } END_OUTER_LOOP release_@lapack_func@(¶ms); } set_fp_invalid_or_clear(error_occurred); } static void @TYPE@_cholesky_lo(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { @TYPE@_cholesky('L', args, dimensions, steps); } /**end repeat**/ /* -------------------------------------------------------------------------- */ /* eig family */ typedef struct geev_params_struct { void *A; void *WR; /* RWORK in complex versions, REAL W buffer for (sd)geev*/ void *WI; void *VLR; /* REAL VL buffers for _geev where _ is s, d */ void *VRR; /* REAL VR buffers for _geev hwere _ is s, d */ void *WORK; void *W; /* final w */ void *VL; /* final vl */ void *VR; /* final vr */ fortran_int N; fortran_int LDA; fortran_int LDVL; fortran_int LDVR; fortran_int LWORK; char JOBVL; char JOBVR; } GEEV_PARAMS_t; static inline void dump_geev_params(const char *name, GEEV_PARAMS_t* params) { TRACE_TXT("\n%s\n" "\t%10s: %p\n"\ "\t%10s: %p\n"\ "\t%10s: %p\n"\ "\t%10s: %p\n"\ "\t%10s: %p\n"\ "\t%10s: %p\n"\ "\t%10s: %p\n"\ "\t%10s: %p\n"\ "\t%10s: %p\n"\ "\t%10s: %d\n"\ "\t%10s: %d\n"\ "\t%10s: %d\n"\ "\t%10s: %d\n"\ "\t%10s: %d\n"\ "\t%10s: %c\n"\ "\t%10s: %c\n", name, "A", params->A, "WR", params->WR, "WI", params->WI, "VLR", params->VLR, "VRR", params->VRR, "WORK", params->WORK, "W", params->W, "VL", params->VL, "VR", params->VR, "N", (int)params->N, "LDA", (int)params->LDA, "LDVL", (int)params->LDVL, "LDVR", (int)params->LDVR, "LWORK", (int)params->LWORK, "JOBVL", params->JOBVL, "JOBVR", params->JOBVR); } /**begin repeat #TYPE=FLOAT,DOUBLE# #CTYPE=CFLOAT,CDOUBLE# #typ=float,double# #complextyp=COMPLEX_t,DOUBLECOMPLEX_t# #lapack_func=sgeev,dgeev# #zero=0.0f,0.0# */ static inline int init_@lapack_func@(GEEV_PARAMS_t *params, char jobvl, char jobvr, fortran_int n) { npy_uint8 *mem_buff=NULL; npy_uint8 *mem_buff2=NULL; npy_uint8 *a, *wr, *wi, *vlr, *vrr, *work, *w, *vl, *vr; size_t a_size = n*n*sizeof(@typ@); size_t wr_size = n*sizeof(@typ@); size_t wi_size = n*sizeof(@typ@); size_t vlr_size = jobvl=='V' ? n*n*sizeof(@typ@) : 0; size_t vrr_size = jobvr=='V' ? n*n*sizeof(@typ@) : 0; size_t w_size = wr_size*2; size_t vl_size = vlr_size*2; size_t vr_size = vrr_size*2; size_t work_count = 0; @typ@ work_size_query; fortran_int do_size_query = -1; fortran_int rv; /* allocate data for known sizes (all but work) */ mem_buff = malloc(a_size + wr_size + wi_size + vlr_size + vrr_size + w_size + vl_size + vr_size); if (!mem_buff) goto error; a = mem_buff; wr = a + a_size; wi = wr + wr_size; vlr = wi + wi_size; vrr = vlr + vlr_size; w = vrr + vrr_size; vl = w + w_size; vr = vl + vl_size; LAPACK(@lapack_func@)(&jobvl, &jobvr, &n, (void *)a, &n, (void *)wr, (void *)wi, (void *)vl, &n, (void *)vr, &n, &work_size_query, &do_size_query, &rv); if (0 != rv) goto error; work_count = (size_t)work_size_query; mem_buff2 = malloc(work_count*sizeof(@typ@)); if (!mem_buff2) goto error; work = mem_buff2; params->A = a; params->WR = wr; params->WI = wi; params->VLR = vlr; params->VRR = vrr; params->WORK = work; params->W = w; params->VL = vl; params->VR = vr; params->N = n; params->LDA = n; params->LDVL = n; params->LDVR = n; params->LWORK = (fortran_int)work_count; params->JOBVL = jobvl; params->JOBVR = jobvr; return 1; error: free(mem_buff2); free(mem_buff); memset(params, 0, sizeof(*params)); return 0; } static inline fortran_int call_@lapack_func@(GEEV_PARAMS_t* params) { fortran_int rv; LAPACK(@lapack_func@)(¶ms->JOBVL, ¶ms->JOBVR, ¶ms->N, params->A, ¶ms->LDA, params->WR, params->WI, params->VLR, ¶ms->LDVL, params->VRR, ¶ms->LDVR, params->WORK, ¶ms->LWORK, &rv); return rv; } static inline void mk_@TYPE@_complex_array_from_real(@complextyp@ *c, const @typ@ *re, size_t n) { size_t iter; for (iter = 0; iter < n; ++iter) { c[iter].array[0] = re[iter]; c[iter].array[1] = @zero@; } } static inline void mk_@TYPE@_complex_array(@complextyp@ *c, const @typ@ *re, const @typ@ *im, size_t n) { size_t iter; for (iter = 0; iter < n; ++iter) { c[iter].array[0] = re[iter]; c[iter].array[1] = im[iter]; } } static inline void mk_@TYPE@_complex_array_conjugate_pair(@complextyp@ *c, const @typ@ *r, size_t n) { size_t iter; for (iter = 0; iter < n; ++iter) { @typ@ re = r[iter]; @typ@ im = r[iter+n]; c[iter].array[0] = re; c[iter].array[1] = im; c[iter+n].array[0] = re; c[iter+n].array[1] = -im; } } /* * make the complex eigenvectors from the real array produced by sgeev/zgeev. * c is the array where the results will be left. * r is the source array of reals produced by sgeev/zgeev * i is the eigenvalue imaginary part produced by sgeev/zgeev * n is so that the order of the matrix is n by n */ static inline void mk_@lapack_func@_complex_eigenvectors(@complextyp@ *c, const @typ@ *r, const @typ@ *i, size_t n) { size_t iter = 0; while (iter < n) { if (i[iter] == @zero@) { /* eigenvalue was real, eigenvectors as well... */ mk_@TYPE@_complex_array_from_real(c, r, n); c += n; r += n; iter ++; } else { /* eigenvalue was complex, generate a pair of eigenvectors */ mk_@TYPE@_complex_array_conjugate_pair(c, r, n); c += 2*n; r += 2*n; iter += 2; } } } static inline void process_@lapack_func@_results(GEEV_PARAMS_t *params) { /* REAL versions of geev need the results to be translated * into complex versions. This is the way to deal with imaginary * results. In our gufuncs we will always return complex arrays! */ mk_@TYPE@_complex_array(params->W, params->WR, params->WI, params->N); /* handle the eigenvectors */ if ('V' == params->JOBVL) { mk_@lapack_func@_complex_eigenvectors(params->VL, params->VLR, params->WI, params->N); } if ('V' == params->JOBVR) { mk_@lapack_func@_complex_eigenvectors(params->VR, params->VRR, params->WI, params->N); } } /**end repeat**/ /**begin repeat #TYPE=CFLOAT,CDOUBLE# #typ=COMPLEX_t,DOUBLECOMPLEX_t# #ftyp=fortran_complex,fortran_doublecomplex# #realtyp=float,double# #lapack_func=cgeev,zgeev# */ static inline int init_@lapack_func@(GEEV_PARAMS_t* params, char jobvl, char jobvr, fortran_int n) { npy_uint8 *mem_buff = NULL; npy_uint8 *mem_buff2 = NULL; npy_uint8 *a, *w, *vl, *vr, *work, *rwork; size_t a_size = n*n*sizeof(@ftyp@); size_t w_size = n*sizeof(@ftyp@); size_t vl_size = jobvl=='V'? n*n*sizeof(@ftyp@) : 0; size_t vr_size = jobvr=='V'? n*n*sizeof(@ftyp@) : 0; size_t rwork_size = 2*n*sizeof(@realtyp@); size_t work_count = 0; @typ@ work_size_query; fortran_int do_size_query = -1; fortran_int rv; size_t total_size = a_size + w_size + vl_size + vr_size + rwork_size; mem_buff = malloc(total_size); if (!mem_buff) goto error; a = mem_buff; w = a + a_size; vl = w + w_size; vr = vl + vl_size; rwork = vr + vr_size; LAPACK(@lapack_func@)(&jobvl, &jobvr, &n, (void *)a, &n, (void *)w, (void *)vl, &n, (void *)vr, &n, (void *)&work_size_query, &do_size_query, (void *)rwork, &rv); if (0 != rv) goto error; work_count = (size_t) work_size_query.array[0]; mem_buff2 = malloc(work_count*sizeof(@ftyp@)); if (!mem_buff2) goto error; work = mem_buff2; params->A = a; params->WR = rwork; params->WI = NULL; params->VLR = NULL; params->VRR = NULL; params->VL = vl; params->VR = vr; params->WORK = work; params->W = w; params->N = n; params->LDA = n; params->LDVL = n; params->LDVR = n; params->LWORK = (fortran_int)work_count; params->JOBVL = jobvl; params->JOBVR = jobvr; return 1; error: free(mem_buff2); free(mem_buff); memset(params, 0, sizeof(*params)); return 0; } static inline fortran_int call_@lapack_func@(GEEV_PARAMS_t* params) { fortran_int rv; LAPACK(@lapack_func@)(¶ms->JOBVL, ¶ms->JOBVR, ¶ms->N, params->A, ¶ms->LDA, params->W, params->VL, ¶ms->LDVL, params->VR, ¶ms->LDVR, params->WORK, ¶ms->LWORK, params->WR, /* actually RWORK */ &rv); return rv; } static inline void process_@lapack_func@_results(GEEV_PARAMS_t *NPY_UNUSED(params)) { /* nothing to do here, complex versions are ready to copy out */ } /**end repeat**/ /**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# */ static inline void release_@lapack_func@(GEEV_PARAMS_t *params) { free(params->WORK); free(params->A); memset(params, 0, sizeof(*params)); } static inline void @TYPE@_eig_wrapper(char JOBVL, char JOBVR, char**args, npy_intp* dimensions, npy_intp* steps) { ptrdiff_t outer_steps[4]; size_t iter; size_t outer_dim = *dimensions++; size_t op_count = 2; int error_occurred = get_fp_invalid_and_clear(); GEEV_PARAMS_t geev_params; assert(JOBVL == 'N'); STACK_TRACE; op_count += 'V'==JOBVL?1:0; op_count += 'V'==JOBVR?1:0; for (iter=0; iter < op_count; ++iter) { outer_steps[iter] = (ptrdiff_t) steps[iter]; } steps += op_count; if (init_@lapack_func@(&geev_params, JOBVL, JOBVR, (fortran_int)dimensions[0])) { LINEARIZE_DATA_t a_in; LINEARIZE_DATA_t w_out; LINEARIZE_DATA_t vl_out; LINEARIZE_DATA_t vr_out; init_linearize_data(&a_in, geev_params.N, geev_params.N, steps[1], steps[0]); steps += 2; init_linearize_data(&w_out, 1, geev_params.N, 0, steps[0]); steps += 1; if ('V' == geev_params.JOBVL) { init_linearize_data(&vl_out, geev_params.N, geev_params.N, steps[1], steps[0]); steps += 2; } if ('V' == geev_params.JOBVR) { init_linearize_data(&vr_out, geev_params.N, geev_params.N, steps[1], steps[0]); } for (iter = 0; iter < outer_dim; ++iter) { int not_ok; char **arg_iter = args; /* copy the matrix in */ linearize_@TYPE@_matrix(geev_params.A, *arg_iter++, &a_in); not_ok = call_@lapack_func@(&geev_params); if (!not_ok) { process_@lapack_func@_results(&geev_params); delinearize_@COMPLEXTYPE@_matrix(*arg_iter++, geev_params.W, &w_out); if ('V' == geev_params.JOBVL) delinearize_@COMPLEXTYPE@_matrix(*arg_iter++, geev_params.VL, &vl_out); if ('V' == geev_params.JOBVR) delinearize_@COMPLEXTYPE@_matrix(*arg_iter++, geev_params.VR, &vr_out); } else { /* geev failed */ error_occurred = 1; nan_@COMPLEXTYPE@_matrix(*arg_iter++, &w_out); if ('V' == geev_params.JOBVL) nan_@COMPLEXTYPE@_matrix(*arg_iter++, &vl_out); if ('V' == geev_params.JOBVR) nan_@COMPLEXTYPE@_matrix(*arg_iter++, &vr_out); } update_pointers((npy_uint8**)args, outer_steps, op_count); } release_@lapack_func@(&geev_params); } set_fp_invalid_or_clear(error_occurred); } static void @TYPE@_eig(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { @TYPE@_eig_wrapper('N', 'V', args, dimensions, steps); } static void @TYPE@_eigvals(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { @TYPE@_eig_wrapper('N', 'N', args, dimensions, steps); } /**end repeat**/ /* -------------------------------------------------------------------------- */ /* singular value decomposition */ typedef struct gessd_params_struct { void *A; void *S; void *U; void *VT; void *WORK; void *RWORK; void *IWORK; fortran_int M; fortran_int N; fortran_int LDA; fortran_int LDU; fortran_int LDVT; fortran_int LWORK; char JOBZ; } GESDD_PARAMS_t; static inline void dump_gesdd_params(const char *name, GESDD_PARAMS_t *params) { TRACE_TXT("\n%s:\n"\ "%14s: %18p\n"\ "%14s: %18p\n"\ "%14s: %18p\n"\ "%14s: %18p\n"\ "%14s: %18p\n"\ "%14s: %18p\n"\ "%14s: %18p\n"\ "%14s: %18d\n"\ "%14s: %18d\n"\ "%14s: %18d\n"\ "%14s: %18d\n"\ "%14s: %18d\n"\ "%14s: %18d\n"\ "%14s: %15c'%c'\n", name, "A", params->A, "S", params->S, "U", params->U, "VT", params->VT, "WORK", params->WORK, "RWORK", params->RWORK, "IWORK", params->IWORK, "M", (int)params->M, "N", (int)params->N, "LDA", (int)params->LDA, "LDU", (int)params->LDU, "LDVT", (int)params->LDVT, "LWORK", (int)params->LWORK, "JOBZ", ' ',params->JOBZ); } static inline int compute_urows_vtcolumns(char jobz, fortran_int m, fortran_int n, fortran_int *urows, fortran_int *vtcolumns) { fortran_int min_m_n = mM = m; params->N = n; params->A = a; params->S = s; params->U = u; params->VT = vt; params->WORK = work; params->RWORK = NULL; params->IWORK = iwork; params->M = m; params->N = n; params->LDA = m; params->LDU = m; params->LDVT = vt_column_count; params->LWORK = work_count; params->JOBZ = jobz; return 1; error: TRACE_TXT("%s failed init\n", __FUNCTION__); free(mem_buff); free(mem_buff2); memset(params, 0, sizeof(*params)); return 0; } static inline fortran_int call_@lapack_func@(GESDD_PARAMS_t *params) { fortran_int rv; LAPACK(@lapack_func@)(¶ms->JOBZ, ¶ms->M, ¶ms->N, params->A, ¶ms->LDA, params->S, params->U, ¶ms->LDU, params->VT, ¶ms->LDVT, params->WORK, ¶ms->LWORK, params->IWORK, &rv); return rv; } /**end repeat**/ /**begin repeat #TYPE=CFLOAT,CDOUBLE# #ftyp=fortran_complex,fortran_doublecomplex# #frealtyp=fortran_real,fortran_doublereal# #typ=COMPLEX_t,DOUBLECOMPLEX_t# #lapack_func=cgesdd,zgesdd# */ static inline int init_@lapack_func@(GESDD_PARAMS_t *params, char jobz, fortran_int m, fortran_int n) { npy_uint8 *mem_buff = NULL, *mem_buff2 = NULL; npy_uint8 *a,*s, *u, *vt, *work, *rwork, *iwork; size_t a_size, s_size, u_size, vt_size, work_size, rwork_size, iwork_size; fortran_int u_row_count, vt_column_count, work_count; fortran_int min_m_n = marray[0]; work_size = (size_t)work_count * sizeof(@ftyp@); } mem_buff2 = malloc(work_size); if (!mem_buff2) goto error; work = mem_buff2; params->A = a; params->S = s; params->U = u; params->VT = vt; params->WORK = work; params->RWORK = rwork; params->IWORK = iwork; params->M = m; params->N = n; params->LDA = m; params->LDU = m; params->LDVT = vt_column_count; params->LWORK = work_count; params->JOBZ = jobz; return 1; error: TRACE_TXT("%s failed init\n", __FUNCTION__); free(mem_buff2); free(mem_buff); memset(params, 0, sizeof(*params)); return 0; } static inline fortran_int call_@lapack_func@(GESDD_PARAMS_t *params) { fortran_int rv; LAPACK(@lapack_func@)(¶ms->JOBZ, ¶ms->M, ¶ms->N, params->A, ¶ms->LDA, params->S, params->U, ¶ms->LDU, params->VT, ¶ms->LDVT, params->WORK, ¶ms->LWORK, params->RWORK, params->IWORK, &rv); return rv; } /**end repeat**/ /**begin repeat #TYPE=FLOAT,DOUBLE,CFLOAT,CDOUBLE# #REALTYPE=FLOAT,DOUBLE,FLOAT,DOUBLE# #lapack_func=sgesdd,dgesdd,cgesdd,zgesdd# */ static inline void release_@lapack_func@(GESDD_PARAMS_t* params) { /* A and WORK contain allocated blocks */ free(params->A); free(params->WORK); memset(params, 0, sizeof(*params)); } static inline void @TYPE@_svd_wrapper(char JOBZ, char **args, npy_intp* dimensions, npy_intp* steps) { ptrdiff_t outer_steps[4]; int error_occurred = get_fp_invalid_and_clear(); size_t iter; size_t outer_dim = *dimensions++; size_t op_count = (JOBZ=='N')?2:4; GESDD_PARAMS_t params; for (iter=0; iter < op_count; ++iter) { outer_steps[iter] = (ptrdiff_t) steps[iter]; } steps += op_count; if (init_@lapack_func@(¶ms, JOBZ, (fortran_int)dimensions[0], (fortran_int)dimensions[1])) { LINEARIZE_DATA_t a_in, u_out, s_out, v_out; init_linearize_data(&a_in, params.N, params.M, steps[1], steps[0]); if ('N' == params.JOBZ) { /* only the singular values are wanted */ fortran_int min_m_n = params.M < params.N? params.M : params.N; init_linearize_data(&s_out, 1, min_m_n, 0, steps[2]); } else { fortran_int u_columns, v_rows; fortran_int min_m_n = params.M < params.N? params.M : params.N; if ('S' == params.JOBZ) { u_columns = min_m_n; v_rows = min_m_n; } else { u_columns = params.M; v_rows = params.N; } init_linearize_data(&u_out, u_columns, params.M, steps[3], steps[2]); init_linearize_data(&s_out, 1, min_m_n, 0, steps[4]); init_linearize_data(&v_out, params.N, v_rows, steps[6], steps[5]); } for (iter = 0; iter < outer_dim; ++iter) { int not_ok; /* copy the matrix in */ linearize_@TYPE@_matrix(params.A, args[0], &a_in); not_ok = call_@lapack_func@(¶ms); if (!not_ok) { if ('N' == params.JOBZ) { delinearize_@REALTYPE@_matrix(args[1], params.S, &s_out); } else { delinearize_@TYPE@_matrix(args[1], params.U, &u_out); delinearize_@REALTYPE@_matrix(args[2], params.S, &s_out); delinearize_@TYPE@_matrix(args[3], params.VT, &v_out); } } else { error_occurred = 1; if ('N' == params.JOBZ) { nan_@REALTYPE@_matrix(args[1], &s_out); } else { nan_@TYPE@_matrix(args[1], &u_out); nan_@REALTYPE@_matrix(args[2], &s_out); nan_@TYPE@_matrix(args[3], &v_out); } } update_pointers((npy_uint8**)args, outer_steps, op_count); } release_@lapack_func@(¶ms); } set_fp_invalid_or_clear(error_occurred); } /**end repeat*/ /* svd gufunc entry points */ /**begin repeat #TYPE=FLOAT,DOUBLE,CFLOAT,CDOUBLE# */ static void @TYPE@_svd_N(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { @TYPE@_svd_wrapper('N', args, dimensions, steps); } static void @TYPE@_svd_S(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { @TYPE@_svd_wrapper('S', args, dimensions, steps); } static void @TYPE@_svd_A(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { @TYPE@_svd_wrapper('A', args, dimensions, steps); } /**end repeat**/ #pragma GCC diagnostic pop /* -------------------------------------------------------------------------- */ /* gufunc registration */ static void *array_of_nulls[] = { (void *)NULL, (void *)NULL, (void *)NULL, (void *)NULL, (void *)NULL, (void *)NULL, (void *)NULL, (void *)NULL, (void *)NULL, (void *)NULL, (void *)NULL, (void *)NULL, (void *)NULL, (void *)NULL, (void *)NULL, (void *)NULL }; #define FUNC_ARRAY_NAME(NAME) NAME ## _funcs #define GUFUNC_FUNC_ARRAY_REAL(NAME) \ static PyUFuncGenericFunction \ FUNC_ARRAY_NAME(NAME)[] = { \ FLOAT_ ## NAME, \ DOUBLE_ ## NAME \ } #define GUFUNC_FUNC_ARRAY_REAL_COMPLEX(NAME) \ static PyUFuncGenericFunction \ FUNC_ARRAY_NAME(NAME)[] = { \ FLOAT_ ## NAME, \ DOUBLE_ ## NAME, \ CFLOAT_ ## NAME, \ CDOUBLE_ ## NAME \ } /* There are problems with eig in complex single precision. * That kernel is disabled */ #define GUFUNC_FUNC_ARRAY_EIG(NAME) \ static PyUFuncGenericFunction \ FUNC_ARRAY_NAME(NAME)[] = { \ FLOAT_ ## NAME, \ DOUBLE_ ## NAME, \ CDOUBLE_ ## NAME \ } GUFUNC_FUNC_ARRAY_REAL_COMPLEX(slogdet); GUFUNC_FUNC_ARRAY_REAL_COMPLEX(det); GUFUNC_FUNC_ARRAY_REAL_COMPLEX(eighlo); GUFUNC_FUNC_ARRAY_REAL_COMPLEX(eighup); GUFUNC_FUNC_ARRAY_REAL_COMPLEX(eigvalshlo); GUFUNC_FUNC_ARRAY_REAL_COMPLEX(eigvalshup); GUFUNC_FUNC_ARRAY_REAL_COMPLEX(solve); GUFUNC_FUNC_ARRAY_REAL_COMPLEX(solve1); GUFUNC_FUNC_ARRAY_REAL_COMPLEX(inv); GUFUNC_FUNC_ARRAY_REAL_COMPLEX(cholesky_lo); GUFUNC_FUNC_ARRAY_REAL_COMPLEX(svd_N); GUFUNC_FUNC_ARRAY_REAL_COMPLEX(svd_S); GUFUNC_FUNC_ARRAY_REAL_COMPLEX(svd_A); GUFUNC_FUNC_ARRAY_EIG(eig); GUFUNC_FUNC_ARRAY_EIG(eigvals); static char equal_2_types[] = { NPY_FLOAT, NPY_FLOAT, NPY_DOUBLE, NPY_DOUBLE, NPY_CFLOAT, NPY_CFLOAT, NPY_CDOUBLE, NPY_CDOUBLE }; static char equal_3_types[] = { NPY_FLOAT, NPY_FLOAT, NPY_FLOAT, NPY_DOUBLE, NPY_DOUBLE, NPY_DOUBLE, NPY_CFLOAT, NPY_CFLOAT, NPY_CFLOAT, 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, NPY_DOUBLE, NPY_DOUBLE, NPY_DOUBLE, NPY_CFLOAT, NPY_CFLOAT, NPY_FLOAT, NPY_CDOUBLE, NPY_CDOUBLE, NPY_DOUBLE }; static char eigh_types[] = { NPY_FLOAT, NPY_FLOAT, NPY_FLOAT, NPY_DOUBLE, NPY_DOUBLE, NPY_DOUBLE, NPY_CFLOAT, NPY_FLOAT, NPY_CFLOAT, NPY_CDOUBLE, NPY_DOUBLE, NPY_CDOUBLE }; static char eighvals_types[] = { NPY_FLOAT, NPY_FLOAT, NPY_DOUBLE, NPY_DOUBLE, NPY_CFLOAT, NPY_FLOAT, NPY_CDOUBLE, NPY_DOUBLE }; static char eig_types[] = { NPY_FLOAT, NPY_CFLOAT, NPY_CFLOAT, NPY_DOUBLE, NPY_CDOUBLE, NPY_CDOUBLE, NPY_CDOUBLE, NPY_CDOUBLE, NPY_CDOUBLE }; static char eigvals_types[] = { NPY_FLOAT, NPY_CFLOAT, NPY_DOUBLE, NPY_CDOUBLE, NPY_CDOUBLE, NPY_CDOUBLE }; static char svd_1_1_types[] = { NPY_FLOAT, NPY_FLOAT, NPY_DOUBLE, NPY_DOUBLE, NPY_CFLOAT, NPY_FLOAT, NPY_CDOUBLE, NPY_DOUBLE }; static char svd_1_3_types[] = { NPY_FLOAT, NPY_FLOAT, NPY_FLOAT, NPY_FLOAT, NPY_DOUBLE, NPY_DOUBLE, NPY_DOUBLE, NPY_DOUBLE, NPY_CFLOAT, NPY_CFLOAT, NPY_FLOAT, NPY_CFLOAT, NPY_CDOUBLE, NPY_CDOUBLE, NPY_DOUBLE, NPY_CDOUBLE }; typedef struct gufunc_descriptor_struct { char *name; char *signature; char *doc; int ntypes; int nin; int nout; PyUFuncGenericFunction *funcs; char *types; } GUFUNC_DESCRIPTOR_t; GUFUNC_DESCRIPTOR_t gufunc_descriptors [] = { { "slogdet", "(m,m)->(),()", "slogdet on the last two dimensions and broadcast on the rest. \n"\ "Results in two arrays, one with sign and the other with log of the"\ " determinants. \n"\ " \"(m,m)->(),()\" \n", 4, 1, 2, FUNC_ARRAY_NAME(slogdet), slogdet_types }, { "det", "(m,m)->()", "det of the last two dimensions and broadcast on the rest. \n"\ " \"(m,m)->()\" \n", 4, 1, 1, FUNC_ARRAY_NAME(det), equal_2_types }, { "eigh_lo", "(m,m)->(m),(m,m)", "eigh on the last two dimension and broadcast to the rest, using"\ " lower triangle \n"\ "Results in a vector of eigenvalues and a matrix with the"\ "eigenvectors. \n"\ " \"(m,m)->(m),(m,m)\" \n", 4, 1, 2, FUNC_ARRAY_NAME(eighlo), eigh_types }, { "eigh_up", "(m,m)->(m),(m,m)", "eigh on the last two dimension and broadcast to the rest, using"\ " upper triangle. \n"\ "Results in a vector of eigenvalues and a matrix with the"\ " eigenvectors. \n"\ " \"(m,m)->(m),(m,m)\" \n", 4, 1, 2, FUNC_ARRAY_NAME(eighup), eigh_types }, { "eigvalsh_lo", "(m,m)->(m)", "eigh on the last two dimension and broadcast to the rest, using"\ " lower triangle. \n"\ "Results in a vector of eigenvalues and a matrix with the"\ "eigenvectors. \n"\ " \"(m,m)->(m)\" \n", 4, 1, 1, FUNC_ARRAY_NAME(eigvalshlo), eighvals_types }, { "eigvalsh_up", "(m,m)->(m)", "eigvalsh on the last two dimension and broadcast to the rest,"\ " using upper triangle. \n"\ "Results in a vector of eigenvalues and a matrix with the"\ "eigenvectors.\n"\ " \"(m,m)->(m)\" \n", 4, 1, 1, FUNC_ARRAY_NAME(eigvalshup), eighvals_types }, { "solve", "(m,m),(m,n)->(m,n)", "solve the system a x = b, on the last two dimensions, broadcast"\ " to the rest. \n"\ "Results in a matrices with the solutions. \n"\ " \"(m,m),(m,n)->(m,n)\" \n", 4, 2, 1, FUNC_ARRAY_NAME(solve), equal_3_types }, { "solve1", "(m,m),(m)->(m)", "solve the system a x = b, for b being a vector, broadcast in"\ " the outer dimensions. \n"\ "Results in vectors with the solutions. \n"\ " \"(m,m),(m)->(m)\" \n", 4,2,1, FUNC_ARRAY_NAME(solve1), equal_3_types }, { "inv", "(m,m)->(m,m)", "compute the inverse of the last two dimensions and broadcast"\ " to the rest. \n"\ "Results in the inverse matrices. \n"\ " \"(m,m)->(m,m)\" \n", 4,1,1, FUNC_ARRAY_NAME(inv), equal_2_types }, { "cholesky_lo", "(m,m)->(m,m)", "cholesky decomposition of hermitian positive-definite matrices. \n"\ "Broadcast to all outer dimensions. \n"\ " \"(m,m)->(m,m)\" \n", 4, 1, 1, FUNC_ARRAY_NAME(cholesky_lo), equal_2_types }, { "svd_m", "(m,n)->(m)", "svd when n>=m. ", 4, 1, 1, FUNC_ARRAY_NAME(svd_N), svd_1_1_types }, { "svd_n", "(m,n)->(n)", "svd when n<=m", 4, 1, 1, FUNC_ARRAY_NAME(svd_N), svd_1_1_types }, { "svd_m_s", "(m,n)->(m,m),(m),(m,n)", "svd when m>=n", 4, 1, 3, FUNC_ARRAY_NAME(svd_S), svd_1_3_types }, { "svd_n_s", "(m,n)->(m,n),(n),(n,n)", "svd when m>=n", 4, 1, 3, FUNC_ARRAY_NAME(svd_S), svd_1_3_types }, { "svd_m_f", "(m,n)->(m,m),(m),(n,n)", "svd when m>=n", 4, 1, 3, FUNC_ARRAY_NAME(svd_A), svd_1_3_types }, { "svd_n_f", "(m,n)->(m,m),(n),(n,n)", "svd when m>=n", 4, 1, 3, FUNC_ARRAY_NAME(svd_A), svd_1_3_types }, { "eig", "(m,m)->(m),(m,m)", "eig on the last two dimension and broadcast to the rest. \n"\ "Results in a vector with the eigenvalues and a matrix with the"\ " eigenvectors. \n"\ " \"(m,m)->(m),(m,m)\" \n", 3, 1, 2, FUNC_ARRAY_NAME(eig), eig_types }, { "eigvals", "(m,m)->(m)", "eigvals on the last two dimension and broadcast to the rest. \n"\ "Results in a vector of eigenvalues. \n"\ " \"(m,m)->(m),(m,m)\" \n", 3, 1, 1, FUNC_ARRAY_NAME(eigvals), eigvals_types }, }; static void addUfuncs(PyObject *dictionary) { PyObject *f; int i; const int gufunc_count = sizeof(gufunc_descriptors)/ sizeof(gufunc_descriptors[0]); for (i=0; i < gufunc_count; i++) { GUFUNC_DESCRIPTOR_t* d = &gufunc_descriptors[i]; f = PyUFunc_FromFuncAndDataAndSignature(d->funcs, array_of_nulls, d->types, d->ntypes, d->nin, d->nout, PyUFunc_None, d->name, d->doc, 0, d->signature); PyDict_SetItemString(dictionary, d->name, f); #if 0 dump_ufunc_object((PyUFuncObject*) f); #endif Py_DECREF(f); } } /* -------------------------------------------------------------------------- */ /* Module initialization stuff */ static PyMethodDef UMath_LinAlgMethods[] = { {NULL, NULL, 0, NULL} /* Sentinel */ }; #if defined(NPY_PY3K) static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, UMATH_LINALG_MODULE_NAME, NULL, -1, UMath_LinAlgMethods, NULL, NULL, NULL, NULL }; #endif #if defined(NPY_PY3K) #define RETVAL m PyObject *PyInit__umath_linalg(void) #else #define RETVAL PyMODINIT_FUNC init_umath_linalg(void) #endif { PyObject *m; PyObject *d; PyObject *version; init_constants(); #if defined(NPY_PY3K) m = PyModule_Create(&moduledef); #else m = Py_InitModule(UMATH_LINALG_MODULE_NAME, UMath_LinAlgMethods); #endif if (m == NULL) return RETVAL; import_array(); import_ufunc(); d = PyModule_GetDict(m); version = PyString_FromString(umath_linalg_version_string); PyDict_SetItemString(d, "__version__", version); Py_DECREF(version); /* Load the ufunc operators into the module's namespace */ addUfuncs(d); if (PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError, "cannot load _umath_linalg module."); } return RETVAL; } numpy-1.8.2/numpy/setup.py0000664000175100017510000000174512370216243016715 0ustar vagrantvagrant00000000000000#!/usr/bin/env python from __future__ import division, print_function def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('numpy', parent_package, top_path) config.add_subpackage('distutils') config.add_subpackage('testing') config.add_subpackage('f2py') config.add_subpackage('core') config.add_subpackage('lib') config.add_subpackage('oldnumeric') config.add_subpackage('numarray') config.add_subpackage('fft') config.add_subpackage('linalg') config.add_subpackage('random') config.add_subpackage('ma') config.add_subpackage('matrixlib') config.add_subpackage('compat') config.add_subpackage('polynomial') config.add_subpackage('doc') config.add_data_dir('doc') config.add_data_dir('tests') config.make_config_py() # installs __config__.py return config if __name__ == '__main__': print('This is the wrong setup.py file to run') numpy-1.8.2/numpy/tests/0000775000175100017510000000000012371375430016343 5ustar vagrantvagrant00000000000000numpy-1.8.2/numpy/tests/test_ctypeslib.py0000664000175100017510000000764512370216242021760 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function import sys import numpy as np from numpy.ctypeslib import ndpointer, load_library from numpy.distutils.misc_util import get_shared_lib_extension from numpy.testing import * try: cdll = load_library('multiarray', np.core.multiarray.__file__) _HAS_CTYPE = True except ImportError: _HAS_CTYPE = False class TestLoadLibrary(TestCase): @dec.skipif(not _HAS_CTYPE, "ctypes not available on this python installation") @dec.knownfailureif(sys.platform=='cygwin', "This test is known to fail on cygwin") def test_basic(self): try: cdll = load_library('multiarray', np.core.multiarray.__file__) except ImportError as e: msg = "ctypes is not available on this python: skipping the test" \ " (import error was: %s)" % str(e) print(msg) @dec.skipif(not _HAS_CTYPE, "ctypes not available on this python installation") @dec.knownfailureif(sys.platform=='cygwin', "This test is known to fail on cygwin") def test_basic2(self): """Regression for #801: load_library with a full library name (including extension) does not work.""" try: try: so = get_shared_lib_extension(is_python_ext=True) cdll = load_library('multiarray%s' % so, np.core.multiarray.__file__) except ImportError: print("No distutils available, skipping test.") except ImportError as e: msg = "ctypes is not available on this python: skipping the test" \ " (import error was: %s)" % str(e) print(msg) class TestNdpointer(TestCase): def test_dtype(self): dt = np.intc p = ndpointer(dtype=dt) self.assertTrue(p.from_param(np.array([1], dt))) dt = 'i4') p = ndpointer(dtype=dt) p.from_param(np.array([1], dt)) self.assertRaises(TypeError, p.from_param, np.array([1], dt.newbyteorder('swap'))) dtnames = ['x', 'y'] dtformats = [np.intc, np.float64] dtdescr = {'names' : dtnames, 'formats' : dtformats} dt = np.dtype(dtdescr) p = ndpointer(dtype=dt) self.assertTrue(p.from_param(np.zeros((10,), dt))) samedt = np.dtype(dtdescr) p = ndpointer(dtype=samedt) self.assertTrue(p.from_param(np.zeros((10,), dt))) dt2 = np.dtype(dtdescr, align=True) if dt.itemsize != dt2.itemsize: self.assertRaises(TypeError, p.from_param, np.zeros((10,), dt2)) else: self.assertTrue(p.from_param(np.zeros((10,), dt2))) def test_ndim(self): p = ndpointer(ndim=0) self.assertTrue(p.from_param(np.array(1))) self.assertRaises(TypeError, p.from_param, np.array([1])) p = ndpointer(ndim=1) self.assertRaises(TypeError, p.from_param, np.array(1)) self.assertTrue(p.from_param(np.array([1]))) p = ndpointer(ndim=2) self.assertTrue(p.from_param(np.array([[1]]))) def test_shape(self): p = ndpointer(shape=(1, 2)) self.assertTrue(p.from_param(np.array([[1, 2]]))) self.assertRaises(TypeError, p.from_param, np.array([[1], [2]])) p = ndpointer(shape=()) self.assertTrue(p.from_param(np.array(1))) def test_flags(self): x = np.array([[1, 2], [3, 4]], order='F') p = ndpointer(flags='FORTRAN') self.assertTrue(p.from_param(x)) p = ndpointer(flags='CONTIGUOUS') self.assertRaises(TypeError, p.from_param, x) p = ndpointer(flags=x.flags.num) self.assertTrue(p.from_param(x)) self.assertRaises(TypeError, p.from_param, np.array([[1, 2], [3, 4]])) if __name__ == "__main__": run_module_suite() numpy-1.8.2/numpy/tests/test_matlib.py0000664000175100017510000000307312370216242021221 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function import numpy as np import numpy.matlib from numpy.testing import assert_array_equal, assert_, run_module_suite def test_empty(): x = np.matlib.empty((2,)) assert_(isinstance(x, np.matrix)) assert_(x.shape, (1, 2)) def test_ones(): assert_array_equal(np.matlib.ones((2, 3)), np.matrix([[ 1., 1., 1.], [ 1., 1., 1.]])) assert_array_equal(np.matlib.ones(2), np.matrix([[ 1., 1.]])) def test_zeros(): assert_array_equal(np.matlib.zeros((2, 3)), np.matrix([[ 0., 0., 0.], [ 0., 0., 0.]])) assert_array_equal(np.matlib.zeros(2), np.matrix([[ 0., 0.]])) def test_identity(): x = np.matlib.identity(2, dtype=np.int) assert_array_equal(x, np.matrix([[1, 0], [0, 1]])) def test_eye(): x = np.matlib.eye(3, k=1, dtype=int) assert_array_equal(x, np.matrix([[ 0, 1, 0], [ 0, 0, 1], [ 0, 0, 0]])) def test_rand(): x = np.matlib.rand(3) # check matrix type, array would have shape (3,) assert_(x.ndim == 2) def test_randn(): x = np.matlib.randn(3) # check matrix type, array would have shape (3,) assert_(x.ndim == 2) def test_repmat(): a1 = np.arange(4) x = np.matlib.repmat(a1, 2, 2) y = np.array([[0, 1, 2, 3, 0, 1, 2, 3], [0, 1, 2, 3, 0, 1, 2, 3]]) assert_array_equal(x, y) if __name__ == "__main__": run_module_suite() numpy-1.8.2/numpy/fft/0000775000175100017510000000000012371375430015760 5ustar vagrantvagrant00000000000000numpy-1.8.2/numpy/fft/helper.py0000664000175100017510000001373212370216243017612 0ustar vagrantvagrant00000000000000""" Discrete Fourier Transforms - helper.py """ from __future__ import division, absolute_import, print_function from numpy.compat import integer_types from numpy.core import ( asarray, concatenate, arange, take, integer, empty ) # Created by Pearu Peterson, September 2002 __all__ = ['fftshift', 'ifftshift', 'fftfreq', 'rfftfreq'] integer_types = integer_types + (integer,) def fftshift(x, axes=None): """ Shift the zero-frequency component to the center of the spectrum. This function swaps half-spaces for all axes listed (defaults to all). Note that ``y[0]`` is the Nyquist component only if ``len(x)`` is even. Parameters ---------- x : array_like Input array. axes : int or shape tuple, optional Axes over which to shift. Default is None, which shifts all axes. Returns ------- y : ndarray The shifted array. See Also -------- ifftshift : The inverse of `fftshift`. Examples -------- >>> freqs = np.fft.fftfreq(10, 0.1) >>> freqs array([ 0., 1., 2., 3., 4., -5., -4., -3., -2., -1.]) >>> np.fft.fftshift(freqs) array([-5., -4., -3., -2., -1., 0., 1., 2., 3., 4.]) Shift the zero-frequency component only along the second axis: >>> freqs = np.fft.fftfreq(9, d=1./9).reshape(3, 3) >>> freqs array([[ 0., 1., 2.], [ 3., 4., -4.], [-3., -2., -1.]]) >>> np.fft.fftshift(freqs, axes=(1,)) array([[ 2., 0., 1.], [-4., 3., 4.], [-1., -3., -2.]]) """ tmp = asarray(x) ndim = len(tmp.shape) if axes is None: axes = list(range(ndim)) elif isinstance(axes, integer_types): axes = (axes,) y = tmp for k in axes: n = tmp.shape[k] p2 = (n+1)//2 mylist = concatenate((arange(p2, n), arange(p2))) y = take(y, mylist, k) return y def ifftshift(x, axes=None): """ The inverse of fftshift. Parameters ---------- x : array_like Input array. axes : int or shape tuple, optional Axes over which to calculate. Defaults to None, which shifts all axes. Returns ------- y : ndarray The shifted array. See Also -------- fftshift : Shift zero-frequency component to the center of the spectrum. Examples -------- >>> freqs = np.fft.fftfreq(9, d=1./9).reshape(3, 3) >>> freqs array([[ 0., 1., 2.], [ 3., 4., -4.], [-3., -2., -1.]]) >>> np.fft.ifftshift(np.fft.fftshift(freqs)) array([[ 0., 1., 2.], [ 3., 4., -4.], [-3., -2., -1.]]) """ tmp = asarray(x) ndim = len(tmp.shape) if axes is None: axes = list(range(ndim)) elif isinstance(axes, integer_types): axes = (axes,) y = tmp for k in axes: n = tmp.shape[k] p2 = n-(n+1)//2 mylist = concatenate((arange(p2, n), arange(p2))) y = take(y, mylist, k) return y def fftfreq(n, d=1.0): """ Return the Discrete Fourier Transform sample frequencies. The returned float array `f` contains the frequency bin centers in cycles per unit of the sample spacing (with zero at the start). For instance, if the sample spacing is in seconds, then the frequency unit is cycles/second. Given a window length `n` and a sample spacing `d`:: f = [0, 1, ..., n/2-1, -n/2, ..., -1] / (d*n) if n is even f = [0, 1, ..., (n-1)/2, -(n-1)/2, ..., -1] / (d*n) if n is odd Parameters ---------- n : int Window length. d : scalar, optional Sample spacing (inverse of the sampling rate). Defaults to 1. Returns ------- f : ndarray Array of length `n` containing the sample frequencies. Examples -------- >>> signal = np.array([-2, 8, 6, 4, 1, 0, 3, 5], dtype=float) >>> fourier = np.fft.fft(signal) >>> n = signal.size >>> timestep = 0.1 >>> freq = np.fft.fftfreq(n, d=timestep) >>> freq array([ 0. , 1.25, 2.5 , 3.75, -5. , -3.75, -2.5 , -1.25]) """ if not isinstance(n, integer_types): raise ValueError("n should be an integer") val = 1.0 / (n * d) results = empty(n, int) N = (n-1)//2 + 1 p1 = arange(0, N, dtype=int) results[:N] = p1 p2 = arange(-(n//2), 0, dtype=int) results[N:] = p2 return results * val #return hstack((arange(0,(n-1)/2 + 1), arange(-(n/2),0))) / (n*d) def rfftfreq(n, d=1.0): """ Return the Discrete Fourier Transform sample frequencies (for usage with rfft, irfft). The returned float array `f` contains the frequency bin centers in cycles per unit of the sample spacing (with zero at the start). For instance, if the sample spacing is in seconds, then the frequency unit is cycles/second. Given a window length `n` and a sample spacing `d`:: f = [0, 1, ..., n/2-1, n/2] / (d*n) if n is even f = [0, 1, ..., (n-1)/2-1, (n-1)/2] / (d*n) if n is odd Unlike `fftfreq` (but like `scipy.fftpack.rfftfreq`) the Nyquist frequency component is considered to be positive. Parameters ---------- n : int Window length. d : scalar, optional Sample spacing (inverse of the sampling rate). Defaults to 1. Returns ------- f : ndarray Array of length ``n//2 + 1`` containing the sample frequencies. Examples -------- >>> signal = np.array([-2, 8, 6, 4, 1, 0, 3, 5, -3, 4], dtype=float) >>> fourier = np.fft.rfft(signal) >>> n = signal.size >>> sample_rate = 100 >>> freq = np.fft.fftfreq(n, d=1./sample_rate) >>> freq array([ 0., 10., 20., 30., 40., -50., -40., -30., -20., -10.]) >>> freq = np.fft.rfftfreq(n, d=1./sample_rate) >>> freq array([ 0., 10., 20., 30., 40., 50.]) """ if not isinstance(n, integer_types): raise ValueError("n should be an integer") val = 1.0/(n*d) N = n//2 + 1 results = arange(0, N, dtype=int) return results * val numpy-1.8.2/numpy/fft/fftpack.h0000664000175100017510000000107112370216242017540 0ustar vagrantvagrant00000000000000/* * This file is part of tela the Tensor Language. * Copyright (c) 1994-1995 Pekka Janhunen */ #ifdef __cplusplus extern "C" { #endif #define DOUBLE #ifdef DOUBLE #define Treal double #else #define Treal float #endif extern void cfftf(int N, Treal data[], const Treal wrk[]); extern void cfftb(int N, Treal data[], const Treal wrk[]); extern void cffti(int N, Treal wrk[]); extern void rfftf(int N, Treal data[], const Treal wrk[]); extern void rfftb(int N, Treal data[], const Treal wrk[]); extern void rffti(int N, Treal wrk[]); #ifdef __cplusplus } #endif numpy-1.8.2/numpy/fft/fftpack.py0000664000175100017510000011603412370216243017750 0ustar vagrantvagrant00000000000000""" Discrete Fourier Transforms Routines in this module: fft(a, n=None, axis=-1) ifft(a, n=None, axis=-1) rfft(a, n=None, axis=-1) irfft(a, n=None, axis=-1) hfft(a, n=None, axis=-1) ihfft(a, n=None, axis=-1) fftn(a, s=None, axes=None) ifftn(a, s=None, axes=None) rfftn(a, s=None, axes=None) irfftn(a, s=None, axes=None) fft2(a, s=None, axes=(-2,-1)) ifft2(a, s=None, axes=(-2, -1)) rfft2(a, s=None, axes=(-2,-1)) irfft2(a, s=None, axes=(-2, -1)) i = inverse transform r = transform of purely real data h = Hermite transform n = n-dimensional transform 2 = 2-dimensional transform (Note: 2D routines are just nD routines with different default behavior.) The underlying code for these functions is an f2c-translated and modified version of the FFTPACK routines. """ from __future__ import division, absolute_import, print_function __all__ = ['fft', 'ifft', 'rfft', 'irfft', 'hfft', 'ihfft', 'rfftn', 'irfftn', 'rfft2', 'irfft2', 'fft2', 'ifft2', 'fftn', 'ifftn'] from numpy.core import asarray, zeros, swapaxes, shape, conjugate, \ take from . import fftpack_lite as fftpack _fft_cache = {} _real_fft_cache = {} def _raw_fft(a, n=None, axis=-1, init_function=fftpack.cffti, work_function=fftpack.cfftf, fft_cache = _fft_cache ): a = asarray(a) if n is None: n = a.shape[axis] if n < 1: raise ValueError("Invalid number of FFT data points (%d) specified." % n) try: # 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) if a.shape[axis] != n: s = list(a.shape) if s[axis] > n: index = [slice(None)]*len(s) index[axis] = slice(0, n) a = a[index] else: index = [slice(None)]*len(s) index[axis] = slice(0, s[axis]) s[axis] = n z = zeros(s, a.dtype.char) z[index] = a a = z if axis != -1: a = swapaxes(a, axis, -1) 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 def fft(a, n=None, axis=-1): """ Compute the one-dimensional discrete Fourier Transform. This function computes the one-dimensional *n*-point discrete Fourier Transform (DFT) with the efficient Fast Fourier Transform (FFT) algorithm [CT]. Parameters ---------- a : array_like Input array, can be complex. n : int, optional Length of the transformed axis of the output. If `n` is smaller than the length of the input, the input is cropped. If it is larger, the input is padded with zeros. If `n` is not given, the length of the input (along the axis specified by `axis`) is used. axis : int, optional Axis over which to compute the FFT. If not given, the last axis is used. Returns ------- out : complex ndarray The truncated or zero-padded input, transformed along the axis indicated by `axis`, or the last one if `axis` is not specified. Raises ------ IndexError if `axes` is larger than the last axis of `a`. See Also -------- numpy.fft : for definition of the DFT and conventions used. ifft : The inverse of `fft`. fft2 : The two-dimensional FFT. fftn : The *n*-dimensional FFT. rfftn : The *n*-dimensional FFT of real input. fftfreq : Frequency bins for given FFT parameters. Notes ----- FFT (Fast Fourier Transform) refers to a way the discrete Fourier Transform (DFT) can be calculated efficiently, by using symmetries in the calculated terms. The symmetry is highest when `n` is a power of 2, and the transform is therefore most efficient for these sizes. The DFT is defined, with the conventions used in this implementation, in the documentation for the `numpy.fft` module. References ---------- .. [CT] Cooley, James W., and John W. Tukey, 1965, "An algorithm for the machine calculation of complex Fourier series," *Math. Comput.* 19: 297-301. Examples -------- >>> np.fft.fft(np.exp(2j * np.pi * np.arange(8) / 8)) array([ -3.44505240e-16 +1.14383329e-17j, 8.00000000e+00 -5.71092652e-15j, 2.33482938e-16 +1.22460635e-16j, 1.64863782e-15 +1.77635684e-15j, 9.95839695e-17 +2.33482938e-16j, 0.00000000e+00 +1.66837030e-15j, 1.14383329e-17 +1.22460635e-16j, -1.64863782e-15 +1.77635684e-15j]) >>> import matplotlib.pyplot as plt >>> t = np.arange(256) >>> sp = np.fft.fft(np.sin(t)) >>> freq = np.fft.fftfreq(t.shape[-1]) >>> plt.plot(freq, sp.real, freq, sp.imag) [, ] >>> plt.show() In this example, real input has an FFT which is Hermitian, i.e., symmetric in the real part and anti-symmetric in the imaginary part, as described in the `numpy.fft` documentation. """ return _raw_fft(a, n, axis, fftpack.cffti, fftpack.cfftf, _fft_cache) def ifft(a, n=None, axis=-1): """ Compute the one-dimensional inverse discrete Fourier Transform. This function computes the inverse of the one-dimensional *n*-point discrete Fourier transform computed by `fft`. In other words, ``ifft(fft(a)) == a`` to within numerical accuracy. For a general description of the algorithm and definitions, see `numpy.fft`. The input should be ordered in the same way as is returned by `fft`, i.e., ``a[0]`` should contain the zero frequency term, ``a[1:n/2+1]`` should contain the positive-frequency terms, and ``a[n/2+1:]`` should contain the negative-frequency terms, in order of decreasingly negative frequency. See `numpy.fft` for details. Parameters ---------- a : array_like Input array, can be complex. n : int, optional Length of the transformed axis of the output. If `n` is smaller than the length of the input, the input is cropped. If it is larger, the input is padded with zeros. If `n` is not given, the length of the input (along the axis specified by `axis`) is used. See notes about padding issues. axis : int, optional Axis over which to compute the inverse DFT. If not given, the last axis is used. Returns ------- out : complex ndarray The truncated or zero-padded input, transformed along the axis indicated by `axis`, or the last one if `axis` is not specified. Raises ------ IndexError If `axes` is larger than the last axis of `a`. See Also -------- numpy.fft : An introduction, with definitions and general explanations. fft : The one-dimensional (forward) FFT, of which `ifft` is the inverse ifft2 : The two-dimensional inverse FFT. ifftn : The n-dimensional inverse FFT. Notes ----- If the input parameter `n` is larger than the size of the input, the input is padded by appending zeros at the end. Even though this is the common approach, it might lead to surprising results. If a different padding is desired, it must be performed before calling `ifft`. Examples -------- >>> np.fft.ifft([0, 4, 0, 0]) array([ 1.+0.j, 0.+1.j, -1.+0.j, 0.-1.j]) Create and plot a band-limited signal with random phases: >>> import matplotlib.pyplot as plt >>> t = np.arange(400) >>> n = np.zeros((400,), dtype=complex) >>> n[40:60] = np.exp(1j*np.random.uniform(0, 2*np.pi, (20,))) >>> s = np.fft.ifft(n) >>> plt.plot(t, s.real, 'b-', t, s.imag, 'r--') [, ] >>> plt.legend(('real', 'imaginary')) >>> plt.show() """ a = asarray(a).astype(complex) if n is None: n = shape(a)[axis] return _raw_fft(a, n, axis, fftpack.cffti, fftpack.cfftb, _fft_cache) / n def rfft(a, n=None, axis=-1): """ Compute the one-dimensional discrete Fourier Transform for real input. This function computes the one-dimensional *n*-point discrete Fourier Transform (DFT) of a real-valued array by means of an efficient algorithm called the Fast Fourier Transform (FFT). Parameters ---------- a : array_like Input array n : int, optional Number of points along transformation axis in the input to use. If `n` is smaller than the length of the input, the input is cropped. If it is larger, the input is padded with zeros. If `n` is not given, the length of the input (along the axis specified by `axis`) is used. axis : int, optional Axis over which to compute the FFT. If not given, the last axis is used. Returns ------- out : complex ndarray The truncated or zero-padded input, transformed along the axis indicated by `axis`, or the last one if `axis` is not specified. If `n` is even, the length of the transformed axis is ``(n/2)+1``. If `n` is odd, the length is ``(n+1)/2``. Raises ------ IndexError If `axis` is larger than the last axis of `a`. See Also -------- numpy.fft : For definition of the DFT and conventions used. irfft : The inverse of `rfft`. fft : The one-dimensional FFT of general (complex) input. fftn : The *n*-dimensional FFT. rfftn : The *n*-dimensional FFT of real input. Notes ----- When the DFT is computed for purely real input, the output is Hermite-symmetric, i.e. the negative frequency terms are just the complex 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``. 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. If `n` is even, ``A[-1]`` contains the term representing both positive and negative Nyquist frequency (+fs/2 and -fs/2), and must also be purely real. If `n` is odd, there is no term at fs/2; ``A[-1]`` contains the largest positive frequency (fs/2*(n-1)/n), and is complex in the general case. If the input `a` contains an imaginary part, it is silently discarded. Examples -------- >>> np.fft.fft([0, 1, 0, 0]) array([ 1.+0.j, 0.-1.j, -1.+0.j, 0.+1.j]) >>> np.fft.rfft([0, 1, 0, 0]) array([ 1.+0.j, 0.-1.j, -1.+0.j]) Notice how the final element of the `fft` output is the complex conjugate of the second element, for real input. For `rfft`, this symmetry is exploited to compute only the non-negative frequency terms. """ a = asarray(a).astype(float) return _raw_fft(a, n, axis, fftpack.rffti, fftpack.rfftf, _real_fft_cache) def irfft(a, n=None, axis=-1): """ Compute the inverse of the n-point DFT for real input. This function computes the inverse of the one-dimensional *n*-point discrete Fourier Transform of real input computed by `rfft`. In other words, ``irfft(rfft(a), len(a)) == a`` to within numerical accuracy. (See Notes below for why ``len(a)`` is necessary here.) The input is expected to be in the form returned by `rfft`, i.e. the real zero-frequency term followed by the complex positive frequency terms in order of increasing frequency. Since the discrete Fourier Transform of real input is Hermite-symmetric, the negative frequency terms are taken to be the complex conjugates of the corresponding positive frequency terms. Parameters ---------- a : array_like The input array. n : int, optional Length of the transformed axis of the output. For `n` output points, ``n//2+1`` input points are necessary. If the input is longer than this, it is cropped. If it is shorter than this, it is padded with zeros. If `n` is not given, it is determined from the length of the input (along the axis specified by `axis`). axis : int, optional Axis over which to compute the inverse FFT. Returns ------- out : ndarray The truncated or zero-padded input, transformed along the axis indicated by `axis`, or the last one if `axis` is not specified. The length of the transformed axis is `n`, or, if `n` is not given, ``2*(m-1)`` where `m` is the length of the transformed axis of the input. To get an odd number of output points, `n` must be specified. Raises ------ IndexError If `axis` is larger than the last axis of `a`. See Also -------- numpy.fft : For definition of the DFT and conventions used. rfft : The one-dimensional FFT of real input, of which `irfft` is inverse. fft : The one-dimensional FFT. irfft2 : The inverse of the two-dimensional FFT of real input. irfftn : The inverse of the *n*-dimensional FFT of real input. Notes ----- Returns the real valued `n`-point inverse discrete Fourier transform of `a`, where `a` contains the non-negative frequency terms of a Hermite-symmetric sequence. `n` is the length of the result, not the input. If you specify an `n` such that `a` must be zero-padded or truncated, the extra/removed values will be added/removed at high frequencies. One can thus resample a series to `m` points via Fourier interpolation by: ``a_resamp = irfft(rfft(a), m)``. Examples -------- >>> np.fft.ifft([1, -1j, -1, 1j]) array([ 0.+0.j, 1.+0.j, 0.+0.j, 0.+0.j]) >>> np.fft.irfft([1, -1j, -1]) array([ 0., 1., 0., 0.]) Notice how the last term in the input to the ordinary `ifft` is the complex conjugate of the second term, and the output has zero imaginary part everywhere. When calling `irfft`, the negative frequencies are not specified, and the output array is purely real. """ a = asarray(a).astype(complex) if n is None: n = (shape(a)[axis] - 1) * 2 return _raw_fft(a, n, axis, fftpack.rffti, fftpack.rfftb, _real_fft_cache) / n def hfft(a, n=None, axis=-1): """ Compute the FFT of a signal whose spectrum has Hermitian symmetry. Parameters ---------- a : array_like The input array. n : int, optional The length of the FFT. axis : int, optional The axis over which to compute the FFT, assuming Hermitian symmetry of the spectrum. Default is the last axis. Returns ------- out : ndarray The transformed input. See also -------- rfft : Compute the one-dimensional FFT for real input. ihfft : The inverse of `hfft`. Notes ----- `hfft`/`ihfft` are a pair analogous to `rfft`/`irfft`, but for the opposite case: here the signal is real in the frequency domain and has Hermite symmetry in the time domain. So here it's `hfft` for which you must supply the length of the result if it is to be odd: ``ihfft(hfft(a), len(a)) == a``, within numerical accuracy. Examples -------- >>> signal = np.array([[1, 1.j], [-1.j, 2]]) >>> np.conj(signal.T) - signal # check Hermitian symmetry array([[ 0.-0.j, 0.+0.j], [ 0.+0.j, 0.-0.j]]) >>> freq_spectrum = np.fft.hfft(signal) >>> freq_spectrum array([[ 1., 1.], [ 2., -2.]]) """ a = asarray(a).astype(complex) if n is None: n = (shape(a)[axis] - 1) * 2 return irfft(conjugate(a), n, axis) * n def ihfft(a, n=None, axis=-1): """ Compute the inverse FFT of a signal whose spectrum has Hermitian symmetry. Parameters ---------- a : array_like Input array. n : int, optional Length of the inverse FFT. axis : int, optional Axis over which to compute the inverse FFT, assuming Hermitian symmetry of the spectrum. Default is the last axis. Returns ------- out : ndarray The transformed input. See also -------- hfft, irfft Notes ----- `hfft`/`ihfft` are a pair analogous to `rfft`/`irfft`, but for the opposite case: here the signal is real in the frequency domain and has Hermite symmetry in the time domain. So here it's `hfft` for which you must supply the length of the result if it is to be odd: ``ihfft(hfft(a), len(a)) == a``, within numerical accuracy. """ a = asarray(a).astype(float) if n is None: n = shape(a)[axis] return conjugate(rfft(a, n, axis))/n def _cook_nd_args(a, s=None, axes=None, invreal=0): if s is None: shapeless = 1 if axes is None: s = list(a.shape) else: s = take(a.shape, axes) else: shapeless = 0 s = list(s) if axes is None: axes = list(range(-len(s), 0)) if len(s) != len(axes): raise ValueError("Shape and axes have different lengths.") if invreal and shapeless: s[-1] = (a.shape[axes[-1]] - 1) * 2 return s, axes def _raw_fftnd(a, s=None, axes=None, function=fft): a = asarray(a) s, axes = _cook_nd_args(a, s, axes) itl = list(range(len(axes))) itl.reverse() for ii in itl: a = function(a, n=s[ii], axis=axes[ii]) return a def fftn(a, s=None, axes=None): """ Compute the N-dimensional discrete Fourier Transform. This function computes the *N*-dimensional discrete Fourier Transform over any number of axes in an *M*-dimensional array by means of the Fast Fourier Transform (FFT). Parameters ---------- a : array_like Input array, can be complex. s : sequence of ints, optional Shape (length of each transformed axis) of the output (`s[0]` refers to axis 0, `s[1]` to axis 1, etc.). This corresponds to `n` for `fft(x, n)`. Along any axis, if the given shape is smaller than that of the input, the input is cropped. If it is larger, the input is padded with zeros. if `s` is not given, the shape of the input (along the axes specified by `axes`) is used. axes : sequence of ints, optional Axes over which to compute the FFT. If not given, the last ``len(s)`` axes are used, or all axes if `s` is also not specified. Repeated indices in `axes` means that the transform over that axis is performed multiple times. Returns ------- out : complex ndarray The truncated or zero-padded input, transformed along the axes indicated by `axes`, or by a combination of `s` and `a`, as explained in the parameters section above. Raises ------ ValueError If `s` and `axes` have different length. IndexError If an element of `axes` is larger than than the number of axes of `a`. See Also -------- numpy.fft : Overall view of discrete Fourier transforms, with definitions and conventions used. ifftn : The inverse of `fftn`, the inverse *n*-dimensional FFT. fft : The one-dimensional FFT, with definitions and conventions used. rfftn : The *n*-dimensional FFT of real input. fft2 : The two-dimensional FFT. fftshift : Shifts zero-frequency terms to centre of array Notes ----- The output, analogously to `fft`, contains the term for zero frequency in the low-order corner of all axes, the positive frequency terms in the first half of all axes, the term for the Nyquist frequency in the middle of all axes and the negative frequency terms in the second half of all axes, in order of decreasingly negative frequency. See `numpy.fft` for details, definitions and conventions used. Examples -------- >>> a = np.mgrid[:3, :3, :3][0] >>> np.fft.fftn(a, axes=(1, 2)) array([[[ 0.+0.j, 0.+0.j, 0.+0.j], [ 0.+0.j, 0.+0.j, 0.+0.j], [ 0.+0.j, 0.+0.j, 0.+0.j]], [[ 9.+0.j, 0.+0.j, 0.+0.j], [ 0.+0.j, 0.+0.j, 0.+0.j], [ 0.+0.j, 0.+0.j, 0.+0.j]], [[ 18.+0.j, 0.+0.j, 0.+0.j], [ 0.+0.j, 0.+0.j, 0.+0.j], [ 0.+0.j, 0.+0.j, 0.+0.j]]]) >>> np.fft.fftn(a, (2, 2), axes=(0, 1)) array([[[ 2.+0.j, 2.+0.j, 2.+0.j], [ 0.+0.j, 0.+0.j, 0.+0.j]], [[-2.+0.j, -2.+0.j, -2.+0.j], [ 0.+0.j, 0.+0.j, 0.+0.j]]]) >>> import matplotlib.pyplot as plt >>> [X, Y] = np.meshgrid(2 * np.pi * np.arange(200) / 12, ... 2 * np.pi * np.arange(200) / 34) >>> S = np.sin(X) + np.cos(Y) + np.random.uniform(0, 1, X.shape) >>> FS = np.fft.fftn(S) >>> plt.imshow(np.log(np.abs(np.fft.fftshift(FS))**2)) >>> plt.show() """ return _raw_fftnd(a, s, axes, fft) def ifftn(a, s=None, axes=None): """ Compute the N-dimensional inverse discrete Fourier Transform. This function computes the inverse of the N-dimensional discrete Fourier Transform over any number of axes in an M-dimensional array by means of the Fast Fourier Transform (FFT). In other words, ``ifftn(fftn(a)) == a`` to within numerical accuracy. For a description of the definitions and conventions used, see `numpy.fft`. The input, analogously to `ifft`, should be ordered in the same way as is returned by `fftn`, i.e. it should have the term for zero frequency in all axes in the low-order corner, the positive frequency terms in the first half of all axes, the term for the Nyquist frequency in the middle of all axes and the negative frequency terms in the second half of all axes, in order of decreasingly negative frequency. Parameters ---------- a : array_like Input array, can be complex. s : sequence of ints, optional Shape (length of each transformed axis) of the output (``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.). This corresponds to ``n`` for ``ifft(x, n)``. Along any axis, if the given shape is smaller than that of the input, the input is cropped. If it is larger, the input is padded with zeros. if `s` is not given, the shape of the input (along the axes specified by `axes`) is used. See notes for issue on `ifft` zero padding. axes : sequence of ints, optional Axes over which to compute the IFFT. If not given, the last ``len(s)`` axes are used, or all axes if `s` is also not specified. Repeated indices in `axes` means that the inverse transform over that axis is performed multiple times. Returns ------- out : complex ndarray The truncated or zero-padded input, transformed along the axes indicated by `axes`, or by a combination of `s` or `a`, as explained in the parameters section above. Raises ------ ValueError If `s` and `axes` have different length. IndexError If an element of `axes` is larger than than the number of axes of `a`. See Also -------- numpy.fft : Overall view of discrete Fourier transforms, with definitions and conventions used. fftn : The forward *n*-dimensional FFT, of which `ifftn` is the inverse. ifft : The one-dimensional inverse FFT. ifft2 : The two-dimensional inverse FFT. ifftshift : Undoes `fftshift`, shifts zero-frequency terms to beginning of array. Notes ----- See `numpy.fft` for definitions and conventions used. Zero-padding, analogously with `ifft`, is performed by appending zeros to the input along the specified dimension. Although this is the common approach, it might lead to surprising results. If another form of zero padding is desired, it must be performed before `ifftn` is called. Examples -------- >>> a = np.eye(4) >>> np.fft.ifftn(np.fft.fftn(a, axes=(0,)), axes=(1,)) array([[ 1.+0.j, 0.+0.j, 0.+0.j, 0.+0.j], [ 0.+0.j, 1.+0.j, 0.+0.j, 0.+0.j], [ 0.+0.j, 0.+0.j, 1.+0.j, 0.+0.j], [ 0.+0.j, 0.+0.j, 0.+0.j, 1.+0.j]]) Create and plot an image with band-limited frequency content: >>> import matplotlib.pyplot as plt >>> n = np.zeros((200,200), dtype=complex) >>> n[60:80, 20:40] = np.exp(1j*np.random.uniform(0, 2*np.pi, (20, 20))) >>> im = np.fft.ifftn(n).real >>> plt.imshow(im) >>> plt.show() """ return _raw_fftnd(a, s, axes, ifft) def fft2(a, s=None, axes=(-2, -1)): """ Compute the 2-dimensional discrete Fourier Transform This function computes the *n*-dimensional discrete Fourier Transform over any axes in an *M*-dimensional array by means of the Fast Fourier Transform (FFT). By default, the transform is computed over the last two axes of the input array, i.e., a 2-dimensional FFT. Parameters ---------- a : array_like Input array, can be complex s : sequence of ints, optional Shape (length of each transformed axis) of the output (`s[0]` refers to axis 0, `s[1]` to axis 1, etc.). This corresponds to `n` for `fft(x, n)`. Along each axis, if the given shape is smaller than that of the input, the input is cropped. If it is larger, the input is padded with zeros. if `s` is not given, the shape of the input (along the axes specified by `axes`) is used. axes : sequence of ints, optional Axes over which to compute the FFT. If not given, the last two axes are used. A repeated index in `axes` means the transform over that axis is performed multiple times. A one-element sequence means that a one-dimensional FFT is performed. Returns ------- out : complex ndarray The truncated or zero-padded input, transformed along the axes indicated by `axes`, or the last two axes if `axes` is not given. Raises ------ ValueError If `s` and `axes` have different length, or `axes` not given and ``len(s) != 2``. IndexError If an element of `axes` is larger than than the number of axes of `a`. See Also -------- numpy.fft : Overall view of discrete Fourier transforms, with definitions and conventions used. ifft2 : The inverse two-dimensional FFT. fft : The one-dimensional FFT. fftn : The *n*-dimensional FFT. fftshift : Shifts zero-frequency terms to the center of the array. For two-dimensional input, swaps first and third quadrants, and second and fourth quadrants. Notes ----- `fft2` is just `fftn` with a different default for `axes`. The output, analogously to `fft`, contains the term for zero frequency in the low-order corner of the transformed axes, the positive frequency terms in the first half of these axes, the term for the Nyquist frequency in the middle of the axes and the negative frequency terms in the second half of the axes, in order of decreasingly negative frequency. See `fftn` for details and a plotting example, and `numpy.fft` for definitions and conventions used. Examples -------- >>> 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]]) """ return _raw_fftnd(a, s, axes, fft) def ifft2(a, s=None, axes=(-2, -1)): """ Compute the 2-dimensional inverse discrete Fourier Transform. This function computes the inverse of the 2-dimensional discrete Fourier Transform over any number of axes in an M-dimensional array by means of the Fast Fourier Transform (FFT). In other words, ``ifft2(fft2(a)) == a`` to within numerical accuracy. By default, the inverse transform is computed over the last two axes of the input array. The input, analogously to `ifft`, should be ordered in the same way as is returned by `fft2`, i.e. it should have the term for zero frequency in the low-order corner of the two axes, the positive frequency terms in the first half of these axes, the term for the Nyquist frequency in the middle of the axes and the negative frequency terms in the second half of both axes, in order of decreasingly negative frequency. Parameters ---------- a : array_like Input array, can be complex. s : sequence of ints, optional Shape (length of each axis) of the output (``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.). This corresponds to `n` for ``ifft(x, n)``. Along each axis, if the given shape is smaller than that of the input, the input is cropped. If it is larger, the input is padded with zeros. if `s` is not given, the shape of the input (along the axes specified by `axes`) is used. See notes for issue on `ifft` zero padding. axes : sequence of ints, optional Axes over which to compute the FFT. If not given, the last two axes are used. A repeated index in `axes` means the transform over that axis is performed multiple times. A one-element sequence means that a one-dimensional FFT is performed. Returns ------- out : complex ndarray The truncated or zero-padded input, transformed along the axes indicated by `axes`, or the last two axes if `axes` is not given. Raises ------ ValueError If `s` and `axes` have different length, or `axes` not given and ``len(s) != 2``. IndexError If an element of `axes` is larger than than the number of axes of `a`. See Also -------- numpy.fft : Overall view of discrete Fourier transforms, with definitions and conventions used. fft2 : The forward 2-dimensional FFT, of which `ifft2` is the inverse. ifftn : The inverse of the *n*-dimensional FFT. fft : The one-dimensional FFT. ifft : The one-dimensional inverse FFT. Notes ----- `ifft2` is just `ifftn` with a different default for `axes`. See `ifftn` for details and a plotting example, and `numpy.fft` for definition and conventions used. Zero-padding, analogously with `ifft`, is performed by appending zeros to the input along the specified dimension. Although this is the common approach, it might lead to surprising results. If another form of zero padding is desired, it must be performed before `ifft2` is called. Examples -------- >>> a = 4 * np.eye(4) >>> np.fft.ifft2(a) array([[ 1.+0.j, 0.+0.j, 0.+0.j, 0.+0.j], [ 0.+0.j, 0.+0.j, 0.+0.j, 1.+0.j], [ 0.+0.j, 0.+0.j, 1.+0.j, 0.+0.j], [ 0.+0.j, 1.+0.j, 0.+0.j, 0.+0.j]]) """ return _raw_fftnd(a, s, axes, ifft) def rfftn(a, s=None, axes=None): """ Compute the N-dimensional discrete Fourier Transform for real input. This function computes the N-dimensional discrete Fourier Transform over any number of axes in an M-dimensional real array by means of the Fast Fourier Transform (FFT). By default, all axes are transformed, with the real transform performed over the last axis, while the remaining transforms are complex. Parameters ---------- a : array_like Input array, taken to be real. s : sequence of ints, optional Shape (length along each transformed axis) to use from the input. (``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.). The final element of `s` corresponds to `n` for ``rfft(x, n)``, while for the remaining axes, it corresponds to `n` for ``fft(x, n)``. Along any axis, if the given shape is smaller than that of the input, the input is cropped. If it is larger, the input is padded with zeros. if `s` is not given, the shape of the input (along the axes specified by `axes`) is used. axes : sequence of ints, optional Axes over which to compute the FFT. If not given, the last ``len(s)`` axes are used, or all axes if `s` is also not specified. Returns ------- out : complex ndarray The truncated or zero-padded input, transformed along the axes indicated by `axes`, or by a combination of `s` and `a`, as explained in the parameters section above. The length of the last axis transformed will be ``s[-1]//2+1``, while the remaining transformed axes will have lengths according to `s`, or unchanged from the input. Raises ------ ValueError If `s` and `axes` have different length. IndexError If an element of `axes` is larger than than the number of axes of `a`. See Also -------- irfftn : The inverse of `rfftn`, i.e. the inverse of the n-dimensional FFT of real input. fft : The one-dimensional FFT, with definitions and conventions used. rfft : The one-dimensional FFT of real input. fftn : The n-dimensional FFT. rfft2 : The two-dimensional FFT of real input. Notes ----- The transform for real input is performed over the last transformation axis, as by `rfft`, then the transform over the remaining axes is performed as by `fftn`. The order of the output is as for `rfft` for the final transformation axis, and as for `fftn` for the remaining transformation axes. See `fft` for details, definitions and conventions used. Examples -------- >>> a = np.ones((2, 2, 2)) >>> np.fft.rfftn(a) array([[[ 8.+0.j, 0.+0.j], [ 0.+0.j, 0.+0.j]], [[ 0.+0.j, 0.+0.j], [ 0.+0.j, 0.+0.j]]]) >>> np.fft.rfftn(a, axes=(2, 0)) array([[[ 4.+0.j, 0.+0.j], [ 4.+0.j, 0.+0.j]], [[ 0.+0.j, 0.+0.j], [ 0.+0.j, 0.+0.j]]]) """ a = asarray(a).astype(float) s, axes = _cook_nd_args(a, s, axes) a = rfft(a, s[-1], axes[-1]) for ii in range(len(axes)-1): a = fft(a, s[ii], axes[ii]) return a def rfft2(a, s=None, axes=(-2, -1)): """ Compute the 2-dimensional FFT of a real array. Parameters ---------- a : array Input array, taken to be real. s : sequence of ints, optional Shape of the FFT. axes : sequence of ints, optional Axes over which to compute the FFT. Returns ------- out : ndarray The result of the real 2-D FFT. See Also -------- rfftn : Compute the N-dimensional discrete Fourier Transform for real input. Notes ----- This is really just `rfftn` with different default behavior. For more details see `rfftn`. """ return rfftn(a, s, axes) def irfftn(a, s=None, axes=None): """ Compute the inverse of the N-dimensional FFT of real input. This function computes the inverse of the N-dimensional discrete Fourier Transform for real input over any number of axes in an M-dimensional array by means of the Fast Fourier Transform (FFT). In other words, ``irfftn(rfftn(a), a.shape) == a`` to within numerical accuracy. (The ``a.shape`` is necessary like ``len(a)`` is for `irfft`, and for the same reason.) The input should be ordered in the same way as is returned by `rfftn`, i.e. as for `irfft` for the final transformation axis, and as for `ifftn` along all the other axes. Parameters ---------- a : array_like Input array. s : sequence of ints, optional Shape (length of each transformed axis) of the output (``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.). `s` is also the number of input points used along this axis, except for the last axis, where ``s[-1]//2+1`` points of the input are used. Along any axis, if the shape indicated by `s` is smaller than that of the input, the input is cropped. If it is larger, the input is padded with zeros. If `s` is not given, the shape of the input (along the axes specified by `axes`) is used. axes : sequence of ints, optional Axes over which to compute the inverse FFT. If not given, the last `len(s)` axes are used, or all axes if `s` is also not specified. Repeated indices in `axes` means that the inverse transform over that axis is performed multiple times. Returns ------- out : ndarray The truncated or zero-padded input, transformed along the axes indicated by `axes`, or by a combination of `s` or `a`, as explained in the parameters section above. The length of each transformed axis is as given by the corresponding element of `s`, or the length of the input in every axis except for the last one if `s` is not given. In the final transformed axis the length of the output when `s` is not given is ``2*(m-1)`` where `m` is the length of the final transformed axis of the input. To get an odd number of output points in the final axis, `s` must be specified. Raises ------ ValueError If `s` and `axes` have different length. IndexError If an element of `axes` is larger than than the number of axes of `a`. See Also -------- rfftn : The forward n-dimensional FFT of real input, of which `ifftn` is the inverse. fft : The one-dimensional FFT, with definitions and conventions used. irfft : The inverse of the one-dimensional FFT of real input. irfft2 : The inverse of the two-dimensional FFT of real input. Notes ----- See `fft` for definitions and conventions used. See `rfft` for definitions and conventions used for real input. Examples -------- >>> a = np.zeros((3, 2, 2)) >>> a[0, 0, 0] = 3 * 2 * 2 >>> np.fft.irfftn(a) array([[[ 1., 1.], [ 1., 1.]], [[ 1., 1.], [ 1., 1.]], [[ 1., 1.], [ 1., 1.]]]) """ a = asarray(a).astype(complex) s, axes = _cook_nd_args(a, s, axes, invreal=1) for ii in range(len(axes)-1): a = ifft(a, s[ii], axes[ii]) a = irfft(a, s[-1], axes[-1]) return a def irfft2(a, s=None, axes=(-2, -1)): """ Compute the 2-dimensional inverse FFT of a real array. Parameters ---------- a : array_like The input array s : sequence of ints, optional Shape of the inverse FFT. axes : sequence of ints, optional The axes over which to compute the inverse fft. Default is the last two axes. Returns ------- out : ndarray The result of the inverse real 2-D FFT. See Also -------- irfftn : Compute the inverse of the N-dimensional FFT of real input. Notes ----- This is really `irfftn` with different defaults. For more details see `irfftn`. """ return irfftn(a, s, axes) numpy-1.8.2/numpy/fft/info.py0000664000175100017510000001534212370216242017264 0ustar vagrantvagrant00000000000000""" Discrete Fourier Transform (:mod:`numpy.fft`) ============================================= .. currentmodule:: numpy.fft Standard FFTs ------------- .. autosummary:: :toctree: generated/ fft Discrete Fourier transform. ifft Inverse discrete Fourier transform. fft2 Discrete Fourier transform in two dimensions. ifft2 Inverse discrete Fourier transform in two dimensions. fftn Discrete Fourier transform in N-dimensions. ifftn Inverse discrete Fourier transform in N dimensions. Real FFTs --------- .. autosummary:: :toctree: generated/ rfft Real discrete Fourier transform. irfft Inverse real discrete Fourier transform. rfft2 Real discrete Fourier transform in two dimensions. irfft2 Inverse real discrete Fourier transform in two dimensions. rfftn Real discrete Fourier transform in N dimensions. irfftn Inverse real discrete Fourier transform in N dimensions. Hermitian FFTs -------------- .. autosummary:: :toctree: generated/ hfft Hermitian discrete Fourier transform. ihfft Inverse Hermitian discrete Fourier transform. Helper routines --------------- .. autosummary:: :toctree: generated/ fftfreq Discrete Fourier Transform sample frequencies. rfftfreq DFT sample frequencies (for usage with rfft, irfft). fftshift Shift zero-frequency component to center of spectrum. ifftshift Inverse of fftshift. Background information ---------------------- Fourier analysis is fundamentally a method for expressing a function as a sum of periodic components, and for recovering the function from those components. When both the function and its Fourier transform are replaced with discretized counterparts, it is called the discrete Fourier transform (DFT). The DFT has become a mainstay of numerical computing in part because of a very fast algorithm for computing it, called the Fast Fourier Transform (FFT), which was known to Gauss (1805) and was brought to light in its current form by Cooley and Tukey [CT]_. Press et al. [NR]_ provide an accessible introduction to Fourier analysis and its applications. Because the discrete Fourier transform separates its input into components that contribute at discrete frequencies, it has a great number of applications in digital signal processing, e.g., for filtering, and in this context the discretized input to the transform is customarily referred to as a *signal*, which exists in the *time domain*. The output is called a *spectrum* or *transform* and exists in the *frequency domain*. Implementation details ---------------------- There are many ways to define the DFT, varying in the sign of the exponent, normalization, etc. In this implementation, the DFT is defined as .. math:: A_k = \\sum_{m=0}^{n-1} a_m \\exp\\left\\{-2\\pi i{mk \\over n}\\right\\} \\qquad k = 0,\\ldots,n-1. The DFT is in general defined for complex inputs and outputs, and a single-frequency component at linear frequency :math:`f` is represented by a complex exponential :math:`a_m = \\exp\\{2\\pi i\\,f m\\Delta t\\}`, where :math:`\\Delta t` is the sampling interval. The values in the result follow so-called "standard" order: If ``A = fft(a, n)``, then ``A[0]`` contains the zero-frequency term (the mean of the signal), which is always purely real for real inputs. Then ``A[1:n/2]`` contains the positive-frequency terms, and ``A[n/2+1:]`` contains the negative-frequency terms, in order of decreasingly negative frequency. For an even number of input points, ``A[n/2]`` represents both positive and negative Nyquist frequency, and is also purely real for real input. For an odd number of input points, ``A[(n-1)/2]`` contains the largest positive frequency, while ``A[(n+1)/2]`` contains the largest negative frequency. The routine ``np.fft.fftfreq(n)`` returns an array giving the frequencies of corresponding elements in the output. The routine ``np.fft.fftshift(A)`` shifts transforms and their frequencies to put the zero-frequency components in the middle, and ``np.fft.ifftshift(A)`` undoes that shift. When the input `a` is a time-domain signal and ``A = fft(a)``, ``np.abs(A)`` is its amplitude spectrum and ``np.abs(A)**2`` is its power spectrum. The phase spectrum is obtained by ``np.angle(A)``. The inverse DFT is defined as .. math:: a_m = \\frac{1}{n}\\sum_{k=0}^{n-1}A_k\\exp\\left\\{2\\pi i{mk\\over n}\\right\\} \\qquad m = 0,\\ldots,n-1. It differs from the forward transform by the sign of the exponential argument and the normalization by :math:`1/n`. Real and Hermitian transforms ----------------------------- When the input is purely real, its transform is Hermitian, i.e., the component at frequency :math:`f_k` is the complex conjugate of the component at frequency :math:`-f_k`, which means that for real inputs there is no information in the negative frequency components that is not already available from the positive frequency components. The family of `rfft` functions is designed to operate on real inputs, and exploits this symmetry by computing only the positive frequency components, up to and including the Nyquist frequency. Thus, ``n`` input points produce ``n/2+1`` complex output points. The inverses of this family assumes the same symmetry of its input, and for an output of ``n`` points uses ``n/2+1`` input points. Correspondingly, when the spectrum is purely real, the signal is Hermitian. The `hfft` family of functions exploits this symmetry by using ``n/2+1`` complex points in the input (time) domain for ``n`` real points in the frequency domain. In higher dimensions, FFTs are used, e.g., for image analysis and filtering. The computational efficiency of the FFT means that it can also be a faster way to compute large convolutions, using the property that a convolution in the time domain is equivalent to a point-by-point multiplication in the frequency domain. Higher dimensions ----------------- In two dimensions, the DFT is defined as .. math:: A_{kl} = \\sum_{m=0}^{M-1} \\sum_{n=0}^{N-1} a_{mn}\\exp\\left\\{-2\\pi i \\left({mk\\over M}+{nl\\over N}\\right)\\right\\} \\qquad k = 0, \\ldots, M-1;\\quad l = 0, \\ldots, N-1, which extends in the obvious way to higher dimensions, and the inverses in higher dimensions also extend in the same way. References ---------- .. [CT] Cooley, James W., and John W. Tukey, 1965, "An algorithm for the machine calculation of complex Fourier series," *Math. Comput.* 19: 297-301. .. [NR] Press, W., Teukolsky, S., Vetterline, W.T., and Flannery, B.P., 2007, *Numerical Recipes: The Art of Scientific Computing*, ch. 12-13. Cambridge Univ. Press, Cambridge, UK. Examples -------- For examples, see the various functions. """ from __future__ import division, absolute_import, print_function depends = ['core'] numpy-1.8.2/numpy/fft/fftpack_litemodule.c0000664000175100017510000002213112370216243021757 0ustar vagrantvagrant00000000000000#define NPY_NO_DEPRECATED_API NPY_API_VERSION #include "fftpack.h" #include "Python.h" #include "numpy/arrayobject.h" static PyObject *ErrorObject; /* ----------------------------------------------------- */ static char fftpack_cfftf__doc__[] = ""; PyObject * fftpack_cfftf(PyObject *NPY_UNUSED(self), PyObject *args) { PyObject *op1, *op2; PyArrayObject *data; PyArray_Descr *descr; double *wsave, *dptr; npy_intp nsave; int npts, nrepeats, i; if(!PyArg_ParseTuple(args, "OO", &op1, &op2)) { return NULL; } data = (PyArrayObject *)PyArray_CopyFromObject(op1, NPY_CDOUBLE, 1, 0); if (data == NULL) { return NULL; } descr = PyArray_DescrFromType(NPY_DOUBLE); if (PyArray_AsCArray(&op2, (void *)&wsave, &nsave, 1, descr) == -1) { goto fail; } if (data == NULL) { goto fail; } npts = PyArray_DIM(data, PyArray_NDIM(data) - 1); if (nsave != npts*4 + 15) { PyErr_SetString(ErrorObject, "invalid work array for fft size"); goto fail; } nrepeats = PyArray_SIZE(data)/npts; dptr = (double *)PyArray_DATA(data); NPY_SIGINT_ON; Py_BEGIN_ALLOW_THREADS; for (i = 0; i < nrepeats; i++) { cfftf(npts, dptr, wsave); dptr += npts*2; } Py_END_ALLOW_THREADS; NPY_SIGINT_OFF; PyArray_Free(op2, (char *)wsave); return (PyObject *)data; fail: PyArray_Free(op2, (char *)wsave); Py_DECREF(data); return NULL; } static char fftpack_cfftb__doc__[] = ""; PyObject * fftpack_cfftb(PyObject *NPY_UNUSED(self), PyObject *args) { PyObject *op1, *op2; PyArrayObject *data; PyArray_Descr *descr; double *wsave, *dptr; npy_intp nsave; int npts, nrepeats, i; if(!PyArg_ParseTuple(args, "OO", &op1, &op2)) { return NULL; } data = (PyArrayObject *)PyArray_CopyFromObject(op1, NPY_CDOUBLE, 1, 0); if (data == NULL) { return NULL; } descr = PyArray_DescrFromType(NPY_DOUBLE); if (PyArray_AsCArray(&op2, (void *)&wsave, &nsave, 1, descr) == -1) { goto fail; } if (data == NULL) { goto fail; } npts = PyArray_DIM(data, PyArray_NDIM(data) - 1); if (nsave != npts*4 + 15) { PyErr_SetString(ErrorObject, "invalid work array for fft size"); goto fail; } nrepeats = PyArray_SIZE(data)/npts; dptr = (double *)PyArray_DATA(data); NPY_SIGINT_ON; Py_BEGIN_ALLOW_THREADS; for (i = 0; i < nrepeats; i++) { cfftb(npts, dptr, wsave); dptr += npts*2; } Py_END_ALLOW_THREADS; NPY_SIGINT_OFF; PyArray_Free(op2, (char *)wsave); return (PyObject *)data; fail: PyArray_Free(op2, (char *)wsave); Py_DECREF(data); return NULL; } static char fftpack_cffti__doc__[] =""; static PyObject * fftpack_cffti(PyObject *NPY_UNUSED(self), PyObject *args) { PyArrayObject *op; npy_intp dim; long n; if (!PyArg_ParseTuple(args, "l", &n)) { return NULL; } /*Magic size needed by cffti*/ dim = 4*n + 15; /*Create a 1 dimensional array of dimensions of type double*/ op = (PyArrayObject *)PyArray_SimpleNew(1, &dim, NPY_DOUBLE); if (op == NULL) { return NULL; } NPY_SIGINT_ON; Py_BEGIN_ALLOW_THREADS; cffti(n, (double *)PyArray_DATA((PyArrayObject*)op)); Py_END_ALLOW_THREADS; NPY_SIGINT_OFF; return (PyObject *)op; } static char fftpack_rfftf__doc__[] =""; PyObject * fftpack_rfftf(PyObject *NPY_UNUSED(self), PyObject *args) { PyObject *op1, *op2; PyArrayObject *data, *ret; PyArray_Descr *descr; double *wsave, *dptr, *rptr; npy_intp nsave; int npts, nrepeats, i, rstep; if(!PyArg_ParseTuple(args, "OO", &op1, &op2)) { return NULL; } data = (PyArrayObject *)PyArray_ContiguousFromObject(op1, NPY_DOUBLE, 1, 0); if (data == NULL) { return NULL; } /* FIXME, direct access changing contents of data->dimensions */ npts = PyArray_DIM(data, PyArray_NDIM(data) - 1); PyArray_DIMS(data)[PyArray_NDIM(data) - 1] = npts/2 + 1; ret = (PyArrayObject *)PyArray_Zeros(PyArray_NDIM(data), PyArray_DIMS(data), PyArray_DescrFromType(NPY_CDOUBLE), 0); PyArray_DIMS(data)[PyArray_NDIM(data) - 1] = npts; rstep = PyArray_DIM(ret, PyArray_NDIM(ret) - 1)*2; descr = PyArray_DescrFromType(NPY_DOUBLE); if (PyArray_AsCArray(&op2, (void *)&wsave, &nsave, 1, descr) == -1) { goto fail; } if (data == NULL || ret == NULL) { goto fail; } if (nsave != npts*2+15) { PyErr_SetString(ErrorObject, "invalid work array for fft size"); goto fail; } nrepeats = PyArray_SIZE(data)/npts; rptr = (double *)PyArray_DATA(ret); dptr = (double *)PyArray_DATA(data); NPY_SIGINT_ON; Py_BEGIN_ALLOW_THREADS; for (i = 0; i < nrepeats; i++) { memcpy((char *)(rptr+1), dptr, npts*sizeof(double)); rfftf(npts, rptr+1, wsave); rptr[0] = rptr[1]; rptr[1] = 0.0; rptr += rstep; dptr += npts; } Py_END_ALLOW_THREADS; NPY_SIGINT_OFF; PyArray_Free(op2, (char *)wsave); Py_DECREF(data); return (PyObject *)ret; fail: PyArray_Free(op2, (char *)wsave); Py_XDECREF(data); Py_XDECREF(ret); return NULL; } static char fftpack_rfftb__doc__[] =""; PyObject * fftpack_rfftb(PyObject *NPY_UNUSED(self), PyObject *args) { PyObject *op1, *op2; PyArrayObject *data, *ret; PyArray_Descr *descr; double *wsave, *dptr, *rptr; npy_intp nsave; int npts, nrepeats, i; if(!PyArg_ParseTuple(args, "OO", &op1, &op2)) { return NULL; } data = (PyArrayObject *)PyArray_ContiguousFromObject(op1, NPY_CDOUBLE, 1, 0); if (data == NULL) { return NULL; } npts = PyArray_DIM(data, PyArray_NDIM(data) - 1); ret = (PyArrayObject *)PyArray_Zeros(PyArray_NDIM(data), PyArray_DIMS(data), PyArray_DescrFromType(NPY_DOUBLE), 0); descr = PyArray_DescrFromType(NPY_DOUBLE); if (PyArray_AsCArray(&op2, (void *)&wsave, &nsave, 1, descr) == -1) { goto fail; } if (data == NULL || ret == NULL) { goto fail; } if (nsave != npts*2 + 15) { PyErr_SetString(ErrorObject, "invalid work array for fft size"); goto fail; } nrepeats = PyArray_SIZE(ret)/npts; rptr = (double *)PyArray_DATA(ret); dptr = (double *)PyArray_DATA(data); NPY_SIGINT_ON; Py_BEGIN_ALLOW_THREADS; for (i = 0; i < nrepeats; i++) { memcpy((char *)(rptr + 1), (dptr + 2), (npts - 1)*sizeof(double)); rptr[0] = dptr[0]; rfftb(npts, rptr, wsave); rptr += npts; dptr += npts*2; } Py_END_ALLOW_THREADS; NPY_SIGINT_OFF; PyArray_Free(op2, (char *)wsave); Py_DECREF(data); return (PyObject *)ret; fail: PyArray_Free(op2, (char *)wsave); Py_XDECREF(data); Py_XDECREF(ret); return NULL; } static char fftpack_rffti__doc__[] =""; static PyObject * fftpack_rffti(PyObject *NPY_UNUSED(self), PyObject *args) { PyArrayObject *op; npy_intp dim; long n; if (!PyArg_ParseTuple(args, "l", &n)) { return NULL; } /*Magic size needed by rffti*/ dim = 2*n + 15; /*Create a 1 dimensional array of dimensions of type double*/ op = (PyArrayObject *)PyArray_SimpleNew(1, &dim, NPY_DOUBLE); if (op == NULL) { return NULL; } NPY_SIGINT_ON; Py_BEGIN_ALLOW_THREADS; rffti(n, (double *)PyArray_DATA((PyArrayObject*)op)); Py_END_ALLOW_THREADS; NPY_SIGINT_OFF; return (PyObject *)op; } /* List of methods defined in the module */ static struct PyMethodDef fftpack_methods[] = { {"cfftf", fftpack_cfftf, 1, fftpack_cfftf__doc__}, {"cfftb", fftpack_cfftb, 1, fftpack_cfftb__doc__}, {"cffti", fftpack_cffti, 1, fftpack_cffti__doc__}, {"rfftf", fftpack_rfftf, 1, fftpack_rfftf__doc__}, {"rfftb", fftpack_rfftb, 1, fftpack_rfftb__doc__}, {"rffti", fftpack_rffti, 1, fftpack_rffti__doc__}, {NULL, NULL, 0, NULL} /* sentinel */ }; /* Initialization function for the module (*must* be called initfftpack) */ static char fftpack_module_documentation[] = "" ; #if PY_MAJOR_VERSION >= 3 static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, "fftpack_lite", NULL, -1, fftpack_methods, NULL, NULL, NULL, NULL }; #endif /* Initialization function for the module */ #if PY_MAJOR_VERSION >= 3 #define RETVAL m PyMODINIT_FUNC PyInit_fftpack_lite(void) #else #define RETVAL PyMODINIT_FUNC initfftpack_lite(void) #endif { PyObject *m,*d; #if PY_MAJOR_VERSION >= 3 m = PyModule_Create(&moduledef); #else m = Py_InitModule4("fftpack_lite", fftpack_methods, fftpack_module_documentation, (PyObject*)NULL,PYTHON_API_VERSION); #endif /* Import the array object */ import_array(); /* Add some symbolic constants to the module */ d = PyModule_GetDict(m); ErrorObject = PyErr_NewException("fftpack.error", NULL, NULL); PyDict_SetItemString(d, "error", ErrorObject); /* XXXX Add constants here */ return RETVAL; } numpy-1.8.2/numpy/fft/fftpack.c0000664000175100017510000014310012370216242017533 0ustar vagrantvagrant00000000000000/* fftpack.c : A set of FFT routines in C. Algorithmically based on Fortran-77 FFTPACK by Paul N. Swarztrauber (Version 4, 1985). */ /* isign is +1 for backward and -1 for forward transforms */ #include #include #define DOUBLE #ifdef DOUBLE #define Treal double #else #define Treal float #endif #define ref(u,a) u[a] #define MAXFAC 13 /* maximum number of factors in factorization of n */ #define NSPECIAL 4 /* number of factors for which we have special-case routines */ #ifdef __cplusplus extern "C" { #endif /* ---------------------------------------------------------------------- passf2, passf3, passf4, passf5, passf. Complex FFT passes fwd and bwd. ---------------------------------------------------------------------- */ static void passf2(int ido, int l1, const Treal cc[], Treal ch[], const Treal wa1[], int isign) /* isign==+1 for backward transform */ { int i, k, ah, ac; Treal ti2, tr2; if (ido <= 2) { for (k=0; k= l1) { for (j=1; j idp) idlj -= idp; war = wa[idlj - 2]; wai = wa[idlj-1]; for (ik=0; ik= l1) { for (j=1; j= l1) { for (k=0; k= l1) { for (j=1; j= l1) { for (k=0; k= l1) { for (j=1; j= l1) { for (j=1; j 5) { wa[i1-1] = wa[i-1]; wa[i1] = wa[i]; } } l1 = l2; } } /* cffti1 */ void cffti(int n, Treal wsave[]) { int iw1, iw2; if (n == 1) return; iw1 = 2*n; iw2 = iw1 + 2*n; cffti1(n, wsave+iw1, (int*)(wsave+iw2)); } /* cffti */ /* ---------------------------------------------------------------------- rfftf1, rfftb1, rfftf, rfftb, rffti1, rffti. Treal FFTs. ---------------------------------------------------------------------- */ static void rfftf1(int n, Treal c[], Treal ch[], const Treal wa[], const int ifac[MAXFAC+2]) { int i; int k1, l1, l2, na, kh, nf, ip, iw, ix2, ix3, ix4, ido, idl1; Treal *cinput, *coutput; nf = ifac[1]; na = 1; l2 = n; iw = n-1; for (k1 = 1; k1 <= nf; ++k1) { kh = nf - k1; ip = ifac[kh + 2]; l1 = l2 / ip; ido = n / l2; idl1 = ido*l1; iw -= (ip - 1)*ido; na = !na; if (na) { cinput = ch; coutput = c; } else { cinput = c; coutput = ch; } switch (ip) { case 4: ix2 = iw + ido; ix3 = ix2 + ido; radf4(ido, l1, cinput, coutput, &wa[iw], &wa[ix2], &wa[ix3]); break; case 2: radf2(ido, l1, cinput, coutput, &wa[iw]); break; case 3: ix2 = iw + ido; radf3(ido, l1, cinput, coutput, &wa[iw], &wa[ix2]); break; case 5: ix2 = iw + ido; ix3 = ix2 + ido; ix4 = ix3 + ido; radf5(ido, l1, cinput, coutput, &wa[iw], &wa[ix2], &wa[ix3], &wa[ix4]); break; default: if (ido == 1) na = !na; if (na == 0) { radfg(ido, ip, l1, idl1, c, ch, &wa[iw]); na = 1; } else { radfg(ido, ip, l1, idl1, ch, c, &wa[iw]); na = 0; } } l2 = l1; } if (na == 1) return; for (i = 0; i < n; i++) c[i] = ch[i]; } /* rfftf1 */ void rfftb1(int n, Treal c[], Treal ch[], const Treal wa[], const int ifac[MAXFAC+2]) { int i; int k1, l1, l2, na, nf, ip, iw, ix2, ix3, ix4, ido, idl1; Treal *cinput, *coutput; nf = ifac[1]; na = 0; l1 = 1; iw = 0; for (k1=1; k1<=nf; k1++) { ip = ifac[k1 + 1]; l2 = ip*l1; ido = n / l2; idl1 = ido*l1; if (na) { cinput = ch; coutput = c; } else { cinput = c; coutput = ch; } switch (ip) { case 4: ix2 = iw + ido; ix3 = ix2 + ido; radb4(ido, l1, cinput, coutput, &wa[iw], &wa[ix2], &wa[ix3]); na = !na; break; case 2: radb2(ido, l1, cinput, coutput, &wa[iw]); na = !na; break; case 3: ix2 = iw + ido; radb3(ido, l1, cinput, coutput, &wa[iw], &wa[ix2]); na = !na; break; case 5: ix2 = iw + ido; ix3 = ix2 + ido; ix4 = ix3 + ido; radb5(ido, l1, cinput, coutput, &wa[iw], &wa[ix2], &wa[ix3], &wa[ix4]); na = !na; break; default: radbg(ido, ip, l1, idl1, cinput, coutput, &wa[iw]); if (ido == 1) na = !na; } l1 = l2; iw += (ip - 1)*ido; } if (na == 0) return; for (i=0; i= 3: import queue else: import Queue as queue def fft1(x): L = len(x) phase = -2j*np.pi*(np.arange(L)/float(L)) 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): self.assertRaises(ValueError, np.fft.fft, [1, 2, 3], 0) class TestFFT1D(TestCase): def test_basic(self): rand = np.random.random x = rand(30) + 1j*rand(30) 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() numpy-1.8.2/numpy/fft/__init__.py0000664000175100017510000000035512370216242020066 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function # To get sub-modules from .info import __doc__ from .fftpack import * from .helper import * from numpy.testing import Tester test = Tester().test bench = Tester().bench numpy-1.8.2/numpy/lib/0000775000175100017510000000000012371375430015747 5ustar vagrantvagrant00000000000000numpy-1.8.2/numpy/lib/stride_tricks.py0000664000175100017510000001015312370216243021165 0ustar vagrantvagrant00000000000000""" Utilities that manipulate strides to achieve desirable effects. An explanation of strides can be found in the "ndarray.rst" file in the NumPy reference guide. """ from __future__ import division, absolute_import, print_function import numpy as np __all__ = ['broadcast_arrays'] class DummyArray(object): """ Dummy object that just exists to hang __array_interface__ dictionaries and possibly keep alive a reference to a base array. """ def __init__(self, interface, base=None): self.__array_interface__ = interface self.base = base def as_strided(x, shape=None, strides=None): """ Make an ndarray from the given array with the given shape and strides. """ interface = dict(x.__array_interface__) if shape is not None: interface['shape'] = tuple(shape) if strides is not None: interface['strides'] = tuple(strides) array = np.asarray(DummyArray(interface, base=x)) # Make sure dtype is correct in case of custom dtype if array.dtype.kind == 'V': array.dtype = x.dtype return array def broadcast_arrays(*args): """ Broadcast any number of arrays against each other. Parameters ---------- `*args` : array_likes The arrays to broadcast. Returns ------- broadcasted : list of arrays These arrays are views on the original arrays. They are typically not contiguous. Furthermore, more than one element of a broadcasted array may refer to a single memory location. If you need to write to the arrays, make copies first. Examples -------- >>> x = np.array([[1,2,3]]) >>> y = np.array([[1],[2],[3]]) >>> np.broadcast_arrays(x, y) [array([[1, 2, 3], [1, 2, 3], [1, 2, 3]]), array([[1, 1, 1], [2, 2, 2], [3, 3, 3]])] Here is a useful idiom for getting contiguous copies instead of non-contiguous views. >>> [np.array(a) for a in np.broadcast_arrays(x, y)] [array([[1, 2, 3], [1, 2, 3], [1, 2, 3]]), array([[1, 1, 1], [2, 2, 2], [3, 3, 3]])] """ args = [np.asarray(_m) for _m in args] shapes = [x.shape for x in args] if len(set(shapes)) == 1: # Common case where nothing needs to be broadcasted. return args shapes = [list(s) for s in shapes] strides = [list(x.strides) for x in args] nds = [len(s) for s in shapes] biggest = max(nds) # Go through each array and prepend dimensions of length 1 to each of the # shapes in order to make the number of dimensions equal. for i in range(len(args)): diff = biggest - nds[i] if diff > 0: shapes[i] = [1] * diff + shapes[i] strides[i] = [0] * diff + strides[i] # Chech each dimension for compatibility. A dimension length of 1 is # accepted as compatible with any other length. common_shape = [] for axis in range(biggest): lengths = [s[axis] for s in shapes] unique = set(lengths + [1]) if len(unique) > 2: # There must be at least two non-1 lengths for this axis. raise ValueError("shape mismatch: two or more arrays have " "incompatible dimensions on axis %r." % (axis,)) elif len(unique) == 2: # There is exactly one non-1 length. The common shape will take this # value. unique.remove(1) new_length = unique.pop() common_shape.append(new_length) # For each array, if this axis is being broadcasted from a length of # 1, then set its stride to 0 so that it repeats its data. for i in range(len(args)): if shapes[i][axis] == 1: shapes[i][axis] = new_length strides[i][axis] = 0 else: # Every array has a length of 1 on this axis. Strides can be left # alone as nothing is broadcasted. common_shape.append(1) # Construct the new arrays. broadcasted = [as_strided(x, shape=sh, strides=st) for (x, sh, st) in zip(args, shapes, strides)] return broadcasted numpy-1.8.2/numpy/lib/financial.py0000664000175100017510000005631012370216243020245 0ustar vagrantvagrant00000000000000"""Some simple financial calculations patterned after spreadsheet computations. There is some complexity in each function so that the functions behave like ufuncs with broadcasting and being able to be called with scalars or arrays (or other sequences). """ from __future__ import division, absolute_import, print_function import numpy as np __all__ = ['fv', 'pmt', 'nper', 'ipmt', 'ppmt', 'pv', 'rate', 'irr', 'npv', 'mirr'] _when_to_num = {'end':0, 'begin':1, 'e':0, 'b':1, 0:0, 1:1, 'beginning':1, 'start':1, 'finish':0} def _convert_when(when): #Test to see if when has already been converted to ndarray #This will happen if one function calls another, for example ppmt if isinstance(when, np.ndarray): return when try: return _when_to_num[when] except (KeyError, TypeError): return [_when_to_num[x] for x in when] def fv(rate, nper, pmt, pv, when='end'): """ Compute the future value. Given: * a present value, `pv` * an interest `rate` compounded once per period, of which there are * `nper` total * a (fixed) payment, `pmt`, paid either * at the beginning (`when` = {'begin', 1}) or the end (`when` = {'end', 0}) of each period Return: the value at the end of the `nper` periods Parameters ---------- rate : scalar or array_like of shape(M, ) Rate of interest as decimal (not per cent) per period nper : scalar or array_like of shape(M, ) Number of compounding periods pmt : scalar or array_like of shape(M, ) Payment pv : scalar or array_like of shape(M, ) Present value when : {{'begin', 1}, {'end', 0}}, {string, int}, optional When payments are due ('begin' (1) or 'end' (0)). Defaults to {'end', 0}. Returns ------- out : ndarray Future values. If all input is scalar, returns a scalar float. If any input is array_like, returns future values for each input element. If multiple inputs are array_like, they all must have the same shape. Notes ----- The future value is computed by solving the equation:: fv + pv*(1+rate)**nper + pmt*(1 + rate*when)/rate*((1 + rate)**nper - 1) == 0 or, when ``rate == 0``:: fv + pv + pmt * nper == 0 References ---------- .. [WRW] Wheeler, D. A., E. Rathke, and R. Weir (Eds.) (2009, May). Open Document Format for Office Applications (OpenDocument)v1.2, Part 2: Recalculated Formula (OpenFormula) Format - Annotated Version, Pre-Draft 12. Organization for the Advancement of Structured Information Standards (OASIS). Billerica, MA, USA. [ODT Document]. Available: http://www.oasis-open.org/committees/documents.php?wg_abbrev=office-formula OpenDocument-formula-20090508.odt Examples -------- What is the future value after 10 years of saving $100 now, with an additional monthly savings of $100. Assume the interest rate is 5% (annually) compounded monthly? >>> np.fv(0.05/12, 10*12, -100, -100) 15692.928894335748 By convention, the negative sign represents cash flow out (i.e. money not available today). Thus, saving $100 a month at 5% annual interest leads to $15,692.93 available to spend in 10 years. If any input is array_like, returns an array of equal shape. Let's compare different interest rates from the example above. >>> a = np.array((0.05, 0.06, 0.07))/12 >>> np.fv(a, 10*12, -100, -100) array([ 15692.92889434, 16569.87435405, 17509.44688102]) """ when = _convert_when(when) (rate, nper, pmt, pv, when) = map(np.asarray, [rate, nper, pmt, pv, when]) temp = (1+rate)**nper miter = np.broadcast(rate, nper, pmt, pv, when) zer = np.zeros(miter.shape) fact = np.where(rate==zer, nper+zer, (1+rate*when)*(temp-1)/rate+zer) return -(pv*temp + pmt*fact) def pmt(rate, nper, pv, fv=0, when='end'): """ Compute the payment against loan principal plus interest. Given: * a present value, `pv` (e.g., an amount borrowed) * a future value, `fv` (e.g., 0) * an interest `rate` compounded once per period, of which there are * `nper` total * and (optional) specification of whether payment is made at the beginning (`when` = {'begin', 1}) or the end (`when` = {'end', 0}) of each period Return: the (fixed) periodic payment. Parameters ---------- rate : array_like Rate of interest (per period) nper : array_like Number of compounding periods pv : array_like Present value fv : array_like (optional) Future value (default = 0) when : {{'begin', 1}, {'end', 0}}, {string, int} When payments are due ('begin' (1) or 'end' (0)) Returns ------- out : ndarray Payment against loan plus interest. If all input is scalar, returns a scalar float. If any input is array_like, returns payment for each input element. If multiple inputs are array_like, they all must have the same shape. Notes ----- The payment is computed by solving the equation:: fv + pv*(1 + rate)**nper + pmt*(1 + rate*when)/rate*((1 + rate)**nper - 1) == 0 or, when ``rate == 0``:: fv + pv + pmt * nper == 0 for ``pmt``. Note that computing a monthly mortgage payment is only one use for this function. For example, pmt returns the periodic deposit one must make to achieve a specified future balance given an initial deposit, a fixed, periodically compounded interest rate, and the total number of periods. References ---------- .. [WRW] Wheeler, D. A., E. Rathke, and R. Weir (Eds.) (2009, May). Open Document Format for Office Applications (OpenDocument)v1.2, Part 2: Recalculated Formula (OpenFormula) Format - Annotated Version, Pre-Draft 12. Organization for the Advancement of Structured Information Standards (OASIS). Billerica, MA, USA. [ODT Document]. Available: http://www.oasis-open.org/committees/documents.php ?wg_abbrev=office-formulaOpenDocument-formula-20090508.odt Examples -------- What is the monthly payment needed to pay off a $200,000 loan in 15 years at an annual interest rate of 7.5%? >>> np.pmt(0.075/12, 12*15, 200000) -1854.0247200054619 In order to pay-off (i.e., have a future-value of 0) the $200,000 obtained today, a monthly payment of $1,854.02 would be required. Note that this example illustrates usage of `fv` having a default value of 0. """ when = _convert_when(when) (rate, nper, pv, fv, when) = map(np.asarray, [rate, nper, pv, fv, when]) temp = (1+rate)**nper miter = np.broadcast(rate, nper, pv, fv, when) zer = np.zeros(miter.shape) fact = np.where(rate==zer, nper+zer, (1+rate*when)*(temp-1)/rate+zer) return -(fv + pv*temp) / fact def nper(rate, pmt, pv, fv=0, when='end'): """ Compute the number of periodic payments. Parameters ---------- rate : array_like Rate of interest (per period) pmt : array_like Payment pv : array_like Present value fv : array_like, optional Future value when : {{'begin', 1}, {'end', 0}}, {string, int}, optional When payments are due ('begin' (1) or 'end' (0)) Notes ----- The number of periods ``nper`` is computed by solving the equation:: fv + pv*(1+rate)**nper + pmt*(1+rate*when)/rate*((1+rate)**nper-1) = 0 but if ``rate = 0`` then:: fv + pv + pmt*nper = 0 Examples -------- If you only had $150/month to pay towards the loan, how long would it take to pay-off a loan of $8,000 at 7% annual interest? >>> print round(np.nper(0.07/12, -150, 8000), 5) 64.07335 So, over 64 months would be required to pay off the loan. The same analysis could be done with several different interest rates and/or payments and/or total amounts to produce an entire table. >>> np.nper(*(np.ogrid[0.07/12: 0.08/12: 0.01/12, ... -150 : -99 : 50 , ... 8000 : 9001 : 1000])) array([[[ 64.07334877, 74.06368256], [ 108.07548412, 127.99022654]], [[ 66.12443902, 76.87897353], [ 114.70165583, 137.90124779]]]) """ when = _convert_when(when) (rate, pmt, pv, fv, when) = map(np.asarray, [rate, pmt, pv, fv, when]) use_zero_rate = False with np.errstate(divide="raise"): try: z = pmt*(1.0+rate*when)/rate except FloatingPointError: use_zero_rate = True if use_zero_rate: return (-fv + pv) / (pmt + 0.0) else: A = -(fv + pv)/(pmt+0.0) B = np.log((-fv+z) / (pv+z))/np.log(1.0+rate) miter = np.broadcast(rate, pmt, pv, fv, when) zer = np.zeros(miter.shape) return np.where(rate==zer, A+zer, B+zer) + 0.0 def ipmt(rate, per, nper, pv, fv=0.0, when='end'): """ Compute the interest portion of a payment. Parameters ---------- rate : scalar or array_like of shape(M, ) Rate of interest as decimal (not per cent) per period per : scalar or array_like of shape(M, ) Interest paid against the loan changes during the life or the loan. The `per` is the payment period to calculate the interest amount. nper : scalar or array_like of shape(M, ) Number of compounding periods pv : scalar or array_like of shape(M, ) Present value fv : scalar or array_like of shape(M, ), optional Future value when : {{'begin', 1}, {'end', 0}}, {string, int}, optional When payments are due ('begin' (1) or 'end' (0)). Defaults to {'end', 0}. Returns ------- out : ndarray Interest portion of payment. If all input is scalar, returns a scalar float. If any input is array_like, returns interest payment for each input element. If multiple inputs are array_like, they all must have the same shape. See Also -------- ppmt, pmt, pv Notes ----- The total payment is made up of payment against principal plus interest. ``pmt = ppmt + ipmt`` Examples -------- What is the amortization schedule for a 1 year loan of $2500 at 8.24% interest per year compounded monthly? >>> principal = 2500.00 The 'per' variable represents the periods of the loan. Remember that financial equations start the period count at 1! >>> per = np.arange(1*12) + 1 >>> ipmt = np.ipmt(0.0824/12, per, 1*12, principal) >>> ppmt = np.ppmt(0.0824/12, per, 1*12, principal) Each element of the sum of the 'ipmt' and 'ppmt' arrays should equal 'pmt'. >>> pmt = np.pmt(0.0824/12, 1*12, principal) >>> np.allclose(ipmt + ppmt, pmt) True >>> fmt = '{0:2d} {1:8.2f} {2:8.2f} {3:8.2f}' >>> for payment in per: ... index = payment - 1 ... principal = principal + ppmt[index] ... print fmt.format(payment, ppmt[index], ipmt[index], principal) 1 -200.58 -17.17 2299.42 2 -201.96 -15.79 2097.46 3 -203.35 -14.40 1894.11 4 -204.74 -13.01 1689.37 5 -206.15 -11.60 1483.22 6 -207.56 -10.18 1275.66 7 -208.99 -8.76 1066.67 8 -210.42 -7.32 856.25 9 -211.87 -5.88 644.38 10 -213.32 -4.42 431.05 11 -214.79 -2.96 216.26 12 -216.26 -1.49 -0.00 >>> interestpd = np.sum(ipmt) >>> np.round(interestpd, 2) -112.98 """ when = _convert_when(when) rate, per, nper, pv, fv, when = np.broadcast_arrays(rate, per, nper, pv, fv, when) total_pmt = pmt(rate, nper, pv, fv, when) ipmt = _rbl(rate, per, total_pmt, pv, when)*rate try: ipmt = np.where(when == 1, ipmt/(1 + rate), ipmt) ipmt = np.where(np.logical_and(when == 1, per == 1), 0.0, ipmt) except IndexError: pass return ipmt def _rbl(rate, per, pmt, pv, when): """ This function is here to simply have a different name for the 'fv' function to not interfere with the 'fv' keyword argument within the 'ipmt' function. It is the 'remaining balance on loan' which might be useful as it's own function, but is easily calculated with the 'fv' function. """ return fv(rate, (per - 1), pmt, pv, when) def ppmt(rate, per, nper, pv, fv=0.0, when='end'): """ Compute the payment against loan principal. Parameters ---------- rate : array_like Rate of interest (per period) per : array_like, int Amount paid against the loan changes. The `per` is the period of interest. nper : array_like Number of compounding periods pv : array_like Present value fv : array_like, optional Future value when : {{'begin', 1}, {'end', 0}}, {string, int} When payments are due ('begin' (1) or 'end' (0)) See Also -------- pmt, pv, ipmt """ total = pmt(rate, nper, pv, fv, when) return total - ipmt(rate, per, nper, pv, fv, when) def pv(rate, nper, pmt, fv=0.0, when='end'): """ Compute the present value. Given: * a future value, `fv` * an interest `rate` compounded once per period, of which there are * `nper` total * a (fixed) payment, `pmt`, paid either * at the beginning (`when` = {'begin', 1}) or the end (`when` = {'end', 0}) of each period Return: the value now Parameters ---------- rate : array_like Rate of interest (per period) nper : array_like Number of compounding periods pmt : array_like Payment fv : array_like, optional Future value when : {{'begin', 1}, {'end', 0}}, {string, int}, optional When payments are due ('begin' (1) or 'end' (0)) Returns ------- out : ndarray, float Present value of a series of payments or investments. Notes ----- The present value is computed by solving the equation:: fv + pv*(1 + rate)**nper + pmt*(1 + rate*when)/rate*((1 + rate)**nper - 1) = 0 or, when ``rate = 0``:: fv + pv + pmt * nper = 0 for `pv`, which is then returned. References ---------- .. [WRW] Wheeler, D. A., E. Rathke, and R. Weir (Eds.) (2009, May). Open Document Format for Office Applications (OpenDocument)v1.2, Part 2: Recalculated Formula (OpenFormula) Format - Annotated Version, Pre-Draft 12. Organization for the Advancement of Structured Information Standards (OASIS). Billerica, MA, USA. [ODT Document]. Available: http://www.oasis-open.org/committees/documents.php?wg_abbrev=office-formula OpenDocument-formula-20090508.odt Examples -------- What is the present value (e.g., the initial investment) of an investment that needs to total $15692.93 after 10 years of saving $100 every month? Assume the interest rate is 5% (annually) compounded monthly. >>> np.pv(0.05/12, 10*12, -100, 15692.93) -100.00067131625819 By convention, the negative sign represents cash flow out (i.e., money not available today). Thus, to end up with $15,692.93 in 10 years saving $100 a month at 5% annual interest, one's initial deposit should also be $100. If any input is array_like, ``pv`` returns an array of equal shape. Let's compare different interest rates in the example above: >>> a = np.array((0.05, 0.04, 0.03))/12 >>> np.pv(a, 10*12, -100, 15692.93) array([ -100.00067132, -649.26771385, -1273.78633713]) So, to end up with the same $15692.93 under the same $100 per month "savings plan," for annual interest rates of 4% and 3%, one would need initial investments of $649.27 and $1273.79, respectively. """ when = _convert_when(when) (rate, nper, pmt, fv, when) = map(np.asarray, [rate, nper, pmt, fv, when]) temp = (1+rate)**nper miter = np.broadcast(rate, nper, pmt, fv, when) zer = np.zeros(miter.shape) fact = np.where(rate == zer, nper+zer, (1+rate*when)*(temp-1)/rate+zer) return -(fv + pmt*fact)/temp # Computed with Sage # (y + (r + 1)^n*x + p*((r + 1)^n - 1)*(r*w + 1)/r)/(n*(r + 1)^(n - 1)*x - p*((r + 1)^n - 1)*(r*w + 1)/r^2 + n*p*(r + 1)^(n - 1)*(r*w + 1)/r + p*((r + 1)^n - 1)*w/r) def _g_div_gp(r, n, p, x, y, w): t1 = (r+1)**n t2 = (r+1)**(n-1) return (y + t1*x + p*(t1 - 1)*(r*w + 1)/r)/(n*t2*x - p*(t1 - 1)*(r*w + 1)/(r**2) + n*p*t2*(r*w + 1)/r + p*(t1 - 1)*w/r) # Use Newton's iteration until the change is less than 1e-6 # for all values or a maximum of 100 iterations is reached. # Newton's rule is # r_{n+1} = r_{n} - g(r_n)/g'(r_n) # where # g(r) is the formula # g'(r) is the derivative with respect to r. def rate(nper, pmt, pv, fv, when='end', guess=0.10, tol=1e-6, maxiter=100): """ Compute the rate of interest per period. Parameters ---------- nper : array_like Number of compounding periods pmt : array_like Payment pv : array_like Present value fv : array_like Future value when : {{'begin', 1}, {'end', 0}}, {string, int}, optional When payments are due ('begin' (1) or 'end' (0)) guess : float, optional Starting guess for solving the rate of interest tol : float, optional Required tolerance for the solution maxiter : int, optional Maximum iterations in finding the solution Notes ----- The rate of interest is computed by iteratively solving the (non-linear) equation:: fv + pv*(1+rate)**nper + pmt*(1+rate*when)/rate * ((1+rate)**nper - 1) = 0 for ``rate``. References ---------- Wheeler, D. A., E. Rathke, and R. Weir (Eds.) (2009, May). Open Document Format for Office Applications (OpenDocument)v1.2, Part 2: Recalculated Formula (OpenFormula) Format - Annotated Version, Pre-Draft 12. Organization for the Advancement of Structured Information Standards (OASIS). Billerica, MA, USA. [ODT Document]. Available: http://www.oasis-open.org/committees/documents.php?wg_abbrev=office-formula OpenDocument-formula-20090508.odt """ when = _convert_when(when) (nper, pmt, pv, fv, when) = map(np.asarray, [nper, pmt, pv, fv, when]) rn = guess iter = 0 close = False while (iter < maxiter) and not close: rnp1 = rn - _g_div_gp(rn, nper, pmt, pv, fv, when) diff = abs(rnp1-rn) close = np.all(diff>> 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]) 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 rate = rate.item(np.argmin(np.abs(rate))) return rate def npv(rate, values): """ Returns the NPV (Net Present Value) of a cash flow series. Parameters ---------- rate : scalar The discount rate. values : array_like, shape(M, ) The values of the time series of cash flows. The (fixed) time interval between cash flow "events" must be the same as that for which `rate` is given (i.e., if `rate` is per year, then precisely a year is understood to elapse between each cash flow event). By convention, investments or "deposits" are negative, income or "withdrawals" are positive; `values` must begin with the initial investment, thus `values[0]` will typically be negative. Returns ------- out : float The NPV of the input cash flow series `values` at the discount `rate`. Notes ----- Returns the result of: [G]_ .. math :: \\sum_{t=0}^{M-1}{\\frac{values_t}{(1+rate)^{t}}} References ---------- .. [G] L. J. Gitman, "Principles of Managerial Finance, Brief," 3rd ed., Addison-Wesley, 2003, pg. 346. Examples -------- >>> np.npv(0.281,[-100, 39, 59, 55, 20]) -0.0084785916384548798 (Compare with the Example given for numpy.lib.financial.irr) """ values = np.asarray(values) return (values / (1+rate)**np.arange(0, len(values))).sum(axis=0) def mirr(values, finance_rate, reinvest_rate): """ Modified internal rate of return. Parameters ---------- values : array_like Cash flows (must contain at least one positive and one negative value) or nan is returned. The first value is considered a sunk cost at time zero. finance_rate : scalar Interest rate paid on the cash flows reinvest_rate : scalar Interest rate received on the cash flows upon reinvestment Returns ------- out : float Modified internal rate of return """ values = np.asarray(values, dtype=np.double) n = values.size pos = values > 0 neg = values < 0 if not (pos.any() and neg.any()): return np.nan numer = np.abs(npv(reinvest_rate, values*pos)) denom = np.abs(npv(finance_rate, values*neg)) return (numer/denom)**(1.0/(n - 1))*(1 + reinvest_rate) - 1 if __name__ == '__main__': import doctest import numpy as np doctest.testmod(verbose=True) numpy-1.8.2/numpy/lib/format.py0000664000175100017510000005151212370216243017610 0ustar vagrantvagrant00000000000000""" Define a simple format for saving numpy arrays to disk with the full information about them. The ``.npy`` format is the standard binary file format in NumPy for persisting a *single* arbitrary NumPy array on disk. The format stores all of the shape and dtype information necessary to reconstruct the array correctly even on another machine with a different architecture. The format is designed to be as simple as possible while achieving its limited goals. The ``.npz`` format is the standard format for persisting *multiple* NumPy arrays on disk. A ``.npz`` file is a zip file containing multiple ``.npy`` files, one for each array. Capabilities ------------ - Can represent all NumPy arrays including nested record arrays and object arrays. - Represents the data in its native binary form. - Supports Fortran-contiguous arrays directly. - Stores all of the necessary information to reconstruct the array including shape and dtype on a machine of a different architecture. Both little-endian and big-endian arrays are supported, and a file with little-endian numbers will yield a little-endian array on any machine reading the file. The types are described in terms of their actual sizes. For example, if a machine with a 64-bit C "long int" writes out an array with "long ints", a reading machine with 32-bit C "long ints" will yield an array with 64-bit integers. - Is straightforward to reverse engineer. Datasets often live longer than the programs that created them. A competent developer should be able to create a solution in his preferred programming language to read most ``.npy`` files that he has been given without much documentation. - Allows memory-mapping of the data. See `open_memmep`. - Can be read from a filelike stream object instead of an actual file. - Stores object arrays, i.e. arrays containing elements that are arbitrary Python objects. Files with object arrays are not to be mmapable, but can be read and written to disk. Limitations ----------- - Arbitrary subclasses of numpy.ndarray are not completely preserved. Subclasses will be accepted for writing, but only the array data will be written out. A regular numpy.ndarray object will be created upon reading the file. .. warning:: Due to limitations in the interpretation of structured dtypes, dtypes with fields with empty names will have the names replaced by 'f0', 'f1', etc. Such arrays will not round-trip through the format entirely accurately. The data is intact; only the field names will differ. We are working on a fix for this. This fix will not require a change in the file format. The arrays with such structures can still be saved and restored, and the correct dtype may be restored by using the ``loadedarray.view(correct_dtype)`` method. File extensions --------------- We recommend using the ``.npy`` and ``.npz`` extensions for files saved in this format. This is by no means a requirement; applications may wish to use these file formats but use an extension specific to the application. In the absence of an obvious alternative, however, we suggest using ``.npy`` and ``.npz``. Version numbering ----------------- The version numbering of these formats is independent of NumPy version numbering. If the format is upgraded, the code in `numpy.io` will still be able to read and write Version 1.0 files. Format Version 1.0 ------------------ The first 6 bytes are a magic string: exactly ``\\x93NUMPY``. The next 1 byte is an unsigned byte: the major version number of the file format, e.g. ``\\x01``. The next 1 byte is an unsigned byte: the minor version number of the file format, e.g. ``\\x00``. Note: the version of the file format is not tied to the version of the numpy package. The next 2 bytes form a little-endian unsigned short int: the length of the header data HEADER_LEN. The next HEADER_LEN bytes form the header data describing the array's format. It is an ASCII string which contains a Python literal expression of a dictionary. It is terminated by a newline (``\\n``) and padded with spaces (``\\x20``) to make the total length of ``magic string + 4 + HEADER_LEN`` be evenly divisible by 16 for alignment purposes. The dictionary contains three keys: "descr" : dtype.descr An object that can be passed as an argument to the `numpy.dtype` constructor to create the array's dtype. "fortran_order" : bool Whether the array data is Fortran-contiguous or not. Since Fortran-contiguous arrays are a common form of non-C-contiguity, we allow them to be written directly to disk for efficiency. "shape" : tuple of int The shape of the array. For repeatability and readability, the dictionary keys are sorted in alphabetic order. This is for convenience only. A writer SHOULD implement this if possible. A reader MUST NOT depend on this. Following the header comes the array data. If the dtype contains Python objects (i.e. ``dtype.hasobject is True``), then the data is a Python pickle of the array. Otherwise the data is the contiguous (either C- or Fortran-, depending on ``fortran_order``) bytes of the array. Consumers can figure out the number of bytes by multiplying the number of elements given by the shape (noting that ``shape=()`` means there is 1 element) by ``dtype.itemsize``. Notes ----- The ``.npy`` format, including reasons for creating it and a comparison of alternatives, is described fully in the "npy-format" NEP. """ from __future__ import division, absolute_import, print_function import numpy import sys import io from numpy.lib.utils import safe_eval from numpy.compat import asbytes, isfileobj, long, basestring if sys.version_info[0] >= 3: import pickle else: import cPickle as pickle MAGIC_PREFIX = asbytes('\x93NUMPY') MAGIC_LEN = len(MAGIC_PREFIX) + 2 BUFFER_SIZE = 2 ** 18 #size of buffer for reading npz files in bytes def magic(major, minor): """ Return the magic string for the given file format version. Parameters ---------- major : int in [0, 255] minor : int in [0, 255] Returns ------- magic : str Raises ------ ValueError if the version cannot be formatted. """ if major < 0 or major > 255: raise ValueError("major version must be 0 <= major < 256") if minor < 0 or minor > 255: raise ValueError("minor version must be 0 <= minor < 256") if sys.version_info[0] < 3: return MAGIC_PREFIX + chr(major) + chr(minor) else: return MAGIC_PREFIX + bytes([major, minor]) def read_magic(fp): """ Read the magic string to get the version of the file format. Parameters ---------- fp : filelike object Returns ------- major : int minor : int """ magic_str = _read_bytes(fp, MAGIC_LEN, "magic string") if magic_str[:-2] != MAGIC_PREFIX: msg = "the magic string is not correct; expected %r, got %r" raise ValueError(msg % (MAGIC_PREFIX, magic_str[:-2])) if sys.version_info[0] < 3: major, minor = map(ord, magic_str[-2:]) else: major, minor = magic_str[-2:] return major, minor def dtype_to_descr(dtype): """ Get a serializable descriptor from the dtype. The .descr attribute of a dtype object cannot be round-tripped through the dtype() constructor. Simple types, like dtype('float32'), have a descr which looks like a record array with one field with '' as a name. The dtype() constructor interprets this as a request to give a default name. Instead, we construct descriptor that can be passed to dtype(). Parameters ---------- dtype : dtype The dtype of the array that will be written to disk. Returns ------- descr : object An object that can be passed to `numpy.dtype()` in order to replicate the input dtype. """ if dtype.names is not None: # This is a record array. The .descr is fine. # XXX: parts of the record array with an empty name, like padding bytes, # still get fiddled with. This needs to be fixed in the C implementation # of dtype(). return dtype.descr else: return dtype.str def header_data_from_array_1_0(array): """ Get the dictionary of header metadata from a numpy.ndarray. Parameters ---------- array : numpy.ndarray Returns ------- d : dict This has the appropriate entries for writing its string representation to the header of the file. """ d = {} d['shape'] = array.shape if array.flags.c_contiguous: d['fortran_order'] = False elif array.flags.f_contiguous: d['fortran_order'] = True else: # Totally non-contiguous data. We will have to make it C-contiguous # before writing. Note that we need to test for C_CONTIGUOUS first # because a 1-D array is both C_CONTIGUOUS and F_CONTIGUOUS. d['fortran_order'] = False 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. Parameters ---------- fp : filelike object d : dict This has the appropriate entries for writing its string representation to the header of the file. """ import struct header = ["{"] for key, value in sorted(d.items()): # Need to use repr here, since we eval these when reading header.append("'%s': %s, " % (key, repr(value))) header.append("}") header = "".join(header) # Pad the header with spaces and a final newline such that the magic # string, the header-length short and the header are aligned on a 16-byte # boundary. Hopefully, some system, possibly memory-mapping, can take # advantage of our premature optimization. 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('>> np.iterable([1, 2, 3]) 1 >>> np.iterable(2) 0 """ try: iter(y) except: return 0 return 1 def histogram(a, bins=10, range=None, normed=False, weights=None, density=None): """ Compute the histogram of a set of data. Parameters ---------- a : array_like Input data. The histogram is computed over the flattened array. bins : int or sequence of scalars, optional If `bins` is an int, it defines the number of equal-width bins in the given range (10, by default). If `bins` is a sequence, it defines the bin edges, including the rightmost edge, allowing for non-uniform bin widths. range : (float, float), optional The lower and upper range of the bins. If not provided, range is simply ``(a.min(), a.max())``. Values outside the range are ignored. normed : bool, optional This keyword is deprecated in Numpy 1.6 due to confusing/buggy behavior. It will be removed in Numpy 2.0. Use the density keyword instead. If False, the result will contain the number of samples in each bin. If True, the result is the value of the probability *density* function at the bin, normalized such that the *integral* over the range is 1. Note that this latter behavior is known to be buggy with unequal bin widths; use `density` instead. weights : array_like, optional An array of weights, of the same shape as `a`. Each value in `a` only contributes its associated weight towards the bin count (instead of 1). If `normed` is True, the weights are normalized, so that the integral of the density over the range remains 1 density : bool, optional If False, the result will contain the number of samples in each bin. If True, the result is the value of the probability *density* function at the bin, normalized such that the *integral* over the range is 1. Note that the sum of the histogram values will not be equal to 1 unless bins of unity width are chosen; it is not a probability *mass* function. Overrides the `normed` keyword if given. Returns ------- hist : array The values of the histogram. See `normed` and `weights` for a description of the possible semantics. bin_edges : array of dtype float Return the bin edges ``(length(hist)+1)``. See Also -------- histogramdd, bincount, searchsorted, digitize Notes ----- All but the last (righthand-most) bin is half-open. In other words, if `bins` is:: [1, 2, 3, 4] then the first bin is ``[1, 2)`` (including 1, but excluding 2) and the second ``[2, 3)``. The last bin, however, is ``[3, 4]``, which *includes* 4. Examples -------- >>> np.histogram([1, 2, 1], bins=[0, 1, 2, 3]) (array([0, 2, 1]), array([0, 1, 2, 3])) >>> np.histogram(np.arange(4), bins=np.arange(5), density=True) (array([ 0.25, 0.25, 0.25, 0.25]), array([0, 1, 2, 3, 4])) >>> np.histogram([[1, 2, 1], [1, 0, 1]], bins=[0,1,2,3]) (array([1, 4, 1]), array([0, 1, 2, 3])) >>> a = np.arange(5) >>> hist, bin_edges = np.histogram(a, density=True) >>> hist array([ 0.5, 0. , 0.5, 0. , 0. , 0.5, 0. , 0.5, 0. , 0.5]) >>> hist.sum() 2.4999999999999996 >>> np.sum(hist*np.diff(bin_edges)) 1.0 """ a = asarray(a) if weights is not None: weights = asarray(weights) if np.any(weights.shape != a.shape): raise ValueError( 'weights should have the same shape as a.') weights = weights.ravel() a = a.ravel() if (range is not None): mn, mx = range if (mn > mx): raise AttributeError( 'max must be larger than min in range parameter.') if not iterable(bins): if np.isscalar(bins) and bins < 1: raise ValueError("`bins` should be a positive integer.") if range is None: if a.size == 0: # handle empty arrays. Can't determine range, so use 0-1. range = (0, 1) else: range = (a.min(), a.max()) mn, mx = [mi+0.0 for mi in range] if mn == mx: mn -= 0.5 mx += 0.5 bins = linspace(mn, mx, bins+1, endpoint=True) else: bins = asarray(bins) if (np.diff(bins) < 0).any(): raise AttributeError( 'bins must increase monotonically.') # Histogram is an integer or a float array depending on the weights. if weights is None: ntype = int else: ntype = weights.dtype n = np.zeros(bins.shape, ntype) block = 65536 if weights is None: for i in arange(0, len(a), block): sa = sort(a[i:i+block]) n += np.r_[sa.searchsorted(bins[:-1], 'left'), \ sa.searchsorted(bins[-1], 'right')] else: zero = array(0, dtype=ntype) for i in arange(0, len(a), block): tmp_a = a[i:i+block] tmp_w = weights[i:i+block] sorting_index = np.argsort(tmp_a) sa = tmp_a[sorting_index] sw = tmp_w[sorting_index] cw = np.concatenate(([zero,], sw.cumsum())) bin_index = np.r_[sa.searchsorted(bins[:-1], 'left'), \ sa.searchsorted(bins[-1], 'right')] n += cw[bin_index] n = np.diff(n) if density is not None: if density: db = array(np.diff(bins), float) return n/db/n.sum(), bins else: return n, bins else: # deprecated, buggy behavior. Remove for Numpy 2.0 if normed: db = array(np.diff(bins), float) return n/(n*db).sum(), bins else: return n, bins def histogramdd(sample, bins=10, range=None, normed=False, weights=None): """ Compute the multidimensional histogram of some data. Parameters ---------- sample : array_like The data to be histogrammed. It must be an (N,D) array or data that can be converted to such. The rows of the resulting array are the coordinates of points in a D dimensional polytope. bins : sequence or int, optional The bin specification: * A sequence of arrays describing the bin edges along each dimension. * The number of bins for each dimension (nx, ny, ... =bins) * The number of bins for all dimensions (nx=ny=...=bins). range : sequence, optional A sequence of lower and upper bin edges to be used if the edges are 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 ``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. Returns ------- H : ndarray 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. See Also -------- histogram: 1-D histogram histogram2d: 2-D histogram Examples -------- >>> r = np.random.randn(100,3) >>> H, edges = np.histogramdd(r, bins = (5, 8, 4)) >>> H.shape, edges[0].size, edges[1].size, edges[2].size ((5, 8, 4), 6, 9, 5) """ try: # Sample is an ND-array. N, D = sample.shape except (AttributeError, ValueError): # Sample is a sequence of 1D arrays. sample = atleast_2d(sample).T N, D = sample.shape nbin = empty(D, int) edges = D*[None] dedges = D*[None] if weights is not None: weights = asarray(weights) try: M = len(bins) if M != D: raise AttributeError( 'The dimension of bins must be equal'\ ' to the dimension of the sample x.') except TypeError: # bins is an integer bins = D*[bins] # Select range for each dimension # Used only if number of bins is given. if range is None: # Handle empty input. Range can't be determined in that case, use 0-1. if N == 0: smin = zeros(D) smax = ones(D) else: smin = atleast_1d(array(sample.min(0), float)) smax = atleast_1d(array(sample.max(0), float)) else: smin = zeros(D) smax = zeros(D) for i in arange(D): smin[i], smax[i] = range[i] # Make sure the bins have a finite width. for i in arange(len(smin)): if smin[i] == smax[i]: smin[i] = smin[i] - .5 smax[i] = smax[i] + .5 # Create edge arrays for i in arange(D): if isscalar(bins[i]): if bins[i] < 1: raise ValueError("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) else: edges[i] = asarray(bins[i], float) nbin[i] = len(edges[i])+1 # +1 for outlier bins dedges[i] = diff(edges[i]) if np.any(np.asarray(dedges[i]) <= 0): raise ValueError(""" Found bin edge of size <= 0. Did you specify `bins` with non-monotonic sequence?""") nbin = asarray(nbin) # Handle empty input. if N == 0: return np.zeros(nbin-2), edges # Compute the bin number each sample falls into. Ncount = {} for i in arange(D): Ncount[i] = digitize(sample[:, i], edges[i]) # Using digitize, values that fall on an edge are put in the right bin. # For the rightmost bin, we want values equal to the right # edge to be counted in the last bin, and not as an outlier. for i in arange(D): # Rounding precision mindiff = dedges[i].min() if not np.isinf(mindiff): decimal = int(-log10(mindiff)) + 6 # Find which points are on the rightmost edge. 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][where(on_edge & not_smaller_than_edge)[0]] -= 1 # Flattened histogram matrix (1D) # Reshape is used so that overlarge arrays # will raise an error. hist = zeros(nbin, float).reshape(-1) # Compute the sample indices in the flattened histogram matrix. ni = nbin.argsort() xy = zeros(N, int) for i in arange(0, D-1): xy += Ncount[ni[i]] * nbin[ni[i+1:]].prod() xy += Ncount[ni[-1]] # Compute the number of repetitions in xy and assign it to the # flattened histmat. if len(xy) == 0: return zeros(nbin-2, int), edges flatcount = bincount(xy, weights) a = arange(len(flatcount)) hist[a] = flatcount # Shape into a proper matrix hist = hist.reshape(sort(nbin)) for i in arange(nbin.size): j = ni.argsort()[i] hist = hist.swapaxes(i, j) ni[i], ni[j] = ni[j], ni[i] # Remove outliers (indices 0 and -1 for each dimension). core = D*[slice(1, -1)] hist = hist[core] # Normalize if normed is True if normed: s = hist.sum() for i in arange(D): shape = ones(D, int) shape[i] = nbin[i] - 2 hist = hist / dedges[i].reshape(shape) hist /= s if (hist.shape != nbin - 2).any(): raise RuntimeError( "Internal Shape Error") return hist, edges def average(a, axis=None, weights=None, returned=False): """ Compute the weighted average along the specified axis. Parameters ---------- a : array_like Array containing data to be averaged. If `a` is not an array, a conversion is attempted. axis : int, optional Axis along which to average `a`. If `None`, averaging is done over the flattened array. weights : array_like, optional An array of weights associated with the values in `a`. Each value in `a` contributes to the average according to its associated weight. The weights array can either be 1-D (in which case its length must be the size of `a` along the given axis) or of the same shape as `a`. If `weights=None`, then all data in `a` are assumed to have a weight equal to one. returned : bool, optional Default is `False`. If `True`, the tuple (`average`, `sum_of_weights`) is returned, otherwise only the average is returned. If `weights=None`, `sum_of_weights` is equivalent to the number of elements over which the average is taken. Returns ------- average, [sum_of_weights] : {array_type, double} Return the average along the specified axis. When returned is `True`, return a tuple with the average as the first element and the sum of the weights as the second element. The return type is `Float` if `a` is of integer type, otherwise it is of the same type as `a`. `sum_of_weights` is of the same type as `average`. Raises ------ ZeroDivisionError When all weights along axis are zero. See `numpy.ma.average` for a version robust to this type of error. TypeError When the length of 1D `weights` is not the same as the shape of `a` along axis. See Also -------- mean ma.average : average for masked arrays -- useful if your data contains "missing" values Examples -------- >>> data = range(1,5) >>> data [1, 2, 3, 4] >>> np.average(data) 2.5 >>> np.average(range(1,11), weights=range(10,0,-1)) 4.0 >>> data = np.arange(6).reshape((3,2)) >>> data array([[0, 1], [2, 3], [4, 5]]) >>> np.average(data, axis=1, weights=[1./4, 3./4]) array([ 0.75, 2.75, 4.75]) >>> np.average(data, weights=[1./4, 3./4]) Traceback (most recent call last): ... TypeError: Axis must be specified when shapes of a and weights differ. """ if not isinstance(a, np.matrix) : a = np.asarray(a) if weights is None : avg = a.mean(axis) scl = avg.dtype.type(a.size/avg.size) else : a = a + 0.0 wgt = np.array(weights, dtype=a.dtype, copy=0) # Sanity checks if a.shape != wgt.shape : if axis is None : raise TypeError( "Axis must be specified when shapes of a "\ "and weights differ.") if wgt.ndim != 1 : raise TypeError( "1D weights expected when shapes of a and "\ "weights differ.") if wgt.shape[0] != a.shape[axis] : raise ValueError( "Length of weights not compatible with "\ "specified axis.") # setup wgt to broadcast along axis wgt = np.array(wgt, copy=0, ndmin=a.ndim).swapaxes(-1, axis) scl = wgt.sum(axis=axis) if (scl == 0.0).any(): raise ZeroDivisionError( "Weights sum to zero, can't be normalized") avg = np.multiply(a, wgt).sum(axis)/scl if returned: scl = np.multiply(avg, 0) + scl return avg, scl else: return avg def asarray_chkfinite(a, dtype=None, order=None): """ Convert the input to an array, checking for NaNs or Infs. Parameters ---------- a : array_like Input data, in any form that can be converted to an array. This includes lists, lists of tuples, tuples, tuples of tuples, tuples of lists and ndarrays. Success requires no NaNs or Infs. dtype : data-type, optional By default, the data-type is inferred from the input data. order : {'C', 'F'}, optional Whether to use row-major ('C') or column-major ('FORTRAN') memory representation. Defaults to 'C'. Returns ------- out : ndarray Array interpretation of `a`. No copy is performed if the input is already an ndarray. If `a` is a subclass of ndarray, a base class ndarray is returned. Raises ------ ValueError Raises ValueError if `a` contains NaN (Not a Number) or Inf (Infinity). See Also -------- asarray : Create and array. asanyarray : Similar function which passes through subclasses. ascontiguousarray : Convert input to a contiguous array. asfarray : Convert input to a floating point ndarray. asfortranarray : Convert input to an ndarray with column-major memory order. fromiter : Create an array from an iterator. fromfunction : Construct an array by executing a function on grid positions. Examples -------- Convert a list into an array. If all elements are finite ``asarray_chkfinite`` is identical to ``asarray``. >>> a = [1, 2] >>> np.asarray_chkfinite(a, dtype=float) array([1., 2.]) Raises ValueError if array_like contains Nans or Infs. >>> a = [1, 2, np.inf] >>> try: ... np.asarray_chkfinite(a) ... except ValueError: ... print 'ValueError' ... ValueError """ a = asarray(a, dtype=dtype, order=order) if a.dtype.char in typecodes['AllFloat'] and not np.isfinite(a).all(): raise ValueError( "array must not contain infs or NaNs") return a def piecewise(x, condlist, funclist, *args, **kw): """ Evaluate a piecewise-defined function. Given a set of conditions and corresponding functions, evaluate each function on the input data wherever its condition is true. Parameters ---------- x : ndarray The input domain. condlist : list of bool arrays Each boolean array corresponds to a function in `funclist`. Wherever `condlist[i]` is True, `funclist[i](x)` is used as the output value. Each boolean array in `condlist` selects a piece of `x`, and should therefore be of the same shape as `x`. The length of `condlist` must correspond to that of `funclist`. If one extra function is given, i.e. if ``len(funclist) - len(condlist) == 1``, then that extra function is the default value, used wherever all conditions are false. funclist : list of callables, f(x,*args,**kw), or scalars Each function is evaluated over `x` wherever its corresponding condition is True. It should take an array as input and give an array or a scalar value as output. If, instead of a callable, a scalar is provided then a constant function (``lambda x: scalar``) is assumed. args : tuple, optional Any further arguments given to `piecewise` are passed to the functions upon execution, i.e., if called ``piecewise(..., ..., 1, 'a')``, then each function is called as ``f(x, 1, 'a')``. kw : dict, optional Keyword arguments used in calling `piecewise` are passed to the functions upon execution, i.e., if called ``piecewise(..., ..., lambda=1)``, then each function is called as ``f(x, lambda=1)``. Returns ------- out : ndarray 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. See Also -------- choose, select, where Notes ----- This is similar to choose or select, except that functions are evaluated on elements of `x` that satisfy the corresponding condition from `condlist`. The result is:: |-- |funclist[0](x[condlist[0]]) out = |funclist[1](x[condlist[1]]) |... |funclist[n2](x[condlist[n2]]) |-- Examples -------- Define the sigma function, which is -1 for ``x < 0`` and +1 for ``x >= 0``. >>> x = np.linspace(-2.5, 2.5, 6) >>> np.piecewise(x, [x < 0, x >= 0], [-1, 1]) array([-1., -1., -1., 1., 1., 1.]) Define the absolute value, which is ``-x`` for ``x <0`` and ``x`` for ``x >= 0``. >>> np.piecewise(x, [x < 0, x >= 0], [lambda x: -x, lambda x: x]) array([ 2.5, 1.5, 0.5, 0.5, 1.5, 2.5]) """ x = asanyarray(x) n2 = len(funclist) 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] 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 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 y = zeros(x.shape, x.dtype) for k in range(n): item = funclist[k] if not isinstance(item, collections.Callable): y[condlist[k]] = item else: vals = x[condlist[k]] if vals.size > 0: y[condlist[k]] = item(vals, *args, **kw) if zerod: y = y.squeeze() return y def select(condlist, choicelist, default=0): """ Return an array drawn from elements in choicelist, depending on conditions. Parameters ---------- condlist : list of bool ndarrays The list of conditions which determine from which array in `choicelist` the output elements are taken. When multiple conditions are satisfied, the first one encountered in `condlist` is used. choicelist : list of ndarrays The list of arrays from which the output elements are taken. It has to be of the same length as `condlist`. default : scalar, optional The element inserted in `output` when all conditions evaluate to False. Returns ------- output : ndarray The output at position m is the m-th element of the array in `choicelist` where the m-th element of the corresponding array in `condlist` is True. See Also -------- where : Return elements from one of two arrays depending on condition. take, choose, compress, diag, diagonal Examples -------- >>> x = np.arange(10) >>> condlist = [x<3, x>5] >>> choicelist = [x, x**2] >>> np.select(condlist, choicelist) array([ 0, 1, 2, 0, 0, 0, 36, 49, 64, 81]) """ n = len(condlist) n2 = len(choicelist) if n2 != n: 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)) def copy(a, order='K'): """ Return an array copy of the given object. Parameters ---------- a : array_like Input data. order : {'C', 'F', 'A', 'K'}, optional Controls the memory layout of the copy. 'C' means C-order, 'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous, 'C' otherwise. 'K' means match the layout of `a` as closely as possible. (Note that this function and :meth:ndarray.copy are very similar, but have different default values for their order= arguments.) Returns ------- arr : ndarray Array interpretation of `a`. Notes ----- This is equivalent to >>> np.array(a, copy=True) #doctest: +SKIP Examples -------- Create an array x, with a reference y and a copy z: >>> x = np.array([1, 2, 3]) >>> y = x >>> z = np.copy(x) Note that, when we modify x, y changes, but not z: >>> x[0] = 10 >>> x[0] == y[0] True >>> x[0] == z[0] False """ return array(a, order=order, copy=True) # Basic operations def gradient(f, *varargs): """ Return the gradient of an N-dimensional array. The gradient is computed using central differences in the interior and first differences at the boundaries. The returned gradient hence has the same shape as the input array. Parameters ---------- f : array_like An N-dimensional array containing samples of a scalar function. `*varargs` : scalars 0, 1, or N scalars specifying the sample distances in each direction, that is: `dx`, `dy`, `dz`, ... The default distance is 1. Returns ------- gradient : ndarray N arrays of the same shape as `f` giving the derivative of `f` with respect to each dimension. Examples -------- >>> x = np.array([1, 2, 4, 7, 11, 16], dtype=np.float) >>> np.gradient(x) array([ 1. , 1.5, 2.5, 3.5, 4.5, 5. ]) >>> np.gradient(x, 2) array([ 0.5 , 0.75, 1.25, 1.75, 2.25, 2.5 ]) >>> np.gradient(np.array([[1, 2, 6], [3, 4, 5]], dtype=np.float)) [array([[ 2., 2., -1.], [ 2., 2., -1.]]), array([[ 1. , 2.5, 4. ], [ 1. , 1. , 1. ]])] """ f = np.asanyarray(f) N = len(f.shape) # number of dimensions n = len(varargs) if n == 0: dx = [1.0]*N elif n == 1: dx = [varargs[0]]*N elif n == N: dx = list(varargs) else: raise SyntaxError( "invalid number of arguments") # use central differences on interior and first differences on endpoints outvals = [] # create slice objects --- initially all are [:, :, ..., :] slice1 = [slice(None)]*N slice2 = [slice(None)]*N slice3 = [slice(None)]*N otype = f.dtype.char if otype not in ['f', 'd', 'F', 'D', 'm', 'M']: otype = 'd' # Difference of datetime64 elements results in timedelta64 if otype == 'M' : # Need to use the full dtype name because it contains unit information otype = f.dtype.name.replace('datetime', 'timedelta') elif otype == 'm' : # Needs to keep the specific units, can't be a general unit otype = f.dtype for axis in range(N): # select out appropriate parts for this dimension out = np.empty_like(f, dtype=otype) slice1[axis] = slice(1, -1) slice2[axis] = slice(2, None) slice3[axis] = slice(None, -2) # 1D equivalent -- out[1:-1] = (f[2:] - f[:-2])/2.0 out[slice1] = (f[slice2] - f[slice3])/2.0 slice1[axis] = 0 slice2[axis] = 1 slice3[axis] = 0 # 1D equivalent -- out[0] = (f[1] - f[0]) out[slice1] = (f[slice2] - f[slice3]) slice1[axis] = -1 slice2[axis] = -1 slice3[axis] = -2 # 1D equivalent -- out[-1] = (f[-1] - f[-2]) out[slice1] = (f[slice2] - f[slice3]) # divide by step size outvals.append(out / dx[axis]) # reset the slice object in this dimension to ":" slice1[axis] = slice(None) slice2[axis] = slice(None) slice3[axis] = slice(None) if N == 1: return outvals[0] else: return outvals def diff(a, n=1, axis=-1): """ Calculate the n-th order discrete difference along given axis. The first order difference is given by ``out[n] = a[n+1] - a[n]`` along the given axis, higher order differences are calculated by using `diff` recursively. Parameters ---------- a : array_like Input array n : int, optional The number of times values are differenced. axis : int, optional The axis along which the difference is taken, default is the last axis. Returns ------- diff : ndarray The `n` order differences. The shape of the output is the same as `a` except along `axis` where the dimension is smaller by `n`. See Also -------- gradient, ediff1d, cumsum Examples -------- >>> x = np.array([1, 2, 4, 7, 0]) >>> np.diff(x) array([ 1, 2, 3, -7]) >>> np.diff(x, n=2) array([ 1, 1, -10]) >>> x = np.array([[1, 3, 6, 10], [0, 5, 6, 8]]) >>> np.diff(x) array([[2, 3, 4], [5, 1, 2]]) >>> np.diff(x, axis=0) array([[-1, 2, 0, -2]]) """ if n == 0: return a if n < 0: raise ValueError( "order must be non-negative but got " + repr(n)) a = asanyarray(a) nd = len(a.shape) slice1 = [slice(None)]*nd slice2 = [slice(None)]*nd slice1[axis] = slice(1, None) slice2[axis] = slice(None, -1) slice1 = tuple(slice1) slice2 = tuple(slice2) if n > 1: return diff(a[slice1]-a[slice2], n-1, axis=axis) else: return a[slice1]-a[slice2] def interp(x, xp, fp, left=None, right=None): """ One-dimensional linear interpolation. Returns the one-dimensional piecewise linear interpolant to a function with given values at discrete data-points. Parameters ---------- x : array_like The x-coordinates of the interpolated values. xp : 1-D sequence of floats The x-coordinates of the data points, must be increasing. fp : 1-D sequence of floats The y-coordinates of the data points, same length as `xp`. left : float, optional Value to return for `x < xp[0]`, default is `fp[0]`. right : float, optional Value to return for `x > xp[-1]`, defaults is `fp[-1]`. Returns ------- y : {float, ndarray} The interpolated values, same shape as `x`. Raises ------ ValueError If `xp` and `fp` have different length Notes ----- Does not check that the x-coordinate sequence `xp` is increasing. If `xp` is not increasing, the results are nonsense. A simple check for increasing is:: np.all(np.diff(xp) > 0) Examples -------- >>> xp = [1, 2, 3] >>> fp = [3, 2, 0] >>> np.interp(2.5, xp, fp) 1.0 >>> np.interp([0, 1, 1.5, 2.72, 3.14], xp, fp) array([ 3. , 3. , 2.5 , 0.56, 0. ]) >>> UNDEF = -99.0 >>> np.interp(3.14, xp, fp, right=UNDEF) -99.0 Plot an interpolant to the sine function: >>> x = np.linspace(0, 2*np.pi, 10) >>> y = np.sin(x) >>> xvals = np.linspace(0, 2*np.pi, 50) >>> yinterp = np.interp(xvals, x, y) >>> import matplotlib.pyplot as plt >>> plt.plot(x, y, 'o') [] >>> plt.plot(xvals, yinterp, '-x') [] >>> plt.show() """ if isinstance(x, (float, int, number)): return compiled_interp([x], xp, fp, left, right).item() elif isinstance(x, np.ndarray) and x.ndim == 0: return compiled_interp([x], xp, fp, left, right).item() else: return compiled_interp(x, xp, fp, left, right) def angle(z, deg=0): """ Return the angle of the complex argument. Parameters ---------- z : array_like A complex number or sequence of complex numbers. deg : bool, optional Return angle in degrees if True, radians if False (default). Returns ------- angle : {ndarray, scalar} The counterclockwise angle from the positive real axis on the complex plane, with dtype as numpy.float64. See Also -------- arctan2 absolute Examples -------- >>> np.angle([1.0, 1.0j, 1+1j]) # in radians array([ 0. , 1.57079633, 0.78539816]) >>> np.angle(1+1j, deg=True) # in degrees 45.0 """ if deg: fact = 180/pi else: fact = 1.0 z = asarray(z) if (issubclass(z.dtype.type, _nx.complexfloating)): zimag = z.imag zreal = z.real else: zimag = 0 zreal = z return arctan2(zimag, zreal) * fact def unwrap(p, discont=pi, axis=-1): """ Unwrap by changing deltas between values to 2*pi complement. Unwrap radian phase `p` by changing absolute jumps greater than `discont` to their 2*pi complement along the given axis. Parameters ---------- p : array_like Input array. discont : float, optional Maximum discontinuity between values, default is ``pi``. axis : int, optional Axis along which unwrap will operate, default is the last axis. Returns ------- out : ndarray Output array. See Also -------- rad2deg, deg2rad Notes ----- If the discontinuity in `p` is smaller than ``pi``, but larger than `discont`, no unwrapping is done because taking the 2*pi complement would only make the discontinuity larger. Examples -------- >>> phase = np.linspace(0, np.pi, num=5) >>> phase[3:] += np.pi >>> phase array([ 0. , 0.78539816, 1.57079633, 5.49778714, 6.28318531]) >>> np.unwrap(phase) array([ 0. , 0.78539816, 1.57079633, -0.78539816, 0. ]) """ p = asarray(p) nd = len(p.shape) dd = diff(p, axis=axis) slice1 = [slice(None, None)]*nd # full slices slice1[axis] = slice(1, None) ddmod = mod(dd+pi, 2*pi)-pi _nx.copyto(ddmod, pi, where=(ddmod==-pi) & (dd > 0)) ph_correct = ddmod - dd; _nx.copyto(ph_correct, 0, where=abs(dd)>> np.sort_complex([5, 3, 6, 2, 1]) array([ 1.+0.j, 2.+0.j, 3.+0.j, 5.+0.j, 6.+0.j]) >>> np.sort_complex([1 + 2j, 2 - 1j, 3 - 2j, 3 - 3j, 3 + 5j]) array([ 1.+2.j, 2.-1.j, 3.-3.j, 3.-2.j, 3.+5.j]) """ b = array(a, copy=True) b.sort() if not issubclass(b.dtype.type, _nx.complexfloating): if b.dtype.char in 'bhBH': return b.astype('F') elif b.dtype.char == 'g': return b.astype('G') else: return b.astype('D') else: return b def trim_zeros(filt, trim='fb'): """ Trim the leading and/or trailing zeros from a 1-D array or sequence. Parameters ---------- filt : 1-D array or sequence Input array. trim : str, optional A string with 'f' representing trim from front and 'b' to trim from back. Default is 'fb', trim zeros from both front and back of the array. Returns ------- trimmed : 1-D array or sequence The result of trimming the input. The input data type is preserved. Examples -------- >>> a = np.array((0, 0, 0, 1, 2, 3, 0, 2, 1, 0)) >>> np.trim_zeros(a) array([1, 2, 3, 0, 2, 1]) >>> np.trim_zeros(a, 'b') array([0, 0, 0, 1, 2, 3, 0, 2, 1]) The input data type is preserved, list/tuple in means list/tuple out. >>> np.trim_zeros([0, 1, 2, 0]) [1, 2] """ first = 0 trim = trim.upper() if 'F' in trim: for i in filt: if i != 0.: break else: first = first + 1 last = len(filt) if 'B' in trim: for i in filt[::-1]: if i != 0.: break else: last = last - 1 return filt[first:last] import sys if sys.hexversion < 0x2040000: from sets import Set as set @deprecate def unique(x): """ This function is deprecated. Use numpy.lib.arraysetops.unique() instead. """ try: tmp = x.flatten() if tmp.size == 0: return tmp tmp.sort() idx = concatenate(([True], tmp[1:]!=tmp[:-1])) return tmp[idx] except AttributeError: items = sorted(set(x)) return asarray(items) def extract(condition, arr): """ Return the elements of an array that satisfy some condition. This is equivalent to ``np.compress(ravel(condition), ravel(arr))``. If `condition` is boolean ``np.extract`` is equivalent to ``arr[condition]``. Parameters ---------- condition : array_like An array whose nonzero or True entries indicate the elements of `arr` to extract. arr : array_like Input array of the same size as `condition`. Returns ------- extract : ndarray Rank 1 array of values from `arr` where `condition` is True. See Also -------- take, put, copyto, compress Examples -------- >>> arr = np.arange(12).reshape((3, 4)) >>> arr array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]]) >>> condition = np.mod(arr, 3)==0 >>> condition array([[ True, False, False, True], [False, False, True, False], [False, True, False, False]], dtype=bool) >>> np.extract(condition, arr) array([0, 3, 6, 9]) If `condition` is boolean: >>> arr[condition] array([0, 3, 6, 9]) """ return _nx.take(ravel(arr), nonzero(ravel(condition))[0]) def place(arr, mask, vals): """ Change elements of an array based on conditional and input values. Similar to ``np.copyto(arr, vals, where=mask)``, the difference is that `place` uses the first N elements of `vals`, where N is the number of True values in `mask`, while `copyto` uses the elements where `mask` is True. Note that `extract` does the exact opposite of `place`. Parameters ---------- arr : array_like Array to put data into. mask : array_like Boolean mask array. Must have the same size as `a`. vals : 1-D sequence Values to put into `a`. Only the first N elements are used, where N is the number of True values in `mask`. If `vals` is smaller than N it will be repeated. See Also -------- copyto, put, take, extract Examples -------- >>> arr = np.arange(6).reshape(2, 3) >>> np.place(arr, arr>2, [44, 55]) >>> arr array([[ 0, 1, 2], [44, 55, 44]]) """ return _insert(arr, mask, vals) def disp(mesg, device=None, linefeed=True): """ Display a message on a device. Parameters ---------- mesg : str Message to display. device : object Device to write message. If None, defaults to ``sys.stdout`` which is very similar to ``print``. `device` needs to have ``write()`` and ``flush()`` methods. linefeed : bool, optional Option whether to print a line feed or not. Defaults to True. Raises ------ AttributeError If `device` does not have a ``write()`` or ``flush()`` method. Examples -------- Besides ``sys.stdout``, a file-like object can also be used as it has both required methods: >>> from StringIO import StringIO >>> buf = StringIO() >>> np.disp('"Display" in a file', device=buf) >>> buf.getvalue() '"Display" in a file\\n' """ if device is None: import sys device = sys.stdout if linefeed: device.write('%s\n' % mesg) else: device.write('%s' % mesg) device.flush() return class vectorize(object): """ vectorize(pyfunc, otypes='', doc=None, excluded=None, cache=False) Generalized function class. Define a vectorized function which takes a nested sequence of objects or numpy arrays as inputs and returns a numpy array as output. The vectorized function evaluates `pyfunc` over successive tuples of the input arrays like the python map function, except it uses the broadcasting rules of numpy. The data type of the output of `vectorized` is determined by calling the function with the first element of the input. This can be avoided by specifying the `otypes` argument. Parameters ---------- pyfunc : callable A python function or method. otypes : str or list of dtypes, optional The output data type. It must be specified as either a string of typecode characters or a list of data type specifiers. There should be one data type specifier for each output. doc : str, optional The docstring for the function. If `None`, the docstring will be the ``pyfunc.__doc__``. excluded : set, optional Set of strings or integers representing the positional or keyword arguments for which the function will not be vectorized. These will be passed directly to `pyfunc` unmodified. .. versionadded:: 1.7.0 cache : bool, optional If `True`, then cache the first function call that determines the number of outputs if `otypes` is not provided. .. versionadded:: 1.7.0 Returns ------- vectorized : callable Vectorized function. Examples -------- >>> def myfunc(a, b): ... "Return a-b if a>b, otherwise return a+b" ... if a > b: ... return a - b ... else: ... return a + b >>> vfunc = np.vectorize(myfunc) >>> vfunc([1, 2, 3, 4], 2) array([3, 4, 1, 2]) The docstring is taken from the input function to `vectorize` unless it is specified >>> vfunc.__doc__ 'Return a-b if a>b, otherwise return a+b' >>> vfunc = np.vectorize(myfunc, doc='Vectorized `myfunc`') >>> vfunc.__doc__ 'Vectorized `myfunc`' The output type is determined by evaluating the first element of the input, unless it is specified >>> out = vfunc([1, 2, 3, 4], 2) >>> type(out[0]) >>> vfunc = np.vectorize(myfunc, otypes=[np.float]) >>> out = vfunc([1, 2, 3, 4], 2) >>> type(out[0]) The `excluded` argument can be used to prevent vectorizing over certain arguments. This can be useful for array-like arguments of a fixed length such as the coefficients for a polynomial as in `polyval`: >>> def mypolyval(p, x): ... _p = list(p) ... res = _p.pop(0) ... while _p: ... res = res*x + _p.pop(0) ... return res >>> vpolyval = np.vectorize(mypolyval, excluded=['p']) >>> vpolyval(p=[1, 2, 3], x=[0, 1]) array([3, 6]) Positional arguments may also be excluded by specifying their position: >>> vpolyval.excluded.add(0) >>> vpolyval([1, 2, 3], x=[0, 1]) array([3, 6]) Notes ----- 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. 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 if doc is None: self.__doc__ = pyfunc.__doc__ else: self.__doc__ = doc if isinstance(otypes, str): self.otypes = otypes for char in self.otypes: if char not in typecodes['All']: raise ValueError("Invalid otype specified: %s" % (char,)) elif iterable(otypes): self.otypes = ''.join([_nx.dtype(x).char for x in otypes]) else: raise ValueError("Invalid otype specification") # Excluded variable support if excluded is None: 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 `args` and `kwargs` not in `excluded`. """ excluded = self.excluded if not kwargs and not excluded: func = self.pyfunc vargs = args else: # The wrapper accepts only positional arguments: we use `names` and # `inds` to mutate `the_args` and `kwargs` to pass to the original # function. nargs = len(args) names = [_n for _n in kwargs if _n not in excluded] inds = [_i for _i in range(nargs) if _i not in excluded] the_args = list(args) def func(*vargs): for _n, _i in enumerate(inds): the_args[_i] = vargs[_n] kwargs.update(zip(names, vargs[len(inds):])) return self.pyfunc(*the_args, **kwargs) vargs = [args[_i] for _i in inds] vargs.extend([kwargs[_n] for _n in names]) return self._vectorize_call(func=func, args=vargs) def _get_ufunc_and_otypes(self, func, args): """Return (ufunc, otypes).""" # frompyfunc will fail if args is empty assert args if self.otypes: otypes = self.otypes nout = len(otypes) # Note logic here: We only *use* self._ufunc if func is self.pyfunc # even though we set self._ufunc regardless. if func is self.pyfunc and self._ufunc is not None: ufunc = self._ufunc else: ufunc = self._ufunc = frompyfunc(func, len(args), nout) else: # Get number of outputs and output types by calling the function on # the first entries of args. We also cache the result to prevent # the subsequent call when the ufunc is evaluated. # Assumes that ufunc first evaluates the 0th elements in the input # arrays (the input values are not checked to ensure this) inputs = [asarray(_a).flat[0] for _a in args] outputs = func(*inputs) # Performance note: profiling indicates that -- for simple functions # at least -- this wrapping can almost double the execution time. # Hence we make it optional. if self.cache: _cache = [outputs] def _func(*vargs): if _cache: return _cache.pop() else: return func(*vargs) else: _func = func if isinstance(outputs, tuple): nout = len(outputs) else: nout = 1 outputs = (outputs,) otypes = ''.join([asarray(outputs[_k]).dtype.char for _k in range(nout)]) # Performance note: profiling indicates that creating the ufunc is # not a significant cost compared with wrapping so it seems not # worth trying to cache this. ufunc = frompyfunc(_func, len(args), nout) return ufunc, otypes def _vectorize_call(self, func, args): """Vectorized call to `func` over positional `args`.""" if not args: _res = func() else: ufunc, otypes = self._get_ufunc_and_otypes(func=func, args=args) # Convert args to object arrays first inputs = [array(_a, copy=False, subok=True, dtype=object) for _a in args] outputs = ufunc(*inputs) if ufunc.nout == 1: _res = array(outputs, copy=False, subok=True, dtype=otypes[0]) else: _res = tuple([array(_x, copy=False, subok=True, dtype=_t) for _x, _t in zip(outputs, otypes)]) return _res def cov(m, y=None, rowvar=1, bias=0, ddof=None): """ Estimate a covariance matrix, given data. Covariance indicates the level to which two variables vary together. If we examine N-dimensional samples, :math:`X = [x_1, x_2, ... x_N]^T`, then the covariance matrix element :math:`C_{ij}` is the covariance of :math:`x_i` and :math:`x_j`. The element :math:`C_{ii}` is the variance of :math:`x_i`. Parameters ---------- m : array_like A 1-D or 2-D array containing multiple variables and observations. Each row of `m` represents a variable, and each column a single observation of all those variables. Also see `rowvar` below. y : array_like, optional An additional set of variables and observations. `y` has the same form as that of `m`. rowvar : int, optional If `rowvar` is non-zero (default), then each row represents a variable, with observations in the columns. Otherwise, the relationship is transposed: each column represents a variable, while the rows contain observations. bias : int, optional Default normalization is by ``(N - 1)``, where ``N`` is the number of observations given (unbiased estimate). If `bias` is 1, then normalization is by ``N``. These values can be overridden by using the keyword ``ddof`` in numpy versions >= 1.5. ddof : int, optional .. versionadded:: 1.5 If not ``None`` normalization is by ``(N - ddof)``, where ``N`` is the number of observations; this overrides the value implied by ``bias``. The default value is ``None``. Returns ------- out : ndarray The covariance matrix of the variables. See Also -------- corrcoef : Normalized covariance matrix Examples -------- Consider two variables, :math:`x_0` and :math:`x_1`, which correlate perfectly, but in opposite directions: >>> x = np.array([[0, 2], [1, 1], [2, 0]]).T >>> x array([[0, 1, 2], [2, 1, 0]]) Note how :math:`x_0` increases while :math:`x_1` decreases. The covariance matrix shows this clearly: >>> np.cov(x) array([[ 1., -1.], [-1., 1.]]) Note that element :math:`C_{0,1}`, which shows the correlation between :math:`x_0` and :math:`x_1`, is negative. Further, note how `x` and `y` are combined: >>> x = [-2.1, -1, 4.3] >>> y = [3, 1.1, 0.12] >>> X = np.vstack((x,y)) >>> print np.cov(X) [[ 11.71 -4.286 ] [ -4.286 2.14413333]] >>> print np.cov(x, y) [[ 11.71 -4.286 ] [ -4.286 2.14413333]] >>> print np.cov(x) 11.71 """ # Check inputs if ddof is not None and ddof != int(ddof): raise ValueError("ddof must be integer") X = array(m, ndmin=2, dtype=float) if X.size == 0: # handle empty arrays return np.array(m) if X.shape[0] == 1: rowvar = 1 if rowvar: axis = 0 tup = (slice(None), newaxis) else: axis = 1 tup = (newaxis, slice(None)) if y is not None: y = array(y, copy=False, ndmin=2, dtype=float) X = concatenate((X, y), axis) X -= X.mean(axis=1-axis)[tup] if rowvar: N = X.shape[1] else: N = X.shape[0] if ddof is None: if bias == 0: ddof = 1 else: ddof = 0 fact = float(N - ddof) if not rowvar: return (dot(X.T, X.conj()) / fact).squeeze() else: return (dot(X, X.T.conj()) / fact).squeeze() def corrcoef(x, y=None, rowvar=1, bias=0, ddof=None): """ Return correlation coefficients. Please refer to the documentation for `cov` for more detail. The relationship between the correlation coefficient matrix, `P`, and the covariance matrix, `C`, is .. math:: P_{ij} = \\frac{ C_{ij} } { \\sqrt{ C_{ii} * C_{jj} } } The values of `P` are between -1 and 1, inclusive. Parameters ---------- x : array_like A 1-D or 2-D array containing multiple variables and observations. Each row of `m` represents a variable, and each column a single observation of all those variables. Also see `rowvar` below. y : array_like, optional An additional set of variables and observations. `y` has the same shape as `m`. rowvar : int, optional If `rowvar` is non-zero (default), then each row represents a variable, with observations in the columns. Otherwise, the relationship is transposed: each column represents a variable, while the rows contain observations. bias : int, optional Default normalization is by ``(N - 1)``, where ``N`` is the number of observations (unbiased estimate). If `bias` is 1, then normalization is by ``N``. These values can be overridden by using the keyword ``ddof`` in numpy versions >= 1.5. ddof : {None, int}, optional .. versionadded:: 1.5 If not ``None`` normalization is by ``(N - ddof)``, where ``N`` is the number of observations; this overrides the value implied by ``bias``. The default value is ``None``. Returns ------- out : ndarray The correlation coefficient matrix of the variables. See Also -------- cov : Covariance matrix """ c = cov(x, y, rowvar, bias, ddof) if c.size == 0: # handle empty arrays return c try: d = diag(c) except ValueError: # scalar covariance return 1 return c/sqrt(multiply.outer(d, d)) def blackman(M): """ Return the Blackman window. 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. Parameters ---------- M : int Number of points in the output window. If zero or less, an empty array is returned. Returns ------- out : ndarray The window, with the maximum value normalized to one (the value one appears only if the number of samples is odd). See Also -------- bartlett, hamming, hanning, kaiser Notes ----- The Blackman window is defined as .. math:: w(n) = 0.42 - 0.5 \\cos(2\\pi n/M) + 0.08 \\cos(4\\pi n/M) Most references to the Blackman 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 "removing the foot", i.e. smoothing discontinuities at the beginning and end of the sampled signal) or tapering function. It is known as a "near optimal" tapering function, almost as good (by some measures) as the kaiser window. References ---------- Blackman, R.B. and Tukey, J.W., (1958) The measurement of power spectra, Dover Publications, New York. Oppenheim, A.V., and R.W. Schafer. Discrete-Time Signal Processing. Upper Saddle River, NJ: Prentice-Hall, 1999, pp. 468-471. Examples -------- >>> np.blackman(12) array([ -1.38777878e-17, 3.26064346e-02, 1.59903635e-01, 4.14397981e-01, 7.36045180e-01, 9.67046769e-01, 9.67046769e-01, 7.36045180e-01, 4.14397981e-01, 1.59903635e-01, 3.26064346e-02, -1.38777878e-17]) Plot the window and the frequency response: >>> from numpy.fft import fft, fftshift >>> window = np.blackman(51) >>> plt.plot(window) [] >>> plt.title("Blackman window") >>> plt.ylabel("Amplitude") >>> plt.xlabel("Sample") >>> plt.show() >>> plt.figure() >>> A = fft(window, 2048) / 25.5 >>> mag = np.abs(fftshift(A)) >>> freq = np.linspace(-0.5, 0.5, len(A)) >>> response = 20 * np.log10(mag) >>> response = np.clip(response, -100, 100) >>> plt.plot(freq, response) [] >>> plt.title("Frequency response of Blackman window") >>> plt.ylabel("Magnitude [dB]") >>> plt.xlabel("Normalized frequency [cycles per sample]") >>> plt.axis('tight') (-0.5, 0.5, -100.0, ...) >>> plt.show() """ if M < 1: return array([]) if M == 1: return ones(1, float) n = arange(0, M) return 0.42-0.5*cos(2.0*pi*n/(M-1)) + 0.08*cos(4.0*pi*n/(M-1)) def bartlett(M): """ Return the Bartlett window. The Bartlett window is very similar to a triangular window, except that the end points are at zero. It is often used in signal processing for tapering a signal, without generating too much ripple in the frequency domain. Parameters ---------- M : int Number of points in the output window. If zero or less, an empty array is returned. Returns ------- out : array The triangular window, with the maximum value normalized to one (the value one appears only if the number of samples is odd), with the first and last samples equal to zero. See Also -------- blackman, hamming, hanning, kaiser Notes ----- The Bartlett window is defined as .. math:: w(n) = \\frac{2}{M-1} \\left( \\frac{M-1}{2} - \\left|n - \\frac{M-1}{2}\\right| \\right) Most references to the Bartlett window come from the signal processing literature, where it is used as one of many windowing functions for smoothing values. Note that convolution with this window produces linear interpolation. It is also known as an apodization (which means"removing the foot", i.e. smoothing discontinuities at the beginning and end of the sampled signal) or tapering function. The fourier transform of the Bartlett is the product of two sinc functions. Note the excellent discussion in Kanasewich. References ---------- .. [1] M.S. Bartlett, "Periodogram Analysis and Continuous Spectra", Biometrika 37, 1-16, 1950. .. [2] E.R. Kanasewich, "Time Sequence Analysis in Geophysics", The University of Alberta Press, 1975, pp. 109-110. .. [3] A.V. Oppenheim and R.W. Schafer, "Discrete-Time Signal Processing", Prentice-Hall, 1999, pp. 468-471. .. [4] Wikipedia, "Window function", http://en.wikipedia.org/wiki/Window_function .. [5] W.H. Press, B.P. Flannery, S.A. Teukolsky, and W.T. Vetterling, "Numerical Recipes", Cambridge University Press, 1986, page 429. Examples -------- >>> np.bartlett(12) array([ 0. , 0.18181818, 0.36363636, 0.54545455, 0.72727273, 0.90909091, 0.90909091, 0.72727273, 0.54545455, 0.36363636, 0.18181818, 0. ]) Plot the window and its frequency response (requires SciPy and matplotlib): >>> from numpy.fft import fft, fftshift >>> window = np.bartlett(51) >>> plt.plot(window) [] >>> plt.title("Bartlett window") >>> plt.ylabel("Amplitude") >>> plt.xlabel("Sample") >>> plt.show() >>> plt.figure() >>> A = fft(window, 2048) / 25.5 >>> mag = np.abs(fftshift(A)) >>> freq = np.linspace(-0.5, 0.5, len(A)) >>> response = 20 * np.log10(mag) >>> response = np.clip(response, -100, 100) >>> plt.plot(freq, response) [] >>> plt.title("Frequency response of Bartlett window") >>> plt.ylabel("Magnitude [dB]") >>> plt.xlabel("Normalized frequency [cycles per sample]") >>> plt.axis('tight') (-0.5, 0.5, -100.0, ...) >>> plt.show() """ if M < 1: return array([]) if M == 1: return ones(1, float) n = arange(0, M) return where(less_equal(n, (M-1)/2.0), 2.0*n/(M-1), 2.0-2.0*n/(M-1)) def hanning(M): """ Return the Hanning window. The Hanning window is a taper formed by using a weighted cosine. Parameters ---------- M : int Number of points in the output window. If zero or less, an empty array is returned. Returns ------- out : ndarray, shape(M,) The window, with the maximum value normalized to one (the value one appears only if `M` is odd). See Also -------- bartlett, blackman, hamming, kaiser Notes ----- The Hanning window is defined as .. 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 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 smoothing values. It is also known as an apodization (which means "removing the foot", i.e. smoothing discontinuities at the beginning and end of the sampled signal) or tapering function. References ---------- .. [1] Blackman, R.B. and Tukey, J.W., (1958) The measurement of power spectra, Dover Publications, New York. .. [2] E.R. Kanasewich, "Time Sequence Analysis in Geophysics", The University of Alberta Press, 1975, pp. 106-108. .. [3] Wikipedia, "Window function", http://en.wikipedia.org/wiki/Window_function .. [4] W.H. Press, B.P. Flannery, S.A. Teukolsky, and W.T. Vetterling, "Numerical Recipes", Cambridge University Press, 1986, page 425. Examples -------- >>> np.hanning(12) array([ 0. , 0.07937323, 0.29229249, 0.57115742, 0.82743037, 0.97974649, 0.97974649, 0.82743037, 0.57115742, 0.29229249, 0.07937323, 0. ]) Plot the window and its frequency response: >>> from numpy.fft import fft, fftshift >>> window = np.hanning(51) >>> plt.plot(window) [] >>> plt.title("Hann window") >>> plt.ylabel("Amplitude") >>> plt.xlabel("Sample") >>> plt.show() >>> plt.figure() >>> A = fft(window, 2048) / 25.5 >>> mag = np.abs(fftshift(A)) >>> freq = np.linspace(-0.5, 0.5, len(A)) >>> response = 20 * np.log10(mag) >>> response = np.clip(response, -100, 100) >>> plt.plot(freq, response) [] >>> plt.title("Frequency response of the Hann window") >>> plt.ylabel("Magnitude [dB]") >>> plt.xlabel("Normalized frequency [cycles per sample]") >>> plt.axis('tight') (-0.5, 0.5, -100.0, ...) >>> plt.show() """ if M < 1: return array([]) if M == 1: return ones(1, float) n = arange(0, M) return 0.5-0.5*cos(2.0*pi*n/(M-1)) def hamming(M): """ Return the Hamming window. The Hamming window is a taper formed by using a weighted cosine. Parameters ---------- M : int Number of points in the output window. If zero or less, an empty array is returned. Returns ------- out : ndarray The window, with the maximum value normalized to one (the value one appears only if the number of samples is odd). See Also -------- bartlett, blackman, hanning, kaiser Notes ----- The Hamming window is defined as .. 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. 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 "removing the foot", i.e. smoothing discontinuities at the beginning and end of the sampled signal) or tapering function. References ---------- .. [1] Blackman, R.B. and Tukey, J.W., (1958) The measurement of power spectra, Dover Publications, New York. .. [2] E.R. Kanasewich, "Time Sequence Analysis in Geophysics", The University of Alberta Press, 1975, pp. 109-110. .. [3] Wikipedia, "Window function", http://en.wikipedia.org/wiki/Window_function .. [4] W.H. Press, B.P. Flannery, S.A. Teukolsky, and W.T. Vetterling, "Numerical Recipes", Cambridge University Press, 1986, page 425. Examples -------- >>> np.hamming(12) array([ 0.08 , 0.15302337, 0.34890909, 0.60546483, 0.84123594, 0.98136677, 0.98136677, 0.84123594, 0.60546483, 0.34890909, 0.15302337, 0.08 ]) Plot the window and the frequency response: >>> from numpy.fft import fft, fftshift >>> window = np.hamming(51) >>> plt.plot(window) [] >>> plt.title("Hamming window") >>> plt.ylabel("Amplitude") >>> plt.xlabel("Sample") >>> plt.show() >>> plt.figure() >>> A = fft(window, 2048) / 25.5 >>> mag = np.abs(fftshift(A)) >>> freq = np.linspace(-0.5, 0.5, len(A)) >>> response = 20 * np.log10(mag) >>> response = np.clip(response, -100, 100) >>> plt.plot(freq, response) [] >>> plt.title("Frequency response of Hamming window") >>> plt.ylabel("Magnitude [dB]") >>> plt.xlabel("Normalized frequency [cycles per sample]") >>> plt.axis('tight') (-0.5, 0.5, -100.0, ...) >>> plt.show() """ if M < 1: return array([]) if M == 1: return ones(1, float) n = arange(0, M) return 0.54-0.46*cos(2.0*pi*n/(M-1)) ## Code from cephes for i0 _i0A = [ -4.41534164647933937950E-18, 3.33079451882223809783E-17, -2.43127984654795469359E-16, 1.71539128555513303061E-15, -1.16853328779934516808E-14, 7.67618549860493561688E-14, -4.85644678311192946090E-13, 2.95505266312963983461E-12, -1.72682629144155570723E-11, 9.67580903537323691224E-11, -5.18979560163526290666E-10, 2.65982372468238665035E-9, -1.30002500998624804212E-8, 6.04699502254191894932E-8, -2.67079385394061173391E-7, 1.11738753912010371815E-6, -4.41673835845875056359E-6, 1.64484480707288970893E-5, -5.75419501008210370398E-5, 1.88502885095841655729E-4, -5.76375574538582365885E-4, 1.63947561694133579842E-3, -4.32430999505057594430E-3, 1.05464603945949983183E-2, -2.37374148058994688156E-2, 4.93052842396707084878E-2, -9.49010970480476444210E-2, 1.71620901522208775349E-1, -3.04682672343198398683E-1, 6.76795274409476084995E-1] _i0B = [ -7.23318048787475395456E-18, -4.83050448594418207126E-18, 4.46562142029675999901E-17, 3.46122286769746109310E-17, -2.82762398051658348494E-16, -3.42548561967721913462E-16, 1.77256013305652638360E-15, 3.81168066935262242075E-15, -9.55484669882830764870E-15, -4.15056934728722208663E-14, 1.54008621752140982691E-14, 3.85277838274214270114E-13, 7.18012445138366623367E-13, -1.79417853150680611778E-12, -1.32158118404477131188E-11, -3.14991652796324136454E-11, 1.18891471078464383424E-11, 4.94060238822496958910E-10, 3.39623202570838634515E-9, 2.26666899049817806459E-8, 2.04891858946906374183E-7, 2.89137052083475648297E-6, 6.88975834691682398426E-5, 3.36911647825569408990E-3, 8.04490411014108831608E-1] def _chbevl(x, vals): b0 = vals[0] b1 = 0.0 for i in range(1, len(vals)): b2 = b1 b1 = b0 b0 = x*b1 - b2 + vals[i] return 0.5*(b0 - b2) def _i0_1(x): return exp(x) * _chbevl(x/2.0-2, _i0A) def _i0_2(x): return exp(x) * _chbevl(32.0/x - 2.0, _i0B) / sqrt(x) def i0(x): """ Modified Bessel function of the first kind, order 0. Usually denoted :math:`I_0`. This function does broadcast, but will *not* "up-cast" int dtype arguments unless accompanied by at least one float or complex dtype argument (see Raises below). Parameters ---------- x : array_like, dtype float or complex Argument of the Bessel function. Returns ------- out : ndarray, shape = x.shape, dtype = x.dtype The modified Bessel function evaluated at each of the elements of `x`. Raises ------ TypeError: array cannot be safely cast to required type If argument consists exclusively of int dtypes. See Also -------- scipy.special.iv, scipy.special.ive 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). References ---------- .. [1] C. W. Clenshaw, "Chebyshev series for mathematical functions", in *National Physical Laboratory Mathematical Tables*, vol. 5, London: Her Majesty's Stationery Office, 1962. .. [2] M. Abramowitz and I. A. Stegun, *Handbook of Mathematical Functions*, 10th printing, New York: Dover, 1964, pp. 379. http://www.math.sfu.ca/~cbm/aands/page_379.htm .. [3] http://kobesearch.cpan.org/htdocs/Math-Cephes/Math/Cephes.html Examples -------- >>> np.i0([0.]) array(1.0) >>> np.i0([0., 1. + 2j]) array([ 1.00000000+0.j , 0.18785373+0.64616944j]) """ x = atleast_1d(x).copy() y = empty_like(x) ind = (x<0) x[ind] = -x[ind] ind = (x<=8.0) y[ind] = _i0_1(x[ind]) ind2 = ~ind y[ind2] = _i0_2(x[ind2]) return y.squeeze() ## End of cephes code for i0 def kaiser(M, beta): """ Return the Kaiser window. The Kaiser window is a taper formed by using a Bessel function. Parameters ---------- M : int Number of points in the output window. If zero or less, an empty array is returned. beta : float Shape parameter for window. Returns ------- out : array The window, with the maximum value normalized to one (the value one appears only if the number of samples is odd). See Also -------- bartlett, blackman, hamming, hanning Notes ----- The Kaiser window is defined as .. math:: w(n) = I_0\\left( \\beta \\sqrt{1-\\frac{4n^2}{(M-1)^2}} \\right)/I_0(\\beta) with .. math:: \\quad -\\frac{M-1}{2} \\leq n \\leq \\frac{M-1}{2}, 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 can approximate many other windows by varying the beta parameter. ==== ======================= beta Window shape ==== ======================= 0 Rectangular 5 Similar to a Hamming 6 Similar to a Hanning 8.6 Similar to a Blackman ==== ======================= A beta value of 14 is probably a good starting point. Note that as beta gets large, the window narrows, and so the number of samples needs to be large enough to sample the increasingly narrow spike, otherwise NaNs will get returned. Most references to the Kaiser 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 "removing the foot", i.e. smoothing discontinuities at the beginning and end of the sampled signal) or tapering function. References ---------- .. [1] J. F. Kaiser, "Digital Filters" - Ch 7 in "Systems analysis by digital computer", Editors: F.F. Kuo and J.F. Kaiser, p 218-285. John Wiley and Sons, New York, (1966). .. [2] E.R. Kanasewich, "Time Sequence Analysis in Geophysics", The University of Alberta Press, 1975, pp. 177-178. .. [3] Wikipedia, "Window function", http://en.wikipedia.org/wiki/Window_function Examples -------- >>> np.kaiser(12, 14) array([ 7.72686684e-06, 3.46009194e-03, 4.65200189e-02, 2.29737120e-01, 5.99885316e-01, 9.45674898e-01, 9.45674898e-01, 5.99885316e-01, 2.29737120e-01, 4.65200189e-02, 3.46009194e-03, 7.72686684e-06]) Plot the window and the frequency response: >>> from numpy.fft import fft, fftshift >>> window = np.kaiser(51, 14) >>> plt.plot(window) [] >>> plt.title("Kaiser window") >>> plt.ylabel("Amplitude") >>> plt.xlabel("Sample") >>> plt.show() >>> plt.figure() >>> A = fft(window, 2048) / 25.5 >>> mag = np.abs(fftshift(A)) >>> freq = np.linspace(-0.5, 0.5, len(A)) >>> response = 20 * np.log10(mag) >>> response = np.clip(response, -100, 100) >>> plt.plot(freq, response) [] >>> plt.title("Frequency response of Kaiser window") >>> plt.ylabel("Magnitude [dB]") >>> plt.xlabel("Normalized frequency [cycles per sample]") >>> plt.axis('tight') (-0.5, 0.5, -100.0, ...) >>> plt.show() """ from numpy.dual import i0 if M == 1: return np.array([1.]) n = arange(0, M) alpha = (M-1)/2.0 return i0(beta * sqrt(1-((n-alpha)/alpha)**2.0))/i0(float(beta)) def sinc(x): """ Return the sinc function. The sinc function is :math:`\\sin(\\pi x)/(\\pi x)`. Parameters ---------- x : ndarray Array (possibly multi-dimensional) of values for which to to calculate ``sinc(x)``. Returns ------- out : ndarray ``sinc(x)``, which has the same shape as the input. Notes ----- ``sinc(0)`` is the limit value 1. 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. For bandlimited interpolation of discrete-time signals, the ideal interpolation kernel is proportional to the sinc function. References ---------- .. [1] Weisstein, Eric W. "Sinc Function." From MathWorld--A Wolfram Web Resource. http://mathworld.wolfram.com/SincFunction.html .. [2] Wikipedia, "Sinc function", http://en.wikipedia.org/wiki/Sinc_function Examples -------- >>> x = np.linspace(-4, 4, 41) >>> np.sinc(x) array([ -3.89804309e-17, -4.92362781e-02, -8.40918587e-02, -8.90384387e-02, -5.84680802e-02, 3.89804309e-17, 6.68206631e-02, 1.16434881e-01, 1.26137788e-01, 8.50444803e-02, -3.89804309e-17, -1.03943254e-01, -1.89206682e-01, -2.16236208e-01, -1.55914881e-01, 3.89804309e-17, 2.33872321e-01, 5.04551152e-01, 7.56826729e-01, 9.35489284e-01, 1.00000000e+00, 9.35489284e-01, 7.56826729e-01, 5.04551152e-01, 2.33872321e-01, 3.89804309e-17, -1.55914881e-01, -2.16236208e-01, -1.89206682e-01, -1.03943254e-01, -3.89804309e-17, 8.50444803e-02, 1.26137788e-01, 1.16434881e-01, 6.68206631e-02, 3.89804309e-17, -5.84680802e-02, -8.90384387e-02, -8.40918587e-02, -4.92362781e-02, -3.89804309e-17]) >>> plt.plot(x, np.sinc(x)) [] >>> plt.title("Sinc Function") >>> plt.ylabel("Amplitude") >>> plt.xlabel("X") >>> plt.show() It works in 2-D as well: >>> x = np.linspace(-4, 4, 401) >>> xx = np.outer(x, x) >>> plt.imshow(np.sinc(xx)) """ x = np.asanyarray(x) y = pi* where(x == 0, 1.0e-20, x) return sin(y)/y def msort(a): """ Return a copy of an array sorted along the first axis. Parameters ---------- a : array_like Array to be sorted. Returns ------- sorted_array : ndarray Array of the same type and shape as `a`. See Also -------- sort Notes ----- ``np.msort(a)`` is equivalent to ``np.sort(a, axis=0)``. """ b = array(a, subok=True, copy=True) b.sort(0) return b def median(a, axis=None, out=None, overwrite_input=False): """ Compute the median along the specified axis. Returns the median of the array elements. 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. 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. 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 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, 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, 7, 4], [3, 2, 1]]) >>> a array([[10, 7, 4], [ 3, 2, 1]]) >>> np.median(a) 3.5 >>> np.median(a, axis=0) array([ 6.5, 4.5, 2.5]) >>> np.median(a, axis=1) array([ 7., 2.]) >>> m = np.median(a, axis=0) >>> out = np.zeros_like(m) >>> np.median(a, axis=0, out=m) array([ 6.5, 4.5, 2.5]) >>> m array([ 6.5, 4.5, 2.5]) >>> b = a.copy() >>> np.median(b, axis=1, overwrite_input=True) array([ 7., 2.]) >>> assert not np.all(a==b) >>> b = a.copy() >>> np.median(b, axis=None, overwrite_input=True) 3.5 >>> assert not np.all(a==b) """ a = np.asanyarray(a) if axis is not None and axis >= a.ndim: raise IndexError("axis %d out of bounds (%d)" % (axis, a.ndim)) if overwrite_input: if axis is None: part = a.ravel() sz = part.size if sz % 2 == 0: szh = sz // 2 part.partition((szh - 1, szh)) else: part.partition((sz - 1) // 2) else: sz = a.shape[axis] if sz % 2 == 0: szh = sz // 2 a.partition((szh - 1, szh), axis=axis) else: a.partition((sz - 1) // 2, axis=axis) part = a else: if axis is None: sz = a.size else: sz = a.shape[axis] if sz % 2 == 0: part = partition(a, ((sz // 2) - 1, sz // 2), axis=axis) else: part = partition(a, (sz - 1) // 2, axis=axis) if part.shape == (): # make 0-D arrays work return part.item() if axis is None: axis = 0 indexer = [slice(None)] * part.ndim index = part.shape[axis] // 2 if part.shape[axis] % 2 == 1: # index with slice to allow mean (below) to work indexer[axis] = slice(index, index+1) else: indexer[axis] = slice(index-1, index+1) # Use mean in odd and even case to coerce data type # and check, use out array. return mean(part[indexer], axis=axis, out=out) def percentile(a, q, axis=None, out=None, overwrite_input=False): """ Compute the qth percentile of the data along the specified axis. 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, optional Axis along which the percentiles are computed. The default (None) is to compute the median along a flattened version of the array. 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 array, an error will be raised. 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. See Also -------- mean, median 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 array([[10, 7, 4], [ 3, 2, 1]]) >>> np.percentile(a, 50) 3.5 >>> np.percentile(a, 50, axis=0) array([ 6.5, 4.5, 2.5]) >>> np.percentile(a, 50, axis=1) array([ 7., 2.]) >>> m = np.percentile(a, 50, axis=0) >>> out = np.zeros_like(m) >>> np.percentile(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.percentile(b, 50, axis=1, overwrite_input=True) array([ 7., 2.]) >>> assert not np.all(a==b) >>> b = a.copy() >>> np.percentile(b, 50, axis=None, overwrite_input=True) 3.5 """ a = np.asarray(a) if q == 0: return a.min(axis=axis, out=out) elif q == 100: return a.max(axis=axis, out=out) if overwrite_input: if axis is None: sorted = a.ravel() sorted.sort() else: a.sort(axis=axis) sorted = a else: sorted = sort(a, axis=axis) if axis is None: axis = 0 return _compute_qth_percentile(sorted, q, axis, out) # handle sequence of q's without calling sort multiple times def _compute_qth_percentile(sorted, q, axis, out): if not isscalar(q): p = [_compute_qth_percentile(sorted, qi, axis, None) for qi in q] if out is not None: out.flat = p return p q = q / 100.0 if (q < 0) or (q > 1): raise ValueError("percentile must be either in the range [0,100]") indexer = [slice(None)] * sorted.ndim Nx = sorted.shape[axis] index = q*(Nx-1) i = int(index) if i == index: indexer[axis] = slice(i, i+1) weights = array(1) sumval = 1.0 else: indexer[axis] = slice(i, i+2) j = i + 1 weights = array([(j - index), (index - i)], float) wshape = [1]*sorted.ndim wshape[axis] = 2 weights.shape = wshape sumval = weights.sum() # Use add.reduce in both cases to coerce data type as well as # check and use out array. return add.reduce(sorted[indexer]*weights, axis=axis, out=out)/sumval def trapz(y, x=None, dx=1.0, axis=-1): """ Integrate along the given axis using the composite trapezoidal rule. Integrate `y` (`x`) along given axis. Parameters ---------- y : array_like Input array to integrate. x : array_like, optional If `x` is None, then spacing between all `y` elements is `dx`. dx : scalar, optional If `x` is None, spacing given by `dx` is assumed. Default is 1. axis : int, optional Specify the axis. Returns ------- trapz : float Definite integral as approximated by trapezoidal rule. See Also -------- sum, cumsum 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. References ---------- .. [1] Wikipedia page: http://en.wikipedia.org/wiki/Trapezoidal_rule .. [2] Illustration image: http://en.wikipedia.org/wiki/File:Composite_trapezoidal_rule_illustration.png Examples -------- >>> np.trapz([1,2,3]) 4.0 >>> np.trapz([1,2,3], x=[4,6,8]) 8.0 >>> np.trapz([1,2,3], dx=2) 8.0 >>> a = np.arange(6).reshape(2, 3) >>> a array([[0, 1, 2], [3, 4, 5]]) >>> np.trapz(a, axis=0) array([ 1.5, 2.5, 3.5]) >>> np.trapz(a, axis=1) array([ 2., 8.]) """ y = asanyarray(y) if x is None: d = dx else: x = asanyarray(x) if x.ndim == 1: d = diff(x) # reshape to correct shape shape = [1]*y.ndim shape[axis] = d.shape[0] d = d.reshape(shape) else: d = diff(x, axis=axis) nd = len(y.shape) slice1 = [slice(None)]*nd slice2 = [slice(None)]*nd slice1[axis] = slice(1, None) slice2[axis] = slice(None, -1) try: ret = (d * (y[slice1] +y [slice2]) / 2.0).sum(axis) except ValueError: # Operations didn't work, cast to ndarray d = np.asarray(d) y = np.asarray(y) ret = add.reduce(d * (y[slice1]+y[slice2])/2.0, axis) return ret #always succeed def add_newdoc(place, obj, doc): """Adds documentation to obj which is in module place. If doc is a string add it to obj as a docstring If doc is a tuple, then the first element is interpreted as an attribute of obj and the second as the docstring (method, docstring) If doc is a list, then each element of the list should be a sequence of length two --> [(method1, docstring1), (method2, docstring2), ...] This routine never raises an error. This routine cannot modify read-only docstrings, as appear in new-style classes or built-in functions. Because this routine never raises an error the caller must check manually that the docstrings were changed. """ try: new = {} exec('from %s import %s' % (place, obj), new) if isinstance(doc, str): add_docstring(new[obj], doc.strip()) elif isinstance(doc, tuple): add_docstring(getattr(new[obj], doc[0]), doc[1].strip()) elif isinstance(doc, list): for val in doc: add_docstring(getattr(new[obj], val[0]), val[1].strip()) except: pass # Based on scitools meshgrid def meshgrid(*xi, **kwargs): """ Return coordinate matrices from two or more coordinate vectors. 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. Parameters ---------- x1, x2,..., xn : array_like 1-D arrays representing the coordinates of a grid. indexing : {'xy', 'ij'}, optional Cartesian ('xy', default) or matrix ('ij') indexing of output. See Notes for more details. sparse : bool, optional If True a sparse grid is returned in order to conserve memory. Default is False. 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. Returns ------- X1, X2,..., XN : ndarray For vectors `x1`, `x2`,..., 'xn' with lengths ``Ni=len(xi)`` , return ``(N1, N2, N3,...Nn)`` shaped arrays if indexing='ij' or ``(N2, N1, N3,...Nn)`` shaped arrays if indexing='xy' with the elements of `xi` repeated to fill the matrix along the first dimension for `x1`, the second for `x2` and so on. 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:: xv, yv = meshgrid(x, y, sparse=False, indexing='ij') for i in range(nx): for j in range(ny): # treat xv[i,j], yv[i,j] xv, yv = meshgrid(x, y, sparse=False, indexing='xy') 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 -------- index_tricks.mgrid : Construct a multi-dimensional "meshgrid" using indexing notation. index_tricks.ogrid : Construct an open multi-dimensional "meshgrid" using indexing notation. Examples -------- >>> nx, ny = (3, 2) >>> x = np.linspace(0, 1, nx) >>> y = np.linspace(0, 1, ny) >>> xv, yv = meshgrid(x, y) >>> xv array([[ 0. , 0.5, 1. ], [ 0. , 0.5, 1. ]]) >>> yv array([[ 0., 0., 0.], [ 1., 1., 1.]]) >>> xv, yv = meshgrid(x, y, sparse=True) # make sparse output arrays >>> xv array([[ 0. , 0.5, 1. ]]) >>> yv array([[ 0.], [ 1.]]) `meshgrid` is very useful to evaluate functions on a grid. >>> x = np.arange(-5, 5, 0.1) >>> y = np.arange(-5, 5, 0.1) >>> xx, yy = meshgrid(x, y, sparse=True) >>> z = np.sin(xx**2 + yy**2) / (xx**2 + yy**2) >>> h = plt.contourf(x,y,z) """ if len(xi) < 2: msg = 'meshgrid() takes 2 or more arguments (%d given)' % int(len(xi) > 0) raise ValueError(msg) args = np.atleast_1d(*xi) ndim = len(args) copy_ = kwargs.get('copy', True) sparse = kwargs.get('sparse', False) indexing = kwargs.get('indexing', 'xy') if not indexing in ['xy', 'ij']: raise ValueError("Valid values for `indexing` are 'xy' and 'ij'.") s0 = (1,) * ndim output = [x.reshape(s0[:i] + (-1,) + s0[i + 1::]) for i, x in enumerate(args)] shape = [x.size for x in output] if indexing == 'xy': # switch first and second axis output[0].shape = (1, -1) + (1,)*(ndim - 2) output[1].shape = (-1, 1) + (1,)*(ndim - 2) shape[0], shape[1] = shape[1], shape[0] if sparse: if copy_: return [x.copy() for x in output] else: return output else: # Return the full N-D matrix (not only the 1-D vector) if copy_: mult_fact = np.ones(shape, dtype=int) return [x * mult_fact for x in output] else: return np.broadcast_arrays(*output) 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]`. Parameters ---------- arr : array_like Input array. obj : slice, int or array of ints Indicate which sub-arrays to remove. axis : int, optional The axis along which to delete the subarray defined by `obj`. If `axis` is None, `obj` is applied to the flattened array. Returns ------- out : ndarray A copy of `arr` with the elements specified by `obj` removed. Note that `delete` does not occur in-place. If `axis` is None, `out` is a flattened array. See Also -------- insert : Insert elements into an array. append : Append elements at the end of an array. 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`. Examples -------- >>> arr = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]]) >>> arr array([[ 1, 2, 3, 4], [ 5, 6, 7, 8], [ 9, 10, 11, 12]]) >>> np.delete(arr, 1, 0) array([[ 1, 2, 3, 4], [ 9, 10, 11, 12]]) >>> np.delete(arr, np.s_[::2], 1) array([[ 2, 4], [ 6, 8], [10, 12]]) >>> np.delete(arr, [1,3,5], None) array([ 1, 3, 5, 7, 8, 9, 10, 11, 12]) """ wrap = None if type(arr) is not ndarray: try: wrap = arr.__array_wrap__ except AttributeError: pass arr = asarray(arr) ndim = arr.ndim if axis is None: if ndim != 1: arr = arr.ravel() ndim = arr.ndim; axis = ndim-1; if ndim == 0: warnings.warn("in the future the special handling of scalars " "will be removed from delete and raise an error", DeprecationWarning) if wrap: return wrap(arr) else: return arr.copy() slobj = [slice(None)]*ndim N = arr.shape[axis] newshape = list(arr.shape) if isinstance(obj, slice): start, stop, step = obj.indices(N) xr = range(start, stop, step) numtodel = len(xr) if numtodel <= 0: if wrap: return wrap(arr.copy()) else: return arr.copy() # Invert if step is negative: if step < 0: step = -step start = xr[-1] stop = xr[0] + 1 newshape[axis] -= numtodel new = empty(newshape, arr.dtype, arr.flags.fnc) # copy initial chunk if start == 0: pass else: slobj[axis] = slice(None, start) new[slobj] = arr[slobj] # copy end chunck if stop == N: pass else: slobj[axis] = slice(stop-numtodel, None) slobj2 = [slice(None)]*ndim slobj2[axis] = slice(stop, None) new[slobj] = arr[slobj2] # copy middle pieces if step == 1: pass else: # use array indexing. keep = ones(stop-start, dtype=bool) keep[:stop-start:step] = False slobj[axis] = slice(start, stop-numtodel) slobj2 = [slice(None)]*ndim slobj2[axis] = slice(start, stop) arr = arr[slobj2] slobj2[axis] = keep new[slobj] = arr[slobj2] if wrap: return wrap(new) else: return new _obj = obj obj = np.asarray(obj) # After removing the special handling of booleans and out of # bounds values, the conversion to the array can be removed. if obj.dtype == bool: warnings.warn("in the future insert will treat boolean arrays " "and array-likes as boolean index instead " "of casting it to integer", FutureWarning) obj = obj.astype(intp) if isinstance(_obj, (int, long, integer)): # optimization for a single value obj = obj.item() if (obj < -N or obj >=N): raise IndexError("index %i is out of bounds for axis " "%i with size %i" % (obj, axis, N)) if (obj < 0): obj += N newshape[axis]-=1; new = empty(newshape, arr.dtype, arr.flags.fnc) slobj[axis] = slice(None, obj) new[slobj] = arr[slobj] slobj[axis] = slice(obj, None) slobj2 = [slice(None)]*ndim slobj2[axis] = slice(obj+1, None) new[slobj] = arr[slobj2] else: if obj.size == 0 and not isinstance(_obj, np.ndarray): obj = obj.astype(intp) if not np.can_cast(obj, intp, 'same_kind'): # obj.size = 1 special case always failed and would just # give superfluous warnings. warnings.warn("using a non-integer array as obj in delete " "will result in an error in the future", DeprecationWarning) obj = obj.astype(intp) keep = ones(N, dtype=bool) # Test if there are out of bound indices, this is deprecated inside_bounds = (obj < N) & (obj >= -N) if not inside_bounds.all(): warnings.warn("in the future out of bounds indices will raise an " "error instead of being ignored by `numpy.delete`.", DeprecationWarning) obj = obj[inside_bounds] positive_indices = obj >= 0 if not positive_indices.all(): warnings.warn("in the future negative indices will not be ignored " "by `numpy.delete`.", FutureWarning) obj = obj[positive_indices] keep[obj,] = False slobj[axis] = keep new = arr[slobj] if wrap: return wrap(new) else: return new def insert(arr, obj, values, axis=None): """ Insert values along the given axis before the given indices. Parameters ---------- arr : array_like Input array. obj : int, slice or sequence of ints Object that defines the index or indices before which `values` is inserted. .. 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). 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`. `values` should be shaped so that ``arr[...,obj,...] = values`` is legal. axis : int, optional Axis along which to insert `values`. If `axis` is None then `arr` is flattened first. Returns ------- out : ndarray A copy of `arr` with `values` inserted. Note that `insert` does not occur in-place: a new array is returned. If `axis` is None, `out` is a flattened array. See Also -------- append : Append elements at the end of an array. concatenate : Join a sequence of arrays together. delete : Delete elements from an array. Notes ----- Note that for higher dimensional inserts `obj=0` behaves very different from `obj=[0]` just like `arr[:,0,:] = values` is different from `arr[:,[0],:] = values`. Examples -------- >>> a = np.array([[1, 1], [2, 2], [3, 3]]) >>> a array([[1, 1], [2, 2], [3, 3]]) >>> np.insert(a, 1, 5) array([1, 5, 1, 2, 2, 3, 3]) >>> np.insert(a, 1, 5, axis=1) array([[1, 5, 1], [2, 5, 2], [3, 5, 3]]) Difference between sequence and scalars: >>> np.insert(a, [1], [[1],[2],[3]], axis=1) array([[1, 1, 1], [2, 2, 2], [3, 3, 3]]) >>> np.array_equal(np.insert(a, 1, [1, 2, 3], axis=1), ... np.insert(a, [1], [[1],[2],[3]], axis=1)) True >>> b = a.flatten() >>> b array([1, 1, 2, 2, 3, 3]) >>> np.insert(b, [2, 2], [5, 6]) array([1, 1, 5, 6, 2, 2, 3, 3]) >>> np.insert(b, slice(2, 4), [5, 6]) array([1, 1, 5, 2, 6, 2, 3, 3]) >>> np.insert(b, [2, 2], [7.13, False]) # type casting array([1, 1, 7, 0, 2, 2, 3, 3]) >>> x = np.arange(8).reshape(2, 4) >>> idx = (1, 3) >>> np.insert(x, idx, 999, axis=1) array([[ 0, 999, 1, 2, 999, 3], [ 4, 999, 5, 6, 999, 7]]) """ wrap = None if type(arr) is not ndarray: try: wrap = arr.__array_wrap__ except AttributeError: pass arr = asarray(arr) ndim = arr.ndim if axis is None: if ndim != 1: arr = arr.ravel() ndim = arr.ndim axis = ndim-1 else: if ndim > 0 and (axis < -ndim or axis >= ndim): raise IndexError("axis %i is out of bounds for an array " "of dimension %i" % (axis, ndim)) if (axis < 0): axis += ndim if (ndim == 0): warnings.warn("in the future the special handling of scalars " "will be removed from insert and raise an error", DeprecationWarning) arr = arr.copy() arr[...] = values if wrap: return wrap(arr) else: return arr slobj = [slice(None)]*ndim N = arr.shape[axis] newshape = list(arr.shape) if isinstance(obj, slice): # turn it into a range object indices = arange(*obj.indices(N),**{'dtype':intp}) else: # need to copy obj, because indices will be changed in-place indices = np.array(obj) if indices.dtype == bool: # See also delete warnings.warn("in the future insert will treat boolean arrays " "and array-likes as a boolean index instead " "of casting it to integer", FutureWarning) indices = indices.astype(intp) # Code after warning period: #if obj.ndim != 1: # raise ValueError('boolean array argument obj to insert ' # 'must be one dimensional') #indices = np.flatnonzero(obj) elif indices.ndim > 1: raise ValueError("index array argument obj to insert must " "be one dimensional or scalar") if indices.size == 1: index = indices.item() if index < -N or index > N: raise IndexError("index %i is out of bounds for axis " "%i with size %i" % (obj, axis, N)) if (index < 0): index += N values = array(values, copy=False, ndmin=arr.ndim) if indices.ndim == 0: # broadcasting is very different here, since a[:,0,:] = ... behaves # very different from a[:,[0],:] = ...! This changes values so that # it works likes the second case. (here a[:,0:1,:]) values = np.rollaxis(values, 0, axis + 1) numnew = values.shape[axis] newshape[axis] += numnew new = empty(newshape, arr.dtype, arr.flags.fnc) slobj[axis] = slice(None, index) new[slobj] = arr[slobj] slobj[axis] = slice(index, index+numnew) new[slobj] = values slobj[axis] = slice(index+numnew, None) slobj2 = [slice(None)] * ndim slobj2[axis] = slice(index, None) new[slobj] = arr[slobj2] if wrap: return wrap(new) return new elif indices.size == 0 and not isinstance(obj, np.ndarray): # Can safely cast the empty list to intp indices = indices.astype(intp) if not np.can_cast(indices, intp, 'same_kind'): warnings.warn("using a non-integer array as obj in insert " "will result in an error in the future", DeprecationWarning) indices = indices.astype(intp) indices[indices < 0] += N numnew = len(indices) order = indices.argsort(kind='mergesort') # stable sort indices[order] += np.arange(numnew) newshape[axis] += numnew old_mask = ones(newshape[axis], dtype=bool) old_mask[indices] = False new = empty(newshape, arr.dtype, arr.flags.fnc) slobj2 = [slice(None)]*ndim slobj[axis] = indices slobj2[axis] = old_mask new[slobj] = values new[slobj2] = arr if wrap: return wrap(new) return new def append(arr, values, axis=None): """ Append values to the end of an array. 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 : 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. See Also -------- insert : Insert elements into an array. delete : Delete elements from an array. Examples -------- >>> np.append([1, 2, 3], [[4, 5, 6], [7, 8, 9]]) array([1, 2, 3, 4, 5, 6, 7, 8, 9]) When `axis` is specified, `values` must have the correct shape. >>> np.append([[1, 2, 3], [4, 5, 6]], [[7, 8, 9]], axis=0) array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) >>> np.append([[1, 2, 3], [4, 5, 6]], [7, 8, 9], axis=0) Traceback (most recent call last): ... ValueError: arrays must have same number of dimensions """ arr = asanyarray(arr) if axis is None: if arr.ndim != 1: arr = arr.ravel() values = ravel(values) axis = arr.ndim-1 return concatenate((arr, values), axis=axis) numpy-1.8.2/numpy/lib/polynomial.py0000664000175100017510000011125012370216243020477 0ustar vagrantvagrant00000000000000""" Functions to operate on polynomials. """ from __future__ import division, absolute_import, print_function __all__ = ['poly', 'roots', 'polyint', 'polyder', 'polyadd', 'polysub', 'polymul', 'polydiv', 'polyval', 'poly1d', 'polyfit', 'RankWarning'] import re import warnings import numpy.core.numeric as NX from numpy.core import isscalar, abs, finfo, atleast_1d, hstack, dot from numpy.lib.twodim_base import diag, vander from numpy.lib.function_base import trim_zeros, sort_complex from numpy.lib.type_check import iscomplex, real, imag from numpy.linalg import eigvals, lstsq, inv class RankWarning(UserWarning): """ Issued by `polyfit` when the Vandermonde matrix is rank deficient. For more information, a way to suppress the warning, and an example of `RankWarning` being issued, see `polyfit`. """ pass def poly(seq_of_zeros): """ Find the coefficients of a polynomial with the given sequence of roots. Returns the coefficients of the polynomial whose leading coefficient is one for the given sequence of zeros (multiple roots must be included in the sequence as many times as their multiplicity; see Examples). A square matrix (or array, which will be treated as a matrix) can also be given, in which case the coefficients of the characteristic polynomial of the matrix are returned. Parameters ---------- seq_of_zeros : array_like, shape (N,) or (N, N) A sequence of polynomial roots, or a square array or matrix object. Returns ------- c : ndarray 1D array of polynomial coefficients from highest to lowest degree: ``c[0] * x**(N) + c[1] * x**(N-1) + ... + c[N-1] * x + c[N]`` where c[0] always equals 1. Raises ------ ValueError If input is the wrong shape (the input must be a 1-D or square 2-D array). See Also -------- polyval : Evaluate a polynomial at a point. roots : Return the roots of a polynomial. polyfit : Least squares polynomial fit. poly1d : A one-dimensional polynomial class. Notes ----- Specifying the roots of a polynomial still leaves one degree of freedom, typically represented by an undetermined leading coefficient. [1]_ In the case of this function, that coefficient - the first one in the returned array - is always taken as one. (If for some reason you have one other point, the only automatic way presently to leverage that information is to use ``polyfit``.) The characteristic polynomial, :math:`p_a(t)`, of an `n`-by-`n` matrix **A** is given by :math:`p_a(t) = \\mathrm{det}(t\\, \\mathbf{I} - \\mathbf{A})`, where **I** is the `n`-by-`n` identity matrix. [2]_ References ---------- .. [1] M. Sullivan and M. Sullivan, III, "Algebra and Trignometry, Enhanced With Graphing Utilities," Prentice-Hall, pg. 318, 1996. .. [2] G. Strang, "Linear Algebra and Its Applications, 2nd Edition," Academic Press, pg. 182, 1980. Examples -------- Given a sequence of a polynomial's zeros: >>> np.poly((0, 0, 0)) # Multiple root example array([1, 0, 0, 0]) The line above represents z**3 + 0*z**2 + 0*z + 0. >>> np.poly((-1./2, 0, 1./2)) array([ 1. , 0. , -0.25, 0. ]) The line above represents z**3 - z/4 >>> np.poly((np.random.random(1.)[0], 0, np.random.random(1.)[0])) array([ 1. , -0.77086955, 0.08618131, 0. ]) #random Given a square array object: >>> P = np.array([[0, 1./3], [-1./2, 0]]) >>> np.poly(P) array([ 1. , 0. , 0.16666667]) Or a square matrix object: >>> np.poly(np.matrix(P)) array([ 1. , 0. , 0.16666667]) Note how in all cases the leading coefficient is always 1. """ seq_of_zeros = atleast_1d(seq_of_zeros) sh = seq_of_zeros.shape if len(sh) == 2 and sh[0] == sh[1] and sh[0] != 0: seq_of_zeros = eigvals(seq_of_zeros) elif len(sh) == 1: pass else: raise ValueError("input must be 1d or square 2d array.") if len(seq_of_zeros) == 0: return 1.0 a = [1] for k in range(len(seq_of_zeros)): a = NX.convolve(a, [1, -seq_of_zeros[k]], mode='full') if issubclass(a.dtype.type, NX.complexfloating): # if complex roots are all complex conjugates, the roots are real. roots = NX.asarray(seq_of_zeros, complex) pos_roots = sort_complex(NX.compress(roots.imag > 0, roots)) neg_roots = NX.conjugate(sort_complex( NX.compress(roots.imag < 0, roots))) if (len(pos_roots) == len(neg_roots) and NX.alltrue(neg_roots == pos_roots)): a = a.real.copy() return a def roots(p): """ Return the roots of a polynomial with coefficients given in p. The values in the rank-1 array `p` are coefficients of a polynomial. If the length of `p` is n+1 then the polynomial is described by:: p[0] * x**n + p[1] * x**(n-1) + ... + p[n-1]*x + p[n] Parameters ---------- p : array_like Rank-1 array of polynomial coefficients. Returns ------- out : ndarray An array containing the complex roots of the polynomial. Raises ------ ValueError When `p` cannot be converted to a rank-1 array. See also -------- poly : Find the coefficients of a polynomial with a given sequence of roots. polyval : Evaluate a polynomial at a point. polyfit : Least squares polynomial fit. poly1d : A one-dimensional polynomial class. Notes ----- The algorithm relies on computing the eigenvalues of the companion matrix [1]_. References ---------- .. [1] R. A. Horn & C. R. Johnson, *Matrix Analysis*. Cambridge, UK: Cambridge University Press, 1999, pp. 146-7. Examples -------- >>> coeff = [3.2, 2, 1] >>> np.roots(coeff) array([-0.3125+0.46351241j, -0.3125-0.46351241j]) """ # If input is scalar, this makes it an array p = atleast_1d(p) if len(p.shape) != 1: raise ValueError("Input must be a rank-1 array.") # find non-zero array entries non_zero = NX.nonzero(NX.ravel(p))[0] # Return an empty array if polynomial is all zeros if len(non_zero) == 0: return NX.array([]) # find the number of trailing zeros -- this is the number of roots at 0. trailing_zeros = len(p) - non_zero[-1] - 1 # strip leading and trailing zeros p = p[int(non_zero[0]):int(non_zero[-1])+1] # casting: if incoming array isn't floating point, make it floating point. if not issubclass(p.dtype.type, (NX.floating, NX.complexfloating)): p = p.astype(float) N = len(p) if N > 1: # build companion matrix and find its eigenvalues (the roots) A = diag(NX.ones((N-2,), p.dtype), -1) A[0,:] = -p[1:] / p[0] roots = eigvals(A) else: roots = NX.array([]) # tack any zeros onto the back of the array roots = hstack((roots, NX.zeros(trailing_zeros, roots.dtype))) return roots def polyint(p, m=1, k=None): """ Return an antiderivative (indefinite integral) of a polynomial. The returned order `m` antiderivative `P` of polynomial `p` satisfies :math:`\\frac{d^m}{dx^m}P(x) = p(x)` and is defined up to `m - 1` integration constants `k`. The constants determine the low-order polynomial part .. math:: \\frac{k_{m-1}}{0!} x^0 + \\ldots + \\frac{k_0}{(m-1)!}x^{m-1} of `P` so that :math:`P^{(j)}(0) = k_{m-j-1}`. Parameters ---------- p : {array_like, poly1d} Polynomial to differentiate. A sequence is interpreted as polynomial coefficients, see `poly1d`. m : int, optional Order of the antiderivative. (Default: 1) k : {None, list of `m` scalars, scalar}, optional Integration constants. They are given in the order of integration: those corresponding to highest-order terms come first. If ``None`` (default), all constants are assumed to be zero. If `m = 1`, a single scalar can be given instead of a list. See Also -------- polyder : derivative of a polynomial poly1d.integ : equivalent method Examples -------- The defining property of the antiderivative: >>> p = np.poly1d([1,1,1]) >>> P = np.polyint(p) >>> P poly1d([ 0.33333333, 0.5 , 1. , 0. ]) >>> np.polyder(P) == p True The integration constants default to zero, but can be specified: >>> P = np.polyint(p, 3) >>> P(0) 0.0 >>> np.polyder(P)(0) 0.0 >>> np.polyder(P, 2)(0) 0.0 >>> P = np.polyint(p, 3, k=[6,5,3]) >>> P poly1d([ 0.01666667, 0.04166667, 0.16666667, 3. , 5. , 3. ]) Note that 3 = 6 / 2!, and that the constants are given in the order of integrations. Constant of the highest-order polynomial term comes first: >>> np.polyder(P, 2)(0) 6.0 >>> np.polyder(P, 1)(0) 5.0 >>> P(0) 3.0 """ m = int(m) if m < 0: raise ValueError("Order of integral must be positive (see polyder)") if k is None: k = NX.zeros(m, float) k = atleast_1d(k) if len(k) == 1 and m > 1: k = k[0]*NX.ones(m, float) if len(k) < m: raise ValueError( "k must be a scalar or a rank-1 array of length 1 or >m.") truepoly = isinstance(p, poly1d) p = NX.asarray(p) if m == 0: if truepoly: return poly1d(p) return p else: # Note: this must work also with object and integer arrays y = NX.concatenate((p.__truediv__(NX.arange(len(p), 0, -1)), [k[0]])) val = polyint(y, m - 1, k=k[1:]) if truepoly: return poly1d(val) return val def polyder(p, m=1): """ Return the derivative of the specified order of a polynomial. Parameters ---------- p : poly1d or sequence Polynomial to differentiate. A sequence is interpreted as polynomial coefficients, see `poly1d`. m : int, optional Order of differentiation (default: 1) Returns ------- der : poly1d A new polynomial representing the derivative. See Also -------- polyint : Anti-derivative of a polynomial. poly1d : Class for one-dimensional polynomials. Examples -------- The derivative of the polynomial :math:`x^3 + x^2 + x^1 + 1` is: >>> p = np.poly1d([1,1,1,1]) >>> p2 = np.polyder(p) >>> p2 poly1d([3, 2, 1]) which evaluates to: >>> p2(2.) 17.0 We can verify this, approximating the derivative with ``(f(x + h) - f(x))/h``: >>> (p(2. + 0.001) - p(2.)) / 0.001 17.007000999997857 The fourth-order derivative of a 3rd-order polynomial is zero: >>> np.polyder(p, 2) poly1d([6, 2]) >>> np.polyder(p, 3) poly1d([6]) >>> np.polyder(p, 4) poly1d([ 0.]) """ m = int(m) if m < 0: raise ValueError("Order of derivative must be positive (see polyint)") truepoly = isinstance(p, poly1d) p = NX.asarray(p) n = len(p) - 1 y = p[:-1] * NX.arange(n, 0, -1) if m == 0: val = p else: val = polyder(y, m - 1) if truepoly: val = poly1d(val) return val def polyfit(x, y, deg, rcond=None, full=False, w=None, cov=False): """ Least squares polynomial fit. Fit a polynomial ``p(x) = p[0] * x**deg + ... + p[deg]`` of degree `deg` to points `(x, y)`. Returns a vector of coefficients `p` that minimises the squared error. 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 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 to apply to the y-coordinates of the sample points. cov : bool, optional Return the estimate and the covariance matrix of the estimate If full is True, then cov is not returned. Returns ------- p : ndarray, shape (M,) or (M, K) Polynomial coefficients, highest power first. If `y` was 2-D, the coefficients for `k`-th data set are in ``p[:,k]``. residuals, rank, singular_values, rcond : present only if `full` = True Residuals of the least-squares fit, the effective rank of the scaled Vandermonde coefficient matrix, its singular values, and the specified value of `rcond`. For more details, see `linalg.lstsq`. V : ndaray, shape (M,M) or (M,M,K) : present only if `full` = False and `cov`=True The covariance matrix of the polynomial coefficient estimates. The diagonal of this matrix are the variance estimates for each coefficient. If y is a 2-d array, then the covariance matrix for the `k`-th data set are in ``V[:,:,k]`` Warns ----- RankWarning The rank of the coefficient matrix in the least-squares fit is deficient. The warning is only raised if `full` = False. The warnings can be turned off by >>> import warnings >>> warnings.simplefilter('ignore', np.RankWarning) See Also -------- polyval : Computes polynomial values. linalg.lstsq : Computes a least-squares fit. scipy.interpolate.UnivariateSpline : Computes spline fits. Notes ----- The solution minimizes the squared error .. math :: E = \\sum_{j=0}^k |p(x_j) - y_j|^2 in the equations:: x[0]**n * p[n] + ... + x[0] * p[1] + p[0] = y[0] x[1]**n * p[n] + ... + x[1] * p[1] + p[0] = y[1] ... x[k]**n * p[n] + ... + x[k] * p[1] + p[0] = y[k] The coefficient matrix of the coefficients `p` is a Vandermonde matrix. `polyfit` issues a `RankWarning` when the least-squares fit is badly conditioned. This implies that the best fit is not well-defined due to numerical error. The results may be improved by lowering the polynomial degree or by replacing `x` by `x` - `x`.mean(). The `rcond` parameter can also be set to a value smaller than its default, but the resulting fit may be spurious: including contributions from the small singular values can add numerical noise to the result. Note that fitting polynomial coefficients is inherently badly conditioned when the degree of the polynomial is large or the interval of sample points is badly centered. The quality of the fit should always be checked in these cases. When polynomial fits are not satisfactory, splines may be a good alternative. References ---------- .. [1] Wikipedia, "Curve fitting", http://en.wikipedia.org/wiki/Curve_fitting .. [2] Wikipedia, "Polynomial interpolation", http://en.wikipedia.org/wiki/Polynomial_interpolation Examples -------- >>> x = np.array([0.0, 1.0, 2.0, 3.0, 4.0, 5.0]) >>> y = np.array([0.0, 0.8, 0.9, 0.1, -0.8, -1.0]) >>> z = np.polyfit(x, y, 3) >>> z array([ 0.08703704, -0.81349206, 1.69312169, -0.03968254]) It is convenient to use `poly1d` objects for dealing with polynomials: >>> p = np.poly1d(z) >>> p(0.5) 0.6143849206349179 >>> p(3.5) -0.34732142857143039 >>> p(10) 22.579365079365115 High-order polynomials may oscillate wildly: >>> p30 = np.poly1d(np.polyfit(x, y, 30)) /... RankWarning: Polyfit may be poorly conditioned... >>> p30(4) -0.80000000000000204 >>> p30(5) -0.99999999999999445 >>> p30(4.5) -0.10547061179440398 Illustration: >>> import matplotlib.pyplot as plt >>> xp = np.linspace(-2, 6, 100) >>> plt.plot(x, y, '.', xp, p(xp), '-', xp, p30(xp), '--') [, , ] >>> plt.ylim(-2,2) (-2, 2) >>> plt.show() """ order = int(deg) + 1 x = NX.asarray(x) + 0.0 y = NX.asarray(y) + 0.0 # check arguments. if deg < 0 : raise ValueError("expected deg >= 0") if x.ndim != 1: raise TypeError("expected 1D vector for x") if x.size == 0: raise TypeError("expected non-empty vector for x") if y.ndim < 1 or y.ndim > 2 : raise TypeError("expected 1D or 2D array for y") if x.shape[0] != y.shape[0] : raise TypeError("expected x and y to have same length") # set rcond if rcond is None : rcond = len(x)*finfo(x.dtype).eps # set up least squares equation for powers of x lhs = vander(x, order) rhs = y # apply weighting if w is not None: w = NX.asarray(w) + 0.0 if w.ndim != 1: raise TypeError("expected a 1-d array for weights") if w.shape[0] != y.shape[0] : raise TypeError("expected w and y to have the same length") lhs *= w[:, NX.newaxis] if rhs.ndim == 2: rhs *= w[:, NX.newaxis] else: rhs *= w # scale lhs to improve condition number and solve scale = NX.sqrt((lhs*lhs).sum(axis=0)) lhs /= scale c, resids, rank, s = lstsq(lhs, rhs, rcond) c = (c.T/scale).T # broadcast scale coefficients # warn on rank reduction, which indicates an ill conditioned matrix if rank != order and not full: msg = "Polyfit may be poorly conditioned" warnings.warn(msg, RankWarning) if full : return c, resids, rank, s, rcond elif cov : Vbase = inv(dot(lhs.T, lhs)) Vbase /= NX.outer(scale, scale) # Some literature ignores the extra -2.0 factor in the denominator, but # it is included here because the covariance of Multivariate Student-T # (which is implied by a Bayesian uncertainty analysis) includes it. # Plus, it gives a slightly more conservative estimate of uncertainty. fac = resids / (len(x) - order - 2.0) if y.ndim == 1: return c, Vbase * fac else: return c, Vbase[:,:, NX.newaxis] * fac else : return c def polyval(p, x): """ Evaluate a polynomial at specific values. If `p` is of length N, this function returns the value: ``p[0]*x**(N-1) + p[1]*x**(N-2) + ... + p[N-2]*x + p[N-1]`` If `x` is a sequence, then `p(x)` is returned for each element of `x`. If `x` is another polynomial then the composite polynomial `p(x(t))` is returned. Parameters ---------- p : array_like or poly1d object 1D array of polynomial coefficients (including coefficients equal to zero) from highest degree to the constant term, or an instance of poly1d. x : array_like or poly1d object A number, a 1D array of numbers, or an instance of poly1d, "at" which to evaluate `p`. Returns ------- values : ndarray or poly1d If `x` is a poly1d instance, the result is the composition of the two polynomials, i.e., `x` is "substituted" in `p` and the simplified result is returned. In addition, the type of `x` - array_like or poly1d - governs the type of the output: `x` array_like => `values` array_like, `x` a poly1d object => `values` is also. See Also -------- poly1d: A polynomial class. Notes ----- Horner's scheme [1]_ is used to evaluate the polynomial. Even so, for polynomials of high degree the values may be inaccurate due to rounding errors. Use carefully. References ---------- .. [1] I. N. Bronshtein, K. A. Semendyayev, and K. A. Hirsch (Eng. trans. Ed.), *Handbook of Mathematics*, New York, Van Nostrand Reinhold Co., 1985, pg. 720. Examples -------- >>> np.polyval([3,0,1], 5) # 3 * 5**2 + 0 * 5**1 + 1 76 >>> np.polyval([3,0,1], np.poly1d(5)) poly1d([ 76.]) >>> np.polyval(np.poly1d([3,0,1]), 5) 76 >>> np.polyval(np.poly1d([3,0,1]), np.poly1d(5)) poly1d([ 76.]) """ p = NX.asarray(p) if isinstance(x, poly1d): y = 0 else: x = NX.asarray(x) y = NX.zeros_like(x) for i in range(len(p)): y = x * y + p[i] return y def polyadd(a1, a2): """ Find the sum of two polynomials. Returns the polynomial resulting from the sum of two input polynomials. Each input must be either a poly1d object or a 1D sequence of polynomial coefficients, from highest to lowest degree. Parameters ---------- a1, a2 : array_like or poly1d object Input polynomials. Returns ------- out : ndarray or poly1d object The sum of the inputs. If either input is a poly1d object, then the output is also a poly1d object. Otherwise, it is a 1D array of polynomial coefficients from highest to lowest degree. See Also -------- poly1d : A one-dimensional polynomial class. poly, polyadd, polyder, polydiv, polyfit, polyint, polysub, polyval Examples -------- >>> np.polyadd([1, 2], [9, 5, 4]) array([9, 6, 6]) Using poly1d objects: >>> p1 = np.poly1d([1, 2]) >>> p2 = np.poly1d([9, 5, 4]) >>> print p1 1 x + 2 >>> print p2 2 9 x + 5 x + 4 >>> print np.polyadd(p1, p2) 2 9 x + 6 x + 6 """ truepoly = (isinstance(a1, poly1d) or isinstance(a2, poly1d)) a1 = atleast_1d(a1) a2 = atleast_1d(a2) diff = len(a2) - len(a1) if diff == 0: val = a1 + a2 elif diff > 0: zr = NX.zeros(diff, a1.dtype) val = NX.concatenate((zr, a1)) + a2 else: zr = NX.zeros(abs(diff), a2.dtype) val = a1 + NX.concatenate((zr, a2)) if truepoly: val = poly1d(val) return val def polysub(a1, a2): """ Difference (subtraction) of two polynomials. Given two polynomials `a1` and `a2`, returns ``a1 - a2``. `a1` and `a2` can be either array_like sequences of the polynomials' coefficients (including coefficients equal to zero), or `poly1d` objects. Parameters ---------- a1, a2 : array_like or poly1d Minuend and subtrahend polynomials, respectively. Returns ------- out : ndarray or poly1d Array or `poly1d` object of the difference polynomial's coefficients. See Also -------- polyval, polydiv, polymul, polyadd Examples -------- .. math:: (2 x^2 + 10 x - 2) - (3 x^2 + 10 x -4) = (-x^2 + 2) >>> np.polysub([2, 10, -2], [3, 10, -4]) array([-1, 0, 2]) """ truepoly = (isinstance(a1, poly1d) or isinstance(a2, poly1d)) a1 = atleast_1d(a1) a2 = atleast_1d(a2) diff = len(a2) - len(a1) if diff == 0: val = a1 - a2 elif diff > 0: zr = NX.zeros(diff, a1.dtype) val = NX.concatenate((zr, a1)) - a2 else: zr = NX.zeros(abs(diff), a2.dtype) val = a1 - NX.concatenate((zr, a2)) if truepoly: val = poly1d(val) return val def polymul(a1, a2): """ Find the product of two polynomials. Finds the polynomial resulting from the multiplication of the two input polynomials. Each input must be either a poly1d object or a 1D sequence of polynomial coefficients, from highest to lowest degree. Parameters ---------- a1, a2 : array_like or poly1d object Input polynomials. Returns ------- out : ndarray or poly1d object The polynomial resulting from the multiplication of the inputs. If either inputs is a poly1d object, then the output is also a poly1d object. Otherwise, it is a 1D array of polynomial coefficients from highest to lowest degree. See Also -------- poly1d : A one-dimensional polynomial class. poly, polyadd, polyder, polydiv, polyfit, polyint, polysub, polyval Examples -------- >>> np.polymul([1, 2, 3], [9, 5, 1]) array([ 9, 23, 38, 17, 3]) Using poly1d objects: >>> p1 = np.poly1d([1, 2, 3]) >>> p2 = np.poly1d([9, 5, 1]) >>> print p1 2 1 x + 2 x + 3 >>> print p2 2 9 x + 5 x + 1 >>> print np.polymul(p1, p2) 4 3 2 9 x + 23 x + 38 x + 17 x + 3 """ truepoly = (isinstance(a1, poly1d) or isinstance(a2, poly1d)) a1, a2 = poly1d(a1), poly1d(a2) val = NX.convolve(a1, a2) if truepoly: val = poly1d(val) return val def polydiv(u, v): """ Returns the quotient and remainder of polynomial division. The input arrays are the coefficients (including any coefficients equal to zero) of the "numerator" (dividend) and "denominator" (divisor) polynomials, respectively. Parameters ---------- u : array_like or poly1d Dividend polynomial's coefficients. v : array_like or poly1d Divisor polynomial's coefficients. Returns ------- q : ndarray Coefficients, including those equal to zero, of the quotient. r : ndarray Coefficients, including those equal to zero, of the remainder. See Also -------- poly, polyadd, polyder, polydiv, polyfit, polyint, polymul, polysub, polyval Notes ----- Both `u` and `v` must be 0-d or 1-d (ndim = 0 or 1), but `u.ndim` need not equal `v.ndim`. In other words, all four possible combinations - ``u.ndim = v.ndim = 0``, ``u.ndim = v.ndim = 1``, ``u.ndim = 1, v.ndim = 0``, and ``u.ndim = 0, v.ndim = 1`` - work. Examples -------- .. math:: \\frac{3x^2 + 5x + 2}{2x + 1} = 1.5x + 1.75, remainder 0.25 >>> x = np.array([3.0, 5.0, 2.0]) >>> y = np.array([2.0, 1.0]) >>> np.polydiv(x, y) (array([ 1.5 , 1.75]), array([ 0.25])) """ truepoly = (isinstance(u, poly1d) or isinstance(u, poly1d)) u = atleast_1d(u) + 0.0 v = atleast_1d(v) + 0.0 # w has the common type w = u[0] + v[0] m = len(u) - 1 n = len(v) - 1 scale = 1. / v[0] q = NX.zeros((max(m - n + 1, 1),), w.dtype) r = u.copy() for k in range(0, m-n+1): d = scale * r[k] q[k] = d r[k:k+n+1] -= d*v while NX.allclose(r[0], 0, rtol=1e-14) and (r.shape[-1] > 1): r = r[1:] if truepoly: return poly1d(q), poly1d(r) return q, r _poly_mat = re.compile(r"[*][*]([0-9]*)") def _raise_power(astr, wrap=70): n = 0 line1 = '' line2 = '' output = ' ' while True: mat = _poly_mat.search(astr, n) if mat is None: break span = mat.span() power = mat.groups()[0] partstr = astr[n:span[0]] n = span[1] toadd2 = partstr + ' '*(len(power)-1) toadd1 = ' '*(len(partstr)-1) + power if ((len(line2)+len(toadd2) > wrap) or \ (len(line1)+len(toadd1) > wrap)): output += line1 + "\n" + line2 + "\n " line1 = toadd1 line2 = toadd2 else: line2 += partstr + ' '*(len(power)-1) line1 += ' '*(len(partstr)-1) + power output += line1 + "\n" + line2 return output + astr[n:] class poly1d(object): """ A one-dimensional polynomial class. A convenience class, used to encapsulate "natural" operations on polynomials so that said operations may take on their customary form in code (see Examples). Parameters ---------- c_or_r : array_like The polynomial's coefficients, in decreasing powers, or if the value of the second parameter is True, the polynomial's roots (values where the polynomial evaluates to 0). For example, ``poly1d([1, 2, 3])`` returns an object that represents :math:`x^2 + 2x + 3`, whereas ``poly1d([1, 2, 3], True)`` returns one that represents :math:`(x-1)(x-2)(x-3) = x^3 - 6x^2 + 11x -6`. r : bool, optional If True, `c_or_r` specifies the polynomial's roots; the default is False. variable : str, optional Changes the variable used when printing `p` from `x` to `variable` (see Examples). Examples -------- Construct the polynomial :math:`x^2 + 2x + 3`: >>> p = np.poly1d([1, 2, 3]) >>> print np.poly1d(p) 2 1 x + 2 x + 3 Evaluate the polynomial at :math:`x = 0.5`: >>> p(0.5) 4.25 Find the roots: >>> p.r array([-1.+1.41421356j, -1.-1.41421356j]) >>> p(p.r) array([ -4.44089210e-16+0.j, -4.44089210e-16+0.j]) These numbers in the previous line represent (0, 0) to machine precision Show the coefficients: >>> p.c array([1, 2, 3]) Display the order (the leading zero-coefficients are removed): >>> p.order 2 Show the coefficient of the k-th power in the polynomial (which is equivalent to ``p.c[-(i+1)]``): >>> p[1] 2 Polynomials can be added, subtracted, multiplied, and divided (returns quotient and remainder): >>> p * p poly1d([ 1, 4, 10, 12, 9]) >>> (p**3 + 4) / p (poly1d([ 1., 4., 10., 12., 9.]), poly1d([ 4.])) ``asarray(p)`` gives the coefficient array, so polynomials can be used in all functions that accept arrays: >>> p**2 # square of polynomial poly1d([ 1, 4, 10, 12, 9]) >>> np.square(p) # square of individual coefficients array([1, 4, 9]) The variable used in the string representation of `p` can be modified, using the `variable` parameter: >>> p = np.poly1d([1,2,3], variable='z') >>> print p 2 1 z + 2 z + 3 Construct a polynomial from its roots: >>> np.poly1d([1, 2], True) poly1d([ 1, -3, 2]) This is the same polynomial as obtained by: >>> np.poly1d([1, -1]) * np.poly1d([1, -2]) poly1d([ 1, -3, 2]) """ coeffs = None order = None variable = None __hash__ = None def __init__(self, c_or_r, r=0, variable=None): if isinstance(c_or_r, poly1d): for key in c_or_r.__dict__.keys(): self.__dict__[key] = c_or_r.__dict__[key] if variable is not None: self.__dict__['variable'] = variable return if r: c_or_r = poly(c_or_r) c_or_r = atleast_1d(c_or_r) if len(c_or_r.shape) > 1: raise ValueError("Polynomial must be 1d only.") c_or_r = trim_zeros(c_or_r, trim='f') if len(c_or_r) == 0: c_or_r = NX.array([0.]) self.__dict__['coeffs'] = c_or_r self.__dict__['order'] = len(c_or_r) - 1 if variable is None: variable = 'x' self.__dict__['variable'] = variable def __array__(self, t=None): if t: return NX.asarray(self.coeffs, t) else: return NX.asarray(self.coeffs) def __repr__(self): vals = repr(self.coeffs) vals = vals[6:-1] return "poly1d(%s)" % vals def __len__(self): return self.order def __str__(self): thestr = "0" var = self.variable # Remove leading zeros coeffs = self.coeffs[NX.logical_or.accumulate(self.coeffs != 0)] N = len(coeffs)-1 def fmt_float(q): s = '%.4g' % q if s.endswith('.0000'): s = s[:-5] return s for k in range(len(coeffs)): if not iscomplex(coeffs[k]): coefstr = fmt_float(real(coeffs[k])) elif real(coeffs[k]) == 0: coefstr = '%sj' % fmt_float(imag(coeffs[k])) else: coefstr = '(%s + %sj)' % (fmt_float(real(coeffs[k])), fmt_float(imag(coeffs[k]))) power = (N-k) if power == 0: if coefstr != '0': newstr = '%s' % (coefstr,) else: if k == 0: newstr = '0' else: newstr = '' elif power == 1: if coefstr == '0': newstr = '' elif coefstr == 'b': newstr = var else: newstr = '%s %s' % (coefstr, var) else: if coefstr == '0': newstr = '' elif coefstr == 'b': newstr = '%s**%d' % (var, power,) else: newstr = '%s %s**%d' % (coefstr, var, power) if k > 0: if newstr != '': if newstr.startswith('-'): thestr = "%s - %s" % (thestr, newstr[1:]) else: thestr = "%s + %s" % (thestr, newstr) else: thestr = newstr return _raise_power(thestr) def __call__(self, val): return polyval(self.coeffs, val) def __neg__(self): return poly1d(-self.coeffs) def __pos__(self): return self def __mul__(self, other): if isscalar(other): return poly1d(self.coeffs * other) else: other = poly1d(other) return poly1d(polymul(self.coeffs, other.coeffs)) def __rmul__(self, other): if isscalar(other): return poly1d(other * self.coeffs) else: other = poly1d(other) return poly1d(polymul(self.coeffs, other.coeffs)) def __add__(self, other): other = poly1d(other) return poly1d(polyadd(self.coeffs, other.coeffs)) def __radd__(self, other): other = poly1d(other) return poly1d(polyadd(self.coeffs, other.coeffs)) def __pow__(self, val): if not isscalar(val) or int(val) != val or val < 0: raise ValueError("Power to non-negative integers only.") res = [1] for _ in range(val): res = polymul(self.coeffs, res) return poly1d(res) def __sub__(self, other): other = poly1d(other) return poly1d(polysub(self.coeffs, other.coeffs)) def __rsub__(self, other): other = poly1d(other) return poly1d(polysub(other.coeffs, self.coeffs)) def __div__(self, other): if isscalar(other): return poly1d(self.coeffs/other) else: other = poly1d(other) return polydiv(self, other) __truediv__ = __div__ def __rdiv__(self, other): if isscalar(other): return poly1d(other/self.coeffs) else: other = poly1d(other) return polydiv(other, self) __rtruediv__ = __rdiv__ def __eq__(self, other): return NX.alltrue(self.coeffs == other.coeffs) def __ne__(self, other): return NX.any(self.coeffs != other.coeffs) def __setattr__(self, key, val): raise ValueError("Attributes cannot be changed this way.") def __getattr__(self, key): if key in ['r', 'roots']: return roots(self.coeffs) elif key in ['c', 'coef', 'coefficients']: return self.coeffs elif key in ['o']: return self.order else: try: return self.__dict__[key] except KeyError: raise AttributeError("'%s' has no attribute '%s'" % (self.__class__, key)) def __getitem__(self, val): ind = self.order - val if val > self.order: return 0 if val < 0: return 0 return self.coeffs[ind] def __setitem__(self, key, val): ind = self.order - key if key < 0: raise ValueError("Does not support negative powers.") if key > self.order: zr = NX.zeros(key-self.order, self.coeffs.dtype) self.__dict__['coeffs'] = NX.concatenate((zr, self.coeffs)) self.__dict__['order'] = key ind = 0 self.__dict__['coeffs'][ind] = val return def __iter__(self): return iter(self.coeffs) def integ(self, m=1, k=0): """ Return an antiderivative (indefinite integral) of this polynomial. Refer to `polyint` for full documentation. See Also -------- polyint : equivalent function """ return poly1d(polyint(self.coeffs, m=m, k=k)) def deriv(self, m=1): """ Return a derivative of this polynomial. Refer to `polyder` for full documentation. See Also -------- polyder : equivalent function """ return poly1d(polyder(self.coeffs, m=m)) # Stuff to do on module import warnings.simplefilter('always', RankWarning) numpy-1.8.2/numpy/lib/arrayterator.py0000664000175100017510000001615512370216243021043 0ustar vagrantvagrant00000000000000""" A buffered iterator for big arrays. This module solves the problem of iterating over a big file-based array without having to read it into memory. The `Arrayterator` class wraps an array object, and when iterated it will return sub-arrays with at most a user-specified number of elements. """ from __future__ import division, absolute_import, print_function import sys from operator import mul from functools import reduce from numpy.compat import long __all__ = ['Arrayterator'] class Arrayterator(object): """ Buffered iterator for big arrays. `Arrayterator` creates a buffered iterator for reading big arrays in small contiguous blocks. The class is useful for objects stored in the file system. It allows iteration over the object *without* reading everything in memory; instead, small blocks are read and iterated over. `Arrayterator` can be used with any object that supports multidimensional slices. This includes NumPy arrays, but also variables from Scientific.IO.NetCDF or pynetcdf for example. Parameters ---------- var : array_like The object to iterate over. buf_size : int, optional The buffer size. If `buf_size` is supplied, the maximum amount of data that will be read into memory is `buf_size` elements. Default is None, which will read as many element as possible into memory. Attributes ---------- var buf_size start stop step shape flat See Also -------- ndenumerate : Multidimensional array iterator. flatiter : Flat array iterator. memmap : Create a memory-map to an array stored in a binary file on disk. Notes ----- The algorithm works by first finding a "running dimension", along which the blocks will be extracted. Given an array of dimensions ``(d1, d2, ..., dn)``, e.g. if `buf_size` is smaller than ``d1``, the first dimension will be used. If, on the other hand, ``d1 < buf_size < d1*d2`` the second dimension will be used, and so on. Blocks are extracted along this dimension, and when the last block is returned the process continues from the next dimension, until all elements have been read. Examples -------- >>> import numpy as np >>> a = np.arange(3 * 4 * 5 * 6).reshape(3, 4, 5, 6) >>> a_itor = np.lib.arrayterator.Arrayterator(a, 2) >>> a_itor.shape (3, 4, 5, 6) Now we can iterate over ``a_itor``, and it will return arrays of size two. Since `buf_size` was smaller than any dimension, the first dimension will be iterated over first: >>> for subarr in a_itor: ... if not subarr.all(): ... print subarr, subarr.shape ... [[[[0 1]]]] (1, 1, 1, 2) """ def __init__(self, var, buf_size=None): self.var = var self.buf_size = buf_size self.start = [0 for dim in var.shape] self.stop = [dim for dim in var.shape] self.step = [1 for dim in var.shape] def __getattr__(self, attr): return getattr(self.var, attr) def __getitem__(self, index): """ Return a new arrayterator. """ # Fix index, handling ellipsis and incomplete slices. if not isinstance(index, tuple): index = (index,) fixed = [] length, dims = len(index), len(self.shape) for slice_ in index: if slice_ is Ellipsis: fixed.extend([slice(None)] * (dims-length+1)) length = len(fixed) elif isinstance(slice_, (int, long)): fixed.append(slice(slice_, slice_+1, 1)) else: fixed.append(slice_) index = tuple(fixed) if len(index) < dims: index += (slice(None),) * (dims-len(index)) # Return a new arrayterator object. out = self.__class__(self.var, self.buf_size) for i, (start, stop, step, slice_) in enumerate( zip(self.start, self.stop, self.step, index)): out.start[i] = start + (slice_.start or 0) out.step[i] = step * (slice_.step or 1) out.stop[i] = start + (slice_.stop or stop-start) out.stop[i] = min(stop, out.stop[i]) return out def __array__(self): """ Return corresponding data. """ slice_ = tuple(slice(*t) for t in zip( self.start, self.stop, self.step)) return self.var[slice_] @property def flat(self): """ A 1-D flat iterator for Arrayterator objects. This iterator returns elements of the array to be iterated over in `Arrayterator` one by one. It is similar to `flatiter`. See Also -------- `Arrayterator` flatiter Examples -------- >>> a = np.arange(3 * 4 * 5 * 6).reshape(3, 4, 5, 6) >>> a_itor = np.lib.arrayterator.Arrayterator(a, 2) >>> for subarr in a_itor.flat: ... if not subarr: ... print subarr, type(subarr) ... 0 """ for block in self: for value in block.flat: yield value @property def shape(self): """ The shape of the array to be iterated over. For an example, see `Arrayterator`. """ return tuple(((stop-start-1)//step+1) for start, stop, step in zip(self.start, self.stop, self.step)) def __iter__(self): # Skip arrays with degenerate dimensions if [dim for dim in self.shape if dim <= 0]: raise StopIteration start = self.start[:] stop = self.stop[:] step = self.step[:] ndims = len(self.var.shape) while True: count = self.buf_size or reduce(mul, self.shape) # iterate over each dimension, looking for the # running dimension (ie, the dimension along which # the blocks will be built from) rundim = 0 for i in range(ndims-1, -1, -1): # if count is zero we ran out of elements to read # along higher dimensions, so we read only a single position if count == 0: stop[i] = start[i]+1 elif count <= self.shape[i]: # limit along this dimension stop[i] = start[i] + count*step[i] rundim = i else: stop[i] = self.stop[i] # read everything along this # dimension stop[i] = min(self.stop[i], stop[i]) count = count//self.shape[i] # yield a block slice_ = tuple(slice(*t) for t in zip(start, stop, step)) yield self.var[slice_] # Update start position, taking care of overflow to # other dimensions start[rundim] = stop[rundim] # start where we stopped for i in range(ndims-1, 0, -1): if start[i] >= self.stop[i]: start[i] = self.start[i] start[i-1] += self.step[i-1] if start[0] >= self.stop[0]: raise StopIteration numpy-1.8.2/numpy/lib/twodim_base.py0000664000175100017510000006060512370216243020620 0ustar vagrantvagrant00000000000000""" Basic functions for manipulating 2d arrays """ from __future__ import division, absolute_import, print_function __all__ = ['diag', 'diagflat', 'eye', 'fliplr', 'flipud', 'rot90', 'tri', 'triu', 'tril', 'vander', 'histogram2d', 'mask_indices', 'tril_indices', 'tril_indices_from', 'triu_indices', 'triu_indices_from', ] from numpy.core.numeric import asanyarray, equal, subtract, arange, \ zeros, greater_equal, multiply, ones, asarray, alltrue, where, \ empty, diagonal def fliplr(m): """ Flip array in the left/right direction. Flip the entries in each row in the left/right direction. Columns are preserved, but appear in a different order than before. Parameters ---------- m : array_like Input array. Returns ------- f : ndarray A view of `m` with the columns reversed. Since a view is returned, this operation is :math:`\\mathcal O(1)`. See Also -------- flipud : Flip array in the up/down direction. rot90 : Rotate array counterclockwise. Notes ----- Equivalent to A[:,::-1]. Does not require the array to be two-dimensional. Examples -------- >>> A = np.diag([1.,2.,3.]) >>> A array([[ 1., 0., 0.], [ 0., 2., 0.], [ 0., 0., 3.]]) >>> np.fliplr(A) array([[ 0., 0., 1.], [ 0., 2., 0.], [ 3., 0., 0.]]) >>> A = np.random.randn(2,3,5) >>> np.all(np.fliplr(A)==A[:,::-1,...]) True """ m = asanyarray(m) if m.ndim < 2: raise ValueError("Input must be >= 2-d.") return m[:, ::-1] def flipud(m): """ Flip array in the up/down direction. Flip the entries in each column in the up/down direction. Rows are preserved, but appear in a different order than before. Parameters ---------- m : array_like Input array. Returns ------- out : array_like A view of `m` with the rows reversed. Since a view is returned, this operation is :math:`\\mathcal O(1)`. See Also -------- fliplr : Flip array in the left/right direction. rot90 : Rotate array counterclockwise. Notes ----- Equivalent to ``A[::-1,...]``. Does not require the array to be two-dimensional. Examples -------- >>> A = np.diag([1.0, 2, 3]) >>> A array([[ 1., 0., 0.], [ 0., 2., 0.], [ 0., 0., 3.]]) >>> np.flipud(A) array([[ 0., 0., 3.], [ 0., 2., 0.], [ 1., 0., 0.]]) >>> A = np.random.randn(2,3,5) >>> np.all(np.flipud(A)==A[::-1,...]) True >>> np.flipud([1,2]) array([2, 1]) """ m = asanyarray(m) if m.ndim < 1: raise ValueError("Input must be >= 1-d.") return m[::-1, ...] def rot90(m, k=1): """ Rotate an array by 90 degrees in the counter-clockwise direction. The first two dimensions are rotated; therefore, the array must be at least 2-D. Parameters ---------- m : array_like Array of two or more dimensions. k : integer Number of times the array is rotated by 90 degrees. Returns ------- y : ndarray Rotated array. See Also -------- fliplr : Flip an array horizontally. flipud : Flip an array vertically. Examples -------- >>> m = np.array([[1,2],[3,4]], int) >>> m array([[1, 2], [3, 4]]) >>> np.rot90(m) array([[2, 4], [1, 3]]) >>> np.rot90(m, 2) array([[4, 3], [2, 1]]) """ m = asanyarray(m) if m.ndim < 2: raise ValueError("Input must >= 2-d.") k = k % 4 if k == 0: return m elif k == 1: return fliplr(m).swapaxes(0, 1) elif k == 2: return fliplr(flipud(m)) else: # k == 3 return fliplr(m.swapaxes(0, 1)) def eye(N, M=None, k=0, dtype=float): """ Return a 2-D array with ones on the diagonal and zeros elsewhere. Parameters ---------- N : int Number of rows in the output. M : int, optional Number of columns in the output. If None, defaults to `N`. k : int, optional Index of the diagonal: 0 (the default) refers to the main diagonal, a positive value refers to an upper diagonal, and a negative value to a lower diagonal. dtype : data-type, optional Data-type of the returned array. Returns ------- I : ndarray of shape (N,M) An array where all elements are equal to zero, except for the `k`-th diagonal, whose values are equal to one. See Also -------- identity : (almost) equivalent function diag : diagonal 2-D array from a 1-D array specified by the user. Examples -------- >>> np.eye(2, dtype=int) array([[1, 0], [0, 1]]) >>> np.eye(3, k=1) array([[ 0., 1., 0.], [ 0., 0., 1.], [ 0., 0., 0.]]) """ if M is None: M = N m = zeros((N, M), dtype=dtype) if k >= M: return m if k >= 0: i = k else: i = (-k) * M m[:M-k].flat[i::M+1] = 1 return m def diag(v, k=0): """ Extract a diagonal or construct a diagonal array. See the more detailed documentation for ``numpy.diagonal`` if you use this function to extract a diagonal and wish to write to the resulting array; whether it returns a copy or a view depends on what version of numpy you are using. Parameters ---------- v : array_like If `v` is a 2-D array, return a copy of its `k`-th diagonal. If `v` is a 1-D array, return a 2-D array with `v` on the `k`-th diagonal. k : int, optional Diagonal in question. The default is 0. Use `k>0` for diagonals above the main diagonal, and `k<0` for diagonals below the main diagonal. Returns ------- out : ndarray The extracted diagonal or constructed diagonal array. See Also -------- diagonal : Return specified diagonals. diagflat : Create a 2-D array with the flattened input as a diagonal. trace : Sum along diagonals. triu : Upper triangle of an array. tril : Lower triange of an array. Examples -------- >>> x = np.arange(9).reshape((3,3)) >>> x array([[0, 1, 2], [3, 4, 5], [6, 7, 8]]) >>> np.diag(x) array([0, 4, 8]) >>> np.diag(x, k=1) array([1, 5]) >>> np.diag(x, k=-1) array([3, 7]) >>> np.diag(np.diag(x)) array([[0, 0, 0], [0, 4, 0], [0, 0, 8]]) """ v = asarray(v) s = v.shape if len(s) == 1: n = s[0]+abs(k) res = zeros((n, n), v.dtype) if k >= 0: i = k else: i = (-k) * n res[:n-k].flat[i::n+1] = v return res elif len(s) == 2: return v.diagonal(k) else: raise ValueError("Input must be 1- or 2-d.") def diagflat(v, k=0): """ Create a two-dimensional array with the flattened input as a diagonal. Parameters ---------- v : array_like Input data, which is flattened and set as the `k`-th diagonal of the output. k : int, optional Diagonal to set; 0, the default, corresponds to the "main" diagonal, a positive (negative) `k` giving the number of the diagonal above (below) the main. Returns ------- out : ndarray The 2-D output array. See Also -------- diag : MATLAB work-alike for 1-D and 2-D arrays. diagonal : Return specified diagonals. trace : Sum along diagonals. Examples -------- >>> np.diagflat([[1,2], [3,4]]) array([[1, 0, 0, 0], [0, 2, 0, 0], [0, 0, 3, 0], [0, 0, 0, 4]]) >>> np.diagflat([1,2], 1) array([[0, 1, 0], [0, 0, 2], [0, 0, 0]]) """ try: wrap = v.__array_wrap__ except AttributeError: wrap = None v = asarray(v).ravel() s = len(v) n = s + abs(k) res = zeros((n, n), v.dtype) if (k >= 0): i = arange(0, n-k) fi = i+k+i*n else: i = arange(0, n+k) fi = i+(i-k)*n res.flat[fi] = v if not wrap: return res return wrap(res) def tri(N, M=None, k=0, dtype=float): """ An array with ones at and below the given diagonal and zeros elsewhere. Parameters ---------- N : int Number of rows in the array. M : int, optional Number of columns in the array. By default, `M` is taken equal to `N`. k : int, optional The sub-diagonal at and below which the array is filled. `k` = 0 is the main diagonal, while `k` < 0 is below it, and `k` > 0 is above. The default is 0. dtype : dtype, optional Data type of the returned array. The default is float. Returns ------- tri : ndarray of shape (N, M) Array with its lower triangle filled with ones and zero elsewhere; in other words ``T[i,j] == 1`` for ``i <= j + k``, 0 otherwise. Examples -------- >>> np.tri(3, 5, 2, dtype=int) array([[1, 1, 1, 0, 0], [1, 1, 1, 1, 0], [1, 1, 1, 1, 1]]) >>> np.tri(3, 5, -1) array([[ 0., 0., 0., 0., 0.], [ 1., 0., 0., 0., 0.], [ 1., 1., 0., 0., 0.]]) """ if M is None: M = N m = greater_equal(subtract.outer(arange(N), arange(M)), -k) return m.astype(dtype) def tril(m, k=0): """ Lower triangle of an array. Return a copy of an array with elements above the `k`-th diagonal zeroed. Parameters ---------- m : array_like, shape (M, N) Input array. k : int, optional Diagonal above which to zero elements. `k = 0` (the default) is the main diagonal, `k < 0` is below it and `k > 0` is above. Returns ------- tril : ndarray, shape (M, N) Lower triangle of `m`, of same shape and data-type as `m`. See Also -------- triu : same thing, only for the upper triangle Examples -------- >>> np.tril([[1,2,3],[4,5,6],[7,8,9],[10,11,12]], -1) array([[ 0, 0, 0], [ 4, 0, 0], [ 7, 8, 0], [10, 11, 12]]) """ m = asanyarray(m) out = multiply(tri(m.shape[0], m.shape[1], k=k, dtype=m.dtype), m) return out def triu(m, k=0): """ Upper triangle of an array. Return a copy of a matrix with the elements below the `k`-th diagonal zeroed. Please refer to the documentation for `tril` for further details. See Also -------- tril : lower triangle of an array Examples -------- >>> np.triu([[1,2,3],[4,5,6],[7,8,9],[10,11,12]], -1) array([[ 1, 2, 3], [ 4, 5, 6], [ 0, 8, 9], [ 0, 0, 12]]) """ m = asanyarray(m) out = multiply((1 - tri(m.shape[0], m.shape[1], k - 1, dtype=m.dtype)), m) return out # borrowed from John Hunter and matplotlib def vander(x, N=None): """ Generate a Van der Monde matrix. The columns of the output matrix are decreasing powers of the input vector. Specifically, 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 ---------- x : array_like 1-D input array. N : int, optional Order of (number of columns in) the output. If `N` is not specified, a square array is returned (``N = len(x)``). Returns ------- out : ndarray Van der Monde matrix of order `N`. The first column is ``x^(N-1)``, the second ``x^(N-2)`` and so forth. Examples -------- >>> x = np.array([1, 2, 3, 5]) >>> N = 3 >>> np.vander(x, N) array([[ 1, 1, 1], [ 4, 2, 1], [ 9, 3, 1], [25, 5, 1]]) >>> np.column_stack([x**(N-1-i) for i in range(N)]) array([[ 1, 1, 1], [ 4, 2, 1], [ 9, 3, 1], [25, 5, 1]]) >>> x = np.array([1, 2, 3, 5]) >>> np.vander(x) array([[ 1, 1, 1, 1], [ 8, 4, 2, 1], [ 27, 9, 3, 1], [125, 25, 5, 1]]) The determinant of a square Vandermonde matrix is the product of the differences between the values of the input vector: >>> np.linalg.det(np.vander(x)) 48.000000000000043 >>> (5-3)*(5-2)*(5-1)*(3-2)*(3-1)*(2-1) 48 """ x = asarray(x) if N is None: N=len(x) X = ones( (len(x), N), x.dtype) for i in range(N - 1): X[:, i] = x**(N - i - 1) return X def histogram2d(x, y, bins=10, range=None, normed=False, weights=None): """ Compute the bi-dimensional histogram of two data samples. Parameters ---------- x : array_like, shape (N,) 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. bins : int or [int, int] or array_like or [array, array], optional The bin specification: * If int, the number of bins for the two dimensions (nx=ny=bins). * If [int, int], the number of bins in each dimension (nx, ny = bins). * If array_like, the bin edges for the two dimensions (x_edges=y_edges=bins). * If [array, array], the bin edges in each dimension (x_edges, y_edges = bins). range : array_like, shape(2,2), optional The leftmost and rightmost edges of the bins along each dimension (if not specified explicitly in the `bins` parameters): ``[[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 ``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. Returns ------- H : ndarray, shape(nx, ny) The bi-dimensional histogram of samples `x` and `y`. Values in `x` are histogrammed along the first dimension and values in `y` are histogrammed along the second dimension. xedges : ndarray, shape(nx,) The bin edges along the first dimension. yedges : ndarray, shape(ny,) The bin edges along the second dimension. See Also -------- histogram : 1D histogram histogramdd : Multidimensional histogram Notes ----- 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 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 -------- >>> import matplotlib as mpl >>> import matplotlib.pyplot as plt Construct a 2D-histogram with variable bin width. First define the bin edges: >>> xedges = [0, 1, 1.5, 3, 5] >>> yedges = [0, 2, 3, 4, 6] Next we create a histogram H with random bin content: >>> x = np.random.normal(3, 1, 100) >>> y = np.random.normal(1, 1, 100) >>> H, xedges, yedges = np.histogram2d(y, x, bins=(xedges, yedges)) Or we fill the histogram H with a determined bin content: >>> H = np.ones((4, 4)).cumsum().reshape(4, 4) >>> print H[::-1] # This shows the bin content in the order as plotted [[ 13. 14. 15. 16.] [ 9. 10. 11. 12.] [ 5. 6. 7. 8.] [ 1. 2. 3. 4.]] Imshow can only do an equidistant representation of bins: >>> fig = plt.figure(figsize=(7, 3)) >>> ax = fig.add_subplot(131) >>> ax.set_title('imshow:\nequidistant') >>> im = plt.imshow(H, interpolation='nearest', origin='low', extent=[xedges[0], xedges[-1], yedges[0], yedges[-1]]) pcolormesh can displaying exact bin edges: >>> ax = fig.add_subplot(132) >>> ax.set_title('pcolormesh:\nexact bin edges') >>> X, Y = np.meshgrid(xedges, yedges) >>> ax.pcolormesh(X, Y, H) >>> ax.set_aspect('equal') NonUniformImage displays exact bin edges with interpolation: >>> ax = fig.add_subplot(133) >>> ax.set_title('NonUniformImage:\ninterpolated') >>> 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]) >>> im.set_data(xcenters, ycenters, H) >>> ax.images.append(im) >>> ax.set_xlim(xedges[0], xedges[-1]) >>> ax.set_ylim(yedges[0], yedges[-1]) >>> ax.set_aspect('equal') >>> plt.show() """ from numpy import histogramdd try: N = len(bins) except TypeError: N = 1 if N != 1 and N != 2: xedges = yedges = asarray(bins, float) bins = [xedges, yedges] hist, edges = histogramdd([x, y], bins, range, normed, weights) return hist, edges[0], edges[1] def mask_indices(n, mask_func, k=0): """ Return the indices to access (n, n) arrays, given a masking function. Assume `mask_func` is a function that, for a square array a of size ``(n, n)`` with a possible offset argument `k`, when called as ``mask_func(a, k)`` returns a new array with zeros in certain locations (functions like `triu` or `tril` do precisely this). Then this function returns the indices where the non-zero values would be located. Parameters ---------- n : int The returned indices will be valid to access arrays of shape (n, n). mask_func : callable A function whose call signature is similar to that of `triu`, `tril`. That is, ``mask_func(x, k)`` returns a boolean array, shaped like `x`. `k` is an optional argument to the function. k : scalar An optional argument which is passed through to `mask_func`. Functions like `triu`, `tril` take a second argument that is interpreted as an offset. Returns ------- indices : tuple of arrays. The `n` arrays of indices corresponding to the locations where ``mask_func(np.ones((n, n)), k)`` is True. See Also -------- triu, tril, triu_indices, tril_indices Notes ----- .. versionadded:: 1.4.0 Examples -------- These are the indices that would allow you to access the upper triangular part of any 3x3 array: >>> iu = np.mask_indices(3, np.triu) For example, if `a` is a 3x3 array: >>> a = np.arange(9).reshape(3, 3) >>> a array([[0, 1, 2], [3, 4, 5], [6, 7, 8]]) >>> a[iu] array([0, 1, 2, 4, 5, 8]) An offset can be passed also to the masking function. This gets us the indices starting on the first diagonal right of the main one: >>> iu1 = np.mask_indices(3, np.triu, 1) with which we now extract only three elements: >>> a[iu1] array([1, 2, 5]) """ m = ones((n, n), int) a = mask_func(m, k) return where(a != 0) def tril_indices(n, k=0): """ Return the indices for the lower-triangle of an (n, n) array. Parameters ---------- n : int The row dimension of the square arrays for which the returned indices will be valid. k : int, optional Diagonal offset (see `tril` for details). Returns ------- inds : tuple of arrays The indices for the triangle. The returned tuple contains two arrays, each with the indices along one dimension of the array. See also -------- triu_indices : similar function, for upper-triangular. mask_indices : generic function accepting an arbitrary mask function. tril, triu Notes ----- .. versionadded:: 1.4.0 Examples -------- Compute two different sets of indices to access 4x4 arrays, one for the lower triangular part starting at the main diagonal, and one starting two diagonals further right: >>> il1 = np.tril_indices(4) >>> il2 = np.tril_indices(4, 2) Here is how they can be used with a sample array: >>> a = np.arange(16).reshape(4, 4) >>> a array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11], [12, 13, 14, 15]]) Both for indexing: >>> a[il1] array([ 0, 4, 5, 8, 9, 10, 12, 13, 14, 15]) And for assigning values: >>> a[il1] = -1 >>> a array([[-1, 1, 2, 3], [-1, -1, 6, 7], [-1, -1, -1, 11], [-1, -1, -1, -1]]) These cover almost the whole array (two diagonals right of the main one): >>> a[il2] = -10 >>> a array([[-10, -10, -10, 3], [-10, -10, -10, -10], [-10, -10, -10, -10], [-10, -10, -10, -10]]) """ return mask_indices(n, tril, k) def tril_indices_from(arr, k=0): """ Return the indices for the lower-triangle of arr. See `tril_indices` for full details. Parameters ---------- arr : array_like The indices will be valid for square arrays whose dimensions are the same as arr. k : int, optional Diagonal offset (see `tril` for details). See Also -------- tril_indices, tril Notes ----- .. 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) def triu_indices(n, k=0): """ Return the indices for the upper-triangle of an (n, n) array. Parameters ---------- n : int The size of the arrays for which the returned indices will be valid. k : int, optional Diagonal offset (see `triu` for details). Returns ------- inds : tuple, shape(2) of ndarrays, shape(`n`) The indices for the triangle. The returned tuple contains two arrays, each with the indices along one dimension of the array. Can be used to slice a ndarray of shape(`n`, `n`). See also -------- tril_indices : similar function, for lower-triangular. mask_indices : generic function accepting an arbitrary mask function. triu, tril Notes ----- .. versionadded:: 1.4.0 Examples -------- Compute two different sets of indices to access 4x4 arrays, one for the upper triangular part starting at the main diagonal, and one starting two diagonals further right: >>> iu1 = np.triu_indices(4) >>> iu2 = np.triu_indices(4, 2) Here is how they can be used with a sample array: >>> a = np.arange(16).reshape(4, 4) >>> a array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11], [12, 13, 14, 15]]) Both for indexing: >>> a[iu1] array([ 0, 1, 2, 3, 5, 6, 7, 10, 11, 15]) And for assigning values: >>> a[iu1] = -1 >>> a array([[-1, -1, -1, -1], [ 4, -1, -1, -1], [ 8, 9, -1, -1], [12, 13, 14, -1]]) These cover only a small part of the whole array (two diagonals right of the main one): >>> a[iu2] = -10 >>> a array([[ -1, -1, -10, -10], [ 4, -1, -1, -10], [ 8, 9, -1, -1], [ 12, 13, 14, -1]]) """ return mask_indices(n, triu, k) def triu_indices_from(arr, k=0): """ Return the indices for the upper-triangle of a (N, N) array. See `triu_indices` for full details. Parameters ---------- arr : ndarray, shape(N, N) The indices will be valid for square arrays. k : int, optional Diagonal offset (see `triu` for details). Returns ------- triu_indices_from : tuple, shape(2) of ndarray, shape(N) Indices for the upper-triangle of `arr`. See Also -------- triu_indices, triu Notes ----- .. 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) numpy-1.8.2/numpy/lib/scimath.py0000664000175100017510000003337212370216243017754 0ustar vagrantvagrant00000000000000""" Wrapper functions to more user-friendly calling of certain math functions whose output data-type is different than the input data-type in certain domains of the input. For example, for functions like `log` with branch cuts, the versions in this module provide the mathematically valid answers in the complex plane:: >>> import math >>> from numpy.lib import scimath >>> scimath.log(-math.exp(1)) == (1+1j*math.pi) True Similarly, `sqrt`, other base logarithms, `power` and trig functions are correctly handled. See their respective docstrings for specific examples. """ from __future__ import division, absolute_import, print_function __all__ = ['sqrt', 'log', 'log2', 'logn', 'log10', 'power', 'arccos', 'arcsin', 'arctanh'] import numpy.core.numeric as nx import numpy.core.numerictypes as nt from numpy.core.numeric import asarray, any from numpy.lib.type_check import isreal _ln2 = nx.log(2.0) def _tocomplex(arr): """Convert its input `arr` to a complex array. The input is returned as a complex array of the smallest type that will fit the original data: types like single, byte, short, etc. become csingle, while others become cdouble. A copy of the input is always made. Parameters ---------- arr : array Returns ------- array An array with the same input data as the input but in complex form. Examples -------- First, consider an input of type short: >>> a = np.array([1,2,3],np.short) >>> ac = np.lib.scimath._tocomplex(a); ac array([ 1.+0.j, 2.+0.j, 3.+0.j], dtype=complex64) >>> ac.dtype dtype('complex64') If the input is of type double, the output is correspondingly of the complex double type as well: >>> b = np.array([1,2,3],np.double) >>> bc = np.lib.scimath._tocomplex(b); bc array([ 1.+0.j, 2.+0.j, 3.+0.j]) >>> bc.dtype dtype('complex128') Note that even if the input was complex to begin with, a copy is still made, since the astype() method always copies: >>> c = np.array([1,2,3],np.csingle) >>> cc = np.lib.scimath._tocomplex(c); cc array([ 1.+0.j, 2.+0.j, 3.+0.j], dtype=complex64) >>> c *= 2; c array([ 2.+0.j, 4.+0.j, 6.+0.j], dtype=complex64) >>> cc array([ 1.+0.j, 2.+0.j, 3.+0.j], dtype=complex64) """ if issubclass(arr.dtype.type, (nt.single, nt.byte, nt.short, nt.ubyte, nt.ushort, nt.csingle)): return arr.astype(nt.csingle) else: return arr.astype(nt.cdouble) def _fix_real_lt_zero(x): """Convert `x` to complex if it has real, negative components. Otherwise, output is just the array version of the input (via asarray). Parameters ---------- x : array_like Returns ------- array Examples -------- >>> np.lib.scimath._fix_real_lt_zero([1,2]) array([1, 2]) >>> np.lib.scimath._fix_real_lt_zero([-1,2]) array([-1.+0.j, 2.+0.j]) """ x = asarray(x) if any(isreal(x) & (x<0)): x = _tocomplex(x) return x def _fix_int_lt_zero(x): """Convert `x` to double if it has real, negative components. Otherwise, output is just the array version of the input (via asarray). Parameters ---------- x : array_like Returns ------- array Examples -------- >>> np.lib.scimath._fix_int_lt_zero([1,2]) array([1, 2]) >>> np.lib.scimath._fix_int_lt_zero([-1,2]) array([-1., 2.]) """ x = asarray(x) if any(isreal(x) & (x < 0)): x = x * 1.0 return x def _fix_real_abs_gt_1(x): """Convert `x` to complex if it has real components x_i with abs(x_i)>1. Otherwise, output is just the array version of the input (via asarray). Parameters ---------- x : array_like Returns ------- array Examples -------- >>> np.lib.scimath._fix_real_abs_gt_1([0,1]) array([0, 1]) >>> np.lib.scimath._fix_real_abs_gt_1([0,2]) array([ 0.+0.j, 2.+0.j]) """ x = asarray(x) if any(isreal(x) & (abs(x)>1)): x = _tocomplex(x) return x def sqrt(x): """ Compute the square root of x. For negative input elements, a complex value is returned (unlike `numpy.sqrt` which returns NaN). Parameters ---------- x : array_like The input value(s). Returns ------- out : ndarray or scalar The square root of `x`. If `x` was a scalar, so is `out`, otherwise an array is returned. See Also -------- numpy.sqrt Examples -------- For real, non-negative inputs this works just like `numpy.sqrt`: >>> np.lib.scimath.sqrt(1) 1.0 >>> np.lib.scimath.sqrt([1, 4]) array([ 1., 2.]) But it automatically handles negative inputs: >>> np.lib.scimath.sqrt(-1) (0.0+1.0j) >>> np.lib.scimath.sqrt([-1,4]) array([ 0.+1.j, 2.+0.j]) """ x = _fix_real_lt_zero(x) return nx.sqrt(x) def log(x): """ Compute the natural logarithm of `x`. Return the "principal value" (for a description of this, see `numpy.log`) of :math:`log_e(x)`. For real `x > 0`, this is a real number (``log(0)`` returns ``-inf`` and ``log(np.inf)`` returns ``inf``). Otherwise, the complex principle value is returned. Parameters ---------- x : array_like The value(s) whose log is (are) required. Returns ------- out : ndarray or scalar The log of the `x` value(s). If `x` was a scalar, so is `out`, otherwise an array is returned. See Also -------- numpy.log Notes ----- For a log() that returns ``NAN`` when real `x < 0`, use `numpy.log` (note, however, that otherwise `numpy.log` and this `log` are identical, i.e., both return ``-inf`` for `x = 0`, ``inf`` for `x = inf`, and, notably, the complex principle value if ``x.imag != 0``). Examples -------- >>> np.emath.log(np.exp(1)) 1.0 Negative arguments are handled "correctly" (recall that ``exp(log(x)) == x`` does *not* hold for real ``x < 0``): >>> np.emath.log(-np.exp(1)) == (1 + np.pi * 1j) True """ x = _fix_real_lt_zero(x) return nx.log(x) def log10(x): """ Compute the logarithm base 10 of `x`. Return the "principal value" (for a description of this, see `numpy.log10`) of :math:`log_{10}(x)`. For real `x > 0`, this is a real number (``log10(0)`` returns ``-inf`` and ``log10(np.inf)`` returns ``inf``). Otherwise, the complex principle value is returned. Parameters ---------- x : array_like or scalar The value(s) whose log base 10 is (are) required. Returns ------- out : ndarray or scalar The log base 10 of the `x` value(s). If `x` was a scalar, so is `out`, otherwise an array object is returned. See Also -------- numpy.log10 Notes ----- For a log10() that returns ``NAN`` when real `x < 0`, use `numpy.log10` (note, however, that otherwise `numpy.log10` and this `log10` are identical, i.e., both return ``-inf`` for `x = 0`, ``inf`` for `x = inf`, and, notably, the complex principle value if ``x.imag != 0``). Examples -------- (We set the printing precision so the example can be auto-tested) >>> np.set_printoptions(precision=4) >>> np.emath.log10(10**1) 1.0 >>> np.emath.log10([-10**1, -10**2, 10**2]) array([ 1.+1.3644j, 2.+1.3644j, 2.+0.j ]) """ x = _fix_real_lt_zero(x) return nx.log10(x) def logn(n, x): """ Take log base n of x. If `x` contains negative inputs, the answer is computed and returned in the complex domain. Parameters ---------- n : int The base in which the log is taken. x : array_like The value(s) whose log base `n` is (are) required. Returns ------- out : ndarray or scalar The log base `n` of the `x` value(s). If `x` was a scalar, so is `out`, otherwise an array is returned. Examples -------- >>> np.set_printoptions(precision=4) >>> np.lib.scimath.logn(2, [4, 8]) array([ 2., 3.]) >>> np.lib.scimath.logn(2, [-4, -8, 8]) array([ 2.+4.5324j, 3.+4.5324j, 3.+0.j ]) """ x = _fix_real_lt_zero(x) n = _fix_real_lt_zero(n) return nx.log(x)/nx.log(n) def log2(x): """ Compute the logarithm base 2 of `x`. Return the "principal value" (for a description of this, see `numpy.log2`) of :math:`log_2(x)`. For real `x > 0`, this is a real number (``log2(0)`` returns ``-inf`` and ``log2(np.inf)`` returns ``inf``). Otherwise, the complex principle value is returned. Parameters ---------- x : array_like The value(s) whose log base 2 is (are) required. Returns ------- out : ndarray or scalar The log base 2 of the `x` value(s). If `x` was a scalar, so is `out`, otherwise an array is returned. See Also -------- numpy.log2 Notes ----- For a log2() that returns ``NAN`` when real `x < 0`, use `numpy.log2` (note, however, that otherwise `numpy.log2` and this `log2` are identical, i.e., both return ``-inf`` for `x = 0`, ``inf`` for `x = inf`, and, notably, the complex principle value if ``x.imag != 0``). Examples -------- We set the printing precision so the example can be auto-tested: >>> np.set_printoptions(precision=4) >>> np.emath.log2(8) 3.0 >>> np.emath.log2([-4, -8, 8]) array([ 2.+4.5324j, 3.+4.5324j, 3.+0.j ]) """ x = _fix_real_lt_zero(x) return nx.log2(x) def power(x, p): """ Return x to the power p, (x**p). If `x` contains negative values, the output is converted to the complex domain. Parameters ---------- x : array_like The input value(s). p : array_like of ints The power(s) to which `x` is raised. If `x` contains multiple values, `p` has to either be a scalar, or contain the same number of values as `x`. In the latter case, the result is ``x[0]**p[0], x[1]**p[1], ...``. Returns ------- out : ndarray or scalar The result of ``x**p``. If `x` and `p` are scalars, so is `out`, otherwise an array is returned. See Also -------- numpy.power Examples -------- >>> np.set_printoptions(precision=4) >>> np.lib.scimath.power([2, 4], 2) array([ 4, 16]) >>> np.lib.scimath.power([2, 4], -2) array([ 0.25 , 0.0625]) >>> np.lib.scimath.power([-2, 4], 2) array([ 4.+0.j, 16.+0.j]) """ x = _fix_real_lt_zero(x) p = _fix_int_lt_zero(p) return nx.power(x, p) def arccos(x): """ Compute the inverse cosine of x. Return the "principal value" (for a description of this, see `numpy.arccos`) of the inverse cosine of `x`. For real `x` such that `abs(x) <= 1`, this is a real number in the closed interval :math:`[0, \\pi]`. Otherwise, the complex principle value is returned. Parameters ---------- x : array_like or scalar The value(s) whose arccos is (are) required. Returns ------- out : ndarray or scalar The inverse cosine(s) of the `x` value(s). If `x` was a scalar, so is `out`, otherwise an array object is returned. See Also -------- numpy.arccos Notes ----- For an arccos() that returns ``NAN`` when real `x` is not in the interval ``[-1,1]``, use `numpy.arccos`. Examples -------- >>> np.set_printoptions(precision=4) >>> np.emath.arccos(1) # a scalar is returned 0.0 >>> np.emath.arccos([1,2]) array([ 0.-0.j , 0.+1.317j]) """ x = _fix_real_abs_gt_1(x) return nx.arccos(x) def arcsin(x): """ Compute the inverse sine of x. Return the "principal value" (for a description of this, see `numpy.arcsin`) of the inverse sine of `x`. For real `x` such that `abs(x) <= 1`, this is a real number in the closed interval :math:`[-\\pi/2, \\pi/2]`. Otherwise, the complex principle value is returned. Parameters ---------- x : array_like or scalar The value(s) whose arcsin is (are) required. Returns ------- out : ndarray or scalar The inverse sine(s) of the `x` value(s). If `x` was a scalar, so is `out`, otherwise an array object is returned. See Also -------- numpy.arcsin Notes ----- For an arcsin() that returns ``NAN`` when real `x` is not in the interval ``[-1,1]``, use `numpy.arcsin`. Examples -------- >>> np.set_printoptions(precision=4) >>> np.emath.arcsin(0) 0.0 >>> np.emath.arcsin([0,1]) array([ 0. , 1.5708]) """ x = _fix_real_abs_gt_1(x) return nx.arcsin(x) def arctanh(x): """ Compute the inverse hyperbolic tangent of `x`. Return the "principal value" (for a description of this, see `numpy.arctanh`) of `arctanh(x)`. For real `x` such that `abs(x) < 1`, this is a real number. If `abs(x) > 1`, or if `x` is complex, the result is complex. Finally, `x = 1` returns``inf`` and `x=-1` returns ``-inf``. Parameters ---------- x : array_like The value(s) whose arctanh is (are) required. Returns ------- out : ndarray or scalar The inverse hyperbolic tangent(s) of the `x` value(s). If `x` was a scalar so is `out`, otherwise an array is returned. See Also -------- numpy.arctanh Notes ----- For an arctanh() that returns ``NAN`` when real `x` is not in the interval ``(-1,1)``, use `numpy.arctanh` (this latter, however, does return +/-inf for `x = +/-1`). Examples -------- >>> np.set_printoptions(precision=4) >>> np.emath.arctanh(np.matrix(np.eye(2))) array([[ Inf, 0.], [ 0., Inf]]) >>> np.emath.arctanh([1j]) array([ 0.+0.7854j]) """ x = _fix_real_abs_gt_1(x) return nx.arctanh(x) numpy-1.8.2/numpy/lib/arraysetops.py0000664000175100017510000003065112370216243020675 0ustar vagrantvagrant00000000000000""" Set operations for 1D numeric arrays based on sorting. :Contains: ediff1d, unique, intersect1d, setxor1d, in1d, union1d, setdiff1d :Notes: For floating point arrays, inaccurate results may appear due to usual round-off and floating point comparison issues. Speed could be gained in some operations by an implementation of sort(), that can provide directly the permutation vectors, avoiding thus calls to argsort(). To do: Optionally return indices analogously to unique for all functions. :Author: Robert Cimrman """ from __future__ import division, absolute_import, print_function __all__ = ['ediff1d', 'intersect1d', 'setxor1d', 'union1d', 'setdiff1d', 'unique', 'in1d'] import numpy as np from numpy.lib.utils import deprecate def ediff1d(ary, to_end=None, to_begin=None): """ The differences between consecutive elements of an array. Parameters ---------- ary : array_like If necessary, will be flattened before the differences are taken. to_end : array_like, optional Number(s) to append at the end of the returned differences. to_begin : array_like, optional Number(s) to prepend at the beginning of the returned differences. Returns ------- ediff1d : ndarray The differences. Loosely, this is ``ary.flat[1:] - ary.flat[:-1]``. See Also -------- diff, gradient Notes ----- When applied to masked arrays, this function drops the mask information if the `to_begin` and/or `to_end` parameters are used. Examples -------- >>> x = np.array([1, 2, 4, 7, 0]) >>> np.ediff1d(x) array([ 1, 2, 3, -7]) >>> np.ediff1d(x, to_begin=-99, to_end=np.array([88, 99])) array([-99, 1, 2, 3, -7, 88, 99]) The returned array is always 1D. >>> y = [[1, 2, 4], [1, 6, 24]] >>> np.ediff1d(y) array([ 1, 2, -3, 5, 18]) """ ary = np.asanyarray(ary).flat ed = ary[1:] - ary[:-1] arrays = [ed] if to_begin is not None: arrays.insert(0, to_begin) if to_end is not None: arrays.append(to_end) if len(arrays) != 1: # We'll save ourselves a copy of a potentially large array in # the common case where neither to_begin or to_end was given. ed = np.hstack(arrays) return ed def unique(ar, return_index=False, return_inverse=False): """ Find the unique elements of an array. Returns the sorted unique elements of an array. There are two optional outputs in addition to the unique elements: the indices of the input array that give the unique values, and the indices of the unique array that reconstruct the input array. Parameters ---------- ar : array_like Input array. This will be flattened if it is not already 1-D. return_index : bool, optional If True, also return the indices of `ar` that result in the unique array. return_inverse : bool, optional If True, also return the indices of the unique array that can be used to reconstruct `ar`. Returns ------- unique : ndarray The sorted unique values. unique_indices : ndarray, optional The indices of the first occurrences of the unique values in the (flattened) original array. Only provided if `return_index` is True. unique_inverse : ndarray, optional The indices to reconstruct the (flattened) original array from the unique array. Only provided if `return_inverse` is True. See Also -------- numpy.lib.arraysetops : Module with a number of other functions for performing set operations on arrays. Examples -------- >>> np.unique([1, 1, 2, 2, 3, 3]) array([1, 2, 3]) >>> a = np.array([[1, 1], [2, 3]]) >>> np.unique(a) array([1, 2, 3]) Return the indices of the original array that give the unique values: >>> a = np.array(['a', 'b', 'b', 'c', 'a']) >>> u, indices = np.unique(a, return_index=True) >>> u array(['a', 'b', 'c'], dtype='|S1') >>> indices array([0, 1, 3]) >>> a[indices] array(['a', 'b', 'c'], dtype='|S1') Reconstruct the input array from the unique values: >>> a = np.array([1, 2, 6, 4, 2, 3, 2]) >>> u, indices = np.unique(a, return_inverse=True) >>> u array([1, 2, 3, 4, 6]) >>> indices array([0, 1, 4, 3, 1, 2, 1]) >>> u[indices] array([1, 2, 6, 4, 2, 3, 2]) """ try: ar = ar.flatten() except AttributeError: if not return_inverse and not return_index: return np.sort(list(set(ar))) else: ar = np.asanyarray(ar).flatten() 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) else: return ar if return_inverse or return_index: if return_index: perm = ar.argsort(kind='mergesort') else: perm = ar.argsort() aux = ar[perm] flag = np.concatenate(([True], aux[1:] != aux[:-1])) 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] def intersect1d(ar1, ar2, assume_unique=False): """ Find the intersection of two arrays. Return the sorted, unique values that are in both of the input arrays. Parameters ---------- ar1, ar2 : array_like Input arrays. assume_unique : bool If True, the input arrays are both assumed to be unique, which can speed up the calculation. Default is False. Returns ------- intersect1d : ndarray Sorted 1D array of common and unique elements. See Also -------- numpy.lib.arraysetops : Module with a number of other functions for performing set operations on arrays. Examples -------- >>> np.intersect1d([1, 3, 4, 3], [3, 1, 2, 1]) array([1, 3]) """ if not assume_unique: # Might be faster than unique( intersect1d( ar1, ar2 ) )? ar1 = unique(ar1) ar2 = unique(ar2) aux = np.concatenate( (ar1, ar2) ) aux.sort() return aux[:-1][aux[1:] == aux[:-1]] def setxor1d(ar1, ar2, assume_unique=False): """ Find the set exclusive-or of two arrays. Return the sorted, unique values that are in only one (not both) of the input arrays. Parameters ---------- ar1, ar2 : array_like Input arrays. assume_unique : bool If True, the input arrays are both assumed to be unique, which can speed up the calculation. Default is False. Returns ------- setxor1d : ndarray Sorted 1D array of unique values that are in only one of the input arrays. Examples -------- >>> a = np.array([1, 2, 3, 2, 4]) >>> b = np.array([2, 3, 5, 7, 5]) >>> np.setxor1d(a,b) array([1, 4, 5, 7]) """ if not assume_unique: ar1 = unique(ar1) ar2 = unique(ar2) aux = np.concatenate( (ar1, ar2) ) if aux.size == 0: return aux aux.sort() # flag = ediff1d( aux, to_end = 1, to_begin = 1 ) == 0 flag = np.concatenate( ([True], aux[1:] != aux[:-1], [True] ) ) # flag2 = ediff1d( flag ) == 0 flag2 = flag[1:] == flag[:-1] return aux[flag2] def in1d(ar1, ar2, assume_unique=False, invert=False): """ Test whether each element of a 1-D array is also present in a second array. Returns a boolean array the same length as `ar1` that is True where an element of `ar1` is in `ar2` and False otherwise. Parameters ---------- ar1 : (M,) array_like Input array. ar2 : array_like The values against which to test each value of `ar1`. assume_unique : bool, optional If True, the input arrays are both assumed to be unique, which can speed up the calculation. Default is False. invert : bool, optional If True, the values in the returned array are inverted (that is, False where an element of `ar1` is in `ar2` and True otherwise). Default is False. ``np.in1d(a, b, invert=True)`` is equivalent to (but is faster than) ``np.invert(in1d(a, b))``. .. versionadded:: 1.8.0 Returns ------- in1d : (M,) ndarray, bool The values `ar1[in1d]` are in `ar2`. See Also -------- numpy.lib.arraysetops : Module with a number of other functions for performing set operations on arrays. Notes ----- `in1d` can be considered as an element-wise function version of the python keyword `in`, for 1-D sequences. ``in1d(a, b)`` is roughly equivalent to ``np.array([item in b for item in a])``. .. versionadded:: 1.4.0 Examples -------- >>> test = np.array([0, 1, 2, 5, 0]) >>> states = [0, 2] >>> mask = np.in1d(test, states) >>> mask array([ True, False, True, False, True], dtype=bool) >>> test[mask] array([0, 2, 0]) >>> mask = np.in1d(test, states, invert=True) >>> mask array([False, True, False, True, False], dtype=bool) >>> test[mask] array([1, 5]) """ # Ravel both arrays, behavior for the first array could be different ar1 = np.asarray(ar1).ravel() ar2 = np.asarray(ar2).ravel() # This code is significantly faster when the condition is satisfied. if len(ar2) < 10 * len(ar1) ** 0.145: if invert: mask = np.ones(len(ar1), dtype=np.bool) for a in ar2: mask &= (ar1 != a) else: mask = np.zeros(len(ar1), dtype=np.bool) for a in ar2: mask |= (ar1 == a) return mask # Otherwise use sorting if not assume_unique: ar1, rev_idx = np.unique(ar1, return_inverse=True) ar2 = np.unique(ar2) ar = np.concatenate( (ar1, ar2) ) # We need this to be a stable sort, so always use 'mergesort' # here. The values from the first array should always come before # the values from the second array. order = ar.argsort(kind='mergesort') sar = ar[order] if invert: bool_ar = (sar[1:] != sar[:-1]) else: bool_ar = (sar[1:] == sar[:-1]) flag = np.concatenate( (bool_ar, [invert]) ) indx = order.argsort(kind='mergesort')[:len( ar1 )] if assume_unique: return flag[indx] else: return flag[indx][rev_idx] def union1d(ar1, ar2): """ Find the union of two arrays. Return the unique, sorted array of values that are in either of the two input arrays. Parameters ---------- ar1, ar2 : array_like Input arrays. They are flattened if they are not already 1D. Returns ------- union1d : ndarray Unique, sorted union of the input arrays. See Also -------- numpy.lib.arraysetops : Module with a number of other functions for performing set operations on arrays. Examples -------- >>> np.union1d([-1, 0, 1], [-2, 0, 2]) array([-2, -1, 0, 1, 2]) """ return unique( np.concatenate( (ar1, ar2) ) ) def setdiff1d(ar1, ar2, assume_unique=False): """ Find the set difference of two arrays. Return the sorted, unique values in `ar1` that are not in `ar2`. Parameters ---------- ar1 : array_like Input array. ar2 : array_like Input comparison array. assume_unique : bool If True, the input arrays are both assumed to be unique, which can speed up the calculation. Default is False. Returns ------- setdiff1d : ndarray Sorted 1D array of values in `ar1` that are not in `ar2`. See Also -------- numpy.lib.arraysetops : Module with a number of other functions for performing set operations on arrays. Examples -------- >>> a = np.array([1, 2, 3, 2, 4, 1]) >>> b = np.array([3, 4, 5, 6]) >>> np.setdiff1d(a, b) array([1, 2]) """ if not assume_unique: ar1 = unique(ar1) ar2 = unique(ar2) aux = in1d(ar1, ar2, assume_unique=True) if aux.size == 0: return aux else: return np.asarray(ar1)[aux == 0] numpy-1.8.2/numpy/lib/src/0000775000175100017510000000000012371375430016536 5ustar vagrantvagrant00000000000000numpy-1.8.2/numpy/lib/src/_compiled_base.c0000664000175100017510000014154012370216243021627 0ustar vagrantvagrant00000000000000#define NPY_NO_DEPRECATED_API NPY_API_VERSION #include "Python.h" #include "structmember.h" #include "numpy/arrayobject.h" #include "numpy/npy_3kcompat.h" #include "npy_config.h" #include "numpy/ufuncobject.h" #include "string.h" static npy_intp incr_slot_(double x, double *bins, npy_intp lbins) { npy_intp i; for ( i = 0; i < lbins; i ++ ) { if ( x < bins [i] ) { return i; } } return lbins; } static npy_intp decr_slot_(double x, double * bins, npy_intp lbins) { npy_intp i; for ( i = lbins - 1; i >= 0; i -- ) { if (x < bins [i]) { return i + 1; } } return 0; } static npy_intp incr_slot_right_(double x, double *bins, npy_intp lbins) { npy_intp i; for ( i = 0; i < lbins; i ++ ) { if ( x <= bins [i] ) { return i; } } return lbins; } static npy_intp decr_slot_right_(double x, double * bins, npy_intp lbins) { npy_intp i; for ( i = lbins - 1; i >= 0; i -- ) { if (x <= bins [i]) { return i + 1; } } 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) { int i; if (a [0] <= a [1]) { /* possibly monotonic increasing */ for (i = 1; i < lena - 1; i ++) { if (a [i] > a [i + 1]) { return 0; } } return 1; } else { /* possibly monotonic decreasing */ for (i = 1; i < lena - 1; i ++) { if (a [i] < a [i + 1]) { return 0; } } return -1; } } /* find the index of the maximum element of an integer array */ static npy_intp mxx (npy_intp *i , npy_intp len) { npy_intp mx = 0, max = i[0]; npy_intp j; for ( j = 1; j < len; j ++ ) { if ( i [j] > max ) { max = i [j]; mx = j; } } 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; } /* * arr_bincount is registered as bincount. * * bincount accepts one, two or three arguments. The first is an array of * non-negative integers The second, if present, is an array of weights, * which must be promotable to double. Call these arguments list and * weight. Both must be one-dimensional with len(weight) == len(list). If * weight is not present then bincount(list)[i] is the number of occurrences * of i in list. If weight is present then bincount(self,list, weight)[i] * is the sum of all weight[j] where list [j] == i. Self is not used. * The third argument, if present, is a minimum length desired for the * output array. */ static PyObject * 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; int i; double *weights , *dans; static char *kwlist[] = {"list", "weights", "minlength", NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|OO", kwlist, &list, &weight, &mlength)) { goto fail; } lst = (PyArrayObject *)PyArray_ContiguousFromAny(list, NPY_INTP, 1, 1); if (lst == NULL) { goto fail; } 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))) { goto fail; } if (!(ans = (PyArrayObject *)PyArray_Zeros(1, &minlength, type, 0))){ goto fail; } Py_DECREF(lst); return (PyObject *)ans; } numbers = (npy_intp *) PyArray_DATA(lst); mxi = mxx(numbers, len); mni = mnx(numbers, len); if (numbers[mni] < 0) { PyErr_SetString(PyExc_ValueError, "The first argument of bincount must be non-negative"); goto fail; } ans_size = numbers [mxi] + 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; } } if (weight == Py_None) { ans = (PyArrayObject *)PyArray_Zeros(1, &ans_size, type, 0); if (ans == NULL) { goto fail; } ians = (npy_intp *)(PyArray_DATA(ans)); NPY_BEGIN_ALLOW_THREADS; for (i = 0; i < len; i++) ians [numbers [i]] += 1; NPY_END_ALLOW_THREADS; Py_DECREF(lst); } else { wts = (PyArrayObject *)PyArray_ContiguousFromAny( weight, NPY_DOUBLE, 1, 1); if (wts == NULL) { goto fail; } weights = (double *)PyArray_DATA (wts); if (PyArray_SIZE(wts) != len) { PyErr_SetString(PyExc_ValueError, "The weights and list don't have the same length."); goto fail; } type = PyArray_DescrFromType(NPY_DOUBLE); ans = (PyArrayObject *)PyArray_Zeros(1, &ans_size, type, 0); if (ans == NULL) { goto fail; } dans = (double *)PyArray_DATA(ans); NPY_BEGIN_ALLOW_THREADS; for (i = 0; i < len; i++) { dans[numbers[i]] += weights[i]; } NPY_END_ALLOW_THREADS; Py_DECREF(lst); Py_DECREF(wts); } return (PyObject *)ans; fail: Py_XDECREF(lst); Py_XDECREF(wts); Py_XDECREF(ans); return NULL; } /* * digitize (x, bins, right=False) returns an array of python integers the same * length of x. The values i returned are such that bins [i - 1] <= x < * bins [i] if bins is monotonically increasing, or bins [i - 1] > x >= * bins [i] if bins is monotonically decreasing. Beyond the bounds of * bins, returns either i = 0 or i = len (bins) as appropriate. * if right == True the comparison is bins [i - 1] < x <= bins[i] * or bins [i - 1] >= x > bins[i] */ static PyObject * arr_digitize(PyObject *NPY_UNUSED(self), PyObject *args, PyObject *kwds) { /* self is not used */ PyObject *ox, *obins; PyArrayObject *ax = NULL, *abins = NULL, *aret = NULL; double *dx, *dbins; npy_intp lbins, lx; /* lengths */ npy_intp right = 0; /* whether right or left is inclusive */ npy_intp *iret; int m, i; static char *kwlist[] = {"x", "bins", "right", NULL}; PyArray_Descr *type; char bins_non_monotonic = 0; if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO|i", kwlist, &ox, &obins, &right)) { goto fail; } type = PyArray_DescrFromType(NPY_DOUBLE); ax = (PyArrayObject *)PyArray_FromAny(ox, type, 1, 1, NPY_ARRAY_CARRAY, NULL); if (ax == NULL) { goto fail; } Py_INCREF(type); abins = (PyArrayObject *)PyArray_FromAny(obins, type, 1, 1, NPY_ARRAY_CARRAY, NULL); if (abins == NULL) { goto fail; } lx = PyArray_SIZE(ax); dx = (double *)PyArray_DATA(ax); lbins = PyArray_SIZE(abins); dbins = (double *)PyArray_DATA(abins); aret = (PyArrayObject *)PyArray_SimpleNew(1, &lx, NPY_INTP); if (aret == NULL) { goto fail; } iret = (npy_intp *)PyArray_DATA(aret); if (lx <= 0 || lbins < 0) { PyErr_SetString(PyExc_ValueError, "Both x and bins must have non-zero length"); goto fail; } NPY_BEGIN_ALLOW_THREADS; if (lbins == 1) { if (right == 0) { for (i = 0; i < lx; i++) { if (dx [i] >= dbins[0]) { iret[i] = 1; } else { iret[i] = 0; } } } else { for (i = 0; i < lx; i++) { if (dx [i] > dbins[0]) { iret[i] = 1; } else { iret[i] = 0; } } } } else { m = check_array_monotonic(dbins, lbins); if (right == 0) { if ( m == -1 ) { for ( i = 0; i < lx; i ++ ) { iret [i] = decr_slot_ ((double)dx[i], dbins, lbins); } } else if ( m == 1 ) { for ( i = 0; i < lx; i ++ ) { iret [i] = incr_slot_ ((double)dx[i], dbins, lbins); } } else { /* defer PyErr_SetString until after NPY_END_ALLOW_THREADS */ bins_non_monotonic = 1; } } else { if ( m == -1 ) { for ( i = 0; i < lx; i ++ ) { iret [i] = decr_slot_right_ ((double)dx[i], dbins, lbins); } } else if ( m == 1 ) { for ( i = 0; i < lx; i ++ ) { iret [i] = incr_slot_right_ ((double)dx[i], dbins, lbins); } } else { /* defer PyErr_SetString until after NPY_END_ALLOW_THREADS */ bins_non_monotonic = 1; } } } NPY_END_ALLOW_THREADS; if (bins_non_monotonic) { PyErr_SetString(PyExc_ValueError, "The bins must be monotonically increasing or decreasing"); goto fail; } Py_DECREF(ax); Py_DECREF(abins); return (PyObject *)aret; fail: Py_XDECREF(ax); Py_XDECREF(abins); Py_XDECREF(aret); return NULL; } static char arr_insert__doc__[] = "Insert vals sequentially into equivalent 1-d positions indicated by mask."; /* * Insert values from an input array into an output array, at positions * indicated by a mask. If the arrays are of dtype object (indicated by * the objarray flag), take care of reference counting. * * This function implements the copying logic of arr_insert() defined * below. */ static void arr_insert_loop(char *mptr, char *vptr, char *input_data, char *zero, char *avals_data, int melsize, int delsize, int objarray, int totmask, int numvals, int nd, npy_intp *instrides, npy_intp *inshape) { int mindx, rem_indx, indx, i, copied; /* * Walk through mask array, when non-zero is encountered * copy next value in the vals array to the input array. * If we get through the value array, repeat it as necessary. */ copied = 0; for (mindx = 0; mindx < totmask; mindx++) { if (memcmp(mptr,zero,melsize) != 0) { /* compute indx into input array */ rem_indx = mindx; indx = 0; for (i = nd - 1; i > 0; --i) { indx += (rem_indx % inshape[i]) * instrides[i]; rem_indx /= inshape[i]; } indx += rem_indx * instrides[0]; /* fprintf(stderr, "mindx = %d, indx=%d\n", mindx, indx); */ /* Copy value element over to input array */ memcpy(input_data+indx,vptr,delsize); if (objarray) { Py_INCREF(*((PyObject **)vptr)); } vptr += delsize; copied += 1; /* If we move past value data. Reset */ if (copied >= numvals) { vptr = avals_data; } } mptr += melsize; } } /* * Returns input array with values inserted sequentially into places * indicated by the mask */ static PyObject * arr_insert(PyObject *NPY_UNUSED(self), PyObject *args, PyObject *kwdict) { PyObject *mask = NULL, *vals = NULL; PyArrayObject *ainput = NULL, *amask = NULL, *avals = NULL, *tmp = NULL; int numvals, totmask, sameshape; char *input_data, *mptr, *vptr, *zero = NULL; int melsize, delsize, nd, objarray, k; npy_intp *instrides, *inshape; static char *kwlist[] = {"input", "mask", "vals", NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwdict, "O&OO", kwlist, PyArray_Converter, &ainput, &mask, &vals)) { goto fail; } amask = (PyArrayObject *)PyArray_FROM_OF(mask, NPY_ARRAY_CARRAY); if (amask == NULL) { goto fail; } /* Cast an object array */ if (PyArray_DESCR(amask)->type_num == NPY_OBJECT) { tmp = (PyArrayObject *)PyArray_Cast(amask, NPY_INTP); if (tmp == NULL) { goto fail; } Py_DECREF(amask); amask = tmp; } sameshape = 1; if (PyArray_NDIM(amask) == PyArray_NDIM(ainput)) { for (k = 0; k < PyArray_NDIM(amask); k++) { if (PyArray_DIMS(amask)[k] != PyArray_DIMS(ainput)[k]) { sameshape = 0; } } } else { /* Test to see if amask is 1d */ if (PyArray_NDIM(amask) != 1) { sameshape = 0; } else if ((PyArray_SIZE(ainput)) != PyArray_SIZE(amask)) { sameshape = 0; } } if (!sameshape) { PyErr_SetString(PyExc_TypeError, "mask array must be 1-d or same shape as input array"); goto fail; } avals = (PyArrayObject *)PyArray_FromObject(vals, PyArray_DESCR(ainput)->type_num, 0, 1); if (avals == NULL) { goto fail; } numvals = PyArray_SIZE(avals); nd = PyArray_NDIM(ainput); input_data = PyArray_DATA(ainput); mptr = PyArray_DATA(amask); melsize = PyArray_DESCR(amask)->elsize; vptr = PyArray_DATA(avals); delsize = PyArray_DESCR(avals)->elsize; zero = PyArray_Zero(amask); if (zero == NULL) { goto fail; } objarray = (PyArray_DESCR(ainput)->type_num == NPY_OBJECT); /* Handle zero-dimensional case separately */ if (nd == 0) { if (memcmp(mptr,zero,melsize) != 0) { /* Copy value element over to input array */ memcpy(input_data,vptr,delsize); if (objarray) { Py_INCREF(*((PyObject **)vptr)); } } Py_DECREF(amask); Py_DECREF(avals); PyDataMem_FREE(zero); Py_DECREF(ainput); Py_INCREF(Py_None); return Py_None; } totmask = (int) PyArray_SIZE(amask); instrides = PyArray_STRIDES(ainput); inshape = PyArray_DIMS(ainput); if (objarray) { /* object array, need to refcount, can't release the GIL */ arr_insert_loop(mptr, vptr, input_data, zero, PyArray_DATA(avals), melsize, delsize, objarray, totmask, numvals, nd, instrides, inshape); } else { /* No increfs take place in arr_insert_loop, so release the GIL */ NPY_BEGIN_ALLOW_THREADS; arr_insert_loop(mptr, vptr, input_data, zero, PyArray_DATA(avals), melsize, delsize, objarray, totmask, numvals, nd, instrides, inshape); NPY_END_ALLOW_THREADS; } Py_DECREF(amask); Py_DECREF(avals); PyDataMem_FREE(zero); Py_DECREF(ainput); Py_INCREF(Py_None); return Py_None; fail: PyDataMem_FREE(zero); Py_XDECREF(ainput); Py_XDECREF(amask); Py_XDECREF(avals); return NULL; } /** @brief Use bisection on a sorted array to find first entry > key. * * Use bisection to find an index i s.t. arr[i] <= key < arr[i + 1]. If there is * no such i the error returns are: * key < arr[0] -- -1 * key == arr[len - 1] -- len - 1 * key > arr[len - 1] -- len * The array is assumed contiguous and sorted in ascending order. * * @param key key value. * @param arr contiguous sorted array to be searched. * @param len length of the array. * @return index */ static npy_intp binary_search(double key, double arr [], npy_intp len) { npy_intp imin = 0; npy_intp imax = len; if (key > arr[len - 1]) { return len; } while (imin < imax) { npy_intp imid = imin + ((imax - imin) >> 1); if (key >= arr[imid]) { imin = imid + 1; } else { imax = imid; } } return imin - 1; } static PyObject * arr_interp(PyObject *NPY_UNUSED(self), PyObject *args, PyObject *kwdict) { PyObject *fp, *xp, *x; PyObject *left = NULL, *right = NULL; PyArrayObject *afp = NULL, *axp = NULL, *ax = NULL, *af = NULL; npy_intp i, lenx, lenxp; double lval, rval; double *dy, *dx, *dz, *dres, *slopes; static char *kwlist[] = {"x", "xp", "fp", "left", "right", NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwdict, "OOO|OO", kwlist, &x, &xp, &fp, &left, &right)) { return NULL; } afp = (PyArrayObject *)PyArray_ContiguousFromAny(fp, NPY_DOUBLE, 1, 1); if (afp == NULL) { return NULL; } axp = (PyArrayObject *)PyArray_ContiguousFromAny(xp, NPY_DOUBLE, 1, 1); if (axp == NULL) { goto fail; } ax = (PyArrayObject *)PyArray_ContiguousFromAny(x, NPY_DOUBLE, 1, 0); if (ax == NULL) { goto fail; } lenxp = PyArray_DIMS(axp)[0]; if (lenxp == 0) { PyErr_SetString(PyExc_ValueError, "array of sample points is empty"); goto fail; } if (PyArray_DIMS(afp)[0] != lenxp) { PyErr_SetString(PyExc_ValueError, "fp and xp are not of the same length."); goto fail; } af = (PyArrayObject *)PyArray_SimpleNew(PyArray_NDIM(ax), PyArray_DIMS(ax), NPY_DOUBLE); if (af == NULL) { goto fail; } lenx = PyArray_SIZE(ax); dy = (double *)PyArray_DATA(afp); dx = (double *)PyArray_DATA(axp); dz = (double *)PyArray_DATA(ax); dres = (double *)PyArray_DATA(af); /* Get left and right fill values. */ if ((left == NULL) || (left == Py_None)) { lval = dy[0]; } else { lval = PyFloat_AsDouble(left); if ((lval == -1) && PyErr_Occurred()) { goto fail; } } if ((right == NULL) || (right == Py_None)) { rval = dy[lenxp-1]; } else { rval = PyFloat_AsDouble(right); if ((rval == -1) && PyErr_Occurred()) { goto fail; } } /* only pre-calculate slopes if there are relatively few of them. */ if (lenxp <= lenx) { slopes = (double *) PyArray_malloc((lenxp - 1)*sizeof(double)); if (! slopes) { goto fail; } NPY_BEGIN_ALLOW_THREADS; for (i = 0; i < lenxp - 1; i++) { 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); if (j == -1) { dres[i] = lval; } else if (j == lenxp - 1) { dres[i] = dy[j]; } else if (j == lenxp) { dres[i] = rval; } else { dres[i] = slopes[j]*(dz[i] - dx[j]) + dy[j]; } } NPY_END_ALLOW_THREADS; PyArray_free(slopes); } else { NPY_BEGIN_ALLOW_THREADS; for (i = 0; i < lenx; i++) { npy_intp j = binary_search(dz[i], dx, lenxp); if (j == -1) { dres[i] = lval; } else if (j == lenxp - 1) { dres[i] = dy[j]; } else if (j == lenxp) { 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]; } } NPY_END_ALLOW_THREADS; } Py_DECREF(afp); Py_DECREF(axp); Py_DECREF(ax); return (PyObject *)af; fail: Py_XDECREF(afp); Py_XDECREF(axp); Py_XDECREF(ax); Py_XDECREF(af); return NULL; } /* * Converts a Python sequence into 'count' PyArrayObjects * * seq - Input Python object, usually a tuple but any sequence works. * op - Where the arrays are placed. * count - How many arrays there should be (errors if it doesn't match). * paramname - The name of the parameter that produced 'seq'. */ static int sequence_to_arrays(PyObject *seq, PyArrayObject **op, int count, char *paramname) { int i; if (!PySequence_Check(seq) || PySequence_Size(seq) != count) { PyErr_Format(PyExc_ValueError, "parameter %s must be a sequence of length %d", paramname, count); return -1; } for (i = 0; i < count; ++i) { PyObject *item = PySequence_GetItem(seq, i); if (item == NULL) { while (--i >= 0) { Py_DECREF(op[i]); op[i] = NULL; } return -1; } op[i] = (PyArrayObject *)PyArray_FromAny(item, NULL, 0, 0, 0, NULL); if (op[i] == NULL) { while (--i >= 0) { Py_DECREF(op[i]); op[i] = NULL; } Py_DECREF(item); return -1; } Py_DECREF(item); } return 0; } /* Inner loop for unravel_index */ static int ravel_multi_index_loop(int ravel_ndim, npy_intp *ravel_dims, npy_intp *ravel_strides, npy_intp count, NPY_CLIPMODE *modes, char **coords, npy_intp *coords_strides) { int i; char invalid; npy_intp j, m; NPY_BEGIN_ALLOW_THREADS; invalid = 0; while (count--) { npy_intp raveled = 0; for (i = 0; i < ravel_ndim; ++i) { m = ravel_dims[i]; j = *(npy_intp *)coords[i]; switch (modes[i]) { case NPY_RAISE: if (j < 0 || j >= m) { invalid = 1; goto end_while; } break; case NPY_WRAP: if (j < 0) { j += m; if (j < 0) { j = j % m; if (j != 0) { j += m; } } } else if (j >= m) { j -= m; if (j >= m) { j = j % m; } } break; case NPY_CLIP: if (j < 0) { j = 0; } else if (j >= m) { j = m - 1; } break; } raveled += j * ravel_strides[i]; coords[i] += coords_strides[i]; } *(npy_intp *)coords[ravel_ndim] = raveled; coords[ravel_ndim] += coords_strides[ravel_ndim]; } end_while: NPY_END_ALLOW_THREADS; if (invalid) { PyErr_SetString(PyExc_ValueError, "invalid entry in coordinates array"); return NPY_FAIL; } return NPY_SUCCEED; } /* ravel_multi_index implementation - see add_newdocs.py */ static PyObject * arr_ravel_multi_index(PyObject *self, PyObject *args, PyObject *kwds) { int i, s; PyObject *mode0=NULL, *coords0=NULL; PyArrayObject *ret = NULL; PyArray_Dims dimensions={0,0}; npy_intp ravel_strides[NPY_MAXDIMS]; NPY_ORDER order = NPY_CORDER; NPY_CLIPMODE modes[NPY_MAXDIMS]; PyArrayObject *op[NPY_MAXARGS]; PyArray_Descr *dtype[NPY_MAXARGS]; npy_uint32 op_flags[NPY_MAXARGS]; NpyIter *iter = NULL; char *kwlist[] = {"multi_index", "dims", "mode", "order", NULL}; memset(op, 0, sizeof(op)); dtype[0] = NULL; if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO&|OO&:ravel_multi_index", kwlist, &coords0, PyArray_IntpConverter, &dimensions, &mode0, PyArray_OrderConverter, &order)) { goto fail; } if (dimensions.len+1 > NPY_MAXARGS) { PyErr_SetString(PyExc_ValueError, "too many dimensions passed to ravel_multi_index"); goto fail; } if (!PyArray_ConvertClipmodeSequence(mode0, modes, dimensions.len)) { goto fail; } switch (order) { case NPY_CORDER: s = 1; for (i = dimensions.len-1; i >= 0; --i) { ravel_strides[i] = s; s *= dimensions.ptr[i]; } break; case NPY_FORTRANORDER: s = 1; for (i = 0; i < dimensions.len; ++i) { ravel_strides[i] = s; s *= dimensions.ptr[i]; } break; default: PyErr_SetString(PyExc_ValueError, "only 'C' or 'F' order is permitted"); goto fail; } /* Get the multi_index into op */ if (sequence_to_arrays(coords0, op, dimensions.len, "multi_index") < 0) { goto fail; } for (i = 0; i < dimensions.len; ++i) { op_flags[i] = NPY_ITER_READONLY| NPY_ITER_ALIGNED; } op_flags[dimensions.len] = NPY_ITER_WRITEONLY| NPY_ITER_ALIGNED| NPY_ITER_ALLOCATE; dtype[0] = PyArray_DescrFromType(NPY_INTP); for (i = 1; i <= dimensions.len; ++i) { dtype[i] = dtype[0]; } iter = NpyIter_MultiNew(dimensions.len+1, op, NPY_ITER_BUFFERED| NPY_ITER_EXTERNAL_LOOP| NPY_ITER_ZEROSIZE_OK, NPY_KEEPORDER, NPY_SAME_KIND_CASTING, op_flags, dtype); if (iter == NULL) { goto fail; } if (NpyIter_GetIterSize(iter) != 0) { NpyIter_IterNextFunc *iternext; char **dataptr; npy_intp *strides; npy_intp *countptr; iternext = NpyIter_GetIterNext(iter, NULL); if (iternext == NULL) { goto fail; } dataptr = NpyIter_GetDataPtrArray(iter); strides = NpyIter_GetInnerStrideArray(iter); countptr = NpyIter_GetInnerLoopSizePtr(iter); do { if (ravel_multi_index_loop(dimensions.len, dimensions.ptr, ravel_strides, *countptr, modes, dataptr, strides) != NPY_SUCCEED) { goto fail; } } while(iternext(iter)); } ret = NpyIter_GetOperandArray(iter)[dimensions.len]; Py_INCREF(ret); Py_DECREF(dtype[0]); for (i = 0; i < dimensions.len; ++i) { Py_XDECREF(op[i]); } PyDimMem_FREE(dimensions.ptr); NpyIter_Deallocate(iter); return PyArray_Return(ret); fail: Py_XDECREF(dtype[0]); for (i = 0; i < dimensions.len; ++i) { Py_XDECREF(op[i]); } if (dimensions.ptr) { PyDimMem_FREE(dimensions.ptr); } if (iter != NULL) { NpyIter_Deallocate(iter); } return NULL; } /* C-order inner loop for unravel_index */ static int unravel_index_loop_corder(int unravel_ndim, npy_intp *unravel_dims, npy_intp unravel_size, npy_intp count, char *indices, npy_intp indices_stride, npy_intp *coords) { int i; char invalid; npy_intp val; NPY_BEGIN_ALLOW_THREADS; invalid = 0; while (count--) { val = *(npy_intp *)indices; if (val < 0 || val >= unravel_size) { invalid = 1; break; } for (i = unravel_ndim-1; i >= 0; --i) { coords[i] = val % unravel_dims[i]; val /= unravel_dims[i]; } coords += unravel_ndim; indices += indices_stride; } NPY_END_ALLOW_THREADS; if (invalid) { PyErr_SetString(PyExc_ValueError, "invalid entry in index array"); return NPY_FAIL; } return NPY_SUCCEED; } /* Fortran-order inner loop for unravel_index */ static int unravel_index_loop_forder(int unravel_ndim, npy_intp *unravel_dims, npy_intp unravel_size, npy_intp count, char *indices, npy_intp indices_stride, npy_intp *coords) { int i; char invalid; npy_intp val; NPY_BEGIN_ALLOW_THREADS; invalid = 0; while (count--) { val = *(npy_intp *)indices; if (val < 0 || val >= unravel_size) { invalid = 1; break; } for (i = 0; i < unravel_ndim; ++i) { *coords++ = val % unravel_dims[i]; val /= unravel_dims[i]; } indices += indices_stride; } NPY_END_ALLOW_THREADS; if (invalid) { PyErr_SetString(PyExc_ValueError, "invalid entry in index array"); return NPY_FAIL; } return NPY_SUCCEED; } /* unravel_index implementation - see add_newdocs.py */ static PyObject * arr_unravel_index(PyObject *self, PyObject *args, PyObject *kwds) { PyObject *indices0 = NULL, *ret_tuple = NULL; PyArrayObject *ret_arr = NULL; PyArrayObject *indices = NULL; PyArray_Descr *dtype = NULL; PyArray_Dims dimensions={0,0}; NPY_ORDER order = NPY_CORDER; npy_intp unravel_size; NpyIter *iter = NULL; int i, ret_ndim; npy_intp ret_dims[NPY_MAXDIMS], ret_strides[NPY_MAXDIMS]; char *kwlist[] = {"indices", "dims", "order", NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO&|O&:unravel_index", kwlist, &indices0, PyArray_IntpConverter, &dimensions, PyArray_OrderConverter, &order)) { goto fail; } if (dimensions.len == 0) { PyErr_SetString(PyExc_ValueError, "dims must have at least one value"); goto fail; } unravel_size = PyArray_MultiplyList(dimensions.ptr, dimensions.len); if (!PyArray_Check(indices0)) { indices = (PyArrayObject*)PyArray_FromAny(indices0, NULL, 0, 0, 0, NULL); if (indices == NULL) { goto fail; } } else { indices = (PyArrayObject *)indices0; Py_INCREF(indices); } dtype = PyArray_DescrFromType(NPY_INTP); if (dtype == NULL) { goto fail; } iter = NpyIter_New(indices, NPY_ITER_READONLY| NPY_ITER_ALIGNED| NPY_ITER_BUFFERED| NPY_ITER_ZEROSIZE_OK| NPY_ITER_DONT_NEGATE_STRIDES| NPY_ITER_MULTI_INDEX, NPY_KEEPORDER, NPY_SAME_KIND_CASTING, dtype); if (iter == NULL) { goto fail; } /* * Create the return array with a layout compatible with the indices * and with a dimension added to the end for the multi-index */ ret_ndim = PyArray_NDIM(indices) + 1; if (NpyIter_GetShape(iter, ret_dims) != NPY_SUCCEED) { goto fail; } ret_dims[ret_ndim-1] = dimensions.len; if (NpyIter_CreateCompatibleStrides(iter, dimensions.len*sizeof(npy_intp), ret_strides) != NPY_SUCCEED) { goto fail; } ret_strides[ret_ndim-1] = sizeof(npy_intp); /* Remove the multi-index and inner loop */ if (NpyIter_RemoveMultiIndex(iter) != NPY_SUCCEED) { goto fail; } if (NpyIter_EnableExternalLoop(iter) != NPY_SUCCEED) { goto fail; } ret_arr = (PyArrayObject *)PyArray_NewFromDescr(&PyArray_Type, dtype, ret_ndim, ret_dims, ret_strides, NULL, 0, NULL); dtype = NULL; if (ret_arr == NULL) { goto fail; } if (order == NPY_CORDER) { if (NpyIter_GetIterSize(iter) != 0) { NpyIter_IterNextFunc *iternext; char **dataptr; npy_intp *strides; npy_intp *countptr, count; npy_intp *coordsptr = (npy_intp *)PyArray_DATA(ret_arr); iternext = NpyIter_GetIterNext(iter, NULL); if (iternext == NULL) { goto fail; } dataptr = NpyIter_GetDataPtrArray(iter); strides = NpyIter_GetInnerStrideArray(iter); countptr = NpyIter_GetInnerLoopSizePtr(iter); do { count = *countptr; if (unravel_index_loop_corder(dimensions.len, dimensions.ptr, unravel_size, count, *dataptr, *strides, coordsptr) != NPY_SUCCEED) { goto fail; } coordsptr += count*dimensions.len; } while(iternext(iter)); } } else if (order == NPY_FORTRANORDER) { if (NpyIter_GetIterSize(iter) != 0) { NpyIter_IterNextFunc *iternext; char **dataptr; npy_intp *strides; npy_intp *countptr, count; npy_intp *coordsptr = (npy_intp *)PyArray_DATA(ret_arr); iternext = NpyIter_GetIterNext(iter, NULL); if (iternext == NULL) { goto fail; } dataptr = NpyIter_GetDataPtrArray(iter); strides = NpyIter_GetInnerStrideArray(iter); countptr = NpyIter_GetInnerLoopSizePtr(iter); do { count = *countptr; if (unravel_index_loop_forder(dimensions.len, dimensions.ptr, unravel_size, count, *dataptr, *strides, coordsptr) != NPY_SUCCEED) { goto fail; } coordsptr += count*dimensions.len; } while(iternext(iter)); } } else { PyErr_SetString(PyExc_ValueError, "only 'C' or 'F' order is permitted"); goto fail; } /* Now make a tuple of views, one per index */ ret_tuple = PyTuple_New(dimensions.len); if (ret_tuple == NULL) { goto fail; } for (i = 0; i < dimensions.len; ++i) { PyArrayObject *view; view = (PyArrayObject *)PyArray_New(&PyArray_Type, ret_ndim-1, ret_dims, NPY_INTP, ret_strides, PyArray_BYTES(ret_arr) + i*sizeof(npy_intp), 0, 0, NULL); if (view == NULL) { goto fail; } Py_INCREF(ret_arr); if (PyArray_SetBaseObject(view, (PyObject *)ret_arr) < 0) { Py_DECREF(view); goto fail; } PyTuple_SET_ITEM(ret_tuple, i, PyArray_Return(view)); } Py_DECREF(ret_arr); Py_XDECREF(indices); PyDimMem_FREE(dimensions.ptr); NpyIter_Deallocate(iter); return ret_tuple; fail: Py_XDECREF(ret_tuple); Py_XDECREF(ret_arr); Py_XDECREF(dtype); Py_XDECREF(indices); if (dimensions.ptr) { PyDimMem_FREE(dimensions.ptr); } if (iter != NULL) { NpyIter_Deallocate(iter); } return NULL; } static PyTypeObject *PyMemberDescr_TypePtr = NULL; static PyTypeObject *PyGetSetDescr_TypePtr = NULL; static PyTypeObject *PyMethodDescr_TypePtr = NULL; /* Can only be called if doc is currently NULL */ static PyObject * arr_add_docstring(PyObject *NPY_UNUSED(dummy), PyObject *args) { PyObject *obj; PyObject *str; char *docstr; static char *msg = "already has a docstring"; /* Don't add docstrings */ if (Py_OptimizeFlag > 1) { Py_INCREF(Py_None); return Py_None; } #if defined(NPY_PY3K) if (!PyArg_ParseTuple(args, "OO!", &obj, &PyUnicode_Type, &str)) { return NULL; } docstr = PyBytes_AS_STRING(PyUnicode_AsUTF8String(str)); #else if (!PyArg_ParseTuple(args, "OO!", &obj, &PyString_Type, &str)) { return NULL; } docstr = PyString_AS_STRING(str); #endif #define _TESTDOC1(typebase) (Py_TYPE(obj) == &Py##typebase##_Type) #define _TESTDOC2(typebase) (Py_TYPE(obj) == Py##typebase##_TypePtr) #define _ADDDOC(typebase, doc, name) do { \ Py##typebase##Object *new = (Py##typebase##Object *)obj; \ if (!(doc)) { \ doc = docstr; \ } \ else { \ PyErr_Format(PyExc_RuntimeError, "%s method %s", name, msg); \ return NULL; \ } \ } while (0) if (_TESTDOC1(CFunction)) { _ADDDOC(CFunction, new->m_ml->ml_doc, new->m_ml->ml_name); } else if (_TESTDOC1(Type)) { _ADDDOC(Type, new->tp_doc, new->tp_name); } else if (_TESTDOC2(MemberDescr)) { _ADDDOC(MemberDescr, new->d_member->doc, new->d_member->name); } else if (_TESTDOC2(GetSetDescr)) { _ADDDOC(GetSetDescr, new->d_getset->doc, new->d_getset->name); } else if (_TESTDOC2(MethodDescr)) { _ADDDOC(MethodDescr, new->d_method->ml_doc, new->d_method->ml_name); } else { PyObject *doc_attr; doc_attr = PyObject_GetAttrString(obj, "__doc__"); if (doc_attr != NULL && doc_attr != Py_None) { PyErr_Format(PyExc_RuntimeError, "object %s", msg); return NULL; } Py_XDECREF(doc_attr); if (PyObject_SetAttrString(obj, "__doc__", str) < 0) { PyErr_SetString(PyExc_TypeError, "Cannot set a docstring for that object"); return NULL; } Py_INCREF(Py_None); return Py_None; } #undef _TESTDOC1 #undef _TESTDOC2 #undef _ADDDOC Py_INCREF(str); Py_INCREF(Py_None); return Py_None; } /* docstring in numpy.add_newdocs.py */ static PyObject * add_newdoc_ufunc(PyObject *NPY_UNUSED(dummy), PyObject *args) { PyUFuncObject *ufunc; PyObject *str; char *docstr, *newdocstr; #if defined(NPY_PY3K) if (!PyArg_ParseTuple(args, "O!O!", &PyUFunc_Type, &ufunc, &PyUnicode_Type, &str)) { return NULL; } docstr = PyBytes_AS_STRING(PyUnicode_AsUTF8String(str)); #else if (!PyArg_ParseTuple(args, "O!O!", &PyUFunc_Type, &ufunc, &PyString_Type, &str)) { return NULL; } docstr = PyString_AS_STRING(str); #endif if (NULL != ufunc->doc) { PyErr_SetString(PyExc_ValueError, "Cannot change docstring of ufunc with non-NULL docstring"); return NULL; } /* * This introduces a memory leak, as the memory allocated for the doc * will not be freed even if the ufunc itself is deleted. In practice * this should not be a problem since the user would have to * repeatedly create, document, and throw away ufuncs. */ newdocstr = malloc(strlen(docstr) + 1); strcpy(newdocstr, docstr); ufunc->doc = newdocstr; Py_INCREF(Py_None); return Py_None; } /* PACKBITS * * This function packs binary (0 or 1) 1-bit per pixel arrays * into contiguous bytes. * */ static void _packbits( void *In, int element_size, /* in bytes */ npy_intp in_N, npy_intp in_stride, void *Out, npy_intp out_N, npy_intp out_stride ) { char build; int i, index; npy_intp out_Nm1; int maxi, remain, nonzero, j; char *outptr,*inptr; outptr = Out; /* pointer to output buffer */ inptr = In; /* pointer to input buffer */ /* * Loop through the elements of In * Determine whether or not it is nonzero. * Yes: set correspdoning bit (and adjust build value) * No: move on * Every 8th value, set the value of build and increment the outptr */ remain = in_N % 8; /* uneven bits */ if (remain == 0) { remain = 8; } out_Nm1 = out_N - 1; for (index = 0; index < out_N; index++) { build = 0; maxi = (index != out_Nm1 ? 8 : remain); for (i = 0; i < maxi; i++) { build <<= 1; nonzero = 0; for (j = 0; j < element_size; j++) { nonzero += (*(inptr++) != 0); } inptr += (in_stride - element_size); build += (nonzero != 0); } if (index == out_Nm1) build <<= (8-remain); /* printf("Here: %d %d %d %d\n",build,slice,index,maxi); */ *outptr = build; outptr += out_stride; } return; } static void _unpackbits(void *In, int NPY_UNUSED(el_size), /* unused */ npy_intp in_N, npy_intp in_stride, void *Out, npy_intp NPY_UNUSED(out_N), npy_intp out_stride ) { unsigned char mask; int i, index; char *inptr, *outptr; outptr = Out; inptr = In; for (index = 0; index < in_N; index++) { mask = 128; for (i = 0; i < 8; i++) { *outptr = ((mask & (unsigned char)(*inptr)) != 0); outptr += out_stride; mask >>= 1; } inptr += in_stride; } return; } /* Fixme -- pack and unpack should be separate routines */ static PyObject * pack_or_unpack_bits(PyObject *input, int axis, int unpack) { PyArrayObject *inp; PyArrayObject *new = NULL; PyArrayObject *out = NULL; npy_intp outdims[NPY_MAXDIMS]; int i; void (*thefunc)(void *, int, npy_intp, npy_intp, void *, npy_intp, npy_intp); PyArrayIterObject *it, *ot; inp = (PyArrayObject *)PyArray_FROM_O(input); if (inp == NULL) { return NULL; } if (unpack) { if (PyArray_TYPE(inp) != NPY_UBYTE) { PyErr_SetString(PyExc_TypeError, "Expected an input array of unsigned byte data type"); goto fail; } } else if (!PyArray_ISINTEGER(inp)) { PyErr_SetString(PyExc_TypeError, "Expected an input array of integer data type"); goto fail; } new = (PyArrayObject *)PyArray_CheckAxis(inp, &axis, 0); Py_DECREF(inp); if (new == NULL) { return NULL; } /* Handle zero-dim array separately */ if (PyArray_SIZE(new) == 0) { return PyArray_Copy(new); } if (PyArray_NDIM(new) == 0) { if (unpack) { /* Handle 0-d array by converting it to a 1-d array */ PyArrayObject *temp; PyArray_Dims newdim = {NULL, 1}; npy_intp shape = 1; newdim.ptr = &shape; temp = (PyArrayObject *)PyArray_Newshape(new, &newdim, NPY_CORDER); if (temp == NULL) { goto fail; } Py_DECREF(new); new = temp; } else { char *optr, *iptr; out = (PyArrayObject *)PyArray_New(Py_TYPE(new), 0, NULL, NPY_UBYTE, NULL, NULL, 0, 0, NULL); if (out == NULL) { goto fail; } optr = PyArray_DATA(out); iptr = PyArray_DATA(new); *optr = 0; for (i = 0; i 1, 9 -> 2, 16 -> 2, 17 -> 3 etc.. */ outdims[axis] = ((outdims[axis] - 1) >> 3) + 1; thefunc = _packbits; } /* Create output array */ out = (PyArrayObject *)PyArray_New(Py_TYPE(new), PyArray_NDIM(new), outdims, NPY_UBYTE, NULL, NULL, 0, PyArray_ISFORTRAN(new), NULL); if (out == NULL) { goto fail; } /* Setup iterators to iterate over all but given axis */ it = (PyArrayIterObject *)PyArray_IterAllButAxis((PyObject *)new, &axis); ot = (PyArrayIterObject *)PyArray_IterAllButAxis((PyObject *)out, &axis); if (it == NULL || ot == NULL) { Py_XDECREF(it); Py_XDECREF(ot); goto fail; } while(PyArray_ITER_NOTDONE(it)) { thefunc(PyArray_ITER_DATA(it), PyArray_ITEMSIZE(new), PyArray_DIM(new, axis), PyArray_STRIDE(new, axis), PyArray_ITER_DATA(ot), PyArray_DIM(out, axis), PyArray_STRIDE(out, axis)); PyArray_ITER_NEXT(it); PyArray_ITER_NEXT(ot); } Py_DECREF(it); Py_DECREF(ot); finish: Py_DECREF(new); return (PyObject *)out; fail: Py_XDECREF(new); Py_XDECREF(out); return NULL; } static PyObject * io_pack(PyObject *NPY_UNUSED(self), PyObject *args, PyObject *kwds) { PyObject *obj; int axis = NPY_MAXDIMS; static char *kwlist[] = {"in", "axis", NULL}; if (!PyArg_ParseTupleAndKeywords( args, kwds, "O|O&" , kwlist, &obj, PyArray_AxisConverter, &axis)) { return NULL; } return pack_or_unpack_bits(obj, axis, 0); } static PyObject * io_unpack(PyObject *NPY_UNUSED(self), PyObject *args, PyObject *kwds) { PyObject *obj; int axis = NPY_MAXDIMS; static char *kwlist[] = {"in", "axis", NULL}; if (!PyArg_ParseTupleAndKeywords( args, kwds, "O|O&" , kwlist, &obj, PyArray_AxisConverter, &axis)) { return NULL; } return pack_or_unpack_bits(obj, axis, 1); } /* The docstrings for many of these methods are in add_newdocs.py. */ static struct PyMethodDef methods[] = { {"_insert", (PyCFunction)arr_insert, METH_VARARGS | METH_KEYWORDS, arr_insert__doc__}, {"bincount", (PyCFunction)arr_bincount, METH_VARARGS | METH_KEYWORDS, NULL}, {"digitize", (PyCFunction)arr_digitize, METH_VARARGS | METH_KEYWORDS, NULL}, {"interp", (PyCFunction)arr_interp, METH_VARARGS | METH_KEYWORDS, NULL}, {"ravel_multi_index", (PyCFunction)arr_ravel_multi_index, METH_VARARGS | METH_KEYWORDS, NULL}, {"unravel_index", (PyCFunction)arr_unravel_index, METH_VARARGS | METH_KEYWORDS, NULL}, {"add_docstring", (PyCFunction)arr_add_docstring, METH_VARARGS, NULL}, {"add_newdoc_ufunc", (PyCFunction)add_newdoc_ufunc, METH_VARARGS, NULL}, {"packbits", (PyCFunction)io_pack, METH_VARARGS | METH_KEYWORDS, NULL}, {"unpackbits", (PyCFunction)io_unpack, METH_VARARGS | METH_KEYWORDS, NULL}, {NULL, NULL, 0, NULL} /* sentinel */ }; static void define_types(void) { PyObject *tp_dict; PyObject *myobj; tp_dict = PyArrayDescr_Type.tp_dict; /* Get "subdescr" */ myobj = PyDict_GetItemString(tp_dict, "fields"); if (myobj == NULL) { return; } PyGetSetDescr_TypePtr = Py_TYPE(myobj); myobj = PyDict_GetItemString(tp_dict, "alignment"); if (myobj == NULL) { return; } PyMemberDescr_TypePtr = Py_TYPE(myobj); myobj = PyDict_GetItemString(tp_dict, "newbyteorder"); if (myobj == NULL) { return; } PyMethodDescr_TypePtr = Py_TYPE(myobj); return; } #if defined(NPY_PY3K) static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, "_compiled_base", NULL, -1, methods, NULL, NULL, NULL, NULL }; #endif #if defined(NPY_PY3K) #define RETVAL m PyMODINIT_FUNC PyInit__compiled_base(void) #else #define RETVAL PyMODINIT_FUNC init_compiled_base(void) #endif { PyObject *m, *d; #if defined(NPY_PY3K) m = PyModule_Create(&moduledef); #else m = Py_InitModule("_compiled_base", methods); #endif if (!m) { return RETVAL; } /* Import the array objects */ import_array(); import_umath(); /* Add some symbolic constants to the module */ d = PyModule_GetDict(m); /* * PyExc_Exception should catch all the standard errors that are * now raised instead of the string exception "numpy.lib.error". * This is for backward compatibility with existing code. */ PyDict_SetItemString(d, "error", PyExc_Exception); /* define PyGetSetDescr_Type and PyMemberDescr_Type */ define_types(); return RETVAL; } numpy-1.8.2/numpy/lib/recfunctions.py0000664000175100017510000010431012370216243021015 0ustar vagrantvagrant00000000000000""" Collection of utilities to manipulate structured arrays. Most of these functions were initially implemented by John Hunter for matplotlib. They have been rewritten and extended for convenience. """ from __future__ import division, absolute_import, print_function import sys import itertools import numpy as np import numpy.ma as ma from numpy import ndarray, recarray from numpy.ma import MaskedArray from numpy.ma.mrecords import MaskedRecords from numpy.lib._iotools import _is_string_like from numpy.compat import basestring if sys.version_info[0] < 3: from future_builtins import zip _check_fill_value = np.ma.core._check_fill_value __all__ = ['append_fields', 'drop_fields', 'find_duplicates', 'get_fieldstructure', 'join_by', 'merge_arrays', 'rec_append_fields', 'rec_drop_fields', 'rec_join', 'recursive_fill_fields', 'rename_fields', 'stack_arrays', ] def recursive_fill_fields(input, output): """ Fills fields from output with fields from input, with support for nested structures. Parameters ---------- input : ndarray Input array. output : ndarray Output array. Notes ----- * `output` should be at least the same size as `input` Examples -------- >>> from numpy.lib import recfunctions as rfn >>> a = np.array([(1, 10.), (2, 20.)], dtype=[('A', int), ('B', float)]) >>> b = np.zeros((3,), dtype=a.dtype) >>> rfn.recursive_fill_fields(a, b) array([(1, 10.0), (2, 20.0), (0, 0.0)], dtype=[('A', '>> from numpy.lib import recfunctions as rfn >>> rfn.get_names(np.empty((1,), dtype=int)) is None True >>> rfn.get_names(np.empty((1,), dtype=[('A',int), ('B', float)])) ('A', 'B') >>> adtype = np.dtype([('a', int), ('b', [('ba', int), ('bb', int)])]) >>> rfn.get_names(adtype) ('a', ('b', ('ba', 'bb'))) """ listnames = [] names = adtype.names for name in names: current = adtype[name] if current.names: listnames.append((name, tuple(get_names(current)))) else: listnames.append(name) return tuple(listnames) or None def get_names_flat(adtype): """ Returns the field names of the input datatype as a tuple. Nested structure are flattend beforehand. Parameters ---------- adtype : dtype Input datatype Examples -------- >>> from numpy.lib import recfunctions as rfn >>> rfn.get_names_flat(np.empty((1,), dtype=int)) is None True >>> rfn.get_names_flat(np.empty((1,), dtype=[('A',int), ('B', float)])) ('A', 'B') >>> adtype = np.dtype([('a', int), ('b', [('ba', int), ('bb', int)])]) >>> rfn.get_names_flat(adtype) ('a', 'b', 'ba', 'bb') """ listnames = [] names = adtype.names for name in names: listnames.append(name) current = adtype[name] if current.names: listnames.extend(get_names_flat(current)) return tuple(listnames) or None def flatten_descr(ndtype): """ Flatten a structured data-type description. Examples -------- >>> from numpy.lib import recfunctions as rfn >>> ndtype = np.dtype([('a', '>> rfn.flatten_descr(ndtype) (('a', dtype('int32')), ('ba', dtype('float64')), ('bb', dtype('int32'))) """ names = ndtype.names if names is None: return ndtype.descr else: descr = [] for field in names: (typ, _) = ndtype.fields[field] if typ.names: descr.extend(flatten_descr(typ)) else: descr.append((field, typ)) return tuple(descr) def zip_descr(seqarrays, flatten=False): """ Combine the dtype description of a series of arrays. Parameters ---------- seqarrays : sequence of arrays Sequence of arrays flatten : {boolean}, optional Whether to collapse nested descriptions. """ newdtype = [] if flatten: for a in seqarrays: newdtype.extend(flatten_descr(a.dtype)) else: for a in seqarrays: current = a.dtype names = current.names or () if len(names) > 1: newdtype.append(('', current.descr)) else: newdtype.extend(current.descr) return np.dtype(newdtype).descr def get_fieldstructure(adtype, lastname=None, parents=None,): """ Returns a dictionary with fields as keys and a list of parent fields as values. This function is used to simplify access to fields nested in other fields. Parameters ---------- adtype : np.dtype Input datatype lastname : optional Last processed field name (used internally during recursion). parents : dictionary Dictionary of parent fields (used interbally during recursion). Examples -------- >>> from numpy.lib import recfunctions as rfn >>> ndtype = np.dtype([('A', int), ... ('B', [('BA', int), ... ('BB', [('BBA', int), ('BBB', int)])])]) >>> rfn.get_fieldstructure(ndtype) ... # XXX: possible regression, order of BBA and BBB is swapped {'A': [], 'B': [], 'BA': ['B'], 'BB': ['B'], 'BBA': ['B', 'BB'], 'BBB': ['B', 'BB']} """ if parents is None: parents = {} names = adtype.names for name in names: current = adtype[name] if current.names: if lastname: parents[name] = [lastname, ] else: parents[name] = [] parents.update(get_fieldstructure(current, name, parents)) else: lastparent = [_ for _ in (parents.get(lastname, []) or [])] if lastparent: # if (lastparent[-1] != lastname): lastparent.append(lastname) elif lastname: lastparent = [lastname, ] parents[name] = lastparent or [] return parents or None def _izip_fields_flat(iterable): """ Returns an iterator of concatenated fields from a sequence of arrays, collapsing any nested structure. """ for element in iterable: if isinstance(element, np.void): for f in _izip_fields_flat(tuple(element)): yield f else: yield element def _izip_fields(iterable): """ Returns an iterator of concatenated fields from a sequence of arrays. """ for element in iterable: if hasattr(element, '__iter__') and not isinstance(element, basestring): for f in _izip_fields(element): yield f elif isinstance(element, np.void) and len(tuple(element)) == 1: for f in _izip_fields(element): yield f else: yield element def izip_records(seqarrays, fill_value=None, flatten=True): """ Returns an iterator of concatenated items from a sequence of arrays. Parameters ---------- seqarray : sequence of arrays Sequence of arrays. fill_value : {None, integer} Value used to pad shorter iterables. flatten : {True, False}, Whether to """ # OK, that's a complete ripoff from Python2.6 itertools.izip_longest def sentinel(counter=([fill_value] * (len(seqarrays) - 1)).pop): "Yields the fill_value or raises IndexError" yield counter() # fillers = itertools.repeat(fill_value) iters = [itertools.chain(it, sentinel(), fillers) for it in seqarrays] # Should we flatten the items, or just use a nested approach if flatten: zipfunc = _izip_fields_flat else: zipfunc = _izip_fields # try: for tup in zip(*iters): yield tuple(zipfunc(tup)) except IndexError: pass def _fix_output(output, usemask=True, asrecarray=False): """ Private function: return a recarray, a ndarray, a MaskedArray or a MaskedRecords depending on the input parameters """ if not isinstance(output, MaskedArray): usemask = False if usemask: if asrecarray: output = output.view(MaskedRecords) else: output = ma.filled(output) if asrecarray: output = output.view(recarray) return output def _fix_defaults(output, defaults=None): """ Update the fill_value and masked data of `output` from the default given in a dictionary defaults. """ names = output.dtype.names (data, mask, fill_value) = (output.data, output.mask, output.fill_value) for (k, v) in (defaults or {}).items(): if k in names: fill_value[k] = v data[k][mask[k]] = v return output def merge_arrays(seqarrays, fill_value= -1, flatten=False, usemask=False, asrecarray=False): """ Merge arrays field by field. Parameters ---------- seqarrays : sequence of ndarrays Sequence of arrays fill_value : {float}, optional Filling value used to pad missing data on the shorter arrays. flatten : {False, True}, optional Whether to collapse nested fields. usemask : {False, True}, optional Whether to return a masked array or not. asrecarray : {False, True}, optional Whether to return a recarray (MaskedRecords) or not. Examples -------- >>> from numpy.lib import recfunctions as rfn >>> rfn.merge_arrays((np.array([1, 2]), np.array([10., 20., 30.]))) masked_array(data = [(1, 10.0) (2, 20.0) (--, 30.0)], mask = [(False, False) (False, False) (True, False)], fill_value = (999999, 1e+20), dtype = [('f0', '>> rfn.merge_arrays((np.array([1, 2]), np.array([10., 20., 30.])), ... usemask=False) array([(1, 10.0), (2, 20.0), (-1, 30.0)], dtype=[('f0', '>> rfn.merge_arrays((np.array([1, 2]).view([('a', int)]), ... np.array([10., 20., 30.])), ... usemask=False, asrecarray=True) rec.array([(1, 10.0), (2, 20.0), (-1, 30.0)], dtype=[('a', '>> from numpy.lib import recfunctions as rfn >>> a = np.array([(1, (2, 3.0)), (4, (5, 6.0))], ... dtype=[('a', int), ('b', [('ba', float), ('bb', int)])]) >>> rfn.drop_fields(a, 'a') array([((2.0, 3),), ((5.0, 6),)], dtype=[('b', [('ba', '>> rfn.drop_fields(a, 'ba') array([(1, (3,)), (4, (6,))], dtype=[('a', '>> rfn.drop_fields(a, ['ba', 'bb']) array([(1,), (4,)], dtype=[('a', '>> from numpy.lib import recfunctions as rfn >>> a = np.array([(1, (2, [3.0, 30.])), (4, (5, [6.0, 60.]))], ... dtype=[('a', int),('b', [('ba', float), ('bb', (float, 2))])]) >>> rfn.rename_fields(a, {'a':'A', 'bb':'BB'}) array([(1, (2.0, [3.0, 30.0])), (4, (5.0, [6.0, 60.0]))], dtype=[('A', ' 1: data = merge_arrays(data, flatten=True, usemask=usemask, fill_value=fill_value) else: data = data.pop() # output = ma.masked_all(max(len(base), len(data)), dtype=base.dtype.descr + data.dtype.descr) output = recursive_fill_fields(base, output) output = recursive_fill_fields(data, output) # return _fix_output(output, usemask=usemask, asrecarray=asrecarray) def rec_append_fields(base, names, data, dtypes=None): """ Add new fields to an existing array. The names of the fields are given with the `names` arguments, the corresponding values with the `data` arguments. If a single field is appended, `names`, `data` and `dtypes` do not have to be lists but just values. Parameters ---------- base : array Input array to extend. names : string, sequence String or sequence of strings corresponding to the names of the new fields. data : array or sequence of arrays Array or sequence of arrays storing the fields to add to the base. dtypes : sequence of datatypes, optional Datatype or sequence of datatypes. If None, the datatypes are estimated from the `data`. See Also -------- append_fields Returns ------- appended_array : np.recarray """ return append_fields(base, names, data=data, dtypes=dtypes, asrecarray=True, usemask=False) def stack_arrays(arrays, defaults=None, usemask=True, asrecarray=False, autoconvert=False): """ Superposes arrays fields by fields Parameters ---------- seqarrays : array or sequence Sequence of input arrays. defaults : dictionary, optional Dictionary mapping field names to the corresponding default values. usemask : {True, False}, optional Whether to return a MaskedArray (or MaskedRecords is `asrecarray==True`) or a ndarray. asrecarray : {False, True}, optional Whether to return a recarray (or MaskedRecords if `usemask==True`) or just a flexible-type ndarray. autoconvert : {False, True}, optional Whether automatically cast the type of the field to the maximum. Examples -------- >>> from numpy.lib import recfunctions as rfn >>> x = np.array([1, 2,]) >>> rfn.stack_arrays(x) is x True >>> z = np.array([('A', 1), ('B', 2)], dtype=[('A', '|S3'), ('B', float)]) >>> zz = np.array([('a', 10., 100.), ('b', 20., 200.), ('c', 30., 300.)], ... dtype=[('A', '|S3'), ('B', float), ('C', float)]) >>> test = rfn.stack_arrays((z,zz)) >>> test masked_array(data = [('A', 1.0, --) ('B', 2.0, --) ('a', 10.0, 100.0) ('b', 20.0, 200.0) ('c', 30.0, 300.0)], mask = [(False, False, True) (False, False, True) (False, False, False) (False, False, False) (False, False, False)], fill_value = ('N/A', 1e+20, 1e+20), dtype = [('A', '|S3'), ('B', ' np.dtype(current_descr[-1]): current_descr = list(current_descr) current_descr[-1] = descr[1] newdescr[nameidx] = tuple(current_descr) elif descr[1] != current_descr[-1]: raise TypeError("Incompatible type '%s' <> '%s'" % \ (dict(newdescr)[name], descr[1])) # Only one field: use concatenate if len(newdescr) == 1: output = ma.concatenate(seqarrays) else: # output = ma.masked_all((np.sum(nrecords),), newdescr) offset = np.cumsum(np.r_[0, nrecords]) seen = [] for (a, n, i, j) in zip(seqarrays, fldnames, offset[:-1], offset[1:]): names = a.dtype.names if names is None: output['f%i' % len(seen)][i:j] = a else: for name in n: output[name][i:j] = a[name] if name not in seen: seen.append(name) # return _fix_output(_fix_defaults(output, defaults), usemask=usemask, asrecarray=asrecarray) def find_duplicates(a, key=None, ignoremask=True, return_index=False): """ Find the duplicates in a structured array along a given key Parameters ---------- a : array-like Input array key : {string, None}, optional Name of the fields along which to check the duplicates. If None, the search is performed by records ignoremask : {True, False}, optional Whether masked data should be discarded or considered as duplicates. return_index : {False, True}, optional Whether to return the indices of the duplicated values. Examples -------- >>> from numpy.lib import recfunctions as rfn >>> ndtype = [('a', int)] >>> a = np.ma.array([1, 1, 1, 2, 2, 3, 3], ... mask=[0, 0, 1, 0, 0, 0, 1]).view(ndtype) >>> rfn.find_duplicates(a, ignoremask=True, return_index=True) ... # XXX: judging by the output, the ignoremask flag has no effect """ a = np.asanyarray(a).ravel() # Get a dictionary of fields fields = get_fieldstructure(a.dtype) # Get the sorting data (by selecting the corresponding field) base = a if key: for f in fields[key]: base = base[f] base = base[key] # Get the sorting indices and the sorted data sortidx = base.argsort() sortedbase = base[sortidx] sorteddata = sortedbase.filled() # Compare the sorting data flag = (sorteddata[:-1] == sorteddata[1:]) # If masked data must be ignored, set the flag to false where needed if ignoremask: sortedmask = sortedbase.recordmask flag[sortedmask[1:]] = False flag = np.concatenate(([False], flag)) # We need to take the point on the left as well (else we're missing it) flag[:-1] = flag[:-1] + flag[1:] duplicates = a[sortidx][flag] if return_index: return (duplicates, sortidx[flag]) else: return duplicates def join_by(key, r1, r2, jointype='inner', r1postfix='1', r2postfix='2', defaults=None, usemask=True, asrecarray=False): """ Join arrays `r1` and `r2` on key `key`. The key should be either a string or a sequence of string corresponding to the fields used to join the array. An exception is raised if the `key` field cannot be found in the two input arrays. Neither `r1` nor `r2` should have any duplicates along `key`: the presence of duplicates will make the output quite unreliable. Note that duplicates are not looked for by the algorithm. Parameters ---------- key : {string, sequence} A string or a sequence of strings corresponding to the fields used for comparison. r1, r2 : arrays Structured arrays. jointype : {'inner', 'outer', 'leftouter'}, optional If 'inner', returns the elements common to both r1 and r2. If 'outer', returns the common elements as well as the elements of r1 not in r2 and the elements of not in r2. If 'leftouter', returns the common elements and the elements of r1 not in r2. r1postfix : string, optional String appended to the names of the fields of r1 that are present in r2 but absent of the key. r2postfix : string, optional String appended to the names of the fields of r2 that are present in r1 but absent of the key. defaults : {dictionary}, optional Dictionary mapping field names to the corresponding default values. usemask : {True, False}, optional Whether to return a MaskedArray (or MaskedRecords is `asrecarray==True`) or a ndarray. asrecarray : {False, True}, optional Whether to return a recarray (or MaskedRecords if `usemask==True`) or just a flexible-type ndarray. Notes ----- * The output is sorted along the key. * A temporary array is formed by dropping the fields not in the key for the two arrays and concatenating the result. This array is then sorted, and the common entries selected. The output is constructed by filling the fields with the selected entries. Matching is not preserved if there are some duplicates... """ # Check jointype if jointype not in ('inner', 'outer', 'leftouter'): raise ValueError("The 'jointype' argument should be in 'inner', "\ "'outer' or 'leftouter' (got '%s' instead)" % jointype) # If we have a single key, put it in a tuple if isinstance(key, basestring): key = (key,) # Check the keys for name in key: if name not in r1.dtype.names: raise ValueError('r1 does not have key field %s' % name) if name not in r2.dtype.names: raise ValueError('r2 does not have key field %s' % name) # Make sure we work with ravelled arrays r1 = r1.ravel() r2 = r2.ravel() (nb1, nb2) = (len(r1), len(r2)) (r1names, r2names) = (r1.dtype.names, r2.dtype.names) # Check the names for collision if (set.intersection(set(r1names), set(r2names)).difference(key) and not (r1postfix or r2postfix)): msg = "r1 and r2 contain common names, r1postfix and r2postfix " msg += "can't be empty" raise ValueError(msg) # Make temporary arrays of just the keys r1k = drop_fields(r1, [n for n in r1names if n not in key]) r2k = drop_fields(r2, [n for n in r2names if n not in key]) # Concatenate the two arrays for comparison aux = ma.concatenate((r1k, r2k)) idx_sort = aux.argsort(order=key) aux = aux[idx_sort] # # Get the common keys flag_in = ma.concatenate(([False], aux[1:] == aux[:-1])) flag_in[:-1] = flag_in[1:] + flag_in[:-1] idx_in = idx_sort[flag_in] idx_1 = idx_in[(idx_in < nb1)] idx_2 = idx_in[(idx_in >= nb1)] - nb1 (r1cmn, r2cmn) = (len(idx_1), len(idx_2)) if jointype == 'inner': (r1spc, r2spc) = (0, 0) elif jointype == 'outer': idx_out = idx_sort[~flag_in] idx_1 = np.concatenate((idx_1, idx_out[(idx_out < nb1)])) idx_2 = np.concatenate((idx_2, idx_out[(idx_out >= nb1)] - nb1)) (r1spc, r2spc) = (len(idx_1) - r1cmn, len(idx_2) - r2cmn) elif jointype == 'leftouter': idx_out = idx_sort[~flag_in] idx_1 = np.concatenate((idx_1, idx_out[(idx_out < nb1)])) (r1spc, r2spc) = (len(idx_1) - r1cmn, 0) # Select the entries from each input (s1, s2) = (r1[idx_1], r2[idx_2]) # # Build the new description of the output array ....... # Start with the key fields ndtype = [list(_) for _ in r1k.dtype.descr] # Add the other fields ndtype.extend(list(_) for _ in r1.dtype.descr if _[0] not in key) # Find the new list of names (it may be different from r1names) names = list(_[0] for _ in ndtype) for desc in r2.dtype.descr: desc = list(desc) name = desc[0] # Have we seen the current name already ? if name in names: nameidx = ndtype.index(desc) current = ndtype[nameidx] # The current field is part of the key: take the largest dtype if name in key: current[-1] = max(desc[1], current[-1]) # The current field is not part of the key: add the suffixes else: current[0] += r1postfix desc[0] += r2postfix ndtype.insert(nameidx + 1, desc) #... we haven't: just add the description to the current list else: names.extend(desc[0]) ndtype.append(desc) # Revert the elements to tuples ndtype = [tuple(_) for _ in ndtype] # Find the largest nb of common fields : r1cmn and r2cmn should be equal, but... cmn = max(r1cmn, r2cmn) # Construct an empty array output = ma.masked_all((cmn + r1spc + r2spc,), dtype=ndtype) names = output.dtype.names for f in r1names: selected = s1[f] if f not in names or (f in r2names and not r2postfix and not f in key): f += r1postfix current = output[f] current[:r1cmn] = selected[:r1cmn] if jointype in ('outer', 'leftouter'): current[cmn:cmn + r1spc] = selected[r1cmn:] for f in r2names: selected = s2[f] if f not in names or (f in r1names and not r1postfix and f not in key): f += r2postfix current = output[f] current[:r2cmn] = selected[:r2cmn] if (jointype == 'outer') and r2spc: current[-r2spc:] = selected[r2cmn:] # Sort and finalize the output output.sort(order=key) kwargs = dict(usemask=usemask, asrecarray=asrecarray) return _fix_output(_fix_defaults(output, defaults), **kwargs) def rec_join(key, r1, r2, jointype='inner', r1postfix='1', r2postfix='2', defaults=None): """ Join arrays `r1` and `r2` on keys. Alternative to join_by, that always returns a np.recarray. See Also -------- join_by : equivalent function """ kwargs = dict(jointype=jointype, r1postfix=r1postfix, r2postfix=r2postfix, defaults=defaults, usemask=False, asrecarray=True) return join_by(key, r1, r2, **kwargs) numpy-1.8.2/numpy/lib/type_check.py0000664000175100017510000003710212370216243020435 0ustar vagrantvagrant00000000000000"""Automatically adapted for numpy Sep 19, 2005 by convertcode.py """ from __future__ import division, absolute_import, print_function __all__ = ['iscomplexobj', 'isrealobj', 'imag', 'iscomplex', 'isreal', 'nan_to_num', 'real', 'real_if_close', 'typename', 'asfarray', 'mintypecode', 'asscalar', 'common_type'] import numpy.core.numeric as _nx from numpy.core.numeric import asarray, asanyarray, array, isnan, \ obj2sctype, zeros from .ufunclike import isneginf, isposinf _typecodes_by_elsize = 'GDFgdfQqLlIiHhBb?' def mintypecode(typechars,typeset='GDFgdf',default='d'): """ Return the character for the minimum-size type to which given types can be safely cast. The returned type character must represent the smallest size dtype such that an array of the returned type can handle the data from an array of all types in `typechars` (or if `typechars` is an array, then its dtype.char). Parameters ---------- typechars : list of str or array_like If a list of strings, each string should represent a dtype. If array_like, the character representation of the array dtype is used. typeset : str or list of str, optional The set of characters that the returned character is chosen from. The default set is 'GDFgdf'. default : str, optional The default character, this is returned if none of the characters in `typechars` matches a character in `typeset`. Returns ------- typechar : str The character representing the minimum-size type that was found. See Also -------- dtype, sctype2char, maximum_sctype Examples -------- >>> np.mintypecode(['d', 'f', 'S']) 'd' >>> x = np.array([1.1, 2-3.j]) >>> np.mintypecode(x) 'D' >>> np.mintypecode('abceh', default='G') 'G' """ typecodes = [(isinstance(t, str) and t) or asarray(t).dtype.char\ for t in typechars] intersection = [t for t in typecodes if t in typeset] if not intersection: return default if 'F' in intersection and 'd' in intersection: return 'D' l = [] for t in intersection: i = _typecodes_by_elsize.index(t) l.append((i, t)) l.sort() return l[0][1] def asfarray(a, dtype=_nx.float_): """ Return an array converted to a float type. Parameters ---------- a : array_like The input array. dtype : str or dtype object, optional Float type code to coerce input array `a`. If `dtype` is one of the 'int' dtypes, it is replaced with float64. Returns ------- out : ndarray The input `a` as a float ndarray. Examples -------- >>> np.asfarray([2, 3]) array([ 2., 3.]) >>> np.asfarray([2, 3], dtype='float') array([ 2., 3.]) >>> np.asfarray([2, 3], dtype='int8') array([ 2., 3.]) """ dtype = _nx.obj2sctype(dtype) if not issubclass(dtype, _nx.inexact): dtype = _nx.float_ return asarray(a, dtype=dtype) def real(val): """ Return the real part of the elements of the array. Parameters ---------- val : array_like Input array. Returns ------- out : ndarray Output array. If `val` is real, the type of `val` is used for the output. If `val` has complex elements, the returned type is float. See Also -------- real_if_close, imag, angle Examples -------- >>> a = np.array([1+2j, 3+4j, 5+6j]) >>> a.real array([ 1., 3., 5.]) >>> a.real = 9 >>> a array([ 9.+2.j, 9.+4.j, 9.+6.j]) >>> a.real = np.array([9, 8, 7]) >>> a array([ 9.+2.j, 8.+4.j, 7.+6.j]) """ return asanyarray(val).real def imag(val): """ Return the imaginary part of the elements of the array. Parameters ---------- val : array_like Input array. Returns ------- out : ndarray Output array. If `val` is real, the type of `val` is used for the output. If `val` has complex elements, the returned type is float. See Also -------- real, angle, real_if_close Examples -------- >>> a = np.array([1+2j, 3+4j, 5+6j]) >>> a.imag array([ 2., 4., 6.]) >>> a.imag = np.array([8, 10, 12]) >>> a array([ 1. +8.j, 3.+10.j, 5.+12.j]) """ return asanyarray(val).imag def iscomplex(x): """ Returns a bool array, where True if input element is complex. What is tested is whether the input has a non-zero imaginary part, not if the input type is complex. Parameters ---------- x : array_like Input array. Returns ------- out : ndarray of bools Output array. See Also -------- isreal iscomplexobj : Return True if x is a complex type or an array of complex numbers. Examples -------- >>> np.iscomplex([1+1j, 1+0j, 4.5, 3, 2, 2j]) array([ True, False, False, False, False, True], dtype=bool) """ ax = asanyarray(x) if issubclass(ax.dtype.type, _nx.complexfloating): return ax.imag != 0 res = zeros(ax.shape, bool) return +res # convet to array-scalar if needed def isreal(x): """ Returns a bool array, where True if input element is real. If element has complex type with zero complex part, the return value for that element is True. Parameters ---------- x : array_like Input array. Returns ------- out : ndarray, bool Boolean array of same shape as `x`. See Also -------- iscomplex isrealobj : Return True if x is not a complex type. Examples -------- >>> np.isreal([1+1j, 1+0j, 4.5, 3, 2, 2j]) array([False, True, True, True, True, False], dtype=bool) """ return imag(x) == 0 def iscomplexobj(x): """ Check for a complex type or an array of complex numbers. The type of the input is checked, not the value. Even if the input has an imaginary part equal to zero, `iscomplexobj` evaluates to True. Parameters ---------- x : any The input can be of any type and shape. Returns ------- iscomplexobj : bool The return value, True if `x` is of a complex type or has at least one complex element. See Also -------- isrealobj, iscomplex Examples -------- >>> np.iscomplexobj(1) False >>> np.iscomplexobj(1+0j) True >>> np.iscomplexobj([3, 1+0j, True]) True """ return issubclass( asarray(x).dtype.type, _nx.complexfloating) def isrealobj(x): """ Return True if x is a not complex type or an array of complex numbers. The type of the input is checked, not the value. So even if the input has an imaginary part equal to zero, `isrealobj` evaluates to False if the data type is complex. Parameters ---------- x : any The input can be of any type and shape. Returns ------- y : bool The return value, False if `x` is of a complex type. See Also -------- iscomplexobj, isreal Examples -------- >>> np.isrealobj(1) True >>> np.isrealobj(1+0j) False >>> np.isrealobj([3, 1+0j, True]) False """ return not issubclass( asarray(x).dtype.type, _nx.complexfloating) #----------------------------------------------------------------------------- def _getmaxmin(t): from numpy.core import getlimits f = getlimits.finfo(t) return f.max, f.min def nan_to_num(x): """ Replace nan with zero and inf with finite numbers. Returns an array or scalar replacing Not a Number (NaN) with zero, (positive) infinity with a very large number and negative infinity with a very small (or negative) number. Parameters ---------- x : array_like Input data. Returns ------- out : ndarray, float Array with the same shape as `x` and dtype of the element in `x` with the greatest precision. NaN is replaced by zero, and infinity (-infinity) is replaced by the largest (smallest or most negative) floating point value that fits in the output dtype. All finite numbers are upcast to the output dtype (default float64). See Also -------- isinf : Shows which elements are negative or negative infinity. isneginf : Shows which elements are negative infinity. isposinf : Shows which elements are positive infinity. isnan : Shows which elements are Not a Number (NaN). isfinite : Shows which elements are finite (not NaN, not infinity) Notes ----- Numpy uses the IEEE Standard for Binary Floating-Point for Arithmetic (IEEE 754). This means that Not a Number is not equivalent to infinity. Examples -------- >>> np.set_printoptions(precision=8) >>> x = np.array([np.inf, -np.inf, np.nan, -128, 128]) >>> np.nan_to_num(x) array([ 1.79769313e+308, -1.79769313e+308, 0.00000000e+000, -1.28000000e+002, 1.28000000e+002]) """ try: t = x.dtype.type except AttributeError: t = obj2sctype(type(x)) if issubclass(t, _nx.complexfloating): return nan_to_num(x.real) + 1j * nan_to_num(x.imag) else: try: y = x.copy() except AttributeError: y = array(x) if not issubclass(t, _nx.integer): if not y.shape: y = array([x]) scalar = True else: scalar = False are_inf = isposinf(y) are_neg_inf = isneginf(y) are_nan = isnan(y) maxf, minf = _getmaxmin(y.dtype.type) y[are_nan] = 0 y[are_inf] = maxf y[are_neg_inf] = minf if scalar: y = y[0] return y #----------------------------------------------------------------------------- def real_if_close(a,tol=100): """ If complex input returns a real array if complex parts are close to zero. "Close to zero" is defined as `tol` * (machine epsilon of the type for `a`). Parameters ---------- a : array_like Input array. tol : float Tolerance in machine epsilons for the complex part of the elements in the array. Returns ------- out : ndarray If `a` is real, the type of `a` is used for the output. If `a` has complex elements, the returned type is float. See Also -------- real, imag, angle Notes ----- Machine epsilon varies from machine to machine and between data types but Python floats on most platforms have a machine epsilon equal to 2.2204460492503131e-16. You can use 'np.finfo(np.float).eps' to print out the machine epsilon for floats. Examples -------- >>> np.finfo(np.float).eps 2.2204460492503131e-16 >>> np.real_if_close([2.1 + 4e-14j], tol=1000) array([ 2.1]) >>> np.real_if_close([2.1 + 4e-13j], tol=1000) array([ 2.1 +4.00000000e-13j]) """ a = asanyarray(a) if not issubclass(a.dtype.type, _nx.complexfloating): return a if tol > 1: from numpy.core import getlimits f = getlimits.finfo(a.dtype.type) tol = f.eps * tol if _nx.allclose(a.imag, 0, atol=tol): a = a.real return a def asscalar(a): """ Convert an array of size 1 to its scalar equivalent. Parameters ---------- a : ndarray Input array of size 1. Returns ------- out : scalar Scalar representation of `a`. The output data type is the same type returned by the input's `item` method. Examples -------- >>> np.asscalar(np.array([24])) 24 """ return a.item() #----------------------------------------------------------------------------- _namefromtype = {'S1' : 'character', '?' : 'bool', 'b' : 'signed char', 'B' : 'unsigned char', 'h' : 'short', 'H' : 'unsigned short', 'i' : 'integer', 'I' : 'unsigned integer', 'l' : 'long integer', 'L' : 'unsigned long integer', 'q' : 'long long integer', 'Q' : 'unsigned long long integer', 'f' : 'single precision', 'd' : 'double precision', 'g' : 'long precision', 'F' : 'complex single precision', 'D' : 'complex double precision', 'G' : 'complex long double precision', 'S' : 'string', 'U' : 'unicode', 'V' : 'void', 'O' : 'object' } def typename(char): """ Return a description for the given data type code. Parameters ---------- char : str Data type code. Returns ------- out : str Description of the input data type code. See Also -------- dtype, typecodes Examples -------- >>> typechars = ['S1', '?', 'B', 'D', 'G', 'F', 'I', 'H', 'L', 'O', 'Q', ... 'S', 'U', 'V', 'b', 'd', 'g', 'f', 'i', 'h', 'l', 'q'] >>> for typechar in typechars: ... print typechar, ' : ', np.typename(typechar) ... S1 : character ? : bool B : unsigned char D : complex double precision G : complex long double precision F : complex single precision I : unsigned integer H : unsigned short L : unsigned long integer O : object Q : unsigned long long integer S : string U : unicode V : void b : signed char d : double precision g : long precision f : single precision i : integer h : short l : long integer q : long long integer """ return _namefromtype[char] #----------------------------------------------------------------------------- #determine the "minimum common type" for a group of arrays. array_type = [[_nx.single, _nx.double, _nx.longdouble], [_nx.csingle, _nx.cdouble, _nx.clongdouble]] array_precision = {_nx.single : 0, _nx.double : 1, _nx.longdouble : 2, _nx.csingle : 0, _nx.cdouble : 1, _nx.clongdouble : 2} def common_type(*arrays): """ Return a scalar type which is common to the input arrays. The return type will always be an inexact (i.e. floating point) scalar type, even if all the arrays are integer arrays. If one of the inputs is an integer array, the minimum precision type that is returned is a 64-bit floating point dtype. All input arrays can be safely cast to the returned dtype without loss of information. Parameters ---------- array1, array2, ... : ndarrays Input arrays. Returns ------- out : data type code Data type code. See Also -------- dtype, mintypecode Examples -------- >>> np.common_type(np.arange(2, dtype=np.float32)) >>> np.common_type(np.arange(2, dtype=np.float32), np.arange(2)) >>> np.common_type(np.arange(4), np.array([45, 6.j]), np.array([45.0])) """ is_complex = False precision = 0 for a in arrays: t = a.dtype.type if iscomplexobj(a): is_complex = True if issubclass(t, _nx.integer): p = 1 else: p = array_precision.get(t, None) if p is None: raise TypeError("can't get common type for non-numeric array") precision = max(precision, p) if is_complex: return array_type[1][precision] else: return array_type[0][precision] numpy-1.8.2/numpy/lib/_iotools.py0000664000175100017510000007343412370216243020156 0ustar vagrantvagrant00000000000000"""A collection of functions designed to help I/O with ascii files. """ from __future__ import division, absolute_import, print_function __docformat__ = "restructuredtext en" import sys import numpy as np import numpy.core.numeric as nx from numpy.compat import asbytes, bytes, asbytes_nested, long, basestring if sys.version_info[0] >= 3: from builtins import bool, int, float, complex, object, str unicode = str else: from __builtin__ import bool, int, float, complex, object, unicode, str if sys.version_info[0] >= 3: def _bytes_to_complex(s): return complex(s.decode('ascii')) def _bytes_to_name(s): return s.decode('ascii') else: _bytes_to_complex = complex _bytes_to_name = str def _is_string_like(obj): """ Check whether obj behaves like a string. """ try: obj + '' except (TypeError, ValueError): return False return True def _is_bytes_like(obj): """ Check whether obj behaves like a bytes object. """ try: obj + asbytes('') except (TypeError, ValueError): return False return True def _to_filehandle(fname, flag='r', return_opened=False): """ Returns the filehandle corresponding to a string or a file. If the string ends in '.gz', the file is automatically unzipped. Parameters ---------- fname : string, filehandle Name of the file whose filehandle must be returned. flag : string, optional Flag indicating the status of the file ('r' for read, 'w' for write). return_opened : boolean, optional Whether to return the opening status of the file. """ if _is_string_like(fname): if fname.endswith('.gz'): import gzip fhd = gzip.open(fname, flag) elif fname.endswith('.bz2'): import bz2 fhd = bz2.BZ2File(fname) else: fhd = file(fname, flag) opened = True elif hasattr(fname, 'seek'): fhd = fname opened = False else: raise ValueError('fname must be a string or file handle') if return_opened: return fhd, opened return fhd def has_nested_fields(ndtype): """ Returns whether one or several fields of a dtype are nested. Parameters ---------- ndtype : dtype Data-type of a structured array. Raises ------ AttributeError If `ndtype` does not have a `names` attribute. Examples -------- >>> dt = np.dtype([('name', 'S4'), ('x', float), ('y', float)]) >>> np.lib._iotools.has_nested_fields(dt) False """ for name in ndtype.names or (): if ndtype[name].names: return True return False def flatten_dtype(ndtype, flatten_base=False): """ Unpack a structured data-type by collapsing nested fields and/or fields with a shape. Note that the field names are lost. Parameters ---------- ndtype : dtype The datatype to collapse flatten_base : {False, True}, optional Whether to transform a field with a shape into several fields or not. Examples -------- >>> dt = np.dtype([('name', 'S4'), ('x', float), ('y', float), ... ('block', int, (2, 3))]) >>> np.lib._iotools.flatten_dtype(dt) [dtype('|S4'), dtype('float64'), dtype('float64'), dtype('int32')] >>> np.lib._iotools.flatten_dtype(dt, flatten_base=True) [dtype('|S4'), dtype('float64'), dtype('float64'), dtype('int32'), dtype('int32'), dtype('int32'), dtype('int32'), dtype('int32'), dtype('int32')] """ names = ndtype.names if names is None: if flatten_base: return [ndtype.base] * int(np.prod(ndtype.shape)) return [ndtype.base] else: types = [] for field in names: info = ndtype.fields[field] flat_dt = flatten_dtype(info[0], flatten_base) types.extend(flat_dt) return types class LineSplitter(object): """ Object to split a string at a given delimiter or at given places. Parameters ---------- delimiter : str, int, or sequence of ints, optional If a string, character used to delimit consecutive fields. If an integer or a sequence of integers, width(s) of each field. comment : str, optional Character used to mark the beginning of a comment. Default is '#'. autostrip : bool, optional Whether to strip each individual field. Default is True. """ def autostrip(self, method): """ Wrapper to strip each member of the output of `method`. Parameters ---------- method : function Function that takes a single argument and returns a sequence of strings. Returns ------- wrapped : function The result of wrapping `method`. `wrapped` takes a single input argument and returns a list of strings that are stripped of white-space. """ return lambda input: [_.strip() for _ in method(input)] # def __init__(self, delimiter=None, comments=asbytes('#'), autostrip=True): self.comments = comments # Delimiter is a character if isinstance(delimiter, unicode): delimiter = delimiter.encode('ascii') if (delimiter is None) or _is_bytes_like(delimiter): delimiter = delimiter or None _handyman = self._delimited_splitter # Delimiter is a list of field widths elif hasattr(delimiter, '__iter__'): _handyman = self._variablewidth_splitter idx = np.cumsum([0] + list(delimiter)) delimiter = [slice(i, j) for (i, j) in zip(idx[:-1], idx[1:])] # Delimiter is a single integer elif int(delimiter): (_handyman, delimiter) = (self._fixedwidth_splitter, int(delimiter)) else: (_handyman, delimiter) = (self._delimited_splitter, None) self.delimiter = delimiter if autostrip: self._handyman = self.autostrip(_handyman) else: self._handyman = _handyman # def _delimited_splitter(self, line): if self.comments is not None: line = line.split(self.comments)[0] line = line.strip(asbytes(" \r\n")) if not line: return [] return line.split(self.delimiter) # def _fixedwidth_splitter(self, line): if self.comments is not None: line = line.split(self.comments)[0] line = line.strip(asbytes("\r\n")) if not line: return [] fixed = self.delimiter slices = [slice(i, i + fixed) for i in range(0, len(line), fixed)] return [line[s] for s in slices] # def _variablewidth_splitter(self, line): if self.comments is not None: line = line.split(self.comments)[0] if not line: return [] slices = self.delimiter return [line[s] for s in slices] # def __call__(self, line): return self._handyman(line) class NameValidator(object): """ Object to validate a list of strings to use as field names. The strings are stripped of any non alphanumeric character, and spaces are replaced by '_'. During instantiation, the user can define a list of names to exclude, as well as a list of invalid characters. Names in the exclusion list are appended a '_' character. Once an instance has been created, it can be called with a list of names, and a list of valid names will be created. The `__call__` method accepts an optional keyword "default" that sets the default name in case of ambiguity. By default this is 'f', so that names will default to `f0`, `f1`, etc. Parameters ---------- excludelist : sequence, optional A list of names to exclude. This list is appended to the default list ['return', 'file', 'print']. Excluded names are appended an underscore: for example, `file` becomes `file_` if supplied. deletechars : str, optional A string combining invalid characters that must be deleted from the names. casesensitive : {True, False, 'upper', 'lower'}, optional * If True, field names are case-sensitive. * If False or 'upper', field names are converted to upper case. * If 'lower', field names are converted to lower case. The default value is True. replace_space : '_', optional Character(s) used in replacement of white spaces. Notes ----- Calling an instance of `NameValidator` is the same as calling its method `validate`. Examples -------- >>> validator = np.lib._iotools.NameValidator() >>> validator(['file', 'field2', 'with space', 'CaSe']) ['file_', 'field2', 'with_space', 'CaSe'] >>> validator = np.lib._iotools.NameValidator(excludelist=['excl'], deletechars='q', case_sensitive='False') >>> validator(['excl', 'field2', 'no_q', 'with space', 'CaSe']) ['excl_', 'field2', 'no_', 'with_space', 'case'] """ # defaultexcludelist = ['return', 'file', 'print'] defaultdeletechars = set("""~!@#$%^&*()-=+~\|]}[{';: /?.>,<""") # def __init__(self, excludelist=None, deletechars=None, case_sensitive=None, replace_space='_'): # Process the exclusion list .. if excludelist is None: excludelist = [] excludelist.extend(self.defaultexcludelist) self.excludelist = excludelist # Process the list of characters to delete if deletechars is None: delete = self.defaultdeletechars else: delete = set(deletechars) delete.add('"') self.deletechars = delete # Process the case option ..... if (case_sensitive is None) or (case_sensitive is True): self.case_converter = lambda x: x elif (case_sensitive is False) or ('u' in case_sensitive): self.case_converter = lambda x: x.upper() elif 'l' in case_sensitive: self.case_converter = lambda x: x.lower() else: self.case_converter = lambda x: x # self.replace_space = replace_space def validate(self, names, defaultfmt="f%i", nbfields=None): """ Validate a list of strings to use as field names for a structured array. Parameters ---------- names : sequence of str Strings to be validated. defaultfmt : str, optional Default format string, used if validating a given string reduces its length to zero. nboutput : integer, optional Final number of validated names, used to expand or shrink the initial list of names. Returns ------- validatednames : list of str The list of validated field names. Notes ----- A `NameValidator` instance can be called directly, which is the same as calling `validate`. For examples, see `NameValidator`. """ # Initial checks .............. if (names is None): if (nbfields is None): return None names = [] if isinstance(names, basestring): names = [names, ] if nbfields is not None: nbnames = len(names) if (nbnames < nbfields): names = list(names) + [''] * (nbfields - nbnames) elif (nbnames > nbfields): names = names[:nbfields] # Set some shortcuts ........... deletechars = self.deletechars excludelist = self.excludelist case_converter = self.case_converter replace_space = self.replace_space # Initializes some variables ... validatednames = [] seen = dict() nbempty = 0 # for item in names: item = case_converter(item).strip() if replace_space: item = item.replace(' ', replace_space) item = ''.join([c for c in item if c not in deletechars]) if item == '': item = defaultfmt % nbempty while item in names: nbempty += 1 item = defaultfmt % nbempty nbempty += 1 elif item in excludelist: item += '_' cnt = seen.get(item, 0) if cnt > 0: validatednames.append(item + '_%d' % cnt) else: validatednames.append(item) seen[item] = cnt + 1 return tuple(validatednames) # def __call__(self, names, defaultfmt="f%i", nbfields=None): return self.validate(names, defaultfmt=defaultfmt, nbfields=nbfields) def str2bool(value): """ Tries to transform a string supposed to represent a boolean to a boolean. Parameters ---------- value : str The string that is transformed to a boolean. Returns ------- boolval : bool The boolean representation of `value`. Raises ------ ValueError If the string is not 'True' or 'False' (case independent) Examples -------- >>> np.lib._iotools.str2bool('TRUE') True >>> np.lib._iotools.str2bool('false') False """ value = value.upper() if value == asbytes('TRUE'): return True elif value == asbytes('FALSE'): return False else: raise ValueError("Invalid boolean") class ConverterError(Exception): """ Exception raised when an error occurs in a converter for string values. """ pass class ConverterLockError(ConverterError): """ Exception raised when an attempt is made to upgrade a locked converter. """ pass class ConversionWarning(UserWarning): """ Warning issued when a string converter has a problem. Notes ----- In `genfromtxt` a `ConversionWarning` is issued if raising exceptions is explicitly suppressed with the "invalid_raise" keyword. """ pass class StringConverter(object): """ Factory class for function transforming a string into another object (int, float). After initialization, an instance can be called to transform a string into another object. If the string is recognized as representing a missing value, a default value is returned. Attributes ---------- func : function Function used for the conversion. default : any Default value to return when the input corresponds to a missing value. type : type Type of the output. _status : int Integer representing the order of the conversion. _mapper : sequence of tuples Sequence of tuples (dtype, function, default value) to evaluate in order. _locked : bool Holds `locked` parameter. Parameters ---------- dtype_or_func : {None, dtype, function}, optional If a `dtype`, specifies the input data type, used to define a basic function and a default value for missing data. For example, when `dtype` is float, the `func` attribute is set to `float` and the default value to `np.nan`. If a function, this function is used to convert a string to another object. In this case, it is recommended to give an associated default value as input. default : any, optional Value to return by default, that is, when the string to be converted is flagged as missing. If not given, `StringConverter` tries to supply a reasonable default value. missing_values : sequence of str, optional Sequence of strings indicating a missing value. locked : bool, optional Whether the StringConverter should be locked to prevent automatic upgrade or not. Default is False. """ # _mapper = [(nx.bool_, str2bool, False), (nx.integer, int, -1), (nx.floating, float, nx.nan), (complex, _bytes_to_complex, nx.nan + 0j), (nx.string_, bytes, asbytes('???'))] (_defaulttype, _defaultfunc, _defaultfill) = zip(*_mapper) # @classmethod def _getdtype(cls, val): """Returns the dtype of the input variable.""" return np.array(val).dtype # @classmethod def _getsubdtype(cls, val): """Returns the type of the dtype of the input variable.""" return np.array(val).dtype.type # # This is a bit annoying. We want to return the "general" type in most cases # (ie. "string" rather than "S10"), but we want to return the specific type # for datetime64 (ie. "datetime64[us]" rather than "datetime64"). @classmethod def _dtypeortype(cls, dtype): """Returns dtype for datetime64 and type of dtype otherwise.""" if dtype.type == np.datetime64: return dtype return dtype.type # @classmethod def upgrade_mapper(cls, func, default=None): """ Upgrade the mapper of a StringConverter by adding a new function and its corresponding default. The input function (or sequence of functions) and its associated default value (if any) is inserted in penultimate position of the mapper. The corresponding type is estimated from the dtype of the default value. Parameters ---------- func : var Function, or sequence of functions Examples -------- >>> import dateutil.parser >>> import datetime >>> dateparser = datetustil.parser.parse >>> defaultdate = datetime.date(2000, 1, 1) >>> StringConverter.upgrade_mapper(dateparser, default=defaultdate) """ # Func is a single functions if hasattr(func, '__call__'): cls._mapper.insert(-1, (cls._getsubdtype(default), func, default)) return elif hasattr(func, '__iter__'): if isinstance(func[0], (tuple, list)): for _ in func: cls._mapper.insert(-1, _) return if default is None: default = [None] * len(func) else: default = list(default) default.append([None] * (len(func) - len(default))) for (fct, dft) in zip(func, default): cls._mapper.insert(-1, (cls._getsubdtype(dft), fct, dft)) # def __init__(self, dtype_or_func=None, default=None, missing_values=None, locked=False): # Convert unicode (for Py3) if isinstance(missing_values, unicode): missing_values = asbytes(missing_values) elif isinstance(missing_values, (list, tuple)): missing_values = asbytes_nested(missing_values) # Defines a lock for upgrade self._locked = bool(locked) # No input dtype: minimal initialization if dtype_or_func is None: self.func = str2bool self._status = 0 self.default = default or False dtype = np.dtype('bool') else: # Is the input a np.dtype ? try: self.func = None dtype = np.dtype(dtype_or_func) except TypeError: # dtype_or_func must be a function, then if not hasattr(dtype_or_func, '__call__'): errmsg = "The input argument `dtype` is neither a function"\ " or a dtype (got '%s' instead)" raise TypeError(errmsg % type(dtype_or_func)) # Set the function self.func = dtype_or_func # If we don't have a default, try to guess it or set it to None if default is None: try: default = self.func(asbytes('0')) except ValueError: default = None dtype = self._getdtype(default) # Set the status according to the dtype _status = -1 for (i, (deftype, func, default_def)) in enumerate(self._mapper): if np.issubdtype(dtype.type, deftype): _status = i if default is None: self.default = default_def else: self.default = default break if _status == -1: # We never found a match in the _mapper... _status = 0 self.default = default self._status = _status # If the input was a dtype, set the function to the last we saw if self.func is None: self.func = func # If the status is 1 (int), change the function to # something more robust. if self.func == self._mapper[1][1]: if issubclass(dtype.type, np.uint64): self.func = np.uint64 elif issubclass(dtype.type, np.int64): self.func = np.int64 else: self.func = lambda x : int(float(x)) # Store the list of strings corresponding to missing values. if missing_values is None: self.missing_values = set([asbytes('')]) else: if isinstance(missing_values, bytes): missing_values = missing_values.split(asbytes(",")) self.missing_values = set(list(missing_values) + [asbytes('')]) # self._callingfunction = self._strict_call self.type = self._dtypeortype(dtype) self._checked = False self._initial_default = default # def _loose_call(self, value): try: return self.func(value) except ValueError: return self.default # def _strict_call(self, value): try: return self.func(value) except ValueError: if value.strip() in self.missing_values: if not self._status: self._checked = False return self.default raise ValueError("Cannot convert string '%s'" % value) # def __call__(self, value): return self._callingfunction(value) # def upgrade(self, value): """ Try to find the best converter for a given string, and return the result. The supplied string `value` is converted by testing different converters in order. First the `func` method of the `StringConverter` instance is tried, if this fails other available converters are tried. The order in which these other converters are tried is determined by the `_status` attribute of the instance. Parameters ---------- value : str The string to convert. Returns ------- out : any The result of converting `value` with the appropriate converter. """ self._checked = True try: self._strict_call(value) except ValueError: # Raise an exception if we locked the converter... if self._locked: errmsg = "Converter is locked and cannot be upgraded" raise ConverterLockError(errmsg) _statusmax = len(self._mapper) # Complains if we try to upgrade by the maximum _status = self._status if _status == _statusmax: errmsg = "Could not find a valid conversion function" raise ConverterError(errmsg) elif _status < _statusmax - 1: _status += 1 (self.type, self.func, default) = self._mapper[_status] self._status = _status if self._initial_default is not None: self.default = self._initial_default else: self.default = default self.upgrade(value) def iterupgrade(self, value): self._checked = True if not hasattr(value, '__iter__'): value = (value,) _strict_call = self._strict_call try: for _m in value: _strict_call(_m) except ValueError: # Raise an exception if we locked the converter... if self._locked: errmsg = "Converter is locked and cannot be upgraded" raise ConverterLockError(errmsg) _statusmax = len(self._mapper) # Complains if we try to upgrade by the maximum _status = self._status if _status == _statusmax: raise ConverterError("Could not find a valid conversion function") elif _status < _statusmax - 1: _status += 1 (self.type, self.func, default) = self._mapper[_status] if self._initial_default is not None: self.default = self._initial_default else: self.default = default self._status = _status self.iterupgrade(value) def update(self, func, default=None, testing_value=None, missing_values=asbytes(''), locked=False): """ Set StringConverter attributes directly. Parameters ---------- func : function Conversion function. default : any, optional Value to return by default, that is, when the string to be converted is flagged as missing. If not given, `StringConverter` tries to supply a reasonable default value. testing_value : str, optional A string representing a standard input value of the converter. This string is used to help defining a reasonable default value. missing_values : sequence of str, optional Sequence of strings indicating a missing value. locked : bool, optional Whether the StringConverter should be locked to prevent automatic upgrade or not. Default is False. Notes ----- `update` takes the same parameters as the constructor of `StringConverter`, except that `func` does not accept a `dtype` whereas `dtype_or_func` in the constructor does. """ self.func = func self._locked = locked # Don't reset the default to None if we can avoid it if default is not None: self.default = default self.type = self._dtypeortype(self._getdtype(default)) else: try: tester = func(testing_value or asbytes('1')) except (TypeError, ValueError): tester = None self.type = self._dtypeortype(self._getdtype(tester)) # Add the missing values to the existing set if missing_values is not None: if _is_bytes_like(missing_values): self.missing_values.add(missing_values) elif hasattr(missing_values, '__iter__'): for val in missing_values: self.missing_values.add(val) else: self.missing_values = [] def easy_dtype(ndtype, names=None, defaultfmt="f%i", **validationargs): """ Convenience function to create a `np.dtype` object. The function processes the input `dtype` and matches it with the given names. Parameters ---------- ndtype : var Definition of the dtype. Can be any string or dictionary recognized by the `np.dtype` function, or a sequence of types. names : str or sequence, optional Sequence of strings to use as field names for a structured dtype. For convenience, `names` can be a string of a comma-separated list of names. defaultfmt : str, optional Format string used to define missing names, such as ``"f%i"`` (default) or ``"fields_%02i"``. validationargs : optional A series of optional arguments used to initialize a `NameValidator`. Examples -------- >>> np.lib._iotools.easy_dtype(float) dtype('float64') >>> np.lib._iotools.easy_dtype("i4, f8") dtype([('f0', '>> np.lib._iotools.easy_dtype("i4, f8", defaultfmt="field_%03i") dtype([('field_000', '>> np.lib._iotools.easy_dtype((int, float, float), names="a,b,c") dtype([('a', '>> np.lib._iotools.easy_dtype(float, names="a,b,c") dtype([('a', ' 0): validate = NameValidator(**validationargs) # Default initial names : should we change the format ? if (ndtype.names == tuple("f%i" % i for i in range(nbtypes))) and \ (defaultfmt != "f%i"): ndtype.names = validate([''] * nbtypes, defaultfmt=defaultfmt) # Explicit initial names : just validate else: ndtype.names = validate(ndtype.names, defaultfmt=defaultfmt) return ndtype numpy-1.8.2/numpy/lib/utils.py0000664000175100017510000010645412370216243017466 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function import os import sys import types import re from numpy.core.numerictypes import issubclass_, issubsctype, issubdtype from numpy.core import product, ndarray, ufunc, asarray __all__ = ['issubclass_', 'issubsctype', 'issubdtype', 'deprecate', 'deprecate_with_doc', 'get_numarray_include', 'get_include', 'info', 'source', 'who', 'lookfor', 'byte_bounds', 'safe_eval'] def get_include(): """ Return the directory that contains the NumPy \\*.h header files. Extension modules that need to compile against NumPy should use this function to locate the appropriate include directory. Notes ----- When using ``distutils``, for example in ``setup.py``. :: import numpy as np ... Extension('extension_name', ... include_dirs=[np.get_include()]) ... """ import numpy if numpy.show_config is None: # running from numpy source directory d = os.path.join(os.path.dirname(numpy.__file__), 'core', 'include') else: # using installed numpy core headers import numpy.core as core d = os.path.join(os.path.dirname(core.__file__), 'include') return d def get_numarray_include(type=None): """ Return the directory that contains the numarray \\*.h header files. Extension modules that need to compile against numarray should use this function to locate the appropriate include directory. Parameters ---------- type : any, optional If `type` is not None, the location of the NumPy headers is returned as well. Returns ------- dirs : str or list of str If `type` is None, `dirs` is a string containing the path to the numarray headers. If `type` is not None, `dirs` is a list of strings with first the path(s) to the numarray headers, followed by the path to the NumPy headers. Notes ----- Useful when using ``distutils``, for example in ``setup.py``. :: import numpy as np ... Extension('extension_name', ... include_dirs=[np.get_numarray_include()]) ... """ from numpy.numarray import get_numarray_include_dirs include_dirs = get_numarray_include_dirs() if type is None: return include_dirs[0] else: return include_dirs + [get_include()] def _set_function_name(func, name): func.__name__ = name return func class _Deprecate(object): """ Decorator class to deprecate old functions. Refer to `deprecate` for details. See Also -------- deprecate """ def __init__(self, old_name=None, new_name=None, message=None): self.old_name = old_name self.new_name = new_name self.message = message def __call__(self, func, *args, **kwargs): """ Decorator call. Refer to ``decorate``. """ old_name = self.old_name new_name = self.new_name message = self.message import warnings if old_name is None: try: old_name = func.__name__ except AttributeError: old_name = func.__name__ if new_name is None: depdoc = "`%s` is deprecated!" % old_name else: depdoc = "`%s` is deprecated, use `%s` instead!" % \ (old_name, new_name) if message is not None: depdoc += "\n" + message def newfunc(*args,**kwds): """`arrayrange` is deprecated, use `arange` instead!""" warnings.warn(depdoc, DeprecationWarning) return func(*args, **kwds) newfunc = _set_function_name(newfunc, old_name) doc = func.__doc__ if doc is None: doc = depdoc else: doc = '\n\n'.join([depdoc, doc]) newfunc.__doc__ = doc try: d = func.__dict__ except AttributeError: pass else: newfunc.__dict__.update(d) return newfunc def deprecate(*args, **kwargs): """ Issues a DeprecationWarning, adds warning to `old_name`'s docstring, rebinds ``old_name.__name__`` and returns the new function object. This function may also be used as a decorator. Parameters ---------- func : function The function to be deprecated. old_name : str, optional The name of the function to be deprecated. Default is None, in which case the name of `func` is used. new_name : str, optional The new name for the function. Default is None, in which case the deprecation message is that `old_name` is deprecated. If given, the deprecation message is that `old_name` is deprecated and `new_name` should be used instead. message : str, optional Additional explanation of the deprecation. Displayed in the docstring after the warning. Returns ------- old_func : function The deprecated function. Examples -------- Note that ``olduint`` returns a value after printing Deprecation Warning: >>> olduint = np.deprecate(np.uint) >>> olduint(6) /usr/lib/python2.5/site-packages/numpy/lib/utils.py:114: DeprecationWarning: uint32 is deprecated warnings.warn(str1, DeprecationWarning) 6 """ # Deprecate may be run as a function or as a decorator # If run as a function, we initialise the decorator class # and execute its __call__ method. if args: fn = args[0] args = args[1:] # backward compatibility -- can be removed # after next release if 'newname' in kwargs: kwargs['new_name'] = kwargs.pop('newname') if 'oldname' in kwargs: kwargs['old_name'] = kwargs.pop('oldname') return _Deprecate(*args, **kwargs)(fn) else: return _Deprecate(*args, **kwargs) deprecate_with_doc = lambda msg: _Deprecate(message=msg) #-------------------------------------------- # Determine if two arrays can share memory #-------------------------------------------- def byte_bounds(a): """ Returns pointers to the end-points of an array. Parameters ---------- a : ndarray Input array. It must conform to the Python-side of the array interface. Returns ------- (low, high) : tuple of 2 integers The first integer is the first byte of the array, the second integer is just past the last byte of the array. If `a` is not contiguous it will not use every byte between the (`low`, `high`) values. Examples -------- >>> I = np.eye(2, dtype='f'); I.dtype dtype('float32') >>> low, high = np.byte_bounds(I) >>> high - low == I.size*I.itemsize True >>> I = np.eye(2, dtype='G'); I.dtype dtype('complex192') >>> low, high = np.byte_bounds(I) >>> high - low == I.size*I.itemsize True """ ai = a.__array_interface__ a_data = ai['data'][0] astrides = ai['strides'] ashape = ai['shape'] bytes_a = asarray(a).dtype.itemsize a_low = a_high = a_data if astrides is None: # contiguous case a_high += a.size * bytes_a else: for shape, stride in zip(ashape, astrides): if stride < 0: a_low += (shape-1)*stride else: a_high += (shape-1)*stride a_high += bytes_a return a_low, a_high #----------------------------------------------------------------------------- # Function for output and information on the variables used. #----------------------------------------------------------------------------- def who(vardict=None): """ Print the Numpy arrays in the given dictionary. If there is no dictionary passed in or `vardict` is None then returns Numpy arrays in the globals() dictionary (all Numpy arrays in the namespace). Parameters ---------- vardict : dict, optional A dictionary possibly containing ndarrays. Default is globals(). Returns ------- out : None Returns 'None'. Notes ----- Prints out the name, shape, bytes and type of all of the ndarrays present in `vardict`. Examples -------- >>> a = np.arange(10) >>> b = np.ones(20) >>> np.who() Name Shape Bytes Type =========================================================== a 10 40 int32 b 20 160 float64 Upper bound on total bytes = 200 >>> d = {'x': np.arange(2.0), 'y': np.arange(3.0), 'txt': 'Some str', ... 'idx':5} >>> np.who(d) Name Shape Bytes Type =========================================================== y 3 24 float64 x 2 16 float64 Upper bound on total bytes = 40 """ if vardict is None: frame = sys._getframe().f_back vardict = frame.f_globals sta = [] cache = {} for name in vardict.keys(): if isinstance(vardict[name], ndarray): var = vardict[name] idv = id(var) if idv in cache.keys(): namestr = name + " (%s)" % cache[idv] original=0 else: cache[idv] = name namestr = name original=1 shapestr = " x ".join(map(str, var.shape)) bytestr = str(var.nbytes) sta.append([namestr, shapestr, bytestr, var.dtype.name, original]) maxname = 0 maxshape = 0 maxbyte = 0 totalbytes = 0 for k in range(len(sta)): val = sta[k] if maxname < len(val[0]): maxname = len(val[0]) if maxshape < len(val[1]): maxshape = len(val[1]) if maxbyte < len(val[2]): maxbyte = len(val[2]) if val[4]: totalbytes += int(val[2]) if len(sta) > 0: sp1 = max(10, maxname) sp2 = max(10, maxshape) sp3 = max(10, maxbyte) prval = "Name %s Shape %s Bytes %s Type" % (sp1*' ', sp2*' ', sp3*' ') print(prval + "\n" + "="*(len(prval)+5) + "\n") for k in range(len(sta)): val = sta[k] print("%s %s %s %s %s %s %s" % (val[0], ' '*(sp1-len(val[0])+4), val[1], ' '*(sp2-len(val[1])+5), val[2], ' '*(sp3-len(val[2])+5), val[3])) print("\nUpper bound on total bytes = %d" % totalbytes) return #----------------------------------------------------------------------------- # NOTE: pydoc defines a help function which works simliarly to this # except it uses a pager to take over the screen. # combine name and arguments and split to multiple lines of # width characters. End lines on a comma and begin argument list # indented with the rest of the arguments. def _split_line(name, arguments, width): firstwidth = len(name) k = firstwidth newstr = name sepstr = ", " arglist = arguments.split(sepstr) for argument in arglist: if k == firstwidth: addstr = "" else: addstr = sepstr k = k + len(argument) + len(addstr) if k > width: k = firstwidth + 1 + len(argument) newstr = newstr + ",\n" + " "*(firstwidth+2) + argument else: newstr = newstr + addstr + argument return newstr _namedict = None _dictlist = None # Traverse all module directories underneath globals # to see if something is defined def _makenamedict(module='numpy'): module = __import__(module, globals(), locals(), []) thedict = {module.__name__:module.__dict__} dictlist = [module.__name__] totraverse = [module.__dict__] while True: if len(totraverse) == 0: break thisdict = totraverse.pop(0) for x in thisdict.keys(): if isinstance(thisdict[x], types.ModuleType): modname = thisdict[x].__name__ if modname not in dictlist: moddict = thisdict[x].__dict__ dictlist.append(modname) totraverse.append(moddict) thedict[modname] = moddict return thedict, dictlist def info(object=None,maxwidth=76,output=sys.stdout,toplevel='numpy'): """ Get help information for a function, class, or module. Parameters ---------- object : object or str, optional Input object or name to get information about. If `object` is a numpy object, its docstring is given. If it is a string, available modules are searched for matching objects. If None, information about `info` itself is returned. maxwidth : int, optional Printing width. output : file like object, optional File like object that the output is written to, default is ``stdout``. The object has to be opened in 'w' or 'a' mode. toplevel : str, optional Start search at this level. See Also -------- source, lookfor Notes ----- When used interactively with an object, ``np.info(obj)`` is equivalent to ``help(obj)`` on the Python prompt or ``obj?`` on the IPython prompt. Examples -------- >>> np.info(np.polyval) # doctest: +SKIP polyval(p, x) Evaluate the polynomial p at x. ... When using a string for `object` it is possible to get multiple results. >>> np.info('fft') # doctest: +SKIP *** Found in numpy *** Core FFT routines ... *** Found in numpy.fft *** fft(a, n=None, axis=-1) ... *** Repeat reference found in numpy.fft.fftpack *** *** Total of 3 references found. *** """ global _namedict, _dictlist # Local import to speed up numpy's import time. import pydoc, inspect if hasattr(object, '_ppimport_importer') or \ hasattr(object, '_ppimport_module'): object = object._ppimport_module elif hasattr(object, '_ppimport_attr'): object = object._ppimport_attr if object is None: info(info) elif isinstance(object, ndarray): import numpy.numarray as nn nn.info(object, output=output, numpy=1) elif isinstance(object, str): if _namedict is None: _namedict, _dictlist = _makenamedict(toplevel) numfound = 0 objlist = [] for namestr in _dictlist: try: obj = _namedict[namestr][object] if id(obj) in objlist: print("\n *** Repeat reference found in %s *** " % namestr, file=output) else: objlist.append(id(obj)) print(" *** Found in %s ***" % namestr, file=output) info(obj) print("-"*maxwidth, file=output) numfound += 1 except KeyError: pass if numfound == 0: print("Help for %s not found." % object, file=output) else: print("\n *** Total of %d references found. ***" % numfound, file=output) elif inspect.isfunction(object): name = object.__name__ arguments = inspect.formatargspec(*inspect.getargspec(object)) if len(name+arguments) > maxwidth: argstr = _split_line(name, arguments, maxwidth) else: argstr = name + arguments print(" " + argstr + "\n", file=output) print(inspect.getdoc(object), file=output) elif inspect.isclass(object): name = object.__name__ arguments = "()" try: if hasattr(object, '__init__'): arguments = inspect.formatargspec(*inspect.getargspec(object.__init__.__func__)) arglist = arguments.split(', ') if len(arglist) > 1: arglist[1] = "("+arglist[1] arguments = ", ".join(arglist[1:]) except: pass if len(name+arguments) > maxwidth: argstr = _split_line(name, arguments, maxwidth) else: argstr = name + arguments print(" " + argstr + "\n", file=output) doc1 = inspect.getdoc(object) if doc1 is None: if hasattr(object, '__init__'): print(inspect.getdoc(object.__init__), file=output) else: print(inspect.getdoc(object), file=output) methods = pydoc.allmethods(object) if methods != []: print("\n\nMethods:\n", file=output) for meth in methods: if meth[0] == '_': continue thisobj = getattr(object, meth, None) if thisobj is not None: methstr, other = pydoc.splitdoc(inspect.getdoc(thisobj) or "None") print(" %s -- %s" % (meth, methstr), file=output) elif (sys.version_info[0] < 3 and isinstance(object, types.InstanceType)): # check for __call__ method # types.InstanceType is the type of the instances of oldstyle classes print("Instance of class: ", object.__class__.__name__, file=output) print(file=output) if hasattr(object, '__call__'): arguments = inspect.formatargspec(*inspect.getargspec(object.__call__.__func__)) arglist = arguments.split(', ') if len(arglist) > 1: arglist[1] = "("+arglist[1] arguments = ", ".join(arglist[1:]) else: arguments = "()" if hasattr(object, 'name'): name = "%s" % object.name else: name = "" if len(name+arguments) > maxwidth: argstr = _split_line(name, arguments, maxwidth) else: argstr = name + arguments print(" " + argstr + "\n", file=output) doc = inspect.getdoc(object.__call__) if doc is not None: print(inspect.getdoc(object.__call__), file=output) print(inspect.getdoc(object), file=output) else: print(inspect.getdoc(object), file=output) elif inspect.ismethod(object): name = object.__name__ arguments = inspect.formatargspec(*inspect.getargspec(object.__func__)) arglist = arguments.split(', ') if len(arglist) > 1: arglist[1] = "("+arglist[1] arguments = ", ".join(arglist[1:]) else: arguments = "()" if len(name+arguments) > maxwidth: argstr = _split_line(name, arguments, maxwidth) else: argstr = name + arguments print(" " + argstr + "\n", file=output) print(inspect.getdoc(object), file=output) elif hasattr(object, '__doc__'): print(inspect.getdoc(object), file=output) def source(object, output=sys.stdout): """ Print or write to a file the source code for a Numpy object. The source code is only returned for objects written in Python. Many functions and classes are defined in C and will therefore not return useful information. Parameters ---------- object : numpy object Input object. This can be any object (function, class, module, ...). output : file object, optional If `output` not supplied then source code is printed to screen (sys.stdout). File object must be created with either write 'w' or append 'a' modes. See Also -------- lookfor, info Examples -------- >>> np.source(np.interp) #doctest: +SKIP In file: /usr/lib/python2.6/dist-packages/numpy/lib/function_base.py def interp(x, xp, fp, left=None, right=None): \"\"\".... (full docstring printed)\"\"\" if isinstance(x, (float, int, number)): return compiled_interp([x], xp, fp, left, right).item() else: return compiled_interp(x, xp, fp, left, right) The source code is only returned for objects written in Python. >>> np.source(np.array) #doctest: +SKIP Not available for this object. """ # Local import to speed up numpy's import time. import inspect try: print("In file: %s\n" % inspect.getsourcefile(object), file=output) print(inspect.getsource(object), file=output) except: print("Not available for this object.", file=output) # Cache for lookfor: {id(module): {name: (docstring, kind, index), ...}...} # where kind: "func", "class", "module", "object" # and index: index in breadth-first namespace traversal _lookfor_caches = {} # regexp whose match indicates that the string may contain a function signature _function_signature_re = re.compile(r"[a-z0-9_]+\(.*[,=].*\)", re.I) def lookfor(what, module=None, import_modules=True, regenerate=False, output=None): """ Do a keyword search on docstrings. A list of of objects that matched the search is displayed, sorted by relevance. All given keywords need to be found in the docstring for it to be returned as a result, but the order does not matter. Parameters ---------- what : str String containing words to look for. module : str or list, optional Name of module(s) whose docstrings to go through. import_modules : bool, optional Whether to import sub-modules in packages. Default is True. regenerate : bool, optional Whether to re-generate the docstring cache. Default is False. output : file-like, optional File-like object to write the output to. If omitted, use a pager. See Also -------- source, info Notes ----- Relevance is determined only roughly, by checking if the keywords occur in the function name, at the start of a docstring, etc. Examples -------- >>> np.lookfor('binary representation') Search results for 'binary representation' ------------------------------------------ numpy.binary_repr Return the binary representation of the input number as a string. numpy.core.setup_common.long_double_representation Given a binary dump as given by GNU od -b, look for long double numpy.base_repr Return a string representation of a number in the given base system. ... """ import pydoc # Cache cache = _lookfor_generate_cache(module, import_modules, regenerate) # Search # XXX: maybe using a real stemming search engine would be better? found = [] whats = str(what).lower().split() if not whats: return for name, (docstring, kind, index) in cache.items(): if kind in ('module', 'object'): # don't show modules or objects continue ok = True doc = docstring.lower() for w in whats: if w not in doc: ok = False break if ok: found.append(name) # Relevance sort # XXX: this is full Harrison-Stetson heuristics now, # XXX: it probably could be improved kind_relevance = {'func': 1000, 'class': 1000, 'module': -1000, 'object': -1000} def relevance(name, docstr, kind, index): r = 0 # do the keywords occur within the start of the docstring? first_doc = "\n".join(docstr.lower().strip().split("\n")[:3]) r += sum([200 for w in whats if w in first_doc]) # do the keywords occur in the function name? r += sum([30 for w in whats if w in name]) # is the full name long? r += -len(name) * 5 # is the object of bad type? r += kind_relevance.get(kind, -1000) # is the object deep in namespace hierarchy? r += -name.count('.') * 10 r += max(-index / 100, -100) return r def relevance_value(a): return relevance(a, *cache[a]) found.sort(key=relevance_value) # Pretty-print s = "Search results for '%s'" % (' '.join(whats)) help_text = [s, "-"*len(s)] for name in found[::-1]: doc, kind, ix = cache[name] doclines = [line.strip() for line in doc.strip().split("\n") if line.strip()] # find a suitable short description try: first_doc = doclines[0].strip() if _function_signature_re.search(first_doc): first_doc = doclines[1].strip() except IndexError: first_doc = "" help_text.append("%s\n %s" % (name, first_doc)) if not found: help_text.append("Nothing found.") # Output if output is not None: output.write("\n".join(help_text)) elif len(help_text) > 10: pager = pydoc.getpager() pager("\n".join(help_text)) else: print("\n".join(help_text)) def _lookfor_generate_cache(module, import_modules, regenerate): """ Generate docstring cache for given module. Parameters ---------- module : str, None, module Module for which to generate docstring cache import_modules : bool Whether to import sub-modules in packages. regenerate : bool Re-generate the docstring cache Returns ------- cache : dict {obj_full_name: (docstring, kind, index), ...} Docstring cache for the module, either cached one (regenerate=False) or newly generated. """ global _lookfor_caches # Local import to speed up numpy's import time. import inspect if sys.version_info[0] >= 3: # In Python3 stderr, stdout are text files. from io import StringIO else: from StringIO import StringIO if module is None: module = "numpy" if isinstance(module, str): try: __import__(module) except ImportError: return {} module = sys.modules[module] elif isinstance(module, list) or isinstance(module, tuple): cache = {} for mod in module: cache.update(_lookfor_generate_cache(mod, import_modules, regenerate)) return cache if id(module) in _lookfor_caches and not regenerate: return _lookfor_caches[id(module)] # walk items and collect docstrings cache = {} _lookfor_caches[id(module)] = cache seen = {} index = 0 stack = [(module.__name__, module)] while stack: name, item = stack.pop(0) if id(item) in seen: continue seen[id(item)] = True index += 1 kind = "object" if inspect.ismodule(item): kind = "module" try: _all = item.__all__ except AttributeError: _all = None # import sub-packages if import_modules and hasattr(item, '__path__'): for pth in item.__path__: for mod_path in os.listdir(pth): this_py = os.path.join(pth, mod_path) init_py = os.path.join(pth, mod_path, '__init__.py') if os.path.isfile(this_py) and mod_path.endswith('.py'): to_import = mod_path[:-3] elif os.path.isfile(init_py): to_import = mod_path else: continue if to_import == '__init__': continue try: # Catch SystemExit, too base_exc = BaseException except NameError: # Python 2.4 doesn't have BaseException base_exc = Exception try: old_stdout = sys.stdout old_stderr = sys.stderr try: sys.stdout = StringIO() sys.stderr = StringIO() __import__("%s.%s" % (name, to_import)) finally: sys.stdout = old_stdout sys.stderr = old_stderr except base_exc: continue for n, v in _getmembers(item): try: item_name = getattr(v, '__name__', "%s.%s" % (name, n)) mod_name = getattr(v, '__module__', None) except NameError: # ref. SWIG's global cvars # NameError: Unknown C global variable item_name = "%s.%s" % (name, n) mod_name = None if '.' not in item_name and mod_name: item_name = "%s.%s" % (mod_name, item_name) if not item_name.startswith(name + '.'): # don't crawl "foreign" objects if isinstance(v, ufunc): # ... unless they are ufuncs pass else: continue elif not (inspect.ismodule(v) or _all is None or n in _all): continue stack.append(("%s.%s" % (name, n), v)) elif inspect.isclass(item): kind = "class" for n, v in _getmembers(item): stack.append(("%s.%s" % (name, n), v)) elif hasattr(item, "__call__"): kind = "func" try: doc = inspect.getdoc(item) except NameError: # ref SWIG's NameError: Unknown C global variable doc = None if doc is not None: cache[name] = (doc, kind, index) return cache def _getmembers(item): import inspect try: members = inspect.getmembers(item) except AttributeError: members = [(x, getattr(item, x)) for x in dir(item) if hasattr(item, x)] return members #----------------------------------------------------------------------------- # The following SafeEval class and company are adapted from Michael Spencer's # ASPN Python Cookbook recipe: # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/364469 # Accordingly it is mostly Copyright 2006 by Michael Spencer. # The recipe, like most of the other ASPN Python Cookbook recipes was made # available under the Python license. # http://www.python.org/license # It has been modified to: # * handle unary -/+ # * support True/False/None # * raise SyntaxError instead of a custom exception. class SafeEval(object): """ Object to evaluate constant string expressions. This includes strings with lists, dicts and tuples using the abstract syntax tree created by ``compiler.parse``. For an example of usage, see `safe_eval`. See Also -------- safe_eval """ if sys.version_info[0] < 3: def visit(self, node, **kw): cls = node.__class__ meth = getattr(self, 'visit'+cls.__name__, self.default) return meth(node, **kw) def default(self, node, **kw): raise SyntaxError("Unsupported source construct: %s" % node.__class__) def visitExpression(self, node, **kw): for child in node.getChildNodes(): return self.visit(child, **kw) def visitConst(self, node, **kw): return node.value def visitDict(self, node,**kw): return dict([(self.visit(k), self.visit(v)) for k, v in node.items]) def visitTuple(self, node, **kw): return tuple([self.visit(i) for i in node.nodes]) def visitList(self, node, **kw): return [self.visit(i) for i in node.nodes] def visitUnaryAdd(self, node, **kw): return +self.visit(node.getChildNodes()[0]) def visitUnarySub(self, node, **kw): return -self.visit(node.getChildNodes()[0]) def visitName(self, node, **kw): if node.name == 'False': return False elif node.name == 'True': return True elif node.name == 'None': return None else: raise SyntaxError("Unknown name: %s" % node.name) else: def visit(self, node): cls = node.__class__ meth = getattr(self, 'visit' + cls.__name__, self.default) return meth(node) def default(self, node): raise SyntaxError("Unsupported source construct: %s" % node.__class__) def visitExpression(self, node): return self.visit(node.body) def visitNum(self, node): return node.n def visitStr(self, node): return node.s def visitBytes(self, node): return node.s def visitDict(self, node,**kw): return dict([(self.visit(k), self.visit(v)) for k, v in zip(node.keys, node.values)]) def visitTuple(self, node): return tuple([self.visit(i) for i in node.elts]) def visitList(self, node): return [self.visit(i) for i in node.elts] def visitUnaryOp(self, node): import ast if isinstance(node.op, ast.UAdd): return +self.visit(node.operand) elif isinstance(node.op, ast.USub): return -self.visit(node.operand) else: raise SyntaxError("Unknown unary op: %r" % node.op) def visitName(self, node): if node.id == 'False': return False elif node.id == 'True': return True elif node.id == 'None': return None else: raise SyntaxError("Unknown name: %s" % node.id) def visitNameConstant(self, node): return node.value def safe_eval(source): """ Protected string evaluation. Evaluate a string containing a Python literal expression without allowing the execution of arbitrary non-literal code. Parameters ---------- source : str The string to evaluate. Returns ------- obj : object The result of evaluating `source`. Raises ------ SyntaxError If the code has invalid Python syntax, or if it contains non-literal code. Examples -------- >>> np.safe_eval('1') 1 >>> np.safe_eval('[1, 2, 3]') [1, 2, 3] >>> np.safe_eval('{"foo": ("bar", 10.0)}') {'foo': ('bar', 10.0)} >>> np.safe_eval('import os') Traceback (most recent call last): ... SyntaxError: invalid syntax >>> np.safe_eval('open("/home/user/.ssh/id_dsa").read()') Traceback (most recent call last): ... SyntaxError: Unsupported source construct: compiler.ast.CallFunc """ # Local imports to speed up numpy's import time. import warnings with warnings.catch_warnings(): # compiler package is deprecated for 3.x, which is already solved here warnings.simplefilter('ignore', DeprecationWarning) try: import compiler except ImportError: import ast as compiler walker = SafeEval() try: ast = compiler.parse(source, mode="eval") except SyntaxError as err: raise try: return walker.visit(ast) except SyntaxError as err: raise #----------------------------------------------------------------------------- numpy-1.8.2/numpy/lib/info.py0000664000175100017510000001424212370216242017251 0ustar vagrantvagrant00000000000000""" Basic functions used by several sub-packages and useful to have in the main name-space. Type Handling ------------- ================ =================== iscomplexobj Test for complex object, scalar result isrealobj Test for real object, scalar result iscomplex Test for complex elements, array result isreal Test for real elements, array result imag Imaginary part real Real part real_if_close Turns complex number with tiny imaginary part to real isneginf Tests for negative infinity, array result isposinf Tests for positive infinity, array result isnan Tests for nans, array result isinf Tests for infinity, array result isfinite Tests for finite numbers, array result isscalar True if argument is a scalar nan_to_num Replaces NaN's with 0 and infinities with large numbers cast Dictionary of functions to force cast to each type common_type Determine the minimum common type code for a group of arrays mintypecode Return minimal allowed common typecode. ================ =================== Index Tricks ------------ ================ =================== mgrid Method which allows easy construction of N-d 'mesh-grids' ``r_`` Append and construct arrays: turns slice objects into ranges and concatenates them, for 2d arrays appends rows. index_exp Konrad Hinsen's index_expression class instance which can be useful for building complicated slicing syntax. ================ =================== Useful Functions ---------------- ================ =================== select Extension of where to multiple conditions and choices extract Extract 1d array from flattened array according to mask insert Insert 1d array of values into Nd array according to mask linspace Evenly spaced samples in linear space logspace Evenly spaced samples in logarithmic space fix Round x to nearest integer towards zero mod Modulo mod(x,y) = x % y except keeps sign of y amax Array maximum along axis amin Array minimum along axis ptp Array max-min along axis cumsum Cumulative sum along axis prod Product of elements along axis cumprod Cumluative product along axis diff Discrete differences along axis angle Returns angle of complex argument unwrap Unwrap phase along given axis (1-d algorithm) sort_complex Sort a complex-array (based on real, then imaginary) trim_zeros Trim the leading and trailing zeros from 1D array. vectorize A class that wraps a Python function taking scalar arguments into a generalized function which can handle arrays of arguments using the broadcast rules of numerix Python. ================ =================== Shape Manipulation ------------------ ================ =================== squeeze Return a with length-one dimensions removed. atleast_1d Force arrays to be > 1D atleast_2d Force arrays to be > 2D atleast_3d Force arrays to be > 3D vstack Stack arrays vertically (row on row) hstack Stack arrays horizontally (column on column) column_stack Stack 1D arrays as columns into 2D array dstack Stack arrays depthwise (along third dimension) split Divide array into a list of sub-arrays hsplit Split into columns vsplit Split into rows dsplit Split along third dimension ================ =================== Matrix (2D Array) Manipulations ------------------------------- ================ =================== fliplr 2D array with columns flipped flipud 2D array with rows flipped rot90 Rotate a 2D array a multiple of 90 degrees eye Return a 2D array with ones down a given diagonal diag Construct a 2D array from a vector, or return a given diagonal from a 2D array. mat Construct a Matrix bmat Build a Matrix from blocks ================ =================== Polynomials ----------- ================ =================== poly1d A one-dimensional polynomial class poly Return polynomial coefficients from roots roots Find roots of polynomial given coefficients polyint Integrate polynomial polyder Differentiate polynomial polyadd Add polynomials polysub Substract polynomials polymul Multiply polynomials polydiv Divide polynomials polyval Evaluate polynomial at given argument ================ =================== Import Tricks ------------- ================ =================== ppimport Postpone module import until trying to use it ppimport_attr Postpone module import until trying to use its attribute ppresolve Import postponed module and return it. ================ =================== Machine Arithmetics ------------------- ================ =================== machar_single Single precision floating point arithmetic parameters machar_double Double precision floating point arithmetic parameters ================ =================== Threading Tricks ---------------- ================ =================== ParallelExec Execute commands in parallel thread. ================ =================== 1D Array Set Operations ----------------------- Set operations for 1D numeric arrays based on sort() function. ================ =================== ediff1d Array difference (auxiliary function). unique Unique elements of an array. intersect1d Intersection of 1D arrays with unique elements. setxor1d Set exclusive-or of 1D arrays with unique elements. in1d Test whether elements in a 1D array are also present in another array. union1d Union of 1D arrays with unique elements. setdiff1d Set difference of 1D arrays with unique elements. ================ =================== """ from __future__ import division, absolute_import, print_function depends = ['core', 'testing'] global_symbols = ['*'] numpy-1.8.2/numpy/lib/index_tricks.py0000664000175100017510000006241312370216243021010 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function __all__ = ['ravel_multi_index', 'unravel_index', 'mgrid', 'ogrid', 'r_', 'c_', 's_', 'index_exp', 'ix_', 'ndenumerate', 'ndindex', 'fill_diagonal', 'diag_indices', 'diag_indices_from'] import sys import numpy.core.numeric as _nx from numpy.core.numeric import ( asarray, ScalarType, array, alltrue, cumprod, arange ) from numpy.core.numerictypes import find_common_type import math from . import function_base import numpy.matrixlib as matrix from .function_base import diff from numpy.lib._compiled_base import ravel_multi_index, unravel_index from numpy.lib.stride_tricks import as_strided makemat = matrix.matrix def ix_(*args): """ Construct an open mesh from multiple sequences. This function takes N 1-D sequences and returns N outputs with N dimensions each, such that the shape is 1 in all but one dimension and the dimension with the non-unit shape value cycles through all N dimensions. Using `ix_` one can quickly construct index arrays that will index the cross product. ``a[np.ix_([1,3],[2,5])]`` returns the array ``[[a[1,2] a[1,5]], [a[3,2] a[3,5]]]``. Parameters ---------- args : 1-D sequences Returns ------- out : tuple of ndarrays N arrays with N dimensions each, with N the number of input sequences. Together these arrays form an open mesh. See Also -------- ogrid, mgrid, meshgrid Examples -------- >>> a = np.arange(10).reshape(2, 5) >>> a array([[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]) >>> ixgrid = np.ix_([0,1], [2,4]) >>> ixgrid (array([[0], [1]]), array([[2, 4]])) >>> ixgrid[0].shape, ixgrid[1].shape ((2, 1), (1, 2)) >>> a[ixgrid] array([[2, 4], [7, 9]]) """ out = [] nd = len(args) baseshape = [1]*nd for k in range(nd): new = _nx.asarray(args[k]) if (new.ndim != 1): raise ValueError("Cross index must be 1 dimensional") if issubclass(new.dtype.type, _nx.bool_): new = new.nonzero()[0] baseshape[k] = len(new) new = new.reshape(tuple(baseshape)) out.append(new) baseshape[k] = 1 return tuple(out) class nd_grid(object): """ Construct a multi-dimensional "meshgrid". ``grid = nd_grid()`` creates an instance which will return a mesh-grid when indexed. The dimension and number of the output arrays are equal to the number of indexing dimensions. If the step length is not a complex number, then the stop is not inclusive. However, if the step length is a **complex number** (e.g. 5j), then the integer part of its magnitude is interpreted as specifying the number of points to create between the start and stop values, where the stop value **is inclusive**. If instantiated with an argument of ``sparse=True``, the mesh-grid is open (or not fleshed out) so that only one-dimension of each returned argument is greater than 1. Parameters ---------- sparse : bool, optional Whether the grid is sparse or not. Default is False. Notes ----- Two instances of `nd_grid` are made available in the NumPy namespace, `mgrid` and `ogrid`:: mgrid = nd_grid(sparse=False) ogrid = nd_grid(sparse=True) Users should use these pre-defined instances instead of using `nd_grid` directly. Examples -------- >>> mgrid = np.lib.index_tricks.nd_grid() >>> mgrid[0:5,0:5] array([[[0, 0, 0, 0, 0], [1, 1, 1, 1, 1], [2, 2, 2, 2, 2], [3, 3, 3, 3, 3], [4, 4, 4, 4, 4]], [[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]]) >>> mgrid[-1:1:5j] array([-1. , -0.5, 0. , 0.5, 1. ]) >>> ogrid = np.lib.index_tricks.nd_grid(sparse=True) >>> ogrid[0:5,0:5] [array([[0], [1], [2], [3], [4]]), array([[0, 1, 2, 3, 4]])] """ def __init__(self, sparse=False): self.sparse = sparse def __getitem__(self, key): try: size = [] typ = int for k in range(len(key)): step = key[k].step start = key[k].start if start is None: start=0 if step is None: step=1 if isinstance(step, complex): size.append(int(abs(step))) typ = float else: size.append(int(math.ceil((key[k].stop - start)/(step*1.0)))) if isinstance(step, float) or \ isinstance(start, float) or \ isinstance(key[k].stop, float): typ = float if self.sparse: nn = [_nx.arange(_x, dtype=_t) for _x, _t in zip(size, (typ,)*len(size))] else: nn = _nx.indices(size, typ) for k in range(len(size)): step = key[k].step start = key[k].start if start is None: start=0 if step is None: step=1 if isinstance(step, complex): step = int(abs(step)) if step != 1: step = (key[k].stop - start)/float(step-1) nn[k] = (nn[k]*step+start) if self.sparse: slobj = [_nx.newaxis]*len(size) for k in range(len(size)): slobj[k] = slice(None, None) nn[k] = nn[k][slobj] slobj[k] = _nx.newaxis return nn except (IndexError, TypeError): step = key.step stop = key.stop start = key.start if start is None: start = 0 if isinstance(step, complex): step = abs(step) length = int(step) if step != 1: step = (key.stop-start)/float(step-1) stop = key.stop+step return _nx.arange(0, length, 1, float)*step + start else: return _nx.arange(start, stop, step) def __getslice__(self, i, j): return _nx.arange(i, j) def __len__(self): return 0 mgrid = nd_grid(sparse=False) ogrid = nd_grid(sparse=True) mgrid.__doc__ = None # set in numpy.add_newdocs ogrid.__doc__ = None # set in numpy.add_newdocs class AxisConcatenator(object): """ Translates slice objects to concatenation along an axis. For detailed documentation on usage, see `r_`. """ def _retval(self, res): if self.matrix: oldndim = res.ndim res = makemat(res) if oldndim == 1 and self.col: res = res.T self.axis = self._axis self.matrix = self._matrix self.col = 0 return res def __init__(self, axis=0, matrix=False, ndmin=1, trans1d=-1): self._axis = axis self._matrix = matrix self.axis = axis self.matrix = matrix self.col = 0 self.trans1d = trans1d self.ndmin = ndmin def __getitem__(self, key): trans1d = self.trans1d ndmin = self.ndmin if isinstance(key, str): frame = sys._getframe().f_back mymat = matrix.bmat(key, frame.f_globals, frame.f_locals) return mymat if not isinstance(key, tuple): key = (key,) objs = [] scalars = [] arraytypes = [] scalartypes = [] for k in range(len(key)): scalar = False if isinstance(key[k], slice): step = key[k].step start = key[k].start stop = key[k].stop if start is None: start = 0 if step is None: step = 1 if isinstance(step, complex): size = int(abs(step)) newobj = function_base.linspace(start, stop, num=size) else: newobj = _nx.arange(start, stop, step) if ndmin > 1: newobj = array(newobj, copy=False, ndmin=ndmin) if trans1d != -1: newobj = newobj.swapaxes(-1, trans1d) elif isinstance(key[k], str): if k != 0: raise ValueError("special directives must be the " "first entry.") key0 = key[0] if key0 in 'rc': self.matrix = True self.col = (key0 == 'c') continue if ',' in key0: vec = key0.split(',') try: self.axis, ndmin = \ [int(x) for x in vec[:2]] if len(vec) == 3: trans1d = int(vec[2]) continue except: raise ValueError("unknown special directive") try: self.axis = int(key[k]) continue except (ValueError, TypeError): raise ValueError("unknown special directive") elif type(key[k]) in ScalarType: newobj = array(key[k], ndmin=ndmin) scalars.append(k) scalar = True scalartypes.append(newobj.dtype) else: newobj = key[k] if ndmin > 1: tempobj = array(newobj, copy=False, subok=True) newobj = array(newobj, copy=False, subok=True, ndmin=ndmin) if trans1d != -1 and tempobj.ndim < ndmin: k2 = ndmin-tempobj.ndim if (trans1d < 0): trans1d += k2 + 1 defaxes = list(range(ndmin)) k1 = trans1d axes = defaxes[:k1] + defaxes[k2:] + \ defaxes[k1:k2] newobj = newobj.transpose(axes) del tempobj objs.append(newobj) if not scalar and isinstance(newobj, _nx.ndarray): arraytypes.append(newobj.dtype) # Esure that scalars won't up-cast unless warranted final_dtype = find_common_type(arraytypes, scalartypes) if final_dtype is not None: for k in scalars: objs[k] = objs[k].astype(final_dtype) res = _nx.concatenate(tuple(objs), axis=self.axis) return self._retval(res) def __getslice__(self, i, j): res = _nx.arange(i, j) return self._retval(res) def __len__(self): return 0 # separate classes are used here instead of just making r_ = concatentor(0), # etc. because otherwise we couldn't get the doc string to come out right # in help(r_) class RClass(AxisConcatenator): """ Translates slice objects to concatenation along the first axis. This is a simple way to build up arrays quickly. There are two use cases. 1. If the index expression contains comma separated arrays, then stack them along their first axis. 2. If the index expression contains slice notation or scalars then create a 1-D array with a range indicated by the slice notation. If slice notation is used, the syntax ``start:stop:step`` is equivalent to ``np.arange(start, stop, step)`` inside of the brackets. However, if ``step`` is an imaginary number (i.e. 100j) then its integer portion is interpreted as a number-of-points desired and the start and stop are inclusive. In other words ``start:stop:stepj`` is interpreted as ``np.linspace(start, stop, step, endpoint=1)`` inside of the brackets. After expansion of slice notation, all comma separated sequences are concatenated together. Optional character strings placed as the first element of the index expression can be used to change the output. The strings 'r' or 'c' result in matrix output. If the result is 1-D and 'r' is specified a 1 x N (row) matrix is produced. If the result is 1-D and 'c' is specified, then a N x 1 (column) matrix is produced. If the result is 2-D then both provide the same matrix result. A string integer specifies which axis to stack multiple comma separated arrays along. A string of two comma-separated integers allows indication of the minimum number of dimensions to force each entry into as the second integer (the axis to concatenate along is still the first integer). A string with three comma-separated integers allows specification of the axis to concatenate along, the minimum number of dimensions to force the entries to, and which axis should contain the start of the arrays which are less than the specified number of dimensions. In other words the third integer allows you to specify where the 1's should be placed in the shape of the arrays that have their shapes upgraded. By default, they are placed in the front of the shape tuple. The third argument allows you to specify where the start of the array should be instead. Thus, a third argument of '0' would place the 1's at the end of the array shape. Negative integers specify where in the new shape tuple the last dimension of upgraded arrays should be placed, so the default is '-1'. Parameters ---------- Not a function, so takes no parameters Returns ------- A concatenated ndarray or matrix. See Also -------- concatenate : Join a sequence of arrays together. c_ : Translates slice objects to concatenation along the second axis. Examples -------- >>> np.r_[np.array([1,2,3]), 0, 0, np.array([4,5,6])] array([1, 2, 3, 0, 0, 4, 5, 6]) >>> np.r_[-1:1:6j, [0]*3, 5, 6] array([-1. , -0.6, -0.2, 0.2, 0.6, 1. , 0. , 0. , 0. , 5. , 6. ]) String integers specify the axis to concatenate along or the minimum number of dimensions to force entries into. >>> a = np.array([[0, 1, 2], [3, 4, 5]]) >>> np.r_['-1', a, a] # concatenate along last axis array([[0, 1, 2, 0, 1, 2], [3, 4, 5, 3, 4, 5]]) >>> np.r_['0,2', [1,2,3], [4,5,6]] # concatenate along first axis, dim>=2 array([[1, 2, 3], [4, 5, 6]]) >>> np.r_['0,2,0', [1,2,3], [4,5,6]] array([[1], [2], [3], [4], [5], [6]]) >>> np.r_['1,2,0', [1,2,3], [4,5,6]] array([[1, 4], [2, 5], [3, 6]]) Using 'r' or 'c' as a first string argument creates a matrix. >>> np.r_['r',[1,2,3], [4,5,6]] matrix([[1, 2, 3, 4, 5, 6]]) """ def __init__(self): AxisConcatenator.__init__(self, 0) r_ = RClass() class CClass(AxisConcatenator): """ Translates slice objects to concatenation along the second axis. This is short-hand for ``np.r_['-1,2,0', index expression]``, which is useful because of its common occurrence. In particular, arrays will be stacked along their last axis after being upgraded to at least 2-D with 1's post-pended to the shape (column vectors made out of 1-D arrays). For detailed documentation, see `r_`. Examples -------- >>> np.c_[np.array([[1,2,3]]), 0, 0, np.array([[4,5,6]])] array([[1, 2, 3, 0, 0, 4, 5, 6]]) """ def __init__(self): AxisConcatenator.__init__(self, -1, ndmin=2, trans1d=0) c_ = CClass() class ndenumerate(object): """ Multidimensional index iterator. Return an iterator yielding pairs of array coordinates and values. Parameters ---------- a : ndarray Input array. See Also -------- ndindex, flatiter Examples -------- >>> a = np.array([[1, 2], [3, 4]]) >>> for index, x in np.ndenumerate(a): ... print index, x (0, 0) 1 (0, 1) 2 (1, 0) 3 (1, 1) 4 """ def __init__(self, arr): self.iter = asarray(arr).flat def __next__(self): """ Standard iterator method, returns the index tuple and array value. Returns ------- coords : tuple of ints The indices of the current iteration. val : scalar The array element of the current iteration. """ return self.iter.coords, next(self.iter) def __iter__(self): return self next = __next__ class ndindex(object): """ An N-dimensional iterator object to index arrays. Given the shape of an array, an `ndindex` instance iterates over the N-dimensional index of the array. At each iteration a tuple of indices is returned, the last dimension is iterated over first. Parameters ---------- `*args` : ints The size of each dimension of the array. See Also -------- ndenumerate, flatiter Examples -------- >>> for index in np.ndindex(3, 2, 1): ... print index (0, 0, 0) (0, 1, 0) (1, 0, 0) (1, 1, 0) (2, 0, 0) (2, 1, 0) """ def __init__(self, *shape): if len(shape) == 1 and isinstance(shape[0], tuple): shape = shape[0] x = as_strided(_nx.zeros(1), shape=shape, strides=_nx.zeros_like(shape)) self._it = _nx.nditer(x, flags=['multi_index', 'zerosize_ok'], order='C') def __iter__(self): return self def ndincr(self): """ Increment the multi-dimensional index by one. This method is for backward compatibility only: do not use. """ next(self) def __next__(self): """ Standard iterator method, updates the index and returns the index tuple. Returns ------- val : tuple of ints Returns a tuple containing the indices of the current iteration. """ next(self._it) return self._it.multi_index next = __next__ # You can do all this with slice() plus a few special objects, # but there's a lot to remember. This version is simpler because # it uses the standard array indexing syntax. # # Written by Konrad Hinsen # last revision: 1999-7-23 # # Cosmetic changes by T. Oliphant 2001 # # class IndexExpression(object): """ A nicer way to build up index tuples for arrays. .. note:: Use one of the two predefined instances `index_exp` or `s_` rather than directly using `IndexExpression`. For any index combination, including slicing and axis insertion, ``a[indices]`` is the same as ``a[np.index_exp[indices]]`` for any array `a`. However, ``np.index_exp[indices]`` can be used anywhere in Python code and returns a tuple of slice objects that can be used in the construction of complex index expressions. Parameters ---------- maketuple : bool If True, always returns a tuple. See Also -------- index_exp : Predefined instance that always returns a tuple: `index_exp = IndexExpression(maketuple=True)`. s_ : Predefined instance without tuple conversion: `s_ = IndexExpression(maketuple=False)`. Notes ----- You can do all this with `slice()` plus a few special objects, but there's a lot to remember and this version is simpler because it uses the standard array indexing syntax. Examples -------- >>> np.s_[2::2] slice(2, None, 2) >>> np.index_exp[2::2] (slice(2, None, 2),) >>> np.array([0, 1, 2, 3, 4])[np.s_[2::2]] array([2, 4]) """ def __init__(self, maketuple): self.maketuple = maketuple def __getitem__(self, item): if self.maketuple and not isinstance(item, tuple): return (item,) else: return item index_exp = IndexExpression(maketuple=True) s_ = IndexExpression(maketuple=False) # End contribution from Konrad. # The following functions complement those in twodim_base, but are # applicable to N-dimensions. def fill_diagonal(a, val, wrap=False): """Fill the main diagonal of the given array of any dimensionality. For an array `a` with ``a.ndim > 2``, the diagonal is the list of locations with indices ``a[i, i, ..., i]`` all identical. This function modifies the input array in-place, it does not return a value. Parameters ---------- a : array, at least 2-D. Array whose diagonal is to be filled, it gets modified in-place. val : scalar Value to be written on the diagonal, its type must be compatible with that of the array a. wrap : bool For tall matrices in NumPy version up to 1.6.2, the diagonal "wrapped" after N columns. You can have this behavior with this option. This affect only tall matrices. See also -------- diag_indices, diag_indices_from Notes ----- .. versionadded:: 1.4.0 This functionality can be obtained via `diag_indices`, but internally this version uses a much faster implementation that never constructs the indices and uses simple slicing. Examples -------- >>> a = np.zeros((3, 3), int) >>> np.fill_diagonal(a, 5) >>> a array([[5, 0, 0], [0, 5, 0], [0, 0, 5]]) The same function can operate on a 4-D array: >>> a = np.zeros((3, 3, 3, 3), int) >>> np.fill_diagonal(a, 4) We only show a few blocks for clarity: >>> a[0, 0] array([[4, 0, 0], [0, 0, 0], [0, 0, 0]]) >>> a[1, 1] array([[0, 0, 0], [0, 4, 0], [0, 0, 0]]) >>> a[2, 2] array([[0, 0, 0], [0, 0, 0], [0, 0, 4]]) # tall matrices no wrap >>> a = np.zeros((5, 3),int) >>> fill_diagonal(a, 4) array([[4, 0, 0], [0, 4, 0], [0, 0, 4], [0, 0, 0], [0, 0, 0]]) # tall matrices wrap >>> a = np.zeros((5, 3),int) >>> fill_diagonal(a, 4) array([[4, 0, 0], [0, 4, 0], [0, 0, 4], [0, 0, 0], [4, 0, 0]]) # wide matrices >>> a = np.zeros((3, 5),int) >>> fill_diagonal(a, 4) array([[4, 0, 0, 0, 0], [0, 4, 0, 0, 0], [0, 0, 4, 0, 0]]) """ if a.ndim < 2: raise ValueError("array must be at least 2-d") end = None if a.ndim == 2: # Explicit, fast formula for the common case. For 2-d arrays, we # accept rectangular ones. step = a.shape[1] + 1 #This is needed to don't have tall matrix have the diagonal wrap. if not wrap: end = a.shape[1] * a.shape[1] else: # For more than d=2, the strided formula is only valid for arrays with # all dimensions equal, so we check first. if not alltrue(diff(a.shape)==0): raise ValueError("All dimensions of input must be of equal length") step = 1 + (cumprod(a.shape[:-1])).sum() # Write the value out into the diagonal. a.flat[:end:step] = val def diag_indices(n, ndim=2): """ Return the indices to access the main diagonal of an array. This returns a tuple of indices that can be used to access the main diagonal of an array `a` with ``a.ndim >= 2`` dimensions and shape (n, n, ..., n). For ``a.ndim = 2`` this is the usual diagonal, for ``a.ndim > 2`` this is the set of indices to access ``a[i, i, ..., i]`` for ``i = [0..n-1]``. Parameters ---------- n : int The size, along each dimension, of the arrays for which the returned indices can be used. ndim : int, optional The number of dimensions. See also -------- diag_indices_from Notes ----- .. versionadded:: 1.4.0 Examples -------- Create a set of indices to access the diagonal of a (4, 4) array: >>> di = np.diag_indices(4) >>> di (array([0, 1, 2, 3]), array([0, 1, 2, 3])) >>> a = np.arange(16).reshape(4, 4) >>> a array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11], [12, 13, 14, 15]]) >>> a[di] = 100 >>> a array([[100, 1, 2, 3], [ 4, 100, 6, 7], [ 8, 9, 100, 11], [ 12, 13, 14, 100]]) Now, we create indices to manipulate a 3-D array: >>> d3 = np.diag_indices(2, 3) >>> d3 (array([0, 1]), array([0, 1]), array([0, 1])) And use it to set the diagonal of an array of zeros to 1: >>> a = np.zeros((2, 2, 2), dtype=np.int) >>> a[d3] = 1 >>> a array([[[1, 0], [0, 0]], [[0, 0], [0, 1]]]) """ idx = arange(n) return (idx,) * ndim def diag_indices_from(arr): """ Return the indices to access the main diagonal of an n-dimensional array. See `diag_indices` for full details. Parameters ---------- arr : array, at least 2-D See Also -------- diag_indices Notes ----- .. versionadded:: 1.4.0 """ if not arr.ndim >= 2: raise ValueError("input array must be at least 2-d") # For more than d=2, the strided formula is only valid for arrays with # all dimensions equal, so we check first. if not alltrue(diff(arr.shape) == 0): raise ValueError("All dimensions of input must be of equal length") return diag_indices(arr.shape[0], arr.ndim) numpy-1.8.2/numpy/lib/setup.py0000664000175100017510000000120212370216243017447 0ustar vagrantvagrant00000000000000from __future__ import division, print_function from os.path import join def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('lib', parent_package, top_path) config.add_include_dirs(join('..', 'core', 'include')) config.add_extension('_compiled_base', sources=[join('src', '_compiled_base.c')] ) config.add_data_dir('benchmarks') config.add_data_dir('tests') return config if __name__=='__main__': from numpy.distutils.core import setup setup(configuration=configuration) numpy-1.8.2/numpy/lib/user_array.py0000664000175100017510000001674112370216243020501 0ustar vagrantvagrant00000000000000""" Standard container-class for easy multiple-inheritance. Try to inherit from the ndarray instead of using this class as this is not complete. """ from __future__ import division, absolute_import, print_function from numpy.core import ( array, asarray, absolute, add, subtract, multiply, divide, remainder, power, left_shift, right_shift, bitwise_and, bitwise_or, bitwise_xor, invert, less, less_equal, not_equal, equal, greater, greater_equal, shape, reshape, arange, sin, sqrt, transpose ) from numpy.compat import long class container(object): def __init__(self, data, dtype=None, copy=True): self.array = array(data, dtype, copy=copy) def __repr__(self): if len(self.shape) > 0: return self.__class__.__name__+repr(self.array)[len("array"):] else: return self.__class__.__name__+"("+repr(self.array)+")" def __array__(self,t=None): if t: return self.array.astype(t) return self.array # Array as sequence def __len__(self): return len(self.array) def __getitem__(self, index): return self._rc(self.array[index]) def __getslice__(self, i, j): return self._rc(self.array[i:j]) def __setitem__(self, index, value): self.array[index] = asarray(value, self.dtype) def __setslice__(self, i, j, value): self.array[i:j] = asarray(value, self.dtype) def __abs__(self): return self._rc(absolute(self.array)) def __neg__(self): return self._rc(-self.array) def __add__(self, other): return self._rc(self.array+asarray(other)) __radd__ = __add__ def __iadd__(self, other): add(self.array, other, self.array) return self def __sub__(self, other): return self._rc(self.array-asarray(other)) def __rsub__(self, other): return self._rc(asarray(other)-self.array) def __isub__(self, other): subtract(self.array, other, self.array) return self def __mul__(self, other): return self._rc(multiply(self.array, asarray(other))) __rmul__ = __mul__ def __imul__(self, other): multiply(self.array, other, self.array) return self def __div__(self, other): return self._rc(divide(self.array, asarray(other))) def __rdiv__(self, other): return self._rc(divide(asarray(other), self.array)) def __idiv__(self, other): divide(self.array, other, self.array) return self def __mod__(self, other): return self._rc(remainder(self.array, other)) def __rmod__(self, other): return self._rc(remainder(other, self.array)) def __imod__(self, other): remainder(self.array, other, self.array) return self def __divmod__(self, other): return (self._rc(divide(self.array, other)), self._rc(remainder(self.array, other))) def __rdivmod__(self, other): return (self._rc(divide(other, self.array)), self._rc(remainder(other, self.array))) def __pow__(self, other): return self._rc(power(self.array, asarray(other))) def __rpow__(self, other): return self._rc(power(asarray(other), self.array)) def __ipow__(self, other): power(self.array, other, self.array) return self def __lshift__(self, other): return self._rc(left_shift(self.array, other)) def __rshift__(self, other): return self._rc(right_shift(self.array, other)) def __rlshift__(self, other): return self._rc(left_shift(other, self.array)) def __rrshift__(self, other): return self._rc(right_shift(other, self.array)) def __ilshift__(self, other): left_shift(self.array, other, self.array) return self def __irshift__(self, other): right_shift(self.array, other, self.array) return self def __and__(self, other): return self._rc(bitwise_and(self.array, other)) def __rand__(self, other): return self._rc(bitwise_and(other, self.array)) def __iand__(self, other): bitwise_and(self.array, other, self.array) return self def __xor__(self, other): return self._rc(bitwise_xor(self.array, other)) def __rxor__(self, other): return self._rc(bitwise_xor(other, self.array)) def __ixor__(self, other): bitwise_xor(self.array, other, self.array) return self def __or__(self, other): return self._rc(bitwise_or(self.array, other)) def __ror__(self, other): return self._rc(bitwise_or(other, self.array)) def __ior__(self, other): bitwise_or(self.array, other, self.array) return self def __neg__(self): return self._rc(-self.array) def __pos__(self): return self._rc(self.array) def __abs__(self): return self._rc(abs(self.array)) def __invert__(self): return self._rc(invert(self.array)) def _scalarfunc(self, func): if len(self.shape) == 0: return func(self[0]) else: raise TypeError("only rank-0 arrays can be converted to Python scalars.") def __complex__(self): return self._scalarfunc(complex) def __float__(self): return self._scalarfunc(float) def __int__(self): return self._scalarfunc(int) def __long__(self): return self._scalarfunc(long) def __hex__(self): return self._scalarfunc(hex) def __oct__(self): return self._scalarfunc(oct) def __lt__(self, other): return self._rc(less(self.array, other)) def __le__(self, other): return self._rc(less_equal(self.array, other)) def __eq__(self, other): return self._rc(equal(self.array, other)) def __ne__(self, other): return self._rc(not_equal(self.array, other)) def __gt__(self, other): return self._rc(greater(self.array, other)) def __ge__(self, other): return self._rc(greater_equal(self.array, other)) def copy(self): return self._rc(self.array.copy()) def tostring(self): return self.array.tostring() def byteswap(self): return self._rc(self.array.byteswap()) def astype(self, typecode): return self._rc(self.array.astype(typecode)) def _rc(self, a): if len(shape(a)) == 0: return a else: return self.__class__(a) def __array_wrap__(self, *args): return self.__class__(args[0]) def __setattr__(self, attr, value): if attr == 'array': object.__setattr__(self, attr, value) return try: self.array.__setattr__(attr, value) except AttributeError: object.__setattr__(self, attr, value) # Only called after other approaches fail. def __getattr__(self, attr): if (attr == 'array'): return object.__getattribute__(self, attr) return self.array.__getattribute__(attr) ############################################################# # Test of class container ############################################################# if __name__ == '__main__': temp=reshape(arange(10000), (100, 100)) ua=container(temp) # new object created begin test print(dir(ua)) print(shape(ua), ua.shape) # I have changed Numeric.py ua_small=ua[:3, :5] print(ua_small) ua_small[0, 0]=10 # this did not change ua[0,0], which is not normal behavior print(ua_small[0, 0], ua[0, 0]) print(sin(ua_small)/3.*6.+sqrt(ua_small**2)) print(less(ua_small, 103), type(less(ua_small, 103))) print(type(ua_small*reshape(arange(15), shape(ua_small)))) print(reshape(ua_small, (5, 3))) print(transpose(ua_small)) numpy-1.8.2/numpy/lib/tests/0000775000175100017510000000000012371375430017111 5ustar vagrantvagrant00000000000000numpy-1.8.2/numpy/lib/tests/test_ufunclike.py0000664000175100017510000000370712370216243022511 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function from numpy.testing import * import numpy.core as nx import numpy.lib.ufunclike as ufl from numpy.testing.decorators import deprecated class TestUfunclike(TestCase): def test_isposinf(self): a = nx.array([nx.inf, -nx.inf, nx.nan, 0.0, 3.0, -3.0]) out = nx.zeros(a.shape, bool) tgt = nx.array([True, False, False, False, False, False]) res = ufl.isposinf(a) assert_equal(res, tgt) res = ufl.isposinf(a, out) assert_equal(res, tgt) assert_equal(out, tgt) def test_isneginf(self): a = nx.array([nx.inf, -nx.inf, nx.nan, 0.0, 3.0, -3.0]) out = nx.zeros(a.shape, bool) tgt = nx.array([False, True, False, False, False, False]) res = ufl.isneginf(a) assert_equal(res, tgt) res = ufl.isneginf(a, out) assert_equal(res, tgt) assert_equal(out, tgt) def test_fix(self): a = nx.array([[1.0, 1.1, 1.5, 1.8], [-1.0, -1.1, -1.5, -1.8]]) out = nx.zeros(a.shape, float) tgt = nx.array([[ 1., 1., 1., 1.], [-1., -1., -1., -1.]]) res = ufl.fix(a) assert_equal(res, tgt) res = ufl.fix(a, out) assert_equal(res, tgt) assert_equal(out, tgt) assert_equal(ufl.fix(3.14), 3) def test_fix_with_subclass(self): class MyArray(nx.ndarray): def __new__(cls, data, metadata=None): res = nx.array(data, copy=True).view(cls) res.metadata = metadata return res def __array_wrap__(self, obj, context=None): obj.metadata = self.metadata return obj a = nx.array([1.1, -1.1]) m = MyArray(a, metadata='foo') f = ufl.fix(m) assert_array_equal(f, nx.array([1, -1])) assert_(isinstance(f, MyArray)) assert_equal(f.metadata, 'foo') if __name__ == "__main__": run_module_suite() numpy-1.8.2/numpy/lib/tests/test_io.py0000664000175100017510000017233712370216243021141 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function import sys import gzip import os import threading import shutil import contextlib from tempfile import mkstemp, mkdtemp, NamedTemporaryFile import time import warnings import gc from io import BytesIO from datetime import datetime import numpy as np import numpy.ma as ma 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.testing import assert_warns, assert_, build_err_msg @contextlib.contextmanager def tempdir(change_dir=False): tmpdir = mkdtemp() yield tmpdir shutil.rmtree(tmpdir) class TextIO(BytesIO): """Helper IO class. Writes encode strings to bytes if needed, reads return bytes. This makes it easier to emulate files opened in binary mode without needing to explicitly convert strings to bytes in setting up the test data. """ def __init__(self, s=""): BytesIO.__init__(self, asbytes(s)) def write(self, s): BytesIO.write(self, asbytes(s)) def writelines(self, lines): BytesIO.writelines(self, [asbytes(s) for s in lines]) MAJVER, MINVER = sys.version_info[:2] IS_64BIT = sys.maxsize > 2**32 def strptime(s, fmt=None): """This function is available in the datetime module only from Python >= 2.5. """ if sys.version_info[0] >= 3: return datetime(*time.strptime(s.decode('latin1'), fmt)[:3]) else: return datetime(*time.strptime(s, fmt)[:3]) class RoundtripTest(object): def roundtrip(self, save_func, *args, **kwargs): """ save_func : callable Function used to save arrays to file. file_on_disk : bool If true, store the file on disk, instead of in a string buffer. save_kwds : dict Parameters passed to `save_func`. load_kwds : dict Parameters passed to `numpy.load`. args : tuple of arrays Arrays stored to file. """ save_kwds = kwargs.get('save_kwds', {}) load_kwds = kwargs.get('load_kwds', {}) 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() load_file = target_file.name else: target_file = BytesIO() load_file = target_file arr = args 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() arr_reloaded = np.load(load_file, **load_kwds) self.arr = arr self.arr_reloaded = arr_reloaded def test_array(self): a = np.array([[1, 2], [3, 4]], float) self.roundtrip(a) a = np.array([[1, 2], [3, 4]], int) self.roundtrip(a) a = np.array([[1 + 5j, 2 + 6j], [3 + 7j, 4 + 8j]], dtype=np.csingle) self.roundtrip(a) a = np.array([[1 + 5j, 2 + 6j], [3 + 7j, 4 + 8j]], dtype=np.cdouble) self.roundtrip(a) def test_1D(self): a = np.array([1, 2, 3, 4], int) self.roundtrip(a) @np.testing.dec.knownfailureif(sys.platform == 'win32', "Fail on Win32") def test_mmap(self): a = np.array([[1, 2.5], [4, 7.3]]) self.roundtrip(a, file_on_disk=True, load_kwds={'mmap_mode': 'r'}) def test_record(self): a = np.array([(1, 2), (3, 4)], dtype=[('x', 'i4'), ('y', 'i4')]) self.roundtrip(a) class TestSaveLoad(RoundtripTest, TestCase): def roundtrip(self, *args, **kwargs): RoundtripTest.roundtrip(self, np.save, *args, **kwargs) assert_equal(self.arr[0], self.arr_reloaded) class TestSavezLoad(RoundtripTest, TestCase): def roundtrip(self, *args, **kwargs): RoundtripTest.roundtrip(self, np.savez, *args, **kwargs) for n, arr in enumerate(self.arr): assert_equal(arr, self.arr_reloaded['arr_%d' % n]) @np.testing.dec.skipif(not IS_64BIT, "Works only with 64bit systems") @np.testing.dec.skipif(sys.platform == 'darwin', "Not yet working on Mac") @np.testing.dec.slow def test_big_arrays(self): L = (1 << 31) + 100000 a = np.empty(L, dtype=np.uint8) with tempdir() 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) b = np.array([[1 + 2j, 2 + 7j], [3 - 6j, 4 + 12j]], complex) self.roundtrip(a, b) def test_named_arrays(self): a = np.array([[1, 2], [3, 4]], float) b = np.array([[1 + 2j, 2 + 7j], [3 - 6j, 4 + 12j]], complex) c = BytesIO() np.savez(c, file_a=a, file_b=b) c.seek(0) l = np.load(c) assert_equal(a, l['file_a']) assert_equal(b, l['file_b']) def test_savez_filename_clashes(self): # Test that issue #852 is fixed # and savez functions in multithreaded environment def writer(error_list): fd, tmp = mkstemp(suffix='.npz') os.close(fd) try: arr = np.random.randn(500, 500) try: np.savez(tmp, arr=arr) except OSError as err: error_list.append(err) finally: os.remove(tmp) errors = [] threads = [threading.Thread(target=writer, args=(errors,)) for j in range(3)] for t in threads: t.start() for t in threads: t.join() if errors: raise AssertionError(errors) def test_not_closing_opened_fid(self): # Test that issue #2178 is fixed: # verify could seek on 'loaded' file fd, tmp = mkstemp(suffix='.npz') os.close(fd) try: fp = open(tmp, 'wb') np.savez(fp, data='LOVELY LOAD') fp.close() fp = open(tmp, 'rb', 10000) fp.seek(0) assert_(not fp.closed) _ = np.load(fp)['data'] assert_(not fp.closed) # must not get closed by .load(opened fp) fp.seek(0) assert_(not fp.closed) finally: fp.close() os.remove(tmp) def test_closing_fid(self): # Test that issue #1517 (too many opened files) remains closed # It might be a "weak" test since failed to get triggered on # e.g. Debian sid of 2012 Jul 05 but was reported to # trigger the failure on Ubuntu 10.04: # http://projects.scipy.org/numpy/ticket/1517#comment:2 fd, tmp = mkstemp(suffix='.npz') os.close(fd) try: fp = open(tmp, 'wb') np.savez(fp, data='LOVELY LOAD') fp.close() # We need to check if the garbage collector can properly close # numpy npz file returned by np.load when their reference count # goes to zero. Python 3 running in debug mode raises a # ResourceWarning when file closing is left to the garbage # collector, so we catch the warnings. Because ResourceWarning # is unknown in Python < 3.x, we take the easy way out and # catch all warnings. with warnings.catch_warnings(): warnings.simplefilter("ignore") for i in range(1, 1025): try: np.load(tmp)["data"] except Exception as e: msg = "Failed to load data from a file: %s" % e raise AssertionError(msg) finally: os.remove(tmp) def test_closing_zipfile_after_load(self): # 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) class TestSaveTxt(TestCase): def test_array(self): a = np.array([[1, 2], [3, 4]], float) fmt = "%.18e" c = BytesIO() np.savetxt(c, a, fmt=fmt) c.seek(0) assert_equal(c.readlines(), [asbytes((fmt + ' ' + fmt + '\n') % (1, 2)), asbytes((fmt + ' ' + fmt + '\n') % (3, 4))]) a = np.array([[1, 2], [3, 4]], int) c = BytesIO() np.savetxt(c, a, fmt='%d') c.seek(0) assert_equal(c.readlines(), [b'1 2\n', b'3 4\n']) def test_1D(self): a = np.array([1, 2, 3, 4], int) c = BytesIO() np.savetxt(c, a, fmt='%d') c.seek(0) lines = c.readlines() assert_equal(lines, [b'1\n', b'2\n', b'3\n', b'4\n']) def test_record(self): a = np.array([(1, 2), (3, 4)], dtype=[('x', 'i4'), ('y', 'i4')]) c = BytesIO() np.savetxt(c, a, fmt='%d') c.seek(0) assert_equal(c.readlines(), [b'1 2\n', b'3 4\n']) def test_delimiter(self): a = np.array([[1., 2.], [3., 4.]]) c = BytesIO() np.savetxt(c, a, delimiter=',', fmt='%d') c.seek(0) assert_equal(c.readlines(), [b'1,2\n', b'3,4\n']) def test_format(self): a = np.array([(1, 2), (3, 4)]) c = BytesIO() # Sequence of formats np.savetxt(c, a, fmt=['%02d', '%3.1f']) c.seek(0) assert_equal(c.readlines(), [b'01 2.0\n', b'03 4.0\n']) # A single multiformat string c = BytesIO() np.savetxt(c, a, fmt='%02d : %3.1f') c.seek(0) lines = c.readlines() assert_equal(lines, [b'01 : 2.0\n', b'03 : 4.0\n']) # Specify delimiter, should be overiden c = BytesIO() np.savetxt(c, a, fmt='%02d : %3.1f', delimiter=',') c.seek(0) lines = c.readlines() assert_equal(lines, [b'01 : 2.0\n', b'03 : 4.0\n']) # Bad fmt, should raise a ValueError c = BytesIO() assert_raises(ValueError, np.savetxt, c, a, fmt=99) def test_header_footer(self): """ Test the functionality of the header and footer keyword argument. """ c = BytesIO() a = np.array([(1, 2), (3, 4)], dtype=np.int) test_header_footer = 'Test header / footer' # Test the header keyword argument np.savetxt(c, a, fmt='%1d', header=test_header_footer) c.seek(0) assert_equal(c.read(), asbytes('# ' + test_header_footer + '\n1 2\n3 4\n')) # Test the footer keyword argument c = BytesIO() np.savetxt(c, a, fmt='%1d', footer=test_header_footer) c.seek(0) assert_equal(c.read(), asbytes('1 2\n3 4\n# ' + test_header_footer + '\n')) # Test the commentstr keyword argument used on the header c = BytesIO() commentstr = '% ' np.savetxt(c, a, fmt='%1d', header=test_header_footer, comments=commentstr) c.seek(0) assert_equal(c.read(), asbytes(commentstr + test_header_footer + '\n' + '1 2\n3 4\n')) # Test the commentstr keyword argument used on the footer c = BytesIO() commentstr = '% ' np.savetxt(c, a, fmt='%1d', footer=test_header_footer, comments=commentstr) c.seek(0) assert_equal(c.read(), asbytes('1 2\n3 4\n' + commentstr + test_header_footer + '\n')) def test_file_roundtrip(self): f, name = mkstemp() os.close(f) try: a = np.array([(1, 2), (3, 4)]) np.savetxt(name, a) b = np.loadtxt(name) assert_array_equal(a, b) finally: os.unlink(name) def test_complex_arrays(self): ncols = 2 nrows = 2 a = np.zeros((ncols, nrows), dtype=np.complex128) re = np.pi im = np.e a[:] = re + 1.0j * im # One format only c = BytesIO() np.savetxt(c, a, fmt=' %+.3e') c.seek(0) lines = c.readlines() _assert_floatstr_lines_equal(lines, [b' ( +3.142e+00+ +2.718e+00j) ( +3.142e+00+ +2.718e+00j)\n', b' ( +3.142e+00+ +2.718e+00j) ( +3.142e+00+ +2.718e+00j)\n']) # One format for each real and imaginary part c = BytesIO() np.savetxt(c, a, fmt=' %+.3e' * 2 * ncols) c.seek(0) lines = c.readlines() _assert_floatstr_lines_equal(lines, [b' +3.142e+00 +2.718e+00 +3.142e+00 +2.718e+00\n', b' +3.142e+00 +2.718e+00 +3.142e+00 +2.718e+00\n']) # One format for each complex number c = BytesIO() np.savetxt(c, a, fmt=['(%.3e%+.3ej)'] * ncols) c.seek(0) lines = c.readlines() _assert_floatstr_lines_equal(lines, [b'(3.142e+00+2.718e+00j) (3.142e+00+2.718e+00j)\n', b'(3.142e+00+2.718e+00j) (3.142e+00+2.718e+00j)\n']) def test_custom_writer(self): class CustomWriter(list): def write(self, text): self.extend(text.split(b'\n')) w = CustomWriter() a = np.array([(1, 2), (3, 4)]) np.savetxt(w, a) b = np.loadtxt(w) assert_array_equal(a, b) def _assert_floatstr_lines_equal(actual_lines, expected_lines): """A string comparison function that also works on Windows + Python 2.5. This is necessary because Python 2.5 on Windows inserts an extra 0 in the exponent of the string representation of floating point numbers. Only used in TestSaveTxt.test_complex_arrays, no attempt made to make this more generic. Once Python 2.5 compatibility is dropped, simply use `assert_equal` instead of this function. """ for actual, expected in zip(actual_lines, expected_lines): if actual != expected: expected_win25 = expected.replace("e+00", "e+000") if actual != expected_win25: msg = build_err_msg([actual, expected], '', verbose=True) raise AssertionError(msg) class TestLoadTxt(TestCase): def test_record(self): c = TextIO() c.write('1 2\n3 4') c.seek(0) x = np.loadtxt(c, dtype=[('x', np.int32), ('y', np.int32)]) a = np.array([(1, 2), (3, 4)], dtype=[('x', 'i4'), ('y', 'i4')]) assert_array_equal(x, a) d = TextIO() d.write('M 64.0 75.0\nF 25.0 60.0') d.seek(0) mydescriptor = {'names': ('gender', 'age', 'weight'), 'formats': ('S1', 'i4', 'f4')} b = np.array([('M', 64.0, 75.0), ('F', 25.0, 60.0)], dtype=mydescriptor) y = np.loadtxt(d, dtype=mydescriptor) assert_array_equal(y, b) def test_array(self): c = TextIO() c.write('1 2\n3 4') c.seek(0) x = np.loadtxt(c, dtype=int) a = np.array([[1, 2], [3, 4]], int) assert_array_equal(x, a) c.seek(0) x = np.loadtxt(c, dtype=float) a = np.array([[1, 2], [3, 4]], float) assert_array_equal(x, a) def test_1D(self): c = TextIO() c.write('1\n2\n3\n4\n') c.seek(0) x = np.loadtxt(c, dtype=int) a = np.array([1, 2, 3, 4], int) assert_array_equal(x, a) c = TextIO() c.write('1,2,3,4\n') c.seek(0) x = np.loadtxt(c, dtype=int, delimiter=',') a = np.array([1, 2, 3, 4], int) assert_array_equal(x, a) def test_missing(self): c = TextIO() c.write('1,2,3,,5\n') c.seek(0) x = np.loadtxt(c, dtype=int, delimiter=',', \ converters={3:lambda s: int(s or - 999)}) a = np.array([1, 2, 3, -999, 5], int) assert_array_equal(x, a) def test_converters_with_usecols(self): c = TextIO() c.write('1,2,3,,5\n6,7,8,9,10\n') c.seek(0) x = np.loadtxt(c, dtype=int, delimiter=',', \ converters={3:lambda s: int(s or - 999)}, \ usecols=(1, 3,)) a = np.array([[2, -999], [7, 9]], int) assert_array_equal(x, a) def test_comments(self): c = TextIO() c.write('# comment\n1,2,3,5\n') c.seek(0) x = np.loadtxt(c, dtype=int, delimiter=',', \ comments='#') a = np.array([1, 2, 3, 5], int) assert_array_equal(x, a) def test_skiprows(self): c = TextIO() c.write('comment\n1,2,3,5\n') c.seek(0) x = np.loadtxt(c, dtype=int, delimiter=',', \ skiprows=1) a = np.array([1, 2, 3, 5], int) assert_array_equal(x, a) c = TextIO() c.write('# comment\n1,2,3,5\n') c.seek(0) x = np.loadtxt(c, dtype=int, delimiter=',', \ skiprows=1) a = np.array([1, 2, 3, 5], int) assert_array_equal(x, a) def test_usecols(self): a = np.array([[1, 2], [3, 4]], float) c = BytesIO() np.savetxt(c, a) c.seek(0) x = np.loadtxt(c, dtype=float, usecols=(1,)) assert_array_equal(x, a[:, 1]) a = np.array([[1, 2, 3], [3, 4, 5]], float) c = BytesIO() np.savetxt(c, a) c.seek(0) x = np.loadtxt(c, dtype=float, usecols=(1, 2)) assert_array_equal(x, a[:, 1:]) # Testing with arrays instead of tuples. c.seek(0) x = np.loadtxt(c, dtype=float, usecols=np.array([1, 2])) assert_array_equal(x, a[:, 1:]) # Checking with dtypes defined converters. data = '''JOE 70.1 25.3 BOB 60.5 27.9 ''' c = TextIO(data) names = ['stid', 'temp'] dtypes = ['S4', 'f8'] arr = np.loadtxt(c, usecols=(0, 2), dtype=list(zip(names, dtypes))) assert_equal(arr['stid'], [b"JOE", b"BOB"]) assert_equal(arr['temp'], [25.3, 27.9]) def test_fancy_dtype(self): c = TextIO() c.write('1,2,3.0\n4,5,6.0\n') c.seek(0) dt = np.dtype([('x', int), ('y', [('t', int), ('s', float)])]) x = np.loadtxt(c, dtype=dt, delimiter=',') a = np.array([(1, (2, 3.0)), (4, (5, 6.0))], dt) assert_array_equal(x, a) def test_shaped_dtype(self): c = TextIO("aaaa 1.0 8.0 1 2 3 4 5 6") dt = np.dtype([('name', 'S4'), ('x', float), ('y', float), ('block', int, (2, 3))]) x = np.loadtxt(c, dtype=dt) a = np.array([('aaaa', 1.0, 8.0, [[1, 2, 3], [4, 5, 6]])], dtype=dt) assert_array_equal(x, a) def test_3d_shaped_dtype(self): c = TextIO("aaaa 1.0 8.0 1 2 3 4 5 6 7 8 9 10 11 12") dt = np.dtype([('name', 'S4'), ('x', float), ('y', float), ('block', int, (2, 2, 3))]) x = np.loadtxt(c, dtype=dt) a = np.array([('aaaa', 1.0, 8.0, [[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])], dtype=dt) assert_array_equal(x, a) def test_empty_file(self): with warnings.catch_warnings(): warnings.filterwarnings("ignore", message="loadtxt: Empty input file:") c = TextIO() x = np.loadtxt(c) assert_equal(x.shape, (0,)) x = np.loadtxt(c, dtype=np.int64) assert_equal(x.shape, (0,)) assert_(x.dtype == np.int64) def test_unused_converter(self): c = TextIO() c.writelines(['1 21\n', '3 42\n']) c.seek(0) data = np.loadtxt(c, usecols=(1,), converters={0: lambda s: int(s, 16)}) assert_array_equal(data, [21, 42]) c.seek(0) data = np.loadtxt(c, usecols=(1,), converters={1: lambda s: int(s, 16)}) assert_array_equal(data, [33, 66]) def test_dtype_with_object(self): "Test using an explicit dtype with an object" from datetime import date import time data = """ 1; 2001-01-01 2; 2002-01-31 """ ndtype = [('idx', int), ('code', np.object)] func = lambda s: strptime(s.strip(), "%Y-%m-%d") converters = {1: func} test = np.loadtxt(TextIO(data), delimiter=";", dtype=ndtype, converters=converters) control = np.array([(1, datetime(2001, 1, 1)), (2, datetime(2002, 1, 31))], dtype=ndtype) assert_equal(test, control) def test_uint64_type(self): tgt = (9223372043271415339, 9223372043271415853) c = TextIO() c.write("%s %s" % tgt) c.seek(0) res = np.loadtxt(c, dtype=np.uint64) assert_equal(res, tgt) def test_int64_type(self): tgt = (-9223372036854775807, 9223372036854775807) c = TextIO() c.write("%s %s" % tgt) c.seek(0) res = np.loadtxt(c, dtype=np.int64) assert_equal(res, tgt) def test_universal_newline(self): f, name = mkstemp() os.write(f, b'1 21\r3 42\r') os.close(f) try: data = np.loadtxt(name) assert_array_equal(data, [[1, 21], [3, 42]]) finally: os.unlink(name) def test_empty_field_after_tab(self): c = TextIO() c.write('1 \t2 \t3\tstart \n4\t5\t6\t \n7\t8\t9.5\t') c.seek(0) dt = { 'names': ('x', 'y', 'z', 'comment'), 'formats': ('= 3: # python 3k is known to fail for '\r' linesep = ('\n', '\r\n') else: linesep = ('\n', '\r\n', '\r') for sep in linesep: data = '0 1 2' + sep + '3 4 5' f, name = mkstemp() # We can't use NamedTemporaryFile on windows, because we cannot # reopen the file. try: os.write(f, asbytes(data)) assert_array_equal(np.genfromtxt(name), wanted) finally: os.close(f) os.unlink(name) def test_gft_using_generator(self): # gft doesn't work with unicode. def count(): for i in range(10): yield asbytes("%d" % i) res = np.genfromtxt(count()) assert_array_equal(res, np.arange(10)) def test_gzip_load(): a = np.random.random((5, 5)) s = BytesIO() f = gzip.GzipFile(fileobj=s, mode="w") np.save(f, a) f.close() s.seek(0) f = gzip.GzipFile(fileobj=s, mode="r") assert_array_equal(np.load(f), a) def test_gzip_loadtxt(): # Thanks to another windows brokeness, we can't use # NamedTemporaryFile: a file created from this function cannot be # reopened by another open call. So we first put the gzipped string # of the test reference array, write it to a securely opened file, # which is then read from by the loadtxt function s = BytesIO() g = gzip.GzipFile(fileobj=s, mode='w') g.write(b'1 2 3\n') g.close() s.seek(0) f, name = mkstemp(suffix='.gz') try: os.write(f, s.read()) s.close() assert_array_equal(np.loadtxt(name), [1, 2, 3]) finally: os.close(f) os.unlink(name) def test_gzip_loadtxt_from_string(): s = BytesIO() f = gzip.GzipFile(fileobj=s, mode="w") f.write(b'1 2 3\n') f.close() s.seek(0) f = gzip.GzipFile(fileobj=s, mode="r") assert_array_equal(np.loadtxt(f), [1, 2, 3]) def test_npzfile_dict(): s = BytesIO() x = np.zeros((3, 3)) y = np.zeros((3, 3)) np.savez(s, x=x, y=y) s.seek(0) z = np.load(s) assert_('x' in z) assert_('y' in z) assert_('x' in z.keys()) assert_('y' in z.keys()) for f, a in z.items(): assert_(f in ['x', 'y']) assert_equal(a.shape, (3, 3)) assert_(len(z.items()) == 2) for f in z: assert_(f in ['x', 'y']) assert_('x' in z.keys()) def test_load_refcount(): # Check that objects returned by np.load are directly freed based on # their refcount, rather than needing the gc to collect them. f = BytesIO() np.savez(f, [1, 2, 3]) f.seek(0) gc.collect() n_before = len(gc.get_objects()) np.load(f) n_after = len(gc.get_objects()) assert_equal(n_before, n_after) if __name__ == "__main__": run_module_suite() numpy-1.8.2/numpy/lib/tests/test_arraypad.py0000664000175100017510000006024512370216243022327 0ustar vagrantvagrant00000000000000"""Tests for the pad functions. """ from __future__ import division, absolute_import, print_function from numpy.testing import TestCase, run_module_suite, assert_array_equal from numpy.testing import assert_raises, assert_array_almost_equal import numpy as np from numpy.lib import pad class TestStatistic(TestCase): def test_check_mean_stat_length(self): a = np.arange(100).astype('f') a = pad(a, ((25, 20), ), 'mean', stat_length=((2, 3), )) b = np.array([ 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0., 1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11., 12., 13., 14., 15., 16., 17., 18., 19., 20., 21., 22., 23., 24., 25., 26., 27., 28., 29., 30., 31., 32., 33., 34., 35., 36., 37., 38., 39., 40., 41., 42., 43., 44., 45., 46., 47., 48., 49., 50., 51., 52., 53., 54., 55., 56., 57., 58., 59., 60., 61., 62., 63., 64., 65., 66., 67., 68., 69., 70., 71., 72., 73., 74., 75., 76., 77., 78., 79., 80., 81., 82., 83., 84., 85., 86., 87., 88., 89., 90., 91., 92., 93., 94., 95., 96., 97., 98., 99., 98., 98., 98., 98., 98., 98., 98., 98., 98., 98., 98., 98., 98., 98., 98., 98., 98., 98., 98., 98.]) assert_array_equal(a, b) def test_check_maximum_1(self): a = np.arange(100) a = pad(a, (25, 20), 'maximum') b = np.array([ 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99]) assert_array_equal(a, b) def test_check_maximum_2(self): a = np.arange(100) + 1 a = pad(a, (25, 20), 'maximum') b = np.array([ 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100]) assert_array_equal(a, b) def test_check_minimum_1(self): a = np.arange(100) a = pad(a, (25, 20), 'minimum') b = np.array([ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) assert_array_equal(a, b) def test_check_minimum_2(self): a = np.arange(100) + 2 a = pad(a, (25, 20), 'minimum') b = np.array([ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2]) assert_array_equal(a, b) def test_check_median(self): a = np.arange(100).astype('f') a = pad(a, (25, 20), 'median') b = np.array([ 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 0., 1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11., 12., 13., 14., 15., 16., 17., 18., 19., 20., 21., 22., 23., 24., 25., 26., 27., 28., 29., 30., 31., 32., 33., 34., 35., 36., 37., 38., 39., 40., 41., 42., 43., 44., 45., 46., 47., 48., 49., 50., 51., 52., 53., 54., 55., 56., 57., 58., 59., 60., 61., 62., 63., 64., 65., 66., 67., 68., 69., 70., 71., 72., 73., 74., 75., 76., 77., 78., 79., 80., 81., 82., 83., 84., 85., 86., 87., 88., 89., 90., 91., 92., 93., 94., 95., 96., 97., 98., 99., 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5]) assert_array_equal(a, b) def test_check_median_01(self): a = np.array([[3, 1, 4], [4, 5, 9], [9, 8, 2]]) a = pad(a, 1, 'median') b = np.array([ [4, 4, 5, 4, 4], [3, 3, 1, 4, 3], [5, 4, 5, 9, 5], [8, 9, 8, 2, 8], [4, 4, 5, 4, 4]]) assert_array_equal(a, b) def test_check_median_02(self): a = np.array([[3, 1, 4], [4, 5, 9], [9, 8, 2]]) a = pad(a.T, 1, 'median').T b = np.array([ [5, 4, 5, 4, 5], [3, 3, 1, 4, 3], [5, 4, 5, 9, 5], [8, 9, 8, 2, 8], [5, 4, 5, 4, 5]]) assert_array_equal(a, b) def test_check_mean_shape_one(self): a = [[4, 5, 6]] a = pad(a, (5, 7), 'mean', stat_length=2) b = np.array([ [4, 4, 4, 4, 4, 4, 5, 6, 6, 6, 6, 6, 6, 6, 6], [4, 4, 4, 4, 4, 4, 5, 6, 6, 6, 6, 6, 6, 6, 6], [4, 4, 4, 4, 4, 4, 5, 6, 6, 6, 6, 6, 6, 6, 6], [4, 4, 4, 4, 4, 4, 5, 6, 6, 6, 6, 6, 6, 6, 6], [4, 4, 4, 4, 4, 4, 5, 6, 6, 6, 6, 6, 6, 6, 6], [4, 4, 4, 4, 4, 4, 5, 6, 6, 6, 6, 6, 6, 6, 6], [4, 4, 4, 4, 4, 4, 5, 6, 6, 6, 6, 6, 6, 6, 6], [4, 4, 4, 4, 4, 4, 5, 6, 6, 6, 6, 6, 6, 6, 6], [4, 4, 4, 4, 4, 4, 5, 6, 6, 6, 6, 6, 6, 6, 6], [4, 4, 4, 4, 4, 4, 5, 6, 6, 6, 6, 6, 6, 6, 6], [4, 4, 4, 4, 4, 4, 5, 6, 6, 6, 6, 6, 6, 6, 6], [4, 4, 4, 4, 4, 4, 5, 6, 6, 6, 6, 6, 6, 6, 6], [4, 4, 4, 4, 4, 4, 5, 6, 6, 6, 6, 6, 6, 6, 6]]) assert_array_equal(a, b) def test_check_mean_2(self): a = np.arange(100).astype('f') a = pad(a, (25, 20), 'mean') b = np.array([ 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 0., 1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11., 12., 13., 14., 15., 16., 17., 18., 19., 20., 21., 22., 23., 24., 25., 26., 27., 28., 29., 30., 31., 32., 33., 34., 35., 36., 37., 38., 39., 40., 41., 42., 43., 44., 45., 46., 47., 48., 49., 50., 51., 52., 53., 54., 55., 56., 57., 58., 59., 60., 61., 62., 63., 64., 65., 66., 67., 68., 69., 70., 71., 72., 73., 74., 75., 76., 77., 78., 79., 80., 81., 82., 83., 84., 85., 86., 87., 88., 89., 90., 91., 92., 93., 94., 95., 96., 97., 98., 99., 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5]) assert_array_equal(a, b) class TestConstant(TestCase): def test_check_constant(self): a = np.arange(100) a = pad(a, (25, 20), 'constant', constant_values=(10, 20)) b = np.array([10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20]) assert_array_equal(a, b) class TestLinearRamp(TestCase): def test_check_simple(self): a = np.arange(100).astype('f') a = pad(a, (25, 20), 'linear_ramp', end_values=(4, 5)) b = np.array([ 4.00, 3.84, 3.68, 3.52, 3.36, 3.20, 3.04, 2.88, 2.72, 2.56, 2.40, 2.24, 2.08, 1.92, 1.76, 1.60, 1.44, 1.28, 1.12, 0.96, 0.80, 0.64, 0.48, 0.32, 0.16, 0.00, 1.00, 2.00, 3.00, 4.00, 5.00, 6.00, 7.00, 8.00, 9.00, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0, 20.0, 21.0, 22.0, 23.0, 24.0, 25.0, 26.0, 27.0, 28.0, 29.0, 30.0, 31.0, 32.0, 33.0, 34.0, 35.0, 36.0, 37.0, 38.0, 39.0, 40.0, 41.0, 42.0, 43.0, 44.0, 45.0, 46.0, 47.0, 48.0, 49.0, 50.0, 51.0, 52.0, 53.0, 54.0, 55.0, 56.0, 57.0, 58.0, 59.0, 60.0, 61.0, 62.0, 63.0, 64.0, 65.0, 66.0, 67.0, 68.0, 69.0, 70.0, 71.0, 72.0, 73.0, 74.0, 75.0, 76.0, 77.0, 78.0, 79.0, 80.0, 81.0, 82.0, 83.0, 84.0, 85.0, 86.0, 87.0, 88.0, 89.0, 90.0, 91.0, 92.0, 93.0, 94.0, 95.0, 96.0, 97.0, 98.0, 99.0, 94.3, 89.6, 84.9, 80.2, 75.5, 70.8, 66.1, 61.4, 56.7, 52.0, 47.3, 42.6, 37.9, 33.2, 28.5, 23.8, 19.1, 14.4, 9.7, 5.]) assert_array_almost_equal(a, b, decimal=5) class TestReflect(TestCase): def test_check_simple(self): a = np.arange(100) a = pad(a, (25, 20), 'reflect') b = np.array([ 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 98, 97, 96, 95, 94, 93, 92, 91, 90, 89, 88, 87, 86, 85, 84, 83, 82, 81, 80, 79]) assert_array_equal(a, b) def test_check_large_pad(self): a = [[4, 5, 6], [6, 7, 8]] a = pad(a, (5, 7), 'reflect') b = np.array([ [7, 6, 7, 8, 7, 6, 7, 8, 7, 6, 7, 8, 7, 6, 7], [5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5], [7, 6, 7, 8, 7, 6, 7, 8, 7, 6, 7, 8, 7, 6, 7], [5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5], [7, 6, 7, 8, 7, 6, 7, 8, 7, 6, 7, 8, 7, 6, 7], [5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5], [7, 6, 7, 8, 7, 6, 7, 8, 7, 6, 7, 8, 7, 6, 7], [5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5], [7, 6, 7, 8, 7, 6, 7, 8, 7, 6, 7, 8, 7, 6, 7], [5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5], [7, 6, 7, 8, 7, 6, 7, 8, 7, 6, 7, 8, 7, 6, 7], [5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5], [7, 6, 7, 8, 7, 6, 7, 8, 7, 6, 7, 8, 7, 6, 7], [5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5]]) assert_array_equal(a, b) def test_check_shape(self): a = [[4, 5, 6]] a = pad(a, (5, 7), 'reflect') b = np.array([ [5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5], [5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5], [5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5], [5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5], [5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5], [5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5], [5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5], [5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5], [5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5], [5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5], [5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5], [5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5], [5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5]]) assert_array_equal(a, b) def test_check_01(self): a = pad([1, 2, 3], 2, 'reflect') b = np.array([3, 2, 1, 2, 3, 2, 1]) assert_array_equal(a, b) def test_check_02(self): a = pad([1, 2, 3], 3, 'reflect') b = np.array([2, 3, 2, 1, 2, 3, 2, 1, 2]) assert_array_equal(a, b) def test_check_03(self): a = pad([1, 2, 3], 4, 'reflect') b = np.array([1, 2, 3, 2, 1, 2, 3, 2, 1, 2, 3]) assert_array_equal(a, b) class TestWrap(TestCase): def test_check_simple(self): a = np.arange(100) a = pad(a, (25, 20), 'wrap') b = np.array([ 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]) assert_array_equal(a, b) def test_check_large_pad(self): a = np.arange(12) a = np.reshape(a, (3, 4)) a = pad(a, (10, 12), 'wrap') b = np.array([ [10, 11, 8, 9, 10, 11, 8, 9, 10, 11, 8, 9, 10, 11, 8, 9, 10, 11, 8, 9, 10, 11, 8, 9, 10, 11], [2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3], [6, 7, 4, 5, 6, 7, 4, 5, 6, 7, 4, 5, 6, 7, 4, 5, 6, 7, 4, 5, 6, 7, 4, 5, 6, 7], [10, 11, 8, 9, 10, 11, 8, 9, 10, 11, 8, 9, 10, 11, 8, 9, 10, 11, 8, 9, 10, 11, 8, 9, 10, 11], [2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3], [6, 7, 4, 5, 6, 7, 4, 5, 6, 7, 4, 5, 6, 7, 4, 5, 6, 7, 4, 5, 6, 7, 4, 5, 6, 7], [10, 11, 8, 9, 10, 11, 8, 9, 10, 11, 8, 9, 10, 11, 8, 9, 10, 11, 8, 9, 10, 11, 8, 9, 10, 11], [2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3], [6, 7, 4, 5, 6, 7, 4, 5, 6, 7, 4, 5, 6, 7, 4, 5, 6, 7, 4, 5, 6, 7, 4, 5, 6, 7], [10, 11, 8, 9, 10, 11, 8, 9, 10, 11, 8, 9, 10, 11, 8, 9, 10, 11, 8, 9, 10, 11, 8, 9, 10, 11], [2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3], [6, 7, 4, 5, 6, 7, 4, 5, 6, 7, 4, 5, 6, 7, 4, 5, 6, 7, 4, 5, 6, 7, 4, 5, 6, 7], [10, 11, 8, 9, 10, 11, 8, 9, 10, 11, 8, 9, 10, 11, 8, 9, 10, 11, 8, 9, 10, 11, 8, 9, 10, 11], [2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3], [6, 7, 4, 5, 6, 7, 4, 5, 6, 7, 4, 5, 6, 7, 4, 5, 6, 7, 4, 5, 6, 7, 4, 5, 6, 7], [10, 11, 8, 9, 10, 11, 8, 9, 10, 11, 8, 9, 10, 11, 8, 9, 10, 11, 8, 9, 10, 11, 8, 9, 10, 11], [2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3], [6, 7, 4, 5, 6, 7, 4, 5, 6, 7, 4, 5, 6, 7, 4, 5, 6, 7, 4, 5, 6, 7, 4, 5, 6, 7], [10, 11, 8, 9, 10, 11, 8, 9, 10, 11, 8, 9, 10, 11, 8, 9, 10, 11, 8, 9, 10, 11, 8, 9, 10, 11], [2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3], [6, 7, 4, 5, 6, 7, 4, 5, 6, 7, 4, 5, 6, 7, 4, 5, 6, 7, 4, 5, 6, 7, 4, 5, 6, 7], [10, 11, 8, 9, 10, 11, 8, 9, 10, 11, 8, 9, 10, 11, 8, 9, 10, 11, 8, 9, 10, 11, 8, 9, 10, 11], [2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3], [6, 7, 4, 5, 6, 7, 4, 5, 6, 7, 4, 5, 6, 7, 4, 5, 6, 7, 4, 5, 6, 7, 4, 5, 6, 7], [10, 11, 8, 9, 10, 11, 8, 9, 10, 11, 8, 9, 10, 11, 8, 9, 10, 11, 8, 9, 10, 11, 8, 9, 10, 11]]) assert_array_equal(a, b) def test_check_01(self): a = pad([1, 2, 3], 3, 'wrap') b = np.array([1, 2, 3, 1, 2, 3, 1, 2, 3]) assert_array_equal(a, b) def test_check_02(self): a = pad([1, 2, 3], 4, 'wrap') b = np.array([3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1]) assert_array_equal(a, b) class TestStatLen(TestCase): def test_check_simple(self): a = np.arange(30) a = np.reshape(a, (6, 5)) a = pad(a, ((2, 3), (3, 2)), mode='mean', stat_length=(3,)) b = np.array([[6, 6, 6, 5, 6, 7, 8, 9, 8, 8], [6, 6, 6, 5, 6, 7, 8, 9, 8, 8], [1, 1, 1, 0, 1, 2, 3, 4, 3, 3], [6, 6, 6, 5, 6, 7, 8, 9, 8, 8], [11, 11, 11, 10, 11, 12, 13, 14, 13, 13], [16, 16, 16, 15, 16, 17, 18, 19, 18, 18], [21, 21, 21, 20, 21, 22, 23, 24, 23, 23], [26, 26, 26, 25, 26, 27, 28, 29, 28, 28], [21, 21, 21, 20, 21, 22, 23, 24, 23, 23], [21, 21, 21, 20, 21, 22, 23, 24, 23, 23], [21, 21, 21, 20, 21, 22, 23, 24, 23, 23]]) assert_array_equal(a, b) class TestEdge(TestCase): def test_check_simple(self): a = np.arange(12) a = np.reshape(a, (4, 3)) a = pad(a, ((2, 3), (3, 2)), 'edge' ) b = np.array([ [0, 0, 0, 0, 1, 2, 2, 2], [0, 0, 0, 0, 1, 2, 2, 2], [0, 0, 0, 0, 1, 2, 2, 2], [3, 3, 3, 3, 4, 5, 5, 5], [6, 6, 6, 6, 7, 8, 8, 8], [9, 9, 9, 9, 10, 11, 11, 11], [9, 9, 9, 9, 10, 11, 11, 11], [9, 9, 9, 9, 10, 11, 11, 11], [9, 9, 9, 9, 10, 11, 11, 11]]) assert_array_equal(a, b) class TestZeroPadWidth(TestCase): def test_zero_pad_width(self): arr = np.arange(30) arr = np.reshape(arr, (6, 5)) for pad_width in (0, (0, 0), ((0, 0), (0, 0))): assert_array_equal(arr, pad(arr, pad_width, mode='constant')) class ValueError1(TestCase): def test_check_simple(self): arr = np.arange(30) arr = np.reshape(arr, (6, 5)) kwargs = dict(mode='mean', stat_length=(3, )) assert_raises(ValueError, pad, arr, ((2, 3), (3, 2), (4, 5)), **kwargs) def test_check_negative_stat_length(self): arr = np.arange(30) arr = np.reshape(arr, (6, 5)) kwargs = dict(mode='mean', stat_length=(-3, )) assert_raises(ValueError, pad, arr, ((2, 3), (3, 2)), **kwargs) def test_check_negative_pad_width(self): arr = np.arange(30) arr = np.reshape(arr, (6, 5)) kwargs = dict(mode='mean', stat_length=(3, )) assert_raises(ValueError, pad, arr, ((-2, 3), (3, 2)), **kwargs) class ValueError2(TestCase): def test_check_simple(self): arr = np.arange(30) arr = np.reshape(arr, (6, 5)) kwargs = dict(mode='mean', stat_length=(3, )) assert_raises(ValueError, pad, arr, ((2, 3, 4), (3, 2)), **kwargs) class ValueError3(TestCase): def test_check_simple(self): arr = np.arange(30) arr = np.reshape(arr, (6, 5)) kwargs = dict(mode='mean', stat_length=(3, )) assert_raises(ValueError, pad, arr, ((-2, 3), (3, 2)), **kwargs) if __name__ == "__main__": run_module_suite() numpy-1.8.2/numpy/lib/tests/test_twodim_base.py0000664000175100017510000002732212370216243023020 0ustar vagrantvagrant00000000000000"""Test functions for matrix module """ from __future__ import division, absolute_import, print_function from numpy.testing import * from numpy import ( arange, rot90, add, fliplr, flipud, zeros, ones, eye, array, diag, histogram2d, tri, mask_indices, triu_indices, triu_indices_from, tril_indices, tril_indices_from ) import numpy as np from numpy.compat import asbytes, asbytes_nested def get_mat(n): data = arange(n) data = add.outer(data, data) return data class TestEye(TestCase): def test_basic(self): assert_equal(eye(4), array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]])) assert_equal(eye(4, dtype='f'), array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]], 'f')) assert_equal(eye(3) == 1, eye(3, dtype=bool)) def test_diag(self): assert_equal(eye(4, k=1), array([[0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1], [0, 0, 0, 0]])) assert_equal(eye(4, k=-1), array([[0, 0, 0, 0], [1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0]])) def test_2d(self): assert_equal(eye(4, 3), array([[1, 0, 0], [0, 1, 0], [0, 0, 1], [0, 0, 0]])) assert_equal(eye(3, 4), array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0]])) def test_diag2d(self): assert_equal(eye(3, 4, k=2), array([[0, 0, 1, 0], [0, 0, 0, 1], [0, 0, 0, 0]])) assert_equal(eye(4, 3, k=-2), array([[0, 0, 0], [0, 0, 0], [1, 0, 0], [0, 1, 0]])) def test_eye_bounds(self): assert_equal(eye(2, 2, 1), [[0, 1], [0, 0]]) assert_equal(eye(2, 2, -1), [[0, 0], [1, 0]]) assert_equal(eye(2, 2, 2), [[0, 0], [0, 0]]) assert_equal(eye(2, 2, -2), [[0, 0], [0, 0]]) assert_equal(eye(3, 2, 2), [[0, 0], [0, 0], [0, 0]]) assert_equal(eye(3, 2, 1), [[0, 1], [0, 0], [0, 0]]) assert_equal(eye(3, 2, -1), [[0, 0], [1, 0], [0, 1]]) assert_equal(eye(3, 2, -2), [[0, 0], [0, 0], [1, 0]]) assert_equal(eye(3, 2, -3), [[0, 0], [0, 0], [0, 0]]) def test_strings(self): assert_equal(eye(2, 2, dtype='S3'), asbytes_nested([['1', ''], ['', '1']])) def test_bool(self): assert_equal(eye(2, 2, dtype=bool), [[True, False], [False, True]]) class TestDiag(TestCase): def test_vector(self): vals = (100 * arange(5)).astype('l') b = zeros((5, 5)) for k in range(5): b[k, k] = vals[k] assert_equal(diag(vals), b) b = zeros((7, 7)) c = b.copy() for k in range(5): b[k, k + 2] = vals[k] c[k + 2, k] = vals[k] assert_equal(diag(vals, k=2), b) assert_equal(diag(vals, k=-2), c) def test_matrix(self, vals=None): if vals is None: vals = (100 * get_mat(5) + 1).astype('l') b = zeros((5,)) for k in range(5): b[k] = vals[k, k] assert_equal(diag(vals), b) b = b * 0 for k in range(3): b[k] = vals[k, k + 2] assert_equal(diag(vals, 2), b[:3]) for k in range(3): b[k] = vals[k + 2, k] assert_equal(diag(vals, -2), b[:3]) def test_fortran_order(self): vals = array((100 * get_mat(5) + 1), order='F', dtype='l') self.test_matrix(vals) def test_diag_bounds(self): A = [[1, 2], [3, 4], [5, 6]] assert_equal(diag(A, k=2), []) assert_equal(diag(A, k=1), [2]) assert_equal(diag(A, k=0), [1, 4]) assert_equal(diag(A, k=-1), [3, 6]) assert_equal(diag(A, k=-2), [5]) assert_equal(diag(A, k=-3), []) def test_failure(self): self.assertRaises(ValueError, diag, [[[1]]]) class TestFliplr(TestCase): def test_basic(self): self.assertRaises(ValueError, fliplr, ones(4)) a = get_mat(4) b = a[:, ::-1] assert_equal(fliplr(a), b) a = [[0, 1, 2], [3, 4, 5]] b = [[2, 1, 0], [5, 4, 3]] assert_equal(fliplr(a), b) class TestFlipud(TestCase): def test_basic(self): a = get_mat(4) b = a[::-1,:] assert_equal(flipud(a), b) a = [[0, 1, 2], [3, 4, 5]] b = [[3, 4, 5], [0, 1, 2]] assert_equal(flipud(a), b) class TestRot90(TestCase): def test_basic(self): self.assertRaises(ValueError, rot90, ones(4)) a = [[0, 1, 2], [3, 4, 5]] b1 = [[2, 5], [1, 4], [0, 3]] b2 = [[5, 4, 3], [2, 1, 0]] b3 = [[3, 0], [4, 1], [5, 2]] b4 = [[0, 1, 2], [3, 4, 5]] for k in range(-3, 13, 4): assert_equal(rot90(a, k=k), b1) for k in range(-2, 13, 4): assert_equal(rot90(a, k=k), b2) for k in range(-1, 13, 4): assert_equal(rot90(a, k=k), b3) for k in range(0, 13, 4): assert_equal(rot90(a, k=k), b4) def test_axes(self): a = ones((50, 40, 3)) assert_equal(rot90(a).shape, (40, 50, 3)) class TestHistogram2d(TestCase): def test_simple(self): x = array([ 0.41702200, 0.72032449, 0.00011437481, 0.302332573, 0.146755891]) y = array([ 0.09233859, 0.18626021, 0.34556073, 0.39676747, 0.53881673]) xedges = np.linspace(0, 1, 10) yedges = np.linspace(0, 1, 10) H = histogram2d(x, y, (xedges, yedges))[0] answer = array([[0, 0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 1, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0]]) assert_array_equal(H.T, answer) H = histogram2d(x, y, xedges)[0] assert_array_equal(H.T, answer) H, xedges, yedges = histogram2d(list(range(10)), list(range(10))) assert_array_equal(H, eye(10, 10)) assert_array_equal(xedges, np.linspace(0, 9, 11)) assert_array_equal(yedges, np.linspace(0, 9, 11)) def test_asym(self): x = array([1, 1, 2, 3, 4, 4, 4, 5]) y = array([1, 3, 2, 0, 1, 2, 3, 4]) H, xed, yed = histogram2d(x, y, (6, 5), range = [[0, 6], [0, 5]], normed=True) answer = array([[0., 0, 0, 0, 0], [0, 1, 0, 1, 0], [0, 0, 1, 0, 0], [1, 0, 0, 0, 0], [0, 1, 1, 1, 0], [0, 0, 0, 0, 1]]) assert_array_almost_equal(H, answer/8., 3) assert_array_equal(xed, np.linspace(0, 6, 7)) assert_array_equal(yed, np.linspace(0, 5, 6)) def test_norm(self): x = array([1, 2, 3, 1, 2, 3, 1, 2, 3]) y = array([1, 1, 1, 2, 2, 2, 3, 3, 3]) H, xed, yed = histogram2d(x, y, [[1, 2, 3, 5], [1, 2, 3, 5]], normed=True) answer=array([[1, 1, .5], [1, 1, .5], [.5, .5, .25]])/9. assert_array_almost_equal(H, answer, 3) def test_all_outliers(self): r = rand(100)+1. H, xed, yed = histogram2d(r, r, (4, 5), range=([0, 1], [0, 1])) assert_array_equal(H, 0) def test_empty(self): a, edge1, edge2 = histogram2d([], [], bins=([0, 1], [0, 1])) assert_array_max_ulp(a, array([[ 0.]])) a, edge1, edge2 = histogram2d([], [], bins=4) assert_array_max_ulp(a, np.zeros((4, 4))) class TestTri(TestCase): def test_dtype(self): out = array([[1, 0, 0], [1, 1, 0], [1, 1, 1]]) assert_array_equal(tri(3), out) assert_array_equal(tri(3, dtype=bool), out.astype(bool)) def test_tril_triu(): 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) # should return the same dtype as the original array assert_equal(b.dtype, a.dtype) assert_equal(c.dtype, a.dtype) def test_mask_indices(): # simple test without offset iu = mask_indices(3, np.triu) a = np.arange(9).reshape(3, 3) yield (assert_array_equal, a[iu], array([0, 1, 2, 4, 5, 8])) # Now with an offset iu1 = mask_indices(3, np.triu, 1) yield (assert_array_equal, a[iu1], array([1, 2, 5])) def test_tril_indices(): # indices without and with offset il1 = tril_indices(4) il2 = tril_indices(4, 2) a = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]) # indexing: yield (assert_array_equal, a[il1], array([ 1, 5, 6, 9, 10, 11, 13, 14, 15, 16]) ) # And for assigning values: a[il1] = -1 yield (assert_array_equal, a, array([[-1, 2, 3, 4], [-1, -1, 7, 8], [-1, -1, -1, 12], [-1, -1, -1, -1]]) ) # These cover almost the whole array (two diagonals right of the main one): a[il2] = -10 yield (assert_array_equal, a, array([[-10, -10, -10, 4], [-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) a = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]) # Both for indexing: yield (assert_array_equal, a[iu1], array([1, 2, 3, 4, 6, 7, 8, 11, 12, 16])) # And for assigning values: a[iu1] = -1 yield (assert_array_equal, a, array([[-1, -1, -1, -1], [ 5, -1, -1, -1], [ 9, 10, -1, -1], [13, 14, 15, -1]]) ) # These cover almost the whole array (two diagonals right of the main one): a[iu2] = -10 yield ( assert_array_equal, a, array([[ -1, -1, -10, -10], [ 5, -1, -1, -10], [ 9, 10, -1, -1], [ 13, 14, 15, -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))) 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))) if __name__ == "__main__": run_module_suite() numpy-1.8.2/numpy/lib/tests/test_arrayterator.py0000664000175100017510000000265712370216242023245 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function from operator import mul from functools import reduce import numpy as np from numpy.random import randint from numpy.lib import Arrayterator from numpy.testing import assert_ def test(): np.random.seed(np.arange(10)) # Create a random array ndims = randint(5)+1 shape = tuple(randint(10)+1 for dim in range(ndims)) els = reduce(mul, shape) a = np.arange(els) a.shape = shape buf_size = randint(2*els) b = Arrayterator(a, buf_size) # Check that each block has at most ``buf_size`` elements for block in b: assert_(len(block.flat) <= (buf_size or els)) # Check that all elements are iterated correctly assert_(list(b.flat) == list(a.flat)) # Slice arrayterator start = [randint(dim) for dim in shape] stop = [randint(dim)+1 for dim in shape] step = [randint(dim)+1 for dim in shape] slice_ = tuple(slice(*t) for t in zip(start, stop, step)) c = b[slice_] d = a[slice_] # Check that each block has at most ``buf_size`` elements for block in c: assert_(len(block.flat) <= (buf_size or els)) # Check that the arrayterator is sliced correctly assert_(np.all(c.__array__() == d)) # Check that all elements are iterated correctly assert_(list(c.flat) == list(d.flat)) if __name__ == '__main__': from numpy.testing import run_module_suite run_module_suite() numpy-1.8.2/numpy/lib/tests/test_format.py0000664000175100017510000006631212370216243022015 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function r''' Test the .npy file format. Set up: >>> import sys >>> from io import BytesIO >>> from numpy.lib import format >>> >>> scalars = [ ... np.uint8, ... np.int8, ... np.uint16, ... np.int16, ... np.uint32, ... np.int32, ... np.uint64, ... np.int64, ... np.float32, ... np.float64, ... np.complex64, ... np.complex128, ... object, ... ] >>> >>> basic_arrays = [] >>> >>> for scalar in scalars: ... for endian in '<>': ... dtype = np.dtype(scalar).newbyteorder(endian) ... basic = np.arange(15).astype(dtype) ... basic_arrays.extend([ ... np.array([], dtype=dtype), ... np.array(10, dtype=dtype), ... basic, ... basic.reshape((3,5)), ... basic.reshape((3,5)).T, ... basic.reshape((3,5))[::-1,::2], ... ]) ... >>> >>> Pdescr = [ ... ('x', 'i4', (2,)), ... ('y', 'f8', (2, 2)), ... ('z', 'u1')] >>> >>> >>> PbufferT = [ ... ([3,2], [[6.,4.],[6.,4.]], 8), ... ([4,3], [[7.,5.],[7.,5.]], 9), ... ] >>> >>> >>> Ndescr = [ ... ('x', 'i4', (2,)), ... ('Info', [ ... ('value', 'c16'), ... ('y2', 'f8'), ... ('Info2', [ ... ('name', 'S2'), ... ('value', 'c16', (2,)), ... ('y3', 'f8', (2,)), ... ('z3', 'u4', (2,))]), ... ('name', 'S2'), ... ('z2', 'b1')]), ... ('color', 'S2'), ... ('info', [ ... ('Name', 'U8'), ... ('Value', 'c16')]), ... ('y', 'f8', (2, 2)), ... ('z', 'u1')] >>> >>> >>> NbufferT = [ ... ([3,2], (6j, 6., ('nn', [6j,4j], [6.,4.], [1,2]), 'NN', True), 'cc', ('NN', 6j), [[6.,4.],[6.,4.]], 8), ... ([4,3], (7j, 7., ('oo', [7j,5j], [7.,5.], [2,1]), 'OO', False), 'dd', ('OO', 7j), [[7.,5.],[7.,5.]], 9), ... ] >>> >>> >>> record_arrays = [ ... np.array(PbufferT, dtype=np.dtype(Pdescr).newbyteorder('<')), ... np.array(NbufferT, dtype=np.dtype(Ndescr).newbyteorder('<')), ... np.array(PbufferT, dtype=np.dtype(Pdescr).newbyteorder('>')), ... np.array(NbufferT, dtype=np.dtype(Ndescr).newbyteorder('>')), ... ] Test the magic string writing. >>> format.magic(1, 0) '\x93NUMPY\x01\x00' >>> format.magic(0, 0) '\x93NUMPY\x00\x00' >>> format.magic(255, 255) '\x93NUMPY\xff\xff' >>> format.magic(2, 5) '\x93NUMPY\x02\x05' Test the magic string reading. >>> format.read_magic(BytesIO(format.magic(1, 0))) (1, 0) >>> format.read_magic(BytesIO(format.magic(0, 0))) (0, 0) >>> format.read_magic(BytesIO(format.magic(255, 255))) (255, 255) >>> format.read_magic(BytesIO(format.magic(2, 5))) (2, 5) Test the header writing. >>> for arr in basic_arrays + record_arrays: ... f = BytesIO() ... format.write_array_header_1_0(f, arr) # XXX: arr is not a dict, items gets called on it ... print repr(f.getvalue()) ... "F\x00{'descr': '|u1', 'fortran_order': False, 'shape': (0,)} \n" "F\x00{'descr': '|u1', 'fortran_order': False, 'shape': ()} \n" "F\x00{'descr': '|u1', 'fortran_order': False, 'shape': (15,)} \n" "F\x00{'descr': '|u1', 'fortran_order': False, 'shape': (3, 5)} \n" "F\x00{'descr': '|u1', 'fortran_order': True, 'shape': (5, 3)} \n" "F\x00{'descr': '|u1', 'fortran_order': False, 'shape': (3, 3)} \n" "F\x00{'descr': '|u1', 'fortran_order': False, 'shape': (0,)} \n" "F\x00{'descr': '|u1', 'fortran_order': False, 'shape': ()} \n" "F\x00{'descr': '|u1', 'fortran_order': False, 'shape': (15,)} \n" "F\x00{'descr': '|u1', 'fortran_order': False, 'shape': (3, 5)} \n" "F\x00{'descr': '|u1', 'fortran_order': True, 'shape': (5, 3)} \n" "F\x00{'descr': '|u1', 'fortran_order': False, 'shape': (3, 3)} \n" "F\x00{'descr': '|i1', 'fortran_order': False, 'shape': (0,)} \n" "F\x00{'descr': '|i1', 'fortran_order': False, 'shape': ()} \n" "F\x00{'descr': '|i1', 'fortran_order': False, 'shape': (15,)} \n" "F\x00{'descr': '|i1', 'fortran_order': False, 'shape': (3, 5)} \n" "F\x00{'descr': '|i1', 'fortran_order': True, 'shape': (5, 3)} \n" "F\x00{'descr': '|i1', 'fortran_order': False, 'shape': (3, 3)} \n" "F\x00{'descr': '|i1', 'fortran_order': False, 'shape': (0,)} \n" "F\x00{'descr': '|i1', 'fortran_order': False, 'shape': ()} \n" "F\x00{'descr': '|i1', 'fortran_order': False, 'shape': (15,)} \n" "F\x00{'descr': '|i1', 'fortran_order': False, 'shape': (3, 5)} \n" "F\x00{'descr': '|i1', 'fortran_order': True, 'shape': (5, 3)} \n" "F\x00{'descr': '|i1', 'fortran_order': False, 'shape': (3, 3)} \n" "F\x00{'descr': 'u2', 'fortran_order': False, 'shape': (0,)} \n" "F\x00{'descr': '>u2', 'fortran_order': False, 'shape': ()} \n" "F\x00{'descr': '>u2', 'fortran_order': False, 'shape': (15,)} \n" "F\x00{'descr': '>u2', 'fortran_order': False, 'shape': (3, 5)} \n" "F\x00{'descr': '>u2', 'fortran_order': True, 'shape': (5, 3)} \n" "F\x00{'descr': '>u2', 'fortran_order': False, 'shape': (3, 3)} \n" "F\x00{'descr': 'i2', 'fortran_order': False, 'shape': (0,)} \n" "F\x00{'descr': '>i2', 'fortran_order': False, 'shape': ()} \n" "F\x00{'descr': '>i2', 'fortran_order': False, 'shape': (15,)} \n" "F\x00{'descr': '>i2', 'fortran_order': False, 'shape': (3, 5)} \n" "F\x00{'descr': '>i2', 'fortran_order': True, 'shape': (5, 3)} \n" "F\x00{'descr': '>i2', 'fortran_order': False, 'shape': (3, 3)} \n" "F\x00{'descr': 'u4', 'fortran_order': False, 'shape': (0,)} \n" "F\x00{'descr': '>u4', 'fortran_order': False, 'shape': ()} \n" "F\x00{'descr': '>u4', 'fortran_order': False, 'shape': (15,)} \n" "F\x00{'descr': '>u4', 'fortran_order': False, 'shape': (3, 5)} \n" "F\x00{'descr': '>u4', 'fortran_order': True, 'shape': (5, 3)} \n" "F\x00{'descr': '>u4', 'fortran_order': False, 'shape': (3, 3)} \n" "F\x00{'descr': 'i4', 'fortran_order': False, 'shape': (0,)} \n" "F\x00{'descr': '>i4', 'fortran_order': False, 'shape': ()} \n" "F\x00{'descr': '>i4', 'fortran_order': False, 'shape': (15,)} \n" "F\x00{'descr': '>i4', 'fortran_order': False, 'shape': (3, 5)} \n" "F\x00{'descr': '>i4', 'fortran_order': True, 'shape': (5, 3)} \n" "F\x00{'descr': '>i4', 'fortran_order': False, 'shape': (3, 3)} \n" "F\x00{'descr': 'u8', 'fortran_order': False, 'shape': (0,)} \n" "F\x00{'descr': '>u8', 'fortran_order': False, 'shape': ()} \n" "F\x00{'descr': '>u8', 'fortran_order': False, 'shape': (15,)} \n" "F\x00{'descr': '>u8', 'fortran_order': False, 'shape': (3, 5)} \n" "F\x00{'descr': '>u8', 'fortran_order': True, 'shape': (5, 3)} \n" "F\x00{'descr': '>u8', 'fortran_order': False, 'shape': (3, 3)} \n" "F\x00{'descr': 'i8', 'fortran_order': False, 'shape': (0,)} \n" "F\x00{'descr': '>i8', 'fortran_order': False, 'shape': ()} \n" "F\x00{'descr': '>i8', 'fortran_order': False, 'shape': (15,)} \n" "F\x00{'descr': '>i8', 'fortran_order': False, 'shape': (3, 5)} \n" "F\x00{'descr': '>i8', 'fortran_order': True, 'shape': (5, 3)} \n" "F\x00{'descr': '>i8', 'fortran_order': False, 'shape': (3, 3)} \n" "F\x00{'descr': 'f4', 'fortran_order': False, 'shape': (0,)} \n" "F\x00{'descr': '>f4', 'fortran_order': False, 'shape': ()} \n" "F\x00{'descr': '>f4', 'fortran_order': False, 'shape': (15,)} \n" "F\x00{'descr': '>f4', 'fortran_order': False, 'shape': (3, 5)} \n" "F\x00{'descr': '>f4', 'fortran_order': True, 'shape': (5, 3)} \n" "F\x00{'descr': '>f4', 'fortran_order': False, 'shape': (3, 3)} \n" "F\x00{'descr': 'f8', 'fortran_order': False, 'shape': (0,)} \n" "F\x00{'descr': '>f8', 'fortran_order': False, 'shape': ()} \n" "F\x00{'descr': '>f8', 'fortran_order': False, 'shape': (15,)} \n" "F\x00{'descr': '>f8', 'fortran_order': False, 'shape': (3, 5)} \n" "F\x00{'descr': '>f8', 'fortran_order': True, 'shape': (5, 3)} \n" "F\x00{'descr': '>f8', 'fortran_order': False, 'shape': (3, 3)} \n" "F\x00{'descr': 'c8', 'fortran_order': False, 'shape': (0,)} \n" "F\x00{'descr': '>c8', 'fortran_order': False, 'shape': ()} \n" "F\x00{'descr': '>c8', 'fortran_order': False, 'shape': (15,)} \n" "F\x00{'descr': '>c8', 'fortran_order': False, 'shape': (3, 5)} \n" "F\x00{'descr': '>c8', 'fortran_order': True, 'shape': (5, 3)} \n" "F\x00{'descr': '>c8', 'fortran_order': False, 'shape': (3, 3)} \n" "F\x00{'descr': 'c16', 'fortran_order': False, 'shape': (0,)} \n" "F\x00{'descr': '>c16', 'fortran_order': False, 'shape': ()} \n" "F\x00{'descr': '>c16', 'fortran_order': False, 'shape': (15,)} \n" "F\x00{'descr': '>c16', 'fortran_order': False, 'shape': (3, 5)} \n" "F\x00{'descr': '>c16', 'fortran_order': True, 'shape': (5, 3)} \n" "F\x00{'descr': '>c16', 'fortran_order': False, 'shape': (3, 3)} \n" "F\x00{'descr': 'O', 'fortran_order': False, 'shape': (0,)} \n" "F\x00{'descr': 'O', 'fortran_order': False, 'shape': ()} \n" "F\x00{'descr': 'O', 'fortran_order': False, 'shape': (15,)} \n" "F\x00{'descr': 'O', 'fortran_order': False, 'shape': (3, 5)} \n" "F\x00{'descr': 'O', 'fortran_order': True, 'shape': (5, 3)} \n" "F\x00{'descr': 'O', 'fortran_order': False, 'shape': (3, 3)} \n" "F\x00{'descr': 'O', 'fortran_order': False, 'shape': (0,)} \n" "F\x00{'descr': 'O', 'fortran_order': False, 'shape': ()} \n" "F\x00{'descr': 'O', 'fortran_order': False, 'shape': (15,)} \n" "F\x00{'descr': 'O', 'fortran_order': False, 'shape': (3, 5)} \n" "F\x00{'descr': 'O', 'fortran_order': True, 'shape': (5, 3)} \n" "F\x00{'descr': 'O', 'fortran_order': False, 'shape': (3, 3)} \n" "v\x00{'descr': [('x', 'i4', (2,)), ('y', '>f8', (2, 2)), ('z', '|u1')],\n 'fortran_order': False,\n 'shape': (2,)} \n" "\x16\x02{'descr': [('x', '>i4', (2,)),\n ('Info',\n [('value', '>c16'),\n ('y2', '>f8'),\n ('Info2',\n [('name', '|S2'),\n ('value', '>c16', (2,)),\n ('y3', '>f8', (2,)),\n ('z3', '>u4', (2,))]),\n ('name', '|S2'),\n ('z2', '|b1')]),\n ('color', '|S2'),\n ('info', [('Name', '>U8'), ('Value', '>c16')]),\n ('y', '>f8', (2, 2)),\n ('z', '|u1')],\n 'fortran_order': False,\n 'shape': (2,)} \n" ''' import sys import os import shutil import tempfile from io import BytesIO import numpy as np from numpy.testing import * from numpy.lib import format from numpy.compat import asbytes, asbytes_nested tempdir = None # Module-level setup. def setup_module(): global tempdir tempdir = tempfile.mkdtemp() def teardown_module(): global tempdir if tempdir is not None and os.path.isdir(tempdir): shutil.rmtree(tempdir) tempdir = None # Generate some basic arrays to test with. scalars = [ np.uint8, np.int8, np.uint16, np.int16, np.uint32, np.int32, np.uint64, np.int64, np.float32, np.float64, np.complex64, np.complex128, object, ] basic_arrays = [] for scalar in scalars: for endian in '<>': dtype = np.dtype(scalar).newbyteorder(endian) basic = np.arange(15).astype(dtype) basic_arrays.extend([ # Empty np.array([], dtype=dtype), # Rank-0 np.array(10, dtype=dtype), # 1-D basic, # 2-D C-contiguous basic.reshape((3, 5)), # 2-D F-contiguous basic.reshape((3, 5)).T, # 2-D non-contiguous basic.reshape((3, 5))[::-1, ::2], ]) # More complicated record arrays. # This is the structure of the table used for plain objects: # # +-+-+-+ # |x|y|z| # +-+-+-+ # Structure of a plain array description: Pdescr = [ ('x', 'i4', (2,)), ('y', 'f8', (2, 2)), ('z', 'u1')] # A plain list of tuples with values for testing: PbufferT = [ # x y z ([3, 2], [[6., 4.], [6., 4.]], 8), ([4, 3], [[7., 5.], [7., 5.]], 9), ] # This is the structure of the table used for nested objects (DON'T PANIC!): # # +-+---------------------------------+-----+----------+-+-+ # |x|Info |color|info |y|z| # | +-----+--+----------------+----+--+ +----+-----+ | | # | |value|y2|Info2 |name|z2| |Name|Value| | | # | | | +----+-----+--+--+ | | | | | | | # | | | |name|value|y3|z3| | | | | | | | # +-+-----+--+----+-----+--+--+----+--+-----+----+-----+-+-+ # # The corresponding nested array description: Ndescr = [ ('x', 'i4', (2,)), ('Info', [ ('value', 'c16'), ('y2', 'f8'), ('Info2', [ ('name', 'S2'), ('value', 'c16', (2,)), ('y3', 'f8', (2,)), ('z3', 'u4', (2,))]), ('name', 'S2'), ('z2', 'b1')]), ('color', 'S2'), ('info', [ ('Name', 'U8'), ('Value', 'c16')]), ('y', 'f8', (2, 2)), ('z', 'u1')] NbufferT = [ # x Info color info y z # value y2 Info2 name z2 Name Value # name value y3 z3 ([3, 2], (6j, 6., ('nn', [6j, 4j], [6., 4.], [1, 2]), 'NN', True), 'cc', ('NN', 6j), [[6., 4.], [6., 4.]], 8), ([4, 3], (7j, 7., ('oo', [7j, 5j], [7., 5.], [2, 1]), 'OO', False), 'dd', ('OO', 7j), [[7., 5.], [7., 5.]], 9), ] record_arrays = [ np.array(PbufferT, dtype=np.dtype(Pdescr).newbyteorder('<')), np.array(NbufferT, dtype=np.dtype(Ndescr).newbyteorder('<')), np.array(PbufferT, dtype=np.dtype(Pdescr).newbyteorder('>')), np.array(NbufferT, dtype=np.dtype(Ndescr).newbyteorder('>')), ] #BytesIO that reads a random number of bytes at a time class BytesIOSRandomSize(BytesIO): def read(self, size=None): import random size = random.randint(1, size) return super(BytesIOSRandomSize, self).read(size) def roundtrip(arr): f = BytesIO() format.write_array(f, arr) f2 = BytesIO(f.getvalue()) arr2 = format.read_array(f2) return arr2 def roundtrip_randsize(arr): f = BytesIO() format.write_array(f, arr) f2 = BytesIOSRandomSize(f.getvalue()) arr2 = format.read_array(f2) return arr2 def roundtrip_truncated(arr): f = BytesIO() format.write_array(f, arr) #BytesIO is one byte short f2 = BytesIO(f.getvalue()[0:-1]) arr2 = format.read_array(f2) return arr2 def assert_equal(o1, o2): assert_(o1 == o2) def test_roundtrip(): for arr in basic_arrays + record_arrays: arr2 = roundtrip(arr) yield assert_array_equal, arr, arr2 def test_roundtrip_randsize(): for arr in basic_arrays + record_arrays: if arr.dtype != object: arr2 = roundtrip_randsize(arr) yield assert_array_equal, arr, arr2 def test_roundtrip_truncated(): for arr in basic_arrays: if arr.dtype != object: yield assert_raises, ValueError, roundtrip_truncated, arr def test_long_str(): # check items larger than internal buffer size, gh-4027 long_str_arr = np.ones(1, dtype=np.dtype((str, format.BUFFER_SIZE + 1))) long_str_arr2 = roundtrip(long_str_arr) assert_array_equal(long_str_arr, long_str_arr2) def test_memmap_roundtrip(): # XXX: test crashes nose on windows. Fix this if not (sys.platform == 'win32' or sys.platform == 'cygwin'): for arr in basic_arrays + record_arrays: if arr.dtype.hasobject: # Skip these since they can't be mmap'ed. continue # Write it out normally and through mmap. nfn = os.path.join(tempdir, 'normal.npy') mfn = os.path.join(tempdir, 'memmap.npy') fp = open(nfn, 'wb') try: format.write_array(fp, arr) finally: fp.close() fortran_order = (arr.flags.f_contiguous and not arr.flags.c_contiguous) ma = format.open_memmap(mfn, mode='w+', dtype=arr.dtype, shape=arr.shape, fortran_order=fortran_order) ma[...] = arr del ma # Check that both of these files' contents are the same. fp = open(nfn, 'rb') normal_bytes = fp.read() fp.close() fp = open(mfn, 'rb') memmap_bytes = fp.read() fp.close() yield assert_equal, normal_bytes, memmap_bytes # Check that reading the file using memmap works. ma = format.open_memmap(nfn, mode='r') #yield assert_array_equal, ma, arr del ma def test_compressed_roundtrip(): arr = np.random.rand(200, 200) npz_file = os.path.join(tempdir, 'compressed.npz') np.savez_compressed(npz_file, arr=arr) arr1 = np.load(npz_file)['arr'] assert_array_equal(arr, arr1) def test_write_version_1_0(): f = BytesIO() arr = np.arange(1) # These should pass. format.write_array(f, arr, version=(1, 0)) format.write_array(f, arr) # These should all fail. bad_versions = [ (1, 1), (0, 0), (0, 1), (2, 0), (2, 2), (255, 255), ] for version in bad_versions: try: format.write_array(f, arr, version=version) except ValueError: pass else: raise AssertionError("we should have raised a ValueError for the bad version %r" % (version,)) bad_version_magic = asbytes_nested([ '\x93NUMPY\x01\x01', '\x93NUMPY\x00\x00', '\x93NUMPY\x00\x01', '\x93NUMPY\x02\x00', '\x93NUMPY\x02\x02', '\x93NUMPY\xff\xff', ]) malformed_magic = asbytes_nested([ '\x92NUMPY\x01\x00', '\x00NUMPY\x01\x00', '\x93numpy\x01\x00', '\x93MATLB\x01\x00', '\x93NUMPY\x01', '\x93NUMPY', '', ]) def test_read_magic_bad_magic(): for magic in malformed_magic: f = BytesIO(magic) yield raises(ValueError)(format.read_magic), f def test_read_version_1_0_bad_magic(): for magic in bad_version_magic + malformed_magic: f = BytesIO(magic) yield raises(ValueError)(format.read_array), f def test_bad_magic_args(): assert_raises(ValueError, format.magic, -1, 1) assert_raises(ValueError, format.magic, 256, 1) assert_raises(ValueError, format.magic, 1, -1) assert_raises(ValueError, format.magic, 1, 256) def test_large_header(): s = BytesIO() d = {'a':1,'b':2} format.write_array_header_1_0(s, d) s = BytesIO() d = {'a':1,'b':2,'c':'x'*256*256} assert_raises(ValueError, format.write_array_header_1_0, s, d) def test_bad_header(): # header of length less than 2 should fail s = BytesIO() assert_raises(ValueError, format.read_array_header_1_0, s) s = BytesIO(asbytes('1')) assert_raises(ValueError, format.read_array_header_1_0, s) # header shorter than indicated size should fail s = BytesIO(asbytes('\x01\x00')) assert_raises(ValueError, format.read_array_header_1_0, s) # headers without the exact keys required should fail d = {"shape":(1, 2), "descr":"x"} s = BytesIO() format.write_array_header_1_0(s, d) assert_raises(ValueError, format.read_array_header_1_0, s) d = {"shape":(1, 2), "fortran_order":False, "descr":"x", "extrakey":-1} s = BytesIO() 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() numpy-1.8.2/numpy/lib/tests/test__iotools.py0000664000175100017510000003203212370216243022344 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function import sys import time from datetime import date import numpy as np from numpy.lib._iotools import LineSplitter, NameValidator, StringConverter, \ has_nested_fields, easy_dtype, flatten_dtype from numpy.testing import * from numpy.compat import asbytes, asbytes_nested class TestLineSplitter(TestCase): "Tests the LineSplitter class." # def test_no_delimiter(self): "Test LineSplitter w/o delimiter" strg = asbytes(" 1 2 3 4 5 # test") test = LineSplitter()(strg) assert_equal(test, asbytes_nested(['1', '2', '3', '4', '5'])) test = LineSplitter('')(strg) assert_equal(test, asbytes_nested(['1', '2', '3', '4', '5'])) def test_space_delimiter(self): "Test space delimiter" strg = asbytes(" 1 2 3 4 5 # test") test = LineSplitter(asbytes(' '))(strg) assert_equal(test, asbytes_nested(['1', '2', '3', '4', '', '5'])) test = LineSplitter(asbytes(' '))(strg) assert_equal(test, asbytes_nested(['1 2 3 4', '5'])) def test_tab_delimiter(self): "Test tab delimiter" strg = asbytes(" 1\t 2\t 3\t 4\t 5 6") test = LineSplitter(asbytes('\t'))(strg) assert_equal(test, asbytes_nested(['1', '2', '3', '4', '5 6'])) strg = asbytes(" 1 2\t 3 4\t 5 6") test = LineSplitter(asbytes('\t'))(strg) assert_equal(test, asbytes_nested(['1 2', '3 4', '5 6'])) def test_other_delimiter(self): "Test LineSplitter on delimiter" strg = asbytes("1,2,3,4,,5") test = LineSplitter(asbytes(','))(strg) assert_equal(test, asbytes_nested(['1', '2', '3', '4', '', '5'])) # strg = asbytes(" 1,2,3,4,,5 # test") test = LineSplitter(asbytes(','))(strg) assert_equal(test, asbytes_nested(['1', '2', '3', '4', '', '5'])) def test_constant_fixed_width(self): "Test LineSplitter w/ fixed-width fields" strg = asbytes(" 1 2 3 4 5 # test") test = LineSplitter(3)(strg) assert_equal(test, asbytes_nested(['1', '2', '3', '4', '', '5', ''])) # strg = asbytes(" 1 3 4 5 6# test") test = LineSplitter(20)(strg) assert_equal(test, asbytes_nested(['1 3 4 5 6'])) # strg = asbytes(" 1 3 4 5 6# test") test = LineSplitter(30)(strg) assert_equal(test, asbytes_nested(['1 3 4 5 6'])) def test_variable_fixed_width(self): strg = asbytes(" 1 3 4 5 6# test") test = LineSplitter((3, 6, 6, 3))(strg) assert_equal(test, asbytes_nested(['1', '3', '4 5', '6'])) # strg = asbytes(" 1 3 4 5 6# test") test = LineSplitter((6, 6, 9))(strg) assert_equal(test, asbytes_nested(['1', '3 4', '5 6'])) #------------------------------------------------------------------------------- class TestNameValidator(TestCase): # def test_case_sensitivity(self): "Test case sensitivity" names = ['A', 'a', 'b', 'c'] test = NameValidator().validate(names) assert_equal(test, ['A', 'a', 'b', 'c']) test = NameValidator(case_sensitive=False).validate(names) assert_equal(test, ['A', 'A_1', 'B', 'C']) test = NameValidator(case_sensitive='upper').validate(names) assert_equal(test, ['A', 'A_1', 'B', 'C']) test = NameValidator(case_sensitive='lower').validate(names) assert_equal(test, ['a', 'a_1', 'b', 'c']) # def test_excludelist(self): "Test excludelist" names = ['dates', 'data', 'Other Data', 'mask'] validator = NameValidator(excludelist=['dates', 'data', 'mask']) test = validator.validate(names) assert_equal(test, ['dates_', 'data_', 'Other_Data', 'mask_']) # def test_missing_names(self): "Test validate missing names" namelist = ('a', 'b', 'c') validator = NameValidator() assert_equal(validator(namelist), ['a', 'b', 'c']) namelist = ('', 'b', 'c') assert_equal(validator(namelist), ['f0', 'b', 'c']) namelist = ('a', 'b', '') assert_equal(validator(namelist), ['a', 'b', 'f0']) namelist = ('', 'f0', '') assert_equal(validator(namelist), ['f1', 'f0', 'f2']) # def test_validate_nb_names(self): "Test validate nb names" namelist = ('a', 'b', 'c') validator = NameValidator() assert_equal(validator(namelist, nbfields=1), ('a',)) assert_equal(validator(namelist, nbfields=5, defaultfmt="g%i"), ['a', 'b', 'c', 'g0', 'g1']) # def test_validate_wo_names(self): "Test validate no names" namelist = None validator = NameValidator() assert_(validator(namelist) is None) assert_equal(validator(namelist, nbfields=3), ['f0', 'f1', 'f2']) #------------------------------------------------------------------------------- def _bytes_to_date(s): if sys.version_info[0] >= 3: return date(*time.strptime(s.decode('latin1'), "%Y-%m-%d")[:3]) else: return date(*time.strptime(s, "%Y-%m-%d")[:3]) class TestStringConverter(TestCase): "Test StringConverter" # def test_creation(self): "Test creation of a StringConverter" converter = StringConverter(int, -99999) assert_equal(converter._status, 1) assert_equal(converter.default, -99999) # def test_upgrade(self): "Tests the upgrade method." converter = StringConverter() assert_equal(converter._status, 0) converter.upgrade(asbytes('0')) assert_equal(converter._status, 1) converter.upgrade(asbytes('0.')) assert_equal(converter._status, 2) converter.upgrade(asbytes('0j')) assert_equal(converter._status, 3) converter.upgrade(asbytes('a')) assert_equal(converter._status, len(converter._mapper) - 1) # def test_missing(self): "Tests the use of missing values." converter = StringConverter(missing_values=(asbytes('missing'), asbytes('missed'))) converter.upgrade(asbytes('0')) assert_equal(converter(asbytes('0')), 0) assert_equal(converter(asbytes('')), converter.default) assert_equal(converter(asbytes('missing')), converter.default) assert_equal(converter(asbytes('missed')), converter.default) try: converter('miss') except ValueError: pass # def test_upgrademapper(self): "Tests updatemapper" dateparser = _bytes_to_date StringConverter.upgrade_mapper(dateparser, date(2000, 1, 1)) convert = StringConverter(dateparser, date(2000, 1, 1)) test = convert(asbytes('2001-01-01')) assert_equal(test, date(2001, 1, 1)) test = convert(asbytes('2009-01-01')) assert_equal(test, date(2009, 1, 1)) test = convert(asbytes('')) assert_equal(test, date(2000, 1, 1)) # def test_string_to_object(self): "Make sure that string-to-object functions are properly recognized" conv = StringConverter(_bytes_to_date) assert_equal(conv._mapper[-2][0](0), 0j) assert_(hasattr(conv, 'default')) # def test_keep_default(self): "Make sure we don't lose an explicit default" converter = StringConverter(None, missing_values=asbytes(''), default= -999) converter.upgrade(asbytes('3.14159265')) assert_equal(converter.default, -999) assert_equal(converter.type, np.dtype(float)) # converter = StringConverter(None, missing_values=asbytes(''), default=0) converter.upgrade(asbytes('3.14159265')) assert_equal(converter.default, 0) assert_equal(converter.type, np.dtype(float)) # def test_keep_default_zero(self): "Check that we don't lose a default of 0" converter = StringConverter(int, default=0, missing_values=asbytes("N/A")) assert_equal(converter.default, 0) # def test_keep_missing_values(self): "Check that we're not losing missing values" converter = StringConverter(int, default=0, missing_values=asbytes("N/A")) assert_equal(converter.missing_values, set(asbytes_nested(['', 'N/A']))) def test_int64_dtype(self): "Check that int64 integer types can be specified" converter = StringConverter(np.int64, default=0) val = asbytes("-9223372036854775807") assert_(converter(val) == -9223372036854775807) val = asbytes("9223372036854775807") assert_(converter(val) == 9223372036854775807) def test_uint64_dtype(self): "Check that uint64 integer types can be specified" converter = StringConverter(np.uint64, default=0) val = asbytes("9223372043271415339") assert_(converter(val) == 9223372043271415339) #------------------------------------------------------------------------------- class TestMiscFunctions(TestCase): # def test_has_nested_dtype(self): "Test has_nested_dtype" ndtype = np.dtype(np.float) assert_equal(has_nested_fields(ndtype), False) ndtype = np.dtype([('A', '|S3'), ('B', float)]) assert_equal(has_nested_fields(ndtype), False) ndtype = np.dtype([('A', int), ('B', [('BA', float), ('BB', '|S1')])]) assert_equal(has_nested_fields(ndtype), True) def test_easy_dtype(self): "Test ndtype on dtypes" # Simple case ndtype = float assert_equal(easy_dtype(ndtype), np.dtype(float)) # As string w/o names ndtype = "i4, f8" assert_equal(easy_dtype(ndtype), np.dtype([('f0', "i4"), ('f1', "f8")])) # As string w/o names but different default format assert_equal(easy_dtype(ndtype, defaultfmt="field_%03i"), np.dtype([('field_000', "i4"), ('field_001', "f8")])) # As string w/ names ndtype = "i4, f8" assert_equal(easy_dtype(ndtype, names="a, b"), np.dtype([('a', "i4"), ('b', "f8")])) # As string w/ names (too many) ndtype = "i4, f8" assert_equal(easy_dtype(ndtype, names="a, b, c"), np.dtype([('a', "i4"), ('b', "f8")])) # As string w/ names (not enough) ndtype = "i4, f8" assert_equal(easy_dtype(ndtype, names=", b"), np.dtype([('f0', "i4"), ('b', "f8")])) # ... (with different default format) assert_equal(easy_dtype(ndtype, names="a", defaultfmt="f%02i"), np.dtype([('a', "i4"), ('f00', "f8")])) # As list of tuples w/o names ndtype = [('A', int), ('B', float)] assert_equal(easy_dtype(ndtype), np.dtype([('A', int), ('B', float)])) # As list of tuples w/ names assert_equal(easy_dtype(ndtype, names="a,b"), np.dtype([('a', int), ('b', float)])) # As list of tuples w/ not enough names assert_equal(easy_dtype(ndtype, names="a"), np.dtype([('a', int), ('f0', float)])) # As list of tuples w/ too many names assert_equal(easy_dtype(ndtype, names="a,b,c"), np.dtype([('a', int), ('b', float)])) # As list of types w/o names ndtype = (int, float, float) assert_equal(easy_dtype(ndtype), np.dtype([('f0', int), ('f1', float), ('f2', float)])) # As list of types w names ndtype = (int, float, float) assert_equal(easy_dtype(ndtype, names="a, b, c"), np.dtype([('a', int), ('b', float), ('c', float)])) # As simple dtype w/ names ndtype = np.dtype(float) assert_equal(easy_dtype(ndtype, names="a, b, c"), np.dtype([(_, float) for _ in ('a', 'b', 'c')])) # As simple dtype w/o names (but multiple fields) ndtype = np.dtype(float) assert_equal(easy_dtype(ndtype, names=['', '', ''], defaultfmt="f%02i"), np.dtype([(_, float) for _ in ('f00', 'f01', 'f02')])) def test_flatten_dtype(self): "Testing flatten_dtype" # Standard dtype dt = np.dtype([("a", "f8"), ("b", "f8")]) dt_flat = flatten_dtype(dt) assert_equal(dt_flat, [float, float]) # Recursive dtype dt = np.dtype([("a", [("aa", '|S1'), ("ab", '|S2')]), ("b", int)]) dt_flat = flatten_dtype(dt) assert_equal(dt_flat, [np.dtype('|S1'), np.dtype('|S2'), int]) # dtype with shaped fields dt = np.dtype([("a", (float, 2)), ("b", (int, 3))]) dt_flat = flatten_dtype(dt) assert_equal(dt_flat, [float, int]) dt_flat = flatten_dtype(dt, True) assert_equal(dt_flat, [float] * 2 + [int] * 3) # dtype w/ titles dt = np.dtype([(("a", "A"), "f8"), (("b", "B"), "f8")]) dt_flat = flatten_dtype(dt) assert_equal(dt_flat, [float, float]) if __name__ == "__main__": run_module_suite() numpy-1.8.2/numpy/lib/tests/test_polynomial.py0000664000175100017510000001102712370216243022701 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function ''' >>> p = np.poly1d([1.,2,3]) >>> p poly1d([ 1., 2., 3.]) >>> print(p) 2 1 x + 2 x + 3 >>> q = np.poly1d([3.,2,1]) >>> q poly1d([ 3., 2., 1.]) >>> print(q) 2 3 x + 2 x + 1 >>> print(np.poly1d([1.89999+2j, -3j, -5.12345678, 2+1j])) 3 2 (1.9 + 2j) x - 3j x - 5.123 x + (2 + 1j) >>> print(np.poly1d([-3, -2, -1])) 2 -3 x - 2 x - 1 >>> p(0) 3.0 >>> p(5) 38.0 >>> q(0) 1.0 >>> q(5) 86.0 >>> p * q poly1d([ 3., 8., 14., 8., 3.]) >>> p / q (poly1d([ 0.33333333]), poly1d([ 1.33333333, 2.66666667])) >>> p + q poly1d([ 4., 4., 4.]) >>> p - q poly1d([-2., 0., 2.]) >>> p ** 4 poly1d([ 1., 8., 36., 104., 214., 312., 324., 216., 81.]) >>> p(q) poly1d([ 9., 12., 16., 8., 6.]) >>> q(p) poly1d([ 3., 12., 32., 40., 34.]) >>> np.asarray(p) array([ 1., 2., 3.]) >>> len(p) 2 >>> p[0], p[1], p[2], p[3] (3.0, 2.0, 1.0, 0) >>> p.integ() poly1d([ 0.33333333, 1. , 3. , 0. ]) >>> p.integ(1) poly1d([ 0.33333333, 1. , 3. , 0. ]) >>> p.integ(5) poly1d([ 0.00039683, 0.00277778, 0.025 , 0. , 0. , 0. , 0. , 0. ]) >>> p.deriv() poly1d([ 2., 2.]) >>> p.deriv(2) poly1d([ 2.]) >>> q = np.poly1d([1.,2,3], variable='y') >>> print(q) 2 1 y + 2 y + 3 >>> q = np.poly1d([1.,2,3], variable='lambda') >>> print(q) 2 1 lambda + 2 lambda + 3 >>> np.polydiv(np.poly1d([1,0,-1]), np.poly1d([1,1])) (poly1d([ 1., -1.]), poly1d([ 0.])) ''' from numpy.testing import * import numpy as np class TestDocs(TestCase): def test_doctests(self): return rundocs() def test_roots(self): assert_array_equal(np.roots([1, 0, 0]), [0, 0]) def test_str_leading_zeros(self): p = np.poly1d([4, 3, 2, 1]) p[3] = 0 assert_equal(str(p), " 2\n" "3 x + 2 x + 1") p = np.poly1d([1, 2]) p[0] = 0 p[1] = 0 assert_equal(str(p), " \n0") def test_polyfit(self) : c = np.array([3., 2., 1.]) x = np.linspace(0, 2, 7) y = np.polyval(c, x) err = [1, -1, 1, -1, 1, -1, 1] weights = np.arange(8, 1, -1)**2/7.0 # check 1D case m, cov = np.polyfit(x, y+err, 2, cov=True) est = [3.8571, 0.2857, 1.619] assert_almost_equal(est, m, decimal=4) val0 = [[2.9388, -5.8776, 1.6327], [-5.8776, 12.7347, -4.2449], [1.6327, -4.2449, 2.3220]] assert_almost_equal(val0, cov, decimal=4) m2, cov2 = np.polyfit(x, y+err, 2, w=weights, cov=True) assert_almost_equal([4.8927, -1.0177, 1.7768], m2, decimal=4) val = [[ 8.7929, -10.0103, 0.9756], [-10.0103, 13.6134, -1.8178], [ 0.9756, -1.8178, 0.6674]] assert_almost_equal(val, cov2, decimal=4) # check 2D (n,1) case y = y[:, np.newaxis] c = c[:, np.newaxis] assert_almost_equal(c, np.polyfit(x, y, 2)) # check 2D (n,2) case yy = np.concatenate((y, y), axis=1) cc = np.concatenate((c, c), axis=1) assert_almost_equal(cc, np.polyfit(x, yy, 2)) m, cov = np.polyfit(x, yy + np.array(err)[:, np.newaxis], 2, cov=True) assert_almost_equal(est, m[:, 0], decimal=4) assert_almost_equal(est, m[:, 1], decimal=4) assert_almost_equal(val0, cov[:,:, 0], decimal=4) assert_almost_equal(val0, cov[:,:, 1], decimal=4) def test_objects(self): from decimal import Decimal p = np.poly1d([Decimal('4.0'), Decimal('3.0'), Decimal('2.0')]) p2 = p * Decimal('1.333333333333333') assert_(p2[1] == Decimal("3.9999999999999990")) p2 = p.deriv() assert_(p2[1] == Decimal('8.0')) p2 = p.integ() assert_(p2[3] == Decimal("1.333333333333333333333333333")) assert_(p2[2] == Decimal('1.5')) assert_(np.issubdtype(p2.coeffs.dtype, np.object_)) def test_complex(self): p = np.poly1d([3j, 2j, 1j]) p2 = p.integ() assert_((p2.coeffs == [1j, 1j, 1j, 0]).all()) p2 = p.deriv() assert_((p2.coeffs == [6j, 2j]).all()) def test_integ_coeffs(self): p = np.poly1d([3, 2, 1]) p2 = p.integ(3, k=[9, 7, 6]) assert_((p2.coeffs == [1/4./5., 1/3./4., 1/2./3., 9/1./2., 7, 6]).all()) def test_zero_dims(self): try: np.poly(np.zeros((0, 0))) except ValueError: pass if __name__ == "__main__": run_module_suite() numpy-1.8.2/numpy/lib/tests/test_recfunctions.py0000664000175100017510000007005512370216243023226 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function import sys import numpy as np import numpy.ma as ma from numpy.ma.testutils import * from numpy.ma.mrecords import MaskedRecords from numpy.lib.recfunctions import * get_names = np.lib.recfunctions.get_names get_names_flat = np.lib.recfunctions.get_names_flat zip_descr = np.lib.recfunctions.zip_descr class TestRecFunctions(TestCase): """ Misc tests """ # def setUp(self): x = np.array([1, 2, ]) y = np.array([10, 20, 30]) z = np.array([('A', 1.), ('B', 2.)], dtype=[('A', '|S3'), ('B', float)]) w = np.array([(1, (2, 3.0)), (4, (5, 6.0))], dtype=[('a', int), ('b', [('ba', float), ('bb', int)])]) self.data = (w, x, y, z) def test_zip_descr(self): "Test zip_descr" (w, x, y, z) = self.data # Std array test = zip_descr((x, x), flatten=True) assert_equal(test, np.dtype([('', int), ('', int)])) test = zip_descr((x, x), flatten=False) assert_equal(test, np.dtype([('', int), ('', int)])) # Std & flexible-dtype test = zip_descr((x, z), flatten=True) assert_equal(test, np.dtype([('', int), ('A', '|S3'), ('B', float)])) test = zip_descr((x, z), flatten=False) assert_equal(test, np.dtype([('', int), ('', [('A', '|S3'), ('B', float)])])) # Standard & nested dtype test = zip_descr((x, w), flatten=True) assert_equal(test, np.dtype([('', int), ('a', int), ('ba', float), ('bb', int)])) test = zip_descr((x, w), flatten=False) assert_equal(test, np.dtype([('', int), ('', [('a', int), ('b', [('ba', float), ('bb', int)])])])) def test_drop_fields(self): "Test drop_fields" a = np.array([(1, (2, 3.0)), (4, (5, 6.0))], dtype=[('a', int), ('b', [('ba', float), ('bb', int)])]) # A basic field test = drop_fields(a, 'a') control = np.array([((2, 3.0),), ((5, 6.0),)], dtype=[('b', [('ba', float), ('bb', int)])]) assert_equal(test, control) # Another basic field (but nesting two fields) test = drop_fields(a, 'b') control = np.array([(1,), (4,)], dtype=[('a', int)]) assert_equal(test, control) # A nested sub-field test = drop_fields(a, ['ba', ]) control = np.array([(1, (3.0,)), (4, (6.0,))], dtype=[('a', int), ('b', [('bb', int)])]) assert_equal(test, control) # All the nested sub-field from a field: zap that field test = drop_fields(a, ['ba', 'bb']) control = np.array([(1,), (4,)], dtype=[('a', int)]) assert_equal(test, control) # test = drop_fields(a, ['a', 'b']) assert_(test is None) def test_rename_fields(self): "Tests rename fields" a = np.array([(1, (2, [3.0, 30.])), (4, (5, [6.0, 60.]))], dtype=[('a', int), ('b', [('ba', float), ('bb', (float, 2))])]) test = rename_fields(a, {'a':'A', 'bb':'BB'}) newdtype = [('A', int), ('b', [('ba', float), ('BB', (float, 2))])] control = a.view(newdtype) assert_equal(test.dtype, newdtype) assert_equal(test, control) def test_get_names(self): "Tests get_names" ndtype = np.dtype([('A', '|S3'), ('B', float)]) test = get_names(ndtype) assert_equal(test, ('A', 'B')) # ndtype = np.dtype([('a', int), ('b', [('ba', float), ('bb', int)])]) test = get_names(ndtype) assert_equal(test, ('a', ('b', ('ba', 'bb')))) def test_get_names_flat(self): "Test get_names_flat" ndtype = np.dtype([('A', '|S3'), ('B', float)]) test = get_names_flat(ndtype) assert_equal(test, ('A', 'B')) # ndtype = np.dtype([('a', int), ('b', [('ba', float), ('bb', int)])]) test = get_names_flat(ndtype) assert_equal(test, ('a', 'b', 'ba', 'bb')) def test_get_fieldstructure(self): "Test get_fieldstructure" # No nested fields ndtype = np.dtype([('A', '|S3'), ('B', float)]) test = get_fieldstructure(ndtype) assert_equal(test, {'A':[], 'B':[]}) # One 1-nested field ndtype = np.dtype([('A', int), ('B', [('BA', float), ('BB', '|S1')])]) test = get_fieldstructure(ndtype) assert_equal(test, {'A': [], 'B': [], 'BA':['B', ], 'BB':['B']}) # One 2-nested fields ndtype = np.dtype([('A', int), ('B', [('BA', int), ('BB', [('BBA', int), ('BBB', int)])])]) test = get_fieldstructure(ndtype) control = {'A': [], 'B': [], 'BA': ['B'], 'BB': ['B'], 'BBA': ['B', 'BB'], 'BBB': ['B', 'BB']} assert_equal(test, control) def test_find_duplicates(self): "Test find_duplicates" a = ma.array([(2, (2., 'B')), (1, (2., 'B')), (2, (2., 'B')), (1, (1., 'B')), (2, (2., 'B')), (2, (2., 'C'))], mask=[(0, (0, 0)), (0, (0, 0)), (0, (0, 0)), (0, (0, 0)), (1, (0, 0)), (0, (1, 0))], dtype=[('A', int), ('B', [('BA', float), ('BB', '|S1')])]) # test = find_duplicates(a, ignoremask=False, return_index=True) control = [0, 2] assert_equal(sorted(test[-1]), control) assert_equal(test[0], a[test[-1]]) # test = find_duplicates(a, key='A', return_index=True) control = [0, 1, 2, 3, 5] assert_equal(sorted(test[-1]), control) assert_equal(test[0], a[test[-1]]) # test = find_duplicates(a, key='B', return_index=True) control = [0, 1, 2, 4] assert_equal(sorted(test[-1]), control) assert_equal(test[0], a[test[-1]]) # test = find_duplicates(a, key='BA', return_index=True) control = [0, 1, 2, 4] assert_equal(sorted(test[-1]), control) assert_equal(test[0], a[test[-1]]) # test = find_duplicates(a, key='BB', return_index=True) control = [0, 1, 2, 3, 4] assert_equal(sorted(test[-1]), control) assert_equal(test[0], a[test[-1]]) def test_find_duplicates_ignoremask(self): "Test the ignoremask option of find_duplicates" ndtype = [('a', int)] a = ma.array([1, 1, 1, 2, 2, 3, 3], mask=[0, 0, 1, 0, 0, 0, 1]).view(ndtype) test = find_duplicates(a, ignoremask=True, return_index=True) control = [0, 1, 3, 4] assert_equal(sorted(test[-1]), control) assert_equal(test[0], a[test[-1]]) # test = find_duplicates(a, ignoremask=False, return_index=True) control = [0, 1, 2, 3, 4, 6] assert_equal(sorted(test[-1]), control) assert_equal(test[0], a[test[-1]]) class TestRecursiveFillFields(TestCase): """ Test recursive_fill_fields. """ def test_simple_flexible(self): "Test recursive_fill_fields on flexible-array" a = np.array([(1, 10.), (2, 20.)], dtype=[('A', int), ('B', float)]) b = np.zeros((3,), dtype=a.dtype) test = recursive_fill_fields(a, b) control = np.array([(1, 10.), (2, 20.), (0, 0.)], dtype=[('A', int), ('B', float)]) assert_equal(test, control) # def test_masked_flexible(self): "Test recursive_fill_fields on masked flexible-array" a = ma.array([(1, 10.), (2, 20.)], mask=[(0, 1), (1, 0)], dtype=[('A', int), ('B', float)]) b = ma.zeros((3,), dtype=a.dtype) test = recursive_fill_fields(a, b) control = ma.array([(1, 10.), (2, 20.), (0, 0.)], mask=[(0, 1), (1, 0), (0, 0)], dtype=[('A', int), ('B', float)]) assert_equal(test, control) # class TestMergeArrays(TestCase): """ Test merge_arrays """ def setUp(self): x = np.array([1, 2, ]) y = np.array([10, 20, 30]) z = np.array([('A', 1.), ('B', 2.)], dtype=[('A', '|S3'), ('B', float)]) w = np.array([(1, (2, 3.0)), (4, (5, 6.0))], dtype=[('a', int), ('b', [('ba', float), ('bb', int)])]) self.data = (w, x, y, z) # def test_solo(self): "Test merge_arrays on a single array." (_, x, _, z) = self.data # test = merge_arrays(x) control = np.array([(1,), (2,)], dtype=[('f0', int)]) assert_equal(test, control) test = merge_arrays((x,)) assert_equal(test, control) # test = merge_arrays(z, flatten=False) assert_equal(test, z) test = merge_arrays(z, flatten=True) assert_equal(test, z) # def test_solo_w_flatten(self): "Test merge_arrays on a single array w & w/o flattening" w = self.data[0] test = merge_arrays(w, flatten=False) assert_equal(test, w) # test = merge_arrays(w, flatten=True) control = np.array([(1, 2, 3.0), (4, 5, 6.0)], dtype=[('a', int), ('ba', float), ('bb', int)]) assert_equal(test, control) # def test_standard(self): "Test standard & standard" # Test merge arrays (_, x, y, _) = self.data test = merge_arrays((x, y), usemask=False) control = np.array([(1, 10), (2, 20), (-1, 30)], dtype=[('f0', int), ('f1', int)]) assert_equal(test, control) # test = merge_arrays((x, y), usemask=True) control = ma.array([(1, 10), (2, 20), (-1, 30)], mask=[(0, 0), (0, 0), (1, 0)], dtype=[('f0', int), ('f1', int)]) assert_equal(test, control) assert_equal(test.mask, control.mask) # def test_flatten(self): "Test standard & flexible" (_, x, _, z) = self.data test = merge_arrays((x, z), flatten=True) control = np.array([(1, 'A', 1.), (2, 'B', 2.)], dtype=[('f0', int), ('A', '|S3'), ('B', float)]) assert_equal(test, control) # test = merge_arrays((x, z), flatten=False) control = np.array([(1, ('A', 1.)), (2, ('B', 2.))], dtype=[('f0', int), ('f1', [('A', '|S3'), ('B', float)])]) assert_equal(test, control) # def test_flatten_wflexible(self): "Test flatten standard & nested" (w, x, _, _) = self.data test = merge_arrays((x, w), flatten=True) control = np.array([(1, 1, 2, 3.0), (2, 4, 5, 6.0)], dtype=[('f0', int), ('a', int), ('ba', float), ('bb', int)]) assert_equal(test, control) # test = merge_arrays((x, w), flatten=False) controldtype = dtype = [('f0', int), ('f1', [('a', int), ('b', [('ba', float), ('bb', int)])])] control = np.array([(1., (1, (2, 3.0))), (2, (4, (5, 6.0)))], dtype=controldtype) # def test_wmasked_arrays(self): "Test merge_arrays masked arrays" (_, x, _, _) = self.data mx = ma.array([1, 2, 3], mask=[1, 0, 0]) test = merge_arrays((x, mx), usemask=True) control = ma.array([(1, 1), (2, 2), (-1, 3)], mask=[(0, 1), (0, 0), (1, 0)], dtype=[('f0', int), ('f1', int)]) assert_equal(test, control) test = merge_arrays((x, mx), usemask=True, asrecarray=True) assert_equal(test, control) assert_(isinstance(test, MaskedRecords)) # def test_w_singlefield(self): "Test single field" test = merge_arrays((np.array([1, 2]).view([('a', int)]), np.array([10., 20., 30.])),) control = ma.array([(1, 10.), (2, 20.), (-1, 30.)], mask=[(0, 0), (0, 0), (1, 0)], dtype=[('a', int), ('f1', float)]) assert_equal(test, control) # def test_w_shorter_flex(self): "Test merge_arrays w/ a shorter flexndarray." z = self.data[-1] test = merge_arrays((z, np.array([10, 20, 30]).view([('C', int)]))) control = np.array([('A', 1., 10), ('B', 2., 20), ('-1', -1, 20)], dtype=[('A', '|S3'), ('B', float), ('C', int)]) # def test_singlerecord(self): (_, x, y, z) = self.data test = merge_arrays((x[0], y[0], z[0]), usemask=False) control = np.array([(1, 10, ('A', 1))], dtype=[('f0', int), ('f1', int), ('f2', [('A', '|S3'), ('B', float)])]) assert_equal(test, control) class TestAppendFields(TestCase): """ Test append_fields """ def setUp(self): x = np.array([1, 2, ]) y = np.array([10, 20, 30]) z = np.array([('A', 1.), ('B', 2.)], dtype=[('A', '|S3'), ('B', float)]) w = np.array([(1, (2, 3.0)), (4, (5, 6.0))], dtype=[('a', int), ('b', [('ba', float), ('bb', int)])]) self.data = (w, x, y, z) # def test_append_single(self): "Test simple case" (_, x, _, _) = self.data test = append_fields(x, 'A', data=[10, 20, 30]) control = ma.array([(1, 10), (2, 20), (-1, 30)], mask=[(0, 0), (0, 0), (1, 0)], dtype=[('f0', int), ('A', int)],) assert_equal(test, control) # def test_append_double(self): "Test simple case" (_, x, _, _) = self.data test = append_fields(x, ('A', 'B'), data=[[10, 20, 30], [100, 200]]) control = ma.array([(1, 10, 100), (2, 20, 200), (-1, 30, -1)], mask=[(0, 0, 0), (0, 0, 0), (1, 0, 1)], dtype=[('f0', int), ('A', int), ('B', int)],) assert_equal(test, control) # def test_append_on_flex(self): "Test append_fields on flexible type arrays" z = self.data[-1] test = append_fields(z, 'C', data=[10, 20, 30]) control = ma.array([('A', 1., 10), ('B', 2., 20), (-1, -1., 30)], mask=[(0, 0, 0), (0, 0, 0), (1, 1, 0)], dtype=[('A', '|S3'), ('B', float), ('C', int)],) assert_equal(test, control) # def test_append_on_nested(self): "Test append_fields on nested fields" w = self.data[0] test = append_fields(w, 'C', data=[10, 20, 30]) control = ma.array([(1, (2, 3.0), 10), (4, (5, 6.0), 20), (-1, (-1, -1.), 30)], mask=[(0, (0, 0), 0), (0, (0, 0), 0), (1, (1, 1), 0)], dtype=[('a', int), ('b', [('ba', float), ('bb', int)]), ('C', int)],) assert_equal(test, control) class TestStackArrays(TestCase): """ Test stack_arrays """ def setUp(self): x = np.array([1, 2, ]) y = np.array([10, 20, 30]) z = np.array([('A', 1.), ('B', 2.)], dtype=[('A', '|S3'), ('B', float)]) w = np.array([(1, (2, 3.0)), (4, (5, 6.0))], dtype=[('a', int), ('b', [('ba', float), ('bb', int)])]) self.data = (w, x, y, z) # def test_solo(self): "Test stack_arrays on single arrays" (_, x, _, _) = self.data test = stack_arrays((x,)) assert_equal(test, x) self.assertTrue(test is x) # test = stack_arrays(x) assert_equal(test, x) self.assertTrue(test is x) # def test_unnamed_fields(self): "Tests combinations of arrays w/o named fields" (_, x, y, _) = self.data # test = stack_arrays((x, x), usemask=False) control = np.array([1, 2, 1, 2]) assert_equal(test, control) # test = stack_arrays((x, y), usemask=False) control = np.array([1, 2, 10, 20, 30]) assert_equal(test, control) # test = stack_arrays((y, x), usemask=False) control = np.array([10, 20, 30, 1, 2]) assert_equal(test, control) # def test_unnamed_and_named_fields(self): "Test combination of arrays w/ & w/o named fields" (_, x, _, z) = self.data # test = stack_arrays((x, z)) control = ma.array([(1, -1, -1), (2, -1, -1), (-1, 'A', 1), (-1, 'B', 2)], mask=[(0, 1, 1), (0, 1, 1), (1, 0, 0), (1, 0, 0)], dtype=[('f0', int), ('A', '|S3'), ('B', float)]) assert_equal(test, control) assert_equal(test.mask, control.mask) # test = stack_arrays((z, x)) control = ma.array([('A', 1, -1), ('B', 2, -1), (-1, -1, 1), (-1, -1, 2), ], mask=[(0, 0, 1), (0, 0, 1), (1, 1, 0), (1, 1, 0)], dtype=[('A', '|S3'), ('B', float), ('f2', int)]) assert_equal(test, control) assert_equal(test.mask, control.mask) # test = stack_arrays((z, z, x)) control = ma.array([('A', 1, -1), ('B', 2, -1), ('A', 1, -1), ('B', 2, -1), (-1, -1, 1), (-1, -1, 2), ], mask=[(0, 0, 1), (0, 0, 1), (0, 0, 1), (0, 0, 1), (1, 1, 0), (1, 1, 0)], dtype=[('A', '|S3'), ('B', float), ('f2', int)]) assert_equal(test, control) # def test_matching_named_fields(self): "Test combination of arrays w/ matching field names" (_, x, _, z) = self.data zz = np.array([('a', 10., 100.), ('b', 20., 200.), ('c', 30., 300.)], dtype=[('A', '|S3'), ('B', float), ('C', float)]) test = stack_arrays((z, zz)) control = ma.array([('A', 1, -1), ('B', 2, -1), ('a', 10., 100.), ('b', 20., 200.), ('c', 30., 300.)], dtype=[('A', '|S3'), ('B', float), ('C', float)], mask=[(0, 0, 1), (0, 0, 1), (0, 0, 0), (0, 0, 0), (0, 0, 0)]) assert_equal(test, control) assert_equal(test.mask, control.mask) # test = stack_arrays((z, zz, x)) ndtype = [('A', '|S3'), ('B', float), ('C', float), ('f3', int)] control = ma.array([('A', 1, -1, -1), ('B', 2, -1, -1), ('a', 10., 100., -1), ('b', 20., 200., -1), ('c', 30., 300., -1), (-1, -1, -1, 1), (-1, -1, -1, 2)], dtype=ndtype, mask=[(0, 0, 1, 1), (0, 0, 1, 1), (0, 0, 0, 1), (0, 0, 0, 1), (0, 0, 0, 1), (1, 1, 1, 0), (1, 1, 1, 0)]) assert_equal(test, control) assert_equal(test.mask, control.mask) def test_defaults(self): "Test defaults: no exception raised if keys of defaults are not fields." (_, _, _, z) = self.data zz = np.array([('a', 10., 100.), ('b', 20., 200.), ('c', 30., 300.)], dtype=[('A', '|S3'), ('B', float), ('C', float)]) defaults = {'A':'???', 'B':-999., 'C':-9999., 'D':-99999.} test = stack_arrays((z, zz), defaults=defaults) control = ma.array([('A', 1, -9999.), ('B', 2, -9999.), ('a', 10., 100.), ('b', 20., 200.), ('c', 30., 300.)], dtype=[('A', '|S3'), ('B', float), ('C', float)], mask=[(0, 0, 1), (0, 0, 1), (0, 0, 0), (0, 0, 0), (0, 0, 0)]) assert_equal(test, control) assert_equal(test.data, control.data) assert_equal(test.mask, control.mask) def test_autoconversion(self): "Tests autoconversion" adtype = [('A', int), ('B', bool), ('C', float)] a = ma.array([(1, 2, 3)], mask=[(0, 1, 0)], dtype=adtype) bdtype = [('A', int), ('B', float), ('C', float)] b = ma.array([(4, 5, 6)], dtype=bdtype) control = ma.array([(1, 2, 3), (4, 5, 6)], mask=[(0, 1, 0), (0, 0, 0)], dtype=bdtype) test = stack_arrays((a, b), autoconvert=True) assert_equal(test, control) assert_equal(test.mask, control.mask) try: test = stack_arrays((a, b), autoconvert=False) except TypeError: pass else: raise AssertionError def test_checktitles(self): "Test using titles in the field names" adtype = [(('a', 'A'), int), (('b', 'B'), bool), (('c', 'C'), float)] a = ma.array([(1, 2, 3)], mask=[(0, 1, 0)], dtype=adtype) bdtype = [(('a', 'A'), int), (('b', 'B'), bool), (('c', 'C'), float)] b = ma.array([(4, 5, 6)], dtype=bdtype) test = stack_arrays((a, b)) control = ma.array([(1, 2, 3), (4, 5, 6)], mask=[(0, 1, 0), (0, 0, 0)], dtype=bdtype) assert_equal(test, control) assert_equal(test.mask, control.mask) class TestJoinBy(TestCase): def setUp(self): self.a = np.array(list(zip(np.arange(10), np.arange(50, 60), np.arange(100, 110))), dtype=[('a', int), ('b', int), ('c', int)]) self.b = np.array(list(zip(np.arange(5, 15), np.arange(65, 75), np.arange(100, 110))), dtype=[('a', int), ('b', int), ('d', int)]) # def test_inner_join(self): "Basic test of join_by" a, b = self.a, self.b # test = join_by('a', a, b, jointype='inner') control = np.array([(5, 55, 65, 105, 100), (6, 56, 66, 106, 101), (7, 57, 67, 107, 102), (8, 58, 68, 108, 103), (9, 59, 69, 109, 104)], dtype=[('a', int), ('b1', int), ('b2', int), ('c', int), ('d', int)]) assert_equal(test, control) def test_join(self): a, b = self.a, self.b # test = join_by(('a', 'b'), a, b) control = np.array([(5, 55, 105, 100), (6, 56, 106, 101), (7, 57, 107, 102), (8, 58, 108, 103), (9, 59, 109, 104)], dtype=[('a', int), ('b', int), ('c', int), ('d', int)]) def test_outer_join(self): a, b = self.a, self.b # test = join_by(('a', 'b'), a, b, 'outer') control = ma.array([(0, 50, 100, -1), (1, 51, 101, -1), (2, 52, 102, -1), (3, 53, 103, -1), (4, 54, 104, -1), (5, 55, 105, -1), (5, 65, -1, 100), (6, 56, 106, -1), (6, 66, -1, 101), (7, 57, 107, -1), (7, 67, -1, 102), (8, 58, 108, -1), (8, 68, -1, 103), (9, 59, 109, -1), (9, 69, -1, 104), (10, 70, -1, 105), (11, 71, -1, 106), (12, 72, -1, 107), (13, 73, -1, 108), (14, 74, -1, 109)], mask=[(0, 0, 0, 1), (0, 0, 0, 1), (0, 0, 0, 1), (0, 0, 0, 1), (0, 0, 0, 1), (0, 0, 0, 1), (0, 0, 1, 0), (0, 0, 0, 1), (0, 0, 1, 0), (0, 0, 0, 1), (0, 0, 1, 0), (0, 0, 0, 1), (0, 0, 1, 0), (0, 0, 0, 1), (0, 0, 1, 0), (0, 0, 1, 0), (0, 0, 1, 0), (0, 0, 1, 0), (0, 0, 1, 0), (0, 0, 1, 0)], dtype=[('a', int), ('b', int), ('c', int), ('d', int)]) assert_equal(test, control) def test_leftouter_join(self): a, b = self.a, self.b # test = join_by(('a', 'b'), a, b, 'leftouter') control = ma.array([(0, 50, 100, -1), (1, 51, 101, -1), (2, 52, 102, -1), (3, 53, 103, -1), (4, 54, 104, -1), (5, 55, 105, -1), (6, 56, 106, -1), (7, 57, 107, -1), (8, 58, 108, -1), (9, 59, 109, -1)], mask=[(0, 0, 0, 1), (0, 0, 0, 1), (0, 0, 0, 1), (0, 0, 0, 1), (0, 0, 0, 1), (0, 0, 0, 1), (0, 0, 0, 1), (0, 0, 0, 1), (0, 0, 0, 1), (0, 0, 0, 1)], dtype=[('a', int), ('b', int), ('c', int), ('d', int)]) class TestJoinBy2(TestCase): @classmethod def setUp(cls): cls.a = np.array(list(zip(np.arange(10), np.arange(50, 60), np.arange(100, 110))), dtype=[('a', int), ('b', int), ('c', int)]) cls.b = np.array(list(zip(np.arange(10), np.arange(65, 75), np.arange(100, 110))), dtype=[('a', int), ('b', int), ('d', int)]) def test_no_r1postfix(self): "Basic test of join_by no_r1postfix" a, b = self.a, self.b test = join_by('a', a, b, r1postfix='', r2postfix='2', jointype='inner') control = np.array([(0, 50, 65, 100, 100), (1, 51, 66, 101, 101), (2, 52, 67, 102, 102), (3, 53, 68, 103, 103), (4, 54, 69, 104, 104), (5, 55, 70, 105, 105), (6, 56, 71, 106, 106), (7, 57, 72, 107, 107), (8, 58, 73, 108, 108), (9, 59, 74, 109, 109)], dtype=[('a', int), ('b', int), ('b2', int), ('c', int), ('d', int)]) assert_equal(test, control) def test_no_postfix(self): self.assertRaises(ValueError, join_by, 'a', self.a, self.b, r1postfix='', r2postfix='') def test_no_r2postfix(self): "Basic test of join_by no_r2postfix" a, b = self.a, self.b test = join_by('a', a, b, r1postfix='1', r2postfix='', jointype='inner') control = np.array([(0, 50, 65, 100, 100), (1, 51, 66, 101, 101), (2, 52, 67, 102, 102), (3, 53, 68, 103, 103), (4, 54, 69, 104, 104), (5, 55, 70, 105, 105), (6, 56, 71, 106, 106), (7, 57, 72, 107, 107), (8, 58, 73, 108, 108), (9, 59, 74, 109, 109)], dtype=[('a', int), ('b1', int), ('b', int), ('c', int), ('d', int)]) assert_equal(test, control) def test_two_keys_two_vars(self): a = np.array(list(zip(np.tile([10, 11], 5), np.repeat(np.arange(5), 2), np.arange(50, 60), np.arange(10, 20))), dtype=[('k', int), ('a', int), ('b', int), ('c', int)]) b = np.array(list(zip(np.tile([10, 11], 5), np.repeat(np.arange(5), 2), np.arange(65, 75), np.arange(0, 10))), dtype=[('k', int), ('a', int), ('b', int), ('c', int)]) control = np.array([(10, 0, 50, 65, 10, 0), (11, 0, 51, 66, 11, 1), (10, 1, 52, 67, 12, 2), (11, 1, 53, 68, 13, 3), (10, 2, 54, 69, 14, 4), (11, 2, 55, 70, 15, 5), (10, 3, 56, 71, 16, 6), (11, 3, 57, 72, 17, 7), (10, 4, 58, 73, 18, 8), (11, 4, 59, 74, 19, 9)], dtype=[('k', int), ('a', int), ('b1', int), ('b2', int), ('c1', int), ('c2', int)]) test = join_by(['a', 'k'], a, b, r1postfix='1', r2postfix='2', jointype='inner') assert_equal(test.dtype, control.dtype) assert_equal(test, control) if __name__ == '__main__': run_module_suite() numpy-1.8.2/numpy/lib/tests/test_financial.py0000664000175100017510000001423712370216243022450 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function from numpy.testing import * import numpy as np class TestFinancial(TestCase): def test_rate(self): assert_almost_equal(np.rate(10, 0, -3500, 10000), 0.1107, 4) def test_irr(self): 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), -127128.17, 2) def test_fv(self): assert_almost_equal(np.fv(0.075, 20, -2000, 0, 0), 86609.36, 2) def test_pmt(self): assert_almost_equal(np.pmt(0.08/12, 5*12, 15000), -304.146, 3) def test_ppmt(self): np.round(np.ppmt(0.1/12, 1, 60, 55000), 2) == 710.25 def test_ipmt(self): np.round(np.ipmt(0.1/12, 1, 24, 2000), 2) == 16.67 def test_nper(self): assert_almost_equal(np.nper(0.075, -2000, 0, 100000.), 21.54, 2) def test_nper2(self): assert_almost_equal(np.nper(0.0, -2000, 0, 100000.), 50.0, 1) def test_npv(self): assert_almost_equal(np.npv(0.05, [-15000, 1500, 2500, 3500, 4500, 6000]), 122.89, 2) def test_mirr(self): val = [-4500, -800, 800, 800, 600, 600, 800, 800, 700, 3000] assert_almost_equal(np.mirr(val, 0.08, 0.055), 0.0666, 4) val = [-120000, 39000, 30000, 21000, 37000, 46000] assert_almost_equal(np.mirr(val, 0.10, 0.12), 0.126094, 6) val = [100, 200, -50, 300, -200] assert_almost_equal(np.mirr(val, 0.05, 0.06), 0.3428, 4) val = [39000, 30000, 21000, 37000, 46000] assert_(np.isnan(np.mirr(val, 0.10, 0.12))) def test_when(self): #begin assert_almost_equal(np.rate(10, 20, -3500, 10000, 1), np.rate(10, 20, -3500, 10000, 'begin'), 4) #end assert_almost_equal(np.rate(10, 20, -3500, 10000), np.rate(10, 20, -3500, 10000, 'end'), 4) assert_almost_equal(np.rate(10, 20, -3500, 10000, 0), np.rate(10, 20, -3500, 10000, 'end'), 4) # begin assert_almost_equal(np.pv(0.07, 20, 12000, 0, 1), np.pv(0.07, 20, 12000, 0, 'begin'), 2) # end assert_almost_equal(np.pv(0.07, 20, 12000, 0), np.pv(0.07, 20, 12000, 0, 'end'), 2) assert_almost_equal(np.pv(0.07, 20, 12000, 0, 0), np.pv(0.07, 20, 12000, 0, 'end'), 2) # begin assert_almost_equal(np.fv(0.075, 20, -2000, 0, 1), np.fv(0.075, 20, -2000, 0, 'begin'), 4) # end assert_almost_equal(np.fv(0.075, 20, -2000, 0), np.fv(0.075, 20, -2000, 0, 'end'), 4) assert_almost_equal(np.fv(0.075, 20, -2000, 0, 0), np.fv(0.075, 20, -2000, 0, 'end'), 4) # begin assert_almost_equal(np.pmt(0.08/12, 5*12, 15000., 0, 1), np.pmt(0.08/12, 5*12, 15000., 0, 'begin'), 4) # end assert_almost_equal(np.pmt(0.08/12, 5*12, 15000., 0), np.pmt(0.08/12, 5*12, 15000., 0, 'end'), 4) assert_almost_equal(np.pmt(0.08/12, 5*12, 15000., 0, 0), np.pmt(0.08/12, 5*12, 15000., 0, 'end'), 4) # begin assert_almost_equal(np.ppmt(0.1/12, 1, 60, 55000, 0, 1), np.ppmt(0.1/12, 1, 60, 55000, 0, 'begin'), 4) # end assert_almost_equal(np.ppmt(0.1/12, 1, 60, 55000, 0), np.ppmt(0.1/12, 1, 60, 55000, 0, 'end'), 4) assert_almost_equal(np.ppmt(0.1/12, 1, 60, 55000, 0, 0), np.ppmt(0.1/12, 1, 60, 55000, 0, 'end'), 4) # begin assert_almost_equal(np.ipmt(0.1/12, 1, 24, 2000, 0, 1), np.ipmt(0.1/12, 1, 24, 2000, 0, 'begin'), 4) # end assert_almost_equal(np.ipmt(0.1/12, 1, 24, 2000, 0), np.ipmt(0.1/12, 1, 24, 2000, 0, 'end'), 4) assert_almost_equal(np.ipmt(0.1/12, 1, 24, 2000, 0, 0), np.ipmt(0.1/12, 1, 24, 2000, 0, 'end'), 4) # begin assert_almost_equal(np.nper(0.075, -2000, 0, 100000., 1), np.nper(0.075, -2000, 0, 100000., 'begin'), 4) # end assert_almost_equal(np.nper(0.075, -2000, 0, 100000.), np.nper(0.075, -2000, 0, 100000., 'end'), 4) assert_almost_equal(np.nper(0.075, -2000, 0, 100000., 0), np.nper(0.075, -2000, 0, 100000., 'end'), 4) def test_broadcast(self): assert_almost_equal(np.nper(0.075, -2000, 0, 100000., [0, 1]), [ 21.5449442, 20.76156441], 4) assert_almost_equal(np.ipmt(0.1/12, list(range(5)), 24, 2000), [-17.29165168, -16.66666667, -16.03647345, -15.40102862, -14.76028842], 4) assert_almost_equal(np.ppmt(0.1/12, list(range(5)), 24, 2000), [-74.998201, -75.62318601, -76.25337923, -76.88882405, -77.52956425], 4) assert_almost_equal(np.ppmt(0.1/12, list(range(5)), 24, 2000, 0, [0, 0, 1, 'end', 'begin']), [-74.998201, -75.62318601, -75.62318601, -76.88882405, -76.88882405], 4) if __name__ == "__main__": run_module_suite() numpy-1.8.2/numpy/lib/tests/test_function_base.py0000664000175100017510000015432012370216243023341 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function import warnings 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 ) from numpy.random import rand from numpy.lib import * from numpy.compat import long class TestAny(TestCase): def test_basic(self): y1 = [0, 0, 1, 0] y2 = [0, 0, 0, 0] y3 = [1, 0, 1, 0] assert_(np.any(y1)) assert_(np.any(y3)) assert_(not np.any(y2)) def test_nd(self): y1 = [[0, 0, 0], [0, 1, 0], [1, 1, 0]] assert_(np.any(y1)) assert_array_equal(np.sometrue(y1, axis=0), [1, 1, 0]) assert_array_equal(np.sometrue(y1, axis=1), [0, 1, 1]) class TestAll(TestCase): def test_basic(self): y1 = [0, 1, 1, 0] y2 = [0, 0, 0, 0] y3 = [1, 1, 1, 1] assert_(not np.all(y1)) assert_(np.all(y3)) assert_(not np.all(y2)) assert_(np.all(~np.array(y2))) def test_nd(self): y1 = [[0, 0, 1], [0, 1, 1], [1, 1, 1]] assert_(not np.all(y1)) assert_array_equal(np.alltrue(y1, axis=0), [0, 0, 1]) assert_array_equal(np.alltrue(y1, axis=1), [0, 0, 1]) class TestCopy(TestCase): def test_basic(self): a = np.array([[1, 2], [3, 4]]) a_copy = np.copy(a) assert_array_equal(a, a_copy) a_copy[0, 0] = 10 assert_equal(a[0, 0], 1) assert_equal(a_copy[0, 0], 10) def test_order(self): # It turns out that people rely on np.copy() preserving order by # default; changing this broke scikit-learn: # https://github.com/scikit-learn/scikit-learn/commit/7842748cf777412c506a8c0ed28090711d3a3783 a = np.array([[1, 2], [3, 4]]) assert_(a.flags.c_contiguous) assert_(not a.flags.f_contiguous) a_fort = np.array([[1, 2], [3, 4]], order="F") assert_(not a_fort.flags.c_contiguous) assert_(a_fort.flags.f_contiguous) a_copy = np.copy(a) assert_(a_copy.flags.c_contiguous) assert_(not a_copy.flags.f_contiguous) a_fort_copy = np.copy(a_fort) assert_(not a_fort_copy.flags.c_contiguous) assert_(a_fort_copy.flags.f_contiguous) class TestAverage(TestCase): def test_basic(self): y1 = np.array([1, 2, 3]) assert_(average(y1, axis=0) == 2.) y2 = np.array([1., 2., 3.]) assert_(average(y2, axis=0) == 2.) y3 = [0., 0., 0.] assert_(average(y3, axis=0) == 0.) y4 = np.ones((4, 4)) y4[0, 1] = 0 y4[1, 0] = 2 assert_almost_equal(y4.mean(0), average(y4, 0)) assert_almost_equal(y4.mean(1), average(y4, 1)) y5 = rand(5, 5) assert_almost_equal(y5.mean(0), average(y5, 0)) assert_almost_equal(y5.mean(1), average(y5, 1)) y6 = np.matrix(rand(5, 5)) assert_array_equal(y6.mean(0), average(y6, 0)) def test_weights(self): y = np.arange(10) w = np.arange(10) actual = average(y, weights=w) desired = (np.arange(10) ** 2).sum()*1. / np.arange(10).sum() assert_almost_equal(actual, desired) y1 = np.array([[1, 2, 3], [4, 5, 6]]) w0 = [1, 2] actual = average(y1, weights=w0, axis=0) desired = np.array([3., 4., 5.]) assert_almost_equal(actual, desired) w1 = [0, 0, 1] actual = average(y1, weights=w1, axis=1) desired = np.array([3., 6.]) assert_almost_equal(actual, desired) # This should raise an error. Can we test for that ? # assert_equal(average(y1, weights=w1), 9./2.) # 2D Case w2 = [[0, 0, 1], [0, 0, 2]] desired = np.array([3., 6.]) assert_array_equal(average(y1, weights=w2, axis=1), desired) assert_equal(average(y1, weights=w2), 5.) def test_returned(self): y = np.array([[1, 2, 3], [4, 5, 6]]) # No weights avg, scl = average(y, returned=True) assert_equal(scl, 6.) avg, scl = average(y, 0, returned=True) assert_array_equal(scl, np.array([2., 2., 2.])) avg, scl = average(y, 1, returned=True) assert_array_equal(scl, np.array([3., 3.])) # With weights w0 = [1, 2] avg, scl = average(y, weights=w0, axis=0, returned=True) assert_array_equal(scl, np.array([3., 3., 3.])) w1 = [1, 2, 3] avg, scl = average(y, weights=w1, axis=1, returned=True) assert_array_equal(scl, np.array([6., 6.])) w2 = [[0, 0, 1], [1, 2, 3]] avg, scl = average(y, weights=w2, axis=1, returned=True) assert_array_equal(scl, np.array([1., 6.])) class TestSelect(TestCase): def _select(self, cond, values, default=0): output = [] for m in range(len(cond)): output += [V[m] for V, C in zip(values, cond) if C[m]] or [default] 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])] assert_array_equal(select(conditions, choices, default=15), self._select(conditions, choices, default=15)) assert_equal(len(choices), 3) assert_equal(len(conditions), 3) class TestInsert(TestCase): def test_basic(self): a = [1, 2, 3] assert_equal(insert(a, 0, 1), [1, 1, 2, 3]) assert_equal(insert(a, 3, 1), [1, 2, 3, 1]) assert_equal(insert(a, [1, 1, 1], [1, 2, 3]), [1, 1, 2, 3, 2, 3]) assert_equal(insert(a, 1, [1, 2, 3]), [1, 1, 2, 3, 2, 3]) assert_equal(insert(a, [1, -1, 3], 9), [1, 9, 2, 9, 3, 9]) assert_equal(insert(a, slice(-1, None, -1), 9), [9, 1, 9, 2, 9, 3]) assert_equal(insert(a, [-1, 1, 3], [7, 8, 9]), [1, 8, 2, 7, 3, 9]) b = np.array([0, 1], dtype=np.float64) assert_equal(insert(b, 0, b[0]), [0., 0., 1.]) assert_equal(insert(b, [], []), b) # Bools will be treated differently in the future: #assert_equal(insert(a, np.array([True]*4), 9), [9,1,9,2,9,3,9]) with warnings.catch_warnings(record=True) as w: warnings.filterwarnings('always', '', FutureWarning) assert_equal(insert(a, np.array([True]*4), 9), [1, 9, 9, 9, 9, 2, 3]) assert_(w[0].category is FutureWarning) def test_multidim(self): a = [[1, 1, 1]] r = [[2, 2, 2], [1, 1, 1]] assert_equal(insert(a, 0, [1]), [1, 1, 1, 1]) assert_equal(insert(a, 0, [2, 2, 2], axis=0), r) assert_equal(insert(a, 0, 2, axis=0), r) assert_equal(insert(a, 2, 2, axis=1), [[1, 1, 2, 1]]) a = np.array([[1, 1], [2, 2], [3, 3]]) b = np.arange(1, 4).repeat(3).reshape(3, 3) c = np.concatenate((a[:, 0:1], np.arange(1, 4).repeat(3).reshape(3, 3).T, a[:, 1:2]), axis=1) assert_equal(insert(a, [1], [[1], [2], [3]], axis=1), b) assert_equal(insert(a, [1], [1, 2, 3], axis=1), c) # scalars behave differently, in this case exactly opposite: assert_equal(insert(a, 1, [1, 2, 3], axis=1), b) assert_equal(insert(a, 1, [[1], [2], [3]], axis=1), c) a = np.arange(4).reshape(2, 2) assert_equal(insert(a[:, :1], 1, a[:, 1], axis=1), a) assert_equal(insert(a[:1,:], 1, a[1,:], axis=0), a) # negative axis value a = np.arange(24).reshape((2, 3, 4)) assert_equal(insert(a, 1, a[:,:, 3], axis=-1), insert(a, 1, a[:,:, 3], axis=2)) assert_equal(insert(a, 1, a[:, 2,:], axis=-2), insert(a, 1, a[:, 2,:], axis=1)) # invalid axis value assert_raises(IndexError, insert, a, 1, a[:, 2,:], axis=3) assert_raises(IndexError, insert, a, 1, a[:, 2,:], axis=-4) def test_0d(self): # This is an error in the future a = np.array(1) with warnings.catch_warnings(record=True) as w: warnings.filterwarnings('always', '', DeprecationWarning) assert_equal(insert(a, [], 2, axis=0), np.array(2)) assert_(w[0].category is DeprecationWarning) def test_subclass(self): class SubClass(np.ndarray): pass a = np.arange(10).view(SubClass) assert_(isinstance(np.insert(a, 0, [0]), SubClass)) 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)) # This is an error in the future: a = np.array(1).view(SubClass) assert_(isinstance(np.insert(a, 0, [0]), SubClass)) def test_index_array_copied(self): x = np.array([1, 1, 1]) np.insert([0, 1, 2], x, [3, 4, 5]) assert_equal(x, np.array([1, 1, 1])) class TestAmax(TestCase): def test_basic(self): a = [3, 4, 5, 10, -3, -5, 6.0] assert_equal(np.amax(a), 10.0) b = [[3, 6.0, 9.0], [4, 10.0, 5.0], [8, 3.0, 2.0]] assert_equal(np.amax(b, axis=0), [8.0, 10.0, 9.0]) assert_equal(np.amax(b, axis=1), [9.0, 10.0, 8.0]) class TestAmin(TestCase): def test_basic(self): a = [3, 4, 5, 10, -3, -5, 6.0] assert_equal(np.amin(a), -5.0) b = [[3, 6.0, 9.0], [4, 10.0, 5.0], [8, 3.0, 2.0]] assert_equal(np.amin(b, axis=0), [3.0, 3.0, 2.0]) assert_equal(np.amin(b, axis=1), [3.0, 4.0, 2.0]) class TestPtp(TestCase): def test_basic(self): a = [3, 4, 5, 10, -3, -5, 6.0] assert_equal(np.ptp(a, axis=0), 15.0) b = [[3, 6.0, 9.0], [4, 10.0, 5.0], [8, 3.0, 2.0]] assert_equal(np.ptp(b, axis=0), [5.0, 7.0, 7.0]) assert_equal(np.ptp(b, axis= -1), [6.0, 6.0, 6.0]) class TestCumsum(TestCase): def test_basic(self): ba = [1, 2, 10, 11, 6, 5, 4] ba2 = [[1, 2, 3, 4], [5, 6, 7, 9], [10, 3, 4, 5]] for ctype in [np.int8, np.uint8, np.int16, np.uint16, np.int32, np.uint32, np.float32, np.float64, np.complex64, np.complex128]: a = np.array(ba, ctype) a2 = np.array(ba2, ctype) tgt = np.array([1, 3, 13, 24, 30, 35, 39], ctype) assert_array_equal(np.cumsum(a, axis=0), tgt) tgt = np.array([[1, 2, 3, 4], [6, 8, 10, 13], [16, 11, 14, 18]], ctype) assert_array_equal(np.cumsum(a2, axis=0), tgt) tgt = np.array([[1, 3, 6, 10], [5, 11, 18, 27], [10, 13, 17, 22]], ctype) assert_array_equal(np.cumsum(a2, axis=1), tgt) class TestProd(TestCase): def test_basic(self): ba = [1, 2, 10, 11, 6, 5, 4] ba2 = [[1, 2, 3, 4], [5, 6, 7, 9], [10, 3, 4, 5]] for ctype in [np.int16, np.uint16, np.int32, np.uint32, np.float32, np.float64, np.complex64, np.complex128]: a = np.array(ba, ctype) a2 = np.array(ba2, ctype) if ctype in ['1', 'b']: self.assertRaises(ArithmeticError, prod, a) self.assertRaises(ArithmeticError, prod, a2, 1) self.assertRaises(ArithmeticError, prod, a) else: assert_equal(np.prod(a, axis=0), 26400) assert_array_equal(np.prod(a2, axis=0), np.array([50, 36, 84, 180], ctype)) assert_array_equal(np.prod(a2, axis= -1), np.array([24, 1890, 600], ctype)) class TestCumprod(TestCase): def test_basic(self): ba = [1, 2, 10, 11, 6, 5, 4] ba2 = [[1, 2, 3, 4], [5, 6, 7, 9], [10, 3, 4, 5]] for ctype in [np.int16, np.uint16, np.int32, np.uint32, np.float32, np.float64, np.complex64, np.complex128]: a = np.array(ba, ctype) a2 = np.array(ba2, ctype) if ctype in ['1', 'b']: self.assertRaises(ArithmeticError, cumprod, a) self.assertRaises(ArithmeticError, cumprod, a2, 1) self.assertRaises(ArithmeticError, cumprod, a) else: assert_array_equal(np.cumprod(a, axis= -1), np.array([1, 2, 20, 220, 1320, 6600, 26400], ctype)) assert_array_equal(np.cumprod(a2, axis=0), np.array([[ 1, 2, 3, 4], [ 5, 12, 21, 36], [50, 36, 84, 180]], ctype)) assert_array_equal(np.cumprod(a2, axis= -1), np.array([[ 1, 2, 6, 24], [ 5, 30, 210, 1890], [10, 30, 120, 600]], ctype)) class TestDiff(TestCase): def test_basic(self): x = [1, 4, 6, 7, 12] out = np.array([3, 2, 1, 5]) out2 = np.array([-1, -1, 4]) out3 = np.array([0, 5]) assert_array_equal(diff(x), out) assert_array_equal(diff(x, n=2), out2) assert_array_equal(diff(x, n=3), out3) def test_nd(self): x = 20 * rand(10, 20, 30) out1 = x[:,:, 1:] - x[:,:, :-1] out2 = out1[:,:, 1:] - out1[:,:, :-1] out3 = x[1:,:,:] - x[:-1,:,:] out4 = out3[1:,:,:] - out3[:-1,:,:] assert_array_equal(diff(x), out1) assert_array_equal(diff(x, n=2), out2) assert_array_equal(diff(x, axis=0), out3) assert_array_equal(diff(x, n=2, axis=0), out4) class TestDelete(TestCase): def setUp(self): self.a = np.arange(5) self.nd_a = np.arange(5).repeat(2).reshape(1, 5, 2) def _check_inverse_of_slicing(self, indices): a_del = delete(self.a, indices) nd_a_del = delete(self.nd_a, indices, axis=1) msg = 'Delete failed for obj: %r' % indices # NOTE: The cast should be removed after warning phase for bools if not isinstance(indices, (slice, int, long, np.integer)): indices = np.asarray(indices, dtype=np.intp) indices = indices[(indices >= 0) & (indices < 5)] assert_array_equal(setxor1d(a_del, self.a[indices,]), self.a, err_msg=msg) xor = setxor1d(nd_a_del[0,:, 0], self.nd_a[0, indices, 0]) assert_array_equal(xor, self.nd_a[0,:, 0], err_msg=msg) def test_slices(self): lims = [-6, -2, 0, 1, 2, 4, 5] steps = [-3, -1, 1, 3] for start in lims: for stop in lims: for step in steps: s = slice(start, stop, step) self._check_inverse_of_slicing(s) def test_fancy(self): # Deprecation/FutureWarning tests should be kept after change. self._check_inverse_of_slicing(np.array([[0, 1], [2, 1]])) with warnings.catch_warnings(): warnings.filterwarnings('error', category=DeprecationWarning) assert_raises(DeprecationWarning, delete, self.a, [100]) assert_raises(DeprecationWarning, delete, self.a, [-100]) with warnings.catch_warnings(record=True) as w: warnings.filterwarnings('always', category=FutureWarning) self._check_inverse_of_slicing([0, -1, 2, 2]) obj = np.array([True, False, False], dtype=bool) self._check_inverse_of_slicing(obj) assert_(w[0].category is FutureWarning) assert_(w[1].category is FutureWarning) def test_single(self): self._check_inverse_of_slicing(0) self._check_inverse_of_slicing(-4) def test_0d(self): a = np.array(1) with warnings.catch_warnings(record=True) as w: warnings.filterwarnings('always', '', DeprecationWarning) assert_equal(delete(a, [], axis=0), a) assert_(w[0].category is DeprecationWarning) def test_subclass(self): class SubClass(np.ndarray): pass a = self.a.view(SubClass) assert_(isinstance(delete(a, 0), SubClass)) assert_(isinstance(delete(a, []), SubClass)) assert_(isinstance(delete(a, [0, 1]), SubClass)) assert_(isinstance(delete(a, slice(1, 2)), SubClass)) assert_(isinstance(delete(a, slice(1, -2)), SubClass)) class TestGradient(TestCase): def test_basic(self): v = [[1, 1], [3, 4]] x = np.array(v) dx = [np.array([[2., 3.], [2., 3.]]), np.array([[0., 0.], [1., 1.]])] assert_array_equal(gradient(x), dx) assert_array_equal(gradient(v), dx) def test_badargs(self): # for 2D array, gradient can take 0, 1, or 2 extra args x = np.array([[1, 1], [3, 4]]) assert_raises(SyntaxError, gradient, x, np.array([1., 1.]), np.array([1., 1.]), np.array([1., 1.])) def test_masked(self): # Make sure that gradient supports subclasses like masked arrays x = np.ma.array([[1, 1], [3, 4]]) assert_equal(type(gradient(x)[0]), type(x)) def test_datetime64(self): # Make sure gradient() can handle special types like datetime64 x = np.array(['1910-08-16', '1910-08-11', '1910-08-10', '1910-08-12', '1910-10-12', '1910-12-12', '1912-12-12'], dtype='datetime64[D]') dx = np.array([ -5, -3, 0, 31, 61, 396, 731], dtype='timedelta64[D]') assert_array_equal(gradient(x), dx) assert_(dx.dtype == np.dtype('timedelta64[D]')) def test_timedelta64(self): # Make sure gradient() can handle special types like timedelta64 x = np.array([-5, -3, 10, 12, 61, 321, 300], dtype='timedelta64[D]') dx = np.array([ 2, 7, 7, 25, 154, 119, -21], dtype='timedelta64[D]') assert_array_equal(gradient(x), dx) assert_(dx.dtype == np.dtype('timedelta64[D]')) class TestAngle(TestCase): def test_basic(self): x = [1 + 3j, np.sqrt(2) / 2.0 + 1j * np.sqrt(2) / 2, 1, 1j, -1, -1j, 1 - 3j, -1 + 3j] y = angle(x) yo = [np.arctan(3.0 / 1.0), np.arctan(1.0), 0, np.pi / 2, np.pi, -np.pi / 2.0, - np.arctan(3.0 / 1.0), np.pi - np.arctan(3.0 / 1.0)] z = angle(x, deg=1) zo = np.array(yo) * 180 / np.pi assert_array_almost_equal(y, yo, 11) assert_array_almost_equal(z, zo, 11) class TestTrimZeros(TestCase): """ only testing for integer splits. """ def test_basic(self): a = np.array([0, 0, 1, 2, 3, 4, 0]) res = trim_zeros(a) assert_array_equal(res, np.array([1, 2, 3, 4])) def test_leading_skip(self): a = np.array([0, 0, 1, 0, 2, 3, 4, 0]) res = trim_zeros(a) assert_array_equal(res, np.array([1, 0, 2, 3, 4])) def test_trailing_skip(self): a = np.array([0, 0, 1, 0, 2, 3, 0, 4, 0]) res = trim_zeros(a) assert_array_equal(res, np.array([1, 0, 2, 3, 0, 4])) class TestExtins(TestCase): def test_basic(self): a = np.array([1, 3, 2, 1, 2, 3, 3]) b = extract(a > 1, a) assert_array_equal(b, [3, 2, 2, 3, 3]) def test_place(self): a = np.array([1, 4, 3, 2, 5, 8, 7]) place(a, [0, 1, 0, 1, 0, 1, 0], [2, 4, 6]) assert_array_equal(a, [1, 2, 3, 4, 5, 6, 7]) def test_both(self): a = rand(10) mask = a > 0.5 ac = a.copy() c = extract(mask, a) place(a, mask, 0) place(a, mask, c) assert_array_equal(a, ac) class TestVectorize(TestCase): def test_simple(self): def addsubtract(a, b): if a > b: return a - b else: return a + b f = vectorize(addsubtract) r = f([0, 3, 6, 9], [1, 3, 5, 7]) assert_array_equal(r, [1, 6, 1, 2]) def test_scalar(self): def addsubtract(a, b): if a > b: return a - b else: return a + b f = vectorize(addsubtract) r = f([0, 3, 6, 9], 5) assert_array_equal(r, [5, 8, 1, 4]) def test_large(self): x = np.linspace(-3, 2, 10000) f = vectorize(lambda x: x) y = f(x) assert_array_equal(y, x) def test_ufunc(self): import math f = vectorize(math.cos) args = np.array([0, 0.5*np.pi, np.pi, 1.5*np.pi, 2*np.pi]) r1 = f(args) r2 = np.cos(args) assert_array_equal(r1, r2) def test_keywords(self): import math def foo(a, b=1): return a + b f = vectorize(foo) args = np.array([1, 2, 3]) r1 = f(args) r2 = np.array([2, 3, 4]) assert_array_equal(r1, r2) r1 = f(args, 2) r2 = np.array([3, 4, 5]) assert_array_equal(r1, r2) def test_keywords_no_func_code(self): # This needs to test a function that has keywords but # no func_code attribute, since otherwise vectorize will # inspect the func_code. import random try: f = vectorize(random.randrange) except: raise AssertionError() def test_keywords2_ticket_2100(self): r"""Test kwarg support: enhancement ticket 2100""" import math def foo(a, b=1): return a + b f = vectorize(foo) args = np.array([1, 2, 3]) r1 = f(a=args) r2 = np.array([2, 3, 4]) assert_array_equal(r1, r2) r1 = f(b=1, a=args) assert_array_equal(r1, r2) r1 = f(args, b=2) r2 = np.array([3, 4, 5]) assert_array_equal(r1, r2) def test_keywords3_ticket_2100(self): """Test excluded with mixed positional and kwargs: ticket 2100""" def mypolyval(x, p): _p = list(p) res = _p.pop(0) while _p: res = res*x + _p.pop(0) return res vpolyval = np.vectorize(mypolyval, excluded=['p', 1]) ans = [3, 6] assert_array_equal(ans, vpolyval(x=[0, 1], p=[1, 2, 3])) assert_array_equal(ans, vpolyval([0, 1], p=[1, 2, 3])) assert_array_equal(ans, vpolyval([0, 1], [1, 2, 3])) def test_keywords4_ticket_2100(self): """Test vectorizing function with no positional args.""" @vectorize def f(**kw): res = 1.0 for _k in kw: res *= kw[_k] return res assert_array_equal(f(a=[1, 2], b=[3, 4]), [3, 8]) def test_keywords5_ticket_2100(self): """Test vectorizing function with no kwargs args.""" @vectorize def f(*v): return np.prod(v) assert_array_equal(f([1, 2], [3, 4]), [3, 8]) def test_coverage1_ticket_2100(self): def foo(): return 1 f = vectorize(foo) assert_array_equal(f(), 1) def test_assigning_docstring(self): def foo(x): return x doc = "Provided documentation" f = vectorize(foo, doc=doc) assert_equal(f.__doc__, doc) def test_UnboundMethod_ticket_1156(self): """Regression test for issue 1156""" class Foo: b = 2 def bar(self, a): return a**self.b assert_array_equal(vectorize(Foo().bar)(np.arange(9)), np.arange(9)**2) assert_array_equal(vectorize(Foo.bar)(Foo(), np.arange(9)), np.arange(9)**2) def test_execution_order_ticket_1487(self): """Regression test for dependence on execution order: issue 1487""" f1 = vectorize(lambda x: x) res1a = f1(np.arange(3)) res1b = f1(np.arange(0.1, 3)) f2 = vectorize(lambda x: x) res2b = f2(np.arange(0.1, 3)) res2a = f2(np.arange(3)) assert_equal(res1a, res2a) assert_equal(res1b, res2b) def test_string_ticket_1892(self): """Test vectorization over strings: issue 1892.""" f = np.vectorize(lambda x:x) s = '0123456789'*10 assert_equal(s, f(s)) #z = f(np.array([s,s])) #assert_array_equal([s,s], f(s)) def test_cache(self): """Ensure that vectorized func called exactly once per argument.""" _calls = [0] @vectorize def f(x): _calls[0] += 1 return x**2 f.cache = True x = np.arange(5) assert_array_equal(f(x), x*x) assert_equal(_calls[0], len(x)) class TestDigitize(TestCase): def test_forward(self): x = np.arange(-6, 5) bins = np.arange(-5, 5) assert_array_equal(digitize(x, bins), np.arange(11)) def test_reverse(self): x = np.arange(5, -6, -1) bins = np.arange(5, -5, -1) assert_array_equal(digitize(x, bins), np.arange(11)) def test_random(self): x = rand(10) bin = np.linspace(x.min(), x.max(), 10) assert_(np.all(digitize(x, bin) != 0)) def test_right_basic(self): x = [1, 5, 4, 10, 8, 11, 0] bins = [1, 5, 10] default_answer = [1, 2, 1, 3, 2, 3, 0] assert_array_equal(digitize(x, bins), default_answer) right_answer = [0, 1, 1, 2, 2, 3, 0] assert_array_equal(digitize(x, bins, True), right_answer) def test_right_open(self): x = np.arange(-6, 5) bins = np.arange(-6, 4) assert_array_equal(digitize(x, bins, True), np.arange(11)) def test_right_open_reverse(self): x = np.arange(5, -6, -1) bins = np.arange(4, -6, -1) assert_array_equal(digitize(x, bins, True), np.arange(11)) def test_right_open_random(self): x = rand(10) bins = np.linspace(x.min(), x.max(), 10) assert_(np.all(digitize(x, bins, True) != 10)) class TestUnwrap(TestCase): def test_simple(self): #check that unwrap removes jumps greather that 2*pi assert_array_equal(unwrap([1, 1 + 2 * np.pi]), [1, 1]) #check that unwrap maintans continuity assert_(np.all(diff(unwrap(rand(10) * 100)) < np.pi)) class TestFilterwindows(TestCase): def test_hanning(self): #check symmetry w = hanning(10) assert_array_almost_equal(w, flipud(w), 7) #check known value assert_almost_equal(np.sum(w, axis=0), 4.500, 4) def test_hamming(self): #check symmetry w = hamming(10) assert_array_almost_equal(w, flipud(w), 7) #check known value assert_almost_equal(np.sum(w, axis=0), 4.9400, 4) def test_bartlett(self): #check symmetry w = bartlett(10) assert_array_almost_equal(w, flipud(w), 7) #check known value assert_almost_equal(np.sum(w, axis=0), 4.4444, 4) def test_blackman(self): #check symmetry w = blackman(10) assert_array_almost_equal(w, flipud(w), 7) #check known value assert_almost_equal(np.sum(w, axis=0), 3.7800, 4) class TestTrapz(TestCase): def test_simple(self): x = np.arange(-10, 10, .1) r = trapz(np.exp(-.5*x**2) / np.sqrt(2*np.pi), dx=0.1) #check integral of normal equals 1 assert_almost_equal(r, 1, 7) def test_ndim(self): x = np.linspace(0, 1, 3) y = np.linspace(0, 2, 8) z = np.linspace(0, 3, 13) wx = np.ones_like(x) * (x[1] - x[0]) wx[0] /= 2 wx[-1] /= 2 wy = np.ones_like(y) * (y[1] - y[0]) wy[0] /= 2 wy[-1] /= 2 wz = np.ones_like(z) * (z[1] - z[0]) wz[0] /= 2 wz[-1] /= 2 q = x[:, None, None] + y[None,:, None] + z[None, None,:] qx = (q * wx[:, None, None]).sum(axis=0) qy = (q * wy[None,:, None]).sum(axis=1) qz = (q * wz[None, None,:]).sum(axis=2) # n-d `x` r = trapz(q, x=x[:, None, None], axis=0) assert_almost_equal(r, qx) r = trapz(q, x=y[None,:, None], axis=1) assert_almost_equal(r, qy) r = trapz(q, x=z[None, None,:], axis=2) assert_almost_equal(r, qz) # 1-d `x` r = trapz(q, x=x, axis=0) assert_almost_equal(r, qx) r = trapz(q, x=y, axis=1) assert_almost_equal(r, qy) r = trapz(q, x=z, axis=2) assert_almost_equal(r, qz) def test_masked(self): #Testing that masked arrays behave as if the function is 0 where #masked x = np.arange(5) y = x * x mask = x == 2 ym = np.ma.array(y, mask=mask) r = 13.0 # sum(0.5 * (0 + 1) * 1.0 + 0.5 * (9 + 16)) assert_almost_equal(trapz(ym, x), r) xm = np.ma.array(x, mask=mask) assert_almost_equal(trapz(ym, xm), r) xm = np.ma.array(x, mask=mask) assert_almost_equal(trapz(y, xm), r) def test_matrix(self): #Test to make sure matrices give the same answer as ndarrays x = np.linspace(0, 5) y = x * x r = trapz(y, x) mx = np.matrix(x) my = np.matrix(y) mr = trapz(my, mx) assert_almost_equal(mr, r) class TestSinc(TestCase): def test_simple(self): assert_(sinc(0) == 1) w = sinc(np.linspace(-1, 1, 100)) #check symmetry assert_array_almost_equal(w, flipud(w), 7) def test_array_like(self): x = [0, 0.5] y1 = sinc(np.array(x)) y2 = sinc(list(x)) y3 = sinc(tuple(x)) assert_array_equal(y1, y2) assert_array_equal(y1, y3) class TestHistogram(TestCase): def setUp(self): pass def tearDown(self): pass def test_simple(self): n = 100 v = rand(n) (a, b) = histogram(v) #check if the sum of the bins equals the number of samples assert_equal(np.sum(a, axis=0), n) #check that the bin counts are evenly spaced when the data is from a # linear function (a, b) = histogram(np.linspace(0, 10, 100)) assert_array_equal(a, 10) def test_one_bin(self): # Ticket 632 hist, edges = histogram([1, 2, 3, 4], [1, 2]) assert_array_equal(hist, [2,]) assert_array_equal(edges, [1, 2]) assert_raises(ValueError, histogram, [1, 2], bins=0) h, e = histogram([1, 2], bins=1) assert_equal(h, np.array([2])) assert_allclose(e, np.array([1., 2.])) def test_normed(self): # Check that the integral of the density equals 1. n = 100 v = rand(n) a, b = histogram(v, normed=True) area = np.sum(a * diff(b)) assert_almost_equal(area, 1) # Check with non-constant bin widths (buggy but backwards compatible) v = np.arange(10) bins = [0, 1, 5, 9, 10] a, b = histogram(v, bins, normed=True) area = np.sum(a * diff(b)) assert_almost_equal(area, 1) def test_density(self): # Check that the integral of the density equals 1. n = 100 v = rand(n) a, b = histogram(v, density=True) area = np.sum(a * diff(b)) assert_almost_equal(area, 1) # Check with non-constant bin widths v = np.arange(10) bins = [0, 1, 3, 6, 10] a, b = histogram(v, bins, density=True) assert_array_equal(a, .1) assert_equal(np.sum(a*diff(b)), 1) # Variale bin widths are especially useful to deal with # infinities. v = np.arange(10) bins = [0, 1, 3, 6, np.inf] a, b = histogram(v, bins, density=True) assert_array_equal(a, [.1, .1, .1, 0.]) # Taken from a bug report from N. Becker on the numpy-discussion # mailing list Aug. 6, 2010. counts, dmy = np.histogram([1, 2, 3, 4], [0.5, 1.5, np.inf], density=True) assert_equal(counts, [.25, 0]) def test_outliers(self): # Check that outliers are not tallied a = np.arange(10) + .5 # Lower outliers h, b = histogram(a, range=[0, 9]) assert_equal(h.sum(), 9) # Upper outliers h, b = histogram(a, range=[1, 10]) assert_equal(h.sum(), 9) # Normalization h, b = histogram(a, range=[1, 9], normed=True) assert_almost_equal((h * diff(b)).sum(), 1, decimal=15) # Weights w = np.arange(10) + .5 h, b = histogram(a, range=[1, 9], weights=w, normed=True) assert_equal((h * diff(b)).sum(), 1) h, b = histogram(a, bins=8, range=[1, 9], weights=w) assert_equal(h, w[1:-1]) def test_type(self): # Check the type of the returned histogram a = np.arange(10) + .5 h, b = histogram(a) assert_(issubdtype(h.dtype, int)) h, b = histogram(a, normed=True) assert_(issubdtype(h.dtype, float)) h, b = histogram(a, weights=np.ones(10, int)) assert_(issubdtype(h.dtype, int)) h, b = histogram(a, weights=np.ones(10, float)) assert_(issubdtype(h.dtype, float)) def test_weights(self): v = rand(100) w = np.ones(100) * 5 a, b = histogram(v) na, nb = histogram(v, normed=True) wa, wb = histogram(v, weights=w) nwa, nwb = histogram(v, weights=w, normed=True) assert_array_almost_equal(a * 5, wa) assert_array_almost_equal(na, nwa) # Check weights are properly applied. v = np.linspace(0, 10, 10) w = np.concatenate((np.zeros(5), np.ones(5))) wa, wb = histogram(v, bins=np.arange(11), weights=w) assert_array_almost_equal(wa, w) # Check with integer weights wa, wb = histogram([1, 2, 2, 4], bins=4, weights=[4, 3, 2, 1]) assert_array_equal(wa, [4, 5, 0, 1]) wa, wb = histogram([1, 2, 2, 4], bins=4, weights=[4, 3, 2, 1], normed=True) assert_array_almost_equal(wa, np.array([4, 5, 0, 1]) / 10. / 3. * 4) # Check weights with non-uniform bin widths a, b = histogram(np.arange(9), [0, 1, 3, 6, 10], \ weights=[2, 1, 1, 1, 1, 1, 1, 1, 1], density=True) assert_almost_equal(a, [.2, .1, .1, .075]) def test_empty(self): a, b = histogram([], bins=([0, 1])) assert_array_equal(a, np.array([0])) assert_array_equal(b, np.array([0, 1])) class TestHistogramdd(TestCase): def test_simple(self): x = np.array([[-.5, .5, 1.5], [-.5, 1.5, 2.5], [-.5, 2.5, .5], \ [.5, .5, 1.5], [.5, 1.5, 2.5], [.5, 2.5, 2.5]]) H, edges = histogramdd(x, (2, 3, 3), range=[[-1, 1], [0, 3], [0, 3]]) answer = np.array([[[0, 1, 0], [0, 0, 1], [1, 0, 0]], [[0, 1, 0], [0, 0, 1], [0, 0, 1]]]) assert_array_equal(H, answer) # Check normalization ed = [[-2, 0, 2], [0, 1, 2, 3], [0, 1, 2, 3]] H, edges = histogramdd(x, bins=ed, normed=True) assert_(np.all(H == answer / 12.)) # Check that H has the correct shape. H, edges = histogramdd(x, (2, 3, 4), range=[[-1, 1], [0, 3], [0, 4]], normed=True) answer = np.array([[[0, 1, 0, 0], [0, 0, 1, 0], [1, 0, 0, 0]], [[0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 1, 0]]]) assert_array_almost_equal(H, answer / 6., 4) # Check that a sequence of arrays is accepted and H has the correct # shape. z = [np.squeeze(y) for y in split(x, 3, axis=1)] H, edges = histogramdd(z, bins=(4, 3, 2), range=[[-2, 2], [0, 3], [0, 2]]) answer = np.array([[[0, 0], [0, 0], [0, 0]], [[0, 1], [0, 0], [1, 0]], [[0, 1], [0, 0], [0, 0]], [[0, 0], [0, 0], [0, 0]]]) assert_array_equal(H, answer) Z = np.zeros((5, 5, 5)) Z[list(range(5)), list(range(5)), list(range(5))] = 1. H, edges = histogramdd([np.arange(5), np.arange(5), np.arange(5)], 5) assert_array_equal(H, Z) def test_shape_3d(self): # All possible permutations for bins of different lengths in 3D. bins = ((5, 4, 6), (6, 4, 5), (5, 6, 4), (4, 6, 5), (6, 5, 4), (4, 5, 6)) r = rand(10, 3) for b in bins: H, edges = histogramdd(r, b) assert_(H.shape == b) def test_shape_4d(self): # All possible permutations for bins of different lengths in 4D. bins = ((7, 4, 5, 6), (4, 5, 7, 6), (5, 6, 4, 7), (7, 6, 5, 4), (5, 7, 6, 4), (4, 6, 7, 5), (6, 5, 7, 4), (7, 5, 4, 6), (7, 4, 6, 5), (6, 4, 7, 5), (6, 7, 5, 4), (4, 6, 5, 7), (4, 7, 5, 6), (5, 4, 6, 7), (5, 7, 4, 6), (6, 7, 4, 5), (6, 5, 4, 7), (4, 7, 6, 5), (4, 5, 6, 7), (7, 6, 4, 5), (5, 4, 7, 6), (5, 6, 7, 4), (6, 4, 5, 7), (7, 5, 6, 4)) r = rand(10, 4) for b in bins: H, edges = histogramdd(r, b) assert_(H.shape == b) def test_weights(self): v = rand(100, 2) hist, edges = histogramdd(v) n_hist, edges = histogramdd(v, normed=True) w_hist, edges = histogramdd(v, weights=np.ones(100)) assert_array_equal(w_hist, hist) w_hist, edges = histogramdd(v, weights=np.ones(100) * 2, normed=True) assert_array_equal(w_hist, n_hist) w_hist, edges = histogramdd(v, weights=np.ones(100, int) * 2) assert_array_equal(w_hist, 2 * hist) def test_identical_samples(self): x = np.zeros((10, 2), int) hist, edges = histogramdd(x, bins=2) assert_array_equal(edges[0], np.array([-0.5, 0., 0.5])) def test_empty(self): a, b = histogramdd([[], []], bins=([0, 1], [0, 1])) assert_array_max_ulp(a, np.array([[ 0.]])) a, b = np.histogramdd([[], [], []], bins=2) assert_array_max_ulp(a, np.zeros((2, 2, 2))) def test_bins_errors(self): """There are two ways to specify bins. Check for the right errors when mixing those.""" x = np.arange(8).reshape(2, 4) assert_raises(ValueError, np.histogramdd, x, bins=[-1, 2, 4, 5]) assert_raises(ValueError, np.histogramdd, x, bins=[1, 0.99, 1, 1]) assert_raises(ValueError, np.histogramdd, x, bins=[1, 1, 1, [1, 2, 2, 3]]) assert_raises(ValueError, np.histogramdd, x, bins=[1, 1, 1, [1, 2, 3, -3]]) assert_(np.histogramdd(x, bins=[1, 1, 1, [1, 2, 3, 4]])) def test_inf_edges(self): """Test using +/-inf bin edges works. See #1788.""" with np.errstate(invalid='ignore'): x = np.arange(6).reshape(3, 2) expected = np.array([[1, 0], [0, 1], [0, 1]]) h, e = np.histogramdd(x, bins=[3, [-np.inf, 2, 10]]) assert_allclose(h, expected) h, e = np.histogramdd(x, bins=[3, np.array([-1, 2, np.inf])]) assert_allclose(h, expected) 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): x = np.array([4, 3, 2, 1, 1, 2, 3, 4, 0]) assert_(np.all(unique(x) == [0, 1, 2, 3, 4])) assert_(unique(np.array([1, 1, 1, 1, 1])) == np.array([1])) x = ['widget', 'ham', 'foo', 'bar', 'foo', 'ham'] assert_(np.all(unique(x) == ['bar', 'foo', 'ham', 'widget'])) x = np.array([5 + 6j, 1 + 1j, 1 + 10j, 10, 5 + 6j]) assert_(np.all(unique(x) == [1 + 1j, 1 + 10j, 5 + 6j, 10])) class TestCheckFinite(TestCase): def test_simple(self): a = [1, 2, 3] b = [1, 2, np.inf] c = [1, 2, np.nan] np.lib.asarray_chkfinite(a) assert_raises(ValueError, np.lib.asarray_chkfinite, b) assert_raises(ValueError, np.lib.asarray_chkfinite, c) def test_dtype_order(self): """Regression test for missing dtype and order arguments""" a = [1, 2, 3] a = np.lib.asarray_chkfinite(a, order='F', dtype=np.float64) assert_(a.dtype == np.float64) class TestCorrCoef(TestCase): A = np.array([[ 0.15391142, 0.18045767, 0.14197213], [ 0.70461506, 0.96474128, 0.27906989], [ 0.9297531, 0.32296769, 0.19267156]]) B = np.array([[ 0.10377691, 0.5417086, 0.49807457], [ 0.82872117, 0.77801674, 0.39226705], [ 0.9314666, 0.66800209, 0.03538394]]) res1 = np.array([[ 1., 0.9379533, -0.04931983], [ 0.9379533, 1., 0.30007991], [-0.04931983, 0.30007991, 1. ]]) res2 = np.array([[ 1., 0.9379533, -0.04931983, 0.30151751, 0.66318558, 0.51532523], [ 0.9379533, 1., 0.30007991, - 0.04781421, 0.88157256, 0.78052386], [-0.04931983, 0.30007991, 1., - 0.96717111, 0.71483595, 0.83053601], [ 0.30151751, -0.04781421, -0.96717111, 1., -0.51366032, -0.66173113], [ 0.66318558, 0.88157256, 0.71483595, - 0.51366032, 1., 0.98317823], [ 0.51532523, 0.78052386, 0.83053601, - 0.66173113, 0.98317823, 1. ]]) def test_simple(self): assert_almost_equal(corrcoef(self.A), self.res1) assert_almost_equal(corrcoef(self.A, self.B), self.res2) def test_ddof(self): assert_almost_equal(corrcoef(self.A, ddof=-1), self.res1) assert_almost_equal(corrcoef(self.A, self.B, ddof=-1), self.res2) def test_empty(self): assert_equal(corrcoef(np.array([])).size, 0) assert_equal(corrcoef(np.array([]).reshape(0, 2)).shape, (0, 2)) class TestCov(TestCase): def test_basic(self): x = np.array([[0, 2], [1, 1], [2, 0]]).T assert_allclose(np.cov(x), np.array([[ 1., -1.], [-1., 1.]])) def test_empty(self): assert_equal(cov(np.array([])).size, 0) assert_equal(cov(np.array([]).reshape(0, 2)).shape, (0, 2)) class Test_I0(TestCase): def test_simple(self): assert_almost_equal(i0(0.5), np.array(1.0634833707413234)) A = np.array([ 0.49842636, 0.6969809, 0.22011976, 0.0155549]) assert_almost_equal(i0(A), np.array([ 1.06307822, 1.12518299, 1.01214991, 1.00006049])) B = np.array([[ 0.827002, 0.99959078], [ 0.89694769, 0.39298162], [ 0.37954418, 0.05206293], [ 0.36465447, 0.72446427], [ 0.48164949, 0.50324519]]) assert_almost_equal(i0(B), np.array([[ 1.17843223, 1.26583466], [ 1.21147086, 1.0389829 ], [ 1.03633899, 1.00067775], [ 1.03352052, 1.13557954], [ 1.0588429, 1.06432317]])) class TestKaiser(TestCase): def test_simple(self): assert_almost_equal(kaiser(0, 1.0), np.array([])) assert_(np.isfinite(kaiser(1, 1.0))) assert_almost_equal(kaiser(2, 1.0), np.array([ 0.78984831, 0.78984831])) assert_almost_equal(kaiser(5, 1.0), np.array([ 0.78984831, 0.94503323, 1., 0.94503323, 0.78984831])) assert_almost_equal(kaiser(5, 1.56789), np.array([ 0.58285404, 0.88409679, 1., 0.88409679, 0.58285404])) def test_int_beta(self): kaiser(3, 4) class TestMsort(TestCase): def test_simple(self): A = np.array([[ 0.44567325, 0.79115165, 0.5490053 ], [ 0.36844147, 0.37325583, 0.96098397], [ 0.64864341, 0.52929049, 0.39172155]]) assert_almost_equal(msort(A), np.array([[ 0.36844147, 0.37325583, 0.39172155], [ 0.44567325, 0.52929049, 0.5490053 ], [ 0.64864341, 0.79115165, 0.96098397]])) class TestMeshgrid(TestCase): def test_simple(self): [X, Y] = meshgrid([1, 2, 3], [4, 5, 6, 7]) assert_(np.all(X == np.array([[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]]))) assert_(np.all(Y == np.array([[4, 4, 4], [5, 5, 5], [6, 6, 6], [7, 7, 7]]))) def test_single_input(self): assert_raises(ValueError, meshgrid, np.arange(5)) def test_indexing(self): x = [1, 2, 3] y = [4, 5, 6, 7] [X, Y] = meshgrid(x, y, indexing='ij') assert_(np.all(X == np.array([[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3]]))) assert_(np.all(Y == np.array([[4, 5, 6, 7], [4, 5, 6, 7], [4, 5, 6, 7]]))) # Test expected shapes: z = [8, 9] assert_(meshgrid(x, y)[0].shape == (4, 3)) assert_(meshgrid(x, y, indexing='ij')[0].shape == (3, 4)) assert_(meshgrid(x, y, z)[0].shape == (4, 3, 2)) assert_(meshgrid(x, y, z, indexing='ij')[0].shape == (3, 4, 2)) assert_raises(ValueError, meshgrid, x, y, indexing='notvalid') def test_sparse(self): [X, Y] = meshgrid([1, 2, 3], [4, 5, 6, 7], sparse=True) assert_(np.all(X == np.array([[1, 2, 3]]))) assert_(np.all(Y == np.array([[4], [5], [6], [7]]))) class TestPiecewise(TestCase): def test_simple(self): # Condition is single bool list x = piecewise([0, 0], [True, False], [1]) assert_array_equal(x, [1, 0]) # List of conditions: single bool list x = piecewise([0, 0], [[True, False]], [1]) assert_array_equal(x, [1, 0]) # Conditions is single bool array x = piecewise([0, 0], np.array([True, False]), [1]) assert_array_equal(x, [1, 0]) # Condition is single int array x = piecewise([0, 0], np.array([1, 0]), [1]) assert_array_equal(x, [1, 0]) # List of conditions: int array x = piecewise([0, 0], [np.array([1, 0])], [1]) assert_array_equal(x, [1, 0]) x = piecewise([0, 0], [[False, True]], [lambda x:-1]) assert_array_equal(x, [0, -1]) x = piecewise([1, 2], [[True, False], [False, True]], [3, 4]) assert_array_equal(x, [3, 4]) def test_default(self): # No value specified for x[1], should be 0 x = piecewise([1, 2], [True, False], [2]) assert_array_equal(x, [2, 0]) # Should set x[1] to 3 x = piecewise([1, 2], [True, False], [2, 3]) assert_array_equal(x, [2, 3]) def test_0d(self): x = np.array(3) y = piecewise(x, x > 3, [4, 0]) assert_(y.ndim == 0) assert_(y == 0) class TestBincount(TestCase): def test_simple(self): y = np.bincount(np.arange(4)) assert_array_equal(y, np.ones(4)) def test_simple2(self): y = np.bincount(np.array([1, 5, 2, 4, 1])) assert_array_equal(y, np.array([0, 2, 1, 0, 1, 1])) def test_simple_weight(self): x = np.arange(4) w = np.array([0.2, 0.3, 0.5, 0.1]) y = np.bincount(x, w) assert_array_equal(y, w) def test_simple_weight2(self): x = np.array([1, 2, 4, 5, 2]) w = np.array([0.2, 0.3, 0.5, 0.1, 0.2]) y = np.bincount(x, w) assert_array_equal(y, np.array([0, 0.2, 0.5, 0, 0.5, 0.1])) def test_with_minlength(self): x = np.array([0, 1, 0, 1, 1]) y = np.bincount(x, minlength=3) assert_array_equal(y, np.array([2, 3, 0])) def test_with_minlength_smaller_than_maxvalue(self): x = np.array([0, 1, 1, 2, 2, 3, 3]) y = np.bincount(x, minlength=2) assert_array_equal(y, np.array([1, 2, 2, 2])) def test_with_minlength_and_weights(self): x = np.array([1, 2, 4, 5, 2]) w = np.array([0.2, 0.3, 0.5, 0.1, 0.2]) y = np.bincount(x, w, 8) assert_array_equal(y, np.array([0, 0.2, 0.5, 0, 0.5, 0.1, 0, 0])) def test_empty(self): x = np.array([], dtype=int) y = np.bincount(x) assert_array_equal(x, y) def test_empty_with_minlength(self): x = np.array([], dtype=int) y = np.bincount(x, minlength=5) assert_array_equal(y, np.zeros(5, dtype=int)) class TestInterp(TestCase): def test_exceptions(self): assert_raises(ValueError, interp, 0, [], []) assert_raises(ValueError, interp, 0, [0], [1, 2]) def test_basic(self): x = np.linspace(0, 1, 5) y = np.linspace(0, 1, 5) x0 = np.linspace(0, 1, 50) assert_almost_equal(np.interp(x0, x, y), x0) def test_right_left_behavior(self): assert_equal(interp([-1, 0, 1], [0], [1]), [1, 1, 1]) assert_equal(interp([-1, 0, 1], [0], [1], left=0), [0, 1, 1]) assert_equal(interp([-1, 0, 1], [0], [1], right=0), [1, 1, 0]) assert_equal(interp([-1, 0, 1], [0], [1], left=0, right=0), [0, 1, 0]) def test_scalar_interpolation_point(self): x = np.linspace(0, 1, 5) y = np.linspace(0, 1, 5) x0 = 0 assert_almost_equal(np.interp(x0, x, y), x0) x0 = .3 assert_almost_equal(np.interp(x0, x, y), x0) x0 = np.float32(.3) assert_almost_equal(np.interp(x0, x, y), x0) x0 = np.float64(.3) assert_almost_equal(np.interp(x0, x, y), x0) def test_zero_dimensional_interpolation_point(self): x = np.linspace(0, 1, 5) y = np.linspace(0, 1, 5) x0 = np.array(.3) assert_almost_equal(np.interp(x0, x, y), x0) x0 = np.array(.3, dtype=object) assert_almost_equal(np.interp(x0, x, y), .3) def test_if_len_x_is_small(self): xp = np.arange(0, 1000, 0.0001) fp = np.sin(xp) assert_almost_equal(np.interp(np.pi, xp, fp), 0.0) def compare_results(res, desired): for i in range(len(desired)): assert_array_equal(res[i], desired[i]) def test_percentile_list(): assert_equal(np.percentile([1, 2, 3], 0), 1) def test_percentile_out(): x = np.array([1, 2, 3]) y = np.zeros((3,)) p = (1, 2, 3) np.percentile(x, p, out=y) assert_equal(y, np.percentile(x, p)) x = np.array([[1, 2, 3], [4, 5, 6]]) y = np.zeros((3, 3)) np.percentile(x, p, axis=0, out=y) assert_equal(y, np.percentile(x, p, axis=0)) y = np.zeros((3, 2)) np.percentile(x, p, axis=1, out=y) assert_equal(y, np.percentile(x, p, axis=1)) class TestMedian(TestCase): def test_basic(self): a0 = np.array(1) a1 = np.arange(2) a2 = np.arange(6).reshape(2, 3) assert_allclose(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_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)) a = np.array([0.0444502, 0.141249, 0.0463301]) assert_almost_equal(a[-1], np.median(a)) def test_axis_keyword(self): a3 = np.array([[2, 3], [0, 1], [6, 7], [4, 5]]) for a in [a3, np.random.randint(0, 100, size=(2, 3, 4))]: orig = a.copy() np.median(a, axis=None) for ax in range(a.ndim): np.median(a, axis=ax) assert_array_equal(a, orig) assert_allclose(np.median(a3, axis=0), [3, 4]) assert_allclose(np.median(a3.T, axis=1), [3, 4]) assert_allclose(np.median(a3), 3.5) assert_allclose(np.median(a3, axis=None), 3.5) assert_allclose(np.median(a3.T), 3.5) def test_overwrite_keyword(self): a3 = np.array([[2, 3], [0, 1], [6, 7], [4, 5]]) a0 = np.array(1) a1 = np.arange(2) a2 = np.arange(6).reshape(2, 3) assert_allclose(np.median(a0.copy(), overwrite_input=True), 1) assert_allclose(np.median(a1.copy(), overwrite_input=True), 0.5) assert_allclose(np.median(a2.copy(), overwrite_input=True), 2.5) assert_allclose(np.median(a2.copy(), overwrite_input=True, axis=0), [1.5, 2.5, 3.5]) assert_allclose(np.median(a2.copy(), overwrite_input=True, axis=1), [1, 4]) assert_allclose(np.median(a2.copy(), overwrite_input=True, axis=None), 2.5) assert_allclose(np.median(a3.copy(), overwrite_input=True, axis=0), [3, 4]) assert_allclose(np.median(a3.T.copy(), overwrite_input=True, axis=1), [3, 4]) a4 = np.arange(3 * 4 * 5, dtype=np.float32).reshape((3, 4, 5)) map(np.random.shuffle, a4) assert_allclose(np.median(a4, axis=None), np.median(a4.copy(), axis=None, overwrite_input=True)) assert_allclose(np.median(a4, axis=0), np.median(a4.copy(), axis=0, overwrite_input=True)) assert_allclose(np.median(a4, axis=1), np.median(a4.copy(), axis=1, overwrite_input=True)) assert_allclose(np.median(a4, axis=2), np.median(a4.copy(), axis=2, overwrite_input=True)) def test_array_like(self): x = [1, 2, 3] assert_almost_equal(np.median(x), 2) x2 = [x] assert_almost_equal(np.median(x2), 2) assert_allclose(np.median(x2, axis=0), x) def test_subclass(self): # gh-3846 class MySubClass(np.ndarray): def __new__(cls, input_array, info=None): obj = np.asarray(input_array).view(cls) obj.info = info return obj def mean(self, axis=None, dtype=None, out=None): return -7 a = MySubClass([1,2,3]) assert_equal(np.median(a), -7) class TestAdd_newdoc_ufunc(TestCase): def test_ufunc_arg(self): assert_raises(TypeError, add_newdoc_ufunc, 2, "blah") assert_raises(ValueError, add_newdoc_ufunc, np.add, "blah") def test_string_arg(self): assert_raises(TypeError, add_newdoc_ufunc, np.add, 3) if __name__ == "__main__": run_module_suite() numpy-1.8.2/numpy/lib/tests/test_regression.py0000664000175100017510000002134512370216243022702 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function import os import sys import numpy as np from numpy.testing import * from numpy.testing.utils import _assert_valid_refcount from numpy.compat import unicode rlevel = 1 class TestRegression(TestCase): def test_poly1d(self,level=rlevel): """Ticket #28""" assert_equal(np.poly1d([1]) - np.poly1d([1, 0]), np.poly1d([-1, 1])) def test_cov_parameters(self,level=rlevel): """Ticket #91""" x = np.random.random((3, 3)) y = x.copy() np.cov(x, rowvar=1) np.cov(y, rowvar=0) assert_array_equal(x, y) def test_mem_digitize(self,level=rlevel): """Ticket #95""" for i in range(100): np.digitize([1, 2, 3, 4], [1, 3]) np.digitize([0, 1, 2, 3, 4], [1, 3]) def test_unique_zero_sized(self,level=rlevel): """Ticket #205""" assert_array_equal([], np.unique(np.array([]))) def test_mem_vectorise(self, level=rlevel): """Ticket #325""" vt = np.vectorize(lambda *args: args) vt(np.zeros((1, 2, 1)), np.zeros((2, 1, 1)), np.zeros((1, 1, 2))) vt(np.zeros((1, 2, 1)), np.zeros((2, 1, 1)), np.zeros((1, 1, 2)), np.zeros((2, 2))) def test_mgrid_single_element(self, level=rlevel): """Ticket #339""" assert_array_equal(np.mgrid[0:0:1j], [0]) assert_array_equal(np.mgrid[0:0], []) def test_refcount_vectorize(self, level=rlevel): """Ticket #378""" def p(x, y): return 123 v = np.vectorize(p) _assert_valid_refcount(v) def test_poly1d_nan_roots(self, level=rlevel): """Ticket #396""" p = np.poly1d([np.nan, np.nan, 1], r=0) self.assertRaises(np.linalg.LinAlgError, getattr, p, "r") def test_mem_polymul(self, level=rlevel): """Ticket #448""" np.polymul([], [1.]) def test_mem_string_concat(self, level=rlevel): """Ticket #469""" x = np.array([]) np.append(x, 'asdasd\tasdasd') def test_poly_div(self, level=rlevel): """Ticket #553""" u = np.poly1d([1, 2, 3]) v = np.poly1d([1, 2, 3, 4, 5]) q, r = np.polydiv(u, v) assert_equal(q*v + r, u) def test_poly_eq(self, level=rlevel): """Ticket #554""" x = np.poly1d([1, 2, 3]) y = np.poly1d([3, 4]) assert_(x != y) assert_(x == x) def test_mem_insert(self, level=rlevel): """Ticket #572""" np.lib.place(1, 1, 1) def test_polyfit_build(self): """Ticket #628""" ref = [-1.06123820e-06, 5.70886914e-04, -1.13822012e-01, 9.95368241e+00, -3.14526520e+02] x = [90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176] y = [9.0, 3.0, 7.0, 4.0, 4.0, 8.0, 6.0, 11.0, 9.0, 8.0, 11.0, 5.0, 6.0, 5.0, 9.0, 8.0, 6.0, 10.0, 6.0, 10.0, 7.0, 6.0, 6.0, 6.0, 13.0, 4.0, 9.0, 11.0, 4.0, 5.0, 8.0, 5.0, 7.0, 7.0, 6.0, 12.0, 7.0, 7.0, 9.0, 4.0, 12.0, 6.0, 6.0, 4.0, 3.0, 9.0, 8.0, 8.0, 6.0, 7.0, 9.0, 10.0, 6.0, 8.0, 4.0, 7.0, 7.0, 10.0, 8.0, 8.0, 6.0, 3.0, 8.0, 4.0, 5.0, 7.0, 8.0, 6.0, 6.0, 4.0, 12.0, 9.0, 8.0, 8.0, 8.0, 6.0, 7.0, 4.0, 4.0, 5.0, 7.0] tested = np.polyfit(x, y, 4) assert_array_almost_equal(ref, tested) def test_polydiv_type(self) : """Make polydiv work for complex types""" msg = "Wrong type, should be complex" x = np.ones(3, dtype=np.complex) q, r = np.polydiv(x, x) assert_(q.dtype == np.complex, msg) msg = "Wrong type, should be float" x = np.ones(3, dtype=np.int) q, r = np.polydiv(x, x) assert_(q.dtype == np.float, msg) def test_histogramdd_too_many_bins(self) : """Ticket 928.""" assert_raises(ValueError, np.histogramdd, np.ones((1, 10)), bins=2**10) def test_polyint_type(self) : """Ticket #944""" msg = "Wrong type, should be complex" x = np.ones(3, dtype=np.complex) assert_(np.polyint(x).dtype == np.complex, msg) msg = "Wrong type, should be float" x = np.ones(3, dtype=np.int) assert_(np.polyint(x).dtype == np.float, msg) def test_ndenumerate_crash(self): """Ticket 1140""" # Shouldn't crash: list(np.ndenumerate(np.array([[]]))) def test_asfarray_none(self, level=rlevel): """Test for changeset r5065""" assert_array_equal(np.array([np.nan]), np.asfarray([None])) def test_large_fancy_indexing(self, level=rlevel): # Large enough to fail on 64-bit. nbits = np.dtype(np.intp).itemsize * 8 thesize = int((2**nbits)**(1.0/5.0)+1) def dp(): n = 3 a = np.ones((n,)*5) i = np.random.randint(0, n, size=thesize) a[np.ix_(i, i, i, i, i)] = 0 def dp2(): n = 3 a = np.ones((n,)*5) i = np.random.randint(0, n, size=thesize) g = a[np.ix_(i, i, i, i, i)] self.assertRaises(ValueError, dp) self.assertRaises(ValueError, dp2) def test_void_coercion(self, level=rlevel): dt = np.dtype([('a', 'f4'), ('b', 'i4')]) x = np.zeros((1,), dt) assert_(np.r_[x, x].dtype == dt) def test_who_with_0dim_array(self, level=rlevel) : """ticket #1243""" import os, sys oldstdout = sys.stdout sys.stdout = open(os.devnull, 'w') try: try: tmp = np.who({'foo' : np.array(1)}) except: raise AssertionError("ticket #1243") finally: sys.stdout.close() sys.stdout = oldstdout def test_include_dirs(self): """As a sanity check, just test that get_include and get_numarray_include include something reasonable. Somewhat related to ticket #1405.""" include_dirs = [np.get_include(), np.get_numarray_include()] for path in include_dirs: assert_(isinstance(path, (str, unicode))) assert_(path != '') def test_polyder_return_type(self): """Ticket #1249""" assert_(isinstance(np.polyder(np.poly1d([1]), 0), np.poly1d)) assert_(isinstance(np.polyder([1], 0), np.ndarray)) assert_(isinstance(np.polyder(np.poly1d([1]), 1), np.poly1d)) assert_(isinstance(np.polyder([1], 1), np.ndarray)) def test_append_fields_dtype_list(self): """Ticket #1676""" from numpy.lib.recfunctions import append_fields F = False base = np.array([1, 2, 3], dtype=np.int32) data = np.eye(3).astype(np.int32) names = ['a', 'b', 'c'] dlist = [np.float64, np.int32, np.int32] try: a = append_fields(base, names, data, dlist) except: raise AssertionError() def test_loadtxt_fields_subarrays(self): # For ticket #1936 if sys.version_info[0] >= 3: from io import StringIO else: from StringIO import StringIO dt = [("a", 'u1', 2), ("b", 'u1', 2)] x = np.loadtxt(StringIO("0 1 2 3"), dtype=dt) assert_equal(x, np.array([((0, 1), (2, 3))], dtype=dt)) dt = [("a", [("a", 'u1', (1, 3)), ("b", 'u1')])] x = np.loadtxt(StringIO("0 1 2 3"), dtype=dt) assert_equal(x, np.array([(((0, 1, 2), 3),)], dtype=dt)) dt = [("a", 'u1', (2, 2))] x = np.loadtxt(StringIO("0 1 2 3"), dtype=dt) assert_equal(x, np.array([(((0, 1), (2, 3)),)], dtype=dt)) dt = [("a", 'u1', (2, 3, 2))] x = np.loadtxt(StringIO("0 1 2 3 4 5 6 7 8 9 10 11"), dtype=dt) data = [((((0, 1), (2, 3), (4, 5)), ((6, 7), (8, 9), (10, 11))),)] assert_equal(x, np.array(data, dtype=dt)) def test_nansum_with_boolean(self): # gh-2978 a = np.zeros(2, dtype=np.bool) try: np.nansum(a) except: raise AssertionError() def test_py3_compat(self): # gh-2561 # Test if the oldstyle class test is bypassed in python3 class C(): """Old-style class in python2, normal class in python3""" pass out = open(os.devnull, 'w') try: np.info(C(), output=out) except AttributeError: raise AssertionError() finally: out.close() if __name__ == "__main__": run_module_suite() numpy-1.8.2/numpy/lib/tests/test_type_check.py0000664000175100017510000002310112370216243022630 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function from numpy.lib import * from numpy.core import * from numpy.random import rand from numpy.compat import asbytes, long from numpy.testing import ( TestCase, assert_, assert_equal, assert_array_equal, run_module_suite) try: import ctypes _HAS_CTYPE = True except ImportError: _HAS_CTYPE = False def assert_all(x): assert_(all(x), x) class TestCommonType(TestCase): def test_basic(self): ai32 = array([[1, 2], [3, 4]], dtype=int32) af32 = array([[1, 2], [3, 4]], dtype=float32) af64 = array([[1, 2], [3, 4]], dtype=float64) acs = array([[1+5j, 2+6j], [3+7j, 4+8j]], dtype=csingle) acd = array([[1+5j, 2+6j], [3+7j, 4+8j]], dtype=cdouble) assert_(common_type(af32) == float32) assert_(common_type(af64) == float64) assert_(common_type(acs) == csingle) assert_(common_type(acd) == cdouble) class TestMintypecode(TestCase): def test_default_1(self): for itype in '1bcsuwil': assert_equal(mintypecode(itype), 'd') assert_equal(mintypecode('f'), 'f') assert_equal(mintypecode('d'), 'd') assert_equal(mintypecode('F'), 'F') assert_equal(mintypecode('D'), 'D') def test_default_2(self): for itype in '1bcsuwil': assert_equal(mintypecode(itype+'f'), 'f') assert_equal(mintypecode(itype+'d'), 'd') assert_equal(mintypecode(itype+'F'), 'F') assert_equal(mintypecode(itype+'D'), 'D') assert_equal(mintypecode('ff'), 'f') assert_equal(mintypecode('fd'), 'd') assert_equal(mintypecode('fF'), 'F') assert_equal(mintypecode('fD'), 'D') assert_equal(mintypecode('df'), 'd') assert_equal(mintypecode('dd'), 'd') #assert_equal(mintypecode('dF',savespace=1),'F') assert_equal(mintypecode('dF'), 'D') assert_equal(mintypecode('dD'), 'D') assert_equal(mintypecode('Ff'), 'F') #assert_equal(mintypecode('Fd',savespace=1),'F') assert_equal(mintypecode('Fd'), 'D') assert_equal(mintypecode('FF'), 'F') assert_equal(mintypecode('FD'), 'D') assert_equal(mintypecode('Df'), 'D') assert_equal(mintypecode('Dd'), 'D') assert_equal(mintypecode('DF'), 'D') assert_equal(mintypecode('DD'), 'D') def test_default_3(self): assert_equal(mintypecode('fdF'), 'D') #assert_equal(mintypecode('fdF',savespace=1),'F') assert_equal(mintypecode('fdD'), 'D') assert_equal(mintypecode('fFD'), 'D') assert_equal(mintypecode('dFD'), 'D') assert_equal(mintypecode('ifd'), 'd') assert_equal(mintypecode('ifF'), 'F') assert_equal(mintypecode('ifD'), 'D') assert_equal(mintypecode('idF'), 'D') #assert_equal(mintypecode('idF',savespace=1),'F') assert_equal(mintypecode('idD'), 'D') class TestIsscalar(TestCase): def test_basic(self): assert_(isscalar(3)) assert_(not isscalar([3])) assert_(not isscalar((3,))) assert_(isscalar(3j)) assert_(isscalar(long(10))) assert_(isscalar(4.0)) class TestReal(TestCase): def test_real(self): y = rand(10,) assert_array_equal(y, real(y)) def test_cmplx(self): y = rand(10,)+1j*rand(10,) assert_array_equal(y.real, real(y)) class TestImag(TestCase): def test_real(self): y = rand(10,) assert_array_equal(0, imag(y)) def test_cmplx(self): y = rand(10,)+1j*rand(10,) assert_array_equal(y.imag, imag(y)) class TestIscomplex(TestCase): def test_fail(self): z = array([-1, 0, 1]) res = iscomplex(z) assert_(not sometrue(res, axis=0)) def test_pass(self): z = array([-1j, 1, 0]) res = iscomplex(z) assert_array_equal(res, [1, 0, 0]) class TestIsreal(TestCase): def test_pass(self): z = array([-1, 0, 1j]) res = isreal(z) assert_array_equal(res, [1, 1, 0]) def test_fail(self): z = array([-1j, 1, 0]) res = isreal(z) assert_array_equal(res, [0, 1, 1]) class TestIscomplexobj(TestCase): def test_basic(self): z = array([-1, 0, 1]) assert_(not iscomplexobj(z)) z = array([-1j, 0, -1]) assert_(iscomplexobj(z)) class TestIsrealobj(TestCase): def test_basic(self): z = array([-1, 0, 1]) assert_(isrealobj(z)) z = array([-1j, 0, -1]) assert_(not isrealobj(z)) class TestIsnan(TestCase): def test_goodvalues(self): z = array((-1., 0., 1.)) res = isnan(z) == 0 assert_all(alltrue(res, axis=0)) def test_posinf(self): with errstate(divide='ignore'): assert_all(isnan(array((1.,))/0.) == 0) def test_neginf(self): with errstate(divide='ignore'): assert_all(isnan(array((-1.,))/0.) == 0) def test_ind(self): with errstate(divide='ignore', invalid='ignore'): assert_all(isnan(array((0.,))/0.) == 1) #def test_qnan(self): log(-1) return pi*j now # assert_all(isnan(log(-1.)) == 1) def test_integer(self): assert_all(isnan(1) == 0) def test_complex(self): assert_all(isnan(1+1j) == 0) def test_complex1(self): with errstate(divide='ignore', invalid='ignore'): assert_all(isnan(array(0+0j)/0.) == 1) class TestIsfinite(TestCase): def test_goodvalues(self): z = array((-1., 0., 1.)) res = isfinite(z) == 1 assert_all(alltrue(res, axis=0)) def test_posinf(self): with errstate(divide='ignore', invalid='ignore'): assert_all(isfinite(array((1.,))/0.) == 0) def test_neginf(self): with errstate(divide='ignore', invalid='ignore'): assert_all(isfinite(array((-1.,))/0.) == 0) def test_ind(self): with errstate(divide='ignore', invalid='ignore'): assert_all(isfinite(array((0.,))/0.) == 0) #def test_qnan(self): # assert_all(isfinite(log(-1.)) == 0) def test_integer(self): assert_all(isfinite(1) == 1) def test_complex(self): assert_all(isfinite(1+1j) == 1) def test_complex1(self): with errstate(divide='ignore', invalid='ignore'): assert_all(isfinite(array(1+1j)/0.) == 0) class TestIsinf(TestCase): def test_goodvalues(self): z = array((-1., 0., 1.)) res = isinf(z) == 0 assert_all(alltrue(res, axis=0)) def test_posinf(self): with errstate(divide='ignore', invalid='ignore'): assert_all(isinf(array((1.,))/0.) == 1) def test_posinf_scalar(self): with errstate(divide='ignore', invalid='ignore'): assert_all(isinf(array(1.,)/0.) == 1) def test_neginf(self): with errstate(divide='ignore', invalid='ignore'): assert_all(isinf(array((-1.,))/0.) == 1) def test_neginf_scalar(self): with errstate(divide='ignore', invalid='ignore'): assert_all(isinf(array(-1.)/0.) == 1) def test_ind(self): with errstate(divide='ignore', invalid='ignore'): assert_all(isinf(array((0.,))/0.) == 0) #def test_qnan(self): # assert_all(isinf(log(-1.)) == 0) # assert_all(isnan(log(-1.)) == 1) class TestIsposinf(TestCase): def test_generic(self): with errstate(divide='ignore', invalid='ignore'): vals = isposinf(array((-1., 0, 1))/0.) assert_(vals[0] == 0) assert_(vals[1] == 0) assert_(vals[2] == 1) class TestIsneginf(TestCase): def test_generic(self): with errstate(divide='ignore', invalid='ignore'): vals = isneginf(array((-1., 0, 1))/0.) assert_(vals[0] == 1) assert_(vals[1] == 0) assert_(vals[2] == 0) class TestNanToNum(TestCase): def test_generic(self): with errstate(divide='ignore', invalid='ignore'): vals = nan_to_num(array((-1., 0, 1))/0.) assert_all(vals[0] < -1e10) and assert_all(isfinite(vals[0])) assert_(vals[1] == 0) assert_all(vals[2] > 1e10) and assert_all(isfinite(vals[2])) def test_integer(self): vals = nan_to_num(1) assert_all(vals == 1) def test_complex_good(self): vals = nan_to_num(1+1j) assert_all(vals == 1+1j) def test_complex_bad(self): with errstate(divide='ignore', invalid='ignore'): v = 1 + 1j v += array(0+1.j)/0. vals = nan_to_num(v) # !! This is actually (unexpectedly) zero assert_all(isfinite(vals)) def test_complex_bad2(self): with errstate(divide='ignore', invalid='ignore'): v = 1 + 1j v += array(-1+1.j)/0. vals = nan_to_num(v) assert_all(isfinite(vals)) #assert_all(vals.imag > 1e10) and assert_all(isfinite(vals)) # !! This is actually (unexpectedly) positive # !! inf. Comment out for now, and see if it # !! changes #assert_all(vals.real < -1e10) and assert_all(isfinite(vals)) class TestRealIfClose(TestCase): def test_basic(self): a = rand(10) b = real_if_close(a+1e-15j) assert_all(isrealobj(b)) assert_array_equal(a, b) b = real_if_close(a+1e-7j) assert_all(iscomplexobj(b)) b = real_if_close(a+1e-7j, tol=1e-6) assert_all(isrealobj(b)) class TestArrayConversion(TestCase): def test_asfarray(self): a = asfarray(array([1, 2, 3])) assert_equal(a.__class__, ndarray) assert_(issubdtype(a.dtype, float)) if __name__ == "__main__": run_module_suite() numpy-1.8.2/numpy/lib/tests/test_index_tricks.py0000664000175100017510000002300112370216243023177 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function from numpy.testing import * import numpy as np from numpy import ( array, ones, r_, mgrid, unravel_index, zeros, where, ndenumerate, fill_diagonal, diag_indices, diag_indices_from, s_, index_exp, ndindex ) class TestRavelUnravelIndex(TestCase): def test_basic(self): assert_equal(np.unravel_index(2, (2, 2)), (1, 0)) assert_equal(np.ravel_multi_index((1, 0), (2, 2)), 2) assert_equal(np.unravel_index(254, (17, 94)), (2, 66)) assert_equal(np.ravel_multi_index((2, 66), (17, 94)), 254) assert_raises(ValueError, np.unravel_index, -1, (2, 2)) assert_raises(TypeError, np.unravel_index, 0.5, (2, 2)) assert_raises(ValueError, np.unravel_index, 4, (2, 2)) assert_raises(ValueError, np.ravel_multi_index, (-3, 1), (2, 2)) assert_raises(ValueError, np.ravel_multi_index, (2, 1), (2, 2)) assert_raises(ValueError, np.ravel_multi_index, (0, -3), (2, 2)) assert_raises(ValueError, np.ravel_multi_index, (0, 2), (2, 2)) assert_raises(TypeError, np.ravel_multi_index, (0.1, 0.), (2, 2)) assert_equal(np.unravel_index((2*3 + 1)*6 + 4, (4, 3, 6)), [2, 1, 4]) assert_equal(np.ravel_multi_index([2, 1, 4], (4, 3, 6)), (2*3 + 1)*6 + 4) arr = np.array([[3, 6, 6], [4, 5, 1]]) assert_equal(np.ravel_multi_index(arr, (7, 6)), [22, 41, 37]) assert_equal(np.ravel_multi_index(arr, (7, 6), order='F'), [31, 41, 13]) assert_equal(np.ravel_multi_index(arr, (4, 6), mode='clip'), [22, 23, 19]) assert_equal(np.ravel_multi_index(arr, (4, 4), mode=('clip', 'wrap')), [12, 13, 13]) assert_equal(np.ravel_multi_index((3, 1, 4, 1), (6, 7, 8, 9)), 1621) assert_equal(np.unravel_index(np.array([22, 41, 37]), (7, 6)), [[3, 6, 6], [4, 5, 1]]) assert_equal(np.unravel_index(np.array([31, 41, 13]), (7, 6), order='F'), [[3, 6, 6], [4, 5, 1]]) assert_equal(np.unravel_index(1621, (6, 7, 8, 9)), [3, 1, 4, 1]) def test_dtypes(self): # Test with different data types for dtype in [np.int16, np.uint16, np.int32, np.uint32, np.int64, np.uint64]: coords = np.array([[1, 0, 1, 2, 3, 4], [1, 6, 1, 3, 2, 0]], dtype=dtype) shape = (5, 8) uncoords = 8*coords[0]+coords[1] assert_equal(np.ravel_multi_index(coords, shape), uncoords) assert_equal(coords, np.unravel_index(uncoords, shape)) uncoords = coords[0]+5*coords[1] assert_equal(np.ravel_multi_index(coords, shape, order='F'), uncoords) assert_equal(coords, np.unravel_index(uncoords, shape, order='F')) coords = np.array([[1, 0, 1, 2, 3, 4], [1, 6, 1, 3, 2, 0], [1, 3, 1, 0, 9, 5]], dtype=dtype) shape = (5, 8, 10) uncoords = 10*(8*coords[0]+coords[1])+coords[2] assert_equal(np.ravel_multi_index(coords, shape), uncoords) assert_equal(coords, np.unravel_index(uncoords, shape)) uncoords = coords[0]+5*(coords[1]+8*coords[2]) assert_equal(np.ravel_multi_index(coords, shape, order='F'), uncoords) assert_equal(coords, np.unravel_index(uncoords, shape, order='F')) def test_clipmodes(self): # Test clipmodes assert_equal(np.ravel_multi_index([5, 1, -1, 2], (4, 3, 7, 12), mode='wrap'), np.ravel_multi_index([1, 1, 6, 2], (4, 3, 7, 12))) assert_equal(np.ravel_multi_index([5, 1, -1, 2], (4, 3, 7, 12), mode=('wrap', 'raise', 'clip', 'raise')), np.ravel_multi_index([1, 1, 0, 2], (4, 3, 7, 12))) assert_raises(ValueError, np.ravel_multi_index, [5, 1, -1, 2], (4, 3, 7, 12)) class TestGrid(TestCase): def test_basic(self): a = mgrid[-1:1:10j] b = mgrid[-1:1:0.1] assert_(a.shape == (10,)) assert_(b.shape == (20,)) assert_(a[0] == -1) assert_almost_equal(a[-1], 1) assert_(b[0] == -1) assert_almost_equal(b[1]-b[0], 0.1, 11) assert_almost_equal(b[-1], b[0]+19*0.1, 11) assert_almost_equal(a[1]-a[0], 2.0/9.0, 11) def test_linspace_equivalence(self): y, st = np.linspace(2, 10, retstep=1) assert_almost_equal(st, 8/49.0) assert_array_almost_equal(y, mgrid[2:10:50j], 13) def test_nd(self): c = mgrid[-1:1:10j, -2:2:10j] d = mgrid[-1:1:0.1, -2:2:0.2] assert_(c.shape == (2, 10, 10)) assert_(d.shape == (2, 20, 20)) assert_array_equal(c[0][0,:], -ones(10, 'd')) assert_array_equal(c[1][:, 0], -2*ones(10, 'd')) assert_array_almost_equal(c[0][-1,:], ones(10, 'd'), 11) assert_array_almost_equal(c[1][:, -1], 2*ones(10, 'd'), 11) assert_array_almost_equal(d[0, 1,:]-d[0, 0,:], 0.1*ones(20, 'd'), 11) assert_array_almost_equal(d[1,:, 1]-d[1,:, 0], 0.2*ones(20, 'd'), 11) class TestConcatenator(TestCase): def test_1d(self): assert_array_equal(r_[1, 2, 3, 4, 5, 6], array([1, 2, 3, 4, 5, 6])) b = ones(5) c = r_[b, 0, 0, b] assert_array_equal(c, [1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1]) def test_mixed_type(self): g = r_[10.1, 1:10] assert_(g.dtype == 'f8') def test_more_mixed_type(self): g = r_[-10.1, array([1]), array([2, 3, 4]), 10.0] assert_(g.dtype == 'f8') def test_2d(self): b = rand(5, 5) c = rand(5, 5) d = r_['1', b, c] # append columns assert_(d.shape == (5, 10)) assert_array_equal(d[:, :5], b) assert_array_equal(d[:, 5:], c) d = r_[b, c] assert_(d.shape == (10, 5)) assert_array_equal(d[:5,:], b) assert_array_equal(d[5:,:], c) class TestNdenumerate(TestCase): def test_basic(self): a = array([[1, 2], [3, 4]]) assert_equal(list(ndenumerate(a)), [((0, 0), 1), ((0, 1), 2), ((1, 0), 3), ((1, 1), 4)]) class TestIndexExpression(TestCase): def test_regression_1(self): # ticket #1196 a = np.arange(2) assert_equal(a[:-1], a[s_[:-1]]) assert_equal(a[:-1], a[index_exp[:-1]]) def test_simple_1(self): a = np.random.rand(4, 5, 6) assert_equal(a[:, :3, [1, 2]], a[index_exp[:, :3, [1, 2]]]) assert_equal(a[:, :3, [1, 2]], a[s_[:, :3, [1, 2]]]) def test_c_(): a = np.c_[np.array([[1, 2, 3]]), 0, 0, np.array([[4, 5, 6]])] assert_equal(a, [[1, 2, 3, 0, 0, 4, 5, 6]]) def test_fill_diagonal(): a = zeros((3, 3), int) fill_diagonal(a, 5) yield (assert_array_equal, a, array([[5, 0, 0], [0, 5, 0], [0, 0, 5]])) #Test tall matrix a = zeros((10, 3), int) fill_diagonal(a, 5) yield (assert_array_equal, a, array([[5, 0, 0], [0, 5, 0], [0, 0, 5], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]])) #Test tall matrix wrap a = zeros((10, 3), int) fill_diagonal(a, 5, True) yield (assert_array_equal, a, array([[5, 0, 0], [0, 5, 0], [0, 0, 5], [0, 0, 0], [5, 0, 0], [0, 5, 0], [0, 0, 5], [0, 0, 0], [5, 0, 0], [0, 5, 0]])) #Test wide matrix a = zeros((3, 10), int) fill_diagonal(a, 5) yield (assert_array_equal, a, array([[5, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 5, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 5, 0, 0, 0, 0, 0, 0, 0]])) # The same function can operate on a 4-d array: a = zeros((3, 3, 3, 3), int) fill_diagonal(a, 4) i = array([0, 1, 2]) yield (assert_equal, where(a != 0), (i, i, i, i)) def test_diag_indices(): di = diag_indices(4) a = array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]) a[di] = 100 yield (assert_array_equal, a, array([[100, 2, 3, 4], [ 5, 100, 7, 8], [ 9, 10, 100, 12], [ 13, 14, 15, 100]])) # Now, we create indices to manipulate a 3-d array: d3 = diag_indices(2, 3) # And use it to set the diagonal of a zeros array to 1: a = zeros((2, 2, 2), int) a[d3] = 1 yield (assert_array_equal, a, array([[[1, 0], [0, 0]], [[0, 0], [0, 1]]]) ) def test_diag_indices_from(): x = np.random.random((4, 4)) r, c = diag_indices_from(x) assert_array_equal(r, np.arange(4)) assert_array_equal(c, np.arange(4)) def test_ndindex(): x = list(np.ndindex(1, 2, 3)) expected = [ix for ix, e in np.ndenumerate(np.zeros((1, 2, 3)))] assert_array_equal(x, expected) x = list(np.ndindex((1, 2, 3))) assert_array_equal(x, expected) # Test use of scalars and tuples x = list(np.ndindex((3,))) assert_array_equal(x, list(np.ndindex(3))) # Make sure size argument is optional x = list(np.ndindex()) assert_equal(x, [()]) x = list(np.ndindex(())) assert_equal(x, [()]) # Make sure 0-sized ndindex works correctly x = list(np.ndindex(*[0])) assert_equal(x, []) if __name__ == "__main__": run_module_suite() numpy-1.8.2/numpy/lib/tests/test_shape_base.py0000664000175100017510000002573312370216243022621 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function from numpy.testing import * from numpy.lib import * from numpy.core import * from numpy import matrix, asmatrix class TestApplyAlongAxis(TestCase): def test_simple(self): a = ones((20, 10), 'd') assert_array_equal(apply_along_axis(len, 0, a), len(a)*ones(shape(a)[1])) def test_simple101(self,level=11): a = ones((10, 101), 'd') assert_array_equal(apply_along_axis(len, 0, a), len(a)*ones(shape(a)[1])) def test_3d(self): a = arange(27).reshape((3, 3, 3)) assert_array_equal(apply_along_axis(sum, 0, a), [[27, 30, 33], [36, 39, 42], [45, 48, 51]]) class TestApplyOverAxes(TestCase): def test_simple(self): a = arange(24).reshape(2, 3, 4) aoa_a = apply_over_axes(sum, a, [0, 2]) assert_array_equal(aoa_a, array([[[60], [92], [124]]])) class TestArraySplit(TestCase): def test_integer_0_split(self): a = arange(10) try: res = array_split(a, 0) assert_(0) # it should have thrown a value error except ValueError: pass def test_integer_split(self): a = arange(10) res = array_split(a, 1) desired = [arange(10)] compare_results(res, desired) res = array_split(a, 2) desired = [arange(5), arange(5, 10)] compare_results(res, desired) res = array_split(a, 3) desired = [arange(4), arange(4, 7), arange(7, 10)] compare_results(res, desired) res = array_split(a, 4) desired = [arange(3), arange(3, 6), arange(6, 8), arange(8, 10)] compare_results(res, desired) res = array_split(a, 5) desired = [arange(2), arange(2, 4), arange(4, 6), arange(6, 8), arange(8, 10)] compare_results(res, desired) res = array_split(a, 6) desired = [arange(2), arange(2, 4), arange(4, 6), arange(6, 8), arange(8, 9), arange(9, 10)] compare_results(res, desired) res = array_split(a, 7) desired = [arange(2), arange(2, 4), arange(4, 6), arange(6, 7), arange(7, 8), arange(8, 9), arange(9, 10)] compare_results(res, desired) res = array_split(a, 8) desired = [arange(2), arange(2, 4), arange(4, 5), arange(5, 6), arange(6, 7), arange(7, 8), arange(8, 9), arange(9, 10)] compare_results(res, desired) res = array_split(a, 9) desired = [arange(2), arange(2, 3), arange(3, 4), arange(4, 5), arange(5, 6), arange(6, 7), arange(7, 8), arange(8, 9), arange(9, 10)] compare_results(res, desired) res = array_split(a, 10) desired = [arange(1), arange(1, 2), arange(2, 3), arange(3, 4), arange(4, 5), arange(5, 6), arange(6, 7), arange(7, 8), arange(8, 9), arange(9, 10)] compare_results(res, desired) res = array_split(a, 11) desired = [arange(1), arange(1, 2), arange(2, 3), arange(3, 4), arange(4, 5), arange(5, 6), arange(6, 7), arange(7, 8), arange(8, 9), arange(9, 10), array([])] compare_results(res, desired) def test_integer_split_2D_rows(self): a = array([arange(10), arange(10)]) res = array_split(a, 3, axis=0) desired = [array([arange(10)]), array([arange(10)]), array([])] compare_results(res, desired) def test_integer_split_2D_cols(self): a = array([arange(10), arange(10)]) res = array_split(a, 3, axis=-1) desired = [array([arange(4), arange(4)]), array([arange(4, 7), arange(4, 7)]), array([arange(7, 10), arange(7, 10)])] compare_results(res, desired) def test_integer_split_2D_default(self): """ This will fail if we change default axis """ a = array([arange(10), arange(10)]) res = array_split(a, 3) desired = [array([arange(10)]), array([arange(10)]), array([])] compare_results(res, desired) #perhaps should check higher dimensions def test_index_split_simple(self): a = arange(10) indices = [1, 5, 7] res = array_split(a, indices, axis=-1) desired = [arange(0, 1), arange(1, 5), arange(5, 7), arange(7, 10)] compare_results(res, desired) def test_index_split_low_bound(self): a = arange(10) indices = [0, 5, 7] res = array_split(a, indices, axis=-1) desired = [array([]), arange(0, 5), arange(5, 7), arange(7, 10)] compare_results(res, desired) def test_index_split_high_bound(self): a = arange(10) indices = [0, 5, 7, 10, 12] res = array_split(a, indices, axis=-1) desired = [array([]), arange(0, 5), arange(5, 7), arange(7, 10), array([]), array([])] compare_results(res, desired) class TestSplit(TestCase): """* This function is essentially the same as array_split, except that it test if splitting will result in an equal split. Only test for this case. *""" def test_equal_split(self): a = arange(10) res = split(a, 2) desired = [arange(5), arange(5, 10)] compare_results(res, desired) def test_unequal_split(self): a = arange(10) try: res = split(a, 3) assert_(0) # should raise an error except ValueError: pass class TestDstack(TestCase): def test_0D_array(self): a = array(1); b = array(2); res=dstack([a, b]) desired = array([[[1, 2]]]) assert_array_equal(res, desired) def test_1D_array(self): a = array([1]); b = array([2]); res=dstack([a, b]) desired = array([[[1, 2]]]) assert_array_equal(res, desired) def test_2D_array(self): a = array([[1], [2]]); b = array([[1], [2]]); res=dstack([a, b]) desired = array([[[1, 1]], [[2, 2,]]]) assert_array_equal(res, desired) def test_2D_array2(self): a = array([1, 2]); b = array([1, 2]); res=dstack([a, b]) desired = array([[[1, 1], [2, 2]]]) assert_array_equal(res, desired) """ array_split has more comprehensive test of splitting. only do simple test on hsplit, vsplit, and dsplit """ class TestHsplit(TestCase): """ only testing for integer splits. """ def test_0D_array(self): a= array(1) try: hsplit(a, 2) assert_(0) except ValueError: pass def test_1D_array(self): a= array([1, 2, 3, 4]) res = hsplit(a, 2) desired = [array([1, 2]), array([3, 4])] compare_results(res, desired) def test_2D_array(self): a= array([[1, 2, 3, 4], [1, 2, 3, 4]]) res = hsplit(a, 2) desired = [array([[1, 2], [1, 2]]), array([[3, 4], [3, 4]])] compare_results(res, desired) class TestVsplit(TestCase): """ only testing for integer splits. """ def test_1D_array(self): a= array([1, 2, 3, 4]) try: vsplit(a, 2) assert_(0) except ValueError: pass def test_2D_array(self): a= array([[1, 2, 3, 4], [1, 2, 3, 4]]) res = vsplit(a, 2) desired = [array([[1, 2, 3, 4]]), array([[1, 2, 3, 4]])] compare_results(res, desired) class TestDsplit(TestCase): """ only testing for integer splits. """ def test_2D_array(self): a= array([[1, 2, 3, 4], [1, 2, 3, 4]]) try: dsplit(a, 2) assert_(0) except ValueError: pass def test_3D_array(self): a= array([[[1, 2, 3, 4], [1, 2, 3, 4]], [[1, 2, 3, 4], [1, 2, 3, 4]]]) res = dsplit(a, 2) desired = [array([[[1, 2], [1, 2]], [[1, 2], [1, 2]]]), array([[[3, 4], [3, 4]], [[3, 4], [3, 4]]])] compare_results(res, desired) class TestSqueeze(TestCase): def test_basic(self): a = rand(20, 10, 10, 1, 1) b = rand(20, 1, 10, 1, 20) c = rand(1, 1, 20, 10) assert_array_equal(squeeze(a), reshape(a, (20, 10, 10))) assert_array_equal(squeeze(b), reshape(b, (20, 10, 20))) assert_array_equal(squeeze(c), reshape(c, (20, 10))) # Squeezing to 0-dim should still give an ndarray a = [[[1.5]]] res = squeeze(a) assert_equal(res, 1.5) assert_equal(res.ndim, 0) assert_equal(type(res), ndarray) class TestKron(TestCase): def test_return_type(self): a = ones([2, 2]) m = asmatrix(a) assert_equal(type(kron(a, a)), ndarray) assert_equal(type(kron(m, m)), matrix) assert_equal(type(kron(a, m)), matrix) assert_equal(type(kron(m, a)), matrix) class myarray(ndarray): __array_priority__ = 0.0 ma = myarray(a.shape, a.dtype, a.data) assert_equal(type(kron(a, a)), ndarray) assert_equal(type(kron(ma, ma)), myarray) assert_equal(type(kron(a, ma)), ndarray) assert_equal(type(kron(ma, a)), myarray) class TestTile(TestCase): def test_basic(self): a = array([0, 1, 2]) b = [[1, 2], [3, 4]] assert_equal(tile(a, 2), [0, 1, 2, 0, 1, 2]) assert_equal(tile(a, (2, 2)), [[0, 1, 2, 0, 1, 2], [0, 1, 2, 0, 1, 2]]) assert_equal(tile(a, (1, 2)), [[0, 1, 2, 0, 1, 2]]) assert_equal(tile(b, 2), [[1, 2, 1, 2], [3, 4, 3, 4]]) assert_equal(tile(b, (2, 1)), [[1, 2], [3, 4], [1, 2], [3, 4]]) assert_equal(tile(b, (2, 2)), [[1, 2, 1, 2], [3, 4, 3, 4], [1, 2, 1, 2], [3, 4, 3, 4]]) def test_empty(self): a = array([[[]]]) d = tile(a, (3, 2, 5)).shape assert_equal(d, (3, 2, 0)) def test_kroncompare(self): import numpy.random as nr reps=[(2,), (1, 2), (2, 1), (2, 2), (2, 3, 2), (3, 2)] shape=[(3,), (2, 3), (3, 4, 3), (3, 2, 3), (4, 3, 2, 4), (2, 2)] for s in shape: b = nr.randint(0, 10, size=s) for r in reps: a = ones(r, b.dtype) large = tile(b, r) klarge = kron(a, b) assert_equal(large, klarge) class TestMayShareMemory(TestCase): def test_basic(self): d = ones((50, 60)) d2 = ones((30, 60, 6)) self.assertTrue(may_share_memory(d, d)) self.assertTrue(may_share_memory(d, d[::-1])) self.assertTrue(may_share_memory(d, d[::2])) self.assertTrue(may_share_memory(d, d[1:, ::-1])) self.assertFalse(may_share_memory(d[::-1], d2)) self.assertFalse(may_share_memory(d[::2], d2)) self.assertFalse(may_share_memory(d[1:, ::-1], d2)) self.assertTrue(may_share_memory(d2[1:, ::-1], d2)) # Utility def compare_results(res, desired): for i in range(len(desired)): assert_array_equal(res[i], desired[i]) if __name__ == "__main__": run_module_suite() numpy-1.8.2/numpy/lib/tests/test_arraysetops.py0000664000175100017510000002020712370216243023072 0ustar vagrantvagrant00000000000000"""Test functions for 1D array set operations. """ from __future__ import division, absolute_import, print_function from numpy.testing import * import numpy as np from numpy.lib.arraysetops import * import warnings class TestSetOps(TestCase): def test_unique( self ): def check_all(a, b, i1, i2, dt): msg = "check values failed for type '%s'" % dt v = unique(a) assert_array_equal(v, b, msg) msg = "check indexes failed for type '%s'" % dt v, j = unique(a, 1, 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) 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) assert_array_equal(v, b, msg) assert_array_equal(j1, i1, msg) assert_array_equal(j2, i2, 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 # test for numeric arrays types = [] types.extend(np.typecodes['AllInteger']) types.extend(np.typecodes['AllFloat']) types.append('datetime64[D]') types.append('timedelta64[D]') for dt in types: aa = np.array(a, dt) bb = np.array(b, dt) check_all(aa, bb, i1, i2, dt) # test for object arrays dt = 'O' aa = np.empty(len(a), dt) aa[:] = a bb = np.empty(len(b), dt) bb[:] = b check_all(aa, bb, i1, i2, 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) # test for ticket #2799 aa = [1.+0.j, 1- 1.j, 1] assert_array_equal(np.unique(aa), [ 1.-1.j, 1.+0.j]) def test_intersect1d( self ): # unique inputs a = np.array( [5, 7, 1, 2] ) b = np.array( [2, 4, 3, 1, 5] ) ec = np.array( [1, 2, 5] ) c = intersect1d( a, b, assume_unique=True ) assert_array_equal( c, ec ) # non-unique inputs a = np.array( [5, 5, 7, 1, 2] ) b = np.array( [2, 1, 4, 3, 3, 1, 5] ) ed = np.array( [1, 2, 5] ) c = intersect1d( a, b ) assert_array_equal( c, ed ) assert_array_equal([], intersect1d([], [])) def test_setxor1d( self ): a = np.array( [5, 7, 1, 2] ) b = np.array( [2, 4, 3, 1, 5] ) ec = np.array( [3, 4, 7] ) c = setxor1d( a, b ) assert_array_equal( c, ec ) a = np.array( [1, 2, 3] ) b = np.array( [6, 5, 4] ) ec = np.array( [1, 2, 3, 4, 5, 6] ) c = setxor1d( a, b ) assert_array_equal( c, ec ) a = np.array( [1, 8, 2, 3] ) b = np.array( [6, 5, 4, 8] ) ec = np.array( [1, 2, 3, 4, 5, 6] ) c = setxor1d( a, b ) assert_array_equal( c, ec ) assert_array_equal([], setxor1d([], [])) def test_ediff1d(self): zero_elem = np.array([]) one_elem = np.array([1]) two_elem = np.array([1, 2]) assert_array_equal([], ediff1d(zero_elem)) assert_array_equal([0], ediff1d(zero_elem, to_begin=0)) assert_array_equal([0], ediff1d(zero_elem, to_end=0)) assert_array_equal([-1, 0], ediff1d(zero_elem, to_begin=-1, to_end=0)) assert_array_equal([], ediff1d(one_elem)) assert_array_equal([1], ediff1d(two_elem)) def test_in1d(self): # we use two different sizes for the b array here to test the # two different paths in in1d(). for mult in (1, 10): # One check without np.array, to make sure lists are handled correct a = [5, 7, 1, 2] b = [2, 4, 3, 1, 5] * mult ec = np.array([True, False, True, True]) c = in1d(a, b, assume_unique=True) assert_array_equal(c, ec) a[0] = 8 ec = np.array([False, False, True, True]) c = in1d(a, b, assume_unique=True) assert_array_equal(c, ec) a[0], a[3] = 4, 8 ec = np.array([True, False, True, False]) c = in1d(a, b, assume_unique=True) assert_array_equal(c, ec) a = np.array([5, 4, 5, 3, 4, 4, 3, 4, 3, 5, 2, 1, 5, 5]) b = [2, 3, 4] * mult ec = [False, True, False, True, True, True, True, True, True, False, True, False, False, False] c = in1d(a, b) assert_array_equal(c, ec) b = b + [5, 5, 4] * mult ec = [True, True, True, True, True, True, True, True, True, True, True, False, True, True] c = in1d(a, b) assert_array_equal(c, ec) a = np.array([5, 7, 1, 2]) b = np.array([2, 4, 3, 1, 5] * mult) ec = np.array([True, False, True, True]) c = in1d(a, b) assert_array_equal(c, ec) a = np.array([5, 7, 1, 1, 2]) b = np.array([2, 4, 3, 3, 1, 5] * mult) ec = np.array([True, False, True, True, True]) c = in1d(a, b) assert_array_equal(c, ec) a = np.array([5, 5]) b = np.array([2, 2] * mult) ec = np.array([False, False]) c = in1d(a, b) assert_array_equal(c, ec) a = np.array([5]) b = np.array([2]) ec = np.array([False]) c = in1d(a, b) assert_array_equal(c, ec) assert_array_equal(in1d([], []), []) def test_in1d_char_array( self ): a = np.array(['a', 'b', 'c', 'd', 'e', 'c', 'e', 'b']) b = np.array(['a', 'c']) ec = np.array([True, False, True, False, False, True, False, False]) c = in1d(a, b) assert_array_equal(c, ec) def test_in1d_invert(self): "Test in1d's invert parameter" # We use two different sizes for the b array here to test the # two different paths in in1d(). for mult in (1, 10): a = np.array([5, 4, 5, 3, 4, 4, 3, 4, 3, 5, 2, 1, 5, 5]) b = [2, 3, 4] * mult assert_array_equal(np.invert(in1d(a, b)), in1d(a, b, invert=True)) def test_in1d_ravel(self): # Test that in1d ravels its input arrays. This is not documented # behavior however. The test is to ensure consistentency. a = np.arange(6).reshape(2, 3) b = np.arange(3, 9).reshape(3, 2) long_b = np.arange(3, 63).reshape(30, 2) ec = np.array([False, False, False, True, True, True]) assert_array_equal(in1d(a, b, assume_unique=True), ec) assert_array_equal(in1d(a, b, assume_unique=False), ec) assert_array_equal(in1d(a, long_b, assume_unique=True), ec) assert_array_equal(in1d(a, long_b, assume_unique=False), ec) def test_union1d( self ): a = np.array( [5, 4, 7, 1, 2] ) b = np.array( [2, 4, 3, 3, 2, 1, 5] ) ec = np.array( [1, 2, 3, 4, 5, 7] ) c = union1d( a, b ) assert_array_equal( c, ec ) assert_array_equal([], union1d([], [])) def test_setdiff1d( self ): a = np.array( [6, 5, 4, 7, 1, 2, 7, 4] ) b = np.array( [2, 4, 3, 3, 2, 1, 5] ) ec = np.array( [6, 7] ) c = setdiff1d( a, b ) assert_array_equal( c, ec ) a = np.arange( 21 ) b = np.arange( 19 ) ec = np.array( [19, 20] ) c = setdiff1d( a, b ) assert_array_equal( c, ec ) assert_array_equal([], setdiff1d([], [])) def test_setdiff1d_char_array(self): a = np.array(['a', 'b', 'c']) b = np.array(['a', 'b', 's']) assert_array_equal(setdiff1d(a, b), np.array(['c'])) def test_manyways( self ): a = np.array( [5, 7, 1, 2, 8] ) b = np.array( [9, 8, 2, 4, 3, 1, 5] ) c1 = setxor1d( a, b ) aux1 = intersect1d( a, b ) aux2 = union1d( a, b ) c2 = setdiff1d( aux2, aux1 ) assert_array_equal( c1, c2 ) if __name__ == "__main__": run_module_suite() numpy-1.8.2/numpy/lib/tests/test_stride_tricks.py0000664000175100017510000001713112370216243023371 0ustar vagrantvagrant00000000000000from __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): """ Broadcast a list of arrays with the given input shapes and check the common output shape. """ inarrays = [np.zeros(s) for s in input_shapes] outarrays = broadcast_arrays(*inarrays) outshapes = [a.shape for a in outarrays] expected = [expected_shape] * len(inarrays) assert_equal(outshapes, expected) def assert_incompatible_shapes_raise(input_shapes): """ Broadcast a list of arrays with the given (incompatible) input shapes and check that they raise a ValueError. """ inarrays = [np.zeros(s) for s in input_shapes] assert_raises(ValueError, broadcast_arrays, *inarrays) def assert_same_as_ufunc(shape0, shape1, transposed=False, flipped=False): """ Broadcast two shapes against each other and check that the data layout is the same as if a ufunc did the broadcasting. """ x0 = np.zeros(shape0, dtype=int) # Note that multiply.reduce's identity element is 1.0, so when shape1==(), # this gives the desired n==1. n = int(np.multiply.reduce(shape1)) x1 = np.arange(n).reshape(shape1) if transposed: x0 = x0.T x1 = x1.T if flipped: x0 = x0[::-1] x1 = x1[::-1] # Use the add ufunc to do the broadcasting. Since we're adding 0s to x1, the # result should be exactly the same as the broadcasted view of x1. y = x0 + x1 b0, b1 = broadcast_arrays(x0, x1) assert_array_equal(y, b1) def test_same(): x = np.arange(10) y = np.arange(10) bx, by = broadcast_arrays(x, y) assert_array_equal(x, bx) assert_array_equal(y, by) def test_one_off(): x = np.array([[1, 2, 3]]) y = np.array([[1], [2], [3]]) bx, by = broadcast_arrays(x, y) bx0 = np.array([[1, 2, 3], [1, 2, 3], [1, 2, 3]]) by0 = bx0.T assert_array_equal(bx0, bx) assert_array_equal(by0, by) def test_same_input_shapes(): """ Check that the final shape is just the input shape. """ data = [ (), (1,), (3,), (0, 1), (0, 3), (1, 0), (3, 0), (1, 3), (3, 1), (3, 3), ] for shape in data: input_shapes = [shape] # Single input. assert_shapes_correct(input_shapes, shape) # Double input. input_shapes2 = [shape, shape] assert_shapes_correct(input_shapes2, shape) # Triple input. input_shapes3 = [shape, shape, shape] assert_shapes_correct(input_shapes3, shape) def test_two_compatible_by_ones_input_shapes(): """ Check that two different input shapes (of the same length but some have 1s) broadcast to the correct shape. """ data = [ [[(1,), (3,)], (3,)], [[(1, 3), (3, 3)], (3, 3)], [[(3, 1), (3, 3)], (3, 3)], [[(1, 3), (3, 1)], (3, 3)], [[(1, 1), (3, 3)], (3, 3)], [[(1, 1), (1, 3)], (1, 3)], [[(1, 1), (3, 1)], (3, 1)], [[(1, 0), (0, 0)], (0, 0)], [[(0, 1), (0, 0)], (0, 0)], [[(1, 0), (0, 1)], (0, 0)], [[(1, 1), (0, 0)], (0, 0)], [[(1, 1), (1, 0)], (1, 0)], [[(1, 1), (0, 1)], (0, 1)], ] for input_shapes, expected_shape in data: assert_shapes_correct(input_shapes, expected_shape) # Reverse the input shapes since broadcasting should be symmetric. assert_shapes_correct(input_shapes[::-1], expected_shape) def test_two_compatible_by_prepending_ones_input_shapes(): """ Check that two different input shapes (of different lengths) broadcast to the correct shape. """ data = [ [[(), (3,)], (3,)], [[(3,), (3, 3)], (3, 3)], [[(3,), (3, 1)], (3, 3)], [[(1,), (3, 3)], (3, 3)], [[(), (3, 3)], (3, 3)], [[(1, 1), (3,)], (1, 3)], [[(1,), (3, 1)], (3, 1)], [[(1,), (1, 3)], (1, 3)], [[(), (1, 3)], (1, 3)], [[(), (3, 1)], (3, 1)], [[(), (0,)], (0,)], [[(0,), (0, 0)], (0, 0)], [[(0,), (0, 1)], (0, 0)], [[(1,), (0, 0)], (0, 0)], [[(), (0, 0)], (0, 0)], [[(1, 1), (0,)], (1, 0)], [[(1,), (0, 1)], (0, 1)], [[(1,), (1, 0)], (1, 0)], [[(), (1, 0)], (1, 0)], [[(), (0, 1)], (0, 1)], ] for input_shapes, expected_shape in data: assert_shapes_correct(input_shapes, expected_shape) # Reverse the input shapes since broadcasting should be symmetric. assert_shapes_correct(input_shapes[::-1], expected_shape) def test_incompatible_shapes_raise_valueerror(): """ Check that a ValueError is raised for incompatible shapes. """ data = [ [(3,), (4,)], [(2, 3), (2,)], [(3,), (3,), (4,)], [(1, 3, 4), (2, 3, 3)], ] for input_shapes in data: assert_incompatible_shapes_raise(input_shapes) # Reverse the input shapes since broadcasting should be symmetric. assert_incompatible_shapes_raise(input_shapes[::-1]) def test_same_as_ufunc(): """ Check that the data layout is the same as if a ufunc did the operation. """ data = [ [[(1,), (3,)], (3,)], [[(1, 3), (3, 3)], (3, 3)], [[(3, 1), (3, 3)], (3, 3)], [[(1, 3), (3, 1)], (3, 3)], [[(1, 1), (3, 3)], (3, 3)], [[(1, 1), (1, 3)], (1, 3)], [[(1, 1), (3, 1)], (3, 1)], [[(1, 0), (0, 0)], (0, 0)], [[(0, 1), (0, 0)], (0, 0)], [[(1, 0), (0, 1)], (0, 0)], [[(1, 1), (0, 0)], (0, 0)], [[(1, 1), (1, 0)], (1, 0)], [[(1, 1), (0, 1)], (0, 1)], [[(), (3,)], (3,)], [[(3,), (3, 3)], (3, 3)], [[(3,), (3, 1)], (3, 3)], [[(1,), (3, 3)], (3, 3)], [[(), (3, 3)], (3, 3)], [[(1, 1), (3,)], (1, 3)], [[(1,), (3, 1)], (3, 1)], [[(1,), (1, 3)], (1, 3)], [[(), (1, 3)], (1, 3)], [[(), (3, 1)], (3, 1)], [[(), (0,)], (0,)], [[(0,), (0, 0)], (0, 0)], [[(0,), (0, 1)], (0, 0)], [[(1,), (0, 0)], (0, 0)], [[(), (0, 0)], (0, 0)], [[(1, 1), (0,)], (1, 0)], [[(1,), (0, 1)], (0, 1)], [[(1,), (1, 0)], (1, 0)], [[(), (1, 0)], (1, 0)], [[(), (0, 1)], (0, 1)], ] for input_shapes, expected_shape in data: assert_same_as_ufunc(input_shapes[0], input_shapes[1], "Shapes: %s %s" % (input_shapes[0], input_shapes[1])) # Reverse the input shapes since broadcasting should be symmetric. assert_same_as_ufunc(input_shapes[1], input_shapes[0]) # Try them transposed, too. assert_same_as_ufunc(input_shapes[0], input_shapes[1], True) # ... and flipped for non-rank-0 inputs in order to test negative # strides. if () not in input_shapes: 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() numpy-1.8.2/numpy/lib/tests/test__datasource.py0000664000175100017510000002432412370216243023013 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function import os import sys import numpy.lib._datasource as datasource from tempfile import mkdtemp, mkstemp, NamedTemporaryFile from shutil import rmtree from numpy.compat import asbytes from numpy.testing import * if sys.version_info[0] >= 3: import urllib.request as urllib_request from urllib.parse import urlparse from urllib.error import URLError else: import urllib2 as urllib_request from urlparse import urlparse from urllib2 import URLError def urlopen_stub(url, data=None): '''Stub to replace urlopen for testing.''' if url == valid_httpurl(): tmpfile = NamedTemporaryFile(prefix='urltmp_') return tmpfile else: raise URLError('Name or service not known') # setup and teardown old_urlopen = None def setup(): global old_urlopen old_urlopen = urllib_request.urlopen urllib_request.urlopen = urlopen_stub def teardown(): urllib_request.urlopen = old_urlopen # A valid website for more robust testing http_path = 'http://www.google.com/' http_file = 'index.html' http_fakepath = 'http://fake.abc.web/site/' http_fakefile = 'fake.txt' malicious_files = ['/etc/shadow', '../../shadow', '..\\system.dat', 'c:\\windows\\system.dat'] magic_line = asbytes('three is the magic number') # Utility functions used by many TestCases def valid_textfile(filedir): # Generate and return a valid temporary file. fd, path = mkstemp(suffix='.txt', prefix='dstmp_', dir=filedir, text=True) os.close(fd) return path def invalid_textfile(filedir): # Generate and return an invalid filename. fd, path = mkstemp(suffix='.txt', prefix='dstmp_', dir=filedir) os.close(fd) os.remove(path) return path def valid_httpurl(): return http_path+http_file def invalid_httpurl(): return http_fakepath+http_fakefile def valid_baseurl(): return http_path def invalid_baseurl(): return http_fakepath def valid_httpfile(): return http_file def invalid_httpfile(): return http_fakefile class TestDataSourceOpen(TestCase): def setUp(self): self.tmpdir = mkdtemp() self.ds = datasource.DataSource(self.tmpdir) def tearDown(self): rmtree(self.tmpdir) del self.ds def test_ValidHTTP(self): fh = self.ds.open(valid_httpurl()) assert_(fh) fh.close() def test_InvalidHTTP(self): url = invalid_httpurl() self.assertRaises(IOError, self.ds.open, url) try: self.ds.open(url) except IOError as e: # Regression test for bug fixed in r4342. assert_(e.errno is None) def test_InvalidHTTPCacheURLError(self): self.assertRaises(URLError, self.ds._cache, invalid_httpurl()) def test_ValidFile(self): local_file = valid_textfile(self.tmpdir) fh = self.ds.open(local_file) assert_(fh) fh.close() def test_InvalidFile(self): invalid_file = invalid_textfile(self.tmpdir) self.assertRaises(IOError, self.ds.open, invalid_file) def test_ValidGzipFile(self): try: import gzip except ImportError: # We don't have the gzip capabilities to test. import nose raise nose.SkipTest # Test datasource's internal file_opener for Gzip files. filepath = os.path.join(self.tmpdir, 'foobar.txt.gz') fp = gzip.open(filepath, 'w') fp.write(magic_line) fp.close() fp = self.ds.open(filepath) result = fp.readline() fp.close() self.assertEqual(magic_line, result) def test_ValidBz2File(self): try: import bz2 except ImportError: # We don't have the bz2 capabilities to test. import nose raise nose.SkipTest # Test datasource's internal file_opener for BZip2 files. filepath = os.path.join(self.tmpdir, 'foobar.txt.bz2') fp = bz2.BZ2File(filepath, 'w') fp.write(magic_line) fp.close() fp = self.ds.open(filepath) result = fp.readline() fp.close() self.assertEqual(magic_line, result) class TestDataSourceExists(TestCase): def setUp(self): self.tmpdir = mkdtemp() self.ds = datasource.DataSource(self.tmpdir) def tearDown(self): rmtree(self.tmpdir) del self.ds def test_ValidHTTP(self): assert_(self.ds.exists(valid_httpurl())) def test_InvalidHTTP(self): self.assertEqual(self.ds.exists(invalid_httpurl()), False) def test_ValidFile(self): # Test valid file in destpath tmpfile = valid_textfile(self.tmpdir) assert_(self.ds.exists(tmpfile)) # Test valid local file not in destpath localdir = mkdtemp() tmpfile = valid_textfile(localdir) assert_(self.ds.exists(tmpfile)) rmtree(localdir) def test_InvalidFile(self): tmpfile = invalid_textfile(self.tmpdir) self.assertEqual(self.ds.exists(tmpfile), False) class TestDataSourceAbspath(TestCase): def setUp(self): self.tmpdir = os.path.abspath(mkdtemp()) self.ds = datasource.DataSource(self.tmpdir) def tearDown(self): rmtree(self.tmpdir) del self.ds def test_ValidHTTP(self): scheme, netloc, upath, pms, qry, frg = urlparse(valid_httpurl()) local_path = os.path.join(self.tmpdir, netloc, upath.strip(os.sep).strip('/')) self.assertEqual(local_path, self.ds.abspath(valid_httpurl())) def test_ValidFile(self): tmpfile = valid_textfile(self.tmpdir) tmpfilename = os.path.split(tmpfile)[-1] # Test with filename only self.assertEqual(tmpfile, self.ds.abspath(os.path.split(tmpfile)[-1])) # Test filename with complete path self.assertEqual(tmpfile, self.ds.abspath(tmpfile)) def test_InvalidHTTP(self): scheme, netloc, upath, pms, qry, frg = urlparse(invalid_httpurl()) invalidhttp = os.path.join(self.tmpdir, netloc, upath.strip(os.sep).strip('/')) self.assertNotEqual(invalidhttp, self.ds.abspath(valid_httpurl())) def test_InvalidFile(self): invalidfile = valid_textfile(self.tmpdir) tmpfile = valid_textfile(self.tmpdir) tmpfilename = os.path.split(tmpfile)[-1] # Test with filename only self.assertNotEqual(invalidfile, self.ds.abspath(tmpfilename)) # Test filename with complete path self.assertNotEqual(invalidfile, self.ds.abspath(tmpfile)) def test_sandboxing(self): tmpfile = valid_textfile(self.tmpdir) tmpfilename = os.path.split(tmpfile)[-1] tmp_path = lambda x: os.path.abspath(self.ds.abspath(x)) assert_(tmp_path(valid_httpurl()).startswith(self.tmpdir)) assert_(tmp_path(invalid_httpurl()).startswith(self.tmpdir)) assert_(tmp_path(tmpfile).startswith(self.tmpdir)) assert_(tmp_path(tmpfilename).startswith(self.tmpdir)) for fn in malicious_files: assert_(tmp_path(http_path+fn).startswith(self.tmpdir)) assert_(tmp_path(fn).startswith(self.tmpdir)) def test_windows_os_sep(self): orig_os_sep = os.sep try: os.sep = '\\' self.test_ValidHTTP() self.test_ValidFile() self.test_InvalidHTTP() self.test_InvalidFile() self.test_sandboxing() finally: os.sep = orig_os_sep class TestRepositoryAbspath(TestCase): def setUp(self): self.tmpdir = os.path.abspath(mkdtemp()) self.repos = datasource.Repository(valid_baseurl(), self.tmpdir) def tearDown(self): rmtree(self.tmpdir) del self.repos def test_ValidHTTP(self): scheme, netloc, upath, pms, qry, frg = urlparse(valid_httpurl()) local_path = os.path.join(self.repos._destpath, netloc, \ upath.strip(os.sep).strip('/')) filepath = self.repos.abspath(valid_httpfile()) self.assertEqual(local_path, filepath) def test_sandboxing(self): tmp_path = lambda x: os.path.abspath(self.repos.abspath(x)) assert_(tmp_path(valid_httpfile()).startswith(self.tmpdir)) for fn in malicious_files: assert_(tmp_path(http_path+fn).startswith(self.tmpdir)) assert_(tmp_path(fn).startswith(self.tmpdir)) def test_windows_os_sep(self): orig_os_sep = os.sep try: os.sep = '\\' self.test_ValidHTTP() self.test_sandboxing() finally: os.sep = orig_os_sep class TestRepositoryExists(TestCase): def setUp(self): self.tmpdir = mkdtemp() self.repos = datasource.Repository(valid_baseurl(), self.tmpdir) def tearDown(self): rmtree(self.tmpdir) del self.repos def test_ValidFile(self): # Create local temp file tmpfile = valid_textfile(self.tmpdir) assert_(self.repos.exists(tmpfile)) def test_InvalidFile(self): tmpfile = invalid_textfile(self.tmpdir) self.assertEqual(self.repos.exists(tmpfile), False) def test_RemoveHTTPFile(self): assert_(self.repos.exists(valid_httpurl())) def test_CachedHTTPFile(self): localfile = valid_httpurl() # Create a locally cached temp file with an URL based # directory structure. This is similar to what Repository.open # would do. scheme, netloc, upath, pms, qry, frg = urlparse(localfile) local_path = os.path.join(self.repos._destpath, netloc) os.mkdir(local_path, 0o0700) tmpfile = valid_textfile(local_path) assert_(self.repos.exists(tmpfile)) class TestOpenFunc(TestCase): def setUp(self): self.tmpdir = mkdtemp() def tearDown(self): rmtree(self.tmpdir) def test_DataSourceOpen(self): local_file = valid_textfile(self.tmpdir) # Test case where destpath is passed in fp = datasource.open(local_file, destpath=self.tmpdir) assert_(fp) fp.close() # Test case where default destpath is used fp = datasource.open(local_file) assert_(fp) fp.close() if __name__ == "__main__": run_module_suite() numpy-1.8.2/numpy/lib/tests/test_nanfunctions.py0000664000175100017510000004475312370216243023237 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function import warnings import numpy as np from numpy.testing import ( run_module_suite, TestCase, assert_, assert_equal, assert_almost_equal, assert_raises ) # 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.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.1610, 0.1859, 0.3146])] class TestNanFunctions_MinMax(TestCase): nanfuncs = [np.nanmin, np.nanmax] stdfuncs = [np.min, np.max] def test_mutation(self): # Check that passed array is not modified. ndat = _ndat.copy() for f in self.nanfuncs: f(ndat) assert_equal(ndat, _ndat) def test_keepdims(self): mat = np.eye(3) for nf, rf in zip(self.nanfuncs, self.stdfuncs): for axis in [None, 0, 1]: tgt = rf(mat, axis=axis, keepdims=True) res = nf(mat, axis=axis, keepdims=True) assert_(res.ndim == tgt.ndim) def test_out(self): mat = np.eye(3) for nf, rf in zip(self.nanfuncs, self.stdfuncs): resout = np.zeros(3) tgt = rf(mat, axis=1) res = nf(mat, axis=1, out=resout) assert_almost_equal(res, resout) assert_almost_equal(res, tgt) def test_dtype_from_input(self): codes = 'efdgFDG' for nf, rf in zip(self.nanfuncs, self.stdfuncs): for c in codes: mat = np.eye(3, dtype=c) tgt = rf(mat, axis=1).dtype.type res = nf(mat, axis=1).dtype.type assert_(res is tgt) # scalar case tgt = rf(mat, axis=None).dtype.type res = nf(mat, axis=None).dtype.type assert_(res is tgt) def test_result_values(self): for nf, rf in zip(self.nanfuncs, self.stdfuncs): tgt = [rf(d) for d in _rdat] res = nf(_ndat, axis=1) assert_almost_equal(res, tgt) def test_allnans(self): mat = np.array([np.nan]*9).reshape(3, 3) for f in self.nanfuncs: for axis in [None, 0, 1]: with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') assert_(np.isnan(f(mat, axis=axis)).all()) assert_(len(w) == 1, 'no warning raised') assert_(issubclass(w[0].category, RuntimeWarning)) # Check scalars with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') assert_(np.isnan(f(np.nan))) assert_(len(w) == 1, 'no warning raised') assert_(issubclass(w[0].category, RuntimeWarning)) def test_masked(self): mat = np.ma.fix_invalid(_ndat) msk = mat._mask.copy() for f in [np.nanmin]: res = f(mat, axis=1) tgt = f(_ndat, axis=1) assert_equal(res, tgt) assert_equal(mat._mask, msk) assert_(not np.isinf(mat).any()) def test_scalar(self): for f in self.nanfuncs: assert_(f(0.) == 0.) def test_matrices(self): # Check that it works and that type and # shape are preserved mat = np.matrix(np.eye(3)) for f in self.nanfuncs: res = f(mat, axis=0) assert_(isinstance(res, np.matrix)) assert_(res.shape == (1, 3)) res = f(mat, axis=1) assert_(isinstance(res, np.matrix)) 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): nanfuncs = [np.nanargmin, np.nanargmax] def test_mutation(self): # Check that passed array is not modified. ndat = _ndat.copy() for f in self.nanfuncs: f(ndat) assert_equal(ndat, _ndat) 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') ind = f(row) val = row[ind] # comparing with NaN is tricky as the result # is always false except for NaN != NaN assert_(not np.isnan(val)) assert_(not fcmp(val, row).any()) assert_(not np.equal(val, row[:ind]).any()) def test_allnans(self): mat = np.array([np.nan]*9).reshape(3, 3) for f in self.nanfuncs: for axis in [None, 0, 1]: assert_raises(ValueError, f, mat, axis=axis) assert_raises(ValueError, f, np.nan) def test_empty(self): mat = np.zeros((0, 3)) for f in self.nanfuncs: for axis in [0, None]: assert_raises(ValueError, f, mat, axis=axis) for axis in [1]: res = f(mat, axis=axis) assert_equal(res, np.zeros(0)) def test_scalar(self): for f in self.nanfuncs: assert_(f(0.) == 0.) def test_matrices(self): # Check that it works and that type and # shape are preserved mat = np.matrix(np.eye(3)) for f in self.nanfuncs: res = f(mat, axis=0) assert_(isinstance(res, np.matrix)) assert_(res.shape == (1, 3)) res = f(mat, axis=1) assert_(isinstance(res, np.matrix)) assert_(res.shape == (3, 1)) res = f(mat) assert_(np.isscalar(res)) class TestNanFunctions_IntTypes(TestCase): int_types = (np.int8, np.int16, np.int32, np.int64, np.uint8, np.uint16, np.uint32, np.uint64) mat = np.array([127, 39, 93, 87, 46]) def integer_arrays(self): for dtype in self.int_types: yield self.mat.astype(dtype) def test_nanmin(self): tgt = np.min(self.mat) for mat in self.integer_arrays(): assert_equal(np.nanmin(mat), tgt) def test_nanmax(self): tgt = np.max(self.mat) for mat in self.integer_arrays(): assert_equal(np.nanmax(mat), tgt) def test_nanargmin(self): tgt = np.argmin(self.mat) for mat in self.integer_arrays(): assert_equal(np.nanargmin(mat), tgt) def test_nanargmax(self): tgt = np.argmax(self.mat) for mat in self.integer_arrays(): assert_equal(np.nanargmax(mat), tgt) def test_nansum(self): tgt = np.sum(self.mat) for mat in self.integer_arrays(): assert_equal(np.nansum(mat), tgt) def test_nanmean(self): tgt = np.mean(self.mat) for mat in self.integer_arrays(): assert_equal(np.nanmean(mat), tgt) def test_nanvar(self): tgt = np.var(self.mat) for mat in self.integer_arrays(): assert_equal(np.nanvar(mat), tgt) tgt = np.var(mat, ddof=1) for mat in self.integer_arrays(): assert_equal(np.nanvar(mat, ddof=1), tgt) def test_nanstd(self): tgt = np.std(self.mat) for mat in self.integer_arrays(): assert_equal(np.nanstd(mat), tgt) tgt = np.std(self.mat, ddof=1) for mat in self.integer_arrays(): assert_equal(np.nanstd(mat, ddof=1), tgt) class TestNanFunctions_Sum(TestCase): def test_mutation(self): # Check that passed array is not modified. ndat = _ndat.copy() np.nansum(ndat) assert_equal(ndat, _ndat) def test_keepdims(self): mat = np.eye(3) for axis in [None, 0, 1]: tgt = np.sum(mat, axis=axis, keepdims=True) res = np.nansum(mat, axis=axis, keepdims=True) assert_(res.ndim == tgt.ndim) def test_out(self): mat = np.eye(3) resout = np.zeros(3) tgt = np.sum(mat, axis=1) res = np.nansum(mat, axis=1, out=resout) assert_almost_equal(res, resout) assert_almost_equal(res, tgt) def test_dtype_from_dtype(self): mat = np.eye(3) codes = 'efdgFDG' for c in codes: tgt = np.sum(mat, dtype=np.dtype(c), axis=1).dtype.type res = np.nansum(mat, dtype=np.dtype(c), axis=1).dtype.type assert_(res is tgt) # scalar case tgt = np.sum(mat, dtype=np.dtype(c), axis=None).dtype.type res = np.nansum(mat, dtype=np.dtype(c), axis=None).dtype.type assert_(res is tgt) def test_dtype_from_char(self): mat = np.eye(3) codes = 'efdgFDG' for c in codes: tgt = np.sum(mat, dtype=c, axis=1).dtype.type res = np.nansum(mat, dtype=c, axis=1).dtype.type assert_(res is tgt) # scalar case tgt = np.sum(mat, dtype=c, axis=None).dtype.type res = np.nansum(mat, dtype=c, axis=None).dtype.type assert_(res is tgt) def test_dtype_from_input(self): codes = 'efdgFDG' for c in codes: mat = np.eye(3, dtype=c) tgt = np.sum(mat, axis=1).dtype.type res = np.nansum(mat, axis=1).dtype.type assert_(res is tgt) # scalar case tgt = np.sum(mat, axis=None).dtype.type res = np.nansum(mat, axis=None).dtype.type assert_(res is tgt) def test_result_values(self): tgt = [np.sum(d) for d in _rdat] res = np.nansum(_ndat, axis=1) assert_almost_equal(res, tgt) def test_allnans(self): # Check for FutureWarning with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') res = np.nansum([np.nan]*3, axis=None) assert_(np.isnan(res), 'result is not NaN') assert_(len(w) == 1, 'no warning raised') assert_(issubclass(w[0].category, FutureWarning)) # Check scalar res = np.nansum(np.nan) assert_(np.isnan(res), 'result is not NaN') assert_(len(w) == 2, 'no warning raised') # Check there is no warning for not all-nan np.nansum([0]*3, axis=None) assert_(len(w) == 2, 'unwanted warning raised') def test_empty(self): mat = np.zeros((0, 3)) tgt = [np.nan]*3 res = np.nansum(mat, axis=0) assert_equal(res, tgt) tgt = [] res = np.nansum(mat, axis=1) assert_equal(res, tgt) tgt = np.nan res = np.nansum(mat, axis=None) assert_equal(res, tgt) def test_scalar(self): assert_(np.nansum(0.) == 0.) def test_matrices(self): # Check that it works and that type and # shape are preserved mat = np.matrix(np.eye(3)) res = np.nansum(mat, axis=0) assert_(isinstance(res, np.matrix)) assert_(res.shape == (1, 3)) res = np.nansum(mat, axis=1) assert_(isinstance(res, np.matrix)) assert_(res.shape == (3, 1)) res = np.nansum(mat) assert_(np.isscalar(res)) class TestNanFunctions_MeanVarStd(TestCase): nanfuncs = [np.nanmean, np.nanvar, np.nanstd] stdfuncs = [np.mean, np.var, np.std] def test_mutation(self): # Check that passed array is not modified. ndat = _ndat.copy() for f in self.nanfuncs: f(ndat) assert_equal(ndat, _ndat) def test_dtype_error(self): for f in self.nanfuncs: for dtype in [np.bool_, np.int_, np.object]: assert_raises( TypeError, f, _ndat, axis=1, dtype=np.int) def test_out_dtype_error(self): for f in self.nanfuncs: for dtype in [np.bool_, np.int_, np.object]: out = np.empty(_ndat.shape[0], dtype=dtype) assert_raises( TypeError, f, _ndat, axis=1, out=out) def test_keepdims(self): mat = np.eye(3) for nf, rf in zip(self.nanfuncs, self.stdfuncs): for axis in [None, 0, 1]: tgt = rf(mat, axis=axis, keepdims=True) res = nf(mat, axis=axis, keepdims=True) assert_(res.ndim == tgt.ndim) def test_out(self): mat = np.eye(3) for nf, rf in zip(self.nanfuncs, self.stdfuncs): resout = np.zeros(3) tgt = rf(mat, axis=1) res = nf(mat, axis=1, out=resout) assert_almost_equal(res, resout) assert_almost_equal(res, tgt) def test_dtype_from_dtype(self): mat = np.eye(3) codes = 'efdgFDG' for nf, rf in zip(self.nanfuncs, self.stdfuncs): for c in codes: tgt = rf(mat, dtype=np.dtype(c), axis=1).dtype.type res = nf(mat, dtype=np.dtype(c), axis=1).dtype.type assert_(res is tgt) # scalar case tgt = rf(mat, dtype=np.dtype(c), axis=None).dtype.type res = nf(mat, dtype=np.dtype(c), axis=None).dtype.type assert_(res is tgt) def test_dtype_from_char(self): mat = np.eye(3) codes = 'efdgFDG' for nf, rf in zip(self.nanfuncs, self.stdfuncs): for c in codes: tgt = rf(mat, dtype=c, axis=1).dtype.type res = nf(mat, dtype=c, axis=1).dtype.type assert_(res is tgt) # scalar case tgt = rf(mat, dtype=c, axis=None).dtype.type res = nf(mat, dtype=c, axis=None).dtype.type assert_(res is tgt) def test_dtype_from_input(self): codes = 'efdgFDG' for nf, rf in zip(self.nanfuncs, self.stdfuncs): for c in codes: mat = np.eye(3, dtype=c) tgt = rf(mat, axis=1).dtype.type res = nf(mat, axis=1).dtype.type assert_(res is tgt, "res %s, tgt %s" % (res, tgt)) # scalar case tgt = rf(mat, axis=None).dtype.type res = nf(mat, axis=None).dtype.type assert_(res is tgt) def test_ddof(self): nanfuncs = [np.nanvar, np.nanstd] stdfuncs = [np.var, np.std] for nf, rf in zip(nanfuncs, stdfuncs): for ddof in [0, 1]: tgt = [rf(d, ddof=ddof) for d in _rdat] res = nf(_ndat, axis=1, ddof=ddof) assert_almost_equal(res, tgt) def test_ddof_too_big(self): nanfuncs = [np.nanvar, np.nanstd] stdfuncs = [np.var, np.std] dsize = [len(d) for d in _rdat] for nf, rf in zip(nanfuncs, stdfuncs): for ddof in range(5): with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') tgt = [ddof >= d for d in dsize] res = nf(_ndat, axis=1, ddof=ddof) assert_equal(np.isnan(res), tgt) if any(tgt): assert_(len(w) == 1) assert_(issubclass(w[0].category, RuntimeWarning)) else: assert_(len(w) == 0) def test_result_values(self): for nf, rf in zip(self.nanfuncs, self.stdfuncs): tgt = [rf(d) for d in _rdat] res = nf(_ndat, axis=1) assert_almost_equal(res, tgt) def test_allnans(self): mat = np.array([np.nan]*9).reshape(3, 3) for f in self.nanfuncs: for axis in [None, 0, 1]: with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') assert_(np.isnan(f(mat, axis=axis)).all()) assert_(len(w) == 1) assert_(issubclass(w[0].category, RuntimeWarning)) # Check scalar assert_(np.isnan(f(np.nan))) assert_(len(w) == 2) assert_(issubclass(w[0].category, RuntimeWarning)) def test_empty(self): mat = np.zeros((0, 3)) for f in self.nanfuncs: for axis in [0, None]: with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') assert_(np.isnan(f(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(f(mat, axis=axis), np.zeros([])) assert_(len(w) == 0) def test_scalar(self): for f in self.nanfuncs: assert_(f(0.) == 0.) def test_matrices(self): # Check that it works and that type and # shape are preserved mat = np.matrix(np.eye(3)) for f in self.nanfuncs: res = f(mat, axis=0) assert_(isinstance(res, np.matrix)) assert_(res.shape == (1, 3)) res = f(mat, axis=1) assert_(isinstance(res, np.matrix)) assert_(res.shape == (3, 1)) res = f(mat) assert_(np.isscalar(res)) if __name__ == "__main__": run_module_suite() numpy-1.8.2/numpy/lib/tests/test_utils.py0000664000175100017510000000253012370216243021655 0ustar vagrantvagrant00000000000000from __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 if sys.version_info[0] >= 3: from io import StringIO else: from StringIO import StringIO def test_lookfor(): out = StringIO() utils.lookfor('eigenvalue', module='numpy', output=out, import_modules=False) out = out.getvalue() assert_('numpy.linalg.eig' in out) @deprecate def old_func(self, x): return x @deprecate(message="Rather use new_func2") def old_func2(self, x): return x def old_func3(self, x): return x new_func3 = deprecate(old_func3, old_name="old_func3", new_name="new_func3") def test_deprecate_decorator(): assert_('deprecated' in old_func.__doc__) def test_deprecate_decorator_message(): assert_('Rather use new_func2' in old_func2.__doc__) 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() numpy-1.8.2/numpy/lib/ufunclike.py0000664000175100017510000001135412370216242020304 0ustar vagrantvagrant00000000000000""" Module of functions that are like ufuncs in acting on arrays and optionally storing results in an output array. """ from __future__ import division, absolute_import, print_function __all__ = ['fix', 'isneginf', 'isposinf'] import numpy.core.numeric as nx def fix(x, y=None): """ Round to nearest integer towards zero. Round an array of floats element-wise to nearest integer towards zero. The rounded values are returned as floats. Parameters ---------- x : array_like An array of floats to be rounded y : ndarray, optional Output array Returns ------- out : ndarray of floats The array of rounded numbers See Also -------- trunc, floor, ceil around : Round to given number of decimals Examples -------- >>> np.fix(3.14) 3.0 >>> np.fix(3) 3.0 >>> np.fix([2.1, 2.9, -2.1, -2.9]) array([ 2., 2., -2., -2.]) """ x = nx.asanyarray(x) y1 = nx.floor(x) y2 = nx.ceil(x) if y is None: y = nx.asanyarray(y1) y[...] = nx.where(x >= 0, y1, y2) return y def isposinf(x, y=None): """ Test element-wise for positive infinity, return result as bool array. Parameters ---------- x : array_like The input array. y : array_like, optional A boolean array with the same shape as `x` to store the result. Returns ------- y : ndarray A boolean array with the same dimensions as the input. If second argument is not supplied then a boolean array is returned with values True where the corresponding element of the input is positive infinity and values False where the element of the input is not positive infinity. If a second argument is 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. The return value `y` is then a reference to that array. See Also -------- isinf, isneginf, isfinite, isnan Notes ----- Numpy uses the IEEE Standard for Binary Floating-Point for Arithmetic (IEEE 754). 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 -------- >>> np.isposinf(np.PINF) array(True, dtype=bool) >>> np.isposinf(np.inf) array(True, dtype=bool) >>> np.isposinf(np.NINF) array(False, dtype=bool) >>> np.isposinf([-np.inf, 0., np.inf]) array([False, False, True], dtype=bool) >>> x = np.array([-np.inf, 0., np.inf]) >>> y = np.array([2, 2, 2]) >>> np.isposinf(x, y) array([0, 0, 1]) >>> y array([0, 0, 1]) """ if y is None: x = nx.asarray(x) y = nx.empty(x.shape, dtype=nx.bool_) nx.logical_and(nx.isinf(x), ~nx.signbit(x), y) return y def isneginf(x, y=None): """ Test element-wise for negative infinity, return result as bool array. Parameters ---------- x : array_like The input array. y : array_like, optional A boolean array with the same shape and type as `x` to store the result. Returns ------- y : ndarray A boolean array with the same dimensions as the input. If second argument is not supplied then a numpy boolean array is returned with values True where the corresponding element of the input is negative infinity and values False where the element of the input is not negative infinity. If a second argument is 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. The return value `y` is then a reference to that array. See Also -------- isinf, isposinf, isnan, isfinite Notes ----- Numpy uses the IEEE Standard for Binary Floating-Point for Arithmetic (IEEE 754). 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 -------- >>> np.isneginf(np.NINF) array(True, dtype=bool) >>> np.isneginf(np.inf) array(False, dtype=bool) >>> np.isneginf(np.PINF) array(False, dtype=bool) >>> np.isneginf([-np.inf, 0., np.inf]) array([ True, False, False], dtype=bool) >>> x = np.array([-np.inf, 0., np.inf]) >>> y = np.array([2, 2, 2]) >>> np.isneginf(x, y) array([1, 0, 0]) >>> y array([1, 0, 0]) """ if y is None: x = nx.asarray(x) y = nx.empty(x.shape, dtype=nx.bool_) nx.logical_and(nx.isinf(x), nx.signbit(x), y) return y numpy-1.8.2/numpy/lib/__init__.py0000664000175100017510000000214212370216243020052 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function import math from .info import __doc__ from numpy.version import version as __version__ from .type_check import * from .index_tricks import * from .function_base import * from .nanfunctions import * from .shape_base import * from .stride_tricks import * from .twodim_base import * from .ufunclike import * from . import scimath as emath from .polynomial import * #import convertcode from .utils import * from .arraysetops import * from .npyio import * from .financial import * from .arrayterator import * from .arraypad import * __all__ = ['emath', 'math'] __all__ += type_check.__all__ __all__ += index_tricks.__all__ __all__ += function_base.__all__ __all__ += shape_base.__all__ __all__ += stride_tricks.__all__ __all__ += twodim_base.__all__ __all__ += ufunclike.__all__ __all__ += arraypad.__all__ __all__ += polynomial.__all__ __all__ += utils.__all__ __all__ += arraysetops.__all__ __all__ += npyio.__all__ __all__ += financial.__all__ __all__ += nanfunctions.__all__ from numpy.testing import Tester test = Tester().test bench = Tester().bench numpy-1.8.2/numpy/lib/arraypad.py0000664000175100017510000014447412370216243020135 0ustar vagrantvagrant00000000000000""" The arraypad module contains a group of functions to pad values onto the edges of an n-dimensional array. """ from __future__ import division, absolute_import, print_function import numpy as np from numpy.compat import long __all__ = ['pad'] ############################################################################### # Private utility functions. def _arange_ndarray(arr, shape, axis, reverse=False): """ Create an ndarray of `shape` with increments along specified `axis` Parameters ---------- arr : ndarray Input array of arbitrary shape. shape : tuple of ints Shape of desired array. Should be equivalent to `arr.shape` except `shape[axis]` which may have any positive value. axis : int Axis to increment along. reverse : bool If False, increment in a positive fashion from 1 to `shape[axis]`, inclusive. If True, the bounds are the same but the order reversed. Returns ------- padarr : ndarray Output array sized to pad `arr` along `axis`, with linear range from 1 to `shape[axis]` along specified `axis`. Notes ----- The range is deliberately 1-indexed for this specific use case. Think of this algorithm as broadcasting `np.arange` to a single `axis` of an arbitrarily shaped ndarray. """ initshape = tuple(1 if i != axis else shape[axis] for (i, x) in enumerate(arr.shape)) if not reverse: padarr = np.arange(1, shape[axis] + 1) else: padarr = np.arange(shape[axis], 0, -1) padarr = padarr.reshape(initshape) for i, dim in enumerate(shape): if padarr.shape[i] != dim: padarr = padarr.repeat(dim, axis=i) return padarr def _round_ifneeded(arr, dtype): """ Rounds arr inplace if destination dtype is integer. Parameters ---------- arr : ndarray Input array. dtype : dtype The dtype of the destination array. """ if np.issubdtype(dtype, np.integer): arr.round(out=arr) def _prepend_const(arr, pad_amt, val, axis=-1): """ Prepend constant `val` along `axis` of `arr`. Parameters ---------- arr : ndarray Input array of arbitrary shape. pad_amt : int Amount of padding to prepend. val : scalar Constant value to use. For best results should be of type `arr.dtype`; if not `arr.dtype` will be cast to `arr.dtype`. axis : int Axis along which to pad `arr`. Returns ------- padarr : ndarray Output array, with `pad_amt` constant `val` prepended along `axis`. """ if pad_amt == 0: return arr padshape = tuple(x if i != axis else pad_amt for (i, x) in enumerate(arr.shape)) if val == 0: return np.concatenate((np.zeros(padshape, dtype=arr.dtype), arr), axis=axis) else: return np.concatenate(((np.zeros(padshape) + val).astype(arr.dtype), arr), axis=axis) def _append_const(arr, pad_amt, val, axis=-1): """ Append constant `val` along `axis` of `arr`. Parameters ---------- arr : ndarray Input array of arbitrary shape. pad_amt : int Amount of padding to append. val : scalar Constant value to use. For best results should be of type `arr.dtype`; if not `arr.dtype` will be cast to `arr.dtype`. axis : int Axis along which to pad `arr`. Returns ------- padarr : ndarray Output array, with `pad_amt` constant `val` appended along `axis`. """ if pad_amt == 0: return arr padshape = tuple(x if i != axis else pad_amt for (i, x) in enumerate(arr.shape)) if val == 0: return np.concatenate((arr, np.zeros(padshape, dtype=arr.dtype)), axis=axis) else: return np.concatenate( (arr, (np.zeros(padshape) + val).astype(arr.dtype)), axis=axis) def _prepend_edge(arr, pad_amt, axis=-1): """ Prepend `pad_amt` to `arr` along `axis` by extending edge values. Parameters ---------- arr : ndarray Input array of arbitrary shape. pad_amt : int Amount of padding to prepend. axis : int Axis along which to pad `arr`. Returns ------- padarr : ndarray Output array, extended by `pad_amt` edge values appended along `axis`. """ if pad_amt == 0: return arr edge_slice = tuple(slice(None) if i != axis else 0 for (i, x) in enumerate(arr.shape)) # Shape to restore singleton dimension after slicing pad_singleton = tuple(x if i != axis else 1 for (i, x) in enumerate(arr.shape)) edge_arr = arr[edge_slice].reshape(pad_singleton) return np.concatenate((edge_arr.repeat(pad_amt, axis=axis), arr), axis=axis) def _append_edge(arr, pad_amt, axis=-1): """ Append `pad_amt` to `arr` along `axis` by extending edge values. Parameters ---------- arr : ndarray Input array of arbitrary shape. pad_amt : int Amount of padding to append. axis : int Axis along which to pad `arr`. Returns ------- padarr : ndarray Output array, extended by `pad_amt` edge values prepended along `axis`. """ if pad_amt == 0: return arr edge_slice = tuple(slice(None) if i != axis else arr.shape[axis] - 1 for (i, x) in enumerate(arr.shape)) # Shape to restore singleton dimension after slicing pad_singleton = tuple(x if i != axis else 1 for (i, x) in enumerate(arr.shape)) edge_arr = arr[edge_slice].reshape(pad_singleton) return np.concatenate((arr, edge_arr.repeat(pad_amt, axis=axis)), axis=axis) def _prepend_ramp(arr, pad_amt, end, axis=-1): """ Prepend linear ramp along `axis`. Parameters ---------- arr : ndarray Input array of arbitrary shape. pad_amt : int Amount of padding to prepend. end : scalar Constal value to use. For best results should be of type `arr.dtype`; if not `arr.dtype` will be cast to `arr.dtype`. axis : int Axis along which to pad `arr`. Returns ------- padarr : ndarray Output array, with `pad_amt` values prepended along `axis`. The prepended region ramps linearly from the edge value to `end`. """ if pad_amt == 0: return arr # Generate shape for final concatenated array padshape = tuple(x if i != axis else pad_amt for (i, x) in enumerate(arr.shape)) # Generate an n-dimensional array incrementing along `axis` ramp_arr = _arange_ndarray(arr, padshape, axis, reverse=True).astype(np.float64) # Appropriate slicing to extract n-dimensional edge along `axis` edge_slice = tuple(slice(None) if i != axis else 0 for (i, x) in enumerate(arr.shape)) # Shape to restore singleton dimension after slicing pad_singleton = tuple(x if i != axis else 1 for (i, x) in enumerate(arr.shape)) # Extract edge, reshape to original rank, and extend along `axis` edge_pad = arr[edge_slice].reshape(pad_singleton).repeat(pad_amt, axis) # Linear ramp slope = (end - edge_pad) / float(pad_amt) ramp_arr = ramp_arr * slope ramp_arr += edge_pad _round_ifneeded(ramp_arr, arr.dtype) # Ramp values will most likely be float, cast them to the same type as arr return np.concatenate((ramp_arr.astype(arr.dtype), arr), axis=axis) def _append_ramp(arr, pad_amt, end, axis=-1): """ Append linear ramp along `axis`. Parameters ---------- arr : ndarray Input array of arbitrary shape. pad_amt : int Amount of padding to append. end : scalar Constal value to use. For best results should be of type `arr.dtype`; if not `arr.dtype` will be cast to `arr.dtype`. axis : int Axis along which to pad `arr`. Returns ------- padarr : ndarray Output array, with `pad_amt` values appended along `axis`. The appended region ramps linearly from the edge value to `end`. """ if pad_amt == 0: return arr # Generate shape for final concatenated array padshape = tuple(x if i != axis else pad_amt for (i, x) in enumerate(arr.shape)) # Generate an n-dimensional array incrementing along `axis` ramp_arr = _arange_ndarray(arr, padshape, axis, reverse=False).astype(np.float64) # Slice a chunk from the edge to calculate stats on edge_slice = tuple(slice(None) if i != axis else -1 for (i, x) in enumerate(arr.shape)) # Shape to restore singleton dimension after slicing pad_singleton = tuple(x if i != axis else 1 for (i, x) in enumerate(arr.shape)) # Extract edge, reshape to original rank, and extend along `axis` edge_pad = arr[edge_slice].reshape(pad_singleton).repeat(pad_amt, axis) # Linear ramp slope = (end - edge_pad) / float(pad_amt) ramp_arr = ramp_arr * slope ramp_arr += edge_pad _round_ifneeded(ramp_arr, arr.dtype) # Ramp values will most likely be float, cast them to the same type as arr return np.concatenate((arr, ramp_arr.astype(arr.dtype)), axis=axis) def _prepend_max(arr, pad_amt, num, axis=-1): """ Prepend `pad_amt` maximum values along `axis`. Parameters ---------- arr : ndarray Input array of arbitrary shape. pad_amt : int Amount of padding to prepend. num : int Depth into `arr` along `axis` to calculate maximum. Range: [1, `arr.shape[axis]`] or None (entire axis) axis : int Axis along which to pad `arr`. Returns ------- padarr : ndarray Output array, with `pad_amt` values appended along `axis`. The prepended region is the maximum of the first `num` values along `axis`. """ if pad_amt == 0: return arr # Equivalent to edge padding for single value, so do that instead if num == 1: return _prepend_edge(arr, pad_amt, axis) # Use entire array if `num` is too large if num is not None: if num >= arr.shape[axis]: num = None # Slice a chunk from the edge to calculate stats on max_slice = tuple(slice(None) if i != axis else slice(num) for (i, x) in enumerate(arr.shape)) # Shape to restore singleton dimension after slicing pad_singleton = tuple(x if i != axis else 1 for (i, x) in enumerate(arr.shape)) # Extract slice, calculate max, reshape to add singleton dimension back max_chunk = arr[max_slice].max(axis=axis).reshape(pad_singleton) # Concatenate `arr` with `max_chunk`, extended along `axis` by `pad_amt` return np.concatenate((max_chunk.repeat(pad_amt, axis=axis), arr), axis=axis) def _append_max(arr, pad_amt, num, axis=-1): """ Pad one `axis` of `arr` with the maximum of the last `num` elements. Parameters ---------- arr : ndarray Input array of arbitrary shape. pad_amt : int Amount of padding to append. num : int Depth into `arr` along `axis` to calculate maximum. Range: [1, `arr.shape[axis]`] or None (entire axis) axis : int Axis along which to pad `arr`. Returns ------- padarr : ndarray Output array, with `pad_amt` values appended along `axis`. The appended region is the maximum of the final `num` values along `axis`. """ if pad_amt == 0: return arr # Equivalent to edge padding for single value, so do that instead if num == 1: return _append_edge(arr, pad_amt, axis) # Use entire array if `num` is too large if num is not None: if num >= arr.shape[axis]: num = None # Slice a chunk from the edge to calculate stats on end = arr.shape[axis] - 1 if num is not None: max_slice = tuple( slice(None) if i != axis else slice(end, end - num, -1) for (i, x) in enumerate(arr.shape)) else: max_slice = tuple(slice(None) for x in arr.shape) # Shape to restore singleton dimension after slicing pad_singleton = tuple(x if i != axis else 1 for (i, x) in enumerate(arr.shape)) # Extract slice, calculate max, reshape to add singleton dimension back max_chunk = arr[max_slice].max(axis=axis).reshape(pad_singleton) # Concatenate `arr` with `max_chunk`, extended along `axis` by `pad_amt` return np.concatenate((arr, max_chunk.repeat(pad_amt, axis=axis)), axis=axis) def _prepend_mean(arr, pad_amt, num, axis=-1): """ Prepend `pad_amt` mean values along `axis`. Parameters ---------- arr : ndarray Input array of arbitrary shape. pad_amt : int Amount of padding to prepend. num : int Depth into `arr` along `axis` to calculate mean. Range: [1, `arr.shape[axis]`] or None (entire axis) axis : int Axis along which to pad `arr`. Returns ------- padarr : ndarray Output array, with `pad_amt` values prepended along `axis`. The prepended region is the mean of the first `num` values along `axis`. """ if pad_amt == 0: return arr # Equivalent to edge padding for single value, so do that instead if num == 1: return _prepend_edge(arr, pad_amt, axis) # Use entire array if `num` is too large if num is not None: if num >= arr.shape[axis]: num = None # Slice a chunk from the edge to calculate stats on mean_slice = tuple(slice(None) if i != axis else slice(num) for (i, x) in enumerate(arr.shape)) # Shape to restore singleton dimension after slicing pad_singleton = tuple(x if i != axis else 1 for (i, x) in enumerate(arr.shape)) # Extract slice, calculate mean, reshape to add singleton dimension back mean_chunk = arr[mean_slice].mean(axis).reshape(pad_singleton) _round_ifneeded(mean_chunk, arr.dtype) # Concatenate `arr` with `mean_chunk`, extended along `axis` by `pad_amt` return np.concatenate((mean_chunk.repeat(pad_amt, axis).astype(arr.dtype), arr), axis=axis) def _append_mean(arr, pad_amt, num, axis=-1): """ Append `pad_amt` mean values along `axis`. Parameters ---------- arr : ndarray Input array of arbitrary shape. pad_amt : int Amount of padding to append. num : int Depth into `arr` along `axis` to calculate mean. Range: [1, `arr.shape[axis]`] or None (entire axis) axis : int Axis along which to pad `arr`. Returns ------- padarr : ndarray Output array, with `pad_amt` values appended along `axis`. The appended region is the maximum of the final `num` values along `axis`. """ if pad_amt == 0: return arr # Equivalent to edge padding for single value, so do that instead if num == 1: return _append_edge(arr, pad_amt, axis) # Use entire array if `num` is too large if num is not None: if num >= arr.shape[axis]: num = None # Slice a chunk from the edge to calculate stats on end = arr.shape[axis] - 1 if num is not None: mean_slice = tuple( slice(None) if i != axis else slice(end, end - num, -1) for (i, x) in enumerate(arr.shape)) else: mean_slice = tuple(slice(None) for x in arr.shape) # Shape to restore singleton dimension after slicing pad_singleton = tuple(x if i != axis else 1 for (i, x) in enumerate(arr.shape)) # Extract slice, calculate mean, reshape to add singleton dimension back mean_chunk = arr[mean_slice].mean(axis=axis).reshape(pad_singleton) _round_ifneeded(mean_chunk, arr.dtype) # Concatenate `arr` with `mean_chunk`, extended along `axis` by `pad_amt` return np.concatenate( (arr, mean_chunk.repeat(pad_amt, axis).astype(arr.dtype)), axis=axis) def _prepend_med(arr, pad_amt, num, axis=-1): """ Prepend `pad_amt` median values along `axis`. Parameters ---------- arr : ndarray Input array of arbitrary shape. pad_amt : int Amount of padding to prepend. num : int Depth into `arr` along `axis` to calculate median. Range: [1, `arr.shape[axis]`] or None (entire axis) axis : int Axis along which to pad `arr`. Returns ------- padarr : ndarray Output array, with `pad_amt` values prepended along `axis`. The prepended region is the median of the first `num` values along `axis`. """ if pad_amt == 0: return arr # Equivalent to edge padding for single value, so do that instead if num == 1: return _prepend_edge(arr, pad_amt, axis) # Use entire array if `num` is too large if num is not None: if num >= arr.shape[axis]: num = None # Slice a chunk from the edge to calculate stats on med_slice = tuple(slice(None) if i != axis else slice(num) for (i, x) in enumerate(arr.shape)) # Shape to restore singleton dimension after slicing pad_singleton = tuple(x if i != axis else 1 for (i, x) in enumerate(arr.shape)) # Extract slice, calculate median, reshape to add singleton dimension back med_chunk = np.median(arr[med_slice], axis=axis).reshape(pad_singleton) _round_ifneeded(med_chunk, arr.dtype) # Concatenate `arr` with `med_chunk`, extended along `axis` by `pad_amt` return np.concatenate( (med_chunk.repeat(pad_amt, axis).astype(arr.dtype), arr), axis=axis) def _append_med(arr, pad_amt, num, axis=-1): """ Append `pad_amt` median values along `axis`. Parameters ---------- arr : ndarray Input array of arbitrary shape. pad_amt : int Amount of padding to append. num : int Depth into `arr` along `axis` to calculate median. Range: [1, `arr.shape[axis]`] or None (entire axis) axis : int Axis along which to pad `arr`. Returns ------- padarr : ndarray Output array, with `pad_amt` values appended along `axis`. The appended region is the median of the final `num` values along `axis`. """ if pad_amt == 0: return arr # Equivalent to edge padding for single value, so do that instead if num == 1: return _append_edge(arr, pad_amt, axis) # Use entire array if `num` is too large if num is not None: if num >= arr.shape[axis]: num = None # Slice a chunk from the edge to calculate stats on end = arr.shape[axis] - 1 if num is not None: med_slice = tuple( slice(None) if i != axis else slice(end, end - num, -1) for (i, x) in enumerate(arr.shape)) else: med_slice = tuple(slice(None) for x in arr.shape) # Shape to restore singleton dimension after slicing pad_singleton = tuple(x if i != axis else 1 for (i, x) in enumerate(arr.shape)) # Extract slice, calculate median, reshape to add singleton dimension back med_chunk = np.median(arr[med_slice], axis=axis).reshape(pad_singleton) _round_ifneeded(med_chunk, arr.dtype) # Concatenate `arr` with `med_chunk`, extended along `axis` by `pad_amt` return np.concatenate( (arr, med_chunk.repeat(pad_amt, axis).astype(arr.dtype)), axis=axis) def _prepend_min(arr, pad_amt, num, axis=-1): """ Prepend `pad_amt` minimum values along `axis`. Parameters ---------- arr : ndarray Input array of arbitrary shape. pad_amt : int Amount of padding to prepend. num : int Depth into `arr` along `axis` to calculate minimum. Range: [1, `arr.shape[axis]`] or None (entire axis) axis : int Axis along which to pad `arr`. Returns ------- padarr : ndarray Output array, with `pad_amt` values prepended along `axis`. The prepended region is the minimum of the first `num` values along `axis`. """ if pad_amt == 0: return arr # Equivalent to edge padding for single value, so do that instead if num == 1: return _prepend_edge(arr, pad_amt, axis) # Use entire array if `num` is too large if num is not None: if num >= arr.shape[axis]: num = None # Slice a chunk from the edge to calculate stats on min_slice = tuple(slice(None) if i != axis else slice(num) for (i, x) in enumerate(arr.shape)) # Shape to restore singleton dimension after slicing pad_singleton = tuple(x if i != axis else 1 for (i, x) in enumerate(arr.shape)) # Extract slice, calculate min, reshape to add singleton dimension back min_chunk = arr[min_slice].min(axis=axis).reshape(pad_singleton) # Concatenate `arr` with `min_chunk`, extended along `axis` by `pad_amt` return np.concatenate((min_chunk.repeat(pad_amt, axis=axis), arr), axis=axis) def _append_min(arr, pad_amt, num, axis=-1): """ Append `pad_amt` median values along `axis`. Parameters ---------- arr : ndarray Input array of arbitrary shape. pad_amt : int Amount of padding to append. num : int Depth into `arr` along `axis` to calculate minimum. Range: [1, `arr.shape[axis]`] or None (entire axis) axis : int Axis along which to pad `arr`. Returns ------- padarr : ndarray Output array, with `pad_amt` values appended along `axis`. The appended region is the minimum of the final `num` values along `axis`. """ if pad_amt == 0: return arr # Equivalent to edge padding for single value, so do that instead if num == 1: return _append_edge(arr, pad_amt, axis) # Use entire array if `num` is too large if num is not None: if num >= arr.shape[axis]: num = None # Slice a chunk from the edge to calculate stats on end = arr.shape[axis] - 1 if num is not None: min_slice = tuple( slice(None) if i != axis else slice(end, end - num, -1) for (i, x) in enumerate(arr.shape)) else: min_slice = tuple(slice(None) for x in arr.shape) # Shape to restore singleton dimension after slicing pad_singleton = tuple(x if i != axis else 1 for (i, x) in enumerate(arr.shape)) # Extract slice, calculate min, reshape to add singleton dimension back min_chunk = arr[min_slice].min(axis=axis).reshape(pad_singleton) # Concatenate `arr` with `min_chunk`, extended along `axis` by `pad_amt` return np.concatenate((arr, min_chunk.repeat(pad_amt, axis=axis)), axis=axis) def _pad_ref(arr, pad_amt, method, axis=-1): """ Pad `axis` of `arr` by reflection. Parameters ---------- arr : ndarray Input array of arbitrary shape. pad_amt : tuple of ints, length 2 Padding to (prepend, append) along `axis`. method : str Controls method of reflection; options are 'even' or 'odd'. axis : int Axis along which to pad `arr`. Returns ------- padarr : ndarray Output array, with `pad_amt[0]` values prepended and `pad_amt[1]` values appended along `axis`. Both regions are padded with reflected values from the original array. Notes ----- This algorithm does not pad with repetition, i.e. the edges are not repeated in the reflection. For that behavior, use `method='symmetric'`. The modes 'reflect', 'symmetric', and 'wrap' must be padded with a single function, lest the indexing tricks in non-integer multiples of the original shape would violate repetition in the final iteration. """ # Implicit booleanness to test for zero (or None) in any scalar type if pad_amt[0] == 0 and pad_amt[1] == 0: return arr ########################################################################## # Prepended region # Slice off a reverse indexed chunk from near edge to pad `arr` before ref_slice = tuple(slice(None) if i != axis else slice(pad_amt[0], 0, -1) for (i, x) in enumerate(arr.shape)) ref_chunk1 = arr[ref_slice] # Shape to restore singleton dimension after slicing pad_singleton = tuple(x if i != axis else 1 for (i, x) in enumerate(arr.shape)) if pad_amt[0] == 1: ref_chunk1 = ref_chunk1.reshape(pad_singleton) # Memory/computationally more expensive, only do this if `method='odd'` if 'odd' in method and pad_amt[0] > 0: edge_slice1 = tuple(slice(None) if i != axis else 0 for (i, x) in enumerate(arr.shape)) edge_chunk = arr[edge_slice1].reshape(pad_singleton) ref_chunk1 = 2 * edge_chunk - ref_chunk1 del edge_chunk ########################################################################## # Appended region # Slice off a reverse indexed chunk from far edge to pad `arr` after start = arr.shape[axis] - pad_amt[1] - 1 end = arr.shape[axis] - 1 ref_slice = tuple(slice(None) if i != axis else slice(start, end) for (i, x) in enumerate(arr.shape)) rev_idx = tuple(slice(None) if i != axis else slice(None, None, -1) for (i, x) in enumerate(arr.shape)) ref_chunk2 = arr[ref_slice][rev_idx] if pad_amt[1] == 1: ref_chunk2 = ref_chunk2.reshape(pad_singleton) if 'odd' in method: edge_slice2 = tuple(slice(None) if i != axis else -1 for (i, x) in enumerate(arr.shape)) edge_chunk = arr[edge_slice2].reshape(pad_singleton) ref_chunk2 = 2 * edge_chunk - ref_chunk2 del edge_chunk # Concatenate `arr` with both chunks, extending along `axis` return np.concatenate((ref_chunk1, arr, ref_chunk2), axis=axis) def _pad_sym(arr, pad_amt, method, axis=-1): """ Pad `axis` of `arr` by symmetry. Parameters ---------- arr : ndarray Input array of arbitrary shape. pad_amt : tuple of ints, length 2 Padding to (prepend, append) along `axis`. method : str Controls method of symmetry; options are 'even' or 'odd'. axis : int Axis along which to pad `arr`. Returns ------- padarr : ndarray Output array, with `pad_amt[0]` values prepended and `pad_amt[1]` values appended along `axis`. Both regions are padded with symmetric values from the original array. Notes ----- This algorithm DOES pad with repetition, i.e. the edges are repeated. For a method that does not repeat edges, use `method='reflect'`. The modes 'reflect', 'symmetric', and 'wrap' must be padded with a single function, lest the indexing tricks in non-integer multiples of the original shape would violate repetition in the final iteration. """ # Implicit booleanness to test for zero (or None) in any scalar type if pad_amt[0] == 0 and pad_amt[1] == 0: return arr ########################################################################## # Prepended region # Slice off a reverse indexed chunk from near edge to pad `arr` before sym_slice = tuple(slice(None) if i != axis else slice(0, pad_amt[0]) for (i, x) in enumerate(arr.shape)) rev_idx = tuple(slice(None) if i != axis else slice(None, None, -1) for (i, x) in enumerate(arr.shape)) sym_chunk1 = arr[sym_slice][rev_idx] # Shape to restore singleton dimension after slicing pad_singleton = tuple(x if i != axis else 1 for (i, x) in enumerate(arr.shape)) if pad_amt[0] == 1: sym_chunk1 = sym_chunk1.reshape(pad_singleton) # Memory/computationally more expensive, only do this if `method='odd'` if 'odd' in method and pad_amt[0] > 0: edge_slice1 = tuple(slice(None) if i != axis else 0 for (i, x) in enumerate(arr.shape)) edge_chunk = arr[edge_slice1].reshape(pad_singleton) sym_chunk1 = 2 * edge_chunk - sym_chunk1 del edge_chunk ########################################################################## # Appended region # Slice off a reverse indexed chunk from far edge to pad `arr` after start = arr.shape[axis] - pad_amt[1] end = arr.shape[axis] sym_slice = tuple(slice(None) if i != axis else slice(start, end) for (i, x) in enumerate(arr.shape)) sym_chunk2 = arr[sym_slice][rev_idx] if pad_amt[1] == 1: sym_chunk2 = sym_chunk2.reshape(pad_singleton) if 'odd' in method: edge_slice2 = tuple(slice(None) if i != axis else -1 for (i, x) in enumerate(arr.shape)) edge_chunk = arr[edge_slice2].reshape(pad_singleton) sym_chunk2 = 2 * edge_chunk - sym_chunk2 del edge_chunk # Concatenate `arr` with both chunks, extending along `axis` return np.concatenate((sym_chunk1, arr, sym_chunk2), axis=axis) def _pad_wrap(arr, pad_amt, axis=-1): """ Pad `axis` of `arr` via wrapping. Parameters ---------- arr : ndarray Input array of arbitrary shape. pad_amt : tuple of ints, length 2 Padding to (prepend, append) along `axis`. axis : int Axis along which to pad `arr`. Returns ------- padarr : ndarray Output array, with `pad_amt[0]` values prepended and `pad_amt[1]` values appended along `axis`. Both regions are padded wrapped values from the opposite end of `axis`. Notes ----- This method of padding is also known as 'tile' or 'tiling'. The modes 'reflect', 'symmetric', and 'wrap' must be padded with a single function, lest the indexing tricks in non-integer multiples of the original shape would violate repetition in the final iteration. """ # Implicit booleanness to test for zero (or None) in any scalar type if pad_amt[0] == 0 and pad_amt[1] == 0: return arr ########################################################################## # Prepended region # Slice off a reverse indexed chunk from near edge to pad `arr` before start = arr.shape[axis] - pad_amt[0] end = arr.shape[axis] wrap_slice = tuple(slice(None) if i != axis else slice(start, end) for (i, x) in enumerate(arr.shape)) wrap_chunk1 = arr[wrap_slice] # Shape to restore singleton dimension after slicing pad_singleton = tuple(x if i != axis else 1 for (i, x) in enumerate(arr.shape)) if pad_amt[0] == 1: wrap_chunk1 = wrap_chunk1.reshape(pad_singleton) ########################################################################## # Appended region # Slice off a reverse indexed chunk from far edge to pad `arr` after wrap_slice = tuple(slice(None) if i != axis else slice(0, pad_amt[1]) for (i, x) in enumerate(arr.shape)) wrap_chunk2 = arr[wrap_slice] if pad_amt[1] == 1: wrap_chunk2 = wrap_chunk2.reshape(pad_singleton) # Concatenate `arr` with both chunks, extending along `axis` return np.concatenate((wrap_chunk1, arr, wrap_chunk2), axis=axis) def _normalize_shape(narray, shape): """ Private function which does some checks and normalizes the possibly much simpler representations of 'pad_width', 'stat_length', 'constant_values', 'end_values'. Parameters ---------- narray : ndarray Input ndarray shape : {sequence, int}, optional The width of padding (pad_width) or the number of elements on the edge of the narray used for statistics (stat_length). ((before_1, after_1), ... (before_N, after_N)) unique number of elements for each axis where `N` is rank of `narray`. ((before, after),) yields same before and after constants for each axis. (constant,) or int is a shortcut for before = after = constant for all axes. Returns ------- _normalize_shape : tuple of tuples int => ((int, int), (int, int), ...) [[int1, int2], [int3, int4], ...] => ((int1, int2), (int3, int4), ...) ((int1, int2), (int3, int4), ...) => no change [[int1, int2], ] => ((int1, int2), (int1, int2), ...) ((int1, int2), ) => ((int1, int2), (int1, int2), ...) [[int , ], ] => ((int, int), (int, int), ...) ((int , ), ) => ((int, int), (int, int), ...) """ normshp = None shapelen = len(np.shape(narray)) if (isinstance(shape, int)) or shape is None: normshp = ((shape, shape), ) * shapelen elif (isinstance(shape, (tuple, list)) and isinstance(shape[0], (tuple, list)) and len(shape) == shapelen): normshp = shape for i in normshp: if len(i) != 2: fmt = "Unable to create correctly shaped tuple from %s" raise ValueError(fmt % (normshp,)) elif (isinstance(shape, (tuple, list)) and isinstance(shape[0], (int, float, long)) and len(shape) == 1): normshp = ((shape[0], shape[0]), ) * shapelen elif (isinstance(shape, (tuple, list)) and isinstance(shape[0], (int, float, long)) and len(shape) == 2): normshp = (shape, ) * shapelen if normshp is None: fmt = "Unable to create correctly shaped tuple from %s" raise ValueError(fmt % (shape,)) return normshp def _validate_lengths(narray, number_elements): """ Private function which does some checks and reformats pad_width and stat_length using _normalize_shape. Parameters ---------- narray : ndarray Input ndarray number_elements : {sequence, int}, optional The width of padding (pad_width) or the number of elements on the edge of the narray used for statistics (stat_length). ((before_1, after_1), ... (before_N, after_N)) unique number of elements for each axis. ((before, after),) yields same before and after constants for each axis. (constant,) or int is a shortcut for before = after = constant for all axes. Returns ------- _validate_lengths : tuple of tuples int => ((int, int), (int, int), ...) [[int1, int2], [int3, int4], ...] => ((int1, int2), (int3, int4), ...) ((int1, int2), (int3, int4), ...) => no change [[int1, int2], ] => ((int1, int2), (int1, int2), ...) ((int1, int2), ) => ((int1, int2), (int1, int2), ...) [[int , ], ] => ((int, int), (int, int), ...) ((int , ), ) => ((int, int), (int, int), ...) """ normshp = _normalize_shape(narray, number_elements) for i in normshp: chk = [1 if x is None else x for x in i] chk = [1 if x >= 0 else -1 for x in chk] if (chk[0] < 0) or (chk[1] < 0): fmt = "%s cannot contain negative values." raise ValueError(fmt % (number_elements,)) return normshp ############################################################################### # Public functions def pad(array, pad_width, mode=None, **kwargs): """ Pads an array. Parameters ---------- array : array_like of rank N Input array pad_width : {sequence, int} Number of values padded to the edges of each axis. ((before_1, after_1), ... (before_N, after_N)) unique pad widths for each axis. ((before, after),) yields same before and after pad for each axis. (pad,) or int is a shortcut for before = after = pad width for all axes. mode : {str, function} One of the following string values or a user supplied function. 'constant' Pads with a constant value. 'edge' Pads with the edge values of array. 'linear_ramp' Pads with the linear ramp between end_value and the array edge value. 'maximum' Pads with the maximum value of all or part of the vector along each axis. 'mean' Pads with the mean value of all or part of the vector along each axis. 'median' Pads with the median value of all or part of the vector along each axis. 'minimum' Pads with the minimum value of all or part of the vector along each axis. 'reflect' Pads with the reflection of the vector mirrored on the first and last values of the vector along each axis. 'symmetric' Pads with the reflection of the vector mirrored along the edge of the array. 'wrap' Pads with the wrap of the vector along the axis. The first values are used to pad the end and the end values are used to pad the beginning. Padding function, see Notes. stat_length : {sequence, int}, optional Used in 'maximum', 'mean', 'median', and 'minimum'. Number of values at edge of each axis used to calculate the statistic value. ((before_1, after_1), ... (before_N, after_N)) unique statistic lengths for each axis. ((before, after),) yields same before and after statistic lengths for each axis. (stat_length,) or int is a shortcut for before = after = statistic length for all axes. Default is ``None``, to use the entire axis. constant_values : {sequence, int}, optional Used in 'constant'. The values to set the padded values for each axis. ((before_1, after_1), ... (before_N, after_N)) unique pad constants for each axis. ((before, after),) yields same before and after constants for each axis. (constant,) or int is a shortcut for before = after = constant for all axes. Default is 0. end_values : {sequence, int}, optional Used in 'linear_ramp'. The values used for the ending value of the linear_ramp and that will form the edge of the padded array. ((before_1, after_1), ... (before_N, after_N)) unique end values for each axis. ((before, after),) yields same before and after end values for each axis. (constant,) or int is a shortcut for before = after = end value for all axes. Default is 0. reflect_type : str {'even', 'odd'}, optional Used in 'reflect', and 'symmetric'. The 'even' style is the default with an unaltered reflection around the edge value. For the 'odd' style, the extented part of the array is created by subtracting the reflected values from two times the edge value. Returns ------- pad : ndarray Padded array of rank equal to `array` with shape increased according to `pad_width`. Notes ----- .. versionadded:: 1.7.0 For an array with rank greater than 1, some of the padding of later axes is calculated from padding of previous axes. This is easiest to think about with a rank 2 array where the corners of the padded array are calculated by using padded values from the first axis. The padding function, if used, should return a rank 1 array equal in length to the vector argument with padded values replaced. It has the following signature: padding_func(vector, iaxis_pad_width, iaxis, **kwargs) where vector : ndarray A rank 1 array already padded with zeros. Padded values are vector[:pad_tuple[0]] and vector[-pad_tuple[1]:]. iaxis_pad_width : tuple A 2-tuple of ints, iaxis_pad_width[0] represents the number of values padded at the beginning of vector where iaxis_pad_width[1] represents the number of values padded at the end of vector. iaxis : int The axis currently being calculated. kwargs : misc Any keyword arguments the function requires. Examples -------- >>> a = [1, 2, 3, 4, 5] >>> np.lib.pad(a, (2,3), 'constant', constant_values=(4,6)) array([4, 4, 1, 2, 3, 4, 5, 6, 6, 6]) >>> np.lib.pad(a, (2,3), 'edge') array([1, 1, 1, 2, 3, 4, 5, 5, 5, 5]) >>> np.lib.pad(a, (2,3), 'linear_ramp', end_values=(5,-4)) array([ 5, 3, 1, 2, 3, 4, 5, 2, -1, -4]) >>> np.lib.pad(a, (2,), 'maximum') array([5, 5, 1, 2, 3, 4, 5, 5, 5]) >>> np.lib.pad(a, (2,), 'mean') array([3, 3, 1, 2, 3, 4, 5, 3, 3]) >>> np.lib.pad(a, (2,), 'median') array([3, 3, 1, 2, 3, 4, 5, 3, 3]) >>> a = [[1,2], [3,4]] >>> np.lib.pad(a, ((3, 2), (2, 3)), 'minimum') array([[1, 1, 1, 2, 1, 1, 1], [1, 1, 1, 2, 1, 1, 1], [1, 1, 1, 2, 1, 1, 1], [1, 1, 1, 2, 1, 1, 1], [3, 3, 3, 4, 3, 3, 3], [1, 1, 1, 2, 1, 1, 1], [1, 1, 1, 2, 1, 1, 1]]) >>> a = [1, 2, 3, 4, 5] >>> np.lib.pad(a, (2,3), 'reflect') array([3, 2, 1, 2, 3, 4, 5, 4, 3, 2]) >>> np.lib.pad(a, (2,3), 'reflect', reflect_type='odd') array([-1, 0, 1, 2, 3, 4, 5, 6, 7, 8]) >>> np.lib.pad(a, (2,3), 'symmetric') array([2, 1, 1, 2, 3, 4, 5, 5, 4, 3]) >>> np.lib.pad(a, (2,3), 'symmetric', reflect_type='odd') array([0, 1, 1, 2, 3, 4, 5, 5, 6, 7]) >>> np.lib.pad(a, (2,3), 'wrap') array([4, 5, 1, 2, 3, 4, 5, 1, 2, 3]) >>> def padwithtens(vector, pad_width, iaxis, kwargs): ... vector[:pad_width[0]] = 10 ... vector[-pad_width[1]:] = 10 ... return vector >>> a = np.arange(6) >>> a = a.reshape((2,3)) >>> np.lib.pad(a, 2, padwithtens) array([[10, 10, 10, 10, 10, 10, 10], [10, 10, 10, 10, 10, 10, 10], [10, 10, 0, 1, 2, 10, 10], [10, 10, 3, 4, 5, 10, 10], [10, 10, 10, 10, 10, 10, 10], [10, 10, 10, 10, 10, 10, 10]]) """ narray = np.array(array) pad_width = _validate_lengths(narray, pad_width) allowedkwargs = { 'constant': ['constant_values'], 'edge': [], 'linear_ramp': ['end_values'], 'maximum': ['stat_length'], 'mean': ['stat_length'], 'median': ['stat_length'], 'minimum': ['stat_length'], 'reflect': ['reflect_type'], 'symmetric': ['reflect_type'], 'wrap': [], } kwdefaults = { 'stat_length': None, 'constant_values': 0, 'end_values': 0, 'reflect_type': 'even', } if isinstance(mode, str): # Make sure have allowed kwargs appropriate for mode for key in kwargs: if key not in allowedkwargs[mode]: raise ValueError('%s keyword not in allowed keywords %s' % (key, allowedkwargs[mode])) # Set kwarg defaults for kw in allowedkwargs[mode]: kwargs.setdefault(kw, kwdefaults[kw]) # Need to only normalize particular keywords. for i in kwargs: if i == 'stat_length': kwargs[i] = _validate_lengths(narray, kwargs[i]) if i in ['end_values', 'constant_values']: kwargs[i] = _normalize_shape(narray, kwargs[i]) elif mode is None: raise ValueError('Keyword "mode" must be a function or one of %s.' % (list(allowedkwargs.keys()),)) else: # Drop back to old, slower np.apply_along_axis mode for user-supplied # vector function function = mode # Create a new padded array rank = list(range(len(narray.shape))) total_dim_increase = [np.sum(pad_width[i]) for i in rank] offset_slices = [slice(pad_width[i][0], pad_width[i][0] + narray.shape[i]) for i in rank] new_shape = np.array(narray.shape) + total_dim_increase newmat = np.zeros(new_shape).astype(narray.dtype) # Insert the original array into the padded array newmat[offset_slices] = narray # This is the core of pad ... for iaxis in rank: np.apply_along_axis(function, iaxis, newmat, pad_width[iaxis], iaxis, kwargs) return newmat # If we get here, use new padding method newmat = narray.copy() # API preserved, but completely new algorithm which pads by building the # entire block to pad before/after `arr` with in one step, for each axis. if mode == 'constant': for axis, ((pad_before, pad_after), (before_val, after_val)) \ in enumerate(zip(pad_width, kwargs['constant_values'])): newmat = _prepend_const(newmat, pad_before, before_val, axis) newmat = _append_const(newmat, pad_after, after_val, axis) elif mode == 'edge': for axis, (pad_before, pad_after) in enumerate(pad_width): newmat = _prepend_edge(newmat, pad_before, axis) newmat = _append_edge(newmat, pad_after, axis) elif mode == 'linear_ramp': for axis, ((pad_before, pad_after), (before_val, after_val)) \ in enumerate(zip(pad_width, kwargs['end_values'])): newmat = _prepend_ramp(newmat, pad_before, before_val, axis) newmat = _append_ramp(newmat, pad_after, after_val, axis) elif mode == 'maximum': for axis, ((pad_before, pad_after), (chunk_before, chunk_after)) \ in enumerate(zip(pad_width, kwargs['stat_length'])): newmat = _prepend_max(newmat, pad_before, chunk_before, axis) newmat = _append_max(newmat, pad_after, chunk_after, axis) elif mode == 'mean': for axis, ((pad_before, pad_after), (chunk_before, chunk_after)) \ in enumerate(zip(pad_width, kwargs['stat_length'])): newmat = _prepend_mean(newmat, pad_before, chunk_before, axis) newmat = _append_mean(newmat, pad_after, chunk_after, axis) elif mode == 'median': for axis, ((pad_before, pad_after), (chunk_before, chunk_after)) \ in enumerate(zip(pad_width, kwargs['stat_length'])): newmat = _prepend_med(newmat, pad_before, chunk_before, axis) newmat = _append_med(newmat, pad_after, chunk_after, axis) elif mode == 'minimum': for axis, ((pad_before, pad_after), (chunk_before, chunk_after)) \ in enumerate(zip(pad_width, kwargs['stat_length'])): newmat = _prepend_min(newmat, pad_before, chunk_before, axis) newmat = _append_min(newmat, pad_after, chunk_after, axis) elif mode == 'reflect': for axis, (pad_before, pad_after) in enumerate(pad_width): # Recursive padding along any axis where `pad_amt` is too large # for indexing tricks. We can only safely pad the original axis # length, to keep the period of the reflections consistent. if ((pad_before > 0) or (pad_after > 0)) and newmat.shape[axis] == 1: # Extending singleton dimension for 'reflect' is legacy # behavior; it really should raise an error. newmat = _prepend_edge(newmat, pad_before, axis) newmat = _append_edge(newmat, pad_after, axis) continue method = kwargs['reflect_type'] safe_pad = newmat.shape[axis] - 1 repeat = safe_pad while ((pad_before > safe_pad) or (pad_after > safe_pad)): offset = 0 pad_iter_b = min(safe_pad, safe_pad * (pad_before // safe_pad)) pad_iter_a = min(safe_pad, safe_pad * (pad_after // safe_pad)) newmat = _pad_ref(newmat, (pad_iter_b, pad_iter_a), method, axis) pad_before -= pad_iter_b pad_after -= pad_iter_a if pad_iter_b > 0: offset += 1 if pad_iter_a > 0: offset += 1 safe_pad += pad_iter_b + pad_iter_a newmat = _pad_ref(newmat, (pad_before, pad_after), method, axis) elif mode == 'symmetric': for axis, (pad_before, pad_after) in enumerate(pad_width): # Recursive padding along any axis where `pad_amt` is too large # for indexing tricks. We can only safely pad the original axis # length, to keep the period of the reflections consistent. method = kwargs['reflect_type'] safe_pad = newmat.shape[axis] repeat = safe_pad while ((pad_before > safe_pad) or (pad_after > safe_pad)): pad_iter_b = min(safe_pad, safe_pad * (pad_before // safe_pad)) pad_iter_a = min(safe_pad, safe_pad * (pad_after // safe_pad)) newmat = _pad_sym(newmat, (pad_iter_b, pad_iter_a), method, axis) pad_before -= pad_iter_b pad_after -= pad_iter_a safe_pad += pad_iter_b + pad_iter_a newmat = _pad_sym(newmat, (pad_before, pad_after), method, axis) elif mode == 'wrap': for axis, (pad_before, pad_after) in enumerate(pad_width): # Recursive padding along any axis where `pad_amt` is too large # for indexing tricks. We can only safely pad the original axis # length, to keep the period of the reflections consistent. safe_pad = newmat.shape[axis] repeat = safe_pad while ((pad_before > safe_pad) or (pad_after > safe_pad)): pad_iter_b = min(safe_pad, safe_pad * (pad_before // safe_pad)) pad_iter_a = min(safe_pad, safe_pad * (pad_after // safe_pad)) newmat = _pad_wrap(newmat, (pad_iter_b, pad_iter_a), axis) pad_before -= pad_iter_b pad_after -= pad_iter_a safe_pad += pad_iter_b + pad_iter_a newmat = _pad_wrap(newmat, (pad_before, pad_after), axis) return newmat numpy-1.8.2/numpy/lib/nanfunctions.py0000664000175100017510000007022312370216243021025 0ustar vagrantvagrant00000000000000""" Functions that ignore NaN. Functions --------- - `nanmin` -- minimum non-NaN value - `nanmax` -- maximum non-NaN value - `nanargmin` -- index of minimum non-NaN value - `nanargmax` -- index of maximum non-NaN value - `nansum` -- sum of non-NaN values - `nanmean` -- mean of non-NaN values - `nanvar` -- variance of non-NaN values - `nanstd` -- standard deviation of non-NaN values """ from __future__ import division, absolute_import, print_function import warnings import numpy as np __all__ = [ 'nansum', 'nanmax', 'nanmin', 'nanargmax', 'nanargmin', 'nanmean', 'nanvar', 'nanstd' ] def _replace_nan(a, val): """ If `a` is of inexact type, make a copy of `a`, replace NaNs with the `val` value, and return the copy together with a boolean mask marking the locations where NaNs were present. If `a` is not of inexact type, do nothing and return `a` together with a mask of None. Parameters ---------- a : array-like Input array. val : float NaN values are set to val before doing the operation. Returns ------- y : ndarray If `a` is of inexact type, return a copy of `a` with the NaNs replaced by the fill value, otherwise return `a`. mask: {bool, None} If `a` is of inexact type, return a boolean mask marking locations of NaNs, otherwise return None. """ is_new = not isinstance(a, np.ndarray) if is_new: a = np.array(a) if not issubclass(a.dtype.type, np.inexact): return a, None if not is_new: # need copy a = np.array(a, subok=True) mask = np.isnan(a) np.copyto(a, val, where=mask) return a, mask def _copyto(a, val, mask): """ Replace values in `a` with NaN where `mask` is True. This differs from copyto in that it will deal with the case where `a` is a numpy scalar. Parameters ---------- a : ndarray or numpy scalar Array or numpy scalar some of whose values are to be replaced by val. val : numpy scalar Value used a replacement. mask : ndarray, scalar Boolean array. Where True the corresponding element of `a` is replaced by `val`. Broadcasts. Returns ------- res : ndarray, scalar Array with elements replaced or scalar `val`. """ if isinstance(a, np.ndarray): np.copyto(a, val, where=mask, casting='unsafe') else: a = a.dtype.type(val) return a def _divide_by_count(a, b, out=None): """ Compute a/b ignoring invalid results. If `a` is an array the division is done in place. If `a` is a scalar, then its type is preserved in the output. If out is None, then then a is used instead so that the division is in place. Note that this is only called with `a` an inexact type. Parameters ---------- a : {ndarray, numpy scalar} Numerator. Expected to be of inexact type but not checked. b : {ndarray, numpy scalar} Denominator. out : ndarray, optional Alternate output array in which to place the result. The default is ``None``; if provided, it must have the same shape as the expected output, but the type will be cast if necessary. Returns ------- ret : {ndarray, numpy scalar} The return value is a/b. If `a` was an ndarray the division is done in place. If `a` is a numpy scalar, the division preserves its type. """ with np.errstate(invalid='ignore'): if isinstance(a, np.ndarray): if out is None: return np.divide(a, b, out=a, casting='unsafe') else: return np.divide(a, b, out=out, casting='unsafe') else: if out is None: return a.dtype.type(a / b) else: # This is questionable, but currently a numpy scalar can # be output to a zero dimensional array. return np.divide(a, b, out=out, casting='unsafe') def nanmin(a, axis=None, out=None, keepdims=False): """ Return minimum of an array or minimum along an axis, ignoring any NaNs. When all-NaN slices are encountered a ``RuntimeWarning`` is raised and Nan is returned for that slice. Parameters ---------- a : array_like Array containing numbers whose minimum is desired. If `a` is not an array, a conversion is attempted. axis : int, optional Axis along which the minimum is computed. The default is to compute the minimum of the flattened array. out : ndarray, optional Alternate output array in which to place the result. The default is ``None``; if provided, it must have the same shape as the expected output, but the type will be cast if necessary. See `doc.ufuncs` for details. .. versionadded:: 1.8.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 `a`. .. versionadded:: 1.8.0 Returns ------- nanmin : ndarray An array with the same shape as `a`, with the specified axis removed. If `a` is a 0-d array, or if axis is None, an ndarray scalar is returned. The same dtype as `a` is returned. See Also -------- nanmax : The maximum value of an array along a given axis, ignoring any NaNs. amin : The minimum value of an array along a given axis, propagating any NaNs. fmin : Element-wise minimum of two arrays, ignoring any NaNs. minimum : Element-wise minimum of two arrays, propagating any NaNs. isnan : Shows which elements are Not a Number (NaN). isfinite: Shows which elements are neither NaN nor infinity. amax, fmax, maximum Notes ----- Numpy uses the IEEE Standard for Binary Floating-Point for Arithmetic (IEEE 754). This means that Not a Number is not equivalent to infinity. Positive infinity is treated as a very large number and negative infinity is treated as a very small (i.e. negative) number. If the input has a integer type the function is equivalent to np.min. Examples -------- >>> a = np.array([[1, 2], [3, np.nan]]) >>> np.nanmin(a) 1.0 >>> np.nanmin(a, axis=0) array([ 1., 2.]) >>> np.nanmin(a, axis=1) array([ 1., 3.]) When positive infinity and negative infinity are present: >>> np.nanmin([1, 2, np.nan, np.inf]) 1.0 >>> np.nanmin([1, 2, np.nan, np.NINF]) -inf """ if not isinstance(a, np.ndarray) or type(a) is np.ndarray: # Fast, but not safe for subclasses of ndarray res = np.fmin.reduce(a, axis=axis, out=out, keepdims=keepdims) if np.isnan(res).any(): warnings.warn("All-NaN axis encountered", RuntimeWarning) else: # Slow, but safe for subclasses of ndarray a, mask = _replace_nan(a, +np.inf) res = np.amin(a, axis=axis, out=out, keepdims=keepdims) if mask is None: return res # Check for all-NaN axis mask = np.all(mask, axis=axis, keepdims=keepdims) if np.any(mask): res = _copyto(res, np.nan, mask) warnings.warn("All-NaN axis encountered", RuntimeWarning) return res def nanmax(a, axis=None, out=None, keepdims=False): """ Return the maximum of an array or maximum along an axis, ignoring any NaNs. When all-NaN slices are encountered a ``RuntimeWarning`` is raised and NaN is returned for that slice. Parameters ---------- a : array_like Array containing numbers whose maximum is desired. If `a` is not an array, a conversion is attempted. axis : int, optional Axis along which the maximum is computed. The default is to compute the maximum of the flattened array. out : ndarray, optional Alternate output array in which to place the result. The default is ``None``; if provided, it must have the same shape as the expected output, but the type will be cast if necessary. See `doc.ufuncs` for details. .. versionadded:: 1.8.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 `a`. .. versionadded:: 1.8.0 Returns ------- nanmax : ndarray An array with the same shape as `a`, with the specified axis removed. If `a` is a 0-d array, or if axis is None, an ndarray scalar is returned. The same dtype as `a` is returned. See Also -------- nanmin : The minimum value of an array along a given axis, ignoring any NaNs. amax : The maximum value of an array along a given axis, propagating any NaNs. fmax : Element-wise maximum of two arrays, ignoring any NaNs. maximum : Element-wise maximum of two arrays, propagating any NaNs. isnan : Shows which elements are Not a Number (NaN). isfinite: Shows which elements are neither NaN nor infinity. amin, fmin, minimum Notes ----- Numpy uses the IEEE Standard for Binary Floating-Point for Arithmetic (IEEE 754). This means that Not a Number is not equivalent to infinity. Positive infinity is treated as a very large number and negative infinity is treated as a very small (i.e. negative) number. If the input has a integer type the function is equivalent to np.max. Examples -------- >>> a = np.array([[1, 2], [3, np.nan]]) >>> np.nanmax(a) 3.0 >>> np.nanmax(a, axis=0) array([ 3., 2.]) >>> np.nanmax(a, axis=1) array([ 2., 3.]) When positive infinity and negative infinity are present: >>> np.nanmax([1, 2, np.nan, np.NINF]) 2.0 >>> np.nanmax([1, 2, np.nan, np.inf]) inf """ if not isinstance(a, np.ndarray) or type(a) is np.ndarray: # Fast, but not safe for subclasses of ndarray res = np.fmax.reduce(a, axis=axis, out=out, keepdims=keepdims) if np.isnan(res).any(): warnings.warn("All-NaN slice encountered", RuntimeWarning) else: # Slow, but safe for subclasses of ndarray a, mask = _replace_nan(a, -np.inf) res = np.amax(a, axis=axis, out=out, keepdims=keepdims) if mask is None: return res # Check for all-NaN axis mask = np.all(mask, axis=axis, keepdims=keepdims) if np.any(mask): res = _copyto(res, np.nan, mask) warnings.warn("All-NaN axis encountered", RuntimeWarning) return res def nanargmin(a, axis=None): """ Return the indices of the minimum values in the specified axis ignoring NaNs. For all-NaN slices ``ValueError`` is raised. Warning: the results cannot be trusted if a slice contains only NaNs and Infs. Parameters ---------- a : array_like Input data. axis : int, optional Axis along which to operate. By default flattened input is used. Returns ------- index_array : ndarray An array of indices or a single index value. See Also -------- argmin, nanargmax Examples -------- >>> a = np.array([[np.nan, 4], [2, 3]]) >>> np.argmin(a) 0 >>> np.nanargmin(a) 2 >>> np.nanargmin(a, axis=0) array([1, 1]) >>> np.nanargmin(a, axis=1) array([1, 0]) """ a, mask = _replace_nan(a, np.inf) res = np.argmin(a, axis=axis) if mask is not None: mask = np.all(mask, axis=axis) if np.any(mask): raise ValueError("All-NaN slice encountered") return res def nanargmax(a, axis=None): """ Return the indices of the maximum values in the specified axis ignoring NaNs. For all-NaN slices ``ValueError`` is raised. Warning: the results cannot be trusted if a slice contains only NaNs and -Infs. Parameters ---------- a : array_like Input data. axis : int, optional Axis along which to operate. By default flattened input is used. Returns ------- index_array : ndarray An array of indices or a single index value. See Also -------- argmax, nanargmin Examples -------- >>> a = np.array([[np.nan, 4], [2, 3]]) >>> np.argmax(a) 0 >>> np.nanargmax(a) 1 >>> np.nanargmax(a, axis=0) array([1, 0]) >>> np.nanargmax(a, axis=1) array([1, 1]) """ a, mask = _replace_nan(a, -np.inf) res = np.argmax(a, axis=axis) if mask is not None: mask = np.all(mask, axis=axis) if np.any(mask): raise ValueError("All-NaN slice encountered") return res def nansum(a, axis=None, dtype=None, out=None, keepdims=0): """ Return the sum of array elements over a given axis treating Not a Numbers (NaNs) as zero. FutureWarning: In Numpy versions <= 1.8 Nan is returned for slices that are all-NaN or empty. In later versions zero will be returned. Parameters ---------- a : array_like Array containing numbers whose sum is desired. If `a` is not an array, a conversion is attempted. axis : int, optional Axis along which the sum is computed. The default is to compute the sum of the flattened array. dtype : data-type, optional The type of the returned array and of the accumulator in which the elements are summed. By default, the dtype of `a` is used. An exception is when `a` has an integer type with less precision than the platform (u)intp. In that case, the default will be either (u)int32 or (u)int64 depending on whether the platform is 32 or 64 bits. For inexact inputs, dtype must be inexact. .. versionadded:: 1.8.0 out : ndarray, optional Alternate output array in which to place the result. The default is ``None``. If provided, it must have the same shape as the expected output, but the type will be cast if necessary. See `doc.ufuncs` for details. The casting of NaN to integer can yield unexpected results. .. versionadded:: 1.8.0 keepdims : bool, optional If 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.8.0 Returns ------- y : ndarray or numpy scalar See Also -------- numpy.sum : Sum across array propagating NaNs. isnan : Show which elements are NaN. isfinite: Show which elements are not NaN or +/-inf. Notes ----- If both positive and negative infinity are present, the sum will be Not A Number (NaN). Numpy integer arithmetic is modular. If the size of a sum exceeds the size of an integer accumulator, its value will wrap around and the result will be incorrect. Specifying ``dtype=double`` can alleviate that problem. Examples -------- >>> np.nansum(1) 1 >>> np.nansum([1]) 1 >>> np.nansum([1, np.nan]) 1.0 >>> a = np.array([[1, 1], [1, np.nan]]) >>> np.nansum(a) 3.0 >>> np.nansum(a, axis=0) array([ 2., 1.]) >>> np.nansum([1, np.nan, np.inf]) inf >>> np.nansum([1, np.nan, np.NINF]) -inf >>> np.nansum([1, np.nan, np.inf, -np.inf]) # both +/- infinity present nan """ a, mask = _replace_nan(a, 0) if mask is None: return np.sum(a, axis=axis, dtype=dtype, out=out, keepdims=keepdims) mask = np.all(mask, axis=axis, keepdims=keepdims) tot = np.sum(a, axis=axis, dtype=dtype, out=out, keepdims=keepdims) if np.any(mask): tot = _copyto(tot, np.nan, mask) warnings.warn("In Numpy 1.9 the sum along empty slices will be zero.", FutureWarning) return tot def nanmean(a, axis=None, dtype=None, out=None, keepdims=False): """ Compute the arithmetic mean along the specified axis, ignoring NaNs. Returns the average of the array elements. The average is taken over the flattened array by default, otherwise over the specified axis. `float64` intermediate and return values are used for integer inputs. For all-NaN slices, NaN is returned and a `RuntimeWarning` is raised. .. versionadded:: 1.8.0 Parameters ---------- a : array_like Array containing numbers whose mean is desired. If `a` is not an array, a conversion is attempted. axis : int, optional Axis along which the means are computed. The default is to compute the mean of the flattened array. dtype : data-type, optional Type to use in computing the mean. For integer inputs, the default is `float64`; for inexact inputs, it is the same as the input dtype. out : ndarray, optional Alternate output array in which to place the result. The default is ``None``; if provided, it must have the same shape as the expected output, but the type will be cast if necessary. See `doc.ufuncs` for details. 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 ------- m : ndarray, see dtype parameter above If `out=None`, returns a new array containing the mean values, otherwise a reference to the output array is returned. Nan is returned for slices that contain only NaNs. See Also -------- average : Weighted average mean : Arithmetic mean taken while not ignoring NaNs var, nanvar Notes ----- The arithmetic mean is the sum of the non-NaN elements along the axis divided by the number of non-NaN elements. Note that for floating-point input, the mean is computed using the same precision the input has. Depending on the input data, this can cause the results to be inaccurate, especially for `float32`. Specifying a higher-precision accumulator using the `dtype` keyword can alleviate this issue. Examples -------- >>> a = np.array([[1, np.nan], [3, 4]]) >>> np.nanmean(a) 2.6666666666666665 >>> np.nanmean(a, axis=0) array([ 2., 4.]) >>> np.nanmean(a, axis=1) array([ 1., 3.5]) """ arr, mask = _replace_nan(a, 0) if mask is None: return np.mean(arr, axis=axis, dtype=dtype, out=out, keepdims=keepdims) if dtype is not None: dtype = np.dtype(dtype) if dtype is not None and not issubclass(dtype.type, np.inexact): raise TypeError("If a is inexact, then dtype must be inexact") if out is not None and not issubclass(out.dtype.type, np.inexact): raise TypeError("If a is inexact, then out must be inexact") # The warning context speeds things up. with warnings.catch_warnings(): warnings.simplefilter('ignore') cnt = np.sum(~mask, axis=axis, dtype=np.intp, keepdims=keepdims) tot = np.sum(arr, axis=axis, dtype=dtype, out=out, keepdims=keepdims) avg = _divide_by_count(tot, cnt, out=out) isbad = (cnt == 0) if isbad.any(): warnings.warn("Mean of empty slice", RuntimeWarning) # NaN is the only possible bad value, so no further # action is needed to handle bad results. return avg def nanvar(a, axis=None, dtype=None, out=None, ddof=0, keepdims=False): """ Compute the variance along the specified axis, while ignoring NaNs. Returns the variance of the array elements, a measure of the spread of a distribution. The variance is computed for the flattened array by default, otherwise over the specified axis. For all-NaN slices or slices with zero degrees of freedom, NaN is returned and a `RuntimeWarning` is raised. .. versionadded:: 1.8.0 Parameters ---------- a : array_like Array containing numbers whose variance is desired. If `a` is not an array, a conversion is attempted. axis : int, optional Axis along which the variance is computed. The default is to compute the variance of the flattened array. dtype : data-type, optional Type to use in computing the variance. For arrays of integer type the default is `float32`; for arrays of float types it is the same as the array type. out : ndarray, optional Alternate output array in which to place the result. It must have the same shape as the expected output, but the type is cast if necessary. ddof : int, optional "Delta Degrees of Freedom": the divisor used in the calculation is ``N - ddof``, where ``N`` represents the number of non-NaN elements. By default `ddof` is zero. 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 ------- variance : ndarray, see dtype parameter above If `out` is None, return a new array containing the variance, otherwise return a reference to the output array. If ddof is >= the number of non-NaN elements in a slice or the slice contains only NaNs, then the result for that slice is NaN. See Also -------- std : Standard deviation mean : Average var : Variance while not ignoring NaNs nanstd, nanmean numpy.doc.ufuncs : Section "Output arguments" Notes ----- The variance is the average of the squared deviations from the mean, i.e., ``var = mean(abs(x - x.mean())**2)``. The mean is normally calculated as ``x.sum() / N``, where ``N = len(x)``. If, however, `ddof` is specified, the divisor ``N - ddof`` is used instead. In standard statistical practice, ``ddof=1`` provides an unbiased estimator of the variance of a hypothetical infinite population. ``ddof=0`` provides a maximum likelihood estimate of the variance for normally distributed variables. Note that for complex numbers, the absolute value is taken before squaring, so that the result is always real and nonnegative. For floating-point input, the variance is computed using the same precision the input has. Depending on the input data, this can cause the results to be inaccurate, especially for `float32` (see example below). Specifying a higher-accuracy accumulator using the ``dtype`` keyword can alleviate this issue. Examples -------- >>> a = np.array([[1, np.nan], [3, 4]]) >>> np.var(a) 1.5555555555555554 >>> np.nanvar(a, axis=0) array([ 1., 0.]) >>> np.nanvar(a, axis=1) array([ 0., 0.25]) """ arr, mask = _replace_nan(a, 0) if mask is None: return np.var(arr, axis=axis, dtype=dtype, out=out, ddof=ddof, keepdims=keepdims) if dtype is not None: dtype = np.dtype(dtype) if dtype is not None and not issubclass(dtype.type, np.inexact): raise TypeError("If a is inexact, then dtype must be inexact") if out is not None and not issubclass(out.dtype.type, np.inexact): raise TypeError("If a is inexact, then out must be inexact") with warnings.catch_warnings(): warnings.simplefilter('ignore') # Compute mean cnt = np.sum(~mask, axis=axis, dtype=np.intp, keepdims=True) avg = np.sum(arr, axis=axis, dtype=dtype, keepdims=True) avg = _divide_by_count(avg, cnt) # Compute squared deviation from mean. arr -= avg arr = _copyto(arr, 0, mask) if issubclass(arr.dtype.type, np.complexfloating): sqr = np.multiply(arr, arr.conj(), out=arr).real else: sqr = np.multiply(arr, arr, out=arr) # Compute variance. var = np.sum(sqr, axis=axis, dtype=dtype, out=out, keepdims=keepdims) if var.ndim < cnt.ndim: # Subclasses of ndarray may ignore keepdims, so check here. cnt = cnt.squeeze(axis) dof = cnt - ddof var = _divide_by_count(var, dof) isbad = (dof <= 0) if np.any(isbad): warnings.warn("Degrees of freedom <= 0 for slice.", RuntimeWarning) # NaN, inf, or negative numbers are all possible bad # values, so explicitly replace them with NaN. var = _copyto(var, np.nan, isbad) return var def nanstd(a, axis=None, dtype=None, out=None, ddof=0, keepdims=False): """ Compute the standard deviation along the specified axis, while ignoring NaNs. Returns the standard deviation, a measure of the spread of a distribution, of the non-NaN array elements. The standard deviation is computed for the flattened array by default, otherwise over the specified axis. For all-NaN slices or slices with zero degrees of freedom, NaN is returned and a `RuntimeWarning` is raised. .. versionadded:: 1.8.0 Parameters ---------- a : array_like Calculate the standard deviation of the non-NaN values. axis : int, optional Axis along which the standard deviation is computed. The default is to compute the standard deviation of the flattened array. dtype : dtype, optional Type to use in computing the standard deviation. For arrays of integer type the default is float64, for arrays of float types it is the same as the array type. out : ndarray, optional Alternative output array in which to place the result. It must have the same shape as the expected output but the type (of the calculated values) will be cast if necessary. ddof : int, optional Means Delta Degrees of Freedom. The divisor used in calculations is ``N - ddof``, where ``N`` represents the number of non-NaN elements. By default `ddof` is zero. 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 ------- standard_deviation : ndarray, see dtype parameter above. If `out` is None, return a new array containing the standard deviation, otherwise return a reference to the output array. If ddof is >= the number of non-NaN elements in a slice or the slice contains only NaNs, then the result for that slice is NaN. See Also -------- var, mean, std nanvar, nanmean numpy.doc.ufuncs : Section "Output arguments" Notes ----- The standard deviation is the square root of the average of the squared deviations from the mean: ``std = sqrt(mean(abs(x - x.mean())**2))``. The average squared deviation is normally calculated as ``x.sum() / N``, where ``N = len(x)``. If, however, `ddof` is specified, the divisor ``N - ddof`` is used instead. In standard statistical practice, ``ddof=1`` provides an unbiased estimator of the variance of the infinite population. ``ddof=0`` provides a maximum likelihood estimate of the variance for normally distributed variables. The standard deviation computed in this function is the square root of the estimated variance, so even with ``ddof=1``, it will not be an unbiased estimate of the standard deviation per se. Note that, for complex numbers, `std` takes the absolute value before squaring, so that the result is always real and nonnegative. For floating-point input, the *std* is computed using the same precision the input has. Depending on the input data, this can cause the results to be inaccurate, especially for float32 (see example below). Specifying a higher-accuracy accumulator using the `dtype` keyword can alleviate this issue. Examples -------- >>> a = np.array([[1, np.nan], [3, 4]]) >>> np.nanstd(a) 1.247219128924647 >>> np.nanstd(a, axis=0) array([ 1., 0.]) >>> np.nanstd(a, axis=1) array([ 0., 0.5]) """ var = nanvar(a, axis=axis, dtype=dtype, out=out, ddof=ddof, keepdims=keepdims) if isinstance(var, np.ndarray): std = np.sqrt(var, out=var) else: std = var.dtype.type(np.sqrt(var)) return std numpy-1.8.2/numpy/lib/_datasource.py0000664000175100017510000005142112370216243020610 0ustar vagrantvagrant00000000000000"""A file interface for handling local and remote data files. The goal of datasource is to abstract some of the file system operations when dealing with data files so the researcher doesn't have to know all the low-level details. Through datasource, a researcher can obtain and use a file with one function call, regardless of location of the file. DataSource is meant to augment standard python libraries, not replace them. It should work seemlessly with standard file IO operations and the os module. DataSource files can originate locally or remotely: - local files : '/home/guido/src/local/data.txt' - URLs (http, ftp, ...) : 'http://www.scipy.org/not/real/data.txt' DataSource files can also be compressed or uncompressed. Currently only gzip and bz2 are supported. Example:: >>> # Create a DataSource, use os.curdir (default) for local storage. >>> ds = datasource.DataSource() >>> >>> # Open a remote file. >>> # DataSource downloads the file, stores it locally in: >>> # './www.google.com/index.html' >>> # opens the file and returns a file object. >>> fp = ds.open('http://www.google.com/index.html') >>> >>> # Use the file as you normally would >>> fp.read() >>> fp.close() """ from __future__ import division, absolute_import, print_function __docformat__ = "restructuredtext en" import os import sys from shutil import rmtree, copyfile, copyfileobj _open = open # Using a class instead of a module-level dictionary # to reduce the inital 'import numpy' overhead by # deferring the import of bz2 and gzip until needed # TODO: .zip support, .tar support? class _FileOpeners(object): """ Container for different methods to open (un-)compressed files. `_FileOpeners` contains a dictionary that holds one method for each supported file format. Attribute lookup is implemented in such a way that an instance of `_FileOpeners` itself can be indexed with the keys of that dictionary. Currently uncompressed files as well as files compressed with ``gzip`` or ``bz2`` compression are supported. Notes ----- `_file_openers`, an instance of `_FileOpeners`, is made available for use in the `_datasource` module. Examples -------- >>> np.lib._datasource._file_openers.keys() [None, '.bz2', '.gz'] >>> np.lib._datasource._file_openers['.gz'] is gzip.open True """ def __init__(self): self._loaded = False self._file_openers = {None: open} def _load(self): if self._loaded: return try: import bz2 self._file_openers[".bz2"] = bz2.BZ2File except ImportError: pass try: import gzip self._file_openers[".gz"] = gzip.open except ImportError: pass self._loaded = True def keys(self): """ Return the keys of currently supported file openers. Parameters ---------- None Returns ------- keys : list The keys are None for uncompressed files and the file extension strings (i.e. ``'.gz'``, ``'.bz2'``) for supported compression methods. """ self._load() return list(self._file_openers.keys()) def __getitem__(self, key): self._load() return self._file_openers[key] _file_openers = _FileOpeners() def open(path, mode='r', destpath=os.curdir): """ Open `path` with `mode` and return the file object. If ``path`` is an URL, it will be downloaded, stored in the `DataSource` `destpath` directory and opened from there. Parameters ---------- path : str Local file path or URL to open. mode : str, optional Mode to open `path`. Mode 'r' for reading, 'w' for writing, 'a' to append. Available modes depend on the type of object specified by path. Default is 'r'. destpath : str, optional Path to the directory where the source file gets downloaded to for use. If `destpath` is None, a temporary directory will be created. The default path is the current directory. Returns ------- out : file object The opened file. Notes ----- This is a convenience function that instantiates a `DataSource` and returns the file object from ``DataSource.open(path)``. """ ds = DataSource(destpath) return ds.open(path, mode) class DataSource (object): """ DataSource(destpath='.') A generic data source file (file, http, ftp, ...). DataSources can be local files or remote files/URLs. The files may also be compressed or uncompressed. DataSource hides some of the low-level details of downloading the file, allowing you to simply pass in a valid file path (or URL) and obtain a file object. Parameters ---------- destpath : str or None, optional Path to the directory where the source file gets downloaded to for use. If `destpath` is None, a temporary directory will be created. The default path is the current directory. Notes ----- URLs require a scheme string (``http://``) to be used, without it they will fail:: >>> repos = DataSource() >>> repos.exists('www.google.com/index.html') False >>> repos.exists('http://www.google.com/index.html') True Temporary directories are deleted when the DataSource is deleted. Examples -------- :: >>> ds = DataSource('/home/guido') >>> urlname = 'http://www.google.com/index.html' >>> gfile = ds.open('http://www.google.com/index.html') # remote file >>> ds.abspath(urlname) '/home/guido/www.google.com/site/index.html' >>> ds = DataSource(None) # use with temporary file >>> ds.open('/home/guido/foobar.txt') >>> ds.abspath('/home/guido/foobar.txt') '/tmp/tmpy4pgsP/home/guido/foobar.txt' """ def __init__(self, destpath=os.curdir): """Create a DataSource with a local path at destpath.""" if destpath: self._destpath = os.path.abspath(destpath) self._istmpdest = False else: import tempfile # deferring import to improve startup time self._destpath = tempfile.mkdtemp() self._istmpdest = True def __del__(self): # Remove temp directories if self._istmpdest: rmtree(self._destpath) def _iszip(self, filename): """Test if the filename is a zip file by looking at the file extension. """ fname, ext = os.path.splitext(filename) return ext in _file_openers.keys() def _iswritemode(self, mode): """Test if the given mode will open a file for writing.""" # Currently only used to test the bz2 files. _writemodes = ("w", "+") for c in mode: if c in _writemodes: return True return False def _splitzipext(self, filename): """Split zip extension from filename and return filename. *Returns*: base, zip_ext : {tuple} """ if self._iszip(filename): return os.path.splitext(filename) else: return filename, None def _possible_names(self, filename): """Return a tuple containing compressed filename variations.""" names = [filename] if not self._iszip(filename): for zipext in _file_openers.keys(): if zipext: names.append(filename+zipext) return names def _isurl(self, path): """Test if path is a net location. Tests the scheme and netloc.""" # We do this here to reduce the 'import numpy' initial import time. if sys.version_info[0] >= 3: from urllib.parse import urlparse else: from urlparse import urlparse # BUG : URLs require a scheme string ('http://') to be used. # www.google.com will fail. # Should we prepend the scheme for those that don't have it and # test that also? Similar to the way we append .gz and test for # for compressed versions of files. scheme, netloc, upath, uparams, uquery, ufrag = urlparse(path) return bool(scheme and netloc) def _cache(self, path): """Cache the file specified by path. Creates a copy of the file in the datasource cache. """ # We import these here because importing urllib2 is slow and # a significant fraction of numpy's total import time. if sys.version_info[0] >= 3: from urllib.request import urlopen from urllib.error import URLError else: from urllib2 import urlopen from urllib2 import URLError upath = self.abspath(path) # ensure directory exists if not os.path.exists(os.path.dirname(upath)): os.makedirs(os.path.dirname(upath)) # TODO: Doesn't handle compressed files! if self._isurl(path): try: openedurl = urlopen(path) f = _open(upath, 'wb') try: copyfileobj(openedurl, f) finally: f.close() openedurl.close() except URLError: raise URLError("URL not found: %s" % path) else: shutil.copyfile(path, upath) return upath def _findfile(self, path): """Searches for ``path`` and returns full path if found. If path is an URL, _findfile will cache a local copy and return the path to the cached file. If path is a local file, _findfile will return a path to that local file. The search will include possible compressed versions of the file and return the first occurence found. """ # Build list of possible local file paths if not self._isurl(path): # Valid local paths filelist = self._possible_names(path) # Paths in self._destpath filelist += self._possible_names(self.abspath(path)) else: # Cached URLs in self._destpath filelist = self._possible_names(self.abspath(path)) # Remote URLs filelist = filelist + self._possible_names(path) for name in filelist: if self.exists(name): if self._isurl(name): name = self._cache(name) return name return None def abspath(self, path): """ Return absolute path of file in the DataSource directory. If `path` is an URL, then `abspath` will return either the location the file exists locally or the location it would exist when opened using the `open` method. Parameters ---------- path : str Can be a local file or a remote URL. Returns ------- out : str Complete path, including the `DataSource` destination directory. Notes ----- The functionality is based on `os.path.abspath`. """ # We do this here to reduce the 'import numpy' initial import time. if sys.version_info[0] >= 3: from urllib.parse import urlparse else: from urlparse import urlparse # TODO: This should be more robust. Handles case where path includes # the destpath, but not other sub-paths. Failing case: # path = /home/guido/datafile.txt # destpath = /home/alex/ # upath = self.abspath(path) # upath == '/home/alex/home/guido/datafile.txt' # handle case where path includes self._destpath splitpath = path.split(self._destpath, 2) if len(splitpath) > 1: path = splitpath[1] scheme, netloc, upath, uparams, uquery, ufrag = urlparse(path) netloc = self._sanitize_relative_path(netloc) upath = self._sanitize_relative_path(upath) return os.path.join(self._destpath, netloc, upath) def _sanitize_relative_path(self, path): """Return a sanitised relative path for which os.path.abspath(os.path.join(base, path)).startswith(base) """ last = None path = os.path.normpath(path) while path != last: last = path # Note: os.path.join treats '/' as os.sep on Windows path = path.lstrip(os.sep).lstrip('/') path = path.lstrip(os.pardir).lstrip('..') drive, path = os.path.splitdrive(path) # for Windows return path def exists(self, path): """ Test if path exists. Test if `path` exists as (and in this order): - a local file. - a remote URL that has been downloaded and stored locally in the `DataSource` directory. - a remote URL that has not been downloaded, but is valid and accessible. Parameters ---------- path : str Can be a local file or a remote URL. Returns ------- out : bool True if `path` exists. Notes ----- When `path` is an URL, `exists` will return True if it's either stored locally in the `DataSource` directory, or is a valid remote URL. `DataSource` does not discriminate between the two, the file is accessible if it exists in either location. """ # We import this here because importing urllib2 is slow and # a significant fraction of numpy's total import time. if sys.version_info[0] >= 3: from urllib.request import urlopen from urllib.error import URLError else: from urllib2 import urlopen from urllib2 import URLError # Test local path if os.path.exists(path): return True # Test cached url upath = self.abspath(path) if os.path.exists(upath): return True # Test remote url if self._isurl(path): try: netfile = urlopen(path) netfile.close() del(netfile) return True except URLError: return False return False def open(self, path, mode='r'): """ Open and return file-like object. If `path` is an URL, it will be downloaded, stored in the `DataSource` directory and opened from there. Parameters ---------- path : str Local file path or URL to open. mode : {'r', 'w', 'a'}, optional Mode to open `path`. Mode 'r' for reading, 'w' for writing, 'a' to append. Available modes depend on the type of object specified by `path`. Default is 'r'. Returns ------- out : file object File object. """ # TODO: There is no support for opening a file for writing which # doesn't exist yet (creating a file). Should there be? # TODO: Add a ``subdir`` parameter for specifying the subdirectory # used to store URLs in self._destpath. if self._isurl(path) and self._iswritemode(mode): raise ValueError("URLs are not writeable") # NOTE: _findfile will fail on a new file opened for writing. found = self._findfile(path) if found: _fname, ext = self._splitzipext(found) if ext == 'bz2': mode.replace("+", "") return _file_openers[ext](found, mode=mode) else: raise IOError("%s not found." % path) class Repository (DataSource): """ Repository(baseurl, destpath='.') A data repository where multiple DataSource's share a base URL/directory. `Repository` extends `DataSource` by prepending a base URL (or directory) to all the files it handles. Use `Repository` when you will be working with multiple files from one base URL. Initialize `Repository` with the base URL, then refer to each file by its filename only. Parameters ---------- baseurl : str Path to the local directory or remote location that contains the data files. destpath : str or None, optional Path to the directory where the source file gets downloaded to for use. If `destpath` is None, a temporary directory will be created. The default path is the current directory. Examples -------- To analyze all files in the repository, do something like this (note: this is not self-contained code):: >>> repos = np.lib._datasource.Repository('/home/user/data/dir/') >>> for filename in filelist: ... fp = repos.open(filename) ... fp.analyze() ... fp.close() Similarly you could use a URL for a repository:: >>> repos = np.lib._datasource.Repository('http://www.xyz.edu/data') """ def __init__(self, baseurl, destpath=os.curdir): """Create a Repository with a shared url or directory of baseurl.""" DataSource.__init__(self, destpath=destpath) self._baseurl = baseurl def __del__(self): DataSource.__del__(self) def _fullpath(self, path): """Return complete path for path. Prepends baseurl if necessary.""" splitpath = path.split(self._baseurl, 2) if len(splitpath) == 1: result = os.path.join(self._baseurl, path) else: result = path # path contains baseurl already return result def _findfile(self, path): """Extend DataSource method to prepend baseurl to ``path``.""" return DataSource._findfile(self, self._fullpath(path)) def abspath(self, path): """ Return absolute path of file in the Repository directory. If `path` is an URL, then `abspath` will return either the location the file exists locally or the location it would exist when opened using the `open` method. Parameters ---------- path : str Can be a local file or a remote URL. This may, but does not have to, include the `baseurl` with which the `Repository` was initialized. Returns ------- out : str Complete path, including the `DataSource` destination directory. """ return DataSource.abspath(self, self._fullpath(path)) def exists(self, path): """ Test if path exists prepending Repository base URL to path. Test if `path` exists as (and in this order): - a local file. - a remote URL that has been downloaded and stored locally in the `DataSource` directory. - a remote URL that has not been downloaded, but is valid and accessible. Parameters ---------- path : str Can be a local file or a remote URL. This may, but does not have to, include the `baseurl` with which the `Repository` was initialized. Returns ------- out : bool True if `path` exists. Notes ----- When `path` is an URL, `exists` will return True if it's either stored locally in the `DataSource` directory, or is a valid remote URL. `DataSource` does not discriminate between the two, the file is accessible if it exists in either location. """ return DataSource.exists(self, self._fullpath(path)) def open(self, path, mode='r'): """ Open and return file-like object prepending Repository base URL. If `path` is an URL, it will be downloaded, stored in the DataSource directory and opened from there. Parameters ---------- path : str Local file path or URL to open. This may, but does not have to, include the `baseurl` with which the `Repository` was initialized. mode : {'r', 'w', 'a'}, optional Mode to open `path`. Mode 'r' for reading, 'w' for writing, 'a' to append. Available modes depend on the type of object specified by `path`. Default is 'r'. Returns ------- out : file object File object. """ return DataSource.open(self, self._fullpath(path), mode) def listdir(self): """ List files in the source Repository. Returns ------- files : list of str List of file names (not containing a directory part). Notes ----- Does not currently work for remote repositories. """ if self._isurl(self._baseurl): raise NotImplementedError( "Directory listing of URLs, not supported yet.") else: return os.listdir(self._baseurl) numpy-1.8.2/numpy/lib/npyio.py0000664000175100017510000020112712370216243017455 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function import numpy as np from . import format import sys import os import re import sys import itertools import warnings import weakref from operator import itemgetter from ._datasource import DataSource from ._compiled_base import packbits, unpackbits from ._iotools import ( LineSplitter, NameValidator, StringConverter, ConverterError, ConverterLockError, ConversionWarning, _is_string_like, has_nested_fields, flatten_dtype, easy_dtype, _bytes_to_name ) from numpy.compat import ( asbytes, asstr, asbytes_nested, bytes, basestring, unicode ) if sys.version_info[0] >= 3: import pickle else: import cPickle as pickle from future_builtins import map loads = pickle.loads __all__ = ['savetxt', 'loadtxt', 'genfromtxt', 'ndfromtxt', 'mafromtxt', 'recfromtxt', 'recfromcsv', 'load', 'loads', 'save', 'savez', 'savez_compressed', 'packbits', 'unpackbits', 'fromregex', 'DataSource'] _string_like = _is_string_like def seek_gzip_factory(f): """Use this factory to produce the class so that we can do a lazy import on gzip. """ import gzip class GzipFile(gzip.GzipFile): def seek(self, offset, whence=0): # figure out new position (we can only seek forwards) if whence == 1: offset = self.offset + offset if whence not in [0, 1]: raise IOError("Illegal argument") if offset < self.offset: # for negative seek, rewind and do positive seek self.rewind() count = offset - self.offset for i in range(count // 1024): self.read(1024) self.read(count % 1024) def tell(self): return self.offset if isinstance(f, str): f = GzipFile(f) elif isinstance(f, gzip.GzipFile): # cast to our GzipFile if its already a gzip.GzipFile try: name = f.name except AttributeError: # Backward compatibility for <= 2.5 name = f.filename mode = f.mode f = GzipFile(fileobj=f.fileobj, filename=name) f.mode = mode return f class BagObj(object): """ BagObj(obj) Convert attribute look-ups to getitems on the object passed in. Parameters ---------- obj : class instance Object on which attribute look-up is performed. Examples -------- >>> from numpy.lib.npyio import BagObj as BO >>> class BagDemo(object): ... def __getitem__(self, key): # An instance of BagObj(BagDemo) ... # will call this method when any ... # attribute look-up is required ... result = "Doesn't matter what you want, " ... return result + "you're gonna get this" ... >>> demo_obj = BagDemo() >>> bagobj = BO(demo_obj) >>> bagobj.hello_there "Doesn't matter what you want, you're gonna get this" >>> bagobj.I_can_be_anything "Doesn't matter what you want, you're gonna get this" """ def __init__(self, obj): # Use weakref to make NpzFile objects collectable by refcount self._obj = weakref.proxy(obj) def __getattribute__(self, key): try: return object.__getattribute__(self, '_obj')[key] except KeyError: raise AttributeError(key) def zipfile_factory(*args, **kwargs): import zipfile kwargs['allowZip64'] = True return zipfile.ZipFile(*args, **kwargs) class NpzFile(object): """ NpzFile(fid) A dictionary-like object with lazy-loading of files in the zipped archive provided on construction. `NpzFile` is used to load files in the NumPy ``.npz`` data archive format. It assumes that files in the archive have a ".npy" extension, other files are ignored. The arrays and file strings are lazily loaded on either getitem access using ``obj['key']`` or attribute lookup using ``obj.f.key``. A list of all files (without ".npy" extensions) can be obtained with ``obj.files`` and the ZipFile object itself using ``obj.zip``. Attributes ---------- files : list of str List of all files in the archive with a ".npy" extension. zip : ZipFile instance The ZipFile object initialized with the zipped archive. f : BagObj instance An object on which attribute can be performed as an alternative to getitem access on the `NpzFile` instance itself. Parameters ---------- fid : file or str The zipped archive to open. This is either a file-like object or a string containing the path to the archive. own_fid : bool, optional Whether NpzFile should close the file handle. Requires that `fid` is a file-like object. Examples -------- >>> from tempfile import TemporaryFile >>> outfile = TemporaryFile() >>> x = np.arange(10) >>> y = np.sin(x) >>> np.savez(outfile, x=x, y=y) >>> outfile.seek(0) >>> npz = np.load(outfile) >>> isinstance(npz, np.lib.io.NpzFile) True >>> npz.files ['y', 'x'] >>> npz['x'] # getitem access array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) >>> npz.f.x # attribute lookup array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) """ def __init__(self, fid, own_fid=False): # Import is postponed to here since zipfile depends on gzip, an optional # component of the so-called standard library. _zip = zipfile_factory(fid) self._files = _zip.namelist() self.files = [] for x in self._files: if x.endswith('.npy'): self.files.append(x[:-4]) else: self.files.append(x) self.zip = _zip self.f = BagObj(self) if own_fid: self.fid = fid else: self.fid = None def __enter__(self): return self def __exit__(self, exc_type, exc_value, traceback): self.close() def close(self): """ Close the file. """ if self.zip is not None: self.zip.close() self.zip = None if self.fid is not None: self.fid.close() self.fid = None self.f = None # break reference cycle def __del__(self): self.close() def __getitem__(self, key): # FIXME: This seems like it will copy strings around # more than is strictly necessary. The zipfile # will read the string and then # the format.read_array will copy the string # to another place in memory. # It would be better if the zipfile could read # (or at least uncompress) the data # directly into the array memory. member = 0 if key in self._files: member = 1 elif key in self.files: member = 1 key += '.npy' if member: bytes = self.zip.open(key) magic = bytes.read(len(format.MAGIC_PREFIX)) bytes.close() if magic == format.MAGIC_PREFIX: bytes = self.zip.open(key) return format.read_array(bytes) else: return self.zip.read(key) else: raise KeyError("%s is not a file in the archive" % key) def __iter__(self): return iter(self.files) def items(self): """ Return a list of tuples, with each tuple (filename, array in file). """ return [(f, self[f]) for f in self.files] def iteritems(self): """Generator that returns tuples (filename, array in file).""" for f in self.files: yield (f, self[f]) def keys(self): """Return files in the archive with a ".npy" extension.""" return self.files def iterkeys(self): """Return an iterator over the files in the archive.""" return self.__iter__() def __contains__(self, key): return self.files.__contains__(key) def load(file, mmap_mode=None): """ Load an array(s) or pickled objects from .npy, .npz, or pickled files. Parameters ---------- file : file-like object or string The file to read. Compressed files with the filename extension ``.gz`` are acceptable. 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. 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. Raises ------ IOError If the input file does not exist or cannot be read. See Also -------- save, savez, savez_compressed, loadtxt memmap : Create a memory-map to an array stored in a file on disk. Notes ----- - If the file contains pickle data, then whatever object is stored in the pickle is returned. - If the file is a ``.npy`` file, then a single array is returned. - 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:: with load('foo.npz') as data: a = data['a'] The underlying file descriptor is closed when exiting the 'with' block. Examples -------- Store data to disk, and load it again: >>> np.save('/tmp/123', np.array([[1, 2, 3], [4, 5, 6]])) >>> np.load('/tmp/123.npy') array([[1, 2, 3], [4, 5, 6]]) Store compressed data to disk, and load it again: >>> a=np.array([[1, 2, 3], [4, 5, 6]]) >>> b=np.array([1, 2]) >>> np.savez('/tmp/123.npz', a=a, b=b) >>> data = np.load('/tmp/123.npz') >>> data['a'] array([[1, 2, 3], [4, 5, 6]]) >>> data['b'] array([1, 2]) >>> data.close() Mem-map the stored array, and then access the second row directly from disk: >>> X = np.load('/tmp/123.npy', mmap_mode='r') >>> X[1, :] memmap([4, 5, 6]) """ import gzip own_fid = False if isinstance(file, basestring): fid = open(file, "rb") own_fid = True elif isinstance(file, gzip.GzipFile): fid = seek_gzip_factory(file) else: fid = file try: # Code to distinguish from NumPy binary files and pickles. _ZIP_PREFIX = asbytes('PK\x03\x04') N = len(format.MAGIC_PREFIX) magic = fid.read(N) fid.seek(-N, 1) # back-up if magic.startswith(_ZIP_PREFIX): # zip-file (assume .npz) # Transfer file ownership to NpzFile tmp = own_fid own_fid = False return NpzFile(fid, own_fid=tmp) elif magic == format.MAGIC_PREFIX: # .npy file if mmap_mode: return format.open_memmap(file, mode=mmap_mode) else: return format.read_array(fid) else: # Try a pickle try: return pickle.load(fid) except: raise IOError( "Failed to interpret file %s as a pickle" % repr(file)) finally: if own_fid: fid.close() def save(file, arr): """ Save an array to a binary file in NumPy ``.npy`` format. Parameters ---------- file : file or str File or filename to which the data is saved. If file is a file-object, then the filename is unchanged. If file is a string, a ``.npy`` extension will be appended to the file name if it does not already have one. arr : array_like Array data to be saved. See Also -------- savez : Save several arrays into a ``.npz`` archive savetxt, load Notes ----- For a description of the ``.npy`` format, see `format`. Examples -------- >>> from tempfile import TemporaryFile >>> outfile = TemporaryFile() >>> x = np.arange(10) >>> np.save(outfile, x) >>> outfile.seek(0) # Only needed here to simulate closing & reopening file >>> np.load(outfile) array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) """ own_fid = False if isinstance(file, basestring): if not file.endswith('.npy'): file = file + '.npy' fid = open(file, "wb") own_fid = True else: fid = file try: arr = np.asanyarray(arr) format.write_array(fid, arr) finally: if own_fid: fid.close() def savez(file, *args, **kwds): """ Save several arrays into a single file in uncompressed ``.npz`` format. If arguments are passed in with no keywords, the corresponding variable names, in the .npz file, are 'arr_0', 'arr_1', etc. If keyword arguments are given, the corresponding variable names, in the ``.npz`` file will match the keyword names. Parameters ---------- file : str or file Either the file name (string) or an open file (file-like object) where the data will be saved. If file is a string, the ``.npz`` extension will be appended to the file name if it is not already there. args : Arguments, optional Arrays to save to the file. Since it is not possible for Python to know the names of the arrays outside `savez`, the arrays will be saved with names "arr_0", "arr_1", and so on. These arguments can be any expression. kwds : Keyword arguments, optional Arrays to save to the file. Arrays will be saved in the file with the keyword names. Returns ------- None See Also -------- save : Save a single array to a binary file in NumPy format. savetxt : Save an array to a file as plain text. savez_compressed : Save several arrays into a compressed .npz file format Notes ----- The ``.npz`` file format is a zipped archive of files named after the variables they contain. The archive is not compressed and each file in the archive contains one variable in ``.npy`` format. For a description of the ``.npy`` format, see `format`. When opening the saved ``.npz`` file with `load` a `NpzFile` object is returned. This is a dictionary-like object which can be queried for its list of arrays (with the ``.files`` attribute), and for the arrays themselves. Examples -------- >>> from tempfile import TemporaryFile >>> outfile = TemporaryFile() >>> x = np.arange(10) >>> y = np.sin(x) Using `savez` with \\*args, the arrays are saved with default names. >>> np.savez(outfile, x, y) >>> outfile.seek(0) # Only needed here to simulate closing & reopening file >>> npzfile = np.load(outfile) >>> npzfile.files ['arr_1', 'arr_0'] >>> npzfile['arr_0'] array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) Using `savez` with \\**kwds, the arrays are saved with the keyword names. >>> outfile = TemporaryFile() >>> np.savez(outfile, x=x, y=y) >>> outfile.seek(0) >>> npzfile = np.load(outfile) >>> npzfile.files ['y', 'x'] >>> npzfile['x'] array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) """ _savez(file, args, kwds, False) def savez_compressed(file, *args, **kwds): """ Save several arrays into a single file in compressed ``.npz`` format. If keyword arguments are given, then filenames are taken from the keywords. If arguments are passed in with no keywords, then stored file names are arr_0, arr_1, etc. Parameters ---------- file : str File name of .npz file. args : Arguments Function arguments. kwds : Keyword arguments Keywords. 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) def _savez(file, args, kwds, compress): # Import is postponed to here since zipfile depends on gzip, an optional # component of the so-called standard library. import zipfile # Import deferred for startup time improvement import tempfile if isinstance(file, basestring): if not file.endswith('.npz'): file = file + '.npz' namedict = kwds for i, val in enumerate(args): key = 'arr_%d' % i if key in namedict.keys(): raise ValueError("Cannot use un-named variables and keyword %s" % key) namedict[key] = val if compress: compression = zipfile.ZIP_DEFLATED else: compression = zipfile.ZIP_STORED zip = zipfile_factory(file, mode="w", compression=compression) # Stage arrays in a temporary file on disk, before writing to zip. fd, tmpfile = tempfile.mkstemp(suffix='-numpy.npy') os.close(fd) try: for key, val in namedict.items(): fname = key + '.npy' fid = open(tmpfile, 'wb') try: format.write_array(fid, np.asanyarray(val)) fid.close() fid = None zip.write(tmpfile, arcname=fname) finally: if fid: fid.close() finally: os.remove(tmpfile) zip.close() # Adapted from matplotlib def _getconv(dtype): typ = dtype.type if issubclass(typ, np.bool_): return lambda x: bool(int(x)) if issubclass(typ, np.uint64): return np.uint64 if issubclass(typ, np.int64): return np.int64 if issubclass(typ, np.integer): return lambda x: int(float(x)) elif issubclass(typ, np.floating): return float elif issubclass(typ, np.complex): return complex elif issubclass(typ, np.bytes_): return bytes else: return str def loadtxt(fname, dtype=float, comments='#', delimiter=None, converters=None, skiprows=0, usecols=None, unpack=False, ndmin=0): """ Load data from a text file. Each row in the text file must have the same number of values. Parameters ---------- fname : file or str File, filename, or generator to read. If the filename extension is ``.gz`` or ``.bz2``, the file is first decompressed. Note that generators should return byte strings for Python 3k. dtype : data-type, optional Data-type of the resulting array; default: float. If this is a record data-type, the resulting array will be 1-dimensional, and each row will be interpreted as an element of the array. In this case, the number of columns used must match the number of fields in the data-type. comments : str, optional The character used to indicate the start of a comment; default: '#'. delimiter : str, optional The string used to separate values. By default, this is any whitespace. converters : dict, optional A dictionary mapping column number to a function that will convert that column to a float. E.g., if column 0 is a date string: ``converters = {0: datestr2num}``. Converters can also be used to provide a default value for missing data (but see also `genfromtxt`): ``converters = {3: lambda s: float(s.strip() or 0)}``. Default: None. skiprows : int, optional Skip the first `skiprows` lines; default: 0. usecols : sequence, optional Which columns to read, with 0 being the first. For example, ``usecols = (1,4,5)`` will extract the 2nd, 5th and 6th columns. The default, None, results in all columns being read. unpack : bool, optional If True, the returned array is transposed, so that arguments may be unpacked using ``x, y, z = loadtxt(...)``. When used with a record data-type, arrays are returned for each field. Default is False. ndmin : int, optional 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 ------- out : ndarray Data read from the text file. See Also -------- load, fromstring, fromregex genfromtxt : Load data with missing values handled as specified. scipy.io.loadmat : reads MATLAB data files Notes ----- This function aims to be a fast reader for simply formatted files. The `genfromtxt` function provides more sophisticated handling of, e.g., lines with missing values. Examples -------- >>> from StringIO import StringIO # StringIO behaves like a file object >>> c = StringIO("0 1\\n2 3") >>> np.loadtxt(c) array([[ 0., 1.], [ 2., 3.]]) >>> d = StringIO("M 21 72\\nF 35 58") >>> np.loadtxt(d, dtype={'names': ('gender', 'age', 'weight'), ... 'formats': ('S1', 'i4', 'f4')}) array([('M', 21, 72.0), ('F', 35, 58.0)], dtype=[('gender', '|S1'), ('age', '>> c = StringIO("1,0,2\\n3,0,4") >>> x, y = np.loadtxt(c, delimiter=',', usecols=(0, 2), unpack=True) >>> x array([ 1., 3.]) >>> y array([ 2., 4.]) """ # Type conversions for Py3 convenience comments = asbytes(comments) user_converters = converters if delimiter is not None: delimiter = asbytes(delimiter) if usecols is not None: usecols = list(usecols) fown = False try: if _is_string_like(fname): fown = True if fname.endswith('.gz'): fh = iter(seek_gzip_factory(fname)) elif fname.endswith('.bz2'): import bz2 fh = iter(bz2.BZ2File(fname)) elif sys.version_info[0] == 2: fh = iter(open(fname, 'U')) else: fh = iter(open(fname)) else: fh = iter(fname) except TypeError: raise ValueError('fname must be a string, file handle, or generator') X = [] def flatten_dtype(dt): """Unpack a structured data-type, and produce re-packing info.""" if dt.names is None: # If the dtype is flattened, return. # If the dtype has a shape, the dtype occurs # in the list more than once. shape = dt.shape if len(shape) == 0: return ([dt.base], None) else: packing = [(shape[-1], list)] if len(shape) > 1: for dim in dt.shape[-2::-1]: packing = [(dim*packing[0][0], packing*dim)] return ([dt.base] * int(np.prod(dt.shape)), packing) else: types = [] packing = [] for field in dt.names: tp, bytes = dt.fields[field] flat_dt, flat_packing = flatten_dtype(tp) types.extend(flat_dt) # Avoid extra nesting for subarrays if len(tp.shape) > 0: packing.extend(flat_packing) else: packing.append((len(flat_dt), flat_packing)) return (types, packing) def pack_items(items, packing): """Pack items into nested lists based on re-packing info.""" if packing == None: return items[0] elif packing is tuple: return tuple(items) elif packing is list: return list(items) else: start = 0 ret = [] for length, subpacking in packing: ret.append(pack_items(items[start:start+length], subpacking)) start += length return tuple(ret) def split_line(line): """Chop off comments, strip, and split at delimiter.""" line = asbytes(line).split(comments)[0].strip(asbytes('\r\n')) if line: return line.split(delimiter) else: return [] try: # Make sure we're dealing with a proper dtype dtype = np.dtype(dtype) defconv = _getconv(dtype) # Skip the first `skiprows` lines for i in range(skiprows): next(fh) # Read until we find a line with some values, and use # it to estimate the number of columns, N. first_vals = None try: while not first_vals: first_line = next(fh) first_vals = split_line(first_line) except StopIteration: # End of lines reached first_line = '' first_vals = [] warnings.warn('loadtxt: Empty input file: "%s"' % fname) N = len(usecols or first_vals) dtype_types, packing = flatten_dtype(dtype) if len(dtype_types) > 1: # We're dealing with a structured array, each field of # the dtype matches a column converters = [_getconv(dt) for dt in dtype_types] else: # All fields have the same dtype converters = [defconv for i in range(N)] if N > 1: packing = [(N, tuple)] # By preference, use the converters specified by the user for i, conv in (user_converters or {}).items(): if usecols: try: i = usecols.index(i) except ValueError: # Unused converter specified continue converters[i] = conv # Parse each line, including the first for i, line in enumerate(itertools.chain([first_line], fh)): vals = split_line(line) if len(vals) == 0: continue if usecols: vals = [vals[i] for i in usecols] # 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 items = pack_items(items, packing) X.append(items) finally: if fown: fh.close() X = np.array(X, dtype) # Multicolumn data are returned with shape (1, N, M), i.e. # (1, 1, M) for a single row - remove the singleton dimension there if X.ndim == 3 and X.shape[:2] == (1, 1): X.shape = (1, -1) # Verify that the array has at least dimensions `ndmin`. # Check correctness of the values of `ndmin` if not ndmin in [0, 1, 2]: raise ValueError('Illegal value of ndmin keyword: %s' % ndmin) # Tweak the size and shape of the arrays - remove extraneous dimensions if X.ndim > ndmin: X = np.squeeze(X) # and ensure we have the minimum number of dimensions asked for # - has to be in this order for the odd case ndmin=1, X.squeeze().ndim=0 if X.ndim < ndmin: if ndmin == 1: X = np.atleast_1d(X) elif ndmin == 2: X = np.atleast_2d(X).T if unpack: if len(dtype_types) > 1: # For structured arrays, return an array for each field. return [X[field] for field in dtype.names] else: return X.T else: return X def savetxt(fname, X, fmt='%.18e', delimiter=' ', newline='\n', header='', footer='', comments='# '): """ Save an array to a text file. Parameters ---------- fname : filename or file handle If the filename ends in ``.gz``, the file is automatically saved in compressed gzip format. `loadtxt` understands gzipped files transparently. X : array_like Data to be saved to a text file. fmt : str or sequence of strs, optional A single format (%10.5f), a sequence of formats, or a multi-format string, e.g. 'Iteration %d -- %10.5f', in which case `delimiter` is ignored. For complex `X`, the legal options for `fmt` are: a) a single specifier, `fmt='%.4e'`, resulting in numbers formatted like `' (%s+%sj)' % (fmt, fmt)` b) a full string specifying every real and imaginary part, e.g. `' %.4e %+.4j %.4e %+.4j %.4e %+.4j'` for 3 columns c) a list of specifiers, one per column - in this case, the real and imaginary part must have separate specifiers, e.g. `['%.3e + %.3ej', '(%.15e%+.15ej)']` for 2 columns delimiter : str, optional Character separating columns. newline : str, optional .. 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 -------- save : Save an array to a binary file in NumPy ``.npy`` format savez : Save several arrays into a ``.npz`` compressed archive Notes ----- Further explanation of the `fmt` parameter (``%[flag]width[.precision]specifier``): flags: ``-`` : left justify ``+`` : Forces to preceed result with + or -. ``0`` : Left pad the number with zeros instead of space (see width). width: Minimum number of characters to be printed. The value is not truncated if it has more characters. precision: - For integer specifiers (eg. ``d,i,o,x``), the minimum number of digits. - For ``e, E`` and ``f`` specifiers, the number of digits to print after the decimal point. - For ``g`` and ``G``, the maximum number of significant digits. - For ``s``, the maximum number of characters. specifiers: ``c`` : character ``d`` or ``i`` : signed decimal integer ``e`` or ``E`` : scientific notation with ``e`` or ``E``. ``f`` : decimal floating point ``g,G`` : use the shorter of ``e,E`` or ``f`` ``o`` : signed octal ``s`` : string of characters ``u`` : unsigned decimal integer ``x,X`` : unsigned hexadecimal integer This explanation of ``fmt`` is not complete, for an exhaustive specification see [1]_. References ---------- .. [1] `Format Specification Mini-Language `_, Python Documentation. Examples -------- >>> x = y = z = np.arange(0.0,5.0,1.0) >>> np.savetxt('test.out', x, delimiter=',') # X is an array >>> np.savetxt('test.out', (x,y,z)) # x,y,z equal sized 1D arrays >>> np.savetxt('test.out', x, fmt='%1.4e') # use exponential notation """ # Py3 conversions first if isinstance(fmt, bytes): fmt = asstr(fmt) delimiter = asstr(delimiter) own_fh = False if _is_string_like(fname): own_fh = True if fname.endswith('.gz'): import gzip fh = gzip.open(fname, 'wb') else: if sys.version_info[0] >= 3: fh = open(fname, 'wb') else: fh = open(fname, 'w') elif hasattr(fname, 'write'): fh = fname else: raise ValueError('fname must be a string or file handle') try: X = np.asarray(X) # Handle 1-dimensional arrays if X.ndim == 1: # Common case -- 1d array of numbers if X.dtype.names is None: X = np.atleast_2d(X).T ncol = 1 # Complex dtype -- each field indicates a separate column else: ncol = len(X.dtype.descr) else: ncol = X.shape[1] iscomplex_X = np.iscomplexobj(X) # `fmt` can be a string with multiple insertion points or a # list of formats. E.g. '%10.5f\t%10d' or ('%10.5f', '$10d') if type(fmt) in (list, tuple): if len(fmt) != ncol: raise AttributeError('fmt has wrong shape. %s' % str(fmt)) format = asstr(delimiter).join(map(asstr, fmt)) elif isinstance(fmt, str): n_fmt_chars = fmt.count('%') error = ValueError('fmt has wrong number of %% formats: %s' % fmt) if n_fmt_chars == 1: if iscomplex_X: fmt = [' (%s+%sj)' % (fmt, fmt),] * ncol else: fmt = [fmt, ] * ncol format = delimiter.join(fmt) elif iscomplex_X and n_fmt_chars != (2 * ncol): raise error elif ((not iscomplex_X) and n_fmt_chars != ncol): raise error else: format = fmt else: raise ValueError('invalid fmt: %r' % (fmt,)) if len(header) > 0: header = header.replace('\n', '\n' + comments) fh.write(asbytes(comments + header + newline)) if iscomplex_X: for row in X: row2 = [] for number in row: row2.append(number.real) row2.append(number.imag) fh.write(asbytes(format % tuple(row2) + newline)) else: for row in X: fh.write(asbytes(format % tuple(row) + newline)) if len(footer) > 0: footer = footer.replace('\n', '\n' + comments) fh.write(asbytes(comments + footer + newline)) finally: if own_fh: fh.close() def fromregex(file, regexp, dtype): """ Construct an array from a text file, using regular expression parsing. The returned array is always a structured array, and is constructed from all matches of the regular expression in the file. Groups in the regular expression are converted to fields of the structured array. Parameters ---------- file : str or file File name or file object to read. regexp : str or regexp Regular expression used to parse the file. Groups in the regular expression correspond to fields in the dtype. dtype : dtype or list of dtypes Dtype for the structured array. Returns ------- output : ndarray The output array, containing the part of the content of `file` that was matched by `regexp`. `output` is always a structured array. Raises ------ TypeError When `dtype` is not a valid dtype for a structured array. See Also -------- fromstring, loadtxt Notes ----- Dtypes for structured arrays can be specified in several forms, but all forms specify at least the data type and field name. For details see `doc.structured_arrays`. Examples -------- >>> f = open('test.dat', 'w') >>> f.write("1312 foo\\n1534 bar\\n444 qux") >>> f.close() >>> regexp = r"(\\d+)\\s+(...)" # match [digits, whitespace, anything] >>> output = np.fromregex('test.dat', regexp, ... [('num', np.int64), ('key', 'S3')]) >>> output array([(1312L, 'foo'), (1534L, 'bar'), (444L, 'qux')], dtype=[('num', '>> output['num'] array([1312, 1534, 444], dtype=int64) """ own_fh = False if not hasattr(file, "read"): file = open(file, 'rb') own_fh = True try: if not hasattr(regexp, 'match'): regexp = re.compile(asbytes(regexp)) if not isinstance(dtype, np.dtype): dtype = np.dtype(dtype) seq = regexp.findall(file.read()) if seq and not isinstance(seq[0], tuple): # Only one group is in the regexp. # Create the new array as a single data-type and then # re-interpret as a single-field structured array. newdtype = np.dtype(dtype[dtype.names[0]]) output = np.array(seq, dtype=newdtype) output.dtype = dtype else: output = np.array(seq, dtype=dtype) return output finally: if own_fh: file.close() #####-------------------------------------------------------------------------- #---- --- ASCII functions --- #####-------------------------------------------------------------------------- def genfromtxt(fname, dtype=float, comments='#', delimiter=None, skiprows=0, skip_header=0, skip_footer=0, converters=None, missing='', missing_values=None, filling_values=None, usecols=None, names=None, excludelist=None, deletechars=None, replace_space='_', autostrip=False, case_sensitive=True, defaultfmt="f%i", unpack=None, usemask=False, loose=True, invalid_raise=True): """ Load data from a text file, with missing values handled as specified. Each line past the first `skip_header` lines is split at the `delimiter` character, and characters following the `comments` character are discarded. Parameters ---------- fname : file or str File, filename, or generator to read. If the filename extension is `.gz` or `.bz2`, the file is first decompressed. Note that generators must return byte strings in Python 3k. dtype : dtype, optional Data type of the resulting array. If None, the dtypes will be determined by the contents of each column, individually. comments : str, optional The character used to indicate the start of a comment. All the characters occurring on a line after a comment are discarded delimiter : str, int, or sequence, optional 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_header : int, optional The numbers 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 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_values : variable, optional The set of strings corresponding to missing data. filling_values : variable, optional The set of values to be used as default when the data are missing. usecols : sequence, optional Which columns to read, with 0 being the first. For example, ``usecols = (1, 4, 5)`` will extract the 2nd, 5th and 6th columns. names : {None, True, str, sequence}, optional If `names` is True, the field names are read from the first valid line after the first `skip_header` lines. If `names` is a sequence or a single-string of comma-separated names, the names will be used to define the field names in a structured dtype. If `names` is None, the names of the dtype fields will be used, if any. excludelist : sequence, optional A list of names to exclude. This list is appended to the default list ['return','file','print']. Excluded names are appended an underscore: for example, `file` would become `file_`. deletechars : str, optional A string combining invalid characters that must be deleted from the names. defaultfmt : str, optional A format used to define default field names, such as "f%i" or "f_%02i". autostrip : bool, optional Whether to automatically strip white spaces from the variables. replace_space : char, optional Character(s) used in replacement of white spaces in the variables names. By default, use a '_'. case_sensitive : {True, False, 'upper', 'lower'}, optional If True, field names are case sensitive. If False or 'upper', field names are converted to upper case. If 'lower', field names are converted to lower case. unpack : bool, optional If True, the returned array is transposed, so that arguments may be unpacked using ``x, y, z = loadtxt(...)`` usemask : bool, optional If True, return a masked array. If False, return a regular array. invalid_raise : bool, optional If True, an exception is raised if an inconsistency is detected in the number of columns. If False, a warning is emitted and the offending lines are skipped. Returns ------- out : ndarray Data read from the text file. If `usemask` is True, this is a masked array. See Also -------- numpy.loadtxt : equivalent function when no data is missing. Notes ----- * When spaces are used as delimiters, or when no delimiter has been given as input, there should not be any missing data between two fields. * When the variables are named (either by a flexible dtype or with `names`, there must not be any header in the file (else a ValueError exception is raised). * Individual values are not stripped of spaces by default. When using a custom converter, make sure the function does remove spaces. References ---------- .. [1] Numpy User Guide, section `I/O with Numpy `_. Examples --------- >>> from StringIO import StringIO >>> import numpy as np Comma delimited file with mixed dtype >>> s = StringIO("1,1.3,abcde") >>> data = np.genfromtxt(s, dtype=[('myint','i8'),('myfloat','f8'), ... ('mystring','S5')], delimiter=",") >>> data array((1, 1.3, 'abcde'), dtype=[('myint', '>> s.seek(0) # needed for StringIO example only >>> data = np.genfromtxt(s, dtype=None, ... names = ['myint','myfloat','mystring'], delimiter=",") >>> data array((1, 1.3, 'abcde'), dtype=[('myint', '>> s.seek(0) >>> data = np.genfromtxt(s, dtype="i8,f8,S5", ... names=['myint','myfloat','mystring'], delimiter=",") >>> data array((1, 1.3, 'abcde'), dtype=[('myint', '>> s = StringIO("11.3abcde") >>> data = np.genfromtxt(s, dtype=None, names=['intvar','fltvar','strvar'], ... delimiter=[1,3,5]) >>> data array((1, 1.3, 'abcde'), dtype=[('intvar', ' nbcols): descr = dtype.descr dtype = np.dtype([descr[_] for _ in usecols]) names = list(dtype.names) # If `names` is not None, update the names elif (names is not None) and (len(names) > nbcols): names = [names[_] for _ in usecols] elif (names is not None) and (dtype is not None): names = list(dtype.names) # Process the missing values ............................... # Rename missing_values for convenience user_missing_values = missing_values or () # Define the list of missing_values (one column: one list) missing_values = [list([asbytes('')]) for _ in range(nbcols)] # We have a dictionary: process it field by field if isinstance(user_missing_values, dict): # Loop on the items for (key, val) in user_missing_values.items(): # Is the key a string ? if _is_string_like(key): try: # Transform it into an integer key = names.index(key) except ValueError: # We couldn't find it: the name must have been dropped, then continue # Redefine the key as needed if it's a column number if usecols: try: key = usecols.index(key) except ValueError: pass # Transform the value as a list of string if isinstance(val, (list, tuple)): val = [str(_) for _ in val] else: val = [str(val), ] # Add the value(s) to the current list of missing if key is None: # None acts as default for miss in missing_values: miss.extend(val) else: missing_values[key].extend(val) # We have a sequence : each item matches a column elif isinstance(user_missing_values, (list, tuple)): for (value, entry) in zip(user_missing_values, missing_values): value = str(value) if value not in entry: entry.append(value) # We have a string : apply it to all entries elif isinstance(user_missing_values, bytes): user_value = user_missing_values.split(asbytes(",")) for entry in missing_values: entry.extend(user_value) # We have something else: apply it to all entries else: for entry in missing_values: entry.extend([str(user_missing_values)]) # Process the deprecated `missing` if missing != asbytes(''): warnings.warn(\ "The use of `missing` is deprecated, it will be removed in Numpy 2.0.\n" \ "Please use `missing_values` instead.", DeprecationWarning) values = [str(_) for _ in missing.split(asbytes(","))] for entry in missing_values: entry.extend(values) # Process the filling_values ............................... # Rename the input for convenience user_filling_values = filling_values or [] # Define the default filling_values = [None] * nbcols # We have a dictionary : update each entry individually if isinstance(user_filling_values, dict): for (key, val) in user_filling_values.items(): if _is_string_like(key): try: # Transform it into an integer key = names.index(key) except ValueError: # We couldn't find it: the name must have been dropped, then continue # Redefine the key if it's a column number and usecols is defined if usecols: try: key = usecols.index(key) except ValueError: pass # Add the value to the list filling_values[key] = val # We have a sequence : update on a one-to-one basis elif isinstance(user_filling_values, (list, tuple)): n = len(user_filling_values) if (n <= nbcols): filling_values[:n] = user_filling_values else: filling_values = user_filling_values[:nbcols] # We have something else : use it for all entries else: filling_values = [user_filling_values] * nbcols # Initialize the converters ................................ if dtype is None: # Note: we can't use a [...]*nbcols, as we would have 3 times the same # ... converter, instead of 3 different converters. converters = [StringConverter(None, missing_values=miss, default=fill) for (miss, fill) in zip(missing_values, filling_values)] else: dtype_flat = flatten_dtype(dtype, flatten_base=True) # Initialize the converters if len(dtype_flat) > 1: # Flexible type : get a converter from each dtype zipit = zip(dtype_flat, missing_values, filling_values) converters = [StringConverter(dt, locked=True, missing_values=miss, default=fill) for (dt, miss, fill) in zipit] else: # Set to a default converter (but w/ different missing values) zipit = zip(missing_values, filling_values) converters = [StringConverter(dtype, locked=True, missing_values=miss, default=fill) for (miss, fill) in zipit] # Update the converters to use the user-defined ones uc_update = [] for (i, conv) in user_converters.items(): # If the converter is specified by column names, use the index instead if _is_string_like(i): try: i = names.index(i) except ValueError: continue elif usecols: try: i = usecols.index(i) except ValueError: # Unused converter specified continue # Find the value to test: if len(first_line): testing_value = first_values[i] else: testing_value = None converters[i].update(conv, locked=True, testing_value=testing_value, default=filling_values[i], missing_values=missing_values[i],) uc_update.append((i, conv)) # Make sure we have the corrected keys in user_converters... user_converters.update(uc_update) miss_chars = [_.missing_values for _ in converters] # Initialize the output lists ... # ... rows rows = [] append_to_rows = rows.append # ... masks if usemask: masks = [] append_to_masks = masks.append # ... invalid invalid = [] append_to_invalid = invalid.append # Parse each line for (i, line) in enumerate(itertools.chain([first_line, ], fhd)): values = split_line(line) nbvalues = len(values) # Skip an empty line if nbvalues == 0: continue # Select only the columns we need if usecols: try: values = [values[_] for _ in usecols] except IndexError: append_to_invalid((i + skip_header + 1, nbvalues)) continue elif nbvalues != nbcols: append_to_invalid((i + skip_header + 1, nbvalues)) continue # Store the values append_to_rows(tuple(values)) if usemask: append_to_masks(tuple([v.strip() in m for (v, m) in zip(values, missing_values)])) if own_fhd: fhd.close() # Upgrade the converters (if needed) if dtype is None: for (i, converter) in enumerate(converters): current_column = [itemgetter(i)(_m) for _m in rows] try: converter.iterupgrade(current_column) except ConverterLockError: errmsg = "Converter #%i is locked and cannot be upgraded: " % i current_column = map(itemgetter(i), rows) for (j, value) in enumerate(current_column): try: converter.upgrade(value) except (ConverterError, ValueError): errmsg += "(occurred line #%i for value '%s')" errmsg %= (j + 1 + skip_header, value) raise ConverterError(errmsg) # Check that we don't have invalid values nbinvalid = len(invalid) if nbinvalid > 0: nbrows = len(rows) + nbinvalid - skip_footer # Construct the error message template = " Line #%%i (got %%i columns instead of %i)" % nbcols if skip_footer > 0: nbinvalid_skipped = len([_ for _ in invalid if _[0] > nbrows + skip_header]) invalid = invalid[:nbinvalid - nbinvalid_skipped] skip_footer -= nbinvalid_skipped # # nbrows -= skip_footer # errmsg = [template % (i, nb) # for (i, nb) in invalid if i < nbrows] # else: errmsg = [template % (i, nb) for (i, nb) in invalid] if len(errmsg): errmsg.insert(0, "Some errors were detected !") errmsg = "\n".join(errmsg) # Raise an exception ? if invalid_raise: raise ValueError(errmsg) # Issue a warning ? else: warnings.warn(errmsg, ConversionWarning) # Strip the last skip_footer data if skip_footer > 0: rows = rows[:-skip_footer] if usemask: masks = masks[:-skip_footer] # Convert each value according to the converter: # We want to modify the list in place to avoid creating a new one... # # if loose: # conversionfuncs = [conv._loose_call for conv in converters] # else: # conversionfuncs = [conv._strict_call for conv in converters] # for (i, vals) in enumerate(rows): # rows[i] = tuple([convert(val) # for (convert, val) in zip(conversionfuncs, vals)]) if loose: rows = list(zip(*[[converter._loose_call(_r) for _r in map(itemgetter(i), rows)] for (i, converter) in enumerate(converters)])) else: rows = list(zip(*[[converter._strict_call(_r) for _r in map(itemgetter(i), rows)] for (i, converter) in enumerate(converters)])) # Reset the dtype data = rows if dtype is None: # Get the dtypes from the types of the converters column_types = [conv.type for conv in converters] # Find the columns with strings... strcolidx = [i for (i, v) in enumerate(column_types) if v in (type('S'), np.string_)] # ... and take the largest number of chars. for i in strcolidx: column_types[i] = "|S%i" % max(len(row[i]) for row in data) # if names is None: # If the dtype is uniform, don't define names, else use '' base = set([c.type for c in converters if c._checked]) if len(base) == 1: (ddtype, mdtype) = (list(base)[0], np.bool) else: ddtype = [(defaultfmt % i, dt) for (i, dt) in enumerate(column_types)] if usemask: mdtype = [(defaultfmt % i, np.bool) for (i, dt) in enumerate(column_types)] else: ddtype = list(zip(names, column_types)) mdtype = list(zip(names, [np.bool] * len(column_types))) output = np.array(data, dtype=ddtype) if usemask: outputmask = np.array(masks, dtype=mdtype) else: # Overwrite the initial dtype names if needed if names and dtype.names: dtype.names = names # Case 1. We have a structured type if len(dtype_flat) > 1: # Nested dtype, eg [('a', int), ('b', [('b0', int), ('b1', 'f4')])] # First, create the array using a flattened dtype: # [('a', int), ('b1', int), ('b2', float)] # Then, view the array using the specified dtype. if 'O' in (_.char for _ in dtype_flat): if has_nested_fields(dtype): errmsg = "Nested fields involving objects "\ "are not supported..." raise NotImplementedError(errmsg) else: output = np.array(data, dtype=dtype) else: rows = np.array(data, dtype=[('', _) for _ in dtype_flat]) output = rows.view(dtype) # Now, process the rowmasks the same way if usemask: rowmasks = np.array(masks, dtype=np.dtype([('', np.bool) for t in dtype_flat])) # Construct the new dtype mdtype = make_mask_descr(dtype) outputmask = rowmasks.view(mdtype) # Case #2. We have a basic dtype else: # We used some user-defined converters if user_converters: ishomogeneous = True descr = [] for (i, ttype) in enumerate([conv.type for conv in converters]): # Keep the dtype of the current converter if i in user_converters: ishomogeneous &= (ttype == dtype.type) if ttype == np.string_: ttype = "|S%i" % max(len(row[i]) for row in data) descr.append(('', ttype)) else: descr.append(('', dtype)) # So we changed the dtype ? if not ishomogeneous: # We have more than one field if len(descr) > 1: dtype = np.dtype(descr) # We have only one field: drop the name if not needed. else: dtype = np.dtype(ttype) # output = np.array(data, dtype) if usemask: if dtype.names: mdtype = [(_, np.bool) for _ in dtype.names] else: mdtype = np.bool outputmask = np.array(masks, dtype=mdtype) # Try to take care of the missing data we missed names = output.dtype.names if usemask and names: for (name, conv) in zip(names or (), converters): missing_values = [conv(_) for _ in conv.missing_values if _ != asbytes('')] for mval in missing_values: outputmask[name] |= (output[name] == mval) # Construct the final array if usemask: output = output.view(MaskedArray) output._mask = outputmask if unpack: return output.squeeze().T return output.squeeze() def ndfromtxt(fname, **kwargs): """ Load ASCII data stored in a file and return it as a single array. Parameters ---------- fname, kwargs : For a description of input parameters, see `genfromtxt`. See Also -------- numpy.genfromtxt : generic function. """ kwargs['usemask'] = False return genfromtxt(fname, **kwargs) def mafromtxt(fname, **kwargs): """ Load ASCII data stored in a text file and return a masked array. Parameters ---------- fname, kwargs : For a description of input parameters, see `genfromtxt`. See Also -------- numpy.genfromtxt : generic function to load ASCII data. """ kwargs['usemask'] = True return genfromtxt(fname, **kwargs) def recfromtxt(fname, **kwargs): """ Load ASCII data from a file and return it in a record array. If ``usemask=False`` a standard `recarray` is returned, if ``usemask=True`` a MaskedRecords array is returned. Parameters ---------- fname, kwargs : For a description of input parameters, see `genfromtxt`. See Also -------- numpy.genfromtxt : generic function Notes ----- By default, `dtype` is None, which means that the data-type of the output array will be determined from the data. """ kwargs.update(dtype=kwargs.get('dtype', None)) usemask = kwargs.get('usemask', False) output = genfromtxt(fname, **kwargs) if usemask: from numpy.ma.mrecords import MaskedRecords output = output.view(MaskedRecords) else: output = output.view(np.recarray) return output def recfromcsv(fname, **kwargs): """ Load ASCII data stored in a comma-separated file. The returned array is a record array (if ``usemask=False``, see `recarray`) or a masked record array (if ``usemask=True``, see `ma.mrecords.MaskedRecords`). Parameters ---------- fname, kwargs : For a description of input parameters, see `genfromtxt`. See Also -------- numpy.genfromtxt : generic function to load ASCII 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) output = genfromtxt(fname, **kwargs) if usemask: from numpy.ma.mrecords import MaskedRecords output = output.view(MaskedRecords) else: output = output.view(np.recarray) return output numpy-1.8.2/numpy/lib/shape_base.py0000664000175100017510000005742512370216243020423 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function __all__ = ['column_stack', 'row_stack', 'dstack', 'array_split', 'split', 'hsplit', 'vsplit', 'dsplit', 'apply_over_axes', 'expand_dims', 'apply_along_axis', 'kron', 'tile', 'get_array_wrap'] import numpy.core.numeric as _nx from numpy.core.numeric import asarray, zeros, newaxis, outer, \ concatenate, isscalar, array, asanyarray from numpy.core.fromnumeric import product, reshape from numpy.core import hstack, vstack, atleast_3d def apply_along_axis(func1d,axis,arr,*args): """ Apply a function to 1-D slices along the given axis. Execute `func1d(a, *args)` where `func1d` operates on 1-D arrays and `a` is a 1-D slice of `arr` along `axis`. Parameters ---------- func1d : function This function should accept 1-D arrays. It is applied to 1-D slices of `arr` along the specified axis. axis : integer Axis along which `arr` is sliced. arr : ndarray Input array. args : any Additional arguments to `func1d`. Returns ------- apply_along_axis : ndarray The output array. The shape of `outarr` is identical to the shape of `arr`, except along the `axis` dimension, where the length of `outarr` is equal to the size of the return value of `func1d`. If `func1d` returns a scalar `outarr` will have one fewer dimensions than `arr`. See Also -------- apply_over_axes : Apply a function repeatedly over multiple axes. Examples -------- >>> def my_func(a): ... \"\"\"Average first and last element of a 1-D array\"\"\" ... return (a[0] + a[-1]) * 0.5 >>> b = np.array([[1,2,3], [4,5,6], [7,8,9]]) >>> np.apply_along_axis(my_func, 0, b) array([ 4., 5., 6.]) >>> np.apply_along_axis(my_func, 1, b) array([ 2., 5., 8.]) For a function that doesn't return a scalar, the number of dimensions in `outarr` is the same as `arr`. >>> b = np.array([[8,1,7], [4,3,9], [5,2,6]]) >>> np.apply_along_axis(sorted, 1, b) array([[1, 7, 8], [3, 4, 9], [2, 5, 6]]) """ arr = asarray(arr) nd = arr.ndim if axis < 0: axis += nd if (axis >= nd): raise ValueError("axis must be less than arr.ndim; axis=%d, rank=%d." % (axis, nd)) ind = [0]*(nd-1) i = zeros(nd, 'O') indlist = list(range(nd)) indlist.remove(axis) i[axis] = slice(None, None) outshape = asarray(arr.shape).take(indlist) i.put(indlist, ind) res = func1d(arr[tuple(i.tolist())],*args) # if res is a number, then we have a smaller output array if isscalar(res): outarr = zeros(outshape, asarray(res).dtype) outarr[tuple(ind)] = res Ntot = product(outshape) k = 1 while k < Ntot: # increment the index ind[-1] += 1 n = -1 while (ind[n] >= outshape[n]) and (n > (1-nd)): ind[n-1] += 1 ind[n] = 0 n -= 1 i.put(indlist, ind) res = func1d(arr[tuple(i.tolist())],*args) outarr[tuple(ind)] = res k += 1 return outarr else: Ntot = product(outshape) holdshape = outshape outshape = list(arr.shape) outshape[axis] = len(res) outarr = zeros(outshape, asarray(res).dtype) outarr[tuple(i.tolist())] = res k = 1 while k < Ntot: # increment the index ind[-1] += 1 n = -1 while (ind[n] >= holdshape[n]) and (n > (1-nd)): ind[n-1] += 1 ind[n] = 0 n -= 1 i.put(indlist, ind) res = func1d(arr[tuple(i.tolist())],*args) outarr[tuple(i.tolist())] = res k += 1 return outarr def apply_over_axes(func, a, axes): """ Apply a function repeatedly over multiple axes. `func` is called as `res = func(a, axis)`, where `axis` is the first element of `axes`. The result `res` of the function call must have either the same dimensions as `a` or one less dimension. If `res` has one less dimension than `a`, a dimension is inserted before `axis`. The call to `func` is then repeated for each axis in `axes`, with `res` as the first argument. Parameters ---------- func : function This function must take two arguments, `func(a, axis)`. a : array_like Input array. axes : array_like Axes over which `func` is applied; the elements must be integers. Returns ------- apply_over_axis : ndarray The output array. The number of dimensions is the same as `a`, but the shape can be different. This depends on whether `func` changes the shape of its output with respect to its input. See Also -------- apply_along_axis : Apply a function to 1-D slices of an array along the given axis. Examples -------- >>> a = np.arange(24).reshape(2,3,4) >>> a array([[[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]], [[12, 13, 14, 15], [16, 17, 18, 19], [20, 21, 22, 23]]]) Sum over axes 0 and 2. The result has same number of dimensions as the original array: >>> np.apply_over_axes(np.sum, a, [0,2]) array([[[ 60], [ 92], [124]]]) """ 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 = func(*args) if res.ndim == val.ndim: val = res else: res = expand_dims(res, axis) if res.ndim == val.ndim: val = res else: raise ValueError("function is not returning " "an array of the correct shape") return val def expand_dims(a, axis): """ Expand the shape of an array. Insert a new axis, corresponding to a given position in the array shape. Parameters ---------- a : array_like Input array. axis : int Position (amongst axes) where new axis is to be inserted. Returns ------- res : ndarray Output array. The number of dimensions is one greater than that of the input array. See Also -------- doc.indexing, atleast_1d, atleast_2d, atleast_3d Examples -------- >>> x = np.array([1,2]) >>> x.shape (2,) The following is equivalent to ``x[np.newaxis,:]`` or ``x[np.newaxis]``: >>> y = np.expand_dims(x, axis=0) >>> y array([[1, 2]]) >>> y.shape (1, 2) >>> y = np.expand_dims(x, axis=1) # Equivalent to x[:,newaxis] >>> y array([[1], [2]]) >>> y.shape (2, 1) Note that some examples may use ``None`` instead of ``np.newaxis``. These are the same objects: >>> np.newaxis is None True """ a = asarray(a) shape = a.shape if axis < 0: axis = axis + len(shape) + 1 return a.reshape(shape[:axis] + (1,) + shape[axis:]) row_stack = vstack def column_stack(tup): """ Stack 1-D arrays as columns into a 2-D array. Take a sequence of 1-D arrays and stack them as columns to make a single 2-D array. 2-D arrays are stacked as-is, just like with `hstack`. 1-D arrays are turned into 2-D columns first. Parameters ---------- tup : sequence of 1-D or 2-D arrays. Arrays to stack. All of them must have the same first dimension. Returns ------- stacked : 2-D array The array formed by stacking the given arrays. See Also -------- hstack, vstack, concatenate Notes ----- This function is equivalent to ``np.vstack(tup).T``. Examples -------- >>> a = np.array((1,2,3)) >>> b = np.array((2,3,4)) >>> np.column_stack((a,b)) array([[1, 2], [2, 3], [3, 4]]) """ arrays = [] for v in tup: arr = array(v, copy=False, subok=True) if arr.ndim < 2: arr = array(arr, copy=False, subok=True, ndmin=2).T arrays.append(arr) return _nx.concatenate(arrays, 1) def dstack(tup): """ Stack arrays in sequence depth wise (along third axis). Takes a sequence of arrays and stack them along the third axis to make a single array. Rebuilds arrays divided by `dsplit`. This is a simple way to stack 2D arrays (images) into a single 3D array for processing. Parameters ---------- tup : sequence of arrays Arrays to stack. All of them must have the same shape along all but the third axis. Returns ------- stacked : ndarray The array formed by stacking the given arrays. See Also -------- vstack : Stack along first axis. hstack : Stack along second axis. concatenate : Join arrays. dsplit : Split array along third axis. Notes ----- Equivalent to ``np.concatenate(tup, axis=2)``. Examples -------- >>> a = np.array((1,2,3)) >>> b = np.array((2,3,4)) >>> np.dstack((a,b)) array([[[1, 2], [2, 3], [3, 4]]]) >>> a = np.array([[1],[2],[3]]) >>> b = np.array([[2],[3],[4]]) >>> np.dstack((a,b)) array([[[1, 2]], [[2, 3]], [[3, 4]]]) """ return _nx.concatenate([atleast_3d(_m) for _m in tup], 2) def _replace_zero_by_x_arrays(sub_arys): for i in range(len(sub_arys)): if len(_nx.shape(sub_arys[i])) == 0: sub_arys[i] = _nx.array([]) elif _nx.sometrue(_nx.equal(_nx.shape(sub_arys[i]), 0)): sub_arys[i] = _nx.array([]) return sub_arys def array_split(ary,indices_or_sections,axis = 0): """ Split an array into multiple sub-arrays. Please refer to the ``split`` documentation. The only difference between these functions is that ``array_split`` allows `indices_or_sections` to be an integer that does *not* equally divide the axis. See Also -------- split : Split array into multiple sub-arrays of equal size. Examples -------- >>> x = np.arange(8.0) >>> np.array_split(x, 3) [array([ 0., 1., 2.]), array([ 3., 4., 5.]), array([ 6., 7.])] """ try: Ntotal = ary.shape[axis] except AttributeError: Ntotal = len(ary) try: # handle scalar case. Nsections = len(indices_or_sections) + 1 div_points = [0] + list(indices_or_sections) + [Ntotal] except TypeError: #indices_or_sections is a scalar, not an array. Nsections = int(indices_or_sections) if Nsections <= 0: raise ValueError('number sections must be larger than 0.') Neach_section, extras = divmod(Ntotal, Nsections) section_sizes = [0] + \ extras * [Neach_section+1] + \ (Nsections-extras) * [Neach_section] div_points = _nx.array(section_sizes).cumsum() sub_arys = [] sary = _nx.swapaxes(ary, axis, 0) for i in range(Nsections): st = div_points[i]; end = div_points[i+1] sub_arys.append(_nx.swapaxes(sary[st:end], axis, 0)) # there is a weird issue with array slicing that allows # 0x10 arrays and other such things. The following kludge is needed # to get around this issue. sub_arys = _replace_zero_by_x_arrays(sub_arys) # end kludge. return sub_arys def split(ary,indices_or_sections,axis=0): """ Split an array into multiple sub-arrays. Parameters ---------- ary : ndarray Array to be divided into sub-arrays. indices_or_sections : int or 1-D array If `indices_or_sections` is an integer, N, the array will be divided into N equal arrays along `axis`. If such a split is not possible, an error is raised. If `indices_or_sections` is a 1-D array of sorted integers, the entries indicate where along `axis` the array is split. For example, ``[2, 3]`` would, for ``axis=0``, result in - ary[:2] - ary[2:3] - ary[3:] If an index exceeds the dimension of the array along `axis`, an empty sub-array is returned correspondingly. axis : int, optional The axis along which to split, default is 0. Returns ------- sub-arrays : list of ndarrays A list of sub-arrays. Raises ------ ValueError If `indices_or_sections` is given as an integer, but a split does not result in equal division. See Also -------- array_split : Split an array into multiple sub-arrays of equal or near-equal size. Does not raise an exception if an equal division cannot be made. hsplit : Split array into multiple sub-arrays horizontally (column-wise). vsplit : Split array into multiple sub-arrays vertically (row wise). dsplit : Split array into multiple sub-arrays along the 3rd axis (depth). concatenate : Join arrays together. hstack : Stack arrays in sequence horizontally (column wise). vstack : Stack arrays in sequence vertically (row wise). dstack : Stack arrays in sequence depth wise (along third dimension). Examples -------- >>> x = np.arange(9.0) >>> np.split(x, 3) [array([ 0., 1., 2.]), array([ 3., 4., 5.]), array([ 6., 7., 8.])] >>> x = np.arange(8.0) >>> np.split(x, [3, 5, 6, 10]) [array([ 0., 1., 2.]), array([ 3., 4.]), array([ 5.]), array([ 6., 7.]), array([], dtype=float64)] """ try: len(indices_or_sections) except TypeError: sections = indices_or_sections N = ary.shape[axis] if N % sections: raise ValueError('array split does not result in an equal division') res = array_split(ary, indices_or_sections, axis) return res def hsplit(ary, indices_or_sections): """ Split an array into multiple sub-arrays horizontally (column-wise). Please refer to the `split` documentation. `hsplit` is equivalent to `split` with ``axis=1``, the array is always split along the second axis regardless of the array dimension. See Also -------- split : Split an array into multiple sub-arrays of equal size. Examples -------- >>> x = np.arange(16.0).reshape(4, 4) >>> x array([[ 0., 1., 2., 3.], [ 4., 5., 6., 7.], [ 8., 9., 10., 11.], [ 12., 13., 14., 15.]]) >>> np.hsplit(x, 2) [array([[ 0., 1.], [ 4., 5.], [ 8., 9.], [ 12., 13.]]), array([[ 2., 3.], [ 6., 7.], [ 10., 11.], [ 14., 15.]])] >>> np.hsplit(x, np.array([3, 6])) [array([[ 0., 1., 2.], [ 4., 5., 6.], [ 8., 9., 10.], [ 12., 13., 14.]]), array([[ 3.], [ 7.], [ 11.], [ 15.]]), array([], dtype=float64)] With a higher dimensional array the split is still along the second axis. >>> x = np.arange(8.0).reshape(2, 2, 2) >>> x array([[[ 0., 1.], [ 2., 3.]], [[ 4., 5.], [ 6., 7.]]]) >>> np.hsplit(x, 2) [array([[[ 0., 1.]], [[ 4., 5.]]]), array([[[ 2., 3.]], [[ 6., 7.]]])] """ if len(_nx.shape(ary)) == 0: raise ValueError('hsplit only works on arrays of 1 or more dimensions') if len(ary.shape) > 1: return split(ary, indices_or_sections, 1) else: return split(ary, indices_or_sections, 0) def vsplit(ary, indices_or_sections): """ Split an array into multiple sub-arrays vertically (row-wise). Please refer to the ``split`` documentation. ``vsplit`` is equivalent to ``split`` with `axis=0` (default), the array is always split along the first axis regardless of the array dimension. See Also -------- split : Split an array into multiple sub-arrays of equal size. Examples -------- >>> x = np.arange(16.0).reshape(4, 4) >>> x array([[ 0., 1., 2., 3.], [ 4., 5., 6., 7.], [ 8., 9., 10., 11.], [ 12., 13., 14., 15.]]) >>> np.vsplit(x, 2) [array([[ 0., 1., 2., 3.], [ 4., 5., 6., 7.]]), array([[ 8., 9., 10., 11.], [ 12., 13., 14., 15.]])] >>> np.vsplit(x, np.array([3, 6])) [array([[ 0., 1., 2., 3.], [ 4., 5., 6., 7.], [ 8., 9., 10., 11.]]), array([[ 12., 13., 14., 15.]]), array([], dtype=float64)] With a higher dimensional array the split is still along the first axis. >>> x = np.arange(8.0).reshape(2, 2, 2) >>> x array([[[ 0., 1.], [ 2., 3.]], [[ 4., 5.], [ 6., 7.]]]) >>> np.vsplit(x, 2) [array([[[ 0., 1.], [ 2., 3.]]]), array([[[ 4., 5.], [ 6., 7.]]])] """ if len(_nx.shape(ary)) < 2: raise ValueError('vsplit only works on arrays of 2 or more dimensions') return split(ary, indices_or_sections, 0) def dsplit(ary, indices_or_sections): """ Split array into multiple sub-arrays along the 3rd axis (depth). Please refer to the `split` documentation. `dsplit` is equivalent to `split` with ``axis=2``, the array is always split along the third axis provided the array dimension is greater than or equal to 3. See Also -------- split : Split an array into multiple sub-arrays of equal size. Examples -------- >>> x = np.arange(16.0).reshape(2, 2, 4) >>> x array([[[ 0., 1., 2., 3.], [ 4., 5., 6., 7.]], [[ 8., 9., 10., 11.], [ 12., 13., 14., 15.]]]) >>> np.dsplit(x, 2) [array([[[ 0., 1.], [ 4., 5.]], [[ 8., 9.], [ 12., 13.]]]), array([[[ 2., 3.], [ 6., 7.]], [[ 10., 11.], [ 14., 15.]]])] >>> np.dsplit(x, np.array([3, 6])) [array([[[ 0., 1., 2.], [ 4., 5., 6.]], [[ 8., 9., 10.], [ 12., 13., 14.]]]), array([[[ 3.], [ 7.]], [[ 11.], [ 15.]]]), array([], dtype=float64)] """ if len(_nx.shape(ary)) < 3: raise ValueError('vsplit only works on arrays of 3 or more dimensions') return split(ary, indices_or_sections, 2) def get_array_prepare(*args): """Find the wrapper for the array with the highest priority. In case of ties, leftmost wins. If no wrapper is found, return None """ wrappers = sorted((getattr(x, '__array_priority__', 0), -i, x.__array_prepare__) for i, x in enumerate(args) if hasattr(x, '__array_prepare__')) if wrappers: return wrappers[-1][-1] return None def get_array_wrap(*args): """Find the wrapper for the array with the highest priority. In case of ties, leftmost wins. If no wrapper is found, return None """ wrappers = sorted((getattr(x, '__array_priority__', 0), -i, x.__array_wrap__) for i, x in enumerate(args) if hasattr(x, '__array_wrap__')) if wrappers: return wrappers[-1][-1] return None def kron(a, b): """ Kronecker product of two arrays. Computes the Kronecker product, a composite array made of blocks of the second array scaled by the first. Parameters ---------- a, b : array_like Returns ------- out : ndarray See Also -------- outer : The outer product Notes ----- The function assumes that the number of dimenensions of `a` and `b` are the same, if necessary prepending the smallest with ones. If `a.shape = (r0,r1,..,rN)` and `b.shape = (s0,s1,...,sN)`, the Kronecker product has shape `(r0*s0, r1*s1, ..., rN*SN)`. The elements are products of elements from `a` and `b`, organized explicitly by:: kron(a,b)[k0,k1,...,kN] = a[i0,i1,...,iN] * b[j0,j1,...,jN] where:: kt = it * st + jt, t = 0,...,N In the common 2-D case (N=1), the block structure can be visualized:: [[ a[0,0]*b, a[0,1]*b, ... , a[0,-1]*b ], [ ... ... ], [ a[-1,0]*b, a[-1,1]*b, ... , a[-1,-1]*b ]] Examples -------- >>> np.kron([1,10,100], [5,6,7]) array([ 5, 6, 7, 50, 60, 70, 500, 600, 700]) >>> np.kron([5,6,7], [1,10,100]) array([ 5, 50, 500, 6, 60, 600, 7, 70, 700]) >>> np.kron(np.eye(2), np.ones((2,2))) array([[ 1., 1., 0., 0.], [ 1., 1., 0., 0.], [ 0., 0., 1., 1.], [ 0., 0., 1., 1.]]) >>> a = np.arange(100).reshape((2,5,2,5)) >>> b = np.arange(24).reshape((2,3,4)) >>> c = np.kron(a,b) >>> c.shape (2, 10, 6, 20) >>> I = (1,3,0,2) >>> J = (0,2,1) >>> J1 = (0,) + J # extend to ndim=4 >>> S1 = (1,) + b.shape >>> K = tuple(np.array(I) * np.array(S1) + np.array(J1)) >>> c[K] == a[I]*b[J] True """ b = asanyarray(b) a = array(a, copy=False, subok=True, ndmin=b.ndim) ndb, nda = b.ndim, a.ndim if (nda == 0 or ndb == 0): return _nx.multiply(a, b) as_ = a.shape bs = b.shape if not a.flags.contiguous: a = reshape(a, as_) if not b.flags.contiguous: b = reshape(b, bs) nd = ndb if (ndb != nda): if (ndb > nda): as_ = (1,)*(ndb-nda) + as_ else: bs = (1,)*(nda-ndb) + bs nd = nda result = outer(a, b).reshape(as_+bs) axis = nd-1 for _ in range(nd): result = concatenate(result, axis=axis) wrapper = get_array_prepare(a, b) if wrapper is not None: result = wrapper(result) wrapper = get_array_wrap(a, b) if wrapper is not None: result = wrapper(result) return result def tile(A, reps): """ Construct an array by repeating A the number of times given by reps. If `reps` has length ``d``, the result will have dimension of ``max(d, A.ndim)``. If ``A.ndim < d``, `A` is promoted to be d-dimensional by prepending new axes. So a shape (3,) array is promoted to (1, 3) for 2-D replication, or shape (1, 1, 3) for 3-D replication. If this is not the desired behavior, promote `A` to d-dimensions manually before calling this function. If ``A.ndim > d``, `reps` is promoted to `A`.ndim by pre-pending 1's to it. Thus for an `A` of shape (2, 3, 4, 5), a `reps` of (2, 2) is treated as (1, 1, 2, 2). Parameters ---------- A : array_like The input array. reps : array_like The number of repetitions of `A` along each axis. Returns ------- c : ndarray The tiled output array. See Also -------- repeat : Repeat elements of an array. Examples -------- >>> a = np.array([0, 1, 2]) >>> np.tile(a, 2) array([0, 1, 2, 0, 1, 2]) >>> np.tile(a, (2, 2)) array([[0, 1, 2, 0, 1, 2], [0, 1, 2, 0, 1, 2]]) >>> np.tile(a, (2, 1, 2)) array([[[0, 1, 2, 0, 1, 2]], [[0, 1, 2, 0, 1, 2]]]) >>> b = np.array([[1, 2], [3, 4]]) >>> np.tile(b, 2) array([[1, 2, 1, 2], [3, 4, 3, 4]]) >>> np.tile(b, (2, 1)) array([[1, 2], [3, 4], [1, 2], [3, 4]]) """ try: tup = tuple(reps) except TypeError: tup = (reps,) d = len(tup) c = _nx.array(A, copy=False, subok=True, ndmin=d) shape = list(c.shape) n = max(c.size, 1) if (d < c.ndim): tup = (1,)*(c.ndim-d) + tup for i, nrep in enumerate(tup): if nrep!=1: c = c.reshape(-1, n).repeat(nrep, 0) dim_in = shape[i] dim_out = dim_in*nrep shape[i] = dim_out n //= max(dim_in, 1) return c.reshape(shape) numpy-1.8.2/numpy/numarray/0000775000175100017510000000000012371375430017037 5ustar vagrantvagrant00000000000000numpy-1.8.2/numpy/numarray/alter_code2.py0000664000175100017510000000305712370216243021574 0ustar vagrantvagrant00000000000000""" This module converts code written for numpy.numarray to work with numpy FIXME: finish this. """ from __future__ import division, absolute_import, print_function __all__ = [] import warnings warnings.warn("numpy.numarray.alter_code2 is not working yet.") import sys import os import glob def makenewfile(name, filestr): fid = file(name, 'w') fid.write(filestr) fid.close() def getandcopy(name): fid = file(name) filestr = fid.read() fid.close() base, ext = os.path.splitext(name) makenewfile(base+'.orig', filestr) return filestr def convertfile(filename): """Convert the filename given from using Numeric to using NumPy Copies the file to filename.orig and then over-writes the file with the updated code """ filestr = getandcopy(filename) filestr = fromstr(filestr) makenewfile(filename, filestr) def fromargs(args): filename = args[1] convertfile(filename) def convertall(direc=os.path.curdir): """Convert all .py files to use NumPy (from Numeric) in the directory given For each file, a backup of .py is made as .py.orig. A new file named .py is then written with the updated code. """ files = glob.glob(os.path.join(direc, '*.py')) for afile in files: convertfile(afile) def _func(arg, dirname, fnames): convertall(dirname) def converttree(direc=os.path.curdir): """Convert all .py files in the tree given """ os.path.walk(direc, _func, None) if __name__ == '__main__': fromargs(sys.argv) numpy-1.8.2/numpy/numarray/matrix.py0000664000175100017510000000034112370216243020706 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function __all__ = ['Matrix'] from numpy import matrix as _matrix def Matrix(data, typecode=None, copy=1, savespace=0): return _matrix(data, typecode, copy=copy) numpy-1.8.2/numpy/numarray/compat.py0000664000175100017510000000024112370216243020664 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function __all__ = ['NewAxis', 'ArrayType'] from numpy import newaxis as NewAxis, ndarray as ArrayType numpy-1.8.2/numpy/numarray/_capi.c0000664000175100017510000027740612370216243020271 0ustar vagrantvagrant00000000000000#include #define NPY_NO_DEPRECATED_API NPY_API_VERSION #define _libnumarray_MODULE #include "include/numpy/libnumarray.h" #include "numpy/npy_3kcompat.h" #include #if (defined(__unix__) || defined(unix)) && !defined(USG) #include #endif #if defined(__GLIBC__) || defined(__APPLE__) || defined(__MINGW32__) || (defined(__FreeBSD__) && (__FreeBSD_version >= 502114)) #include #elif defined(__CYGWIN__) #include "numpy/fenv/fenv.h" #include "numpy/fenv/fenv.c" #endif static PyObject *pCfuncClass; static PyTypeObject CfuncType; static PyObject *pHandleErrorFunc; static int deferred_libnumarray_init(void) { static int initialized=0; if (initialized) return 0; pCfuncClass = (PyObject *) &CfuncType; Py_INCREF(pCfuncClass); pHandleErrorFunc = NA_initModuleGlobal("numpy.numarray.util", "handleError"); if (!pHandleErrorFunc) goto _fail; /* _exit: */ initialized = 1; return 0; _fail: initialized = 0; return -1; } /**********************************************************************/ /* Buffer Utility Functions */ /**********************************************************************/ static PyObject * getBuffer( PyObject *obj) { if (!obj) return PyErr_Format(PyExc_RuntimeError, "NULL object passed to getBuffer()"); if (((PyObject*)obj)->ob_type->tp_as_buffer == NULL) { return PyObject_CallMethod(obj, "__buffer__", NULL); } else { Py_INCREF(obj); /* Since CallMethod returns a new object when it succeeds, We'll need to DECREF later to free it. INCREF ordinary buffers here so we don't have to remember where the buffer came from at DECREF time. */ return obj; } } /* Either it defines the buffer API, or it is an instance which returns a buffer when obj.__buffer__() is called */ static int isBuffer (PyObject *obj) { PyObject *buf = getBuffer(obj); int ans = 0; if (buf) { ans = buf->ob_type->tp_as_buffer != NULL; Py_DECREF(buf); } else { PyErr_Clear(); } return ans; } /**********************************************************************/ static int getWriteBufferDataPtr(PyObject *buffobj, void **buff) { #if defined(NPY_PY3K) /* FIXME: XXX - needs implementation */ PyErr_SetString(PyExc_RuntimeError, "XXX: getWriteBufferDataPtr is not implemented"); return -1; #else int rval = -1; PyObject *buff2; if ((buff2 = getBuffer(buffobj))) { if (buff2->ob_type->tp_as_buffer->bf_getwritebuffer) rval = buff2->ob_type->tp_as_buffer->bf_getwritebuffer(buff2, 0, buff); Py_DECREF(buff2); } return rval; #endif } /**********************************************************************/ static int isBufferWriteable (PyObject *buffobj) { void *ptr; int rval = -1; rval = getWriteBufferDataPtr(buffobj, &ptr); if (rval == -1) PyErr_Clear(); /* Since we're just "testing", it's not really an error */ return rval != -1; } /**********************************************************************/ static int getReadBufferDataPtr(PyObject *buffobj, void **buff) { #if defined(NPY_PY3K) /* FIXME: XXX - needs implementation */ PyErr_SetString(PyExc_RuntimeError, "XXX: getWriteBufferDataPtr is not implemented"); return -1; #else int rval = -1; PyObject *buff2; if ((buff2 = getBuffer(buffobj))) { if (buff2->ob_type->tp_as_buffer->bf_getreadbuffer) rval = buff2->ob_type->tp_as_buffer->bf_getreadbuffer(buff2, 0, buff); Py_DECREF(buff2); } return rval; #endif } /**********************************************************************/ static int getBufferSize(PyObject *buffobj) { #if defined(NPY_PY3K) /* FIXME: XXX - needs implementation */ PyErr_SetString(PyExc_RuntimeError, "XXX: getWriteBufferDataPtr is not implemented"); return -1; #else Py_ssize_t size=0; PyObject *buff2; if ((buff2 = getBuffer(buffobj))) { (void) buff2->ob_type->tp_as_buffer->bf_getsegcount(buff2, &size); Py_DECREF(buff2); } else size = -1; return size; #endif } static double numarray_zero = 0.0; static double raiseDivByZero(void) { return 1.0/numarray_zero; } static double raiseNegDivByZero(void) { return -1.0/numarray_zero; } static double num_log(double x) { if (x == 0.0) return raiseNegDivByZero(); else return log(x); } static double num_log10(double x) { if (x == 0.0) return raiseNegDivByZero(); else return log10(x); } static double num_pow(double x, double y) { int z = (int) y; if ((x < 0.0) && (y != z)) return raiseDivByZero(); else return pow(x, y); } /* Inverse hyperbolic trig functions from Numeric */ static double num_acosh(double x) { return log(x + sqrt((x-1.0)*(x+1.0))); } static double num_asinh(double xx) { double x; int sign; if (xx < 0.0) { sign = -1; x = -xx; } else { sign = 1; x = xx; } return sign*log(x + sqrt(x*x+1.0)); } static double num_atanh(double x) { return 0.5*log((1.0+x)/(1.0-x)); } /* NUM_CROUND (in numcomplex.h) also calls num_round */ static double num_round(double x) { return (x >= 0) ? floor(x+0.5) : ceil(x-0.5); } /* The following routine is used in the event of a detected integer * ** divide by zero so that a floating divide by zero is generated. * ** This is done since numarray uses the floating point exception * ** sticky bits to detect errors. The last bit is an attempt to * ** prevent optimization of the divide by zero away, the input value * ** should always be 0 * */ static int int_dividebyzero_error(long NPY_UNUSED(value), long NPY_UNUSED(unused)) { double dummy; dummy = 1./numarray_zero; if (dummy) /* to prevent optimizer from eliminating expression */ return 0; else return 1; } /* Likewise for Integer overflows */ #if defined(__GLIBC__) || defined(__APPLE__) || defined(__CYGWIN__) || defined(__MINGW32__) || (defined(__FreeBSD__) && (__FreeBSD_version >= 502114)) static int int_overflow_error(Float64 value) { /* For x86_64 */ feraiseexcept(FE_OVERFLOW); return (int) value; } #else static int int_overflow_error(Float64 value) { double dummy; dummy = pow(1.e10, fabs(value/2)); if (dummy) /* to prevent optimizer from eliminating expression */ return (int) value; else return 1; } #endif static int umult64_overflow(UInt64 a, UInt64 b) { UInt64 ah, al, bh, bl, w, x, y, z; ah = (a >> 32); al = (a & 0xFFFFFFFFL); bh = (b >> 32); bl = (b & 0xFFFFFFFFL); /* 128-bit product: z*2**64 + (x+y)*2**32 + w */ w = al*bl; x = bh*al; y = ah*bl; z = ah*bh; /* *c = ((x + y)<<32) + w; */ return z || (x>>32) || (y>>32) || (((x & 0xFFFFFFFFL) + (y & 0xFFFFFFFFL) + (w >> 32)) >> 32); } static int smult64_overflow(Int64 a0, Int64 b0) { UInt64 a, b; UInt64 ah, al, bh, bl, w, x, y, z; /* Convert to non-negative quantities */ if (a0 < 0) { a = -a0; } else { a = a0; } if (b0 < 0) { b = -b0; } else { b = b0; } ah = (a >> 32); al = (a & 0xFFFFFFFFL); bh = (b >> 32); bl = (b & 0xFFFFFFFFL); w = al*bl; x = bh*al; y = ah*bl; z = ah*bh; /* UInt64 c = ((x + y)<<32) + w; if ((a0 < 0) ^ (b0 < 0)) *c = -c; else *c = c */ return z || (x>>31) || (y>>31) || (((x & 0xFFFFFFFFL) + (y & 0xFFFFFFFFL) + (w >> 32)) >> 31); } static void NA_Done(void) { return; } static PyArrayObject * NA_NewAll(int ndim, maybelong *shape, NumarrayType type, void *buffer, maybelong byteoffset, maybelong bytestride, int byteorder, int aligned, int writeable) { PyArrayObject *result = NA_NewAllFromBuffer( ndim, shape, type, Py_None, byteoffset, bytestride, byteorder, aligned, writeable); if (result) { if (!NA_NumArrayCheck((PyObject *) result)) { PyErr_Format( PyExc_TypeError, "NA_NewAll: non-NumArray result"); result = NULL; } else { if (buffer) { memcpy(PyArray_DATA(result), buffer, NA_NBYTES(result)); } else { memset(PyArray_DATA(result), 0, NA_NBYTES(result)); } } } return result; } static PyArrayObject * NA_NewAllStrides(int ndim, maybelong *shape, maybelong *strides, NumarrayType type, void *buffer, maybelong byteoffset, int byteorder, int aligned, int writeable) { int i; PyArrayObject *result = NA_NewAll(ndim, shape, type, buffer, byteoffset, 0, byteorder, aligned, writeable); for(i=0; i out.copyFrom(shadow) */ Py_DECREF(shadow); Py_INCREF(Py_None); rval = Py_None; return rval; } } static long NA_getBufferPtrAndSize(PyObject *buffobj, int readonly, void **ptr) { long rval; if (readonly) rval = getReadBufferDataPtr(buffobj, ptr); else rval = getWriteBufferDataPtr(buffobj, ptr); return rval; } static int NA_checkIo(char *name, int wantIn, int wantOut, int gotIn, int gotOut) { if (wantIn != gotIn) { PyErr_Format(_Error, "%s: wrong # of input buffers. Expected %d. Got %d.", name, wantIn, gotIn); return -1; } if (wantOut != gotOut) { PyErr_Format(_Error, "%s: wrong # of output buffers. Expected %d. Got %d.", name, wantOut, gotOut); return -1; } return 0; } static int NA_checkOneCBuffer(char *name, long niter, void *buffer, long bsize, size_t typesize) { Int64 lniter = niter, ltypesize = typesize; if (lniter*ltypesize > bsize) { PyErr_Format(_Error, "%s: access out of buffer. niter=%d typesize=%d bsize=%d", name, (int) niter, (int) typesize, (int) bsize); return -1; } if ((typesize <= sizeof(Float64)) && (((long) buffer) % typesize)) { PyErr_Format(_Error, "%s: buffer not aligned on %d byte boundary.", name, (int) typesize); return -1; } return 0; } static int NA_checkNCBuffers(char *name, int N, long niter, void **buffers, long *bsizes, Int8 *typesizes, Int8 *iters) { int i; for (i=0; i= 0) { /* Skip dimension == 0. */ omax = MAX(omax, tmax); omin = MIN(omin, tmin); if (align && (ABS(stride[i]) % alignsize)) { PyErr_Format(_Error, "%s: stride %d not aligned on %d byte boundary.", name, (int) stride[i], (int) alignsize); return -1; } if (omax + itemsize > buffersize) { PyErr_Format(_Error, "%s: access beyond buffer. offset=%d buffersize=%d", name, (int) (omax+itemsize-1), (int) buffersize); return -1; } if (omin < 0) { PyErr_Format(_Error, "%s: access before buffer. offset=%d buffersize=%d", name, (int) omin, (int) buffersize); return -1; } } } return 0; } /* Function to call standard C Ufuncs ** ** The C Ufuncs expect contiguous 1-d data numarray, input and output numarray ** iterate with standard increments of one data element over all numarray. ** (There are some exceptions like arrayrangexxx which use one or more of ** the data numarray as parameter or other sources of information and do not ** iterate over every buffer). ** ** Arguments: ** ** Number of iterations (simple integer value). ** Number of input numarray. ** Number of output numarray. ** Tuple of tuples, one tuple per input/output array. Each of these ** tuples consists of a buffer object and a byte offset to start. ** ** Returns None */ static PyObject * NA_callCUFuncCore(PyObject *self, long niter, long ninargs, long noutargs, PyObject **BufferObj, long *offset) { CfuncObject *me = (CfuncObject *) self; char *buffers[MAXARGS]; long bsizes[MAXARGS]; long i, pnargs = ninargs + noutargs; UFUNC ufuncptr; if (pnargs > MAXARGS) return PyErr_Format(PyExc_RuntimeError, "NA_callCUFuncCore: too many parameters"); if (!PyObject_IsInstance(self, (PyObject *) &CfuncType) || me->descr.type != CFUNC_UFUNC) return PyErr_Format(PyExc_TypeError, "NA_callCUFuncCore: problem with cfunc."); for (i=0; idescr.name, (int) offset[i], (int) i); if ((bsizes[i] = NA_getBufferPtrAndSize(BufferObj[i], readonly, (void *) &buffers[i])) < 0) return PyErr_Format(_Error, "%s: Problem with %s buffer[%d].", me->descr.name, readonly ? "read" : "write", (int) i); buffers[i] += offset[i]; bsizes[i] -= offset[i]; /* "shorten" buffer size by offset. */ } ufuncptr = (UFUNC) me->descr.fptr; /* If it's not a self-checking ufunc, check arg count match, buffer size, and alignment for all buffers */ if (!me->descr.chkself && (NA_checkIo(me->descr.name, me->descr.wantIn, me->descr.wantOut, ninargs, noutargs) || NA_checkNCBuffers(me->descr.name, pnargs, niter, (void **) buffers, bsizes, me->descr.sizes, me->descr.iters))) return NULL; /* Since the parameters are valid, call the C Ufunc */ if (!(*ufuncptr)(niter, ninargs, noutargs, (void **)buffers, bsizes)) { Py_INCREF(Py_None); return Py_None; } else { return NULL; } } static PyObject * callCUFunc(PyObject *self, PyObject *args) { PyObject *DataArgs, *ArgTuple; long pnargs, ninargs, noutargs, niter, i; CfuncObject *me = (CfuncObject *) self; PyObject *BufferObj[MAXARGS]; long offset[MAXARGS]; if (!PyArg_ParseTuple(args, "lllO", &niter, &ninargs, &noutargs, &DataArgs)) return PyErr_Format(_Error, "%s: Problem with argument list", me->descr.name); /* check consistency of stated inputs/outputs and supplied buffers */ pnargs = PyObject_Length(DataArgs); if ((pnargs != (ninargs+noutargs)) || (pnargs > MAXARGS)) return PyErr_Format(_Error, "%s: wrong buffer count for function", me->descr.name); /* Unpack buffers and offsets, get data pointers */ for (i=0; idescr.name); } return NA_callCUFuncCore(self, niter, ninargs, noutargs, BufferObj, offset); } static PyObject * callStrideConvCFunc(PyObject *self, PyObject *args) { PyObject *inbuffObj, *outbuffObj, *shapeObj; PyObject *inbstridesObj, *outbstridesObj; CfuncObject *me = (CfuncObject *) self; int nshape, ninbstrides, noutbstrides; maybelong shape[MAXDIM], inbstrides[MAXDIM], outbstrides[MAXDIM], *outbstrides1 = outbstrides; long inboffset, outboffset, nbytes=0; if (!PyArg_ParseTuple(args, "OOlOOlO|l", &shapeObj, &inbuffObj, &inboffset, &inbstridesObj, &outbuffObj, &outboffset, &outbstridesObj, &nbytes)) { return PyErr_Format(_Error, "%s: Problem with argument list", me->descr.name); } nshape = NA_maybeLongsFromIntTuple(MAXDIM, shape, shapeObj); if (nshape < 0) return NULL; ninbstrides = NA_maybeLongsFromIntTuple(MAXDIM, inbstrides, inbstridesObj); if (ninbstrides < 0) return NULL; noutbstrides= NA_maybeLongsFromIntTuple(MAXDIM, outbstrides, outbstridesObj); if (noutbstrides < 0) return NULL; if (nshape && (nshape != ninbstrides)) { return PyErr_Format(_Error, "%s: Missmatch between input iteration and strides tuples", me->descr.name); } if (nshape && (nshape != noutbstrides)) { if (noutbstrides < 1 || outbstrides[ noutbstrides - 1 ])/* allow 0 for reductions. */ return PyErr_Format(_Error, "%s: Missmatch between output " "iteration and strides tuples", me->descr.name); } return NA_callStrideConvCFuncCore( self, nshape, shape, inbuffObj, inboffset, ninbstrides, inbstrides, outbuffObj, outboffset, noutbstrides, outbstrides1, nbytes); } static int _NA_callStridingHelper(PyObject *aux, long dim, long nnumarray, PyArrayObject *numarray[], char *data[], CFUNC_STRIDED_FUNC f) { int i, j, status=0; dim -= 1; for(i=0; i MAXARRAYS)) return PyErr_Format(_Error, "%s, too many or too few numarray.", me->descr.name); aux = PySequence_GetItem(args, 0); if (!aux) return NULL; for(i=0; idescr.name, i); if (!NA_NDArrayCheck(otemp)) return PyErr_Format(PyExc_TypeError, "%s arg[%d] is not an array.", me->descr.name, i); numarray[i] = (PyArrayObject *) otemp; data[i] = PyArray_DATA(numarray[i]); Py_DECREF(otemp); if (!NA_updateDataPtr(numarray[i])) return NULL; } /* Cast function pointer and perform stride operation */ f = (CFUNC_STRIDED_FUNC) me->descr.fptr; if (_NA_callStridingHelper(aux, PyArray_NDIM(numarray[0]), nnumarray, numarray, data, f)) { return NULL; } else { Py_INCREF(Py_None); return Py_None; } } /* Convert a standard C numeric value to a Python numeric value. ** ** Handles both nonaligned and/or byteswapped C data. ** ** Input arguments are: ** ** Buffer object that contains the C numeric value. ** Offset (in bytes) into the buffer that the data is located at. ** The size of the C numeric data item in bytes. ** Flag indicating if the C data is byteswapped from the processor's ** natural representation. ** ** Returns a Python numeric value. */ static PyObject * NumTypeAsPyValue(PyObject *self, PyObject *args) { PyObject *bufferObj; long offset, itemsize, byteswap, i, buffersize; Py_complex temp; /* to hold copies of largest possible type */ void *buffer; char *tempptr; CFUNCasPyValue funcptr; CfuncObject *me = (CfuncObject *) self; if (!PyArg_ParseTuple(args, "Olll", &bufferObj, &offset, &itemsize, &byteswap)) return PyErr_Format(_Error, "NumTypeAsPyValue: Problem with argument list"); if ((buffersize = NA_getBufferPtrAndSize(bufferObj, 1, &buffer)) < 0) return PyErr_Format(_Error, "NumTypeAsPyValue: Problem with array buffer"); if (offset < 0) return PyErr_Format(_Error, "NumTypeAsPyValue: invalid negative offset: %d", (int) offset); /* Guarantee valid buffer pointer */ if (offset+itemsize > buffersize) return PyErr_Format(_Error, "NumTypeAsPyValue: buffer too small for offset and itemsize."); /* Do byteswapping. Guarantee double alignment by using temp. */ tempptr = (char *) &temp; if (!byteswap) { for (i=0; idescr.fptr; /* Call function to build PyObject. Bad parameters to this function may render call meaningless, but "temp" guarantees that its safe. */ return (*funcptr)((void *)(&temp)); } /* Convert a Python numeric value to a standard C numeric value. ** ** Handles both nonaligned and/or byteswapped C data. ** ** Input arguments are: ** ** The Python numeric value to be converted. ** Buffer object to contain the C numeric value. ** Offset (in bytes) into the buffer that the data is to be copied to. ** The size of the C numeric data item in bytes. ** Flag indicating if the C data is byteswapped from the processor's ** natural representation. ** ** Returns None */ static PyObject * NumTypeFromPyValue(PyObject *self, PyObject *args) { PyObject *bufferObj, *valueObj; long offset, itemsize, byteswap, i, buffersize; Py_complex temp; /* to hold copies of largest possible type */ void *buffer; char *tempptr; CFUNCfromPyValue funcptr; CfuncObject *me = (CfuncObject *) self; if (!PyArg_ParseTuple(args, "OOlll", &valueObj, &bufferObj, &offset, &itemsize, &byteswap)) return PyErr_Format(_Error, "%s: Problem with argument list", me->descr.name); if ((buffersize = NA_getBufferPtrAndSize(bufferObj, 0, &buffer)) < 0) return PyErr_Format(_Error, "%s: Problem with array buffer (read only?)", me->descr.name); funcptr = (CFUNCfromPyValue) me->descr.fptr; /* Convert python object into "temp". Always safe. */ if (!((*funcptr)(valueObj, (void *)( &temp)))) return PyErr_Format(_Error, "%s: Problem converting value", me->descr.name); /* Check buffer offset. */ if (offset < 0) return PyErr_Format(_Error, "%s: invalid negative offset: %d", me->descr.name, (int) offset); if (offset+itemsize > buffersize) return PyErr_Format(_Error, "%s: buffer too small(%d) for offset(%d) and itemsize(%d)", me->descr.name, (int) buffersize, (int) offset, (int) itemsize); /* Copy "temp" to array buffer. */ tempptr = (char *) &temp; if (!byteswap) { for (i=0; idescr.type) { case CFUNC_UFUNC: return callCUFunc(self, argsTuple); break; case CFUNC_STRIDING: return callStrideConvCFunc(self, argsTuple); break; case CFUNC_NSTRIDING: return callStridingCFunc(self, argsTuple); case CFUNC_FROM_PY_VALUE: return NumTypeFromPyValue(self, argsTuple); break; case CFUNC_AS_PY_VALUE: return NumTypeAsPyValue(self, argsTuple); break; default: return PyErr_Format( _Error, "cfunc_call: Can't dispatch cfunc '%s' with type: %d.", me->descr.name, me->descr.type); } } static PyTypeObject CfuncType; static void cfunc_dealloc(PyObject* self) { PyObject_Del(self); } static PyObject * cfunc_repr(PyObject *self) { char buf[256]; CfuncObject *me = (CfuncObject *) self; sprintf(buf, "", me->descr.name, (unsigned long ) me->descr.fptr, me->descr.chkself, me->descr.align, me->descr.wantIn, me->descr.wantOut); return PyUString_FromString(buf); } static PyTypeObject CfuncType = { #if defined(NPY_PY3K) PyVarObject_HEAD_INIT(0,0) #else PyObject_HEAD_INIT(0) 0, /* ob_size */ #endif "Cfunc", sizeof(CfuncObject), 0, cfunc_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_compare */ cfunc_repr, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ cfunc_call, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ 0, /* tp_flags */ 0, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ 0, /* 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 */ 0, /* tp_init */ 0, /* tp_alloc */ 0, /* 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 */ 0, /* tp_version_tag */ }; /* CfuncObjects are created at the c-level only. They ensure that each cfunc is called via the correct python-c-wrapper as defined by its CfuncDescriptor. The wrapper, in turn, does conversions and buffer size and alignment checking. Allowing these to be created at the python level would enable them to be created *wrong* at the python level, and thereby enable python code to *crash* python. */ static PyObject* NA_new_cfunc(CfuncDescriptor *cfd) { CfuncObject* cfunc; /* Should be done once at init. Do now since there is no init. */ ((PyObject*)&CfuncType)->ob_type = &PyType_Type; cfunc = PyObject_New(CfuncObject, &CfuncType); if (!cfunc) { return PyErr_Format(_Error, "NA_new_cfunc: failed creating '%s'", cfd->name); } cfunc->descr = *cfd; return (PyObject*)cfunc; } static int NA_add_cfunc(PyObject *dict, char *keystr, CfuncDescriptor *descr) { PyObject *c = (PyObject *) NA_new_cfunc(descr); if (!c) return -1; return PyDict_SetItemString(dict, keystr, c); } static PyArrayObject* NA_InputArray(PyObject *a, NumarrayType t, int requires) { PyArray_Descr *descr; if (t == tAny) descr = NULL; else descr = PyArray_DescrFromType(t); return (PyArrayObject *) \ PyArray_CheckFromAny(a, descr, 0, 0, requires, NULL); } /* satisfies ensures that 'a' meets a set of requirements and matches the specified type. */ static int satisfies(PyArrayObject *a, int requirements, NumarrayType t) { int type_ok = (PyArray_DESCR(a)->type_num == t) || (t == tAny); if (PyArray_ISCARRAY(a)) return type_ok; if (PyArray_ISBYTESWAPPED(a) && (requirements & NUM_NOTSWAPPED)) return 0; if (!PyArray_ISALIGNED(a) && (requirements & NUM_ALIGNED)) return 0; if (!PyArray_ISCONTIGUOUS(a) && (requirements & NUM_CONTIGUOUS)) return 0; if (!PyArray_ISWRITABLE(a) && (requirements & NUM_WRITABLE)) return 0; if (requirements & NUM_COPY) return 0; return type_ok; } static PyArrayObject * NA_OutputArray(PyObject *a, NumarrayType t, int requires) { PyArray_Descr *dtype; PyArrayObject *ret; if (!PyArray_Check(a)) { PyErr_Format(PyExc_TypeError, "NA_OutputArray: only arrays work for output."); return NULL; } if (PyArray_FailUnlessWriteable((PyArrayObject *)a, "output array") < 0) { return NULL; } if (satisfies((PyArrayObject *)a, requires, t)) { Py_INCREF(a); return (PyArrayObject *)a; } if (t == tAny) { dtype = PyArray_DESCR((PyArrayObject *)a); Py_INCREF(dtype); } else { dtype = PyArray_DescrFromType(t); } ret = (PyArrayObject *)PyArray_Empty(PyArray_NDIM((PyArrayObject *)a), PyArray_DIMS((PyArrayObject *)a), dtype, 0); Py_INCREF(a); if (PyArray_SetUpdateIfCopyBase(ret, a) < 0) { Py_DECREF(ret); return NULL; } return ret; } /* NA_IoArray is a combination of NA_InputArray and NA_OutputArray. Unlike NA_OutputArray, if a temporary is required it is initialized to a copy of the input array. Unlike NA_InputArray, deallocating any resulting temporary array results in a copy from the temporary back to the original. */ static PyArrayObject * NA_IoArray(PyObject *a, NumarrayType t, int requires) { PyArrayObject *shadow = NA_InputArray(a, t, requires | NPY_ARRAY_UPDATEIFCOPY ); if (!shadow) return NULL; /* Guard against non-writable, but otherwise satisfying requires. In this case, shadow == a. */ if (!PyArray_FailUnlessWriteable(shadow, "input/output array")) { PyArray_XDECREF_ERR(shadow); return NULL; } return shadow; } /* NA_OptionalOutputArray works like NA_OutputArray, but handles the case where the output array 'optional' is omitted entirely at the python level, resulting in 'optional'==Py_None. When 'optional' is Py_None, the return value is cloned (but with NumarrayType 't') from 'master', typically an input array with the same shape as the output array. */ static PyArrayObject * NA_OptionalOutputArray(PyObject *optional, NumarrayType t, int requires, PyArrayObject *master) { if ((optional == Py_None) || (optional == NULL)) { PyObject *rval; PyArray_Descr *descr; if (t == tAny) descr=NULL; else descr = PyArray_DescrFromType(t); rval = PyArray_FromArray( master, descr, NUM_C_ARRAY | NUM_COPY | NUM_WRITABLE); return (PyArrayObject *)rval; } else { return NA_OutputArray(optional, t, requires); } } Complex64 NA_get_Complex64(PyArrayObject *a, long offset) { Complex32 v0; Complex64 v; switch(PyArray_DESCR(a)->type_num) { case tComplex32: v0 = NA_GETP(a, Complex32, (NA_PTR(a)+offset)); v.r = v0.r; v.i = v0.i; break; case tComplex64: v = NA_GETP(a, Complex64, (NA_PTR(a)+offset)); break; default: v.r = NA_get_Float64(a, offset); v.i = 0; break; } return v; } void NA_set_Complex64(PyArrayObject *a, long offset, Complex64 v) { Complex32 v0; switch(PyArray_DESCR(a)->type_num) { case tComplex32: v0.r = v.r; v0.i = v.i; NA_SETP(a, Complex32, (NA_PTR(a)+offset), v0); break; case tComplex64: NA_SETP(a, Complex64, (NA_PTR(a)+offset), v); break; default: NA_set_Float64(a, offset, v.r); break; } } Int64 NA_get_Int64(PyArrayObject *a, long offset) { switch(PyArray_DESCR(a)->type_num) { case tBool: return NA_GETP(a, Bool, (NA_PTR(a)+offset)) != 0; case tInt8: return NA_GETP(a, Int8, (NA_PTR(a)+offset)); case tUInt8: return NA_GETP(a, UInt8, (NA_PTR(a)+offset)); case tInt16: return NA_GETP(a, Int16, (NA_PTR(a)+offset)); case tUInt16: return NA_GETP(a, UInt16, (NA_PTR(a)+offset)); case tInt32: return NA_GETP(a, Int32, (NA_PTR(a)+offset)); case tUInt32: return NA_GETP(a, UInt32, (NA_PTR(a)+offset)); case tInt64: return NA_GETP(a, Int64, (NA_PTR(a)+offset)); case tUInt64: return NA_GETP(a, UInt64, (NA_PTR(a)+offset)); case tFloat32: return NA_GETP(a, Float32, (NA_PTR(a)+offset)); case tFloat64: return NA_GETP(a, Float64, (NA_PTR(a)+offset)); case tComplex32: return NA_GETP(a, Float32, (NA_PTR(a)+offset)); case tComplex64: return NA_GETP(a, Float64, (NA_PTR(a)+offset)); default: PyErr_Format( PyExc_TypeError, "Unknown type %d in NA_get_Int64", PyArray_DESCR(a)->type_num); PyErr_Print(); } return 0; /* suppress warning */ } void NA_set_Int64(PyArrayObject *a, long offset, Int64 v) { Bool b; switch(PyArray_DESCR(a)->type_num) { case tBool: b = (v != 0); NA_SETP(a, Bool, (NA_PTR(a)+offset), b); break; case tInt8: NA_SETP(a, Int8, (NA_PTR(a)+offset), v); break; case tUInt8: NA_SETP(a, UInt8, (NA_PTR(a)+offset), v); break; case tInt16: NA_SETP(a, Int16, (NA_PTR(a)+offset), v); break; case tUInt16: NA_SETP(a, UInt16, (NA_PTR(a)+offset), v); break; case tInt32: NA_SETP(a, Int32, (NA_PTR(a)+offset), v); break; case tUInt32: NA_SETP(a, UInt32, (NA_PTR(a)+offset), v); break; case tInt64: NA_SETP(a, Int64, (NA_PTR(a)+offset), v); break; case tUInt64: NA_SETP(a, UInt64, (NA_PTR(a)+offset), v); break; case tFloat32: NA_SETP(a, Float32, (NA_PTR(a)+offset), v); break; case tFloat64: NA_SETP(a, Float64, (NA_PTR(a)+offset), v); break; case tComplex32: NA_SETP(a, Float32, (NA_PTR(a)+offset), v); NA_SETP(a, Float32, (NA_PTR(a)+offset+sizeof(Float32)), 0); break; case tComplex64: NA_SETP(a, Float64, (NA_PTR(a)+offset), v); NA_SETP(a, Float64, (NA_PTR(a)+offset+sizeof(Float64)), 0); break; default: PyErr_Format( PyExc_TypeError, "Unknown type %d in NA_set_Int64", PyArray_DESCR(a)->type_num); PyErr_Print(); } } /* NA_get_offset computes the offset specified by the set of indices. If N > 0, the indices are taken from the outer dimensions of the array. If N < 0, the indices are taken from the inner dimensions of the array. If N == 0, the offset is 0. */ long NA_get_offset(PyArrayObject *a, int N, ...) { int i; long offset = 0; va_list ap; va_start(ap, N); if (N > 0) { /* compute offset of "outer" indices. */ for(i=0; itype_num) { case tBool: return NA_GETP(a, Bool, (NA_PTR(a)+offset)) != 0; case tInt8: return NA_GETP(a, Int8, (NA_PTR(a)+offset)); case tUInt8: return NA_GETP(a, UInt8, (NA_PTR(a)+offset)); case tInt16: return NA_GETP(a, Int16, (NA_PTR(a)+offset)); case tUInt16: return NA_GETP(a, UInt16, (NA_PTR(a)+offset)); case tInt32: return NA_GETP(a, Int32, (NA_PTR(a)+offset)); case tUInt32: return NA_GETP(a, UInt32, (NA_PTR(a)+offset)); case tInt64: return NA_GETP(a, Int64, (NA_PTR(a)+offset)); #if HAS_UINT64 case tUInt64: return NA_GETP(a, UInt64, (NA_PTR(a)+offset)); #endif case tFloat32: return NA_GETP(a, Float32, (NA_PTR(a)+offset)); case tFloat64: return NA_GETP(a, Float64, (NA_PTR(a)+offset)); case tComplex32: /* Since real value is first */ return NA_GETP(a, Float32, (NA_PTR(a)+offset)); case tComplex64: /* Since real value is first */ return NA_GETP(a, Float64, (NA_PTR(a)+offset)); default: PyErr_Format( PyExc_TypeError, "Unknown type %d in NA_get_Float64", PyArray_DESCR(a)->type_num); } return 0; /* suppress warning */ } void NA_set_Float64(PyArrayObject *a, long offset, Float64 v) { Bool b; switch(PyArray_DESCR(a)->type_num) { case tBool: b = (v != 0); NA_SETP(a, Bool, (NA_PTR(a)+offset), b); break; case tInt8: NA_SETP(a, Int8, (NA_PTR(a)+offset), v); break; case tUInt8: NA_SETP(a, UInt8, (NA_PTR(a)+offset), v); break; case tInt16: NA_SETP(a, Int16, (NA_PTR(a)+offset), v); break; case tUInt16: NA_SETP(a, UInt16, (NA_PTR(a)+offset), v); break; case tInt32: NA_SETP(a, Int32, (NA_PTR(a)+offset), v); break; case tUInt32: NA_SETP(a, UInt32, (NA_PTR(a)+offset), v); break; case tInt64: NA_SETP(a, Int64, (NA_PTR(a)+offset), v); break; #if HAS_UINT64 case tUInt64: NA_SETP(a, UInt64, (NA_PTR(a)+offset), v); break; #endif case tFloat32: NA_SETP(a, Float32, (NA_PTR(a)+offset), v); break; case tFloat64: NA_SETP(a, Float64, (NA_PTR(a)+offset), v); break; case tComplex32: { NA_SETP(a, Float32, (NA_PTR(a)+offset), v); NA_SETP(a, Float32, (NA_PTR(a)+offset+sizeof(Float32)), 0); break; } case tComplex64: { NA_SETP(a, Float64, (NA_PTR(a)+offset), v); NA_SETP(a, Float64, (NA_PTR(a)+offset+sizeof(Float64)), 0); break; } default: PyErr_Format( PyExc_TypeError, "Unknown type %d in NA_set_Float64", PyArray_DESCR(a)->type_num ); PyErr_Print(); } } Float64 NA_get1_Float64(PyArrayObject *a, long i) { long offset = i * PyArray_STRIDES(a)[0]; return NA_get_Float64(a, offset); } Float64 NA_get2_Float64(PyArrayObject *a, long i, long j) { long offset = i * PyArray_STRIDES(a)[0] + j * PyArray_STRIDES(a)[1]; return NA_get_Float64(a, offset); } Float64 NA_get3_Float64(PyArrayObject *a, long i, long j, long k) { long offset = i * PyArray_STRIDES(a)[0] + j * PyArray_STRIDES(a)[1] + k * PyArray_STRIDES(a)[2]; return NA_get_Float64(a, offset); } void NA_set1_Float64(PyArrayObject *a, long i, Float64 v) { long offset = i * PyArray_STRIDES(a)[0]; NA_set_Float64(a, offset, v); } void NA_set2_Float64(PyArrayObject *a, long i, long j, Float64 v) { long offset = i * PyArray_STRIDES(a)[0] + j * PyArray_STRIDES(a)[1]; NA_set_Float64(a, offset, v); } void NA_set3_Float64(PyArrayObject *a, long i, long j, long k, Float64 v) { long offset = i * PyArray_STRIDES(a)[0] + j * PyArray_STRIDES(a)[1] + k * PyArray_STRIDES(a)[2]; NA_set_Float64(a, offset, v); } Complex64 NA_get1_Complex64(PyArrayObject *a, long i) { long offset = i * PyArray_STRIDES(a)[0]; return NA_get_Complex64(a, offset); } Complex64 NA_get2_Complex64(PyArrayObject *a, long i, long j) { long offset = i * PyArray_STRIDES(a)[0] + j * PyArray_STRIDES(a)[1]; return NA_get_Complex64(a, offset); } Complex64 NA_get3_Complex64(PyArrayObject *a, long i, long j, long k) { long offset = i * PyArray_STRIDES(a)[0] + j * PyArray_STRIDES(a)[1] + k * PyArray_STRIDES(a)[2]; return NA_get_Complex64(a, offset); } void NA_set1_Complex64(PyArrayObject *a, long i, Complex64 v) { long offset = i * PyArray_STRIDES(a)[0]; NA_set_Complex64(a, offset, v); } void NA_set2_Complex64(PyArrayObject *a, long i, long j, Complex64 v) { long offset = i * PyArray_STRIDES(a)[0] + j * PyArray_STRIDES(a)[1]; NA_set_Complex64(a, offset, v); } void NA_set3_Complex64(PyArrayObject *a, long i, long j, long k, Complex64 v) { long offset = i * PyArray_STRIDES(a)[0] + j * PyArray_STRIDES(a)[1] + k * PyArray_STRIDES(a)[2]; NA_set_Complex64(a, offset, v); } Int64 NA_get1_Int64(PyArrayObject *a, long i) { long offset = i * PyArray_STRIDES(a)[0]; return NA_get_Int64(a, offset); } Int64 NA_get2_Int64(PyArrayObject *a, long i, long j) { long offset = i * PyArray_STRIDES(a)[0] + j * PyArray_STRIDES(a)[1]; return NA_get_Int64(a, offset); } Int64 NA_get3_Int64(PyArrayObject *a, long i, long j, long k) { long offset = i * PyArray_STRIDES(a)[0] + j * PyArray_STRIDES(a)[1] + k * PyArray_STRIDES(a)[2]; return NA_get_Int64(a, offset); } void NA_set1_Int64(PyArrayObject *a, long i, Int64 v) { long offset = i * PyArray_STRIDES(a)[0]; NA_set_Int64(a, offset, v); } void NA_set2_Int64(PyArrayObject *a, long i, long j, Int64 v) { long offset = i * PyArray_STRIDES(a)[0] + j * PyArray_STRIDES(a)[1]; NA_set_Int64(a, offset, v); } void NA_set3_Int64(PyArrayObject *a, long i, long j, long k, Int64 v) { long offset = i * PyArray_STRIDES(a)[0] + j * PyArray_STRIDES(a)[1] + k * PyArray_STRIDES(a)[2]; NA_set_Int64(a, offset, v); } /* SET_CMPLX could be made faster by factoring it into 3 seperate loops. */ #define NA_SET_CMPLX(a, type, base, cnt, in) \ { \ int i; \ int stride = PyArray_STRIDES(a)[ PyArray_NDIM(a) - 1]; \ NA_SET1D(a, type, base, cnt, in); \ base = NA_PTR(a) + offset + sizeof(type); \ for(i=0; itype_num) { case tBool: NA_GET1D(a, Bool, base, cnt, out); break; case tInt8: NA_GET1D(a, Int8, base, cnt, out); break; case tUInt8: NA_GET1D(a, UInt8, base, cnt, out); break; case tInt16: NA_GET1D(a, Int16, base, cnt, out); break; case tUInt16: NA_GET1D(a, UInt16, base, cnt, out); break; case tInt32: NA_GET1D(a, Int32, base, cnt, out); break; case tUInt32: NA_GET1D(a, UInt32, base, cnt, out); break; case tInt64: NA_GET1D(a, Int64, base, cnt, out); break; #if HAS_UINT64 case tUInt64: NA_GET1D(a, UInt64, base, cnt, out); break; #endif case tFloat32: NA_GET1D(a, Float32, base, cnt, out); break; case tFloat64: NA_GET1D(a, Float64, base, cnt, out); break; case tComplex32: NA_GET1D(a, Float32, base, cnt, out); break; case tComplex64: NA_GET1D(a, Float64, base, cnt, out); break; default: PyErr_Format( PyExc_TypeError, "Unknown type %d in NA_get1D_Float64", PyArray_DESCR(a)->type_num); PyErr_Print(); return -1; } return 0; } static Float64 * NA_alloc1D_Float64(PyArrayObject *a, long offset, int cnt) { Float64 *result = PyMem_New(Float64, (size_t)cnt); if (!result) return NULL; if (NA_get1D_Float64(a, offset, cnt, result) < 0) { PyMem_Free(result); return NULL; } return result; } static int NA_set1D_Float64(PyArrayObject *a, long offset, int cnt, Float64*in) { char *base = NA_PTR(a) + offset; switch(PyArray_DESCR(a)->type_num) { case tBool: NA_SET1D(a, Bool, base, cnt, in); break; case tInt8: NA_SET1D(a, Int8, base, cnt, in); break; case tUInt8: NA_SET1D(a, UInt8, base, cnt, in); break; case tInt16: NA_SET1D(a, Int16, base, cnt, in); break; case tUInt16: NA_SET1D(a, UInt16, base, cnt, in); break; case tInt32: NA_SET1D(a, Int32, base, cnt, in); break; case tUInt32: NA_SET1D(a, UInt32, base, cnt, in); break; case tInt64: NA_SET1D(a, Int64, base, cnt, in); break; #if HAS_UINT64 case tUInt64: NA_SET1D(a, UInt64, base, cnt, in); break; #endif case tFloat32: NA_SET1D(a, Float32, base, cnt, in); break; case tFloat64: NA_SET1D(a, Float64, base, cnt, in); break; case tComplex32: NA_SET_CMPLX(a, Float32, base, cnt, in); break; case tComplex64: NA_SET_CMPLX(a, Float64, base, cnt, in); break; default: PyErr_Format( PyExc_TypeError, "Unknown type %d in NA_set1D_Float64", PyArray_DESCR(a)->type_num); PyErr_Print(); return -1; } return 0; } static int NA_get1D_Int64(PyArrayObject *a, long offset, int cnt, Int64*out) { char *base = NA_PTR(a) + offset; switch(PyArray_DESCR(a)->type_num) { case tBool: NA_GET1D(a, Bool, base, cnt, out); break; case tInt8: NA_GET1D(a, Int8, base, cnt, out); break; case tUInt8: NA_GET1D(a, UInt8, base, cnt, out); break; case tInt16: NA_GET1D(a, Int16, base, cnt, out); break; case tUInt16: NA_GET1D(a, UInt16, base, cnt, out); break; case tInt32: NA_GET1D(a, Int32, base, cnt, out); break; case tUInt32: NA_GET1D(a, UInt32, base, cnt, out); break; case tInt64: NA_GET1D(a, Int64, base, cnt, out); break; case tUInt64: NA_GET1D(a, UInt64, base, cnt, out); break; case tFloat32: NA_GET1D(a, Float32, base, cnt, out); break; case tFloat64: NA_GET1D(a, Float64, base, cnt, out); break; case tComplex32: NA_GET1D(a, Float32, base, cnt, out); break; case tComplex64: NA_GET1D(a, Float64, base, cnt, out); break; default: PyErr_Format( PyExc_TypeError, "Unknown type %d in NA_get1D_Int64", PyArray_DESCR(a)->type_num); PyErr_Print(); return -1; } return 0; } static Int64 * NA_alloc1D_Int64(PyArrayObject *a, long offset, int cnt) { Int64 *result = PyMem_New(Int64, (size_t)cnt); if (!result) return NULL; if (NA_get1D_Int64(a, offset, cnt, result) < 0) { PyMem_Free(result); return NULL; } return result; } static int NA_set1D_Int64(PyArrayObject *a, long offset, int cnt, Int64*in) { char *base = NA_PTR(a) + offset; switch(PyArray_DESCR(a)->type_num) { case tBool: NA_SET1D(a, Bool, base, cnt, in); break; case tInt8: NA_SET1D(a, Int8, base, cnt, in); break; case tUInt8: NA_SET1D(a, UInt8, base, cnt, in); break; case tInt16: NA_SET1D(a, Int16, base, cnt, in); break; case tUInt16: NA_SET1D(a, UInt16, base, cnt, in); break; case tInt32: NA_SET1D(a, Int32, base, cnt, in); break; case tUInt32: NA_SET1D(a, UInt32, base, cnt, in); break; case tInt64: NA_SET1D(a, Int64, base, cnt, in); break; case tUInt64: NA_SET1D(a, UInt64, base, cnt, in); break; case tFloat32: NA_SET1D(a, Float32, base, cnt, in); break; case tFloat64: NA_SET1D(a, Float64, base, cnt, in); break; case tComplex32: NA_SET_CMPLX(a, Float32, base, cnt, in); break; case tComplex64: NA_SET_CMPLX(a, Float64, base, cnt, in); break; default: PyErr_Format( PyExc_TypeError, "Unknown type %d in NA_set1D_Int64", PyArray_DESCR(a)->type_num); PyErr_Print(); return -1; } return 0; } static int NA_get1D_Complex64(PyArrayObject *a, long offset, int cnt, Complex64*out) { char *base = NA_PTR(a) + offset; switch(PyArray_DESCR(a)->type_num) { case tComplex64: NA_GET1D(a, Complex64, base, cnt, out); break; default: PyErr_Format( PyExc_TypeError, "Unsupported type %d in NA_get1D_Complex64", PyArray_DESCR(a)->type_num); PyErr_Print(); return -1; } return 0; } static int NA_set1D_Complex64(PyArrayObject *a, long offset, int cnt, Complex64*in) { char *base = NA_PTR(a) + offset; switch(PyArray_DESCR(a)->type_num) { case tComplex64: NA_SET1D(a, Complex64, base, cnt, in); break; default: PyErr_Format( PyExc_TypeError, "Unsupported type %d in NA_set1D_Complex64", PyArray_DESCR(a)->type_num); PyErr_Print(); return -1; } return 0; } /* NA_ShapeEqual returns 1 if 'a' and 'b' have the same shape, 0 otherwise. */ static int NA_ShapeEqual(PyArrayObject *a, PyArrayObject *b) { int i; if (!NA_NDArrayCheck((PyObject *) a) || !NA_NDArrayCheck((PyObject*) b)) { PyErr_Format( PyExc_TypeError, "NA_ShapeEqual: non-array as parameter."); return -1; } if (PyArray_NDIM(a) != PyArray_NDIM(b)) return 0; for(i=0; i= PyArray_DIMS(b)[i+boff]) return 0; return 1; } static int NA_ByteOrder(void) { unsigned long byteorder_test; byteorder_test = 1; if (*((char *) &byteorder_test)) return NUM_LITTLE_ENDIAN; else return NUM_BIG_ENDIAN; } static Bool NA_IeeeSpecial32( Float32 *f, Int32 *mask) { return NA_IeeeMask32(*f, *mask); } static Bool NA_IeeeSpecial64( Float64 *f, Int32 *mask) { return NA_IeeeMask64(*f, *mask); } static PyArrayObject * NA_updateDataPtr(PyArrayObject *me) { return me; } #define ELEM(x) (sizeof(x)/sizeof(x[0])) typedef struct { char *name; int typeno; } NumarrayTypeNameMapping; static NumarrayTypeNameMapping NumarrayTypeNameMap[] = { {"Any", tAny}, {"Bool", tBool}, {"Int8", tInt8}, {"UInt8", tUInt8}, {"Int16", tInt16}, {"UInt16", tUInt16}, {"Int32", tInt32}, {"UInt32", tUInt32}, {"Int64", tInt64}, {"UInt64", tUInt64}, {"Float32", tFloat32}, {"Float64", tFloat64}, {"Complex32", tComplex32}, {"Complex64", tComplex64}, {"Object", tObject}, {"Long", tLong}, }; /* Convert NumarrayType 'typeno' into the string of the type's name. */ static char * NA_typeNoToName(int typeno) { size_t i; PyObject *typeObj; int typeno2; for(i=0; i PyArray_NDIM(a)) { PyErr_Format(PyExc_ValueError, "setArrayFromSequence: sequence/array dimensions mismatch."); return -1; } if (slen != PyArray_DIMS(a)[dim]) { PyErr_Format(PyExc_ValueError, "setArrayFromSequence: sequence/array shape mismatch."); return -1; } for(i=0; i MAXDIM) { PyErr_Format( PyExc_ValueError, "NA_maxType: sequence nested too deep." ); return -1; } if (NA_NumArrayCheck(seq)) { switch(PyArray_DESCR(PyArray(seq))->type_num) { case tBool: return BOOL_SCALAR; case tInt8: case tUInt8: case tInt16: case tUInt16: case tInt32: case tUInt32: return INT_SCALAR; case tInt64: case tUInt64: return LONG_SCALAR; case tFloat32: case tFloat64: return FLOAT_SCALAR; case tComplex32: case tComplex64: return COMPLEX_SCALAR; default: PyErr_Format(PyExc_TypeError, "Expecting a python numeric type, got something else."); return -1; } } else if (PySequence_Check(seq) && !PyBytes_Check(seq)) { long i, maxtype=BOOL_SCALAR, slen; slen = PySequence_Length(seq); if (slen < 0) return -1; if (slen == 0) return INT_SCALAR; for(i=0; i maxtype) { maxtype = newmax; } Py_DECREF(o); } return maxtype; } else { if (PyBool_Check(seq)) return BOOL_SCALAR; else #if defined(NPY_PY3K) if (PyInt_Check(seq)) return INT_SCALAR; else if (PyLong_Check(seq)) #else if (PyLong_Check(seq)) #endif return LONG_SCALAR; else if (PyFloat_Check(seq)) return FLOAT_SCALAR; else if (PyComplex_Check(seq)) return COMPLEX_SCALAR; else { PyErr_Format(PyExc_TypeError, "Expecting a python numeric type, got something else."); return -1; } } } static int NA_maxType(PyObject *seq) { int rval; rval = _NA_maxType(seq, 0); return rval; } static int NA_isPythonScalar(PyObject *o) { int rval; rval = PyInt_Check(o) || PyLong_Check(o) || PyFloat_Check(o) || PyComplex_Check(o) || (PyBytes_Check(o) && (PyBytes_Size(o) == 1)); return rval; } #if (NPY_SIZEOF_INTP == 8) #define PlatBigInt PyInt_FromLong #define PlatBigUInt PyLong_FromUnsignedLong #else #define PlatBigInt PyLong_FromLongLong #define PlatBigUInt PyLong_FromUnsignedLongLong #endif static PyObject * NA_getPythonScalar(PyArrayObject *a, long offset) { int type = PyArray_DESCR(a)->type_num; PyObject *rval = NULL; switch(type) { case tBool: case tInt8: case tUInt8: case tInt16: case tUInt16: case tInt32: { Int64 v = NA_get_Int64(a, offset); rval = PyInt_FromLong(v); break; } case tUInt32: { Int64 v = NA_get_Int64(a, offset); rval = PlatBigUInt(v); break; } case tInt64: { Int64 v = NA_get_Int64(a, offset); rval = PlatBigInt( v); break; } case tUInt64: { Int64 v = NA_get_Int64(a, offset); rval = PlatBigUInt( v); break; } case tFloat32: case tFloat64: { Float64 v = NA_get_Float64(a, offset); rval = PyFloat_FromDouble( v ); break; } case tComplex32: case tComplex64: { Complex64 v = NA_get_Complex64(a, offset); rval = PyComplex_FromDoubles(v.r, v.i); break; } default: rval = PyErr_Format(PyExc_TypeError, "NA_getPythonScalar: bad type %d\n", type); } return rval; } static int NA_overflow(PyArrayObject *a, Float64 v) { if ((PyArray_FLAGS(a) & CHECKOVERFLOW) == 0) return 0; switch(PyArray_DESCR(a)->type_num) { case tBool: return 0; case tInt8: if ((v < -128) || (v > 127)) goto _fail; return 0; case tUInt8: if ((v < 0) || (v > 255)) goto _fail; return 0; case tInt16: if ((v < -32768) || (v > 32767)) goto _fail; return 0; case tUInt16: if ((v < 0) || (v > 65535)) goto _fail; return 0; case tInt32: if ((v < -2147483648.) || (v > 2147483647.)) goto _fail; return 0; case tUInt32: if ((v < 0) || (v > 4294967295.)) goto _fail; return 0; case tInt64: if ((v < -9223372036854775808.) || (v > 9223372036854775807.)) goto _fail; return 0; #if HAS_UINT64 case tUInt64: if ((v < 0) || (v > 18446744073709551615.)) goto _fail; return 0; #endif case tFloat32: if ((v < -FLT_MAX) || (v > FLT_MAX)) goto _fail; return 0; case tFloat64: return 0; case tComplex32: if ((v < -FLT_MAX) || (v > FLT_MAX)) goto _fail; return 0; case tComplex64: return 0; default: PyErr_Format( PyExc_TypeError, "Unknown type %d in NA_overflow", PyArray_DESCR(a)->type_num ); PyErr_Print(); return -1; } _fail: PyErr_Format(PyExc_OverflowError, "value out of range for array"); return -1; } static int _setFromPythonScalarCore(PyArrayObject *a, long offset, PyObject*value, int entries) { Int64 v; if (entries >= 100) { PyErr_Format(PyExc_RuntimeError, "NA_setFromPythonScalar: __tonumtype__ conversion chain too long"); return -1; } else if (PyInt_Check(value)) { v = PyInt_AsLong(value); if (NA_overflow(a, v) < 0) return -1; NA_set_Int64(a, offset, v); } else if (PyLong_Check(value)) { if (PyArray_DESCR(a)->type_num == tInt64) { v = (Int64) PyLong_AsLongLong( value ); } else if (PyArray_DESCR(a)->type_num == tUInt64) { v = (UInt64) PyLong_AsUnsignedLongLong( value ); } else if (PyArray_DESCR(a)->type_num == tUInt32) { v = PyLong_AsUnsignedLong(value); } else { v = PyLong_AsLongLong(value); } if (PyErr_Occurred()) return -1; if (NA_overflow(a, v) < 0) return -1; NA_set_Int64(a, offset, v); } else if (PyFloat_Check(value)) { Float64 v = PyFloat_AsDouble(value); if (NA_overflow(a, v) < 0) return -1; NA_set_Float64(a, offset, v); } else if (PyComplex_Check(value)) { Complex64 vc; vc.r = PyComplex_RealAsDouble(value); vc.i = PyComplex_ImagAsDouble(value); if (NA_overflow(a, vc.r) < 0) return -1; if (NA_overflow(a, vc.i) < 0) return -1; NA_set_Complex64(a, offset, vc); } else if (PyObject_HasAttrString(value, "__tonumtype__")) { int rval; PyObject *type = NA_typeNoToTypeObject(PyArray_DESCR(a)->type_num); if (!type) return -1; value = PyObject_CallMethod( value, "__tonumtype__", "(N)", type); if (!value) return -1; rval = _setFromPythonScalarCore(a, offset, value, entries+1); Py_DECREF(value); return rval; } else if (PyBytes_Check(value)) { long size = PyBytes_Size(value); if ((size <= 0) || (size > 1)) { PyErr_Format( PyExc_ValueError, "NA_setFromPythonScalar: len(string) must be 1."); return -1; } NA_set_Int64(a, offset, *PyBytes_AsString(value)); } else { PyErr_Format(PyExc_TypeError, "NA_setFromPythonScalar: bad value type."); return -1; } return 0; } static int NA_setFromPythonScalar(PyArrayObject *a, long offset, PyObject *value) { if (PyArray_FailUnlessWriteable(a, "array") < 0) { return -1; } return _setFromPythonScalarCore(a, offset, value, 0); } static int NA_NDArrayCheck(PyObject *obj) { return PyArray_Check(obj); } static int NA_NumArrayCheck(PyObject *obj) { return PyArray_Check(obj); } static int NA_ComplexArrayCheck(PyObject *a) { int rval = NA_NumArrayCheck(a); if (rval > 0) { PyArrayObject *arr = (PyArrayObject *) a; switch(PyArray_DESCR(arr)->type_num) { case tComplex64: case tComplex32: return 1; default: return 0; } } return rval; } static unsigned long NA_elements(PyArrayObject *a) { int i; unsigned long n = 1; for(i = 0; itype_num; return i; } static int NA_copyArray(PyArrayObject *to, const PyArrayObject *from) { return PyArray_CopyInto(to, (PyArrayObject *)from); } static PyArrayObject * NA_copy(PyArrayObject *from) { return (PyArrayObject *)PyArray_NewCopy(from, 0); } static PyObject * NA_getType( PyObject *type) { PyArray_Descr *typeobj = NULL; if (!type && PyArray_DescrConverter(type, &typeobj) == NPY_FAIL) { PyErr_Format(PyExc_ValueError, "NA_getType: unknown type."); typeobj = NULL; } return (PyObject *)typeobj; } /* Call a standard "stride" function ** ** Stride functions always take one input and one output array. ** They can handle n-dimensional data with arbitrary strides (of ** either sign) for both the input and output numarray. Typically ** these functions are used to copy data, byteswap, or align data. ** ** ** It expects the following arguments: ** ** Number of iterations for each dimension as a tuple ** Input Buffer Object ** Offset in bytes for input buffer ** Input strides (in bytes) for each dimension as a tuple ** Output Buffer Object ** Offset in bytes for output buffer ** Output strides (in bytes) for each dimension as a tuple ** An integer (Optional), typically the number of bytes to copy per * element. ** ** Returns None ** ** The arguments expected by the standard stride functions that this ** function calls are: ** ** Number of dimensions to iterate over ** Long int value (from the optional last argument to ** callStrideConvCFunc) ** often unused by the C Function ** An array of long ints. Each is the number of iterations for each ** dimension. NOTE: the previous argument as well as the stride ** arguments are reversed in order with respect to how they are ** used in Python. Fastest changing dimension is the first element ** in the numarray! ** A void pointer to the input data buffer. ** The starting offset for the input data buffer in bytes (long int). ** An array of long int input strides (in bytes) [reversed as with ** the iteration array] ** A void pointer to the output data buffer. ** The starting offset for the output data buffer in bytes (long int). ** An array of long int output strides (in bytes) [also reversed] */ static PyObject * NA_callStrideConvCFuncCore( PyObject *self, int nshape, maybelong *shape, PyObject *inbuffObj, long inboffset, int NPY_UNUSED(ninbstrides), maybelong *inbstrides, PyObject *outbuffObj, long outboffset, int NPY_UNUSED(noutbstrides), maybelong *outbstrides, long nbytes) { CfuncObject *me = (CfuncObject *) self; CFUNC_STRIDE_CONV_FUNC funcptr; void *inbuffer, *outbuffer; long inbsize, outbsize; maybelong i, lshape[MAXDIM], in_strides[MAXDIM], out_strides[MAXDIM]; maybelong shape_0, inbstr_0, outbstr_0; if (nshape == 0) { /* handle rank-0 numarray. */ nshape = 1; shape = &shape_0; inbstrides = &inbstr_0; outbstrides = &outbstr_0; shape[0] = 1; inbstrides[0] = outbstrides[0] = 0; } for(i=0; idescr.type != CFUNC_STRIDING) return PyErr_Format(PyExc_TypeError, "NA_callStrideConvCFuncCore: problem with cfunc"); if ((inbsize = NA_getBufferPtrAndSize(inbuffObj, 1, &inbuffer)) < 0) return PyErr_Format(_Error, "%s: Problem with input buffer", me->descr.name); if ((outbsize = NA_getBufferPtrAndSize(outbuffObj, 0, &outbuffer)) < 0) return PyErr_Format(_Error, "%s: Problem with output buffer (read only?)", me->descr.name); /* Check buffer alignment and bounds */ if (NA_checkOneStriding(me->descr.name, nshape, lshape, inboffset, in_strides, inbsize, (me->descr.sizes[0] == -1) ? nbytes : me->descr.sizes[0], me->descr.align) || NA_checkOneStriding(me->descr.name, nshape, lshape, outboffset, out_strides, outbsize, (me->descr.sizes[1] == -1) ? nbytes : me->descr.sizes[1], me->descr.align)) return NULL; /* Cast function pointer and perform stride operation */ funcptr = (CFUNC_STRIDE_CONV_FUNC) me->descr.fptr; if ((*funcptr)(nshape-1, nbytes, lshape, inbuffer, inboffset, in_strides, outbuffer, outboffset, out_strides) == 0) { Py_INCREF(Py_None); return Py_None; } else { return NULL; } } static void NA_stridesFromShape(int nshape, maybelong *shape, maybelong bytestride, maybelong *strides) { int i; if (nshape > 0) { for(i=0; i=0; i--) strides[i] = strides[i+1]*shape[i+1]; } } static int NA_OperatorCheck(PyObject *NPY_UNUSED(op)) { return 0; } static int NA_ConverterCheck(PyObject *NPY_UNUSED(op)) { return 0; } static int NA_UfuncCheck(PyObject *NPY_UNUSED(op)) { return 0; } static int NA_CfuncCheck(PyObject *op) { return PyObject_TypeCheck(op, &CfuncType); } static int NA_getByteOffset(PyArrayObject *NPY_UNUSED(array), int NPY_UNUSED(nindices), maybelong *NPY_UNUSED(indices), long *NPY_UNUSED(offset)) { return 0; } static int NA_swapAxes(PyArrayObject *array, int x, int y) { long temp; if (((PyObject *) array) == Py_None) return 0; if (PyArray_NDIM(array) < 2) return 0; if (x < 0) x += PyArray_NDIM(array); if (y < 0) y += PyArray_NDIM(array); if ((x < 0) || (x >= PyArray_NDIM(array)) || (y < 0) || (y >= PyArray_NDIM(array))) { PyErr_Format(PyExc_ValueError, "Specified dimension does not exist"); return -1; } temp = PyArray_DIMS(array)[x]; PyArray_DIMS(array)[x] = PyArray_DIMS(array)[y]; PyArray_DIMS(array)[y] = temp; temp = PyArray_STRIDES(array)[x]; PyArray_STRIDES(array)[x] = PyArray_STRIDES(array)[y]; PyArray_STRIDES(array)[y] = temp; PyArray_UpdateFlags(array, NPY_ARRAY_UPDATE_ALL); return 0; } static PyObject * NA_initModuleGlobal(char *modulename, char *globalname) { PyObject *module, *dict, *global = NULL; module = PyImport_ImportModule(modulename); if (!module) { PyErr_Format(PyExc_RuntimeError, "Can't import '%s' module", modulename); goto _exit; } dict = PyModule_GetDict(module); global = PyDict_GetItemString(dict, globalname); if (!global) { PyErr_Format(PyExc_RuntimeError, "Can't find '%s' global in '%s' module.", globalname, modulename); goto _exit; } Py_DECREF(module); Py_INCREF(global); _exit: return global; } NumarrayType NA_NumarrayType(PyObject *seq) { int maxtype = NA_maxType(seq); int rval; switch(maxtype) { case BOOL_SCALAR: rval = tBool; goto _exit; case INT_SCALAR: case LONG_SCALAR: rval = tLong; /* tLong corresponds to C long int, not Python long int */ goto _exit; case FLOAT_SCALAR: rval = tFloat64; goto _exit; case COMPLEX_SCALAR: rval = tComplex64; goto _exit; default: PyErr_Format(PyExc_TypeError, "expecting Python numeric scalar value; got something else."); rval = -1; } _exit: return rval; } /* ignores bytestride */ static PyArrayObject * NA_NewAllFromBuffer(int ndim, maybelong *shape, NumarrayType type, PyObject *bufferObject, maybelong byteoffset, maybelong NPY_UNUSED(bytestride), int byteorder, int NPY_UNUSED(aligned), int NPY_UNUSED(writeable)) { PyArrayObject *self = NULL; PyArray_Descr *dtype; if (type == tAny) type = tDefault; dtype = PyArray_DescrFromType(type); if (dtype == NULL) return NULL; if (byteorder != NA_ByteOrder()) { PyArray_Descr *temp; temp = PyArray_DescrNewByteorder(dtype, NPY_SWAP); Py_DECREF(dtype); if (temp == NULL) return NULL; dtype = temp; } if (bufferObject == Py_None || bufferObject == NULL) { self = (PyArrayObject *) \ PyArray_NewFromDescr(&PyArray_Type, dtype, ndim, shape, NULL, NULL, 0, NULL); } else { npy_intp size = 1; int i; PyArrayObject *newself; PyArray_Dims newdims; for(i=0; iob_type == &PyArray_Type); } static int NA_NDArrayCheckExact(PyObject *op) { return (op->ob_type == &PyArray_Type); } static int NA_OperatorCheckExact(PyObject *NPY_UNUSED(op)) { return 0; } static int NA_ConverterCheckExact(PyObject *NPY_UNUSED(op)) { return 0; } static int NA_UfuncCheckExact(PyObject *NPY_UNUSED(op)) { return 0; } static int NA_CfuncCheckExact(PyObject *op) { return op->ob_type == &CfuncType; } static char * NA_getArrayData(PyArrayObject *obj) { if (!NA_NDArrayCheck((PyObject *) obj)) { PyErr_Format(PyExc_TypeError, "expected an NDArray"); } return PyArray_DATA(obj); } /* Byteswap is not a flag of the array --- it is implicit in the data-type */ static void NA_updateByteswap(PyArrayObject *NPY_UNUSED(self)) { return; } static PyArray_Descr * NA_DescrFromType(int type) { if (type == tAny) type = tDefault; return PyArray_DescrFromType(type); } static PyObject * NA_Cast(PyArrayObject *a, int type) { return PyArray_Cast(a, type); } /* The following function has much platform dependent code since ** there is no platform-independent way of checking Floating Point ** status bits */ /* OSF/Alpha (Tru64) ---------------------------------------------*/ #if defined(__osf__) && defined(__alpha) static int NA_checkFPErrors(void) { unsigned long fpstatus; int retstatus; #include /* Should migrate to global scope */ fpstatus = ieee_get_fp_control(); /* clear status bits as well as disable exception mode if on */ ieee_set_fp_control( 0 ); retstatus = pyFPE_DIVIDE_BY_ZERO* (int)((IEEE_STATUS_DZE & fpstatus) != 0) + pyFPE_OVERFLOW * (int)((IEEE_STATUS_OVF & fpstatus) != 0) + pyFPE_UNDERFLOW * (int)((IEEE_STATUS_UNF & fpstatus) != 0) + pyFPE_INVALID * (int)((IEEE_STATUS_INV & fpstatus) != 0); return retstatus; } /* MS Windows -----------------------------------------------------*/ #elif defined(_MSC_VER) #include static int NA_checkFPErrors(void) { int fpstatus = (int) _clear87(); int retstatus = pyFPE_DIVIDE_BY_ZERO * ((SW_ZERODIVIDE & fpstatus) != 0) + pyFPE_OVERFLOW * ((SW_OVERFLOW & fpstatus) != 0) + pyFPE_UNDERFLOW * ((SW_UNDERFLOW & fpstatus) != 0) + pyFPE_INVALID * ((SW_INVALID & fpstatus) != 0); return retstatus; } /* Solaris --------------------------------------------------------*/ /* --------ignoring SunOS ieee_flags approach, someone else can ** deal with that! */ #elif defined(sun) #include static int NA_checkFPErrors(void) { int fpstatus; int retstatus; fpstatus = (int) fpgetsticky(); retstatus = pyFPE_DIVIDE_BY_ZERO * ((FP_X_DZ & fpstatus) != 0) + pyFPE_OVERFLOW * ((FP_X_OFL & fpstatus) != 0) + pyFPE_UNDERFLOW * ((FP_X_UFL & fpstatus) != 0) + pyFPE_INVALID * ((FP_X_INV & fpstatus) != 0); (void) fpsetsticky(0); return retstatus; } #elif defined(__GLIBC__) || defined(__APPLE__) || defined(__CYGWIN__) || defined(__MINGW32__) || (defined(__FreeBSD__) && (__FreeBSD_version >= 502114)) static int NA_checkFPErrors(void) { int fpstatus = (int) fetestexcept( FE_DIVBYZERO | FE_OVERFLOW | FE_UNDERFLOW | FE_INVALID); int retstatus = pyFPE_DIVIDE_BY_ZERO * ((FE_DIVBYZERO & fpstatus) != 0) + pyFPE_OVERFLOW * ((FE_OVERFLOW & fpstatus) != 0) + pyFPE_UNDERFLOW * ((FE_UNDERFLOW & fpstatus) != 0) + pyFPE_INVALID * ((FE_INVALID & fpstatus) != 0); (void) feclearexcept(FE_DIVBYZERO | FE_OVERFLOW | FE_UNDERFLOW | FE_INVALID); return retstatus; } #else static int NA_checkFPErrors(void) { return 0; } #endif static void NA_clearFPErrors() { NA_checkFPErrors(); } /* Not supported yet */ static int NA_checkAndReportFPErrors(char *name) { int error = NA_checkFPErrors(); if (error) { PyObject *ans; char msg[128]; strcpy(msg, " in "); strncat(msg, name, 100); ans = PyObject_CallFunction(pHandleErrorFunc, "(is)", error, msg); if (!ans) return -1; Py_DECREF(ans); /* Py_None */ } return 0; } #define WITHIN32(v, f) (((v) >= f##_MIN32) && ((v) <= f##_MAX32)) #define WITHIN64(v, f) (((v) >= f##_MIN64) && ((v) <= f##_MAX64)) static Bool NA_IeeeMask32( Float32 f, Int32 mask) { Int32 category; UInt32 v = *(UInt32 *) &f; if (v & BIT(31)) { if (WITHIN32(v, NEG_NORMALIZED)) { category = MSK_NEG_NOR; } else if (WITHIN32(v, NEG_DENORMALIZED)) { category = MSK_NEG_DEN; } else if (WITHIN32(v, NEG_SIGNAL_NAN)) { category = MSK_NEG_SNAN; } else if (WITHIN32(v, NEG_QUIET_NAN)) { category = MSK_NEG_QNAN; } else if (v == NEG_INFINITY_MIN32) { category = MSK_NEG_INF; } else if (v == NEG_ZERO_MIN32) { category = MSK_NEG_ZERO; } else if (v == INDETERMINATE_MIN32) { category = MSK_INDETERM; } else { category = MSK_BUG; } } else { if (WITHIN32(v, POS_NORMALIZED)) { category = MSK_POS_NOR; } else if (WITHIN32(v, POS_DENORMALIZED)) { category = MSK_POS_DEN; } else if (WITHIN32(v, POS_SIGNAL_NAN)) { category = MSK_POS_SNAN; } else if (WITHIN32(v, POS_QUIET_NAN)) { category = MSK_POS_QNAN; } else if (v == POS_INFINITY_MIN32) { category = MSK_POS_INF; } else if (v == POS_ZERO_MIN32) { category = MSK_POS_ZERO; } else { category = MSK_BUG; } } return (category & mask) != 0; } static Bool NA_IeeeMask64( Float64 f, Int32 mask) { Int32 category; UInt64 v = *(UInt64 *) &f; if (v & BIT(63)) { if (WITHIN64(v, NEG_NORMALIZED)) { category = MSK_NEG_NOR; } else if (WITHIN64(v, NEG_DENORMALIZED)) { category = MSK_NEG_DEN; } else if (WITHIN64(v, NEG_SIGNAL_NAN)) { category = MSK_NEG_SNAN; } else if (WITHIN64(v, NEG_QUIET_NAN)) { category = MSK_NEG_QNAN; } else if (v == NEG_INFINITY_MIN64) { category = MSK_NEG_INF; } else if (v == NEG_ZERO_MIN64) { category = MSK_NEG_ZERO; } else if (v == INDETERMINATE_MIN64) { category = MSK_INDETERM; } else { category = MSK_BUG; } } else { if (WITHIN64(v, POS_NORMALIZED)) { category = MSK_POS_NOR; } else if (WITHIN64(v, POS_DENORMALIZED)) { category = MSK_POS_DEN; } else if (WITHIN64(v, POS_SIGNAL_NAN)) { category = MSK_POS_SNAN; } else if (WITHIN64(v, POS_QUIET_NAN)) { category = MSK_POS_QNAN; } else if (v == POS_INFINITY_MIN64) { category = MSK_POS_INF; } else if (v == POS_ZERO_MIN64) { category = MSK_POS_ZERO; } else { category = MSK_BUG; } } return (category & mask) != 0; } static PyArrayObject * NA_FromDimsStridesDescrAndData(int nd, maybelong *d, maybelong *s, PyArray_Descr *descr, char *data) { return (PyArrayObject *)\ PyArray_NewFromDescr(&PyArray_Type, descr, nd, d, s, data, 0, NULL); } static PyArrayObject * NA_FromDimsTypeAndData(int nd, maybelong *d, int type, char *data) { PyArray_Descr *descr = NA_DescrFromType(type); return NA_FromDimsStridesDescrAndData(nd, d, NULL, descr, data); } static PyArrayObject * NA_FromDimsStridesTypeAndData(int nd, maybelong *shape, maybelong *strides, int type, char *data) { PyArray_Descr *descr = NA_DescrFromType(type); return NA_FromDimsStridesDescrAndData(nd, shape, strides, descr, data); } typedef struct { NumarrayType type_num; char suffix[5]; int itemsize; } scipy_typestr; static scipy_typestr scipy_descriptors[ ] = { { tAny, "", 0}, { tBool, "b1", 1}, { tInt8, "i1", 1}, { tUInt8, "u1", 1}, { tInt16, "i2", 2}, { tUInt16, "u2", 2}, { tInt32, "i4", 4}, { tUInt32, "u4", 4}, { tInt64, "i8", 8}, { tUInt64, "u8", 8}, { tFloat32, "f4", 4}, { tFloat64, "f8", 8}, { tComplex32, "c8", 8}, { tComplex64, "c16", 16} }; static int NA_scipy_typestr(NumarrayType t, int byteorder, char *typestr) { size_t i; if (byteorder) strcpy(typestr, ">"); else strcpy(typestr, "<"); for(i=0; itype_num == t) { strncat(typestr, ts->suffix, 4); return 0; } } return -1; } static PyArrayObject * NA_FromArrayStruct(PyObject *obj) { return (PyArrayObject *)PyArray_FromStructInterface(obj); } static PyObject *_Error; void *libnumarray_API[] = { (void*) getBuffer, (void*) isBuffer, (void*) getWriteBufferDataPtr, (void*) isBufferWriteable, (void*) getReadBufferDataPtr, (void*) getBufferSize, (void*) num_log, (void*) num_log10, (void*) num_pow, (void*) num_acosh, (void*) num_asinh, (void*) num_atanh, (void*) num_round, (void*) int_dividebyzero_error, (void*) int_overflow_error, (void*) umult64_overflow, (void*) smult64_overflow, (void*) NA_Done, (void*) NA_NewAll, (void*) NA_NewAllStrides, (void*) NA_New, (void*) NA_Empty, (void*) NA_NewArray, (void*) NA_vNewArray, (void*) NA_ReturnOutput, (void*) NA_getBufferPtrAndSize, (void*) NA_checkIo, (void*) NA_checkOneCBuffer, (void*) NA_checkNCBuffers, (void*) NA_checkOneStriding, (void*) NA_new_cfunc, (void*) NA_add_cfunc, (void*) NA_InputArray, (void*) NA_OutputArray, (void*) NA_IoArray, (void*) NA_OptionalOutputArray, (void*) NA_get_offset, (void*) NA_get_Float64, (void*) NA_set_Float64, (void*) NA_get_Complex64, (void*) NA_set_Complex64, (void*) NA_get_Int64, (void*) NA_set_Int64, (void*) NA_get1_Float64, (void*) NA_get2_Float64, (void*) NA_get3_Float64, (void*) NA_set1_Float64, (void*) NA_set2_Float64, (void*) NA_set3_Float64, (void*) NA_get1_Complex64, (void*) NA_get2_Complex64, (void*) NA_get3_Complex64, (void*) NA_set1_Complex64, (void*) NA_set2_Complex64, (void*) NA_set3_Complex64, (void*) NA_get1_Int64, (void*) NA_get2_Int64, (void*) NA_get3_Int64, (void*) NA_set1_Int64, (void*) NA_set2_Int64, (void*) NA_set3_Int64, (void*) NA_get1D_Float64, (void*) NA_set1D_Float64, (void*) NA_get1D_Int64, (void*) NA_set1D_Int64, (void*) NA_get1D_Complex64, (void*) NA_set1D_Complex64, (void*) NA_ShapeEqual, (void*) NA_ShapeLessThan, (void*) NA_ByteOrder, (void*) NA_IeeeSpecial32, (void*) NA_IeeeSpecial64, (void*) NA_updateDataPtr, (void*) NA_typeNoToName, (void*) NA_nameToTypeNo, (void*) NA_typeNoToTypeObject, (void*) NA_intTupleFromMaybeLongs, (void*) NA_maybeLongsFromIntTuple, (void*) NA_intTupleProduct, (void*) NA_isIntegerSequence, (void*) NA_setArrayFromSequence, (void*) NA_maxType, (void*) NA_isPythonScalar, (void*) NA_getPythonScalar, (void*) NA_setFromPythonScalar, (void*) NA_NDArrayCheck, (void*) NA_NumArrayCheck, (void*) NA_ComplexArrayCheck, (void*) NA_elements, (void*) NA_typeObjectToTypeNo, (void*) NA_copyArray, (void*) NA_copy, (void*) NA_getType, (void*) NA_callCUFuncCore, (void*) NA_callStrideConvCFuncCore, (void*) NA_stridesFromShape, (void*) NA_OperatorCheck, (void*) NA_ConverterCheck, (void*) NA_UfuncCheck, (void*) NA_CfuncCheck, (void*) NA_getByteOffset, (void*) NA_swapAxes, (void*) NA_initModuleGlobal, (void*) NA_NumarrayType, (void*) NA_NewAllFromBuffer, (void*) NA_alloc1D_Float64, (void*) NA_alloc1D_Int64, (void*) NA_updateAlignment, (void*) NA_updateContiguous, (void*) NA_updateStatus, (void*) NA_NumArrayCheckExact, (void*) NA_NDArrayCheckExact, (void*) NA_OperatorCheckExact, (void*) NA_ConverterCheckExact, (void*) NA_UfuncCheckExact, (void*) NA_CfuncCheckExact, (void*) NA_getArrayData, (void*) NA_updateByteswap, (void*) NA_DescrFromType, (void*) NA_Cast, (void*) NA_checkFPErrors, (void*) NA_clearFPErrors, (void*) NA_checkAndReportFPErrors, (void*) NA_IeeeMask32, (void*) NA_IeeeMask64, (void*) _NA_callStridingHelper, (void*) NA_FromDimsStridesDescrAndData, (void*) NA_FromDimsTypeAndData, (void*) NA_FromDimsStridesTypeAndData, (void*) NA_scipy_typestr, (void*) NA_FromArrayStruct }; #if (!defined(METHOD_TABLE_EXISTS)) static PyMethodDef _libnumarrayMethods[] = { {NULL, NULL, 0, NULL} /* Sentinel */ }; #endif /* boiler plate API init */ #if defined(NPY_PY3K) #define RETVAL m static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, "_capi", NULL, -1, _libnumarrayMethods, NULL, NULL, NULL, NULL }; PyMODINIT_FUNC PyInit__capi(void) #else #define RETVAL PyMODINIT_FUNC init_capi(void) #endif { PyObject *m; PyObject *c_api_object; _Error = PyErr_NewException("numpy.numarray._capi.error", NULL, NULL); /* Create a CObject containing the API pointer array's address */ #if defined(NPY_PY3K) m = PyModule_Create(&moduledef); #else m = Py_InitModule("_capi", _libnumarrayMethods); #endif #if defined(NPY_PY3K) c_api_object = PyCapsule_New((void *)libnumarray_API, NULL, NULL); if (c_api_object == NULL) { PyErr_Clear(); } #else c_api_object = PyCObject_FromVoidPtr((void *)libnumarray_API, NULL); #endif if (c_api_object != NULL) { /* Create a name for this object in the module's namespace */ PyObject *d = PyModule_GetDict(m); PyDict_SetItemString(d, "_C_API", c_api_object); PyDict_SetItemString(d, "error", _Error); Py_DECREF(c_api_object); } else { return RETVAL; } if (PyModule_AddObject(m, "__version__", PyUString_FromString("0.9")) < 0) { return RETVAL; } if (_import_array() < 0) { return RETVAL; } deferred_libnumarray_init(); return RETVAL; } numpy-1.8.2/numpy/numarray/random_array.py0000664000175100017510000000074312370216243022066 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function __all__ = ['ArgumentError', 'F', 'beta', 'binomial', 'chi_square', 'exponential', 'gamma', 'get_seed', 'multinomial', 'multivariate_normal', 'negative_binomial', 'noncentral_F', 'noncentral_chi_square', 'normal', 'permutation', 'poisson', 'randint', 'random', 'random_integers', 'standard_normal', 'uniform', 'seed'] from numpy.oldnumeric.random_array import * numpy-1.8.2/numpy/numarray/util.py0000664000175100017510000000312112370216243020356 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function import os import numpy as np __all__ = ['MathDomainError', 'UnderflowError', 'NumOverflowError', 'handleError', 'get_numarray_include_dirs'] class MathDomainError(ArithmeticError): pass class UnderflowError(ArithmeticError): pass class NumOverflowError(OverflowError, ArithmeticError): pass def handleError(errorStatus, sourcemsg): """Take error status and use error mode to handle it.""" modes = np.geterr() if errorStatus & np.FPE_INVALID: if modes['invalid'] == "warn": print("Warning: Encountered invalid numeric result(s)", sourcemsg) if modes['invalid'] == "raise": raise MathDomainError(sourcemsg) if errorStatus & np.FPE_DIVIDEBYZERO: if modes['dividebyzero'] == "warn": print("Warning: Encountered divide by zero(s)", sourcemsg) if modes['dividebyzero'] == "raise": raise ZeroDivisionError(sourcemsg) if errorStatus & np.FPE_OVERFLOW: if modes['overflow'] == "warn": print("Warning: Encountered overflow(s)", sourcemsg) if modes['overflow'] == "raise": raise NumOverflowError(sourcemsg) if errorStatus & np.FPE_UNDERFLOW: if modes['underflow'] == "warn": print("Warning: Encountered underflow(s)", sourcemsg) if modes['underflow'] == "raise": raise UnderflowError(sourcemsg) def get_numarray_include_dirs(): base = os.path.dirname(np.__file__) newdirs = [os.path.join(base, 'numarray', 'include')] return newdirs numpy-1.8.2/numpy/numarray/session.py0000664000175100017510000002523412370216243021075 0ustar vagrantvagrant00000000000000""" This module contains a "session saver" which saves the state of a NumPy session to a file. At a later time, a different Python process can be started and the saved session can be restored using load(). The session saver relies on the Python pickle protocol to save and restore objects. Objects which are not themselves picklable (e.g. modules) can sometimes be saved by "proxy", particularly when they are global constants of some kind. If it's not known that proxying will work, a warning is issued at save time. If a proxy fails to reload properly (e.g. because it's not a global constant), a warning is issued at reload time and that name is bound to a _ProxyFailure instance which tries to identify what should have been restored. First, some unfortunate (probably unnecessary) concessions to doctest to keep the test run free of warnings. >>> del _PROXY_ALLOWED >>> del __builtins__ By default, save() stores every variable in the caller's namespace: >>> import numpy as na >>> a = na.arange(10) >>> save() Alternately, save() can be passed a comma seperated string of variables: >>> save("a,na") Alternately, save() can be passed a dictionary, typically one you already have lying around somewhere rather than created inline as shown here: >>> save(dictionary={"a":a,"na":na}) If both variables and a dictionary are specified, the variables to be saved are taken from the dictionary. >>> save(variables="a,na",dictionary={"a":a,"na":na}) Remove names from the session namespace >>> del a, na By default, load() restores every variable/object in the session file to the caller's namespace. >>> load() load() can be passed a comma seperated string of variables to be restored from the session file to the caller's namespace: >>> load("a,na") load() can also be passed a dictionary to *restore to*: >>> d = {} >>> load(dictionary=d) load can be passed both a list variables of variables to restore and a dictionary to restore to: >>> load(variables="a,na", dictionary=d) >>> na.all(a == na.arange(10)) 1 >>> na.__name__ 'numpy' NOTE: session saving is faked for modules using module proxy objects. Saved modules are re-imported at load time but any "state" in the module which is not restored by a simple import is lost. """ from __future__ import division, absolute_import, print_function __all__ = ['load', 'save'] import sys import pickle SAVEFILE="session.dat" VERBOSE = False # global import-time override def _foo(): pass _PROXY_ALLOWED = (type(sys), # module type(_foo), # function type(None)) # None def _update_proxy_types(): """Suppress warnings for known un-picklables with working proxies.""" pass def _unknown(_type): """returns True iff _type isn't known as OK to proxy""" return (_type is not None) and (_type not in _PROXY_ALLOWED) # caller() from the following article with one extra f_back added. # from http://www.python.org/search/hypermail/python-1994q1/0506.html # SUBJECT: import ( how to put a symbol into caller's namespace ) # SENDER: Steven D. Majewski (sdm7g@elvis.med.virginia.edu) # DATE: Thu, 24 Mar 1994 15:38:53 -0500 def _caller(): """caller() returns the frame object of the function's caller.""" try: 1 + '' # make an error happen except: # and return the caller's caller's frame return sys.exc_traceback.tb_frame.f_back.f_back.f_back def _callers_globals(): """callers_globals() returns the global dictionary of the caller.""" frame = _caller() return frame.f_globals def _callers_modules(): """returns a list containing the names of all the modules in the caller's global namespace.""" g = _callers_globals() mods = [] for k, v in g.items(): if isinstance(v, type(sys)): mods.append(getattr(v, "__name__")) return mods def _errout(*args): for a in args: print(a, end=' ', file=sys.stderr) print(file=sys.stderr) def _verbose(*args): if VERBOSE: _errout(*args) class _ProxyingFailure: """Object which is bound to a variable for a proxy pickle which failed to reload""" def __init__(self, module, name, type=None): self.module = module self.name = name self.type = type def __repr__(self): return "ProxyingFailure('%s','%s','%s')" % (self.module, self.name, self.type) class _ModuleProxy(object): """Proxy object which fakes pickling a module""" def __new__(_type, name, save=False): if save: _verbose("proxying module", name) self = object.__new__(_type) self.name = name else: _verbose("loading module proxy", name) try: self = _loadmodule(name) except ImportError: _errout("warning: module", name, "import failed.") return self def __getnewargs__(self): return (self.name,) def __getstate__(self): return False def _loadmodule(module): if module not in sys.modules: modules = module.split(".") s = "" for i in range(len(modules)): s = ".".join(modules[:i+1]) exec("import " + s) return sys.modules[module] class _ObjectProxy(object): """Proxy object which fakes pickling an arbitrary object. Only global constants can really be proxied.""" def __new__(_type, module, name, _type2, save=False): if save: if _unknown(_type2): _errout("warning: proxying object", module + "." + name, "of type", _type2, "because it wouldn't pickle...", "it may not reload later.") else: _verbose("proxying object", module, name) self = object.__new__(_type) self.module, self.name, self.type = module, name, str(_type2) else: _verbose("loading object proxy", module, name) try: m = _loadmodule(module) except (ImportError, KeyError): _errout("warning: loading object proxy", module + "." + name, "module import failed.") return _ProxyingFailure(module, name, _type2) try: self = getattr(m, name) except AttributeError: _errout("warning: object proxy", module + "." + name, "wouldn't reload from", m) return _ProxyingFailure(module, name, _type2) return self def __getnewargs__(self): return (self.module, self.name, self.type) def __getstate__(self): return False class _SaveSession(object): """Tag object which marks the end of a save session and holds the saved session variable names as a list of strings in the same order as the session pickles.""" def __new__(_type, keys, save=False): if save: _verbose("saving session", keys) else: _verbose("loading session", keys) self = object.__new__(_type) self.keys = keys return self def __getnewargs__(self): return (self.keys,) def __getstate__(self): return False class ObjectNotFound(RuntimeError): pass def _locate(modules, object): for mname in modules: m = sys.modules[mname] if m: for k, v in m.__dict__.items(): if v is object: return m.__name__, k else: raise ObjectNotFound(k) def save(variables=None, file=SAVEFILE, dictionary=None, verbose=False): """saves variables from a numpy session to a file. Variables which won't pickle are "proxied" if possible. 'variables' a string of comma seperated variables: e.g. "a,b,c" Defaults to dictionary.keys(). 'file' a filename or file object for the session file. 'dictionary' the dictionary in which to look up the variables. Defaults to the caller's globals() 'verbose' print additional debug output when True. """ global VERBOSE VERBOSE = verbose _update_proxy_types() if isinstance(file, str): file = open(file, "wb") if dictionary is None: dictionary = _callers_globals() if variables is None: keys = list(dictionary.keys()) else: keys = variables.split(",") source_modules = _callers_modules() + list(sys.modules.keys()) p = pickle.Pickler(file, protocol=2) _verbose("variables:", keys) for k in keys: v = dictionary[k] _verbose("saving", k, type(v)) try: # Try to write an ordinary pickle p.dump(v) _verbose("pickled", k) except (pickle.PicklingError, TypeError, SystemError): # Use proxies for stuff that won't pickle if isinstance(v, type(sys)): # module proxy = _ModuleProxy(v.__name__, save=True) else: try: module, name = _locate(source_modules, v) except ObjectNotFound: _errout("warning: couldn't find object", k, "in any module... skipping.") continue else: proxy = _ObjectProxy(module, name, type(v), save=True) p.dump(proxy) o = _SaveSession(keys, save=True) p.dump(o) file.close() def load(variables=None, file=SAVEFILE, dictionary=None, verbose=False): """load a numpy session from a file and store the specified 'variables' into 'dictionary'. 'variables' a string of comma seperated variables: e.g. "a,b,c" Defaults to dictionary.keys(). 'file' a filename or file object for the session file. 'dictionary' the dictionary in which to look up the variables. Defaults to the caller's globals() 'verbose' print additional debug output when True. """ global VERBOSE VERBOSE = verbose if isinstance(file, str): file = open(file, "rb") if dictionary is None: dictionary = _callers_globals() values = [] p = pickle.Unpickler(file) while True: o = p.load() if isinstance(o, _SaveSession): session = dict(zip(o.keys, values)) _verbose("updating dictionary with session variables.") if variables is None: keys = list(session.keys()) else: keys = variables.split(",") for k in keys: dictionary[k] = session[k] return None else: _verbose("unpickled object", str(o)) values.append(o) def test(): import doctest, numpy.numarray.session return doctest.testmod(numpy.numarray.session) numpy-1.8.2/numpy/numarray/linear_algebra.py0000664000175100017510000000057712370216243022344 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function from numpy.oldnumeric.linear_algebra import * import numpy.oldnumeric.linear_algebra as nol __all__ = list(nol.__all__) __all__ += ['qr_decomposition'] from numpy.linalg import qr as _qr def qr_decomposition(a, mode='full'): res = _qr(a, mode) if mode == 'full': return res return (None, res) numpy-1.8.2/numpy/numarray/functions.py0000664000175100017510000003716212370216243021425 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function # missing Numarray defined names (in from numarray import *) __all__ = ['asarray', 'ones', 'zeros', 'array', 'where'] __all__ += ['vdot', 'dot', 'matrixmultiply', 'ravel', 'indices', 'arange', 'concatenate', 'all', 'allclose', 'alltrue', 'and_', 'any', 'argmax', 'argmin', 'argsort', 'around', 'array_equal', 'array_equiv', 'arrayrange', 'array_str', 'array_repr', 'array2list', 'average', 'choose', 'CLIP', 'RAISE', 'WRAP', 'clip', 'compress', 'copy', 'copy_reg', 'diagonal', 'divide_remainder', 'e', 'explicit_type', 'pi', 'flush_caches', 'fromfile', 'os', 'sys', 'STRICT', 'SLOPPY', 'WARN', 'EarlyEOFError', 'SizeMismatchError', 'SizeMismatchWarning', 'FileSeekWarning', 'fromstring', 'fromfunction', 'fromlist', 'getShape', 'getTypeObject', 'identity', 'info', 'innerproduct', 'inputarray', 'isBigEndian', 'kroneckerproduct', 'lexsort', 'math', 'operator', 'outerproduct', 'put', 'putmask', 'rank', 'repeat', 'reshape', 'resize', 'round', 'searchsorted', 'shape', 'size', 'sometrue', 'sort', 'swapaxes', 'take', 'tcode', 'tname', 'tensormultiply', 'trace', 'transpose', 'types', 'value', 'cumsum', 'cumproduct', 'nonzero', 'newobj', 'togglebyteorder' ] import copy import types import os import sys import math import operator import numpy as np from numpy import dot as matrixmultiply, dot, vdot, ravel, concatenate, all,\ allclose, any, argsort, array_equal, array_equiv,\ array_str, array_repr, CLIP, RAISE, WRAP, clip, concatenate, \ diagonal, e, pi, inner as innerproduct, nonzero, \ outer as outerproduct, kron as kroneckerproduct, lexsort, putmask, rank, \ resize, searchsorted, shape, size, sort, swapaxes, trace, transpose from numpy.compat import long from .numerictypes import typefrom if sys.version_info[0] >= 3: import copyreg as copy_reg else: import copy_reg isBigEndian = sys.byteorder != 'little' value = tcode = 'f' tname = 'Float32' # If dtype is not None, then it is used # If type is not None, then it is used # If typecode is not None then it is used # If use_default is True, then the default # data-type is returned if all are None def type2dtype(typecode, type, dtype, use_default=True): if dtype is None: if type is None: if use_default or typecode is not None: dtype = np.dtype(typecode) else: dtype = np.dtype(type) if use_default and dtype is None: dtype = np.dtype('int') return dtype def fromfunction(shape, dimensions, type=None, typecode=None, dtype=None): dtype = type2dtype(typecode, type, dtype, 1) return np.fromfunction(shape, dimensions, dtype=dtype) def ones(shape, type=None, typecode=None, dtype=None): dtype = type2dtype(typecode, type, dtype, 1) return np.ones(shape, dtype) def zeros(shape, type=None, typecode=None, dtype=None): dtype = type2dtype(typecode, type, dtype, 1) return np.zeros(shape, dtype) def where(condition, x=None, y=None, out=None): if x is None and y is None: arr = np.where(condition) else: arr = np.where(condition, x, y) if out is not None: out[...] = arr return out return arr def indices(shape, type=None): return np.indices(shape, type) def arange(a1, a2=None, stride=1, type=None, shape=None, typecode=None, dtype=None): dtype = type2dtype(typecode, type, dtype, 0) return np.arange(a1, a2, stride, dtype) arrayrange = arange def alltrue(x, axis=0): return np.alltrue(x, axis) def and_(a, b): """Same as a & b """ return a & b def divide_remainder(a, b): a, b = asarray(a), asarray(b) return (a/b, a%b) def around(array, digits=0, output=None): ret = np.around(array, digits, output) if output is None: return ret return def array2list(arr): return arr.tolist() def choose(selector, population, outarr=None, clipmode=RAISE): a = np.asarray(selector) ret = a.choose(population, out=outarr, mode=clipmode) if outarr is None: return ret return def compress(condition, a, axis=0): return np.compress(condition, a, axis) # only returns a view def explicit_type(a): x = a.view() return x # stub def flush_caches(): pass class EarlyEOFError(Exception): "Raised in fromfile() if EOF unexpectedly occurs." pass class SizeMismatchError(Exception): "Raised in fromfile() if file size does not match shape." pass class SizeMismatchWarning(Warning): "Issued in fromfile() if file size does not match shape." pass class FileSeekWarning(Warning): "Issued in fromfile() if there is unused data and seek() fails" pass STRICT, SLOPPY, WARN = list(range(3)) _BLOCKSIZE=1024 # taken and adapted directly from numarray def fromfile(infile, type=None, shape=None, sizing=STRICT, typecode=None, dtype=None): if isinstance(infile, (str, unicode)): infile = open(infile, 'rb') dtype = type2dtype(typecode, type, dtype, True) if shape is None: shape = (-1,) if not isinstance(shape, tuple): shape = (shape,) if (list(shape).count(-1)>1): raise ValueError("At most one unspecified dimension in shape") if -1 not in shape: if sizing != STRICT: raise ValueError("sizing must be STRICT if size complete") arr = np.empty(shape, dtype) bytesleft=arr.nbytes bytesread=0 while(bytesleft > _BLOCKSIZE): data = infile.read(_BLOCKSIZE) if len(data) != _BLOCKSIZE: raise EarlyEOFError("Unexpected EOF reading data for size complete array") arr.data[bytesread:bytesread+_BLOCKSIZE]=data bytesread += _BLOCKSIZE bytesleft -= _BLOCKSIZE if bytesleft > 0: data = infile.read(bytesleft) if len(data) != bytesleft: raise EarlyEOFError("Unexpected EOF reading data for size complete array") arr.data[bytesread:bytesread+bytesleft]=data return arr ##shape is incompletely specified ##read until EOF ##implementation 1: naively use memory blocks ##problematic because memory allocation can be double what is ##necessary (!) ##the most common case, namely reading in data from an unchanging ##file whose size may be determined before allocation, should be ##quick -- only one allocation will be needed. recsize = int(dtype.itemsize * np.product([i for i in shape if i != -1])) blocksize = max(_BLOCKSIZE//recsize, 1)*recsize ##try to estimate file size try: curpos=infile.tell() infile.seek(0, 2) endpos=infile.tell() infile.seek(curpos) except (AttributeError, IOError): initsize=blocksize else: initsize=max(1, (endpos-curpos)//recsize)*recsize buf = np.newbuffer(initsize) bytesread=0 while True: data=infile.read(blocksize) if len(data) != blocksize: ##eof break ##do we have space? if len(buf) < bytesread+blocksize: buf=_resizebuf(buf, len(buf)+blocksize) ## or rather a=resizebuf(a,2*len(a)) ? assert len(buf) >= bytesread+blocksize buf[bytesread:bytesread+blocksize]=data bytesread += blocksize if len(data) % recsize != 0: if sizing == STRICT: raise SizeMismatchError("Filesize does not match specified shape") if sizing == WARN: _warnings.warn("Filesize does not match specified shape", SizeMismatchWarning) try: infile.seek(-(len(data) % recsize), 1) except AttributeError: _warnings.warn("Could not rewind (no seek support)", FileSeekWarning) except IOError: _warnings.warn("Could not rewind (IOError in seek)", FileSeekWarning) datasize = (len(data)//recsize) * recsize if len(buf) != bytesread+datasize: buf=_resizebuf(buf, bytesread+datasize) buf[bytesread:bytesread+datasize]=data[:datasize] ##deduce shape from len(buf) shape = list(shape) uidx = shape.index(-1) shape[uidx]=len(buf) // recsize a = np.ndarray(shape=shape, dtype=type, buffer=buf) if a.dtype.char == '?': np.not_equal(a, 0, a) return a # this function is referenced in the code above but not defined. adding # it back. - phensley def _resizebuf(buf, newsize): "Return a copy of BUF of size NEWSIZE." newbuf = np.newbuffer(newsize) if newsize > len(buf): newbuf[:len(buf)]=buf else: newbuf[:]=buf[:len(newbuf)] return newbuf def fromstring(datastring, type=None, shape=None, typecode=None, dtype=None): dtype = type2dtype(typecode, type, dtype, True) if shape is None: count = -1 else: count = np.product(shape) res = np.fromstring(datastring, dtype=dtype, count=count) if shape is not None: res.shape = shape return res # check_overflow is ignored def fromlist(seq, type=None, shape=None, check_overflow=0, typecode=None, dtype=None): dtype = type2dtype(typecode, type, dtype, False) return np.array(seq, dtype) def array(sequence=None, typecode=None, copy=1, savespace=0, type=None, shape=None, dtype=None): dtype = type2dtype(typecode, type, dtype, 0) if sequence is None: if shape is None: return None if dtype is None: dtype = 'l' return np.empty(shape, dtype) if isinstance(sequence, file): return fromfile(sequence, dtype=dtype, shape=shape) if isinstance(sequence, str): return fromstring(sequence, dtype=dtype, shape=shape) if isinstance(sequence, buffer): arr = np.frombuffer(sequence, dtype=dtype) else: arr = np.array(sequence, dtype, copy=copy) if shape is not None: arr.shape = shape return arr def asarray(seq, type=None, typecode=None, dtype=None): if isinstance(seq, np.ndarray) and type is None and \ typecode is None and dtype is None: return seq return array(seq, type=type, typecode=typecode, copy=0, dtype=dtype) inputarray = asarray def getTypeObject(sequence, type): if type is not None: return type try: return typefrom(np.array(sequence)) except: raise TypeError("Can't determine a reasonable type from sequence") def getShape(shape, *args): try: if shape is () and not args: return () if len(args) > 0: shape = (shape, ) + args else: shape = tuple(shape) dummy = np.array(shape) if not issubclass(dummy.dtype.type, np.integer): raise TypeError if len(dummy) > np.MAXDIMS: raise TypeError except: raise TypeError("Shape must be a sequence of integers") return shape def identity(n, type=None, typecode=None, dtype=None): dtype = type2dtype(typecode, type, dtype, True) return np.identity(n, dtype) def info(obj, output=sys.stdout, numpy=0): if numpy: bp = lambda x: x else: bp = lambda x: int(x) cls = getattr(obj, '__class__', type(obj)) if numpy: nm = getattr(cls, '__name__', cls) else: nm = cls print("class: ", nm, file=output) print("shape: ", obj.shape, file=output) strides = obj.strides print("strides: ", strides, file=output) if not numpy: print("byteoffset: 0", file=output) if len(strides) > 0: bs = obj.strides[0] else: bs = obj.itemsize print("bytestride: ", bs, file=output) print("itemsize: ", obj.itemsize, file=output) print("aligned: ", bp(obj.flags.aligned), file=output) print("contiguous: ", bp(obj.flags.contiguous), file=output) if numpy: print("fortran: ", obj.flags.fortran, file=output) if not numpy: print("buffer: ", repr(obj.data), file=output) if not numpy: extra = " (DEBUG ONLY)" tic = "'" else: extra = "" tic = "" print("data pointer: %s%s" % (hex(obj.ctypes._as_parameter_.value), extra), file=output) print("byteorder: ", end=' ', file=output) endian = obj.dtype.byteorder if endian in ['|', '=']: print("%s%s%s" % (tic, sys.byteorder, tic), file=output) byteswap = False elif endian == '>': print("%sbig%s" % (tic, tic), file=output) byteswap = sys.byteorder != "big" else: print("%slittle%s" % (tic, tic), file=output) byteswap = sys.byteorder != "little" print("byteswap: ", bp(byteswap), file=output) if not numpy: print("type: ", typefrom(obj).name, file=output) else: print("type: %s" % obj.dtype, file=output) #clipmode is ignored if axis is not 0 and array is not 1d def put(array, indices, values, axis=0, clipmode=RAISE): if not isinstance(array, np.ndarray): raise TypeError("put only works on subclass of ndarray") work = asarray(array) if axis == 0: if array.ndim == 1: work.put(indices, values, clipmode) else: work[indices] = values elif isinstance(axis, (int, long, np.integer)): work = work.swapaxes(0, axis) work[indices] = values work = work.swapaxes(0, axis) else: def_axes = list(range(work.ndim)) for x in axis: def_axes.remove(x) axis = list(axis)+def_axes work = work.transpose(axis) work[indices] = values work = work.transpose(axis) def repeat(array, repeats, axis=0): return np.repeat(array, repeats, axis) def reshape(array, shape, *args): if len(args) > 0: shape = (shape,) + args return np.reshape(array, shape) import warnings as _warnings def round(*args, **keys): _warnings.warn("round() is deprecated. Switch to around()", DeprecationWarning) return around(*args, **keys) def sometrue(array, axis=0): return np.sometrue(array, axis) #clipmode is ignored if axis is not an integer def take(array, indices, axis=0, outarr=None, clipmode=RAISE): array = np.asarray(array) if isinstance(axis, (int, long, np.integer)): res = array.take(indices, axis, outarr, clipmode) if outarr is None: return res return else: def_axes = list(range(array.ndim)) for x in axis: def_axes.remove(x) axis = list(axis) + def_axes work = array.transpose(axis) res = work[indices] if outarr is None: return res outarr[...] = res return def tensormultiply(a1, a2): a1, a2 = np.asarray(a1), np.asarray(a2) if (a1.shape[-1] != a2.shape[0]): raise ValueError("Unmatched dimensions") shape = a1.shape[:-1] + a2.shape[1:] return np.reshape(dot(np.reshape(a1, (-1, a1.shape[-1])), np.reshape(a2, (a2.shape[0], -1))), shape) def cumsum(a1, axis=0, out=None, type=None, dim=0): return np.asarray(a1).cumsum(axis, dtype=type, out=out) def cumproduct(a1, axis=0, out=None, type=None, dim=0): return np.asarray(a1).cumprod(axis, dtype=type, out=out) def argmax(x, axis=-1): return np.argmax(x, axis) def argmin(x, axis=-1): return np.argmin(x, axis) def newobj(self, type): if type is None: return np.empty_like(self) else: return np.empty(self.shape, type) def togglebyteorder(self): self.dtype=self.dtype.newbyteorder() def average(a, axis=0, weights=None, returned=0): return np.average(a, axis, weights, returned) numpy-1.8.2/numpy/numarray/nd_image.py0000664000175100017510000000071512370216243021152 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function try: from ndimage import * except ImportError: try: from scipy.ndimage import * except ImportError: msg = \ """The nd_image package is not installed It can be downloaded by checking out the latest source from http://svn.scipy.org/svn/scipy/trunk/Lib/ndimage or by downloading and installing all of SciPy from http://www.scipy.org. """ raise ImportError(msg) numpy-1.8.2/numpy/numarray/setup.py0000664000175100017510000000102312370216243020540 0ustar vagrantvagrant00000000000000from __future__ import division, print_function from os.path import join def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('numarray', parent_package, top_path) config.add_data_files('include/numpy/*') config.add_extension('_capi', sources=['_capi.c'], ) return config if __name__ == '__main__': from numpy.distutils.core import setup setup(configuration=configuration) numpy-1.8.2/numpy/numarray/include/0000775000175100017510000000000012371375427020470 5ustar vagrantvagrant00000000000000numpy-1.8.2/numpy/numarray/include/numpy/0000775000175100017510000000000012371375430021632 5ustar vagrantvagrant00000000000000numpy-1.8.2/numpy/numarray/include/numpy/ieeespecial.h0000664000175100017510000000726312370216243024256 0ustar vagrantvagrant00000000000000/* 32-bit special value ranges */ #if defined(_MSC_VER) #define MKINT(x) (x##UL) #define MKINT64(x) (x##Ui64) #define BIT(x) (1Ui64 << (x)) #else #define MKINT(x) (x##U) #define MKINT64(x) (x##ULL) #define BIT(x) (1ULL << (x)) #endif #define NEG_QUIET_NAN_MIN32 MKINT(0xFFC00001) #define NEG_QUIET_NAN_MAX32 MKINT(0xFFFFFFFF) #define INDETERMINATE_MIN32 MKINT(0xFFC00000) #define INDETERMINATE_MAX32 MKINT(0xFFC00000) #define NEG_SIGNAL_NAN_MIN32 MKINT(0xFF800001) #define NEG_SIGNAL_NAN_MAX32 MKINT(0xFFBFFFFF) #define NEG_INFINITY_MIN32 MKINT(0xFF800000) #define NEG_NORMALIZED_MIN32 MKINT(0x80800000) #define NEG_NORMALIZED_MAX32 MKINT(0xFF7FFFFF) #define NEG_DENORMALIZED_MIN32 MKINT(0x80000001) #define NEG_DENORMALIZED_MAX32 MKINT(0x807FFFFF) #define NEG_ZERO_MIN32 MKINT(0x80000000) #define NEG_ZERO_MAX32 MKINT(0x80000000) #define POS_ZERO_MIN32 MKINT(0x00000000) #define POS_ZERO_MAX32 MKINT(0x00000000) #define POS_DENORMALIZED_MIN32 MKINT(0x00000001) #define POS_DENORMALIZED_MAX32 MKINT(0x007FFFFF) #define POS_NORMALIZED_MIN32 MKINT(0x00800000) #define POS_NORMALIZED_MAX32 MKINT(0x7F7FFFFF) #define POS_INFINITY_MIN32 MKINT(0x7F800000) #define POS_INFINITY_MAX32 MKINT(0x7F800000) #define POS_SIGNAL_NAN_MIN32 MKINT(0x7F800001) #define POS_SIGNAL_NAN_MAX32 MKINT(0x7FBFFFFF) #define POS_QUIET_NAN_MIN32 MKINT(0x7FC00000) #define POS_QUIET_NAN_MAX32 MKINT(0x7FFFFFFF) /* 64-bit special value ranges */ #define NEG_QUIET_NAN_MIN64 MKINT64(0xFFF8000000000001) #define NEG_QUIET_NAN_MAX64 MKINT64(0xFFFFFFFFFFFFFFFF) #define INDETERMINATE_MIN64 MKINT64(0xFFF8000000000000) #define INDETERMINATE_MAX64 MKINT64(0xFFF8000000000000) #define NEG_SIGNAL_NAN_MIN64 MKINT64(0xFFF7FFFFFFFFFFFF) #define NEG_SIGNAL_NAN_MAX64 MKINT64(0xFFF0000000000001) #define NEG_INFINITY_MIN64 MKINT64(0xFFF0000000000000) #define NEG_NORMALIZED_MIN64 MKINT64(0xFFEFFFFFFFFFFFFF) #define NEG_NORMALIZED_MAX64 MKINT64(0x8010000000000000) #define NEG_DENORMALIZED_MIN64 MKINT64(0x800FFFFFFFFFFFFF) #define NEG_DENORMALIZED_MAX64 MKINT64(0x8000000000000001) #define NEG_ZERO_MIN64 MKINT64(0x8000000000000000) #define NEG_ZERO_MAX64 MKINT64(0x8000000000000000) #define POS_ZERO_MIN64 MKINT64(0x0000000000000000) #define POS_ZERO_MAX64 MKINT64(0x0000000000000000) #define POS_DENORMALIZED_MIN64 MKINT64(0x0000000000000001) #define POS_DENORMALIZED_MAX64 MKINT64(0x000FFFFFFFFFFFFF) #define POS_NORMALIZED_MIN64 MKINT64(0x0010000000000000) #define POS_NORMALIZED_MAX64 MKINT64(0x7FEFFFFFFFFFFFFF) #define POS_INFINITY_MIN64 MKINT64(0x7FF0000000000000) #define POS_INFINITY_MAX64 MKINT64(0x7FF0000000000000) #define POS_SIGNAL_NAN_MIN64 MKINT64(0x7FF0000000000001) #define POS_SIGNAL_NAN_MAX64 MKINT64(0x7FF7FFFFFFFFFFFF) #define POS_QUIET_NAN_MIN64 MKINT64(0x7FF8000000000000) #define POS_QUIET_NAN_MAX64 MKINT64(0x7FFFFFFFFFFFFFFF) typedef enum { POS_QNAN_BIT, NEG_QNAN_BIT, POS_SNAN_BIT, NEG_SNAN_BIT, POS_INF_BIT, NEG_INF_BIT, POS_DEN_BIT, NEG_DEN_BIT, POS_NOR_BIT, NEG_NOR_BIT, POS_ZERO_BIT, NEG_ZERO_BIT, INDETERM_BIT, BUG_BIT } ieee_selects; #define MSK_POS_QNAN BIT(POS_QNAN_BIT) #define MSK_POS_SNAN BIT(POS_SNAN_BIT) #define MSK_POS_INF BIT(POS_INF_BIT) #define MSK_POS_DEN BIT(POS_DEN_BIT) #define MSK_POS_NOR BIT(POS_NOR_BIT) #define MSK_POS_ZERO BIT(POS_ZERO_BIT) #define MSK_NEG_QNAN BIT(NEG_QNAN_BIT) #define MSK_NEG_SNAN BIT(NEG_SNAN_BIT) #define MSK_NEG_INF BIT(NEG_INF_BIT) #define MSK_NEG_DEN BIT(NEG_DEN_BIT) #define MSK_NEG_NOR BIT(NEG_NOR_BIT) #define MSK_NEG_ZERO BIT(NEG_ZERO_BIT) #define MSK_INDETERM BIT(INDETERM_BIT) #define MSK_BUG BIT(BUG_BIT) numpy-1.8.2/numpy/numarray/include/numpy/numcomplex.h0000664000175100017510000003237112370216243024173 0ustar vagrantvagrant00000000000000/* See numarray.h for Complex32, Complex64: typedef struct { Float32 r, i; } Complex32; typedef struct { Float64 r, i; } Complex64; */ typedef struct { Float32 a, theta; } PolarComplex32; typedef struct { Float64 a, theta; } PolarComplex64; #define NUM_SQ(x) ((x)*(x)) #define NUM_CABSSQ(p) (NUM_SQ((p).r) + NUM_SQ((p).i)) #define NUM_CABS(p) sqrt(NUM_CABSSQ(p)) #define NUM_C_TO_P(c, p) (p).a = NUM_CABS(c); \ (p).theta = atan2((c).i, (c).r); #define NUM_P_TO_C(p, c) (c).r = (p).a*cos((p).theta); \ (c).i = (p).a*sin((p).theta); #define NUM_CASS(p, q) (q).r = (p).r, (q).i = (p).i #define NUM_CADD(p, q, s) (s).r = (p).r + (q).r, \ (s).i = (p).i + (q).i #define NUM_CSUB(p, q, s) (s).r = (p).r - (q).r, \ (s).i = (p).i - (q).i #define NUM_CMUL(p, q, s) \ { Float64 rp = (p).r; \ Float64 rq = (q).r; \ (s).r = rp*rq - (p).i*(q).i; \ (s).i = rp*(q).i + rq*(p).i; \ } #define NUM_CDIV(p, q, s) \ { \ Float64 rp = (p).r; \ Float64 ip = (p).i; \ Float64 rq = (q).r; \ if ((q).i != 0) { \ Float64 temp = NUM_CABSSQ(q); \ (s).r = (rp*rq+(p).i*(q).i)/temp; \ (s).i = (rq*(p).i-(q).i*rp)/temp; \ } else { \ (s).r = rp/rq; \ (s).i = ip/rq; \ } \ } #define NUM_CREM(p, q, s) \ { Complex64 r; \ NUM_CDIV(p, q, r); \ r.r = floor(r.r); \ r.i = 0; \ NUM_CMUL(r, q, r); \ NUM_CSUB(p, r, s); \ } #define NUM_CMINUS(p, s) (s).r = -(p).r; (s).i = -(p).i; #define NUM_CNEG NUM_CMINUS #define NUM_CEQ(p, q) (((p).r == (q).r) && ((p).i == (q).i)) #define NUM_CNE(p, q) (((p).r != (q).r) || ((p).i != (q).i)) #define NUM_CLT(p, q) ((p).r < (q).r) #define NUM_CGT(p, q) ((p).r > (q).r) #define NUM_CLE(p, q) ((p).r <= (q).r) #define NUM_CGE(p, q) ((p).r >= (q).r) /* e**z = e**x * (cos(y)+ i*sin(y)) where z = x + i*y so e**z = e**x * cos(y) + i * e**x * sin(y) */ #define NUM_CEXP(p, s) \ { Float64 ex = exp((p).r); \ (s).r = ex * cos((p).i); \ (s).i = ex * sin((p).i); \ } /* e**w = z; w = u + i*v; z = r * e**(i*theta); e**u * e**(i*v) = r * e**(i*theta); log(z) = w; log(z) = log(r) + i*theta; */ #define NUM_CLOG(p, s) \ { PolarComplex64 temp; NUM_C_TO_P(p, temp); \ (s).r = num_log(temp.a); \ (s).i = temp.theta; \ } #define NUM_LOG10_E 0.43429448190325182 #define NUM_CLOG10(p, s) \ { NUM_CLOG(p, s); \ (s).r *= NUM_LOG10_E; \ (s).i *= NUM_LOG10_E; \ } /* s = p ** q */ #define NUM_CPOW(p, q, s) { if (NUM_CABSSQ(p) == 0) { \ if ((q).r == 0 && (q).i == 0) { \ (s).r = (s).i = 1; \ } else { \ (s).r = (s).i = 0; \ } \ } else { \ NUM_CLOG(p, s); \ NUM_CMUL(s, q, s); \ NUM_CEXP(s, s); \ } \ } #define NUM_CSQRT(p, s) { Complex64 temp; temp.r = 0.5; temp.i=0; \ NUM_CPOW(p, temp, s); \ } #define NUM_CSQR(p, s) { Complex64 temp; temp.r = 2.0; temp.i=0; \ NUM_CPOW(p, temp, s); \ } #define NUM_CSIN(p, s) { Float64 sp = sin((p).r); \ Float64 cp = cos((p).r); \ (s).r = cosh((p).i) * sp; \ (s).i = sinh((p).i) * cp; \ } #define NUM_CCOS(p, s) { Float64 sp = sin((p).r); \ Float64 cp = cos((p).r); \ (s).r = cosh((p).i) * cp; \ (s).i = -sinh((p).i) * sp; \ } #define NUM_CTAN(p, s) { Complex64 ss, cs; \ NUM_CSIN(p, ss); \ NUM_CCOS(p, cs); \ NUM_CDIV(ss, cs, s); \ } #define NUM_CSINH(p, s) { Float64 sp = sin((p).i); \ Float64 cp = cos((p).i); \ (s).r = sinh((p).r) * cp; \ (s).i = cosh((p).r) * sp; \ } #define NUM_CCOSH(p, s) { Float64 sp = sin((p).i); \ Float64 cp = cos((p).i); \ (s).r = cosh((p).r) * cp; \ (s).i = sinh((p).r) * sp; \ } #define NUM_CTANH(p, s) { Complex64 ss, cs; \ NUM_CSINH(p, ss); \ NUM_CCOSH(p, cs); \ NUM_CDIV(ss, cs, s); \ } #define NUM_CRPOW(p, v, s) { Complex64 cr; cr.r = v; cr.i = 0; \ NUM_CPOW(p,cr,s); \ } #define NUM_CRMUL(p, v, s) (s).r = (p).r * v; (s).i = (p).i * v; #define NUM_CIMUL(p, s) { Float64 temp = (s).r; \ (s).r = -(p).i; (s).i = temp; \ } /* asin(z) = -i * log(i*z + (1 - z**2)**0.5) */ #define NUM_CASIN(p, s) { Complex64 p1; NUM_CASS(p, p1); \ NUM_CIMUL(p, p1); \ NUM_CMUL(p, p, s); \ NUM_CNEG(s, s); \ (s).r += 1; \ NUM_CRPOW(s, 0.5, s); \ NUM_CADD(p1, s, s); \ NUM_CLOG(s, s); \ NUM_CIMUL(s, s); \ NUM_CNEG(s, s); \ } /* acos(z) = -i * log(z + i*(1 - z**2)**0.5) */ #define NUM_CACOS(p, s) { Complex64 p1; NUM_CASS(p, p1); \ NUM_CMUL(p, p, s); \ NUM_CNEG(s, s); \ (s).r += 1; \ NUM_CRPOW(s, 0.5, s); \ NUM_CIMUL(s, s); \ NUM_CADD(p1, s, s); \ NUM_CLOG(s, s); \ NUM_CIMUL(s, s); \ NUM_CNEG(s, s); \ } /* atan(z) = i/2 * log( (i+z) / (i - z) ) */ #define NUM_CATAN(p, s) { Complex64 p1, p2; \ NUM_CASS(p, p1); NUM_CNEG(p, p2); \ p1.i += 1; \ p2.i += 1; \ NUM_CDIV(p1, p2, s); \ NUM_CLOG(s, s); \ NUM_CIMUL(s, s); \ NUM_CRMUL(s, 0.5, s); \ } /* asinh(z) = log( z + (z**2 + 1)**0.5 ) */ #define NUM_CASINH(p, s) { Complex64 p1; NUM_CASS(p, p1); \ NUM_CMUL(p, p, s); \ (s).r += 1; \ NUM_CRPOW(s, 0.5, s); \ NUM_CADD(p1, s, s); \ NUM_CLOG(s, s); \ } /* acosh(z) = log( z + (z**2 - 1)**0.5 ) */ #define NUM_CACOSH(p, s) { Complex64 p1; NUM_CASS(p, p1); \ NUM_CMUL(p, p, s); \ (s).r -= 1; \ NUM_CRPOW(s, 0.5, s); \ NUM_CADD(p1, s, s); \ NUM_CLOG(s, s); \ } /* atanh(z) = 1/2 * log( (1+z)/(1-z) ) */ #define NUM_CATANH(p, s) { Complex64 p1, p2; \ NUM_CASS(p, p1); NUM_CNEG(p, p2); \ p1.r += 1; \ p2.r += 1; \ NUM_CDIV(p1, p2, s); \ NUM_CLOG(s, s); \ NUM_CRMUL(s, 0.5, s); \ } #define NUM_CMIN(p, q) (NUM_CLE(p, q) ? p : q) #define NUM_CMAX(p, q) (NUM_CGE(p, q) ? p : q) #define NUM_CNZ(p) (((p).r != 0) || ((p).i != 0)) #define NUM_CLAND(p, q) (NUM_CNZ(p) & NUM_CNZ(q)) #define NUM_CLOR(p, q) (NUM_CNZ(p) | NUM_CNZ(q)) #define NUM_CLXOR(p, q) (NUM_CNZ(p) ^ NUM_CNZ(q)) #define NUM_CLNOT(p) (!NUM_CNZ(p)) #define NUM_CFLOOR(p, s) (s).r = floor((p).r); (s).i = floor((p).i); #define NUM_CCEIL(p, s) (s).r = ceil((p).r); (s).i = ceil((p).i); #define NUM_CFABS(p, s) (s).r = fabs((p).r); (s).i = fabs((p).i); #define NUM_CROUND(p, s) (s).r = num_round((p).r); (s).i = num_round((p).i); #define NUM_CHYPOT(p, q, s) { Complex64 t; \ NUM_CSQR(p, s); NUM_CSQR(q, t); \ NUM_CADD(s, t, s); \ NUM_CSQRT(s, s); \ } numpy-1.8.2/numpy/numarray/include/numpy/nummacro.h0000664000175100017510000003542612370216243023631 0ustar vagrantvagrant00000000000000/* Primarily for compatibility with numarray C-API */ #if !defined(_ndarraymacro) #define _ndarraymacro /* The structs defined here are private implementation details of numarray which are subject to change w/o notice. */ #define PY_BOOL_CHAR "b" #define PY_INT8_CHAR "b" #define PY_INT16_CHAR "h" #define PY_INT32_CHAR "i" #define PY_FLOAT32_CHAR "f" #define PY_FLOAT64_CHAR "d" #define PY_UINT8_CHAR "h" #define PY_UINT16_CHAR "i" #define PY_UINT32_CHAR "i" /* Unless longer int available */ #define PY_COMPLEX64_CHAR "D" #define PY_COMPLEX128_CHAR "D" #define PY_LONG_CHAR "l" #define PY_LONG_LONG_CHAR "L" #define pyFPE_DIVIDE_BY_ZERO 1 #define pyFPE_OVERFLOW 2 #define pyFPE_UNDERFLOW 4 #define pyFPE_INVALID 8 #define isNonZERO(x) (x != 0) /* to convert values to boolean 1's or 0's */ typedef enum { NUM_CONTIGUOUS=1, NUM_NOTSWAPPED=0x0200, NUM_ALIGNED=0x0100, NUM_WRITABLE=0x0400, NUM_COPY=0x0020, NUM_C_ARRAY = (NUM_CONTIGUOUS | NUM_ALIGNED | NUM_NOTSWAPPED), NUM_UNCONVERTED = 0 } NumRequirements; #define UNCONVERTED 0 #define C_ARRAY (NUM_CONTIGUOUS | NUM_NOTSWAPPED | NUM_ALIGNED) #define MUST_BE_COMPUTED 2 #define NUM_FLOORDIVIDE(a,b,out) (out) = floor((a)/(b)) #define NA_Begin() Py_Initialize(); import_libnumarray(); #define NA_End() NA_Done(); Py_Finalize(); #define NA_OFFSETDATA(num) ((void *) PyArray_DATA(num)) /* unaligned NA_COPY functions */ #define NA_COPY1(i, o) (*(o) = *(i)) #define NA_COPY2(i, o) NA_COPY1(i, o), NA_COPY1(i+1, o+1) #define NA_COPY4(i, o) NA_COPY2(i, o), NA_COPY2(i+2, o+2) #define NA_COPY8(i, o) NA_COPY4(i, o), NA_COPY4(i+4, o+4) #define NA_COPY16(i, o) NA_COPY8(i, o), NA_COPY8(i+8, o+8) /* byteswapping macros: these fail if i==o */ #define NA_SWAP1(i, o) NA_COPY1(i, o) #define NA_SWAP2(i, o) NA_SWAP1(i, o+1), NA_SWAP1(i+1, o) #define NA_SWAP4(i, o) NA_SWAP2(i, o+2), NA_SWAP2(i+2, o) #define NA_SWAP8(i, o) NA_SWAP4(i, o+4), NA_SWAP4(i+4, o) #define NA_SWAP16(i, o) NA_SWAP8(i, o+8), NA_SWAP8(i+8, o) /* complex byteswaps must swap each part (real, imag) independently */ #define NA_COMPLEX_SWAP8(i, o) NA_SWAP4(i, o), NA_SWAP4(i+4, o+4) #define NA_COMPLEX_SWAP16(i, o) NA_SWAP8(i, o), NA_SWAP8(i+8, o+8) /* byteswapping macros: these work even if i == o */ #define NA_TSWAP1(i, o, t) NA_COPY1(i, t), NA_SWAP1(t, o) #define NA_TSWAP2(i, o, t) NA_COPY2(i, t), NA_SWAP2(t, o) #define NA_TSWAP4(i, o, t) NA_COPY4(i, t), NA_SWAP4(t, o) #define NA_TSWAP8(i, o, t) NA_COPY8(i, t), NA_SWAP8(t, o) /* fast copy functions for %N aligned i and o */ #define NA_ACOPY1(i, o) (((Int8 *)o)[0] = ((Int8 *)i)[0]) #define NA_ACOPY2(i, o) (((Int16 *)o)[0] = ((Int16 *)i)[0]) #define NA_ACOPY4(i, o) (((Int32 *)o)[0] = ((Int32 *)i)[0]) #define NA_ACOPY8(i, o) (((Float64 *)o)[0] = ((Float64 *)i)[0]) #define NA_ACOPY16(i, o) (((Complex64 *)o)[0] = ((Complex64 *)i)[0]) /* from here down, type("ai") is NDInfo* */ #define NA_PTR(ai) ((char *) NA_OFFSETDATA((ai))) #define NA_PTR1(ai, i) (NA_PTR(ai) + \ (i)*PyArray_STRIDES(ai)[0]) #define NA_PTR2(ai, i, j) (NA_PTR(ai) + \ (i)*PyArray_STRIDES(ai)[0] + \ (j)*PyArray_STRIDES(ai)[1]) #define NA_PTR3(ai, i, j, k) (NA_PTR(ai) + \ (i)*PyArray_STRIDES(ai)[0] + \ (j)*PyArray_STRIDES(ai)[1] + \ (k)*PyArray_STRIDES(ai)[2]) #define NA_SET_TEMP(ai, type, v) (((type *) &__temp__)[0] = v) #define NA_SWAPComplex64 NA_COMPLEX_SWAP16 #define NA_SWAPComplex32 NA_COMPLEX_SWAP8 #define NA_SWAPFloat64 NA_SWAP8 #define NA_SWAPFloat32 NA_SWAP4 #define NA_SWAPInt64 NA_SWAP8 #define NA_SWAPUInt64 NA_SWAP8 #define NA_SWAPInt32 NA_SWAP4 #define NA_SWAPUInt32 NA_SWAP4 #define NA_SWAPInt16 NA_SWAP2 #define NA_SWAPUInt16 NA_SWAP2 #define NA_SWAPInt8 NA_SWAP1 #define NA_SWAPUInt8 NA_SWAP1 #define NA_SWAPBool NA_SWAP1 #define NA_COPYComplex64 NA_COPY16 #define NA_COPYComplex32 NA_COPY8 #define NA_COPYFloat64 NA_COPY8 #define NA_COPYFloat32 NA_COPY4 #define NA_COPYInt64 NA_COPY8 #define NA_COPYUInt64 NA_COPY8 #define NA_COPYInt32 NA_COPY4 #define NA_COPYUInt32 NA_COPY4 #define NA_COPYInt16 NA_COPY2 #define NA_COPYUInt16 NA_COPY2 #define NA_COPYInt8 NA_COPY1 #define NA_COPYUInt8 NA_COPY1 #define NA_COPYBool NA_COPY1 #ifdef __cplusplus extern "C" { #endif #define _makeGetPb(type) \ static type _NA_GETPb_##type(char *ptr) \ { \ type temp; \ NA_SWAP##type(ptr, (char *)&temp); \ return temp; \ } #define _makeGetPa(type) \ static type _NA_GETPa_##type(char *ptr) \ { \ type temp; \ NA_COPY##type(ptr, (char *)&temp); \ return temp; \ } _makeGetPb(Complex64) _makeGetPb(Complex32) _makeGetPb(Float64) _makeGetPb(Float32) _makeGetPb(Int64) _makeGetPb(UInt64) _makeGetPb(Int32) _makeGetPb(UInt32) _makeGetPb(Int16) _makeGetPb(UInt16) _makeGetPb(Int8) _makeGetPb(UInt8) _makeGetPb(Bool) _makeGetPa(Complex64) _makeGetPa(Complex32) _makeGetPa(Float64) _makeGetPa(Float32) _makeGetPa(Int64) _makeGetPa(UInt64) _makeGetPa(Int32) _makeGetPa(UInt32) _makeGetPa(Int16) _makeGetPa(UInt16) _makeGetPa(Int8) _makeGetPa(UInt8) _makeGetPa(Bool) #undef _makeGetPb #undef _makeGetPa #define _makeSetPb(type) \ static void _NA_SETPb_##type(char *ptr, type v) \ { \ NA_SWAP##type(((char *)&v), ptr); \ return; \ } #define _makeSetPa(type) \ static void _NA_SETPa_##type(char *ptr, type v) \ { \ NA_COPY##type(((char *)&v), ptr); \ return; \ } _makeSetPb(Complex64) _makeSetPb(Complex32) _makeSetPb(Float64) _makeSetPb(Float32) _makeSetPb(Int64) _makeSetPb(UInt64) _makeSetPb(Int32) _makeSetPb(UInt32) _makeSetPb(Int16) _makeSetPb(UInt16) _makeSetPb(Int8) _makeSetPb(UInt8) _makeSetPb(Bool) _makeSetPa(Complex64) _makeSetPa(Complex32) _makeSetPa(Float64) _makeSetPa(Float32) _makeSetPa(Int64) _makeSetPa(UInt64) _makeSetPa(Int32) _makeSetPa(UInt32) _makeSetPa(Int16) _makeSetPa(UInt16) _makeSetPa(Int8) _makeSetPa(UInt8) _makeSetPa(Bool) #undef _makeSetPb #undef _makeSetPa #ifdef __cplusplus } #endif /* ========================== ptr get/set ================================ */ /* byteswapping */ #define NA_GETPb(ai, type, ptr) _NA_GETPb_##type(ptr) /* aligning */ #define NA_GETPa(ai, type, ptr) _NA_GETPa_##type(ptr) /* fast (aligned, !byteswapped) */ #define NA_GETPf(ai, type, ptr) (*((type *) (ptr))) #define NA_GETP(ai, type, ptr) \ (PyArray_ISCARRAY(ai) ? NA_GETPf(ai, type, ptr) \ : (PyArray_ISBYTESWAPPED(ai) ? \ NA_GETPb(ai, type, ptr) \ : NA_GETPa(ai, type, ptr))) /* NOTE: NA_SET* macros cannot be used as values. */ /* byteswapping */ #define NA_SETPb(ai, type, ptr, v) _NA_SETPb_##type(ptr, v) /* aligning */ #define NA_SETPa(ai, type, ptr, v) _NA_SETPa_##type(ptr, v) /* fast (aligned, !byteswapped) */ #define NA_SETPf(ai, type, ptr, v) ((*((type *) ptr)) = (v)) #define NA_SETP(ai, type, ptr, v) \ if (PyArray_ISCARRAY(ai)) { \ NA_SETPf((ai), type, (ptr), (v)); \ } else if (PyArray_ISBYTESWAPPED(ai)) { \ NA_SETPb((ai), type, (ptr), (v)); \ } else \ NA_SETPa((ai), type, (ptr), (v)) /* ========================== 1 index get/set ============================ */ /* byteswapping */ #define NA_GET1b(ai, type, i) NA_GETPb(ai, type, NA_PTR1(ai, i)) /* aligning */ #define NA_GET1a(ai, type, i) NA_GETPa(ai, type, NA_PTR1(ai, i)) /* fast (aligned, !byteswapped) */ #define NA_GET1f(ai, type, i) NA_GETPf(ai, type, NA_PTR1(ai, i)) /* testing */ #define NA_GET1(ai, type, i) NA_GETP(ai, type, NA_PTR1(ai, i)) /* byteswapping */ #define NA_SET1b(ai, type, i, v) NA_SETPb(ai, type, NA_PTR1(ai, i), v) /* aligning */ #define NA_SET1a(ai, type, i, v) NA_SETPa(ai, type, NA_PTR1(ai, i), v) /* fast (aligned, !byteswapped) */ #define NA_SET1f(ai, type, i, v) NA_SETPf(ai, type, NA_PTR1(ai, i), v) /* testing */ #define NA_SET1(ai, type, i, v) NA_SETP(ai, type, NA_PTR1(ai, i), v) /* ========================== 2 index get/set ============================= */ /* byteswapping */ #define NA_GET2b(ai, type, i, j) NA_GETPb(ai, type, NA_PTR2(ai, i, j)) /* aligning */ #define NA_GET2a(ai, type, i, j) NA_GETPa(ai, type, NA_PTR2(ai, i, j)) /* fast (aligned, !byteswapped) */ #define NA_GET2f(ai, type, i, j) NA_GETPf(ai, type, NA_PTR2(ai, i, j)) /* testing */ #define NA_GET2(ai, type, i, j) NA_GETP(ai, type, NA_PTR2(ai, i, j)) /* byteswapping */ #define NA_SET2b(ai, type, i, j, v) NA_SETPb(ai, type, NA_PTR2(ai, i, j), v) /* aligning */ #define NA_SET2a(ai, type, i, j, v) NA_SETPa(ai, type, NA_PTR2(ai, i, j), v) /* fast (aligned, !byteswapped) */ #define NA_SET2f(ai, type, i, j, v) NA_SETPf(ai, type, NA_PTR2(ai, i, j), v) #define NA_SET2(ai, type, i, j, v) NA_SETP(ai, type, NA_PTR2(ai, i, j), v) /* ========================== 3 index get/set ============================= */ /* byteswapping */ #define NA_GET3b(ai, type, i, j, k) NA_GETPb(ai, type, NA_PTR3(ai, i, j, k)) /* aligning */ #define NA_GET3a(ai, type, i, j, k) NA_GETPa(ai, type, NA_PTR3(ai, i, j, k)) /* fast (aligned, !byteswapped) */ #define NA_GET3f(ai, type, i, j, k) NA_GETPf(ai, type, NA_PTR3(ai, i, j, k)) /* testing */ #define NA_GET3(ai, type, i, j, k) NA_GETP(ai, type, NA_PTR3(ai, i, j, k)) /* byteswapping */ #define NA_SET3b(ai, type, i, j, k, v) \ NA_SETPb(ai, type, NA_PTR3(ai, i, j, k), v) /* aligning */ #define NA_SET3a(ai, type, i, j, k, v) \ NA_SETPa(ai, type, NA_PTR3(ai, i, j, k), v) /* fast (aligned, !byteswapped) */ #define NA_SET3f(ai, type, i, j, k, v) \ NA_SETPf(ai, type, NA_PTR3(ai, i, j, k), v) #define NA_SET3(ai, type, i, j, k, v) \ NA_SETP(ai, type, NA_PTR3(ai, i, j, k), v) /* ========================== 1D get/set ================================== */ #define NA_GET1Db(ai, type, base, cnt, out) \ { int i, stride = PyArray_STRIDES(ai)[PyArray_NDIM(ai)-1]; \ for(i=0; i=(y)) ? (x) : (y)) #endif #if !defined(ABS) #define ABS(x) (((x) >= 0) ? (x) : -(x)) #endif #define ELEM(x) (sizeof(x)/sizeof(x[0])) #define BOOLEAN_BITWISE_NOT(x) ((x) ^ 1) #define NA_NBYTES(a) (PyArray_DESCR(a)->elsize * NA_elements(a)) #if defined(NA_SMP) #define BEGIN_THREADS Py_BEGIN_ALLOW_THREADS #define END_THREADS Py_END_ALLOW_THREADS #else #define BEGIN_THREADS #define END_THREADS #endif #if !defined(NA_isnan) #define U32(u) (* (Int32 *) &(u) ) #define U64(u) (* (Int64 *) &(u) ) #define NA_isnan32(u) \ ( (( U32(u) & 0x7f800000) == 0x7f800000) && ((U32(u) & 0x007fffff) != 0)) ? 1:0 #if !defined(_MSC_VER) #define NA_isnan64(u) \ ( (( U64(u) & 0x7ff0000000000000LL) == 0x7ff0000000000000LL) && ((U64(u) & 0x000fffffffffffffLL) != 0)) ? 1:0 #else #define NA_isnan64(u) \ ( (( U64(u) & 0x7ff0000000000000i64) == 0x7ff0000000000000i64) && ((U64(u) & 0x000fffffffffffffi64) != 0)) ? 1:0 #endif #define NA_isnanC32(u) (NA_isnan32(((Complex32 *)&(u))->r) || NA_isnan32(((Complex32 *)&(u))->i)) #define NA_isnanC64(u) (NA_isnan64(((Complex64 *)&(u))->r) || NA_isnan64(((Complex64 *)&(u))->i)) #endif /* NA_isnan */ #endif /* _ndarraymacro */ numpy-1.8.2/numpy/numarray/include/numpy/arraybase.h0000664000175100017510000000310412370216243023745 0ustar vagrantvagrant00000000000000#if !defined(__arraybase_h) #define _arraybase_h 1 #define SZ_BUF 79 #define MAXDIM NPY_MAXDIMS #define MAXARGS 18 typedef npy_intp maybelong; typedef npy_bool Bool; typedef npy_int8 Int8; typedef npy_uint8 UInt8; typedef npy_int16 Int16; typedef npy_uint16 UInt16; typedef npy_int32 Int32; typedef npy_uint32 UInt32; typedef npy_int64 Int64; typedef npy_uint64 UInt64; typedef npy_float32 Float32; typedef npy_float64 Float64; typedef enum { tAny = -1, tBool = NPY_BOOL, tInt8 = NPY_INT8, tUInt8 = NPY_UINT8, tInt16 = NPY_INT16, tUInt16 = NPY_UINT16, tInt32 = NPY_INT32, tUInt32 = NPY_UINT32, tInt64 = NPY_INT64, tUInt64 = NPY_UINT64, tFloat32 = NPY_FLOAT32, tFloat64 = NPY_FLOAT64, tComplex32 = NPY_COMPLEX64, tComplex64 = NPY_COMPLEX128, tObject = NPY_OBJECT, /* placeholder... does nothing */ tMaxType = NPY_NTYPES, tDefault = tFloat64, #if NPY_BITSOF_LONG == 64 tLong = tInt64, #else tLong = tInt32, #endif } NumarrayType; #define nNumarrayType PyArray_NTYPES #define HAS_UINT64 1 typedef enum { NUM_LITTLE_ENDIAN=0, NUM_BIG_ENDIAN = 1 } NumarrayByteOrder; typedef struct { Float32 r, i; } Complex32; typedef struct { Float64 r, i; } Complex64; #define WRITABLE NPY_WRITEABLE #define CHECKOVERFLOW 0x800 #define UPDATEDICT 0x1000 #define FORTRAN_CONTIGUOUS NPY_FORTRAN #define IS_CARRAY (NPY_CONTIGUOUS | NPY_ALIGNED) #define PyArray(m) ((PyArrayObject *)(m)) #define PyArray_ISFORTRAN_CONTIGUOUS(m) (((PyArray(m))->flags & FORTRAN_CONTIGUOUS) != 0) #define PyArray_ISWRITABLE PyArray_ISWRITEABLE #endif numpy-1.8.2/numpy/numarray/include/numpy/libnumarray.h0000664000175100017510000011311612370216243024326 0ustar vagrantvagrant00000000000000/* Compatibility with numarray. Do not use in new code. */ #ifndef NUMPY_LIBNUMARRAY_H #define NUMPY_LIBNUMARRAY_H #include "numpy/arrayobject.h" #include "arraybase.h" #include "nummacro.h" #include "numcomplex.h" #include "ieeespecial.h" #include "cfunc.h" #ifdef __cplusplus extern "C" { #endif /* Header file for libnumarray */ #if !defined(_libnumarray_MODULE) /* Extensions constructed from seperate compilation units can access the C-API defined here by defining "libnumarray_UNIQUE_SYMBOL" to a global name unique to the extension. Doing this circumvents the requirement to import libnumarray into each compilation unit, but is nevertheless mildly discouraged as "outside the Python norm" and potentially leading to problems. Looking around at "existing Python art", most extension modules are monolithic C files, and likely for good reason. */ /* C API address pointer */ #if defined(NO_IMPORT) || defined(NO_IMPORT_ARRAY) extern void **libnumarray_API; #else #if defined(libnumarray_UNIQUE_SYMBOL) void **libnumarray_API; #else static void **libnumarray_API; #endif #endif #if PY_VERSION_HEX >= 0x03000000 #define _import_libnumarray() \ { \ PyObject *module = PyImport_ImportModule("numpy.numarray._capi"); \ if (module != NULL) { \ PyObject *module_dict = PyModule_GetDict(module); \ PyObject *c_api_object = \ PyDict_GetItemString(module_dict, "_C_API"); \ if (c_api_object && PyCapsule_CheckExact(c_api_object)) { \ libnumarray_API = (void **)PyCapsule_GetPointer(c_api_object, NULL); \ } else { \ PyErr_Format(PyExc_ImportError, \ "Can't get API for module 'numpy.numarray._capi'"); \ } \ } \ } #else #define _import_libnumarray() \ { \ PyObject *module = PyImport_ImportModule("numpy.numarray._capi"); \ if (module != NULL) { \ PyObject *module_dict = PyModule_GetDict(module); \ PyObject *c_api_object = \ PyDict_GetItemString(module_dict, "_C_API"); \ if (c_api_object && PyCObject_Check(c_api_object)) { \ libnumarray_API = (void **)PyCObject_AsVoidPtr(c_api_object); \ } else { \ PyErr_Format(PyExc_ImportError, \ "Can't get API for module 'numpy.numarray._capi'"); \ } \ } \ } #endif #define import_libnumarray() _import_libnumarray(); if (PyErr_Occurred()) { PyErr_Print(); PyErr_SetString(PyExc_ImportError, "numpy.numarray._capi failed to import.\n"); return; } #endif #define libnumarray_FatalApiError (Py_FatalError("Call to API function without first calling import_libnumarray() in " __FILE__), NULL) /* Macros defining components of function prototypes */ #ifdef _libnumarray_MODULE /* This section is used when compiling libnumarray */ static PyObject *_Error; static PyObject* getBuffer (PyObject*o); static int isBuffer (PyObject*o); static int getWriteBufferDataPtr (PyObject*o,void**p); static int isBufferWriteable (PyObject*o); static int getReadBufferDataPtr (PyObject*o,void**p); static int getBufferSize (PyObject*o); static double num_log (double x); static double num_log10 (double x); static double num_pow (double x, double y); static double num_acosh (double x); static double num_asinh (double x); static double num_atanh (double x); static double num_round (double x); static int int_dividebyzero_error (long value, long unused); static int int_overflow_error (Float64 value); static int umult64_overflow (UInt64 a, UInt64 b); static int smult64_overflow (Int64 a0, Int64 b0); static void NA_Done (void); static PyArrayObject* NA_NewAll (int ndim, maybelong* shape, NumarrayType type, void* buffer, maybelong byteoffset, maybelong bytestride, int byteorder, int aligned, int writeable); static PyArrayObject* NA_NewAllStrides (int ndim, maybelong* shape, maybelong* strides, NumarrayType type, void* buffer, maybelong byteoffset, int byteorder, int aligned, int writeable); static PyArrayObject* NA_New (void* buffer, NumarrayType type, int ndim,...); static PyArrayObject* NA_Empty (int ndim, maybelong* shape, NumarrayType type); static PyArrayObject* NA_NewArray (void* buffer, NumarrayType type, int ndim, ...); static PyArrayObject* NA_vNewArray (void* buffer, NumarrayType type, int ndim, maybelong *shape); static PyObject* NA_ReturnOutput (PyObject*,PyArrayObject*); static long NA_getBufferPtrAndSize (PyObject*,int,void**); static int NA_checkIo (char*,int,int,int,int); static int NA_checkOneCBuffer (char*,long,void*,long,size_t); static int NA_checkNCBuffers (char*,int,long,void**,long*,Int8*,Int8*); static int NA_checkOneStriding (char*,long,maybelong*,long,maybelong*,long,long,int); static PyObject* NA_new_cfunc (CfuncDescriptor*); static int NA_add_cfunc (PyObject*,char*,CfuncDescriptor*); static PyArrayObject* NA_InputArray (PyObject*,NumarrayType,int); static PyArrayObject* NA_OutputArray (PyObject*,NumarrayType,int); static PyArrayObject* NA_IoArray (PyObject*,NumarrayType,int); static PyArrayObject* NA_OptionalOutputArray (PyObject*,NumarrayType,int,PyArrayObject*); static long NA_get_offset (PyArrayObject*,int,...); static Float64 NA_get_Float64 (PyArrayObject*,long); static void NA_set_Float64 (PyArrayObject*,long,Float64); static Complex64 NA_get_Complex64 (PyArrayObject*,long); static void NA_set_Complex64 (PyArrayObject*,long,Complex64); static Int64 NA_get_Int64 (PyArrayObject*,long); static void NA_set_Int64 (PyArrayObject*,long,Int64); static Float64 NA_get1_Float64 (PyArrayObject*,long); static Float64 NA_get2_Float64 (PyArrayObject*,long,long); static Float64 NA_get3_Float64 (PyArrayObject*,long,long,long); static void NA_set1_Float64 (PyArrayObject*,long,Float64); static void NA_set2_Float64 (PyArrayObject*,long,long,Float64); static void NA_set3_Float64 (PyArrayObject*,long,long,long,Float64); static Complex64 NA_get1_Complex64 (PyArrayObject*,long); static Complex64 NA_get2_Complex64 (PyArrayObject*,long,long); static Complex64 NA_get3_Complex64 (PyArrayObject*,long,long,long); static void NA_set1_Complex64 (PyArrayObject*,long,Complex64); static void NA_set2_Complex64 (PyArrayObject*,long,long,Complex64); static void NA_set3_Complex64 (PyArrayObject*,long,long,long,Complex64); static Int64 NA_get1_Int64 (PyArrayObject*,long); static Int64 NA_get2_Int64 (PyArrayObject*,long,long); static Int64 NA_get3_Int64 (PyArrayObject*,long,long,long); static void NA_set1_Int64 (PyArrayObject*,long,Int64); static void NA_set2_Int64 (PyArrayObject*,long,long,Int64); static void NA_set3_Int64 (PyArrayObject*,long,long,long,Int64); static int NA_get1D_Float64 (PyArrayObject*,long,int,Float64*); static int NA_set1D_Float64 (PyArrayObject*,long,int,Float64*); static int NA_get1D_Int64 (PyArrayObject*,long,int,Int64*); static int NA_set1D_Int64 (PyArrayObject*,long,int,Int64*); static int NA_get1D_Complex64 (PyArrayObject*,long,int,Complex64*); static int NA_set1D_Complex64 (PyArrayObject*,long,int,Complex64*); static int NA_ShapeEqual (PyArrayObject*,PyArrayObject*); static int NA_ShapeLessThan (PyArrayObject*,PyArrayObject*); static int NA_ByteOrder (void); static Bool NA_IeeeSpecial32 (Float32*,Int32*); static Bool NA_IeeeSpecial64 (Float64*,Int32*); static PyArrayObject* NA_updateDataPtr (PyArrayObject*); static char* NA_typeNoToName (int); static int NA_nameToTypeNo (char*); static PyObject* NA_typeNoToTypeObject (int); static PyObject* NA_intTupleFromMaybeLongs (int,maybelong*); static long NA_maybeLongsFromIntTuple (int,maybelong*,PyObject*); static int NA_intTupleProduct (PyObject *obj, long *product); static long NA_isIntegerSequence (PyObject*); static PyObject* NA_setArrayFromSequence (PyArrayObject*,PyObject*); static int NA_maxType (PyObject*); static int NA_isPythonScalar (PyObject *obj); static PyObject* NA_getPythonScalar (PyArrayObject*,long); static int NA_setFromPythonScalar (PyArrayObject*,long,PyObject*); static int NA_NDArrayCheck (PyObject*); static int NA_NumArrayCheck (PyObject*); static int NA_ComplexArrayCheck (PyObject*); static unsigned long NA_elements (PyArrayObject*); static int NA_typeObjectToTypeNo (PyObject*); static int NA_copyArray (PyArrayObject* to, const PyArrayObject* from); static PyArrayObject* NA_copy (PyArrayObject*); static PyObject* NA_getType (PyObject *typeobj_or_name); static PyObject * NA_callCUFuncCore (PyObject *cfunc, long niter, long ninargs, long noutargs, PyObject **BufferObj, long *offset); static PyObject * NA_callStrideConvCFuncCore (PyObject *cfunc, int nshape, maybelong *shape, PyObject *inbuffObj, long inboffset, int nstrides0, maybelong *inbstrides, PyObject *outbuffObj, long outboffset, int nstrides1, maybelong *outbstrides, long nbytes); static void NA_stridesFromShape (int nshape, maybelong *shape, maybelong bytestride, maybelong *strides); static int NA_OperatorCheck (PyObject *obj); static int NA_ConverterCheck (PyObject *obj); static int NA_UfuncCheck (PyObject *obj); static int NA_CfuncCheck (PyObject *obj); static int NA_getByteOffset (PyArrayObject *array, int nindices, maybelong *indices, long *offset); static int NA_swapAxes (PyArrayObject *array, int x, int y); static PyObject * NA_initModuleGlobal (char *module, char *global); static NumarrayType NA_NumarrayType (PyObject *seq); static PyArrayObject * NA_NewAllFromBuffer (int ndim, maybelong *shape, NumarrayType type, PyObject *bufferObject, maybelong byteoffset, maybelong bytestride, int byteorder, int aligned, int writeable); static Float64 * NA_alloc1D_Float64 (PyArrayObject *a, long offset, int cnt); static Int64 * NA_alloc1D_Int64 (PyArrayObject *a, long offset, int cnt); static void NA_updateAlignment (PyArrayObject *self); static void NA_updateContiguous (PyArrayObject *self); static void NA_updateStatus (PyArrayObject *self); static int NA_NumArrayCheckExact (PyObject *op); static int NA_NDArrayCheckExact (PyObject *op); static int NA_OperatorCheckExact (PyObject *op); static int NA_ConverterCheckExact (PyObject *op); static int NA_UfuncCheckExact (PyObject *op); static int NA_CfuncCheckExact (PyObject *op); static char * NA_getArrayData (PyArrayObject *ap); static void NA_updateByteswap (PyArrayObject *ap); static PyArray_Descr * NA_DescrFromType (int type); static PyObject * NA_Cast (PyArrayObject *a, int type); static int NA_checkFPErrors (void); static void NA_clearFPErrors (void); static int NA_checkAndReportFPErrors (char *name); static Bool NA_IeeeMask32 (Float32,Int32); static Bool NA_IeeeMask64 (Float64,Int32); static int _NA_callStridingHelper (PyObject *aux, long dim, long nnumarray, PyArrayObject *numarray[], char *data[], CFUNC_STRIDED_FUNC f); static PyArrayObject * NA_FromDimsStridesDescrAndData (int nd, maybelong *dims, maybelong *strides, PyArray_Descr *descr, char *data); static PyArrayObject * NA_FromDimsTypeAndData (int nd, maybelong *dims, int type, char *data); static PyArrayObject * NA_FromDimsStridesTypeAndData (int nd, maybelong *dims, maybelong *strides, int type, char *data); static int NA_scipy_typestr (NumarrayType t, int byteorder, char *typestr); static PyArrayObject * NA_FromArrayStruct (PyObject *a); #else /* This section is used in modules that use libnumarray */ #define getBuffer (libnumarray_API ? (*(PyObject* (*) (PyObject*o) ) libnumarray_API[ 0 ]) : (*(PyObject* (*) (PyObject*o) ) libnumarray_FatalApiError)) #define isBuffer (libnumarray_API ? (*(int (*) (PyObject*o) ) libnumarray_API[ 1 ]) : (*(int (*) (PyObject*o) ) libnumarray_FatalApiError)) #define getWriteBufferDataPtr (libnumarray_API ? (*(int (*) (PyObject*o,void**p) ) libnumarray_API[ 2 ]) : (*(int (*) (PyObject*o,void**p) ) libnumarray_FatalApiError)) #define isBufferWriteable (libnumarray_API ? (*(int (*) (PyObject*o) ) libnumarray_API[ 3 ]) : (*(int (*) (PyObject*o) ) libnumarray_FatalApiError)) #define getReadBufferDataPtr (libnumarray_API ? (*(int (*) (PyObject*o,void**p) ) libnumarray_API[ 4 ]) : (*(int (*) (PyObject*o,void**p) ) libnumarray_FatalApiError)) #define getBufferSize (libnumarray_API ? (*(int (*) (PyObject*o) ) libnumarray_API[ 5 ]) : (*(int (*) (PyObject*o) ) libnumarray_FatalApiError)) #define num_log (libnumarray_API ? (*(double (*) (double x) ) libnumarray_API[ 6 ]) : (*(double (*) (double x) ) libnumarray_FatalApiError)) #define num_log10 (libnumarray_API ? (*(double (*) (double x) ) libnumarray_API[ 7 ]) : (*(double (*) (double x) ) libnumarray_FatalApiError)) #define num_pow (libnumarray_API ? (*(double (*) (double x, double y) ) libnumarray_API[ 8 ]) : (*(double (*) (double x, double y) ) libnumarray_FatalApiError)) #define num_acosh (libnumarray_API ? (*(double (*) (double x) ) libnumarray_API[ 9 ]) : (*(double (*) (double x) ) libnumarray_FatalApiError)) #define num_asinh (libnumarray_API ? (*(double (*) (double x) ) libnumarray_API[ 10 ]) : (*(double (*) (double x) ) libnumarray_FatalApiError)) #define num_atanh (libnumarray_API ? (*(double (*) (double x) ) libnumarray_API[ 11 ]) : (*(double (*) (double x) ) libnumarray_FatalApiError)) #define num_round (libnumarray_API ? (*(double (*) (double x) ) libnumarray_API[ 12 ]) : (*(double (*) (double x) ) libnumarray_FatalApiError)) #define int_dividebyzero_error (libnumarray_API ? (*(int (*) (long value, long unused) ) libnumarray_API[ 13 ]) : (*(int (*) (long value, long unused) ) libnumarray_FatalApiError)) #define int_overflow_error (libnumarray_API ? (*(int (*) (Float64 value) ) libnumarray_API[ 14 ]) : (*(int (*) (Float64 value) ) libnumarray_FatalApiError)) #define umult64_overflow (libnumarray_API ? (*(int (*) (UInt64 a, UInt64 b) ) libnumarray_API[ 15 ]) : (*(int (*) (UInt64 a, UInt64 b) ) libnumarray_FatalApiError)) #define smult64_overflow (libnumarray_API ? (*(int (*) (Int64 a0, Int64 b0) ) libnumarray_API[ 16 ]) : (*(int (*) (Int64 a0, Int64 b0) ) libnumarray_FatalApiError)) #define NA_Done (libnumarray_API ? (*(void (*) (void) ) libnumarray_API[ 17 ]) : (*(void (*) (void) ) libnumarray_FatalApiError)) #define NA_NewAll (libnumarray_API ? (*(PyArrayObject* (*) (int ndim, maybelong* shape, NumarrayType type, void* buffer, maybelong byteoffset, maybelong bytestride, int byteorder, int aligned, int writeable) ) libnumarray_API[ 18 ]) : (*(PyArrayObject* (*) (int ndim, maybelong* shape, NumarrayType type, void* buffer, maybelong byteoffset, maybelong bytestride, int byteorder, int aligned, int writeable) ) libnumarray_FatalApiError)) #define NA_NewAllStrides (libnumarray_API ? (*(PyArrayObject* (*) (int ndim, maybelong* shape, maybelong* strides, NumarrayType type, void* buffer, maybelong byteoffset, int byteorder, int aligned, int writeable) ) libnumarray_API[ 19 ]) : (*(PyArrayObject* (*) (int ndim, maybelong* shape, maybelong* strides, NumarrayType type, void* buffer, maybelong byteoffset, int byteorder, int aligned, int writeable) ) libnumarray_FatalApiError)) #define NA_New (libnumarray_API ? (*(PyArrayObject* (*) (void* buffer, NumarrayType type, int ndim,...) ) libnumarray_API[ 20 ]) : (*(PyArrayObject* (*) (void* buffer, NumarrayType type, int ndim,...) ) libnumarray_FatalApiError)) #define NA_Empty (libnumarray_API ? (*(PyArrayObject* (*) (int ndim, maybelong* shape, NumarrayType type) ) libnumarray_API[ 21 ]) : (*(PyArrayObject* (*) (int ndim, maybelong* shape, NumarrayType type) ) libnumarray_FatalApiError)) #define NA_NewArray (libnumarray_API ? (*(PyArrayObject* (*) (void* buffer, NumarrayType type, int ndim, ...) ) libnumarray_API[ 22 ]) : (*(PyArrayObject* (*) (void* buffer, NumarrayType type, int ndim, ...) ) libnumarray_FatalApiError)) #define NA_vNewArray (libnumarray_API ? (*(PyArrayObject* (*) (void* buffer, NumarrayType type, int ndim, maybelong *shape) ) libnumarray_API[ 23 ]) : (*(PyArrayObject* (*) (void* buffer, NumarrayType type, int ndim, maybelong *shape) ) libnumarray_FatalApiError)) #define NA_ReturnOutput (libnumarray_API ? (*(PyObject* (*) (PyObject*,PyArrayObject*) ) libnumarray_API[ 24 ]) : (*(PyObject* (*) (PyObject*,PyArrayObject*) ) libnumarray_FatalApiError)) #define NA_getBufferPtrAndSize (libnumarray_API ? (*(long (*) (PyObject*,int,void**) ) libnumarray_API[ 25 ]) : (*(long (*) (PyObject*,int,void**) ) libnumarray_FatalApiError)) #define NA_checkIo (libnumarray_API ? (*(int (*) (char*,int,int,int,int) ) libnumarray_API[ 26 ]) : (*(int (*) (char*,int,int,int,int) ) libnumarray_FatalApiError)) #define NA_checkOneCBuffer (libnumarray_API ? (*(int (*) (char*,long,void*,long,size_t) ) libnumarray_API[ 27 ]) : (*(int (*) (char*,long,void*,long,size_t) ) libnumarray_FatalApiError)) #define NA_checkNCBuffers (libnumarray_API ? (*(int (*) (char*,int,long,void**,long*,Int8*,Int8*) ) libnumarray_API[ 28 ]) : (*(int (*) (char*,int,long,void**,long*,Int8*,Int8*) ) libnumarray_FatalApiError)) #define NA_checkOneStriding (libnumarray_API ? (*(int (*) (char*,long,maybelong*,long,maybelong*,long,long,int) ) libnumarray_API[ 29 ]) : (*(int (*) (char*,long,maybelong*,long,maybelong*,long,long,int) ) libnumarray_FatalApiError)) #define NA_new_cfunc (libnumarray_API ? (*(PyObject* (*) (CfuncDescriptor*) ) libnumarray_API[ 30 ]) : (*(PyObject* (*) (CfuncDescriptor*) ) libnumarray_FatalApiError)) #define NA_add_cfunc (libnumarray_API ? (*(int (*) (PyObject*,char*,CfuncDescriptor*) ) libnumarray_API[ 31 ]) : (*(int (*) (PyObject*,char*,CfuncDescriptor*) ) libnumarray_FatalApiError)) #define NA_InputArray (libnumarray_API ? (*(PyArrayObject* (*) (PyObject*,NumarrayType,int) ) libnumarray_API[ 32 ]) : (*(PyArrayObject* (*) (PyObject*,NumarrayType,int) ) libnumarray_FatalApiError)) #define NA_OutputArray (libnumarray_API ? (*(PyArrayObject* (*) (PyObject*,NumarrayType,int) ) libnumarray_API[ 33 ]) : (*(PyArrayObject* (*) (PyObject*,NumarrayType,int) ) libnumarray_FatalApiError)) #define NA_IoArray (libnumarray_API ? (*(PyArrayObject* (*) (PyObject*,NumarrayType,int) ) libnumarray_API[ 34 ]) : (*(PyArrayObject* (*) (PyObject*,NumarrayType,int) ) libnumarray_FatalApiError)) #define NA_OptionalOutputArray (libnumarray_API ? (*(PyArrayObject* (*) (PyObject*,NumarrayType,int,PyArrayObject*) ) libnumarray_API[ 35 ]) : (*(PyArrayObject* (*) (PyObject*,NumarrayType,int,PyArrayObject*) ) libnumarray_FatalApiError)) #define NA_get_offset (libnumarray_API ? (*(long (*) (PyArrayObject*,int,...) ) libnumarray_API[ 36 ]) : (*(long (*) (PyArrayObject*,int,...) ) libnumarray_FatalApiError)) #define NA_get_Float64 (libnumarray_API ? (*(Float64 (*) (PyArrayObject*,long) ) libnumarray_API[ 37 ]) : (*(Float64 (*) (PyArrayObject*,long) ) libnumarray_FatalApiError)) #define NA_set_Float64 (libnumarray_API ? (*(void (*) (PyArrayObject*,long,Float64) ) libnumarray_API[ 38 ]) : (*(void (*) (PyArrayObject*,long,Float64) ) libnumarray_FatalApiError)) #define NA_get_Complex64 (libnumarray_API ? (*(Complex64 (*) (PyArrayObject*,long) ) libnumarray_API[ 39 ]) : (*(Complex64 (*) (PyArrayObject*,long) ) libnumarray_FatalApiError)) #define NA_set_Complex64 (libnumarray_API ? (*(void (*) (PyArrayObject*,long,Complex64) ) libnumarray_API[ 40 ]) : (*(void (*) (PyArrayObject*,long,Complex64) ) libnumarray_FatalApiError)) #define NA_get_Int64 (libnumarray_API ? (*(Int64 (*) (PyArrayObject*,long) ) libnumarray_API[ 41 ]) : (*(Int64 (*) (PyArrayObject*,long) ) libnumarray_FatalApiError)) #define NA_set_Int64 (libnumarray_API ? (*(void (*) (PyArrayObject*,long,Int64) ) libnumarray_API[ 42 ]) : (*(void (*) (PyArrayObject*,long,Int64) ) libnumarray_FatalApiError)) #define NA_get1_Float64 (libnumarray_API ? (*(Float64 (*) (PyArrayObject*,long) ) libnumarray_API[ 43 ]) : (*(Float64 (*) (PyArrayObject*,long) ) libnumarray_FatalApiError)) #define NA_get2_Float64 (libnumarray_API ? (*(Float64 (*) (PyArrayObject*,long,long) ) libnumarray_API[ 44 ]) : (*(Float64 (*) (PyArrayObject*,long,long) ) libnumarray_FatalApiError)) #define NA_get3_Float64 (libnumarray_API ? (*(Float64 (*) (PyArrayObject*,long,long,long) ) libnumarray_API[ 45 ]) : (*(Float64 (*) (PyArrayObject*,long,long,long) ) libnumarray_FatalApiError)) #define NA_set1_Float64 (libnumarray_API ? (*(void (*) (PyArrayObject*,long,Float64) ) libnumarray_API[ 46 ]) : (*(void (*) (PyArrayObject*,long,Float64) ) libnumarray_FatalApiError)) #define NA_set2_Float64 (libnumarray_API ? (*(void (*) (PyArrayObject*,long,long,Float64) ) libnumarray_API[ 47 ]) : (*(void (*) (PyArrayObject*,long,long,Float64) ) libnumarray_FatalApiError)) #define NA_set3_Float64 (libnumarray_API ? (*(void (*) (PyArrayObject*,long,long,long,Float64) ) libnumarray_API[ 48 ]) : (*(void (*) (PyArrayObject*,long,long,long,Float64) ) libnumarray_FatalApiError)) #define NA_get1_Complex64 (libnumarray_API ? (*(Complex64 (*) (PyArrayObject*,long) ) libnumarray_API[ 49 ]) : (*(Complex64 (*) (PyArrayObject*,long) ) libnumarray_FatalApiError)) #define NA_get2_Complex64 (libnumarray_API ? (*(Complex64 (*) (PyArrayObject*,long,long) ) libnumarray_API[ 50 ]) : (*(Complex64 (*) (PyArrayObject*,long,long) ) libnumarray_FatalApiError)) #define NA_get3_Complex64 (libnumarray_API ? (*(Complex64 (*) (PyArrayObject*,long,long,long) ) libnumarray_API[ 51 ]) : (*(Complex64 (*) (PyArrayObject*,long,long,long) ) libnumarray_FatalApiError)) #define NA_set1_Complex64 (libnumarray_API ? (*(void (*) (PyArrayObject*,long,Complex64) ) libnumarray_API[ 52 ]) : (*(void (*) (PyArrayObject*,long,Complex64) ) libnumarray_FatalApiError)) #define NA_set2_Complex64 (libnumarray_API ? (*(void (*) (PyArrayObject*,long,long,Complex64) ) libnumarray_API[ 53 ]) : (*(void (*) (PyArrayObject*,long,long,Complex64) ) libnumarray_FatalApiError)) #define NA_set3_Complex64 (libnumarray_API ? (*(void (*) (PyArrayObject*,long,long,long,Complex64) ) libnumarray_API[ 54 ]) : (*(void (*) (PyArrayObject*,long,long,long,Complex64) ) libnumarray_FatalApiError)) #define NA_get1_Int64 (libnumarray_API ? (*(Int64 (*) (PyArrayObject*,long) ) libnumarray_API[ 55 ]) : (*(Int64 (*) (PyArrayObject*,long) ) libnumarray_FatalApiError)) #define NA_get2_Int64 (libnumarray_API ? (*(Int64 (*) (PyArrayObject*,long,long) ) libnumarray_API[ 56 ]) : (*(Int64 (*) (PyArrayObject*,long,long) ) libnumarray_FatalApiError)) #define NA_get3_Int64 (libnumarray_API ? (*(Int64 (*) (PyArrayObject*,long,long,long) ) libnumarray_API[ 57 ]) : (*(Int64 (*) (PyArrayObject*,long,long,long) ) libnumarray_FatalApiError)) #define NA_set1_Int64 (libnumarray_API ? (*(void (*) (PyArrayObject*,long,Int64) ) libnumarray_API[ 58 ]) : (*(void (*) (PyArrayObject*,long,Int64) ) libnumarray_FatalApiError)) #define NA_set2_Int64 (libnumarray_API ? (*(void (*) (PyArrayObject*,long,long,Int64) ) libnumarray_API[ 59 ]) : (*(void (*) (PyArrayObject*,long,long,Int64) ) libnumarray_FatalApiError)) #define NA_set3_Int64 (libnumarray_API ? (*(void (*) (PyArrayObject*,long,long,long,Int64) ) libnumarray_API[ 60 ]) : (*(void (*) (PyArrayObject*,long,long,long,Int64) ) libnumarray_FatalApiError)) #define NA_get1D_Float64 (libnumarray_API ? (*(int (*) (PyArrayObject*,long,int,Float64*) ) libnumarray_API[ 61 ]) : (*(int (*) (PyArrayObject*,long,int,Float64*) ) libnumarray_FatalApiError)) #define NA_set1D_Float64 (libnumarray_API ? (*(int (*) (PyArrayObject*,long,int,Float64*) ) libnumarray_API[ 62 ]) : (*(int (*) (PyArrayObject*,long,int,Float64*) ) libnumarray_FatalApiError)) #define NA_get1D_Int64 (libnumarray_API ? (*(int (*) (PyArrayObject*,long,int,Int64*) ) libnumarray_API[ 63 ]) : (*(int (*) (PyArrayObject*,long,int,Int64*) ) libnumarray_FatalApiError)) #define NA_set1D_Int64 (libnumarray_API ? (*(int (*) (PyArrayObject*,long,int,Int64*) ) libnumarray_API[ 64 ]) : (*(int (*) (PyArrayObject*,long,int,Int64*) ) libnumarray_FatalApiError)) #define NA_get1D_Complex64 (libnumarray_API ? (*(int (*) (PyArrayObject*,long,int,Complex64*) ) libnumarray_API[ 65 ]) : (*(int (*) (PyArrayObject*,long,int,Complex64*) ) libnumarray_FatalApiError)) #define NA_set1D_Complex64 (libnumarray_API ? (*(int (*) (PyArrayObject*,long,int,Complex64*) ) libnumarray_API[ 66 ]) : (*(int (*) (PyArrayObject*,long,int,Complex64*) ) libnumarray_FatalApiError)) #define NA_ShapeEqual (libnumarray_API ? (*(int (*) (PyArrayObject*,PyArrayObject*) ) libnumarray_API[ 67 ]) : (*(int (*) (PyArrayObject*,PyArrayObject*) ) libnumarray_FatalApiError)) #define NA_ShapeLessThan (libnumarray_API ? (*(int (*) (PyArrayObject*,PyArrayObject*) ) libnumarray_API[ 68 ]) : (*(int (*) (PyArrayObject*,PyArrayObject*) ) libnumarray_FatalApiError)) #define NA_ByteOrder (libnumarray_API ? (*(int (*) (void) ) libnumarray_API[ 69 ]) : (*(int (*) (void) ) libnumarray_FatalApiError)) #define NA_IeeeSpecial32 (libnumarray_API ? (*(Bool (*) (Float32*,Int32*) ) libnumarray_API[ 70 ]) : (*(Bool (*) (Float32*,Int32*) ) libnumarray_FatalApiError)) #define NA_IeeeSpecial64 (libnumarray_API ? (*(Bool (*) (Float64*,Int32*) ) libnumarray_API[ 71 ]) : (*(Bool (*) (Float64*,Int32*) ) libnumarray_FatalApiError)) #define NA_updateDataPtr (libnumarray_API ? (*(PyArrayObject* (*) (PyArrayObject*) ) libnumarray_API[ 72 ]) : (*(PyArrayObject* (*) (PyArrayObject*) ) libnumarray_FatalApiError)) #define NA_typeNoToName (libnumarray_API ? (*(char* (*) (int) ) libnumarray_API[ 73 ]) : (*(char* (*) (int) ) libnumarray_FatalApiError)) #define NA_nameToTypeNo (libnumarray_API ? (*(int (*) (char*) ) libnumarray_API[ 74 ]) : (*(int (*) (char*) ) libnumarray_FatalApiError)) #define NA_typeNoToTypeObject (libnumarray_API ? (*(PyObject* (*) (int) ) libnumarray_API[ 75 ]) : (*(PyObject* (*) (int) ) libnumarray_FatalApiError)) #define NA_intTupleFromMaybeLongs (libnumarray_API ? (*(PyObject* (*) (int,maybelong*) ) libnumarray_API[ 76 ]) : (*(PyObject* (*) (int,maybelong*) ) libnumarray_FatalApiError)) #define NA_maybeLongsFromIntTuple (libnumarray_API ? (*(long (*) (int,maybelong*,PyObject*) ) libnumarray_API[ 77 ]) : (*(long (*) (int,maybelong*,PyObject*) ) libnumarray_FatalApiError)) #define NA_intTupleProduct (libnumarray_API ? (*(int (*) (PyObject *obj, long *product) ) libnumarray_API[ 78 ]) : (*(int (*) (PyObject *obj, long *product) ) libnumarray_FatalApiError)) #define NA_isIntegerSequence (libnumarray_API ? (*(long (*) (PyObject*) ) libnumarray_API[ 79 ]) : (*(long (*) (PyObject*) ) libnumarray_FatalApiError)) #define NA_setArrayFromSequence (libnumarray_API ? (*(PyObject* (*) (PyArrayObject*,PyObject*) ) libnumarray_API[ 80 ]) : (*(PyObject* (*) (PyArrayObject*,PyObject*) ) libnumarray_FatalApiError)) #define NA_maxType (libnumarray_API ? (*(int (*) (PyObject*) ) libnumarray_API[ 81 ]) : (*(int (*) (PyObject*) ) libnumarray_FatalApiError)) #define NA_isPythonScalar (libnumarray_API ? (*(int (*) (PyObject *obj) ) libnumarray_API[ 82 ]) : (*(int (*) (PyObject *obj) ) libnumarray_FatalApiError)) #define NA_getPythonScalar (libnumarray_API ? (*(PyObject* (*) (PyArrayObject*,long) ) libnumarray_API[ 83 ]) : (*(PyObject* (*) (PyArrayObject*,long) ) libnumarray_FatalApiError)) #define NA_setFromPythonScalar (libnumarray_API ? (*(int (*) (PyArrayObject*,long,PyObject*) ) libnumarray_API[ 84 ]) : (*(int (*) (PyArrayObject*,long,PyObject*) ) libnumarray_FatalApiError)) #define NA_NDArrayCheck (libnumarray_API ? (*(int (*) (PyObject*) ) libnumarray_API[ 85 ]) : (*(int (*) (PyObject*) ) libnumarray_FatalApiError)) #define NA_NumArrayCheck (libnumarray_API ? (*(int (*) (PyObject*) ) libnumarray_API[ 86 ]) : (*(int (*) (PyObject*) ) libnumarray_FatalApiError)) #define NA_ComplexArrayCheck (libnumarray_API ? (*(int (*) (PyObject*) ) libnumarray_API[ 87 ]) : (*(int (*) (PyObject*) ) libnumarray_FatalApiError)) #define NA_elements (libnumarray_API ? (*(unsigned long (*) (PyArrayObject*) ) libnumarray_API[ 88 ]) : (*(unsigned long (*) (PyArrayObject*) ) libnumarray_FatalApiError)) #define NA_typeObjectToTypeNo (libnumarray_API ? (*(int (*) (PyObject*) ) libnumarray_API[ 89 ]) : (*(int (*) (PyObject*) ) libnumarray_FatalApiError)) #define NA_copyArray (libnumarray_API ? (*(int (*) (PyArrayObject* to, const PyArrayObject* from) ) libnumarray_API[ 90 ]) : (*(int (*) (PyArrayObject* to, const PyArrayObject* from) ) libnumarray_FatalApiError)) #define NA_copy (libnumarray_API ? (*(PyArrayObject* (*) (PyArrayObject*) ) libnumarray_API[ 91 ]) : (*(PyArrayObject* (*) (PyArrayObject*) ) libnumarray_FatalApiError)) #define NA_getType (libnumarray_API ? (*(PyObject* (*) (PyObject *typeobj_or_name) ) libnumarray_API[ 92 ]) : (*(PyObject* (*) (PyObject *typeobj_or_name) ) libnumarray_FatalApiError)) #define NA_callCUFuncCore (libnumarray_API ? (*(PyObject * (*) (PyObject *cfunc, long niter, long ninargs, long noutargs, PyObject **BufferObj, long *offset) ) libnumarray_API[ 93 ]) : (*(PyObject * (*) (PyObject *cfunc, long niter, long ninargs, long noutargs, PyObject **BufferObj, long *offset) ) libnumarray_FatalApiError)) #define NA_callStrideConvCFuncCore (libnumarray_API ? (*(PyObject * (*) (PyObject *cfunc, int nshape, maybelong *shape, PyObject *inbuffObj, long inboffset, int nstrides0, maybelong *inbstrides, PyObject *outbuffObj, long outboffset, int nstrides1, maybelong *outbstrides, long nbytes) ) libnumarray_API[ 94 ]) : (*(PyObject * (*) (PyObject *cfunc, int nshape, maybelong *shape, PyObject *inbuffObj, long inboffset, int nstrides0, maybelong *inbstrides, PyObject *outbuffObj, long outboffset, int nstrides1, maybelong *outbstrides, long nbytes) ) libnumarray_FatalApiError)) #define NA_stridesFromShape (libnumarray_API ? (*(void (*) (int nshape, maybelong *shape, maybelong bytestride, maybelong *strides) ) libnumarray_API[ 95 ]) : (*(void (*) (int nshape, maybelong *shape, maybelong bytestride, maybelong *strides) ) libnumarray_FatalApiError)) #define NA_OperatorCheck (libnumarray_API ? (*(int (*) (PyObject *obj) ) libnumarray_API[ 96 ]) : (*(int (*) (PyObject *obj) ) libnumarray_FatalApiError)) #define NA_ConverterCheck (libnumarray_API ? (*(int (*) (PyObject *obj) ) libnumarray_API[ 97 ]) : (*(int (*) (PyObject *obj) ) libnumarray_FatalApiError)) #define NA_UfuncCheck (libnumarray_API ? (*(int (*) (PyObject *obj) ) libnumarray_API[ 98 ]) : (*(int (*) (PyObject *obj) ) libnumarray_FatalApiError)) #define NA_CfuncCheck (libnumarray_API ? (*(int (*) (PyObject *obj) ) libnumarray_API[ 99 ]) : (*(int (*) (PyObject *obj) ) libnumarray_FatalApiError)) #define NA_getByteOffset (libnumarray_API ? (*(int (*) (PyArrayObject *array, int nindices, maybelong *indices, long *offset) ) libnumarray_API[ 100 ]) : (*(int (*) (PyArrayObject *array, int nindices, maybelong *indices, long *offset) ) libnumarray_FatalApiError)) #define NA_swapAxes (libnumarray_API ? (*(int (*) (PyArrayObject *array, int x, int y) ) libnumarray_API[ 101 ]) : (*(int (*) (PyArrayObject *array, int x, int y) ) libnumarray_FatalApiError)) #define NA_initModuleGlobal (libnumarray_API ? (*(PyObject * (*) (char *module, char *global) ) libnumarray_API[ 102 ]) : (*(PyObject * (*) (char *module, char *global) ) libnumarray_FatalApiError)) #define NA_NumarrayType (libnumarray_API ? (*(NumarrayType (*) (PyObject *seq) ) libnumarray_API[ 103 ]) : (*(NumarrayType (*) (PyObject *seq) ) libnumarray_FatalApiError)) #define NA_NewAllFromBuffer (libnumarray_API ? (*(PyArrayObject * (*) (int ndim, maybelong *shape, NumarrayType type, PyObject *bufferObject, maybelong byteoffset, maybelong bytestride, int byteorder, int aligned, int writeable) ) libnumarray_API[ 104 ]) : (*(PyArrayObject * (*) (int ndim, maybelong *shape, NumarrayType type, PyObject *bufferObject, maybelong byteoffset, maybelong bytestride, int byteorder, int aligned, int writeable) ) libnumarray_FatalApiError)) #define NA_alloc1D_Float64 (libnumarray_API ? (*(Float64 * (*) (PyArrayObject *a, long offset, int cnt) ) libnumarray_API[ 105 ]) : (*(Float64 * (*) (PyArrayObject *a, long offset, int cnt) ) libnumarray_FatalApiError)) #define NA_alloc1D_Int64 (libnumarray_API ? (*(Int64 * (*) (PyArrayObject *a, long offset, int cnt) ) libnumarray_API[ 106 ]) : (*(Int64 * (*) (PyArrayObject *a, long offset, int cnt) ) libnumarray_FatalApiError)) #define NA_updateAlignment (libnumarray_API ? (*(void (*) (PyArrayObject *self) ) libnumarray_API[ 107 ]) : (*(void (*) (PyArrayObject *self) ) libnumarray_FatalApiError)) #define NA_updateContiguous (libnumarray_API ? (*(void (*) (PyArrayObject *self) ) libnumarray_API[ 108 ]) : (*(void (*) (PyArrayObject *self) ) libnumarray_FatalApiError)) #define NA_updateStatus (libnumarray_API ? (*(void (*) (PyArrayObject *self) ) libnumarray_API[ 109 ]) : (*(void (*) (PyArrayObject *self) ) libnumarray_FatalApiError)) #define NA_NumArrayCheckExact (libnumarray_API ? (*(int (*) (PyObject *op) ) libnumarray_API[ 110 ]) : (*(int (*) (PyObject *op) ) libnumarray_FatalApiError)) #define NA_NDArrayCheckExact (libnumarray_API ? (*(int (*) (PyObject *op) ) libnumarray_API[ 111 ]) : (*(int (*) (PyObject *op) ) libnumarray_FatalApiError)) #define NA_OperatorCheckExact (libnumarray_API ? (*(int (*) (PyObject *op) ) libnumarray_API[ 112 ]) : (*(int (*) (PyObject *op) ) libnumarray_FatalApiError)) #define NA_ConverterCheckExact (libnumarray_API ? (*(int (*) (PyObject *op) ) libnumarray_API[ 113 ]) : (*(int (*) (PyObject *op) ) libnumarray_FatalApiError)) #define NA_UfuncCheckExact (libnumarray_API ? (*(int (*) (PyObject *op) ) libnumarray_API[ 114 ]) : (*(int (*) (PyObject *op) ) libnumarray_FatalApiError)) #define NA_CfuncCheckExact (libnumarray_API ? (*(int (*) (PyObject *op) ) libnumarray_API[ 115 ]) : (*(int (*) (PyObject *op) ) libnumarray_FatalApiError)) #define NA_getArrayData (libnumarray_API ? (*(char * (*) (PyArrayObject *ap) ) libnumarray_API[ 116 ]) : (*(char * (*) (PyArrayObject *ap) ) libnumarray_FatalApiError)) #define NA_updateByteswap (libnumarray_API ? (*(void (*) (PyArrayObject *ap) ) libnumarray_API[ 117 ]) : (*(void (*) (PyArrayObject *ap) ) libnumarray_FatalApiError)) #define NA_DescrFromType (libnumarray_API ? (*(PyArray_Descr * (*) (int type) ) libnumarray_API[ 118 ]) : (*(PyArray_Descr * (*) (int type) ) libnumarray_FatalApiError)) #define NA_Cast (libnumarray_API ? (*(PyObject * (*) (PyArrayObject *a, int type) ) libnumarray_API[ 119 ]) : (*(PyObject * (*) (PyArrayObject *a, int type) ) libnumarray_FatalApiError)) #define NA_checkFPErrors (libnumarray_API ? (*(int (*) (void) ) libnumarray_API[ 120 ]) : (*(int (*) (void) ) libnumarray_FatalApiError)) #define NA_clearFPErrors (libnumarray_API ? (*(void (*) (void) ) libnumarray_API[ 121 ]) : (*(void (*) (void) ) libnumarray_FatalApiError)) #define NA_checkAndReportFPErrors (libnumarray_API ? (*(int (*) (char *name) ) libnumarray_API[ 122 ]) : (*(int (*) (char *name) ) libnumarray_FatalApiError)) #define NA_IeeeMask32 (libnumarray_API ? (*(Bool (*) (Float32,Int32) ) libnumarray_API[ 123 ]) : (*(Bool (*) (Float32,Int32) ) libnumarray_FatalApiError)) #define NA_IeeeMask64 (libnumarray_API ? (*(Bool (*) (Float64,Int32) ) libnumarray_API[ 124 ]) : (*(Bool (*) (Float64,Int32) ) libnumarray_FatalApiError)) #define _NA_callStridingHelper (libnumarray_API ? (*(int (*) (PyObject *aux, long dim, long nnumarray, PyArrayObject *numarray[], char *data[], CFUNC_STRIDED_FUNC f) ) libnumarray_API[ 125 ]) : (*(int (*) (PyObject *aux, long dim, long nnumarray, PyArrayObject *numarray[], char *data[], CFUNC_STRIDED_FUNC f) ) libnumarray_FatalApiError)) #define NA_FromDimsStridesDescrAndData (libnumarray_API ? (*(PyArrayObject * (*) (int nd, maybelong *dims, maybelong *strides, PyArray_Descr *descr, char *data) ) libnumarray_API[ 126 ]) : (*(PyArrayObject * (*) (int nd, maybelong *dims, maybelong *strides, PyArray_Descr *descr, char *data) ) libnumarray_FatalApiError)) #define NA_FromDimsTypeAndData (libnumarray_API ? (*(PyArrayObject * (*) (int nd, maybelong *dims, int type, char *data) ) libnumarray_API[ 127 ]) : (*(PyArrayObject * (*) (int nd, maybelong *dims, int type, char *data) ) libnumarray_FatalApiError)) #define NA_FromDimsStridesTypeAndData (libnumarray_API ? (*(PyArrayObject * (*) (int nd, maybelong *dims, maybelong *strides, int type, char *data) ) libnumarray_API[ 128 ]) : (*(PyArrayObject * (*) (int nd, maybelong *dims, maybelong *strides, int type, char *data) ) libnumarray_FatalApiError)) #define NA_scipy_typestr (libnumarray_API ? (*(int (*) (NumarrayType t, int byteorder, char *typestr) ) libnumarray_API[ 129 ]) : (*(int (*) (NumarrayType t, int byteorder, char *typestr) ) libnumarray_FatalApiError)) #define NA_FromArrayStruct (libnumarray_API ? (*(PyArrayObject * (*) (PyObject *a) ) libnumarray_API[ 130 ]) : (*(PyArrayObject * (*) (PyObject *a) ) libnumarray_FatalApiError)) #endif /* Total number of C API pointers */ #define libnumarray_API_pointers 131 #ifdef __cplusplus } #endif #endif /* NUMPY_LIBNUMARRAY_H */ numpy-1.8.2/numpy/numarray/include/numpy/cfunc.h0000664000175100017510000000577512370216243023112 0ustar vagrantvagrant00000000000000#if !defined(__cfunc__) #define __cfunc__ 1 typedef PyObject *(*CFUNCasPyValue)(void *); typedef int (*UFUNC)(long, long, long, void **, long*); /* typedef void (*CFUNC_2ARG)(long, void *, void *); */ /* typedef void (*CFUNC_3ARG)(long, void *, void *, void *); */ typedef int (*CFUNCfromPyValue)(PyObject *, void *); typedef int (*CFUNC_STRIDE_CONV_FUNC)(long, long, maybelong *, void *, long, maybelong*, void *, long, maybelong *); typedef int (*CFUNC_STRIDED_FUNC)(PyObject *, long, PyArrayObject **, char **data); #define MAXARRAYS 16 typedef enum { CFUNC_UFUNC, CFUNC_STRIDING, CFUNC_NSTRIDING, CFUNC_AS_PY_VALUE, CFUNC_FROM_PY_VALUE } eCfuncType; typedef struct { char *name; void *fptr; /* Pointer to "un-wrapped" c function */ eCfuncType type; /* UFUNC, STRIDING, AsPyValue, FromPyValue */ Bool chkself; /* CFUNC does own alignment/bounds checking */ Bool align; /* CFUNC requires aligned buffer pointers */ Int8 wantIn, wantOut; /* required input/output arg counts. */ Int8 sizes[MAXARRAYS]; /* array of align/itemsizes. */ Int8 iters[MAXARRAYS]; /* array of element counts. 0 --> niter. */ } CfuncDescriptor; typedef struct { PyObject_HEAD CfuncDescriptor descr; } CfuncObject; #define SELF_CHECKED_CFUNC_DESCR(name, type) \ static CfuncDescriptor name##_descr = { #name, (void *) name, type, 1 } #define CHECK_ALIGN 1 #define CFUNC_DESCR(name, type, align, iargs, oargs, s1, s2, s3, i1, i2, i3) \ static CfuncDescriptor name##_descr = \ { #name, (void *)name, type, 0, align, iargs, oargs, {s1, s2, s3}, {i1, i2, i3} } #define UFUNC_DESCR1(name, s1) \ CFUNC_DESCR(name, CFUNC_UFUNC, CHECK_ALIGN, 0, 1, s1, 0, 0, 0, 0, 0) #define UFUNC_DESCR2(name, s1, s2) \ CFUNC_DESCR(name, CFUNC_UFUNC, CHECK_ALIGN, 1, 1, s1, s2, 0, 0, 0, 0) #define UFUNC_DESCR3(name, s1, s2, s3) \ CFUNC_DESCR(name, CFUNC_UFUNC, CHECK_ALIGN, 2, 1, s1, s2, s3, 0, 0, 0) #define UFUNC_DESCR3sv(name, s1, s2, s3) \ CFUNC_DESCR(name, CFUNC_UFUNC, CHECK_ALIGN, 2, 1, s1, s2, s3, 1, 0, 0) #define UFUNC_DESCR3vs(name, s1, s2, s3) \ CFUNC_DESCR(name, CFUNC_UFUNC, CHECK_ALIGN, 2, 1, s1, s2, s3, 0, 1, 0) #define STRIDING_DESCR2(name, align, s1, s2) \ CFUNC_DESCR(name, CFUNC_STRIDING, align, 1, 1, s1, s2, 0, 0, 0, 0) #define NSTRIDING_DESCR1(name) \ CFUNC_DESCR(name, CFUNC_NSTRIDING, 0, 0, 1, 0, 0, 0, 0, 0, 0) #define NSTRIDING_DESCR2(name) \ CFUNC_DESCR(name, CFUNC_NSTRIDING, 0, 1, 1, 0, 0, 0, 0, 0, 0) #define NSTRIDING_DESCR3(name) \ CFUNC_DESCR(name, CFUNC_NSTRIDING, 0, 2, 1, 0, 0, 0, 0, 0, 0) #endif numpy-1.8.2/numpy/numarray/fft.py0000664000175100017510000000025012370216243020160 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function from numpy.oldnumeric.fft import * import numpy.oldnumeric.fft as nof __all__ = nof.__all__ del nof numpy-1.8.2/numpy/numarray/convolve.py0000664000175100017510000000073212370216243021241 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function try: from stsci.convolve import * except ImportError: try: from scipy.stsci.convolve import * except ImportError: msg = \ """The convolve package is not installed. It can be downloaded by checking out the latest source from http://svn.scipy.org/svn/scipy/trunk/Lib/stsci or by downloading and installing all of SciPy from http://www.scipy.org. """ raise ImportError(msg) numpy-1.8.2/numpy/numarray/alter_code1.py0000664000175100017510000002240512370216243021571 0ustar vagrantvagrant00000000000000""" This module converts code written for numarray to run with numpy Makes the following changes: * Changes import statements import numarray.package --> import numpy.numarray.package as numarray_package with all numarray.package in code changed to numarray_package import numarray --> import numpy.numarray as numarray import numarray.package as --> import numpy.numarray.package as from numarray import --> from numpy.numarray import from numarray.package import --> from numpy.numarray.package import package can be convolve, image, nd_image, mlab, linear_algebra, ma, matrix, fft, random_array * Makes search and replace changes to: - .imaginary --> .imag - .flat --> .ravel() (most of the time) - .byteswapped() --> .byteswap(False) - .byteswap() --> .byteswap(True) - .info() --> numarray.info(self) - .isaligned() --> .flags.aligned - .isbyteswapped() --> (not .dtype.isnative) - .typecode() --> .dtype.char - .iscontiguous() --> .flags.contiguous - .is_c_array() --> .flags.carray and .dtype.isnative - .is_fortran_contiguous() --> .flags.fortran - .is_f_array() --> .dtype.isnative and .flags.farray - .itemsize() --> .itemsize - .nelements() --> .size - self.new(type) --> numarray.newobj(self, type) - .repeat(r) --> .repeat(r, axis=0) - .size() --> .size - self.type() -- numarray.typefrom(self) - .typecode() --> .dtype.char - .stddev() --> .std() - .togglebyteorder() --> numarray.togglebyteorder(self) - .getshape() --> .shape - .setshape(obj) --> .shape=obj - .getflat() --> .ravel() - .getreal() --> .real - .setreal() --> .real = - .getimag() --> .imag - .setimag() --> .imag = - .getimaginary() --> .imag - .setimaginary() --> .imag """ from __future__ import division, absolute_import, print_function __all__ = ['convertfile', 'convertall', 'converttree', 'convertsrc'] import sys import os import re import glob def changeimports(fstr, name, newname): importstr = 'import %s' % name importasstr = 'import %s as ' % name fromstr = 'from %s import ' % name fromall=0 name_ = name if ('.' in name): name_ = name.replace('.', '_') fstr = re.sub(r'(import\s+[^,\n\r]+,\s*)(%s)' % name, "\\1%s as %s" % (newname, name), fstr) fstr = fstr.replace(importasstr, 'import %s as ' % newname) fstr = fstr.replace(importstr, 'import %s as %s' % (newname, name_)) if (name_ != name): fstr = fstr.replace(name, name_) ind = 0 Nlen = len(fromstr) Nlen2 = len("from %s import " % newname) while True: found = fstr.find(fromstr, ind) if (found < 0): break ind = found + Nlen if fstr[ind] == '*': continue fstr = "%sfrom %s import %s" % (fstr[:found], newname, fstr[ind:]) ind += Nlen2 - Nlen return fstr, fromall flatindex_re = re.compile('([.]flat(\s*?[[=]))') def addimport(astr): # find the first line with import on it ind = astr.find('import') start = astr.rfind(os.linesep, 0, ind) astr = "%s%s%s%s" % (astr[:start], os.linesep, "import numpy.numarray as numarray", astr[start:]) return astr def replaceattr(astr): astr = astr.replace(".imaginary", ".imag") astr = astr.replace(".byteswapped()", ".byteswap(False)") astr = astr.replace(".byteswap()", ".byteswap(True)") astr = astr.replace(".isaligned()", ".flags.aligned") astr = astr.replace(".iscontiguous()", ".flags.contiguous") astr = astr.replace(".is_fortran_contiguous()", ".flags.fortran") astr = astr.replace(".itemsize()", ".itemsize") astr = astr.replace(".size()", ".size") astr = astr.replace(".nelements()", ".size") astr = astr.replace(".typecode()", ".dtype.char") astr = astr.replace(".stddev()", ".std()") astr = astr.replace(".getshape()", ".shape") astr = astr.replace(".getflat()", ".ravel()") astr = astr.replace(".getreal", ".real") astr = astr.replace(".getimag", ".imag") astr = astr.replace(".getimaginary", ".imag") # preserve uses of flat that should be o.k. tmpstr = flatindex_re.sub(r"@@@@\2", astr) # replace other uses of flat tmpstr = tmpstr.replace(".flat", ".ravel()") # put back .flat where it was valid astr = tmpstr.replace("@@@@", ".flat") return astr info_re = re.compile(r'(\S+)\s*[.]\s*info\s*[(]\s*[)]') new_re = re.compile(r'(\S+)\s*[.]\s*new\s*[(]\s*(\S+)\s*[)]') toggle_re = re.compile(r'(\S+)\s*[.]\s*togglebyteorder\s*[(]\s*[)]') type_re = re.compile(r'(\S+)\s*[.]\s*type\s*[(]\s*[)]') isbyte_re = re.compile(r'(\S+)\s*[.]\s*isbyteswapped\s*[(]\s*[)]') iscarr_re = re.compile(r'(\S+)\s*[.]\s*is_c_array\s*[(]\s*[)]') isfarr_re = re.compile(r'(\S+)\s*[.]\s*is_f_array\s*[(]\s*[)]') repeat_re = re.compile(r'(\S+)\s*[.]\s*repeat\s*[(]\s*(\S+)\s*[)]') setshape_re = re.compile(r'(\S+)\s*[.]\s*setshape\s*[(]\s*(\S+)\s*[)]') setreal_re = re.compile(r'(\S+)\s*[.]\s*setreal\s*[(]\s*(\S+)\s*[)]') setimag_re = re.compile(r'(\S+)\s*[.]\s*setimag\s*[(]\s*(\S+)\s*[)]') setimaginary_re = re.compile(r'(\S+)\s*[.]\s*setimaginary\s*[(]\s*(\S+)\s*[)]') def replaceother(astr): # self.info() --> numarray.info(self) # self.new(type) --> numarray.newobj(self, type) # self.togglebyteorder() --> numarray.togglebyteorder(self) # self.type() --> numarray.typefrom(self) (astr, n1) = info_re.subn('numarray.info(\\1)', astr) (astr, n2) = new_re.subn('numarray.newobj(\\1, \\2)', astr) (astr, n3) = toggle_re.subn('numarray.togglebyteorder(\\1)', astr) (astr, n4) = type_re.subn('numarray.typefrom(\\1)', astr) if (n1+n2+n3+n4 > 0): astr = addimport(astr) astr = isbyte_re.sub('not \\1.dtype.isnative', astr) astr = iscarr_re.sub('\\1.dtype.isnative and \\1.flags.carray', astr) astr = isfarr_re.sub('\\1.dtype.isnative and \\1.flags.farray', astr) astr = repeat_re.sub('\\1.repeat(\\2, axis=0)', astr) astr = setshape_re.sub('\\1.shape = \\2', astr) astr = setreal_re.sub('\\1.real = \\2', astr) astr = setimag_re.sub('\\1.imag = \\2', astr) astr = setimaginary_re.sub('\\1.imag = \\2', astr) return astr import datetime def fromstr(filestr): savestr = filestr[:] filestr, fromall = changeimports(filestr, 'numarray', 'numpy.numarray') base = 'numarray' newbase = 'numpy.numarray' for sub in ['', 'convolve', 'image', 'nd_image', 'mlab', 'linear_algebra', 'ma', 'matrix', 'fft', 'random_array']: if sub != '': sub = '.'+sub filestr, fromall = changeimports(filestr, base+sub, newbase+sub) filestr = replaceattr(filestr) filestr = replaceother(filestr) if savestr != filestr: name = os.path.split(sys.argv[0])[-1] today = datetime.date.today().strftime('%b %d, %Y') filestr = '## Automatically adapted for '\ 'numpy.numarray %s by %s\n\n%s' % (today, name, filestr) return filestr, 1 return filestr, 0 def makenewfile(name, filestr): fid = file(name, 'w') fid.write(filestr) fid.close() def convertfile(filename, orig=1): """Convert the filename given from using Numarray to using NumPy Copies the file to filename.orig and then over-writes the file with the updated code """ fid = open(filename) filestr = fid.read() fid.close() filestr, changed = fromstr(filestr) if changed: if orig: base, ext = os.path.splitext(filename) os.rename(filename, base+".orig") else: os.remove(filename) makenewfile(filename, filestr) def fromargs(args): filename = args[1] convertfile(filename) def convertall(direc=os.path.curdir, orig=1): """Convert all .py files to use numpy.oldnumeric (from Numeric) in the directory given For each file, a backup of .py is made as .py.orig. A new file named .py is then written with the updated code. """ files = glob.glob(os.path.join(direc, '*.py')) for afile in files: if afile[-8:] == 'setup.py': continue convertfile(afile, orig) header_re = re.compile(r'(numarray/libnumarray.h)') def convertsrc(direc=os.path.curdir, ext=None, orig=1): """Replace Numeric/arrayobject.h with numpy/oldnumeric.h in all files in the directory with extension give by list ext (if ext is None, then all files are replaced).""" if ext is None: files = glob.glob(os.path.join(direc, '*')) else: files = [] for aext in ext: files.extend(glob.glob(os.path.join(direc, "*.%s" % aext))) for afile in files: fid = open(afile) fstr = fid.read() fid.close() fstr, n = header_re.subn(r'numpy/libnumarray.h', fstr) if n > 0: if orig: base, ext = os.path.splitext(afile) os.rename(afile, base+".orig") else: os.remove(afile) makenewfile(afile, fstr) def _func(arg, dirname, fnames): convertall(dirname, orig=0) convertsrc(dirname, ['h', 'c'], orig=0) def converttree(direc=os.path.curdir): """Convert all .py files in the tree given """ os.path.walk(direc, _func, None) if __name__ == '__main__': converttree(sys.argv) numpy-1.8.2/numpy/numarray/ufuncs.py0000664000175100017510000000261712370216243020715 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function __all__ = ['abs', 'absolute', 'add', 'arccos', 'arccosh', 'arcsin', 'arcsinh', 'arctan', 'arctan2', 'arctanh', 'bitwise_and', 'bitwise_not', 'bitwise_or', 'bitwise_xor', 'ceil', 'cos', 'cosh', 'divide', 'equal', 'exp', 'fabs', 'floor', 'floor_divide', 'fmod', 'greater', 'greater_equal', 'hypot', 'isnan', 'less', 'less_equal', 'log', 'log10', 'logical_and', 'logical_not', 'logical_or', 'logical_xor', 'lshift', 'maximum', 'minimum', 'minus', 'multiply', 'negative', 'not_equal', 'power', 'product', 'remainder', 'rshift', 'sin', 'sinh', 'sqrt', 'subtract', 'sum', 'tan', 'tanh', 'true_divide', 'conjugate', 'sign'] from numpy import absolute as abs, absolute, add, arccos, arccosh, arcsin, \ arcsinh, arctan, arctan2, arctanh, bitwise_and, invert as bitwise_not, \ bitwise_or, bitwise_xor, ceil, cos, cosh, divide, \ equal, exp, fabs, floor, floor_divide, fmod, greater, greater_equal, \ hypot, isnan, less, less_equal, log, log10, logical_and, \ logical_not, logical_or, logical_xor, left_shift as lshift, \ maximum, minimum, negative as minus, multiply, negative, \ not_equal, power, product, remainder, right_shift as rshift, sin, \ sinh, sqrt, subtract, sum, tan, tanh, true_divide, conjugate, sign numpy-1.8.2/numpy/numarray/__init__.py0000664000175100017510000000150112370216243021140 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function import warnings from numpy import ModuleDeprecationWarning from .util import * from .numerictypes import * from .functions import * from .ufuncs import * from .compat import * from .session import * from . import util from . import numerictypes from . import functions from . import ufuncs from . import compat from . import session _msg = "The numarray module will be dropped in Numpy 1.9" warnings.warn(_msg, ModuleDeprecationWarning) __all__ = ['session', 'numerictypes'] __all__ += util.__all__ __all__ += numerictypes.__all__ __all__ += functions.__all__ __all__ += ufuncs.__all__ __all__ += compat.__all__ __all__ += session.__all__ del util del functions del ufuncs del compat from numpy.testing import Tester test = Tester().test bench = Tester().bench numpy-1.8.2/numpy/numarray/mlab.py0000664000175100017510000000025212370216243020316 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function from numpy.oldnumeric.mlab import * import numpy.oldnumeric.mlab as nom __all__ = nom.__all__ del nom numpy-1.8.2/numpy/numarray/ma.py0000664000175100017510000000014412370216243020000 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function from numpy.oldnumeric.ma import * numpy-1.8.2/numpy/numarray/image.py0000664000175100017510000000072012370216243020465 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function try: from stsci.image import * except ImportError: try: from scipy.stsci.image import * except ImportError: msg = \ """The image package is not installed It can be downloaded by checking out the latest source from http://svn.scipy.org/svn/scipy/trunk/Lib/stsci or by downloading and installing all of SciPy from http://www.scipy.org. """ raise ImportError(msg) numpy-1.8.2/numpy/numarray/numerictypes.py0000664000175100017510000003615712370216243022147 0ustar vagrantvagrant00000000000000"""numerictypes: Define the numeric type objects This module is designed so 'from numerictypes import *' is safe. Exported symbols include: Dictionary with all registered number types (including aliases): typeDict Numeric type objects: Bool Int8 Int16 Int32 Int64 UInt8 UInt16 UInt32 UInt64 Float32 Double64 Complex32 Complex64 Numeric type classes: NumericType BooleanType SignedType UnsignedType IntegralType SignedIntegralType UnsignedIntegralType FloatingType ComplexType $Id: numerictypes.py,v 1.55 2005/12/01 16:22:03 jaytmiller Exp $ """ from __future__ import division, absolute_import, print_function import numpy from numpy.compat import long __all__ = ['NumericType', 'HasUInt64', 'typeDict', 'IsType', 'BooleanType', 'SignedType', 'UnsignedType', 'IntegralType', 'SignedIntegralType', 'UnsignedIntegralType', 'FloatingType', 'ComplexType', 'AnyType', 'ObjectType', 'Any', 'Object', 'Bool', 'Int8', 'Int16', 'Int32', 'Int64', 'Float32', 'Float64', 'UInt8', 'UInt16', 'UInt32', 'UInt64', 'Complex32', 'Complex64', 'Byte', 'Short', 'Int', 'Long', 'Float', 'Complex', 'genericTypeRank', 'pythonTypeRank', 'pythonTypeMap', 'scalarTypeMap', 'genericCoercions', 'typecodes', 'genericPromotionExclusions', 'MaximumType', 'getType', 'scalarTypes', 'typefrom'] MAX_ALIGN = 8 MAX_INT_SIZE = 8 LP64 = numpy.intp(0).itemsize == 8 HasUInt64 = 1 try: numpy.int64(0) except: HasUInt64 = 0 #from typeconv import typeConverters as _typeConverters #import numinclude #from _numerictype import _numerictype, typeDict # Enumeration of numarray type codes typeDict = {} _tAny = 0 _tBool = 1 _tInt8 = 2 _tUInt8 = 3 _tInt16 = 4 _tUInt16 = 5 _tInt32 = 6 _tUInt32 = 7 _tInt64 = 8 _tUInt64 = 9 _tFloat32 = 10 _tFloat64 = 11 _tComplex32 = 12 _tComplex64 = 13 _tObject = 14 def IsType(rep): """Determines whether the given object or string, 'rep', represents a numarray type.""" return isinstance(rep, NumericType) or rep in typeDict def _register(name, type, force=0): """Register the type object. Raise an exception if it is already registered unless force is true. """ if name in typeDict and not force: raise ValueError("Type %s has already been registered" % name) typeDict[name] = type return type class NumericType(object): """Numeric type class Used both as a type identification and the repository of characteristics and conversion functions. """ def __new__(type, name, bytes, default, typeno): """__new__() implements a 'quasi-singleton pattern because attempts to create duplicate types return the first created instance of that particular type parameterization, i.e. the second time you try to create "Int32", you get the original Int32, not a new one. """ if name in typeDict: self = typeDict[name] if self.bytes != bytes or self.default != default or \ self.typeno != typeno: raise ValueError("Redeclaration of existing NumericType "\ "with different parameters.") return self else: self = object.__new__(type) self.name = "no name" self.bytes = None self.default = None self.typeno = -1 return self def __init__(self, name, bytes, default, typeno): if not isinstance(name, str): raise TypeError("name must be a string") self.name = name self.bytes = bytes self.default = default self.typeno = typeno self._conv = None _register(self.name, self) def __getnewargs__(self): """support the pickling protocol.""" return (self.name, self.bytes, self.default, self.typeno) def __getstate__(self): """support pickling protocol... no __setstate__ required.""" False class BooleanType(NumericType): pass class SignedType(object): """Marker class used for signed type check""" pass class UnsignedType(object): """Marker class used for unsigned type check""" pass class IntegralType(NumericType): pass class SignedIntegralType(IntegralType, SignedType): pass class UnsignedIntegralType(IntegralType, UnsignedType): pass class FloatingType(NumericType): pass class ComplexType(NumericType): pass class AnyType(NumericType): pass class ObjectType(NumericType): pass # C-API Type Any Any = AnyType("Any", None, None, _tAny) Object = ObjectType("Object", None, None, _tObject) # Numeric Types: Bool = BooleanType("Bool", 1, 0, _tBool) Int8 = SignedIntegralType( "Int8", 1, 0, _tInt8) Int16 = SignedIntegralType("Int16", 2, 0, _tInt16) Int32 = SignedIntegralType("Int32", 4, 0, _tInt32) Int64 = SignedIntegralType("Int64", 8, 0, _tInt64) Float32 = FloatingType("Float32", 4, 0.0, _tFloat32) Float64 = FloatingType("Float64", 8, 0.0, _tFloat64) UInt8 = UnsignedIntegralType( "UInt8", 1, 0, _tUInt8) UInt16 = UnsignedIntegralType("UInt16", 2, 0, _tUInt16) UInt32 = UnsignedIntegralType("UInt32", 4, 0, _tUInt32) UInt64 = UnsignedIntegralType("UInt64", 8, 0, _tUInt64) Complex32 = ComplexType("Complex32", 8, complex(0.0), _tComplex32) Complex64 = ComplexType("Complex64", 16, complex(0.0), _tComplex64) Object.dtype = 'O' Bool.dtype = '?' Int8.dtype = 'i1' Int16.dtype = 'i2' Int32.dtype = 'i4' Int64.dtype = 'i8' UInt8.dtype = 'u1' UInt16.dtype = 'u2' UInt32.dtype = 'u4' UInt64.dtype = 'u8' Float32.dtype = 'f4' Float64.dtype = 'f8' Complex32.dtype = 'c8' Complex64.dtype = 'c16' # Aliases Byte = _register("Byte", Int8) Short = _register("Short", Int16) Int = _register("Int", Int32) if LP64: Long = _register("Long", Int64) if HasUInt64: _register("ULong", UInt64) MaybeLong = _register("MaybeLong", Int64) __all__.append('MaybeLong') else: Long = _register("Long", Int32) _register("ULong", UInt32) MaybeLong = _register("MaybeLong", Int32) __all__.append('MaybeLong') _register("UByte", UInt8) _register("UShort", UInt16) _register("UInt", UInt32) Float = _register("Float", Float64) Complex = _register("Complex", Complex64) # short forms _register("b1", Bool) _register("u1", UInt8) _register("u2", UInt16) _register("u4", UInt32) _register("i1", Int8) _register("i2", Int16) _register("i4", Int32) _register("i8", Int64) if HasUInt64: _register("u8", UInt64) _register("f4", Float32) _register("f8", Float64) _register("c8", Complex32) _register("c16", Complex64) # NumPy forms _register("1", Int8) _register("B", Bool) _register("c", Int8) _register("b", UInt8) _register("s", Int16) _register("w", UInt16) _register("i", Int32) _register("N", Int64) _register("u", UInt32) _register("U", UInt64) if LP64: _register("l", Int64) else: _register("l", Int32) _register("d", Float64) _register("f", Float32) _register("D", Complex64) _register("F", Complex32) # scipy.base forms def _scipy_alias(scipy_type, numarray_type): _register(scipy_type, eval(numarray_type)) globals()[scipy_type] = globals()[numarray_type] _scipy_alias("bool_", "Bool") _scipy_alias("bool8", "Bool") _scipy_alias("int8", "Int8") _scipy_alias("uint8", "UInt8") _scipy_alias("int16", "Int16") _scipy_alias("uint16", "UInt16") _scipy_alias("int32", "Int32") _scipy_alias("uint32", "UInt32") _scipy_alias("int64", "Int64") _scipy_alias("uint64", "UInt64") _scipy_alias("float64", "Float64") _scipy_alias("float32", "Float32") _scipy_alias("complex128", "Complex64") _scipy_alias("complex64", "Complex32") # The rest is used by numeric modules to determine conversions # Ranking of types from lowest to highest (sorta) if not HasUInt64: genericTypeRank = ['Bool', 'Int8', 'UInt8', 'Int16', 'UInt16', 'Int32', 'UInt32', 'Int64', 'Float32', 'Float64', 'Complex32', 'Complex64', 'Object'] else: genericTypeRank = ['Bool', 'Int8', 'UInt8', 'Int16', 'UInt16', 'Int32', 'UInt32', 'Int64', 'UInt64', 'Float32', 'Float64', 'Complex32', 'Complex64', 'Object'] pythonTypeRank = [ bool, int, long, float, complex ] # The next line is not platform independent XXX Needs to be generalized if not LP64: pythonTypeMap = { int:("Int32", "int"), long:("Int64", "int"), float:("Float64", "float"), complex:("Complex64", "complex")} scalarTypeMap = { int:"Int32", long:"Int64", float:"Float64", complex:"Complex64"} else: pythonTypeMap = { int:("Int64", "int"), long:("Int64", "int"), float:("Float64", "float"), complex:("Complex64", "complex")} scalarTypeMap = { int:"Int64", long:"Int64", float:"Float64", complex:"Complex64"} pythonTypeMap.update({bool:("Bool", "bool") }) scalarTypeMap.update({bool:"Bool"}) # Generate coercion matrix def _initGenericCoercions(): global genericCoercions genericCoercions = {} # vector with ... for ntype1 in genericTypeRank: nt1 = typeDict[ntype1] rank1 = genericTypeRank.index(ntype1) ntypesize1, inttype1, signedtype1 = nt1.bytes, \ isinstance(nt1, IntegralType), isinstance(nt1, SignedIntegralType) for ntype2 in genericTypeRank: # vector nt2 = typeDict[ntype2] ntypesize2, inttype2, signedtype2 = nt2.bytes, \ isinstance(nt2, IntegralType), isinstance(nt2, SignedIntegralType) rank2 = genericTypeRank.index(ntype2) if (signedtype1 != signedtype2) and inttype1 and inttype2: # mixing of signed and unsigned ints is a special case # If unsigned same size or larger, final size needs to be bigger # if possible if signedtype1: if ntypesize2 >= ntypesize1: size = min(2*ntypesize2, MAX_INT_SIZE) else: size = ntypesize1 else: if ntypesize1 >= ntypesize2: size = min(2*ntypesize1, MAX_INT_SIZE) else: size = ntypesize2 outtype = "Int"+str(8*size) else: if rank1 >= rank2: outtype = ntype1 else: outtype = ntype2 genericCoercions[(ntype1, ntype2)] = outtype for ntype2 in pythonTypeRank: # scalar mapto, kind = pythonTypeMap[ntype2] if ((inttype1 and kind=="int") or (not inttype1 and kind=="float")): # both are of the same "kind" thus vector type dominates outtype = ntype1 else: rank2 = genericTypeRank.index(mapto) if rank1 >= rank2: outtype = ntype1 else: outtype = mapto genericCoercions[(ntype1, ntype2)] = outtype genericCoercions[(ntype2, ntype1)] = outtype # scalar-scalar for ntype1 in pythonTypeRank: maptype1 = scalarTypeMap[ntype1] genericCoercions[(ntype1,)] = maptype1 for ntype2 in pythonTypeRank: maptype2 = scalarTypeMap[ntype2] genericCoercions[(ntype1, ntype2)] = genericCoercions[(maptype1, maptype2)] # Special cases more easily dealt with outside of the loop genericCoercions[("Complex32", "Float64")] = "Complex64" genericCoercions[("Float64", "Complex32")] = "Complex64" genericCoercions[("Complex32", "Int64")] = "Complex64" genericCoercions[("Int64", "Complex32")] = "Complex64" genericCoercions[("Complex32", "UInt64")] = "Complex64" genericCoercions[("UInt64", "Complex32")] = "Complex64" genericCoercions[("Int64", "Float32")] = "Float64" genericCoercions[("Float32", "Int64")] = "Float64" genericCoercions[("UInt64", "Float32")] = "Float64" genericCoercions[("Float32", "UInt64")] = "Float64" genericCoercions[(float, "Bool")] = "Float64" genericCoercions[("Bool", float)] = "Float64" genericCoercions[(float, float, float)] = "Float64" # for scipy.special genericCoercions[(int, int, float)] = "Float64" # for scipy.special _initGenericCoercions() # If complex is subclassed, the following may not be necessary genericPromotionExclusions = { 'Bool': (), 'Int8': (), 'Int16': (), 'Int32': ('Float32', 'Complex32'), 'UInt8': (), 'UInt16': (), 'UInt32': ('Float32', 'Complex32'), 'Int64' : ('Float32', 'Complex32'), 'UInt64' : ('Float32', 'Complex32'), 'Float32': (), 'Float64': ('Complex32',), 'Complex32':(), 'Complex64':() } # e.g., don't allow promotion from Float64 to Complex32 or Int64 to Float32 # Numeric typecodes typecodes = {'Integer': '1silN', 'UnsignedInteger': 'bBwuU', 'Float': 'fd', 'Character': 'c', 'Complex': 'FD' } if HasUInt64: _MaximumType = { Bool : UInt64, Int8 : Int64, Int16 : Int64, Int32 : Int64, Int64 : Int64, UInt8 : UInt64, UInt16 : UInt64, UInt32 : UInt64, UInt8 : UInt64, Float32 : Float64, Float64 : Float64, Complex32 : Complex64, Complex64 : Complex64 } else: _MaximumType = { Bool : Int64, Int8 : Int64, Int16 : Int64, Int32 : Int64, Int64 : Int64, UInt8 : Int64, UInt16 : Int64, UInt32 : Int64, UInt8 : Int64, Float32 : Float64, Float64 : Float64, Complex32 : Complex64, Complex64 : Complex64 } def MaximumType(t): """returns the type of highest precision of the same general kind as 't'""" return _MaximumType[t] def getType(type): """Return the numeric type object for type type may be the name of a type object or the actual object """ if isinstance(type, NumericType): return type try: return typeDict[type] except KeyError: raise TypeError("Not a numeric type") scalarTypes = (bool, int, long, float, complex) _scipy_dtypechar = { Int8 : 'b', UInt8 : 'B', Int16 : 'h', UInt16 : 'H', Int32 : 'i', UInt32 : 'I', Int64 : 'q', UInt64 : 'Q', Float32 : 'f', Float64 : 'd', Complex32 : 'F', # Note the switchup here: Complex64 : 'D' # numarray.Complex32 == scipy.complex64, etc. } _scipy_dtypechar_inverse = {} for key, value in _scipy_dtypechar.items(): _scipy_dtypechar_inverse[value] = key _val = numpy.int_(0).itemsize if _val == 8: _scipy_dtypechar_inverse['l'] = Int64 _scipy_dtypechar_inverse['L'] = UInt64 elif _val == 4: _scipy_dtypechar_inverse['l'] = Int32 _scipy_dtypechar_inverse['L'] = UInt32 del _val if LP64: _scipy_dtypechar_inverse['p'] = Int64 _scipy_dtypechar_inverse['P'] = UInt64 else: _scipy_dtypechar_inverse['p'] = Int32 _scipy_dtypechar_inverse['P'] = UInt32 def typefrom(obj): return _scipy_dtypechar_inverse[obj.dtype.char] numpy-1.8.2/numpy/core/0000775000175100017510000000000012371375427016137 5ustar vagrantvagrant00000000000000numpy-1.8.2/numpy/core/fromnumeric.py0000664000175100017510000025763512370216243021046 0ustar vagrantvagrant00000000000000"""Module containing non-deprecated functions borrowed from Numeric. """ from __future__ import division, absolute_import, print_function import types from . import multiarray as mu from . import umath as um from . import numerictypes as nt from .numeric import asarray, array, asanyarray, concatenate from . import _methods _dt_ = nt.sctype2char # functions that are methods __all__ = [ 'alen', 'all', 'alltrue', 'amax', 'amin', 'any', 'argmax', 'argmin', 'argpartition', 'argsort', 'around', 'choose', 'clip', 'compress', 'cumprod', 'cumproduct', 'cumsum', 'diagonal', 'mean', 'ndim', 'nonzero', 'partition', 'prod', 'product', 'ptp', 'put', 'rank', 'ravel', 'repeat', 'reshape', 'resize', 'round_', 'searchsorted', 'shape', 'size', 'sometrue', 'sort', 'squeeze', 'std', 'sum', 'swapaxes', 'take', 'trace', 'transpose', 'var', ] try: _gentype = types.GeneratorType except AttributeError: _gentype = type(None) # save away Python sum _sum_ = sum # functions that are now methods def _wrapit(obj, method, *args, **kwds): try: wrap = obj.__array_wrap__ except AttributeError: wrap = None result = getattr(asarray(obj), method)(*args, **kwds) if wrap: if not isinstance(result, mu.ndarray): result = asarray(result) result = wrap(result) return result def take(a, indices, axis=None, out=None, mode='raise'): """ Take elements from an array along an axis. This function does the same thing as "fancy" indexing (indexing arrays using arrays); however, it can be easier to use if you need elements along a given axis. Parameters ---------- a : array_like The source array. indices : array_like The indices of the values to extract. .. versionadded:: 1.8.0 Also allow scalars for indices. axis : int, optional The axis over which to select values. By default, the flattened input array is used. out : ndarray, optional If provided, the result will be placed in this array. It should be of the appropriate shape and dtype. mode : {'raise', 'wrap', 'clip'}, optional Specifies how out-of-bounds indices will behave. * 'raise' -- raise an error (default) * 'wrap' -- wrap around * 'clip' -- clip to the range 'clip' mode means that all indices that are too large are replaced by the index that addresses the last element along that axis. Note that this disables indexing with negative numbers. Returns ------- subarray : ndarray The returned array has the same type as `a`. See Also -------- ndarray.take : equivalent method Examples -------- >>> a = [4, 3, 5, 7, 6, 8] >>> indices = [0, 1, 4] >>> np.take(a, indices) array([4, 3, 6]) In this example if `a` is an ndarray, "fancy" indexing can be used. >>> a = np.array(a) >>> a[indices] array([4, 3, 6]) If `indices` is not one dimensional, the output also has these dimensions. >>> np.take(a, [[0, 1], [2, 3]]) array([[4, 3], [5, 7]]) """ try: take = a.take except AttributeError: return _wrapit(a, 'take', indices, axis, out, mode) return take(indices, axis, out, mode) # not deprecated --- copy if necessary, view otherwise def reshape(a, newshape, order='C'): """ Gives a new shape to an array without changing its data. Parameters ---------- a : array_like Array to be reshaped. newshape : int or tuple of ints The new shape should be compatible with the original shape. If an integer, then the result will be a 1-D array of that length. One shape dimension can be -1. In this case, the value is inferred from the length of the array and remaining dimensions. order : {'C', 'F', 'A'}, optional Read the elements of `a` using this index order, and place the elements into the reshaped array using this index order. 'C' means to read / write the elements using C-like index order, with the last axis index changing fastest, back to the first axis index changing slowest. 'F' means to read / write the elements using Fortran-like index order, with the first index changing fastest, and the last index changing slowest. Note that the 'C' and 'F' options take no account of the memory layout of the underlying array, and only refer to the order of indexing. 'A' means to read / write the elements in Fortran-like index order if `a` is Fortran *contiguous* in memory, C-like order otherwise. Returns ------- reshaped_array : ndarray This will be a new view object if possible; otherwise, it will be a copy. Note there is no guarantee of the *memory layout* (C- or Fortran- contiguous) of the returned array. See Also -------- ndarray.reshape : Equivalent method. Notes ----- It is not always possible to change the shape of an array without copying the data. If you want an error to be raise if the data is copied, you should assign the new shape to the shape attribute of the array:: >>> a = np.zeros((10, 2)) # A transpose make the array non-contiguous >>> b = a.T # Taking a view makes it possible to modify the shape without modifying the # initial object. >>> c = b.view() >>> c.shape = (20) AttributeError: incompatible shape for a non-contiguous array The `order` keyword gives the index ordering both for *fetching* the values from `a`, and then *placing* the values into the output array. For example, let's say you have an array: >>> a = np.arange(6).reshape((3, 2)) >>> a array([[0, 1], [2, 3], [4, 5]]) You can think of reshaping as first raveling the array (using the given index order), then inserting the elements from the raveled array into the new array using the same kind of index ordering as was used for the raveling. >>> np.reshape(a, (2, 3)) # C-like index ordering array([[0, 1, 2], [3, 4, 5]]) >>> np.reshape(np.ravel(a), (2, 3)) # equivalent to C ravel then C reshape array([[0, 1, 2], [3, 4, 5]]) >>> np.reshape(a, (2, 3), order='F') # Fortran-like index ordering array([[0, 4, 3], [2, 1, 5]]) >>> np.reshape(np.ravel(a, order='F'), (2, 3), order='F') array([[0, 4, 3], [2, 1, 5]]) Examples -------- >>> a = np.array([[1,2,3], [4,5,6]]) >>> np.reshape(a, 6) array([1, 2, 3, 4, 5, 6]) >>> np.reshape(a, 6, order='F') array([1, 4, 2, 5, 3, 6]) >>> np.reshape(a, (3,-1)) # the unspecified value is inferred to be 2 array([[1, 2], [3, 4], [5, 6]]) """ try: reshape = a.reshape except AttributeError: return _wrapit(a, 'reshape', newshape, order=order) return reshape(newshape, order=order) def choose(a, choices, out=None, mode='raise'): """ Construct an array from an index array and a set of arrays to choose from. First of all, if confused or uncertain, definitely look at the Examples - in its full generality, this function is less simple than it might seem from the following code description (below ndi = `numpy.lib.index_tricks`): ``np.choose(a,c) == np.array([c[a[I]][I] for I in ndi.ndindex(a.shape)])``. But this omits some subtleties. Here is a fully general summary: Given an "index" array (`a`) of integers and a sequence of `n` arrays (`choices`), `a` and each choice array are first broadcast, as necessary, to arrays of a common shape; calling these *Ba* and *Bchoices[i], i = 0,...,n-1* we have that, necessarily, ``Ba.shape == Bchoices[i].shape`` for each `i`. Then, a new array with shape ``Ba.shape`` is created as follows: * if ``mode=raise`` (the default), then, first of all, each element of `a` (and thus `Ba`) must be in the range `[0, n-1]`; now, suppose that `i` (in that range) is the value at the `(j0, j1, ..., jm)` position in `Ba` - then the value at the same position in the new array is the value in `Bchoices[i]` at that same position; * if ``mode=wrap``, values in `a` (and thus `Ba`) may be any (signed) integer; modular arithmetic is used to map integers outside the range `[0, n-1]` back into that range; and then the new array is constructed as above; * if ``mode=clip``, values in `a` (and thus `Ba`) may be any (signed) integer; negative integers are mapped to 0; values greater than `n-1` are mapped to `n-1`; and then the new array is constructed as above. Parameters ---------- a : int array This array must contain integers in `[0, n-1]`, where `n` is the number of choices, unless ``mode=wrap`` or ``mode=clip``, in which cases any integers are permissible. choices : sequence of arrays Choice arrays. `a` and all of the choices must be broadcastable to the same shape. If `choices` is itself an array (not recommended), then its outermost dimension (i.e., the one corresponding to ``choices.shape[0]``) is taken as defining the "sequence". out : array, optional If provided, the result will be inserted into this array. It should be of the appropriate shape and dtype. mode : {'raise' (default), 'wrap', 'clip'}, optional Specifies how indices outside `[0, n-1]` will be treated: * 'raise' : an exception is raised * 'wrap' : value becomes value mod `n` * 'clip' : values < 0 are mapped to 0, values > n-1 are mapped to n-1 Returns ------- merged_array : array The merged result. Raises ------ ValueError: shape mismatch If `a` and each choice array are not all broadcastable to the same shape. See Also -------- ndarray.choose : equivalent method Notes ----- To reduce the chance of misinterpretation, even though the following "abuse" is nominally supported, `choices` should neither be, nor be thought of as, a single array, i.e., the outermost sequence-like container should be either a list or a tuple. Examples -------- >>> choices = [[0, 1, 2, 3], [10, 11, 12, 13], ... [20, 21, 22, 23], [30, 31, 32, 33]] >>> np.choose([2, 3, 1, 0], choices ... # the first element of the result will be the first element of the ... # third (2+1) "array" in choices, namely, 20; the second element ... # will be the second element of the fourth (3+1) choice array, i.e., ... # 31, etc. ... ) array([20, 31, 12, 3]) >>> np.choose([2, 4, 1, 0], choices, mode='clip') # 4 goes to 3 (4-1) array([20, 31, 12, 3]) >>> # because there are 4 choice arrays >>> np.choose([2, 4, 1, 0], choices, mode='wrap') # 4 goes to (4 mod 4) array([20, 1, 12, 3]) >>> # i.e., 0 A couple examples illustrating how choose broadcasts: >>> a = [[1, 0, 1], [0, 1, 0], [1, 0, 1]] >>> choices = [-10, 10] >>> np.choose(a, choices) array([[ 10, -10, 10], [-10, 10, -10], [ 10, -10, 10]]) >>> # With thanks to Anne Archibald >>> a = np.array([0, 1]).reshape((2,1,1)) >>> c1 = np.array([1, 2, 3]).reshape((1,3,1)) >>> c2 = np.array([-1, -2, -3, -4, -5]).reshape((1,1,5)) >>> np.choose(a, (c1, c2)) # result is 2x3x5, res[0,:,:]=c1, res[1,:,:]=c2 array([[[ 1, 1, 1, 1, 1], [ 2, 2, 2, 2, 2], [ 3, 3, 3, 3, 3]], [[-1, -2, -3, -4, -5], [-1, -2, -3, -4, -5], [-1, -2, -3, -4, -5]]]) """ try: choose = a.choose except AttributeError: return _wrapit(a, 'choose', choices, out=out, mode=mode) return choose(choices, out=out, mode=mode) def repeat(a, repeats, axis=None): """ Repeat elements of an array. Parameters ---------- a : array_like Input array. repeats : {int, array of ints} The number of repetitions for each element. `repeats` is broadcasted to fit the shape of the given axis. axis : int, optional The axis along which to repeat values. By default, use the flattened input array, and return a flat output array. Returns ------- repeated_array : ndarray Output array which has the same shape as `a`, except along the given axis. See Also -------- tile : Tile an array. Examples -------- >>> x = np.array([[1,2],[3,4]]) >>> np.repeat(x, 2) array([1, 1, 2, 2, 3, 3, 4, 4]) >>> np.repeat(x, 3, axis=1) array([[1, 1, 1, 2, 2, 2], [3, 3, 3, 4, 4, 4]]) >>> np.repeat(x, [1, 2], axis=0) array([[1, 2], [3, 4], [3, 4]]) """ try: repeat = a.repeat except AttributeError: return _wrapit(a, 'repeat', repeats, axis) return repeat(repeats, axis) def put(a, ind, v, mode='raise'): """ Replaces specified elements of an array with given values. The indexing works on the flattened target array. `put` is roughly equivalent to: :: a.flat[ind] = v Parameters ---------- a : ndarray Target array. ind : array_like Target indices, interpreted as integers. v : array_like Values to place in `a` at target indices. If `v` is shorter than `ind` it will be repeated as necessary. mode : {'raise', 'wrap', 'clip'}, optional Specifies how out-of-bounds indices will behave. * 'raise' -- raise an error (default) * 'wrap' -- wrap around * 'clip' -- clip to the range 'clip' mode means that all indices that are too large are replaced by the index that addresses the last element along that axis. Note that this disables indexing with negative numbers. See Also -------- putmask, place Examples -------- >>> a = np.arange(5) >>> np.put(a, [0, 2], [-44, -55]) >>> a array([-44, 1, -55, 3, 4]) >>> a = np.arange(5) >>> np.put(a, 22, -5, mode='clip') >>> a array([ 0, 1, 2, 3, -5]) """ return a.put(ind, v, mode) def swapaxes(a, axis1, axis2): """ Interchange two axes of an array. Parameters ---------- a : array_like Input array. axis1 : int First axis. axis2 : int Second axis. Returns ------- a_swapped : ndarray If `a` is an ndarray, then a view of `a` is returned; otherwise a new array is created. Examples -------- >>> x = np.array([[1,2,3]]) >>> np.swapaxes(x,0,1) array([[1], [2], [3]]) >>> x = np.array([[[0,1],[2,3]],[[4,5],[6,7]]]) >>> x array([[[0, 1], [2, 3]], [[4, 5], [6, 7]]]) >>> np.swapaxes(x,0,2) array([[[0, 4], [2, 6]], [[1, 5], [3, 7]]]) """ try: swapaxes = a.swapaxes except AttributeError: return _wrapit(a, 'swapaxes', axis1, axis2) return swapaxes(axis1, axis2) def transpose(a, axes=None): """ Permute the dimensions of an array. Parameters ---------- a : array_like Input array. axes : list of ints, optional By default, reverse the dimensions, otherwise permute the axes according to the values given. Returns ------- p : ndarray `a` with its axes permuted. A view is returned whenever possible. See Also -------- rollaxis Examples -------- >>> x = np.arange(4).reshape((2,2)) >>> x array([[0, 1], [2, 3]]) >>> np.transpose(x) array([[0, 2], [1, 3]]) >>> x = np.ones((1, 2, 3)) >>> np.transpose(x, (1, 0, 2)).shape (2, 1, 3) """ try: transpose = a.transpose except AttributeError: return _wrapit(a, 'transpose', axes) return transpose(axes) def partition(a, kth, axis=-1, kind='introselect', order=None): """ Return a partitioned copy of an array. Creates a copy of the array with its elements rearranged in such a way that the value of the element in kth position is in the position it would be in a sorted array. All elements smaller than the kth element are moved before this element and all equal or greater are moved behind it. The ordering of the elements in the two partitions is undefined. .. versionadded:: 1.8.0 Parameters ---------- a : array_like Array to be sorted. kth : int or sequence of ints Element index to partition by. The kth value of the element will be in its final sorted position and all smaller elements will be moved before it and all equal or greater elements behind it. The order all elements in the partitions is undefined. If provided with a sequence of kth it will partition all elements indexed by kth of them into their sorted position at once. axis : int or None, optional Axis along which to sort. If None, the array is flattened before sorting. The default is -1, which sorts along the last axis. kind : {'introselect'}, optional Selection algorithm. Default is 'introselect'. order : list, optional When `a` is a structured array, this argument specifies which fields to compare first, second, and so on. This list does not need to include all of the fields. Returns ------- partitioned_array : ndarray Array of the same type and shape as `a`. See Also -------- ndarray.partition : Method to sort an array in-place. argpartition : Indirect partition. sort : Full sorting Notes ----- 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: ================= ======= ============= ============ ======= kind speed worst case work space stable ================= ======= ============= ============ ======= 'introselect' 1 O(n) 0 no ================= ======= ============= ============ ======= All the partition algorithms make temporary copies of the data when partitioning along any but the last axis. Consequently, partitioning along the last axis is faster and uses less space than partitioning along any other axis. The sort order for complex numbers is lexicographic. If both the real and imaginary parts are non-nan then the order is determined by the real parts except when they are equal, in which case the order is determined by the imaginary parts. Examples -------- >>> a = np.array([3, 4, 2, 1]) >>> np.partition(a, 3) array([2, 1, 3, 4]) >>> np.partition(a, (1, 3)) array([1, 2, 3, 4]) """ if axis is None: a = asanyarray(a).flatten() axis = 0 else: a = asanyarray(a).copy() a.partition(kth, axis=axis, kind=kind, order=order) return a def argpartition(a, kth, axis=-1, kind='introselect', order=None): """ Perform an indirect partition along the given axis using the algorithm specified by the `kind` keyword. It returns an array of indices of the same shape as `a` that index data along the given axis in partitioned order. .. versionadded:: 1.8.0 Parameters ---------- a : array_like Array to sort. kth : int or sequence of ints Element index to partition by. The kth element will be in its final sorted position and all smaller elements will be moved before it and all larger elements behind it. The order all elements in the partitions is undefined. If provided with a sequence of kth it will partition all of them into their sorted position at once. axis : int or None, optional Axis along which to sort. The default is -1 (the last axis). If None, the flattened array is used. kind : {'introselect'}, optional Selection algorithm. Default is 'introselect' order : list, optional When `a` is an array with fields defined, this argument specifies which fields to compare first, second, etc. Not all fields need be specified. Returns ------- index_array : ndarray, int Array of indices that partition `a` along the specified axis. In other words, ``a[index_array]`` yields a sorted `a`. See Also -------- partition : Describes partition algorithms used. ndarray.partition : Inplace partition. argsort : Full indirect sort Notes ----- See `partition` for notes on the different selection algorithms. Examples -------- One dimensional array: >>> x = np.array([3, 4, 2, 1]) >>> x[np.argpartition(x, 3)] array([2, 1, 3, 4]) >>> x[np.argpartition(x, (1, 3))] array([1, 2, 3, 4]) """ return a.argpartition(kth, axis, kind=kind, order=order) def sort(a, axis=-1, kind='quicksort', order=None): """ Return a sorted copy of an array. Parameters ---------- a : array_like Array to be sorted. axis : int or None, optional Axis along which to sort. If None, the array is flattened before sorting. The default is -1, which sorts along the last axis. kind : {'quicksort', 'mergesort', 'heapsort'}, optional Sorting algorithm. Default is 'quicksort'. order : list, optional When `a` is a structured array, this argument specifies which fields to compare first, second, and so on. This list does not need to include all of the fields. Returns ------- sorted_array : ndarray Array of the same type and shape as `a`. See Also -------- ndarray.sort : Method to sort an array in-place. argsort : Indirect sort. lexsort : Indirect stable sort on multiple keys. searchsorted : Find elements in a sorted array. partition : Partial sort. Notes ----- The various sorting 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: =========== ======= ============= ============ ======= kind speed worst case work space stable =========== ======= ============= ============ ======= 'quicksort' 1 O(n^2) 0 no 'mergesort' 2 O(n*log(n)) ~n/2 yes 'heapsort' 3 O(n*log(n)) 0 no =========== ======= ============= ============ ======= All the sort algorithms make temporary copies of the data when sorting along any but the last axis. Consequently, sorting along the last axis is faster and uses less space than sorting along any other axis. The sort order for complex numbers is lexicographic. If both the real and imaginary parts are non-nan then the order is determined by the real parts except when they are equal, in which case the order is determined by the imaginary parts. Previous to numpy 1.4.0 sorting real and complex arrays containing nan values led to undefined behaviour. In numpy versions >= 1.4.0 nan values are sorted to the end. The extended sort order is: * Real: [R, nan] * Complex: [R + Rj, R + nanj, nan + Rj, nan + nanj] where R is a non-nan real value. Complex values with the same nan placements are sorted according to the non-nan part if it exists. Non-nan values are sorted as before. Examples -------- >>> a = np.array([[1,4],[3,1]]) >>> np.sort(a) # sort along the last axis array([[1, 4], [1, 3]]) >>> np.sort(a, axis=None) # sort the flattened array array([1, 1, 3, 4]) >>> np.sort(a, axis=0) # sort along the first axis array([[1, 1], [3, 4]]) Use the `order` keyword to specify a field to use when sorting a structured array: >>> dtype = [('name', 'S10'), ('height', float), ('age', int)] >>> values = [('Arthur', 1.8, 41), ('Lancelot', 1.9, 38), ... ('Galahad', 1.7, 38)] >>> a = np.array(values, dtype=dtype) # create a structured array >>> np.sort(a, order='height') # doctest: +SKIP array([('Galahad', 1.7, 38), ('Arthur', 1.8, 41), ('Lancelot', 1.8999999999999999, 38)], dtype=[('name', '|S10'), ('height', '>> np.sort(a, order=['age', 'height']) # doctest: +SKIP array([('Galahad', 1.7, 38), ('Lancelot', 1.8999999999999999, 38), ('Arthur', 1.8, 41)], dtype=[('name', '|S10'), ('height', '>> x = np.array([3, 1, 2]) >>> np.argsort(x) array([1, 2, 0]) Two-dimensional array: >>> x = np.array([[0, 3], [2, 2]]) >>> x array([[0, 3], [2, 2]]) >>> np.argsort(x, axis=0) array([[0, 1], [1, 0]]) >>> np.argsort(x, axis=1) array([[0, 1], [0, 1]]) Sorting with keys: >>> x = np.array([(1, 0), (0, 1)], dtype=[('x', '>> x array([(1, 0), (0, 1)], dtype=[('x', '>> np.argsort(x, order=('x','y')) array([1, 0]) >>> np.argsort(x, order=('y','x')) array([0, 1]) """ try: argsort = a.argsort except AttributeError: return _wrapit(a, 'argsort', axis, kind, order) return argsort(axis, kind, order) def argmax(a, axis=None): """ Indices of the maximum values along an axis. Parameters ---------- a : array_like Input array. axis : int, optional By default, the index is into the flattened array, otherwise along the specified axis. Returns ------- index_array : ndarray of ints Array of indices into the array. It has the same shape as `a.shape` with the dimension along `axis` removed. See Also -------- ndarray.argmax, argmin amax : The maximum value along a given axis. unravel_index : Convert a flat index into an index tuple. Notes ----- In case of multiple occurrences of the maximum values, the indices corresponding to the first occurrence are returned. Examples -------- >>> a = np.arange(6).reshape(2,3) >>> a array([[0, 1, 2], [3, 4, 5]]) >>> np.argmax(a) 5 >>> np.argmax(a, axis=0) array([1, 1, 1]) >>> np.argmax(a, axis=1) array([2, 2]) >>> b = np.arange(6) >>> b[1] = 5 >>> b array([0, 5, 2, 3, 4, 5]) >>> np.argmax(b) # Only the first occurrence is returned. 1 """ try: argmax = a.argmax except AttributeError: return _wrapit(a, 'argmax', axis) return argmax(axis) def argmin(a, axis=None): """ Return the indices of the minimum values along an axis. See Also -------- argmax : Similar function. Please refer to `numpy.argmax` for detailed documentation. """ try: argmin = a.argmin except AttributeError: return _wrapit(a, 'argmin', axis) return argmin(axis) def searchsorted(a, v, side='left', sorter=None): """ Find indices where elements should be inserted to maintain order. Find the indices into a sorted array `a` such that, if the corresponding elements in `v` were inserted before the indices, the order of `a` would be preserved. Parameters ---------- a : 1-D array_like Input array. If `sorter` is None, then it must be sorted in ascending order, otherwise `sorter` must be an array of indices that sort it. v : array_like Values to insert into `a`. side : {'left', 'right'}, optional If 'left', the index of the first suitable location found is given. If 'right', return the last such index. If there is no suitable index, return either 0 or N (where N is the length of `a`). sorter : 1-D array_like, optional .. versionadded:: 1.7.0 Optional array of integer indices that sort array a into ascending order. They are typically the result of argsort. Returns ------- indices : array of ints Array of insertion points with the same shape as `v`. See Also -------- sort : Return a sorted copy of an array. histogram : Produce histogram from 1-D data. Notes ----- Binary search is used to find the required insertion points. As of Numpy 1.4.0 `searchsorted` works with real/complex arrays containing `nan` values. The enhanced sort order is documented in `sort`. Examples -------- >>> np.searchsorted([1,2,3,4,5], 3) 2 >>> np.searchsorted([1,2,3,4,5], 3, side='right') 3 >>> np.searchsorted([1,2,3,4,5], [-10, 10, 2, 3]) array([0, 5, 1, 2]) """ try: searchsorted = a.searchsorted except AttributeError: return _wrapit(a, 'searchsorted', v, side, sorter) return searchsorted(v, side, sorter) def resize(a, new_shape): """ Return a new array with the specified shape. If the new array is larger than the original array, then the new array is filled with repeated copies of `a`. Note that this behavior is different from a.resize(new_shape) which fills with zeros instead of repeated copies of `a`. Parameters ---------- a : array_like Array to be resized. new_shape : int or tuple of int Shape of resized array. Returns ------- reshaped_array : ndarray The new array is formed from the data in the old array, repeated if necessary to fill out the required number of elements. The data are repeated in the order that they are stored in memory. See Also -------- ndarray.resize : resize an array in-place. Examples -------- >>> a=np.array([[0,1],[2,3]]) >>> np.resize(a,(1,4)) array([[0, 1, 2, 3]]) >>> np.resize(a,(2,4)) array([[0, 1, 2, 3], [0, 1, 2, 3]]) """ if isinstance(new_shape, (int, nt.integer)): new_shape = (new_shape,) a = ravel(a) Na = len(a) if not Na: return mu.zeros(new_shape, a.dtype.char) total_size = um.multiply.reduce(new_shape) n_copies = int(total_size / Na) extra = total_size % Na if total_size == 0: return a[:0] if extra != 0: n_copies = n_copies+1 extra = Na-extra a = concatenate( (a,)*n_copies) if extra > 0: a = a[:-extra] return reshape(a, new_shape) def squeeze(a, axis=None): """ Remove single-dimensional entries from the shape of an array. Parameters ---------- a : array_like Input data. axis : None or int or tuple of ints, optional .. versionadded:: 1.7.0 Selects a subset of the single-dimensional entries in the shape. If an axis is selected with shape entry greater than one, an error is raised. Returns ------- squeezed : ndarray The input array, but with with all or a subset of the dimensions of length 1 removed. This is always `a` itself or a view into `a`. Examples -------- >>> x = np.array([[[0], [1], [2]]]) >>> x.shape (1, 3, 1) >>> np.squeeze(x).shape (3,) >>> np.squeeze(x, axis=(2,)).shape (1, 3) """ try: squeeze = a.squeeze except AttributeError: return _wrapit(a, 'squeeze') try: # First try to use the new axis= parameter return squeeze(axis=axis) except TypeError: # For backwards compatibility return squeeze() def diagonal(a, offset=0, axis1=0, axis2=1): """ Return specified diagonals. If `a` is 2-D, returns the diagonal of `a` with the given offset, i.e., the collection of elements of the form ``a[i, i+offset]``. If `a` has more than two dimensions, then the axes specified by `axis1` and `axis2` are used to determine the 2-D sub-array whose diagonal is returned. The shape of the resulting array can be determined by removing `axis1` and `axis2` and appending an index to the right equal to the size of the resulting diagonals. In versions of NumPy prior to 1.7, this function always returned a new, independent array containing a copy of the values in the diagonal. In NumPy 1.7, it continues to return a copy of the diagonal, but depending on this fact is deprecated. Writing to the resulting array continues to work as it used to, but a FutureWarning will be issued. In NumPy 1.9, it will switch to returning a read-only view on the original array. Attempting to write to the resulting array will produce an error. In NumPy 1.10, it will still return a view, but this view will no longer be marked read-only. Writing to the returned array will alter your original array as well. If you don't write to the array returned by this function, then you can just ignore all of the above. If you depend on the current behavior, then we suggest copying the returned array explicitly, i.e., use ``np.diagonal(a).copy()`` instead of just ``np.diagonal(a)``. This will work with both past and future versions of NumPy. Parameters ---------- a : array_like Array from which the diagonals are taken. offset : int, optional Offset of the diagonal from the main diagonal. Can be positive or negative. Defaults to main diagonal (0). axis1 : int, optional Axis to be used as the first axis of the 2-D sub-arrays from which the diagonals should be taken. Defaults to first axis (0). axis2 : int, optional Axis to be used as the second axis of the 2-D sub-arrays from which the diagonals should be taken. Defaults to second axis (1). Returns ------- array_of_diagonals : ndarray If `a` is 2-D, a 1-D array containing the diagonal is returned. If the dimension of `a` is larger, then an array of diagonals is returned, "packed" from left-most dimension to right-most (e.g., if `a` is 3-D, then the diagonals are "packed" along rows). Raises ------ ValueError If the dimension of `a` is less than 2. See Also -------- diag : MATLAB work-a-like for 1-D and 2-D arrays. diagflat : Create diagonal arrays. trace : Sum along diagonals. Examples -------- >>> a = np.arange(4).reshape(2,2) >>> a array([[0, 1], [2, 3]]) >>> a.diagonal() array([0, 3]) >>> a.diagonal(1) array([1]) A 3-D example: >>> a = np.arange(8).reshape(2,2,2); a array([[[0, 1], [2, 3]], [[4, 5], [6, 7]]]) >>> a.diagonal(0, # Main diagonals of two arrays created by skipping ... 0, # across the outer(left)-most axis last and ... 1) # the "middle" (row) axis first. array([[0, 6], [1, 7]]) The sub-arrays whose main diagonals we just obtained; note that each corresponds to fixing the right-most (column) axis, and that the diagonals are "packed" in rows. >>> a[:,:,0] # main diagonal is [0 6] array([[0, 2], [4, 6]]) >>> a[:,:,1] # main diagonal is [1 7] array([[1, 3], [5, 7]]) """ return asarray(a).diagonal(offset, axis1, axis2) def trace(a, offset=0, axis1=0, axis2=1, dtype=None, out=None): """ Return the sum along diagonals of the array. If `a` is 2-D, the sum along its diagonal with the given offset is returned, i.e., the sum of elements ``a[i,i+offset]`` for all i. If `a` has more than two dimensions, then the axes specified by axis1 and axis2 are used to determine the 2-D sub-arrays whose traces are returned. The shape of the resulting array is the same as that of `a` with `axis1` and `axis2` removed. Parameters ---------- a : array_like Input array, from which the diagonals are taken. offset : int, optional Offset of the diagonal from the main diagonal. Can be both positive and negative. Defaults to 0. axis1, axis2 : int, optional Axes to be used as the first and second axis of the 2-D sub-arrays from which the diagonals should be taken. Defaults are the first two axes of `a`. dtype : dtype, optional Determines the data-type of the returned array and of the accumulator where the elements are summed. If dtype has the value None and `a` is of integer type of precision less than the default integer precision, then the default integer precision is used. Otherwise, the precision is the same as that of `a`. 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. Returns ------- sum_along_diagonals : ndarray If `a` is 2-D, the sum along the diagonal is returned. If `a` has larger dimensions, then an array of sums along diagonals is returned. See Also -------- diag, diagonal, diagflat Examples -------- >>> np.trace(np.eye(3)) 3.0 >>> a = np.arange(8).reshape((2,2,2)) >>> np.trace(a) array([6, 8]) >>> a = np.arange(24).reshape((2,2,2,3)) >>> np.trace(a).shape (2, 3) """ return asarray(a).trace(offset, axis1, axis2, dtype, out) def ravel(a, order='C'): """ Return a flattened array. A 1-D array, containing the elements of the input, is returned. A copy is made only if needed. Parameters ---------- a : array_like Input array. The elements in `a` are read in the order specified by `order`, and packed as a 1-D array. order : {'C','F', 'A', 'K'}, optional The elements of `a` are read using this index order. 'C' means to index the elements in C-like order, with the last axis index changing fastest, back to the first axis index changing slowest. 'F' means to index the elements in Fortran-like index order, with the first index changing fastest, and the last index changing slowest. Note that the 'C' and 'F' options take no account of the memory layout of the underlying array, and only refer to the order of axis indexing. 'A' means to read the elements in Fortran-like index order if `a` is Fortran *contiguous* in memory, C-like order otherwise. 'K' means to read the elements in the order they occur in memory, except for reversing the data when strides are negative. By default, 'C' index order is used. Returns ------- 1d_array : ndarray Output of the same dtype as `a`, and of shape ``(a.size,)``. See Also -------- ndarray.flat : 1-D iterator over an array. ndarray.flatten : 1-D array copy of the elements of an array in row-major order. Notes ----- In C-like (row-major) order, in two dimensions, the row index varies the slowest, and the column index the quickest. This can be generalized to multiple dimensions, where row-major order implies that the index along the first axis varies slowest, and the index along the last quickest. The opposite holds for Fortran-like, or column-major, index ordering. Examples -------- It is equivalent to ``reshape(-1, order=order)``. >>> x = np.array([[1, 2, 3], [4, 5, 6]]) >>> print np.ravel(x) [1 2 3 4 5 6] >>> print x.reshape(-1) [1 2 3 4 5 6] >>> print np.ravel(x, order='F') [1 4 2 5 3 6] When ``order`` is 'A', it will preserve the array's 'C' or 'F' ordering: >>> print np.ravel(x.T) [1 4 2 5 3 6] >>> print np.ravel(x.T, order='A') [1 2 3 4 5 6] When ``order`` is 'K', it will preserve orderings that are neither 'C' nor 'F', but won't reverse axes: >>> a = np.arange(3)[::-1]; a array([2, 1, 0]) >>> a.ravel(order='C') array([2, 1, 0]) >>> a.ravel(order='K') array([2, 1, 0]) >>> a = np.arange(12).reshape(2,3,2).swapaxes(1,2); a array([[[ 0, 2, 4], [ 1, 3, 5]], [[ 6, 8, 10], [ 7, 9, 11]]]) >>> a.ravel(order='C') array([ 0, 2, 4, 1, 3, 5, 6, 8, 10, 7, 9, 11]) >>> a.ravel(order='K') array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]) """ return asarray(a).ravel(order) def nonzero(a): """ Return the indices of the elements that are non-zero. Returns a tuple of arrays, one for each dimension of `a`, containing the indices of the non-zero elements in that dimension. The corresponding non-zero values can be obtained with:: a[nonzero(a)] To group the indices by element, rather than dimension, use:: transpose(nonzero(a)) The result of this is always a 2-D array, with a row for each non-zero element. Parameters ---------- a : array_like Input array. Returns ------- tuple_of_arrays : tuple Indices of elements that are non-zero. See Also -------- flatnonzero : Return indices that are non-zero in the flattened version of the input array. ndarray.nonzero : Equivalent ndarray method. count_nonzero : Counts the number of non-zero elements in the input array. Examples -------- >>> x = np.eye(3) >>> x array([[ 1., 0., 0.], [ 0., 1., 0.], [ 0., 0., 1.]]) >>> np.nonzero(x) (array([0, 1, 2]), array([0, 1, 2])) >>> x[np.nonzero(x)] array([ 1., 1., 1.]) >>> np.transpose(np.nonzero(x)) array([[0, 0], [1, 1], [2, 2]]) A common use for ``nonzero`` is to find the indices of an array, where a condition is True. Given an array `a`, the condition `a` > 3 is a boolean array and since False is interpreted as 0, np.nonzero(a > 3) yields the indices of the `a` where the condition is true. >>> a = np.array([[1,2,3],[4,5,6],[7,8,9]]) >>> a > 3 array([[False, False, False], [ True, True, True], [ True, True, True]], dtype=bool) >>> np.nonzero(a > 3) (array([1, 1, 1, 2, 2, 2]), array([0, 1, 2, 0, 1, 2])) The ``nonzero`` method of the boolean array can also be called. >>> (a > 3).nonzero() (array([1, 1, 1, 2, 2, 2]), array([0, 1, 2, 0, 1, 2])) """ try: nonzero = a.nonzero except AttributeError: res = _wrapit(a, 'nonzero') else: res = nonzero() return res def shape(a): """ Return the shape of an array. Parameters ---------- a : array_like Input array. Returns ------- shape : tuple of ints The elements of the shape tuple give the lengths of the corresponding array dimensions. See Also -------- alen ndarray.shape : Equivalent array method. Examples -------- >>> np.shape(np.eye(3)) (3, 3) >>> np.shape([[1, 2]]) (1, 2) >>> np.shape([0]) (1,) >>> np.shape(0) () >>> a = np.array([(1, 2), (3, 4)], dtype=[('x', 'i4'), ('y', 'i4')]) >>> np.shape(a) (2,) >>> a.shape (2,) """ try: result = a.shape except AttributeError: result = asarray(a).shape return result def compress(condition, a, axis=None, out=None): """ Return selected slices of an array along given axis. When working along a given axis, a slice along that axis is returned in `output` for each index where `condition` evaluates to True. When working on a 1-D array, `compress` is equivalent to `extract`. Parameters ---------- condition : 1-D array of bools Array that selects which entries to return. If len(condition) is less than the size of `a` along the given axis, then output is truncated to the length of the condition array. a : array_like Array from which to extract a part. axis : int, optional Axis along which to take slices. If None (default), work on the flattened array. out : ndarray, optional Output array. Its type is preserved and it must be of the right shape to hold the output. Returns ------- compressed_array : ndarray A copy of `a` without the slices along axis for which `condition` is false. See Also -------- take, choose, diag, diagonal, select ndarray.compress : Equivalent method in ndarray np.extract: Equivalent method when working on 1-D arrays numpy.doc.ufuncs : Section "Output arguments" Examples -------- >>> a = np.array([[1, 2], [3, 4], [5, 6]]) >>> a array([[1, 2], [3, 4], [5, 6]]) >>> np.compress([0, 1], a, axis=0) array([[3, 4]]) >>> np.compress([False, True, True], a, axis=0) array([[3, 4], [5, 6]]) >>> np.compress([False, True], a, axis=1) array([[2], [4], [6]]) Working on the flattened array does not return slices along an axis but selects elements. >>> np.compress([False, True], a) array([2]) """ try: compress = a.compress except AttributeError: return _wrapit(a, 'compress', condition, axis, out) return compress(condition, axis, out) def clip(a, a_min, a_max, out=None): """ Clip (limit) the values in an array. Given an interval, values outside the interval are clipped to the interval edges. For example, if an interval of ``[0, 1]`` is specified, values smaller than 0 become 0, and values larger than 1 become 1. Parameters ---------- a : array_like Array containing elements to clip. a_min : scalar or array_like Minimum value. a_max : scalar or array_like Maximum value. If `a_min` or `a_max` are array_like, then they will be broadcasted to the shape of `a`. out : ndarray, optional The results will be placed in this array. It may be the input array for in-place clipping. `out` must be of the right shape to hold the output. Its type is preserved. Returns ------- clipped_array : ndarray An array with the elements of `a`, but where values < `a_min` are replaced with `a_min`, and those > `a_max` with `a_max`. See Also -------- numpy.doc.ufuncs : Section "Output arguments" Examples -------- >>> a = np.arange(10) >>> np.clip(a, 1, 8) array([1, 1, 2, 3, 4, 5, 6, 7, 8, 8]) >>> a array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) >>> np.clip(a, 3, 6, out=a) array([3, 3, 3, 3, 4, 5, 6, 6, 6, 6]) >>> a = np.arange(10) >>> a array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) >>> np.clip(a, [3,4,1,1,1,4,4,4,4,4], 8) array([3, 4, 2, 3, 4, 5, 6, 7, 8, 8]) """ try: clip = a.clip except AttributeError: return _wrapit(a, 'clip', a_min, a_max, out) return clip(a_min, a_max, out) def sum(a, axis=None, dtype=None, out=None, keepdims=False): """ Sum of array elements over a given axis. Parameters ---------- a : array_like Elements to sum. axis : None or int or tuple of ints, optional Axis or axes along which a sum is performed. The default (`axis` = `None`) is perform a sum over all the dimensions of the input array. `axis` may be negative, in which case it counts from the last to the first axis. .. versionadded:: 1.7.0 If this is a tuple of ints, a sum is performed on multiple axes, instead of a single axis or all the axes as before. dtype : dtype, optional The type of the returned array and of the accumulator in which the elements are summed. By default, the dtype of `a` is used. An exception is when `a` has an integer type with less precision than the default platform integer. In that case, the default platform integer is used instead. out : ndarray, optional Array into which the output is placed. By default, a new array is created. If `out` is given, it must be of the appropriate shape (the shape of `a` with `axis` removed, i.e., ``numpy.delete(a.shape, axis)``). Its type is preserved. See `doc.ufuncs` (Section "Output arguments") for more details. 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 ------- sum_along_axis : ndarray An array with the same shape as `a`, with the specified axis removed. If `a` is a 0-d array, or if `axis` is None, a scalar is returned. If an output array is specified, a reference to `out` is returned. See Also -------- ndarray.sum : Equivalent method. cumsum : Cumulative sum of array elements. trapz : Integration of array values using the composite trapezoidal rule. mean, average Notes ----- Arithmetic is modular when using integer types, and no error is raised on overflow. Examples -------- >>> np.sum([0.5, 1.5]) 2.0 >>> np.sum([0.5, 0.7, 0.2, 1.5], dtype=np.int32) 1 >>> np.sum([[0, 1], [0, 5]]) 6 >>> np.sum([[0, 1], [0, 5]], axis=0) array([0, 6]) >>> np.sum([[0, 1], [0, 5]], axis=1) array([1, 5]) If the accumulator is too small, overflow occurs: >>> np.ones(128, dtype=np.int8).sum(dtype=np.int8) -128 """ if isinstance(a, _gentype): res = _sum_(a) if out is not None: out[...] = res return out return res elif type(a) is not mu.ndarray: try: sum = a.sum except AttributeError: return _methods._sum(a, axis=axis, dtype=dtype, out=out, keepdims=keepdims) # NOTE: Dropping the keepdims parameters here... return sum(axis=axis, dtype=dtype, out=out) else: return _methods._sum(a, axis=axis, dtype=dtype, out=out, keepdims=keepdims) def product (a, axis=None, dtype=None, out=None, keepdims=False): """ Return the product of array elements over a given axis. See Also -------- prod : equivalent function; see for details. """ return um.multiply.reduce(a, axis=axis, dtype=dtype, out=out, keepdims=keepdims) def sometrue(a, axis=None, out=None, keepdims=False): """ Check whether some values are true. Refer to `any` for full documentation. See Also -------- any : equivalent function """ arr = asanyarray(a) try: return arr.any(axis=axis, out=out, keepdims=keepdims) except TypeError: return arr.any(axis=axis, out=out) def alltrue (a, axis=None, out=None, keepdims=False): """ Check if all elements of input array are true. See Also -------- numpy.all : Equivalent function; see for details. """ arr = asanyarray(a) try: return arr.all(axis=axis, out=out, keepdims=keepdims) except TypeError: return arr.all(axis=axis, out=out) def any(a, axis=None, out=None, keepdims=False): """ Test whether any array element along a given axis evaluates to True. Returns single boolean unless `axis` is not ``None`` Parameters ---------- a : array_like 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 dimensions of the input array. `axis` may be negative, in which case it counts from the last to the first axis. .. versionadded:: 1.7.0 If this is a tuple of ints, a reduction is performed on multiple axes, instead of a single axis or all the axes as before. out : ndarray, optional Alternate output array in which to place the result. It must have the same shape as the expected output and its type is preserved (e.g., if it is of type float, then it will remain so, returning 1.0 for True and 0.0 for False, regardless of the type of `a`). See `doc.ufuncs` (Section "Output arguments") for details. 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 ------- any : bool or ndarray A new boolean or `ndarray` is returned unless `out` is specified, in which case a reference to `out` is returned. See Also -------- ndarray.any : equivalent method all : Test whether all elements along a given axis evaluate to True. Notes ----- Not a Number (NaN), positive infinity and negative infinity evaluate to `True` because these are not equal to zero. Examples -------- >>> np.any([[True, False], [True, True]]) True >>> np.any([[True, False], [False, False]], axis=0) array([ True, False], dtype=bool) >>> np.any([-1, 0, 5]) True >>> np.any(np.nan) True >>> o=np.array([False]) >>> z=np.any([-1, 4, 5], out=o) >>> z, o (array([ True], dtype=bool), array([ True], dtype=bool)) >>> # Check now that z is a reference to o >>> z is o True >>> id(z), id(o) # identity of z and o # doctest: +SKIP (191614240, 191614240) """ arr = asanyarray(a) try: return arr.any(axis=axis, out=out, keepdims=keepdims) except TypeError: return arr.any(axis=axis, out=out) def all(a, axis=None, out=None, keepdims=False): """ Test whether all array elements along a given axis evaluate to True. Parameters ---------- a : array_like 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 dimensions of the input array. `axis` may be negative, in which case it counts from the last to the first axis. .. versionadded:: 1.7.0 If this is a tuple of ints, a reduction is performed on multiple axes, instead of a single axis or all the axes as before. out : ndarray, optional Alternate output array in which to place the result. It must have the same shape as the expected output and its type is preserved (e.g., if ``dtype(out)`` is float, the result will consist of 0.0's and 1.0's). See `doc.ufuncs` (Section "Output arguments") for more details. 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 ------- all : ndarray, bool A new boolean or array is returned unless `out` is specified, in which case a reference to `out` is returned. See Also -------- ndarray.all : equivalent method any : Test whether any element along a given axis evaluates to True. Notes ----- Not a Number (NaN), positive infinity and negative infinity evaluate to `True` because these are not equal to zero. Examples -------- >>> np.all([[True,False],[True,True]]) False >>> np.all([[True,False],[True,True]], axis=0) array([ True, False], dtype=bool) >>> np.all([-1, 4, 5]) True >>> np.all([1.0, np.nan]) True >>> o=np.array([False]) >>> z=np.all([-1, 4, 5], out=o) >>> id(z), id(o), z # doctest: +SKIP (28293632, 28293632, array([ True], dtype=bool)) """ arr = asanyarray(a) try: return arr.all(axis=axis, out=out, keepdims=keepdims) except TypeError: return arr.all(axis=axis, out=out) def cumsum (a, axis=None, dtype=None, out=None): """ Return the cumulative sum of the elements along a given axis. Parameters ---------- a : array_like Input array. axis : int, optional Axis along which the cumulative sum is computed. The default (None) is to compute the cumsum over the flattened array. dtype : dtype, optional Type of the returned array and of the accumulator in which the elements are summed. If `dtype` is not specified, it defaults to the dtype of `a`, unless `a` has an integer dtype with a precision less than that of the default platform integer. In that case, the default platform integer is used. 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 will be cast if necessary. See `doc.ufuncs` (Section "Output arguments") for more details. Returns ------- cumsum_along_axis : ndarray. A new array holding the result is returned unless `out` is specified, in which case a reference to `out` is returned. The result has the same size as `a`, and the same shape as `a` if `axis` is not None or `a` is a 1-d array. See Also -------- sum : Sum array elements. trapz : Integration of array values using the composite trapezoidal rule. diff : Calculate the n-th order discrete difference along given axis. Notes ----- Arithmetic is modular when using integer types, and no error is raised on overflow. Examples -------- >>> a = np.array([[1,2,3], [4,5,6]]) >>> a array([[1, 2, 3], [4, 5, 6]]) >>> np.cumsum(a) array([ 1, 3, 6, 10, 15, 21]) >>> np.cumsum(a, dtype=float) # specifies type of output value(s) array([ 1., 3., 6., 10., 15., 21.]) >>> np.cumsum(a,axis=0) # sum over rows for each of the 3 columns array([[1, 2, 3], [5, 7, 9]]) >>> np.cumsum(a,axis=1) # sum over columns for each of the 2 rows array([[ 1, 3, 6], [ 4, 9, 15]]) """ try: cumsum = a.cumsum except AttributeError: return _wrapit(a, 'cumsum', axis, dtype, out) return cumsum(axis, dtype, out) def cumproduct(a, axis=None, dtype=None, out=None): """ Return the cumulative product over the given axis. See Also -------- cumprod : equivalent function; see for details. """ try: cumprod = a.cumprod except AttributeError: return _wrapit(a, 'cumprod', axis, dtype, out) return cumprod(axis, dtype, out) def ptp(a, axis=None, out=None): """ Range of values (maximum - minimum) along an axis. The name of the function comes from the acronym for 'peak to peak'. Parameters ---------- a : array_like Input values. axis : int, optional Axis along which to find the peaks. By default, flatten the array. out : array_like 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 values will be cast if necessary. Returns ------- ptp : ndarray A new array holding the result, unless `out` was specified, in which case a reference to `out` is returned. Examples -------- >>> x = np.arange(4).reshape((2,2)) >>> x array([[0, 1], [2, 3]]) >>> np.ptp(x, axis=0) array([2, 2]) >>> np.ptp(x, axis=1) array([1, 1]) """ try: ptp = a.ptp except AttributeError: return _wrapit(a, 'ptp', axis, out) return ptp(axis, out) def amax(a, axis=None, out=None, keepdims=False): """ Return the maximum of an array or maximum along an axis. Parameters ---------- a : array_like Input data. axis : int, optional Axis along which to operate. By default, flattened input is used. out : ndarray, optional Alternative output array in which to place the result. Must be of the same shape and buffer length as the expected output. See `doc.ufuncs` (Section "Output arguments") for more details. 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 ------- amax : ndarray or scalar Maximum of `a`. If `axis` is None, the result is a scalar value. If `axis` is given, the result is an array of dimension ``a.ndim - 1``. See Also -------- amin : The minimum value of an array along a given axis, propagating any NaNs. nanmax : The maximum value of an array along a given axis, ignoring any NaNs. maximum : Element-wise maximum of two arrays, propagating any NaNs. fmax : Element-wise maximum of two arrays, ignoring any NaNs. argmax : Return the indices of the maximum values. nanmin, minimum, fmin Notes ----- NaN values are propagated, that is if at least one item is NaN, the corresponding max value will be NaN as well. To ignore NaN values (MATLAB behavior), please use nanmax. Don't use `amax` for element-wise comparison of 2 arrays; when ``a.shape[0]`` is 2, ``maximum(a[0], a[1])`` is faster than ``amax(a, axis=0)``. Examples -------- >>> a = np.arange(4).reshape((2,2)) >>> a array([[0, 1], [2, 3]]) >>> np.amax(a) # Maximum of the flattened array 3 >>> np.amax(a, axis=0) # Maxima along the first axis array([2, 3]) >>> np.amax(a, axis=1) # Maxima along the second axis array([1, 3]) >>> b = np.arange(5, dtype=np.float) >>> b[2] = np.NaN >>> np.amax(b) nan >>> np.nanmax(b) 4.0 """ if type(a) is not mu.ndarray: try: amax = a.max except AttributeError: return _methods._amax(a, axis=axis, out=out, keepdims=keepdims) # NOTE: Dropping the keepdims parameter return amax(axis=axis, out=out) else: return _methods._amax(a, axis=axis, out=out, keepdims=keepdims) def amin(a, axis=None, out=None, keepdims=False): """ Return the minimum of an array or minimum along an axis. Parameters ---------- a : array_like Input data. axis : int, optional Axis along which to operate. By default, flattened input is used. out : ndarray, optional Alternative output array in which to place the result. Must be of the same shape and buffer length as the expected output. See `doc.ufuncs` (Section "Output arguments") for more details. 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 ------- amin : ndarray or scalar Minimum of `a`. If `axis` is None, the result is a scalar value. If `axis` is given, the result is an array of dimension ``a.ndim - 1``. See Also -------- amax : The maximum value of an array along a given axis, propagating any NaNs. nanmin : The minimum value of an array along a given axis, ignoring any NaNs. minimum : Element-wise minimum of two arrays, propagating any NaNs. fmin : Element-wise minimum of two arrays, ignoring any NaNs. argmin : Return the indices of the minimum values. nanmax, maximum, fmax Notes ----- NaN values are propagated, that is if at least one item is NaN, the corresponding min value will be NaN as well. To ignore NaN values (MATLAB behavior), please use nanmin. Don't use `amin` for element-wise comparison of 2 arrays; when ``a.shape[0]`` is 2, ``minimum(a[0], a[1])`` is faster than ``amin(a, axis=0)``. Examples -------- >>> a = np.arange(4).reshape((2,2)) >>> a array([[0, 1], [2, 3]]) >>> np.amin(a) # Minimum of the flattened array 0 >>> np.amin(a, axis=0) # Minima along the first axis array([0, 1]) >>> np.amin(a, axis=1) # Minima along the second axis array([0, 2]) >>> b = np.arange(5, dtype=np.float) >>> b[2] = np.NaN >>> np.amin(b) nan >>> np.nanmin(b) 0.0 """ if type(a) is not mu.ndarray: try: amin = a.min except AttributeError: return _methods._amin(a, axis=axis, out=out, keepdims=keepdims) # NOTE: Dropping the keepdims parameter return amin(axis=axis, out=out) else: return _methods._amin(a, axis=axis, out=out, keepdims=keepdims) def alen(a): """ Return the length of the first dimension of the input array. Parameters ---------- a : array_like Input array. Returns ------- alen : int Length of the first dimension of `a`. See Also -------- shape, size Examples -------- >>> a = np.zeros((7,4,5)) >>> a.shape[0] 7 >>> np.alen(a) 7 """ try: return len(a) except TypeError: return len(array(a, ndmin=1)) def prod(a, axis=None, dtype=None, out=None, keepdims=False): """ Return the product of array elements over a given axis. Parameters ---------- a : array_like Input data. axis : None or int or tuple of ints, optional Axis or axes along which a product is performed. The default (`axis` = `None`) is perform a product over all the dimensions of the input array. `axis` may be negative, in which case it counts from the last to the first axis. .. versionadded:: 1.7.0 If this is a tuple of ints, a product is performed on multiple axes, instead of a single axis or all the axes as before. dtype : data-type, optional The data-type of the returned array, as well as of the accumulator in which the elements are multiplied. By default, if `a` is of integer type, `dtype` is the default platform integer. (Note: if the type of `a` is unsigned, then so is `dtype`.) Otherwise, the dtype is the same as that of `a`. out : ndarray, optional Alternative output array in which to place the result. It must have the same shape as the expected output, but the type of the output values will be cast if necessary. 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 ------- product_along_axis : ndarray, see `dtype` parameter above. An array shaped as `a` but with the specified axis removed. Returns a reference to `out` if specified. See Also -------- ndarray.prod : equivalent method numpy.doc.ufuncs : Section "Output arguments" Notes ----- Arithmetic is modular when using integer types, and no error is raised on overflow. That means that, on a 32-bit platform: >>> x = np.array([536870910, 536870910, 536870910, 536870910]) >>> np.prod(x) #random 16 Examples -------- By default, calculate the product of all elements: >>> np.prod([1.,2.]) 2.0 Even when the input array is two-dimensional: >>> np.prod([[1.,2.],[3.,4.]]) 24.0 But we can also specify the axis over which to multiply: >>> np.prod([[1.,2.],[3.,4.]], axis=1) array([ 2., 12.]) If the type of `x` is unsigned, then the output type is the unsigned platform integer: >>> x = np.array([1, 2, 3], dtype=np.uint8) >>> np.prod(x).dtype == np.uint True If `x` is of a signed integer type, then the output type is the default platform integer: >>> x = np.array([1, 2, 3], dtype=np.int8) >>> np.prod(x).dtype == np.int True """ if type(a) is not mu.ndarray: try: prod = a.prod except AttributeError: return _methods._prod(a, axis=axis, dtype=dtype, out=out, keepdims=keepdims) return prod(axis=axis, dtype=dtype, out=out) else: return _methods._prod(a, axis=axis, dtype=dtype, out=out, keepdims=keepdims) def cumprod(a, axis=None, dtype=None, out=None): """ Return the cumulative product of elements along a given axis. Parameters ---------- a : array_like Input array. axis : int, optional Axis along which the cumulative product is computed. By default the input is flattened. dtype : dtype, optional Type of the returned array, as well as of the accumulator in which the elements are multiplied. If *dtype* is not specified, it defaults to the dtype of `a`, unless `a` has an integer dtype with a precision less than that of the default platform integer. In that case, the default platform integer is used instead. 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 resulting values will be cast if necessary. Returns ------- cumprod : ndarray A new array holding the result is returned unless `out` is specified, in which case a reference to out is returned. See Also -------- numpy.doc.ufuncs : Section "Output arguments" Notes ----- Arithmetic is modular when using integer types, and no error is raised on overflow. Examples -------- >>> a = np.array([1,2,3]) >>> np.cumprod(a) # intermediate results 1, 1*2 ... # total product 1*2*3 = 6 array([1, 2, 6]) >>> a = np.array([[1, 2, 3], [4, 5, 6]]) >>> np.cumprod(a, dtype=float) # specify type of output array([ 1., 2., 6., 24., 120., 720.]) The cumulative product for each column (i.e., over the rows) of `a`: >>> np.cumprod(a, axis=0) array([[ 1, 2, 3], [ 4, 10, 18]]) The cumulative product for each row (i.e. over the columns) of `a`: >>> np.cumprod(a,axis=1) array([[ 1, 2, 6], [ 4, 20, 120]]) """ try: cumprod = a.cumprod except AttributeError: return _wrapit(a, 'cumprod', axis, dtype, out) return cumprod(axis, dtype, out) def ndim(a): """ Return the number of dimensions of an array. Parameters ---------- a : array_like Input array. If it is not already an ndarray, a conversion is attempted. Returns ------- number_of_dimensions : int The number of dimensions in `a`. Scalars are zero-dimensional. See Also -------- ndarray.ndim : equivalent method shape : dimensions of array ndarray.shape : dimensions of array Examples -------- >>> np.ndim([[1,2,3],[4,5,6]]) 2 >>> np.ndim(np.array([[1,2,3],[4,5,6]])) 2 >>> np.ndim(1) 0 """ try: return a.ndim except AttributeError: return asarray(a).ndim def rank(a): """ Return the number of dimensions of an array. If `a` is not already an array, a conversion is attempted. Scalars are zero dimensional. Parameters ---------- a : array_like Array whose number of dimensions is desired. If `a` is not an array, a conversion is attempted. Returns ------- number_of_dimensions : int The number of dimensions in the array. See Also -------- ndim : equivalent function ndarray.ndim : equivalent property shape : dimensions of array ndarray.shape : dimensions of array Notes ----- In the old Numeric package, `rank` was the term used for the number of dimensions, but in Numpy `ndim` is used instead. Examples -------- >>> np.rank([1,2,3]) 1 >>> np.rank(np.array([[1,2,3],[4,5,6]])) 2 >>> np.rank(1) 0 """ try: return a.ndim except AttributeError: return asarray(a).ndim def size(a, axis=None): """ Return the number of elements along a given axis. Parameters ---------- a : array_like Input data. axis : int, optional Axis along which the elements are counted. By default, give the total number of elements. Returns ------- element_count : int Number of elements along the specified axis. See Also -------- shape : dimensions of array ndarray.shape : dimensions of array ndarray.size : number of elements in array Examples -------- >>> a = np.array([[1,2,3],[4,5,6]]) >>> np.size(a) 6 >>> np.size(a,1) 3 >>> np.size(a,0) 2 """ if axis is None: try: return a.size except AttributeError: return asarray(a).size else: try: return a.shape[axis] except AttributeError: return asarray(a).shape[axis] def around(a, decimals=0, out=None): """ Evenly round to the given number of decimals. Parameters ---------- a : array_like Input data. decimals : int, optional Number of decimal places to round to (default: 0). If decimals is negative, it specifies the number of positions to the left of the decimal point. out : ndarray, optional Alternative output array in which to place the result. It must have the same shape as the expected output, but the type of the output values will be cast if necessary. See `doc.ufuncs` (Section "Output arguments") for details. Returns ------- rounded_array : ndarray An array of the same type as `a`, containing the rounded values. Unless `out` was specified, a new array is created. A reference to the result is returned. The real and imaginary parts of complex numbers are rounded separately. The result of rounding a float is a float. See Also -------- ndarray.round : equivalent method ceil, fix, floor, rint, trunc Notes ----- For values exactly halfway between rounded decimal values, Numpy rounds to the nearest even value. Thus 1.5 and 2.5 round to 2.0, -0.5 and 0.5 round to 0.0, etc. Results may also be surprising due to the inexact representation of decimal fractions in the IEEE floating point standard [1]_ and errors introduced when scaling by powers of ten. References ---------- .. [1] "Lecture Notes on the Status of IEEE 754", William Kahan, http://www.cs.berkeley.edu/~wkahan/ieee754status/IEEE754.PDF .. [2] "How Futile are Mindless Assessments of Roundoff in Floating-Point Computation?", William Kahan, http://www.cs.berkeley.edu/~wkahan/Mindless.pdf Examples -------- >>> np.around([0.37, 1.64]) array([ 0., 2.]) >>> np.around([0.37, 1.64], decimals=1) array([ 0.4, 1.6]) >>> np.around([.5, 1.5, 2.5, 3.5, 4.5]) # rounds to nearest even value array([ 0., 2., 2., 4., 4.]) >>> np.around([1,2,3,11], decimals=1) # ndarray of ints is returned array([ 1, 2, 3, 11]) >>> np.around([1,2,3,11], decimals=-1) array([ 0, 0, 0, 10]) """ try: round = a.round except AttributeError: return _wrapit(a, 'round', decimals, out) return round(decimals, out) def round_(a, decimals=0, out=None): """ Round an array to the given number of decimals. Refer to `around` for full documentation. See Also -------- around : equivalent function """ try: round = a.round except AttributeError: return _wrapit(a, 'round', decimals, out) return round(decimals, out) def mean(a, axis=None, dtype=None, out=None, keepdims=False): """ Compute the arithmetic mean along the specified axis. Returns the average of the array elements. The average is taken over the flattened array by default, otherwise over the specified axis. `float64` intermediate and return values are used for integer inputs. Parameters ---------- a : array_like Array containing numbers whose mean is desired. If `a` is not an array, a conversion is attempted. axis : int, optional Axis along which the means are computed. The default is to compute the mean of the flattened array. dtype : data-type, optional Type to use in computing the mean. For integer inputs, the default is `float64`; for floating point inputs, it is the same as the input dtype. out : ndarray, optional Alternate output array in which to place the result. The default is ``None``; if provided, it must have the same shape as the expected output, but the type will be cast if necessary. See `doc.ufuncs` for details. 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 ------- m : ndarray, see dtype parameter above If `out=None`, returns a new array containing the mean values, otherwise a reference to the output array is returned. See Also -------- average : Weighted average std, var, nanmean, nanstd, nanvar Notes ----- The arithmetic mean is the sum of the elements along the axis divided by the number of elements. Note that for floating-point input, the mean is computed using the same precision the input has. Depending on the input data, this can cause the results to be inaccurate, especially for `float32` (see example below). Specifying a higher-precision accumulator using the `dtype` keyword can alleviate this issue. Examples -------- >>> a = np.array([[1, 2], [3, 4]]) >>> np.mean(a) 2.5 >>> np.mean(a, axis=0) array([ 2., 3.]) >>> np.mean(a, axis=1) array([ 1.5, 3.5]) In single precision, `mean` can be inaccurate: >>> a = np.zeros((2, 512*512), dtype=np.float32) >>> a[0, :] = 1.0 >>> a[1, :] = 0.1 >>> np.mean(a) 0.546875 Computing the mean in float64 is more accurate: >>> np.mean(a, dtype=np.float64) 0.55000000074505806 """ if type(a) is not mu.ndarray: try: mean = a.mean return mean(axis=axis, dtype=dtype, out=out) except AttributeError: pass return _methods._mean(a, axis=axis, dtype=dtype, out=out, keepdims=keepdims) def std(a, axis=None, dtype=None, out=None, ddof=0, keepdims=False): """ Compute the standard deviation along the specified axis. Returns the standard deviation, a measure of the spread of a distribution, of the array elements. The standard deviation is computed for the flattened array by default, otherwise over the specified axis. Parameters ---------- a : array_like Calculate the standard deviation of these values. axis : int, optional Axis along which the standard deviation is computed. The default is to compute the standard deviation of the flattened array. dtype : dtype, optional Type to use in computing the standard deviation. For arrays of integer type the default is float64, for arrays of float types it is the same as the array type. out : ndarray, optional Alternative output array in which to place the result. It must have the same shape as the expected output but the type (of the calculated values) will be cast if necessary. ddof : int, optional Means Delta Degrees of Freedom. The divisor used in calculations is ``N - ddof``, where ``N`` represents the number of elements. By default `ddof` is zero. 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 ------- standard_deviation : ndarray, see dtype parameter above. If `out` is None, return a new array containing the standard deviation, otherwise return a reference to the output array. See Also -------- var, mean, nanmean, nanstd, nanvar numpy.doc.ufuncs : Section "Output arguments" Notes ----- The standard deviation is the square root of the average of the squared deviations from the mean, i.e., ``std = sqrt(mean(abs(x - x.mean())**2))``. The average squared deviation is normally calculated as ``x.sum() / N``, where ``N = len(x)``. If, however, `ddof` is specified, the divisor ``N - ddof`` is used instead. In standard statistical practice, ``ddof=1`` provides an unbiased estimator of the variance of the infinite population. ``ddof=0`` provides a maximum likelihood estimate of the variance for normally distributed variables. The standard deviation computed in this function is the square root of the estimated variance, so even with ``ddof=1``, it will not be an unbiased estimate of the standard deviation per se. Note that, for complex numbers, `std` takes the absolute value before squaring, so that the result is always real and nonnegative. For floating-point input, the *std* is computed using the same precision the input has. Depending on the input data, this can cause the results to be inaccurate, especially for float32 (see example below). Specifying a higher-accuracy accumulator using the `dtype` keyword can alleviate this issue. Examples -------- >>> a = np.array([[1, 2], [3, 4]]) >>> np.std(a) 1.1180339887498949 >>> np.std(a, axis=0) array([ 1., 1.]) >>> np.std(a, axis=1) array([ 0.5, 0.5]) In single precision, std() can be inaccurate: >>> a = np.zeros((2,512*512), dtype=np.float32) >>> a[0,:] = 1.0 >>> a[1,:] = 0.1 >>> np.std(a) 0.45172946707416706 Computing the standard deviation in float64 is more accurate: >>> np.std(a, dtype=np.float64) 0.44999999925552653 """ if type(a) is not mu.ndarray: try: std = a.std return std(axis=axis, dtype=dtype, out=out, ddof=ddof) except AttributeError: pass return _methods._std(a, axis=axis, dtype=dtype, out=out, ddof=ddof, keepdims=keepdims) def var(a, axis=None, dtype=None, out=None, ddof=0, keepdims=False): """ Compute the variance along the specified axis. Returns the variance of the array elements, a measure of the spread of a distribution. The variance is computed for the flattened array by default, otherwise over the specified axis. Parameters ---------- a : array_like Array containing numbers whose variance is desired. If `a` is not an array, a conversion is attempted. axis : int, optional Axis along which the variance is computed. The default is to compute the variance of the flattened array. dtype : data-type, optional Type to use in computing the variance. For arrays of integer type the default is `float32`; for arrays of float types it is the same as the array type. out : ndarray, optional Alternate output array in which to place the result. It must have the same shape as the expected output, but the type is cast if necessary. ddof : int, optional "Delta Degrees of Freedom": the divisor used in the calculation is ``N - ddof``, where ``N`` represents the number of elements. By default `ddof` is zero. 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 ------- variance : ndarray, see dtype parameter above If ``out=None``, returns a new array containing the variance; otherwise, a reference to the output array is returned. See Also -------- std , mean, nanmean, nanstd, nanvar numpy.doc.ufuncs : Section "Output arguments" Notes ----- The variance is the average of the squared deviations from the mean, i.e., ``var = mean(abs(x - x.mean())**2)``. The mean is normally calculated as ``x.sum() / N``, where ``N = len(x)``. If, however, `ddof` is specified, the divisor ``N - ddof`` is used instead. In standard statistical practice, ``ddof=1`` provides an unbiased estimator of the variance of a hypothetical infinite population. ``ddof=0`` provides a maximum likelihood estimate of the variance for normally distributed variables. Note that for complex numbers, the absolute value is taken before squaring, so that the result is always real and nonnegative. For floating-point input, the variance is computed using the same precision the input has. Depending on the input data, this can cause the results to be inaccurate, especially for `float32` (see example below). Specifying a higher-accuracy accumulator using the ``dtype`` keyword can alleviate this issue. Examples -------- >>> a = np.array([[1,2],[3,4]]) >>> np.var(a) 1.25 >>> np.var(a, axis=0) array([ 1., 1.]) >>> np.var(a, axis=1) array([ 0.25, 0.25]) In single precision, var() can be inaccurate: >>> a = np.zeros((2,512*512), dtype=np.float32) >>> a[0,:] = 1.0 >>> a[1,:] = 0.1 >>> np.var(a) 0.20405951142311096 Computing the variance in float64 is more accurate: >>> np.var(a, dtype=np.float64) 0.20249999932997387 >>> ((1-0.55)**2 + (0.1-0.55)**2)/2 0.20250000000000001 """ if type(a) is not mu.ndarray: try: var = a.var return var(axis=axis, dtype=dtype, out=out, ddof=ddof) except AttributeError: pass return _methods._var(a, axis=axis, dtype=dtype, out=out, ddof=ddof, keepdims=keepdims) numpy-1.8.2/numpy/core/_internal.py0000664000175100017510000004072612370216242020461 0ustar vagrantvagrant00000000000000""" A place for code to be called from core C-code. Some things are more easily handled Python. """ from __future__ import division, absolute_import, print_function import re import sys import warnings from numpy.compat import asbytes, bytes if (sys.byteorder == 'little'): _nbo = asbytes('<') else: _nbo = asbytes('>') def _makenames_list(adict, align): from .multiarray import dtype allfields = [] fnames = list(adict.keys()) for fname in fnames: obj = adict[fname] n = len(obj) if not isinstance(obj, tuple) or n not in [2, 3]: raise ValueError("entry not a 2- or 3- tuple") if (n > 2) and (obj[2] == fname): continue num = int(obj[1]) if (num < 0): raise ValueError("invalid offset.") format = dtype(obj[0], align=align) if (format.itemsize == 0): raise ValueError("all itemsizes must be fixed.") if (n > 2): title = obj[2] else: title = None allfields.append((fname, format, num, title)) # sort by offsets allfields.sort(key=lambda x: x[2]) names = [x[0] for x in allfields] formats = [x[1] for x in allfields] offsets = [x[2] for x in allfields] titles = [x[3] for x in allfields] return names, formats, offsets, titles # Called in PyArray_DescrConverter function when # a dictionary without "names" and "formats" # fields is used as a data-type descriptor. def _usefields(adict, align): from .multiarray import dtype try: names = adict[-1] except KeyError: names = None if names is None: names, formats, offsets, titles = _makenames_list(adict, align) else: formats = [] offsets = [] titles = [] for name in names: res = adict[name] formats.append(res[0]) offsets.append(res[1]) if (len(res) > 2): titles.append(res[2]) else: titles.append(None) return dtype({"names" : names, "formats" : formats, "offsets" : offsets, "titles" : titles}, align) # construct an array_protocol descriptor list # from the fields attribute of a descriptor # This calls itself recursively but should eventually hit # a descriptor that has no fields and then return # a simple typestring def _array_descr(descriptor): fields = descriptor.fields if fields is None: subdtype = descriptor.subdtype if subdtype is None: if descriptor.metadata is None: return descriptor.str else: new = descriptor.metadata.copy() if new: return (descriptor.str, new) else: return descriptor.str else: return (_array_descr(subdtype[0]), subdtype[1]) names = descriptor.names ordered_fields = [fields[x] + (x,) for x in names] result = [] offset = 0 for field in ordered_fields: if field[1] > offset: num = field[1] - offset result.append(('', '|V%d' % num)) offset += num if len(field) > 3: name = (field[2], field[3]) else: name = field[2] if field[0].subdtype: tup = (name, _array_descr(field[0].subdtype[0]), field[0].subdtype[1]) else: tup = (name, _array_descr(field[0])) offset += field[0].itemsize result.append(tup) return result # Build a new array from the information in a pickle. # Note that the name numpy.core._internal._reconstruct is embedded in # pickles of ndarrays made with NumPy before release 1.0 # so don't remove the name here, or you'll # break backward compatibilty. def _reconstruct(subtype, shape, dtype): from .multiarray import ndarray return ndarray.__new__(subtype, shape, dtype) # format_re was originally from numarray by J. Todd Miller format_re = re.compile(asbytes( r'(?P[<>|=]?)' r'(?P *[(]?[ ,0-9L]*[)]? *)' r'(?P[<>|=]?)' r'(?P[A-Za-z0-9.]*(?:\[[a-zA-Z0-9,.]+\])?)')) sep_re = re.compile(asbytes(r'\s*,\s*')) space_re = re.compile(asbytes(r'\s+$')) # astr is a string (perhaps comma separated) _convorder = {asbytes('='): _nbo} def _commastring(astr): startindex = 0 result = [] while startindex < len(astr): mo = format_re.match(astr, pos=startindex) try: (order1, repeats, order2, dtype) = mo.groups() except (TypeError, AttributeError): raise ValueError('format number %d of "%s" is not recognized' % (len(result)+1, astr)) startindex = mo.end() # Separator or ending padding if startindex < len(astr): if space_re.match(astr, pos=startindex): startindex = len(astr) else: mo = sep_re.match(astr, pos=startindex) if not mo: raise ValueError( 'format number %d of "%s" is not recognized' % (len(result)+1, astr)) startindex = mo.end() if order2 == asbytes(''): order = order1 elif order1 == asbytes(''): order = order2 else: order1 = _convorder.get(order1, order1) order2 = _convorder.get(order2, order2) if (order1 != order2): raise ValueError('inconsistent byte-order specification %s and %s' % (order1, order2)) order = order1 if order in [asbytes('|'), asbytes('='), _nbo]: order = asbytes('') dtype = order + dtype if (repeats == asbytes('')): newitem = dtype else: newitem = (dtype, eval(repeats)) result.append(newitem) return result def _getintp_ctype(): from .multiarray import dtype val = _getintp_ctype.cache if val is not None: return val char = dtype('p').char import ctypes if (char == 'i'): val = ctypes.c_int elif char == 'l': val = ctypes.c_long elif char == 'q': val = ctypes.c_longlong else: val = ctypes.c_long _getintp_ctype.cache = val return val _getintp_ctype.cache = None # Used for .ctypes attribute of ndarray class _missing_ctypes(object): def cast(self, num, obj): return num def c_void_p(self, num): return num class _ctypes(object): def __init__(self, array, ptr=None): try: import ctypes self._ctypes = ctypes except ImportError: self._ctypes = _missing_ctypes() self._arr = array self._data = ptr if self._arr.ndim == 0: self._zerod = True else: self._zerod = False def data_as(self, obj): return self._ctypes.cast(self._data, obj) def shape_as(self, obj): if self._zerod: return None return (obj*self._arr.ndim)(*self._arr.shape) def strides_as(self, obj): if self._zerod: return None return (obj*self._arr.ndim)(*self._arr.strides) def get_data(self): return self._data def get_shape(self): if self._zerod: return None return (_getintp_ctype()*self._arr.ndim)(*self._arr.shape) def get_strides(self): if self._zerod: return None return (_getintp_ctype()*self._arr.ndim)(*self._arr.strides) def get_as_parameter(self): return self._ctypes.c_void_p(self._data) data = property(get_data, None, doc="c-types data") shape = property(get_shape, None, doc="c-types shape") strides = property(get_strides, None, doc="c-types strides") _as_parameter_ = property(get_as_parameter, None, doc="_as parameter_") # Given a datatype and an order object # return a new names tuple # with the order indicated def _newnames(datatype, order): oldnames = datatype.names nameslist = list(oldnames) if isinstance(order, str): order = [order] if isinstance(order, (list, tuple)): for name in order: try: nameslist.remove(name) except ValueError: raise ValueError("unknown field name: %s" % (name,)) return tuple(list(order) + nameslist) raise ValueError("unsupported order value: %s" % (order,)) # Given an array with fields and a sequence of field names # construct a new array with just those fields copied over def _index_fields(ary, fields): from .multiarray import empty, dtype, array dt = ary.dtype names = [name for name in fields if name in dt.names] formats = [dt.fields[name][0] for name in fields if name in dt.names] offsets = [dt.fields[name][1] for name in fields if name in dt.names] view_dtype = {'names':names, 'formats':formats, 'offsets':offsets, 'itemsize':dt.itemsize} view = ary.view(dtype=view_dtype) # Return a copy for now until behavior is fully deprecated # in favor of returning view copy_dtype = {'names':view_dtype['names'], 'formats':view_dtype['formats']} return array(view, dtype=copy_dtype, copy=True) # Given a string containing a PEP 3118 format specifier, # construct a Numpy dtype _pep3118_native_map = { '?': '?', 'b': 'b', 'B': 'B', 'h': 'h', 'H': 'H', 'i': 'i', 'I': 'I', 'l': 'l', 'L': 'L', 'q': 'q', 'Q': 'Q', 'e': 'e', 'f': 'f', 'd': 'd', 'g': 'g', 'Zf': 'F', 'Zd': 'D', 'Zg': 'G', 's': 'S', 'w': 'U', 'O': 'O', 'x': 'V', # padding } _pep3118_native_typechars = ''.join(_pep3118_native_map.keys()) _pep3118_standard_map = { '?': '?', 'b': 'b', 'B': 'B', 'h': 'i2', 'H': 'u2', 'i': 'i4', 'I': 'u4', 'l': 'i4', 'L': 'u4', 'q': 'i8', 'Q': 'u8', 'e': 'f2', 'f': 'f', 'd': 'd', 'Zf': 'F', 'Zd': 'D', 's': 'S', 'w': 'U', 'O': 'O', 'x': 'V', # padding } _pep3118_standard_typechars = ''.join(_pep3118_standard_map.keys()) def _dtype_from_pep3118(spec, byteorder='@', is_subdtype=False): from numpy.core.multiarray import dtype fields = {} offset = 0 explicit_name = False this_explicit_name = False common_alignment = 1 is_padding = False last_offset = 0 dummy_name_index = [0] def next_dummy_name(): dummy_name_index[0] += 1 def get_dummy_name(): while True: name = 'f%d' % dummy_name_index[0] if name not in fields: return name next_dummy_name() # Parse spec while spec: value = None # End of structure, bail out to upper level if spec[0] == '}': spec = spec[1:] break # Sub-arrays (1) shape = None if spec[0] == '(': j = spec.index(')') shape = tuple(map(int, spec[1:j].split(','))) spec = spec[j+1:] # Byte order if spec[0] in ('@', '=', '<', '>', '^', '!'): byteorder = spec[0] if byteorder == '!': byteorder = '>' spec = spec[1:] # Byte order characters also control native vs. standard type sizes if byteorder in ('@', '^'): type_map = _pep3118_native_map type_map_chars = _pep3118_native_typechars else: type_map = _pep3118_standard_map type_map_chars = _pep3118_standard_typechars # Item sizes itemsize = 1 if spec[0].isdigit(): j = 1 for j in range(1, len(spec)): if not spec[j].isdigit(): break itemsize = int(spec[:j]) spec = spec[j:] # Data types is_padding = False if spec[:2] == 'T{': value, spec, align, next_byteorder = _dtype_from_pep3118( spec[2:], byteorder=byteorder, is_subdtype=True) elif spec[0] in type_map_chars: next_byteorder = byteorder if spec[0] == 'Z': j = 2 else: j = 1 typechar = spec[:j] spec = spec[j:] is_padding = (typechar == 'x') dtypechar = type_map[typechar] if dtypechar in 'USV': dtypechar += '%d' % itemsize itemsize = 1 numpy_byteorder = {'@': '=', '^': '='}.get(byteorder, byteorder) value = dtype(numpy_byteorder + dtypechar) align = value.alignment else: raise ValueError("Unknown PEP 3118 data type specifier %r" % spec) # # Native alignment may require padding # # Here we assume that the presence of a '@' character implicitly implies # that the start of the array is *already* aligned. # extra_offset = 0 if byteorder == '@': start_padding = (-offset) % align intra_padding = (-value.itemsize) % align offset += start_padding if intra_padding != 0: if itemsize > 1 or (shape is not None and _prod(shape) > 1): # Inject internal padding to the end of the sub-item value = _add_trailing_padding(value, intra_padding) else: # We can postpone the injection of internal padding, # as the item appears at most once extra_offset += intra_padding # Update common alignment common_alignment = (align*common_alignment / _gcd(align, common_alignment)) # Convert itemsize to sub-array if itemsize != 1: value = dtype((value, (itemsize,))) # Sub-arrays (2) if shape is not None: value = dtype((value, shape)) # Field name this_explicit_name = False if spec and spec.startswith(':'): i = spec[1:].index(':') + 1 name = spec[1:i] spec = spec[i+1:] explicit_name = True this_explicit_name = True else: name = get_dummy_name() if not is_padding or this_explicit_name: if name in fields: raise RuntimeError("Duplicate field name '%s' in PEP3118 format" % name) fields[name] = (value, offset) last_offset = offset if not this_explicit_name: next_dummy_name() byteorder = next_byteorder offset += value.itemsize offset += extra_offset # Check if this was a simple 1-item type if len(fields) == 1 and not explicit_name and fields['f0'][1] == 0 \ and not is_subdtype: ret = fields['f0'][0] else: ret = dtype(fields) # Trailing padding must be explicitly added padding = offset - ret.itemsize if byteorder == '@': padding += (-offset) % common_alignment if is_padding and not this_explicit_name: ret = _add_trailing_padding(ret, padding) # Finished if is_subdtype: return ret, spec, common_alignment, byteorder else: return ret def _add_trailing_padding(value, padding): """Inject the specified number of padding bytes at the end of a dtype""" from numpy.core.multiarray import dtype if value.fields is None: vfields = {'f0': (value, 0)} else: vfields = dict(value.fields) if value.names and value.names[-1] == '' and \ value[''].char == 'V': # A trailing padding field is already present vfields[''] = ('V%d' % (vfields[''][0].itemsize + padding), vfields[''][1]) value = dtype(vfields) else: # Get a free name for the padding field j = 0 while True: name = 'pad%d' % j if name not in vfields: vfields[name] = ('V%d' % padding, value.itemsize) break j += 1 value = dtype(vfields) if '' not in vfields: # Strip out the name of the padding field names = list(value.names) names[-1] = '' value.names = tuple(names) return value def _prod(a): p = 1 for x in a: p *= x return p def _gcd(a, b): """Calculate the greatest common divisor of a and b""" while b: a, b = b, a%b return a numpy-1.8.2/numpy/core/function_base.py0000664000175100017510000001303012370216243021312 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function __all__ = ['logspace', 'linspace'] from . import numeric as _nx from .numeric import array def linspace(start, stop, num=50, endpoint=True, retstep=False): """ Return evenly spaced numbers over a specified interval. Returns `num` evenly spaced samples, calculated over the interval [`start`, `stop` ]. The endpoint of the interval can optionally be excluded. Parameters ---------- start : scalar The starting value of the sequence. stop : scalar The end value of the sequence, unless `endpoint` is set to False. In that case, the sequence consists of all but the last of ``num + 1`` evenly spaced samples, so that `stop` is excluded. Note that the step size changes when `endpoint` is False. num : int, optional Number of samples to generate. Default is 50. endpoint : bool, optional If True, `stop` is the last sample. Otherwise, it is not included. Default is True. retstep : bool, optional If True, return (`samples`, `step`), where `step` is the spacing between samples. Returns ------- samples : ndarray There are `num` equally spaced samples in the closed interval ``[start, stop]`` or the half-open interval ``[start, stop)`` (depending on whether `endpoint` is True or False). step : float (only if `retstep` is True) Size of spacing between samples. See Also -------- arange : Similar to `linspace`, but uses a step size (instead of the number of samples). logspace : Samples uniformly distributed in log space. Examples -------- >>> np.linspace(2.0, 3.0, num=5) array([ 2. , 2.25, 2.5 , 2.75, 3. ]) >>> np.linspace(2.0, 3.0, num=5, endpoint=False) array([ 2. , 2.2, 2.4, 2.6, 2.8]) >>> np.linspace(2.0, 3.0, num=5, retstep=True) (array([ 2. , 2.25, 2.5 , 2.75, 3. ]), 0.25) Graphical illustration: >>> import matplotlib.pyplot as plt >>> N = 8 >>> y = np.zeros(N) >>> x1 = np.linspace(0, 10, N, endpoint=True) >>> x2 = np.linspace(0, 10, N, endpoint=False) >>> plt.plot(x1, y, 'o') [] >>> plt.plot(x2, y + 0.5, 'o') [] >>> plt.ylim([-0.5, 1]) (-0.5, 1) >>> plt.show() """ num = int(num) # Convert float/complex array scalars to float, gh-3504 start = start * 1. stop = stop * 1. if num <= 0: return array([], float) if endpoint: if num == 1: return array([float(start)]) step = (stop-start)/float((num-1)) y = _nx.arange(0, num) * step + start y[-1] = stop else: step = (stop-start)/float(num) y = _nx.arange(0, num) * step + start if retstep: return y, step else: return y def logspace(start,stop,num=50,endpoint=True,base=10.0): """ Return numbers spaced evenly on a log scale. In linear space, the sequence starts at ``base ** start`` (`base` to the power of `start`) and ends with ``base ** stop`` (see `endpoint` below). Parameters ---------- start : float ``base ** start`` is the starting value of the sequence. stop : float ``base ** stop`` is the final value of the sequence, unless `endpoint` is False. In that case, ``num + 1`` values are spaced over the interval in log-space, of which all but the last (a sequence of length ``num``) are returned. num : integer, optional Number of samples to generate. Default is 50. endpoint : boolean, optional If true, `stop` is the last sample. Otherwise, it is not included. Default is True. base : float, optional The base of the log space. The step size between the elements in ``ln(samples) / ln(base)`` (or ``log_base(samples)``) is uniform. Default is 10.0. Returns ------- samples : ndarray `num` samples, equally spaced on a log scale. See Also -------- arange : Similar to linspace, with the step size specified instead of the number of samples. Note that, when used with a float endpoint, the endpoint may or may not be included. linspace : Similar to logspace, but with the samples uniformly distributed in linear space, instead of log space. Notes ----- Logspace is equivalent to the code >>> y = np.linspace(start, stop, num=num, endpoint=endpoint) ... # doctest: +SKIP >>> power(base, y) ... # doctest: +SKIP Examples -------- >>> np.logspace(2.0, 3.0, num=4) array([ 100. , 215.443469 , 464.15888336, 1000. ]) >>> np.logspace(2.0, 3.0, num=4, endpoint=False) array([ 100. , 177.827941 , 316.22776602, 562.34132519]) >>> np.logspace(2.0, 3.0, num=4, base=2.0) array([ 4. , 5.0396842 , 6.34960421, 8. ]) Graphical illustration: >>> import matplotlib.pyplot as plt >>> N = 10 >>> x1 = np.logspace(0.1, 1, N, endpoint=True) >>> x2 = np.logspace(0.1, 1, N, endpoint=False) >>> y = np.zeros(N) >>> plt.plot(x1, y, 'o') [] >>> plt.plot(x2, y + 0.5, 'o') [] >>> plt.ylim([-0.5, 1]) (-0.5, 1) >>> plt.show() """ y = linspace(start, stop, num=num, endpoint=endpoint) return _nx.power(base, y) numpy-1.8.2/numpy/core/getlimits.py0000664000175100017510000002237612370216242020510 0ustar vagrantvagrant00000000000000"""Machine limits for Float32 and Float64 and (long double) if available... """ from __future__ import division, absolute_import, print_function __all__ = ['finfo', 'iinfo'] from .machar import MachAr from . import numeric from . import numerictypes as ntypes from .numeric import array def _frz(a): """fix rank-0 --> rank-1""" if a.ndim == 0: a.shape = (1,) return a _convert_to_float = { ntypes.csingle: ntypes.single, ntypes.complex_: ntypes.float_, ntypes.clongfloat: ntypes.longfloat } class finfo(object): """ finfo(dtype) Machine limits for floating point types. Attributes ---------- eps : float The smallest representable positive number such that ``1.0 + eps != 1.0``. Type of `eps` is an appropriate floating point type. epsneg : floating point number of the appropriate type The smallest representable positive number such that ``1.0 - epsneg != 1.0``. iexp : int The number of bits in the exponent portion of the floating point representation. machar : MachAr The object which calculated these parameters and holds more detailed information. machep : int The exponent that yields `eps`. max : floating point number of the appropriate type The largest representable number. maxexp : int The smallest positive power of the base (2) that causes overflow. min : floating point number of the appropriate type The smallest representable number, typically ``-max``. minexp : int The most negative power of the base (2) consistent with there being no leading 0's in the mantissa. negep : int The exponent that yields `epsneg`. nexp : int The number of bits in the exponent including its sign and bias. nmant : int The number of bits in the mantissa. precision : int The approximate number of decimal digits to which this kind of float is precise. resolution : floating point number of the appropriate type The approximate decimal resolution of this type, i.e., ``10**-precision``. tiny : float The smallest positive usable number. Type of `tiny` is an appropriate floating point type. Parameters ---------- dtype : float, dtype, or instance Kind of floating point data-type about which to get information. See Also -------- MachAr : The implementation of the tests that produce this information. iinfo : The equivalent for integer data types. Notes ----- For developers of NumPy: do not instantiate this at the module level. The initial calculation of these parameters is expensive and negatively impacts import times. These objects are cached, so calling ``finfo()`` repeatedly inside your functions is not a problem. """ _finfo_cache = {} def __new__(cls, dtype): try: dtype = numeric.dtype(dtype) except TypeError: # In case a float instance was given dtype = numeric.dtype(type(dtype)) obj = cls._finfo_cache.get(dtype, None) if obj is not None: return obj dtypes = [dtype] newdtype = numeric.obj2sctype(dtype) if newdtype is not dtype: dtypes.append(newdtype) dtype = newdtype if not issubclass(dtype, numeric.inexact): raise ValueError("data type %r not inexact" % (dtype)) obj = cls._finfo_cache.get(dtype, None) if obj is not None: return obj if not issubclass(dtype, numeric.floating): newdtype = _convert_to_float[dtype] if newdtype is not dtype: dtypes.append(newdtype) dtype = newdtype obj = cls._finfo_cache.get(dtype, None) if obj is not None: return obj obj = object.__new__(cls)._init(dtype) for dt in dtypes: cls._finfo_cache[dt] = obj return obj def _init(self, dtype): self.dtype = numeric.dtype(dtype) if dtype is ntypes.double: itype = ntypes.int64 fmt = '%24.16e' precname = 'double' elif dtype is ntypes.single: itype = ntypes.int32 fmt = '%15.7e' precname = 'single' elif dtype is ntypes.longdouble: itype = ntypes.longlong fmt = '%s' precname = 'long double' elif dtype is ntypes.half: itype = ntypes.int16 fmt = '%12.5e' precname = 'half' else: raise ValueError(repr(dtype)) machar = MachAr(lambda v:array([v], dtype), lambda v:_frz(v.astype(itype))[0], lambda v:array(_frz(v)[0], dtype), lambda v: fmt % array(_frz(v)[0], dtype), 'numpy %s precision floating point number' % precname) for word in ['precision', 'iexp', 'maxexp', 'minexp', 'negep', 'machep']: setattr(self, word, getattr(machar, word)) for word in ['tiny', 'resolution', 'epsneg']: setattr(self, word, getattr(machar, word).flat[0]) self.max = machar.huge.flat[0] self.min = -self.max self.eps = machar.eps.flat[0] self.nexp = machar.iexp self.nmant = machar.it self.machar = machar self._str_tiny = machar._str_xmin.strip() self._str_max = machar._str_xmax.strip() self._str_epsneg = machar._str_epsneg.strip() self._str_eps = machar._str_eps.strip() self._str_resolution = machar._str_resolution.strip() return self def __str__(self): return '''\ Machine parameters for %(dtype)s --------------------------------------------------------------------- precision=%(precision)3s resolution= %(_str_resolution)s machep=%(machep)6s eps= %(_str_eps)s negep =%(negep)6s epsneg= %(_str_epsneg)s minexp=%(minexp)6s tiny= %(_str_tiny)s maxexp=%(maxexp)6s max= %(_str_max)s nexp =%(nexp)6s min= -max --------------------------------------------------------------------- ''' % self.__dict__ def __repr__(self): c = self.__class__.__name__ d = self.__dict__.copy() d['klass'] = c return ("%(klass)s(resolution=%(resolution)s, min=-%(_str_max)s," \ + " max=%(_str_max)s, dtype=%(dtype)s)") \ % d class iinfo(object): """ iinfo(type) Machine limits for integer types. Attributes ---------- min : int The smallest integer expressible by the type. max : int The largest integer expressible by the type. Parameters ---------- type : integer type, dtype, or instance The kind of integer data type to get information about. See Also -------- finfo : The equivalent for floating point data types. Examples -------- With types: >>> ii16 = np.iinfo(np.int16) >>> ii16.min -32768 >>> ii16.max 32767 >>> ii32 = np.iinfo(np.int32) >>> ii32.min -2147483648 >>> ii32.max 2147483647 With instances: >>> ii32 = np.iinfo(np.int32(10)) >>> ii32.min -2147483648 >>> ii32.max 2147483647 """ _min_vals = {} _max_vals = {} def __init__(self, int_type): try: self.dtype = numeric.dtype(int_type) except TypeError: self.dtype = numeric.dtype(type(int_type)) self.kind = self.dtype.kind self.bits = self.dtype.itemsize * 8 self.key = "%s%d" % (self.kind, self.bits) if not self.kind in 'iu': raise ValueError("Invalid integer data type.") def min(self): """Minimum value of given dtype.""" if self.kind == 'u': return 0 else: try: val = iinfo._min_vals[self.key] except KeyError: val = int(-(1 << (self.bits-1))) iinfo._min_vals[self.key] = val return val min = property(min) def max(self): """Maximum value of given dtype.""" try: val = iinfo._max_vals[self.key] except KeyError: if self.kind == 'u': val = int((1 << self.bits) - 1) else: val = int((1 << (self.bits-1)) - 1) iinfo._max_vals[self.key] = val return val max = property(max) def __str__(self): """String representation.""" return '''\ Machine parameters for %(dtype)s --------------------------------------------------------------------- min = %(min)s max = %(max)s --------------------------------------------------------------------- ''' % {'dtype': self.dtype, 'min': self.min, 'max': self.max} def __repr__(self): return "%s(min=%s, max=%s, dtype=%s)" % (self.__class__.__name__, self.min, self.max, self.dtype) if __name__ == '__main__': f = finfo(ntypes.single) print('single epsilon:', f.eps) print('single tiny:', f.tiny) f = finfo(ntypes.float) print('float epsilon:', f.eps) print('float tiny:', f.tiny) f = finfo(ntypes.longfloat) print('longfloat epsilon:', f.eps) print('longfloat tiny:', f.tiny) numpy-1.8.2/numpy/core/arrayprint.py0000664000175100017510000006241512370216242020700 0ustar vagrantvagrant00000000000000"""Array printing function $Id: arrayprint.py,v 1.9 2005/09/13 13:58:44 teoliphant Exp $ """ from __future__ import division, absolute_import, print_function __all__ = ["array2string", "set_printoptions", "get_printoptions"] __docformat__ = 'restructuredtext' # # Written by Konrad Hinsen # last revision: 1996-3-13 # modified by Jim Hugunin 1997-3-3 for repr's and str's (and other details) # and by Perry Greenfield 2000-4-1 for numarray # and by Travis Oliphant 2005-8-22 for numpy import sys from functools import reduce from . import numerictypes as _nt from .umath import maximum, minimum, absolute, not_equal, isnan, isinf from .multiarray import format_longfloat, datetime_as_string, datetime_data from .fromnumeric import ravel if sys.version_info[0] >= 3: _MAXINT = sys.maxsize _MININT = -sys.maxsize - 1 else: _MAXINT = sys.maxint _MININT = -sys.maxint - 1 def product(x, y): return x*y _summaryEdgeItems = 3 # repr N leading and trailing items of each dimension _summaryThreshold = 1000 # total items > triggers array summarization _float_output_precision = 8 _float_output_suppress_small = False _line_width = 75 _nan_str = 'nan' _inf_str = 'inf' _formatter = None # formatting function for array elements def set_printoptions(precision=None, threshold=None, edgeitems=None, linewidth=None, suppress=None, nanstr=None, infstr=None, formatter=None): """ Set printing options. These options determine the way floating point numbers, arrays and other NumPy objects are displayed. Parameters ---------- precision : int, optional Number of digits of precision for floating point output (default 8). threshold : int, optional Total number of array elements which trigger summarization rather than full repr (default 1000). edgeitems : int, optional Number of array items in summary at beginning and end of each dimension (default 3). linewidth : int, optional The number of characters per line for the purpose of inserting line breaks (default 75). suppress : bool, optional Whether or not suppress printing of small floating point values using scientific notation (default False). nanstr : str, optional String representation of floating point not-a-number (default nan). infstr : str, optional String representation of floating point infinity (default inf). formatter : dict of callables, optional If not None, the keys should indicate the type(s) that the respective formatting function applies to. Callables should return a string. Types that are not specified (by their corresponding keys) are handled by the default formatters. Individual types for which a formatter can be set are:: - 'bool' - 'int' - 'timedelta' : a `numpy.timedelta64` - 'datetime' : a `numpy.datetime64` - 'float' - 'longfloat' : 128-bit floats - 'complexfloat' - 'longcomplexfloat' : composed of two 128-bit floats - 'numpy_str' : types `numpy.string_` and `numpy.unicode_` - 'str' : all other strings Other keys that can be used to set a group of types at once are:: - 'all' : sets all types - 'int_kind' : sets 'int' - 'float_kind' : sets 'float' and 'longfloat' - 'complex_kind' : sets 'complexfloat' and 'longcomplexfloat' - 'str_kind' : sets 'str' and 'numpystr' See Also -------- get_printoptions, set_string_function, array2string Notes ----- `formatter` is always reset with a call to `set_printoptions`. Examples -------- Floating point precision can be set: >>> np.set_printoptions(precision=4) >>> print np.array([1.123456789]) [ 1.1235] Long arrays can be summarised: >>> np.set_printoptions(threshold=5) >>> print np.arange(10) [0 1 2 ..., 7 8 9] Small results can be suppressed: >>> eps = np.finfo(float).eps >>> x = np.arange(4.) >>> x**2 - (x + eps)**2 array([ -4.9304e-32, -4.4409e-16, 0.0000e+00, 0.0000e+00]) >>> np.set_printoptions(suppress=True) >>> x**2 - (x + eps)**2 array([-0., -0., 0., 0.]) A custom formatter can be used to display array elements as desired: >>> np.set_printoptions(formatter={'all':lambda x: 'int: '+str(-x)}) >>> x = np.arange(3) >>> x array([int: 0, int: -1, int: -2]) >>> np.set_printoptions() # formatter gets reset >>> x array([0, 1, 2]) To put back the default options, you can use: >>> np.set_printoptions(edgeitems=3,infstr='inf', ... linewidth=75, nanstr='nan', precision=8, ... suppress=False, threshold=1000, formatter=None) """ global _summaryThreshold, _summaryEdgeItems, _float_output_precision, \ _line_width, _float_output_suppress_small, _nan_str, _inf_str, \ _formatter if linewidth is not None: _line_width = linewidth if threshold is not None: _summaryThreshold = threshold if edgeitems is not None: _summaryEdgeItems = edgeitems if precision is not None: _float_output_precision = precision if suppress is not None: _float_output_suppress_small = not not suppress if nanstr is not None: _nan_str = nanstr if infstr is not None: _inf_str = infstr _formatter = formatter def get_printoptions(): """ Return the current print options. Returns ------- print_opts : dict Dictionary of current print options with keys - precision : int - threshold : int - edgeitems : int - linewidth : int - suppress : bool - nanstr : str - infstr : str - formatter : dict of callables For a full description of these options, see `set_printoptions`. See Also -------- set_printoptions, set_string_function """ d = dict(precision=_float_output_precision, threshold=_summaryThreshold, edgeitems=_summaryEdgeItems, linewidth=_line_width, suppress=_float_output_suppress_small, nanstr=_nan_str, infstr=_inf_str, formatter=_formatter) return d def _leading_trailing(a): from . import numeric as _nc if a.ndim == 1: if len(a) > 2*_summaryEdgeItems: b = _nc.concatenate((a[:_summaryEdgeItems], a[-_summaryEdgeItems:])) else: b = a else: if len(a) > 2*_summaryEdgeItems: l = [_leading_trailing(a[i]) for i in range( min(len(a), _summaryEdgeItems))] l.extend([_leading_trailing(a[-i]) for i in range( min(len(a), _summaryEdgeItems), 0, -1)]) else: l = [_leading_trailing(a[i]) for i in range(0, len(a))] b = _nc.concatenate(tuple(l)) return b def _boolFormatter(x): if x: return ' True' else: return 'False' def repr_format(x): return repr(x) def _array2string(a, max_line_width, precision, suppress_small, separator=' ', prefix="", formatter=None): if max_line_width is None: max_line_width = _line_width if precision is None: precision = _float_output_precision if suppress_small is None: suppress_small = _float_output_suppress_small if formatter is None: formatter = _formatter if a.size > _summaryThreshold: summary_insert = "..., " data = _leading_trailing(a) else: summary_insert = "" data = ravel(a) formatdict = {'bool' : _boolFormatter, 'int' : IntegerFormat(data), 'float' : FloatFormat(data, precision, suppress_small), 'longfloat' : LongFloatFormat(precision), 'complexfloat' : ComplexFormat(data, precision, suppress_small), 'longcomplexfloat' : LongComplexFormat(precision), 'datetime' : DatetimeFormat(data), 'timedelta' : TimedeltaFormat(data), 'numpystr' : repr_format, 'str' : str} if formatter is not None: fkeys = [k for k in formatter.keys() if formatter[k] is not None] if 'all' in fkeys: for key in formatdict.keys(): formatdict[key] = formatter['all'] if 'int_kind' in fkeys: for key in ['int']: formatdict[key] = formatter['int_kind'] if 'float_kind' in fkeys: for key in ['float', 'longfloat']: formatdict[key] = formatter['float_kind'] if 'complex_kind' in fkeys: for key in ['complexfloat', 'longcomplexfloat']: formatdict[key] = formatter['complex_kind'] if 'str_kind' in fkeys: for key in ['numpystr', 'str']: formatdict[key] = formatter['str_kind'] for key in formatdict.keys(): if key in fkeys: formatdict[key] = formatter[key] try: format_function = a._format msg = "The `_format` attribute is deprecated in Numpy 2.0 and " \ "will be removed in 2.1. Use the `formatter` kw instead." import warnings warnings.warn(msg, DeprecationWarning) except AttributeError: # find the right formatting function for the array dtypeobj = a.dtype.type if issubclass(dtypeobj, _nt.bool_): format_function = formatdict['bool'] elif issubclass(dtypeobj, _nt.integer): if issubclass(dtypeobj, _nt.timedelta64): format_function = formatdict['timedelta'] else: format_function = formatdict['int'] elif issubclass(dtypeobj, _nt.floating): if issubclass(dtypeobj, _nt.longfloat): format_function = formatdict['longfloat'] else: format_function = formatdict['float'] elif issubclass(dtypeobj, _nt.complexfloating): if issubclass(dtypeobj, _nt.clongfloat): format_function = formatdict['longcomplexfloat'] else: format_function = formatdict['complexfloat'] elif issubclass(dtypeobj, (_nt.unicode_, _nt.string_)): format_function = formatdict['numpystr'] elif issubclass(dtypeobj, _nt.datetime64): format_function = formatdict['datetime'] else: format_function = formatdict['numpystr'] # skip over "[" next_line_prefix = " " # skip over array( next_line_prefix += " "*len(prefix) lst = _formatArray(a, format_function, len(a.shape), max_line_width, next_line_prefix, separator, _summaryEdgeItems, summary_insert)[:-1] return lst def _convert_arrays(obj): from . import numeric as _nc newtup = [] for k in obj: if isinstance(k, _nc.ndarray): k = k.tolist() elif isinstance(k, tuple): k = _convert_arrays(k) newtup.append(k) return tuple(newtup) def array2string(a, max_line_width=None, precision=None, suppress_small=None, separator=' ', prefix="", style=repr, formatter=None): """ Return a string representation of an array. Parameters ---------- a : ndarray Input array. max_line_width : int, optional The maximum number of columns the string should span. Newline characters splits the string appropriately after array elements. precision : int, optional Floating point precision. Default is the current printing precision (usually 8), which can be altered using `set_printoptions`. suppress_small : bool, optional Represent very small numbers as zero. A number is "very small" if it is smaller than the current printing precision. separator : str, optional Inserted between elements. prefix : str, optional An array is typically printed as:: 'prefix(' + array2string(a) + ')' The length of the prefix string is used to align the output correctly. style : function, optional A function that accepts an ndarray and returns a string. Used only when the shape of `a` is equal to ``()``, i.e. for 0-D arrays. formatter : dict of callables, optional If not None, the keys should indicate the type(s) that the respective formatting function applies to. Callables should return a string. Types that are not specified (by their corresponding keys) are handled by the default formatters. Individual types for which a formatter can be set are:: - 'bool' - 'int' - 'timedelta' : a `numpy.timedelta64` - 'datetime' : a `numpy.datetime64` - 'float' - 'longfloat' : 128-bit floats - 'complexfloat' - 'longcomplexfloat' : composed of two 128-bit floats - 'numpy_str' : types `numpy.string_` and `numpy.unicode_` - 'str' : all other strings Other keys that can be used to set a group of types at once are:: - 'all' : sets all types - 'int_kind' : sets 'int' - 'float_kind' : sets 'float' and 'longfloat' - 'complex_kind' : sets 'complexfloat' and 'longcomplexfloat' - 'str_kind' : sets 'str' and 'numpystr' Returns ------- array_str : str String representation of the array. Raises ------ TypeError if a callable in `formatter` does not return a string. See Also -------- array_str, array_repr, set_printoptions, get_printoptions Notes ----- If a formatter is specified for a certain type, the `precision` keyword is ignored for that type. Examples -------- >>> x = np.array([1e-16,1,2,3]) >>> print np.array2string(x, precision=2, separator=',', ... suppress_small=True) [ 0., 1., 2., 3.] >>> x = np.arange(3.) >>> np.array2string(x, formatter={'float_kind':lambda x: "%.2f" % x}) '[0.00 1.00 2.00]' >>> x = np.arange(3) >>> np.array2string(x, formatter={'int':lambda x: hex(x)}) '[0x0L 0x1L 0x2L]' """ if a.shape == (): x = a.item() try: lst = a._format(x) msg = "The `_format` attribute is deprecated in Numpy " \ "2.0 and will be removed in 2.1. Use the " \ "`formatter` kw instead." import warnings warnings.warn(msg, DeprecationWarning) except AttributeError: if isinstance(x, tuple): x = _convert_arrays(x) lst = style(x) elif reduce(product, a.shape) == 0: # treat as a null array if any of shape elements == 0 lst = "[]" else: lst = _array2string(a, max_line_width, precision, suppress_small, separator, prefix, formatter=formatter) return lst def _extendLine(s, line, word, max_line_len, next_line_prefix): if len(line.rstrip()) + len(word.rstrip()) >= max_line_len: s += line.rstrip() + "\n" line = next_line_prefix line += word return s, line def _formatArray(a, format_function, rank, max_line_len, next_line_prefix, separator, edge_items, summary_insert): """formatArray is designed for two modes of operation: 1. Full output 2. Summarized output """ if rank == 0: obj = a.item() if isinstance(obj, tuple): obj = _convert_arrays(obj) return str(obj) if summary_insert and 2*edge_items < len(a): leading_items, trailing_items, summary_insert1 = \ edge_items, edge_items, summary_insert else: leading_items, trailing_items, summary_insert1 = 0, len(a), "" if rank == 1: s = "" line = next_line_prefix for i in range(leading_items): word = format_function(a[i]) + separator s, line = _extendLine(s, line, word, max_line_len, next_line_prefix) if summary_insert1: s, line = _extendLine(s, line, summary_insert1, max_line_len, next_line_prefix) for i in range(trailing_items, 1, -1): word = format_function(a[-i]) + separator s, line = _extendLine(s, line, word, max_line_len, next_line_prefix) word = format_function(a[-1]) s, line = _extendLine(s, line, word, max_line_len, next_line_prefix) s += line + "]\n" s = '[' + s[len(next_line_prefix):] else: s = '[' sep = separator.rstrip() for i in range(leading_items): if i > 0: s += next_line_prefix s += _formatArray(a[i], format_function, rank-1, max_line_len, " " + next_line_prefix, separator, edge_items, summary_insert) s = s.rstrip() + sep.rstrip() + '\n'*max(rank-1, 1) if summary_insert1: s += next_line_prefix + summary_insert1 + "\n" for i in range(trailing_items, 1, -1): if leading_items or i != trailing_items: s += next_line_prefix s += _formatArray(a[-i], format_function, rank-1, max_line_len, " " + next_line_prefix, separator, edge_items, summary_insert) s = s.rstrip() + sep.rstrip() + '\n'*max(rank-1, 1) if leading_items or trailing_items > 1: s += next_line_prefix s += _formatArray(a[-1], format_function, rank-1, max_line_len, " " + next_line_prefix, separator, edge_items, summary_insert).rstrip()+']\n' return s class FloatFormat(object): def __init__(self, data, precision, suppress_small, sign=False): self.precision = precision self.suppress_small = suppress_small self.sign = sign self.exp_format = False self.large_exponent = False self.max_str_len = 0 try: self.fillFormat(data) except (TypeError, NotImplementedError): # if reduce(data) fails, this instance will not be called, just # instantiated in formatdict. pass def fillFormat(self, data): from . import numeric as _nc with _nc.errstate(all='ignore'): special = isnan(data) | isinf(data) valid = not_equal(data, 0) & ~special non_zero = absolute(data.compress(valid)) if len(non_zero) == 0: max_val = 0. min_val = 0. else: max_val = maximum.reduce(non_zero) min_val = minimum.reduce(non_zero) if max_val >= 1.e8: self.exp_format = True if not self.suppress_small and (min_val < 0.0001 or max_val/min_val > 1000.): self.exp_format = True if self.exp_format: self.large_exponent = 0 < min_val < 1e-99 or max_val >= 1e100 self.max_str_len = 8 + self.precision if self.large_exponent: self.max_str_len += 1 if self.sign: format = '%+' else: format = '%' format = format + '%d.%de' % (self.max_str_len, self.precision) else: format = '%%.%df' % (self.precision,) if len(non_zero): precision = max([_digits(x, self.precision, format) for x in non_zero]) else: precision = 0 precision = min(self.precision, precision) self.max_str_len = len(str(int(max_val))) + precision + 2 if _nc.any(special): self.max_str_len = max(self.max_str_len, len(_nan_str), len(_inf_str)+1) if self.sign: format = '%#+' else: format = '%#' format = format + '%d.%df' % (self.max_str_len, precision) self.special_fmt = '%%%ds' % (self.max_str_len,) self.format = format def __call__(self, x, strip_zeros=True): from . import numeric as _nc with _nc.errstate(invalid='ignore'): if isnan(x): if self.sign: return self.special_fmt % ('+' + _nan_str,) else: return self.special_fmt % (_nan_str,) elif isinf(x): if x > 0: if self.sign: return self.special_fmt % ('+' + _inf_str,) else: return self.special_fmt % (_inf_str,) else: return self.special_fmt % ('-' + _inf_str,) s = self.format % x if self.large_exponent: # 3-digit exponent expsign = s[-3] if expsign == '+' or expsign == '-': s = s[1:-2] + '0' + s[-2:] elif self.exp_format: # 2-digit exponent if s[-3] == '0': s = ' ' + s[:-3] + s[-2:] elif strip_zeros: z = s.rstrip('0') s = z + ' '*(len(s)-len(z)) return s def _digits(x, precision, format): s = format % x z = s.rstrip('0') return precision - len(s) + len(z) class IntegerFormat(object): def __init__(self, data): try: max_str_len = max(len(str(maximum.reduce(data))), len(str(minimum.reduce(data)))) self.format = '%' + str(max_str_len) + 'd' except (TypeError, NotImplementedError): # if reduce(data) fails, this instance will not be called, just # instantiated in formatdict. pass except ValueError: # this occurs when everything is NA pass def __call__(self, x): if _MININT < x < _MAXINT: return self.format % x else: return "%s" % x class LongFloatFormat(object): # XXX Have to add something to determine the width to use a la FloatFormat # Right now, things won't line up properly def __init__(self, precision, sign=False): self.precision = precision self.sign = sign def __call__(self, x): if isnan(x): if self.sign: return '+' + _nan_str else: return ' ' + _nan_str elif isinf(x): if x > 0: if self.sign: return '+' + _inf_str else: return ' ' + _inf_str else: return '-' + _inf_str elif x >= 0: if self.sign: return '+' + format_longfloat(x, self.precision) else: return ' ' + format_longfloat(x, self.precision) else: return format_longfloat(x, self.precision) class LongComplexFormat(object): def __init__(self, precision): self.real_format = LongFloatFormat(precision) self.imag_format = LongFloatFormat(precision, sign=True) def __call__(self, x): r = self.real_format(x.real) i = self.imag_format(x.imag) return r + i + 'j' class ComplexFormat(object): def __init__(self, x, precision, suppress_small): self.real_format = FloatFormat(x.real, precision, suppress_small) self.imag_format = FloatFormat(x.imag, precision, suppress_small, sign=True) def __call__(self, x): r = self.real_format(x.real, strip_zeros=False) i = self.imag_format(x.imag, strip_zeros=False) if not self.imag_format.exp_format: z = i.rstrip('0') i = z + 'j' + ' '*(len(i)-len(z)) else: i = i + 'j' return r + i class DatetimeFormat(object): def __init__(self, x, unit=None, timezone=None, casting='same_kind'): # Get the unit from the dtype if unit is None: if x.dtype.kind == 'M': unit = datetime_data(x.dtype)[0] else: unit = 's' # If timezone is default, make it 'local' or 'UTC' based on the unit if timezone is None: # Date units -> UTC, time units -> local if unit in ('Y', 'M', 'W', 'D'): self.timezone = 'UTC' else: self.timezone = 'local' else: self.timezone = timezone self.unit = unit self.casting = casting def __call__(self, x): return "'%s'" % datetime_as_string(x, unit=self.unit, timezone=self.timezone, casting=self.casting) class TimedeltaFormat(object): def __init__(self, data): if data.dtype.kind == 'm': v = data.view('i8') max_str_len = max(len(str(maximum.reduce(v))), len(str(minimum.reduce(v)))) self.format = '%' + str(max_str_len) + 'd' def __call__(self, x): return self.format % x.astype('i8') numpy-1.8.2/numpy/core/_methods.py0000664000175100017510000001052012370216243020276 0ustar vagrantvagrant00000000000000""" Array methods which are called by the both the C-code for the method and the Python code for the NumPy-namespace function """ from __future__ import division, absolute_import, print_function import warnings from numpy.core import multiarray as mu from numpy.core import umath as um from numpy.core.numeric import asanyarray from numpy.core import numerictypes as nt def _amax(a, axis=None, out=None, keepdims=False): return um.maximum.reduce(a, axis=axis, out=out, keepdims=keepdims) def _amin(a, axis=None, out=None, keepdims=False): return um.minimum.reduce(a, axis=axis, out=out, keepdims=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) def _prod(a, axis=None, dtype=None, out=None, keepdims=False): return um.multiply.reduce(a, axis=axis, dtype=dtype, out=out, keepdims=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) 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) def _count_reduce_items(arr, axis): if axis is None: axis = tuple(range(arr.ndim)) if not isinstance(axis, tuple): axis = (axis,) items = 1 for ax in axis: items *= arr.shape[ax] return items def _mean(a, axis=None, dtype=None, out=None, keepdims=False): arr = asanyarray(a) rcount = _count_reduce_items(arr, axis) # Make this warning show up first if rcount == 0: warnings.warn("Mean of empty slice.", RuntimeWarning) # Cast bool, unsigned int, and int to float64 by default 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) if isinstance(ret, mu.ndarray): ret = um.true_divide( ret, rcount, out=ret, casting='unsafe', subok=False) elif hasattr(ret, 'dtype'): ret = ret.dtype.type(ret / rcount) else: ret = ret / rcount return ret def _var(a, axis=None, dtype=None, out=None, ddof=0, keepdims=False): arr = asanyarray(a) rcount = _count_reduce_items(arr, axis) # Make this warning show up on top. if ddof >= rcount: warnings.warn("Degrees of freedom <= 0 for slice", RuntimeWarning) # Cast bool, unsigned int, and int to float64 by default if dtype is None and issubclass(arr.dtype.type, (nt.integer, nt.bool_)): dtype = mu.dtype('f8') # 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) if isinstance(arrmean, mu.ndarray): arrmean = um.true_divide( arrmean, rcount, out=arrmean, casting='unsafe', subok=False) else: arrmean = arrmean.dtype.type(arrmean / rcount) # Compute sum of squared deviations from mean # Note that x may not be inexact and that we need it to be an array, # not a scalar. x = asanyarray(arr - arrmean) if issubclass(arr.dtype.type, nt.complexfloating): 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) # Compute degrees of freedom and make sure it is not negative. rcount = max([rcount - ddof, 0]) # divide by degrees of freedom if isinstance(ret, mu.ndarray): ret = um.true_divide( ret, rcount, out=ret, casting='unsafe', subok=False) elif hasattr(ret, 'dtype'): ret = ret.dtype.type(ret / rcount) else: ret = ret / rcount return ret def _std(a, axis=None, dtype=None, out=None, ddof=0, keepdims=False): ret = _var(a, axis=axis, dtype=dtype, out=out, ddof=ddof, keepdims=keepdims) if isinstance(ret, mu.ndarray): ret = um.sqrt(ret, out=ret) elif hasattr(ret, 'dtype'): ret = ret.dtype.type(um.sqrt(ret)) else: ret = um.sqrt(ret) return ret numpy-1.8.2/numpy/core/blasdot/0000775000175100017510000000000012371375427017567 5ustar vagrantvagrant00000000000000numpy-1.8.2/numpy/core/blasdot/_dotblas.c0000664000175100017510000013137212370216243021516 0ustar vagrantvagrant00000000000000/* * This module provides a BLAS optimized\nmatrix multiply, * inner product and dot for numpy arrays */ #define NPY_NO_DEPRECATED_API NPY_API_VERSION #include "Python.h" #include "npy_config.h" #include "numpy/arrayobject.h" #ifndef CBLAS_HEADER #define CBLAS_HEADER "cblas.h" #endif #include CBLAS_HEADER #include static char module_doc[] = "This module provides a BLAS optimized\nmatrix multiply, inner product and dot for numpy arrays"; static PyArray_DotFunc *oldFunctions[NPY_NTYPES]; static void FLOAT_dot(void *a, npy_intp stridea, void *b, npy_intp strideb, void *res, npy_intp n, void *tmp) { register npy_intp na = stridea / sizeof(float); register npy_intp nb = strideb / sizeof(float); if ((sizeof(float) * na == (size_t)stridea) && (sizeof(float) * nb == (size_t)strideb) && (na >= 0) && (nb >= 0)) *((float *)res) = cblas_sdot((int)n, (float *)a, na, (float *)b, nb); else oldFunctions[NPY_FLOAT](a, stridea, b, strideb, res, n, tmp); } static void DOUBLE_dot(void *a, npy_intp stridea, void *b, npy_intp strideb, void *res, npy_intp n, void *tmp) { register int na = stridea / sizeof(double); register int nb = strideb / sizeof(double); if ((sizeof(double) * na == (size_t)stridea) && (sizeof(double) * nb == (size_t)strideb) && (na >= 0) && (nb >= 0)) *((double *)res) = cblas_ddot((int)n, (double *)a, na, (double *)b, nb); else oldFunctions[NPY_DOUBLE](a, stridea, b, strideb, res, n, tmp); } static void CFLOAT_dot(void *a, npy_intp stridea, void *b, npy_intp strideb, void *res, npy_intp n, void *tmp) { register int na = stridea / sizeof(npy_cfloat); register int nb = strideb / sizeof(npy_cfloat); if ((sizeof(npy_cfloat) * na == (size_t)stridea) && (sizeof(npy_cfloat) * nb == (size_t)strideb) && (na >= 0) && (nb >= 0)) cblas_cdotu_sub((int)n, (float *)a, na, (float *)b, nb, (float *)res); else oldFunctions[NPY_CFLOAT](a, stridea, b, strideb, res, n, tmp); } static void CDOUBLE_dot(void *a, npy_intp stridea, void *b, npy_intp strideb, void *res, npy_intp n, void *tmp) { register int na = stridea / sizeof(npy_cdouble); register int nb = strideb / sizeof(npy_cdouble); if ((sizeof(npy_cdouble) * na == (size_t)stridea) && (sizeof(npy_cdouble) * nb == (size_t)strideb) && (na >= 0) && (nb >= 0)) cblas_zdotu_sub((int)n, (double *)a, na, (double *)b, nb, (double *)res); else oldFunctions[NPY_CDOUBLE](a, stridea, b, strideb, res, n, tmp); } static npy_bool altered=NPY_FALSE; /* * alterdot() changes all dot functions to use blas. */ static PyObject * dotblas_alterdot(PyObject *NPY_UNUSED(dummy), PyObject *args) { PyArray_Descr *descr; if (!PyArg_ParseTuple(args, "")) return NULL; /* Replace the dot functions to the ones using blas */ if (!altered) { descr = PyArray_DescrFromType(NPY_FLOAT); oldFunctions[NPY_FLOAT] = descr->f->dotfunc; descr->f->dotfunc = (PyArray_DotFunc *)FLOAT_dot; descr = PyArray_DescrFromType(NPY_DOUBLE); oldFunctions[NPY_DOUBLE] = descr->f->dotfunc; descr->f->dotfunc = (PyArray_DotFunc *)DOUBLE_dot; descr = PyArray_DescrFromType(NPY_CFLOAT); oldFunctions[NPY_CFLOAT] = descr->f->dotfunc; descr->f->dotfunc = (PyArray_DotFunc *)CFLOAT_dot; descr = PyArray_DescrFromType(NPY_CDOUBLE); oldFunctions[NPY_CDOUBLE] = descr->f->dotfunc; descr->f->dotfunc = (PyArray_DotFunc *)CDOUBLE_dot; altered = NPY_TRUE; } Py_INCREF(Py_None); return Py_None; } /* * restoredot() restores dots to defaults. */ static PyObject * dotblas_restoredot(PyObject *NPY_UNUSED(dummy), PyObject *args) { PyArray_Descr *descr; if (!PyArg_ParseTuple(args, "")) return NULL; if (altered) { descr = PyArray_DescrFromType(NPY_FLOAT); descr->f->dotfunc = oldFunctions[NPY_FLOAT]; oldFunctions[NPY_FLOAT] = NULL; Py_XDECREF(descr); descr = PyArray_DescrFromType(NPY_DOUBLE); descr->f->dotfunc = oldFunctions[NPY_DOUBLE]; oldFunctions[NPY_DOUBLE] = NULL; Py_XDECREF(descr); descr = PyArray_DescrFromType(NPY_CFLOAT); descr->f->dotfunc = oldFunctions[NPY_CFLOAT]; oldFunctions[NPY_CFLOAT] = NULL; Py_XDECREF(descr); descr = PyArray_DescrFromType(NPY_CDOUBLE); descr->f->dotfunc = oldFunctions[NPY_CDOUBLE]; oldFunctions[NPY_CDOUBLE] = NULL; Py_XDECREF(descr); altered = NPY_FALSE; } Py_INCREF(Py_None); return Py_None; } typedef enum {_scalar, _column, _row, _matrix} MatrixShape; static MatrixShape _select_matrix_shape(PyArrayObject *array) { switch (PyArray_NDIM(array)) { case 0: return _scalar; case 1: if (PyArray_DIM(array, 0) > 1) return _column; return _scalar; case 2: if (PyArray_DIM(array, 0) > 1) { if (PyArray_DIM(array, 1) == 1) return _column; else return _matrix; } if (PyArray_DIM(array, 1) == 1) return _scalar; return _row; } return _matrix; } /* This also makes sure that the data segment is aligned with an itemsize address as well by returning one if not true. */ static int _bad_strides(PyArrayObject *ap) { register int itemsize = PyArray_ITEMSIZE(ap); register int i, N=PyArray_NDIM(ap); register npy_intp *strides = PyArray_STRIDES(ap); if (((npy_intp)(PyArray_DATA(ap)) % itemsize) != 0) return 1; for (i=0; i 2) || (PyArray_NDIM(ap2) > 2)) { /* * This function doesn't handle dimensions greater than 2 * (or negative striding) -- other * than to ensure the dot function is altered */ if (!altered) { /* need to alter dot product */ PyObject *tmp1, *tmp2; tmp1 = PyTuple_New(0); tmp2 = dotblas_alterdot(NULL, tmp1); Py_DECREF(tmp1); Py_DECREF(tmp2); } ret = (PyArrayObject *)PyArray_MatrixProduct2((PyObject *)ap1, (PyObject *)ap2, out); Py_DECREF(ap1); Py_DECREF(ap2); return PyArray_Return(ret); } if (_bad_strides(ap1)) { op1 = PyArray_NewCopy(ap1, NPY_ANYORDER); Py_DECREF(ap1); ap1 = (PyArrayObject *)op1; if (ap1 == NULL) { goto fail; } } if (_bad_strides(ap2)) { op2 = PyArray_NewCopy(ap2, NPY_ANYORDER); Py_DECREF(ap2); ap2 = (PyArrayObject *)op2; if (ap2 == NULL) { goto fail; } } ap1shape = _select_matrix_shape(ap1); ap2shape = _select_matrix_shape(ap2); if (ap1shape == _scalar || ap2shape == _scalar) { PyArrayObject *oap1, *oap2; oap1 = ap1; oap2 = ap2; /* One of ap1 or ap2 is a scalar */ if (ap1shape == _scalar) { /* Make ap2 the scalar */ PyArrayObject *t = ap1; ap1 = ap2; ap2 = t; ap1shape = ap2shape; ap2shape = _scalar; } if (ap1shape == _row) { ap1stride = PyArray_STRIDE(ap1, 1); } else if (PyArray_NDIM(ap1) > 0) { ap1stride = PyArray_STRIDE(ap1, 0); } if (PyArray_NDIM(ap1) == 0 || PyArray_NDIM(ap2) == 0) { npy_intp *thisdims; if (PyArray_NDIM(ap1) == 0) { nd = PyArray_NDIM(ap2); thisdims = PyArray_DIMS(ap2); } else { nd = PyArray_NDIM(ap1); thisdims = PyArray_DIMS(ap1); } l = 1; for (j = 0; j < nd; j++) { dimensions[j] = thisdims[j]; l *= dimensions[j]; } } else { l = PyArray_DIM(oap1, PyArray_NDIM(oap1) - 1); if (PyArray_DIM(oap2, 0) != l) { PyErr_SetString(PyExc_ValueError, "matrices are not aligned"); goto fail; } nd = PyArray_NDIM(ap1) + PyArray_NDIM(ap2) - 2; /* * nd = 0 or 1 or 2. If nd == 0 do nothing ... */ if (nd == 1) { /* * Either PyArray_NDIM(ap1) is 1 dim or PyArray_NDIM(ap2) is 1 dim * and the other is 2-dim */ dimensions[0] = (PyArray_NDIM(oap1) == 2) ? PyArray_DIM(oap1, 0) : PyArray_DIM(oap2, 1); l = dimensions[0]; /* * Fix it so that dot(shape=(N,1), shape=(1,)) * and dot(shape=(1,), shape=(1,N)) both return * an (N,) array (but use the fast scalar code) */ } else if (nd == 2) { dimensions[0] = PyArray_DIM(oap1, 0); dimensions[1] = PyArray_DIM(oap2, 1); /* * We need to make sure that dot(shape=(1,1), shape=(1,N)) * and dot(shape=(N,1),shape=(1,1)) uses * scalar multiplication appropriately */ if (ap1shape == _row) { l = dimensions[1]; } else { l = dimensions[0]; } } /* Check if the summation dimension is 0-sized */ if (PyArray_DIM(oap1, PyArray_NDIM(oap1) - 1) == 0) { l = 0; } } } else { /* * (PyArray_NDIM(ap1) <= 2 && PyArray_NDIM(ap2) <= 2) * Both ap1 and ap2 are vectors or matrices */ l = PyArray_DIM(ap1, PyArray_NDIM(ap1) - 1); if (PyArray_DIM(ap2, 0) != l) { PyErr_SetString(PyExc_ValueError, "matrices are not aligned"); goto fail; } nd = PyArray_NDIM(ap1) + PyArray_NDIM(ap2) - 2; if (nd == 1) dimensions[0] = (PyArray_NDIM(ap1) == 2) ? PyArray_DIM(ap1, 0) : PyArray_DIM(ap2, 1); else if (nd == 2) { dimensions[0] = PyArray_DIM(ap1, 0); dimensions[1] = PyArray_DIM(ap2, 1); } } /* Choose which subtype to return */ if (Py_TYPE(ap1) != Py_TYPE(ap2)) { prior2 = PyArray_GetPriority((PyObject *)ap2, 0.0); prior1 = PyArray_GetPriority((PyObject *)ap1, 0.0); subtype = (prior2 > prior1 ? Py_TYPE(ap2) : Py_TYPE(ap1)); } else { prior1 = prior2 = 0.0; subtype = Py_TYPE(ap1); } if (out) { int d; /* verify that out is usable */ if (Py_TYPE(out) != subtype || PyArray_NDIM(out) != nd || PyArray_TYPE(out) != typenum || !PyArray_ISCARRAY(out)) { PyErr_SetString(PyExc_ValueError, "output array is not acceptable " "(must have the right type, nr dimensions, and be a C-Array)"); goto fail; } for (d = 0; d < nd; ++d) { if (dimensions[d] != PyArray_DIM(out, d)) { PyErr_SetString(PyExc_ValueError, "output array has wrong dimensions"); goto fail; } } Py_INCREF(out); ret = out; } else { ret = (PyArrayObject *)PyArray_New(subtype, nd, dimensions, typenum, NULL, NULL, 0, 0, (PyObject *) (prior2 > prior1 ? ap2 : ap1)); } if (ret == NULL) { goto fail; } numbytes = PyArray_NBYTES(ret); memset(PyArray_DATA(ret), 0, numbytes); if (numbytes==0 || l == 0) { Py_DECREF(ap1); Py_DECREF(ap2); return PyArray_Return(ret); } if (ap2shape == _scalar) { /* * Multiplication by a scalar -- Level 1 BLAS * if ap1shape is a matrix and we are not contiguous, then we can't * just blast through the entire array using a single striding factor */ NPY_BEGIN_ALLOW_THREADS; if (typenum == NPY_DOUBLE) { if (l == 1) { *((double *)PyArray_DATA(ret)) = *((double *)PyArray_DATA(ap2)) * *((double *)PyArray_DATA(ap1)); } else if (ap1shape != _matrix) { cblas_daxpy(l, *((double *)PyArray_DATA(ap2)), (double *)PyArray_DATA(ap1), ap1stride/sizeof(double), (double *)PyArray_DATA(ret), 1); } else { int maxind, oind, i, a1s, rets; char *ptr, *rptr; double val; maxind = (PyArray_DIM(ap1, 0) >= PyArray_DIM(ap1, 1) ? 0 : 1); oind = 1-maxind; ptr = PyArray_DATA(ap1); rptr = PyArray_DATA(ret); l = PyArray_DIM(ap1, maxind); val = *((double *)PyArray_DATA(ap2)); a1s = PyArray_STRIDE(ap1, maxind) / sizeof(double); rets = PyArray_STRIDE(ret, maxind) / sizeof(double); for (i = 0; i < PyArray_DIM(ap1, oind); i++) { cblas_daxpy(l, val, (double *)ptr, a1s, (double *)rptr, rets); ptr += PyArray_STRIDE(ap1, oind); rptr += PyArray_STRIDE(ret, oind); } } } else if (typenum == NPY_CDOUBLE) { if (l == 1) { npy_cdouble *ptr1, *ptr2, *res; ptr1 = (npy_cdouble *)PyArray_DATA(ap2); ptr2 = (npy_cdouble *)PyArray_DATA(ap1); res = (npy_cdouble *)PyArray_DATA(ret); res->real = ptr1->real * ptr2->real - ptr1->imag * ptr2->imag; res->imag = ptr1->real * ptr2->imag + ptr1->imag * ptr2->real; } else if (ap1shape != _matrix) { cblas_zaxpy(l, (double *)PyArray_DATA(ap2), (double *)PyArray_DATA(ap1), ap1stride/sizeof(npy_cdouble), (double *)PyArray_DATA(ret), 1); } else { int maxind, oind, i, a1s, rets; char *ptr, *rptr; double *pval; maxind = (PyArray_DIM(ap1, 0) >= PyArray_DIM(ap1, 1) ? 0 : 1); oind = 1-maxind; ptr = PyArray_DATA(ap1); rptr = PyArray_DATA(ret); l = PyArray_DIM(ap1, maxind); pval = (double *)PyArray_DATA(ap2); a1s = PyArray_STRIDE(ap1, maxind) / sizeof(npy_cdouble); rets = PyArray_STRIDE(ret, maxind) / sizeof(npy_cdouble); for (i = 0; i < PyArray_DIM(ap1, oind); i++) { cblas_zaxpy(l, pval, (double *)ptr, a1s, (double *)rptr, rets); ptr += PyArray_STRIDE(ap1, oind); rptr += PyArray_STRIDE(ret, oind); } } } else if (typenum == NPY_FLOAT) { if (l == 1) { *((float *)PyArray_DATA(ret)) = *((float *)PyArray_DATA(ap2)) * *((float *)PyArray_DATA(ap1)); } else if (ap1shape != _matrix) { cblas_saxpy(l, *((float *)PyArray_DATA(ap2)), (float *)PyArray_DATA(ap1), ap1stride/sizeof(float), (float *)PyArray_DATA(ret), 1); } else { int maxind, oind, i, a1s, rets; char *ptr, *rptr; float val; maxind = (PyArray_DIM(ap1, 0) >= PyArray_DIM(ap1, 1) ? 0 : 1); oind = 1-maxind; ptr = PyArray_DATA(ap1); rptr = PyArray_DATA(ret); l = PyArray_DIM(ap1, maxind); val = *((float *)PyArray_DATA(ap2)); a1s = PyArray_STRIDE(ap1, maxind) / sizeof(float); rets = PyArray_STRIDE(ret, maxind) / sizeof(float); for (i = 0; i < PyArray_DIM(ap1, oind); i++) { cblas_saxpy(l, val, (float *)ptr, a1s, (float *)rptr, rets); ptr += PyArray_STRIDE(ap1, oind); rptr += PyArray_STRIDE(ret, oind); } } } else if (typenum == NPY_CFLOAT) { if (l == 1) { npy_cfloat *ptr1, *ptr2, *res; ptr1 = (npy_cfloat *)PyArray_DATA(ap2); ptr2 = (npy_cfloat *)PyArray_DATA(ap1); res = (npy_cfloat *)PyArray_DATA(ret); res->real = ptr1->real * ptr2->real - ptr1->imag * ptr2->imag; res->imag = ptr1->real * ptr2->imag + ptr1->imag * ptr2->real; } else if (ap1shape != _matrix) { cblas_caxpy(l, (float *)PyArray_DATA(ap2), (float *)PyArray_DATA(ap1), ap1stride/sizeof(npy_cfloat), (float *)PyArray_DATA(ret), 1); } else { int maxind, oind, i, a1s, rets; char *ptr, *rptr; float *pval; maxind = (PyArray_DIM(ap1, 0) >= PyArray_DIM(ap1, 1) ? 0 : 1); oind = 1-maxind; ptr = PyArray_DATA(ap1); rptr = PyArray_DATA(ret); l = PyArray_DIM(ap1, maxind); pval = (float *)PyArray_DATA(ap2); a1s = PyArray_STRIDE(ap1, maxind) / sizeof(npy_cfloat); rets = PyArray_STRIDE(ret, maxind) / sizeof(npy_cfloat); for (i = 0; i < PyArray_DIM(ap1, oind); i++) { cblas_caxpy(l, pval, (float *)ptr, a1s, (float *)rptr, rets); ptr += PyArray_STRIDE(ap1, oind); rptr += PyArray_STRIDE(ret, oind); } } } NPY_END_ALLOW_THREADS; } else if ((ap2shape == _column) && (ap1shape != _matrix)) { int ap1s, ap2s; NPY_BEGIN_ALLOW_THREADS; ap2s = PyArray_STRIDE(ap2, 0) / PyArray_ITEMSIZE(ap2); if (ap1shape == _row) { ap1s = PyArray_STRIDE(ap1, 1) / PyArray_ITEMSIZE(ap1); } else { ap1s = PyArray_STRIDE(ap1, 0) / PyArray_ITEMSIZE(ap1); } /* Dot product between two vectors -- Level 1 BLAS */ if (typenum == NPY_DOUBLE) { double result = cblas_ddot(l, (double *)PyArray_DATA(ap1), ap1s, (double *)PyArray_DATA(ap2), ap2s); *((double *)PyArray_DATA(ret)) = result; } else if (typenum == NPY_FLOAT) { float result = cblas_sdot(l, (float *)PyArray_DATA(ap1), ap1s, (float *)PyArray_DATA(ap2), ap2s); *((float *)PyArray_DATA(ret)) = result; } else if (typenum == NPY_CDOUBLE) { cblas_zdotu_sub(l, (double *)PyArray_DATA(ap1), ap1s, (double *)PyArray_DATA(ap2), ap2s, (double *)PyArray_DATA(ret)); } else if (typenum == NPY_CFLOAT) { cblas_cdotu_sub(l, (float *)PyArray_DATA(ap1), ap1s, (float *)PyArray_DATA(ap2), ap2s, (float *)PyArray_DATA(ret)); } NPY_END_ALLOW_THREADS; } else if (ap1shape == _matrix && ap2shape != _matrix) { /* Matrix vector multiplication -- Level 2 BLAS */ /* lda must be MAX(M,1) */ enum CBLAS_ORDER Order; int ap2s; if (!PyArray_ISONESEGMENT(ap1)) { PyObject *new; new = PyArray_Copy(ap1); Py_DECREF(ap1); ap1 = (PyArrayObject *)new; if (new == NULL) { goto fail; } } NPY_BEGIN_ALLOW_THREADS if (PyArray_ISCONTIGUOUS(ap1)) { Order = CblasRowMajor; lda = (PyArray_DIM(ap1, 1) > 1 ? PyArray_DIM(ap1, 1) : 1); } else { Order = CblasColMajor; lda = (PyArray_DIM(ap1, 0) > 1 ? PyArray_DIM(ap1, 0) : 1); } ap2s = PyArray_STRIDE(ap2, 0) / PyArray_ITEMSIZE(ap2); if (typenum == NPY_DOUBLE) { cblas_dgemv(Order, CblasNoTrans, PyArray_DIM(ap1, 0), PyArray_DIM(ap1, 1), 1.0, (double *)PyArray_DATA(ap1), lda, (double *)PyArray_DATA(ap2), ap2s, 0.0, (double *)PyArray_DATA(ret), 1); } else if (typenum == NPY_FLOAT) { cblas_sgemv(Order, CblasNoTrans, PyArray_DIM(ap1, 0), PyArray_DIM(ap1, 1), 1.0, (float *)PyArray_DATA(ap1), lda, (float *)PyArray_DATA(ap2), ap2s, 0.0, (float *)PyArray_DATA(ret), 1); } else if (typenum == NPY_CDOUBLE) { cblas_zgemv(Order, CblasNoTrans, PyArray_DIM(ap1, 0), PyArray_DIM(ap1, 1), oneD, (double *)PyArray_DATA(ap1), lda, (double *)PyArray_DATA(ap2), ap2s, zeroD, (double *)PyArray_DATA(ret), 1); } else if (typenum == NPY_CFLOAT) { cblas_cgemv(Order, CblasNoTrans, PyArray_DIM(ap1, 0), PyArray_DIM(ap1, 1), oneF, (float *)PyArray_DATA(ap1), lda, (float *)PyArray_DATA(ap2), ap2s, zeroF, (float *)PyArray_DATA(ret), 1); } NPY_END_ALLOW_THREADS; } else if (ap1shape != _matrix && ap2shape == _matrix) { /* Vector matrix multiplication -- Level 2 BLAS */ enum CBLAS_ORDER Order; int ap1s; if (!PyArray_ISONESEGMENT(ap2)) { PyObject *new; new = PyArray_Copy(ap2); Py_DECREF(ap2); ap2 = (PyArrayObject *)new; if (new == NULL) { goto fail; } } NPY_BEGIN_ALLOW_THREADS if (PyArray_ISCONTIGUOUS(ap2)) { Order = CblasRowMajor; lda = (PyArray_DIM(ap2, 1) > 1 ? PyArray_DIM(ap2, 1) : 1); } else { Order = CblasColMajor; lda = (PyArray_DIM(ap2, 0) > 1 ? PyArray_DIM(ap2, 0) : 1); } if (ap1shape == _row) { ap1s = PyArray_STRIDE(ap1, 1) / PyArray_ITEMSIZE(ap1); } else { ap1s = PyArray_STRIDE(ap1, 0) / PyArray_ITEMSIZE(ap1); } if (typenum == NPY_DOUBLE) { cblas_dgemv(Order, CblasTrans, PyArray_DIM(ap2, 0), PyArray_DIM(ap2, 1), 1.0, (double *)PyArray_DATA(ap2), lda, (double *)PyArray_DATA(ap1), ap1s, 0.0, (double *)PyArray_DATA(ret), 1); } else if (typenum == NPY_FLOAT) { cblas_sgemv(Order, CblasTrans, PyArray_DIM(ap2, 0), PyArray_DIM(ap2, 1), 1.0, (float *)PyArray_DATA(ap2), lda, (float *)PyArray_DATA(ap1), ap1s, 0.0, (float *)PyArray_DATA(ret), 1); } else if (typenum == NPY_CDOUBLE) { cblas_zgemv(Order, CblasTrans, PyArray_DIM(ap2, 0), PyArray_DIM(ap2, 1), oneD, (double *)PyArray_DATA(ap2), lda, (double *)PyArray_DATA(ap1), ap1s, zeroD, (double *)PyArray_DATA(ret), 1); } else if (typenum == NPY_CFLOAT) { cblas_cgemv(Order, CblasTrans, PyArray_DIM(ap2, 0), PyArray_DIM(ap2, 1), oneF, (float *)PyArray_DATA(ap2), lda, (float *)PyArray_DATA(ap1), ap1s, zeroF, (float *)PyArray_DATA(ret), 1); } NPY_END_ALLOW_THREADS; } else { /* * (PyArray_NDIM(ap1) == 2 && PyArray_NDIM(ap2) == 2) * Matrix matrix multiplication -- Level 3 BLAS * L x M multiplied by M x N */ enum CBLAS_ORDER Order; enum CBLAS_TRANSPOSE Trans1, Trans2; int M, N, L; /* Optimization possible: */ /* * We may be able to handle single-segment arrays here * using appropriate values of Order, Trans1, and Trans2. */ if (!PyArray_IS_C_CONTIGUOUS(ap2) && !PyArray_IS_F_CONTIGUOUS(ap2)) { PyObject *new = PyArray_Copy(ap2); Py_DECREF(ap2); ap2 = (PyArrayObject *)new; if (new == NULL) { goto fail; } } if (!PyArray_IS_C_CONTIGUOUS(ap1) && !PyArray_IS_F_CONTIGUOUS(ap1)) { PyObject *new = PyArray_Copy(ap1); Py_DECREF(ap1); ap1 = (PyArrayObject *)new; if (new == NULL) { goto fail; } } NPY_BEGIN_ALLOW_THREADS; Order = CblasRowMajor; Trans1 = CblasNoTrans; Trans2 = CblasNoTrans; L = PyArray_DIM(ap1, 0); N = PyArray_DIM(ap2, 1); M = PyArray_DIM(ap2, 0); lda = (PyArray_DIM(ap1, 1) > 1 ? PyArray_DIM(ap1, 1) : 1); ldb = (PyArray_DIM(ap2, 1) > 1 ? PyArray_DIM(ap2, 1) : 1); ldc = (PyArray_DIM(ret, 1) > 1 ? PyArray_DIM(ret, 1) : 1); /* * Avoid temporary copies for arrays in Fortran order */ if (PyArray_IS_F_CONTIGUOUS(ap1)) { Trans1 = CblasTrans; lda = (PyArray_DIM(ap1, 0) > 1 ? PyArray_DIM(ap1, 0) : 1); } if (PyArray_IS_F_CONTIGUOUS(ap2)) { Trans2 = CblasTrans; ldb = (PyArray_DIM(ap2, 0) > 1 ? PyArray_DIM(ap2, 0) : 1); } if (typenum == NPY_DOUBLE) { cblas_dgemm(Order, Trans1, Trans2, L, N, M, 1.0, (double *)PyArray_DATA(ap1), lda, (double *)PyArray_DATA(ap2), ldb, 0.0, (double *)PyArray_DATA(ret), ldc); } else if (typenum == NPY_FLOAT) { cblas_sgemm(Order, Trans1, Trans2, L, N, M, 1.0, (float *)PyArray_DATA(ap1), lda, (float *)PyArray_DATA(ap2), ldb, 0.0, (float *)PyArray_DATA(ret), ldc); } else if (typenum == NPY_CDOUBLE) { cblas_zgemm(Order, Trans1, Trans2, L, N, M, oneD, (double *)PyArray_DATA(ap1), lda, (double *)PyArray_DATA(ap2), ldb, zeroD, (double *)PyArray_DATA(ret), ldc); } else if (typenum == NPY_CFLOAT) { cblas_cgemm(Order, Trans1, Trans2, L, N, M, oneF, (float *)PyArray_DATA(ap1), lda, (float *)PyArray_DATA(ap2), ldb, zeroF, (float *)PyArray_DATA(ret), ldc); } NPY_END_ALLOW_THREADS; } Py_DECREF(ap1); Py_DECREF(ap2); return PyArray_Return(ret); fail: Py_XDECREF(ap1); Py_XDECREF(ap2); Py_XDECREF(ret); return NULL; } /* * innerproduct(a,b) * * Returns the inner product of a and b for arrays of * floating point types. Like the generic NumPy equivalent the product * sum is over the last dimension of a and b. * NB: The first argument is not conjugated. */ static PyObject * dotblas_innerproduct(PyObject *NPY_UNUSED(dummy), PyObject *args) { PyObject *op1, *op2; PyArrayObject *ap1, *ap2, *ret; int j, l, lda, ldb, ldc; int typenum, nd; npy_intp dimensions[NPY_MAXDIMS]; static const float oneF[2] = {1.0, 0.0}; static const float zeroF[2] = {0.0, 0.0}; static const double oneD[2] = {1.0, 0.0}; static const double zeroD[2] = {0.0, 0.0}; PyTypeObject *subtype; double prior1, prior2; if (!PyArg_ParseTuple(args, "OO", &op1, &op2)) return NULL; /* * Inner product using the BLAS. The product sum is taken along the last * dimensions of the two arrays. * Only speeds things up for float double and complex types. */ typenum = PyArray_ObjectType(op1, 0); typenum = PyArray_ObjectType(op2, typenum); /* This function doesn't handle other types */ if ((typenum != NPY_DOUBLE && typenum != NPY_CDOUBLE && typenum != NPY_FLOAT && typenum != NPY_CFLOAT)) { return PyArray_Return((PyArrayObject *)PyArray_InnerProduct(op1, op2)); } ret = NULL; ap1 = (PyArrayObject *)PyArray_ContiguousFromObject(op1, typenum, 0, 0); if (ap1 == NULL) return NULL; ap2 = (PyArrayObject *)PyArray_ContiguousFromObject(op2, typenum, 0, 0); if (ap2 == NULL) goto fail; if ((PyArray_NDIM(ap1) > 2) || (PyArray_NDIM(ap2) > 2)) { /* This function doesn't handle dimensions greater than 2 -- other than to ensure the dot function is altered */ if (!altered) { /* need to alter dot product */ PyObject *tmp1, *tmp2; tmp1 = PyTuple_New(0); tmp2 = dotblas_alterdot(NULL, tmp1); Py_DECREF(tmp1); Py_DECREF(tmp2); } ret = (PyArrayObject *)PyArray_InnerProduct((PyObject *)ap1, (PyObject *)ap2); Py_DECREF(ap1); Py_DECREF(ap2); return PyArray_Return(ret); } if (PyArray_NDIM(ap1) == 0 || PyArray_NDIM(ap2) == 0) { /* One of ap1 or ap2 is a scalar */ if (PyArray_NDIM(ap1) == 0) { /* Make ap2 the scalar */ PyArrayObject *t = ap1; ap1 = ap2; ap2 = t; } for (l = 1, j = 0; j < PyArray_NDIM(ap1); j++) { dimensions[j] = PyArray_DIM(ap1, j); l *= dimensions[j]; } nd = PyArray_NDIM(ap1); } else { /* (PyArray_NDIM(ap1) <= 2 && PyArray_NDIM(ap2) <= 2) */ /* Both ap1 and ap2 are vectors or matrices */ l = PyArray_DIM(ap1, PyArray_NDIM(ap1)-1); if (PyArray_DIM(ap2, PyArray_NDIM(ap2)-1) != l) { PyErr_SetString(PyExc_ValueError, "matrices are not aligned"); goto fail; } nd = PyArray_NDIM(ap1)+PyArray_NDIM(ap2)-2; if (nd == 1) dimensions[0] = (PyArray_NDIM(ap1) == 2) ? PyArray_DIM(ap1, 0) : PyArray_DIM(ap2, 0); else if (nd == 2) { dimensions[0] = PyArray_DIM(ap1, 0); dimensions[1] = PyArray_DIM(ap2, 0); } } /* Choose which subtype to return */ prior2 = PyArray_GetPriority((PyObject *)ap2, 0.0); prior1 = PyArray_GetPriority((PyObject *)ap1, 0.0); subtype = (prior2 > prior1 ? Py_TYPE(ap2) : Py_TYPE(ap1)); ret = (PyArrayObject *)PyArray_New(subtype, nd, dimensions, typenum, NULL, NULL, 0, 0, (PyObject *)\ (prior2 > prior1 ? ap2 : ap1)); if (ret == NULL) goto fail; NPY_BEGIN_ALLOW_THREADS memset(PyArray_DATA(ret), 0, PyArray_NBYTES(ret)); if (PyArray_NDIM(ap2) == 0) { /* Multiplication by a scalar -- Level 1 BLAS */ if (typenum == NPY_DOUBLE) { cblas_daxpy(l, *((double *)PyArray_DATA(ap2)), (double *)PyArray_DATA(ap1), 1, (double *)PyArray_DATA(ret), 1); } else if (typenum == NPY_CDOUBLE) { cblas_zaxpy(l, (double *)PyArray_DATA(ap2), (double *)PyArray_DATA(ap1), 1, (double *)PyArray_DATA(ret), 1); } else if (typenum == NPY_FLOAT) { cblas_saxpy(l, *((float *)PyArray_DATA(ap2)), (float *)PyArray_DATA(ap1), 1, (float *)PyArray_DATA(ret), 1); } else if (typenum == NPY_CFLOAT) { cblas_caxpy(l, (float *)PyArray_DATA(ap2), (float *)PyArray_DATA(ap1), 1, (float *)PyArray_DATA(ret), 1); } } else if (PyArray_NDIM(ap1) == 1 && PyArray_NDIM(ap2) == 1) { /* Dot product between two vectors -- Level 1 BLAS */ if (typenum == NPY_DOUBLE) { double result = cblas_ddot(l, (double *)PyArray_DATA(ap1), 1, (double *)PyArray_DATA(ap2), 1); *((double *)PyArray_DATA(ret)) = result; } else if (typenum == NPY_CDOUBLE) { cblas_zdotu_sub(l, (double *)PyArray_DATA(ap1), 1, (double *)PyArray_DATA(ap2), 1, (double *)PyArray_DATA(ret)); } else if (typenum == NPY_FLOAT) { float result = cblas_sdot(l, (float *)PyArray_DATA(ap1), 1, (float *)PyArray_DATA(ap2), 1); *((float *)PyArray_DATA(ret)) = result; } else if (typenum == NPY_CFLOAT) { cblas_cdotu_sub(l, (float *)PyArray_DATA(ap1), 1, (float *)PyArray_DATA(ap2), 1, (float *)PyArray_DATA(ret)); } } else if (PyArray_NDIM(ap1) == 2 && PyArray_NDIM(ap2) == 1) { /* Matrix-vector multiplication -- Level 2 BLAS */ lda = (PyArray_DIM(ap1, 1) > 1 ? PyArray_DIM(ap1, 1) : 1); if (typenum == NPY_DOUBLE) { cblas_dgemv(CblasRowMajor, CblasNoTrans, PyArray_DIM(ap1, 0), PyArray_DIM(ap1, 1), 1.0, (double *)PyArray_DATA(ap1), lda, (double *)PyArray_DATA(ap2), 1, 0.0, (double *)PyArray_DATA(ret), 1); } else if (typenum == NPY_CDOUBLE) { cblas_zgemv(CblasRowMajor, CblasNoTrans, PyArray_DIM(ap1, 0), PyArray_DIM(ap1, 1), oneD, (double *)PyArray_DATA(ap1), lda, (double *)PyArray_DATA(ap2), 1, zeroD, (double *)PyArray_DATA(ret), 1); } else if (typenum == NPY_FLOAT) { cblas_sgemv(CblasRowMajor, CblasNoTrans, PyArray_DIM(ap1, 0), PyArray_DIM(ap1, 1), 1.0, (float *)PyArray_DATA(ap1), lda, (float *)PyArray_DATA(ap2), 1, 0.0, (float *)PyArray_DATA(ret), 1); } else if (typenum == NPY_CFLOAT) { cblas_cgemv(CblasRowMajor, CblasNoTrans, PyArray_DIM(ap1, 0), PyArray_DIM(ap1, 1), oneF, (float *)PyArray_DATA(ap1), lda, (float *)PyArray_DATA(ap2), 1, zeroF, (float *)PyArray_DATA(ret), 1); } } else if (PyArray_NDIM(ap1) == 1 && PyArray_NDIM(ap2) == 2) { /* Vector matrix multiplication -- Level 2 BLAS */ lda = (PyArray_DIM(ap2, 1) > 1 ? PyArray_DIM(ap2, 1) : 1); if (typenum == NPY_DOUBLE) { cblas_dgemv(CblasRowMajor, CblasNoTrans, PyArray_DIM(ap2, 0), PyArray_DIM(ap2, 1), 1.0, (double *)PyArray_DATA(ap2), lda, (double *)PyArray_DATA(ap1), 1, 0.0, (double *)PyArray_DATA(ret), 1); } else if (typenum == NPY_CDOUBLE) { cblas_zgemv(CblasRowMajor, CblasNoTrans, PyArray_DIM(ap2, 0), PyArray_DIM(ap2, 1), oneD, (double *)PyArray_DATA(ap2), lda, (double *)PyArray_DATA(ap1), 1, zeroD, (double *)PyArray_DATA(ret), 1); } else if (typenum == NPY_FLOAT) { cblas_sgemv(CblasRowMajor, CblasNoTrans, PyArray_DIM(ap2, 0), PyArray_DIM(ap2, 1), 1.0, (float *)PyArray_DATA(ap2), lda, (float *)PyArray_DATA(ap1), 1, 0.0, (float *)PyArray_DATA(ret), 1); } else if (typenum == NPY_CFLOAT) { cblas_cgemv(CblasRowMajor, CblasNoTrans, PyArray_DIM(ap2, 0), PyArray_DIM(ap2, 1), oneF, (float *)PyArray_DATA(ap2), lda, (float *)PyArray_DATA(ap1), 1, zeroF, (float *)PyArray_DATA(ret), 1); } } else { /* (PyArray_NDIM(ap1) == 2 && PyArray_NDIM(ap2) == 2) */ /* Matrix matrix multiplication -- Level 3 BLAS */ lda = (PyArray_DIM(ap1, 1) > 1 ? PyArray_DIM(ap1, 1) : 1); ldb = (PyArray_DIM(ap2, 1) > 1 ? PyArray_DIM(ap2, 1) : 1); ldc = (PyArray_DIM(ret, 1) > 1 ? PyArray_DIM(ret, 1) : 1); if (typenum == NPY_DOUBLE) { cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasTrans, PyArray_DIM(ap1, 0), PyArray_DIM(ap2, 0), PyArray_DIM(ap1, 1), 1.0, (double *)PyArray_DATA(ap1), lda, (double *)PyArray_DATA(ap2), ldb, 0.0, (double *)PyArray_DATA(ret), ldc); } else if (typenum == NPY_FLOAT) { cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasTrans, PyArray_DIM(ap1, 0), PyArray_DIM(ap2, 0), PyArray_DIM(ap1, 1), 1.0, (float *)PyArray_DATA(ap1), lda, (float *)PyArray_DATA(ap2), ldb, 0.0, (float *)PyArray_DATA(ret), ldc); } else if (typenum == NPY_CDOUBLE) { cblas_zgemm(CblasRowMajor, CblasNoTrans, CblasTrans, PyArray_DIM(ap1, 0), PyArray_DIM(ap2, 0), PyArray_DIM(ap1, 1), oneD, (double *)PyArray_DATA(ap1), lda, (double *)PyArray_DATA(ap2), ldb, zeroD, (double *)PyArray_DATA(ret), ldc); } else if (typenum == NPY_CFLOAT) { cblas_cgemm(CblasRowMajor, CblasNoTrans, CblasTrans, PyArray_DIM(ap1, 0), PyArray_DIM(ap2, 0), PyArray_DIM(ap1, 1), oneF, (float *)PyArray_DATA(ap1), lda, (float *)PyArray_DATA(ap2), ldb, zeroF, (float *)PyArray_DATA(ret), ldc); } } NPY_END_ALLOW_THREADS Py_DECREF(ap1); Py_DECREF(ap2); return PyArray_Return(ret); fail: Py_XDECREF(ap1); Py_XDECREF(ap2); Py_XDECREF(ret); return NULL; } /* * vdot(a,b) * * Returns the dot product of a and b for scalars and vectors of * floating point and complex types. The first argument, a, is conjugated. */ static PyObject *dotblas_vdot(PyObject *NPY_UNUSED(dummy), PyObject *args) { PyObject *op1, *op2; PyArrayObject *ap1=NULL, *ap2=NULL, *ret=NULL; int l; int typenum; npy_intp dimensions[NPY_MAXDIMS]; PyArray_Descr *type; if (!PyArg_ParseTuple(args, "OO", &op1, &op2)) return NULL; /* * Conjugating dot product using the BLAS for vectors. * Multiplies op1 and op2, each of which must be vector. */ typenum = PyArray_ObjectType(op1, 0); typenum = PyArray_ObjectType(op2, typenum); type = PyArray_DescrFromType(typenum); Py_INCREF(type); ap1 = (PyArrayObject *)PyArray_FromAny(op1, type, 0, 0, 0, NULL); if (ap1==NULL) {Py_DECREF(type); goto fail;} op1 = PyArray_Flatten(ap1, 0); if (op1==NULL) {Py_DECREF(type); goto fail;} Py_DECREF(ap1); ap1 = (PyArrayObject *)op1; ap2 = (PyArrayObject *)PyArray_FromAny(op2, type, 0, 0, 0, NULL); if (ap2==NULL) goto fail; op2 = PyArray_Flatten(ap2, 0); if (op2 == NULL) goto fail; Py_DECREF(ap2); ap2 = (PyArrayObject *)op2; if (typenum != NPY_FLOAT && typenum != NPY_DOUBLE && typenum != NPY_CFLOAT && typenum != NPY_CDOUBLE) { if (!altered) { /* need to alter dot product */ PyObject *tmp1, *tmp2; tmp1 = PyTuple_New(0); tmp2 = dotblas_alterdot(NULL, tmp1); Py_DECREF(tmp1); Py_DECREF(tmp2); } if (PyTypeNum_ISCOMPLEX(typenum)) { op1 = PyArray_Conjugate(ap1, NULL); if (op1==NULL) goto fail; Py_DECREF(ap1); ap1 = (PyArrayObject *)op1; } ret = (PyArrayObject *)PyArray_InnerProduct((PyObject *)ap1, (PyObject *)ap2); Py_DECREF(ap1); Py_DECREF(ap2); return PyArray_Return(ret); } if (PyArray_DIM(ap2, 0) != PyArray_DIM(ap1, PyArray_NDIM(ap1)-1)) { PyErr_SetString(PyExc_ValueError, "vectors have different lengths"); goto fail; } l = PyArray_DIM(ap1, PyArray_NDIM(ap1)-1); ret = (PyArrayObject *)PyArray_SimpleNew(0, dimensions, typenum); if (ret == NULL) goto fail; NPY_BEGIN_ALLOW_THREADS /* Dot product between two vectors -- Level 1 BLAS */ if (typenum == NPY_DOUBLE) { *((double *)PyArray_DATA(ret)) = cblas_ddot(l, (double *)PyArray_DATA(ap1), 1, (double *)PyArray_DATA(ap2), 1); } else if (typenum == NPY_FLOAT) { *((float *)PyArray_DATA(ret)) = cblas_sdot(l, (float *)PyArray_DATA(ap1), 1, (float *)PyArray_DATA(ap2), 1); } else if (typenum == NPY_CDOUBLE) { cblas_zdotc_sub(l, (double *)PyArray_DATA(ap1), 1, (double *)PyArray_DATA(ap2), 1, (double *)PyArray_DATA(ret)); } else if (typenum == NPY_CFLOAT) { cblas_cdotc_sub(l, (float *)PyArray_DATA(ap1), 1, (float *)PyArray_DATA(ap2), 1, (float *)PyArray_DATA(ret)); } NPY_END_ALLOW_THREADS Py_DECREF(ap1); Py_DECREF(ap2); return PyArray_Return(ret); fail: Py_XDECREF(ap1); Py_XDECREF(ap2); Py_XDECREF(ret); return NULL; } static struct PyMethodDef dotblas_module_methods[] = { {"dot", (PyCFunction)dotblas_matrixproduct, METH_VARARGS|METH_KEYWORDS, NULL}, {"inner", (PyCFunction)dotblas_innerproduct, 1, NULL}, {"vdot", (PyCFunction)dotblas_vdot, 1, NULL}, {"alterdot", (PyCFunction)dotblas_alterdot, 1, NULL}, {"restoredot", (PyCFunction)dotblas_restoredot, 1, NULL}, {NULL, NULL, 0, NULL} /* sentinel */ }; #if defined(NPY_PY3K) static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, "_dotblas", NULL, -1, dotblas_module_methods, NULL, NULL, NULL, NULL }; #endif /* Initialization function for the module */ #if defined(NPY_PY3K) #define RETVAL m PyMODINIT_FUNC PyInit__dotblas(void) #else #define RETVAL PyMODINIT_FUNC init_dotblas(void) #endif { #if defined(NPY_PY3K) int i; PyObject *d, *s, *m; m = PyModule_Create(&moduledef); #else int i; PyObject *d, *s; Py_InitModule3("_dotblas", dotblas_module_methods, module_doc); #endif /* add the functions */ /* Import the array object */ import_array(); /* Initialise the array of dot functions */ for (i = 0; i < NPY_NTYPES; i++) oldFunctions[i] = NULL; /* alterdot at load */ d = PyTuple_New(0); s = dotblas_alterdot(NULL, d); Py_DECREF(d); Py_DECREF(s); return RETVAL; } numpy-1.8.2/numpy/core/blasdot/cblas.h0000664000175100017510000007737412370216242021032 0ustar vagrantvagrant00000000000000#ifndef CBLAS_H #define CBLAS_H #include /* Allow the use in C++ code. */ #ifdef __cplusplus extern "C" { #endif /* * Enumerated and derived types */ #define CBLAS_INDEX size_t /* this may vary between platforms */ enum CBLAS_ORDER {CblasRowMajor=101, CblasColMajor=102}; enum CBLAS_TRANSPOSE {CblasNoTrans=111, CblasTrans=112, CblasConjTrans=113}; enum CBLAS_UPLO {CblasUpper=121, CblasLower=122}; enum CBLAS_DIAG {CblasNonUnit=131, CblasUnit=132}; enum CBLAS_SIDE {CblasLeft=141, CblasRight=142}; /* * =========================================================================== * Prototypes for level 1 BLAS functions (complex are recast as routines) * =========================================================================== */ float cblas_sdsdot(const int N, const float alpha, const float *X, const int incX, const float *Y, const int incY); double cblas_dsdot(const int N, const float *X, const int incX, const float *Y, const int incY); float cblas_sdot(const int N, const float *X, const int incX, const float *Y, const int incY); double cblas_ddot(const int N, const double *X, const int incX, const double *Y, const int incY); /* * Functions having prefixes Z and C only */ void cblas_cdotu_sub(const int N, const void *X, const int incX, const void *Y, const int incY, void *dotu); void cblas_cdotc_sub(const int N, const void *X, const int incX, const void *Y, const int incY, void *dotc); void cblas_zdotu_sub(const int N, const void *X, const int incX, const void *Y, const int incY, void *dotu); void cblas_zdotc_sub(const int N, const void *X, const int incX, const void *Y, const int incY, void *dotc); /* * Functions having prefixes S D SC DZ */ float cblas_snrm2(const int N, const float *X, const int incX); float cblas_sasum(const int N, const float *X, const int incX); double cblas_dnrm2(const int N, const double *X, const int incX); double cblas_dasum(const int N, const double *X, const int incX); float cblas_scnrm2(const int N, const void *X, const int incX); float cblas_scasum(const int N, const void *X, const int incX); double cblas_dznrm2(const int N, const void *X, const int incX); double cblas_dzasum(const int N, const void *X, const int incX); /* * Functions having standard 4 prefixes (S D C Z) */ CBLAS_INDEX cblas_isamax(const int N, const float *X, const int incX); CBLAS_INDEX cblas_idamax(const int N, const double *X, const int incX); CBLAS_INDEX cblas_icamax(const int N, const void *X, const int incX); CBLAS_INDEX cblas_izamax(const int N, const void *X, const int incX); /* * =========================================================================== * Prototypes for level 1 BLAS routines * =========================================================================== */ /* * Routines with standard 4 prefixes (s, d, c, z) */ void cblas_sswap(const int N, float *X, const int incX, float *Y, const int incY); void cblas_scopy(const int N, const float *X, const int incX, float *Y, const int incY); void cblas_saxpy(const int N, const float alpha, const float *X, const int incX, float *Y, const int incY); void cblas_dswap(const int N, double *X, const int incX, double *Y, const int incY); void cblas_dcopy(const int N, const double *X, const int incX, double *Y, const int incY); void cblas_daxpy(const int N, const double alpha, const double *X, const int incX, double *Y, const int incY); void cblas_cswap(const int N, void *X, const int incX, void *Y, const int incY); void cblas_ccopy(const int N, const void *X, const int incX, void *Y, const int incY); void cblas_caxpy(const int N, const void *alpha, const void *X, const int incX, void *Y, const int incY); void cblas_zswap(const int N, void *X, const int incX, void *Y, const int incY); void cblas_zcopy(const int N, const void *X, const int incX, void *Y, const int incY); void cblas_zaxpy(const int N, const void *alpha, const void *X, const int incX, void *Y, const int incY); /* * Routines with S and D prefix only */ void cblas_srotg(float *a, float *b, float *c, float *s); void cblas_srotmg(float *d1, float *d2, float *b1, const float b2, float *P); void cblas_srot(const int N, float *X, const int incX, float *Y, const int incY, const float c, const float s); void cblas_srotm(const int N, float *X, const int incX, float *Y, const int incY, const float *P); void cblas_drotg(double *a, double *b, double *c, double *s); void cblas_drotmg(double *d1, double *d2, double *b1, const double b2, double *P); void cblas_drot(const int N, double *X, const int incX, double *Y, const int incY, const double c, const double s); void cblas_drotm(const int N, double *X, const int incX, double *Y, const int incY, const double *P); /* * Routines with S D C Z CS and ZD prefixes */ void cblas_sscal(const int N, const float alpha, float *X, const int incX); void cblas_dscal(const int N, const double alpha, double *X, const int incX); void cblas_cscal(const int N, const void *alpha, void *X, const int incX); void cblas_zscal(const int N, const void *alpha, void *X, const int incX); void cblas_csscal(const int N, const float alpha, void *X, const int incX); void cblas_zdscal(const int N, const double alpha, void *X, const int incX); /* * =========================================================================== * Prototypes for level 2 BLAS * =========================================================================== */ /* * Routines with standard 4 prefixes (S, D, C, Z) */ void cblas_sgemv(const enum CBLAS_ORDER order, const enum CBLAS_TRANSPOSE TransA, const int M, const int N, const float alpha, const float *A, const int lda, const float *X, const int incX, const float beta, float *Y, const int incY); void cblas_sgbmv(const enum CBLAS_ORDER order, const enum CBLAS_TRANSPOSE TransA, const int M, const int N, const int KL, const int KU, const float alpha, const float *A, const int lda, const float *X, const int incX, const float beta, float *Y, const int incY); void cblas_strmv(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_DIAG Diag, const int N, const float *A, const int lda, float *X, const int incX); void cblas_stbmv(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_DIAG Diag, const int N, const int K, const float *A, const int lda, float *X, const int incX); void cblas_stpmv(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_DIAG Diag, const int N, const float *Ap, float *X, const int incX); void cblas_strsv(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_DIAG Diag, const int N, const float *A, const int lda, float *X, const int incX); void cblas_stbsv(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_DIAG Diag, const int N, const int K, const float *A, const int lda, float *X, const int incX); void cblas_stpsv(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_DIAG Diag, const int N, const float *Ap, float *X, const int incX); void cblas_dgemv(const enum CBLAS_ORDER order, const enum CBLAS_TRANSPOSE TransA, const int M, const int N, const double alpha, const double *A, const int lda, const double *X, const int incX, const double beta, double *Y, const int incY); void cblas_dgbmv(const enum CBLAS_ORDER order, const enum CBLAS_TRANSPOSE TransA, const int M, const int N, const int KL, const int KU, const double alpha, const double *A, const int lda, const double *X, const int incX, const double beta, double *Y, const int incY); void cblas_dtrmv(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_DIAG Diag, const int N, const double *A, const int lda, double *X, const int incX); void cblas_dtbmv(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_DIAG Diag, const int N, const int K, const double *A, const int lda, double *X, const int incX); void cblas_dtpmv(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_DIAG Diag, const int N, const double *Ap, double *X, const int incX); void cblas_dtrsv(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_DIAG Diag, const int N, const double *A, const int lda, double *X, const int incX); void cblas_dtbsv(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_DIAG Diag, const int N, const int K, const double *A, const int lda, double *X, const int incX); void cblas_dtpsv(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_DIAG Diag, const int N, const double *Ap, double *X, const int incX); void cblas_cgemv(const enum CBLAS_ORDER order, const enum CBLAS_TRANSPOSE TransA, const int M, const int N, const void *alpha, const void *A, const int lda, const void *X, const int incX, const void *beta, void *Y, const int incY); void cblas_cgbmv(const enum CBLAS_ORDER order, const enum CBLAS_TRANSPOSE TransA, const int M, const int N, const int KL, const int KU, const void *alpha, const void *A, const int lda, const void *X, const int incX, const void *beta, void *Y, const int incY); void cblas_ctrmv(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_DIAG Diag, const int N, const void *A, const int lda, void *X, const int incX); void cblas_ctbmv(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_DIAG Diag, const int N, const int K, const void *A, const int lda, void *X, const int incX); void cblas_ctpmv(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_DIAG Diag, const int N, const void *Ap, void *X, const int incX); void cblas_ctrsv(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_DIAG Diag, const int N, const void *A, const int lda, void *X, const int incX); void cblas_ctbsv(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_DIAG Diag, const int N, const int K, const void *A, const int lda, void *X, const int incX); void cblas_ctpsv(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_DIAG Diag, const int N, const void *Ap, void *X, const int incX); void cblas_zgemv(const enum CBLAS_ORDER order, const enum CBLAS_TRANSPOSE TransA, const int M, const int N, const void *alpha, const void *A, const int lda, const void *X, const int incX, const void *beta, void *Y, const int incY); void cblas_zgbmv(const enum CBLAS_ORDER order, const enum CBLAS_TRANSPOSE TransA, const int M, const int N, const int KL, const int KU, const void *alpha, const void *A, const int lda, const void *X, const int incX, const void *beta, void *Y, const int incY); void cblas_ztrmv(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_DIAG Diag, const int N, const void *A, const int lda, void *X, const int incX); void cblas_ztbmv(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_DIAG Diag, const int N, const int K, const void *A, const int lda, void *X, const int incX); void cblas_ztpmv(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_DIAG Diag, const int N, const void *Ap, void *X, const int incX); void cblas_ztrsv(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_DIAG Diag, const int N, const void *A, const int lda, void *X, const int incX); void cblas_ztbsv(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_DIAG Diag, const int N, const int K, const void *A, const int lda, void *X, const int incX); void cblas_ztpsv(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_DIAG Diag, const int N, const void *Ap, void *X, const int incX); /* * Routines with S and D prefixes only */ void cblas_ssymv(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo, const int N, const float alpha, const float *A, const int lda, const float *X, const int incX, const float beta, float *Y, const int incY); void cblas_ssbmv(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo, const int N, const int K, const float alpha, const float *A, const int lda, const float *X, const int incX, const float beta, float *Y, const int incY); void cblas_sspmv(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo, const int N, const float alpha, const float *Ap, const float *X, const int incX, const float beta, float *Y, const int incY); void cblas_sger(const enum CBLAS_ORDER order, const int M, const int N, const float alpha, const float *X, const int incX, const float *Y, const int incY, float *A, const int lda); void cblas_ssyr(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo, const int N, const float alpha, const float *X, const int incX, float *A, const int lda); void cblas_sspr(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo, const int N, const float alpha, const float *X, const int incX, float *Ap); void cblas_ssyr2(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo, const int N, const float alpha, const float *X, const int incX, const float *Y, const int incY, float *A, const int lda); void cblas_sspr2(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo, const int N, const float alpha, const float *X, const int incX, const float *Y, const int incY, float *A); void cblas_dsymv(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo, const int N, const double alpha, const double *A, const int lda, const double *X, const int incX, const double beta, double *Y, const int incY); void cblas_dsbmv(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo, const int N, const int K, const double alpha, const double *A, const int lda, const double *X, const int incX, const double beta, double *Y, const int incY); void cblas_dspmv(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo, const int N, const double alpha, const double *Ap, const double *X, const int incX, const double beta, double *Y, const int incY); void cblas_dger(const enum CBLAS_ORDER order, const int M, const int N, const double alpha, const double *X, const int incX, const double *Y, const int incY, double *A, const int lda); void cblas_dsyr(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo, const int N, const double alpha, const double *X, const int incX, double *A, const int lda); void cblas_dspr(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo, const int N, const double alpha, const double *X, const int incX, double *Ap); void cblas_dsyr2(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo, const int N, const double alpha, const double *X, const int incX, const double *Y, const int incY, double *A, const int lda); void cblas_dspr2(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo, const int N, const double alpha, const double *X, const int incX, const double *Y, const int incY, double *A); /* * Routines with C and Z prefixes only */ void cblas_chemv(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo, const int N, const void *alpha, const void *A, const int lda, const void *X, const int incX, const void *beta, void *Y, const int incY); void cblas_chbmv(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo, const int N, const int K, const void *alpha, const void *A, const int lda, const void *X, const int incX, const void *beta, void *Y, const int incY); void cblas_chpmv(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo, const int N, const void *alpha, const void *Ap, const void *X, const int incX, const void *beta, void *Y, const int incY); void cblas_cgeru(const enum CBLAS_ORDER order, const int M, const int N, const void *alpha, const void *X, const int incX, const void *Y, const int incY, void *A, const int lda); void cblas_cgerc(const enum CBLAS_ORDER order, const int M, const int N, const void *alpha, const void *X, const int incX, const void *Y, const int incY, void *A, const int lda); void cblas_cher(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo, const int N, const float alpha, const void *X, const int incX, void *A, const int lda); void cblas_chpr(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo, const int N, const float alpha, const void *X, const int incX, void *A); void cblas_cher2(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo, const int N, const void *alpha, const void *X, const int incX, const void *Y, const int incY, void *A, const int lda); void cblas_chpr2(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo, const int N, const void *alpha, const void *X, const int incX, const void *Y, const int incY, void *Ap); void cblas_zhemv(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo, const int N, const void *alpha, const void *A, const int lda, const void *X, const int incX, const void *beta, void *Y, const int incY); void cblas_zhbmv(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo, const int N, const int K, const void *alpha, const void *A, const int lda, const void *X, const int incX, const void *beta, void *Y, const int incY); void cblas_zhpmv(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo, const int N, const void *alpha, const void *Ap, const void *X, const int incX, const void *beta, void *Y, const int incY); void cblas_zgeru(const enum CBLAS_ORDER order, const int M, const int N, const void *alpha, const void *X, const int incX, const void *Y, const int incY, void *A, const int lda); void cblas_zgerc(const enum CBLAS_ORDER order, const int M, const int N, const void *alpha, const void *X, const int incX, const void *Y, const int incY, void *A, const int lda); void cblas_zher(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo, const int N, const double alpha, const void *X, const int incX, void *A, const int lda); void cblas_zhpr(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo, const int N, const double alpha, const void *X, const int incX, void *A); void cblas_zher2(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo, const int N, const void *alpha, const void *X, const int incX, const void *Y, const int incY, void *A, const int lda); void cblas_zhpr2(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo, const int N, const void *alpha, const void *X, const int incX, const void *Y, const int incY, void *Ap); /* * =========================================================================== * Prototypes for level 3 BLAS * =========================================================================== */ /* * Routines with standard 4 prefixes (S, D, C, Z) */ void cblas_sgemm(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_TRANSPOSE TransB, const int M, const int N, const int K, const float alpha, const float *A, const int lda, const float *B, const int ldb, const float beta, float *C, const int ldc); void cblas_ssymm(const enum CBLAS_ORDER Order, const enum CBLAS_SIDE Side, const enum CBLAS_UPLO Uplo, const int M, const int N, const float alpha, const float *A, const int lda, const float *B, const int ldb, const float beta, float *C, const int ldc); void cblas_ssyrk(const enum CBLAS_ORDER Order, const enum CBLAS_UPLO Uplo, const enum CBLAS_TRANSPOSE Trans, const int N, const int K, const float alpha, const float *A, const int lda, const float beta, float *C, const int ldc); void cblas_ssyr2k(const enum CBLAS_ORDER Order, const enum CBLAS_UPLO Uplo, const enum CBLAS_TRANSPOSE Trans, const int N, const int K, const float alpha, const float *A, const int lda, const float *B, const int ldb, const float beta, float *C, const int ldc); void cblas_strmm(const enum CBLAS_ORDER Order, const enum CBLAS_SIDE Side, const enum CBLAS_UPLO Uplo, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_DIAG Diag, const int M, const int N, const float alpha, const float *A, const int lda, float *B, const int ldb); void cblas_strsm(const enum CBLAS_ORDER Order, const enum CBLAS_SIDE Side, const enum CBLAS_UPLO Uplo, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_DIAG Diag, const int M, const int N, const float alpha, const float *A, const int lda, float *B, const int ldb); void cblas_dgemm(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_TRANSPOSE TransB, const int M, const int N, const int K, const double alpha, const double *A, const int lda, const double *B, const int ldb, const double beta, double *C, const int ldc); void cblas_dsymm(const enum CBLAS_ORDER Order, const enum CBLAS_SIDE Side, const enum CBLAS_UPLO Uplo, const int M, const int N, const double alpha, const double *A, const int lda, const double *B, const int ldb, const double beta, double *C, const int ldc); void cblas_dsyrk(const enum CBLAS_ORDER Order, const enum CBLAS_UPLO Uplo, const enum CBLAS_TRANSPOSE Trans, const int N, const int K, const double alpha, const double *A, const int lda, const double beta, double *C, const int ldc); void cblas_dsyr2k(const enum CBLAS_ORDER Order, const enum CBLAS_UPLO Uplo, const enum CBLAS_TRANSPOSE Trans, const int N, const int K, const double alpha, const double *A, const int lda, const double *B, const int ldb, const double beta, double *C, const int ldc); void cblas_dtrmm(const enum CBLAS_ORDER Order, const enum CBLAS_SIDE Side, const enum CBLAS_UPLO Uplo, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_DIAG Diag, const int M, const int N, const double alpha, const double *A, const int lda, double *B, const int ldb); void cblas_dtrsm(const enum CBLAS_ORDER Order, const enum CBLAS_SIDE Side, const enum CBLAS_UPLO Uplo, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_DIAG Diag, const int M, const int N, const double alpha, const double *A, const int lda, double *B, const int ldb); void cblas_cgemm(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_TRANSPOSE TransB, const int M, const int N, const int K, const void *alpha, const void *A, const int lda, const void *B, const int ldb, const void *beta, void *C, const int ldc); void cblas_csymm(const enum CBLAS_ORDER Order, const enum CBLAS_SIDE Side, const enum CBLAS_UPLO Uplo, const int M, const int N, const void *alpha, const void *A, const int lda, const void *B, const int ldb, const void *beta, void *C, const int ldc); void cblas_csyrk(const enum CBLAS_ORDER Order, const enum CBLAS_UPLO Uplo, const enum CBLAS_TRANSPOSE Trans, const int N, const int K, const void *alpha, const void *A, const int lda, const void *beta, void *C, const int ldc); void cblas_csyr2k(const enum CBLAS_ORDER Order, const enum CBLAS_UPLO Uplo, const enum CBLAS_TRANSPOSE Trans, const int N, const int K, const void *alpha, const void *A, const int lda, const void *B, const int ldb, const void *beta, void *C, const int ldc); void cblas_ctrmm(const enum CBLAS_ORDER Order, const enum CBLAS_SIDE Side, const enum CBLAS_UPLO Uplo, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_DIAG Diag, const int M, const int N, const void *alpha, const void *A, const int lda, void *B, const int ldb); void cblas_ctrsm(const enum CBLAS_ORDER Order, const enum CBLAS_SIDE Side, const enum CBLAS_UPLO Uplo, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_DIAG Diag, const int M, const int N, const void *alpha, const void *A, const int lda, void *B, const int ldb); void cblas_zgemm(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_TRANSPOSE TransB, const int M, const int N, const int K, const void *alpha, const void *A, const int lda, const void *B, const int ldb, const void *beta, void *C, const int ldc); void cblas_zsymm(const enum CBLAS_ORDER Order, const enum CBLAS_SIDE Side, const enum CBLAS_UPLO Uplo, const int M, const int N, const void *alpha, const void *A, const int lda, const void *B, const int ldb, const void *beta, void *C, const int ldc); void cblas_zsyrk(const enum CBLAS_ORDER Order, const enum CBLAS_UPLO Uplo, const enum CBLAS_TRANSPOSE Trans, const int N, const int K, const void *alpha, const void *A, const int lda, const void *beta, void *C, const int ldc); void cblas_zsyr2k(const enum CBLAS_ORDER Order, const enum CBLAS_UPLO Uplo, const enum CBLAS_TRANSPOSE Trans, const int N, const int K, const void *alpha, const void *A, const int lda, const void *B, const int ldb, const void *beta, void *C, const int ldc); void cblas_ztrmm(const enum CBLAS_ORDER Order, const enum CBLAS_SIDE Side, const enum CBLAS_UPLO Uplo, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_DIAG Diag, const int M, const int N, const void *alpha, const void *A, const int lda, void *B, const int ldb); void cblas_ztrsm(const enum CBLAS_ORDER Order, const enum CBLAS_SIDE Side, const enum CBLAS_UPLO Uplo, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_DIAG Diag, const int M, const int N, const void *alpha, const void *A, const int lda, void *B, const int ldb); /* * Routines with prefixes C and Z only */ void cblas_chemm(const enum CBLAS_ORDER Order, const enum CBLAS_SIDE Side, const enum CBLAS_UPLO Uplo, const int M, const int N, const void *alpha, const void *A, const int lda, const void *B, const int ldb, const void *beta, void *C, const int ldc); void cblas_cherk(const enum CBLAS_ORDER Order, const enum CBLAS_UPLO Uplo, const enum CBLAS_TRANSPOSE Trans, const int N, const int K, const float alpha, const void *A, const int lda, const float beta, void *C, const int ldc); void cblas_cher2k(const enum CBLAS_ORDER Order, const enum CBLAS_UPLO Uplo, const enum CBLAS_TRANSPOSE Trans, const int N, const int K, const void *alpha, const void *A, const int lda, const void *B, const int ldb, const float beta, void *C, const int ldc); void cblas_zhemm(const enum CBLAS_ORDER Order, const enum CBLAS_SIDE Side, const enum CBLAS_UPLO Uplo, const int M, const int N, const void *alpha, const void *A, const int lda, const void *B, const int ldb, const void *beta, void *C, const int ldc); void cblas_zherk(const enum CBLAS_ORDER Order, const enum CBLAS_UPLO Uplo, const enum CBLAS_TRANSPOSE Trans, const int N, const int K, const double alpha, const void *A, const int lda, const double beta, void *C, const int ldc); void cblas_zher2k(const enum CBLAS_ORDER Order, const enum CBLAS_UPLO Uplo, const enum CBLAS_TRANSPOSE Trans, const int N, const int K, const void *alpha, const void *A, const int lda, const void *B, const int ldb, const double beta, void *C, const int ldc); void cblas_xerbla(int p, const char *rout, const char *form, ...); #ifdef __cplusplus } #endif #endif numpy-1.8.2/numpy/core/npymath.ini.in0000664000175100017510000000055712370216242020720 0ustar vagrantvagrant00000000000000[meta] Name=npymath Description=Portable, core math library implementing C99 standard Version=0.1 [variables] pkgname=@pkgname@ prefix=${pkgdir} libdir=${prefix}@sep@lib includedir=${prefix}@sep@include [default] Libs=-L${libdir} -lnpymath Cflags=-I${includedir} Requires=mlib [msvc] Libs=/LIBPATH:${libdir} npymath.lib Cflags=/INCLUDE:${includedir} Requires=mlib numpy-1.8.2/numpy/core/src/0000775000175100017510000000000012371375427016726 5ustar vagrantvagrant00000000000000numpy-1.8.2/numpy/core/src/dummymodule.c0000664000175100017510000000151112370216243021416 0ustar vagrantvagrant00000000000000/* -*- c -*- */ /* * This is a dummy module whose purpose is to get distutils to generate the * configuration files before the libraries are made. */ #define NPY_NO_DEPRECATED_API NPY_API_VERSION #include #include static struct PyMethodDef methods[] = { {NULL, NULL, 0, NULL} }; #if defined(NPY_PY3K) static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, "dummy", NULL, -1, methods, NULL, NULL, NULL, NULL }; #endif /* Initialization function for the module */ #if defined(NPY_PY3K) PyMODINIT_FUNC PyInit__dummy(void) { PyObject *m; m = PyModule_Create(&moduledef); if (!m) { return NULL; } return m; } #else PyMODINIT_FUNC init_dummy(void) { Py_InitModule("_dummy", methods); } #endif numpy-1.8.2/numpy/core/src/scalarmathmodule.c.src0000664000175100017510000015412612370216242023202 0ustar vagrantvagrant00000000000000/* -*- c -*- */ /* The purpose of this module is to add faster math for array scalars that does not go through the ufunc machinery but still supports error-modes. */ #define NPY_NO_DEPRECATED_API NPY_API_VERSION #include "Python.h" #include "numpy/arrayobject.h" #include "numpy/ufuncobject.h" #include "numpy/arrayscalars.h" #include "npy_pycompat.h" #include "numpy/halffloat.h" #include "scalarmathmodule.h" /* Basic operations: * * BINARY: * * add, subtract, multiply, divide, remainder, divmod, power, * floor_divide, true_divide * * lshift, rshift, and, or, xor (integers only) * * UNARY: * * negative, positive, absolute, nonzero, invert, int, long, float, oct, hex * */ /**begin repeat * #name = byte, short, int, long, longlong# * #type = npy_byte, npy_short, npy_int, npy_long, npy_longlong# */ static void @name@_ctype_add(@type@ a, @type@ b, @type@ *out) { *out = a + b; if ((*out^a) >= 0 || (*out^b) >= 0) { return; } npy_set_floatstatus_overflow(); return; } static void @name@_ctype_subtract(@type@ a, @type@ b, @type@ *out) { *out = a - b; if ((*out^a) >= 0 || (*out^~b) >= 0) { return; } npy_set_floatstatus_overflow(); return; } /**end repeat**/ /**begin repeat * #name = ubyte, ushort, uint, ulong, ulonglong# * #type = npy_ubyte, npy_ushort, npy_uint, npy_ulong, npy_ulonglong# */ static void @name@_ctype_add(@type@ a, @type@ b, @type@ *out) { *out = a + b; if (*out >= a && *out >= b) { return; } npy_set_floatstatus_overflow(); return; } static void @name@_ctype_subtract(@type@ a, @type@ b, @type@ *out) { *out = a - b; if (a >= b) { return; } npy_set_floatstatus_overflow(); return; } /**end repeat**/ #ifndef NPY_SIZEOF_BYTE #define NPY_SIZEOF_BYTE 1 #endif /**begin repeat * * #name = byte, ubyte, short, ushort, * int, uint, long, ulong# * #type = npy_byte, npy_ubyte, npy_short, npy_ushort, * npy_int, npy_uint, npy_long, npy_ulong# * #big = npy_int, npy_uint, npy_int, npy_uint, * npy_longlong, npy_ulonglong, npy_longlong, npy_ulonglong# * #NAME = BYTE, UBYTE, SHORT, USHORT, * INT, UINT, LONG, ULONG# * #SIZENAME = BYTE*2, SHORT*2, INT*2, LONG*2# * #SIZE = INT*4,LONGLONG*4# * #neg = (1,0)*4# */ #if NPY_SIZEOF_@SIZE@ > NPY_SIZEOF_@SIZENAME@ static void @name@_ctype_multiply(@type@ a, @type@ b, @type@ *out) { @big@ temp; temp = ((@big@) a) * ((@big@) b); *out = (@type@) temp; #if @neg@ if (temp > NPY_MAX_@NAME@ || temp < NPY_MIN_@NAME@) #else if (temp > NPY_MAX_@NAME@) #endif npy_set_floatstatus_overflow(); return; } #endif /**end repeat**/ /**begin repeat * * #name = int, uint, long, ulong, * longlong, ulonglong# * #type = npy_int, npy_uint, npy_long, npy_ulong, * npy_longlong, npy_ulonglong# * #SIZE = INT*2, LONG*2, LONGLONG*2# */ #if NPY_SIZEOF_LONGLONG == NPY_SIZEOF_@SIZE@ static void @name@_ctype_multiply(@type@ a, @type@ b, @type@ *out) { if (npy_mul_with_overflow_@name@(out, a, b)) { npy_set_floatstatus_overflow(); } return; } #endif /**end repeat**/ /**begin repeat * * #name = byte, ubyte, short, ushort, int, uint, * long, ulong, longlong, ulonglong# * #type = npy_byte, npy_ubyte, npy_short, npy_ushort, npy_int, npy_uint, * npy_long, npy_ulong, npy_longlong, npy_ulonglong# * #neg = (1,0)*5# */ static void @name@_ctype_divide(@type@ a, @type@ b, @type@ *out) { if (b == 0) { npy_set_floatstatus_divbyzero(); *out = 0; } #if @neg@ else if (b == -1 && a < 0 && a == -a) { npy_set_floatstatus_overflow(); *out = a / b; } #endif else { #if @neg@ @type@ tmp; tmp = a / b; if (((a > 0) != (b > 0)) && (a % b != 0)) { tmp--; } *out = tmp; #else *out = a / b; #endif } } #define @name@_ctype_floor_divide @name@_ctype_divide static void @name@_ctype_remainder(@type@ a, @type@ b, @type@ *out) { if (a == 0 || b == 0) { if (b == 0) npy_set_floatstatus_divbyzero(); *out = 0; return; } #if @neg@ else if ((a > 0) == (b > 0)) { *out = a % b; } else { /* handled like Python does */ *out = a % b; if (*out) *out += b; } #else *out = a % b; #endif } /**end repeat**/ /**begin repeat * * #name = byte, ubyte, short, ushort, int, uint, long, * ulong, longlong, ulonglong# * #otyp = npy_float*4, npy_double*6# */ #define @name@_ctype_true_divide(a, b, out) \ *(out) = ((@otyp@) (a)) / ((@otyp@) (b)); /**end repeat**/ /* b will always be positive in this call */ /**begin repeat * * #name = byte, ubyte, short, ushort, int, uint, * long, ulong, longlong, ulonglong# * #type = npy_byte, npy_ubyte, npy_short, npy_ushort, npy_int, npy_uint, * npy_long, npy_ulong, npy_longlong, npy_ulonglong# * #upc = BYTE, UBYTE, SHORT, USHORT, INT, UINT, * LONG, ULONG, LONGLONG, ULONGLONG# */ static void @name@_ctype_power(@type@ a, @type@ b, @type@ *out) { @type@ temp, ix, mult; /* code from Python's intobject.c, with overflow checking removed. */ temp = a; ix = 1; while (b > 0) { if (b & 1) { @name@_ctype_multiply(ix, temp, &mult); ix = mult; if (temp == 0) { break; } } b >>= 1; /* Shift exponent down by 1 bit */ if (b==0) { break; } /* Square the value of temp */ @name@_ctype_multiply(temp, temp, &mult); temp = mult; } *out = ix; } /**end repeat**/ /* QUESTION: Should we check for overflow / underflow in (l,r)shift? */ /**begin repeat * #name = byte, ubyte, short, ushort, int, uint, * long, ulong, longlong, ulonglong# * #type = npy_byte, npy_ubyte, npy_short, npy_ushort, npy_int, npy_uint, * npy_long, npy_ulong, npy_longlong, npy_ulonglong# */ /**begin repeat1 * #oper = and, xor, or, lshift, rshift# * #op = &, ^, |, <<, >># */ #define @name@_ctype_@oper@(arg1, arg2, out) *(out) = (arg1) @op@ (arg2) /**end repeat1**/ /**end repeat**/ /**begin repeat * #name = float, double, longdouble# * #type = npy_float, npy_double, npy_longdouble# */ static @type@ (*_basic_@name@_floor)(@type@); static @type@ (*_basic_@name@_sqrt)(@type@); static @type@ (*_basic_@name@_fmod)(@type@, @type@); #define @name@_ctype_add(a, b, outp) *(outp) = a + b #define @name@_ctype_subtract(a, b, outp) *(outp) = a - b #define @name@_ctype_multiply(a, b, outp) *(outp) = a * b #define @name@_ctype_divide(a, b, outp) *(outp) = a / b #define @name@_ctype_true_divide @name@_ctype_divide #define @name@_ctype_floor_divide(a, b, outp) \ *(outp) = _basic_@name@_floor((a) / (b)) /**end repeat**/ static npy_half (*_basic_half_floor)(npy_half); static npy_half (*_basic_half_sqrt)(npy_half); static npy_half (*_basic_half_fmod)(npy_half, npy_half); #define half_ctype_add(a, b, outp) *(outp) = \ npy_float_to_half(npy_half_to_float(a) + npy_half_to_float(b)) #define half_ctype_subtract(a, b, outp) *(outp) = \ npy_float_to_half(npy_half_to_float(a) - npy_half_to_float(b)) #define half_ctype_multiply(a, b, outp) *(outp) = \ npy_float_to_half(npy_half_to_float(a) * npy_half_to_float(b)) #define half_ctype_divide(a, b, outp) *(outp) = \ npy_float_to_half(npy_half_to_float(a) / npy_half_to_float(b)) #define half_ctype_true_divide half_ctype_divide #define half_ctype_floor_divide(a, b, outp) \ *(outp) = npy_float_to_half(_basic_float_floor(npy_half_to_float(a) / \ npy_half_to_float(b))) /**begin repeat * #name = cfloat, cdouble, clongdouble# * #rname = float, double, longdouble# * #rtype = npy_float, npy_double, npy_longdouble# * #c = f,,l# */ #define @name@_ctype_add(a, b, outp) do{ \ (outp)->real = (a).real + (b).real; \ (outp)->imag = (a).imag + (b).imag; \ } while(0) #define @name@_ctype_subtract(a, b, outp) do{ \ (outp)->real = (a).real - (b).real; \ (outp)->imag = (a).imag - (b).imag; \ } while(0) #define @name@_ctype_multiply(a, b, outp) do{ \ (outp)->real = (a).real * (b).real - (a).imag * (b).imag; \ (outp)->imag = (a).real * (b).imag + (a).imag * (b).real; \ } while(0) /* Note: complex division by zero must yield some complex inf */ #define @name@_ctype_divide(a, b, outp) do{ \ @rtype@ d = (b).real*(b).real + (b).imag*(b).imag; \ if (d != 0) { \ (outp)->real = ((a).real*(b).real + (a).imag*(b).imag)/d; \ (outp)->imag = ((a).imag*(b).real - (a).real*(b).imag)/d; \ } \ else { \ (outp)->real = (a).real/d; \ (outp)->imag = (a).imag/d; \ } \ } while(0) #define @name@_ctype_true_divide @name@_ctype_divide #define @name@_ctype_floor_divide(a, b, outp) do { \ (outp)->real = _basic_@rname@_floor \ (((a).real*(b).real + (a).imag*(b).imag) / \ ((b).real*(b).real + (b).imag*(b).imag)); \ (outp)->imag = 0; \ } while(0) /**end repeat**/ /**begin repeat * #name = float, double, longdouble# * #type = npy_float, npy_double, npy_longdouble# */ static void @name@_ctype_remainder(@type@ a, @type@ b, @type@ *out) { @type@ mod; mod = _basic_@name@_fmod(a, b); if (mod && (((b < 0) != (mod < 0)))) { mod += b; } *out = mod; } /**end repeat**/ static void half_ctype_remainder(npy_half a, npy_half b, npy_half *out) { float mod, fa = npy_half_to_float(a), fb = npy_half_to_float(b); mod = _basic_float_fmod(fa, fb); if (mod && (((fb < 0) != (mod < 0)))) { mod += fb; } *out = npy_float_to_half(mod); } /**begin repeat * #name = byte, ubyte, short, ushort, int, uint, long, ulong, * longlong, ulonglong, half, float, double, longdouble, * cfloat, cdouble, clongdouble# */ #define @name@_ctype_divmod(a, b, out, out2) { \ @name@_ctype_floor_divide(a, b, out); \ @name@_ctype_remainder(a, b, out2); \ } /**end repeat**/ /**begin repeat * #name = float, double, longdouble# * #type = npy_float, npy_double, npy_longdouble# */ static npy_@name@ (*_basic_@name@_pow)(@type@ a, @type@ b); static void @name@_ctype_power(@type@ a, @type@ b, @type@ *out) { *out = _basic_@name@_pow(a, b); } /**end repeat**/ static void half_ctype_power(npy_half a, npy_half b, npy_half *out) { const npy_float af = npy_half_to_float(a); const npy_float bf = npy_half_to_float(b); const npy_float outf = _basic_float_pow(af,bf); *out = npy_float_to_half(outf); } /**begin repeat * #name = byte, ubyte, short, ushort, int, uint, * long, ulong, longlong, ulonglong, * float, double, longdouble# * #type = npy_byte, npy_ubyte, npy_short, npy_ushort, npy_int, npy_uint, * npy_long, npy_ulong, npy_longlong, npy_ulonglong, * npy_float, npy_double, npy_longdouble# * #uns = (0,1)*5,0*3# */ static void @name@_ctype_negative(@type@ a, @type@ *out) { #if @uns@ npy_set_floatstatus_overflow(); #endif *out = -a; } /**end repeat**/ static void half_ctype_negative(npy_half a, npy_half *out) { *out = a^0x8000u; } /**begin repeat * #name = cfloat, cdouble, clongdouble# * #type = npy_cfloat, npy_cdouble, npy_clongdouble# */ static void @name@_ctype_negative(@type@ a, @type@ *out) { out->real = -a.real; out->imag = -a.imag; } /**end repeat**/ /**begin repeat * #name = byte, ubyte, short, ushort, int, uint, * long, ulong, longlong, ulonglong, * half, float, double, longdouble# * #type = npy_byte, npy_ubyte, npy_short, npy_ushort, npy_int, npy_uint, * npy_long, npy_ulong, npy_longlong, npy_ulonglong, * npy_half, npy_float, npy_double, npy_longdouble# */ static void @name@_ctype_positive(@type@ a, @type@ *out) { *out = a; } /**end repeat**/ /* * Get the nc_powf, nc_pow, and nc_powl functions from * the data area of the power ufunc in umathmodule. */ /**begin repeat * #name = cfloat, cdouble, clongdouble# * #type = npy_cfloat, npy_cdouble, npy_clongdouble# */ static void @name@_ctype_positive(@type@ a, @type@ *out) { out->real = a.real; out->imag = a.imag; } static void (*_basic_@name@_pow)(@type@ *, @type@ *, @type@ *); static void @name@_ctype_power(@type@ a, @type@ b, @type@ *out) { _basic_@name@_pow(&a, &b, out); } /**end repeat**/ /**begin repeat * #name = ubyte, ushort, uint, ulong, ulonglong# */ #define @name@_ctype_absolute @name@_ctype_positive /**end repeat**/ /**begin repeat * #name = byte, short, int, long, longlong, * float, double, longdouble# * #type = npy_byte, npy_short, npy_int, npy_long, npy_longlong, * npy_float, npy_double, npy_longdouble# */ static void @name@_ctype_absolute(@type@ a, @type@ *out) { *out = (a < 0 ? -a : a); } /**end repeat**/ static void half_ctype_absolute(npy_half a, npy_half *out) { *out = a&0x7fffu; } /**begin repeat * #name = cfloat, cdouble, clongdouble# * #type = npy_cfloat, npy_cdouble, npy_clongdouble# * #rname = float, double, longdouble# * #rtype = npy_float, npy_double, npy_longdouble# */ static void @name@_ctype_absolute(@type@ a, @rtype@ *out) { *out = _basic_@rname@_sqrt(a.real*a.real + a.imag*a.imag); } /**end repeat**/ /**begin repeat * #name = byte, ubyte, short, ushort, int, uint, long, * ulong, longlong, ulonglong# */ #define @name@_ctype_invert(a, out) *(out) = ~a; /**end repeat**/ /*** END OF BASIC CODE **/ /* The general strategy for commutative binary operators is to * * 1) Convert the types to the common type if both are scalars (0 return) * 2) If both are not scalars use ufunc machinery (-2 return) * 3) If both are scalars but cannot be cast to the right type * return NotImplmented (-1 return) * * 4) Perform the function on the C-type. * 5) If an error condition occurred, check to see * what the current error-handling is and handle the error. * * 6) Construct and return the output scalar. */ /**begin repeat * #name = byte, ubyte, short, ushort, int, uint, * long, ulong, longlong, ulonglong, * half, float, longdouble, * cfloat, cdouble, clongdouble# * #type = npy_byte, npy_ubyte, npy_short, npy_ushort, npy_int, npy_uint, * npy_long, npy_ulong, npy_longlong, npy_ulonglong, * npy_half, npy_float, npy_longdouble, * npy_cfloat, npy_cdouble, npy_clongdouble# * #Name = Byte, UByte, Short, UShort, Int, UInt, * Long, ULong, LongLong, ULongLong, * Half, Float, LongDouble, * CFloat, CDouble, CLongDouble# * #TYPE = NPY_BYTE, NPY_UBYTE, NPY_SHORT, NPY_USHORT, NPY_INT, NPY_UINT, * NPY_LONG, NPY_ULONG, NPY_LONGLONG, NPY_ULONGLONG, * NPY_HALF, NPY_FLOAT, NPY_LONGDOUBLE, * NPY_CFLOAT, NPY_CDOUBLE, NPY_CLONGDOUBLE# */ static int _@name@_convert_to_ctype(PyObject *a, @type@ *arg1) { PyObject *temp; if (PyArray_IsScalar(a, @Name@)) { *arg1 = PyArrayScalar_VAL(a, @Name@); return 0; } else if (PyArray_IsScalar(a, Generic)) { PyArray_Descr *descr1; if (!PyArray_IsScalar(a, Number)) { return -1; } descr1 = PyArray_DescrFromTypeObject((PyObject *)Py_TYPE(a)); if (PyArray_CanCastSafely(descr1->type_num, @TYPE@)) { PyArray_CastScalarDirect(a, descr1, arg1, @TYPE@); Py_DECREF(descr1); return 0; } else { Py_DECREF(descr1); return -1; } } else if (PyArray_GetPriority(a, NPY_PRIORITY) > NPY_PRIORITY) { return -2; } else if ((temp = PyArray_ScalarFromObject(a)) != NULL) { int retval = _@name@_convert_to_ctype(temp, arg1); Py_DECREF(temp); return retval; } return -2; } /**end repeat**/ /* Same as above but added exact checks against known python types for speed */ /**begin repeat * #name = double# * #type = npy_double# * #Name = Double# * #TYPE = NPY_DOUBLE# * #PYCHECKEXACT = PyFloat_CheckExact# * #PYEXTRACTCTYPE = PyFloat_AS_DOUBLE# */ static int _@name@_convert_to_ctype(PyObject *a, @type@ *arg1) { PyObject *temp; if (@PYCHECKEXACT@(a)){ *arg1 = @PYEXTRACTCTYPE@(a); return 0; } if (PyArray_IsScalar(a, @Name@)) { *arg1 = PyArrayScalar_VAL(a, @Name@); return 0; } else if (PyArray_IsScalar(a, Generic)) { PyArray_Descr *descr1; if (!PyArray_IsScalar(a, Number)) { return -1; } descr1 = PyArray_DescrFromTypeObject((PyObject *)Py_TYPE(a)); if (PyArray_CanCastSafely(descr1->type_num, @TYPE@)) { PyArray_CastScalarDirect(a, descr1, arg1, @TYPE@); Py_DECREF(descr1); return 0; } else { Py_DECREF(descr1); return -1; } } else if (PyArray_GetPriority(a, NPY_PRIORITY) > NPY_PRIORITY) { return -2; } else if ((temp = PyArray_ScalarFromObject(a)) != NULL) { int retval = _@name@_convert_to_ctype(temp, arg1); Py_DECREF(temp); return retval; } return -2; } /**end repeat**/ /**begin repeat * #name = byte, ubyte, short, ushort, int, uint, * long, ulong, longlong, ulonglong, * half, float, double, cfloat, cdouble# * #type = npy_byte, npy_ubyte, npy_short, npy_ushort, npy_int, npy_uint, * npy_long, npy_ulong, npy_longlong, npy_ulonglong, * npy_half, npy_float, npy_double, npy_cfloat, npy_cdouble# */ static int _@name@_convert2_to_ctypes(PyObject *a, @type@ *arg1, PyObject *b, @type@ *arg2) { int ret; ret = _@name@_convert_to_ctype(a, arg1); if (ret < 0) { return ret; } ret = _@name@_convert_to_ctype(b, arg2); if (ret < 0) { return ret; } return 0; } /**end repeat**/ /**begin repeat * #name = longdouble, clongdouble# * #type = npy_longdouble, npy_clongdouble# */ static int _@name@_convert2_to_ctypes(PyObject *a, @type@ *arg1, PyObject *b, @type@ *arg2) { int ret; ret = _@name@_convert_to_ctype(a, arg1); if (ret < 0) { return ret; } ret = _@name@_convert_to_ctype(b, arg2); if (ret == -2) { ret = -3; } if (ret < 0) { return ret; } return 0; } /**end repeat**/ #if defined(NPY_PY3K) #define CODEGEN_SKIP_divide_FLAG #endif /**begin repeat * * #name = (byte, ubyte, short, ushort, int, uint, * long, ulong, longlong, ulonglong)*13, * (half, float, double, longdouble, * cfloat, cdouble, clongdouble)*6, * (half, float, double, longdouble)*2# * #Name = (Byte, UByte, Short, UShort, Int, UInt, * Long, ULong,LongLong,ULongLong)*13, * (Half, Float, Double, LongDouble, * CFloat, CDouble, CLongDouble)*6, * (Half, Float, Double, LongDouble)*2# * #type = (npy_byte, npy_ubyte, npy_short, npy_ushort, npy_int, npy_uint, * npy_long, npy_ulong, npy_longlong, npy_ulonglong)*13, * (npy_half, npy_float, npy_double, npy_longdouble, * npy_cfloat, npy_cdouble, npy_clongdouble)*6, * (npy_half, npy_float, npy_double, npy_longdouble)*2# * * #oper = add*10, subtract*10, multiply*10, divide*10, remainder*10, * divmod*10, floor_divide*10, lshift*10, rshift*10, and*10, * or*10, xor*10, true_divide*10, * add*7, subtract*7, multiply*7, divide*7, floor_divide*7, true_divide*7, * divmod*4, remainder*4# * * #fperr = 1*70,0*50,1*10, * 1*42, * 1*8# * #twoout = 0*50,1*10,0*70, * 0*42, * 1*4,0*4# * #otype = (npy_byte, npy_ubyte, npy_short, npy_ushort, npy_int, npy_uint, * npy_long, npy_ulong, npy_longlong, npy_ulonglong)*12, * npy_float*4, npy_double*6, * (npy_half, npy_float, npy_double, npy_longdouble, * npy_cfloat, npy_cdouble, npy_clongdouble)*6, * (npy_half, npy_float, npy_double, npy_longdouble)*2# * #OName = (Byte, UByte, Short, UShort, Int, UInt, * Long, ULong, LongLong, ULongLong)*12, * Float*4, Double*6, * (Half, Float, Double, LongDouble, * CFloat, CDouble, CLongDouble)*6, * (Half, Float, Double, LongDouble)*2# */ #if !defined(CODEGEN_SKIP_@oper@_FLAG) static PyObject * @name@_@oper@(PyObject *a, PyObject *b) { PyObject *ret; @type@ arg1, arg2; /* * NOTE: In gcc >= 4.1, the compiler will reorder floating point * operations and floating point error state checks. In * particular, the arithmetic operations were being reordered * so that the errors weren't caught. Declaring this output * variable volatile was the minimal fix for the issue. * (Ticket #1671) */ volatile @otype@ out; #if @twoout@ @otype@ out2; PyObject *obj; #endif #if @fperr@ int retstatus; int first; #endif switch(_@name@_convert2_to_ctypes(a, &arg1, b, &arg2)) { case 0: break; case -1: /* one of them can't be cast safely must be mixed-types*/ return PyArray_Type.tp_as_number->nb_@oper@(a,b); case -2: /* use default handling */ if (PyErr_Occurred()) { return NULL; } return PyGenericArrType_Type.tp_as_number->nb_@oper@(a,b); case -3: /* * special case for longdouble and clongdouble * because they have a recursive getitem in their dtype */ Py_INCREF(Py_NotImplemented); return Py_NotImplemented; } #if @fperr@ PyUFunc_clearfperr(); #endif /* * here we do the actual calculation with arg1 and arg2 * as a function call. */ #if @twoout@ @name@_ctype_@oper@(arg1, arg2, (@otype@ *)&out, &out2); #else @name@_ctype_@oper@(arg1, arg2, (@otype@ *)&out); #endif #if @fperr@ /* Check status flag. If it is set, then look up what to do */ retstatus = PyUFunc_getfperr(); if (retstatus) { int bufsize, errmask; PyObject *errobj; if (PyUFunc_GetPyValues("@name@_scalars", &bufsize, &errmask, &errobj) < 0) { return NULL; } first = 1; if (PyUFunc_handlefperr(errmask, errobj, retstatus, &first)) { Py_XDECREF(errobj); return NULL; } Py_XDECREF(errobj); } #endif #if @twoout@ ret = PyTuple_New(2); if (ret == NULL) { return NULL; } obj = PyArrayScalar_New(@OName@); if (obj == NULL) { Py_DECREF(ret); return NULL; } PyArrayScalar_ASSIGN(obj, @OName@, out); PyTuple_SET_ITEM(ret, 0, obj); obj = PyArrayScalar_New(@OName@); if (obj == NULL) { Py_DECREF(ret); return NULL; } PyArrayScalar_ASSIGN(obj, @OName@, out2); PyTuple_SET_ITEM(ret, 1, obj); #else ret = PyArrayScalar_New(@OName@); if (ret == NULL) { return NULL; } PyArrayScalar_ASSIGN(ret, @OName@, out); #endif return ret; } #endif /**end repeat**/ #undef CODEGEN_SKIP_divide_FLAG #define _IS_ZERO(x) (x == 0) /**begin repeat * * #name = byte, ubyte, short, ushort, int, uint, * long, ulong, longlong, ulonglong, * half, float, double, longdouble, * cfloat, cdouble, clongdouble# * * #type = npy_byte, npy_ubyte, npy_short, npy_ushort, npy_int, npy_uint, * npy_long, npy_ulong, npy_longlong, npy_ulonglong, * npy_half, npy_float, npy_double, npy_longdouble, * npy_cfloat, npy_cdouble, npy_clongdouble# * * #Name = Byte, UByte, Short, UShort, Int, UInt, * Long, ULong, LongLong, ULongLong, * Half, Float, Double, LongDouble, * CFloat, CDouble, CLongDouble# * * #otype = npy_float*4, npy_double*6, npy_half, npy_float, * npy_double, npy_longdouble, * npy_cfloat, npy_cdouble, npy_clongdouble# * * #OName = Float*4, Double*6, Half, Float, * Double, LongDouble, * CFloat, CDouble, CLongDouble# * * #isint = (1,0)*5,0*7# * #cmplx = 0*14,1*3# * #iszero = _IS_ZERO*10, npy_half_iszero, _IS_ZERO*6# * #zero = 0*10, NPY_HALF_ZERO, 0*6# * #one = 1*10, NPY_HALF_ONE, 1*6# */ #if @cmplx@ static PyObject * @name@_power(PyObject *a, PyObject *b, PyObject *NPY_UNUSED(c)) { PyObject *ret; @type@ arg1, arg2; int retstatus; int first; @type@ out = {@zero@, @zero@}; switch(_@name@_convert2_to_ctypes(a, &arg1, b, &arg2)) { case 0: break; case -1: /* can't cast both safely mixed-types? */ return PyArray_Type.tp_as_number->nb_power(a,b,NULL); case -2: /* use default handling */ if (PyErr_Occurred()) { return NULL; } return PyGenericArrType_Type.tp_as_number->nb_power(a,b,NULL); case -3: /* * special case for longdouble and clongdouble * because they have a recursive getitem in their dtype */ Py_INCREF(Py_NotImplemented); return Py_NotImplemented; } PyUFunc_clearfperr(); /* * here we do the actual calculation with arg1 and arg2 * as a function call. */ if (@iszero@(arg2.real) && @iszero@(arg2.imag)) { out.real = @one@; out.imag = @zero@; } else { @name@_ctype_power(arg1, arg2, &out); } /* Check status flag. If it is set, then look up what to do */ retstatus = PyUFunc_getfperr(); if (retstatus) { int bufsize, errmask; PyObject *errobj; if (PyUFunc_GetPyValues("@name@_scalars", &bufsize, &errmask, &errobj) < 0) { return NULL; } first = 1; if (PyUFunc_handlefperr(errmask, errobj, retstatus, &first)) { Py_XDECREF(errobj); return NULL; } Py_XDECREF(errobj); } ret = PyArrayScalar_New(@Name@); if (ret == NULL) { return NULL; } PyArrayScalar_ASSIGN(ret, @Name@, out); return ret; } #elif @isint@ static PyObject * @name@_power(PyObject *a, PyObject *b, PyObject *NPY_UNUSED(c)) { PyObject *ret; @type@ arg1, arg2; int retstatus; int first; @type@ out = @zero@; @otype@ out1 = @zero@; switch(_@name@_convert2_to_ctypes(a, &arg1, b, &arg2)) { case 0: break; case -1: /* can't cast both safely mixed-types? */ return PyArray_Type.tp_as_number->nb_power(a,b,NULL); case -2: /* use default handling */ if (PyErr_Occurred()) { return NULL; } return PyGenericArrType_Type.tp_as_number->nb_power(a,b,NULL); case -3: /* * special case for longdouble and clongdouble * because they have a recursive getitem in their dtype */ Py_INCREF(Py_NotImplemented); return Py_NotImplemented; } PyUFunc_clearfperr(); /* * here we do the actual calculation with arg1 and arg2 * as a function call. */ if (@iszero@(arg2)) { out1 = out = @one@; } else if (arg2 < 0) { @name@_ctype_power(arg1, -arg2, &out); out1 = (@otype@) (1.0 / out); } else { @name@_ctype_power(arg1, arg2, &out); } /* Check status flag. If it is set, then look up what to do */ retstatus = PyUFunc_getfperr(); if (retstatus) { int bufsize, errmask; PyObject *errobj; if (PyUFunc_GetPyValues("@name@_scalars", &bufsize, &errmask, &errobj) < 0) { return NULL; } first = 1; if (PyUFunc_handlefperr(errmask, errobj, retstatus, &first)) { Py_XDECREF(errobj); return NULL; } Py_XDECREF(errobj); } if (arg2 < 0) { ret = PyArrayScalar_New(@OName@); if (ret == NULL) { return NULL; } PyArrayScalar_ASSIGN(ret, @OName@, out1); } else { ret = PyArrayScalar_New(@Name@); if (ret == NULL) { return NULL; } PyArrayScalar_ASSIGN(ret, @Name@, out); } return ret; } #else static PyObject * @name@_power(PyObject *a, PyObject *b, PyObject *NPY_UNUSED(c)) { PyObject *ret; @type@ arg1, arg2; int retstatus; int first; @type@ out = @zero@; switch(_@name@_convert2_to_ctypes(a, &arg1, b, &arg2)) { case 0: break; case -1: /* can't cast both safely mixed-types? */ return PyArray_Type.tp_as_number->nb_power(a,b,NULL); case -2: /* use default handling */ if (PyErr_Occurred()) { return NULL; } return PyGenericArrType_Type.tp_as_number->nb_power(a,b,NULL); case -3: /* * special case for longdouble and clongdouble * because they have a recursive getitem in their dtype */ Py_INCREF(Py_NotImplemented); return Py_NotImplemented; } PyUFunc_clearfperr(); /* * here we do the actual calculation with arg1 and arg2 * as a function call. */ if (@iszero@(arg2)) { out = @one@; } else { @name@_ctype_power(arg1, arg2, &out); } /* Check status flag. If it is set, then look up what to do */ retstatus = PyUFunc_getfperr(); if (retstatus) { int bufsize, errmask; PyObject *errobj; if (PyUFunc_GetPyValues("@name@_scalars", &bufsize, &errmask, &errobj) < 0) { return NULL; } first = 1; if (PyUFunc_handlefperr(errmask, errobj, retstatus, &first)) { Py_XDECREF(errobj); return NULL; } Py_XDECREF(errobj); } ret = PyArrayScalar_New(@Name@); if (ret == NULL) { return NULL; } PyArrayScalar_ASSIGN(ret, @Name@, out); return ret; } #endif /**end repeat**/ #undef _IS_ZERO /**begin repeat * * #name = cfloat, cdouble, clongdouble# * */ /**begin repeat1 * * #oper = divmod, remainder# * */ #define @name@_@oper@ NULL /**end repeat1**/ /**end repeat**/ /**begin repeat * * #name = half, float, double, longdouble, cfloat, cdouble, clongdouble# * */ /**begin repeat1 * * #oper = lshift, rshift, and, or, xor# * */ #define @name@_@oper@ NULL /**end repeat1**/ /**end repeat**/ /**begin repeat * #name = (byte, ubyte, short, ushort, int, uint, * long, ulong, longlong, ulonglong, * half, float, double, longdouble, * cfloat, cdouble, clongdouble)*3, * * byte, ubyte, short, ushort, int, uint, * long, ulong, longlong, ulonglong# * * #type = (npy_byte, npy_ubyte, npy_short, npy_ushort, npy_int, npy_uint, * npy_long, npy_ulong, npy_longlong, npy_ulonglong, * npy_half, npy_float, npy_double, npy_longdouble, * npy_cfloat, npy_cdouble, npy_clongdouble)*3, * * npy_byte, npy_ubyte, npy_short, npy_ushort, npy_int, npy_uint, * npy_long, npy_ulong, npy_longlong, npy_ulonglong# * * #otype = (npy_byte, npy_ubyte, npy_short, npy_ushort, npy_int, npy_uint, * npy_long, npy_ulong, npy_longlong, npy_ulonglong, * npy_half, npy_float, npy_double, npy_longdouble, * npy_cfloat, npy_cdouble, npy_clongdouble)*2, * npy_byte, npy_ubyte, npy_short, npy_ushort, npy_int, npy_uint, * npy_long, npy_ulong, npy_longlong, npy_ulonglong, * npy_half, npy_float, npy_double, npy_longdouble, * npy_float, npy_double, npy_longdouble, * * npy_byte, npy_ubyte, npy_short, npy_ushort, npy_int, npy_uint, * npy_long, npy_ulong, npy_longlong, npy_ulonglong# * * #OName = (Byte, UByte, Short, UShort, Int, UInt, * Long, ULong, LongLong, ULongLong, * Half, Float, Double, LongDouble, * CFloat, CDouble, CLongDouble)*2, * Byte, UByte, Short, UShort, Int, UInt, * Long, ULong, LongLong, ULongLong, * Half, Float, Double, LongDouble, * Float, Double, LongDouble, * * Byte, UByte, Short, UShort, Int, UInt, * Long, ULong, LongLong, ULongLong# * * #oper = negative*17, positive*17, absolute*17, invert*10# */ static PyObject * @name@_@oper@(PyObject *a) { @type@ arg1; @otype@ out; PyObject *ret; switch(_@name@_convert_to_ctype(a, &arg1)) { case 0: break; case -1: /* can't cast both safely use different add function */ Py_INCREF(Py_NotImplemented); return Py_NotImplemented; case -2: /* use default handling */ if (PyErr_Occurred()) { return NULL; } return PyGenericArrType_Type.tp_as_number->nb_@oper@(a); } /* * here we do the actual calculation with arg1 and arg2 * make it a function call. */ @name@_ctype_@oper@(arg1, &out); ret = PyArrayScalar_New(@OName@); PyArrayScalar_ASSIGN(ret, @OName@, out); return ret; } /**end repeat**/ /**begin repeat * * #name = half, float, double, longdouble, cfloat, cdouble, clongdouble# */ #define @name@_invert NULL /**end repeat**/ #if defined(NPY_PY3K) #define NONZERO_NAME(prefix) prefix##bool #else #define NONZERO_NAME(prefix) prefix##nonzero #endif #define _IS_NONZERO(x) (x != 0) /**begin repeat * * #name = byte, ubyte, short, ushort, int, * uint, long, ulong, longlong, ulonglong, * half, float, double, longdouble, * cfloat, cdouble, clongdouble# * #type = npy_byte, npy_ubyte, npy_short, npy_ushort, npy_int, * npy_uint, npy_long, npy_ulong, npy_longlong, npy_ulonglong, * npy_half, npy_float, npy_double, npy_longdouble, * npy_cfloat, npy_cdouble, npy_clongdouble# * #simp = 1*14, 0*3# * #nonzero = _IS_NONZERO*10, !npy_half_iszero, _IS_NONZERO*6# */ static int NONZERO_NAME(@name@_)(PyObject *a) { int ret; @type@ arg1; if (_@name@_convert_to_ctype(a, &arg1) < 0) { if (PyErr_Occurred()) { return -1; } return PyGenericArrType_Type.tp_as_number->NONZERO_NAME(nb_)(a); } /* * here we do the actual calculation with arg1 and arg2 * make it a function call. */ #if @simp@ ret = @nonzero@(arg1); #else ret = (@nonzero@(arg1.real) || @nonzero@(arg1.imag)); #endif return ret; } /**end repeat**/ #undef _IS_NONZERO static int emit_complexwarning(void) { static PyObject *cls = NULL; if (cls == NULL) { PyObject *mod; mod = PyImport_ImportModule("numpy.core"); assert(mod != NULL); cls = PyObject_GetAttrString(mod, "ComplexWarning"); assert(cls != NULL); Py_DECREF(mod); } return PyErr_WarnEx(cls, "Casting complex values to real discards the imaginary part", 1); } /**begin repeat * * #name = byte, ubyte, short, ushort, int, * uint, long, ulong, longlong, ulonglong, * half, float, double, longdouble, * cfloat, cdouble, clongdouble# * * #Name = Byte, UByte, Short, UShort, Int, * UInt, Long, ULong, LongLong, ULongLong, * Half, Float, Double, LongDouble, * CFloat, CDouble, CLongDouble# * * #cmplx = 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1# * #sign = (signed, unsigned)*5, , , , , , , # * #unsigntyp = 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0*7# * #ctype = long*8, PY_LONG_LONG*2, double*7# * #to_ctype = , , , , , , , , , , npy_half_to_double, , , , , , # * #realtyp = 0*10, 1*7# * #func = (PyLong_FromLong, PyLong_FromUnsignedLong)*4, * PyLong_FromLongLong, PyLong_FromUnsignedLongLong, * PyLong_FromDouble*7# */ static PyObject * @name@_int(PyObject *obj) { #if @cmplx@ @sign@ @ctype@ x= @to_ctype@(PyArrayScalar_VAL(obj, @Name@).real); int ret; #else @sign@ @ctype@ x= @to_ctype@(PyArrayScalar_VAL(obj, @Name@)); #endif #if @realtyp@ double ix; modf(x, &ix); x = ix; #endif #if @cmplx@ ret = emit_complexwarning(); if (ret < 0) { return NULL; } #endif #if @unsigntyp@ if(x < LONG_MAX) return PyInt_FromLong(x); #else if(LONG_MIN < x && x < LONG_MAX) return PyInt_FromLong(x); #endif return @func@(x); } /**end repeat**/ /**begin repeat * * #name = (byte, ubyte, short, ushort, int, uint, * long, ulong, longlong, ulonglong, * half, float, double, longdouble, * cfloat, cdouble, clongdouble)*2# * #Name = (Byte, UByte, Short, UShort, Int, UInt, * Long, ULong, LongLong, ULongLong, * Half, Float, Double, LongDouble, * CFloat, CDouble, CLongDouble)*2# * #cmplx = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1)*2# * #to_ctype = (, , , , , , , , , , npy_half_to_double, , , , , , )*2# * #which = long*17, float*17# * #func = (PyLong_FromLongLong, PyLong_FromUnsignedLongLong)*5, * PyLong_FromDouble*7, PyFloat_FromDouble*17# */ static PyObject * @name@_@which@(PyObject *obj) { #if @cmplx@ int ret; ret = emit_complexwarning(); if (ret < 0) { return NULL; } return @func@(@to_ctype@((PyArrayScalar_VAL(obj, @Name@)).real)); #else return @func@(@to_ctype@(PyArrayScalar_VAL(obj, @Name@))); #endif } /**end repeat**/ #if !defined(NPY_PY3K) /**begin repeat * * #name = (byte, ubyte, short, ushort, int, uint, * long, ulong, longlong, ulonglong, * half, float, double, longdouble, * cfloat, cdouble, clongdouble)*2# * #oper = oct*17, hex*17# * #kind = (int*5, long*5, int*2, long*2, int, long*2)*2# * #cap = (Int*5, Long*5, Int*2, Long*2, Int, Long*2)*2# */ static PyObject * @name@_@oper@(PyObject *obj) { PyObject *pyint; pyint = @name@_@kind@(obj); if (pyint == NULL) { return NULL; } return Py@cap@_Type.tp_as_number->nb_@oper@(pyint); } /**end repeat**/ #endif /**begin repeat * #oper = le, ge, lt, gt, eq, ne# * #op = <=, >=, <, >, ==, !=# * #halfop = npy_half_le, npy_half_ge, npy_half_lt, * npy_half_gt, npy_half_eq, npy_half_ne# */ #define def_cmp_@oper@(arg1, arg2) (arg1 @op@ arg2) #define cmplx_cmp_@oper@(arg1, arg2) ((arg1.real == arg2.real) ? \ arg1.imag @op@ arg2.imag : \ arg1.real @op@ arg2.real) #define def_half_cmp_@oper@(arg1, arg2) @halfop@(arg1, arg2) /**end repeat**/ /**begin repeat * #name = byte, ubyte, short, ushort, int, uint, * long, ulong, longlong, ulonglong, * half, float, double, longdouble, * cfloat, cdouble, clongdouble# * #simp = def*10, def_half, def*3, cmplx*3# */ static PyObject* @name@_richcompare(PyObject *self, PyObject *other, int cmp_op) { npy_@name@ arg1, arg2; int out=0; switch(_@name@_convert2_to_ctypes(self, &arg1, other, &arg2)) { case 0: break; case -1: /* can't cast both safely use different add function */ case -2: /* use ufunc */ if (PyErr_Occurred()) { return NULL; } return PyGenericArrType_Type.tp_richcompare(self, other, cmp_op); case -3: /* * special case for longdouble and clongdouble * because they have a recursive getitem in their dtype */ Py_INCREF(Py_NotImplemented); return Py_NotImplemented; } /* here we do the actual calculation with arg1 and arg2 */ switch (cmp_op) { case Py_EQ: out = @simp@_cmp_eq(arg1, arg2); break; case Py_NE: out = @simp@_cmp_ne(arg1, arg2); break; case Py_LE: out = @simp@_cmp_le(arg1, arg2); break; case Py_GE: out = @simp@_cmp_ge(arg1, arg2); break; case Py_LT: out = @simp@_cmp_lt(arg1, arg2); break; case Py_GT: out = @simp@_cmp_gt(arg1, arg2); break; } if (out) { PyArrayScalar_RETURN_TRUE; } else { PyArrayScalar_RETURN_FALSE; } } /**end repeat**/ /**begin repeat * #name = byte, ubyte, short, ushort, int, uint, * long, ulong, longlong, ulonglong, * half, float, double, longdouble, * cfloat, cdouble, clongdouble# **/ static PyNumberMethods @name@_as_number = { (binaryfunc)@name@_add, /*nb_add*/ (binaryfunc)@name@_subtract, /*nb_subtract*/ (binaryfunc)@name@_multiply, /*nb_multiply*/ #if defined(NPY_PY3K) #else (binaryfunc)@name@_divide, /*nb_divide*/ #endif (binaryfunc)@name@_remainder, /*nb_remainder*/ (binaryfunc)@name@_divmod, /*nb_divmod*/ (ternaryfunc)@name@_power, /*nb_power*/ (unaryfunc)@name@_negative, (unaryfunc)@name@_positive, /*nb_pos*/ (unaryfunc)@name@_absolute, /*nb_abs*/ #if defined(NPY_PY3K) (inquiry)@name@_bool, /*nb_bool*/ #else (inquiry)@name@_nonzero, /*nb_nonzero*/ #endif (unaryfunc)@name@_invert, /*nb_invert*/ (binaryfunc)@name@_lshift, /*nb_lshift*/ (binaryfunc)@name@_rshift, /*nb_rshift*/ (binaryfunc)@name@_and, /*nb_and*/ (binaryfunc)@name@_xor, /*nb_xor*/ (binaryfunc)@name@_or, /*nb_or*/ #if defined(NPY_PY3K) #else 0, /*nb_coerce*/ #endif (unaryfunc)@name@_int, /*nb_int*/ #if defined(NPY_PY3K) (unaryfunc)0, /*nb_reserved*/ #else (unaryfunc)@name@_long, /*nb_long*/ #endif (unaryfunc)@name@_float, /*nb_float*/ #if defined(NPY_PY3K) #else (unaryfunc)@name@_oct, /*nb_oct*/ (unaryfunc)@name@_hex, /*nb_hex*/ #endif 0, /*inplace_add*/ 0, /*inplace_subtract*/ 0, /*inplace_multiply*/ #if defined(NPY_PY3K) #else 0, /*inplace_divide*/ #endif 0, /*inplace_remainder*/ 0, /*inplace_power*/ 0, /*inplace_lshift*/ 0, /*inplace_rshift*/ 0, /*inplace_and*/ 0, /*inplace_xor*/ 0, /*inplace_or*/ (binaryfunc)@name@_floor_divide, /*nb_floor_divide*/ (binaryfunc)@name@_true_divide, /*nb_true_divide*/ 0, /*nb_inplace_floor_divide*/ 0, /*nb_inplace_true_divide*/ (unaryfunc)NULL, /*nb_index*/ }; /**end repeat**/ static void *saved_tables_arrtype[9]; static void add_scalarmath(void) { /**begin repeat * #name = byte, ubyte, short, ushort, int, uint, * long, ulong, longlong, ulonglong, * half, float, double, longdouble, * cfloat, cdouble, clongdouble# * #NAME = Byte, UByte, Short, UShort, Int, UInt, * Long, ULong, LongLong, ULongLong, * Half, Float, Double, LongDouble, * CFloat, CDouble, CLongDouble# **/ @name@_as_number.nb_index = Py@NAME@ArrType_Type.tp_as_number->nb_index; Py@NAME@ArrType_Type.tp_as_number = &(@name@_as_number); Py@NAME@ArrType_Type.tp_richcompare = @name@_richcompare; /**end repeat**/ saved_tables_arrtype[0] = PyLongArrType_Type.tp_as_number; #if !defined(NPY_PY3K) saved_tables_arrtype[1] = PyLongArrType_Type.tp_compare; #endif saved_tables_arrtype[2] = PyLongArrType_Type.tp_richcompare; saved_tables_arrtype[3] = PyDoubleArrType_Type.tp_as_number; #if !defined(NPY_PY3K) saved_tables_arrtype[4] = PyDoubleArrType_Type.tp_compare; #endif saved_tables_arrtype[5] = PyDoubleArrType_Type.tp_richcompare; saved_tables_arrtype[6] = PyCDoubleArrType_Type.tp_as_number; #if !defined(NPY_PY3K) saved_tables_arrtype[7] = PyCDoubleArrType_Type.tp_compare; #endif saved_tables_arrtype[8] = PyCDoubleArrType_Type.tp_richcompare; } static int get_functions(void) { PyObject *mm, *obj; void **funcdata; char *signatures; int i, j; int ret = -1; /* Get the nc_pow functions */ /* Get the pow functions */ mm = PyImport_ImportModule("numpy.core.umath"); if (mm == NULL) { return -1; } obj = PyObject_GetAttrString(mm, "power"); if (obj == NULL) { goto fail; } funcdata = ((PyUFuncObject *)obj)->data; signatures = ((PyUFuncObject *)obj)->types; i = 0; j = 0; while (signatures[i] != NPY_FLOAT) { i += 3; j++; } _basic_float_pow = funcdata[j]; _basic_double_pow = funcdata[j + 1]; _basic_longdouble_pow = funcdata[j + 2]; _basic_cfloat_pow = funcdata[j + 3]; _basic_cdouble_pow = funcdata[j + 4]; _basic_clongdouble_pow = funcdata[j + 5]; Py_DECREF(obj); /* Get the floor functions */ obj = PyObject_GetAttrString(mm, "floor"); if (obj == NULL) { goto fail; } funcdata = ((PyUFuncObject *)obj)->data; signatures = ((PyUFuncObject *)obj)->types; i = 0; j = 0; while(signatures[i] != NPY_FLOAT) { i += 2; j++; } _basic_half_floor = funcdata[j - 1]; _basic_float_floor = funcdata[j]; _basic_double_floor = funcdata[j + 1]; _basic_longdouble_floor = funcdata[j + 2]; Py_DECREF(obj); /* Get the sqrt functions */ obj = PyObject_GetAttrString(mm, "sqrt"); if (obj == NULL) { goto fail; } funcdata = ((PyUFuncObject *)obj)->data; signatures = ((PyUFuncObject *)obj)->types; /* * sqrt ufunc is specialized for double and float loops in * generate_umath.py, the first to go into FLOAT/DOUBLE_sqrt * they have the same signature as the scalar variants so we need to skip * over them */ i = 4; j = 2; while (signatures[i] != NPY_FLOAT) { i += 2; j++; } _basic_half_sqrt = funcdata[j - 1]; _basic_float_sqrt = funcdata[j]; _basic_double_sqrt = funcdata[j + 1]; _basic_longdouble_sqrt = funcdata[j + 2]; Py_DECREF(obj); /* Get the fmod functions */ obj = PyObject_GetAttrString(mm, "fmod"); if (obj == NULL) { goto fail; } funcdata = ((PyUFuncObject *)obj)->data; signatures = ((PyUFuncObject *)obj)->types; i = 0; j = 0; while (signatures[i] != NPY_FLOAT) { i += 3; j++; } _basic_half_fmod = funcdata[j - 1]; _basic_float_fmod = funcdata[j]; _basic_double_fmod = funcdata[j + 1]; _basic_longdouble_fmod = funcdata[j + 2]; Py_DECREF(obj); return ret = 0; fail: Py_DECREF(mm); return ret; } static void *saved_tables[9]; char doc_alterpyscalars[] = ""; static PyObject * alter_pyscalars(PyObject *NPY_UNUSED(dummy), PyObject *args) { int n; PyObject *obj; n = PyTuple_GET_SIZE(args); while (n--) { obj = PyTuple_GET_ITEM(args, n); #if !defined(NPY_PY3K) if (obj == (PyObject *)(&PyInt_Type)) { PyInt_Type.tp_as_number = PyLongArrType_Type.tp_as_number; PyInt_Type.tp_compare = PyLongArrType_Type.tp_compare; PyInt_Type.tp_richcompare = PyLongArrType_Type.tp_richcompare; } else #endif if (obj == (PyObject *)(&PyFloat_Type)) { PyFloat_Type.tp_as_number = PyDoubleArrType_Type.tp_as_number; #if !defined(NPY_PY3K) PyFloat_Type.tp_compare = PyDoubleArrType_Type.tp_compare; #endif PyFloat_Type.tp_richcompare = PyDoubleArrType_Type.tp_richcompare; } else if (obj == (PyObject *)(&PyComplex_Type)) { PyComplex_Type.tp_as_number = PyCDoubleArrType_Type.tp_as_number; #if !defined(NPY_PY3K) PyComplex_Type.tp_compare = PyCDoubleArrType_Type.tp_compare; #endif PyComplex_Type.tp_richcompare = \ PyCDoubleArrType_Type.tp_richcompare; } else { PyErr_SetString(PyExc_ValueError, "arguments must be int, float, or complex"); return NULL; } } Py_INCREF(Py_None); return Py_None; } char doc_restorepyscalars[] = ""; static PyObject * restore_pyscalars(PyObject *NPY_UNUSED(dummy), PyObject *args) { int n; PyObject *obj; n = PyTuple_GET_SIZE(args); while (n--) { obj = PyTuple_GET_ITEM(args, n); #if !defined(NPY_PY3K) if (obj == (PyObject *)(&PyInt_Type)) { PyInt_Type.tp_as_number = saved_tables[0]; PyInt_Type.tp_compare = saved_tables[1]; PyInt_Type.tp_richcompare = saved_tables[2]; } else #endif if (obj == (PyObject *)(&PyFloat_Type)) { PyFloat_Type.tp_as_number = saved_tables[3]; #if !defined(NPY_PY3K) PyFloat_Type.tp_compare = saved_tables[4]; #endif PyFloat_Type.tp_richcompare = saved_tables[5]; } else if (obj == (PyObject *)(&PyComplex_Type)) { PyComplex_Type.tp_as_number = saved_tables[6]; #if !defined(NPY_PY3K) PyComplex_Type.tp_compare = saved_tables[7]; #endif PyComplex_Type.tp_richcompare = saved_tables[8]; } else { PyErr_SetString(PyExc_ValueError, "arguments must be int, float, or complex"); return NULL; } } Py_INCREF(Py_None); return Py_None; } char doc_usepythonmath[] = ""; static PyObject * use_pythonmath(PyObject *NPY_UNUSED(dummy), PyObject *args) { int n; PyObject *obj; n = PyTuple_GET_SIZE(args); while (n--) { obj = PyTuple_GET_ITEM(args, n); #if !defined(NPY_PY3K) if (obj == (PyObject *)(&PyInt_Type)) { PyLongArrType_Type.tp_as_number = saved_tables[0]; PyLongArrType_Type.tp_compare = saved_tables[1]; PyLongArrType_Type.tp_richcompare = saved_tables[2]; } else #endif if (obj == (PyObject *)(&PyFloat_Type)) { PyDoubleArrType_Type.tp_as_number = saved_tables[3]; #if !defined(NPY_PY3K) PyDoubleArrType_Type.tp_compare = saved_tables[4]; #endif PyDoubleArrType_Type.tp_richcompare = saved_tables[5]; } else if (obj == (PyObject *)(&PyComplex_Type)) { PyCDoubleArrType_Type.tp_as_number = saved_tables[6]; #if !defined(NPY_PY3K) PyCDoubleArrType_Type.tp_compare = saved_tables[7]; #endif PyCDoubleArrType_Type.tp_richcompare = saved_tables[8]; } else { PyErr_SetString(PyExc_ValueError, "arguments must be int, float, or complex"); return NULL; } } Py_INCREF(Py_None); return Py_None; } char doc_usescalarmath[] = ""; static PyObject * use_scalarmath(PyObject *NPY_UNUSED(dummy), PyObject *args) { int n; PyObject *obj; n = PyTuple_GET_SIZE(args); while (n--) { obj = PyTuple_GET_ITEM(args, n); #if !defined(NPY_PY3K) if (obj == (PyObject *)(&PyInt_Type)) { PyLongArrType_Type.tp_as_number = saved_tables_arrtype[0]; PyLongArrType_Type.tp_compare = saved_tables_arrtype[1]; PyLongArrType_Type.tp_richcompare = saved_tables_arrtype[2]; } else #endif if (obj == (PyObject *)(&PyFloat_Type)) { PyDoubleArrType_Type.tp_as_number = saved_tables_arrtype[3]; #if !defined(NPY_PY3K) PyDoubleArrType_Type.tp_compare = saved_tables_arrtype[4]; #endif PyDoubleArrType_Type.tp_richcompare = saved_tables_arrtype[5]; } else if (obj == (PyObject *)(&PyComplex_Type)) { PyCDoubleArrType_Type.tp_as_number = saved_tables_arrtype[6]; #if !defined(NPY_PY3K) PyCDoubleArrType_Type.tp_compare = saved_tables_arrtype[7]; #endif PyCDoubleArrType_Type.tp_richcompare = saved_tables_arrtype[8]; } else { PyErr_SetString(PyExc_ValueError, "arguments must be int, float, or complex"); return NULL; } } Py_INCREF(Py_None); return Py_None; } static struct PyMethodDef methods[] = { {"alter_pythonmath", (PyCFunction) alter_pyscalars, METH_VARARGS, doc_alterpyscalars}, {"restore_pythonmath", (PyCFunction) restore_pyscalars, METH_VARARGS, doc_restorepyscalars}, {"use_pythonmath", (PyCFunction) use_pythonmath, METH_VARARGS, doc_usepythonmath}, {"use_scalarmath", (PyCFunction) use_scalarmath, METH_VARARGS, doc_usescalarmath}, {NULL, NULL, 0, NULL} }; #if defined(NPY_PY3K) static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, "scalarmath", NULL, -1, methods, NULL, NULL, NULL, NULL }; #endif #if defined(NPY_PY3K) #define RETVAL m PyMODINIT_FUNC PyInit_scalarmath(void) #else #define RETVAL PyMODINIT_FUNC initscalarmath(void) #endif { #if defined(NPY_PY3K) PyObject *m = PyModule_Create(&moduledef); if (!m) { return NULL; } #else Py_InitModule("scalarmath", methods); #endif import_array(); import_umath(); if (get_functions() < 0) { return RETVAL; } add_scalarmath(); #if !defined(NPY_PY3K) saved_tables[0] = PyInt_Type.tp_as_number; saved_tables[1] = PyInt_Type.tp_compare; saved_tables[2] = PyInt_Type.tp_richcompare; #endif saved_tables[3] = PyFloat_Type.tp_as_number; #if !defined(NPY_PY3K) saved_tables[4] = PyFloat_Type.tp_compare; #endif saved_tables[5] = PyFloat_Type.tp_richcompare; saved_tables[6] = PyComplex_Type.tp_as_number; #if !defined(NPY_PY3K) saved_tables[7] = PyComplex_Type.tp_compare; #endif saved_tables[8] = PyComplex_Type.tp_richcompare; return RETVAL; } numpy-1.8.2/numpy/core/src/umath/0000775000175100017510000000000012371375430020036 5ustar vagrantvagrant00000000000000numpy-1.8.2/numpy/core/src/umath/reduction.c0000664000175100017510000004720512370216242022200 0ustar vagrantvagrant00000000000000/* * This file implements generic methods for computing reductions on arrays. * * Written by Mark Wiebe (mwwiebe@gmail.com) * Copyright (c) 2011 by Enthought, Inc. * * See LICENSE.txt for the license. */ #define _UMATHMODULE #define NPY_NO_DEPRECATED_API NPY_API_VERSION #define PY_SSIZE_T_CLEAN #include #include "npy_config.h" #ifdef ENABLE_SEPARATE_COMPILATION #define PY_ARRAY_UNIQUE_SYMBOL _npy_umathmodule_ARRAY_API #define NO_IMPORT_ARRAY #endif #include #include "npy_config.h" #include "npy_pycompat.h" #include "lowlevel_strided_loops.h" #include "reduction.h" /* * Allocates a result array for a reduction operation, with * dimensions matching 'arr' except set to 1 with 0 stride * whereever axis_flags is True. Dropping the reduction axes * from the result must be done later by the caller once the * computation is complete. * * This function always allocates a base class ndarray. * * If 'dtype' isn't NULL, this function steals its reference. */ static PyArrayObject * allocate_reduce_result(PyArrayObject *arr, npy_bool *axis_flags, PyArray_Descr *dtype, int subok) { npy_intp strides[NPY_MAXDIMS], stride; npy_intp shape[NPY_MAXDIMS], *arr_shape = PyArray_DIMS(arr); npy_stride_sort_item strideperm[NPY_MAXDIMS]; int idim, ndim = PyArray_NDIM(arr); if (dtype == NULL) { dtype = PyArray_DTYPE(arr); Py_INCREF(dtype); } PyArray_CreateSortedStridePerm(PyArray_NDIM(arr), PyArray_STRIDES(arr), strideperm); /* Build the new strides and shape */ stride = dtype->elsize; memcpy(shape, arr_shape, ndim * sizeof(shape[0])); for (idim = ndim-1; idim >= 0; --idim) { npy_intp i_perm = strideperm[idim].perm; if (axis_flags[i_perm]) { strides[i_perm] = 0; shape[i_perm] = 1; } else { strides[i_perm] = stride; stride *= shape[i_perm]; } } /* Finally, allocate the array */ return (PyArrayObject *)PyArray_NewFromDescr( subok ? Py_TYPE(arr) : &PyArray_Type, dtype, ndim, shape, strides, NULL, 0, subok ? (PyObject *)arr : NULL); } /* * Conforms an output parameter 'out' to have 'ndim' dimensions * with dimensions of size one added in the appropriate places * indicated by 'axis_flags'. * * The return value is a view into 'out'. */ static PyArrayObject * conform_reduce_result(int ndim, npy_bool *axis_flags, PyArrayObject *out, int keepdims, const char *funcname) { npy_intp strides[NPY_MAXDIMS], shape[NPY_MAXDIMS]; npy_intp *strides_out = PyArray_STRIDES(out); npy_intp *shape_out = PyArray_DIMS(out); int idim, idim_out, ndim_out = PyArray_NDIM(out); PyArray_Descr *dtype; PyArrayObject_fields *ret; /* * If the 'keepdims' parameter is true, do a simpler validation and * return a new reference to 'out'. */ if (keepdims) { if (PyArray_NDIM(out) != ndim) { PyErr_Format(PyExc_ValueError, "output parameter for reduction operation %s " "has the wrong number of dimensions (must match " "the operand's when keepdims=True)", funcname); return NULL; } for (idim = 0; idim < ndim; ++idim) { if (axis_flags[idim]) { if (shape_out[idim] != 1) { PyErr_Format(PyExc_ValueError, "output parameter for reduction operation %s " "has a reduction dimension not equal to one " "(required when keepdims=True)", funcname); return NULL; } } } Py_INCREF(out); return out; } /* Construct the strides and shape */ idim_out = 0; for (idim = 0; idim < ndim; ++idim) { if (axis_flags[idim]) { strides[idim] = 0; shape[idim] = 1; } else { if (idim_out >= ndim_out) { PyErr_Format(PyExc_ValueError, "output parameter for reduction operation %s " "does not have enough dimensions", funcname); return NULL; } strides[idim] = strides_out[idim_out]; shape[idim] = shape_out[idim_out]; ++idim_out; } } if (idim_out != ndim_out) { PyErr_Format(PyExc_ValueError, "output parameter for reduction operation %s " "has too many dimensions", funcname); return NULL; } /* Allocate the view */ dtype = PyArray_DESCR(out); Py_INCREF(dtype); ret = (PyArrayObject_fields *)PyArray_NewFromDescr(&PyArray_Type, dtype, ndim, shape, strides, PyArray_DATA(out), PyArray_FLAGS(out), NULL); if (ret == NULL) { return NULL; } Py_INCREF(out); if (PyArray_SetBaseObject((PyArrayObject *)ret, (PyObject *)out) < 0) { Py_DECREF(ret); return NULL; } return (PyArrayObject *)ret; } /* * Creates a result for reducing 'operand' along the axes specified * in 'axis_flags'. If 'dtype' isn't NULL, this function steals a * reference to 'dtype'. * * If 'out' isn't NULL, this function creates a view conforming * to the number of dimensions of 'operand', adding a singleton dimension * for each reduction axis specified. In this case, 'dtype' is ignored * (but its reference is still stolen), and the caller must handle any * type conversion/validity check for 'out' * * If 'subok' is true, creates a result with the subtype of 'operand', * otherwise creates on with the base ndarray class. * * If 'out' is NULL, it allocates a new array whose shape matches that of * 'operand', except for at the reduction axes. If 'dtype' is NULL, the dtype * of 'operand' is used for the result. */ NPY_NO_EXPORT PyArrayObject * PyArray_CreateReduceResult(PyArrayObject *operand, PyArrayObject *out, PyArray_Descr *dtype, npy_bool *axis_flags, int keepdims, int subok, const char *funcname) { PyArrayObject *result; if (out == NULL) { /* This function steals the reference to 'dtype' */ result = allocate_reduce_result(operand, axis_flags, dtype, subok); } else { /* Steal the dtype reference */ Py_XDECREF(dtype); result = conform_reduce_result(PyArray_NDIM(operand), axis_flags, out, keepdims, funcname); } return result; } /* * Checks that there are only zero or one dimensions selected in 'axis_flags', * and raises an error about a non-reorderable reduction if not. */ static int check_nonreorderable_axes(int ndim, npy_bool *axis_flags, const char *funcname) { int idim, single_axis = 0; for (idim = 0; idim < ndim; ++idim) { if (axis_flags[idim]) { if (single_axis) { PyErr_Format(PyExc_ValueError, "reduction operation '%s' is not reorderable, " "so only one axis may be specified", funcname); return -1; } else { single_axis = 1; } } } return 0; } /* * This function initializes a result array for a reduction operation * which has no identity. This means it needs to copy the first element * it sees along the reduction axes to result, then return a view of * the operand which excludes that element. * * If a reduction has an identity, such as 0 or 1, the result should be * initialized by calling PyArray_AssignZero(result, NULL, NULL) or * PyArray_AssignOne(result, NULL, NULL), because this function raises an * exception when there are no elements to reduce (which appropriate iff the * reduction operation has no identity). * * This means it copies the subarray indexed at zero along each reduction axis * into 'result', then returns a view into 'operand' excluding those copied * elements. * * result : The array into which the result is computed. This must have * the same number of dimensions as 'operand', but for each * axis i where 'axis_flags[i]' is True, it has a single element. * operand : The array being reduced. * axis_flags : An array of boolean flags, one for each axis of 'operand'. * When a flag is True, it indicates to reduce along that axis. * reorderable : If True, the reduction being done is reorderable, which * means specifying multiple axes of reduction at once is ok, * and the reduction code may calculate the reduction in an * arbitrary order. The calculation may be reordered because * of cache behavior or multithreading requirements. * out_skip_first_count : This gets populated with the number of first-visit * elements that should be skipped during the * iteration loop. * funcname : The name of the reduction operation, for the purpose of * better quality error messages. For example, "numpy.max" * would be a good name for NumPy's max function. * * Returns a view which contains the remaining elements on which to do * the reduction. */ NPY_NO_EXPORT PyArrayObject * PyArray_InitializeReduceResult( PyArrayObject *result, PyArrayObject *operand, npy_bool *axis_flags, int reorderable, npy_intp *out_skip_first_count, const char *funcname) { npy_intp *strides, *shape, shape_orig[NPY_MAXDIMS]; PyArrayObject *op_view = NULL; int idim, ndim, nreduce_axes; ndim = PyArray_NDIM(operand); /* Default to no skipping first-visit elements in the iteration */ *out_skip_first_count = 0; /* * If this reduction is non-reorderable, make sure there are * only 0 or 1 axes in axis_flags. */ if (!reorderable && check_nonreorderable_axes(ndim, axis_flags, funcname) < 0) { return NULL; } /* Take a view into 'operand' which we can modify. */ op_view = (PyArrayObject *)PyArray_View(operand, NULL, &PyArray_Type); if (op_view == NULL) { return NULL; } /* * Now copy the subarray of the first element along each reduction axis, * then return a view to the rest. * * Adjust the shape to only look at the first element along * any of the reduction axes. We count the number of reduction axes * at the same time. */ shape = PyArray_SHAPE(op_view); nreduce_axes = 0; memcpy(shape_orig, shape, ndim * sizeof(npy_intp)); for (idim = 0; idim < ndim; ++idim) { if (axis_flags[idim]) { if (shape[idim] == 0) { PyErr_Format(PyExc_ValueError, "zero-size array to reduction operation %s " "which has no identity", funcname); Py_DECREF(op_view); return NULL; } shape[idim] = 1; ++nreduce_axes; } } /* * Copy the elements into the result to start. */ if (PyArray_CopyInto(result, op_view) < 0) { Py_DECREF(op_view); return NULL; } /* * If there is one reduction axis, adjust the view's * shape to only look at the remaining elements */ if (nreduce_axes == 1) { strides = PyArray_STRIDES(op_view); for (idim = 0; idim < ndim; ++idim) { if (axis_flags[idim]) { shape[idim] = shape_orig[idim] - 1; ((PyArrayObject_fields *)op_view)->data += strides[idim]; } } } /* If there are zero reduction axes, make the view empty */ else if (nreduce_axes == 0) { for (idim = 0; idim < ndim; ++idim) { shape[idim] = 0; } } /* * Otherwise iterate over the whole operand, but tell the inner loop * to skip the elements we already copied by setting the skip_first_count. */ else { *out_skip_first_count = PyArray_SIZE(result); Py_DECREF(op_view); Py_INCREF(operand); op_view = operand; } return op_view; } /* * This function executes all the standard NumPy reduction function * boilerplate code, just calling assign_identity and the appropriate * inner loop function where necessary. * * operand : The array to be reduced. * out : NULL, or the array into which to place the result. * wheremask : NOT YET SUPPORTED, but this parameter is placed here * so that support can be added in the future without breaking * API compatibility. Pass in NULL. * operand_dtype : The dtype the inner loop expects for the operand. * result_dtype : The dtype the inner loop expects for the result. * casting : The casting rule to apply to the operands. * axis_flags : Flags indicating the reduction axes of 'operand'. * reorderable : If True, the reduction being done is reorderable, which * means specifying multiple axes of reduction at once is ok, * and the reduction code may calculate the reduction in an * arbitrary order. The calculation may be reordered because * of cache behavior or multithreading requirements. * keepdims : If true, leaves the reduction dimensions in the result * with size one. * subok : If true, the result uses the subclass of operand, otherwise * it is always a base class ndarray. * assign_identity : If NULL, PyArray_InitializeReduceResult is used, otherwise * this function is called to initialize the result to * the reduction's unit. * loop : The loop which does the reduction. * data : Data which is passed to assign_identity and the inner loop. * buffersize : Buffer size for the iterator. For the default, pass in 0. * funcname : The name of the reduction function, for error messages. * * TODO FIXME: if you squint, this is essentially an second independent * implementation of generalized ufuncs with signature (i)->(), plus a few * extra bells and whistles. (Indeed, as far as I can tell, it was originally * split out to support a fancy version of count_nonzero... which is not * actually a reduction function at all, it's just a (i)->() function!) So * probably these two implementation should be merged into one. (In fact it * would be quite nice to support axis= and keepdims etc. for arbitrary * generalized ufuncs!) */ NPY_NO_EXPORT PyArrayObject * PyUFunc_ReduceWrapper(PyArrayObject *operand, PyArrayObject *out, PyArrayObject *wheremask, PyArray_Descr *operand_dtype, PyArray_Descr *result_dtype, NPY_CASTING casting, npy_bool *axis_flags, int reorderable, int keepdims, int subok, PyArray_AssignReduceIdentityFunc *assign_identity, PyArray_ReduceLoopFunc *loop, void *data, npy_intp buffersize, const char *funcname) { PyArrayObject *result = NULL, *op_view = NULL; npy_intp skip_first_count = 0; /* Iterator parameters */ NpyIter *iter = NULL; PyArrayObject *op[2]; PyArray_Descr *op_dtypes[2]; npy_uint32 flags, op_flags[2]; /* Validate that the parameters for future expansion are NULL */ if (wheremask != NULL) { PyErr_SetString(PyExc_RuntimeError, "Reduce operations in NumPy do not yet support " "a where mask"); return NULL; } /* * This either conforms 'out' to the ndim of 'operand', or allocates * a new array appropriate for this reduction. */ Py_INCREF(result_dtype); result = PyArray_CreateReduceResult(operand, out, result_dtype, axis_flags, keepdims, subok, funcname); if (result == NULL) { goto fail; } /* * Initialize the result to the reduction unit if possible, * otherwise copy the initial values and get a view to the rest. */ if (assign_identity != NULL) { /* * If this reduction is non-reorderable, make sure there are * only 0 or 1 axes in axis_flags. */ if (!reorderable && check_nonreorderable_axes(PyArray_NDIM(operand), axis_flags, funcname) < 0) { goto fail; } if (assign_identity(result, data) < 0) { goto fail; } op_view = operand; Py_INCREF(op_view); } else { op_view = PyArray_InitializeReduceResult(result, operand, axis_flags, reorderable, &skip_first_count, funcname); if (op_view == NULL) { goto fail; } /* empty op_view signals no reduction; but 0-d arrays cannot be empty */ if ((PyArray_SIZE(op_view) == 0) || (PyArray_NDIM(operand) == 0)) { Py_DECREF(op_view); op_view = NULL; goto finish; } } /* Set up the iterator */ op[0] = result; op[1] = op_view; op_dtypes[0] = result_dtype; op_dtypes[1] = operand_dtype; flags = NPY_ITER_BUFFERED | NPY_ITER_EXTERNAL_LOOP | NPY_ITER_GROWINNER | NPY_ITER_DONT_NEGATE_STRIDES | NPY_ITER_ZEROSIZE_OK | NPY_ITER_REDUCE_OK | NPY_ITER_REFS_OK; op_flags[0] = NPY_ITER_READWRITE | NPY_ITER_ALIGNED | NPY_ITER_NO_SUBTYPE; op_flags[1] = NPY_ITER_READONLY | NPY_ITER_ALIGNED; iter = NpyIter_AdvancedNew(2, op, flags, NPY_KEEPORDER, casting, op_flags, op_dtypes, -1, NULL, NULL, buffersize); if (iter == NULL) { goto fail; } if (NpyIter_GetIterSize(iter) != 0) { NpyIter_IterNextFunc *iternext; char **dataptr; npy_intp *strideptr; npy_intp *countptr; int needs_api; iternext = NpyIter_GetIterNext(iter, NULL); if (iternext == NULL) { goto fail; } dataptr = NpyIter_GetDataPtrArray(iter); strideptr = NpyIter_GetInnerStrideArray(iter); countptr = NpyIter_GetInnerLoopSizePtr(iter); needs_api = NpyIter_IterationNeedsAPI(iter); /* Straightforward reduction */ if (loop == NULL) { PyErr_Format(PyExc_RuntimeError, "reduction operation %s did not supply an " "inner loop function", funcname); goto fail; } if (loop(iter, dataptr, strideptr, countptr, iternext, needs_api, skip_first_count, data) < 0) { goto fail; } } NpyIter_Deallocate(iter); Py_DECREF(op_view); finish: /* Strip out the extra 'one' dimensions in the result */ if (out == NULL) { if (!keepdims) { PyArray_RemoveAxesInPlace(result, axis_flags); } } else { Py_DECREF(result); result = out; Py_INCREF(result); } return result; fail: Py_XDECREF(result); Py_XDECREF(op_view); if (iter != NULL) { NpyIter_Deallocate(iter); } return NULL; } numpy-1.8.2/numpy/core/src/umath/ufunc_object.c0000664000175100017510000051471112370216243022654 0ustar vagrantvagrant00000000000000/* * Python Universal Functions Object -- Math for all types, plus fast * arrays math * * Full description * * This supports mathematical (and Boolean) functions on arrays and other python * objects. Math on large arrays of basic C types is rather efficient. * * Travis E. Oliphant 2005, 2006 oliphant@ee.byu.edu (oliphant.travis@ieee.org) * Brigham Young University * * based on the * * Original Implementation: * Copyright (c) 1995, 1996, 1997 Jim Hugunin, hugunin@mit.edu * * with inspiration and code from * Numarray * Space Science Telescope Institute * J. Todd Miller * Perry Greenfield * Rick White * */ #define _UMATHMODULE #define NPY_NO_DEPRECATED_API NPY_API_VERSION #include "Python.h" #include "npy_config.h" #ifdef ENABLE_SEPARATE_COMPILATION #define PY_ARRAY_UNIQUE_SYMBOL _npy_umathmodule_ARRAY_API #define NO_IMPORT_ARRAY #endif #include "npy_pycompat.h" #include "numpy/arrayobject.h" #include "numpy/ufuncobject.h" #include "numpy/arrayscalars.h" #include "lowlevel_strided_loops.h" #include "ufunc_type_resolution.h" #include "reduction.h" #include "ufunc_object.h" /********** PRINTF DEBUG TRACING **************/ #define NPY_UF_DBG_TRACING 0 #if NPY_UF_DBG_TRACING #define NPY_UF_DBG_PRINT(s) {printf("%s", s);fflush(stdout);} #define NPY_UF_DBG_PRINT1(s, p1) {printf((s), (p1));fflush(stdout);} #define NPY_UF_DBG_PRINT2(s, p1, p2) {printf(s, p1, p2);fflush(stdout);} #define NPY_UF_DBG_PRINT3(s, p1, p2, p3) {printf(s, p1, p2, p3);fflush(stdout);} #else #define NPY_UF_DBG_PRINT(s) #define NPY_UF_DBG_PRINT1(s, p1) #define NPY_UF_DBG_PRINT2(s, p1, p2) #define NPY_UF_DBG_PRINT3(s, p1, p2, p3) #endif /**********************************************/ /********************/ #define USE_USE_DEFAULTS 1 /********************/ /* ---------------------------------------------------------------- */ static int _does_loop_use_arrays(void *data); static int assign_reduce_identity_zero(PyArrayObject *result); static int assign_reduce_identity_one(PyArrayObject *result); /* * fpstatus is the ufunc_formatted hardware status * errmask is the handling mask specified by the user. * errobj is a Python object with (string, callable object or None) * or NULL */ /* * 2. for each of the flags * determine whether to ignore, warn, raise error, or call Python function. * If ignore, do nothing * If warn, print a warning and continue * If raise return an error * If call, call a user-defined function with string */ static int _error_handler(int method, PyObject *errobj, char *errtype, int retstatus, int *first) { PyObject *pyfunc, *ret, *args; char *name = PyBytes_AS_STRING(PyTuple_GET_ITEM(errobj,0)); char msg[100]; NPY_ALLOW_C_API_DEF; NPY_ALLOW_C_API; switch(method) { case UFUNC_ERR_WARN: PyOS_snprintf(msg, sizeof(msg), "%s encountered in %s", errtype, name); if (PyErr_Warn(PyExc_RuntimeWarning, msg) < 0) { goto fail; } break; case UFUNC_ERR_RAISE: PyErr_Format(PyExc_FloatingPointError, "%s encountered in %s", errtype, name); goto fail; case UFUNC_ERR_CALL: pyfunc = PyTuple_GET_ITEM(errobj, 1); if (pyfunc == Py_None) { PyErr_Format(PyExc_NameError, "python callback specified for %s (in " \ " %s) but no function found.", errtype, name); goto fail; } args = Py_BuildValue("NN", PyUString_FromString(errtype), PyInt_FromLong((long) retstatus)); if (args == NULL) { goto fail; } ret = PyObject_CallObject(pyfunc, args); Py_DECREF(args); if (ret == NULL) { goto fail; } Py_DECREF(ret); break; case UFUNC_ERR_PRINT: if (*first) { fprintf(stderr, "Warning: %s encountered in %s\n", errtype, name); *first = 0; } break; case UFUNC_ERR_LOG: if (first) { *first = 0; pyfunc = PyTuple_GET_ITEM(errobj, 1); if (pyfunc == Py_None) { PyErr_Format(PyExc_NameError, "log specified for %s (in %s) but no " \ "object with write method found.", errtype, name); goto fail; } PyOS_snprintf(msg, sizeof(msg), "Warning: %s encountered in %s\n", errtype, name); ret = PyObject_CallMethod(pyfunc, "write", "s", msg); if (ret == NULL) { goto fail; } Py_DECREF(ret); } break; } NPY_DISABLE_C_API; return 0; fail: NPY_DISABLE_C_API; return -1; } /*UFUNC_API*/ NPY_NO_EXPORT int PyUFunc_getfperr(void) { int retstatus; UFUNC_CHECK_STATUS(retstatus); return retstatus; } #define HANDLEIT(NAME, str) {if (retstatus & UFUNC_FPE_##NAME) { \ handle = errmask & UFUNC_MASK_##NAME; \ if (handle && \ _error_handler(handle >> UFUNC_SHIFT_##NAME, \ errobj, str, retstatus, first) < 0) \ return -1; \ }} /*UFUNC_API*/ NPY_NO_EXPORT int PyUFunc_handlefperr(int errmask, PyObject *errobj, int retstatus, int *first) { int handle; if (errmask && retstatus) { HANDLEIT(DIVIDEBYZERO, "divide by zero"); HANDLEIT(OVERFLOW, "overflow"); HANDLEIT(UNDERFLOW, "underflow"); HANDLEIT(INVALID, "invalid value"); } return 0; } #undef HANDLEIT /*UFUNC_API*/ NPY_NO_EXPORT int PyUFunc_checkfperr(int errmask, PyObject *errobj, int *first) { int retstatus; /* 1. check hardware flag --- this is platform dependent code */ retstatus = PyUFunc_getfperr(); return PyUFunc_handlefperr(errmask, errobj, retstatus, first); } /* Checking the status flag clears it */ /*UFUNC_API*/ NPY_NO_EXPORT void PyUFunc_clearfperr() { PyUFunc_getfperr(); } /* * This function analyzes the input arguments * and determines an appropriate __array_prepare__ function to call * for the outputs. * * If an output argument is provided, then it is prepped * with its own __array_prepare__ not with the one determined by * the input arguments. * * if the provided output argument is already an ndarray, * the prepping function is None (which means no prepping will * be done --- not even PyArray_Return). * * A NULL is placed in output_prep for outputs that * should just have PyArray_Return called. */ static void _find_array_prepare(PyObject *args, PyObject *kwds, PyObject **output_prep, int nin, int nout) { Py_ssize_t nargs; int i; int np = 0; PyObject *with_prep[NPY_MAXARGS], *preps[NPY_MAXARGS]; PyObject *obj, *prep = NULL; /* If a 'subok' parameter is passed and isn't True, don't wrap */ if (kwds != NULL && (obj = PyDict_GetItemString(kwds, "subok")) != NULL) { if (obj != Py_True) { for (i = 0; i < nout; i++) { output_prep[i] = NULL; } return; } } nargs = PyTuple_GET_SIZE(args); for (i = 0; i < nin; i++) { obj = PyTuple_GET_ITEM(args, i); if (PyArray_CheckExact(obj) || PyArray_IsAnyScalar(obj)) { continue; } prep = PyObject_GetAttrString(obj, "__array_prepare__"); if (prep) { if (PyCallable_Check(prep)) { with_prep[np] = obj; preps[np] = prep; ++np; } else { Py_DECREF(prep); prep = NULL; } } else { PyErr_Clear(); } } if (np > 0) { /* If we have some preps defined, find the one of highest priority */ prep = preps[0]; if (np > 1) { double maxpriority = PyArray_GetPriority(with_prep[0], NPY_PRIORITY); for (i = 1; i < np; ++i) { double priority = PyArray_GetPriority(with_prep[i], NPY_PRIORITY); if (priority > maxpriority) { maxpriority = priority; Py_DECREF(prep); prep = preps[i]; } else { Py_DECREF(preps[i]); } } } } /* * Here prep is the prepping function determined from the * input arrays (could be NULL). * * For all the output arrays decide what to do. * * 1) Use the prep function determined from the input arrays * This is the default if the output array is not * passed in. * * 2) Use the __array_prepare__ method of the output object. * This is special cased for * exact ndarray so that no PyArray_Return is * done in that case. */ for (i = 0; i < nout; i++) { int j = nin + i; int incref = 1; output_prep[i] = prep; obj = NULL; if (j < nargs) { obj = PyTuple_GET_ITEM(args, j); /* Output argument one may also be in a keyword argument */ if (i == 0 && obj == Py_None && kwds != NULL) { obj = PyDict_GetItemString(kwds, "out"); } } /* Output argument one may also be in a keyword argument */ else if (i == 0 && kwds != NULL) { obj = PyDict_GetItemString(kwds, "out"); } if (obj != Py_None && obj != NULL) { if (PyArray_CheckExact(obj)) { /* None signals to not call any wrapping */ output_prep[i] = Py_None; } else { PyObject *oprep = PyObject_GetAttrString(obj, "__array_prepare__"); incref = 0; if (!(oprep) || !(PyCallable_Check(oprep))) { Py_XDECREF(oprep); oprep = prep; incref = 1; PyErr_Clear(); } output_prep[i] = oprep; } } if (incref) { Py_XINCREF(output_prep[i]); } } Py_XDECREF(prep); return; } #if USE_USE_DEFAULTS==1 static int PyUFunc_NUM_NODEFAULTS = 0; #endif static PyObject *PyUFunc_PYVALS_NAME = NULL; /* * Extracts some values from the global pyvals tuple. * ref - should hold the global tuple * name - is the name of the ufunc (ufuncobj->name) * bufsize - receives the buffer size to use * errmask - receives the bitmask for error handling * errobj - receives the python object to call with the error, * if an error handling method is 'call' */ static int _extract_pyvals(PyObject *ref, char *name, int *bufsize, int *errmask, PyObject **errobj) { PyObject *retval; *errobj = NULL; if (!PyList_Check(ref) || (PyList_GET_SIZE(ref)!=3)) { PyErr_Format(PyExc_TypeError, "%s must be a length 3 list.", UFUNC_PYVALS_NAME); return -1; } *bufsize = PyInt_AsLong(PyList_GET_ITEM(ref, 0)); if ((*bufsize == -1) && PyErr_Occurred()) { return -1; } if ((*bufsize < NPY_MIN_BUFSIZE) || (*bufsize > NPY_MAX_BUFSIZE) || (*bufsize % 16 != 0)) { PyErr_Format(PyExc_ValueError, "buffer size (%d) is not in range " "(%"NPY_INTP_FMT" - %"NPY_INTP_FMT") or not a multiple of 16", *bufsize, (npy_intp) NPY_MIN_BUFSIZE, (npy_intp) NPY_MAX_BUFSIZE); return -1; } *errmask = PyInt_AsLong(PyList_GET_ITEM(ref, 1)); if (*errmask < 0) { if (PyErr_Occurred()) { return -1; } PyErr_Format(PyExc_ValueError, "invalid error mask (%d)", *errmask); return -1; } retval = PyList_GET_ITEM(ref, 2); if (retval != Py_None && !PyCallable_Check(retval)) { PyObject *temp; temp = PyObject_GetAttrString(retval, "write"); if (temp == NULL || !PyCallable_Check(temp)) { PyErr_SetString(PyExc_TypeError, "python object must be callable or have " \ "a callable write method"); Py_XDECREF(temp); return -1; } Py_DECREF(temp); } *errobj = Py_BuildValue("NO", PyBytes_FromString(name), retval); if (*errobj == NULL) { return -1; } return 0; } /*UFUNC_API * * On return, if errobj is populated with a non-NULL value, the caller * owns a new reference to errobj. */ NPY_NO_EXPORT int PyUFunc_GetPyValues(char *name, int *bufsize, int *errmask, PyObject **errobj) { PyObject *thedict; PyObject *ref = NULL; #if USE_USE_DEFAULTS==1 if (PyUFunc_NUM_NODEFAULTS != 0) { #endif if (PyUFunc_PYVALS_NAME == NULL) { PyUFunc_PYVALS_NAME = PyUString_InternFromString(UFUNC_PYVALS_NAME); } thedict = PyThreadState_GetDict(); if (thedict == NULL) { thedict = PyEval_GetBuiltins(); } ref = PyDict_GetItem(thedict, PyUFunc_PYVALS_NAME); #if USE_USE_DEFAULTS==1 } #endif if (ref == NULL) { *errmask = UFUNC_ERR_DEFAULT; *errobj = Py_BuildValue("NO", PyBytes_FromString(name), Py_None); *bufsize = NPY_BUFSIZE; return 0; } return _extract_pyvals(ref, name, bufsize, errmask, errobj); } #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) { _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); return 0; } #undef _GETATTR_ /* Return the position of next non-white-space char in the string */ static int _next_non_white_space(const char* str, int offset) { int ret = offset; while (str[ret] == ' ' || str[ret] == '\t') { ret++; } return ret; } static int _is_alpha_underscore(char ch) { return (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || ch == '_'; } static int _is_alnum_underscore(char ch) { return _is_alpha_underscore(ch) || (ch >= '0' && ch <= '9'); } /* * Return the ending position of a variable name */ static int _get_end_of_name(const char* str, int offset) { int ret = offset; while (_is_alnum_underscore(str[ret])) { ret++; } return ret; } /* * Returns 1 if the dimension names pointed by s1 and s2 are the same, * otherwise returns 0. */ static int _is_same_name(const char* s1, const char* s2) { while (_is_alnum_underscore(*s1) && _is_alnum_underscore(*s2)) { if (*s1 != *s2) { return 0; } s1++; s2++; } return !_is_alnum_underscore(*s1) && !_is_alnum_underscore(*s2); } /* * Sets core_num_dim_ix, core_num_dims, core_dim_ixs, core_offsets, * and core_signature in PyUFuncObject "ufunc". Returns 0 unless an * error occured. */ static int _parse_signature(PyUFuncObject *ufunc, const char *signature) { size_t len; char const **var_names; int nd = 0; /* number of dimension of the current argument */ int cur_arg = 0; /* index into core_num_dims&core_offsets */ int cur_core_dim = 0; /* index into core_dim_ixs */ int i = 0; char *parse_error = NULL; if (signature == NULL) { PyErr_SetString(PyExc_RuntimeError, "_parse_signature with NULL signature"); return -1; } len = strlen(signature); ufunc->core_signature = PyArray_malloc(sizeof(char) * (len+1)); if (ufunc->core_signature) { strcpy(ufunc->core_signature, signature); } /* Allocate sufficient memory to store pointers to all dimension names */ var_names = PyArray_malloc(sizeof(char const*) * len); if (var_names == NULL) { PyErr_NoMemory(); return -1; } ufunc->core_enabled = 1; ufunc->core_num_dim_ix = 0; ufunc->core_num_dims = PyArray_malloc(sizeof(int) * ufunc->nargs); ufunc->core_dim_ixs = PyArray_malloc(sizeof(int) * len); /* shrink this later */ ufunc->core_offsets = PyArray_malloc(sizeof(int) * ufunc->nargs); if (ufunc->core_num_dims == NULL || ufunc->core_dim_ixs == NULL || ufunc->core_offsets == NULL) { PyErr_NoMemory(); goto fail; } i = _next_non_white_space(signature, 0); while (signature[i] != '\0') { /* loop over input/output arguments */ if (cur_arg == ufunc->nin) { /* expect "->" */ if (signature[i] != '-' || signature[i+1] != '>') { parse_error = "expect '->'"; goto fail; } i = _next_non_white_space(signature, i + 2); } /* * parse core dimensions of one argument, * e.g. "()", "(i)", or "(i,j)" */ if (signature[i] != '(') { parse_error = "expect '('"; goto fail; } i = _next_non_white_space(signature, i + 1); while (signature[i] != ')') { /* loop over core dimensions */ int j = 0; if (!_is_alpha_underscore(signature[i])) { parse_error = "expect dimension name"; goto fail; } while (j < ufunc->core_num_dim_ix) { if (_is_same_name(signature+i, var_names[j])) { break; } j++; } if (j >= ufunc->core_num_dim_ix) { var_names[j] = signature+i; ufunc->core_num_dim_ix++; } ufunc->core_dim_ixs[cur_core_dim] = j; cur_core_dim++; nd++; i = _get_end_of_name(signature, i); i = _next_non_white_space(signature, i); if (signature[i] != ',' && signature[i] != ')') { parse_error = "expect ',' or ')'"; goto fail; } if (signature[i] == ',') { i = _next_non_white_space(signature, i + 1); if (signature[i] == ')') { parse_error = "',' must not be followed by ')'"; goto fail; } } } ufunc->core_num_dims[cur_arg] = nd; ufunc->core_offsets[cur_arg] = cur_core_dim-nd; cur_arg++; nd = 0; i = _next_non_white_space(signature, i + 1); if (cur_arg != ufunc->nin && cur_arg != ufunc->nargs) { /* * The list of input arguments (or output arguments) was * only read partially */ if (signature[i] != ',') { parse_error = "expect ','"; goto fail; } i = _next_non_white_space(signature, i + 1); } } if (cur_arg != ufunc->nargs) { parse_error = "incomplete signature: not all arguments found"; goto fail; } ufunc->core_dim_ixs = PyArray_realloc(ufunc->core_dim_ixs, sizeof(int)*cur_core_dim); /* check for trivial core-signature, e.g. "(),()->()" */ if (cur_core_dim == 0) { ufunc->core_enabled = 0; } PyArray_free((void*)var_names); return 0; fail: PyArray_free((void*)var_names); if (parse_error) { char *buf = PyArray_malloc(sizeof(char) * (len + 200)); if (buf) { sprintf(buf, "%s at position %d in \"%s\"", parse_error, i, signature); PyErr_SetString(PyExc_ValueError, signature); PyArray_free(buf); } else { PyErr_NoMemory(); } } return -1; } /********* GENERIC UFUNC USING ITERATOR *********/ /* * Parses the positional and keyword arguments for a generic ufunc call. * * Note that if an error is returned, the caller must free the * non-zero references in out_op. This * function does not do its own clean-up. */ static int get_ufunc_arguments(PyUFuncObject *ufunc, PyObject *args, PyObject *kwds, PyArrayObject **out_op, NPY_ORDER *out_order, NPY_CASTING *out_casting, PyObject **out_extobj, PyObject **out_typetup, int *out_subok, PyArrayObject **out_wheremask) { int i, nargs, nin = ufunc->nin; PyObject *obj, *context; PyObject *str_key_obj = NULL; char *ufunc_name; int type_num; int any_flexible = 0, any_object = 0, any_flexible_userloops = 0; ufunc_name = ufunc->name ? ufunc->name : ""; *out_extobj = NULL; *out_typetup = NULL; if (out_wheremask != NULL) { *out_wheremask = NULL; } /* Check number of arguments */ nargs = PyTuple_Size(args); if ((nargs < nin) || (nargs > ufunc->nargs)) { PyErr_SetString(PyExc_ValueError, "invalid number of arguments"); return -1; } /* Get input arguments */ for (i = 0; i < nin; ++i) { obj = PyTuple_GET_ITEM(args, i); if (PyArray_Check(obj)) { out_op[i] = (PyArrayObject *)PyArray_FromArray(obj,NULL,0); } else { if (!PyArray_IsScalar(obj, Generic)) { /* * TODO: There should be a comment here explaining what * context does. */ context = Py_BuildValue("OOi", ufunc, args, i); if (context == NULL) { return -1; } } else { context = NULL; } out_op[i] = (PyArrayObject *)PyArray_FromAny(obj, NULL, 0, 0, 0, context); Py_XDECREF(context); } if (out_op[i] == NULL) { return -1; } type_num = PyArray_DESCR(out_op[i])->type_num; if (!any_flexible && PyTypeNum_ISFLEXIBLE(type_num)) { any_flexible = 1; } if (!any_object && PyTypeNum_ISOBJECT(type_num)) { any_object = 1; } /* * If any operand is a flexible dtype, check to see if any * struct dtype ufuncs are registered. A ufunc has been registered * for a struct dtype if ufunc's arg_dtypes array is not NULL. */ if (PyTypeNum_ISFLEXIBLE(type_num) && !any_flexible_userloops && ufunc->userloops != NULL) { PyUFunc_Loop1d *funcdata; PyObject *key, *obj; key = PyInt_FromLong(type_num); if (key == NULL) { continue; } obj = PyDict_GetItem(ufunc->userloops, key); Py_DECREF(key); if (obj == NULL) { continue; } funcdata = (PyUFunc_Loop1d *)NpyCapsule_AsVoidPtr(obj); while (funcdata != NULL) { if (funcdata->arg_dtypes != NULL) { any_flexible_userloops = 1; break; } funcdata = funcdata->next; } } } /* * Indicate not implemented if there are flexible objects (structured * type or string) but no object types and no registered struct * dtype ufuncs. * * Not sure - adding this increased to 246 errors, 150 failures. */ if (any_flexible && !any_flexible_userloops && !any_object) { return -2; } /* Get positional output arguments */ for (i = nin; i < nargs; ++i) { obj = PyTuple_GET_ITEM(args, i); /* Translate None to NULL */ if (obj == Py_None) { continue; } /* If it's an array, can use it */ if (PyArray_Check(obj)) { if (PyArray_FailUnlessWriteable((PyArrayObject *)obj, "output array") < 0) { return -1; } Py_INCREF(obj); out_op[i] = (PyArrayObject *)obj; } else { PyErr_SetString(PyExc_TypeError, "return arrays must be " "of ArrayType"); return -1; } } /* * Get keyword output and other arguments. * Raise an error if anything else is present in the * keyword dictionary. */ if (kwds != NULL) { PyObject *key, *value; Py_ssize_t pos = 0; while (PyDict_Next(kwds, &pos, &key, &value)) { Py_ssize_t length = 0; char *str = NULL; int bad_arg = 1; #if defined(NPY_PY3K) Py_XDECREF(str_key_obj); str_key_obj = PyUnicode_AsASCIIString(key); if (str_key_obj != NULL) { key = str_key_obj; } #endif if (PyBytes_AsStringAndSize(key, &str, &length) == -1) { PyErr_SetString(PyExc_TypeError, "invalid keyword argument"); goto fail; } switch (str[0]) { case 'c': /* Provides a policy for allowed casting */ if (strncmp(str,"casting",7) == 0) { if (!PyArray_CastingConverter(value, out_casting)) { goto fail; } bad_arg = 0; } break; case 'd': /* Another way to specify 'sig' */ if (strncmp(str,"dtype",5) == 0) { /* Allow this parameter to be None */ PyArray_Descr *dtype; if (!PyArray_DescrConverter2(value, &dtype)) { goto fail; } if (dtype != NULL) { if (*out_typetup != NULL) { PyErr_SetString(PyExc_RuntimeError, "cannot specify both 'sig' and 'dtype'"); goto fail; } *out_typetup = Py_BuildValue("(N)", dtype); } bad_arg = 0; } break; case 'e': /* * Overrides the global parameters buffer size, * error mask, and error object */ if (strncmp(str,"extobj",6) == 0) { *out_extobj = value; bad_arg = 0; } break; case 'o': /* First output may be specified as a keyword parameter */ if (strncmp(str,"out",3) == 0) { if (out_op[nin] != NULL) { PyErr_SetString(PyExc_ValueError, "cannot specify 'out' as both a " "positional and keyword argument"); goto fail; } if (PyArray_Check(value)) { const char *name = "output array"; PyArrayObject *value_arr = (PyArrayObject *)value; if (PyArray_FailUnlessWriteable(value_arr, name) < 0) { goto fail; } Py_INCREF(value); out_op[nin] = (PyArrayObject *)value; } else { PyErr_SetString(PyExc_TypeError, "return arrays must be " "of ArrayType"); goto fail; } bad_arg = 0; } /* Allows the default output layout to be overridden */ else if (strncmp(str,"order",5) == 0) { if (!PyArray_OrderConverter(value, out_order)) { goto fail; } bad_arg = 0; } break; case 's': /* Allows a specific function inner loop to be selected */ if (strncmp(str,"sig",3) == 0) { if (*out_typetup != NULL) { PyErr_SetString(PyExc_RuntimeError, "cannot specify both 'sig' and 'dtype'"); goto fail; } *out_typetup = value; Py_INCREF(value); bad_arg = 0; } else if (strncmp(str,"subok",5) == 0) { if (!PyBool_Check(value)) { PyErr_SetString(PyExc_TypeError, "'subok' must be a boolean"); goto fail; } *out_subok = (value == Py_True); bad_arg = 0; } break; case 'w': /* * Provides a boolean array 'where=' mask if * out_wheremask is supplied. */ if (out_wheremask != NULL && strncmp(str,"where",5) == 0) { PyArray_Descr *dtype; dtype = PyArray_DescrFromType(NPY_BOOL); if (dtype == NULL) { goto fail; } *out_wheremask = (PyArrayObject *)PyArray_FromAny( value, dtype, 0, 0, 0, NULL); if (*out_wheremask == NULL) { goto fail; } bad_arg = 0; } break; } if (bad_arg) { char *format = "'%s' is an invalid keyword to ufunc '%s'"; PyErr_Format(PyExc_TypeError, format, str, ufunc_name); goto fail; } } } Py_XDECREF(str_key_obj); return 0; fail: Py_XDECREF(str_key_obj); Py_XDECREF(*out_extobj); *out_extobj = NULL; Py_XDECREF(*out_typetup); *out_typetup = NULL; if (out_wheremask != NULL) { Py_XDECREF(*out_wheremask); *out_wheremask = NULL; } return -1; } /* * This checks whether a trivial loop is ok, * making copies of scalar and one dimensional operands if that will * help. * * Returns 1 if a trivial loop is ok, 0 if it is not, and * -1 if there is an error. */ static int check_for_trivial_loop(PyUFuncObject *ufunc, PyArrayObject **op, PyArray_Descr **dtype, npy_intp buffersize) { npy_intp i, nin = ufunc->nin, nop = nin + ufunc->nout; for (i = 0; i < nop; ++i) { /* * If the dtype doesn't match, or the array isn't aligned, * indicate that the trivial loop can't be done. */ if (op[i] != NULL && (!PyArray_ISALIGNED(op[i]) || !PyArray_EquivTypes(dtype[i], PyArray_DESCR(op[i])) )) { /* * If op[j] is a scalar or small one dimensional * array input, make a copy to keep the opportunity * for a trivial loop. */ if (i < nin && (PyArray_NDIM(op[i]) == 0 || (PyArray_NDIM(op[i]) == 1 && PyArray_DIM(op[i],0) <= buffersize))) { PyArrayObject *tmp; Py_INCREF(dtype[i]); tmp = (PyArrayObject *) PyArray_CastToType(op[i], dtype[i], 0); if (tmp == NULL) { return -1; } Py_DECREF(op[i]); op[i] = tmp; } else { return 0; } } } return 1; } static void trivial_two_operand_loop(PyArrayObject **op, PyUFuncGenericFunction innerloop, void *innerloopdata) { char *data[2]; npy_intp count[2], stride[2]; int needs_api; NPY_BEGIN_THREADS_DEF; needs_api = PyDataType_REFCHK(PyArray_DESCR(op[0])) || PyDataType_REFCHK(PyArray_DESCR(op[1])); PyArray_PREPARE_TRIVIAL_PAIR_ITERATION(op[0], op[1], count[0], data[0], data[1], stride[0], stride[1]); count[1] = count[0]; NPY_UF_DBG_PRINT1("two operand loop count %d\n", (int)count[0]); if (!needs_api) { NPY_BEGIN_THREADS_THRESHOLDED(count[0]); } innerloop(data, count, stride, innerloopdata); if (!needs_api) { NPY_END_THREADS; } } static void trivial_three_operand_loop(PyArrayObject **op, PyUFuncGenericFunction innerloop, void *innerloopdata) { char *data[3]; npy_intp count[3], stride[3]; int needs_api; NPY_BEGIN_THREADS_DEF; needs_api = PyDataType_REFCHK(PyArray_DESCR(op[0])) || PyDataType_REFCHK(PyArray_DESCR(op[1])) || PyDataType_REFCHK(PyArray_DESCR(op[2])); PyArray_PREPARE_TRIVIAL_TRIPLE_ITERATION(op[0], op[1], op[2], count[0], data[0], data[1], data[2], stride[0], stride[1], stride[2]); count[1] = count[0]; count[2] = count[0]; NPY_UF_DBG_PRINT1("three operand loop count %d\n", (int)count[0]); if (!needs_api) { NPY_BEGIN_THREADS_THRESHOLDED(count[0]); } innerloop(data, count, stride, innerloopdata); if (!needs_api) { NPY_END_THREADS; } } /* * Calls the given __array_prepare__ function on the operand *op, * substituting it in place if a new array is returned and matches * the old one. * * This requires that the dimensions, strides and data type remain * exactly the same, which may be more strict than before. */ static int prepare_ufunc_output(PyUFuncObject *ufunc, PyArrayObject **op, PyObject *arr_prep, PyObject *arr_prep_args, int i) { if (arr_prep != NULL && arr_prep != Py_None) { PyObject *res; PyArrayObject *arr; res = PyObject_CallFunction(arr_prep, "O(OOi)", *op, ufunc, arr_prep_args, i); if ((res == NULL) || (res == Py_None) || !PyArray_Check(res)) { if (!PyErr_Occurred()){ PyErr_SetString(PyExc_TypeError, "__array_prepare__ must return an " "ndarray or subclass thereof"); } Py_XDECREF(res); return -1; } arr = (PyArrayObject *)res; /* If the same object was returned, nothing to do */ if (arr == *op) { Py_DECREF(arr); } /* If the result doesn't match, throw an error */ else if (PyArray_NDIM(arr) != PyArray_NDIM(*op) || !PyArray_CompareLists(PyArray_DIMS(arr), PyArray_DIMS(*op), PyArray_NDIM(arr)) || !PyArray_CompareLists(PyArray_STRIDES(arr), PyArray_STRIDES(*op), PyArray_NDIM(arr)) || !PyArray_EquivTypes(PyArray_DESCR(arr), PyArray_DESCR(*op))) { PyErr_SetString(PyExc_TypeError, "__array_prepare__ must return an " "ndarray or subclass thereof which is " "otherwise identical to its input"); Py_DECREF(arr); return -1; } /* Replace the op value */ else { Py_DECREF(*op); *op = arr; } } return 0; } static int iterator_loop(PyUFuncObject *ufunc, PyArrayObject **op, PyArray_Descr **dtype, NPY_ORDER order, npy_intp buffersize, PyObject **arr_prep, PyObject *arr_prep_args, PyUFuncGenericFunction innerloop, void *innerloopdata) { npy_intp i, nin = ufunc->nin, nout = ufunc->nout; npy_intp nop = nin + nout; npy_uint32 op_flags[NPY_MAXARGS]; NpyIter *iter; char *baseptrs[NPY_MAXARGS]; int needs_api; NpyIter_IterNextFunc *iternext; char **dataptr; npy_intp *stride; npy_intp *count_ptr; PyArrayObject **op_it; npy_uint32 iter_flags; NPY_BEGIN_THREADS_DEF; /* Set up the flags */ for (i = 0; i < nin; ++i) { op_flags[i] = NPY_ITER_READONLY | NPY_ITER_ALIGNED; /* * If READWRITE flag has been set for this operand, * then clear default READONLY flag */ op_flags[i] |= ufunc->op_flags[i]; if (op_flags[i] & (NPY_ITER_READWRITE | NPY_ITER_WRITEONLY)) { op_flags[i] &= ~NPY_ITER_READONLY; } } for (i = nin; i < nop; ++i) { op_flags[i] = NPY_ITER_WRITEONLY | NPY_ITER_ALIGNED | NPY_ITER_ALLOCATE | NPY_ITER_NO_BROADCAST | NPY_ITER_NO_SUBTYPE; } iter_flags = ufunc->iter_flags | NPY_ITER_EXTERNAL_LOOP | NPY_ITER_REFS_OK | NPY_ITER_ZEROSIZE_OK | NPY_ITER_BUFFERED | NPY_ITER_GROWINNER | NPY_ITER_DELAY_BUFALLOC; /* * Allocate the iterator. Because the types of the inputs * were already checked, we use the casting rule 'unsafe' which * is faster to calculate. */ iter = NpyIter_AdvancedNew(nop, op, iter_flags, order, NPY_UNSAFE_CASTING, op_flags, dtype, -1, NULL, NULL, buffersize); if (iter == NULL) { return -1; } needs_api = NpyIter_IterationNeedsAPI(iter); /* Copy any allocated outputs */ op_it = NpyIter_GetOperandArray(iter); for (i = nin; i < nop; ++i) { if (op[i] == NULL) { op[i] = op_it[i]; Py_INCREF(op[i]); } } /* Call the __array_prepare__ functions where necessary */ for (i = 0; i < nout; ++i) { if (prepare_ufunc_output(ufunc, &op[nin+i], arr_prep[i], arr_prep_args, i) < 0) { NpyIter_Deallocate(iter); return -1; } } /* Only do the loop if the iteration size is non-zero */ if (NpyIter_GetIterSize(iter) != 0) { /* Reset the iterator with the base pointers from the wrapped outputs */ for (i = 0; i < nin; ++i) { baseptrs[i] = PyArray_BYTES(op_it[i]); } for (i = nin; i < nop; ++i) { baseptrs[i] = PyArray_BYTES(op[i]); } if (NpyIter_ResetBasePointers(iter, baseptrs, NULL) != NPY_SUCCEED) { NpyIter_Deallocate(iter); return -1; } /* Get the variables needed for the loop */ iternext = NpyIter_GetIterNext(iter, NULL); if (iternext == NULL) { NpyIter_Deallocate(iter); return -1; } dataptr = NpyIter_GetDataPtrArray(iter); stride = NpyIter_GetInnerStrideArray(iter); count_ptr = NpyIter_GetInnerLoopSizePtr(iter); if (!needs_api) { NPY_BEGIN_THREADS; } /* Execute the loop */ do { NPY_UF_DBG_PRINT1("iterator loop count %d\n", (int)*count_ptr); innerloop(dataptr, count_ptr, stride, innerloopdata); } while (iternext(iter)); if (!needs_api) { NPY_END_THREADS; } } NpyIter_Deallocate(iter); return 0; } /* * trivial_loop_ok - 1 if no alignment, data conversion, etc required * nin - number of inputs * nout - number of outputs * op - the operands (nin + nout of them) * order - the loop execution order/output memory order * buffersize - how big of a buffer to use * arr_prep - the __array_prepare__ functions for the outputs * innerloop - the inner loop function * innerloopdata - data to pass to the inner loop */ static int execute_legacy_ufunc_loop(PyUFuncObject *ufunc, int trivial_loop_ok, PyArrayObject **op, PyArray_Descr **dtypes, NPY_ORDER order, npy_intp buffersize, PyObject **arr_prep, PyObject *arr_prep_args) { npy_intp nin = ufunc->nin, nout = ufunc->nout; PyUFuncGenericFunction innerloop; void *innerloopdata; int needs_api = 0; if (ufunc->legacy_inner_loop_selector(ufunc, dtypes, &innerloop, &innerloopdata, &needs_api) < 0) { return -1; } /* If the loop wants the arrays, provide them. */ if (_does_loop_use_arrays(innerloopdata)) { innerloopdata = (void*)op; } /* First check for the trivial cases that don't need an iterator */ if (trivial_loop_ok) { if (nin == 1 && nout == 1) { if (op[1] == NULL && (order == NPY_ANYORDER || order == NPY_KEEPORDER) && PyArray_TRIVIALLY_ITERABLE(op[0])) { Py_INCREF(dtypes[1]); op[1] = (PyArrayObject *)PyArray_NewFromDescr(&PyArray_Type, dtypes[1], PyArray_NDIM(op[0]), PyArray_DIMS(op[0]), NULL, NULL, PyArray_ISFORTRAN(op[0]) ? NPY_ARRAY_F_CONTIGUOUS : 0, NULL); if (op[1] == NULL) { return -1; } /* Call the __prepare_array__ if necessary */ if (prepare_ufunc_output(ufunc, &op[1], arr_prep[0], arr_prep_args, 0) < 0) { return -1; } NPY_UF_DBG_PRINT("trivial 1 input with allocated output\n"); trivial_two_operand_loop(op, innerloop, innerloopdata); return 0; } else if (op[1] != NULL && PyArray_NDIM(op[1]) >= PyArray_NDIM(op[0]) && PyArray_TRIVIALLY_ITERABLE_PAIR(op[0], op[1])) { /* Call the __prepare_array__ if necessary */ if (prepare_ufunc_output(ufunc, &op[1], arr_prep[0], arr_prep_args, 0) < 0) { return -1; } NPY_UF_DBG_PRINT("trivial 1 input\n"); trivial_two_operand_loop(op, innerloop, innerloopdata); return 0; } } else if (nin == 2 && nout == 1) { if (op[2] == NULL && (order == NPY_ANYORDER || order == NPY_KEEPORDER) && PyArray_TRIVIALLY_ITERABLE_PAIR(op[0], op[1])) { PyArrayObject *tmp; /* * Have to choose the input with more dimensions to clone, as * one of them could be a scalar. */ if (PyArray_NDIM(op[0]) >= PyArray_NDIM(op[1])) { tmp = op[0]; } else { tmp = op[1]; } Py_INCREF(dtypes[2]); op[2] = (PyArrayObject *)PyArray_NewFromDescr(&PyArray_Type, dtypes[2], PyArray_NDIM(tmp), PyArray_DIMS(tmp), NULL, NULL, PyArray_ISFORTRAN(tmp) ? NPY_ARRAY_F_CONTIGUOUS : 0, NULL); if (op[2] == NULL) { return -1; } /* Call the __prepare_array__ if necessary */ if (prepare_ufunc_output(ufunc, &op[2], arr_prep[0], arr_prep_args, 0) < 0) { return -1; } NPY_UF_DBG_PRINT("trivial 2 input with allocated output\n"); trivial_three_operand_loop(op, innerloop, innerloopdata); return 0; } else if (op[2] != NULL && PyArray_NDIM(op[2]) >= PyArray_NDIM(op[0]) && PyArray_NDIM(op[2]) >= PyArray_NDIM(op[1]) && PyArray_TRIVIALLY_ITERABLE_TRIPLE(op[0], op[1], op[2])) { /* Call the __prepare_array__ if necessary */ if (prepare_ufunc_output(ufunc, &op[2], arr_prep[0], arr_prep_args, 0) < 0) { return -1; } NPY_UF_DBG_PRINT("trivial 2 input\n"); trivial_three_operand_loop(op, innerloop, innerloopdata); return 0; } } } /* * If no trivial loop matched, an iterator is required to * resolve broadcasting, etc */ NPY_UF_DBG_PRINT("iterator loop\n"); if (iterator_loop(ufunc, op, dtypes, order, buffersize, arr_prep, arr_prep_args, innerloop, innerloopdata) < 0) { return -1; } return 0; } /* * nin - number of inputs * nout - number of outputs * wheremask - if not NULL, the 'where=' parameter to the ufunc. * op - the operands (nin + nout of them) * order - the loop execution order/output memory order * buffersize - how big of a buffer to use * arr_prep - the __array_prepare__ functions for the outputs * innerloop - the inner loop function * innerloopdata - data to pass to the inner loop */ static int execute_fancy_ufunc_loop(PyUFuncObject *ufunc, PyArrayObject *wheremask, PyArrayObject **op, PyArray_Descr **dtypes, NPY_ORDER order, npy_intp buffersize, PyObject **arr_prep, PyObject *arr_prep_args) { int i, nin = ufunc->nin, nout = ufunc->nout; int nop = nin + nout; npy_uint32 op_flags[NPY_MAXARGS]; NpyIter *iter; int needs_api; npy_intp default_op_in_flags = 0, default_op_out_flags = 0; NpyIter_IterNextFunc *iternext; char **dataptr; npy_intp *strides; npy_intp *countptr; PyArrayObject **op_it; npy_uint32 iter_flags; NPY_BEGIN_THREADS_DEF; if (wheremask != NULL) { if (nop + 1 > NPY_MAXARGS) { PyErr_SetString(PyExc_ValueError, "Too many operands when including where= parameter"); return -1; } op[nop] = wheremask; dtypes[nop] = NULL; default_op_out_flags |= NPY_ITER_WRITEMASKED; } /* Set up the flags */ for (i = 0; i < nin; ++i) { op_flags[i] = default_op_in_flags | NPY_ITER_READONLY | NPY_ITER_ALIGNED; /* * If READWRITE flag has been set for this operand, * then clear default READONLY flag */ op_flags[i] |= ufunc->op_flags[i]; if (op_flags[i] & (NPY_ITER_READWRITE | NPY_ITER_WRITEONLY)) { op_flags[i] &= ~NPY_ITER_READONLY; } } for (i = nin; i < nop; ++i) { op_flags[i] = default_op_out_flags | NPY_ITER_WRITEONLY | NPY_ITER_ALIGNED | NPY_ITER_ALLOCATE | NPY_ITER_NO_BROADCAST | NPY_ITER_NO_SUBTYPE; } if (wheremask != NULL) { op_flags[nop] = NPY_ITER_READONLY | NPY_ITER_ARRAYMASK; } NPY_UF_DBG_PRINT("Making iterator\n"); iter_flags = ufunc->iter_flags | NPY_ITER_EXTERNAL_LOOP | NPY_ITER_REFS_OK | NPY_ITER_ZEROSIZE_OK | NPY_ITER_BUFFERED | NPY_ITER_GROWINNER; /* * Allocate the iterator. Because the types of the inputs * were already checked, we use the casting rule 'unsafe' which * is faster to calculate. */ iter = NpyIter_AdvancedNew(nop + ((wheremask != NULL) ? 1 : 0), op, iter_flags, order, NPY_UNSAFE_CASTING, op_flags, dtypes, -1, NULL, NULL, buffersize); if (iter == NULL) { return -1; } NPY_UF_DBG_PRINT("Made iterator\n"); needs_api = NpyIter_IterationNeedsAPI(iter); /* Copy any allocated outputs */ op_it = NpyIter_GetOperandArray(iter); for (i = nin; i < nop; ++i) { if (op[i] == NULL) { op[i] = op_it[i]; Py_INCREF(op[i]); } } /* Call the __array_prepare__ functions where necessary */ for (i = 0; i < nout; ++i) { if (prepare_ufunc_output(ufunc, &op[nin+i], arr_prep[i], arr_prep_args, i) < 0) { NpyIter_Deallocate(iter); return -1; } } /* Only do the loop if the iteration size is non-zero */ if (NpyIter_GetIterSize(iter) != 0) { PyUFunc_MaskedStridedInnerLoopFunc *innerloop; NpyAuxData *innerloopdata; npy_intp fixed_strides[2*NPY_MAXARGS]; PyArray_Descr **iter_dtypes; /* Validate that the prepare_ufunc_output didn't mess with pointers */ for (i = nin; i < nop; ++i) { if (PyArray_BYTES(op[i]) != PyArray_BYTES(op_it[i])) { PyErr_SetString(PyExc_ValueError, "The __array_prepare__ functions modified the data " "pointer addresses in an invalid fashion"); NpyIter_Deallocate(iter); return -1; } } /* * Get the inner loop, with the possibility of specialization * based on the fixed strides. */ NpyIter_GetInnerFixedStrideArray(iter, fixed_strides); iter_dtypes = NpyIter_GetDescrArray(iter); if (ufunc->masked_inner_loop_selector(ufunc, dtypes, wheremask != NULL ? iter_dtypes[nop] : iter_dtypes[nop + nin], fixed_strides, wheremask != NULL ? fixed_strides[nop] : fixed_strides[nop + nin], &innerloop, &innerloopdata, &needs_api) < 0) { NpyIter_Deallocate(iter); return -1; } /* Get the variables needed for the loop */ iternext = NpyIter_GetIterNext(iter, NULL); if (iternext == NULL) { NpyIter_Deallocate(iter); return -1; } dataptr = NpyIter_GetDataPtrArray(iter); strides = NpyIter_GetInnerStrideArray(iter); countptr = NpyIter_GetInnerLoopSizePtr(iter); if (!needs_api) { NPY_BEGIN_THREADS; } NPY_UF_DBG_PRINT("Actual inner loop:\n"); /* Execute the loop */ do { NPY_UF_DBG_PRINT1("iterator loop count %d\n", (int)*countptr); innerloop(dataptr, strides, dataptr[nop], strides[nop], *countptr, innerloopdata); } while (iternext(iter)); if (!needs_api) { NPY_END_THREADS; } NPY_AUXDATA_FREE(innerloopdata); } NpyIter_Deallocate(iter); return 0; } static PyObject * make_arr_prep_args(npy_intp nin, PyObject *args, PyObject *kwds) { PyObject *out = kwds ? PyDict_GetItemString(kwds, "out") : NULL; PyObject *arr_prep_args; if (out == NULL) { Py_INCREF(args); return args; } else { npy_intp i, nargs = PyTuple_GET_SIZE(args), n; n = nargs; if (n < nin + 1) { n = nin + 1; } arr_prep_args = PyTuple_New(n); if (arr_prep_args == NULL) { return NULL; } /* Copy the tuple, but set the nin-th item to the keyword arg */ for (i = 0; i < nin; ++i) { PyObject *item = PyTuple_GET_ITEM(args, i); Py_INCREF(item); PyTuple_SET_ITEM(arr_prep_args, i, item); } Py_INCREF(out); PyTuple_SET_ITEM(arr_prep_args, nin, out); for (i = nin+1; i < n; ++i) { PyObject *item = PyTuple_GET_ITEM(args, i); Py_INCREF(item); PyTuple_SET_ITEM(arr_prep_args, i, item); } return arr_prep_args; } } static int PyUFunc_GeneralizedFunction(PyUFuncObject *ufunc, PyObject *args, PyObject *kwds, PyArrayObject **op) { int nin, nout; int i, j, idim, nop; char *ufunc_name; int retval = -1, subok = 1; int needs_api = 0; PyArray_Descr *dtypes[NPY_MAXARGS]; /* Use remapped axes for generalized ufunc */ int broadcast_ndim, iter_ndim; int op_axes_arrays[NPY_MAXARGS][NPY_MAXDIMS]; int *op_axes[NPY_MAXARGS]; npy_uint32 op_flags[NPY_MAXARGS]; npy_intp iter_shape[NPY_MAXARGS]; NpyIter *iter = NULL; npy_uint32 iter_flags; /* These parameters come from extobj= or from a TLS global */ int buffersize = 0, errormask = 0; PyObject *errobj = NULL; int first_error = 1; /* The selected inner loop */ PyUFuncGenericFunction innerloop = NULL; void *innerloopdata = NULL; /* The dimensions which get passed to the inner loop */ npy_intp inner_dimensions[NPY_MAXDIMS+1]; /* The strides which get passed to the inner loop */ npy_intp *inner_strides = NULL; /* The sizes of the core dimensions (# entries is ufunc->core_num_dim_ix) */ npy_intp *core_dim_sizes = inner_dimensions + 1; int core_dim_ixs_size; /* The __array_prepare__ function to call for each output */ PyObject *arr_prep[NPY_MAXARGS]; /* * This is either args, or args with the out= parameter from * kwds added appropriately. */ PyObject *arr_prep_args = NULL; NPY_ORDER order = NPY_KEEPORDER; /* Use the default assignment casting rule */ NPY_CASTING casting = NPY_DEFAULT_ASSIGN_CASTING; /* When provided, extobj and typetup contain borrowed references */ PyObject *extobj = NULL, *type_tup = NULL; if (ufunc == NULL) { PyErr_SetString(PyExc_ValueError, "function not supported"); return -1; } nin = ufunc->nin; nout = ufunc->nout; nop = nin + nout; ufunc_name = ufunc->name ? ufunc->name : ""; NPY_UF_DBG_PRINT1("\nEvaluating ufunc %s\n", ufunc_name); /* Initialize all the operands and dtypes to NULL */ for (i = 0; i < nop; ++i) { op[i] = NULL; dtypes[i] = NULL; arr_prep[i] = NULL; } NPY_UF_DBG_PRINT("Getting arguments\n"); /* Get all the arguments */ retval = get_ufunc_arguments(ufunc, args, kwds, op, &order, &casting, &extobj, &type_tup, &subok, NULL); if (retval < 0) { goto fail; } /* * Figure out the number of iteration dimensions, which * is the broadcast result of all the input non-core * dimensions. */ broadcast_ndim = 0; for (i = 0; i < nin; ++i) { int n = PyArray_NDIM(op[i]) - ufunc->core_num_dims[i]; if (n > broadcast_ndim) { broadcast_ndim = n; } } /* * Figure out the number of iterator creation dimensions, * which is the broadcast dimensions + all the core dimensions of * the outputs, so that the iterator can allocate those output * dimensions following the rules of order='F', for example. */ iter_ndim = broadcast_ndim; for (i = nin; i < nop; ++i) { iter_ndim += ufunc->core_num_dims[i]; } if (iter_ndim > NPY_MAXDIMS) { PyErr_Format(PyExc_ValueError, "too many dimensions for generalized ufunc %s", ufunc_name); retval = -1; goto fail; } /* * Validate the core dimensions of all the operands, * and collect all of the labeled core dimension sizes * into the array 'core_dim_sizes'. Initialize them to * 1, for example in the case where the operand broadcasts * to a core dimension, it won't be visited. */ for (i = 0; i < ufunc->core_num_dim_ix; ++i) { core_dim_sizes[i] = 1; } for (i = 0; i < nop; ++i) { if (op[i] != NULL) { int dim_offset = ufunc->core_offsets[i]; int num_dims = ufunc->core_num_dims[i]; int core_start_dim = PyArray_NDIM(op[i]) - num_dims; /* Make sure any output operand has enough dimensions */ if (i >= nin && core_start_dim < 0) { PyErr_Format(PyExc_ValueError, "%s: Output operand %d does not have enough dimensions " "(has %d, gufunc core with signature %s " "requires %d)", ufunc_name, i - nin, PyArray_NDIM(op[i]), ufunc->core_signature, num_dims); retval = -1; goto fail; } /* * Make sure each core dimension matches all other core * dimensions with the same label * * NOTE: For input operands, core_start_dim may be negative. * In that case, the operand is being broadcast onto * core dimensions. For example, a scalar will broadcast * to fit any core signature. */ if (core_start_dim >= 0) { idim = 0; } else { idim = -core_start_dim; } for (; idim < num_dims; ++idim) { int core_dim_index = ufunc->core_dim_ixs[dim_offset + idim]; npy_intp op_dim_size = PyArray_SHAPE(op[i])[core_start_dim + idim]; if (core_dim_sizes[core_dim_index] == 1) { core_dim_sizes[core_dim_index] = op_dim_size; } else if ((i >= nin || op_dim_size != 1) && core_dim_sizes[core_dim_index] != op_dim_size) { PyErr_Format(PyExc_ValueError, "%s: Operand %d has a mismatch in its core " "dimension %d, with gufunc signature %s " "(size %zd is different from %zd)", ufunc_name, i, idim, ufunc->core_signature, op_dim_size, core_dim_sizes[core_dim_index]); retval = -1; goto fail; } } } } /* Fill in the initial part of 'iter_shape' */ for (idim = 0; idim < broadcast_ndim; ++idim) { iter_shape[idim] = -1; } /* Fill in op_axes for all the operands */ j = broadcast_ndim; core_dim_ixs_size = 0; for (i = 0; i < nop; ++i) { int n; if (op[i]) { /* * Note that n may be negative if broadcasting * extends into the core dimensions. */ n = PyArray_NDIM(op[i]) - ufunc->core_num_dims[i]; } else { n = broadcast_ndim; } /* Broadcast all the unspecified dimensions normally */ for (idim = 0; idim < broadcast_ndim; ++idim) { if (idim >= broadcast_ndim - n) { op_axes_arrays[i][idim] = idim - (broadcast_ndim - n); } else { op_axes_arrays[i][idim] = -1; } } /* Any output core dimensions shape should be ignored */ for (idim = broadcast_ndim; idim < iter_ndim; ++idim) { op_axes_arrays[i][idim] = -1; } /* Except for when it belongs to this output */ if (i >= nin) { int dim_offset = ufunc->core_offsets[i]; int num_dims = ufunc->core_num_dims[i]; /* Fill in 'iter_shape' and 'op_axes' for this output */ for (idim = 0; idim < num_dims; ++idim) { iter_shape[j] = core_dim_sizes[ ufunc->core_dim_ixs[dim_offset + idim]]; op_axes_arrays[i][j] = n + idim; ++j; } } op_axes[i] = op_axes_arrays[i]; core_dim_ixs_size += ufunc->core_num_dims[i]; } /* Get the buffersize, errormask, and error object globals */ if (extobj == NULL) { if (PyUFunc_GetPyValues(ufunc_name, &buffersize, &errormask, &errobj) < 0) { retval = -1; goto fail; } } else { if (_extract_pyvals(extobj, ufunc_name, &buffersize, &errormask, &errobj) < 0) { retval = -1; goto fail; } } NPY_UF_DBG_PRINT("Finding inner loop\n"); retval = ufunc->type_resolver(ufunc, casting, op, type_tup, dtypes); if (retval < 0) { goto fail; } /* For the generalized ufunc, we get the loop right away too */ retval = ufunc->legacy_inner_loop_selector(ufunc, dtypes, &innerloop, &innerloopdata, &needs_api); if (retval < 0) { goto fail; } /* * FAIL with NotImplemented if the other object has * the __r__ method and has a higher priority than * the current op (signalling it can handle ndarray's). */ if (nin == 2 && nout == 1 && dtypes[1]->type_num == NPY_OBJECT) { PyObject *_obj = PyTuple_GET_ITEM(args, 1); if (!PyArray_CheckExact(_obj)) { double self_prio, other_prio; self_prio = PyArray_GetPriority(PyTuple_GET_ITEM(args, 0), NPY_SCALAR_PRIORITY); other_prio = PyArray_GetPriority(_obj, NPY_SCALAR_PRIORITY); if (self_prio < other_prio && _has_reflected_op(_obj, ufunc_name)) { retval = -2; goto fail; } } } #if NPY_UF_DBG_TRACING printf("input types:\n"); for (i = 0; i < nin; ++i) { PyObject_Print((PyObject *)dtypes[i], stdout, 0); printf(" "); } printf("\noutput types:\n"); for (i = nin; i < nop; ++i) { PyObject_Print((PyObject *)dtypes[i], stdout, 0); printf(" "); } printf("\n"); #endif if (subok) { /* * Get the appropriate __array_prepare__ function to call * for each output */ _find_array_prepare(args, kwds, arr_prep, nin, nout); /* Set up arr_prep_args if a prep function was needed */ for (i = 0; i < nout; ++i) { if (arr_prep[i] != NULL && arr_prep[i] != Py_None) { arr_prep_args = make_arr_prep_args(nin, args, kwds); break; } } } /* If the loop wants the arrays, provide them */ if (_does_loop_use_arrays(innerloopdata)) { innerloopdata = (void*)op; } /* * Set up the iterator per-op flags. For generalized ufuncs, we * can't do buffering, so must COPY or UPDATEIFCOPY. */ for (i = 0; i < nin; ++i) { op_flags[i] = NPY_ITER_READONLY | NPY_ITER_COPY | NPY_ITER_ALIGNED; /* * If READWRITE flag has been set for this operand, * then clear default READONLY flag */ op_flags[i] |= ufunc->op_flags[i]; if (op_flags[i] & (NPY_ITER_READWRITE | NPY_ITER_WRITEONLY)) { op_flags[i] &= ~NPY_ITER_READONLY; } } for (i = nin; i < nop; ++i) { op_flags[i] = NPY_ITER_READWRITE| NPY_ITER_UPDATEIFCOPY| NPY_ITER_ALIGNED| NPY_ITER_ALLOCATE| NPY_ITER_NO_BROADCAST; } iter_flags = ufunc->iter_flags | NPY_ITER_MULTI_INDEX | NPY_ITER_REFS_OK | NPY_ITER_REDUCE_OK | NPY_ITER_ZEROSIZE_OK; /* Create the iterator */ iter = NpyIter_AdvancedNew(nop, op, iter_flags, order, NPY_UNSAFE_CASTING, op_flags, dtypes, iter_ndim, op_axes, iter_shape, 0); if (iter == NULL) { retval = -1; goto fail; } /* Fill in any allocated outputs */ for (i = nin; i < nop; ++i) { if (op[i] == NULL) { op[i] = NpyIter_GetOperandArray(iter)[i]; Py_INCREF(op[i]); } } /* * Set up the inner strides array. Because we're not doing * buffering, the strides are fixed throughout the looping. */ 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) { int num_dims = ufunc->core_num_dims[i]; int core_start_dim = PyArray_NDIM(op[i]) - num_dims; /* * Need to use the arrays in the iterator, not op, because * a copy with a different-sized type may have been made. */ PyArrayObject *arr = NpyIter_GetOperandArray(iter)[i]; npy_intp *shape = PyArray_SHAPE(arr); npy_intp *strides = PyArray_STRIDES(arr); for (j = 0; j < num_dims; ++j) { if (core_start_dim + j >= 0) { /* * Force the stride to zero when the shape is 1, sot * that the broadcasting works right. */ if (shape[core_start_dim + j] != 1) { inner_strides[idim++] = strides[core_start_dim + j]; } else { inner_strides[idim++] = 0; } } else { inner_strides[idim++] = 0; } } } /* Remove all the core output dimensions from the iterator */ for (i = broadcast_ndim; i < iter_ndim; ++i) { if (NpyIter_RemoveAxis(iter, broadcast_ndim) != NPY_SUCCEED) { retval = -1; goto fail; } } if (NpyIter_RemoveMultiIndex(iter) != NPY_SUCCEED) { retval = -1; goto fail; } if (NpyIter_EnableExternalLoop(iter) != NPY_SUCCEED) { retval = -1; goto fail; } /* * The first nop strides are for the inner loop (but only can * copy them after removing the core axes */ memcpy(inner_strides, NpyIter_GetInnerStrideArray(iter), NPY_SIZEOF_INTP * nop); #if 0 printf("strides: "); for (i = 0; i < nop+core_dim_ixs_size; ++i) { printf("%d ", (int)inner_strides[i]); } printf("\n"); #endif /* Start with the floating-point exception flags cleared */ PyUFunc_clearfperr(); NPY_UF_DBG_PRINT("Executing inner loop\n"); if (NpyIter_GetIterSize(iter) != 0) { /* Do the ufunc loop */ NpyIter_IterNextFunc *iternext; char **dataptr; npy_intp *count_ptr; /* Get the variables needed for the loop */ iternext = NpyIter_GetIterNext(iter, NULL); if (iternext == NULL) { NpyIter_Deallocate(iter); retval = -1; goto fail; } dataptr = NpyIter_GetDataPtrArray(iter); count_ptr = NpyIter_GetInnerLoopSizePtr(iter); do { inner_dimensions[0] = *count_ptr; innerloop(dataptr, inner_dimensions, inner_strides, innerloopdata); } while (iternext(iter)); } else { /** * For each output operand, check if it has non-zero size, * and assign the identity if it does. For example, a dot * product of two zero-length arrays will be a scalar, * which has size one. */ for (i = nin; i < nop; ++i) { if (PyArray_SIZE(op[i]) != 0) { switch (ufunc->identity) { case PyUFunc_Zero: assign_reduce_identity_zero(op[i]); break; case PyUFunc_One: assign_reduce_identity_one(op[i]); break; case PyUFunc_None: case PyUFunc_ReorderableNone: 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; } } } } /* Check whether any errors occurred during the loop */ if (PyErr_Occurred() || (errormask && PyUFunc_checkfperr(errormask, errobj, &first_error))) { retval = -1; goto fail; } PyArray_free(inner_strides); NpyIter_Deallocate(iter); /* The caller takes ownership of all the references in op */ for (i = 0; i < nop; ++i) { Py_XDECREF(dtypes[i]); Py_XDECREF(arr_prep[i]); } Py_XDECREF(errobj); Py_XDECREF(type_tup); Py_XDECREF(arr_prep_args); NPY_UF_DBG_PRINT("Returning Success\n"); return 0; fail: NPY_UF_DBG_PRINT1("Returning failure code %d\n", retval); if (inner_strides) { PyArray_free(inner_strides); } if (iter != NULL) { NpyIter_Deallocate(iter); } for (i = 0; i < nop; ++i) { Py_XDECREF(op[i]); op[i] = NULL; Py_XDECREF(dtypes[i]); Py_XDECREF(arr_prep[i]); } Py_XDECREF(errobj); Py_XDECREF(type_tup); Py_XDECREF(arr_prep_args); return retval; } /*UFUNC_API * * This generic function is called with the ufunc object, the arguments to it, * and an array of (pointers to) PyArrayObjects which are NULL. * * 'op' is an array of at least NPY_MAXARGS PyArrayObject *. */ NPY_NO_EXPORT int PyUFunc_GenericFunction(PyUFuncObject *ufunc, PyObject *args, PyObject *kwds, PyArrayObject **op) { int nin, nout; int i, nop; char *ufunc_name; int retval = -1, subok = 1; int need_fancy = 0; PyArray_Descr *dtypes[NPY_MAXARGS]; /* These parameters come from extobj= or from a TLS global */ int buffersize = 0, errormask = 0; PyObject *errobj = NULL; int first_error = 1; /* The mask provided in the 'where=' parameter */ PyArrayObject *wheremask = NULL; /* The __array_prepare__ function to call for each output */ PyObject *arr_prep[NPY_MAXARGS]; /* * This is either args, or args with the out= parameter from * kwds added appropriately. */ PyObject *arr_prep_args = NULL; int trivial_loop_ok = 0; NPY_ORDER order = NPY_KEEPORDER; /* Use the default assignment casting rule */ NPY_CASTING casting = NPY_DEFAULT_ASSIGN_CASTING; /* When provided, extobj and typetup contain borrowed references */ PyObject *extobj = NULL, *type_tup = NULL; if (ufunc == NULL) { PyErr_SetString(PyExc_ValueError, "function not supported"); return -1; } if (ufunc->core_enabled) { return PyUFunc_GeneralizedFunction(ufunc, args, kwds, op); } nin = ufunc->nin; nout = ufunc->nout; nop = nin + nout; ufunc_name = ufunc->name ? ufunc->name : ""; NPY_UF_DBG_PRINT1("\nEvaluating ufunc %s\n", ufunc_name); /* Initialize all the operands and dtypes to NULL */ for (i = 0; i < nop; ++i) { op[i] = NULL; dtypes[i] = NULL; arr_prep[i] = NULL; } NPY_UF_DBG_PRINT("Getting arguments\n"); /* Get all the arguments */ retval = get_ufunc_arguments(ufunc, args, kwds, op, &order, &casting, &extobj, &type_tup, &subok, &wheremask); if (retval < 0) { goto fail; } /* * Use the masked loop if a wheremask was specified. */ if (wheremask != NULL) { need_fancy = 1; } /* Get the buffersize, errormask, and error object globals */ if (extobj == NULL) { if (PyUFunc_GetPyValues(ufunc_name, &buffersize, &errormask, &errobj) < 0) { retval = -1; goto fail; } } else { if (_extract_pyvals(extobj, ufunc_name, &buffersize, &errormask, &errobj) < 0) { retval = -1; goto fail; } } NPY_UF_DBG_PRINT("Finding inner loop\n"); retval = ufunc->type_resolver(ufunc, casting, op, type_tup, dtypes); if (retval < 0) { goto fail; } /* Only do the trivial loop check for the unmasked version. */ if (!need_fancy) { /* * This checks whether a trivial loop is ok, making copies of * scalar and one dimensional operands if that will help. */ trivial_loop_ok = check_for_trivial_loop(ufunc, op, dtypes, buffersize); if (trivial_loop_ok < 0) { goto fail; } } /* * FAIL with NotImplemented if the other object has * the __r__ method and has __array_priority__ as * an attribute (signalling it can handle ndarray's) * and is not already an ndarray or a subtype of the same type. */ if (nin == 2 && nout == 1 && dtypes[1]->type_num == NPY_OBJECT) { PyObject *_obj = PyTuple_GET_ITEM(args, 1); if (!PyArray_Check(_obj)) { double self_prio, other_prio; self_prio = PyArray_GetPriority(PyTuple_GET_ITEM(args, 0), NPY_SCALAR_PRIORITY); other_prio = PyArray_GetPriority(_obj, NPY_SCALAR_PRIORITY); if (self_prio < other_prio && _has_reflected_op(_obj, ufunc_name)) { retval = -2; goto fail; } } } #if NPY_UF_DBG_TRACING printf("input types:\n"); for (i = 0; i < nin; ++i) { PyObject_Print((PyObject *)dtypes[i], stdout, 0); printf(" "); } printf("\noutput types:\n"); for (i = nin; i < nop; ++i) { PyObject_Print((PyObject *)dtypes[i], stdout, 0); printf(" "); } printf("\n"); #endif if (subok) { /* * Get the appropriate __array_prepare__ function to call * for each output */ _find_array_prepare(args, kwds, arr_prep, nin, nout); /* Set up arr_prep_args if a prep function was needed */ for (i = 0; i < nout; ++i) { if (arr_prep[i] != NULL && arr_prep[i] != Py_None) { arr_prep_args = make_arr_prep_args(nin, args, kwds); break; } } } /* Start with the floating-point exception flags cleared */ PyUFunc_clearfperr(); /* Do the ufunc loop */ if (need_fancy) { NPY_UF_DBG_PRINT("Executing fancy inner loop\n"); retval = execute_fancy_ufunc_loop(ufunc, wheremask, op, dtypes, order, buffersize, arr_prep, arr_prep_args); } else { NPY_UF_DBG_PRINT("Executing legacy inner loop\n"); if (ufunc->legacy_inner_loop_selector != NULL) { retval = execute_legacy_ufunc_loop(ufunc, trivial_loop_ok, op, dtypes, order, buffersize, arr_prep, arr_prep_args); } else { /* * TODO: When this is supported, it should be preferred over * the legacy_inner_loop_selector */ PyErr_SetString(PyExc_RuntimeError, "usage of the new inner_loop_selector isn't " "implemented yet"); retval = -1; goto fail; } } if (retval < 0) { goto fail; } /* Check whether any errors occurred during the loop */ if (PyErr_Occurred() || (errormask && PyUFunc_checkfperr(errormask, errobj, &first_error))) { retval = -1; goto fail; } /* The caller takes ownership of all the references in op */ for (i = 0; i < nop; ++i) { Py_XDECREF(dtypes[i]); Py_XDECREF(arr_prep[i]); } Py_XDECREF(errobj); Py_XDECREF(type_tup); Py_XDECREF(arr_prep_args); Py_XDECREF(wheremask); NPY_UF_DBG_PRINT("Returning Success\n"); return 0; fail: NPY_UF_DBG_PRINT1("Returning failure code %d\n", retval); for (i = 0; i < nop; ++i) { Py_XDECREF(op[i]); op[i] = NULL; Py_XDECREF(dtypes[i]); Py_XDECREF(arr_prep[i]); } Py_XDECREF(errobj); Py_XDECREF(type_tup); Py_XDECREF(arr_prep_args); Py_XDECREF(wheremask); return retval; } /* * Given the output type, finds the specified binary op. The * ufunc must have nin==2 and nout==1. The function may modify * otype if the given type isn't found. * * Returns 0 on success, -1 on failure. */ static int get_binary_op_function(PyUFuncObject *ufunc, int *otype, PyUFuncGenericFunction *out_innerloop, void **out_innerloopdata) { int i; PyUFunc_Loop1d *funcdata; NPY_UF_DBG_PRINT1("Getting binary op function for type number %d\n", *otype); /* If the type is custom and there are userloops, search for it here */ if (ufunc->userloops != NULL && PyTypeNum_ISUSERDEF(*otype)) { PyObject *key, *obj; key = PyInt_FromLong(*otype); if (key == NULL) { return -1; } obj = PyDict_GetItem(ufunc->userloops, key); Py_DECREF(key); if (obj != NULL) { funcdata = (PyUFunc_Loop1d *)NpyCapsule_AsVoidPtr(obj); while (funcdata != NULL) { int *types = funcdata->arg_types; if (types[0] == *otype && types[1] == *otype && types[2] == *otype) { *out_innerloop = funcdata->func; *out_innerloopdata = funcdata->data; return 0; } funcdata = funcdata->next; } } } /* Search for a function with compatible inputs */ for (i = 0; i < ufunc->ntypes; ++i) { char *types = ufunc->types + i*ufunc->nargs; NPY_UF_DBG_PRINT3("Trying loop with signature %d %d -> %d\n", types[0], types[1], types[2]); if (PyArray_CanCastSafely(*otype, types[0]) && types[0] == types[1] && (*otype == NPY_OBJECT || types[0] != NPY_OBJECT)) { /* If the signature is "xx->x", we found the loop */ if (types[2] == types[0]) { *out_innerloop = ufunc->functions[i]; *out_innerloopdata = ufunc->data[i]; *otype = types[0]; return 0; } /* * Otherwise, we found the natural type of the reduction, * replace otype and search again */ else { *otype = types[2]; break; } } } /* Search for the exact function */ for (i = 0; i < ufunc->ntypes; ++i) { char *types = ufunc->types + i*ufunc->nargs; if (PyArray_CanCastSafely(*otype, types[0]) && types[0] == types[1] && types[1] == types[2] && (*otype == NPY_OBJECT || types[0] != NPY_OBJECT)) { /* Since the signature is "xx->x", we found the loop */ *out_innerloop = ufunc->functions[i]; *out_innerloopdata = ufunc->data[i]; *otype = types[0]; return 0; } } return -1; } static int reduce_type_resolver(PyUFuncObject *ufunc, PyArrayObject *arr, PyArray_Descr *odtype, PyArray_Descr **out_dtype) { int i, retcode; PyArrayObject *op[3] = {arr, arr, NULL}; PyArray_Descr *dtypes[3] = {NULL, NULL, NULL}; char *ufunc_name = ufunc->name ? ufunc->name : "(unknown)"; PyObject *type_tup = NULL; *out_dtype = NULL; /* * If odtype is specified, make a type tuple for the type * resolution. */ if (odtype != NULL) { type_tup = Py_BuildValue("OOO", odtype, odtype, Py_None); if (type_tup == NULL) { return -1; } } /* Use the type resolution function to find our loop */ retcode = ufunc->type_resolver( ufunc, NPY_UNSAFE_CASTING, op, type_tup, dtypes); Py_DECREF(type_tup); if (retcode == -1) { return -1; } else if (retcode == -2) { PyErr_Format(PyExc_RuntimeError, "type resolution returned NotImplemented to " "reduce ufunc %s", ufunc_name); return -1; } /* * The first two type should be equivalent. Because of how * reduce has historically behaved in NumPy, the return type * could be different, and it is the return type on which the * reduction occurs. */ if (!PyArray_EquivTypes(dtypes[0], dtypes[1])) { for (i = 0; i < 3; ++i) { Py_DECREF(dtypes[i]); } PyErr_Format(PyExc_RuntimeError, "could not find a type resolution appropriate for " "reduce ufunc %s", ufunc_name); return -1; } Py_DECREF(dtypes[0]); Py_DECREF(dtypes[1]); *out_dtype = dtypes[2]; return 0; } static int assign_reduce_identity_zero(PyArrayObject *result) { return PyArray_FillWithScalar(result, PyArrayScalar_False); } static int assign_reduce_identity_one(PyArrayObject *result) { return PyArray_FillWithScalar(result, PyArrayScalar_True); } static int reduce_loop(NpyIter *iter, char **dataptrs, npy_intp *strides, npy_intp *countptr, NpyIter_IterNextFunc *iternext, int needs_api, npy_intp skip_first_count, void *data) { PyArray_Descr *dtypes[3], **iter_dtypes; PyUFuncObject *ufunc = (PyUFuncObject *)data; char *dataptrs_copy[3]; npy_intp strides_copy[3]; /* The normal selected inner loop */ PyUFuncGenericFunction innerloop = NULL; void *innerloopdata = NULL; NPY_BEGIN_THREADS_DEF; /* Get the inner loop */ iter_dtypes = NpyIter_GetDescrArray(iter); dtypes[0] = iter_dtypes[0]; dtypes[1] = iter_dtypes[1]; dtypes[2] = iter_dtypes[0]; if (ufunc->legacy_inner_loop_selector(ufunc, dtypes, &innerloop, &innerloopdata, &needs_api) < 0) { return -1; } if (!needs_api) { NPY_BEGIN_THREADS; } if (skip_first_count > 0) { do { npy_intp count = *countptr; /* Skip any first-visit elements */ if (NpyIter_IsFirstVisit(iter, 0)) { if (strides[0] == 0) { --count; --skip_first_count; dataptrs[1] += strides[1]; } else { skip_first_count -= count; count = 0; } } /* Turn the two items into three for the inner loop */ dataptrs_copy[0] = dataptrs[0]; dataptrs_copy[1] = dataptrs[1]; dataptrs_copy[2] = dataptrs[0]; strides_copy[0] = strides[0]; strides_copy[1] = strides[1]; strides_copy[2] = strides[0]; innerloop(dataptrs_copy, &count, strides_copy, innerloopdata); /* Jump to the faster loop when skipping is done */ if (skip_first_count == 0) { if (iternext(iter)) { break; } else { goto finish_loop; } } } while (iternext(iter)); } do { /* Turn the two items into three for the inner loop */ dataptrs_copy[0] = dataptrs[0]; dataptrs_copy[1] = dataptrs[1]; dataptrs_copy[2] = dataptrs[0]; strides_copy[0] = strides[0]; strides_copy[1] = strides[1]; strides_copy[2] = strides[0]; innerloop(dataptrs_copy, countptr, strides_copy, innerloopdata); } while (iternext(iter)); finish_loop: if (!needs_api) { NPY_END_THREADS; } return (needs_api && PyErr_Occurred()) ? -1 : 0; } /* * The implementation of the reduction operators with the new iterator * turned into a bit of a long function here, but I think the design * of this part needs to be changed to be more like einsum, so it may * not be worth refactoring it too much. Consider this timing: * * >>> a = arange(10000) * * >>> timeit sum(a) * 10000 loops, best of 3: 17 us per loop * * >>> timeit einsum("i->",a) * 100000 loops, best of 3: 13.5 us per loop * * The axes must already be bounds-checked by the calling function, * this function does not validate them. */ static PyArrayObject * PyUFunc_Reduce(PyUFuncObject *ufunc, PyArrayObject *arr, PyArrayObject *out, int naxes, int *axes, PyArray_Descr *odtype, int keepdims) { int iaxes, reorderable, ndim; npy_bool axis_flags[NPY_MAXDIMS]; PyArray_Descr *dtype; PyArrayObject *result; PyArray_AssignReduceIdentityFunc *assign_identity = NULL; char *ufunc_name = ufunc->name ? ufunc->name : "(unknown)"; /* These parameters come from a TLS global */ int buffersize = 0, errormask = 0; PyObject *errobj = NULL; NPY_UF_DBG_PRINT1("\nEvaluating ufunc %s.reduce\n", ufunc_name); ndim = PyArray_NDIM(arr); /* Create an array of flags for reduction */ memset(axis_flags, 0, ndim); for (iaxes = 0; iaxes < naxes; ++iaxes) { int axis = axes[iaxes]; if (axis_flags[axis]) { PyErr_SetString(PyExc_ValueError, "duplicate value in 'axis'"); return NULL; } axis_flags[axis] = 1; } switch (ufunc->identity) { case PyUFunc_Zero: assign_identity = &assign_reduce_identity_zero; reorderable = 1; /* * The identity for a dynamic dtype like * object arrays can't be used in general */ if (PyArray_ISOBJECT(arr) && PyArray_SIZE(arr) != 0) { assign_identity = NULL; } break; case PyUFunc_One: assign_identity = &assign_reduce_identity_one; reorderable = 1; /* * The identity for a dynamic dtype like * object arrays can't be used in general */ if (PyArray_ISOBJECT(arr) && PyArray_SIZE(arr) != 0) { assign_identity = NULL; } break; case PyUFunc_None: reorderable = 0; break; case PyUFunc_ReorderableNone: reorderable = 1; break; default: PyErr_Format(PyExc_ValueError, "ufunc %s has an invalid identity for reduction", ufunc_name); return NULL; } if (PyUFunc_GetPyValues("reduce", &buffersize, &errormask, &errobj) < 0) { return NULL; } /* Get the reduction dtype */ if (reduce_type_resolver(ufunc, arr, odtype, &dtype) < 0) { Py_XDECREF(errobj); return NULL; } result = PyUFunc_ReduceWrapper(arr, out, NULL, dtype, dtype, NPY_UNSAFE_CASTING, axis_flags, reorderable, keepdims, 0, assign_identity, reduce_loop, ufunc, buffersize, ufunc_name); Py_DECREF(dtype); Py_XDECREF(errobj); return result; } static PyObject * PyUFunc_Accumulate(PyUFuncObject *ufunc, PyArrayObject *arr, PyArrayObject *out, int axis, int otype) { PyArrayObject *op[2]; PyArray_Descr *op_dtypes[2] = {NULL, NULL}; int op_axes_arrays[2][NPY_MAXDIMS]; int *op_axes[2] = {op_axes_arrays[0], op_axes_arrays[1]}; npy_uint32 op_flags[2]; int idim, ndim, otype_final; int needs_api, need_outer_iterator; NpyIter *iter = NULL, *iter_inner = NULL; /* The selected inner loop */ PyUFuncGenericFunction innerloop = NULL; void *innerloopdata = NULL; char *ufunc_name = ufunc->name ? ufunc->name : "(unknown)"; /* These parameters come from extobj= or from a TLS global */ int buffersize = 0, errormask = 0; PyObject *errobj = NULL; NPY_BEGIN_THREADS_DEF; NPY_UF_DBG_PRINT1("\nEvaluating ufunc %s.accumulate\n", ufunc_name); #if 0 printf("Doing %s.accumulate on array with dtype : ", ufunc_name); PyObject_Print((PyObject *)PyArray_DESCR(arr), stdout, 0); printf("\n"); #endif if (PyUFunc_GetPyValues("accumulate", &buffersize, &errormask, &errobj) < 0) { return NULL; } /* Take a reference to out for later returning */ Py_XINCREF(out); otype_final = otype; if (get_binary_op_function(ufunc, &otype_final, &innerloop, &innerloopdata) < 0) { PyArray_Descr *dtype = PyArray_DescrFromType(otype); PyErr_Format(PyExc_ValueError, "could not find a matching type for %s.accumulate, " "requested type has type code '%c'", ufunc_name, dtype ? dtype->type : '-'); Py_XDECREF(dtype); goto fail; } ndim = PyArray_NDIM(arr); /* * Set up the output data type, using the input's exact * data type if the type number didn't change to preserve * metadata */ if (PyArray_DESCR(arr)->type_num == otype_final) { if (PyArray_ISNBO(PyArray_DESCR(arr)->byteorder)) { op_dtypes[0] = PyArray_DESCR(arr); Py_INCREF(op_dtypes[0]); } else { op_dtypes[0] = PyArray_DescrNewByteorder(PyArray_DESCR(arr), NPY_NATIVE); } } else { op_dtypes[0] = PyArray_DescrFromType(otype_final); } if (op_dtypes[0] == NULL) { goto fail; } #if NPY_UF_DBG_TRACING printf("Found %s.accumulate inner loop with dtype : ", ufunc_name); PyObject_Print((PyObject *)op_dtypes[0], stdout, 0); printf("\n"); #endif /* Set up the op_axes for the outer loop */ for (idim = 0; idim < ndim; ++idim) { op_axes_arrays[0][idim] = idim; op_axes_arrays[1][idim] = idim; } /* The per-operand flags for the outer loop */ op_flags[0] = NPY_ITER_READWRITE | NPY_ITER_NO_BROADCAST | NPY_ITER_ALLOCATE | NPY_ITER_NO_SUBTYPE; op_flags[1] = NPY_ITER_READONLY; op[0] = out; op[1] = arr; need_outer_iterator = (ndim > 1); /* We can't buffer, so must do UPDATEIFCOPY */ if (!PyArray_ISALIGNED(arr) || (out && !PyArray_ISALIGNED(out)) || !PyArray_EquivTypes(op_dtypes[0], PyArray_DESCR(arr)) || (out && !PyArray_EquivTypes(op_dtypes[0], PyArray_DESCR(out)))) { need_outer_iterator = 1; } if (need_outer_iterator) { int ndim_iter = 0; npy_uint32 flags = NPY_ITER_ZEROSIZE_OK| NPY_ITER_REFS_OK; PyArray_Descr **op_dtypes_param = NULL; /* * The way accumulate is set up, we can't do buffering, * so make a copy instead when necessary. */ ndim_iter = ndim; flags |= NPY_ITER_MULTI_INDEX; /* Add some more flags */ op_flags[0] |= NPY_ITER_UPDATEIFCOPY|NPY_ITER_ALIGNED; op_flags[1] |= NPY_ITER_COPY|NPY_ITER_ALIGNED; op_dtypes_param = op_dtypes; op_dtypes[1] = op_dtypes[0]; NPY_UF_DBG_PRINT("Allocating outer iterator\n"); iter = NpyIter_AdvancedNew(2, op, flags, NPY_KEEPORDER, NPY_UNSAFE_CASTING, op_flags, op_dtypes_param, ndim_iter, op_axes, NULL, 0); if (iter == NULL) { goto fail; } /* In case COPY or UPDATEIFCOPY occurred */ op[0] = NpyIter_GetOperandArray(iter)[0]; op[1] = NpyIter_GetOperandArray(iter)[1]; if (PyArray_SIZE(op[0]) == 0) { if (out == NULL) { out = op[0]; Py_INCREF(out); } goto finish; } if (NpyIter_RemoveAxis(iter, axis) != NPY_SUCCEED) { goto fail; } if (NpyIter_RemoveMultiIndex(iter) != NPY_SUCCEED) { goto fail; } } /* Get the output */ if (out == NULL) { if (iter) { op[0] = out = NpyIter_GetOperandArray(iter)[0]; Py_INCREF(out); } else { PyArray_Descr *dtype = op_dtypes[0]; Py_INCREF(dtype); op[0] = out = (PyArrayObject *)PyArray_NewFromDescr( &PyArray_Type, dtype, ndim, PyArray_DIMS(op[1]), NULL, NULL, 0, NULL); if (out == NULL) { goto fail; } } } /* * If the reduction axis has size zero, either return the reduction * unit for UFUNC_REDUCE, or return the zero-sized output array * for UFUNC_ACCUMULATE. */ if (PyArray_DIM(op[1], axis) == 0) { goto finish; } else if (PyArray_SIZE(op[0]) == 0) { goto finish; } if (iter && NpyIter_GetIterSize(iter) != 0) { char *dataptr_copy[3]; npy_intp stride_copy[3]; npy_intp count_m1, stride0, stride1; NpyIter_IterNextFunc *iternext; char **dataptr; int itemsize = op_dtypes[0]->elsize; /* Get the variables needed for the loop */ iternext = NpyIter_GetIterNext(iter, NULL); if (iternext == NULL) { goto fail; } dataptr = NpyIter_GetDataPtrArray(iter); /* Execute the loop with just the outer iterator */ count_m1 = PyArray_DIM(op[1], axis)-1; stride0 = 0, stride1 = PyArray_STRIDE(op[1], axis); NPY_UF_DBG_PRINT("UFunc: Reduce loop with just outer iterator\n"); stride0 = PyArray_STRIDE(op[0], axis); stride_copy[0] = stride0; stride_copy[1] = stride1; stride_copy[2] = stride0; needs_api = NpyIter_IterationNeedsAPI(iter); if (!needs_api) { NPY_BEGIN_THREADS; } do { dataptr_copy[0] = dataptr[0]; dataptr_copy[1] = dataptr[1]; dataptr_copy[2] = dataptr[0]; /* Copy the first element to start the reduction */ if (otype == NPY_OBJECT) { Py_XDECREF(*(PyObject **)dataptr_copy[0]); *(PyObject **)dataptr_copy[0] = *(PyObject **)dataptr_copy[1]; Py_XINCREF(*(PyObject **)dataptr_copy[0]); } else { memcpy(dataptr_copy[0], dataptr_copy[1], itemsize); } if (count_m1 > 0) { /* Turn the two items into three for the inner loop */ dataptr_copy[1] += stride1; dataptr_copy[2] += stride0; NPY_UF_DBG_PRINT1("iterator loop count %d\n", (int)count_m1); innerloop(dataptr_copy, &count_m1, stride_copy, innerloopdata); } } while (iternext(iter)); if (!needs_api) { NPY_END_THREADS; } } else if (iter == NULL) { char *dataptr_copy[3]; npy_intp stride_copy[3]; int itemsize = op_dtypes[0]->elsize; /* Execute the loop with no iterators */ npy_intp count = PyArray_DIM(op[1], axis); npy_intp stride0 = 0, stride1 = PyArray_STRIDE(op[1], axis); NPY_UF_DBG_PRINT("UFunc: Reduce loop with no iterators\n"); if (PyArray_NDIM(op[0]) != PyArray_NDIM(op[1]) || !PyArray_CompareLists(PyArray_DIMS(op[0]), PyArray_DIMS(op[1]), PyArray_NDIM(op[0]))) { PyErr_SetString(PyExc_ValueError, "provided out is the wrong size " "for the reduction"); goto fail; } stride0 = PyArray_STRIDE(op[0], axis); stride_copy[0] = stride0; stride_copy[1] = stride1; stride_copy[2] = stride0; /* Turn the two items into three for the inner loop */ dataptr_copy[0] = PyArray_BYTES(op[0]); dataptr_copy[1] = PyArray_BYTES(op[1]); dataptr_copy[2] = PyArray_BYTES(op[0]); /* Copy the first element to start the reduction */ if (otype == NPY_OBJECT) { Py_XDECREF(*(PyObject **)dataptr_copy[0]); *(PyObject **)dataptr_copy[0] = *(PyObject **)dataptr_copy[1]; Py_XINCREF(*(PyObject **)dataptr_copy[0]); } else { memcpy(dataptr_copy[0], dataptr_copy[1], itemsize); } if (count > 1) { --count; dataptr_copy[1] += stride1; dataptr_copy[2] += stride0; NPY_UF_DBG_PRINT1("iterator loop count %d\n", (int)count); needs_api = PyDataType_REFCHK(op_dtypes[0]); if (!needs_api) { NPY_BEGIN_THREADS; } innerloop(dataptr_copy, &count, stride_copy, innerloopdata); if (!needs_api) { NPY_END_THREADS; } } } finish: Py_XDECREF(op_dtypes[0]); if (iter != NULL) { NpyIter_Deallocate(iter); } if (iter_inner != NULL) { NpyIter_Deallocate(iter_inner); } Py_XDECREF(errobj); return (PyObject *)out; fail: Py_XDECREF(out); Py_XDECREF(op_dtypes[0]); if (iter != NULL) { NpyIter_Deallocate(iter); } if (iter_inner != NULL) { NpyIter_Deallocate(iter_inner); } Py_XDECREF(errobj); return NULL; } /* * Reduceat performs a reduce over an axis using the indices as a guide * * op.reduceat(array,indices) computes * op.reduce(array[indices[i]:indices[i+1]] * for i=0..end with an implicit indices[i+1]=len(array) * assumed when i=end-1 * * if indices[i+1] <= indices[i]+1 * then the result is array[indices[i]] for that value * * op.accumulate(array) is the same as * op.reduceat(array,indices)[::2] * where indices is range(len(array)-1) with a zero placed in every other sample * indices = zeros(len(array)*2-1) * indices[1::2] = range(1,len(array)) * * output shape is based on the size of indices */ static PyObject * PyUFunc_Reduceat(PyUFuncObject *ufunc, PyArrayObject *arr, PyArrayObject *ind, PyArrayObject *out, int axis, int otype) { PyArrayObject *op[3]; PyArray_Descr *op_dtypes[3] = {NULL, NULL, NULL}; int op_axes_arrays[3][NPY_MAXDIMS]; int *op_axes[3] = {op_axes_arrays[0], op_axes_arrays[1], op_axes_arrays[2]}; npy_uint32 op_flags[3]; int i, idim, ndim, otype_final; int needs_api, need_outer_iterator; NpyIter *iter = NULL; /* The reduceat indices - ind must be validated outside this call */ npy_intp *reduceat_ind; npy_intp ind_size, red_axis_size; /* The selected inner loop */ PyUFuncGenericFunction innerloop = NULL; void *innerloopdata = NULL; char *ufunc_name = ufunc->name ? ufunc->name : "(unknown)"; char *opname = "reduceat"; /* These parameters come from extobj= or from a TLS global */ int buffersize = 0, errormask = 0; PyObject *errobj = NULL; NPY_BEGIN_THREADS_DEF; reduceat_ind = (npy_intp *)PyArray_DATA(ind); ind_size = PyArray_DIM(ind, 0); red_axis_size = PyArray_DIM(arr, axis); /* Check for out-of-bounds values in indices array */ for (i = 0; i < ind_size; ++i) { if (reduceat_ind[i] < 0 || reduceat_ind[i] >= red_axis_size) { PyErr_Format(PyExc_IndexError, "index %d out-of-bounds in %s.%s [0, %d)", (int)reduceat_ind[i], ufunc_name, opname, (int)red_axis_size); return NULL; } } NPY_UF_DBG_PRINT2("\nEvaluating ufunc %s.%s\n", ufunc_name, opname); #if 0 printf("Doing %s.%s on array with dtype : ", ufunc_name, opname); PyObject_Print((PyObject *)PyArray_DESCR(arr), stdout, 0); printf("\n"); printf("Index size is %d\n", (int)ind_size); #endif if (PyUFunc_GetPyValues(opname, &buffersize, &errormask, &errobj) < 0) { return NULL; } /* Take a reference to out for later returning */ Py_XINCREF(out); otype_final = otype; if (get_binary_op_function(ufunc, &otype_final, &innerloop, &innerloopdata) < 0) { PyArray_Descr *dtype = PyArray_DescrFromType(otype); PyErr_Format(PyExc_ValueError, "could not find a matching type for %s.%s, " "requested type has type code '%c'", ufunc_name, opname, dtype ? dtype->type : '-'); Py_XDECREF(dtype); goto fail; } ndim = PyArray_NDIM(arr); /* * Set up the output data type, using the input's exact * data type if the type number didn't change to preserve * metadata */ if (PyArray_DESCR(arr)->type_num == otype_final) { if (PyArray_ISNBO(PyArray_DESCR(arr)->byteorder)) { op_dtypes[0] = PyArray_DESCR(arr); Py_INCREF(op_dtypes[0]); } else { op_dtypes[0] = PyArray_DescrNewByteorder(PyArray_DESCR(arr), NPY_NATIVE); } } else { op_dtypes[0] = PyArray_DescrFromType(otype_final); } if (op_dtypes[0] == NULL) { goto fail; } #if NPY_UF_DBG_TRACING printf("Found %s.%s inner loop with dtype : ", ufunc_name, opname); PyObject_Print((PyObject *)op_dtypes[0], stdout, 0); printf("\n"); #endif /* Set up the op_axes for the outer loop */ for (i = 0, idim = 0; idim < ndim; ++idim) { /* Use the i-th iteration dimension to match up ind */ if (idim == axis) { op_axes_arrays[0][idim] = axis; op_axes_arrays[1][idim] = -1; op_axes_arrays[2][idim] = 0; } else { op_axes_arrays[0][idim] = idim; op_axes_arrays[1][idim] = idim; op_axes_arrays[2][idim] = -1; } } op[0] = out; op[1] = arr; op[2] = ind; if (out != NULL || ndim > 1 || !PyArray_ISALIGNED(arr) || !PyArray_EquivTypes(op_dtypes[0], PyArray_DESCR(arr))) { need_outer_iterator = 1; } /* Special case when the index array's size is zero */ if (ind_size == 0) { if (out == NULL) { npy_intp out_shape[NPY_MAXDIMS]; memcpy(out_shape, PyArray_SHAPE(arr), PyArray_NDIM(arr) * NPY_SIZEOF_INTP); out_shape[axis] = 0; Py_INCREF(op_dtypes[0]); op[0] = out = (PyArrayObject *)PyArray_NewFromDescr( &PyArray_Type, op_dtypes[0], PyArray_NDIM(arr), out_shape, NULL, NULL, 0, NULL); if (out == NULL) { goto fail; } } else { /* Allow any zero-sized output array in this case */ if (PyArray_SIZE(out) != 0) { PyErr_SetString(PyExc_ValueError, "output operand shape for reduceat is " "incompatible with index array of shape (0,)"); goto fail; } } goto finish; } if (need_outer_iterator) { npy_uint32 flags = NPY_ITER_ZEROSIZE_OK| NPY_ITER_REFS_OK| NPY_ITER_MULTI_INDEX; /* * The way reduceat is set up, we can't do buffering, * so make a copy instead when necessary using * the UPDATEIFCOPY flag */ /* The per-operand flags for the outer loop */ op_flags[0] = NPY_ITER_READWRITE| NPY_ITER_NO_BROADCAST| NPY_ITER_ALLOCATE| NPY_ITER_NO_SUBTYPE| NPY_ITER_UPDATEIFCOPY| NPY_ITER_ALIGNED; op_flags[1] = NPY_ITER_READONLY| NPY_ITER_COPY| NPY_ITER_ALIGNED; op_flags[2] = NPY_ITER_READONLY; op_dtypes[1] = op_dtypes[0]; NPY_UF_DBG_PRINT("Allocating outer iterator\n"); iter = NpyIter_AdvancedNew(3, op, flags, NPY_KEEPORDER, NPY_UNSAFE_CASTING, op_flags, op_dtypes, ndim, op_axes, NULL, 0); if (iter == NULL) { goto fail; } /* Remove the inner loop axis from the outer iterator */ if (NpyIter_RemoveAxis(iter, axis) != NPY_SUCCEED) { goto fail; } if (NpyIter_RemoveMultiIndex(iter) != NPY_SUCCEED) { goto fail; } /* In case COPY or UPDATEIFCOPY occurred */ op[0] = NpyIter_GetOperandArray(iter)[0]; op[1] = NpyIter_GetOperandArray(iter)[1]; if (out == NULL) { out = op[0]; Py_INCREF(out); } } /* Allocate the output for when there's no outer iterator */ else if (out == NULL) { Py_INCREF(op_dtypes[0]); op[0] = out = (PyArrayObject *)PyArray_NewFromDescr( &PyArray_Type, op_dtypes[0], 1, &ind_size, NULL, NULL, 0, NULL); if (out == NULL) { goto fail; } } /* * If the output has zero elements, return now. */ if (PyArray_SIZE(op[0]) == 0) { goto finish; } if (iter && NpyIter_GetIterSize(iter) != 0) { char *dataptr_copy[3]; npy_intp stride_copy[3]; NpyIter_IterNextFunc *iternext; char **dataptr; npy_intp count_m1; npy_intp stride0, stride1; npy_intp stride0_ind = PyArray_STRIDE(op[0], axis); int itemsize = op_dtypes[0]->elsize; /* Get the variables needed for the loop */ iternext = NpyIter_GetIterNext(iter, NULL); if (iternext == NULL) { goto fail; } dataptr = NpyIter_GetDataPtrArray(iter); /* Execute the loop with just the outer iterator */ count_m1 = PyArray_DIM(op[1], axis)-1; stride0 = 0; stride1 = PyArray_STRIDE(op[1], axis); NPY_UF_DBG_PRINT("UFunc: Reduce loop with just outer iterator\n"); stride_copy[0] = stride0; stride_copy[1] = stride1; stride_copy[2] = stride0; needs_api = NpyIter_IterationNeedsAPI(iter); if (!needs_api) { NPY_BEGIN_THREADS; } do { for (i = 0; i < ind_size; ++i) { npy_intp start = reduceat_ind[i], end = (i == ind_size-1) ? count_m1+1 : reduceat_ind[i+1]; npy_intp count = end - start; dataptr_copy[0] = dataptr[0] + stride0_ind*i; dataptr_copy[1] = dataptr[1] + stride1*start; dataptr_copy[2] = dataptr[0] + stride0_ind*i; /* Copy the first element to start the reduction */ if (otype == NPY_OBJECT) { Py_XDECREF(*(PyObject **)dataptr_copy[0]); *(PyObject **)dataptr_copy[0] = *(PyObject **)dataptr_copy[1]; Py_XINCREF(*(PyObject **)dataptr_copy[0]); } else { memcpy(dataptr_copy[0], dataptr_copy[1], itemsize); } if (count > 1) { /* Inner loop like REDUCE */ --count; dataptr_copy[1] += stride1; NPY_UF_DBG_PRINT1("iterator loop count %d\n", (int)count); innerloop(dataptr_copy, &count, stride_copy, innerloopdata); } } } while (iternext(iter)); if (!needs_api) { NPY_END_THREADS; } } else if (iter == NULL) { char *dataptr_copy[3]; npy_intp stride_copy[3]; int itemsize = op_dtypes[0]->elsize; npy_intp stride0_ind = PyArray_STRIDE(op[0], axis); /* Execute the loop with no iterators */ npy_intp stride0 = 0, stride1 = PyArray_STRIDE(op[1], axis); needs_api = PyDataType_REFCHK(op_dtypes[0]); NPY_UF_DBG_PRINT("UFunc: Reduce loop with no iterators\n"); stride_copy[0] = stride0; stride_copy[1] = stride1; stride_copy[2] = stride0; if (!needs_api) { NPY_BEGIN_THREADS; } for (i = 0; i < ind_size; ++i) { npy_intp start = reduceat_ind[i], end = (i == ind_size-1) ? PyArray_DIM(arr,axis) : reduceat_ind[i+1]; npy_intp count = end - start; dataptr_copy[0] = PyArray_BYTES(op[0]) + stride0_ind*i; dataptr_copy[1] = PyArray_BYTES(op[1]) + stride1*start; dataptr_copy[2] = PyArray_BYTES(op[0]) + stride0_ind*i; /* Copy the first element to start the reduction */ if (otype == NPY_OBJECT) { Py_XDECREF(*(PyObject **)dataptr_copy[0]); *(PyObject **)dataptr_copy[0] = *(PyObject **)dataptr_copy[1]; Py_XINCREF(*(PyObject **)dataptr_copy[0]); } else { memcpy(dataptr_copy[0], dataptr_copy[1], itemsize); } if (count > 1) { /* Inner loop like REDUCE */ --count; dataptr_copy[1] += stride1; NPY_UF_DBG_PRINT1("iterator loop count %d\n", (int)count); innerloop(dataptr_copy, &count, stride_copy, innerloopdata); } } if (!needs_api) { NPY_END_THREADS; } } finish: Py_XDECREF(op_dtypes[0]); if (iter != NULL) { NpyIter_Deallocate(iter); } Py_XDECREF(errobj); return (PyObject *)out; fail: Py_XDECREF(out); Py_XDECREF(op_dtypes[0]); if (iter != NULL) { NpyIter_Deallocate(iter); } Py_XDECREF(errobj); return NULL; } /* * This code handles reduce, reduceat, and accumulate * (accumulate and reduce are special cases of the more general reduceat * but they are handled separately for speed) */ static PyObject * PyUFunc_GenericReduction(PyUFuncObject *ufunc, PyObject *args, PyObject *kwds, int operation) { int i, naxes=0, ndim; int axes[NPY_MAXDIMS]; PyObject *axes_in = NULL; PyArrayObject *mp, *ret = NULL; PyObject *op, *res = NULL; PyObject *obj_ind, *context; PyArrayObject *indices = NULL; PyArray_Descr *otype = NULL; PyArrayObject *out = NULL; int keepdims = 0; static char *kwlist1[] = {"array", "axis", "dtype", "out", "keepdims", NULL}; static char *kwlist2[] = {"array", "indices", "axis", "dtype", "out", NULL}; static char *_reduce_type[] = {"reduce", "accumulate", "reduceat", NULL}; if (ufunc == NULL) { PyErr_SetString(PyExc_ValueError, "function not supported"); return NULL; } if (ufunc->core_enabled) { PyErr_Format(PyExc_RuntimeError, "Reduction not defined on ufunc with signature"); return NULL; } if (ufunc->nin != 2) { PyErr_Format(PyExc_ValueError, "%s only supported for binary functions", _reduce_type[operation]); return NULL; } if (ufunc->nout != 1) { PyErr_Format(PyExc_ValueError, "%s only supported for functions " "returning a single value", _reduce_type[operation]); return NULL; } if (operation == UFUNC_REDUCEAT) { PyArray_Descr *indtype; indtype = PyArray_DescrFromType(NPY_INTP); if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO|OO&O&", kwlist2, &op, &obj_ind, &axes_in, PyArray_DescrConverter2, &otype, PyArray_OutputConverter, &out)) { Py_XDECREF(otype); return NULL; } indices = (PyArrayObject *)PyArray_FromAny(obj_ind, indtype, 1, 1, NPY_ARRAY_CARRAY, NULL); if (indices == NULL) { Py_XDECREF(otype); return NULL; } } else if (operation == UFUNC_ACCUMULATE) { if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|OO&O&i", kwlist1, &op, &axes_in, PyArray_DescrConverter2, &otype, PyArray_OutputConverter, &out, &keepdims)) { Py_XDECREF(otype); return NULL; } } else { if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|OO&O&i", kwlist1, &op, &axes_in, PyArray_DescrConverter2, &otype, PyArray_OutputConverter, &out, &keepdims)) { Py_XDECREF(otype); return NULL; } } /* Ensure input is an array */ if (!PyArray_Check(op) && !PyArray_IsScalar(op, Generic)) { context = Py_BuildValue("O(O)i", ufunc, op, 0); } else { context = NULL; } mp = (PyArrayObject *)PyArray_FromAny(op, NULL, 0, 0, 0, context); Py_XDECREF(context); if (mp == NULL) { return NULL; } ndim = PyArray_NDIM(mp); /* Check to see that type (and otype) is not FLEXIBLE */ if (PyArray_ISFLEXIBLE(mp) || (otype && PyTypeNum_ISFLEXIBLE(otype->type_num))) { PyErr_Format(PyExc_TypeError, "cannot perform %s with flexible type", _reduce_type[operation]); Py_XDECREF(otype); Py_DECREF(mp); return NULL; } /* Convert the 'axis' parameter into a list of axes */ if (axes_in == NULL) { naxes = 1; axes[0] = 0; } /* Convert 'None' into all the axes */ else if (axes_in == Py_None) { naxes = ndim; for (i = 0; i < naxes; ++i) { axes[i] = i; } } else if (PyTuple_Check(axes_in)) { naxes = PyTuple_Size(axes_in); if (naxes < 0 || naxes > NPY_MAXDIMS) { PyErr_SetString(PyExc_ValueError, "too many values for 'axis'"); Py_XDECREF(otype); Py_DECREF(mp); return NULL; } for (i = 0; i < naxes; ++i) { PyObject *tmp = PyTuple_GET_ITEM(axes_in, i); long axis = PyInt_AsLong(tmp); if (axis == -1 && PyErr_Occurred()) { Py_XDECREF(otype); Py_DECREF(mp); return NULL; } if (axis < 0) { axis += ndim; } if (axis < 0 || axis >= ndim) { PyErr_SetString(PyExc_ValueError, "'axis' entry is out of bounds"); Py_XDECREF(otype); Py_DECREF(mp); return NULL; } axes[i] = (int)axis; } } /* Try to interpret axis as an integer */ else { long axis = PyInt_AsLong(axes_in); /* TODO: PyNumber_Index would be good to use here */ if (axis == -1 && PyErr_Occurred()) { Py_XDECREF(otype); Py_DECREF(mp); return NULL; } if (axis < 0) { axis += ndim; } /* Special case letting axis={0 or -1} slip through for scalars */ if (ndim == 0 && (axis == 0 || axis == -1)) { axis = 0; } else if (axis < 0 || axis >= ndim) { PyErr_SetString(PyExc_ValueError, "'axis' entry is out of bounds"); Py_XDECREF(otype); Py_DECREF(mp); return NULL; } axes[0] = (int)axis; naxes = 1; } /* Check to see if input is zero-dimensional. */ if (ndim == 0) { /* * A reduction with no axes is still valid but trivial. * As a special case for backwards compatibility in 'sum', * 'prod', et al, also allow a reduction where axis=0, even * though this is technically incorrect. */ naxes = 0; if (!(operation == UFUNC_REDUCE && (naxes == 0 || (naxes == 1 && axes[0] == 0)))) { PyErr_Format(PyExc_TypeError, "cannot %s on a scalar", _reduce_type[operation]); Py_XDECREF(otype); Py_DECREF(mp); return NULL; } } /* * If out is specified it determines otype * unless otype already specified. */ if (otype == NULL && out != NULL) { otype = PyArray_DESCR(out); Py_INCREF(otype); } if (otype == NULL) { /* * For integer types --- make sure at least a long * is used for add and multiply reduction to avoid overflow */ int typenum = PyArray_TYPE(mp); if ((PyTypeNum_ISBOOL(typenum) || PyTypeNum_ISINTEGER(typenum)) && ((strcmp(ufunc->name,"add") == 0) || (strcmp(ufunc->name,"multiply") == 0))) { if (PyTypeNum_ISBOOL(typenum)) { typenum = NPY_LONG; } else if ((size_t)PyArray_DESCR(mp)->elsize < sizeof(long)) { if (PyTypeNum_ISUNSIGNED(typenum)) { typenum = NPY_ULONG; } else { typenum = NPY_LONG; } } } otype = PyArray_DescrFromType(typenum); } switch(operation) { case UFUNC_REDUCE: ret = PyUFunc_Reduce(ufunc, mp, out, naxes, axes, otype, keepdims); break; case UFUNC_ACCUMULATE: if (naxes != 1) { PyErr_SetString(PyExc_ValueError, "accumulate does not allow multiple axes"); Py_XDECREF(otype); Py_DECREF(mp); return NULL; } ret = (PyArrayObject *)PyUFunc_Accumulate(ufunc, mp, out, axes[0], otype->type_num); break; case UFUNC_REDUCEAT: if (naxes != 1) { PyErr_SetString(PyExc_ValueError, "reduceat does not allow multiple axes"); Py_XDECREF(otype); Py_DECREF(mp); return NULL; } ret = (PyArrayObject *)PyUFunc_Reduceat(ufunc, mp, indices, out, axes[0], otype->type_num); Py_DECREF(indices); break; } Py_DECREF(mp); Py_DECREF(otype); if (ret == NULL) { return NULL; } /* If an output parameter was provided, don't wrap it */ if (out != NULL) { return (PyObject *)ret; } if (Py_TYPE(op) != Py_TYPE(ret)) { res = PyObject_CallMethod(op, "__array_wrap__", "O", ret); if (res == NULL) { PyErr_Clear(); } else if (res == Py_None) { Py_DECREF(res); } else { Py_DECREF(ret); return res; } } return PyArray_Return(ret); } /* * This function analyzes the input arguments * and determines an appropriate __array_wrap__ function to call * for the outputs. * * If an output argument is provided, then it is wrapped * with its own __array_wrap__ not with the one determined by * the input arguments. * * if the provided output argument is already an array, * the wrapping function is None (which means no wrapping will * be done --- not even PyArray_Return). * * A NULL is placed in output_wrap for outputs that * should just have PyArray_Return called. */ static void _find_array_wrap(PyObject *args, PyObject *kwds, PyObject **output_wrap, int nin, int nout) { Py_ssize_t nargs; int i; int np = 0; PyObject *with_wrap[NPY_MAXARGS], *wraps[NPY_MAXARGS]; PyObject *obj, *wrap = NULL; /* If a 'subok' parameter is passed and isn't True, don't wrap */ if (kwds != NULL && (obj = PyDict_GetItemString(kwds, "subok")) != NULL) { if (obj != Py_True) { for (i = 0; i < nout; i++) { output_wrap[i] = NULL; } return; } } nargs = PyTuple_GET_SIZE(args); for (i = 0; i < nin; i++) { obj = PyTuple_GET_ITEM(args, i); if (PyArray_CheckExact(obj) || PyArray_IsAnyScalar(obj)) { continue; } wrap = PyObject_GetAttrString(obj, "__array_wrap__"); if (wrap) { if (PyCallable_Check(wrap)) { with_wrap[np] = obj; wraps[np] = wrap; ++np; } else { Py_DECREF(wrap); wrap = NULL; } } else { PyErr_Clear(); } } if (np > 0) { /* If we have some wraps defined, find the one of highest priority */ wrap = wraps[0]; if (np > 1) { double maxpriority = PyArray_GetPriority(with_wrap[0], NPY_PRIORITY); for (i = 1; i < np; ++i) { double priority = PyArray_GetPriority(with_wrap[i], NPY_PRIORITY); if (priority > maxpriority) { maxpriority = priority; Py_DECREF(wrap); wrap = wraps[i]; } else { Py_DECREF(wraps[i]); } } } } /* * Here wrap is the wrapping function determined from the * input arrays (could be NULL). * * For all the output arrays decide what to do. * * 1) Use the wrap function determined from the input arrays * This is the default if the output array is not * passed in. * * 2) Use the __array_wrap__ method of the output object * passed in. -- this is special cased for * exact ndarray so that no PyArray_Return is * done in that case. */ for (i = 0; i < nout; i++) { int j = nin + i; int incref = 1; output_wrap[i] = wrap; obj = NULL; if (j < nargs) { obj = PyTuple_GET_ITEM(args, j); /* Output argument one may also be in a keyword argument */ if (i == 0 && obj == Py_None && kwds != NULL) { obj = PyDict_GetItemString(kwds, "out"); } } /* Output argument one may also be in a keyword argument */ else if (i == 0 && kwds != NULL) { obj = PyDict_GetItemString(kwds, "out"); } if (obj != Py_None && obj != NULL) { if (PyArray_CheckExact(obj)) { /* None signals to not call any wrapping */ output_wrap[i] = Py_None; } else { PyObject *owrap = PyObject_GetAttrString(obj,"__array_wrap__"); incref = 0; if (!(owrap) || !(PyCallable_Check(owrap))) { Py_XDECREF(owrap); owrap = wrap; incref = 1; PyErr_Clear(); } output_wrap[i] = owrap; } } if (incref) { Py_XINCREF(output_wrap[i]); } } Py_XDECREF(wrap); return; } static PyObject * ufunc_generic_call(PyUFuncObject *ufunc, PyObject *args, PyObject *kwds) { int i; PyTupleObject *ret; PyArrayObject *mps[NPY_MAXARGS]; PyObject *retobj[NPY_MAXARGS]; PyObject *wraparr[NPY_MAXARGS]; PyObject *res; int errval; /* * Initialize all array objects to NULL to make cleanup easier * if something goes wrong. */ for (i = 0; i < ufunc->nargs; i++) { mps[i] = NULL; } errval = PyUFunc_GenericFunction(ufunc, args, kwds, mps); if (errval < 0) { for (i = 0; i < ufunc->nargs; i++) { PyArray_XDECREF_ERR(mps[i]); } if (errval == -1) { return NULL; } else if (ufunc->nin == 2 && ufunc->nout == 1) { /* To allow the other argument to be given a chance */ Py_INCREF(Py_NotImplemented); return Py_NotImplemented; } else { PyErr_SetString(PyExc_TypeError, "Not implemented for this type"); return NULL; } } /* Free the input references */ for (i = 0; i < ufunc->nin; i++) { Py_XDECREF(mps[i]); } /* * Use __array_wrap__ on all outputs * if present on one of the input arguments. * If present for multiple inputs: * use __array_wrap__ of input object with largest * __array_priority__ (default = 0.0) * * Exception: we should not wrap outputs for items already * passed in as output-arguments. These items should either * be left unwrapped or wrapped by calling their own __array_wrap__ * routine. * * For each output argument, wrap will be either * NULL --- call PyArray_Return() -- default if no output arguments given * None --- array-object passed in don't call PyArray_Return * method --- the __array_wrap__ method to call. */ _find_array_wrap(args, kwds, wraparr, ufunc->nin, ufunc->nout); /* wrap outputs */ for (i = 0; i < ufunc->nout; i++) { int j = ufunc->nin+i; PyObject *wrap = wraparr[i]; if (wrap != NULL) { if (wrap == Py_None) { Py_DECREF(wrap); retobj[i] = (PyObject *)mps[j]; continue; } res = PyObject_CallFunction(wrap, "O(OOi)", mps[j], ufunc, args, i); if (res == NULL && PyErr_ExceptionMatches(PyExc_TypeError)) { PyErr_Clear(); res = PyObject_CallFunctionObjArgs(wrap, mps[j], NULL); } Py_DECREF(wrap); if (res == NULL) { goto fail; } else if (res == Py_None) { Py_DECREF(res); } else { Py_DECREF(mps[j]); retobj[i] = res; continue; } } else { /* default behavior */ retobj[i] = PyArray_Return(mps[j]); } } if (ufunc->nout == 1) { return retobj[0]; } else { ret = (PyTupleObject *)PyTuple_New(ufunc->nout); for (i = 0; i < ufunc->nout; i++) { PyTuple_SET_ITEM(ret, i, retobj[i]); } return (PyObject *)ret; } fail: for (i = ufunc->nin; i < ufunc->nargs; i++) { Py_XDECREF(mps[i]); } return NULL; } NPY_NO_EXPORT PyObject * ufunc_geterr(PyObject *NPY_UNUSED(dummy), PyObject *args) { PyObject *thedict; PyObject *res; if (!PyArg_ParseTuple(args, "")) { return NULL; } if (PyUFunc_PYVALS_NAME == NULL) { PyUFunc_PYVALS_NAME = PyUString_InternFromString(UFUNC_PYVALS_NAME); } thedict = PyThreadState_GetDict(); if (thedict == NULL) { thedict = PyEval_GetBuiltins(); } res = PyDict_GetItem(thedict, PyUFunc_PYVALS_NAME); if (res != NULL) { Py_INCREF(res); return res; } /* Construct list of defaults */ res = PyList_New(3); if (res == NULL) { return NULL; } PyList_SET_ITEM(res, 0, PyInt_FromLong(NPY_BUFSIZE)); PyList_SET_ITEM(res, 1, PyInt_FromLong(UFUNC_ERR_DEFAULT)); PyList_SET_ITEM(res, 2, Py_None); Py_INCREF(Py_None); return res; } #if USE_USE_DEFAULTS==1 /* * This is a strategy to buy a little speed up and avoid the dictionary * look-up in the default case. It should work in the presence of * threads. If it is deemed too complicated or it doesn't actually work * it could be taken out. */ static int ufunc_update_use_defaults(void) { PyObject *errobj = NULL; int errmask, bufsize; int res; PyUFunc_NUM_NODEFAULTS += 1; res = PyUFunc_GetPyValues("test", &bufsize, &errmask, &errobj); PyUFunc_NUM_NODEFAULTS -= 1; if (res < 0) { Py_XDECREF(errobj); return -1; } if ((errmask != UFUNC_ERR_DEFAULT) || (bufsize != NPY_BUFSIZE) || (PyTuple_GET_ITEM(errobj, 1) != Py_None)) { PyUFunc_NUM_NODEFAULTS += 1; } else if (PyUFunc_NUM_NODEFAULTS > 0) { PyUFunc_NUM_NODEFAULTS -= 1; } Py_XDECREF(errobj); return 0; } #endif NPY_NO_EXPORT PyObject * ufunc_seterr(PyObject *NPY_UNUSED(dummy), PyObject *args) { PyObject *thedict; int res; PyObject *val; static char *msg = "Error object must be a list of length 3"; if (!PyArg_ParseTuple(args, "O", &val)) { return NULL; } if (!PyList_CheckExact(val) || PyList_GET_SIZE(val) != 3) { PyErr_SetString(PyExc_ValueError, msg); return NULL; } if (PyUFunc_PYVALS_NAME == NULL) { PyUFunc_PYVALS_NAME = PyUString_InternFromString(UFUNC_PYVALS_NAME); } thedict = PyThreadState_GetDict(); if (thedict == NULL) { thedict = PyEval_GetBuiltins(); } res = PyDict_SetItem(thedict, PyUFunc_PYVALS_NAME, val); if (res < 0) { return NULL; } #if USE_USE_DEFAULTS==1 if (ufunc_update_use_defaults() < 0) { return NULL; } #endif Py_INCREF(Py_None); return Py_None; } /*UFUNC_API*/ NPY_NO_EXPORT int PyUFunc_ReplaceLoopBySignature(PyUFuncObject *func, PyUFuncGenericFunction newfunc, int *signature, PyUFuncGenericFunction *oldfunc) { int i, j; int res = -1; /* Find the location of the matching signature */ for (i = 0; i < func->ntypes; i++) { for (j = 0; j < func->nargs; j++) { if (signature[j] != func->types[i*func->nargs+j]) { break; } } if (j < func->nargs) { continue; } if (oldfunc != NULL) { *oldfunc = func->functions[i]; } func->functions[i] = newfunc; res = 0; break; } return res; } /*UFUNC_API*/ 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) { return PyUFunc_FromFuncAndDataAndSignature(func, data, types, ntypes, nin, nout, identity, name, doc, check_return, NULL); } /*UFUNC_API*/ NPY_NO_EXPORT PyObject * PyUFunc_FromFuncAndDataAndSignature(PyUFuncGenericFunction *func, void **data, char *types, int ntypes, int nin, int nout, int identity, char *name, char *doc, int check_return, const char *signature) { PyUFuncObject *ufunc; ufunc = PyArray_malloc(sizeof(PyUFuncObject)); if (ufunc == NULL) { return NULL; } PyObject_Init((PyObject *)ufunc, &PyUFunc_Type); ufunc->nin = nin; ufunc->nout = nout; ufunc->nargs = nin+nout; ufunc->identity = identity; ufunc->functions = func; ufunc->data = data; ufunc->types = types; ufunc->ntypes = ntypes; ufunc->check_return = check_return; ufunc->ptr = NULL; ufunc->obj = NULL; ufunc->userloops=NULL; /* Type resolution and inner loop selection functions */ ufunc->type_resolver = &PyUFunc_DefaultTypeResolver; ufunc->legacy_inner_loop_selector = &PyUFunc_DefaultLegacyInnerLoopSelector; ufunc->inner_loop_selector = NULL; ufunc->masked_inner_loop_selector = &PyUFunc_DefaultMaskedInnerLoopSelector; if (name == NULL) { ufunc->name = "?"; } else { ufunc->name = name; } ufunc->doc = doc; ufunc->op_flags = PyArray_malloc(sizeof(npy_uint32)*ufunc->nargs); if (ufunc->op_flags == NULL) { return PyErr_NoMemory(); } memset(ufunc->op_flags, 0, sizeof(npy_uint32)*ufunc->nargs); ufunc->iter_flags = 0; /* generalized ufunc */ ufunc->core_enabled = 0; ufunc->core_num_dim_ix = 0; ufunc->core_num_dims = NULL; ufunc->core_dim_ixs = NULL; ufunc->core_offsets = NULL; ufunc->core_signature = NULL; if (signature != NULL) { if (_parse_signature(ufunc, signature) != 0) { Py_DECREF(ufunc); return NULL; } } return (PyObject *)ufunc; } /* Specify that the loop specified by the given index should use the array of * input and arrays as the data pointer to the loop. */ /*UFUNC_API*/ NPY_NO_EXPORT int PyUFunc_SetUsesArraysAsData(void **data, size_t i) { data[i] = (void*)PyUFunc_SetUsesArraysAsData; return 0; } /* * Return 1 if the given data pointer for the loop specifies that it needs the * arrays as the data pointer. * * NOTE: This is easier to specify with the type_resolver * in the ufunc object. * * TODO: Remove this, since this is already basically broken * with the addition of the masked inner loops and * not worth fixing since the new loop selection functions * have access to the full dtypes and can dynamically allocate * arbitrary auxiliary data. */ static int _does_loop_use_arrays(void *data) { return (data == PyUFunc_SetUsesArraysAsData); } /* * This is the first-part of the CObject structure. * * I don't think this will change, but if it should, then * this needs to be fixed. The exposed C-API was insufficient * because I needed to replace the pointer and it wouldn't * let me with a destructor set (even though it works fine * with the destructor). */ typedef struct { PyObject_HEAD void *c_obj; } _simple_cobj; #define _SETCPTR(cobj, val) ((_simple_cobj *)(cobj))->c_obj = (val) /* return 1 if arg1 > arg2, 0 if arg1 == arg2, and -1 if arg1 < arg2 */ static int cmp_arg_types(int *arg1, int *arg2, int n) { for (; n > 0; n--, arg1++, arg2++) { if (PyArray_EquivTypenums(*arg1, *arg2)) { continue; } if (PyArray_CanCastSafely(*arg1, *arg2)) { return -1; } return 1; } return 0; } /* * This frees the linked-list structure when the CObject * is destroyed (removed from the internal dictionary) */ static NPY_INLINE void _free_loop1d_list(PyUFunc_Loop1d *data) { int i; while (data != NULL) { PyUFunc_Loop1d *next = data->next; PyArray_free(data->arg_types); if (data->arg_dtypes != NULL) { for (i = 0; i < data->nargs; i++) { Py_DECREF(data->arg_dtypes[i]); } PyArray_free(data->arg_dtypes); } PyArray_free(data); data = next; } } #if PY_VERSION_HEX >= 0x03000000 static void _loop1d_list_free(PyObject *ptr) { PyUFunc_Loop1d *data = (PyUFunc_Loop1d *)PyCapsule_GetPointer(ptr, NULL); _free_loop1d_list(data); } #else static void _loop1d_list_free(void *ptr) { PyUFunc_Loop1d *data = (PyUFunc_Loop1d *)ptr; _free_loop1d_list(data); } #endif /* * This function allows the user to register a 1-d loop with an already * created ufunc. This function is similar to RegisterLoopForType except * that it allows a 1-d loop to be registered with PyArray_Descr objects * instead of dtype type num values. This allows a 1-d loop to be registered * for a structured array dtype or a custom dtype. The ufunc is called * whenever any of it's input arguments match the user_dtype argument. * ufunc - ufunc object created from call to PyUFunc_FromFuncAndData * user_dtype - dtype that ufunc will be registered with * function - 1-d loop function pointer * arg_dtypes - array of dtype objects describing the ufunc operands * data - arbitrary data pointer passed in to loop function */ /*UFUNC_API*/ NPY_NO_EXPORT int PyUFunc_RegisterLoopForDescr(PyUFuncObject *ufunc, PyArray_Descr *user_dtype, PyUFuncGenericFunction function, PyArray_Descr **arg_dtypes, void *data) { int i; int result = 0; int *arg_typenums; PyObject *key, *cobj; if (user_dtype == NULL) { PyErr_SetString(PyExc_TypeError, "unknown user defined struct dtype"); return -1; } key = PyInt_FromLong((long) user_dtype->type_num); if (key == NULL) { return -1; } arg_typenums = PyArray_malloc(ufunc->nargs * sizeof(int)); if (arg_typenums == NULL) { PyErr_NoMemory(); return -1; } if (arg_dtypes != NULL) { for (i = 0; i < ufunc->nargs; i++) { arg_typenums[i] = arg_dtypes[i]->type_num; } } else { for (i = 0; i < ufunc->nargs; i++) { arg_typenums[i] = user_dtype->type_num; } } result = PyUFunc_RegisterLoopForType(ufunc, user_dtype->type_num, function, arg_typenums, data); if (result == 0) { cobj = PyDict_GetItem(ufunc->userloops, key); if (cobj == NULL) { PyErr_SetString(PyExc_KeyError, "userloop for user dtype not found"); result = -1; } else { PyUFunc_Loop1d *current, *prev = NULL; int cmp = 1; current = (PyUFunc_Loop1d *)NpyCapsule_AsVoidPtr(cobj); while (current != NULL) { cmp = cmp_arg_types(current->arg_types, arg_typenums, ufunc->nargs); if (cmp >= 0 && current->arg_dtypes == NULL) { break; } prev = current; current = current->next; } if (cmp == 0 && current->arg_dtypes == NULL) { current->arg_dtypes = PyArray_malloc(ufunc->nargs * sizeof(PyArray_Descr*)); if (arg_dtypes != NULL) { for (i = 0; i < ufunc->nargs; i++) { current->arg_dtypes[i] = arg_dtypes[i]; Py_INCREF(current->arg_dtypes[i]); } } else { for (i = 0; i < ufunc->nargs; i++) { current->arg_dtypes[i] = user_dtype; Py_INCREF(current->arg_dtypes[i]); } } current->nargs = ufunc->nargs; } else { result = -1; } } } PyArray_free(arg_typenums); Py_DECREF(key); return result; } /*UFUNC_API*/ NPY_NO_EXPORT int PyUFunc_RegisterLoopForType(PyUFuncObject *ufunc, int usertype, PyUFuncGenericFunction function, int *arg_types, void *data) { PyArray_Descr *descr; PyUFunc_Loop1d *funcdata; PyObject *key, *cobj; int i; int *newtypes=NULL; descr=PyArray_DescrFromType(usertype); if ((usertype < NPY_USERDEF && usertype != NPY_VOID) || (descr==NULL)) { PyErr_SetString(PyExc_TypeError, "unknown user-defined type"); return -1; } Py_DECREF(descr); if (ufunc->userloops == NULL) { ufunc->userloops = PyDict_New(); } key = PyInt_FromLong((long) usertype); if (key == NULL) { return -1; } funcdata = PyArray_malloc(sizeof(PyUFunc_Loop1d)); if (funcdata == NULL) { goto fail; } newtypes = PyArray_malloc(sizeof(int)*ufunc->nargs); if (newtypes == NULL) { goto fail; } if (arg_types != NULL) { for (i = 0; i < ufunc->nargs; i++) { newtypes[i] = arg_types[i]; } } else { for (i = 0; i < ufunc->nargs; i++) { newtypes[i] = usertype; } } funcdata->func = function; funcdata->arg_types = newtypes; funcdata->data = data; funcdata->next = NULL; funcdata->arg_dtypes = NULL; funcdata->nargs = 0; /* Get entry for this user-defined type*/ cobj = PyDict_GetItem(ufunc->userloops, key); /* If it's not there, then make one and return. */ if (cobj == NULL) { cobj = NpyCapsule_FromVoidPtr((void *)funcdata, _loop1d_list_free); if (cobj == NULL) { goto fail; } PyDict_SetItem(ufunc->userloops, key, cobj); Py_DECREF(cobj); Py_DECREF(key); return 0; } else { PyUFunc_Loop1d *current, *prev = NULL; int cmp = 1; /* * There is already at least 1 loop. Place this one in * lexicographic order. If the next one signature * is exactly like this one, then just replace. * Otherwise insert. */ current = (PyUFunc_Loop1d *)NpyCapsule_AsVoidPtr(cobj); while (current != NULL) { cmp = cmp_arg_types(current->arg_types, newtypes, ufunc->nargs); if (cmp >= 0) { break; } prev = current; current = current->next; } if (cmp == 0) { /* just replace it with new function */ current->func = function; current->data = data; PyArray_free(newtypes); PyArray_free(funcdata); } else { /* * insert it before the current one by hacking the internals * of cobject to replace the function pointer --- can't use * CObject API because destructor is set. */ funcdata->next = current; if (prev == NULL) { /* place this at front */ _SETCPTR(cobj, funcdata); } else { prev->next = funcdata; } } } Py_DECREF(key); return 0; fail: Py_DECREF(key); PyArray_free(funcdata); PyArray_free(newtypes); if (!PyErr_Occurred()) PyErr_NoMemory(); return -1; } #undef _SETCPTR static void ufunc_dealloc(PyUFuncObject *ufunc) { if (ufunc->core_num_dims) { PyArray_free(ufunc->core_num_dims); } if (ufunc->core_dim_ixs) { PyArray_free(ufunc->core_dim_ixs); } if (ufunc->core_offsets) { PyArray_free(ufunc->core_offsets); } if (ufunc->core_signature) { PyArray_free(ufunc->core_signature); } if (ufunc->ptr) { PyArray_free(ufunc->ptr); } if (ufunc->op_flags) { PyArray_free(ufunc->op_flags); } Py_XDECREF(ufunc->userloops); Py_XDECREF(ufunc->obj); PyArray_free(ufunc); } static PyObject * ufunc_repr(PyUFuncObject *ufunc) { char buf[100]; sprintf(buf, "", ufunc->name); return PyUString_FromString(buf); } /****************************************************************************** *** UFUNC METHODS *** *****************************************************************************/ /* * op.outer(a,b) is equivalent to op(a[:,NewAxis,NewAxis,etc.],b) * where a has b.ndim NewAxis terms appended. * * The result has dimensions a.ndim + b.ndim */ static PyObject * ufunc_outer(PyUFuncObject *ufunc, PyObject *args, PyObject *kwds) { int i; PyObject *ret; PyArrayObject *ap1 = NULL, *ap2 = NULL, *ap_new = NULL; PyObject *new_args, *tmp; PyObject *shape1, *shape2, *newshape; if (ufunc->core_enabled) { PyErr_Format(PyExc_TypeError, "method outer is not allowed in ufunc with non-trivial"\ " signature"); return NULL; } if (ufunc->nin != 2) { PyErr_SetString(PyExc_ValueError, "outer product only supported "\ "for binary functions"); return NULL; } if (PySequence_Length(args) != 2) { PyErr_SetString(PyExc_TypeError, "exactly two arguments expected"); return NULL; } tmp = PySequence_GetItem(args, 0); if (tmp == NULL) { return NULL; } ap1 = (PyArrayObject *) PyArray_FromObject(tmp, NPY_NOTYPE, 0, 0); Py_DECREF(tmp); if (ap1 == NULL) { return NULL; } tmp = PySequence_GetItem(args, 1); if (tmp == NULL) { return NULL; } ap2 = (PyArrayObject *)PyArray_FromObject(tmp, NPY_NOTYPE, 0, 0); Py_DECREF(tmp); if (ap2 == NULL) { Py_DECREF(ap1); return NULL; } /* Construct new shape tuple */ shape1 = PyTuple_New(PyArray_NDIM(ap1)); if (shape1 == NULL) { goto fail; } for (i = 0; i < PyArray_NDIM(ap1); i++) { PyTuple_SET_ITEM(shape1, i, PyLong_FromLongLong((npy_longlong)PyArray_DIMS(ap1)[i])); } shape2 = PyTuple_New(PyArray_NDIM(ap2)); for (i = 0; i < PyArray_NDIM(ap2); i++) { PyTuple_SET_ITEM(shape2, i, PyInt_FromLong((long) 1)); } if (shape2 == NULL) { Py_DECREF(shape1); goto fail; } newshape = PyNumber_Add(shape1, shape2); Py_DECREF(shape1); Py_DECREF(shape2); if (newshape == NULL) { goto fail; } ap_new = (PyArrayObject *)PyArray_Reshape(ap1, newshape); Py_DECREF(newshape); if (ap_new == NULL) { goto fail; } new_args = Py_BuildValue("(OO)", ap_new, ap2); Py_DECREF(ap1); Py_DECREF(ap2); Py_DECREF(ap_new); ret = ufunc_generic_call(ufunc, new_args, kwds); Py_DECREF(new_args); return ret; fail: Py_XDECREF(ap1); Py_XDECREF(ap2); Py_XDECREF(ap_new); return NULL; } static PyObject * ufunc_reduce(PyUFuncObject *ufunc, PyObject *args, PyObject *kwds) { return PyUFunc_GenericReduction(ufunc, args, kwds, UFUNC_REDUCE); } static PyObject * ufunc_accumulate(PyUFuncObject *ufunc, PyObject *args, PyObject *kwds) { return PyUFunc_GenericReduction(ufunc, args, kwds, UFUNC_ACCUMULATE); } static PyObject * ufunc_reduceat(PyUFuncObject *ufunc, PyObject *args, PyObject *kwds) { return PyUFunc_GenericReduction(ufunc, args, kwds, UFUNC_REDUCEAT); } /* * Call ufunc only on selected array items and store result in first operand. * For add ufunc, method call is equivalent to op1[idx] += op2 with no * buffering of the first operand. * Arguments: * op1 - First operand to ufunc * idx - Indices that are applied to first operand. Equivalent to op1[idx]. * op2 - Second operand to ufunc (if needed). Must be able to broadcast * over first operand. */ static PyObject * ufunc_at(PyUFuncObject *ufunc, PyObject *args) { PyObject *op1 = NULL; PyObject *idx = NULL; PyObject *op2 = NULL; PyArrayObject *op1_array = NULL; PyArrayObject *op2_array = NULL; PyArrayMapIterObject *iter = NULL; PyArrayIterObject *iter2 = NULL; PyArray_Descr *dtypes[3] = {NULL, NULL, NULL}; PyArrayObject *operands[3] = {NULL, NULL, NULL}; PyArrayObject *array_operands[3] = {NULL, NULL, NULL}; npy_intp dims[1] = {1}; int needs_api; PyUFuncGenericFunction innerloop; void *innerloopdata; npy_intp count[1], stride[1]; int i; int nop; NpyIter *iter_buffer; NpyIter_IterNextFunc *iternext; npy_uint32 op_flags[NPY_MAXARGS]; int buffersize; int errormask = 0; PyObject *errobj = NULL; char * err_msg = NULL; NPY_BEGIN_THREADS_DEF; if (ufunc->nin > 2) { PyErr_SetString(PyExc_ValueError, "Only unary and binary ufuncs supported at this time"); return NULL; } if (!PyArg_ParseTuple(args, "OO|O", &op1, &idx, &op2)) { return NULL; } if (ufunc->nin == 2 && op2 == NULL) { PyErr_SetString(PyExc_ValueError, "second operand needed for ufunc"); return NULL; } if (!PyArray_Check(op1)) { PyErr_SetString(PyExc_TypeError, "first operand must be array"); return NULL; } op1_array = op1; iter = PyArray_MapIterArray(op1_array, idx); if (iter == NULL) { goto fail; } /* Create second operand from number array if needed. */ if (op2 != NULL) { op2_array = (PyArrayObject *)PyArray_FromAny(op2, NULL, 0, 0, 0, NULL); if (op2_array == NULL) { goto fail; } /* * May need to swap axes so that second operand is * iterated over correctly */ if ((iter->subspace != NULL) && (iter->consec)) { PyArray_MapIterSwapAxes(iter, &op2_array, 0); if (op2_array == NULL) { goto fail; } } /* * Create array iter object for second operand that * "matches" the map iter object for the first operand. * Then we can just iterate over the first and second * operands at the same time and not have to worry about * picking the correct elements from each operand to apply * the ufunc to. */ if ((iter2 = (PyArrayIterObject *)\ PyArray_BroadcastToShape((PyObject *)op2_array, iter->dimensions, iter->nd))==NULL) { goto fail; } } /* * Create dtypes array for either one or two input operands. * The output operand is set to the first input operand */ dtypes[0] = PyArray_DESCR(op1_array); operands[0] = op1_array; if (op2_array != NULL) { dtypes[1] = PyArray_DESCR(op2_array); dtypes[2] = dtypes[0]; operands[1] = op2_array; operands[2] = op1_array; nop = 3; } else { dtypes[1] = dtypes[0]; dtypes[2] = NULL; operands[1] = op1_array; operands[2] = NULL; nop = 2; } if (ufunc->type_resolver(ufunc, NPY_UNSAFE_CASTING, operands, NULL, dtypes) < 0) { goto fail; } if (ufunc->legacy_inner_loop_selector(ufunc, dtypes, &innerloop, &innerloopdata, &needs_api) < 0) { goto fail; } count[0] = 1; stride[0] = 1; Py_INCREF(PyArray_DESCR(op1_array)); array_operands[0] = PyArray_NewFromDescr(&PyArray_Type, PyArray_DESCR(op1_array), 1, dims, NULL, iter->dataptr, NPY_ARRAY_WRITEABLE, NULL); if (iter2 != NULL) { Py_INCREF(PyArray_DESCR(op2_array)); array_operands[1] = PyArray_NewFromDescr(&PyArray_Type, PyArray_DESCR(op2_array), 1, dims, NULL, PyArray_ITER_DATA(iter2), NPY_ARRAY_WRITEABLE, NULL); Py_INCREF(PyArray_DESCR(op1_array)); array_operands[2] = PyArray_NewFromDescr(&PyArray_Type, PyArray_DESCR(op1_array), 1, dims, NULL, iter->dataptr, NPY_ARRAY_WRITEABLE, NULL); } else { Py_INCREF(PyArray_DESCR(op1_array)); array_operands[1] = PyArray_NewFromDescr(&PyArray_Type, PyArray_DESCR(op1_array), 1, dims, NULL, iter->dataptr, NPY_ARRAY_WRITEABLE, NULL); array_operands[2] = NULL; } /* Set up the flags */ op_flags[0] = NPY_ITER_READONLY| NPY_ITER_ALIGNED; if (iter2 != NULL) { op_flags[1] = NPY_ITER_READONLY| NPY_ITER_ALIGNED; op_flags[2] = NPY_ITER_WRITEONLY| NPY_ITER_ALIGNED| NPY_ITER_ALLOCATE| NPY_ITER_NO_BROADCAST| NPY_ITER_NO_SUBTYPE; } else { op_flags[1] = NPY_ITER_WRITEONLY| NPY_ITER_ALIGNED| NPY_ITER_ALLOCATE| NPY_ITER_NO_BROADCAST| NPY_ITER_NO_SUBTYPE; } PyUFunc_GetPyValues(ufunc->name, &buffersize, &errormask, &errobj); /* * Create NpyIter object to "iterate" over single element of each input * operand. This is an easy way to reuse the NpyIter logic for dealing * with certain cases like casting operands to correct dtype. On each * iteration over the MapIterArray object created above, we'll take the * current data pointers from that and reset this NpyIter object using * those data pointers, and then trigger a buffer copy. The buffer data * pointers from the NpyIter object will then be passed to the inner loop * function. */ iter_buffer = NpyIter_AdvancedNew(nop, array_operands, NPY_ITER_EXTERNAL_LOOP| NPY_ITER_REFS_OK| NPY_ITER_ZEROSIZE_OK| NPY_ITER_BUFFERED| NPY_ITER_GROWINNER| NPY_ITER_DELAY_BUFALLOC, NPY_KEEPORDER, NPY_UNSAFE_CASTING, op_flags, dtypes, -1, NULL, NULL, buffersize); if (iter_buffer == NULL) { goto fail; } needs_api = needs_api | NpyIter_IterationNeedsAPI(iter_buffer); iternext = NpyIter_GetIterNext(iter_buffer, NULL); if (iternext == NULL) { NpyIter_Deallocate(iter_buffer); goto fail; } if (!needs_api) { NPY_BEGIN_THREADS; } /* * Iterate over first and second operands and call ufunc * for each pair of inputs */ i = iter->size; while (i > 0) { char *dataptr[3]; char **buffer_dataptr; /* * Set up data pointers for either one or two input operands. * The output data pointer points to the first operand data. */ dataptr[0] = iter->dataptr; if (iter2 != NULL) { dataptr[1] = PyArray_ITER_DATA(iter2); dataptr[2] = iter->dataptr; } else { dataptr[1] = iter->dataptr; dataptr[2] = NULL; } /* Reset NpyIter data pointers which will trigger a buffer copy */ NpyIter_ResetBasePointers(iter_buffer, dataptr, &err_msg); if (err_msg) { break; } buffer_dataptr = NpyIter_GetDataPtrArray(iter_buffer); innerloop(buffer_dataptr, count, stride, innerloopdata); if (needs_api && PyErr_Occurred()) { break; } /* * Call to iternext triggers copy from buffer back to output array * after innerloop puts result in buffer. */ iternext(iter_buffer); PyArray_MapIterNext(iter); if (iter2 != NULL) { PyArray_ITER_NEXT(iter2); } i--; } if (!needs_api) { NPY_END_THREADS; } if (err_msg) { PyErr_SetString(PyExc_ValueError, err_msg); } NpyIter_Deallocate(iter_buffer); Py_XDECREF(op2_array); Py_XDECREF(iter); Py_XDECREF(iter2); Py_XDECREF(array_operands[0]); Py_XDECREF(array_operands[1]); Py_XDECREF(array_operands[2]); Py_XDECREF(errobj); if (needs_api && PyErr_Occurred()) { return NULL; } else { Py_RETURN_NONE; } fail: Py_XDECREF(op2_array); Py_XDECREF(iter); Py_XDECREF(iter2); Py_XDECREF(array_operands[0]); Py_XDECREF(array_operands[1]); Py_XDECREF(array_operands[2]); Py_XDECREF(errobj); return NULL; } static struct PyMethodDef ufunc_methods[] = { {"reduce", (PyCFunction)ufunc_reduce, METH_VARARGS | METH_KEYWORDS, NULL }, {"accumulate", (PyCFunction)ufunc_accumulate, METH_VARARGS | METH_KEYWORDS, NULL }, {"reduceat", (PyCFunction)ufunc_reduceat, METH_VARARGS | METH_KEYWORDS, NULL }, {"outer", (PyCFunction)ufunc_outer, METH_VARARGS | METH_KEYWORDS, NULL}, {"at", (PyCFunction)ufunc_at, METH_VARARGS, NULL}, {NULL, NULL, 0, NULL} /* sentinel */ }; /****************************************************************************** *** UFUNC GETSET *** *****************************************************************************/ /* construct the string y1,y2,...,yn */ static PyObject * _makeargs(int num, char *ltr, int null_if_none) { PyObject *str; int i; switch (num) { case 0: if (null_if_none) { return NULL; } return PyString_FromString(""); case 1: return PyString_FromString(ltr); } str = PyString_FromFormat("%s1, %s2", ltr, ltr); for (i = 3; i <= num; ++i) { PyString_ConcatAndDel(&str, PyString_FromFormat(", %s%d", ltr, i)); } return str; } static char _typecharfromnum(int num) { PyArray_Descr *descr; char ret; descr = PyArray_DescrFromType(num); ret = descr->type; Py_DECREF(descr); return ret; } static PyObject * ufunc_get_doc(PyUFuncObject *ufunc) { /* * Put docstring first or FindMethod finds it... could so some * introspection on name and nin + nout to automate the first part * of it the doc string shouldn't need the calling convention * construct name(x1, x2, ...,[ out1, out2, ...]) __doc__ */ PyObject *outargs, *inargs, *doc; outargs = _makeargs(ufunc->nout, "out", 1); inargs = _makeargs(ufunc->nin, "x", 0); if (ufunc->doc == NULL) { if (outargs == NULL) { doc = PyUString_FromFormat("%s(%s)\n\n", ufunc->name, PyString_AS_STRING(inargs)); } else { doc = PyUString_FromFormat("%s(%s[, %s])\n\n", ufunc->name, PyString_AS_STRING(inargs), PyString_AS_STRING(outargs)); Py_DECREF(outargs); } } else { if (outargs == NULL) { doc = PyUString_FromFormat("%s(%s)\n\n%s", ufunc->name, PyString_AS_STRING(inargs), ufunc->doc); } else { doc = PyUString_FromFormat("%s(%s[, %s])\n\n%s", ufunc->name, PyString_AS_STRING(inargs), PyString_AS_STRING(outargs), ufunc->doc); Py_DECREF(outargs); } } Py_DECREF(inargs); return doc; } static PyObject * ufunc_get_nin(PyUFuncObject *ufunc) { return PyInt_FromLong(ufunc->nin); } static PyObject * ufunc_get_nout(PyUFuncObject *ufunc) { return PyInt_FromLong(ufunc->nout); } static PyObject * ufunc_get_nargs(PyUFuncObject *ufunc) { return PyInt_FromLong(ufunc->nargs); } static PyObject * ufunc_get_ntypes(PyUFuncObject *ufunc) { return PyInt_FromLong(ufunc->ntypes); } static PyObject * ufunc_get_types(PyUFuncObject *ufunc) { /* return a list with types grouped input->output */ PyObject *list; PyObject *str; int k, j, n, nt = ufunc->ntypes; int ni = ufunc->nin; int no = ufunc->nout; char *t; list = PyList_New(nt); if (list == NULL) { return NULL; } t = PyArray_malloc(no+ni+2); n = 0; for (k = 0; k < nt; k++) { for (j = 0; jtypes[n]); n++; } t[ni] = '-'; t[ni+1] = '>'; for (j = 0; j < no; j++) { t[ni + 2 + j] = _typecharfromnum(ufunc->types[n]); n++; } str = PyUString_FromStringAndSize(t, no + ni + 2); PyList_SET_ITEM(list, k, str); } PyArray_free(t); return list; } static PyObject * ufunc_get_name(PyUFuncObject *ufunc) { return PyUString_FromString(ufunc->name); } static PyObject * ufunc_get_identity(PyUFuncObject *ufunc) { switch(ufunc->identity) { case PyUFunc_One: return PyInt_FromLong(1); case PyUFunc_Zero: return PyInt_FromLong(0); } return Py_None; } static PyObject * ufunc_get_signature(PyUFuncObject *ufunc) { if (!ufunc->core_enabled) { Py_RETURN_NONE; } return PyUString_FromString(ufunc->core_signature); } #undef _typecharfromnum /* * Docstring is now set from python * static char *Ufunctype__doc__ = NULL; */ static PyGetSetDef ufunc_getset[] = { {"__doc__", (getter)ufunc_get_doc, NULL, NULL, NULL}, {"nin", (getter)ufunc_get_nin, NULL, NULL, NULL}, {"nout", (getter)ufunc_get_nout, NULL, NULL, NULL}, {"nargs", (getter)ufunc_get_nargs, NULL, NULL, NULL}, {"ntypes", (getter)ufunc_get_ntypes, NULL, NULL, NULL}, {"types", (getter)ufunc_get_types, NULL, NULL, NULL}, {"__name__", (getter)ufunc_get_name, NULL, NULL, NULL}, {"identity", (getter)ufunc_get_identity, NULL, NULL, NULL}, {"signature", (getter)ufunc_get_signature, NULL, NULL, NULL}, {NULL, NULL, NULL, NULL, NULL}, /* Sentinel */ }; /****************************************************************************** *** UFUNC TYPE OBJECT *** *****************************************************************************/ NPY_NO_EXPORT PyTypeObject PyUFunc_Type = { #if defined(NPY_PY3K) PyVarObject_HEAD_INIT(NULL, 0) #else PyObject_HEAD_INIT(NULL) 0, /* ob_size */ #endif "numpy.ufunc", /* tp_name */ sizeof(PyUFuncObject), /* tp_basicsize */ 0, /* tp_itemsize */ /* methods */ (destructor)ufunc_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ #if defined(NPY_PY3K) 0, /* tp_reserved */ #else 0, /* tp_compare */ #endif (reprfunc)ufunc_repr, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ (ternaryfunc)ufunc_generic_call, /* tp_call */ (reprfunc)ufunc_repr, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT, /* tp_flags */ 0, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ ufunc_methods, /* tp_methods */ 0, /* tp_members */ ufunc_getset, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ 0, /* 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 */ 0, /* tp_version_tag */ }; /* End of code for ufunc objects */ numpy-1.8.2/numpy/core/src/umath/loops.h0000664000175100017510000023750712370216243021354 0ustar vagrantvagrant00000000000000 /* ***************************************************************************** ** 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 * $ 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 numpy-1.8.2/numpy/core/src/umath/funcs.inc.src0000664000175100017510000003716112370216242022437 0ustar vagrantvagrant00000000000000/* -*- c -*- */ /* * This file is for the definitions of the non-c99 functions used in ufuncs. * All the complex ufuncs are defined here along with a smattering of real and * object functions. */ #define NPY_NO_DEPRECATED_API NPY_API_VERSION #include "npy_pycompat.h" /* ***************************************************************************** ** PYTHON OBJECT FUNCTIONS ** ***************************************************************************** */ static PyObject * Py_square(PyObject *o) { return PyNumber_Multiply(o, o); } static PyObject * Py_get_one(PyObject *NPY_UNUSED(o)) { return PyInt_FromLong(1); } static PyObject * Py_reciprocal(PyObject *o) { PyObject *one = PyInt_FromLong(1); PyObject *result; if (!one) { return NULL; } #if defined(NPY_PY3K) result = PyNumber_TrueDivide(one, o); #else result = PyNumber_Divide(one, o); #endif Py_DECREF(one); return result; } /* * Define numpy version of PyNumber_Power as binary function. */ static PyObject * npy_ObjectPower(PyObject *x, PyObject *y) { return PyNumber_Power(x, y, Py_None); } #if defined(NPY_PY3K) /**begin repeat * #Kind = Max, Min# * #OP = Py_GE, Py_LE# */ static PyObject * npy_Object@Kind@(PyObject *i1, PyObject *i2) { PyObject *result; int cmp; cmp = PyObject_RichCompareBool(i1, i2, @OP@); if (cmp < 0) { return NULL; } if (cmp == 1) { result = i1; } else { result = i2; } Py_INCREF(result); return result; } /**end repeat**/ #else /**begin repeat * #Kind = Max, Min# * #OP = >=, <=# */ static PyObject * npy_Object@Kind@(PyObject *i1, PyObject *i2) { PyObject *result; int cmp; if (PyObject_Cmp(i1, i2, &cmp) < 0) { return NULL; } if (cmp @OP@ 0) { result = i1; } else { result = i2; } Py_INCREF(result); return result; } /**end repeat**/ #endif /* Emulates Python's 'a or b' behavior */ static PyObject * npy_ObjectLogicalOr(PyObject *i1, PyObject *i2) { if (i1 == NULL) { Py_XINCREF(i2); return i2; } else if (i2 == NULL) { Py_INCREF(i2); return i1; } else { int retcode = PyObject_IsTrue(i1); if (retcode == -1) { return NULL; } else if (retcode) { Py_INCREF(i1); return i1; } else { Py_INCREF(i2); return i2; } } } /* Emulates Python's 'a and b' behavior */ static PyObject * npy_ObjectLogicalAnd(PyObject *i1, PyObject *i2) { if (i1 == NULL) { return NULL; } else if (i2 == NULL) { return NULL; } else { int retcode = PyObject_IsTrue(i1); if (retcode == -1) { return NULL; } else if (!retcode) { Py_INCREF(i1); return i1; } else { Py_INCREF(i2); return i2; } } } /* Emulates Python's 'not b' behavior */ static PyObject * npy_ObjectLogicalNot(PyObject *i1) { if (i1 == NULL) { return NULL; } else { int retcode = PyObject_Not(i1); if (retcode == -1) { return NULL; } else if (retcode) { Py_INCREF(Py_True); return Py_True; } else { Py_INCREF(Py_False); return Py_False; } } } /* ***************************************************************************** ** COMPLEX FUNCTIONS ** ***************************************************************************** */ /* * Don't pass structures between functions (only pointers) because how * structures are passed is compiler dependent and could cause segfaults if * umath_ufunc_object.inc is compiled with a different compiler than an * extension that makes use of the UFUNC API */ /**begin repeat * * #ctype = npy_cfloat, npy_cdouble, npy_clongdouble# * #ftype = npy_float, npy_double, npy_longdouble# * #c = f, ,l# * #C = F, ,L# * #precision = 1,2,4# */ /* * Perform the operation result := 1 + coef * x * result, * with real coefficient `coef`. */ #define SERIES_HORNER_TERM@c@(result, x, coef) \ do { \ nc_prod@c@((result), (x), (result)); \ (result)->real *= (coef); \ (result)->imag *= (coef); \ nc_sum@c@((result), &nc_1@c@, (result)); \ } while(0) /* constants */ static @ctype@ nc_1@c@ = {1., 0.}; static @ctype@ nc_half@c@ = {0.5, 0.}; static @ctype@ nc_i@c@ = {0., 1.}; static @ctype@ nc_i2@c@ = {0., 0.5}; /* * static @ctype@ nc_mi@c@ = {0.0@c@, -1.0@c@}; * static @ctype@ nc_pi2@c@ = {NPY_PI_2@c@., 0.0@c@}; */ static void nc_sum@c@(@ctype@ *a, @ctype@ *b, @ctype@ *r) { r->real = a->real + b->real; r->imag = a->imag + b->imag; return; } static void nc_diff@c@(@ctype@ *a, @ctype@ *b, @ctype@ *r) { r->real = a->real - b->real; r->imag = a->imag - b->imag; return; } static void nc_neg@c@(@ctype@ *a, @ctype@ *r) { r->real = -a->real; r->imag = -a->imag; return; } static void nc_prod@c@(@ctype@ *a, @ctype@ *b, @ctype@ *r) { @ftype@ ar=a->real, br=b->real, ai=a->imag, bi=b->imag; r->real = ar*br - ai*bi; r->imag = ar*bi + ai*br; return; } static void nc_quot@c@(@ctype@ *a, @ctype@ *b, @ctype@ *r) { @ftype@ ar=a->real, br=b->real, ai=a->imag, bi=b->imag; @ftype@ d = br*br + bi*bi; r->real = (ar*br + ai*bi)/d; r->imag = (ai*br - ar*bi)/d; return; } static void nc_sqrt@c@(@ctype@ *x, @ctype@ *r) { *r = npy_csqrt@c@(*x); return; } static void nc_rint@c@(@ctype@ *x, @ctype@ *r) { r->real = npy_rint@c@(x->real); r->imag = npy_rint@c@(x->imag); } static void nc_log@c@(@ctype@ *x, @ctype@ *r) { *r = npy_clog@c@(*x); return; } static void nc_log1p@c@(@ctype@ *x, @ctype@ *r) { @ftype@ l = npy_hypot@c@(x->real + 1,x->imag); r->imag = npy_atan2@c@(x->imag, x->real + 1); r->real = npy_log@c@(l); return; } static void nc_exp@c@(@ctype@ *x, @ctype@ *r) { *r = npy_cexp@c@(*x); return; } static void nc_exp2@c@(@ctype@ *x, @ctype@ *r) { @ctype@ a; a.real = x->real*NPY_LOGE2@c@; a.imag = x->imag*NPY_LOGE2@c@; nc_exp@c@(&a, r); return; } static void nc_expm1@c@(@ctype@ *x, @ctype@ *r) { @ftype@ a = npy_exp@c@(x->real); r->real = a*npy_cos@c@(x->imag) - 1.0@c@; r->imag = a*npy_sin@c@(x->imag); return; } static void nc_pow@c@(@ctype@ *a, @ctype@ *b, @ctype@ *r) { npy_intp n; @ftype@ ar = npy_creal@c@(*a); @ftype@ br = npy_creal@c@(*b); @ftype@ ai = npy_cimag@c@(*a); @ftype@ bi = npy_cimag@c@(*b); if (br == 0. && bi == 0.) { *r = npy_cpack@c@(1., 0.); return; } if (ar == 0. && ai == 0.) { if (br > 0 && bi == 0) { *r = npy_cpack@c@(0., 0.); } else { volatile @ftype@ tmp = NPY_INFINITY; /* NB: there are four complex zeros; c0 = (+-0, +-0), so that unlike * for reals, c0**p, with `p` negative is in general * ill-defined. * * c0**z with z complex is also ill-defined. */ *r = npy_cpack@c@(NPY_NAN, NPY_NAN); /* Raise invalid */ tmp -= NPY_INFINITY; ar = tmp; } return; } if (bi == 0 && (n=(npy_intp)br) == br) { if (n == 1) { /* unroll: handle inf better */ *r = npy_cpack@c@(ar, ai); return; } else if (n == 2) { /* unroll: handle inf better */ nc_prod@c@(a, a, r); return; } else if (n == 3) { /* unroll: handle inf better */ nc_prod@c@(a, a, r); nc_prod@c@(a, r, r); return; } else if (n > -100 && n < 100) { @ctype@ p, aa; npy_intp mask = 1; if (n < 0) n = -n; aa = nc_1@c@; p = npy_cpack@c@(ar, ai); while (1) { if (n & mask) nc_prod@c@(&aa,&p,&aa); mask <<= 1; if (n < mask || mask <= 0) break; nc_prod@c@(&p,&p,&p); } *r = npy_cpack@c@(npy_creal@c@(aa), npy_cimag@c@(aa)); if (br < 0) nc_quot@c@(&nc_1@c@, r, r); return; } } *r = npy_cpow@c@(*a, *b); return; } static void nc_prodi@c@(@ctype@ *x, @ctype@ *r) { @ftype@ xr = x->real; r->real = -x->imag; r->imag = xr; return; } static void nc_acos@c@(@ctype@ *x, @ctype@ *r) { /* * return nc_neg(nc_prodi(nc_log(nc_sum(x,nc_prod(nc_i, * nc_sqrt(nc_diff(nc_1,nc_prod(x,x)))))))); */ nc_prod@c@(x,x,r); nc_diff@c@(&nc_1@c@, r, r); nc_sqrt@c@(r, r); nc_prodi@c@(r, r); nc_sum@c@(x, r, r); nc_log@c@(r, r); nc_prodi@c@(r, r); nc_neg@c@(r, r); return; } static void nc_acosh@c@(@ctype@ *x, @ctype@ *r) { /* * return nc_log(nc_sum(x, * nc_prod(nc_sqrt(nc_sum(x,nc_1)), nc_sqrt(nc_diff(x,nc_1))))); */ @ctype@ t; nc_sum@c@(x, &nc_1@c@, &t); nc_sqrt@c@(&t, &t); nc_diff@c@(x, &nc_1@c@, r); nc_sqrt@c@(r, r); nc_prod@c@(&t, r, r); nc_sum@c@(x, r, r); nc_log@c@(r, r); return; } static void nc_asin@c@(@ctype@ *x, @ctype@ *r) { /* * return nc_neg(nc_prodi(nc_log(nc_sum(nc_prod(nc_i,x), * nc_sqrt(nc_diff(nc_1,nc_prod(x,x))))))); */ if (fabs(x->real) > 1e-3 || fabs(x->imag) > 1e-3) { @ctype@ a, *pa=&a; nc_prod@c@(x, x, r); nc_diff@c@(&nc_1@c@, r, r); nc_sqrt@c@(r, r); nc_prodi@c@(x, pa); nc_sum@c@(pa, r, r); nc_log@c@(r, r); nc_prodi@c@(r, r); nc_neg@c@(r, r); } else { /* * Small arguments: series expansion, to avoid loss of precision * asin(x) = x [1 + (1/6) x^2 [1 + (9/20) x^2 [1 + ...]]] * * |x| < 1e-3 => |rel. error| < 1e-18 (f), 1e-24, 1e-36 (l) */ @ctype@ x2; nc_prod@c@(x, x, &x2); *r = nc_1@c@; #if @precision@ >= 3 SERIES_HORNER_TERM@c@(r, &x2, 81.0@C@/110); SERIES_HORNER_TERM@c@(r, &x2, 49.0@C@/72); #endif #if @precision@ >= 2 SERIES_HORNER_TERM@c@(r, &x2, 25.0@C@/42); #endif SERIES_HORNER_TERM@c@(r, &x2, 9.0@C@/20); SERIES_HORNER_TERM@c@(r, &x2, 1.0@C@/6); nc_prod@c@(r, x, r); } return; } static void nc_asinh@c@(@ctype@ *x, @ctype@ *r) { /* * return nc_log(nc_sum(nc_sqrt(nc_sum(nc_1,nc_prod(x,x))),x)); */ if (fabs(x->real) > 1e-3 || fabs(x->imag) > 1e-3) { nc_prod@c@(x, x, r); nc_sum@c@(&nc_1@c@, r, r); nc_sqrt@c@(r, r); nc_sum@c@(r, x, r); nc_log@c@(r, r); } else { /* * Small arguments: series expansion, to avoid loss of precision * asinh(x) = x [1 - (1/6) x^2 [1 - (9/20) x^2 [1 - ...]]] * * |x| < 1e-3 => |rel. error| < 1e-18 (f), 1e-24, 1e-36 (l) */ @ctype@ x2; nc_prod@c@(x, x, &x2); *r = nc_1@c@; #if @precision@ >= 3 SERIES_HORNER_TERM@c@(r, &x2, -81.0@C@/110); SERIES_HORNER_TERM@c@(r, &x2, -49.0@C@/72); #endif #if @precision@ >= 2 SERIES_HORNER_TERM@c@(r, &x2, -25.0@C@/42); #endif SERIES_HORNER_TERM@c@(r, &x2, -9.0@C@/20); SERIES_HORNER_TERM@c@(r, &x2, -1.0@C@/6); nc_prod@c@(r, x, r); } return; } static void nc_atan@c@(@ctype@ *x, @ctype@ *r) { /* * return nc_prod(nc_i2,nc_log(nc_quot(nc_sum(nc_i,x),nc_diff(nc_i,x)))); */ if (fabs(x->real) > 1e-3 || fabs(x->imag) > 1e-3) { @ctype@ a, *pa=&a; nc_diff@c@(&nc_i@c@, x, pa); nc_sum@c@(&nc_i@c@, x, r); nc_quot@c@(r, pa, r); nc_log@c@(r,r); nc_prod@c@(&nc_i2@c@, r, r); } else { /* * Small arguments: series expansion, to avoid loss of precision * atan(x) = x [1 - (1/3) x^2 [1 - (3/5) x^2 [1 - ...]]] * * |x| < 1e-3 => |rel. error| < 1e-18 (f), 1e-24, 1e-36 (l) */ @ctype@ x2; nc_prod@c@(x, x, &x2); *r = nc_1@c@; #if @precision@ >= 3 SERIES_HORNER_TERM@c@(r, &x2, -9.0@C@/11); SERIES_HORNER_TERM@c@(r, &x2, -7.0@C@/9); #endif #if @precision@ >= 2 SERIES_HORNER_TERM@c@(r, &x2, -5.0@C@/7); #endif SERIES_HORNER_TERM@c@(r, &x2, -3.0@C@/5); SERIES_HORNER_TERM@c@(r, &x2, -1.0@C@/3); nc_prod@c@(r, x, r); } return; } static void nc_atanh@c@(@ctype@ *x, @ctype@ *r) { /* * return nc_prod(nc_half,nc_log(nc_quot(nc_sum(nc_1,x),nc_diff(nc_1,x)))); */ if (fabs(x->real) > 1e-3 || fabs(x->imag) > 1e-3) { @ctype@ a, *pa=&a; nc_diff@c@(&nc_1@c@, x, r); nc_sum@c@(&nc_1@c@, x, pa); nc_quot@c@(pa, r, r); nc_log@c@(r, r); nc_prod@c@(&nc_half@c@, r, r); } else { /* * Small arguments: series expansion, to avoid loss of precision * atan(x) = x [1 + (1/3) x^2 [1 + (3/5) x^2 [1 + ...]]] * * |x| < 1e-3 => |rel. error| < 1e-18 (f), 1e-24, 1e-36 (l) */ @ctype@ x2; nc_prod@c@(x, x, &x2); *r = nc_1@c@; #if @precision@ >= 3 SERIES_HORNER_TERM@c@(r, &x2, 9.0@C@/11); SERIES_HORNER_TERM@c@(r, &x2, 7.0@C@/9); #endif #if @precision@ >= 2 SERIES_HORNER_TERM@c@(r, &x2, 5.0@C@/7); #endif SERIES_HORNER_TERM@c@(r, &x2, 3.0@C@/5); SERIES_HORNER_TERM@c@(r, &x2, 1.0@C@/3); nc_prod@c@(r, x, r); } return; } static void nc_cos@c@(@ctype@ *x, @ctype@ *r) { @ftype@ xr=x->real, xi=x->imag; r->real = npy_cos@c@(xr)*npy_cosh@c@(xi); r->imag = -npy_sin@c@(xr)*npy_sinh@c@(xi); return; } static void nc_cosh@c@(@ctype@ *x, @ctype@ *r) { @ftype@ xr=x->real, xi=x->imag; r->real = npy_cos@c@(xi)*npy_cosh@c@(xr); r->imag = npy_sin@c@(xi)*npy_sinh@c@(xr); return; } static void nc_log10@c@(@ctype@ *x, @ctype@ *r) { nc_log@c@(x, r); r->real *= NPY_LOG10E@c@; r->imag *= NPY_LOG10E@c@; return; } static void nc_log2@c@(@ctype@ *x, @ctype@ *r) { nc_log@c@(x, r); r->real *= NPY_LOG2E@c@; r->imag *= NPY_LOG2E@c@; return; } static void nc_sin@c@(@ctype@ *x, @ctype@ *r) { @ftype@ xr=x->real, xi=x->imag; r->real = npy_sin@c@(xr)*npy_cosh@c@(xi); r->imag = npy_cos@c@(xr)*npy_sinh@c@(xi); return; } static void nc_sinh@c@(@ctype@ *x, @ctype@ *r) { @ftype@ xr=x->real, xi=x->imag; r->real = npy_cos@c@(xi)*npy_sinh@c@(xr); r->imag = npy_sin@c@(xi)*npy_cosh@c@(xr); return; } static void nc_tan@c@(@ctype@ *x, @ctype@ *r) { @ftype@ sr,cr,shi,chi; @ftype@ rs,is,rc,ic; @ftype@ d; @ftype@ xr=x->real, xi=x->imag; sr = npy_sin@c@(xr); cr = npy_cos@c@(xr); shi = npy_sinh@c@(xi); chi = npy_cosh@c@(xi); rs = sr*chi; is = cr*shi; rc = cr*chi; ic = -sr*shi; d = rc*rc + ic*ic; r->real = (rs*rc+is*ic)/d; r->imag = (is*rc-rs*ic)/d; return; } static void nc_tanh@c@(@ctype@ *x, @ctype@ *r) { @ftype@ si,ci,shr,chr; @ftype@ rs,is,rc,ic; @ftype@ d; @ftype@ xr=x->real, xi=x->imag; si = npy_sin@c@(xi); ci = npy_cos@c@(xi); shr = npy_sinh@c@(xr); chr = npy_cosh@c@(xr); rs = ci*shr; is = si*chr; rc = ci*chr; ic = si*shr; d = rc*rc + ic*ic; r->real = (rs*rc+is*ic)/d; r->imag = (is*rc-rs*ic)/d; return; } #undef SERIES_HORNER_TERM@c@ /**end repeat**/ numpy-1.8.2/numpy/core/src/umath/operand_flag_tests.c.src0000664000175100017510000000437512370216242024636 0ustar vagrantvagrant00000000000000#define NPY_NO_DEPRECATED_API NPY_API_VERSION #include #include #include #include #include #include "numpy/npy_3kcompat.h" static PyMethodDef TestMethods[] = { {NULL, NULL, 0, NULL} }; static void inplace_add(char **args, npy_intp *dimensions, npy_intp *steps, void *data) { npy_intp i; npy_intp n = dimensions[0]; char *in1 = args[0]; char *in2 = args[1]; npy_intp in1_step = steps[0]; npy_intp in2_step = steps[1]; for (i = 0; i < n; i++) { (*(long *)in1) = *(long*)in1 + *(long*)in2; in1 += in1_step; in2 += in2_step; } } /*This a pointer to the above function*/ PyUFuncGenericFunction funcs[1] = {&inplace_add}; /* These are the input and return dtypes of logit.*/ static char types[2] = {NPY_LONG, NPY_LONG}; static void *data[1] = {NULL}; #if defined(NPY_PY3K) static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, "operand_flag_tests", NULL, -1, TestMethods, NULL, NULL, NULL, NULL }; #define RETVAL m PyMODINIT_FUNC PyInit_operand_flag_tests(void) { #else #define RETVAL PyMODINIT_FUNC initoperand_flag_tests(void) { #endif PyObject *m = NULL; PyObject *ufunc; #if defined(NPY_PY3K) m = PyModule_Create(&moduledef); #else m = Py_InitModule("operand_flag_tests", TestMethods); #endif if (m == NULL) { goto fail; } import_array(); import_umath(); ufunc = PyUFunc_FromFuncAndData(funcs, data, types, 1, 2, 0, PyUFunc_None, "inplace_add", "inplace_add_docstring", 0); /* * Set flags to turn off buffering for first input operand, * so that result can be written back to input operand. */ ((PyUFuncObject*)ufunc)->op_flags[0] = NPY_ITER_READWRITE; ((PyUFuncObject*)ufunc)->iter_flags = NPY_ITER_REDUCE_OK; PyModule_AddObject(m, "inplace_add", (PyObject*)ufunc); return RETVAL; fail: if (!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError, "cannot load operand_flag_tests module."); } #if defined(NPY_PY3K) if (m) { Py_DECREF(m); m = NULL; } #endif return RETVAL; } numpy-1.8.2/numpy/core/src/umath/reduction.h0000664000175100017510000001465012370216242022203 0ustar vagrantvagrant00000000000000#ifndef _NPY_PRIVATE__REDUCTION_H_ #define _NPY_PRIVATE__REDUCTION_H_ /************************************************************ * Typedefs used by PyArray_ReduceWrapper, new in 1.7. ************************************************************/ /* * This is a function for assigning a reduction identity to the result, * before doing the reduction computation. The * value in 'data' is passed through from PyArray_ReduceWrapper. * * This function could, for example, simply be a call like * return PyArray_AssignZero(result, NULL, NULL); * * It should return -1 on failure, or 0 on success. */ typedef int (PyArray_AssignReduceIdentityFunc)(PyArrayObject *result, void *data); /* * This is a function for the reduce loop. * * The needs_api parameter indicates whether it's ok to release the GIL during * the loop, such as when the iternext() function never calls * a function which could raise a Python exception. * * Ths skip_first_count parameter indicates how many elements need to be * skipped based on NpyIter_IsFirstVisit checks. This can only be positive * when the 'assign_identity' parameter was NULL when calling * PyArray_ReduceWrapper. * * The loop gets two data pointers and two strides, and should * look roughly like this: * { * NPY_BEGIN_THREADS_DEF; * if (!needs_api) { * NPY_BEGIN_THREADS; * } * // This first-visit loop can be skipped if 'assign_identity' was non-NULL * if (skip_first_count > 0) { * do { * char *data0 = dataptr[0], *data1 = dataptr[1]; * npy_intp stride0 = strideptr[0], stride1 = strideptr[1]; * npy_intp count = *countptr; * * // Skip any first-visit elements * if (NpyIter_IsFirstVisit(iter, 0)) { * if (stride0 == 0) { * --count; * --skip_first_count; * data1 += stride1; * } * else { * skip_first_count -= count; * count = 0; * } * } * * while (count--) { * *(result_t *)data0 = my_reduce_op(*(result_t *)data0, * *(operand_t *)data1); * data0 += stride0; * data1 += stride1; * } * * // Jump to the faster loop when skipping is done * if (skip_first_count == 0) { * if (iternext(iter)) { * break; * } * else { * goto finish_loop; * } * } * } while (iternext(iter)); * } * do { * char *data0 = dataptr[0], *data1 = dataptr[1]; * npy_intp stride0 = strideptr[0], stride1 = strideptr[1]; * npy_intp count = *countptr; * * while (count--) { * *(result_t *)data0 = my_reduce_op(*(result_t *)data0, * *(operand_t *)data1); * data0 += stride0; * data1 += stride1; * } * } while (iternext(iter)); * finish_loop: * if (!needs_api) { * NPY_END_THREADS; * } * return (needs_api && PyErr_Occurred()) ? -1 : 0; * } * * If needs_api is True, this function should call PyErr_Occurred() * to check if an error occurred during processing, and return -1 for * error, 0 for success. */ typedef int (PyArray_ReduceLoopFunc)(NpyIter *iter, char **dataptr, npy_intp *strideptr, npy_intp *countptr, NpyIter_IterNextFunc *iternext, int needs_api, npy_intp skip_first_count, void *data); /* * This function executes all the standard NumPy reduction function * boilerplate code, just calling assign_identity and the appropriate * inner loop function where necessary. * * operand : The array to be reduced. * out : NULL, or the array into which to place the result. * wheremask : NOT YET SUPPORTED, but this parameter is placed here * so that support can be added in the future without breaking * API compatibility. Pass in NULL. * operand_dtype : The dtype the inner loop expects for the operand. * result_dtype : The dtype the inner loop expects for the result. * casting : The casting rule to apply to the operands. * axis_flags : Flags indicating the reduction axes of 'operand'. * reorderable : If True, the reduction being done is reorderable, which * means specifying multiple axes of reduction at once is ok, * and the reduction code may calculate the reduction in an * arbitrary order. The calculation may be reordered because * of cache behavior or multithreading requirements. * keepdims : If true, leaves the reduction dimensions in the result * with size one. * subok : If true, the result uses the subclass of operand, otherwise * it is always a base class ndarray. * assign_identity : If NULL, PyArray_InitializeReduceResult is used, otherwise * this function is called to initialize the result to * the reduction's unit. * loop : The loop which does the reduction. * data : Data which is passed to assign_identity and the inner loop. * buffersize : Buffer size for the iterator. For the default, pass in 0. * funcname : The name of the reduction function, for error messages. */ NPY_NO_EXPORT PyArrayObject * PyUFunc_ReduceWrapper(PyArrayObject *operand, PyArrayObject *out, PyArrayObject *wheremask, PyArray_Descr *operand_dtype, PyArray_Descr *result_dtype, NPY_CASTING casting, npy_bool *axis_flags, int reorderable, int keepdims, int subok, PyArray_AssignReduceIdentityFunc *assign_identity, PyArray_ReduceLoopFunc *loop, void *data, npy_intp buffersize, const char *funcname); #endif numpy-1.8.2/numpy/core/src/umath/ufunc_object.h0000664000175100017510000000037012370216243022650 0ustar vagrantvagrant00000000000000#ifndef _NPY_UMATH_UFUNC_OBJECT_H_ #define _NPY_UMATH_UFUNC_OBJECT_H_ NPY_NO_EXPORT PyObject * ufunc_geterr(PyObject *NPY_UNUSED(dummy), PyObject *args); NPY_NO_EXPORT PyObject * ufunc_seterr(PyObject *NPY_UNUSED(dummy), PyObject *args); #endif numpy-1.8.2/numpy/core/src/umath/ufunc_type_resolution.c0000664000175100017510000021254412370216243024651 0ustar vagrantvagrant00000000000000/* * This file implements type resolution for NumPy element-wise ufuncs. * This mechanism is still backwards-compatible with the pre-existing * legacy mechanism, so performs much slower than is necessary. * * Written by Mark Wiebe (mwwiebe@gmail.com) * Copyright (c) 2011 by Enthought, Inc. * * See LICENSE.txt for the license. */ #define _UMATHMODULE #define NPY_NO_DEPRECATED_API NPY_API_VERSION #include "Python.h" #include "npy_config.h" #ifdef ENABLE_SEPARATE_COMPILATION #define PY_ARRAY_UNIQUE_SYMBOL _npy_umathmodule_ARRAY_API #define NO_IMPORT_ARRAY #endif #include "npy_pycompat.h" #include "numpy/ufuncobject.h" #include "ufunc_type_resolution.h" static const char * npy_casting_to_string(NPY_CASTING casting) { switch (casting) { case NPY_NO_CASTING: return "'no'"; case NPY_EQUIV_CASTING: return "'equiv'"; case NPY_SAFE_CASTING: return "'safe'"; case NPY_SAME_KIND_CASTING: return "'same_kind'"; case NPY_UNSAFE_CASTING: return "'unsafe'"; default: return ""; } } /*UFUNC_API * * Validates that the input operands can be cast to * the input types, and the output types can be cast to * the output operands where provided. * * Returns 0 on success, -1 (with exception raised) on validation failure. */ NPY_NO_EXPORT int PyUFunc_ValidateCasting(PyUFuncObject *ufunc, NPY_CASTING casting, PyArrayObject **operands, PyArray_Descr **dtypes) { int i, nin = ufunc->nin, nop = nin + ufunc->nout; char *ufunc_name; ufunc_name = ufunc->name ? ufunc->name : ""; for (i = 0; i < nop; ++i) { if (i < nin) { if (!PyArray_CanCastArrayTo(operands[i], dtypes[i], casting)) { PyObject *errmsg; errmsg = PyUString_FromFormat("Cannot cast ufunc %s " "input from ", ufunc_name); PyUString_ConcatAndDel(&errmsg, PyObject_Repr((PyObject *)PyArray_DESCR(operands[i]))); PyUString_ConcatAndDel(&errmsg, PyUString_FromString(" to ")); PyUString_ConcatAndDel(&errmsg, PyObject_Repr((PyObject *)dtypes[i])); PyUString_ConcatAndDel(&errmsg, PyUString_FromFormat(" with casting rule %s", npy_casting_to_string(casting))); PyErr_SetObject(PyExc_TypeError, errmsg); Py_DECREF(errmsg); return -1; } } else if (operands[i] != NULL) { if (!PyArray_CanCastTypeTo(dtypes[i], PyArray_DESCR(operands[i]), casting)) { PyObject *errmsg; errmsg = PyUString_FromFormat("Cannot cast ufunc %s " "output from ", ufunc_name); PyUString_ConcatAndDel(&errmsg, PyObject_Repr((PyObject *)dtypes[i])); PyUString_ConcatAndDel(&errmsg, PyUString_FromString(" to ")); PyUString_ConcatAndDel(&errmsg, PyObject_Repr((PyObject *)PyArray_DESCR(operands[i]))); PyUString_ConcatAndDel(&errmsg, PyUString_FromFormat(" with casting rule %s", npy_casting_to_string(casting))); PyErr_SetObject(PyExc_TypeError, errmsg); Py_DECREF(errmsg); return -1; } } } return 0; } /* * Returns a new reference to type if it is already NBO, otherwise * returns a copy converted to NBO. */ static PyArray_Descr * ensure_dtype_nbo(PyArray_Descr *type) { if (PyArray_ISNBO(type->byteorder)) { Py_INCREF(type); return type; } else { return PyArray_DescrNewByteorder(type, NPY_NATIVE); } } /*UFUNC_API * * This function applies the default type resolution rules * for the provided ufunc. * * Returns 0 on success, -1 on error. */ NPY_NO_EXPORT int PyUFunc_DefaultTypeResolver(PyUFuncObject *ufunc, NPY_CASTING casting, PyArrayObject **operands, PyObject *type_tup, PyArray_Descr **out_dtypes) { int i, nop = ufunc->nin + ufunc->nout; int retval = 0, any_object = 0; NPY_CASTING input_casting; for (i = 0; i < nop; ++i) { if (operands[i] != NULL && PyTypeNum_ISOBJECT(PyArray_DESCR(operands[i])->type_num)) { any_object = 1; break; } } /* * Decide the casting rules for inputs and outputs. We want * NPY_SAFE_CASTING or stricter, so that the loop selection code * doesn't choose an integer loop for float inputs, or a float32 * loop for float64 inputs. */ input_casting = (casting > NPY_SAFE_CASTING) ? NPY_SAFE_CASTING : casting; if (type_tup == NULL) { /* Find the best ufunc inner loop, and fill in the dtypes */ retval = linear_search_type_resolver(ufunc, operands, input_casting, casting, any_object, out_dtypes); } else { /* Find the specified ufunc inner loop, and fill in the dtypes */ retval = type_tuple_type_resolver(ufunc, type_tup, operands, casting, any_object, out_dtypes); } return retval; } /* * This function applies special type resolution rules for the case * where all the functions have the pattern XX->bool, using * PyArray_ResultType instead of a linear search to get the best * loop. * * Returns 0 on success, -1 on error. */ NPY_NO_EXPORT int PyUFunc_SimpleBinaryComparisonTypeResolver(PyUFuncObject *ufunc, NPY_CASTING casting, PyArrayObject **operands, PyObject *type_tup, PyArray_Descr **out_dtypes) { int i, type_num1, type_num2; char *ufunc_name; ufunc_name = ufunc->name ? ufunc->name : ""; if (ufunc->nin != 2 || ufunc->nout != 1) { PyErr_Format(PyExc_RuntimeError, "ufunc %s is configured " "to use binary comparison type resolution but has " "the wrong number of inputs or outputs", ufunc_name); return -1; } /* * Use the default type resolution if there's a custom data type * or object arrays. */ type_num1 = PyArray_DESCR(operands[0])->type_num; type_num2 = PyArray_DESCR(operands[1])->type_num; if (type_num1 >= NPY_NTYPES || type_num2 >= NPY_NTYPES || type_num1 == NPY_OBJECT || type_num2 == NPY_OBJECT) { return PyUFunc_DefaultTypeResolver(ufunc, casting, operands, type_tup, out_dtypes); } if (type_tup == NULL) { /* Input types are the result type */ out_dtypes[0] = PyArray_ResultType(2, operands, 0, NULL); if (out_dtypes[0] == NULL) { return -1; } out_dtypes[1] = out_dtypes[0]; Py_INCREF(out_dtypes[1]); } else { PyObject *item; PyArray_Descr *dtype = NULL; /* * If the type tuple isn't a single-element tuple, let the * default type resolution handle this one. */ if (!PyTuple_Check(type_tup) || PyTuple_GET_SIZE(type_tup) != 1) { return PyUFunc_DefaultTypeResolver(ufunc, casting, operands, type_tup, out_dtypes); } item = PyTuple_GET_ITEM(type_tup, 0); if (item == Py_None) { PyErr_SetString(PyExc_ValueError, "require data type in the type tuple"); return -1; } else if (!PyArray_DescrConverter(item, &dtype)) { return -1; } out_dtypes[0] = ensure_dtype_nbo(dtype); if (out_dtypes[0] == NULL) { return -1; } out_dtypes[1] = out_dtypes[0]; Py_INCREF(out_dtypes[1]); } /* Output type is always boolean */ out_dtypes[2] = PyArray_DescrFromType(NPY_BOOL); if (out_dtypes[2] == NULL) { for (i = 0; i < 2; ++i) { Py_DECREF(out_dtypes[i]); out_dtypes[i] = NULL; } return -1; } /* Check against the casting rules */ if (PyUFunc_ValidateCasting(ufunc, casting, operands, out_dtypes) < 0) { for (i = 0; i < 3; ++i) { Py_DECREF(out_dtypes[i]); out_dtypes[i] = NULL; } return -1; } return 0; } /* * This function applies special type resolution rules for the case * where all the functions have the pattern X->X, copying * the input descr directly so that metadata is maintained. * * Note that a simpler linear search through the functions loop * is still done, but switching to a simple array lookup for * built-in types would be better at some point. * * Returns 0 on success, -1 on error. */ NPY_NO_EXPORT int PyUFunc_SimpleUnaryOperationTypeResolver(PyUFuncObject *ufunc, NPY_CASTING casting, PyArrayObject **operands, PyObject *type_tup, PyArray_Descr **out_dtypes) { int i, type_num1; char *ufunc_name; ufunc_name = ufunc->name ? ufunc->name : ""; if (ufunc->nin != 1 || ufunc->nout != 1) { PyErr_Format(PyExc_RuntimeError, "ufunc %s is configured " "to use unary operation type resolution but has " "the wrong number of inputs or outputs", ufunc_name); return -1; } /* * Use the default type resolution if there's a custom data type * or object arrays. */ type_num1 = PyArray_DESCR(operands[0])->type_num; if (type_num1 >= NPY_NTYPES || type_num1 == NPY_OBJECT) { return PyUFunc_DefaultTypeResolver(ufunc, casting, operands, type_tup, out_dtypes); } if (type_tup == NULL) { /* Input types are the result type */ out_dtypes[0] = ensure_dtype_nbo(PyArray_DESCR(operands[0])); if (out_dtypes[0] == NULL) { return -1; } out_dtypes[1] = out_dtypes[0]; Py_INCREF(out_dtypes[1]); } else { PyObject *item; PyArray_Descr *dtype = NULL; /* * If the type tuple isn't a single-element tuple, let the * default type resolution handle this one. */ if (!PyTuple_Check(type_tup) || PyTuple_GET_SIZE(type_tup) != 1) { return PyUFunc_DefaultTypeResolver(ufunc, casting, operands, type_tup, out_dtypes); } item = PyTuple_GET_ITEM(type_tup, 0); if (item == Py_None) { PyErr_SetString(PyExc_ValueError, "require data type in the type tuple"); return -1; } else if (!PyArray_DescrConverter(item, &dtype)) { return -1; } out_dtypes[0] = ensure_dtype_nbo(dtype); if (out_dtypes[0] == NULL) { return -1; } out_dtypes[1] = out_dtypes[0]; Py_INCREF(out_dtypes[1]); } /* Check against the casting rules */ if (PyUFunc_ValidateCasting(ufunc, casting, operands, out_dtypes) < 0) { for (i = 0; i < 2; ++i) { Py_DECREF(out_dtypes[i]); out_dtypes[i] = NULL; } return -1; } return 0; } /* * The ones_like function shouldn't really be a ufunc, but while it * still is, this provides type resolution that always forces UNSAFE * casting. */ NPY_NO_EXPORT int PyUFunc_OnesLikeTypeResolver(PyUFuncObject *ufunc, NPY_CASTING NPY_UNUSED(casting), PyArrayObject **operands, PyObject *type_tup, PyArray_Descr **out_dtypes) { return PyUFunc_SimpleUnaryOperationTypeResolver(ufunc, NPY_UNSAFE_CASTING, operands, type_tup, out_dtypes); } /* * This function applies special type resolution rules for the case * where all the functions have the pattern XX->X, using * PyArray_ResultType instead of a linear search to get the best * loop. * * Note that a simpler linear search through the functions loop * is still done, but switching to a simple array lookup for * built-in types would be better at some point. * * Returns 0 on success, -1 on error. */ NPY_NO_EXPORT int PyUFunc_SimpleBinaryOperationTypeResolver(PyUFuncObject *ufunc, NPY_CASTING casting, PyArrayObject **operands, PyObject *type_tup, PyArray_Descr **out_dtypes) { int i, type_num1, type_num2; char *ufunc_name; ufunc_name = ufunc->name ? ufunc->name : ""; if (ufunc->nin != 2 || ufunc->nout != 1) { PyErr_Format(PyExc_RuntimeError, "ufunc %s is configured " "to use binary operation type resolution but has " "the wrong number of inputs or outputs", ufunc_name); return -1; } /* * Use the default type resolution if there's a custom data type * or object arrays. */ type_num1 = PyArray_DESCR(operands[0])->type_num; type_num2 = PyArray_DESCR(operands[1])->type_num; if (type_num1 >= NPY_NTYPES || type_num2 >= NPY_NTYPES || type_num1 == NPY_OBJECT || type_num2 == NPY_OBJECT) { return PyUFunc_DefaultTypeResolver(ufunc, casting, operands, type_tup, out_dtypes); } if (type_tup == NULL) { /* Input types are the result type */ out_dtypes[0] = PyArray_ResultType(2, operands, 0, NULL); if (out_dtypes[0] == NULL) { return -1; } out_dtypes[1] = out_dtypes[0]; Py_INCREF(out_dtypes[1]); out_dtypes[2] = out_dtypes[0]; Py_INCREF(out_dtypes[2]); } else { PyObject *item; PyArray_Descr *dtype = NULL; /* * If the type tuple isn't a single-element tuple, let the * default type resolution handle this one. */ if (!PyTuple_Check(type_tup) || PyTuple_GET_SIZE(type_tup) != 1) { return PyUFunc_DefaultTypeResolver(ufunc, casting, operands, type_tup, out_dtypes); } item = PyTuple_GET_ITEM(type_tup, 0); if (item == Py_None) { PyErr_SetString(PyExc_ValueError, "require data type in the type tuple"); return -1; } else if (!PyArray_DescrConverter(item, &dtype)) { return -1; } out_dtypes[0] = ensure_dtype_nbo(dtype); if (out_dtypes[0] == NULL) { return -1; } out_dtypes[1] = out_dtypes[0]; Py_INCREF(out_dtypes[1]); out_dtypes[2] = out_dtypes[0]; Py_INCREF(out_dtypes[2]); } /* Check against the casting rules */ if (PyUFunc_ValidateCasting(ufunc, casting, operands, out_dtypes) < 0) { for (i = 0; i < 3; ++i) { Py_DECREF(out_dtypes[i]); out_dtypes[i] = NULL; } return -1; } return 0; } /* * This function applies special type resolution rules for the absolute * ufunc. This ufunc converts complex -> float, so isn't covered * by the simple unary type resolution. * * Returns 0 on success, -1 on error. */ NPY_NO_EXPORT int PyUFunc_AbsoluteTypeResolver(PyUFuncObject *ufunc, NPY_CASTING casting, PyArrayObject **operands, PyObject *type_tup, PyArray_Descr **out_dtypes) { /* Use the default for complex types, to find the loop producing float */ if (PyTypeNum_ISCOMPLEX(PyArray_DESCR(operands[0])->type_num)) { return PyUFunc_DefaultTypeResolver(ufunc, casting, operands, type_tup, out_dtypes); } else { return PyUFunc_SimpleUnaryOperationTypeResolver(ufunc, casting, operands, type_tup, out_dtypes); } } /* * Creates a new NPY_TIMEDELTA dtype, copying the datetime metadata * from the given dtype. * * NOTE: This function is copied from datetime.c in multiarray, * because umath and multiarray are not linked together. */ static PyArray_Descr * timedelta_dtype_with_copied_meta(PyArray_Descr *dtype) { PyArray_Descr *ret; PyArray_DatetimeMetaData *dst, *src; PyArray_DatetimeDTypeMetaData *dst_dtmd, *src_dtmd; ret = PyArray_DescrNewFromType(NPY_TIMEDELTA); if (ret == NULL) { return NULL; } src_dtmd = ((PyArray_DatetimeDTypeMetaData *)dtype->c_metadata); dst_dtmd = ((PyArray_DatetimeDTypeMetaData *)ret->c_metadata); src = &(src_dtmd->meta); dst = &(dst_dtmd->meta); *dst = *src; return ret; } /* * This function applies the type resolution rules for addition. * In particular, there are a number of special cases with datetime: * m8[] + m8[] => m8[gcd(,)] + m8[gcd(,)] * m8[] + int => m8[] + m8[] * int + m8[] => m8[] + m8[] * M8[] + int => M8[] + m8[] * int + M8[] => m8[] + M8[] * M8[] + m8[] => M8[gcd(,)] + m8[gcd(,)] * m8[] + M8[] => m8[gcd(,)] + M8[gcd(,)] * TODO: Non-linear time unit cases require highly special-cased loops * M8[] + m8[Y|M|B] * m8[Y|M|B] + M8[] */ NPY_NO_EXPORT int PyUFunc_AdditionTypeResolver(PyUFuncObject *ufunc, NPY_CASTING casting, PyArrayObject **operands, PyObject *type_tup, PyArray_Descr **out_dtypes) { int type_num1, type_num2; int i; char *ufunc_name; ufunc_name = ufunc->name ? ufunc->name : ""; type_num1 = PyArray_DESCR(operands[0])->type_num; type_num2 = PyArray_DESCR(operands[1])->type_num; /* 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); } if (type_num1 == NPY_TIMEDELTA) { /* m8[] + m8[] => m8[gcd(,)] + m8[gcd(,)] */ if (type_num2 == NPY_TIMEDELTA) { out_dtypes[0] = PyArray_PromoteTypes(PyArray_DESCR(operands[0]), PyArray_DESCR(operands[1])); if (out_dtypes[0] == NULL) { return -1; } out_dtypes[1] = out_dtypes[0]; Py_INCREF(out_dtypes[1]); out_dtypes[2] = out_dtypes[0]; Py_INCREF(out_dtypes[2]); } /* m8[] + M8[] => m8[gcd(,)] + M8[gcd(,)] */ else if (type_num2 == NPY_DATETIME) { out_dtypes[1] = PyArray_PromoteTypes(PyArray_DESCR(operands[0]), PyArray_DESCR(operands[1])); if (out_dtypes[1] == NULL) { return -1; } /* Make a new NPY_TIMEDELTA, and copy the datetime's metadata */ out_dtypes[0] = timedelta_dtype_with_copied_meta(out_dtypes[1]); if (out_dtypes[0] == NULL) { Py_DECREF(out_dtypes[1]); out_dtypes[1] = NULL; return -1; } out_dtypes[2] = out_dtypes[1]; Py_INCREF(out_dtypes[2]); } /* m8[] + int => m8[] + m8[] */ else if (PyTypeNum_ISINTEGER(type_num2) || PyTypeNum_ISBOOL(type_num2)) { out_dtypes[0] = ensure_dtype_nbo(PyArray_DESCR(operands[0])); if (out_dtypes[0] == NULL) { return -1; } out_dtypes[1] = out_dtypes[0]; Py_INCREF(out_dtypes[1]); out_dtypes[2] = out_dtypes[0]; Py_INCREF(out_dtypes[2]); type_num2 = NPY_TIMEDELTA; } else { goto type_reso_error; } } else if (type_num1 == NPY_DATETIME) { /* M8[] + m8[] => M8[gcd(,)] + m8[gcd(,)] */ if (type_num2 == NPY_TIMEDELTA) { out_dtypes[0] = PyArray_PromoteTypes(PyArray_DESCR(operands[0]), PyArray_DESCR(operands[1])); if (out_dtypes[0] == NULL) { return -1; } /* Make a new NPY_TIMEDELTA, and copy the datetime's metadata */ out_dtypes[1] = timedelta_dtype_with_copied_meta(out_dtypes[0]); if (out_dtypes[1] == NULL) { Py_DECREF(out_dtypes[0]); out_dtypes[0] = NULL; return -1; } out_dtypes[2] = out_dtypes[0]; Py_INCREF(out_dtypes[2]); } /* M8[] + int => M8[] + m8[] */ else if (PyTypeNum_ISINTEGER(type_num2) || PyTypeNum_ISBOOL(type_num2)) { out_dtypes[0] = ensure_dtype_nbo(PyArray_DESCR(operands[0])); if (out_dtypes[0] == NULL) { return -1; } /* Make a new NPY_TIMEDELTA, and copy type1's metadata */ out_dtypes[1] = timedelta_dtype_with_copied_meta( PyArray_DESCR(operands[0])); if (out_dtypes[1] == NULL) { Py_DECREF(out_dtypes[0]); out_dtypes[0] = NULL; return -1; } out_dtypes[2] = out_dtypes[0]; Py_INCREF(out_dtypes[2]); type_num2 = NPY_TIMEDELTA; } else { goto type_reso_error; } } else if (PyTypeNum_ISINTEGER(type_num1) || PyTypeNum_ISBOOL(type_num1)) { /* int + m8[] => m8[] + m8[] */ if (type_num2 == NPY_TIMEDELTA) { out_dtypes[0] = ensure_dtype_nbo(PyArray_DESCR(operands[1])); if (out_dtypes[0] == NULL) { return -1; } out_dtypes[1] = out_dtypes[0]; Py_INCREF(out_dtypes[1]); out_dtypes[2] = out_dtypes[0]; Py_INCREF(out_dtypes[2]); type_num1 = NPY_TIMEDELTA; } else if (type_num2 == NPY_DATETIME) { /* Make a new NPY_TIMEDELTA, and copy type2's metadata */ out_dtypes[0] = timedelta_dtype_with_copied_meta( PyArray_DESCR(operands[1])); if (out_dtypes[0] == NULL) { return -1; } out_dtypes[1] = ensure_dtype_nbo(PyArray_DESCR(operands[1])); if (out_dtypes[1] == NULL) { Py_DECREF(out_dtypes[0]); out_dtypes[0] = NULL; return -1; } out_dtypes[2] = out_dtypes[1]; Py_INCREF(out_dtypes[2]); type_num1 = NPY_TIMEDELTA; } else { goto type_reso_error; } } else { goto type_reso_error; } /* Check against the casting rules */ if (PyUFunc_ValidateCasting(ufunc, casting, operands, out_dtypes) < 0) { for (i = 0; i < 3; ++i) { Py_DECREF(out_dtypes[i]); out_dtypes[i] = NULL; } return -1; } return 0; type_reso_error: { PyObject *errmsg; errmsg = PyUString_FromFormat("ufunc %s cannot use operands " "with types ", ufunc_name); PyUString_ConcatAndDel(&errmsg, PyObject_Repr((PyObject *)PyArray_DESCR(operands[0]))); PyUString_ConcatAndDel(&errmsg, PyUString_FromString(" and ")); PyUString_ConcatAndDel(&errmsg, PyObject_Repr((PyObject *)PyArray_DESCR(operands[1]))); PyErr_SetObject(PyExc_TypeError, errmsg); Py_DECREF(errmsg); return -1; } } /* * This function applies the type resolution rules for subtraction. * In particular, there are a number of special cases with datetime: * m8[] - m8[] => m8[gcd(,)] - m8[gcd(,)] * m8[] - int => m8[] - m8[] * int - m8[] => m8[] - m8[] * M8[] - int => M8[] - m8[] * M8[] - m8[] => M8[gcd(,)] - m8[gcd(,)] * TODO: Non-linear time unit cases require highly special-cased loops * M8[] - m8[Y|M|B] */ NPY_NO_EXPORT int PyUFunc_SubtractionTypeResolver(PyUFuncObject *ufunc, NPY_CASTING casting, PyArrayObject **operands, PyObject *type_tup, PyArray_Descr **out_dtypes) { int type_num1, type_num2; int i; char *ufunc_name; ufunc_name = ufunc->name ? ufunc->name : ""; type_num1 = PyArray_DESCR(operands[0])->type_num; type_num2 = PyArray_DESCR(operands[1])->type_num; /* 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); } if (type_num1 == NPY_TIMEDELTA) { /* m8[] - m8[] => m8[gcd(,)] - m8[gcd(,)] */ if (type_num2 == NPY_TIMEDELTA) { out_dtypes[0] = PyArray_PromoteTypes(PyArray_DESCR(operands[0]), PyArray_DESCR(operands[1])); if (out_dtypes[0] == NULL) { return -1; } out_dtypes[1] = out_dtypes[0]; Py_INCREF(out_dtypes[1]); out_dtypes[2] = out_dtypes[0]; Py_INCREF(out_dtypes[2]); } /* m8[] - int => m8[] - m8[] */ else if (PyTypeNum_ISINTEGER(type_num2) || PyTypeNum_ISBOOL(type_num2)) { out_dtypes[0] = ensure_dtype_nbo(PyArray_DESCR(operands[0])); if (out_dtypes[0] == NULL) { return -1; } out_dtypes[1] = out_dtypes[0]; Py_INCREF(out_dtypes[1]); out_dtypes[2] = out_dtypes[0]; Py_INCREF(out_dtypes[2]); type_num2 = NPY_TIMEDELTA; } else { goto type_reso_error; } } else if (type_num1 == NPY_DATETIME) { /* M8[] - m8[] => M8[gcd(,)] - m8[gcd(,)] */ if (type_num2 == NPY_TIMEDELTA) { out_dtypes[0] = PyArray_PromoteTypes(PyArray_DESCR(operands[0]), PyArray_DESCR(operands[1])); if (out_dtypes[0] == NULL) { return -1; } /* Make a new NPY_TIMEDELTA, and copy the datetime's metadata */ out_dtypes[1] = timedelta_dtype_with_copied_meta(out_dtypes[0]); if (out_dtypes[1] == NULL) { Py_DECREF(out_dtypes[0]); out_dtypes[0] = NULL; return -1; } out_dtypes[2] = out_dtypes[0]; Py_INCREF(out_dtypes[2]); } /* M8[] - int => M8[] - m8[] */ else if (PyTypeNum_ISINTEGER(type_num2) || PyTypeNum_ISBOOL(type_num2)) { out_dtypes[0] = ensure_dtype_nbo(PyArray_DESCR(operands[0])); if (out_dtypes[0] == NULL) { return -1; } /* Make a new NPY_TIMEDELTA, and copy type1's metadata */ out_dtypes[1] = timedelta_dtype_with_copied_meta( PyArray_DESCR(operands[0])); if (out_dtypes[1] == NULL) { Py_DECREF(out_dtypes[0]); out_dtypes[0] = NULL; return -1; } out_dtypes[2] = out_dtypes[0]; Py_INCREF(out_dtypes[2]); type_num2 = NPY_TIMEDELTA; } /* M8[] - M8[] => M8[gcd(,)] - M8[gcd(,)] */ else if (type_num2 == NPY_DATETIME) { out_dtypes[0] = PyArray_PromoteTypes(PyArray_DESCR(operands[0]), PyArray_DESCR(operands[1])); if (out_dtypes[0] == NULL) { return -1; } /* Make a new NPY_TIMEDELTA, and copy type1's metadata */ out_dtypes[2] = timedelta_dtype_with_copied_meta(out_dtypes[0]); if (out_dtypes[2] == NULL) { Py_DECREF(out_dtypes[0]); return -1; } out_dtypes[1] = out_dtypes[0]; Py_INCREF(out_dtypes[1]); } else { goto type_reso_error; } } else if (PyTypeNum_ISINTEGER(type_num1) || PyTypeNum_ISBOOL(type_num1)) { /* int - m8[] => m8[] - m8[] */ if (type_num2 == NPY_TIMEDELTA) { out_dtypes[0] = ensure_dtype_nbo(PyArray_DESCR(operands[1])); if (out_dtypes[0] == NULL) { return -1; } out_dtypes[1] = out_dtypes[0]; Py_INCREF(out_dtypes[1]); out_dtypes[2] = out_dtypes[0]; Py_INCREF(out_dtypes[2]); type_num1 = NPY_TIMEDELTA; } else { goto type_reso_error; } } else { goto type_reso_error; } /* Check against the casting rules */ if (PyUFunc_ValidateCasting(ufunc, casting, operands, out_dtypes) < 0) { for (i = 0; i < 3; ++i) { Py_DECREF(out_dtypes[i]); out_dtypes[i] = NULL; } return -1; } return 0; type_reso_error: { PyObject *errmsg; errmsg = PyUString_FromFormat("ufunc %s cannot use operands " "with types ", ufunc_name); PyUString_ConcatAndDel(&errmsg, PyObject_Repr((PyObject *)PyArray_DESCR(operands[0]))); PyUString_ConcatAndDel(&errmsg, PyUString_FromString(" and ")); PyUString_ConcatAndDel(&errmsg, PyObject_Repr((PyObject *)PyArray_DESCR(operands[1]))); PyErr_SetObject(PyExc_TypeError, errmsg); Py_DECREF(errmsg); return -1; } } /* * This function applies the type resolution rules for multiplication. * In particular, there are a number of special cases with datetime: * int## * m8[] => int64 * m8[] * m8[] * int## => m8[] * int64 * float## * m8[] => float64 * m8[] * m8[] * float## => m8[] * float64 */ NPY_NO_EXPORT int PyUFunc_MultiplicationTypeResolver(PyUFuncObject *ufunc, NPY_CASTING casting, PyArrayObject **operands, PyObject *type_tup, PyArray_Descr **out_dtypes) { int type_num1, type_num2; int i; char *ufunc_name; ufunc_name = ufunc->name ? ufunc->name : ""; type_num1 = PyArray_DESCR(operands[0])->type_num; type_num2 = PyArray_DESCR(operands[1])->type_num; /* 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); } if (type_num1 == NPY_TIMEDELTA) { /* m8[] * int## => m8[] * int64 */ if (PyTypeNum_ISINTEGER(type_num2) || PyTypeNum_ISBOOL(type_num2)) { out_dtypes[0] = ensure_dtype_nbo(PyArray_DESCR(operands[0])); if (out_dtypes[0] == NULL) { return -1; } out_dtypes[1] = PyArray_DescrNewFromType(NPY_LONGLONG); if (out_dtypes[1] == NULL) { Py_DECREF(out_dtypes[0]); out_dtypes[0] = NULL; return -1; } out_dtypes[2] = out_dtypes[0]; Py_INCREF(out_dtypes[2]); type_num2 = NPY_LONGLONG; } /* m8[] * float## => m8[] * float64 */ else if (PyTypeNum_ISFLOAT(type_num2)) { out_dtypes[0] = ensure_dtype_nbo(PyArray_DESCR(operands[0])); if (out_dtypes[0] == NULL) { return -1; } out_dtypes[1] = PyArray_DescrNewFromType(NPY_DOUBLE); if (out_dtypes[1] == NULL) { Py_DECREF(out_dtypes[0]); out_dtypes[0] = NULL; return -1; } out_dtypes[2] = out_dtypes[0]; Py_INCREF(out_dtypes[2]); type_num2 = NPY_DOUBLE; } else { goto type_reso_error; } } else if (PyTypeNum_ISINTEGER(type_num1) || PyTypeNum_ISBOOL(type_num1)) { /* int## * m8[] => int64 * m8[] */ if (type_num2 == NPY_TIMEDELTA) { out_dtypes[0] = PyArray_DescrNewFromType(NPY_LONGLONG); if (out_dtypes[0] == NULL) { return -1; } out_dtypes[1] = ensure_dtype_nbo(PyArray_DESCR(operands[1])); if (out_dtypes[1] == NULL) { Py_DECREF(out_dtypes[0]); out_dtypes[0] = NULL; return -1; } out_dtypes[2] = out_dtypes[1]; Py_INCREF(out_dtypes[2]); type_num1 = NPY_LONGLONG; } else { goto type_reso_error; } } else if (PyTypeNum_ISFLOAT(type_num1)) { /* float## * m8[] => float64 * m8[] */ if (type_num2 == NPY_TIMEDELTA) { out_dtypes[0] = PyArray_DescrNewFromType(NPY_DOUBLE); if (out_dtypes[0] == NULL) { return -1; } out_dtypes[1] = ensure_dtype_nbo(PyArray_DESCR(operands[1])); if (out_dtypes[1] == NULL) { Py_DECREF(out_dtypes[0]); out_dtypes[0] = NULL; return -1; } out_dtypes[2] = out_dtypes[1]; Py_INCREF(out_dtypes[2]); type_num1 = NPY_DOUBLE; } else { goto type_reso_error; } } else { goto type_reso_error; } /* Check against the casting rules */ if (PyUFunc_ValidateCasting(ufunc, casting, operands, out_dtypes) < 0) { for (i = 0; i < 3; ++i) { Py_DECREF(out_dtypes[i]); out_dtypes[i] = NULL; } return -1; } return 0; type_reso_error: { PyObject *errmsg; errmsg = PyUString_FromFormat("ufunc %s cannot use operands " "with types ", ufunc_name); PyUString_ConcatAndDel(&errmsg, PyObject_Repr((PyObject *)PyArray_DESCR(operands[0]))); PyUString_ConcatAndDel(&errmsg, PyUString_FromString(" and ")); PyUString_ConcatAndDel(&errmsg, PyObject_Repr((PyObject *)PyArray_DESCR(operands[1]))); PyErr_SetObject(PyExc_TypeError, errmsg); Py_DECREF(errmsg); return -1; } } /* * This function applies the type resolution rules for division. * In particular, there are a number of special cases with datetime: * m8[] / m8[] to m8[gcd(,)] / m8[gcd(,)] -> float64 * m8[] / int## to m8[] / int64 -> m8[] * m8[] / float## to m8[] / float64 -> m8[] */ NPY_NO_EXPORT int PyUFunc_DivisionTypeResolver(PyUFuncObject *ufunc, NPY_CASTING casting, PyArrayObject **operands, PyObject *type_tup, PyArray_Descr **out_dtypes) { int type_num1, type_num2; int i; char *ufunc_name; ufunc_name = ufunc->name ? ufunc->name : ""; type_num1 = PyArray_DESCR(operands[0])->type_num; type_num2 = PyArray_DESCR(operands[1])->type_num; /* Use the default when datetime and timedelta are not involved */ if (!PyTypeNum_ISDATETIME(type_num1) && !PyTypeNum_ISDATETIME(type_num2)) { return PyUFunc_DefaultTypeResolver(ufunc, casting, operands, type_tup, out_dtypes); } if (type_num1 == NPY_TIMEDELTA) { /* * m8[] / m8[] to * m8[gcd(,)] / m8[gcd(,)] -> float64 */ if (type_num2 == NPY_TIMEDELTA) { out_dtypes[0] = PyArray_PromoteTypes(PyArray_DESCR(operands[0]), PyArray_DESCR(operands[1])); if (out_dtypes[0] == NULL) { return -1; } out_dtypes[1] = out_dtypes[0]; Py_INCREF(out_dtypes[1]); out_dtypes[2] = PyArray_DescrFromType(NPY_DOUBLE); if (out_dtypes[2] == NULL) { Py_DECREF(out_dtypes[0]); out_dtypes[0] = NULL; Py_DECREF(out_dtypes[1]); out_dtypes[1] = NULL; return -1; } } /* m8[] / int## => m8[] / int64 */ else if (PyTypeNum_ISINTEGER(type_num2)) { out_dtypes[0] = ensure_dtype_nbo(PyArray_DESCR(operands[0])); if (out_dtypes[0] == NULL) { return -1; } out_dtypes[1] = PyArray_DescrFromType(NPY_LONGLONG); if (out_dtypes[1] == NULL) { Py_DECREF(out_dtypes[0]); out_dtypes[0] = NULL; return -1; } out_dtypes[2] = out_dtypes[0]; Py_INCREF(out_dtypes[2]); type_num2 = NPY_LONGLONG; } /* m8[] / float## => m8[] / float64 */ else if (PyTypeNum_ISFLOAT(type_num2)) { out_dtypes[0] = ensure_dtype_nbo(PyArray_DESCR(operands[0])); if (out_dtypes[0] == NULL) { return -1; } out_dtypes[1] = PyArray_DescrNewFromType(NPY_DOUBLE); if (out_dtypes[1] == NULL) { Py_DECREF(out_dtypes[0]); out_dtypes[0] = NULL; return -1; } out_dtypes[2] = out_dtypes[0]; Py_INCREF(out_dtypes[2]); type_num2 = NPY_DOUBLE; } else { goto type_reso_error; } } else { goto type_reso_error; } /* Check against the casting rules */ if (PyUFunc_ValidateCasting(ufunc, casting, operands, out_dtypes) < 0) { for (i = 0; i < 3; ++i) { Py_DECREF(out_dtypes[i]); out_dtypes[i] = NULL; } return -1; } return 0; type_reso_error: { PyObject *errmsg; errmsg = PyUString_FromFormat("ufunc %s cannot use operands " "with types ", ufunc_name); PyUString_ConcatAndDel(&errmsg, PyObject_Repr((PyObject *)PyArray_DESCR(operands[0]))); PyUString_ConcatAndDel(&errmsg, PyUString_FromString(" and ")); PyUString_ConcatAndDel(&errmsg, PyObject_Repr((PyObject *)PyArray_DESCR(operands[1]))); PyErr_SetObject(PyExc_TypeError, errmsg); Py_DECREF(errmsg); return -1; } } static int find_userloop(PyUFuncObject *ufunc, PyArray_Descr **dtypes, PyUFuncGenericFunction *out_innerloop, void **out_innerloopdata) { npy_intp i, nin = ufunc->nin, j, nargs = nin + ufunc->nout; PyUFunc_Loop1d *funcdata; /* Use this to try to avoid repeating the same userdef loop search */ int last_userdef = -1; for (i = 0; i < nargs; ++i) { int type_num; /* no more ufunc arguments to check */ if (dtypes[i] == NULL) { break; } type_num = dtypes[i]->type_num; if (type_num != last_userdef && (PyTypeNum_ISUSERDEF(type_num) || type_num == NPY_VOID)) { PyObject *key, *obj; last_userdef = type_num; key = PyInt_FromLong(type_num); if (key == NULL) { return -1; } obj = PyDict_GetItem(ufunc->userloops, key); Py_DECREF(key); if (obj == NULL) { continue; } funcdata = (PyUFunc_Loop1d *)NpyCapsule_AsVoidPtr(obj); while (funcdata != NULL) { int *types = funcdata->arg_types; for (j = 0; j < nargs; ++j) { if (types[j] != dtypes[j]->type_num) { break; } } /* It matched */ if (j == nargs) { *out_innerloop = funcdata->func; *out_innerloopdata = funcdata->data; return 1; } funcdata = funcdata->next; } } } /* Didn't find a match */ return 0; } NPY_NO_EXPORT int PyUFunc_DefaultLegacyInnerLoopSelector(PyUFuncObject *ufunc, PyArray_Descr **dtypes, PyUFuncGenericFunction *out_innerloop, void **out_innerloopdata, int *out_needs_api) { int nargs = ufunc->nargs; char *types; const char *ufunc_name; PyObject *errmsg; int i, j; ufunc_name = ufunc->name ? ufunc->name : "(unknown)"; /* * If there are user-loops search them first. * TODO: There needs to be a loop selection acceleration structure, * like a hash table. */ if (ufunc->userloops) { switch (find_userloop(ufunc, dtypes, out_innerloop, out_innerloopdata)) { /* Error */ case -1: return -1; /* Found a loop */ case 1: return 0; } } types = ufunc->types; for (i = 0; i < ufunc->ntypes; ++i) { /* Copy the types into an int array for matching */ for (j = 0; j < nargs; ++j) { if (types[j] != dtypes[j]->type_num) { break; } } if (j == nargs) { *out_innerloop = ufunc->functions[i]; *out_innerloopdata = ufunc->data[i]; return 0; } types += nargs; } errmsg = PyUString_FromFormat("ufunc '%s' did not contain a loop " "with signature matching types ", ufunc_name); for (i = 0; i < nargs; ++i) { PyUString_ConcatAndDel(&errmsg, PyObject_Repr((PyObject *)dtypes[i])); if (i < nargs - 1) { PyUString_ConcatAndDel(&errmsg, PyUString_FromString(" ")); } } PyErr_SetObject(PyExc_TypeError, errmsg); Py_DECREF(errmsg); return -1; } typedef struct { NpyAuxData base; PyUFuncGenericFunction unmasked_innerloop; void *unmasked_innerloopdata; int nargs; } _ufunc_masker_data; static NpyAuxData * ufunc_masker_data_clone(NpyAuxData *data) { _ufunc_masker_data *n; /* Allocate a new one */ n = (_ufunc_masker_data *)PyArray_malloc(sizeof(_ufunc_masker_data)); if (n == NULL) { return NULL; } /* Copy the data (unmasked data doesn't have object semantics) */ memcpy(n, data, sizeof(_ufunc_masker_data)); return (NpyAuxData *)n; } /* * This function wraps a regular unmasked ufunc inner loop as a * masked ufunc inner loop, only calling the function for * elements where the mask is True. */ static void unmasked_ufunc_loop_as_masked( char **dataptrs, npy_intp *strides, char *mask, npy_intp mask_stride, npy_intp loopsize, NpyAuxData *innerloopdata) { _ufunc_masker_data *data; int iargs, nargs; PyUFuncGenericFunction unmasked_innerloop; void *unmasked_innerloopdata; npy_intp subloopsize; /* Put the aux data into local variables */ data = (_ufunc_masker_data *)innerloopdata; unmasked_innerloop = data->unmasked_innerloop; unmasked_innerloopdata = data->unmasked_innerloopdata; nargs = data->nargs; /* Process the data as runs of unmasked values */ do { /* Skip masked values */ subloopsize = 0; while (subloopsize < loopsize && !*mask) { ++subloopsize; mask += mask_stride; } for (iargs = 0; iargs < nargs; ++iargs) { dataptrs[iargs] += subloopsize * strides[iargs]; } loopsize -= subloopsize; /* * Process unmasked values (assumes unmasked loop doesn't * mess with the 'args' pointer values) */ subloopsize = 0; while (subloopsize < loopsize && *mask) { ++subloopsize; mask += mask_stride; } unmasked_innerloop(dataptrs, &subloopsize, strides, unmasked_innerloopdata); for (iargs = 0; iargs < nargs; ++iargs) { dataptrs[iargs] += subloopsize * strides[iargs]; } loopsize -= subloopsize; } while (loopsize > 0); } /* * This function wraps a legacy inner loop so it becomes masked. * * Returns 0 on success, -1 on error. */ NPY_NO_EXPORT int PyUFunc_DefaultMaskedInnerLoopSelector(PyUFuncObject *ufunc, PyArray_Descr **dtypes, PyArray_Descr *mask_dtype, npy_intp *NPY_UNUSED(fixed_strides), npy_intp NPY_UNUSED(fixed_mask_stride), PyUFunc_MaskedStridedInnerLoopFunc **out_innerloop, NpyAuxData **out_innerloopdata, int *out_needs_api) { int retcode; _ufunc_masker_data *data; if (ufunc->legacy_inner_loop_selector == NULL) { PyErr_SetString(PyExc_RuntimeError, "the ufunc default masked inner loop selector doesn't " "yet support wrapping the new inner loop selector, it " "still only wraps the legacy inner loop selector"); return -1; } if (mask_dtype->type_num != NPY_BOOL) { PyErr_SetString(PyExc_ValueError, "only boolean masks are supported in ufunc inner loops " "presently"); return -1; } /* Create a new NpyAuxData object for the masker data */ data = (_ufunc_masker_data *)PyArray_malloc(sizeof(_ufunc_masker_data)); if (data == NULL) { PyErr_NoMemory(); return -1; } memset(data, 0, sizeof(_ufunc_masker_data)); data->base.free = (NpyAuxData_FreeFunc *)&PyArray_free; data->base.clone = &ufunc_masker_data_clone; data->nargs = ufunc->nin + ufunc->nout; /* Get the unmasked ufunc inner loop */ retcode = ufunc->legacy_inner_loop_selector(ufunc, dtypes, &data->unmasked_innerloop, &data->unmasked_innerloopdata, out_needs_api); if (retcode < 0) { PyArray_free(data); return retcode; } /* Return the loop function + aux data */ *out_innerloop = &unmasked_ufunc_loop_as_masked; *out_innerloopdata = (NpyAuxData *)data; return 0; } static int ufunc_loop_matches(PyUFuncObject *self, PyArrayObject **op, NPY_CASTING input_casting, NPY_CASTING output_casting, int any_object, int use_min_scalar, int *types, PyArray_Descr **dtypes, int *out_no_castable_output, char *out_err_src_typecode, char *out_err_dst_typecode) { npy_intp i, nin = self->nin, nop = nin + self->nout; /* * First check if all the inputs can be safely cast * to the types for this function */ for (i = 0; i < nin; ++i) { PyArray_Descr *tmp; /* * If no inputs are objects and there are more than one * loop, don't allow conversion to object. The rationale * behind this is mostly performance. Except for custom * ufuncs built with just one object-parametered inner loop, * only the types that are supported are implemented. Trying * the object version of logical_or on float arguments doesn't * seem right. */ if (types[i] == NPY_OBJECT && !any_object && self->ntypes > 1) { return 0; } /* * If type num is NPY_VOID and struct dtypes have been passed in, * use struct dtype object. Otherwise create new dtype object * from type num. */ if (types[i] == NPY_VOID && dtypes != NULL) { tmp = dtypes[i]; Py_INCREF(tmp); } else { tmp = PyArray_DescrFromType(types[i]); } if (tmp == NULL) { return -1; } #if NPY_UF_DBG_TRACING printf("Checking type for op %d, type %d: ", (int)i, (int)types[i]); PyObject_Print((PyObject *)tmp, stdout, 0); printf(", operand type: "); PyObject_Print((PyObject *)PyArray_DESCR(op[i]), stdout, 0); printf("\n"); #endif /* * If all the inputs are scalars, use the regular * promotion rules, not the special value-checking ones. */ if (!use_min_scalar) { if (!PyArray_CanCastTypeTo(PyArray_DESCR(op[i]), tmp, input_casting)) { Py_DECREF(tmp); return 0; } } else { if (!PyArray_CanCastArrayTo(op[i], tmp, input_casting)) { Py_DECREF(tmp); return 0; } } Py_DECREF(tmp); } /* * If all the inputs were ok, then check casting back to the * outputs. */ for (i = nin; i < nop; ++i) { if (op[i] != NULL) { PyArray_Descr *tmp = PyArray_DescrFromType(types[i]); if (tmp == NULL) { return -1; } if (!PyArray_CanCastTypeTo(tmp, PyArray_DESCR(op[i]), output_casting)) { if (!(*out_no_castable_output)) { *out_no_castable_output = 1; *out_err_src_typecode = tmp->type; *out_err_dst_typecode = PyArray_DESCR(op[i])->type; } Py_DECREF(tmp); return 0; } Py_DECREF(tmp); } } return 1; } static int set_ufunc_loop_data_types(PyUFuncObject *self, PyArrayObject **op, PyArray_Descr **out_dtypes, int *type_nums, PyArray_Descr **dtypes) { int i, nin = self->nin, nop = nin + self->nout; /* * Fill the dtypes array. * For outputs, * also search the inputs for a matching type_num to copy * instead of creating a new one, similarly to preserve metadata. **/ for (i = 0; i < nop; ++i) { if (dtypes != NULL) { out_dtypes[i] = dtypes[i]; Py_XINCREF(out_dtypes[i]); /* * Copy the dtype from 'op' if the type_num matches, * to preserve metadata. */ } else if (op[i] != NULL && PyArray_DESCR(op[i])->type_num == type_nums[i]) { out_dtypes[i] = ensure_dtype_nbo(PyArray_DESCR(op[i])); Py_XINCREF(out_dtypes[i]); } /* * For outputs, copy the dtype from op[0] if the type_num * matches, similarly to preserve metdata. */ else if (i >= nin && op[0] != NULL && PyArray_DESCR(op[0])->type_num == type_nums[i]) { out_dtypes[i] = ensure_dtype_nbo(PyArray_DESCR(op[0])); Py_XINCREF(out_dtypes[i]); } /* Otherwise create a plain descr from the type number */ else { out_dtypes[i] = PyArray_DescrFromType(type_nums[i]); } if (out_dtypes[i] == NULL) { goto fail; } } return 0; fail: while (--i >= 0) { Py_DECREF(out_dtypes[i]); out_dtypes[i] = NULL; } return -1; } /* * Does a search through the arguments and the loops */ static int linear_search_userloop_type_resolver(PyUFuncObject *self, PyArrayObject **op, NPY_CASTING input_casting, NPY_CASTING output_casting, int any_object, int use_min_scalar, PyArray_Descr **out_dtype, int *out_no_castable_output, char *out_err_src_typecode, char *out_err_dst_typecode) { npy_intp i, nop = self->nin + self->nout; PyUFunc_Loop1d *funcdata; /* Use this to try to avoid repeating the same userdef loop search */ int last_userdef = -1; for (i = 0; i < nop; ++i) { int type_num; /* no more ufunc arguments to check */ if (op[i] == NULL) { break; } type_num = PyArray_DESCR(op[i])->type_num; if (type_num != last_userdef && (PyTypeNum_ISUSERDEF(type_num) || type_num == NPY_VOID)) { PyObject *key, *obj; last_userdef = type_num; key = PyInt_FromLong(type_num); if (key == NULL) { return -1; } obj = PyDict_GetItem(self->userloops, key); Py_DECREF(key); if (obj == NULL) { continue; } funcdata = (PyUFunc_Loop1d *)NpyCapsule_AsVoidPtr(obj); while (funcdata != NULL) { int *types = funcdata->arg_types; switch (ufunc_loop_matches(self, op, input_casting, output_casting, any_object, use_min_scalar, types, funcdata->arg_dtypes, out_no_castable_output, out_err_src_typecode, out_err_dst_typecode)) { /* Error */ case -1: return -1; /* Found a match */ case 1: set_ufunc_loop_data_types(self, op, out_dtype, types, funcdata->arg_dtypes); return 1; } funcdata = funcdata->next; } } } /* Didn't find a match */ return 0; } /* * Does a search through the arguments and the loops */ static int type_tuple_userloop_type_resolver(PyUFuncObject *self, int n_specified, int *specified_types, PyArrayObject **op, NPY_CASTING casting, int any_object, int use_min_scalar, PyArray_Descr **out_dtype) { int i, j, nin = self->nin, nop = nin + self->nout; PyUFunc_Loop1d *funcdata; /* Use this to try to avoid repeating the same userdef loop search */ int last_userdef = -1; int no_castable_output = 0; char err_src_typecode = '-', err_dst_typecode = '-'; for (i = 0; i < nin; ++i) { int type_num = PyArray_DESCR(op[i])->type_num; if (type_num != last_userdef && PyTypeNum_ISUSERDEF(type_num)) { PyObject *key, *obj; last_userdef = type_num; key = PyInt_FromLong(type_num); if (key == NULL) { return -1; } obj = PyDict_GetItem(self->userloops, key); Py_DECREF(key); if (obj == NULL) { continue; } funcdata = (PyUFunc_Loop1d *)NpyCapsule_AsVoidPtr(obj); while (funcdata != NULL) { int *types = funcdata->arg_types; int matched = 1; if (n_specified == nop) { for (j = 0; j < nop; ++j) { if (types[j] != specified_types[j] && specified_types[j] != NPY_NOTYPE) { matched = 0; break; } } } else { if (types[nin] != specified_types[0]) { matched = 0; } } if (!matched) { continue; } switch (ufunc_loop_matches(self, op, casting, casting, any_object, use_min_scalar, types, NULL, &no_castable_output, &err_src_typecode, &err_dst_typecode)) { /* It works */ case 1: set_ufunc_loop_data_types(self, op, out_dtype, types, NULL); return 1; /* Didn't match */ case 0: PyErr_Format(PyExc_TypeError, "found a user loop for ufunc '%s' " "matching the type-tuple, " "but the inputs and/or outputs could not be " "cast according to the casting rule", self->name ? self->name : "(unknown)"); return -1; /* Error */ case -1: return -1; } funcdata = funcdata->next; } } } /* Didn't find a match */ return 0; } /* * Provides an ordering for the dtype 'kind' character codes, to help * determine when to use the min_scalar_type function. This groups * 'kind' into boolean, integer, floating point, and everything else. */ static int dtype_kind_to_simplified_ordering(char kind) { switch (kind) { /* Boolean kind */ case 'b': return 0; /* Unsigned int kind */ case 'u': /* Signed int kind */ case 'i': return 1; /* Float kind */ case 'f': /* Complex kind */ case 'c': return 2; /* Anything else */ default: return 3; } } static int should_use_min_scalar(PyArrayObject **op, int nop) { int i, use_min_scalar, kind; int all_scalars = 1, max_scalar_kind = -1, max_array_kind = -1; /* * Determine if there are any scalars, and if so, whether * the maximum "kind" of the scalars surpasses the maximum * "kind" of the arrays */ use_min_scalar = 0; if (nop > 1) { for(i = 0; i < nop; ++i) { kind = dtype_kind_to_simplified_ordering( PyArray_DESCR(op[i])->kind); if (PyArray_NDIM(op[i]) == 0) { if (kind > max_scalar_kind) { max_scalar_kind = kind; } } else { all_scalars = 0; if (kind > max_array_kind) { max_array_kind = kind; } } } /* Indicate whether to use the min_scalar_type function */ if (!all_scalars && max_array_kind >= max_scalar_kind) { use_min_scalar = 1; } } return use_min_scalar; } /* * Does a linear search for the best inner loop of the ufunc. * * Note that if an error is returned, the caller must free the non-zero * references in out_dtype. This function does not do its own clean-up. */ NPY_NO_EXPORT int linear_search_type_resolver(PyUFuncObject *self, PyArrayObject **op, NPY_CASTING input_casting, NPY_CASTING output_casting, int any_object, PyArray_Descr **out_dtype) { npy_intp i, j, nin = self->nin, nop = nin + self->nout; int types[NPY_MAXARGS]; char *ufunc_name; int no_castable_output, use_min_scalar; /* For making a better error message on coercion error */ char err_dst_typecode = '-', err_src_typecode = '-'; ufunc_name = self->name ? self->name : "(unknown)"; use_min_scalar = should_use_min_scalar(op, nin); /* If the ufunc has userloops, search for them. */ if (self->userloops) { switch (linear_search_userloop_type_resolver(self, op, input_casting, output_casting, any_object, use_min_scalar, out_dtype, &no_castable_output, &err_src_typecode, &err_dst_typecode)) { /* Error */ case -1: return -1; /* A loop was found */ case 1: return 0; } } /* * Determine the UFunc loop. This could in general be *much* faster, * and a better way to implement it might be for the ufunc to * provide a function which gives back the result type and inner * loop function. * * A default fast mechanism could be provided for functions which * follow the most typical pattern, when all functions have signatures * "xx...x -> x" for some built-in data type x, as follows. * - Use PyArray_ResultType to get the output type * - Look up the inner loop in a table based on the output type_num * * The method for finding the loop in the previous code did not * appear consistent (as noted by some asymmetry in the generated * coercion tables for np.add). */ no_castable_output = 0; for (i = 0; i < self->ntypes; ++i) { char *orig_types = self->types + i*self->nargs; /* Copy the types into an int array for matching */ for (j = 0; j < nop; ++j) { types[j] = orig_types[j]; } switch (ufunc_loop_matches(self, op, input_casting, output_casting, any_object, use_min_scalar, types, NULL, &no_castable_output, &err_src_typecode, &err_dst_typecode)) { /* Error */ case -1: return -1; /* Found a match */ case 1: set_ufunc_loop_data_types(self, op, out_dtype, types, NULL); return 0; } } /* If no function was found, throw an error */ if (no_castable_output) { PyErr_Format(PyExc_TypeError, "ufunc '%s' output (typecode '%c') could not be coerced to " "provided output parameter (typecode '%c') according " "to the casting rule '%s'", ufunc_name, err_src_typecode, err_dst_typecode, npy_casting_to_string(output_casting)); } else { /* * TODO: We should try again if the casting rule is same_kind * or unsafe, and look for a function more liberally. */ PyErr_Format(PyExc_TypeError, "ufunc '%s' not supported for the input types, and the " "inputs could not be safely coerced to any supported " "types according to the casting rule '%s'", ufunc_name, npy_casting_to_string(input_casting)); } return -1; } /* * Does a linear search for the inner loop of the ufunc specified by type_tup. * * Note that if an error is returned, the caller must free the non-zero * references in out_dtype. This function does not do its own clean-up. */ NPY_NO_EXPORT int type_tuple_type_resolver(PyUFuncObject *self, PyObject *type_tup, PyArrayObject **op, NPY_CASTING casting, int any_object, PyArray_Descr **out_dtype) { 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; int no_castable_output, use_min_scalar; /* For making a better error message on coercion error */ char err_dst_typecode = '-', err_src_typecode = '-'; ufunc_name = self->name ? self->name : "(unknown)"; use_min_scalar = should_use_min_scalar(op, nin); /* Fill in specified_types from the tuple or string */ if (PyTuple_Check(type_tup)) { int nonecount = 0; n = PyTuple_GET_SIZE(type_tup); if (n != 1 && n != nop) { PyErr_Format(PyExc_ValueError, "a type-tuple must be specified " "of length 1 or %d for ufunc '%s'", (int)nop, self->name ? self->name : "(unknown)"); return -1; } for (i = 0; i < n; ++i) { PyObject *item = PyTuple_GET_ITEM(type_tup, i); if (item == Py_None) { specified_types[i] = NPY_NOTYPE; ++nonecount; } else { PyArray_Descr *dtype = NULL; if (!PyArray_DescrConverter(item, &dtype)) { return -1; } specified_types[i] = dtype->type_num; Py_DECREF(dtype); } } if (nonecount == n) { PyErr_SetString(PyExc_ValueError, "the type-tuple provided to the ufunc " "must specify at least one none-None dtype"); return -1; } n_specified = n; } else if (PyBytes_Check(type_tup) || PyUnicode_Check(type_tup)) { Py_ssize_t length; char *str; PyObject *str_obj = NULL; if (PyUnicode_Check(type_tup)) { str_obj = PyUnicode_AsASCIIString(type_tup); if (str_obj == NULL) { return -1; } type_tup = str_obj; } if (!PyBytes_AsStringAndSize(type_tup, &str, &length) < 0) { Py_XDECREF(str_obj); return -1; } if (length != 1 && (length != nop + 2 || str[nin] != '-' || str[nin+1] != '>')) { PyErr_Format(PyExc_ValueError, "a type-string for %s, " \ "requires 1 typecode, or " "%d typecode(s) before " \ "and %d after the -> sign", self->name ? self->name : "(unknown)", self->nin, self->nout); Py_XDECREF(str_obj); return -1; } if (length == 1) { PyArray_Descr *dtype; n_specified = 1; dtype = PyArray_DescrFromType(str[0]); if (dtype == NULL) { Py_XDECREF(str_obj); return -1; } specified_types[0] = dtype->type_num; Py_DECREF(dtype); } else { PyArray_Descr *dtype; n_specified = (int)nop; for (i = 0; i < nop; ++i) { npy_intp istr = i < nin ? i : i+2; dtype = PyArray_DescrFromType(str[istr]); if (dtype == NULL) { Py_XDECREF(str_obj); return -1; } specified_types[i] = dtype->type_num; Py_DECREF(dtype); } } Py_XDECREF(str_obj); } /* If the ufunc has userloops, search for them. */ if (self->userloops) { switch (type_tuple_userloop_type_resolver(self, n_specified, specified_types, op, casting, any_object, use_min_scalar, out_dtype)) { /* Error */ case -1: return -1; /* Found matching loop */ case 1: return 0; } } for (i = 0; i < self->ntypes; ++i) { char *orig_types = self->types + i*self->nargs; int matched = 1; /* Copy the types into an int array for matching */ for (j = 0; j < nop; ++j) { types[j] = orig_types[j]; } if (n_specified == nop) { for (j = 0; j < nop; ++j) { if (types[j] != specified_types[j] && specified_types[j] != NPY_NOTYPE) { matched = 0; break; } } } else { if (types[nin] != specified_types[0]) { matched = 0; } } if (!matched) { continue; } switch (ufunc_loop_matches(self, op, casting, casting, any_object, use_min_scalar, types, NULL, &no_castable_output, &err_src_typecode, &err_dst_typecode)) { /* Error */ case -1: return -1; /* It worked */ case 1: set_ufunc_loop_data_types(self, op, out_dtype, types, NULL); return 0; /* Didn't work */ case 0: PyErr_Format(PyExc_TypeError, "found a loop for ufunc '%s' " "matching the type-tuple, " "but the inputs and/or outputs could not be " "cast according to the casting rule", ufunc_name); return -1; } } /* If no function was found, throw an error */ PyErr_Format(PyExc_TypeError, "No loop matching the specified signature was found " "for ufunc %s", ufunc_name); return -1; } numpy-1.8.2/numpy/core/src/umath/ufunc_type_resolution.h0000664000175100017510000001110112370216243024640 0ustar vagrantvagrant00000000000000#ifndef _NPY_PRIVATE__UFUNC_TYPE_RESOLUTION_H_ #define _NPY_PRIVATE__UFUNC_TYPE_RESOLUTION_H_ NPY_NO_EXPORT int PyUFunc_SimpleBinaryComparisonTypeResolver(PyUFuncObject *ufunc, NPY_CASTING casting, PyArrayObject **operands, PyObject *type_tup, PyArray_Descr **out_dtypes); NPY_NO_EXPORT int PyUFunc_SimpleUnaryOperationTypeResolver(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, PyObject *type_tup, PyArray_Descr **out_dtypes); NPY_NO_EXPORT int PyUFunc_SimpleBinaryOperationTypeResolver(PyUFuncObject *ufunc, NPY_CASTING casting, PyArrayObject **operands, PyObject *type_tup, PyArray_Descr **out_dtypes); NPY_NO_EXPORT int PyUFunc_AbsoluteTypeResolver(PyUFuncObject *ufunc, NPY_CASTING casting, PyArrayObject **operands, PyObject *type_tup, PyArray_Descr **out_dtypes); NPY_NO_EXPORT int PyUFunc_AdditionTypeResolver(PyUFuncObject *ufunc, NPY_CASTING casting, PyArrayObject **operands, PyObject *type_tup, PyArray_Descr **out_dtypes); NPY_NO_EXPORT int PyUFunc_SubtractionTypeResolver(PyUFuncObject *ufunc, NPY_CASTING casting, PyArrayObject **operands, PyObject *type_tup, PyArray_Descr **out_dtypes); NPY_NO_EXPORT int PyUFunc_MultiplicationTypeResolver(PyUFuncObject *ufunc, NPY_CASTING casting, PyArrayObject **operands, PyObject *type_tup, PyArray_Descr **out_dtypes); NPY_NO_EXPORT int PyUFunc_DivisionTypeResolver(PyUFuncObject *ufunc, NPY_CASTING casting, PyArrayObject **operands, PyObject *type_tup, PyArray_Descr **out_dtypes); /* * Does a linear search for the best inner loop of the ufunc. * * Note that if an error is returned, the caller must free the non-zero * references in out_dtype. This function does not do its own clean-up. */ NPY_NO_EXPORT int linear_search_type_resolver(PyUFuncObject *self, PyArrayObject **op, NPY_CASTING input_casting, NPY_CASTING output_casting, int any_object, PyArray_Descr **out_dtype); /* * Does a linear search for the inner loop of the ufunc specified by type_tup. * * Note that if an error is returned, the caller must free the non-zero * references in out_dtype. This function does not do its own clean-up. */ NPY_NO_EXPORT int type_tuple_type_resolver(PyUFuncObject *self, PyObject *type_tup, PyArrayObject **op, NPY_CASTING casting, int any_object, PyArray_Descr **out_dtype); NPY_NO_EXPORT int PyUFunc_DefaultLegacyInnerLoopSelector(PyUFuncObject *ufunc, PyArray_Descr **dtypes, PyUFuncGenericFunction *out_innerloop, void **out_innerloopdata, int *out_needs_api); NPY_NO_EXPORT int PyUFunc_DefaultMaskedInnerLoopSelector(PyUFuncObject *ufunc, PyArray_Descr **dtypes, PyArray_Descr *mask_dtypes, npy_intp *NPY_UNUSED(fixed_strides), npy_intp NPY_UNUSED(fixed_mask_stride), PyUFunc_MaskedStridedInnerLoopFunc **out_innerloop, NpyAuxData **out_innerloopdata, int *out_needs_api); #endif numpy-1.8.2/numpy/core/src/umath/struct_ufunc_test.c.src0000664000175100017510000000532112370216242024546 0ustar vagrantvagrant00000000000000#define NPY_NO_DEPRECATED_API NPY_API_VERSION #include "Python.h" #include "math.h" #include "numpy/ndarraytypes.h" #include "numpy/ufuncobject.h" #include "numpy/npy_3kcompat.h" /* * struct_ufunc_test.c * This is the C code for creating your own * Numpy ufunc for a structured array dtype. * * Details explaining the Python-C API can be found under * 'Extending and Embedding' and 'Python/C API' at * docs.python.org . */ static PyMethodDef StructUfuncTestMethods[] = { {NULL, NULL, 0, NULL} }; /* The loop definition must precede the PyMODINIT_FUNC. */ static void add_uint64_triplet(char **args, npy_intp *dimensions, npy_intp* steps, void* data) { npy_intp i; npy_intp is1=steps[0]; npy_intp is2=steps[1]; npy_intp os=steps[2]; npy_intp n=dimensions[0]; npy_uint64 *x, *y, *z; char *i1=args[0]; char *i2=args[1]; char *op=args[2]; for (i = 0; i < n; i++) { x = (npy_uint64*)i1; y = (npy_uint64*)i2; z = (npy_uint64*)op; z[0] = x[0] + y[0]; z[1] = x[1] + y[1]; z[2] = x[2] + y[2]; i1 += is1; i2 += is2; op += os; } } #if defined(NPY_PY3K) static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, "struct_ufunc_test", NULL, -1, StructUfuncTestMethods, NULL, NULL, NULL, NULL }; #endif #if defined(NPY_PY3K) PyMODINIT_FUNC PyInit_struct_ufunc_test(void) #else PyMODINIT_FUNC initstruct_ufunc_test(void) #endif { PyObject *m, *add_triplet, *d; PyObject *dtype_dict; PyArray_Descr *dtype; PyArray_Descr *dtypes[3]; #if defined(NPY_PY3K) m = PyModule_Create(&moduledef); #else m = Py_InitModule("struct_ufunc_test", StructUfuncTestMethods); #endif if (m == NULL) { #if defined(NPY_PY3K) return NULL; #else return; #endif } import_array(); import_umath(); add_triplet = PyUFunc_FromFuncAndData(NULL, NULL, NULL, 0, 2, 1, PyUFunc_None, "add_triplet", "add_triplet_docstring", 0); dtype_dict = Py_BuildValue("[(s, s), (s, s), (s, s)]", "f0", "u8", "f1", "u8", "f2", "u8"); PyArray_DescrConverter(dtype_dict, &dtype); Py_DECREF(dtype_dict); dtypes[0] = dtype; dtypes[1] = dtype; dtypes[2] = dtype; PyUFunc_RegisterLoopForDescr((PyUFuncObject *)add_triplet, dtype, &add_uint64_triplet, dtypes, NULL); d = PyModule_GetDict(m); PyDict_SetItemString(d, "add_triplet", add_triplet); Py_DECREF(add_triplet); #if defined(NPY_PY3K) return m; #endif } numpy-1.8.2/numpy/core/src/umath/simd.inc.src0000664000175100017510000006017312370216243022255 0ustar vagrantvagrant00000000000000/* -*- c -*- */ /* * This file is for the definitions of simd vectorized operations. * * Currently contains sse2 functions that are built on amd64, x32 or * non-generic builds (CFLAGS=-march=...) * In future it may contain other instruction sets like AVX or NEON detected * at runtime in which case it needs to be included indirectly via a file * compiled with special options (or use gcc target attributes) so the binary * stays portable. */ #ifndef __NPY_SIMD_INC #define __NPY_SIMD_INC #include "lowlevel_strided_loops.h" #include "numpy/npy_common.h" /* for NO_FLOATING_POINT_SUPPORT */ #include "numpy/ufuncobject.h" #ifdef NPY_HAVE_SSE2_INTRINSICS #include #endif #include #include #include /* for memcpy */ int PyUFunc_getfperr(void); void PyUFunc_clearfperr(void); /* * stride is equal to element size and input and destination are equal or * don't overlap within one register */ #define IS_BLOCKABLE_UNARY(esize, vsize) \ (steps[0] == (esize) && steps[0] == steps[1] && \ (npy_is_aligned(args[0], esize) && npy_is_aligned(args[1], esize)) && \ ((abs(args[1] - args[0]) >= (vsize)) || ((abs(args[1] - args[0]) == 0)))) #define IS_BLOCKABLE_REDUCE(esize, vsize) \ (steps[1] == (esize) && abs(args[1] - args[0]) >= (vsize) && \ npy_is_aligned(args[1], (esize)) && \ npy_is_aligned(args[0], (esize))) #define IS_BLOCKABLE_BINARY(esize, vsize) \ (steps[0] == steps[1] && steps[1] == steps[2] && steps[2] == (esize) && \ npy_is_aligned(args[2], (esize)) && npy_is_aligned(args[1], (esize)) && \ npy_is_aligned(args[0], (esize)) && \ (abs(args[2] - args[0]) >= (vsize) || abs(args[2] - args[0]) == 0) && \ (abs(args[2] - args[1]) >= (vsize) || abs(args[2] - args[1]) >= 0)) #define IS_BLOCKABLE_BINARY_SCALAR1(esize, vsize) \ (steps[0] == 0 && steps[1] == steps[2] && steps[2] == (esize) && \ npy_is_aligned(args[2], (esize)) && npy_is_aligned(args[1], (esize)) && \ ((abs(args[2] - args[1]) >= (vsize)) || (abs(args[2] - args[1]) == 0)) && \ abs(args[2] - args[0]) >= (esize)) #define IS_BLOCKABLE_BINARY_SCALAR2(esize, vsize) \ (steps[1] == 0 && steps[0] == steps[2] && steps[2] == (esize) && \ npy_is_aligned(args[2], (esize)) && npy_is_aligned(args[0], (esize)) && \ ((abs(args[2] - args[0]) >= (vsize)) || (abs(args[2] - args[0]) == 0)) && \ abs(args[2] - args[1]) >= (esize)) #define IS_BLOCKABLE_BINARY_BOOL(esize, vsize) \ (steps[0] == (esize) && steps[0] == steps[1] && steps[2] == (1) && \ npy_is_aligned(args[1], (esize)) && \ npy_is_aligned(args[0], (esize))) #define IS_BLOCKABLE_BINARY_SCALAR1_BOOL(esize, vsize) \ (steps[0] == 0 && steps[1] == (esize) && steps[2] == (1) && \ npy_is_aligned(args[1], (esize))) #define IS_BLOCKABLE_BINARY_SCALAR2_BOOL(esize, vsize) \ (steps[0] == (esize) && steps[1] == 0 && steps[2] == (1) && \ npy_is_aligned(args[0], (esize))) /* align var to alignment */ #define LOOP_BLOCK_ALIGN_VAR(var, type, alignment)\ npy_intp i, peel = npy_aligned_block_offset(var, sizeof(type),\ alignment, n);\ for(i = 0; i < peel; i++) #define LOOP_BLOCKED(type, vsize)\ for(; i < npy_blocked_end(peel, sizeof(type), vsize, n);\ i += (vsize / sizeof(type))) #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 * decide whether the operation can be vectorized and run it * if it was run returns true and false if nothing was done */ /* ***************************************************************************** ** FLOAT DISPATCHERS ***************************************************************************** */ /**begin repeat * Float types * #type = npy_float, npy_double, npy_longdouble# * #TYPE = FLOAT, DOUBLE, LONGDOUBLE# * #vector = 1, 1, 0# */ /**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# */ #if @vector@ && defined NPY_HAVE_SSE2_INTRINSICS /* prototypes */ static void sse2_@func@_@TYPE@(@type@ *, @type@ *, const npy_intp n); #endif static NPY_INLINE int run_@name@_simd_@func@_@TYPE@(char **args, npy_intp *dimensions, npy_intp *steps) { #if @vector@ && defined NPY_HAVE_SSE2_INTRINSICS if (@check@(sizeof(@type@), 16)) { sse2_@func@_@TYPE@((@type@*)args[1], (@type@*)args[0], dimensions[0]); return 1; } #endif return 0; } /**end repeat1**/ /**begin repeat1 * Arithmetic * # kind = add, subtract, multiply, divide# */ #if @vector@ && defined NPY_HAVE_SSE2_INTRINSICS /* prototypes */ static void sse2_binary_@kind@_@TYPE@(@type@ * op, @type@ * ip1, @type@ * ip2, npy_intp n); static void sse2_binary_scalar1_@kind@_@TYPE@(@type@ * op, @type@ * ip1, @type@ * ip2, npy_intp n); static void sse2_binary_scalar2_@kind@_@TYPE@(@type@ * op, @type@ * ip1, @type@ * ip2, npy_intp n); #endif static NPY_INLINE int run_binary_simd_@kind@_@TYPE@(char **args, npy_intp *dimensions, npy_intp *steps) { #if @vector@ && defined NPY_HAVE_SSE2_INTRINSICS @type@ * ip1 = (@type@ *)args[0]; @type@ * ip2 = (@type@ *)args[1]; @type@ * op = (@type@ *)args[2]; npy_intp n = dimensions[0]; /* argument one scalar */ if (IS_BLOCKABLE_BINARY_SCALAR1(sizeof(@type@), 16)) { sse2_binary_scalar1_@kind@_@TYPE@(op, ip1, ip2, n); return 1; } /* argument two scalar */ else if (IS_BLOCKABLE_BINARY_SCALAR2(sizeof(@type@), 16)) { sse2_binary_scalar2_@kind@_@TYPE@(op, ip1, ip2, n); return 1; } else if (IS_BLOCKABLE_BINARY(sizeof(@type@), 16)) { sse2_binary_@kind@_@TYPE@(op, ip1, ip2, n); return 1; } #endif return 0; } /**end repeat1**/ /**begin repeat1 * #kind = equal, not_equal, less, less_equal, greater, greater_equal, * logical_and, logical_or# * #simd = 1, 1, 1, 1, 1, 1, 0, 0# */ #if @vector@ && @simd@ && defined NPY_HAVE_SSE2_INTRINSICS /* prototypes */ static void 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); static void sse2_binary_scalar2_@kind@_@TYPE@(npy_bool * op, @type@ * ip1, @type@ * ip2, npy_intp n); #endif static NPY_INLINE int run_binary_simd_@kind@_@TYPE@(char **args, npy_intp *dimensions, npy_intp *steps) { #if @vector@ && @simd@ && defined NPY_HAVE_SSE2_INTRINSICS @type@ * ip1 = (@type@ *)args[0]; @type@ * ip2 = (@type@ *)args[1]; npy_bool * op = (npy_bool *)args[2]; npy_intp n = dimensions[0]; /* argument one scalar */ if (IS_BLOCKABLE_BINARY_SCALAR1_BOOL(sizeof(@type@), 16)) { sse2_binary_scalar1_@kind@_@TYPE@(op, ip1, ip2, n); return 1; } /* argument two scalar */ else if (IS_BLOCKABLE_BINARY_SCALAR2_BOOL(sizeof(@type@), 16)) { sse2_binary_scalar2_@kind@_@TYPE@(op, ip1, ip2, n); return 1; } else if (IS_BLOCKABLE_BINARY_BOOL(sizeof(@type@), 16)) { sse2_binary_@kind@_@TYPE@(op, ip1, ip2, n); return 1; } #endif return 0; } /**end repeat1**/ /**end repeat**/ /* ***************************************************************************** ** BOOL DISPATCHERS ***************************************************************************** */ /**begin repeat * # kind = logical_or, logical_and# */ static void sse2_binary_@kind@_BOOL(npy_bool * op, npy_bool * ip1, npy_bool * ip2, npy_intp n); static NPY_INLINE int run_binary_simd_@kind@_BOOL(char **args, npy_intp *dimensions, npy_intp *steps) { #if defined NPY_HAVE_SSE2_INTRINSICS if (sizeof(npy_bool) == 1 && IS_BLOCKABLE_BINARY(sizeof(npy_bool), 16)) { sse2_binary_@kind@_BOOL((npy_bool*)args[2], (npy_bool*)args[0], (npy_bool*)args[1], dimensions[0]); return 1; } #endif return 0; } 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) { #if defined NPY_HAVE_SSE2_INTRINSICS if (sizeof(npy_bool) == 1 && IS_BLOCKABLE_REDUCE(sizeof(npy_bool), 16)) { sse2_reduce_@kind@_BOOL((npy_bool*)args[0], (npy_bool*)args[1], dimensions[0]); return 1; } #endif return 0; } /**end repeat**/ /**begin repeat * # kind = absolute, logical_not# */ static void sse2_@kind@_BOOL(npy_bool *, npy_bool *, const npy_intp n); static NPY_INLINE int run_unary_simd_@kind@_BOOL(char **args, npy_intp *dimensions, npy_intp *steps) { #if defined NPY_HAVE_SSE2_INTRINSICS if (sizeof(npy_bool) == 1 && IS_BLOCKABLE_UNARY(sizeof(npy_bool), 16)) { sse2_@kind@_BOOL((npy_bool*)args[1], (npy_bool*)args[0], dimensions[0]); return 1; } #endif return 0; } /**end repeat**/ #ifdef NPY_HAVE_SSE2_INTRINSICS /* * Vectorized operations */ /* ***************************************************************************** ** FLOAT LOOPS ***************************************************************************** */ /**begin repeat * horizontal reductions on a vector * # VOP = min, max# */ static NPY_INLINE npy_float sse2_horizontal_@VOP@___m128(__m128 v) { npy_float r; __m128 tmp = _mm_movehl_ps(v, v); /* c d ... */ __m128 m = _mm_@VOP@_ps(v, tmp); /* m(ac) m(bd) ... */ tmp = _mm_shuffle_ps(m, m, _MM_SHUFFLE(1, 1, 1, 1));/* m(bd) m(bd) ... */ _mm_store_ss(&r, _mm_@VOP@_ps(tmp, m)); /* m(acbd) ... */ return r; } static NPY_INLINE npy_double sse2_horizontal_@VOP@___m128d(__m128d v) { npy_double r; __m128d tmp = _mm_unpackhi_pd(v, v); /* b b */ _mm_store_sd(&r, _mm_@VOP@_pd(tmp, v)); /* m(ab) m(bb) */ return r; } /**end repeat**/ /**begin repeat * #type = npy_float, npy_double# * #TYPE = FLOAT, DOUBLE# * #scalarf = npy_sqrtf, npy_sqrt# * #c = f, # * #vtype = __m128, __m128d# * #vpre = _mm, _mm# * #vsuf = ps, pd# * #vsufs = ss, sd# * #nan = NPY_NANF, NPY_NAN# * #mtype = npy_int32, npy_int16# * #fanout = fanout_4, fanout_2# */ /**begin repeat1 * Arithmetic * # kind = add, subtract, multiply, divide# * # OP = +, -, *, /# * # VOP = add, sub, mul, div# */ static void sse2_binary_@kind@_@TYPE@(@type@ * op, @type@ * ip1, @type@ * ip2, npy_intp n) { LOOP_BLOCK_ALIGN_VAR(op, @type@, 16) op[i] = ip1[i] @OP@ ip2[i]; /* lots of specializations, to squeeze out max performance */ if (npy_is_aligned(&ip1[i], 16) && npy_is_aligned(&ip2[i], 16)) { if (ip1 == ip2) { LOOP_BLOCKED(@type@, 16) { @vtype@ a = @vpre@_load_@vsuf@(&ip1[i]); @vtype@ c = @vpre@_@VOP@_@vsuf@(a, a); @vpre@_store_@vsuf@(&op[i], c); } } else { LOOP_BLOCKED(@type@, 16) { @vtype@ a = @vpre@_load_@vsuf@(&ip1[i]); @vtype@ b = @vpre@_load_@vsuf@(&ip2[i]); @vtype@ c = @vpre@_@VOP@_@vsuf@(a, b); @vpre@_store_@vsuf@(&op[i], c); } } } else if (npy_is_aligned(&ip1[i], 16)) { 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); @vpre@_store_@vsuf@(&op[i], c); } } else if (npy_is_aligned(&ip2[i], 16)) { LOOP_BLOCKED(@type@, 16) { @vtype@ a = @vpre@_loadu_@vsuf@(&ip1[i]); @vtype@ b = @vpre@_load_@vsuf@(&ip2[i]); @vtype@ c = @vpre@_@VOP@_@vsuf@(a, b); @vpre@_store_@vsuf@(&op[i], c); } } else { if (ip1 == ip2) { LOOP_BLOCKED(@type@, 16) { @vtype@ a = @vpre@_loadu_@vsuf@(&ip1[i]); @vtype@ c = @vpre@_@VOP@_@vsuf@(a, a); @vpre@_store_@vsuf@(&op[i], c); } } else { LOOP_BLOCKED(@type@, 16) { @vtype@ a = @vpre@_loadu_@vsuf@(&ip1[i]); @vtype@ b = @vpre@_loadu_@vsuf@(&ip2[i]); @vtype@ c = @vpre@_@VOP@_@vsuf@(a, b); @vpre@_store_@vsuf@(&op[i], c); } } } LOOP_BLOCKED_END { op[i] = ip1[i] @OP@ ip2[i]; } } static void sse2_binary_scalar1_@kind@_@TYPE@(@type@ * op, @type@ * ip1, @type@ * ip2, npy_intp n) { const @vtype@ a = @vpre@_set1_@vsuf@(ip1[0]); LOOP_BLOCK_ALIGN_VAR(op, @type@, 16) op[i] = ip1[0] @OP@ ip2[i]; if (npy_is_aligned(&ip2[i], 16)) { LOOP_BLOCKED(@type@, 16) { @vtype@ b = @vpre@_load_@vsuf@(&ip2[i]); @vtype@ c = @vpre@_@VOP@_@vsuf@(a, b); @vpre@_store_@vsuf@(&op[i], c); } } else { LOOP_BLOCKED(@type@, 16) { @vtype@ b = @vpre@_loadu_@vsuf@(&ip2[i]); @vtype@ c = @vpre@_@VOP@_@vsuf@(a, b); @vpre@_store_@vsuf@(&op[i], c); } } LOOP_BLOCKED_END { op[i] = ip1[0] @OP@ ip2[i]; } } static void sse2_binary_scalar2_@kind@_@TYPE@(@type@ * op, @type@ * ip1, @type@ * ip2, npy_intp n) { const @vtype@ b = @vpre@_set1_@vsuf@(ip2[0]); LOOP_BLOCK_ALIGN_VAR(op, @type@, 16) op[i] = ip1[i] @OP@ ip2[0]; if (npy_is_aligned(&ip1[i], 16)) { LOOP_BLOCKED(@type@, 16) { @vtype@ a = @vpre@_load_@vsuf@(&ip1[i]); @vtype@ c = @vpre@_@VOP@_@vsuf@(a, b); @vpre@_store_@vsuf@(&op[i], c); } } else { LOOP_BLOCKED(@type@, 16) { @vtype@ a = @vpre@_loadu_@vsuf@(&ip1[i]); @vtype@ c = @vpre@_@VOP@_@vsuf@(a, b); @vpre@_store_@vsuf@(&op[i], c); } } LOOP_BLOCKED_END { op[i] = ip1[i] @OP@ ip2[0]; } } /**end repeat1**/ /**begin repeat1 * #kind = equal, not_equal, less, less_equal, greater, greater_equal# * #OP = ==, !=, <, <=, >, >=# * #VOP = cmpeq, cmpneq, cmplt, cmple, cmpgt, cmpge# */ /* sets invalid fpu flag on QNaN for consistency with packed compare */ static NPY_INLINE int sse2_ordered_cmp_@kind@_@TYPE@(const @type@ a, const @type@ b) { @type@ tmp; @vtype@ v = @vpre@_@VOP@_@vsufs@(@vpre@_load_@vsufs@(&a), @vpre@_load_@vsufs@(&b)); @vpre@_store_@vsufs@(&tmp, v); return sizeof(@type@) == 4 ? (*(npy_uint32 *)&tmp) & 1 : (*(npy_uint64 *)&tmp) & 1; } 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); } LOOP_BLOCKED_END { op[i] = sse2_ordered_cmp_@kind@_@TYPE@(ip1[i], ip2[i]); } } 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]); 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_END { op[i] = sse2_ordered_cmp_@kind@_@TYPE@(ip1[0], ip2[i]); } } 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]); 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_END { op[i] = sse2_ordered_cmp_@kind@_@TYPE@(ip1[i], ip2[0]); } } /**end repeat1**/ static void sse2_sqrt_@TYPE@(@type@ * op, @type@ * ip, const npy_intp n) { /* align output to 16 bytes */ LOOP_BLOCK_ALIGN_VAR(op, @type@, 16) { op[i] = @scalarf@(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@ d = @vpre@_load_@vsuf@(&ip[i]); @vpre@_store_@vsuf@(&op[i], @vpre@_sqrt_@vsuf@(d)); } } else { LOOP_BLOCKED(@type@, 16) { @vtype@ d = @vpre@_loadu_@vsuf@(&ip[i]); @vpre@_store_@vsuf@(&op[i], @vpre@_sqrt_@vsuf@(d)); } } LOOP_BLOCKED_END { op[i] = @scalarf@(ip[i]); } } static void sse2_absolute_@TYPE@(@type@ * op, @type@ * ip, const npy_intp n) { /* * get 0x7FFFFFFF mask (everything but signbit set) * float & ~mask will remove 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; } 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)); } } else { LOOP_BLOCKED(@type@, 16) { @vtype@ a = @vpre@_loadu_@vsuf@(&ip[i]); @vpre@_store_@vsuf@(&op[i], @vpre@_andnot_@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; } } /**begin repeat1 * #kind = maximum, minimum# * #VOP = max, min# * #OP = >=, <=# **/ /* arguments swapped as unary reduce has the swapped compared to unary */ static void sse2_@kind@_@TYPE@(@type@ * ip, @type@ * op, const npy_intp n) { LOOP_BLOCK_ALIGN_VAR(ip, @type@, 16) { *op = (*op @OP@ ip[i] || npy_isnan(*op)) ? *op : ip[i]; } assert(n < (16 / sizeof(@type@)) || npy_is_aligned(&ip[i], 16)); if (i + 2 * 16 / sizeof(@type@) <= n) { /* load the first elements */ @vtype@ c = @vpre@_load_@vsuf@((@type@*)&ip[i]); #ifdef NO_FLOATING_POINT_SUPPORT @vtype@ cnan = @vpre@_cmpneq_@vsuf@(c, c); #else /* minps/minpd will set invalid flag if nan is encountered */ PyUFunc_clearfperr(); #endif i += 16 / sizeof(@type@); LOOP_BLOCKED(@type@, 16) { @vtype@ v = @vpre@_load_@vsuf@((@type@*)&ip[i]); c = @vpre@_@VOP@_@vsuf@(c, v); #ifdef NO_FLOATING_POINT_SUPPORT /* check for nan, breaking the loop makes non nan case slow */ cnan = @vpre@_or_@vsuf@(@vpre@_cmpneq_@vsuf@(v, v), cnan); } if (@vpre@_movemask_@vsuf@(cnan)) { *op = @nan@; return; } #else } #endif { @type@ tmp = sse2_horizontal_@VOP@_@vtype@(c); if (PyUFunc_getfperr() & UFUNC_FPE_INVALID) *op = @nan@; else *op = (*op @OP@ tmp || npy_isnan(*op)) ? *op : tmp; } } LOOP_BLOCKED_END { *op = (*op @OP@ ip[i] || npy_isnan(*op)) ? *op : ip[i]; } } /**end repeat1**/ /**end repeat**/ /* ***************************************************************************** ** BOOL LOOPS ***************************************************************************** */ /**begin repeat * # kind = logical_or, logical_and# * # and = 0, 1# * # op = ||, &&# * # sc = !=, ==# * # vpre = _mm*2# * # vsuf = si128*2# * # vtype = __m128i*2# * # type = npy_bool*2# * # vload = _mm_load_si128*2# * # vloadu = _mm_loadu_si128*2# * # vstore = _mm_store_si128*2# */ /* * convert any bit set to boolean true so vectorized and normal operations are * consistent, should not be required if bool is used correctly everywhere but * you never know */ #if !@and@ static NPY_INLINE @vtype@ byte_to_true(@vtype@ v) { const @vtype@ zero = @vpre@_setzero_@vsuf@(); const @vtype@ truemask = @vpre@_set1_epi8(1 == 1); /* get 0xFF for zeros */ @vtype@ tmp = @vpre@_cmpeq_epi8(v, zero); /* filled with 0xFF/0x00, negate and mask to boolean true */ return @vpre@_andnot_@vsuf@(tmp, truemask); } #endif static void sse2_binary_@kind@_BOOL(npy_bool * op, npy_bool * ip1, npy_bool * ip2, npy_intp n) { LOOP_BLOCK_ALIGN_VAR(op, @type@, 16) op[i] = ip1[i] @op@ ip2[i]; LOOP_BLOCKED(@type@, 16) { @vtype@ a = @vloadu@((@vtype@*)&ip1[i]); @vtype@ b = @vloadu@((@vtype@*)&ip2[i]); #if @and@ const @vtype@ zero = @vpre@_setzero_@vsuf@(); /* get 0xFF for non zeros*/ @vtype@ tmp = @vpre@_cmpeq_epi8(a, zero); /* andnot -> 0x00 for zeros xFF for non zeros, & with ip2 */ tmp = @vpre@_andnot_@vsuf@(tmp, b); #else @vtype@ tmp = @vpre@_or_@vsuf@(a, b); #endif @vstore@((@vtype@*)&op[i], byte_to_true(tmp)); } LOOP_BLOCKED_END { op[i] = (ip1[i] @op@ ip2[i]); } } static void sse2_reduce_@kind@_BOOL(npy_bool * op, npy_bool * ip, const npy_intp n) { const @vtype@ zero = @vpre@_setzero_@vsuf@(); LOOP_BLOCK_ALIGN_VAR(ip, npy_bool, 16) { *op = *op @op@ ip[i]; if (*op @sc@ 0) { return; } } /* unrolled once to replace a slow movmsk with a fast pmaxb */ LOOP_BLOCKED(npy_bool, 32) { @vtype@ v = @vload@((@vtype@*)&ip[i]); @vtype@ v2 = @vload@((@vtype@*)&ip[i + 16]); v = @vpre@_cmpeq_epi8(v, zero); v2 = @vpre@_cmpeq_epi8(v2, zero); #if @and@ if ((@vpre@_movemask_epi8(@vpre@_max_epu8(v, v2)) != 0)) { *op = 0; #else if ((@vpre@_movemask_epi8(@vpre@_min_epu8(v, v2)) != 0xFFFF)) { *op = 1; #endif return; } } LOOP_BLOCKED_END { *op = *op @op@ ip[i]; if (*op @sc@ 0) { return; } } } /**end repeat**/ /**begin repeat * # kind = absolute, logical_not# * # op = !=, ==# * # not = 0, 1# * # vpre = _mm*2# * # vsuf = si128*2# * # vtype = __m128i*2# * # type = npy_bool*2# * # vloadu = _mm_loadu_si128*2# * # vstore = _mm_store_si128*2# */ static void sse2_@kind@_BOOL(@type@ * op, @type@ * ip, const npy_intp n) { LOOP_BLOCK_ALIGN_VAR(op, @type@, 16) op[i] = (ip[i] @op@ 0); LOOP_BLOCKED(@type@, 16) { @vtype@ a = @vloadu@((@vtype@*)&ip[i]); #if @not@ const @vtype@ zero = @vpre@_setzero_@vsuf@(); const @vtype@ truemask = @vpre@_set1_epi8(1 == 1); /* equivalent to byte_to_true but can skip the negation */ a = @vpre@_cmpeq_epi8(a, zero); a = @vpre@_and_@vsuf@(a, truemask); #else /* abs is kind of pointless but maybe its used for byte_to_true */ a = byte_to_true(a); #endif @vstore@((@vtype@*)&op[i], a); } LOOP_BLOCKED_END { op[i] = (ip[i] @op@ 0); } } /**end repeat**/ #endif /* NPY_HAVE_SSE2_INTRINSICS */ #endif numpy-1.8.2/numpy/core/src/umath/umath_tests.c.src0000664000175100017510000002340212370216242023323 0ustar vagrantvagrant00000000000000/* -*- c -*- */ /* ***************************************************************************** ** INCLUDES ** ***************************************************************************** */ #define NPY_NO_DEPRECATED_API NPY_API_VERSION #include "Python.h" #include "numpy/arrayobject.h" #include "numpy/ufuncobject.h" #include "npy_pycompat.h" #include "npy_config.h" /* ***************************************************************************** ** BASICS ** ***************************************************************************** */ #define INIT_OUTER_LOOP_1 \ npy_intp dN = *dimensions++;\ npy_intp N_; \ npy_intp s0 = *steps++; #define INIT_OUTER_LOOP_2 \ INIT_OUTER_LOOP_1 \ npy_intp s1 = *steps++; #define INIT_OUTER_LOOP_3 \ INIT_OUTER_LOOP_2 \ npy_intp s2 = *steps++; #define INIT_OUTER_LOOP_4 \ INIT_OUTER_LOOP_3 \ npy_intp s3 = *steps++; #define BEGIN_OUTER_LOOP_3 \ for (N_ = 0; N_ < dN; N_++, args[0] += s0, args[1] += s1, args[2] += s2) { #define BEGIN_OUTER_LOOP_4 \ for (N_ = 0; N_ < dN; N_++, args[0] += s0, args[1] += s1, args[2] += s2, args[3] += s3) { #define END_OUTER_LOOP } /* ***************************************************************************** ** UFUNC LOOPS ** ***************************************************************************** */ char *inner1d_signature = "(i),(i)->()"; /**begin repeat #TYPE=LONG,DOUBLE# #typ=npy_long, npy_double# */ /* * This implements the function * out[n] = sum_i { in1[n, i] * in2[n, i] }. */ static void @TYPE@_inner1d(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { INIT_OUTER_LOOP_3 npy_intp di = dimensions[0]; npy_intp i; npy_intp is1=steps[0], is2=steps[1]; BEGIN_OUTER_LOOP_3 char *ip1=args[0], *ip2=args[1], *op=args[2]; @typ@ sum = 0; for (i = 0; i < di; i++) { sum += (*(@typ@ *)ip1) * (*(@typ@ *)ip2); ip1 += is1; ip2 += is2; } *(@typ@ *)op = sum; END_OUTER_LOOP } /**end repeat**/ char *innerwt_signature = "(i),(i),(i)->()"; /**begin repeat #TYPE=LONG,DOUBLE# #typ=npy_long, npy_double# */ /* * This implements the function * out[n] = sum_i { in1[n, i] * in2[n, i] * in3[n, i] }. */ static void @TYPE@_innerwt(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { INIT_OUTER_LOOP_4 npy_intp di = dimensions[0]; npy_intp i; npy_intp is1=steps[0], is2=steps[1], is3=steps[2]; BEGIN_OUTER_LOOP_4 char *ip1=args[0], *ip2=args[1], *ip3=args[2], *op=args[3]; @typ@ sum = 0; for (i = 0; i < di; i++) { sum += (*(@typ@ *)ip1) * (*(@typ@ *)ip2) * (*(@typ@ *)ip3); ip1 += is1; ip2 += is2; ip3 += is3; } *(@typ@ *)op = sum; END_OUTER_LOOP } /**end repeat**/ char *matrix_multiply_signature = "(m,n),(n,p)->(m,p)"; /**begin repeat #TYPE=FLOAT,DOUBLE,LONG# #typ=npy_float, npy_double,npy_long# */ /* * This implements the function * out[k, m, p] = sum_n { in1[k, m, n] * in2[k, n, p] }. */ static void @TYPE@_matrix_multiply(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { /* no BLAS is available */ INIT_OUTER_LOOP_3 npy_intp dm = dimensions[0]; npy_intp dn = dimensions[1]; npy_intp dp = dimensions[2]; npy_intp m,n,p; npy_intp is1_m=steps[0], is1_n=steps[1], is2_n=steps[2], is2_p=steps[3], os_m=steps[4], os_p=steps[5]; npy_intp ib1_n = is1_n*dn; npy_intp ib2_n = is2_n*dn; npy_intp ib2_p = is2_p*dp; npy_intp ob_p = os_p *dp; BEGIN_OUTER_LOOP_3 char *ip1=args[0], *ip2=args[1], *op=args[2]; for (m = 0; m < dm; m++) { for (n = 0; n < dn; n++) { @typ@ val1 = (*(@typ@ *)ip1); for (p = 0; p < dp; p++) { if (n == 0) *(@typ@ *)op = 0; *(@typ@ *)op += val1 * (*(@typ@ *)ip2); ip2 += is2_p; op += os_p; } ip2 -= ib2_p; op -= ob_p; ip1 += is1_n; ip2 += is2_n; } ip1 -= ib1_n; ip2 -= ib2_n; ip1 += is1_m; op += os_m; } END_OUTER_LOOP } /**end repeat**/ /* The following lines were generated using a slightly modified version of code_generators/generate_umath.py and adding these lines to defdict: defdict = { 'inner1d' : Ufunc(2, 1, None_, r'''inner on the last dimension and broadcast on the rest \n" " \"(i),(i)->()\" \n''', TD('ld'), ), 'innerwt' : Ufunc(3, 1, None_, r'''inner1d with a weight argument \n" " \"(i),(i),(i)->()\" \n''', TD('ld'), ), } */ static PyUFuncGenericFunction inner1d_functions[] = { LONG_inner1d, DOUBLE_inner1d }; static void * inner1d_data[] = { (void *)NULL, (void *)NULL }; static char inner1d_signatures[] = { NPY_LONG, NPY_LONG, NPY_LONG, NPY_DOUBLE, NPY_DOUBLE, NPY_DOUBLE }; static PyUFuncGenericFunction innerwt_functions[] = { LONG_innerwt, DOUBLE_innerwt }; static void * innerwt_data[] = { (void *)NULL, (void *)NULL }; static char innerwt_signatures[] = { NPY_LONG, NPY_LONG, NPY_LONG, NPY_LONG, NPY_DOUBLE, NPY_DOUBLE, NPY_DOUBLE, NPY_DOUBLE }; static PyUFuncGenericFunction matrix_multiply_functions[] = { LONG_matrix_multiply, FLOAT_matrix_multiply, DOUBLE_matrix_multiply }; static void *matrix_multiply_data[] = { (void *)NULL, (void *)NULL, (void *)NULL }; static char matrix_multiply_signatures[] = { NPY_LONG, NPY_LONG, NPY_LONG, NPY_FLOAT, NPY_FLOAT, NPY_FLOAT, NPY_DOUBLE, NPY_DOUBLE, NPY_DOUBLE }; static void addUfuncs(PyObject *dictionary) { PyObject *f; f = PyUFunc_FromFuncAndDataAndSignature(inner1d_functions, inner1d_data, inner1d_signatures, 2, 2, 1, PyUFunc_None, "inner1d", "inner on the last dimension and broadcast on the rest \n"\ " \"(i),(i)->()\" \n", 0, inner1d_signature); PyDict_SetItemString(dictionary, "inner1d", f); Py_DECREF(f); f = PyUFunc_FromFuncAndDataAndSignature(innerwt_functions, innerwt_data, innerwt_signatures, 2, 3, 1, PyUFunc_None, "innerwt", "inner1d with a weight argument \n"\ " \"(i),(i),(i)->()\" \n", 0, innerwt_signature); PyDict_SetItemString(dictionary, "innerwt", f); Py_DECREF(f); f = PyUFunc_FromFuncAndDataAndSignature(matrix_multiply_functions, matrix_multiply_data, matrix_multiply_signatures, 3, 2, 1, PyUFunc_None, "matrix_multiply", "matrix multiplication on last two dimensions \n"\ " \"(m,n),(n,p)->(m,p)\" \n", 0, matrix_multiply_signature); PyDict_SetItemString(dictionary, "matrix_multiply", f); Py_DECREF(f); } /* End of auto-generated code. */ static PyObject * UMath_Tests_test_signature(PyObject *NPY_UNUSED(dummy), PyObject *args) { int nin, nout; PyObject *signature, *sig_str; PyObject *f; int core_enabled; if (!PyArg_ParseTuple(args, "iiO", &nin, &nout, &signature)) return NULL; if (PyString_Check(signature)) { sig_str = signature; } else if (PyUnicode_Check(signature)) { sig_str = PyUnicode_AsUTF8String(signature); } else { PyErr_SetString(PyExc_ValueError, "signature should be a string"); return NULL; } f = PyUFunc_FromFuncAndDataAndSignature(NULL, NULL, NULL, 0, nin, nout, PyUFunc_None, "no name", "doc:none", 1, PyString_AS_STRING(sig_str)); if (sig_str != signature) { Py_DECREF(sig_str); } if (f == NULL) return NULL; core_enabled = ((PyUFuncObject*)f)->core_enabled; Py_DECREF(f); return Py_BuildValue("i", core_enabled); } static PyMethodDef UMath_TestsMethods[] = { {"test_signature", UMath_Tests_test_signature, METH_VARARGS, "Test signature parsing of ufunc. \n" "Arguments: nin nout signature \n" "If fails, it returns NULL. Otherwise it will returns 0 for scalar ufunc " "and 1 for generalized ufunc. \n", }, {NULL, NULL, 0, NULL} /* Sentinel */ }; #if defined(NPY_PY3K) static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, "umath_tests", NULL, -1, UMath_TestsMethods, NULL, NULL, NULL, NULL }; #endif #if defined(NPY_PY3K) #define RETVAL m PyMODINIT_FUNC PyInit_umath_tests(void) #else #define RETVAL PyMODINIT_FUNC initumath_tests(void) #endif { PyObject *m; PyObject *d; PyObject *version; #if defined(NPY_PY3K) m = PyModule_Create(&moduledef); #else m = Py_InitModule("umath_tests", UMath_TestsMethods); #endif if (m == NULL) return RETVAL; import_array(); import_ufunc(); d = PyModule_GetDict(m); version = PyString_FromString("0.1"); PyDict_SetItemString(d, "__version__", version); Py_DECREF(version); /* Load the ufunc operators into the module's namespace */ addUfuncs(d); if (PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError, "cannot load umath_tests module."); } return RETVAL; } numpy-1.8.2/numpy/core/src/umath/umathmodule.c0000664000175100017510000003542412370216243022531 0ustar vagrantvagrant00000000000000/* -*- c -*- */ /* * vim:syntax=c */ /* ***************************************************************************** ** INCLUDES ** ***************************************************************************** */ /* * _UMATHMODULE IS needed in __ufunc_api.h, included from numpy/ufuncobject.h. * This is a mess and it would be nice to fix it. It has nothing to do with * __ufunc_api.c */ #define _UMATHMODULE #define NPY_NO_DEPRECATED_API NPY_API_VERSION #include "Python.h" #include "npy_config.h" #ifdef ENABLE_SEPARATE_COMPILATION #define PY_ARRAY_UNIQUE_SYMBOL _npy_umathmodule_ARRAY_API #endif #include "numpy/arrayobject.h" #include "numpy/ufuncobject.h" #include "abstract.h" #include "numpy/npy_math.h" /* ***************************************************************************** ** INCLUDE GENERATED CODE ** ***************************************************************************** */ #include "funcs.inc" #include "loops.h" #include "ufunc_object.h" #include "ufunc_type_resolution.h" #include "__umath_generated.c" #include "__ufunc_api.c" static PyUFuncGenericFunction pyfunc_functions[] = {PyUFunc_On_Om}; static int object_ufunc_type_resolver(PyUFuncObject *ufunc, NPY_CASTING casting, PyArrayObject **operands, PyObject *type_tup, 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) { return -1; } for (i = 0; i < nop; ++i) { Py_INCREF(obj_dtype); out_dtypes[i] = obj_dtype; } return 0; } static int object_ufunc_loop_selector(PyUFuncObject *ufunc, PyArray_Descr **NPY_UNUSED(dtypes), PyUFuncGenericFunction *out_innerloop, void **out_innerloopdata, int *out_needs_api) { *out_innerloop = ufunc->functions[0]; *out_innerloopdata = ufunc->data[0]; *out_needs_api = 1; return 0; } static PyObject * ufunc_frompyfunc(PyObject *NPY_UNUSED(dummy), PyObject *args, PyObject *NPY_UNUSED(kwds)) { /* Keywords are ignored for now */ PyObject *function, *pyname = NULL; int nin, nout, i; PyUFunc_PyFuncData *fdata; PyUFuncObject *self; char *fname, *str; Py_ssize_t fname_len = -1; int offset[2]; if (!PyArg_ParseTuple(args, "Oii", &function, &nin, &nout)) { return NULL; } if (!PyCallable_Check(function)) { PyErr_SetString(PyExc_TypeError, "function must be callable"); return NULL; } self = PyArray_malloc(sizeof(PyUFuncObject)); if (self == NULL) { return NULL; } PyObject_Init((PyObject *)self, &PyUFunc_Type); self->userloops = NULL; self->nin = nin; self->nout = nout; self->nargs = nin + nout; self->identity = PyUFunc_None; self->functions = pyfunc_functions; self->ntypes = 1; self->check_return = 0; /* generalized ufunc */ self->core_enabled = 0; self->core_num_dim_ix = 0; self->core_num_dims = NULL; self->core_dim_ixs = NULL; self->core_offsets = NULL; self->core_signature = NULL; self->op_flags = PyArray_malloc(sizeof(npy_uint32)*self->nargs); if (self->op_flags == NULL) { return PyErr_NoMemory(); } memset(self->op_flags, 0, sizeof(npy_uint32)*self->nargs); self->iter_flags = 0; self->type_resolver = &object_ufunc_type_resolver; self->legacy_inner_loop_selector = &object_ufunc_loop_selector; pyname = PyObject_GetAttrString(function, "__name__"); if (pyname) { (void) PyString_AsStringAndSize(pyname, &fname, &fname_len); } if (PyErr_Occurred()) { fname = "?"; fname_len = 1; PyErr_Clear(); } /* * self->ptr holds a pointer for enough memory for * self->data[0] (fdata) * self->data * self->name * self->types * * To be safest, all of these need their memory aligned on void * pointers * Therefore, we may need to allocate extra space. */ offset[0] = sizeof(PyUFunc_PyFuncData); i = (sizeof(PyUFunc_PyFuncData) % sizeof(void *)); if (i) { offset[0] += (sizeof(void *) - i); } offset[1] = self->nargs; i = (self->nargs % sizeof(void *)); if (i) { offset[1] += (sizeof(void *)-i); } self->ptr = PyArray_malloc(offset[0] + offset[1] + sizeof(void *) + (fname_len + 14)); if (self->ptr == NULL) { Py_XDECREF(pyname); return PyErr_NoMemory(); } Py_INCREF(function); self->obj = function; fdata = (PyUFunc_PyFuncData *)(self->ptr); fdata->nin = nin; fdata->nout = nout; fdata->callable = function; self->data = (void **)(((char *)self->ptr) + offset[0]); self->data[0] = (void *)fdata; self->types = (char *)self->data + sizeof(void *); for (i = 0; i < self->nargs; i++) { self->types[i] = NPY_OBJECT; } str = self->types + offset[1]; memcpy(str, fname, fname_len); memcpy(str+fname_len, " (vectorized)", 14); self->name = str; Py_XDECREF(pyname); /* Do a better job someday */ self->doc = "dynamic ufunc based on a python function"; return (PyObject *)self; } /* ***************************************************************************** ** SETUP UFUNCS ** ***************************************************************************** */ /* Less automated additions to the ufuncs */ static PyUFuncGenericFunction frexp_functions[] = { #ifdef HAVE_FREXPF HALF_frexp, FLOAT_frexp, #endif DOUBLE_frexp #ifdef HAVE_FREXPL ,LONGDOUBLE_frexp #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, NPY_FLOAT, NPY_FLOAT, NPY_INT, #endif NPY_DOUBLE, NPY_DOUBLE, NPY_INT #ifdef HAVE_FREXPL ,NPY_LONGDOUBLE, NPY_LONGDOUBLE, NPY_INT #endif }; #if NPY_SIZEOF_LONG == NPY_SIZEOF_INT #define LDEXP_LONG(typ) typ##_ldexp #else #define LDEXP_LONG(typ) typ##_ldexp_long #endif static PyUFuncGenericFunction ldexp_functions[] = { #ifdef HAVE_LDEXPF HALF_ldexp, FLOAT_ldexp, LDEXP_LONG(HALF), LDEXP_LONG(FLOAT), #endif DOUBLE_ldexp, LDEXP_LONG(DOUBLE) #ifdef HAVE_LDEXPL , LONGDOUBLE_ldexp, LDEXP_LONG(LONGDOUBLE) #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, NPY_FLOAT, NPY_INT, NPY_FLOAT, NPY_HALF, NPY_LONG, NPY_HALF, NPY_FLOAT, NPY_LONG, NPY_FLOAT, #endif NPY_DOUBLE, NPY_INT, NPY_DOUBLE, NPY_DOUBLE, NPY_LONG, NPY_DOUBLE #ifdef HAVE_LDEXPL ,NPY_LONGDOUBLE, NPY_INT, NPY_LONGDOUBLE ,NPY_LONGDOUBLE, NPY_LONG, NPY_LONGDOUBLE #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, frexp_signatures, num, 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", lddoc, 0); PyDict_SetItemString(dictionary, "ldexp", f); Py_DECREF(f); #if defined(NPY_PY3K) f = PyDict_GetItemString(dictionary, "true_divide"); PyDict_SetItemString(dictionary, "divide", f); #endif return; } /* Setup the umath module */ /* Remove for time being, it is declared in __ufunc_api.h */ /*static PyTypeObject PyUFunc_Type;*/ static struct PyMethodDef methods[] = { {"frompyfunc", (PyCFunction) ufunc_frompyfunc, METH_VARARGS | METH_KEYWORDS, NULL}, {"seterrobj", (PyCFunction) ufunc_seterr, METH_VARARGS, NULL}, {"geterrobj", (PyCFunction) ufunc_geterr, METH_VARARGS, NULL}, {NULL, NULL, 0, NULL} /* sentinel */ }; #if defined(NPY_PY3K) static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, "umath", NULL, -1, methods, NULL, NULL, NULL, NULL }; #endif #include #if defined(NPY_PY3K) #define RETVAL m PyMODINIT_FUNC PyInit_umath(void) #else #define RETVAL PyMODINIT_FUNC initumath(void) #endif { PyObject *m, *d, *s, *s2, *c_api; int UFUNC_FLOATING_POINT_SUPPORT = 1; #ifdef NO_UFUNC_FLOATING_POINT_SUPPORT UFUNC_FLOATING_POINT_SUPPORT = 0; #endif /* Create the module and add the functions */ #if defined(NPY_PY3K) m = PyModule_Create(&moduledef); #else m = Py_InitModule("umath", methods); #endif if (!m) { return RETVAL; } /* Import the array */ if (_import_array() < 0) { if (!PyErr_Occurred()) { PyErr_SetString(PyExc_ImportError, "umath failed: Could not import array core."); } return RETVAL; } /* Initialize the types */ if (PyType_Ready(&PyUFunc_Type) < 0) return RETVAL; /* Add some symbolic constants to the module */ d = PyModule_GetDict(m); c_api = NpyCapsule_FromVoidPtr((void *)PyUFunc_API, NULL); if (PyErr_Occurred()) { goto err; } PyDict_SetItemString(d, "_UFUNC_API", c_api); Py_DECREF(c_api); if (PyErr_Occurred()) { goto err; } s = PyString_FromString("0.4.0"); PyDict_SetItemString(d, "__version__", s); Py_DECREF(s); /* Load the ufunc operators into the array module's namespace */ InitOperators(d); InitOtherOperators(d); PyDict_SetItemString(d, "pi", s = PyFloat_FromDouble(NPY_PI)); Py_DECREF(s); PyDict_SetItemString(d, "e", s = PyFloat_FromDouble(NPY_E)); Py_DECREF(s); PyDict_SetItemString(d, "euler_gamma", s = PyFloat_FromDouble(NPY_EULER)); Py_DECREF(s); #define ADDCONST(str) PyModule_AddIntConstant(m, #str, UFUNC_##str) #define ADDSCONST(str) PyModule_AddStringConstant(m, "UFUNC_" #str, UFUNC_##str) ADDCONST(ERR_IGNORE); ADDCONST(ERR_WARN); ADDCONST(ERR_CALL); ADDCONST(ERR_RAISE); ADDCONST(ERR_PRINT); ADDCONST(ERR_LOG); ADDCONST(ERR_DEFAULT); ADDCONST(ERR_DEFAULT2); ADDCONST(SHIFT_DIVIDEBYZERO); ADDCONST(SHIFT_OVERFLOW); ADDCONST(SHIFT_UNDERFLOW); ADDCONST(SHIFT_INVALID); ADDCONST(FPE_DIVIDEBYZERO); ADDCONST(FPE_OVERFLOW); ADDCONST(FPE_UNDERFLOW); ADDCONST(FPE_INVALID); ADDCONST(FLOATING_POINT_SUPPORT); ADDSCONST(PYVALS_NAME); #undef ADDCONST #undef ADDSCONST PyModule_AddIntConstant(m, "UFUNC_BUFSIZE_DEFAULT", (long)NPY_BUFSIZE); PyModule_AddObject(m, "PINF", PyFloat_FromDouble(NPY_INFINITY)); PyModule_AddObject(m, "NINF", PyFloat_FromDouble(-NPY_INFINITY)); PyModule_AddObject(m, "PZERO", PyFloat_FromDouble(NPY_PZERO)); PyModule_AddObject(m, "NZERO", PyFloat_FromDouble(NPY_NZERO)); PyModule_AddObject(m, "NAN", PyFloat_FromDouble(NPY_NAN)); s = PyDict_GetItemString(d, "conjugate"); s2 = PyDict_GetItemString(d, "remainder"); /* Setup the array object's numerical structures with appropriate ufuncs in d*/ PyArray_SetNumericOps(d); PyDict_SetItemString(d, "conj", s); PyDict_SetItemString(d, "mod", s2); return RETVAL; err: /* Check for errors */ if (!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError, "cannot load umath module."); } return RETVAL; } numpy-1.8.2/numpy/core/src/umath/test_rational.c.src0000664000175100017510000012113712370216243023640 0ustar vagrantvagrant00000000000000/* Fixed size rational numbers exposed to Python */ #define NPY_NO_DEPRECATED_API NPY_API_VERSION #include #include #include #include #include #include /* Relevant arithmetic exceptions */ /* Uncomment the following line to work around a bug in numpy */ /* #define ACQUIRE_GIL */ static void set_overflow(void) { #ifdef ACQUIRE_GIL /* Need to grab the GIL to dodge a bug in numpy */ PyGILState_STATE state = PyGILState_Ensure(); #endif if (!PyErr_Occurred()) { PyErr_SetString(PyExc_OverflowError, "overflow in rational arithmetic"); } #ifdef ACQUIRE_GIL PyGILState_Release(state); #endif } static void set_zero_divide(void) { #ifdef ACQUIRE_GIL /* Need to grab the GIL to dodge a bug in numpy */ PyGILState_STATE state = PyGILState_Ensure(); #endif if (!PyErr_Occurred()) { PyErr_SetString(PyExc_ZeroDivisionError, "zero divide in rational arithmetic"); } #ifdef ACQUIRE_GIL PyGILState_Release(state); #endif } /* Integer arithmetic utilities */ static NPY_INLINE npy_int32 safe_neg(npy_int32 x) { if (x==(npy_int32)1<<31) { set_overflow(); } return -x; } static NPY_INLINE npy_int32 safe_abs32(npy_int32 x) { npy_int32 nx; if (x>=0) { return x; } nx = -x; if (nx<0) { set_overflow(); } return nx; } static NPY_INLINE npy_int64 safe_abs64(npy_int64 x) { npy_int64 nx; if (x>=0) { return x; } nx = -x; if (nx<0) { set_overflow(); } return nx; } static NPY_INLINE npy_int64 gcd(npy_int64 x, npy_int64 y) { x = safe_abs64(x); y = safe_abs64(y); if (x < y) { npy_int64 t = x; x = y; y = t; } while (y) { npy_int64 t; x = x%y; t = x; x = y; y = t; } return x; } static NPY_INLINE npy_int64 lcm(npy_int64 x, npy_int64 y) { npy_int64 lcm; if (!x || !y) { return 0; } x /= gcd(x,y); lcm = x*y; if (lcm/y!=x) { set_overflow(); } return safe_abs64(lcm); } /* Fixed precision rational numbers */ typedef struct { /* numerator */ npy_int32 n; /* * denominator minus one: numpy.zeros() uses memset(0) for non-object * types, so need to ensure that rational(0) has all zero bytes */ npy_int32 dmm; } rational; static NPY_INLINE rational make_rational_int(npy_int64 n) { rational r = {(npy_int32)n,0}; if (r.n != n) { set_overflow(); } return r; } static rational make_rational_slow(npy_int64 n_, npy_int64 d_) { rational r = {0}; if (!d_) { set_zero_divide(); } else { npy_int64 g = gcd(n_,d_); npy_int32 d; n_ /= g; d_ /= g; r.n = (npy_int32)n_; d = (npy_int32)d_; if (r.n!=n_ || d!=d_) { set_overflow(); } else { if (d <= 0) { d = -d; r.n = safe_neg(r.n); } r.dmm = d-1; } } return r; } static NPY_INLINE npy_int32 d(rational r) { return r.dmm+1; } /* Assumes d_ > 0 */ static rational make_rational_fast(npy_int64 n_, npy_int64 d_) { npy_int64 g = gcd(n_,d_); rational r; n_ /= g; d_ /= g; r.n = (npy_int32)n_; r.dmm = (npy_int32)(d_-1); if (r.n!=n_ || r.dmm+1!=d_) { set_overflow(); } return r; } static NPY_INLINE rational rational_negative(rational r) { rational x; x.n = safe_neg(r.n); x.dmm = r.dmm; return x; } static NPY_INLINE rational rational_add(rational x, rational y) { /* * Note that the numerator computation can never overflow int128_t, * since each term is strictly under 2**128/4 (since d > 0). */ return make_rational_fast((npy_int64)x.n*d(y)+(npy_int64)d(x)*y.n, (npy_int64)d(x)*d(y)); } static NPY_INLINE rational rational_subtract(rational x, rational y) { /* We're safe from overflow as with + */ return make_rational_fast((npy_int64)x.n*d(y)-(npy_int64)d(x)*y.n, (npy_int64)d(x)*d(y)); } static NPY_INLINE rational rational_multiply(rational x, rational y) { /* We're safe from overflow as with + */ return make_rational_fast((npy_int64)x.n*y.n,(npy_int64)d(x)*d(y)); } static NPY_INLINE rational rational_divide(rational x, rational y) { return make_rational_slow((npy_int64)x.n*d(y),(npy_int64)d(x)*y.n); } static NPY_INLINE npy_int64 rational_floor(rational x) { /* Always round down */ if (x.n>=0) { return x.n/d(x); } /* * This can be done without casting up to 64 bits, but it requires * working out all the sign cases */ return -((-(npy_int64)x.n+d(x)-1)/d(x)); } static NPY_INLINE npy_int64 rational_ceil(rational x) { return -rational_floor(rational_negative(x)); } static NPY_INLINE rational rational_remainder(rational x, rational y) { return rational_subtract(x, rational_multiply(y,make_rational_int( rational_floor(rational_divide(x,y))))); } static NPY_INLINE rational rational_abs(rational x) { rational y; y.n = safe_abs32(x.n); y.dmm = x.dmm; return y; } static NPY_INLINE npy_int64 rational_rint(rational x) { /* * Round towards nearest integer, moving exact half integers towards * zero */ npy_int32 d_ = d(x); return (2*(npy_int64)x.n+(x.n<0?-d_:d_))/(2*(npy_int64)d_); } static NPY_INLINE int rational_sign(rational x) { return x.n<0?-1:x.n==0?0:1; } static NPY_INLINE rational rational_inverse(rational x) { rational y = {0}; if (!x.n) { set_zero_divide(); } else { npy_int32 d_; y.n = d(x); d_ = x.n; if (d_ <= 0) { d_ = safe_neg(d_); y.n = -y.n; } y.dmm = d_-1; } return y; } static NPY_INLINE int rational_eq(rational x, rational y) { /* * Since we enforce d > 0, and store fractions in reduced form, * equality is easy. */ return x.n==y.n && x.dmm==y.dmm; } static NPY_INLINE int rational_ne(rational x, rational y) { return !rational_eq(x,y); } static NPY_INLINE int rational_lt(rational x, rational y) { return (npy_int64)x.n*d(y) < (npy_int64)y.n*d(x); } static NPY_INLINE int rational_gt(rational x, rational y) { return rational_lt(y,x); } static NPY_INLINE int rational_le(rational x, rational y) { return !rational_lt(y,x); } static NPY_INLINE int rational_ge(rational x, rational y) { return !rational_lt(x,y); } static NPY_INLINE npy_int32 rational_int(rational x) { return x.n/d(x); } static NPY_INLINE double rational_double(rational x) { return (double)x.n/d(x); } static NPY_INLINE int rational_nonzero(rational x) { return x.n!=0; } static int scan_rational(const char** s, rational* x) { long n,d; int offset; const char* ss; if (sscanf(*s,"%ld%n",&n,&offset)<=0) { return 0; } ss = *s+offset; if (*ss!='/') { *s = ss; *x = make_rational_int(n); return 1; } ss++; if (sscanf(ss,"%ld%n",&d,&offset)<=0 || d<=0) { return 0; } *s = ss+offset; *x = make_rational_slow(n,d); return 1; } /* Expose rational to Python as a numpy scalar */ typedef struct { PyObject_HEAD rational r; } PyRational; static PyTypeObject PyRational_Type; static NPY_INLINE int PyRational_Check(PyObject* object) { return PyObject_IsInstance(object,(PyObject*)&PyRational_Type); } static PyObject* PyRational_FromRational(rational x) { PyRational* p = (PyRational*)PyRational_Type.tp_alloc(&PyRational_Type,0); if (p) { p->r = x; } return (PyObject*)p; } static PyObject* pyrational_new(PyTypeObject* type, PyObject* args, PyObject* kwds) { Py_ssize_t size; PyObject* x[2]; long n[2]={0,1}; int i; rational r; if (kwds && PyDict_Size(kwds)) { PyErr_SetString(PyExc_TypeError, "constructor takes no keyword arguments"); return 0; } size = PyTuple_GET_SIZE(args); if (size>2) { PyErr_SetString(PyExc_TypeError, "expected rational or numerator and optional denominator"); return 0; } x[0] = PyTuple_GET_ITEM(args,0); x[1] = PyTuple_GET_ITEM(args,1); if (size==1) { if (PyRational_Check(x[0])) { Py_INCREF(x[0]); return x[0]; } else if (PyString_Check(x[0])) { const char* s = PyString_AS_STRING(x[0]); rational x; if (scan_rational(&s,&x)) { const char* p; for (p = s; *p; p++) { if (!isspace(*p)) { goto bad; } } return PyRational_FromRational(x); } bad: PyErr_Format(PyExc_ValueError, "invalid rational literal '%s'",s); return 0; } } for (i=0;iob_type->tp_name); } return 0; } /* Check that we had an exact integer */ y = PyInt_FromLong(n[i]); if (!y) { return 0; } eq = PyObject_RichCompareBool(x[i],y,Py_EQ); Py_DECREF(y); if (eq<0) { return 0; } if (!eq) { PyErr_Format(PyExc_TypeError, "expected integer %s, got %s", (i ? "denominator" : "numerator"), x[i]->ob_type->tp_name); return 0; } } r = make_rational_slow(n[0],n[1]); if (PyErr_Occurred()) { return 0; } return PyRational_FromRational(r); } /* * Returns Py_NotImplemented on most conversion failures, or raises an * overflow error for too long ints */ #define AS_RATIONAL(dst,object) \ { \ dst.n = 0; \ if (PyRational_Check(object)) { \ dst = ((PyRational*)object)->r; \ } \ else { \ PyObject* y_; \ int eq_; \ long n_ = PyInt_AsLong(object); \ if (n_==-1 && PyErr_Occurred()) { \ if (PyErr_ExceptionMatches(PyExc_TypeError)) { \ PyErr_Clear(); \ Py_INCREF(Py_NotImplemented); \ return Py_NotImplemented; \ } \ return 0; \ } \ y_ = PyInt_FromLong(n_); \ if (!y_) { \ return 0; \ } \ eq_ = PyObject_RichCompareBool(object,y_,Py_EQ); \ Py_DECREF(y_); \ if (eq_<0) { \ return 0; \ } \ if (!eq_) { \ Py_INCREF(Py_NotImplemented); \ return Py_NotImplemented; \ } \ dst = make_rational_int(n_); \ } \ } static PyObject* pyrational_richcompare(PyObject* a, PyObject* b, int op) { rational x, y; int result = 0; AS_RATIONAL(x,a); AS_RATIONAL(y,b); #define OP(py,op) case py: result = rational_##op(x,y); break; switch (op) { OP(Py_LT,lt) OP(Py_LE,le) OP(Py_EQ,eq) OP(Py_NE,ne) OP(Py_GT,gt) OP(Py_GE,ge) }; #undef OP return PyBool_FromLong(result); } static PyObject* pyrational_repr(PyObject* self) { rational x = ((PyRational*)self)->r; if (d(x)!=1) { return PyUString_FromFormat( "rational(%ld,%ld)",(long)x.n,(long)d(x)); } else { return PyUString_FromFormat( "rational(%ld)",(long)x.n); } } static PyObject* pyrational_str(PyObject* self) { rational x = ((PyRational*)self)->r; if (d(x)!=1) { return PyString_FromFormat( "%ld/%ld",(long)x.n,(long)d(x)); } else { return PyString_FromFormat( "%ld",(long)x.n); } } static long pyrational_hash(PyObject* self) { rational x = ((PyRational*)self)->r; /* Use a fairly weak hash as Python expects */ long h = 131071*x.n+524287*x.dmm; /* Never return the special error value -1 */ return h==-1?2:h; } #define RATIONAL_BINOP_2(name,exp) \ static PyObject* \ pyrational_##name(PyObject* a, PyObject* b) { \ rational x, y, z; \ AS_RATIONAL(x,a); \ AS_RATIONAL(y,b); \ z = exp; \ if (PyErr_Occurred()) { \ return 0; \ } \ return PyRational_FromRational(z); \ } #define RATIONAL_BINOP(name) RATIONAL_BINOP_2(name,rational_##name(x,y)) RATIONAL_BINOP(add) RATIONAL_BINOP(subtract) RATIONAL_BINOP(multiply) RATIONAL_BINOP(divide) RATIONAL_BINOP(remainder) RATIONAL_BINOP_2(floor_divide, make_rational_int(rational_floor(rational_divide(x,y)))) #define RATIONAL_UNOP(name,type,exp,convert) \ static PyObject* \ pyrational_##name(PyObject* self) { \ rational x = ((PyRational*)self)->r; \ type y = exp; \ if (PyErr_Occurred()) { \ return 0; \ } \ return convert(y); \ } RATIONAL_UNOP(negative,rational,rational_negative(x),PyRational_FromRational) RATIONAL_UNOP(absolute,rational,rational_abs(x),PyRational_FromRational) RATIONAL_UNOP(int,long,rational_int(x),PyInt_FromLong) RATIONAL_UNOP(float,double,rational_double(x),PyFloat_FromDouble) static PyObject* pyrational_positive(PyObject* self) { Py_INCREF(self); return self; } static int pyrational_nonzero(PyObject* self) { rational x = ((PyRational*)self)->r; return rational_nonzero(x); } static PyNumberMethods pyrational_as_number = { pyrational_add, /* nb_add */ pyrational_subtract, /* nb_subtract */ pyrational_multiply, /* nb_multiply */ #if PY_MAJOR_VERSION < 3 pyrational_divide, /* nb_divide */ #endif pyrational_remainder, /* nb_remainder */ 0, /* nb_divmod */ 0, /* nb_power */ pyrational_negative, /* nb_negative */ pyrational_positive, /* nb_positive */ pyrational_absolute, /* nb_absolute */ pyrational_nonzero, /* 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 pyrational_int, /* nb_int */ #if PY_MAJOR_VERSION < 3 pyrational_int, /* nb_long */ #else 0, /* reserved */ #endif pyrational_float, /* nb_float */ #if PY_MAJOR_VERSION < 3 0, /* nb_oct */ 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 */ pyrational_floor_divide, /* nb_floor_divide */ pyrational_divide, /* nb_true_divide */ 0, /* nb_inplace_floor_divide */ 0, /* nb_inplace_true_divide */ 0, /* nb_index */ }; static PyObject* pyrational_n(PyObject* self, void* closure) { return PyInt_FromLong(((PyRational*)self)->r.n); } static PyObject* pyrational_d(PyObject* self, void* closure) { return PyInt_FromLong(d(((PyRational*)self)->r)); } static PyGetSetDef pyrational_getset[] = { {(char*)"n",pyrational_n,0,(char*)"numerator",0}, {(char*)"d",pyrational_d,0,(char*)"denominator",0}, {0} /* sentinel */ }; static PyTypeObject PyRational_Type = { #if defined(NPY_PY3K) PyVarObject_HEAD_INIT(NULL, 0) #else PyObject_HEAD_INIT(NULL) 0, /* ob_size */ #endif "rational", /* tp_name */ sizeof(PyRational), /* tp_basicsize */ 0, /* tp_itemsize */ 0, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ #if defined(NPY_PY3K) 0, /* tp_reserved */ #else 0, /* tp_compare */ #endif pyrational_repr, /* tp_repr */ &pyrational_as_number, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ pyrational_hash, /* tp_hash */ 0, /* tp_call */ pyrational_str, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ "Fixed precision rational numbers", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ pyrational_richcompare, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ 0, /* tp_methods */ 0, /* tp_members */ pyrational_getset, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ pyrational_new, /* 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 */ 0, /* tp_version_tag */ }; /* Numpy support */ static PyObject* npyrational_getitem(void* data, void* arr) { rational r; memcpy(&r,data,sizeof(rational)); return PyRational_FromRational(r); } static int npyrational_setitem(PyObject* item, void* data, void* arr) { rational r; if (PyRational_Check(item)) { r = ((PyRational*)item)->r; } else { long n = PyInt_AsLong(item); PyObject* y; int eq; if (n==-1 && PyErr_Occurred()) { return -1; } y = PyInt_FromLong(n); if (!y) { return -1; } eq = PyObject_RichCompareBool(item,y,Py_EQ); Py_DECREF(y); if (eq<0) { return -1; } if (!eq) { PyErr_Format(PyExc_TypeError, "expected rational, got %s", item->ob_type->tp_name); return -1; } r = make_rational_int(n); } memcpy(data,&r,sizeof(rational)); return 0; } static NPY_INLINE void byteswap(npy_int32* x) { char* p = (char*)x; size_t i; for (i = 0; i < sizeof(*x)/2; i++) { size_t j = sizeof(*x)-1-i; char t = p[i]; p[i] = p[j]; p[j] = t; } } static void npyrational_copyswapn(void* dst_, npy_intp dstride, void* src_, npy_intp sstride, npy_intp n, int swap, void* arr) { char *dst = (char*)dst_, *src = (char*)src_; npy_intp i; if (!src) { return; } if (swap) { for (i = 0; i < n; i++) { rational* r = (rational*)(dst+dstride*i); memcpy(r,src+sstride*i,sizeof(rational)); byteswap(&r->n); byteswap(&r->dmm); } } else if (dstride == sizeof(rational) && sstride == sizeof(rational)) { memcpy(dst, src, n*sizeof(rational)); } else { for (i = 0; i < n; i++) { memcpy(dst + dstride*i, src + sstride*i, sizeof(rational)); } } } static void npyrational_copyswap(void* dst, void* src, int swap, void* arr) { rational* r; if (!src) { return; } r = (rational*)dst; memcpy(r,src,sizeof(rational)); if (swap) { byteswap(&r->n); byteswap(&r->dmm); } } static int npyrational_compare(const void* d0, const void* d1, void* arr) { rational x = *(rational*)d0, y = *(rational*)d1; return rational_lt(x,y)?-1:rational_eq(x,y)?0:1; } #define FIND_EXTREME(name,op) \ static int \ npyrational_##name(void* data_, npy_intp n, \ npy_intp* max_ind, void* arr) { \ const rational* data; \ npy_intp best_i; \ rational best_r; \ npy_intp i; \ if (!n) { \ return 0; \ } \ 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; \ best_r = data[i]; \ } \ } \ *max_ind = best_i; \ return 0; \ } FIND_EXTREME(argmin,lt) FIND_EXTREME(argmax,gt) static void npyrational_dot(void* ip0_, npy_intp is0, void* ip1_, npy_intp is1, void* op, npy_intp n, void* arr) { rational r = {0}; const char *ip0 = (char*)ip0_, *ip1 = (char*)ip1_; npy_intp i; for (i = 0; i < n; i++) { r = rational_add(r,rational_multiply(*(rational*)ip0,*(rational*)ip1)); ip0 += is0; ip1 += is1; } *(rational*)op = r; } static npy_bool npyrational_nonzero(void* data, void* arr) { rational r; memcpy(&r,data,sizeof(r)); return rational_nonzero(r)?NPY_TRUE:NPY_FALSE; } static int npyrational_fill(void* data_, npy_intp length, void* arr) { rational* data = (rational*)data_; rational delta = rational_subtract(data[1],data[0]); rational r = data[1]; npy_intp i; for (i = 2; i < length; i++) { r = rational_add(r,delta); data[i] = r; } return 0; } static int npyrational_fillwithscalar(void* buffer_, npy_intp length, void* value, void* arr) { rational r = *(rational*)value; rational* buffer = (rational*)buffer_; npy_intp i; for (i = 0; i < length; i++) { buffer[i] = r; } return 0; } static PyArray_ArrFuncs npyrational_arrfuncs; typedef struct { char c; rational r; } align_test; PyArray_Descr npyrational_descr = { PyObject_HEAD_INIT(0) &PyRational_Type, /* typeobj */ 'V', /* kind */ 'r', /* type */ '=', /* byteorder */ /* * For now, we need NPY_NEEDS_PYAPI in order to make numpy detect our * exceptions. This isn't technically necessary, * since we're careful about thread safety, and hopefully future * versions of numpy will recognize that. */ NPY_NEEDS_PYAPI | NPY_USE_GETITEM | NPY_USE_SETITEM, /* hasobject */ 0, /* type_num */ sizeof(rational), /* elsize */ offsetof(align_test,r), /* alignment */ 0, /* subarray */ 0, /* fields */ 0, /* names */ &npyrational_arrfuncs, /* f */ }; #define DEFINE_CAST(From,To,statement) \ static void \ npycast_##From##_##To(void* from_, void* to_, npy_intp n, \ void* fromarr, void* toarr) { \ const From* from = (From*)from_; \ To* to = (To*)to_; \ npy_intp i; \ for (i = 0; i < n; i++) { \ From x = from[i]; \ statement \ to[i] = y; \ } \ } #define DEFINE_INT_CAST(bits) \ DEFINE_CAST(npy_int##bits,rational,rational y = make_rational_int(x);) \ DEFINE_CAST(rational,npy_int##bits,npy_int32 z = rational_int(x); \ npy_int##bits y = z; if (y != z) set_overflow();) DEFINE_INT_CAST(8) DEFINE_INT_CAST(16) DEFINE_INT_CAST(32) DEFINE_INT_CAST(64) DEFINE_CAST(rational,float,double y = rational_double(x);) DEFINE_CAST(rational,double,double y = rational_double(x);) DEFINE_CAST(npy_bool,rational,rational y = make_rational_int(x);) DEFINE_CAST(rational,npy_bool,npy_bool y = rational_nonzero(x);) #define BINARY_UFUNC(name,intype0,intype1,outtype,exp) \ void name(char** args, npy_intp* dimensions, \ npy_intp* steps, void* data) { \ npy_intp is0 = steps[0], is1 = steps[1], \ os = steps[2], n = *dimensions; \ char *i0 = args[0], *i1 = args[1], *o = args[2]; \ int k; \ for (k = 0; k < n; k++) { \ intype0 x = *(intype0*)i0; \ intype1 y = *(intype1*)i1; \ *(outtype*)o = exp; \ i0 += is0; i1 += is1; o += os; \ } \ } #define RATIONAL_BINARY_UFUNC(name,type,exp) \ BINARY_UFUNC(rational_ufunc_##name,rational,rational,type,exp) RATIONAL_BINARY_UFUNC(add,rational,rational_add(x,y)) RATIONAL_BINARY_UFUNC(subtract,rational,rational_subtract(x,y)) RATIONAL_BINARY_UFUNC(multiply,rational,rational_multiply(x,y)) RATIONAL_BINARY_UFUNC(divide,rational,rational_divide(x,y)) RATIONAL_BINARY_UFUNC(remainder,rational,rational_remainder(x,y)) RATIONAL_BINARY_UFUNC(floor_divide,rational, make_rational_int(rational_floor(rational_divide(x,y)))) PyUFuncGenericFunction rational_ufunc_true_divide = rational_ufunc_divide; RATIONAL_BINARY_UFUNC(minimum,rational,rational_lt(x,y)?x:y) RATIONAL_BINARY_UFUNC(maximum,rational,rational_lt(x,y)?y:x) RATIONAL_BINARY_UFUNC(equal,npy_bool,rational_eq(x,y)) RATIONAL_BINARY_UFUNC(not_equal,npy_bool,rational_ne(x,y)) RATIONAL_BINARY_UFUNC(less,npy_bool,rational_lt(x,y)) RATIONAL_BINARY_UFUNC(greater,npy_bool,rational_gt(x,y)) RATIONAL_BINARY_UFUNC(less_equal,npy_bool,rational_le(x,y)) RATIONAL_BINARY_UFUNC(greater_equal,npy_bool,rational_ge(x,y)) BINARY_UFUNC(gcd_ufunc,npy_int64,npy_int64,npy_int64,gcd(x,y)) BINARY_UFUNC(lcm_ufunc,npy_int64,npy_int64,npy_int64,lcm(x,y)) #define UNARY_UFUNC(name,type,exp) \ void rational_ufunc_##name(char** args, npy_intp* dimensions, \ npy_intp* steps, void* data) { \ npy_intp is = steps[0], os = steps[1], n = *dimensions; \ char *i = args[0], *o = args[1]; \ int k; \ for (k = 0; k < n; k++) { \ rational x = *(rational*)i; \ *(type*)o = exp; \ i += is; o += os; \ } \ } UNARY_UFUNC(negative,rational,rational_negative(x)) UNARY_UFUNC(absolute,rational,rational_abs(x)) UNARY_UFUNC(floor,rational,make_rational_int(rational_floor(x))) UNARY_UFUNC(ceil,rational,make_rational_int(rational_ceil(x))) UNARY_UFUNC(trunc,rational,make_rational_int(x.n/d(x))) UNARY_UFUNC(square,rational,rational_multiply(x,x)) UNARY_UFUNC(rint,rational,make_rational_int(rational_rint(x))) UNARY_UFUNC(sign,rational,make_rational_int(rational_sign(x))) UNARY_UFUNC(reciprocal,rational,rational_inverse(x)) UNARY_UFUNC(numerator,npy_int64,x.n) UNARY_UFUNC(denominator,npy_int64,d(x)) static NPY_INLINE void rational_matrix_multiply(char **args, npy_intp *dimensions, npy_intp *steps) { /* pointers to data for input and output arrays */ char *ip1 = args[0]; char *ip2 = args[1]; char *op = args[2]; /* lengths of core dimensions */ npy_intp dm = dimensions[0]; npy_intp dn = dimensions[1]; npy_intp dp = dimensions[2]; /* striding over core dimensions */ npy_intp is1_m = steps[0]; npy_intp is1_n = steps[1]; npy_intp is2_n = steps[2]; npy_intp is2_p = steps[3]; npy_intp os_m = steps[4]; npy_intp os_p = steps[5]; /* core dimensions counters */ npy_intp m, p; /* calculate dot product for each row/column vector pair */ for (m = 0; m < dm; m++) { for (p = 0; p < dp; p++) { npyrational_dot(ip1, is1_n, ip2, is2_n, op, dn, NULL); /* advance to next column of 2nd input array and output array */ ip2 += is2_p; op += os_p; } /* reset to first column of 2nd input array and output array */ ip2 -= is2_p * p; op -= os_p * p; /* advance to next row of 1st input array and output array */ ip1 += is1_m; op += os_m; } } static void rational_gufunc_matrix_multiply(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { /* outer dimensions counter */ npy_intp N_; /* length of flattened outer dimensions */ npy_intp dN = dimensions[0]; /* striding over flattened outer dimensions for input and output arrays */ npy_intp s0 = steps[0]; npy_intp s1 = steps[1]; npy_intp s2 = steps[2]; /* * loop through outer dimensions, performing matrix multiply on * core dimensions for each loop */ for (N_ = 0; N_ < dN; N_++, args[0] += s0, args[1] += s1, args[2] += s2) { rational_matrix_multiply(args, dimensions+1, steps+3); } } static void rational_ufunc_test_add(char** args, npy_intp* dimensions, npy_intp* steps, void* data) { npy_intp is0 = steps[0], is1 = steps[1], os = steps[2], n = *dimensions; char *i0 = args[0], *i1 = args[1], *o = args[2]; int k; for (k = 0; k < n; k++) { npy_int64 x = *(npy_int64*)i0; npy_int64 y = *(npy_int64*)i1; *(rational*)o = rational_add(make_rational_fast(x, 1), make_rational_fast(y, 1)); i0 += is0; i1 += is1; o += os; } } static void rational_ufunc_test_add_rationals(char** args, npy_intp* dimensions, npy_intp* steps, void* data) { npy_intp is0 = steps[0], is1 = steps[1], os = steps[2], n = *dimensions; char *i0 = args[0], *i1 = args[1], *o = args[2]; int k; for (k = 0; k < n; k++) { rational x = *(rational*)i0; rational y = *(rational*)i1; *(rational*)o = rational_add(x, y); i0 += is0; i1 += is1; o += os; } } PyMethodDef module_methods[] = { {0} /* sentinel */ }; #if defined(NPY_PY3K) static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, "test_rational", NULL, -1, module_methods, NULL, NULL, NULL, NULL }; #endif #if defined(NPY_PY3K) #define RETVAL m PyMODINIT_FUNC PyInit_test_rational(void) { #else #define RETVAL PyMODINIT_FUNC inittest_rational(void) { #endif PyObject *m = NULL; PyObject* numpy_str; PyObject* numpy; int npy_rational; import_array(); if (PyErr_Occurred()) { goto fail; } import_umath(); if (PyErr_Occurred()) { goto fail; } numpy_str = PyUString_FromString("numpy"); if (!numpy_str) { goto fail; } numpy = PyImport_Import(numpy_str); Py_DECREF(numpy_str); if (!numpy) { goto fail; } /* Can't set this until we import numpy */ PyRational_Type.tp_base = &PyGenericArrType_Type; /* Initialize rational type object */ if (PyType_Ready(&PyRational_Type) < 0) { goto fail; } /* Initialize rational descriptor */ PyArray_InitArrFuncs(&npyrational_arrfuncs); npyrational_arrfuncs.getitem = npyrational_getitem; npyrational_arrfuncs.setitem = npyrational_setitem; npyrational_arrfuncs.copyswapn = npyrational_copyswapn; npyrational_arrfuncs.copyswap = npyrational_copyswap; npyrational_arrfuncs.compare = npyrational_compare; npyrational_arrfuncs.argmin = npyrational_argmin; npyrational_arrfuncs.argmax = npyrational_argmax; npyrational_arrfuncs.dotfunc = npyrational_dot; npyrational_arrfuncs.nonzero = npyrational_nonzero; npyrational_arrfuncs.fill = npyrational_fill; npyrational_arrfuncs.fillwithscalar = npyrational_fillwithscalar; /* Left undefined: scanfunc, fromstr, sort, argsort */ Py_TYPE(&npyrational_descr) = &PyArrayDescr_Type; npy_rational = PyArray_RegisterDataType(&npyrational_descr); if (npy_rational<0) { goto fail; } /* Support dtype(rational) syntax */ if (PyDict_SetItemString(PyRational_Type.tp_dict, "dtype", (PyObject*)&npyrational_descr) < 0) { goto fail; } /* Register casts to and from rational */ #define REGISTER_CAST(From,To,from_descr,to_typenum,safe) { \ PyArray_Descr* from_descr_##From##_##To = (from_descr); \ if (PyArray_RegisterCastFunc(from_descr_##From##_##To, \ (to_typenum), \ npycast_##From##_##To) < 0) { \ goto fail; \ } \ if (safe && PyArray_RegisterCanCast(from_descr_##From##_##To, \ (to_typenum), \ NPY_NOSCALAR) < 0) { \ goto fail; \ } \ } #define REGISTER_INT_CASTS(bits) \ REGISTER_CAST(npy_int##bits, rational, \ PyArray_DescrFromType(NPY_INT##bits), npy_rational, 1) \ REGISTER_CAST(rational, npy_int##bits, &npyrational_descr, \ NPY_INT##bits, 0) REGISTER_INT_CASTS(8) REGISTER_INT_CASTS(16) REGISTER_INT_CASTS(32) REGISTER_INT_CASTS(64) REGISTER_CAST(rational,float,&npyrational_descr,NPY_FLOAT,0) REGISTER_CAST(rational,double,&npyrational_descr,NPY_DOUBLE,1) REGISTER_CAST(npy_bool,rational, PyArray_DescrFromType(NPY_BOOL), npy_rational,1) REGISTER_CAST(rational,npy_bool,&npyrational_descr,NPY_BOOL,0) /* Register ufuncs */ #define REGISTER_UFUNC(name,...) { \ PyUFuncObject* ufunc = \ (PyUFuncObject*)PyObject_GetAttrString(numpy, #name); \ int _types[] = __VA_ARGS__; \ if (!ufunc) { \ goto fail; \ } \ 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)); \ goto fail; \ } \ if (PyUFunc_RegisterLoopForType((PyUFuncObject*)ufunc, npy_rational, \ rational_ufunc_##name, _types, 0) < 0) { \ goto fail; \ } \ } #define REGISTER_UFUNC_BINARY_RATIONAL(name) \ REGISTER_UFUNC(name, {npy_rational, npy_rational, npy_rational}) #define REGISTER_UFUNC_BINARY_COMPARE(name) \ REGISTER_UFUNC(name, {npy_rational, npy_rational, NPY_BOOL}) #define REGISTER_UFUNC_UNARY(name) \ REGISTER_UFUNC(name, {npy_rational, npy_rational}) /* Binary */ REGISTER_UFUNC_BINARY_RATIONAL(add) REGISTER_UFUNC_BINARY_RATIONAL(subtract) REGISTER_UFUNC_BINARY_RATIONAL(multiply) REGISTER_UFUNC_BINARY_RATIONAL(divide) REGISTER_UFUNC_BINARY_RATIONAL(remainder) REGISTER_UFUNC_BINARY_RATIONAL(true_divide) REGISTER_UFUNC_BINARY_RATIONAL(floor_divide) REGISTER_UFUNC_BINARY_RATIONAL(minimum) REGISTER_UFUNC_BINARY_RATIONAL(maximum) /* Comparisons */ REGISTER_UFUNC_BINARY_COMPARE(equal) REGISTER_UFUNC_BINARY_COMPARE(not_equal) REGISTER_UFUNC_BINARY_COMPARE(less) REGISTER_UFUNC_BINARY_COMPARE(greater) REGISTER_UFUNC_BINARY_COMPARE(less_equal) REGISTER_UFUNC_BINARY_COMPARE(greater_equal) /* Unary */ REGISTER_UFUNC_UNARY(negative) REGISTER_UFUNC_UNARY(absolute) REGISTER_UFUNC_UNARY(floor) REGISTER_UFUNC_UNARY(ceil) REGISTER_UFUNC_UNARY(trunc) REGISTER_UFUNC_UNARY(rint) REGISTER_UFUNC_UNARY(square) REGISTER_UFUNC_UNARY(reciprocal) REGISTER_UFUNC_UNARY(sign) /* Create module */ #if defined(NPY_PY3K) m = PyModule_Create(&moduledef); #else m = Py_InitModule("test_rational", module_methods); #endif if (!m) { goto fail; } /* Add rational type */ Py_INCREF(&PyRational_Type); PyModule_AddObject(m,"rational",(PyObject*)&PyRational_Type); /* Create matrix multiply generalized ufunc */ { int types2[3] = {npy_rational,npy_rational,npy_rational}; PyObject* gufunc = PyUFunc_FromFuncAndDataAndSignature(0,0,0,0,2,1, PyUFunc_None,(char*)"matrix_multiply", (char*)"return result of multiplying two matrices of rationals", 0,"(m,n),(n,p)->(m,p)"); if (!gufunc) { goto fail; } if (PyUFunc_RegisterLoopForType((PyUFuncObject*)gufunc, npy_rational, rational_gufunc_matrix_multiply, types2, 0) < 0) { goto fail; } PyModule_AddObject(m,"matrix_multiply",(PyObject*)gufunc); } /* Create test ufunc with built in input types and rational output type */ { int types3[3] = {NPY_INT64,NPY_INT64,npy_rational}; PyObject* ufunc = PyUFunc_FromFuncAndData(0,0,0,0,2,1, PyUFunc_None,(char*)"test_add", (char*)"add two matrices of int64 and return rational matrix",0); if (!ufunc) { goto fail; } if (PyUFunc_RegisterLoopForType((PyUFuncObject*)ufunc, npy_rational, rational_ufunc_test_add, types3, 0) < 0) { goto fail; } PyModule_AddObject(m,"test_add",(PyObject*)ufunc); } /* Create test ufunc with rational types using RegisterLoopForDescr */ { PyObject* ufunc = PyUFunc_FromFuncAndData(0,0,0,0,2,1, PyUFunc_None,(char*)"test_add_rationals", (char*)"add two matrices of rationals and return rational matrix",0); PyArray_Descr* types[3] = {&npyrational_descr, &npyrational_descr, &npyrational_descr}; if (!ufunc) { goto fail; } if (PyUFunc_RegisterLoopForDescr((PyUFuncObject*)ufunc, &npyrational_descr, rational_ufunc_test_add_rationals, types, 0) < 0) { goto fail; } PyModule_AddObject(m,"test_add_rationals",(PyObject*)ufunc); } /* Create numerator and denominator ufuncs */ #define NEW_UNARY_UFUNC(name,type,doc) { \ int types[2] = {npy_rational,type}; \ PyObject* ufunc = PyUFunc_FromFuncAndData(0,0,0,0,1,1, \ PyUFunc_None,(char*)#name,(char*)doc,0); \ if (!ufunc) { \ goto fail; \ } \ if (PyUFunc_RegisterLoopForType((PyUFuncObject*)ufunc, \ npy_rational,rational_ufunc_##name,types,0)<0) { \ goto fail; \ } \ PyModule_AddObject(m,#name,(PyObject*)ufunc); \ } NEW_UNARY_UFUNC(numerator,NPY_INT64,"rational number numerator"); NEW_UNARY_UFUNC(denominator,NPY_INT64,"rational number denominator"); /* Create gcd and lcm ufuncs */ #define GCD_LCM_UFUNC(name,type,doc) { \ static const PyUFuncGenericFunction func[1] = {name##_ufunc}; \ static const char types[3] = {type,type,type}; \ static void* data[1] = {0}; \ PyObject* ufunc = PyUFunc_FromFuncAndData( \ (PyUFuncGenericFunction*)func, data,(char*)types, \ 1,2,1,PyUFunc_One,(char*)#name,(char*)doc,0); \ if (!ufunc) { \ goto fail; \ } \ PyModule_AddObject(m,#name,(PyObject*)ufunc); \ } GCD_LCM_UFUNC(gcd,NPY_INT64,"greatest common denominator of two integers"); GCD_LCM_UFUNC(lcm,NPY_INT64,"least common multiple of two integers"); return RETVAL; fail: if (!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError, "cannot load test_rational module."); } #if defined(NPY_PY3K) if (m) { Py_DECREF(m); m = NULL; } #endif return RETVAL; } numpy-1.8.2/numpy/core/src/umath/loops.c.src0000664000175100017510000020573512370216243022133 0ustar vagrantvagrant00000000000000/* -*- c -*- */ #define _UMATHMODULE #define NPY_NO_DEPRECATED_API NPY_API_VERSION #include "Python.h" #ifdef ENABLE_SEPARATE_COMPILATION #define PY_ARRAY_UNIQUE_SYMBOL _npy_umathmodule_ARRAY_API #define NO_IMPORT_ARRAY #endif #include "numpy/npy_common.h" #include "numpy/arrayobject.h" #include "numpy/ufuncobject.h" #include "numpy/npy_math.h" #include "numpy/halffloat.h" #include "lowlevel_strided_loops.h" #include "npy_pycompat.h" #include "ufunc_object.h" #include /* for memchr */ /* * include vectorized functions and dispatchers * this file is safe to include also for generic builds * platform specific instructions are either masked via the proprocessor or * runtime detected */ #include "simd.inc" /* ***************************************************************************** ** UFUNC LOOPS ** ***************************************************************************** */ #define IS_BINARY_REDUCE ((args[0] == args[2])\ && (steps[0] == steps[2])\ && (steps[0] == 0)) #define OUTPUT_LOOP\ char *op1 = args[1];\ npy_intp os1 = steps[1];\ npy_intp n = dimensions[0];\ npy_intp i;\ for(i = 0; i < n; i++, op1 += os1) #define UNARY_LOOP\ char *ip1 = args[0], *op1 = args[1];\ npy_intp is1 = steps[0], os1 = steps[1];\ npy_intp n = dimensions[0];\ npy_intp i;\ for(i = 0; i < n; i++, ip1 += is1, op1 += os1) #define UNARY_LOOP_TWO_OUT\ char *ip1 = args[0], *op1 = args[1], *op2 = args[2];\ npy_intp is1 = steps[0], os1 = steps[1], os2 = steps[2];\ npy_intp n = dimensions[0];\ npy_intp i;\ for(i = 0; i < n; i++, ip1 += is1, op1 += os1, op2 += os2) #define BINARY_LOOP\ char *ip1 = args[0], *ip2 = args[1], *op1 = args[2];\ npy_intp is1 = steps[0], is2 = steps[1], os1 = steps[2];\ npy_intp n = dimensions[0];\ npy_intp i;\ for(i = 0; i < n; i++, ip1 += is1, ip2 += is2, op1 += os1) #define BINARY_REDUCE_LOOP_INNER\ char *ip2 = args[1]; \ npy_intp is2 = steps[1]; \ npy_intp n = dimensions[0]; \ npy_intp i; \ for(i = 0; i < n; i++, ip2 += is2) #define BINARY_REDUCE_LOOP(TYPE)\ char *iop1 = args[0]; \ TYPE io1 = *(TYPE *)iop1; \ BINARY_REDUCE_LOOP_INNER #define BINARY_LOOP_TWO_OUT\ char *ip1 = args[0], *ip2 = args[1], *op1 = args[2], *op2 = args[3];\ npy_intp is1 = steps[0], is2 = steps[1], os1 = steps[2], os2 = steps[3];\ npy_intp n = dimensions[0];\ npy_intp i;\ for(i = 0; i < n; i++, ip1 += is1, ip2 += is2, op1 += os1, op2 += os2) /****************************************************************************** ** GENERIC FLOAT LOOPS ** *****************************************************************************/ typedef float halfUnaryFunc(npy_half x); typedef float floatUnaryFunc(float x); typedef double doubleUnaryFunc(double x); typedef npy_longdouble longdoubleUnaryFunc(npy_longdouble x); typedef npy_half halfBinaryFunc(npy_half x, npy_half y); typedef float floatBinaryFunc(float x, float y); typedef double doubleBinaryFunc(double x, double y); typedef npy_longdouble longdoubleBinaryFunc(npy_longdouble x, npy_longdouble y); /*UFUNC_API*/ NPY_NO_EXPORT void PyUFunc_e_e(char **args, npy_intp *dimensions, npy_intp *steps, void *func) { halfUnaryFunc *f = (halfUnaryFunc *)func; UNARY_LOOP { const npy_half in1 = *(npy_half *)ip1; *(npy_half *)op1 = f(in1); } } /*UFUNC_API*/ NPY_NO_EXPORT void PyUFunc_e_e_As_f_f(char **args, npy_intp *dimensions, npy_intp *steps, void *func) { floatUnaryFunc *f = (floatUnaryFunc *)func; UNARY_LOOP { const float in1 = npy_half_to_float(*(npy_half *)ip1); *(npy_half *)op1 = npy_float_to_half(f(in1)); } } /*UFUNC_API*/ NPY_NO_EXPORT void PyUFunc_e_e_As_d_d(char **args, npy_intp *dimensions, npy_intp *steps, void *func) { doubleUnaryFunc *f = (doubleUnaryFunc *)func; UNARY_LOOP { const double in1 = npy_half_to_double(*(npy_half *)ip1); *(npy_half *)op1 = npy_double_to_half(f(in1)); } } /*UFUNC_API*/ NPY_NO_EXPORT void PyUFunc_f_f(char **args, npy_intp *dimensions, npy_intp *steps, void *func) { floatUnaryFunc *f = (floatUnaryFunc *)func; UNARY_LOOP { const float in1 = *(float *)ip1; *(float *)op1 = f(in1); } } /*UFUNC_API*/ NPY_NO_EXPORT void PyUFunc_f_f_As_d_d(char **args, npy_intp *dimensions, npy_intp *steps, void *func) { doubleUnaryFunc *f = (doubleUnaryFunc *)func; UNARY_LOOP { const float in1 = *(float *)ip1; *(float *)op1 = (float)f((double)in1); } } /*UFUNC_API*/ NPY_NO_EXPORT void PyUFunc_ee_e(char **args, npy_intp *dimensions, npy_intp *steps, void *func) { halfBinaryFunc *f = (halfBinaryFunc *)func; BINARY_LOOP { npy_half in1 = *(npy_half *)ip1; npy_half in2 = *(npy_half *)ip2; *(npy_half *)op1 = f(in1, in2); } } /*UFUNC_API*/ NPY_NO_EXPORT void PyUFunc_ee_e_As_ff_f(char **args, npy_intp *dimensions, npy_intp *steps, void *func) { floatBinaryFunc *f = (floatBinaryFunc *)func; BINARY_LOOP { float in1 = npy_half_to_float(*(npy_half *)ip1); float in2 = npy_half_to_float(*(npy_half *)ip2); *(npy_half *)op1 = npy_float_to_half(f(in1, in2)); } } /*UFUNC_API*/ NPY_NO_EXPORT void PyUFunc_ee_e_As_dd_d(char **args, npy_intp *dimensions, npy_intp *steps, void *func) { doubleBinaryFunc *f = (doubleBinaryFunc *)func; BINARY_LOOP { double in1 = npy_half_to_double(*(npy_half *)ip1); double in2 = npy_half_to_double(*(npy_half *)ip2); *(npy_half *)op1 = npy_double_to_half(f(in1, in2)); } } /*UFUNC_API*/ NPY_NO_EXPORT void PyUFunc_ff_f(char **args, npy_intp *dimensions, npy_intp *steps, void *func) { floatBinaryFunc *f = (floatBinaryFunc *)func; BINARY_LOOP { float in1 = *(float *)ip1; float in2 = *(float *)ip2; *(float *)op1 = f(in1, in2); } } /*UFUNC_API*/ NPY_NO_EXPORT void PyUFunc_ff_f_As_dd_d(char **args, npy_intp *dimensions, npy_intp *steps, void *func) { doubleBinaryFunc *f = (doubleBinaryFunc *)func; BINARY_LOOP { float in1 = *(float *)ip1; float in2 = *(float *)ip2; *(float *)op1 = (double)f((double)in1, (double)in2); } } /*UFUNC_API*/ NPY_NO_EXPORT void PyUFunc_d_d(char **args, npy_intp *dimensions, npy_intp *steps, void *func) { doubleUnaryFunc *f = (doubleUnaryFunc *)func; UNARY_LOOP { double in1 = *(double *)ip1; *(double *)op1 = f(in1); } } /*UFUNC_API*/ NPY_NO_EXPORT void PyUFunc_dd_d(char **args, npy_intp *dimensions, npy_intp *steps, void *func) { doubleBinaryFunc *f = (doubleBinaryFunc *)func; BINARY_LOOP { double in1 = *(double *)ip1; double in2 = *(double *)ip2; *(double *)op1 = f(in1, in2); } } /*UFUNC_API*/ NPY_NO_EXPORT void PyUFunc_g_g(char **args, npy_intp *dimensions, npy_intp *steps, void *func) { longdoubleUnaryFunc *f = (longdoubleUnaryFunc *)func; UNARY_LOOP { npy_longdouble in1 = *(npy_longdouble *)ip1; *(npy_longdouble *)op1 = f(in1); } } /*UFUNC_API*/ NPY_NO_EXPORT void PyUFunc_gg_g(char **args, npy_intp *dimensions, npy_intp *steps, void *func) { longdoubleBinaryFunc *f = (longdoubleBinaryFunc *)func; BINARY_LOOP { npy_longdouble in1 = *(npy_longdouble *)ip1; npy_longdouble in2 = *(npy_longdouble *)ip2; *(npy_longdouble *)op1 = f(in1, in2); } } /****************************************************************************** ** GENERIC COMPLEX LOOPS ** *****************************************************************************/ typedef void cdoubleUnaryFunc(npy_cdouble *x, npy_cdouble *r); typedef void cfloatUnaryFunc(npy_cfloat *x, npy_cfloat *r); typedef void clongdoubleUnaryFunc(npy_clongdouble *x, npy_clongdouble *r); typedef void cdoubleBinaryFunc(npy_cdouble *x, npy_cdouble *y, npy_cdouble *r); typedef void cfloatBinaryFunc(npy_cfloat *x, npy_cfloat *y, npy_cfloat *r); typedef void clongdoubleBinaryFunc(npy_clongdouble *x, npy_clongdouble *y, npy_clongdouble *r); /*UFUNC_API*/ NPY_NO_EXPORT void PyUFunc_F_F(char **args, npy_intp *dimensions, npy_intp *steps, void *func) { cfloatUnaryFunc *f = (cfloatUnaryFunc *)func; UNARY_LOOP { npy_cfloat in1 = *(npy_cfloat *)ip1; npy_cfloat *out = (npy_cfloat *)op1; f(&in1, out); } } /*UFUNC_API*/ NPY_NO_EXPORT void PyUFunc_F_F_As_D_D(char **args, npy_intp *dimensions, npy_intp *steps, void *func) { cdoubleUnaryFunc *f = (cdoubleUnaryFunc *)func; UNARY_LOOP { npy_cdouble tmp, out; tmp.real = (double)((float *)ip1)[0]; tmp.imag = (double)((float *)ip1)[1]; f(&tmp, &out); ((float *)op1)[0] = (float)out.real; ((float *)op1)[1] = (float)out.imag; } } /*UFUNC_API*/ NPY_NO_EXPORT void PyUFunc_FF_F(char **args, npy_intp *dimensions, npy_intp *steps, void *func) { cfloatBinaryFunc *f = (cfloatBinaryFunc *)func; BINARY_LOOP { npy_cfloat in1 = *(npy_cfloat *)ip1; npy_cfloat in2 = *(npy_cfloat *)ip2; npy_cfloat *out = (npy_cfloat *)op1; f(&in1, &in2, out); } } /*UFUNC_API*/ NPY_NO_EXPORT void PyUFunc_FF_F_As_DD_D(char **args, npy_intp *dimensions, npy_intp *steps, void *func) { cdoubleBinaryFunc *f = (cdoubleBinaryFunc *)func; BINARY_LOOP { npy_cdouble tmp1, tmp2, out; tmp1.real = (double)((float *)ip1)[0]; tmp1.imag = (double)((float *)ip1)[1]; tmp2.real = (double)((float *)ip2)[0]; tmp2.imag = (double)((float *)ip2)[1]; f(&tmp1, &tmp2, &out); ((float *)op1)[0] = (float)out.real; ((float *)op1)[1] = (float)out.imag; } } /*UFUNC_API*/ NPY_NO_EXPORT void PyUFunc_D_D(char **args, npy_intp *dimensions, npy_intp *steps, void *func) { cdoubleUnaryFunc *f = (cdoubleUnaryFunc *)func; UNARY_LOOP { npy_cdouble in1 = *(npy_cdouble *)ip1; npy_cdouble *out = (npy_cdouble *)op1; f(&in1, out); } } /*UFUNC_API*/ NPY_NO_EXPORT void PyUFunc_DD_D(char **args, npy_intp *dimensions, npy_intp *steps, void *func) { cdoubleBinaryFunc *f = (cdoubleBinaryFunc *)func; BINARY_LOOP { npy_cdouble in1 = *(npy_cdouble *)ip1; npy_cdouble in2 = *(npy_cdouble *)ip2; npy_cdouble *out = (npy_cdouble *)op1; f(&in1, &in2, out); } } /*UFUNC_API*/ NPY_NO_EXPORT void PyUFunc_G_G(char **args, npy_intp *dimensions, npy_intp *steps, void *func) { clongdoubleUnaryFunc *f = (clongdoubleUnaryFunc *)func; UNARY_LOOP { npy_clongdouble in1 = *(npy_clongdouble *)ip1; npy_clongdouble *out = (npy_clongdouble *)op1; f(&in1, out); } } /*UFUNC_API*/ NPY_NO_EXPORT void PyUFunc_GG_G(char **args, npy_intp *dimensions, npy_intp *steps, void *func) { clongdoubleBinaryFunc *f = (clongdoubleBinaryFunc *)func; BINARY_LOOP { npy_clongdouble in1 = *(npy_clongdouble *)ip1; npy_clongdouble in2 = *(npy_clongdouble *)ip2; npy_clongdouble *out = (npy_clongdouble *)op1; f(&in1, &in2, out); } } /****************************************************************************** ** GENERIC OBJECT lOOPS ** *****************************************************************************/ /*UFUNC_API*/ NPY_NO_EXPORT void PyUFunc_O_O(char **args, npy_intp *dimensions, npy_intp *steps, void *func) { unaryfunc f = (unaryfunc)func; UNARY_LOOP { PyObject *in1 = *(PyObject **)ip1; PyObject **out = (PyObject **)op1; PyObject *ret = f(in1 ? in1 : Py_None); if (ret == NULL) { return; } Py_XDECREF(*out); *out = ret; } } /*UFUNC_API*/ NPY_NO_EXPORT void PyUFunc_O_O_method(char **args, npy_intp *dimensions, npy_intp *steps, void *func) { char *meth = (char *)func; UNARY_LOOP { PyObject *in1 = *(PyObject **)ip1; PyObject **out = (PyObject **)op1; PyObject *ret = PyObject_CallMethod(in1 ? in1 : Py_None, meth, NULL); if (ret == NULL) { return; } Py_XDECREF(*out); *out = ret; } } /*UFUNC_API*/ NPY_NO_EXPORT void PyUFunc_OO_O(char **args, npy_intp *dimensions, npy_intp *steps, void *func) { binaryfunc f = (binaryfunc)func; BINARY_LOOP { PyObject *in1 = *(PyObject **)ip1; PyObject *in2 = *(PyObject **)ip2; PyObject **out = (PyObject **)op1; PyObject *ret = f(in1 ? in1 : Py_None, in2 ? in2 : Py_None); if (ret == NULL) { return; } Py_XDECREF(*out); *out = ret; } } /*UFUNC_API*/ NPY_NO_EXPORT void PyUFunc_OO_O_method(char **args, npy_intp *dimensions, npy_intp *steps, void *func) { char *meth = (char *)func; BINARY_LOOP { PyObject *in1 = *(PyObject **)ip1; PyObject *in2 = *(PyObject **)ip2; PyObject **out = (PyObject **)op1; PyObject *ret = PyObject_CallMethod(in1 ? in1 : Py_None, meth, "(O)", in2); if (ret == NULL) { return; } Py_XDECREF(*out); *out = ret; } } /* * A general-purpose ufunc that deals with general-purpose Python callable. * func is a structure with nin, nout, and a Python callable function */ /*UFUNC_API*/ NPY_NO_EXPORT void PyUFunc_On_Om(char **args, npy_intp *dimensions, npy_intp *steps, void *func) { npy_intp n = dimensions[0]; PyUFunc_PyFuncData *data = (PyUFunc_PyFuncData *)func; int nin = data->nin; int nout = data->nout; PyObject *tocall = data->callable; char *ptrs[NPY_MAXARGS]; PyObject *arglist, *result; PyObject *in, **op; npy_intp i, j, ntot; ntot = nin+nout; for(j = 0; j < ntot; j++) { ptrs[j] = args[j]; } for(i = 0; i < n; i++) { arglist = PyTuple_New(nin); if (arglist == NULL) { return; } for(j = 0; j < nin; j++) { in = *((PyObject **)ptrs[j]); if (in == NULL) { in = Py_None; } PyTuple_SET_ITEM(arglist, j, in); Py_INCREF(in); } result = PyEval_CallObject(tocall, arglist); Py_DECREF(arglist); if (result == NULL) { return; } if (PyTuple_Check(result)) { if (nout != PyTuple_Size(result)) { Py_DECREF(result); return; } for(j = 0; j < nout; j++) { op = (PyObject **)ptrs[j+nin]; Py_XDECREF(*op); *op = PyTuple_GET_ITEM(result, j); Py_INCREF(*op); } Py_DECREF(result); } else { op = (PyObject **)ptrs[nin]; Py_XDECREF(*op); *op = result; } for(j = 0; j < ntot; j++) { ptrs[j] += steps[j]; } } } /* ***************************************************************************** ** BOOLEAN LOOPS ** ***************************************************************************** */ /**begin repeat * #kind = equal, not_equal, greater, greater_equal, less, less_equal# * #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; } } /**end repeat**/ /**begin repeat * #kind = logical_and, logical_or# * #OP = &&, ||# * #SC = ==, !=# * #and = 1, 0# **/ NPY_NO_EXPORT void BOOL_@kind@(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { if(IS_BINARY_REDUCE) { #ifdef NPY_HAVE_SSE2_INTRINSICS /* * stick with our variant for more reliable performance, only known * platform which outperforms it by ~20% is an i7 with glibc 2.17 */ if (run_reduce_simd_@kind@_BOOL(args, dimensions, steps)) { return; } #else /* for now only use libc on 32-bit/non-x86 */ if (steps[1] == 1) { npy_bool * op = (npy_bool *)args[0]; #if @and@ /* np.all(), search for a zero (false) */ if (*op) { *op = memchr(args[1], 0, dimensions[0]) == NULL; } #else /* * np.any(), search for a non-zero (true) via comparing against * zero blocks, memcmp is faster than memchr on SSE4 machines * with glibc >= 2.12 and memchr can only check for equal 1 */ static const npy_bool zero[4096]; /* zero by C standard */ npy_uintp i, n = dimensions[0]; for (i = 0; !*op && i < n - (n % sizeof(zero)); i += sizeof(zero)) { *op = memcmp(&args[1][i], zero, sizeof(zero)) != 0; } if (!*op && n - i > 0) { *op = memcmp(&args[1][i], zero, n - i) != 0; } #endif return; } #endif else { BINARY_REDUCE_LOOP(npy_bool) { const npy_bool in2 = *(npy_bool *)ip2; io1 = io1 @OP@ in2; if (io1 @SC@ 0) { break; } } *((npy_bool *)iop1) = io1; } } else { if (run_binary_simd_@kind@_BOOL(args, dimensions, steps)) { return; } else { BINARY_LOOP { const npy_bool in1 = *(npy_bool *)ip1; const npy_bool in2 = *(npy_bool *)ip2; *((npy_bool *)op1) = in1 @OP@ in2; } } } } /**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 = !=, ==# **/ NPY_NO_EXPORT void BOOL_@kind@(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { if (run_unary_simd_@kind@_BOOL(args, dimensions, steps)) { return; } else { UNARY_LOOP { npy_bool in1 = *(npy_bool *)ip1; *((npy_bool *)op1) = in1 @OP@ 0; } } } /**end repeat**/ NPY_NO_EXPORT void BOOL__ones_like(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)) { OUTPUT_LOOP { *((npy_bool *)op1) = 1; } } /* ***************************************************************************** ** INTEGER LOOPS ***************************************************************************** */ /**begin repeat * #TYPE = BYTE, UBYTE, SHORT, USHORT, INT, UINT, * LONG, ULONG, LONGLONG, ULONGLONG# * #type = npy_byte, npy_ubyte, npy_short, npy_ushort, npy_int, npy_uint, * npy_long, npy_ulong, npy_longlong, npy_ulonglong# * #ftype = npy_float, npy_float, npy_float, npy_float, npy_double, npy_double, * npy_double, npy_double, npy_double, npy_double# */ #define @TYPE@_floor_divide @TYPE@_divide #define @TYPE@_fmax @TYPE@_maximum #define @TYPE@_fmin @TYPE@_minimum NPY_NO_EXPORT void @TYPE@__ones_like(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)) { OUTPUT_LOOP { *((@type@ *)op1) = 1; } } NPY_NO_EXPORT void @TYPE@_square(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)) { UNARY_LOOP { const @type@ in1 = *(@type@ *)ip1; *((@type@ *)op1) = in1*in1; } } NPY_NO_EXPORT void @TYPE@_reciprocal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)) { UNARY_LOOP { const @type@ in1 = *(@type@ *)ip1; *((@type@ *)op1) = (@type@)(1.0/in1); } } NPY_NO_EXPORT void @TYPE@_conjugate(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { UNARY_LOOP { const @type@ in1 = *(@type@ *)ip1; *((@type@ *)op1) = in1; } } 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) = (@type@)(-(@type@)in1); } } NPY_NO_EXPORT void @TYPE@_logical_not(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { UNARY_LOOP { const @type@ in1 = *(@type@ *)ip1; *((npy_bool *)op1) = !in1; } } NPY_NO_EXPORT void @TYPE@_invert(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { UNARY_LOOP { const @type@ in1 = *(@type@ *)ip1; *((@type@ *)op1) = ~in1; } } /**begin repeat1 * Arithmetic * #kind = add, subtract, multiply, bitwise_and, bitwise_or, bitwise_xor, * left_shift, right_shift# * #OP = +, -,*, &, |, ^, <<, >># */ NPY_NO_EXPORT void @TYPE@_@kind@(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { if(IS_BINARY_REDUCE) { BINARY_REDUCE_LOOP(@type@) { io1 @OP@= *(@type@ *)ip2; } *((@type@ *)iop1) = io1; } else { BINARY_LOOP { const @type@ in1 = *(@type@ *)ip1; const @type@ in2 = *(@type@ *)ip2; *((@type@ *)op1) = in1 @OP@ in2; } } } /**end repeat1**/ /**begin repeat1 * #kind = equal, not_equal, greater, greater_equal, less, less_equal, * logical_and, logical_or# * #OP = ==, !=, >, >=, <, <=, &&, ||# */ NPY_NO_EXPORT 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; } } /**end repeat1**/ NPY_NO_EXPORT void @TYPE@_logical_xor(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 && !in2) || (!in1 && in2); } } /**begin repeat1 * #kind = maximum, minimum# * #OP = >, <# **/ NPY_NO_EXPORT void @TYPE@_@kind@(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { if (IS_BINARY_REDUCE) { BINARY_REDUCE_LOOP(@type@) { const @type@ in2 = *(@type@ *)ip2; io1 = (io1 @OP@ in2) ? io1 : in2; } *((@type@ *)iop1) = io1; } else { BINARY_LOOP { const @type@ in1 = *(@type@ *)ip1; const @type@ in2 = *(@type@ *)ip2; *((@type@ *)op1) = (in1 @OP@ in2) ? in1 : in2; } } } /**end repeat1**/ NPY_NO_EXPORT void @TYPE@_true_divide(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { BINARY_LOOP { const double in1 = (double)(*(@type@ *)ip1); const double in2 = (double)(*(@type@ *)ip2); *((double *)op1) = in1/in2; } } NPY_NO_EXPORT void @TYPE@_power(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { BINARY_LOOP { const @ftype@ in1 = (@ftype@)*(@type@ *)ip1; const @ftype@ in2 = (@ftype@)*(@type@ *)ip2; *((@type@ *)op1) = (@type@) pow(in1, in2); } } NPY_NO_EXPORT void @TYPE@_fmod(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { BINARY_LOOP { const @type@ in1 = *(@type@ *)ip1; const @type@ in2 = *(@type@ *)ip2; if (in2 == 0) { npy_set_floatstatus_divbyzero(); *((@type@ *)op1) = 0; } else { *((@type@ *)op1)= in1 % in2; } } } /**end repeat**/ /**begin repeat * #TYPE = BYTE, SHORT, INT, LONG, LONGLONG# * #type = npy_byte, npy_short, npy_int, npy_long, npy_longlong# */ NPY_NO_EXPORT void @TYPE@_absolute(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { UNARY_LOOP { const @type@ in1 = *(@type@ *)ip1; *((@type@ *)op1) = (in1 >= 0) ? in1 : -in1; } } NPY_NO_EXPORT void @TYPE@_sign(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { UNARY_LOOP { const @type@ in1 = *(@type@ *)ip1; *((@type@ *)op1) = in1 > 0 ? 1 : (in1 < 0 ? -1 : 0); } } NPY_NO_EXPORT void @TYPE@_divide(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { BINARY_LOOP { const @type@ in1 = *(@type@ *)ip1; const @type@ in2 = *(@type@ *)ip2; /* * FIXME: On x86 at least, dividing the smallest representable integer * by -1 causes a SIFGPE (division overflow). We treat this case here * (to avoid a SIGFPE crash at python level), but a good solution would * be to treat integer division problems separately from FPU exceptions * (i.e. a different approach than npy_set_floatstatus_divbyzero()). */ if (in2 == 0 || (in1 == NPY_MIN_@TYPE@ && in2 == -1)) { npy_set_floatstatus_divbyzero(); *((@type@ *)op1) = 0; } else if (((in1 > 0) != (in2 > 0)) && (in1 % in2 != 0)) { *((@type@ *)op1) = in1/in2 - 1; } else { *((@type@ *)op1) = in1/in2; } } } NPY_NO_EXPORT void @TYPE@_remainder(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { BINARY_LOOP { const @type@ in1 = *(@type@ *)ip1; const @type@ in2 = *(@type@ *)ip2; if (in2 == 0) { npy_set_floatstatus_divbyzero(); *((@type@ *)op1) = 0; } else { /* handle mixed case the way Python does */ const @type@ rem = in1 % in2; if ((in1 > 0) == (in2 > 0) || rem == 0) { *((@type@ *)op1) = rem; } else { *((@type@ *)op1) = rem + in2; } } } } /**end repeat**/ /**begin repeat * #TYPE = UBYTE, USHORT, UINT, ULONG, ULONGLONG# * #type = npy_ubyte, npy_ushort, npy_uint, npy_ulong, npy_ulonglong# */ NPY_NO_EXPORT void @TYPE@_absolute(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { UNARY_LOOP { const @type@ in1 = *(@type@ *)ip1; *((@type@ *)op1) = in1; } } NPY_NO_EXPORT void @TYPE@_sign(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { UNARY_LOOP { const @type@ in1 = *(@type@ *)ip1; *((@type@ *)op1) = in1 > 0 ? 1 : 0; } } NPY_NO_EXPORT void @TYPE@_divide(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { BINARY_LOOP { const @type@ in1 = *(@type@ *)ip1; const @type@ in2 = *(@type@ *)ip2; if (in2 == 0) { npy_set_floatstatus_divbyzero(); *((@type@ *)op1) = 0; } else { *((@type@ *)op1)= in1/in2; } } } NPY_NO_EXPORT void @TYPE@_remainder(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { BINARY_LOOP { const @type@ in1 = *(@type@ *)ip1; const @type@ in2 = *(@type@ *)ip2; if (in2 == 0) { npy_set_floatstatus_divbyzero(); *((@type@ *)op1) = 0; } else { *((@type@ *)op1) = in1 % in2; } } } /**end repeat**/ /* ***************************************************************************** ** DATETIME LOOPS ** ***************************************************************************** */ NPY_NO_EXPORT void TIMEDELTA_negative(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { UNARY_LOOP { const npy_timedelta in1 = *(npy_timedelta *)ip1; if (in1 == NPY_DATETIME_NAT) { *((npy_timedelta *)op1) = NPY_DATETIME_NAT; } else { *((npy_timedelta *)op1) = -in1; } } } NPY_NO_EXPORT void TIMEDELTA_absolute(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { UNARY_LOOP { const npy_timedelta in1 = *(npy_timedelta *)ip1; if (in1 == NPY_DATETIME_NAT) { *((npy_timedelta *)op1) = NPY_DATETIME_NAT; } else { *((npy_timedelta *)op1) = (in1 >= 0) ? in1 : -in1; } } } NPY_NO_EXPORT void TIMEDELTA_sign(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { UNARY_LOOP { const npy_timedelta in1 = *(npy_timedelta *)ip1; *((npy_timedelta *)op1) = in1 > 0 ? 1 : (in1 < 0 ? -1 : 0); } } /**begin repeat * #type = npy_datetime, npy_timedelta# * #TYPE = DATETIME, TIMEDELTA# */ NPY_NO_EXPORT void @TYPE@__ones_like(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)) { OUTPUT_LOOP { *((@type@ *)op1) = 1; } } /**begin repeat1 * #kind = equal, not_equal, greater, greater_equal, less, less_equal# * #OP = ==, !=, >, >=, <, <=# */ NPY_NO_EXPORT 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; } } /**end repeat1**/ /**begin repeat1 * #kind = maximum, minimum# * #OP = >, <# **/ NPY_NO_EXPORT void @TYPE@_@kind@(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { if (IS_BINARY_REDUCE) { BINARY_REDUCE_LOOP(@type@) { const @type@ in2 = *(@type@ *)ip2; io1 = (io1 @OP@ in2 || in2 == NPY_DATETIME_NAT) ? io1 : in2; } *((@type@ *)iop1) = io1; } else { BINARY_LOOP { const @type@ in1 = *(@type@ *)ip1; const @type@ in2 = *(@type@ *)ip2; if (in1 == NPY_DATETIME_NAT) { *((@type@ *)op1) = in2; } else if (in2 == NPY_DATETIME_NAT) { *((@type@ *)op1) = in1; } else { *((@type@ *)op1) = (in1 @OP@ in2) ? in1 : in2; } } } } /**end repeat1**/ /**end repeat**/ NPY_NO_EXPORT void DATETIME_Mm_M_add(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)) { BINARY_LOOP { const npy_datetime in1 = *(npy_datetime *)ip1; const npy_timedelta in2 = *(npy_timedelta *)ip2; if (in1 == NPY_DATETIME_NAT || in2 == NPY_DATETIME_NAT) { *((npy_datetime *)op1) = NPY_DATETIME_NAT; } else { *((npy_datetime *)op1) = in1 + in2; } } } NPY_NO_EXPORT void DATETIME_mM_M_add(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { BINARY_LOOP { const npy_timedelta in1 = *(npy_timedelta *)ip1; const npy_datetime in2 = *(npy_datetime *)ip2; if (in1 == NPY_DATETIME_NAT || in2 == NPY_DATETIME_NAT) { *((npy_datetime *)op1) = NPY_DATETIME_NAT; } else { *((npy_datetime *)op1) = in1 + in2; } } } NPY_NO_EXPORT void TIMEDELTA_mm_m_add(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { BINARY_LOOP { const npy_timedelta in1 = *(npy_timedelta *)ip1; const npy_timedelta in2 = *(npy_timedelta *)ip2; if (in1 == NPY_DATETIME_NAT || in2 == NPY_DATETIME_NAT) { *((npy_timedelta *)op1) = NPY_DATETIME_NAT; } else { *((npy_timedelta *)op1) = in1 + in2; } } } NPY_NO_EXPORT void DATETIME_Mm_M_subtract(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { BINARY_LOOP { const npy_datetime in1 = *(npy_datetime *)ip1; const npy_timedelta in2 = *(npy_timedelta *)ip2; if (in1 == NPY_DATETIME_NAT || in2 == NPY_DATETIME_NAT) { *((npy_datetime *)op1) = NPY_DATETIME_NAT; } else { *((npy_datetime *)op1) = in1 - in2; } } } NPY_NO_EXPORT void DATETIME_MM_m_subtract(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { BINARY_LOOP { const npy_datetime in1 = *(npy_datetime *)ip1; const npy_datetime in2 = *(npy_datetime *)ip2; if (in1 == NPY_DATETIME_NAT || in2 == NPY_DATETIME_NAT) { *((npy_timedelta *)op1) = NPY_DATETIME_NAT; } else { *((npy_timedelta *)op1) = in1 - in2; } } } NPY_NO_EXPORT void TIMEDELTA_mm_m_subtract(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { BINARY_LOOP { const npy_timedelta in1 = *(npy_timedelta *)ip1; const npy_timedelta in2 = *(npy_timedelta *)ip2; if (in1 == NPY_DATETIME_NAT || in2 == NPY_DATETIME_NAT) { *((npy_timedelta *)op1) = NPY_DATETIME_NAT; } else { *((npy_timedelta *)op1) = in1 - in2; } } } /* Note: Assuming 'q' == NPY_LONGLONG */ NPY_NO_EXPORT void TIMEDELTA_mq_m_multiply(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { BINARY_LOOP { const npy_timedelta in1 = *(npy_timedelta *)ip1; const npy_int64 in2 = *(npy_int64 *)ip2; if (in1 == NPY_DATETIME_NAT) { *((npy_timedelta *)op1) = NPY_DATETIME_NAT; } else { *((npy_timedelta *)op1) = in1 * in2; } } } /* Note: Assuming 'q' == NPY_LONGLONG */ NPY_NO_EXPORT void TIMEDELTA_qm_m_multiply(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { BINARY_LOOP { const npy_int64 in1 = *(npy_int64 *)ip1; const npy_timedelta in2 = *(npy_timedelta *)ip2; if (in2 == NPY_DATETIME_NAT) { *((npy_timedelta *)op1) = NPY_DATETIME_NAT; } else { *((npy_timedelta *)op1) = in1 * in2; } } } NPY_NO_EXPORT void TIMEDELTA_md_m_multiply(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { BINARY_LOOP { const npy_timedelta in1 = *(npy_timedelta *)ip1; const double in2 = *(double *)ip2; if (in1 == NPY_DATETIME_NAT || npy_isnan(in2)) { *((npy_timedelta *)op1) = NPY_DATETIME_NAT; } else { *((npy_timedelta *)op1) = (npy_timedelta)(in1 * in2); } } } NPY_NO_EXPORT void TIMEDELTA_dm_m_multiply(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { BINARY_LOOP { const double in1 = *(double *)ip1; const npy_timedelta in2 = *(npy_timedelta *)ip2; if (npy_isnan(in1) || in2 == NPY_DATETIME_NAT) { *((npy_timedelta *)op1) = NPY_DATETIME_NAT; } else { *((npy_timedelta *)op1) = (npy_timedelta)(in1 * in2); } } } /* Note: Assuming 'q' == NPY_LONGLONG */ NPY_NO_EXPORT void TIMEDELTA_mq_m_divide(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { BINARY_LOOP { const npy_timedelta in1 = *(npy_timedelta *)ip1; const npy_int64 in2 = *(npy_int64 *)ip2; if (in1 == NPY_DATETIME_NAT || in2 == 0) { *((npy_timedelta *)op1) = NPY_DATETIME_NAT; } else { *((npy_timedelta *)op1) = in1 / in2; } } } NPY_NO_EXPORT void TIMEDELTA_md_m_divide(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { BINARY_LOOP { const npy_timedelta in1 = *(npy_timedelta *)ip1; const double in2 = *(double *)ip2; if (in1 == NPY_DATETIME_NAT) { *((npy_timedelta *)op1) = NPY_DATETIME_NAT; } else { double result = in1 / in2; if (npy_isnan(result)) { *((npy_timedelta *)op1) = NPY_DATETIME_NAT; } else { *((npy_timedelta *)op1) = (npy_timedelta)(result); } } } } NPY_NO_EXPORT void TIMEDELTA_mm_d_divide(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { BINARY_LOOP { const npy_timedelta in1 = *(npy_timedelta *)ip1; const npy_timedelta in2 = *(npy_timedelta *)ip2; if (in1 == NPY_DATETIME_NAT || in2 == NPY_DATETIME_NAT) { *((double *)op1) = NPY_NAN; } else { *((double *)op1) = (double)in1 / (double)in2; } } } /* ***************************************************************************** ** FLOAT LOOPS ** ***************************************************************************** */ /**begin repeat * Float types * #type = npy_float, npy_double# * #TYPE = FLOAT, DOUBLE# * #scalarf = npy_sqrtf, npy_sqrt# */ NPY_NO_EXPORT void @TYPE@_sqrt(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { if (!run_unary_simd_sqrt_@TYPE@(args, dimensions, steps)) { UNARY_LOOP { const @type@ in1 = *(@type@ *)ip1; *(@type@ *)op1 = @scalarf@(in1); } } } /**end repeat**/ /**begin repeat * Float types * #type = npy_float, npy_double, npy_longdouble# * #TYPE = FLOAT, DOUBLE, LONGDOUBLE# * #c = f, , l# * #C = F, , L# */ /**begin repeat1 * Arithmetic * # kind = add, subtract, multiply, divide# * # OP = +, -, *, /# */ NPY_NO_EXPORT void @TYPE@_@kind@(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { if (IS_BINARY_REDUCE) { BINARY_REDUCE_LOOP(@type@) { io1 @OP@= *(@type@ *)ip2; } *((@type@ *)iop1) = io1; } else if (!run_binary_simd_@kind@_@TYPE@(args, dimensions, steps)) { BINARY_LOOP { const @type@ in1 = *(@type@ *)ip1; const @type@ in2 = *(@type@ *)ip2; *((@type@ *)op1) = in1 @OP@ in2; } } } /**end repeat1**/ /**begin repeat1 * #kind = equal, not_equal, less, less_equal, greater, greater_equal, * logical_and, logical_or# * #OP = ==, !=, <, <=, >, >=, &&, ||# */ NPY_NO_EXPORT void @TYPE@_@kind@(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { if (!run_binary_simd_@kind@_@TYPE@(args, dimensions, steps)) { BINARY_LOOP { const @type@ in1 = *(@type@ *)ip1; const @type@ in2 = *(@type@ *)ip2; *((npy_bool *)op1) = in1 @OP@ in2; } } } /**end repeat1**/ NPY_NO_EXPORT void @TYPE@_logical_xor(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 && !in2) || (!in1 && in2); } } NPY_NO_EXPORT void @TYPE@_logical_not(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { UNARY_LOOP { const @type@ in1 = *(@type@ *)ip1; *((npy_bool *)op1) = !in1; } } /**begin repeat1 * #kind = isnan, isinf, isfinite, signbit# * #func = npy_isnan, npy_isinf, npy_isfinite, npy_signbit# **/ 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; } } /**end repeat1**/ NPY_NO_EXPORT void @TYPE@_spacing(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { UNARY_LOOP { const @type@ in1 = *(@type@ *)ip1; *((@type@ *)op1) = npy_spacing@c@(in1); } } NPY_NO_EXPORT void @TYPE@_copysign(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { BINARY_LOOP { const @type@ in1 = *(@type@ *)ip1; const @type@ in2 = *(@type@ *)ip2; *((@type@ *)op1)= npy_copysign@c@(in1, in2); } } NPY_NO_EXPORT void @TYPE@_nextafter(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { BINARY_LOOP { const @type@ in1 = *(@type@ *)ip1; const @type@ in2 = *(@type@ *)ip2; *((@type@ *)op1)= npy_nextafter@c@(in1, in2); } } /**begin repeat1 * #kind = maximum, minimum# * #OP = >=, <=# **/ NPY_NO_EXPORT void @TYPE@_@kind@(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { /* */ if (IS_BINARY_REDUCE) { if (!run_unary_reduce_simd_@kind@_@TYPE@(args, dimensions, steps)) { BINARY_REDUCE_LOOP(@type@) { const @type@ in2 = *(@type@ *)ip2; io1 = (io1 @OP@ in2 || npy_isnan(io1)) ? io1 : in2; } *((@type@ *)iop1) = io1; } } else { BINARY_LOOP { const @type@ in1 = *(@type@ *)ip1; const @type@ in2 = *(@type@ *)ip2; *((@type@ *)op1) = (in1 @OP@ in2 || npy_isnan(in1)) ? in1 : in2; } } } /**end repeat1**/ /**begin repeat1 * #kind = fmax, fmin# * #OP = >=, <=# **/ NPY_NO_EXPORT void @TYPE@_@kind@(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { /* */ if (IS_BINARY_REDUCE) { BINARY_REDUCE_LOOP(@type@) { const @type@ in2 = *(@type@ *)ip2; io1 = (io1 @OP@ in2 || npy_isnan(in2)) ? io1 : in2; } *((@type@ *)iop1) = io1; } else { BINARY_LOOP { const @type@ in1 = *(@type@ *)ip1; const @type@ in2 = *(@type@ *)ip2; *((@type@ *)op1) = (in1 @OP@ in2 || npy_isnan(in2)) ? in1 : in2; } } } /**end repeat1**/ NPY_NO_EXPORT void @TYPE@_floor_divide(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { BINARY_LOOP { const @type@ in1 = *(@type@ *)ip1; const @type@ in2 = *(@type@ *)ip2; *((@type@ *)op1) = npy_floor@c@(in1/in2); } } NPY_NO_EXPORT void @TYPE@_remainder(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { BINARY_LOOP { const @type@ in1 = *(@type@ *)ip1; const @type@ in2 = *(@type@ *)ip2; const @type@ res = npy_fmod@c@(in1,in2); if (res && ((in2 < 0) != (res < 0))) { *((@type@ *)op1) = res + in2; } else { *((@type@ *)op1) = res; } } } NPY_NO_EXPORT void @TYPE@_square(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)) { char * margs[] = {args[0], args[0], args[1]}; npy_intp msteps[] = {steps[0], steps[0], steps[1]}; if (!run_binary_simd_multiply_@TYPE@(margs, dimensions, msteps)) { UNARY_LOOP { const @type@ in1 = *(@type@ *)ip1; *((@type@ *)op1) = in1*in1; } } } NPY_NO_EXPORT void @TYPE@_reciprocal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)) { @type@ one = 1.@c@; char * margs[] = {(char*)&one, args[0], args[1]}; npy_intp msteps[] = {0, steps[0], steps[1]}; if (!run_binary_simd_divide_@TYPE@(margs, dimensions, msteps)) { UNARY_LOOP { const @type@ in1 = *(@type@ *)ip1; *((@type@ *)op1) = 1/in1; } } } NPY_NO_EXPORT void @TYPE@__ones_like(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)) { OUTPUT_LOOP { *((@type@ *)op1) = 1; } } NPY_NO_EXPORT void @TYPE@_conjugate(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { UNARY_LOOP { const @type@ in1 = *(@type@ *)ip1; *((@type@ *)op1) = in1; } } NPY_NO_EXPORT void @TYPE@_absolute(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { if (!run_unary_simd_absolute_@TYPE@(args, dimensions, steps)) { UNARY_LOOP { const @type@ in1 = *(@type@ *)ip1; const @type@ tmp = in1 > 0 ? in1 : -in1; /* add 0 to clear -0.0 */ *((@type@ *)op1) = tmp + 0; } } } 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; } } NPY_NO_EXPORT void @TYPE@_sign(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { /* Sign of nan is nan */ UNARY_LOOP { const @type@ in1 = *(@type@ *)ip1; *((@type@ *)op1) = in1 > 0 ? 1 : (in1 < 0 ? -1 : (in1 == 0 ? 0 : in1)); } } NPY_NO_EXPORT void @TYPE@_modf(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { UNARY_LOOP_TWO_OUT { const @type@ in1 = *(@type@ *)ip1; *((@type@ *)op1) = npy_modf@c@(in1, (@type@ *)op2); } } #ifdef HAVE_FREXP@C@ NPY_NO_EXPORT void @TYPE@_frexp(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { UNARY_LOOP_TWO_OUT { const @type@ in1 = *(@type@ *)ip1; *((@type@ *)op1) = frexp@c@(in1, (int *)op2); } } #endif #ifdef HAVE_LDEXP@C@ NPY_NO_EXPORT void @TYPE@_ldexp(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { BINARY_LOOP { const @type@ in1 = *(@type@ *)ip1; const int in2 = *(int *)ip2; *((@type@ *)op1) = ldexp@c@(in1, in2); } } NPY_NO_EXPORT void @TYPE@_ldexp_long(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { /* * Additional loop to handle npy_long integer inputs (cf. #866, #1633). * npy_long != npy_int on many 64-bit platforms, so we need this second loop * to handle the default integer type. */ BINARY_LOOP { const @type@ in1 = *(@type@ *)ip1; const long in2 = *(long *)ip2; if (((int)in2) == in2) { /* Range OK */ *((@type@ *)op1) = ldexp@c@(in1, ((int)in2)); } else { /* * Outside npy_int range -- also ldexp will overflow in this case, * given that exponent has less bits than npy_int. */ if (in2 > 0) { *((@type@ *)op1) = ldexp@c@(in1, NPY_MAX_INT); } else { *((@type@ *)op1) = ldexp@c@(in1, NPY_MIN_INT); } } } } #endif #define @TYPE@_true_divide @TYPE@_divide /**end repeat**/ /* ***************************************************************************** ** HALF-FLOAT LOOPS ** ***************************************************************************** */ /**begin repeat * Arithmetic * # kind = add, subtract, multiply, divide# * # OP = +, -, *, /# */ 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); BINARY_REDUCE_LOOP_INNER { io1 @OP@= npy_half_to_float(*(npy_half *)ip2); } *((npy_half *)iop1) = npy_float_to_half(io1); } else { BINARY_LOOP { const float in1 = npy_half_to_float(*(npy_half *)ip1); const float in2 = npy_half_to_float(*(npy_half *)ip2); *((npy_half *)op1) = npy_float_to_half(in1 @OP@ in2); } } } /**end repeat**/ #define _HALF_LOGICAL_AND(a,b) (!npy_half_iszero(a) && !npy_half_iszero(b)) #define _HALF_LOGICAL_OR(a,b) (!npy_half_iszero(a) || !npy_half_iszero(b)) /**begin repeat * #kind = equal, not_equal, less, less_equal, greater, * greater_equal, logical_and, logical_or# * #OP = npy_half_eq, npy_half_ne, npy_half_lt, npy_half_le, npy_half_gt, * npy_half_ge, _HALF_LOGICAL_AND, _HALF_LOGICAL_OR# */ NPY_NO_EXPORT void HALF_@kind@(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { BINARY_LOOP { const npy_half in1 = *(npy_half *)ip1; const npy_half in2 = *(npy_half *)ip2; *((npy_bool *)op1) = @OP@(in1, in2); } } /**end repeat**/ #undef _HALF_LOGICAL_AND #undef _HALF_LOGICAL_OR NPY_NO_EXPORT void HALF_logical_xor(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { BINARY_LOOP { const int in1 = !npy_half_iszero(*(npy_half *)ip1); const int in2 = !npy_half_iszero(*(npy_half *)ip2); *((npy_bool *)op1)= (in1 && !in2) || (!in1 && in2); } } NPY_NO_EXPORT void HALF_logical_not(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { UNARY_LOOP { const npy_half in1 = *(npy_half *)ip1; *((npy_bool *)op1) = npy_half_iszero(in1); } } /**begin repeat * #kind = isnan, isinf, isfinite, signbit# * #func = npy_half_isnan, npy_half_isinf, npy_half_isfinite, npy_half_signbit# **/ NPY_NO_EXPORT void HALF_@kind@(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { UNARY_LOOP { const npy_half in1 = *(npy_half *)ip1; *((npy_bool *)op1) = @func@(in1) != 0; } } /**end repeat**/ NPY_NO_EXPORT void HALF_spacing(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { UNARY_LOOP { const npy_half in1 = *(npy_half *)ip1; *((npy_half *)op1) = npy_half_spacing(in1); } } NPY_NO_EXPORT void HALF_copysign(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { BINARY_LOOP { const npy_half in1 = *(npy_half *)ip1; const npy_half in2 = *(npy_half *)ip2; *((npy_half *)op1)= npy_half_copysign(in1, in2); } } NPY_NO_EXPORT void HALF_nextafter(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { BINARY_LOOP { const npy_half in1 = *(npy_half *)ip1; const npy_half in2 = *(npy_half *)ip2; *((npy_half *)op1)= npy_half_nextafter(in1, in2); } } /**begin repeat * #kind = maximum, minimum# * #OP = npy_half_ge, npy_half_le# **/ NPY_NO_EXPORT void HALF_@kind@(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { /* */ BINARY_LOOP { const npy_half in1 = *(npy_half *)ip1; const npy_half in2 = *(npy_half *)ip2; *((npy_half *)op1) = (@OP@(in1, in2) || npy_half_isnan(in1)) ? in1 : in2; } } /**end repeat**/ /**begin repeat * #kind = fmax, fmin# * #OP = npy_half_ge, npy_half_le# **/ NPY_NO_EXPORT void HALF_@kind@(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { /* */ BINARY_LOOP { const npy_half in1 = *(npy_half *)ip1; const npy_half in2 = *(npy_half *)ip2; *((npy_half *)op1) = (@OP@(in1, in2) || npy_half_isnan(in2)) ? in1 : in2; } } /**end repeat**/ NPY_NO_EXPORT void HALF_floor_divide(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { BINARY_LOOP { const float in1 = npy_half_to_float(*(npy_half *)ip1); const float in2 = npy_half_to_float(*(npy_half *)ip2); *((npy_half *)op1) = npy_float_to_half(npy_floorf(in1/in2)); } } NPY_NO_EXPORT void HALF_remainder(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { BINARY_LOOP { const float in1 = npy_half_to_float(*(npy_half *)ip1); const float in2 = npy_half_to_float(*(npy_half *)ip2); const float res = npy_fmodf(in1,in2); if (res && ((in2 < 0) != (res < 0))) { *((npy_half *)op1) = npy_float_to_half(res + in2); } else { *((npy_half *)op1) = npy_float_to_half(res); } } } NPY_NO_EXPORT void HALF_square(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)) { UNARY_LOOP { const float in1 = npy_half_to_float(*(npy_half *)ip1); *((npy_half *)op1) = npy_float_to_half(in1*in1); } } NPY_NO_EXPORT void HALF_reciprocal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)) { UNARY_LOOP { const float in1 = npy_half_to_float(*(npy_half *)ip1); *((npy_half *)op1) = npy_float_to_half(1/in1); } } NPY_NO_EXPORT void HALF__ones_like(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)) { OUTPUT_LOOP { *((npy_half *)op1) = NPY_HALF_ONE; } } NPY_NO_EXPORT void HALF_conjugate(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { UNARY_LOOP { const npy_half in1 = *(npy_half *)ip1; *((npy_half *)op1) = in1; } } NPY_NO_EXPORT void HALF_absolute(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { UNARY_LOOP { const npy_half in1 = *(npy_half *)ip1; *((npy_half *)op1) = in1&0x7fffu; } } NPY_NO_EXPORT void HALF_negative(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { UNARY_LOOP { const npy_half in1 = *(npy_half *)ip1; *((npy_half *)op1) = in1^0x8000u; } } NPY_NO_EXPORT void HALF_sign(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { /* Sign of nan is nan */ UNARY_LOOP { const npy_half in1 = *(npy_half *)ip1; *((npy_half *)op1) = npy_half_isnan(in1) ? in1 : (((in1&0x7fffu) == 0) ? 0 : (((in1&0x8000u) == 0) ? NPY_HALF_ONE : NPY_HALF_NEGONE)); } } NPY_NO_EXPORT void HALF_modf(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { float temp; UNARY_LOOP_TWO_OUT { const float in1 = npy_half_to_float(*(npy_half *)ip1); *((npy_half *)op1) = npy_float_to_half(npy_modff(in1, &temp)); *((npy_half *)op2) = npy_float_to_half(temp); } } #ifdef HAVE_FREXPF NPY_NO_EXPORT void HALF_frexp(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { UNARY_LOOP_TWO_OUT { const float in1 = npy_half_to_float(*(npy_half *)ip1); *((npy_half *)op1) = npy_float_to_half(frexpf(in1, (int *)op2)); } } #endif #ifdef HAVE_LDEXPF NPY_NO_EXPORT void HALF_ldexp(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { BINARY_LOOP { const float in1 = npy_half_to_float(*(npy_half *)ip1); const int in2 = *(int *)ip2; *((npy_half *)op1) = npy_float_to_half(ldexpf(in1, in2)); } } NPY_NO_EXPORT void HALF_ldexp_long(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { /* * Additional loop to handle npy_long integer inputs (cf. #866, #1633). * npy_long != npy_int on many 64-bit platforms, so we need this second loop * to handle the default integer type. */ BINARY_LOOP { const float in1 = npy_half_to_float(*(npy_half *)ip1); const long in2 = *(long *)ip2; if (((int)in2) == in2) { /* Range OK */ *((npy_half *)op1) = npy_float_to_half(ldexpf(in1, ((int)in2))); } else { /* * Outside npy_int range -- also ldexp will overflow in this case, * given that exponent has less bits than npy_int. */ if (in2 > 0) { *((npy_half *)op1) = npy_float_to_half(ldexpf(in1, NPY_MAX_INT)); } else { *((npy_half *)op1) = npy_float_to_half(ldexpf(in1, NPY_MIN_INT)); } } } } #endif #define HALF_true_divide HALF_divide /* ***************************************************************************** ** COMPLEX LOOPS ** ***************************************************************************** */ #define CGE(xr,xi,yr,yi) ((xr > yr && !npy_isnan(xi) && !npy_isnan(yi)) \ || (xr == yr && xi >= yi)) #define CLE(xr,xi,yr,yi) ((xr < yr && !npy_isnan(xi) && !npy_isnan(yi)) \ || (xr == yr && xi <= yi)) #define CGT(xr,xi,yr,yi) ((xr > yr && !npy_isnan(xi) && !npy_isnan(yi)) \ || (xr == yr && xi > yi)) #define CLT(xr,xi,yr,yi) ((xr < yr && !npy_isnan(xi) && !npy_isnan(yi)) \ || (xr == yr && xi < yi)) #define CEQ(xr,xi,yr,yi) (xr == yr && xi == yi) #define CNE(xr,xi,yr,yi) (xr != yr || xi != yi) /**begin repeat * complex types * #TYPE = CFLOAT, CDOUBLE, CLONGDOUBLE# * #ftype = npy_float, npy_double, npy_longdouble# * #c = f, , l# * #C = F, , L# */ /**begin repeat1 * arithmetic * #kind = add, subtract# * #OP = +, -# */ NPY_NO_EXPORT void @TYPE@_@kind@(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { BINARY_LOOP { const @ftype@ in1r = ((@ftype@ *)ip1)[0]; const @ftype@ in1i = ((@ftype@ *)ip1)[1]; const @ftype@ in2r = ((@ftype@ *)ip2)[0]; const @ftype@ in2i = ((@ftype@ *)ip2)[1]; ((@ftype@ *)op1)[0] = in1r @OP@ in2r; ((@ftype@ *)op1)[1] = in1i @OP@ in2i; } } /**end repeat1**/ NPY_NO_EXPORT void @TYPE@_multiply(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { BINARY_LOOP { const @ftype@ in1r = ((@ftype@ *)ip1)[0]; const @ftype@ in1i = ((@ftype@ *)ip1)[1]; const @ftype@ in2r = ((@ftype@ *)ip2)[0]; const @ftype@ in2i = ((@ftype@ *)ip2)[1]; ((@ftype@ *)op1)[0] = in1r*in2r - in1i*in2i; ((@ftype@ *)op1)[1] = in1r*in2i + in1i*in2r; } } NPY_NO_EXPORT void @TYPE@_divide(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { BINARY_LOOP { const @ftype@ in1r = ((@ftype@ *)ip1)[0]; const @ftype@ in1i = ((@ftype@ *)ip1)[1]; const @ftype@ in2r = ((@ftype@ *)ip2)[0]; const @ftype@ in2i = ((@ftype@ *)ip2)[1]; const @ftype@ in2r_abs = npy_fabs@c@(in2r); const @ftype@ in2i_abs = npy_fabs@c@(in2i); if (in2r_abs >= in2i_abs) { if (in2r_abs == 0 && in2i_abs == 0) { /* divide by zero should yield a complex inf or nan */ ((@ftype@ *)op1)[0] = in1r/in2r_abs; ((@ftype@ *)op1)[1] = in1i/in2i_abs; } else { const @ftype@ rat = in2i/in2r; const @ftype@ scl = 1.0@c@/(in2r + in2i*rat); ((@ftype@ *)op1)[0] = (in1r + in1i*rat)*scl; ((@ftype@ *)op1)[1] = (in1i - in1r*rat)*scl; } } else { const @ftype@ rat = in2r/in2i; const @ftype@ scl = 1.0@c@/(in2i + in2r*rat); ((@ftype@ *)op1)[0] = (in1r*rat + in1i)*scl; ((@ftype@ *)op1)[1] = (in1i*rat - in1r)*scl; } } } NPY_NO_EXPORT void @TYPE@_floor_divide(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { BINARY_LOOP { const @ftype@ in1r = ((@ftype@ *)ip1)[0]; const @ftype@ in1i = ((@ftype@ *)ip1)[1]; const @ftype@ in2r = ((@ftype@ *)ip2)[0]; const @ftype@ in2i = ((@ftype@ *)ip2)[1]; if (npy_fabs@c@(in2r) >= npy_fabs@c@(in2i)) { const @ftype@ rat = in2i/in2r; ((@ftype@ *)op1)[0] = npy_floor@c@((in1r + in1i*rat)/(in2r + in2i*rat)); ((@ftype@ *)op1)[1] = 0; } else { const @ftype@ rat = in2r/in2i; ((@ftype@ *)op1)[0] = npy_floor@c@((in1r*rat + in1i)/(in2i + in2r*rat)); ((@ftype@ *)op1)[1] = 0; } } } /**begin repeat1 * #kind= greater, greater_equal, less, less_equal, equal, not_equal# * #OP = CGT, CGE, CLT, CLE, CEQ, CNE# */ NPY_NO_EXPORT void @TYPE@_@kind@(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { BINARY_LOOP { const @ftype@ in1r = ((@ftype@ *)ip1)[0]; const @ftype@ in1i = ((@ftype@ *)ip1)[1]; const @ftype@ in2r = ((@ftype@ *)ip2)[0]; const @ftype@ in2i = ((@ftype@ *)ip2)[1]; *((npy_bool *)op1) = @OP@(in1r,in1i,in2r,in2i); } } /**end repeat1**/ /**begin repeat1 #kind = logical_and, logical_or# #OP1 = ||, ||# #OP2 = &&, ||# */ NPY_NO_EXPORT void @TYPE@_@kind@(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { BINARY_LOOP { const @ftype@ in1r = ((@ftype@ *)ip1)[0]; const @ftype@ in1i = ((@ftype@ *)ip1)[1]; const @ftype@ in2r = ((@ftype@ *)ip2)[0]; const @ftype@ in2i = ((@ftype@ *)ip2)[1]; *((npy_bool *)op1) = (in1r @OP1@ in1i) @OP2@ (in2r @OP1@ in2i); } } /**end repeat1**/ NPY_NO_EXPORT void @TYPE@_logical_xor(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { BINARY_LOOP { const @ftype@ in1r = ((@ftype@ *)ip1)[0]; const @ftype@ in1i = ((@ftype@ *)ip1)[1]; const @ftype@ in2r = ((@ftype@ *)ip2)[0]; const @ftype@ in2i = ((@ftype@ *)ip2)[1]; const npy_bool tmp1 = (in1r || in1i); const npy_bool tmp2 = (in2r || in2i); *((npy_bool *)op1) = (tmp1 && !tmp2) || (!tmp1 && tmp2); } } NPY_NO_EXPORT void @TYPE@_logical_not(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { UNARY_LOOP { const @ftype@ in1r = ((@ftype@ *)ip1)[0]; const @ftype@ in1i = ((@ftype@ *)ip1)[1]; *((npy_bool *)op1) = !(in1r || in1i); } } /**begin repeat1 * #kind = isnan, isinf, isfinite# * #func = npy_isnan, npy_isinf, npy_isfinite# * #OP = ||, ||, &&# **/ NPY_NO_EXPORT void @TYPE@_@kind@(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { UNARY_LOOP { const @ftype@ in1r = ((@ftype@ *)ip1)[0]; const @ftype@ in1i = ((@ftype@ *)ip1)[1]; *((npy_bool *)op1) = @func@(in1r) @OP@ @func@(in1i); } } /**end repeat1**/ NPY_NO_EXPORT void @TYPE@_square(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)) { UNARY_LOOP { const @ftype@ in1r = ((@ftype@ *)ip1)[0]; const @ftype@ in1i = ((@ftype@ *)ip1)[1]; ((@ftype@ *)op1)[0] = in1r*in1r - in1i*in1i; ((@ftype@ *)op1)[1] = in1r*in1i + in1i*in1r; } } NPY_NO_EXPORT void @TYPE@_reciprocal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)) { UNARY_LOOP { const @ftype@ in1r = ((@ftype@ *)ip1)[0]; const @ftype@ in1i = ((@ftype@ *)ip1)[1]; if (npy_fabs@c@(in1i) <= npy_fabs@c@(in1r)) { const @ftype@ r = in1i/in1r; const @ftype@ d = in1r + in1i*r; ((@ftype@ *)op1)[0] = 1/d; ((@ftype@ *)op1)[1] = -r/d; } else { const @ftype@ r = in1r/in1i; const @ftype@ d = in1r*r + in1i; ((@ftype@ *)op1)[0] = r/d; ((@ftype@ *)op1)[1] = -1/d; } } } NPY_NO_EXPORT void @TYPE@__ones_like(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)) { OUTPUT_LOOP { ((@ftype@ *)op1)[0] = 1; ((@ftype@ *)op1)[1] = 0; } } NPY_NO_EXPORT void @TYPE@_conjugate(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { UNARY_LOOP { const @ftype@ in1r = ((@ftype@ *)ip1)[0]; const @ftype@ in1i = ((@ftype@ *)ip1)[1]; ((@ftype@ *)op1)[0] = in1r; ((@ftype@ *)op1)[1] = -in1i; } } NPY_NO_EXPORT void @TYPE@_absolute(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { UNARY_LOOP { const @ftype@ in1r = ((@ftype@ *)ip1)[0]; const @ftype@ in1i = ((@ftype@ *)ip1)[1]; *((@ftype@ *)op1) = npy_hypot@c@(in1r, in1i); } } NPY_NO_EXPORT void @TYPE@__arg(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { UNARY_LOOP { const @ftype@ in1r = ((@ftype@ *)ip1)[0]; const @ftype@ in1i = ((@ftype@ *)ip1)[1]; *((@ftype@ *)op1) = npy_atan2@c@(in1i, in1r); } } NPY_NO_EXPORT void @TYPE@_sign(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { /* fixme: sign of nan is currently 0 */ UNARY_LOOP { const @ftype@ in1r = ((@ftype@ *)ip1)[0]; const @ftype@ in1i = ((@ftype@ *)ip1)[1]; ((@ftype@ *)op1)[0] = CGT(in1r, in1i, 0.0, 0.0) ? 1 : (CLT(in1r, in1i, 0.0, 0.0) ? -1 : (CEQ(in1r, in1i, 0.0, 0.0) ? 0 : NPY_NAN@C@)); ((@ftype@ *)op1)[1] = 0; } } /**begin repeat1 * #kind = maximum, minimum# * #OP = CGE, CLE# */ NPY_NO_EXPORT void @TYPE@_@kind@(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { BINARY_LOOP { const @ftype@ in1r = ((@ftype@ *)ip1)[0]; const @ftype@ in1i = ((@ftype@ *)ip1)[1]; const @ftype@ in2r = ((@ftype@ *)ip2)[0]; const @ftype@ in2i = ((@ftype@ *)ip2)[1]; if (@OP@(in1r, in1i, in2r, in2i) || npy_isnan(in1r) || npy_isnan(in1i)) { ((@ftype@ *)op1)[0] = in1r; ((@ftype@ *)op1)[1] = in1i; } else { ((@ftype@ *)op1)[0] = in2r; ((@ftype@ *)op1)[1] = in2i; } } } /**end repeat1**/ /**begin repeat1 * #kind = fmax, fmin# * #OP = CGE, CLE# */ NPY_NO_EXPORT void @TYPE@_@kind@(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { BINARY_LOOP { const @ftype@ in1r = ((@ftype@ *)ip1)[0]; const @ftype@ in1i = ((@ftype@ *)ip1)[1]; const @ftype@ in2r = ((@ftype@ *)ip2)[0]; const @ftype@ in2i = ((@ftype@ *)ip2)[1]; if (@OP@(in1r, in1i, in2r, in2i) || npy_isnan(in2r) || npy_isnan(in2i)) { ((@ftype@ *)op1)[0] = in1r; ((@ftype@ *)op1)[1] = in1i; } else { ((@ftype@ *)op1)[0] = in2r; ((@ftype@ *)op1)[1] = in2i; } } } /**end repeat1**/ #define @TYPE@_true_divide @TYPE@_divide /**end repeat**/ #undef CGE #undef CLE #undef CGT #undef CLT #undef CEQ #undef CNE /* ***************************************************************************** ** OBJECT LOOPS ** ***************************************************************************** */ /**begin repeat * #kind = equal, not_equal, greater, greater_equal, less, less_equal# * #OP = EQ, NE, GT, GE, LT, LE# */ NPY_NO_EXPORT void OBJECT_@kind@(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { BINARY_LOOP { PyObject *in1 = *(PyObject **)ip1; PyObject *in2 = *(PyObject **)ip2; int ret = PyObject_RichCompareBool( in1 ? in1 : Py_None, in2 ? in2 : Py_None, Py_@OP@); if (ret == -1) { return; } *((npy_bool *)op1) = (npy_bool)ret; } } /**end repeat**/ NPY_NO_EXPORT void OBJECT_sign(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)) { #if defined(NPY_PY3K) PyObject *zero = PyLong_FromLong(0); UNARY_LOOP { PyObject *in1 = *(PyObject **)ip1; PyObject **out = (PyObject **)op1; int v; PyObject *ret; PyObject_Cmp(in1 ? in1 : Py_None, zero, &v); ret = PyLong_FromLong(v); if (PyErr_Occurred()) { return; } Py_XDECREF(*out); *out = ret; } Py_DECREF(zero); #else PyObject *zero = PyInt_FromLong(0); UNARY_LOOP { PyObject *in1 = *(PyObject **)ip1; PyObject **out = (PyObject **)op1; PyObject *ret = PyInt_FromLong( PyObject_Compare(in1 ? in1 : Py_None, zero)); if (PyErr_Occurred()) { return; } Py_XDECREF(*out); *out = ret; } Py_DECREF(zero); #endif } /* ***************************************************************************** ** END LOOPS ** ***************************************************************************** */ numpy-1.8.2/numpy/core/src/multiarray/0000775000175100017510000000000012371375427021117 5ustar vagrantvagrant00000000000000numpy-1.8.2/numpy/core/src/multiarray/multiarray_tests.c.src0000664000175100017510000005516412370216243025464 0ustar vagrantvagrant00000000000000#define NPY_NO_DEPRECATED_API NPY_API_VERSION #include #include "numpy/arrayobject.h" #include "npy_pycompat.h" /* * TODO: * - Handle mode */ /**begin repeat * #name = double, int# * #type = npy_double, npy_int# * #typenum = NPY_DOUBLE, NPY_INT# */ static int copy_@name@(PyArrayIterObject *itx, PyArrayNeighborhoodIterObject *niterx, npy_intp *bounds, PyObject **out) { npy_intp i, j; @type@ *ptr; npy_intp odims[NPY_MAXDIMS]; PyArrayObject *aout; /* * For each point in itx, copy the current neighborhood into an array which * is appended at the output list */ for (i = 0; i < itx->size; ++i) { PyArrayNeighborhoodIter_Reset(niterx); for (j = 0; j < PyArray_NDIM(itx->ao); ++j) { odims[j] = bounds[2 * j + 1] - bounds[2 * j] + 1; } aout = (PyArrayObject*)PyArray_SimpleNew( PyArray_NDIM(itx->ao), odims, @typenum@); if (aout == NULL) { return -1; } ptr = (@type@*)PyArray_DATA(aout); for (j = 0; j < niterx->size; ++j) { *ptr = *((@type@*)niterx->dataptr); PyArrayNeighborhoodIter_Next(niterx); ptr += 1; } PyList_Append(*out, (PyObject*)aout); Py_DECREF(aout); PyArray_ITER_NEXT(itx); } return 0; } /**end repeat**/ static int copy_object(PyArrayIterObject *itx, PyArrayNeighborhoodIterObject *niterx, npy_intp *bounds, PyObject **out) { npy_intp i, j; npy_intp odims[NPY_MAXDIMS]; PyArrayObject *aout; PyArray_CopySwapFunc *copyswap = PyArray_DESCR(itx->ao)->f->copyswap; npy_int itemsize = PyArray_ITEMSIZE(itx->ao); /* * For each point in itx, copy the current neighborhood into an array which * is appended at the output list */ for (i = 0; i < itx->size; ++i) { PyArrayNeighborhoodIter_Reset(niterx); for (j = 0; j < PyArray_NDIM(itx->ao); ++j) { odims[j] = bounds[2 * j + 1] - bounds[2 * j] + 1; } aout = (PyArrayObject*)PyArray_SimpleNew(PyArray_NDIM(itx->ao), odims, NPY_OBJECT); if (aout == NULL) { return -1; } for (j = 0; j < niterx->size; ++j) { copyswap(PyArray_BYTES(aout) + j * itemsize, niterx->dataptr, 0, NULL); PyArrayNeighborhoodIter_Next(niterx); } PyList_Append(*out, (PyObject*)aout); Py_DECREF(aout); PyArray_ITER_NEXT(itx); } return 0; } static PyObject* test_neighborhood_iterator(PyObject* NPY_UNUSED(self), PyObject* args) { PyObject *x, *fill, *out, *b; PyArrayObject *ax, *afill; PyArrayIterObject *itx; int i, typenum, mode, st; npy_intp bounds[NPY_MAXDIMS*2]; PyArrayNeighborhoodIterObject *niterx; if (!PyArg_ParseTuple(args, "OOOi", &x, &b, &fill, &mode)) { return NULL; } if (!PySequence_Check(b)) { return NULL; } typenum = PyArray_ObjectType(x, 0); typenum = PyArray_ObjectType(fill, typenum); ax = (PyArrayObject*)PyArray_FromObject(x, typenum, 1, 10); if (ax == NULL) { return NULL; } if (PySequence_Size(b) != 2 * PyArray_NDIM(ax)) { PyErr_SetString(PyExc_ValueError, "bounds sequence size not compatible with x input"); goto clean_ax; } out = PyList_New(0); if (out == NULL) { goto clean_ax; } itx = (PyArrayIterObject*)PyArray_IterNew(x); if (itx == NULL) { goto clean_out; } /* Compute boundaries for the neighborhood iterator */ for (i = 0; i < 2 * PyArray_NDIM(ax); ++i) { PyObject* bound; bound = PySequence_GetItem(b, i); if (bounds == NULL) { goto clean_itx; } if (!PyInt_Check(bound)) { PyErr_SetString(PyExc_ValueError, "bound not long"); Py_DECREF(bound); goto clean_itx; } bounds[i] = PyInt_AsLong(bound); Py_DECREF(bound); } /* Create the neighborhood iterator */ afill = NULL; if (mode == NPY_NEIGHBORHOOD_ITER_CONSTANT_PADDING) { afill = (PyArrayObject *)PyArray_FromObject(fill, typenum, 0, 0); if (afill == NULL) { goto clean_itx; } } niterx = (PyArrayNeighborhoodIterObject*)PyArray_NeighborhoodIterNew( (PyArrayIterObject*)itx, bounds, mode, afill); if (niterx == NULL) { goto clean_afill; } switch (typenum) { case NPY_OBJECT: st = copy_object(itx, niterx, bounds, &out); break; case NPY_INT: st = copy_int(itx, niterx, bounds, &out); break; case NPY_DOUBLE: st = copy_double(itx, niterx, bounds, &out); break; default: PyErr_SetString(PyExc_ValueError, "Type not supported"); goto clean_niterx; } if (st) { goto clean_niterx; } Py_DECREF(niterx); Py_XDECREF(afill); Py_DECREF(itx); Py_DECREF(ax); return out; clean_niterx: Py_DECREF(niterx); clean_afill: Py_XDECREF(afill); clean_itx: Py_DECREF(itx); clean_out: Py_DECREF(out); clean_ax: Py_DECREF(ax); return NULL; } static int copy_double_double(PyArrayNeighborhoodIterObject *itx, PyArrayNeighborhoodIterObject *niterx, npy_intp *bounds, PyObject **out) { npy_intp i, j; double *ptr; npy_intp odims[NPY_MAXDIMS]; PyArrayObject *aout; /* * For each point in itx, copy the current neighborhood into an array which * is appended at the output list */ PyArrayNeighborhoodIter_Reset(itx); for (i = 0; i < itx->size; ++i) { for (j = 0; j < PyArray_NDIM(itx->ao); ++j) { odims[j] = bounds[2 * j + 1] - bounds[2 * j] + 1; } aout = (PyArrayObject*)PyArray_SimpleNew( PyArray_NDIM(itx->ao), odims, NPY_DOUBLE); if (aout == NULL) { return -1; } ptr = (double*)PyArray_DATA(aout); PyArrayNeighborhoodIter_Reset(niterx); for (j = 0; j < niterx->size; ++j) { *ptr = *((double*)niterx->dataptr); ptr += 1; PyArrayNeighborhoodIter_Next(niterx); } PyList_Append(*out, (PyObject*)aout); Py_DECREF(aout); PyArrayNeighborhoodIter_Next(itx); } return 0; } static PyObject* test_neighborhood_iterator_oob(PyObject* NPY_UNUSED(self), PyObject* args) { PyObject *x, *out, *b1, *b2; PyArrayObject *ax; PyArrayIterObject *itx; int i, typenum, mode1, mode2, st; npy_intp bounds[NPY_MAXDIMS*2]; PyArrayNeighborhoodIterObject *niterx1, *niterx2; if (!PyArg_ParseTuple(args, "OOiOi", &x, &b1, &mode1, &b2, &mode2)) { return NULL; } if (!PySequence_Check(b1) || !PySequence_Check(b2)) { return NULL; } typenum = PyArray_ObjectType(x, 0); ax = (PyArrayObject*)PyArray_FromObject(x, typenum, 1, 10); if (ax == NULL) { return NULL; } if (PySequence_Size(b1) != 2 * PyArray_NDIM(ax)) { PyErr_SetString(PyExc_ValueError, "bounds sequence 1 size not compatible with x input"); goto clean_ax; } if (PySequence_Size(b2) != 2 * PyArray_NDIM(ax)) { PyErr_SetString(PyExc_ValueError, "bounds sequence 2 size not compatible with x input"); goto clean_ax; } out = PyList_New(0); if (out == NULL) { goto clean_ax; } itx = (PyArrayIterObject*)PyArray_IterNew(x); if (itx == NULL) { goto clean_out; } /* Compute boundaries for the neighborhood iterator */ for (i = 0; i < 2 * PyArray_NDIM(ax); ++i) { PyObject* bound; bound = PySequence_GetItem(b1, i); if (bounds == NULL) { goto clean_itx; } if (!PyInt_Check(bound)) { PyErr_SetString(PyExc_ValueError, "bound not long"); Py_DECREF(bound); goto clean_itx; } bounds[i] = PyInt_AsLong(bound); Py_DECREF(bound); } /* Create the neighborhood iterator */ niterx1 = (PyArrayNeighborhoodIterObject*)PyArray_NeighborhoodIterNew( (PyArrayIterObject*)itx, bounds, mode1, NULL); if (niterx1 == NULL) { goto clean_out; } for (i = 0; i < 2 * PyArray_NDIM(ax); ++i) { PyObject* bound; bound = PySequence_GetItem(b2, i); if (bounds == NULL) { goto clean_itx; } if (!PyInt_Check(bound)) { PyErr_SetString(PyExc_ValueError, "bound not long"); Py_DECREF(bound); goto clean_itx; } bounds[i] = PyInt_AsLong(bound); Py_DECREF(bound); } niterx2 = (PyArrayNeighborhoodIterObject*)PyArray_NeighborhoodIterNew( (PyArrayIterObject*)niterx1, bounds, mode2, NULL); if (niterx1 == NULL) { goto clean_niterx1; } switch (typenum) { case NPY_DOUBLE: st = copy_double_double(niterx1, niterx2, bounds, &out); break; default: PyErr_SetString(PyExc_ValueError, "Type not supported"); goto clean_niterx2; } if (st) { goto clean_niterx2; } Py_DECREF(niterx2); Py_DECREF(niterx1); Py_DECREF(itx); Py_DECREF(ax); return out; clean_niterx2: Py_DECREF(niterx2); clean_niterx1: Py_DECREF(niterx1); clean_itx: Py_DECREF(itx); clean_out: Py_DECREF(out); clean_ax: Py_DECREF(ax); return NULL; } /* PyDataMem_SetHook tests */ static int malloc_free_counts[2]; static PyDataMem_EventHookFunc *old_hook = NULL; static void *old_data; static void test_hook(void *old, void *new, size_t size, void *user_data) { int* counters = (int *) user_data; if (old == NULL) { counters[0]++; /* malloc counter */ } if (size == 0) { counters[1]++; /* free counter */ } } static PyObject* test_pydatamem_seteventhook_start(PyObject* NPY_UNUSED(self), PyObject* NPY_UNUSED(args)) { malloc_free_counts[0] = malloc_free_counts[1] = 0; old_hook = PyDataMem_SetEventHook(test_hook, (void *) malloc_free_counts, &old_data); Py_INCREF(Py_None); return Py_None; } static PyObject* test_pydatamem_seteventhook_end(PyObject* NPY_UNUSED(self), PyObject* NPY_UNUSED(args)) { PyDataMem_EventHookFunc *my_hook; void *my_data; my_hook = PyDataMem_SetEventHook(old_hook, old_data, &my_data); if ((my_hook != test_hook) || (my_data != (void *) malloc_free_counts)) { PyErr_SetString(PyExc_ValueError, "hook/data was not the expected test hook"); return NULL; } if (malloc_free_counts[0] == 0) { PyErr_SetString(PyExc_ValueError, "malloc count is zero after test"); return NULL; } if (malloc_free_counts[1] == 0) { PyErr_SetString(PyExc_ValueError, "free count is zero after test"); return NULL; } Py_INCREF(Py_None); return Py_None; } typedef void (*inplace_map_binop)(PyArrayMapIterObject *, PyArrayIterObject *); static void npy_float64_inplace_add(PyArrayMapIterObject *mit, PyArrayIterObject *it) { int index = mit->size; while (index--) { ((npy_float64*)mit->dataptr)[0] = ((npy_float64*)mit->dataptr)[0] + ((npy_float64*)it->dataptr)[0]; PyArray_MapIterNext(mit); PyArray_ITER_NEXT(it); } } inplace_map_binop addition_funcs[] = { npy_float64_inplace_add, NULL}; int type_numbers[] = { NPY_FLOAT64, -1000}; static int map_increment(PyArrayMapIterObject *mit, PyObject *op, inplace_map_binop add_inplace) { PyArrayObject *arr = NULL; PyArrayIterObject *it; PyArray_Descr *descr; 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 ((mit->subspace != NULL) && (mit->consec)) { PyArray_MapIterSwapAxes(mit, (PyArrayObject **)&arr, 0); if (arr == NULL) { return -1; } } if ((it = (PyArrayIterObject *)\ PyArray_BroadcastToShape((PyObject *)arr, mit->dimensions, mit->nd)) == NULL) { Py_DECREF(arr); return -1; } (*add_inplace)(mit, it); Py_DECREF(arr); Py_DECREF(it); return 0; } static PyObject * inplace_increment(PyObject *dummy, PyObject *args) { PyObject *arg_a = NULL, *index=NULL, *inc=NULL; PyArrayObject *a; inplace_map_binop add_inplace = NULL; int type_number = -1; int i =0; PyArrayMapIterObject * mit; if (!PyArg_ParseTuple(args, "OOO", &arg_a, &index, &inc)) { return NULL; } if (!PyArray_Check(arg_a)) { PyErr_SetString(PyExc_ValueError, "needs an ndarray as first argument"); return NULL; } a = (PyArrayObject *) arg_a; if (PyArray_FailUnlessWriteable(a, "input/output array") < 0) { return NULL; } if (PyArray_NDIM(a) == 0) { PyErr_SetString(PyExc_IndexError, "0-d arrays can't be indexed."); return NULL; } type_number = PyArray_TYPE(a); while (type_numbers[i] >= 0 && addition_funcs[i] != NULL){ if (type_number == type_numbers[i]) { add_inplace = addition_funcs[i]; break; } i++ ; } if (add_inplace == NULL) { PyErr_SetString(PyExc_TypeError, "unsupported type for a"); return NULL; } mit = (PyArrayMapIterObject *) PyArray_MapIterArray(a, index); if (mit == NULL) { goto fail; } if (map_increment(mit, inc, add_inplace) != 0) { goto fail; } Py_DECREF(mit); Py_INCREF(Py_None); return Py_None; fail: Py_XDECREF(mit); return NULL; } #if !defined(NPY_PY3K) static PyObject * int_subclass(PyObject *dummy, PyObject *args) { PyObject *result = NULL; PyObject *scalar_object = NULL; if (!PyArg_UnpackTuple(args, "test_int_subclass", 1, 1, &scalar_object)) return NULL; if (PyInt_Check(scalar_object)) result = Py_True; else result = Py_False; Py_INCREF(result); return result; } #endif /* * Create python string from a FLAG and or the corresponding PyBuf flag * for the use in get_buffer_info. */ #define GET_PYBUF_FLAG(FLAG) \ buf_flag = PyUnicode_FromString(#FLAG); \ flag_matches = PyObject_RichCompareBool(buf_flag, tmp, Py_EQ); \ Py_DECREF(buf_flag); \ if (flag_matches == 1) { \ Py_DECREF(tmp); \ flags |= PyBUF_##FLAG; \ continue; \ } \ else if (flag_matches == -1) { \ Py_DECREF(tmp); \ return NULL; \ } /* * Get information for a buffer through PyBuf_GetBuffer with the * corresponding flags or'ed. Note that the python caller has to * make sure that or'ing those flags actually makes sense. * More information should probably be returned for future tests. */ static PyObject * get_buffer_info(PyObject *NPY_UNUSED(self), PyObject *args) { PyObject *buffer_obj, *pyflags; PyObject *tmp, *buf_flag; Py_buffer buffer; PyObject *shape, *strides; Py_ssize_t i, n; int flag_matches; int flags = 0; if (!PyArg_ParseTuple(args, "OO", &buffer_obj, &pyflags)) { return NULL; } n = PySequence_Length(pyflags); if (n < 0) { return NULL; } for (i=0; i < n; i++) { tmp = PySequence_GetItem(pyflags, i); if (tmp == NULL) { return NULL; } GET_PYBUF_FLAG(SIMPLE); GET_PYBUF_FLAG(WRITABLE); GET_PYBUF_FLAG(STRIDES); GET_PYBUF_FLAG(ND); GET_PYBUF_FLAG(C_CONTIGUOUS); GET_PYBUF_FLAG(F_CONTIGUOUS); GET_PYBUF_FLAG(ANY_CONTIGUOUS); GET_PYBUF_FLAG(INDIRECT); GET_PYBUF_FLAG(FORMAT); GET_PYBUF_FLAG(STRIDED); GET_PYBUF_FLAG(STRIDED_RO); GET_PYBUF_FLAG(RECORDS); GET_PYBUF_FLAG(RECORDS_RO); GET_PYBUF_FLAG(FULL); GET_PYBUF_FLAG(FULL_RO); GET_PYBUF_FLAG(CONTIG); GET_PYBUF_FLAG(CONTIG_RO); Py_DECREF(tmp); /* One of the flags must match */ PyErr_SetString(PyExc_ValueError, "invalid flag used."); return NULL; } if (PyObject_GetBuffer(buffer_obj, &buffer, flags) < 0) { return NULL; } if (buffer.shape == NULL) { Py_INCREF(Py_None); shape = Py_None; } else { shape = PyTuple_New(buffer.ndim); for (i=0; i < buffer.ndim; i++) { PyTuple_SET_ITEM(shape, i, PyLong_FromSsize_t(buffer.shape[i])); } } if (buffer.strides == NULL) { Py_INCREF(Py_None); strides = Py_None; } else { strides = PyTuple_New(buffer.ndim); for (i=0; i < buffer.ndim; i++) { PyTuple_SET_ITEM(strides, i, PyLong_FromSsize_t(buffer.strides[i])); } } PyBuffer_Release(&buffer); return Py_BuildValue("(NN)", shape, strides); } #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, METH_VARARGS, NULL}, {"test_neighborhood_iterator_oob", test_neighborhood_iterator_oob, METH_VARARGS, NULL}, {"test_pydatamem_seteventhook_start", test_pydatamem_seteventhook_start, METH_NOARGS, NULL}, {"test_pydatamem_seteventhook_end", test_pydatamem_seteventhook_end, METH_NOARGS, NULL}, {"test_inplace_increment", inplace_increment, METH_VARARGS, NULL}, #if !defined(NPY_PY3K) {"test_int_subclass", int_subclass, METH_VARARGS, NULL}, #endif {"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 */ }; #if defined(NPY_PY3K) static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, "multiarray_tests", NULL, -1, Multiarray_TestsMethods, NULL, NULL, NULL, NULL }; #endif #if defined(NPY_PY3K) #define RETVAL m PyMODINIT_FUNC PyInit_multiarray_tests(void) #else #define RETVAL PyMODINIT_FUNC initmultiarray_tests(void) #endif { PyObject *m; #if defined(NPY_PY3K) m = PyModule_Create(&moduledef); #else m = Py_InitModule("multiarray_tests", Multiarray_TestsMethods); #endif if (m == NULL) { return RETVAL; } import_array(); if (PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError, "cannot load umath_tests module."); } return RETVAL; } numpy-1.8.2/numpy/core/src/multiarray/_datetime.h0000664000175100017510000003003512370216242023210 0ustar vagrantvagrant00000000000000#ifndef _NPY_PRIVATE__DATETIME_H_ #define _NPY_PRIVATE__DATETIME_H_ #ifdef NPY_ENABLE_SEPARATE_COMPILATION extern NPY_NO_EXPORT char *_datetime_strings[NPY_DATETIME_NUMUNITS]; extern NPY_NO_EXPORT int _days_per_month_table[2][12]; #else NPY_NO_EXPORT char *_datetime_strings[NPY_DATETIME_NUMUNITS]; NPY_NO_EXPORT int _days_per_month_table[2][12]; #endif NPY_NO_EXPORT void numpy_pydatetime_import(void); /* * Returns 1 if the given year is a leap year, 0 otherwise. */ NPY_NO_EXPORT int is_leapyear(npy_int64 year); /* * Calculates the days offset from the 1970 epoch. */ NPY_NO_EXPORT npy_int64 get_datetimestruct_days(const npy_datetimestruct *dts); /* * Creates a datetime or timedelta dtype using a copy of the provided metadata. */ NPY_NO_EXPORT PyArray_Descr * create_datetime_dtype(int type_num, PyArray_DatetimeMetaData *meta); /* * Creates a datetime or timedelta dtype using the given unit. */ NPY_NO_EXPORT PyArray_Descr * create_datetime_dtype_with_unit(int type_num, NPY_DATETIMEUNIT unit); /* * This function returns a pointer to the DateTimeMetaData * contained within the provided datetime dtype. */ NPY_NO_EXPORT PyArray_DatetimeMetaData * get_datetime_metadata_from_dtype(PyArray_Descr *dtype); /* * Both type1 and type2 must be either NPY_DATETIME or NPY_TIMEDELTA. * Applies the type promotion rules between the two types, returning * the promoted type. */ NPY_NO_EXPORT PyArray_Descr * datetime_type_promotion(PyArray_Descr *type1, PyArray_Descr *type2); /* * Converts a datetime from a datetimestruct to a datetime based * on some metadata. */ NPY_NO_EXPORT int convert_datetimestruct_to_datetime(PyArray_DatetimeMetaData *meta, const npy_datetimestruct *dts, npy_datetime *out); /* * Extracts the month number, within the current year, * from a 'datetime64[D]' value. January is 1, etc. */ NPY_NO_EXPORT int days_to_month_number(npy_datetime days); /* * Parses the metadata string into the metadata C structure. * * Returns 0 on success, -1 on failure. */ NPY_NO_EXPORT int parse_datetime_metadata_from_metastr(char *metastr, Py_ssize_t len, PyArray_DatetimeMetaData *out_meta); /* * Converts a datetype dtype string into a dtype descr object. * The "type" string should be NULL-terminated, and len should * contain its string length. */ NPY_NO_EXPORT PyArray_Descr * parse_dtype_from_datetime_typestr(char *typestr, Py_ssize_t len); /* * Converts a substring given by 'str' and 'len' into * a date time unit enum value. The 'metastr' parameter * is used for error messages, and may be NULL. * * Returns 0 on success, -1 on failure. */ NPY_NO_EXPORT NPY_DATETIMEUNIT parse_datetime_unit_from_string(char *str, Py_ssize_t len, char *metastr); /* * Translate divisors into multiples of smaller units. * 'metastr' is used for the error message if the divisor doesn't work, * and can be NULL if the metadata didn't come from a string. * * Returns 0 on success, -1 on failure. */ NPY_NO_EXPORT int convert_datetime_divisor_to_multiple(PyArray_DatetimeMetaData *meta, int den, char *metastr); /* * Determines whether the 'divisor' metadata divides evenly into * the 'dividend' metadata. */ NPY_NO_EXPORT npy_bool datetime_metadata_divides( PyArray_DatetimeMetaData *dividend, PyArray_DatetimeMetaData *divisor, int strict_with_nonlinear_units); /* * This provides the casting rules for the DATETIME data type units. * * Notably, there is a barrier between 'date units' and 'time units' * for all but 'unsafe' casting. */ NPY_NO_EXPORT npy_bool can_cast_datetime64_units(NPY_DATETIMEUNIT src_unit, NPY_DATETIMEUNIT dst_unit, NPY_CASTING casting); /* * This provides the casting rules for the DATETIME data type metadata. */ NPY_NO_EXPORT npy_bool can_cast_datetime64_metadata(PyArray_DatetimeMetaData *src_meta, PyArray_DatetimeMetaData *dst_meta, NPY_CASTING casting); /* * This provides the casting rules for the TIMEDELTA data type units. * * Notably, there is a barrier between the nonlinear years and * months units, and all the other units. */ NPY_NO_EXPORT npy_bool can_cast_timedelta64_units(NPY_DATETIMEUNIT src_unit, NPY_DATETIMEUNIT dst_unit, NPY_CASTING casting); /* * This provides the casting rules for the TIMEDELTA data type metadata. */ NPY_NO_EXPORT npy_bool can_cast_timedelta64_metadata(PyArray_DatetimeMetaData *src_meta, PyArray_DatetimeMetaData *dst_meta, NPY_CASTING casting); /* * Computes the conversion factor to convert data with 'src_meta' metadata * into data with 'dst_meta' metadata. * * If overflow occurs, both out_num and out_denom are set to 0, but * no error is set. */ NPY_NO_EXPORT void get_datetime_conversion_factor(PyArray_DatetimeMetaData *src_meta, PyArray_DatetimeMetaData *dst_meta, npy_int64 *out_num, npy_int64 *out_denom); /* * Given a pointer to datetime metadata, * returns a tuple for pickling and other purposes. */ NPY_NO_EXPORT PyObject * convert_datetime_metadata_to_tuple(PyArray_DatetimeMetaData *meta); /* * Converts a metadata tuple into a datetime metadata C struct. * * Returns 0 on success, -1 on failure. */ NPY_NO_EXPORT int convert_datetime_metadata_tuple_to_datetime_metadata(PyObject *tuple, PyArray_DatetimeMetaData *out_meta); /* * Gets a tzoffset in minutes by calling the fromutc() function on * the Python datetime.tzinfo object. */ NPY_NO_EXPORT int get_tzoffset_from_pytzinfo(PyObject *timezone, npy_datetimestruct *dts); /* * Converts an input object into datetime metadata. The input * may be either a string or a tuple. * * Returns 0 on success, -1 on failure. */ NPY_NO_EXPORT int convert_pyobject_to_datetime_metadata(PyObject *obj, PyArray_DatetimeMetaData *out_meta); /* * 'ret' is a PyUString containing the datetime string, and this * function appends the metadata string to it. * * If 'skip_brackets' is true, skips the '[]'. * * This function steals the reference 'ret' */ NPY_NO_EXPORT PyObject * append_metastr_to_string(PyArray_DatetimeMetaData *meta, int skip_brackets, PyObject *ret); /* * Tests for and converts a Python datetime.datetime or datetime.date * object into a NumPy npy_datetimestruct. * * 'out_bestunit' gives a suggested unit based on whether the object * was a datetime.date or datetime.datetime object. * * If 'apply_tzinfo' is 1, this function uses the tzinfo to convert * to UTC time, otherwise it returns the struct with the local time. * * Returns -1 on error, 0 on success, and 1 (with no error set) * if obj doesn't have the neeeded date or datetime attributes. */ NPY_NO_EXPORT int convert_pydatetime_to_datetimestruct(PyObject *obj, npy_datetimestruct *out, NPY_DATETIMEUNIT *out_bestunit, int apply_tzinfo); /* * Converts a PyObject * into a datetime, in any of the forms supported. * * If the units metadata isn't known ahead of time, set meta->base * to -1, and this function will populate meta with either default * values or values from the input object. * * The 'casting' parameter is used to control what kinds of inputs * are accepted, and what happens. For example, with 'unsafe' casting, * unrecognized inputs are converted to 'NaT' instead of throwing an error, * while with 'safe' casting an error will be thrown if any precision * from the input will be thrown away. * * Returns -1 on error, 0 on success. */ NPY_NO_EXPORT int convert_pyobject_to_datetime(PyArray_DatetimeMetaData *meta, PyObject *obj, NPY_CASTING casting, npy_datetime *out); /* * Converts a PyObject * into a timedelta, in any of the forms supported * * If the units metadata isn't known ahead of time, set meta->base * to -1, and this function will populate meta with either default * values or values from the input object. * * The 'casting' parameter is used to control what kinds of inputs * are accepted, and what happens. For example, with 'unsafe' casting, * unrecognized inputs are converted to 'NaT' instead of throwing an error, * while with 'safe' casting an error will be thrown if any precision * from the input will be thrown away. * * Returns -1 on error, 0 on success. */ NPY_NO_EXPORT int convert_pyobject_to_timedelta(PyArray_DatetimeMetaData *meta, PyObject *obj, NPY_CASTING casting, npy_timedelta *out); /* * Converts a datetime into a PyObject *. * * For days or coarser, returns a datetime.date. * For microseconds or coarser, returns a datetime.datetime. * For units finer than microseconds, returns an integer. */ NPY_NO_EXPORT PyObject * convert_datetime_to_pyobject(npy_datetime dt, PyArray_DatetimeMetaData *meta); /* * Converts a timedelta into a PyObject *. * * Not-a-time is returned as the string "NaT". * For microseconds or coarser, returns a datetime.timedelta. * For units finer than microseconds, returns an integer. */ NPY_NO_EXPORT PyObject * convert_timedelta_to_pyobject(npy_timedelta td, PyArray_DatetimeMetaData *meta); /* * Converts a datetime based on the given metadata into a datetimestruct */ NPY_NO_EXPORT int convert_datetime_to_datetimestruct(PyArray_DatetimeMetaData *meta, npy_datetime dt, npy_datetimestruct *out); /* * Converts a datetime from a datetimestruct to a datetime based * on some metadata. The date is assumed to be valid. * * TODO: If meta->num is really big, there could be overflow * * Returns 0 on success, -1 on failure. */ NPY_NO_EXPORT int convert_datetimestruct_to_datetime(PyArray_DatetimeMetaData *meta, const npy_datetimestruct *dts, npy_datetime *out); /* * Adjusts a datetimestruct based on a seconds offset. Assumes * the current values are valid. */ NPY_NO_EXPORT void add_seconds_to_datetimestruct(npy_datetimestruct *dts, int seconds); /* * Adjusts a datetimestruct based on a minutes offset. Assumes * the current values are valid. */ NPY_NO_EXPORT void add_minutes_to_datetimestruct(npy_datetimestruct *dts, int minutes); /* * Returns true if the datetime metadata matches */ NPY_NO_EXPORT npy_bool has_equivalent_datetime_metadata(PyArray_Descr *type1, PyArray_Descr *type2); /* * Casts a single datetime from having src_meta metadata into * dst_meta metadata. * * Returns 0 on success, -1 on failure. */ NPY_NO_EXPORT int cast_datetime_to_datetime(PyArray_DatetimeMetaData *src_meta, PyArray_DatetimeMetaData *dst_meta, npy_datetime src_dt, npy_datetime *dst_dt); /* * Casts a single timedelta from having src_meta metadata into * dst_meta metadata. * * Returns 0 on success, -1 on failure. */ NPY_NO_EXPORT int cast_timedelta_to_timedelta(PyArray_DatetimeMetaData *src_meta, PyArray_DatetimeMetaData *dst_meta, npy_timedelta src_dt, npy_timedelta *dst_dt); /* * Returns true if the object is something that is best considered * a Datetime or Timedelta, false otherwise. */ NPY_NO_EXPORT npy_bool is_any_numpy_datetime_or_timedelta(PyObject *obj); /* * Implements a datetime-specific arange */ NPY_NO_EXPORT PyArrayObject * datetime_arange(PyObject *start, PyObject *stop, PyObject *step, PyArray_Descr *dtype); /* * Examines all the objects in the given Python object by * recursively descending the sequence structure. Returns a * datetime or timedelta type with metadata based on the data. */ NPY_NO_EXPORT PyArray_Descr * find_object_datetime_type(PyObject *obj, int type_num); #endif numpy-1.8.2/numpy/core/src/multiarray/nditer_impl.h0000664000175100017510000002706012370216242023567 0ustar vagrantvagrant00000000000000/* * This is a PRIVATE INTERNAL NumPy header, intended to be used *ONLY* * by the iterator implementation code. All other internal NumPy code * should use the exposed iterator API. */ #ifndef NPY_ITERATOR_IMPLEMENTATION_CODE #error "This header is intended for use ONLY by iterator implementation code." #endif #ifndef _NPY_PRIVATE__NDITER_IMPL_H_ #define _NPY_PRIVATE__NDITER_IMPL_H_ #define PY_SSIZE_T_CLEAN #include "Python.h" #include "structmember.h" #define NPY_NO_DEPRECATED_API NPY_API_VERSION #define _MULTIARRAYMODULE #include #include #include "convert_datatype.h" #include "lowlevel_strided_loops.h" /********** ITERATOR CONSTRUCTION TIMING **************/ #define NPY_IT_CONSTRUCTION_TIMING 0 #if NPY_IT_CONSTRUCTION_TIMING #define NPY_IT_TIME_POINT(var) { \ unsigned int hi, lo; \ __asm__ __volatile__ ( \ "rdtsc" \ : "=d" (hi), "=a" (lo)); \ var = (((unsigned long long)hi) << 32) | lo; \ } #define NPY_IT_PRINT_TIME_START(var) { \ printf("%30s: start\n", #var); \ c_temp = var; \ } #define NPY_IT_PRINT_TIME_VAR(var) { \ printf("%30s: %6.0f clocks\n", #var, \ ((double)(var-c_temp))); \ c_temp = var; \ } #else #define NPY_IT_TIME_POINT(var) #endif /******************************************************/ /********** PRINTF DEBUG TRACING **************/ #define NPY_IT_DBG_TRACING 0 #if NPY_IT_DBG_TRACING #define NPY_IT_DBG_PRINT(s) printf("%s", s) #define NPY_IT_DBG_PRINT1(s, p1) printf(s, p1) #define NPY_IT_DBG_PRINT2(s, p1, p2) printf(s, p1, p2) #define NPY_IT_DBG_PRINT3(s, p1, p2, p3) printf(s, p1, p2, p3) #else #define NPY_IT_DBG_PRINT(s) #define NPY_IT_DBG_PRINT1(s, p1) #define NPY_IT_DBG_PRINT2(s, p1, p2) #define NPY_IT_DBG_PRINT3(s, p1, p2, p3) #endif /**********************************************/ /* Rounds up a number of bytes to be divisible by sizeof intp */ #if NPY_SIZEOF_INTP == 4 #define NPY_INTP_ALIGNED(size) ((size + 0x3)&(-0x4)) #else #define NPY_INTP_ALIGNED(size) ((size + 0x7)&(-0x8)) #endif /* Internal iterator flags */ /* The perm is the identity */ #define NPY_ITFLAG_IDENTPERM 0x0001 /* The perm has negative entries (indicating flipped axes) */ #define NPY_ITFLAG_NEGPERM 0x0002 /* The iterator is tracking an index */ #define NPY_ITFLAG_HASINDEX 0x0004 /* The iterator is tracking a multi-index */ #define NPY_ITFLAG_HASMULTIINDEX 0x0008 /* The iteration order was forced on construction */ #define NPY_ITFLAG_FORCEDORDER 0x0010 /* The inner loop is handled outside the iterator */ #define NPY_ITFLAG_EXLOOP 0x0020 /* The iterator is ranged */ #define NPY_ITFLAG_RANGE 0x0040 /* The iterator is buffered */ #define NPY_ITFLAG_BUFFER 0x0080 /* The iterator should grow the buffered inner loop when possible */ #define NPY_ITFLAG_GROWINNER 0x0100 /* There is just one iteration, can specialize iternext for that */ #define NPY_ITFLAG_ONEITERATION 0x0200 /* Delay buffer allocation until first Reset* call */ #define NPY_ITFLAG_DELAYBUF 0x0400 /* Iteration needs API access during iternext */ #define NPY_ITFLAG_NEEDSAPI 0x0800 /* Iteration includes one or more operands being reduced */ #define NPY_ITFLAG_REDUCE 0x1000 /* Reduce iteration doesn't need to recalculate reduce loops next time */ #define NPY_ITFLAG_REUSE_REDUCE_LOOPS 0x2000 /* Internal iterator per-operand iterator flags */ /* The operand will be written to */ #define NPY_OP_ITFLAG_WRITE 0x0001 /* The operand will be read from */ #define NPY_OP_ITFLAG_READ 0x0002 /* The operand needs type conversion/byte swapping/alignment */ #define NPY_OP_ITFLAG_CAST 0x0004 /* The operand never needs buffering */ #define NPY_OP_ITFLAG_BUFNEVER 0x0008 /* The operand is aligned */ #define NPY_OP_ITFLAG_ALIGNED 0x0010 /* The operand is being reduced */ #define NPY_OP_ITFLAG_REDUCE 0x0020 /* The operand is for temporary use, does not have a backing array */ #define NPY_OP_ITFLAG_VIRTUAL 0x0040 /* The operand requires masking when copying buffer -> array */ #define NPY_OP_ITFLAG_WRITEMASKED 0x0080 /* The operand's data pointer is pointing into its buffer */ #define NPY_OP_ITFLAG_USINGBUFFER 0x0100 /* * The data layout of the iterator is fully specified by * a triple (itflags, ndim, nop). These three variables * are expected to exist in all functions calling these macros, * either as true variables initialized to the correct values * from the iterator, or as constants in the case of specialized * functions such as the various iternext functions. */ struct NpyIter_InternalOnly { /* Initial fixed position data */ npy_uint32 itflags; npy_uint8 ndim, nop; npy_int8 maskop; npy_intp itersize, iterstart, iterend; /* iterindex is only used if RANGED or BUFFERED is set */ npy_intp iterindex; /* The rest is variable */ char iter_flexdata; }; typedef struct NpyIter_AD NpyIter_AxisData; typedef struct NpyIter_BD NpyIter_BufferData; typedef npy_int16 npyiter_opitflags; /* Byte sizes of the iterator members */ #define NIT_PERM_SIZEOF(itflags, ndim, nop) \ NPY_INTP_ALIGNED(NPY_MAXDIMS) #define NIT_DTYPES_SIZEOF(itflags, ndim, nop) \ ((NPY_SIZEOF_INTP)*(nop)) #define NIT_RESETDATAPTR_SIZEOF(itflags, ndim, nop) \ ((NPY_SIZEOF_INTP)*(nop+1)) #define NIT_BASEOFFSETS_SIZEOF(itflags, ndim, nop) \ ((NPY_SIZEOF_INTP)*(nop+1)) #define NIT_OPERANDS_SIZEOF(itflags, ndim, nop) \ ((NPY_SIZEOF_INTP)*(nop)) #define NIT_OPITFLAGS_SIZEOF(itflags, ndim, nop) \ (NPY_INTP_ALIGNED(sizeof(npyiter_opitflags) * nop)) #define NIT_BUFFERDATA_SIZEOF(itflags, ndim, nop) \ ((itflags&NPY_ITFLAG_BUFFER) ? ((NPY_SIZEOF_INTP)*(6 + 9*nop)) : 0) /* Byte offsets of the iterator members starting from iter->iter_flexdata */ #define NIT_PERM_OFFSET() \ (0) #define NIT_DTYPES_OFFSET(itflags, ndim, nop) \ (NIT_PERM_OFFSET() + \ NIT_PERM_SIZEOF(itflags, ndim, nop)) #define NIT_RESETDATAPTR_OFFSET(itflags, ndim, nop) \ (NIT_DTYPES_OFFSET(itflags, ndim, nop) + \ NIT_DTYPES_SIZEOF(itflags, ndim, nop)) #define NIT_BASEOFFSETS_OFFSET(itflags, ndim, nop) \ (NIT_RESETDATAPTR_OFFSET(itflags, ndim, nop) + \ NIT_RESETDATAPTR_SIZEOF(itflags, ndim, nop)) #define NIT_OPERANDS_OFFSET(itflags, ndim, nop) \ (NIT_BASEOFFSETS_OFFSET(itflags, ndim, nop) + \ NIT_BASEOFFSETS_SIZEOF(itflags, ndim, nop)) #define NIT_OPITFLAGS_OFFSET(itflags, ndim, nop) \ (NIT_OPERANDS_OFFSET(itflags, ndim, nop) + \ NIT_OPERANDS_SIZEOF(itflags, ndim, nop)) #define NIT_BUFFERDATA_OFFSET(itflags, ndim, nop) \ (NIT_OPITFLAGS_OFFSET(itflags, ndim, nop) + \ NIT_OPITFLAGS_SIZEOF(itflags, ndim, nop)) #define NIT_AXISDATA_OFFSET(itflags, ndim, nop) \ (NIT_BUFFERDATA_OFFSET(itflags, ndim, nop) + \ NIT_BUFFERDATA_SIZEOF(itflags, ndim, nop)) /* Internal-only ITERATOR DATA MEMBER ACCESS */ #define NIT_ITFLAGS(iter) \ ((iter)->itflags) #define NIT_NDIM(iter) \ ((iter)->ndim) #define NIT_NOP(iter) \ ((iter)->nop) #define NIT_MASKOP(iter) \ ((iter)->maskop) #define NIT_ITERSIZE(iter) \ (iter->itersize) #define NIT_ITERSTART(iter) \ (iter->iterstart) #define NIT_ITEREND(iter) \ (iter->iterend) #define NIT_ITERINDEX(iter) \ (iter->iterindex) #define NIT_PERM(iter) ((npy_int8 *)( \ &(iter)->iter_flexdata + NIT_PERM_OFFSET())) #define NIT_DTYPES(iter) ((PyArray_Descr **)( \ &(iter)->iter_flexdata + NIT_DTYPES_OFFSET(itflags, ndim, nop))) #define NIT_RESETDATAPTR(iter) ((char **)( \ &(iter)->iter_flexdata + NIT_RESETDATAPTR_OFFSET(itflags, ndim, nop))) #define NIT_BASEOFFSETS(iter) ((npy_intp *)( \ &(iter)->iter_flexdata + NIT_BASEOFFSETS_OFFSET(itflags, ndim, nop))) #define NIT_OPERANDS(iter) ((PyArrayObject **)( \ &(iter)->iter_flexdata + NIT_OPERANDS_OFFSET(itflags, ndim, nop))) #define NIT_OPITFLAGS(iter) ((npyiter_opitflags *)( \ &(iter)->iter_flexdata + NIT_OPITFLAGS_OFFSET(itflags, ndim, nop))) #define NIT_BUFFERDATA(iter) ((NpyIter_BufferData *)( \ &(iter)->iter_flexdata + NIT_BUFFERDATA_OFFSET(itflags, ndim, nop))) #define NIT_AXISDATA(iter) ((NpyIter_AxisData *)( \ &(iter)->iter_flexdata + NIT_AXISDATA_OFFSET(itflags, ndim, nop))) /* Internal-only BUFFERDATA MEMBER ACCESS */ struct NpyIter_BD { npy_intp buffersize, size, bufiterend, reduce_pos, reduce_outersize, reduce_outerdim; npy_intp bd_flexdata; }; #define NBF_BUFFERSIZE(bufferdata) ((bufferdata)->buffersize) #define NBF_SIZE(bufferdata) ((bufferdata)->size) #define NBF_BUFITEREND(bufferdata) ((bufferdata)->bufiterend) #define NBF_REDUCE_POS(bufferdata) ((bufferdata)->reduce_pos) #define NBF_REDUCE_OUTERSIZE(bufferdata) ((bufferdata)->reduce_outersize) #define NBF_REDUCE_OUTERDIM(bufferdata) ((bufferdata)->reduce_outerdim) #define NBF_STRIDES(bufferdata) ( \ &(bufferdata)->bd_flexdata + 0) #define NBF_PTRS(bufferdata) ((char **) \ (&(bufferdata)->bd_flexdata + 1*(nop))) #define NBF_REDUCE_OUTERSTRIDES(bufferdata) ( \ (&(bufferdata)->bd_flexdata + 2*(nop))) #define NBF_REDUCE_OUTERPTRS(bufferdata) ((char **) \ (&(bufferdata)->bd_flexdata + 3*(nop))) #define NBF_READTRANSFERFN(bufferdata) ((PyArray_StridedUnaryOp **) \ (&(bufferdata)->bd_flexdata + 4*(nop))) #define NBF_READTRANSFERDATA(bufferdata) ((NpyAuxData **) \ (&(bufferdata)->bd_flexdata + 5*(nop))) #define NBF_WRITETRANSFERFN(bufferdata) ((PyArray_StridedUnaryOp **) \ (&(bufferdata)->bd_flexdata + 6*(nop))) #define NBF_WRITETRANSFERDATA(bufferdata) ((NpyAuxData **) \ (&(bufferdata)->bd_flexdata + 7*(nop))) #define NBF_BUFFERS(bufferdata) ((char **) \ (&(bufferdata)->bd_flexdata + 8*(nop))) /* Internal-only AXISDATA MEMBER ACCESS. */ struct NpyIter_AD { npy_intp shape, index; npy_intp ad_flexdata; }; #define NAD_SHAPE(axisdata) ((axisdata)->shape) #define NAD_INDEX(axisdata) ((axisdata)->index) #define NAD_STRIDES(axisdata) ( \ &(axisdata)->ad_flexdata + 0) #define NAD_PTRS(axisdata) ((char **) \ &(axisdata)->ad_flexdata + 1*(nop+1)) #define NAD_NSTRIDES() \ ((nop) + ((itflags&NPY_ITFLAG_HASINDEX) ? 1 : 0)) /* Size of one AXISDATA struct within the iterator */ #define NIT_AXISDATA_SIZEOF(itflags, ndim, nop) (( \ /* intp shape */ \ 1 + \ /* intp index */ \ 1 + \ /* intp stride[nop+1] AND char* ptr[nop+1] */ \ 2*((nop)+1) \ )*NPY_SIZEOF_INTP ) /* * Macro to advance an AXISDATA pointer by a specified count. * Requires that sizeof_axisdata be previously initialized * to NIT_AXISDATA_SIZEOF(itflags, ndim, nop). */ #define NIT_INDEX_AXISDATA(axisdata, index) ((NpyIter_AxisData *) \ (((char *)(axisdata)) + (index)*sizeof_axisdata)) #define NIT_ADVANCE_AXISDATA(axisdata, count) \ axisdata = NIT_INDEX_AXISDATA(axisdata, count) /* Size of the whole iterator */ #define NIT_SIZEOF_ITERATOR(itflags, ndim, nop) ( \ sizeof(struct NpyIter_InternalOnly) + \ NIT_AXISDATA_OFFSET(itflags, ndim, nop) + \ NIT_AXISDATA_SIZEOF(itflags, ndim, nop)*(ndim ? ndim : 1)) /* Internal helper functions shared between implementation files */ NPY_NO_EXPORT void npyiter_coalesce_axes(NpyIter *iter); NPY_NO_EXPORT int npyiter_allocate_buffers(NpyIter *iter, char **errmsg); NPY_NO_EXPORT void npyiter_goto_iterindex(NpyIter *iter, npy_intp iterindex); NPY_NO_EXPORT void npyiter_copy_from_buffers(NpyIter *iter); NPY_NO_EXPORT void npyiter_copy_to_buffers(NpyIter *iter, char **prev_dataptrs); #endif numpy-1.8.2/numpy/core/src/multiarray/numpyos.c0000664000175100017510000004747012370216243022776 0ustar vagrantvagrant00000000000000#define PY_SSIZE_T_CLEAN #include #include #include #define NPY_NO_DEPRECATED_API NPY_API_VERSION #define _MULTIARRAYMODULE #include "numpy/arrayobject.h" #include "numpy/npy_math.h" #include "npy_config.h" #include "npy_pycompat.h" /* * From the C99 standard, section 7.19.6: The exponent always contains at least * two digits, and only as many more digits as necessary to represent the * exponent. */ #define MIN_EXPONENT_DIGITS 2 /* * Ensure that any exponent, if present, is at least MIN_EXPONENT_DIGITS * in length. */ static void _ensure_minimum_exponent_length(char* buffer, size_t buf_size) { char *p = strpbrk(buffer, "eE"); if (p && (*(p + 1) == '-' || *(p + 1) == '+')) { char *start = p + 2; int exponent_digit_cnt = 0; int leading_zero_cnt = 0; int in_leading_zeros = 1; int significant_digit_cnt; /* Skip over the exponent and the sign. */ p += 2; /* Find the end of the exponent, keeping track of leading zeros. */ while (*p && isdigit(Py_CHARMASK(*p))) { if (in_leading_zeros && *p == '0') { ++leading_zero_cnt; } if (*p != '0') { in_leading_zeros = 0; } ++p; ++exponent_digit_cnt; } significant_digit_cnt = exponent_digit_cnt - leading_zero_cnt; if (exponent_digit_cnt == MIN_EXPONENT_DIGITS) { /* * If there are 2 exactly digits, we're done, * regardless of what they contain */ } else if (exponent_digit_cnt > MIN_EXPONENT_DIGITS) { int extra_zeros_cnt; /* * There are more than 2 digits in the exponent. See * if we can delete some of the leading zeros */ if (significant_digit_cnt < MIN_EXPONENT_DIGITS) { significant_digit_cnt = MIN_EXPONENT_DIGITS; } extra_zeros_cnt = exponent_digit_cnt - significant_digit_cnt; /* * Delete extra_zeros_cnt worth of characters from the * front of the exponent */ assert(extra_zeros_cnt >= 0); /* * Add one to significant_digit_cnt to copy the * trailing 0 byte, thus setting the length */ memmove(start, start + extra_zeros_cnt, significant_digit_cnt + 1); } else { /* * If there are fewer than 2 digits, add zeros * until there are 2, if there's enough room */ int zeros = MIN_EXPONENT_DIGITS - exponent_digit_cnt; if (start + zeros + exponent_digit_cnt + 1 < buffer + buf_size) { memmove(start + zeros, start, exponent_digit_cnt + 1); memset(start, '0', zeros); } } } } /* * Ensure that buffer has a decimal point in it. The decimal point * will not be in the current locale, it will always be '.' */ static void _ensure_decimal_point(char* buffer, size_t buf_size) { int insert_count = 0; char* chars_to_insert; /* search for the first non-digit character */ char *p = buffer; if (*p == '-' || *p == '+') /* * Skip leading sign, if present. I think this could only * ever be '-', but it can't hurt to check for both. */ ++p; while (*p && isdigit(Py_CHARMASK(*p))) { ++p; } if (*p == '.') { if (isdigit(Py_CHARMASK(*(p+1)))) { /* * Nothing to do, we already have a decimal * point and a digit after it. */ } else { /* * We have a decimal point, but no following * digit. Insert a zero after the decimal. */ ++p; chars_to_insert = "0"; insert_count = 1; } } else { chars_to_insert = ".0"; insert_count = 2; } if (insert_count) { size_t buf_len = strlen(buffer); if (buf_len + insert_count + 1 >= buf_size) { /* * If there is not enough room in the buffer * for the additional text, just skip it. It's * not worth generating an error over. */ } else { memmove(p + insert_count, p, buffer + strlen(buffer) - p + 1); memcpy(p, chars_to_insert, insert_count); } } } /* see FORMATBUFLEN in unicodeobject.c */ #define FLOAT_FORMATBUFLEN 120 /* * Given a string that may have a decimal point in the current * locale, change it back to a dot. Since the string cannot get * longer, no need for a maximum buffer size parameter. */ static void _change_decimal_from_locale_to_dot(char* buffer) { struct lconv *locale_data = localeconv(); const char *decimal_point = locale_data->decimal_point; if (decimal_point[0] != '.' || decimal_point[1] != 0) { size_t decimal_point_len = strlen(decimal_point); if (*buffer == '+' || *buffer == '-') { buffer++; } while (isdigit(Py_CHARMASK(*buffer))) { buffer++; } if (strncmp(buffer, decimal_point, decimal_point_len) == 0) { *buffer = '.'; buffer++; if (decimal_point_len > 1) { /* buffer needs to get smaller */ size_t rest_len = strlen(buffer + (decimal_point_len - 1)); memmove(buffer, buffer + (decimal_point_len - 1), rest_len); buffer[rest_len] = 0; } } } } /* * Check that the format string is a valid one for NumPyOS_ascii_format* */ static int _check_ascii_format(const char *format) { char format_char; size_t format_len = strlen(format); /* The last character in the format string must be the format char */ format_char = format[format_len - 1]; if (format[0] != '%') { return -1; } /* * I'm not sure why this test is here. It's ensuring that the format * string after the first character doesn't have a single quote, a * lowercase l, or a percent. This is the reverse of the commented-out * test about 10 lines ago. */ if (strpbrk(format + 1, "'l%")) { return -1; } /* * Also curious about this function is that it accepts format strings * like "%xg", which are invalid for floats. In general, the * interface to this function is not very good, but changing it is * difficult because it's a public API. */ if (!(format_char == 'e' || format_char == 'E' || format_char == 'f' || format_char == 'F' || format_char == 'g' || format_char == 'G')) { return -1; } return 0; } /* * Fix the generated string: make sure the decimal is ., that exponent has a * minimal number of digits, and that it has a decimal + one digit after that * decimal if decimal argument != 0 (Same effect that 'Z' format in * PyOS_ascii_formatd */ static char* _fix_ascii_format(char* buf, size_t buflen, int decimal) { /* * Get the current locale, and find the decimal point string. * Convert that string back to a dot. */ _change_decimal_from_locale_to_dot(buf); /* * If an exponent exists, ensure that the exponent is at least * MIN_EXPONENT_DIGITS digits, providing the buffer is large enough * for the extra zeros. Also, if there are more than * MIN_EXPONENT_DIGITS, remove as many zeros as possible until we get * back to MIN_EXPONENT_DIGITS */ _ensure_minimum_exponent_length(buf, buflen); if (decimal != 0) { _ensure_decimal_point(buf, buflen); } return buf; } /* * NumPyOS_ascii_format*: * - buffer: A buffer to place the resulting string in * - buf_size: The length of the buffer. * - format: The printf()-style format to use for the code to use for * converting. * - value: The value to convert * - decimal: if != 0, always has a decimal, and at leasat one digit after * the decimal. This has the same effect as passing 'Z' in the origianl * PyOS_ascii_formatd * * This is similar to PyOS_ascii_formatd in python > 2.6, except that it does * not handle 'n', and handles nan / inf. * * Converts a #gdouble to a string, using the '.' as decimal point. To format * the number you pass in a printf()-style format string. Allowed conversion * specifiers are 'e', 'E', 'f', 'F', 'g', 'G'. * * Return value: The pointer to the buffer with the converted string. */ #define _ASCII_FORMAT(type, suffix, print_type) \ NPY_NO_EXPORT char* \ NumPyOS_ascii_format ## suffix(char *buffer, size_t buf_size, \ const char *format, \ type val, int decimal) \ { \ if (npy_isfinite(val)) { \ if(_check_ascii_format(format)) { \ return NULL; \ } \ PyOS_snprintf(buffer, buf_size, format, (print_type)val); \ return _fix_ascii_format(buffer, buf_size, decimal); \ } \ else if (npy_isnan(val)){ \ if (buf_size < 4) { \ return NULL; \ } \ strcpy(buffer, "nan"); \ } \ else { \ if (npy_signbit(val)) { \ if (buf_size < 5) { \ return NULL; \ } \ strcpy(buffer, "-inf"); \ } \ else { \ if (buf_size < 4) { \ return NULL; \ } \ strcpy(buffer, "inf"); \ } \ } \ return buffer; \ } _ASCII_FORMAT(float, f, float) _ASCII_FORMAT(double, d, double) #ifndef FORCE_NO_LONG_DOUBLE_FORMATTING _ASCII_FORMAT(long double, l, long double) #else _ASCII_FORMAT(long double, l, double) #endif /* * NumPyOS_ascii_isspace: * * Same as isspace under C locale */ NPY_NO_EXPORT int NumPyOS_ascii_isspace(char c) { return c == ' ' || c == '\f' || c == '\n' || c == '\r' || c == '\t' || c == '\v'; } /* * NumPyOS_ascii_isalpha: * * Same as isalpha under C locale */ static int NumPyOS_ascii_isalpha(char c) { return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z'); } /* * NumPyOS_ascii_isdigit: * * Same as isdigit under C locale */ static int NumPyOS_ascii_isdigit(char c) { return (c >= '0' && c <= '9'); } /* * NumPyOS_ascii_isalnum: * * Same as isalnum under C locale */ static int NumPyOS_ascii_isalnum(char c) { return NumPyOS_ascii_isdigit(c) || NumPyOS_ascii_isalpha(c); } /* * NumPyOS_ascii_tolower: * * Same as tolower under C locale */ static char NumPyOS_ascii_tolower(char c) { if (c >= 'A' && c <= 'Z') { return c + ('a'-'A'); } return c; } /* * NumPyOS_ascii_strncasecmp: * * Same as strncasecmp under C locale */ static int NumPyOS_ascii_strncasecmp(const char* s1, const char* s2, size_t len) { int diff; while (len > 0 && *s1 != '\0' && *s2 != '\0') { diff = ((int)NumPyOS_ascii_tolower(*s1)) - ((int)NumPyOS_ascii_tolower(*s2)); if (diff != 0) { return diff; } ++s1; ++s2; --len; } if (len > 0) { return ((int)*s1) - ((int)*s2); } return 0; } /* * _NumPyOS_ascii_strtod_plain: * * PyOS_ascii_strtod work-alike, with no enhanced features, * for forward compatibility with Python >= 2.7 */ static double NumPyOS_ascii_strtod_plain(const char *s, char** endptr) { double result; #if PY_VERSION_HEX >= 0x02070000 NPY_ALLOW_C_API_DEF; NPY_ALLOW_C_API; result = PyOS_string_to_double(s, endptr, NULL); if (PyErr_Occurred()) { if (endptr) { *endptr = (char*)s; } PyErr_Clear(); } NPY_DISABLE_C_API; #else result = PyOS_ascii_strtod(s, endptr); #endif return result; } /* * NumPyOS_ascii_strtod: * * Work around bugs in PyOS_ascii_strtod */ NPY_NO_EXPORT double NumPyOS_ascii_strtod(const char *s, char** endptr) { struct lconv *locale_data = localeconv(); const char *decimal_point = locale_data->decimal_point; size_t decimal_point_len = strlen(decimal_point); char buffer[FLOAT_FORMATBUFLEN+1]; const char *p; char *q; size_t n; double result; while (NumPyOS_ascii_isspace(*s)) { ++s; } /* * ##1 * * Recognize POSIX inf/nan representations on all platforms. */ p = s; result = 1.0; if (*p == '-') { result = -1.0; ++p; } else if (*p == '+') { ++p; } if (NumPyOS_ascii_strncasecmp(p, "nan", 3) == 0) { p += 3; if (*p == '(') { ++p; while (NumPyOS_ascii_isalnum(*p) || *p == '_') { ++p; } if (*p == ')') { ++p; } } if (endptr != NULL) { *endptr = (char*)p; } return NPY_NAN; } else if (NumPyOS_ascii_strncasecmp(p, "inf", 3) == 0) { p += 3; if (NumPyOS_ascii_strncasecmp(p, "inity", 5) == 0) { p += 5; } if (endptr != NULL) { *endptr = (char*)p; } return result*NPY_INFINITY; } /* End of ##1 */ /* * ## 2 * * At least Python versions <= 2.5.2 and <= 2.6.1 * * Fails to do best-efforts parsing of strings of the form "1234" * where is the decimal point under the foreign locale. */ if (decimal_point[0] != '.' || decimal_point[1] != 0) { p = s; if (*p == '+' || *p == '-') { ++p; } while (*p >= '0' && *p <= '9') { ++p; } if (strncmp(p, decimal_point, decimal_point_len) == 0) { n = (size_t)(p - s); if (n > FLOAT_FORMATBUFLEN) { n = FLOAT_FORMATBUFLEN; } memcpy(buffer, s, n); buffer[n] = '\0'; result = NumPyOS_ascii_strtod_plain(buffer, &q); if (endptr != NULL) { *endptr = (char*)(s + (q - buffer)); } return result; } } /* End of ##2 */ return NumPyOS_ascii_strtod_plain(s, endptr); } /* * NumPyOS_ascii_ftolf: * * fp: FILE pointer * * value: Place to store the value read * * Similar to PyOS_ascii_strtod, except that it reads input from a file. * * Similarly to fscanf, this function always consumes leading whitespace, * and any text that could be the leading part in valid input. * * Return value: similar to fscanf. * * 0 if no number read, * * 1 if a number read, * * EOF if end-of-file met before reading anything. */ NPY_NO_EXPORT int NumPyOS_ascii_ftolf(FILE *fp, double *value) { char buffer[FLOAT_FORMATBUFLEN + 1]; char *endp; char *p; int c; int ok; /* * Pass on to PyOS_ascii_strtod the leftmost matching part in regexp * * \s*[+-]? ( [0-9]*\.[0-9]+([eE][+-]?[0-9]+) * | nan ( \([:alphanum:_]*\) )? * | inf(inity)? * ) * * case-insensitively. * * The "do { ... } while (0)" wrapping in macros ensures that they behave * properly eg. in "if ... else" structures. */ #define END_MATCH() \ goto buffer_filled #define NEXT_CHAR() \ do { \ if (c == EOF || endp >= buffer + FLOAT_FORMATBUFLEN) \ END_MATCH(); \ *endp++ = (char)c; \ c = getc(fp); \ } while (0) #define MATCH_ALPHA_STRING_NOCASE(string) \ do { \ for (p=(string); *p!='\0' && (c==*p || c+('a'-'A')==*p); ++p) \ NEXT_CHAR(); \ if (*p != '\0') END_MATCH(); \ } while (0) #define MATCH_ONE_OR_NONE(condition) \ do { if (condition) NEXT_CHAR(); } while (0) #define MATCH_ONE_OR_MORE(condition) \ do { \ ok = 0; \ while (condition) { NEXT_CHAR(); ok = 1; } \ if (!ok) END_MATCH(); \ } while (0) #define MATCH_ZERO_OR_MORE(condition) \ while (condition) { NEXT_CHAR(); } /* 1. emulate fscanf EOF handling */ c = getc(fp); if (c == EOF) { return EOF; } /* 2. consume leading whitespace unconditionally */ while (NumPyOS_ascii_isspace(c)) { c = getc(fp); } /* 3. start reading matching input to buffer */ endp = buffer; /* 4.1 sign (optional) */ MATCH_ONE_OR_NONE(c == '+' || c == '-'); /* 4.2 nan, inf, infinity; [case-insensitive] */ if (c == 'n' || c == 'N') { NEXT_CHAR(); MATCH_ALPHA_STRING_NOCASE("an"); /* accept nan([:alphanum:_]*), similarly to strtod */ if (c == '(') { NEXT_CHAR(); MATCH_ZERO_OR_MORE(NumPyOS_ascii_isalnum(c) || c == '_'); if (c == ')') { NEXT_CHAR(); } } END_MATCH(); } else if (c == 'i' || c == 'I') { NEXT_CHAR(); MATCH_ALPHA_STRING_NOCASE("nfinity"); END_MATCH(); } /* 4.3 mantissa */ MATCH_ZERO_OR_MORE(NumPyOS_ascii_isdigit(c)); if (c == '.') { NEXT_CHAR(); MATCH_ONE_OR_MORE(NumPyOS_ascii_isdigit(c)); } /* 4.4 exponent */ if (c == 'e' || c == 'E') { NEXT_CHAR(); MATCH_ONE_OR_NONE(c == '+' || c == '-'); MATCH_ONE_OR_MORE(NumPyOS_ascii_isdigit(c)); } END_MATCH(); buffer_filled: ungetc(c, fp); *endp = '\0'; /* 5. try to convert buffer. */ *value = NumPyOS_ascii_strtod(buffer, &p); /* return 1 if something read, else 0 */ return (buffer == p) ? 0 : 1; } #undef END_MATCH #undef NEXT_CHAR #undef MATCH_ALPHA_STRING_NOCASE #undef MATCH_ONE_OR_NONE #undef MATCH_ONE_OR_MORE #undef MATCH_ZERO_OR_MORE numpy-1.8.2/numpy/core/src/multiarray/multiarraymodule.c0000664000175100017510000033762112370216243024663 0ustar vagrantvagrant00000000000000/* Python Multiarray Module -- A useful collection of functions for creating and using ndarrays Original file Copyright (c) 1995, 1996, 1997 Jim Hugunin, hugunin@mit.edu Modified for numpy in 2005 Travis E. Oliphant oliphant@ee.byu.edu Brigham Young University */ /* $Id: multiarraymodule.c,v 1.36 2005/09/14 00:14:00 teoliphant Exp $ */ #define PY_SSIZE_T_CLEAN #include "Python.h" #include "structmember.h" #define NPY_NO_DEPRECATED_API NPY_API_VERSION #define _MULTIARRAYMODULE #include "numpy/arrayobject.h" #include "numpy/arrayscalars.h" #include "numpy/npy_math.h" #include "npy_config.h" #include "npy_pycompat.h" NPY_NO_EXPORT int NPY_NUMUSERTYPES = 0; /* Internal APIs */ #include "arraytypes.h" #include "arrayobject.h" #include "hashdescr.h" #include "descriptor.h" #include "calculation.h" #include "number.h" #include "scalartypes.h" #include "numpymemoryview.h" #include "convert_datatype.h" #include "conversion_utils.h" #include "nditer_pywrap.h" #include "methods.h" #include "_datetime.h" #include "datetime_strings.h" #include "datetime_busday.h" #include "datetime_busdaycal.h" #include "item_selection.h" #include "shape.h" #include "ctors.h" #include "array_assign.h" #include "common.h" /* Only here for API compatibility */ NPY_NO_EXPORT PyTypeObject PyBigArray_Type; /*NUMPY_API * Get Priority from object */ NPY_NO_EXPORT double PyArray_GetPriority(PyObject *obj, double default_) { PyObject *ret; double priority = NPY_PRIORITY; if (PyArray_CheckExact(obj)) return priority; ret = PyArray_GetAttrString_SuppressException(obj, "__array_priority__"); if (ret == NULL) { return default_; } priority = PyFloat_AsDouble(ret); Py_DECREF(ret); return priority; } /*NUMPY_API * Multiply a List of ints */ NPY_NO_EXPORT int PyArray_MultiplyIntList(int *l1, int n) { int s = 1; while (n--) { s *= (*l1++); } return s; } /*NUMPY_API * Multiply a List */ NPY_NO_EXPORT npy_intp PyArray_MultiplyList(npy_intp *l1, int n) { npy_intp s = 1; while (n--) { s *= (*l1++); } return s; } /*NUMPY_API * Multiply a List of Non-negative numbers with over-flow detection. */ NPY_NO_EXPORT npy_intp PyArray_OverflowMultiplyList(npy_intp *l1, int n) { npy_intp prod = 1; npy_intp imax = NPY_MAX_INTP; int i; for (i = 0; i < n; i++) { npy_intp dim = l1[i]; if (dim == 0) { return 0; } if (dim > imax) { return -1; } imax /= dim; prod *= dim; } return prod; } /*NUMPY_API * Produce a pointer into array */ NPY_NO_EXPORT void * PyArray_GetPtr(PyArrayObject *obj, npy_intp* ind) { int n = PyArray_NDIM(obj); npy_intp *strides = PyArray_STRIDES(obj); char *dptr = PyArray_DATA(obj); while (n--) { dptr += (*strides++) * (*ind++); } return (void *)dptr; } /*NUMPY_API * Compare Lists */ NPY_NO_EXPORT int PyArray_CompareLists(npy_intp *l1, npy_intp *l2, int n) { int i; for (i = 0; i < n; i++) { if (l1[i] != l2[i]) { return 0; } } return 1; } /* * simulates a C-style 1-3 dimensional array which can be accesed using * ptr[i] or ptr[i][j] or ptr[i][j][k] -- requires pointer allocation * for 2-d and 3-d. * * For 2-d and up, ptr is NOT equivalent to a statically defined * 2-d or 3-d array. In particular, it cannot be passed into a * function that requires a true pointer to a fixed-size array. */ /*NUMPY_API * Simulate a C-array * steals a reference to typedescr -- can be NULL */ NPY_NO_EXPORT int PyArray_AsCArray(PyObject **op, void *ptr, npy_intp *dims, int nd, PyArray_Descr* typedescr) { PyArrayObject *ap; npy_intp n, m, i, j; char **ptr2; char ***ptr3; if ((nd < 1) || (nd > 3)) { PyErr_SetString(PyExc_ValueError, "C arrays of only 1-3 dimensions available"); Py_XDECREF(typedescr); return -1; } if ((ap = (PyArrayObject*)PyArray_FromAny(*op, typedescr, nd, nd, NPY_ARRAY_CARRAY, NULL)) == NULL) { return -1; } switch(nd) { case 1: *((char **)ptr) = PyArray_DATA(ap); break; case 2: n = PyArray_DIMS(ap)[0]; ptr2 = (char **)PyArray_malloc(n * sizeof(char *)); if (!ptr2) { goto fail; } for (i = 0; i < n; i++) { ptr2[i] = PyArray_BYTES(ap) + i*PyArray_STRIDES(ap)[0]; } *((char ***)ptr) = ptr2; break; case 3: n = PyArray_DIMS(ap)[0]; m = PyArray_DIMS(ap)[1]; ptr3 = (char ***)PyArray_malloc(n*(m+1) * sizeof(char *)); if (!ptr3) { goto fail; } for (i = 0; i < n; i++) { ptr3[i] = ptr3[n + (m-1)*i]; for (j = 0; j < m; j++) { ptr3[i][j] = PyArray_BYTES(ap) + i*PyArray_STRIDES(ap)[0] + j*PyArray_STRIDES(ap)[1]; } } *((char ****)ptr) = ptr3; } memcpy(dims, PyArray_DIMS(ap), nd*sizeof(npy_intp)); *op = (PyObject *)ap; return 0; fail: PyErr_SetString(PyExc_MemoryError, "no memory"); return -1; } /* Deprecated --- Use PyArray_AsCArray instead */ /*NUMPY_API * Convert to a 1D C-array */ NPY_NO_EXPORT int PyArray_As1D(PyObject **op, char **ptr, int *d1, int typecode) { npy_intp newd1; PyArray_Descr *descr; char msg[] = "PyArray_As1D: use PyArray_AsCArray."; if (DEPRECATE(msg) < 0) { return -1; } descr = PyArray_DescrFromType(typecode); if (PyArray_AsCArray(op, (void *)ptr, &newd1, 1, descr) == -1) { return -1; } *d1 = (int) newd1; return 0; } /*NUMPY_API * Convert to a 2D C-array */ NPY_NO_EXPORT int PyArray_As2D(PyObject **op, char ***ptr, int *d1, int *d2, int typecode) { npy_intp newdims[2]; PyArray_Descr *descr; char msg[] = "PyArray_As1D: use PyArray_AsCArray."; if (DEPRECATE(msg) < 0) { return -1; } descr = PyArray_DescrFromType(typecode); if (PyArray_AsCArray(op, (void *)ptr, newdims, 2, descr) == -1) { return -1; } *d1 = (int ) newdims[0]; *d2 = (int ) newdims[1]; return 0; } /* End Deprecated */ /*NUMPY_API * Free pointers created if As2D is called */ NPY_NO_EXPORT int PyArray_Free(PyObject *op, void *ptr) { PyArrayObject *ap = (PyArrayObject *)op; if ((PyArray_NDIM(ap) < 1) || (PyArray_NDIM(ap) > 3)) { return -1; } if (PyArray_NDIM(ap) >= 2) { PyArray_free(ptr); } Py_DECREF(ap); return 0; } /* * Concatenates a list of ndarrays. */ NPY_NO_EXPORT PyArrayObject * PyArray_ConcatenateArrays(int narrays, PyArrayObject **arrays, int axis) { PyTypeObject *subtype = &PyArray_Type; double priority = NPY_PRIORITY; int iarrays, idim, ndim; npy_intp shape[NPY_MAXDIMS], s, strides[NPY_MAXDIMS]; int strideperm[NPY_MAXDIMS]; PyArray_Descr *dtype = NULL; PyArrayObject *ret = NULL; PyArrayObject_fields *sliding_view = NULL; int orig_axis = axis; if (narrays <= 0) { PyErr_SetString(PyExc_ValueError, "need at least one array to concatenate"); return NULL; } /* All the arrays must have the same 'ndim' */ ndim = PyArray_NDIM(arrays[0]); if (ndim == 0) { PyErr_SetString(PyExc_ValueError, "zero-dimensional arrays cannot be concatenated"); return NULL; } /* Handle standard Python negative indexing */ if (axis < 0) { axis += ndim; } if (ndim == 1 && axis != 0) { char msg[] = "axis != 0 for ndim == 1; this will raise an error in " "future versions of numpy"; if (DEPRECATE(msg) < 0) { return NULL; } axis = 0; } if (axis < 0 || axis >= ndim) { PyErr_Format(PyExc_IndexError, "axis %d out of bounds [0, %d)", orig_axis, ndim); return NULL; } /* * Figure out the final concatenated shape starting from the first * array's shape. */ memcpy(shape, PyArray_SHAPE(arrays[0]), ndim * sizeof(shape[0])); for (iarrays = 1; iarrays < narrays; ++iarrays) { npy_intp *arr_shape; if (PyArray_NDIM(arrays[iarrays]) != ndim) { PyErr_SetString(PyExc_ValueError, "all the input arrays must have same " "number of dimensions"); return NULL; } arr_shape = PyArray_SHAPE(arrays[iarrays]); for (idim = 0; idim < ndim; ++idim) { /* Build up the size of the concatenation axis */ if (idim == axis) { shape[idim] += arr_shape[idim]; } /* Validate that the rest of the dimensions match */ else if (shape[idim] != arr_shape[idim]) { PyErr_SetString(PyExc_ValueError, "all the input array dimensions " "except for the concatenation axis " "must match exactly"); return NULL; } } } /* Get the priority subtype for the array */ for (iarrays = 0; iarrays < narrays; ++iarrays) { if (Py_TYPE(arrays[iarrays]) != subtype) { double pr = PyArray_GetPriority((PyObject *)(arrays[iarrays]), 0.0); if (pr > priority) { priority = pr; subtype = Py_TYPE(arrays[iarrays]); } } } /* Get the resulting dtype from combining all the arrays */ dtype = PyArray_ResultType(narrays, arrays, 0, NULL); if (dtype == NULL) { return NULL; } /* * Figure out the permutation to apply to the strides to match * the memory layout of the input arrays, using ambiguity * resolution rules matching that of the NpyIter. */ PyArray_CreateMultiSortedStridePerm(narrays, arrays, ndim, strideperm); s = dtype->elsize; for (idim = ndim-1; idim >= 0; --idim) { int iperm = strideperm[idim]; strides[iperm] = s; s *= shape[iperm]; } /* Allocate the array for the result. This steals the 'dtype' reference. */ ret = (PyArrayObject *)PyArray_NewFromDescr(subtype, dtype, ndim, shape, strides, NULL, 0, NULL); if (ret == NULL) { return NULL; } /* * Create a view which slides through ret for assigning the * successive input arrays. */ sliding_view = (PyArrayObject_fields *)PyArray_View(ret, NULL, &PyArray_Type); if (sliding_view == NULL) { Py_DECREF(ret); return NULL; } for (iarrays = 0; iarrays < narrays; ++iarrays) { /* Set the dimension to match the input array's */ sliding_view->dimensions[axis] = PyArray_SHAPE(arrays[iarrays])[axis]; /* Copy the data for this array */ if (PyArray_AssignArray((PyArrayObject *)sliding_view, arrays[iarrays], NULL, NPY_SAME_KIND_CASTING) < 0) { Py_DECREF(sliding_view); Py_DECREF(ret); return NULL; } /* Slide to the start of the next window */ sliding_view->data += sliding_view->dimensions[axis] * sliding_view->strides[axis]; } Py_DECREF(sliding_view); return ret; } /* * Concatenates a list of ndarrays, flattening each in the specified order. */ NPY_NO_EXPORT PyArrayObject * PyArray_ConcatenateFlattenedArrays(int narrays, PyArrayObject **arrays, NPY_ORDER order) { PyTypeObject *subtype = &PyArray_Type; double priority = NPY_PRIORITY; int iarrays; npy_intp stride, sizes[NPY_MAXDIMS]; npy_intp shape = 0; PyArray_Descr *dtype = NULL; PyArrayObject *ret = NULL; PyArrayObject_fields *sliding_view = NULL; if (narrays <= 0) { PyErr_SetString(PyExc_ValueError, "need at least one array to concatenate"); return NULL; } /* * Figure out the final concatenated shape starting from the first * array's shape. */ for (iarrays = 0; iarrays < narrays; ++iarrays) { shape += sizes[iarrays] = PyArray_SIZE(arrays[iarrays]); /* Check for overflow */ if (shape < 0) { PyErr_SetString(PyExc_ValueError, "total number of elements " "too large to concatenate"); return NULL; } } /* Get the priority subtype for the array */ for (iarrays = 0; iarrays < narrays; ++iarrays) { if (Py_TYPE(arrays[iarrays]) != subtype) { double pr = PyArray_GetPriority((PyObject *)(arrays[iarrays]), 0.0); if (pr > priority) { priority = pr; subtype = Py_TYPE(arrays[iarrays]); } } } /* Get the resulting dtype from combining all the arrays */ dtype = PyArray_ResultType(narrays, arrays, 0, NULL); if (dtype == NULL) { return NULL; } stride = dtype->elsize; /* Allocate the array for the result. This steals the 'dtype' reference. */ ret = (PyArrayObject *)PyArray_NewFromDescr(subtype, dtype, 1, &shape, &stride, NULL, 0, NULL); if (ret == NULL) { return NULL; } /* * Create a view which slides through ret for assigning the * successive input arrays. */ sliding_view = (PyArrayObject_fields *)PyArray_View(ret, NULL, &PyArray_Type); if (sliding_view == NULL) { Py_DECREF(ret); return NULL; } for (iarrays = 0; iarrays < narrays; ++iarrays) { /* Adjust the window dimensions for this array */ sliding_view->dimensions[0] = sizes[iarrays]; /* Copy the data for this array */ if (PyArray_CopyAsFlat((PyArrayObject *)sliding_view, arrays[iarrays], order) < 0) { Py_DECREF(sliding_view); Py_DECREF(ret); return NULL; } /* Slide to the start of the next window */ sliding_view->data += sliding_view->strides[0] * sizes[iarrays]; } Py_DECREF(sliding_view); return ret; } /*NUMPY_API * Concatenate * * Concatenate an arbitrary Python sequence into an array. * op is a python object supporting the sequence interface. * Its elements will be concatenated together to form a single * multidimensional array. If axis is NPY_MAXDIMS or bigger, then * each sequence object will be flattened before concatenation */ NPY_NO_EXPORT PyObject * PyArray_Concatenate(PyObject *op, int axis) { int iarrays, narrays; PyArrayObject **arrays; PyArrayObject *ret; /* Convert the input list into arrays */ narrays = PySequence_Size(op); if (narrays < 0) { return NULL; } arrays = PyArray_malloc(narrays * sizeof(arrays[0])); if (arrays == NULL) { PyErr_NoMemory(); return NULL; } for (iarrays = 0; iarrays < narrays; ++iarrays) { PyObject *item = PySequence_GetItem(op, iarrays); if (item == NULL) { narrays = iarrays; goto fail; } arrays[iarrays] = (PyArrayObject *)PyArray_FromAny(item, NULL, 0, 0, 0, NULL); Py_DECREF(item); if (arrays[iarrays] == NULL) { narrays = iarrays; goto fail; } } if (axis >= NPY_MAXDIMS) { ret = PyArray_ConcatenateFlattenedArrays(narrays, arrays, NPY_CORDER); } else { ret = PyArray_ConcatenateArrays(narrays, arrays, axis); } for (iarrays = 0; iarrays < narrays; ++iarrays) { Py_DECREF(arrays[iarrays]); } PyArray_free(arrays); return (PyObject *)ret; fail: /* 'narrays' was set to how far we got in the conversion */ for (iarrays = 0; iarrays < narrays; ++iarrays) { Py_DECREF(arrays[iarrays]); } PyArray_free(arrays); return NULL; } static int _signbit_set(PyArrayObject *arr) { static char bitmask = (char) 0x80; char *ptr; /* points to the npy_byte to test */ char byteorder; int elsize; elsize = PyArray_DESCR(arr)->elsize; byteorder = PyArray_DESCR(arr)->byteorder; ptr = PyArray_DATA(arr); if (elsize > 1 && (byteorder == NPY_LITTLE || (byteorder == NPY_NATIVE && PyArray_ISNBO(NPY_LITTLE)))) { ptr += elsize - 1; } return ((*ptr & bitmask) != 0); } /*NUMPY_API * ScalarKind * * Returns the scalar kind of a type number, with an * optional tweak based on the scalar value itself. * If no scalar is provided, it returns INTPOS_SCALAR * for both signed and unsigned integers, otherwise * it checks the sign of any signed integer to choose * INTNEG_SCALAR when appropriate. */ NPY_NO_EXPORT NPY_SCALARKIND PyArray_ScalarKind(int typenum, PyArrayObject **arr) { NPY_SCALARKIND ret = NPY_NOSCALAR; if ((unsigned int)typenum < NPY_NTYPES) { ret = _npy_scalar_kinds_table[typenum]; /* Signed integer types are INTNEG in the table */ if (ret == NPY_INTNEG_SCALAR) { if (!arr || !_signbit_set(*arr)) { ret = NPY_INTPOS_SCALAR; } } } else if (PyTypeNum_ISUSERDEF(typenum)) { PyArray_Descr* descr = PyArray_DescrFromType(typenum); if (descr->f->scalarkind) { ret = descr->f->scalarkind((arr ? *arr : NULL)); } Py_DECREF(descr); } return ret; } /*NUMPY_API * * Determines whether the data type 'thistype', with * scalar kind 'scalar', can be coerced into 'neededtype'. */ NPY_NO_EXPORT int PyArray_CanCoerceScalar(int thistype, int neededtype, NPY_SCALARKIND scalar) { PyArray_Descr* from; int *castlist; /* If 'thistype' is not a scalar, it must be safely castable */ if (scalar == NPY_NOSCALAR) { return PyArray_CanCastSafely(thistype, neededtype); } if ((unsigned int)neededtype < NPY_NTYPES) { NPY_SCALARKIND neededscalar; if (scalar == NPY_OBJECT_SCALAR) { return PyArray_CanCastSafely(thistype, neededtype); } /* * The lookup table gives us exactly what we need for * this comparison, which PyArray_ScalarKind would not. * * The rule is that positive scalars can be coerced * to a signed ints, but negative scalars cannot be coerced * to unsigned ints. * _npy_scalar_kinds_table[int]==NEGINT > POSINT, * so 1 is returned, but * _npy_scalar_kinds_table[uint]==POSINT < NEGINT, * so 0 is returned, as required. * */ neededscalar = _npy_scalar_kinds_table[neededtype]; if (neededscalar >= scalar) { return 1; } if (!PyTypeNum_ISUSERDEF(thistype)) { return 0; } } from = PyArray_DescrFromType(thistype); if (from->f->cancastscalarkindto && (castlist = from->f->cancastscalarkindto[scalar])) { while (*castlist != NPY_NOTYPE) { if (*castlist++ == neededtype) { Py_DECREF(from); return 1; } } } Py_DECREF(from); return 0; } /* * Make a new empty array, of the passed size, of a type that takes the * priority of ap1 and ap2 into account. */ static PyArrayObject * new_array_for_sum(PyArrayObject *ap1, PyArrayObject *ap2, PyArrayObject* out, int nd, npy_intp dimensions[], int typenum) { PyArrayObject *ret; PyTypeObject *subtype; double prior1, prior2; /* * Need to choose an output array that can hold a sum * -- use priority to determine which subtype. */ if (Py_TYPE(ap2) != Py_TYPE(ap1)) { prior2 = PyArray_GetPriority((PyObject *)ap2, 0.0); prior1 = PyArray_GetPriority((PyObject *)ap1, 0.0); subtype = (prior2 > prior1 ? Py_TYPE(ap2) : Py_TYPE(ap1)); } else { prior1 = prior2 = 0.0; subtype = Py_TYPE(ap1); } if (out) { int d; /* verify that out is usable */ if (Py_TYPE(out) != subtype || PyArray_NDIM(out) != nd || PyArray_TYPE(out) != typenum || !PyArray_ISCARRAY(out)) { PyErr_SetString(PyExc_ValueError, "output array is not acceptable " "(must have the right type, nr dimensions, and be a C-Array)"); return 0; } for (d = 0; d < nd; ++d) { if (dimensions[d] != PyArray_DIM(out, d)) { PyErr_SetString(PyExc_ValueError, "output array has wrong dimensions"); return 0; } } Py_INCREF(out); return out; } ret = (PyArrayObject *)PyArray_New(subtype, nd, dimensions, typenum, NULL, NULL, 0, 0, (PyObject *) (prior2 > prior1 ? ap2 : ap1)); return ret; } /* Could perhaps be redone to not make contiguous arrays */ /*NUMPY_API * Numeric.innerproduct(a,v) */ NPY_NO_EXPORT PyObject * PyArray_InnerProduct(PyObject *op1, PyObject *op2) { PyArrayObject *ap1, *ap2, *ret = NULL; PyArrayIterObject *it1, *it2; npy_intp i, j, l; int typenum, nd, axis; npy_intp is1, is2, os; char *op; npy_intp dimensions[NPY_MAXDIMS]; PyArray_DotFunc *dot; PyArray_Descr *typec; NPY_BEGIN_THREADS_DEF; typenum = PyArray_ObjectType(op1, 0); typenum = PyArray_ObjectType(op2, typenum); typec = PyArray_DescrFromType(typenum); Py_INCREF(typec); ap1 = (PyArrayObject *)PyArray_FromAny(op1, typec, 0, 0, NPY_ARRAY_ALIGNED, NULL); if (ap1 == NULL) { Py_DECREF(typec); return NULL; } ap2 = (PyArrayObject *)PyArray_FromAny(op2, typec, 0, 0, NPY_ARRAY_ALIGNED, NULL); if (ap2 == NULL) { goto fail; } if (PyArray_NDIM(ap1) == 0 || PyArray_NDIM(ap2) == 0) { ret = (PyArray_NDIM(ap1) == 0 ? ap1 : ap2); ret = (PyArrayObject *)Py_TYPE(ret)->tp_as_number->nb_multiply( (PyObject *)ap1, (PyObject *)ap2); Py_DECREF(ap1); Py_DECREF(ap2); return (PyObject *)ret; } l = PyArray_DIMS(ap1)[PyArray_NDIM(ap1) - 1]; if (PyArray_DIMS(ap2)[PyArray_NDIM(ap2) - 1] != l) { PyErr_SetString(PyExc_ValueError, "matrices are not aligned"); goto fail; } nd = PyArray_NDIM(ap1) + PyArray_NDIM(ap2) - 2; j = 0; for (i = 0; i < PyArray_NDIM(ap1) - 1; i++) { dimensions[j++] = PyArray_DIMS(ap1)[i]; } for (i = 0; i < PyArray_NDIM(ap2) - 1; i++) { dimensions[j++] = PyArray_DIMS(ap2)[i]; } /* * Need to choose an output array that can hold a sum * -- use priority to determine which subtype. */ ret = new_array_for_sum(ap1, ap2, NULL, nd, dimensions, typenum); if (ret == NULL) { goto fail; } /* Ensure that multiarray.inner(,) -> zeros((N,M)) */ if (PyArray_SIZE(ap1) == 0 && PyArray_SIZE(ap2) == 0) { memset(PyArray_DATA(ret), 0, PyArray_NBYTES(ret)); } dot = (PyArray_DESCR(ret)->f->dotfunc); if (dot == NULL) { PyErr_SetString(PyExc_ValueError, "dot not available for this type"); goto fail; } is1 = PyArray_STRIDES(ap1)[PyArray_NDIM(ap1) - 1]; is2 = PyArray_STRIDES(ap2)[PyArray_NDIM(ap2) - 1]; op = PyArray_DATA(ret); os = PyArray_DESCR(ret)->elsize; axis = PyArray_NDIM(ap1) - 1; it1 = (PyArrayIterObject *) PyArray_IterAllButAxis((PyObject *)ap1, &axis); axis = PyArray_NDIM(ap2) - 1; it2 = (PyArrayIterObject *) PyArray_IterAllButAxis((PyObject *)ap2, &axis); NPY_BEGIN_THREADS_DESCR(PyArray_DESCR(ap2)); while (it1->index < it1->size) { while (it2->index < it2->size) { dot(it1->dataptr, is1, it2->dataptr, is2, op, l, ret); op += os; PyArray_ITER_NEXT(it2); } PyArray_ITER_NEXT(it1); PyArray_ITER_RESET(it2); } NPY_END_THREADS_DESCR(PyArray_DESCR(ap2)); Py_DECREF(it1); Py_DECREF(it2); if (PyErr_Occurred()) { goto fail; } Py_DECREF(ap1); Py_DECREF(ap2); return (PyObject *)ret; fail: Py_XDECREF(ap1); Py_XDECREF(ap2); Py_XDECREF(ret); return NULL; } /*NUMPY_API * Numeric.matrixproduct(a,v,out) * just like inner product but does the swapaxes stuff on the fly */ NPY_NO_EXPORT PyObject * PyArray_MatrixProduct2(PyObject *op1, PyObject *op2, PyArrayObject* out) { PyArrayObject *ap1, *ap2, *ret = NULL; PyArrayIterObject *it1, *it2; npy_intp i, j, l; int typenum, nd, axis, matchDim; npy_intp is1, is2, os; char *op; npy_intp dimensions[NPY_MAXDIMS]; PyArray_DotFunc *dot; PyArray_Descr *typec = NULL; NPY_BEGIN_THREADS_DEF; typenum = PyArray_ObjectType(op1, 0); typenum = PyArray_ObjectType(op2, typenum); typec = PyArray_DescrFromType(typenum); if (typec == NULL) { PyErr_SetString(PyExc_ValueError, "Cannot find a common data type."); return NULL; } Py_INCREF(typec); ap1 = (PyArrayObject *)PyArray_FromAny(op1, typec, 0, 0, NPY_ARRAY_ALIGNED, NULL); if (ap1 == NULL) { Py_DECREF(typec); return NULL; } ap2 = (PyArrayObject *)PyArray_FromAny(op2, typec, 0, 0, NPY_ARRAY_ALIGNED, NULL); if (ap2 == NULL) { goto fail; } if (PyArray_NDIM(ap1) == 0 || PyArray_NDIM(ap2) == 0) { ret = (PyArray_NDIM(ap1) == 0 ? ap1 : ap2); ret = (PyArrayObject *)Py_TYPE(ret)->tp_as_number->nb_multiply( (PyObject *)ap1, (PyObject *)ap2); Py_DECREF(ap1); Py_DECREF(ap2); return (PyObject *)ret; } l = PyArray_DIMS(ap1)[PyArray_NDIM(ap1) - 1]; if (PyArray_NDIM(ap2) > 1) { matchDim = PyArray_NDIM(ap2) - 2; } else { matchDim = 0; } if (PyArray_DIMS(ap2)[matchDim] != l) { PyErr_SetString(PyExc_ValueError, "objects are not aligned"); goto fail; } nd = PyArray_NDIM(ap1) + PyArray_NDIM(ap2) - 2; if (nd > NPY_MAXDIMS) { PyErr_SetString(PyExc_ValueError, "dot: too many dimensions in result"); goto fail; } j = 0; for (i = 0; i < PyArray_NDIM(ap1) - 1; i++) { dimensions[j++] = PyArray_DIMS(ap1)[i]; } for (i = 0; i < PyArray_NDIM(ap2) - 2; i++) { dimensions[j++] = PyArray_DIMS(ap2)[i]; } if(PyArray_NDIM(ap2) > 1) { dimensions[j++] = PyArray_DIMS(ap2)[PyArray_NDIM(ap2)-1]; } /* fprintf(stderr, "nd=%d dimensions=", nd); for(i=0; i,<0xM>) -> zeros((N,M)) */ if (PyArray_SIZE(ap1) == 0 && PyArray_SIZE(ap2) == 0) { memset(PyArray_DATA(ret), 0, PyArray_NBYTES(ret)); } dot = PyArray_DESCR(ret)->f->dotfunc; if (dot == NULL) { PyErr_SetString(PyExc_ValueError, "dot not available for this type"); goto fail; } op = PyArray_DATA(ret); os = PyArray_DESCR(ret)->elsize; 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) { dot(it1->dataptr, is1, it2->dataptr, is2, op, l, ret); op += os; PyArray_ITER_NEXT(it2); } PyArray_ITER_NEXT(it1); PyArray_ITER_RESET(it2); } NPY_END_THREADS_DESCR(PyArray_DESCR(ap2)); Py_DECREF(it1); Py_DECREF(it2); if (PyErr_Occurred()) { /* only for OBJECT arrays */ goto fail; } Py_DECREF(ap1); Py_DECREF(ap2); return (PyObject *)ret; fail: Py_XDECREF(ap1); Py_XDECREF(ap2); Py_XDECREF(ret); return NULL; } /*NUMPY_API *Numeric.matrixproduct(a,v) * just like inner product but does the swapaxes stuff on the fly */ NPY_NO_EXPORT PyObject * PyArray_MatrixProduct(PyObject *op1, PyObject *op2) { return PyArray_MatrixProduct2(op1, op2, NULL); } /*NUMPY_API * Copy and Transpose * * Could deprecate this function, as there isn't a speed benefit over * calling Transpose and then Copy. */ NPY_NO_EXPORT PyObject * PyArray_CopyAndTranspose(PyObject *op) { PyArrayObject *arr, *tmp, *ret; int i; npy_intp new_axes_values[NPY_MAXDIMS]; PyArray_Dims new_axes; /* Make sure we have an array */ arr = (PyArrayObject *)PyArray_FromAny(op, NULL, 0, 0, 0, NULL); if (arr == NULL) { return NULL; } if (PyArray_NDIM(arr) > 1) { /* Set up the transpose operation */ new_axes.len = PyArray_NDIM(arr); for (i = 0; i < new_axes.len; ++i) { new_axes_values[i] = new_axes.len - i - 1; } new_axes.ptr = new_axes_values; /* Do the transpose (always returns a view) */ tmp = (PyArrayObject *)PyArray_Transpose(arr, &new_axes); if (tmp == NULL) { Py_DECREF(arr); return NULL; } } else { tmp = arr; arr = NULL; } /* TODO: Change this to NPY_KEEPORDER for NumPy 2.0 */ ret = (PyArrayObject *)PyArray_NewCopy(tmp, NPY_CORDER); Py_XDECREF(arr); Py_DECREF(tmp); return (PyObject *)ret; } /* * Implementation which is common between PyArray_Correlate * and PyArray_Correlate2. * * inverted is set to 1 if computed correlate(ap2, ap1), 0 otherwise */ static PyArrayObject* _pyarray_correlate(PyArrayObject *ap1, PyArrayObject *ap2, int typenum, int mode, int *inverted) { PyArrayObject *ret; npy_intp length; npy_intp i, n1, n2, n, n_left, n_right; npy_intp is1, is2, os; char *ip1, *ip2, *op; PyArray_DotFunc *dot; NPY_BEGIN_THREADS_DEF; n1 = PyArray_DIMS(ap1)[0]; n2 = PyArray_DIMS(ap2)[0]; if (n1 < n2) { ret = ap1; ap1 = ap2; ap2 = ret; ret = NULL; i = n1; n1 = n2; n2 = i; *inverted = 1; } else { *inverted = 0; } length = n1; n = n2; switch(mode) { case 0: length = length - n + 1; n_left = n_right = 0; break; case 1: n_left = (npy_intp)(n/2); n_right = n - n_left - 1; break; case 2: n_right = n - 1; n_left = n - 1; length = length + n - 1; break; default: PyErr_SetString(PyExc_ValueError, "mode must be 0, 1, or 2"); return NULL; } /* * Need to choose an output array that can hold a sum * -- use priority to determine which subtype. */ ret = new_array_for_sum(ap1, ap2, NULL, 1, &length, typenum); if (ret == NULL) { return NULL; } dot = PyArray_DESCR(ret)->f->dotfunc; if (dot == NULL) { PyErr_SetString(PyExc_ValueError, "function not available for this data type"); goto clean_ret; } NPY_BEGIN_THREADS_DESCR(PyArray_DESCR(ret)); is1 = PyArray_STRIDES(ap1)[0]; is2 = PyArray_STRIDES(ap2)[0]; op = PyArray_DATA(ret); os = PyArray_DESCR(ret)->elsize; ip1 = PyArray_DATA(ap1); ip2 = PyArray_BYTES(ap2) + n_left*is2; n = n - n_left; for (i = 0; i < n_left; i++) { dot(ip1, is1, ip2, is2, op, n, ret); n++; ip2 -= is2; op += os; } for (i = 0; i < (n1 - n2 + 1); i++) { dot(ip1, is1, ip2, is2, op, n, ret); ip1 += is1; op += os; } for (i = 0; i < n_right; i++) { n--; dot(ip1, is1, ip2, is2, op, n, ret); ip1 += is1; op += os; } NPY_END_THREADS_DESCR(PyArray_DESCR(ret)); if (PyErr_Occurred()) { goto clean_ret; } return ret; clean_ret: Py_DECREF(ret); return NULL; } /* * Revert a one dimensional array in-place * * Return 0 on success, other value on failure */ static int _pyarray_revert(PyArrayObject *ret) { npy_intp length; npy_intp i; PyArray_CopySwapFunc *copyswap; char *tmp = NULL, *sw1, *sw2; npy_intp os; char *op; length = PyArray_DIMS(ret)[0]; copyswap = PyArray_DESCR(ret)->f->copyswap; tmp = PyArray_malloc(PyArray_DESCR(ret)->elsize); if (tmp == NULL) { return -1; } os = PyArray_DESCR(ret)->elsize; op = PyArray_DATA(ret); sw1 = op; sw2 = op + (length - 1) * os; if (PyArray_ISFLEXIBLE(ret) || PyArray_ISOBJECT(ret)) { for(i = 0; i < length/2; ++i) { memmove(tmp, sw1, os); copyswap(tmp, NULL, 0, NULL); memmove(sw1, sw2, os); copyswap(sw1, NULL, 0, NULL); memmove(sw2, tmp, os); copyswap(sw2, NULL, 0, NULL); sw1 += os; sw2 -= os; } } else { for(i = 0; i < length/2; ++i) { memcpy(tmp, sw1, os); memcpy(sw1, sw2, os); memcpy(sw2, tmp, os); sw1 += os; sw2 -= os; } } PyArray_free(tmp); return 0; } /*NUMPY_API * correlate(a1,a2,mode) * * This function computes the usual correlation (correlate(a1, a2) != * correlate(a2, a1), and conjugate the second argument for complex inputs */ NPY_NO_EXPORT PyObject * PyArray_Correlate2(PyObject *op1, PyObject *op2, int mode) { PyArrayObject *ap1, *ap2, *ret = NULL; int typenum; PyArray_Descr *typec; int inverted; int st; typenum = PyArray_ObjectType(op1, 0); typenum = PyArray_ObjectType(op2, typenum); typec = PyArray_DescrFromType(typenum); Py_INCREF(typec); ap1 = (PyArrayObject *)PyArray_FromAny(op1, typec, 1, 1, NPY_ARRAY_DEFAULT, NULL); if (ap1 == NULL) { Py_DECREF(typec); return NULL; } ap2 = (PyArrayObject *)PyArray_FromAny(op2, typec, 1, 1, NPY_ARRAY_DEFAULT, NULL); if (ap2 == NULL) { goto clean_ap1; } if (PyArray_ISCOMPLEX(ap2)) { PyArrayObject *cap2; cap2 = (PyArrayObject *)PyArray_Conjugate(ap2, NULL); if (cap2 == NULL) { goto clean_ap2; } Py_DECREF(ap2); ap2 = cap2; } ret = _pyarray_correlate(ap1, ap2, typenum, mode, &inverted); if (ret == NULL) { goto clean_ap2; } /* * If we inverted input orders, we need to reverse the output array (i.e. * ret = ret[::-1]) */ if (inverted) { st = _pyarray_revert(ret); if(st) { goto clean_ret; } } Py_DECREF(ap1); Py_DECREF(ap2); return (PyObject *)ret; clean_ret: Py_DECREF(ret); clean_ap2: Py_DECREF(ap2); clean_ap1: Py_DECREF(ap1); return NULL; } /*NUMPY_API * Numeric.correlate(a1,a2,mode) */ NPY_NO_EXPORT PyObject * PyArray_Correlate(PyObject *op1, PyObject *op2, int mode) { PyArrayObject *ap1, *ap2, *ret = NULL; int typenum; int unused; PyArray_Descr *typec; typenum = PyArray_ObjectType(op1, 0); typenum = PyArray_ObjectType(op2, typenum); typec = PyArray_DescrFromType(typenum); Py_INCREF(typec); ap1 = (PyArrayObject *)PyArray_FromAny(op1, typec, 1, 1, NPY_ARRAY_DEFAULT, NULL); if (ap1 == NULL) { Py_DECREF(typec); return NULL; } ap2 = (PyArrayObject *)PyArray_FromAny(op2, typec, 1, 1, NPY_ARRAY_DEFAULT, NULL); if (ap2 == NULL) { goto fail; } ret = _pyarray_correlate(ap1, ap2, typenum, mode, &unused); if(ret == NULL) { goto fail; } Py_DECREF(ap1); Py_DECREF(ap2); return (PyObject *)ret; fail: Py_XDECREF(ap1); Py_XDECREF(ap2); Py_XDECREF(ret); return NULL; } static PyObject * array_putmask(PyObject *NPY_UNUSED(module), PyObject *args, PyObject *kwds) { PyObject *mask, *values; PyObject *array; static char *kwlist[] = {"arr", "mask", "values", NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!OO:putmask", kwlist, &PyArray_Type, &array, &mask, &values)) { return NULL; } return PyArray_PutMask((PyArrayObject *)array, values, mask); } /* * Compare the field dictionaries for two types. * * Return 1 if the contents are the same, 0 if not. */ static int _equivalent_fields(PyObject *field1, PyObject *field2) { int same, val; if (field1 == field2) { return 1; } 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; } else { same = 1; } PyErr_Clear(); return same; } /* * Compare the subarray data for two types. * Return 1 if they are the same, 0 if not. */ static int _equivalent_subarrays(PyArray_ArrayDescr *sub1, PyArray_ArrayDescr *sub2) { int val; if (sub1 == sub2) { return 1; } if (sub1 == NULL || sub2 == NULL) { return 0; } #if defined(NPY_PY3K) val = PyObject_RichCompareBool(sub1->shape, sub2->shape, Py_EQ); if (val != 1 || PyErr_Occurred()) { #else val = PyObject_Compare(sub1->shape, sub2->shape); if (val != 0 || PyErr_Occurred()) { #endif PyErr_Clear(); return 0; } return PyArray_EquivTypes(sub1->base, sub2->base); } /*NUMPY_API * * This function returns true if the two typecodes are * equivalent (same basic kind and same itemsize). */ NPY_NO_EXPORT unsigned char PyArray_EquivTypes(PyArray_Descr *type1, PyArray_Descr *type2) { int type_num1, type_num2, size1, size2; if (type1 == type2) { return NPY_TRUE; } type_num1 = type1->type_num; type_num2 = type2->type_num; size1 = type1->elsize; size2 = type2->elsize; if (size1 != size2) { return NPY_FALSE; } if (PyArray_ISNBO(type1->byteorder) != PyArray_ISNBO(type2->byteorder)) { return NPY_FALSE; } if (type1->subarray || type2->subarray) { return ((type_num1 == type_num2) && _equivalent_subarrays(type1->subarray, type2->subarray)); } if (type_num1 == NPY_VOID || type_num2 == NPY_VOID) { return ((type_num1 == type_num2) && _equivalent_fields(type1->fields, type2->fields)); } if (type_num1 == NPY_DATETIME || type_num1 == NPY_DATETIME || type_num2 == NPY_TIMEDELTA || type_num2 == NPY_TIMEDELTA) { return ((type_num1 == type_num2) && has_equivalent_datetime_metadata(type1, type2)); } return type1->kind == type2->kind; } /*NUMPY_API*/ NPY_NO_EXPORT unsigned char PyArray_EquivTypenums(int typenum1, int typenum2) { PyArray_Descr *d1, *d2; npy_bool ret; d1 = PyArray_DescrFromType(typenum1); d2 = PyArray_DescrFromType(typenum2); ret = PyArray_EquivTypes(d1, d2); Py_DECREF(d1); Py_DECREF(d2); return ret; } /*** END C-API FUNCTIONS **/ /* * NPY_RELAXED_STRIDES_CHECKING: If the strides logic is changed, the * order specific stride setting is not necessary. */ static PyObject * _prepend_ones(PyArrayObject *arr, int nd, int ndmin, NPY_ORDER order) { npy_intp newdims[NPY_MAXDIMS]; npy_intp newstrides[NPY_MAXDIMS]; npy_intp newstride; int i, k, num; PyArrayObject *ret; PyArray_Descr *dtype; if (order == NPY_FORTRANORDER || PyArray_ISFORTRAN(arr) || PyArray_NDIM(arr) == 0) { newstride = PyArray_DESCR(arr)->elsize; } else { newstride = PyArray_STRIDES(arr)[0] * PyArray_DIMS(arr)[0]; } num = ndmin - nd; for (i = 0; i < num; i++) { newdims[i] = 1; newstrides[i] = newstride; } for (i = num; i < ndmin; i++) { k = i - num; newdims[i] = PyArray_DIMS(arr)[k]; newstrides[i] = PyArray_STRIDES(arr)[k]; } dtype = PyArray_DESCR(arr); Py_INCREF(dtype); ret = (PyArrayObject *)PyArray_NewFromDescr(Py_TYPE(arr), dtype, ndmin, newdims, newstrides, PyArray_DATA(arr), PyArray_FLAGS(arr), (PyObject *)arr); if (ret == NULL) { return NULL; } /* steals a reference to arr --- so don't increment here */ if (PyArray_SetBaseObject(ret, (PyObject *)arr) < 0) { Py_DECREF(ret); return NULL; } return (PyObject *)ret; } #define STRIDING_OK(op, order) \ ((order) == NPY_ANYORDER || \ (order) == NPY_KEEPORDER || \ ((order) == NPY_CORDER && PyArray_IS_C_CONTIGUOUS(op)) || \ ((order) == NPY_FORTRANORDER && PyArray_IS_F_CONTIGUOUS(op))) static PyObject * _array_fromobject(PyObject *NPY_UNUSED(ignored), PyObject *args, PyObject *kws) { PyObject *op; PyArrayObject *oparr = NULL, *ret = NULL; npy_bool subok = NPY_FALSE; npy_bool copy = NPY_TRUE; int ndmin = 0, nd; PyArray_Descr *type = NULL; PyArray_Descr *oldtype = NULL; NPY_ORDER order = NPY_KEEPORDER; int flags = 0; static char *kwd[]= {"object", "dtype", "copy", "order", "subok", "ndmin", NULL}; if (PyTuple_GET_SIZE(args) > 2) { PyErr_SetString(PyExc_ValueError, "only 2 non-keyword arguments accepted"); return NULL; } if(!PyArg_ParseTupleAndKeywords(args, kws, "O|O&O&O&O&i", kwd, &op, PyArray_DescrConverter2, &type, PyArray_BoolConverter, ©, PyArray_OrderConverter, &order, PyArray_BoolConverter, &subok, &ndmin)) { goto clean_type; } if (ndmin > NPY_MAXDIMS) { PyErr_Format(PyExc_ValueError, "ndmin bigger than allowable number of dimensions " "NPY_MAXDIMS (=%d)", NPY_MAXDIMS); goto clean_type; } /* fast exit if simple call */ if ((subok && PyArray_Check(op)) || (!subok && PyArray_CheckExact(op))) { oparr = (PyArrayObject *)op; if (type == NULL) { if (!copy && STRIDING_OK(oparr, order)) { ret = oparr; Py_INCREF(ret); goto finish; } else { ret = (PyArrayObject *)PyArray_NewCopy(oparr, order); goto finish; } } /* One more chance */ oldtype = PyArray_DESCR(oparr); if (PyArray_EquivTypes(oldtype, type)) { if (!copy && STRIDING_OK(oparr, order)) { Py_INCREF(op); ret = oparr; goto finish; } else { ret = (PyArrayObject *)PyArray_NewCopy(oparr, order); if (oldtype == type || ret == NULL) { goto finish; } Py_INCREF(oldtype); Py_DECREF(PyArray_DESCR(ret)); ((PyArrayObject_fields *)ret)->descr = oldtype; goto finish; } } } if (copy) { flags = NPY_ARRAY_ENSURECOPY; } if (order == NPY_CORDER) { flags |= NPY_ARRAY_C_CONTIGUOUS; } else if ((order == NPY_FORTRANORDER) /* order == NPY_ANYORDER && */ || (PyArray_Check(op) && PyArray_ISFORTRAN((PyArrayObject *)op))) { flags |= NPY_ARRAY_F_CONTIGUOUS; } if (!subok) { flags |= NPY_ARRAY_ENSUREARRAY; } flags |= NPY_ARRAY_FORCECAST; Py_XINCREF(type); ret = (PyArrayObject *)PyArray_CheckFromAny(op, type, 0, 0, flags, NULL); finish: Py_XDECREF(type); if (ret == NULL) { return NULL; } nd = PyArray_NDIM(ret); if (nd >= ndmin) { return (PyObject *)ret; } /* * create a new array from the same data with ones in the shape * steals a reference to ret */ return _prepend_ones(ret, nd, ndmin, order); clean_type: Py_XDECREF(type); return NULL; } static PyObject * array_copyto(PyObject *NPY_UNUSED(ignored), PyObject *args, PyObject *kwds) { static char *kwlist[] = {"dst","src","casting","where",NULL}; PyObject *wheremask_in = NULL; PyArrayObject *dst = NULL, *src = NULL, *wheremask = NULL; NPY_CASTING casting = NPY_SAME_KIND_CASTING; if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!O&|O&O", kwlist, &PyArray_Type, &dst, &PyArray_Converter, &src, &PyArray_CastingConverter, &casting, &wheremask_in)) { goto fail; } if (wheremask_in != NULL) { /* Get the boolean where mask */ PyArray_Descr *dtype = PyArray_DescrFromType(NPY_BOOL); if (dtype == NULL) { goto fail; } wheremask = (PyArrayObject *)PyArray_FromAny(wheremask_in, dtype, 0, 0, 0, NULL); if (wheremask == NULL) { goto fail; } } if (PyArray_AssignArray(dst, src, wheremask, casting) < 0) { goto fail; } Py_XDECREF(src); Py_XDECREF(wheremask); Py_INCREF(Py_None); return Py_None; fail: Py_XDECREF(src); Py_XDECREF(wheremask); return NULL; } static PyObject * array_empty(PyObject *NPY_UNUSED(ignored), PyObject *args, PyObject *kwds) { static char *kwlist[] = {"shape","dtype","order",NULL}; PyArray_Descr *typecode = NULL; PyArray_Dims shape = {NULL, 0}; NPY_ORDER order = NPY_CORDER; npy_bool is_f_order; PyArrayObject *ret = NULL; if (!PyArg_ParseTupleAndKeywords(args, kwds, "O&|O&O&", kwlist, PyArray_IntpConverter, &shape, PyArray_DescrConverter, &typecode, PyArray_OrderConverter, &order)) { goto fail; } switch (order) { case NPY_CORDER: is_f_order = NPY_FALSE; break; case NPY_FORTRANORDER: is_f_order = NPY_TRUE; break; default: PyErr_SetString(PyExc_ValueError, "only 'C' or 'F' order is permitted"); goto fail; } ret = (PyArrayObject *)PyArray_Empty(shape.len, shape.ptr, typecode, is_f_order); PyDimMem_FREE(shape.ptr); return (PyObject *)ret; fail: Py_XDECREF(typecode); PyDimMem_FREE(shape.ptr); return NULL; } static PyObject * array_empty_like(PyObject *NPY_UNUSED(ignored), PyObject *args, PyObject *kwds) { static char *kwlist[] = {"prototype","dtype","order","subok",NULL}; PyArrayObject *prototype = NULL; PyArray_Descr *dtype = NULL; NPY_ORDER order = NPY_KEEPORDER; PyArrayObject *ret = NULL; int subok = 1; if (!PyArg_ParseTupleAndKeywords(args, kwds, "O&|O&O&i", kwlist, &PyArray_Converter, &prototype, &PyArray_DescrConverter2, &dtype, &PyArray_OrderConverter, &order, &subok)) { goto fail; } /* steals the reference to dtype if it's not NULL */ ret = (PyArrayObject *)PyArray_NewLikeArray(prototype, order, dtype, subok); Py_DECREF(prototype); return (PyObject *)ret; fail: Py_XDECREF(prototype); Py_XDECREF(dtype); return NULL; } /* * This function is needed for supporting Pickles of * numpy scalar objects. */ static PyObject * array_scalar(PyObject *NPY_UNUSED(ignored), PyObject *args, PyObject *kwds) { static char *kwlist[] = {"dtype","obj", NULL}; PyArray_Descr *typecode; PyObject *obj = NULL; int alloc = 0; void *dptr; PyObject *ret; if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!|O", kwlist, &PyArrayDescr_Type, &typecode, &obj)) { return NULL; } if (typecode->elsize == 0) { PyErr_SetString(PyExc_ValueError, "itemsize cannot be zero"); return NULL; } if (PyDataType_FLAGCHK(typecode, NPY_ITEM_IS_POINTER)) { if (obj == NULL) { obj = Py_None; } dptr = &obj; } else { if (obj == NULL) { dptr = PyArray_malloc(typecode->elsize); if (dptr == NULL) { return PyErr_NoMemory(); } memset(dptr, '\0', typecode->elsize); alloc = 1; } else { if (!PyString_Check(obj)) { PyErr_SetString(PyExc_TypeError, "initializing object must be a string"); return NULL; } if (PyString_GET_SIZE(obj) < typecode->elsize) { PyErr_SetString(PyExc_ValueError, "initialization string is too small"); return NULL; } dptr = PyString_AS_STRING(obj); } } ret = PyArray_Scalar(dptr, typecode, NULL); /* free dptr which contains zeros */ if (alloc) { PyArray_free(dptr); } return ret; } static PyObject * array_zeros(PyObject *NPY_UNUSED(ignored), PyObject *args, PyObject *kwds) { static char *kwlist[] = {"shape","dtype","order",NULL}; PyArray_Descr *typecode = NULL; PyArray_Dims shape = {NULL, 0}; NPY_ORDER order = NPY_CORDER; npy_bool is_f_order = NPY_FALSE; PyArrayObject *ret = NULL; if (!PyArg_ParseTupleAndKeywords(args, kwds, "O&|O&O&", kwlist, PyArray_IntpConverter, &shape, PyArray_DescrConverter, &typecode, PyArray_OrderConverter, &order)) { goto fail; } switch (order) { case NPY_CORDER: is_f_order = NPY_FALSE; break; case NPY_FORTRANORDER: is_f_order = NPY_TRUE; break; default: PyErr_SetString(PyExc_ValueError, "only 'C' or 'F' order is permitted"); goto fail; } ret = (PyArrayObject *)PyArray_Zeros(shape.len, shape.ptr, typecode, (int) is_f_order); PyDimMem_FREE(shape.ptr); return (PyObject *)ret; fail: Py_XDECREF(typecode); PyDimMem_FREE(shape.ptr); return (PyObject *)ret; } static PyObject * array_count_nonzero(PyObject *NPY_UNUSED(self), PyObject *args, PyObject *kwds) { PyObject *array_in; PyArrayObject *array; npy_intp count; if (!PyArg_ParseTuple(args, "O", &array_in)) { return NULL; } array = (PyArrayObject *)PyArray_FromAny(array_in, NULL, 0, 0, 0, NULL); if (array == NULL) { return NULL; } count = PyArray_CountNonzero(array); Py_DECREF(array); if (count == -1) { return NULL; } #if defined(NPY_PY3K) return PyLong_FromSsize_t(count); #else return PyInt_FromSsize_t(count); #endif } static PyObject * array_fromstring(PyObject *NPY_UNUSED(ignored), PyObject *args, PyObject *keywds) { char *data; Py_ssize_t nin = -1; char *sep = NULL; Py_ssize_t s; static char *kwlist[] = {"string", "dtype", "count", "sep", NULL}; PyArray_Descr *descr = NULL; if (!PyArg_ParseTupleAndKeywords(args, keywds, "s#|O&" NPY_SSIZE_T_PYFMT "s", kwlist, &data, &s, PyArray_DescrConverter, &descr, &nin, &sep)) { Py_XDECREF(descr); return NULL; } return PyArray_FromString(data, (npy_intp)s, descr, (npy_intp)nin, sep); } static PyObject * array_fromfile(PyObject *NPY_UNUSED(ignored), PyObject *args, PyObject *keywds) { PyObject *file = NULL, *ret; char *sep = ""; Py_ssize_t nin = -1; static char *kwlist[] = {"file", "dtype", "count", "sep", NULL}; PyArray_Descr *type = NULL; int own; npy_off_t orig_pos; FILE *fp; if (!PyArg_ParseTupleAndKeywords(args, keywds, "O|O&" NPY_SSIZE_T_PYFMT "s", kwlist, &file, PyArray_DescrConverter, &type, &nin, &sep)) { Py_XDECREF(type); return NULL; } if (PyString_Check(file) || PyUnicode_Check(file)) { file = npy_PyFile_OpenFile(file, "rb"); if (file == NULL) { return NULL; } own = 1; } else { Py_INCREF(file); own = 0; } fp = npy_PyFile_Dup2(file, "rb", &orig_pos); if (fp == NULL) { PyErr_SetString(PyExc_IOError, "first argument must be an open file"); Py_DECREF(file); return NULL; } if (type == NULL) { type = PyArray_DescrFromType(NPY_DEFAULT_TYPE); } ret = PyArray_FromFile(fp, type, (npy_intp) nin, sep); if (npy_PyFile_DupClose2(file, fp, orig_pos) < 0) { goto fail; } if (own && npy_PyFile_CloseFile(file) < 0) { goto fail; } Py_DECREF(file); return ret; fail: Py_DECREF(file); Py_DECREF(ret); return NULL; } static PyObject * array_fromiter(PyObject *NPY_UNUSED(ignored), PyObject *args, PyObject *keywds) { PyObject *iter; Py_ssize_t nin = -1; static char *kwlist[] = {"iter", "dtype", "count", NULL}; PyArray_Descr *descr = NULL; if (!PyArg_ParseTupleAndKeywords(args, keywds, "OO&|" NPY_SSIZE_T_PYFMT, kwlist, &iter, PyArray_DescrConverter, &descr, &nin)) { Py_XDECREF(descr); return NULL; } return PyArray_FromIter(iter, descr, (npy_intp)nin); } static PyObject * array_frombuffer(PyObject *NPY_UNUSED(ignored), PyObject *args, PyObject *keywds) { PyObject *obj = NULL; Py_ssize_t nin = -1, offset = 0; static char *kwlist[] = {"buffer", "dtype", "count", "offset", NULL}; PyArray_Descr *type = NULL; if (!PyArg_ParseTupleAndKeywords(args, keywds, "O|O&" NPY_SSIZE_T_PYFMT NPY_SSIZE_T_PYFMT, kwlist, &obj, PyArray_DescrConverter, &type, &nin, &offset)) { Py_XDECREF(type); return NULL; } if (type == NULL) { type = PyArray_DescrFromType(NPY_DEFAULT_TYPE); } return PyArray_FromBuffer(obj, type, (npy_intp)nin, (npy_intp)offset); } static PyObject * array_concatenate(PyObject *NPY_UNUSED(dummy), PyObject *args, PyObject *kwds) { PyObject *a0; int axis = 0; static char *kwlist[] = {"seq", "axis", NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O&", kwlist, &a0, PyArray_AxisConverter, &axis)) { return NULL; } return PyArray_Concatenate(a0, axis); } static PyObject * array_innerproduct(PyObject *NPY_UNUSED(dummy), PyObject *args) { PyObject *b0, *a0; if (!PyArg_ParseTuple(args, "OO", &a0, &b0)) { return NULL; } return PyArray_Return((PyArrayObject *)PyArray_InnerProduct(a0, b0)); } static PyObject * array_matrixproduct(PyObject *NPY_UNUSED(dummy), PyObject *args, PyObject* kwds) { PyObject *v, *a, *o = NULL; char* kwlist[] = {"a", "b", "out", NULL }; if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO|O", kwlist, &a, &v, &o)) { return NULL; } if (o == Py_None) { o = NULL; } if (o != NULL && !PyArray_Check(o)) { PyErr_SetString(PyExc_TypeError, "'out' must be an array"); return NULL; } return PyArray_Return((PyArrayObject *)PyArray_MatrixProduct2(a, v, (PyArrayObject *)o)); } static int einsum_sub_op_from_str(PyObject *args, PyObject **str_obj, char **subscripts, PyArrayObject **op) { int i, nop; PyObject *subscripts_str; nop = PyTuple_GET_SIZE(args) - 1; if (nop <= 0) { PyErr_SetString(PyExc_ValueError, "must specify the einstein sum subscripts string " "and at least one operand"); return -1; } else if (nop >= NPY_MAXARGS) { PyErr_SetString(PyExc_ValueError, "too many operands"); return -1; } /* Get the subscripts string */ subscripts_str = PyTuple_GET_ITEM(args, 0); if (PyUnicode_Check(subscripts_str)) { *str_obj = PyUnicode_AsASCIIString(subscripts_str); if (*str_obj == NULL) { return -1; } subscripts_str = *str_obj; } *subscripts = PyBytes_AsString(subscripts_str); if (*subscripts == NULL) { Py_XDECREF(*str_obj); *str_obj = NULL; return -1; } /* Set the operands to NULL */ for (i = 0; i < nop; ++i) { op[i] = NULL; } /* Get the operands */ for (i = 0; i < nop; ++i) { PyObject *obj = PyTuple_GET_ITEM(args, i+1); op[i] = (PyArrayObject *)PyArray_FromAny(obj, NULL, 0, 0, NPY_ARRAY_ENSUREARRAY, NULL); if (op[i] == NULL) { goto fail; } } return nop; fail: for (i = 0; i < nop; ++i) { Py_XDECREF(op[i]); op[i] = NULL; } return -1; } /* * Converts a list of subscripts to a string. * * Returns -1 on error, the number of characters placed in subscripts * otherwise. */ static int einsum_list_to_subscripts(PyObject *obj, char *subscripts, int subsize) { int ellipsis = 0, subindex = 0; npy_intp i, size; PyObject *item; obj = PySequence_Fast(obj, "the subscripts for each operand must " "be a list or a tuple"); if (obj == NULL) { return -1; } size = PySequence_Size(obj); for (i = 0; i < size; ++i) { item = PySequence_Fast_GET_ITEM(obj, i); /* Ellipsis */ if (item == Py_Ellipsis) { if (ellipsis) { PyErr_SetString(PyExc_ValueError, "each subscripts list may have only one ellipsis"); Py_DECREF(obj); return -1; } if (subindex + 3 >= subsize) { PyErr_SetString(PyExc_ValueError, "subscripts list is too long"); Py_DECREF(obj); return -1; } subscripts[subindex++] = '.'; subscripts[subindex++] = '.'; subscripts[subindex++] = '.'; ellipsis = 1; } /* Subscript */ else if (PyInt_Check(item) || PyLong_Check(item)) { long s = PyInt_AsLong(item); if ( s < 0 || s > 2*26) { PyErr_SetString(PyExc_ValueError, "subscript is not within the valid range [0, 52]"); Py_DECREF(obj); return -1; } if (s < 26) { subscripts[subindex++] = 'A' + s; } else { subscripts[subindex++] = 'a' + s; } if (subindex >= subsize) { PyErr_SetString(PyExc_ValueError, "subscripts list is too long"); Py_DECREF(obj); return -1; } } /* Invalid */ else { PyErr_SetString(PyExc_ValueError, "each subscript must be either an integer " "or an ellipsis"); Py_DECREF(obj); return -1; } } Py_DECREF(obj); return subindex; } /* * Fills in the subscripts, with maximum size subsize, and op, * with the values in the tuple 'args'. * * Returns -1 on error, number of operands placed in op otherwise. */ static int einsum_sub_op_from_lists(PyObject *args, char *subscripts, int subsize, PyArrayObject **op) { int subindex = 0; npy_intp i, nop; nop = PyTuple_Size(args)/2; if (nop == 0) { PyErr_SetString(PyExc_ValueError, "must provide at least an " "operand and a subscripts list to einsum"); return -1; } else if(nop >= NPY_MAXARGS) { PyErr_SetString(PyExc_ValueError, "too many operands"); return -1; } /* Set the operands to NULL */ for (i = 0; i < nop; ++i) { op[i] = NULL; } /* Get the operands and build the subscript string */ for (i = 0; i < nop; ++i) { PyObject *obj = PyTuple_GET_ITEM(args, 2*i); int n; /* Comma between the subscripts for each operand */ if (i != 0) { subscripts[subindex++] = ','; if (subindex >= subsize) { PyErr_SetString(PyExc_ValueError, "subscripts list is too long"); goto fail; } } op[i] = (PyArrayObject *)PyArray_FromAny(obj, NULL, 0, 0, NPY_ARRAY_ENSUREARRAY, NULL); if (op[i] == NULL) { goto fail; } obj = PyTuple_GET_ITEM(args, 2*i+1); n = einsum_list_to_subscripts(obj, subscripts+subindex, subsize-subindex); if (n < 0) { goto fail; } subindex += n; } /* Add the '->' to the string if provided */ if (PyTuple_Size(args) == 2*nop+1) { PyObject *obj; int n; if (subindex + 2 >= subsize) { PyErr_SetString(PyExc_ValueError, "subscripts list is too long"); goto fail; } subscripts[subindex++] = '-'; subscripts[subindex++] = '>'; obj = PyTuple_GET_ITEM(args, 2*nop); n = einsum_list_to_subscripts(obj, subscripts+subindex, subsize-subindex); if (n < 0) { goto fail; } subindex += n; } /* NULL-terminate the subscripts string */ subscripts[subindex] = '\0'; return nop; fail: for (i = 0; i < nop; ++i) { Py_XDECREF(op[i]); op[i] = NULL; } return -1; } static PyObject * array_einsum(PyObject *NPY_UNUSED(dummy), PyObject *args, PyObject *kwds) { char *subscripts = NULL, subscripts_buffer[256]; PyObject *str_obj = NULL, *str_key_obj = NULL; PyObject *arg0; int i, nop; PyArrayObject *op[NPY_MAXARGS]; NPY_ORDER order = NPY_KEEPORDER; NPY_CASTING casting = NPY_SAFE_CASTING; PyArrayObject *out = NULL; PyArray_Descr *dtype = NULL; PyObject *ret = NULL; if (PyTuple_GET_SIZE(args) < 1) { PyErr_SetString(PyExc_ValueError, "must specify the einstein sum subscripts string " "and at least one operand, or at least one operand " "and its corresponding subscripts list"); return NULL; } arg0 = PyTuple_GET_ITEM(args, 0); /* einsum('i,j', a, b), einsum('i,j->ij', a, b) */ if (PyString_Check(arg0) || PyUnicode_Check(arg0)) { nop = einsum_sub_op_from_str(args, &str_obj, &subscripts, op); } /* einsum(a, [0], b, [1]), einsum(a, [0], b, [1], [0,1]) */ else { nop = einsum_sub_op_from_lists(args, subscripts_buffer, sizeof(subscripts_buffer), op); subscripts = subscripts_buffer; } if (nop <= 0) { goto finish; } /* Get the keyword arguments */ if (kwds != NULL) { PyObject *key, *value; Py_ssize_t pos = 0; while (PyDict_Next(kwds, &pos, &key, &value)) { char *str = NULL; #if defined(NPY_PY3K) Py_XDECREF(str_key_obj); str_key_obj = PyUnicode_AsASCIIString(key); if (str_key_obj != NULL) { key = str_key_obj; } #endif str = PyBytes_AsString(key); if (str == NULL) { PyErr_Clear(); PyErr_SetString(PyExc_TypeError, "invalid keyword"); goto finish; } if (strcmp(str,"out") == 0) { if (PyArray_Check(value)) { out = (PyArrayObject *)value; } else { PyErr_SetString(PyExc_TypeError, "keyword parameter out must be an " "array for einsum"); goto finish; } } else if (strcmp(str,"order") == 0) { if (!PyArray_OrderConverter(value, &order)) { goto finish; } } else if (strcmp(str,"casting") == 0) { if (!PyArray_CastingConverter(value, &casting)) { goto finish; } } else if (strcmp(str,"dtype") == 0) { if (!PyArray_DescrConverter2(value, &dtype)) { goto finish; } } else { PyErr_Format(PyExc_TypeError, "'%s' is an invalid keyword for einsum", str); goto finish; } } } ret = (PyObject *)PyArray_EinsteinSum(subscripts, nop, op, dtype, order, casting, out); /* If no output was supplied, possibly convert to a scalar */ if (ret != NULL && out == NULL) { ret = PyArray_Return((PyArrayObject *)ret); } finish: for (i = 0; i < nop; ++i) { Py_XDECREF(op[i]); } Py_XDECREF(dtype); Py_XDECREF(str_obj); Py_XDECREF(str_key_obj); /* out is a borrowed reference */ return ret; } static PyObject * array_fastCopyAndTranspose(PyObject *NPY_UNUSED(dummy), PyObject *args) { PyObject *a0; if (!PyArg_ParseTuple(args, "O", &a0)) { return NULL; } return PyArray_Return((PyArrayObject *)PyArray_CopyAndTranspose(a0)); } static PyObject * array_correlate(PyObject *NPY_UNUSED(dummy), PyObject *args, PyObject *kwds) { PyObject *shape, *a0; int mode = 0; static char *kwlist[] = {"a", "v", "mode", NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO|i", kwlist, &a0, &shape, &mode)) { return NULL; } return PyArray_Correlate(a0, shape, mode); } static PyObject* array_correlate2(PyObject *NPY_UNUSED(dummy), PyObject *args, PyObject *kwds) { PyObject *shape, *a0; int mode = 0; static char *kwlist[] = {"a", "v", "mode", NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO|i", kwlist, &a0, &shape, &mode)) { return NULL; } return PyArray_Correlate2(a0, shape, mode); } static PyObject * array_arange(PyObject *NPY_UNUSED(ignored), PyObject *args, PyObject *kws) { PyObject *o_start = NULL, *o_stop = NULL, *o_step = NULL, *range=NULL; static char *kwd[]= {"start", "stop", "step", "dtype", NULL}; PyArray_Descr *typecode = NULL; if(!PyArg_ParseTupleAndKeywords(args, kws, "O|OOO&", kwd, &o_start, &o_stop, &o_step, PyArray_DescrConverter2, &typecode)) { Py_XDECREF(typecode); return NULL; } range = PyArray_ArangeObj(o_start, o_stop, o_step, typecode); Py_XDECREF(typecode); return range; } /*NUMPY_API * * Included at the very first so not auto-grabbed and thus not labeled. */ NPY_NO_EXPORT unsigned int PyArray_GetNDArrayCVersion(void) { return (unsigned int)NPY_ABI_VERSION; } /*NUMPY_API * Returns the built-in (at compilation time) C API version */ NPY_NO_EXPORT unsigned int PyArray_GetNDArrayCFeatureVersion(void) { return (unsigned int)NPY_API_VERSION; } static PyObject * array__get_ndarray_c_version(PyObject *NPY_UNUSED(dummy), PyObject *args, PyObject *kwds) { static char *kwlist[] = {NULL}; if(!PyArg_ParseTupleAndKeywords(args, kwds, "", kwlist )) { return NULL; } return PyInt_FromLong( (long) PyArray_GetNDArrayCVersion() ); } /*NUMPY_API */ NPY_NO_EXPORT int PyArray_GetEndianness(void) { const union { npy_uint32 i; char c[4]; } bint = {0x01020304}; if (bint.c[0] == 1) { return NPY_CPU_BIG; } else if (bint.c[0] == 4) { return NPY_CPU_LITTLE; } else { return NPY_CPU_UNKNOWN_ENDIAN; } } static PyObject * array__reconstruct(PyObject *NPY_UNUSED(dummy), PyObject *args) { PyObject *ret; PyTypeObject *subtype; PyArray_Dims shape = {NULL, 0}; PyArray_Descr *dtype = NULL; evil_global_disable_warn_O4O8_flag = 1; if (!PyArg_ParseTuple(args, "O!O&O&", &PyType_Type, &subtype, PyArray_IntpConverter, &shape, PyArray_DescrConverter, &dtype)) { goto fail; } if (!PyType_IsSubtype(subtype, &PyArray_Type)) { PyErr_SetString(PyExc_TypeError, "_reconstruct: First argument must be a sub-type of ndarray"); goto fail; } ret = PyArray_NewFromDescr(subtype, dtype, (int)shape.len, shape.ptr, NULL, NULL, 0, NULL); if (shape.ptr) { PyDimMem_FREE(shape.ptr); } evil_global_disable_warn_O4O8_flag = 0; return ret; fail: evil_global_disable_warn_O4O8_flag = 0; Py_XDECREF(dtype); if (shape.ptr) { PyDimMem_FREE(shape.ptr); } return NULL; } static PyObject * array_set_string_function(PyObject *NPY_UNUSED(self), PyObject *args, PyObject *kwds) { PyObject *op = NULL; int repr = 1; static char *kwlist[] = {"f", "repr", NULL}; if(!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi", kwlist, &op, &repr)) { return NULL; } /* reset the array_repr function to built-in */ if (op == Py_None) { op = NULL; } if (op != NULL && !PyCallable_Check(op)) { PyErr_SetString(PyExc_TypeError, "Argument must be callable."); return NULL; } PyArray_SetStringFunction(op, repr); Py_INCREF(Py_None); return Py_None; } static PyObject * array_set_ops_function(PyObject *NPY_UNUSED(self), PyObject *NPY_UNUSED(args), PyObject *kwds) { PyObject *oldops = NULL; if ((oldops = PyArray_GetNumericOps()) == NULL) { return NULL; } /* * Should probably ensure that objects are at least callable * Leave this to the caller for now --- error will be raised * later when use is attempted */ if (kwds && PyArray_SetNumericOps(kwds) == -1) { Py_DECREF(oldops); PyErr_SetString(PyExc_ValueError, "one or more objects not callable"); return NULL; } return oldops; } static PyObject * array_set_datetimeparse_function(PyObject *NPY_UNUSED(self), PyObject *NPY_UNUSED(args), PyObject *NPY_UNUSED(kwds)) { PyErr_SetString(PyExc_RuntimeError, "This function has been removed"); return NULL; } /*NUMPY_API * Where */ NPY_NO_EXPORT PyObject * PyArray_Where(PyObject *condition, PyObject *x, PyObject *y) { PyArrayObject *arr; PyObject *tup = NULL, *obj = NULL; PyObject *ret = NULL, *zero = NULL; arr = (PyArrayObject *)PyArray_FromAny(condition, NULL, 0, 0, 0, NULL); if (arr == NULL) { return NULL; } if ((x == NULL) && (y == NULL)) { ret = PyArray_Nonzero(arr); Py_DECREF(arr); return ret; } if ((x == NULL) || (y == NULL)) { Py_DECREF(arr); PyErr_SetString(PyExc_ValueError, "either both or neither of x and y should be given"); 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; } tup = Py_BuildValue("(OO)", y, x); if (tup == NULL) { Py_DECREF(obj); return NULL; } ret = PyArray_Choose((PyArrayObject *)obj, tup, NULL, NPY_RAISE); Py_DECREF(obj); Py_DECREF(tup); return ret; } static PyObject * array_where(PyObject *NPY_UNUSED(ignored), PyObject *args) { PyObject *obj = NULL, *x = NULL, *y = NULL; if (!PyArg_ParseTuple(args, "O|OO", &obj, &x, &y)) { return NULL; } return PyArray_Where(obj, x, y); } static PyObject * array_lexsort(PyObject *NPY_UNUSED(ignored), PyObject *args, PyObject *kwds) { int axis = -1; PyObject *obj; static char *kwlist[] = {"keys", "axis", NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|i", kwlist, &obj, &axis)) { return NULL; } return PyArray_Return((PyArrayObject *)PyArray_LexSort(obj, axis)); } static PyObject * array_can_cast_safely(PyObject *NPY_UNUSED(self), PyObject *args, PyObject *kwds) { PyObject *from_obj = NULL; PyArray_Descr *d1 = NULL; PyArray_Descr *d2 = NULL; npy_bool ret; PyObject *retobj = NULL; NPY_CASTING casting = NPY_SAFE_CASTING; static char *kwlist[] = {"from", "to", "casting", NULL}; if(!PyArg_ParseTupleAndKeywords(args, kwds, "OO&|O&", kwlist, &from_obj, PyArray_DescrConverter2, &d2, PyArray_CastingConverter, &casting)) { goto finish; } if (d2 == NULL) { PyErr_SetString(PyExc_TypeError, "did not understand one of the types; 'None' not accepted"); goto finish; } /* If the first parameter is an object or scalar, use CanCastArrayTo */ if (PyArray_Check(from_obj)) { ret = PyArray_CanCastArrayTo((PyArrayObject *)from_obj, d2, casting); } else if (PyArray_IsScalar(from_obj, Generic) || PyArray_IsPythonNumber(from_obj)) { PyArrayObject *arr; arr = (PyArrayObject *)PyArray_FromAny(from_obj, NULL, 0, 0, 0, NULL); if (arr == NULL) { goto finish; } ret = PyArray_CanCastArrayTo(arr, d2, casting); Py_DECREF(arr); } /* Otherwise use CanCastTypeTo */ else { if (!PyArray_DescrConverter2(from_obj, &d1) || d1 == NULL) { PyErr_SetString(PyExc_TypeError, "did not understand one of the types; 'None' not accepted"); goto finish; } ret = PyArray_CanCastTypeTo(d1, d2, casting); } retobj = ret ? Py_True : Py_False; Py_INCREF(retobj); finish: Py_XDECREF(d1); Py_XDECREF(d2); return retobj; } static PyObject * array_promote_types(PyObject *NPY_UNUSED(dummy), PyObject *args) { PyArray_Descr *d1 = NULL; PyArray_Descr *d2 = NULL; PyObject *ret = NULL; if(!PyArg_ParseTuple(args, "O&O&", PyArray_DescrConverter2, &d1, PyArray_DescrConverter2, &d2)) { goto finish; } if (d1 == NULL || d2 == NULL) { PyErr_SetString(PyExc_TypeError, "did not understand one of the types"); goto finish; } ret = (PyObject *)PyArray_PromoteTypes(d1, d2); finish: Py_XDECREF(d1); Py_XDECREF(d2); return ret; } static PyObject * array_min_scalar_type(PyObject *NPY_UNUSED(dummy), PyObject *args) { PyObject *array_in = NULL; PyArrayObject *array; PyObject *ret = NULL; if(!PyArg_ParseTuple(args, "O", &array_in)) { return NULL; } array = (PyArrayObject *)PyArray_FromAny(array_in, NULL, 0, 0, 0, NULL); if (array == NULL) { return NULL; } ret = (PyObject *)PyArray_MinScalarType(array); Py_DECREF(array); return ret; } 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]; PyObject *ret = NULL; len = PyTuple_GET_SIZE(args); if (len == 0) { PyErr_SetString(PyExc_ValueError, "at least one array or dtype is required"); goto finish; } 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) { goto finish; } ++narr; } else { if (ndtypes == NPY_MAXARGS) { PyErr_SetString(PyExc_ValueError, "too many arguments"); goto finish; } if (!PyArray_DescrConverter(obj, &dtypes[ndtypes])) { goto finish; } ++ndtypes; } } ret = (PyObject *)PyArray_ResultType(narr, arr, ndtypes, dtypes); finish: for (i = 0; i < narr; ++i) { Py_DECREF(arr[i]); } for (i = 0; i < ndtypes; ++i) { Py_DECREF(dtypes[i]); } return ret; } static PyObject * array_datetime_data(PyObject *NPY_UNUSED(dummy), PyObject *args) { PyArray_Descr *dtype; PyArray_DatetimeMetaData *meta; if(!PyArg_ParseTuple(args, "O&:datetime_data", PyArray_DescrConverter, &dtype)) { return NULL; } meta = get_datetime_metadata_from_dtype(dtype); if (meta == NULL) { return NULL; } return convert_datetime_metadata_to_tuple(meta); } #if !defined(NPY_PY3K) static PyObject * new_buffer(PyObject *NPY_UNUSED(dummy), PyObject *args) { int size; if(!PyArg_ParseTuple(args, "i", &size)) { return NULL; } return PyBuffer_New(size); } static PyObject * buffer_buffer(PyObject *NPY_UNUSED(dummy), PyObject *args, PyObject *kwds) { PyObject *obj; Py_ssize_t offset = 0, n; Py_ssize_t size = Py_END_OF_BUFFER; void *unused; static char *kwlist[] = {"object", "offset", "size", NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|" NPY_SSIZE_T_PYFMT NPY_SSIZE_T_PYFMT, kwlist, &obj, &offset, &size)) { return NULL; } if (PyObject_AsWriteBuffer(obj, &unused, &n) < 0) { PyErr_Clear(); return PyBuffer_FromObject(obj, offset, size); } else { return PyBuffer_FromReadWriteObject(obj, offset, size); } } #endif #ifndef _MSC_VER #include #include jmp_buf _NPY_SIGSEGV_BUF; static void _SigSegv_Handler(int signum) { longjmp(_NPY_SIGSEGV_BUF, signum); } #endif #define _test_code() { \ test = *((char*)memptr); \ if (!ro) { \ *((char *)memptr) = '\0'; \ *((char *)memptr) = test; \ } \ test = *((char*)memptr+size-1); \ if (!ro) { \ *((char *)memptr+size-1) = '\0'; \ *((char *)memptr+size-1) = test; \ } \ } static PyObject * as_buffer(PyObject *NPY_UNUSED(dummy), PyObject *args, PyObject *kwds) { PyObject *mem; Py_ssize_t size; npy_bool ro = NPY_FALSE, check = NPY_TRUE; void *memptr; static char *kwlist[] = {"mem", "size", "readonly", "check", NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "O" NPY_SSIZE_T_PYFMT "|O&O&", kwlist, &mem, &size, PyArray_BoolConverter, &ro, PyArray_BoolConverter, &check)) { return NULL; } memptr = PyLong_AsVoidPtr(mem); if (memptr == NULL) { return NULL; } if (check) { /* * Try to dereference the start and end of the memory region * Catch segfault and report error if it occurs */ char test; int err = 0; #ifdef _MSC_VER __try { _test_code(); } __except(1) { err = 1; } #else PyOS_sighandler_t _npy_sig_save; _npy_sig_save = PyOS_setsig(SIGSEGV, _SigSegv_Handler); if (setjmp(_NPY_SIGSEGV_BUF) == 0) { _test_code(); } else { err = 1; } PyOS_setsig(SIGSEGV, _npy_sig_save); #endif if (err) { PyErr_SetString(PyExc_ValueError, "cannot use memory location as a buffer."); return NULL; } } #if defined(NPY_PY3K) PyErr_SetString(PyExc_RuntimeError, "XXX -- not implemented!"); return NULL; #else if (ro) { return PyBuffer_FromMemory(memptr, size); } return PyBuffer_FromReadWriteMemory(memptr, size); #endif } #undef _test_code static PyObject * format_longfloat(PyObject *NPY_UNUSED(dummy), PyObject *args, PyObject *kwds) { PyObject *obj; unsigned int precision; npy_longdouble x; static char *kwlist[] = {"x", "precision", NULL}; static char repr[100]; if (!PyArg_ParseTupleAndKeywords(args, kwds, "OI", kwlist, &obj, &precision)) { return NULL; } if (!PyArray_IsScalar(obj, LongDouble)) { PyErr_SetString(PyExc_TypeError, "not a longfloat"); return NULL; } x = ((PyLongDoubleScalarObject *)obj)->obval; if (precision > 70) { precision = 70; } format_longdouble(repr, 100, x, precision); return PyUString_FromString(repr); } static PyObject * compare_chararrays(PyObject *NPY_UNUSED(dummy), PyObject *args, PyObject *kwds) { PyObject *array; PyObject *other; PyArrayObject *newarr, *newoth; int cmp_op; npy_bool rstrip; char *cmp_str; Py_ssize_t strlength; PyObject *res = NULL; static char msg[] = "comparision must be '==', '!=', '<', '>', '<=', '>='"; static char *kwlist[] = {"a1", "a2", "cmp", "rstrip", NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "OOs#O&", kwlist, &array, &other, &cmp_str, &strlength, PyArray_BoolConverter, &rstrip)) { return NULL; } if (strlength < 1 || strlength > 2) { goto err; } if (strlength > 1) { if (cmp_str[1] != '=') { goto err; } if (cmp_str[0] == '=') { cmp_op = Py_EQ; } else if (cmp_str[0] == '!') { cmp_op = Py_NE; } else if (cmp_str[0] == '<') { cmp_op = Py_LE; } else if (cmp_str[0] == '>') { cmp_op = Py_GE; } else { goto err; } } else { if (cmp_str[0] == '<') { cmp_op = Py_LT; } else if (cmp_str[0] == '>') { cmp_op = Py_GT; } else { goto err; } } newarr = (PyArrayObject *)PyArray_FROM_O(array); if (newarr == NULL) { return NULL; } newoth = (PyArrayObject *)PyArray_FROM_O(other); if (newoth == NULL) { Py_DECREF(newarr); return NULL; } if (PyArray_ISSTRING(newarr) && PyArray_ISSTRING(newoth)) { res = _strings_richcompare(newarr, newoth, cmp_op, rstrip != 0); } else { PyErr_SetString(PyExc_TypeError, "comparison of non-string arrays"); } Py_DECREF(newarr); Py_DECREF(newoth); return res; err: PyErr_SetString(PyExc_ValueError, msg); return NULL; } static PyObject * _vec_string_with_args(PyArrayObject* char_array, PyArray_Descr* type, PyObject* method, PyObject* args) { PyObject* broadcast_args[NPY_MAXARGS]; PyArrayMultiIterObject* in_iter = NULL; PyArrayObject* result = NULL; PyArrayIterObject* out_iter = NULL; PyObject* args_tuple = NULL; Py_ssize_t i, n, nargs; nargs = PySequence_Size(args) + 1; if (nargs == -1 || nargs > NPY_MAXARGS) { PyErr_Format(PyExc_ValueError, "len(args) must be < %d", NPY_MAXARGS - 1); goto err; } broadcast_args[0] = (PyObject*)char_array; for (i = 1; i < nargs; i++) { PyObject* item = PySequence_GetItem(args, i-1); if (item == NULL) { goto err; } broadcast_args[i] = item; Py_DECREF(item); } in_iter = (PyArrayMultiIterObject*)PyArray_MultiIterFromObjects (broadcast_args, nargs, 0); if (in_iter == NULL) { goto err; } n = in_iter->numiter; result = (PyArrayObject*)PyArray_SimpleNewFromDescr(in_iter->nd, in_iter->dimensions, type); if (result == NULL) { goto err; } out_iter = (PyArrayIterObject*)PyArray_IterNew((PyObject*)result); if (out_iter == NULL) { goto err; } args_tuple = PyTuple_New(n); if (args_tuple == NULL) { goto err; } while (PyArray_MultiIter_NOTDONE(in_iter)) { PyObject* item_result; for (i = 0; i < n; i++) { PyArrayIterObject* it = in_iter->iters[i]; PyObject* arg = PyArray_ToScalar(PyArray_ITER_DATA(it), it->ao); if (arg == NULL) { goto err; } /* Steals ref to arg */ PyTuple_SetItem(args_tuple, i, arg); } item_result = PyObject_CallObject(method, args_tuple); if (item_result == NULL) { goto err; } if (PyArray_SETITEM(result, PyArray_ITER_DATA(out_iter), item_result)) { Py_DECREF(item_result); PyErr_SetString( PyExc_TypeError, "result array type does not match underlying function"); goto err; } Py_DECREF(item_result); PyArray_MultiIter_NEXT(in_iter); PyArray_ITER_NEXT(out_iter); } Py_DECREF(in_iter); Py_DECREF(out_iter); Py_DECREF(args_tuple); return (PyObject*)result; err: Py_XDECREF(in_iter); Py_XDECREF(out_iter); Py_XDECREF(args_tuple); Py_XDECREF(result); return 0; } static PyObject * _vec_string_no_args(PyArrayObject* char_array, PyArray_Descr* type, PyObject* method) { /* * This is a faster version of _vec_string_args to use when there * are no additional arguments to the string method. This doesn't * require a broadcast iterator (and broadcast iterators don't work * with 1 argument anyway). */ PyArrayIterObject* in_iter = NULL; PyArrayObject* result = NULL; PyArrayIterObject* out_iter = NULL; in_iter = (PyArrayIterObject*)PyArray_IterNew((PyObject*)char_array); if (in_iter == NULL) { goto err; } result = (PyArrayObject*)PyArray_SimpleNewFromDescr( PyArray_NDIM(char_array), PyArray_DIMS(char_array), type); if (result == NULL) { goto err; } out_iter = (PyArrayIterObject*)PyArray_IterNew((PyObject*)result); if (out_iter == NULL) { goto err; } while (PyArray_ITER_NOTDONE(in_iter)) { PyObject* item_result; PyObject* item = PyArray_ToScalar(in_iter->dataptr, in_iter->ao); if (item == NULL) { goto err; } item_result = PyObject_CallFunctionObjArgs(method, item, NULL); Py_DECREF(item); if (item_result == NULL) { goto err; } if (PyArray_SETITEM(result, PyArray_ITER_DATA(out_iter), item_result)) { Py_DECREF(item_result); PyErr_SetString( PyExc_TypeError, "result array type does not match underlying function"); goto err; } Py_DECREF(item_result); PyArray_ITER_NEXT(in_iter); PyArray_ITER_NEXT(out_iter); } Py_DECREF(in_iter); Py_DECREF(out_iter); return (PyObject*)result; err: Py_XDECREF(in_iter); Py_XDECREF(out_iter); Py_XDECREF(result); return 0; } static PyObject * _vec_string(PyObject *NPY_UNUSED(dummy), PyObject *args, PyObject *kwds) { PyArrayObject* char_array = NULL; PyArray_Descr *type = NULL; PyObject* method_name; PyObject* args_seq = NULL; PyObject* method = NULL; PyObject* result = NULL; if (!PyArg_ParseTuple(args, "O&O&O|O", PyArray_Converter, &char_array, PyArray_DescrConverter, &type, &method_name, &args_seq)) { goto err; } if (PyArray_TYPE(char_array) == NPY_STRING) { method = PyObject_GetAttr((PyObject *)&PyString_Type, method_name); } else if (PyArray_TYPE(char_array) == NPY_UNICODE) { method = PyObject_GetAttr((PyObject *)&PyUnicode_Type, method_name); } else { PyErr_SetString(PyExc_TypeError, "string operation on non-string array"); goto err; } if (method == NULL) { goto err; } if (args_seq == NULL || (PySequence_Check(args_seq) && PySequence_Size(args_seq) == 0)) { result = _vec_string_no_args(char_array, type, method); } else if (PySequence_Check(args_seq)) { result = _vec_string_with_args(char_array, type, method, args_seq); } else { PyErr_SetString(PyExc_TypeError, "'args' must be a sequence of arguments"); goto err; } if (result == NULL) { goto err; } Py_DECREF(char_array); Py_DECREF(method); return (PyObject*)result; err: Py_XDECREF(char_array); Py_XDECREF(method); return 0; } #ifndef __NPY_PRIVATE_NO_SIGNAL NPY_SIGJMP_BUF _NPY_SIGINT_BUF; /*NUMPY_API */ NPY_NO_EXPORT void _PyArray_SigintHandler(int signum) { PyOS_setsig(signum, SIG_IGN); NPY_SIGLONGJMP(_NPY_SIGINT_BUF, signum); } /*NUMPY_API */ NPY_NO_EXPORT void* _PyArray_GetSigintBuf(void) { return (void *)&_NPY_SIGINT_BUF; } #else NPY_NO_EXPORT void _PyArray_SigintHandler(int signum) { return; } NPY_NO_EXPORT void* _PyArray_GetSigintBuf(void) { return NULL; } #endif static PyObject * test_interrupt(PyObject *NPY_UNUSED(self), PyObject *args) { int kind = 0; int a = 0; if (!PyArg_ParseTuple(args, "|i", &kind)) { return NULL; } if (kind) { Py_BEGIN_ALLOW_THREADS; while (a >= 0) { if ((a % 1000 == 0) && PyOS_InterruptOccurred()) { break; } a += 1; } Py_END_ALLOW_THREADS; } else { NPY_SIGINT_ON while(a >= 0) { a += 1; } NPY_SIGINT_OFF } 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) { 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 (char *)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 (char *)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 (char *)result; } static PyObject * array_may_share_memory(PyObject *NPY_UNUSED(ignored), PyObject *args) { PyArrayObject * self = NULL; PyArrayObject * other = NULL; int overlap; if (!PyArg_ParseTuple(args, "O&O&", PyArray_Converter, &self, PyArray_Converter, &other)) { return NULL; } overlap = arrays_overlap(self, other); Py_XDECREF(self); Py_XDECREF(other); if (overlap) { Py_RETURN_TRUE; } else { Py_RETURN_FALSE; } } static struct PyMethodDef array_module_methods[] = { {"_get_ndarray_c_version", (PyCFunction)array__get_ndarray_c_version, METH_VARARGS|METH_KEYWORDS, NULL}, {"_reconstruct", (PyCFunction)array__reconstruct, METH_VARARGS, NULL}, {"set_string_function", (PyCFunction)array_set_string_function, METH_VARARGS|METH_KEYWORDS, NULL}, {"set_numeric_ops", (PyCFunction)array_set_ops_function, METH_VARARGS|METH_KEYWORDS, NULL}, {"set_datetimeparse_function", (PyCFunction)array_set_datetimeparse_function, METH_VARARGS|METH_KEYWORDS, NULL}, {"set_typeDict", (PyCFunction)array_set_typeDict, METH_VARARGS, NULL}, {"array", (PyCFunction)_array_fromobject, METH_VARARGS|METH_KEYWORDS, NULL}, {"copyto", (PyCFunction)array_copyto, METH_VARARGS|METH_KEYWORDS, NULL}, {"nested_iters", (PyCFunction)NpyIter_NestedIters, METH_VARARGS|METH_KEYWORDS, NULL}, {"arange", (PyCFunction)array_arange, METH_VARARGS|METH_KEYWORDS, NULL}, {"zeros", (PyCFunction)array_zeros, METH_VARARGS|METH_KEYWORDS, NULL}, {"count_nonzero", (PyCFunction)array_count_nonzero, METH_VARARGS|METH_KEYWORDS, NULL}, {"empty", (PyCFunction)array_empty, METH_VARARGS|METH_KEYWORDS, NULL}, {"empty_like", (PyCFunction)array_empty_like, METH_VARARGS|METH_KEYWORDS, NULL}, {"scalar", (PyCFunction)array_scalar, METH_VARARGS|METH_KEYWORDS, NULL}, {"where", (PyCFunction)array_where, METH_VARARGS, NULL}, {"lexsort", (PyCFunction)array_lexsort, METH_VARARGS | METH_KEYWORDS, NULL}, {"putmask", (PyCFunction)array_putmask, METH_VARARGS | METH_KEYWORDS, NULL}, {"fromstring", (PyCFunction)array_fromstring, METH_VARARGS|METH_KEYWORDS, NULL}, {"fromiter", (PyCFunction)array_fromiter, METH_VARARGS|METH_KEYWORDS, NULL}, {"concatenate", (PyCFunction)array_concatenate, METH_VARARGS|METH_KEYWORDS, NULL}, {"inner", (PyCFunction)array_innerproduct, METH_VARARGS, NULL}, {"dot", (PyCFunction)array_matrixproduct, METH_VARARGS | METH_KEYWORDS, NULL}, {"einsum", (PyCFunction)array_einsum, METH_VARARGS|METH_KEYWORDS, NULL}, {"_fastCopyAndTranspose", (PyCFunction)array_fastCopyAndTranspose, METH_VARARGS, NULL}, {"correlate", (PyCFunction)array_correlate, METH_VARARGS | METH_KEYWORDS, NULL}, {"correlate2", (PyCFunction)array_correlate2, METH_VARARGS | METH_KEYWORDS, NULL}, {"frombuffer", (PyCFunction)array_frombuffer, METH_VARARGS | METH_KEYWORDS, NULL}, {"fromfile", (PyCFunction)array_fromfile, METH_VARARGS | METH_KEYWORDS, NULL}, {"can_cast", (PyCFunction)array_can_cast_safely, METH_VARARGS | METH_KEYWORDS, NULL}, {"promote_types", (PyCFunction)array_promote_types, METH_VARARGS, NULL}, {"min_scalar_type", (PyCFunction)array_min_scalar_type, METH_VARARGS, NULL}, {"result_type", (PyCFunction)array_result_type, METH_VARARGS, NULL}, {"may_share_memory", (PyCFunction)array_may_share_memory, METH_VARARGS, NULL}, /* Datetime-related functions */ {"datetime_data", (PyCFunction)array_datetime_data, METH_VARARGS, NULL}, {"datetime_as_string", (PyCFunction)array_datetime_as_string, METH_VARARGS | METH_KEYWORDS, NULL}, /* Datetime business-day API */ {"busday_offset", (PyCFunction)array_busday_offset, METH_VARARGS | METH_KEYWORDS, NULL}, {"busday_count", (PyCFunction)array_busday_count, METH_VARARGS | METH_KEYWORDS, NULL}, {"is_busday", (PyCFunction)array_is_busday, METH_VARARGS | METH_KEYWORDS, NULL}, #if !defined(NPY_PY3K) {"newbuffer", (PyCFunction)new_buffer, METH_VARARGS, NULL}, {"getbuffer", (PyCFunction)buffer_buffer, METH_VARARGS | METH_KEYWORDS, NULL}, #endif {"int_asbuffer", (PyCFunction)as_buffer, METH_VARARGS | METH_KEYWORDS, NULL}, {"format_longfloat", (PyCFunction)format_longfloat, METH_VARARGS | METH_KEYWORDS, NULL}, {"compare_chararrays", (PyCFunction)compare_chararrays, METH_VARARGS | METH_KEYWORDS, NULL}, {"_vec_string", (PyCFunction)_vec_string, METH_VARARGS | METH_KEYWORDS, NULL}, {"test_interrupt", (PyCFunction)test_interrupt, METH_VARARGS, NULL}, {NULL, NULL, 0, NULL} /* sentinel */ }; #include "__multiarray_api.c" /* Establish scalar-type hierarchy * * For dual inheritance we need to make sure that the objects being * inherited from have the tp->mro object initialized. This is * not necessarily true for the basic type objects of Python (it is * checked for single inheritance but not dual in PyType_Ready). * * Thus, we call PyType_Ready on the standard Python Types, here. */ static int setup_scalartypes(PyObject *NPY_UNUSED(dict)) { initialize_casting_tables(); initialize_numeric_types(); if (PyType_Ready(&PyBool_Type) < 0) { return -1; } #if !defined(NPY_PY3K) if (PyType_Ready(&PyInt_Type) < 0) { return -1; } #endif if (PyType_Ready(&PyFloat_Type) < 0) { return -1; } if (PyType_Ready(&PyComplex_Type) < 0) { return -1; } if (PyType_Ready(&PyString_Type) < 0) { return -1; } if (PyType_Ready(&PyUnicode_Type) < 0) { return -1; } #define SINGLE_INHERIT(child, parent) \ Py##child##ArrType_Type.tp_base = &Py##parent##ArrType_Type; \ if (PyType_Ready(&Py##child##ArrType_Type) < 0) { \ PyErr_Print(); \ PyErr_Format(PyExc_SystemError, \ "could not initialize Py%sArrType_Type", \ #child); \ return -1; \ } if (PyType_Ready(&PyGenericArrType_Type) < 0) { return -1; } SINGLE_INHERIT(Number, Generic); SINGLE_INHERIT(Integer, Number); SINGLE_INHERIT(Inexact, Number); SINGLE_INHERIT(SignedInteger, Integer); SINGLE_INHERIT(UnsignedInteger, Integer); SINGLE_INHERIT(Floating, Inexact); SINGLE_INHERIT(ComplexFloating, Inexact); SINGLE_INHERIT(Flexible, Generic); SINGLE_INHERIT(Character, Flexible); #define DUAL_INHERIT(child, parent1, parent2) \ Py##child##ArrType_Type.tp_base = &Py##parent2##ArrType_Type; \ Py##child##ArrType_Type.tp_bases = \ Py_BuildValue("(OO)", &Py##parent2##ArrType_Type, \ &Py##parent1##_Type); \ if (PyType_Ready(&Py##child##ArrType_Type) < 0) { \ PyErr_Print(); \ PyErr_Format(PyExc_SystemError, \ "could not initialize Py%sArrType_Type", \ #child); \ return -1; \ } \ Py##child##ArrType_Type.tp_hash = Py##parent1##_Type.tp_hash; /* * In Py3K, int is no longer a fixed-width integer type, so don't * inherit numpy.int_ from it. */ #if defined(NPY_PY3K) #define INHERIT_INT(child, parent2) \ SINGLE_INHERIT(child, parent2); #else #define INHERIT_INT(child, parent2) \ Py##child##ArrType_Type.tp_flags |= Py_TPFLAGS_INT_SUBCLASS; \ DUAL_INHERIT(child, Int, parent2); #endif #if defined(NPY_PY3K) #define DUAL_INHERIT_COMPARE(child, parent1, parent2) #else #define DUAL_INHERIT_COMPARE(child, parent1, parent2) \ Py##child##ArrType_Type.tp_compare = \ Py##parent1##_Type.tp_compare; #endif #define DUAL_INHERIT2(child, parent1, parent2) \ Py##child##ArrType_Type.tp_base = &Py##parent1##_Type; \ Py##child##ArrType_Type.tp_bases = \ Py_BuildValue("(OO)", &Py##parent1##_Type, \ &Py##parent2##ArrType_Type); \ Py##child##ArrType_Type.tp_richcompare = \ Py##parent1##_Type.tp_richcompare; \ DUAL_INHERIT_COMPARE(child, parent1, parent2) \ Py##child##ArrType_Type.tp_hash = Py##parent1##_Type.tp_hash; \ if (PyType_Ready(&Py##child##ArrType_Type) < 0) { \ PyErr_Print(); \ PyErr_Format(PyExc_SystemError, \ "could not initialize Py%sArrType_Type", \ #child); \ return -1; \ } SINGLE_INHERIT(Bool, Generic); SINGLE_INHERIT(Byte, SignedInteger); SINGLE_INHERIT(Short, SignedInteger); #if NPY_SIZEOF_INT == NPY_SIZEOF_LONG INHERIT_INT(Int, SignedInteger); #else SINGLE_INHERIT(Int, SignedInteger); #endif INHERIT_INT(Long, SignedInteger); #if NPY_SIZEOF_LONGLONG == NPY_SIZEOF_LONG INHERIT_INT(LongLong, SignedInteger); #else SINGLE_INHERIT(LongLong, SignedInteger); #endif /* Datetime doesn't fit in any category */ SINGLE_INHERIT(Datetime, Generic); /* Timedelta is an integer with an associated unit */ SINGLE_INHERIT(Timedelta, SignedInteger); /* fprintf(stderr, "tp_free = %p, PyObject_Del = %p, int_tp_free = %p, base.tp_free = %p\n", PyIntArrType_Type.tp_free, PyObject_Del, PyInt_Type.tp_free, PySignedIntegerArrType_Type.tp_free); */ SINGLE_INHERIT(UByte, UnsignedInteger); SINGLE_INHERIT(UShort, UnsignedInteger); SINGLE_INHERIT(UInt, UnsignedInteger); SINGLE_INHERIT(ULong, UnsignedInteger); SINGLE_INHERIT(ULongLong, UnsignedInteger); SINGLE_INHERIT(Half, Floating); SINGLE_INHERIT(Float, Floating); DUAL_INHERIT(Double, Float, Floating); SINGLE_INHERIT(LongDouble, Floating); SINGLE_INHERIT(CFloat, ComplexFloating); DUAL_INHERIT(CDouble, Complex, ComplexFloating); SINGLE_INHERIT(CLongDouble, ComplexFloating); DUAL_INHERIT2(String, String, Character); DUAL_INHERIT2(Unicode, Unicode, Character); SINGLE_INHERIT(Void, Flexible); SINGLE_INHERIT(Object, Generic); return 0; #undef SINGLE_INHERIT #undef DUAL_INHERIT #undef INHERIT_INT #undef DUAL_INHERIT2 #undef DUAL_INHERIT_COMPARE /* * Clean up string and unicode array types so they act more like * strings -- get their tables from the standard types. */ } /* place a flag dictionary in d */ static void set_flaginfo(PyObject *d) { PyObject *s; PyObject *newd; newd = PyDict_New(); #define _addnew(key, val, one) \ PyDict_SetItemString(newd, #key, s=PyInt_FromLong(val)); \ Py_DECREF(s); \ PyDict_SetItemString(newd, #one, s=PyInt_FromLong(val)); \ Py_DECREF(s) #define _addone(key, val) \ PyDict_SetItemString(newd, #key, s=PyInt_FromLong(val)); \ Py_DECREF(s) _addnew(OWNDATA, NPY_ARRAY_OWNDATA, O); _addnew(FORTRAN, NPY_ARRAY_F_CONTIGUOUS, F); _addnew(CONTIGUOUS, NPY_ARRAY_C_CONTIGUOUS, C); _addnew(ALIGNED, NPY_ARRAY_ALIGNED, A); _addnew(UPDATEIFCOPY, NPY_ARRAY_UPDATEIFCOPY, U); _addnew(WRITEABLE, NPY_ARRAY_WRITEABLE, W); _addone(C_CONTIGUOUS, NPY_ARRAY_C_CONTIGUOUS); _addone(F_CONTIGUOUS, NPY_ARRAY_F_CONTIGUOUS); #undef _addone #undef _addnew PyDict_SetItemString(d, "_flagdict", newd); Py_DECREF(newd); return; } #if defined(NPY_PY3K) static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, "multiarray", NULL, -1, array_module_methods, NULL, NULL, NULL, NULL }; #endif /* Initialization function for the module */ #if defined(NPY_PY3K) #define RETVAL m PyMODINIT_FUNC PyInit_multiarray(void) { #else #define RETVAL PyMODINIT_FUNC initmultiarray(void) { #endif PyObject *m, *d, *s; PyObject *c_api; /* Create the module and add the functions */ #if defined(NPY_PY3K) m = PyModule_Create(&moduledef); #else m = Py_InitModule("multiarray", array_module_methods); #endif if (!m) { goto err; } #if defined(MS_WIN64) && defined(__GNUC__) PyErr_WarnEx(PyExc_Warning, "Numpy built with MINGW-W64 on Windows 64 bits is experimental, " \ "and only available for \n" \ "testing. You are advised not to use it for production. \n\n" \ "CRASHES ARE TO BE EXPECTED - PLEASE REPORT THEM TO NUMPY DEVELOPERS", 1); #endif /* Initialize access to the PyDateTime API */ numpy_pydatetime_import(); /* Add some symbolic constants to the module */ d = PyModule_GetDict(m); if (!d) { goto err; } PyArray_Type.tp_free = PyArray_free; if (PyType_Ready(&PyArray_Type) < 0) { return RETVAL; } if (setup_scalartypes(d) < 0) { goto err; } PyArrayIter_Type.tp_iter = PyObject_SelfIter; NpyIter_Type.tp_iter = PyObject_SelfIter; PyArrayMultiIter_Type.tp_iter = PyObject_SelfIter; PyArrayMultiIter_Type.tp_free = PyArray_free; if (PyType_Ready(&PyArrayIter_Type) < 0) { return RETVAL; } if (PyType_Ready(&PyArrayMapIter_Type) < 0) { return RETVAL; } if (PyType_Ready(&PyArrayMultiIter_Type) < 0) { return RETVAL; } PyArrayNeighborhoodIter_Type.tp_new = PyType_GenericNew; if (PyType_Ready(&PyArrayNeighborhoodIter_Type) < 0) { return RETVAL; } if (PyType_Ready(&NpyIter_Type) < 0) { return RETVAL; } PyArrayDescr_Type.tp_hash = PyArray_DescrHash; if (PyType_Ready(&PyArrayDescr_Type) < 0) { return RETVAL; } if (PyType_Ready(&PyArrayFlags_Type) < 0) { return RETVAL; } NpyBusDayCalendar_Type.tp_new = PyType_GenericNew; if (PyType_Ready(&NpyBusDayCalendar_Type) < 0) { return RETVAL; } /* FIXME * There is no error handling here */ c_api = NpyCapsule_FromVoidPtr((void *)PyArray_API, NULL); PyDict_SetItemString(d, "_ARRAY_API", c_api); Py_DECREF(c_api); if (PyErr_Occurred()) { goto err; } /* Initialize types in numpymemoryview.c */ if (_numpymemoryview_init(&s) < 0) { return RETVAL; } if (s != NULL) { PyDict_SetItemString(d, "memorysimpleview", s); } /* * PyExc_Exception should catch all the standard errors that are * now raised instead of the string exception "multiarray.error" * This is for backward compatibility with existing code. */ PyDict_SetItemString (d, "error", PyExc_Exception); s = PyUString_FromString("3.1"); PyDict_SetItemString(d, "__version__", s); Py_DECREF(s); /* FIXME * There is no error handling here */ s = NpyCapsule_FromVoidPtr((void *)_datetime_strings, NULL); PyDict_SetItemString(d, "DATETIMEUNITS", s); Py_DECREF(s); #define ADDCONST(NAME) \ s = PyInt_FromLong(NPY_##NAME); \ PyDict_SetItemString(d, #NAME, s); \ Py_DECREF(s) ADDCONST(ALLOW_THREADS); ADDCONST(BUFSIZE); ADDCONST(CLIP); ADDCONST(ITEM_HASOBJECT); ADDCONST(LIST_PICKLE); ADDCONST(ITEM_IS_POINTER); ADDCONST(NEEDS_INIT); ADDCONST(NEEDS_PYAPI); ADDCONST(USE_GETITEM); ADDCONST(USE_SETITEM); ADDCONST(RAISE); ADDCONST(WRAP); ADDCONST(MAXDIMS); #undef ADDCONST Py_INCREF(&PyArray_Type); PyDict_SetItemString(d, "ndarray", (PyObject *)&PyArray_Type); Py_INCREF(&PyArrayIter_Type); PyDict_SetItemString(d, "flatiter", (PyObject *)&PyArrayIter_Type); Py_INCREF(&PyArrayMultiIter_Type); PyDict_SetItemString(d, "nditer", (PyObject *)&NpyIter_Type); Py_INCREF(&NpyIter_Type); PyDict_SetItemString(d, "broadcast", (PyObject *)&PyArrayMultiIter_Type); Py_INCREF(&PyArrayDescr_Type); PyDict_SetItemString(d, "dtype", (PyObject *)&PyArrayDescr_Type); Py_INCREF(&PyArrayFlags_Type); PyDict_SetItemString(d, "flagsobj", (PyObject *)&PyArrayFlags_Type); /* Business day calendar object */ Py_INCREF(&NpyBusDayCalendar_Type); PyDict_SetItemString(d, "busdaycalendar", (PyObject *)&NpyBusDayCalendar_Type); set_flaginfo(d); if (set_typeinfo(d) != 0) { goto err; } return RETVAL; err: if (!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError, "cannot load multiarray module."); } return RETVAL; } numpy-1.8.2/numpy/core/src/multiarray/convert.c0000664000175100017510000003703412370216243022737 0ustar vagrantvagrant00000000000000#define PY_SSIZE_T_CLEAN #include #include "structmember.h" #define NPY_NO_DEPRECATED_API NPY_API_VERSION #define _MULTIARRAYMODULE #include "numpy/arrayobject.h" #include "numpy/arrayscalars.h" #include "npy_config.h" #include "npy_pycompat.h" #include "arrayobject.h" #include "mapping.h" #include "lowlevel_strided_loops.h" #include "scalartypes.h" #include "array_assign.h" #include "convert.h" /* * Converts a subarray of 'self' into lists, with starting data pointer * 'dataptr' and from dimension 'startdim' to the last dimension of 'self'. * * Returns a new reference. */ static PyObject * recursive_tolist(PyArrayObject *self, char *dataptr, int startdim) { npy_intp i, n, stride; PyObject *ret, *item; /* Base case */ if (startdim >= PyArray_NDIM(self)) { return PyArray_DESCR(self)->f->getitem(dataptr,self); } n = PyArray_DIM(self, startdim); stride = PyArray_STRIDE(self, startdim); ret = PyList_New(n); if (ret == NULL) { return NULL; } for (i = 0; i < n; ++i) { item = recursive_tolist(self, dataptr, startdim+1); if (item == NULL) { Py_DECREF(ret); return NULL; } PyList_SET_ITEM(ret, i, item); dataptr += stride; } return ret; } /*NUMPY_API * To List */ NPY_NO_EXPORT PyObject * PyArray_ToList(PyArrayObject *self) { return recursive_tolist(self, PyArray_DATA(self), 0); } /* XXX: FIXME --- add ordering argument to Allow Fortran ordering on write This will need the addition of a Fortran-order iterator. */ /*NUMPY_API To File */ NPY_NO_EXPORT int PyArray_ToFile(PyArrayObject *self, FILE *fp, char *sep, char *format) { npy_intp size; npy_intp n, n2; size_t n3, n4; PyArrayIterObject *it; PyObject *obj, *strobj, *tupobj, *byteobj; n3 = (sep ? strlen((const char *)sep) : 0); 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"); return -1; } if (PyArray_ISCONTIGUOUS(self)) { size = PyArray_SIZE(self); NPY_BEGIN_ALLOW_THREADS; #if defined (_MSC_VER) && defined(_WIN64) /* Workaround Win64 fwrite() bug. Ticket #1660 */ { npy_intp maxsize = 2147483648 / PyArray_DESCR(self)->elsize; npy_intp chunksize; n = 0; while (size > 0) { chunksize = (size > maxsize) ? maxsize : size; n2 = fwrite((const void *) ((char *)PyArray_DATA(self) + (n * PyArray_DESCR(self)->elsize)), (size_t) PyArray_DESCR(self)->elsize, (size_t) chunksize, fp); if (n2 < chunksize) { break; } n += n2; size -= chunksize; } size = PyArray_SIZE(self); } #else n = fwrite((const void *)PyArray_DATA(self), (size_t) PyArray_DESCR(self)->elsize, (size_t) size, fp); #endif NPY_END_ALLOW_THREADS; if (n < size) { PyErr_Format(PyExc_ValueError, "%ld requested and %ld written", (long) size, (long) n); return -1; } } else { NPY_BEGIN_THREADS_DEF; it = (PyArrayIterObject *) PyArray_IterNew((PyObject *)self); NPY_BEGIN_THREADS; while (it->index < it->size) { if (fwrite((const void *)it->dataptr, (size_t) PyArray_DESCR(self)->elsize, 1, fp) < 1) { NPY_END_THREADS; PyErr_Format(PyExc_IOError, "problem writing element"\ " %"NPY_INTP_FMT" to file", it->index); Py_DECREF(it); return -1; } PyArray_ITER_NEXT(it); } NPY_END_THREADS; Py_DECREF(it); } } else { /* * text data */ it = (PyArrayIterObject *) PyArray_IterNew((PyObject *)self); n4 = (format ? strlen((const char *)format) : 0); while (it->index < it->size) { obj = PyArray_DESCR(self)->f->getitem(it->dataptr, self); if (obj == NULL) { Py_DECREF(it); return -1; } if (n4 == 0) { /* * standard writing */ strobj = PyObject_Str(obj); Py_DECREF(obj); if (strobj == NULL) { Py_DECREF(it); return -1; } } else { /* * use format string */ tupobj = PyTuple_New(1); if (tupobj == NULL) { Py_DECREF(it); return -1; } PyTuple_SET_ITEM(tupobj,0,obj); obj = PyUString_FromString((const char *)format); if (obj == NULL) { Py_DECREF(tupobj); Py_DECREF(it); return -1; } strobj = PyUString_Format(obj, tupobj); Py_DECREF(obj); Py_DECREF(tupobj); if (strobj == NULL) { Py_DECREF(it); return -1; } } #if defined(NPY_PY3K) byteobj = PyUnicode_AsASCIIString(strobj); #else byteobj = strobj; #endif NPY_BEGIN_ALLOW_THREADS; n2 = PyBytes_GET_SIZE(byteobj); n = fwrite(PyBytes_AS_STRING(byteobj), 1, n2, fp); NPY_END_ALLOW_THREADS; #if defined(NPY_PY3K) Py_DECREF(byteobj); #endif if (n < n2) { PyErr_Format(PyExc_IOError, "problem writing element %"NPY_INTP_FMT\ " to file", it->index); Py_DECREF(strobj); Py_DECREF(it); return -1; } /* write separator for all but last one */ if (it->index != it->size-1) { if (fwrite(sep, 1, n3, fp) < n3) { PyErr_Format(PyExc_IOError, "problem writing "\ "separator to file"); Py_DECREF(strobj); Py_DECREF(it); return -1; } } Py_DECREF(strobj); PyArray_ITER_NEXT(it); } Py_DECREF(it); } return 0; } /*NUMPY_API*/ NPY_NO_EXPORT PyObject * PyArray_ToString(PyArrayObject *self, NPY_ORDER order) { npy_intp numbytes; npy_intp i; char *dptr; int elsize; PyObject *ret; PyArrayIterObject *it; if (order == NPY_ANYORDER) order = PyArray_ISFORTRAN(self); /* if (PyArray_TYPE(self) == NPY_OBJECT) { PyErr_SetString(PyExc_ValueError, "a string for the data" \ "in an object array is not appropriate"); return NULL; } */ numbytes = PyArray_NBYTES(self); if ((PyArray_IS_C_CONTIGUOUS(self) && (order == NPY_CORDER)) || (PyArray_IS_F_CONTIGUOUS(self) && (order == NPY_FORTRANORDER))) { ret = PyBytes_FromStringAndSize(PyArray_DATA(self), (Py_ssize_t) numbytes); } else { PyObject *new; if (order == NPY_FORTRANORDER) { /* iterators are always in C-order */ new = PyArray_Transpose(self, NULL); if (new == NULL) { return NULL; } } else { Py_INCREF(self); new = (PyObject *)self; } it = (PyArrayIterObject *)PyArray_IterNew(new); Py_DECREF(new); if (it == NULL) { return NULL; } ret = PyBytes_FromStringAndSize(NULL, (Py_ssize_t) numbytes); if (ret == NULL) { Py_DECREF(it); return NULL; } dptr = PyBytes_AS_STRING(ret); i = it->size; elsize = PyArray_DESCR(self)->elsize; while (i--) { memcpy(dptr, it->dataptr, elsize); dptr += elsize; PyArray_ITER_NEXT(it); } Py_DECREF(it); } return ret; } /*NUMPY_API*/ NPY_NO_EXPORT int PyArray_FillWithScalar(PyArrayObject *arr, PyObject *obj) { PyArray_Descr *dtype = NULL; npy_longlong value_buffer[4]; char *value = NULL; int retcode = 0; /* * If 'arr' is an object array, copy the object as is unless * 'obj' is a zero-dimensional array, in which case we copy * the element in that array instead. */ if (PyArray_DESCR(arr)->type_num == NPY_OBJECT && !(PyArray_Check(obj) && PyArray_NDIM((PyArrayObject *)obj) == 0)) { value = (char *)&obj; dtype = PyArray_DescrFromType(NPY_OBJECT); if (dtype == NULL) { return -1; } } /* NumPy scalar */ else if (PyArray_IsScalar(obj, Generic)) { dtype = PyArray_DescrFromScalar(obj); if (dtype == NULL) { return -1; } value = scalar_value(obj, dtype); if (value == NULL) { Py_DECREF(dtype); return -1; } } /* Python boolean */ else if (PyBool_Check(obj)) { value = (char *)value_buffer; *value = (obj == Py_True); dtype = PyArray_DescrFromType(NPY_BOOL); if (dtype == NULL) { return -1; } } /* Python integer */ else if (PyLong_Check(obj) || PyInt_Check(obj)) { npy_longlong v = PyLong_AsLongLong(obj); if (v == -1 && PyErr_Occurred()) { return -1; } value = (char *)value_buffer; *(npy_longlong *)value = v; dtype = PyArray_DescrFromType(NPY_LONGLONG); if (dtype == NULL) { return -1; } } /* Python float */ else if (PyFloat_Check(obj)) { npy_double v = PyFloat_AsDouble(obj); if (v == -1 && PyErr_Occurred()) { return -1; } value = (char *)value_buffer; *(npy_double *)value = v; dtype = PyArray_DescrFromType(NPY_DOUBLE); if (dtype == NULL) { return -1; } } /* Python complex */ else if (PyComplex_Check(obj)) { npy_double re, im; re = PyComplex_RealAsDouble(obj); if (re == -1 && PyErr_Occurred()) { return -1; } im = PyComplex_ImagAsDouble(obj); if (im == -1 && PyErr_Occurred()) { return -1; } value = (char *)value_buffer; ((npy_double *)value)[0] = re; ((npy_double *)value)[1] = im; dtype = PyArray_DescrFromType(NPY_CDOUBLE); if (dtype == NULL) { return -1; } } /* Use the value pointer we got if possible */ if (value != NULL) { /* TODO: switch to SAME_KIND casting */ retcode = PyArray_AssignRawScalar(arr, dtype, value, NULL, NPY_UNSAFE_CASTING); Py_DECREF(dtype); return retcode; } /* Otherwise convert to an array to do the assignment */ else { PyArrayObject *src_arr; /** * The dtype of the destination is used when converting * from the pyobject, so that for example a tuple gets * recognized as a struct scalar of the required type. */ Py_INCREF(PyArray_DTYPE(arr)); src_arr = (PyArrayObject *)PyArray_FromAny(obj, PyArray_DTYPE(arr), 0, 0, 0, NULL); if (src_arr == NULL) { return -1; } if (PyArray_NDIM(src_arr) != 0) { PyErr_SetString(PyExc_ValueError, "Input object to FillWithScalar is not a scalar"); Py_DECREF(src_arr); return -1; } retcode = PyArray_CopyInto(arr, src_arr); Py_DECREF(src_arr); return retcode; } } /* * Fills an array with zeros. * * dst: The destination array. * wheremask: If non-NULL, a boolean mask specifying where to set the values. * * Returns 0 on success, -1 on failure. */ NPY_NO_EXPORT int PyArray_AssignZero(PyArrayObject *dst, PyArrayObject *wheremask) { npy_bool value; PyArray_Descr *bool_dtype; int retcode; /* Create a raw bool scalar with the value False */ bool_dtype = PyArray_DescrFromType(NPY_BOOL); if (bool_dtype == NULL) { return -1; } value = 0; retcode = PyArray_AssignRawScalar(dst, bool_dtype, (char *)&value, wheremask, NPY_SAFE_CASTING); Py_DECREF(bool_dtype); return retcode; } /* * Fills an array with ones. * * dst: The destination array. * wheremask: If non-NULL, a boolean mask specifying where to set the values. * * Returns 0 on success, -1 on failure. */ NPY_NO_EXPORT int PyArray_AssignOne(PyArrayObject *dst, PyArrayObject *wheremask) { npy_bool value; PyArray_Descr *bool_dtype; int retcode; /* Create a raw bool scalar with the value True */ bool_dtype = PyArray_DescrFromType(NPY_BOOL); if (bool_dtype == NULL) { return -1; } value = 1; retcode = PyArray_AssignRawScalar(dst, bool_dtype, (char *)&value, wheremask, NPY_SAFE_CASTING); Py_DECREF(bool_dtype); return retcode; } /*NUMPY_API * Copy an array. */ NPY_NO_EXPORT PyObject * PyArray_NewCopy(PyArrayObject *obj, NPY_ORDER order) { PyArrayObject *ret; ret = (PyArrayObject *)PyArray_NewLikeArray(obj, order, NULL, 1); if (ret == NULL) { return NULL; } if (PyArray_AssignArray(ret, obj, NULL, NPY_UNSAFE_CASTING) < 0) { Py_DECREF(ret); return NULL; } return (PyObject *)ret; } /*NUMPY_API * View * steals a reference to type -- accepts NULL */ NPY_NO_EXPORT PyObject * PyArray_View(PyArrayObject *self, PyArray_Descr *type, PyTypeObject *pytype) { PyArrayObject *ret = NULL; PyArray_Descr *dtype; PyTypeObject *subtype; int flags; if (pytype) { subtype = pytype; } else { subtype = Py_TYPE(self); } flags = PyArray_FLAGS(self); dtype = PyArray_DESCR(self); Py_INCREF(dtype); ret = (PyArrayObject *)PyArray_NewFromDescr(subtype, dtype, PyArray_NDIM(self), PyArray_DIMS(self), PyArray_STRIDES(self), PyArray_DATA(self), flags, (PyObject *)self); if (ret == NULL) { return NULL; } /* Set the base object */ Py_INCREF(self); if (PyArray_SetBaseObject(ret, (PyObject *)self) < 0) { Py_DECREF(ret); Py_DECREF(type); return NULL; } if (type != NULL) { if (PyObject_SetAttrString((PyObject *)ret, "dtype", (PyObject *)type) < 0) { Py_DECREF(ret); Py_DECREF(type); return NULL; } Py_DECREF(type); } return (PyObject *)ret; } numpy-1.8.2/numpy/core/src/multiarray/nditer_pywrap.h0000664000175100017510000000027312370216242024145 0ustar vagrantvagrant00000000000000#ifndef __NDITER_PYWRAP_H #define __NDITER_PYWRAP_H NPY_NO_EXPORT PyObject * NpyIter_NestedIters(PyObject *NPY_UNUSED(self), PyObject *args, PyObject *kwds); #endif numpy-1.8.2/numpy/core/src/multiarray/numpyos.h0000664000175100017510000000134512370216242022771 0ustar vagrantvagrant00000000000000#ifndef _NPY_NUMPYOS_H_ #define _NPY_NUMPYOS_H_ NPY_NO_EXPORT char* NumPyOS_ascii_formatd(char *buffer, size_t buf_size, const char *format, double val, int decimal); NPY_NO_EXPORT char* NumPyOS_ascii_formatf(char *buffer, size_t buf_size, const char *format, float val, int decimal); NPY_NO_EXPORT char* NumPyOS_ascii_formatl(char *buffer, size_t buf_size, const char *format, long double val, int decimal); NPY_NO_EXPORT double NumPyOS_ascii_strtod(const char *s, char** endptr); NPY_NO_EXPORT int NumPyOS_ascii_ftolf(FILE *fp, double *value); NPY_NO_EXPORT int NumPyOS_ascii_isspace(char c); #endif numpy-1.8.2/numpy/core/src/multiarray/datetime_busdaycal.h0000664000175100017510000000361512370216242025104 0ustar vagrantvagrant00000000000000#ifndef _NPY_PRIVATE__DATETIME_BUSDAYDEF_H_ #define _NPY_PRIVATE__DATETIME_BUSDAYDEF_H_ /* * A list of holidays, which should be sorted, not contain any * duplicates or NaTs, and not include any days already excluded * by the associated weekmask. * * The data is manually managed with PyArray_malloc/PyArray_free. */ typedef struct { npy_datetime *begin, *end; } npy_holidayslist; /* * This object encapsulates a weekmask and normalized holidays list, * so that the business day API can use this data without having * to normalize it repeatedly. All the data of this object is private * and cannot be modified from Python. Copies are made when giving * the weekmask and holidays data to Python code. */ typedef struct { PyObject_HEAD npy_holidayslist holidays; int busdays_in_weekmask; npy_bool weekmask[7]; } NpyBusDayCalendar; #ifdef NPY_ENABLE_SEPARATE_COMPILATION extern NPY_NO_EXPORT PyTypeObject NpyBusDayCalendar_Type; #else NPY_NO_EXPORT PyTypeObject NpyBusDayCalendar_Type; #endif /* * Converts a Python input into a 7-element weekmask, where 0 means * weekend and 1 means business day. */ NPY_NO_EXPORT int PyArray_WeekMaskConverter(PyObject *weekmask_in, npy_bool *weekmask); /* * Sorts the the array of dates provided in place and removes * NaT, duplicates and any date which is already excluded on account * of the weekmask. * * Returns the number of dates left after removing weekmask-excluded * dates. */ NPY_NO_EXPORT void normalize_holidays_list(npy_holidayslist *holidays, npy_bool *weekmask); /* * Converts a Python input into a non-normalized list of holidays. * * IMPORTANT: This function can't do the normalization, because it doesn't * know the weekmask. You must call 'normalize_holiday_list' * on the result before using it. */ NPY_NO_EXPORT int PyArray_HolidaysConverter(PyObject *dates_in, npy_holidayslist *holidays); #endif numpy-1.8.2/numpy/core/src/multiarray/conversion_utils.c0000664000175100017510000007707312370216243024673 0ustar vagrantvagrant00000000000000#define PY_SSIZE_T_CLEAN #include #include "structmember.h" #define NPY_NO_DEPRECATED_API NPY_API_VERSION #define _MULTIARRAYMODULE #include "numpy/arrayobject.h" #include "numpy/arrayscalars.h" #include "numpy/arrayobject.h" #include "npy_config.h" #include "npy_pycompat.h" #include "common.h" #include "arraytypes.h" #include "conversion_utils.h" /**************************************************************** * Useful function for conversion when used with PyArg_ParseTuple ****************************************************************/ /*NUMPY_API * * Useful to pass as converter function for O& processing in PyArgs_ParseTuple. * * This conversion function can be used with the "O&" argument for * PyArg_ParseTuple. It will immediately return an object of array type * or will convert to a NPY_ARRAY_CARRAY any other object. * * If you use PyArray_Converter, you must DECREF the array when finished * as you get a new reference to it. */ NPY_NO_EXPORT int PyArray_Converter(PyObject *object, PyObject **address) { if (PyArray_Check(object)) { *address = object; Py_INCREF(object); return NPY_SUCCEED; } else { *address = PyArray_FromAny(object, NULL, 0, 0, NPY_ARRAY_CARRAY, NULL); if (*address == NULL) { return NPY_FAIL; } return NPY_SUCCEED; } } /*NUMPY_API * Useful to pass as converter function for O& processing in * PyArgs_ParseTuple for output arrays */ NPY_NO_EXPORT int PyArray_OutputConverter(PyObject *object, PyArrayObject **address) { if (object == NULL || object == Py_None) { *address = NULL; return NPY_SUCCEED; } if (PyArray_Check(object)) { *address = (PyArrayObject *)object; return NPY_SUCCEED; } else { PyErr_SetString(PyExc_TypeError, "output must be an array"); *address = NULL; return NPY_FAIL; } } /*NUMPY_API * Get intp chunk from sequence * * This function takes a Python sequence object and allocates and * fills in an intp array with the converted values. * * Remember to free the pointer seq.ptr when done using * PyDimMem_FREE(seq.ptr)** */ NPY_NO_EXPORT int PyArray_IntpConverter(PyObject *obj, PyArray_Dims *seq) { Py_ssize_t len; int nd; seq->ptr = NULL; seq->len = 0; if (obj == Py_None) { return NPY_SUCCEED; } len = PySequence_Size(obj); if (len == -1) { /* Check to see if it is an integer number */ if (PyNumber_Check(obj)) { /* * After the deprecation the PyNumber_Check could be replaced * by PyIndex_Check. * FIXME 1.9 ? */ len = 1; } } if (len < 0) { PyErr_SetString(PyExc_TypeError, "expected sequence object with len >= 0 or a single integer"); return NPY_FAIL; } if (len > NPY_MAXDIMS) { PyErr_Format(PyExc_ValueError, "sequence too large; " "must be smaller than %d", NPY_MAXDIMS); return NPY_FAIL; } if (len > 0) { seq->ptr = PyDimMem_NEW(len); if (seq->ptr == NULL) { PyErr_NoMemory(); return NPY_FAIL; } } seq->len = len; nd = PyArray_IntpFromIndexSequence(obj, (npy_intp *)seq->ptr, len); if (nd == -1 || nd != len) { PyDimMem_FREE(seq->ptr); seq->ptr = NULL; return NPY_FAIL; } return NPY_SUCCEED; } /*NUMPY_API * Get buffer chunk from object * * this function takes a Python object which exposes the (single-segment) * buffer interface and returns a pointer to the data segment * * You should increment the reference count by one of buf->base * if you will hang on to a reference * * You only get a borrowed reference to the object. Do not free the * memory... */ NPY_NO_EXPORT int PyArray_BufferConverter(PyObject *obj, PyArray_Chunk *buf) { #if defined(NPY_PY3K) Py_buffer view; #else Py_ssize_t buflen; #endif buf->ptr = NULL; buf->flags = NPY_ARRAY_BEHAVED; buf->base = NULL; if (obj == Py_None) { return NPY_SUCCEED; } #if defined(NPY_PY3K) if (PyObject_GetBuffer(obj, &view, PyBUF_ANY_CONTIGUOUS|PyBUF_WRITABLE) != 0) { PyErr_Clear(); buf->flags &= ~NPY_ARRAY_WRITEABLE; if (PyObject_GetBuffer(obj, &view, PyBUF_ANY_CONTIGUOUS) != 0) { return NPY_FAIL; } } buf->ptr = view.buf; buf->len = (npy_intp) view.len; /* * XXX: PyObject_AsWriteBuffer does also this, but it is unsafe, as there is * no strict guarantee that the buffer sticks around after being released. */ PyBuffer_Release(&view); /* Point to the base of the buffer object if present */ if (PyMemoryView_Check(obj)) { buf->base = PyMemoryView_GET_BASE(obj); } #else if (PyObject_AsWriteBuffer(obj, &(buf->ptr), &buflen) < 0) { PyErr_Clear(); buf->flags &= ~NPY_ARRAY_WRITEABLE; if (PyObject_AsReadBuffer(obj, (const void **)&(buf->ptr), &buflen) < 0) { return NPY_FAIL; } } buf->len = (npy_intp) buflen; /* Point to the base of the buffer object if present */ if (PyBuffer_Check(obj)) { buf->base = ((PyArray_Chunk *)obj)->base; } #endif if (buf->base == NULL) { buf->base = obj; } return NPY_SUCCEED; } /*NUMPY_API * Get axis from an object (possibly None) -- a converter function, * * See also PyArray_ConvertMultiAxis, which also handles a tuple of axes. */ NPY_NO_EXPORT int PyArray_AxisConverter(PyObject *obj, int *axis) { if (obj == Py_None) { *axis = NPY_MAXDIMS; } else { *axis = PyArray_PyIntAsInt(obj); if (PyErr_Occurred()) { return NPY_FAIL; } } return NPY_SUCCEED; } /* * Converts an axis parameter into an ndim-length C-array of * boolean flags, True for each axis specified. * * If obj is None or NULL, everything is set to True. If obj is a tuple, * each axis within the tuple is set to True. If obj is an integer, * just that axis is set to True. */ NPY_NO_EXPORT int PyArray_ConvertMultiAxis(PyObject *axis_in, int ndim, npy_bool *out_axis_flags) { /* None means all of the axes */ if (axis_in == Py_None || axis_in == NULL) { memset(out_axis_flags, 1, ndim); return NPY_SUCCEED; } /* A tuple of which axes */ else if (PyTuple_Check(axis_in)) { int i, naxes; memset(out_axis_flags, 0, ndim); naxes = PyTuple_Size(axis_in); if (naxes < 0) { return NPY_FAIL; } for (i = 0; i < naxes; ++i) { PyObject *tmp = PyTuple_GET_ITEM(axis_in, i); int axis = PyArray_PyIntAsInt(tmp); int axis_orig = axis; if (error_converting(axis)) { return NPY_FAIL; } if (axis < 0) { axis += ndim; } if (axis < 0 || axis >= ndim) { PyErr_Format(PyExc_ValueError, "'axis' entry %d is out of bounds [-%d, %d)", axis_orig, ndim, ndim); return NPY_FAIL; } if (out_axis_flags[axis]) { PyErr_SetString(PyExc_ValueError, "duplicate value in 'axis'"); return NPY_FAIL; } out_axis_flags[axis] = 1; } return NPY_SUCCEED; } /* Try to interpret axis as an integer */ else { int axis, axis_orig; memset(out_axis_flags, 0, ndim); axis = PyArray_PyIntAsInt(axis_in); axis_orig = axis; if (error_converting(axis)) { return NPY_FAIL; } if (axis < 0) { axis += ndim; } /* * Special case letting axis={-1,0} slip through for scalars, * for backwards compatibility reasons. */ if (ndim == 0 && (axis == 0 || axis == -1)) { return NPY_SUCCEED; } if (axis < 0 || axis >= ndim) { PyErr_Format(PyExc_ValueError, "'axis' entry %d is out of bounds [-%d, %d)", axis_orig, ndim, ndim); return NPY_FAIL; } out_axis_flags[axis] = 1; return NPY_SUCCEED; } } /*NUMPY_API * Convert an object to true / false */ NPY_NO_EXPORT int PyArray_BoolConverter(PyObject *object, npy_bool *val) { if (PyObject_IsTrue(object)) { *val = NPY_TRUE; } else { *val = NPY_FALSE; } if (PyErr_Occurred()) { return NPY_FAIL; } return NPY_SUCCEED; } /*NUMPY_API * Convert object to endian */ NPY_NO_EXPORT int PyArray_ByteorderConverter(PyObject *obj, char *endian) { char *str; PyObject *tmp = NULL; if (PyUnicode_Check(obj)) { obj = tmp = PyUnicode_AsASCIIString(obj); } *endian = NPY_SWAP; str = PyBytes_AsString(obj); if (!str) { Py_XDECREF(tmp); return NPY_FAIL; } if (strlen(str) < 1) { PyErr_SetString(PyExc_ValueError, "Byteorder string must be at least length 1"); Py_XDECREF(tmp); return NPY_FAIL; } *endian = str[0]; if (str[0] != NPY_BIG && str[0] != NPY_LITTLE && str[0] != NPY_NATIVE && str[0] != NPY_IGNORE) { if (str[0] == 'b' || str[0] == 'B') { *endian = NPY_BIG; } else if (str[0] == 'l' || str[0] == 'L') { *endian = NPY_LITTLE; } else if (str[0] == 'n' || str[0] == 'N') { *endian = NPY_NATIVE; } else if (str[0] == 'i' || str[0] == 'I') { *endian = NPY_IGNORE; } else if (str[0] == 's' || str[0] == 'S') { *endian = NPY_SWAP; } else { PyErr_Format(PyExc_ValueError, "%s is an unrecognized byteorder", str); Py_XDECREF(tmp); return NPY_FAIL; } } Py_XDECREF(tmp); return NPY_SUCCEED; } /*NUMPY_API * Convert object to sort kind */ NPY_NO_EXPORT int PyArray_SortkindConverter(PyObject *obj, NPY_SORTKIND *sortkind) { char *str; PyObject *tmp = NULL; if (PyUnicode_Check(obj)) { obj = tmp = PyUnicode_AsASCIIString(obj); } *sortkind = NPY_QUICKSORT; str = PyBytes_AsString(obj); if (!str) { Py_XDECREF(tmp); return NPY_FAIL; } if (strlen(str) < 1) { PyErr_SetString(PyExc_ValueError, "Sort kind string must be at least length 1"); Py_XDECREF(tmp); return NPY_FAIL; } if (str[0] == 'q' || str[0] == 'Q') { *sortkind = NPY_QUICKSORT; } else if (str[0] == 'h' || str[0] == 'H') { *sortkind = NPY_HEAPSORT; } else if (str[0] == 'm' || str[0] == 'M') { *sortkind = NPY_MERGESORT; } else { PyErr_Format(PyExc_ValueError, "%s is an unrecognized kind of sort", str); Py_XDECREF(tmp); return NPY_FAIL; } Py_XDECREF(tmp); return NPY_SUCCEED; } /*NUMPY_API * Convert object to select kind */ NPY_NO_EXPORT int PyArray_SelectkindConverter(PyObject *obj, NPY_SELECTKIND *selectkind) { char *str; PyObject *tmp = NULL; if (PyUnicode_Check(obj)) { obj = tmp = PyUnicode_AsASCIIString(obj); } *selectkind = NPY_INTROSELECT; str = PyBytes_AsString(obj); if (!str) { Py_XDECREF(tmp); return NPY_FAIL; } if (strlen(str) < 1) { PyErr_SetString(PyExc_ValueError, "Select kind string must be at least length 1"); Py_XDECREF(tmp); return NPY_FAIL; } if (strcmp(str, "introselect") == 0) { *selectkind = NPY_INTROSELECT; } else { PyErr_Format(PyExc_ValueError, "%s is an unrecognized kind of select", str); Py_XDECREF(tmp); return NPY_FAIL; } Py_XDECREF(tmp); return NPY_SUCCEED; } /*NUMPY_API * Convert object to searchsorted side */ NPY_NO_EXPORT int PyArray_SearchsideConverter(PyObject *obj, void *addr) { NPY_SEARCHSIDE *side = (NPY_SEARCHSIDE *)addr; char *str; PyObject *tmp = NULL; if (PyUnicode_Check(obj)) { obj = tmp = PyUnicode_AsASCIIString(obj); } str = PyBytes_AsString(obj); if (!str || strlen(str) < 1) { PyErr_SetString(PyExc_ValueError, "expected nonempty string for keyword 'side'"); Py_XDECREF(tmp); return NPY_FAIL; } if (str[0] == 'l' || str[0] == 'L') { *side = NPY_SEARCHLEFT; } else if (str[0] == 'r' || str[0] == 'R') { *side = NPY_SEARCHRIGHT; } else { PyErr_Format(PyExc_ValueError, "'%s' is an invalid value for keyword 'side'", str); Py_XDECREF(tmp); return NPY_FAIL; } Py_XDECREF(tmp); return NPY_SUCCEED; } /*NUMPY_API * Convert an object to FORTRAN / C / ANY / KEEP */ NPY_NO_EXPORT int PyArray_OrderConverter(PyObject *object, NPY_ORDER *val) { char *str; /* Leave the desired default from the caller for NULL/Py_None */ if (object == NULL || object == Py_None) { return NPY_SUCCEED; } else if (PyUnicode_Check(object)) { PyObject *tmp; int ret; tmp = PyUnicode_AsASCIIString(object); ret = PyArray_OrderConverter(tmp, val); Py_DECREF(tmp); return ret; } else if (!PyBytes_Check(object) || PyBytes_GET_SIZE(object) < 1) { if (PyObject_IsTrue(object)) { *val = NPY_FORTRANORDER; } else { *val = NPY_CORDER; } if (PyErr_Occurred()) { return NPY_FAIL; } return NPY_SUCCEED; } else { str = PyBytes_AS_STRING(object); if (str[0] == 'C' || str[0] == 'c') { *val = NPY_CORDER; } else if (str[0] == 'F' || str[0] == 'f') { *val = NPY_FORTRANORDER; } else if (str[0] == 'A' || str[0] == 'a') { *val = NPY_ANYORDER; } else if (str[0] == 'K' || str[0] == 'k') { *val = NPY_KEEPORDER; } else { PyErr_SetString(PyExc_TypeError, "order not understood"); return NPY_FAIL; } } return NPY_SUCCEED; } /*NUMPY_API * Convert an object to NPY_RAISE / NPY_CLIP / NPY_WRAP */ NPY_NO_EXPORT int PyArray_ClipmodeConverter(PyObject *object, NPY_CLIPMODE *val) { if (object == NULL || object == Py_None) { *val = NPY_RAISE; } else if (PyBytes_Check(object)) { char *str; str = PyBytes_AS_STRING(object); if (str[0] == 'C' || str[0] == 'c') { *val = NPY_CLIP; } else if (str[0] == 'W' || str[0] == 'w') { *val = NPY_WRAP; } else if (str[0] == 'R' || str[0] == 'r') { *val = NPY_RAISE; } else { PyErr_SetString(PyExc_TypeError, "clipmode not understood"); return NPY_FAIL; } } else if (PyUnicode_Check(object)) { PyObject *tmp; int ret; tmp = PyUnicode_AsASCIIString(object); ret = PyArray_ClipmodeConverter(tmp, val); Py_DECREF(tmp); return ret; } else { int number = PyArray_PyIntAsInt(object); if (error_converting(number)) { goto fail; } if (number <= (int) NPY_RAISE && number >= (int) NPY_CLIP) { *val = (NPY_CLIPMODE) number; } else { goto fail; } } return NPY_SUCCEED; fail: PyErr_SetString(PyExc_TypeError, "clipmode not understood"); return NPY_FAIL; } /*NUMPY_API * Convert an object to an array of n NPY_CLIPMODE values. * This is intended to be used in functions where a different mode * could be applied to each axis, like in ravel_multi_index. */ NPY_NO_EXPORT int PyArray_ConvertClipmodeSequence(PyObject *object, NPY_CLIPMODE *modes, int n) { int i; /* Get the clip mode(s) */ if (object && (PyTuple_Check(object) || PyList_Check(object))) { if (PySequence_Size(object) != n) { PyErr_Format(PyExc_ValueError, "list of clipmodes has wrong length (%d instead of %d)", (int)PySequence_Size(object), n); return NPY_FAIL; } for (i = 0; i < n; ++i) { PyObject *item = PySequence_GetItem(object, i); if(item == NULL) { return NPY_FAIL; } if(PyArray_ClipmodeConverter(item, &modes[i]) != NPY_SUCCEED) { Py_DECREF(item); return NPY_FAIL; } Py_DECREF(item); } } else if (PyArray_ClipmodeConverter(object, &modes[0]) == NPY_SUCCEED) { for (i = 1; i < n; ++i) { modes[i] = modes[0]; } } else { return NPY_FAIL; } return NPY_SUCCEED; } /*NUMPY_API * Convert any Python object, *obj*, to an NPY_CASTING enum. */ NPY_NO_EXPORT int PyArray_CastingConverter(PyObject *obj, NPY_CASTING *casting) { char *str = NULL; Py_ssize_t length = 0; if (PyUnicode_Check(obj)) { PyObject *str_obj; int ret; str_obj = PyUnicode_AsASCIIString(obj); if (str_obj == NULL) { return 0; } ret = PyArray_CastingConverter(str_obj, casting); Py_DECREF(str_obj); return ret; } if (PyBytes_AsStringAndSize(obj, &str, &length) == -1) { return 0; } if (length >= 2) switch (str[2]) { case 0: if (strcmp(str, "no") == 0) { *casting = NPY_NO_CASTING; return 1; } break; case 'u': if (strcmp(str, "equiv") == 0) { *casting = NPY_EQUIV_CASTING; return 1; } break; case 'f': if (strcmp(str, "safe") == 0) { *casting = NPY_SAFE_CASTING; return 1; } break; case 'm': if (strcmp(str, "same_kind") == 0) { *casting = NPY_SAME_KIND_CASTING; return 1; } break; case 's': if (strcmp(str, "unsafe") == 0) { *casting = NPY_UNSAFE_CASTING; return 1; } break; } PyErr_SetString(PyExc_ValueError, "casting must be one of 'no', 'equiv', 'safe', " "'same_kind', or 'unsafe'"); return 0; } /***************************** * Other conversion functions *****************************/ /*NUMPY_API*/ NPY_NO_EXPORT int PyArray_PyIntAsInt(PyObject *o) { npy_intp long_value; /* This assumes that NPY_SIZEOF_INTP >= NPY_SIZEOF_INT */ long_value = PyArray_PyIntAsIntp(o); #if (NPY_SIZEOF_INTP > NPY_SIZEOF_INT) if ((long_value < INT_MIN) || (long_value > INT_MAX)) { PyErr_SetString(PyExc_ValueError, "integer won't fit into a C int"); return -1; } #endif return (int) long_value; } /*NUMPY_API*/ NPY_NO_EXPORT npy_intp PyArray_PyIntAsIntp(PyObject *o) { #if (NPY_SIZEOF_LONG < NPY_SIZEOF_INTP) long long long_value = -1; #else long long_value = -1; #endif PyObject *obj, *err; static char *msg = "an integer is required"; if (!o) { PyErr_SetString(PyExc_TypeError, msg); return -1; } /* Be a bit stricter and not allow bools, np.bool_ is handled later */ if (PyBool_Check(o)) { if (DEPRECATE("using a boolean instead of an integer" " will result in an error in the future") < 0) { return -1; } } /* * Since it is the usual case, first check if o is an integer. This is * an exact check, since otherwise __index__ is used. */ #if !defined(NPY_PY3K) 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); #else long_value = PyInt_AS_LONG(o); goto overflow_check; #endif } else #endif if (PyLong_CheckExact(o)) { #if (NPY_SIZEOF_LONG < NPY_SIZEOF_INTP) long_value = PyLong_AsLongLong(o); #else long_value = PyLong_AsLong(o); #endif return (npy_intp)long_value; } /* Disallow numpy.bool_. Boolean arrays do not currently support index. */ if (PyArray_IsScalar(o, Bool)) { if (DEPRECATE("using a boolean instead of an integer" " will result in an error in the future") < 0) { return -1; } } /* * The most general case. PyNumber_Index(o) covers everything * including arrays. In principle it may be possible to replace * the whole function by PyIndex_AsSSize_t after deprecation. */ obj = PyNumber_Index(o); if (obj) { #if (NPY_SIZEOF_LONG < NPY_SIZEOF_INTP) long_value = PyLong_AsLongLong(obj); #else long_value = PyLong_AsLong(obj); #endif Py_DECREF(obj); goto finish; } else { /* * Set the TypeError like PyNumber_Index(o) would after trying * the general case. */ PyErr_Clear(); } /* * For backward compatibility check the number C-Api number protcol * This should be removed up the finish label after deprecation. */ if (Py_TYPE(o)->tp_as_number != NULL && Py_TYPE(o)->tp_as_number->nb_int != NULL) { obj = Py_TYPE(o)->tp_as_number->nb_int(o); if (obj == NULL) { return -1; } #if (NPY_SIZEOF_LONG < NPY_SIZEOF_INTP) long_value = PyLong_AsLongLong(obj); #else long_value = PyLong_AsLong(obj); #endif Py_DECREF(obj); } #if !defined(NPY_PY3K) else if (Py_TYPE(o)->tp_as_number != NULL && Py_TYPE(o)->tp_as_number->nb_long != NULL) { obj = Py_TYPE(o)->tp_as_number->nb_long(o); if (obj == NULL) { return -1; } #if (NPY_SIZEOF_LONG < NPY_SIZEOF_INTP) long_value = PyLong_AsLongLong(obj); #else long_value = PyLong_AsLong(obj); #endif Py_DECREF(obj); } #endif else { PyErr_SetString(PyExc_TypeError, msg); return -1; } /* Give a deprecation warning, unless there was already an error */ if (!error_converting(long_value)) { if (DEPRECATE("using a non-integer number instead of an integer" " will result in an error in the future") < 0) { return -1; } } finish: if (error_converting(long_value)) { err = PyErr_Occurred(); /* Only replace TypeError's here, which are the normal errors. */ if (PyErr_GivenExceptionMatches(err, PyExc_TypeError)) { PyErr_SetString(PyExc_TypeError, msg); } return -1; } overflow_check: #if (NPY_SIZEOF_LONG < NPY_SIZEOF_INTP) #if (NPY_SIZEOF_LONGLONG > NPY_SIZEOF_INTP) if ((long_value < NPY_MIN_INTP) || (long_value > NPY_MAX_INTP)) { PyErr_SetString(PyExc_OverflowError, "Python int too large to convert to C numpy.intp"); return -1; } #endif #else #if (NPY_SIZEOF_LONG > NPY_SIZEOF_INTP) if ((long_value < NPY_MIN_INTP) || (long_value > NPY_MAX_INTP)) { PyErr_SetString(PyExc_OverflowError, "Python int too large to convert to C numpy.intp"); return -1; } #endif #endif return long_value; } /* * PyArray_IntpFromIndexSequence * Returns the number of dimensions or -1 if an error occurred. * vals must be large enough to hold maxvals. * Opposed to PyArray_IntpFromSequence it uses and returns npy_intp * for the number of values. */ NPY_NO_EXPORT npy_intp PyArray_IntpFromIndexSequence(PyObject *seq, npy_intp *vals, npy_intp maxvals) { Py_ssize_t nd; npy_intp i; PyObject *op, *err; /* * Check to see if sequence is a single integer first. * or, can be made into one */ nd = PySequence_Length(seq); if (nd == -1) { if (PyErr_Occurred()) { PyErr_Clear(); } vals[0] = PyArray_PyIntAsIntp(seq); if(vals[0] == -1) { err = PyErr_Occurred(); if (err && PyErr_GivenExceptionMatches(err, PyExc_OverflowError)) { PyErr_SetString(PyExc_ValueError, "Maximum allowed dimension exceeded"); } if(err != NULL) { return -1; } } nd = 1; } else { for (i = 0; i < PyArray_MIN(nd,maxvals); i++) { op = PySequence_GetItem(seq, i); if (op == NULL) { return -1; } vals[i] = PyArray_PyIntAsIntp(op); Py_DECREF(op); if(vals[i] == -1) { err = PyErr_Occurred(); if (err && PyErr_GivenExceptionMatches(err, PyExc_OverflowError)) { PyErr_SetString(PyExc_ValueError, "Maximum allowed dimension exceeded"); } if(err != NULL) { return -1; } } } } return nd; } /*NUMPY_API * PyArray_IntpFromSequence * Returns the number of integers converted or -1 if an error occurred. * vals must be large enough to hold maxvals */ NPY_NO_EXPORT int PyArray_IntpFromSequence(PyObject *seq, npy_intp *vals, int maxvals) { return PyArray_IntpFromIndexSequence(seq, vals, (npy_intp)maxvals); } /** * WARNING: This flag is a bad idea, but was the only way to both * 1) Support unpickling legacy pickles with object types. * 2) Deprecate (and later disable) usage of O4 and O8 * * The key problem is that the pickled representation unpickles by * directly calling the dtype constructor, which has no way of knowing * that it is in an unpickle context instead of a normal context without * evil global state like we create here. */ NPY_NO_EXPORT int evil_global_disable_warn_O4O8_flag = 0; /*NUMPY_API * Typestr converter */ NPY_NO_EXPORT int PyArray_TypestrConvert(int itemsize, int gentype) { int newtype = NPY_NOTYPE; PyArray_Descr *temp; const char *msg = "Specified size is invalid for this data type.\n" "Size will be ignored in NumPy 1.7 but may throw an exception in future versions."; switch (gentype) { case NPY_GENBOOLLTR: if (itemsize == 1) { newtype = NPY_BOOL; } break; case NPY_SIGNEDLTR: switch(itemsize) { case 1: newtype = NPY_INT8; break; case 2: newtype = NPY_INT16; break; case 4: newtype = NPY_INT32; break; case 8: newtype = NPY_INT64; break; #ifdef NPY_INT128 case 16: newtype = NPY_INT128; break; #endif } break; case NPY_UNSIGNEDLTR: switch(itemsize) { case 1: newtype = NPY_UINT8; break; case 2: newtype = NPY_UINT16; break; case 4: newtype = NPY_UINT32; break; case 8: newtype = NPY_UINT64; break; #ifdef NPY_INT128 case 16: newtype = NPY_UINT128; break; #endif } break; case NPY_FLOATINGLTR: switch(itemsize) { case 2: newtype = NPY_FLOAT16; break; case 4: newtype = NPY_FLOAT32; break; case 8: newtype = NPY_FLOAT64; break; #ifdef NPY_FLOAT80 case 10: newtype = NPY_FLOAT80; break; #endif #ifdef NPY_FLOAT96 case 12: newtype = NPY_FLOAT96; break; #endif #ifdef NPY_FLOAT128 case 16: newtype = NPY_FLOAT128; break; #endif } break; case NPY_COMPLEXLTR: switch(itemsize) { case 8: newtype = NPY_COMPLEX64; break; case 16: newtype = NPY_COMPLEX128; break; #ifdef NPY_FLOAT80 case 20: newtype = NPY_COMPLEX160; break; #endif #ifdef NPY_FLOAT96 case 24: newtype = NPY_COMPLEX192; break; #endif #ifdef NPY_FLOAT128 case 32: newtype = NPY_COMPLEX256; break; #endif } break; case NPY_OBJECTLTR: /* * For 'O4' and 'O8', let it pass, but raise a * deprecation warning. For all other cases, raise * an exception by leaving newtype unset. */ if (itemsize == 4 || itemsize == 8) { int ret = 0; if (evil_global_disable_warn_O4O8_flag) { ret = DEPRECATE("DType strings 'O4' and 'O8' are " "deprecated because they are platform " "specific. Use 'O' instead"); } if (ret == 0) { newtype = NPY_OBJECT; } } break; case NPY_STRINGLTR: case NPY_STRINGLTR2: newtype = NPY_STRING; break; case NPY_UNICODELTR: newtype = NPY_UNICODE; break; case NPY_VOIDLTR: newtype = NPY_VOID; break; case NPY_DATETIMELTR: if (itemsize == 8) { newtype = NPY_DATETIME; } break; case NPY_TIMEDELTALTR: if (itemsize == 8) { newtype = NPY_TIMEDELTA; } break; } /* * Raise deprecate warning if new type hasn't been * set yet and size char is invalid. * This should eventually be changed to an error in * future NumPy versions. */ if (newtype == NPY_NOTYPE) { temp = PyArray_DescrFromType(gentype); if (temp != NULL) { if (temp->elsize != itemsize) { if (DEPRECATE(msg) < 0) { Py_DECREF(temp); return -1; } newtype = gentype; } else { newtype = gentype; } Py_DECREF(temp); } } return newtype; } /* Lifted from numarray */ /* TODO: not documented */ /*NUMPY_API PyArray_IntTupleFromIntp */ NPY_NO_EXPORT PyObject * PyArray_IntTupleFromIntp(int len, npy_intp *vals) { int i; PyObject *intTuple = PyTuple_New(len); if (!intTuple) { goto fail; } for (i = 0; i < len; i++) { #if NPY_SIZEOF_INTP <= NPY_SIZEOF_LONG PyObject *o = PyInt_FromLong((long) vals[i]); #else PyObject *o = PyLong_FromLongLong((npy_longlong) vals[i]); #endif if (!o) { Py_DECREF(intTuple); intTuple = NULL; goto fail; } PyTuple_SET_ITEM(intTuple, i, o); } fail: return intTuple; } numpy-1.8.2/numpy/core/src/multiarray/array_assign.h0000664000175100017510000000635612370216242023750 0ustar vagrantvagrant00000000000000#ifndef _NPY_PRIVATE__ARRAY_ASSIGN_H_ #define _NPY_PRIVATE__ARRAY_ASSIGN_H_ /* * An array assignment function for copying arrays, treating the * arrays as flat according to their respective ordering rules. * This function makes a temporary copy of 'src' if 'src' and * 'dst' overlap, to be able to handle views of the same data with * different strides. * * dst: The destination array. * dst_order: The rule for how 'dst' is to be made flat. * src: The source array. * src_order: The rule for how 'src' is to be made flat. * casting: An exception is raised if the copy violates this * casting rule. * * Returns 0 on success, -1 on failure. */ /* Not yet implemented NPY_NO_EXPORT int PyArray_AssignArrayAsFlat(PyArrayObject *dst, NPY_ORDER dst_order, PyArrayObject *src, NPY_ORDER src_order, NPY_CASTING casting, npy_bool preservena, npy_bool *preservewhichna); */ NPY_NO_EXPORT int PyArray_AssignArray(PyArrayObject *dst, PyArrayObject *src, PyArrayObject *wheremask, NPY_CASTING casting); NPY_NO_EXPORT int PyArray_AssignRawScalar(PyArrayObject *dst, PyArray_Descr *src_dtype, char *src_data, PyArrayObject *wheremask, NPY_CASTING casting); /******** LOW-LEVEL SCALAR TO ARRAY ASSIGNMENT ********/ /* * Assigns the scalar value to every element of the destination raw array. * * Returns 0 on success, -1 on failure. */ NPY_NO_EXPORT int raw_array_assign_scalar(int ndim, npy_intp *shape, PyArray_Descr *dst_dtype, char *dst_data, npy_intp *dst_strides, PyArray_Descr *src_dtype, char *src_data); /* * Assigns the scalar value to every element of the destination raw array * where the 'wheremask' value is True. * * Returns 0 on success, -1 on failure. */ NPY_NO_EXPORT int raw_array_wheremasked_assign_scalar(int ndim, npy_intp *shape, PyArray_Descr *dst_dtype, char *dst_data, npy_intp *dst_strides, PyArray_Descr *src_dtype, char *src_data, PyArray_Descr *wheremask_dtype, char *wheremask_data, npy_intp *wheremask_strides); /******** LOW-LEVEL ARRAY MANIPULATION HELPERS ********/ /* * Internal detail of how much to buffer during array assignments which * need it. This is for more complex NA masking operations where masks * need to be inverted or combined together. */ #define NPY_ARRAY_ASSIGN_BUFFERSIZE 8192 /* * Broadcasts strides to match the given dimensions. Can be used, * for instance, to set up a raw iteration. * * 'strides_name' is used to produce an error message if the strides * cannot be broadcast. * * Returns 0 on success, -1 on failure. */ NPY_NO_EXPORT int broadcast_strides(int ndim, npy_intp *shape, int strides_ndim, npy_intp *strides_shape, npy_intp *strides, char *strides_name, npy_intp *out_strides); /* * Checks whether a data pointer + set of strides refers to a raw * array which is fully aligned data. */ NPY_NO_EXPORT int raw_array_is_aligned(int ndim, char *data, npy_intp *strides, int alignment); /* Returns 1 if the arrays have overlapping data, 0 otherwise */ NPY_NO_EXPORT int arrays_overlap(PyArrayObject *arr1, PyArrayObject *arr2); #endif numpy-1.8.2/numpy/core/src/multiarray/buffer.h0000664000175100017510000000055112370216242022526 0ustar vagrantvagrant00000000000000#ifndef _NPY_PRIVATE_BUFFER_H_ #define _NPY_PRIVATE_BUFFER_H_ #ifdef NPY_ENABLE_SEPARATE_COMPILATION extern NPY_NO_EXPORT PyBufferProcs array_as_buffer; #else NPY_NO_EXPORT PyBufferProcs array_as_buffer; #endif NPY_NO_EXPORT void _array_dealloc_buffer_info(PyArrayObject *self); NPY_NO_EXPORT PyArray_Descr* _descriptor_from_pep3118_format(char *s); #endif numpy-1.8.2/numpy/core/src/multiarray/lowlevel_strided_loops.c.src0000664000175100017510000011356612370216243026635 0ustar vagrantvagrant00000000000000/* * This file contains low-level loops for copying and byte-swapping * strided data. * * Copyright (c) 2010 by Mark Wiebe (mwwiebe@gmail.com) * The Univerity of British Columbia * * See LICENSE.txt for the license. */ #define PY_SSIZE_T_CLEAN #include "Python.h" #include "structmember.h" #define NPY_NO_DEPRECATED_API NPY_API_VERSION #define _MULTIARRAYMODULE #include #include #include #include "lowlevel_strided_loops.h" /* * x86 platform works with unaligned access but the compiler is allowed to * assume all data is aligned to its size by the C standard. This means it can * vectorize instructions peeling only by the size of the type, if the data is * not aligned to this size one ends up with data not correctly aligned for SSE * instructions (16 byte). * So this flag can only be enabled if autovectorization is disabled. */ #if (defined(NPY_CPU_X86) || defined(NPY_CPU_AMD64)) # define NPY_USE_UNALIGNED_ACCESS 0 #else # define NPY_USE_UNALIGNED_ACCESS 0 #endif #define _NPY_NOP1(x) (x) #define _NPY_NOP2(x) (x) #define _NPY_NOP4(x) (x) #define _NPY_NOP8(x) (x) #define _NPY_SWAP2(x) npy_bswap2(x) #define _NPY_SWAP4(x) npy_bswap4(x) #define _NPY_SWAP_PAIR4(x) (((((npy_uint32)x)&0xffu) << 8) | \ ((((npy_uint32)x)&0xff00u) >> 8) | \ ((((npy_uint32)x)&0xff0000u) << 8) | \ ((((npy_uint32)x)&0xff000000u) >> 8)) #define _NPY_SWAP8(x) npy_bswap8(x) #define _NPY_SWAP_PAIR8(x) (((((npy_uint64)x)&0xffULL) << 24) | \ ((((npy_uint64)x)&0xff00ULL) << 8) | \ ((((npy_uint64)x)&0xff0000ULL) >> 8) | \ ((((npy_uint64)x)&0xff000000ULL) >> 24) | \ ((((npy_uint64)x)&0xff00000000ULL) << 24) | \ ((((npy_uint64)x)&0xff0000000000ULL) << 8) | \ ((((npy_uint64)x)&0xff000000000000ULL) >> 8) | \ ((((npy_uint64)x)&0xff00000000000000ULL) >> 24)) #define _NPY_SWAP_INPLACE2(x) npy_bswap2_unaligned(x) #define _NPY_SWAP_INPLACE4(x) npy_bswap4_unaligned(x) #define _NPY_SWAP_INPLACE8(x) npy_bswap8_unaligned(x) #define _NPY_SWAP_INPLACE16(x) { \ char a = (x)[0]; (x)[0] = (x)[15]; (x)[15] = a; \ a = (x)[1]; (x)[1] = (x)[14]; (x)[14] = a; \ a = (x)[2]; (x)[2] = (x)[13]; (x)[13] = a; \ a = (x)[3]; (x)[3] = (x)[12]; (x)[12] = a; \ a = (x)[4]; (x)[4] = (x)[11]; (x)[11] = a; \ a = (x)[5]; (x)[5] = (x)[10]; (x)[10] = a; \ a = (x)[6]; (x)[6] = (x)[9]; (x)[9] = a; \ a = (x)[7]; (x)[7] = (x)[8]; (x)[8] = a; \ } /************* STRIDED COPYING/SWAPPING SPECIALIZED FUNCTIONS *************/ /**begin repeat * #elsize = 1, 2, 4, 8, 16# * #elsize_half = 0, 1, 2, 4, 8# * #type = npy_uint8, npy_uint16, npy_uint32, npy_uint64, npy_uint128# */ /**begin repeat1 * #oper = strided_to_strided, strided_to_contig, * contig_to_strided, contig_to_contig# * #src_contig = 0, 0, 1 ,1# * #dst_contig = 0, 1, 0 ,1# */ /**begin repeat2 * #swap = _NPY_NOP, _NPY_NOP, _NPY_SWAP_INPLACE, _NPY_SWAP, * _NPY_SWAP_INPLACE, _NPY_SWAP_PAIR# * #prefix = , _aligned, _swap, _aligned_swap, _swap_pair, _aligned_swap_pair# * #is_aligned = 0, 1, 0, 1, 0, 1# * #minelsize = 1, 1, 2, 2, 4, 4# * #is_swap = 0, 0, 1, 1, 2, 2# */ #if (@elsize@ >= @minelsize@) && \ (@elsize@ > 1 || @is_aligned@) && \ (!NPY_USE_UNALIGNED_ACCESS || @is_aligned@) #if @is_swap@ || @src_contig@ == 0 || @dst_contig@ == 0 /* * unrolling gains about 20-50% if the copy can be done in one mov instruction * if not it can decrease performance * tested to improve performance on intel xeon 5x/7x, core2duo, amd phenom x4 */ static void #if @is_aligned@ && @is_swap@ == 0 && @elsize@ <= NPY_SIZEOF_INTP NPY_GCC_UNROLL_LOOPS #endif @prefix@_@oper@_size@elsize@(char *dst, npy_intp dst_stride, char *src, npy_intp src_stride, npy_intp N, npy_intp NPY_UNUSED(src_itemsize), NpyAuxData *NPY_UNUSED(data)) { /*printf("fn @prefix@_@oper@_size@elsize@\n");*/ while (N > 0) { #if @is_aligned@ /* aligned copy and swap */ # if @elsize@ != 16 (*((@type@ *)dst)) = @swap@@elsize@(*((@type@ *)src)); # else # if @is_swap@ == 0 (*((npy_uint64 *)dst)) = (*((npy_uint64 *)src)); (*((npy_uint64 *)dst + 1)) = (*((npy_uint64 *)src + 1)); # elif @is_swap@ == 1 (*((npy_uint64 *)dst)) = _NPY_SWAP8(*((npy_uint64 *)src + 1)); (*((npy_uint64 *)dst + 1)) = _NPY_SWAP8(*((npy_uint64 *)src)); # elif @is_swap@ == 2 (*((npy_uint64 *)dst)) = _NPY_SWAP8(*((npy_uint64 *)src)); (*((npy_uint64 *)dst + 1)) = _NPY_SWAP8(*((npy_uint64 *)src + 1)); # endif # endif #else /* unaligned copy and swap */ memmove(dst, src, @elsize@); # if @is_swap@ == 1 @swap@@elsize@(dst); # elif @is_swap@ == 2 @swap@@elsize_half@(dst); @swap@@elsize_half@(dst + @elsize_half@); # endif #endif #if @dst_contig@ dst += @elsize@; #else dst += dst_stride; #endif #if @src_contig@ src += @elsize@; #else src += src_stride; #endif --N; } } #endif /* * 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 */ #if (@src_contig@ == 0) && @is_aligned@ static void @prefix@_@oper@_size@elsize@_srcstride0(char *dst, npy_intp dst_stride, char *src, npy_intp NPY_UNUSED(src_stride), npy_intp N, npy_intp NPY_UNUSED(src_itemsize), NpyAuxData *NPY_UNUSED(data)) { #if @elsize@ == 1 && @dst_contig@ memset(dst, *src, N); #else # if @elsize@ != 16 @type@ temp = @swap@@elsize@(*((@type@ *)src)); # else npy_uint64 temp0, temp1; # if @is_swap@ == 0 temp0 = (*((npy_uint64 *)src)); temp1 = (*((npy_uint64 *)src + 1)); # elif @is_swap@ == 1 temp0 = _NPY_SWAP8(*((npy_uint64 *)src + 1)); temp1 = _NPY_SWAP8(*((npy_uint64 *)src)); # elif @is_swap@ == 2 temp0 = _NPY_SWAP8(*((npy_uint64 *)src)); temp1 = _NPY_SWAP8(*((npy_uint64 *)src + 1)); # endif # endif while (N > 0) { # if @elsize@ != 16 *((@type@ *)dst) = temp; # else *((npy_uint64 *)dst) = temp0; *((npy_uint64 *)dst + 1) = temp1; # endif # if @dst_contig@ dst += @elsize@; # else dst += dst_stride; # endif --N; } #endif/* @elsize == 1 && @dst_contig@ -- else */ } #endif/* (@src_contig@ == 0) && @is_aligned@ */ #endif/* @elsize@ >= @minelsize@ */ /**end repeat2**/ /**end repeat1**/ /**end repeat**/ static void _strided_to_strided(char *dst, npy_intp dst_stride, char *src, npy_intp src_stride, npy_intp N, npy_intp src_itemsize, NpyAuxData *NPY_UNUSED(data)) { while (N > 0) { memmove(dst, src, src_itemsize); dst += dst_stride; src += src_stride; --N; } } static void _swap_strided_to_strided(char *dst, npy_intp dst_stride, char *src, npy_intp src_stride, npy_intp N, npy_intp src_itemsize, NpyAuxData *NPY_UNUSED(data)) { char *a, *b, c; while (N > 0) { memmove(dst, src, src_itemsize); /* general in-place swap */ a = dst; b = dst + src_itemsize - 1; while (a < b) { c = *a; *a = *b; *b = c; ++a; --b; } dst += dst_stride; src += src_stride; --N; } } static void _swap_pair_strided_to_strided(char *dst, npy_intp dst_stride, char *src, npy_intp src_stride, npy_intp N, npy_intp src_itemsize, NpyAuxData *NPY_UNUSED(data)) { char *a, *b, c; npy_intp itemsize_half = src_itemsize / 2; while (N > 0) { memmove(dst, src, src_itemsize); /* general in-place swap */ a = dst; b = dst + itemsize_half - 1; while (a < b) { c = *a; *a = *b; *b = c; ++a; --b; } /* general in-place swap */ a = dst + itemsize_half; b = dst + 2*itemsize_half - 1; while (a < b) { c = *a; *a = *b; *b = c; ++a; --b; } dst += dst_stride; src += src_stride; --N; } } static void _contig_to_contig(char *dst, npy_intp NPY_UNUSED(dst_stride), char *src, npy_intp NPY_UNUSED(src_stride), npy_intp N, npy_intp src_itemsize, NpyAuxData *NPY_UNUSED(data)) { memmove(dst, src, src_itemsize*N); } NPY_NO_EXPORT PyArray_StridedUnaryOp * PyArray_GetStridedCopyFn(int aligned, npy_intp src_stride, npy_intp dst_stride, npy_intp itemsize) { /* * Skip the "unaligned" versions on CPUs which support unaligned * memory accesses. */ #if !NPY_USE_UNALIGNED_ACCESS if (aligned) { #endif/*!NPY_USE_UNALIGNED_ACCESS*/ /* contiguous dst */ if (itemsize != 0 && dst_stride == itemsize) { /* constant src */ if (src_stride == 0) { switch (itemsize) { /**begin repeat * #elsize = 1, 2, 4, 8, 16# */ case @elsize@: return &_aligned_strided_to_contig_size@elsize@_srcstride0; /**end repeat**/ } } /* contiguous src */ else if (src_stride == itemsize) { return &_contig_to_contig; } /* general src */ else { switch (itemsize) { /**begin repeat * #elsize = 1, 2, 4, 8, 16# */ case @elsize@: return &_aligned_strided_to_contig_size@elsize@; /**end repeat**/ } } return &_strided_to_strided; } /* general dst */ else { /* constant src */ if (src_stride == 0) { switch (itemsize) { /**begin repeat * #elsize = 1, 2, 4, 8, 16# */ case @elsize@: return &_aligned_strided_to_strided_size@elsize@_srcstride0; /**end repeat**/ } } /* contiguous src */ else if (src_stride == itemsize) { switch (itemsize) { /**begin repeat * #elsize = 1, 2, 4, 8, 16# */ case @elsize@: return &_aligned_contig_to_strided_size@elsize@; /**end repeat**/ } return &_strided_to_strided; } else { switch (itemsize) { /**begin repeat * #elsize = 1, 2, 4, 8, 16# */ case @elsize@: return &_aligned_strided_to_strided_size@elsize@; /**end repeat**/ } } } #if !NPY_USE_UNALIGNED_ACCESS } else { /* contiguous dst */ if (itemsize != 0 && dst_stride == itemsize) { /* contiguous src */ if (itemsize != 0 && src_stride == itemsize) { return &_contig_to_contig; } /* general src */ else { switch (itemsize) { case 1: return &_aligned_strided_to_contig_size1; /**begin repeat * #elsize = 2, 4, 8, 16# */ case @elsize@: return &_strided_to_contig_size@elsize@; /**end repeat**/ } } return &_strided_to_strided; } /* general dst */ else { /* contiguous src */ if (itemsize != 0 && src_stride == itemsize) { switch (itemsize) { case 1: return &_aligned_contig_to_strided_size1; /**begin repeat * #elsize = 2, 4, 8, 16# */ case @elsize@: return &_contig_to_strided_size@elsize@; /**end repeat**/ } return &_strided_to_strided; } /* general src */ else { switch (itemsize) { case 1: return &_aligned_strided_to_strided_size1; /**begin repeat * #elsize = 2, 4, 8, 16# */ case @elsize@: return &_strided_to_strided_size@elsize@; /**end repeat**/ } } } } #endif/*!NPY_USE_UNALIGNED_ACCESS*/ return &_strided_to_strided; } /* * PyArray_GetStridedCopySwapFn and PyArray_GetStridedCopySwapPairFn are * nearly identical, so can do a repeat for them. */ /**begin repeat * #function = PyArray_GetStridedCopySwapFn, PyArray_GetStridedCopySwapPairFn# * #tag = , _pair# * #not_pair = 1, 0# */ NPY_NO_EXPORT PyArray_StridedUnaryOp * @function@(int aligned, npy_intp src_stride, npy_intp dst_stride, npy_intp itemsize) { /* * Skip the "unaligned" versions on CPUs which support unaligned * memory accesses. */ #if !NPY_USE_UNALIGNED_ACCESS if (aligned) { #endif/*!NPY_USE_UNALIGNED_ACCESS*/ /* contiguous dst */ if (itemsize != 0 && dst_stride == itemsize) { /* constant src */ if (src_stride == 0) { switch (itemsize) { /**begin repeat1 * #elsize = 2, 4, 8, 16# */ #if @not_pair@ || @elsize@ > 2 case @elsize@: return &_aligned_swap@tag@_strided_to_contig_size@elsize@_srcstride0; #endif /**end repeat1**/ } } /* contiguous src */ else if (src_stride == itemsize) { switch (itemsize) { /**begin repeat1 * #elsize = 2, 4, 8, 16# */ #if @not_pair@ || @elsize@ > 2 case @elsize@: return &_aligned_swap@tag@_contig_to_contig_size@elsize@; #endif /**end repeat1**/ } } /* general src */ else { switch (itemsize) { /**begin repeat1 * #elsize = 2, 4, 8, 16# */ #if @not_pair@ || @elsize@ > 2 case @elsize@: return &_aligned_swap@tag@_strided_to_contig_size@elsize@; #endif /**end repeat1**/ } } } /* general dst */ else { /* constant src */ if (src_stride == 0) { switch (itemsize) { /**begin repeat1 * #elsize = 2, 4, 8, 16# */ #if @not_pair@ || @elsize@ > 2 case @elsize@: return &_aligned_swap@tag@_strided_to_strided_size@elsize@_srcstride0; #endif /**end repeat1**/ } } /* contiguous src */ else if (src_stride == itemsize) { switch (itemsize) { /**begin repeat1 * #elsize = 2, 4, 8, 16# */ #if @not_pair@ || @elsize@ > 2 case @elsize@: return &_aligned_swap@tag@_contig_to_strided_size@elsize@; #endif /**end repeat1**/ } return &_swap@tag@_strided_to_strided; } else { switch (itemsize) { /**begin repeat1 * #elsize = 2, 4, 8, 16# */ #if @not_pair@ || @elsize@ > 2 case @elsize@: return &_aligned_swap@tag@_strided_to_strided_size@elsize@; #endif /**end repeat1**/ } } } #if !NPY_USE_UNALIGNED_ACCESS } else { /* contiguous dst */ if (itemsize != 0 && dst_stride == itemsize) { /* contiguous src */ if (itemsize != 0 && src_stride == itemsize) { switch (itemsize) { /**begin repeat1 * #elsize = 2, 4, 8, 16# */ #if @not_pair@ || @elsize@ > 2 case @elsize@: return &_swap@tag@_contig_to_contig_size@elsize@; #endif /**end repeat1**/ } } /* general src */ else { switch (itemsize) { /**begin repeat1 * #elsize = 2, 4, 8, 16# */ #if @not_pair@ || @elsize@ > 2 case @elsize@: return &_swap@tag@_strided_to_contig_size@elsize@; #endif /**end repeat1**/ } } return &_swap@tag@_strided_to_strided; } /* general dst */ else { /* contiguous src */ if (itemsize != 0 && src_stride == itemsize) { switch (itemsize) { /**begin repeat1 * #elsize = 2, 4, 8, 16# */ #if @not_pair@ || @elsize@ > 2 case @elsize@: return &_swap@tag@_contig_to_strided_size@elsize@; #endif /**end repeat1**/ } return &_swap@tag@_strided_to_strided; } /* general src */ else { switch (itemsize) { /**begin repeat1 * #elsize = 2, 4, 8, 16# */ #if @not_pair@ || @elsize@ > 2 case @elsize@: return &_swap@tag@_strided_to_strided_size@elsize@; #endif /**end repeat1**/ } } } } #endif/*!NPY_USE_UNALIGNED_ACCESS*/ return &_swap@tag@_strided_to_strided; } /**end repeat**/ /************* STRIDED CASTING SPECIALIZED FUNCTIONS *************/ /**begin repeat * * #NAME1 = BOOL, * UBYTE, USHORT, UINT, ULONG, ULONGLONG, * BYTE, SHORT, INT, LONG, LONGLONG, * HALF, FLOAT, DOUBLE, LONGDOUBLE, * CFLOAT, CDOUBLE, CLONGDOUBLE# * #name1 = bool, * ubyte, ushort, uint, ulong, ulonglong, * byte, short, int, long, longlong, * half, float, double, longdouble, * cfloat, cdouble, clongdouble# * #type1 = npy_bool, * npy_ubyte, npy_ushort, npy_uint, npy_ulong, npy_ulonglong, * npy_byte, npy_short, npy_int, npy_long, npy_longlong, * npy_half, npy_float, npy_double, npy_longdouble, * npy_cfloat, npy_cdouble, npy_clongdouble# * #rtype1 = npy_bool, * npy_ubyte, npy_ushort, npy_uint, npy_ulong, npy_ulonglong, * npy_byte, npy_short, npy_int, npy_long, npy_longlong, * npy_half, npy_float, npy_double, npy_longdouble, * npy_float, npy_double, npy_longdouble# * #is_bool1 = 1, 0*17# * #is_half1 = 0*11, 1, 0*6# * #is_float1 = 0*12, 1, 0, 0, 1, 0, 0# * #is_double1 = 0*13, 1, 0, 0, 1, 0# * #is_complex1 = 0*15, 1*3# */ /**begin repeat1 * * #NAME2 = BOOL, * UBYTE, USHORT, UINT, ULONG, ULONGLONG, * BYTE, SHORT, INT, LONG, LONGLONG, * HALF, FLOAT, DOUBLE, LONGDOUBLE, * CFLOAT, CDOUBLE, CLONGDOUBLE# * #name2 = bool, * ubyte, ushort, uint, ulong, ulonglong, * byte, short, int, long, longlong, * half, float, double, longdouble, * cfloat, cdouble, clongdouble# * #type2 = npy_bool, * npy_ubyte, npy_ushort, npy_uint, npy_ulong, npy_ulonglong, * npy_byte, npy_short, npy_int, npy_long, npy_longlong, * npy_half, npy_float, npy_double, npy_longdouble, * npy_cfloat, npy_cdouble, npy_clongdouble# * #rtype2 = npy_bool, * npy_ubyte, npy_ushort, npy_uint, npy_ulong, npy_ulonglong, * npy_byte, npy_short, npy_int, npy_long, npy_longlong, * npy_half, npy_float, npy_double, npy_longdouble, * npy_float, npy_double, npy_longdouble# * #is_bool2 = 1, 0*17# * #is_half2 = 0*11, 1, 0*6# * #is_float2 = 0*12, 1, 0, 0, 1, 0, 0# * #is_double2 = 0*13, 1, 0, 0, 1, 0# * #is_complex2 = 0*15, 1*3# */ /**begin repeat2 * #prefix = _aligned,,_aligned_contig,_contig# * #aligned = 1,0,1,0# * #contig = 0,0,1,1# */ #if !(NPY_USE_UNALIGNED_ACCESS && !@aligned@) /* For half types, don't use actual double/float types in conversion */ #if @is_half1@ || @is_half2@ # if @is_float1@ # define _TYPE1 npy_uint32 # elif @is_double1@ # define _TYPE1 npy_uint64 # else # define _TYPE1 @rtype1@ # endif # if @is_float2@ # define _TYPE2 npy_uint32 # elif @is_double2@ # define _TYPE2 npy_uint64 # else # define _TYPE2 @rtype2@ # endif #else #define _TYPE1 @rtype1@ #define _TYPE2 @rtype2@ #endif /* Determine an appropriate casting conversion function */ #if @is_half1@ # if @is_float2@ # define _CONVERT_FN(x) npy_halfbits_to_floatbits(x) # elif @is_double2@ # define _CONVERT_FN(x) npy_halfbits_to_doublebits(x) # elif @is_half2@ # define _CONVERT_FN(x) (x) # elif @is_bool2@ # define _CONVERT_FN(x) ((npy_bool)!npy_half_iszero(x)) # else # define _CONVERT_FN(x) ((_TYPE2)npy_half_to_float(x)) # endif #elif @is_half2@ # if @is_float1@ # define _CONVERT_FN(x) npy_floatbits_to_halfbits(x) # elif @is_double1@ # define _CONVERT_FN(x) npy_doublebits_to_halfbits(x) # else # define _CONVERT_FN(x) npy_float_to_half((float)x) # endif #else # if @is_bool2@ # define _CONVERT_FN(x) ((npy_bool)(x != 0)) # else # define _CONVERT_FN(x) ((_TYPE2)x) # endif #endif static void @prefix@_cast_@name1@_to_@name2@( char *dst, npy_intp dst_stride, char *src, npy_intp src_stride, npy_intp N, npy_intp NPY_UNUSED(src_itemsize), NpyAuxData *NPY_UNUSED(data)) { #if @is_complex1@ _TYPE1 src_value[2]; #elif !@aligned@ _TYPE1 src_value; #endif #if @is_complex2@ _TYPE2 dst_value[2]; #elif !@aligned@ _TYPE2 dst_value; #endif /*printf("@prefix@_cast_@name1@_to_@name2@\n");*/ while (N--) { #if @aligned@ # if @is_complex1@ src_value[0] = ((_TYPE1 *)src)[0]; src_value[1] = ((_TYPE1 *)src)[1]; # elif !@aligned@ src_value = *((_TYPE1 *)src); # endif #else memmove(&src_value, src, sizeof(src_value)); #endif /* Do the cast */ #if @is_complex1@ # if @is_complex2@ dst_value[0] = _CONVERT_FN(src_value[0]); dst_value[1] = _CONVERT_FN(src_value[1]); # elif !@aligned@ # if @is_bool2@ dst_value = _CONVERT_FN(src_value[0]) || _CONVERT_FN(src_value[1]); # else dst_value = _CONVERT_FN(src_value[0]); # endif # else # if @is_bool2@ *(_TYPE2 *)dst = _CONVERT_FN(src_value[0]) || _CONVERT_FN(src_value[1]); # else *(_TYPE2 *)dst = _CONVERT_FN(src_value[0]); # endif # endif #else # if @is_complex2@ # if !@aligned@ dst_value[0] = _CONVERT_FN(src_value); # else dst_value[0] = _CONVERT_FN(*(_TYPE1 *)src); # endif dst_value[1] = 0; # elif !@aligned@ dst_value = _CONVERT_FN(src_value); # else *(_TYPE2 *)dst = _CONVERT_FN(*(_TYPE1 *)src); # endif #endif #if @aligned@ # if @is_complex2@ ((_TYPE2 *)dst)[0] = dst_value[0]; ((_TYPE2 *)dst)[1] = dst_value[1]; # elif !@aligned@ *((_TYPE2 *)dst) = dst_value; # endif #else memmove(dst, &dst_value, sizeof(dst_value)); #endif #if @contig@ dst += sizeof(@type2@); src += sizeof(@type1@); #else dst += dst_stride; src += src_stride; #endif } } #undef _CONVERT_FN #undef _TYPE2 #undef _TYPE1 #endif /**end repeat2**/ /**end repeat1**/ /**end repeat**/ NPY_NO_EXPORT PyArray_StridedUnaryOp * PyArray_GetStridedNumericCastFn(int aligned, npy_intp src_stride, npy_intp dst_stride, int src_type_num, int dst_type_num) { switch (src_type_num) { /**begin repeat * * #NAME1 = BOOL, * UBYTE, USHORT, UINT, ULONG, ULONGLONG, * BYTE, SHORT, INT, LONG, LONGLONG, * HALF, FLOAT, DOUBLE, LONGDOUBLE, * CFLOAT, CDOUBLE, CLONGDOUBLE# * #name1 = bool, * ubyte, ushort, uint, ulong, ulonglong, * byte, short, int, long, longlong, * half, float, double, longdouble, * cfloat, cdouble, clongdouble# * #type1 = npy_bool, * npy_ubyte, npy_ushort, npy_uint, npy_ulong, npy_ulonglong, * npy_byte, npy_short, npy_int, npy_long, npy_longlong, * npy_half, npy_float, npy_double, npy_longdouble, * npy_cfloat, npy_cdouble, npy_clongdouble# */ case NPY_@NAME1@: /*printf("test fn %d - second %d\n", NPY_@NAME1@, dst_type_num);*/ switch (dst_type_num) { /**begin repeat1 * * #NAME2 = BOOL, * UBYTE, USHORT, UINT, ULONG, ULONGLONG, * BYTE, SHORT, INT, LONG, LONGLONG, * HALF, FLOAT, DOUBLE, LONGDOUBLE, * CFLOAT, CDOUBLE, CLONGDOUBLE# * #name2 = bool, * ubyte, ushort, uint, ulong, ulonglong, * byte, short, int, long, longlong, * half, float, double, longdouble, * cfloat, cdouble, clongdouble# * #type2 = npy_bool, * npy_ubyte, npy_ushort, npy_uint, npy_ulong, npy_ulonglong, * npy_byte, npy_short, npy_int, npy_long, npy_longlong, * npy_half, npy_float, npy_double, npy_longdouble, * npy_cfloat, npy_cdouble, npy_clongdouble# */ case NPY_@NAME2@: /*printf("ret fn %d %d\n", NPY_@NAME1@, NPY_@NAME2@);*/ # if NPY_USE_UNALIGNED_ACCESS if (src_stride == sizeof(@type1@) && dst_stride == sizeof(@type2@)) { return &_aligned_contig_cast_@name1@_to_@name2@; } else { return &_aligned_cast_@name1@_to_@name2@; } # else if (src_stride == sizeof(@type1@) && dst_stride == sizeof(@type2@)) { return aligned ? &_aligned_contig_cast_@name1@_to_@name2@ : &_contig_cast_@name1@_to_@name2@; } else { return aligned ? &_aligned_cast_@name1@_to_@name2@ : &_cast_@name1@_to_@name2@; } # endif /**end repeat1**/ } /*printf("switched test fn %d - second %d\n", NPY_@NAME1@, dst_type_num);*/ /**end repeat**/ } return NULL; } /****************** PRIMITIVE FLAT TO/FROM NDIM FUNCTIONS ******************/ /* See documentation of arguments in lowlevel_strided_loops.h */ NPY_NO_EXPORT npy_intp PyArray_TransferNDimToStrided(npy_intp ndim, char *dst, npy_intp dst_stride, char *src, npy_intp *src_strides, npy_intp src_strides_inc, npy_intp *coords, npy_intp coords_inc, npy_intp *shape, npy_intp shape_inc, npy_intp count, npy_intp src_itemsize, PyArray_StridedUnaryOp *stransfer, NpyAuxData *data) { npy_intp i, M, N, coord0, shape0, src_stride0, coord1, shape1, src_stride1; /* Finish off dimension 0 */ coord0 = coords[0]; shape0 = shape[0]; src_stride0 = src_strides[0]; N = shape0 - coord0; if (N >= count) { stransfer(dst, dst_stride, src, src_stride0, count, src_itemsize, data); return 0; } stransfer(dst, dst_stride, src, src_stride0, N, src_itemsize, data); count -= N; /* If it's 1-dimensional, there's no more to copy */ if (ndim == 1) { return count; } /* Adjust the src and dst pointers */ coord1 = (coords + coords_inc)[0]; shape1 = (shape + shape_inc)[0]; src_stride1 = (src_strides + src_strides_inc)[0]; src = src - coord0*src_stride0 + src_stride1; dst += N*dst_stride; /* Finish off dimension 1 */ M = (shape1 - coord1 - 1); N = shape0*M; for (i = 0; i < M; ++i) { if (shape0 >= count) { stransfer(dst, dst_stride, src, src_stride0, count, src_itemsize, data); return 0; } else { stransfer(dst, dst_stride, src, src_stride0, shape0, src_itemsize, data); } count -= shape0; src += src_stride1; dst += shape0*dst_stride; } /* If it's 2-dimensional, there's no more to copy */ if (ndim == 2) { return count; } /* General-case loop for everything else */ else { /* Iteration structure for dimensions 2 and up */ struct { npy_intp coord, shape, src_stride; } it[NPY_MAXDIMS]; /* Copy the coordinates and shape */ coords += 2*coords_inc; shape += 2*shape_inc; src_strides += 2*src_strides_inc; for (i = 0; i < ndim-2; ++i) { it[i].coord = coords[0]; it[i].shape = shape[0]; it[i].src_stride = src_strides[0]; coords += coords_inc; shape += shape_inc; src_strides += src_strides_inc; } for (;;) { /* Adjust the src pointer from the dimension 0 and 1 loop */ src = src - shape1*src_stride1; /* Increment to the next coordinate */ for (i = 0; i < ndim-2; ++i) { src += it[i].src_stride; if (++it[i].coord >= it[i].shape) { it[i].coord = 0; src -= it[i].src_stride*it[i].shape; } else { break; } } /* If the last dimension rolled over, we're done */ if (i == ndim-2) { return count; } /* A loop for dimensions 0 and 1 */ for (i = 0; i < shape1; ++i) { if (shape0 >= count) { stransfer(dst, dst_stride, src, src_stride0, count, src_itemsize, data); return 0; } else { stransfer(dst, dst_stride, src, src_stride0, shape0, src_itemsize, data); } count -= shape0; src += src_stride1; dst += shape0*dst_stride; } } } } /* See documentation of arguments in lowlevel_strided_loops.h */ NPY_NO_EXPORT npy_intp PyArray_TransferStridedToNDim(npy_intp ndim, char *dst, npy_intp *dst_strides, npy_intp dst_strides_inc, char *src, npy_intp src_stride, npy_intp *coords, npy_intp coords_inc, npy_intp *shape, npy_intp shape_inc, npy_intp count, npy_intp src_itemsize, PyArray_StridedUnaryOp *stransfer, NpyAuxData *data) { npy_intp i, M, N, coord0, shape0, dst_stride0, coord1, shape1, dst_stride1; /* Finish off dimension 0 */ coord0 = coords[0]; shape0 = shape[0]; dst_stride0 = dst_strides[0]; N = shape0 - coord0; if (N >= count) { stransfer(dst, dst_stride0, src, src_stride, count, src_itemsize, data); return 0; } stransfer(dst, dst_stride0, src, src_stride, N, src_itemsize, data); count -= N; /* If it's 1-dimensional, there's no more to copy */ if (ndim == 1) { return count; } /* Adjust the src and dst pointers */ coord1 = (coords + coords_inc)[0]; shape1 = (shape + shape_inc)[0]; dst_stride1 = (dst_strides + dst_strides_inc)[0]; dst = dst - coord0*dst_stride0 + dst_stride1; src += N*src_stride; /* Finish off dimension 1 */ M = (shape1 - coord1 - 1); N = shape0*M; for (i = 0; i < M; ++i) { if (shape0 >= count) { stransfer(dst, dst_stride0, src, src_stride, count, src_itemsize, data); return 0; } else { stransfer(dst, dst_stride0, src, src_stride, shape0, src_itemsize, data); } count -= shape0; dst += dst_stride1; src += shape0*src_stride; } /* If it's 2-dimensional, there's no more to copy */ if (ndim == 2) { return count; } /* General-case loop for everything else */ else { /* Iteration structure for dimensions 2 and up */ struct { npy_intp coord, shape, dst_stride; } it[NPY_MAXDIMS]; /* Copy the coordinates and shape */ coords += 2*coords_inc; shape += 2*shape_inc; dst_strides += 2*dst_strides_inc; for (i = 0; i < ndim-2; ++i) { it[i].coord = coords[0]; it[i].shape = shape[0]; it[i].dst_stride = dst_strides[0]; coords += coords_inc; shape += shape_inc; dst_strides += dst_strides_inc; } for (;;) { /* Adjust the dst pointer from the dimension 0 and 1 loop */ dst = dst - shape1*dst_stride1; /* Increment to the next coordinate */ for (i = 0; i < ndim-2; ++i) { dst += it[i].dst_stride; if (++it[i].coord >= it[i].shape) { it[i].coord = 0; dst -= it[i].dst_stride*it[i].shape; } else { break; } } /* If the last dimension rolled over, we're done */ if (i == ndim-2) { return count; } /* A loop for dimensions 0 and 1 */ for (i = 0; i < shape1; ++i) { if (shape0 >= count) { stransfer(dst, dst_stride0, src, src_stride, count, src_itemsize, data); return 0; } else { stransfer(dst, dst_stride0, src, src_stride, shape0, src_itemsize, data); } count -= shape0; dst += dst_stride1; src += shape0*src_stride; } } } } /* See documentation of arguments in lowlevel_strided_loops.h */ NPY_NO_EXPORT npy_intp PyArray_TransferMaskedStridedToNDim(npy_intp ndim, char *dst, npy_intp *dst_strides, npy_intp dst_strides_inc, char *src, npy_intp src_stride, npy_uint8 *mask, npy_intp mask_stride, npy_intp *coords, npy_intp coords_inc, npy_intp *shape, npy_intp shape_inc, npy_intp count, npy_intp src_itemsize, PyArray_MaskedStridedUnaryOp *stransfer, NpyAuxData *data) { npy_intp i, M, N, coord0, shape0, dst_stride0, coord1, shape1, dst_stride1; /* Finish off dimension 0 */ coord0 = coords[0]; shape0 = shape[0]; dst_stride0 = dst_strides[0]; N = shape0 - coord0; if (N >= count) { stransfer(dst, dst_stride0, src, src_stride, mask, mask_stride, count, src_itemsize, data); return 0; } stransfer(dst, dst_stride0, src, src_stride, mask, mask_stride, N, src_itemsize, data); count -= N; /* If it's 1-dimensional, there's no more to copy */ if (ndim == 1) { return count; } /* Adjust the src and dst pointers */ coord1 = (coords + coords_inc)[0]; shape1 = (shape + shape_inc)[0]; dst_stride1 = (dst_strides + dst_strides_inc)[0]; dst = dst - coord0*dst_stride0 + dst_stride1; src += N*src_stride; mask += N*mask_stride; /* Finish off dimension 1 */ M = (shape1 - coord1 - 1); N = shape0*M; for (i = 0; i < M; ++i) { if (shape0 >= count) { stransfer(dst, dst_stride0, src, src_stride, mask, mask_stride, count, src_itemsize, data); return 0; } else { stransfer(dst, dst_stride0, src, src_stride, mask, mask_stride, shape0, src_itemsize, data); } count -= shape0; dst += dst_stride1; src += shape0*src_stride; mask += shape0*mask_stride; } /* If it's 2-dimensional, there's no more to copy */ if (ndim == 2) { return count; } /* General-case loop for everything else */ else { /* Iteration structure for dimensions 2 and up */ struct { npy_intp coord, shape, dst_stride; } it[NPY_MAXDIMS]; /* Copy the coordinates and shape */ coords += 2*coords_inc; shape += 2*shape_inc; dst_strides += 2*dst_strides_inc; for (i = 0; i < ndim-2; ++i) { it[i].coord = coords[0]; it[i].shape = shape[0]; it[i].dst_stride = dst_strides[0]; coords += coords_inc; shape += shape_inc; dst_strides += dst_strides_inc; } for (;;) { /* Adjust the dst pointer from the dimension 0 and 1 loop */ dst = dst - shape1*dst_stride1; /* Increment to the next coordinate */ for (i = 0; i < ndim-2; ++i) { dst += it[i].dst_stride; if (++it[i].coord >= it[i].shape) { it[i].coord = 0; dst -= it[i].dst_stride*it[i].shape; } else { break; } } /* If the last dimension rolled over, we're done */ if (i == ndim-2) { return count; } /* A loop for dimensions 0 and 1 */ for (i = 0; i < shape1; ++i) { if (shape0 >= count) { stransfer(dst, dst_stride0, src, src_stride, mask, mask_stride, count, src_itemsize, data); return 0; } else { stransfer(dst, dst_stride0, src, src_stride, mask, mask_stride, shape0, src_itemsize, data); } count -= shape0; dst += dst_stride1; src += shape0*src_stride; mask += shape0*mask_stride; } } } } numpy-1.8.2/numpy/core/src/multiarray/nditer_pywrap.c0000664000175100017510000021354112370216243024145 0ustar vagrantvagrant00000000000000/* * This file implements the CPython wrapper of the new NumPy iterator. * * Copyright (c) 2010 by Mark Wiebe (mwwiebe@gmail.com) * The Univerity of British Columbia * * See LICENSE.txt for the license. */ #define PY_SSIZE_T_CLEAN #include "Python.h" #include "structmember.h" #define NPY_NO_DEPRECATED_API NPY_API_VERSION #define _MULTIARRAYMODULE #include #include "npy_config.h" #include "npy_pycompat.h" typedef struct NewNpyArrayIterObject_tag NewNpyArrayIterObject; struct NewNpyArrayIterObject_tag { PyObject_HEAD /* The iterator */ NpyIter *iter; /* Flag indicating iteration started/stopped */ char started, finished; /* Child to update for nested iteration */ NewNpyArrayIterObject *nested_child; /* Cached values from the iterator */ NpyIter_IterNextFunc *iternext; NpyIter_GetMultiIndexFunc *get_multi_index; char **dataptrs; PyArray_Descr **dtypes; PyArrayObject **operands; npy_intp *innerstrides, *innerloopsizeptr; char readflags[NPY_MAXARGS]; char writeflags[NPY_MAXARGS]; }; 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); } else { self->get_multi_index = NULL; } /* Internal data pointers */ self->dataptrs = NpyIter_GetDataPtrArray(iter); self->dtypes = NpyIter_GetDescrArray(iter); self->operands = NpyIter_GetOperandArray(iter); if (NpyIter_HasExternalLoop(iter)) { self->innerstrides = NpyIter_GetInnerStrideArray(iter); self->innerloopsizeptr = NpyIter_GetInnerLoopSizePtr(iter); } else { self->innerstrides = NULL; self->innerloopsizeptr = NULL; } /* The read/write settings */ NpyIter_GetReadFlags(iter, self->readflags); NpyIter_GetWriteFlags(iter, self->writeflags); return 0; } static PyObject * npyiter_new(PyTypeObject *subtype, PyObject *args, PyObject *kwds) { NewNpyArrayIterObject *self; self = (NewNpyArrayIterObject *)subtype->tp_alloc(subtype, 0); if (self != NULL) { self->iter = NULL; self->nested_child = NULL; } return (PyObject *)self; } static int NpyIter_GlobalFlagsConverter(PyObject *flags_in, npy_uint32 *flags) { npy_uint32 tmpflags = 0; int iflags, nflags; PyObject *f; char *str = NULL; Py_ssize_t length = 0; npy_uint32 flag; if (flags_in == NULL || flags_in == Py_None) { return 1; } if (!PyTuple_Check(flags_in) && !PyList_Check(flags_in)) { PyErr_SetString(PyExc_ValueError, "Iterator global flags must be a list or tuple of strings"); return 0; } nflags = PySequence_Size(flags_in); for (iflags = 0; iflags < nflags; ++iflags) { f = PySequence_GetItem(flags_in, iflags); if (f == NULL) { return 0; } if (PyUnicode_Check(f)) { /* accept unicode input */ PyObject *f_str; f_str = PyUnicode_AsASCIIString(f); if (f_str == NULL) { Py_DECREF(f); return 0; } Py_DECREF(f); f = f_str; } if (PyBytes_AsStringAndSize(f, &str, &length) == -1) { Py_DECREF(f); return 0; } /* Use switch statements to quickly isolate the right flag */ flag = 0; switch (str[0]) { case 'b': if (strcmp(str, "buffered") == 0) { flag = NPY_ITER_BUFFERED; } break; case 'c': if (length >= 6) switch (str[5]) { case 'e': if (strcmp(str, "c_index") == 0) { flag = NPY_ITER_C_INDEX; } break; case 'n': if (strcmp(str, "common_dtype") == 0) { flag = NPY_ITER_COMMON_DTYPE; } break; } break; case 'd': if (strcmp(str, "delay_bufalloc") == 0) { flag = NPY_ITER_DELAY_BUFALLOC; } break; case 'e': if (strcmp(str, "external_loop") == 0) { flag = NPY_ITER_EXTERNAL_LOOP; } break; case 'f': if (strcmp(str, "f_index") == 0) { flag = NPY_ITER_F_INDEX; } break; case 'g': /* * Documentation is grow_inner, but initial implementation * was growinner, so allowing for either. */ if (strcmp(str, "grow_inner") == 0 || strcmp(str, "growinner") == 0) { flag = NPY_ITER_GROWINNER; } break; case 'm': if (strcmp(str, "multi_index") == 0) { flag = NPY_ITER_MULTI_INDEX; } break; case 'r': if (strcmp(str, "ranged") == 0) { flag = NPY_ITER_RANGED; } else if (strcmp(str, "refs_ok") == 0) { flag = NPY_ITER_REFS_OK; } else if (strcmp(str, "reduce_ok") == 0) { flag = NPY_ITER_REDUCE_OK; } break; case 'z': if (strcmp(str, "zerosize_ok") == 0) { flag = NPY_ITER_ZEROSIZE_OK; } break; } if (flag == 0) { PyErr_Format(PyExc_ValueError, "Unexpected iterator global flag \"%s\"", str); Py_DECREF(f); return 0; } else { tmpflags |= flag; } Py_DECREF(f); } *flags |= tmpflags; return 1; } /* TODO: Use PyArray_OrderConverter once 'K' is added there */ static int npyiter_order_converter(PyObject *order_in, NPY_ORDER *order) { char *str = NULL; Py_ssize_t length = 0; if (PyUnicode_Check(order_in)) { /* accept unicode input */ PyObject *str_obj; int ret; str_obj = PyUnicode_AsASCIIString(order_in); if (str_obj == NULL) { return 0; } ret = npyiter_order_converter(str_obj, order); Py_DECREF(str_obj); return ret; } if (PyBytes_AsStringAndSize(order_in, &str, &length) == -1) { return 0; } if (length == 1) switch (str[0]) { case 'C': *order = NPY_CORDER; return 1; case 'F': *order = NPY_FORTRANORDER; return 1; case 'A': *order = NPY_ANYORDER; return 1; case 'K': *order = NPY_KEEPORDER; return 1; } PyErr_SetString(PyExc_ValueError, "order must be one of 'C', 'F', 'A', or 'K'"); return 0; } static int NpyIter_OpFlagsConverter(PyObject *op_flags_in, npy_uint32 *op_flags) { int iflags, nflags; npy_uint32 flag; if (!PyTuple_Check(op_flags_in) && !PyList_Check(op_flags_in)) { PyErr_SetString(PyExc_ValueError, "op_flags must be a tuple or array of per-op flag-tuples"); return 0; } nflags = PySequence_Size(op_flags_in); *op_flags = 0; for (iflags = 0; iflags < nflags; ++iflags) { PyObject *f; char *str = NULL; Py_ssize_t length = 0; f = PySequence_GetItem(op_flags_in, iflags); if (f == NULL) { return 0; } if (PyUnicode_Check(f)) { /* accept unicode input */ PyObject *f_str; f_str = PyUnicode_AsASCIIString(f); if (f_str == NULL) { Py_DECREF(f); return 0; } Py_DECREF(f); f = f_str; } if (PyBytes_AsStringAndSize(f, &str, &length) == -1) { Py_DECREF(f); PyErr_SetString(PyExc_ValueError, "op_flags must be a tuple or array of per-op flag-tuples"); return 0; } /* Use switch statements to quickly isolate the right flag */ flag = 0; switch (str[0]) { case 'a': if (length > 2) switch(str[2]) { case 'i': if (strcmp(str, "aligned") == 0) { flag = NPY_ITER_ALIGNED; } break; case 'l': if (strcmp(str, "allocate") == 0) { flag = NPY_ITER_ALLOCATE; } break; case 'r': if (strcmp(str, "arraymask") == 0) { flag = NPY_ITER_ARRAYMASK; } break; } break; case 'c': if (strcmp(str, "copy") == 0) { flag = NPY_ITER_COPY; } if (strcmp(str, "contig") == 0) { flag = NPY_ITER_CONTIG; } break; case 'n': switch (str[1]) { case 'b': if (strcmp(str, "nbo") == 0) { flag = NPY_ITER_NBO; } break; case 'o': if (strcmp(str, "no_subtype") == 0) { flag = NPY_ITER_NO_SUBTYPE; } else if (strcmp(str, "no_broadcast") == 0) { flag = NPY_ITER_NO_BROADCAST; } break; } break; case 'r': if (length > 4) switch (str[4]) { case 'o': if (strcmp(str, "readonly") == 0) { flag = NPY_ITER_READONLY; } break; case 'w': if (strcmp(str, "readwrite") == 0) { flag = NPY_ITER_READWRITE; } break; } break; case 'u': switch (str[1]) { case 'p': if (strcmp(str, "updateifcopy") == 0) { flag = NPY_ITER_UPDATEIFCOPY; } break; } break; case 'v': if (strcmp(str, "virtual") == 0) { flag = NPY_ITER_VIRTUAL; } break; case 'w': if (length > 5) switch (str[5]) { case 'o': if (strcmp(str, "writeonly") == 0) { flag = NPY_ITER_WRITEONLY; } break; case 'm': if (strcmp(str, "writemasked") == 0) { flag = NPY_ITER_WRITEMASKED; } break; } break; } if (flag == 0) { PyErr_Format(PyExc_ValueError, "Unexpected per-op iterator flag \"%s\"", str); Py_DECREF(f); return 0; } else { *op_flags |= flag; } Py_DECREF(f); } return 1; } static int npyiter_convert_op_flags_array(PyObject *op_flags_in, npy_uint32 *op_flags_array, npy_intp nop) { npy_intp iop; if (!PyTuple_Check(op_flags_in) && !PyList_Check(op_flags_in)) { PyErr_SetString(PyExc_ValueError, "op_flags must be a tuple or array of per-op flag-tuples"); return 0; } if (PySequence_Size(op_flags_in) != nop) { goto try_single_flags; } for (iop = 0; iop < nop; ++iop) { PyObject *f = PySequence_GetItem(op_flags_in, iop); if (f == NULL) { return 0; } /* If the first item is a string, try as one set of flags */ if (iop == 0 && (PyBytes_Check(f) || PyUnicode_Check(f))) { Py_DECREF(f); goto try_single_flags; } if (NpyIter_OpFlagsConverter(f, &op_flags_array[iop]) != 1) { Py_DECREF(f); return 0; } Py_DECREF(f); } return 1; try_single_flags: if (NpyIter_OpFlagsConverter(op_flags_in, &op_flags_array[0]) != 1) { return 0; } for (iop = 1; iop < nop; ++iop) { op_flags_array[iop] = op_flags_array[0]; } return 1; } static int npyiter_convert_dtypes(PyObject *op_dtypes_in, PyArray_Descr **op_dtypes, npy_intp nop) { npy_intp iop; /* * If the input isn't a tuple of dtypes, try converting it as-is * to a dtype, and replicating to all operands. */ if ((!PyTuple_Check(op_dtypes_in) && !PyList_Check(op_dtypes_in)) || PySequence_Size(op_dtypes_in) != nop) { goto try_single_dtype; } for (iop = 0; iop < nop; ++iop) { PyObject *dtype = PySequence_GetItem(op_dtypes_in, iop); if (dtype == NULL) { npy_intp i; for (i = 0; i < iop; ++i ) { Py_XDECREF(op_dtypes[i]); } return 0; } /* Try converting the object to a descr */ if (PyArray_DescrConverter2(dtype, &op_dtypes[iop]) != 1) { npy_intp i; for (i = 0; i < iop; ++i ) { Py_XDECREF(op_dtypes[i]); } Py_DECREF(dtype); PyErr_Clear(); goto try_single_dtype; } Py_DECREF(dtype); } return 1; try_single_dtype: if (PyArray_DescrConverter2(op_dtypes_in, &op_dtypes[0]) == 1) { for (iop = 1; iop < nop; ++iop) { op_dtypes[iop] = op_dtypes[0]; Py_XINCREF(op_dtypes[iop]); } return 1; } return 0; } static int npyiter_convert_op_axes(PyObject *op_axes_in, npy_intp nop, int **op_axes, int *oa_ndim) { PyObject *a; int iop; if ((!PyTuple_Check(op_axes_in) && !PyList_Check(op_axes_in)) || PySequence_Size(op_axes_in) != nop) { PyErr_SetString(PyExc_ValueError, "op_axes must be a tuple/list matching the number of ops"); return 0; } *oa_ndim = -1; /* Copy the tuples into op_axes */ for (iop = 0; iop < nop; ++iop) { int idim; a = PySequence_GetItem(op_axes_in, iop); if (a == NULL) { return 0; } if (a == Py_None) { op_axes[iop] = NULL; } else { if (!PyTuple_Check(a) && !PyList_Check(a)) { PyErr_SetString(PyExc_ValueError, "Each entry of op_axes must be None " "or a tuple/list"); Py_DECREF(a); return 0; } if (*oa_ndim == -1) { *oa_ndim = PySequence_Size(a); if (*oa_ndim > NPY_MAXDIMS) { PyErr_SetString(PyExc_ValueError, "Too many dimensions in op_axes"); return 0; } } if (PySequence_Size(a) != *oa_ndim) { PyErr_SetString(PyExc_ValueError, "Each entry of op_axes must have the same size"); Py_DECREF(a); return 0; } for (idim = 0; idim < *oa_ndim; ++idim) { PyObject *v = PySequence_GetItem(a, idim); if (v == NULL) { Py_DECREF(a); return 0; } /* numpy.newaxis is None */ if (v == Py_None) { op_axes[iop][idim] = -1; } else { op_axes[iop][idim] = PyArray_PyIntAsInt(v); if (op_axes[iop][idim]==-1 && PyErr_Occurred()) { Py_DECREF(a); Py_DECREF(v); return 0; } } Py_DECREF(v); } Py_DECREF(a); } } if (*oa_ndim == -1) { PyErr_SetString(PyExc_ValueError, "If op_axes is provided, at least one list of axes " "must be contained within it"); return 0; } return 1; } /* * Converts the operand array and op_flags array into the form * NpyIter_AdvancedNew needs. Sets nop, and on success, each * op[i] owns a reference to an array object. */ static int npyiter_convert_ops(PyObject *op_in, PyObject *op_flags_in, PyArrayObject **op, npy_uint32 *op_flags, int *nop_out) { int iop, nop; /* nop and op */ if (PyTuple_Check(op_in) || PyList_Check(op_in)) { nop = PySequence_Size(op_in); if (nop == 0) { PyErr_SetString(PyExc_ValueError, "Must provide at least one operand"); return 0; } if (nop > NPY_MAXARGS) { PyErr_SetString(PyExc_ValueError, "Too many operands"); return 0; } for (iop = 0; iop < nop; ++iop) { PyObject *item = PySequence_GetItem(op_in, iop); if (item == NULL) { npy_intp i; for (i = 0; i < iop; ++i) { Py_XDECREF(op[i]); } return 0; } else if (item == Py_None) { Py_DECREF(item); item = NULL; } /* This is converted to an array after op flags are retrieved */ op[iop] = (PyArrayObject *)item; } } else { nop = 1; /* Is converted to an array after op flags are retrieved */ Py_INCREF(op_in); op[0] = (PyArrayObject *)op_in; } *nop_out = nop; /* op_flags */ if (op_flags_in == NULL || op_flags_in == Py_None) { for (iop = 0; iop < nop; ++iop) { /* * By default, make NULL operands writeonly and flagged for * allocation, and everything else readonly. To write * to a provided operand, you must specify the write flag manually. */ if (op[iop] == NULL) { op_flags[iop] = NPY_ITER_WRITEONLY | NPY_ITER_ALLOCATE; } else { op_flags[iop] = NPY_ITER_READONLY; } } } else if (npyiter_convert_op_flags_array(op_flags_in, op_flags, nop) != 1) { for (iop = 0; iop < nop; ++iop) { Py_XDECREF(op[iop]); } *nop_out = 0; return 0; } /* Now that we have the flags - convert all the ops to arrays */ for (iop = 0; iop < nop; ++iop) { if (op[iop] != NULL) { PyArrayObject *ao; int fromanyflags = 0; if (op_flags[iop]&(NPY_ITER_READWRITE|NPY_ITER_WRITEONLY)) { fromanyflags |= NPY_ARRAY_UPDATEIFCOPY; } ao = (PyArrayObject *)PyArray_FromAny((PyObject *)op[iop], NULL, 0, 0, fromanyflags, NULL); if (ao == NULL) { if (PyErr_Occurred() && PyErr_ExceptionMatches(PyExc_TypeError)) { PyErr_SetString(PyExc_TypeError, "Iterator operand is flagged as writeable, " "but is an object which cannot be written " "back to via UPDATEIFCOPY"); } for (iop = 0; iop < nop; ++iop) { Py_DECREF(op[iop]); } *nop_out = 0; return 0; } Py_DECREF(op[iop]); op[iop] = ao; } } return 1; } static int npyiter_init(NewNpyArrayIterObject *self, PyObject *args, PyObject *kwds) { static char *kwlist[] = {"op", "flags", "op_flags", "op_dtypes", "order", "casting", "op_axes", "itershape", "buffersize", NULL}; PyObject *op_in = NULL, *op_flags_in = NULL, *op_dtypes_in = NULL, *op_axes_in = NULL; int iop, nop = 0; PyArrayObject *op[NPY_MAXARGS]; npy_uint32 flags = 0; NPY_ORDER order = NPY_KEEPORDER; NPY_CASTING casting = NPY_SAFE_CASTING; npy_uint32 op_flags[NPY_MAXARGS]; PyArray_Descr *op_request_dtypes[NPY_MAXARGS]; int oa_ndim = -1; int op_axes_arrays[NPY_MAXARGS][NPY_MAXDIMS]; int *op_axes[NPY_MAXARGS]; PyArray_Dims itershape = {NULL, 0}; int buffersize = 0; if (self->iter != NULL) { PyErr_SetString(PyExc_ValueError, "Iterator was already initialized"); return -1; } if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O&OOO&O&OO&i", kwlist, &op_in, NpyIter_GlobalFlagsConverter, &flags, &op_flags_in, &op_dtypes_in, npyiter_order_converter, &order, PyArray_CastingConverter, &casting, &op_axes_in, PyArray_IntpConverter, &itershape, &buffersize)) { PyDimMem_FREE(itershape.ptr); return -1; } /* Set the dtypes and ops to all NULL to start */ memset(op_request_dtypes, 0, sizeof(op_request_dtypes)); /* op and op_flags */ if (npyiter_convert_ops(op_in, op_flags_in, op, op_flags, &nop) != 1) { goto fail; } /* op_request_dtypes */ if (op_dtypes_in != NULL && op_dtypes_in != Py_None && npyiter_convert_dtypes(op_dtypes_in, op_request_dtypes, nop) != 1) { goto fail; } /* op_axes */ if (op_axes_in != NULL && op_axes_in != Py_None) { /* Initialize to point to the op_axes arrays */ for (iop = 0; iop < nop; ++iop) { op_axes[iop] = op_axes_arrays[iop]; } if (npyiter_convert_op_axes(op_axes_in, nop, op_axes, &oa_ndim) != 1) { goto fail; } } if (itershape.len > 0) { if (oa_ndim == -1) { oa_ndim = itershape.len; memset(op_axes, 0, sizeof(op_axes[0]) * nop); } else if (oa_ndim != itershape.len) { PyErr_SetString(PyExc_ValueError, "'op_axes' and 'itershape' must have the same number " "of entries equal to the iterator ndim"); goto fail; } } else if (itershape.ptr != NULL) { PyDimMem_FREE(itershape.ptr); itershape.ptr = NULL; } self->iter = NpyIter_AdvancedNew(nop, op, flags, order, casting, op_flags, op_request_dtypes, oa_ndim, oa_ndim >= 0 ? op_axes : NULL, itershape.ptr, buffersize); if (self->iter == NULL) { goto fail; } /* Cache some values for the member functions to use */ if (npyiter_cache_values(self) < 0) { goto fail; } if (NpyIter_GetIterSize(self->iter) == 0) { self->started = 1; self->finished = 1; } else { self->started = 0; self->finished = 0; } PyDimMem_FREE(itershape.ptr); /* Release the references we got to the ops and dtypes */ for (iop = 0; iop < nop; ++iop) { Py_XDECREF(op[iop]); Py_XDECREF(op_request_dtypes[iop]); } return 0; fail: PyDimMem_FREE(itershape.ptr); for (iop = 0; iop < nop; ++iop) { Py_XDECREF(op[iop]); Py_XDECREF(op_request_dtypes[iop]); } return -1; } NPY_NO_EXPORT PyObject * NpyIter_NestedIters(PyObject *NPY_UNUSED(self), PyObject *args, PyObject *kwds) { static char *kwlist[] = {"op", "axes", "flags", "op_flags", "op_dtypes", "order", "casting", "buffersize", NULL}; PyObject *op_in = NULL, *axes_in = NULL, *op_flags_in = NULL, *op_dtypes_in = NULL; int iop, nop = 0, inest, nnest = 0; PyArrayObject *op[NPY_MAXARGS]; npy_uint32 flags = 0, flags_inner; NPY_ORDER order = NPY_KEEPORDER; NPY_CASTING casting = NPY_SAFE_CASTING; npy_uint32 op_flags[NPY_MAXARGS], op_flags_inner[NPY_MAXARGS]; PyArray_Descr *op_request_dtypes[NPY_MAXARGS], *op_request_dtypes_inner[NPY_MAXARGS]; int op_axes_data[NPY_MAXDIMS]; int *nested_op_axes[NPY_MAXDIMS]; int nested_naxes[NPY_MAXDIMS], iaxes, naxes; int negones[NPY_MAXDIMS]; char used_axes[NPY_MAXDIMS]; int buffersize = 0; PyObject *ret = NULL; if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO|O&OOO&O&i", kwlist, &op_in, &axes_in, NpyIter_GlobalFlagsConverter, &flags, &op_flags_in, &op_dtypes_in, npyiter_order_converter, &order, PyArray_CastingConverter, &casting, &buffersize)) { return NULL; } /* axes */ if (!PyTuple_Check(axes_in) && !PyList_Check(axes_in)) { PyErr_SetString(PyExc_ValueError, "axes must be a tuple of axis arrays"); return NULL; } nnest = PySequence_Size(axes_in); if (nnest < 2) { PyErr_SetString(PyExc_ValueError, "axes must have at least 2 entries for nested iteration"); return NULL; } naxes = 0; memset(used_axes, 0, NPY_MAXDIMS); for (inest = 0; inest < nnest; ++inest) { PyObject *item = PySequence_GetItem(axes_in, inest); npy_intp i; if (item == NULL) { return NULL; } if (!PyTuple_Check(item) && !PyList_Check(item)) { PyErr_SetString(PyExc_ValueError, "Each item in axes must be a an integer tuple"); Py_DECREF(item); return NULL; } nested_naxes[inest] = PySequence_Size(item); if (naxes + nested_naxes[inest] > NPY_MAXDIMS) { PyErr_SetString(PyExc_ValueError, "Too many axes given"); Py_DECREF(item); return NULL; } for (i = 0; i < nested_naxes[inest]; ++i) { PyObject *v = PySequence_GetItem(item, i); npy_intp axis; if (v == NULL) { Py_DECREF(item); return NULL; } axis = PyInt_AsLong(v); Py_DECREF(v); if (axis < 0 || axis >= NPY_MAXDIMS) { PyErr_SetString(PyExc_ValueError, "An axis is out of bounds"); Py_DECREF(item); return NULL; } /* * This check is very important, without it out of bounds * data accesses are possible. */ if (used_axes[axis] != 0) { PyErr_SetString(PyExc_ValueError, "An axis is used more than once"); Py_DECREF(item); return NULL; } used_axes[axis] = 1; op_axes_data[naxes+i] = axis; } nested_op_axes[inest] = &op_axes_data[naxes]; naxes += nested_naxes[inest]; Py_DECREF(item); } /* op and op_flags */ if (npyiter_convert_ops(op_in, op_flags_in, op, op_flags, &nop) != 1) { return NULL; } /* Set the dtypes to all NULL to start as well */ memset(op_request_dtypes, 0, sizeof(op_request_dtypes[0])*nop); memset(op_request_dtypes_inner, 0, sizeof(op_request_dtypes_inner[0])*nop); /* op_request_dtypes */ if (op_dtypes_in != NULL && op_dtypes_in != Py_None && npyiter_convert_dtypes(op_dtypes_in, op_request_dtypes, nop) != 1) { goto fail; } ret = PyTuple_New(nnest); if (ret == NULL) { goto fail; } /* For broadcasting allocated arrays */ for (iaxes = 0; iaxes < naxes; ++iaxes) { negones[iaxes] = -1; } /* * Clear any unnecessary ALLOCATE flags, so we can use them * to indicate exactly the allocated outputs. Also, separate * the inner loop flags. */ for (iop = 0; iop < nop; ++iop) { if ((op_flags[iop]&NPY_ITER_ALLOCATE) && op[iop] != NULL) { op_flags[iop] &= ~NPY_ITER_ALLOCATE; } /* * Clear any flags allowing copies or output allocation for * the inner loop. */ op_flags_inner[iop] = op_flags[iop] & ~(NPY_ITER_COPY| NPY_ITER_UPDATEIFCOPY| NPY_ITER_ALLOCATE); /* * If buffering is enabled and copying is not, * clear the nbo_aligned flag and strip the data type * for the outer loops. */ if ((flags&(NPY_ITER_BUFFERED)) && !(op_flags[iop]&(NPY_ITER_COPY| NPY_ITER_UPDATEIFCOPY| NPY_ITER_ALLOCATE))) { op_flags[iop] &= ~(NPY_ITER_NBO|NPY_ITER_ALIGNED|NPY_ITER_CONTIG); op_request_dtypes_inner[iop] = op_request_dtypes[iop]; op_request_dtypes[iop] = NULL; } } /* Only the inner loop gets the buffering and no inner flags */ flags_inner = flags&~NPY_ITER_COMMON_DTYPE; flags &= ~(NPY_ITER_EXTERNAL_LOOP| NPY_ITER_BUFFERED); for (inest = 0; inest < nnest; ++inest) { NewNpyArrayIterObject *iter; int *op_axes_nop[NPY_MAXARGS]; /* * All the operands' op_axes are the same, except for * allocated outputs. */ for (iop = 0; iop < nop; ++iop) { if (op_flags[iop]&NPY_ITER_ALLOCATE) { if (inest == 0) { op_axes_nop[iop] = NULL; } else { op_axes_nop[iop] = negones; } } else { op_axes_nop[iop] = nested_op_axes[inest]; } } /* printf("\n"); for (iop = 0; iop < nop; ++iop) { npy_intp i; for (i = 0; i < nested_naxes[inest]; ++i) { printf("%d ", (int)op_axes_nop[iop][i]); } printf("\n"); } */ /* Allocate the iterator */ iter = (NewNpyArrayIterObject *)npyiter_new(&NpyIter_Type, NULL, NULL); if (iter == NULL) { Py_DECREF(ret); goto fail; } if (inest < nnest-1) { iter->iter = NpyIter_AdvancedNew(nop, op, flags, order, casting, op_flags, op_request_dtypes, nested_naxes[inest], op_axes_nop, NULL, 0); } else { iter->iter = NpyIter_AdvancedNew(nop, op, flags_inner, order, casting, op_flags_inner, op_request_dtypes_inner, nested_naxes[inest], op_axes_nop, NULL, buffersize); } if (iter->iter == NULL) { Py_DECREF(ret); goto fail; } /* Cache some values for the member functions to use */ if (npyiter_cache_values(iter) < 0) { Py_DECREF(ret); goto fail; } if (NpyIter_GetIterSize(iter->iter) == 0) { iter->started = 1; iter->finished = 1; } else { iter->started = 0; iter->finished = 0; } /* * If there are any allocated outputs or any copies were made, * adjust op so that the other iterators use the same ones. */ if (inest == 0) { PyArrayObject **operands = NpyIter_GetOperandArray(iter->iter); for (iop = 0; iop < nop; ++iop) { if (op[iop] != operands[iop]) { Py_XDECREF(op[iop]); op[iop] = operands[iop]; Py_INCREF(op[iop]); } /* * Clear any flags allowing copies for * the rest of the iterators */ op_flags[iop] &= ~(NPY_ITER_COPY| NPY_ITER_UPDATEIFCOPY); } /* Clear the common dtype flag for the rest of the iterators */ flags &= ~NPY_ITER_COMMON_DTYPE; } PyTuple_SET_ITEM(ret, inest, (PyObject *)iter); } /* Release our references to the ops and dtypes */ for (iop = 0; iop < nop; ++iop) { Py_XDECREF(op[iop]); Py_XDECREF(op_request_dtypes[iop]); Py_XDECREF(op_request_dtypes_inner[iop]); } /* Set up the nested child references */ for (inest = 0; inest < nnest-1; ++inest) { NewNpyArrayIterObject *iter; iter = (NewNpyArrayIterObject *)PyTuple_GET_ITEM(ret, inest); /* * Indicates which iterator to reset with new base pointers * each iteration step. */ iter->nested_child = (NewNpyArrayIterObject *)PyTuple_GET_ITEM(ret, inest+1); Py_INCREF(iter->nested_child); /* * Need to do a nested reset so all the iterators point * at the right data */ if (NpyIter_ResetBasePointers(iter->nested_child->iter, iter->dataptrs, NULL) != NPY_SUCCEED) { Py_DECREF(ret); return NULL; } } return ret; fail: for (iop = 0; iop < nop; ++iop) { Py_XDECREF(op[iop]); Py_XDECREF(op_request_dtypes[iop]); Py_XDECREF(op_request_dtypes_inner[iop]); } return NULL; } static void npyiter_dealloc(NewNpyArrayIterObject *self) { if (self->iter) { NpyIter_Deallocate(self->iter); self->iter = NULL; Py_XDECREF(self->nested_child); self->nested_child = NULL; } Py_TYPE(self)->tp_free((PyObject*)self); } static int npyiter_resetbasepointers(NewNpyArrayIterObject *self) { while (self->nested_child) { if (NpyIter_ResetBasePointers(self->nested_child->iter, self->dataptrs, NULL) != NPY_SUCCEED) { return NPY_FAIL; } self = self->nested_child; if (NpyIter_GetIterSize(self->iter) == 0) { self->started = 1; self->finished = 1; } else { self->started = 0; self->finished = 0; } } return NPY_SUCCEED; } static PyObject * npyiter_reset(NewNpyArrayIterObject *self) { if (self->iter == NULL) { PyErr_SetString(PyExc_ValueError, "Iterator is invalid"); return NULL; } if (NpyIter_Reset(self->iter, NULL) != NPY_SUCCEED) { return NULL; } if (NpyIter_GetIterSize(self->iter) == 0) { self->started = 1; self->finished = 1; } else { self->started = 0; self->finished = 0; } if (self->get_multi_index == NULL && NpyIter_HasMultiIndex(self->iter)) { self->get_multi_index = NpyIter_GetGetMultiIndex(self->iter, NULL); } /* If there is nesting, the nested iterators should be reset */ if (npyiter_resetbasepointers(self) != NPY_SUCCEED) { return NULL; } Py_RETURN_NONE; } /* * Makes a copy of the iterator. Note that the nesting is not * copied. */ static PyObject * npyiter_copy(NewNpyArrayIterObject *self) { NewNpyArrayIterObject *iter; if (self->iter == NULL) { PyErr_SetString(PyExc_ValueError, "Iterator is invalid"); return NULL; } /* Allocate the iterator */ iter = (NewNpyArrayIterObject *)npyiter_new(&NpyIter_Type, NULL, NULL); if (iter == NULL) { return NULL; } /* Copy the C iterator */ iter->iter = NpyIter_Copy(self->iter); if (iter->iter == NULL) { Py_DECREF(iter); return NULL; } /* Cache some values for the member functions to use */ if (npyiter_cache_values(iter) < 0) { Py_DECREF(iter); return NULL; } iter->started = self->started; iter->finished = self->finished; return (PyObject *)iter; } static PyObject * npyiter_iternext(NewNpyArrayIterObject *self) { if (self->iter != NULL && self->iternext != NULL && !self->finished && self->iternext(self->iter)) { /* If there is nesting, the nested iterators should be reset */ if (npyiter_resetbasepointers(self) != NPY_SUCCEED) { return NULL; } Py_RETURN_TRUE; } else { self->finished = 1; Py_RETURN_FALSE; } } static PyObject * npyiter_remove_axis(NewNpyArrayIterObject *self, PyObject *args) { int axis = 0; if (self->iter == NULL) { PyErr_SetString(PyExc_ValueError, "Iterator is invalid"); return NULL; } if (!PyArg_ParseTuple(args, "i", &axis)) { return NULL; } if (NpyIter_RemoveAxis(self->iter, axis) != NPY_SUCCEED) { return NULL; } /* RemoveAxis invalidates cached values */ if (npyiter_cache_values(self) < 0) { return NULL; } /* RemoveAxis also resets the iterator */ if (NpyIter_GetIterSize(self->iter) == 0) { self->started = 1; self->finished = 1; } else { self->started = 0; self->finished = 0; } Py_RETURN_NONE; } static PyObject * npyiter_remove_multi_index(NewNpyArrayIterObject *self) { if (self->iter == NULL) { PyErr_SetString(PyExc_ValueError, "Iterator is invalid"); return NULL; } NpyIter_RemoveMultiIndex(self->iter); /* RemoveMultiIndex invalidates cached values */ npyiter_cache_values(self); /* RemoveMultiIndex also resets the iterator */ if (NpyIter_GetIterSize(self->iter) == 0) { self->started = 1; self->finished = 1; } else { self->started = 0; self->finished = 0; } Py_RETURN_NONE; } static PyObject * npyiter_enable_external_loop(NewNpyArrayIterObject *self) { if (self->iter == NULL) { PyErr_SetString(PyExc_ValueError, "Iterator is invalid"); return NULL; } NpyIter_EnableExternalLoop(self->iter); /* EnableExternalLoop invalidates cached values */ npyiter_cache_values(self); /* EnableExternalLoop also resets the iterator */ if (NpyIter_GetIterSize(self->iter) == 0) { self->started = 1; self->finished = 1; } else { self->started = 0; self->finished = 0; } Py_RETURN_NONE; } static PyObject * npyiter_debug_print(NewNpyArrayIterObject *self) { if (self->iter != NULL) { NpyIter_DebugPrint(self->iter); } else { printf("Iterator: (nil)\n"); } Py_RETURN_NONE; } NPY_NO_EXPORT PyObject * npyiter_seq_item(NewNpyArrayIterObject *self, Py_ssize_t i); static PyObject *npyiter_value_get(NewNpyArrayIterObject *self) { PyObject *ret; npy_intp iop, nop; if (self->iter == NULL || self->finished) { PyErr_SetString(PyExc_ValueError, "Iterator is past the end"); return NULL; } nop = NpyIter_GetNOp(self->iter); /* Return an array or tuple of arrays with the values */ if (nop == 1) { ret = npyiter_seq_item(self, 0); } else { ret = PyTuple_New(nop); if (ret == NULL) { return NULL; } for (iop = 0; iop < nop; ++iop) { PyObject *a = npyiter_seq_item(self, iop); if (a == NULL) { Py_DECREF(ret); return NULL; } PyTuple_SET_ITEM(ret, iop, a); } } return ret; } static PyObject *npyiter_operands_get(NewNpyArrayIterObject *self) { PyObject *ret; npy_intp iop, nop; PyArrayObject **operands; if (self->iter == NULL) { PyErr_SetString(PyExc_ValueError, "Iterator is invalid"); return NULL; } nop = NpyIter_GetNOp(self->iter); operands = self->operands; ret = PyTuple_New(nop); if (ret == NULL) { return NULL; } for (iop = 0; iop < nop; ++iop) { PyObject *operand = (PyObject *)operands[iop]; Py_INCREF(operand); PyTuple_SET_ITEM(ret, iop, operand); } return ret; } static PyObject *npyiter_itviews_get(NewNpyArrayIterObject *self) { PyObject *ret; npy_intp iop, nop; if (self->iter == NULL) { PyErr_SetString(PyExc_ValueError, "Iterator is invalid"); return NULL; } nop = NpyIter_GetNOp(self->iter); ret = PyTuple_New(nop); if (ret == NULL) { return NULL; } for (iop = 0; iop < nop; ++iop) { PyArrayObject *view = NpyIter_GetIterView(self->iter, iop); if (view == NULL) { Py_DECREF(ret); return NULL; } PyTuple_SET_ITEM(ret, iop, (PyObject *)view); } return ret; } static PyObject * npyiter_next(NewNpyArrayIterObject *self) { if (self->iter == NULL || self->iternext == NULL || self->finished) { return NULL; } /* * Use the started flag for the Python iteration protocol to work * when buffering is enabled. */ if (self->started) { if (!self->iternext(self->iter)) { self->finished = 1; return NULL; } /* If there is nesting, the nested iterators should be reset */ if (npyiter_resetbasepointers(self) != NPY_SUCCEED) { return NULL; } } self->started = 1; return npyiter_value_get(self); }; static PyObject *npyiter_shape_get(NewNpyArrayIterObject *self) { PyObject *ret; npy_intp idim, ndim, shape[NPY_MAXDIMS]; if (self->iter == NULL || self->finished) { PyErr_SetString(PyExc_ValueError, "Iterator is past the end"); return NULL; } if (NpyIter_GetShape(self->iter, shape) == NPY_SUCCEED) { ndim = NpyIter_GetNDim(self->iter); ret = PyTuple_New(ndim); if (ret != NULL) { for (idim = 0; idim < ndim; ++idim) { PyTuple_SET_ITEM(ret, idim, PyInt_FromLong(shape[idim])); } return ret; } } return NULL; } static PyObject *npyiter_multi_index_get(NewNpyArrayIterObject *self) { PyObject *ret; npy_intp idim, ndim, multi_index[NPY_MAXDIMS]; if (self->iter == NULL || self->finished) { PyErr_SetString(PyExc_ValueError, "Iterator is past the end"); return NULL; } if (self->get_multi_index != NULL) { ndim = NpyIter_GetNDim(self->iter); self->get_multi_index(self->iter, multi_index); ret = PyTuple_New(ndim); for (idim = 0; idim < ndim; ++idim) { PyTuple_SET_ITEM(ret, idim, PyInt_FromLong(multi_index[idim])); } return ret; } else { if (!NpyIter_HasMultiIndex(self->iter)) { PyErr_SetString(PyExc_ValueError, "Iterator is not tracking a multi-index"); return NULL; } else if (NpyIter_HasDelayedBufAlloc(self->iter)) { PyErr_SetString(PyExc_ValueError, "Iterator construction used delayed buffer allocation, " "and no reset has been done yet"); return NULL; } else { PyErr_SetString(PyExc_ValueError, "Iterator is in an invalid state"); return NULL; } } } static int npyiter_multi_index_set(NewNpyArrayIterObject *self, PyObject *value) { npy_intp idim, ndim, multi_index[NPY_MAXDIMS]; if (value == NULL) { PyErr_SetString(PyExc_AttributeError, "Cannot delete nditer multi_index"); return -1; } if (self->iter == NULL) { PyErr_SetString(PyExc_ValueError, "Iterator is invalid"); return -1; } if (NpyIter_HasMultiIndex(self->iter)) { ndim = NpyIter_GetNDim(self->iter); if (!PySequence_Check(value)) { PyErr_SetString(PyExc_ValueError, "multi_index must be set with a sequence"); return -1; } if (PySequence_Size(value) != ndim) { PyErr_SetString(PyExc_ValueError, "Wrong number of indices"); return -1; } for (idim = 0; idim < ndim; ++idim) { PyObject *v = PySequence_GetItem(value, idim); multi_index[idim] = PyInt_AsLong(v); if (multi_index[idim]==-1 && PyErr_Occurred()) { return -1; } } if (NpyIter_GotoMultiIndex(self->iter, multi_index) != NPY_SUCCEED) { return -1; } self->started = 0; self->finished = 0; /* If there is nesting, the nested iterators should be reset */ if (npyiter_resetbasepointers(self) != NPY_SUCCEED) { return -1; } return 0; } else { PyErr_SetString(PyExc_ValueError, "Iterator is not tracking a multi-index"); return -1; } } static PyObject *npyiter_index_get(NewNpyArrayIterObject *self) { if (self->iter == NULL || self->finished) { PyErr_SetString(PyExc_ValueError, "Iterator is past the end"); return NULL; } if (NpyIter_HasIndex(self->iter)) { npy_intp ind = *NpyIter_GetIndexPtr(self->iter); return PyInt_FromLong(ind); } else { PyErr_SetString(PyExc_ValueError, "Iterator does not have an index"); return NULL; } } static int npyiter_index_set(NewNpyArrayIterObject *self, PyObject *value) { if (value == NULL) { PyErr_SetString(PyExc_AttributeError, "Cannot delete nditer index"); return -1; } if (self->iter == NULL) { PyErr_SetString(PyExc_ValueError, "Iterator is invalid"); return -1; } if (NpyIter_HasIndex(self->iter)) { npy_intp ind; ind = PyInt_AsLong(value); if (ind==-1 && PyErr_Occurred()) { return -1; } if (NpyIter_GotoIndex(self->iter, ind) != NPY_SUCCEED) { return -1; } self->started = 0; self->finished = 0; /* If there is nesting, the nested iterators should be reset */ if (npyiter_resetbasepointers(self) != NPY_SUCCEED) { return -1; } return 0; } else { PyErr_SetString(PyExc_ValueError, "Iterator does not have an index"); return -1; } } static PyObject *npyiter_iterindex_get(NewNpyArrayIterObject *self) { if (self->iter == NULL || self->finished) { PyErr_SetString(PyExc_ValueError, "Iterator is past the end"); return NULL; } return PyInt_FromLong(NpyIter_GetIterIndex(self->iter)); } static int npyiter_iterindex_set(NewNpyArrayIterObject *self, PyObject *value) { npy_intp iterindex; if (value == NULL) { PyErr_SetString(PyExc_AttributeError, "Cannot delete nditer iterindex"); return -1; } if (self->iter == NULL) { PyErr_SetString(PyExc_ValueError, "Iterator is invalid"); return -1; } iterindex = PyInt_AsLong(value); if (iterindex==-1 && PyErr_Occurred()) { return -1; } if (NpyIter_GotoIterIndex(self->iter, iterindex) != NPY_SUCCEED) { return -1; } self->started = 0; self->finished = 0; /* If there is nesting, the nested iterators should be reset */ if (npyiter_resetbasepointers(self) != NPY_SUCCEED) { return -1; } return 0; } static PyObject *npyiter_iterrange_get(NewNpyArrayIterObject *self) { npy_intp istart = 0, iend = 0; PyObject *ret; if (self->iter == NULL) { PyErr_SetString(PyExc_ValueError, "Iterator is invalid"); return NULL; } NpyIter_GetIterIndexRange(self->iter, &istart, &iend); ret = PyTuple_New(2); if (ret == NULL) { return NULL; } PyTuple_SET_ITEM(ret, 0, PyInt_FromLong(istart)); PyTuple_SET_ITEM(ret, 1, PyInt_FromLong(iend)); return ret; } static int npyiter_iterrange_set(NewNpyArrayIterObject *self, PyObject *value) { npy_intp istart = 0, iend = 0; if (value == NULL) { PyErr_SetString(PyExc_AttributeError, "Cannot delete nditer iterrange"); return -1; } if (self->iter == NULL) { PyErr_SetString(PyExc_ValueError, "Iterator is invalid"); return -1; } if (!PyArg_ParseTuple(value, "nn", &istart, &iend)) { return -1; } if (NpyIter_ResetToIterIndexRange(self->iter, istart, iend, NULL) != NPY_SUCCEED) { return -1; } if (istart < iend) { self->started = self->finished = 0; } else { self->started = self->finished = 1; } if (self->get_multi_index == NULL && NpyIter_HasMultiIndex(self->iter)) { self->get_multi_index = NpyIter_GetGetMultiIndex(self->iter, NULL); } /* If there is nesting, the nested iterators should be reset */ if (npyiter_resetbasepointers(self) != NPY_SUCCEED) { return -1; } return 0; } static PyObject *npyiter_has_delayed_bufalloc_get(NewNpyArrayIterObject *self) { if (self->iter == NULL) { PyErr_SetString(PyExc_ValueError, "Iterator is invalid"); return NULL; } if (NpyIter_HasDelayedBufAlloc(self->iter)) { Py_RETURN_TRUE; } else { Py_RETURN_FALSE; } } static PyObject *npyiter_iterationneedsapi_get(NewNpyArrayIterObject *self) { if (self->iter == NULL) { PyErr_SetString(PyExc_ValueError, "Iterator is invalid"); return NULL; } if (NpyIter_IterationNeedsAPI(self->iter)) { Py_RETURN_TRUE; } else { Py_RETURN_FALSE; } } static PyObject *npyiter_has_multi_index_get(NewNpyArrayIterObject *self) { if (self->iter == NULL) { PyErr_SetString(PyExc_ValueError, "Iterator is invalid"); return NULL; } if (NpyIter_HasMultiIndex(self->iter)) { Py_RETURN_TRUE; } else { Py_RETURN_FALSE; } } static PyObject *npyiter_has_index_get(NewNpyArrayIterObject *self) { if (self->iter == NULL) { PyErr_SetString(PyExc_ValueError, "Iterator is invalid"); return NULL; } if (NpyIter_HasIndex(self->iter)) { Py_RETURN_TRUE; } else { Py_RETURN_FALSE; } } static PyObject *npyiter_dtypes_get(NewNpyArrayIterObject *self) { PyObject *ret; npy_intp iop, nop; PyArray_Descr **dtypes; if (self->iter == NULL) { PyErr_SetString(PyExc_ValueError, "Iterator is invalid"); return NULL; } nop = NpyIter_GetNOp(self->iter); ret = PyTuple_New(nop); if (ret == NULL) { return NULL; } dtypes = self->dtypes; for (iop = 0; iop < nop; ++iop) { PyArray_Descr *dtype = dtypes[iop]; Py_INCREF(dtype); PyTuple_SET_ITEM(ret, iop, (PyObject *)dtype); } return ret; } static PyObject *npyiter_ndim_get(NewNpyArrayIterObject *self) { if (self->iter == NULL) { PyErr_SetString(PyExc_ValueError, "Iterator is invalid"); return NULL; } return PyInt_FromLong(NpyIter_GetNDim(self->iter)); } static PyObject *npyiter_nop_get(NewNpyArrayIterObject *self) { if (self->iter == NULL) { PyErr_SetString(PyExc_ValueError, "Iterator is invalid"); return NULL; } return PyInt_FromLong(NpyIter_GetNOp(self->iter)); } static PyObject *npyiter_itersize_get(NewNpyArrayIterObject *self) { if (self->iter == NULL) { PyErr_SetString(PyExc_ValueError, "Iterator is invalid"); return NULL; } return PyInt_FromLong(NpyIter_GetIterSize(self->iter)); } static PyObject *npyiter_finished_get(NewNpyArrayIterObject *self) { if (self->iter == NULL || !self->finished) { Py_RETURN_FALSE; } else { Py_RETURN_TRUE; } } NPY_NO_EXPORT Py_ssize_t npyiter_seq_length(NewNpyArrayIterObject *self) { if (self->iter == NULL) { return 0; } else { return NpyIter_GetNOp(self->iter); } } NPY_NO_EXPORT PyObject * npyiter_seq_item(NewNpyArrayIterObject *self, Py_ssize_t i) { PyArrayObject *ret; npy_intp ret_ndim; npy_intp nop, innerloopsize, innerstride; char *dataptr; PyArray_Descr *dtype; int has_external_loop; Py_ssize_t i_orig = i; if (self->iter == NULL || self->finished) { PyErr_SetString(PyExc_ValueError, "Iterator is past the end"); return NULL; } if (NpyIter_HasDelayedBufAlloc(self->iter)) { PyErr_SetString(PyExc_ValueError, "Iterator construction used delayed buffer allocation, " "and no reset has been done yet"); return NULL; } nop = NpyIter_GetNOp(self->iter); /* Negative indexing */ if (i < 0) { i += nop; } if (i < 0 || i >= nop) { PyErr_Format(PyExc_IndexError, "Iterator operand index %d is out of bounds", (int)i_orig); return NULL; } #if 0 /* * This check is disabled because it prevents things like * np.add(it[0], it[1], it[2]), where it[2] is a write-only * parameter. When write-only, the value of it[i] is * likely random junk, as if it were allocated with an * np.empty(...) call. */ if (!self->readflags[i]) { PyErr_Format(PyExc_RuntimeError, "Iterator operand %d is write-only", (int)i); return NULL; } #endif dataptr = self->dataptrs[i]; dtype = self->dtypes[i]; has_external_loop = NpyIter_HasExternalLoop(self->iter); if (has_external_loop) { innerloopsize = *self->innerloopsizeptr; innerstride = self->innerstrides[i]; ret_ndim = 1; } else { innerloopsize = 1; innerstride = 0; /* If the iterator is going over every element, return array scalars */ ret_ndim = 0; } Py_INCREF(dtype); ret = (PyArrayObject *)PyArray_NewFromDescr(&PyArray_Type, dtype, 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_XDECREF(ret); return NULL; } PyArray_UpdateFlags(ret, NPY_ARRAY_UPDATE_ALL); return (PyObject *)ret; } NPY_NO_EXPORT PyObject * npyiter_seq_slice(NewNpyArrayIterObject *self, Py_ssize_t ilow, Py_ssize_t ihigh) { PyObject *ret; npy_intp nop; Py_ssize_t i; if (self->iter == NULL || self->finished) { PyErr_SetString(PyExc_ValueError, "Iterator is past the end"); return NULL; } if (NpyIter_HasDelayedBufAlloc(self->iter)) { PyErr_SetString(PyExc_ValueError, "Iterator construction used delayed buffer allocation, " "and no reset has been done yet"); return NULL; } nop = NpyIter_GetNOp(self->iter); if (ilow < 0) { ilow = 0; } else if (ilow >= nop) { ilow = nop-1; } if (ihigh < ilow) { ihigh = ilow; } else if (ihigh > nop) { ihigh = nop; } ret = PyTuple_New(ihigh-ilow); if (ret == NULL) { return NULL; } for (i = ilow; i < ihigh ; ++i) { PyObject *item = npyiter_seq_item(self, i); if (item == NULL) { Py_DECREF(ret); return NULL; } PyTuple_SET_ITEM(ret, i-ilow, item); } return ret; } NPY_NO_EXPORT int npyiter_seq_ass_item(NewNpyArrayIterObject *self, Py_ssize_t i, PyObject *v) { npy_intp nop, innerloopsize, innerstride; char *dataptr; PyArray_Descr *dtype; PyArrayObject *tmp; int ret, has_external_loop; Py_ssize_t i_orig = i; if (v == NULL) { PyErr_SetString(PyExc_TypeError, "Cannot delete iterator elements"); return -1; } if (self->iter == NULL || self->finished) { PyErr_SetString(PyExc_ValueError, "Iterator is past the end"); return -1; } if (NpyIter_HasDelayedBufAlloc(self->iter)) { PyErr_SetString(PyExc_ValueError, "Iterator construction used delayed buffer allocation, " "and no reset has been done yet"); return -1; } nop = NpyIter_GetNOp(self->iter); /* Negative indexing */ if (i < 0) { i += nop; } if (i < 0 || i >= nop) { PyErr_Format(PyExc_IndexError, "Iterator operand index %d is out of bounds", (int)i_orig); return -1; } if (!self->writeflags[i]) { PyErr_Format(PyExc_RuntimeError, "Iterator operand %d is not writeable", (int)i_orig); return -1; } dataptr = self->dataptrs[i]; dtype = self->dtypes[i]; has_external_loop = NpyIter_HasExternalLoop(self->iter); if (has_external_loop) { innerloopsize = *self->innerloopsizeptr; innerstride = self->innerstrides[i]; } else { innerloopsize = 1; innerstride = 0; } /* TODO - there should be a better way than this... */ Py_INCREF(dtype); tmp = (PyArrayObject *)PyArray_NewFromDescr(&PyArray_Type, dtype, 1, &innerloopsize, &innerstride, dataptr, NPY_ARRAY_WRITEABLE, NULL); if (tmp == NULL) { return -1; } PyArray_UpdateFlags(tmp, NPY_ARRAY_UPDATE_ALL); ret = PyArray_CopyObject(tmp, v); Py_DECREF(tmp); return ret; } static int npyiter_seq_ass_slice(NewNpyArrayIterObject *self, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v) { npy_intp nop; Py_ssize_t i; if (v == NULL) { PyErr_SetString(PyExc_TypeError, "Cannot delete iterator elements"); return -1; } if (self->iter == NULL || self->finished) { PyErr_SetString(PyExc_ValueError, "Iterator is past the end"); return -1; } if (NpyIter_HasDelayedBufAlloc(self->iter)) { PyErr_SetString(PyExc_ValueError, "Iterator construction used delayed buffer allocation, " "and no reset has been done yet"); return -1; } nop = NpyIter_GetNOp(self->iter); if (ilow < 0) { ilow = 0; } else if (ilow >= nop) { ilow = nop-1; } if (ihigh < ilow) { ihigh = ilow; } else if (ihigh > nop) { ihigh = nop; } if (!PySequence_Check(v) || PySequence_Size(v) != ihigh-ilow) { PyErr_SetString(PyExc_ValueError, "Wrong size to assign to iterator slice"); return -1; } for (i = ilow; i < ihigh ; ++i) { PyObject *item = PySequence_GetItem(v, i-ilow); if (item == NULL) { return -1; } if (npyiter_seq_ass_item(self, i, item) < 0) { Py_DECREF(item); return -1; } Py_DECREF(item); } return 0; } static PyObject * npyiter_subscript(NewNpyArrayIterObject *self, PyObject *op) { if (self->iter == NULL || self->finished) { PyErr_SetString(PyExc_ValueError, "Iterator is past the end"); return NULL; } if (NpyIter_HasDelayedBufAlloc(self->iter)) { PyErr_SetString(PyExc_ValueError, "Iterator construction used delayed buffer allocation, " "and no reset has been done yet"); return NULL; } if (PyInt_Check(op) || PyLong_Check(op) || (PyIndex_Check(op) && !PySequence_Check(op))) { npy_intp i = PyArray_PyIntAsIntp(op); if (i == -1 && PyErr_Occurred()) { return NULL; } return npyiter_seq_item(self, i); } else if (PySlice_Check(op)) { Py_ssize_t istart = 0, iend = 0, istep = 0; if (PySlice_GetIndices((PySliceObject *)op, NpyIter_GetNOp(self->iter), &istart, &iend, &istep) < 0) { return NULL; } if (istep != 1) { PyErr_SetString(PyExc_ValueError, "Iterator slicing only supports a step of 1"); return NULL; } return npyiter_seq_slice(self, istart, iend); } PyErr_SetString(PyExc_TypeError, "invalid index type for iterator indexing"); return NULL; } static int npyiter_ass_subscript(NewNpyArrayIterObject *self, PyObject *op, PyObject *value) { if (value == NULL) { PyErr_SetString(PyExc_TypeError, "Cannot delete iterator elements"); return -1; } if (self->iter == NULL || self->finished) { PyErr_SetString(PyExc_ValueError, "Iterator is past the end"); return -1; } if (NpyIter_HasDelayedBufAlloc(self->iter)) { PyErr_SetString(PyExc_ValueError, "Iterator construction used delayed buffer allocation, " "and no reset has been done yet"); return -1; } if (PyInt_Check(op) || PyLong_Check(op) || (PyIndex_Check(op) && !PySequence_Check(op))) { npy_intp i = PyArray_PyIntAsIntp(op); if (i == -1 && PyErr_Occurred()) { return -1; } return npyiter_seq_ass_item(self, i, value); } else if (PySlice_Check(op)) { Py_ssize_t istart = 0, iend = 0, istep = 0; if (PySlice_GetIndices((PySliceObject *)op, NpyIter_GetNOp(self->iter), &istart, &iend, &istep) < 0) { return -1; } if (istep != 1) { PyErr_SetString(PyExc_ValueError, "Iterator slice assignment only supports a step of 1"); return -1; } return npyiter_seq_ass_slice(self, istart, iend, value); } PyErr_SetString(PyExc_TypeError, "invalid index type for iterator indexing"); return -1; } static PyMethodDef npyiter_methods[] = { {"reset", (PyCFunction)npyiter_reset, METH_NOARGS, NULL}, {"copy", (PyCFunction)npyiter_copy, METH_NOARGS, NULL}, {"__copy__", (PyCFunction)npyiter_copy, METH_NOARGS, NULL}, {"iternext", (PyCFunction)npyiter_iternext, METH_NOARGS, NULL}, {"remove_axis", (PyCFunction)npyiter_remove_axis, METH_VARARGS, NULL}, {"remove_multi_index", (PyCFunction)npyiter_remove_multi_index, METH_NOARGS, NULL}, {"enable_external_loop", (PyCFunction)npyiter_enable_external_loop, METH_NOARGS, NULL}, {"debug_print", (PyCFunction)npyiter_debug_print, METH_NOARGS, NULL}, {NULL, NULL, 0, NULL}, }; static PyMemberDef npyiter_members[] = { {NULL, 0, 0, 0, NULL}, }; static PyGetSetDef npyiter_getsets[] = { {"value", (getter)npyiter_value_get, NULL, NULL, NULL}, {"shape", (getter)npyiter_shape_get, NULL, NULL, NULL}, {"multi_index", (getter)npyiter_multi_index_get, (setter)npyiter_multi_index_set, NULL, NULL}, {"index", (getter)npyiter_index_get, (setter)npyiter_index_set, NULL, NULL}, {"iterindex", (getter)npyiter_iterindex_get, (setter)npyiter_iterindex_set, NULL, NULL}, {"iterrange", (getter)npyiter_iterrange_get, (setter)npyiter_iterrange_set, NULL, NULL}, {"operands", (getter)npyiter_operands_get, NULL, NULL, NULL}, {"itviews", (getter)npyiter_itviews_get, NULL, NULL, NULL}, {"has_delayed_bufalloc", (getter)npyiter_has_delayed_bufalloc_get, NULL, NULL, NULL}, {"iterationneedsapi", (getter)npyiter_iterationneedsapi_get, NULL, NULL, NULL}, {"has_multi_index", (getter)npyiter_has_multi_index_get, NULL, NULL, NULL}, {"has_index", (getter)npyiter_has_index_get, NULL, NULL, NULL}, {"dtypes", (getter)npyiter_dtypes_get, NULL, NULL, NULL}, {"ndim", (getter)npyiter_ndim_get, NULL, NULL, NULL}, {"nop", (getter)npyiter_nop_get, NULL, NULL, NULL}, {"itersize", (getter)npyiter_itersize_get, NULL, NULL, NULL}, {"finished", (getter)npyiter_finished_get, NULL, NULL, NULL}, {NULL, NULL, NULL, NULL, NULL} }; NPY_NO_EXPORT PySequenceMethods npyiter_as_sequence = { (lenfunc)npyiter_seq_length, /*sq_length*/ (binaryfunc)NULL, /*sq_concat*/ (ssizeargfunc)NULL, /*sq_repeat*/ (ssizeargfunc)npyiter_seq_item, /*sq_item*/ (ssizessizeargfunc)npyiter_seq_slice, /*sq_slice*/ (ssizeobjargproc)npyiter_seq_ass_item, /*sq_ass_item*/ (ssizessizeobjargproc)npyiter_seq_ass_slice,/*sq_ass_slice*/ (objobjproc)NULL, /*sq_contains */ (binaryfunc)NULL, /*sq_inplace_concat */ (ssizeargfunc)NULL, /*sq_inplace_repeat */ }; NPY_NO_EXPORT PyMappingMethods npyiter_as_mapping = { (lenfunc)npyiter_seq_length, /*mp_length*/ (binaryfunc)npyiter_subscript, /*mp_subscript*/ (objobjargproc)npyiter_ass_subscript, /*mp_ass_subscript*/ }; NPY_NO_EXPORT PyTypeObject NpyIter_Type = { #if defined(NPY_PY3K) PyVarObject_HEAD_INIT(NULL, 0) #else PyObject_HEAD_INIT(NULL) 0, /* ob_size */ #endif "numpy.nditer", /* tp_name */ sizeof(NewNpyArrayIterObject), /* tp_basicsize */ 0, /* tp_itemsize */ /* methods */ (destructor)npyiter_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ #if defined(NPY_PY3K) 0, /* tp_reserved */ #else 0, /* tp_compare */ #endif 0, /* tp_repr */ 0, /* tp_as_number */ &npyiter_as_sequence, /* tp_as_sequence */ &npyiter_as_mapping, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT, /* tp_flags */ 0, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ (iternextfunc)npyiter_next, /* tp_iternext */ npyiter_methods, /* tp_methods */ npyiter_members, /* tp_members */ npyiter_getsets, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc)npyiter_init, /* tp_init */ 0, /* tp_alloc */ npyiter_new, /* 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 */ 0, /* tp_version_tag */ }; numpy-1.8.2/numpy/core/src/multiarray/sequence.c0000664000175100017510000001053412370216243023063 0ustar vagrantvagrant00000000000000#define PY_SSIZE_T_CLEAN #include #include "structmember.h" #define NPY_NO_DEPRECATED_API NPY_API_VERSION #define _MULTIARRAYMODULE #include "numpy/arrayobject.h" #include "numpy/arrayscalars.h" #include "npy_config.h" #include "npy_pycompat.h" #include "common.h" #include "mapping.h" #include "sequence.h" static int array_any_nonzero(PyArrayObject *mp); /************************************************************************* **************** Implement Sequence Protocol ************************** *************************************************************************/ /* Some of this is repeated in the array_as_mapping protocol. But we fill it in here so that PySequence_XXXX calls work as expected */ static PyObject * array_slice(PyArrayObject *self, Py_ssize_t ilow, Py_ssize_t ihigh) { PyArrayObject *ret; PyArray_Descr *dtype; Py_ssize_t dim0; char *data; npy_intp shape[NPY_MAXDIMS]; if (PyArray_NDIM(self) == 0) { PyErr_SetString(PyExc_ValueError, "cannot slice a 0-d array"); return NULL; } dim0 = PyArray_DIM(self, 0); if (ilow < 0) { ilow = 0; } else if (ilow > dim0) { ilow = dim0; } if (ihigh < ilow) { ihigh = ilow; } else if (ihigh > dim0) { ihigh = dim0; } data = PyArray_DATA(self); if (ilow < ihigh) { data += ilow * PyArray_STRIDE(self, 0); } /* Same shape except dimension 0 */ shape[0] = ihigh - ilow; memcpy(shape+1, PyArray_DIMS(self) + 1, (PyArray_NDIM(self)-1)*sizeof(npy_intp)); dtype = PyArray_DESCR(self); Py_INCREF(dtype); ret = (PyArrayObject *)PyArray_NewFromDescr(Py_TYPE(self), dtype, PyArray_NDIM(self), shape, PyArray_STRIDES(self), data, PyArray_FLAGS(self), (PyObject *)self); if (ret == NULL) { return NULL; } Py_INCREF(self); if (PyArray_SetBaseObject(ret, (PyObject *)self) < 0) { Py_DECREF(ret); return NULL; } PyArray_UpdateFlags(ret, NPY_ARRAY_UPDATE_ALL); return (PyObject *)ret; } static int array_ass_slice(PyArrayObject *self, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v) { int ret; PyArrayObject *tmp; if (v == NULL) { PyErr_SetString(PyExc_ValueError, "cannot delete array elements"); return -1; } if (PyArray_FailUnlessWriteable(self, "assignment destination") < 0) { return -1; } tmp = (PyArrayObject *)array_slice(self, ilow, ihigh); if (tmp == NULL) { return -1; } ret = PyArray_CopyObject(tmp, v); Py_DECREF(tmp); return ret; } static int array_contains(PyArrayObject *self, PyObject *el) { /* equivalent to (self == el).any() */ PyObject *res; int ret; res = PyArray_EnsureAnyArray(PyObject_RichCompare((PyObject *)self, el, Py_EQ)); if (res == NULL) { return -1; } ret = array_any_nonzero((PyArrayObject *)res); Py_DECREF(res); return ret; } NPY_NO_EXPORT PySequenceMethods array_as_sequence = { (lenfunc)array_length, /*sq_length*/ (binaryfunc)NULL, /*sq_concat is handled by nb_add*/ (ssizeargfunc)NULL, (ssizeargfunc)array_item, (ssizessizeargfunc)array_slice, (ssizeobjargproc)array_ass_item, /*sq_ass_item*/ (ssizessizeobjargproc)array_ass_slice, /*sq_ass_slice*/ (objobjproc) array_contains, /*sq_contains */ (binaryfunc) NULL, /*sg_inplace_concat */ (ssizeargfunc)NULL, }; /****************** End of Sequence Protocol ****************************/ /* * Helpers */ /* Array evaluates as "TRUE" if any of the elements are non-zero*/ static int array_any_nonzero(PyArrayObject *arr) { npy_intp counter; PyArrayIterObject *it; npy_bool anyTRUE = NPY_FALSE; it = (PyArrayIterObject *)PyArray_IterNew((PyObject *)arr); if (it == NULL) { return anyTRUE; } counter = it->size; while (counter--) { if (PyArray_DESCR(arr)->f->nonzero(it->dataptr, arr)) { anyTRUE = NPY_TRUE; break; } PyArray_ITER_NEXT(it); } Py_DECREF(it); return anyTRUE; } numpy-1.8.2/numpy/core/src/multiarray/array_assign_scalar.c0000664000175100017510000002254312370216243025265 0ustar vagrantvagrant00000000000000/* * This file implements assignment from a scalar to an ndarray. * * Written by Mark Wiebe (mwwiebe@gmail.com) * Copyright (c) 2011 by Enthought, Inc. * * See LICENSE.txt for the license. */ #define PY_SSIZE_T_CLEAN #include #define NPY_NO_DEPRECATED_API NPY_API_VERSION #define _MULTIARRAYMODULE #include #include "npy_config.h" #include "npy_pycompat.h" #include "convert_datatype.h" #include "methods.h" #include "shape.h" #include "lowlevel_strided_loops.h" #include "array_assign.h" /* * Assigns the scalar value to every element of the destination raw array. * * Returns 0 on success, -1 on failure. */ NPY_NO_EXPORT int raw_array_assign_scalar(int ndim, npy_intp *shape, PyArray_Descr *dst_dtype, char *dst_data, npy_intp *dst_strides, PyArray_Descr *src_dtype, char *src_data) { int idim; npy_intp shape_it[NPY_MAXDIMS], dst_strides_it[NPY_MAXDIMS]; npy_intp coord[NPY_MAXDIMS]; PyArray_StridedUnaryOp *stransfer = NULL; NpyAuxData *transferdata = NULL; int aligned, needs_api = 0; npy_intp src_itemsize = src_dtype->elsize; NPY_BEGIN_THREADS_DEF; /* Check alignment */ aligned = raw_array_is_aligned(ndim, dst_data, dst_strides, dst_dtype->alignment); if (!npy_is_aligned(src_data, src_dtype->alignment)) { aligned = 0; } /* Use raw iteration with no heap allocation */ if (PyArray_PrepareOneRawArrayIter( ndim, shape, dst_data, dst_strides, &ndim, shape_it, &dst_data, dst_strides_it) < 0) { return -1; } /* Get the function to do the casting */ if (PyArray_GetDTypeTransferFunction(aligned, 0, dst_strides_it[0], src_dtype, dst_dtype, 0, &stransfer, &transferdata, &needs_api) != NPY_SUCCEED) { return -1; } if (!needs_api) { NPY_BEGIN_THREADS; } NPY_RAW_ITER_START(idim, ndim, coord, shape_it) { /* Process the innermost dimension */ stransfer(dst_data, dst_strides_it[0], src_data, 0, shape_it[0], src_itemsize, transferdata); } NPY_RAW_ITER_ONE_NEXT(idim, ndim, coord, shape_it, dst_data, dst_strides_it); if (!needs_api) { NPY_END_THREADS; } NPY_AUXDATA_FREE(transferdata); return (needs_api && PyErr_Occurred()) ? -1 : 0; } /* * Assigns the scalar value to every element of the destination raw array * where the 'wheremask' value is True. * * Returns 0 on success, -1 on failure. */ NPY_NO_EXPORT int raw_array_wheremasked_assign_scalar(int ndim, npy_intp *shape, PyArray_Descr *dst_dtype, char *dst_data, npy_intp *dst_strides, PyArray_Descr *src_dtype, char *src_data, PyArray_Descr *wheremask_dtype, char *wheremask_data, npy_intp *wheremask_strides) { int idim; npy_intp shape_it[NPY_MAXDIMS], dst_strides_it[NPY_MAXDIMS]; npy_intp wheremask_strides_it[NPY_MAXDIMS]; npy_intp coord[NPY_MAXDIMS]; PyArray_MaskedStridedUnaryOp *stransfer = NULL; NpyAuxData *transferdata = NULL; int aligned, needs_api = 0; npy_intp src_itemsize = src_dtype->elsize; NPY_BEGIN_THREADS_DEF; /* Check alignment */ aligned = raw_array_is_aligned(ndim, dst_data, dst_strides, dst_dtype->alignment); if (!npy_is_aligned(src_data, src_dtype->alignment)) { aligned = 0; } /* Use raw iteration with no heap allocation */ if (PyArray_PrepareTwoRawArrayIter( ndim, shape, dst_data, dst_strides, wheremask_data, wheremask_strides, &ndim, shape_it, &dst_data, dst_strides_it, &wheremask_data, wheremask_strides_it) < 0) { return -1; } /* Get the function to do the casting */ if (PyArray_GetMaskedDTypeTransferFunction(aligned, 0, dst_strides_it[0], wheremask_strides_it[0], src_dtype, dst_dtype, wheremask_dtype, 0, &stransfer, &transferdata, &needs_api) != NPY_SUCCEED) { return -1; } if (!needs_api) { NPY_BEGIN_THREADS; } NPY_RAW_ITER_START(idim, ndim, coord, shape_it) { /* Process the innermost dimension */ stransfer(dst_data, dst_strides_it[0], src_data, 0, (npy_bool *)wheremask_data, wheremask_strides_it[0], shape_it[0], src_itemsize, transferdata); } NPY_RAW_ITER_TWO_NEXT(idim, ndim, coord, shape_it, dst_data, dst_strides_it, wheremask_data, wheremask_strides_it); if (!needs_api) { NPY_END_THREADS; } NPY_AUXDATA_FREE(transferdata); return (needs_api && PyErr_Occurred()) ? -1 : 0; } /* * Assigns a scalar value specified by 'src_dtype' and 'src_data' * to elements of 'dst'. * * dst: The destination array. * src_dtype: The data type of the source scalar. * src_data: The memory element of the source scalar. * wheremask: If non-NULL, a boolean mask specifying where to copy. * casting: An exception is raised if the assignment violates this * casting rule. * * This function is implemented in array_assign_scalar.c. * * Returns 0 on success, -1 on failure. */ NPY_NO_EXPORT int PyArray_AssignRawScalar(PyArrayObject *dst, PyArray_Descr *src_dtype, char *src_data, PyArrayObject *wheremask, NPY_CASTING casting) { int allocated_src_data = 0; npy_longlong scalarbuffer[4]; if (PyArray_FailUnlessWriteable(dst, "assignment destination") < 0) { return -1; } /* Check the casting rule */ if (!can_cast_scalar_to(src_dtype, src_data, PyArray_DESCR(dst), casting)) { PyObject *errmsg; errmsg = PyUString_FromString("Cannot cast scalar from "); PyUString_ConcatAndDel(&errmsg, PyObject_Repr((PyObject *)src_dtype)); PyUString_ConcatAndDel(&errmsg, PyUString_FromString(" to ")); PyUString_ConcatAndDel(&errmsg, PyObject_Repr((PyObject *)PyArray_DESCR(dst))); PyUString_ConcatAndDel(&errmsg, PyUString_FromFormat(" according to the rule %s", npy_casting_to_string(casting))); PyErr_SetObject(PyExc_TypeError, errmsg); Py_DECREF(errmsg); return -1; } /* * Make a copy of the src data if it's a different dtype than 'dst' * or isn't aligned, and the destination we're copying to has * more than one element. To avoid having to manage object lifetimes, * we also skip this if 'dst' has an object dtype. */ if ((!PyArray_EquivTypes(PyArray_DESCR(dst), src_dtype) || !npy_is_aligned(src_data, src_dtype->alignment)) && PyArray_SIZE(dst) > 1 && !PyDataType_REFCHK(PyArray_DESCR(dst))) { char *tmp_src_data; /* * Use a static buffer to store the aligned/cast version, * or allocate some memory if more space is needed. */ if (sizeof(scalarbuffer) >= PyArray_DESCR(dst)->elsize) { tmp_src_data = (char *)&scalarbuffer[0]; } 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; } /* Replace src_data/src_dtype */ src_data = tmp_src_data; src_dtype = PyArray_DESCR(dst); } if (wheremask == NULL) { /* A straightforward value assignment */ /* Do the assignment with raw array iteration */ if (raw_array_assign_scalar(PyArray_NDIM(dst), PyArray_DIMS(dst), PyArray_DESCR(dst), PyArray_DATA(dst), PyArray_STRIDES(dst), src_dtype, src_data) < 0) { goto fail; } } else { npy_intp wheremask_strides[NPY_MAXDIMS]; /* Broadcast the wheremask to 'dst' for raw iteration */ if (broadcast_strides(PyArray_NDIM(dst), PyArray_DIMS(dst), PyArray_NDIM(wheremask), PyArray_DIMS(wheremask), PyArray_STRIDES(wheremask), "where mask", wheremask_strides) < 0) { goto fail; } /* Do the masked assignment with raw array iteration */ if (raw_array_wheremasked_assign_scalar( PyArray_NDIM(dst), PyArray_DIMS(dst), PyArray_DESCR(dst), PyArray_DATA(dst), PyArray_STRIDES(dst), src_dtype, src_data, PyArray_DESCR(wheremask), PyArray_DATA(wheremask), wheremask_strides) < 0) { goto fail; } } if (allocated_src_data) { PyArray_free(src_data); } return 0; fail: if (allocated_src_data) { PyArray_free(src_data); } return -1; } numpy-1.8.2/numpy/core/src/multiarray/ctors.c0000664000175100017510000033022712370216243022411 0ustar vagrantvagrant00000000000000#define PY_SSIZE_T_CLEAN #include #include "structmember.h" #define NPY_NO_DEPRECATED_API NPY_API_VERSION #define _MULTIARRAYMODULE #include "numpy/arrayobject.h" #include "numpy/arrayscalars.h" #include "numpy/npy_math.h" #include "npy_config.h" #include "npy_pycompat.h" #include "common.h" #include "ctors.h" #include "convert_datatype.h" #include "shape.h" #include "buffer.h" #include "numpymemoryview.h" #include "lowlevel_strided_loops.h" #include "methods.h" #include "_datetime.h" #include "datetime_strings.h" #include "array_assign.h" /* * Reading from a file or a string. * * As much as possible, we try to use the same code for both files and strings, * so the semantics for fromstring and fromfile are the same, especially with * regards to the handling of text representations. */ typedef int (*next_element)(void **, void *, PyArray_Descr *, void *); typedef int (*skip_separator)(void **, const char *, void *); static int fromstr_next_element(char **s, void *dptr, PyArray_Descr *dtype, const char *end) { int r = dtype->f->fromstr(*s, dptr, s, dtype); if (end != NULL && *s > end) { return -1; } return r; } static int fromfile_next_element(FILE **fp, void *dptr, PyArray_Descr *dtype, void *NPY_UNUSED(stream_data)) { /* the NULL argument is for backwards-compatibility */ return dtype->f->scanfunc(*fp, dptr, NULL, dtype); } /* * Remove multiple whitespace from the separator, and add a space to the * beginning and end. This simplifies the separator-skipping code below. */ static char * swab_separator(char *sep) { int skip_space = 0; char *s, *start; s = start = malloc(strlen(sep)+3); /* add space to front if there isn't one */ if (*sep != '\0' && !isspace(*sep)) { *s = ' '; s++; } while (*sep != '\0') { if (isspace(*sep)) { if (skip_space) { sep++; } else { *s = ' '; s++; sep++; skip_space = 1; } } else { *s = *sep; s++; sep++; skip_space = 0; } } /* add space to end if there isn't one */ if (s != start && s[-1] == ' ') { *s = ' '; s++; } *s = '\0'; return start; } /* * Assuming that the separator is the next bit in the string (file), skip it. * * Single spaces in the separator are matched to arbitrary-long sequences * of whitespace in the input. If the separator consists only of spaces, * it matches one or more whitespace characters. * * If we can't match the separator, return -2. * If we hit the end of the string (file), return -1. * Otherwise, return 0. */ static int fromstr_skip_separator(char **s, const char *sep, const char *end) { char *string = *s; int result = 0; while (1) { char c = *string; if (c == '\0' || (end != NULL && string >= end)) { result = -1; break; } else if (*sep == '\0') { if (string != *s) { /* matched separator */ result = 0; break; } else { /* separator was whitespace wildcard that didn't match */ result = -2; break; } } else if (*sep == ' ') { /* whitespace wildcard */ if (!isspace(c)) { sep++; continue; } } else if (*sep != c) { result = -2; break; } else { sep++; } string++; } *s = string; return result; } static int fromfile_skip_separator(FILE **fp, const char *sep, void *NPY_UNUSED(stream_data)) { int result = 0; const char *sep_start = sep; while (1) { int c = fgetc(*fp); if (c == EOF) { result = -1; break; } else if (*sep == '\0') { ungetc(c, *fp); if (sep != sep_start) { /* matched separator */ result = 0; break; } else { /* separator was whitespace wildcard that didn't match */ result = -2; break; } } else if (*sep == ' ') { /* whitespace wildcard */ if (!isspace(c)) { sep++; sep_start++; ungetc(c, *fp); } else if (sep == sep_start) { sep_start--; } } else if (*sep != c) { ungetc(c, *fp); result = -2; break; } else { sep++; } } return result; } /* * Change a sub-array field to the base descriptor * and update the dimensions and strides * appropriately. Dimensions and strides are added * to the end. * * Strides are only added if given (because data is given). */ static int _update_descr_and_dimensions(PyArray_Descr **des, npy_intp *newdims, npy_intp *newstrides, int oldnd) { PyArray_Descr *old; int newnd; int numnew; npy_intp *mydim; int i; int tuple; old = *des; *des = old->subarray->base; mydim = newdims + oldnd; tuple = PyTuple_Check(old->subarray->shape); if (tuple) { numnew = PyTuple_GET_SIZE(old->subarray->shape); } else { numnew = 1; } newnd = oldnd + numnew; if (newnd > NPY_MAXDIMS) { goto finish; } if (tuple) { for (i = 0; i < numnew; i++) { mydim[i] = (npy_intp) PyInt_AsLong( PyTuple_GET_ITEM(old->subarray->shape, i)); } } else { mydim[0] = (npy_intp) PyInt_AsLong(old->subarray->shape); } if (newstrides) { npy_intp tempsize; npy_intp *mystrides; mystrides = newstrides + oldnd; /* Make new strides -- alwasy C-contiguous */ tempsize = (*des)->elsize; for (i = numnew - 1; i >= 0; i--) { mystrides[i] = tempsize; tempsize *= mydim[i] ? mydim[i] : 1; } } finish: Py_INCREF(*des); Py_DECREF(old); return newnd; } NPY_NO_EXPORT void _unaligned_strided_byte_copy(char *dst, npy_intp outstrides, char *src, npy_intp instrides, npy_intp N, int elsize) { npy_intp i; char *tout = dst; char *tin = src; #define _COPY_N_SIZE(size) \ for(i=0; i 0; n--, a += stride) { npy_uint32 * a_ = (npy_uint32 *)a; *a_ = npy_bswap4(*a_); } } else { for (a = (char*)p; n > 0; n--, a += stride) { npy_bswap4_unaligned(a); } } break; case 8: 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_); } } else { for (a = (char*)p; n > 0; n--, a += stride) { npy_bswap8_unaligned(a); } } break; case 2: 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_); } } else { for (a = (char*)p; n > 0; n--, a += stride) { npy_bswap2_unaligned(a); } } break; default: m = size/2; for (a = (char *)p; n > 0; n--, a += stride - m) { b = a + (size - 1); for (j = 0; j < m; j++) { c=*a; *a++ = *b; *b-- = c; } } break; } } NPY_NO_EXPORT void byte_swap_vector(void *p, npy_intp n, int size) { _strided_byte_swap(p, (npy_intp) size, n, size); return; } /* If numitems > 1, then dst must be contiguous */ NPY_NO_EXPORT void copy_and_swap(void *dst, void *src, int itemsize, npy_intp numitems, npy_intp srcstrides, int swap) { if ((numitems == 1) || (itemsize == srcstrides)) { memcpy(dst, src, itemsize*numitems); } else { npy_intp i; char *s1 = (char *)src; char *d1 = (char *)dst; for (i = 0; i < numitems; i++) { memcpy(d1, s1, itemsize); d1 += itemsize; s1 += srcstrides; } } if (swap) { byte_swap_vector(dst, numitems, itemsize); } } /* adapted from Numarray */ static int setArrayFromSequence(PyArrayObject *a, PyObject *s, int dim, npy_intp offset) { Py_ssize_t i, slen; int res = -1; /* * This code is to ensure that the sequence access below will * return a lower-dimensional sequence. */ /* INCREF on entry DECREF on exit */ Py_INCREF(s); if (PyArray_Check(s) && !(PyArray_CheckExact(s))) { /* * FIXME: This could probably copy the entire subarray at once here using * a faster algorithm. Right now, just make sure a base-class array is * used so that the dimensionality reduction assumption is correct. */ /* This will DECREF(s) if replaced */ s = PyArray_EnsureArray(s); if (s == NULL) { goto fail; } } if (dim > PyArray_NDIM(a)) { PyErr_Format(PyExc_ValueError, "setArrayFromSequence: sequence/array dimensions mismatch."); goto fail; } slen = PySequence_Length(s); if (slen < 0) { goto fail; } /* * Either the dimensions match, or the sequence has length 1 and can * be broadcast to the destination. */ if (slen != PyArray_DIMS(a)[dim] && slen != 1) { PyErr_Format(PyExc_ValueError, "cannot copy sequence with size %d to array axis " "with dimension %d", (int)slen, (int)PyArray_DIMS(a)[dim]); goto fail; } /* Broadcast the one element from the sequence to all the outputs */ if (slen == 1) { PyObject *o; npy_intp alen = PyArray_DIM(a, dim); o = PySequence_GetItem(s, 0); if (o == NULL) { goto fail; } for (i = 0; i < alen; i++) { if ((PyArray_NDIM(a) - dim) > 1) { res = setArrayFromSequence(a, o, dim+1, offset); } else { res = PyArray_DESCR(a)->f->setitem(o, (PyArray_BYTES(a) + offset), a); } if (res < 0) { Py_DECREF(o); goto fail; } offset += PyArray_STRIDES(a)[dim]; } Py_DECREF(o); } /* Copy element by element */ else { for (i = 0; i < slen; i++) { PyObject *o = PySequence_GetItem(s, i); if (o == NULL) { goto fail; } if ((PyArray_NDIM(a) - dim) > 1) { res = setArrayFromSequence(a, o, dim+1, offset); } else { res = PyArray_DESCR(a)->f->setitem(o, (PyArray_BYTES(a) + offset), a); } Py_DECREF(o); if (res < 0) { goto fail; } offset += PyArray_STRIDES(a)[dim]; } } Py_DECREF(s); return 0; fail: Py_DECREF(s); return res; } NPY_NO_EXPORT int PyArray_AssignFromSequence(PyArrayObject *self, PyObject *v) { if (!PySequence_Check(v)) { PyErr_SetString(PyExc_ValueError, "assignment from non-sequence"); return -1; } if (PyArray_NDIM(self) == 0) { PyErr_SetString(PyExc_ValueError, "assignment to 0-d array"); return -1; } return setArrayFromSequence(self, v, 0, 0); } /* * The rest of this code is to build the right kind of array * from a python object. */ static int discover_itemsize(PyObject *s, int nd, int *itemsize, int string_type) { int n, r, i; if (PyArray_Check(s)) { *itemsize = PyArray_MAX(*itemsize, PyArray_ITEMSIZE((PyArrayObject *)s)); return 0; } if ((nd == 0) || PyString_Check(s) || #if defined(NPY_PY3K) PyMemoryView_Check(s) || #else PyBuffer_Check(s) || #endif PyUnicode_Check(s)) { /* If an object has no length, leave it be */ if (string_type && s != NULL && !PyString_Check(s) && !PyUnicode_Check(s)) { PyObject *s_string = NULL; if (string_type == NPY_STRING) { s_string = PyObject_Str(s); } else { #if defined(NPY_PY3K) s_string = PyObject_Str(s); #else s_string = PyObject_Unicode(s); #endif } if (s_string) { n = PyObject_Length(s_string); Py_DECREF(s_string); } else { n = -1; } } else { n = PyObject_Length(s); } if (n == -1) { PyErr_Clear(); } else { *itemsize = PyArray_MAX(*itemsize, n); } return 0; } n = PySequence_Length(s); for (i = 0; i < n; i++) { PyObject *e = PySequence_GetItem(s,i); if (e == NULL) { return -1; } r = discover_itemsize(e, nd - 1, itemsize, string_type); Py_DECREF(e); if (r == -1) { return -1; } } return 0; } /* * Take an arbitrary object and discover how many dimensions it * has, filling in the dimensions as we go. */ static int discover_dimensions(PyObject *obj, int *maxndim, npy_intp *d, int check_it, int stop_at_string, int stop_at_tuple, int *out_is_object) { PyObject *e; int r, n, i; Py_buffer buffer_view; if (*maxndim == 0) { return 0; } /* obj is an Array */ if (PyArray_Check(obj)) { PyArrayObject *arr = (PyArrayObject *)obj; if (PyArray_NDIM(arr) < *maxndim) { *maxndim = PyArray_NDIM(arr); } for (i=0; i<*maxndim; i++) { d[i] = PyArray_DIM(arr,i); } return 0; } /* obj is a Scalar */ if (PyArray_IsScalar(obj, Generic)) { *maxndim = 0; return 0; } /* obj is not a Sequence */ if (!PySequence_Check(obj) || #if defined(NPY_PY3K) /* FIXME: XXX -- what is the correct thing to do here? */ #else PyInstance_Check(obj) || #endif PySequence_Length(obj) < 0) { *maxndim = 0; PyErr_Clear(); return 0; } /* obj is a String */ if (PyString_Check(obj) || #if defined(NPY_PY3K) #else PyBuffer_Check(obj) || #endif PyUnicode_Check(obj)) { if (stop_at_string) { *maxndim = 0; } else { d[0] = PySequence_Length(obj); *maxndim = 1; } return 0; } /* obj is a Tuple, but tuples aren't expanded */ if (stop_at_tuple && PyTuple_Check(obj)) { *maxndim = 0; return 0; } /* obj is a PEP 3118 buffer */ /* PEP 3118 buffer interface */ if (PyObject_CheckBuffer(obj) == 1) { memset(&buffer_view, 0, sizeof(Py_buffer)); if (PyObject_GetBuffer(obj, &buffer_view, PyBUF_STRIDES) == 0 || PyObject_GetBuffer(obj, &buffer_view, PyBUF_ND) == 0) { int nd = buffer_view.ndim; if (nd < *maxndim) { *maxndim = nd; } for (i=0; i<*maxndim; i++) { d[i] = buffer_view.shape[i]; } PyBuffer_Release(&buffer_view); return 0; } else if (PyObject_GetBuffer(obj, &buffer_view, PyBUF_SIMPLE) == 0) { d[0] = buffer_view.len; *maxndim = 1; PyBuffer_Release(&buffer_view); return 0; } else { PyErr_Clear(); } } /* obj has the __array_struct__ interface */ e = PyArray_GetAttrString_SuppressException(obj, "__array_struct__"); if (e != NULL) { int nd = -1; if (NpyCapsule_Check(e)) { PyArrayInterface *inter; inter = (PyArrayInterface *)NpyCapsule_AsVoidPtr(e); if (inter->two == 2) { nd = inter->nd; if (nd >= 0) { if (nd < *maxndim) { *maxndim = nd; } for (i=0; i<*maxndim; i++) { d[i] = inter->shape[i]; } } } } Py_DECREF(e); if (nd >= 0) { return 0; } } /* obj has the __array_interface__ interface */ e = PyArray_GetAttrString_SuppressException(obj, "__array_interface__"); if (e != NULL) { int nd = -1; if (PyDict_Check(e)) { PyObject *new; new = PyDict_GetItemString(e, "shape"); if (new && PyTuple_Check(new)) { nd = PyTuple_GET_SIZE(new); if (nd < *maxndim) { *maxndim = nd; } for (i=0; i<*maxndim; i++) { d[i] = PyInt_AsSsize_t(PyTuple_GET_ITEM(new, i)); if (d[i] < 0) { PyErr_SetString(PyExc_RuntimeError, "Invalid shape in __array_interface__"); Py_DECREF(e); return -1; } } } } Py_DECREF(e); if (nd >= 0) { return 0; } } n = PySequence_Size(obj); if (n < 0) { return -1; } d[0] = n; /* 1-dimensional sequence */ if (n == 0 || *maxndim == 1) { *maxndim = 1; return 0; } else { npy_intp dtmp[NPY_MAXDIMS]; int j, maxndim_m1 = *maxndim - 1; 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) { return r; } /* For the dimension truncation check below */ *maxndim = maxndim_m1 + 1; for (i = 1; i < n; ++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) { return r; } /* Reduce max_ndim_m1 to just items which match */ for (j = 0; j < maxndim_m1; ++j) { if (dtmp[j] != d[j+1]) { maxndim_m1 = j; break; } } } /* * If the dimensions are truncated, need to produce * an object array. */ if (maxndim_m1 + 1 < *maxndim) { *out_is_object = 1; *maxndim = maxndim_m1 + 1; } } return 0; } /* * Generic new array creation routine. * Internal variant with calloc argument for PyArray_Zeros. * * steals a reference to descr (even on failure) */ static PyObject * PyArray_NewFromDescr_int(PyTypeObject *subtype, PyArray_Descr *descr, int nd, npy_intp *dims, npy_intp *strides, void *data, int flags, PyObject *obj, int zeroed) { PyArrayObject_fields *fa; int i; size_t sd; npy_intp largest; npy_intp size; if (descr->subarray) { PyObject *ret; npy_intp newdims[2*NPY_MAXDIMS]; npy_intp *newstrides = NULL; memcpy(newdims, dims, nd*sizeof(npy_intp)); if (strides) { newstrides = newdims + NPY_MAXDIMS; memcpy(newstrides, strides, nd*sizeof(npy_intp)); } nd =_update_descr_and_dimensions(&descr, newdims, newstrides, nd); ret = PyArray_NewFromDescr_int(subtype, descr, nd, newdims, newstrides, data, flags, obj, zeroed); return ret; } if ((unsigned int)nd > (unsigned int)NPY_MAXDIMS) { PyErr_Format(PyExc_ValueError, "number of dimensions must be within [0, %d]", NPY_MAXDIMS); Py_DECREF(descr); return NULL; } /* Check dimensions */ size = 1; sd = (size_t) descr->elsize; if (sd == 0) { if (!PyDataType_ISSTRING(descr)) { PyErr_SetString(PyExc_TypeError, "Empty data-type"); Py_DECREF(descr); return NULL; } PyArray_DESCR_REPLACE(descr); if (descr == NULL) { return NULL; } if (descr->type_num == NPY_STRING) { sd = descr->elsize = 1; } else { sd = descr->elsize = sizeof(npy_ucs4); } } largest = NPY_MAX_INTP / sd; for (i = 0; i < nd; i++) { npy_intp dim = dims[i]; if (dim == 0) { /* * Compare to PyArray_OverflowMultiplyList that * returns 0 in this case. */ continue; } if (dim < 0) { PyErr_SetString(PyExc_ValueError, "negative dimensions " \ "are not allowed"); Py_DECREF(descr); return NULL; } /* * Care needs to be taken to avoid integer overflow when * multiplying the dimensions together to get the total size of the * array. Hence before each multiplication we first check that the * product will not exceed the maximum allowable size. */ if (dim > largest) { PyErr_SetString(PyExc_ValueError, "array is too big."); Py_DECREF(descr); return NULL; } size *= dim; largest /= dim; } fa = (PyArrayObject_fields *) subtype->tp_alloc(subtype, 0); if (fa == NULL) { Py_DECREF(descr); return NULL; } fa->nd = nd; fa->dimensions = NULL; fa->data = NULL; if (data == NULL) { fa->flags = NPY_ARRAY_DEFAULT; if (flags) { fa->flags |= NPY_ARRAY_F_CONTIGUOUS; if (nd > 1) { fa->flags &= ~NPY_ARRAY_C_CONTIGUOUS; } flags = NPY_ARRAY_F_CONTIGUOUS; } } else { fa->flags = (flags & ~NPY_ARRAY_UPDATEIFCOPY); } fa->descr = descr; fa->base = (PyObject *)NULL; fa->weakreflist = (PyObject *)NULL; if (nd > 0) { fa->dimensions = PyDimMem_NEW(3*nd); if (fa->dimensions == NULL) { PyErr_NoMemory(); goto fail; } fa->strides = fa->dimensions + nd; memcpy(fa->dimensions, dims, sizeof(npy_intp)*nd); if (strides == NULL) { /* fill it in */ sd = _array_fill_strides(fa->strides, dims, nd, sd, flags, &(fa->flags)); } else { /* * we allow strides even when we create * the memory, but be careful with this... */ memcpy(fa->strides, strides, sizeof(npy_intp)*nd); sd *= size; } } else { fa->dimensions = fa->strides = NULL; fa->flags |= NPY_ARRAY_F_CONTIGUOUS; } if (data == NULL) { /* * Allocate something even for zero-space arrays * e.g. shape=(0,) -- otherwise buffer exposure * (a.data) doesn't work as it should. */ if (sd == 0) { sd = descr->elsize; } /* * It is bad to have unitialized OBJECT pointers * which could also be sub-fields of a VOID array */ if (zeroed || PyDataType_FLAGCHK(descr, NPY_NEEDS_INIT)) { data = PyDataMem_NEW_ZEROED(sd, 1); } else { data = PyDataMem_NEW(sd); } if (data == NULL) { PyErr_NoMemory(); goto fail; } fa->flags |= NPY_ARRAY_OWNDATA; } else { /* * If data is passed in, this object won't own it by default. * Caller must arrange for this to be reset if truly desired */ fa->flags &= ~NPY_ARRAY_OWNDATA; } fa->data = data; /* * If the strides were provided to the function, need to * update the flags to get the right CONTIGUOUS, ALIGN properties */ if (strides != NULL) { PyArray_UpdateFlags((PyArrayObject *)fa, NPY_ARRAY_UPDATE_ALL); } /* * call the __array_finalize__ * method if a subtype. * If obj is NULL, then call method with Py_None */ if ((subtype != &PyArray_Type)) { PyObject *res, *func, *args; func = PyObject_GetAttrString((PyObject *)fa, "__array_finalize__"); if (func && func != Py_None) { if (NpyCapsule_Check(func)) { /* A C-function is stored here */ PyArray_FinalizeFunc *cfunc; cfunc = NpyCapsule_AsVoidPtr(func); Py_DECREF(func); if (cfunc((PyArrayObject *)fa, obj) < 0) { goto fail; } } else { args = PyTuple_New(1); if (obj == NULL) { obj=Py_None; } Py_INCREF(obj); PyTuple_SET_ITEM(args, 0, obj); res = PyObject_Call(func, args, NULL); Py_DECREF(args); Py_DECREF(func); if (res == NULL) { goto fail; } else { Py_DECREF(res); } } } else Py_XDECREF(func); } return (PyObject *)fa; fail: Py_DECREF(fa); return NULL; } /*NUMPY_API * Generic new array creation routine. * * steals a reference to descr (even on failure) */ NPY_NO_EXPORT PyObject * PyArray_NewFromDescr(PyTypeObject *subtype, PyArray_Descr *descr, int nd, npy_intp *dims, npy_intp *strides, void *data, int flags, PyObject *obj) { return PyArray_NewFromDescr_int(subtype, descr, nd, dims, strides, data, flags, obj, 0); } /*NUMPY_API * Creates a new array with the same shape as the provided one, * with possible memory layout order and data type changes. * * prototype - The array the new one should be like. * order - NPY_CORDER - C-contiguous result. * NPY_FORTRANORDER - Fortran-contiguous result. * NPY_ANYORDER - Fortran if prototype is Fortran, C otherwise. * NPY_KEEPORDER - Keeps the axis ordering of prototype. * dtype - If not NULL, overrides the data type of the result. * subok - If 1, use the prototype's array subtype, otherwise * always create a base-class array. * * NOTE: If dtype is not NULL, steals the dtype reference. */ NPY_NO_EXPORT PyObject * PyArray_NewLikeArray(PyArrayObject *prototype, NPY_ORDER order, PyArray_Descr *dtype, int subok) { PyObject *ret = NULL; int ndim = PyArray_NDIM(prototype); /* If no override data type, use the one from the prototype */ if (dtype == NULL) { dtype = PyArray_DESCR(prototype); Py_INCREF(dtype); } /* Handle ANYORDER and simple KEEPORDER cases */ switch (order) { case NPY_ANYORDER: order = PyArray_ISFORTRAN(prototype) ? NPY_FORTRANORDER : NPY_CORDER; break; case NPY_KEEPORDER: if (PyArray_IS_C_CONTIGUOUS(prototype) || ndim <= 1) { order = NPY_CORDER; break; } else if (PyArray_IS_F_CONTIGUOUS(prototype)) { order = NPY_FORTRANORDER; break; } break; default: break; } /* If it's not KEEPORDER, this is simple */ if (order != NPY_KEEPORDER) { ret = PyArray_NewFromDescr(subok ? Py_TYPE(prototype) : &PyArray_Type, dtype, ndim, PyArray_DIMS(prototype), NULL, NULL, order, subok ? (PyObject *)prototype : NULL); } /* KEEPORDER needs some analysis of the strides */ else { npy_intp strides[NPY_MAXDIMS], stride; npy_intp *shape = PyArray_DIMS(prototype); npy_stride_sort_item strideperm[NPY_MAXDIMS]; int idim; PyArray_CreateSortedStridePerm(PyArray_NDIM(prototype), PyArray_STRIDES(prototype), strideperm); /* Build the new strides */ stride = dtype->elsize; for (idim = ndim-1; idim >= 0; --idim) { npy_intp i_perm = strideperm[idim].perm; strides[i_perm] = stride; stride *= shape[i_perm]; } /* Finally, allocate the array */ ret = PyArray_NewFromDescr(subok ? Py_TYPE(prototype) : &PyArray_Type, dtype, ndim, shape, strides, NULL, 0, subok ? (PyObject *)prototype : NULL); } return ret; } /*NUMPY_API * Generic new array creation routine. */ NPY_NO_EXPORT PyObject * PyArray_New(PyTypeObject *subtype, int nd, npy_intp *dims, int type_num, npy_intp *strides, void *data, int itemsize, int flags, PyObject *obj) { PyArray_Descr *descr; PyObject *new; descr = PyArray_DescrFromType(type_num); if (descr == NULL) { return NULL; } if (descr->elsize == 0) { if (itemsize < 1) { PyErr_SetString(PyExc_ValueError, "data type must provide an itemsize"); Py_DECREF(descr); return NULL; } PyArray_DESCR_REPLACE(descr); descr->elsize = itemsize; } new = PyArray_NewFromDescr(subtype, descr, nd, dims, strides, data, flags, obj); return new; } NPY_NO_EXPORT int _array_from_buffer_3118(PyObject *obj, PyObject **out) { /* PEP 3118 */ PyObject *memoryview; Py_buffer *view; PyArray_Descr *descr = NULL; PyObject *r; int nd, flags, k; Py_ssize_t d; npy_intp shape[NPY_MAXDIMS], strides[NPY_MAXDIMS]; memoryview = PyMemoryView_FromObject(obj); if (memoryview == NULL) { PyErr_Clear(); return -1; } view = PyMemoryView_GET_BUFFER(memoryview); if (view->format != NULL) { descr = _descriptor_from_pep3118_format(view->format); if (descr == NULL) { PyObject *msg; msg = PyBytes_FromFormat("Invalid PEP 3118 format string: '%s'", view->format); PyErr_WarnEx(PyExc_RuntimeWarning, PyBytes_AS_STRING(msg), 0); Py_DECREF(msg); goto fail; } /* Sanity check */ if (descr->elsize != view->itemsize) { PyErr_WarnEx(PyExc_RuntimeWarning, "Item size computed from the PEP 3118 buffer format " "string does not match the actual item size.", 0); goto fail; } } else { descr = PyArray_DescrNewFromType(NPY_STRING); descr->elsize = view->itemsize; } if (view->shape != NULL) { nd = view->ndim; if (nd >= NPY_MAXDIMS || nd < 0) { goto fail; } for (k = 0; k < nd; ++k) { if (k >= NPY_MAXDIMS) { goto fail; } shape[k] = view->shape[k]; } if (view->strides != NULL) { for (k = 0; k < nd; ++k) { strides[k] = view->strides[k]; } } else { d = view->len; for (k = 0; k < nd; ++k) { if (view->shape[k] != 0) { d /= view->shape[k]; } strides[k] = d; } } } else { nd = 1; shape[0] = view->len / view->itemsize; strides[0] = view->itemsize; } flags = NPY_ARRAY_BEHAVED & (view->readonly ? ~NPY_ARRAY_WRITEABLE : ~0); r = PyArray_NewFromDescr(&PyArray_Type, descr, nd, shape, strides, view->buf, flags, NULL); 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); *out = r; return 0; fail: Py_XDECREF(descr); Py_DECREF(memoryview); return -1; } /*NUMPY_API * Retrieves the array parameters for viewing/converting an arbitrary * PyObject* to a NumPy array. This allows the "innate type and shape" * of Python list-of-lists to be discovered without * actually converting to an array. * * In some cases, such as structured arrays and the __array__ interface, * a data type needs to be used to make sense of the object. When * this is needed, provide a Descr for 'requested_dtype', otherwise * provide NULL. This reference is not stolen. Also, if the requested * dtype doesn't modify the interpretation of the input, out_dtype will * still get the "innate" dtype of the object, not the dtype passed * in 'requested_dtype'. * * If writing to the value in 'op' is desired, set the boolean * 'writeable' to 1. This raises an error when 'op' is a scalar, list * of lists, or other non-writeable 'op'. * * Result: When success (0 return value) is returned, either out_arr * is filled with a non-NULL PyArrayObject and * the rest of the parameters are untouched, or out_arr is * filled with NULL, and the rest of the parameters are * filled. * * Typical usage: * * PyArrayObject *arr = NULL; * PyArray_Descr *dtype = NULL; * int ndim = 0; * npy_intp dims[NPY_MAXDIMS]; * * if (PyArray_GetArrayParamsFromObject(op, NULL, 1, &dtype, * &ndim, &dims, &arr, NULL) < 0) { * return NULL; * } * if (arr == NULL) { * ... validate/change dtype, validate flags, ndim, etc ... * // Could make custom strides here too * arr = PyArray_NewFromDescr(&PyArray_Type, dtype, ndim, * dims, NULL, * is_f_order ? NPY_ARRAY_F_CONTIGUOUS : 0, * NULL); * if (arr == NULL) { * return NULL; * } * if (PyArray_CopyObject(arr, op) < 0) { * Py_DECREF(arr); * return NULL; * } * } * else { * ... in this case the other parameters weren't filled, just * validate and possibly copy arr itself ... * } * ... use arr ... */ NPY_NO_EXPORT int PyArray_GetArrayParamsFromObject(PyObject *op, PyArray_Descr *requested_dtype, npy_bool writeable, PyArray_Descr **out_dtype, int *out_ndim, npy_intp *out_dims, PyArrayObject **out_arr, PyObject *context) { PyObject *tmp; /* If op is an array */ if (PyArray_Check(op)) { if (writeable && PyArray_FailUnlessWriteable((PyArrayObject *)op, "array") < 0) { return -1; } Py_INCREF(op); *out_arr = (PyArrayObject *)op; return 0; } /* If op is a NumPy scalar */ if (PyArray_IsScalar(op, Generic)) { if (writeable) { PyErr_SetString(PyExc_RuntimeError, "cannot write to scalar"); return -1; } *out_dtype = PyArray_DescrFromScalar(op); if (*out_dtype == NULL) { return -1; } *out_ndim = 0; *out_arr = NULL; return 0; } /* If op is a Python scalar */ *out_dtype = _array_find_python_scalar_type(op); if (*out_dtype != NULL) { if (writeable) { PyErr_SetString(PyExc_RuntimeError, "cannot write to scalar"); Py_DECREF(*out_dtype); return -1; } *out_ndim = 0; *out_arr = NULL; return 0; } /* If op supports the PEP 3118 buffer interface */ if (!PyBytes_Check(op) && !PyUnicode_Check(op) && _array_from_buffer_3118(op, (PyObject **)out_arr) == 0) { if (writeable && PyArray_FailUnlessWriteable(*out_arr, "PEP 3118 buffer") < 0) { Py_DECREF(*out_arr); return -1; } return (*out_arr) == NULL ? -1 : 0; } /* If op supports the __array_struct__ or __array_interface__ interface */ tmp = PyArray_FromStructInterface(op); if (tmp == NULL) { return -1; } if (tmp == Py_NotImplemented) { tmp = PyArray_FromInterface(op); if (tmp == NULL) { return -1; } } if (tmp != Py_NotImplemented) { if (writeable && PyArray_FailUnlessWriteable((PyArrayObject *)tmp, "array interface object") < 0) { Py_DECREF(tmp); return -1; } *out_arr = (PyArrayObject *)tmp; return (*out_arr) == NULL ? -1 : 0; } /* * If op supplies the __array__ function. * The documentation says this should produce a copy, so * we skip this method if writeable is true, because the intent * of writeable is to modify the operand. * XXX: If the implementation is wrong, and/or if actual * usage requires this behave differently, * this should be changed! */ if (!writeable) { tmp = PyArray_FromArrayAttr(op, requested_dtype, context); if (tmp != Py_NotImplemented) { if (writeable && PyArray_FailUnlessWriteable((PyArrayObject *)tmp, "array interface object") < 0) { Py_DECREF(tmp); return -1; } *out_arr = (PyArrayObject *)tmp; return (*out_arr) == NULL ? -1 : 0; } } /* Try to treat op as a list of lists */ if (!writeable && PySequence_Check(op)) { int check_it, stop_at_string, stop_at_tuple, is_object; int type_num, type; /* * Determine the type, using the requested data type if * it will affect how the array is retrieved */ if (requested_dtype != NULL && ( requested_dtype->type_num == NPY_STRING || requested_dtype->type_num == NPY_UNICODE || (requested_dtype->type_num == NPY_VOID && (requested_dtype->names || requested_dtype->subarray)) || requested_dtype->type == NPY_CHARLTR || requested_dtype->type_num == NPY_OBJECT)) { Py_INCREF(requested_dtype); *out_dtype = requested_dtype; } else { *out_dtype = NULL; if (PyArray_DTypeFromObject(op, NPY_MAXDIMS, out_dtype) < 0) { if (PyErr_ExceptionMatches(PyExc_MemoryError)) { return -1; } /* Return NPY_OBJECT for most exceptions */ else { PyErr_Clear(); *out_dtype = PyArray_DescrFromType(NPY_OBJECT); if (*out_dtype == NULL) { return -1; } } } if (*out_dtype == NULL) { *out_dtype = PyArray_DescrFromType(NPY_DEFAULT_TYPE); if (*out_dtype == NULL) { return -1; } } } type_num = (*out_dtype)->type_num; type = (*out_dtype)->type; check_it = (type != NPY_CHARLTR); stop_at_string = (type_num != NPY_STRING) || (type == NPY_STRINGLTR); stop_at_tuple = (type_num == NPY_VOID && ((*out_dtype)->names || (*out_dtype)->subarray)); *out_ndim = NPY_MAXDIMS; is_object = 0; if (discover_dimensions(op, out_ndim, out_dims, check_it, stop_at_string, stop_at_tuple, &is_object) < 0) { Py_DECREF(*out_dtype); if (PyErr_Occurred()) { return -1; } *out_dtype = PyArray_DescrFromType(NPY_OBJECT); if (*out_dtype == NULL) { return -1; } *out_ndim = 0; *out_arr = NULL; return 0; } /* If object arrays are forced */ if (is_object) { Py_DECREF(*out_dtype); *out_dtype = PyArray_DescrFromType(NPY_OBJECT); if (*out_dtype == NULL) { return -1; } } if ((*out_dtype)->type == NPY_CHARLTR && (*out_ndim) > 0 && out_dims[(*out_ndim) - 1] == 1) { (*out_ndim) -= 1; } /* If the type is flexible, determine its size */ if ((*out_dtype)->elsize == 0 && PyTypeNum_ISEXTENDED((*out_dtype)->type_num)) { int itemsize = 0; int string_type = 0; if ((*out_dtype)->type_num == NPY_STRING || (*out_dtype)->type_num == NPY_UNICODE) { string_type = (*out_dtype)->type_num; } if (discover_itemsize(op, *out_ndim, &itemsize, string_type) < 0) { Py_DECREF(*out_dtype); if (PyErr_Occurred() && PyErr_GivenExceptionMatches(PyErr_Occurred(), PyExc_MemoryError)) { return -1; } /* Say it's an OBJECT scalar if there's an error */ PyErr_Clear(); *out_dtype = PyArray_DescrFromType(NPY_OBJECT); *out_ndim = 0; *out_arr = NULL; return 0; } if ((*out_dtype)->type_num == NPY_UNICODE) { itemsize *= 4; } if (itemsize != (*out_dtype)->elsize) { PyArray_DESCR_REPLACE(*out_dtype); (*out_dtype)->elsize = itemsize; } } *out_arr = NULL; return 0; } /* Anything can be viewed as an object, unless it needs to be writeable */ if (!writeable) { *out_dtype = PyArray_DescrFromType(NPY_OBJECT); if (*out_dtype == NULL) { return -1; } *out_ndim = 0; *out_arr = NULL; return 0; } PyErr_SetString(PyExc_RuntimeError, "object cannot be viewed as a writeable numpy array"); return -1; } /*NUMPY_API * Does not check for NPY_ARRAY_ENSURECOPY and NPY_ARRAY_NOTSWAPPED in flags * Steals a reference to newtype --- which can be NULL */ NPY_NO_EXPORT PyObject * PyArray_FromAny(PyObject *op, PyArray_Descr *newtype, int min_depth, int max_depth, int flags, PyObject *context) { /* * This is the main code to make a NumPy array from a Python * Object. It is called from many different places. */ PyArrayObject *arr = NULL, *ret; PyArray_Descr *dtype = NULL; int ndim = 0; npy_intp dims[NPY_MAXDIMS]; /* Get either the array or its parameters if it isn't an array */ if (PyArray_GetArrayParamsFromObject(op, newtype, 0, &dtype, &ndim, dims, &arr, context) < 0) { Py_XDECREF(newtype); return NULL; } /* If the requested dtype is flexible, adapt it */ if (newtype != NULL) { PyArray_AdaptFlexibleDType(op, (dtype == NULL) ? PyArray_DESCR(arr) : dtype, &newtype); } /* If we got dimensions and dtype instead of an array */ if (arr == NULL) { if (flags & NPY_ARRAY_UPDATEIFCOPY) { Py_XDECREF(newtype); PyErr_SetString(PyExc_TypeError, "UPDATEIFCOPY used for non-array input."); return NULL; } else if (min_depth != 0 && ndim < min_depth) { Py_DECREF(dtype); Py_XDECREF(newtype); PyErr_SetString(PyExc_ValueError, "object of too small depth for desired array"); ret = NULL; } else if (max_depth != 0 && ndim > max_depth) { Py_DECREF(dtype); Py_XDECREF(newtype); PyErr_SetString(PyExc_ValueError, "object too deep for desired array"); ret = NULL; } else if (ndim == 0 && PyArray_IsScalar(op, Generic)) { ret = (PyArrayObject *)PyArray_FromScalar(op, newtype); Py_DECREF(dtype); } else { if (newtype == NULL) { newtype = dtype; } else { /* * TODO: would be nice to do this too, but it's * a behavior change. It's also a bit tricky * for downcasting to small integer and float * types, and might be better to modify * PyArray_AssignFromSequence and descr->f->setitem * to have a 'casting' parameter and * to check each value with scalar rules like * in PyArray_MinScalarType. */ /* if (!(flags&NPY_ARRAY_FORCECAST) && ndim > 0 && !PyArray_CanCastTo(dtype, newtype)) { Py_DECREF(dtype); Py_XDECREF(newtype); PyErr_SetString(PyExc_TypeError, "object cannot be safely cast to array " "of required type"); return NULL; } */ Py_DECREF(dtype); } /* Create an array and copy the data */ ret = (PyArrayObject *)PyArray_NewFromDescr(&PyArray_Type, newtype, ndim, dims, NULL, NULL, flags&NPY_ARRAY_F_CONTIGUOUS, NULL); if (ret == NULL) { return NULL; } if (ndim > 0) { if (PyArray_AssignFromSequence(ret, op) < 0) { Py_DECREF(ret); ret = NULL; } } else { if (PyArray_DESCR(ret)->f->setitem(op, PyArray_DATA(ret), ret) < 0) { Py_DECREF(ret); ret = NULL; } } } } else { if (min_depth != 0 && PyArray_NDIM(arr) < min_depth) { PyErr_SetString(PyExc_ValueError, "object of too small depth for desired array"); Py_DECREF(arr); ret = NULL; } else if (max_depth != 0 && PyArray_NDIM(arr) > max_depth) { PyErr_SetString(PyExc_ValueError, "object too deep for desired array"); Py_DECREF(arr); ret = NULL; } else { ret = (PyArrayObject *)PyArray_FromArray(arr, newtype, flags); Py_DECREF(arr); } } return (PyObject *)ret; } /* * flags is any of * NPY_ARRAY_C_CONTIGUOUS (formerly CONTIGUOUS), * NPY_ARRAY_F_CONTIGUOUS (formerly FORTRAN), * NPY_ARRAY_ALIGNED, * NPY_ARRAY_WRITEABLE, * NPY_ARRAY_NOTSWAPPED, * NPY_ARRAY_ENSURECOPY, * NPY_ARRAY_UPDATEIFCOPY, * NPY_ARRAY_FORCECAST, * NPY_ARRAY_ENSUREARRAY, * NPY_ARRAY_ELEMENTSTRIDES * * or'd (|) together * * Any of these flags present means that the returned array should * guarantee that aspect of the array. Otherwise the returned array * won't guarantee it -- it will depend on the object as to whether or * not it has such features. * * Note that NPY_ARRAY_ENSURECOPY is enough * to guarantee NPY_ARRAY_C_CONTIGUOUS, NPY_ARRAY_ALIGNED and * NPY_ARRAY_WRITEABLE and therefore it is redundant to include * those as well. * * NPY_ARRAY_BEHAVED == NPY_ARRAY_ALIGNED | NPY_ARRAY_WRITEABLE * NPY_ARRAY_CARRAY = NPY_ARRAY_C_CONTIGUOUS | NPY_ARRAY_BEHAVED * NPY_ARRAY_FARRAY = NPY_ARRAY_F_CONTIGUOUS | NPY_ARRAY_BEHAVED * * NPY_ARRAY_F_CONTIGUOUS can be set in the FLAGS to request a FORTRAN array. * Fortran arrays are always behaved (aligned, * notswapped, and writeable) and not (C) CONTIGUOUS (if > 1d). * * NPY_ARRAY_UPDATEIFCOPY flag sets this flag in the returned array if a copy * is made and the base argument points to the (possibly) misbehaved array. * When the new array is deallocated, the original array held in base * is updated with the contents of the new array. * * NPY_ARRAY_FORCECAST will cause a cast to occur regardless of whether or not * it is safe. */ /*NUMPY_API * steals a reference to descr -- accepts NULL */ NPY_NO_EXPORT PyObject * PyArray_CheckFromAny(PyObject *op, PyArray_Descr *descr, int min_depth, int max_depth, int requires, PyObject *context) { PyObject *obj; if (requires & NPY_ARRAY_NOTSWAPPED) { if (!descr && PyArray_Check(op) && !PyArray_ISNBO(PyArray_DESCR((PyArrayObject *)op)->byteorder)) { descr = PyArray_DescrNew(PyArray_DESCR((PyArrayObject *)op)); } else if (descr && !PyArray_ISNBO(descr->byteorder)) { PyArray_DESCR_REPLACE(descr); } if (descr && descr->byteorder != NPY_IGNORE) { descr->byteorder = NPY_NATIVE; } } obj = PyArray_FromAny(op, descr, min_depth, max_depth, requires, context); if (obj == NULL) { return NULL; } if ((requires & NPY_ARRAY_ELEMENTSTRIDES) && !PyArray_ElementStrides(obj)) { PyObject *ret; ret = PyArray_NewCopy((PyArrayObject *)obj, NPY_ANYORDER); Py_DECREF(obj); obj = ret; } return obj; } /*NUMPY_API * steals reference to newtype --- acc. NULL */ NPY_NO_EXPORT PyObject * PyArray_FromArray(PyArrayObject *arr, PyArray_Descr *newtype, int flags) { PyArrayObject *ret = NULL; int itemsize; int copy = 0; int arrflags; PyArray_Descr *oldtype; NPY_CASTING casting = NPY_SAFE_CASTING; oldtype = PyArray_DESCR(arr); if (newtype == NULL) { /* * Check if object is of array with Null newtype. * If so return it directly instead of checking for casting. */ if (flags == 0) { Py_INCREF(arr); return (PyObject *)arr; } newtype = oldtype; Py_INCREF(oldtype); } itemsize = newtype->elsize; if (itemsize == 0) { PyArray_DESCR_REPLACE(newtype); if (newtype == NULL) { return NULL; } newtype->elsize = oldtype->elsize; itemsize = newtype->elsize; } /* If the casting if forced, use the 'unsafe' casting rule */ if (flags & NPY_ARRAY_FORCECAST) { casting = NPY_UNSAFE_CASTING; } /* Raise an error if the casting rule isn't followed */ if (!PyArray_CanCastArrayTo(arr, newtype, casting)) { PyObject *errmsg; errmsg = PyUString_FromString("Cannot cast array data from "); PyUString_ConcatAndDel(&errmsg, PyObject_Repr((PyObject *)PyArray_DESCR(arr))); PyUString_ConcatAndDel(&errmsg, PyUString_FromString(" to ")); PyUString_ConcatAndDel(&errmsg, PyObject_Repr((PyObject *)newtype)); PyUString_ConcatAndDel(&errmsg, PyUString_FromFormat(" according to the rule %s", npy_casting_to_string(casting))); PyErr_SetObject(PyExc_TypeError, errmsg); Py_DECREF(errmsg); Py_DECREF(newtype); return NULL; } arrflags = PyArray_FLAGS(arr); /* If a guaranteed copy was requested */ copy = (flags & NPY_ARRAY_ENSURECOPY) || /* If C contiguous was requested, and arr is not */ ((flags & NPY_ARRAY_C_CONTIGUOUS) && (!(arrflags & NPY_ARRAY_C_CONTIGUOUS))) || /* If an aligned array was requested, and arr is not */ ((flags & NPY_ARRAY_ALIGNED) && (!(arrflags & NPY_ARRAY_ALIGNED))) || /* If a Fortran contiguous array was requested, and arr is not */ ((flags & NPY_ARRAY_F_CONTIGUOUS) && (!(arrflags & NPY_ARRAY_F_CONTIGUOUS))) || /* If a writeable array was requested, and arr is not */ ((flags & NPY_ARRAY_WRITEABLE) && (!(arrflags & NPY_ARRAY_WRITEABLE))) || !PyArray_EquivTypes(oldtype, newtype); if (copy) { NPY_ORDER order = NPY_KEEPORDER; int subok = 1; /* Set the order for the copy being made based on the flags */ if (flags & NPY_ARRAY_F_CONTIGUOUS) { order = NPY_FORTRANORDER; } else if (flags & NPY_ARRAY_C_CONTIGUOUS) { order = NPY_CORDER; } if ((flags & NPY_ARRAY_ENSUREARRAY)) { subok = 0; } ret = (PyArrayObject *)PyArray_NewLikeArray(arr, order, newtype, subok); if (ret == NULL) { return NULL; } if (PyArray_CopyInto(ret, arr) < 0) { Py_DECREF(ret); return NULL; } if (flags & NPY_ARRAY_UPDATEIFCOPY) { Py_INCREF(arr); if (PyArray_SetUpdateIfCopyBase(ret, arr) < 0) { Py_DECREF(ret); return NULL; } } } /* * If no copy then take an appropriate view if necessary, or * just return a reference to ret itself. */ else { int needview = ((flags & NPY_ARRAY_ENSUREARRAY) && !PyArray_CheckExact(arr)); Py_DECREF(newtype); if (needview) { PyArray_Descr *dtype = PyArray_DESCR(arr); PyTypeObject *subtype = NULL; if (flags & NPY_ARRAY_ENSUREARRAY) { subtype = &PyArray_Type; } Py_INCREF(dtype); ret = (PyArrayObject *)PyArray_View(arr, NULL, subtype); if (ret == NULL) { return NULL; } } else { Py_INCREF(arr); ret = arr; } } return (PyObject *)ret; } /*NUMPY_API */ NPY_NO_EXPORT PyObject * PyArray_FromStructInterface(PyObject *input) { PyArray_Descr *thetype = NULL; char buf[40]; PyArrayInterface *inter; PyObject *attr; PyArrayObject *ret; char endian = NPY_NATBYTE; attr = PyArray_GetAttrString_SuppressException(input, "__array_struct__"); if (attr == NULL) { return Py_NotImplemented; } if (!NpyCapsule_Check(attr)) { goto fail; } inter = NpyCapsule_AsVoidPtr(attr); if (inter->two != 2) { goto fail; } if ((inter->flags & NPY_ARRAY_NOTSWAPPED) != NPY_ARRAY_NOTSWAPPED) { endian = NPY_OPPBYTE; inter->flags &= ~NPY_ARRAY_NOTSWAPPED; } if (inter->flags & NPY_ARR_HAS_DESCR) { if (PyArray_DescrConverter(inter->descr, &thetype) == NPY_FAIL) { thetype = NULL; PyErr_Clear(); } } if (thetype == NULL) { PyOS_snprintf(buf, sizeof(buf), "%c%c%d", endian, inter->typekind, inter->itemsize); if (!(thetype=_array_typedescr_fromstr(buf))) { Py_DECREF(attr); return NULL; } } ret = (PyArrayObject *)PyArray_NewFromDescr(&PyArray_Type, thetype, inter->nd, inter->shape, inter->strides, inter->data, inter->flags, NULL); Py_INCREF(input); if (PyArray_SetBaseObject(ret, input) < 0) { Py_DECREF(ret); return NULL; } Py_DECREF(attr); PyArray_UpdateFlags(ret, NPY_ARRAY_UPDATE_ALL); return (PyObject *)ret; fail: PyErr_SetString(PyExc_ValueError, "invalid __array_struct__"); Py_DECREF(attr); return NULL; } #define PyIntOrLong_Check(obj) (PyInt_Check(obj) || PyLong_Check(obj)) /*NUMPY_API*/ NPY_NO_EXPORT PyObject * PyArray_FromInterface(PyObject *origin) { PyObject *tmp = NULL; PyObject *iface = NULL; PyObject *attr = NULL; PyObject *base = NULL; PyArrayObject *ret; PyArray_Descr *dtype = NULL; char *data = NULL; Py_ssize_t buffer_len; int res, i, n; npy_intp dims[NPY_MAXDIMS], strides[NPY_MAXDIMS]; int dataflags = NPY_ARRAY_BEHAVED; /* Get the typestring -- ignore array_descr */ /* Get the shape */ /* Get the memory from __array_data__ and __array_offset__ */ /* Get the strides */ iface = PyArray_GetAttrString_SuppressException(origin, "__array_interface__"); if (iface == NULL) { return Py_NotImplemented; } if (!PyDict_Check(iface)) { Py_DECREF(iface); PyErr_SetString(PyExc_ValueError, "Invalid __array_interface__ value, must be a dict"); return NULL; } /* Get type string from interface specification */ attr = PyDict_GetItemString(iface, "typestr"); if (attr == NULL) { Py_DECREF(iface); PyErr_SetString(PyExc_ValueError, "Missing __array_interface__ typestr"); return NULL; } #if defined(NPY_PY3K) /* Allow unicode type strings */ if (PyUnicode_Check(attr)) { tmp = PyUnicode_AsASCIIString(attr); attr = tmp; } #endif if (!PyBytes_Check(attr)) { PyErr_SetString(PyExc_TypeError, "__array_interface__ typestr must be a string"); goto fail; } /* Get dtype from type string */ dtype = _array_typedescr_fromstr(PyString_AS_STRING(attr)); #if defined(NPY_PY3K) if (tmp == attr) { Py_DECREF(tmp); } #endif if (dtype == NULL) { goto fail; } /* Get shape tuple from interface specification */ attr = PyDict_GetItemString(iface, "shape"); if (attr == NULL) { /* Shape must be specified when 'data' is specified */ if (PyDict_GetItemString(iface, "data") != NULL) { Py_DECREF(iface); PyErr_SetString(PyExc_ValueError, "Missing __array_interface__ shape"); return NULL; } /* Assume shape as scalar otherwise */ else { /* NOTE: pointers to data and base should be NULL */ n = dims[0] = 0; } } /* Make sure 'shape' is a tuple */ else if (!PyTuple_Check(attr)) { PyErr_SetString(PyExc_TypeError, "shape must be a tuple"); goto fail; } /* Get dimensions from shape tuple */ else { n = PyTuple_GET_SIZE(attr); for (i = 0; i < n; i++) { tmp = PyTuple_GET_ITEM(attr, i); dims[i] = PyArray_PyIntAsIntp(tmp); if (error_converting(dims[i])) { goto fail; } } } /* Get data buffer from interface specification */ attr = PyDict_GetItemString(iface, "data"); /* Case for data access through pointer */ if (attr && PyTuple_Check(attr)) { PyObject *dataptr; if (PyTuple_GET_SIZE(attr) != 2) { PyErr_SetString(PyExc_TypeError, "__array_interface__ data must be a 2-tuple with " "(data pointer integer, read-only flag)"); goto fail; } dataptr = PyTuple_GET_ITEM(attr, 0); if (PyString_Check(dataptr)) { res = sscanf(PyString_AsString(dataptr), "%p", (void **)&data); if (res < 1) { PyErr_SetString(PyExc_TypeError, "__array_interface__ data string cannot be converted"); goto fail; } } else if (PyIntOrLong_Check(dataptr)) { data = PyLong_AsVoidPtr(dataptr); } else { PyErr_SetString(PyExc_TypeError, "first element of __array_interface__ data tuple " "must be integer or string."); goto fail; } if (PyObject_IsTrue(PyTuple_GET_ITEM(attr,1))) { dataflags &= ~NPY_ARRAY_WRITEABLE; } base = origin; } /* Case for data access through buffer */ else if (attr) { if (n == 0) { PyErr_SetString(PyExc_ValueError, "__array_interface__ shape must be at least size 1"); goto fail; } if (attr && (attr != Py_None)) { base = attr; } else { base = origin; } res = PyObject_AsWriteBuffer(base, (void **)&data, &buffer_len); if (res < 0) { PyErr_Clear(); res = PyObject_AsReadBuffer( base, (const void **)&data, &buffer_len); if (res < 0) { goto fail; } dataflags &= ~NPY_ARRAY_WRITEABLE; } /* Get offset number from interface specification */ attr = PyDict_GetItemString(origin, "offset"); if (attr) { npy_longlong num = PyLong_AsLongLong(attr); if (error_converting(num)) { PyErr_SetString(PyExc_TypeError, "__array_interface__ offset must be an integer"); goto fail; } data += num; } } ret = (PyArrayObject *)PyArray_NewFromDescr(&PyArray_Type, dtype, n, dims, NULL, data, dataflags, NULL); if (ret == NULL) { goto fail; } if (data == NULL) { if (PyArray_SIZE(ret) > 1) { PyErr_SetString(PyExc_ValueError, "cannot coerce scalar to array with size > 1"); Py_DECREF(ret); goto fail; } if (PyArray_SETITEM(ret, PyArray_DATA(ret), origin) < 0) { Py_DECREF(ret); goto fail; } } if (base) { Py_INCREF(base); if (PyArray_SetBaseObject(ret, base) < 0) { Py_DECREF(ret); goto fail; } } attr = PyDict_GetItemString(iface, "strides"); if (attr != NULL && attr != Py_None) { if (!PyTuple_Check(attr)) { PyErr_SetString(PyExc_TypeError, "strides must be a tuple"); Py_DECREF(ret); goto fail; } if (n != PyTuple_GET_SIZE(attr)) { PyErr_SetString(PyExc_ValueError, "mismatch in length of strides and shape"); Py_DECREF(ret); goto fail; } for (i = 0; i < n; i++) { tmp = PyTuple_GET_ITEM(attr, i); strides[i] = PyArray_PyIntAsIntp(tmp); if (error_converting(strides[i])) { Py_DECREF(ret); goto fail; } } memcpy(PyArray_STRIDES(ret), strides, n*sizeof(npy_intp)); } PyArray_UpdateFlags(ret, NPY_ARRAY_UPDATE_ALL); Py_DECREF(iface); return (PyObject *)ret; fail: Py_XDECREF(dtype); Py_XDECREF(iface); return NULL; } /*NUMPY_API*/ NPY_NO_EXPORT PyObject * PyArray_FromArrayAttr(PyObject *op, PyArray_Descr *typecode, PyObject *context) { PyObject *new; PyObject *array_meth; array_meth = PyArray_GetAttrString_SuppressException(op, "__array__"); if (array_meth == NULL) { return Py_NotImplemented; } if (context == NULL) { if (typecode == NULL) { new = PyObject_CallFunction(array_meth, NULL); } else { new = PyObject_CallFunction(array_meth, "O", typecode); } } else { if (typecode == NULL) { new = PyObject_CallFunction(array_meth, "OO", Py_None, context); if (new == NULL && PyErr_ExceptionMatches(PyExc_TypeError)) { PyErr_Clear(); new = PyObject_CallFunction(array_meth, ""); } } else { new = PyObject_CallFunction(array_meth, "OO", typecode, context); if (new == NULL && PyErr_ExceptionMatches(PyExc_TypeError)) { PyErr_Clear(); new = PyObject_CallFunction(array_meth, "O", typecode); } } } Py_DECREF(array_meth); if (new == NULL) { return NULL; } if (!PyArray_Check(new)) { PyErr_SetString(PyExc_ValueError, "object __array__ method not " \ "producing an array"); Py_DECREF(new); return NULL; } return new; } /*NUMPY_API * new reference -- accepts NULL for mintype */ NPY_NO_EXPORT PyArray_Descr * PyArray_DescrFromObject(PyObject *op, PyArray_Descr *mintype) { PyArray_Descr *dtype; dtype = mintype; Py_XINCREF(dtype); if (PyArray_DTypeFromObject(op, NPY_MAXDIMS, &dtype) < 0) { return NULL; } if (dtype == NULL) { return PyArray_DescrFromType(NPY_DEFAULT_TYPE); } else { return dtype; } } /* These are also old calls (should use PyArray_NewFromDescr) */ /* They all zero-out the memory as previously done */ /* steals reference to descr -- and enforces native byteorder on it.*/ /*NUMPY_API Like FromDimsAndData but uses the Descr structure instead of typecode as input. */ NPY_NO_EXPORT PyObject * PyArray_FromDimsAndDataAndDescr(int nd, int *d, PyArray_Descr *descr, char *data) { PyObject *ret; int i; npy_intp newd[NPY_MAXDIMS]; char msg[] = "PyArray_FromDimsAndDataAndDescr: use PyArray_NewFromDescr."; if (DEPRECATE(msg) < 0) { return NULL; } if (!PyArray_ISNBO(descr->byteorder)) descr->byteorder = '='; for (i = 0; i < nd; i++) { newd[i] = (npy_intp) d[i]; } ret = PyArray_NewFromDescr(&PyArray_Type, descr, nd, newd, NULL, data, (data ? NPY_ARRAY_CARRAY : 0), NULL); return ret; } /*NUMPY_API Construct an empty array from dimensions and typenum */ NPY_NO_EXPORT PyObject * PyArray_FromDims(int nd, int *d, int type) { PyArrayObject *ret; char msg[] = "PyArray_FromDims: use PyArray_SimpleNew."; if (DEPRECATE(msg) < 0) { return NULL; } ret = (PyArrayObject *)PyArray_FromDimsAndDataAndDescr(nd, d, PyArray_DescrFromType(type), NULL); /* * Old FromDims set memory to zero --- some algorithms * relied on that. Better keep it the same. If * Object type, then it's already been set to zero, though. */ if (ret && (PyArray_DESCR(ret)->type_num != NPY_OBJECT)) { memset(PyArray_DATA(ret), 0, PyArray_NBYTES(ret)); } return (PyObject *)ret; } /* end old calls */ /*NUMPY_API * This is a quick wrapper around PyArray_FromAny(op, NULL, 0, 0, ENSUREARRAY) * that special cases Arrays and PyArray_Scalars up front * It *steals a reference* to the object * It also guarantees that the result is PyArray_Type * Because it decrefs op if any conversion needs to take place * so it can be used like PyArray_EnsureArray(some_function(...)) */ NPY_NO_EXPORT PyObject * PyArray_EnsureArray(PyObject *op) { PyObject *new; if ((op == NULL) || (PyArray_CheckExact(op))) { new = op; Py_XINCREF(new); } else if (PyArray_Check(op)) { new = PyArray_View((PyArrayObject *)op, NULL, &PyArray_Type); } else if (PyArray_IsScalar(op, Generic)) { new = PyArray_FromScalar(op, NULL); } else { new = PyArray_FromAny(op, NULL, 0, 0, NPY_ARRAY_ENSUREARRAY, NULL); } Py_XDECREF(op); return new; } /*NUMPY_API*/ NPY_NO_EXPORT PyObject * PyArray_EnsureAnyArray(PyObject *op) { if (op && PyArray_Check(op)) { return op; } return PyArray_EnsureArray(op); } /* TODO: Put the order parameter in PyArray_CopyAnyInto and remove this */ NPY_NO_EXPORT int PyArray_CopyAsFlat(PyArrayObject *dst, PyArrayObject *src, NPY_ORDER order) { PyArray_StridedUnaryOp *stransfer = NULL; NpyAuxData *transferdata = NULL; NpyIter *dst_iter, *src_iter; NpyIter_IterNextFunc *dst_iternext, *src_iternext; char **dst_dataptr, **src_dataptr; npy_intp dst_stride, src_stride; npy_intp *dst_countptr, *src_countptr; npy_uint32 baseflags; char *dst_data, *src_data; npy_intp dst_count, src_count, count; npy_intp src_itemsize; npy_intp dst_size, src_size; int needs_api; NPY_BEGIN_THREADS_DEF; if (PyArray_FailUnlessWriteable(dst, "destination array") < 0) { return -1; } /* * If the shapes match and a particular order is forced * for both, use the more efficient CopyInto */ if (order != NPY_ANYORDER && order != NPY_KEEPORDER && PyArray_NDIM(dst) == PyArray_NDIM(src) && PyArray_CompareLists(PyArray_DIMS(dst), PyArray_DIMS(src), PyArray_NDIM(dst))) { return PyArray_CopyInto(dst, src); } dst_size = PyArray_SIZE(dst); src_size = PyArray_SIZE(src); if (dst_size != src_size) { PyErr_Format(PyExc_ValueError, "cannot copy from array of size %d into an array " "of size %d", (int)src_size, (int)dst_size); return -1; } /* Zero-sized arrays require nothing be done */ if (dst_size == 0) { return 0; } baseflags = NPY_ITER_EXTERNAL_LOOP | NPY_ITER_DONT_NEGATE_STRIDES | NPY_ITER_REFS_OK; /* * This copy is based on matching C-order traversals of src and dst. * By using two iterators, we can find maximal sub-chunks that * can be processed at once. */ dst_iter = NpyIter_New(dst, NPY_ITER_WRITEONLY | baseflags, order, NPY_NO_CASTING, NULL); if (dst_iter == NULL) { return -1; } src_iter = NpyIter_New(src, NPY_ITER_READONLY | baseflags, order, NPY_NO_CASTING, NULL); if (src_iter == NULL) { NpyIter_Deallocate(dst_iter); return -1; } /* Get all the values needed for the inner loop */ dst_iternext = NpyIter_GetIterNext(dst_iter, NULL); dst_dataptr = NpyIter_GetDataPtrArray(dst_iter); /* Since buffering is disabled, we can cache the stride */ dst_stride = NpyIter_GetInnerStrideArray(dst_iter)[0]; dst_countptr = NpyIter_GetInnerLoopSizePtr(dst_iter); src_iternext = NpyIter_GetIterNext(src_iter, NULL); src_dataptr = NpyIter_GetDataPtrArray(src_iter); /* Since buffering is disabled, we can cache the stride */ src_stride = NpyIter_GetInnerStrideArray(src_iter)[0]; src_countptr = NpyIter_GetInnerLoopSizePtr(src_iter); src_itemsize = PyArray_DESCR(src)->elsize; if (dst_iternext == NULL || src_iternext == NULL) { NpyIter_Deallocate(dst_iter); NpyIter_Deallocate(src_iter); return -1; } needs_api = NpyIter_IterationNeedsAPI(dst_iter) || NpyIter_IterationNeedsAPI(src_iter); /* * Because buffering is disabled in the iterator, the inner loop * strides will be the same throughout the iteration loop. Thus, * we can pass them to this function to take advantage of * contiguous strides, etc. */ if (PyArray_GetDTypeTransferFunction( PyArray_ISALIGNED(src) && PyArray_ISALIGNED(dst), src_stride, dst_stride, PyArray_DESCR(src), PyArray_DESCR(dst), 0, &stransfer, &transferdata, &needs_api) != NPY_SUCCEED) { NpyIter_Deallocate(dst_iter); NpyIter_Deallocate(src_iter); return -1; } if (!needs_api) { NPY_BEGIN_THREADS; } dst_count = *dst_countptr; src_count = *src_countptr; dst_data = dst_dataptr[0]; src_data = src_dataptr[0]; for(;;) { /* Transfer the biggest amount that fits both */ count = (src_count < dst_count) ? src_count : dst_count; stransfer(dst_data, dst_stride, src_data, src_stride, count, src_itemsize, transferdata); /* If we exhausted the dst block, refresh it */ if (dst_count == count) { if (!dst_iternext(dst_iter)) { break; } dst_count = *dst_countptr; dst_data = dst_dataptr[0]; } else { dst_count -= count; dst_data += count*dst_stride; } /* If we exhausted the src block, refresh it */ if (src_count == count) { if (!src_iternext(src_iter)) { break; } src_count = *src_countptr; src_data = src_dataptr[0]; } else { src_count -= count; src_data += count*src_stride; } } if (!needs_api) { NPY_END_THREADS; } NPY_AUXDATA_FREE(transferdata); NpyIter_Deallocate(dst_iter); NpyIter_Deallocate(src_iter); return PyErr_Occurred() ? -1 : 0; } /*NUMPY_API * Copy an Array into another array -- memory must not overlap * Does not require src and dest to have "broadcastable" shapes * (only the same number of elements). * * TODO: For NumPy 2.0, this could accept an order parameter which * only allows NPY_CORDER and NPY_FORDER. Could also rename * this to CopyAsFlat to make the name more intuitive. * * Returns 0 on success, -1 on error. */ NPY_NO_EXPORT int PyArray_CopyAnyInto(PyArrayObject *dst, PyArrayObject *src) { return PyArray_CopyAsFlat(dst, src, NPY_CORDER); } /*NUMPY_API * Copy an Array into another array. * Broadcast to the destination shape if necessary. * * Returns 0 on success, -1 on failure. */ NPY_NO_EXPORT int PyArray_CopyInto(PyArrayObject *dst, PyArrayObject *src) { return PyArray_AssignArray(dst, src, NULL, NPY_UNSAFE_CASTING); } /*NUMPY_API * Move the memory of one array into another, allowing for overlapping data. * * Returns 0 on success, negative on failure. */ NPY_NO_EXPORT int PyArray_MoveInto(PyArrayObject *dst, PyArrayObject *src) { return PyArray_AssignArray(dst, src, NULL, NPY_UNSAFE_CASTING); } /*NUMPY_API * PyArray_CheckAxis * * check that axis is valid * convert 0-d arrays to 1-d arrays */ NPY_NO_EXPORT PyObject * PyArray_CheckAxis(PyArrayObject *arr, int *axis, int flags) { PyObject *temp1, *temp2; int n = PyArray_NDIM(arr); int axis_orig = *axis; if (*axis == NPY_MAXDIMS || n == 0) { if (n != 1) { temp1 = PyArray_Ravel(arr,0); if (temp1 == NULL) { *axis = 0; return NULL; } if (*axis == NPY_MAXDIMS) { *axis = PyArray_NDIM((PyArrayObject *)temp1)-1; } } else { temp1 = (PyObject *)arr; Py_INCREF(temp1); *axis = 0; } if (!flags && *axis == 0) { return temp1; } } else { temp1 = (PyObject *)arr; Py_INCREF(temp1); } if (flags) { temp2 = PyArray_CheckFromAny((PyObject *)temp1, NULL, 0, 0, flags, NULL); Py_DECREF(temp1); if (temp2 == NULL) { return NULL; } } else { temp2 = (PyObject *)temp1; } n = PyArray_NDIM((PyArrayObject *)temp2); if (*axis < 0) { *axis += n; } if ((*axis < 0) || (*axis >= n)) { PyErr_Format(PyExc_ValueError, "axis(=%d) out of bounds", axis_orig); Py_DECREF(temp2); return NULL; } return temp2; } /*NUMPY_API * Zeros * * steal a reference * accepts NULL type */ NPY_NO_EXPORT PyObject * PyArray_Zeros(int nd, npy_intp *dims, PyArray_Descr *type, int is_f_order) { PyArrayObject *ret; if (!type) { type = PyArray_DescrFromType(NPY_DEFAULT_TYPE); } ret = (PyArrayObject *)PyArray_NewFromDescr_int(&PyArray_Type, type, nd, dims, NULL, NULL, is_f_order, NULL, 1); if (ret == NULL) { return NULL; } /* handle objects */ if (PyDataType_REFCHK(PyArray_DESCR(ret))) { if (_zerofill(ret) < 0) { Py_DECREF(ret); return NULL; } } return (PyObject *)ret; } /*NUMPY_API * Empty * * accepts NULL type * steals referenct to type */ NPY_NO_EXPORT PyObject * PyArray_Empty(int nd, npy_intp *dims, PyArray_Descr *type, int is_f_order) { PyArrayObject *ret; if (!type) type = PyArray_DescrFromType(NPY_DEFAULT_TYPE); ret = (PyArrayObject *)PyArray_NewFromDescr(&PyArray_Type, type, nd, dims, NULL, NULL, is_f_order, NULL); if (ret == NULL) { return NULL; } if (PyDataType_REFCHK(type)) { PyArray_FillObjectArray(ret, Py_None); if (PyErr_Occurred()) { Py_DECREF(ret); return NULL; } } return (PyObject *)ret; } /* * Like ceil(value), but check for overflow. * * Return 0 on success, -1 on failure. In case of failure, set a PyExc_Overflow * exception */ static int _safe_ceil_to_intp(double value, npy_intp* ret) { double ivalue; ivalue = npy_ceil(value); if (ivalue < NPY_MIN_INTP || ivalue > NPY_MAX_INTP) { return -1; } *ret = (npy_intp)ivalue; return 0; } /*NUMPY_API Arange, */ NPY_NO_EXPORT PyObject * PyArray_Arange(double start, double stop, double step, int type_num) { npy_intp length; PyArrayObject *range; PyArray_ArrFuncs *funcs; PyObject *obj; int ret; if (_safe_ceil_to_intp((stop - start)/step, &length)) { PyErr_SetString(PyExc_OverflowError, "arange: overflow while computing length"); } if (length <= 0) { length = 0; return PyArray_New(&PyArray_Type, 1, &length, type_num, NULL, NULL, 0, 0, NULL); } range = (PyArrayObject *)PyArray_New(&PyArray_Type, 1, &length, type_num, NULL, NULL, 0, 0, NULL); if (range == NULL) { return NULL; } funcs = PyArray_DESCR(range)->f; /* * place start in the buffer and the next value in the second position * if length > 2, then call the inner loop, otherwise stop */ obj = PyFloat_FromDouble(start); ret = funcs->setitem(obj, PyArray_DATA(range), range); Py_DECREF(obj); if (ret < 0) { goto fail; } if (length == 1) { return (PyObject *)range; } obj = PyFloat_FromDouble(start + step); ret = funcs->setitem(obj, PyArray_BYTES(range)+PyArray_ITEMSIZE(range), range); Py_DECREF(obj); if (ret < 0) { goto fail; } if (length == 2) { return (PyObject *)range; } if (!funcs->fill) { PyErr_SetString(PyExc_ValueError, "no fill-function for data-type."); Py_DECREF(range); return NULL; } funcs->fill(PyArray_DATA(range), length, range); if (PyErr_Occurred()) { goto fail; } return (PyObject *)range; fail: Py_DECREF(range); return NULL; } /* * the formula is len = (intp) ceil((start - stop) / step); */ static npy_intp _calc_length(PyObject *start, PyObject *stop, PyObject *step, PyObject **next, int cmplx) { npy_intp len, tmp; PyObject *val; double value; *next = PyNumber_Subtract(stop, start); if (!(*next)) { if (PyTuple_Check(stop)) { PyErr_Clear(); PyErr_SetString(PyExc_TypeError, "arange: scalar arguments expected "\ "instead of a tuple."); } return -1; } val = PyNumber_TrueDivide(*next, step); Py_DECREF(*next); *next = NULL; if (!val) { return -1; } if (cmplx && PyComplex_Check(val)) { value = PyComplex_RealAsDouble(val); if (error_converting(value)) { Py_DECREF(val); return -1; } if (_safe_ceil_to_intp(value, &len)) { Py_DECREF(val); PyErr_SetString(PyExc_OverflowError, "arange: overflow while computing length"); return -1; } value = PyComplex_ImagAsDouble(val); Py_DECREF(val); if (error_converting(value)) { return -1; } if (_safe_ceil_to_intp(value, &tmp)) { PyErr_SetString(PyExc_OverflowError, "arange: overflow while computing length"); return -1; } len = PyArray_MIN(len, tmp); } else { value = PyFloat_AsDouble(val); Py_DECREF(val); if (error_converting(value)) { return -1; } if (_safe_ceil_to_intp(value, &len)) { PyErr_SetString(PyExc_OverflowError, "arange: overflow while computing length"); return -1; } } if (len > 0) { *next = PyNumber_Add(start, step); if (!next) { return -1; } } return len; } /*NUMPY_API * * ArangeObj, * * this doesn't change the references */ NPY_NO_EXPORT PyObject * PyArray_ArangeObj(PyObject *start, PyObject *stop, PyObject *step, PyArray_Descr *dtype) { PyArrayObject *range; PyArray_ArrFuncs *funcs; PyObject *next, *err; npy_intp length; PyArray_Descr *native = NULL; int swap; /* Datetime arange is handled specially */ if ((dtype != NULL && (dtype->type_num == NPY_DATETIME || dtype->type_num == NPY_TIMEDELTA)) || (dtype == NULL && (is_any_numpy_datetime_or_timedelta(start) || is_any_numpy_datetime_or_timedelta(stop) || is_any_numpy_datetime_or_timedelta(step)))) { return (PyObject *)datetime_arange(start, stop, step, dtype); } if (!dtype) { PyArray_Descr *deftype; PyArray_Descr *newtype; /* intentionally made to be at least NPY_LONG */ deftype = PyArray_DescrFromType(NPY_LONG); newtype = PyArray_DescrFromObject(start, deftype); Py_DECREF(deftype); if (newtype == NULL) { return NULL; } deftype = newtype; if (stop && stop != Py_None) { newtype = PyArray_DescrFromObject(stop, deftype); Py_DECREF(deftype); if (newtype == NULL) { return NULL; } deftype = newtype; } if (step && step != Py_None) { newtype = PyArray_DescrFromObject(step, deftype); Py_DECREF(deftype); if (newtype == NULL) { return NULL; } deftype = newtype; } dtype = deftype; } else { Py_INCREF(dtype); } if (!step || step == Py_None) { step = PyInt_FromLong(1); } else { Py_XINCREF(step); } if (!stop || stop == Py_None) { stop = start; start = PyInt_FromLong(0); } else { Py_INCREF(start); } /* calculate the length and next = start + step*/ length = _calc_length(start, stop, step, &next, PyTypeNum_ISCOMPLEX(dtype->type_num)); err = PyErr_Occurred(); if (err) { Py_DECREF(dtype); if (err && PyErr_GivenExceptionMatches(err, PyExc_OverflowError)) { PyErr_SetString(PyExc_ValueError, "Maximum allowed size exceeded"); } goto fail; } if (length <= 0) { length = 0; range = (PyArrayObject *)PyArray_SimpleNewFromDescr(1, &length, dtype); Py_DECREF(step); Py_DECREF(start); return (PyObject *)range; } /* * If dtype is not in native byte-order then get native-byte * order version. And then swap on the way out. */ if (!PyArray_ISNBO(dtype->byteorder)) { native = PyArray_DescrNewByteorder(dtype, NPY_NATBYTE); swap = 1; } else { native = dtype; swap = 0; } range = (PyArrayObject *)PyArray_SimpleNewFromDescr(1, &length, native); if (range == NULL) { goto fail; } /* * place start in the buffer and the next value in the second position * if length > 2, then call the inner loop, otherwise stop */ funcs = PyArray_DESCR(range)->f; if (funcs->setitem(start, PyArray_DATA(range), range) < 0) { goto fail; } if (length == 1) { goto finish; } if (funcs->setitem(next, PyArray_BYTES(range)+PyArray_ITEMSIZE(range), range) < 0) { goto fail; } if (length == 2) { goto finish; } if (!funcs->fill) { PyErr_SetString(PyExc_ValueError, "no fill-function for data-type."); Py_DECREF(range); goto fail; } funcs->fill(PyArray_DATA(range), length, range); if (PyErr_Occurred()) { goto fail; } finish: /* TODO: This swapping could be handled on the fly by the nditer */ if (swap) { PyObject *new; new = PyArray_Byteswap(range, 1); Py_DECREF(new); Py_DECREF(PyArray_DESCR(range)); /* steals the reference */ ((PyArrayObject_fields *)range)->descr = dtype; } Py_DECREF(start); Py_DECREF(step); Py_DECREF(next); return (PyObject *)range; fail: Py_DECREF(start); Py_DECREF(step); Py_XDECREF(next); return NULL; } static PyArrayObject * array_fromfile_binary(FILE *fp, PyArray_Descr *dtype, npy_intp num, size_t *nread) { PyArrayObject *r; npy_off_t start, numbytes; if (num < 0) { int fail = 0; start = npy_ftell(fp); if (start < 0) { fail = 1; } if (npy_fseek(fp, 0, SEEK_END) < 0) { fail = 1; } numbytes = npy_ftell(fp); if (numbytes < 0) { fail = 1; } numbytes -= start; if (npy_fseek(fp, start, SEEK_SET) < 0) { fail = 1; } if (fail) { PyErr_SetString(PyExc_IOError, "could not seek in file"); Py_DECREF(dtype); return NULL; } num = numbytes / dtype->elsize; } r = (PyArrayObject *)PyArray_NewFromDescr(&PyArray_Type, dtype, 1, &num, NULL, NULL, 0, NULL); if (r == NULL) { return NULL; } NPY_BEGIN_ALLOW_THREADS; *nread = fread(PyArray_DATA(r), dtype->elsize, num, fp); NPY_END_ALLOW_THREADS; return r; } /* * Create an array by reading from the given stream, using the passed * next_element and skip_separator functions. */ #define FROM_BUFFER_SIZE 4096 static PyArrayObject * array_from_text(PyArray_Descr *dtype, npy_intp num, char *sep, size_t *nread, void *stream, next_element next, skip_separator skip_sep, void *stream_data) { PyArrayObject *r; npy_intp i; char *dptr, *clean_sep, *tmp; int err = 0; npy_intp thisbuf = 0; npy_intp size; npy_intp bytes, totalbytes; size = (num >= 0) ? num : FROM_BUFFER_SIZE; r = (PyArrayObject *) PyArray_NewFromDescr(&PyArray_Type, dtype, 1, &size, NULL, NULL, 0, NULL); if (r == NULL) { return NULL; } clean_sep = swab_separator(sep); NPY_BEGIN_ALLOW_THREADS; totalbytes = bytes = size * dtype->elsize; dptr = PyArray_DATA(r); for (i= 0; num < 0 || i < num; i++) { if (next(&stream, dptr, dtype, stream_data) < 0) { break; } *nread += 1; thisbuf += 1; dptr += dtype->elsize; if (num < 0 && thisbuf == size) { totalbytes += bytes; tmp = PyDataMem_RENEW(PyArray_DATA(r), totalbytes); if (tmp == NULL) { err = 1; break; } ((PyArrayObject_fields *)r)->data = tmp; dptr = tmp + (totalbytes - bytes); thisbuf = 0; } if (skip_sep(&stream, clean_sep, stream_data) < 0) { break; } } if (num < 0) { tmp = PyDataMem_RENEW(PyArray_DATA(r), PyArray_MAX(*nread,1)*dtype->elsize); if (tmp == NULL) { err = 1; } else { PyArray_DIMS(r)[0] = *nread; ((PyArrayObject_fields *)r)->data = tmp; } } NPY_END_ALLOW_THREADS; free(clean_sep); if (err == 1) { PyErr_NoMemory(); } if (PyErr_Occurred()) { Py_DECREF(r); return NULL; } return r; } #undef FROM_BUFFER_SIZE /*NUMPY_API * * Given a ``FILE *`` pointer ``fp``, and a ``PyArray_Descr``, return an * array corresponding to the data encoded in that file. * * If the dtype is NULL, the default array type is used (double). * If non-null, the reference is stolen. * * The number of elements to read is given as ``num``; if it is < 0, then * then as many as possible are read. * * If ``sep`` is NULL or empty, then binary data is assumed, else * text data, with ``sep`` as the separator between elements. Whitespace in * the separator matches any length of whitespace in the text, and a match * for whitespace around the separator is added. * * For memory-mapped files, use the buffer interface. No more data than * necessary is read by this routine. */ NPY_NO_EXPORT PyObject * PyArray_FromFile(FILE *fp, PyArray_Descr *dtype, npy_intp num, char *sep) { PyArrayObject *ret; size_t nread = 0; if (PyDataType_REFCHK(dtype)) { PyErr_SetString(PyExc_ValueError, "Cannot read into object array"); Py_DECREF(dtype); return NULL; } if (dtype->elsize == 0) { PyErr_SetString(PyExc_ValueError, "The elements are 0-sized."); Py_DECREF(dtype); return NULL; } if ((sep == NULL) || (strlen(sep) == 0)) { ret = array_fromfile_binary(fp, dtype, num, &nread); } else { if (dtype->f->scanfunc == NULL) { PyErr_SetString(PyExc_ValueError, "Unable to read character files of that array type"); Py_DECREF(dtype); return NULL; } ret = array_from_text(dtype, num, sep, &nread, fp, (next_element) fromfile_next_element, (skip_separator) fromfile_skip_separator, NULL); } if (ret == NULL) { Py_DECREF(dtype); return NULL; } if (((npy_intp) nread) < num) { /* Realloc memory for smaller number of elements */ const size_t nsize = PyArray_MAX(nread,1)*PyArray_DESCR(ret)->elsize; char *tmp; if((tmp = PyDataMem_RENEW(PyArray_DATA(ret), nsize)) == NULL) { Py_DECREF(ret); return PyErr_NoMemory(); } ((PyArrayObject_fields *)ret)->data = tmp; PyArray_DIMS(ret)[0] = nread; } return (PyObject *)ret; } /*NUMPY_API*/ NPY_NO_EXPORT PyObject * PyArray_FromBuffer(PyObject *buf, PyArray_Descr *type, npy_intp count, npy_intp offset) { PyArrayObject *ret; char *data; Py_ssize_t ts; npy_intp s, n; int itemsize; int writeable = 1; if (PyDataType_REFCHK(type)) { PyErr_SetString(PyExc_ValueError, "cannot create an OBJECT array from memory"\ " buffer"); Py_DECREF(type); return NULL; } if (type->elsize == 0) { PyErr_SetString(PyExc_ValueError, "itemsize cannot be zero in type"); Py_DECREF(type); return NULL; } if (Py_TYPE(buf)->tp_as_buffer == NULL #if defined(NPY_PY3K) || Py_TYPE(buf)->tp_as_buffer->bf_getbuffer == NULL #else || (Py_TYPE(buf)->tp_as_buffer->bf_getwritebuffer == NULL && Py_TYPE(buf)->tp_as_buffer->bf_getreadbuffer == NULL) #endif ) { PyObject *newbuf; newbuf = PyObject_GetAttrString(buf, "__buffer__"); if (newbuf == NULL) { Py_DECREF(type); return NULL; } buf = newbuf; } else { Py_INCREF(buf); } if (PyObject_AsWriteBuffer(buf, (void *)&data, &ts) == -1) { writeable = 0; PyErr_Clear(); if (PyObject_AsReadBuffer(buf, (void *)&data, &ts) == -1) { Py_DECREF(buf); Py_DECREF(type); return NULL; } } if ((offset < 0) || (offset > ts)) { PyErr_Format(PyExc_ValueError, "offset must be non-negative and no greater than buffer "\ "length (%" NPY_INTP_FMT ")", (npy_intp)ts); Py_DECREF(buf); Py_DECREF(type); return NULL; } data += offset; s = (npy_intp)ts - offset; n = (npy_intp)count; itemsize = type->elsize; if (n < 0 ) { if (s % itemsize != 0) { PyErr_SetString(PyExc_ValueError, "buffer size must be a multiple"\ " of element size"); Py_DECREF(buf); Py_DECREF(type); return NULL; } n = s/itemsize; } else { if (s < n*itemsize) { PyErr_SetString(PyExc_ValueError, "buffer is smaller than requested"\ " size"); Py_DECREF(buf); Py_DECREF(type); return NULL; } } if ((ret = (PyArrayObject *)PyArray_NewFromDescr(&PyArray_Type, type, 1, &n, NULL, data, NPY_ARRAY_DEFAULT, NULL)) == NULL) { Py_DECREF(buf); return NULL; } if (!writeable) { PyArray_CLEARFLAGS(ret, NPY_ARRAY_WRITEABLE); } /* Store a reference for decref on deallocation */ if (PyArray_SetBaseObject(ret, buf) < 0) { Py_DECREF(ret); return NULL; } PyArray_UpdateFlags(ret, NPY_ARRAY_ALIGNED); return (PyObject *)ret; } /*NUMPY_API * * Given a pointer to a string ``data``, a string length ``slen``, and * a ``PyArray_Descr``, return an array corresponding to the data * encoded in that string. * * If the dtype is NULL, the default array type is used (double). * If non-null, the reference is stolen. * * If ``slen`` is < 0, then the end of string is used for text data. * It is an error for ``slen`` to be < 0 for binary data (since embedded NULLs * would be the norm). * * The number of elements to read is given as ``num``; if it is < 0, then * then as many as possible are read. * * If ``sep`` is NULL or empty, then binary data is assumed, else * text data, with ``sep`` as the separator between elements. Whitespace in * the separator matches any length of whitespace in the text, and a match * for whitespace around the separator is added. */ NPY_NO_EXPORT PyObject * PyArray_FromString(char *data, npy_intp slen, PyArray_Descr *dtype, npy_intp num, char *sep) { int itemsize; PyArrayObject *ret; npy_bool binary; if (dtype == NULL) { dtype=PyArray_DescrFromType(NPY_DEFAULT_TYPE); if (dtype == NULL) { return NULL; } } if (PyDataType_FLAGCHK(dtype, NPY_ITEM_IS_POINTER) || PyDataType_REFCHK(dtype)) { PyErr_SetString(PyExc_ValueError, "Cannot create an object array from" \ " a string"); Py_DECREF(dtype); return NULL; } itemsize = dtype->elsize; if (itemsize == 0) { PyErr_SetString(PyExc_ValueError, "zero-valued itemsize"); Py_DECREF(dtype); return NULL; } binary = ((sep == NULL) || (strlen(sep) == 0)); if (binary) { if (num < 0 ) { if (slen % itemsize != 0) { PyErr_SetString(PyExc_ValueError, "string size must be a "\ "multiple of element size"); Py_DECREF(dtype); return NULL; } num = slen/itemsize; } else { if (slen < num*itemsize) { PyErr_SetString(PyExc_ValueError, "string is smaller than " \ "requested size"); Py_DECREF(dtype); return NULL; } } ret = (PyArrayObject *) PyArray_NewFromDescr(&PyArray_Type, dtype, 1, &num, NULL, NULL, 0, NULL); if (ret == NULL) { return NULL; } memcpy(PyArray_DATA(ret), data, num*dtype->elsize); } else { /* read from character-based string */ size_t nread = 0; char *end; if (dtype->f->scanfunc == NULL) { PyErr_SetString(PyExc_ValueError, "don't know how to read " \ "character strings with that " \ "array type"); Py_DECREF(dtype); return NULL; } if (slen < 0) { end = NULL; } else { end = data + slen; } ret = array_from_text(dtype, num, sep, &nread, data, (next_element) fromstr_next_element, (skip_separator) fromstr_skip_separator, end); } return (PyObject *)ret; } /*NUMPY_API * * steals a reference to dtype (which cannot be NULL) */ NPY_NO_EXPORT PyObject * PyArray_FromIter(PyObject *obj, PyArray_Descr *dtype, npy_intp count) { PyObject *value; PyObject *iter = PyObject_GetIter(obj); PyArrayObject *ret = NULL; npy_intp i, elsize, elcount; char *item, *new_data; if (iter == NULL) { goto done; } elcount = (count < 0) ? 0 : count; if ((elsize = dtype->elsize) == 0) { PyErr_SetString(PyExc_ValueError, "Must specify length when using variable-size data-type."); goto done; } /* * We would need to alter the memory RENEW code to decrement any * reference counts before throwing away any memory. */ if (PyDataType_REFCHK(dtype)) { PyErr_SetString(PyExc_ValueError, "cannot create object arrays from iterator"); goto done; } ret = (PyArrayObject *)PyArray_NewFromDescr(&PyArray_Type, dtype, 1, &elcount, NULL,NULL, 0, NULL); dtype = NULL; if (ret == NULL) { goto done; } for (i = 0; (i < count || count == -1) && (value = PyIter_Next(iter)); i++) { if (i >= elcount) { /* Grow PyArray_DATA(ret): this is similar for the strategy for PyListObject, but we use 50% overallocation => 0, 4, 8, 14, 23, 36, 56, 86 ... */ elcount = (i >> 1) + (i < 4 ? 4 : 2) + i; if (elcount <= NPY_MAX_INTP/elsize) { new_data = PyDataMem_RENEW(PyArray_DATA(ret), elcount * elsize); } else { new_data = NULL; } if (new_data == NULL) { PyErr_SetString(PyExc_MemoryError, "cannot allocate array memory"); Py_DECREF(value); goto done; } ((PyArrayObject_fields *)ret)->data = new_data; } PyArray_DIMS(ret)[0] = i + 1; if (((item = index2ptr(ret, i)) == NULL) || (PyArray_DESCR(ret)->f->setitem(value, item, ret) == -1)) { Py_DECREF(value); goto done; } Py_DECREF(value); } if (PyErr_Occurred()) { goto done; } if (i < count) { PyErr_SetString(PyExc_ValueError, "iterator too short"); goto done; } /* * Realloc the data so that don't keep extra memory tied up * (assuming realloc is reasonably good about reusing space...) */ if (i == 0) { /* The size cannot be zero for PyDataMem_RENEW. */ i = 1; } new_data = PyDataMem_RENEW(PyArray_DATA(ret), i * elsize); if (new_data == NULL) { PyErr_SetString(PyExc_MemoryError, "cannot allocate array memory"); goto done; } ((PyArrayObject_fields *)ret)->data = new_data; done: Py_XDECREF(iter); Py_XDECREF(dtype); if (PyErr_Occurred()) { Py_XDECREF(ret); return NULL; } return (PyObject *)ret; } /* * This is the main array creation routine. * * Flags argument has multiple related meanings * depending on data and strides: * * If data is given, then flags is flags associated with data. * If strides is not given, then a contiguous strides array will be created * and the NPY_ARRAY_C_CONTIGUOUS bit will be set. If the flags argument * has the NPY_ARRAY_F_CONTIGUOUS bit set, then a FORTRAN-style strides array will be * created (and of course the NPY_ARRAY_F_CONTIGUOUS flag bit will be set). * * If data is not given but created here, then flags will be NPY_ARRAY_DEFAULT * and a non-zero flags argument can be used to indicate a FORTRAN style * array is desired. */ NPY_NO_EXPORT size_t _array_fill_strides(npy_intp *strides, npy_intp *dims, int nd, size_t itemsize, int inflag, int *objflags) { int i; #if NPY_RELAXED_STRIDES_CHECKING npy_bool not_cf_contig = 0; npy_bool nod = 0; /* A dim != 1 was found */ /* Check if new array is both F- and C-contiguous */ for (i = 0; i < nd; i++) { if (dims[i] != 1) { if (nod) { not_cf_contig = 1; break; } nod = 1; } } #endif /* NPY_RELAXED_STRIDES_CHECKING */ /* Only make Fortran strides if not contiguous as well */ if ((inflag & (NPY_ARRAY_F_CONTIGUOUS|NPY_ARRAY_C_CONTIGUOUS)) == NPY_ARRAY_F_CONTIGUOUS) { for (i = 0; i < nd; i++) { strides[i] = itemsize; if (dims[i]) { itemsize *= dims[i]; } #if NPY_RELAXED_STRIDES_CHECKING else { not_cf_contig = 0; } if (dims[i] == 1) { /* For testing purpose only */ strides[i] = NPY_MAX_INTP; } #endif /* NPY_RELAXED_STRIDES_CHECKING */ } #if NPY_RELAXED_STRIDES_CHECKING if (not_cf_contig) { #else /* not NPY_RELAXED_STRIDES_CHECKING */ if ((nd > 1) && ((strides[0] != strides[nd-1]) || (dims[nd-1] > 1))) { #endif /* not NPY_RELAXED_STRIDES_CHECKING */ *objflags = ((*objflags)|NPY_ARRAY_F_CONTIGUOUS) & ~NPY_ARRAY_C_CONTIGUOUS; } else { *objflags |= (NPY_ARRAY_F_CONTIGUOUS|NPY_ARRAY_C_CONTIGUOUS); } } else { for (i = nd - 1; i >= 0; i--) { strides[i] = itemsize; if (dims[i]) { itemsize *= dims[i]; } #if NPY_RELAXED_STRIDES_CHECKING else { not_cf_contig = 0; } if (dims[i] == 1) { /* For testing purpose only */ strides[i] = NPY_MAX_INTP; } #endif /* NPY_RELAXED_STRIDES_CHECKING */ } #if NPY_RELAXED_STRIDES_CHECKING if (not_cf_contig) { #else /* not NPY_RELAXED_STRIDES_CHECKING */ if ((nd > 1) && ((strides[0] != strides[nd-1]) || (dims[0] > 1))) { #endif /* not NPY_RELAXED_STRIDES_CHECKING */ *objflags = ((*objflags)|NPY_ARRAY_C_CONTIGUOUS) & ~NPY_ARRAY_F_CONTIGUOUS; } else { *objflags |= (NPY_ARRAY_C_CONTIGUOUS|NPY_ARRAY_F_CONTIGUOUS); } } return itemsize; } /* * Calls arr_of_subclass.__array_wrap__(towrap), in order to make 'towrap' * have the same ndarray subclass as 'arr_of_subclass'. */ NPY_NO_EXPORT PyArrayObject * PyArray_SubclassWrap(PyArrayObject *arr_of_subclass, PyArrayObject *towrap) { PyObject *wrapped = PyObject_CallMethod((PyObject *)arr_of_subclass, "__array_wrap__", "O", towrap); if (wrapped == NULL) { return NULL; } if (!PyArray_Check(wrapped)) { PyErr_SetString(PyExc_RuntimeError, "ndarray subclass __array_wrap__ method returned an " "object which was not an instance of an ndarray subclass"); Py_DECREF(wrapped); return NULL; } return (PyArrayObject *)wrapped; } numpy-1.8.2/numpy/core/src/multiarray/nditer_templ.c.src0000664000175100017510000004505512370216242024534 0ustar vagrantvagrant00000000000000/* * This file implements the API functions for NumPy's nditer that * are specialized using the templating system. * * Copyright (c) 2010-2011 by Mark Wiebe (mwwiebe@gmail.com) * The Univerity of British Columbia * * See LICENSE.txt for the license. */ /* Indicate that this .c file is allowed to include the header */ #define NPY_ITERATOR_IMPLEMENTATION_CODE #include "nditer_impl.h" /* SPECIALIZED iternext functions that handle the non-buffering part */ /**begin repeat * #const_itflags = 0, * NPY_ITFLAG_HASINDEX, * NPY_ITFLAG_EXLOOP, * NPY_ITFLAG_RANGE, * NPY_ITFLAG_RANGE|NPY_ITFLAG_HASINDEX# * #tag_itflags = 0, IND, NOINN, RNG, RNGuIND# */ /**begin repeat1 * #const_ndim = 1, 2, NPY_MAXDIMS# * #tag_ndim = 1, 2, ANY# */ /**begin repeat2 * #const_nop = 1, 2, NPY_MAXDIMS# * #tag_nop = 1, 2, ANY# */ /* Specialized iternext (@const_itflags@,@tag_ndim@,@tag_nop@) */ static int npyiter_iternext_itflags@tag_itflags@_dims@tag_ndim@_iters@tag_nop@( NpyIter *iter) { #if !(@const_itflags@&NPY_ITFLAG_EXLOOP) || (@const_ndim@ > 1) const npy_uint32 itflags = @const_itflags@; # if @const_ndim@ >= NPY_MAXDIMS int idim, ndim = NIT_NDIM(iter); # endif # if @const_nop@ < NPY_MAXDIMS const int nop = @const_nop@; # else int nop = NIT_NOP(iter); # endif NpyIter_AxisData *axisdata0; npy_intp istrides, nstrides = NAD_NSTRIDES(); #endif #if @const_ndim@ > 1 NpyIter_AxisData *axisdata1; npy_intp sizeof_axisdata; #endif #if @const_ndim@ > 2 NpyIter_AxisData *axisdata2; #endif #if (@const_itflags@&NPY_ITFLAG_RANGE) /* When ranged iteration is enabled, use the iterindex */ if (++NIT_ITERINDEX(iter) >= NIT_ITEREND(iter)) { return 0; } #endif #if @const_ndim@ > 1 sizeof_axisdata = NIT_AXISDATA_SIZEOF(itflags, ndim, nop); #endif # if !(@const_itflags@&NPY_ITFLAG_EXLOOP) || (@const_ndim@ > 1) axisdata0 = NIT_AXISDATA(iter); # endif # if !(@const_itflags@&NPY_ITFLAG_EXLOOP) /* Increment index 0 */ NAD_INDEX(axisdata0)++; /* Increment pointer 0 */ for (istrides = 0; istrides < nstrides; ++istrides) { NAD_PTRS(axisdata0)[istrides] += NAD_STRIDES(axisdata0)[istrides]; } # endif #if @const_ndim@ == 1 # if !(@const_itflags@&NPY_ITFLAG_EXLOOP) /* Finished when the index equals the shape */ return NAD_INDEX(axisdata0) < NAD_SHAPE(axisdata0); # else return 0; # endif #else # if !(@const_itflags@&NPY_ITFLAG_EXLOOP) if (NAD_INDEX(axisdata0) < NAD_SHAPE(axisdata0)) { return 1; } # endif axisdata1 = NIT_INDEX_AXISDATA(axisdata0, 1); /* Increment index 1 */ NAD_INDEX(axisdata1)++; /* Increment pointer 1 */ for (istrides = 0; istrides < nstrides; ++istrides) { NAD_PTRS(axisdata1)[istrides] += NAD_STRIDES(axisdata1)[istrides]; } if (NAD_INDEX(axisdata1) < NAD_SHAPE(axisdata1)) { /* Reset the 1st index to 0 */ NAD_INDEX(axisdata0) = 0; /* Reset the 1st pointer to the value of the 2nd */ for (istrides = 0; istrides < nstrides; ++istrides) { NAD_PTRS(axisdata0)[istrides] = NAD_PTRS(axisdata1)[istrides]; } return 1; } # if @const_ndim@ == 2 return 0; # else axisdata2 = NIT_INDEX_AXISDATA(axisdata1, 1); /* Increment index 2 */ NAD_INDEX(axisdata2)++; /* Increment pointer 2 */ for (istrides = 0; istrides < nstrides; ++istrides) { NAD_PTRS(axisdata2)[istrides] += NAD_STRIDES(axisdata2)[istrides]; } if (NAD_INDEX(axisdata2) < NAD_SHAPE(axisdata2)) { /* Reset the 1st and 2nd indices to 0 */ NAD_INDEX(axisdata0) = 0; NAD_INDEX(axisdata1) = 0; /* Reset the 1st and 2nd pointers to the value of the 3nd */ for (istrides = 0; istrides < nstrides; ++istrides) { NAD_PTRS(axisdata0)[istrides] = NAD_PTRS(axisdata2)[istrides]; NAD_PTRS(axisdata1)[istrides] = NAD_PTRS(axisdata2)[istrides]; } return 1; } for (idim = 3; idim < ndim; ++idim) { NIT_ADVANCE_AXISDATA(axisdata2, 1); /* Increment the index */ NAD_INDEX(axisdata2)++; /* Increment the pointer */ for (istrides = 0; istrides < nstrides; ++istrides) { NAD_PTRS(axisdata2)[istrides] += NAD_STRIDES(axisdata2)[istrides]; } if (NAD_INDEX(axisdata2) < NAD_SHAPE(axisdata2)) { /* Reset the indices and pointers of all previous axisdatas */ axisdata1 = axisdata2; do { NIT_ADVANCE_AXISDATA(axisdata1, -1); /* Reset the index to 0 */ NAD_INDEX(axisdata1) = 0; /* Reset the pointer to the updated value */ for (istrides = 0; istrides < nstrides; ++istrides) { NAD_PTRS(axisdata1)[istrides] = NAD_PTRS(axisdata2)[istrides]; } } while (axisdata1 != axisdata0); return 1; } } return 0; # endif /* ndim != 2 */ #endif /* ndim != 1 */ } /**end repeat2**/ /**end repeat1**/ /**end repeat**/ /**begin repeat * #const_nop = 1, 2, 3, 4, NPY_MAXDIMS# * #tag_nop = 1, 2, 3, 4, ANY# */ /* * Iternext function that handles the reduction buffering part. This * is done with a double loop to avoid frequent re-buffering. */ static int npyiter_buffered_reduce_iternext_iters@tag_nop@(NpyIter *iter) { npy_uint32 itflags = NIT_ITFLAGS(iter); /*int ndim = NIT_NDIM(iter);*/ #if @const_nop@ >= NPY_MAXDIMS int nop = NIT_NOP(iter); #else const int nop = @const_nop@; #endif int iop; NpyIter_AxisData *axisdata; NpyIter_BufferData *bufferdata = NIT_BUFFERDATA(iter); char **ptrs; char *prev_dataptrs[NPY_MAXARGS]; ptrs = NBF_PTRS(bufferdata); /* * If the iterator handles the inner loop, need to increment all * the indices and pointers */ if (!(itflags&NPY_ITFLAG_EXLOOP)) { /* Increment within the buffer */ if (++NIT_ITERINDEX(iter) < NBF_BUFITEREND(bufferdata)) { npy_intp *strides; strides = NBF_STRIDES(bufferdata); for (iop = 0; iop < nop; ++iop) { ptrs[iop] += strides[iop]; } return 1; } } else { NIT_ITERINDEX(iter) += NBF_SIZE(bufferdata); } NPY_IT_DBG_PRINT1("Iterator: Finished iteration %d of outer reduce loop\n", (int)NBF_REDUCE_POS(bufferdata)); /* The outer increment for the reduce double loop */ if (++NBF_REDUCE_POS(bufferdata) < NBF_REDUCE_OUTERSIZE(bufferdata)) { npy_intp *reduce_outerstrides = NBF_REDUCE_OUTERSTRIDES(bufferdata); char **reduce_outerptrs = NBF_REDUCE_OUTERPTRS(bufferdata); for (iop = 0; iop < nop; ++iop) { char *ptr = reduce_outerptrs[iop] + reduce_outerstrides[iop]; ptrs[iop] = ptr; reduce_outerptrs[iop] = ptr; } NBF_BUFITEREND(bufferdata) = NIT_ITERINDEX(iter) + NBF_SIZE(bufferdata); return 1; } /* Save the previously used data pointers */ axisdata = NIT_AXISDATA(iter); memcpy(prev_dataptrs, NAD_PTRS(axisdata), NPY_SIZEOF_INTP*nop); /* Write back to the arrays */ npyiter_copy_from_buffers(iter); /* Check if we're past the end */ if (NIT_ITERINDEX(iter) >= NIT_ITEREND(iter)) { NBF_SIZE(bufferdata) = 0; return 0; } /* Increment to the next buffer */ else { npyiter_goto_iterindex(iter, NIT_ITERINDEX(iter)); } /* Prepare the next buffers and set iterend/size */ npyiter_copy_to_buffers(iter, prev_dataptrs); return 1; } /**end repeat**/ /* iternext function that handles the buffering part */ static int npyiter_buffered_iternext(NpyIter *iter) { npy_uint32 itflags = NIT_ITFLAGS(iter); /*int ndim = NIT_NDIM(iter);*/ int nop = NIT_NOP(iter); NpyIter_BufferData *bufferdata = NIT_BUFFERDATA(iter); /* * If the iterator handles the inner loop, need to increment all * the indices and pointers */ if (!(itflags&NPY_ITFLAG_EXLOOP)) { /* Increment within the buffer */ if (++NIT_ITERINDEX(iter) < NBF_BUFITEREND(bufferdata)) { int iop; npy_intp *strides; char **ptrs; strides = NBF_STRIDES(bufferdata); ptrs = NBF_PTRS(bufferdata); for (iop = 0; iop < nop; ++iop) { ptrs[iop] += strides[iop]; } return 1; } } else { NIT_ITERINDEX(iter) += NBF_SIZE(bufferdata); } /* Write back to the arrays */ npyiter_copy_from_buffers(iter); /* Check if we're past the end */ if (NIT_ITERINDEX(iter) >= NIT_ITEREND(iter)) { NBF_SIZE(bufferdata) = 0; return 0; } /* Increment to the next buffer */ else { npyiter_goto_iterindex(iter, NIT_ITERINDEX(iter)); } /* Prepare the next buffers and set iterend/size */ npyiter_copy_to_buffers(iter, NULL); return 1; } /**end repeat2**/ /**end repeat1**/ /**end repeat**/ /* Specialization of iternext for when the iteration size is 1 */ static int npyiter_iternext_sizeone(NpyIter *iter) { return 0; } /*NUMPY_API * Compute the specialized iteration function for an iterator * * If errmsg is non-NULL, it should point to a variable which will * receive the error message, and no Python exception will be set. * This is so that the function can be called from code not holding * the GIL. */ NPY_NO_EXPORT NpyIter_IterNextFunc * NpyIter_GetIterNext(NpyIter *iter, char **errmsg) { npy_uint32 itflags = NIT_ITFLAGS(iter); 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. */ if (itflags&NPY_ITFLAG_ONEITERATION) { return &npyiter_iternext_sizeone; } /* * If buffering is enabled. */ if (itflags&NPY_ITFLAG_BUFFER) { if (itflags&NPY_ITFLAG_REDUCE) { switch (nop) { case 1: return &npyiter_buffered_reduce_iternext_iters1; case 2: return &npyiter_buffered_reduce_iternext_iters2; case 3: return &npyiter_buffered_reduce_iternext_iters3; case 4: return &npyiter_buffered_reduce_iternext_iters4; default: return &npyiter_buffered_reduce_iternext_itersANY; } } else { return &npyiter_buffered_iternext; } } /* * Ignore all the flags that don't affect the iterator memory * layout or the iternext function. Currently only HASINDEX, * EXLOOP, and RANGE affect them here. */ itflags &= (NPY_ITFLAG_HASINDEX|NPY_ITFLAG_EXLOOP|NPY_ITFLAG_RANGE); /* Switch statements let the compiler optimize this most effectively */ switch (itflags) { /* * The combinations HASINDEX|EXLOOP and RANGE|EXLOOP are excluded * by the New functions */ /**begin repeat * #const_itflags = 0, * NPY_ITFLAG_HASINDEX, * NPY_ITFLAG_EXLOOP, * NPY_ITFLAG_RANGE, * NPY_ITFLAG_RANGE|NPY_ITFLAG_HASINDEX# * #tag_itflags = 0, IND, NOINN, RNG, RNGuIND# */ case @const_itflags@: switch (ndim) { /**begin repeat1 * #const_ndim = 1, 2# * #tag_ndim = 1, 2# */ case @const_ndim@: switch (nop) { /**begin repeat2 * #const_nop = 1, 2# * #tag_nop = 1, 2# */ case @const_nop@: return &npyiter_iternext_itflags@tag_itflags@_dims@tag_ndim@_iters@tag_nop@; /**end repeat2**/ /* Not specialized on nop */ default: return &npyiter_iternext_itflags@tag_itflags@_dims@tag_ndim@_itersANY; } /**end repeat1**/ /* Not specialized on ndim */ default: switch (nop) { /**begin repeat1 * #const_nop = 1, 2# * #tag_nop = 1, 2# */ case @const_nop@: return &npyiter_iternext_itflags@tag_itflags@_dimsANY_iters@tag_nop@; /**end repeat1**/ /* Not specialized on nop */ default: return &npyiter_iternext_itflags@tag_itflags@_dimsANY_itersANY; } } /**end repeat**/ } /* The switch above should have caught all the possibilities. */ if (errmsg == NULL) { PyErr_Format(PyExc_ValueError, "GetIterNext internal iterator error - unexpected " "itflags/ndim/nop combination (%04x/%d/%d)", (int)itflags, (int)ndim, (int)nop); } else { *errmsg = "GetIterNext internal iterator error - unexpected " "itflags/ndim/nop combination"; } return NULL; } /* SPECIALIZED getindex functions */ /**begin repeat * #const_itflags = 0, * NPY_ITFLAG_HASINDEX, * NPY_ITFLAG_IDENTPERM, * NPY_ITFLAG_HASINDEX|NPY_ITFLAG_IDENTPERM, * NPY_ITFLAG_NEGPERM, * NPY_ITFLAG_HASINDEX|NPY_ITFLAG_NEGPERM, * NPY_ITFLAG_BUFFER, * NPY_ITFLAG_HASINDEX|NPY_ITFLAG_BUFFER, * NPY_ITFLAG_IDENTPERM|NPY_ITFLAG_BUFFER, * NPY_ITFLAG_HASINDEX|NPY_ITFLAG_IDENTPERM|NPY_ITFLAG_BUFFER, * NPY_ITFLAG_NEGPERM|NPY_ITFLAG_BUFFER, * NPY_ITFLAG_HASINDEX|NPY_ITFLAG_NEGPERM|NPY_ITFLAG_BUFFER# * #tag_itflags = 0, IND, IDP, INDuIDP, NEGP, INDuNEGP, * BUF, INDuBUF, IDPuBUF, INDuIDPuBUF, NEGPuBUF, INDuNEGPuBUF# */ static void npyiter_get_multi_index_itflags@tag_itflags@( NpyIter *iter, npy_intp *out_multi_index) { const npy_uint32 itflags = @const_itflags@; int idim, ndim = NIT_NDIM(iter); int nop = NIT_NOP(iter); npy_intp sizeof_axisdata; NpyIter_AxisData *axisdata; #if !((@const_itflags@)&NPY_ITFLAG_IDENTPERM) npy_int8 *perm = NIT_PERM(iter); #endif axisdata = NIT_AXISDATA(iter); sizeof_axisdata = NIT_AXISDATA_SIZEOF(itflags, ndim, nop); #if ((@const_itflags@)&NPY_ITFLAG_IDENTPERM) out_multi_index += ndim-1; for(idim = 0; idim < ndim; ++idim, --out_multi_index, NIT_ADVANCE_AXISDATA(axisdata, 1)) { *out_multi_index = NAD_INDEX(axisdata); } #elif !((@const_itflags@)&NPY_ITFLAG_NEGPERM) for(idim = 0; idim < ndim; ++idim, NIT_ADVANCE_AXISDATA(axisdata, 1)) { npy_int8 p = perm[idim]; out_multi_index[ndim-p-1] = NAD_INDEX(axisdata); } #else for(idim = 0; idim < ndim; ++idim, NIT_ADVANCE_AXISDATA(axisdata, 1)) { npy_int8 p = perm[idim]; if (p < 0) { /* If the perm entry is negative, reverse the index */ out_multi_index[ndim+p] = NAD_SHAPE(axisdata) - NAD_INDEX(axisdata) - 1; } else { out_multi_index[ndim-p-1] = NAD_INDEX(axisdata); } } #endif /* not ident perm */ } /**end repeat**/ /*NUMPY_API * Compute a specialized get_multi_index function for the iterator * * If errmsg is non-NULL, it should point to a variable which will * receive the error message, and no Python exception will be set. * This is so that the function can be called from code not holding * the GIL. */ NPY_NO_EXPORT NpyIter_GetMultiIndexFunc * NpyIter_GetGetMultiIndex(NpyIter *iter, char **errmsg) { npy_uint32 itflags = NIT_ITFLAGS(iter); int ndim = NIT_NDIM(iter); int nop = NIT_NOP(iter); /* These flags must be correct */ if ((itflags&(NPY_ITFLAG_HASMULTIINDEX|NPY_ITFLAG_DELAYBUF)) != NPY_ITFLAG_HASMULTIINDEX) { if (!(itflags&NPY_ITFLAG_HASMULTIINDEX)) { if (errmsg == NULL) { PyErr_SetString(PyExc_ValueError, "Cannot retrieve a GetMultiIndex function for an " "iterator that doesn't track a multi-index."); } else { *errmsg = "Cannot retrieve a GetMultiIndex function for an " "iterator that doesn't track a multi-index."; } return NULL; } else { if (errmsg == NULL) { PyErr_SetString(PyExc_ValueError, "Cannot retrieve a GetMultiIndex function for an " "iterator that used DELAY_BUFALLOC before a Reset call"); } else { *errmsg = "Cannot retrieve a GetMultiIndex function for an " "iterator that used DELAY_BUFALLOC before a " "Reset call"; } return NULL; } } /* * Only these flags affect the iterator memory layout or * the get_multi_index behavior. IDENTPERM and NEGPERM are mutually * exclusive, so that reduces the number of cases slightly. */ itflags &= (NPY_ITFLAG_HASINDEX | NPY_ITFLAG_IDENTPERM | NPY_ITFLAG_NEGPERM | NPY_ITFLAG_BUFFER); switch (itflags) { /**begin repeat * #const_itflags = 0, * NPY_ITFLAG_HASINDEX, * NPY_ITFLAG_IDENTPERM, * NPY_ITFLAG_HASINDEX|NPY_ITFLAG_IDENTPERM, * NPY_ITFLAG_NEGPERM, * NPY_ITFLAG_HASINDEX|NPY_ITFLAG_NEGPERM, * NPY_ITFLAG_BUFFER, * NPY_ITFLAG_HASINDEX|NPY_ITFLAG_BUFFER, * NPY_ITFLAG_IDENTPERM|NPY_ITFLAG_BUFFER, * NPY_ITFLAG_HASINDEX|NPY_ITFLAG_IDENTPERM|NPY_ITFLAG_BUFFER, * NPY_ITFLAG_NEGPERM|NPY_ITFLAG_BUFFER, * NPY_ITFLAG_HASINDEX|NPY_ITFLAG_NEGPERM|NPY_ITFLAG_BUFFER# * #tag_itflags = 0, IND, IDP, INDuIDP, NEGP, INDuNEGP, * BUF, INDuBUF, IDPuBUF, INDuIDPuBUF, NEGPuBUF, INDuNEGPuBUF# */ case @const_itflags@: return npyiter_get_multi_index_itflags@tag_itflags@; /**end repeat**/ } /* The switch above should have caught all the possibilities. */ if (errmsg == NULL) { PyErr_Format(PyExc_ValueError, "GetGetMultiIndex internal iterator error - unexpected " "itflags/ndim/nop combination (%04x/%d/%d)", (int)itflags, (int)ndim, (int)nop); } else { *errmsg = "GetGetMultiIndex internal iterator error - unexpected " "itflags/ndim/nop combination"; } return NULL; } #undef NPY_ITERATOR_IMPLEMENTATION_CODE numpy-1.8.2/numpy/core/src/multiarray/convert_datatype.c0000664000175100017510000017302012370216243024626 0ustar vagrantvagrant00000000000000#define PY_SSIZE_T_CLEAN #include #include "structmember.h" #define NPY_NO_DEPRECATED_API NPY_API_VERSION #define _MULTIARRAYMODULE #include "numpy/arrayobject.h" #include "numpy/arrayscalars.h" #include "npy_config.h" #include "npy_pycompat.h" #include "common.h" #include "scalartypes.h" #include "mapping.h" #include "convert_datatype.h" #include "_datetime.h" #include "datetime_strings.h" /*NUMPY_API * For backward compatibility * * Cast an array using typecode structure. * steals reference to at --- cannot be NULL * * This function always makes a copy of arr, even if the dtype * doesn't change. */ NPY_NO_EXPORT PyObject * PyArray_CastToType(PyArrayObject *arr, PyArray_Descr *dtype, int is_f_order) { PyObject *out; /* If the requested dtype is flexible, adapt it */ PyArray_AdaptFlexibleDType((PyObject *)arr, PyArray_DESCR(arr), &dtype); if (dtype == NULL) { return NULL; } out = PyArray_NewFromDescr(Py_TYPE(arr), dtype, PyArray_NDIM(arr), PyArray_DIMS(arr), NULL, NULL, is_f_order, (PyObject *)arr); if (out == NULL) { return NULL; } if (PyArray_CopyInto((PyArrayObject *)out, arr) < 0) { Py_DECREF(out); return NULL; } return out; } /*NUMPY_API * Get a cast function to cast from the input descriptor to the * output type_number (must be a registered data-type). * Returns NULL if un-successful. */ NPY_NO_EXPORT PyArray_VectorUnaryFunc * PyArray_GetCastFunc(PyArray_Descr *descr, int type_num) { PyArray_VectorUnaryFunc *castfunc = NULL; if (type_num < NPY_NTYPES_ABI_COMPATIBLE) { castfunc = descr->f->cast[type_num]; } else { PyObject *obj = descr->f->castdict; if (obj && PyDict_Check(obj)) { PyObject *key; PyObject *cobj; key = PyInt_FromLong(type_num); cobj = PyDict_GetItem(obj, key); Py_DECREF(key); if (cobj && NpyCapsule_Check(cobj)) { castfunc = NpyCapsule_AsVoidPtr(cobj); } } } if (PyTypeNum_ISCOMPLEX(descr->type_num) && !PyTypeNum_ISCOMPLEX(type_num) && PyTypeNum_ISNUMBER(type_num) && !PyTypeNum_ISBOOL(type_num)) { PyObject *cls = NULL, *obj = NULL; int ret; obj = PyImport_ImportModule("numpy.core"); if (obj) { cls = PyObject_GetAttrString(obj, "ComplexWarning"); Py_DECREF(obj); } ret = PyErr_WarnEx(cls, "Casting complex values to real discards " "the imaginary part", 1); Py_XDECREF(cls); if (ret < 0) { return NULL; } } if (castfunc) { return castfunc; } PyErr_SetString(PyExc_ValueError, "No cast function available."); return NULL; } /* * This function calls Py_DECREF on flex_dtype, and replaces it with * a new dtype that has been adapted based on the values in data_dtype * and data_obj. If the flex_dtype is not flexible, it leaves it as is. * * Usually, if data_obj is not an array, dtype should be the result * given by the PyArray_GetArrayParamsFromObject function. * * The data_obj may be NULL if just a dtype is is known for the source. * * If *flex_dtype is NULL, returns immediately, without setting an * exception. This basically assumes an error was already set previously. * * The current flexible dtypes include NPY_STRING, NPY_UNICODE, NPY_VOID, * and NPY_DATETIME with generic units. */ NPY_NO_EXPORT void PyArray_AdaptFlexibleDType(PyObject *data_obj, PyArray_Descr *data_dtype, PyArray_Descr **flex_dtype) { PyArray_DatetimeMetaData *meta; int flex_type_num; PyArrayObject *arr = NULL; PyArray_Descr *dtype = NULL; int ndim = 0; npy_intp dims[NPY_MAXDIMS]; PyObject *list = NULL; int result; if (*flex_dtype == NULL) { if (!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError, "NumPy AdaptFlexibleDType was called with NULL flex_dtype " "but no error set"); } return; } flex_type_num = (*flex_dtype)->type_num; /* Flexible types with expandable size */ if ((*flex_dtype)->elsize == 0) { /* First replace the flex dtype */ PyArray_DESCR_REPLACE(*flex_dtype); if (*flex_dtype == NULL) { return; } if (data_dtype->type_num == flex_type_num || flex_type_num == NPY_VOID) { (*flex_dtype)->elsize = data_dtype->elsize; } else { npy_intp size = 8; /* * Get a string-size estimate of the input. These * are generallly the size needed, rounded up to * a multiple of eight. */ 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; break; case NPY_HALF: case NPY_FLOAT: case NPY_DOUBLE: case NPY_LONGDOUBLE: size = 32; break; case NPY_CFLOAT: case NPY_CDOUBLE: case NPY_CLONGDOUBLE: size = 64; break; case NPY_OBJECT: size = 64; if ((flex_type_num == NPY_STRING || flex_type_num == NPY_UNICODE) && data_obj != NULL) { if (PyArray_CheckScalar(data_obj)) { PyObject *scalar = PyArray_ToList(data_obj); if (scalar != NULL) { PyObject *s = PyObject_Str(scalar); if (s == NULL) { Py_DECREF(scalar); Py_DECREF(*flex_dtype); *flex_dtype = NULL; return; } else { size = PyObject_Length(s); Py_DECREF(s); } Py_DECREF(scalar); } } else if (PyArray_Check(data_obj)) { /* * Convert data array to list of objects since * GetArrayParamsFromObject won't iterate over * array. */ list = PyArray_ToList(data_obj); result = PyArray_GetArrayParamsFromObject( list, *flex_dtype, 0, &dtype, &ndim, dims, &arr, NULL); if (result == 0 && dtype != NULL) { if (flex_type_num == NPY_UNICODE) { size = dtype->elsize / 4; } else { size = dtype->elsize; } } Py_DECREF(list); } else if (PyArray_IsPythonScalar(data_obj)) { PyObject *s = PyObject_Str(data_obj); if (s == NULL) { Py_DECREF(*flex_dtype); *flex_dtype = NULL; return; } else { size = PyObject_Length(s); Py_DECREF(s); } } } break; case NPY_STRING: case NPY_VOID: size = data_dtype->elsize; break; case NPY_UNICODE: size = data_dtype->elsize / 4; break; case NPY_DATETIME: meta = get_datetime_metadata_from_dtype(data_dtype); if (meta == NULL) { Py_DECREF(*flex_dtype); *flex_dtype = NULL; return; } size = get_datetime_iso_8601_strlen(0, meta->base); break; case NPY_TIMEDELTA: size = 21; break; } if (flex_type_num == NPY_STRING) { (*flex_dtype)->elsize = size; } else if (flex_type_num == NPY_UNICODE) { (*flex_dtype)->elsize = size * 4; } } } /* Flexible type with generic time unit that adapts */ else if (flex_type_num == NPY_DATETIME || flex_type_num == NPY_TIMEDELTA) { meta = get_datetime_metadata_from_dtype(*flex_dtype); if (meta == NULL) { Py_DECREF(*flex_dtype); *flex_dtype = NULL; return; } if (meta->base == NPY_FR_GENERIC) { if (data_dtype->type_num == NPY_DATETIME || data_dtype->type_num == NPY_TIMEDELTA) { meta = get_datetime_metadata_from_dtype(data_dtype); if (meta == NULL) { Py_DECREF(*flex_dtype); *flex_dtype = NULL; return; } Py_DECREF(*flex_dtype); *flex_dtype = create_datetime_dtype(flex_type_num, meta); } else if (data_obj != NULL) { /* Detect the unit from the input's data */ Py_DECREF(*flex_dtype); *flex_dtype = find_object_datetime_type(data_obj, flex_type_num); } } } } /* * Must be broadcastable. * This code is very similar to PyArray_CopyInto/PyArray_MoveInto * except casting is done --- NPY_BUFSIZE is used * as the size of the casting buffer. */ /*NUMPY_API * Cast to an already created array. */ NPY_NO_EXPORT int PyArray_CastTo(PyArrayObject *out, PyArrayObject *mp) { /* CopyInto handles the casting now */ return PyArray_CopyInto(out, mp); } /*NUMPY_API * Cast to an already created array. Arrays don't have to be "broadcastable" * Only requirement is they have the same number of elements. */ NPY_NO_EXPORT int PyArray_CastAnyTo(PyArrayObject *out, PyArrayObject *mp) { /* CopyAnyInto handles the casting now */ return PyArray_CopyAnyInto(out, mp); } /*NUMPY_API *Check the type coercion rules. */ NPY_NO_EXPORT int PyArray_CanCastSafely(int fromtype, int totype) { PyArray_Descr *from; /* Fast table lookup for small type numbers */ if ((unsigned int)fromtype < NPY_NTYPES && (unsigned int)totype < NPY_NTYPES) { return _npy_can_cast_safely_table[fromtype][totype]; } /* Identity */ if (fromtype == totype) { return 1; } /* Special-cases for some types */ switch (fromtype) { case NPY_DATETIME: case NPY_TIMEDELTA: case NPY_OBJECT: case NPY_VOID: return 0; case NPY_BOOL: return 1; } switch (totype) { case NPY_BOOL: case NPY_DATETIME: case NPY_TIMEDELTA: return 0; case NPY_OBJECT: case NPY_VOID: return 1; } from = PyArray_DescrFromType(fromtype); /* * cancastto is a NPY_NOTYPE terminated C-int-array of types that * the data-type can be cast to safely. */ if (from->f->cancastto) { int *curtype = from->f->cancastto; while (*curtype != NPY_NOTYPE) { if (*curtype++ == totype) { return 1; } } } return 0; } /*NUMPY_API * leaves reference count alone --- cannot be NULL * * PyArray_CanCastTypeTo is equivalent to this, but adds a 'casting' * parameter. */ NPY_NO_EXPORT npy_bool PyArray_CanCastTo(PyArray_Descr *from, PyArray_Descr *to) { int from_type_num = from->type_num; int to_type_num = to->type_num; npy_bool ret; ret = (npy_bool) PyArray_CanCastSafely(from_type_num, to_type_num); if (ret) { /* Check String and Unicode more closely */ if (from_type_num == NPY_STRING) { if (to_type_num == NPY_STRING) { ret = (from->elsize <= to->elsize); } else if (to_type_num == NPY_UNICODE) { ret = (from->elsize << 2 <= to->elsize); } } else if (from_type_num == NPY_UNICODE) { if (to_type_num == NPY_UNICODE) { ret = (from->elsize <= to->elsize); } } /* * For datetime/timedelta, only treat casts moving towards * more precision as safe. */ else if (from_type_num == NPY_DATETIME && to_type_num == NPY_DATETIME) { PyArray_DatetimeMetaData *meta1, *meta2; meta1 = get_datetime_metadata_from_dtype(from); if (meta1 == NULL) { PyErr_Clear(); return 0; } meta2 = get_datetime_metadata_from_dtype(to); if (meta2 == NULL) { PyErr_Clear(); return 0; } return can_cast_datetime64_metadata(meta1, meta2, NPY_SAFE_CASTING); } else if (from_type_num == NPY_TIMEDELTA && to_type_num == NPY_TIMEDELTA) { PyArray_DatetimeMetaData *meta1, *meta2; meta1 = get_datetime_metadata_from_dtype(from); if (meta1 == NULL) { PyErr_Clear(); return 0; } meta2 = get_datetime_metadata_from_dtype(to); if (meta2 == NULL) { PyErr_Clear(); return 0; } return can_cast_timedelta64_metadata(meta1, meta2, NPY_SAFE_CASTING); } /* * TODO: If to_type_num is STRING or unicode * see if the length is long enough to hold the * stringified value of the object. */ } return ret; } /* Provides an ordering for the dtype 'kind' character codes */ static int dtype_kind_to_ordering(char kind) { switch (kind) { /* Boolean kind */ case 'b': return 0; /* Unsigned int kind */ case 'u': return 1; /* Signed int kind */ case 'i': return 2; /* Float kind */ case 'f': return 4; /* Complex kind */ case 'c': return 5; /* String kind */ case 'S': case 'a': return 6; /* Unicode kind */ case 'U': return 7; /* Void kind */ case 'V': return 8; /* Object kind */ case 'O': return 9; /* * Anything else, like datetime, is special cased to * not fit in this hierarchy */ default: return -1; } } /* Converts a type number from unsigned to signed */ static int type_num_unsigned_to_signed(int type_num) { switch (type_num) { case NPY_UBYTE: return NPY_BYTE; case NPY_USHORT: return NPY_SHORT; case NPY_UINT: return NPY_INT; case NPY_ULONG: return NPY_LONG; case NPY_ULONGLONG: return NPY_LONGLONG; default: return type_num; } } /* * NOTE: once the UNSAFE_CASTING -> SAME_KIND_CASTING transition is over, * we should remove NPY_INTERNAL_UNSAFE_CASTING_BUT_WARN_UNLESS_SAME_KIND * and PyArray_CanCastTypeTo_impl should be renamed back to * PyArray_CanCastTypeTo. */ static npy_bool PyArray_CanCastTypeTo_impl(PyArray_Descr *from, PyArray_Descr *to, NPY_CASTING casting); /*NUMPY_API * Returns true if data of type 'from' may be cast to data of type * 'to' according to the rule 'casting'. */ 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) { 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, NPY_SAME_KIND_CASTING); if (unsafe_ok && !same_kind_ok) { char * msg = "Implicitly casting between incompatible kinds. In " "a future numpy release, this will raise an error. " "Use casting=\"unsafe\" if this is intentional."; if (DEPRECATE(msg) < 0) { /* We have no way to propagate an exception :-( */ PyErr_Clear(); PySys_WriteStderr("Sorry, you requested this warning " "be raised as an error, but we couldn't " "do it. (See issue #3806 in the numpy " "bug tracker.) So FYI, it was: " "DeprecationWarning: %s\n", msg); } } return unsafe_ok; } else { return PyArray_CanCastTypeTo_impl(from, to, casting); } } static npy_bool PyArray_CanCastTypeTo_impl(PyArray_Descr *from, PyArray_Descr *to, NPY_CASTING casting) { /* If unsafe casts are allowed */ if (casting == NPY_UNSAFE_CASTING) { return 1; } /* Equivalent types can be cast with any value of 'casting' */ else if (PyArray_EquivTypenums(from->type_num, to->type_num)) { /* For complicated case, use EquivTypes (for now) */ if (PyTypeNum_ISUSERDEF(from->type_num) || PyDataType_HASFIELDS(from) || from->subarray != NULL) { int ret; /* Only NPY_NO_CASTING prevents byte order conversion */ if ((casting != NPY_NO_CASTING) && (!PyArray_ISNBO(from->byteorder) || !PyArray_ISNBO(to->byteorder))) { PyArray_Descr *nbo_from, *nbo_to; nbo_from = PyArray_DescrNewByteorder(from, NPY_NATIVE); nbo_to = PyArray_DescrNewByteorder(to, NPY_NATIVE); if (nbo_from == NULL || nbo_to == NULL) { Py_XDECREF(nbo_from); Py_XDECREF(nbo_to); PyErr_Clear(); return 0; } ret = PyArray_EquivTypes(nbo_from, nbo_to); Py_DECREF(nbo_from); Py_DECREF(nbo_to); } else { ret = PyArray_EquivTypes(from, to); } return ret; } switch (from->type_num) { case NPY_DATETIME: { PyArray_DatetimeMetaData *meta1, *meta2; meta1 = get_datetime_metadata_from_dtype(from); if (meta1 == NULL) { PyErr_Clear(); return 0; } meta2 = get_datetime_metadata_from_dtype(to); if (meta2 == NULL) { PyErr_Clear(); return 0; } if (casting == NPY_NO_CASTING) { return PyArray_ISNBO(from->byteorder) == PyArray_ISNBO(to->byteorder) && can_cast_datetime64_metadata(meta1, meta2, casting); } else { return can_cast_datetime64_metadata(meta1, meta2, casting); } } case NPY_TIMEDELTA: { PyArray_DatetimeMetaData *meta1, *meta2; meta1 = get_datetime_metadata_from_dtype(from); if (meta1 == NULL) { PyErr_Clear(); return 0; } meta2 = get_datetime_metadata_from_dtype(to); if (meta2 == NULL) { PyErr_Clear(); return 0; } if (casting == NPY_NO_CASTING) { return PyArray_ISNBO(from->byteorder) == PyArray_ISNBO(to->byteorder) && can_cast_timedelta64_metadata(meta1, meta2, casting); } else { return can_cast_timedelta64_metadata(meta1, meta2, casting); } } default: switch (casting) { case NPY_NO_CASTING: return PyArray_EquivTypes(from, to); case NPY_EQUIV_CASTING: return (from->elsize == to->elsize); case NPY_SAFE_CASTING: return (from->elsize <= to->elsize); default: return 1; } break; } } /* If safe or same-kind casts are allowed */ else if (casting == NPY_SAFE_CASTING || casting == NPY_SAME_KIND_CASTING) { if (PyArray_CanCastTo(from, to)) { return 1; } else if(casting == NPY_SAME_KIND_CASTING) { /* * Also allow casting from lower to higher kinds, according * to the ordering provided by dtype_kind_to_ordering. * Some kinds, like datetime, don't fit in the hierarchy, * and are special cased as -1. */ int from_order, to_order; from_order = dtype_kind_to_ordering(from->kind); to_order = dtype_kind_to_ordering(to->kind); return from_order != -1 && from_order <= to_order; } else { return 0; } } /* NPY_NO_CASTING or NPY_EQUIV_CASTING was specified */ else { return 0; } } /* CanCastArrayTo needs this function */ static int min_scalar_type_num(char *valueptr, int type_num, int *is_small_unsigned); NPY_NO_EXPORT npy_bool can_cast_scalar_to(PyArray_Descr *scal_type, char *scal_data, PyArray_Descr *to, NPY_CASTING casting) { int swap; int is_small_unsigned = 0, type_num; npy_bool ret; PyArray_Descr *dtype; /* An aligned memory buffer large enough to hold any type */ npy_longlong value[4]; /* * If the two dtypes are actually references to the same object * or if casting type is forced unsafe then always OK. */ if (scal_type == to || casting == NPY_UNSAFE_CASTING ) { return 1; } /* * If the scalar isn't a number, or the rule is stricter than * NPY_SAFE_CASTING, use the straight type-based rules */ if (!PyTypeNum_ISNUMBER(scal_type->type_num) || casting < NPY_SAFE_CASTING) { return PyArray_CanCastTypeTo(scal_type, to, casting); } swap = !PyArray_ISNBO(scal_type->byteorder); scal_type->f->copyswap(&value, scal_data, swap, NULL); type_num = min_scalar_type_num((char *)&value, scal_type->type_num, &is_small_unsigned); /* * If we've got a small unsigned scalar, and the 'to' type * is not unsigned, then make it signed to allow the value * to be cast more appropriately. */ if (is_small_unsigned && !(PyTypeNum_ISUNSIGNED(to->type_num))) { type_num = type_num_unsigned_to_signed(type_num); } dtype = PyArray_DescrFromType(type_num); if (dtype == NULL) { return 0; } #if 0 printf("min scalar cast "); PyObject_Print(dtype, stdout, 0); printf(" to "); PyObject_Print(to, stdout, 0); printf("\n"); #endif ret = PyArray_CanCastTypeTo(dtype, to, casting); Py_DECREF(dtype); return ret; } /*NUMPY_API * Returns 1 if the array object may be cast to the given data type using * the casting rule, 0 otherwise. This differs from PyArray_CanCastTo in * that it handles scalar arrays (0 dimensions) specially, by checking * their value. */ NPY_NO_EXPORT npy_bool PyArray_CanCastArrayTo(PyArrayObject *arr, PyArray_Descr *to, NPY_CASTING casting) { PyArray_Descr *from = PyArray_DESCR(arr); /* If it's a scalar, check the value */ if (PyArray_NDIM(arr) == 0 && !PyArray_HASFIELDS(arr)) { return can_cast_scalar_to(from, PyArray_DATA(arr), to, casting); } /* Otherwise, use the standard rules */ return PyArray_CanCastTypeTo(from, to, casting); } /*NUMPY_API * See if array scalars can be cast. * * TODO: For NumPy 2.0, add a NPY_CASTING parameter. */ NPY_NO_EXPORT npy_bool PyArray_CanCastScalar(PyTypeObject *from, PyTypeObject *to) { int fromtype; int totype; fromtype = _typenum_fromtypeobj((PyObject *)from, 0); totype = _typenum_fromtypeobj((PyObject *)to, 0); if (fromtype == NPY_NOTYPE || totype == NPY_NOTYPE) { return NPY_FALSE; } return (npy_bool) PyArray_CanCastSafely(fromtype, totype); } /* * Internal promote types function which handles unsigned integers which * fit in same-sized signed integers specially. */ static PyArray_Descr * promote_types(PyArray_Descr *type1, PyArray_Descr *type2, int is_small_unsigned1, int is_small_unsigned2) { if (is_small_unsigned1) { int type_num1 = type1->type_num; int type_num2 = type2->type_num; int ret_type_num; if (type_num2 < NPY_NTYPES && !(PyTypeNum_ISBOOL(type_num2) || PyTypeNum_ISUNSIGNED(type_num2))) { /* Convert to the equivalent-sized signed integer */ type_num1 = type_num_unsigned_to_signed(type_num1); ret_type_num = _npy_type_promotion_table[type_num1][type_num2]; /* The table doesn't handle string/unicode/void, check the result */ if (ret_type_num >= 0) { return PyArray_DescrFromType(ret_type_num); } } return PyArray_PromoteTypes(type1, type2); } else if (is_small_unsigned2) { int type_num1 = type1->type_num; int type_num2 = type2->type_num; int ret_type_num; if (type_num1 < NPY_NTYPES && !(PyTypeNum_ISBOOL(type_num1) || PyTypeNum_ISUNSIGNED(type_num1))) { /* Convert to the equivalent-sized signed integer */ type_num2 = type_num_unsigned_to_signed(type_num2); ret_type_num = _npy_type_promotion_table[type_num1][type_num2]; /* The table doesn't handle string/unicode/void, check the result */ if (ret_type_num >= 0) { return PyArray_DescrFromType(ret_type_num); } } return PyArray_PromoteTypes(type1, type2); } else { return PyArray_PromoteTypes(type1, type2); } } /* * Returns a new reference to type if it is already NBO, otherwise * returns a copy converted to NBO. */ static PyArray_Descr * ensure_dtype_nbo(PyArray_Descr *type) { if (PyArray_ISNBO(type->byteorder)) { Py_INCREF(type); return type; } else { return PyArray_DescrNewByteorder(type, NPY_NATIVE); } } /*NUMPY_API * Produces the smallest size and lowest kind type to which both * input types can be cast. */ NPY_NO_EXPORT PyArray_Descr * PyArray_PromoteTypes(PyArray_Descr *type1, PyArray_Descr *type2) { int type_num1, type_num2, ret_type_num; type_num1 = type1->type_num; type_num2 = type2->type_num; /* If they're built-in types, use the promotion table */ if (type_num1 < NPY_NTYPES && type_num2 < NPY_NTYPES) { ret_type_num = _npy_type_promotion_table[type_num1][type_num2]; /* * The table doesn't handle string/unicode/void/datetime/timedelta, * so check the result */ if (ret_type_num >= 0) { return PyArray_DescrFromType(ret_type_num); } } /* If one or both are user defined, calculate it */ else { int skind1 = NPY_NOSCALAR, skind2 = NPY_NOSCALAR, skind; if (PyArray_CanCastTo(type2, type1)) { /* Promoted types are always native byte order */ return ensure_dtype_nbo(type1); } else if (PyArray_CanCastTo(type1, type2)) { /* Promoted types are always native byte order */ return ensure_dtype_nbo(type2); } /* Convert the 'kind' char into a scalar kind */ switch (type1->kind) { case 'b': skind1 = NPY_BOOL_SCALAR; break; case 'u': skind1 = NPY_INTPOS_SCALAR; break; case 'i': skind1 = NPY_INTNEG_SCALAR; break; case 'f': skind1 = NPY_FLOAT_SCALAR; break; case 'c': skind1 = NPY_COMPLEX_SCALAR; break; } switch (type2->kind) { case 'b': skind2 = NPY_BOOL_SCALAR; break; case 'u': skind2 = NPY_INTPOS_SCALAR; break; case 'i': skind2 = NPY_INTNEG_SCALAR; break; case 'f': skind2 = NPY_FLOAT_SCALAR; break; case 'c': skind2 = NPY_COMPLEX_SCALAR; break; } /* If both are scalars, there may be a promotion possible */ if (skind1 != NPY_NOSCALAR && skind2 != NPY_NOSCALAR) { /* Start with the larger scalar kind */ skind = (skind1 > skind2) ? skind1 : skind2; ret_type_num = _npy_smallest_type_of_kind_table[skind]; for (;;) { /* If there is no larger type of this kind, try a larger kind */ if (ret_type_num < 0) { ++skind; /* Use -1 to signal no promoted type found */ if (skind < NPY_NSCALARKINDS) { ret_type_num = _npy_smallest_type_of_kind_table[skind]; } else { break; } } /* If we found a type to which we can promote both, done! */ if (PyArray_CanCastSafely(type_num1, ret_type_num) && PyArray_CanCastSafely(type_num2, ret_type_num)) { return PyArray_DescrFromType(ret_type_num); } /* Try the next larger type of this kind */ ret_type_num = _npy_next_larger_type_table[ret_type_num]; } } PyErr_SetString(PyExc_TypeError, "invalid type promotion with custom data type"); return NULL; } switch (type_num1) { /* BOOL can convert to anything except datetime/void */ case NPY_BOOL: if (type_num2 != NPY_DATETIME && type_num2 != NPY_VOID) { return ensure_dtype_nbo(type2); } else { break; } /* For strings and unicodes, take the larger size */ case NPY_STRING: if (type_num2 == NPY_STRING) { if (type1->elsize > type2->elsize) { return ensure_dtype_nbo(type1); } else { return ensure_dtype_nbo(type2); } } else if (type_num2 == NPY_UNICODE) { if (type2->elsize >= type1->elsize * 4) { return ensure_dtype_nbo(type2); } else { PyArray_Descr *d = PyArray_DescrNewFromType(NPY_UNICODE); if (d == NULL) { return NULL; } d->elsize = type1->elsize * 4; return d; } } /* Allow NUMBER -> STRING */ else if (PyTypeNum_ISNUMBER(type_num2)) { return ensure_dtype_nbo(type1); } case NPY_UNICODE: if (type_num2 == NPY_UNICODE) { if (type1->elsize > type2->elsize) { return ensure_dtype_nbo(type1); } else { return ensure_dtype_nbo(type2); } } else if (type_num2 == NPY_STRING) { if (type1->elsize >= type2->elsize * 4) { return ensure_dtype_nbo(type1); } else { PyArray_Descr *d = PyArray_DescrNewFromType(NPY_UNICODE); if (d == NULL) { return NULL; } d->elsize = type2->elsize * 4; return d; } } /* Allow NUMBER -> UNICODE */ else if (PyTypeNum_ISNUMBER(type_num2)) { return ensure_dtype_nbo(type1); } break; case NPY_DATETIME: case NPY_TIMEDELTA: if (type_num2 == NPY_DATETIME || type_num2 == NPY_TIMEDELTA) { return datetime_type_promotion(type1, type2); } break; } switch (type_num2) { /* BOOL can convert to almost anything */ case NPY_BOOL: if (type_num1 != NPY_DATETIME && type_num1 != NPY_TIMEDELTA && type_num1 != NPY_VOID) { return ensure_dtype_nbo(type1); } else { break; } case NPY_STRING: /* Allow NUMBER -> STRING */ if (PyTypeNum_ISNUMBER(type_num1)) { return ensure_dtype_nbo(type2); } case NPY_UNICODE: /* Allow NUMBER -> UNICODE */ if (PyTypeNum_ISNUMBER(type_num1)) { return ensure_dtype_nbo(type2); } break; case NPY_TIMEDELTA: if (PyTypeNum_ISINTEGER(type_num1) || PyTypeNum_ISFLOAT(type_num1)) { return ensure_dtype_nbo(type2); } break; } /* For types equivalent up to endianness, can return either */ if (PyArray_CanCastTypeTo(type1, type2, NPY_EQUIV_CASTING)) { return ensure_dtype_nbo(type1); } /* TODO: Also combine fields, subarrays, strings, etc */ /* printf("invalid type promotion: "); PyObject_Print(type1, stdout, 0); printf(" "); PyObject_Print(type2, stdout, 0); printf("\n"); */ PyErr_SetString(PyExc_TypeError, "invalid type promotion"); return NULL; } /* * NOTE: While this is unlikely to be a performance problem, if * it is it could be reverted to a simple positive/negative * check as the previous system used. * * The is_small_unsigned output flag indicates whether it's an unsigned integer, * and would fit in a signed integer of the same bit size. */ static int min_scalar_type_num(char *valueptr, int type_num, int *is_small_unsigned) { switch (type_num) { case NPY_BOOL: { return NPY_BOOL; } case NPY_UBYTE: { npy_ubyte value = *(npy_ubyte *)valueptr; if (value <= NPY_MAX_BYTE) { *is_small_unsigned = 1; } return NPY_UBYTE; } case NPY_BYTE: { npy_byte value = *(npy_byte *)valueptr; if (value >= 0) { *is_small_unsigned = 1; return NPY_UBYTE; } break; } case NPY_USHORT: { npy_ushort value = *(npy_ushort *)valueptr; if (value <= NPY_MAX_UBYTE) { if (value <= NPY_MAX_BYTE) { *is_small_unsigned = 1; } return NPY_UBYTE; } if (value <= NPY_MAX_SHORT) { *is_small_unsigned = 1; } break; } case NPY_SHORT: { npy_short value = *(npy_short *)valueptr; if (value >= 0) { return min_scalar_type_num(valueptr, NPY_USHORT, is_small_unsigned); } else if (value >= NPY_MIN_BYTE) { return NPY_BYTE; } break; } #if NPY_SIZEOF_LONG == NPY_SIZEOF_INT case NPY_ULONG: #endif case NPY_UINT: { npy_uint value = *(npy_uint *)valueptr; if (value <= NPY_MAX_UBYTE) { if (value < NPY_MAX_BYTE) { *is_small_unsigned = 1; } return NPY_UBYTE; } else if (value <= NPY_MAX_USHORT) { if (value <= NPY_MAX_SHORT) { *is_small_unsigned = 1; } return NPY_USHORT; } if (value <= NPY_MAX_INT) { *is_small_unsigned = 1; } break; } #if NPY_SIZEOF_LONG == NPY_SIZEOF_INT case NPY_LONG: #endif case NPY_INT: { npy_int value = *(npy_int *)valueptr; if (value >= 0) { return min_scalar_type_num(valueptr, NPY_UINT, is_small_unsigned); } else if (value >= NPY_MIN_BYTE) { return NPY_BYTE; } else if (value >= NPY_MIN_SHORT) { return NPY_SHORT; } break; } #if NPY_SIZEOF_LONG != NPY_SIZEOF_INT && NPY_SIZEOF_LONG != NPY_SIZEOF_LONGLONG case NPY_ULONG: { npy_ulong value = *(npy_ulong *)valueptr; if (value <= NPY_MAX_UBYTE) { if (value <= NPY_MAX_BYTE) { *is_small_unsigned = 1; } return NPY_UBYTE; } else if (value <= NPY_MAX_USHORT) { if (value <= NPY_MAX_SHORT) { *is_small_unsigned = 1; } return NPY_USHORT; } else if (value <= NPY_MAX_UINT) { if (value <= NPY_MAX_INT) { *is_small_unsigned = 1; } return NPY_UINT; } if (value <= NPY_MAX_LONG) { *is_small_unsigned = 1; } break; } case NPY_LONG: { npy_long value = *(npy_long *)valueptr; if (value >= 0) { return min_scalar_type_num(valueptr, NPY_ULONG, is_small_unsigned); } else if (value >= NPY_MIN_BYTE) { return NPY_BYTE; } else if (value >= NPY_MIN_SHORT) { return NPY_SHORT; } else if (value >= NPY_MIN_INT) { return NPY_INT; } break; } #endif #if NPY_SIZEOF_LONG == NPY_SIZEOF_LONGLONG case NPY_ULONG: #endif case NPY_ULONGLONG: { npy_ulonglong value = *(npy_ulonglong *)valueptr; if (value <= NPY_MAX_UBYTE) { if (value <= NPY_MAX_BYTE) { *is_small_unsigned = 1; } return NPY_UBYTE; } else if (value <= NPY_MAX_USHORT) { if (value <= NPY_MAX_SHORT) { *is_small_unsigned = 1; } return NPY_USHORT; } else if (value <= NPY_MAX_UINT) { if (value <= NPY_MAX_INT) { *is_small_unsigned = 1; } return NPY_UINT; } #if NPY_SIZEOF_LONG != NPY_SIZEOF_INT && NPY_SIZEOF_LONG != NPY_SIZEOF_LONGLONG else if (value <= NPY_MAX_ULONG) { if (value <= NPY_MAX_LONG) { *is_small_unsigned = 1; } return NPY_ULONG; } #endif if (value <= NPY_MAX_LONGLONG) { *is_small_unsigned = 1; } break; } #if NPY_SIZEOF_LONG == NPY_SIZEOF_LONGLONG case NPY_LONG: #endif case NPY_LONGLONG: { npy_longlong value = *(npy_longlong *)valueptr; if (value >= 0) { return min_scalar_type_num(valueptr, NPY_ULONGLONG, is_small_unsigned); } else if (value >= NPY_MIN_BYTE) { return NPY_BYTE; } else if (value >= NPY_MIN_SHORT) { return NPY_SHORT; } else if (value >= NPY_MIN_INT) { return NPY_INT; } #if NPY_SIZEOF_LONG != NPY_SIZEOF_INT && NPY_SIZEOF_LONG != NPY_SIZEOF_LONGLONG else if (value >= NPY_MIN_LONG) { return NPY_LONG; } #endif break; } /* * Float types aren't allowed to be demoted to integer types, * but precision loss is allowed. */ case NPY_HALF: { return NPY_HALF; } case NPY_FLOAT: { float value = *(float *)valueptr; if (value > -65000 && value < 65000) { return NPY_HALF; } break; } case NPY_DOUBLE: { double value = *(double *)valueptr; if (value > -65000 && value < 65000) { return NPY_HALF; } else if (value > -3.4e38 && value < 3.4e38) { return NPY_FLOAT; } break; } case NPY_LONGDOUBLE: { npy_longdouble value = *(npy_longdouble *)valueptr; if (value > -65000 && value < 65000) { return NPY_HALF; } else if (value > -3.4e38 && value < 3.4e38) { return NPY_FLOAT; } else if (value > -1.7e308 && value < 1.7e308) { return NPY_DOUBLE; } break; } /* * The code to demote complex to float is disabled for now, * as forcing complex by adding 0j is probably desireable. */ case NPY_CFLOAT: { /* npy_cfloat value = *(npy_cfloat *)valueptr; if (value.imag == 0) { return min_scalar_type_num((char *)&value.real, NPY_FLOAT, is_small_unsigned); } */ break; } case NPY_CDOUBLE: { npy_cdouble value = *(npy_cdouble *)valueptr; /* if (value.imag == 0) { return min_scalar_type_num((char *)&value.real, NPY_DOUBLE, is_small_unsigned); } */ if (value.real > -3.4e38 && value.real < 3.4e38 && value.imag > -3.4e38 && value.imag < 3.4e38) { return NPY_CFLOAT; } break; } case NPY_CLONGDOUBLE: { npy_cdouble value = *(npy_cdouble *)valueptr; /* if (value.imag == 0) { return min_scalar_type_num((char *)&value.real, NPY_LONGDOUBLE, is_small_unsigned); } */ if (value.real > -3.4e38 && value.real < 3.4e38 && value.imag > -3.4e38 && value.imag < 3.4e38) { return NPY_CFLOAT; } else if (value.real > -1.7e308 && value.real < 1.7e308 && value.imag > -1.7e308 && value.imag < 1.7e308) { return NPY_CDOUBLE; } break; } } return type_num; } /*NUMPY_API * If arr is a scalar (has 0 dimensions) with a built-in number data type, * finds the smallest type size/kind which can still represent its data. * Otherwise, returns the array's data type. * */ NPY_NO_EXPORT PyArray_Descr * PyArray_MinScalarType(PyArrayObject *arr) { PyArray_Descr *dtype = PyArray_DESCR(arr); /* * If the array isn't a numeric scalar, just return the array's dtype. */ if (PyArray_NDIM(arr) > 0 || !PyTypeNum_ISNUMBER(dtype->type_num)) { Py_INCREF(dtype); return dtype; } else { char *data = PyArray_BYTES(arr); int swap = !PyArray_ISNBO(dtype->byteorder); int is_small_unsigned = 0; /* An aligned memory buffer large enough to hold any type */ npy_longlong value[4]; dtype->f->copyswap(&value, data, swap, NULL); return PyArray_DescrFromType( min_scalar_type_num((char *)&value, dtype->type_num, &is_small_unsigned)); } } /* * Provides an ordering for the dtype 'kind' character codes, to help * determine when to use the min_scalar_type function. This groups * 'kind' into boolean, integer, floating point, and everything else. */ static int dtype_kind_to_simplified_ordering(char kind) { switch (kind) { /* Boolean kind */ case 'b': return 0; /* Unsigned int kind */ case 'u': /* Signed int kind */ case 'i': return 1; /* Float kind */ case 'f': /* Complex kind */ case 'c': return 2; /* Anything else */ default: return 3; } } /*NUMPY_API * Produces the result type of a bunch of inputs, using the UFunc * type promotion rules. Use this function when you have a set of * input arrays, and need to determine an output array dtype. * * If all the inputs are scalars (have 0 dimensions) or the maximum "kind" * of the scalars is greater than the maximum "kind" of the arrays, does * a regular type promotion. * * Otherwise, does a type promotion on the MinScalarType * of all the inputs. Data types passed directly are treated as array * types. * */ NPY_NO_EXPORT PyArray_Descr * PyArray_ResultType(npy_intp narrs, PyArrayObject **arr, npy_intp ndtypes, PyArray_Descr **dtypes) { npy_intp i; int use_min_scalar = 0; PyArray_Descr *ret = NULL, *tmpret; int ret_is_small_unsigned = 0; /* If there's just one type, pass it through */ if (narrs + ndtypes == 1) { if (narrs == 1) { ret = PyArray_DESCR(arr[0]); } else { ret = dtypes[0]; } Py_INCREF(ret); return ret; } /* * Determine if there are any scalars, and if so, whether * the maximum "kind" of the scalars surpasses the maximum * "kind" of the arrays */ if (narrs > 0) { int all_scalars, max_scalar_kind = -1, max_array_kind = -1; int kind; all_scalars = (ndtypes > 0) ? 0 : 1; /* Compute the maximum "kinds" and whether everything is scalar */ for (i = 0; i < narrs; ++i) { if (PyArray_NDIM(arr[i]) == 0) { kind = dtype_kind_to_simplified_ordering( PyArray_DESCR(arr[i])->kind); if (kind > max_scalar_kind) { max_scalar_kind = kind; } } else { all_scalars = 0; kind = dtype_kind_to_simplified_ordering( PyArray_DESCR(arr[i])->kind); if (kind > max_array_kind) { max_array_kind = kind; } } } /* * If the max scalar kind is bigger than the max array kind, * finish computing the max array kind */ for (i = 0; i < ndtypes; ++i) { kind = dtype_kind_to_simplified_ordering(dtypes[i]->kind); if (kind > max_array_kind) { max_array_kind = kind; } } /* Indicate whether to use the min_scalar_type function */ if (!all_scalars && max_array_kind >= max_scalar_kind) { use_min_scalar = 1; } } /* Loop through all the types, promoting them */ if (!use_min_scalar) { for (i = 0; i < narrs; ++i) { PyArray_Descr *tmp = PyArray_DESCR(arr[i]); /* Combine it with the existing type */ if (ret == NULL) { ret = tmp; Py_INCREF(ret); } else { /* Only call promote if the types aren't the same dtype */ if (tmp != ret || !PyArray_ISNBO(ret->byteorder)) { tmpret = PyArray_PromoteTypes(tmp, ret); Py_DECREF(ret); ret = tmpret; if (ret == NULL) { return NULL; } } } } for (i = 0; i < ndtypes; ++i) { PyArray_Descr *tmp = dtypes[i]; /* Combine it with the existing type */ if (ret == NULL) { ret = tmp; Py_INCREF(ret); } else { /* Only call promote if the types aren't the same dtype */ if (tmp != ret || !PyArray_ISNBO(tmp->byteorder)) { tmpret = PyArray_PromoteTypes(tmp, ret); Py_DECREF(ret); ret = tmpret; if (ret == NULL) { return NULL; } } } } } else { for (i = 0; i < narrs; ++i) { /* Get the min scalar type for the array */ PyArray_Descr *tmp = PyArray_DESCR(arr[i]); int tmp_is_small_unsigned = 0; /* * If it's a scalar, find the min scalar type. The function * is expanded here so that we can flag whether we've got an * unsigned integer which would fit an a signed integer * of the same size, something not exposed in the public API. */ if (PyArray_NDIM(arr[i]) == 0 && PyTypeNum_ISNUMBER(tmp->type_num)) { char *data = PyArray_BYTES(arr[i]); int swap = !PyArray_ISNBO(tmp->byteorder); int type_num; /* An aligned memory buffer large enough to hold any type */ npy_longlong value[4]; tmp->f->copyswap(&value, data, swap, NULL); type_num = min_scalar_type_num((char *)&value, tmp->type_num, &tmp_is_small_unsigned); tmp = PyArray_DescrFromType(type_num); if (tmp == NULL) { Py_XDECREF(ret); return NULL; } } else { Py_INCREF(tmp); } /* Combine it with the existing type */ if (ret == NULL) { ret = tmp; ret_is_small_unsigned = tmp_is_small_unsigned; } else { #if 0 printf("promoting type "); PyObject_Print(tmp, stdout, 0); printf(" (%d) ", tmp_is_small_unsigned); PyObject_Print(ret, stdout, 0); printf(" (%d) ", ret_is_small_unsigned); printf("\n"); #endif /* If they point to the same type, don't call promote */ if (tmp == ret && PyArray_ISNBO(tmp->byteorder)) { Py_DECREF(tmp); } else { tmpret = promote_types(tmp, ret, tmp_is_small_unsigned, ret_is_small_unsigned); if (tmpret == NULL) { Py_DECREF(tmp); Py_DECREF(ret); return NULL; } Py_DECREF(tmp); Py_DECREF(ret); ret = tmpret; } ret_is_small_unsigned = tmp_is_small_unsigned && ret_is_small_unsigned; } } for (i = 0; i < ndtypes; ++i) { PyArray_Descr *tmp = dtypes[i]; /* Combine it with the existing type */ if (ret == NULL) { ret = tmp; Py_INCREF(ret); } else { /* Only call promote if the types aren't the same dtype */ if (tmp != ret || !PyArray_ISNBO(tmp->byteorder)) { if (ret_is_small_unsigned) { tmpret = promote_types(tmp, ret, 0, ret_is_small_unsigned); if (tmpret == NULL) { Py_DECREF(tmp); Py_DECREF(ret); return NULL; } } else { tmpret = PyArray_PromoteTypes(tmp, ret); } Py_DECREF(ret); ret = tmpret; if (ret == NULL) { return NULL; } } } } } if (ret == NULL) { PyErr_SetString(PyExc_TypeError, "no arrays or types available to calculate result type"); } return ret; } /*NUMPY_API * Is the typenum valid? */ NPY_NO_EXPORT int PyArray_ValidType(int type) { PyArray_Descr *descr; int res=NPY_TRUE; descr = PyArray_DescrFromType(type); if (descr == NULL) { res = NPY_FALSE; } Py_DECREF(descr); return res; } /* Backward compatibility only */ /* In both Zero and One ***You must free the memory once you are done with it using PyDataMem_FREE(ptr) or you create a memory leak*** If arr is an Object array you are getting a BORROWED reference to Zero or One. Do not DECREF. Please INCREF if you will be hanging on to it. The memory for the ptr still must be freed in any case; */ static int _check_object_rec(PyArray_Descr *descr) { if (PyDataType_HASFIELDS(descr) && PyDataType_REFCHK(descr)) { PyErr_SetString(PyExc_TypeError, "Not supported for this data-type."); return -1; } return 0; } /*NUMPY_API Get pointer to zero of correct type for array. */ NPY_NO_EXPORT char * PyArray_Zero(PyArrayObject *arr) { char *zeroval; int ret, storeflags; PyObject *obj; if (_check_object_rec(PyArray_DESCR(arr)) < 0) { return NULL; } zeroval = PyDataMem_NEW(PyArray_DESCR(arr)->elsize); if (zeroval == NULL) { PyErr_SetNone(PyExc_MemoryError); return NULL; } obj=PyInt_FromLong((long) 0); if (PyArray_ISOBJECT(arr)) { memcpy(zeroval, &obj, sizeof(PyObject *)); Py_DECREF(obj); return zeroval; } storeflags = PyArray_FLAGS(arr); PyArray_ENABLEFLAGS(arr, NPY_ARRAY_BEHAVED); ret = PyArray_DESCR(arr)->f->setitem(obj, zeroval, arr); ((PyArrayObject_fields *)arr)->flags = storeflags; Py_DECREF(obj); if (ret < 0) { PyDataMem_FREE(zeroval); return NULL; } return zeroval; } /*NUMPY_API Get pointer to one of correct type for array */ NPY_NO_EXPORT char * PyArray_One(PyArrayObject *arr) { char *oneval; int ret, storeflags; PyObject *obj; if (_check_object_rec(PyArray_DESCR(arr)) < 0) { return NULL; } oneval = PyDataMem_NEW(PyArray_DESCR(arr)->elsize); if (oneval == NULL) { PyErr_SetNone(PyExc_MemoryError); return NULL; } obj = PyInt_FromLong((long) 1); if (PyArray_ISOBJECT(arr)) { memcpy(oneval, &obj, sizeof(PyObject *)); Py_DECREF(obj); return oneval; } storeflags = PyArray_FLAGS(arr); PyArray_ENABLEFLAGS(arr, NPY_ARRAY_BEHAVED); ret = PyArray_DESCR(arr)->f->setitem(obj, oneval, arr); ((PyArrayObject_fields *)arr)->flags = storeflags; Py_DECREF(obj); if (ret < 0) { PyDataMem_FREE(oneval); return NULL; } return oneval; } /* End deprecated */ /*NUMPY_API * Return the typecode of the array a Python object would be converted to * * Returns the type number the result should have, or NPY_NOTYPE on error. */ NPY_NO_EXPORT int PyArray_ObjectType(PyObject *op, int minimum_type) { PyArray_Descr *dtype = NULL; int ret; if (minimum_type != NPY_NOTYPE && minimum_type >= 0) { dtype = PyArray_DescrFromType(minimum_type); if (dtype == NULL) { return NPY_NOTYPE; } } if (PyArray_DTypeFromObject(op, NPY_MAXDIMS, &dtype) < 0) { return NPY_NOTYPE; } if (dtype == NULL) { ret = NPY_DEFAULT_TYPE; } else { ret = dtype->type_num; } Py_XDECREF(dtype); return ret; } /* Raises error when len(op) == 0 */ /*NUMPY_API*/ NPY_NO_EXPORT PyArrayObject ** PyArray_ConvertToCommonType(PyObject *op, int *retn) { int i, n, allscalars = 0; PyArrayObject **mps = NULL; PyObject *otmp; PyArray_Descr *intype = NULL, *stype = NULL; PyArray_Descr *newtype = NULL; NPY_SCALARKIND scalarkind = NPY_NOSCALAR, intypekind = NPY_NOSCALAR; *retn = n = PySequence_Length(op); if (n == 0) { PyErr_SetString(PyExc_ValueError, "0-length sequence."); } if (PyErr_Occurred()) { *retn = 0; return NULL; } mps = (PyArrayObject **)PyDataMem_NEW(n*sizeof(PyArrayObject *)); if (mps == NULL) { *retn = 0; return (void*)PyErr_NoMemory(); } if (PyArray_Check(op)) { for (i = 0; i < n; i++) { mps[i] = (PyArrayObject *) array_item_asarray((PyArrayObject *)op, i); } if (!PyArray_ISCARRAY((PyArrayObject *)op)) { for (i = 0; i < n; i++) { PyObject *obj; obj = PyArray_NewCopy(mps[i], NPY_CORDER); Py_DECREF(mps[i]); mps[i] = (PyArrayObject *)obj; } } return mps; } for (i = 0; i < n; i++) { mps[i] = NULL; } for (i = 0; i < n; i++) { otmp = PySequence_GetItem(op, i); if (!PyArray_CheckAnyScalar(otmp)) { newtype = PyArray_DescrFromObject(otmp, intype); Py_XDECREF(intype); if (newtype == NULL) { goto fail; } intype = newtype; intypekind = PyArray_ScalarKind(intype->type_num, NULL); } else { newtype = PyArray_DescrFromObject(otmp, stype); Py_XDECREF(stype); if (newtype == NULL) { goto fail; } stype = newtype; scalarkind = PyArray_ScalarKind(newtype->type_num, NULL); mps[i] = (PyArrayObject *)Py_None; Py_INCREF(Py_None); } Py_XDECREF(otmp); } if (intype == NULL) { /* all scalars */ allscalars = 1; intype = stype; Py_INCREF(intype); for (i = 0; i < n; i++) { Py_XDECREF(mps[i]); mps[i] = NULL; } } else if ((stype != NULL) && (intypekind != scalarkind)) { /* * we need to upconvert to type that * handles both intype and stype * also don't forcecast the scalars. */ if (!PyArray_CanCoerceScalar(stype->type_num, intype->type_num, scalarkind)) { newtype = PyArray_PromoteTypes(intype, stype); Py_XDECREF(intype); intype = newtype; } for (i = 0; i < n; i++) { Py_XDECREF(mps[i]); mps[i] = NULL; } } /* Make sure all arrays are actual array objects. */ for (i = 0; i < n; i++) { int flags = NPY_ARRAY_CARRAY; if ((otmp = PySequence_GetItem(op, i)) == NULL) { goto fail; } if (!allscalars && ((PyObject *)(mps[i]) == Py_None)) { /* forcecast scalars */ flags |= NPY_ARRAY_FORCECAST; Py_DECREF(Py_None); } Py_INCREF(intype); mps[i] = (PyArrayObject*) PyArray_FromAny(otmp, intype, 0, 0, flags, NULL); Py_DECREF(otmp); if (mps[i] == NULL) { goto fail; } } Py_DECREF(intype); Py_XDECREF(stype); return mps; fail: Py_XDECREF(intype); Py_XDECREF(stype); *retn = 0; for (i = 0; i < n; i++) { Py_XDECREF(mps[i]); } PyDataMem_FREE(mps); return NULL; } numpy-1.8.2/numpy/core/src/multiarray/refcount.h0000664000175100017510000000063612370216242023106 0ustar vagrantvagrant00000000000000#ifndef _NPY_PRIVATE_REFCOUNT_H_ #define _NPY_PRIVATE_REFCOUNT_H_ NPY_NO_EXPORT void PyArray_Item_INCREF(char *data, PyArray_Descr *descr); NPY_NO_EXPORT void PyArray_Item_XDECREF(char *data, PyArray_Descr *descr); NPY_NO_EXPORT int PyArray_INCREF(PyArrayObject *mp); NPY_NO_EXPORT int PyArray_XDECREF(PyArrayObject *mp); NPY_NO_EXPORT void PyArray_FillObjectArray(PyArrayObject *arr, PyObject *obj); #endif numpy-1.8.2/numpy/core/src/multiarray/calculation.c0000664000175100017510000007630212370216243023556 0ustar vagrantvagrant00000000000000#define PY_SSIZE_T_CLEAN #include #include "structmember.h" #define NPY_NO_DEPRECATED_API NPY_API_VERSION #define _MULTIARRAYMODULE #include "numpy/arrayobject.h" #include "npy_config.h" #include "npy_pycompat.h" #include "common.h" #include "number.h" #include "calculation.h" #include "array_assign.h" static double power_of_ten(int n) { static const double p10[] = {1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8}; double ret; if (n < 9) { ret = p10[n]; } else { ret = 1e9; while (n-- > 9) { ret *= 10.; } } return ret; } /*NUMPY_API * ArgMax */ NPY_NO_EXPORT PyObject * PyArray_ArgMax(PyArrayObject *op, int axis, PyArrayObject *out) { PyArrayObject *ap = NULL, *rp = NULL; PyArray_ArgFunc* arg_func; char *ip; npy_intp *rptr; npy_intp i, n, m; int elsize; NPY_BEGIN_THREADS_DEF; if ((ap = (PyArrayObject *)PyArray_CheckAxis(op, &axis, 0)) == NULL) { return NULL; } /* * We need to permute the array so that axis is placed at the end. * And all other dimensions are shifted left. */ if (axis != PyArray_NDIM(ap)-1) { PyArray_Dims newaxes; npy_intp dims[NPY_MAXDIMS]; int j; newaxes.ptr = dims; newaxes.len = PyArray_NDIM(ap); for (j = 0; j < axis; j++) { dims[j] = j; } for (j = axis; j < PyArray_NDIM(ap) - 1; j++) { dims[j] = j + 1; } dims[PyArray_NDIM(ap) - 1] = axis; op = (PyArrayObject *)PyArray_Transpose(ap, &newaxes); Py_DECREF(ap); if (op == NULL) { return NULL; } } else { op = ap; } /* Will get native-byte order contiguous copy. */ ap = (PyArrayObject *)PyArray_ContiguousFromAny((PyObject *)op, PyArray_DESCR(op)->type_num, 1, 0); Py_DECREF(op); if (ap == NULL) { return NULL; } arg_func = PyArray_DESCR(ap)->f->argmax; if (arg_func == NULL) { PyErr_SetString(PyExc_TypeError, "data type not ordered"); goto fail; } elsize = PyArray_DESCR(ap)->elsize; m = PyArray_DIMS(ap)[PyArray_NDIM(ap)-1]; if (m == 0) { PyErr_SetString(PyExc_ValueError, "attempt to get argmax of an empty sequence"); goto fail; } if (!out) { rp = (PyArrayObject *)PyArray_New(Py_TYPE(ap), PyArray_NDIM(ap)-1, PyArray_DIMS(ap), NPY_INTP, NULL, NULL, 0, 0, (PyObject *)ap); if (rp == NULL) { goto fail; } } else { if (PyArray_SIZE(out) != PyArray_MultiplyList(PyArray_DIMS(ap), PyArray_NDIM(ap) - 1)) { PyErr_SetString(PyExc_TypeError, "invalid shape for output array."); } rp = (PyArrayObject *)PyArray_FromArray(out, PyArray_DescrFromType(NPY_INTP), NPY_ARRAY_CARRAY | NPY_ARRAY_UPDATEIFCOPY); if (rp == NULL) { goto fail; } } NPY_BEGIN_THREADS_DESCR(PyArray_DESCR(ap)); n = PyArray_SIZE(ap)/m; rptr = (npy_intp *)PyArray_DATA(rp); for (ip = PyArray_DATA(ap), i = 0; i < n; i++, ip += elsize*m) { arg_func(ip, m, rptr, ap); rptr += 1; } NPY_END_THREADS_DESCR(PyArray_DESCR(ap)); Py_DECREF(ap); /* Trigger the UPDATEIFCOPY if necessary */ if (out != NULL && out != rp) { Py_DECREF(rp); rp = out; Py_INCREF(rp); } return (PyObject *)rp; fail: Py_DECREF(ap); Py_XDECREF(rp); return NULL; } /*NUMPY_API * ArgMin */ NPY_NO_EXPORT PyObject * PyArray_ArgMin(PyArrayObject *op, int axis, PyArrayObject *out) { PyArrayObject *ap = NULL, *rp = NULL; PyArray_ArgFunc* arg_func; char *ip; npy_intp *rptr; npy_intp i, n, m; int elsize; NPY_BEGIN_THREADS_DEF; if ((ap = (PyArrayObject *)PyArray_CheckAxis(op, &axis, 0)) == NULL) { return NULL; } /* * We need to permute the array so that axis is placed at the end. * And all other dimensions are shifted left. */ if (axis != PyArray_NDIM(ap)-1) { PyArray_Dims newaxes; npy_intp dims[NPY_MAXDIMS]; int i; newaxes.ptr = dims; newaxes.len = PyArray_NDIM(ap); for (i = 0; i < axis; i++) { dims[i] = i; } for (i = axis; i < PyArray_NDIM(ap) - 1; i++) { dims[i] = i + 1; } dims[PyArray_NDIM(ap) - 1] = axis; op = (PyArrayObject *)PyArray_Transpose(ap, &newaxes); Py_DECREF(ap); if (op == NULL) { return NULL; } } else { op = ap; } /* Will get native-byte order contiguous copy. */ ap = (PyArrayObject *)PyArray_ContiguousFromAny((PyObject *)op, PyArray_DESCR(op)->type_num, 1, 0); Py_DECREF(op); if (ap == NULL) { return NULL; } arg_func = PyArray_DESCR(ap)->f->argmin; if (arg_func == NULL) { PyErr_SetString(PyExc_TypeError, "data type not ordered"); goto fail; } elsize = PyArray_DESCR(ap)->elsize; m = PyArray_DIMS(ap)[PyArray_NDIM(ap)-1]; if (m == 0) { PyErr_SetString(PyExc_ValueError, "attempt to get argmin of an empty sequence"); goto fail; } if (!out) { rp = (PyArrayObject *)PyArray_New(Py_TYPE(ap), PyArray_NDIM(ap)-1, PyArray_DIMS(ap), NPY_INTP, NULL, NULL, 0, 0, (PyObject *)ap); if (rp == NULL) { goto fail; } } else { if (PyArray_SIZE(out) != PyArray_MultiplyList(PyArray_DIMS(ap), PyArray_NDIM(ap) - 1)) { PyErr_SetString(PyExc_TypeError, "invalid shape for output array."); } rp = (PyArrayObject *)PyArray_FromArray(out, PyArray_DescrFromType(NPY_INTP), NPY_ARRAY_CARRAY | NPY_ARRAY_UPDATEIFCOPY); if (rp == NULL) { goto fail; } } NPY_BEGIN_THREADS_DESCR(PyArray_DESCR(ap)); n = PyArray_SIZE(ap)/m; rptr = (npy_intp *)PyArray_DATA(rp); for (ip = PyArray_DATA(ap), i = 0; i < n; i++, ip += elsize*m) { arg_func(ip, m, rptr, ap); rptr += 1; } NPY_END_THREADS_DESCR(PyArray_DESCR(ap)); Py_DECREF(ap); /* Trigger the UPDATEIFCOPY if necessary */ if (out != NULL && out != rp) { Py_DECREF(rp); rp = out; Py_INCREF(rp); } return (PyObject *)rp; fail: Py_DECREF(ap); Py_XDECREF(rp); return NULL; } /*NUMPY_API * Max */ NPY_NO_EXPORT PyObject * PyArray_Max(PyArrayObject *ap, int axis, PyArrayObject *out) { PyArrayObject *arr; PyObject *ret; arr = (PyArrayObject *)PyArray_CheckAxis(ap, &axis, 0); if (arr == NULL) { return NULL; } ret = PyArray_GenericReduceFunction(arr, n_ops.maximum, axis, PyArray_DESCR(arr)->type_num, out); Py_DECREF(arr); return ret; } /*NUMPY_API * Min */ NPY_NO_EXPORT PyObject * PyArray_Min(PyArrayObject *ap, int axis, PyArrayObject *out) { PyArrayObject *arr; PyObject *ret; arr=(PyArrayObject *)PyArray_CheckAxis(ap, &axis, 0); if (arr == NULL) { return NULL; } ret = PyArray_GenericReduceFunction(arr, n_ops.minimum, axis, PyArray_DESCR(arr)->type_num, out); Py_DECREF(arr); return ret; } /*NUMPY_API * Ptp */ NPY_NO_EXPORT PyObject * PyArray_Ptp(PyArrayObject *ap, int axis, PyArrayObject *out) { PyArrayObject *arr; PyObject *ret; PyObject *obj1 = NULL, *obj2 = NULL; arr=(PyArrayObject *)PyArray_CheckAxis(ap, &axis, 0); if (arr == NULL) { return NULL; } obj1 = PyArray_Max(arr, axis, out); if (obj1 == NULL) { goto fail; } obj2 = PyArray_Min(arr, axis, NULL); if (obj2 == NULL) { goto fail; } Py_DECREF(arr); if (out) { ret = PyObject_CallFunction(n_ops.subtract, "OOO", out, obj2, out); } else { ret = PyNumber_Subtract(obj1, obj2); } Py_DECREF(obj1); Py_DECREF(obj2); return ret; fail: Py_XDECREF(arr); Py_XDECREF(obj1); Py_XDECREF(obj2); return NULL; } /*NUMPY_API * Set variance to 1 to by-pass square-root calculation and return variance * Std */ NPY_NO_EXPORT PyObject * PyArray_Std(PyArrayObject *self, int axis, int rtype, PyArrayObject *out, int variance) { return __New_PyArray_Std(self, axis, rtype, out, variance, 0); } NPY_NO_EXPORT PyObject * __New_PyArray_Std(PyArrayObject *self, int axis, int rtype, PyArrayObject *out, int variance, int num) { PyObject *obj1 = NULL, *obj2 = NULL, *obj3 = NULL; PyArrayObject *arr1 = NULL, *arr2 = NULL, *arrnew = NULL; PyObject *ret = NULL, *newshape = NULL; int i, n; npy_intp val; arrnew = (PyArrayObject *)PyArray_CheckAxis(self, &axis, 0); if (arrnew == NULL) { return NULL; } /* Compute and reshape mean */ arr1 = (PyArrayObject *)PyArray_EnsureAnyArray( PyArray_Mean(arrnew, axis, rtype, NULL)); if (arr1 == NULL) { Py_DECREF(arrnew); return NULL; } n = PyArray_NDIM(arrnew); newshape = PyTuple_New(n); if (newshape == NULL) { Py_DECREF(arr1); Py_DECREF(arrnew); return NULL; } for (i = 0; i < n; i++) { if (i == axis) { val = 1; } else { val = PyArray_DIM(arrnew,i); } PyTuple_SET_ITEM(newshape, i, PyInt_FromLong((long)val)); } arr2 = (PyArrayObject *)PyArray_Reshape(arr1, newshape); Py_DECREF(arr1); Py_DECREF(newshape); if (arr2 == NULL) { Py_DECREF(arrnew); return NULL; } /* Compute x = x - mx */ arr1 = (PyArrayObject *)PyArray_EnsureAnyArray( PyNumber_Subtract((PyObject *)arrnew, (PyObject *)arr2)); Py_DECREF(arr2); if (arr1 == NULL) { Py_DECREF(arrnew); return NULL; } /* Compute x * x */ if (PyArray_ISCOMPLEX(arr1)) { obj3 = PyArray_Conjugate(arr1, NULL); } else { obj3 = (PyObject *)arr1; Py_INCREF(arr1); } if (obj3 == NULL) { Py_DECREF(arrnew); return NULL; } arr2 = (PyArrayObject *)PyArray_EnsureAnyArray( PyArray_GenericBinaryFunction(arr1, obj3, n_ops.multiply)); Py_DECREF(arr1); Py_DECREF(obj3); if (arr2 == NULL) { Py_DECREF(arrnew); return NULL; } if (PyArray_ISCOMPLEX(arr2)) { obj3 = PyObject_GetAttrString((PyObject *)arr2, "real"); switch(rtype) { case NPY_CDOUBLE: rtype = NPY_DOUBLE; break; case NPY_CFLOAT: rtype = NPY_FLOAT; break; case NPY_CLONGDOUBLE: rtype = NPY_LONGDOUBLE; break; } } else { obj3 = (PyObject *)arr2; Py_INCREF(arr2); } if (obj3 == NULL) { Py_DECREF(arrnew); return NULL; } /* Compute add.reduce(x*x,axis) */ obj1 = PyArray_GenericReduceFunction((PyArrayObject *)obj3, n_ops.add, axis, rtype, NULL); Py_DECREF(obj3); Py_DECREF(arr2); if (obj1 == NULL) { Py_DECREF(arrnew); return NULL; } n = PyArray_DIM(arrnew,axis); Py_DECREF(arrnew); n = (n-num); if (n == 0) { n = 1; } obj2 = PyFloat_FromDouble(1.0/((double )n)); if (obj2 == NULL) { Py_DECREF(obj1); return NULL; } ret = PyNumber_Multiply(obj1, obj2); Py_DECREF(obj1); Py_DECREF(obj2); if (!variance) { arr1 = (PyArrayObject *)PyArray_EnsureAnyArray(ret); /* sqrt() */ ret = PyArray_GenericUnaryFunction(arr1, n_ops.sqrt); Py_DECREF(arr1); } if (ret == NULL) { return NULL; } if (PyArray_CheckExact(self)) { goto finish; } if (PyArray_Check(self) && Py_TYPE(self) == Py_TYPE(ret)) { goto finish; } arr1 = (PyArrayObject *)PyArray_EnsureArray(ret); if (arr1 == NULL) { return NULL; } ret = PyArray_View(arr1, NULL, Py_TYPE(self)); Py_DECREF(arr1); finish: if (out) { if (PyArray_AssignArray(out, (PyArrayObject *)ret, NULL, NPY_DEFAULT_ASSIGN_CASTING) < 0) { Py_DECREF(ret); return NULL; } Py_DECREF(ret); Py_INCREF(out); return (PyObject *)out; } return ret; } /*NUMPY_API *Sum */ NPY_NO_EXPORT PyObject * PyArray_Sum(PyArrayObject *self, int axis, int rtype, PyArrayObject *out) { PyObject *arr, *ret; arr = PyArray_CheckAxis(self, &axis, 0); if (arr == NULL) { return NULL; } ret = PyArray_GenericReduceFunction((PyArrayObject *)arr, n_ops.add, axis, rtype, out); Py_DECREF(arr); return ret; } /*NUMPY_API * Prod */ NPY_NO_EXPORT PyObject * PyArray_Prod(PyArrayObject *self, int axis, int rtype, PyArrayObject *out) { PyObject *arr, *ret; arr = PyArray_CheckAxis(self, &axis, 0); if (arr == NULL) { return NULL; } ret = PyArray_GenericReduceFunction((PyArrayObject *)arr, n_ops.multiply, axis, rtype, out); Py_DECREF(arr); return ret; } /*NUMPY_API *CumSum */ NPY_NO_EXPORT PyObject * PyArray_CumSum(PyArrayObject *self, int axis, int rtype, PyArrayObject *out) { PyObject *arr, *ret; arr = PyArray_CheckAxis(self, &axis, 0); if (arr == NULL) { return NULL; } ret = PyArray_GenericAccumulateFunction((PyArrayObject *)arr, n_ops.add, axis, rtype, out); Py_DECREF(arr); return ret; } /*NUMPY_API * CumProd */ NPY_NO_EXPORT PyObject * PyArray_CumProd(PyArrayObject *self, int axis, int rtype, PyArrayObject *out) { PyObject *arr, *ret; arr = PyArray_CheckAxis(self, &axis, 0); if (arr == NULL) { return NULL; } ret = PyArray_GenericAccumulateFunction((PyArrayObject *)arr, n_ops.multiply, axis, rtype, out); Py_DECREF(arr); return ret; } /*NUMPY_API * Round */ NPY_NO_EXPORT PyObject * PyArray_Round(PyArrayObject *a, int decimals, PyArrayObject *out) { PyObject *f, *ret = NULL, *tmp, *op1, *op2; int ret_int=0; PyArray_Descr *my_descr; if (out && (PyArray_SIZE(out) != PyArray_SIZE(a))) { PyErr_SetString(PyExc_ValueError, "invalid output shape"); return NULL; } if (PyArray_ISCOMPLEX(a)) { PyObject *part; PyObject *round_part; PyObject *arr; int res; if (out) { arr = (PyObject *)out; Py_INCREF(arr); } else { arr = PyArray_Copy(a); if (arr == NULL) { return NULL; } } /* arr.real = a.real.round(decimals) */ part = PyObject_GetAttrString(arr, "real"); if (part == NULL) { Py_DECREF(arr); return NULL; } part = PyArray_EnsureAnyArray(part); round_part = PyArray_Round((PyArrayObject *)part, decimals, NULL); Py_DECREF(part); if (round_part == NULL) { Py_DECREF(arr); return NULL; } res = PyObject_SetAttrString(arr, "real", round_part); Py_DECREF(round_part); if (res < 0) { Py_DECREF(arr); return NULL; } /* arr.imag = a.imag.round(decimals) */ part = PyObject_GetAttrString(arr, "imag"); if (part == NULL) { Py_DECREF(arr); return NULL; } part = PyArray_EnsureAnyArray(part); round_part = PyArray_Round((PyArrayObject *)part, decimals, NULL); Py_DECREF(part); if (round_part == NULL) { Py_DECREF(arr); return NULL; } res = PyObject_SetAttrString(arr, "imag", round_part); Py_DECREF(round_part); if (res < 0) { Py_DECREF(arr); return NULL; } return arr; } /* do the most common case first */ if (decimals >= 0) { if (PyArray_ISINTEGER(a)) { if (out) { if (PyArray_AssignArray(out, a, NULL, NPY_DEFAULT_ASSIGN_CASTING) < 0) { return NULL; } Py_INCREF(out); return (PyObject *)out; } else { Py_INCREF(a); return (PyObject *)a; } } if (decimals == 0) { if (out) { return PyObject_CallFunction(n_ops.rint, "OO", a, out); } return PyObject_CallFunction(n_ops.rint, "O", a); } op1 = n_ops.multiply; op2 = n_ops.true_divide; } else { op1 = n_ops.true_divide; op2 = n_ops.multiply; decimals = -decimals; } if (!out) { if (PyArray_ISINTEGER(a)) { ret_int = 1; my_descr = PyArray_DescrFromType(NPY_DOUBLE); } else { Py_INCREF(PyArray_DESCR(a)); my_descr = PyArray_DESCR(a); } out = (PyArrayObject *)PyArray_Empty(PyArray_NDIM(a), PyArray_DIMS(a), my_descr, PyArray_ISFORTRAN(a)); if (out == NULL) { return NULL; } } else { Py_INCREF(out); } f = PyFloat_FromDouble(power_of_ten(decimals)); if (f == NULL) { return NULL; } ret = PyObject_CallFunction(op1, "OOO", a, f, out); if (ret == NULL) { goto finish; } tmp = PyObject_CallFunction(n_ops.rint, "OO", ret, ret); if (tmp == NULL) { Py_DECREF(ret); ret = NULL; goto finish; } Py_DECREF(tmp); tmp = PyObject_CallFunction(op2, "OOO", ret, f, ret); if (tmp == NULL) { Py_DECREF(ret); ret = NULL; goto finish; } Py_DECREF(tmp); finish: Py_DECREF(f); Py_DECREF(out); if (ret_int) { Py_INCREF(PyArray_DESCR(a)); tmp = PyArray_CastToType((PyArrayObject *)ret, PyArray_DESCR(a), PyArray_ISFORTRAN(a)); Py_DECREF(ret); return tmp; } return ret; } /*NUMPY_API * Mean */ NPY_NO_EXPORT PyObject * PyArray_Mean(PyArrayObject *self, int axis, int rtype, PyArrayObject *out) { PyObject *obj1 = NULL, *obj2 = NULL, *ret; PyArrayObject *arr; arr = (PyArrayObject *)PyArray_CheckAxis(self, &axis, 0); if (arr == NULL) { return NULL; } obj1 = PyArray_GenericReduceFunction(arr, n_ops.add, axis, rtype, out); obj2 = PyFloat_FromDouble((double)PyArray_DIM(arr,axis)); Py_DECREF(arr); if (obj1 == NULL || obj2 == NULL) { Py_XDECREF(obj1); Py_XDECREF(obj2); return NULL; } if (!out) { #if defined(NPY_PY3K) ret = PyNumber_TrueDivide(obj1, obj2); #else ret = PyNumber_Divide(obj1, obj2); #endif } else { ret = PyObject_CallFunction(n_ops.divide, "OOO", out, obj2, out); } Py_DECREF(obj1); Py_DECREF(obj2); return ret; } /*NUMPY_API * Any */ NPY_NO_EXPORT PyObject * PyArray_Any(PyArrayObject *self, int axis, PyArrayObject *out) { PyObject *arr, *ret; arr = PyArray_CheckAxis(self, &axis, 0); if (arr == NULL) { return NULL; } ret = PyArray_GenericReduceFunction((PyArrayObject *)arr, n_ops.logical_or, axis, NPY_BOOL, out); Py_DECREF(arr); return ret; } /*NUMPY_API * All */ NPY_NO_EXPORT PyObject * PyArray_All(PyArrayObject *self, int axis, PyArrayObject *out) { PyObject *arr, *ret; arr = PyArray_CheckAxis(self, &axis, 0); if (arr == NULL) { return NULL; } ret = PyArray_GenericReduceFunction((PyArrayObject *)arr, n_ops.logical_and, axis, NPY_BOOL, out); Py_DECREF(arr); return ret; } static PyObject * _GenericBinaryOutFunction(PyArrayObject *m1, PyObject *m2, PyArrayObject *out, PyObject *op) { if (out == NULL) { return PyObject_CallFunction(op, "OO", m1, m2); } else { PyObject *args, *kw, *ret; args = Py_BuildValue("OOO", m1, m2, out); if (args == NULL) { return NULL; } kw = PyDict_New(); if (kw == NULL) { Py_DECREF(args); return NULL; } if (PyDict_SetItemString(kw, "casting", PyUString_FromString("unsafe")) < 0) { Py_DECREF(args); Py_DECREF(kw); return NULL; } ret = PyObject_Call(op, args, kw); Py_DECREF(args); Py_DECREF(kw); return ret; } } static PyObject * _slow_array_clip(PyArrayObject *self, PyObject *min, PyObject *max, PyArrayObject *out) { PyObject *res1=NULL, *res2=NULL; if (max != NULL) { res1 = _GenericBinaryOutFunction(self, max, out, n_ops.minimum); if (res1 == NULL) { return NULL; } } else { res1 = (PyObject *)self; Py_INCREF(res1); } if (min != NULL) { res2 = _GenericBinaryOutFunction((PyArrayObject *)res1, min, out, n_ops.maximum); if (res2 == NULL) { Py_XDECREF(res1); return NULL; } } else { res2 = res1; Py_INCREF(res2); } Py_DECREF(res1); return res2; } /*NUMPY_API * Clip */ NPY_NO_EXPORT PyObject * PyArray_Clip(PyArrayObject *self, PyObject *min, PyObject *max, PyArrayObject *out) { PyArray_FastClipFunc *func; int outgood = 0, ingood = 0; PyArrayObject *maxa = NULL; PyArrayObject *mina = NULL; PyArrayObject *newout = NULL, *newin = NULL; PyArray_Descr *indescr = NULL, *newdescr = NULL; char *max_data, *min_data; PyObject *zero; /* Treat None the same as NULL */ if (min == Py_None) { min = NULL; } if (max == Py_None) { max = NULL; } if ((max == NULL) && (min == NULL)) { PyErr_SetString(PyExc_ValueError, "array_clip: must set either max or min"); return NULL; } func = PyArray_DESCR(self)->f->fastclip; if (func == NULL || (min != NULL && !PyArray_CheckAnyScalar(min)) || (max != NULL && !PyArray_CheckAnyScalar(max))) { return _slow_array_clip(self, min, max, out); } /* Use the fast scalar clip function */ /* First we need to figure out the correct type */ if (min != NULL) { indescr = PyArray_DescrFromObject(min, NULL); if (indescr == NULL) { goto fail; } } if (max != NULL) { newdescr = PyArray_DescrFromObject(max, indescr); Py_XDECREF(indescr); indescr = NULL; if (newdescr == NULL) { goto fail; } } else { /* Steal the reference */ newdescr = indescr; indescr = NULL; } /* * Use the scalar descriptor only if it is of a bigger * KIND than the input array (and then find the * type that matches both). */ if (PyArray_ScalarKind(newdescr->type_num, NULL) > PyArray_ScalarKind(PyArray_DESCR(self)->type_num, NULL)) { indescr = PyArray_PromoteTypes(newdescr, PyArray_DESCR(self)); if (indescr == NULL) { goto fail; } func = indescr->f->fastclip; if (func == NULL) { Py_DECREF(indescr); return _slow_array_clip(self, min, max, out); } } else { indescr = PyArray_DESCR(self); Py_INCREF(indescr); } Py_DECREF(newdescr); newdescr = NULL; if (!PyDataType_ISNOTSWAPPED(indescr)) { PyArray_Descr *descr2; descr2 = PyArray_DescrNewByteorder(indescr, '='); Py_DECREF(indescr); indescr = NULL; if (descr2 == NULL) { goto fail; } indescr = descr2; } /* Convert max to an array */ if (max != NULL) { Py_INCREF(indescr); maxa = (PyArrayObject *)PyArray_FromAny(max, indescr, 0, 0, NPY_ARRAY_DEFAULT, NULL); if (maxa == NULL) { goto fail; } } /* * If we are unsigned, then make sure min is not < 0 * This is to match the behavior of _slow_array_clip * * We allow min and max to go beyond the limits * for other data-types in which case they * are interpreted as their modular counterparts. */ if (min != NULL) { if (PyArray_ISUNSIGNED(self)) { int cmp; zero = PyInt_FromLong(0); cmp = PyObject_RichCompareBool(min, zero, Py_LT); if (cmp == -1) { Py_DECREF(zero); goto fail; } if (cmp == 1) { min = zero; } else { Py_DECREF(zero); Py_INCREF(min); } } else { Py_INCREF(min); } /* Convert min to an array */ Py_INCREF(indescr); mina = (PyArrayObject *)PyArray_FromAny(min, indescr, 0, 0, NPY_ARRAY_DEFAULT, NULL); Py_DECREF(min); if (mina == NULL) { goto fail; } } /* * Check to see if input is single-segment, aligned, * and in native byteorder */ if (PyArray_ISONESEGMENT(self) && PyArray_CHKFLAGS(self, NPY_ARRAY_ALIGNED) && PyArray_ISNOTSWAPPED(self) && (PyArray_DESCR(self) == indescr)) { ingood = 1; } if (!ingood) { int flags; if (PyArray_ISFORTRAN(self)) { flags = NPY_ARRAY_FARRAY; } else { flags = NPY_ARRAY_CARRAY; } Py_INCREF(indescr); newin = (PyArrayObject *)PyArray_FromArray(self, indescr, flags); if (newin == NULL) { goto fail; } } else { newin = self; Py_INCREF(newin); } /* * At this point, newin is a single-segment, aligned, and correct * byte-order array of the correct type * * if ingood == 0, then it is a copy, otherwise, * it is the original input. */ /* * If we have already made a copy of the data, then use * that as the output array */ if (out == NULL && !ingood) { out = newin; } /* * Now, we know newin is a usable array for fastclip, * we need to make sure the output array is available * and usable */ if (out == NULL) { Py_INCREF(indescr); out = (PyArrayObject*)PyArray_NewFromDescr(Py_TYPE(self), indescr, PyArray_NDIM(self), PyArray_DIMS(self), NULL, NULL, PyArray_ISFORTRAN(self), (PyObject *)self); if (out == NULL) { goto fail; } outgood = 1; } else Py_INCREF(out); /* Input is good at this point */ if (out == newin) { outgood = 1; } if (!outgood && PyArray_ISONESEGMENT(out) && PyArray_CHKFLAGS(out, NPY_ARRAY_ALIGNED) && PyArray_ISNOTSWAPPED(out) && PyArray_EquivTypes(PyArray_DESCR(out), indescr)) { outgood = 1; } /* * Do we still not have a suitable output array? * Create one, now */ if (!outgood) { int oflags; if (PyArray_ISFORTRAN(out)) oflags = NPY_ARRAY_FARRAY; else oflags = NPY_ARRAY_CARRAY; oflags |= NPY_ARRAY_UPDATEIFCOPY | NPY_ARRAY_FORCECAST; Py_INCREF(indescr); newout = (PyArrayObject*)PyArray_FromArray(out, indescr, oflags); if (newout == NULL) { goto fail; } } else { newout = out; Py_INCREF(newout); } /* make sure the shape of the output array is the same */ if (!PyArray_SAMESHAPE(newin, newout)) { PyErr_SetString(PyExc_ValueError, "clip: Output array must have the" "same shape as the input."); goto fail; } if (PyArray_DATA(newout) != PyArray_DATA(newin)) { if (PyArray_AssignArray(newout, newin, NULL, NPY_DEFAULT_ASSIGN_CASTING) < 0) { goto fail; } } /* Now we can call the fast-clip function */ min_data = max_data = NULL; if (mina != NULL) { min_data = PyArray_DATA(mina); } if (maxa != NULL) { max_data = PyArray_DATA(maxa); } func(PyArray_DATA(newin), PyArray_SIZE(newin), min_data, max_data, PyArray_DATA(newout)); /* Clean up temporary variables */ Py_XDECREF(indescr); Py_XDECREF(newdescr); Py_XDECREF(mina); Py_XDECREF(maxa); Py_DECREF(newin); /* Copy back into out if out was not already a nice array. */ Py_DECREF(newout); return (PyObject *)out; fail: Py_XDECREF(indescr); Py_XDECREF(newdescr); Py_XDECREF(maxa); Py_XDECREF(mina); Py_XDECREF(newin); PyArray_XDECREF_ERR(newout); return NULL; } /*NUMPY_API * Conjugate */ NPY_NO_EXPORT PyObject * PyArray_Conjugate(PyArrayObject *self, PyArrayObject *out) { if (PyArray_ISCOMPLEX(self)) { if (out == NULL) { return PyArray_GenericUnaryFunction(self, n_ops.conjugate); } else { return PyArray_GenericBinaryFunction(self, (PyObject *)out, n_ops.conjugate); } } else { PyArrayObject *ret; if (out) { if (PyArray_AssignArray(out, self, NULL, NPY_DEFAULT_ASSIGN_CASTING) < 0) { return NULL; } ret = out; } else { ret = self; } Py_INCREF(ret); return (PyObject *)ret; } } /*NUMPY_API * Trace */ NPY_NO_EXPORT PyObject * PyArray_Trace(PyArrayObject *self, int offset, int axis1, int axis2, int rtype, PyArrayObject *out) { PyObject *diag = NULL, *ret = NULL; diag = PyArray_Diagonal(self, offset, axis1, axis2); if (diag == NULL) { return NULL; } ret = PyArray_GenericReduceFunction((PyArrayObject *)diag, n_ops.add, -1, rtype, out); Py_DECREF(diag); return ret; } numpy-1.8.2/numpy/core/src/multiarray/datetime.c0000664000175100017510000033512212370216243023052 0ustar vagrantvagrant00000000000000/* * This file implements core functionality for NumPy datetime. * * Written by Mark Wiebe (mwwiebe@gmail.com) * Copyright (c) 2011 by Enthought, Inc. * * See LICENSE.txt for the license. */ #define PY_SSIZE_T_CLEAN #include #include #include #define NPY_NO_DEPRECATED_API NPY_API_VERSION #define _MULTIARRAYMODULE #include #include "npy_config.h" #include "npy_pycompat.h" #include "numpy/arrayscalars.h" #include "methods.h" #include "_datetime.h" #include "datetime_strings.h" /* * Imports the PyDateTime functions so we can create these objects. * This is called during module initialization */ NPY_NO_EXPORT void numpy_pydatetime_import(void) { PyDateTime_IMPORT; } /* Exported as DATETIMEUNITS in multiarraymodule.c */ NPY_NO_EXPORT char *_datetime_strings[NPY_DATETIME_NUMUNITS] = { "Y", "M", "W", "", "D", "h", "m", "s", "ms", "us", "ns", "ps", "fs", "as", "generic" }; /* Days per month, regular year and leap year */ NPY_NO_EXPORT int _days_per_month_table[2][12] = { { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }, { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 } }; /* * Returns 1 if the given year is a leap year, 0 otherwise. */ NPY_NO_EXPORT int is_leapyear(npy_int64 year) { return (year & 0x3) == 0 && /* year % 4 == 0 */ ((year % 100) != 0 || (year % 400) == 0); } /* * Calculates the days offset from the 1970 epoch. */ NPY_NO_EXPORT npy_int64 get_datetimestruct_days(const npy_datetimestruct *dts) { int i, month; npy_int64 year, days = 0; int *month_lengths; year = dts->year - 1970; days = year * 365; /* Adjust for leap years */ if (days >= 0) { /* * 1968 is the closest leap year before 1970. * Exclude the current year, so add 1. */ year += 1; /* Add one day for each 4 years */ days += year / 4; /* 1900 is the closest previous year divisible by 100 */ year += 68; /* Subtract one day for each 100 years */ days -= year / 100; /* 1600 is the closest previous year divisible by 400 */ year += 300; /* Add one day for each 400 years */ days += year / 400; } else { /* * 1972 is the closest later year after 1970. * Include the current year, so subtract 2. */ year -= 2; /* Subtract one day for each 4 years */ days += year / 4; /* 2000 is the closest later year divisible by 100 */ year -= 28; /* Add one day for each 100 years */ days -= year / 100; /* 2000 is also the closest later year divisible by 400 */ /* Subtract one day for each 400 years */ days += year / 400; } month_lengths = _days_per_month_table[is_leapyear(dts->year)]; month = dts->month - 1; /* Add the months */ for (i = 0; i < month; ++i) { days += month_lengths[i]; } /* Add the days */ days += dts->day - 1; return days; } /* * Calculates the minutes offset from the 1970 epoch. */ NPY_NO_EXPORT npy_int64 get_datetimestruct_minutes(const npy_datetimestruct *dts) { npy_int64 days = get_datetimestruct_days(dts) * 24 * 60; days += dts->hour * 60; days += dts->min; return days; } /* * Modifies '*days_' to be the day offset within the year, * and returns the year. */ static npy_int64 days_to_yearsdays(npy_int64 *days_) { const npy_int64 days_per_400years = (400*365 + 100 - 4 + 1); /* Adjust so it's relative to the year 2000 (divisible by 400) */ npy_int64 days = (*days_) - (365*30 + 7); npy_int64 year; /* Break down the 400 year cycle to get the year and day within the year */ if (days >= 0) { year = 400 * (days / days_per_400years); days = days % days_per_400years; } else { year = 400 * ((days - (days_per_400years - 1)) / days_per_400years); days = days % days_per_400years; if (days < 0) { days += days_per_400years; } } /* Work out the year/day within the 400 year cycle */ if (days >= 366) { year += 100 * ((days-1) / (100*365 + 25 - 1)); days = (days-1) % (100*365 + 25 - 1); if (days >= 365) { year += 4 * ((days+1) / (4*365 + 1)); days = (days+1) % (4*365 + 1); if (days >= 366) { year += (days-1) / 365; days = (days-1) % 365; } } } *days_ = days; return year + 2000; } /* Extracts the month number from a 'datetime64[D]' value */ NPY_NO_EXPORT int days_to_month_number(npy_datetime days) { npy_int64 year; int *month_lengths, i; year = days_to_yearsdays(&days); month_lengths = _days_per_month_table[is_leapyear(year)]; for (i = 0; i < 12; ++i) { if (days < month_lengths[i]) { return i + 1; } else { days -= month_lengths[i]; } } /* Should never get here */ return 1; } /* * Fills in the year, month, day in 'dts' based on the days * offset from 1970. */ static void set_datetimestruct_days(npy_int64 days, npy_datetimestruct *dts) { int *month_lengths, i; dts->year = days_to_yearsdays(&days); month_lengths = _days_per_month_table[is_leapyear(dts->year)]; for (i = 0; i < 12; ++i) { if (days < month_lengths[i]) { dts->month = i + 1; dts->day = (int)days + 1; return; } else { days -= month_lengths[i]; } } } /* * Converts a datetime from a datetimestruct to a datetime based * on some metadata. The date is assumed to be valid. * * TODO: If meta->num is really big, there could be overflow * * Returns 0 on success, -1 on failure. */ NPY_NO_EXPORT int convert_datetimestruct_to_datetime(PyArray_DatetimeMetaData *meta, const npy_datetimestruct *dts, npy_datetime *out) { npy_datetime ret; NPY_DATETIMEUNIT base = meta->base; /* If the datetimestruct is NaT, return NaT */ if (dts->year == NPY_DATETIME_NAT) { *out = NPY_DATETIME_NAT; return 0; } /* Cannot instantiate a datetime with generic units */ if (meta->base == NPY_FR_GENERIC) { PyErr_SetString(PyExc_ValueError, "Cannot create a NumPy datetime other than NaT " "with generic units"); return -1; } if (base == NPY_FR_Y) { /* Truncate to the year */ ret = dts->year - 1970; } else if (base == NPY_FR_M) { /* Truncate to the month */ ret = 12 * (dts->year - 1970) + (dts->month - 1); } else { /* Otherwise calculate the number of days to start */ npy_int64 days = get_datetimestruct_days(dts); switch (base) { case NPY_FR_W: /* Truncate to weeks */ if (days >= 0) { ret = days / 7; } else { ret = (days - 6) / 7; } break; case NPY_FR_D: ret = days; break; case NPY_FR_h: ret = days * 24 + dts->hour; break; case NPY_FR_m: ret = (days * 24 + dts->hour) * 60 + dts->min; break; case NPY_FR_s: ret = ((days * 24 + dts->hour) * 60 + dts->min) * 60 + dts->sec; break; case NPY_FR_ms: ret = (((days * 24 + dts->hour) * 60 + dts->min) * 60 + dts->sec) * 1000 + dts->us / 1000; break; case NPY_FR_us: ret = (((days * 24 + dts->hour) * 60 + dts->min) * 60 + dts->sec) * 1000000 + dts->us; break; case NPY_FR_ns: ret = ((((days * 24 + dts->hour) * 60 + dts->min) * 60 + dts->sec) * 1000000 + dts->us) * 1000 + dts->ps / 1000; break; case NPY_FR_ps: ret = ((((days * 24 + dts->hour) * 60 + dts->min) * 60 + dts->sec) * 1000000 + dts->us) * 1000000 + dts->ps; break; case NPY_FR_fs: /* only 2.6 hours */ ret = (((((days * 24 + dts->hour) * 60 + dts->min) * 60 + dts->sec) * 1000000 + dts->us) * 1000000 + dts->ps) * 1000 + dts->as / 1000; break; case NPY_FR_as: /* only 9.2 secs */ ret = (((((days * 24 + dts->hour) * 60 + dts->min) * 60 + dts->sec) * 1000000 + dts->us) * 1000000 + dts->ps) * 1000000 + dts->as; break; default: /* Something got corrupted */ PyErr_SetString(PyExc_ValueError, "NumPy datetime metadata with corrupt unit value"); return -1; } } /* Divide by the multiplier */ if (meta->num > 1) { if (ret >= 0) { ret /= meta->num; } else { ret = (ret - meta->num + 1) / meta->num; } } *out = ret; return 0; } /*NUMPY_API * Create a datetime value from a filled datetime struct and resolution unit. * * TO BE REMOVED - NOT USED INTERNALLY. */ NPY_NO_EXPORT npy_datetime PyArray_DatetimeStructToDatetime(NPY_DATETIMEUNIT fr, npy_datetimestruct *d) { PyErr_SetString(PyExc_RuntimeError, "The NumPy PyArray_DatetimeStructToDatetime function has " "been removed"); return -1; } /*NUMPY_API * Create a timdelta value from a filled timedelta struct and resolution unit. * * TO BE REMOVED - NOT USED INTERNALLY. */ NPY_NO_EXPORT npy_datetime PyArray_TimedeltaStructToTimedelta(NPY_DATETIMEUNIT fr, npy_timedeltastruct *d) { PyErr_SetString(PyExc_RuntimeError, "The NumPy PyArray_TimedeltaStructToTimedelta function has " "been removed"); return -1; } /* * Converts a datetime based on the given metadata into a datetimestruct */ NPY_NO_EXPORT int convert_datetime_to_datetimestruct(PyArray_DatetimeMetaData *meta, npy_datetime dt, npy_datetimestruct *out) { npy_int64 perday; /* Initialize the output to all zeros */ memset(out, 0, sizeof(npy_datetimestruct)); out->year = 1970; out->month = 1; out->day = 1; /* NaT is signaled in the year */ if (dt == NPY_DATETIME_NAT) { out->year = NPY_DATETIME_NAT; return 0; } /* Datetimes can't be in generic units */ if (meta->base == NPY_FR_GENERIC) { PyErr_SetString(PyExc_ValueError, "Cannot convert a NumPy datetime value other than NaT " "with generic units"); return -1; } /* TODO: Change to a mechanism that avoids the potential overflow */ dt *= meta->num; /* * Note that care must be taken with the / and % operators * for negative values. */ switch (meta->base) { case NPY_FR_Y: out->year = 1970 + dt; break; case NPY_FR_M: if (dt >= 0) { out->year = 1970 + dt / 12; out->month = dt % 12 + 1; } else { out->year = 1969 + (dt + 1) / 12; out->month = 12 + (dt + 1)% 12; } break; case NPY_FR_W: /* A week is 7 days */ set_datetimestruct_days(dt * 7, out); break; case NPY_FR_D: set_datetimestruct_days(dt, out); break; case NPY_FR_h: perday = 24LL; if (dt >= 0) { set_datetimestruct_days(dt / perday, out); dt = dt % perday; } else { set_datetimestruct_days((dt - (perday-1)) / perday, out); dt = (perday-1) + (dt + 1) % perday; } out->hour = (int)dt; break; case NPY_FR_m: perday = 24LL * 60; if (dt >= 0) { set_datetimestruct_days(dt / perday, out); dt = dt % perday; } else { set_datetimestruct_days((dt - (perday-1)) / perday, out); dt = (perday-1) + (dt + 1) % perday; } out->hour = (int)(dt / 60); out->min = (int)(dt % 60); break; case NPY_FR_s: perday = 24LL * 60 * 60; if (dt >= 0) { set_datetimestruct_days(dt / perday, out); dt = dt % perday; } else { set_datetimestruct_days((dt - (perday-1)) / perday, out); dt = (perday-1) + (dt + 1) % perday; } out->hour = (int)(dt / (60*60)); out->min = (int)((dt / 60) % 60); out->sec = (int)(dt % 60); break; case NPY_FR_ms: perday = 24LL * 60 * 60 * 1000; if (dt >= 0) { set_datetimestruct_days(dt / perday, out); dt = dt % perday; } else { set_datetimestruct_days((dt - (perday-1)) / perday, out); dt = (perday-1) + (dt + 1) % perday; } out->hour = (int)(dt / (60*60*1000LL)); out->min = (int)((dt / (60*1000LL)) % 60); out->sec = (int)((dt / 1000LL) % 60); out->us = (int)((dt % 1000LL) * 1000); break; case NPY_FR_us: perday = 24LL * 60LL * 60LL * 1000LL * 1000LL; if (dt >= 0) { set_datetimestruct_days(dt / perday, out); dt = dt % perday; } else { set_datetimestruct_days((dt - (perday-1)) / perday, out); dt = (perday-1) + (dt + 1) % perday; } out->hour = (int)(dt / (60*60*1000000LL)); out->min = (int)((dt / (60*1000000LL)) % 60); out->sec = (int)((dt / 1000000LL) % 60); out->us = (int)(dt % 1000000LL); break; case NPY_FR_ns: perday = 24LL * 60LL * 60LL * 1000LL * 1000LL * 1000LL; if (dt >= 0) { set_datetimestruct_days(dt / perday, out); dt = dt % perday; } else { set_datetimestruct_days((dt - (perday-1)) / perday, out); dt = (perday-1) + (dt + 1) % perday; } out->hour = (int)(dt / (60*60*1000000000LL)); out->min = (int)((dt / (60*1000000000LL)) % 60); out->sec = (int)((dt / 1000000000LL) % 60); out->us = (int)((dt / 1000LL) % 1000000LL); out->ps = (int)((dt % 1000LL) * 1000); break; case NPY_FR_ps: perday = 24LL * 60 * 60 * 1000 * 1000 * 1000 * 1000; if (dt >= 0) { set_datetimestruct_days(dt / perday, out); dt = dt % perday; } else { set_datetimestruct_days((dt - (perday-1)) / perday, out); dt = (perday-1) + (dt + 1) % perday; } out->hour = (int)(dt / (60*60*1000000000000LL)); out->min = (int)((dt / (60*1000000000000LL)) % 60); out->sec = (int)((dt / 1000000000000LL) % 60); out->us = (int)((dt / 1000000LL) % 1000000LL); out->ps = (int)(dt % 1000000LL); break; case NPY_FR_fs: /* entire range is only +- 2.6 hours */ if (dt >= 0) { out->hour = (int)(dt / (60*60*1000000000000000LL)); out->min = (int)((dt / (60*1000000000000000LL)) % 60); out->sec = (int)((dt / 1000000000000000LL) % 60); out->us = (int)((dt / 1000000000LL) % 1000000LL); out->ps = (int)((dt / 1000LL) % 1000000LL); out->as = (int)((dt % 1000LL) * 1000); } else { npy_datetime minutes; minutes = dt / (60*1000000000000000LL); dt = dt % (60*1000000000000000LL); if (dt < 0) { dt += (60*1000000000000000LL); --minutes; } /* Offset the negative minutes */ add_minutes_to_datetimestruct(out, minutes); out->sec = (int)((dt / 1000000000000000LL) % 60); out->us = (int)((dt / 1000000000LL) % 1000000LL); out->ps = (int)((dt / 1000LL) % 1000000LL); out->as = (int)((dt % 1000LL) * 1000); } break; case NPY_FR_as: /* entire range is only +- 9.2 seconds */ if (dt >= 0) { out->sec = (int)((dt / 1000000000000000000LL) % 60); out->us = (int)((dt / 1000000000000LL) % 1000000LL); out->ps = (int)((dt / 1000000LL) % 1000000LL); out->as = (int)(dt % 1000000LL); } else { npy_datetime seconds; seconds = dt / 1000000000000000000LL; dt = dt % 1000000000000000000LL; if (dt < 0) { dt += 1000000000000000000LL; --seconds; } /* Offset the negative seconds */ add_seconds_to_datetimestruct(out, seconds); out->us = (int)((dt / 1000000000000LL) % 1000000LL); out->ps = (int)((dt / 1000000LL) % 1000000LL); out->as = (int)(dt % 1000000LL); } break; default: PyErr_SetString(PyExc_RuntimeError, "NumPy datetime metadata is corrupted with invalid " "base unit"); return -1; } return 0; } /*NUMPY_API * Fill the datetime struct from the value and resolution unit. * * TO BE REMOVED - NOT USED INTERNALLY. */ NPY_NO_EXPORT void PyArray_DatetimeToDatetimeStruct(npy_datetime val, NPY_DATETIMEUNIT fr, npy_datetimestruct *result) { PyErr_SetString(PyExc_RuntimeError, "The NumPy PyArray_DatetimeToDatetimeStruct function has " "been removed"); memset(result, -1, sizeof(npy_datetimestruct)); } /* * FIXME: Overflow is not handled at all * To convert from Years or Months, * multiplication by the average is done */ /*NUMPY_API * Fill the timedelta struct from the timedelta value and resolution unit. * * TO BE REMOVED - NOT USED INTERNALLY. */ NPY_NO_EXPORT void PyArray_TimedeltaToTimedeltaStruct(npy_timedelta val, NPY_DATETIMEUNIT fr, npy_timedeltastruct *result) { PyErr_SetString(PyExc_RuntimeError, "The NumPy PyArray_TimedeltaToTimedeltaStruct function has " "been removed"); memset(result, -1, sizeof(npy_timedeltastruct)); } /* * Creates a datetime or timedelta dtype using a copy of the provided metadata. */ NPY_NO_EXPORT PyArray_Descr * create_datetime_dtype(int type_num, PyArray_DatetimeMetaData *meta) { PyArray_Descr *dtype = NULL; PyArray_DatetimeMetaData *dt_data; /* Create a default datetime or timedelta */ if (type_num == NPY_DATETIME || type_num == NPY_TIMEDELTA) { dtype = PyArray_DescrNewFromType(type_num); } else { PyErr_SetString(PyExc_RuntimeError, "Asked to create a datetime type with a non-datetime " "type number"); return NULL; } if (dtype == NULL) { return NULL; } dt_data = &(((PyArray_DatetimeDTypeMetaData *)dtype->c_metadata)->meta); /* Copy the metadata */ *dt_data = *meta; return dtype; } /* * Creates a datetime or timedelta dtype using the given unit. */ NPY_NO_EXPORT PyArray_Descr * create_datetime_dtype_with_unit(int type_num, NPY_DATETIMEUNIT unit) { PyArray_DatetimeMetaData meta; meta.base = unit; meta.num = 1; return create_datetime_dtype(type_num, &meta); } /* * This function returns a pointer to the DateTimeMetaData * contained within the provided datetime dtype. */ NPY_NO_EXPORT PyArray_DatetimeMetaData * get_datetime_metadata_from_dtype(PyArray_Descr *dtype) { if (!PyDataType_ISDATETIME(dtype)) { PyErr_SetString(PyExc_TypeError, "cannot get datetime metadata from non-datetime type"); return NULL; } return &(((PyArray_DatetimeDTypeMetaData *)dtype->c_metadata)->meta); } /* * Converts a substring given by 'str' and 'len' into * a date time unit multiplier + enum value, which are populated * into out_meta. Other metadata is left along. * * 'metastr' is only used in the error message, and may be NULL. * * Returns 0 on success, -1 on failure. */ NPY_NO_EXPORT int parse_datetime_extended_unit_from_string(char *str, Py_ssize_t len, char *metastr, PyArray_DatetimeMetaData *out_meta) { char *substr = str, *substrend = NULL; int den = 1; /* First comes an optional integer multiplier */ out_meta->num = (int)strtol(substr, &substrend, 10); if (substr == substrend) { out_meta->num = 1; } substr = substrend; /* Next comes the unit itself, followed by either '/' or the string end */ substrend = substr; while (substrend-str < len && *substrend != '/') { ++substrend; } if (substr == substrend) { goto bad_input; } out_meta->base = parse_datetime_unit_from_string(substr, substrend-substr, metastr); if (out_meta->base == -1) { return -1; } substr = substrend; /* Next comes an optional integer denominator */ if (substr-str < len && *substr == '/') { substr++; den = (int)strtol(substr, &substrend, 10); /* If the '/' exists, there must be a number followed by ']' */ if (substr == substrend || *substrend != ']') { goto bad_input; } substr = substrend + 1; } else if (substr-str != len) { goto bad_input; } if (den != 1) { if (convert_datetime_divisor_to_multiple( out_meta, den, metastr) < 0) { return -1; } } return 0; bad_input: if (metastr != NULL) { PyErr_Format(PyExc_TypeError, "Invalid datetime metadata string \"%s\" at position %d", metastr, (int)(substr-metastr)); } else { PyErr_Format(PyExc_TypeError, "Invalid datetime metadata string \"%s\"", str); } return -1; } /* * Parses the metadata string into the metadata C structure. * * Returns 0 on success, -1 on failure. */ NPY_NO_EXPORT int parse_datetime_metadata_from_metastr(char *metastr, Py_ssize_t len, PyArray_DatetimeMetaData *out_meta) { char *substr = metastr, *substrend = NULL; /* Treat the empty string as generic units */ if (len == 0) { out_meta->base = NPY_FR_GENERIC; out_meta->num = 1; return 0; } /* The metadata string must start with a '[' */ if (len < 3 || *substr++ != '[') { goto bad_input; } substrend = substr; while (substrend - metastr < len && *substrend != ']') { ++substrend; } if (substrend - metastr == len || substr == substrend) { substr = substrend; goto bad_input; } /* Parse the extended unit inside the [] */ if (parse_datetime_extended_unit_from_string(substr, substrend-substr, metastr, out_meta) < 0) { return -1; } substr = substrend+1; if (substr - metastr != len) { goto bad_input; } return 0; bad_input: if (substr != metastr) { PyErr_Format(PyExc_TypeError, "Invalid datetime metadata string \"%s\" at position %d", metastr, (int)(substr-metastr)); } else { PyErr_Format(PyExc_TypeError, "Invalid datetime metadata string \"%s\"", metastr); } return -1; } /* * Converts a datetype dtype string into a dtype descr object. * The "type" string should be NULL-terminated. */ NPY_NO_EXPORT PyArray_Descr * parse_dtype_from_datetime_typestr(char *typestr, Py_ssize_t len) { PyArray_DatetimeMetaData meta; char *metastr = NULL; int is_timedelta = 0; Py_ssize_t metalen = 0; if (len < 2) { PyErr_Format(PyExc_TypeError, "Invalid datetime typestr \"%s\"", typestr); return NULL; } /* * First validate that the root is correct, * and get the metadata string address */ if (typestr[0] == 'm' && typestr[1] == '8') { is_timedelta = 1; metastr = typestr + 2; metalen = len - 2; } else if (typestr[0] == 'M' && typestr[1] == '8') { is_timedelta = 0; metastr = typestr + 2; metalen = len - 2; } else if (len >= 11 && strncmp(typestr, "timedelta64", 11) == 0) { is_timedelta = 1; metastr = typestr + 11; metalen = len - 11; } else if (len >= 10 && strncmp(typestr, "datetime64", 10) == 0) { is_timedelta = 0; metastr = typestr + 10; metalen = len - 10; } else { PyErr_Format(PyExc_TypeError, "Invalid datetime typestr \"%s\"", typestr); return NULL; } /* Parse the metadata string into a metadata struct */ if (parse_datetime_metadata_from_metastr(metastr, metalen, &meta) < 0) { return NULL; } return create_datetime_dtype(is_timedelta ? NPY_TIMEDELTA : NPY_DATETIME, &meta); } static NPY_DATETIMEUNIT _multiples_table[16][4] = { {12, 52, 365}, /* NPY_FR_Y */ {NPY_FR_M, NPY_FR_W, NPY_FR_D}, {4, 30, 720}, /* NPY_FR_M */ {NPY_FR_W, NPY_FR_D, NPY_FR_h}, {7, 168, 10080}, /* NPY_FR_W */ {NPY_FR_D, NPY_FR_h, NPY_FR_m}, {0}, /* Gap for removed NPY_FR_B */ {0}, {24, 1440, 86400}, /* NPY_FR_D */ {NPY_FR_h, NPY_FR_m, NPY_FR_s}, {60, 3600}, /* NPY_FR_h */ {NPY_FR_m, NPY_FR_s}, {60, 60000}, /* NPY_FR_m */ {NPY_FR_s, NPY_FR_ms}, {1000, 1000000}, /* >=NPY_FR_s */ {0, 0} }; /* * Translate divisors into multiples of smaller units. * 'metastr' is used for the error message if the divisor doesn't work, * and can be NULL if the metadata didn't come from a string. * * This function only affects the 'base' and 'num' values in the metadata. * * Returns 0 on success, -1 on failure. */ NPY_NO_EXPORT int convert_datetime_divisor_to_multiple(PyArray_DatetimeMetaData *meta, int den, char *metastr) { int i, num, ind; NPY_DATETIMEUNIT *totry; NPY_DATETIMEUNIT *baseunit; int q, r; if (meta->base == NPY_FR_GENERIC) { PyErr_SetString(PyExc_ValueError, "Can't use 'den' divisor with generic units"); return -1; } ind = ((int)meta->base - (int)NPY_FR_Y)*2; totry = _multiples_table[ind]; baseunit = _multiples_table[ind + 1]; num = 3; if (meta->base == NPY_FR_W) { num = 4; } else if (meta->base > NPY_FR_D) { num = 2; } if (meta->base >= NPY_FR_s) { ind = ((int)NPY_FR_s - (int)NPY_FR_Y)*2; totry = _multiples_table[ind]; baseunit = _multiples_table[ind + 1]; baseunit[0] = meta->base + 1; baseunit[1] = meta->base + 2; if (meta->base == NPY_FR_as - 1) { num = 1; } if (meta->base == NPY_FR_as) { num = 0; } } for (i = 0; i < num; i++) { q = totry[i] / den; r = totry[i] % den; if (r == 0) { break; } } if (i == num) { if (metastr == NULL) { PyErr_Format(PyExc_ValueError, "divisor (%d) is not a multiple of a lower-unit " "in datetime metadata", den); } else { PyErr_Format(PyExc_ValueError, "divisor (%d) is not a multiple of a lower-unit " "in datetime metadata \"%s\"", den, metastr); } return -1; } meta->base = baseunit[i]; meta->num *= q; return 0; } /* * Lookup table for factors between datetime units, except * for years and months. */ static npy_uint32 _datetime_factors[] = { 1, /* Years - not used */ 1, /* Months - not used */ 7, /* Weeks -> Days */ 1, /* Business Days - was removed but a gap still exists in the enum */ 24, /* Days -> Hours */ 60, /* Hours -> Minutes */ 60, /* Minutes -> Seconds */ 1000, 1000, 1000, 1000, 1000, 1000, 1, /* Attoseconds are the smallest base unit */ 0 /* Generic units don't have a conversion */ }; /* * Returns the scale factor between the units. Does not validate * that bigbase represents larger units than littlebase, or that * the units are not generic. * * Returns 0 if there is an overflow. */ static npy_uint64 get_datetime_units_factor(NPY_DATETIMEUNIT bigbase, NPY_DATETIMEUNIT littlebase) { npy_uint64 factor = 1; int unit = (int)bigbase; while (littlebase > unit) { factor *= _datetime_factors[unit]; /* * Detect overflow by disallowing the top 16 bits to be 1. * That alows a margin of error much bigger than any of * the datetime factors. */ if (factor&0xff00000000000000ULL) { return 0; } ++unit; } return factor; } /* Euclidean algorithm on two positive numbers */ static npy_uint64 _uint64_euclidean_gcd(npy_uint64 x, npy_uint64 y) { npy_uint64 tmp; if (x > y) { tmp = x; x = y; y = tmp; } while (x != y && y != 0) { tmp = x % y; x = y; y = tmp; } return x; } /* * Computes the conversion factor to convert data with 'src_meta' metadata * into data with 'dst_meta' metadata. * * If overflow occurs, both out_num and out_denom are set to 0, but * no error is set. */ NPY_NO_EXPORT void get_datetime_conversion_factor(PyArray_DatetimeMetaData *src_meta, PyArray_DatetimeMetaData *dst_meta, npy_int64 *out_num, npy_int64 *out_denom) { int src_base, dst_base, swapped; npy_uint64 num = 1, denom = 1, tmp, gcd; /* Generic units change to the destination with no conversion factor */ if (src_meta->base == NPY_FR_GENERIC) { *out_num = 1; *out_denom = 1; return; } /* * Converting to a generic unit from something other than a generic * unit is an error. */ else if (dst_meta->base == NPY_FR_GENERIC) { PyErr_SetString(PyExc_ValueError, "Cannot convert from specific units to generic " "units in NumPy datetimes or timedeltas"); *out_num = 0; *out_denom = 0; return; } if (src_meta->base <= dst_meta->base) { src_base = src_meta->base; dst_base = dst_meta->base; swapped = 0; } else { src_base = dst_meta->base; dst_base = src_meta->base; swapped = 1; } if (src_base != dst_base) { /* * Conversions between years/months and other units use * the factor averaged over the 400 year leap year cycle. */ if (src_base == NPY_FR_Y) { if (dst_base == NPY_FR_M) { num *= 12; } else if (dst_base == NPY_FR_W) { num *= (97 + 400*365); denom *= 400*7; } else { /* Year -> Day */ num *= (97 + 400*365); denom *= 400; /* Day -> dst_base */ num *= get_datetime_units_factor(NPY_FR_D, dst_base); } } else if (src_base == NPY_FR_M) { if (dst_base == NPY_FR_W) { num *= (97 + 400*365); denom *= 400*12*7; } else { /* Month -> Day */ num *= (97 + 400*365); denom *= 400*12; /* Day -> dst_base */ num *= get_datetime_units_factor(NPY_FR_D, dst_base); } } else { num *= get_datetime_units_factor(src_base, dst_base); } } /* If something overflowed, make both num and 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", _datetime_strings[src_base], _datetime_strings[dst_base]); *out_num = 0; *out_denom = 0; return; } /* Swap the numerator and denominator if necessary */ if (swapped) { tmp = num; num = denom; denom = tmp; } num *= src_meta->num; denom *= dst_meta->num; /* Return as a fraction in reduced form */ gcd = _uint64_euclidean_gcd(num, denom); *out_num = (npy_int64)(num / gcd); *out_denom = (npy_int64)(denom / gcd); } /* * Determines whether the 'divisor' metadata divides evenly into * the 'dividend' metadata. */ NPY_NO_EXPORT npy_bool datetime_metadata_divides( PyArray_DatetimeMetaData *dividend, PyArray_DatetimeMetaData *divisor, int strict_with_nonlinear_units) { npy_uint64 num1, num2; /* Generic units divide into anything */ if (divisor->base == NPY_FR_GENERIC) { return 1; } /* Non-generic units never divide into generic units */ else if (dividend->base == NPY_FR_GENERIC) { return 0; } num1 = (npy_uint64)dividend->num; num2 = (npy_uint64)divisor->num; /* If the bases are different, factor in a conversion */ if (dividend->base != divisor->base) { /* * Years and Months are incompatible with * all other units (except years and months are compatible * with each other). */ if (dividend->base == NPY_FR_Y) { if (divisor->base == NPY_FR_M) { num1 *= 12; } else if (strict_with_nonlinear_units) { return 0; } else { /* Could do something complicated here */ return 1; } } else if (divisor->base == NPY_FR_Y) { if (dividend->base == NPY_FR_M) { num2 *= 12; } else if (strict_with_nonlinear_units) { return 0; } else { /* Could do something complicated here */ return 1; } } else if (dividend->base == NPY_FR_M || divisor->base == NPY_FR_M) { if (strict_with_nonlinear_units) { return 0; } else { /* Could do something complicated here */ return 1; } } /* Take the greater base (unit sizes are decreasing in enum) */ if (dividend->base > divisor->base) { num2 *= get_datetime_units_factor(divisor->base, dividend->base); if (num2 == 0) { return 0; } } else { num1 *= get_datetime_units_factor(dividend->base, divisor->base); if (num1 == 0) { return 0; } } } /* Crude, incomplete check for overflow */ if (num1&0xff00000000000000LL || num2&0xff00000000000000LL ) { return 0; } return (num1 % num2) == 0; } /* * This provides the casting rules for the DATETIME data type units. * * Notably, there is a barrier between 'date units' and 'time units' * for all but 'unsafe' casting. */ NPY_NO_EXPORT npy_bool can_cast_datetime64_units(NPY_DATETIMEUNIT src_unit, NPY_DATETIMEUNIT dst_unit, NPY_CASTING casting) { switch (casting) { /* Allow anything with unsafe casting */ case NPY_UNSAFE_CASTING: return 1; /* * Only enforce the 'date units' vs 'time units' barrier with * 'same_kind' casting. */ case NPY_SAME_KIND_CASTING: if (src_unit == NPY_FR_GENERIC || dst_unit == NPY_FR_GENERIC) { return src_unit == dst_unit; } else { return (src_unit <= NPY_FR_D && dst_unit <= NPY_FR_D) || (src_unit > NPY_FR_D && dst_unit > NPY_FR_D); } /* * Enforce the 'date units' vs 'time units' barrier and that * casting is only allowed towards more precise units with * 'safe' casting. */ case NPY_SAFE_CASTING: if (src_unit == NPY_FR_GENERIC || dst_unit == NPY_FR_GENERIC) { return src_unit == dst_unit; } else { return (src_unit <= dst_unit) && ((src_unit <= NPY_FR_D && dst_unit <= NPY_FR_D) || (src_unit > NPY_FR_D && dst_unit > NPY_FR_D)); } /* Enforce equality with 'no' or 'equiv' casting */ default: return src_unit == dst_unit; } } /* * This provides the casting rules for the TIMEDELTA data type units. * * Notably, there is a barrier between the nonlinear years and * months units, and all the other units. */ NPY_NO_EXPORT npy_bool can_cast_timedelta64_units(NPY_DATETIMEUNIT src_unit, NPY_DATETIMEUNIT dst_unit, NPY_CASTING casting) { switch (casting) { /* Allow anything with unsafe casting */ case NPY_UNSAFE_CASTING: return 1; /* * Only enforce the 'date units' vs 'time units' barrier with * 'same_kind' casting. */ case NPY_SAME_KIND_CASTING: if (src_unit == NPY_FR_GENERIC || dst_unit == NPY_FR_GENERIC) { return src_unit == dst_unit; } else { return (src_unit <= NPY_FR_M && dst_unit <= NPY_FR_M) || (src_unit > NPY_FR_M && dst_unit > NPY_FR_M); } /* * Enforce the 'date units' vs 'time units' barrier and that * casting is only allowed towards more precise units with * 'safe' casting. */ case NPY_SAFE_CASTING: if (src_unit == NPY_FR_GENERIC || dst_unit == NPY_FR_GENERIC) { return src_unit == dst_unit; } else { return (src_unit <= dst_unit) && ((src_unit <= NPY_FR_M && dst_unit <= NPY_FR_M) || (src_unit > NPY_FR_M && dst_unit > NPY_FR_M)); } /* Enforce equality with 'no' or 'equiv' casting */ default: return src_unit == dst_unit; } } /* * This provides the casting rules for the DATETIME data type metadata. */ NPY_NO_EXPORT npy_bool can_cast_datetime64_metadata(PyArray_DatetimeMetaData *src_meta, PyArray_DatetimeMetaData *dst_meta, NPY_CASTING casting) { switch (casting) { case NPY_UNSAFE_CASTING: return 1; case NPY_SAME_KIND_CASTING: return can_cast_datetime64_units(src_meta->base, dst_meta->base, casting); case NPY_SAFE_CASTING: return can_cast_datetime64_units(src_meta->base, dst_meta->base, casting) && datetime_metadata_divides(src_meta, dst_meta, 0); default: return src_meta->base == dst_meta->base && src_meta->num == dst_meta->num; } } /* * This provides the casting rules for the TIMEDELTA data type metadata. */ NPY_NO_EXPORT npy_bool can_cast_timedelta64_metadata(PyArray_DatetimeMetaData *src_meta, PyArray_DatetimeMetaData *dst_meta, NPY_CASTING casting) { switch (casting) { case NPY_UNSAFE_CASTING: return 1; case NPY_SAME_KIND_CASTING: return can_cast_timedelta64_units(src_meta->base, dst_meta->base, casting); case NPY_SAFE_CASTING: return can_cast_timedelta64_units(src_meta->base, dst_meta->base, casting) && datetime_metadata_divides(src_meta, dst_meta, 1); default: return src_meta->base == dst_meta->base && src_meta->num == dst_meta->num; } } /* * Tests whether a datetime64 can be cast from the source metadata * to the destination metadata according to the specified casting rule. * * Returns -1 if an exception was raised, 0 otherwise. */ NPY_NO_EXPORT int raise_if_datetime64_metadata_cast_error(char *object_type, PyArray_DatetimeMetaData *src_meta, PyArray_DatetimeMetaData *dst_meta, NPY_CASTING casting) { if (can_cast_datetime64_metadata(src_meta, dst_meta, casting)) { return 0; } else { PyObject *errmsg; errmsg = PyUString_FromFormat("Cannot cast %s " "from metadata ", object_type); errmsg = append_metastr_to_string(src_meta, 0, errmsg); PyUString_ConcatAndDel(&errmsg, PyUString_FromString(" to ")); errmsg = append_metastr_to_string(dst_meta, 0, errmsg); PyUString_ConcatAndDel(&errmsg, PyUString_FromFormat(" according to the rule %s", npy_casting_to_string(casting))); PyErr_SetObject(PyExc_TypeError, errmsg); Py_DECREF(errmsg); return -1; } } /* * Tests whether a timedelta64 can be cast from the source metadata * to the destination metadata according to the specified casting rule. * * Returns -1 if an exception was raised, 0 otherwise. */ NPY_NO_EXPORT int raise_if_timedelta64_metadata_cast_error(char *object_type, PyArray_DatetimeMetaData *src_meta, PyArray_DatetimeMetaData *dst_meta, NPY_CASTING casting) { if (can_cast_timedelta64_metadata(src_meta, dst_meta, casting)) { return 0; } else { PyObject *errmsg; errmsg = PyUString_FromFormat("Cannot cast %s " "from metadata ", object_type); errmsg = append_metastr_to_string(src_meta, 0, errmsg); PyUString_ConcatAndDel(&errmsg, PyUString_FromString(" to ")); errmsg = append_metastr_to_string(dst_meta, 0, errmsg); PyUString_ConcatAndDel(&errmsg, PyUString_FromFormat(" according to the rule %s", npy_casting_to_string(casting))); PyErr_SetObject(PyExc_TypeError, errmsg); Py_DECREF(errmsg); return -1; } } /* * Computes the GCD of the two date-time metadata values. Raises * an exception if there is no reasonable GCD, such as with * years and days. * * The result is placed in 'out_meta'. * * Returns 0 on success, -1 on failure. */ NPY_NO_EXPORT int compute_datetime_metadata_greatest_common_divisor( PyArray_DatetimeMetaData *meta1, PyArray_DatetimeMetaData *meta2, PyArray_DatetimeMetaData *out_meta, int strict_with_nonlinear_units1, int strict_with_nonlinear_units2) { NPY_DATETIMEUNIT base; npy_uint64 num1, num2, num; /* If either unit is generic, adopt the metadata from the other one */ if (meta1->base == NPY_FR_GENERIC) { *out_meta = *meta2; return 0; } else if (meta2->base == NPY_FR_GENERIC) { *out_meta = *meta1; return 0; } num1 = (npy_uint64)meta1->num; num2 = (npy_uint64)meta2->num; /* First validate that the units have a reasonable GCD */ if (meta1->base == meta2->base) { base = meta1->base; } else { /* * Years and Months are incompatible with * all other units (except years and months are compatible * with each other). */ if (meta1->base == NPY_FR_Y) { if (meta2->base == NPY_FR_M) { base = NPY_FR_M; num1 *= 12; } else if (strict_with_nonlinear_units1) { goto incompatible_units; } else { base = meta2->base; /* Don't multiply num1 since there is no even factor */ } } else if (meta2->base == NPY_FR_Y) { if (meta1->base == NPY_FR_M) { base = NPY_FR_M; num2 *= 12; } else if (strict_with_nonlinear_units2) { goto incompatible_units; } else { base = meta1->base; /* Don't multiply num2 since there is no even factor */ } } else if (meta1->base == NPY_FR_M) { if (strict_with_nonlinear_units1) { goto incompatible_units; } else { base = meta2->base; /* Don't multiply num1 since there is no even factor */ } } else if (meta2->base == NPY_FR_M) { if (strict_with_nonlinear_units2) { goto incompatible_units; } else { base = meta1->base; /* Don't multiply num2 since there is no even factor */ } } /* Take the greater base (unit sizes are decreasing in enum) */ if (meta1->base > meta2->base) { base = meta1->base; num2 *= get_datetime_units_factor(meta2->base, meta1->base); if (num2 == 0) { goto units_overflow; } } else { base = meta2->base; num1 *= get_datetime_units_factor(meta1->base, meta2->base); if (num1 == 0) { goto units_overflow; } } } /* Compute the GCD of the resulting multipliers */ num = _uint64_euclidean_gcd(num1, num2); /* Fill the 'out_meta' values */ out_meta->base = base; out_meta->num = (int)num; if (out_meta->num <= 0 || num != (npy_uint64)out_meta->num) { goto units_overflow; } return 0; incompatible_units: { PyObject *errmsg; errmsg = PyUString_FromString("Cannot get " "a common metadata divisor for " "NumPy datetime metadata "); errmsg = append_metastr_to_string(meta1, 0, errmsg); PyUString_ConcatAndDel(&errmsg, PyUString_FromString(" and ")); errmsg = append_metastr_to_string(meta2, 0, errmsg); PyUString_ConcatAndDel(&errmsg, PyUString_FromString(" because they have " "incompatible nonlinear base time units")); PyErr_SetObject(PyExc_TypeError, errmsg); Py_DECREF(errmsg); return -1; } units_overflow: { PyObject *errmsg; errmsg = PyUString_FromString("Integer overflow " "getting a common metadata divisor for " "NumPy datetime metadata "); errmsg = append_metastr_to_string(meta1, 0, errmsg); PyUString_ConcatAndDel(&errmsg, PyUString_FromString(" and ")); errmsg = append_metastr_to_string(meta2, 0, errmsg); PyErr_SetObject(PyExc_OverflowError, errmsg); Py_DECREF(errmsg); return -1; } } /* * Both type1 and type2 must be either NPY_DATETIME or NPY_TIMEDELTA. * Applies the type promotion rules between the two types, returning * the promoted type. */ NPY_NO_EXPORT PyArray_Descr * datetime_type_promotion(PyArray_Descr *type1, PyArray_Descr *type2) { int type_num1, type_num2; PyArray_Descr *dtype; int is_datetime; type_num1 = type1->type_num; type_num2 = type2->type_num; is_datetime = (type_num1 == NPY_DATETIME || type_num2 == NPY_DATETIME); /* Create a DATETIME or TIMEDELTA dtype */ dtype = PyArray_DescrNewFromType(is_datetime ? NPY_DATETIME : NPY_TIMEDELTA); if (dtype == NULL) { return NULL; } /* * Get the metadata GCD, being strict about nonlinear units for * timedelta and relaxed for datetime. */ if (compute_datetime_metadata_greatest_common_divisor( get_datetime_metadata_from_dtype(type1), get_datetime_metadata_from_dtype(type2), get_datetime_metadata_from_dtype(dtype), type_num1 == NPY_TIMEDELTA, type_num2 == NPY_TIMEDELTA) < 0) { Py_DECREF(dtype); return NULL; } return dtype; } /* * Converts a substring given by 'str' and 'len' into * a date time unit enum value. The 'metastr' parameter * is used for error messages, and may be NULL. * * Generic units have no representation as a string in this form. * * Returns 0 on success, -1 on failure. */ NPY_NO_EXPORT NPY_DATETIMEUNIT parse_datetime_unit_from_string(char *str, Py_ssize_t len, char *metastr) { /* Use switch statements so the compiler can make it fast */ if (len == 1) { switch (str[0]) { case 'Y': return NPY_FR_Y; case 'M': return NPY_FR_M; case 'W': return NPY_FR_W; case 'D': return NPY_FR_D; case 'h': return NPY_FR_h; case 'm': return NPY_FR_m; case 's': return NPY_FR_s; } } /* All the two-letter units are variants of seconds */ else if (len == 2 && str[1] == 's') { switch (str[0]) { case 'm': return NPY_FR_ms; case 'u': return NPY_FR_us; case 'n': return NPY_FR_ns; case 'p': return NPY_FR_ps; case 'f': return NPY_FR_fs; case 'a': return NPY_FR_as; } } /* If nothing matched, it's an error */ if (metastr == NULL) { PyErr_Format(PyExc_TypeError, "Invalid datetime unit \"%s\" in metadata", str); } else { PyErr_Format(PyExc_TypeError, "Invalid datetime unit in metadata string \"%s\"", metastr); } return -1; } NPY_NO_EXPORT PyObject * convert_datetime_metadata_to_tuple(PyArray_DatetimeMetaData *meta) { PyObject *dt_tuple; dt_tuple = PyTuple_New(2); if (dt_tuple == NULL) { return NULL; } PyTuple_SET_ITEM(dt_tuple, 0, PyUString_FromString(_datetime_strings[meta->base])); PyTuple_SET_ITEM(dt_tuple, 1, PyInt_FromLong(meta->num)); return dt_tuple; } /* * Converts a metadata tuple into a datetime metadata C struct. * * Returns 0 on success, -1 on failure. */ NPY_NO_EXPORT int convert_datetime_metadata_tuple_to_datetime_metadata(PyObject *tuple, PyArray_DatetimeMetaData *out_meta) { char *basestr = NULL; Py_ssize_t len = 0, tuple_size; int den = 1; PyObject *unit_str = NULL; if (!PyTuple_Check(tuple)) { PyObject *errmsg; errmsg = PyUString_FromString("Require tuple for tuple to NumPy " "datetime metadata conversion, not "); PyUString_ConcatAndDel(&errmsg, PyObject_Repr(tuple)); PyErr_SetObject(PyExc_TypeError, errmsg); Py_DECREF(errmsg); return -1; } tuple_size = PyTuple_GET_SIZE(tuple); if (tuple_size < 2 || tuple_size > 4) { PyErr_SetString(PyExc_TypeError, "Require tuple of size 2 to 4 for " "tuple to NumPy datetime metadata conversion"); return -1; } unit_str = PyTuple_GET_ITEM(tuple, 0); Py_INCREF(unit_str); if (PyUnicode_Check(unit_str)) { /* Allow unicode format strings: convert to bytes */ PyObject *tmp = PyUnicode_AsASCIIString(unit_str); Py_DECREF(unit_str); if (tmp == NULL) { return -1; } unit_str = tmp; } if (PyBytes_AsStringAndSize(unit_str, &basestr, &len) < 0) { Py_DECREF(unit_str); return -1; } out_meta->base = parse_datetime_unit_from_string(basestr, len, NULL); if (out_meta->base == -1) { Py_DECREF(unit_str); return -1; } Py_DECREF(unit_str); /* Convert the values to longs */ out_meta->num = PyInt_AsLong(PyTuple_GET_ITEM(tuple, 1)); if (out_meta->num == -1 && PyErr_Occurred()) { return -1; } if (tuple_size == 4) { den = PyInt_AsLong(PyTuple_GET_ITEM(tuple, 2)); if (den == -1 && PyErr_Occurred()) { return -1; } } if (out_meta->num <= 0 || den <= 0) { PyErr_SetString(PyExc_TypeError, "Invalid tuple values for " "tuple to NumPy datetime metadata conversion"); return -1; } if (den != 1) { if (convert_datetime_divisor_to_multiple(out_meta, den, NULL) < 0) { return -1; } } return 0; } /* * Converts an input object into datetime metadata. The input * may be either a string or a tuple. * * Returns 0 on success, -1 on failure. */ NPY_NO_EXPORT int convert_pyobject_to_datetime_metadata(PyObject *obj, PyArray_DatetimeMetaData *out_meta) { PyObject *ascii = NULL; char *str = NULL; Py_ssize_t len = 0; if (PyTuple_Check(obj)) { return convert_datetime_metadata_tuple_to_datetime_metadata(obj, out_meta); } /* Get an ASCII string */ if (PyUnicode_Check(obj)) { /* Allow unicode format strings: convert to bytes */ ascii = PyUnicode_AsASCIIString(obj); if (ascii == NULL) { return -1; } } else if (PyBytes_Check(obj)) { ascii = obj; Py_INCREF(ascii); } else { PyErr_SetString(PyExc_TypeError, "Invalid object for specifying NumPy datetime metadata"); return -1; } if (PyBytes_AsStringAndSize(ascii, &str, &len) < 0) { return -1; } if (len > 0 && str[0] == '[') { return parse_datetime_metadata_from_metastr(str, len, out_meta); } else { if (parse_datetime_extended_unit_from_string(str, len, NULL, out_meta) < 0) { return -1; } return 0; } } /* * 'ret' is a PyUString containing the datetime string, and this * function appends the metadata string to it. * * If 'skip_brackets' is true, skips the '[]'. * * This function steals the reference 'ret' */ NPY_NO_EXPORT PyObject * append_metastr_to_string(PyArray_DatetimeMetaData *meta, int skip_brackets, PyObject *ret) { PyObject *res; int num; char *basestr; if (ret == NULL) { return NULL; } if (meta->base == NPY_FR_GENERIC) { /* Without brackets, give a string "generic" */ if (skip_brackets) { PyUString_ConcatAndDel(&ret, PyUString_FromString("generic")); return ret; } /* But with brackets, append nothing */ else { return ret; } } num = meta->num; if (meta->base >= 0 && meta->base < NPY_DATETIME_NUMUNITS) { basestr = _datetime_strings[meta->base]; } else { PyErr_SetString(PyExc_RuntimeError, "NumPy datetime metadata is corrupted"); return NULL; } if (num == 1) { if (skip_brackets) { res = PyUString_FromFormat("%s", basestr); } else { res = PyUString_FromFormat("[%s]", basestr); } } else { if (skip_brackets) { res = PyUString_FromFormat("%d%s", num, basestr); } else { res = PyUString_FromFormat("[%d%s]", num, basestr); } } PyUString_ConcatAndDel(&ret, res); return ret; } /* * Adjusts a datetimestruct based on a seconds offset. Assumes * the current values are valid. */ NPY_NO_EXPORT void add_seconds_to_datetimestruct(npy_datetimestruct *dts, int seconds) { int minutes; dts->sec += seconds; if (dts->sec < 0) { minutes = dts->sec / 60; dts->sec = dts->sec % 60; if (dts->sec < 0) { --minutes; dts->sec += 60; } add_minutes_to_datetimestruct(dts, minutes); } else if (dts->sec >= 60) { minutes = dts->sec / 60; dts->sec = dts->sec % 60; add_minutes_to_datetimestruct(dts, minutes); } } /* * Adjusts a datetimestruct based on a minutes offset. Assumes * the current values are valid. */ NPY_NO_EXPORT void add_minutes_to_datetimestruct(npy_datetimestruct *dts, int minutes) { int isleap; /* MINUTES */ dts->min += minutes; while (dts->min < 0) { dts->min += 60; dts->hour--; } while (dts->min >= 60) { dts->min -= 60; dts->hour++; } /* HOURS */ while (dts->hour < 0) { dts->hour += 24; dts->day--; } while (dts->hour >= 24) { dts->hour -= 24; dts->day++; } /* DAYS */ if (dts->day < 1) { dts->month--; if (dts->month < 1) { dts->year--; dts->month = 12; } isleap = is_leapyear(dts->year); dts->day += _days_per_month_table[isleap][dts->month-1]; } else if (dts->day > 28) { isleap = is_leapyear(dts->year); if (dts->day > _days_per_month_table[isleap][dts->month-1]) { dts->day -= _days_per_month_table[isleap][dts->month-1]; dts->month++; if (dts->month > 12) { dts->year++; dts->month = 1; } } } } /* * Tests for and converts a Python datetime.datetime or datetime.date * object into a NumPy npy_datetimestruct. * * While the C API has PyDate_* and PyDateTime_* functions, the following * implementation just asks for attributes, and thus supports * datetime duck typing. The tzinfo time zone conversion would require * this style of access anyway. * * 'out_bestunit' gives a suggested unit based on whether the object * was a datetime.date or datetime.datetime object. * * If 'apply_tzinfo' is 1, this function uses the tzinfo to convert * to UTC time, otherwise it returns the struct with the local time. * * Returns -1 on error, 0 on success, and 1 (with no error set) * if obj doesn't have the neeeded date or datetime attributes. */ NPY_NO_EXPORT int convert_pydatetime_to_datetimestruct(PyObject *obj, npy_datetimestruct *out, NPY_DATETIMEUNIT *out_bestunit, int apply_tzinfo) { PyObject *tmp; int isleap; /* Initialize the output to all zeros */ memset(out, 0, sizeof(npy_datetimestruct)); out->month = 1; out->day = 1; /* Need at least year/month/day attributes */ if (!PyObject_HasAttrString(obj, "year") || !PyObject_HasAttrString(obj, "month") || !PyObject_HasAttrString(obj, "day")) { return 1; } /* Get the year */ tmp = PyObject_GetAttrString(obj, "year"); if (tmp == NULL) { return -1; } out->year = PyInt_AsLong(tmp); if (out->year == -1 && PyErr_Occurred()) { Py_DECREF(tmp); return -1; } Py_DECREF(tmp); /* Get the month */ tmp = PyObject_GetAttrString(obj, "month"); if (tmp == NULL) { return -1; } out->month = PyInt_AsLong(tmp); if (out->month == -1 && PyErr_Occurred()) { Py_DECREF(tmp); return -1; } Py_DECREF(tmp); /* Get the day */ tmp = PyObject_GetAttrString(obj, "day"); if (tmp == NULL) { return -1; } out->day = PyInt_AsLong(tmp); if (out->day == -1 && PyErr_Occurred()) { Py_DECREF(tmp); return -1; } Py_DECREF(tmp); /* Validate that the month and day are valid for the year */ if (out->month < 1 || out->month > 12) { goto invalid_date; } isleap = is_leapyear(out->year); if (out->day < 1 || out->day > _days_per_month_table[isleap][out->month-1]) { goto invalid_date; } /* Check for time attributes (if not there, return success as a date) */ if (!PyObject_HasAttrString(obj, "hour") || !PyObject_HasAttrString(obj, "minute") || !PyObject_HasAttrString(obj, "second") || !PyObject_HasAttrString(obj, "microsecond")) { /* The best unit for date is 'D' */ if (out_bestunit != NULL) { *out_bestunit = NPY_FR_D; } return 0; } /* Get the hour */ tmp = PyObject_GetAttrString(obj, "hour"); if (tmp == NULL) { return -1; } out->hour = PyInt_AsLong(tmp); if (out->hour == -1 && PyErr_Occurred()) { Py_DECREF(tmp); return -1; } Py_DECREF(tmp); /* Get the minute */ tmp = PyObject_GetAttrString(obj, "minute"); if (tmp == NULL) { return -1; } out->min = PyInt_AsLong(tmp); if (out->min == -1 && PyErr_Occurred()) { Py_DECREF(tmp); return -1; } Py_DECREF(tmp); /* Get the second */ tmp = PyObject_GetAttrString(obj, "second"); if (tmp == NULL) { return -1; } out->sec = PyInt_AsLong(tmp); if (out->sec == -1 && PyErr_Occurred()) { Py_DECREF(tmp); return -1; } Py_DECREF(tmp); /* Get the microsecond */ tmp = PyObject_GetAttrString(obj, "microsecond"); if (tmp == NULL) { return -1; } out->us = PyInt_AsLong(tmp); if (out->us == -1 && PyErr_Occurred()) { Py_DECREF(tmp); return -1; } Py_DECREF(tmp); if (out->hour < 0 || out->hour >= 24 || out->min < 0 || out->min >= 60 || out->sec < 0 || out->sec >= 60 || out->us < 0 || out->us >= 1000000) { goto invalid_time; } /* Apply the time zone offset if it exists */ if (apply_tzinfo && PyObject_HasAttrString(obj, "tzinfo")) { tmp = PyObject_GetAttrString(obj, "tzinfo"); if (tmp == NULL) { return -1; } if (tmp == Py_None) { Py_DECREF(tmp); } else { PyObject *offset; int seconds_offset, minutes_offset; /* The utcoffset function should return a timedelta */ offset = PyObject_CallMethod(tmp, "utcoffset", "O", obj); if (offset == NULL) { Py_DECREF(tmp); return -1; } Py_DECREF(tmp); /* * The timedelta should have a function "total_seconds" * which contains the value we want. */ tmp = PyObject_CallMethod(offset, "total_seconds", ""); if (tmp == NULL) { return -1; } seconds_offset = PyInt_AsLong(tmp); if (seconds_offset == -1 && PyErr_Occurred()) { Py_DECREF(tmp); return -1; } Py_DECREF(tmp); /* Convert to a minutes offset and apply it */ minutes_offset = seconds_offset / 60; add_minutes_to_datetimestruct(out, -minutes_offset); } } /* The resolution of Python's datetime is 'us' */ if (out_bestunit != NULL) { *out_bestunit = NPY_FR_us; } return 0; invalid_date: PyErr_Format(PyExc_ValueError, "Invalid date (%d,%d,%d) when converting to NumPy datetime", (int)out->year, (int)out->month, (int)out->day); return -1; invalid_time: PyErr_Format(PyExc_ValueError, "Invalid time (%d,%d,%d,%d) when converting " "to NumPy datetime", (int)out->hour, (int)out->min, (int)out->sec, (int)out->us); return -1; } /* * Gets a tzoffset in minutes by calling the fromutc() function on * the Python datetime.tzinfo object. */ NPY_NO_EXPORT int get_tzoffset_from_pytzinfo(PyObject *timezone_obj, npy_datetimestruct *dts) { PyObject *dt, *loc_dt; npy_datetimestruct loc_dts; /* Create a Python datetime to give to the timezone object */ dt = PyDateTime_FromDateAndTime((int)dts->year, dts->month, dts->day, dts->hour, dts->min, 0, 0); if (dt == NULL) { return -1; } /* Convert the datetime from UTC to local time */ loc_dt = PyObject_CallMethod(timezone_obj, "fromutc", "O", dt); Py_DECREF(dt); if (loc_dt == NULL) { return -1; } /* Convert the local datetime into a datetimestruct */ if (convert_pydatetime_to_datetimestruct(loc_dt, &loc_dts, NULL, 0) < 0) { Py_DECREF(loc_dt); return -1; } Py_DECREF(loc_dt); /* Calculate the tzoffset as the difference between the datetimes */ return (int)(get_datetimestruct_minutes(&loc_dts) - get_datetimestruct_minutes(dts)); } /* * Converts a PyObject * into a datetime, in any of the forms supported. * * If the units metadata isn't known ahead of time, set meta->base * to -1, and this function will populate meta with either default * values or values from the input object. * * The 'casting' parameter is used to control what kinds of inputs * are accepted, and what happens. For example, with 'unsafe' casting, * unrecognized inputs are converted to 'NaT' instead of throwing an error, * while with 'safe' casting an error will be thrown if any precision * from the input will be thrown away. * * Returns -1 on error, 0 on success. */ NPY_NO_EXPORT int convert_pyobject_to_datetime(PyArray_DatetimeMetaData *meta, PyObject *obj, NPY_CASTING casting, npy_datetime *out) { if (PyBytes_Check(obj) || PyUnicode_Check(obj)) { PyObject *bytes = NULL; char *str = NULL; Py_ssize_t len = 0; npy_datetimestruct dts; NPY_DATETIMEUNIT bestunit = -1; /* Convert to an ASCII string for the date parser */ if (PyUnicode_Check(obj)) { bytes = PyUnicode_AsASCIIString(obj); if (bytes == NULL) { return -1; } } else { bytes = obj; Py_INCREF(bytes); } if (PyBytes_AsStringAndSize(bytes, &str, &len) == -1) { Py_DECREF(bytes); return -1; } /* Parse the ISO date */ if (parse_iso_8601_datetime(str, len, meta->base, casting, &dts, NULL, &bestunit, NULL) < 0) { Py_DECREF(bytes); return -1; } Py_DECREF(bytes); /* Use the detected unit if none was specified */ if (meta->base == -1) { meta->base = bestunit; meta->num = 1; } if (convert_datetimestruct_to_datetime(meta, &dts, out) < 0) { return -1; } return 0; } /* Do no conversion on raw integers */ else if (PyInt_Check(obj) || PyLong_Check(obj)) { /* Don't allow conversion from an integer without specifying a unit */ if (meta->base == -1 || meta->base == NPY_FR_GENERIC) { PyErr_SetString(PyExc_ValueError, "Converting an integer to a " "NumPy datetime requires a specified unit"); return -1; } *out = PyLong_AsLongLong(obj); return 0; } /* Datetime scalar */ else if (PyArray_IsScalar(obj, Datetime)) { PyDatetimeScalarObject *dts = (PyDatetimeScalarObject *)obj; /* Copy the scalar directly if units weren't specified */ if (meta->base == -1) { *meta = dts->obmeta; *out = dts->obval; return 0; } /* Otherwise do a casting transformation */ else { /* Allow NaT (not-a-time) values to slip through any rule */ if (dts->obval != NPY_DATETIME_NAT && raise_if_datetime64_metadata_cast_error( "NumPy timedelta64 scalar", &dts->obmeta, meta, casting) < 0) { return -1; } else { return cast_datetime_to_datetime(&dts->obmeta, meta, dts->obval, out); } } } /* Datetime zero-dimensional array */ else if (PyArray_Check(obj) && PyArray_NDIM((PyArrayObject *)obj) == 0 && PyArray_DESCR((PyArrayObject *)obj)->type_num == NPY_DATETIME) { PyArrayObject *arr = (PyArrayObject *)obj; PyArray_DatetimeMetaData *arr_meta; npy_datetime dt = 0; arr_meta = get_datetime_metadata_from_dtype(PyArray_DESCR(arr)); if (arr_meta == NULL) { return -1; } PyArray_DESCR(arr)->f->copyswap(&dt, PyArray_DATA(arr), !PyArray_ISNOTSWAPPED(arr), obj); /* Copy the value directly if units weren't specified */ if (meta->base == -1) { *meta = *arr_meta; *out = dt; return 0; } /* Otherwise do a casting transformation */ else { /* Allow NaT (not-a-time) values to slip through any rule */ if (dt != NPY_DATETIME_NAT && raise_if_datetime64_metadata_cast_error( "NumPy timedelta64 scalar", arr_meta, meta, casting) < 0) { return -1; } else { return cast_datetime_to_datetime(arr_meta, meta, dt, out); } } } /* Convert from a Python date or datetime object */ else { int code; npy_datetimestruct dts; NPY_DATETIMEUNIT bestunit = -1; code = convert_pydatetime_to_datetimestruct(obj, &dts, &bestunit, 1); if (code == -1) { return -1; } else if (code == 0) { /* Use the detected unit if none was specified */ if (meta->base == -1) { meta->base = bestunit; meta->num = 1; } else { PyArray_DatetimeMetaData obj_meta; obj_meta.base = bestunit; obj_meta.num = 1; if (raise_if_datetime64_metadata_cast_error( bestunit == NPY_FR_D ? "datetime.date object" : "datetime.datetime object", &obj_meta, meta, casting) < 0) { return -1; } } return convert_datetimestruct_to_datetime(meta, &dts, out); } } /* * With unsafe casting, convert unrecognized objects into NaT * and with same_kind casting, convert None into NaT */ if (casting == NPY_UNSAFE_CASTING || (obj == Py_None && casting == NPY_SAME_KIND_CASTING)) { if (meta->base == -1) { meta->base = NPY_FR_GENERIC; meta->num = 1; } *out = NPY_DATETIME_NAT; return 0; } else { PyErr_SetString(PyExc_ValueError, "Could not convert object to NumPy datetime"); return -1; } } /* * Converts a PyObject * into a timedelta, in any of the forms supported * * If the units metadata isn't known ahead of time, set meta->base * to -1, and this function will populate meta with either default * values or values from the input object. * * The 'casting' parameter is used to control what kinds of inputs * are accepted, and what happens. For example, with 'unsafe' casting, * unrecognized inputs are converted to 'NaT' instead of throwing an error, * while with 'safe' casting an error will be thrown if any precision * from the input will be thrown away. * * Returns -1 on error, 0 on success. */ NPY_NO_EXPORT int convert_pyobject_to_timedelta(PyArray_DatetimeMetaData *meta, PyObject *obj, NPY_CASTING casting, npy_timedelta *out) { if (PyBytes_Check(obj) || PyUnicode_Check(obj)) { PyObject *bytes = NULL; char *str = NULL; Py_ssize_t len = 0; int succeeded = 0; /* Convert to an ASCII string for the date parser */ if (PyUnicode_Check(obj)) { bytes = PyUnicode_AsASCIIString(obj); if (bytes == NULL) { return -1; } } else { bytes = obj; Py_INCREF(bytes); } if (PyBytes_AsStringAndSize(bytes, &str, &len) == -1) { Py_DECREF(bytes); return -1; } /* Check for a NaT string */ if (len <= 0 || (len == 3 && tolower(str[0]) == 'n' && tolower(str[1]) == 'a' && tolower(str[2]) == 't')) { *out = NPY_DATETIME_NAT; succeeded = 1; } /* Parse as an integer */ else { char *strend = NULL; *out = strtol(str, &strend, 10); if (strend - str == len) { succeeded = 1; } } if (succeeded) { /* Use generic units if none was specified */ if (meta->base == -1) { meta->base = NPY_FR_GENERIC; meta->num = 1; } return 0; } } /* Do no conversion on raw integers */ else if (PyInt_Check(obj) || PyLong_Check(obj)) { /* Use the default unit if none was specified */ if (meta->base == -1) { meta->base = NPY_DATETIME_DEFAULTUNIT; meta->num = 1; } *out = PyLong_AsLongLong(obj); return 0; } /* Timedelta scalar */ else if (PyArray_IsScalar(obj, Timedelta)) { PyTimedeltaScalarObject *dts = (PyTimedeltaScalarObject *)obj; /* Copy the scalar directly if units weren't specified */ if (meta->base == -1) { *meta = dts->obmeta; *out = dts->obval; return 0; } /* Otherwise do a casting transformation */ else { /* Allow NaT (not-a-time) values to slip through any rule */ if (dts->obval != NPY_DATETIME_NAT && raise_if_timedelta64_metadata_cast_error( "NumPy timedelta64 scalar", &dts->obmeta, meta, casting) < 0) { return -1; } else { return cast_timedelta_to_timedelta(&dts->obmeta, meta, dts->obval, out); } } } /* Timedelta zero-dimensional array */ else if (PyArray_Check(obj) && PyArray_NDIM((PyArrayObject *)obj) == 0 && PyArray_DESCR((PyArrayObject *)obj)->type_num == NPY_TIMEDELTA) { PyArrayObject *arr = (PyArrayObject *)obj; PyArray_DatetimeMetaData *arr_meta; npy_timedelta dt = 0; arr_meta = get_datetime_metadata_from_dtype(PyArray_DESCR(arr)); if (arr_meta == NULL) { return -1; } PyArray_DESCR(arr)->f->copyswap(&dt, PyArray_DATA(arr), !PyArray_ISNOTSWAPPED(arr), obj); /* Copy the value directly if units weren't specified */ if (meta->base == -1) { *meta = *arr_meta; *out = dt; return 0; } /* Otherwise do a casting transformation */ else { /* Allow NaT (not-a-time) values to slip through any rule */ if (dt != NPY_DATETIME_NAT && raise_if_timedelta64_metadata_cast_error( "NumPy timedelta64 scalar", arr_meta, meta, casting) < 0) { return -1; } else { return cast_timedelta_to_timedelta(arr_meta, meta, dt, out); } } } /* Convert from a Python timedelta object */ else if (PyObject_HasAttrString(obj, "days") && PyObject_HasAttrString(obj, "seconds") && PyObject_HasAttrString(obj, "microseconds")) { PyObject *tmp; PyArray_DatetimeMetaData us_meta; npy_timedelta td; npy_int64 days; int seconds = 0, useconds = 0; /* Get the days */ tmp = PyObject_GetAttrString(obj, "days"); if (tmp == NULL) { return -1; } days = PyLong_AsLongLong(tmp); if (days == -1 && PyErr_Occurred()) { Py_DECREF(tmp); return -1; } Py_DECREF(tmp); /* Get the seconds */ tmp = PyObject_GetAttrString(obj, "seconds"); if (tmp == NULL) { return -1; } seconds = PyInt_AsLong(tmp); if (seconds == -1 && PyErr_Occurred()) { Py_DECREF(tmp); return -1; } Py_DECREF(tmp); /* Get the microseconds */ tmp = PyObject_GetAttrString(obj, "microseconds"); if (tmp == NULL) { return -1; } useconds = PyInt_AsLong(tmp); if (useconds == -1 && PyErr_Occurred()) { Py_DECREF(tmp); return -1; } Py_DECREF(tmp); td = days*(24*60*60*1000000LL) + seconds*1000000LL + useconds; /* Use microseconds if none was specified */ if (meta->base == -1) { meta->base = NPY_FR_us; meta->num = 1; *out = td; return 0; } else { /* * Detect the largest unit where every value after is zero, * to allow safe casting to seconds if microseconds is zero, * for instance. */ if (td % 1000LL != 0) { us_meta.base = NPY_FR_us; } else if (td % 1000000LL != 0) { us_meta.base = NPY_FR_ms; } else if (td % (60*1000000LL) != 0) { us_meta.base = NPY_FR_s; } else if (td % (60*60*1000000LL) != 0) { us_meta.base = NPY_FR_m; } else if (td % (24*60*60*1000000LL) != 0) { us_meta.base = NPY_FR_D; } else if (td % (7*24*60*60*1000000LL) != 0) { us_meta.base = NPY_FR_W; } us_meta.num = 1; if (raise_if_timedelta64_metadata_cast_error( "datetime.timedelta object", &us_meta, meta, casting) < 0) { return -1; } else { /* Switch back to microseconds for the casting operation */ us_meta.base = NPY_FR_us; return cast_timedelta_to_timedelta(&us_meta, meta, td, out); } } } /* * With unsafe casting, convert unrecognized objects into NaT * and with same_kind casting, convert None into NaT */ if (casting == NPY_UNSAFE_CASTING || (obj == Py_None && casting == NPY_SAME_KIND_CASTING)) { if (meta->base == -1) { meta->base = NPY_FR_GENERIC; meta->num = 1; } *out = NPY_DATETIME_NAT; return 0; } else { PyErr_SetString(PyExc_ValueError, "Could not convert object to NumPy timedelta"); return -1; } } /* * Converts a datetime into a PyObject *. * * Not-a-time is returned as the string "NaT". * For days or coarser, returns a datetime.date. * For microseconds or coarser, returns a datetime.datetime. * For units finer than microseconds, returns an integer. */ NPY_NO_EXPORT PyObject * convert_datetime_to_pyobject(npy_datetime dt, PyArray_DatetimeMetaData *meta) { PyObject *ret = NULL; npy_datetimestruct dts; /* * Convert NaT (not-a-time) and any value with generic units * into None. */ if (dt == NPY_DATETIME_NAT || meta->base == NPY_FR_GENERIC) { Py_INCREF(Py_None); return Py_None; } /* If the type's precision is greater than microseconds, return an int */ if (meta->base > NPY_FR_us) { return PyLong_FromLongLong(dt); } /* Convert to a datetimestruct */ if (convert_datetime_to_datetimestruct(meta, dt, &dts) < 0) { return NULL; } /* * If the year is outside the range of years supported by Python's * datetime, or the datetime64 falls on a leap second, * return a raw int. */ if (dts.year < 1 || dts.year > 9999 || dts.sec == 60) { return PyLong_FromLongLong(dt); } /* If the type's precision is greater than days, return a datetime */ if (meta->base > NPY_FR_D) { ret = PyDateTime_FromDateAndTime(dts.year, dts.month, dts.day, dts.hour, dts.min, dts.sec, dts.us); } /* Otherwise return a date */ else { ret = PyDate_FromDate(dts.year, dts.month, dts.day); } return ret; } /* * Converts a timedelta into a PyObject *. * * Not-a-time is returned as the string "NaT". * For microseconds or coarser, returns a datetime.timedelta. * For units finer than microseconds, returns an integer. */ NPY_NO_EXPORT PyObject * convert_timedelta_to_pyobject(npy_timedelta td, PyArray_DatetimeMetaData *meta) { PyObject *ret = NULL; npy_timedelta value; int days = 0, seconds = 0, useconds = 0; /* * Convert NaT (not-a-time) into None. */ if (td == NPY_DATETIME_NAT) { Py_INCREF(Py_None); return Py_None; } /* * If the type's precision is greater than microseconds, is * Y/M/B (nonlinear units), or is generic units, return an int */ if (meta->base > NPY_FR_us || meta->base == NPY_FR_Y || meta->base == NPY_FR_M || meta->base == NPY_FR_GENERIC) { return PyLong_FromLongLong(td); } value = td; /* Apply the unit multiplier (TODO: overflow treatment...) */ value *= meta->num; /* Convert to days/seconds/useconds */ switch (meta->base) { case NPY_FR_W: value *= 7; break; case NPY_FR_D: break; case NPY_FR_h: seconds = (int)((value % 24) * (60*60)); value = value / 24; break; case NPY_FR_m: seconds = (int)(value % (24*60)) * 60; value = value / (24*60); break; case NPY_FR_s: seconds = (int)(value % (24*60*60)); value = value / (24*60*60); break; case NPY_FR_ms: useconds = (int)(value % 1000) * 1000; value = value / 1000; seconds = (int)(value % (24*60*60)); value = value / (24*60*60); break; case NPY_FR_us: useconds = (int)(value % (1000*1000)); value = value / (1000*1000); seconds = (int)(value % (24*60*60)); value = value / (24*60*60); break; default: break; } /* * 'value' represents days, and seconds/useconds are filled. * * If it would overflow the datetime.timedelta days, return a raw int */ if (value < -999999999 || value > 999999999) { return PyLong_FromLongLong(td); } else { days = (int)value; ret = PyDelta_FromDSU(days, seconds, useconds); if (ret == NULL) { return NULL; } } return ret; } /* * Returns true if the datetime metadata matches */ NPY_NO_EXPORT npy_bool has_equivalent_datetime_metadata(PyArray_Descr *type1, PyArray_Descr *type2) { PyArray_DatetimeMetaData *meta1, *meta2; if ((type1->type_num != NPY_DATETIME && type1->type_num != NPY_TIMEDELTA) || (type2->type_num != NPY_DATETIME && type2->type_num != NPY_TIMEDELTA)) { return 0; } meta1 = get_datetime_metadata_from_dtype(type1); if (meta1 == NULL) { PyErr_Clear(); return 0; } meta2 = get_datetime_metadata_from_dtype(type2); if (meta2 == NULL) { PyErr_Clear(); return 0; } /* For generic units, the num is ignored */ if (meta1->base == NPY_FR_GENERIC && meta2->base == NPY_FR_GENERIC) { return 1; } return meta1->base == meta2->base && meta1->num == meta2->num; } /* * Casts a single datetime from having src_meta metadata into * dst_meta metadata. * * Returns 0 on success, -1 on failure. */ NPY_NO_EXPORT int cast_datetime_to_datetime(PyArray_DatetimeMetaData *src_meta, PyArray_DatetimeMetaData *dst_meta, npy_datetime src_dt, npy_datetime *dst_dt) { npy_datetimestruct dts; /* If the metadata is the same, short-circuit the conversion */ if (src_meta->base == dst_meta->base && src_meta->num == dst_meta->num) { *dst_dt = src_dt; return 0; } /* Otherwise convert through a datetimestruct */ if (convert_datetime_to_datetimestruct(src_meta, src_dt, &dts) < 0) { *dst_dt = NPY_DATETIME_NAT; return -1; } if (convert_datetimestruct_to_datetime(dst_meta, &dts, dst_dt) < 0) { *dst_dt = NPY_DATETIME_NAT; return -1; } return 0; } /* * Casts a single timedelta from having src_meta metadata into * dst_meta metadata. * * Returns 0 on success, -1 on failure. */ NPY_NO_EXPORT int cast_timedelta_to_timedelta(PyArray_DatetimeMetaData *src_meta, PyArray_DatetimeMetaData *dst_meta, npy_timedelta src_dt, npy_timedelta *dst_dt) { npy_int64 num = 0, denom = 0; /* If the metadata is the same, short-circuit the conversion */ if (src_meta->base == dst_meta->base && src_meta->num == dst_meta->num) { *dst_dt = src_dt; return 0; } /* Get the conversion factor */ get_datetime_conversion_factor(src_meta, dst_meta, &num, &denom); if (num == 0) { return -1; } /* Apply the scaling */ if (src_dt < 0) { *dst_dt = (src_dt * num - (denom - 1)) / denom; } else { *dst_dt = src_dt * num / denom; } return 0; } /* * Returns true if the object is something that is best considered * a Datetime, false otherwise. */ static npy_bool is_any_numpy_datetime(PyObject *obj) { return (PyArray_IsScalar(obj, Datetime) || (PyArray_Check(obj) && ( PyArray_DESCR((PyArrayObject *)obj)->type_num == NPY_DATETIME)) || PyDate_Check(obj) || PyDateTime_Check(obj)); } /* * Returns true if the object is something that is best considered * a Timedelta, false otherwise. */ static npy_bool is_any_numpy_timedelta(PyObject *obj) { return (PyArray_IsScalar(obj, Timedelta) || (PyArray_Check(obj) && ( PyArray_DESCR((PyArrayObject *)obj)->type_num == NPY_TIMEDELTA)) || PyDelta_Check(obj)); } /* * Returns true if the object is something that is best considered * a Datetime or Timedelta, false otherwise. */ NPY_NO_EXPORT npy_bool is_any_numpy_datetime_or_timedelta(PyObject *obj) { return obj != NULL && (is_any_numpy_datetime(obj) || is_any_numpy_timedelta(obj)); } /* * Converts an array of PyObject * into datetimes and/or timedeltas, * based on the values in type_nums. * * If inout_meta->base is -1, uses GCDs to calculate the metadata, filling * in 'inout_meta' with the resulting metadata. Otherwise uses the provided * 'inout_meta' for all the conversions. * * When obj[i] is NULL, out_value[i] will be set to NPY_DATETIME_NAT. * * Returns 0 on success, -1 on failure. */ NPY_NO_EXPORT int convert_pyobjects_to_datetimes(int count, PyObject **objs, int *type_nums, NPY_CASTING casting, npy_int64 *out_values, PyArray_DatetimeMetaData *inout_meta) { int i, is_out_strict; PyArray_DatetimeMetaData *meta; /* No values trivially succeeds */ if (count == 0) { return 0; } /* Use the inputs to resolve the unit metadata if requested */ if (inout_meta->base == -1) { /* Allocate an array of metadata corresponding to the objects */ meta = PyArray_malloc(count * sizeof(PyArray_DatetimeMetaData)); if (meta == NULL) { PyErr_NoMemory(); return -1; } /* Convert all the objects into timedeltas or datetimes */ for (i = 0; i < count; ++i) { meta[i].base = -1; meta[i].num = 1; /* NULL -> NaT */ if (objs[i] == NULL) { out_values[i] = NPY_DATETIME_NAT; meta[i].base = NPY_FR_GENERIC; } else if (type_nums[i] == NPY_DATETIME) { if (convert_pyobject_to_datetime(&meta[i], objs[i], casting, &out_values[i]) < 0) { PyArray_free(meta); return -1; } } else if (type_nums[i] == NPY_TIMEDELTA) { if (convert_pyobject_to_timedelta(&meta[i], objs[i], casting, &out_values[i]) < 0) { PyArray_free(meta); return -1; } } else { PyErr_SetString(PyExc_ValueError, "convert_pyobjects_to_datetimes requires that " "all the type_nums provided be datetime or timedelta"); PyArray_free(meta); return -1; } } /* Merge all the metadatas, starting with the first one */ *inout_meta = meta[0]; is_out_strict = (type_nums[0] == NPY_TIMEDELTA); for (i = 1; i < count; ++i) { if (compute_datetime_metadata_greatest_common_divisor( &meta[i], inout_meta, inout_meta, type_nums[i] == NPY_TIMEDELTA, is_out_strict) < 0) { PyArray_free(meta); return -1; } is_out_strict = is_out_strict || (type_nums[i] == NPY_TIMEDELTA); } /* Convert all the values into the resolved unit metadata */ for (i = 0; i < count; ++i) { if (type_nums[i] == NPY_DATETIME) { if (cast_datetime_to_datetime(&meta[i], inout_meta, out_values[i], &out_values[i]) < 0) { PyArray_free(meta); return -1; } } else if (type_nums[i] == NPY_TIMEDELTA) { if (cast_timedelta_to_timedelta(&meta[i], inout_meta, out_values[i], &out_values[i]) < 0) { PyArray_free(meta); return -1; } } } PyArray_free(meta); } /* Otherwise convert to the provided unit metadata */ else { /* Convert all the objects into timedeltas or datetimes */ for (i = 0; i < count; ++i) { /* NULL -> NaT */ if (objs[i] == NULL) { out_values[i] = NPY_DATETIME_NAT; } else if (type_nums[i] == NPY_DATETIME) { if (convert_pyobject_to_datetime(inout_meta, objs[i], casting, &out_values[i]) < 0) { return -1; } } else if (type_nums[i] == NPY_TIMEDELTA) { if (convert_pyobject_to_timedelta(inout_meta, objs[i], casting, &out_values[i]) < 0) { return -1; } } else { PyErr_SetString(PyExc_ValueError, "convert_pyobjects_to_datetimes requires that " "all the type_nums provided be datetime or timedelta"); return -1; } } } return 0; } NPY_NO_EXPORT PyArrayObject * datetime_arange(PyObject *start, PyObject *stop, PyObject *step, PyArray_Descr *dtype) { PyArray_DatetimeMetaData meta; /* * Both datetime and timedelta are stored as int64, so they can * share value variables. */ npy_int64 values[3]; PyObject *objs[3]; int type_nums[3]; npy_intp i, length; PyArrayObject *ret; npy_int64 *ret_data; /* * First normalize the input parameters so there is no Py_None, * and start is moved to stop if stop is unspecified. */ if (step == Py_None) { step = NULL; } if (stop == NULL || stop == Py_None) { stop = start; start = NULL; /* If start was NULL or None, raise an exception */ if (stop == NULL || stop == Py_None) { PyErr_SetString(PyExc_ValueError, "arange needs at least a stopping value"); return NULL; } } if (start == Py_None) { start = NULL; } /* Step must not be a Datetime */ if (step != NULL && is_any_numpy_datetime(step)) { PyErr_SetString(PyExc_ValueError, "cannot use a datetime as a step in arange"); return NULL; } /* Check if the units of the given dtype are generic, in which * case we use the code path that detects the units */ if (dtype != NULL) { PyArray_DatetimeMetaData *meta_tmp; type_nums[0] = dtype->type_num; if (type_nums[0] != NPY_DATETIME && type_nums[0] != NPY_TIMEDELTA) { PyErr_SetString(PyExc_ValueError, "datetime_arange was given a non-datetime dtype"); return NULL; } meta_tmp = get_datetime_metadata_from_dtype(dtype); if (meta_tmp == NULL) { return NULL; } /* * If the dtype specified is in generic units, detect the * units from the input parameters. */ if (meta_tmp->base == NPY_FR_GENERIC) { dtype = NULL; meta.base = -1; } /* Otherwise use the provided metadata */ else { meta = *meta_tmp; } } else { if (is_any_numpy_datetime(start) || is_any_numpy_datetime(stop)) { type_nums[0] = NPY_DATETIME; } else { type_nums[0] = NPY_TIMEDELTA; } meta.base = -1; } if (type_nums[0] == NPY_DATETIME && start == NULL) { PyErr_SetString(PyExc_ValueError, "arange requires both a start and a stop for " "NumPy datetime64 ranges"); return NULL; } /* Set up to convert the objects to a common datetime unit metadata */ objs[0] = start; objs[1] = stop; objs[2] = step; if (type_nums[0] == NPY_TIMEDELTA) { type_nums[1] = NPY_TIMEDELTA; type_nums[2] = NPY_TIMEDELTA; } else { if (PyInt_Check(objs[1]) || PyLong_Check(objs[1]) || PyArray_IsScalar(objs[1], Integer) || is_any_numpy_timedelta(objs[1])) { type_nums[1] = NPY_TIMEDELTA; } else { type_nums[1] = NPY_DATETIME; } type_nums[2] = NPY_TIMEDELTA; } /* Convert all the arguments */ if (convert_pyobjects_to_datetimes(3, objs, type_nums, NPY_SAME_KIND_CASTING, values, &meta) < 0) { return NULL; } /* If no step was provided, default to 1 */ if (step == NULL) { values[2] = 1; } /* * In the case of arange(datetime, timedelta), convert * the timedelta into a datetime by adding the start datetime. */ if (type_nums[0] == NPY_DATETIME && type_nums[1] == NPY_TIMEDELTA) { values[1] += values[0]; } /* Now start, stop, and step have their values and matching metadata */ if (values[0] == NPY_DATETIME_NAT || values[1] == NPY_DATETIME_NAT || values[2] == NPY_DATETIME_NAT) { PyErr_SetString(PyExc_ValueError, "arange: cannot use NaT (not-a-time) datetime values"); return NULL; } /* Calculate the array length */ if (values[2] > 0 && values[1] > values[0]) { length = (values[1] - values[0] + (values[2] - 1)) / values[2]; } else if (values[2] < 0 && values[1] < values[0]) { length = (values[1] - values[0] + (values[2] + 1)) / values[2]; } else if (values[2] != 0) { length = 0; } else { PyErr_SetString(PyExc_ValueError, "arange: step cannot be zero"); return NULL; } /* Create the dtype of the result */ if (dtype != NULL) { Py_INCREF(dtype); } else { dtype = create_datetime_dtype(type_nums[0], &meta); if (dtype == NULL) { return NULL; } } /* Create the result array */ ret = (PyArrayObject *)PyArray_NewFromDescr( &PyArray_Type, dtype, 1, &length, NULL, NULL, 0, NULL); if (ret == NULL) { return NULL; } if (length > 0) { /* Extract the data pointer */ ret_data = (npy_int64 *)PyArray_DATA(ret); /* Create the timedeltas or datetimes */ for (i = 0; i < length; ++i) { *ret_data = values[0]; values[0] += values[2]; ret_data++; } } return ret; } /* * Examines all the strings in the given string array, and parses them * to find the right metadata. * * Returns 0 on success, -1 on failure. */ static int find_string_array_datetime64_type(PyArrayObject *arr, PyArray_DatetimeMetaData *meta) { NpyIter* iter; NpyIter_IterNextFunc *iternext; char **dataptr; npy_intp *strideptr, *innersizeptr; PyArray_Descr *string_dtype; int maxlen; char *tmp_buffer = NULL; npy_datetimestruct dts; PyArray_DatetimeMetaData tmp_meta; /* Handle zero-sized arrays specially */ if (PyArray_SIZE(arr) == 0) { return 0; } string_dtype = PyArray_DescrFromType(NPY_STRING); if (string_dtype == NULL) { return -1; } /* Use unsafe casting to allow unicode -> ascii string */ iter = NpyIter_New((PyArrayObject *)arr, NPY_ITER_READONLY| NPY_ITER_EXTERNAL_LOOP| NPY_ITER_BUFFERED, NPY_KEEPORDER, NPY_UNSAFE_CASTING, string_dtype); Py_DECREF(string_dtype); if (iter == NULL) { return -1; } iternext = NpyIter_GetIterNext(iter, NULL); if (iternext == NULL) { NpyIter_Deallocate(iter); return -1; } dataptr = NpyIter_GetDataPtrArray(iter); strideptr = NpyIter_GetInnerStrideArray(iter); innersizeptr = NpyIter_GetInnerLoopSizePtr(iter); /* Get the resulting string length */ maxlen = NpyIter_GetDescrArray(iter)[0]->elsize; /* Allocate a buffer for strings which fill the buffer completely */ tmp_buffer = PyArray_malloc(maxlen+1); if (tmp_buffer == NULL) { PyErr_NoMemory(); NpyIter_Deallocate(iter); return -1; } /* The iteration loop */ do { /* Get the inner loop data/stride/count values */ char* data = *dataptr; npy_intp stride = *strideptr; npy_intp count = *innersizeptr; char *tmp; /* The inner loop */ while (count--) { /* Replicating strnlen with memchr, because Mac OS X lacks it */ tmp = memchr(data, '\0', maxlen); /* If the string is all full, use the buffer */ if (tmp == NULL) { memcpy(tmp_buffer, data, maxlen); tmp_buffer[maxlen] = '\0'; tmp_meta.base = -1; if (parse_iso_8601_datetime(tmp_buffer, maxlen, -1, NPY_UNSAFE_CASTING, &dts, NULL, &tmp_meta.base, NULL) < 0) { goto fail; } } /* Otherwise parse the data in place */ else { tmp_meta.base = -1; if (parse_iso_8601_datetime(data, tmp - data, -1, NPY_UNSAFE_CASTING, &dts, NULL, &tmp_meta.base, NULL) < 0) { goto fail; } } tmp_meta.num = 1; /* Combine it with 'meta' */ if (compute_datetime_metadata_greatest_common_divisor(meta, &tmp_meta, meta, 0, 0) < 0) { goto fail; } data += stride; } } while(iternext(iter)); PyArray_free(tmp_buffer); NpyIter_Deallocate(iter); return 0; fail: if (tmp_buffer != NULL) { PyArray_free(tmp_buffer); } if (iter != NULL) { NpyIter_Deallocate(iter); } return -1; } /* * Recursively determines the metadata for an NPY_DATETIME dtype. * * Returns 0 on success, -1 on failure. */ static int recursive_find_object_datetime64_type(PyObject *obj, PyArray_DatetimeMetaData *meta) { /* Array -> use its metadata */ if (PyArray_Check(obj)) { PyArrayObject *arr = (PyArrayObject *)obj; PyArray_Descr *arr_dtype = PyArray_DESCR(arr); if (arr_dtype->type_num == NPY_STRING || arr_dtype->type_num == NPY_UNICODE) { return find_string_array_datetime64_type(arr, meta); } /* If the array has metadata, use it */ else if (arr_dtype->type_num == NPY_DATETIME || arr_dtype->type_num == NPY_TIMEDELTA) { PyArray_DatetimeMetaData *tmp_meta; /* Get the metadata from the type */ tmp_meta = get_datetime_metadata_from_dtype(arr_dtype); if (tmp_meta == NULL) { return -1; } /* Combine it with 'meta' */ if (compute_datetime_metadata_greatest_common_divisor(meta, tmp_meta, meta, 0, 0) < 0) { return -1; } return 0; } /* If it's not an object array, stop looking */ else if (arr_dtype->type_num != NPY_OBJECT) { return 0; } } /* Datetime scalar -> use its metadata */ else if (PyArray_IsScalar(obj, Datetime)) { PyDatetimeScalarObject *dts = (PyDatetimeScalarObject *)obj; /* Combine it with 'meta' */ if (compute_datetime_metadata_greatest_common_divisor(meta, &dts->obmeta, meta, 0, 0) < 0) { return -1; } return 0; } /* String -> parse it to find out */ else if (PyBytes_Check(obj) || PyUnicode_Check(obj)) { npy_datetime tmp = 0; PyArray_DatetimeMetaData tmp_meta; tmp_meta.base = -1; tmp_meta.num = 1; if (convert_pyobject_to_datetime(&tmp_meta, obj, NPY_UNSAFE_CASTING, &tmp) < 0) { /* If it's a value error, clear the error */ if (PyErr_Occurred() && PyErr_GivenExceptionMatches(PyErr_Occurred(), PyExc_ValueError)) { PyErr_Clear(); return 0; } /* Otherwise propagate the error */ else { return -1; } } /* Combine it with 'meta' */ if (compute_datetime_metadata_greatest_common_divisor(meta, &tmp_meta, meta, 0, 0) < 0) { return -1; } return 0; } /* Python date object -> 'D' */ else if (PyDate_Check(obj)) { PyArray_DatetimeMetaData tmp_meta; tmp_meta.base = NPY_FR_D; tmp_meta.num = 1; /* Combine it with 'meta' */ if (compute_datetime_metadata_greatest_common_divisor(meta, &tmp_meta, meta, 0, 0) < 0) { return -1; } return 0; } /* Python datetime object -> 'us' */ else if (PyDateTime_Check(obj)) { PyArray_DatetimeMetaData tmp_meta; tmp_meta.base = NPY_FR_us; tmp_meta.num = 1; /* Combine it with 'meta' */ if (compute_datetime_metadata_greatest_common_divisor(meta, &tmp_meta, meta, 0, 0) < 0) { return -1; } return 0; } /* Now check if what we have left is a sequence for recursion */ if (PySequence_Check(obj)) { Py_ssize_t i, len = PySequence_Size(obj); if (len < 0 && PyErr_Occurred()) { return -1; } for (i = 0; i < len; ++i) { PyObject *f = PySequence_GetItem(obj, i); if (f == NULL) { return -1; } if (f == obj) { Py_DECREF(f); return 0; } if (recursive_find_object_datetime64_type(f, meta) < 0) { Py_DECREF(f); return -1; } Py_DECREF(f); } return 0; } /* Otherwise ignore it */ else { return 0; } } /* * Recursively determines the metadata for an NPY_TIMEDELTA dtype. * * Returns 0 on success, -1 on failure. */ static int recursive_find_object_timedelta64_type(PyObject *obj, PyArray_DatetimeMetaData *meta) { /* Array -> use its metadata */ if (PyArray_Check(obj)) { PyArrayObject *arr = (PyArrayObject *)obj; PyArray_Descr *arr_dtype = PyArray_DESCR(arr); /* If the array has metadata, use it */ if (arr_dtype->type_num == NPY_DATETIME || arr_dtype->type_num == NPY_TIMEDELTA) { PyArray_DatetimeMetaData *tmp_meta; /* Get the metadata from the type */ tmp_meta = get_datetime_metadata_from_dtype(arr_dtype); if (tmp_meta == NULL) { return -1; } /* Combine it with 'meta' */ if (compute_datetime_metadata_greatest_common_divisor(meta, tmp_meta, meta, 0, 0) < 0) { return -1; } return 0; } /* If it's not an object array, stop looking */ else if (arr_dtype->type_num != NPY_OBJECT) { return 0; } } /* Datetime scalar -> use its metadata */ else if (PyArray_IsScalar(obj, Timedelta)) { PyTimedeltaScalarObject *dts = (PyTimedeltaScalarObject *)obj; /* Combine it with 'meta' */ if (compute_datetime_metadata_greatest_common_divisor(meta, &dts->obmeta, meta, 1, 1) < 0) { return -1; } return 0; } /* String -> parse it to find out */ else if (PyBytes_Check(obj) || PyUnicode_Check(obj)) { /* No timedelta parser yet */ return 0; } /* Python timedelta object -> 'us' */ else if (PyDelta_Check(obj)) { PyArray_DatetimeMetaData tmp_meta; tmp_meta.base = NPY_FR_us; tmp_meta.num = 1; /* Combine it with 'meta' */ if (compute_datetime_metadata_greatest_common_divisor(meta, &tmp_meta, meta, 0, 0) < 0) { return -1; } return 0; } /* Now check if what we have left is a sequence for recursion */ if (PySequence_Check(obj)) { Py_ssize_t i, len = PySequence_Size(obj); if (len < 0 && PyErr_Occurred()) { return -1; } for (i = 0; i < len; ++i) { PyObject *f = PySequence_GetItem(obj, i); if (f == NULL) { return -1; } if (f == obj) { Py_DECREF(f); return 0; } if (recursive_find_object_timedelta64_type(f, meta) < 0) { Py_DECREF(f); return -1; } Py_DECREF(f); } return 0; } /* Otherwise ignore it */ else { return 0; } } /* * Examines all the objects in the given Python object by * recursively descending the sequence structure. Returns a * datetime or timedelta type with metadata based on the data. */ NPY_NO_EXPORT PyArray_Descr * find_object_datetime_type(PyObject *obj, int type_num) { PyArray_DatetimeMetaData meta; meta.base = NPY_FR_GENERIC; meta.num = 1; if (type_num == NPY_DATETIME) { if (recursive_find_object_datetime64_type(obj, &meta) < 0) { return NULL; } else { return create_datetime_dtype(type_num, &meta); } } else if (type_num == NPY_TIMEDELTA) { if (recursive_find_object_timedelta64_type(obj, &meta) < 0) { return NULL; } else { return create_datetime_dtype(type_num, &meta); } } else { PyErr_SetString(PyExc_ValueError, "find_object_datetime_type needs a datetime or " "timedelta type number"); return NULL; } } numpy-1.8.2/numpy/core/src/multiarray/datetime_busdaycal.c0000664000175100017510000004152012370216243025075 0ustar vagrantvagrant00000000000000/* * This file implements an object encapsulating a business day * calendar object for accelerating NumPy datetime business day functions. * * Written by Mark Wiebe (mwwiebe@gmail.com) * Copyright (c) 2011 by Enthought, Inc. * * See LICENSE.txt for the license. */ #define PY_SSIZE_T_CLEAN #include #define NPY_NO_DEPRECATED_API NPY_API_VERSION #define _MULTIARRAYMODULE #include #include "npy_config.h" #include "npy_pycompat.h" #include "numpy/arrayscalars.h" #include "lowlevel_strided_loops.h" #include "_datetime.h" #include "datetime_busday.h" #include "datetime_busdaycal.h" NPY_NO_EXPORT int PyArray_WeekMaskConverter(PyObject *weekmask_in, npy_bool *weekmask) { PyObject *obj = weekmask_in; /* Make obj into an ASCII string if it is UNICODE */ Py_INCREF(obj); if (PyUnicode_Check(obj)) { /* accept unicode input */ PyObject *obj_str; obj_str = PyUnicode_AsASCIIString(obj); if (obj_str == NULL) { Py_DECREF(obj); return 0; } Py_DECREF(obj); obj = obj_str; } if (PyBytes_Check(obj)) { char *str; Py_ssize_t len; int i; if (PyBytes_AsStringAndSize(obj, &str, &len) < 0) { Py_DECREF(obj); return 0; } /* Length 7 is a string like "1111100" */ if (len == 7) { for (i = 0; i < 7; ++i) { switch(str[i]) { case '0': weekmask[i] = 0; break; case '1': weekmask[i] = 1; break; default: goto general_weekmask_string; } } goto finish; } general_weekmask_string: /* a string like "SatSun" or "Mon Tue Wed" */ memset(weekmask, 0, 7); for (i = 0; i < len; i += 3) { while (isspace(str[i])) ++i; if (i == len) { goto finish; } else if (i + 2 >= len) { goto invalid_weekmask_string; } switch (str[i]) { case 'M': if (str[i+1] == 'o' && str[i+2] == 'n') { weekmask[0] = 1; } else { goto invalid_weekmask_string; } break; case 'T': if (str[i+1] == 'u' && str[i+2] == 'e') { weekmask[1] = 1; } else if (str[i+1] == 'h' && str[i+2] == 'u') { weekmask[3] = 1; } else { goto invalid_weekmask_string; } break; case 'W': if (str[i+1] == 'e' && str[i+2] == 'd') { weekmask[2] = 1; } else { goto invalid_weekmask_string; } break; case 'F': if (str[i+1] == 'r' && str[i+2] == 'i') { weekmask[4] = 1; } else { goto invalid_weekmask_string; } break; case 'S': if (str[i+1] == 'a' && str[i+2] == 't') { weekmask[5] = 1; } else if (str[i+1] == 'u' && str[i+2] == 'n') { weekmask[6] = 1; } else { goto invalid_weekmask_string; } break; default: goto invalid_weekmask_string; } } goto finish; invalid_weekmask_string: PyErr_Format(PyExc_ValueError, "Invalid business day weekmask string \"%s\"", str); Py_DECREF(obj); return 0; } /* Something like [1,1,1,1,1,0,0] */ else if (PySequence_Check(obj)) { if (PySequence_Size(obj) != 7 || (PyArray_Check(obj) && PyArray_NDIM((PyArrayObject *)obj) != 1)) { PyErr_SetString(PyExc_ValueError, "A business day weekmask array must have length 7"); Py_DECREF(obj); return 0; } else { int i; PyObject *f; for (i = 0; i < 7; ++i) { long val; f = PySequence_GetItem(obj, i); if (f == NULL) { Py_DECREF(obj); return 0; } val = PyInt_AsLong(f); if (val == -1 && PyErr_Occurred()) { Py_DECREF(obj); return 0; } if (val == 0) { weekmask[i] = 0; } else if (val == 1) { weekmask[i] = 1; } else { PyErr_SetString(PyExc_ValueError, "A business day weekmask array must have all " "1's and 0's"); Py_DECREF(obj); return 0; } } goto finish; } } PyErr_SetString(PyExc_ValueError, "Couldn't convert object into a business day weekmask"); Py_DECREF(obj); return 0; finish: Py_DECREF(obj); return 1; } static int qsort_datetime_compare(const void *elem1, const void *elem2) { npy_datetime e1 = *(const npy_datetime *)elem1; npy_datetime e2 = *(const npy_datetime *)elem2; return (e1 < e2) ? -1 : (e1 == e2) ? 0 : 1; } /* * Sorts the the array of dates provided in place and removes * NaT, duplicates and any date which is already excluded on account * of the weekmask. * * Returns the number of dates left after removing weekmask-excluded * dates. */ NPY_NO_EXPORT void normalize_holidays_list(npy_holidayslist *holidays, npy_bool *weekmask) { npy_datetime *dates = holidays->begin; npy_intp count = holidays->end - dates; npy_datetime lastdate = NPY_DATETIME_NAT; npy_intp trimcount, i; int day_of_week; /* Sort the dates */ qsort(dates, count, sizeof(npy_datetime), &qsort_datetime_compare); /* Sweep throught the array, eliminating unnecessary values */ trimcount = 0; for (i = 0; i < count; ++i) { npy_datetime date = dates[i]; /* Skip any NaT or duplicate */ if (date != NPY_DATETIME_NAT && date != lastdate) { /* Get the day of the week (1970-01-05 is Monday) */ day_of_week = (int)((date - 4) % 7); if (day_of_week < 0) { day_of_week += 7; } /* * If the holiday falls on a possible business day, * then keep it. */ if (weekmask[day_of_week] == 1) { dates[trimcount++] = date; lastdate = date; } } } /* Adjust the end of the holidays array */ holidays->end = dates + trimcount; } /* * Converts a Python input into a non-normalized list of holidays. * * IMPORTANT: This function can't do the normalization, because it doesn't * know the weekmask. You must call 'normalize_holiday_list' * on the result before using it. */ NPY_NO_EXPORT int PyArray_HolidaysConverter(PyObject *dates_in, npy_holidayslist *holidays) { PyArrayObject *dates = NULL; PyArray_Descr *date_dtype = NULL; npy_intp count; /* Make 'dates' into an array */ if (PyArray_Check(dates_in)) { dates = (PyArrayObject *)dates_in; Py_INCREF(dates); } else { PyArray_Descr *datetime_dtype; /* Use the datetime dtype with generic units so it fills it in */ datetime_dtype = PyArray_DescrFromType(NPY_DATETIME); if (datetime_dtype == NULL) { goto fail; } /* This steals the datetime_dtype reference */ dates = (PyArrayObject *)PyArray_FromAny(dates_in, datetime_dtype, 0, 0, 0, dates_in); if (dates == NULL) { goto fail; } } date_dtype = create_datetime_dtype_with_unit(NPY_DATETIME, NPY_FR_D); if (date_dtype == NULL) { goto fail; } if (!PyArray_CanCastTypeTo(PyArray_DESCR(dates), date_dtype, NPY_SAFE_CASTING)) { PyErr_SetString(PyExc_ValueError, "Cannot safely convert " "provided holidays input into an array of dates"); goto fail; } if (PyArray_NDIM(dates) != 1) { PyErr_SetString(PyExc_ValueError, "holidays must be a provided " "as a one-dimensional array"); goto fail; } /* Allocate the memory for the dates */ count = PyArray_DIM(dates, 0); holidays->begin = PyArray_malloc(sizeof(npy_datetime) * count); if (holidays->begin == NULL) { PyErr_NoMemory(); goto fail; } holidays->end = holidays->begin + count; /* Cast the data into a raw date array */ if (PyArray_CastRawArrays(count, PyArray_BYTES(dates), (char *)holidays->begin, PyArray_STRIDE(dates, 0), sizeof(npy_datetime), PyArray_DESCR(dates), date_dtype, 0) != NPY_SUCCEED) { goto fail; } Py_DECREF(dates); Py_DECREF(date_dtype); return 1; fail: Py_XDECREF(dates); Py_XDECREF(date_dtype); return 0; } static PyObject * busdaycalendar_new(PyTypeObject *subtype, PyObject *NPY_UNUSED(args), PyObject *NPY_UNUSED(kwds)) { NpyBusDayCalendar *self; self = (NpyBusDayCalendar *)subtype->tp_alloc(subtype, 0); if (self != NULL) { /* Start with an empty holidays list */ self->holidays.begin = NULL; self->holidays.end = NULL; /* Set the weekmask to the default */ self->busdays_in_weekmask = 5; self->weekmask[0] = 1; self->weekmask[1] = 1; self->weekmask[2] = 1; self->weekmask[3] = 1; self->weekmask[4] = 1; self->weekmask[5] = 0; self->weekmask[6] = 0; } return (PyObject *)self; } static int busdaycalendar_init(NpyBusDayCalendar *self, PyObject *args, PyObject *kwds) { static char *kwlist[] = {"weekmask", "holidays", NULL}; int i, busdays_in_weekmask; /* Clear the holidays if necessary */ if (self->holidays.begin != NULL) { PyArray_free(self->holidays.begin); self->holidays.begin = NULL; self->holidays.end = NULL; } /* Reset the weekmask to the default */ self->busdays_in_weekmask = 5; self->weekmask[0] = 1; self->weekmask[1] = 1; self->weekmask[2] = 1; self->weekmask[3] = 1; self->weekmask[4] = 1; self->weekmask[5] = 0; self->weekmask[6] = 0; /* Parse the parameters */ if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O&O&:busdaycal", kwlist, &PyArray_WeekMaskConverter, &self->weekmask[0], &PyArray_HolidaysConverter, &self->holidays)) { return -1; } /* Count the number of business days in a week */ busdays_in_weekmask = 0; for (i = 0; i < 7; ++i) { busdays_in_weekmask += self->weekmask[i]; } self->busdays_in_weekmask = busdays_in_weekmask; /* Normalize the holidays list */ normalize_holidays_list(&self->holidays, self->weekmask); if (self->busdays_in_weekmask == 0) { PyErr_SetString(PyExc_ValueError, "Cannot construct a numpy.busdaycal with a weekmask of " "all zeros"); return -1; } return 0; } static void busdaycalendar_dealloc(NpyBusDayCalendar *self) { /* Clear the holidays */ if (self->holidays.begin != NULL) { PyArray_free(self->holidays.begin); self->holidays.begin = NULL; self->holidays.end = NULL; } Py_TYPE(self)->tp_free((PyObject*)self); } static PyObject * busdaycalendar_weekmask_get(NpyBusDayCalendar *self) { PyArrayObject *ret; npy_intp size = 7; /* Allocate a 7-element boolean array */ ret = (PyArrayObject *)PyArray_SimpleNew(1, &size, NPY_BOOL); if (ret == NULL) { return NULL; } /* Copy the weekmask data */ memcpy(PyArray_DATA(ret), self->weekmask, 7); return (PyObject *)ret; } static PyObject * busdaycalendar_holidays_get(NpyBusDayCalendar *self) { PyArrayObject *ret; PyArray_Descr *date_dtype; npy_intp size = self->holidays.end - self->holidays.begin; /* Create a date dtype */ date_dtype = create_datetime_dtype_with_unit(NPY_DATETIME, NPY_FR_D); if (date_dtype == NULL) { return NULL; } /* Allocate a date array (this steals the date_dtype reference) */ ret = (PyArrayObject *)PyArray_SimpleNewFromDescr(1, &size, date_dtype); if (ret == NULL) { return NULL; } /* Copy the holidays */ if (size > 0) { memcpy(PyArray_DATA(ret), self->holidays.begin, size * sizeof(npy_datetime)); } return (PyObject *)ret; } static PyGetSetDef busdaycalendar_getsets[] = { {"weekmask", (getter)busdaycalendar_weekmask_get, NULL, NULL, NULL}, {"holidays", (getter)busdaycalendar_holidays_get, NULL, NULL, NULL}, {NULL, NULL, NULL, NULL, NULL} }; NPY_NO_EXPORT PyTypeObject NpyBusDayCalendar_Type = { #if defined(NPY_PY3K) PyVarObject_HEAD_INIT(NULL, 0) #else PyObject_HEAD_INIT(NULL) 0, /* ob_size */ #endif "numpy.busdaycalendar", /* tp_name */ sizeof(NpyBusDayCalendar), /* tp_basicsize */ 0, /* tp_itemsize */ /* methods */ (destructor)busdaycalendar_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ #if defined(NPY_PY3K) 0, /* tp_reserved */ #else 0, /* tp_compare */ #endif 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT, /* tp_flags */ 0, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ 0, /* tp_methods */ 0, /* tp_members */ busdaycalendar_getsets, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc)busdaycalendar_init, /* tp_init */ 0, /* tp_alloc */ busdaycalendar_new, /* 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 */ 0, /* tp_version_tag */ }; numpy-1.8.2/numpy/core/src/multiarray/common.c0000664000175100017510000005741712370216243022556 0ustar vagrantvagrant00000000000000#define PY_SSIZE_T_CLEAN #include #define NPY_NO_DEPRECATED_API NPY_API_VERSION #define _MULTIARRAYMODULE #include "numpy/arrayobject.h" #include "npy_config.h" #include "npy_pycompat.h" #include "common.h" #include "usertypes.h" #include "common.h" #include "buffer.h" /* * The casting to use for implicit assignment operations resulting from * in-place operations (like +=) and out= arguments. (Notice that this * variable is misnamed, but it's part of the public API so I'm not sure we * can just change it. Maybe someone should try and see if anyone notices. */ /* * In numpy 1.6 and earlier, this was NPY_UNSAFE_CASTING. In a future * release, it will become NPY_SAME_KIND_CASTING. Right now, during the * transitional period, we continue to follow the NPY_UNSAFE_CASTING rules (to * avoid breaking people's code), but we also check for whether the cast would * be allowed under the NPY_SAME_KIND_CASTING rules, and if not we issue a * warning (that people's code will be broken in a future release.) */ /* * PyArray_GetAttrString_SuppressException: * * Stripped down version of PyObject_GetAttrString, * avoids lookups for None, tuple, and List objects, * and doesn't create a PyErr since this code ignores it. * * This can be much faster then PyObject_GetAttrString where * exceptions are not used by caller. * * 'obj' is the object to search for attribute. * * 'name' is the attribute to search for. * * Returns attribute value on success, 0 on failure. */ PyObject * PyArray_GetAttrString_SuppressException(PyObject *obj, char *name) { PyTypeObject *tp = Py_TYPE(obj); PyObject *res = (PyObject *)NULL; /* We do not need to check for special attributes on trivial types */ if (obj == Py_None || PyList_CheckExact(obj) || PyTuple_CheckExact(obj)) { return NULL; } /* Attribute referenced by (char *)name */ if (tp->tp_getattr != NULL) { res = (*tp->tp_getattr)(obj, name); if (res == NULL) { PyErr_Clear(); } } /* Attribute referenced by (PyObject *)name */ else if (tp->tp_getattro != NULL) { #if defined(NPY_PY3K) PyObject *w = PyUnicode_InternFromString(name); #else PyObject *w = PyString_InternFromString(name); #endif if (w == NULL) { return (PyObject *)NULL; } res = (*tp->tp_getattro)(obj, w); Py_DECREF(w); if (res == NULL) { PyErr_Clear(); } } return res; } NPY_NO_EXPORT NPY_CASTING NPY_DEFAULT_ASSIGN_CASTING = NPY_INTERNAL_UNSAFE_CASTING_BUT_WARN_UNLESS_SAME_KIND; NPY_NO_EXPORT PyArray_Descr * _array_find_python_scalar_type(PyObject *op) { if (PyFloat_Check(op)) { return PyArray_DescrFromType(NPY_DOUBLE); } else if (PyComplex_Check(op)) { return PyArray_DescrFromType(NPY_CDOUBLE); } else if (PyInt_Check(op)) { /* bools are a subclass of int */ if (PyBool_Check(op)) { return PyArray_DescrFromType(NPY_BOOL); } else { return PyArray_DescrFromType(NPY_LONG); } } else if (PyLong_Check(op)) { /* check to see if integer can fit into a longlong or ulonglong and return that --- otherwise return object */ if ((PyLong_AsLongLong(op) == -1) && PyErr_Occurred()) { PyErr_Clear(); } else { return PyArray_DescrFromType(NPY_LONGLONG); } if ((PyLong_AsUnsignedLongLong(op) == (unsigned long long) -1) && PyErr_Occurred()){ PyErr_Clear(); } else { return PyArray_DescrFromType(NPY_ULONGLONG); } return PyArray_DescrFromType(NPY_OBJECT); } return NULL; } #if !defined(NPY_PY3K) static PyArray_Descr * _use_default_type(PyObject *op) { int typenum, l; PyObject *type; typenum = -1; l = 0; type = (PyObject *)Py_TYPE(op); while (l < NPY_NUMUSERTYPES) { if (type == (PyObject *)(userdescrs[l]->typeobj)) { typenum = l + NPY_USERDEF; break; } l++; } if (typenum == -1) { typenum = NPY_OBJECT; } return PyArray_DescrFromType(typenum); } #endif /* * These constants are used to signal that the recursive dtype determination in * PyArray_DTypeFromObject encountered a string type, and that the recursive * search must be restarted so that string representation lengths can be * computed for all scalar types. */ #define RETRY_WITH_STRING 1 #define RETRY_WITH_UNICODE 2 /* * Recursively examines the object to determine an appropriate dtype * to use for converting to an ndarray. * * 'obj' is the object to be converted to an ndarray. * * 'maxdims' is the maximum recursion depth. * * 'out_dtype' should be either NULL or a minimal starting dtype when * the function is called. It is updated with the results of type * promotion. This dtype does not get updated when processing NA objects. * This is reset to NULL on failure. * * Returns 0 on success, -1 on failure. */ NPY_NO_EXPORT int PyArray_DTypeFromObject(PyObject *obj, int maxdims, PyArray_Descr **out_dtype) { int res; res = PyArray_DTypeFromObjectHelper(obj, maxdims, out_dtype, 0); if (res == RETRY_WITH_STRING) { res = PyArray_DTypeFromObjectHelper(obj, maxdims, out_dtype, NPY_STRING); if (res == RETRY_WITH_UNICODE) { res = PyArray_DTypeFromObjectHelper(obj, maxdims, out_dtype, NPY_UNICODE); } } else if (res == RETRY_WITH_UNICODE) { res = PyArray_DTypeFromObjectHelper(obj, maxdims, out_dtype, NPY_UNICODE); } return res; } NPY_NO_EXPORT int PyArray_DTypeFromObjectHelper(PyObject *obj, int maxdims, PyArray_Descr **out_dtype, int string_type) { int i, size; PyArray_Descr *dtype = NULL; PyObject *ip; Py_buffer buffer_view; /* Check if it's an ndarray */ if (PyArray_Check(obj)) { dtype = PyArray_DESCR((PyArrayObject *)obj); Py_INCREF(dtype); goto promote_types; } /* See if it's a python None */ if (obj == Py_None) { dtype = PyArray_DescrFromType(NPY_OBJECT); if (dtype == NULL) { goto fail; } Py_INCREF(dtype); goto promote_types; } /* Check if it's a NumPy scalar */ else if (PyArray_IsScalar(obj, Generic)) { if (!string_type) { dtype = PyArray_DescrFromScalar(obj); if (dtype == NULL) { goto fail; } } else { int itemsize; PyObject *temp; if (string_type == NPY_STRING) { if ((temp = PyObject_Str(obj)) == NULL) { return -1; } #if defined(NPY_PY3K) #if PY_VERSION_HEX >= 0x03030000 itemsize = PyUnicode_GetLength(temp); #else itemsize = PyUnicode_GET_SIZE(temp); #endif #else itemsize = PyString_GET_SIZE(temp); #endif } else if (string_type == NPY_UNICODE) { #if defined(NPY_PY3K) if ((temp = PyObject_Str(obj)) == NULL) { #else if ((temp = PyObject_Unicode(obj)) == NULL) { #endif return -1; } itemsize = PyUnicode_GET_DATA_SIZE(temp); #ifndef Py_UNICODE_WIDE itemsize <<= 1; #endif } else { goto fail; } Py_DECREF(temp); if (*out_dtype != NULL && (*out_dtype)->type_num == string_type && (*out_dtype)->elsize >= itemsize) { return 0; } dtype = PyArray_DescrNewFromType(string_type); if (dtype == NULL) { goto fail; } dtype->elsize = itemsize; } goto promote_types; } /* Check if it's a Python scalar */ dtype = _array_find_python_scalar_type(obj); if (dtype != NULL) { if (string_type) { int itemsize; PyObject *temp; if (string_type == NPY_STRING) { if ((temp = PyObject_Str(obj)) == NULL) { return -1; } #if defined(NPY_PY3K) #if PY_VERSION_HEX >= 0x03030000 itemsize = PyUnicode_GetLength(temp); #else itemsize = PyUnicode_GET_SIZE(temp); #endif #else itemsize = PyString_GET_SIZE(temp); #endif } else if (string_type == NPY_UNICODE) { #if defined(NPY_PY3K) if ((temp = PyObject_Str(obj)) == NULL) { #else if ((temp = PyObject_Unicode(obj)) == NULL) { #endif return -1; } itemsize = PyUnicode_GET_DATA_SIZE(temp); #ifndef Py_UNICODE_WIDE itemsize <<= 1; #endif } else { goto fail; } Py_DECREF(temp); if (*out_dtype != NULL && (*out_dtype)->type_num == string_type && (*out_dtype)->elsize >= itemsize) { return 0; } dtype = PyArray_DescrNewFromType(string_type); if (dtype == NULL) { goto fail; } dtype->elsize = itemsize; } goto promote_types; } /* Check if it's an ASCII string */ if (PyBytes_Check(obj)) { int itemsize = PyString_GET_SIZE(obj); /* If it's already a big enough string, don't bother type promoting */ if (*out_dtype != NULL && (*out_dtype)->type_num == NPY_STRING && (*out_dtype)->elsize >= itemsize) { return 0; } dtype = PyArray_DescrNewFromType(NPY_STRING); if (dtype == NULL) { goto fail; } dtype->elsize = itemsize; goto promote_types; } /* Check if it's a Unicode string */ if (PyUnicode_Check(obj)) { int itemsize = PyUnicode_GET_DATA_SIZE(obj); #ifndef Py_UNICODE_WIDE itemsize <<= 1; #endif /* * If it's already a big enough unicode object, * don't bother type promoting */ if (*out_dtype != NULL && (*out_dtype)->type_num == NPY_UNICODE && (*out_dtype)->elsize >= itemsize) { return 0; } dtype = PyArray_DescrNewFromType(NPY_UNICODE); if (dtype == NULL) { goto fail; } dtype->elsize = itemsize; goto promote_types; } /* PEP 3118 buffer interface */ if (PyObject_CheckBuffer(obj) == 1) { memset(&buffer_view, 0, sizeof(Py_buffer)); if (PyObject_GetBuffer(obj, &buffer_view, PyBUF_FORMAT|PyBUF_STRIDES) == 0 || PyObject_GetBuffer(obj, &buffer_view, PyBUF_FORMAT) == 0) { PyErr_Clear(); dtype = _descriptor_from_pep3118_format(buffer_view.format); PyBuffer_Release(&buffer_view); if (dtype) { goto promote_types; } } else if (PyObject_GetBuffer(obj, &buffer_view, PyBUF_STRIDES) == 0 || PyObject_GetBuffer(obj, &buffer_view, PyBUF_SIMPLE) == 0) { PyErr_Clear(); dtype = PyArray_DescrNewFromType(NPY_VOID); dtype->elsize = buffer_view.itemsize; PyBuffer_Release(&buffer_view); goto promote_types; } else { PyErr_Clear(); } } /* The array interface */ ip = PyArray_GetAttrString_SuppressException(obj, "__array_interface__"); if (ip != NULL) { if (PyDict_Check(ip)) { PyObject *typestr; #if defined(NPY_PY3K) PyObject *tmp = NULL; #endif typestr = PyDict_GetItemString(ip, "typestr"); #if defined(NPY_PY3K) /* Allow unicode type strings */ if (PyUnicode_Check(typestr)) { tmp = PyUnicode_AsASCIIString(typestr); typestr = tmp; } #endif if (typestr && PyBytes_Check(typestr)) { dtype =_array_typedescr_fromstr(PyBytes_AS_STRING(typestr)); #if defined(NPY_PY3K) if (tmp == typestr) { Py_DECREF(tmp); } #endif Py_DECREF(ip); if (dtype == NULL) { goto fail; } goto promote_types; } } Py_DECREF(ip); } /* The array struct interface */ ip = PyArray_GetAttrString_SuppressException(obj, "__array_struct__"); if (ip != NULL) { PyArrayInterface *inter; char buf[40]; if (NpyCapsule_Check(ip)) { inter = (PyArrayInterface *)NpyCapsule_AsVoidPtr(ip); if (inter->two == 2) { PyOS_snprintf(buf, sizeof(buf), "|%c%d", inter->typekind, inter->itemsize); dtype = _array_typedescr_fromstr(buf); Py_DECREF(ip); if (dtype == NULL) { goto fail; } goto promote_types; } } Py_DECREF(ip); } /* The old buffer interface */ #if !defined(NPY_PY3K) if (PyBuffer_Check(obj)) { dtype = PyArray_DescrNewFromType(NPY_VOID); if (dtype == NULL) { goto fail; } dtype->elsize = Py_TYPE(obj)->tp_as_sequence->sq_length(obj); PyErr_Clear(); goto promote_types; } #endif /* The __array__ attribute */ ip = PyArray_GetAttrString_SuppressException(obj, "__array__"); if (ip != NULL) { Py_DECREF(ip); ip = PyObject_CallMethod(obj, "__array__", NULL); if(ip && PyArray_Check(ip)) { dtype = PyArray_DESCR((PyArrayObject *)ip); Py_INCREF(dtype); Py_DECREF(ip); goto promote_types; } Py_XDECREF(ip); if (PyErr_Occurred()) { goto fail; } } /* Not exactly sure what this is about... */ #if !defined(NPY_PY3K) if (PyInstance_Check(obj)) { dtype = _use_default_type(obj); if (dtype == NULL) { goto fail; } else { goto promote_types; } } #endif /* * If we reached the maximum recursion depth without hitting one * of the above cases, the output dtype should be OBJECT */ if (maxdims == 0 || !PySequence_Check(obj)) { if (*out_dtype == NULL || (*out_dtype)->type_num != NPY_OBJECT) { Py_XDECREF(*out_dtype); *out_dtype = PyArray_DescrFromType(NPY_OBJECT); if (*out_dtype == NULL) { return -1; } } return 0; } /* Recursive case */ size = PySequence_Size(obj); if (size < 0) { goto fail; } /* 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); if (res < 0) { Py_DECREF(ip); goto fail; } else if (res > 0) { Py_DECREF(ip); return res; } Py_DECREF(ip); } return 0; promote_types: /* Set 'out_dtype' if it's NULL */ if (*out_dtype == NULL) { if (!string_type && dtype->type_num == NPY_STRING) { Py_DECREF(dtype); return RETRY_WITH_STRING; } if (!string_type && dtype->type_num == NPY_UNICODE) { Py_DECREF(dtype); return RETRY_WITH_UNICODE; } *out_dtype = dtype; return 0; } /* Do type promotion with 'out_dtype' */ else { PyArray_Descr *res_dtype = PyArray_PromoteTypes(dtype, *out_dtype); Py_DECREF(dtype); if (res_dtype == NULL) { return -1; } if (!string_type && res_dtype->type_num == NPY_UNICODE && (*out_dtype)->type_num != NPY_UNICODE) { Py_DECREF(res_dtype); return RETRY_WITH_UNICODE; } if (!string_type && res_dtype->type_num == NPY_STRING && (*out_dtype)->type_num != NPY_STRING) { Py_DECREF(res_dtype); return RETRY_WITH_STRING; } Py_DECREF(*out_dtype); *out_dtype = res_dtype; return 0; } fail: Py_XDECREF(*out_dtype); *out_dtype = NULL; return -1; } #undef RETRY_WITH_STRING #undef RETRY_WITH_UNICODE /* new reference */ NPY_NO_EXPORT PyArray_Descr * _array_typedescr_fromstr(char *c_str) { PyArray_Descr *descr = NULL; PyObject *stringobj = PyString_FromString(c_str); if (stringobj == NULL) { return NULL; } if (PyArray_DescrConverter(stringobj, &descr) != NPY_SUCCEED) { Py_DECREF(stringobj); return NULL; } Py_DECREF(stringobj); return descr; } NPY_NO_EXPORT int check_and_adjust_index(npy_intp *index, npy_intp max_item, int axis) { /* Check that index is valid, taking into account negative indices */ if ((*index < -max_item) || (*index >= max_item)) { /* Try to be as clear as possible about what went wrong. */ if (axis >= 0) { PyErr_Format(PyExc_IndexError, "index %"NPY_INTP_FMT" is out of bounds " "for axis %d with size %"NPY_INTP_FMT, *index, axis, max_item); } else { PyErr_Format(PyExc_IndexError, "index %"NPY_INTP_FMT" is out of bounds " "for size %"NPY_INTP_FMT, *index, max_item); } return -1; } /* adjust negative indices */ if (*index < 0) { *index += max_item; } return 0; } NPY_NO_EXPORT char * index2ptr(PyArrayObject *mp, npy_intp i) { npy_intp dim0; if (PyArray_NDIM(mp) == 0) { PyErr_SetString(PyExc_IndexError, "0-d arrays can't be indexed"); return NULL; } dim0 = PyArray_DIMS(mp)[0]; if (check_and_adjust_index(&i, dim0, 0) < 0) return NULL; if (i == 0) { return PyArray_DATA(mp); } return PyArray_BYTES(mp)+i*PyArray_STRIDES(mp)[0]; } NPY_NO_EXPORT int _zerofill(PyArrayObject *ret) { if (PyDataType_REFCHK(PyArray_DESCR(ret))) { PyObject *zero = PyInt_FromLong(0); PyArray_FillObjectArray(ret, zero); Py_DECREF(zero); if (PyErr_Occurred()) { Py_DECREF(ret); return -1; } } else { npy_intp n = PyArray_NBYTES(ret); memset(PyArray_DATA(ret), 0, n); } return 0; } NPY_NO_EXPORT int _IsAligned(PyArrayObject *ap) { unsigned int i, aligned = 1; const unsigned int 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(). */ if (alignment == 1) { return 1; } aligned = npy_is_aligned(PyArray_DATA(ap), alignment); for (i = 0; i < PyArray_NDIM(ap); i++) { #if NPY_RELAXED_STRIDES_CHECKING if (PyArray_DIM(ap, i) > 1) { /* if shape[i] == 1, the stride is never used */ aligned &= npy_is_aligned((void*)PyArray_STRIDES(ap)[i], alignment); } else if (PyArray_DIM(ap, i) == 0) { /* an array with zero elements is always aligned */ return 1; } #else /* not NPY_RELAXED_STRIDES_CHECKING */ aligned &= npy_is_aligned((void*)PyArray_STRIDES(ap)[i], alignment); #endif /* not NPY_RELAXED_STRIDES_CHECKING */ } return aligned != 0; } NPY_NO_EXPORT npy_bool _IsWriteable(PyArrayObject *ap) { PyObject *base=PyArray_BASE(ap); void *dummy; Py_ssize_t n; /* If we own our own data, then no-problem */ if ((base == NULL) || (PyArray_FLAGS(ap) & NPY_ARRAY_OWNDATA)) { return NPY_TRUE; } /* * Get to the final base object * If it is a writeable array, then return TRUE * If we can find an array object * or a writeable buffer object as the final base object * or a string object (for pickling support memory savings). * - this last could be removed if a proper pickleable * buffer was added to Python. * * MW: I think it would better to disallow switching from READONLY * to WRITEABLE like this... */ while(PyArray_Check(base)) { if (PyArray_CHKFLAGS((PyArrayObject *)base, NPY_ARRAY_OWNDATA)) { return (npy_bool) (PyArray_ISWRITEABLE((PyArrayObject *)base)); } base = PyArray_BASE((PyArrayObject *)base); } /* * here so pickle support works seamlessly * and unpickled array can be set and reset writeable * -- could be abused -- */ if (PyString_Check(base)) { return NPY_TRUE; } if (PyObject_AsWriteBuffer(base, &dummy, &n) < 0) { return NPY_FALSE; } return NPY_TRUE; } /* Gets a half-open range [start, end) of offsets from the data pointer */ 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_intp max_axis_offset; npy_intp lower = 0; npy_intp upper = 0; int i; for (i = 0; i < nd; i++) { if (dims[i] == 0) { /* If the array size is zero, return an empty range */ *lower_offset = 0; *upper_offset = 0; return; } /* Expand either upwards or downwards depending on stride */ max_axis_offset = strides[i] * (dims[i] - 1); if (max_axis_offset > 0) { upper += max_axis_offset; } else { lower += max_axis_offset; } } /* Return a half-open range */ upper += itemsize; *lower_offset = lower; *upper_offset = upper; } /** * 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) { 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; } } 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; } numpy-1.8.2/numpy/core/src/multiarray/getset.h0000664000175100017510000000024612370216242022551 0ustar vagrantvagrant00000000000000#ifndef _NPY_ARRAY_GETSET_H_ #define _NPY_ARRAY_GETSET_H_ #ifdef NPY_ENABLE_SEPARATE_COMPILATION extern NPY_NO_EXPORT PyGetSetDef array_getsetlist[]; #endif #endif numpy-1.8.2/numpy/core/src/multiarray/common.h0000664000175100017510000000512612370216243022551 0ustar vagrantvagrant00000000000000#ifndef _NPY_PRIVATE_COMMON_H_ #define _NPY_PRIVATE_COMMON_H_ #include #define error_converting(x) (((x) == -1) && PyErr_Occurred()) /* * Recursively examines the object to determine an appropriate dtype * to use for converting to an ndarray. * * 'obj' is the object to be converted to an ndarray. * * 'maxdims' is the maximum recursion depth. * * 'out_dtype' should be either NULL or a minimal starting dtype when * the function is called. It is updated with the results of type * promotion. This dtype does not get updated when processing NA objects. * * Returns 0 on success, -1 on failure. */ NPY_NO_EXPORT int PyArray_DTypeFromObject(PyObject *obj, int maxdims, PyArray_Descr **out_dtype); NPY_NO_EXPORT int PyArray_DTypeFromObjectHelper(PyObject *obj, int maxdims, PyArray_Descr **out_dtype, int string_status); NPY_NO_EXPORT PyObject * PyArray_GetAttrString_SuppressException(PyObject *v, char *name); /* * Returns NULL without setting an exception if no scalar is matched, a * new dtype reference otherwise. */ NPY_NO_EXPORT PyArray_Descr * _array_find_python_scalar_type(PyObject *op); NPY_NO_EXPORT PyArray_Descr * _array_typedescr_fromstr(char *str); /* * Returns -1 and sets an exception if *index is an invalid index for * an array of size max_item, otherwise adjusts it in place to be * 0 <= *index < max_item, and returns 0. * 'axis' should be the array axis that is being indexed over, if known. If * unknown, use -1. */ NPY_NO_EXPORT int check_and_adjust_index(npy_intp *index, npy_intp max_item, int axis); NPY_NO_EXPORT char * index2ptr(PyArrayObject *mp, npy_intp i); NPY_NO_EXPORT int _zerofill(PyArrayObject *ret); NPY_NO_EXPORT int _IsAligned(PyArrayObject *ap); NPY_NO_EXPORT npy_bool _IsWriteable(PyArrayObject *ap); 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); /* * return true if pointer is aligned to 'alignment' */ static NPY_INLINE int npy_is_aligned(const void * p, const npy_uintp alignment) { /* * alignment is usually a power of two * the test is faster than a direct modulo */ if (NPY_LIKELY((alignment & (alignment - 1)) == 0)) { return ((npy_uintp)(p) & ((alignment) - 1)) == 0; } else { return ((npy_uintp)(p) % alignment) == 0; } } #include "ucsnarrow.h" #endif numpy-1.8.2/numpy/core/src/multiarray/convert.h0000664000175100017510000000027012370216242022733 0ustar vagrantvagrant00000000000000#ifndef _NPY_ARRAYOBJECT_CONVERT_H_ #define _NPY_ARRAYOBJECT_CONVERT_H_ NPY_NO_EXPORT int PyArray_AssignZero(PyArrayObject *dst, PyArrayObject *wheremask); #endif numpy-1.8.2/numpy/core/src/multiarray/ucsnarrow.h0000664000175100017510000000054212370216242023300 0ustar vagrantvagrant00000000000000#ifndef _NPY_UCSNARROW_H_ #define _NPY_UCSNARROW_H_ NPY_NO_EXPORT int PyUCS2Buffer_FromUCS4(Py_UNICODE *ucs2, npy_ucs4 *ucs4, int ucs4length); NPY_NO_EXPORT int PyUCS2Buffer_AsUCS4(Py_UNICODE *ucs2, npy_ucs4 *ucs4, int ucs2len, int ucs4len); NPY_NO_EXPORT PyUnicodeObject * PyUnicode_FromUCS4(char *src, Py_ssize_t size, int swap, int align); #endif numpy-1.8.2/numpy/core/src/multiarray/descriptor.h0000664000175100017510000000323612370216242023436 0ustar vagrantvagrant00000000000000#ifndef _NPY_ARRAYDESCR_H_ #define _NPY_ARRAYDESCR_H_ NPY_NO_EXPORT PyObject *arraydescr_protocol_typestr_get(PyArray_Descr *); NPY_NO_EXPORT PyObject *arraydescr_protocol_descr_get(PyArray_Descr *self); NPY_NO_EXPORT PyObject * array_set_typeDict(PyObject *NPY_UNUSED(ignored), PyObject *args); NPY_NO_EXPORT PyArray_Descr * _arraydescr_fromobj(PyObject *obj); /* * Creates a string repr of the dtype, excluding the 'dtype()' part * surrounding the object. This object may be a string, a list, or * a dict depending on the nature of the dtype. This * is the object passed as the first parameter to the dtype * constructor, and if no additional constructor parameters are * given, will reproduce the exact memory layout. * * If 'shortrepr' is non-zero, this creates a shorter repr using * 'kind' and 'itemsize', instead of the longer type name. * * If 'includealignflag' is true, this includes the 'align=True' parameter * inside the struct dtype construction dict when needed. Use this flag * if you want a proper repr string without the 'dtype()' part around it. * * If 'includealignflag' is false, this does not preserve the * 'align=True' parameter or sticky NPY_ALIGNED_STRUCT flag for * struct arrays like the regular repr does, because the 'align' * flag is not part of first dtype constructor parameter. This * mode is intended for a full 'repr', where the 'align=True' is * provided as the second parameter. */ NPY_NO_EXPORT PyObject * arraydescr_construction_repr(PyArray_Descr *dtype, int includealignflag, int shortrepr); #ifdef NPY_ENABLE_SEPARATE_COMPILATION extern NPY_NO_EXPORT char *_datetime_strings[]; #endif #endif numpy-1.8.2/numpy/core/src/multiarray/item_selection.c0000664000175100017510000024117012370216243024260 0ustar vagrantvagrant00000000000000#define PY_SSIZE_T_CLEAN #include #include "structmember.h" #define NPY_NO_DEPRECATED_API NPY_API_VERSION #define _MULTIARRAYMODULE #include "numpy/arrayobject.h" #include "numpy/arrayscalars.h" #include "numpy/npy_math.h" #include "npy_config.h" #include "npy_pycompat.h" #include "common.h" #include "arrayobject.h" #include "ctors.h" #include "lowlevel_strided_loops.h" #include "item_selection.h" #include "npy_sort.h" #include "npy_partition.h" /*NUMPY_API * Take */ NPY_NO_EXPORT PyObject * PyArray_TakeFrom(PyArrayObject *self0, PyObject *indices0, int axis, PyArrayObject *out, NPY_CLIPMODE clipmode) { PyArray_Descr *dtype; PyArray_FastTakeFunc *func; PyArrayObject *obj = NULL, *self, *indices; npy_intp nd, i, j, n, m, k, max_item, tmp, chunk, itemsize, nelem; npy_intp shape[NPY_MAXDIMS]; char *src, *dest, *tmp_src; int err; npy_bool needs_refcounting; indices = NULL; self = (PyArrayObject *)PyArray_CheckAxis(self0, &axis, NPY_ARRAY_CARRAY); if (self == NULL) { return NULL; } indices = (PyArrayObject *)PyArray_ContiguousFromAny(indices0, NPY_INTP, 0, 0); if (indices == NULL) { goto fail; } n = m = chunk = 1; nd = PyArray_NDIM(self) + PyArray_NDIM(indices) - 1; for (i = 0; i < nd; i++) { if (i < axis) { shape[i] = PyArray_DIMS(self)[i]; n *= shape[i]; } else { if (i < axis+PyArray_NDIM(indices)) { shape[i] = PyArray_DIMS(indices)[i-axis]; m *= shape[i]; } else { shape[i] = PyArray_DIMS(self)[i-PyArray_NDIM(indices)+1]; chunk *= shape[i]; } } } if (!out) { dtype = PyArray_DESCR(self); Py_INCREF(dtype); obj = (PyArrayObject *)PyArray_NewFromDescr(Py_TYPE(self), dtype, nd, shape, NULL, NULL, 0, (PyObject *)self); if (obj == NULL) { goto fail; } } else { int flags = NPY_ARRAY_CARRAY | NPY_ARRAY_UPDATEIFCOPY; if ((PyArray_NDIM(out) != nd) || !PyArray_CompareLists(PyArray_DIMS(out), shape, nd)) { PyErr_SetString(PyExc_ValueError, "output array does not match result of ndarray.take"); goto fail; } if (clipmode == NPY_RAISE) { /* * we need to make sure and get a copy * so the input array is not changed * before the error is called */ flags |= NPY_ARRAY_ENSURECOPY; } dtype = PyArray_DESCR(self); Py_INCREF(dtype); obj = (PyArrayObject *)PyArray_FromArray(out, dtype, flags); if (obj == NULL) { goto fail; } } max_item = PyArray_DIMS(self)[axis]; nelem = chunk; itemsize = PyArray_ITEMSIZE(obj); chunk = chunk * itemsize; src = PyArray_DATA(self); dest = PyArray_DATA(obj); needs_refcounting = PyDataType_REFCHK(PyArray_DESCR(self)); if ((max_item == 0) && (PyArray_SIZE(obj) != 0)) { /* Index error, since that is the usual error for raise mode */ PyErr_SetString(PyExc_IndexError, "cannot do a non-empty take from an empty axes."); goto fail; } func = PyArray_DESCR(self)->f->fasttake; if (func == NULL) { 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) { goto fail; } tmp_src = src + tmp * chunk; if (needs_refcounting) { for (k=0; k < nelem; k++) { PyArray_Item_INCREF(tmp_src, PyArray_DESCR(self)); PyArray_Item_XDECREF(dest, PyArray_DESCR(self)); memmove(dest, tmp_src, itemsize); dest += itemsize; tmp_src += itemsize; } } else { memmove(dest, tmp_src, chunk); dest += chunk; } } src += chunk*max_item; } break; case NPY_WRAP: for (i = 0; i < n; i++) { for (j = 0; j < m; j++) { tmp = ((npy_intp *)(PyArray_DATA(indices)))[j]; if (tmp < 0) { while (tmp < 0) { tmp += max_item; } } else if (tmp >= max_item) { while (tmp >= max_item) { tmp -= max_item; } } tmp_src = src + tmp * chunk; if (needs_refcounting) { for (k=0; k < nelem; k++) { PyArray_Item_INCREF(tmp_src, PyArray_DESCR(self)); PyArray_Item_XDECREF(dest, PyArray_DESCR(self)); memmove(dest, tmp_src, itemsize); dest += itemsize; tmp_src += itemsize; } } else { memmove(dest, tmp_src, chunk); dest += chunk; } } src += chunk*max_item; } break; case NPY_CLIP: for (i = 0; i < n; i++) { for (j = 0; j < m; j++) { tmp = ((npy_intp *)(PyArray_DATA(indices)))[j]; if (tmp < 0) { tmp = 0; } else if (tmp >= max_item) { tmp = max_item - 1; } tmp_src = src + tmp * chunk; if (needs_refcounting) { for (k=0; k < nelem; k++) { PyArray_Item_INCREF(tmp_src, PyArray_DESCR(self)); PyArray_Item_XDECREF(dest, PyArray_DESCR(self)); memmove(dest, tmp_src, itemsize); dest += itemsize; tmp_src += itemsize; } } else { memmove(dest, tmp_src, chunk); dest += chunk; } } src += chunk*max_item; } break; } } else { err = func(dest, src, (npy_intp *)(PyArray_DATA(indices)), max_item, n, m, nelem, clipmode); if (err) { goto fail; } } Py_XDECREF(indices); Py_XDECREF(self); if (out != NULL && out != obj) { Py_INCREF(out); Py_DECREF(obj); obj = out; } return (PyObject *)obj; fail: PyArray_XDECREF_ERR(obj); Py_XDECREF(indices); Py_XDECREF(self); return NULL; } /*NUMPY_API * Put values into an array */ NPY_NO_EXPORT PyObject * PyArray_PutTo(PyArrayObject *self, PyObject* values0, PyObject *indices0, NPY_CLIPMODE clipmode) { PyArrayObject *indices, *values; npy_intp i, chunk, ni, max_item, nv, tmp; char *src, *dest; int copied = 0; indices = NULL; values = NULL; if (!PyArray_Check(self)) { PyErr_SetString(PyExc_TypeError, "put: first argument must be an array"); return NULL; } if (!PyArray_ISCONTIGUOUS(self)) { PyArrayObject *obj; int flags = NPY_ARRAY_CARRAY | NPY_ARRAY_UPDATEIFCOPY; if (clipmode == NPY_RAISE) { flags |= NPY_ARRAY_ENSURECOPY; } Py_INCREF(PyArray_DESCR(self)); obj = (PyArrayObject *)PyArray_FromArray(self, PyArray_DESCR(self), flags); if (obj != self) { copied = 1; } self = obj; } max_item = PyArray_SIZE(self); dest = PyArray_DATA(self); chunk = PyArray_DESCR(self)->elsize; indices = (PyArrayObject *)PyArray_ContiguousFromAny(indices0, NPY_INTP, 0, 0); if (indices == NULL) { goto fail; } ni = PyArray_SIZE(indices); Py_INCREF(PyArray_DESCR(self)); values = (PyArrayObject *)PyArray_FromAny(values0, PyArray_DESCR(self), 0, 0, NPY_ARRAY_DEFAULT | NPY_ARRAY_FORCECAST, NULL); if (values == NULL) { goto fail; } nv = PyArray_SIZE(values); if (nv <= 0) { goto finish; } if (PyDataType_REFCHK(PyArray_DESCR(self))) { 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) { goto fail; } PyArray_Item_INCREF(src, PyArray_DESCR(self)); PyArray_Item_XDECREF(dest+tmp*chunk, PyArray_DESCR(self)); memmove(dest + tmp*chunk, src, chunk); } break; case NPY_WRAP: for (i = 0; i < ni; i++) { src = PyArray_BYTES(values) + chunk * (i % nv); tmp = ((npy_intp *)(PyArray_DATA(indices)))[i]; if (tmp < 0) { while (tmp < 0) { tmp += max_item; } } else if (tmp >= max_item) { while (tmp >= max_item) { tmp -= max_item; } } PyArray_Item_INCREF(src, PyArray_DESCR(self)); PyArray_Item_XDECREF(dest+tmp*chunk, PyArray_DESCR(self)); memmove(dest + tmp * chunk, src, chunk); } break; case NPY_CLIP: for (i = 0; i < ni; i++) { src = PyArray_BYTES(values) + chunk * (i % nv); tmp = ((npy_intp *)(PyArray_DATA(indices)))[i]; if (tmp < 0) { tmp = 0; } else if (tmp >= max_item) { tmp = max_item - 1; } PyArray_Item_INCREF(src, PyArray_DESCR(self)); PyArray_Item_XDECREF(dest+tmp*chunk, PyArray_DESCR(self)); memmove(dest + tmp * chunk, src, chunk); } break; } } else { 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) { goto fail; } memmove(dest + tmp * chunk, src, chunk); } break; case NPY_WRAP: for (i = 0; i < ni; i++) { src = PyArray_BYTES(values) + chunk * (i % nv); tmp = ((npy_intp *)(PyArray_DATA(indices)))[i]; if (tmp < 0) { while (tmp < 0) { tmp += max_item; } } else if (tmp >= max_item) { while (tmp >= max_item) { tmp -= max_item; } } memmove(dest + tmp * chunk, src, chunk); } break; case NPY_CLIP: for (i = 0; i < ni; i++) { src = PyArray_BYTES(values) + chunk * (i % nv); tmp = ((npy_intp *)(PyArray_DATA(indices)))[i]; if (tmp < 0) { tmp = 0; } else if (tmp >= max_item) { tmp = max_item - 1; } memmove(dest + tmp * chunk, src, chunk); } break; } } finish: Py_XDECREF(values); Py_XDECREF(indices); if (copied) { Py_DECREF(self); } Py_INCREF(Py_None); return Py_None; fail: Py_XDECREF(indices); Py_XDECREF(values); if (copied) { PyArray_XDECREF_ERR(self); } return NULL; } /*NUMPY_API * Put values into an array according to a mask. */ NPY_NO_EXPORT PyObject * PyArray_PutMask(PyArrayObject *self, PyObject* values0, PyObject* mask0) { PyArray_FastPutmaskFunc *func; PyArrayObject *mask, *values; PyArray_Descr *dtype; npy_intp i, chunk, ni, max_item, nv, tmp; char *src, *dest; int copied = 0; mask = NULL; values = NULL; if (!PyArray_Check(self)) { PyErr_SetString(PyExc_TypeError, "putmask: first argument must " "be an array"); return NULL; } if (!PyArray_ISCONTIGUOUS(self)) { PyArrayObject *obj; dtype = PyArray_DESCR(self); Py_INCREF(dtype); obj = (PyArrayObject *)PyArray_FromArray(self, dtype, NPY_ARRAY_CARRAY | NPY_ARRAY_UPDATEIFCOPY); if (obj != self) { copied = 1; } self = obj; } max_item = PyArray_SIZE(self); dest = PyArray_DATA(self); chunk = PyArray_DESCR(self)->elsize; mask = (PyArrayObject *)PyArray_FROM_OTF(mask0, NPY_BOOL, NPY_ARRAY_CARRAY | NPY_ARRAY_FORCECAST); if (mask == NULL) { goto fail; } ni = PyArray_SIZE(mask); if (ni != max_item) { PyErr_SetString(PyExc_ValueError, "putmask: mask and data must be " "the same size"); goto fail; } dtype = PyArray_DESCR(self); Py_INCREF(dtype); values = (PyArrayObject *)PyArray_FromAny(values0, dtype, 0, 0, NPY_ARRAY_CARRAY, NULL); if (values == NULL) { goto fail; } nv = PyArray_SIZE(values); /* zero if null array */ if (nv <= 0) { Py_XDECREF(values); Py_XDECREF(mask); Py_INCREF(Py_None); return Py_None; } if (PyDataType_REFCHK(PyArray_DESCR(self))) { for (i = 0; i < ni; i++) { tmp = ((npy_bool *)(PyArray_DATA(mask)))[i]; if (tmp) { src = PyArray_BYTES(values) + chunk * (i % nv); PyArray_Item_INCREF(src, PyArray_DESCR(self)); PyArray_Item_XDECREF(dest+i*chunk, PyArray_DESCR(self)); memmove(dest + i * chunk, src, chunk); } } } else { func = PyArray_DESCR(self)->f->fastputmask; if (func == NULL) { for (i = 0; i < ni; i++) { tmp = ((npy_bool *)(PyArray_DATA(mask)))[i]; if (tmp) { src = PyArray_BYTES(values) + chunk*(i % nv); memmove(dest + i*chunk, src, chunk); } } } else { func(dest, PyArray_DATA(mask), ni, PyArray_DATA(values), nv); } } Py_XDECREF(values); Py_XDECREF(mask); if (copied) { Py_DECREF(self); } Py_INCREF(Py_None); return Py_None; fail: Py_XDECREF(mask); Py_XDECREF(values); if (copied) { PyArray_XDECREF_ERR(self); } return NULL; } /*NUMPY_API * Repeat the array. */ NPY_NO_EXPORT PyObject * PyArray_Repeat(PyArrayObject *aop, PyObject *op, int axis) { npy_intp *counts; npy_intp n, n_outer, i, j, k, chunk, total; npy_intp tmp; int nd; PyArrayObject *repeats = NULL; PyObject *ap = NULL; PyArrayObject *ret = NULL; char *new_data, *old_data; repeats = (PyArrayObject *)PyArray_ContiguousFromAny(op, NPY_INTP, 0, 1); if (repeats == NULL) { return NULL; } nd = PyArray_NDIM(repeats); counts = (npy_intp *)PyArray_DATA(repeats); if ((ap=PyArray_CheckAxis(aop, &axis, NPY_ARRAY_CARRAY))==NULL) { Py_DECREF(repeats); return NULL; } aop = (PyArrayObject *)ap; if (nd == 1) { n = PyArray_DIMS(repeats)[0]; } else { /* nd == 0 */ n = PyArray_DIMS(aop)[axis]; } if (PyArray_DIMS(aop)[axis] != n) { PyErr_SetString(PyExc_ValueError, "a.shape[axis] != len(repeats)"); goto fail; } if (nd == 0) { total = counts[0]*n; } else { total = 0; for (j = 0; j < n; j++) { if (counts[j] < 0) { PyErr_SetString(PyExc_ValueError, "count < 0"); goto fail; } total += counts[j]; } } /* Construct new array */ PyArray_DIMS(aop)[axis] = total; Py_INCREF(PyArray_DESCR(aop)); ret = (PyArrayObject *)PyArray_NewFromDescr(Py_TYPE(aop), PyArray_DESCR(aop), PyArray_NDIM(aop), PyArray_DIMS(aop), NULL, NULL, 0, (PyObject *)aop); PyArray_DIMS(aop)[axis] = n; if (ret == NULL) { goto fail; } new_data = PyArray_DATA(ret); old_data = PyArray_DATA(aop); chunk = PyArray_DESCR(aop)->elsize; for(i = axis + 1; i < PyArray_NDIM(aop); i++) { chunk *= PyArray_DIMS(aop)[i]; } n_outer = 1; for (i = 0; i < axis; i++) { n_outer *= PyArray_DIMS(aop)[i]; } for (i = 0; i < n_outer; i++) { for (j = 0; j < n; j++) { tmp = nd ? counts[j] : counts[0]; for (k = 0; k < tmp; k++) { memcpy(new_data, old_data, chunk); new_data += chunk; } old_data += chunk; } } Py_DECREF(repeats); PyArray_INCREF(ret); Py_XDECREF(aop); return (PyObject *)ret; fail: Py_DECREF(repeats); Py_XDECREF(aop); Py_XDECREF(ret); return NULL; } /*NUMPY_API */ NPY_NO_EXPORT PyObject * PyArray_Choose(PyArrayObject *ip, PyObject *op, PyArrayObject *out, NPY_CLIPMODE clipmode) { PyArrayObject *obj = NULL; PyArray_Descr *dtype; int n, elsize; npy_intp i; char *ret_data; PyArrayObject **mps, *ap; PyArrayMultiIterObject *multi = NULL; npy_intp mi; ap = NULL; /* * Convert all inputs to arrays of a common type * Also makes them C-contiguous */ mps = PyArray_ConvertToCommonType(op, &n); if (mps == NULL) { return NULL; } for (i = 0; i < n; i++) { if (mps[i] == NULL) { goto fail; } } ap = (PyArrayObject *)PyArray_FROM_OT((PyObject *)ip, NPY_INTP); if (ap == NULL) { goto fail; } /* Broadcast all arrays to each other, index array at the end. */ multi = (PyArrayMultiIterObject *) PyArray_MultiIterFromObjects((PyObject **)mps, n, 1, ap); if (multi == NULL) { goto fail; } /* Set-up return array */ if (out == NULL) { dtype = PyArray_DESCR(mps[0]); Py_INCREF(dtype); obj = (PyArrayObject *)PyArray_NewFromDescr(Py_TYPE(ap), dtype, multi->nd, multi->dimensions, NULL, NULL, 0, (PyObject *)ap); } else { int flags = NPY_ARRAY_CARRAY | NPY_ARRAY_UPDATEIFCOPY | NPY_ARRAY_FORCECAST; if ((PyArray_NDIM(out) != multi->nd) || !PyArray_CompareLists(PyArray_DIMS(out), multi->dimensions, multi->nd)) { PyErr_SetString(PyExc_TypeError, "choose: invalid shape for output array."); goto fail; } if (clipmode == NPY_RAISE) { /* * we need to make sure and get a copy * so the input array is not changed * before the error is called */ flags |= NPY_ARRAY_ENSURECOPY; } dtype = PyArray_DESCR(mps[0]); Py_INCREF(dtype); obj = (PyArrayObject *)PyArray_FromArray(out, dtype, flags); } if (obj == NULL) { goto fail; } elsize = PyArray_DESCR(obj)->elsize; ret_data = PyArray_DATA(obj); while (PyArray_MultiIter_NOTDONE(multi)) { mi = *((npy_intp *)PyArray_MultiIter_DATA(multi, n)); if (mi < 0 || mi >= n) { switch(clipmode) { case NPY_RAISE: PyErr_SetString(PyExc_ValueError, "invalid entry in choice "\ "array"); goto fail; case NPY_WRAP: if (mi < 0) { while (mi < 0) { mi += n; } } else { while (mi >= n) { mi -= n; } } break; case NPY_CLIP: if (mi < 0) { mi = 0; } else if (mi >= n) { mi = n - 1; } break; } } memmove(ret_data, PyArray_MultiIter_DATA(multi, mi), elsize); ret_data += elsize; PyArray_MultiIter_NEXT(multi); } PyArray_INCREF(obj); Py_DECREF(multi); for (i = 0; i < n; i++) { Py_XDECREF(mps[i]); } Py_DECREF(ap); PyDataMem_FREE(mps); if (out != NULL && out != obj) { Py_INCREF(out); Py_DECREF(obj); obj = out; } return (PyObject *)obj; fail: Py_XDECREF(multi); for (i = 0; i < n; i++) { Py_XDECREF(mps[i]); } Py_XDECREF(ap); PyDataMem_FREE(mps); PyArray_XDECREF_ERR(obj); return NULL; } /* * These algorithms use special sorting. They are not called unless the * underlying sort function for the type is available. Note that axis is * already valid. The sort functions require 1-d contiguous and well-behaved * data. Therefore, a copy will be made of the data if needed before handing * it to the sorting routine. An iterator is constructed and adjusted to walk * over all but the desired sorting axis. */ static int _new_sortlike(PyArrayObject *op, int axis, NPY_SORTKIND swhich, PyArray_PartitionFunc * part, NPY_SELECTKIND pwhich, npy_intp * kth, npy_intp nkth) { PyArrayIterObject *it; int needcopy = 0, swap; npy_intp N, size; int elsize; npy_intp astride; PyArray_SortFunc *sort = NULL; NPY_BEGIN_THREADS_DEF; it = (PyArrayIterObject *)PyArray_IterAllButAxis((PyObject *)op, &axis); swap = !PyArray_ISNOTSWAPPED(op); if (it == NULL) { return -1; } NPY_BEGIN_THREADS_DESCR(PyArray_DESCR(op)); if (part == NULL) { sort = PyArray_DESCR(op)->f->sort[swhich]; } size = it->size; N = PyArray_DIMS(op)[axis]; elsize = PyArray_DESCR(op)->elsize; astride = PyArray_STRIDES(op)[axis]; needcopy = !(PyArray_FLAGS(op) & NPY_ARRAY_ALIGNED) || (astride != (npy_intp) elsize) || swap; if (needcopy) { char *buffer = PyDataMem_NEW(N*elsize); if (buffer == NULL) { goto fail; } while (size--) { _unaligned_strided_byte_copy(buffer, (npy_intp) elsize, it->dataptr, astride, N, elsize); if (swap) { _strided_byte_swap(buffer, (npy_intp) elsize, N, elsize); } if (part == NULL) { if (sort(buffer, N, op) < 0) { PyDataMem_FREE(buffer); goto fail; } } else { npy_intp pivots[NPY_MAX_PIVOT_STACK]; npy_intp npiv = 0; npy_intp i; for (i = 0; i < nkth; i++) { if (part(buffer, N, kth[i], pivots, &npiv, op) < 0) { PyDataMem_FREE(buffer); goto fail; } } } if (swap) { _strided_byte_swap(buffer, (npy_intp) elsize, N, elsize); } _unaligned_strided_byte_copy(it->dataptr, astride, buffer, (npy_intp) elsize, N, elsize); PyArray_ITER_NEXT(it); } PyDataMem_FREE(buffer); } else { while (size--) { if (part == NULL) { if (sort(it->dataptr, N, op) < 0) { goto fail; } } else { npy_intp pivots[NPY_MAX_PIVOT_STACK]; npy_intp npiv = 0; npy_intp i; for (i = 0; i < nkth; i++) { if (part(it->dataptr, N, kth[i], pivots, &npiv, op) < 0) { goto fail; } } } PyArray_ITER_NEXT(it); } } NPY_END_THREADS_DESCR(PyArray_DESCR(op)); Py_DECREF(it); return 0; fail: /* Out of memory during sorting or buffer creation */ NPY_END_THREADS; PyErr_NoMemory(); Py_DECREF(it); return -1; } static PyObject* _new_argsortlike(PyArrayObject *op, int axis, NPY_SORTKIND swhich, PyArray_ArgPartitionFunc * argpart, NPY_SELECTKIND pwhich, npy_intp * kth, npy_intp nkth) { PyArrayIterObject *it = NULL; PyArrayIterObject *rit = NULL; PyArrayObject *ret; npy_intp N, size, i; npy_intp astride, rstride, *iptr; int elsize; int needcopy = 0, swap; PyArray_ArgSortFunc *argsort = NULL; NPY_BEGIN_THREADS_DEF; ret = (PyArrayObject *)PyArray_New(Py_TYPE(op), PyArray_NDIM(op), PyArray_DIMS(op), NPY_INTP, NULL, NULL, 0, 0, (PyObject *)op); if (ret == NULL) { return NULL; } it = (PyArrayIterObject *)PyArray_IterAllButAxis((PyObject *)op, &axis); rit = (PyArrayIterObject *)PyArray_IterAllButAxis((PyObject *)ret, &axis); if (rit == NULL || it == NULL) { goto fail; } swap = !PyArray_ISNOTSWAPPED(op); NPY_BEGIN_THREADS_DESCR(PyArray_DESCR(op)); if (argpart == NULL) { argsort = PyArray_DESCR(op)->f->argsort[swhich]; } else { argpart = get_argpartition_func(PyArray_TYPE(op), pwhich); } size = it->size; N = PyArray_DIMS(op)[axis]; elsize = PyArray_DESCR(op)->elsize; astride = PyArray_STRIDES(op)[axis]; rstride = PyArray_STRIDE(ret,axis); needcopy = swap || !(PyArray_FLAGS(op) & NPY_ARRAY_ALIGNED) || (astride != (npy_intp) elsize) || (rstride != sizeof(npy_intp)); if (needcopy) { char *valbuffer, *indbuffer; valbuffer = PyDataMem_NEW(N*elsize); if (valbuffer == NULL) { goto fail; } indbuffer = PyDataMem_NEW(N*sizeof(npy_intp)); if (indbuffer == NULL) { PyDataMem_FREE(valbuffer); goto fail; } while (size--) { _unaligned_strided_byte_copy(valbuffer, (npy_intp) elsize, it->dataptr, astride, N, elsize); if (swap) { _strided_byte_swap(valbuffer, (npy_intp) elsize, N, elsize); } iptr = (npy_intp *)indbuffer; for (i = 0; i < N; i++) { *iptr++ = i; } if (argpart == NULL) { if (argsort(valbuffer, (npy_intp *)indbuffer, N, op) < 0) { PyDataMem_FREE(valbuffer); PyDataMem_FREE(indbuffer); goto fail; } } else { npy_intp pivots[NPY_MAX_PIVOT_STACK]; npy_intp npiv = 0; npy_intp i; for (i = 0; i < nkth; i++) { if (argpart(valbuffer, (npy_intp *)indbuffer, N, kth[i], pivots, &npiv, op) < 0) { PyDataMem_FREE(valbuffer); PyDataMem_FREE(indbuffer); goto fail; } } } _unaligned_strided_byte_copy(rit->dataptr, rstride, indbuffer, sizeof(npy_intp), N, sizeof(npy_intp)); PyArray_ITER_NEXT(it); PyArray_ITER_NEXT(rit); } PyDataMem_FREE(valbuffer); PyDataMem_FREE(indbuffer); } else { while (size--) { iptr = (npy_intp *)rit->dataptr; for (i = 0; i < N; i++) { *iptr++ = i; } if (argpart == NULL) { if (argsort(it->dataptr, (npy_intp *)rit->dataptr, N, op) < 0) { goto fail; } } else { npy_intp pivots[NPY_MAX_PIVOT_STACK]; npy_intp npiv = 0; npy_intp i; for (i = 0; i < nkth; i++) { if (argpart(it->dataptr, (npy_intp *)rit->dataptr, N, kth[i], pivots, &npiv, op) < 0) { goto fail; } } } PyArray_ITER_NEXT(it); PyArray_ITER_NEXT(rit); } } NPY_END_THREADS_DESCR(PyArray_DESCR(op)); Py_DECREF(it); Py_DECREF(rit); return (PyObject *)ret; fail: NPY_END_THREADS; if (!PyErr_Occurred()) { /* Out of memory during sorting or buffer creation */ PyErr_NoMemory(); } Py_DECREF(ret); Py_XDECREF(it); Py_XDECREF(rit); return NULL; } /* Be sure to save this global_compare when necessary */ static PyArrayObject *global_obj; static int sortCompare (const void *a, const void *b) { return PyArray_DESCR(global_obj)->f->compare(a,b,global_obj); } /* * Consumes reference to ap (op gets it) op contains a version of * the array with axes swapped if local variable axis is not the * last dimension. Origin must be defined locally. */ #define SWAPAXES(op, ap) { \ orign = PyArray_NDIM(ap)-1; \ if (axis != orign) { \ (op) = (PyArrayObject *)PyArray_SwapAxes((ap), axis, orign); \ Py_DECREF((ap)); \ if ((op) == NULL) return NULL; \ } \ else (op) = (ap); \ } /* * Consumes reference to ap (op gets it) origin must be previously * defined locally. SWAPAXES must have been called previously. * op contains the swapped version of the array. */ #define SWAPBACK(op, ap) { \ if (axis != orign) { \ (op) = (PyArrayObject *)PyArray_SwapAxes((ap), axis, orign); \ Py_DECREF((ap)); \ if ((op) == NULL) return NULL; \ } \ else (op) = (ap); \ } /* These swap axes in-place if necessary */ #define SWAPINTP(a,b) {npy_intp c; c=(a); (a) = (b); (b) = c;} #define SWAPAXES2(ap) { \ orign = PyArray_NDIM(ap)-1; \ if (axis != orign) { \ SWAPINTP(PyArray_DIMS(ap)[axis], PyArray_DIMS(ap)[orign]); \ SWAPINTP(PyArray_STRIDES(ap)[axis], PyArray_STRIDES(ap)[orign]); \ PyArray_UpdateFlags(ap, NPY_ARRAY_C_CONTIGUOUS | \ NPY_ARRAY_F_CONTIGUOUS); \ } \ } #define SWAPBACK2(ap) { \ if (axis != orign) { \ SWAPINTP(PyArray_DIMS(ap)[axis], PyArray_DIMS(ap)[orign]); \ SWAPINTP(PyArray_STRIDES(ap)[axis], PyArray_STRIDES(ap)[orign]); \ PyArray_UpdateFlags(ap, NPY_ARRAY_C_CONTIGUOUS | \ NPY_ARRAY_F_CONTIGUOUS); \ } \ } /*NUMPY_API * Sort an array in-place */ NPY_NO_EXPORT int PyArray_Sort(PyArrayObject *op, int axis, NPY_SORTKIND which) { PyArrayObject *ap = NULL, *store_arr = NULL; char *ip; npy_intp i, n, m; int elsize, orign; int res = 0; int axis_orig = axis; int (*sort)(void *, size_t, size_t, npy_comparator); n = PyArray_NDIM(op); if ((n == 0) || (PyArray_SIZE(op) == 1)) { return 0; } if (axis < 0) { axis += n; } if ((axis < 0) || (axis >= n)) { PyErr_Format(PyExc_ValueError, "axis(=%d) out of bounds", axis_orig); return -1; } if (PyArray_FailUnlessWriteable(op, "sort array") < 0) { return -1; } /* Determine if we should use type-specific algorithm or not */ if (PyArray_DESCR(op)->f->sort[which] != NULL) { return _new_sortlike(op, axis, which, NULL, 0, NULL, 0); } if (PyArray_DESCR(op)->f->compare == NULL) { PyErr_SetString(PyExc_TypeError, "type does not have compare function"); return -1; } SWAPAXES2(op); switch (which) { case NPY_QUICKSORT : sort = npy_quicksort; break; case NPY_HEAPSORT : sort = npy_heapsort; break; case NPY_MERGESORT : sort = npy_mergesort; break; default: PyErr_SetString(PyExc_TypeError, "requested sort kind is not supported"); goto fail; } ap = (PyArrayObject *)PyArray_FromAny((PyObject *)op, NULL, 1, 0, NPY_ARRAY_DEFAULT | NPY_ARRAY_UPDATEIFCOPY, NULL); if (ap == NULL) { goto fail; } elsize = PyArray_DESCR(ap)->elsize; m = PyArray_DIMS(ap)[PyArray_NDIM(ap)-1]; if (m == 0) { goto finish; } n = PyArray_SIZE(ap)/m; /* Store global -- allows re-entry -- restore before leaving*/ store_arr = global_obj; global_obj = ap; for (ip = PyArray_DATA(ap), i = 0; i < n; i++, ip += elsize*m) { res = sort(ip, m, elsize, sortCompare); if (res < 0) { break; } } global_obj = store_arr; if (PyErr_Occurred()) { goto fail; } else if (res == -NPY_ENOMEM) { PyErr_NoMemory(); goto fail; } else if (res == -NPY_ECOMP) { PyErr_SetString(PyExc_TypeError, "sort comparison failed"); goto fail; } finish: Py_DECREF(ap); /* Should update op if needed */ SWAPBACK2(op); return 0; fail: Py_XDECREF(ap); SWAPBACK2(op); return -1; } /* * make kth array positive, ravel and sort it */ static PyArrayObject * partition_prep_kth_array(PyArrayObject * ktharray, PyArrayObject * op, int axis) { const npy_intp * shape = PyArray_SHAPE(op); PyArrayObject * kthrvl; npy_intp * kth; npy_intp nkth, i; if (!PyArray_CanCastSafely(PyArray_TYPE(ktharray), NPY_INTP)) { if (DEPRECATE("Calling partition with a non integer index" " will result in an error in the future") < 0) { return NULL; } } if (PyArray_NDIM(ktharray) > 1) { PyErr_Format(PyExc_ValueError, "kth array must have dimension <= 1"); return NULL; } kthrvl = PyArray_Cast(ktharray, NPY_INTP); if (kthrvl == NULL) return NULL; kth = PyArray_DATA(kthrvl); nkth = PyArray_SIZE(kthrvl); for (i = 0; i < nkth; i++) { if (kth[i] < 0) { kth[i] += shape[axis]; } if (PyArray_SIZE(op) != 0 && ((kth[i] < 0) || (kth[i] >= shape[axis]))) { PyErr_Format(PyExc_ValueError, "kth(=%zd) out of bounds (%zd)", kth[i], shape[axis]); Py_XDECREF(kthrvl); return NULL; } } /* * sort the array of kths so the partitions will * not trample on each other */ PyArray_Sort(kthrvl, -1, NPY_QUICKSORT); return kthrvl; } /*NUMPY_API * Partition an array in-place */ NPY_NO_EXPORT int PyArray_Partition(PyArrayObject *op, PyArrayObject * ktharray, int axis, NPY_SELECTKIND which) { PyArrayObject *ap = NULL, *store_arr = NULL; char *ip; npy_intp i, n, m; int elsize, orign; int res = 0; int axis_orig = axis; int (*sort)(void *, size_t, size_t, npy_comparator); PyArray_PartitionFunc * part = get_partition_func(PyArray_TYPE(op), which); n = PyArray_NDIM(op); if ((n == 0)) { return 0; } if (axis < 0) { axis += n; } if ((axis < 0) || (axis >= n)) { PyErr_Format(PyExc_ValueError, "axis(=%d) out of bounds", axis_orig); return -1; } if (PyArray_FailUnlessWriteable(op, "sort array") < 0) { return -1; } if (part) { PyArrayObject * kthrvl = partition_prep_kth_array(ktharray, op, axis); if (kthrvl == NULL) return -1; res = _new_sortlike(op, axis, 0, part, which, PyArray_DATA(kthrvl), PyArray_SIZE(kthrvl)); Py_DECREF(kthrvl); return res; } if (PyArray_DESCR(op)->f->compare == NULL) { PyErr_SetString(PyExc_TypeError, "type does not have compare function"); return -1; } SWAPAXES2(op); /* select not implemented, use quicksort, slower but equivalent */ switch (which) { case NPY_INTROSELECT : sort = npy_quicksort; break; default: PyErr_SetString(PyExc_TypeError, "requested sort kind is not supported"); goto fail; } ap = (PyArrayObject *)PyArray_FromAny((PyObject *)op, NULL, 1, 0, NPY_ARRAY_DEFAULT | NPY_ARRAY_UPDATEIFCOPY, NULL); if (ap == NULL) { goto fail; } elsize = PyArray_DESCR(ap)->elsize; m = PyArray_DIMS(ap)[PyArray_NDIM(ap)-1]; if (m == 0) { goto finish; } n = PyArray_SIZE(ap)/m; /* Store global -- allows re-entry -- restore before leaving*/ store_arr = global_obj; global_obj = ap; /* we don't need to care about kth here as we are using a full sort */ for (ip = PyArray_DATA(ap), i = 0; i < n; i++, ip += elsize*m) { res = sort(ip, m, elsize, sortCompare); if (res < 0) { break; } } global_obj = store_arr; if (PyErr_Occurred()) { goto fail; } else if (res == -NPY_ENOMEM) { PyErr_NoMemory(); goto fail; } else if (res == -NPY_ECOMP) { PyErr_SetString(PyExc_TypeError, "sort comparison failed"); goto fail; } finish: Py_DECREF(ap); /* Should update op if needed */ SWAPBACK2(op); return 0; fail: Py_XDECREF(ap); SWAPBACK2(op); return -1; } static char *global_data; static int argsort_static_compare(const void *ip1, const void *ip2) { int isize = PyArray_DESCR(global_obj)->elsize; const npy_intp *ipa = ip1; const npy_intp *ipb = ip2; return PyArray_DESCR(global_obj)->f->compare(global_data + (isize * *ipa), global_data + (isize * *ipb), global_obj); } /*NUMPY_API * ArgSort an array */ NPY_NO_EXPORT PyObject * PyArray_ArgSort(PyArrayObject *op, int axis, NPY_SORTKIND which) { PyArrayObject *ap = NULL, *ret = NULL, *store, *op2; npy_intp *ip; npy_intp i, j, n, m, orign; int argsort_elsize; char *store_ptr; int res = 0; int (*sort)(void *, size_t, size_t, npy_comparator); n = PyArray_NDIM(op); if ((n == 0) || (PyArray_SIZE(op) == 1)) { ret = (PyArrayObject *)PyArray_New(Py_TYPE(op), PyArray_NDIM(op), PyArray_DIMS(op), NPY_INTP, NULL, NULL, 0, 0, (PyObject *)op); if (ret == NULL) { return NULL; } *((npy_intp *)PyArray_DATA(ret)) = 0; return (PyObject *)ret; } /* Creates new reference op2 */ if ((op2=(PyArrayObject *)PyArray_CheckAxis(op, &axis, 0)) == NULL) { return NULL; } /* Determine if we should use new algorithm or not */ if (PyArray_DESCR(op2)->f->argsort[which] != NULL) { ret = (PyArrayObject *)_new_argsortlike(op2, axis, which, NULL, 0, NULL, 0); Py_DECREF(op2); return (PyObject *)ret; } if (PyArray_DESCR(op2)->f->compare == NULL) { PyErr_SetString(PyExc_TypeError, "type does not have compare function"); Py_DECREF(op2); op = NULL; goto fail; } switch (which) { case NPY_QUICKSORT : sort = npy_quicksort; break; case NPY_HEAPSORT : sort = npy_heapsort; break; case NPY_MERGESORT : sort = npy_mergesort; break; default: PyErr_SetString(PyExc_TypeError, "requested sort kind is not supported"); Py_DECREF(op2); op = NULL; goto fail; } /* ap will contain the reference to op2 */ SWAPAXES(ap, op2); op = (PyArrayObject *)PyArray_ContiguousFromAny((PyObject *)ap, NPY_NOTYPE, 1, 0); Py_DECREF(ap); if (op == NULL) { return NULL; } ret = (PyArrayObject *)PyArray_New(Py_TYPE(op), PyArray_NDIM(op), PyArray_DIMS(op), NPY_INTP, NULL, NULL, 0, 0, (PyObject *)op); if (ret == NULL) { goto fail; } ip = (npy_intp *)PyArray_DATA(ret); argsort_elsize = PyArray_DESCR(op)->elsize; m = PyArray_DIMS(op)[PyArray_NDIM(op)-1]; if (m == 0) { goto finish; } n = PyArray_SIZE(op)/m; store_ptr = global_data; global_data = PyArray_DATA(op); store = global_obj; global_obj = op; for (i = 0; i < n; i++, ip += m, global_data += m*argsort_elsize) { for (j = 0; j < m; j++) { ip[j] = j; } res = sort((char *)ip, m, sizeof(npy_intp), argsort_static_compare); if (res < 0) { break; } } global_data = store_ptr; global_obj = store; if (PyErr_Occurred()) { goto fail; } else if (res == -NPY_ENOMEM) { PyErr_NoMemory(); goto fail; } else if (res == -NPY_ECOMP) { PyErr_SetString(PyExc_TypeError, "sort comparison failed"); goto fail; } finish: Py_DECREF(op); SWAPBACK(op, ret); return (PyObject *)op; fail: Py_XDECREF(op); Py_XDECREF(ret); return NULL; } /*NUMPY_API * ArgPartition an array */ NPY_NO_EXPORT PyObject * PyArray_ArgPartition(PyArrayObject *op, PyArrayObject * ktharray, int axis, NPY_SELECTKIND which) { PyArrayObject *ap = NULL, *ret = NULL, *store, *op2; npy_intp *ip; npy_intp i, j, n, m, orign; int argsort_elsize; char *store_ptr; int res = 0; int (*sort)(void *, size_t, size_t, npy_comparator); PyArray_ArgPartitionFunc * argpart = get_argpartition_func(PyArray_TYPE(op), which); n = PyArray_NDIM(op); if ((n == 0) || (PyArray_SIZE(op) == 1)) { ret = (PyArrayObject *)PyArray_New(Py_TYPE(op), PyArray_NDIM(op), PyArray_DIMS(op), NPY_INTP, NULL, NULL, 0, 0, (PyObject *)op); if (ret == NULL) { return NULL; } *((npy_intp *)PyArray_DATA(ret)) = 0; return (PyObject *)ret; } /* Creates new reference op2 */ if ((op2=(PyArrayObject *)PyArray_CheckAxis(op, &axis, 0)) == NULL) { return NULL; } /* Determine if we should use new algorithm or not */ if (argpart) { PyArrayObject * kthrvl = partition_prep_kth_array(ktharray, op2, axis); if (kthrvl == NULL) { Py_DECREF(op2); return NULL; } ret = (PyArrayObject *)_new_argsortlike(op2, axis, 0, argpart, which, PyArray_DATA(kthrvl), PyArray_SIZE(kthrvl)); Py_DECREF(kthrvl); Py_DECREF(op2); return (PyObject *)ret; } if (PyArray_DESCR(op2)->f->compare == NULL) { PyErr_SetString(PyExc_TypeError, "type does not have compare function"); Py_DECREF(op2); op = NULL; goto fail; } /* select not implemented, use quicksort, slower but equivalent */ switch (which) { case NPY_INTROSELECT : sort = npy_quicksort; break; default: PyErr_SetString(PyExc_TypeError, "requested sort kind is not supported"); Py_DECREF(op2); op = NULL; goto fail; } /* ap will contain the reference to op2 */ SWAPAXES(ap, op2); op = (PyArrayObject *)PyArray_ContiguousFromAny((PyObject *)ap, NPY_NOTYPE, 1, 0); Py_DECREF(ap); if (op == NULL) { return NULL; } ret = (PyArrayObject *)PyArray_New(Py_TYPE(op), PyArray_NDIM(op), PyArray_DIMS(op), NPY_INTP, NULL, NULL, 0, 0, (PyObject *)op); if (ret == NULL) { goto fail; } ip = (npy_intp *)PyArray_DATA(ret); argsort_elsize = PyArray_DESCR(op)->elsize; m = PyArray_DIMS(op)[PyArray_NDIM(op)-1]; if (m == 0) { goto finish; } n = PyArray_SIZE(op)/m; store_ptr = global_data; global_data = PyArray_DATA(op); store = global_obj; global_obj = op; /* we don't need to care about kth here as we are using a full sort */ for (i = 0; i < n; i++, ip += m, global_data += m*argsort_elsize) { for (j = 0; j < m; j++) { ip[j] = j; } res = sort((char *)ip, m, sizeof(npy_intp), argsort_static_compare); if (res < 0) { break; } } global_data = store_ptr; global_obj = store; if (PyErr_Occurred()) { goto fail; } else if (res == -NPY_ENOMEM) { PyErr_NoMemory(); goto fail; } else if (res == -NPY_ECOMP) { PyErr_SetString(PyExc_TypeError, "sort comparison failed"); goto fail; } finish: Py_DECREF(op); SWAPBACK(op, ret); return (PyObject *)op; fail: Py_XDECREF(op); Py_XDECREF(ret); return NULL; } /*NUMPY_API *LexSort an array providing indices that will sort a collection of arrays *lexicographically. The first key is sorted on first, followed by the second key *-- requires that arg"merge"sort is available for each sort_key * *Returns an index array that shows the indexes for the lexicographic sort along *the given axis. */ NPY_NO_EXPORT PyObject * PyArray_LexSort(PyObject *sort_keys, int axis) { PyArrayObject **mps; PyArrayIterObject **its; PyArrayObject *ret = NULL; PyArrayIterObject *rit = NULL; npy_intp n, N, size, i, j; npy_intp astride, rstride, *iptr; int nd; int needcopy = 0; int elsize; int maxelsize; int object = 0; PyArray_ArgSortFunc *argsort; NPY_BEGIN_THREADS_DEF; if (!PySequence_Check(sort_keys) || ((n = PySequence_Size(sort_keys)) <= 0)) { PyErr_SetString(PyExc_TypeError, "need sequence of keys with len > 0 in lexsort"); return NULL; } mps = (PyArrayObject **) PyArray_malloc(n * sizeof(PyArrayObject *)); if (mps == NULL) { return PyErr_NoMemory(); } its = (PyArrayIterObject **) PyArray_malloc(n * sizeof(PyArrayIterObject *)); if (its == NULL) { PyArray_free(mps); return PyErr_NoMemory(); } for (i = 0; i < n; i++) { mps[i] = NULL; its[i] = NULL; } for (i = 0; i < n; i++) { PyObject *obj; obj = PySequence_GetItem(sort_keys, i); if (obj == NULL) { goto fail; } mps[i] = (PyArrayObject *)PyArray_FROM_O(obj); Py_DECREF(obj); if (mps[i] == NULL) { goto fail; } if (i > 0) { if ((PyArray_NDIM(mps[i]) != PyArray_NDIM(mps[0])) || (!PyArray_CompareLists(PyArray_DIMS(mps[i]), PyArray_DIMS(mps[0]), PyArray_NDIM(mps[0])))) { PyErr_SetString(PyExc_ValueError, "all keys need to be the same shape"); goto fail; } } if (!PyArray_DESCR(mps[i])->f->argsort[NPY_MERGESORT]) { PyErr_Format(PyExc_TypeError, "merge sort not available for item %zd", i); goto fail; } if (!object && PyDataType_FLAGCHK(PyArray_DESCR(mps[i]), NPY_NEEDS_PYAPI)) { object = 1; } its[i] = (PyArrayIterObject *)PyArray_IterAllButAxis( (PyObject *)mps[i], &axis); if (its[i] == NULL) { goto fail; } } /* Now we can check the axis */ nd = PyArray_NDIM(mps[0]); if ((nd == 0) || (PyArray_SIZE(mps[0]) == 1)) { /* single element case */ ret = (PyArrayObject *)PyArray_New(&PyArray_Type, PyArray_NDIM(mps[0]), PyArray_DIMS(mps[0]), NPY_INTP, NULL, NULL, 0, 0, NULL); if (ret == NULL) { goto fail; } *((npy_intp *)(PyArray_DATA(ret))) = 0; goto finish; } if (axis < 0) { axis += nd; } if ((axis < 0) || (axis >= nd)) { PyErr_Format(PyExc_ValueError, "axis(=%d) out of bounds", axis); goto fail; } /* Now do the sorting */ ret = (PyArrayObject *)PyArray_New(&PyArray_Type, PyArray_NDIM(mps[0]), PyArray_DIMS(mps[0]), NPY_INTP, NULL, NULL, 0, 0, NULL); if (ret == NULL) { goto fail; } rit = (PyArrayIterObject *) PyArray_IterAllButAxis((PyObject *)ret, &axis); if (rit == NULL) { goto fail; } if (!object) { NPY_BEGIN_THREADS; } size = rit->size; N = PyArray_DIMS(mps[0])[axis]; rstride = PyArray_STRIDE(ret, axis); maxelsize = PyArray_DESCR(mps[0])->elsize; needcopy = (rstride != sizeof(npy_intp)); for (j = 0; j < n; j++) { needcopy = needcopy || PyArray_ISBYTESWAPPED(mps[j]) || !(PyArray_FLAGS(mps[j]) & NPY_ARRAY_ALIGNED) || (PyArray_STRIDES(mps[j])[axis] != (npy_intp)PyArray_DESCR(mps[j])->elsize); if (PyArray_DESCR(mps[j])->elsize > maxelsize) { maxelsize = PyArray_DESCR(mps[j])->elsize; } } if (needcopy) { char *valbuffer, *indbuffer; int *swaps; valbuffer = PyDataMem_NEW(N*maxelsize); if (valbuffer == NULL) { goto fail; } indbuffer = PyDataMem_NEW(N*sizeof(npy_intp)); if (indbuffer == NULL) { PyDataMem_FREE(indbuffer); goto fail; } swaps = malloc(n*sizeof(int)); for (j = 0; j < n; j++) { swaps[j] = PyArray_ISBYTESWAPPED(mps[j]); } while (size--) { iptr = (npy_intp *)indbuffer; for (i = 0; i < N; i++) { *iptr++ = i; } for (j = 0; j < n; j++) { elsize = PyArray_DESCR(mps[j])->elsize; astride = PyArray_STRIDES(mps[j])[axis]; argsort = PyArray_DESCR(mps[j])->f->argsort[NPY_MERGESORT]; _unaligned_strided_byte_copy(valbuffer, (npy_intp) elsize, its[j]->dataptr, astride, N, elsize); if (swaps[j]) { _strided_byte_swap(valbuffer, (npy_intp) elsize, N, elsize); } if (argsort(valbuffer, (npy_intp *)indbuffer, N, mps[j]) < 0) { PyDataMem_FREE(valbuffer); PyDataMem_FREE(indbuffer); free(swaps); goto fail; } PyArray_ITER_NEXT(its[j]); } _unaligned_strided_byte_copy(rit->dataptr, rstride, indbuffer, sizeof(npy_intp), N, sizeof(npy_intp)); PyArray_ITER_NEXT(rit); } PyDataMem_FREE(valbuffer); PyDataMem_FREE(indbuffer); free(swaps); } else { while (size--) { iptr = (npy_intp *)rit->dataptr; for (i = 0; i < N; i++) { *iptr++ = i; } for (j = 0; j < n; j++) { argsort = PyArray_DESCR(mps[j])->f->argsort[NPY_MERGESORT]; if (argsort(its[j]->dataptr, (npy_intp *)rit->dataptr, N, mps[j]) < 0) { goto fail; } PyArray_ITER_NEXT(its[j]); } PyArray_ITER_NEXT(rit); } } if (!object) { NPY_END_THREADS; } finish: for (i = 0; i < n; i++) { Py_XDECREF(mps[i]); Py_XDECREF(its[i]); } Py_XDECREF(rit); PyArray_free(mps); PyArray_free(its); return (PyObject *)ret; fail: NPY_END_THREADS; if (!PyErr_Occurred()) { /* Out of memory during sorting or buffer creation */ PyErr_NoMemory(); } Py_XDECREF(rit); Py_XDECREF(ret); for (i = 0; i < n; i++) { Py_XDECREF(mps[i]); Py_XDECREF(its[i]); } PyArray_free(mps); PyArray_free(its); return NULL; } /** @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 * result is an array of indexes, one for each element in op2, such that if * the item were to be inserted in op1 just before that index the array * would still be in sorted order. * * Parameters * ---------- * op1 : PyArrayObject * * Array to be searched, must be 1-D. * op2 : PyObject * * Array of items whose insertion indexes in op1 are wanted * side : {NPY_SEARCHLEFT, NPY_SEARCHRIGHT} * If NPY_SEARCHLEFT, return first valid insertion indexes * If NPY_SEARCHRIGHT, return last valid insertion indexes * perm : PyObject * * Permutation array that sorts op1 (optional) * * Returns * ------- * ret : PyObject * * New reference to npy_intp array containing indexes where items in op2 * could be validly inserted into op1. NULL on error. * * Notes * ----- * Binary search is used to find the indexes. */ NPY_NO_EXPORT PyObject * PyArray_SearchSorted(PyArrayObject *op1, PyObject *op2, NPY_SEARCHSIDE side, PyObject *perm) { PyArrayObject *ap1 = NULL; PyArrayObject *ap2 = NULL; PyArrayObject *ap3 = NULL; PyArrayObject *sorter = NULL; PyArrayObject *ret = NULL; PyArray_Descr *dtype; int ap1_flags = NPY_ARRAY_NOTSWAPPED | NPY_ARRAY_ALIGNED; NPY_BEGIN_THREADS_DEF; /* Find common type */ dtype = PyArray_DescrFromObject((PyObject *)op2, PyArray_DESCR(op1)); if (dtype == NULL) { return NULL; } /* need ap2 as contiguous array and of right type */ Py_INCREF(dtype); ap2 = (PyArrayObject *)PyArray_CheckFromAny(op2, dtype, 0, 0, NPY_ARRAY_CARRAY_RO | NPY_ARRAY_NOTSWAPPED, NULL); if (ap2 == NULL) { Py_DECREF(dtype); return NULL; } /* * If the needle (ap2) is larger than the haystack (op1) we copy the * haystack to a continuous 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); 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 */ ap3 = (PyArrayObject *)PyArray_CheckFromAny(perm, NULL, 1, 1, NPY_ARRAY_ALIGNED | NPY_ARRAY_NOTSWAPPED, NULL); if (ap3 == NULL) { PyErr_SetString(PyExc_TypeError, "could not parse sorter argument"); goto fail; } if (!PyArray_ISINTEGER(ap3)) { PyErr_SetString(PyExc_TypeError, "sorter must only contain integers"); goto fail; } /* convert to known integer size */ sorter = (PyArrayObject *)PyArray_FromArray(ap3, PyArray_DescrFromType(NPY_INTP), NPY_ARRAY_ALIGNED | NPY_ARRAY_NOTSWAPPED); if (sorter == NULL) { PyErr_SetString(PyExc_ValueError, "could not parse sorter argument"); goto fail; } if (PyArray_SIZE(sorter) != PyArray_SIZE(ap1)) { PyErr_SetString(PyExc_ValueError, "sorter.size must equal a.size"); goto fail; } } /* ret is a contiguous array of intp type to hold returned indices */ ret = (PyArrayObject *)PyArray_New(Py_TYPE(ap2), PyArray_NDIM(ap2), PyArray_DIMS(ap2), NPY_INTP, NULL, NULL, 0, 0, (PyObject *)ap2); if (ret == NULL) { goto fail; } 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)); } } 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) { PyErr_SetString(PyExc_ValueError, "Sorter index out of range."); goto fail; } Py_DECREF(ap3); Py_DECREF(sorter); } Py_DECREF(ap1); Py_DECREF(ap2); return (PyObject *)ret; fail: Py_XDECREF(ap1); Py_XDECREF(ap2); Py_XDECREF(ap3); Py_XDECREF(sorter); Py_XDECREF(ret); return NULL; } /*NUMPY_API * Diagonal * * In NumPy versions prior to 1.7, this function always returned a copy of * the diagonal array. In 1.7, the code has been updated to compute a view * onto 'self', but it still copies this array before returning, as well as * setting the internal WARN_ON_WRITE flag. In a future version, it will * simply return a view onto self. */ NPY_NO_EXPORT PyObject * PyArray_Diagonal(PyArrayObject *self, int offset, int axis1, int axis2) { int i, idim, ndim = PyArray_NDIM(self); npy_intp *strides; npy_intp stride1, stride2; npy_intp *shape, dim1, dim2; char *data; npy_intp diag_size; PyArrayObject *ret; PyArray_Descr *dtype; npy_intp ret_shape[NPY_MAXDIMS], ret_strides[NPY_MAXDIMS]; PyObject *copy; if (ndim < 2) { PyErr_SetString(PyExc_ValueError, "diag requires an array of at least two dimensions"); return NULL; } /* Handle negative axes with standard Python indexing rules */ if (axis1 < 0) { axis1 += ndim; } if (axis2 < 0) { axis2 += ndim; } /* Error check the two axes */ if (axis1 == axis2) { PyErr_SetString(PyExc_ValueError, "axis1 and axis2 cannot be the same"); return NULL; } else if (axis1 < 0 || axis1 >= ndim || axis2 < 0 || axis2 >= ndim) { PyErr_Format(PyExc_ValueError, "axis1(=%d) and axis2(=%d) " "must be within range (ndim=%d)", axis1, axis2, ndim); return NULL; } /* Get the shape and strides of the two axes */ shape = PyArray_SHAPE(self); dim1 = shape[axis1]; dim2 = shape[axis2]; strides = PyArray_STRIDES(self); stride1 = strides[axis1]; stride2 = strides[axis2]; /* Compute the data pointers and diag_size for the view */ data = PyArray_DATA(self); if (offset > 0) { if (offset >= dim2) { diag_size = 0; } else { data += offset * stride2; diag_size = dim2 - offset; if (dim1 < diag_size) { diag_size = dim1; } } } else if (offset < 0) { offset = -offset; if (offset >= dim1) { diag_size = 0; } else { data += offset * stride1; diag_size = dim1 - offset; if (dim2 < diag_size) { diag_size = dim2; } } } else { diag_size = dim1 < dim2 ? dim1 : dim2; } /* Build the new shape and strides for the main data */ i = 0; for (idim = 0; idim < ndim; ++idim) { if (idim != axis1 && idim != axis2) { ret_shape[i] = shape[idim]; ret_strides[i] = strides[idim]; ++i; } } ret_shape[ndim-2] = diag_size; ret_strides[ndim-2] = stride1 + stride2; /* Create the diagonal view */ dtype = PyArray_DTYPE(self); Py_INCREF(dtype); ret = (PyArrayObject *)PyArray_NewFromDescr(Py_TYPE(self), dtype, ndim-1, ret_shape, ret_strides, data, PyArray_FLAGS(self), (PyObject *)self); if (ret == NULL) { return NULL; } Py_INCREF(self); if (PyArray_SetBaseObject(ret, (PyObject *)self) < 0) { Py_DECREF(ret); return NULL; } /* For backwards compatibility, during the deprecation period: */ copy = PyArray_NewCopy(ret, NPY_KEEPORDER); Py_DECREF(ret); if (!copy) { return NULL; } PyArray_ENABLEFLAGS((PyArrayObject *)copy, NPY_ARRAY_WARN_ON_WRITE); return copy; } /*NUMPY_API * Compress */ NPY_NO_EXPORT PyObject * PyArray_Compress(PyArrayObject *self, PyObject *condition, int axis, PyArrayObject *out) { PyArrayObject *cond; PyObject *res, *ret; if (PyArray_Check(condition)) { cond = (PyArrayObject *)condition; Py_INCREF(cond); } else { PyArray_Descr *dtype = PyArray_DescrFromType(NPY_BOOL); if (dtype == NULL) { return NULL; } cond = (PyArrayObject *)PyArray_FromAny(condition, dtype, 0, 0, 0, NULL); if (cond == NULL) { return NULL; } } if (PyArray_NDIM(cond) != 1) { Py_DECREF(cond); PyErr_SetString(PyExc_ValueError, "condition must be a 1-d array"); return NULL; } res = PyArray_Nonzero(cond); Py_DECREF(cond); if (res == NULL) { return res; } ret = PyArray_TakeFrom(self, PyTuple_GET_ITEM(res, 0), axis, out, NPY_RAISE); Py_DECREF(res); return ret; } /* * Counts the number of True values in a raw boolean array. This * is a low-overhead function which does no heap allocations. * * Returns -1 on error. */ NPY_NO_EXPORT npy_intp count_boolean_trues(int ndim, char *data, npy_intp *ashape, npy_intp *astrides) { int idim; npy_intp shape[NPY_MAXDIMS], strides[NPY_MAXDIMS]; npy_intp i, coord[NPY_MAXDIMS]; npy_intp count = 0; /* Use raw iteration with no heap memory allocation */ if (PyArray_PrepareOneRawArrayIter( ndim, ashape, data, astrides, &ndim, shape, &data, strides) < 0) { return -1; } /* Handle zero-sized array */ if (shape[0] == 0) { return 0; } /* Special case for contiguous inner loop */ if (strides[0] == 1) { NPY_RAW_ITER_START(idim, ndim, coord, shape) { char *d = data; /* Process the innermost dimension */ for (i = 0; i < shape[0]; ++i, ++d) { count += (*d != 0); } } NPY_RAW_ITER_ONE_NEXT(idim, ndim, coord, shape, data, strides); } /* General inner loop */ else { NPY_RAW_ITER_START(idim, ndim, coord, shape) { char *d = data; /* Process the innermost dimension */ for (i = 0; i < shape[0]; ++i, d += strides[0]) { count += (*d != 0); } } NPY_RAW_ITER_ONE_NEXT(idim, ndim, coord, shape, data, strides); } return count; } /*NUMPY_API * Counts the number of non-zero elements in the array. * * Returns -1 on error. */ NPY_NO_EXPORT npy_intp PyArray_CountNonzero(PyArrayObject *self) { PyArray_NonzeroFunc *nonzero; char *data; npy_intp stride, count; npy_intp nonzero_count = 0; NpyIter *iter; NpyIter_IterNextFunc *iternext; char **dataptr; npy_intp *strideptr, *innersizeptr; /* Special low-overhead version specific to the boolean type */ if (PyArray_DESCR(self)->type_num == NPY_BOOL) { return count_boolean_trues(PyArray_NDIM(self), PyArray_DATA(self), PyArray_DIMS(self), PyArray_STRIDES(self)); } nonzero = PyArray_DESCR(self)->f->nonzero; /* If it's a trivial one-dimensional loop, don't use an iterator */ if (PyArray_TRIVIALLY_ITERABLE(self)) { PyArray_PREPARE_TRIVIAL_ITERATION(self, count, data, stride); while (count--) { if (nonzero(data, self)) { ++nonzero_count; } data += stride; } return nonzero_count; } /* * If the array has size zero, return zero (the iterator rejects * size zero arrays) */ if (PyArray_SIZE(self) == 0) { return 0; } /* * Otherwise create and use an iterator to count the nonzeros. */ iter = NpyIter_New(self, NPY_ITER_READONLY | NPY_ITER_EXTERNAL_LOOP | NPY_ITER_REFS_OK, NPY_KEEPORDER, NPY_NO_CASTING, NULL); if (iter == NULL) { return -1; } /* Get the pointers for inner loop iteration */ iternext = NpyIter_GetIterNext(iter, NULL); if (iternext == NULL) { NpyIter_Deallocate(iter); return -1; } dataptr = NpyIter_GetDataPtrArray(iter); strideptr = NpyIter_GetInnerStrideArray(iter); innersizeptr = NpyIter_GetInnerLoopSizePtr(iter); /* Iterate over all the elements to count the nonzeros */ do { data = *dataptr; stride = *strideptr; count = *innersizeptr; while (count--) { if (nonzero(data, self)) { ++nonzero_count; } data += stride; } } while(iternext(iter)); NpyIter_Deallocate(iter); return PyErr_Occurred() ? -1 : nonzero_count; } /*NUMPY_API * Nonzero * * TODO: In NumPy 2.0, should make the iteration order a parameter. */ NPY_NO_EXPORT PyObject * PyArray_Nonzero(PyArrayObject *self) { int i, ndim = PyArray_NDIM(self); PyArrayObject *ret = NULL; 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; NpyIter_GetMultiIndexFunc *get_multi_index; char **dataptr; /* * First count the number of non-zeros in 'self'. */ nonzero_count = PyArray_CountNonzero(self); if (nonzero_count < 0) { return NULL; } /* Allocate the result as a 2D array */ ret_dims[0] = nonzero_count; ret_dims[1] = (ndim == 0) ? 1 : ndim; ret = (PyArrayObject *)PyArray_New(&PyArray_Type, 2, ret_dims, NPY_INTP, NULL, NULL, 0, 0, NULL); if (ret == NULL) { return NULL; } /* If it's a one-dimensional result, don't use an iterator */ if (ndim <= 1) { npy_intp j; 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); for (j = 0; j < count; ++j) { if (nonzero(data, self)) { *multi_index++ = j; } data += stride; } goto finish; } /* * Build an iterator tracking a multi-index, in C order. */ iter = NpyIter_New(self, NPY_ITER_READONLY | NPY_ITER_MULTI_INDEX | NPY_ITER_ZEROSIZE_OK | NPY_ITER_REFS_OK, NPY_CORDER, NPY_NO_CASTING, NULL); if (iter == NULL) { Py_DECREF(ret); return NULL; } if (NpyIter_GetIterSize(iter) != 0) { /* Get the pointers for inner loop iteration */ iternext = NpyIter_GetIterNext(iter, NULL); if (iternext == NULL) { NpyIter_Deallocate(iter); Py_DECREF(ret); return NULL; } get_multi_index = NpyIter_GetGetMultiIndex(iter, NULL); if (get_multi_index == NULL) { NpyIter_Deallocate(iter); Py_DECREF(ret); return NULL; } dataptr = NpyIter_GetDataPtrArray(iter); multi_index = (npy_intp *)PyArray_DATA(ret); /* Get the multi-index for each non-zero element */ do { if (nonzero(*dataptr, self)) { get_multi_index(iter, multi_index); multi_index += ndim; } } while(iternext(iter)); } NpyIter_Deallocate(iter); finish: /* Treat zero-dimensional as shape (1,) */ if (ndim == 0) { ndim = 1; } ret_tuple = PyTuple_New(ndim); if (ret_tuple == NULL) { Py_DECREF(ret); return NULL; } /* Create views into ret, one for each dimension */ if (ndim == 1) { /* Directly switch to one dimensions (dimension 1 is 1 anyway) */ ((PyArrayObject_fields *)ret)->nd = 1; PyTuple_SET_ITEM(ret_tuple, 0, (PyObject *)ret); } else { for (i = 0; i < ndim; ++i) { PyArrayObject *view; stride = ndim*NPY_SIZEOF_INTP; view = (PyArrayObject *)PyArray_New(Py_TYPE(self), 1, &nonzero_count, NPY_INTP, &stride, PyArray_BYTES(ret) + i*NPY_SIZEOF_INTP, 0, 0, (PyObject *)self); if (view == NULL) { Py_DECREF(ret); Py_DECREF(ret_tuple); return NULL; } Py_INCREF(ret); if (PyArray_SetBaseObject(view, (PyObject *)ret) < 0) { Py_DECREF(ret); Py_DECREF(ret_tuple); } PyTuple_SET_ITEM(ret_tuple, i, (PyObject *)view); } Py_DECREF(ret); } return ret_tuple; } /* * Gets a single item from the array, based on a single multi-index * array of values, which must be of length PyArray_NDIM(self). */ NPY_NO_EXPORT PyObject * PyArray_MultiIndexGetItem(PyArrayObject *self, npy_intp *multi_index) { int idim, ndim = PyArray_NDIM(self); char *data = PyArray_DATA(self); npy_intp *shape = PyArray_SHAPE(self); npy_intp *strides = PyArray_STRIDES(self); /* Get the data pointer */ for (idim = 0; idim < ndim; ++idim) { npy_intp shapevalue = shape[idim]; npy_intp ind = multi_index[idim]; if (check_and_adjust_index(&ind, shapevalue, idim) < 0) { return NULL; } data += ind * strides[idim]; } return PyArray_DESCR(self)->f->getitem(data, self); } /* * Sets a single item in the array, based on a single multi-index * array of values, which must be of length PyArray_NDIM(self). * * Returns 0 on success, -1 on failure. */ NPY_NO_EXPORT int PyArray_MultiIndexSetItem(PyArrayObject *self, npy_intp *multi_index, PyObject *obj) { int idim, ndim = PyArray_NDIM(self); char *data = PyArray_DATA(self); npy_intp *shape = PyArray_SHAPE(self); npy_intp *strides = PyArray_STRIDES(self); /* Get the data pointer */ for (idim = 0; idim < ndim; ++idim) { npy_intp shapevalue = shape[idim]; npy_intp ind = multi_index[idim]; if (check_and_adjust_index(&ind, shapevalue, idim) < 0) { return -1; } data += ind * strides[idim]; } return PyArray_DESCR(self)->f->setitem(obj, data, self); } numpy-1.8.2/numpy/core/src/multiarray/number.c0000664000175100017510000006500112370216243022542 0ustar vagrantvagrant00000000000000#define PY_SSIZE_T_CLEAN #include #include "structmember.h" /*#include */ #define NPY_NO_DEPRECATED_API NPY_API_VERSION #define _MULTIARRAYMODULE #include "numpy/arrayobject.h" #include "npy_config.h" #include "npy_pycompat.h" #include "number.h" /************************************************************************* **************** Implement Number Protocol **************************** *************************************************************************/ NPY_NO_EXPORT NumericOps n_ops; /* NB: static objects initialized to zero */ /* * Dictionary can contain any of the numeric operations, by name. * Those not present will not be changed */ /* FIXME - macro contains a return */ #define SET(op) temp = PyDict_GetItemString(dict, #op); \ if (temp != NULL) { \ if (!(PyCallable_Check(temp))) { \ return -1; \ } \ Py_INCREF(temp); \ Py_XDECREF(n_ops.op); \ n_ops.op = temp; \ } /*NUMPY_API *Set internal structure with number functions that all arrays will use */ NPY_NO_EXPORT int PyArray_SetNumericOps(PyObject *dict) { PyObject *temp = NULL; SET(add); SET(subtract); SET(multiply); SET(divide); SET(remainder); SET(power); SET(square); SET(reciprocal); SET(_ones_like); SET(sqrt); SET(negative); SET(absolute); SET(invert); SET(left_shift); SET(right_shift); SET(bitwise_and); SET(bitwise_or); SET(bitwise_xor); SET(less); SET(less_equal); SET(equal); SET(not_equal); SET(greater); SET(greater_equal); SET(floor_divide); SET(true_divide); SET(logical_or); SET(logical_and); SET(floor); SET(ceil); SET(maximum); SET(minimum); SET(rint); SET(conjugate); return 0; } /* FIXME - macro contains goto */ #define GET(op) if (n_ops.op && \ (PyDict_SetItemString(dict, #op, n_ops.op)==-1)) \ goto fail; /*NUMPY_API Get dictionary showing number functions that all arrays will use */ NPY_NO_EXPORT PyObject * PyArray_GetNumericOps(void) { PyObject *dict; if ((dict = PyDict_New())==NULL) return NULL; GET(add); GET(subtract); GET(multiply); GET(divide); GET(remainder); GET(power); GET(square); GET(reciprocal); GET(_ones_like); GET(sqrt); GET(negative); GET(absolute); GET(invert); GET(left_shift); GET(right_shift); GET(bitwise_and); GET(bitwise_or); GET(bitwise_xor); GET(less); GET(less_equal); GET(equal); GET(not_equal); GET(greater); GET(greater_equal); GET(floor_divide); GET(true_divide); GET(logical_or); GET(logical_and); GET(floor); GET(ceil); GET(maximum); GET(minimum); GET(rint); GET(conjugate); return dict; fail: Py_DECREF(dict); return NULL; } static PyObject * _get_keywords(int rtype, PyArrayObject *out) { PyObject *kwds = NULL; if (rtype != NPY_NOTYPE || out != NULL) { kwds = PyDict_New(); if (rtype != NPY_NOTYPE) { PyArray_Descr *descr; descr = PyArray_DescrFromType(rtype); if (descr) { PyDict_SetItemString(kwds, "dtype", (PyObject *)descr); Py_DECREF(descr); } } if (out != NULL) { PyDict_SetItemString(kwds, "out", (PyObject *)out); } } return kwds; } NPY_NO_EXPORT PyObject * PyArray_GenericReduceFunction(PyArrayObject *m1, PyObject *op, int axis, int rtype, PyArrayObject *out) { PyObject *args, *ret = NULL, *meth; PyObject *kwds; if (op == NULL) { Py_INCREF(Py_NotImplemented); return Py_NotImplemented; } args = Py_BuildValue("(Oi)", m1, axis); kwds = _get_keywords(rtype, out); meth = PyObject_GetAttrString(op, "reduce"); if (meth && PyCallable_Check(meth)) { ret = PyObject_Call(meth, args, kwds); } Py_DECREF(args); Py_DECREF(meth); Py_XDECREF(kwds); return ret; } NPY_NO_EXPORT PyObject * PyArray_GenericAccumulateFunction(PyArrayObject *m1, PyObject *op, int axis, int rtype, PyArrayObject *out) { PyObject *args, *ret = NULL, *meth; PyObject *kwds; if (op == NULL) { Py_INCREF(Py_NotImplemented); return Py_NotImplemented; } args = Py_BuildValue("(Oi)", m1, axis); kwds = _get_keywords(rtype, out); meth = PyObject_GetAttrString(op, "accumulate"); if (meth && PyCallable_Check(meth)) { ret = PyObject_Call(meth, args, kwds); } Py_DECREF(args); Py_DECREF(meth); Py_XDECREF(kwds); return ret; } NPY_NO_EXPORT PyObject * PyArray_GenericBinaryFunction(PyArrayObject *m1, PyObject *m2, PyObject *op) { if (op == NULL) { Py_INCREF(Py_NotImplemented); return Py_NotImplemented; } if (!PyArray_Check(m2)) { /* * Catch priority inversion and punt, but only if it's guaranteed * that we were called through m1 and the other guy is not an array * at all. Note that some arrays need to pass through here even * with priorities inverted, for example: float(17) * np.matrix(...) * * See also: * - https://github.com/numpy/numpy/issues/3502 * - https://github.com/numpy/numpy/issues/3503 */ double m1_prio = PyArray_GetPriority(m1, NPY_SCALAR_PRIORITY); double m2_prio = PyArray_GetPriority(m2, NPY_SCALAR_PRIORITY); if (m1_prio < m2_prio) { Py_INCREF(Py_NotImplemented); return Py_NotImplemented; } } return PyObject_CallFunction(op, "OO", m1, m2); } NPY_NO_EXPORT PyObject * PyArray_GenericUnaryFunction(PyArrayObject *m1, PyObject *op) { if (op == NULL) { Py_INCREF(Py_NotImplemented); return Py_NotImplemented; } return PyObject_CallFunction(op, "(O)", m1); } static PyObject * PyArray_GenericInplaceBinaryFunction(PyArrayObject *m1, PyObject *m2, PyObject *op) { if (op == NULL) { Py_INCREF(Py_NotImplemented); return Py_NotImplemented; } return PyObject_CallFunction(op, "OOO", m1, m2, m1); } static PyObject * PyArray_GenericInplaceUnaryFunction(PyArrayObject *m1, PyObject *op) { if (op == NULL) { Py_INCREF(Py_NotImplemented); return Py_NotImplemented; } return PyObject_CallFunction(op, "OO", m1, m1); } static PyObject * array_add(PyArrayObject *m1, PyObject *m2) { return PyArray_GenericBinaryFunction(m1, m2, n_ops.add); } static PyObject * array_subtract(PyArrayObject *m1, PyObject *m2) { return PyArray_GenericBinaryFunction(m1, m2, n_ops.subtract); } static PyObject * array_multiply(PyArrayObject *m1, PyObject *m2) { return PyArray_GenericBinaryFunction(m1, m2, n_ops.multiply); } #if !defined(NPY_PY3K) static PyObject * array_divide(PyArrayObject *m1, PyObject *m2) { return PyArray_GenericBinaryFunction(m1, m2, n_ops.divide); } #endif static PyObject * array_remainder(PyArrayObject *m1, PyObject *m2) { return PyArray_GenericBinaryFunction(m1, m2, n_ops.remainder); } /* Determine if object is a scalar and if so, convert the object * to a double and place it in the out_exponent argument * and return the "scalar kind" as a result. If the object is * not a scalar (or if there are other error conditions) * return NPY_NOSCALAR, and out_exponent is undefined. */ static NPY_SCALARKIND is_scalar_with_conversion(PyObject *o2, double* out_exponent) { PyObject *temp; const int optimize_fpexps = 1; if (PyInt_Check(o2)) { *out_exponent = (double)PyInt_AsLong(o2); return NPY_INTPOS_SCALAR; } if (optimize_fpexps && PyFloat_Check(o2)) { *out_exponent = PyFloat_AsDouble(o2); return NPY_FLOAT_SCALAR; } if (PyArray_Check(o2)) { if ((PyArray_NDIM(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_ISINTEGER((PyArrayObject *)o2)) { return NPY_INTPOS_SCALAR; } else { /* ISFLOAT */ return NPY_FLOAT_SCALAR; } } } 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) { if (PyErr_Occurred()) { PyErr_Clear(); } return NPY_NOSCALAR; } val = PyInt_AsSsize_t(value); if (val == -1 && PyErr_Occurred()) { PyErr_Clear(); return NPY_NOSCALAR; } *out_exponent = (double) val; return NPY_INTPOS_SCALAR; } return NPY_NOSCALAR; } /* optimize float array or complex array to a scalar power */ static PyObject * fast_scalar_power(PyArrayObject *a1, PyObject *o2, int inplace) { double exponent; NPY_SCALARKIND kind; /* NPY_NOSCALAR is not scalar */ if (PyArray_Check(a1) && ((kind=is_scalar_with_conversion(o2, &exponent))>0)) { PyObject *fastop = NULL; if (PyArray_ISFLOAT(a1) || PyArray_ISCOMPLEX(a1)) { if (exponent == 1.0) { /* we have to do this one special, as the "copy" method of array objects isn't set up early enough to be added by PyArray_SetNumericOps. */ if (inplace) { Py_INCREF(a1); return (PyObject *)a1; } else { return PyArray_Copy(a1); } } else if (exponent == -1.0) { fastop = n_ops.reciprocal; } else if (exponent == 0.0) { fastop = n_ops._ones_like; } else if (exponent == 0.5) { fastop = n_ops.sqrt; } else if (exponent == 2.0) { fastop = n_ops.square; } else { return NULL; } if (inplace) { return PyArray_GenericInplaceUnaryFunction(a1, fastop); } else { return PyArray_GenericUnaryFunction(a1, fastop); } } /* Because this is called with all arrays, we need to * change the output if the kind of the scalar is different * than that of the input and inplace is not on --- * (thus, the input should be up-cast) */ else if (exponent == 2.0) { fastop = n_ops.multiply; if (inplace) { return PyArray_GenericInplaceBinaryFunction (a1, (PyObject *)a1, fastop); } else { PyArray_Descr *dtype = NULL; PyObject *res; /* We only special-case the FLOAT_SCALAR and integer types */ if (kind == NPY_FLOAT_SCALAR && PyArray_ISINTEGER(a1)) { dtype = PyArray_DescrFromType(NPY_DOUBLE); a1 = (PyArrayObject *)PyArray_CastToType(a1, dtype, PyArray_ISFORTRAN(a1)); if (a1 == NULL) { return NULL; } } else { Py_INCREF(a1); } res = PyArray_GenericBinaryFunction(a1, (PyObject *)a1, fastop); Py_DECREF(a1); return res; } } } return NULL; } static PyObject * array_power(PyArrayObject *a1, PyObject *o2, PyObject *NPY_UNUSED(modulo)) { /* modulo is ignored! */ PyObject *value; value = fast_scalar_power(a1, o2, 0); if (!value) { value = PyArray_GenericBinaryFunction(a1, o2, n_ops.power); } return value; } static PyObject * array_negative(PyArrayObject *m1) { return PyArray_GenericUnaryFunction(m1, n_ops.negative); } static PyObject * array_absolute(PyArrayObject *m1) { return PyArray_GenericUnaryFunction(m1, n_ops.absolute); } static PyObject * array_invert(PyArrayObject *m1) { return PyArray_GenericUnaryFunction(m1, n_ops.invert); } static PyObject * array_left_shift(PyArrayObject *m1, PyObject *m2) { return PyArray_GenericBinaryFunction(m1, m2, n_ops.left_shift); } static PyObject * array_right_shift(PyArrayObject *m1, PyObject *m2) { return PyArray_GenericBinaryFunction(m1, m2, n_ops.right_shift); } static PyObject * array_bitwise_and(PyArrayObject *m1, PyObject *m2) { return PyArray_GenericBinaryFunction(m1, m2, n_ops.bitwise_and); } static PyObject * array_bitwise_or(PyArrayObject *m1, PyObject *m2) { return PyArray_GenericBinaryFunction(m1, m2, n_ops.bitwise_or); } static PyObject * array_bitwise_xor(PyArrayObject *m1, PyObject *m2) { return PyArray_GenericBinaryFunction(m1, m2, n_ops.bitwise_xor); } static PyObject * array_inplace_add(PyArrayObject *m1, PyObject *m2) { return PyArray_GenericInplaceBinaryFunction(m1, m2, n_ops.add); } static PyObject * array_inplace_subtract(PyArrayObject *m1, PyObject *m2) { return PyArray_GenericInplaceBinaryFunction(m1, m2, n_ops.subtract); } static PyObject * array_inplace_multiply(PyArrayObject *m1, PyObject *m2) { return PyArray_GenericInplaceBinaryFunction(m1, m2, n_ops.multiply); } #if !defined(NPY_PY3K) static PyObject * array_inplace_divide(PyArrayObject *m1, PyObject *m2) { return PyArray_GenericInplaceBinaryFunction(m1, m2, n_ops.divide); } #endif static PyObject * array_inplace_remainder(PyArrayObject *m1, PyObject *m2) { return PyArray_GenericInplaceBinaryFunction(m1, m2, n_ops.remainder); } static PyObject * array_inplace_power(PyArrayObject *a1, PyObject *o2, PyObject *NPY_UNUSED(modulo)) { /* modulo is ignored! */ PyObject *value; value = fast_scalar_power(a1, o2, 1); if (!value) { value = PyArray_GenericInplaceBinaryFunction(a1, o2, n_ops.power); } return value; } static PyObject * array_inplace_left_shift(PyArrayObject *m1, PyObject *m2) { return PyArray_GenericInplaceBinaryFunction(m1, m2, n_ops.left_shift); } static PyObject * array_inplace_right_shift(PyArrayObject *m1, PyObject *m2) { return PyArray_GenericInplaceBinaryFunction(m1, m2, n_ops.right_shift); } static PyObject * array_inplace_bitwise_and(PyArrayObject *m1, PyObject *m2) { return PyArray_GenericInplaceBinaryFunction(m1, m2, n_ops.bitwise_and); } static PyObject * array_inplace_bitwise_or(PyArrayObject *m1, PyObject *m2) { return PyArray_GenericInplaceBinaryFunction(m1, m2, n_ops.bitwise_or); } static PyObject * array_inplace_bitwise_xor(PyArrayObject *m1, PyObject *m2) { return PyArray_GenericInplaceBinaryFunction(m1, m2, n_ops.bitwise_xor); } static PyObject * array_floor_divide(PyArrayObject *m1, PyObject *m2) { return PyArray_GenericBinaryFunction(m1, m2, n_ops.floor_divide); } static PyObject * array_true_divide(PyArrayObject *m1, PyObject *m2) { return PyArray_GenericBinaryFunction(m1, m2, n_ops.true_divide); } static PyObject * array_inplace_floor_divide(PyArrayObject *m1, PyObject *m2) { return PyArray_GenericInplaceBinaryFunction(m1, m2, n_ops.floor_divide); } static PyObject * array_inplace_true_divide(PyArrayObject *m1, PyObject *m2) { return PyArray_GenericInplaceBinaryFunction(m1, m2, n_ops.true_divide); } static int _array_nonzero(PyArrayObject *mp) { npy_intp n; n = PyArray_SIZE(mp); if (n == 1) { return PyArray_DESCR(mp)->f->nonzero(PyArray_DATA(mp), mp); } else if (n == 0) { return 0; } else { PyErr_SetString(PyExc_ValueError, "The truth value of an array " \ "with more than one element is ambiguous. " \ "Use a.any() or a.all()"); return -1; } } static PyObject * array_divmod(PyArrayObject *op1, PyObject *op2) { PyObject *divp, *modp, *result; divp = array_floor_divide(op1, op2); if (divp == NULL) { return NULL; } else if(divp == Py_NotImplemented) { return divp; } modp = array_remainder(op1, op2); if (modp == NULL) { Py_DECREF(divp); return NULL; } else if(modp == Py_NotImplemented) { Py_DECREF(divp); return modp; } result = Py_BuildValue("OO", divp, modp); Py_DECREF(divp); Py_DECREF(modp); return result; } NPY_NO_EXPORT PyObject * array_int(PyArrayObject *v) { PyObject *pv, *pv2; if (PyArray_SIZE(v) != 1) { PyErr_SetString(PyExc_TypeError, "only length-1 arrays can be"\ " converted to Python scalars"); return NULL; } pv = PyArray_DESCR(v)->f->getitem(PyArray_DATA(v), v); if (pv == NULL) { return NULL; } if (Py_TYPE(pv)->tp_as_number == 0) { PyErr_SetString(PyExc_TypeError, "cannot convert to an int; "\ "scalar object is not a number"); Py_DECREF(pv); return NULL; } if (Py_TYPE(pv)->tp_as_number->nb_int == 0) { PyErr_SetString(PyExc_TypeError, "don't know how to convert "\ "scalar number to int"); Py_DECREF(pv); return NULL; } /* * If we still got an array which can hold references, stop * because it could point back at 'v'. */ if (PyArray_Check(pv) && PyDataType_REFCHK(PyArray_DESCR((PyArrayObject *)pv))) { PyErr_SetString(PyExc_TypeError, "object array may be self-referencing"); return NULL; } pv2 = Py_TYPE(pv)->tp_as_number->nb_int(pv); Py_DECREF(pv); return pv2; } static PyObject * array_float(PyArrayObject *v) { PyObject *pv, *pv2; if (PyArray_SIZE(v) != 1) { PyErr_SetString(PyExc_TypeError, "only length-1 arrays can "\ "be converted to Python scalars"); return NULL; } pv = PyArray_DESCR(v)->f->getitem(PyArray_DATA(v), v); if (pv == NULL) { return NULL; } if (Py_TYPE(pv)->tp_as_number == 0) { PyErr_SetString(PyExc_TypeError, "cannot convert to a "\ "float; scalar object is not a number"); Py_DECREF(pv); return NULL; } if (Py_TYPE(pv)->tp_as_number->nb_float == 0) { PyErr_SetString(PyExc_TypeError, "don't know how to convert "\ "scalar number to float"); Py_DECREF(pv); return NULL; } /* * If we still got an array which can hold references, stop * because it could point back at 'v'. */ if (PyArray_Check(pv) && PyDataType_REFCHK(PyArray_DESCR((PyArrayObject *)pv))) { PyErr_SetString(PyExc_TypeError, "object array may be self-referencing"); return NULL; } pv2 = Py_TYPE(pv)->tp_as_number->nb_float(pv); Py_DECREF(pv); return pv2; } #if !defined(NPY_PY3K) static PyObject * array_long(PyArrayObject *v) { PyObject *pv, *pv2; if (PyArray_SIZE(v) != 1) { PyErr_SetString(PyExc_TypeError, "only length-1 arrays can "\ "be converted to Python scalars"); return NULL; } pv = PyArray_DESCR(v)->f->getitem(PyArray_DATA(v), v); if (Py_TYPE(pv)->tp_as_number == 0) { PyErr_SetString(PyExc_TypeError, "cannot convert to an int; "\ "scalar object is not a number"); return NULL; } if (Py_TYPE(pv)->tp_as_number->nb_long == 0) { PyErr_SetString(PyExc_TypeError, "don't know how to convert "\ "scalar number to long"); return NULL; } /* * If we still got an array which can hold references, stop * because it could point back at 'v'. */ if (PyArray_Check(pv) && PyDataType_REFCHK(PyArray_DESCR((PyArrayObject *)pv))) { PyErr_SetString(PyExc_TypeError, "object array may be self-referencing"); return NULL; } pv2 = Py_TYPE(pv)->tp_as_number->nb_long(pv); Py_DECREF(pv); return pv2; } static PyObject * array_oct(PyArrayObject *v) { PyObject *pv, *pv2; if (PyArray_SIZE(v) != 1) { PyErr_SetString(PyExc_TypeError, "only length-1 arrays can "\ "be converted to Python scalars"); return NULL; } pv = PyArray_DESCR(v)->f->getitem(PyArray_DATA(v), v); if (Py_TYPE(pv)->tp_as_number == 0) { PyErr_SetString(PyExc_TypeError, "cannot convert to an int; "\ "scalar object is not a number"); return NULL; } if (Py_TYPE(pv)->tp_as_number->nb_oct == 0) { PyErr_SetString(PyExc_TypeError, "don't know how to convert "\ "scalar number to oct"); return NULL; } /* * If we still got an array which can hold references, stop * because it could point back at 'v'. */ if (PyArray_Check(pv) && PyDataType_REFCHK(PyArray_DESCR((PyArrayObject *)pv))) { PyErr_SetString(PyExc_TypeError, "object array may be self-referencing"); return NULL; } pv2 = Py_TYPE(pv)->tp_as_number->nb_oct(pv); Py_DECREF(pv); return pv2; } static PyObject * array_hex(PyArrayObject *v) { PyObject *pv, *pv2; if (PyArray_SIZE(v) != 1) { PyErr_SetString(PyExc_TypeError, "only length-1 arrays can "\ "be converted to Python scalars"); return NULL; } pv = PyArray_DESCR(v)->f->getitem(PyArray_DATA(v), v); if (Py_TYPE(pv)->tp_as_number == 0) { PyErr_SetString(PyExc_TypeError, "cannot convert to an int; "\ "scalar object is not a number"); return NULL; } if (Py_TYPE(pv)->tp_as_number->nb_hex == 0) { PyErr_SetString(PyExc_TypeError, "don't know how to convert "\ "scalar number to hex"); return NULL; } /* * If we still got an array which can hold references, stop * because it could point back at 'v'. */ if (PyArray_Check(pv) && PyDataType_REFCHK(PyArray_DESCR((PyArrayObject *)pv))) { PyErr_SetString(PyExc_TypeError, "object array may be self-referencing"); return NULL; } pv2 = Py_TYPE(pv)->tp_as_number->nb_hex(pv); Py_DECREF(pv); return pv2; } #endif static PyObject * _array_copy_nice(PyArrayObject *self) { return PyArray_Return((PyArrayObject *) PyArray_Copy(self)); } static PyObject * array_index(PyArrayObject *v) { if (!PyArray_ISINTEGER(v) || PyArray_SIZE(v) != 1) { PyErr_SetString(PyExc_TypeError, "only integer arrays with " \ "one element can be converted to an index"); return NULL; } if (PyArray_NDIM(v) != 0) { if (DEPRECATE("converting an array with ndim > 0 to an index" " will result in an error in the future") < 0) { return NULL; } } return PyArray_DESCR(v)->f->getitem(PyArray_DATA(v), v); } NPY_NO_EXPORT PyNumberMethods array_as_number = { (binaryfunc)array_add, /*nb_add*/ (binaryfunc)array_subtract, /*nb_subtract*/ (binaryfunc)array_multiply, /*nb_multiply*/ #if !defined(NPY_PY3K) (binaryfunc)array_divide, /*nb_divide*/ #endif (binaryfunc)array_remainder, /*nb_remainder*/ (binaryfunc)array_divmod, /*nb_divmod*/ (ternaryfunc)array_power, /*nb_power*/ (unaryfunc)array_negative, /*nb_neg*/ (unaryfunc)_array_copy_nice, /*nb_pos*/ (unaryfunc)array_absolute, /*(unaryfunc)array_abs,*/ (inquiry)_array_nonzero, /*nb_nonzero*/ (unaryfunc)array_invert, /*nb_invert*/ (binaryfunc)array_left_shift, /*nb_lshift*/ (binaryfunc)array_right_shift, /*nb_rshift*/ (binaryfunc)array_bitwise_and, /*nb_and*/ (binaryfunc)array_bitwise_xor, /*nb_xor*/ (binaryfunc)array_bitwise_or, /*nb_or*/ #if !defined(NPY_PY3K) 0, /*nb_coerce*/ #endif (unaryfunc)array_int, /*nb_int*/ #if defined(NPY_PY3K) 0, /*nb_reserved*/ #else (unaryfunc)array_long, /*nb_long*/ #endif (unaryfunc)array_float, /*nb_float*/ #if !defined(NPY_PY3K) (unaryfunc)array_oct, /*nb_oct*/ (unaryfunc)array_hex, /*nb_hex*/ #endif /* * This code adds augmented assignment functionality * that was made available in Python 2.0 */ (binaryfunc)array_inplace_add, /*inplace_add*/ (binaryfunc)array_inplace_subtract, /*inplace_subtract*/ (binaryfunc)array_inplace_multiply, /*inplace_multiply*/ #if !defined(NPY_PY3K) (binaryfunc)array_inplace_divide, /*inplace_divide*/ #endif (binaryfunc)array_inplace_remainder, /*inplace_remainder*/ (ternaryfunc)array_inplace_power, /*inplace_power*/ (binaryfunc)array_inplace_left_shift, /*inplace_lshift*/ (binaryfunc)array_inplace_right_shift, /*inplace_rshift*/ (binaryfunc)array_inplace_bitwise_and, /*inplace_and*/ (binaryfunc)array_inplace_bitwise_xor, /*inplace_xor*/ (binaryfunc)array_inplace_bitwise_or, /*inplace_or*/ (binaryfunc)array_floor_divide, /*nb_floor_divide*/ (binaryfunc)array_true_divide, /*nb_true_divide*/ (binaryfunc)array_inplace_floor_divide, /*nb_inplace_floor_divide*/ (binaryfunc)array_inplace_true_divide, /*nb_inplace_true_divide*/ (unaryfunc)array_index, /* nb_index */ }; numpy-1.8.2/numpy/core/src/multiarray/scalarapi.c0000664000175100017510000005744212370216243023223 0ustar vagrantvagrant00000000000000#define PY_SSIZE_T_CLEAN #include #include "structmember.h" #define NPY_NO_DEPRECATED_API NPY_API_VERSION #define _MULTIARRAYMODULE #include "numpy/arrayobject.h" #include "numpy/arrayscalars.h" #include "numpy/npy_math.h" #include "npy_config.h" #include "npy_pycompat.h" #include "ctors.h" #include "descriptor.h" #include "scalartypes.h" #include "common.h" static PyArray_Descr * _descr_from_subtype(PyObject *type) { PyObject *mro; mro = ((PyTypeObject *)type)->tp_mro; if (PyTuple_GET_SIZE(mro) < 2) { return PyArray_DescrFromType(NPY_OBJECT); } return PyArray_DescrFromTypeObject(PyTuple_GET_ITEM(mro, 1)); } NPY_NO_EXPORT void * scalar_value(PyObject *scalar, PyArray_Descr *descr) { int type_num; int align; npy_intp memloc; if (descr == NULL) { descr = PyArray_DescrFromScalar(scalar); type_num = descr->type_num; Py_DECREF(descr); } else { type_num = descr->type_num; } switch (type_num) { #define CASE(ut,lt) case NPY_##ut: return &(((Py##lt##ScalarObject *)scalar)->obval) CASE(BOOL, Bool); CASE(BYTE, Byte); CASE(UBYTE, UByte); CASE(SHORT, Short); CASE(USHORT, UShort); CASE(INT, Int); CASE(UINT, UInt); CASE(LONG, Long); CASE(ULONG, ULong); CASE(LONGLONG, LongLong); CASE(ULONGLONG, ULongLong); CASE(HALF, Half); CASE(FLOAT, Float); CASE(DOUBLE, Double); CASE(LONGDOUBLE, LongDouble); CASE(CFLOAT, CFloat); CASE(CDOUBLE, CDouble); CASE(CLONGDOUBLE, CLongDouble); CASE(OBJECT, Object); CASE(DATETIME, Datetime); CASE(TIMEDELTA, Timedelta); #undef CASE case NPY_STRING: return (void *)PyString_AS_STRING(scalar); case NPY_UNICODE: return (void *)PyUnicode_AS_DATA(scalar); case NPY_VOID: return ((PyVoidScalarObject *)scalar)->obval; } /* * Must be a user-defined type --- check to see which * scalar it inherits from. */ #define _CHK(cls) (PyObject_IsInstance(scalar, \ (PyObject *)&Py##cls##ArrType_Type)) #define _OBJ(lt) &(((Py##lt##ScalarObject *)scalar)->obval) #define _IFCASE(cls) if _CHK(cls) return _OBJ(cls) if _CHK(Number) { if _CHK(Integer) { if _CHK(SignedInteger) { _IFCASE(Byte); _IFCASE(Short); _IFCASE(Int); _IFCASE(Long); _IFCASE(LongLong); _IFCASE(Timedelta); } else { /* Unsigned Integer */ _IFCASE(UByte); _IFCASE(UShort); _IFCASE(UInt); _IFCASE(ULong); _IFCASE(ULongLong); } } else { /* Inexact */ if _CHK(Floating) { _IFCASE(Half); _IFCASE(Float); _IFCASE(Double); _IFCASE(LongDouble); } else { /*ComplexFloating */ _IFCASE(CFloat); _IFCASE(CDouble); _IFCASE(CLongDouble); } } } else if (_CHK(Bool)) { return _OBJ(Bool); } else if (_CHK(Datetime)) { return _OBJ(Datetime); } else if (_CHK(Flexible)) { if (_CHK(String)) { return (void *)PyString_AS_STRING(scalar); } if (_CHK(Unicode)) { return (void *)PyUnicode_AS_DATA(scalar); } if (_CHK(Void)) { return ((PyVoidScalarObject *)scalar)->obval; } } else { _IFCASE(Object); } /* * Use the alignment flag to figure out where the data begins * after a PyObject_HEAD */ memloc = (npy_intp)scalar; memloc += sizeof(PyObject); /* now round-up to the nearest alignment value */ align = descr->alignment; if (align > 1) { memloc = ((memloc + align - 1)/align)*align; } return (void *)memloc; #undef _IFCASE #undef _OBJ #undef _CHK } /*NUMPY_API * Convert to c-type * * no error checking is performed -- ctypeptr must be same type as scalar * in case of flexible type, the data is not copied * into ctypeptr which is expected to be a pointer to pointer */ NPY_NO_EXPORT void PyArray_ScalarAsCtype(PyObject *scalar, void *ctypeptr) { PyArray_Descr *typecode; void *newptr; typecode = PyArray_DescrFromScalar(scalar); newptr = scalar_value(scalar, typecode); if (PyTypeNum_ISEXTENDED(typecode->type_num)) { void **ct = (void **)ctypeptr; *ct = newptr; } else { memcpy(ctypeptr, newptr, typecode->elsize); } Py_DECREF(typecode); return; } /*NUMPY_API * Cast Scalar to c-type * * The output buffer must be large-enough to receive the value * Even for flexible types which is different from ScalarAsCtype * where only a reference for flexible types is returned * * This may not work right on narrow builds for NumPy unicode scalars. */ NPY_NO_EXPORT int PyArray_CastScalarToCtype(PyObject *scalar, void *ctypeptr, PyArray_Descr *outcode) { PyArray_Descr* descr; PyArray_VectorUnaryFunc* castfunc; descr = PyArray_DescrFromScalar(scalar); castfunc = PyArray_GetCastFunc(descr, outcode->type_num); if (castfunc == NULL) { return -1; } if (PyTypeNum_ISEXTENDED(descr->type_num) || PyTypeNum_ISEXTENDED(outcode->type_num)) { PyArrayObject *ain, *aout; ain = (PyArrayObject *)PyArray_FromScalar(scalar, NULL); if (ain == NULL) { Py_DECREF(descr); return -1; } aout = (PyArrayObject *) PyArray_NewFromDescr(&PyArray_Type, outcode, 0, NULL, NULL, ctypeptr, NPY_ARRAY_CARRAY, NULL); if (aout == NULL) { Py_DECREF(ain); return -1; } castfunc(PyArray_DATA(ain), PyArray_DATA(aout), 1, ain, aout); Py_DECREF(ain); Py_DECREF(aout); } else { castfunc(scalar_value(scalar, descr), ctypeptr, 1, NULL, NULL); } Py_DECREF(descr); return 0; } /*NUMPY_API * Cast Scalar to c-type */ NPY_NO_EXPORT int PyArray_CastScalarDirect(PyObject *scalar, PyArray_Descr *indescr, void *ctypeptr, int outtype) { PyArray_VectorUnaryFunc* castfunc; void *ptr; castfunc = PyArray_GetCastFunc(indescr, outtype); if (castfunc == NULL) { return -1; } ptr = scalar_value(scalar, indescr); castfunc(ptr, ctypeptr, 1, NULL, NULL); return 0; } /*NUMPY_API * Get 0-dim array from scalar * * 0-dim array from array-scalar object * always contains a copy of the data * unless outcode is NULL, it is of void type and the referrer does * not own it either. * * steals reference to outcode */ NPY_NO_EXPORT PyObject * PyArray_FromScalar(PyObject *scalar, PyArray_Descr *outcode) { PyArray_Descr *typecode; PyArrayObject *r; char *memptr; PyObject *ret; /* 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) { r = (PyArrayObject *)PyArray_NewFromDescr(&PyArray_Type, typecode, 0, NULL, NULL, ((PyVoidScalarObject *)scalar)->obval, ((PyVoidScalarObject *)scalar)->flags, NULL); if (r == NULL) { return NULL; } Py_INCREF(scalar); if (PyArray_SetBaseObject(r, (PyObject *)scalar) < 0) { Py_DECREF(r); return NULL; } return (PyObject *)r; } /* Need to INCREF typecode because PyArray_NewFromDescr steals a * reference below and we still need to access typecode afterwards. */ Py_INCREF(typecode); r = (PyArrayObject *)PyArray_NewFromDescr(&PyArray_Type, typecode, 0, NULL, NULL, NULL, 0, NULL); if (r==NULL) { Py_DECREF(typecode); Py_XDECREF(outcode); return NULL; } if (PyDataType_FLAGCHK(typecode, NPY_USE_SETITEM)) { if (typecode->f->setitem(scalar, PyArray_DATA(r), r) < 0) { Py_DECREF(typecode); Py_XDECREF(outcode); Py_DECREF(r); return NULL; } goto finish; } memptr = scalar_value(scalar, typecode); #ifndef Py_UNICODE_WIDE if (typecode->type_num == NPY_UNICODE) { PyUCS2Buffer_AsUCS4((Py_UNICODE *)memptr, (npy_ucs4 *)PyArray_DATA(r), PyUnicode_GET_SIZE(scalar), PyArray_ITEMSIZE(r) >> 2); } else #endif { memcpy(PyArray_DATA(r), memptr, PyArray_ITEMSIZE(r)); if (PyDataType_FLAGCHK(typecode, NPY_ITEM_HASOBJECT)) { /* Need to INCREF just the PyObject portion */ PyArray_Item_INCREF(memptr, typecode); } } finish: if (outcode == NULL) { Py_DECREF(typecode); return (PyObject *)r; } if (PyArray_EquivTypes(outcode, typecode)) { if (!PyTypeNum_ISEXTENDED(typecode->type_num) || (outcode->elsize == typecode->elsize)) { Py_DECREF(typecode); Py_DECREF(outcode); return (PyObject *)r; } } /* cast if necessary to desired output typecode */ ret = PyArray_CastToType((PyArrayObject *)r, outcode, 0); Py_DECREF(typecode); Py_DECREF(r); return ret; } /*NUMPY_API * Get an Array Scalar From a Python Object * * Returns NULL if unsuccessful but error is only set if another error occurred. * Currently only Numeric-like object supported. */ NPY_NO_EXPORT PyObject * PyArray_ScalarFromObject(PyObject *object) { PyObject *ret=NULL; if (PyArray_IsZeroDim(object)) { return PyArray_ToScalar(PyArray_DATA((PyArrayObject *)object), (PyArrayObject *)object); } /* * Booleans in Python are implemented as a subclass of integers, * so PyBool_Check must be called before PyInt_Check. */ if (PyBool_Check(object)) { if (object == Py_True) { PyArrayScalar_RETURN_TRUE; } else { PyArrayScalar_RETURN_FALSE; } } else if (PyInt_Check(object)) { ret = PyArrayScalar_New(Long); if (ret == NULL) { return NULL; } PyArrayScalar_VAL(ret, Long) = PyInt_AS_LONG(object); } else if (PyFloat_Check(object)) { ret = PyArrayScalar_New(Double); if (ret == NULL) { return NULL; } PyArrayScalar_VAL(ret, Double) = PyFloat_AS_DOUBLE(object); } else if (PyComplex_Check(object)) { ret = PyArrayScalar_New(CDouble); if (ret == NULL) { return NULL; } PyArrayScalar_VAL(ret, CDouble).real = PyComplex_RealAsDouble(object); PyArrayScalar_VAL(ret, CDouble).imag = PyComplex_ImagAsDouble(object); } else if (PyLong_Check(object)) { npy_longlong val; val = PyLong_AsLongLong(object); if (val==-1 && PyErr_Occurred()) { PyErr_Clear(); return NULL; } ret = PyArrayScalar_New(LongLong); if (ret == NULL) { return NULL; } PyArrayScalar_VAL(ret, LongLong) = val; } return ret; } /*New reference */ /*NUMPY_API */ NPY_NO_EXPORT PyArray_Descr * PyArray_DescrFromTypeObject(PyObject *type) { int typenum; PyArray_Descr *new, *conv = NULL; /* if it's a builtin type, then use the typenumber */ typenum = _typenum_fromtypeobj(type,1); if (typenum != NPY_NOTYPE) { new = PyArray_DescrFromType(typenum); return new; } /* Check the generic types */ if ((type == (PyObject *) &PyNumberArrType_Type) || (type == (PyObject *) &PyInexactArrType_Type) || (type == (PyObject *) &PyFloatingArrType_Type)) { typenum = NPY_DOUBLE; } else if (type == (PyObject *)&PyComplexFloatingArrType_Type) { typenum = NPY_CDOUBLE; } else if ((type == (PyObject *)&PyIntegerArrType_Type) || (type == (PyObject *)&PySignedIntegerArrType_Type)) { typenum = NPY_LONG; } else if (type == (PyObject *) &PyUnsignedIntegerArrType_Type) { typenum = NPY_ULONG; } else if (type == (PyObject *) &PyCharacterArrType_Type) { typenum = NPY_STRING; } else if ((type == (PyObject *) &PyGenericArrType_Type) || (type == (PyObject *) &PyFlexibleArrType_Type)) { typenum = NPY_VOID; } if (typenum != NPY_NOTYPE) { return PyArray_DescrFromType(typenum); } /* * Otherwise --- type is a sub-type of an array scalar * not corresponding to a registered data-type object. */ /* Do special thing for VOID sub-types */ if (PyType_IsSubtype((PyTypeObject *)type, &PyVoidArrType_Type)) { new = PyArray_DescrNewFromType(NPY_VOID); conv = _arraydescr_fromobj(type); if (conv) { new->fields = conv->fields; Py_INCREF(new->fields); new->names = conv->names; Py_INCREF(new->names); new->elsize = conv->elsize; new->subarray = conv->subarray; conv->subarray = NULL; Py_DECREF(conv); } Py_XDECREF(new->typeobj); new->typeobj = (PyTypeObject *)type; Py_INCREF(type); return new; } return _descr_from_subtype(type); } /*NUMPY_API * Return the tuple of ordered field names from a dictionary. */ NPY_NO_EXPORT PyObject * PyArray_FieldNames(PyObject *fields) { PyObject *tup; PyObject *ret; PyObject *_numpy_internal; if (!PyDict_Check(fields)) { PyErr_SetString(PyExc_TypeError, "Fields must be a dictionary"); return NULL; } _numpy_internal = PyImport_ImportModule("numpy.core._internal"); if (_numpy_internal == NULL) { return NULL; } tup = PyObject_CallMethod(_numpy_internal, "_makenames_list", "OO", fields, Py_False); Py_DECREF(_numpy_internal); if (tup == NULL) { return NULL; } ret = PyTuple_GET_ITEM(tup, 0); ret = PySequence_Tuple(ret); Py_DECREF(tup); return ret; } /*NUMPY_API * Return descr object from array scalar. * * New reference */ NPY_NO_EXPORT PyArray_Descr * PyArray_DescrFromScalar(PyObject *sc) { int type_num; PyArray_Descr *descr; if (PyArray_IsScalar(sc, Void)) { descr = ((PyVoidScalarObject *)sc)->descr; Py_INCREF(descr); return descr; } if (PyArray_IsScalar(sc, Datetime) || PyArray_IsScalar(sc, Timedelta)) { PyArray_DatetimeMetaData *dt_data; if (PyArray_IsScalar(sc, Datetime)) { descr = PyArray_DescrNewFromType(NPY_DATETIME); } else { /* 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)); return descr; } descr = PyArray_DescrFromTypeObject((PyObject *)Py_TYPE(sc)); if (descr->elsize == 0) { PyArray_DESCR_REPLACE(descr); type_num = descr->type_num; if (type_num == NPY_STRING) { descr->elsize = PyString_GET_SIZE(sc); } else if (type_num == NPY_UNICODE) { descr->elsize = PyUnicode_GET_DATA_SIZE(sc); #ifndef Py_UNICODE_WIDE descr->elsize <<= 1; #endif } else { PyArray_Descr *dtype; dtype = (PyArray_Descr *)PyObject_GetAttrString(sc, "dtype"); if (dtype != NULL) { descr->elsize = dtype->elsize; descr->fields = dtype->fields; Py_XINCREF(dtype->fields); descr->names = dtype->names; Py_XINCREF(dtype->names); Py_DECREF(dtype); } PyErr_Clear(); } } return descr; } /*NUMPY_API * Get a typeobject from a type-number -- can return NULL. * * New reference */ NPY_NO_EXPORT PyObject * PyArray_TypeObjectFromType(int type) { PyArray_Descr *descr; PyObject *obj; descr = PyArray_DescrFromType(type); if (descr == NULL) { return NULL; } obj = (PyObject *)descr->typeobj; Py_XINCREF(obj); Py_DECREF(descr); return obj; } /* Does nothing with descr (cannot be NULL) */ /*NUMPY_API Get scalar-equivalent to a region of memory described by a descriptor. */ NPY_NO_EXPORT PyObject * PyArray_Scalar(void *data, PyArray_Descr *descr, PyObject *base) { PyTypeObject *type; PyObject *obj; void *destptr; PyArray_CopySwapFunc *copyswap; int type_num; int itemsize; int swap; type_num = descr->type_num; if (type_num == NPY_BOOL) { PyArrayScalar_RETURN_BOOL_FROM_LONG(*(npy_bool*)data); } else if (PyDataType_FLAGCHK(descr, NPY_USE_GETITEM)) { return descr->f->getitem(data, base); } itemsize = descr->elsize; copyswap = descr->f->copyswap; type = descr->typeobj; swap = !PyArray_ISNBO(descr->byteorder); if PyTypeNum_ISSTRING(type_num) { /* Eliminate NULL bytes */ char *dptr = data; dptr += itemsize - 1; while(itemsize && *dptr-- == 0) { itemsize--; } if (type_num == NPY_UNICODE && itemsize) { /* * make sure itemsize is a multiple of 4 * so round up to nearest multiple */ itemsize = (((itemsize - 1) >> 2) + 1) << 2; } } #if PY_VERSION_HEX >= 0x03030000 if (type_num == NPY_UNICODE) { PyObject *u, *args; int byteorder; #if NPY_BYTE_ORDER == NPY_LITTLE_ENDIAN byteorder = -1; #elif NPY_BYTE_ORDER == NPY_BIG_ENDIAN byteorder = +1; #else #error Endianness undefined ? #endif if (swap) byteorder *= -1; u = PyUnicode_DecodeUTF32(data, itemsize, NULL, &byteorder); if (u == NULL) { return NULL; } args = Py_BuildValue("(O)", u); if (args == NULL) { Py_DECREF(u); return NULL; } obj = type->tp_new(type, args, NULL); Py_DECREF(u); Py_DECREF(args); return obj; } #endif if (type->tp_itemsize != 0) { /* String type */ obj = type->tp_alloc(type, itemsize); } else { obj = type->tp_alloc(type, 0); } if (obj == NULL) { return NULL; } if (PyTypeNum_ISDATETIME(type_num)) { /* * We need to copy the resolution information over to the scalar * Get the void * from the metadata dictionary */ PyArray_DatetimeMetaData *dt_data; dt_data = &(((PyArray_DatetimeDTypeMetaData *)descr->c_metadata)->meta); memcpy(&(((PyDatetimeScalarObject *)obj)->obmeta), dt_data, sizeof(PyArray_DatetimeMetaData)); } if (PyTypeNum_ISFLEXIBLE(type_num)) { if (type_num == NPY_STRING) { destptr = PyString_AS_STRING(obj); ((PyStringObject *)obj)->ob_shash = -1; #if !defined(NPY_PY3K) ((PyStringObject *)obj)->ob_sstate = SSTATE_NOT_INTERNED; #endif memcpy(destptr, data, itemsize); return obj; } #if PY_VERSION_HEX < 0x03030000 else if (type_num == NPY_UNICODE) { /* tp_alloc inherited from Python PyBaseObject_Type */ PyUnicodeObject *uni = (PyUnicodeObject*)obj; size_t length = itemsize >> 2; Py_UNICODE *dst; #ifndef Py_UNICODE_WIDE char *buffer; Py_UNICODE *tmp; int alloc = 0; length *= 2; #endif /* Set uni->str so that object can be deallocated on failure */ uni->str = NULL; uni->defenc = NULL; uni->hash = -1; dst = PyObject_MALLOC(sizeof(Py_UNICODE) * (length + 1)); if (dst == NULL) { Py_DECREF(obj); PyErr_NoMemory(); return NULL; } #ifdef Py_UNICODE_WIDE memcpy(dst, data, itemsize); if (swap) { byte_swap_vector(dst, length, 4); } uni->str = dst; uni->str[length] = 0; uni->length = length; #else /* need aligned data buffer */ if ((swap) || ((((npy_intp)data) % descr->alignment) != 0)) { buffer = malloc(itemsize); if (buffer == NULL) { PyObject_FREE(dst); Py_DECREF(obj); PyErr_NoMemory(); } alloc = 1; memcpy(buffer, data, itemsize); if (swap) { byte_swap_vector(buffer, itemsize >> 2, 4); } } else { buffer = data; } /* * Allocated enough for 2-characters per itemsize. * Now convert from the data-buffer */ length = PyUCS2Buffer_FromUCS4(dst, (npy_ucs4 *)buffer, itemsize >> 2); if (alloc) { free(buffer); } /* Resize the unicode result */ tmp = PyObject_REALLOC(dst, sizeof(Py_UNICODE)*(length + 1)); if (tmp == NULL) { PyObject_FREE(dst); Py_DECREF(obj); return NULL; } uni->str = tmp; uni->str[length] = 0; uni->length = length; #endif return obj; } #endif /* PY_VERSION_HEX < 0x03030000 */ else { PyVoidScalarObject *vobj = (PyVoidScalarObject *)obj; vobj->base = NULL; vobj->descr = descr; Py_INCREF(descr); vobj->obval = NULL; Py_SIZE(vobj) = itemsize; vobj->flags = NPY_ARRAY_BEHAVED | NPY_ARRAY_OWNDATA; swap = 0; if (PyDataType_HASFIELDS(descr)) { if (base) { Py_INCREF(base); vobj->base = base; vobj->flags = PyArray_FLAGS((PyArrayObject *)base); vobj->flags &= ~NPY_ARRAY_OWNDATA; vobj->obval = data; return obj; } } destptr = PyDataMem_NEW(itemsize); if (destptr == NULL) { Py_DECREF(obj); return PyErr_NoMemory(); } vobj->obval = destptr; /* * No base available for copyswp and no swap required. * Copy data directly into dest. */ if (base == NULL) { memcpy(destptr, data, itemsize); return obj; } } } else { destptr = scalar_value(obj, descr); } /* copyswap for OBJECT increments the reference count */ copyswap(destptr, data, swap, base); return obj; } /* Return Array Scalar if 0-d array object is encountered */ /*NUMPY_API * *Return either an array or the appropriate Python object if the array *is 0d and matches a Python type. */ NPY_NO_EXPORT PyObject * PyArray_Return(PyArrayObject *mp) { if (mp == NULL) { return NULL; } if (PyErr_Occurred()) { Py_XDECREF(mp); return NULL; } if (!PyArray_Check(mp)) { return (PyObject *)mp; } if (PyArray_NDIM(mp) == 0) { PyObject *ret; ret = PyArray_ToScalar(PyArray_DATA(mp), mp); Py_DECREF(mp); return ret; } else { return (PyObject *)mp; } } numpy-1.8.2/numpy/core/src/multiarray/iterators.c0000664000175100017510000017504512370216243023300 0ustar vagrantvagrant00000000000000#define PY_SSIZE_T_CLEAN #include #include "structmember.h" #define NPY_NO_DEPRECATED_API NPY_API_VERSION #define _MULTIARRAYMODULE #include "numpy/arrayobject.h" #include "numpy/arrayscalars.h" #include "npy_config.h" #include "npy_pycompat.h" #include "arrayobject.h" #include "iterators.h" #include "ctors.h" #include "common.h" #define NEWAXIS_INDEX -1 #define ELLIPSIS_INDEX -2 #define SINGLE_INDEX -3 static int slice_coerce_index(PyObject *o, npy_intp *v); /* * This function converts one element of the indexing tuple * into a step size and a number of steps, returning the * starting index. Non-slices are signalled in 'n_steps', * as NEWAXIS_INDEX, ELLIPSIS_INDEX, or SINGLE_INDEX. */ NPY_NO_EXPORT npy_intp parse_index_entry(PyObject *op, npy_intp *step_size, npy_intp *n_steps, npy_intp max, int axis, int check_index) { npy_intp i; if (op == Py_None) { *n_steps = NEWAXIS_INDEX; i = 0; } else if (op == Py_Ellipsis) { *n_steps = ELLIPSIS_INDEX; i = 0; } else if (PySlice_Check(op)) { npy_intp stop; if (slice_GetIndices((PySliceObject *)op, max, &i, &stop, step_size, n_steps) < 0) { if (!PyErr_Occurred()) { PyErr_SetString(PyExc_IndexError, "invalid slice"); } goto fail; } if (*n_steps <= 0) { *n_steps = 0; *step_size = 1; i = 0; } } else { if (!slice_coerce_index(op, &i)) { PyErr_SetString(PyExc_IndexError, "each index entry must be either a " "slice, an integer, Ellipsis, or " "newaxis"); goto fail; } *n_steps = SINGLE_INDEX; *step_size = 0; if (check_index) { if (check_and_adjust_index(&i, max, axis) < 0) { goto fail; } } } return i; fail: return -1; } /* * Parses an index that has no fancy indexing. Populates * out_dimensions, out_strides, and out_offset. */ NPY_NO_EXPORT int parse_index(PyArrayObject *self, PyObject *op, npy_intp *out_dimensions, npy_intp *out_strides, npy_intp *out_offset, int check_index) { int i, j, n; int nd_old, nd_new, n_add, n_ellipsis; npy_intp n_steps, start, offset, step_size; PyObject *op1 = NULL; int is_slice; if (PySlice_Check(op) || op == Py_Ellipsis || op == Py_None) { n = 1; op1 = op; Py_INCREF(op); /* this relies on the fact that n==1 for loop below */ is_slice = 1; } else { if (!PySequence_Check(op)) { PyErr_SetString(PyExc_IndexError, "index must be either an int " "or a sequence"); return -1; } n = PySequence_Length(op); is_slice = 0; } nd_old = nd_new = 0; offset = 0; for (i = 0; i < n; i++) { if (!is_slice) { op1 = PySequence_GetItem(op, i); if (op1 == NULL) { return -1; } } start = parse_index_entry(op1, &step_size, &n_steps, nd_old < PyArray_NDIM(self) ? PyArray_DIMS(self)[nd_old] : 0, nd_old, check_index ? nd_old < PyArray_NDIM(self) : 0); Py_DECREF(op1); if (start == -1) { break; } if (n_steps == NEWAXIS_INDEX) { out_dimensions[nd_new] = 1; out_strides[nd_new] = 0; nd_new++; } else if (n_steps == ELLIPSIS_INDEX) { for (j = i + 1, n_ellipsis = 0; j < n; j++) { op1 = PySequence_GetItem(op, j); if (op1 == Py_None) { n_ellipsis++; } Py_DECREF(op1); } n_add = PyArray_NDIM(self)-(n-i-n_ellipsis-1+nd_old); if (n_add < 0) { PyErr_SetString(PyExc_IndexError, "too many indices"); return -1; } for (j = 0; j < n_add; j++) { out_dimensions[nd_new] = PyArray_DIMS(self)[nd_old]; out_strides[nd_new] = PyArray_STRIDES(self)[nd_old]; nd_new++; nd_old++; } } else { if (nd_old >= PyArray_NDIM(self)) { PyErr_SetString(PyExc_IndexError, "too many indices"); return -1; } offset += PyArray_STRIDES(self)[nd_old]*start; nd_old++; if (n_steps != SINGLE_INDEX) { out_dimensions[nd_new] = n_steps; out_strides[nd_new] = step_size * PyArray_STRIDES(self)[nd_old-1]; nd_new++; } } } if (i < n) { return -1; } n_add = PyArray_NDIM(self)-nd_old; for (j = 0; j < n_add; j++) { out_dimensions[nd_new] = PyArray_DIMS(self)[nd_old]; out_strides[nd_new] = PyArray_STRIDES(self)[nd_old]; nd_new++; nd_old++; } *out_offset = offset; return nd_new; } /* * Tries to convert 'o' into an npy_intp interpreted as an * index. Returns 1 if it was successful, 0 otherwise. Does * not set an exception. */ static int slice_coerce_index(PyObject *o, npy_intp *v) { *v = PyArray_PyIntAsIntp(o); if ((*v) == -1 && PyErr_Occurred()) { PyErr_Clear(); return 0; } return 1; } /* * This is basically PySlice_GetIndicesEx, but with our coercion * of indices to integers (plus, that function is new in Python 2.3) * * N.B. The coercion to integers is deprecated; once the DeprecationWarning * is changed to an error, it would seem that this is obsolete. */ NPY_NO_EXPORT int slice_GetIndices(PySliceObject *r, npy_intp length, npy_intp *start, npy_intp *stop, npy_intp *step, npy_intp *slicelength) { npy_intp defstop; if (r->step == Py_None) { *step = 1; } else { if (!slice_coerce_index(r->step, step)) { return -1; } if (*step == 0) { PyErr_SetString(PyExc_ValueError, "slice step cannot be zero"); return -1; } } /* defstart = *step < 0 ? length - 1 : 0; */ defstop = *step < 0 ? -1 : length; if (r->start == Py_None) { *start = *step < 0 ? length-1 : 0; } else { if (!slice_coerce_index(r->start, start)) { return -1; } if (*start < 0) { *start += length; } if (*start < 0) { *start = (*step < 0) ? -1 : 0; } if (*start >= length) { *start = (*step < 0) ? length - 1 : length; } } if (r->stop == Py_None) { *stop = defstop; } else { if (!slice_coerce_index(r->stop, stop)) { return -1; } if (*stop < 0) { *stop += length; } if (*stop < 0) { *stop = -1; } if (*stop > length) { *stop = length; } } if ((*step < 0 && *stop >= *start) || (*step > 0 && *start >= *stop)) { *slicelength = 0; } else if (*step < 0) { *slicelength = (*stop - *start + 1) / (*step) + 1; } else { *slicelength = (*stop - *start - 1) / (*step) + 1; } return 0; } /*********************** Element-wise Array Iterator ***********************/ /* Aided by Peter J. Verveer's nd_image package and numpy's arraymap ****/ /* and Python's array iterator ***/ /* get the dataptr from its current coordinates for simple iterator */ static char* get_ptr_simple(PyArrayIterObject* iter, npy_intp *coordinates) { npy_intp i; char *ret; ret = PyArray_DATA(iter->ao); for(i = 0; i < PyArray_NDIM(iter->ao); ++i) { ret += coordinates[i] * iter->strides[i]; } return ret; } /* * This is common initialization code between PyArrayIterObject and * PyArrayNeighborhoodIterObject * * Increase ao refcount */ static PyObject * array_iter_base_init(PyArrayIterObject *it, PyArrayObject *ao) { int nd, i; nd = PyArray_NDIM(ao); PyArray_UpdateFlags(ao, NPY_ARRAY_C_CONTIGUOUS); if (PyArray_ISCONTIGUOUS(ao)) { it->contiguous = 1; } else { it->contiguous = 0; } Py_INCREF(ao); it->ao = ao; it->size = PyArray_SIZE(ao); it->nd_m1 = nd - 1; it->factors[nd-1] = 1; for (i = 0; i < nd; i++) { it->dims_m1[i] = PyArray_DIMS(ao)[i] - 1; it->strides[i] = PyArray_STRIDES(ao)[i]; it->backstrides[i] = it->strides[i] * it->dims_m1[i]; if (i > 0) { it->factors[nd-i-1] = it->factors[nd-i] * PyArray_DIMS(ao)[nd-i]; } it->bounds[i][0] = 0; it->bounds[i][1] = PyArray_DIMS(ao)[i] - 1; it->limits[i][0] = 0; it->limits[i][1] = PyArray_DIMS(ao)[i] - 1; it->limits_sizes[i] = it->limits[i][1] - it->limits[i][0] + 1; } it->translate = &get_ptr_simple; PyArray_ITER_RESET(it); return (PyObject *)it; } static void array_iter_base_dealloc(PyArrayIterObject *it) { Py_XDECREF(it->ao); } /*NUMPY_API * Get Iterator. */ NPY_NO_EXPORT PyObject * PyArray_IterNew(PyObject *obj) { PyArrayIterObject *it; PyArrayObject *ao; if (!PyArray_Check(obj)) { PyErr_BadInternalCall(); return NULL; } ao = (PyArrayObject *)obj; it = (PyArrayIterObject *)PyArray_malloc(sizeof(PyArrayIterObject)); PyObject_Init((PyObject *)it, &PyArrayIter_Type); /* it = PyObject_New(PyArrayIterObject, &PyArrayIter_Type);*/ if (it == NULL) { return NULL; } array_iter_base_init(it, ao); return (PyObject *)it; } /*NUMPY_API * Get Iterator broadcast to a particular shape */ NPY_NO_EXPORT PyObject * PyArray_BroadcastToShape(PyObject *obj, npy_intp *dims, int nd) { PyArrayIterObject *it; int i, diff, j, compat, k; PyArrayObject *ao = (PyArrayObject *)obj; if (PyArray_NDIM(ao) > nd) { goto err; } compat = 1; diff = j = nd - PyArray_NDIM(ao); for (i = 0; i < PyArray_NDIM(ao); i++, j++) { if (PyArray_DIMS(ao)[i] == 1) { continue; } if (PyArray_DIMS(ao)[i] != dims[j]) { compat = 0; break; } } if (!compat) { goto err; } it = (PyArrayIterObject *)PyArray_malloc(sizeof(PyArrayIterObject)); if (it == NULL) { return NULL; } PyObject_Init((PyObject *)it, &PyArrayIter_Type); PyArray_UpdateFlags(ao, NPY_ARRAY_C_CONTIGUOUS); if (PyArray_ISCONTIGUOUS(ao)) { it->contiguous = 1; } else { it->contiguous = 0; } Py_INCREF(ao); it->ao = ao; it->size = PyArray_MultiplyList(dims, nd); it->nd_m1 = nd - 1; it->factors[nd-1] = 1; for (i = 0; i < nd; i++) { it->dims_m1[i] = dims[i] - 1; k = i - diff; if ((k < 0) || PyArray_DIMS(ao)[k] != dims[i]) { it->contiguous = 0; it->strides[i] = 0; } else { it->strides[i] = PyArray_STRIDES(ao)[k]; } it->backstrides[i] = it->strides[i] * it->dims_m1[i]; if (i > 0) { it->factors[nd-i-1] = it->factors[nd-i] * dims[nd-i]; } } PyArray_ITER_RESET(it); return (PyObject *)it; err: PyErr_SetString(PyExc_ValueError, "array is not broadcastable to "\ "correct shape"); return NULL; } /*NUMPY_API * Get Iterator that iterates over all but one axis (don't use this with * PyArray_ITER_GOTO1D). The axis will be over-written if negative * with the axis having the smallest stride. */ NPY_NO_EXPORT PyObject * PyArray_IterAllButAxis(PyObject *obj, int *inaxis) { PyArrayObject *arr; PyArrayIterObject *it; int axis; if (!PyArray_Check(obj)) { PyErr_SetString(PyExc_ValueError, "Numpy IterAllButAxis requires an ndarray"); return NULL; } arr = (PyArrayObject *)obj; it = (PyArrayIterObject *)PyArray_IterNew((PyObject *)arr); if (it == NULL) { return NULL; } if (PyArray_NDIM(arr)==0) { return (PyObject *)it; } if (*inaxis < 0) { int i, minaxis = 0; npy_intp minstride = 0; i = 0; while (minstride == 0 && i < PyArray_NDIM(arr)) { minstride = PyArray_STRIDE(arr,i); i++; } for (i = 1; i < PyArray_NDIM(arr); i++) { if (PyArray_STRIDE(arr,i) > 0 && PyArray_STRIDE(arr, i) < minstride) { minaxis = i; minstride = PyArray_STRIDE(arr,i); } } *inaxis = minaxis; } axis = *inaxis; /* adjust so that will not iterate over axis */ it->contiguous = 0; if (it->size != 0) { it->size /= PyArray_DIM(arr,axis); } it->dims_m1[axis] = 0; it->backstrides[axis] = 0; /* * (won't fix factors so don't use * PyArray_ITER_GOTO1D with this iterator) */ return (PyObject *)it; } /*NUMPY_API * Adjusts previously broadcasted iterators so that the axis with * the smallest sum of iterator strides is not iterated over. * Returns dimension which is smallest in the range [0,multi->nd). * A -1 is returned if multi->nd == 0. * * don't use with PyArray_ITER_GOTO1D because factors are not adjusted */ NPY_NO_EXPORT int PyArray_RemoveSmallest(PyArrayMultiIterObject *multi) { PyArrayIterObject *it; int i, j; int axis; npy_intp smallest; npy_intp sumstrides[NPY_MAXDIMS]; if (multi->nd == 0) { return -1; } for (i = 0; i < multi->nd; i++) { sumstrides[i] = 0; for (j = 0; j < multi->numiter; j++) { sumstrides[i] += multi->iters[j]->strides[i]; } } axis = 0; smallest = sumstrides[0]; /* Find longest dimension */ for (i = 1; i < multi->nd; i++) { if (sumstrides[i] < smallest) { axis = i; smallest = sumstrides[i]; } } for(i = 0; i < multi->numiter; i++) { it = multi->iters[i]; it->contiguous = 0; if (it->size != 0) { it->size /= (it->dims_m1[axis]+1); } it->dims_m1[axis] = 0; it->backstrides[axis] = 0; } multi->size = multi->iters[0]->size; return axis; } /* Returns an array scalar holding the element desired */ static PyObject * arrayiter_next(PyArrayIterObject *it) { PyObject *ret; if (it->index < it->size) { ret = PyArray_ToScalar(it->dataptr, it->ao); PyArray_ITER_NEXT(it); return ret; } return NULL; } static void arrayiter_dealloc(PyArrayIterObject *it) { array_iter_base_dealloc(it); PyArray_free(it); } static Py_ssize_t iter_length(PyArrayIterObject *self) { return self->size; } static PyArrayObject * iter_subscript_Bool(PyArrayIterObject *self, PyArrayObject *ind) { npy_intp counter, strides; int itemsize; npy_intp count = 0; char *dptr, *optr; PyArrayObject *ret; int swap; PyArray_CopySwapFunc *copyswap; if (PyArray_NDIM(ind) != 1) { PyErr_SetString(PyExc_ValueError, "boolean index array should have 1 dimension"); return NULL; } counter = PyArray_DIMS(ind)[0]; if (counter > self->size) { PyErr_SetString(PyExc_ValueError, "too many boolean indices"); return NULL; } strides = PyArray_STRIDES(ind)[0]; dptr = PyArray_DATA(ind); /* Get size of return array */ while (counter--) { if (*((npy_bool *)dptr) != 0) { count++; } dptr += strides; } itemsize = PyArray_DESCR(self->ao)->elsize; Py_INCREF(PyArray_DESCR(self->ao)); ret = (PyArrayObject *)PyArray_NewFromDescr(Py_TYPE(self->ao), PyArray_DESCR(self->ao), 1, &count, NULL, NULL, 0, (PyObject *)self->ao); if (ret == NULL) { return NULL; } /* Set up loop */ optr = PyArray_DATA(ret); counter = PyArray_DIMS(ind)[0]; dptr = PyArray_DATA(ind); copyswap = PyArray_DESCR(self->ao)->f->copyswap; /* Loop over Boolean array */ swap = (PyArray_ISNOTSWAPPED(self->ao) != PyArray_ISNOTSWAPPED(ret)); while (counter--) { if (*((npy_bool *)dptr) != 0) { copyswap(optr, self->dataptr, swap, self->ao); optr += itemsize; } dptr += strides; PyArray_ITER_NEXT(self); } PyArray_ITER_RESET(self); return ret; } static PyObject * iter_subscript_int(PyArrayIterObject *self, PyArrayObject *ind) { npy_intp num; PyArrayObject *ret; PyArrayIterObject *ind_it; int itemsize; int swap; char *optr; npy_intp counter; PyArray_CopySwapFunc *copyswap; 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) { PyArray_ITER_RESET(self); return NULL; } else { PyObject *tmp; PyArray_ITER_GOTO1D(self, num); tmp = PyArray_ToScalar(self->dataptr, self->ao); PyArray_ITER_RESET(self); return tmp; } } Py_INCREF(PyArray_DESCR(self->ao)); ret = (PyArrayObject *)PyArray_NewFromDescr(Py_TYPE(self->ao), PyArray_DESCR(self->ao), PyArray_NDIM(ind), PyArray_DIMS(ind), NULL, NULL, 0, (PyObject *)self->ao); if (ret == NULL) { return NULL; } optr = PyArray_DATA(ret); ind_it = (PyArrayIterObject *)PyArray_IterNew((PyObject *)ind); if (ind_it == NULL) { Py_DECREF(ret); return NULL; } counter = ind_it->size; copyswap = PyArray_DESCR(ret)->f->copyswap; 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) { Py_DECREF(ind_it); Py_DECREF(ret); PyArray_ITER_RESET(self); return NULL; } PyArray_ITER_GOTO1D(self, num); copyswap(optr, self->dataptr, swap, ret); optr += itemsize; PyArray_ITER_NEXT(ind_it); } Py_DECREF(ind_it); PyArray_ITER_RESET(self); return (PyObject *)ret; } /* Always returns arrays */ NPY_NO_EXPORT PyObject * iter_subscript(PyArrayIterObject *self, PyObject *ind) { PyArray_Descr *indtype = NULL; PyArray_Descr *dtype; npy_intp start, step_size; npy_intp n_steps; PyArrayObject *ret; char *dptr; int size; PyObject *obj = NULL; PyArray_CopySwapFunc *copyswap; if (ind == Py_Ellipsis) { ind = PySlice_New(NULL, NULL, NULL); obj = iter_subscript(self, ind); Py_DECREF(ind); return obj; } if (PyTuple_Check(ind)) { int len; len = PyTuple_GET_SIZE(ind); if (len > 1) { goto fail; } if (len == 0) { Py_INCREF(self->ao); return (PyObject *)self->ao; } ind = PyTuple_GET_ITEM(ind, 0); } /* * Tuples >1d not accepted --- i.e. no newaxis * Could implement this with adjusted strides and dimensions in iterator * Check for Boolean -- this is first because Bool is a subclass of Int */ PyArray_ITER_RESET(self); if (PyBool_Check(ind)) { if (PyObject_IsTrue(ind)) { return PyArray_ToScalar(self->dataptr, self->ao); } else { /* empty array */ npy_intp ii = 0; dtype = PyArray_DESCR(self->ao); Py_INCREF(dtype); ret = (PyArrayObject *)PyArray_NewFromDescr(Py_TYPE(self->ao), dtype, 1, &ii, NULL, NULL, 0, (PyObject *)self->ao); return (PyObject *)ret; } } /* Check for Integer or Slice */ if (PyLong_Check(ind) || PyInt_Check(ind) || PySlice_Check(ind)) { start = parse_index_entry(ind, &step_size, &n_steps, self->size, 0, 1); if (start == -1) { goto fail; } if (n_steps == ELLIPSIS_INDEX || n_steps == NEWAXIS_INDEX) { PyErr_SetString(PyExc_IndexError, "cannot use Ellipsis or newaxes here"); goto fail; } PyArray_ITER_GOTO1D(self, start); if (n_steps == SINGLE_INDEX) { /* Integer */ PyObject *tmp; tmp = PyArray_ToScalar(self->dataptr, self->ao); PyArray_ITER_RESET(self); return tmp; } size = PyArray_DESCR(self->ao)->elsize; dtype = PyArray_DESCR(self->ao); Py_INCREF(dtype); ret = (PyArrayObject *)PyArray_NewFromDescr(Py_TYPE(self->ao), dtype, 1, &n_steps, NULL, NULL, 0, (PyObject *)self->ao); if (ret == NULL) { goto fail; } dptr = PyArray_DATA(ret); copyswap = PyArray_DESCR(ret)->f->copyswap; while (n_steps--) { copyswap(dptr, self->dataptr, 0, ret); start += step_size; PyArray_ITER_GOTO1D(self, start); dptr += size; } PyArray_ITER_RESET(self); return (PyObject *)ret; } /* convert to INTP array if Integer array scalar or List */ indtype = PyArray_DescrFromType(NPY_INTP); if (PyArray_IsScalar(ind, Integer) || PyList_Check(ind)) { Py_INCREF(indtype); obj = PyArray_FromAny(ind, indtype, 0, 0, NPY_ARRAY_FORCECAST, NULL); if (obj == NULL) { goto fail; } } else { Py_INCREF(ind); obj = ind; } if (PyArray_Check(obj)) { /* Check for Boolean object */ if (PyArray_TYPE((PyArrayObject *)obj) == NPY_BOOL) { ret = iter_subscript_Bool(self, (PyArrayObject *)obj); Py_DECREF(indtype); } /* Check for integer array */ else if (PyArray_ISINTEGER((PyArrayObject *)obj)) { PyObject *new; new = PyArray_FromAny(obj, indtype, 0, 0, NPY_ARRAY_FORCECAST | NPY_ARRAY_ALIGNED, NULL); if (new == NULL) { goto fail; } Py_DECREF(obj); obj = new; new = iter_subscript_int(self, (PyArrayObject *)obj); Py_DECREF(obj); return new; } else { goto fail; } Py_DECREF(obj); return (PyObject *)ret; } else { Py_DECREF(indtype); } fail: if (!PyErr_Occurred()) { PyErr_SetString(PyExc_IndexError, "unsupported iterator index"); } Py_XDECREF(indtype); Py_XDECREF(obj); return NULL; } static int iter_ass_sub_Bool(PyArrayIterObject *self, PyArrayObject *ind, PyArrayIterObject *val, int swap) { npy_intp counter, strides; char *dptr; PyArray_CopySwapFunc *copyswap; if (PyArray_NDIM(ind) != 1) { PyErr_SetString(PyExc_ValueError, "boolean index array should have 1 dimension"); return -1; } counter = PyArray_DIMS(ind)[0]; if (counter > self->size) { PyErr_SetString(PyExc_ValueError, "boolean index array has too many values"); return -1; } strides = PyArray_STRIDES(ind)[0]; dptr = PyArray_DATA(ind); PyArray_ITER_RESET(self); /* Loop over Boolean array */ copyswap = PyArray_DESCR(self->ao)->f->copyswap; while (counter--) { if (*((npy_bool *)dptr) != 0) { copyswap(self->dataptr, val->dataptr, swap, self->ao); PyArray_ITER_NEXT(val); if (val->index == val->size) { PyArray_ITER_RESET(val); } } dptr += strides; PyArray_ITER_NEXT(self); } PyArray_ITER_RESET(self); return 0; } static int iter_ass_sub_int(PyArrayIterObject *self, PyArrayObject *ind, PyArrayIterObject *val, int swap) { npy_intp num; PyArrayIterObject *ind_it; npy_intp counter; PyArray_CopySwapFunc *copyswap; 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) { return -1; } PyArray_ITER_GOTO1D(self, num); copyswap(self->dataptr, val->dataptr, swap, self->ao); return 0; } ind_it = (PyArrayIterObject *)PyArray_IterNew((PyObject *)ind); if (ind_it == NULL) { return -1; } counter = ind_it->size; while (counter--) { num = *((npy_intp *)(ind_it->dataptr)); if (check_and_adjust_index(&num, self->size, -1) < 0) { Py_DECREF(ind_it); return -1; } PyArray_ITER_GOTO1D(self, num); copyswap(self->dataptr, val->dataptr, swap, self->ao); PyArray_ITER_NEXT(ind_it); PyArray_ITER_NEXT(val); if (val->index == val->size) { PyArray_ITER_RESET(val); } } Py_DECREF(ind_it); return 0; } NPY_NO_EXPORT int iter_ass_subscript(PyArrayIterObject *self, PyObject *ind, PyObject *val) { PyArrayObject *arrval = NULL; PyArrayIterObject *val_it = NULL; PyArray_Descr *type; PyArray_Descr *indtype = NULL; int swap, retval = -1; npy_intp start, step_size; npy_intp n_steps; PyObject *obj = NULL; PyArray_CopySwapFunc *copyswap; if (val == NULL) { PyErr_SetString(PyExc_TypeError, "Cannot delete iterator elements"); return -1; } if (PyArray_FailUnlessWriteable(self->ao, "underlying array") < 0) return -1; if (ind == Py_Ellipsis) { ind = PySlice_New(NULL, NULL, NULL); retval = iter_ass_subscript(self, ind, val); Py_DECREF(ind); return retval; } if (PyTuple_Check(ind)) { int len; len = PyTuple_GET_SIZE(ind); if (len > 1) { goto finish; } ind = PyTuple_GET_ITEM(ind, 0); } type = PyArray_DESCR(self->ao); /* * Check for Boolean -- this is first becasue * Bool is a subclass of Int */ if (PyBool_Check(ind)) { retval = 0; if (PyObject_IsTrue(ind)) { retval = type->f->setitem(val, self->dataptr, self->ao); } goto finish; } if (PySequence_Check(ind) || PySlice_Check(ind)) { goto skip; } start = PyArray_PyIntAsIntp(ind); if (start==-1 && PyErr_Occurred()) { PyErr_Clear(); } else { if (check_and_adjust_index(&start, self->size, -1) < 0) { goto finish; } retval = 0; PyArray_ITER_GOTO1D(self, start); retval = type->f->setitem(val, self->dataptr, self->ao); PyArray_ITER_RESET(self); if (retval < 0) { PyErr_SetString(PyExc_ValueError, "Error setting single item of array."); } goto finish; } skip: Py_INCREF(type); arrval = (PyArrayObject *)PyArray_FromAny(val, type, 0, 0, NPY_ARRAY_FORCECAST, NULL); if (arrval == NULL) { return -1; } val_it = (PyArrayIterObject *)PyArray_IterNew((PyObject *)arrval); if (val_it == NULL) { goto finish; } if (val_it->size == 0) { retval = 0; goto finish; } copyswap = PyArray_DESCR(arrval)->f->copyswap; swap = (PyArray_ISNOTSWAPPED(self->ao)!=PyArray_ISNOTSWAPPED(arrval)); /* Check Slice */ if (PySlice_Check(ind)) { start = parse_index_entry(ind, &step_size, &n_steps, self->size, 0, 0); if (start == -1) { goto finish; } if (n_steps == ELLIPSIS_INDEX || n_steps == NEWAXIS_INDEX) { PyErr_SetString(PyExc_IndexError, "cannot use Ellipsis or newaxes here"); goto finish; } PyArray_ITER_GOTO1D(self, start); if (n_steps == SINGLE_INDEX) { /* Integer */ copyswap(self->dataptr, PyArray_DATA(arrval), swap, arrval); PyArray_ITER_RESET(self); retval = 0; goto finish; } while (n_steps--) { copyswap(self->dataptr, val_it->dataptr, swap, arrval); start += step_size; PyArray_ITER_GOTO1D(self, start); PyArray_ITER_NEXT(val_it); if (val_it->index == val_it->size) { PyArray_ITER_RESET(val_it); } } PyArray_ITER_RESET(self); retval = 0; goto finish; } /* convert to INTP array if Integer array scalar or List */ indtype = PyArray_DescrFromType(NPY_INTP); if (PyList_Check(ind)) { Py_INCREF(indtype); obj = PyArray_FromAny(ind, indtype, 0, 0, NPY_ARRAY_FORCECAST, NULL); } else { Py_INCREF(ind); obj = ind; } if (obj != NULL && PyArray_Check(obj)) { /* Check for Boolean object */ if (PyArray_TYPE((PyArrayObject *)obj)==NPY_BOOL) { if (iter_ass_sub_Bool(self, (PyArrayObject *)obj, val_it, swap) < 0) { goto finish; } retval=0; } /* Check for integer array */ else if (PyArray_ISINTEGER((PyArrayObject *)obj)) { PyObject *new; Py_INCREF(indtype); new = PyArray_CheckFromAny(obj, indtype, 0, 0, NPY_ARRAY_FORCECAST | NPY_ARRAY_BEHAVED_NS, NULL); Py_DECREF(obj); obj = new; if (new == NULL) { goto finish; } if (iter_ass_sub_int(self, (PyArrayObject *)obj, val_it, swap) < 0) { goto finish; } retval = 0; } } finish: if (!PyErr_Occurred() && retval < 0) { PyErr_SetString(PyExc_IndexError, "unsupported iterator index"); } Py_XDECREF(indtype); Py_XDECREF(obj); Py_XDECREF(val_it); Py_XDECREF(arrval); return retval; } static PyMappingMethods iter_as_mapping = { (lenfunc)iter_length, /*mp_length*/ (binaryfunc)iter_subscript, /*mp_subscript*/ (objobjargproc)iter_ass_subscript, /*mp_ass_subscript*/ }; static PyArrayObject * iter_array(PyArrayIterObject *it, PyObject *NPY_UNUSED(op)) { PyArrayObject *ret; npy_intp size; /* Any argument ignored */ /* Two options: * 1) underlying array is contiguous * -- return 1-d wrapper around it * 2) underlying array is not contiguous * -- make new 1-d contiguous array with updateifcopy flag set * to copy back to the old array * * If underlying array is readonly, then we make the output array readonly * and updateifcopy does not apply. */ size = PyArray_SIZE(it->ao); Py_INCREF(PyArray_DESCR(it->ao)); if (PyArray_ISCONTIGUOUS(it->ao)) { ret = (PyArrayObject *)PyArray_NewFromDescr(&PyArray_Type, PyArray_DESCR(it->ao), 1, &size, NULL, PyArray_DATA(it->ao), PyArray_FLAGS(it->ao), (PyObject *)it->ao); if (ret == NULL) { return NULL; } Py_INCREF(it->ao); if (PyArray_SetBaseObject(ret, (PyObject *)it->ao) < 0) { Py_DECREF(ret); return NULL; } } else { ret = (PyArrayObject *)PyArray_NewFromDescr(&PyArray_Type, PyArray_DESCR(it->ao), 1, &size, NULL, NULL, 0, (PyObject *)it->ao); if (ret == NULL) { return NULL; } if (PyArray_CopyAnyInto(ret, it->ao) < 0) { Py_DECREF(ret); return NULL; } if (PyArray_ISWRITEABLE(it->ao)) { Py_INCREF(it->ao); if (PyArray_SetUpdateIfCopyBase(ret, it->ao) < 0) { Py_DECREF(ret); return NULL; } } else { PyArray_CLEARFLAGS(ret, NPY_ARRAY_WRITEABLE); } } return ret; } static PyObject * iter_copy(PyArrayIterObject *it, PyObject *args) { if (!PyArg_ParseTuple(args, "")) { return NULL; } return PyArray_Flatten(it->ao, 0); } static PyMethodDef iter_methods[] = { /* to get array */ {"__array__", (PyCFunction)iter_array, METH_VARARGS, NULL}, {"copy", (PyCFunction)iter_copy, METH_VARARGS, NULL}, {NULL, NULL, 0, NULL} /* sentinel */ }; static PyObject * iter_richcompare(PyArrayIterObject *self, PyObject *other, int cmp_op) { PyArrayObject *new; PyObject *ret; new = (PyArrayObject *)iter_array(self, NULL); if (new == NULL) { return NULL; } ret = array_richcompare(new, other, cmp_op); Py_DECREF(new); return ret; } static PyMemberDef iter_members[] = { {"base", T_OBJECT, offsetof(PyArrayIterObject, ao), READONLY, NULL}, {"index", T_INT, offsetof(PyArrayIterObject, index), READONLY, NULL}, {NULL, 0, 0, 0, NULL}, }; static PyObject * iter_coords_get(PyArrayIterObject *self) { int nd; nd = PyArray_NDIM(self->ao); if (self->contiguous) { /* * coordinates not kept track of --- * need to generate from index */ npy_intp val; int i; val = self->index; for (i = 0; i < nd; i++) { if (self->factors[i] != 0) { self->coordinates[i] = val / self->factors[i]; val = val % self->factors[i]; } else { self->coordinates[i] = 0; } } } return PyArray_IntTupleFromIntp(nd, self->coordinates); } static PyGetSetDef iter_getsets[] = { {"coords", (getter)iter_coords_get, NULL, NULL, NULL}, {NULL, NULL, NULL, NULL, NULL}, }; NPY_NO_EXPORT PyTypeObject PyArrayIter_Type = { #if defined(NPY_PY3K) PyVarObject_HEAD_INIT(NULL, 0) #else PyObject_HEAD_INIT(NULL) 0, /* ob_size */ #endif "numpy.flatiter", /* tp_name */ sizeof(PyArrayIterObject), /* tp_basicsize */ 0, /* tp_itemsize */ /* methods */ (destructor)arrayiter_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ #if defined(NPY_PY3K) 0, /* tp_reserved */ #else 0, /* tp_compare */ #endif 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ &iter_as_mapping, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT, /* tp_flags */ 0, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ (richcmpfunc)iter_richcompare, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ (iternextfunc)arrayiter_next, /* tp_iternext */ iter_methods, /* tp_methods */ iter_members, /* tp_members */ iter_getsets, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ 0, /* 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 */ 0, /* tp_version_tag */ }; /** END of Array Iterator **/ /* Adjust dimensionality and strides for index object iterators --- i.e. broadcast */ /*NUMPY_API*/ NPY_NO_EXPORT int PyArray_Broadcast(PyArrayMultiIterObject *mit) { int i, nd, k, j; npy_intp tmp; PyArrayIterObject *it; /* Discover the broadcast number of dimensions */ for (i = 0, nd = 0; i < mit->numiter; i++) { nd = PyArray_MAX(nd, PyArray_NDIM(mit->iters[i]->ao)); } mit->nd = nd; /* Discover the broadcast shape in each dimension */ for (i = 0; i < nd; i++) { mit->dimensions[i] = 1; for (j = 0; j < mit->numiter; j++) { it = mit->iters[j]; /* This prepends 1 to shapes not already equal to nd */ k = i + PyArray_NDIM(it->ao) - nd; if (k >= 0) { tmp = PyArray_DIMS(it->ao)[k]; if (tmp == 1) { continue; } if (mit->dimensions[i] == 1) { mit->dimensions[i] = tmp; } else if (mit->dimensions[i] != tmp) { PyErr_SetString(PyExc_ValueError, "shape mismatch: objects" \ " cannot be broadcast" \ " to a single shape"); return -1; } } } } /* * Reset the iterator dimensions and strides of each iterator * object -- using 0 valued strides for broadcasting * Need to check for overflow */ tmp = PyArray_OverflowMultiplyList(mit->dimensions, mit->nd); if (tmp < 0) { PyErr_SetString(PyExc_ValueError, "broadcast dimensions too large."); return -1; } mit->size = tmp; for (i = 0; i < mit->numiter; i++) { it = mit->iters[i]; it->nd_m1 = mit->nd - 1; it->size = tmp; nd = PyArray_NDIM(it->ao); it->factors[mit->nd-1] = 1; for (j = 0; j < mit->nd; j++) { it->dims_m1[j] = mit->dimensions[j] - 1; k = j + nd - mit->nd; /* * If this dimension was added or shape of * underlying array was 1 */ if ((k < 0) || PyArray_DIMS(it->ao)[k] != mit->dimensions[j]) { it->contiguous = 0; it->strides[j] = 0; } else { it->strides[j] = PyArray_STRIDES(it->ao)[k]; } it->backstrides[j] = it->strides[j] * it->dims_m1[j]; if (j > 0) it->factors[mit->nd-j-1] = it->factors[mit->nd-j] * mit->dimensions[mit->nd-j]; } PyArray_ITER_RESET(it); } return 0; } /*NUMPY_API * Get MultiIterator from array of Python objects and any additional * * PyObject **mps -- array of PyObjects * int n - number of PyObjects in the array * int nadd - number of additional arrays to include in the iterator. * * Returns a multi-iterator object. */ NPY_NO_EXPORT PyObject * PyArray_MultiIterFromObjects(PyObject **mps, int n, int nadd, ...) { va_list va; PyArrayMultiIterObject *multi; PyObject *current; PyObject *arr; int i, ntot, err=0; ntot = n + nadd; if (ntot < 2 || ntot > NPY_MAXARGS) { PyErr_Format(PyExc_ValueError, "Need between 2 and (%d) " \ "array objects (inclusive).", NPY_MAXARGS); return NULL; } multi = PyArray_malloc(sizeof(PyArrayMultiIterObject)); if (multi == NULL) { return PyErr_NoMemory(); } PyObject_Init((PyObject *)multi, &PyArrayMultiIter_Type); for (i = 0; i < ntot; i++) { multi->iters[i] = NULL; } multi->numiter = ntot; multi->index = 0; va_start(va, nadd); for (i = 0; i < ntot; i++) { if (i < n) { current = mps[i]; } else { current = va_arg(va, PyObject *); } arr = PyArray_FROM_O(current); if (arr == NULL) { err = 1; break; } else { multi->iters[i] = (PyArrayIterObject *)PyArray_IterNew(arr); if (multi->iters[i] == NULL) { err = 1; break; } Py_DECREF(arr); } } va_end(va); if (!err && PyArray_Broadcast(multi) < 0) { err = 1; } if (err) { Py_DECREF(multi); return NULL; } PyArray_MultiIter_RESET(multi); return (PyObject *)multi; } /*NUMPY_API * Get MultiIterator, */ NPY_NO_EXPORT PyObject * PyArray_MultiIterNew(int n, ...) { va_list va; PyArrayMultiIterObject *multi; PyObject *current; PyObject *arr; int i, err = 0; if (n < 2 || n > NPY_MAXARGS) { PyErr_Format(PyExc_ValueError, "Need between 2 and (%d) " \ "array objects (inclusive).", NPY_MAXARGS); return NULL; } /* fprintf(stderr, "multi new...");*/ multi = PyArray_malloc(sizeof(PyArrayMultiIterObject)); if (multi == NULL) { return PyErr_NoMemory(); } PyObject_Init((PyObject *)multi, &PyArrayMultiIter_Type); for (i = 0; i < n; i++) { multi->iters[i] = NULL; } multi->numiter = n; multi->index = 0; va_start(va, n); for (i = 0; i < n; i++) { current = va_arg(va, PyObject *); arr = PyArray_FROM_O(current); if (arr == NULL) { err = 1; break; } else { multi->iters[i] = (PyArrayIterObject *)PyArray_IterNew(arr); if (multi->iters[i] == NULL) { err = 1; break; } Py_DECREF(arr); } } va_end(va); if (!err && PyArray_Broadcast(multi) < 0) { err = 1; } if (err) { Py_DECREF(multi); return NULL; } PyArray_MultiIter_RESET(multi); return (PyObject *)multi; } static PyObject * arraymultiter_new(PyTypeObject *NPY_UNUSED(subtype), PyObject *args, PyObject *kwds) { Py_ssize_t n, i; PyArrayMultiIterObject *multi; PyObject *arr; if (kwds != NULL) { PyErr_SetString(PyExc_ValueError, "keyword arguments not accepted."); return NULL; } n = PyTuple_Size(args); if (n < 2 || n > NPY_MAXARGS) { if (PyErr_Occurred()) { return NULL; } PyErr_Format(PyExc_ValueError, "Need at least two and fewer than (%d) " \ "array objects.", NPY_MAXARGS); return NULL; } multi = PyArray_malloc(sizeof(PyArrayMultiIterObject)); if (multi == NULL) { return PyErr_NoMemory(); } PyObject_Init((PyObject *)multi, &PyArrayMultiIter_Type); multi->numiter = n; multi->index = 0; for (i = 0; i < n; i++) { multi->iters[i] = NULL; } for (i = 0; i < n; i++) { arr = PyArray_FromAny(PyTuple_GET_ITEM(args, i), NULL, 0, 0, 0, NULL); if (arr == NULL) { goto fail; } if ((multi->iters[i] = (PyArrayIterObject *)PyArray_IterNew(arr)) == NULL) { goto fail; } Py_DECREF(arr); } if (PyArray_Broadcast(multi) < 0) { goto fail; } PyArray_MultiIter_RESET(multi); return (PyObject *)multi; fail: Py_DECREF(multi); return NULL; } static PyObject * arraymultiter_next(PyArrayMultiIterObject *multi) { PyObject *ret; int i, n; n = multi->numiter; ret = PyTuple_New(n); if (ret == NULL) { return NULL; } if (multi->index < multi->size) { for (i = 0; i < n; i++) { PyArrayIterObject *it=multi->iters[i]; PyTuple_SET_ITEM(ret, i, PyArray_ToScalar(it->dataptr, it->ao)); PyArray_ITER_NEXT(it); } multi->index++; return ret; } Py_DECREF(ret); return NULL; } static void arraymultiter_dealloc(PyArrayMultiIterObject *multi) { int i; for (i = 0; i < multi->numiter; i++) { Py_XDECREF(multi->iters[i]); } Py_TYPE(multi)->tp_free((PyObject *)multi); } static PyObject * arraymultiter_size_get(PyArrayMultiIterObject *self) { #if NPY_SIZEOF_INTP <= NPY_SIZEOF_LONG return PyInt_FromLong((long) self->size); #else if (self->size < NPY_MAX_LONG) { return PyInt_FromLong((long) self->size); } else { return PyLong_FromLongLong((npy_longlong) self->size); } #endif } static PyObject * arraymultiter_index_get(PyArrayMultiIterObject *self) { #if NPY_SIZEOF_INTP <= NPY_SIZEOF_LONG return PyInt_FromLong((long) self->index); #else if (self->size < NPY_MAX_LONG) { return PyInt_FromLong((long) self->index); } else { return PyLong_FromLongLong((npy_longlong) self->index); } #endif } static PyObject * arraymultiter_shape_get(PyArrayMultiIterObject *self) { return PyArray_IntTupleFromIntp(self->nd, self->dimensions); } static PyObject * arraymultiter_iters_get(PyArrayMultiIterObject *self) { PyObject *res; int i, n; n = self->numiter; res = PyTuple_New(n); if (res == NULL) { return res; } for (i = 0; i < n; i++) { Py_INCREF(self->iters[i]); PyTuple_SET_ITEM(res, i, (PyObject *)self->iters[i]); } return res; } static PyGetSetDef arraymultiter_getsetlist[] = { {"size", (getter)arraymultiter_size_get, NULL, NULL, NULL}, {"index", (getter)arraymultiter_index_get, NULL, NULL, NULL}, {"shape", (getter)arraymultiter_shape_get, NULL, NULL, NULL}, {"iters", (getter)arraymultiter_iters_get, NULL, NULL, NULL}, {NULL, NULL, NULL, NULL, NULL}, }; static PyMemberDef arraymultiter_members[] = { {"numiter", T_INT, offsetof(PyArrayMultiIterObject, numiter), READONLY, NULL}, {"nd", T_INT, offsetof(PyArrayMultiIterObject, nd), READONLY, NULL}, {NULL, 0, 0, 0, NULL}, }; static PyObject * arraymultiter_reset(PyArrayMultiIterObject *self, PyObject *args) { if (!PyArg_ParseTuple(args, "")) { return NULL; } PyArray_MultiIter_RESET(self); Py_INCREF(Py_None); return Py_None; } static PyMethodDef arraymultiter_methods[] = { {"reset", (PyCFunction) arraymultiter_reset, METH_VARARGS, NULL}, {NULL, NULL, 0, NULL}, /* sentinal */ }; NPY_NO_EXPORT PyTypeObject PyArrayMultiIter_Type = { #if defined(NPY_PY3K) PyVarObject_HEAD_INIT(NULL, 0) #else PyObject_HEAD_INIT(NULL) 0, /* ob_size */ #endif "numpy.broadcast", /* tp_name */ sizeof(PyArrayMultiIterObject), /* tp_basicsize */ 0, /* tp_itemsize */ /* methods */ (destructor)arraymultiter_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ #if defined(NPY_PY3K) 0, /* tp_reserved */ #else 0, /* tp_compare */ #endif 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT, /* tp_flags */ 0, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ (iternextfunc)arraymultiter_next, /* tp_iternext */ arraymultiter_methods, /* tp_methods */ arraymultiter_members, /* tp_members */ arraymultiter_getsetlist, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc)0, /* tp_init */ 0, /* tp_alloc */ arraymultiter_new, /* 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 */ 0, /* tp_version_tag */ }; /*========================= Neighborhood iterator ======================*/ static void neighiter_dealloc(PyArrayNeighborhoodIterObject* iter); static char* _set_constant(PyArrayNeighborhoodIterObject* iter, PyArrayObject *fill) { char *ret; PyArrayIterObject *ar = iter->_internal_iter; int storeflags, st; ret = PyDataMem_NEW(PyArray_DESCR(ar->ao)->elsize); if (ret == NULL) { PyErr_SetNone(PyExc_MemoryError); return NULL; } if (PyArray_ISOBJECT(ar->ao)) { memcpy(ret, PyArray_DATA(fill), sizeof(PyObject*)); Py_INCREF(*(PyObject**)ret); } else { /* Non-object types */ storeflags = PyArray_FLAGS(ar->ao); PyArray_ENABLEFLAGS(ar->ao, NPY_ARRAY_BEHAVED); st = PyArray_DESCR(ar->ao)->f->setitem((PyObject*)fill, ret, ar->ao); ((PyArrayObject_fields *)ar->ao)->flags = storeflags; if (st < 0) { PyDataMem_FREE(ret); return NULL; } } return ret; } #define _INF_SET_PTR(c) \ bd = coordinates[c] + p->coordinates[c]; \ if (bd < p->limits[c][0] || bd > p->limits[c][1]) { \ return niter->constant; \ } \ _coordinates[c] = bd; /* set the dataptr from its current coordinates */ static char* get_ptr_constant(PyArrayIterObject* _iter, npy_intp *coordinates) { int i; npy_intp bd, _coordinates[NPY_MAXDIMS]; PyArrayNeighborhoodIterObject *niter = (PyArrayNeighborhoodIterObject*)_iter; PyArrayIterObject *p = niter->_internal_iter; for(i = 0; i < niter->nd; ++i) { _INF_SET_PTR(i) } return p->translate(p, _coordinates); } #undef _INF_SET_PTR #define _NPY_IS_EVEN(x) ((x) % 2 == 0) /* For an array x of dimension n, and given index i, returns j, 0 <= j < n * such as x[i] = x[j], with x assumed to be mirrored. For example, for x = * {1, 2, 3} (n = 3) * * index -5 -4 -3 -2 -1 0 1 2 3 4 5 6 * value 2 3 3 2 1 1 2 3 3 2 1 1 * * _npy_pos_index_mirror(4, 3) will return 1, because x[4] = x[1]*/ NPY_INLINE static npy_intp __npy_pos_remainder(npy_intp i, npy_intp n) { npy_intp k, l, j; /* Mirror i such as it is guaranteed to be positive */ if (i < 0) { i = - i - 1; } /* compute k and l such as i = k * n + l, 0 <= l < k */ k = i / n; l = i - k * n; if (_NPY_IS_EVEN(k)) { j = l; } else { j = n - 1 - l; } return j; } #undef _NPY_IS_EVEN #define _INF_SET_PTR_MIRROR(c) \ lb = p->limits[c][0]; \ bd = coordinates[c] + p->coordinates[c] - lb; \ _coordinates[c] = lb + __npy_pos_remainder(bd, p->limits_sizes[c]); /* set the dataptr from its current coordinates */ static char* get_ptr_mirror(PyArrayIterObject* _iter, npy_intp *coordinates) { int i; npy_intp bd, _coordinates[NPY_MAXDIMS], lb; PyArrayNeighborhoodIterObject *niter = (PyArrayNeighborhoodIterObject*)_iter; PyArrayIterObject *p = niter->_internal_iter; for(i = 0; i < niter->nd; ++i) { _INF_SET_PTR_MIRROR(i) } return p->translate(p, _coordinates); } #undef _INF_SET_PTR_MIRROR /* compute l such as i = k * n + l, 0 <= l < |k| */ NPY_INLINE static npy_intp __npy_euclidean_division(npy_intp i, npy_intp n) { npy_intp l; l = i % n; if (l < 0) { l += n; } return l; } #define _INF_SET_PTR_CIRCULAR(c) \ lb = p->limits[c][0]; \ bd = coordinates[c] + p->coordinates[c] - lb; \ _coordinates[c] = lb + __npy_euclidean_division(bd, p->limits_sizes[c]); static char* get_ptr_circular(PyArrayIterObject* _iter, npy_intp *coordinates) { int i; npy_intp bd, _coordinates[NPY_MAXDIMS], lb; PyArrayNeighborhoodIterObject *niter = (PyArrayNeighborhoodIterObject*)_iter; PyArrayIterObject *p = niter->_internal_iter; for(i = 0; i < niter->nd; ++i) { _INF_SET_PTR_CIRCULAR(i) } return p->translate(p, _coordinates); } #undef _INF_SET_PTR_CIRCULAR /* * fill and x->ao should have equivalent types */ /*NUMPY_API * A Neighborhood Iterator object. */ NPY_NO_EXPORT PyObject* PyArray_NeighborhoodIterNew(PyArrayIterObject *x, npy_intp *bounds, int mode, PyArrayObject* fill) { int i; PyArrayNeighborhoodIterObject *ret; ret = PyArray_malloc(sizeof(*ret)); if (ret == NULL) { return NULL; } PyObject_Init((PyObject *)ret, &PyArrayNeighborhoodIter_Type); array_iter_base_init((PyArrayIterObject*)ret, x->ao); Py_INCREF(x); ret->_internal_iter = x; ret->nd = PyArray_NDIM(x->ao); for (i = 0; i < ret->nd; ++i) { ret->dimensions[i] = PyArray_DIMS(x->ao)[i]; } /* Compute the neighborhood size and copy the shape */ ret->size = 1; for (i = 0; i < ret->nd; ++i) { ret->bounds[i][0] = bounds[2 * i]; ret->bounds[i][1] = bounds[2 * i + 1]; ret->size *= (ret->bounds[i][1] - ret->bounds[i][0]) + 1; /* limits keep track of valid ranges for the neighborhood: if a bound * of the neighborhood is outside the array, then limits is the same as * boundaries. On the contrary, if a bound is strictly inside the * array, then limits correspond to the array range. For example, for * an array [1, 2, 3], if bounds are [-1, 3], limits will be [-1, 3], * but if bounds are [1, 2], then limits will be [0, 2]. * * This is used by neighborhood iterators stacked on top of this one */ ret->limits[i][0] = ret->bounds[i][0] < 0 ? ret->bounds[i][0] : 0; ret->limits[i][1] = ret->bounds[i][1] >= ret->dimensions[i] - 1 ? ret->bounds[i][1] : ret->dimensions[i] - 1; ret->limits_sizes[i] = (ret->limits[i][1] - ret->limits[i][0]) + 1; } switch (mode) { case NPY_NEIGHBORHOOD_ITER_ZERO_PADDING: ret->constant = PyArray_Zero(x->ao); ret->mode = mode; ret->translate = &get_ptr_constant; break; case NPY_NEIGHBORHOOD_ITER_ONE_PADDING: ret->constant = PyArray_One(x->ao); ret->mode = mode; ret->translate = &get_ptr_constant; break; case NPY_NEIGHBORHOOD_ITER_CONSTANT_PADDING: /* New reference in returned value of _set_constant if array * object */ assert(PyArray_EquivArrTypes(x->ao, fill) == NPY_TRUE); ret->constant = _set_constant(ret, fill); if (ret->constant == NULL) { goto clean_x; } ret->mode = mode; ret->translate = &get_ptr_constant; break; case NPY_NEIGHBORHOOD_ITER_MIRROR_PADDING: ret->mode = mode; ret->constant = NULL; ret->translate = &get_ptr_mirror; break; case NPY_NEIGHBORHOOD_ITER_CIRCULAR_PADDING: ret->mode = mode; ret->constant = NULL; ret->translate = &get_ptr_circular; break; default: PyErr_SetString(PyExc_ValueError, "Unsupported padding mode"); goto clean_x; } /* * XXX: we force x iterator to be non contiguous because we need * coordinates... Modifying the iterator here is not great */ x->contiguous = 0; PyArrayNeighborhoodIter_Reset(ret); return (PyObject*)ret; clean_x: Py_DECREF(ret->_internal_iter); array_iter_base_dealloc((PyArrayIterObject*)ret); PyArray_free((PyArrayObject*)ret); return NULL; } static void neighiter_dealloc(PyArrayNeighborhoodIterObject* iter) { if (iter->mode == NPY_NEIGHBORHOOD_ITER_CONSTANT_PADDING) { if (PyArray_ISOBJECT(iter->_internal_iter->ao)) { Py_DECREF(*(PyObject**)iter->constant); } } if (iter->constant != NULL) { PyDataMem_FREE(iter->constant); } Py_DECREF(iter->_internal_iter); array_iter_base_dealloc((PyArrayIterObject*)iter); PyArray_free((PyArrayObject*)iter); } NPY_NO_EXPORT PyTypeObject PyArrayNeighborhoodIter_Type = { #if defined(NPY_PY3K) PyVarObject_HEAD_INIT(NULL, 0) #else PyObject_HEAD_INIT(NULL) 0, /* ob_size */ #endif "numpy.neigh_internal_iter", /* tp_name*/ sizeof(PyArrayNeighborhoodIterObject), /* tp_basicsize*/ 0, /* tp_itemsize*/ (destructor)neighiter_dealloc, /* tp_dealloc*/ 0, /* tp_print*/ 0, /* tp_getattr*/ 0, /* tp_setattr*/ #if defined(NPY_PY3K) 0, /* tp_reserved */ #else 0, /* tp_compare */ #endif 0, /* tp_repr*/ 0, /* tp_as_number*/ 0, /* tp_as_sequence*/ 0, /* tp_as_mapping*/ 0, /* tp_hash */ 0, /* tp_call*/ 0, /* tp_str*/ 0, /* tp_getattro*/ 0, /* tp_setattro*/ 0, /* tp_as_buffer*/ Py_TPFLAGS_DEFAULT, /* tp_flags*/ 0, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ (iternextfunc)0, /* tp_iternext */ 0, /* 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 */ (initproc)0, /* tp_init */ 0, /* tp_alloc */ 0, /* 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 */ 0, /* tp_version_tag */ }; numpy-1.8.2/numpy/core/src/multiarray/arrayobject.h0000664000175100017510000000163212370216242023563 0ustar vagrantvagrant00000000000000#ifndef _NPY_INTERNAL_ARRAYOBJECT_H_ #define _NPY_INTERNAL_ARRAYOBJECT_H_ #ifndef _MULTIARRAYMODULE #error You should not include this #endif NPY_NO_EXPORT PyObject * _strings_richcompare(PyArrayObject *self, PyArrayObject *other, int cmp_op, int rstrip); NPY_NO_EXPORT PyObject * array_richcompare(PyArrayObject *self, PyObject *other, int cmp_op); NPY_NO_EXPORT int array_might_be_written(PyArrayObject *obj); /* * This flag is used to mark arrays which we would like to, in the future, * turn into views. It causes a warning to be issued on the first attempt to * write to the array (but the write is allowed to succeed). * * This flag is for internal use only, and may be removed in a future release, * which is why the #define is not exposed to user code. Currently it is set * on arrays returned by ndarray.diagonal. */ static const int NPY_ARRAY_WARN_ON_WRITE = (1 << 31); #endif numpy-1.8.2/numpy/core/src/multiarray/numpymemoryview.c0000664000175100017510000002152012370216242024543 0ustar vagrantvagrant00000000000000/* * Simple PyMemoryView'ish object for Python 2.6 compatibility. * * On Python >= 2.7, we can use the actual PyMemoryView objects. * * Some code copied from the CPython implementation. */ #define PY_SSIZE_T_CLEAN #include #include "structmember.h" #define NPY_NO_DEPRECATED_API NPY_API_VERSION #define _MULTIARRAYMODULE #include "numpy/arrayobject.h" #include "numpy/arrayscalars.h" #include "npy_config.h" #include "npy_pycompat.h" #include "numpymemoryview.h" #if PY_VERSION_HEX < 0x02070000 /* * Memory allocation */ static int memorysimpleview_traverse(PyMemorySimpleViewObject *self, visitproc visit, void *arg) { if (self->base != NULL) Py_VISIT(self->base); if (self->view.obj != NULL) Py_VISIT(self->view.obj); return 0; } static int memorysimpleview_clear(PyMemorySimpleViewObject *self) { Py_CLEAR(self->base); PyBuffer_Release(&self->view); self->view.obj = NULL; return 0; } static void memorysimpleview_dealloc(PyMemorySimpleViewObject *self) { PyObject_GC_UnTrack(self); Py_CLEAR(self->base); if (self->view.obj != NULL) { PyBuffer_Release(&self->view); self->view.obj = NULL; } PyObject_GC_Del(self); } static PyObject * memorysimpleview_new(PyTypeObject *subtype, PyObject *args, PyObject *kwds) { PyObject *obj; static char *kwlist[] = {"object", 0}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "O:memorysimpleview", kwlist, &obj)) { return NULL; } return PyMemorySimpleView_FromObject(obj); } /* * Buffer interface */ static int memorysimpleview_getbuffer(PyMemorySimpleViewObject *self, Py_buffer *view, int flags) { return PyObject_GetBuffer(self->base, view, flags); } static void memorysimpleview_releasebuffer(PyMemorySimpleViewObject *self, Py_buffer *view) { PyBuffer_Release(view); } static PyBufferProcs memorysimpleview_as_buffer = { (readbufferproc)0, /*bf_getreadbuffer*/ (writebufferproc)0, /*bf_getwritebuffer*/ (segcountproc)0, /*bf_getsegcount*/ (charbufferproc)0, /*bf_getcharbuffer*/ (getbufferproc)memorysimpleview_getbuffer, /* bf_getbuffer */ (releasebufferproc)memorysimpleview_releasebuffer, /* bf_releasebuffer */ }; /* * Getters */ static PyObject * _IntTupleFromSsizet(int len, Py_ssize_t *vals) { int i; PyObject *o; PyObject *intTuple; if (vals == NULL) { Py_INCREF(Py_None); return Py_None; } intTuple = PyTuple_New(len); if (!intTuple) return NULL; for(i=0; iview.format); } static PyObject * memorysimpleview_itemsize_get(PyMemorySimpleViewObject *self) { return PyLong_FromSsize_t(self->view.itemsize); } static PyObject * memorysimpleview_shape_get(PyMemorySimpleViewObject *self) { return _IntTupleFromSsizet(self->view.ndim, self->view.shape); } static PyObject * memorysimpleview_strides_get(PyMemorySimpleViewObject *self) { return _IntTupleFromSsizet(self->view.ndim, self->view.strides); } static PyObject * memorysimpleview_suboffsets_get(PyMemorySimpleViewObject *self) { return _IntTupleFromSsizet(self->view.ndim, self->view.suboffsets); } static PyObject * memorysimpleview_readonly_get(PyMemorySimpleViewObject *self) { return PyBool_FromLong(self->view.readonly); } static PyObject * memorysimpleview_ndim_get(PyMemorySimpleViewObject *self) { return PyLong_FromLong(self->view.ndim); } static PyGetSetDef memorysimpleview_getsets[] = { {"format", (getter)memorysimpleview_format_get, NULL, NULL, NULL}, {"itemsize", (getter)memorysimpleview_itemsize_get, NULL, NULL, NULL}, {"shape", (getter)memorysimpleview_shape_get, NULL, NULL, NULL}, {"strides", (getter)memorysimpleview_strides_get, NULL, NULL, NULL}, {"suboffsets", (getter)memorysimpleview_suboffsets_get, NULL, NULL, NULL}, {"readonly", (getter)memorysimpleview_readonly_get, NULL, NULL, NULL}, {"ndim", (getter)memorysimpleview_ndim_get, NULL, NULL, NULL}, {NULL, NULL, NULL, NULL} }; NPY_NO_EXPORT PyTypeObject PyMemorySimpleView_Type = { #if defined(NPY_PY3K) PyVarObject_HEAD_INIT(NULL, 0) #else PyObject_HEAD_INIT(NULL) 0, /* ob_size */ #endif "numpy.memorysimpleview", sizeof(PyMemorySimpleViewObject), 0, /* tp_itemsize */ /* methods */ (destructor)memorysimpleview_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ #if defined(NPY_PY3K) 0, /* tp_reserved */ #else (cmpfunc)0, /* tp_compare */ #endif (reprfunc)0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ (reprfunc)0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ &memorysimpleview_as_buffer, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_HAVE_NEWBUFFER, /* tp_flags */ 0, /* tp_doc */ (traverseproc)memorysimpleview_traverse, /* tp_traverse */ (inquiry)memorysimpleview_clear, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ 0, /* tp_methods */ 0, /* tp_members */ memorysimpleview_getsets, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ memorysimpleview_new, /* 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 */ 0, /* tp_version_tag */ }; /* * Factory */ NPY_NO_EXPORT PyObject * PyMemorySimpleView_FromObject(PyObject *base) { PyMemorySimpleViewObject *mview = NULL; if (Py_TYPE(base)->tp_as_buffer == NULL || Py_TYPE(base)->tp_as_buffer->bf_getbuffer == NULL) { PyErr_SetString(PyExc_TypeError, "cannot make memory view because object does " "not have the buffer interface"); return NULL; } mview = (PyMemorySimpleViewObject *) PyObject_GC_New(PyMemorySimpleViewObject, &PyMemorySimpleView_Type); if (mview == NULL) { return NULL; } 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); PyObject_GC_Track(mview); return (PyObject *)mview; } /* * Module initialization */ NPY_NO_EXPORT int _numpymemoryview_init(PyObject **typeobject) { if (PyType_Ready(&PyMemorySimpleView_Type) < 0) { return -1; } *typeobject = (PyObject*)&PyMemorySimpleView_Type; return 0; } #else NPY_NO_EXPORT int _numpymemoryview_init(PyObject **typeobject) { *typeobject = NULL; return 0; } #endif numpy-1.8.2/numpy/core/src/multiarray/ucsnarrow.c0000664000175100017510000001010512370216242023267 0ustar vagrantvagrant00000000000000#define NPY_NO_DEPRECATED_API NPY_API_VERSION #define PY_SSIZE_T_CLEAN #include #include #include #define _MULTIARRAYMODULE #include "numpy/arrayobject.h" #include "numpy/npy_math.h" #include "npy_config.h" #include "npy_pycompat.h" #include "ctors.h" /* * Functions only needed on narrow builds of Python for converting back and * forth between the NumPy Unicode data-type (always 4-bytes) and the * Python Unicode scalar (2-bytes on a narrow build). */ /* * The ucs2 buffer must be large enough to hold 2*ucs4length characters * due to the use of surrogate pairs. * * The return value is the number of ucs2 bytes used-up which * is ucs4length + number of surrogate pairs found. * * Values above 0xffff are converted to surrogate pairs. */ NPY_NO_EXPORT int PyUCS2Buffer_FromUCS4(Py_UNICODE *ucs2, npy_ucs4 *ucs4, int ucs4length) { int i; int numucs2 = 0; npy_ucs4 chr; for (i = 0; i < ucs4length; i++) { chr = *ucs4++; if (chr > 0xffff) { numucs2++; chr -= 0x10000L; *ucs2++ = 0xD800 + (Py_UNICODE) (chr >> 10); *ucs2++ = 0xDC00 + (Py_UNICODE) (chr & 0x03FF); } else { *ucs2++ = (Py_UNICODE) chr; } numucs2++; } return numucs2; } /* * This converts a UCS2 buffer of the given length to UCS4 buffer. * It converts up to ucs4len characters of UCS2 * * It returns the number of characters converted which can * be less than ucs2len if there are surrogate pairs in ucs2. * * The return value is the actual size of the used part of the ucs4 buffer. */ NPY_NO_EXPORT int PyUCS2Buffer_AsUCS4(Py_UNICODE *ucs2, npy_ucs4 *ucs4, int ucs2len, int ucs4len) { int i; npy_ucs4 chr; Py_UNICODE ch; int numchars=0; for (i = 0; (i < ucs2len) && (numchars < ucs4len); i++) { ch = *ucs2++; if (ch >= 0xd800 && ch <= 0xdfff) { /* surrogate pair */ chr = ((npy_ucs4)(ch-0xd800)) << 10; chr += *ucs2++ + 0x2400; /* -0xdc00 + 0x10000 */ i++; } else { chr = (npy_ucs4) ch; } *ucs4++ = chr; numchars++; } return numchars; } /* * Returns a PyUnicodeObject initialized from a buffer containing * UCS4 unicode. * * Parameters * ---------- * src: char * * Pointer to buffer containing UCS4 unicode. * size: Py_ssize_t * Size of buffer in bytes. * swap: int * If true, the data will be swapped. * align: int * If true, the data will be aligned. * * Returns * ------- * new_reference: PyUnicodeObject */ NPY_NO_EXPORT PyUnicodeObject * PyUnicode_FromUCS4(char *src, Py_ssize_t size, int swap, int align) { Py_ssize_t ucs4len = size / sizeof(npy_ucs4); npy_ucs4 *buf = (npy_ucs4 *)src; int alloc = 0; PyUnicodeObject *ret; /* swap and align if needed */ if (swap || align) { buf = (npy_ucs4 *)malloc(size); if (buf == NULL) { PyErr_NoMemory(); goto fail; } alloc = 1; memcpy(buf, src, size); if (swap) { byte_swap_vector(buf, ucs4len, sizeof(npy_ucs4)); } } /* trim trailing zeros */ while (ucs4len > 0 && buf[ucs4len - 1] == 0) { ucs4len--; } /* produce PyUnicode object */ #ifdef Py_UNICODE_WIDE { ret = (PyUnicodeObject *)PyUnicode_FromUnicode(buf, (Py_ssize_t) ucs4len); if (ret == NULL) { goto fail; } } #else { Py_ssize_t tmpsiz = 2 * sizeof(Py_UNICODE) * ucs4len; Py_ssize_t ucs2len; Py_UNICODE *tmp; if ((tmp = (Py_UNICODE *)malloc(tmpsiz)) == NULL) { PyErr_NoMemory(); goto fail; } ucs2len = PyUCS2Buffer_FromUCS4(tmp, buf, ucs4len); ret = (PyUnicodeObject *)PyUnicode_FromUnicode(tmp, (Py_ssize_t) ucs2len); free(tmp); if (ret == NULL) { goto fail; } } #endif if (alloc) { free(buf); } return ret; fail: if (alloc) { free(buf); } return NULL; } numpy-1.8.2/numpy/core/src/multiarray/flagsobject.c0000664000175100017510000005121712370216242023540 0ustar vagrantvagrant00000000000000/* Array Flags Object */ #define PY_SSIZE_T_CLEAN #include #include "structmember.h" #define NPY_NO_DEPRECATED_API NPY_API_VERSION #define _MULTIARRAYMODULE #include "numpy/arrayobject.h" #include "numpy/arrayscalars.h" #include "npy_config.h" #include "npy_pycompat.h" #include "common.h" static void _UpdateContiguousFlags(PyArrayObject *ap); /*NUMPY_API * * Get New ArrayFlagsObject */ NPY_NO_EXPORT PyObject * PyArray_NewFlagsObject(PyObject *obj) { PyObject *flagobj; int flags; if (obj == NULL) { flags = NPY_ARRAY_C_CONTIGUOUS | NPY_ARRAY_OWNDATA | NPY_ARRAY_F_CONTIGUOUS | NPY_ARRAY_ALIGNED; } else { if (!PyArray_Check(obj)) { PyErr_SetString(PyExc_ValueError, "Need a NumPy array to create a flags object"); return NULL; } flags = PyArray_FLAGS((PyArrayObject *)obj); } flagobj = PyArrayFlags_Type.tp_alloc(&PyArrayFlags_Type, 0); if (flagobj == NULL) { return NULL; } Py_XINCREF(obj); ((PyArrayFlagsObject *)flagobj)->arr = obj; ((PyArrayFlagsObject *)flagobj)->flags = flags; return flagobj; } /*NUMPY_API * Update Several Flags at once. */ NPY_NO_EXPORT void PyArray_UpdateFlags(PyArrayObject *ret, int flagmask) { /* Always update both, as its not trivial to guess one from the other */ if (flagmask & (NPY_ARRAY_F_CONTIGUOUS | NPY_ARRAY_C_CONTIGUOUS)) { _UpdateContiguousFlags(ret); } if (flagmask & NPY_ARRAY_ALIGNED) { if (_IsAligned(ret)) { PyArray_ENABLEFLAGS(ret, NPY_ARRAY_ALIGNED); } else { PyArray_CLEARFLAGS(ret, NPY_ARRAY_ALIGNED); } } /* * This is not checked by default WRITEABLE is not * part of UPDATE_ALL */ if (flagmask & NPY_ARRAY_WRITEABLE) { if (_IsWriteable(ret)) { PyArray_ENABLEFLAGS(ret, NPY_ARRAY_WRITEABLE); } else { PyArray_CLEARFLAGS(ret, NPY_ARRAY_WRITEABLE); } } return; } /* * Check whether the given array is stored contiguously * in memory. And update the passed in ap flags apropriately. * * The traditional rule is that for an array to be flagged as C contiguous, * the following must hold: * * strides[-1] == itemsize * strides[i] == shape[i+1] * strides[i + 1] * * And for an array to be flagged as F contiguous, the obvious reversal: * * strides[0] == itemsize * strides[i] == shape[i - 1] * strides[i - 1] * * According to these rules, a 0- or 1-dimensional array is either both * C- and F-contiguous, or neither; and an array with 2+ dimensions * can be C- or F- contiguous, or neither, but not both. Though there * there are exceptions for arrays with zero or one item, in the first * case the check is relaxed up to and including the first dimension * with shape[i] == 0. In the second case `strides == itemsize` will * can be true for all dimensions and both flags are set. * * When NPY_RELAXED_STRIDES_CHECKING is set, we use a more accurate * definition of C- and F-contiguity, in which all 0-sized arrays are * contiguous (regardless of dimensionality), and if shape[i] == 1 * then we ignore strides[i] (since it has no affect on memory layout). * With these new rules, it is possible for e.g. a 10x1 array to be both * C- and F-contiguous -- but, they break downstream code which assumes * that for contiguous arrays strides[-1] (resp. strides[0]) always * contains the itemsize. */ static void _UpdateContiguousFlags(PyArrayObject *ap) { npy_intp sd; npy_intp dim; int i; npy_bool is_c_contig = 1; sd = PyArray_ITEMSIZE(ap); for (i = PyArray_NDIM(ap) - 1; i >= 0; --i) { dim = PyArray_DIMS(ap)[i]; #if NPY_RELAXED_STRIDES_CHECKING /* contiguous by definition */ if (dim == 0) { PyArray_ENABLEFLAGS(ap, NPY_ARRAY_C_CONTIGUOUS); PyArray_ENABLEFLAGS(ap, NPY_ARRAY_F_CONTIGUOUS); return; } if (dim != 1) { if (PyArray_STRIDES(ap)[i] != sd) { is_c_contig = 0; } sd *= dim; } #else /* not NPY_RELAXED_STRIDES_CHECKING */ if (PyArray_STRIDES(ap)[i] != sd) { is_c_contig = 0; break; } /* contiguous, if it got this far */ if (dim == 0) { break; } sd *= dim; #endif /* not NPY_RELAXED_STRIDES_CHECKING */ } if (is_c_contig) { PyArray_ENABLEFLAGS(ap, NPY_ARRAY_C_CONTIGUOUS); } else { PyArray_CLEARFLAGS(ap, NPY_ARRAY_C_CONTIGUOUS); } /* check if fortran contiguous */ sd = PyArray_ITEMSIZE(ap); for (i = 0; i < PyArray_NDIM(ap); ++i) { dim = PyArray_DIMS(ap)[i]; #if NPY_RELAXED_STRIDES_CHECKING if (dim != 1) { if (PyArray_STRIDES(ap)[i] != sd) { PyArray_CLEARFLAGS(ap, NPY_ARRAY_F_CONTIGUOUS); return; } sd *= dim; } #else /* not NPY_RELAXED_STRIDES_CHECKING */ if (PyArray_STRIDES(ap)[i] != sd) { PyArray_CLEARFLAGS(ap, NPY_ARRAY_F_CONTIGUOUS); return; } if (dim == 0) { break; } sd *= dim; #endif /* not NPY_RELAXED_STRIDES_CHECKING */ } PyArray_ENABLEFLAGS(ap, NPY_ARRAY_F_CONTIGUOUS); return; } static void arrayflags_dealloc(PyArrayFlagsObject *self) { Py_XDECREF(self->arr); Py_TYPE(self)->tp_free((PyObject *)self); } #define _define_get(UPPER, lower) \ static PyObject * \ arrayflags_ ## lower ## _get(PyArrayFlagsObject *self) \ { \ PyObject *item; \ item = ((self->flags & (UPPER)) == (UPPER)) ? Py_True : Py_False; \ Py_INCREF(item); \ return item; \ } _define_get(NPY_ARRAY_C_CONTIGUOUS, contiguous) _define_get(NPY_ARRAY_F_CONTIGUOUS, fortran) _define_get(NPY_ARRAY_UPDATEIFCOPY, updateifcopy) _define_get(NPY_ARRAY_OWNDATA, owndata) _define_get(NPY_ARRAY_ALIGNED, aligned) _define_get(NPY_ARRAY_WRITEABLE, writeable) _define_get(NPY_ARRAY_ALIGNED| NPY_ARRAY_WRITEABLE, behaved) _define_get(NPY_ARRAY_ALIGNED| NPY_ARRAY_WRITEABLE| NPY_ARRAY_C_CONTIGUOUS, carray) static PyObject * arrayflags_forc_get(PyArrayFlagsObject *self) { PyObject *item; if (((self->flags & NPY_ARRAY_F_CONTIGUOUS) == NPY_ARRAY_F_CONTIGUOUS) || ((self->flags & NPY_ARRAY_C_CONTIGUOUS) == NPY_ARRAY_C_CONTIGUOUS)) { item = Py_True; } else { item = Py_False; } Py_INCREF(item); return item; } static PyObject * arrayflags_fnc_get(PyArrayFlagsObject *self) { PyObject *item; if (((self->flags & NPY_ARRAY_F_CONTIGUOUS) == NPY_ARRAY_F_CONTIGUOUS) && !((self->flags & NPY_ARRAY_C_CONTIGUOUS) == NPY_ARRAY_C_CONTIGUOUS)) { item = Py_True; } else { item = Py_False; } Py_INCREF(item); return item; } static PyObject * arrayflags_farray_get(PyArrayFlagsObject *self) { PyObject *item; if (((self->flags & (NPY_ARRAY_ALIGNED| NPY_ARRAY_WRITEABLE| NPY_ARRAY_F_CONTIGUOUS)) != 0) && !((self->flags & NPY_ARRAY_C_CONTIGUOUS) != 0)) { item = Py_True; } else { item = Py_False; } Py_INCREF(item); return item; } static PyObject * arrayflags_num_get(PyArrayFlagsObject *self) { return PyInt_FromLong(self->flags); } /* relies on setflags order being write, align, uic */ static int arrayflags_updateifcopy_set(PyArrayFlagsObject *self, PyObject *obj) { PyObject *res; if (obj == NULL) { PyErr_SetString(PyExc_AttributeError, "Cannot delete flags updateifcopy attribute"); return -1; } if (self->arr == NULL) { PyErr_SetString(PyExc_ValueError, "Cannot set flags on array scalars."); return -1; } res = PyObject_CallMethod(self->arr, "setflags", "OOO", Py_None, Py_None, (PyObject_IsTrue(obj) ? Py_True : Py_False)); if (res == NULL) { return -1; } Py_DECREF(res); return 0; } static int arrayflags_aligned_set(PyArrayFlagsObject *self, PyObject *obj) { PyObject *res; if (obj == NULL) { PyErr_SetString(PyExc_AttributeError, "Cannot delete flags aligned attribute"); return -1; } if (self->arr == NULL) { PyErr_SetString(PyExc_ValueError, "Cannot set flags on array scalars."); return -1; } res = PyObject_CallMethod(self->arr, "setflags", "OOO", Py_None, (PyObject_IsTrue(obj) ? Py_True : Py_False), Py_None); if (res == NULL) { return -1; } Py_DECREF(res); return 0; } static int arrayflags_writeable_set(PyArrayFlagsObject *self, PyObject *obj) { PyObject *res; if (obj == NULL) { PyErr_SetString(PyExc_AttributeError, "Cannot delete flags writeable attribute"); return -1; } if (self->arr == NULL) { PyErr_SetString(PyExc_ValueError, "Cannot set flags on array scalars."); return -1; } res = PyObject_CallMethod(self->arr, "setflags", "OOO", (PyObject_IsTrue(obj) ? Py_True : Py_False), Py_None, Py_None); if (res == NULL) { return -1; } Py_DECREF(res); return 0; } static PyGetSetDef arrayflags_getsets[] = { {"contiguous", (getter)arrayflags_contiguous_get, NULL, NULL, NULL}, {"c_contiguous", (getter)arrayflags_contiguous_get, NULL, NULL, NULL}, {"f_contiguous", (getter)arrayflags_fortran_get, NULL, NULL, NULL}, {"fortran", (getter)arrayflags_fortran_get, NULL, NULL, NULL}, {"updateifcopy", (getter)arrayflags_updateifcopy_get, (setter)arrayflags_updateifcopy_set, NULL, NULL}, {"owndata", (getter)arrayflags_owndata_get, NULL, NULL, NULL}, {"aligned", (getter)arrayflags_aligned_get, (setter)arrayflags_aligned_set, NULL, NULL}, {"writeable", (getter)arrayflags_writeable_get, (setter)arrayflags_writeable_set, NULL, NULL}, {"fnc", (getter)arrayflags_fnc_get, NULL, NULL, NULL}, {"forc", (getter)arrayflags_forc_get, NULL, NULL, NULL}, {"behaved", (getter)arrayflags_behaved_get, NULL, NULL, NULL}, {"carray", (getter)arrayflags_carray_get, NULL, NULL, NULL}, {"farray", (getter)arrayflags_farray_get, NULL, NULL, NULL}, {"num", (getter)arrayflags_num_get, NULL, NULL, NULL}, {NULL, NULL, NULL, NULL, NULL}, }; static PyObject * arrayflags_getitem(PyArrayFlagsObject *self, PyObject *ind) { char *key = NULL; char buf[16]; int n; if (PyUnicode_Check(ind)) { PyObject *tmp_str; tmp_str = PyUnicode_AsASCIIString(ind); if (tmp_str == NULL) { return NULL; } key = PyBytes_AS_STRING(tmp_str); n = PyBytes_GET_SIZE(tmp_str); if (n > 16) { Py_DECREF(tmp_str); goto fail; } memcpy(buf, key, n); Py_DECREF(tmp_str); key = buf; } else if (PyBytes_Check(ind)) { key = PyBytes_AS_STRING(ind); n = PyBytes_GET_SIZE(ind); } else { goto fail; } switch(n) { case 1: switch(key[0]) { case 'C': return arrayflags_contiguous_get(self); case 'F': return arrayflags_fortran_get(self); case 'W': return arrayflags_writeable_get(self); case 'B': return arrayflags_behaved_get(self); case 'O': return arrayflags_owndata_get(self); case 'A': return arrayflags_aligned_get(self); case 'U': return arrayflags_updateifcopy_get(self); default: goto fail; } break; case 2: if (strncmp(key, "CA", n) == 0) { return arrayflags_carray_get(self); } if (strncmp(key, "FA", n) == 0) { return arrayflags_farray_get(self); } break; case 3: if (strncmp(key, "FNC", n) == 0) { return arrayflags_fnc_get(self); } break; case 4: if (strncmp(key, "FORC", n) == 0) { return arrayflags_forc_get(self); } break; case 6: if (strncmp(key, "CARRAY", n) == 0) { return arrayflags_carray_get(self); } if (strncmp(key, "FARRAY", n) == 0) { return arrayflags_farray_get(self); } break; case 7: if (strncmp(key,"FORTRAN",n) == 0) { return arrayflags_fortran_get(self); } if (strncmp(key,"BEHAVED",n) == 0) { return arrayflags_behaved_get(self); } if (strncmp(key,"OWNDATA",n) == 0) { return arrayflags_owndata_get(self); } if (strncmp(key,"ALIGNED",n) == 0) { return arrayflags_aligned_get(self); } break; case 9: if (strncmp(key,"WRITEABLE",n) == 0) { return arrayflags_writeable_get(self); } break; case 10: if (strncmp(key,"CONTIGUOUS",n) == 0) { return arrayflags_contiguous_get(self); } break; case 12: if (strncmp(key, "UPDATEIFCOPY", n) == 0) { return arrayflags_updateifcopy_get(self); } if (strncmp(key, "C_CONTIGUOUS", n) == 0) { return arrayflags_contiguous_get(self); } if (strncmp(key, "F_CONTIGUOUS", n) == 0) { return arrayflags_fortran_get(self); } break; } fail: PyErr_SetString(PyExc_KeyError, "Unknown flag"); return NULL; } static int arrayflags_setitem(PyArrayFlagsObject *self, PyObject *ind, PyObject *item) { char *key; char buf[16]; int n; if (PyUnicode_Check(ind)) { PyObject *tmp_str; tmp_str = PyUnicode_AsASCIIString(ind); key = PyBytes_AS_STRING(tmp_str); n = PyBytes_GET_SIZE(tmp_str); if (n > 16) n = 16; memcpy(buf, key, n); Py_DECREF(tmp_str); key = buf; } else if (PyBytes_Check(ind)) { key = PyBytes_AS_STRING(ind); n = PyBytes_GET_SIZE(ind); } else { goto fail; } if (((n==9) && (strncmp(key, "WRITEABLE", n) == 0)) || ((n==1) && (strncmp(key, "W", n) == 0))) { return arrayflags_writeable_set(self, item); } else if (((n==7) && (strncmp(key, "ALIGNED", n) == 0)) || ((n==1) && (strncmp(key, "A", n) == 0))) { return arrayflags_aligned_set(self, item); } else if (((n==12) && (strncmp(key, "UPDATEIFCOPY", n) == 0)) || ((n==1) && (strncmp(key, "U", n) == 0))) { return arrayflags_updateifcopy_set(self, item); } fail: PyErr_SetString(PyExc_KeyError, "Unknown flag"); return -1; } static char * _torf_(int flags, int val) { if ((flags & val) == val) { return "True"; } else { return "False"; } } static PyObject * arrayflags_print(PyArrayFlagsObject *self) { int fl = self->flags; return PyUString_FromFormat( " %s : %s\n %s : %s\n" " %s : %s\n %s : %s\n" " %s : %s\n %s : %s", "C_CONTIGUOUS", _torf_(fl, NPY_ARRAY_C_CONTIGUOUS), "F_CONTIGUOUS", _torf_(fl, NPY_ARRAY_F_CONTIGUOUS), "OWNDATA", _torf_(fl, NPY_ARRAY_OWNDATA), "WRITEABLE", _torf_(fl, NPY_ARRAY_WRITEABLE), "ALIGNED", _torf_(fl, NPY_ARRAY_ALIGNED), "UPDATEIFCOPY", _torf_(fl, NPY_ARRAY_UPDATEIFCOPY)); } static int arrayflags_compare(PyArrayFlagsObject *self, PyArrayFlagsObject *other) { if (self->flags == other->flags) { return 0; } else if (self->flags < other->flags) { return -1; } else { return 1; } } static PyObject* arrayflags_richcompare(PyObject *self, PyObject *other, int cmp_op) { PyObject *result = Py_NotImplemented; int cmp; if (cmp_op != Py_EQ && cmp_op != Py_NE) { PyErr_SetString(PyExc_TypeError, "undefined comparison for flag object"); return NULL; } if (PyObject_TypeCheck(other, &PyArrayFlags_Type)) { cmp = arrayflags_compare((PyArrayFlagsObject *)self, (PyArrayFlagsObject *)other); if (cmp_op == Py_EQ) { result = (cmp == 0) ? Py_True : Py_False; } else if (cmp_op == Py_NE) { result = (cmp != 0) ? Py_True : Py_False; } } Py_INCREF(result); return result; } static PyMappingMethods arrayflags_as_mapping = { (lenfunc)NULL, /*mp_length*/ (binaryfunc)arrayflags_getitem, /*mp_subscript*/ (objobjargproc)arrayflags_setitem, /*mp_ass_subscript*/ }; static PyObject * arrayflags_new(PyTypeObject *NPY_UNUSED(self), PyObject *args, PyObject *NPY_UNUSED(kwds)) { PyObject *arg=NULL; if (!PyArg_UnpackTuple(args, "flagsobj", 0, 1, &arg)) { return NULL; } if ((arg != NULL) && PyArray_Check(arg)) { return PyArray_NewFlagsObject(arg); } else { return PyArray_NewFlagsObject(NULL); } } NPY_NO_EXPORT PyTypeObject PyArrayFlags_Type = { #if defined(NPY_PY3K) PyVarObject_HEAD_INIT(NULL, 0) #else PyObject_HEAD_INIT(NULL) 0, /* ob_size */ #endif "numpy.flagsobj", sizeof(PyArrayFlagsObject), 0, /* tp_itemsize */ /* methods */ (destructor)arrayflags_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ #if defined(NPY_PY3K) 0, /* tp_reserved */ #else (cmpfunc)arrayflags_compare, /* tp_compare */ #endif (reprfunc)arrayflags_print, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ &arrayflags_as_mapping, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ (reprfunc)arrayflags_print, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT, /* tp_flags */ 0, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ arrayflags_richcompare, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ 0, /* tp_methods */ 0, /* tp_members */ arrayflags_getsets, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ arrayflags_new, /* 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 */ 0, /* tp_version_tag */ }; numpy-1.8.2/numpy/core/src/multiarray/array_assign.c0000664000175100017510000000712712370216242023740 0ustar vagrantvagrant00000000000000/* * This file implements some helper functions for the array assignment * routines. The actual assignment routines are in array_assign_*.c * * Written by Mark Wiebe (mwwiebe@gmail.com) * Copyright (c) 2011 by Enthought, Inc. * * See LICENSE.txt for the license. */ #define PY_SSIZE_T_CLEAN #include #define NPY_NO_DEPRECATED_API NPY_API_VERSION #define _MULTIARRAYMODULE #include #include "npy_config.h" #include "npy_pycompat.h" #include "shape.h" #include "array_assign.h" #include "common.h" #include "lowlevel_strided_loops.h" /* See array_assign.h for parameter documentation */ NPY_NO_EXPORT int broadcast_strides(int ndim, npy_intp *shape, int strides_ndim, npy_intp *strides_shape, npy_intp *strides, char *strides_name, npy_intp *out_strides) { int idim, idim_start = ndim - strides_ndim; /* Can't broadcast to fewer dimensions */ if (idim_start < 0) { goto broadcast_error; } /* * Process from the end to the start, so that 'strides' and 'out_strides' * can point to the same memory. */ for (idim = ndim - 1; idim >= idim_start; --idim) { npy_intp strides_shape_value = strides_shape[idim - idim_start]; /* If it doesn't have dimension one, it must match */ if (strides_shape_value == 1) { out_strides[idim] = 0; } else if (strides_shape_value != shape[idim]) { goto broadcast_error; } else { out_strides[idim] = strides[idim - idim_start]; } } /* New dimensions get a zero stride */ for (idim = 0; idim < idim_start; ++idim) { out_strides[idim] = 0; } return 0; broadcast_error: { PyObject *errmsg; errmsg = PyUString_FromFormat("could not broadcast %s from shape ", strides_name); PyUString_ConcatAndDel(&errmsg, build_shape_string(strides_ndim, strides_shape)); PyUString_ConcatAndDel(&errmsg, PyUString_FromString(" into shape ")); PyUString_ConcatAndDel(&errmsg, build_shape_string(ndim, shape)); PyErr_SetObject(PyExc_ValueError, errmsg); Py_DECREF(errmsg); return -1; } } /* See array_assign.h for parameter documentation */ NPY_NO_EXPORT int raw_array_is_aligned(int ndim, char *data, npy_intp *strides, int alignment) { if (alignment > 1) { npy_intp align_check = (npy_intp)data; int idim; for (idim = 0; idim < ndim; ++idim) { align_check |= strides[idim]; } return npy_is_aligned((void *)align_check, alignment); } else { return 1; } } /* Gets a half-open range [start, end) which contains the array data */ NPY_NO_EXPORT void get_array_memory_extents(PyArrayObject *arr, npy_uintp *out_start, npy_uintp *out_end) { npy_intp low, upper; offset_bounds_from_strides(PyArray_ITEMSIZE(arr), PyArray_NDIM(arr), PyArray_DIMS(arr), PyArray_STRIDES(arr), &low, &upper); *out_start = (npy_uintp)PyArray_DATA(arr) + (npy_uintp)low; *out_end = (npy_uintp)PyArray_DATA(arr) + (npy_uintp)upper; } /* Returns 1 if the arrays have overlapping data, 0 otherwise */ NPY_NO_EXPORT int arrays_overlap(PyArrayObject *arr1, PyArrayObject *arr2) { npy_uintp start1 = 0, start2 = 0, end1 = 0, end2 = 0; get_array_memory_extents(arr1, &start1, &end1); get_array_memory_extents(arr2, &start2, &end2); return (start1 < end2) && (start2 < end1); } numpy-1.8.2/numpy/core/src/multiarray/scalartypes.c.src0000664000175100017510000037070412370216243024403 0ustar vagrantvagrant00000000000000/* -*- c -*- */ #define PY_SSIZE_T_CLEAN #include "Python.h" #include "structmember.h" #define NPY_NO_DEPRECATED_API NPY_API_VERSION #ifndef _MULTIARRAYMODULE #define _MULTIARRAYMODULE #endif #include "numpy/arrayobject.h" #include "numpy/npy_math.h" #include "numpy/halffloat.h" #include "numpy/arrayscalars.h" #include "npy_pycompat.h" #include "npy_config.h" #include "mapping.h" #include "ctors.h" #include "usertypes.h" #include "numpyos.h" #include "common.h" #include "scalartypes.h" #include "_datetime.h" #include "datetime_strings.h" NPY_NO_EXPORT PyBoolScalarObject _PyArrayScalar_BoolValues[] = { {PyObject_HEAD_INIT(&PyBoolArrType_Type) 0}, {PyObject_HEAD_INIT(&PyBoolArrType_Type) 1}, }; /* TimeInteger is deleted, but still here to fill the API slot */ NPY_NO_EXPORT PyTypeObject PyTimeIntegerArrType_Type; /* * Inheritance is established later when tp_bases is set (or tp_base for * single inheritance) */ /**begin repeat * #name = number, integer, signedinteger, unsignedinteger, inexact, * floating, complexfloating, flexible, character# * #NAME = Number, Integer, SignedInteger, UnsignedInteger, Inexact, * Floating, ComplexFloating, Flexible, Character# */ NPY_NO_EXPORT PyTypeObject Py@NAME@ArrType_Type = { #if defined(NPY_PY3K) PyVarObject_HEAD_INIT(NULL, 0) #else PyObject_HEAD_INIT(NULL) 0, /* ob_size */ #endif "numpy.@name@", /* tp_name*/ sizeof(PyObject), /* tp_basicsize*/ 0, /* tp_itemsize */ /* methods */ 0, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ #if defined(NPY_PY3K) 0, /* tp_reserved */ #else 0, /* tp_compare */ #endif 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ 0, /* tp_flags */ 0, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ 0, /* 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 */ 0, /* tp_init */ 0, /* tp_alloc */ 0, /* 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 */ 0, /* tp_version_tag */ }; /**end repeat**/ static PyObject * gentype_alloc(PyTypeObject *type, Py_ssize_t nitems) { PyObject *obj; const size_t size = _PyObject_VAR_SIZE(type, nitems + 1); obj = (PyObject *)PyArray_malloc(size); memset(obj, 0, size); if (type->tp_itemsize == 0) { PyObject_INIT(obj, type); } else { (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems); } return obj; } static void gentype_dealloc(PyObject *v) { Py_TYPE(v)->tp_free(v); } static PyObject * gentype_power(PyObject *m1, PyObject *m2, PyObject *NPY_UNUSED(m3)) { PyObject *arr, *ret, *arg2; char *msg="unsupported operand type(s) for ** or pow()"; if (!PyArray_IsScalar(m1, Generic)) { if (PyArray_Check(m1)) { ret = Py_TYPE(m1)->tp_as_number->nb_power(m1,m2, Py_None); } else { if (!PyArray_IsScalar(m2, Generic)) { PyErr_SetString(PyExc_TypeError, msg); return NULL; } arr = PyArray_FromScalar(m2, NULL); if (arr == NULL) { return NULL; } ret = Py_TYPE(arr)->tp_as_number->nb_power(m1, arr, Py_None); Py_DECREF(arr); } return ret; } if (!PyArray_IsScalar(m2, Generic)) { if (PyArray_Check(m2)) { ret = Py_TYPE(m2)->tp_as_number->nb_power(m1,m2, Py_None); } else { if (!PyArray_IsScalar(m1, Generic)) { PyErr_SetString(PyExc_TypeError, msg); return NULL; } arr = PyArray_FromScalar(m1, NULL); if (arr == NULL) { return NULL; } ret = Py_TYPE(arr)->tp_as_number->nb_power(arr, m2, Py_None); Py_DECREF(arr); } return ret; } arr = arg2 = NULL; arr = PyArray_FromScalar(m1, NULL); arg2 = PyArray_FromScalar(m2, NULL); if (arr == NULL || arg2 == NULL) { Py_XDECREF(arr); Py_XDECREF(arg2); return NULL; } ret = Py_TYPE(arr)->tp_as_number->nb_power(arr, arg2, Py_None); Py_DECREF(arr); Py_DECREF(arg2); return ret; } static PyObject * gentype_generic_method(PyObject *self, PyObject *args, PyObject *kwds, char *str) { PyObject *arr, *meth, *ret; arr = PyArray_FromScalar(self, NULL); if (arr == NULL) { return NULL; } meth = PyObject_GetAttrString(arr, str); if (meth == NULL) { Py_DECREF(arr); return NULL; } if (kwds == NULL) { ret = PyObject_CallObject(meth, args); } else { ret = PyObject_Call(meth, args, kwds); } Py_DECREF(meth); Py_DECREF(arr); if (ret && PyArray_Check(ret)) { return PyArray_Return((PyArrayObject *)ret); } else { return ret; } } /**begin repeat * * #name = add, subtract, remainder, divmod, lshift, rshift, * and, xor, or, floor_divide, true_divide# */ static PyObject * gentype_@name@(PyObject *m1, PyObject *m2) { return PyArray_Type.tp_as_number->nb_@name@(m1, m2); } /**end repeat**/ #if !defined(NPY_PY3K) /**begin repeat * * #name = divide# */ static PyObject * gentype_@name@(PyObject *m1, PyObject *m2) { return PyArray_Type.tp_as_number->nb_@name@(m1, m2); } /**end repeat**/ #endif static PyObject * gentype_multiply(PyObject *m1, PyObject *m2) { PyObject *ret = NULL; long repeat; if (!PyArray_IsScalar(m1, Generic) && ((Py_TYPE(m1)->tp_as_number == NULL) || (Py_TYPE(m1)->tp_as_number->nb_multiply == NULL))) { /* Try to convert m2 to an int and try sequence repeat */ repeat = PyInt_AsLong(m2); if (repeat == -1 && PyErr_Occurred()) { return NULL; } ret = PySequence_Repeat(m1, (int) repeat); } else if (!PyArray_IsScalar(m2, Generic) && ((Py_TYPE(m2)->tp_as_number == NULL) || (Py_TYPE(m2)->tp_as_number->nb_multiply == NULL))) { /* Try to convert m1 to an int and try sequence repeat */ repeat = PyInt_AsLong(m1); if (repeat == -1 && PyErr_Occurred()) { return NULL; } ret = PySequence_Repeat(m2, (int) repeat); } if (ret == NULL) { PyErr_Clear(); /* no effect if not set */ ret = PyArray_Type.tp_as_number->nb_multiply(m1, m2); } return ret; } /**begin repeat * * #name = positive, negative, absolute, invert, int, float# */ static PyObject * gentype_@name@(PyObject *m1) { PyObject *arr, *ret; arr = PyArray_FromScalar(m1, NULL); if (arr == NULL) { return NULL; } ret = Py_TYPE(arr)->tp_as_number->nb_@name@(arr); Py_DECREF(arr); return ret; } /**end repeat**/ #if !defined(NPY_PY3K) /**begin repeat * * #name = long, oct, hex# */ static PyObject * gentype_@name@(PyObject *m1) { PyObject *arr, *ret; arr = PyArray_FromScalar(m1, NULL); if (arr == NULL) { return NULL; } ret = Py_TYPE(arr)->tp_as_number->nb_@name@(arr); Py_DECREF(arr); return ret; } /**end repeat**/ #endif static int gentype_nonzero_number(PyObject *m1) { PyObject *arr; int ret; arr = PyArray_FromScalar(m1, NULL); if (arr == NULL) { return -1; } #if defined(NPY_PY3K) ret = Py_TYPE(arr)->tp_as_number->nb_bool(arr); #else ret = Py_TYPE(arr)->tp_as_number->nb_nonzero(arr); #endif Py_DECREF(arr); return ret; } static PyObject * gentype_str(PyObject *self) { PyObject *arr, *ret = NULL; arr = PyArray_FromScalar(self, NULL); if (arr != NULL) { ret = PyObject_Str((PyObject *)arr); Py_DECREF(arr); } return ret; } static PyObject * gentype_repr(PyObject *self) { PyObject *arr, *ret = NULL; arr = PyArray_FromScalar(self, NULL); if (arr != NULL) { /* XXX: Why are we using str here? */ ret = PyObject_Str((PyObject *)arr); Py_DECREF(arr); } return ret; } /* * The __format__ method for PEP 3101. */ static PyObject * gentype_format(PyObject *self, PyObject *args) { PyObject *format_spec; PyObject *obj, *ret; #if defined(NPY_PY3K) if (!PyArg_ParseTuple(args, "U:__format__", &format_spec)) { return NULL; } #else if (!PyArg_ParseTuple(args, "O:__format__", &format_spec)) { return NULL; } if (!PyUnicode_Check(format_spec) && !PyString_Check(format_spec)) { PyErr_SetString(PyExc_TypeError, "format must be a string"); return NULL; } #endif /* * Convert to an appropriate Python type and call its format. * TODO: For some types, like long double, this isn't right, * because it throws away precision. */ if (Py_TYPE(self) == &PyBoolArrType_Type) { obj = PyBool_FromLong(((PyBoolScalarObject *)self)->obval); } else if (PyArray_IsScalar(self, Integer)) { #if defined(NPY_PY3K) obj = Py_TYPE(self)->tp_as_number->nb_int(self); #else obj = Py_TYPE(self)->tp_as_number->nb_long(self); #endif } else if (PyArray_IsScalar(self, Floating)) { obj = Py_TYPE(self)->tp_as_number->nb_float(self); } else if (PyArray_IsScalar(self, ComplexFloating)) { double val[2]; PyArray_Descr *dtype = PyArray_DescrFromScalar(self); if (dtype == NULL) { return NULL; } if (PyArray_CastScalarDirect(self, dtype, &val[0], NPY_CDOUBLE) < 0) { Py_DECREF(dtype); return NULL; } obj = PyComplex_FromDoubles(val[0], val[1]); Py_DECREF(dtype); } else { obj = PyObject_Str(self); } if (obj == NULL) { return NULL; } ret = PyObject_Format(obj, format_spec); Py_DECREF(obj); return ret; } #ifdef FORCE_NO_LONG_DOUBLE_FORMATTING #undef NPY_LONGDOUBLE_FMT #define NPY_LONGDOUBLE_FMT NPY_DOUBLE_FMT #endif /**begin repeat * #name = float, double, longdouble# * #NAME = FLOAT, DOUBLE, LONGDOUBLE# * #type = npy_float, npy_double, npy_longdouble# * #suff = f, d, l# */ #define _FMT1 "%%.%i" NPY_@NAME@_FMT #define _FMT2 "%%+.%i" NPY_@NAME@_FMT NPY_NO_EXPORT void format_@name@(char *buf, size_t buflen, @type@ val, unsigned int prec) { /* XXX: Find a correct size here for format string */ char format[64], *res; size_t i, cnt; PyOS_snprintf(format, sizeof(format), _FMT1, prec); res = NumPyOS_ascii_format@suff@(buf, buflen, format, val, 0); if (res == NULL) { fprintf(stderr, "Error while formatting\n"); return; } /* If nothing but digits after sign, append ".0" */ cnt = strlen(buf); for (i = (buf[0] == '-') ? 1 : 0; i < cnt; ++i) { if (!isdigit(Py_CHARMASK(buf[i]))) { break; } } if (i == cnt && buflen >= cnt + 3) { strcpy(&buf[cnt],".0"); } } #undef _FMT1 #undef _FMT2 /**end repeat**/ /**begin repeat * #name = cfloat, cdouble, clongdouble# * #NAME = FLOAT, DOUBLE, LONGDOUBLE# * #type = npy_cfloat, npy_cdouble, npy_clongdouble# * #suff = f, d, l# */ #define _FMT1 "%%.%i" NPY_@NAME@_FMT #define _FMT2 "%%+.%i" NPY_@NAME@_FMT static void format_@name@(char *buf, size_t buflen, @type@ val, unsigned int prec) { /* XXX: Find a correct size here for format string */ char format[64]; char *res; /* * Ideally, we should handle this nan/inf stuff in NumpyOS_ascii_format* */ #if PY_VERSION_HEX >= 0x02070000 if (val.real == 0.0 && npy_signbit(val.real) == 0) { #else if (val.real == 0.0) { #endif PyOS_snprintf(format, sizeof(format), _FMT1, prec); res = NumPyOS_ascii_format@suff@(buf, buflen - 1, format, val.imag, 0); if (res == NULL) { /* FIXME * We need a better way to handle the error message */ fprintf(stderr, "Error while formatting\n"); return; } if (!npy_isfinite(val.imag)) { strncat(buf, "*", 1); } strncat(buf, "j", 1); } else { char re[64], im[64]; if (npy_isfinite(val.real)) { PyOS_snprintf(format, sizeof(format), _FMT1, prec); res = NumPyOS_ascii_format@suff@(re, sizeof(re), format, val.real, 0); if (res == NULL) { /* FIXME * We need a better way to handle the error message */ fprintf(stderr, "Error while formatting\n"); return; } } else { if (npy_isnan(val.real)) { strcpy(re, "nan"); } else if (val.real > 0){ strcpy(re, "inf"); } else { strcpy(re, "-inf"); } } if (npy_isfinite(val.imag)) { PyOS_snprintf(format, sizeof(format), _FMT2, prec); res = NumPyOS_ascii_format@suff@(im, sizeof(im), format, val.imag, 0); if (res == NULL) { fprintf(stderr, "Error while formatting\n"); return; } } else { if (npy_isnan(val.imag)) { strcpy(im, "+nan"); } else if (val.imag > 0){ strcpy(im, "+inf"); } else { strcpy(im, "-inf"); } if (!npy_isfinite(val.imag)) { strncat(im, "*", 1); } } PyOS_snprintf(buf, buflen, "(%s%sj)", re, im); } } #undef _FMT1 #undef _FMT2 /**end repeat**/ NPY_NO_EXPORT void format_half(char *buf, size_t buflen, npy_half val, unsigned int prec) { format_float(buf, buflen, npy_half_to_float(val), prec); } /* * over-ride repr and str of array-scalar strings and unicode to * remove NULL bytes and then call the corresponding functions * of string and unicode. */ /**begin repeat * #name = string*2,unicode*2# * #form = (repr,str)*2# * #Name = String*2,Unicode*2# * #NAME = STRING*2,UNICODE*2# * #extra = AndSize*2,,# * #type = npy_char*2, Py_UNICODE*2# */ static PyObject * @name@type_@form@(PyObject *self) { const @type@ *dptr, *ip; int len; PyObject *new; PyObject *ret; ip = dptr = Py@Name@_AS_@NAME@(self); len = Py@Name@_GET_SIZE(self); dptr += len-1; while(len > 0 && *dptr-- == 0) { len--; } new = Py@Name@_From@Name@@extra@(ip, len); if (new == NULL) { return PyUString_FromString(""); } ret = Py@Name@_Type.tp_@form@(new); Py_DECREF(new); return ret; } /**end repeat**/ static PyObject * datetimetype_repr(PyObject *self) { PyDatetimeScalarObject *scal; npy_datetimestruct dts; PyObject *ret; char iso[NPY_DATETIME_MAX_ISO8601_STRLEN]; int local; NPY_DATETIMEUNIT unit; if (!PyArray_IsScalar(self, Datetime)) { PyErr_SetString(PyExc_RuntimeError, "Called NumPy datetime repr on a non-datetime type"); return NULL; } scal = (PyDatetimeScalarObject *)self; if (convert_datetime_to_datetimestruct(&scal->obmeta, scal->obval, &dts) < 0) { return NULL; } local = (scal->obmeta.base > NPY_FR_D); /* * Because we're defaulting to local time, display hours with * minutes precision, so that 30-minute timezone offsets can work. */ unit = scal->obmeta.base; if (unit == NPY_FR_h) { unit = NPY_FR_m; } if (make_iso_8601_datetime(&dts, iso, sizeof(iso), local, unit, -1, NPY_SAFE_CASTING) < 0) { return NULL; } /* * For straight units or generic units, the unit will be deduced * from the string, so it's not necessary to specify it. */ if ((scal->obmeta.num == 1 && scal->obmeta.base != NPY_FR_h) || scal->obmeta.base == NPY_FR_GENERIC) { ret = PyUString_FromString("numpy.datetime64('"); PyUString_ConcatAndDel(&ret, PyUString_FromString(iso)); PyUString_ConcatAndDel(&ret, PyUString_FromString("')")); } else { ret = PyUString_FromString("numpy.datetime64('"); PyUString_ConcatAndDel(&ret, PyUString_FromString(iso)); PyUString_ConcatAndDel(&ret, PyUString_FromString("','")); ret = append_metastr_to_string(&scal->obmeta, 1, ret); PyUString_ConcatAndDel(&ret, PyUString_FromString("')")); } return ret; } static PyObject * timedeltatype_repr(PyObject *self) { PyTimedeltaScalarObject *scal; PyObject *ret; if (!PyArray_IsScalar(self, Timedelta)) { PyErr_SetString(PyExc_RuntimeError, "Called NumPy timedelta repr on a non-datetime type"); return NULL; } scal = (PyTimedeltaScalarObject *)self; /* The value */ if (scal->obval == NPY_DATETIME_NAT) { ret = PyUString_FromString("numpy.timedelta64('NaT'"); } else { /* * Can't use "%lld" in Python < 2.7, Python3 < 3.2, * or if HAVE_LONG_LONG is not defined */ #if defined(HAVE_LONG_LONG) && \ ((PY_VERSION_HEX >= 0x02070000 && PY_VERSION_HEX < 0x03000000) || \ (PY_VERSION_HEX >= 0x03020000)) ret = PyUString_FromFormat("numpy.timedelta64(%lld", (long long)scal->obval); #else ret = PyUString_FromFormat("numpy.timedelta64(%ld", (long)scal->obval); #endif } /* The metadata unit */ if (scal->obmeta.base == NPY_FR_GENERIC) { PyUString_ConcatAndDel(&ret, PyUString_FromString(")")); } else { PyUString_ConcatAndDel(&ret, PyUString_FromString(",'")); ret = append_metastr_to_string(&scal->obmeta, 1, ret); PyUString_ConcatAndDel(&ret, PyUString_FromString("')")); } return ret; } static PyObject * datetimetype_str(PyObject *self) { PyDatetimeScalarObject *scal; npy_datetimestruct dts; char iso[NPY_DATETIME_MAX_ISO8601_STRLEN]; int local; NPY_DATETIMEUNIT unit; if (!PyArray_IsScalar(self, Datetime)) { PyErr_SetString(PyExc_RuntimeError, "Called NumPy datetime str on a non-datetime type"); return NULL; } scal = (PyDatetimeScalarObject *)self; if (convert_datetime_to_datetimestruct(&scal->obmeta, scal->obval, &dts) < 0) { return NULL; } local = (scal->obmeta.base > NPY_FR_D); /* * Because we're defaulting to local time, display hours with * minutes precision, so that 30-minute timezone offsets can work. */ unit = scal->obmeta.base; if (unit == NPY_FR_h) { unit = NPY_FR_m; } if (make_iso_8601_datetime(&dts, iso, sizeof(iso), local, unit, -1, NPY_SAFE_CASTING) < 0) { return NULL; } return PyUString_FromString(iso); } static char *_datetime_verbose_strings[NPY_DATETIME_NUMUNITS] = { "years", "months", "weeks", "", "days", "hours", "minutes", "seconds", "milliseconds", "microseconds", "nanoseconds", "picoseconds", "femtoseconds", "attoseconds", "generic time units" }; static PyObject * timedeltatype_str(PyObject *self) { PyTimedeltaScalarObject *scal; PyObject *ret; char *basestr = "invalid"; if (!PyArray_IsScalar(self, Timedelta)) { PyErr_SetString(PyExc_RuntimeError, "Called NumPy timedelta str on a non-datetime type"); return NULL; } scal = (PyTimedeltaScalarObject *)self; if (scal->obmeta.base >= 0 && scal->obmeta.base < NPY_DATETIME_NUMUNITS) { basestr = _datetime_verbose_strings[scal->obmeta.base]; } else { PyErr_SetString(PyExc_RuntimeError, "NumPy datetime metadata is corrupted"); return NULL; } if (scal->obval == NPY_DATETIME_NAT) { ret = PyUString_FromString("NaT"); } else { /* * Can't use "%lld" in Python < 2.7, Python3 < 3.2, * or if HAVE_LONG_LONG is not defined */ #if defined(HAVE_LONG_LONG) && \ ((PY_VERSION_HEX >= 0x02070000 && PY_VERSION_HEX < 0x03000000) || \ (PY_VERSION_HEX >= 0x03020000)) ret = PyUString_FromFormat("%lld ", (long long)(scal->obval * scal->obmeta.num)); #else ret = PyUString_FromFormat("%ld ", (long)(scal->obval * scal->obmeta.num)); #endif PyUString_ConcatAndDel(&ret, PyUString_FromString(basestr)); } return ret; } /* The REPR values are finfo.precision + 2 */ #define HALFPREC_REPR 5 #define HALFPREC_STR 5 #define FLOATPREC_REPR 8 #define FLOATPREC_STR 6 #define DOUBLEPREC_REPR 17 #define DOUBLEPREC_STR 12 #if NPY_SIZEOF_LONGDOUBLE == NPY_SIZEOF_DOUBLE #define LONGDOUBLEPREC_REPR DOUBLEPREC_REPR #define LONGDOUBLEPREC_STR DOUBLEPREC_STR #else /* More than probably needed on Intel FP */ #define LONGDOUBLEPREC_REPR 20 #define LONGDOUBLEPREC_STR 12 #endif /* * float type str and repr * * These functions will return NULL if PyString creation fails. */ /**begin repeat * #name = half, float, double, longdouble# * #Name = Half, Float, Double, LongDouble# * #NAME = HALF, FLOAT, DOUBLE, LONGDOUBLE# * #hascomplex = 0, 1, 1, 1# */ /**begin repeat1 * #kind = str, repr# * #KIND = STR, REPR# */ #define PREC @NAME@PREC_@KIND@ static PyObject * @name@type_@kind@(PyObject *self) { char buf[100]; npy_@name@ val = ((Py@Name@ScalarObject *)self)->obval; format_@name@(buf, sizeof(buf), val, PREC); return PyUString_FromString(buf); } #if @hascomplex@ static PyObject * c@name@type_@kind@(PyObject *self) { char buf[202]; npy_c@name@ val = ((PyC@Name@ScalarObject *)self)->obval; format_c@name@(buf, sizeof(buf), val, PREC); return PyUString_FromString(buf); } #endif #undef PREC /**end repeat1**/ /**end repeat**/ /* * float type print (control print a, where a is a float type instance) */ /**begin repeat * #name = half, float, double, longdouble# * #Name = Half, Float, Double, LongDouble# * #NAME = HALF, FLOAT, DOUBLE, LONGDOUBLE# * #hascomplex = 0, 1, 1, 1# */ static int @name@type_print(PyObject *v, FILE *fp, int flags) { char buf[100]; npy_@name@ val = ((Py@Name@ScalarObject *)v)->obval; format_@name@(buf, sizeof(buf), val, (flags & Py_PRINT_RAW) ? @NAME@PREC_STR : @NAME@PREC_REPR); Py_BEGIN_ALLOW_THREADS fputs(buf, fp); Py_END_ALLOW_THREADS return 0; } #if @hascomplex@ static int c@name@type_print(PyObject *v, FILE *fp, int flags) { /* Size of buf: twice sizeof(real) + 2 (for the parenthesis) */ char buf[202]; npy_c@name@ val = ((PyC@Name@ScalarObject *)v)->obval; format_c@name@(buf, sizeof(buf), val, (flags & Py_PRINT_RAW) ? @NAME@PREC_STR : @NAME@PREC_REPR); Py_BEGIN_ALLOW_THREADS fputs(buf, fp); Py_END_ALLOW_THREADS return 0; } #endif /**end repeat**/ /* * Could improve this with a PyLong_FromLongDouble(longdouble ldval) * but this would need some more work... */ /**begin repeat * * #name = (int, float)*2# * #KIND = (Long, Float)*2# * #char = ,,c*2# * #CHAR = ,,C*2# * #POST = ,,.real*2# */ static PyObject * @char@longdoubletype_@name@(PyObject *self) { double dval; PyObject *obj, *ret; dval = (double)(((Py@CHAR@LongDoubleScalarObject *)self)->obval)@POST@; obj = Py@KIND@_FromDouble(dval); ret = Py_TYPE(obj)->tp_as_number->nb_@name@(obj); Py_DECREF(obj); return ret; } /**end repeat**/ #if !defined(NPY_PY3K) /**begin repeat * * #name = (long, hex, oct)*2# * #KIND = (Long*3)*2# * #char = ,,,c*3# * #CHAR = ,,,C*3# * #POST = ,,,.real*3# */ static PyObject * @char@longdoubletype_@name@(PyObject *self) { double dval; PyObject *obj, *ret; dval = (double)(((Py@CHAR@LongDoubleScalarObject *)self)->obval)@POST@; obj = Py@KIND@_FromDouble(dval); ret = Py_TYPE(obj)->tp_as_number->nb_@name@(obj); Py_DECREF(obj); return ret; } /**end repeat**/ #endif /* !defined(NPY_PY3K) */ static PyNumberMethods gentype_as_number = { (binaryfunc)gentype_add, /*nb_add*/ (binaryfunc)gentype_subtract, /*nb_subtract*/ (binaryfunc)gentype_multiply, /*nb_multiply*/ #if defined(NPY_PY3K) #else (binaryfunc)gentype_divide, /*nb_divide*/ #endif (binaryfunc)gentype_remainder, /*nb_remainder*/ (binaryfunc)gentype_divmod, /*nb_divmod*/ (ternaryfunc)gentype_power, /*nb_power*/ (unaryfunc)gentype_negative, (unaryfunc)gentype_positive, /*nb_pos*/ (unaryfunc)gentype_absolute, /*(unaryfunc)gentype_abs,*/ (inquiry)gentype_nonzero_number, /*nb_nonzero*/ (unaryfunc)gentype_invert, /*nb_invert*/ (binaryfunc)gentype_lshift, /*nb_lshift*/ (binaryfunc)gentype_rshift, /*nb_rshift*/ (binaryfunc)gentype_and, /*nb_and*/ (binaryfunc)gentype_xor, /*nb_xor*/ (binaryfunc)gentype_or, /*nb_or*/ #if defined(NPY_PY3K) #else 0, /*nb_coerce*/ #endif (unaryfunc)gentype_int, /*nb_int*/ #if defined(NPY_PY3K) 0, /*nb_reserved*/ #else (unaryfunc)gentype_long, /*nb_long*/ #endif (unaryfunc)gentype_float, /*nb_float*/ #if defined(NPY_PY3K) #else (unaryfunc)gentype_oct, /*nb_oct*/ (unaryfunc)gentype_hex, /*nb_hex*/ #endif 0, /*inplace_add*/ 0, /*inplace_subtract*/ 0, /*inplace_multiply*/ #if defined(NPY_PY3K) #else 0, /*inplace_divide*/ #endif 0, /*inplace_remainder*/ 0, /*inplace_power*/ 0, /*inplace_lshift*/ 0, /*inplace_rshift*/ 0, /*inplace_and*/ 0, /*inplace_xor*/ 0, /*inplace_or*/ (binaryfunc)gentype_floor_divide, /*nb_floor_divide*/ (binaryfunc)gentype_true_divide, /*nb_true_divide*/ 0, /*nb_inplace_floor_divide*/ 0, /*nb_inplace_true_divide*/ (unaryfunc)NULL, /*nb_index*/ }; static PyObject * gentype_richcompare(PyObject *self, PyObject *other, int cmp_op) { PyObject *arr, *ret; arr = PyArray_FromScalar(self, NULL); if (arr == NULL) { return NULL; } ret = Py_TYPE(arr)->tp_richcompare(arr, other, cmp_op); Py_DECREF(arr); return ret; } static PyObject * gentype_ndim_get(PyObject *NPY_UNUSED(self)) { return PyInt_FromLong(0); } static PyObject * gentype_flags_get(PyObject *NPY_UNUSED(self)) { return PyArray_NewFlagsObject(NULL); } static PyObject * voidtype_flags_get(PyVoidScalarObject *self) { PyObject *flagobj; flagobj = PyArrayFlags_Type.tp_alloc(&PyArrayFlags_Type, 0); if (flagobj == NULL) { return NULL; } ((PyArrayFlagsObject *)flagobj)->arr = NULL; ((PyArrayFlagsObject *)flagobj)->flags = self->flags; return flagobj; } static PyObject * voidtype_dtypedescr_get(PyVoidScalarObject *self) { Py_INCREF(self->descr); return (PyObject *)self->descr; } static PyObject * gentype_data_get(PyObject *self) { #if defined(NPY_PY3K) return PyMemoryView_FromObject(self); #else return PyBuffer_FromObject(self, 0, Py_END_OF_BUFFER); #endif } static PyObject * gentype_itemsize_get(PyObject *self) { PyArray_Descr *typecode; PyObject *ret; int elsize; typecode = PyArray_DescrFromScalar(self); elsize = typecode->elsize; #ifndef Py_UNICODE_WIDE if (typecode->type_num == NPY_UNICODE) { elsize >>= 1; } #endif ret = PyInt_FromLong((long) elsize); Py_DECREF(typecode); return ret; } static PyObject * gentype_size_get(PyObject *NPY_UNUSED(self)) { return PyInt_FromLong(1); } #if PY_VERSION_HEX >= 0x03000000 NPY_NO_EXPORT void gentype_struct_free(PyObject *ptr) { PyArrayInterface *arrif; PyObject *context; arrif = (PyArrayInterface*)PyCapsule_GetPointer(ptr, NULL); context = (PyObject *)PyCapsule_GetContext(ptr); Py_DECREF(context); Py_XDECREF(arrif->descr); PyArray_free(arrif->shape); PyArray_free(arrif); } #else NPY_NO_EXPORT void gentype_struct_free(void *ptr, void *arg) { PyArrayInterface *arrif = (PyArrayInterface *)ptr; Py_DECREF((PyObject *)arg); Py_XDECREF(arrif->descr); PyArray_free(arrif->shape); PyArray_free(arrif); } #endif static PyObject * gentype_struct_get(PyObject *self) { PyArrayObject *arr; PyArrayInterface *inter; PyObject *ret; arr = (PyArrayObject *)PyArray_FromScalar(self, NULL); inter = (PyArrayInterface *)PyArray_malloc(sizeof(PyArrayInterface)); inter->two = 2; inter->nd = 0; inter->flags = PyArray_FLAGS(arr); inter->flags &= ~(NPY_ARRAY_UPDATEIFCOPY | NPY_ARRAY_OWNDATA); inter->flags |= NPY_ARRAY_NOTSWAPPED; inter->typekind = PyArray_DESCR(arr)->kind; inter->itemsize = PyArray_DESCR(arr)->elsize; inter->strides = NULL; inter->shape = NULL; inter->data = PyArray_DATA(arr); inter->descr = NULL; ret = NpyCapsule_FromVoidPtrAndDesc(inter, arr, gentype_struct_free); return ret; } static PyObject * gentype_priority_get(PyObject *NPY_UNUSED(self)) { return PyFloat_FromDouble(NPY_SCALAR_PRIORITY); } static PyObject * gentype_shape_get(PyObject *NPY_UNUSED(self)) { return PyTuple_New(0); } static PyObject * gentype_interface_get(PyObject *self) { PyArrayObject *arr; PyObject *inter; arr = (PyArrayObject *)PyArray_FromScalar(self, NULL); if (arr == NULL) { return NULL; } inter = PyObject_GetAttrString((PyObject *)arr, "__array_interface__"); if (inter != NULL) { PyDict_SetItemString(inter, "__ref", (PyObject *)arr); } Py_DECREF(arr); return inter; } static PyObject * gentype_typedescr_get(PyObject *self) { return (PyObject *)PyArray_DescrFromScalar(self); } static PyObject * gentype_base_get(PyObject *NPY_UNUSED(self)) { Py_INCREF(Py_None); return Py_None; } static PyArray_Descr * _realdescr_fromcomplexscalar(PyObject *self, int *typenum) { if (PyArray_IsScalar(self, CDouble)) { *typenum = NPY_CDOUBLE; return PyArray_DescrFromType(NPY_DOUBLE); } if (PyArray_IsScalar(self, CFloat)) { *typenum = NPY_CFLOAT; return PyArray_DescrFromType(NPY_FLOAT); } if (PyArray_IsScalar(self, CLongDouble)) { *typenum = NPY_CLONGDOUBLE; return PyArray_DescrFromType(NPY_LONGDOUBLE); } return NULL; } static PyObject * gentype_real_get(PyObject *self) { PyArray_Descr *typecode; PyObject *ret; int typenum; if (PyArray_IsScalar(self, ComplexFloating)) { void *ptr; typecode = _realdescr_fromcomplexscalar(self, &typenum); ptr = scalar_value(self, NULL); ret = PyArray_Scalar(ptr, typecode, NULL); Py_DECREF(typecode); return ret; } else if (PyArray_IsScalar(self, Object)) { PyObject *obj = ((PyObjectScalarObject *)self)->obval; ret = PyObject_GetAttrString(obj, "real"); if (ret != NULL) { return ret; } PyErr_Clear(); } Py_INCREF(self); return (PyObject *)self; } static PyObject * gentype_imag_get(PyObject *self) { PyArray_Descr *typecode=NULL; PyObject *ret; int typenum; if (PyArray_IsScalar(self, ComplexFloating)) { char *ptr; typecode = _realdescr_fromcomplexscalar(self, &typenum); ptr = (char *)scalar_value(self, NULL); ret = PyArray_Scalar(ptr + typecode->elsize, typecode, NULL); } else if (PyArray_IsScalar(self, Object)) { PyObject *obj = ((PyObjectScalarObject *)self)->obval; PyArray_Descr *newtype; ret = PyObject_GetAttrString(obj, "imag"); if (ret == NULL) { PyErr_Clear(); obj = PyInt_FromLong(0); newtype = PyArray_DescrFromType(NPY_OBJECT); ret = PyArray_Scalar((char *)&obj, newtype, NULL); Py_DECREF(newtype); Py_DECREF(obj); } } else { char *temp; int elsize; typecode = PyArray_DescrFromScalar(self); elsize = typecode->elsize; temp = PyDataMem_NEW(elsize); memset(temp, '\0', elsize); ret = PyArray_Scalar(temp, typecode, NULL); PyDataMem_FREE(temp); } Py_XDECREF(typecode); return ret; } static PyObject * gentype_flat_get(PyObject *self) { PyObject *ret, *arr; arr = PyArray_FromScalar(self, NULL); if (arr == NULL) { return NULL; } ret = PyArray_IterNew(arr); Py_DECREF(arr); return ret; } static PyObject * gentype_transpose_get(PyObject *self) { Py_INCREF(self); return self; } static PyGetSetDef gentype_getsets[] = { {"ndim", (getter)gentype_ndim_get, (setter) 0, "number of array dimensions", NULL}, {"flags", (getter)gentype_flags_get, (setter)0, "integer value of flags", NULL}, {"shape", (getter)gentype_shape_get, (setter)0, "tuple of array dimensions", NULL}, {"strides", (getter)gentype_shape_get, (setter) 0, "tuple of bytes steps in each dimension", NULL}, {"data", (getter)gentype_data_get, (setter) 0, "pointer to start of data", NULL}, {"itemsize", (getter)gentype_itemsize_get, (setter)0, "length of one element in bytes", NULL}, {"size", (getter)gentype_size_get, (setter)0, "number of elements in the gentype", NULL}, {"nbytes", (getter)gentype_itemsize_get, (setter)0, "length of item in bytes", NULL}, {"base", (getter)gentype_base_get, (setter)0, "base object", NULL}, {"dtype", (getter)gentype_typedescr_get, NULL, "get array data-descriptor", NULL}, {"real", (getter)gentype_real_get, (setter)0, "real part of scalar", NULL}, {"imag", (getter)gentype_imag_get, (setter)0, "imaginary part of scalar", NULL}, {"flat", (getter)gentype_flat_get, (setter)0, "a 1-d view of scalar", NULL}, {"T", (getter)gentype_transpose_get, (setter)0, "transpose", NULL}, {"__array_interface__", (getter)gentype_interface_get, NULL, "Array protocol: Python side", NULL}, {"__array_struct__", (getter)gentype_struct_get, NULL, "Array protocol: struct", NULL}, {"__array_priority__", (getter)gentype_priority_get, NULL, "Array priority.", NULL}, {NULL, NULL, NULL, NULL, NULL} /* Sentinel */ }; /* 0-dim array from scalar object */ static char doc_getarray[] = "sc.__array__(|type) return 0-dim array"; static PyObject * gentype_getarray(PyObject *scalar, PyObject *args) { PyArray_Descr *outcode=NULL; PyObject *ret; if (!PyArg_ParseTuple(args, "|O&", &PyArray_DescrConverter, &outcode)) { Py_XDECREF(outcode); return NULL; } ret = PyArray_FromScalar(scalar, outcode); return ret; } static char doc_sc_wraparray[] = "sc.__array_wrap__(obj) return scalar from array"; static PyObject * gentype_wraparray(PyObject *NPY_UNUSED(scalar), PyObject *args) { PyObject *obj; PyArrayObject *arr; if (PyTuple_Size(args) < 1) { PyErr_SetString(PyExc_TypeError, "only accepts 1 argument."); return NULL; } obj = PyTuple_GET_ITEM(args, 0); if (!PyArray_Check(obj)) { PyErr_SetString(PyExc_TypeError, "can only be called with ndarray object"); return NULL; } arr = (PyArrayObject *)obj; return PyArray_Scalar(PyArray_DATA(arr), PyArray_DESCR(arr), (PyObject *)arr); } /* * These gentype_* functions do not take keyword arguments. * The proper flag is METH_VARARGS. */ /**begin repeat * * #name = tolist, item, tostring, astype, copy, __deepcopy__, searchsorted, * view, swapaxes, conj, conjugate, nonzero, flatten, ravel, fill, * transpose, newbyteorder# */ static PyObject * gentype_@name@(PyObject *self, PyObject *args) { return gentype_generic_method(self, args, NULL, "@name@"); } /**end repeat**/ static PyObject * gentype_itemset(PyObject *NPY_UNUSED(self), PyObject *NPY_UNUSED(args)) { PyErr_SetString(PyExc_ValueError, "array-scalars are immutable"); return NULL; } static PyObject * gentype_squeeze(PyObject *self, PyObject *args) { if (!PyArg_ParseTuple(args, "")) { return NULL; } Py_INCREF(self); return self; } static Py_ssize_t gentype_getreadbuf(PyObject *, Py_ssize_t, void **); static PyObject * gentype_byteswap(PyObject *self, PyObject *args) { npy_bool inplace = NPY_FALSE; if (!PyArg_ParseTuple(args, "|O&", PyArray_BoolConverter, &inplace)) { return NULL; } if (inplace) { PyErr_SetString(PyExc_ValueError, "cannot byteswap a scalar in-place"); return NULL; } else { /* get the data, copyswap it and pass it to a new Array scalar */ char *data; PyArray_Descr *descr; PyObject *new; char *newmem; gentype_getreadbuf(self, 0, (void **)&data); descr = PyArray_DescrFromScalar(self); newmem = PyArray_malloc(descr->elsize); if (newmem == NULL) { Py_DECREF(descr); return PyErr_NoMemory(); } else { descr->f->copyswap(newmem, data, 1, NULL); } new = PyArray_Scalar(newmem, descr, NULL); PyArray_free(newmem); Py_DECREF(descr); return new; } } /* * These gentype_* functions take keyword arguments. * The proper flag is METH_VARARGS | METH_KEYWORDS. */ /**begin repeat * * #name = take, getfield, put, repeat, tofile, mean, trace, diagonal, clip, * std, var, sum, cumsum, prod, cumprod, compress, sort, argsort, * round, argmax, argmin, max, min, ptp, any, all, resize, reshape, * choose# */ static PyObject * gentype_@name@(PyObject *self, PyObject *args, PyObject *kwds) { return gentype_generic_method(self, args, kwds, "@name@"); } /**end repeat**/ static PyObject * voidtype_getfield(PyVoidScalarObject *self, PyObject *args, PyObject *kwds) { PyObject *ret, *newargs; newargs = PyTuple_GetSlice(args, 0, 2); if (newargs == NULL) { return NULL; } ret = gentype_generic_method((PyObject *)self, newargs, kwds, "getfield"); Py_DECREF(newargs); if (!ret) { return ret; } if (PyArray_IsScalar(ret, Generic) && \ (!PyArray_IsScalar(ret, Void))) { PyArray_Descr *new; void *ptr; if (!PyArray_ISNBO(self->descr->byteorder)) { new = PyArray_DescrFromScalar(ret); ptr = scalar_value(ret, new); byte_swap_vector(ptr, 1, new->elsize); Py_DECREF(new); } } return ret; } static PyObject * gentype_setfield(PyObject *NPY_UNUSED(self), PyObject *NPY_UNUSED(args), PyObject *NPY_UNUSED(kwds)) { PyErr_SetString(PyExc_TypeError, "Can't set fields in a non-void array scalar."); return NULL; } static PyObject * voidtype_setfield(PyVoidScalarObject *self, PyObject *args, PyObject *kwds) { PyArray_Descr *typecode = NULL; int offset = 0; PyObject *value; PyArrayObject *src; int mysize; char *dptr; static char *kwlist[] = {"value", "dtype", "offset", 0}; if ((self->flags & NPY_ARRAY_WRITEABLE) != NPY_ARRAY_WRITEABLE) { PyErr_SetString(PyExc_RuntimeError, "Can't write to memory"); return NULL; } if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO&|i", kwlist, &value, PyArray_DescrConverter, &typecode, &offset)) { Py_XDECREF(typecode); return NULL; } mysize = Py_SIZE(self); if (offset < 0 || (offset + typecode->elsize) > mysize) { PyErr_Format(PyExc_ValueError, "Need 0 <= offset <= %d for requested type " \ "but received offset = %d", mysize-typecode->elsize, offset); Py_DECREF(typecode); return NULL; } dptr = self->obval + offset; if (typecode->type_num == NPY_OBJECT) { PyObject *temp; Py_INCREF(value); NPY_COPY_PYOBJECT_PTR(&temp, dptr); Py_XDECREF(temp); NPY_COPY_PYOBJECT_PTR(dptr, &value); Py_DECREF(typecode); } else { /* Copy data from value to correct place in dptr */ src = (PyArrayObject *)PyArray_FromAny(value, typecode, 0, 0, NPY_ARRAY_CARRAY, NULL); if (src == NULL) { return NULL; } typecode->f->copyswap(dptr, PyArray_DATA(src), !PyArray_ISNBO(self->descr->byteorder), src); Py_DECREF(src); } Py_INCREF(Py_None); return Py_None; } static PyObject * gentype_reduce(PyObject *self, PyObject *NPY_UNUSED(args)) { PyObject *ret = NULL, *obj = NULL, *mod = NULL; const char *buffer; Py_ssize_t buflen; /* Return a tuple of (callable object, arguments) */ ret = PyTuple_New(2); if (ret == NULL) { return NULL; } #if defined(NPY_PY3K) if (PyArray_IsScalar(self, Unicode)) { /* Unicode on Python 3 does not expose the buffer interface */ buffer = PyUnicode_AS_DATA(self); buflen = PyUnicode_GET_DATA_SIZE(self); } else #endif if (PyObject_AsReadBuffer(self, (const void **)&buffer, &buflen)<0) { Py_DECREF(ret); return NULL; } mod = PyImport_ImportModule("numpy.core.multiarray"); if (mod == NULL) { return NULL; } obj = PyObject_GetAttrString(mod, "scalar"); Py_DECREF(mod); if (obj == NULL) { return NULL; } PyTuple_SET_ITEM(ret, 0, obj); obj = PyObject_GetAttrString((PyObject *)self, "dtype"); if (PyArray_IsScalar(self, Object)) { mod = ((PyObjectScalarObject *)self)->obval; PyTuple_SET_ITEM(ret, 1, Py_BuildValue("NO", obj, mod)); } else { #ifndef Py_UNICODE_WIDE /* * We need to expand the buffer so that we always write * UCS4 to disk for pickle of unicode scalars. * * This could be in a unicode_reduce function, but * that would require re-factoring. */ int alloc = 0; char *tmp; int newlen; if (PyArray_IsScalar(self, Unicode)) { tmp = PyArray_malloc(buflen*2); if (tmp == NULL) { Py_DECREF(ret); return PyErr_NoMemory(); } alloc = 1; newlen = PyUCS2Buffer_AsUCS4((Py_UNICODE *)buffer, (npy_ucs4 *)tmp, buflen / 2, buflen / 2); buflen = newlen*4; buffer = tmp; } #endif mod = PyBytes_FromStringAndSize(buffer, buflen); if (mod == NULL) { Py_DECREF(ret); #ifndef Py_UNICODE_WIDE ret = NULL; goto fail; #else return NULL; #endif } PyTuple_SET_ITEM(ret, 1, Py_BuildValue("NN", obj, mod)); #ifndef Py_UNICODE_WIDE fail: if (alloc) PyArray_free((char *)buffer); #endif } return ret; } /* ignores everything */ static PyObject * gentype_setstate(PyObject *NPY_UNUSED(self), PyObject *NPY_UNUSED(args)) { Py_INCREF(Py_None); return (Py_None); } static PyObject * gentype_dump(PyObject *self, PyObject *args) { PyObject *file = NULL; int ret; if (!PyArg_ParseTuple(args, "O", &file)) { return NULL; } ret = PyArray_Dump(self, file, 2); if (ret < 0) { return NULL; } Py_INCREF(Py_None); return Py_None; } static PyObject * gentype_dumps(PyObject *self, PyObject *args) { if (!PyArg_ParseTuple(args, "")) { return NULL; } return PyArray_Dumps(self, 2); } /* setting flags cannot be done for scalars */ static PyObject * gentype_setflags(PyObject *NPY_UNUSED(self), PyObject *NPY_UNUSED(args), PyObject *NPY_UNUSED(kwds)) { Py_INCREF(Py_None); return Py_None; } /* * casting complex numbers (that don't inherit from Python complex) * to Python complex */ /**begin repeat * #name = cfloat, clongdouble# * #Name = CFloat, CLongDouble# */ static PyObject * @name@_complex(PyObject *self, PyObject *NPY_UNUSED(args), PyObject *NPY_UNUSED(kwds)) { return PyComplex_FromDoubles(PyArrayScalar_VAL(self, @Name@).real, PyArrayScalar_VAL(self, @Name@).imag); } /**end repeat**/ /* * need to fill in doc-strings for these methods on import -- copy from * array docstrings */ static PyMethodDef gentype_methods[] = { {"tolist", (PyCFunction)gentype_tolist, METH_VARARGS, NULL}, {"item", (PyCFunction)gentype_item, METH_VARARGS, NULL}, {"itemset", (PyCFunction)gentype_itemset, METH_VARARGS, NULL}, {"tofile", (PyCFunction)gentype_tofile, METH_VARARGS | METH_KEYWORDS, NULL}, {"tostring", (PyCFunction)gentype_tostring, METH_VARARGS, NULL}, {"byteswap", (PyCFunction)gentype_byteswap, METH_VARARGS, NULL}, {"astype", (PyCFunction)gentype_astype, METH_VARARGS, NULL}, {"getfield", (PyCFunction)gentype_getfield, METH_VARARGS | METH_KEYWORDS, NULL}, {"setfield", (PyCFunction)gentype_setfield, METH_VARARGS | METH_KEYWORDS, NULL}, {"copy", (PyCFunction)gentype_copy, METH_VARARGS, NULL}, {"resize", (PyCFunction)gentype_resize, METH_VARARGS | METH_KEYWORDS, NULL}, {"__array__", (PyCFunction)gentype_getarray, METH_VARARGS, doc_getarray}, {"__array_wrap__", (PyCFunction)gentype_wraparray, METH_VARARGS, doc_sc_wraparray}, /* for the copy module */ {"__copy__", (PyCFunction)gentype_copy, METH_VARARGS, NULL}, {"__deepcopy__", (PyCFunction)gentype___deepcopy__, METH_VARARGS, NULL}, {"__reduce__", (PyCFunction) gentype_reduce, METH_VARARGS, NULL}, /* For consistency does nothing */ {"__setstate__", (PyCFunction) gentype_setstate, METH_VARARGS, NULL}, {"dumps", (PyCFunction) gentype_dumps, METH_VARARGS, NULL}, {"dump", (PyCFunction) gentype_dump, METH_VARARGS, NULL}, /* Methods for array */ {"fill", (PyCFunction)gentype_fill, METH_VARARGS, NULL}, {"transpose", (PyCFunction)gentype_transpose, METH_VARARGS, NULL}, {"take", (PyCFunction)gentype_take, METH_VARARGS | METH_KEYWORDS, NULL}, {"put", (PyCFunction)gentype_put, METH_VARARGS | METH_KEYWORDS, NULL}, {"repeat", (PyCFunction)gentype_repeat, METH_VARARGS | METH_KEYWORDS, NULL}, {"choose", (PyCFunction)gentype_choose, METH_VARARGS | METH_KEYWORDS, NULL}, {"sort", (PyCFunction)gentype_sort, METH_VARARGS | METH_KEYWORDS, NULL}, {"argsort", (PyCFunction)gentype_argsort, METH_VARARGS | METH_KEYWORDS, NULL}, {"searchsorted", (PyCFunction)gentype_searchsorted, METH_VARARGS, NULL}, {"argmax", (PyCFunction)gentype_argmax, METH_VARARGS | METH_KEYWORDS, NULL}, {"argmin", (PyCFunction)gentype_argmin, METH_VARARGS | METH_KEYWORDS, NULL}, {"reshape", (PyCFunction)gentype_reshape, METH_VARARGS | METH_KEYWORDS, NULL}, {"squeeze", (PyCFunction)gentype_squeeze, METH_VARARGS, NULL}, {"view", (PyCFunction)gentype_view, METH_VARARGS, NULL}, {"swapaxes", (PyCFunction)gentype_swapaxes, METH_VARARGS, NULL}, {"max", (PyCFunction)gentype_max, METH_VARARGS | METH_KEYWORDS, NULL}, {"min", (PyCFunction)gentype_min, METH_VARARGS | METH_KEYWORDS, NULL}, {"ptp", (PyCFunction)gentype_ptp, METH_VARARGS | METH_KEYWORDS, NULL}, {"mean", (PyCFunction)gentype_mean, METH_VARARGS | METH_KEYWORDS, NULL}, {"trace", (PyCFunction)gentype_trace, METH_VARARGS | METH_KEYWORDS, NULL}, {"diagonal", (PyCFunction)gentype_diagonal, METH_VARARGS | METH_KEYWORDS, NULL}, {"clip", (PyCFunction)gentype_clip, METH_VARARGS | METH_KEYWORDS, NULL}, {"conj", (PyCFunction)gentype_conj, METH_VARARGS, NULL}, {"conjugate", (PyCFunction)gentype_conjugate, METH_VARARGS, NULL}, {"nonzero", (PyCFunction)gentype_nonzero, METH_VARARGS, NULL}, {"std", (PyCFunction)gentype_std, METH_VARARGS | METH_KEYWORDS, NULL}, {"var", (PyCFunction)gentype_var, METH_VARARGS | METH_KEYWORDS, NULL}, {"sum", (PyCFunction)gentype_sum, METH_VARARGS | METH_KEYWORDS, NULL}, {"cumsum", (PyCFunction)gentype_cumsum, METH_VARARGS | METH_KEYWORDS, NULL}, {"prod", (PyCFunction)gentype_prod, METH_VARARGS | METH_KEYWORDS, NULL}, {"cumprod", (PyCFunction)gentype_cumprod, METH_VARARGS | METH_KEYWORDS, NULL}, {"all", (PyCFunction)gentype_all, METH_VARARGS | METH_KEYWORDS, NULL}, {"any", (PyCFunction)gentype_any, METH_VARARGS | METH_KEYWORDS, NULL}, {"compress", (PyCFunction)gentype_compress, METH_VARARGS | METH_KEYWORDS, NULL}, {"flatten", (PyCFunction)gentype_flatten, METH_VARARGS, NULL}, {"ravel", (PyCFunction)gentype_ravel, METH_VARARGS, NULL}, {"round", (PyCFunction)gentype_round, METH_VARARGS | METH_KEYWORDS, NULL}, #if defined(NPY_PY3K) /* Hook for the round() builtin */ {"__round__", (PyCFunction)gentype_round, METH_VARARGS | METH_KEYWORDS, NULL}, #endif /* For the format function */ {"__format__", gentype_format, METH_VARARGS, "NumPy array scalar formatter"}, {"setflags", (PyCFunction)gentype_setflags, METH_VARARGS | METH_KEYWORDS, NULL}, {"newbyteorder", (PyCFunction)gentype_newbyteorder, METH_VARARGS, NULL}, {NULL, NULL, 0, NULL} /* sentinel */ }; static PyGetSetDef voidtype_getsets[] = { {"flags", (getter)voidtype_flags_get, (setter)0, "integer value of flags", NULL}, {"dtype", (getter)voidtype_dtypedescr_get, (setter)0, "dtype object", NULL}, {NULL, NULL, NULL, NULL, NULL} }; static PyMethodDef voidtype_methods[] = { {"getfield", (PyCFunction)voidtype_getfield, METH_VARARGS | METH_KEYWORDS, NULL}, {"setfield", (PyCFunction)voidtype_setfield, METH_VARARGS | METH_KEYWORDS, NULL}, {NULL, NULL, 0, NULL} }; /**begin repeat * #name = cfloat,clongdouble# */ static PyMethodDef @name@type_methods[] = { {"__complex__", (PyCFunction)@name@_complex, METH_VARARGS | METH_KEYWORDS, NULL}, {NULL, NULL, 0, NULL} }; /**end repeat**/ /************* As_mapping functions for void array scalar ************/ static Py_ssize_t voidtype_length(PyVoidScalarObject *self) { if (!PyDataType_HASFIELDS(self->descr)) { return 0; } else { /* return the number of fields */ return (Py_ssize_t) PyTuple_GET_SIZE(self->descr->names); } } static PyObject * voidtype_item(PyVoidScalarObject *self, Py_ssize_t n) { npy_intp m; PyObject *flist=NULL, *fieldinfo; if (!(PyDataType_HASFIELDS(self->descr))) { PyErr_SetString(PyExc_IndexError, "can't index void scalar without fields"); return NULL; } flist = self->descr->names; m = PyTuple_GET_SIZE(flist); if (n < 0) { n += m; } if (n < 0 || n >= m) { PyErr_Format(PyExc_IndexError, "invalid index (%d)", (int) n); return NULL; } fieldinfo = PyDict_GetItem(self->descr->fields, PyTuple_GET_ITEM(flist, n)); return voidtype_getfield(self, fieldinfo, NULL); } /* get field by name or number */ static PyObject * voidtype_subscript(PyVoidScalarObject *self, PyObject *ind) { npy_intp n; PyObject *fieldinfo; if (!(PyDataType_HASFIELDS(self->descr))) { PyErr_SetString(PyExc_IndexError, "can't index void scalar without fields"); return NULL; } #if defined(NPY_PY3K) if (PyUString_Check(ind)) { #else if (PyBytes_Check(ind) || PyUnicode_Check(ind)) { #endif /* look up in fields */ fieldinfo = PyDict_GetItem(self->descr->fields, ind); if (!fieldinfo) { goto fail; } return voidtype_getfield(self, fieldinfo, NULL); } /* try to convert it to a number */ n = PyArray_PyIntAsIntp(ind); if (error_converting(n)) { goto fail; } return voidtype_item(self, (Py_ssize_t)n); fail: PyErr_SetString(PyExc_IndexError, "invalid index"); return NULL; } static int voidtype_ass_item(PyVoidScalarObject *self, Py_ssize_t n, PyObject *val) { npy_intp m; PyObject *flist=NULL, *fieldinfo, *newtup; PyObject *res; if (!(PyDataType_HASFIELDS(self->descr))) { PyErr_SetString(PyExc_IndexError, "can't index void scalar without fields"); return -1; } flist = self->descr->names; m = PyTuple_GET_SIZE(flist); if (n < 0) { n += m; } if (n < 0 || n >= m) { goto fail; } fieldinfo = PyDict_GetItem(self->descr->fields, PyTuple_GET_ITEM(flist, n)); newtup = Py_BuildValue("(OOO)", val, PyTuple_GET_ITEM(fieldinfo, 0), PyTuple_GET_ITEM(fieldinfo, 1)); res = voidtype_setfield(self, newtup, NULL); Py_DECREF(newtup); if (!res) { return -1; } Py_DECREF(res); return 0; fail: PyErr_Format(PyExc_IndexError, "invalid index (%d)", (int) n); return -1; } static int voidtype_ass_subscript(PyVoidScalarObject *self, PyObject *ind, PyObject *val) { npy_intp n; char *msg = "invalid index"; PyObject *fieldinfo, *newtup; PyObject *res; if (!PyDataType_HASFIELDS(self->descr)) { PyErr_SetString(PyExc_IndexError, "can't index void scalar without fields"); return -1; } if (!val) { PyErr_SetString(PyExc_ValueError, "cannot delete scalar field"); return -1; } #if defined(NPY_PY3K) if (PyUString_Check(ind)) { #else if (PyBytes_Check(ind) || PyUnicode_Check(ind)) { #endif /* look up in fields */ fieldinfo = PyDict_GetItem(self->descr->fields, ind); if (!fieldinfo) { goto fail; } newtup = Py_BuildValue("(OOO)", val, PyTuple_GET_ITEM(fieldinfo, 0), PyTuple_GET_ITEM(fieldinfo, 1)); res = voidtype_setfield(self, newtup, NULL); Py_DECREF(newtup); if (!res) { return -1; } Py_DECREF(res); return 0; } /* try to convert it to a number */ n = PyArray_PyIntAsIntp(ind); if (error_converting(n)) { goto fail; } return voidtype_ass_item(self, (Py_ssize_t)n, val); fail: PyErr_SetString(PyExc_IndexError, msg); return -1; } static PyMappingMethods voidtype_as_mapping = { (lenfunc)voidtype_length, /*mp_length*/ (binaryfunc)voidtype_subscript, /*mp_subscript*/ (objobjargproc)voidtype_ass_subscript, /*mp_ass_subscript*/ }; static PySequenceMethods voidtype_as_sequence = { (lenfunc)voidtype_length, /*sq_length*/ 0, /*sq_concat*/ 0, /*sq_repeat*/ (ssizeargfunc)voidtype_item, /*sq_item*/ 0, /*sq_slice*/ (ssizeobjargproc)voidtype_ass_item, /*sq_ass_item*/ 0, /* ssq_ass_slice */ 0, /* sq_contains */ 0, /* sq_inplace_concat */ 0, /* sq_inplace_repeat */ }; static Py_ssize_t gentype_getreadbuf(PyObject *self, Py_ssize_t segment, void **ptrptr) { int numbytes; PyArray_Descr *outcode; if (segment != 0) { PyErr_SetString(PyExc_SystemError, "Accessing non-existent array segment"); return -1; } outcode = PyArray_DescrFromScalar(self); numbytes = outcode->elsize; *ptrptr = (void *)scalar_value(self, outcode); #ifndef Py_UNICODE_WIDE if (outcode->type_num == NPY_UNICODE) { numbytes >>= 1; } #endif Py_DECREF(outcode); return numbytes; } #if !defined(NPY_PY3K) static Py_ssize_t gentype_getsegcount(PyObject *self, Py_ssize_t *lenp) { PyArray_Descr *outcode; outcode = PyArray_DescrFromScalar(self); if (lenp) { *lenp = outcode->elsize; #ifndef Py_UNICODE_WIDE if (outcode->type_num == NPY_UNICODE) { *lenp >>= 1; } #endif } Py_DECREF(outcode); return 1; } static Py_ssize_t gentype_getcharbuf(PyObject *self, Py_ssize_t segment, constchar **ptrptr) { if (PyArray_IsScalar(self, String) || PyArray_IsScalar(self, Unicode)) { return gentype_getreadbuf(self, segment, (void **)ptrptr); } else { PyErr_SetString(PyExc_TypeError, "Non-character array cannot be interpreted "\ "as character buffer."); return -1; } } #endif /* !defined(NPY_PY3K) */ static int gentype_getbuffer(PyObject *self, Py_buffer *view, int flags) { Py_ssize_t len; void *buf; /* FIXME: XXX: the format is not implemented! -- this needs more work */ len = gentype_getreadbuf(self, 0, &buf); return PyBuffer_FillInfo(view, self, buf, len, 1, flags); } /* releasebuffer is not needed */ static PyBufferProcs gentype_as_buffer = { #if !defined(NPY_PY3K) gentype_getreadbuf, /* bf_getreadbuffer*/ NULL, /* bf_getwritebuffer*/ gentype_getsegcount, /* bf_getsegcount*/ gentype_getcharbuf, /* bf_getcharbuffer*/ #endif gentype_getbuffer, /* bf_getbuffer */ NULL, /* bf_releasebuffer */ }; #if defined(NPY_PY3K) #define BASEFLAGS Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE #define LEAFFLAGS Py_TPFLAGS_DEFAULT #else #define BASEFLAGS Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_CHECKTYPES #define LEAFFLAGS Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES #endif NPY_NO_EXPORT PyTypeObject PyGenericArrType_Type = { #if defined(NPY_PY3K) PyVarObject_HEAD_INIT(NULL, 0) #else PyObject_HEAD_INIT(NULL) 0, /* ob_size */ #endif "numpy.generic", /* tp_name*/ sizeof(PyObject), /* tp_basicsize*/ 0, /* tp_itemsize */ /* methods */ 0, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ #if defined(NPY_PY3K) 0, /* tp_reserved */ #else 0, /* tp_compare */ #endif 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ 0, /* tp_flags */ 0, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ 0, /* 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 */ 0, /* tp_init */ 0, /* tp_alloc */ 0, /* 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 */ 0, /* tp_version_tag */ }; static void void_dealloc(PyVoidScalarObject *v) { if (v->flags & NPY_ARRAY_OWNDATA) { PyDataMem_FREE(v->obval); } Py_XDECREF(v->descr); Py_XDECREF(v->base); Py_TYPE(v)->tp_free(v); } static void object_arrtype_dealloc(PyObject *v) { Py_XDECREF(((PyObjectScalarObject *)v)->obval); Py_TYPE(v)->tp_free(v); } /* * string and unicode inherit from Python Type first and so GET_ITEM * is different to get to the Python Type. * * ok is a work-around for a bug in complex_new that doesn't allocate * memory from the sub-types memory allocator. */ #define _WORK(num) \ if (type->tp_bases && (PyTuple_GET_SIZE(type->tp_bases)==2)) { \ PyTypeObject *sup; \ /* 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(); \ /* now do default conversion */ \ } #define _WORK1 _WORK(1) #define _WORKz _WORK(0) #define _WORK0 /**begin repeat * #name = byte, short, int, long, longlong, ubyte, ushort, uint, ulong, * ulonglong, half, float, double, longdouble, cfloat, cdouble, * clongdouble, string, unicode, object# * #Name = Byte, Short, Int, Long, LongLong, UByte, UShort, UInt, ULong, * ULongLong, Half, Float, Double, LongDouble, CFloat, CDouble, * CLongDouble, String, Unicode, Object# * #TYPE = BYTE, SHORT, INT, LONG, LONGLONG, UBYTE, USHORT, UINT, ULONG, * ULONGLONG, HALF, FLOAT, DOUBLE, LONGDOUBLE, CFLOAT, CDOUBLE, * CLONGDOUBLE, STRING, UNICODE, OBJECT# * #work = 0,0,1,1,1,0,0,0,0,0,0,0,1,0,0,0,0,z,z,0# * #default = 0*17,1*2,2# */ #define _NPY_UNUSED2_1 #define _NPY_UNUSED2_z #define _NPY_UNUSED2_0 NPY_UNUSED #define _NPY_UNUSED1_0 #define _NPY_UNUSED1_1 #define _NPY_UNUSED1_2 NPY_UNUSED static PyObject * @name@_arrtype_new(PyTypeObject *_NPY_UNUSED1_@default@(type), PyObject *args, PyObject *_NPY_UNUSED2_@work@(kwds)) { PyObject *obj = NULL; PyObject *robj; PyArrayObject *arr; PyArray_Descr *typecode = NULL; #if !(@default@ == 2) int itemsize; void *dest, *src; #endif /* * allow base-class (if any) to do conversion * If successful, this will jump to finish: */ _WORK@work@ if (!PyArg_ParseTuple(args, "|O", &obj)) { return NULL; } typecode = PyArray_DescrFromType(NPY_@TYPE@); if (typecode == NULL) { return NULL; } /* * typecode is new reference and stolen by * PyArray_FromAny but not PyArray_Scalar */ if (obj == NULL) { #if @default@ == 0 robj = PyArray_Scalar(NULL, typecode, NULL); if (robj == NULL) { Py_DECREF(typecode); return NULL; } memset(&((Py@Name@ScalarObject *)robj)->obval, 0, sizeof(npy_@name@)); #elif @default@ == 1 robj = PyArray_Scalar(NULL, typecode, NULL); #elif @default@ == 2 Py_INCREF(Py_None); robj = Py_None; #endif Py_DECREF(typecode); goto finish; } /* * It is expected at this point that robj is a PyArrayScalar * (even for Object Data Type) */ arr = (PyArrayObject *)PyArray_FromAny(obj, typecode, 0, 0, NPY_ARRAY_FORCECAST, NULL); if ((arr == NULL) || (PyArray_NDIM(arr) > 0)) { return (PyObject *)arr; } /* 0-d array */ robj = PyArray_ToScalar(PyArray_DATA(arr), arr); Py_DECREF(arr); finish: /* * In OBJECT case, robj is no longer a * PyArrayScalar at this point but the * remaining code assumes it is */ #if @default@ == 2 return robj; #else /* Normal return */ if ((robj == NULL) || (Py_TYPE(robj) == type)) { return robj; } /* * This return path occurs when the requested type is not created * but another scalar object is created instead (i.e. when * the base-class does the conversion in _WORK macro) */ /* Need to allocate new type and copy data-area over */ if (type->tp_itemsize) { itemsize = PyBytes_GET_SIZE(robj); } else { itemsize = 0; } obj = type->tp_alloc(type, itemsize); if (obj == NULL) { Py_DECREF(robj); return NULL; } /* typecode will be NULL */ typecode = PyArray_DescrFromType(NPY_@TYPE@); dest = scalar_value(obj, typecode); src = scalar_value(robj, typecode); Py_DECREF(typecode); #if @default@ == 0 *((npy_@name@ *)dest) = *((npy_@name@ *)src); #elif @default@ == 1 /* unicode and strings */ if (itemsize == 0) { /* unicode */ #if PY_VERSION_HEX >= 0x03030000 itemsize = PyUnicode_GetLength(robj) * PyUnicode_KIND(robj); #else itemsize = ((PyUnicodeObject *)robj)->length * sizeof(Py_UNICODE); #endif } memcpy(dest, src, itemsize); /* @default@ == 2 won't get here */ #endif Py_DECREF(robj); return obj; #endif } /**end repeat**/ #undef _WORK1 #undef _WORKz #undef _WORK0 #undef _WORK /**begin repeat * #name = datetime, timedelta# * #Name = Datetime, Timedelta# * #NAME = DATETIME, TIMEDELTA# * #is_datetime = 1, 0# */ static PyObject * @name@_arrtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { PyObject *obj = NULL, *meta_obj = NULL; Py@Name@ScalarObject *ret; if (!PyArg_ParseTuple(args, "|OO", &obj, &meta_obj)) { return NULL; } /* Allocate the return scalar */ ret = (Py@Name@ScalarObject *)Py@Name@ArrType_Type.tp_alloc( &Py@Name@ArrType_Type, 0); if (ret == NULL) { return NULL; } /* Incorporate the metadata if its provided */ if (meta_obj != NULL) { /* Parse the provided metadata input */ if (convert_pyobject_to_datetime_metadata(meta_obj, &ret->obmeta) < 0) { Py_DECREF(ret); return NULL; } } else { /* * A unit of -1 signals that convert_pyobject_to_datetime * should populate. */ ret->obmeta.base = -1; } if (obj == NULL) { if (ret->obmeta.base == -1) { ret->obmeta.base = NPY_DATETIME_DEFAULTUNIT; ret->obmeta.num = 1; } /* Make datetime default to NaT, timedelta default to zero */ #if @is_datetime@ ret->obval = NPY_DATETIME_NAT; #else ret->obval = 0; #endif } else if (convert_pyobject_to_@name@(&ret->obmeta, obj, NPY_SAME_KIND_CASTING, &ret->obval) < 0) { Py_DECREF(ret); return NULL; } return (PyObject *)ret; } /**end repeat**/ /* bool->tp_new only returns Py_True or Py_False */ static PyObject * bool_arrtype_new(PyTypeObject *NPY_UNUSED(type), PyObject *args, PyObject *NPY_UNUSED(kwds)) { PyObject *obj = NULL; PyArrayObject *arr; if (!PyArg_ParseTuple(args, "|O", &obj)) { return NULL; } if (obj == NULL) { PyArrayScalar_RETURN_FALSE; } if (obj == Py_False) { PyArrayScalar_RETURN_FALSE; } if (obj == Py_True) { PyArrayScalar_RETURN_TRUE; } arr = (PyArrayObject *)PyArray_FROM_OTF(obj, NPY_BOOL, NPY_ARRAY_FORCECAST); if (arr && 0 == PyArray_NDIM(arr)) { npy_bool val = *((npy_bool *)PyArray_DATA(arr)); Py_DECREF(arr); PyArrayScalar_RETURN_BOOL_FROM_LONG(val); } return PyArray_Return((PyArrayObject *)arr); } static PyObject * bool_arrtype_and(PyObject *a, PyObject *b) { if (PyArray_IsScalar(a, Bool) && PyArray_IsScalar(b, Bool)) { PyArrayScalar_RETURN_BOOL_FROM_LONG ((a == PyArrayScalar_True) & (b == PyArrayScalar_True)); } return PyGenericArrType_Type.tp_as_number->nb_and(a, b); } static PyObject * bool_arrtype_or(PyObject *a, PyObject *b) { if (PyArray_IsScalar(a, Bool) && PyArray_IsScalar(b, Bool)) { PyArrayScalar_RETURN_BOOL_FROM_LONG ((a == PyArrayScalar_True)|(b == PyArrayScalar_True)); } return PyGenericArrType_Type.tp_as_number->nb_or(a, b); } static PyObject * bool_arrtype_xor(PyObject *a, PyObject *b) { if (PyArray_IsScalar(a, Bool) && PyArray_IsScalar(b, Bool)) { PyArrayScalar_RETURN_BOOL_FROM_LONG ((a == PyArrayScalar_True)^(b == PyArrayScalar_True)); } return PyGenericArrType_Type.tp_as_number->nb_xor(a, b); } static int bool_arrtype_nonzero(PyObject *a) { return a == PyArrayScalar_True; } /**begin repeat * #name = byte, short, int, long, ubyte, ushort, longlong, uint, * ulong, ulonglong# * #Name = Byte, Short, Int, Long, UByte, UShort, LongLong, UInt, * ULong, ULongLong# * #type = PyInt_FromLong*6, PyLong_FromLongLong*1, * PyLong_FromUnsignedLong*2, PyLong_FromUnsignedLongLong# */ static PyNumberMethods @name@_arrtype_as_number; static PyObject * @name@_index(PyObject *self) { return @type@(PyArrayScalar_VAL(self, @Name@)); } /**end repeat**/ static PyObject * bool_index(PyObject *a) { return PyInt_FromLong(PyArrayScalar_VAL(a, Bool)); } /* Arithmetic methods -- only so we can override &, |, ^. */ NPY_NO_EXPORT PyNumberMethods bool_arrtype_as_number = { 0, /* nb_add */ 0, /* nb_subtract */ 0, /* nb_multiply */ #if defined(NPY_PY3K) #else 0, /* nb_divide */ #endif 0, /* nb_remainder */ 0, /* nb_divmod */ 0, /* nb_power */ 0, /* nb_negative */ 0, /* nb_positive */ 0, /* nb_absolute */ (inquiry)bool_arrtype_nonzero, /* nb_nonzero / nb_bool */ 0, /* nb_invert */ 0, /* nb_lshift */ 0, /* nb_rshift */ (binaryfunc)bool_arrtype_and, /* nb_and */ (binaryfunc)bool_arrtype_xor, /* nb_xor */ (binaryfunc)bool_arrtype_or, /* nb_or */ #if defined(NPY_PY3K) #else 0, /* nb_coerce */ #endif 0, /* nb_int */ #if defined(NPY_PY3K) 0, /* nb_reserved */ #else 0, /* nb_long */ #endif 0, /* nb_float */ #if defined(NPY_PY3K) #else 0, /* nb_oct */ 0, /* nb_hex */ #endif /* Added in release 2.0 */ 0, /* nb_inplace_add */ 0, /* nb_inplace_subtract */ 0, /* nb_inplace_multiply */ #if defined(NPY_PY3K) #else 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 */ /* Added in release 2.2 */ /* The following require the Py_TPFLAGS_HAVE_CLASS flag */ 0, /* nb_floor_divide */ 0, /* nb_true_divide */ 0, /* nb_inplace_floor_divide */ 0, /* nb_inplace_true_divide */ /* Added in release 2.5 */ 0, /* nb_index */ }; static PyObject * void_arrtype_new(PyTypeObject *type, PyObject *args, PyObject *NPY_UNUSED(kwds)) { PyObject *obj, *arr; npy_ulonglong memu = 1; PyObject *new = NULL; char *destptr; if (!PyArg_ParseTuple(args, "O", &obj)) { return NULL; } /* * For a VOID scalar first see if obj is an integer or long * and create new memory of that size (filled with 0) for the scalar */ if (PyLong_Check(obj) || PyInt_Check(obj) || PyArray_IsScalar(obj, Integer) || (PyArray_Check(obj) && PyArray_NDIM((PyArrayObject *)obj)==0 && PyArray_ISINTEGER((PyArrayObject *)obj))) { #if defined(NPY_PY3K) new = Py_TYPE(obj)->tp_as_number->nb_int(obj); #else new = Py_TYPE(obj)->tp_as_number->nb_long(obj); #endif } if (new && PyLong_Check(new)) { PyObject *ret; memu = PyLong_AsUnsignedLongLong(new); Py_DECREF(new); if (PyErr_Occurred() || (memu > NPY_MAX_INT)) { PyErr_Clear(); PyErr_Format(PyExc_OverflowError, "size must be smaller than %d", (int) NPY_MAX_INT); return NULL; } destptr = PyDataMem_NEW((int) memu); if (destptr == NULL) { return PyErr_NoMemory(); } ret = type->tp_alloc(type, 0); if (ret == NULL) { PyDataMem_FREE(destptr); return PyErr_NoMemory(); } ((PyVoidScalarObject *)ret)->obval = destptr; Py_SIZE((PyVoidScalarObject *)ret) = (int) memu; ((PyVoidScalarObject *)ret)->descr = PyArray_DescrNewFromType(NPY_VOID); ((PyVoidScalarObject *)ret)->descr->elsize = (int) memu; ((PyVoidScalarObject *)ret)->flags = NPY_ARRAY_BEHAVED | NPY_ARRAY_OWNDATA; ((PyVoidScalarObject *)ret)->base = NULL; memset(destptr, '\0', (size_t) memu); return ret; } arr = PyArray_FROM_OTF(obj, NPY_VOID, NPY_ARRAY_FORCECAST); return PyArray_Return((PyArrayObject *)arr); } /**************** Define Hash functions ********************/ /**begin repeat * #lname = bool, ubyte, ushort# * #name = Bool,UByte, UShort# */ static npy_hash_t @lname@_arrtype_hash(PyObject *obj) { return (npy_hash_t)(((Py@name@ScalarObject *)obj)->obval); } /**end repeat**/ /**begin repeat * #lname = byte, short, uint# * #name = Byte, Short, UInt# */ static npy_hash_t @lname@_arrtype_hash(PyObject *obj) { npy_hash_t x = (npy_hash_t)(((Py@name@ScalarObject *)obj)->obval); if (x == -1) { x = -2; } return x; } /**end repeat**/ static npy_hash_t ulong_arrtype_hash(PyObject *obj) { PyObject * l = PyLong_FromUnsignedLong(((PyULongScalarObject*)obj)->obval); npy_hash_t x = PyObject_Hash(l); Py_DECREF(l); return x; } #if (NPY_SIZEOF_INT != NPY_SIZEOF_LONG) || defined(NPY_PY3K) static npy_hash_t int_arrtype_hash(PyObject *obj) { npy_hash_t x = (npy_hash_t)(((PyIntScalarObject *)obj)->obval); if (x == -1) { x = -2; } return x; } #endif #if defined(NPY_PY3K) static npy_hash_t long_arrtype_hash(PyObject *obj) { PyObject * l = PyLong_FromLong(((PyLongScalarObject*)obj)->obval); npy_hash_t x = PyObject_Hash(l); Py_DECREF(l); return x; } #endif /**begin repeat * #char = ,u# * #Char = ,U# * #Word = ,Unsigned# */ static npy_hash_t @char@longlong_arrtype_hash(PyObject *obj) { PyObject * l = PyLong_From@Word@LongLong( ((Py@Char@LongLongScalarObject*)obj)->obval); npy_hash_t x = PyObject_Hash(l); Py_DECREF(l); return x; } /**end repeat**/ /**begin repeat * #lname = datetime, timedelta# * #name = Datetime, Timedelta# */ #if NPY_SIZEOF_HASH_T==NPY_SIZEOF_DATETIME static npy_hash_t @lname@_arrtype_hash(PyObject *obj) { npy_hash_t x = (npy_hash_t)(((Py@name@ScalarObject *)obj)->obval); if (x == -1) { x = -2; } return x; } #elif NPY_SIZEOF_LONGLONG==NPY_SIZEOF_DATETIME static npy_hash_t @lname@_arrtype_hash(PyObject *obj) { npy_hash_t y; npy_longlong x = (((Py@name@ScalarObject *)obj)->obval); if ((x <= LONG_MAX)) { y = (npy_hash_t) x; } else { union Mask { long hashvals[2]; npy_longlong v; } both; both.v = x; y = both.hashvals[0] + (1000003)*both.hashvals[1]; } if (y == -1) { y = -2; } return y; } #endif /**end repeat**/ /* Wrong thing to do for longdouble, but....*/ /**begin repeat * #lname = float, longdouble# * #name = Float, LongDouble# */ static npy_hash_t @lname@_arrtype_hash(PyObject *obj) { return _Py_HashDouble((double) ((Py@name@ScalarObject *)obj)->obval); } /* borrowed from complex_hash */ static npy_hash_t c@lname@_arrtype_hash(PyObject *obj) { npy_hash_t hashreal, hashimag, combined; hashreal = _Py_HashDouble((double) (((PyC@name@ScalarObject *)obj)->obval).real); if (hashreal == -1) { return -1; } hashimag = _Py_HashDouble((double) (((PyC@name@ScalarObject *)obj)->obval).imag); if (hashimag == -1) { return -1; } combined = hashreal + 1000003 * hashimag; if (combined == -1) { combined = -2; } return combined; } /**end repeat**/ static npy_hash_t half_arrtype_hash(PyObject *obj) { return _Py_HashDouble(npy_half_to_double(((PyHalfScalarObject *)obj)->obval)); } static npy_hash_t object_arrtype_hash(PyObject *obj) { return PyObject_Hash(((PyObjectScalarObject *)obj)->obval); } /* we used to just hash the pointer */ /* now use tuplehash algorithm using voidtype_item to get the object */ static npy_hash_t void_arrtype_hash(PyObject *obj) { npy_hash_t x, y; Py_ssize_t len, n; PyVoidScalarObject *p; PyObject *element; npy_hash_t mult = 1000003L; x = 0x345678L; p = (PyVoidScalarObject *)obj; /* Cannot hash mutable void scalars */ if (p->flags & NPY_ARRAY_WRITEABLE) { PyErr_SetString(PyExc_TypeError, "unhashable type: 'writeable void-scalar'"); return -1; } len = voidtype_length(p); for (n=0; n < len; n++) { element = voidtype_item(p, n); y = PyObject_Hash(element); Py_DECREF(element); if (y == -1) return -1; x = (x ^ y) * mult; mult += (npy_hash_t)(82520L + len + len); } x += 97531L; if (x == -1) x = -2; return x; } /*object arrtype getattro and setattro */ static PyObject * object_arrtype_getattro(PyObjectScalarObject *obj, PyObject *attr) { PyObject *res; /* first look in object and then hand off to generic type */ res = PyObject_GenericGetAttr(obj->obval, attr); if (res) { return res; } PyErr_Clear(); return PyObject_GenericGetAttr((PyObject *)obj, attr); } static int object_arrtype_setattro(PyObjectScalarObject *obj, PyObject *attr, PyObject *val) { int res; /* first look in object and then hand off to generic type */ res = PyObject_GenericSetAttr(obj->obval, attr, val); if (res >= 0) { return res; } PyErr_Clear(); return PyObject_GenericSetAttr((PyObject *)obj, attr, val); } static PyObject * object_arrtype_concat(PyObjectScalarObject *self, PyObject *other) { return PySequence_Concat(self->obval, other); } static Py_ssize_t object_arrtype_length(PyObjectScalarObject *self) { return PyObject_Length(self->obval); } static PyObject * object_arrtype_repeat(PyObjectScalarObject *self, Py_ssize_t count) { return PySequence_Repeat(self->obval, count); } static PyObject * object_arrtype_subscript(PyObjectScalarObject *self, PyObject *key) { return PyObject_GetItem(self->obval, key); } static int object_arrtype_ass_subscript(PyObjectScalarObject *self, PyObject *key, PyObject *value) { return PyObject_SetItem(self->obval, key, value); } static int object_arrtype_contains(PyObjectScalarObject *self, PyObject *ob) { return PySequence_Contains(self->obval, ob); } static PyObject * object_arrtype_inplace_concat(PyObjectScalarObject *self, PyObject *o) { return PySequence_InPlaceConcat(self->obval, o); } static PyObject * object_arrtype_inplace_repeat(PyObjectScalarObject *self, Py_ssize_t count) { return PySequence_InPlaceRepeat(self->obval, count); } static PySequenceMethods object_arrtype_as_sequence = { (lenfunc)object_arrtype_length, /*sq_length*/ (binaryfunc)object_arrtype_concat, /*sq_concat*/ (ssizeargfunc)object_arrtype_repeat, /*sq_repeat*/ 0, /*sq_item*/ 0, /*sq_slice*/ 0, /* sq_ass_item */ 0, /* sq_ass_slice */ (objobjproc)object_arrtype_contains, /* sq_contains */ (binaryfunc)object_arrtype_inplace_concat, /* sq_inplace_concat */ (ssizeargfunc)object_arrtype_inplace_repeat, /* sq_inplace_repeat */ }; static PyMappingMethods object_arrtype_as_mapping = { (lenfunc)object_arrtype_length, (binaryfunc)object_arrtype_subscript, (objobjargproc)object_arrtype_ass_subscript, }; #if !defined(NPY_PY3K) static Py_ssize_t object_arrtype_getsegcount(PyObjectScalarObject *self, Py_ssize_t *lenp) { Py_ssize_t newlen; int cnt; PyBufferProcs *pb = Py_TYPE(self->obval)->tp_as_buffer; if (pb == NULL || pb->bf_getsegcount == NULL || (cnt = (*pb->bf_getsegcount)(self->obval, &newlen)) != 1) { return 0; } if (lenp) { *lenp = newlen; } return cnt; } static Py_ssize_t object_arrtype_getreadbuf(PyObjectScalarObject *self, Py_ssize_t segment, void **ptrptr) { PyBufferProcs *pb = Py_TYPE(self->obval)->tp_as_buffer; if (pb == NULL || pb->bf_getreadbuffer == NULL || pb->bf_getsegcount == NULL) { PyErr_SetString(PyExc_TypeError, "expected a readable buffer object"); return -1; } return (*pb->bf_getreadbuffer)(self->obval, segment, ptrptr); } static Py_ssize_t object_arrtype_getwritebuf(PyObjectScalarObject *self, Py_ssize_t segment, void **ptrptr) { PyBufferProcs *pb = Py_TYPE(self->obval)->tp_as_buffer; if (pb == NULL || pb->bf_getwritebuffer == NULL || pb->bf_getsegcount == NULL) { PyErr_SetString(PyExc_TypeError, "expected a writeable buffer object"); return -1; } return (*pb->bf_getwritebuffer)(self->obval, segment, ptrptr); } static Py_ssize_t object_arrtype_getcharbuf(PyObjectScalarObject *self, Py_ssize_t segment, constchar **ptrptr) { PyBufferProcs *pb = Py_TYPE(self->obval)->tp_as_buffer; if (pb == NULL || pb->bf_getcharbuffer == NULL || pb->bf_getsegcount == NULL) { PyErr_SetString(PyExc_TypeError, "expected a character buffer object"); return -1; } return (*pb->bf_getcharbuffer)(self->obval, segment, ptrptr); } #endif static int object_arrtype_getbuffer(PyObjectScalarObject *self, Py_buffer *view, int flags) { PyBufferProcs *pb = Py_TYPE(self->obval)->tp_as_buffer; if (pb == NULL || pb->bf_getbuffer == NULL) { PyErr_SetString(PyExc_TypeError, "expected a readable buffer object"); return -1; } return (*pb->bf_getbuffer)(self->obval, view, flags); } static void object_arrtype_releasebuffer(PyObjectScalarObject *self, Py_buffer *view) { PyBufferProcs *pb = Py_TYPE(self->obval)->tp_as_buffer; if (pb == NULL) { PyErr_SetString(PyExc_TypeError, "expected a readable buffer object"); return; } if (pb->bf_releasebuffer != NULL) { (*pb->bf_releasebuffer)(self->obval, view); } } static PyBufferProcs object_arrtype_as_buffer = { #if !defined(NPY_PY3K) (readbufferproc)object_arrtype_getreadbuf, (writebufferproc)object_arrtype_getwritebuf, (segcountproc)object_arrtype_getsegcount, (charbufferproc)object_arrtype_getcharbuf, #endif (getbufferproc)object_arrtype_getbuffer, (releasebufferproc)object_arrtype_releasebuffer, }; static PyObject * object_arrtype_call(PyObjectScalarObject *obj, PyObject *args, PyObject *kwds) { return PyObject_Call(obj->obval, args, kwds); } NPY_NO_EXPORT PyTypeObject PyObjectArrType_Type = { #if defined(NPY_PY3K) PyVarObject_HEAD_INIT(NULL, 0) #else PyObject_HEAD_INIT(NULL) 0, /* ob_size */ #endif "numpy.object_", /* tp_name*/ sizeof(PyObjectScalarObject), /* tp_basicsize*/ 0, /* tp_itemsize */ (destructor)object_arrtype_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ #if defined(NPY_PY3K) 0, /* tp_reserved */ #else 0, /* tp_compare */ #endif 0, /* tp_repr */ 0, /* tp_as_number */ &object_arrtype_as_sequence, /* tp_as_sequence */ &object_arrtype_as_mapping, /* tp_as_mapping */ 0, /* tp_hash */ (ternaryfunc)object_arrtype_call, /* tp_call */ 0, /* tp_str */ (getattrofunc)object_arrtype_getattro, /* tp_getattro */ (setattrofunc)object_arrtype_setattro, /* tp_setattro */ &object_arrtype_as_buffer, /* tp_as_buffer */ 0, /* tp_flags */ 0, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ 0, /* 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 */ 0, /* tp_init */ 0, /* tp_alloc */ 0, /* 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 */ 0, /* tp_version_tag */ }; static PyObject * gen_arrtype_subscript(PyObject *self, PyObject *key) { /* * Only [...], [...,], [, ...], * is allowed for indexing a scalar * * These return a new N-d array with a copy of * 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 { PyErr_SetString(PyExc_IndexError, "invalid index to scalar variable."); return NULL; } 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; } #define NAME_bool "bool" #define NAME_void "void" #if defined(NPY_PY3K) #define NAME_string "bytes" #define NAME_unicode "str" #else #define NAME_string "string" #define NAME_unicode "unicode" #endif /**begin repeat * #name = bool, string, unicode, void# * #NAME = Bool, String, Unicode, Void# * #ex = _,_,_,# */ NPY_NO_EXPORT PyTypeObject Py@NAME@ArrType_Type = { #if defined(NPY_PY3K) PyVarObject_HEAD_INIT(NULL, 0) #else PyObject_HEAD_INIT(NULL) 0, /* ob_size */ #endif "numpy." NAME_@name@ "@ex@", /* tp_name*/ sizeof(Py@NAME@ScalarObject), /* tp_basicsize*/ 0, /* tp_itemsize */ 0, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ #if defined(NPY_PY3K) 0, /* tp_reserved */ #else 0, /* tp_compare */ #endif 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ 0, /* tp_flags */ 0, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ 0, /* 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 */ 0, /* tp_init */ 0, /* tp_alloc */ 0, /* 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 */ 0, /* tp_version_tag */ }; /**end repeat**/ #undef NAME_bool #undef NAME_void #undef NAME_string #undef NAME_unicode /**begin repeat * #NAME = Byte, Short, Int, Long, LongLong, UByte, UShort, UInt, ULong, * ULongLong, Half, Float, Double, LongDouble, Datetime, Timedelta# * #name = int*5, uint*5, float*4, datetime, timedelta# * #CNAME = (CHAR, SHORT, INT, LONG, LONGLONG)*2, HALF, FLOAT, DOUBLE, * LONGDOUBLE, DATETIME, TIMEDELTA# */ #if NPY_BITSOF_@CNAME@ == 8 #define _THIS_SIZE "8" #elif NPY_BITSOF_@CNAME@ == 16 #define _THIS_SIZE "16" #elif NPY_BITSOF_@CNAME@ == 32 #define _THIS_SIZE "32" #elif NPY_BITSOF_@CNAME@ == 64 #define _THIS_SIZE "64" #elif NPY_BITSOF_@CNAME@ == 80 #define _THIS_SIZE "80" #elif NPY_BITSOF_@CNAME@ == 96 #define _THIS_SIZE "96" #elif NPY_BITSOF_@CNAME@ == 128 #define _THIS_SIZE "128" #elif NPY_BITSOF_@CNAME@ == 256 #define _THIS_SIZE "256" #endif NPY_NO_EXPORT PyTypeObject Py@NAME@ArrType_Type = { #if defined(NPY_PY3K) PyVarObject_HEAD_INIT(NULL, 0) #else PyObject_HEAD_INIT(NULL) 0, /* ob_size */ #endif "numpy.@name@" _THIS_SIZE, /* tp_name*/ sizeof(Py@NAME@ScalarObject), /* tp_basicsize*/ 0, /* tp_itemsize */ 0, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ #if defined(NPY_PY3K) 0, /* tp_reserved */ #else 0, /* tp_compare */ #endif 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ 0, /* tp_flags */ 0, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ 0, /* 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 */ 0, /* tp_init */ 0, /* tp_alloc */ 0, /* 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 */ 0, /* tp_version_tag */ }; #undef _THIS_SIZE /**end repeat**/ static PyMappingMethods gentype_as_mapping = { NULL, (binaryfunc)gen_arrtype_subscript, NULL }; /**begin repeat * #NAME = CFloat, CDouble, CLongDouble# * #name = complex*3# * #CNAME = FLOAT, DOUBLE, LONGDOUBLE# */ #if NPY_BITSOF_@CNAME@ == 16 #define _THIS_SIZE2 "16" #define _THIS_SIZE1 "32" #elif NPY_BITSOF_@CNAME@ == 32 #define _THIS_SIZE2 "32" #define _THIS_SIZE1 "64" #elif NPY_BITSOF_@CNAME@ == 64 #define _THIS_SIZE2 "64" #define _THIS_SIZE1 "128" #elif NPY_BITSOF_@CNAME@ == 80 #define _THIS_SIZE2 "80" #define _THIS_SIZE1 "160" #elif NPY_BITSOF_@CNAME@ == 96 #define _THIS_SIZE2 "96" #define _THIS_SIZE1 "192" #elif NPY_BITSOF_@CNAME@ == 128 #define _THIS_SIZE2 "128" #define _THIS_SIZE1 "256" #elif NPY_BITSOF_@CNAME@ == 256 #define _THIS_SIZE2 "256" #define _THIS_SIZE1 "512" #endif #define _THIS_DOC "Composed of two " _THIS_SIZE2 " bit floats" NPY_NO_EXPORT PyTypeObject Py@NAME@ArrType_Type = { #if defined(NPY_PY3K) PyVarObject_HEAD_INIT(0, 0) #else PyObject_HEAD_INIT(0) 0, /* ob_size */ #endif "numpy.@name@" _THIS_SIZE1, /* tp_name*/ sizeof(Py@NAME@ScalarObject), /* tp_basicsize*/ 0, /* tp_itemsize*/ 0, /* tp_dealloc*/ 0, /* tp_print*/ 0, /* tp_getattr*/ 0, /* tp_setattr*/ #if defined(NPY_PY3K) 0, /* tp_reserved */ #else 0, /* tp_compare */ #endif 0, /* tp_repr*/ 0, /* tp_as_number*/ 0, /* tp_as_sequence*/ 0, /* tp_as_mapping*/ 0, /* tp_hash */ 0, /* tp_call*/ 0, /* tp_str*/ 0, /* tp_getattro*/ 0, /* tp_setattro*/ 0, /* tp_as_buffer*/ Py_TPFLAGS_DEFAULT, /* tp_flags*/ _THIS_DOC, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ 0, /* 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 */ 0, /* tp_init */ 0, /* tp_alloc */ 0, /* 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 */ 0, /* tp_version_tag */ }; #undef _THIS_SIZE1 #undef _THIS_SIZE2 #undef _THIS_DOC /**end repeat**/ #ifdef NPY_ENABLE_SEPARATE_COMPILATION /* * This table maps the built-in type numbers to their scalar * type numbers. Note that signed integers are mapped to INTNEG_SCALAR, * which is different than what PyArray_ScalarKind returns. */ NPY_NO_EXPORT signed char _npy_scalar_kinds_table[NPY_NTYPES]; /* * This table maps a scalar kind (excluding NPY_NOSCALAR) * to the smallest type number of that kind. */ NPY_NO_EXPORT signed char _npy_smallest_type_of_kind_table[NPY_NSCALARKINDS]; /* * This table gives the type of the same kind, but next in the sequence * of sizes. */ NPY_NO_EXPORT signed char _npy_next_larger_type_table[NPY_NTYPES]; /* * This table describes safe casting for small type numbers, * and is used by PyArray_CanCastSafely. */ NPY_NO_EXPORT unsigned char _npy_can_cast_safely_table[NPY_NTYPES][NPY_NTYPES]; /* * This table gives the smallest-size and smallest-kind type to which * the input types may be safely cast, according to _npy_can_cast_safely. */ NPY_NO_EXPORT signed char _npy_type_promotion_table[NPY_NTYPES][NPY_NTYPES]; #endif NPY_NO_EXPORT void initialize_casting_tables(void) { int i, j; _npy_smallest_type_of_kind_table[NPY_BOOL_SCALAR] = NPY_BOOL; _npy_smallest_type_of_kind_table[NPY_INTPOS_SCALAR] = NPY_UBYTE; _npy_smallest_type_of_kind_table[NPY_INTNEG_SCALAR] = NPY_BYTE; _npy_smallest_type_of_kind_table[NPY_FLOAT_SCALAR] = NPY_HALF; _npy_smallest_type_of_kind_table[NPY_COMPLEX_SCALAR] = NPY_CFLOAT; _npy_smallest_type_of_kind_table[NPY_OBJECT_SCALAR] = NPY_OBJECT; /* Default for built-in types is object scalar */ memset(_npy_scalar_kinds_table, NPY_OBJECT_SCALAR, sizeof(_npy_scalar_kinds_table)); /* Default for next largest type is -1, signalling no bigger */ memset(_npy_next_larger_type_table, -1, sizeof(_npy_next_larger_type_table)); /* Compile-time loop of scalar kinds */ /**begin repeat * #NAME = BOOL, * BYTE, UBYTE, SHORT, USHORT, INT, UINT, * LONG, ULONG, LONGLONG, ULONGLONG, * HALF, FLOAT, DOUBLE, LONGDOUBLE, * CFLOAT, CDOUBLE, CLONGDOUBLE# * #BIGGERTYPE = -1, * NPY_SHORT, NPY_USHORT, NPY_INT, NPY_UINT, NPY_LONG, NPY_ULONG, * NPY_LONGLONG, NPY_ULONGLONG, -1, -1, * NPY_FLOAT, NPY_DOUBLE, NPY_LONGDOUBLE, -1, * NPY_CDOUBLE, NPY_CLONGDOUBLE, -1# * #SCKIND = BOOL, * (INTNEG, INTPOS)*5, * FLOAT*4, * COMPLEX*3# */ _npy_scalar_kinds_table[NPY_@NAME@] = NPY_@SCKIND@_SCALAR; _npy_next_larger_type_table[NPY_@NAME@] = @BIGGERTYPE@; /**end repeat**/ memset(_npy_can_cast_safely_table, 0, sizeof(_npy_can_cast_safely_table)); for (i = 0; i < NPY_NTYPES; ++i) { /* Identity */ _npy_can_cast_safely_table[i][i] = 1; if (i != NPY_DATETIME) { /* * Bool -> except datetime (since * it conceptually has no zero) */ _npy_can_cast_safely_table[NPY_BOOL][i] = 1; } /* -> Object */ _npy_can_cast_safely_table[i][NPY_OBJECT] = 1; /* -> Void */ _npy_can_cast_safely_table[i][NPY_VOID] = 1; } _npy_can_cast_safely_table[NPY_STRING][NPY_UNICODE] = 1; _npy_can_cast_safely_table[NPY_BOOL][NPY_TIMEDELTA] = 1; #ifndef NPY_SIZEOF_BYTE #define NPY_SIZEOF_BYTE 1 #endif /* Compile-time loop of casting rules */ /**begin repeat * #FROM_NAME = BYTE, UBYTE, SHORT, USHORT, INT, UINT, * LONG, ULONG, LONGLONG, ULONGLONG, * HALF, FLOAT, DOUBLE, LONGDOUBLE, * CFLOAT, CDOUBLE, CLONGDOUBLE# * #FROM_BASENAME = BYTE, BYTE, SHORT, SHORT, INT, INT, * LONG, LONG, LONGLONG, LONGLONG, * HALF, FLOAT, DOUBLE, LONGDOUBLE, * FLOAT, DOUBLE, LONGDOUBLE# * #from_isint = 1, 0, 1, 0, 1, 0, 1, 0, * 1, 0, 0, 0, 0, 0, * 0, 0, 0# * #from_isuint = 0, 1, 0, 1, 0, 1, 0, 1, * 0, 1, 0, 0, 0, 0, * 0, 0, 0# * #from_isfloat = 0, 0, 0, 0, 0, 0, 0, 0, * 0, 0, 1, 1, 1, 1, * 0, 0, 0# * #from_iscomplex = 0, 0, 0, 0, 0, 0, 0, 0, * 0, 0, 0, 0, 0, 0, * 1, 1, 1# */ #define _FROM_BSIZE NPY_SIZEOF_@FROM_BASENAME@ #define _FROM_NUM (NPY_@FROM_NAME@) _npy_can_cast_safely_table[_FROM_NUM][NPY_STRING] = 1; _npy_can_cast_safely_table[_FROM_NUM][NPY_UNICODE] = 1; /* Allow casts from any integer to the TIMEDELTA type */ #if @from_isint@ || @from_isuint@ _npy_can_cast_safely_table[_FROM_NUM][NPY_TIMEDELTA] = 1; #endif /**begin repeat1 * #TO_NAME = BYTE, UBYTE, SHORT, USHORT, INT, UINT, * LONG, ULONG, LONGLONG, ULONGLONG, * HALF, FLOAT, DOUBLE, LONGDOUBLE, * CFLOAT, CDOUBLE, CLONGDOUBLE# * #TO_BASENAME = BYTE, BYTE, SHORT, SHORT, INT, INT, * LONG, LONG, LONGLONG, LONGLONG, * HALF, FLOAT, DOUBLE, LONGDOUBLE, * FLOAT, DOUBLE, LONGDOUBLE# * #to_isint = 1, 0, 1, 0, 1, 0, 1, 0, * 1, 0, 0, 0, 0, 0, * 0, 0, 0# * #to_isuint = 0, 1, 0, 1, 0, 1, 0, 1, * 0, 1, 0, 0, 0, 0, * 0, 0, 0# * #to_isfloat = 0, 0, 0, 0, 0, 0, 0, 0, * 0, 0, 1, 1, 1, 1, * 0, 0, 0# * #to_iscomplex = 0, 0, 0, 0, 0, 0, 0, 0, * 0, 0, 0, 0, 0, 0, * 1, 1, 1# */ #define _TO_BSIZE NPY_SIZEOF_@TO_BASENAME@ #define _TO_NUM (NPY_@TO_NAME@) /* * NOTE: _FROM_BSIZE and _TO_BSIZE are the sizes of the "base type" * which is the same as the size of the type except for * complex, where it is the size of the real type. */ #if @from_isint@ # if @to_isint@ && (_TO_BSIZE >= _FROM_BSIZE) /* int -> int */ _npy_can_cast_safely_table[_FROM_NUM][_TO_NUM] = 1; # elif @to_isfloat@ && (_FROM_BSIZE < 8) && (_TO_BSIZE > _FROM_BSIZE) /* int -> float */ _npy_can_cast_safely_table[_FROM_NUM][_TO_NUM] = 1; # elif @to_isfloat@ && (_FROM_BSIZE >= 8) && (_TO_BSIZE >= _FROM_BSIZE) /* int -> float */ _npy_can_cast_safely_table[_FROM_NUM][_TO_NUM] = 1; # elif @to_iscomplex@ && (_FROM_BSIZE < 8) && (_TO_BSIZE > _FROM_BSIZE) /* int -> complex */ _npy_can_cast_safely_table[_FROM_NUM][_TO_NUM] = 1; # elif @to_iscomplex@ && (_FROM_BSIZE >= 8) && (_TO_BSIZE >= _FROM_BSIZE) /* int -> complex */ _npy_can_cast_safely_table[_FROM_NUM][_TO_NUM] = 1; # endif #elif @from_isuint@ # if @to_isint@ && (_TO_BSIZE > _FROM_BSIZE) /* uint -> int */ _npy_can_cast_safely_table[_FROM_NUM][_TO_NUM] = 1; # elif @to_isuint@ && (_TO_BSIZE >= _FROM_BSIZE) /* uint -> uint */ _npy_can_cast_safely_table[_FROM_NUM][_TO_NUM] = 1; # elif @to_isfloat@ && (_FROM_BSIZE < 8) && (_TO_BSIZE > _FROM_BSIZE) /* uint -> float */ _npy_can_cast_safely_table[_FROM_NUM][_TO_NUM] = 1; # elif @to_isfloat@ && (_FROM_BSIZE >= 8) && (_TO_BSIZE >= _FROM_BSIZE) /* uint -> float */ _npy_can_cast_safely_table[_FROM_NUM][_TO_NUM] = 1; # elif @to_iscomplex@ && (_FROM_BSIZE < 8) && (_TO_BSIZE > _FROM_BSIZE) /* uint -> complex */ _npy_can_cast_safely_table[_FROM_NUM][_TO_NUM] = 1; # elif @to_iscomplex@ && (_FROM_BSIZE >= 8) && (_TO_BSIZE >= _FROM_BSIZE) /* uint -> complex */ _npy_can_cast_safely_table[_FROM_NUM][_TO_NUM] = 1; # endif #elif @from_isfloat@ # if @to_isfloat@ && (_TO_BSIZE >= _FROM_BSIZE) /* float -> float */ _npy_can_cast_safely_table[_FROM_NUM][_TO_NUM] = 1; # elif @to_iscomplex@ && (_TO_BSIZE >= _FROM_BSIZE) /* float -> complex */ _npy_can_cast_safely_table[_FROM_NUM][_TO_NUM] = 1; # endif #elif @from_iscomplex@ # if @to_iscomplex@ && (_TO_BSIZE >= _FROM_BSIZE) /* complex -> complex */ _npy_can_cast_safely_table[_FROM_NUM][_TO_NUM] = 1; # endif #endif #undef _TO_NUM #undef _TO_BSIZE /**end repeat1**/ #undef _FROM_NUM #undef _FROM_BSIZE /**end repeat**/ /* * Now that the _can_cast_safely table is finished, we can * use it to build the _type_promotion table */ for (i = 0; i < NPY_NTYPES; ++i) { _npy_type_promotion_table[i][i] = i; /* Don't let number promote to string/unicode/void/datetime/timedelta */ if (i == NPY_STRING || i == NPY_UNICODE || i == NPY_VOID || i == NPY_DATETIME || i == NPY_TIMEDELTA) { /* Promoting these types requires examining their contents */ _npy_type_promotion_table[i][i] = -1; for (j = i + 1; j < NPY_NTYPES; ++j) { _npy_type_promotion_table[i][j] = -1; _npy_type_promotion_table[j][i] = -1; } /* Except they can convert to OBJECT */ _npy_type_promotion_table[i][NPY_OBJECT] = NPY_OBJECT; _npy_type_promotion_table[NPY_OBJECT][i] = NPY_OBJECT; } else { for (j = i + 1; j < NPY_NTYPES; ++j) { /* Don't let number promote to string/unicode/void */ if (j == NPY_STRING || j == NPY_UNICODE || j == NPY_VOID) { _npy_type_promotion_table[i][j] = -1; _npy_type_promotion_table[j][i] = -1; } else if (_npy_can_cast_safely_table[i][j]) { _npy_type_promotion_table[i][j] = j; _npy_type_promotion_table[j][i] = j; } else if (_npy_can_cast_safely_table[j][i]) { _npy_type_promotion_table[i][j] = i; _npy_type_promotion_table[j][i] = i; } else { int k, iskind, jskind, skind; iskind = _npy_scalar_kinds_table[i]; jskind = _npy_scalar_kinds_table[j]; /* If there's no kind (void/string/etc) */ if (iskind == NPY_NOSCALAR || jskind == NPY_NOSCALAR) { k = -1; } else { /* Start with the type of larger kind */ if (iskind > jskind) { skind = iskind; k = i; } else { skind = jskind; k = j; } for (;;) { /* Try the next larger type of this kind */ k = _npy_next_larger_type_table[k]; /* If there is no larger, try a larger kind */ if (k < 0) { ++skind; /* Use -1 to signal no promoted type found */ if (skind < NPY_NSCALARKINDS) { k = _npy_smallest_type_of_kind_table[skind]; } else { k = -1; break; } } if (_npy_can_cast_safely_table[i][k] && _npy_can_cast_safely_table[j][k]) { break; } } } _npy_type_promotion_table[i][j] = k; _npy_type_promotion_table[j][i] = k; } } } } } static PyNumberMethods longdoubletype_as_number; static PyNumberMethods clongdoubletype_as_number; NPY_NO_EXPORT void initialize_numeric_types(void) { PyGenericArrType_Type.tp_dealloc = (destructor)gentype_dealloc; PyGenericArrType_Type.tp_as_number = &gentype_as_number; PyGenericArrType_Type.tp_as_buffer = &gentype_as_buffer; PyGenericArrType_Type.tp_as_mapping = &gentype_as_mapping; PyGenericArrType_Type.tp_flags = BASEFLAGS; PyGenericArrType_Type.tp_methods = gentype_methods; PyGenericArrType_Type.tp_getset = gentype_getsets; PyGenericArrType_Type.tp_new = NULL; PyGenericArrType_Type.tp_alloc = gentype_alloc; PyGenericArrType_Type.tp_free = PyArray_free; PyGenericArrType_Type.tp_repr = gentype_repr; PyGenericArrType_Type.tp_str = gentype_str; PyGenericArrType_Type.tp_richcompare = gentype_richcompare; PyBoolArrType_Type.tp_as_number = &bool_arrtype_as_number; /* * need to add dummy versions with filled-in nb_index * in-order for PyType_Ready to fill in .__index__() method */ /**begin repeat * #name = byte, short, int, long, longlong, ubyte, ushort, * uint, ulong, ulonglong# * #NAME = Byte, Short, Int, Long, LongLong, UByte, UShort, * UInt, ULong, ULongLong# */ Py@NAME@ArrType_Type.tp_as_number = &@name@_arrtype_as_number; Py@NAME@ArrType_Type.tp_as_number->nb_index = (unaryfunc)@name@_index; /**end repeat**/ PyBoolArrType_Type.tp_as_number->nb_index = (unaryfunc)bool_index; PyStringArrType_Type.tp_alloc = NULL; PyStringArrType_Type.tp_free = NULL; PyStringArrType_Type.tp_repr = stringtype_repr; PyStringArrType_Type.tp_str = stringtype_str; PyUnicodeArrType_Type.tp_repr = unicodetype_repr; PyUnicodeArrType_Type.tp_str = unicodetype_str; PyVoidArrType_Type.tp_methods = voidtype_methods; PyVoidArrType_Type.tp_getset = voidtype_getsets; PyVoidArrType_Type.tp_as_mapping = &voidtype_as_mapping; PyVoidArrType_Type.tp_as_sequence = &voidtype_as_sequence; /**begin repeat * #NAME= Number, Integer, SignedInteger, UnsignedInteger, Inexact, * Floating, ComplexFloating, Flexible, Character# */ Py@NAME@ArrType_Type.tp_flags = BASEFLAGS; /**end repeat**/ /**begin repeat * #name = bool, byte, short, int, long, longlong, ubyte, ushort, uint, * ulong, ulonglong, half, float, double, longdouble, cfloat, * cdouble, clongdouble, string, unicode, void, object, datetime, * timedelta# * #NAME = Bool, Byte, Short, Int, Long, LongLong, UByte, UShort, UInt, * ULong, ULongLong, Half, Float, Double, LongDouble, CFloat, * CDouble, CLongDouble, String, Unicode, Void, Object, Datetime, * Timedelta# */ Py@NAME@ArrType_Type.tp_flags = BASEFLAGS; Py@NAME@ArrType_Type.tp_new = @name@_arrtype_new; Py@NAME@ArrType_Type.tp_richcompare = gentype_richcompare; /**end repeat**/ /**begin repeat * #name = bool, byte, short, ubyte, ushort, uint, ulong, ulonglong, * half, float, longdouble, cfloat, clongdouble, void, object, * datetime, timedelta# * #NAME = Bool, Byte, Short, UByte, UShort, UInt, ULong, ULongLong, * Half, Float, LongDouble, CFloat, CLongDouble, Void, Object, * Datetime, Timedelta# */ Py@NAME@ArrType_Type.tp_hash = @name@_arrtype_hash; /**end repeat**/ /**begin repeat * #name = cfloat, clongdouble# * #NAME = CFloat, CLongDouble# */ Py@NAME@ArrType_Type.tp_methods = @name@type_methods; /**end repeat**/ #if (NPY_SIZEOF_INT != NPY_SIZEOF_LONG) || defined(NPY_PY3K) /* We won't be inheriting from Python Int type. */ PyIntArrType_Type.tp_hash = int_arrtype_hash; #endif #if defined(NPY_PY3K) /* We won't be inheriting from Python Int type. */ PyLongArrType_Type.tp_hash = long_arrtype_hash; #endif #if (NPY_SIZEOF_LONG != NPY_SIZEOF_LONGLONG) || defined(NPY_PY3K) /* We won't be inheriting from Python Int type. */ PyLongLongArrType_Type.tp_hash = longlong_arrtype_hash; #endif /**begin repeat * #name = repr, str# */ PyHalfArrType_Type.tp_@name@ = halftype_@name@; PyFloatArrType_Type.tp_@name@ = floattype_@name@; PyCFloatArrType_Type.tp_@name@ = cfloattype_@name@; PyDoubleArrType_Type.tp_@name@ = doubletype_@name@; PyCDoubleArrType_Type.tp_@name@ = cdoubletype_@name@; PyDatetimeArrType_Type.tp_@name@ = datetimetype_@name@; PyTimedeltaArrType_Type.tp_@name@ = timedeltatype_@name@; /**end repeat**/ PyHalfArrType_Type.tp_print = halftype_print; PyFloatArrType_Type.tp_print = floattype_print; PyDoubleArrType_Type.tp_print = doubletype_print; PyLongDoubleArrType_Type.tp_print = longdoubletype_print; PyCFloatArrType_Type.tp_print = cfloattype_print; PyCDoubleArrType_Type.tp_print = cdoubletype_print; PyCLongDoubleArrType_Type.tp_print = clongdoubletype_print; /* * These need to be coded specially because getitem does not * return a normal Python type */ PyLongDoubleArrType_Type.tp_as_number = &longdoubletype_as_number; PyCLongDoubleArrType_Type.tp_as_number = &clongdoubletype_as_number; /**begin repeat * #name = int, float, repr, str# * #kind = tp_as_number->nb*2, tp*2# */ PyLongDoubleArrType_Type.@kind@_@name@ = longdoubletype_@name@; PyCLongDoubleArrType_Type.@kind@_@name@ = clongdoubletype_@name@; /**end repeat**/ #if !defined(NPY_PY3K) /**begin repeat * #name = long, hex, oct# * #kind = tp_as_number->nb*3# */ PyLongDoubleArrType_Type.@kind@_@name@ = longdoubletype_@name@; PyCLongDoubleArrType_Type.@kind@_@name@ = clongdoubletype_@name@; /**end repeat**/ #endif PyStringArrType_Type.tp_itemsize = sizeof(char); PyVoidArrType_Type.tp_dealloc = (destructor) void_dealloc; PyArrayIter_Type.tp_iter = PyObject_SelfIter; PyArrayMapIter_Type.tp_iter = PyObject_SelfIter; } /* the order of this table is important */ static PyTypeObject *typeobjects[] = { &PyBoolArrType_Type, &PyByteArrType_Type, &PyUByteArrType_Type, &PyShortArrType_Type, &PyUShortArrType_Type, &PyIntArrType_Type, &PyUIntArrType_Type, &PyLongArrType_Type, &PyULongArrType_Type, &PyLongLongArrType_Type, &PyULongLongArrType_Type, &PyFloatArrType_Type, &PyDoubleArrType_Type, &PyLongDoubleArrType_Type, &PyCFloatArrType_Type, &PyCDoubleArrType_Type, &PyCLongDoubleArrType_Type, &PyObjectArrType_Type, &PyStringArrType_Type, &PyUnicodeArrType_Type, &PyVoidArrType_Type, &PyDatetimeArrType_Type, &PyTimedeltaArrType_Type, &PyHalfArrType_Type }; NPY_NO_EXPORT int _typenum_fromtypeobj(PyObject *type, int user) { int typenum, i; typenum = NPY_NOTYPE; i = 0; while(i < NPY_NTYPES) { if (type == (PyObject *)typeobjects[i]) { typenum = i; break; } i++; } if (!user) { return typenum; } /* Search any registered types */ i = 0; while (i < NPY_NUMUSERTYPES) { if (type == (PyObject *)(userdescrs[i]->typeobj)) { typenum = i + NPY_USERDEF; break; } i++; } return typenum; } numpy-1.8.2/numpy/core/src/multiarray/methods.h0000664000175100017510000000035512370216242022722 0ustar vagrantvagrant00000000000000#ifndef _NPY_ARRAY_METHODS_H_ #define _NPY_ARRAY_METHODS_H_ #ifdef NPY_ENABLE_SEPARATE_COMPILATION extern NPY_NO_EXPORT PyMethodDef array_methods[]; #endif NPY_NO_EXPORT const char * npy_casting_to_string(NPY_CASTING casting); #endif numpy-1.8.2/numpy/core/src/multiarray/datetime_busday.h0000664000175100017510000000131412370216242024416 0ustar vagrantvagrant00000000000000#ifndef _NPY_PRIVATE__DATETIME_BUSDAY_H_ #define _NPY_PRIVATE__DATETIME_BUSDAY_H_ /* * This is the 'busday_offset' function exposed for calling * from Python. */ NPY_NO_EXPORT PyObject * array_busday_offset(PyObject *NPY_UNUSED(self), PyObject *args, PyObject *kwds); /* * This is the 'busday_count' function exposed for calling * from Python. */ NPY_NO_EXPORT PyObject * array_busday_count(PyObject *NPY_UNUSED(self), PyObject *args, PyObject *kwds); /* * This is the 'is_busday' function exposed for calling * from Python. */ NPY_NO_EXPORT PyObject * array_is_busday(PyObject *NPY_UNUSED(self), PyObject *args, PyObject *kwds); #endif numpy-1.8.2/numpy/core/src/multiarray/arraytypes.h0000664000175100017510000000045612370216242023464 0ustar vagrantvagrant00000000000000#ifndef _NPY_ARRAYTYPES_H_ #define _NPY_ARRAYTYPES_H_ #ifdef NPY_ENABLE_SEPARATE_COMPILATION extern NPY_NO_EXPORT PyArray_Descr LONGLONG_Descr; extern NPY_NO_EXPORT PyArray_Descr LONG_Descr; extern NPY_NO_EXPORT PyArray_Descr INT_Descr; #endif NPY_NO_EXPORT int set_typeinfo(PyObject *dict); #endif numpy-1.8.2/numpy/core/src/multiarray/ctors.h0000664000175100017510000000515412370216242022413 0ustar vagrantvagrant00000000000000#ifndef _NPY_ARRAY_CTORS_H_ #define _NPY_ARRAY_CTORS_H_ NPY_NO_EXPORT PyObject * PyArray_NewFromDescr(PyTypeObject *subtype, PyArray_Descr *descr, int nd, npy_intp *dims, npy_intp *strides, void *data, int flags, PyObject *obj); NPY_NO_EXPORT PyObject *PyArray_New(PyTypeObject *, int nd, npy_intp *, int, npy_intp *, void *, int, int, PyObject *); NPY_NO_EXPORT PyObject * PyArray_FromAny(PyObject *op, PyArray_Descr *newtype, int min_depth, int max_depth, int flags, PyObject *context); NPY_NO_EXPORT PyObject * PyArray_CheckFromAny(PyObject *op, PyArray_Descr *descr, int min_depth, int max_depth, int requires, PyObject *context); NPY_NO_EXPORT PyObject * PyArray_FromArray(PyArrayObject *arr, PyArray_Descr *newtype, int flags); NPY_NO_EXPORT PyObject * PyArray_FromStructInterface(PyObject *input); NPY_NO_EXPORT PyObject * PyArray_FromInterface(PyObject *input); NPY_NO_EXPORT PyObject * PyArray_FromArrayAttr(PyObject *op, PyArray_Descr *typecode, PyObject *context); NPY_NO_EXPORT PyObject * PyArray_EnsureArray(PyObject *op); NPY_NO_EXPORT PyObject * PyArray_EnsureAnyArray(PyObject *op); NPY_NO_EXPORT int PyArray_MoveInto(PyArrayObject *dest, PyArrayObject *src); NPY_NO_EXPORT int PyArray_CopyAnyInto(PyArrayObject *dest, PyArrayObject *src); NPY_NO_EXPORT PyObject * PyArray_CheckAxis(PyArrayObject *arr, int *axis, int flags); /* TODO: Put the order parameter in PyArray_CopyAnyInto and remove this */ NPY_NO_EXPORT int PyArray_CopyAsFlat(PyArrayObject *dst, PyArrayObject *src, NPY_ORDER order); /* FIXME: remove those from here */ NPY_NO_EXPORT size_t _array_fill_strides(npy_intp *strides, npy_intp *dims, int nd, size_t itemsize, int inflag, int *objflags); NPY_NO_EXPORT void _unaligned_strided_byte_copy(char *dst, npy_intp outstrides, char *src, npy_intp instrides, npy_intp N, int elsize); NPY_NO_EXPORT void _strided_byte_swap(void *p, npy_intp stride, npy_intp n, int size); NPY_NO_EXPORT void copy_and_swap(void *dst, void *src, int itemsize, npy_intp numitems, npy_intp srcstrides, int swap); NPY_NO_EXPORT void byte_swap_vector(void *p, npy_intp n, int size); NPY_NO_EXPORT int PyArray_AssignFromSequence(PyArrayObject *self, PyObject *v); /* * Calls arr_of_subclass.__array_wrap__(towrap), in order to make 'towrap' * have the same ndarray subclass as 'arr_of_subclass'. */ NPY_NO_EXPORT PyArrayObject * PyArray_SubclassWrap(PyArrayObject *arr_of_subclass, PyArrayObject *towrap); #endif numpy-1.8.2/numpy/core/src/multiarray/datetime_strings.h0000664000175100017510000000721412370216242024625 0ustar vagrantvagrant00000000000000#ifndef _NPY_PRIVATE__DATETIME_STRINGS_H_ #define _NPY_PRIVATE__DATETIME_STRINGS_H_ /* * Parses (almost) standard ISO 8601 date strings. The differences are: * * + The date "20100312" is parsed as the year 20100312, not as * equivalent to "2010-03-12". The '-' in the dates are not optional. * + Only seconds may have a decimal point, with up to 18 digits after it * (maximum attoseconds precision). * + Either a 'T' as in ISO 8601 or a ' ' may be used to separate * the date and the time. Both are treated equivalently. * + Doesn't (yet) handle the "YYYY-DDD" or "YYYY-Www" formats. * + Doesn't handle leap seconds (seconds value has 60 in these cases). * + Doesn't handle 24:00:00 as synonym for midnight (00:00:00) tomorrow * + Accepts special values "NaT" (not a time), "Today", (current * day according to local time) and "Now" (current time in UTC). * * 'str' must be a NULL-terminated string, and 'len' must be its length. * 'unit' should contain -1 if the unit is unknown, or the unit * which will be used if it is. * 'casting' controls how the detected unit from the string is allowed * to be cast to the 'unit' parameter. * * 'out' gets filled with the parsed date-time. * 'out_local' gets set to 1 if the parsed time was in local time, * to 0 otherwise. The values 'now' and 'today' don't get counted * as local, and neither do UTC +/-#### timezone offsets, because * they aren't using the computer's local timezone offset. * 'out_bestunit' gives a suggested unit based on the amount of * resolution provided in the string, or -1 for NaT. * 'out_special' gets set to 1 if the parsed time was 'today', * 'now', or ''/'NaT'. For 'today', the unit recommended is * 'D', for 'now', the unit recommended is 's', and for 'NaT' * the unit recommended is 'Y'. * * Returns 0 on success, -1 on failure. */ NPY_NO_EXPORT int parse_iso_8601_datetime(char *str, Py_ssize_t len, NPY_DATETIMEUNIT unit, NPY_CASTING casting, npy_datetimestruct *out, npy_bool *out_local, NPY_DATETIMEUNIT *out_bestunit, npy_bool *out_special); /* * Provides a string length to use for converting datetime * objects with the given local and unit settings. */ NPY_NO_EXPORT int get_datetime_iso_8601_strlen(int local, NPY_DATETIMEUNIT base); /* * Converts an npy_datetimestruct to an (almost) ISO 8601 * NULL-terminated string. * * If 'local' is non-zero, it produces a string in local time with * a +-#### timezone offset, otherwise it uses timezone Z (UTC). * * 'base' restricts the output to that unit. Set 'base' to * -1 to auto-detect a base after which all the values are zero. * * 'tzoffset' is used if 'local' is enabled, and 'tzoffset' is * set to a value other than -1. This is a manual override for * the local time zone to use, as an offset in minutes. * * 'casting' controls whether data loss is allowed by truncating * the data to a coarser unit. This interacts with 'local', slightly, * in order to form a date unit string as a local time, the casting * must be unsafe. * * Returns 0 on success, -1 on failure (for example if the output * string was too short). */ NPY_NO_EXPORT int make_iso_8601_datetime(npy_datetimestruct *dts, char *outstr, int outlen, int local, NPY_DATETIMEUNIT base, int tzoffset, NPY_CASTING casting); /* * This is the Python-exposed datetime_as_string function. */ NPY_NO_EXPORT PyObject * array_datetime_as_string(PyObject *NPY_UNUSED(self), PyObject *args, PyObject *kwds); #endif numpy-1.8.2/numpy/core/src/multiarray/numpymemoryview.h0000664000175100017510000000131612370216242024551 0ustar vagrantvagrant00000000000000#ifndef _NPY_PRIVATE_NUMPYMEMORYVIEW_H_ #define _NPY_PRIVATE_NUMPYMEMORYVIEW_H_ /* * Memoryview is introduced to 2.x series only in 2.7, so for supporting 2.6, * we need to have a minimal implementation here. */ #if PY_VERSION_HEX < 0x02070000 typedef struct { PyObject_HEAD PyObject *base; Py_buffer view; } PyMemorySimpleViewObject; NPY_NO_EXPORT PyObject * PyMemorySimpleView_FromObject(PyObject *base); #define PyMemorySimpleView_GET_BUFFER(op) (&((PyMemorySimpleViewObject *)(op))->view) #define PyMemoryView_FromObject PyMemorySimpleView_FromObject #define PyMemoryView_GET_BUFFER PyMemorySimpleView_GET_BUFFER #endif NPY_NO_EXPORT int _numpymemoryview_init(PyObject **typeobject); #endif numpy-1.8.2/numpy/core/src/multiarray/dtype_transfer.c0000664000175100017510000044203012370216243024304 0ustar vagrantvagrant00000000000000/* * This file contains low-level loops for data type transfers. * In particular the function PyArray_GetDTypeTransferFunction is * implemented here. * * Copyright (c) 2010 by Mark Wiebe (mwwiebe@gmail.com) * The Univerity of British Columbia * * See LICENSE.txt for the license. */ #define PY_SSIZE_T_CLEAN #include "Python.h" #include "structmember.h" #define NPY_NO_DEPRECATED_API NPY_API_VERSION #define _MULTIARRAYMODULE #include #include #include "npy_pycompat.h" #include "convert_datatype.h" #include "_datetime.h" #include "datetime_strings.h" #include "shape.h" #include "lowlevel_strided_loops.h" #define NPY_LOWLEVEL_BUFFER_BLOCKSIZE 128 /********** PRINTF DEBUG TRACING **************/ #define NPY_DT_DBG_TRACING 0 /* Tracing incref/decref can be very noisy */ #define NPY_DT_REF_DBG_TRACING 0 #if NPY_DT_REF_DBG_TRACING #define NPY_DT_DBG_REFTRACE(msg, ref) \ printf("%-12s %20p %s%d%s\n", msg, ref, \ ref ? "(refcnt " : "", \ ref ? (int)ref->ob_refcnt : 0, \ ref ? ((ref->ob_refcnt <= 0) ? \ ") <- BIG PROBLEM!!!!" : ")") : ""); \ fflush(stdout); #else #define NPY_DT_DBG_REFTRACE(msg, ref) #endif /**********************************************/ /* * Returns a transfer function which DECREFs any references in src_type. * * Returns NPY_SUCCEED or NPY_FAIL. */ static int get_decsrcref_transfer_function(int aligned, npy_intp src_stride, PyArray_Descr *src_dtype, PyArray_StridedUnaryOp **out_stransfer, NpyAuxData **out_transferdata, int *out_needs_api); /* * Returns a transfer function which zeros out the dest values. * * Returns NPY_SUCCEED or NPY_FAIL. */ static int get_setdstzero_transfer_function(int aligned, npy_intp dst_stride, PyArray_Descr *dst_dtype, PyArray_StridedUnaryOp **out_stransfer, NpyAuxData **out_transferdata, int *out_needs_api); /* * Returns a transfer function which sets a boolean type to ones. * * Returns NPY_SUCCEED or NPY_FAIL. */ NPY_NO_EXPORT int get_bool_setdstone_transfer_function(npy_intp dst_stride, PyArray_StridedUnaryOp **out_stransfer, NpyAuxData **out_transferdata, int *NPY_UNUSED(out_needs_api)); /*************************** COPY REFERENCES *******************************/ /* Moves references from src to dst */ static void _strided_to_strided_move_references(char *dst, npy_intp dst_stride, char *src, npy_intp src_stride, npy_intp N, npy_intp src_itemsize, NpyAuxData *data) { PyObject *src_ref = NULL, *dst_ref = NULL; while (N > 0) { NPY_COPY_PYOBJECT_PTR(&src_ref, src); NPY_COPY_PYOBJECT_PTR(&dst_ref, dst); /* Release the reference in dst */ NPY_DT_DBG_REFTRACE("dec dst ref", dst_ref); Py_XDECREF(dst_ref); /* Move the reference */ NPY_DT_DBG_REFTRACE("move src ref", src_ref); NPY_COPY_PYOBJECT_PTR(dst, &src_ref); /* Set the source reference to NULL */ src_ref = NULL; NPY_COPY_PYOBJECT_PTR(src, &src_ref); src += src_stride; dst += dst_stride; --N; } } /* Copies references from src to dst */ static void _strided_to_strided_copy_references(char *dst, npy_intp dst_stride, char *src, npy_intp src_stride, npy_intp N, npy_intp src_itemsize, NpyAuxData *data) { PyObject *src_ref = NULL, *dst_ref = NULL; while (N > 0) { NPY_COPY_PYOBJECT_PTR(&src_ref, src); NPY_COPY_PYOBJECT_PTR(&dst_ref, dst); /* Copy the reference */ NPY_DT_DBG_REFTRACE("copy src ref", src_ref); NPY_COPY_PYOBJECT_PTR(dst, &src_ref); /* Claim the reference */ Py_XINCREF(src_ref); /* Release the reference in dst */ NPY_DT_DBG_REFTRACE("dec dst ref", dst_ref); Py_XDECREF(dst_ref); src += src_stride; dst += dst_stride; --N; } } /************************** ZERO-PADDED COPY ******************************/ /* Does a zero-padded copy */ typedef struct { NpyAuxData base; npy_intp dst_itemsize; } _strided_zero_pad_data; /* zero-padded data copy function */ NpyAuxData *_strided_zero_pad_data_clone(NpyAuxData *data) { _strided_zero_pad_data *newdata = (_strided_zero_pad_data *)PyArray_malloc( sizeof(_strided_zero_pad_data)); if (newdata == NULL) { return NULL; } memcpy(newdata, data, sizeof(_strided_zero_pad_data)); return (NpyAuxData *)newdata; } /* * Does a strided to strided zero-padded copy for the case where * dst_itemsize > src_itemsize */ static void _strided_to_strided_zero_pad_copy(char *dst, npy_intp dst_stride, char *src, npy_intp src_stride, npy_intp N, npy_intp src_itemsize, NpyAuxData *data) { _strided_zero_pad_data *d = (_strided_zero_pad_data *)data; npy_intp dst_itemsize = d->dst_itemsize; npy_intp zero_size = dst_itemsize-src_itemsize; while (N > 0) { memcpy(dst, src, src_itemsize); memset(dst + src_itemsize, 0, zero_size); src += src_stride; dst += dst_stride; --N; } } /* * Does a strided to strided zero-padded copy for the case where * dst_itemsize < src_itemsize */ static void _strided_to_strided_truncate_copy(char *dst, npy_intp dst_stride, char *src, npy_intp src_stride, npy_intp N, npy_intp src_itemsize, NpyAuxData *data) { _strided_zero_pad_data *d = (_strided_zero_pad_data *)data; npy_intp dst_itemsize = d->dst_itemsize; while (N > 0) { memcpy(dst, src, dst_itemsize); src += src_stride; dst += dst_stride; --N; } } NPY_NO_EXPORT int PyArray_GetStridedZeroPadCopyFn(int aligned, npy_intp src_stride, npy_intp dst_stride, npy_intp src_itemsize, npy_intp dst_itemsize, PyArray_StridedUnaryOp **out_stransfer, NpyAuxData **out_transferdata) { if (src_itemsize == dst_itemsize) { *out_stransfer = PyArray_GetStridedCopyFn(aligned, src_stride, dst_stride, src_itemsize); *out_transferdata = NULL; return (*out_stransfer == NULL) ? NPY_FAIL : NPY_SUCCEED; } else { _strided_zero_pad_data *d = PyArray_malloc( sizeof(_strided_zero_pad_data)); if (d == NULL) { PyErr_NoMemory(); return NPY_FAIL; } d->dst_itemsize = dst_itemsize; d->base.free = (NpyAuxData_FreeFunc *)&PyArray_free; d->base.clone = &_strided_zero_pad_data_clone; if (src_itemsize < dst_itemsize) { *out_stransfer = &_strided_to_strided_zero_pad_copy; } else { *out_stransfer = &_strided_to_strided_truncate_copy; } *out_transferdata = (NpyAuxData *)d; return NPY_SUCCEED; } } /***************** WRAP ALIGNED CONTIGUOUS TRANSFER FUNCTION **************/ /* Wraps a transfer function + data in alignment code */ typedef struct { NpyAuxData base; PyArray_StridedUnaryOp *wrapped, *tobuffer, *frombuffer; NpyAuxData *wrappeddata, *todata, *fromdata; npy_intp src_itemsize, dst_itemsize; char *bufferin, *bufferout; } _align_wrap_data; /* transfer data free function */ void _align_wrap_data_free(NpyAuxData *data) { _align_wrap_data *d = (_align_wrap_data *)data; NPY_AUXDATA_FREE(d->wrappeddata); NPY_AUXDATA_FREE(d->todata); NPY_AUXDATA_FREE(d->fromdata); PyArray_free(data); } /* transfer data copy function */ NpyAuxData *_align_wrap_data_clone(NpyAuxData *data) { _align_wrap_data *d = (_align_wrap_data *)data; _align_wrap_data *newdata; npy_intp basedatasize, datasize; /* Round up the structure size to 16-byte boundary */ basedatasize = (sizeof(_align_wrap_data)+15)&(-0x10); /* Add space for two low level buffers */ datasize = basedatasize + NPY_LOWLEVEL_BUFFER_BLOCKSIZE*d->src_itemsize + NPY_LOWLEVEL_BUFFER_BLOCKSIZE*d->dst_itemsize; /* Allocate the data, and populate it */ newdata = (_align_wrap_data *)PyArray_malloc(datasize); if (newdata == NULL) { return NULL; } memcpy(newdata, data, basedatasize); newdata->bufferin = (char *)newdata + basedatasize; newdata->bufferout = newdata->bufferin + NPY_LOWLEVEL_BUFFER_BLOCKSIZE*newdata->src_itemsize; if (newdata->wrappeddata != NULL) { newdata->wrappeddata = NPY_AUXDATA_CLONE(d->wrappeddata); if (newdata->wrappeddata == NULL) { PyArray_free(newdata); return NULL; } } if (newdata->todata != NULL) { newdata->todata = NPY_AUXDATA_CLONE(d->todata); if (newdata->todata == NULL) { NPY_AUXDATA_FREE(newdata->wrappeddata); PyArray_free(newdata); return NULL; } } if (newdata->fromdata != NULL) { newdata->fromdata = NPY_AUXDATA_CLONE(d->fromdata); if (newdata->fromdata == NULL) { NPY_AUXDATA_FREE(newdata->wrappeddata); NPY_AUXDATA_FREE(newdata->todata); PyArray_free(newdata); return NULL; } } return (NpyAuxData *)newdata; } static void _strided_to_strided_contig_align_wrap(char *dst, npy_intp dst_stride, char *src, npy_intp src_stride, npy_intp N, npy_intp src_itemsize, NpyAuxData *data) { _align_wrap_data *d = (_align_wrap_data *)data; PyArray_StridedUnaryOp *wrapped = d->wrapped, *tobuffer = d->tobuffer, *frombuffer = d->frombuffer; npy_intp inner_src_itemsize = d->src_itemsize, dst_itemsize = d->dst_itemsize; NpyAuxData *wrappeddata = d->wrappeddata, *todata = d->todata, *fromdata = d->fromdata; char *bufferin = d->bufferin, *bufferout = d->bufferout; for(;;) { if (N > NPY_LOWLEVEL_BUFFER_BLOCKSIZE) { tobuffer(bufferin, inner_src_itemsize, src, src_stride, NPY_LOWLEVEL_BUFFER_BLOCKSIZE, src_itemsize, todata); wrapped(bufferout, dst_itemsize, bufferin, inner_src_itemsize, NPY_LOWLEVEL_BUFFER_BLOCKSIZE, inner_src_itemsize, wrappeddata); frombuffer(dst, dst_stride, bufferout, dst_itemsize, NPY_LOWLEVEL_BUFFER_BLOCKSIZE, dst_itemsize, fromdata); N -= NPY_LOWLEVEL_BUFFER_BLOCKSIZE; src += NPY_LOWLEVEL_BUFFER_BLOCKSIZE*src_stride; dst += NPY_LOWLEVEL_BUFFER_BLOCKSIZE*dst_stride; } else { tobuffer(bufferin, inner_src_itemsize, src, src_stride, N, src_itemsize, todata); wrapped(bufferout, dst_itemsize, bufferin, inner_src_itemsize, N, inner_src_itemsize, wrappeddata); frombuffer(dst, dst_stride, bufferout, dst_itemsize, N, dst_itemsize, fromdata); return; } } } static void _strided_to_strided_contig_align_wrap_init_dest(char *dst, npy_intp dst_stride, char *src, npy_intp src_stride, npy_intp N, npy_intp src_itemsize, NpyAuxData *data) { _align_wrap_data *d = (_align_wrap_data *)data; PyArray_StridedUnaryOp *wrapped = d->wrapped, *tobuffer = d->tobuffer, *frombuffer = d->frombuffer; npy_intp inner_src_itemsize = d->src_itemsize, dst_itemsize = d->dst_itemsize; NpyAuxData *wrappeddata = d->wrappeddata, *todata = d->todata, *fromdata = d->fromdata; char *bufferin = d->bufferin, *bufferout = d->bufferout; for(;;) { if (N > NPY_LOWLEVEL_BUFFER_BLOCKSIZE) { tobuffer(bufferin, inner_src_itemsize, src, src_stride, NPY_LOWLEVEL_BUFFER_BLOCKSIZE, src_itemsize, todata); memset(bufferout, 0, dst_itemsize*NPY_LOWLEVEL_BUFFER_BLOCKSIZE); wrapped(bufferout, dst_itemsize, bufferin, inner_src_itemsize, NPY_LOWLEVEL_BUFFER_BLOCKSIZE, inner_src_itemsize, wrappeddata); frombuffer(dst, dst_stride, bufferout, dst_itemsize, NPY_LOWLEVEL_BUFFER_BLOCKSIZE, dst_itemsize, fromdata); N -= NPY_LOWLEVEL_BUFFER_BLOCKSIZE; src += NPY_LOWLEVEL_BUFFER_BLOCKSIZE*src_stride; dst += NPY_LOWLEVEL_BUFFER_BLOCKSIZE*dst_stride; } else { tobuffer(bufferin, inner_src_itemsize, src, src_stride, N, src_itemsize, todata); memset(bufferout, 0, dst_itemsize*N); wrapped(bufferout, dst_itemsize, bufferin, inner_src_itemsize, N, inner_src_itemsize, wrappeddata); frombuffer(dst, dst_stride, bufferout, dst_itemsize, N, dst_itemsize, fromdata); return; } } } /* * Wraps an aligned contig to contig transfer function between either * copies or byte swaps to temporary buffers. * * src_itemsize/dst_itemsize - The sizes of the src and dst datatypes. * tobuffer - copy/swap function from src to an aligned contiguous buffer. * todata - data for tobuffer * frombuffer - copy/swap function from an aligned contiguous buffer to dst. * fromdata - data for frombuffer * wrapped - contig to contig transfer function being wrapped * wrappeddata - data for wrapped * init_dest - 1 means to memset the dest buffer to 0 before calling wrapped. * * Returns NPY_SUCCEED or NPY_FAIL. */ NPY_NO_EXPORT int wrap_aligned_contig_transfer_function( npy_intp src_itemsize, npy_intp dst_itemsize, PyArray_StridedUnaryOp *tobuffer, NpyAuxData *todata, PyArray_StridedUnaryOp *frombuffer, NpyAuxData *fromdata, PyArray_StridedUnaryOp *wrapped, NpyAuxData *wrappeddata, int init_dest, PyArray_StridedUnaryOp **out_stransfer, NpyAuxData **out_transferdata) { _align_wrap_data *data; npy_intp basedatasize, datasize; /* Round up the structure size to 16-byte boundary */ basedatasize = (sizeof(_align_wrap_data)+15)&(-0x10); /* Add space for two low level buffers */ datasize = basedatasize + NPY_LOWLEVEL_BUFFER_BLOCKSIZE*src_itemsize + NPY_LOWLEVEL_BUFFER_BLOCKSIZE*dst_itemsize; /* Allocate the data, and populate it */ data = (_align_wrap_data *)PyArray_malloc(datasize); if (data == NULL) { PyErr_NoMemory(); return NPY_FAIL; } data->base.free = &_align_wrap_data_free; data->base.clone = &_align_wrap_data_clone; data->tobuffer = tobuffer; data->todata = todata; data->frombuffer = frombuffer; data->fromdata = fromdata; data->wrapped = wrapped; data->wrappeddata = wrappeddata; data->src_itemsize = src_itemsize; data->dst_itemsize = dst_itemsize; data->bufferin = (char *)data + basedatasize; data->bufferout = data->bufferin + NPY_LOWLEVEL_BUFFER_BLOCKSIZE*src_itemsize; /* Set the function and data */ if (init_dest) { *out_stransfer = &_strided_to_strided_contig_align_wrap_init_dest; } else { *out_stransfer = &_strided_to_strided_contig_align_wrap; } *out_transferdata = (NpyAuxData *)data; return NPY_SUCCEED; } /*************************** WRAP DTYPE COPY/SWAP *************************/ /* Wraps the dtype copy swap function */ typedef struct { NpyAuxData base; PyArray_CopySwapNFunc *copyswapn; int swap; PyArrayObject *arr; } _wrap_copy_swap_data; /* wrap copy swap data free function */ void _wrap_copy_swap_data_free(NpyAuxData *data) { _wrap_copy_swap_data *d = (_wrap_copy_swap_data *)data; Py_DECREF(d->arr); PyArray_free(data); } /* wrap copy swap data copy function */ NpyAuxData *_wrap_copy_swap_data_clone(NpyAuxData *data) { _wrap_copy_swap_data *newdata = (_wrap_copy_swap_data *)PyArray_malloc(sizeof(_wrap_copy_swap_data)); if (newdata == NULL) { return NULL; } memcpy(newdata, data, sizeof(_wrap_copy_swap_data)); Py_INCREF(newdata->arr); return (NpyAuxData *)newdata; } static void _strided_to_strided_wrap_copy_swap(char *dst, npy_intp dst_stride, char *src, npy_intp src_stride, npy_intp N, npy_intp NPY_UNUSED(src_itemsize), NpyAuxData *data) { _wrap_copy_swap_data *d = (_wrap_copy_swap_data *)data; d->copyswapn(dst, dst_stride, src, src_stride, N, d->swap, d->arr); } /* This only gets used for custom data types */ static int wrap_copy_swap_function(int aligned, npy_intp src_stride, npy_intp dst_stride, PyArray_Descr *dtype, int should_swap, PyArray_StridedUnaryOp **out_stransfer, NpyAuxData **out_transferdata) { _wrap_copy_swap_data *data; npy_intp shape = 1; /* Allocate the data for the copy swap */ data = (_wrap_copy_swap_data *)PyArray_malloc(sizeof(_wrap_copy_swap_data)); if (data == NULL) { PyErr_NoMemory(); *out_stransfer = NULL; *out_transferdata = NULL; return NPY_FAIL; } data->base.free = &_wrap_copy_swap_data_free; data->base.clone = &_wrap_copy_swap_data_clone; data->copyswapn = dtype->f->copyswapn; data->swap = should_swap; /* * TODO: This is a hack so the copyswap functions have an array. * The copyswap functions shouldn't need that. */ Py_INCREF(dtype); data->arr = (PyArrayObject *)PyArray_NewFromDescr(&PyArray_Type, dtype, 1, &shape, NULL, NULL, 0, NULL); if (data->arr == NULL) { PyArray_free(data); return NPY_FAIL; } *out_stransfer = &_strided_to_strided_wrap_copy_swap; *out_transferdata = (NpyAuxData *)data; return NPY_SUCCEED; } /*************************** DTYPE CAST FUNCTIONS *************************/ /* Does a simple aligned cast */ typedef struct { NpyAuxData base; PyArray_VectorUnaryFunc *castfunc; PyArrayObject *aip, *aop; } _strided_cast_data; /* strided cast data free function */ void _strided_cast_data_free(NpyAuxData *data) { _strided_cast_data *d = (_strided_cast_data *)data; Py_DECREF(d->aip); Py_DECREF(d->aop); PyArray_free(data); } /* strided cast data copy function */ NpyAuxData *_strided_cast_data_clone(NpyAuxData *data) { _strided_cast_data *newdata = (_strided_cast_data *)PyArray_malloc(sizeof(_strided_cast_data)); if (newdata == NULL) { return NULL; } memcpy(newdata, data, sizeof(_strided_cast_data)); Py_INCREF(newdata->aip); Py_INCREF(newdata->aop); return (NpyAuxData *)newdata; } static void _aligned_strided_to_strided_cast(char *dst, npy_intp dst_stride, char *src, npy_intp src_stride, npy_intp N, npy_intp src_itemsize, NpyAuxData *data) { _strided_cast_data *d = (_strided_cast_data *)data; PyArray_VectorUnaryFunc *castfunc = d->castfunc; PyArrayObject *aip = d->aip, *aop = d->aop; while (N > 0) { castfunc(src, dst, 1, aip, aop); dst += dst_stride; src += src_stride; --N; } } /* This one requires src be of type NPY_OBJECT */ static void _aligned_strided_to_strided_cast_decref_src(char *dst, npy_intp dst_stride, char *src, npy_intp src_stride, npy_intp N, npy_intp src_itemsize, NpyAuxData *data) { _strided_cast_data *d = (_strided_cast_data *)data; PyArray_VectorUnaryFunc *castfunc = d->castfunc; PyArrayObject *aip = d->aip, *aop = d->aop; PyObject *src_ref; while (N > 0) { castfunc(src, dst, 1, aip, aop); /* After casting, decrement the source ref */ NPY_COPY_PYOBJECT_PTR(&src_ref, src); NPY_DT_DBG_REFTRACE("dec src ref (cast object -> not object)", src_ref); Py_XDECREF(src_ref); dst += dst_stride; src += src_stride; --N; } } static void _aligned_contig_to_contig_cast(char *dst, npy_intp NPY_UNUSED(dst_stride), char *src, npy_intp NPY_UNUSED(src_stride), npy_intp N, npy_intp NPY_UNUSED(itemsize), NpyAuxData *data) { _strided_cast_data *d = (_strided_cast_data *)data; d->castfunc(src, dst, N, d->aip, d->aop); } static int get_nbo_cast_numeric_transfer_function(int aligned, npy_intp src_stride, npy_intp dst_stride, int src_type_num, int dst_type_num, PyArray_StridedUnaryOp **out_stransfer, NpyAuxData **out_transferdata) { /* Emit a warning if complex imaginary is being cast away */ if (PyTypeNum_ISCOMPLEX(src_type_num) && !PyTypeNum_ISCOMPLEX(dst_type_num) && !PyTypeNum_ISBOOL(dst_type_num)) { PyObject *cls = NULL, *obj = NULL; int ret; obj = PyImport_ImportModule("numpy.core"); if (obj) { cls = PyObject_GetAttrString(obj, "ComplexWarning"); Py_DECREF(obj); } ret = PyErr_WarnEx(cls, "Casting complex values to real discards " "the imaginary part", 1); Py_XDECREF(cls); if (ret < 0) { return NPY_FAIL; } } *out_stransfer = PyArray_GetStridedNumericCastFn(aligned, src_stride, dst_stride, src_type_num, dst_type_num); *out_transferdata = NULL; if (*out_stransfer == NULL) { PyErr_SetString(PyExc_ValueError, "unexpected error in GetStridedNumericCastFn"); return NPY_FAIL; } return NPY_SUCCEED; } /* * Does a datetime->datetime, timedelta->timedelta, * datetime->ascii, or ascii->datetime cast */ typedef struct { NpyAuxData base; /* The conversion fraction */ npy_int64 num, denom; /* For the datetime -> string conversion, the dst string length */ npy_intp src_itemsize, dst_itemsize; /* * A buffer of size 'src_itemsize + 1', for when the input * string is exactly of length src_itemsize with no NULL * terminator. */ char *tmp_buffer; /* * The metadata for when dealing with Months or Years * which behave non-linearly with respect to the other * units. */ PyArray_DatetimeMetaData src_meta, dst_meta; } _strided_datetime_cast_data; /* strided datetime cast data free function */ void _strided_datetime_cast_data_free(NpyAuxData *data) { _strided_datetime_cast_data *d = (_strided_datetime_cast_data *)data; if (d->tmp_buffer != NULL) { PyArray_free(d->tmp_buffer); } PyArray_free(data); } /* strided datetime cast data copy function */ NpyAuxData *_strided_datetime_cast_data_clone(NpyAuxData *data) { _strided_datetime_cast_data *newdata = (_strided_datetime_cast_data *)PyArray_malloc( sizeof(_strided_datetime_cast_data)); if (newdata == NULL) { return NULL; } memcpy(newdata, data, sizeof(_strided_datetime_cast_data)); if (newdata->tmp_buffer != NULL) { newdata->tmp_buffer = PyArray_malloc(newdata->src_itemsize + 1); if (newdata->tmp_buffer == NULL) { PyArray_free(newdata); return NULL; } } return (NpyAuxData *)newdata; } static void _strided_to_strided_datetime_general_cast(char *dst, npy_intp dst_stride, char *src, npy_intp src_stride, npy_intp N, npy_intp src_itemsize, NpyAuxData *data) { _strided_datetime_cast_data *d = (_strided_datetime_cast_data *)data; npy_int64 dt; npy_datetimestruct dts; while (N > 0) { memcpy(&dt, src, sizeof(dt)); if (convert_datetime_to_datetimestruct(&d->src_meta, dt, &dts) < 0) { dt = NPY_DATETIME_NAT; } else { if (convert_datetimestruct_to_datetime(&d->dst_meta, &dts, &dt) < 0) { dt = NPY_DATETIME_NAT; } } memcpy(dst, &dt, sizeof(dt)); dst += dst_stride; src += src_stride; --N; } } static void _strided_to_strided_datetime_cast(char *dst, npy_intp dst_stride, char *src, npy_intp src_stride, npy_intp N, npy_intp src_itemsize, NpyAuxData *data) { _strided_datetime_cast_data *d = (_strided_datetime_cast_data *)data; npy_int64 num = d->num, denom = d->denom; npy_int64 dt; while (N > 0) { memcpy(&dt, src, sizeof(dt)); if (dt != NPY_DATETIME_NAT) { /* Apply the scaling */ if (dt < 0) { dt = (dt * num - (denom - 1)) / denom; } else { dt = dt * num / denom; } } memcpy(dst, &dt, sizeof(dt)); dst += dst_stride; src += src_stride; --N; } } static void _aligned_strided_to_strided_datetime_cast(char *dst, npy_intp dst_stride, char *src, npy_intp src_stride, npy_intp N, npy_intp src_itemsize, NpyAuxData *data) { _strided_datetime_cast_data *d = (_strided_datetime_cast_data *)data; npy_int64 num = d->num, denom = d->denom; npy_int64 dt; while (N > 0) { dt = *(npy_int64 *)src; if (dt != NPY_DATETIME_NAT) { /* Apply the scaling */ if (dt < 0) { dt = (dt * num - (denom - 1)) / denom; } else { dt = dt * num / denom; } } *(npy_int64 *)dst = dt; dst += dst_stride; src += src_stride; --N; } } static void _strided_to_strided_datetime_to_string(char *dst, npy_intp dst_stride, char *src, npy_intp src_stride, npy_intp N, npy_intp NPY_UNUSED(src_itemsize), NpyAuxData *data) { _strided_datetime_cast_data *d = (_strided_datetime_cast_data *)data; npy_intp dst_itemsize = d->dst_itemsize; npy_int64 dt; npy_datetimestruct dts; while (N > 0) { memcpy(&dt, src, sizeof(dt)); if (convert_datetime_to_datetimestruct(&d->src_meta, dt, &dts) < 0) { /* For an error, produce a 'NaT' string */ dts.year = NPY_DATETIME_NAT; } /* Initialize the destination to all zeros */ memset(dst, 0, dst_itemsize); /* * This may also raise an error, but the caller needs * to use PyErr_Occurred(). */ make_iso_8601_datetime(&dts, dst, dst_itemsize, 0, d->src_meta.base, -1, NPY_UNSAFE_CASTING); dst += dst_stride; src += src_stride; --N; } } static void _strided_to_strided_string_to_datetime(char *dst, npy_intp dst_stride, char *src, npy_intp src_stride, npy_intp N, npy_intp src_itemsize, NpyAuxData *data) { _strided_datetime_cast_data *d = (_strided_datetime_cast_data *)data; npy_datetimestruct dts; char *tmp_buffer = d->tmp_buffer; char *tmp; while (N > 0) { npy_int64 dt = ~NPY_DATETIME_NAT; /* Replicating strnlen with memchr, because Mac OS X lacks it */ tmp = memchr(src, '\0', src_itemsize); /* If the string is all full, use the buffer */ if (tmp == NULL) { memcpy(tmp_buffer, src, src_itemsize); tmp_buffer[src_itemsize] = '\0'; if (parse_iso_8601_datetime(tmp_buffer, src_itemsize, d->dst_meta.base, NPY_SAME_KIND_CASTING, &dts, NULL, NULL, NULL) < 0) { dt = NPY_DATETIME_NAT; } } /* Otherwise parse the data in place */ else { if (parse_iso_8601_datetime(src, tmp - src, d->dst_meta.base, NPY_SAME_KIND_CASTING, &dts, NULL, NULL, NULL) < 0) { dt = NPY_DATETIME_NAT; } } /* Convert to the datetime */ if (dt != NPY_DATETIME_NAT && convert_datetimestruct_to_datetime(&d->dst_meta, &dts, &dt) < 0) { dt = NPY_DATETIME_NAT; } memcpy(dst, &dt, sizeof(dt)); dst += dst_stride; src += src_stride; --N; } } /* * Assumes src_dtype and dst_dtype are both datetimes or both timedeltas */ static int get_nbo_cast_datetime_transfer_function(int aligned, npy_intp src_stride, npy_intp dst_stride, PyArray_Descr *src_dtype, PyArray_Descr *dst_dtype, PyArray_StridedUnaryOp **out_stransfer, NpyAuxData **out_transferdata) { PyArray_DatetimeMetaData *src_meta, *dst_meta; npy_int64 num = 0, denom = 0; _strided_datetime_cast_data *data; src_meta = get_datetime_metadata_from_dtype(src_dtype); if (src_meta == NULL) { return NPY_FAIL; } dst_meta = get_datetime_metadata_from_dtype(dst_dtype); if (dst_meta == NULL) { return NPY_FAIL; } get_datetime_conversion_factor(src_meta, dst_meta, &num, &denom); if (num == 0) { return NPY_FAIL; } /* Allocate the data for the casting */ data = (_strided_datetime_cast_data *)PyArray_malloc( sizeof(_strided_datetime_cast_data)); if (data == NULL) { PyErr_NoMemory(); *out_stransfer = NULL; *out_transferdata = NULL; return NPY_FAIL; } data->base.free = &_strided_datetime_cast_data_free; data->base.clone = &_strided_datetime_cast_data_clone; data->num = num; data->denom = denom; data->tmp_buffer = NULL; /* * Special case the datetime (but not timedelta) with the nonlinear * units (years and months). For timedelta, an average * years and months value is used. */ if (src_dtype->type_num == NPY_DATETIME && (src_meta->base == NPY_FR_Y || src_meta->base == NPY_FR_M || dst_meta->base == NPY_FR_Y || dst_meta->base == NPY_FR_M)) { memcpy(&data->src_meta, src_meta, sizeof(data->src_meta)); memcpy(&data->dst_meta, dst_meta, sizeof(data->dst_meta)); *out_stransfer = &_strided_to_strided_datetime_general_cast; } else if (aligned) { *out_stransfer = &_aligned_strided_to_strided_datetime_cast; } else { *out_stransfer = &_strided_to_strided_datetime_cast; } *out_transferdata = (NpyAuxData *)data; #if NPY_DT_DBG_TRACING printf("Dtype transfer from "); PyObject_Print((PyObject *)src_dtype, stdout, 0); printf(" to "); PyObject_Print((PyObject *)dst_dtype, stdout, 0); printf("\n"); printf("has conversion fraction %lld/%lld\n", num, denom); #endif return NPY_SUCCEED; } static int get_nbo_datetime_to_string_transfer_function(int aligned, npy_intp src_stride, npy_intp dst_stride, PyArray_Descr *src_dtype, PyArray_Descr *dst_dtype, PyArray_StridedUnaryOp **out_stransfer, NpyAuxData **out_transferdata) { PyArray_DatetimeMetaData *src_meta; _strided_datetime_cast_data *data; src_meta = get_datetime_metadata_from_dtype(src_dtype); if (src_meta == NULL) { return NPY_FAIL; } /* Allocate the data for the casting */ data = (_strided_datetime_cast_data *)PyArray_malloc( sizeof(_strided_datetime_cast_data)); if (data == NULL) { PyErr_NoMemory(); *out_stransfer = NULL; *out_transferdata = NULL; return NPY_FAIL; } data->base.free = &_strided_datetime_cast_data_free; data->base.clone = &_strided_datetime_cast_data_clone; data->dst_itemsize = dst_dtype->elsize; data->tmp_buffer = NULL; memcpy(&data->src_meta, src_meta, sizeof(data->src_meta)); *out_stransfer = &_strided_to_strided_datetime_to_string; *out_transferdata = (NpyAuxData *)data; #if NPY_DT_DBG_TRACING printf("Dtype transfer from "); PyObject_Print((PyObject *)src_dtype, stdout, 0); printf(" to "); PyObject_Print((PyObject *)dst_dtype, stdout, 0); printf("\n"); #endif return NPY_SUCCEED; } static int get_datetime_to_unicode_transfer_function(int aligned, npy_intp src_stride, npy_intp dst_stride, PyArray_Descr *src_dtype, PyArray_Descr *dst_dtype, PyArray_StridedUnaryOp **out_stransfer, NpyAuxData **out_transferdata, int *out_needs_api) { NpyAuxData *castdata = NULL, *todata = NULL, *fromdata = NULL; PyArray_StridedUnaryOp *caststransfer, *tobuffer, *frombuffer; PyArray_Descr *str_dtype; /* Get an ASCII string data type, adapted to match the UNICODE one */ str_dtype = PyArray_DescrFromType(NPY_STRING); PyArray_AdaptFlexibleDType(NULL, dst_dtype, &str_dtype); if (str_dtype == NULL) { return NPY_FAIL; } /* Get the copy/swap operation to dst */ if (PyArray_GetDTypeCopySwapFn(aligned, src_stride, src_dtype->elsize, src_dtype, &tobuffer, &todata) != NPY_SUCCEED) { Py_DECREF(str_dtype); return NPY_FAIL; } /* Get the NBO datetime to string aligned contig function */ if (get_nbo_datetime_to_string_transfer_function(1, src_dtype->elsize, str_dtype->elsize, src_dtype, str_dtype, &caststransfer, &castdata) != NPY_SUCCEED) { Py_DECREF(str_dtype); NPY_AUXDATA_FREE(todata); return NPY_FAIL; } /* Get the cast operation to dst */ if (PyArray_GetDTypeTransferFunction(aligned, str_dtype->elsize, dst_stride, str_dtype, dst_dtype, 0, &frombuffer, &fromdata, out_needs_api) != NPY_SUCCEED) { Py_DECREF(str_dtype); NPY_AUXDATA_FREE(todata); NPY_AUXDATA_FREE(castdata); return NPY_FAIL; } /* Wrap it all up in a new transfer function + data */ if (wrap_aligned_contig_transfer_function( src_dtype->elsize, str_dtype->elsize, tobuffer, todata, frombuffer, fromdata, caststransfer, castdata, PyDataType_FLAGCHK(str_dtype, NPY_NEEDS_INIT), out_stransfer, out_transferdata) != NPY_SUCCEED) { NPY_AUXDATA_FREE(castdata); NPY_AUXDATA_FREE(todata); NPY_AUXDATA_FREE(fromdata); return NPY_FAIL; } Py_DECREF(str_dtype); return NPY_SUCCEED; } static int get_nbo_string_to_datetime_transfer_function(int aligned, npy_intp src_stride, npy_intp dst_stride, PyArray_Descr *src_dtype, PyArray_Descr *dst_dtype, PyArray_StridedUnaryOp **out_stransfer, NpyAuxData **out_transferdata) { PyArray_DatetimeMetaData *dst_meta; _strided_datetime_cast_data *data; dst_meta = get_datetime_metadata_from_dtype(dst_dtype); if (dst_meta == NULL) { return NPY_FAIL; } /* Allocate the data for the casting */ data = (_strided_datetime_cast_data *)PyArray_malloc( sizeof(_strided_datetime_cast_data)); if (data == NULL) { PyErr_NoMemory(); *out_stransfer = NULL; *out_transferdata = NULL; return NPY_FAIL; } data->base.free = &_strided_datetime_cast_data_free; data->base.clone = &_strided_datetime_cast_data_clone; data->src_itemsize = src_dtype->elsize; data->tmp_buffer = PyArray_malloc(data->src_itemsize + 1); if (data->tmp_buffer == NULL) { PyErr_NoMemory(); PyArray_free(data); *out_stransfer = NULL; *out_transferdata = NULL; return NPY_FAIL; } memcpy(&data->dst_meta, dst_meta, sizeof(data->dst_meta)); *out_stransfer = &_strided_to_strided_string_to_datetime; *out_transferdata = (NpyAuxData *)data; #if NPY_DT_DBG_TRACING printf("Dtype transfer from "); PyObject_Print((PyObject *)src_dtype, stdout, 0); printf(" to "); PyObject_Print((PyObject *)dst_dtype, stdout, 0); printf("\n"); #endif return NPY_SUCCEED; } static int get_unicode_to_datetime_transfer_function(int aligned, npy_intp src_stride, npy_intp dst_stride, PyArray_Descr *src_dtype, PyArray_Descr *dst_dtype, PyArray_StridedUnaryOp **out_stransfer, NpyAuxData **out_transferdata, int *out_needs_api) { NpyAuxData *castdata = NULL, *todata = NULL, *fromdata = NULL; PyArray_StridedUnaryOp *caststransfer, *tobuffer, *frombuffer; PyArray_Descr *str_dtype; /* Get an ASCII string data type, adapted to match the UNICODE one */ str_dtype = PyArray_DescrFromType(NPY_STRING); PyArray_AdaptFlexibleDType(NULL, src_dtype, &str_dtype); if (str_dtype == NULL) { return NPY_FAIL; } /* Get the cast operation from src */ if (PyArray_GetDTypeTransferFunction(aligned, src_stride, str_dtype->elsize, src_dtype, str_dtype, 0, &tobuffer, &todata, out_needs_api) != NPY_SUCCEED) { Py_DECREF(str_dtype); return NPY_FAIL; } /* Get the string to NBO datetime aligned contig function */ if (get_nbo_string_to_datetime_transfer_function(1, str_dtype->elsize, dst_dtype->elsize, str_dtype, dst_dtype, &caststransfer, &castdata) != NPY_SUCCEED) { Py_DECREF(str_dtype); NPY_AUXDATA_FREE(todata); return NPY_FAIL; } /* Get the copy/swap operation to dst */ if (PyArray_GetDTypeCopySwapFn(aligned, dst_dtype->elsize, dst_stride, dst_dtype, &frombuffer, &fromdata) != NPY_SUCCEED) { Py_DECREF(str_dtype); NPY_AUXDATA_FREE(todata); NPY_AUXDATA_FREE(castdata); return NPY_FAIL; } /* Wrap it all up in a new transfer function + data */ if (wrap_aligned_contig_transfer_function( str_dtype->elsize, dst_dtype->elsize, tobuffer, todata, frombuffer, fromdata, caststransfer, castdata, PyDataType_FLAGCHK(dst_dtype, NPY_NEEDS_INIT), out_stransfer, out_transferdata) != NPY_SUCCEED) { Py_DECREF(str_dtype); NPY_AUXDATA_FREE(castdata); NPY_AUXDATA_FREE(todata); NPY_AUXDATA_FREE(fromdata); return NPY_FAIL; } Py_DECREF(str_dtype); return NPY_SUCCEED; } static int get_nbo_cast_transfer_function(int aligned, npy_intp src_stride, npy_intp dst_stride, PyArray_Descr *src_dtype, PyArray_Descr *dst_dtype, int move_references, PyArray_StridedUnaryOp **out_stransfer, NpyAuxData **out_transferdata, int *out_needs_api, int *out_needs_wrap) { _strided_cast_data *data; PyArray_VectorUnaryFunc *castfunc; PyArray_Descr *tmp_dtype; npy_intp shape = 1, src_itemsize = src_dtype->elsize, dst_itemsize = dst_dtype->elsize; if (PyTypeNum_ISNUMBER(src_dtype->type_num) && PyTypeNum_ISNUMBER(dst_dtype->type_num)) { *out_needs_wrap = !PyArray_ISNBO(src_dtype->byteorder) || !PyArray_ISNBO(dst_dtype->byteorder); return get_nbo_cast_numeric_transfer_function(aligned, src_stride, dst_stride, src_dtype->type_num, dst_dtype->type_num, out_stransfer, out_transferdata); } if (src_dtype->type_num == NPY_DATETIME || src_dtype->type_num == NPY_TIMEDELTA || dst_dtype->type_num == NPY_DATETIME || dst_dtype->type_num == NPY_TIMEDELTA) { /* A parameterized type, datetime->datetime sometimes needs casting */ if ((src_dtype->type_num == NPY_DATETIME && dst_dtype->type_num == NPY_DATETIME) || (src_dtype->type_num == NPY_TIMEDELTA && dst_dtype->type_num == NPY_TIMEDELTA)) { *out_needs_wrap = !PyArray_ISNBO(src_dtype->byteorder) || !PyArray_ISNBO(dst_dtype->byteorder); return get_nbo_cast_datetime_transfer_function(aligned, src_stride, dst_stride, src_dtype, dst_dtype, out_stransfer, out_transferdata); } /* * Datetime <-> string conversions can be handled specially. * The functions may raise an error if the strings have no * space, or can't be parsed properly. */ if (src_dtype->type_num == NPY_DATETIME) { switch (dst_dtype->type_num) { case NPY_STRING: *out_needs_api = 1; *out_needs_wrap = !PyArray_ISNBO(src_dtype->byteorder); return get_nbo_datetime_to_string_transfer_function( aligned, src_stride, dst_stride, src_dtype, dst_dtype, out_stransfer, out_transferdata); case NPY_UNICODE: return get_datetime_to_unicode_transfer_function( aligned, src_stride, dst_stride, src_dtype, dst_dtype, out_stransfer, out_transferdata, out_needs_api); } } else if (dst_dtype->type_num == NPY_DATETIME) { switch (src_dtype->type_num) { case NPY_STRING: *out_needs_api = 1; *out_needs_wrap = !PyArray_ISNBO(dst_dtype->byteorder); return get_nbo_string_to_datetime_transfer_function( aligned, src_stride, dst_stride, src_dtype, dst_dtype, out_stransfer, out_transferdata); case NPY_UNICODE: return get_unicode_to_datetime_transfer_function( aligned, src_stride, dst_stride, src_dtype, dst_dtype, out_stransfer, out_transferdata, out_needs_api); } } } *out_needs_wrap = !aligned || !PyArray_ISNBO(src_dtype->byteorder) || !PyArray_ISNBO(dst_dtype->byteorder); /* Check the data types whose casting functions use API calls */ switch (src_dtype->type_num) { case NPY_OBJECT: case NPY_STRING: case NPY_UNICODE: case NPY_VOID: if (out_needs_api) { *out_needs_api = 1; } break; } switch (dst_dtype->type_num) { case NPY_OBJECT: case NPY_STRING: case NPY_UNICODE: case NPY_VOID: if (out_needs_api) { *out_needs_api = 1; } break; } /* Get the cast function */ castfunc = PyArray_GetCastFunc(src_dtype, dst_dtype->type_num); if (!castfunc) { *out_stransfer = NULL; *out_transferdata = NULL; return NPY_FAIL; } /* Allocate the data for the casting */ data = (_strided_cast_data *)PyArray_malloc(sizeof(_strided_cast_data)); if (data == NULL) { PyErr_NoMemory(); *out_stransfer = NULL; *out_transferdata = NULL; return NPY_FAIL; } data->base.free = &_strided_cast_data_free; data->base.clone = &_strided_cast_data_clone; data->castfunc = castfunc; /* * TODO: This is a hack so the cast functions have an array. * The cast functions shouldn't need that. Also, since we * always handle byte order conversions, this array should * have native byte order. */ if (PyArray_ISNBO(src_dtype->byteorder)) { tmp_dtype = src_dtype; Py_INCREF(tmp_dtype); } else { tmp_dtype = PyArray_DescrNewByteorder(src_dtype, NPY_NATIVE); if (tmp_dtype == NULL) { PyArray_free(data); return NPY_FAIL; } } data->aip = (PyArrayObject *)PyArray_NewFromDescr(&PyArray_Type, tmp_dtype, 1, &shape, NULL, NULL, 0, NULL); if (data->aip == NULL) { PyArray_free(data); return NPY_FAIL; } /* * TODO: This is a hack so the cast functions have an array. * The cast functions shouldn't need that. Also, since we * always handle byte order conversions, this array should * have native byte order. */ if (PyArray_ISNBO(dst_dtype->byteorder)) { tmp_dtype = dst_dtype; Py_INCREF(tmp_dtype); } else { tmp_dtype = PyArray_DescrNewByteorder(dst_dtype, NPY_NATIVE); if (tmp_dtype == NULL) { Py_DECREF(data->aip); PyArray_free(data); return NPY_FAIL; } } data->aop = (PyArrayObject *)PyArray_NewFromDescr(&PyArray_Type, tmp_dtype, 1, &shape, NULL, NULL, 0, NULL); if (data->aop == NULL) { Py_DECREF(data->aip); PyArray_free(data); return NPY_FAIL; } /* If it's aligned and all native byte order, we're all done */ if (move_references && src_dtype->type_num == NPY_OBJECT) { *out_stransfer = _aligned_strided_to_strided_cast_decref_src; } else { /* * Use the contig version if the strides are contiguous or * we're telling the caller to wrap the return, because * the wrapping uses a contiguous buffer. */ if ((src_stride == src_itemsize && dst_stride == dst_itemsize) || *out_needs_wrap) { *out_stransfer = _aligned_contig_to_contig_cast; } else { *out_stransfer = _aligned_strided_to_strided_cast; } } *out_transferdata = (NpyAuxData *)data; return NPY_SUCCEED; } static int get_cast_transfer_function(int aligned, npy_intp src_stride, npy_intp dst_stride, PyArray_Descr *src_dtype, PyArray_Descr *dst_dtype, int move_references, PyArray_StridedUnaryOp **out_stransfer, NpyAuxData **out_transferdata, int *out_needs_api) { PyArray_StridedUnaryOp *caststransfer; NpyAuxData *castdata, *todata = NULL, *fromdata = NULL; int needs_wrap = 0; npy_intp src_itemsize = src_dtype->elsize, dst_itemsize = dst_dtype->elsize; if (get_nbo_cast_transfer_function(aligned, src_stride, dst_stride, src_dtype, dst_dtype, move_references, &caststransfer, &castdata, out_needs_api, &needs_wrap) != NPY_SUCCEED) { return NPY_FAIL; } /* * If all native byte order and doesn't need alignment wrapping, * return the function */ if (!needs_wrap) { *out_stransfer = caststransfer; *out_transferdata = castdata; return NPY_SUCCEED; } /* Otherwise, we have to copy and/or swap to aligned temporaries */ else { PyArray_StridedUnaryOp *tobuffer, *frombuffer; /* Get the copy/swap operation from src */ PyArray_GetDTypeCopySwapFn(aligned, src_stride, src_itemsize, src_dtype, &tobuffer, &todata); /* Get the copy/swap operation to dst */ PyArray_GetDTypeCopySwapFn(aligned, dst_itemsize, dst_stride, dst_dtype, &frombuffer, &fromdata); if (frombuffer == NULL || tobuffer == NULL) { NPY_AUXDATA_FREE(castdata); NPY_AUXDATA_FREE(todata); NPY_AUXDATA_FREE(fromdata); return NPY_FAIL; } *out_stransfer = caststransfer; /* Wrap it all up in a new transfer function + data */ if (wrap_aligned_contig_transfer_function( src_itemsize, dst_itemsize, tobuffer, todata, frombuffer, fromdata, caststransfer, castdata, PyDataType_FLAGCHK(dst_dtype, NPY_NEEDS_INIT), out_stransfer, out_transferdata) != NPY_SUCCEED) { NPY_AUXDATA_FREE(castdata); NPY_AUXDATA_FREE(todata); NPY_AUXDATA_FREE(fromdata); return NPY_FAIL; } return NPY_SUCCEED; } } /**************************** COPY 1 TO N CONTIGUOUS ************************/ /* Copies 1 element to N contiguous elements */ typedef struct { NpyAuxData base; PyArray_StridedUnaryOp *stransfer; NpyAuxData *data; npy_intp N, dst_itemsize; /* If this is non-NULL the source type has references needing a decref */ PyArray_StridedUnaryOp *stransfer_finish_src; NpyAuxData *data_finish_src; } _one_to_n_data; /* transfer data free function */ void _one_to_n_data_free(NpyAuxData *data) { _one_to_n_data *d = (_one_to_n_data *)data; NPY_AUXDATA_FREE(d->data); NPY_AUXDATA_FREE(d->data_finish_src); PyArray_free(data); } /* transfer data copy function */ NpyAuxData *_one_to_n_data_clone(NpyAuxData *data) { _one_to_n_data *d = (_one_to_n_data *)data; _one_to_n_data *newdata; /* Allocate the data, and populate it */ newdata = (_one_to_n_data *)PyArray_malloc(sizeof(_one_to_n_data)); if (newdata == NULL) { return NULL; } memcpy(newdata, data, sizeof(_one_to_n_data)); if (d->data != NULL) { newdata->data = NPY_AUXDATA_CLONE(d->data); if (newdata->data == NULL) { PyArray_free(newdata); return NULL; } } if (d->data_finish_src != NULL) { newdata->data_finish_src = NPY_AUXDATA_CLONE(d->data_finish_src); if (newdata->data_finish_src == NULL) { NPY_AUXDATA_FREE(newdata->data); PyArray_free(newdata); return NULL; } } return (NpyAuxData *)newdata; } static void _strided_to_strided_one_to_n(char *dst, npy_intp dst_stride, char *src, npy_intp src_stride, npy_intp N, npy_intp src_itemsize, NpyAuxData *data) { _one_to_n_data *d = (_one_to_n_data *)data; PyArray_StridedUnaryOp *subtransfer = d->stransfer; NpyAuxData *subdata = d->data; npy_intp subN = d->N, dst_itemsize = d->dst_itemsize; while (N > 0) { subtransfer(dst, dst_itemsize, src, 0, subN, src_itemsize, subdata); src += src_stride; dst += dst_stride; --N; } } static void _strided_to_strided_one_to_n_with_finish(char *dst, npy_intp dst_stride, char *src, npy_intp src_stride, npy_intp N, npy_intp src_itemsize, NpyAuxData *data) { _one_to_n_data *d = (_one_to_n_data *)data; PyArray_StridedUnaryOp *subtransfer = d->stransfer, *stransfer_finish_src = d->stransfer_finish_src; NpyAuxData *subdata = d->data, *data_finish_src = d->data_finish_src; npy_intp subN = d->N, dst_itemsize = d->dst_itemsize; while (N > 0) { subtransfer(dst, dst_itemsize, src, 0, subN, src_itemsize, subdata); stransfer_finish_src(NULL, 0, src, 0, 1, src_itemsize, data_finish_src); src += src_stride; dst += dst_stride; --N; } } /* * Wraps a transfer function to produce one that copies one element * of src to N contiguous elements of dst. If stransfer_finish_src is * not NULL, it should be a transfer function which just affects * src, for example to do a final DECREF operation for references. */ static int wrap_transfer_function_one_to_n( PyArray_StridedUnaryOp *stransfer_inner, NpyAuxData *data_inner, PyArray_StridedUnaryOp *stransfer_finish_src, NpyAuxData *data_finish_src, npy_intp dst_itemsize, npy_intp N, PyArray_StridedUnaryOp **out_stransfer, NpyAuxData **out_transferdata) { _one_to_n_data *data; data = PyArray_malloc(sizeof(_one_to_n_data)); if (data == NULL) { PyErr_NoMemory(); return NPY_FAIL; } data->base.free = &_one_to_n_data_free; data->base.clone = &_one_to_n_data_clone; data->stransfer = stransfer_inner; data->data = data_inner; data->stransfer_finish_src = stransfer_finish_src; data->data_finish_src = data_finish_src; data->N = N; data->dst_itemsize = dst_itemsize; if (stransfer_finish_src == NULL) { *out_stransfer = &_strided_to_strided_one_to_n; } else { *out_stransfer = &_strided_to_strided_one_to_n_with_finish; } *out_transferdata = (NpyAuxData *)data; return NPY_SUCCEED; } static int get_one_to_n_transfer_function(int aligned, npy_intp src_stride, npy_intp dst_stride, PyArray_Descr *src_dtype, PyArray_Descr *dst_dtype, int move_references, npy_intp N, PyArray_StridedUnaryOp **out_stransfer, NpyAuxData **out_transferdata, int *out_needs_api) { PyArray_StridedUnaryOp *stransfer, *stransfer_finish_src = NULL; NpyAuxData *data, *data_finish_src = NULL; /* * move_references is set to 0, handled in the wrapping transfer fn, * src_stride is set to zero, because its 1 to N copying, * and dst_stride is set to contiguous, because subarrays are always * contiguous. */ if (PyArray_GetDTypeTransferFunction(aligned, 0, dst_dtype->elsize, src_dtype, dst_dtype, 0, &stransfer, &data, out_needs_api) != NPY_SUCCEED) { return NPY_FAIL; } /* If the src object will need a DECREF, set src_dtype */ if (move_references && PyDataType_REFCHK(src_dtype)) { if (get_decsrcref_transfer_function(aligned, src_stride, src_dtype, &stransfer_finish_src, &data_finish_src, out_needs_api) != NPY_SUCCEED) { NPY_AUXDATA_FREE(data); return NPY_FAIL; } } if (wrap_transfer_function_one_to_n(stransfer, data, stransfer_finish_src, data_finish_src, dst_dtype->elsize, N, out_stransfer, out_transferdata) != NPY_SUCCEED) { NPY_AUXDATA_FREE(data); NPY_AUXDATA_FREE(data_finish_src); return NPY_FAIL; } return NPY_SUCCEED; } /**************************** COPY N TO N CONTIGUOUS ************************/ /* Copies N contiguous elements to N contiguous elements */ typedef struct { NpyAuxData base; PyArray_StridedUnaryOp *stransfer; NpyAuxData *data; npy_intp N, src_itemsize, dst_itemsize; } _n_to_n_data; /* transfer data free function */ void _n_to_n_data_free(NpyAuxData *data) { _n_to_n_data *d = (_n_to_n_data *)data; NPY_AUXDATA_FREE(d->data); PyArray_free(data); } /* transfer data copy function */ NpyAuxData *_n_to_n_data_clone(NpyAuxData *data) { _n_to_n_data *d = (_n_to_n_data *)data; _n_to_n_data *newdata; /* Allocate the data, and populate it */ newdata = (_n_to_n_data *)PyArray_malloc(sizeof(_n_to_n_data)); if (newdata == NULL) { return NULL; } memcpy(newdata, data, sizeof(_n_to_n_data)); if (newdata->data != NULL) { newdata->data = NPY_AUXDATA_CLONE(d->data); if (newdata->data == NULL) { PyArray_free(newdata); return NULL; } } return (NpyAuxData *)newdata; } static void _strided_to_strided_n_to_n(char *dst, npy_intp dst_stride, char *src, npy_intp src_stride, npy_intp N, npy_intp src_itemsize, NpyAuxData *data) { _n_to_n_data *d = (_n_to_n_data *)data; PyArray_StridedUnaryOp *subtransfer = d->stransfer; NpyAuxData *subdata = d->data; npy_intp subN = d->N, src_subitemsize = d->src_itemsize, dst_subitemsize = d->dst_itemsize; while (N > 0) { subtransfer(dst, dst_subitemsize, src, src_subitemsize, subN, src_subitemsize, subdata); src += src_stride; dst += dst_stride; --N; } } static void _contig_to_contig_n_to_n(char *dst, npy_intp NPY_UNUSED(dst_stride), char *src, npy_intp NPY_UNUSED(src_stride), npy_intp N, npy_intp NPY_UNUSED(src_itemsize), NpyAuxData *data) { _n_to_n_data *d = (_n_to_n_data *)data; PyArray_StridedUnaryOp *subtransfer = d->stransfer; NpyAuxData *subdata = d->data; npy_intp subN = d->N, src_subitemsize = d->src_itemsize, dst_subitemsize = d->dst_itemsize; subtransfer(dst, dst_subitemsize, src, src_subitemsize, subN*N, src_subitemsize, subdata); } /* * Wraps a transfer function to produce one that copies N contiguous elements * of src to N contiguous elements of dst. */ static int wrap_transfer_function_n_to_n( PyArray_StridedUnaryOp *stransfer_inner, NpyAuxData *data_inner, npy_intp src_stride, npy_intp dst_stride, npy_intp src_itemsize, npy_intp dst_itemsize, npy_intp N, PyArray_StridedUnaryOp **out_stransfer, NpyAuxData **out_transferdata) { _n_to_n_data *data; data = PyArray_malloc(sizeof(_n_to_n_data)); if (data == NULL) { PyErr_NoMemory(); return NPY_FAIL; } data->base.free = &_n_to_n_data_free; data->base.clone = &_n_to_n_data_clone; data->stransfer = stransfer_inner; data->data = data_inner; data->N = N; data->src_itemsize = src_itemsize; data->dst_itemsize = dst_itemsize; /* * If the N subarray elements exactly fit in the strides, * then can do a faster contiguous transfer. */ if (src_stride == N * src_itemsize && dst_stride == N * dst_itemsize) { *out_stransfer = &_contig_to_contig_n_to_n; } else { *out_stransfer = &_strided_to_strided_n_to_n; } *out_transferdata = (NpyAuxData *)data; return NPY_SUCCEED; } static int get_n_to_n_transfer_function(int aligned, npy_intp src_stride, npy_intp dst_stride, PyArray_Descr *src_dtype, PyArray_Descr *dst_dtype, int move_references, npy_intp N, PyArray_StridedUnaryOp **out_stransfer, NpyAuxData **out_transferdata, int *out_needs_api) { PyArray_StridedUnaryOp *stransfer; NpyAuxData *data; /* * src_stride and dst_stride are set to contiguous, because * subarrays are always contiguous. */ if (PyArray_GetDTypeTransferFunction(aligned, src_dtype->elsize, dst_dtype->elsize, src_dtype, dst_dtype, move_references, &stransfer, &data, out_needs_api) != NPY_SUCCEED) { return NPY_FAIL; } if (wrap_transfer_function_n_to_n(stransfer, data, src_stride, dst_stride, src_dtype->elsize, dst_dtype->elsize, N, out_stransfer, out_transferdata) != NPY_SUCCEED) { NPY_AUXDATA_FREE(data); return NPY_FAIL; } return NPY_SUCCEED; } /********************** COPY WITH SUBARRAY BROADCAST ************************/ typedef struct { npy_intp offset, count; } _subarray_broadcast_offsetrun; /* Copies element with subarray broadcasting */ typedef struct { NpyAuxData base; PyArray_StridedUnaryOp *stransfer; NpyAuxData *data; npy_intp src_N, dst_N, src_itemsize, dst_itemsize; PyArray_StridedUnaryOp *stransfer_decsrcref; NpyAuxData *data_decsrcref; PyArray_StridedUnaryOp *stransfer_decdstref; NpyAuxData *data_decdstref; /* This gets a run-length encoded representation of the transfer */ npy_intp run_count; _subarray_broadcast_offsetrun offsetruns; } _subarray_broadcast_data; /* transfer data free function */ void _subarray_broadcast_data_free(NpyAuxData *data) { _subarray_broadcast_data *d = (_subarray_broadcast_data *)data; NPY_AUXDATA_FREE(d->data); NPY_AUXDATA_FREE(d->data_decsrcref); NPY_AUXDATA_FREE(d->data_decdstref); PyArray_free(data); } /* transfer data copy function */ NpyAuxData *_subarray_broadcast_data_clone( NpyAuxData *data) { _subarray_broadcast_data *d = (_subarray_broadcast_data *)data; _subarray_broadcast_data *newdata; npy_intp run_count = d->run_count, structsize; structsize = sizeof(_subarray_broadcast_data) + run_count*sizeof(_subarray_broadcast_offsetrun); /* Allocate the data and populate it */ newdata = (_subarray_broadcast_data *)PyArray_malloc(structsize); if (newdata == NULL) { return NULL; } memcpy(newdata, data, structsize); if (d->data != NULL) { newdata->data = NPY_AUXDATA_CLONE(d->data); if (newdata->data == NULL) { PyArray_free(newdata); return NULL; } } if (d->data_decsrcref != NULL) { newdata->data_decsrcref = NPY_AUXDATA_CLONE(d->data_decsrcref); if (newdata->data_decsrcref == NULL) { NPY_AUXDATA_FREE(newdata->data); PyArray_free(newdata); return NULL; } } if (d->data_decdstref != NULL) { newdata->data_decdstref = NPY_AUXDATA_CLONE(d->data_decdstref); if (newdata->data_decdstref == NULL) { NPY_AUXDATA_FREE(newdata->data); NPY_AUXDATA_FREE(newdata->data_decsrcref); PyArray_free(newdata); return NULL; } } return (NpyAuxData *)newdata; } static void _strided_to_strided_subarray_broadcast(char *dst, npy_intp dst_stride, char *src, npy_intp src_stride, npy_intp N, npy_intp NPY_UNUSED(src_itemsize), NpyAuxData *data) { _subarray_broadcast_data *d = (_subarray_broadcast_data *)data; PyArray_StridedUnaryOp *subtransfer = d->stransfer; NpyAuxData *subdata = d->data; npy_intp run, run_count = d->run_count, src_subitemsize = d->src_itemsize, dst_subitemsize = d->dst_itemsize; npy_intp loop_index, offset, count; char *dst_ptr; _subarray_broadcast_offsetrun *offsetruns = &d->offsetruns; while (N > 0) { loop_index = 0; for (run = 0; run < run_count; ++run) { offset = offsetruns[run].offset; count = offsetruns[run].count; dst_ptr = dst + loop_index*dst_subitemsize; if (offset != -1) { subtransfer(dst_ptr, dst_subitemsize, src + offset, src_subitemsize, count, src_subitemsize, subdata); } else { memset(dst_ptr, 0, count*dst_subitemsize); } loop_index += count; } src += src_stride; dst += dst_stride; --N; } } static void _strided_to_strided_subarray_broadcast_withrefs(char *dst, npy_intp dst_stride, char *src, npy_intp src_stride, npy_intp N, npy_intp NPY_UNUSED(src_itemsize), NpyAuxData *data) { _subarray_broadcast_data *d = (_subarray_broadcast_data *)data; PyArray_StridedUnaryOp *subtransfer = d->stransfer; NpyAuxData *subdata = d->data; PyArray_StridedUnaryOp *stransfer_decsrcref = d->stransfer_decsrcref; NpyAuxData *data_decsrcref = d->data_decsrcref; PyArray_StridedUnaryOp *stransfer_decdstref = d->stransfer_decdstref; NpyAuxData *data_decdstref = d->data_decdstref; npy_intp run, run_count = d->run_count, src_subitemsize = d->src_itemsize, dst_subitemsize = d->dst_itemsize, src_subN = d->src_N; npy_intp loop_index, offset, count; char *dst_ptr; _subarray_broadcast_offsetrun *offsetruns = &d->offsetruns; while (N > 0) { loop_index = 0; for (run = 0; run < run_count; ++run) { offset = offsetruns[run].offset; count = offsetruns[run].count; dst_ptr = dst + loop_index*dst_subitemsize; if (offset != -1) { subtransfer(dst_ptr, dst_subitemsize, src + offset, src_subitemsize, count, src_subitemsize, subdata); } else { if (stransfer_decdstref != NULL) { stransfer_decdstref(NULL, 0, dst_ptr, dst_subitemsize, count, dst_subitemsize, data_decdstref); } memset(dst_ptr, 0, count*dst_subitemsize); } loop_index += count; } if (stransfer_decsrcref != NULL) { stransfer_decsrcref(NULL, 0, src, src_subitemsize, src_subN, src_subitemsize, data_decsrcref); } src += src_stride; dst += dst_stride; --N; } } static int get_subarray_broadcast_transfer_function(int aligned, npy_intp src_stride, npy_intp dst_stride, PyArray_Descr *src_dtype, PyArray_Descr *dst_dtype, npy_intp src_size, npy_intp dst_size, PyArray_Dims src_shape, PyArray_Dims dst_shape, int move_references, PyArray_StridedUnaryOp **out_stransfer, NpyAuxData **out_transferdata, int *out_needs_api) { _subarray_broadcast_data *data; npy_intp structsize, loop_index, run, run_size, src_index, dst_index, i, ndim; _subarray_broadcast_offsetrun *offsetruns; structsize = sizeof(_subarray_broadcast_data) + dst_size*sizeof(_subarray_broadcast_offsetrun); /* Allocate the data and populate it */ data = (_subarray_broadcast_data *)PyArray_malloc(structsize); if (data == NULL) { PyErr_NoMemory(); return NPY_FAIL; } /* * move_references is set to 0, handled in the wrapping transfer fn, * src_stride and dst_stride are set to contiguous, as N will always * be 1 when it's called. */ if (PyArray_GetDTypeTransferFunction(aligned, src_dtype->elsize, dst_dtype->elsize, src_dtype, dst_dtype, 0, &data->stransfer, &data->data, out_needs_api) != NPY_SUCCEED) { PyArray_free(data); return NPY_FAIL; } data->base.free = &_subarray_broadcast_data_free; data->base.clone = &_subarray_broadcast_data_clone; data->src_N = src_size; data->dst_N = dst_size; data->src_itemsize = src_dtype->elsize; data->dst_itemsize = dst_dtype->elsize; /* If the src object will need a DECREF */ if (move_references && PyDataType_REFCHK(src_dtype)) { if (PyArray_GetDTypeTransferFunction(aligned, src_dtype->elsize, 0, src_dtype, NULL, 1, &data->stransfer_decsrcref, &data->data_decsrcref, out_needs_api) != NPY_SUCCEED) { NPY_AUXDATA_FREE(data->data); PyArray_free(data); return NPY_FAIL; } } else { data->stransfer_decsrcref = NULL; data->data_decsrcref = NULL; } /* If the dst object needs a DECREF to set it to NULL */ if (PyDataType_REFCHK(dst_dtype)) { if (PyArray_GetDTypeTransferFunction(aligned, dst_dtype->elsize, 0, dst_dtype, NULL, 1, &data->stransfer_decdstref, &data->data_decdstref, out_needs_api) != NPY_SUCCEED) { NPY_AUXDATA_FREE(data->data); NPY_AUXDATA_FREE(data->data_decsrcref); PyArray_free(data); return NPY_FAIL; } } else { data->stransfer_decdstref = NULL; data->data_decdstref = NULL; } /* Calculate the broadcasting and set the offsets */ offsetruns = &data->offsetruns; ndim = (src_shape.len > dst_shape.len) ? src_shape.len : dst_shape.len; for (loop_index = 0; loop_index < dst_size; ++loop_index) { npy_intp src_factor = 1; dst_index = loop_index; src_index = 0; for (i = ndim-1; i >= 0; --i) { npy_intp coord = 0, shape; /* Get the dst coord of this index for dimension i */ if (i >= ndim - dst_shape.len) { shape = dst_shape.ptr[i-(ndim-dst_shape.len)]; coord = dst_index % shape; dst_index /= shape; } /* Translate it into a src coord and update src_index */ if (i >= ndim - src_shape.len) { shape = src_shape.ptr[i-(ndim-src_shape.len)]; if (shape == 1) { coord = 0; } else { if (coord < shape) { src_index += src_factor*coord; src_factor *= shape; } else { /* Out of bounds, flag with -1 */ src_index = -1; break; } } } } /* Set the offset */ if (src_index == -1) { offsetruns[loop_index].offset = -1; } else { offsetruns[loop_index].offset = src_index; } } /* Run-length encode the result */ run = 0; run_size = 1; for (loop_index = 1; loop_index < dst_size; ++loop_index) { if (offsetruns[run].offset == -1) { /* Stop the run when there's a valid index again */ if (offsetruns[loop_index].offset != -1) { offsetruns[run].count = run_size; run++; run_size = 1; offsetruns[run].offset = offsetruns[loop_index].offset; } else { run_size++; } } else { /* Stop the run when there's a valid index again */ if (offsetruns[loop_index].offset != offsetruns[loop_index-1].offset + 1) { offsetruns[run].count = run_size; run++; run_size = 1; offsetruns[run].offset = offsetruns[loop_index].offset; } else { run_size++; } } } offsetruns[run].count = run_size; run++; data->run_count = run; /* Multiply all the offsets by the src item size */ while (run--) { if (offsetruns[run].offset != -1) { offsetruns[run].offset *= src_dtype->elsize; } } if (data->stransfer_decsrcref == NULL && data->stransfer_decdstref == NULL) { *out_stransfer = &_strided_to_strided_subarray_broadcast; } else { *out_stransfer = &_strided_to_strided_subarray_broadcast_withrefs; } *out_transferdata = (NpyAuxData *)data; return NPY_SUCCEED; } /* * Handles subarray transfer. To call this, at least one of the dtype's * subarrays must be non-NULL */ static int get_subarray_transfer_function(int aligned, npy_intp src_stride, npy_intp dst_stride, PyArray_Descr *src_dtype, PyArray_Descr *dst_dtype, int move_references, PyArray_StridedUnaryOp **out_stransfer, NpyAuxData **out_transferdata, int *out_needs_api) { PyArray_Dims src_shape = {NULL, -1}, dst_shape = {NULL, -1}; npy_intp src_size = 1, dst_size = 1; /* Get the subarray shapes and sizes */ if (PyDataType_HASSUBARRAY(src_dtype)) { if (!(PyArray_IntpConverter(src_dtype->subarray->shape, &src_shape))) { PyErr_SetString(PyExc_ValueError, "invalid subarray shape"); return NPY_FAIL; } src_size = PyArray_MultiplyList(src_shape.ptr, src_shape.len); src_dtype = src_dtype->subarray->base; } if (PyDataType_HASSUBARRAY(dst_dtype)) { if (!(PyArray_IntpConverter(dst_dtype->subarray->shape, &dst_shape))) { if (src_shape.ptr != NULL) { PyDimMem_FREE(src_shape.ptr); } PyErr_SetString(PyExc_ValueError, "invalid subarray shape"); return NPY_FAIL; } dst_size = PyArray_MultiplyList(dst_shape.ptr, dst_shape.len); dst_dtype = dst_dtype->subarray->base; } /* * Just a straight one-element copy. */ if (dst_size == 1 && src_size == 1) { PyDimMem_FREE(src_shape.ptr); PyDimMem_FREE(dst_shape.ptr); return PyArray_GetDTypeTransferFunction(aligned, src_stride, dst_stride, src_dtype, dst_dtype, move_references, out_stransfer, out_transferdata, out_needs_api); } /* Copy the src value to all the dst values */ else if (src_size == 1) { PyDimMem_FREE(src_shape.ptr); PyDimMem_FREE(dst_shape.ptr); return get_one_to_n_transfer_function(aligned, src_stride, dst_stride, src_dtype, dst_dtype, move_references, dst_size, out_stransfer, out_transferdata, out_needs_api); } /* If the shapes match exactly, do an n to n copy */ else if (src_shape.len == dst_shape.len && PyArray_CompareLists(src_shape.ptr, dst_shape.ptr, src_shape.len)) { PyDimMem_FREE(src_shape.ptr); PyDimMem_FREE(dst_shape.ptr); return get_n_to_n_transfer_function(aligned, src_stride, dst_stride, src_dtype, dst_dtype, move_references, src_size, out_stransfer, out_transferdata, out_needs_api); } /* * Copy the subarray with broadcasting, truncating, and zero-padding * as necessary. */ else { int ret = get_subarray_broadcast_transfer_function(aligned, src_stride, dst_stride, src_dtype, dst_dtype, src_size, dst_size, src_shape, dst_shape, move_references, out_stransfer, out_transferdata, out_needs_api); PyDimMem_FREE(src_shape.ptr); PyDimMem_FREE(dst_shape.ptr); return ret; } } /**************************** COPY FIELDS *******************************/ typedef struct { npy_intp src_offset, dst_offset, src_itemsize; PyArray_StridedUnaryOp *stransfer; NpyAuxData *data; } _single_field_transfer; typedef struct { NpyAuxData base; npy_intp field_count; _single_field_transfer fields; } _field_transfer_data; /* transfer data free function */ void _field_transfer_data_free(NpyAuxData *data) { _field_transfer_data *d = (_field_transfer_data *)data; npy_intp i, field_count; _single_field_transfer *fields; field_count = d->field_count; fields = &d->fields; for (i = 0; i < field_count; ++i) { NPY_AUXDATA_FREE(fields[i].data); } PyArray_free(d); } /* transfer data copy function */ NpyAuxData *_field_transfer_data_clone(NpyAuxData *data) { _field_transfer_data *d = (_field_transfer_data *)data; _field_transfer_data *newdata; npy_intp i, field_count = d->field_count, structsize; _single_field_transfer *fields, *newfields; structsize = sizeof(_field_transfer_data) + field_count * sizeof(_single_field_transfer); /* Allocate the data and populate it */ newdata = (_field_transfer_data *)PyArray_malloc(structsize); if (newdata == NULL) { return NULL; } memcpy(newdata, d, structsize); /* Copy all the fields transfer data */ fields = &d->fields; newfields = &newdata->fields; for (i = 0; i < field_count; ++i) { if (fields[i].data != NULL) { newfields[i].data = NPY_AUXDATA_CLONE(fields[i].data); if (newfields[i].data == NULL) { for (i = i-1; i >= 0; --i) { NPY_AUXDATA_FREE(newfields[i].data); } PyArray_free(newdata); return NULL; } } } return (NpyAuxData *)newdata; } static void _strided_to_strided_field_transfer(char *dst, npy_intp dst_stride, char *src, npy_intp src_stride, npy_intp N, npy_intp NPY_UNUSED(src_itemsize), NpyAuxData *data) { _field_transfer_data *d = (_field_transfer_data *)data; npy_intp i, field_count = d->field_count; _single_field_transfer *field; /* Do the transfer a block at a time */ for (;;) { field = &d->fields; if (N > NPY_LOWLEVEL_BUFFER_BLOCKSIZE) { for (i = 0; i < field_count; ++i, ++field) { field->stransfer(dst + field->dst_offset, dst_stride, src + field->src_offset, src_stride, NPY_LOWLEVEL_BUFFER_BLOCKSIZE, field->src_itemsize, field->data); } N -= NPY_LOWLEVEL_BUFFER_BLOCKSIZE; src += NPY_LOWLEVEL_BUFFER_BLOCKSIZE*src_stride; dst += NPY_LOWLEVEL_BUFFER_BLOCKSIZE*dst_stride; } else { for (i = 0; i < field_count; ++i, ++field) { field->stransfer(dst + field->dst_offset, dst_stride, src + field->src_offset, src_stride, N, field->src_itemsize, field->data); } return; } } } /* * Handles fields transfer. To call this, at least one of the dtypes * must have fields */ static int get_fields_transfer_function(int aligned, npy_intp src_stride, npy_intp dst_stride, PyArray_Descr *src_dtype, PyArray_Descr *dst_dtype, int move_references, PyArray_StridedUnaryOp **out_stransfer, NpyAuxData **out_transferdata, int *out_needs_api) { PyObject *names, *key, *tup, *title; PyArray_Descr *src_fld_dtype, *dst_fld_dtype; npy_int i, names_size, field_count, structsize; int src_offset, dst_offset; _field_transfer_data *data; _single_field_transfer *fields; /* Copy the src value to all the fields of dst */ if (!PyDataType_HASFIELDS(src_dtype)) { names = dst_dtype->names; names_size = PyTuple_GET_SIZE(dst_dtype->names); field_count = names_size; structsize = sizeof(_field_transfer_data) + (field_count + 1) * sizeof(_single_field_transfer); /* Allocate the data and populate it */ data = (_field_transfer_data *)PyArray_malloc(structsize); if (data == NULL) { PyErr_NoMemory(); return NPY_FAIL; } data->base.free = &_field_transfer_data_free; data->base.clone = &_field_transfer_data_clone; fields = &data->fields; for (i = 0; i < names_size; ++i) { key = PyTuple_GET_ITEM(names, i); tup = PyDict_GetItem(dst_dtype->fields, key); if (!PyArg_ParseTuple(tup, "Oi|O", &dst_fld_dtype, &dst_offset, &title)) { PyArray_free(data); return NPY_FAIL; } if (PyArray_GetDTypeTransferFunction(0, src_stride, dst_stride, src_dtype, dst_fld_dtype, 0, &fields[i].stransfer, &fields[i].data, out_needs_api) != NPY_SUCCEED) { for (i = i-1; i >= 0; --i) { NPY_AUXDATA_FREE(fields[i].data); } PyArray_free(data); return NPY_FAIL; } fields[i].src_offset = 0; fields[i].dst_offset = dst_offset; fields[i].src_itemsize = src_dtype->elsize; } /* * If the references should be removed from src, add * another transfer function to do that. */ if (move_references && PyDataType_REFCHK(src_dtype)) { if (get_decsrcref_transfer_function(0, src_stride, src_dtype, &fields[field_count].stransfer, &fields[field_count].data, out_needs_api) != NPY_SUCCEED) { for (i = 0; i < field_count; ++i) { NPY_AUXDATA_FREE(fields[i].data); } PyArray_free(data); return NPY_FAIL; } fields[field_count].src_offset = 0; fields[field_count].dst_offset = 0; fields[field_count].src_itemsize = src_dtype->elsize; field_count++; } data->field_count = field_count; *out_stransfer = &_strided_to_strided_field_transfer; *out_transferdata = (NpyAuxData *)data; return NPY_SUCCEED; } /* Copy the value of the first field to dst */ else if (!PyDataType_HASFIELDS(dst_dtype)) { names = src_dtype->names; names_size = PyTuple_GET_SIZE(src_dtype->names); /* * If DECREF is needed on source fields, may need * to process all the fields */ if (move_references && PyDataType_REFCHK(src_dtype)) { field_count = names_size + 1; } else { field_count = 1; } structsize = sizeof(_field_transfer_data) + field_count * sizeof(_single_field_transfer); /* Allocate the data and populate it */ data = (_field_transfer_data *)PyArray_malloc(structsize); if (data == NULL) { PyErr_NoMemory(); return NPY_FAIL; } data->base.free = &_field_transfer_data_free; data->base.clone = &_field_transfer_data_clone; fields = &data->fields; key = PyTuple_GET_ITEM(names, 0); tup = PyDict_GetItem(src_dtype->fields, key); if (!PyArg_ParseTuple(tup, "Oi|O", &src_fld_dtype, &src_offset, &title)) { PyArray_free(data); return NPY_FAIL; } field_count = 0; /* * Special case bool type, the existence of fields implies True * * TODO: Perhaps a better behavior would be to combine all the * input fields with an OR? The same would apply to subarrays. */ if (dst_dtype->type_num == NPY_BOOL) { if (get_bool_setdstone_transfer_function(dst_stride, &fields[field_count].stransfer, &fields[field_count].data, out_needs_api) != NPY_SUCCEED) { PyArray_free(data); return NPY_FAIL; } fields[field_count].src_offset = 0; fields[field_count].dst_offset = 0; fields[field_count].src_itemsize = 0; field_count++; /* If the src field has references, may need to clear them */ if (move_references && PyDataType_REFCHK(src_fld_dtype)) { if (get_decsrcref_transfer_function(0, src_stride, src_fld_dtype, &fields[field_count].stransfer, &fields[field_count].data, out_needs_api) != NPY_SUCCEED) { NPY_AUXDATA_FREE(fields[0].data); PyArray_free(data); return NPY_FAIL; } fields[field_count].src_offset = src_offset; fields[field_count].dst_offset = 0; fields[field_count].src_itemsize = src_fld_dtype->elsize; field_count++; } } /* Transfer the first field to the output */ else { if (PyArray_GetDTypeTransferFunction(0, src_stride, dst_stride, src_fld_dtype, dst_dtype, move_references, &fields[field_count].stransfer, &fields[field_count].data, out_needs_api) != NPY_SUCCEED) { PyArray_free(data); return NPY_FAIL; } fields[field_count].src_offset = src_offset; fields[field_count].dst_offset = 0; fields[field_count].src_itemsize = src_fld_dtype->elsize; field_count++; } /* * If the references should be removed from src, add * more transfer functions to decrement the references * for all the other fields. */ if (move_references && PyDataType_REFCHK(src_dtype)) { for (i = 1; i < names_size; ++i) { key = PyTuple_GET_ITEM(names, i); tup = PyDict_GetItem(src_dtype->fields, key); if (!PyArg_ParseTuple(tup, "Oi|O", &src_fld_dtype, &src_offset, &title)) { return NPY_FAIL; } if (PyDataType_REFCHK(src_fld_dtype)) { if (get_decsrcref_transfer_function(0, src_stride, src_fld_dtype, &fields[field_count].stransfer, &fields[field_count].data, out_needs_api) != NPY_SUCCEED) { for (i = field_count-1; i >= 0; --i) { NPY_AUXDATA_FREE(fields[i].data); } PyArray_free(data); return NPY_FAIL; } fields[field_count].src_offset = src_offset; fields[field_count].dst_offset = 0; fields[field_count].src_itemsize = src_fld_dtype->elsize; field_count++; } } } data->field_count = field_count; *out_stransfer = &_strided_to_strided_field_transfer; *out_transferdata = (NpyAuxData *)data; return NPY_SUCCEED; } /* Match up the fields to copy */ else { /* Keeps track of the names we already used */ PyObject *used_names_dict = NULL; names = dst_dtype->names; names_size = PyTuple_GET_SIZE(dst_dtype->names); /* * If DECREF is needed on source fields, will need * to also go through its fields. */ if (move_references && PyDataType_REFCHK(src_dtype)) { field_count = names_size + PyTuple_GET_SIZE(src_dtype->names); used_names_dict = PyDict_New(); if (used_names_dict == NULL) { return NPY_FAIL; } } else { field_count = names_size; } structsize = sizeof(_field_transfer_data) + field_count * sizeof(_single_field_transfer); /* Allocate the data and populate it */ data = (_field_transfer_data *)PyArray_malloc(structsize); if (data == NULL) { PyErr_NoMemory(); Py_XDECREF(used_names_dict); return NPY_FAIL; } data->base.free = &_field_transfer_data_free; data->base.clone = &_field_transfer_data_clone; fields = &data->fields; for (i = 0; i < names_size; ++i) { key = PyTuple_GET_ITEM(names, i); tup = PyDict_GetItem(dst_dtype->fields, key); if (!PyArg_ParseTuple(tup, "Oi|O", &dst_fld_dtype, &dst_offset, &title)) { for (i = i-1; i >= 0; --i) { NPY_AUXDATA_FREE(fields[i].data); } PyArray_free(data); Py_XDECREF(used_names_dict); return NPY_FAIL; } tup = PyDict_GetItem(src_dtype->fields, key); if (tup != NULL) { if (!PyArg_ParseTuple(tup, "Oi|O", &src_fld_dtype, &src_offset, &title)) { for (i = i-1; i >= 0; --i) { NPY_AUXDATA_FREE(fields[i].data); } PyArray_free(data); Py_XDECREF(used_names_dict); return NPY_FAIL; } if (PyArray_GetDTypeTransferFunction(0, src_stride, dst_stride, src_fld_dtype, dst_fld_dtype, move_references, &fields[i].stransfer, &fields[i].data, out_needs_api) != NPY_SUCCEED) { for (i = i-1; i >= 0; --i) { NPY_AUXDATA_FREE(fields[i].data); } PyArray_free(data); Py_XDECREF(used_names_dict); return NPY_FAIL; } fields[i].src_offset = src_offset; fields[i].dst_offset = dst_offset; fields[i].src_itemsize = src_fld_dtype->elsize; if (used_names_dict != NULL) { PyDict_SetItem(used_names_dict, key, Py_True); } } else { if (get_setdstzero_transfer_function(0, dst_stride, dst_fld_dtype, &fields[i].stransfer, &fields[i].data, out_needs_api) != NPY_SUCCEED) { for (i = i-1; i >= 0; --i) { NPY_AUXDATA_FREE(fields[i].data); } PyArray_free(data); Py_XDECREF(used_names_dict); return NPY_FAIL; } fields[i].src_offset = 0; fields[i].dst_offset = dst_offset; fields[i].src_itemsize = 0; } } if (move_references && PyDataType_REFCHK(src_dtype)) { /* Use field_count to track additional functions added */ field_count = names_size; names = src_dtype->names; names_size = PyTuple_GET_SIZE(src_dtype->names); for (i = 0; i < names_size; ++i) { key = PyTuple_GET_ITEM(names, i); if (PyDict_GetItem(used_names_dict, key) == NULL) { tup = PyDict_GetItem(src_dtype->fields, key); if (!PyArg_ParseTuple(tup, "Oi|O", &src_fld_dtype, &src_offset, &title)) { for (i = field_count-1; i >= 0; --i) { NPY_AUXDATA_FREE(fields[i].data); } PyArray_free(data); Py_XDECREF(used_names_dict); return NPY_FAIL; } if (PyDataType_REFCHK(src_fld_dtype)) { if (get_decsrcref_transfer_function(0, src_stride, src_fld_dtype, &fields[field_count].stransfer, &fields[field_count].data, out_needs_api) != NPY_SUCCEED) { for (i = field_count-1; i >= 0; --i) { NPY_AUXDATA_FREE(fields[i].data); } PyArray_free(data); return NPY_FAIL; } fields[field_count].src_offset = src_offset; fields[field_count].dst_offset = 0; fields[field_count].src_itemsize = src_fld_dtype->elsize; field_count++; } } } } Py_XDECREF(used_names_dict); data->field_count = field_count; *out_stransfer = &_strided_to_strided_field_transfer; *out_transferdata = (NpyAuxData *)data; return NPY_SUCCEED; } } static int get_decsrcref_fields_transfer_function(int aligned, npy_intp src_stride, PyArray_Descr *src_dtype, PyArray_StridedUnaryOp **out_stransfer, NpyAuxData **out_transferdata, int *out_needs_api) { PyObject *names, *key, *tup, *title; PyArray_Descr *src_fld_dtype; npy_int i, names_size, field_count, structsize; int src_offset; _field_transfer_data *data; _single_field_transfer *fields; names = src_dtype->names; names_size = PyTuple_GET_SIZE(src_dtype->names); field_count = names_size; structsize = sizeof(_field_transfer_data) + field_count * sizeof(_single_field_transfer); /* Allocate the data and populate it */ data = (_field_transfer_data *)PyArray_malloc(structsize); if (data == NULL) { PyErr_NoMemory(); return NPY_FAIL; } data->base.free = &_field_transfer_data_free; data->base.clone = &_field_transfer_data_clone; fields = &data->fields; field_count = 0; for (i = 0; i < names_size; ++i) { key = PyTuple_GET_ITEM(names, i); tup = PyDict_GetItem(src_dtype->fields, key); if (!PyArg_ParseTuple(tup, "Oi|O", &src_fld_dtype, &src_offset, &title)) { PyArray_free(data); return NPY_FAIL; } if (PyDataType_REFCHK(src_fld_dtype)) { if (out_needs_api) { *out_needs_api = 1; } if (get_decsrcref_transfer_function(0, src_stride, src_fld_dtype, &fields[field_count].stransfer, &fields[field_count].data, out_needs_api) != NPY_SUCCEED) { for (i = field_count-1; i >= 0; --i) { NPY_AUXDATA_FREE(fields[i].data); } PyArray_free(data); return NPY_FAIL; } fields[field_count].src_offset = src_offset; fields[field_count].dst_offset = 0; fields[field_count].src_itemsize = src_dtype->elsize; field_count++; } } data->field_count = field_count; *out_stransfer = &_strided_to_strided_field_transfer; *out_transferdata = (NpyAuxData *)data; return NPY_SUCCEED; } static int get_setdestzero_fields_transfer_function(int aligned, npy_intp dst_stride, PyArray_Descr *dst_dtype, PyArray_StridedUnaryOp **out_stransfer, NpyAuxData **out_transferdata, int *out_needs_api) { PyObject *names, *key, *tup, *title; PyArray_Descr *dst_fld_dtype; npy_int i, names_size, field_count, structsize; int dst_offset; _field_transfer_data *data; _single_field_transfer *fields; names = dst_dtype->names; names_size = PyTuple_GET_SIZE(dst_dtype->names); field_count = names_size; structsize = sizeof(_field_transfer_data) + field_count * sizeof(_single_field_transfer); /* Allocate the data and populate it */ data = (_field_transfer_data *)PyArray_malloc(structsize); if (data == NULL) { PyErr_NoMemory(); return NPY_FAIL; } data->base.free = &_field_transfer_data_free; data->base.clone = &_field_transfer_data_clone; fields = &data->fields; for (i = 0; i < names_size; ++i) { key = PyTuple_GET_ITEM(names, i); tup = PyDict_GetItem(dst_dtype->fields, key); if (!PyArg_ParseTuple(tup, "Oi|O", &dst_fld_dtype, &dst_offset, &title)) { PyArray_free(data); return NPY_FAIL; } if (get_setdstzero_transfer_function(0, dst_stride, dst_fld_dtype, &fields[i].stransfer, &fields[i].data, out_needs_api) != NPY_SUCCEED) { for (i = i-1; i >= 0; --i) { NPY_AUXDATA_FREE(fields[i].data); } PyArray_free(data); return NPY_FAIL; } fields[i].src_offset = 0; fields[i].dst_offset = dst_offset; fields[i].src_itemsize = 0; } data->field_count = field_count; *out_stransfer = &_strided_to_strided_field_transfer; *out_transferdata = (NpyAuxData *)data; return NPY_SUCCEED; } /************************* MASKED TRANSFER WRAPPER *************************/ typedef struct { NpyAuxData base; /* The transfer function being wrapped */ PyArray_StridedUnaryOp *stransfer; NpyAuxData *transferdata; /* The src decref function if necessary */ PyArray_StridedUnaryOp *decsrcref_stransfer; NpyAuxData *decsrcref_transferdata; } _masked_wrapper_transfer_data; /* transfer data free function */ void _masked_wrapper_transfer_data_free(NpyAuxData *data) { _masked_wrapper_transfer_data *d = (_masked_wrapper_transfer_data *)data; NPY_AUXDATA_FREE(d->transferdata); NPY_AUXDATA_FREE(d->decsrcref_transferdata); PyArray_free(data); } /* transfer data copy function */ NpyAuxData *_masked_wrapper_transfer_data_clone(NpyAuxData *data) { _masked_wrapper_transfer_data *d = (_masked_wrapper_transfer_data *)data; _masked_wrapper_transfer_data *newdata; /* Allocate the data and populate it */ newdata = (_masked_wrapper_transfer_data *)PyArray_malloc( sizeof(_masked_wrapper_transfer_data)); if (newdata == NULL) { return NULL; } memcpy(newdata, d, sizeof(_masked_wrapper_transfer_data)); /* Clone all the owned auxdata as well */ if (newdata->transferdata != NULL) { newdata->transferdata = NPY_AUXDATA_CLONE(newdata->transferdata); if (newdata->transferdata == NULL) { PyArray_free(newdata); return NULL; } } if (newdata->decsrcref_transferdata != NULL) { newdata->decsrcref_transferdata = NPY_AUXDATA_CLONE(newdata->decsrcref_transferdata); if (newdata->decsrcref_transferdata == NULL) { NPY_AUXDATA_FREE(newdata->transferdata); PyArray_free(newdata); return NULL; } } return (NpyAuxData *)newdata; } 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, npy_intp N, npy_intp src_itemsize, NpyAuxData *transferdata) { _masked_wrapper_transfer_data *d = (_masked_wrapper_transfer_data *)transferdata; npy_intp subloopsize; PyArray_StridedUnaryOp *unmasked_stransfer, *decsrcref_stransfer; NpyAuxData *unmasked_transferdata, *decsrcref_transferdata; unmasked_stransfer = d->stransfer; unmasked_transferdata = d->transferdata; decsrcref_stransfer = d->decsrcref_stransfer; decsrcref_transferdata = d->decsrcref_transferdata; while (N > 0) { /* Skip masked values, still calling decsrcref for move_references */ subloopsize = 0; while (subloopsize < N && !*mask) { ++subloopsize; mask += mask_stride; } 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 */ subloopsize = 0; while (subloopsize < N && *mask) { ++subloopsize; mask += mask_stride; } unmasked_stransfer(dst, dst_stride, src, src_stride, subloopsize, src_itemsize, unmasked_transferdata); dst += subloopsize * dst_stride; src += subloopsize * src_stride; N -= subloopsize; } } 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, npy_intp N, npy_intp src_itemsize, NpyAuxData *transferdata) { _masked_wrapper_transfer_data *d = (_masked_wrapper_transfer_data *)transferdata; npy_intp subloopsize; PyArray_StridedUnaryOp *unmasked_stransfer; NpyAuxData *unmasked_transferdata; unmasked_stransfer = d->stransfer; unmasked_transferdata = d->transferdata; while (N > 0) { /* Skip masked values */ subloopsize = 0; while (subloopsize < N && !*mask) { ++subloopsize; mask += mask_stride; } dst += subloopsize * dst_stride; src += subloopsize * src_stride; N -= subloopsize; /* Process unmasked values */ subloopsize = 0; while (subloopsize < N && *mask) { ++subloopsize; mask += mask_stride; } unmasked_stransfer(dst, dst_stride, src, src_stride, subloopsize, src_itemsize, unmasked_transferdata); dst += subloopsize * dst_stride; src += subloopsize * src_stride; N -= subloopsize; } } /************************* DEST BOOL SETONE *******************************/ static void _null_to_strided_set_bool_one(char *dst, npy_intp dst_stride, char *NPY_UNUSED(src), npy_intp NPY_UNUSED(src_stride), npy_intp N, npy_intp NPY_UNUSED(src_itemsize), NpyAuxData *NPY_UNUSED(data)) { /* bool type is one byte, so can just use the char */ while (N > 0) { *dst = 1; dst += dst_stride; --N; } } static void _null_to_contig_set_bool_one(char *dst, npy_intp NPY_UNUSED(dst_stride), char *NPY_UNUSED(src), npy_intp NPY_UNUSED(src_stride), npy_intp N, npy_intp NPY_UNUSED(src_itemsize), NpyAuxData *NPY_UNUSED(data)) { /* bool type is one byte, so can just use the char */ memset(dst, 1, N); } /* Only for the bool type, sets the destination to 1 */ NPY_NO_EXPORT int get_bool_setdstone_transfer_function(npy_intp dst_stride, PyArray_StridedUnaryOp **out_stransfer, NpyAuxData **out_transferdata, int *NPY_UNUSED(out_needs_api)) { if (dst_stride == 1) { *out_stransfer = &_null_to_contig_set_bool_one; } else { *out_stransfer = &_null_to_strided_set_bool_one; } *out_transferdata = NULL; return NPY_SUCCEED; } /*************************** DEST SETZERO *******************************/ /* Sets dest to zero */ typedef struct { NpyAuxData base; npy_intp dst_itemsize; } _dst_memset_zero_data; /* zero-padded data copy function */ NpyAuxData *_dst_memset_zero_data_clone(NpyAuxData *data) { _dst_memset_zero_data *newdata = (_dst_memset_zero_data *)PyArray_malloc( sizeof(_dst_memset_zero_data)); if (newdata == NULL) { return NULL; } memcpy(newdata, data, sizeof(_dst_memset_zero_data)); return (NpyAuxData *)newdata; } static void _null_to_strided_memset_zero(char *dst, npy_intp dst_stride, char *NPY_UNUSED(src), npy_intp NPY_UNUSED(src_stride), npy_intp N, npy_intp NPY_UNUSED(src_itemsize), NpyAuxData *data) { _dst_memset_zero_data *d = (_dst_memset_zero_data *)data; npy_intp dst_itemsize = d->dst_itemsize; while (N > 0) { memset(dst, 0, dst_itemsize); dst += dst_stride; --N; } } static void _null_to_contig_memset_zero(char *dst, npy_intp dst_stride, char *NPY_UNUSED(src), npy_intp NPY_UNUSED(src_stride), npy_intp N, npy_intp NPY_UNUSED(src_itemsize), NpyAuxData *data) { _dst_memset_zero_data *d = (_dst_memset_zero_data *)data; npy_intp dst_itemsize = d->dst_itemsize; memset(dst, 0, N*dst_itemsize); } static void _null_to_strided_reference_setzero(char *dst, npy_intp dst_stride, char *NPY_UNUSED(src), npy_intp NPY_UNUSED(src_stride), npy_intp N, npy_intp NPY_UNUSED(src_itemsize), NpyAuxData *NPY_UNUSED(data)) { PyObject *dst_ref = NULL; while (N > 0) { NPY_COPY_PYOBJECT_PTR(&dst_ref, dst); /* Release the reference in dst */ NPY_DT_DBG_REFTRACE("dec dest ref (to set zero)", dst_ref); Py_XDECREF(dst_ref); /* Set it to zero */ dst_ref = NULL; NPY_COPY_PYOBJECT_PTR(dst, &dst_ref); dst += dst_stride; --N; } } NPY_NO_EXPORT int get_setdstzero_transfer_function(int aligned, npy_intp dst_stride, PyArray_Descr *dst_dtype, PyArray_StridedUnaryOp **out_stransfer, NpyAuxData **out_transferdata, int *out_needs_api) { _dst_memset_zero_data *data; /* If there are no references, just set the whole thing to zero */ if (!PyDataType_REFCHK(dst_dtype)) { data = (_dst_memset_zero_data *) PyArray_malloc(sizeof(_dst_memset_zero_data)); if (data == NULL) { PyErr_NoMemory(); return NPY_FAIL; } data->base.free = (NpyAuxData_FreeFunc *)(&PyArray_free); data->base.clone = &_dst_memset_zero_data_clone; data->dst_itemsize = dst_dtype->elsize; if (dst_stride == data->dst_itemsize) { *out_stransfer = &_null_to_contig_memset_zero; } else { *out_stransfer = &_null_to_strided_memset_zero; } *out_transferdata = (NpyAuxData *)data; } /* If it's exactly one reference, use the decref function */ else if (dst_dtype->type_num == NPY_OBJECT) { if (out_needs_api) { *out_needs_api = 1; } *out_stransfer = &_null_to_strided_reference_setzero; *out_transferdata = NULL; } /* If there are subarrays, need to wrap it */ else if (PyDataType_HASSUBARRAY(dst_dtype)) { PyArray_Dims dst_shape = {NULL, -1}; npy_intp dst_size = 1; PyArray_StridedUnaryOp *contig_stransfer; NpyAuxData *contig_data; if (out_needs_api) { *out_needs_api = 1; } if (!(PyArray_IntpConverter(dst_dtype->subarray->shape, &dst_shape))) { PyErr_SetString(PyExc_ValueError, "invalid subarray shape"); return NPY_FAIL; } dst_size = PyArray_MultiplyList(dst_shape.ptr, dst_shape.len); PyDimMem_FREE(dst_shape.ptr); /* Get a function for contiguous dst of the subarray type */ if (get_setdstzero_transfer_function(aligned, dst_dtype->subarray->base->elsize, dst_dtype->subarray->base, &contig_stransfer, &contig_data, out_needs_api) != NPY_SUCCEED) { return NPY_FAIL; } if (wrap_transfer_function_n_to_n(contig_stransfer, contig_data, 0, dst_stride, 0, dst_dtype->subarray->base->elsize, dst_size, out_stransfer, out_transferdata) != NPY_SUCCEED) { NPY_AUXDATA_FREE(contig_data); return NPY_FAIL; } } /* If there are fields, need to do each field */ else if (PyDataType_HASFIELDS(dst_dtype)) { if (out_needs_api) { *out_needs_api = 1; } return get_setdestzero_fields_transfer_function(aligned, dst_stride, dst_dtype, out_stransfer, out_transferdata, out_needs_api); } return NPY_SUCCEED; } static void _dec_src_ref_nop(char *NPY_UNUSED(dst), npy_intp NPY_UNUSED(dst_stride), char *NPY_UNUSED(src), npy_intp NPY_UNUSED(src_stride), npy_intp NPY_UNUSED(N), npy_intp NPY_UNUSED(src_itemsize), NpyAuxData *NPY_UNUSED(data)) { /* NOP */ } static void _strided_to_null_dec_src_ref_reference(char *NPY_UNUSED(dst), npy_intp NPY_UNUSED(dst_stride), char *src, npy_intp src_stride, npy_intp N, npy_intp NPY_UNUSED(src_itemsize), NpyAuxData *NPY_UNUSED(data)) { PyObject *src_ref = NULL; while (N > 0) { NPY_COPY_PYOBJECT_PTR(&src_ref, src); /* Release the reference in src */ NPY_DT_DBG_REFTRACE("dec src ref (null dst)", src_ref); Py_XDECREF(src_ref); src += src_stride; --N; } } NPY_NO_EXPORT int get_decsrcref_transfer_function(int aligned, npy_intp src_stride, PyArray_Descr *src_dtype, PyArray_StridedUnaryOp **out_stransfer, NpyAuxData **out_transferdata, int *out_needs_api) { /* If there are no references, it's a nop */ if (!PyDataType_REFCHK(src_dtype)) { *out_stransfer = &_dec_src_ref_nop; *out_transferdata = NULL; return NPY_SUCCEED; } /* If it's a single reference, it's one decref */ else if (src_dtype->type_num == NPY_OBJECT) { if (out_needs_api) { *out_needs_api = 1; } *out_stransfer = &_strided_to_null_dec_src_ref_reference; *out_transferdata = NULL; return NPY_SUCCEED; } /* If there are subarrays, need to wrap it */ else if (PyDataType_HASSUBARRAY(src_dtype)) { PyArray_Dims src_shape = {NULL, -1}; npy_intp src_size = 1; PyArray_StridedUnaryOp *stransfer; NpyAuxData *data; if (out_needs_api) { *out_needs_api = 1; } if (!(PyArray_IntpConverter(src_dtype->subarray->shape, &src_shape))) { PyErr_SetString(PyExc_ValueError, "invalid subarray shape"); return NPY_FAIL; } src_size = PyArray_MultiplyList(src_shape.ptr, src_shape.len); PyDimMem_FREE(src_shape.ptr); /* Get a function for contiguous src of the subarray type */ if (get_decsrcref_transfer_function(aligned, src_dtype->subarray->base->elsize, src_dtype->subarray->base, &stransfer, &data, out_needs_api) != NPY_SUCCEED) { return NPY_FAIL; } if (wrap_transfer_function_n_to_n(stransfer, data, src_stride, 0, src_dtype->subarray->base->elsize, 0, src_size, out_stransfer, out_transferdata) != NPY_SUCCEED) { NPY_AUXDATA_FREE(data); return NPY_FAIL; } return NPY_SUCCEED; } /* If there are fields, need to do each field */ else { if (out_needs_api) { *out_needs_api = 1; } return get_decsrcref_fields_transfer_function(aligned, src_stride, src_dtype, out_stransfer, out_transferdata, out_needs_api); } } /********************* DTYPE COPY SWAP FUNCTION ***********************/ NPY_NO_EXPORT int PyArray_GetDTypeCopySwapFn(int aligned, npy_intp src_stride, npy_intp dst_stride, PyArray_Descr *dtype, PyArray_StridedUnaryOp **outstransfer, NpyAuxData **outtransferdata) { npy_intp itemsize = dtype->elsize; /* If it's a custom data type, wrap its copy swap function */ if (dtype->type_num >= NPY_NTYPES) { *outstransfer = NULL; wrap_copy_swap_function(aligned, src_stride, dst_stride, dtype, !PyArray_ISNBO(dtype->byteorder), outstransfer, outtransferdata); } /* A straight copy */ else if (itemsize == 1 || PyArray_ISNBO(dtype->byteorder)) { *outstransfer = PyArray_GetStridedCopyFn(aligned, src_stride, dst_stride, itemsize); *outtransferdata = NULL; } /* If it's not complex, one swap */ else if(dtype->kind != 'c') { *outstransfer = PyArray_GetStridedCopySwapFn(aligned, src_stride, dst_stride, itemsize); *outtransferdata = NULL; } /* If complex, a paired swap */ else { *outstransfer = PyArray_GetStridedCopySwapPairFn(aligned, src_stride, dst_stride, itemsize); *outtransferdata = NULL; } return (*outstransfer == NULL) ? NPY_FAIL : NPY_SUCCEED; } /********************* MAIN DTYPE TRANSFER FUNCTION ***********************/ NPY_NO_EXPORT int PyArray_GetDTypeTransferFunction(int aligned, npy_intp src_stride, npy_intp dst_stride, PyArray_Descr *src_dtype, PyArray_Descr *dst_dtype, int move_references, PyArray_StridedUnaryOp **out_stransfer, NpyAuxData **out_transferdata, int *out_needs_api) { npy_intp src_itemsize, dst_itemsize; int src_type_num, dst_type_num; #if NPY_DT_DBG_TRACING printf("Calculating dtype transfer from "); PyObject_Print((PyObject *)src_dtype, stdout, 0); printf(" to "); PyObject_Print((PyObject *)dst_dtype, stdout, 0); printf("\n"); #endif /* * If one of the dtypes is NULL, we give back either a src decref * function or a dst setzero function */ if (dst_dtype == NULL) { if (move_references) { return get_decsrcref_transfer_function(aligned, src_dtype->elsize, src_dtype, out_stransfer, out_transferdata, out_needs_api); } else { *out_stransfer = &_dec_src_ref_nop; *out_transferdata = NULL; return NPY_SUCCEED; } } else if (src_dtype == NULL) { return get_setdstzero_transfer_function(aligned, dst_dtype->elsize, dst_dtype, out_stransfer, out_transferdata, out_needs_api); } src_itemsize = src_dtype->elsize; dst_itemsize = dst_dtype->elsize; src_type_num = src_dtype->type_num; dst_type_num = dst_dtype->type_num; /* Common special case - number -> number NBO cast */ if (PyTypeNum_ISNUMBER(src_type_num) && PyTypeNum_ISNUMBER(dst_type_num) && PyArray_ISNBO(src_dtype->byteorder) && PyArray_ISNBO(dst_dtype->byteorder)) { if (PyArray_EquivTypenums(src_type_num, dst_type_num)) { *out_stransfer = PyArray_GetStridedCopyFn(aligned, src_stride, dst_stride, src_itemsize); *out_transferdata = NULL; return (*out_stransfer == NULL) ? NPY_FAIL : NPY_SUCCEED; } else { return get_nbo_cast_numeric_transfer_function (aligned, src_stride, dst_stride, src_type_num, dst_type_num, out_stransfer, out_transferdata); } } /* * If there are no references and the data types are equivalent, * return a simple copy */ if (!PyDataType_REFCHK(src_dtype) && !PyDataType_REFCHK(dst_dtype) && PyArray_EquivTypes(src_dtype, dst_dtype)) { /* * We can't pass through the aligned flag because it's not * appropriate. Consider a size-8 string, it will say it's * aligned because strings only need alignment 1, but the * copy function wants to know if it's alignment 8. * * TODO: Change align from a flag to a "best power of 2 alignment" * which holds the strongest alignment value for all * the data which will be used. */ *out_stransfer = PyArray_GetStridedCopyFn(0, src_stride, dst_stride, src_dtype->elsize); *out_transferdata = NULL; return NPY_SUCCEED; } /* First look at the possibilities of just a copy or swap */ if (src_itemsize == dst_itemsize && src_dtype->kind == dst_dtype->kind && !PyDataType_HASFIELDS(src_dtype) && !PyDataType_HASFIELDS(dst_dtype) && !PyDataType_HASSUBARRAY(src_dtype) && !PyDataType_HASSUBARRAY(dst_dtype) && src_type_num != NPY_DATETIME && src_type_num != NPY_TIMEDELTA) { /* A custom data type requires that we use its copy/swap */ if (src_type_num >= NPY_NTYPES || dst_type_num >= NPY_NTYPES) { /* * If the sizes and kinds are identical, but they're different * custom types, then get a cast function */ if (src_type_num != dst_type_num) { return get_cast_transfer_function(aligned, src_stride, dst_stride, src_dtype, dst_dtype, move_references, out_stransfer, out_transferdata, out_needs_api); } else { return wrap_copy_swap_function(aligned, src_stride, dst_stride, src_dtype, PyArray_ISNBO(src_dtype->byteorder) != PyArray_ISNBO(dst_dtype->byteorder), out_stransfer, out_transferdata); } } /* The special types, which have no byte-order */ switch (src_type_num) { case NPY_VOID: case NPY_STRING: case NPY_UNICODE: *out_stransfer = PyArray_GetStridedCopyFn(0, src_stride, dst_stride, src_itemsize); *out_transferdata = NULL; return NPY_SUCCEED; case NPY_OBJECT: if (out_needs_api) { *out_needs_api = 1; } if (move_references) { *out_stransfer = &_strided_to_strided_move_references; *out_transferdata = NULL; } else { *out_stransfer = &_strided_to_strided_copy_references; *out_transferdata = NULL; } return NPY_SUCCEED; } /* This is a straight copy */ if (src_itemsize == 1 || PyArray_ISNBO(src_dtype->byteorder) == PyArray_ISNBO(dst_dtype->byteorder)) { *out_stransfer = PyArray_GetStridedCopyFn(aligned, src_stride, dst_stride, src_itemsize); *out_transferdata = NULL; return (*out_stransfer == NULL) ? NPY_FAIL : NPY_SUCCEED; } /* This is a straight copy + byte swap */ else if (!PyTypeNum_ISCOMPLEX(src_type_num)) { *out_stransfer = PyArray_GetStridedCopySwapFn(aligned, src_stride, dst_stride, src_itemsize); *out_transferdata = NULL; return (*out_stransfer == NULL) ? NPY_FAIL : NPY_SUCCEED; } /* This is a straight copy + element pair byte swap */ else { *out_stransfer = PyArray_GetStridedCopySwapPairFn(aligned, src_stride, dst_stride, src_itemsize); *out_transferdata = NULL; return (*out_stransfer == NULL) ? NPY_FAIL : NPY_SUCCEED; } } /* Handle subarrays */ if (PyDataType_HASSUBARRAY(src_dtype) || PyDataType_HASSUBARRAY(dst_dtype)) { return get_subarray_transfer_function(aligned, src_stride, dst_stride, src_dtype, dst_dtype, move_references, out_stransfer, out_transferdata, out_needs_api); } /* Handle fields */ if ((PyDataType_HASFIELDS(src_dtype) || PyDataType_HASFIELDS(dst_dtype)) && src_type_num != NPY_OBJECT && dst_type_num != NPY_OBJECT) { return get_fields_transfer_function(aligned, src_stride, dst_stride, src_dtype, dst_dtype, move_references, out_stransfer, out_transferdata, out_needs_api); } /* Check for different-sized strings, unicodes, or voids */ if (src_type_num == dst_type_num) { switch (src_type_num) { case NPY_STRING: case NPY_UNICODE: case NPY_VOID: return PyArray_GetStridedZeroPadCopyFn(0, src_stride, dst_stride, src_dtype->elsize, dst_dtype->elsize, out_stransfer, out_transferdata); } } /* Otherwise a cast is necessary */ return get_cast_transfer_function(aligned, src_stride, dst_stride, src_dtype, dst_dtype, move_references, out_stransfer, out_transferdata, out_needs_api); } NPY_NO_EXPORT int PyArray_GetMaskedDTypeTransferFunction(int aligned, npy_intp src_stride, npy_intp dst_stride, npy_intp mask_stride, PyArray_Descr *src_dtype, PyArray_Descr *dst_dtype, PyArray_Descr *mask_dtype, int move_references, PyArray_MaskedStridedUnaryOp **out_stransfer, NpyAuxData **out_transferdata, int *out_needs_api) { PyArray_StridedUnaryOp *stransfer = NULL; NpyAuxData *transferdata = NULL; _masked_wrapper_transfer_data *data; /* TODO: Add struct-based mask_dtype support later */ if (mask_dtype->type_num != NPY_BOOL && mask_dtype->type_num != NPY_UINT8) { PyErr_SetString(PyExc_TypeError, "Only bool and uint8 masks are supported at the moment, " "structs of bool/uint8 is planned for the future"); return NPY_FAIL; } /* TODO: Special case some important cases so they're fast */ /* Fall back to wrapping a non-masked transfer function */ if (PyArray_GetDTypeTransferFunction(aligned, src_stride, dst_stride, src_dtype, dst_dtype, move_references, &stransfer, &transferdata, out_needs_api) != NPY_SUCCEED) { return NPY_FAIL; } /* Create the wrapper function's auxdata */ data = (_masked_wrapper_transfer_data *)PyArray_malloc( sizeof(_masked_wrapper_transfer_data)); if (data == NULL) { PyErr_NoMemory(); NPY_AUXDATA_FREE(transferdata); return NPY_FAIL; } /* Fill in the auxdata object */ memset(data, 0, sizeof(_masked_wrapper_transfer_data)); data->base.free = &_masked_wrapper_transfer_data_free; data->base.clone = &_masked_wrapper_transfer_data_clone; data->stransfer = stransfer; data->transferdata = transferdata; /* If the src object will need a DECREF, get a function to handle that */ if (move_references && PyDataType_REFCHK(src_dtype)) { if (get_decsrcref_transfer_function(aligned, src_stride, src_dtype, &data->decsrcref_stransfer, &data->decsrcref_transferdata, out_needs_api) != NPY_SUCCEED) { NPY_AUXDATA_FREE((NpyAuxData *)data); return NPY_FAIL; } *out_stransfer = &_strided_masked_wrapper_decsrcref_transfer_function; } else { *out_stransfer = &_strided_masked_wrapper_transfer_function; } *out_transferdata = (NpyAuxData *)data; return NPY_SUCCEED; } NPY_NO_EXPORT int PyArray_CastRawArrays(npy_intp count, char *src, char *dst, npy_intp src_stride, npy_intp dst_stride, PyArray_Descr *src_dtype, PyArray_Descr *dst_dtype, int move_references) { PyArray_StridedUnaryOp *stransfer = NULL; NpyAuxData *transferdata = NULL; int aligned = 1, needs_api = 0; /* Make sure the copy is reasonable */ if (dst_stride == 0 && count > 1) { PyErr_SetString(PyExc_ValueError, "NumPy CastRawArrays cannot do a reduction"); return NPY_FAIL; } else if (count == 0) { return NPY_SUCCEED; } /* Check data alignment */ aligned = (((npy_intp)src | src_stride) & (src_dtype->alignment - 1)) == 0 && (((npy_intp)dst | dst_stride) & (dst_dtype->alignment - 1)) == 0; /* Get the function to do the casting */ if (PyArray_GetDTypeTransferFunction(aligned, src_stride, dst_stride, src_dtype, dst_dtype, move_references, &stransfer, &transferdata, &needs_api) != NPY_SUCCEED) { return NPY_FAIL; } /* Cast */ stransfer(dst, dst_stride, src, src_stride, count, src_dtype->elsize, transferdata); /* Cleanup */ NPY_AUXDATA_FREE(transferdata); /* If needs_api was set to 1, it may have raised a Python exception */ return (needs_api && PyErr_Occurred()) ? NPY_FAIL : NPY_SUCCEED; } /* * Prepares shape and strides for a simple raw array iteration. * This sorts the strides into FORTRAN order, reverses any negative * strides, then coalesces axes where possible. The results are * filled in the output parameters. * * This is intended for simple, lightweight iteration over arrays * where no buffering of any kind is needed, and the array may * not be stored as a PyArrayObject. * * The arrays shape, out_shape, strides, and out_strides must all * point to different data. * * Returns 0 on success, -1 on failure. */ NPY_NO_EXPORT int PyArray_PrepareOneRawArrayIter(int ndim, npy_intp *shape, char *data, npy_intp *strides, int *out_ndim, npy_intp *out_shape, char **out_data, npy_intp *out_strides) { npy_stride_sort_item strideperm[NPY_MAXDIMS]; int i, j; /* Special case 0 and 1 dimensions */ if (ndim == 0) { *out_ndim = 1; *out_data = data; out_shape[0] = 1; out_strides[0] = 0; return 0; } else if (ndim == 1) { npy_intp stride_entry = strides[0], shape_entry = shape[0]; *out_ndim = 1; out_shape[0] = shape[0]; /* Always make a positive stride */ if (stride_entry >= 0) { *out_data = data; out_strides[0] = stride_entry; } else { *out_data = data + stride_entry * (shape_entry - 1); out_strides[0] = -stride_entry; } return 0; } /* Sort the axes based on the destination strides */ PyArray_CreateSortedStridePerm(ndim, strides, strideperm); for (i = 0; i < ndim; ++i) { int iperm = strideperm[ndim - i - 1].perm; out_shape[i] = shape[iperm]; out_strides[i] = strides[iperm]; } /* Reverse any negative strides */ for (i = 0; i < ndim; ++i) { npy_intp stride_entry = out_strides[i], shape_entry = out_shape[i]; if (stride_entry < 0) { data += stride_entry * (shape_entry - 1); out_strides[i] = -stride_entry; } /* Detect 0-size arrays here */ if (shape_entry == 0) { *out_ndim = 1; *out_data = data; out_shape[0] = 0; out_strides[0] = 0; return 0; } } /* Coalesce any dimensions where possible */ i = 0; for (j = 1; j < ndim; ++j) { if (out_shape[i] == 1) { /* Drop axis i */ out_shape[i] = out_shape[j]; out_strides[i] = out_strides[j]; } else if (out_shape[j] == 1) { /* Drop axis j */ } else if (out_strides[i] * out_shape[i] == out_strides[j]) { /* Coalesce axes i and j */ out_shape[i] *= out_shape[j]; } else { /* Can't coalesce, go to next i */ ++i; out_shape[i] = out_shape[j]; out_strides[i] = out_strides[j]; } } ndim = i+1; #if 0 /* DEBUG */ { printf("raw iter ndim %d\n", ndim); printf("shape: "); for (i = 0; i < ndim; ++i) { printf("%d ", (int)out_shape[i]); } printf("\n"); printf("strides: "); for (i = 0; i < ndim; ++i) { printf("%d ", (int)out_strides[i]); } printf("\n"); } #endif *out_data = data; *out_ndim = ndim; return 0; } /* * The same as PyArray_PrepareOneRawArrayIter, but for two * operands instead of one. Any broadcasting of the two operands * should have already been done before calling this function, * as the ndim and shape is only specified once for both operands. * * Only the strides of the first operand are used to reorder * the dimensions, no attempt to consider all the strides together * is made, as is done in the NpyIter object. * * You can use this together with NPY_RAW_ITER_START and * NPY_RAW_ITER_TWO_NEXT to handle the looping boilerplate of everything * but the innermost loop (which is for idim == 0). * * Returns 0 on success, -1 on failure. */ NPY_NO_EXPORT int PyArray_PrepareTwoRawArrayIter(int ndim, npy_intp *shape, char *dataA, npy_intp *stridesA, char *dataB, npy_intp *stridesB, int *out_ndim, npy_intp *out_shape, char **out_dataA, npy_intp *out_stridesA, char **out_dataB, npy_intp *out_stridesB) { npy_stride_sort_item strideperm[NPY_MAXDIMS]; int i, j; /* Special case 0 and 1 dimensions */ if (ndim == 0) { *out_ndim = 1; *out_dataA = dataA; *out_dataB = dataB; out_shape[0] = 1; out_stridesA[0] = 0; out_stridesB[0] = 0; return 0; } else if (ndim == 1) { npy_intp stride_entryA = stridesA[0], stride_entryB = stridesB[0]; npy_intp shape_entry = shape[0]; *out_ndim = 1; out_shape[0] = shape[0]; /* Always make a positive stride for the first operand */ if (stride_entryA >= 0) { *out_dataA = dataA; *out_dataB = dataB; out_stridesA[0] = stride_entryA; out_stridesB[0] = stride_entryB; } else { *out_dataA = dataA + stride_entryA * (shape_entry - 1); *out_dataB = dataB + stride_entryB * (shape_entry - 1); out_stridesA[0] = -stride_entryA; out_stridesB[0] = -stride_entryB; } return 0; } /* Sort the axes based on the destination strides */ PyArray_CreateSortedStridePerm(ndim, stridesA, strideperm); for (i = 0; i < ndim; ++i) { int iperm = strideperm[ndim - i - 1].perm; out_shape[i] = shape[iperm]; out_stridesA[i] = stridesA[iperm]; out_stridesB[i] = stridesB[iperm]; } /* Reverse any negative strides of operand A */ for (i = 0; i < ndim; ++i) { npy_intp stride_entryA = out_stridesA[i]; npy_intp stride_entryB = out_stridesB[i]; npy_intp shape_entry = out_shape[i]; if (stride_entryA < 0) { dataA += stride_entryA * (shape_entry - 1); dataB += stride_entryB * (shape_entry - 1); out_stridesA[i] = -stride_entryA; out_stridesB[i] = -stride_entryB; } /* Detect 0-size arrays here */ if (shape_entry == 0) { *out_ndim = 1; *out_dataA = dataA; *out_dataB = dataB; out_shape[0] = 0; out_stridesA[0] = 0; out_stridesB[0] = 0; return 0; } } /* Coalesce any dimensions where possible */ i = 0; for (j = 1; j < ndim; ++j) { if (out_shape[i] == 1) { /* Drop axis i */ out_shape[i] = out_shape[j]; out_stridesA[i] = out_stridesA[j]; out_stridesB[i] = out_stridesB[j]; } else if (out_shape[j] == 1) { /* Drop axis j */ } else if (out_stridesA[i] * out_shape[i] == out_stridesA[j] && out_stridesB[i] * out_shape[i] == out_stridesB[j]) { /* Coalesce axes i and j */ out_shape[i] *= out_shape[j]; } else { /* Can't coalesce, go to next i */ ++i; out_shape[i] = out_shape[j]; out_stridesA[i] = out_stridesA[j]; out_stridesB[i] = out_stridesB[j]; } } ndim = i+1; *out_dataA = dataA; *out_dataB = dataB; *out_ndim = ndim; return 0; } /* * The same as PyArray_PrepareOneRawArrayIter, but for three * operands instead of one. Any broadcasting of the three operands * should have already been done before calling this function, * as the ndim and shape is only specified once for all operands. * * Only the strides of the first operand are used to reorder * the dimensions, no attempt to consider all the strides together * is made, as is done in the NpyIter object. * * You can use this together with NPY_RAW_ITER_START and * NPY_RAW_ITER_THREE_NEXT to handle the looping boilerplate of everything * but the innermost loop (which is for idim == 0). * * Returns 0 on success, -1 on failure. */ NPY_NO_EXPORT int PyArray_PrepareThreeRawArrayIter(int ndim, npy_intp *shape, char *dataA, npy_intp *stridesA, char *dataB, npy_intp *stridesB, char *dataC, npy_intp *stridesC, int *out_ndim, npy_intp *out_shape, char **out_dataA, npy_intp *out_stridesA, char **out_dataB, npy_intp *out_stridesB, char **out_dataC, npy_intp *out_stridesC) { npy_stride_sort_item strideperm[NPY_MAXDIMS]; int i, j; /* Special case 0 and 1 dimensions */ if (ndim == 0) { *out_ndim = 1; *out_dataA = dataA; *out_dataB = dataB; *out_dataC = dataC; out_shape[0] = 1; out_stridesA[0] = 0; out_stridesB[0] = 0; out_stridesC[0] = 0; return 0; } else if (ndim == 1) { npy_intp stride_entryA = stridesA[0]; npy_intp stride_entryB = stridesB[0]; npy_intp stride_entryC = stridesC[0]; npy_intp shape_entry = shape[0]; *out_ndim = 1; out_shape[0] = shape[0]; /* Always make a positive stride for the first operand */ if (stride_entryA >= 0) { *out_dataA = dataA; *out_dataB = dataB; *out_dataC = dataC; out_stridesA[0] = stride_entryA; out_stridesB[0] = stride_entryB; out_stridesC[0] = stride_entryC; } else { *out_dataA = dataA + stride_entryA * (shape_entry - 1); *out_dataB = dataB + stride_entryB * (shape_entry - 1); *out_dataC = dataC + stride_entryC * (shape_entry - 1); out_stridesA[0] = -stride_entryA; out_stridesB[0] = -stride_entryB; out_stridesC[0] = -stride_entryC; } return 0; } /* Sort the axes based on the destination strides */ PyArray_CreateSortedStridePerm(ndim, stridesA, strideperm); for (i = 0; i < ndim; ++i) { int iperm = strideperm[ndim - i - 1].perm; out_shape[i] = shape[iperm]; out_stridesA[i] = stridesA[iperm]; out_stridesB[i] = stridesB[iperm]; out_stridesC[i] = stridesC[iperm]; } /* Reverse any negative strides of operand A */ for (i = 0; i < ndim; ++i) { npy_intp stride_entryA = out_stridesA[i]; npy_intp stride_entryB = out_stridesB[i]; npy_intp stride_entryC = out_stridesC[i]; npy_intp shape_entry = out_shape[i]; if (stride_entryA < 0) { dataA += stride_entryA * (shape_entry - 1); dataB += stride_entryB * (shape_entry - 1); dataC += stride_entryC * (shape_entry - 1); out_stridesA[i] = -stride_entryA; out_stridesB[i] = -stride_entryB; out_stridesC[i] = -stride_entryC; } /* Detect 0-size arrays here */ if (shape_entry == 0) { *out_ndim = 1; *out_dataA = dataA; *out_dataB = dataB; *out_dataC = dataC; out_shape[0] = 0; out_stridesA[0] = 0; out_stridesB[0] = 0; out_stridesC[0] = 0; return 0; } } /* Coalesce any dimensions where possible */ i = 0; for (j = 1; j < ndim; ++j) { if (out_shape[i] == 1) { /* Drop axis i */ out_shape[i] = out_shape[j]; out_stridesA[i] = out_stridesA[j]; out_stridesB[i] = out_stridesB[j]; out_stridesC[i] = out_stridesC[j]; } else if (out_shape[j] == 1) { /* Drop axis j */ } else if (out_stridesA[i] * out_shape[i] == out_stridesA[j] && out_stridesB[i] * out_shape[i] == out_stridesB[j] && out_stridesC[i] * out_shape[i] == out_stridesC[j]) { /* Coalesce axes i and j */ out_shape[i] *= out_shape[j]; } else { /* Can't coalesce, go to next i */ ++i; out_shape[i] = out_shape[j]; out_stridesA[i] = out_stridesA[j]; out_stridesB[i] = out_stridesB[j]; out_stridesC[i] = out_stridesC[j]; } } ndim = i+1; *out_dataA = dataA; *out_dataB = dataB; *out_dataC = dataC; *out_ndim = ndim; return 0; } numpy-1.8.2/numpy/core/src/multiarray/descriptor.c0000664000175100017510000031120212370216243023425 0ustar vagrantvagrant00000000000000/* Array Descr Object */ #define PY_SSIZE_T_CLEAN #include #include "structmember.h" #define NPY_NO_DEPRECATED_API NPY_API_VERSION #define _MULTIARRAYMODULE #include "numpy/arrayobject.h" #include "numpy/arrayscalars.h" #include "npy_config.h" #include "npy_pycompat.h" #include "_datetime.h" #include "common.h" #include "descriptor.h" /* * offset: A starting offset. * alignment: A power-of-two alignment. * * This macro returns the smallest value >= 'offset' * that is divisible by 'alignment'. Because 'alignment' * is a power of two and integers are twos-complement, * it is possible to use some simple bit-fiddling to do this. */ #define NPY_NEXT_ALIGNED_OFFSET(offset, alignment) \ (((offset) + (alignment) - 1) & (-(alignment))) static PyObject *typeDict = NULL; /* Must be explicitly loaded */ static PyArray_Descr * _use_inherit(PyArray_Descr *type, PyObject *newobj, int *errflag); /* * Creates a dtype object from ctypes inputs. * * Returns a new reference to a dtype object, or NULL * if this is not possible. When it returns NULL, it does * not set a Python exception. */ static PyArray_Descr * _arraydescr_fromctypes(PyObject *obj) { PyObject *dtypedescr; PyArray_Descr *newdescr; int ret; /* Understand basic ctypes */ dtypedescr = PyObject_GetAttrString(obj, "_type_"); PyErr_Clear(); if (dtypedescr) { ret = PyArray_DescrConverter(dtypedescr, &newdescr); Py_DECREF(dtypedescr); if (ret == NPY_SUCCEED) { PyObject *length; /* Check for ctypes arrays */ length = PyObject_GetAttrString(obj, "_length_"); PyErr_Clear(); if (length) { /* derived type */ PyObject *newtup; PyArray_Descr *derived; newtup = Py_BuildValue("NO", newdescr, length); ret = PyArray_DescrConverter(newtup, &derived); Py_DECREF(newtup); if (ret == NPY_SUCCEED) { return derived; } PyErr_Clear(); return NULL; } return newdescr; } PyErr_Clear(); return NULL; } /* Understand ctypes structures -- bit-fields are not supported automatically aligns */ dtypedescr = PyObject_GetAttrString(obj, "_fields_"); PyErr_Clear(); if (dtypedescr) { ret = PyArray_DescrAlignConverter(dtypedescr, &newdescr); Py_DECREF(dtypedescr); if (ret == NPY_SUCCEED) { return newdescr; } PyErr_Clear(); } return NULL; } /* * This function creates a dtype object when: * - The object has a "dtype" attribute, and it can be converted * to a dtype object. * - The object is a ctypes type object, including array * and structure types. * * Returns a new reference to a dtype object, or NULL * if this is not possible. When it returns NULL, it does * not set a Python exception. */ NPY_NO_EXPORT PyArray_Descr * _arraydescr_fromobj(PyObject *obj) { PyObject *dtypedescr; PyArray_Descr *newdescr = NULL; int ret; /* For arbitrary objects that have a "dtype" attribute */ dtypedescr = PyObject_GetAttrString(obj, "dtype"); PyErr_Clear(); if (dtypedescr != NULL) { ret = PyArray_DescrConverter(dtypedescr, &newdescr); Py_DECREF(dtypedescr); if (ret == NPY_SUCCEED) { return newdescr; } PyErr_Clear(); } return _arraydescr_fromctypes(obj); } /* * Sets the global typeDict object, which is a dictionary mapping * dtype names to numpy scalar types. */ NPY_NO_EXPORT PyObject * array_set_typeDict(PyObject *NPY_UNUSED(ignored), PyObject *args) { PyObject *dict; if (!PyArg_ParseTuple(args, "O", &dict)) { return NULL; } /* Decrement old reference (if any)*/ Py_XDECREF(typeDict); typeDict = dict; /* Create an internal reference to it */ Py_INCREF(dict); Py_INCREF(Py_None); return Py_None; } #define _chk_byteorder(arg) (arg == '>' || arg == '<' || \ arg == '|' || arg == '=') static int _check_for_commastring(char *type, Py_ssize_t len) { Py_ssize_t i; int sqbracket; /* Check for ints at start of string */ if ((type[0] >= '0' && type[0] <= '9') || ((len > 1) && _chk_byteorder(type[0]) && (type[1] >= '0' && type[1] <= '9'))) { return 1; } /* Check for empty tuple */ if (((len > 1) && (type[0] == '(' && type[1] == ')')) || ((len > 3) && _chk_byteorder(type[0]) && (type[1] == '(' && type[2] == ')'))) { return 1; } /* * Check for presence of commas outside square [] brackets. This * allows commas inside of [], for parameterized dtypes to use. */ sqbracket = 0; for (i = 1; i < len; i++) { switch (type[i]) { case ',': if (sqbracket == 0) { return 1; } break; case '[': ++sqbracket; break; case ']': --sqbracket; break; } } return 0; } #undef _chk_byteorder static int is_datetime_typestr(char *type, Py_ssize_t len) { if (len < 2) { return 0; } if (type[1] == '8' && (type[0] == 'M' || type[0] == 'm')) { return 1; } if (len < 10) { return 0; } if (strncmp(type, "datetime64", 10) == 0) { return 1; } if (len < 11) { return 0; } if (strncmp(type, "timedelta64", 11) == 0) { return 1; } return 0; } static PyArray_Descr * _convert_from_tuple(PyObject *obj) { PyArray_Descr *type, *res; PyObject *val; int errflag; if (PyTuple_GET_SIZE(obj) != 2) { return NULL; } if (!PyArray_DescrConverter(PyTuple_GET_ITEM(obj,0), &type)) { return NULL; } val = PyTuple_GET_ITEM(obj,1); /* try to interpret next item as a type */ res = _use_inherit(type, val, &errflag); if (res || errflag) { Py_DECREF(type); if (res) { return res; } else { return NULL; } } PyErr_Clear(); /* * We get here if res was NULL but errflag wasn't set * --- i.e. the conversion to a data-descr failed in _use_inherit */ if (type->elsize == 0) { /* interpret next item as a typesize */ int itemsize = PyArray_PyIntAsInt(PyTuple_GET_ITEM(obj,1)); if (error_converting(itemsize)) { PyErr_SetString(PyExc_ValueError, "invalid itemsize in generic type tuple"); goto fail; } PyArray_DESCR_REPLACE(type); if (type->type_num == NPY_UNICODE) { type->elsize = itemsize << 2; } else { type->elsize = itemsize; } } else if (PyDict_Check(val)) { /* Assume it's a metadata dictionary */ if (PyDict_Merge(type->metadata, val, 0) == -1) { Py_DECREF(type); return NULL; } } else { /* * interpret next item as shape (if it's a tuple) * and reset the type to NPY_VOID with * a new fields attribute. */ PyArray_Dims shape = {NULL, -1}; PyArray_Descr *newdescr; if (!(PyArray_IntpConverter(val, &shape)) || (shape.len > NPY_MAXDIMS)) { PyDimMem_FREE(shape.ptr); PyErr_SetString(PyExc_ValueError, "invalid shape in fixed-type tuple."); goto fail; } /* * If (type, 1) was given, it is equivalent to type... * or (type, ()) was given it is equivalent to type... */ if ((shape.len == 1 && shape.ptr[0] == 1 && PyNumber_Check(val)) || (shape.len == 0 && PyTuple_Check(val))) { PyDimMem_FREE(shape.ptr); return type; } newdescr = PyArray_DescrNewFromType(NPY_VOID); if (newdescr == NULL) { PyDimMem_FREE(shape.ptr); goto fail; } newdescr->elsize = type->elsize; newdescr->elsize *= PyArray_MultiplyList(shape.ptr, shape.len); PyDimMem_FREE(shape.ptr); newdescr->subarray = PyArray_malloc(sizeof(PyArray_ArrayDescr)); if (newdescr->subarray == NULL) { Py_DECREF(newdescr); PyErr_NoMemory(); goto fail; } newdescr->flags = type->flags; 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); goto fail; } } type = newdescr; } return type; fail: Py_XDECREF(type); return NULL; } /* * obj is a list. Each item is a tuple with * * (field-name, data-type (either a list or a string), and an optional * shape parameter). * * field-name can be a string or a 2-tuple * data-type can now be a list, string, or 2-tuple * (string, metadata dictionary) */ static PyArray_Descr * _convert_from_array_descr(PyObject *obj, int align) { int n, i, totalsize; int ret; PyObject *fields, *item, *newobj; PyObject *name, *tup, *title; PyObject *nameslist; PyArray_Descr *new; PyArray_Descr *conv; /* Types with fields need the Python C API for field access */ char dtypeflags = NPY_NEEDS_PYAPI; int maxalign = 0; n = PyList_GET_SIZE(obj); nameslist = PyTuple_New(n); if (!nameslist) { return NULL; } totalsize = 0; fields = PyDict_New(); for (i = 0; i < n; i++) { item = PyList_GET_ITEM(obj, i); if (!PyTuple_Check(item) || (PyTuple_GET_SIZE(item) < 2)) { goto fail; } name = PyTuple_GET_ITEM(item, 0); if (PyUString_Check(name)) { title = NULL; } else if (PyTuple_Check(name)) { if (PyTuple_GET_SIZE(name) != 2) { goto fail; } title = PyTuple_GET_ITEM(name, 0); name = PyTuple_GET_ITEM(name, 1); if (!PyUString_Check(name)) { goto fail; } } else { goto fail; } /* Insert name into nameslist */ Py_INCREF(name); if (PyUString_GET_SIZE(name) == 0) { Py_DECREF(name); if (title == NULL) { name = PyUString_FromFormat("f%d", i); } #if defined(NPY_PY3K) /* On Py3, allow only non-empty Unicode strings as field names */ else if (PyUString_Check(title) && PyUString_GET_SIZE(title) > 0) { name = title; Py_INCREF(name); } else { goto fail; } #else else { name = title; Py_INCREF(name); } #endif } PyTuple_SET_ITEM(nameslist, i, name); /* Process rest */ if (PyTuple_GET_SIZE(item) == 2) { if (align) { ret = PyArray_DescrAlignConverter(PyTuple_GET_ITEM(item, 1), &conv); } else { ret = PyArray_DescrConverter(PyTuple_GET_ITEM(item, 1), &conv); } if (ret == NPY_FAIL) { PyObject_Print(PyTuple_GET_ITEM(item, 1), stderr, 0); } } else if (PyTuple_GET_SIZE(item) == 3) { newobj = PyTuple_GetSlice(item, 1, 3); if (align) { ret = PyArray_DescrAlignConverter(newobj, &conv); } else { ret = PyArray_DescrConverter(newobj, &conv); } Py_DECREF(newobj); } else { goto fail; } if (ret == NPY_FAIL) { goto fail; } if ((PyDict_GetItem(fields, name) != NULL) || (title #if defined(NPY_PY3K) && PyUString_Check(title) #else && (PyUString_Check(title) || PyUnicode_Check(title)) #endif && (PyDict_GetItem(fields, title) != NULL))) { PyErr_SetString(PyExc_ValueError, "two fields with the same name"); goto fail; } dtypeflags |= (conv->flags & NPY_FROM_FIELDS); tup = PyTuple_New((title == NULL ? 2 : 3)); PyTuple_SET_ITEM(tup, 0, (PyObject *)conv); if (align) { int _align; _align = conv->alignment; if (_align > 1) { totalsize = NPY_NEXT_ALIGNED_OFFSET(totalsize, _align); } maxalign = PyArray_MAX(maxalign, _align); } PyTuple_SET_ITEM(tup, 1, PyInt_FromLong((long) totalsize)); PyDict_SetItem(fields, name, tup); /* * Title can be "meta-data". Only insert it * into the fields dictionary if it is a string * and if it is not the same as the name. */ if (title != NULL) { Py_INCREF(title); PyTuple_SET_ITEM(tup, 2, title); #if defined(NPY_PY3K) if (PyUString_Check(title)) { #else if (PyUString_Check(title) || PyUnicode_Check(title)) { #endif if (PyDict_GetItem(fields, title) != NULL) { PyErr_SetString(PyExc_ValueError, "title already used as a name or title."); Py_DECREF(tup); goto fail; } PyDict_SetItem(fields, title, tup); } } totalsize += conv->elsize; Py_DECREF(tup); } if (maxalign > 1) { totalsize = NPY_NEXT_ALIGNED_OFFSET(totalsize, maxalign); } new = PyArray_DescrNewFromType(NPY_VOID); if (new == NULL) { Py_XDECREF(fields); Py_XDECREF(nameslist); return NULL; } new->fields = fields; new->names = nameslist; new->elsize = totalsize; new->flags = dtypeflags; /* Structured arrays get a sticky aligned bit */ if (align) { new->flags |= NPY_ALIGNED_STRUCT; new->alignment = maxalign; } return new; fail: Py_DECREF(fields); Py_DECREF(nameslist); return NULL; } /* * a list specifying a data-type can just be * a list of formats. The names for the fields * will default to f0, f1, f2, and so forth. */ static PyArray_Descr * _convert_from_list(PyObject *obj, int align) { int n, i; int totalsize; PyObject *fields; PyArray_Descr *conv = NULL; PyArray_Descr *new; PyObject *key, *tup; PyObject *nameslist = NULL; int ret; int maxalign = 0; /* Types with fields need the Python C API for field access */ char dtypeflags = NPY_NEEDS_PYAPI; n = PyList_GET_SIZE(obj); /* * Ignore any empty string at end which _internal._commastring * can produce */ key = PyList_GET_ITEM(obj, n-1); if (PyBytes_Check(key) && PyBytes_GET_SIZE(key) == 0) { n = n - 1; } /* End ignore code.*/ totalsize = 0; if (n == 0) { return NULL; } nameslist = PyTuple_New(n); if (!nameslist) { return NULL; } fields = PyDict_New(); for (i = 0; i < n; i++) { tup = PyTuple_New(2); key = PyUString_FromFormat("f%d", i); if (align) { ret = PyArray_DescrAlignConverter(PyList_GET_ITEM(obj, i), &conv); } else { ret = PyArray_DescrConverter(PyList_GET_ITEM(obj, i), &conv); } if (ret == NPY_FAIL) { Py_DECREF(tup); Py_DECREF(key); goto fail; } dtypeflags |= (conv->flags & NPY_FROM_FIELDS); PyTuple_SET_ITEM(tup, 0, (PyObject *)conv); if (align) { int _align; _align = conv->alignment; if (_align > 1) { totalsize = NPY_NEXT_ALIGNED_OFFSET(totalsize, _align); } maxalign = PyArray_MAX(maxalign, _align); } PyTuple_SET_ITEM(tup, 1, PyInt_FromLong((long) totalsize)); PyDict_SetItem(fields, key, tup); Py_DECREF(tup); PyTuple_SET_ITEM(nameslist, i, key); totalsize += conv->elsize; } new = PyArray_DescrNewFromType(NPY_VOID); new->fields = fields; new->names = nameslist; new->flags = dtypeflags; if (maxalign > 1) { totalsize = NPY_NEXT_ALIGNED_OFFSET(totalsize, maxalign); } /* Structured arrays get a sticky aligned bit */ if (align) { new->flags |= NPY_ALIGNED_STRUCT; new->alignment = maxalign; } new->elsize = totalsize; return new; fail: Py_DECREF(nameslist); Py_DECREF(fields); return NULL; } /* * comma-separated string * this is the format developed by the numarray records module and implemented * by the format parser in that module this is an alternative implementation * found in the _internal.py file patterned after that one -- the approach is * to try to convert to a list (with tuples if any repeat information is * present) and then call the _convert_from_list) * * TODO: Calling Python from C like this in critical-path code is not * a good idea. This should all be converted to C code. */ static PyArray_Descr * _convert_from_commastring(PyObject *obj, int align) { PyObject *listobj; PyArray_Descr *res; PyObject *_numpy_internal; if (!PyBytes_Check(obj)) { return NULL; } _numpy_internal = PyImport_ImportModule("numpy.core._internal"); if (_numpy_internal == NULL) { return NULL; } listobj = PyObject_CallMethod(_numpy_internal, "_commastring", "O", obj); Py_DECREF(_numpy_internal); if (listobj == NULL) { return NULL; } if (!PyList_Check(listobj) || PyList_GET_SIZE(listobj) < 1) { PyErr_SetString(PyExc_RuntimeError, "_commastring is not returning a list with len >= 1"); return NULL; } if (PyList_GET_SIZE(listobj) == 1) { int retcode; retcode = PyArray_DescrConverter(PyList_GET_ITEM(listobj, 0), &res); if (retcode == NPY_FAIL) { res = NULL; } } else { res = _convert_from_list(listobj, align); } Py_DECREF(listobj); if (!res && !PyErr_Occurred()) { PyErr_SetString(PyExc_ValueError, "invalid data-type"); return NULL; } return res; } static int _is_tuple_of_integers(PyObject *obj) { int i; if (!PyTuple_Check(obj)) { return 0; } for (i = 0; i < PyTuple_GET_SIZE(obj); i++) { if (!PyArray_IsIntegerScalar(PyTuple_GET_ITEM(obj, i))) { return 0; } } return 1; } /* * A tuple type would be either (generic typeobject, typesize) * or (fixed-length data-type, shape) * * or (inheriting data-type, new-data-type) * The new data-type must have the same itemsize as the inheriting data-type * unless the latter is 0 * * Thus (int32, {'real':(int16,0),'imag',(int16,2)}) * * is one way to specify a descriptor that will give * a['real'] and a['imag'] to an int32 array. * * leave type reference alone */ static PyArray_Descr * _use_inherit(PyArray_Descr *type, PyObject *newobj, int *errflag) { PyArray_Descr *new; PyArray_Descr *conv; *errflag = 0; if (PyArray_IsScalar(newobj, Integer) || _is_tuple_of_integers(newobj) || !PyArray_DescrConverter(newobj, &conv)) { return NULL; } *errflag = 1; new = PyArray_DescrNew(type); if (new == NULL) { goto fail; } if (new->elsize && new->elsize != conv->elsize) { PyErr_SetString(PyExc_ValueError, "mismatch in size of old and new data-descriptor"); goto fail; } new->elsize = conv->elsize; if (PyDataType_HASFIELDS(conv)) { new->fields = conv->fields; Py_XINCREF(new->fields); new->names = conv->names; Py_XINCREF(new->names); } new->flags = conv->flags; Py_DECREF(conv); *errflag = 0; return new; fail: Py_DECREF(conv); return NULL; } /* * Validates that any field of the structured array 'dtype' which has * the NPY_ITEM_HASOBJECT flag set does not overlap with another field. * * This algorithm is worst case O(n^2). It could be done with a sort * and sweep algorithm, but the structured dtype representation is * rather ugly right now, so writing something better can wait until * that representation is made sane. * * Returns 0 on success, -1 if an exception is raised. */ static int validate_object_field_overlap(PyArray_Descr *dtype) { PyObject *names, *fields, *key, *tup, *title; Py_ssize_t i, j, names_size; PyArray_Descr *fld_dtype, *fld2_dtype; int fld_offset, fld2_offset; /* Get some properties from the dtype */ names = dtype->names; names_size = PyTuple_GET_SIZE(names); fields = dtype->fields; for (i = 0; i < names_size; ++i) { key = PyTuple_GET_ITEM(names, i); if (key == NULL) { return -1; } tup = PyDict_GetItem(fields, key); if (tup == NULL) { return -1; } if (!PyArg_ParseTuple(tup, "Oi|O", &fld_dtype, &fld_offset, &title)) { return -1; } /* If this field has objects, check for overlaps */ if (PyDataType_REFCHK(fld_dtype)) { for (j = 0; j < names_size; ++j) { if (i != j) { key = PyTuple_GET_ITEM(names, j); if (key == NULL) { return -1; } tup = PyDict_GetItem(fields, key); if (tup == NULL) { return -1; } if (!PyArg_ParseTuple(tup, "Oi|O", &fld2_dtype, &fld2_offset, &title)) { return -1; } /* Raise an exception if it overlaps */ if (fld_offset < fld2_offset + fld2_dtype->elsize && fld2_offset < fld_offset + fld_dtype->elsize) { PyErr_SetString(PyExc_TypeError, "Cannot create a NumPy dtype with overlapping " "object fields"); return -1; } } } } } /* It passed all the overlap tests */ return 0; } /* * a dictionary specifying a data-type * must have at least two and up to four * keys These must all be sequences of the same length. * * can also have an additional key called "metadata" which can be any dictionary * * "names" --- field names * "formats" --- the data-type descriptors for the field. * * Optional: * * "offsets" --- integers indicating the offset into the * record of the start of the field. * if not given, then "consecutive offsets" * will be assumed and placed in the dictionary. * * "titles" --- Allows the use of an additional key * for the fields dictionary.(if these are strings * or unicode objects) or * this can also be meta-data to * be passed around with the field description. * * Attribute-lookup-based field names merely has to query the fields * dictionary of the data-descriptor. Any result present can be used * to return the correct field. * * So, the notion of what is a name and what is a title is really quite * arbitrary. * * What does distinguish a title, however, is that if it is not None, * it will be placed at the end of the tuple inserted into the * fields dictionary.and can therefore be used to carry meta-data around. * * If the dictionary does not have "names" and "formats" entries, * then it will be checked for conformity and used directly. */ static PyArray_Descr * _use_fields_dict(PyObject *obj, int align) { PyObject *_numpy_internal; PyArray_Descr *res; _numpy_internal = PyImport_ImportModule("numpy.core._internal"); if (_numpy_internal == NULL) { return NULL; } res = (PyArray_Descr *)PyObject_CallMethod(_numpy_internal, "_usefields", "Oi", obj, align); Py_DECREF(_numpy_internal); return res; } /* * Creates a struct dtype object from a Python dictionary. */ static PyArray_Descr * _convert_from_dict(PyObject *obj, int align) { PyArray_Descr *new; PyObject *fields = NULL; PyObject *names, *offsets, *descrs, *titles, *tmp; PyObject *metadata; int n, i; int totalsize, itemsize; int maxalign = 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(); if (fields == NULL) { return (PyArray_Descr *)PyErr_NoMemory(); } names = PyDict_GetItemString(obj, "names"); descrs = PyDict_GetItemString(obj, "formats"); if (!names || !descrs) { Py_DECREF(fields); return _use_fields_dict(obj, align); } n = PyObject_Length(names); offsets = PyDict_GetItemString(obj, "offsets"); titles = PyDict_GetItemString(obj, "titles"); if ((n > PyObject_Length(descrs)) || (offsets && (n > PyObject_Length(offsets))) || (titles && (n > PyObject_Length(titles)))) { PyErr_SetString(PyExc_ValueError, "'names', 'formats', 'offsets', and 'titles' dicct " "entries must have the same length"); goto fail; } /* * If a property 'aligned' is in the dict, it overrides the align flag * to be True if it not already true. */ tmp = PyDict_GetItemString(obj, "aligned"); if (tmp != NULL) { if (tmp == Py_True) { align = 1; } else if (tmp != Py_False) { PyErr_SetString(PyExc_ValueError, "NumPy dtype descriptor includes 'aligned' entry, " "but its value is neither True nor False"); return NULL; } } totalsize = 0; for (i = 0; i < n; i++) { PyObject *tup, *descr, *ind, *title, *name, *off; int len, ret, _align = 1; PyArray_Descr *newdescr; /* Build item to insert (descr, offset, [title])*/ len = 2; title = NULL; ind = PyInt_FromLong(i); if (titles) { title=PyObject_GetItem(titles, ind); if (title && title != Py_None) { len = 3; } else { Py_XDECREF(title); } PyErr_Clear(); } tup = PyTuple_New(len); descr = PyObject_GetItem(descrs, ind); if (!descr) { goto fail; } if (align) { ret = PyArray_DescrAlignConverter(descr, &newdescr); } else { ret = PyArray_DescrConverter(descr, &newdescr); } Py_DECREF(descr); if (ret == NPY_FAIL) { Py_DECREF(tup); Py_DECREF(ind); goto fail; } PyTuple_SET_ITEM(tup, 0, (PyObject *)newdescr); if (align) { _align = newdescr->alignment; maxalign = PyArray_MAX(maxalign,_align); } if (offsets) { long offset; off = PyObject_GetItem(offsets, ind); if (!off) { goto fail; } offset = PyInt_AsLong(off); PyTuple_SET_ITEM(tup, 1, off); /* Flag whether the fields are specified out of order */ if (offset < totalsize) { has_out_of_order_fields = 1; } /* If align=True, enforce field alignment */ if (align && offset % newdescr->alignment != 0) { PyErr_Format(PyExc_ValueError, "offset %d for NumPy dtype with fields is " "not divisible by the field alignment %d " "with align=True", (int)offset, (int)newdescr->alignment); ret = NPY_FAIL; } else if (offset + newdescr->elsize > totalsize) { totalsize = offset + newdescr->elsize; } } else { if (align && _align > 1) { totalsize = NPY_NEXT_ALIGNED_OFFSET(totalsize, _align); } PyTuple_SET_ITEM(tup, 1, PyInt_FromLong(totalsize)); totalsize += newdescr->elsize; } if (len == 3) { PyTuple_SET_ITEM(tup, 2, title); } name = PyObject_GetItem(names, ind); if (!name) { goto fail; } Py_DECREF(ind); #if defined(NPY_PY3K) if (!PyUString_Check(name)) { #else if (!(PyUString_Check(name) || PyUnicode_Check(name))) { #endif PyErr_SetString(PyExc_ValueError, "field names must be strings"); ret = NPY_FAIL; } /* Insert into dictionary */ if (PyDict_GetItem(fields, name) != NULL) { PyErr_SetString(PyExc_ValueError, "name already used as a name or title"); ret = NPY_FAIL; } PyDict_SetItem(fields, name, tup); Py_DECREF(name); if (len == 3) { #if defined(NPY_PY3K) if (PyUString_Check(title)) { #else if (PyUString_Check(title) || PyUnicode_Check(title)) { #endif if (PyDict_GetItem(fields, title) != NULL) { PyErr_SetString(PyExc_ValueError, "title already used as a name or title."); ret=NPY_FAIL; } PyDict_SetItem(fields, title, tup); } } Py_DECREF(tup); if ((ret == NPY_FAIL) || (newdescr->elsize == 0)) { goto fail; } dtypeflags |= (newdescr->flags & NPY_FROM_FIELDS); } new = PyArray_DescrNewFromType(NPY_VOID); if (new == NULL) { goto fail; } if (maxalign > 1) { totalsize = NPY_NEXT_ALIGNED_OFFSET(totalsize, maxalign); } if (align) { new->alignment = maxalign; } new->elsize = totalsize; if (!PyTuple_Check(names)) { names = PySequence_Tuple(names); } else { Py_INCREF(names); } new->names = names; new->fields = fields; new->flags = dtypeflags; /* * If the fields weren't in order, and there was an OBJECT type, * need to verify that no OBJECT types overlap with something else. */ if (has_out_of_order_fields && PyDataType_REFCHK(new)) { if (validate_object_field_overlap(new) < 0) { Py_DECREF(new); return NULL; } } /* Structured arrays get a sticky aligned bit */ if (align) { new->flags |= NPY_ALIGNED_STRUCT; } /* Override the itemsize if provided */ tmp = PyDict_GetItemString(obj, "itemsize"); if (tmp != NULL) { itemsize = (int)PyInt_AsLong(tmp); if (itemsize == -1 && PyErr_Occurred()) { Py_DECREF(new); return NULL; } /* Make sure the itemsize isn't made too small */ if (itemsize < new->elsize) { PyErr_Format(PyExc_ValueError, "NumPy dtype descriptor requires %d bytes, " "cannot override to smaller itemsize of %d", (int)new->elsize, (int)itemsize); Py_DECREF(new); return NULL; } /* If align is set, make sure the alignment divides into the size */ if (align && itemsize % new->alignment != 0) { PyErr_Format(PyExc_ValueError, "NumPy dtype descriptor requires alignment of %d bytes, " "which is not divisible into the specified itemsize %d", (int)new->alignment, (int)itemsize); Py_DECREF(new); return NULL; } /* Set the itemsize */ new->elsize = itemsize; } /* Add the metadata if provided */ metadata = PyDict_GetItemString(obj, "metadata"); if (new->metadata == NULL) { new->metadata = metadata; Py_XINCREF(new->metadata); } else if (metadata != NULL) { if (PyDict_Merge(new->metadata, metadata, 0) == -1) { Py_DECREF(new); return NULL; } } return new; fail: Py_XDECREF(fields); return NULL; } /*NUMPY_API*/ NPY_NO_EXPORT PyArray_Descr * PyArray_DescrNewFromType(int type_num) { PyArray_Descr *old; PyArray_Descr *new; old = PyArray_DescrFromType(type_num); new = PyArray_DescrNew(old); Py_DECREF(old); return new; } /*NUMPY_API * Get typenum from an object -- None goes to NULL */ NPY_NO_EXPORT int PyArray_DescrConverter2(PyObject *obj, PyArray_Descr **at) { if (obj == Py_None) { *at = NULL; return NPY_SUCCEED; } else { return PyArray_DescrConverter(obj, at); } } /*NUMPY_API * Get typenum from an object -- None goes to NPY_DEFAULT_TYPE * This function takes a Python object representing a type and converts it * to a the correct PyArray_Descr * structure to describe the type. * * Many objects can be used to represent a data-type which in NumPy is * quite a flexible concept. * * This is the central code that converts Python objects to * Type-descriptor objects that are used throughout numpy. * * Returns a new reference in *at, but the returned should not be * modified as it may be one of the canonical immutable objects or * a reference to the input obj. */ NPY_NO_EXPORT int PyArray_DescrConverter(PyObject *obj, PyArray_Descr **at) { int check_num = NPY_NOTYPE + 10; PyObject *item; int elsize = 0; char endian = '='; *at = NULL; /* default */ if (obj == Py_None) { *at = PyArray_DescrFromType(NPY_DEFAULT_TYPE); return NPY_SUCCEED; } if (PyArray_DescrCheck(obj)) { *at = (PyArray_Descr *)obj; Py_INCREF(*at); return NPY_SUCCEED; } if (PyType_Check(obj)) { if (PyType_IsSubtype((PyTypeObject *)obj, &PyGenericArrType_Type)) { *at = PyArray_DescrFromTypeObject(obj); return (*at) ? NPY_SUCCEED : NPY_FAIL; } check_num = NPY_OBJECT; #if !defined(NPY_PY3K) if (obj == (PyObject *)(&PyInt_Type)) { check_num = NPY_LONG; } else if (obj == (PyObject *)(&PyLong_Type)) { check_num = NPY_LONGLONG; } #else if (obj == (PyObject *)(&PyLong_Type)) { check_num = NPY_LONG; } #endif else if (obj == (PyObject *)(&PyFloat_Type)) { check_num = NPY_DOUBLE; } else if (obj == (PyObject *)(&PyComplex_Type)) { check_num = NPY_CDOUBLE; } else if (obj == (PyObject *)(&PyBool_Type)) { check_num = NPY_BOOL; } else if (obj == (PyObject *)(&PyBytes_Type)) { check_num = NPY_STRING; } else if (obj == (PyObject *)(&PyUnicode_Type)) { check_num = NPY_UNICODE; } #if defined(NPY_PY3K) else if (obj == (PyObject *)(&PyMemoryView_Type)) { #else else if (obj == (PyObject *)(&PyBuffer_Type)) { #endif check_num = NPY_VOID; } else { *at = _arraydescr_fromobj(obj); if (*at) { return NPY_SUCCEED; } } goto finish; } /* or a typecode string */ if (PyUnicode_Check(obj)) { /* Allow unicode format strings: convert to bytes */ int retval; PyObject *obj2; obj2 = PyUnicode_AsASCIIString(obj); if (obj2 == NULL) { return NPY_FAIL; } retval = PyArray_DescrConverter(obj2, at); Py_DECREF(obj2); return retval; } if (PyBytes_Check(obj)) { char *type = NULL; Py_ssize_t len = 0; /* Check for a string typecode. */ if (PyBytes_AsStringAndSize(obj, &type, &len) < 0) { goto error; } /* Empty string is invalid */ if (len == 0) { goto fail; } /* check for commas present or first (or second) element a digit */ if (_check_for_commastring(type, len)) { *at = _convert_from_commastring(obj, 0); return (*at) ? NPY_SUCCEED : NPY_FAIL; } /* Process the endian character. '|' is replaced by '='*/ switch (type[0]) { case '>': case '<': case '=': endian = type[0]; ++type; --len; break; case '|': endian = '='; ++type; --len; break; } /* Just an endian character is invalid */ if (len == 0) { goto fail; } /* Check for datetime format */ if (is_datetime_typestr(type, len)) { *at = parse_dtype_from_datetime_typestr(type, len); if (*at == NULL) { return NPY_FAIL; } /* *at has byte order '=' at this point */ if (!PyArray_ISNBO(endian)) { (*at)->byteorder = endian; } return NPY_SUCCEED; } /* A typecode like 'd' */ if (len == 1) { check_num = type[0]; } /* A kind + size like 'f8' */ else { char *typeend = NULL; int kind; /* Parse the integer, make sure it's the rest of the string */ elsize = (int)strtol(type + 1, &typeend, 10); if (typeend - type == len) { kind = type[0]; switch (kind) { case NPY_STRINGLTR: case NPY_STRINGLTR2: check_num = NPY_STRING; break; /* * When specifying length of UNICODE * the number of characters is given to match * the STRING interface. Each character can be * more than one byte and itemsize must be * the number of bytes. */ case NPY_UNICODELTR: check_num = NPY_UNICODE; elsize <<= 2; break; case NPY_VOIDLTR: check_num = NPY_VOID; break; default: if (elsize == 0) { check_num = NPY_NOTYPE+10; } /* Support for generic processing c8, i4, f8, etc...*/ else { check_num = PyArray_TypestrConvert(elsize, kind); if (check_num == NPY_NOTYPE) { check_num += 10; } elsize = 0; } } } } } else if (PyTuple_Check(obj)) { /* or a tuple */ *at = _convert_from_tuple(obj); if (*at == NULL){ if (PyErr_Occurred()) { return NPY_FAIL; } goto fail; } return NPY_SUCCEED; } else if (PyList_Check(obj)) { /* or a list */ *at = _convert_from_array_descr(obj,0); if (*at == NULL) { if (PyErr_Occurred()) { return NPY_FAIL; } goto fail; } return NPY_SUCCEED; } else if (PyDict_Check(obj)) { /* or a dictionary */ *at = _convert_from_dict(obj,0); if (*at == NULL) { if (PyErr_Occurred()) { return NPY_FAIL; } goto fail; } return NPY_SUCCEED; } else if (PyArray_Check(obj)) { goto fail; } else { *at = _arraydescr_fromobj(obj); if (*at) { return NPY_SUCCEED; } if (PyErr_Occurred()) { return NPY_FAIL; } goto fail; } if (PyErr_Occurred()) { goto fail; } finish: if ((check_num == NPY_NOTYPE + 10) || (*at = PyArray_DescrFromType(check_num)) == NULL) { PyErr_Clear(); /* Now check to see if the object is registered in typeDict */ if (typeDict != NULL) { item = PyDict_GetItem(typeDict, obj); #if defined(NPY_PY3K) if (!item && PyBytes_Check(obj)) { PyObject *tmp; tmp = PyUnicode_FromEncodedObject(obj, "ascii", "strict"); if (tmp != NULL) { item = PyDict_GetItem(typeDict, tmp); Py_DECREF(tmp); } } #endif if (item) { return PyArray_DescrConverter(item, at); } } goto fail; } if (((*at)->elsize == 0) && (elsize != 0)) { PyArray_DESCR_REPLACE(*at); (*at)->elsize = elsize; } if (endian != '=' && PyArray_ISNBO(endian)) { endian = '='; } if (endian != '=' && (*at)->byteorder != '|' && (*at)->byteorder != endian) { PyArray_DESCR_REPLACE(*at); (*at)->byteorder = endian; } return NPY_SUCCEED; fail: if (PyBytes_Check(obj)) { PyErr_Format(PyExc_TypeError, "data type \"%s\" not understood", PyBytes_AS_STRING(obj)); } else { PyErr_SetString(PyExc_TypeError, "data type not understood"); } error: *at = NULL; return NPY_FAIL; } /** Array Descr Objects for dynamic types **/ /* * There are some statically-defined PyArray_Descr objects corresponding * to the basic built-in types. * These can and should be DECREF'd and INCREF'd as appropriate, anyway. * If a mistake is made in reference counting, deallocation on these * builtins will be attempted leading to problems. * * This lets us deal with all PyArray_Descr objects using reference * counting (regardless of whether they are statically or dynamically * allocated). */ /*NUMPY_API * base cannot be NULL */ NPY_NO_EXPORT PyArray_Descr * PyArray_DescrNew(PyArray_Descr *base) { PyArray_Descr *newdescr = PyObject_New(PyArray_Descr, &PyArrayDescr_Type); if (newdescr == NULL) { return NULL; } /* Don't copy PyObject_HEAD part */ memcpy((char *)newdescr + sizeof(PyObject), (char *)base + sizeof(PyObject), sizeof(PyArray_Descr) - sizeof(PyObject)); /* * The c_metadata has a by-value ownership model, need to clone it * (basically a deep copy, but the auxdata clone function has some * flexibility still) so the new PyArray_Descr object owns * a copy of the data. Having both 'base' and 'newdescr' point to * the same auxdata pointer would cause a double-free of memory. */ if (base->c_metadata != NULL) { newdescr->c_metadata = NPY_AUXDATA_CLONE(base->c_metadata); if (newdescr->c_metadata == NULL) { PyErr_NoMemory(); Py_DECREF(newdescr); return NULL; } } if (newdescr->fields == Py_None) { newdescr->fields = NULL; } Py_XINCREF(newdescr->fields); Py_XINCREF(newdescr->names); if (newdescr->subarray) { newdescr->subarray = PyArray_malloc(sizeof(PyArray_ArrayDescr)); if (newdescr->subarray == NULL) { Py_DECREF(newdescr); return PyErr_NoMemory(); } memcpy(newdescr->subarray, base->subarray, sizeof(PyArray_ArrayDescr)); Py_INCREF(newdescr->subarray->shape); Py_INCREF(newdescr->subarray->base); } Py_XINCREF(newdescr->typeobj); Py_XINCREF(newdescr->metadata); return newdescr; } /* * should never be called for builtin-types unless * there is a reference-count problem */ static void arraydescr_dealloc(PyArray_Descr *self) { if (self->fields == Py_None) { fprintf(stderr, "*** Reference count error detected: \n" \ "an attempt was made to deallocate %d (%c) ***\n", self->type_num, self->type); Py_INCREF(self); Py_INCREF(self); return; } Py_XDECREF(self->typeobj); Py_XDECREF(self->names); Py_XDECREF(self->fields); if (self->subarray) { Py_XDECREF(self->subarray->shape); Py_DECREF(self->subarray->base); PyArray_free(self->subarray); } Py_XDECREF(self->metadata); NPY_AUXDATA_FREE(self->c_metadata); self->c_metadata = NULL; Py_TYPE(self)->tp_free((PyObject *)self); } /* * we need to be careful about setting attributes because these * objects are pointed to by arrays that depend on them for interpreting * data. Currently no attributes of data-type objects can be set * directly except names. */ static PyMemberDef arraydescr_members[] = { {"type", T_OBJECT, offsetof(PyArray_Descr, typeobj), READONLY, NULL}, {"kind", T_CHAR, offsetof(PyArray_Descr, kind), READONLY, NULL}, {"char", T_CHAR, offsetof(PyArray_Descr, type), READONLY, NULL}, {"num", T_INT, offsetof(PyArray_Descr, type_num), READONLY, NULL}, {"byteorder", T_CHAR, offsetof(PyArray_Descr, byteorder), READONLY, NULL}, {"itemsize", T_INT, offsetof(PyArray_Descr, elsize), READONLY, NULL}, {"alignment", T_INT, offsetof(PyArray_Descr, alignment), READONLY, NULL}, {"flags", T_BYTE, offsetof(PyArray_Descr, flags), READONLY, NULL}, {NULL, 0, 0, 0, NULL}, }; static PyObject * arraydescr_subdescr_get(PyArray_Descr *self) { if (!PyDataType_HASSUBARRAY(self)) { Py_INCREF(Py_None); return Py_None; } return Py_BuildValue("OO", (PyObject *)self->subarray->base, self->subarray->shape); } NPY_NO_EXPORT PyObject * arraydescr_protocol_typestr_get(PyArray_Descr *self) { char basic_ = self->kind; char endian = self->byteorder; int size = self->elsize; PyObject *ret; if (endian == '=') { endian = '<'; if (!PyArray_IsNativeByteOrder(endian)) { endian = '>'; } } if (self->type_num == NPY_UNICODE) { size >>= 2; } ret = PyUString_FromFormat("%c%c%d", endian, basic_, size); if (PyDataType_ISDATETIME(self)) { PyArray_DatetimeMetaData *meta; meta = get_datetime_metadata_from_dtype(self); if (meta == NULL) { Py_DECREF(ret); return NULL; } ret = append_metastr_to_string(meta, 0, ret); } return ret; } static PyObject * arraydescr_typename_get(PyArray_Descr *self) { int len; PyTypeObject *typeobj = self->typeobj; PyObject *res; char *s; /* fixme: not reentrant */ static int prefix_len = 0; if (PyTypeNum_ISUSERDEF(self->type_num)) { s = strrchr(typeobj->tp_name, '.'); if (s == NULL) { res = PyUString_FromString(typeobj->tp_name); } else { res = PyUString_FromStringAndSize(s + 1, strlen(s) - 1); } return res; } else { if (prefix_len == 0) { prefix_len = strlen("numpy."); } len = strlen(typeobj->tp_name); if (*(typeobj->tp_name + (len-1)) == '_') { len -= 1; } len -= prefix_len; res = PyUString_FromStringAndSize(typeobj->tp_name+prefix_len, len); } if (PyTypeNum_ISFLEXIBLE(self->type_num) && self->elsize != 0) { PyObject *p; p = PyUString_FromFormat("%d", self->elsize * 8); PyUString_ConcatAndDel(&res, p); } if (PyDataType_ISDATETIME(self)) { PyArray_DatetimeMetaData *meta; meta = get_datetime_metadata_from_dtype(self); if (meta == NULL) { Py_DECREF(res); return NULL; } res = append_metastr_to_string(meta, 0, res); } return res; } static PyObject * arraydescr_base_get(PyArray_Descr *self) { if (!PyDataType_HASSUBARRAY(self)) { Py_INCREF(self); return (PyObject *)self; } Py_INCREF(self->subarray->base); return (PyObject *)(self->subarray->base); } static PyObject * arraydescr_shape_get(PyArray_Descr *self) { if (!PyDataType_HASSUBARRAY(self)) { return PyTuple_New(0); } /*TODO * self->subarray->shape should always be a tuple, * so this check should be unnecessary */ if (PyTuple_Check(self->subarray->shape)) { Py_INCREF(self->subarray->shape); return (PyObject *)(self->subarray->shape); } return Py_BuildValue("(O)", self->subarray->shape); } NPY_NO_EXPORT PyObject * arraydescr_protocol_descr_get(PyArray_Descr *self) { PyObject *dobj, *res; PyObject *_numpy_internal; if (!PyDataType_HASFIELDS(self)) { /* get default */ dobj = PyTuple_New(2); if (dobj == NULL) { return NULL; } PyTuple_SET_ITEM(dobj, 0, PyUString_FromString("")); PyTuple_SET_ITEM(dobj, 1, arraydescr_protocol_typestr_get(self)); res = PyList_New(1); if (res == NULL) { Py_DECREF(dobj); return NULL; } PyList_SET_ITEM(res, 0, dobj); return res; } _numpy_internal = PyImport_ImportModule("numpy.core._internal"); if (_numpy_internal == NULL) { return NULL; } res = PyObject_CallMethod(_numpy_internal, "_array_descr", "O", self); Py_DECREF(_numpy_internal); return res; } /* * returns 1 for a builtin type * and 2 for a user-defined data-type descriptor * return 0 if neither (i.e. it's a copy of one) */ static PyObject * arraydescr_isbuiltin_get(PyArray_Descr *self) { long val; val = 0; if (self->fields == Py_None) { val = 1; } if (PyTypeNum_ISUSERDEF(self->type_num)) { val = 2; } return PyInt_FromLong(val); } static int _arraydescr_isnative(PyArray_Descr *self) { if (!PyDataType_HASFIELDS(self)) { return PyArray_ISNBO(self->byteorder); } else { PyObject *key, *value, *title = NULL; PyArray_Descr *new; int offset; Py_ssize_t pos = 0; while (PyDict_Next(self->fields, &pos, &key, &value)) { if NPY_TITLE_KEY(key, value) { continue; } if (!PyArg_ParseTuple(value, "Oi|O", &new, &offset, &title)) { return -1; } if (!_arraydescr_isnative(new)) { return 0; } } } return 1; } /* * return Py_True if this data-type descriptor * has native byteorder if no fields are defined * * or if all sub-fields have native-byteorder if * fields are defined */ static PyObject * arraydescr_isnative_get(PyArray_Descr *self) { PyObject *ret; int retval; retval = _arraydescr_isnative(self); if (retval == -1) { return NULL; } ret = retval ? Py_True : Py_False; Py_INCREF(ret); return ret; } static PyObject * arraydescr_isalignedstruct_get(PyArray_Descr *self) { PyObject *ret; ret = (self->flags&NPY_ALIGNED_STRUCT) ? Py_True : Py_False; Py_INCREF(ret); return ret; } static PyObject * arraydescr_fields_get(PyArray_Descr *self) { if (!PyDataType_HASFIELDS(self)) { Py_INCREF(Py_None); return Py_None; } return PyDictProxy_New(self->fields); } static PyObject * arraydescr_metadata_get(PyArray_Descr *self) { if (self->metadata == NULL) { Py_INCREF(Py_None); return Py_None; } return PyDictProxy_New(self->metadata); } static PyObject * arraydescr_hasobject_get(PyArray_Descr *self) { if (PyDataType_FLAGCHK(self, NPY_ITEM_HASOBJECT)) { Py_RETURN_TRUE; } else { Py_RETURN_FALSE; } } static PyObject * arraydescr_names_get(PyArray_Descr *self) { if (!PyDataType_HASFIELDS(self)) { Py_INCREF(Py_None); return Py_None; } Py_INCREF(self->names); return self->names; } static int arraydescr_names_set(PyArray_Descr *self, PyObject *val) { int N = 0; int i; PyObject *new_names; PyObject *new_fields; if (val == NULL) { PyErr_SetString(PyExc_AttributeError, "Cannot delete dtype names attribute"); return -1; } if (!PyDataType_HASFIELDS(self)) { PyErr_SetString(PyExc_ValueError, "there are no fields defined"); return -1; } /* * This deprecation has been temporarily removed for the NumPy 1.7 * release. It should be re-added after the 1.7 branch is done, * and a convenience API to replace the typical use-cases for * mutable names should be implemented. * * if (DEPRECATE("Setting NumPy dtype names is deprecated, the dtype " * "will become immutable in a future version") < 0) { * return -1; * } */ N = PyTuple_GET_SIZE(self->names); if (!PySequence_Check(val) || PyObject_Size((PyObject *)val) != N) { PyErr_Format(PyExc_ValueError, "must replace all names at once with a sequence of length %d", N); return -1; } /* Make sure all entries are strings */ for (i = 0; i < N; i++) { PyObject *item; int valid = 1; item = PySequence_GetItem(val, i); valid = PyUString_Check(item); Py_DECREF(item); if (!valid) { PyErr_Format(PyExc_ValueError, "item #%d of names is of type %s and not string", i, Py_TYPE(item)->tp_name); return -1; } } /* Update dictionary keys in fields */ new_names = PySequence_Tuple(val); new_fields = PyDict_New(); for (i = 0; i < N; i++) { PyObject *key; PyObject *item; PyObject *new_key; int ret; key = PyTuple_GET_ITEM(self->names, i); /* Borrowed references to item and new_key */ item = PyDict_GetItem(self->fields, key); new_key = PyTuple_GET_ITEM(new_names, i); /* Check for duplicates */ ret = PyDict_Contains(new_fields, new_key); if (ret != 0) { if (ret < 0) { PyErr_Clear(); } PyErr_SetString(PyExc_ValueError, "Duplicate field names given."); Py_DECREF(new_names); Py_DECREF(new_fields); return -1; } PyDict_SetItem(new_fields, new_key, item); } /* Replace names */ Py_DECREF(self->names); self->names = new_names; /* Replace fields */ Py_DECREF(self->fields); self->fields = new_fields; return 0; } static PyGetSetDef arraydescr_getsets[] = { {"subdtype", (getter)arraydescr_subdescr_get, NULL, NULL, NULL}, {"descr", (getter)arraydescr_protocol_descr_get, NULL, NULL, NULL}, {"str", (getter)arraydescr_protocol_typestr_get, NULL, NULL, NULL}, {"name", (getter)arraydescr_typename_get, NULL, NULL, NULL}, {"base", (getter)arraydescr_base_get, NULL, NULL, NULL}, {"shape", (getter)arraydescr_shape_get, NULL, NULL, NULL}, {"isbuiltin", (getter)arraydescr_isbuiltin_get, NULL, NULL, NULL}, {"isnative", (getter)arraydescr_isnative_get, NULL, NULL, NULL}, {"isalignedstruct", (getter)arraydescr_isalignedstruct_get, NULL, NULL, NULL}, {"fields", (getter)arraydescr_fields_get, NULL, NULL, NULL}, {"metadata", (getter)arraydescr_metadata_get, NULL, NULL, NULL}, {"names", (getter)arraydescr_names_get, (setter)arraydescr_names_set, NULL, NULL}, {"hasobject", (getter)arraydescr_hasobject_get, NULL, NULL, NULL}, {NULL, NULL, NULL, NULL, NULL}, }; static PyObject * arraydescr_new(PyTypeObject *NPY_UNUSED(subtype), PyObject *args, PyObject *kwds) { PyObject *odescr, *metadata=NULL; PyArray_Descr *descr, *conv; npy_bool align = NPY_FALSE; npy_bool copy = NPY_FALSE; npy_bool copied = NPY_FALSE; static char *kwlist[] = {"dtype", "align", "copy", "metadata", NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O&O&O!", kwlist, &odescr, PyArray_BoolConverter, &align, PyArray_BoolConverter, ©, &PyDict_Type, &metadata)) { return NULL; } if (align) { if (!PyArray_DescrAlignConverter(odescr, &conv)) { return NULL; } } else if (!PyArray_DescrConverter(odescr, &conv)) { return NULL; } /* Get a new copy of it unless it's already a copy */ if (copy && conv->fields == Py_None) { descr = PyArray_DescrNew(conv); Py_DECREF(conv); conv = descr; copied = NPY_TRUE; } if ((metadata != NULL)) { /* * We need to be sure to make a new copy of the data-type and any * underlying dictionary */ if (!copied) { copied = NPY_TRUE; descr = PyArray_DescrNew(conv); Py_DECREF(conv); conv = descr; } if ((conv->metadata != NULL)) { /* * Make a copy of the metadata before merging with the * input metadata so that this data-type descriptor has * it's own copy */ /* Save a reference */ odescr = conv->metadata; conv->metadata = PyDict_Copy(odescr); /* Decrement the old reference */ Py_DECREF(odescr); /* * Update conv->metadata with anything new in metadata * keyword, but do not over-write anything already there */ if (PyDict_Merge(conv->metadata, metadata, 0) != 0) { Py_DECREF(conv); return NULL; } } else { /* Make a copy of the input dictionary */ conv->metadata = PyDict_Copy(metadata); } } return (PyObject *)conv; } /* * Return a tuple of * (cleaned metadata dictionary, tuple with (str, num)) */ static PyObject * _get_pickleabletype_from_datetime_metadata(PyArray_Descr *dtype) { PyObject *ret, *dt_tuple; PyArray_DatetimeMetaData *meta; /* Create the 2-item tuple to return */ ret = PyTuple_New(2); if (ret == NULL) { return NULL; } /* Store the metadata dictionary */ if (dtype->metadata != NULL) { Py_INCREF(dtype->metadata); PyTuple_SET_ITEM(ret, 0, dtype->metadata); } else { PyTuple_SET_ITEM(ret, 0, PyDict_New()); } /* Convert the datetime metadata into a tuple */ meta = get_datetime_metadata_from_dtype(dtype); if (meta == NULL) { Py_DECREF(ret); return NULL; } /* Use a 4-tuple that numpy 1.6 knows how to unpickle */ dt_tuple = PyTuple_New(4); if (dt_tuple == NULL) { Py_DECREF(ret); return NULL; } PyTuple_SET_ITEM(dt_tuple, 0, PyBytes_FromString(_datetime_strings[meta->base])); PyTuple_SET_ITEM(dt_tuple, 1, PyInt_FromLong(meta->num)); PyTuple_SET_ITEM(dt_tuple, 2, PyInt_FromLong(1)); PyTuple_SET_ITEM(dt_tuple, 3, PyInt_FromLong(1)); PyTuple_SET_ITEM(ret, 1, dt_tuple); return ret; } /* * return a tuple of (callable object, args, state). * * TODO: This method needs to change so that unpickling doesn't * use __setstate__. This is required for the dtype * to be an immutable object. */ static PyObject * arraydescr_reduce(PyArray_Descr *self, PyObject *NPY_UNUSED(args)) { /* * version number of this pickle type. Increment if we need to * change the format. Be sure to handle the old versions in * arraydescr_setstate. */ const int version = 4; PyObject *ret, *mod, *obj; PyObject *state; char endian; int elsize, alignment; ret = PyTuple_New(3); if (ret == NULL) { return NULL; } mod = PyImport_ImportModule("numpy.core.multiarray"); if (mod == NULL) { Py_DECREF(ret); return NULL; } obj = PyObject_GetAttrString(mod, "dtype"); Py_DECREF(mod); if (obj == NULL) { Py_DECREF(ret); return NULL; } PyTuple_SET_ITEM(ret, 0, obj); if (PyTypeNum_ISUSERDEF(self->type_num) || ((self->type_num == NPY_VOID && self->typeobj != &PyVoidArrType_Type))) { obj = (PyObject *)self->typeobj; Py_INCREF(obj); } else { elsize = self->elsize; if (self->type_num == NPY_UNICODE) { elsize >>= 2; } obj = PyUString_FromFormat("%c%d",self->kind, elsize); } PyTuple_SET_ITEM(ret, 1, Py_BuildValue("(Nii)", obj, 0, 1)); /* * Now return the state which is at least byteorder, * subarray, and fields */ endian = self->byteorder; if (endian == '=') { endian = '<'; if (!PyArray_IsNativeByteOrder(endian)) { endian = '>'; } } if (PyDataType_ISDATETIME(self)) { PyObject *newobj; state = PyTuple_New(9); PyTuple_SET_ITEM(state, 0, PyInt_FromLong(version)); /* * newobj is a tuple of the Python metadata dictionary * and tuple of date_time info (str, num) */ newobj = _get_pickleabletype_from_datetime_metadata(self); if (newobj == NULL) { Py_DECREF(state); Py_DECREF(ret); return NULL; } PyTuple_SET_ITEM(state, 8, newobj); } else if (self->metadata) { state = PyTuple_New(9); PyTuple_SET_ITEM(state, 0, PyInt_FromLong(version)); Py_INCREF(self->metadata); PyTuple_SET_ITEM(state, 8, self->metadata); } else { /* Use version 3 pickle format */ state = PyTuple_New(8); PyTuple_SET_ITEM(state, 0, PyInt_FromLong(3)); } PyTuple_SET_ITEM(state, 1, PyUString_FromFormat("%c", endian)); PyTuple_SET_ITEM(state, 2, arraydescr_subdescr_get(self)); if (PyDataType_HASFIELDS(self)) { Py_INCREF(self->names); Py_INCREF(self->fields); PyTuple_SET_ITEM(state, 3, self->names); PyTuple_SET_ITEM(state, 4, self->fields); } else { PyTuple_SET_ITEM(state, 3, Py_None); PyTuple_SET_ITEM(state, 4, Py_None); Py_INCREF(Py_None); Py_INCREF(Py_None); } /* for extended types it also includes elsize and alignment */ if (PyTypeNum_ISEXTENDED(self->type_num)) { elsize = self->elsize; alignment = self->alignment; } else { elsize = -1; alignment = -1; } PyTuple_SET_ITEM(state, 5, PyInt_FromLong(elsize)); PyTuple_SET_ITEM(state, 6, PyInt_FromLong(alignment)); PyTuple_SET_ITEM(state, 7, PyInt_FromLong(self->flags)); PyTuple_SET_ITEM(ret, 2, state); return ret; } /* * returns NPY_OBJECT_DTYPE_FLAGS if this data-type has an object portion used * when setting the state because hasobject is not stored. */ static char _descr_find_object(PyArray_Descr *self) { if (self->flags || self->type_num == NPY_OBJECT || self->kind == 'O') { return NPY_OBJECT_DTYPE_FLAGS; } if (PyDataType_HASFIELDS(self)) { PyObject *key, *value, *title = NULL; PyArray_Descr *new; int offset; Py_ssize_t pos = 0; while (PyDict_Next(self->fields, &pos, &key, &value)) { if NPY_TITLE_KEY(key, value) { continue; } if (!PyArg_ParseTuple(value, "Oi|O", &new, &offset, &title)) { PyErr_Clear(); return 0; } if (_descr_find_object(new)) { new->flags = NPY_OBJECT_DTYPE_FLAGS; return NPY_OBJECT_DTYPE_FLAGS; } } } return 0; } /* * state is at least byteorder, subarray, and fields but could include elsize * and alignment for EXTENDED arrays */ static PyObject * arraydescr_setstate(PyArray_Descr *self, PyObject *args) { int elsize = -1, alignment = -1; int version = 4; #if defined(NPY_PY3K) int endian; #else char endian; #endif PyObject *subarray, *fields, *names = NULL, *metadata=NULL; int incref_names = 1; int int_dtypeflags = 0; char dtypeflags; if (self->fields == Py_None) { Py_INCREF(Py_None); return Py_None; } if (PyTuple_GET_SIZE(args) != 1 || !(PyTuple_Check(PyTuple_GET_ITEM(args, 0)))) { PyErr_BadInternalCall(); return NULL; } switch (PyTuple_GET_SIZE(PyTuple_GET_ITEM(args,0))) { case 9: #if defined(NPY_PY3K) #define _ARGSTR_ "(iCOOOiiiO)" #else #define _ARGSTR_ "(icOOOiiiO)" #endif if (!PyArg_ParseTuple(args, _ARGSTR_, &version, &endian, &subarray, &names, &fields, &elsize, &alignment, &int_dtypeflags, &metadata)) { return NULL; #undef _ARGSTR_ } break; case 8: #if defined(NPY_PY3K) #define _ARGSTR_ "(iCOOOiii)" #else #define _ARGSTR_ "(icOOOiii)" #endif if (!PyArg_ParseTuple(args, _ARGSTR_, &version, &endian, &subarray, &names, &fields, &elsize, &alignment, &int_dtypeflags)) { return NULL; #undef _ARGSTR_ } break; case 7: #if defined(NPY_PY3K) #define _ARGSTR_ "(iCOOOii)" #else #define _ARGSTR_ "(icOOOii)" #endif if (!PyArg_ParseTuple(args, _ARGSTR_, &version, &endian, &subarray, &names, &fields, &elsize, &alignment)) { return NULL; #undef _ARGSTR_ } break; case 6: #if defined(NPY_PY3K) #define _ARGSTR_ "(iCOOii)" #else #define _ARGSTR_ "(icOOii)" #endif if (!PyArg_ParseTuple(args, _ARGSTR_, &version, &endian, &subarray, &fields, &elsize, &alignment)) { PyErr_Clear(); #undef _ARGSTR_ } break; case 5: version = 0; #if defined(NPY_PY3K) #define _ARGSTR_ "(COOii)" #else #define _ARGSTR_ "(cOOii)" #endif if (!PyArg_ParseTuple(args, _ARGSTR_, &endian, &subarray, &fields, &elsize, &alignment)) { #undef _ARGSTR_ return NULL; } break; default: /* raise an error */ if (PyTuple_GET_SIZE(PyTuple_GET_ITEM(args,0)) > 5) { version = PyInt_AsLong(PyTuple_GET_ITEM(args, 0)); } else { version = -1; } } /* * If we ever need another pickle format, increment the version * number. But we should still be able to handle the old versions. */ if (version < 0 || version > 4) { PyErr_Format(PyExc_ValueError, "can't handle version %d of numpy.dtype pickle", version); return NULL; } if (version == 1 || version == 0) { if (fields != Py_None) { PyObject *key, *list; key = PyInt_FromLong(-1); list = PyDict_GetItem(fields, key); if (!list) { return NULL; } Py_INCREF(list); names = list; PyDict_DelItem(fields, key); incref_names = 0; } else { names = Py_None; } } if ((fields == Py_None && names != Py_None) || (names == Py_None && fields != Py_None)) { PyErr_Format(PyExc_ValueError, "inconsistent fields and names"); return NULL; } if (endian != '|' && PyArray_IsNativeByteOrder(endian)) { endian = '='; } self->byteorder = endian; if (self->subarray) { Py_XDECREF(self->subarray->base); Py_XDECREF(self->subarray->shape); PyArray_free(self->subarray); } self->subarray = NULL; if (subarray != Py_None) { PyObject *subarray_shape; /* * Ensure that subarray[0] is an ArrayDescr and * that subarray_shape obtained from subarray[1] is a tuple of integers. */ if (!(PyTuple_Check(subarray) && PyTuple_Size(subarray) == 2 && PyArray_DescrCheck(PyTuple_GET_ITEM(subarray, 0)))) { PyErr_Format(PyExc_ValueError, "incorrect subarray in __setstate__"); return NULL; } subarray_shape = PyTuple_GET_ITEM(subarray, 1); if (PyNumber_Check(subarray_shape)) { PyObject *tmp; #if defined(NPY_PY3K) tmp = PyNumber_Long(subarray_shape); #else tmp = PyNumber_Int(subarray_shape); #endif if (tmp == NULL) { return NULL; } subarray_shape = Py_BuildValue("(O)", tmp); Py_DECREF(tmp); if (subarray_shape == NULL) { return NULL; } } else if (_is_tuple_of_integers(subarray_shape)) { Py_INCREF(subarray_shape); } else { PyErr_Format(PyExc_ValueError, "incorrect subarray shape in __setstate__"); return NULL; } self->subarray = PyArray_malloc(sizeof(PyArray_ArrayDescr)); if (!PyDataType_HASSUBARRAY(self)) { return PyErr_NoMemory(); } self->subarray->base = (PyArray_Descr *)PyTuple_GET_ITEM(subarray, 0); Py_INCREF(self->subarray->base); self->subarray->shape = subarray_shape; } if (fields != Py_None) { Py_XDECREF(self->fields); self->fields = fields; Py_INCREF(fields); Py_XDECREF(self->names); self->names = names; if (incref_names) { Py_INCREF(names); } } if (PyTypeNum_ISEXTENDED(self->type_num)) { self->elsize = elsize; self->alignment = alignment; } /* * We use an integer converted to char for backward compatibility with * pickled arrays. Pickled arrays created with previous versions encoded * flags as an int even though it actually was a char in the PyArray_Descr * structure */ dtypeflags = int_dtypeflags; if (dtypeflags != int_dtypeflags) { PyErr_Format(PyExc_ValueError, "incorrect value for flags variable (overflow)"); return NULL; } else { self->flags = dtypeflags; } if (version < 3) { self->flags = _descr_find_object(self); } /* * We have a borrowed reference to metadata so no need * to alter reference count when throwing away Py_None. */ if (metadata == Py_None) { metadata = NULL; } if (PyDataType_ISDATETIME(self) && (metadata != NULL)) { PyObject *old_metadata, *errmsg; PyArray_DatetimeMetaData temp_dt_data; if ((! PyTuple_Check(metadata)) || (PyTuple_Size(metadata) != 2)) { errmsg = PyUString_FromString("Invalid datetime dtype (metadata, c_metadata): "); PyUString_ConcatAndDel(&errmsg, PyObject_Repr(metadata)); PyErr_SetObject(PyExc_ValueError, errmsg); Py_DECREF(errmsg); return NULL; } if (convert_datetime_metadata_tuple_to_datetime_metadata( PyTuple_GET_ITEM(metadata, 1), &temp_dt_data) < 0) { return NULL; } old_metadata = self->metadata; self->metadata = PyTuple_GET_ITEM(metadata, 0); memcpy((char *) &((PyArray_DatetimeDTypeMetaData *)self->c_metadata)->meta, (char *) &temp_dt_data, sizeof(PyArray_DatetimeMetaData)); Py_XINCREF(self->metadata); Py_XDECREF(old_metadata); } else { PyObject *old_metadata = self->metadata; self->metadata = metadata; Py_XINCREF(self->metadata); Py_XDECREF(old_metadata); } Py_INCREF(Py_None); return Py_None; } /*NUMPY_API * * Get type-descriptor from an object forcing alignment if possible * None goes to DEFAULT type. * * any object with the .fields attribute and/or .itemsize attribute (if the *.fields attribute does not give the total size -- i.e. a partial record * naming). If itemsize is given it must be >= size computed from fields * * The .fields attribute must return a convertible dictionary if present. * Result inherits from NPY_VOID. */ NPY_NO_EXPORT int PyArray_DescrAlignConverter(PyObject *obj, PyArray_Descr **at) { if (PyDict_Check(obj)) { *at = _convert_from_dict(obj, 1); } else if (PyBytes_Check(obj)) { *at = _convert_from_commastring(obj, 1); } else if (PyUnicode_Check(obj)) { PyObject *tmp; tmp = PyUnicode_AsASCIIString(obj); *at = _convert_from_commastring(tmp, 1); Py_DECREF(tmp); } else if (PyList_Check(obj)) { *at = _convert_from_array_descr(obj, 1); } else { return PyArray_DescrConverter(obj, at); } if (*at == NULL) { if (!PyErr_Occurred()) { PyErr_SetString(PyExc_ValueError, "data-type-descriptor not understood"); } return NPY_FAIL; } return NPY_SUCCEED; } /*NUMPY_API * * Get type-descriptor from an object forcing alignment if possible * None goes to NULL. */ NPY_NO_EXPORT int PyArray_DescrAlignConverter2(PyObject *obj, PyArray_Descr **at) { if (PyDict_Check(obj)) { *at = _convert_from_dict(obj, 1); } else if (PyBytes_Check(obj)) { *at = _convert_from_commastring(obj, 1); } else if (PyUnicode_Check(obj)) { PyObject *tmp; tmp = PyUnicode_AsASCIIString(obj); *at = _convert_from_commastring(tmp, 1); Py_DECREF(tmp); } else if (PyList_Check(obj)) { *at = _convert_from_array_descr(obj, 1); } else { return PyArray_DescrConverter2(obj, at); } if (*at == NULL) { if (!PyErr_Occurred()) { PyErr_SetString(PyExc_ValueError, "data-type-descriptor not understood"); } return NPY_FAIL; } return NPY_SUCCEED; } /*NUMPY_API * * returns a copy of the PyArray_Descr structure with the byteorder * altered: * no arguments: The byteorder is swapped (in all subfields as well) * single argument: The byteorder is forced to the given state * (in all subfields as well) * * Valid states: ('big', '>') or ('little' or '<') * ('native', or '=') * * If a descr structure with | is encountered it's own * byte-order is not changed but any fields are: * * * Deep bytorder change of a data-type descriptor * *** Leaves reference count of self unchanged --- does not DECREF self *** */ NPY_NO_EXPORT PyArray_Descr * PyArray_DescrNewByteorder(PyArray_Descr *self, char newendian) { PyArray_Descr *new; char endian; new = PyArray_DescrNew(self); endian = new->byteorder; if (endian != NPY_IGNORE) { if (newendian == NPY_SWAP) { /* swap byteorder */ if PyArray_ISNBO(endian) { endian = NPY_OPPBYTE; } else { endian = NPY_NATBYTE; } new->byteorder = endian; } else if (newendian != NPY_IGNORE) { new->byteorder = newendian; } } if (PyDataType_HASFIELDS(new)) { PyObject *newfields; PyObject *key, *value; PyObject *newvalue; PyObject *old; PyArray_Descr *newdescr; Py_ssize_t pos = 0; int len, i; newfields = PyDict_New(); /* make new dictionary with replaced PyArray_Descr Objects */ while (PyDict_Next(self->fields, &pos, &key, &value)) { if NPY_TITLE_KEY(key, value) { continue; } if (!PyUString_Check(key) || !PyTuple_Check(value) || ((len=PyTuple_GET_SIZE(value)) < 2)) { continue; } old = PyTuple_GET_ITEM(value, 0); if (!PyArray_DescrCheck(old)) { continue; } newdescr = PyArray_DescrNewByteorder( (PyArray_Descr *)old, newendian); if (newdescr == NULL) { Py_DECREF(newfields); Py_DECREF(new); return NULL; } newvalue = PyTuple_New(len); PyTuple_SET_ITEM(newvalue, 0, (PyObject *)newdescr); for (i = 1; i < len; i++) { old = PyTuple_GET_ITEM(value, i); Py_INCREF(old); PyTuple_SET_ITEM(newvalue, i, old); } PyDict_SetItem(newfields, key, newvalue); Py_DECREF(newvalue); } Py_DECREF(new->fields); new->fields = newfields; } if (PyDataType_HASSUBARRAY(new)) { Py_DECREF(new->subarray->base); new->subarray->base = PyArray_DescrNewByteorder( self->subarray->base, newendian); } return new; } static PyObject * arraydescr_newbyteorder(PyArray_Descr *self, PyObject *args) { char endian=NPY_SWAP; if (!PyArg_ParseTuple(args, "|O&", PyArray_ByteorderConverter, &endian)) { return NULL; } return (PyObject *)PyArray_DescrNewByteorder(self, endian); } static PyMethodDef arraydescr_methods[] = { /* for pickling */ {"__reduce__", (PyCFunction)arraydescr_reduce, METH_VARARGS, NULL}, {"__setstate__", (PyCFunction)arraydescr_setstate, METH_VARARGS, NULL}, {"newbyteorder", (PyCFunction)arraydescr_newbyteorder, METH_VARARGS, NULL}, {NULL, NULL, 0, NULL} /* sentinel */ }; /* * Checks whether the structured data type in 'dtype' * has a simple layout, where all the fields are in order, * and follow each other with no alignment padding. * * When this returns true, the dtype can be reconstructed * from a list of the field names and dtypes with no additional * dtype parameters. * * Returns 1 if it has a simple layout, 0 otherwise. */ static int is_dtype_struct_simple_unaligned_layout(PyArray_Descr *dtype) { PyObject *names, *fields, *key, *tup, *title; Py_ssize_t i, names_size; PyArray_Descr *fld_dtype; int fld_offset; npy_intp total_offset; /* Get some properties from the dtype */ names = dtype->names; names_size = PyTuple_GET_SIZE(names); fields = dtype->fields; /* Start at offset zero */ total_offset = 0; for (i = 0; i < names_size; ++i) { key = PyTuple_GET_ITEM(names, i); if (key == NULL) { return 0; } tup = PyDict_GetItem(fields, key); if (tup == NULL) { return 0; } if (!PyArg_ParseTuple(tup, "Oi|O", &fld_dtype, &fld_offset, &title)) { PyErr_Clear(); return 0; } /* If this field doesn't follow the pattern, not a simple layout */ if (total_offset != fld_offset) { return 0; } /* Get the next offset */ total_offset += fld_dtype->elsize; } /* * If the itemsize doesn't match the final offset, it's * not a simple layout. */ if (total_offset != dtype->elsize) { return 0; } /* It's a simple layout, since all the above tests passed */ return 1; } /* * Returns a string representation of a structured array, * in a list format. */ static PyObject * arraydescr_struct_list_str(PyArray_Descr *dtype) { PyObject *names, *key, *fields, *ret, *tmp, *tup, *title; Py_ssize_t i, names_size; PyArray_Descr *fld_dtype; int fld_offset; names = dtype->names; names_size = PyTuple_GET_SIZE(names); fields = dtype->fields; /* Build up a string to make the list */ /* Go through all the names */ ret = PyUString_FromString("["); for (i = 0; i < names_size; ++i) { key = PyTuple_GET_ITEM(names, i); tup = PyDict_GetItem(fields, key); if (tup == NULL) { return 0; } title = NULL; if (!PyArg_ParseTuple(tup, "Oi|O", &fld_dtype, &fld_offset, &title)) { PyErr_Clear(); return 0; } PyUString_ConcatAndDel(&ret, PyUString_FromString("(")); /* Check for whether to do titles as well */ if (title != NULL && title != Py_None) { PyUString_ConcatAndDel(&ret, PyUString_FromString("(")); PyUString_ConcatAndDel(&ret, PyObject_Repr(title)); PyUString_ConcatAndDel(&ret, PyUString_FromString(", ")); PyUString_ConcatAndDel(&ret, PyObject_Repr(key)); PyUString_ConcatAndDel(&ret, PyUString_FromString("), ")); } else { PyUString_ConcatAndDel(&ret, PyObject_Repr(key)); PyUString_ConcatAndDel(&ret, PyUString_FromString(", ")); } /* Special case subarray handling here */ if (PyDataType_HASSUBARRAY(fld_dtype)) { tmp = arraydescr_construction_repr( fld_dtype->subarray->base, 0, 1); PyUString_ConcatAndDel(&ret, tmp); PyUString_ConcatAndDel(&ret, PyUString_FromString(", ")); PyUString_ConcatAndDel(&ret, PyObject_Str(fld_dtype->subarray->shape)); } else { tmp = arraydescr_construction_repr(fld_dtype, 0, 1); PyUString_ConcatAndDel(&ret, tmp); } PyUString_ConcatAndDel(&ret, PyUString_FromString(")")); if (i != names_size - 1) { PyUString_ConcatAndDel(&ret, PyUString_FromString(", ")); } } PyUString_ConcatAndDel(&ret, PyUString_FromString("]")); return ret; } /* * Returns a string representation of a structured array, * in a dict format. */ static PyObject * arraydescr_struct_dict_str(PyArray_Descr *dtype, int includealignedflag) { PyObject *names, *key, *fields, *ret, *tmp, *tup, *title; Py_ssize_t i, names_size; PyArray_Descr *fld_dtype; int fld_offset, has_titles; names = dtype->names; names_size = PyTuple_GET_SIZE(names); fields = dtype->fields; has_titles = 0; /* Build up a string to make the dictionary */ /* First, the names */ ret = PyUString_FromString("{'names':["); for (i = 0; i < names_size; ++i) { key = PyTuple_GET_ITEM(names, i); PyUString_ConcatAndDel(&ret, PyObject_Repr(key)); if (i != names_size - 1) { PyUString_ConcatAndDel(&ret, PyUString_FromString(",")); } } /* Second, the formats */ PyUString_ConcatAndDel(&ret, PyUString_FromString("], 'formats':[")); for (i = 0; i < names_size; ++i) { key = PyTuple_GET_ITEM(names, i); tup = PyDict_GetItem(fields, key); if (tup == NULL) { return 0; } title = NULL; if (!PyArg_ParseTuple(tup, "Oi|O", &fld_dtype, &fld_offset, &title)) { PyErr_Clear(); return 0; } /* Check for whether to do titles as well */ if (title != NULL && title != Py_None) { has_titles = 1; } tmp = arraydescr_construction_repr(fld_dtype, 0, 1); PyUString_ConcatAndDel(&ret, tmp); if (i != names_size - 1) { PyUString_ConcatAndDel(&ret, PyUString_FromString(",")); } } /* Third, the offsets */ PyUString_ConcatAndDel(&ret, PyUString_FromString("], 'offsets':[")); for (i = 0; i < names_size; ++i) { key = PyTuple_GET_ITEM(names, i); tup = PyDict_GetItem(fields, key); if (tup == NULL) { return 0; } if (!PyArg_ParseTuple(tup, "Oi|O", &fld_dtype, &fld_offset, &title)) { PyErr_Clear(); return 0; } PyUString_ConcatAndDel(&ret, PyUString_FromFormat("%d", fld_offset)); if (i != names_size - 1) { PyUString_ConcatAndDel(&ret, PyUString_FromString(",")); } } /* Fourth, the titles */ if (has_titles) { PyUString_ConcatAndDel(&ret, PyUString_FromString("], 'titles':[")); for (i = 0; i < names_size; ++i) { key = PyTuple_GET_ITEM(names, i); tup = PyDict_GetItem(fields, key); if (tup == NULL) { return 0; } title = Py_None; if (!PyArg_ParseTuple(tup, "Oi|O", &fld_dtype, &fld_offset, &title)) { PyErr_Clear(); return 0; } PyUString_ConcatAndDel(&ret, PyObject_Repr(title)); if (i != names_size - 1) { PyUString_ConcatAndDel(&ret, PyUString_FromString(",")); } } } if (includealignedflag && (dtype->flags&NPY_ALIGNED_STRUCT)) { /* Finally, the itemsize/itemsize and aligned flag */ PyUString_ConcatAndDel(&ret, PyUString_FromFormat("], 'itemsize':%d, 'aligned':True}", (int)dtype->elsize)); } else { /* Finally, the itemsize/itemsize*/ PyUString_ConcatAndDel(&ret, PyUString_FromFormat("], 'itemsize':%d}", (int)dtype->elsize)); } return ret; } /* Produces a string representation for a structured dtype */ static PyObject * arraydescr_struct_str(PyArray_Descr *dtype, int includealignflag) { /* * The list str representation can't include the 'align=' flag, * so if it is requested and the struct has the aligned flag set, * we must use the dict str instead. */ if (!(includealignflag && (dtype->flags&NPY_ALIGNED_STRUCT)) && is_dtype_struct_simple_unaligned_layout(dtype)) { return arraydescr_struct_list_str(dtype); } else { return arraydescr_struct_dict_str(dtype, includealignflag); } } /* Produces a string representation for a subarray dtype */ static PyObject * arraydescr_subarray_str(PyArray_Descr *dtype) { PyObject *p, *ret; ret = PyUString_FromString("("); p = arraydescr_construction_repr(dtype->subarray->base, 0, 1); PyUString_ConcatAndDel(&ret, p); PyUString_ConcatAndDel(&ret, PyUString_FromString(", ")); PyUString_ConcatAndDel(&ret, PyObject_Str(dtype->subarray->shape)); PyUString_ConcatAndDel(&ret, PyUString_FromString(")")); return ret; } static PyObject * arraydescr_str(PyArray_Descr *dtype) { PyObject *sub; if (PyDataType_HASFIELDS(dtype)) { sub = arraydescr_struct_str(dtype, 1); } else if (PyDataType_HASSUBARRAY(dtype)) { sub = arraydescr_subarray_str(dtype); } else if (PyDataType_ISFLEXIBLE(dtype) || !PyArray_ISNBO(dtype->byteorder)) { sub = arraydescr_protocol_typestr_get(dtype); } else { sub = arraydescr_typename_get(dtype); } return sub; } /* * The dtype repr function specifically for structured arrays. */ static PyObject * arraydescr_struct_repr(PyArray_Descr *dtype) { PyObject *sub, *s; s = PyUString_FromString("dtype("); sub = arraydescr_struct_str(dtype, 0); if (sub == NULL) { return NULL; } PyUString_ConcatAndDel(&s, sub); /* If it's an aligned structure, add the align=True parameter */ if (dtype->flags&NPY_ALIGNED_STRUCT) { PyUString_ConcatAndDel(&s, PyUString_FromString(", align=True")); } PyUString_ConcatAndDel(&s, PyUString_FromString(")")); return s; } /* See descriptor.h for documentation */ NPY_NO_EXPORT PyObject * arraydescr_construction_repr(PyArray_Descr *dtype, int includealignflag, int shortrepr) { PyObject *ret; PyArray_DatetimeMetaData *meta; char byteorder[2]; if (PyDataType_HASFIELDS(dtype)) { return arraydescr_struct_str(dtype, includealignflag); } else if (PyDataType_HASSUBARRAY(dtype)) { return arraydescr_subarray_str(dtype); } /* Normalize byteorder to '<' or '>' */ switch (dtype->byteorder) { case NPY_NATIVE: byteorder[0] = NPY_NATBYTE; break; case NPY_SWAP: byteorder[0] = NPY_OPPBYTE; break; case NPY_IGNORE: byteorder[0] = '\0'; break; default: byteorder[0] = dtype->byteorder; break; } byteorder[1] = '\0'; /* Handle booleans, numbers, and custom dtypes */ if (dtype->type_num == NPY_BOOL) { if (shortrepr) { return PyUString_FromString("'?'"); } else { return PyUString_FromString("'bool'"); } } else if (PyTypeNum_ISNUMBER(dtype->type_num)) { /* Short repr with endianness, like 'byteorder != NPY_NATIVE && dtype->byteorder != NPY_IGNORE)) { return PyUString_FromFormat("'%s%c%d'", byteorder, (int)dtype->kind, dtype->elsize); } /* Longer repr, like 'float64' */ else { char *kindstr; switch (dtype->kind) { case 'u': kindstr = "uint"; break; case 'i': kindstr = "int"; break; case 'f': kindstr = "float"; break; case 'c': kindstr = "complex"; break; default: PyErr_Format(PyExc_RuntimeError, "internal dtype repr error, unknown kind '%c'", (int)dtype->kind); return NULL; } return PyUString_FromFormat("'%s%d'", kindstr, 8*dtype->elsize); } } else if (PyTypeNum_ISUSERDEF(dtype->type_num)) { char *s = strrchr(dtype->typeobj->tp_name, '.'); if (s == NULL) { return PyUString_FromString(dtype->typeobj->tp_name); } else { return PyUString_FromStringAndSize(s + 1, strlen(s) - 1); } } /* All the rest which don't fit in the same pattern */ switch (dtype->type_num) { /* * The object reference may be different sizes on different * platforms, so it should never include the itemsize here. */ case NPY_OBJECT: return PyUString_FromString("'O'"); case NPY_STRING: if (dtype->elsize == 0) { return PyUString_FromString("'S'"); } else { return PyUString_FromFormat("'S%d'", (int)dtype->elsize); } case NPY_UNICODE: if (dtype->elsize == 0) { return PyUString_FromFormat("'%sU'", byteorder); } else { return PyUString_FromFormat("'%sU%d'", byteorder, (int)dtype->elsize / 4); } case NPY_VOID: if (dtype->elsize == 0) { return PyUString_FromString("'V'"); } else { return PyUString_FromFormat("'V%d'", (int)dtype->elsize); } case NPY_DATETIME: meta = get_datetime_metadata_from_dtype(dtype); if (meta == NULL) { return NULL; } ret = PyUString_FromFormat("'%sM8", byteorder); ret = append_metastr_to_string(meta, 0, ret); PyUString_ConcatAndDel(&ret, PyUString_FromString("'")); return ret; case NPY_TIMEDELTA: meta = get_datetime_metadata_from_dtype(dtype); if (meta == NULL) { return NULL; } ret = PyUString_FromFormat("'%sm8", byteorder); ret = append_metastr_to_string(meta, 0, ret); PyUString_ConcatAndDel(&ret, PyUString_FromString("'")); return ret; default: PyErr_SetString(PyExc_RuntimeError, "Internal error: NumPy dtype " "unrecognized type number"); return NULL; } } /* * The general dtype repr function. */ static PyObject * arraydescr_repr(PyArray_Descr *dtype) { PyObject *ret; if (PyDataType_HASFIELDS(dtype)) { return arraydescr_struct_repr(dtype); } else { ret = PyUString_FromString("dtype("); PyUString_ConcatAndDel(&ret, arraydescr_construction_repr(dtype, 1, 0)); PyUString_ConcatAndDel(&ret, PyUString_FromString(")")); return ret; } } static PyObject * arraydescr_richcompare(PyArray_Descr *self, PyObject *other, int cmp_op) { PyArray_Descr *new = NULL; PyObject *result = Py_NotImplemented; if (!PyArray_DescrCheck(other)) { if (PyArray_DescrConverter(other, &new) == NPY_FAIL) { return NULL; } } else { new = (PyArray_Descr *)other; Py_INCREF(new); } switch (cmp_op) { case Py_LT: if (!PyArray_EquivTypes(self, new) && PyArray_CanCastTo(self, new)) { result = Py_True; } else { result = Py_False; } break; case Py_LE: if (PyArray_CanCastTo(self, new)) { result = Py_True; } else { result = Py_False; } break; case Py_EQ: if (PyArray_EquivTypes(self, new)) { result = Py_True; } else { result = Py_False; } break; case Py_NE: if (PyArray_EquivTypes(self, new)) result = Py_False; else result = Py_True; break; case Py_GT: if (!PyArray_EquivTypes(self, new) && PyArray_CanCastTo(new, self)) { result = Py_True; } else { result = Py_False; } break; case Py_GE: if (PyArray_CanCastTo(new, self)) { result = Py_True; } else { result = Py_False; } break; default: result = Py_NotImplemented; } Py_XDECREF(new); Py_INCREF(result); return result; } /************************************************************************* **************** Implement Mapping Protocol *************************** *************************************************************************/ static Py_ssize_t descr_length(PyObject *self0) { PyArray_Descr *self = (PyArray_Descr *)self0; if (PyDataType_HASFIELDS(self)) { return PyTuple_GET_SIZE(self->names); } else { return 0; } } static PyObject * descr_repeat(PyObject *self, Py_ssize_t length) { PyObject *tup; PyArray_Descr *new; if (length < 0) { return PyErr_Format(PyExc_ValueError, "Array length must be >= 0, not %"NPY_INTP_FMT, (npy_intp)length); } tup = Py_BuildValue("O" NPY_SSIZE_T_PYFMT, self, length); if (tup == NULL) { return NULL; } PyArray_DescrConverter(tup, &new); Py_DECREF(tup); return (PyObject *)new; } static PyObject * descr_subscript(PyArray_Descr *self, PyObject *op) { PyObject *retval; if (!PyDataType_HASFIELDS(self)) { PyObject *astr = arraydescr_str(self); #if defined(NPY_PY3K) PyObject *bstr = PyUnicode_AsUnicodeEscapeString(astr); Py_DECREF(astr); astr = bstr; #endif PyErr_Format(PyExc_KeyError, "There are no fields in dtype %s.", PyBytes_AsString(astr)); Py_DECREF(astr); return NULL; } #if defined(NPY_PY3K) if (PyUString_Check(op)) { #else if (PyUString_Check(op) || PyUnicode_Check(op)) { #endif PyObject *obj = PyDict_GetItem(self->fields, op); PyObject *descr; PyObject *s; if (obj == NULL) { if (PyUnicode_Check(op)) { s = PyUnicode_AsUnicodeEscapeString(op); } else { s = op; } PyErr_Format(PyExc_KeyError, "Field named \'%s\' not found.", PyBytes_AsString(s)); if (s != op) { Py_DECREF(s); } return NULL; } descr = PyTuple_GET_ITEM(obj, 0); Py_INCREF(descr); retval = descr; } else if (PyInt_Check(op)) { PyObject *name; int size = PyTuple_GET_SIZE(self->names); int value = PyArray_PyIntAsInt(op); int orig_value = value; if (PyErr_Occurred()) { return NULL; } if (value < 0) { value += size; } if (value < 0 || value >= size) { PyErr_Format(PyExc_IndexError, "Field index %d out of range.", orig_value); return NULL; } name = PyTuple_GET_ITEM(self->names, value); retval = descr_subscript(self, name); } else { PyErr_SetString(PyExc_ValueError, "Field key must be an integer, string, or unicode."); return NULL; } return retval; } static PySequenceMethods descr_as_sequence = { descr_length, (binaryfunc)NULL, descr_repeat, NULL, NULL, NULL, /* sq_ass_item */ NULL, /* ssizessizeobjargproc sq_ass_slice */ 0, /* sq_contains */ 0, /* sq_inplace_concat */ 0, /* sq_inplace_repeat */ }; static PyMappingMethods descr_as_mapping = { descr_length, /* mp_length*/ (binaryfunc)descr_subscript, /* mp_subscript*/ (objobjargproc)NULL, /* mp_ass_subscript*/ }; /****************** End of Mapping Protocol ******************************/ NPY_NO_EXPORT PyTypeObject PyArrayDescr_Type = { #if defined(NPY_PY3K) PyVarObject_HEAD_INIT(NULL, 0) #else PyObject_HEAD_INIT(NULL) 0, /* ob_size */ #endif "numpy.dtype", /* tp_name */ sizeof(PyArray_Descr), /* tp_basicsize */ 0, /* tp_itemsize */ /* methods */ (destructor)arraydescr_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ #if defined(NPY_PY3K) (void *)0, /* tp_reserved */ #else 0, /* tp_compare */ #endif (reprfunc)arraydescr_repr, /* tp_repr */ 0, /* tp_as_number */ &descr_as_sequence, /* tp_as_sequence */ &descr_as_mapping, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ (reprfunc)arraydescr_str, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT, /* tp_flags */ 0, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ (richcmpfunc)arraydescr_richcompare, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ arraydescr_methods, /* tp_methods */ arraydescr_members, /* tp_members */ arraydescr_getsets, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ arraydescr_new, /* 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 */ 0, /* tp_version_tag */ }; numpy-1.8.2/numpy/core/src/multiarray/shape.h0000664000175100017510000000176512370216242022365 0ustar vagrantvagrant00000000000000#ifndef _NPY_ARRAY_SHAPE_H_ #define _NPY_ARRAY_SHAPE_H_ /* * Builds a string representation of the shape given in 'vals'. * A negative value in 'vals' gets interpreted as newaxis. */ NPY_NO_EXPORT PyObject * build_shape_string(npy_intp n, npy_intp *vals); /* * Creates a sorted stride perm matching the KEEPORDER behavior * of the NpyIter object. Because this operates based on multiple * input strides, the 'stride' member of the npy_stride_sort_item * would be useless and we simply argsort a list of indices instead. * * The caller should have already validated that 'ndim' matches for * every array in the arrays list. */ NPY_NO_EXPORT void PyArray_CreateMultiSortedStridePerm(int narrays, PyArrayObject **arrays, int ndim, int *out_strideperm); /* * Just like PyArray_Squeeze, but allows the caller to select * a subset of the size-one dimensions to squeeze out. */ NPY_NO_EXPORT PyObject * PyArray_SqueezeSelected(PyArrayObject *self, npy_bool *axis_flags); #endif numpy-1.8.2/numpy/core/src/multiarray/multiarraymodule.h0000664000175100017510000000007612370216243024657 0ustar vagrantvagrant00000000000000#ifndef _NPY_MULTIARRAY_H_ #define _NPY_MULTIARRAY_H_ #endif numpy-1.8.2/numpy/core/src/multiarray/usertypes.c0000664000175100017510000001610712370216242023317 0ustar vagrantvagrant00000000000000/* Provide multidimensional arrays as a basic object type in python. Based on Original Numeric implementation Copyright (c) 1995, 1996, 1997 Jim Hugunin, hugunin@mit.edu with contributions from many Numeric Python developers 1995-2004 Heavily modified in 2005 with inspiration from Numarray by Travis Oliphant, oliphant@ee.byu.edu Brigham Young Univeristy maintainer email: oliphant.travis@ieee.org Numarray design (which provided guidance) by Space Science Telescope Institute (J. Todd Miller, Perry Greenfield, Rick White) */ #define PY_SSIZE_T_CLEAN #include #include "structmember.h" /*#include */ #define NPY_NO_DEPRECATED_API NPY_API_VERSION #define _MULTIARRAYMODULE #include "numpy/arrayobject.h" #include "numpy/arrayscalars.h" #include "npy_config.h" #include "common.h" #include "npy_pycompat.h" #include "usertypes.h" NPY_NO_EXPORT PyArray_Descr **userdescrs=NULL; static int * _append_new(int *types, int insert) { int n = 0; int *newtypes; while (types[n] != NPY_NOTYPE) { n++; } newtypes = (int *)realloc(types, (n + 2)*sizeof(int)); newtypes[n] = insert; newtypes[n + 1] = NPY_NOTYPE; return newtypes; } static npy_bool _default_nonzero(void *ip, void *arr) { int elsize = PyArray_ITEMSIZE(arr); char *ptr = ip; while (elsize--) { if (*ptr++ != 0) { return NPY_TRUE; } } return NPY_FALSE; } static void _default_copyswapn(void *dst, npy_intp dstride, void *src, npy_intp sstride, npy_intp n, int swap, void *arr) { npy_intp i; PyArray_CopySwapFunc *copyswap; char *dstptr = dst; char *srcptr = src; copyswap = PyArray_DESCR(arr)->f->copyswap; for (i = 0; i < n; i++) { copyswap(dstptr, srcptr, swap, arr); dstptr += dstride; srcptr += sstride; } } /*NUMPY_API Initialize arrfuncs to NULL */ NPY_NO_EXPORT void PyArray_InitArrFuncs(PyArray_ArrFuncs *f) { int i; for(i = 0; i < NPY_NTYPES_ABI_COMPATIBLE; i++) { f->cast[i] = NULL; } f->getitem = NULL; f->setitem = NULL; f->copyswapn = NULL; f->copyswap = NULL; f->compare = NULL; f->argmax = NULL; f->argmin = NULL; f->dotfunc = NULL; f->scanfunc = NULL; f->fromstr = NULL; f->nonzero = NULL; f->fill = NULL; f->fillwithscalar = NULL; for(i = 0; i < NPY_NSORTS; i++) { f->sort[i] = NULL; f->argsort[i] = NULL; } f->castdict = NULL; f->scalarkind = NULL; f->cancastscalarkindto = NULL; f->cancastto = NULL; } /* returns typenum to associate with this type >=NPY_USERDEF. needs the userdecrs table and PyArray_NUMUSER variables defined in arraytypes.inc */ /*NUMPY_API Register Data type Does not change the reference count of descr */ NPY_NO_EXPORT int PyArray_RegisterDataType(PyArray_Descr *descr) { PyArray_Descr *descr2; int typenum; int i; PyArray_ArrFuncs *f; /* See if this type is already registered */ for (i = 0; i < NPY_NUMUSERTYPES; i++) { descr2 = userdescrs[i]; if (descr2 == descr) { return descr->type_num; } } typenum = NPY_USERDEF + NPY_NUMUSERTYPES; descr->type_num = typenum; if (descr->elsize == 0) { PyErr_SetString(PyExc_ValueError, "cannot register a" \ "flexible data-type"); return -1; } f = descr->f; if (f->nonzero == NULL) { f->nonzero = _default_nonzero; } if (f->copyswapn == NULL) { f->copyswapn = _default_copyswapn; } if (f->copyswap == NULL || f->getitem == NULL || f->setitem == NULL) { PyErr_SetString(PyExc_ValueError, "a required array function" \ " is missing."); return -1; } if (descr->typeobj == NULL) { PyErr_SetString(PyExc_ValueError, "missing typeobject"); return -1; } userdescrs = realloc(userdescrs, (NPY_NUMUSERTYPES+1)*sizeof(void *)); if (userdescrs == NULL) { PyErr_SetString(PyExc_MemoryError, "RegisterDataType"); return -1; } userdescrs[NPY_NUMUSERTYPES++] = descr; return typenum; } /*NUMPY_API Register Casting Function Replaces any function currently stored. */ NPY_NO_EXPORT int PyArray_RegisterCastFunc(PyArray_Descr *descr, int totype, PyArray_VectorUnaryFunc *castfunc) { PyObject *cobj, *key; int ret; if (totype < NPY_NTYPES_ABI_COMPATIBLE) { descr->f->cast[totype] = castfunc; return 0; } if (totype >= NPY_NTYPES && !PyTypeNum_ISUSERDEF(totype)) { PyErr_SetString(PyExc_TypeError, "invalid type number."); return -1; } if (descr->f->castdict == NULL) { descr->f->castdict = PyDict_New(); if (descr->f->castdict == NULL) { return -1; } } key = PyInt_FromLong(totype); if (PyErr_Occurred()) { return -1; } cobj = NpyCapsule_FromVoidPtr((void *)castfunc, NULL); if (cobj == NULL) { Py_DECREF(key); return -1; } ret = PyDict_SetItem(descr->f->castdict, key, cobj); Py_DECREF(key); Py_DECREF(cobj); return ret; } /*NUMPY_API * Register a type number indicating that a descriptor can be cast * to it safely */ NPY_NO_EXPORT int PyArray_RegisterCanCast(PyArray_Descr *descr, int totype, NPY_SCALARKIND scalar) { /* * If we were to allow this, the casting lookup table for * built-in types needs to be modified, as cancastto is * not checked for them. */ if (!PyTypeNum_ISUSERDEF(descr->type_num) && !PyTypeNum_ISUSERDEF(totype)) { PyErr_SetString(PyExc_ValueError, "At least one of the types provided to" "RegisterCanCast must be user-defined."); return -1; } if (scalar == NPY_NOSCALAR) { /* * register with cancastto * These lists won't be freed once created * -- they become part of the data-type */ if (descr->f->cancastto == NULL) { descr->f->cancastto = (int *)malloc(1*sizeof(int)); descr->f->cancastto[0] = NPY_NOTYPE; } descr->f->cancastto = _append_new(descr->f->cancastto, totype); } else { /* register with cancastscalarkindto */ if (descr->f->cancastscalarkindto == NULL) { int i; descr->f->cancastscalarkindto = (int **)malloc(NPY_NSCALARKINDS* sizeof(int*)); for (i = 0; i < NPY_NSCALARKINDS; i++) { descr->f->cancastscalarkindto[i] = NULL; } } if (descr->f->cancastscalarkindto[scalar] == NULL) { descr->f->cancastscalarkindto[scalar] = (int *)malloc(1*sizeof(int)); descr->f->cancastscalarkindto[scalar][0] = NPY_NOTYPE; } descr->f->cancastscalarkindto[scalar] = _append_new(descr->f->cancastscalarkindto[scalar], totype); } return 0; } numpy-1.8.2/numpy/core/src/multiarray/sequence.h0000664000175100017510000000035012370216242023062 0ustar vagrantvagrant00000000000000#ifndef _NPY_ARRAY_SEQUENCE_H_ #define _NPY_ARRAY_SEQUENCE_H_ #ifdef NPY_ENABLE_SEPARATE_COMPILATION extern NPY_NO_EXPORT PySequenceMethods array_as_sequence; #else NPY_NO_EXPORT PySequenceMethods array_as_sequence; #endif #endif numpy-1.8.2/numpy/core/src/multiarray/hashdescr.h0000664000175100017510000000017312370216242023221 0ustar vagrantvagrant00000000000000#ifndef _NPY_HASHDESCR_H_ #define _NPY_HASHDESCR_H_ NPY_NO_EXPORT npy_hash_t PyArray_DescrHash(PyObject* odescr); #endif numpy-1.8.2/numpy/core/src/multiarray/scalartypes.h0000664000175100017510000000262412370216242023612 0ustar vagrantvagrant00000000000000#ifndef _NPY_SCALARTYPES_H_ #define _NPY_SCALARTYPES_H_ /* Internal look-up tables */ #ifdef NPY_ENABLE_SEPARATE_COMPILATION extern NPY_NO_EXPORT unsigned char _npy_can_cast_safely_table[NPY_NTYPES][NPY_NTYPES]; extern NPY_NO_EXPORT signed char _npy_scalar_kinds_table[NPY_NTYPES]; extern NPY_NO_EXPORT signed char _npy_type_promotion_table[NPY_NTYPES][NPY_NTYPES]; extern NPY_NO_EXPORT signed char _npy_smallest_type_of_kind_table[NPY_NSCALARKINDS]; extern NPY_NO_EXPORT signed char _npy_next_larger_type_table[NPY_NTYPES]; #else NPY_NO_EXPORT unsigned char _npy_can_cast_safely_table[NPY_NTYPES][NPY_NTYPES]; NPY_NO_EXPORT signed char _npy_scalar_kinds_table[NPY_NTYPES]; NPY_NO_EXPORT signed char _npy_type_promotion_table[NPY_NTYPES][NPY_NTYPES]; NPY_NO_EXPORT signed char _npy_smallest_type_of_kind_table[NPY_NSCALARKINDS]; NPY_NO_EXPORT signed char _npy_next_larger_type_table[NPY_NTYPES]; #endif NPY_NO_EXPORT void initialize_casting_tables(void); NPY_NO_EXPORT void initialize_numeric_types(void); NPY_NO_EXPORT void format_longdouble(char *buf, size_t buflen, npy_longdouble val, unsigned int prec); #if PY_VERSION_HEX >= 0x03000000 NPY_NO_EXPORT void gentype_struct_free(PyObject *ptr); #else NPY_NO_EXPORT void gentype_struct_free(void *ptr, void *arg); #endif NPY_NO_EXPORT int _typenum_fromtypeobj(PyObject *type, int user); NPY_NO_EXPORT void * scalar_value(PyObject *scalar, PyArray_Descr *descr); #endif numpy-1.8.2/numpy/core/src/multiarray/arraytypes.c.src0000664000175100017510000034005312371375326024257 0ustar vagrantvagrant00000000000000/* -*- c -*- */ #define PY_SSIZE_T_CLEAN #include "Python.h" #include "structmember.h" #define NPY_NO_DEPRECATED_API NPY_API_VERSION #define _MULTIARRAYMODULE #include "numpy/arrayobject.h" #include "numpy/arrayscalars.h" #include "npy_pycompat.h" #include "numpy/npy_math.h" #include "numpy/halffloat.h" #include "npy_config.h" #include "npy_sort.h" #include "common.h" #include "ctors.h" #include "usertypes.h" #include "_datetime.h" #include "arrayobject.h" #include "numpyos.h" /* ***************************************************************************** ** PYTHON TYPES TO C TYPES ** ***************************************************************************** */ static double MyPyFloat_AsDouble(PyObject *obj) { double ret = 0; PyObject *num; if (obj == Py_None) { return NPY_NAN; } num = PyNumber_Float(obj); if (num == NULL) { return NPY_NAN; } ret = PyFloat_AsDouble(num); Py_DECREF(num); return ret; } static npy_half MyPyFloat_AsHalf(PyObject *obj) { return npy_double_to_half(MyPyFloat_AsDouble(obj)); } static PyObject * MyPyFloat_FromHalf(npy_half h) { return PyFloat_FromDouble(npy_half_to_double(h)); } /**begin repeat * * #Type = Long, LongLong# * #type = npy_long, npy_longlong# */ static @type@ MyPyLong_As@Type@ (PyObject *obj) { @type@ ret; PyObject *num = PyNumber_Long(obj); if (num == NULL) { return -1; } ret = PyLong_As@Type@(num); Py_DECREF(num); return ret; } /**end repeat**/ /**begin repeat * * #Type = Long, LongLong# * #type = npy_ulong, npy_ulonglong# */ static @type@ MyPyLong_AsUnsigned@Type@ (PyObject *obj) { @type@ ret; PyObject *num = PyNumber_Long(obj); if (num == NULL) { return -1; } ret = PyLong_AsUnsigned@Type@(num); if (PyErr_Occurred()) { PyErr_Clear(); ret = PyLong_As@Type@(num); } Py_DECREF(num); return ret; } /**end repeat**/ /* ***************************************************************************** ** GETITEM AND SETITEM ** ***************************************************************************** */ /**begin repeat * * #TYPE = BOOL, BYTE, UBYTE, SHORT, USHORT, INT, LONG, UINT, ULONG, * LONGLONG, ULONGLONG, HALF, FLOAT, DOUBLE# * #func1 = PyBool_FromLong, PyInt_FromLong*6, PyLong_FromUnsignedLong*2, * PyLong_FromLongLong, PyLong_FromUnsignedLongLong, * MyPyFloat_FromHalf, PyFloat_FromDouble*2# * #func2 = PyObject_IsTrue, MyPyLong_AsLong*6, MyPyLong_AsUnsignedLong*2, * MyPyLong_AsLongLong, MyPyLong_AsUnsignedLongLong, * MyPyFloat_AsHalf, MyPyFloat_AsDouble*2# * #type = npy_bool, * npy_byte, npy_ubyte, npy_short, npy_ushort, npy_int, * npy_long, npy_uint, npy_ulong, npy_longlong, npy_ulonglong, * npy_half, npy_float, npy_double# * #type1 = long*7, npy_ulong*2, npy_longlong, npy_ulonglong, * npy_half, npy_float, npy_double# * #kind = Bool, Byte, UByte, Short, UShort, Int, Long, UInt, ULong, * LongLong, ULongLong, Half, Float, Double# */ static PyObject * @TYPE@_getitem(char *ip, PyArrayObject *ap) { @type@ t1; if ((ap == NULL) || PyArray_ISBEHAVED_RO(ap)) { t1 = *((@type@ *)ip); return @func1@((@type1@)t1); } else { PyArray_DESCR(ap)->f->copyswap(&t1, ip, !PyArray_ISNOTSWAPPED(ap), ap); return @func1@((@type1@)t1); } } static int @TYPE@_setitem(PyObject *op, char *ov, PyArrayObject *ap) { @type@ temp; /* ensures alignment */ if (PyArray_IsScalar(op, @kind@)) { temp = ((Py@kind@ScalarObject *)op)->obval; } else { temp = (@type@)@func2@(op); } if (PyErr_Occurred()) { if (PySequence_Check(op) && !PyString_Check(op) && !PyUnicode_Check(op)) { PyErr_Clear(); PyErr_SetString(PyExc_ValueError, "setting an array element with a sequence."); } return -1; } if (ap == NULL || PyArray_ISBEHAVED(ap)) *((@type@ *)ov)=temp; else { PyArray_DESCR(ap)->f->copyswap(ov, &temp, !PyArray_ISNOTSWAPPED(ap), ap); } return 0; } /**end repeat**/ /**begin repeat * * #TYPE = CFLOAT, CDOUBLE# * #type = npy_float, npy_double# */ static PyObject * @TYPE@_getitem(char *ip, PyArrayObject *ap) { @type@ t1, t2; if ((ap == NULL) || PyArray_ISBEHAVED_RO(ap)) { return PyComplex_FromDoubles((double)((@type@ *)ip)[0], (double)((@type@ *)ip)[1]); } else { int size = sizeof(@type@); npy_bool swap = !PyArray_ISNOTSWAPPED(ap); copy_and_swap(&t1, ip, size, 1, 0, swap); copy_and_swap(&t2, ip + size, size, 1, 0, swap); return PyComplex_FromDoubles((double)t1, (double)t2); } } /**end repeat**/ /**begin repeat * * #NAME = CFLOAT, CDOUBLE, CLONGDOUBLE# * #type = npy_cfloat, npy_cdouble, npy_clongdouble# * #ftype = npy_float, npy_double, npy_longdouble# * #kind = CFloat, CDouble, CLongDouble# */ static int @NAME@_setitem(PyObject *op, char *ov, PyArrayObject *ap) { Py_complex oop; PyObject *op2; @type@ temp; int rsize; if (PyArray_IsScalar(op, @kind@)){ temp = ((Py@kind@ScalarObject *)op)->obval; } else { if (PyArray_Check(op) && (PyArray_NDIM((PyArrayObject *)op) == 0)) { op2 = PyArray_DESCR((PyArrayObject *)op)->f->getitem( PyArray_BYTES((PyArrayObject *)op), (PyArrayObject *)op); } else { op2 = op; Py_INCREF(op); } if (op2 == Py_None) { oop.real = NPY_NAN; oop.imag = NPY_NAN; } else { oop = PyComplex_AsCComplex (op2); } Py_DECREF(op2); if (PyErr_Occurred()) { return -1; } temp.real = (@ftype@) oop.real; temp.imag = (@ftype@) oop.imag; } memcpy(ov, &temp, PyArray_DESCR(ap)->elsize); if (!PyArray_ISNOTSWAPPED(ap)) { byte_swap_vector(ov, 2, sizeof(@ftype@)); } rsize = sizeof(@ftype@); copy_and_swap(ov, &temp, rsize, 2, rsize, !PyArray_ISNOTSWAPPED(ap)); return 0; } /**end repeat**/ /* * These return array scalars which are different than other date-types. */ static PyObject * LONGDOUBLE_getitem(char *ip, PyArrayObject *ap) { return PyArray_Scalar(ip, PyArray_DESCR(ap), NULL); } static int LONGDOUBLE_setitem(PyObject *op, char *ov, PyArrayObject *ap) { /* ensure alignment */ npy_longdouble temp; if (PyArray_IsScalar(op, LongDouble)) { temp = ((PyLongDoubleScalarObject *)op)->obval; } else { temp = (npy_longdouble) MyPyFloat_AsDouble(op); } if (PyErr_Occurred()) { return -1; } if (ap == NULL || PyArray_ISBEHAVED(ap)) { *((npy_longdouble *)ov) = temp; } else { copy_and_swap(ov, &temp, PyArray_DESCR(ap)->elsize, 1, 0, !PyArray_ISNOTSWAPPED(ap)); } return 0; } static PyObject * CLONGDOUBLE_getitem(char *ip, PyArrayObject *ap) { return PyArray_Scalar(ip, PyArray_DESCR(ap), NULL); } /* UNICODE */ static PyObject * UNICODE_getitem(char *ip, PyArrayObject *ap) { Py_ssize_t size = PyArray_ITEMSIZE(ap); int swap = !PyArray_ISNOTSWAPPED(ap); int align = !PyArray_ISALIGNED(ap); return (PyObject *)PyUnicode_FromUCS4(ip, size, swap, align); } static int UNICODE_setitem(PyObject *op, char *ov, PyArrayObject *ap) { PyObject *temp; Py_UNICODE *ptr; int datalen; #ifndef Py_UNICODE_WIDE char *buffer; #endif if (!PyBytes_Check(op) && !PyUnicode_Check(op) && PySequence_Check(op) && PySequence_Size(op) > 0) { PyErr_SetString(PyExc_ValueError, "setting an array element with a sequence"); return -1; } /* Sequence_Size might have returned an error */ if (PyErr_Occurred()) { PyErr_Clear(); } #if defined(NPY_PY3K) if (PyBytes_Check(op)) { /* Try to decode from ASCII */ temp = PyUnicode_FromEncodedObject(op, "ASCII", "strict"); if (temp == NULL) { return -1; } } else if ((temp=PyObject_Str(op)) == NULL) { #else if ((temp=PyObject_Unicode(op)) == NULL) { #endif return -1; } ptr = PyUnicode_AS_UNICODE(temp); if ((ptr == NULL) || (PyErr_Occurred())) { Py_DECREF(temp); return -1; } datalen = PyUnicode_GET_DATA_SIZE(temp); #ifdef Py_UNICODE_WIDE memcpy(ov, ptr, PyArray_MIN(PyArray_DESCR(ap)->elsize, datalen)); #else if (!PyArray_ISALIGNED(ap)) { buffer = PyArray_malloc(PyArray_DESCR(ap)->elsize); if (buffer == NULL) { Py_DECREF(temp); PyErr_NoMemory(); return -1; } } else { buffer = ov; } datalen = PyUCS2Buffer_AsUCS4(ptr, (npy_ucs4 *)buffer, datalen >> 1, PyArray_DESCR(ap)->elsize >> 2); datalen <<= 2; if (!PyArray_ISALIGNED(ap)) { memcpy(ov, buffer, datalen); PyArray_free(buffer); } #endif /* Fill in the rest of the space with 0 */ if (PyArray_DESCR(ap)->elsize > datalen) { memset(ov + datalen, 0, (PyArray_DESCR(ap)->elsize - datalen)); } if (!PyArray_ISNOTSWAPPED(ap)) { byte_swap_vector(ov, PyArray_DESCR(ap)->elsize >> 2, 4); } Py_DECREF(temp); return 0; } /* STRING * * can handle both NULL-terminated and not NULL-terminated cases * will truncate all ending NULLs in returned string. */ static PyObject * STRING_getitem(char *ip, PyArrayObject *ap) { /* Will eliminate NULLs at the end */ char *ptr; int size = PyArray_DESCR(ap)->elsize; ptr = ip + size - 1; while (size > 0 && *ptr-- == '\0') { size--; } return PyBytes_FromStringAndSize(ip,size); } static int STRING_setitem(PyObject *op, char *ov, PyArrayObject *ap) { char *ptr; Py_ssize_t len; PyObject *temp = NULL; /* Handle case of assigning from an array scalar */ if (PyArray_Check(op) && PyArray_NDIM((PyArrayObject *)op) == 0) { temp = PyArray_ToScalar(PyArray_BYTES((PyArrayObject *)op), (PyArrayObject *)op); if (temp == NULL) { return -1; } else { int res = STRING_setitem(temp, ov, ap); Py_DECREF(temp); return res; } } if (!PyBytes_Check(op) && !PyUnicode_Check(op) && PySequence_Check(op) && PySequence_Size(op) != 0) { PyErr_SetString(PyExc_ValueError, "cannot set an array element with a sequence"); return -1; } #if defined(NPY_PY3K) if (PyUnicode_Check(op)) { /* Assume ASCII codec -- function similarly as Python 2 */ temp = PyUnicode_AsASCIIString(op); if (temp == NULL) { return -1; } } else if (PyBytes_Check(op) || PyMemoryView_Check(op)) { temp = PyObject_Bytes(op); if (temp == NULL) { return -1; } } else { /* Emulate similar casting behavior as on Python 2 */ PyObject *str; str = PyObject_Str(op); if (str == NULL) { return -1; } temp = PyUnicode_AsASCIIString(str); Py_DECREF(str); if (temp == NULL) { return -1; } } #else if ((temp = PyObject_Str(op)) == NULL) { return -1; } #endif if (PyBytes_AsStringAndSize(temp, &ptr, &len) == -1) { Py_DECREF(temp); return -1; } memcpy(ov, ptr, PyArray_MIN(PyArray_DESCR(ap)->elsize,len)); /* * If string lenth is smaller than room in array * Then fill the rest of the element size with NULL */ if (PyArray_DESCR(ap)->elsize > len) { memset(ov + len, 0, (PyArray_DESCR(ap)->elsize - len)); } Py_DECREF(temp); return 0; } /* OBJECT */ #define __ALIGNED(obj, sz) ((((size_t) obj) % (sz))==0) static PyObject * OBJECT_getitem(char *ip, PyArrayObject *ap) { PyObject *obj; NPY_COPY_PYOBJECT_PTR(&obj, ip); if (obj == NULL) { Py_INCREF(Py_None); return Py_None; } else { Py_INCREF(obj); return obj; } } static int OBJECT_setitem(PyObject *op, char *ov, PyArrayObject *ap) { PyObject *obj; NPY_COPY_PYOBJECT_PTR(&obj, ov); Py_INCREF(op); Py_XDECREF(obj); NPY_COPY_PYOBJECT_PTR(ov, &op); return PyErr_Occurred() ? -1 : 0; } /* VOID */ static PyObject * VOID_getitem(char *ip, PyArrayObject *ap) { PyArrayObject *u = NULL; PyArray_Descr* descr; int itemsize; descr = PyArray_DESCR(ap); if (PyDataType_HASFIELDS(descr)) { PyObject *key; PyObject *names; int i, n; PyObject *ret; PyObject *tup, *title; PyArray_Descr *new; int offset; int savedflags; /* get the names from the fields dictionary*/ names = descr->names; n = PyTuple_GET_SIZE(names); ret = PyTuple_New(n); savedflags = PyArray_FLAGS(ap); for (i = 0; i < n; i++) { key = PyTuple_GET_ITEM(names, i); tup = PyDict_GetItem(descr->fields, key); if (!PyArg_ParseTuple(tup, "Oi|O", &new, &offset, &title)) { Py_DECREF(ret); ((PyArrayObject_fields *)ap)->descr = descr; return NULL; } /* * TODO: temporarily modifying the array like this * is bad coding style, should be changed. */ ((PyArrayObject_fields *)ap)->descr = new; /* update alignment based on offset */ if ((new->alignment > 1) && ((((npy_intp)(ip+offset)) % new->alignment) != 0)) { PyArray_CLEARFLAGS(ap, NPY_ARRAY_ALIGNED); } else { PyArray_ENABLEFLAGS(ap, NPY_ARRAY_ALIGNED); } PyTuple_SET_ITEM(ret, i, new->f->getitem(ip+offset, ap)); ((PyArrayObject_fields *)ap)->flags = savedflags; } ((PyArrayObject_fields *)ap)->descr = descr; return ret; } if (descr->subarray) { /* return an array of the basic type */ PyArray_Dims shape = {NULL, -1}; PyArrayObject *ret; if (!(PyArray_IntpConverter(descr->subarray->shape, &shape))) { PyDimMem_FREE(shape.ptr); PyErr_SetString(PyExc_ValueError, "invalid shape in fixed-type tuple."); return NULL; } Py_INCREF(descr->subarray->base); ret = (PyArrayObject *)PyArray_NewFromDescr(&PyArray_Type, descr->subarray->base, shape.len, shape.ptr, NULL, ip, PyArray_FLAGS(ap)&(~NPY_ARRAY_F_CONTIGUOUS), NULL); PyDimMem_FREE(shape.ptr); if (!ret) { return NULL; } Py_INCREF(ap); if (PyArray_SetBaseObject(ret, (PyObject *)ap) < 0) { Py_DECREF(ret); return NULL; } PyArray_UpdateFlags((PyArrayObject *)ret, NPY_ARRAY_UPDATE_ALL); return (PyObject *)ret; } if (PyDataType_FLAGCHK(descr, NPY_ITEM_HASOBJECT) || PyDataType_FLAGCHK(descr, NPY_ITEM_IS_POINTER)) { PyErr_SetString(PyExc_ValueError, "tried to get void-array with object members as buffer."); return NULL; } itemsize = PyArray_DESCR(ap)->elsize; #if defined(NPY_PY3K) /* * Return a byte array; there are no plain buffer objects on Py3 */ { npy_intp dims[1], strides[1]; dims[0] = itemsize; strides[0] = 1; descr = PyArray_DescrNewFromType(NPY_BYTE); u = (PyArrayObject *)PyArray_NewFromDescr(&PyArray_Type, descr, 1, dims, strides, ip, PyArray_ISWRITEABLE(ap) ? NPY_ARRAY_WRITEABLE : 0, NULL); Py_INCREF(ap); if (PyArray_SetBaseObject(u, (PyObject *)ap) < 0) { Py_DECREF(u); return NULL; } } #else /* * default is to return buffer object pointing to * current item a view of it */ if (PyArray_ISWRITEABLE(ap)) { if (array_might_be_written(ap) < 0) { return NULL; } u = (PyArrayObject *)PyBuffer_FromReadWriteMemory(ip, itemsize); } else { u = (PyArrayObject *)PyBuffer_FromMemory(ip, itemsize); } #endif if (u == NULL) { return NULL; } return (PyObject *)u; } NPY_NO_EXPORT int PyArray_CopyObject(PyArrayObject *, PyObject *); static int VOID_setitem(PyObject *op, char *ip, PyArrayObject *ap) { PyArray_Descr* descr; int itemsize=PyArray_DESCR(ap)->elsize; int res; descr = PyArray_DESCR(ap); if (descr->names && PyTuple_Check(op)) { PyObject *key; PyObject *names; int i, n; PyObject *tup, *title; PyArray_Descr *new; int offset; int savedflags; res = -1; /* get the names from the fields dictionary*/ names = descr->names; n = PyTuple_GET_SIZE(names); if (PyTuple_GET_SIZE(op) != n) { PyErr_SetString(PyExc_ValueError, "size of tuple must match number of fields."); return -1; } savedflags = PyArray_FLAGS(ap); for (i = 0; i < n; i++) { key = PyTuple_GET_ITEM(names, i); tup = PyDict_GetItem(descr->fields, key); if (!PyArg_ParseTuple(tup, "Oi|O", &new, &offset, &title)) { ((PyArrayObject_fields *)ap)->descr = descr; return -1; } /* * TODO: temporarily modifying the array like this * is bad coding style, should be changed. */ ((PyArrayObject_fields *)ap)->descr = new; /* remember to update alignment flags */ if ((new->alignment > 1) && ((((npy_intp)(ip+offset)) % new->alignment) != 0)) { PyArray_CLEARFLAGS(ap, NPY_ARRAY_ALIGNED); } else { PyArray_ENABLEFLAGS(ap, NPY_ARRAY_ALIGNED); } res = new->f->setitem(PyTuple_GET_ITEM(op, i), ip+offset, ap); ((PyArrayObject_fields *)ap)->flags = savedflags; if (res < 0) { break; } } ((PyArrayObject_fields *)ap)->descr = descr; return res; } if (descr->subarray) { /* copy into an array of the same basic type */ PyArray_Dims shape = {NULL, -1}; PyArrayObject *ret; if (!(PyArray_IntpConverter(descr->subarray->shape, &shape))) { PyDimMem_FREE(shape.ptr); PyErr_SetString(PyExc_ValueError, "invalid shape in fixed-type tuple."); return -1; } Py_INCREF(descr->subarray->base); ret = (PyArrayObject *)PyArray_NewFromDescr(&PyArray_Type, descr->subarray->base, shape.len, shape.ptr, NULL, ip, PyArray_FLAGS(ap), NULL); PyDimMem_FREE(shape.ptr); if (!ret) { return -1; } Py_INCREF(ap); if (PyArray_SetBaseObject(ret, (PyObject *)ap) < 0) { Py_DECREF(ret); return -1; } PyArray_UpdateFlags(ret, NPY_ARRAY_UPDATE_ALL); res = PyArray_CopyObject(ret, op); Py_DECREF(ret); return res; } /* Default is to use buffer interface to set item */ { const void *buffer; Py_ssize_t buflen; if (PyDataType_FLAGCHK(descr, NPY_ITEM_HASOBJECT) || PyDataType_FLAGCHK(descr, NPY_ITEM_IS_POINTER)) { PyErr_SetString(PyExc_ValueError, "Setting void-array with object members using buffer."); return -1; } res = PyObject_AsReadBuffer(op, &buffer, &buflen); if (res == -1) { goto fail; } memcpy(ip, buffer, PyArray_MIN(buflen, itemsize)); if (itemsize > buflen) { memset(ip + buflen, 0, itemsize - buflen); } } return 0; fail: return -1; } static PyObject * DATETIME_getitem(char *ip, PyArrayObject *ap) { npy_datetime dt; PyArray_DatetimeMetaData *meta = NULL; /* Get the datetime units metadata */ meta = get_datetime_metadata_from_dtype(PyArray_DESCR(ap)); if (meta == NULL) { return NULL; } if ((ap == NULL) || PyArray_ISBEHAVED_RO(ap)) { dt = *((npy_datetime *)ip); } else { PyArray_DESCR(ap)->f->copyswap(&dt, ip, !PyArray_ISNOTSWAPPED(ap), ap); } return convert_datetime_to_pyobject(dt, meta); } static PyObject * TIMEDELTA_getitem(char *ip, PyArrayObject *ap) { npy_timedelta td; PyArray_DatetimeMetaData *meta = NULL; /* Get the datetime units metadata */ meta = get_datetime_metadata_from_dtype(PyArray_DESCR(ap)); if (meta == NULL) { return NULL; } if ((ap == NULL) || PyArray_ISBEHAVED_RO(ap)) { td = *((npy_timedelta *)ip); } else { PyArray_DESCR(ap)->f->copyswap(&td, ip, !PyArray_ISNOTSWAPPED(ap), ap); } return convert_timedelta_to_pyobject(td, meta); } static int DATETIME_setitem(PyObject *op, char *ov, PyArrayObject *ap) { /* ensure alignment */ npy_datetime temp = 0; PyArray_DatetimeMetaData *meta = NULL; /* Get the datetime units metadata */ meta = get_datetime_metadata_from_dtype(PyArray_DESCR(ap)); if (meta == NULL) { return -1; } /* Convert the object into a NumPy datetime */ if (convert_pyobject_to_datetime(meta, op, NPY_SAME_KIND_CASTING, &temp) < 0) { return -1; } /* Copy the value into the output */ if (ap == NULL || PyArray_ISBEHAVED(ap)) { *((npy_datetime *)ov)=temp; } else { PyArray_DESCR(ap)->f->copyswap(ov, &temp, !PyArray_ISNOTSWAPPED(ap), ap); } return 0; } static int TIMEDELTA_setitem(PyObject *op, char *ov, PyArrayObject *ap) { /* ensure alignment */ npy_timedelta temp = 0; PyArray_DatetimeMetaData *meta = NULL; /* Get the datetime units metadata */ meta = get_datetime_metadata_from_dtype(PyArray_DESCR(ap)); if (meta == NULL) { return -1; } /* Convert the object into a NumPy datetime */ if (convert_pyobject_to_timedelta(meta, op, NPY_SAME_KIND_CASTING, &temp) < 0) { return -1; } /* Copy the value into the output */ if (ap == NULL || PyArray_ISBEHAVED(ap)) { *((npy_timedelta *)ov)=temp; } else { PyArray_DESCR(ap)->f->copyswap(ov, &temp, !PyArray_ISNOTSWAPPED(ap), ap); } return 0; } /* ***************************************************************************** ** TYPE TO TYPE CONVERSIONS ** ***************************************************************************** */ /* Assumes contiguous, and aligned, from and to */ /**begin repeat * * #TOTYPE = BYTE, UBYTE, SHORT, USHORT, INT, UINT, LONG, ULONG, * LONGLONG, ULONGLONG, FLOAT, DOUBLE, LONGDOUBLE, DATETIME, * TIMEDELTA# * #totype = npy_byte, npy_ubyte, npy_short, npy_ushort, npy_int, npy_uint, * npy_long, npy_ulong, npy_longlong, npy_ulonglong, * npy_float, npy_double, npy_longdouble, * npy_datetime, npy_timedelta# */ /**begin repeat1 * * #FROMTYPE = BYTE, UBYTE, SHORT, USHORT, INT, UINT, LONG, ULONG, * LONGLONG, ULONGLONG, FLOAT, DOUBLE, LONGDOUBLE, DATETIME, * TIMEDELTA# * #fromtype = npy_byte, npy_ubyte, npy_short, npy_ushort, npy_int, npy_uint, * npy_long, npy_ulong, npy_longlong, npy_ulonglong, * npy_float, npy_double, npy_longdouble, * npy_datetime, npy_timedelta# */ static void @FROMTYPE@_to_@TOTYPE@(@fromtype@ *ip, @totype@ *op, npy_intp n, PyArrayObject *NPY_UNUSED(aip), PyArrayObject *NPY_UNUSED(aop)) { while (n--) { *op++ = (@totype@)*ip++; } } /**end repeat1**/ /**begin repeat1 * * #FROMTYPE = CFLOAT, CDOUBLE, CLONGDOUBLE# * #fromtype = npy_float, npy_double, npy_longdouble# */ static void @FROMTYPE@_to_@TOTYPE@(@fromtype@ *ip, @totype@ *op, npy_intp n, PyArrayObject *NPY_UNUSED(aip), PyArrayObject *NPY_UNUSED(aop)) { while (n--) { *op++ = (@totype@)*ip; ip += 2; } } /**end repeat1**/ /**end repeat**/ /**begin repeat * * #TYPE = BYTE, UBYTE, SHORT, USHORT, INT, UINT, LONG, ULONG, * LONGLONG, ULONGLONG, LONGDOUBLE, DATETIME, * TIMEDELTA# * #type = npy_byte, npy_ubyte, npy_short, npy_ushort, npy_int, npy_uint, * npy_long, npy_ulong, npy_longlong, npy_ulonglong, * npy_longdouble, * npy_datetime, npy_timedelta# */ static void @TYPE@_to_HALF(@type@ *ip, npy_half *op, npy_intp n, PyArrayObject *NPY_UNUSED(aip), PyArrayObject *NPY_UNUSED(aop)) { while (n--) { *op++ = npy_float_to_half((float)(*ip++)); } } static void HALF_to_@TYPE@(npy_half *ip, @type@ *op, npy_intp n, PyArrayObject *NPY_UNUSED(aip), PyArrayObject *NPY_UNUSED(aop)) { while (n--) { *op++ = (@type@)npy_half_to_float(*ip++); } } /**end repeat**/ #if NPY_SIZEOF_SHORT == 2 #define HALF_to_HALF SHORT_to_SHORT #elif NPY_SIZEOF_INT == 2 #define HALF_to_HALF INT_to_INT #endif /**begin repeat * * #TYPE = FLOAT, DOUBLE, CFLOAT, CDOUBLE# * #name = float, double, float, double# * #itype = npy_uint32, npy_uint64, npy_uint32, npy_uint64# * #iscomplex = 0, 0, 1, 1# */ static void @TYPE@_to_HALF(@itype@ *ip, npy_half *op, npy_intp n, PyArrayObject *NPY_UNUSED(aip), PyArrayObject *NPY_UNUSED(aop)) { while (n--) { *op++ = npy_@name@bits_to_halfbits(*ip); #if @iscomplex@ ip += 2; #else ip++; #endif } } static void HALF_to_@TYPE@(npy_half *ip, @itype@ *op, npy_intp n, PyArrayObject *NPY_UNUSED(aip), PyArrayObject *NPY_UNUSED(aop)) { while (n--) { *op++ = npy_halfbits_to_@name@bits(*ip++); #if @iscomplex@ *op++ = 0; #endif } } /**end repeat**/ static void CLONGDOUBLE_to_HALF(npy_longdouble *ip, npy_half *op, npy_intp n, PyArrayObject *NPY_UNUSED(aip), PyArrayObject *NPY_UNUSED(aop)) { while (n--) { *op++ = npy_double_to_half((double) (*ip++)); ip += 2; } } static void HALF_to_CLONGDOUBLE(npy_half *ip, npy_longdouble *op, npy_intp n, PyArrayObject *NPY_UNUSED(aip), PyArrayObject *NPY_UNUSED(aop)) { while (n--) { *op++ = npy_half_to_double(*ip++); *op++ = 0; } } /**begin repeat * * #FROMTYPE = BOOL, * BYTE, UBYTE, SHORT, USHORT, INT, UINT, * LONG, ULONG, LONGLONG, ULONGLONG, * FLOAT, DOUBLE, LONGDOUBLE, * DATETIME, TIMEDELTA# * #fromtype = npy_bool, * npy_byte, npy_ubyte, npy_short, npy_ushort, npy_int, npy_uint, * npy_long, npy_ulong, npy_longlong, npy_ulonglong, * npy_float, npy_double, npy_longdouble, * npy_datetime, npy_timedelta# */ static void @FROMTYPE@_to_BOOL(@fromtype@ *ip, npy_bool *op, npy_intp n, PyArrayObject *NPY_UNUSED(aip), PyArrayObject *NPY_UNUSED(aop)) { while (n--) { *op++ = (npy_bool)(*ip++ != NPY_FALSE); } } /**end repeat**/ static void HALF_to_BOOL(npy_half *ip, npy_bool *op, npy_intp n, PyArrayObject *NPY_UNUSED(aip), PyArrayObject *NPY_UNUSED(aop)) { while (n--) { *op++ = (npy_bool)(!npy_half_iszero(*ip++)); } } /**begin repeat * * #FROMTYPE = CFLOAT, CDOUBLE, CLONGDOUBLE# * #fromtype = npy_cfloat, npy_cdouble, npy_clongdouble# */ static void @FROMTYPE@_to_BOOL(@fromtype@ *ip, npy_bool *op, npy_intp n, PyArrayObject *NPY_UNUSED(aip), PyArrayObject *NPY_UNUSED(aop)) { while (n--) { *op = (npy_bool)(((*ip).real != NPY_FALSE) || ((*ip).imag != NPY_FALSE)); op++; ip++; } } /**end repeat**/ /**begin repeat * #TOTYPE = BYTE, UBYTE, SHORT, USHORT, INT, UINT, * LONG, ULONG, LONGLONG, ULONGLONG, * HALF, FLOAT, DOUBLE, LONGDOUBLE, * DATETIME, TIMEDELTA# * #totype = npy_byte, npy_ubyte, npy_short, npy_ushort, npy_int, npy_uint, * npy_long, npy_ulong, npy_longlong, npy_ulonglong, * npy_half, npy_float, npy_double, npy_longdouble, * npy_datetime, npy_timedelta# * #one = 1*10, NPY_HALF_ONE, 1*5# * #zero = 0*10, NPY_HALF_ZERO, 0*5# */ static void BOOL_to_@TOTYPE@(npy_bool *ip, @totype@ *op, npy_intp n, PyArrayObject *NPY_UNUSED(aip), PyArrayObject *NPY_UNUSED(aop)) { while (n--) { *op++ = (@totype@)((*ip++ != NPY_FALSE) ? @one@ : @zero@); } } /**end repeat**/ /**begin repeat * * #TOTYPE = CFLOAT, CDOUBLE,CLONGDOUBLE# * #totype = npy_float, npy_double, npy_longdouble# */ /**begin repeat1 * #FROMTYPE = BOOL, * BYTE, UBYTE, SHORT, USHORT, INT, UINT, * LONG, ULONG, LONGLONG, ULONGLONG, * FLOAT, DOUBLE, LONGDOUBLE, * DATETIME, TIMEDELTA# * #fromtype = npy_bool, * npy_byte, npy_ubyte, npy_short, npy_ushort, npy_int, npy_uint, * npy_long, npy_ulong, npy_longlong, npy_ulonglong, * npy_float, npy_double, npy_longdouble, * npy_datetime, npy_timedelta# */ static void @FROMTYPE@_to_@TOTYPE@(@fromtype@ *ip, @totype@ *op, npy_intp n, PyArrayObject *NPY_UNUSED(aip), PyArrayObject *NPY_UNUSED(aop)) { while (n--) { *op++ = (@totype@)*ip++; *op++ = 0.0; } } /**end repeat1**/ /**end repeat**/ /**begin repeat * * #TOTYPE = CFLOAT,CDOUBLE,CLONGDOUBLE# * #totype = npy_float, npy_double, npy_longdouble# */ /**begin repeat1 * #FROMTYPE = CFLOAT,CDOUBLE,CLONGDOUBLE# * #fromtype = npy_float, npy_double, npy_longdouble# */ static void @FROMTYPE@_to_@TOTYPE@(@fromtype@ *ip, @totype@ *op, npy_intp n, PyArrayObject *NPY_UNUSED(aip), PyArrayObject *NPY_UNUSED(aop)) { n <<= 1; while (n--) { *op++ = (@totype@)*ip++; } } /**end repeat1**/ /**end repeat**/ /**begin repeat * * #FROMTYPE = BOOL, * BYTE, UBYTE, SHORT, USHORT, INT, UINT, * LONG, ULONG, LONGLONG, ULONGLONG, * HALF, FLOAT, DOUBLE, LONGDOUBLE, * CFLOAT, CDOUBLE, CLONGDOUBLE, * STRING, UNICODE, VOID, OBJECT, * DATETIME, TIMEDELTA# * #fromtype = npy_bool, * npy_byte, npy_ubyte, npy_short, npy_ushort, npy_int, npy_uint, * npy_long, npy_ulong, npy_longlong, npy_ulonglong, * npy_half, npy_float, npy_double, npy_longdouble, * npy_cfloat, npy_cdouble, npy_clongdouble, * npy_char, npy_char, npy_char, PyObject *, * npy_datetime, npy_timedelta# * #skip = 1*18, PyArray_DESCR(aip)->elsize*3, 1*3# */ static void @FROMTYPE@_to_OBJECT(@fromtype@ *ip, PyObject **op, npy_intp n, PyArrayObject *aip, PyArrayObject *NPY_UNUSED(aop)) { npy_intp i; int skip = @skip@; PyObject *tmp; for (i = 0; i < n; i++, ip +=skip, op++) { tmp = *op; *op = @FROMTYPE@_getitem((char *)ip, aip); Py_XDECREF(tmp); } } /**end repeat**/ #define _NPY_UNUSEDBOOL NPY_UNUSED #define _NPY_UNUSEDBYTE NPY_UNUSED #define _NPY_UNUSEDUBYTE NPY_UNUSED #define _NPY_UNUSEDSHORT NPY_UNUSED #define _NPY_UNUSEDUSHORT NPY_UNUSED #define _NPY_UNUSEDINT NPY_UNUSED #define _NPY_UNUSEDUINT NPY_UNUSED #define _NPY_UNUSEDLONG NPY_UNUSED #define _NPY_UNUSEDULONG NPY_UNUSED #define _NPY_UNUSEDLONGLONG NPY_UNUSED #define _NPY_UNUSEDULONGLONG NPY_UNUSED #define _NPY_UNUSEDHALF NPY_UNUSED #define _NPY_UNUSEDFLOAT NPY_UNUSED #define _NPY_UNUSEDDOUBLE NPY_UNUSED #define _NPY_UNUSEDLONGDOUBLE NPY_UNUSED #define _NPY_UNUSEDCFLOAT NPY_UNUSED #define _NPY_UNUSEDCDOUBLE NPY_UNUSED #define _NPY_UNUSEDCLONGDOUBLE NPY_UNUSED #define _NPY_UNUSEDDATETIME NPY_UNUSED #define _NPY_UNUSEDTIMEDELTA NPY_UNUSED #define _NPY_UNUSEDHALF NPY_UNUSED #define _NPY_UNUSEDSTRING #define _NPY_UNUSEDVOID #define _NPY_UNUSEDUNICODE /**begin repeat * * #TOTYPE = BOOL, * BYTE, UBYTE, SHORT, USHORT, INT, UINT, * LONG, ULONG, LONGLONG, ULONGLONG, * HALF, FLOAT, DOUBLE, LONGDOUBLE, * CFLOAT, CDOUBLE, CLONGDOUBLE, * STRING, UNICODE, VOID, * DATETIME, TIMEDELTA# * #totype = npy_bool, * npy_byte, npy_ubyte, npy_short, npy_ushort, npy_int, npy_uint, * npy_long, npy_ulong, npy_longlong, npy_ulonglong, * npy_half, npy_float, npy_double, npy_longdouble, * npy_cfloat, npy_cdouble, npy_clongdouble, * npy_char, npy_char, npy_char, * npy_datetime, npy_timedelta# * #skip = 1*18, PyArray_DESCR(aop)->elsize*3, 1*2# */ static void OBJECT_to_@TOTYPE@(PyObject **ip, @totype@ *op, npy_intp n, PyArrayObject *_NPY_UNUSED@TOTYPE@(aip), PyArrayObject *aop) { npy_intp i; int skip = @skip@; for (i = 0; i < n; i++, ip++, op += skip) { if (*ip == NULL) { @TOTYPE@_setitem(Py_False, (char *)op, aop); } else { @TOTYPE@_setitem(*ip, (char *)op, aop); } } } /**end repeat**/ /**begin repeat * * #from = STRING*23, UNICODE*23, VOID*23# * #fromtyp = npy_char*69# * #to = (BOOL, * BYTE, UBYTE, SHORT, USHORT, INT, UINT, * LONG, ULONG, LONGLONG, ULONGLONG, * HALF, FLOAT, DOUBLE, LONGDOUBLE, * CFLOAT, CDOUBLE, CLONGDOUBLE, * STRING, UNICODE, VOID, * DATETIME, TIMEDELTA)*3# * #totyp = (npy_bool, * npy_byte, npy_ubyte, npy_short, npy_ushort, npy_int, npy_uint, * npy_long, npy_ulong, npy_longlong, npy_ulonglong, * npy_half, npy_float, npy_double, npy_longdouble, * npy_cfloat, npy_cdouble, npy_clongdouble, * npy_char, npy_char, npy_char, * npy_datetime, npy_timedelta)*3# * #oskip = 1*18,(PyArray_DESCR(aop)->elsize)*3,1*2, * 1*18,(PyArray_DESCR(aop)->elsize)*3,1*2, * 1*18,(PyArray_DESCR(aop)->elsize)*3,1*2# * #convert = 1*18, 0*3, 1*2, * 1*18, 0*3, 1*2, * 0*23# * #convstr = (Int*9, Long*2, Float*4, Complex*3, Tuple*3, Long*2)*3# */ #if @convert@ #define IS_@from@ static void @from@_to_@to@(@fromtyp@ *ip, @totyp@ *op, npy_intp n, PyArrayObject *aip, PyArrayObject *aop) { npy_intp i; PyObject *temp = NULL, *new; int skip = PyArray_DESCR(aip)->elsize; int oskip = @oskip@; for (i = 0; i < n; i++, ip+=skip, op+=oskip) { temp = @from@_getitem((char *)ip, aip); if (temp == NULL) { return; } #if defined(NPY_PY3K) && defined(IS_STRING) /* Work around some Python 3K */ new = PyUnicode_FromEncodedObject(temp, "ascii", "strict"); Py_DECREF(temp); temp = new; if (temp == NULL) { return; } #endif /* convert from Python object to needed one */ { PyObject *args; /* call out to the Python builtin given by convstr */ args = Py_BuildValue("(N)", temp); #if defined(NPY_PY3K) #define PyInt_Type PyLong_Type #endif new = Py@convstr@_Type.tp_new(&Py@convstr@_Type, args, NULL); #if defined(NPY_PY3K) #undef PyInt_Type #endif Py_DECREF(args); temp = new; if (temp == NULL) { return; } } if (@to@_setitem(temp,(char *)op, aop)) { Py_DECREF(temp); return; } Py_DECREF(temp); } } #undef IS_@from@ #else static void @from@_to_@to@(@fromtyp@ *ip, @totyp@ *op, npy_intp n, PyArrayObject *aip, PyArrayObject *aop) { npy_intp i; PyObject *temp = NULL; int skip = PyArray_DESCR(aip)->elsize; int oskip = @oskip@; for (i = 0; i < n; i++, ip+=skip, op+=oskip) { temp = @from@_getitem((char *)ip, aip); if (temp == NULL) { return; } if (@to@_setitem(temp,(char *)op, aop)) { Py_DECREF(temp); return; } Py_DECREF(temp); } } #endif /**end repeat**/ /**begin repeat * * #to = STRING*20, UNICODE*20, VOID*20# * #totyp = npy_char*20, npy_char*20, npy_char*20# * #from = (BOOL, * BYTE, UBYTE, SHORT, USHORT, INT, UINT, * LONG, ULONG, LONGLONG, ULONGLONG, * HALF, FLOAT, DOUBLE, LONGDOUBLE, * CFLOAT, CDOUBLE, CLONGDOUBLE, * DATETIME, TIMEDELTA)*3# * #fromtyp = (npy_bool, * npy_byte, npy_ubyte, npy_short, npy_ushort, npy_int, npy_uint, * npy_long, npy_ulong, npy_longlong, npy_ulonglong, * npy_half, npy_float, npy_double, npy_longdouble, * npy_cfloat, npy_cdouble, npy_clongdouble, * npy_datetime, npy_timedelta)*3# */ static void @from@_to_@to@(@fromtyp@ *ip, @totyp@ *op, npy_intp n, PyArrayObject *aip, PyArrayObject *aop) { npy_intp i; PyObject *temp = NULL; int skip = 1; int oskip = PyArray_DESCR(aop)->elsize; for (i = 0; i < n; i++, ip += skip, op += oskip) { temp = @from@_getitem((char *)ip, aip); if (temp == NULL) { Py_INCREF(Py_False); temp = Py_False; } if (@to@_setitem(temp,(char *)op, aop)) { Py_DECREF(temp); return; } Py_DECREF(temp); } } /**end repeat**/ /* ***************************************************************************** ** SCAN ** ***************************************************************************** */ /* * The first ignore argument is for backwards compatibility. * Should be removed when the API version is bumped up. */ /**begin repeat * #fname = SHORT, USHORT, INT, UINT, * LONG, ULONG, LONGLONG, ULONGLONG# * #type = npy_short, npy_ushort, npy_int, npy_uint, * npy_long, npy_ulong, npy_longlong, npy_ulonglong# * #format = "hd", "hu", "d", "u", * "ld", "lu", NPY_LONGLONG_FMT, NPY_ULONGLONG_FMT# */ static int @fname@_scan(FILE *fp, @type@ *ip, void *NPY_UNUSED(ignore), PyArray_Descr *NPY_UNUSED(ignored)) { return fscanf(fp, "%"@format@, ip); } /**end repeat**/ /**begin repeat * #fname = FLOAT, DOUBLE, LONGDOUBLE# * #type = npy_float, npy_double, npy_longdouble# */ static int @fname@_scan(FILE *fp, @type@ *ip, void *NPY_UNUSED(ignore), PyArray_Descr *NPY_UNUSED(ignored)) { double result; int ret; ret = NumPyOS_ascii_ftolf(fp, &result); *ip = (@type@) result; return ret; } /**end repeat**/ static int HALF_scan(FILE *fp, npy_half *ip, void *NPY_UNUSED(ignore), PyArray_Descr *NPY_UNUSED(ignored)) { double result; int ret; ret = NumPyOS_ascii_ftolf(fp, &result); *ip = npy_double_to_half(result); return ret; } /**begin repeat * #fname = BYTE, UBYTE# * #type = npy_byte, npy_ubyte# * #btype = npy_int, npy_uint# * #format = "d", "u"# */ static int @fname@_scan(FILE *fp, @type@ *ip, void *NPY_UNUSED(ignore), PyArray_Descr *NPY_UNUSED(ignore2)) { @btype@ temp; int num; num = fscanf(fp, "%"@format@, &temp); *ip = (@type@) temp; return num; } /**end repeat**/ static int BOOL_scan(FILE *fp, npy_bool *ip, void *NPY_UNUSED(ignore), PyArray_Descr *NPY_UNUSED(ignore2)) { double result; int ret; ret = NumPyOS_ascii_ftolf(fp, &result); *ip = (npy_bool) (result != 0.0); return ret; } /**begin repeat * #fname = CFLOAT, CDOUBLE, CLONGDOUBLE, * OBJECT, STRING, UNICODE, VOID, * DATETIME, TIMEDELTA# */ #define @fname@_scan NULL /**end repeat**/ /* ***************************************************************************** ** FROMSTR ** ***************************************************************************** */ /**begin repeat * #fname = BYTE, UBYTE, SHORT, USHORT, INT, UINT, * LONG, ULONG, LONGLONG, ULONGLONG, * DATETIME, TIMEDELTA# * #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# */ static int @fname@_fromstr(char *str, @type@ *ip, char **endptr, PyArray_Descr *NPY_UNUSED(ignore)) { @btype@ result; result = PyOS_strto@func@(str, endptr, 10); *ip = (@type@) result; return 0; } /**end repeat**/ /**begin repeat * * #fname = FLOAT, DOUBLE, LONGDOUBLE# * #type = npy_float, npy_double, npy_longdouble# */ static int @fname@_fromstr(char *str, @type@ *ip, char **endptr, PyArray_Descr *NPY_UNUSED(ignore)) { double result; result = NumPyOS_ascii_strtod(str, endptr); *ip = (@type@) result; return 0; } /**end repeat**/ static int HALF_fromstr(char *str, npy_half *ip, char **endptr, PyArray_Descr *NPY_UNUSED(ignore)) { double result; result = NumPyOS_ascii_strtod(str, endptr); *ip = npy_double_to_half(result); return 0; } static int BOOL_fromstr(char *str, npy_bool *ip, char **endptr, PyArray_Descr *NPY_UNUSED(ignore)) { double result; result = NumPyOS_ascii_strtod(str, endptr); *ip = (npy_bool) (result != 0.0); return 0; } /**begin repeat * #fname = CFLOAT, CDOUBLE, CLONGDOUBLE, * OBJECT, STRING, UNICODE, VOID# */ #define @fname@_fromstr NULL /**end repeat**/ /* ***************************************************************************** ** COPYSWAPN ** ***************************************************************************** */ /**begin repeat * * #fname = SHORT, USHORT, INT, UINT, * LONG, ULONG, LONGLONG, ULONGLONG, * HALF, FLOAT, DOUBLE, LONGDOUBLE, * DATETIME, TIMEDELTA# * #fsize = SHORT, SHORT, INT, INT, * LONG, LONG, LONGLONG, LONGLONG, * HALF, FLOAT, DOUBLE, LONGDOUBLE, * DATETIME, TIMEDELTA# * #type = npy_short, npy_ushort, npy_int, npy_uint, * npy_long, npy_ulong, npy_longlong, npy_ulonglong, * npy_half, npy_float, npy_double, npy_longdouble, * npy_datetime, npy_timedelta# */ static void @fname@_copyswapn (void *dst, npy_intp dstride, void *src, npy_intp sstride, npy_intp n, int swap, void *NPY_UNUSED(arr)) { if (src != NULL) { if (sstride == sizeof(@type@) && dstride == sizeof(@type@)) { memcpy(dst, src, n*sizeof(@type@)); } else { _unaligned_strided_byte_copy(dst, dstride, src, sstride, n, sizeof(@type@)); } } if (swap) { _strided_byte_swap(dst, dstride, n, sizeof(@type@)); } } static void @fname@_copyswap (void *dst, void *src, int swap, void *NPY_UNUSED(arr)) { if (src != NULL) { /* copy first if needed */ memcpy(dst, src, sizeof(@type@)); } if (swap) { char *a, *b, c; a = (char *)dst; #if NPY_SIZEOF_@fsize@ == 2 b = a + 1; c = *a; *a++ = *b; *b = c; #elif NPY_SIZEOF_@fsize@ == 4 b = a + 3; c = *a; *a++ = *b; *b-- = c; c = *a; *a++ = *b; *b = c; #elif NPY_SIZEOF_@fsize@ == 8 b = a + 7; c = *a; *a++ = *b; *b-- = c; c = *a; *a++ = *b; *b-- = c; c = *a; *a++ = *b; *b-- = c; c = *a; *a++ = *b; *b = c; #elif NPY_SIZEOF_@fsize@ == 10 b = a + 9; c = *a; *a++ = *b; *b-- = c; c = *a; *a++ = *b; *b-- = c; c = *a; *a++ = *b; *b-- = c; c = *a; *a++ = *b; *b-- = c; c = *a; *a++ = *b; *b = c; #elif NPY_SIZEOF_@fsize@ == 12 b = a + 11; c = *a; *a++ = *b; *b-- = c; c = *a; *a++ = *b; *b-- = c; c = *a; *a++ = *b; *b-- = c; c = *a; *a++ = *b; *b-- = c; c = *a; *a++ = *b; *b-- = c; c = *a; *a++ = *b; *b = c; #elif NPY_SIZEOF_@fsize@ == 16 b = a + 15; c = *a; *a++ = *b; *b-- = c; c = *a; *a++ = *b; *b-- = c; c = *a; *a++ = *b; *b-- = c; c = *a; *a++ = *b; *b-- = c; c = *a; *a++ = *b; *b-- = c; c = *a; *a++ = *b; *b-- = c; c = *a; *a++ = *b; *b-- = c; c = *a; *a++ = *b; *b = c; #else { int i, nn; b = a + (NPY_SIZEOF_@fsize@-1); nn = NPY_SIZEOF_@fsize@ / 2; for (i = 0; i < nn; i++) { c = *a; *a++ = *b; *b-- = c; } } #endif } } /**end repeat**/ /**begin repeat * * #fname = BOOL, * BYTE, UBYTE# * #type = npy_bool, * npy_byte, npy_ubyte# */ static void @fname@_copyswapn (void *dst, npy_intp dstride, void *src, npy_intp sstride, npy_intp n, int NPY_UNUSED(swap), void *NPY_UNUSED(arr)) { if (src != NULL) { if (sstride == sizeof(@type@) && dstride == sizeof(@type@)) { memcpy(dst, src, n*sizeof(@type@)); } else { _unaligned_strided_byte_copy(dst, dstride, src, sstride, n, sizeof(@type@)); } } /* ignore swap */ } static void @fname@_copyswap (void *dst, void *src, int NPY_UNUSED(swap), void *NPY_UNUSED(arr)) { if (src != NULL) { /* copy first if needed */ memcpy(dst, src, sizeof(@type@)); } /* ignore swap */ } /**end repeat**/ /**begin repeat * * #fname = CFLOAT, CDOUBLE, CLONGDOUBLE# * #fsize = FLOAT, DOUBLE, LONGDOUBLE# * #type = npy_cfloat, npy_cdouble, npy_clongdouble# */ static void @fname@_copyswapn (void *dst, npy_intp dstride, void *src, npy_intp sstride, npy_intp n, int swap, void *NPY_UNUSED(arr)) { if (src != NULL) { /* copy first if needed */ if (sstride == sizeof(@type@) && dstride == sizeof(@type@)) { memcpy(dst, src, n*sizeof(@type@)); } else { _unaligned_strided_byte_copy(dst, dstride, src, sstride, n, sizeof(@type@)); } } if (swap) { _strided_byte_swap(dst, dstride, n, NPY_SIZEOF_@fsize@); _strided_byte_swap(((char *)dst + NPY_SIZEOF_@fsize@), dstride, n, NPY_SIZEOF_@fsize@); } } static void @fname@_copyswap (void *dst, void *src, int swap, void *NPY_UNUSED(arr)) { if (src != NULL) /* copy first if needed */ memcpy(dst, src, sizeof(@type@)); if (swap) { char *a, *b, c; a = (char *)dst; #if NPY_SIZEOF_@fsize@ == 4 b = a + 3; c = *a; *a++ = *b; *b-- = c; c = *a; *a++ = *b; *b = c; a += 2; b = a + 3; c = *a; *a++ = *b; *b-- = c; c = *a; *a++ = *b; *b = c; #elif NPY_SIZEOF_@fsize@ == 8 b = a + 7; c = *a; *a++ = *b; *b-- = c; c = *a; *a++ = *b; *b-- = c; c = *a; *a++ = *b; *b-- = c; c = *a; *a++ = *b; *b = c; a += 4; b = a + 7; c = *a; *a++ = *b; *b-- = c; c = *a; *a++ = *b; *b-- = c; c = *a; *a++ = *b; *b-- = c; c = *a; *a++ = *b; *b = c; #elif NPY_SIZEOF_@fsize@ == 10 b = a + 9; c = *a; *a++ = *b; *b-- = c; c = *a; *a++ = *b; *b-- = c; c = *a; *a++ = *b; *b-- = c; c = *a; *a++ = *b; *b-- = c; c = *a; *a++ = *b; *b = c; a += 5; b = a + 9; c = *a; *a++ = *b; *b-- = c; c = *a; *a++ = *b; *b-- = c; c = *a; *a++ = *b; *b-- = c; c = *a; *a++ = *b; *b-- = c; c = *a; *a++ = *b; *b = c; #elif NPY_SIZEOF_@fsize@ == 12 b = a + 11; c = *a; *a++ = *b; *b-- = c; c = *a; *a++ = *b; *b-- = c; c = *a; *a++ = *b; *b-- = c; c = *a; *a++ = *b; *b-- = c; c = *a; *a++ = *b; *b-- = c; c = *a; *a++ = *b; *b = c; a += 6; b = a + 11; c = *a; *a++ = *b; *b-- = c; c = *a; *a++ = *b; *b-- = c; c = *a; *a++ = *b; *b-- = c; c = *a; *a++ = *b; *b-- = c; c = *a; *a++ = *b; *b-- = c; c = *a; *a++ = *b; *b = c; #elif NPY_SIZEOF_@fsize@ == 16 b = a + 15; c = *a; *a++ = *b; *b-- = c; c = *a; *a++ = *b; *b-- = c; c = *a; *a++ = *b; *b-- = c; c = *a; *a++ = *b; *b-- = c; c = *a; *a++ = *b; *b-- = c; c = *a; *a++ = *b; *b-- = c; c = *a; *a++ = *b; *b-- = c; c = *a; *a++ = *b; *b = c; a += 8; b = a + 15; c = *a; *a++ = *b; *b-- = c; c = *a; *a++ = *b; *b-- = c; c = *a; *a++ = *b; *b-- = c; c = *a; *a++ = *b; *b-- = c; c = *a; *a++ = *b; *b-- = c; c = *a; *a++ = *b; *b-- = c; c = *a; *a++ = *b; *b-- = c; c = *a; *a++ = *b; *b = c; #else { int i, nn; b = a + (NPY_SIZEOF_@fsize@ - 1); nn = NPY_SIZEOF_@fsize@ / 2; for (i = 0; i < nn; i++) { c = *a; *a++ = *b; *b-- = c; } a += nn; b = a + (NPY_SIZEOF_@fsize@ - 1); for (i = 0; i < nn; i++) { c = *a; *a++ = *b; *b-- = c; } } #endif } } /**end repeat**/ static void OBJECT_copyswapn(PyObject **dst, npy_intp dstride, PyObject **src, npy_intp sstride, npy_intp n, int NPY_UNUSED(swap), void *NPY_UNUSED(arr)) { npy_intp i; if (src != NULL) { if (__ALIGNED(dst, sizeof(PyObject **)) && __ALIGNED(src, sizeof(PyObject **)) && __ALIGNED(dstride, sizeof(PyObject **)) && __ALIGNED(sstride, sizeof(PyObject **))) { dstride /= sizeof(PyObject **); sstride /= sizeof(PyObject **); for (i = 0; i < n; i++) { Py_XINCREF(*src); Py_XDECREF(*dst); *dst = *src; dst += dstride; src += sstride; } } else { unsigned char *dstp, *srcp; PyObject *tmp; dstp = (unsigned char*)dst; srcp = (unsigned char*)src; for (i = 0; i < n; i++) { NPY_COPY_PYOBJECT_PTR(&tmp, srcp); Py_XINCREF(tmp); NPY_COPY_PYOBJECT_PTR(&tmp, dstp); Py_XDECREF(tmp); NPY_COPY_PYOBJECT_PTR(dstp, srcp); dstp += dstride; srcp += sstride; } } } /* ignore swap */ return; } static void OBJECT_copyswap(PyObject **dst, PyObject **src, int NPY_UNUSED(swap), void *NPY_UNUSED(arr)) { if (src != NULL) { if (__ALIGNED(dst,sizeof(PyObject **)) && __ALIGNED(src,sizeof(PyObject **))) { Py_XINCREF(*src); Py_XDECREF(*dst); *dst = *src; } else { PyObject *tmp; NPY_COPY_PYOBJECT_PTR(&tmp, src); Py_XINCREF(tmp); NPY_COPY_PYOBJECT_PTR(&tmp, dst); Py_XDECREF(tmp); NPY_COPY_PYOBJECT_PTR(dst, src); } } } /* ignore swap */ static void STRING_copyswapn (char *dst, npy_intp dstride, char *src, npy_intp sstride, npy_intp n, int NPY_UNUSED(swap), PyArrayObject *arr) { if (src != NULL && arr != NULL) { int itemsize = PyArray_DESCR(arr)->elsize; if (dstride == itemsize && sstride == itemsize) { memcpy(dst, src, itemsize * n); } else { _unaligned_strided_byte_copy(dst, dstride, src, sstride, n, itemsize); } } return; } /* */ static void VOID_copyswapn (char *dst, npy_intp dstride, char *src, npy_intp sstride, npy_intp n, int swap, PyArrayObject *arr) { if (arr == NULL) { return; } if (PyArray_HASFIELDS(arr)) { PyObject *key, *value, *title = NULL; PyArray_Descr *new, *descr; int offset; Py_ssize_t pos = 0; descr = PyArray_DESCR(arr); while (PyDict_Next(descr->fields, &pos, &key, &value)) { if NPY_TITLE_KEY(key, value) { continue; } if (!PyArg_ParseTuple(value, "Oi|O", &new, &offset, &title)) { ((PyArrayObject_fields *)arr)->descr = descr; return; } /* * TODO: temporarily modifying the array like this * is bad coding style, should be changed. */ ((PyArrayObject_fields *)arr)->descr = new; new->f->copyswapn(dst+offset, dstride, (src != NULL ? src+offset : NULL), sstride, n, swap, arr); } ((PyArrayObject_fields *)arr)->descr = descr; return; } if (swap && PyArray_DESCR(arr)->subarray != NULL) { PyArray_Descr *descr, *new; npy_intp num; npy_intp i; int subitemsize; char *dstptr, *srcptr; descr = PyArray_DESCR(arr); new = descr->subarray->base; /* * TODO: temporarily modifying the array like this * is bad coding style, should be changed. */ ((PyArrayObject_fields *)arr)->descr = new; dstptr = dst; srcptr = src; subitemsize = new->elsize; num = descr->elsize / subitemsize; for (i = 0; i < n; i++) { new->f->copyswapn(dstptr, subitemsize, srcptr, subitemsize, num, swap, arr); dstptr += dstride; if (srcptr) { srcptr += sstride; } } ((PyArrayObject_fields *)arr)->descr = descr; return; } if (src != NULL) { memcpy(dst, src, PyArray_DESCR(arr)->elsize * n); } return; } static void VOID_copyswap (char *dst, char *src, int swap, PyArrayObject *arr) { if (arr == NULL) { return; } if (PyArray_HASFIELDS(arr)) { PyObject *key, *value, *title = NULL; PyArray_Descr *new, *descr; int offset; Py_ssize_t pos = 0; descr = PyArray_DESCR(arr); while (PyDict_Next(descr->fields, &pos, &key, &value)) { if NPY_TITLE_KEY(key, value) { continue; } if (!PyArg_ParseTuple(value, "Oi|O", &new, &offset, &title)) { ((PyArrayObject_fields *)arr)->descr = descr; return; } /* * TODO: temporarily modifying the array like this * is bad coding style, should be changed. */ ((PyArrayObject_fields *)arr)->descr = new; new->f->copyswap(dst+offset, (src != NULL ? src+offset : NULL), swap, arr); } ((PyArrayObject_fields *)arr)->descr = descr; return; } if (swap && PyArray_DESCR(arr)->subarray != NULL) { PyArray_Descr *descr, *new; npy_intp num; int itemsize; descr = PyArray_DESCR(arr); new = descr->subarray->base; /* * TODO: temporarily modifying the array like this * is bad coding style, should be changed. */ ((PyArrayObject_fields *)arr)->descr = new; itemsize = new->elsize; num = descr->elsize / itemsize; new->f->copyswapn(dst, itemsize, src, itemsize, num, swap, arr); ((PyArrayObject_fields *)arr)->descr = descr; return; } if (src != NULL) { memcpy(dst, src, PyArray_DESCR(arr)->elsize); } return; } static void UNICODE_copyswapn (char *dst, npy_intp dstride, char *src, npy_intp sstride, npy_intp n, int swap, PyArrayObject *arr) { int itemsize; if (arr == NULL) { return; } itemsize = PyArray_DESCR(arr)->elsize; if (src != NULL) { if (dstride == itemsize && sstride == itemsize) { memcpy(dst, src, n * itemsize); } else { _unaligned_strided_byte_copy(dst, dstride, src, sstride, n, itemsize); } } n *= itemsize; if (swap) { char *a, *b, c; /* n is the number of unicode characters to swap */ n >>= 2; for (a = (char *)dst; n > 0; n--) { b = a + 3; c = *a; *a++ = *b; *b-- = c; c = *a; *a++ = *b; *b-- = c; a += 2; } } } static void STRING_copyswap(char *dst, char *src, int NPY_UNUSED(swap), PyArrayObject *arr) { if (src != NULL && arr != NULL) { memcpy(dst, src, PyArray_DESCR(arr)->elsize); } } static void UNICODE_copyswap (char *dst, char *src, int swap, PyArrayObject *arr) { int itemsize; if (arr == NULL) { return; } itemsize = PyArray_DESCR(arr)->elsize; if (src != NULL) { memcpy(dst, src, itemsize); } if (swap) { char *a, *b, c; itemsize >>= 2; for (a = (char *)dst; itemsize>0; itemsize--) { b = a + 3; c = *a; *a++ = *b; *b-- = c; c = *a; *a++ = *b; *b-- = c; a += 2; } } } /* ***************************************************************************** ** NONZERO ** ***************************************************************************** */ #define _NONZERO(a) ((a) != 0) /**begin repeat * * #fname = BOOL, * BYTE, UBYTE, SHORT, USHORT, INT, UINT, * LONG, ULONG, LONGLONG, ULONGLONG, * HALF, FLOAT, DOUBLE, LONGDOUBLE, * 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_half, npy_float, npy_double, npy_longdouble, * npy_datetime, npy_timedelta# * #isfloat = 0*11, 1*4, 0*2# * #nonzero = _NONZERO*11, !npy_half_iszero, _NONZERO*5# */ static npy_bool @fname@_nonzero (char *ip, PyArrayObject *ap) { if (ap == NULL || PyArray_ISBEHAVED_RO(ap)) { @type@ *ptmp = (@type@ *)ip; return (npy_bool) @nonzero@(*ptmp); } else { /* * Don't worry about swapping for integer types, * since we are just testing for equality with 0. * For float types, the signed zeros require us to swap. */ @type@ tmp; #if @isfloat@ PyArray_DESCR(ap)->f->copyswap(&tmp, ip, !PyArray_ISNOTSWAPPED(ap), ap); #else memcpy(&tmp, ip, sizeof(@type@)); #endif return (npy_bool) @nonzero@(tmp); } } /**end repeat**/ /**begin repeat * * #fname = CFLOAT, CDOUBLE, CLONGDOUBLE# * #type = npy_cfloat, npy_cdouble, npy_clongdouble# */ static npy_bool @fname@_nonzero (char *ip, PyArrayObject *ap) { if (ap == NULL || PyArray_ISBEHAVED_RO(ap)) { @type@ *ptmp = (@type@ *)ip; return (npy_bool) ((ptmp->real != 0) || (ptmp->imag != 0)); } else { @type@ tmp; PyArray_DESCR(ap)->f->copyswap(&tmp, ip, !PyArray_ISNOTSWAPPED(ap), ap); return (npy_bool) ((tmp.real != 0) || (tmp.imag != 0)); } } /**end repeat**/ #define WHITESPACE " \t\n\r\v\f" #define WHITELEN 6 static npy_bool Py_STRING_ISSPACE(char ch) { char white[] = WHITESPACE; int j; npy_bool space = NPY_FALSE; for (j = 0; j < WHITELEN; j++) { if (ch == white[j]) { space = NPY_TRUE; break; } } return space; } static npy_bool STRING_nonzero (char *ip, PyArrayObject *ap) { int len = PyArray_DESCR(ap)->elsize; int i; npy_bool nonz = NPY_FALSE; for (i = 0; i < len; i++) { if (!Py_STRING_ISSPACE(*ip)) { nonz = NPY_TRUE; break; } ip++; } return nonz; } #ifdef Py_UNICODE_WIDE #define PyArray_UCS4_ISSPACE Py_UNICODE_ISSPACE #else #define PyArray_UCS4_ISSPACE(ch) Py_STRING_ISSPACE((char)ch) #endif static npy_bool UNICODE_nonzero (npy_ucs4 *ip, PyArrayObject *ap) { int len = PyArray_DESCR(ap)->elsize >> 2; int i; npy_bool nonz = NPY_FALSE; char *buffer = NULL; if ((!PyArray_ISNOTSWAPPED(ap)) || (!PyArray_ISALIGNED(ap))) { buffer = PyArray_malloc(PyArray_DESCR(ap)->elsize); if (buffer == NULL) { return nonz; } memcpy(buffer, ip, PyArray_DESCR(ap)->elsize); if (!PyArray_ISNOTSWAPPED(ap)) { byte_swap_vector(buffer, len, 4); } ip = (npy_ucs4 *)buffer; } for (i = 0; i < len; i++) { if (!PyArray_UCS4_ISSPACE(*ip)) { nonz = NPY_TRUE; break; } ip++; } PyArray_free(buffer); return nonz; } static npy_bool OBJECT_nonzero (PyObject **ip, PyArrayObject *ap) { if (PyArray_ISALIGNED(ap)) { if (*ip == NULL) { return NPY_FALSE; } return (npy_bool) PyObject_IsTrue(*ip); } else { PyObject *obj; NPY_COPY_PYOBJECT_PTR(&obj, ip); if (obj == NULL) { return NPY_FALSE; } return (npy_bool) PyObject_IsTrue(obj); } } /* * if we have fields, then nonzero only if all sub-fields are nonzero. */ static npy_bool VOID_nonzero (char *ip, PyArrayObject *ap) { int i; int len; npy_bool nonz = NPY_FALSE; if (PyArray_HASFIELDS(ap)) { PyArray_Descr *descr, *new; PyObject *key, *value, *title; int savedflags, offset; 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) { continue; } if (!PyArg_ParseTuple(value, "Oi|O", &new, &offset, &title)) { PyErr_Clear(); continue; } /* * TODO: temporarily modifying the array like this * is bad coding style, should be changed. */ ((PyArrayObject_fields *)ap)->descr = new; ((PyArrayObject_fields *)ap)->flags = savedflags; if ((new->alignment > 1) && !__ALIGNED(ip + offset, new->alignment)) { PyArray_CLEARFLAGS(ap, NPY_ARRAY_ALIGNED); } else { PyArray_ENABLEFLAGS(ap, NPY_ARRAY_ALIGNED); } if (new->f->nonzero(ip+offset, ap)) { nonz = NPY_TRUE; break; } } ((PyArrayObject_fields *)ap)->descr = descr; ((PyArrayObject_fields *)ap)->flags = savedflags; return nonz; } len = PyArray_DESCR(ap)->elsize; for (i = 0; i < len; i++) { if (*ip != '\0') { nonz = NPY_TRUE; break; } ip++; } return nonz; } #undef __ALIGNED /* ***************************************************************************** ** COMPARE ** ***************************************************************************** */ /* boolean type */ static int BOOL_compare(npy_bool *ip1, npy_bool *ip2, PyArrayObject *NPY_UNUSED(ap)) { return (*ip1 ? (*ip2 ? 0 : 1) : (*ip2 ? -1 : 0)); } /* integer types */ /**begin repeat * #TYPE = BYTE, UBYTE, SHORT, USHORT, INT, UINT, * LONG, ULONG, LONGLONG, ULONGLONG, * DATETIME, TIMEDELTA# * #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# */ static int @TYPE@_compare (@type@ *pa, @type@ *pb, PyArrayObject *NPY_UNUSED(ap)) { const @type@ a = *pa; const @type@ b = *pb; return a < b ? -1 : a == b ? 0 : 1; } /**end repeat**/ /* float types */ /* * The real/complex comparison functions are compatible with the new sort * order for nans introduced in numpy 1.4.0. All nan values now compare * larger than non-nan values and are sorted to the end. The comparison * order is: * * Real: [R, nan] * Complex: [R + Rj, R + nanj, nan + Rj, nan + nanj] * * where complex values with the same nan placements are sorted according * to the non-nan part if it exists. If both the real and imaginary parts * of complex types are non-nan the order is the same as the real parts * unless they happen to be equal, in which case the order is that of the * imaginary parts. */ /**begin repeat * * #TYPE = FLOAT, DOUBLE, LONGDOUBLE# * #type = npy_float, npy_double, npy_longdouble# */ #define LT(a,b) ((a) < (b) || ((b) != (b) && (a) ==(a))) static int @TYPE@_compare(@type@ *pa, @type@ *pb) { const @type@ a = *pa; const @type@ b = *pb; int ret; if (LT(a,b)) { ret = -1; } else if (LT(b,a)) { ret = 1; } else { ret = 0; } return ret; } static int C@TYPE@_compare(@type@ *pa, @type@ *pb) { const @type@ ar = pa[0]; const @type@ ai = pa[1]; const @type@ br = pb[0]; const @type@ bi = pb[1]; int ret; if (ar < br) { if (ai == ai || bi != bi) { ret = -1; } else { ret = 1; } } else if (br < ar) { if (bi == bi || ai != ai) { ret = 1; } else { ret = -1; } } else if (ar == br || (ar != ar && br != br)) { if (LT(ai,bi)) { ret = -1; } else if (LT(bi,ai)) { ret = 1; } else { ret = 0; } } else if (ar == ar) { ret = -1; } else { ret = 1; } return ret; } #undef LT /**end repeat**/ static int HALF_compare (npy_half *pa, npy_half *pb, PyArrayObject *NPY_UNUSED(ap)) { npy_half a = *pa, b = *pb; npy_bool a_isnan, b_isnan; int ret; a_isnan = npy_half_isnan(a); b_isnan = npy_half_isnan(b); if (a_isnan) { ret = b_isnan ? 0 : -1; } else if (b_isnan) { ret = 1; } else if(npy_half_lt_nonan(a, b)) { ret = -1; } else if(npy_half_lt_nonan(b, a)) { ret = 1; } else { ret = 0; } return ret; } /* object type */ static int OBJECT_compare(PyObject **ip1, PyObject **ip2, PyArrayObject *NPY_UNUSED(ap)) { /* * ALIGNMENT NOTE: It seems that PyArray_Sort is already handling * the alignment of pointers, so it doesn't need to be handled * here. */ if ((*ip1 == NULL) || (*ip2 == NULL)) { if (ip1 == ip2) { return 1; } if (ip1 == NULL) { return -1; } return 1; } #if defined(NPY_PY3K) if (PyObject_RichCompareBool(*ip1, *ip2, Py_LT) == 1) { return -1; } else if (PyObject_RichCompareBool(*ip1, *ip2, Py_GT) == 1) { return 1; } else { return 0; } #else return PyObject_Compare(*ip1, *ip2); #endif } /* string type */ static int STRING_compare(char *ip1, char *ip2, PyArrayObject *ap) { const unsigned char *c1 = (unsigned char *)ip1; const unsigned char *c2 = (unsigned char *)ip2; const size_t len = PyArray_DESCR(ap)->elsize; size_t i; for(i = 0; i < len; ++i) { if (c1[i] != c2[i]) { return (c1[i] > c2[i]) ? 1 : -1; } } return 0; } /* unicode type */ static int UNICODE_compare(npy_ucs4 *ip1, npy_ucs4 *ip2, PyArrayObject *ap) { int itemsize = PyArray_DESCR(ap)->elsize; if (itemsize < 0) { return 0; } itemsize /= sizeof(npy_ucs4); while (itemsize-- > 0) { npy_ucs4 c1 = *ip1++; npy_ucs4 c2 = *ip2++; if (c1 != c2) { return (c1 < c2) ? -1 : 1; } } return 0; } /* void type */ /* * If fields are defined, then compare on first field and if equal * compare on second field. Continue until done or comparison results * in not_equal. * * Must align data passed on to sub-comparisons. * Also must swap data based on to sub-comparisons. */ static int VOID_compare(char *ip1, char *ip2, PyArrayObject *ap) { PyArray_Descr *descr, *new; PyObject *names, *key; PyObject *tup, *title; char *nip1, *nip2; int i, offset, res = 0, swap=0; if (!PyArray_HASFIELDS(ap)) { return STRING_compare(ip1, ip2, ap); } descr = PyArray_DESCR(ap); /* * Compare on the first-field. If equal, then * compare on the second-field, etc. */ names = descr->names; for (i = 0; i < PyTuple_GET_SIZE(names); i++) { key = PyTuple_GET_ITEM(names, i); tup = PyDict_GetItem(descr->fields, key); if (!PyArg_ParseTuple(tup, "Oi|O", &new, &offset, &title)) { goto finish; } /* * TODO: temporarily modifying the array like this * is bad coding style, should be changed. */ ((PyArrayObject_fields *)ap)->descr = new; swap = PyArray_ISBYTESWAPPED(ap); nip1 = ip1 + offset; nip2 = ip2 + offset; if ((swap) || (new->alignment > 1)) { if ((swap) || (((npy_intp)(nip1) % new->alignment) != 0)) { /* create buffer and copy */ nip1 = PyArray_malloc(new->elsize); if (nip1 == NULL) { goto finish; } memcpy(nip1, ip1+offset, new->elsize); if (swap) new->f->copyswap(nip1, NULL, swap, ap); } if ((swap) || (((npy_intp)(nip2) % new->alignment) != 0)) { /* copy data to a buffer */ nip2 = PyArray_malloc(new->elsize); if (nip2 == NULL) { if (nip1 != ip1 + offset) { PyArray_free(nip1); } goto finish; } memcpy(nip2, ip2 + offset, new->elsize); if (swap) new->f->copyswap(nip2, NULL, swap, ap); } } res = new->f->compare(nip1, nip2, ap); if ((swap) || (new->alignment > 1)) { if (nip1 != ip1 + offset) { PyArray_free(nip1); } if (nip2 != ip2 + offset) { PyArray_free(nip2); } } if (res != 0) { break; } } finish: ((PyArrayObject_fields *)ap)->descr = descr; return res; } /* ***************************************************************************** ** ARGFUNC ** ***************************************************************************** */ #define _LESS_THAN_OR_EQUAL(a,b) ((a) <= (b)) /**begin repeat * * #fname = 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_half, npy_float, npy_double, npy_longdouble, * npy_float, npy_double, npy_longdouble, * npy_datetime, npy_timedelta# * #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# * #iscomplex = 0*15, 1*3, 0*2# * #incr = ip++*15, ip+=2*3, ip++*2# */ static int @fname@_argmax(@type@ *ip, npy_intp n, npy_intp *max_ind, PyArrayObject *NPY_UNUSED(aip)) { npy_intp i; @type@ mp = *ip; #if @iscomplex@ @type@ mp_im = ip[1]; #endif *max_ind = 0; #if @isfloat@ if (@isnan@(mp)) { /* nan encountered; it's maximal */ return 0; } #endif #if @iscomplex@ if (@isnan@(mp_im)) { /* nan encountered; it's maximal */ return 0; } #endif for (i = 1; i < n; i++) { @incr@; /* * Propagate nans, similarly as max() and min() */ #if @iscomplex@ /* Lexical order for complex numbers */ if ((ip[0] > mp) || ((ip[0] == mp) && (ip[1] > mp_im)) || @isnan@(ip[0]) || @isnan@(ip[1])) { mp = ip[0]; mp_im = ip[1]; *max_ind = i; if (@isnan@(mp) || @isnan@(mp_im)) { /* nan encountered, it's maximal */ break; } } #else if (!@le@(*ip, mp)) { /* negated, for correct nan handling */ mp = *ip; *max_ind = i; #if @isfloat@ if (@isnan@(mp)) { /* nan encountered, it's maximal */ break; } #endif } #endif } return 0; } /**end repeat**/ /**begin repeat * * #fname = 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_half, npy_float, npy_double, npy_longdouble, * npy_float, npy_double, npy_longdouble, * npy_datetime, npy_timedelta# * #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# * #iscomplex = 0*15, 1*3, 0*2# * #incr = ip++*15, ip+=2*3, ip++*2# */ static int @fname@_argmin(@type@ *ip, npy_intp n, npy_intp *min_ind, PyArrayObject *NPY_UNUSED(aip)) { npy_intp i; @type@ mp = *ip; #if @iscomplex@ @type@ mp_im = ip[1]; #endif *min_ind = 0; #if @isfloat@ if (@isnan@(mp)) { /* nan encountered; it's minimal */ return 0; } #endif #if @iscomplex@ if (@isnan@(mp_im)) { /* nan encountered; it's minimal */ return 0; } #endif for (i = 1; i < n; i++) { @incr@; /* * Propagate nans, similarly as max() and min() */ #if @iscomplex@ /* Lexical order for complex numbers */ if ((mp > ip[0]) || ((ip[0] == mp) && (mp_im > ip[1])) || @isnan@(ip[0]) || @isnan@(ip[1])) { mp = ip[0]; mp_im = ip[1]; *min_ind = i; if (@isnan@(mp) || @isnan@(mp_im)) { /* nan encountered, it's minimal */ break; } } #else if (!@le@(mp, *ip)) { /* negated, for correct nan handling */ mp = *ip; *min_ind = i; #if @isfloat@ if (@isnan@(mp)) { /* nan encountered, it's minimal */ break; } #endif } #endif } return 0; } /**end repeat**/ #undef _LESS_THAN_OR_EQUAL static int OBJECT_argmax(PyObject **ip, npy_intp n, npy_intp *max_ind, PyArrayObject *NPY_UNUSED(aip)) { npy_intp i; PyObject *mp = ip[0]; *max_ind = 0; i = 1; while (i < n && mp == NULL) { mp = ip[i]; i++; } for (; i < n; i++) { ip++; #if defined(NPY_PY3K) if (*ip != NULL && PyObject_RichCompareBool(*ip, mp, Py_GT) == 1) { #else if (*ip != NULL && PyObject_Compare(*ip, mp) > 0) { #endif mp = *ip; *max_ind = i; } } return 0; } /**begin repeat * * #fname = STRING, UNICODE# * #type = npy_char, npy_ucs4# */ static int @fname@_argmax(@type@ *ip, npy_intp n, npy_intp *max_ind, PyArrayObject *aip) { npy_intp i; int elsize = PyArray_DESCR(aip)->elsize; @type@ *mp = (@type@ *)PyArray_malloc(elsize); if (mp == NULL) { return 0; } memcpy(mp, ip, elsize); *max_ind = 0; for (i = 1; i < n; i++) { ip += elsize; if (@fname@_compare(ip, mp, aip) > 0) { memcpy(mp, ip, elsize); *max_ind = i; } } PyArray_free(mp); return 0; } /**end repeat**/ #define VOID_argmax NULL static int OBJECT_argmin(PyObject **ip, npy_intp n, npy_intp *min_ind, PyArrayObject *NPY_UNUSED(aip)) { npy_intp i; PyObject *mp = ip[0]; *min_ind = 0; i = 1; while (i < n && mp == NULL) { mp = ip[i]; i++; } for (; i < n; i++) { ip++; #if defined(NPY_PY3K) if (*ip != NULL && PyObject_RichCompareBool(mp, *ip, Py_GT) == 1) { #else if (*ip != NULL && PyObject_Compare(mp, *ip) > 0) { #endif mp = *ip; *min_ind = i; } } return 0; } /**begin repeat * * #fname = STRING, UNICODE# * #type = npy_char, npy_ucs4# */ static int @fname@_argmin(@type@ *ip, npy_intp n, npy_intp *min_ind, PyArrayObject *aip) { npy_intp i; int elsize = PyArray_DESCR(aip)->elsize; @type@ *mp = (@type@ *)PyArray_malloc(elsize); if (mp==NULL) return 0; memcpy(mp, ip, elsize); *min_ind = 0; for(i=1; i 0) { memcpy(mp, ip, elsize); *min_ind=i; } } PyArray_free(mp); return 0; } /**end repeat**/ #define VOID_argmin NULL /* ***************************************************************************** ** DOT ** ***************************************************************************** */ /* * dot means inner product */ static void BOOL_dot(char *ip1, npy_intp is1, char *ip2, npy_intp is2, char *op, npy_intp n, void *NPY_UNUSED(ignore)) { npy_bool tmp = NPY_FALSE; npy_intp i; for (i = 0; i < n; i++, ip1 += is1, ip2 += is2) { if ((*((npy_bool *)ip1) != 0) && (*((npy_bool *)ip2) != 0)) { tmp = NPY_TRUE; break; } } *((npy_bool *)op) = tmp; } /**begin repeat * * #name = BYTE, UBYTE, SHORT, USHORT, INT, UINT, * LONG, ULONG, LONGLONG, ULONGLONG, * FLOAT, DOUBLE, LONGDOUBLE, * DATETIME, TIMEDELTA# * #type = npy_byte, npy_ubyte, npy_short, npy_ushort, npy_int, npy_uint, * npy_long, npy_ulong, npy_longlong, npy_ulonglong, * npy_float, npy_double, npy_longdouble, * npy_datetime, npy_timedelta# * #out = npy_long, npy_ulong, npy_long, npy_ulong, npy_long, npy_ulong, * npy_long, npy_ulong, npy_longlong, npy_ulonglong, * npy_float, npy_double, npy_longdouble, * npy_datetime, npy_timedelta# */ static void @name@_dot(char *ip1, npy_intp is1, char *ip2, npy_intp is2, char *op, npy_intp n, void *NPY_UNUSED(ignore)) { @out@ tmp = (@out@)0; npy_intp i; for (i = 0; i < n; i++, ip1 += is1, ip2 += is2) { tmp += (@out@)(*((@type@ *)ip1)) * (@out@)(*((@type@ *)ip2)); } *((@type@ *)op) = (@type@) tmp; } /**end repeat**/ static void HALF_dot(char *ip1, npy_intp is1, char *ip2, npy_intp is2, char *op, npy_intp n, void *NPY_UNUSED(ignore)) { float tmp = 0.0f; npy_intp i; for (i = 0; i < n; i++, ip1 += is1, ip2 += is2) { tmp += npy_half_to_float(*((npy_half *)ip1)) * npy_half_to_float(*((npy_half *)ip2)); } *((npy_half *)op) = npy_float_to_half(tmp); } /**begin repeat * * #name = CFLOAT, CDOUBLE, CLONGDOUBLE# * #type = npy_float, npy_double, npy_longdouble# */ static void @name@_dot(char *ip1, npy_intp is1, char *ip2, npy_intp is2, char *op, npy_intp n, void *NPY_UNUSED(ignore)) { @type@ tmpr = (@type@)0.0, tmpi=(@type@)0.0; npy_intp i; for (i = 0; i < n; i++, ip1 += is1, ip2 += is2) { tmpr += ((@type@ *)ip1)[0] * ((@type@ *)ip2)[0] - ((@type@ *)ip1)[1] * ((@type@ *)ip2)[1]; tmpi += ((@type@ *)ip1)[1] * ((@type@ *)ip2)[0] + ((@type@ *)ip1)[0] * ((@type@ *)ip2)[1]; } ((@type@ *)op)[0] = tmpr; ((@type@ *)op)[1] = tmpi; } /**end repeat**/ static void OBJECT_dot(char *ip1, npy_intp is1, char *ip2, npy_intp is2, char *op, npy_intp n, void *NPY_UNUSED(ignore)) { /* * ALIGNMENT NOTE: np.dot, np.inner etc. enforce that the array is * BEHAVED before getting to this point, so unaligned pointers aren't * handled here. */ npy_intp i; PyObject *tmp1, *tmp2, *tmp = NULL; PyObject **tmp3; for (i = 0; i < n; i++, ip1 += is1, ip2 += is2) { if ((*((PyObject **)ip1) == NULL) || (*((PyObject **)ip2) == NULL)) { tmp1 = Py_False; Py_INCREF(Py_False); } else { tmp1 = PyNumber_Multiply(*((PyObject **)ip1), *((PyObject **)ip2)); if (!tmp1) { Py_XDECREF(tmp); return; } } if (i == 0) { tmp = tmp1; } else { tmp2 = PyNumber_Add(tmp, tmp1); Py_XDECREF(tmp); Py_XDECREF(tmp1); if (!tmp2) { return; } tmp = tmp2; } } tmp3 = (PyObject**) op; tmp2 = *tmp3; *((PyObject **)op) = tmp; Py_XDECREF(tmp2); } /* ***************************************************************************** ** FILL ** ***************************************************************************** */ #define BOOL_fill NULL /* this requires buffer to be filled with objects or NULL */ static void OBJECT_fill(PyObject **buffer, npy_intp length, void *NPY_UNUSED(ignored)) { npy_intp i; PyObject *start = buffer[0]; PyObject *delta = buffer[1]; PyObject *second; delta = PyNumber_Subtract(delta, start); if (!delta) { return; } second = start = PyNumber_Add(start, delta); if (!start) { goto finish; } buffer += 2; for (i = 2; i < length; i++, buffer++) { start = PyNumber_Add(start, delta); if (!start) { goto finish; } Py_XDECREF(*buffer); *buffer = start; } finish: Py_XDECREF(second); Py_DECREF(delta); return; } /**begin repeat * * #NAME = BYTE, UBYTE, SHORT, USHORT, INT, UINT, * LONG, ULONG, LONGLONG, ULONGLONG, * FLOAT, DOUBLE, LONGDOUBLE, * DATETIME, TIMEDELTA# * #type = npy_byte, npy_ubyte, npy_short, npy_ushort, npy_int, npy_uint, * npy_long, npy_ulong, npy_longlong, npy_ulonglong, * npy_float, npy_double, npy_longdouble, * npy_datetime, npy_timedelta# */ static void @NAME@_fill(@type@ *buffer, npy_intp length, void *NPY_UNUSED(ignored)) { npy_intp i; @type@ start = buffer[0]; @type@ delta = buffer[1]; delta -= start; for (i = 2; i < length; ++i) { buffer[i] = start + i*delta; } } /**end repeat**/ static void HALF_fill(npy_half *buffer, npy_intp length, void *NPY_UNUSED(ignored)) { npy_intp i; float start = npy_half_to_float(buffer[0]); float delta = npy_half_to_float(buffer[1]); delta -= start; for (i = 2; i < length; ++i) { buffer[i] = npy_float_to_half(start + i*delta); } } /**begin repeat * * #NAME = CFLOAT, CDOUBLE, CLONGDOUBLE# * #type = npy_cfloat, npy_cdouble, npy_clongdouble# */ static void @NAME@_fill(@type@ *buffer, npy_intp length, void *NPY_UNUSED(ignore)) { npy_intp i; @type@ start; @type@ delta; start.real = buffer->real; start.imag = buffer->imag; delta.real = buffer[1].real; delta.imag = buffer[1].imag; delta.real -= start.real; delta.imag -= start.imag; buffer += 2; for (i = 2; i < length; i++, buffer++) { buffer->real = start.real + i*delta.real; buffer->imag = start.imag + i*delta.imag; } } /**end repeat**/ /* this requires buffer to be filled with objects or NULL */ static void OBJECT_fillwithscalar(PyObject **buffer, npy_intp length, PyObject **value, void *NPY_UNUSED(ignored)) { npy_intp i; PyObject *val = *value; for (i = 0; i < length; i++) { Py_XINCREF(val); Py_XDECREF(buffer[i]); buffer[i] = val; } } /**begin repeat * * #NAME = BOOL, BYTE, UBYTE# * #type = npy_bool, npy_byte, npy_ubyte# */ static void @NAME@_fillwithscalar(@type@ *buffer, npy_intp length, @type@ *value, void *NPY_UNUSED(ignored)) { memset(buffer, *value, length); } /**end repeat**/ /**begin repeat * * #NAME = SHORT, USHORT, INT, UINT, * LONG, ULONG, LONGLONG, ULONGLONG, * HALF, FLOAT, DOUBLE, LONGDOUBLE, * CFLOAT, CDOUBLE, CLONGDOUBLE, * DATETIME, TIMEDELTA# * #type = npy_short, npy_ushort, npy_int, npy_uint, * npy_long, npy_ulong, npy_longlong, npy_ulonglong, * npy_half, npy_float, npy_double, npy_longdouble, * npy_cfloat, npy_cdouble, npy_clongdouble, * npy_datetime, npy_timedelta# */ static void @NAME@_fillwithscalar(@type@ *buffer, npy_intp length, @type@ *value, void *NPY_UNUSED(ignored)) { npy_intp i; @type@ val = *value; for (i = 0; i < length; ++i) { buffer[i] = val; } } /**end repeat**/ /* ***************************************************************************** ** FASTCLIP ** ***************************************************************************** */ #define _LESS_THAN(a, b) ((a) < (b)) #define _GREATER_THAN(a, b) ((a) > (b)) /* * In fastclip, 'b' was already checked for NaN, so the half comparison * only needs to check 'a' for NaN. */ #define _HALF_LESS_THAN(a, b) (!npy_half_isnan(a) && npy_half_lt_nonan(a, b)) #define _HALF_GREATER_THAN(a, b) (!npy_half_isnan(a) && npy_half_lt_nonan(b, a)) /**begin repeat * * #name = BOOL, * BYTE, UBYTE, SHORT, USHORT, INT, UINT, * LONG, ULONG, LONGLONG, ULONGLONG, * HALF, FLOAT, DOUBLE, LONGDOUBLE, * 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_half, npy_float, npy_double, npy_longdouble, * npy_datetime, npy_timedelta# * #isfloat = 0*11, 1*4, 0*2# * #isnan = nop*11, npy_half_isnan, npy_isnan*3, nop*2# * #lt = _LESS_THAN*11, _HALF_LESS_THAN, _LESS_THAN*5# * #gt = _GREATER_THAN*11, _HALF_GREATER_THAN, _GREATER_THAN*5# */ static void @name@_fastclip(@type@ *in, npy_intp ni, @type@ *min, @type@ *max, @type@ *out) { npy_intp i; @type@ max_val = 0, min_val = 0; if (max != NULL) { max_val = *max; #if @isfloat@ /* NaNs result in no clipping, so optimize the case away */ if (@isnan@(max_val)) { if (min == NULL) { return; } max = NULL; } #endif } if (min != NULL) { min_val = *min; #if @isfloat@ if (@isnan@(min_val)) { if (max == NULL) { return; } min = NULL; } #endif } if (max == NULL) { for (i = 0; i < ni; i++) { if (@lt@(in[i], min_val)) { out[i] = min_val; } } } else if (min == NULL) { for (i = 0; i < ni; i++) { if (@gt@(in[i], max_val)) { out[i] = max_val; } } } else { for (i = 0; i < ni; i++) { if (@lt@(in[i], min_val)) { out[i] = min_val; } else if (@gt@(in[i], max_val)) { out[i] = max_val; } } } } /**end repeat**/ #undef _LESS_THAN #undef _GREATER_THAN #undef _HALF_LESS_THAN #undef _HALF_GREATER_THAN /**begin repeat * * #name = CFLOAT, CDOUBLE, CLONGDOUBLE# * #type = npy_cfloat, npy_cdouble, npy_clongdouble# */ static void @name@_fastclip(@type@ *in, npy_intp ni, @type@ *min, @type@ *max, @type@ *out) { npy_intp i; @type@ max_val, min_val; min_val = *min; max_val = *max; if (max != NULL) { max_val = *max; } if (min != NULL) { min_val = *min; } if (max == NULL) { for (i = 0; i < ni; i++) { if (PyArray_CLT(in[i],min_val)) { out[i] = min_val; } } } else if (min == NULL) { for (i = 0; i < ni; i++) { if (PyArray_CGT(in[i], max_val)) { out[i] = max_val; } } } else { for (i = 0; i < ni; i++) { if (PyArray_CLT(in[i], min_val)) { out[i] = min_val; } else if (PyArray_CGT(in[i], max_val)) { out[i] = max_val; } } } } /**end repeat**/ #define OBJECT_fastclip NULL /* ***************************************************************************** ** FASTPUTMASK ** ***************************************************************************** */ /**begin repeat * * #name = 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_half, npy_float, npy_double, npy_longdouble, * npy_cfloat, npy_cdouble, npy_clongdouble, * npy_datetime, npy_timedelta# */ static void @name@_fastputmask(@type@ *in, npy_bool *mask, npy_intp ni, @type@ *vals, npy_intp nv) { npy_intp i; @type@ s_val; if (nv == 1) { s_val = *vals; for (i = 0; i < ni; i++) { if (mask[i]) { in[i] = s_val; } } } else { for (i = 0; i < ni; i++) { if (mask[i]) { in[i] = vals[i%nv]; } } } return; } /**end repeat**/ #define OBJECT_fastputmask NULL /* ***************************************************************************** ** FASTTAKE ** ***************************************************************************** */ /**begin repeat * * #name = 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_half, npy_float, npy_double, npy_longdouble, * npy_cfloat, npy_cdouble, npy_clongdouble, * npy_datetime, npy_timedelta# */ static int @name@_fasttake(@type@ *dest, @type@ *src, npy_intp *indarray, npy_intp nindarray, npy_intp n_outer, npy_intp m_middle, npy_intp nelem, NPY_CLIPMODE clipmode) { npy_intp i, j, k, tmp; 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) return 1; if (NPY_LIKELY(nelem == 1)) { *dest++ = *(src + tmp); } else { for (k = 0; k < nelem; k++) { *dest++ = *(src + tmp*nelem + k); } } } src += nelem*nindarray; } break; case NPY_WRAP: for (i = 0; i < n_outer; i++) { for (j = 0; j < m_middle; j++) { tmp = indarray[j]; if (tmp < 0) { while (tmp < 0) { tmp += nindarray; } } else if (tmp >= nindarray) { while (tmp >= nindarray) { tmp -= nindarray; } } if (NPY_LIKELY(nelem == 1)) { *dest++ = *(src+tmp); } else { for (k = 0; k < nelem; k++) { *dest++ = *(src+tmp*nelem+k); } } } src += nelem*nindarray; } break; case NPY_CLIP: for (i = 0; i < n_outer; i++) { for (j = 0; j < m_middle; j++) { tmp = indarray[j]; if (tmp < 0) { tmp = 0; } else if (tmp >= nindarray) { tmp = nindarray - 1; } if (NPY_LIKELY(nelem == 1)) { *dest++ = *(src + tmp); } else { for (k = 0; k < nelem; k++) { *dest++ = *(src + tmp*nelem + k); } } } src += nelem*nindarray; } break; } return 0; } /**end repeat**/ #define OBJECT_fasttake NULL /* ***************************************************************************** ** SETUP FUNCTION POINTERS ** ***************************************************************************** */ #define _ALIGN(type) offsetof(struct {char c; type v;}, v) /* * Disable harmless compiler warning "4116: unnamed type definition in * parentheses" which is caused by the _ALIGN macro. */ #if defined(_MSC_VER) #pragma warning(disable:4116) #endif /**begin repeat * * #from = VOID, STRING, UNICODE# * #suff = void, string, unicode# * #sort = 0, 1, 1# * #align = char, char, npy_ucs4# * #NAME = Void, String, Unicode# * #endian = |, |, =# */ static PyArray_ArrFuncs _Py@NAME@_ArrFuncs = { { (PyArray_VectorUnaryFunc*)@from@_to_BOOL, (PyArray_VectorUnaryFunc*)@from@_to_BYTE, (PyArray_VectorUnaryFunc*)@from@_to_UBYTE, (PyArray_VectorUnaryFunc*)@from@_to_SHORT, (PyArray_VectorUnaryFunc*)@from@_to_USHORT, (PyArray_VectorUnaryFunc*)@from@_to_INT, (PyArray_VectorUnaryFunc*)@from@_to_UINT, (PyArray_VectorUnaryFunc*)@from@_to_LONG, (PyArray_VectorUnaryFunc*)@from@_to_ULONG, (PyArray_VectorUnaryFunc*)@from@_to_LONGLONG, (PyArray_VectorUnaryFunc*)@from@_to_ULONGLONG, (PyArray_VectorUnaryFunc*)@from@_to_FLOAT, (PyArray_VectorUnaryFunc*)@from@_to_DOUBLE, (PyArray_VectorUnaryFunc*)@from@_to_LONGDOUBLE, (PyArray_VectorUnaryFunc*)@from@_to_CFLOAT, (PyArray_VectorUnaryFunc*)@from@_to_CDOUBLE, (PyArray_VectorUnaryFunc*)@from@_to_CLONGDOUBLE, (PyArray_VectorUnaryFunc*)@from@_to_OBJECT, (PyArray_VectorUnaryFunc*)@from@_to_STRING, (PyArray_VectorUnaryFunc*)@from@_to_UNICODE, (PyArray_VectorUnaryFunc*)@from@_to_VOID }, (PyArray_GetItemFunc*)@from@_getitem, (PyArray_SetItemFunc*)@from@_setitem, (PyArray_CopySwapNFunc*)@from@_copyswapn, (PyArray_CopySwapFunc*)@from@_copyswap, (PyArray_CompareFunc*)@from@_compare, (PyArray_ArgFunc*)@from@_argmax, (PyArray_DotFunc*)NULL, (PyArray_ScanFunc*)@from@_scan, (PyArray_FromStrFunc*)@from@_fromstr, (PyArray_NonzeroFunc*)@from@_nonzero, (PyArray_FillFunc*)NULL, (PyArray_FillWithScalarFunc*)NULL, #if @sort@ { (PyArray_SortFunc *)quicksort_@suff@, (PyArray_SortFunc *)heapsort_@suff@, (PyArray_SortFunc *)mergesort_@suff@ }, { (PyArray_ArgSortFunc *)aquicksort_@suff@, (PyArray_ArgSortFunc *)aheapsort_@suff@, (PyArray_ArgSortFunc *)amergesort_@suff@ }, #else { NULL, NULL, NULL }, { NULL, NULL, NULL }, #endif NULL, (PyArray_ScalarKindFunc*)NULL, NULL, NULL, (PyArray_FastClipFunc *)NULL, (PyArray_FastPutmaskFunc *)NULL, (PyArray_FastTakeFunc *)NULL, (PyArray_ArgFunc*)@from@_argmin }; /* * FIXME: check for PY3K */ static PyArray_Descr @from@_Descr = { PyObject_HEAD_INIT(&PyArrayDescr_Type) /* typeobj */ &Py@NAME@ArrType_Type, /* kind */ NPY_@from@LTR, /* type */ NPY_@from@LTR, /* byteorder */ '@endian@', /* flags */ 0, /* type_num */ NPY_@from@, /* elsize */ 0, /* alignment */ _ALIGN(@align@), /* subarray */ NULL, /* fields */ NULL, /* names */ NULL, /* f */ &_Py@NAME@_ArrFuncs, /* metadata */ NULL, /* c_metadata */ NULL, }; /**end repeat**/ /**begin repeat * * #from = BOOL, * BYTE, UBYTE, SHORT, USHORT, INT, UINT, * LONG, ULONG, LONGLONG, ULONGLONG, * HALF, FLOAT, DOUBLE, LONGDOUBLE, * CFLOAT, CDOUBLE, CLONGDOUBLE, * OBJECT, DATETIME, TIMEDELTA# * #suff = bool, * byte, ubyte, short, ushort, int, uint, * long, ulong, longlong, ulonglong, * half, float, double, longdouble, * cfloat, cdouble, clongdouble, * object, datetime, timedelta# * #sort = 1*18, 0*3# * #num = 1*15, 2*3, 1*3# * #fromtype = npy_bool, * npy_byte, npy_ubyte, npy_short, npy_ushort, npy_int, npy_uint, * npy_long, npy_ulong, npy_longlong, npy_ulonglong, * npy_half, npy_float, npy_double, npy_longdouble, * npy_float, npy_double, npy_longdouble, * PyObject *, npy_datetime, npy_timedelta# * #NAME = Bool, * Byte, UByte, Short, UShort, Int, UInt, * Long, ULong, LongLong, ULongLong, * Half, Float, Double, LongDouble, * CFloat, CDouble, CLongDouble, * Object, Datetime, Timedelta# * #kind = GENBOOL, * SIGNED, UNSIGNED, SIGNED, UNSIGNED, SIGNED, UNSIGNED, * SIGNED, UNSIGNED, SIGNED, UNSIGNED, * FLOATING, FLOATING, FLOATING, FLOATING, * COMPLEX, COMPLEX, COMPLEX, * OBJECT, DATETIME, TIMEDELTA# * #endian = |*3, =*15, |, =*2# * #isobject= 0*18,NPY_OBJECT_DTYPE_FLAGS,0*2# */ static PyArray_ArrFuncs _Py@NAME@_ArrFuncs = { { (PyArray_VectorUnaryFunc*)@from@_to_BOOL, (PyArray_VectorUnaryFunc*)@from@_to_BYTE, (PyArray_VectorUnaryFunc*)@from@_to_UBYTE, (PyArray_VectorUnaryFunc*)@from@_to_SHORT, (PyArray_VectorUnaryFunc*)@from@_to_USHORT, (PyArray_VectorUnaryFunc*)@from@_to_INT, (PyArray_VectorUnaryFunc*)@from@_to_UINT, (PyArray_VectorUnaryFunc*)@from@_to_LONG, (PyArray_VectorUnaryFunc*)@from@_to_ULONG, (PyArray_VectorUnaryFunc*)@from@_to_LONGLONG, (PyArray_VectorUnaryFunc*)@from@_to_ULONGLONG, (PyArray_VectorUnaryFunc*)@from@_to_FLOAT, (PyArray_VectorUnaryFunc*)@from@_to_DOUBLE, (PyArray_VectorUnaryFunc*)@from@_to_LONGDOUBLE, (PyArray_VectorUnaryFunc*)@from@_to_CFLOAT, (PyArray_VectorUnaryFunc*)@from@_to_CDOUBLE, (PyArray_VectorUnaryFunc*)@from@_to_CLONGDOUBLE, (PyArray_VectorUnaryFunc*)@from@_to_OBJECT, (PyArray_VectorUnaryFunc*)@from@_to_STRING, (PyArray_VectorUnaryFunc*)@from@_to_UNICODE, (PyArray_VectorUnaryFunc*)@from@_to_VOID }, (PyArray_GetItemFunc*)@from@_getitem, (PyArray_SetItemFunc*)@from@_setitem, (PyArray_CopySwapNFunc*)@from@_copyswapn, (PyArray_CopySwapFunc*)@from@_copyswap, (PyArray_CompareFunc*)@from@_compare, (PyArray_ArgFunc*)@from@_argmax, (PyArray_DotFunc*)@from@_dot, (PyArray_ScanFunc*)@from@_scan, (PyArray_FromStrFunc*)@from@_fromstr, (PyArray_NonzeroFunc*)@from@_nonzero, (PyArray_FillFunc*)@from@_fill, (PyArray_FillWithScalarFunc*)@from@_fillwithscalar, #if @sort@ { (PyArray_SortFunc *)quicksort_@suff@, (PyArray_SortFunc *)heapsort_@suff@, (PyArray_SortFunc *)mergesort_@suff@ }, { (PyArray_ArgSortFunc *)aquicksort_@suff@, (PyArray_ArgSortFunc *)aheapsort_@suff@, (PyArray_ArgSortFunc *)amergesort_@suff@ }, #else { NULL, NULL, NULL }, { NULL, NULL, NULL }, #endif NULL, (PyArray_ScalarKindFunc*)NULL, NULL, NULL, (PyArray_FastClipFunc*)@from@_fastclip, (PyArray_FastPutmaskFunc*)@from@_fastputmask, (PyArray_FastTakeFunc*)@from@_fasttake, (PyArray_ArgFunc*)@from@_argmin }; /* * FIXME: check for PY3K */ NPY_NO_EXPORT PyArray_Descr @from@_Descr = { PyObject_HEAD_INIT(&PyArrayDescr_Type) /* typeobj */ &Py@NAME@ArrType_Type, /* kind */ NPY_@kind@LTR, /* type */ NPY_@from@LTR, /* byteorder */ '@endian@', /* flags */ @isobject@, /* type_num */ NPY_@from@, /* elsize */ @num@ * sizeof(@fromtype@), /* alignment */ @num@ * _ALIGN(@fromtype@), /* subarray */ NULL, /* fields */ NULL, /* names */ NULL, /* f */ &_Py@NAME@_ArrFuncs, /* metadata */ NULL, /* c_metadata */ NULL, }; /**end repeat**/ #define _MAX_LETTER 128 static char _letter_to_num[_MAX_LETTER]; static PyArray_Descr *_builtin_descrs[] = { &BOOL_Descr, &BYTE_Descr, &UBYTE_Descr, &SHORT_Descr, &USHORT_Descr, &INT_Descr, &UINT_Descr, &LONG_Descr, &ULONG_Descr, &LONGLONG_Descr, &ULONGLONG_Descr, &FLOAT_Descr, &DOUBLE_Descr, &LONGDOUBLE_Descr, &CFLOAT_Descr, &CDOUBLE_Descr, &CLONGDOUBLE_Descr, &OBJECT_Descr, &STRING_Descr, &UNICODE_Descr, &VOID_Descr, &DATETIME_Descr, &TIMEDELTA_Descr, &HALF_Descr }; /*NUMPY_API * Get the PyArray_Descr structure for a type. */ NPY_NO_EXPORT PyArray_Descr * PyArray_DescrFromType(int type) { PyArray_Descr *ret = NULL; if (type < NPY_NTYPES) { ret = _builtin_descrs[type]; } else if (type == NPY_NOTYPE) { /* * This needs to not raise an error so * that PyArray_DescrFromType(NPY_NOTYPE) * works for backwards-compatible C-API */ return NULL; } else if ((type == NPY_CHAR) || (type == NPY_CHARLTR)) { ret = PyArray_DescrNew(_builtin_descrs[NPY_STRING]); if (ret == NULL) { return NULL; } ret->elsize = 1; ret->type = NPY_CHARLTR; return ret; } else if (PyTypeNum_ISUSERDEF(type)) { ret = userdescrs[type - NPY_USERDEF]; } else { int num = NPY_NTYPES; if (type < _MAX_LETTER) { num = (int) _letter_to_num[type]; } if (num >= NPY_NTYPES) { ret = NULL; } else { ret = _builtin_descrs[num]; } } if (ret == NULL) { PyErr_SetString(PyExc_ValueError, "Invalid data-type for array"); } else { Py_INCREF(ret); } return ret; } /* A clone function for the datetime dtype metadata */ static NpyAuxData * datetime_dtype_metadata_clone(NpyAuxData *data) { PyArray_DatetimeDTypeMetaData *newdata = (PyArray_DatetimeDTypeMetaData *)PyArray_malloc( sizeof(PyArray_DatetimeDTypeMetaData)); if (newdata == NULL) { return NULL; } memcpy(newdata, data, sizeof(PyArray_DatetimeDTypeMetaData)); return (NpyAuxData *)newdata; } /* * Initializes the c_metadata field for the _builtin_descrs DATETIME * and TIMEDELTA. */ int initialize_builtin_datetime_metadata(void) { PyArray_DatetimeDTypeMetaData *data1, *data2; /* Allocate memory for the metadata */ data1 = PyArray_malloc(sizeof(PyArray_DatetimeDTypeMetaData)); if (data1 == NULL) { return -1; } data2 = PyArray_malloc(sizeof(PyArray_DatetimeDTypeMetaData)); if (data2 == NULL) { PyArray_free(data1); return -1; } /* Initialize the base aux data */ memset(data1, 0, sizeof(PyArray_DatetimeDTypeMetaData)); memset(data2, 0, sizeof(PyArray_DatetimeDTypeMetaData)); data1->base.free = (NpyAuxData_FreeFunc *)PyArray_free; data2->base.free = (NpyAuxData_FreeFunc *)PyArray_free; data1->base.clone = datetime_dtype_metadata_clone; data2->base.clone = datetime_dtype_metadata_clone; /* Set to the default metadata */ data1->meta.base = NPY_DATETIME_DEFAULTUNIT; data1->meta.num = 1; data2->meta.base = NPY_DATETIME_DEFAULTUNIT; data2->meta.num = 1; _builtin_descrs[NPY_DATETIME]->c_metadata = (NpyAuxData *)data1; _builtin_descrs[NPY_TIMEDELTA]->c_metadata = (NpyAuxData *)data2; return 0; } /* ***************************************************************************** ** SETUP TYPE INFO ** ***************************************************************************** */ /* * This function is called during numpy module initialization, * and is used to initialize internal dtype tables. */ NPY_NO_EXPORT int set_typeinfo(PyObject *dict) { PyObject *infodict, *s; int i; PyArray_Descr *dtype; PyObject *cobj, *key; /* * Add cast functions for the new types */ /**begin repeat * * #name1 = BOOL, * BYTE, UBYTE, SHORT, USHORT, INT, UINT, * LONG, ULONG, LONGLONG, ULONGLONG, * HALF, FLOAT, DOUBLE, LONGDOUBLE, * CFLOAT, CDOUBLE, CLONGDOUBLE, * OBJECT, STRING, UNICODE, VOID, * DATETIME,TIMEDELTA# */ /**begin repeat1 * * #name2 = HALF, DATETIME, TIMEDELTA# */ dtype = _builtin_descrs[NPY_@name1@]; if (dtype->f->castdict == NULL) { dtype->f->castdict = PyDict_New(); if (dtype->f->castdict == NULL) { return -1; } } key = PyInt_FromLong(NPY_@name2@); if (key == NULL) { return -1; } cobj = NpyCapsule_FromVoidPtr((void *)@name1@_to_@name2@, NULL); if (cobj == NULL) { Py_DECREF(key); return -1; } if (PyDict_SetItem(dtype->f->castdict, key, cobj) < 0) { Py_DECREF(key); Py_DECREF(cobj); return -1; } Py_DECREF(key); Py_DECREF(cobj); /**end repeat1**/ /**end repeat**/ if (initialize_builtin_datetime_metadata() < 0) { return -1; } for (i = 0; i < _MAX_LETTER; i++) { _letter_to_num[i] = NPY_NTYPES; } /**begin repeat * * #name = BOOL, * BYTE, UBYTE, SHORT, USHORT, INT, UINT, * INTP, UINTP, * LONG, ULONG, LONGLONG, ULONGLONG, * HALF, FLOAT, DOUBLE, LONGDOUBLE, * CFLOAT, CDOUBLE, CLONGDOUBLE, * OBJECT, STRING, UNICODE, VOID, * DATETIME,TIMEDELTA# */ _letter_to_num[NPY_@name@LTR] = NPY_@name@; /**end repeat**/ _letter_to_num[NPY_STRINGLTR2] = NPY_STRING; /**begin repeat * #name = BOOL, * BYTE, UBYTE, SHORT, USHORT, INT, UINT, * LONG, ULONG, LONGLONG, ULONGLONG, * HALF, FLOAT, DOUBLE, LONGDOUBLE, * CFLOAT, CDOUBLE, CLONGDOUBLE, * OBJECT, STRING, UNICODE, VOID, * DATETIME, TIMEDELTA# */ @name@_Descr.fields = Py_None; /**end repeat**/ /* Set a dictionary with type information */ infodict = PyDict_New(); if (infodict == NULL) return -1; /**begin repeat * * #name = BOOL, * BYTE, UBYTE, SHORT, USHORT, INT, UINT, * INTP, UINTP, * LONG, ULONG, LONGLONG, ULONGLONG# * #uname = BOOL, * BYTE*2, SHORT*2, INT*2, * INTP*2, * LONG*2, LONGLONG*2# * #Name = Bool, * Byte, UByte, Short, UShort, Int, UInt, * Intp, UIntp, * Long, ULong, LongLong, ULongLong# * #type = npy_bool, * npy_byte, npy_ubyte, npy_short, npy_ushort, npy_int, npy_uint, * npy_intp, npy_uintp, * npy_long, npy_ulong, npy_longlong, npy_ulonglong# * #max= 1, * NPY_MAX_BYTE, NPY_MAX_UBYTE, NPY_MAX_SHORT, * NPY_MAX_USHORT, NPY_MAX_INT, PyLong_FromUnsignedLong(NPY_MAX_UINT), * PyLong_FromLongLong((npy_longlong) NPY_MAX_INTP), * PyLong_FromUnsignedLongLong((npy_ulonglong) NPY_MAX_UINTP), * NPY_MAX_LONG, * PyLong_FromUnsignedLong((npy_ulong) NPY_MAX_ULONG), * PyLong_FromLongLong((npy_longlong) NPY_MAX_LONGLONG), * PyLong_FromUnsignedLongLong((npy_ulonglong) NPY_MAX_ULONGLONG)# * #min = 0, NPY_MIN_BYTE, 0, NPY_MIN_SHORT, 0, NPY_MIN_INT, 0, * PyLong_FromLongLong((npy_longlong) NPY_MIN_INTP), * 0, NPY_MIN_LONG, 0, * PyLong_FromLongLong((npy_longlong) NPY_MIN_LONGLONG), 0# * #cx = i*6, N, N, N, l, N, N, N# * #cn = i*7, N, i, l, i, N, i# */ PyDict_SetItemString(infodict, "@name@", #if defined(NPY_PY3K) s = Py_BuildValue("Ciii@cx@@cn@O", #else s = Py_BuildValue("ciii@cx@@cn@O", #endif NPY_@name@LTR, NPY_@name@, NPY_BITSOF_@uname@, _ALIGN(@type@), @max@, @min@, (PyObject *) &Py@Name@ArrType_Type)); Py_DECREF(s); /**end repeat**/ /**begin repeat * * #type = npy_half, npy_float, npy_double, npy_longdouble, * npy_cfloat, npy_cdouble, npy_clongdouble# * #name = HALF, FLOAT, DOUBLE, LONGDOUBLE, * CFLOAT, CDOUBLE, CLONGDOUBLE# * #Name = Half, Float, Double, LongDouble, * CFloat, CDouble, CLongDouble# * #num = 1, 1, 1, 1, 2, 2, 2# */ PyDict_SetItemString(infodict, "@name@", #if defined(NPY_PY3K) s = Py_BuildValue("CiiiO", NPY_@name@LTR, #else s = Py_BuildValue("ciiiO", NPY_@name@LTR, #endif NPY_@name@, NPY_BITSOF_@name@, @num@ * _ALIGN(@type@), (PyObject *) &Py@Name@ArrType_Type)); Py_DECREF(s); /**end repeat**/ PyDict_SetItemString(infodict, "OBJECT", #if defined(NPY_PY3K) s = Py_BuildValue("CiiiO", NPY_OBJECTLTR, #else s = Py_BuildValue("ciiiO", NPY_OBJECTLTR, #endif NPY_OBJECT, sizeof(PyObject *) * CHAR_BIT, _ALIGN(PyObject *), (PyObject *) &PyObjectArrType_Type)); Py_DECREF(s); PyDict_SetItemString(infodict, "STRING", #if defined(NPY_PY3K) s = Py_BuildValue("CiiiO", NPY_STRINGLTR, #else s = Py_BuildValue("ciiiO", NPY_STRINGLTR, #endif NPY_STRING, 0, _ALIGN(char), (PyObject *) &PyStringArrType_Type)); Py_DECREF(s); PyDict_SetItemString(infodict, "UNICODE", #if defined(NPY_PY3K) s = Py_BuildValue("CiiiO", NPY_UNICODELTR, #else s = Py_BuildValue("ciiiO", NPY_UNICODELTR, #endif NPY_UNICODE, 0, _ALIGN(npy_ucs4), (PyObject *) &PyUnicodeArrType_Type)); Py_DECREF(s); PyDict_SetItemString(infodict, "VOID", #if defined(NPY_PY3K) s = Py_BuildValue("CiiiO", NPY_VOIDLTR, #else s = Py_BuildValue("ciiiO", NPY_VOIDLTR, #endif NPY_VOID, 0, _ALIGN(char), (PyObject *) &PyVoidArrType_Type)); Py_DECREF(s); PyDict_SetItemString(infodict, "DATETIME", #if defined(NPY_PY3K) s = Py_BuildValue("CiiiNNO", NPY_DATETIMELTR, #else s = Py_BuildValue("ciiiNNO", NPY_DATETIMELTR, #endif NPY_DATETIME, NPY_BITSOF_DATETIME, _ALIGN(npy_datetime), MyPyLong_FromInt64(NPY_MAX_DATETIME), MyPyLong_FromInt64(NPY_MIN_DATETIME), (PyObject *) &PyDatetimeArrType_Type)); Py_DECREF(s); PyDict_SetItemString(infodict, "TIMEDELTA", #if defined(NPY_PY3K) s = Py_BuildValue("CiiiNNO", NPY_TIMEDELTALTR, #else s = Py_BuildValue("ciiiNNO",NPY_TIMEDELTALTR, #endif NPY_TIMEDELTA, NPY_BITSOF_TIMEDELTA, _ALIGN(npy_timedelta), MyPyLong_FromInt64(NPY_MAX_TIMEDELTA), MyPyLong_FromInt64(NPY_MIN_TIMEDELTA), (PyObject *)&PyTimedeltaArrType_Type)); Py_DECREF(s); #define SETTYPE(name) \ Py_INCREF(&Py##name##ArrType_Type); \ PyDict_SetItemString(infodict, #name, \ (PyObject *)&Py##name##ArrType_Type) SETTYPE(Generic); SETTYPE(Number); SETTYPE(Integer); SETTYPE(Inexact); SETTYPE(SignedInteger); SETTYPE(UnsignedInteger); SETTYPE(Floating); SETTYPE(ComplexFloating); SETTYPE(Flexible); SETTYPE(Character); #undef SETTYPE PyDict_SetItemString(dict, "typeinfo", infodict); Py_DECREF(infodict); return 0; } #undef _MAX_LETTER numpy-1.8.2/numpy/core/src/multiarray/hashdescr.c0000664000175100017510000002034312370216242023215 0ustar vagrantvagrant00000000000000#define PY_SSIZE_T_CLEAN #include #define NPY_NO_DEPRECATED_API NPY_API_VERSION #define _MULTIARRAYMODULE #include #include "npy_config.h" #include "npy_pycompat.h" #include "hashdescr.h" /* * How does this work ? The hash is computed from a list which contains all the * information specific to a type. The hard work is to build the list * (_array_descr_walk). The list is built as follows: * * If the dtype is builtin (no fields, no subarray), then the list * contains 6 items which uniquely define one dtype (_array_descr_builtin) * * If the dtype is a compound array, one walk on each field. For each * field, we append title, names, offset to the final list used for * hashing, and then append the list recursively built for each * corresponding dtype (_array_descr_walk_fields) * * If the dtype is a subarray, one adds the shape tuple to the list, and * then append the list recursively built for each corresponding dtype * (_array_descr_walk_subarray) * */ static int _is_array_descr_builtin(PyArray_Descr* descr); static int _array_descr_walk(PyArray_Descr* descr, PyObject *l); static int _array_descr_walk_fields(PyObject* fields, PyObject* l); static int _array_descr_builtin(PyArray_Descr* descr, PyObject *l); /* * normalize endian character: always return 'I', '<' or '>' */ static char _normalize_byteorder(char byteorder) { switch(byteorder) { case '=': if (PyArray_GetEndianness() == NPY_CPU_BIG) { return '>'; } else { return '<'; } default: return byteorder; } } /* * Return true if descr is a builtin type */ static int _is_array_descr_builtin(PyArray_Descr* descr) { if (descr->fields != NULL && descr->fields != Py_None) { return 0; } if (PyDataType_HASSUBARRAY(descr)) { return 0; } return 1; } /* * Add to l all the items which uniquely define a builtin type */ static int _array_descr_builtin(PyArray_Descr* descr, PyObject *l) { Py_ssize_t i; PyObject *t, *item; char nbyteorder = _normalize_byteorder(descr->byteorder); /* * For builtin type, hash relies on : kind + byteorder + flags + * type_num + elsize + alignment */ t = Py_BuildValue("(cccii)", descr->kind, nbyteorder, descr->flags, descr->elsize, descr->alignment); for(i = 0; i < PyTuple_Size(t); ++i) { item = PyTuple_GetItem(t, i); if (item == NULL) { PyErr_SetString(PyExc_SystemError, "(Hash) Error while computing builting hash"); goto clean_t; } Py_INCREF(item); PyList_Append(l, item); } Py_DECREF(t); return 0; clean_t: Py_DECREF(t); return -1; } /* * Walk inside the fields and add every item which will be used for hashing * into the list l * * Return 0 on success */ static int _array_descr_walk_fields(PyObject* fields, PyObject* l) { PyObject *key, *value, *foffset, *fdescr; Py_ssize_t pos = 0; int st; while (PyDict_Next(fields, &pos, &key, &value)) { /* * For each field, add the key + descr + offset to l */ /* XXX: are those checks necessary ? */ if (!PyUString_Check(key)) { PyErr_SetString(PyExc_SystemError, "(Hash) key of dtype dict not a string ???"); return -1; } if (!PyTuple_Check(value)) { PyErr_SetString(PyExc_SystemError, "(Hash) value of dtype dict not a dtype ???"); return -1; } if (PyTuple_Size(value) < 2) { PyErr_SetString(PyExc_SystemError, "(Hash) Less than 2 items in dtype dict ???"); return -1; } Py_INCREF(key); PyList_Append(l, key); fdescr = PyTuple_GetItem(value, 0); if (!PyArray_DescrCheck(fdescr)) { PyErr_SetString(PyExc_SystemError, "(Hash) First item in compound dtype tuple not a descr ???"); return -1; } else { Py_INCREF(fdescr); st = _array_descr_walk((PyArray_Descr*)fdescr, l); Py_DECREF(fdescr); if (st) { return -1; } } foffset = PyTuple_GetItem(value, 1); if (!PyInt_Check(foffset)) { PyErr_SetString(PyExc_SystemError, "(Hash) Second item in compound dtype tuple not an int ???"); return -1; } else { Py_INCREF(foffset); PyList_Append(l, foffset); } } return 0; } /* * Walk into subarray, and add items for hashing in l * * Return 0 on success */ static int _array_descr_walk_subarray(PyArray_ArrayDescr* adescr, PyObject *l) { PyObject *item; Py_ssize_t i; int st; /* * Add shape and descr itself to the list of object to hash */ if (PyTuple_Check(adescr->shape)) { for(i = 0; i < PyTuple_Size(adescr->shape); ++i) { item = PyTuple_GetItem(adescr->shape, i); if (item == NULL) { PyErr_SetString(PyExc_SystemError, "(Hash) Error while getting shape item of subarray dtype ???"); return -1; } Py_INCREF(item); PyList_Append(l, item); } } else if (PyInt_Check(adescr->shape)) { Py_INCREF(adescr->shape); PyList_Append(l, adescr->shape); } else { PyErr_SetString(PyExc_SystemError, "(Hash) Shape of subarray dtype neither a tuple or int ???"); return -1; } Py_INCREF(adescr->base); st = _array_descr_walk(adescr->base, l); Py_DECREF(adescr->base); return st; } /* * 'Root' function to walk into a dtype. May be called recursively */ static int _array_descr_walk(PyArray_Descr* descr, PyObject *l) { int st; if (_is_array_descr_builtin(descr)) { return _array_descr_builtin(descr, l); } else { if(descr->fields != NULL && descr->fields != Py_None) { if (!PyDict_Check(descr->fields)) { PyErr_SetString(PyExc_SystemError, "(Hash) fields is not a dict ???"); return -1; } st = _array_descr_walk_fields(descr->fields, l); if (st) { return -1; } } if(PyDataType_HASSUBARRAY(descr)) { st = _array_descr_walk_subarray(descr->subarray, l); if (st) { return -1; } } } return 0; } /* * Return 0 if successfull */ static int _PyArray_DescrHashImp(PyArray_Descr *descr, npy_hash_t *hash) { PyObject *l, *tl, *item; Py_ssize_t i; int st; l = PyList_New(0); if (l == NULL) { return -1; } st = _array_descr_walk(descr, l); if (st) { goto clean_l; } /* * Convert the list to tuple and compute the tuple hash using python * builtin function */ tl = PyTuple_New(PyList_Size(l)); for(i = 0; i < PyList_Size(l); ++i) { item = PyList_GetItem(l, i); if (item == NULL) { PyErr_SetString(PyExc_SystemError, "(Hash) Error while translating the list into a tuple " \ "(NULL item)"); goto clean_tl; } PyTuple_SetItem(tl, i, item); } *hash = PyObject_Hash(tl); if (*hash == -1) { /* XXX: does PyObject_Hash set an exception on failure ? */ #if 0 PyErr_SetString(PyExc_SystemError, "(Hash) Error while hashing final tuple"); #endif goto clean_tl; } Py_DECREF(tl); Py_DECREF(l); return 0; clean_tl: Py_DECREF(tl); clean_l: Py_DECREF(l); return -1; } NPY_NO_EXPORT npy_hash_t PyArray_DescrHash(PyObject* odescr) { PyArray_Descr *descr; int st; npy_hash_t hash; if (!PyArray_DescrCheck(odescr)) { PyErr_SetString(PyExc_ValueError, "PyArray_DescrHash argument must be a type descriptor"); return -1; } descr = (PyArray_Descr*)odescr; st = _PyArray_DescrHashImp(descr, &hash); if (st) { return -1; } return hash; } numpy-1.8.2/numpy/core/src/multiarray/einsum.c.src0000664000175100017510000027444012370216243023351 0ustar vagrantvagrant00000000000000/* * This file contains the implementation of the 'einsum' function, * which provides an einstein-summation operation. * * Copyright (c) 2011 by Mark Wiebe (mwwiebe@gmail.com) * The Univerity of British Columbia * * See LICENSE.txt for the license. */ #define PY_SSIZE_T_CLEAN #include "Python.h" #include "structmember.h" #define NPY_NO_DEPRECATED_API NPY_API_VERSION #define _MULTIARRAYMODULE #include #include #include #include #include #include "convert.h" #ifdef NPY_HAVE_SSE_INTRINSICS #define EINSUM_USE_SSE1 1 #else #define EINSUM_USE_SSE1 0 #endif /* * TODO: Only some SSE2 for float64 is implemented. */ #ifdef NPY_HAVE_SSE2_INTRINSICS #define EINSUM_USE_SSE2 1 #else #define EINSUM_USE_SSE2 0 #endif #if EINSUM_USE_SSE1 #include #endif #if EINSUM_USE_SSE2 #include #endif #define EINSUM_IS_SSE_ALIGNED(x) ((((npy_intp)x)&0xf) == 0) /********** PRINTF DEBUG TRACING **************/ #define NPY_EINSUM_DBG_TRACING 0 #if NPY_EINSUM_DBG_TRACING #define NPY_EINSUM_DBG_PRINT(s) printf("%s", s); #define NPY_EINSUM_DBG_PRINT1(s, p1) printf(s, p1); #define NPY_EINSUM_DBG_PRINT2(s, p1, p2) printf(s, p1, p2); #define NPY_EINSUM_DBG_PRINT3(s, p1, p2, p3) printf(s); #else #define NPY_EINSUM_DBG_PRINT(s) #define NPY_EINSUM_DBG_PRINT1(s, p1) #define NPY_EINSUM_DBG_PRINT2(s, p1, p2) #define NPY_EINSUM_DBG_PRINT3(s, p1, p2, p3) #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, * half, float, double, longdouble, * cfloat, cdouble, clongdouble# * #type = npy_byte, npy_short, npy_int, npy_long, npy_longlong, * npy_ubyte, npy_ushort, npy_uint, npy_ulong, npy_ulonglong, * npy_half, npy_float, npy_double, npy_longdouble, * npy_cfloat, npy_cdouble, npy_clongdouble# * #temptype = npy_byte, npy_short, npy_int, npy_long, npy_longlong, * npy_ubyte, npy_ushort, npy_uint, npy_ulong, npy_ulonglong, * npy_float, npy_float, npy_double, npy_longdouble, * npy_float, npy_double, npy_longdouble# * #to = ,,,,, * ,,,,, * npy_float_to_half,,,, * ,,# * #from = ,,,,, * ,,,,, * npy_half_to_float,,,, * ,,# * #complex = 0*5, * 0*5, * 0*4, * 1*3# * #float32 = 0*5, * 0*5, * 0,1,0,0, * 0*3# * #float64 = 0*5, * 0*5, * 0,0,1,0, * 0*3# */ /**begin repeat1 * #nop = 1, 2, 3, 1000# * #noplabel = one, two, three, any# */ static void @name@_sum_of_products_@noplabel@(int nop, char **dataptr, npy_intp *strides, npy_intp count) { #if (@nop@ == 1) || (@nop@ <= 3 && !@complex@) char *data0 = dataptr[0]; npy_intp stride0 = strides[0]; #endif #if (@nop@ == 2 || @nop@ == 3) && !@complex@ char *data1 = dataptr[1]; npy_intp stride1 = strides[1]; #endif #if (@nop@ == 3) && !@complex@ char *data2 = dataptr[2]; npy_intp stride2 = strides[2]; #endif #if (@nop@ == 1) || (@nop@ <= 3 && !@complex@) char *data_out = dataptr[@nop@]; npy_intp stride_out = strides[@nop@]; #endif NPY_EINSUM_DBG_PRINT1("@name@_sum_of_products_@noplabel@ (%d)\n", (int)count); while (count--) { #if !@complex@ # if @nop@ == 1 *(@type@ *)data_out = @to@(@from@(*(@type@ *)data0) + @from@(*(@type@ *)data_out)); data0 += stride0; data_out += stride_out; # elif @nop@ == 2 *(@type@ *)data_out = @to@(@from@(*(@type@ *)data0) * @from@(*(@type@ *)data1) + @from@(*(@type@ *)data_out)); data0 += stride0; data1 += stride1; data_out += stride_out; # elif @nop@ == 3 *(@type@ *)data_out = @to@(@from@(*(@type@ *)data0) * @from@(*(@type@ *)data1) * @from@(*(@type@ *)data2) + @from@(*(@type@ *)data_out)); data0 += stride0; data1 += stride1; data2 += stride2; data_out += stride_out; # else @temptype@ temp = @from@(*(@type@ *)dataptr[0]); int i; for (i = 1; i < nop; ++i) { temp *= @from@(*(@type@ *)dataptr[i]); } *(@type@ *)dataptr[nop] = @to@(temp + @from@(*(@type@ *)dataptr[i])); for (i = 0; i <= nop; ++i) { dataptr[i] += strides[i]; } # endif #else /* complex */ # if @nop@ == 1 ((@temptype@ *)data_out)[0] = ((@temptype@ *)data0)[0] + ((@temptype@ *)data_out)[0]; ((@temptype@ *)data_out)[1] = ((@temptype@ *)data0)[1] + ((@temptype@ *)data_out)[1]; data0 += stride0; data_out += stride_out; # else # if @nop@ <= 3 #define _SUMPROD_NOP @nop@ # else #define _SUMPROD_NOP nop # endif @temptype@ re, im, tmp; int i; re = ((@temptype@ *)dataptr[0])[0]; im = ((@temptype@ *)dataptr[0])[1]; for (i = 1; i < _SUMPROD_NOP; ++i) { tmp = re * ((@temptype@ *)dataptr[i])[0] - im * ((@temptype@ *)dataptr[i])[1]; im = re * ((@temptype@ *)dataptr[i])[1] + im * ((@temptype@ *)dataptr[i])[0]; re = tmp; } ((@temptype@ *)dataptr[_SUMPROD_NOP])[0] = re + ((@temptype@ *)dataptr[_SUMPROD_NOP])[0]; ((@temptype@ *)dataptr[_SUMPROD_NOP])[1] = im + ((@temptype@ *)dataptr[_SUMPROD_NOP])[1]; for (i = 0; i <= _SUMPROD_NOP; ++i) { dataptr[i] += strides[i]; } #undef _SUMPROD_NOP # endif #endif } } #if @nop@ == 1 static void @name@_sum_of_products_contig_one(int nop, char **dataptr, npy_intp *NPY_UNUSED(strides), npy_intp count) { @type@ *data0 = (@type@ *)dataptr[0]; @type@ *data_out = (@type@ *)dataptr[1]; NPY_EINSUM_DBG_PRINT1("@name@_sum_of_products_contig_one (%d)\n", (int)count); /* This is placed before the main loop to make small counts faster */ finish_after_unrolled_loop: switch (count) { /**begin repeat2 * #i = 6, 5, 4, 3, 2, 1, 0# */ case @i@+1: #if !@complex@ data_out[@i@] = @to@(@from@(data0[@i@]) + @from@(data_out[@i@])); #else ((@temptype@ *)data_out + 2*@i@)[0] = ((@temptype@ *)data0 + 2*@i@)[0] + ((@temptype@ *)data_out + 2*@i@)[0]; ((@temptype@ *)data_out + 2*@i@)[1] = ((@temptype@ *)data0 + 2*@i@)[1] + ((@temptype@ *)data_out + 2*@i@)[1]; #endif /**end repeat2**/ case 0: return; } /* Unroll the loop by 8 */ while (count >= 8) { count -= 8; /**begin repeat2 * #i = 0, 1, 2, 3, 4, 5, 6, 7# */ #if !@complex@ data_out[@i@] = @to@(@from@(data0[@i@]) + @from@(data_out[@i@])); #else /* complex */ ((@temptype@ *)data_out + 2*@i@)[0] = ((@temptype@ *)data0 + 2*@i@)[0] + ((@temptype@ *)data_out + 2*@i@)[0]; ((@temptype@ *)data_out + 2*@i@)[1] = ((@temptype@ *)data0 + 2*@i@)[1] + ((@temptype@ *)data_out + 2*@i@)[1]; #endif /**end repeat2**/ data0 += 8; data_out += 8; } /* Finish off the loop */ goto finish_after_unrolled_loop; } #elif @nop@ == 2 && !@complex@ static void @name@_sum_of_products_contig_two(int nop, char **dataptr, npy_intp *NPY_UNUSED(strides), npy_intp count) { @type@ *data0 = (@type@ *)dataptr[0]; @type@ *data1 = (@type@ *)dataptr[1]; @type@ *data_out = (@type@ *)dataptr[2]; #if EINSUM_USE_SSE1 && @float32@ __m128 a, b; #endif NPY_EINSUM_DBG_PRINT1("@name@_sum_of_products_contig_two (%d)\n", (int)count); /* This is placed before the main loop to make small counts faster */ finish_after_unrolled_loop: switch (count) { /**begin repeat2 * #i = 6, 5, 4, 3, 2, 1, 0# */ case @i@+1: data_out[@i@] = @to@(@from@(data0[@i@]) * @from@(data1[@i@]) + @from@(data_out[@i@])); /**end repeat2**/ case 0: return; } #if EINSUM_USE_SSE1 && @float32@ /* Use aligned instructions if possible */ if (EINSUM_IS_SSE_ALIGNED(data0) && EINSUM_IS_SSE_ALIGNED(data1) && EINSUM_IS_SSE_ALIGNED(data_out)) { /* Unroll the loop by 8 */ while (count >= 8) { count -= 8; /**begin repeat2 * #i = 0, 4# */ a = _mm_mul_ps(_mm_load_ps(data0+@i@), _mm_load_ps(data1+@i@)); b = _mm_add_ps(a, _mm_load_ps(data_out+@i@)); _mm_store_ps(data_out+@i@, b); /**end repeat2**/ data0 += 8; data1 += 8; data_out += 8; } /* Finish off the loop */ goto finish_after_unrolled_loop; } #endif /* Unroll the loop by 8 */ while (count >= 8) { count -= 8; #if EINSUM_USE_SSE1 && @float32@ /**begin repeat2 * #i = 0, 4# */ a = _mm_mul_ps(_mm_loadu_ps(data0+@i@), _mm_loadu_ps(data1+@i@)); b = _mm_add_ps(a, _mm_loadu_ps(data_out+@i@)); _mm_storeu_ps(data_out+@i@, b); /**end repeat2**/ #else /**begin repeat2 * #i = 0, 1, 2, 3, 4, 5, 6, 7# */ data_out[@i@] = @to@(@from@(data0[@i@]) * @from@(data1[@i@]) + @from@(data_out[@i@])); /**end repeat2**/ #endif data0 += 8; data1 += 8; data_out += 8; } /* Finish off the loop */ goto finish_after_unrolled_loop; } /* Some extra specializations for the two operand case */ static void @name@_sum_of_products_stride0_contig_outcontig_two(int nop, char **dataptr, npy_intp *NPY_UNUSED(strides), npy_intp count) { @temptype@ value0 = @from@(*(@type@ *)dataptr[0]); @type@ *data1 = (@type@ *)dataptr[1]; @type@ *data_out = (@type@ *)dataptr[2]; #if EINSUM_USE_SSE1 && @float32@ __m128 a, b, value0_sse; #elif EINSUM_USE_SSE2 && @float64@ __m128d a, b, value0_sse; #endif NPY_EINSUM_DBG_PRINT1("@name@_sum_of_products_stride0_contig_outcontig_two (%d)\n", (int)count); /* This is placed before the main loop to make small counts faster */ finish_after_unrolled_loop: switch (count) { /**begin repeat2 * #i = 6, 5, 4, 3, 2, 1, 0# */ case @i@+1: data_out[@i@] = @to@(value0 * @from@(data1[@i@]) + @from@(data_out[@i@])); /**end repeat2**/ case 0: return; } #if EINSUM_USE_SSE1 && @float32@ value0_sse = _mm_set_ps1(value0); /* Use aligned instructions if possible */ if (EINSUM_IS_SSE_ALIGNED(data1) && EINSUM_IS_SSE_ALIGNED(data_out)) { /* Unroll the loop by 8 */ while (count >= 8) { count -= 8; /**begin repeat2 * #i = 0, 4# */ a = _mm_mul_ps(value0_sse, _mm_load_ps(data1+@i@)); b = _mm_add_ps(a, _mm_load_ps(data_out+@i@)); _mm_store_ps(data_out+@i@, b); /**end repeat2**/ data1 += 8; data_out += 8; } /* Finish off the loop */ if (count > 0) { goto finish_after_unrolled_loop; } else { return; } } #elif EINSUM_USE_SSE2 && @float64@ value0_sse = _mm_set1_pd(value0); /* Use aligned instructions if possible */ if (EINSUM_IS_SSE_ALIGNED(data1) && EINSUM_IS_SSE_ALIGNED(data_out)) { /* Unroll the loop by 8 */ while (count >= 8) { count -= 8; /**begin repeat2 * #i = 0, 2, 4, 6# */ a = _mm_mul_pd(value0_sse, _mm_load_pd(data1+@i@)); b = _mm_add_pd(a, _mm_load_pd(data_out+@i@)); _mm_store_pd(data_out+@i@, b); /**end repeat2**/ data1 += 8; data_out += 8; } /* Finish off the loop */ if (count > 0) { goto finish_after_unrolled_loop; } else { return; } } #endif /* Unroll the loop by 8 */ while (count >= 8) { count -= 8; #if EINSUM_USE_SSE1 && @float32@ /**begin repeat2 * #i = 0, 4# */ a = _mm_mul_ps(value0_sse, _mm_loadu_ps(data1+@i@)); b = _mm_add_ps(a, _mm_loadu_ps(data_out+@i@)); _mm_storeu_ps(data_out+@i@, b); /**end repeat2**/ #elif EINSUM_USE_SSE2 && @float64@ /**begin repeat2 * #i = 0, 2, 4, 6# */ a = _mm_mul_pd(value0_sse, _mm_loadu_pd(data1+@i@)); b = _mm_add_pd(a, _mm_loadu_pd(data_out+@i@)); _mm_storeu_pd(data_out+@i@, b); /**end repeat2**/ #else /**begin repeat2 * #i = 0, 1, 2, 3, 4, 5, 6, 7# */ data_out[@i@] = @to@(value0 * @from@(data1[@i@]) + @from@(data_out[@i@])); /**end repeat2**/ #endif data1 += 8; data_out += 8; } /* Finish off the loop */ if (count > 0) { goto finish_after_unrolled_loop; } } static void @name@_sum_of_products_contig_stride0_outcontig_two(int nop, char **dataptr, npy_intp *NPY_UNUSED(strides), npy_intp count) { @type@ *data0 = (@type@ *)dataptr[0]; @temptype@ value1 = @from@(*(@type@ *)dataptr[1]); @type@ *data_out = (@type@ *)dataptr[2]; #if EINSUM_USE_SSE1 && @float32@ __m128 a, b, value1_sse; #endif NPY_EINSUM_DBG_PRINT1("@name@_sum_of_products_contig_stride0_outcontig_two (%d)\n", (int)count); /* This is placed before the main loop to make small counts faster */ finish_after_unrolled_loop: switch (count) { /**begin repeat2 * #i = 6, 5, 4, 3, 2, 1, 0# */ case @i@+1: data_out[@i@] = @to@(@from@(data0[@i@])* value1 + @from@(data_out[@i@])); /**end repeat2**/ case 0: return; } #if EINSUM_USE_SSE1 && @float32@ value1_sse = _mm_set_ps1(value1); /* Use aligned instructions if possible */ if (EINSUM_IS_SSE_ALIGNED(data0) && EINSUM_IS_SSE_ALIGNED(data_out)) { /* Unroll the loop by 8 */ while (count >= 8) { count -= 8; /**begin repeat2 * #i = 0, 4# */ a = _mm_mul_ps(_mm_load_ps(data0+@i@), value1_sse); b = _mm_add_ps(a, _mm_load_ps(data_out+@i@)); _mm_store_ps(data_out+@i@, b); /**end repeat2**/ data0 += 8; data_out += 8; } /* Finish off the loop */ goto finish_after_unrolled_loop; } #endif /* Unroll the loop by 8 */ while (count >= 8) { count -= 8; #if EINSUM_USE_SSE1 && @float32@ /**begin repeat2 * #i = 0, 4# */ a = _mm_mul_ps(_mm_loadu_ps(data0+@i@), value1_sse); b = _mm_add_ps(a, _mm_loadu_ps(data_out+@i@)); _mm_storeu_ps(data_out+@i@, b); /**end repeat2**/ #else /**begin repeat2 * #i = 0, 1, 2, 3, 4, 5, 6, 7# */ data_out[@i@] = @to@(@from@(data0[@i@])* value1 + @from@(data_out[@i@])); /**end repeat2**/ #endif data0 += 8; data_out += 8; } /* Finish off the loop */ goto finish_after_unrolled_loop; } static void @name@_sum_of_products_contig_contig_outstride0_two(int nop, char **dataptr, npy_intp *NPY_UNUSED(strides), npy_intp count) { @type@ *data0 = (@type@ *)dataptr[0]; @type@ *data1 = (@type@ *)dataptr[1]; @temptype@ accum = 0; #if EINSUM_USE_SSE1 && @float32@ __m128 a, accum_sse = _mm_setzero_ps(); #elif EINSUM_USE_SSE2 && @float64@ __m128d a, accum_sse = _mm_setzero_pd(); #endif NPY_EINSUM_DBG_PRINT1("@name@_sum_of_products_contig_contig_outstride0_two (%d)\n", (int)count); /* This is placed before the main loop to make small counts faster */ finish_after_unrolled_loop: switch (count) { /**begin repeat2 * #i = 6, 5, 4, 3, 2, 1, 0# */ case @i@+1: accum += @from@(data0[@i@]) * @from@(data1[@i@]); /**end repeat2**/ case 0: *(@type@ *)dataptr[2] += @to@(accum); return; } #if EINSUM_USE_SSE1 && @float32@ /* Use aligned instructions if possible */ if (EINSUM_IS_SSE_ALIGNED(data0) && EINSUM_IS_SSE_ALIGNED(data1)) { /* Unroll the loop by 8 */ while (count >= 8) { count -= 8; _mm_prefetch(data0 + 512, _MM_HINT_T0); _mm_prefetch(data1 + 512, _MM_HINT_T0); /**begin repeat2 * #i = 0, 4# */ /* * NOTE: This accumulation changes the order, so will likely * produce slightly different results. */ a = _mm_mul_ps(_mm_load_ps(data0+@i@), _mm_load_ps(data1+@i@)); accum_sse = _mm_add_ps(accum_sse, a); /**end repeat2**/ data0 += 8; data1 += 8; } /* Add the four SSE values and put in accum */ a = _mm_shuffle_ps(accum_sse, accum_sse, _MM_SHUFFLE(2,3,0,1)); accum_sse = _mm_add_ps(a, accum_sse); a = _mm_shuffle_ps(accum_sse, accum_sse, _MM_SHUFFLE(1,0,3,2)); accum_sse = _mm_add_ps(a, accum_sse); _mm_store_ss(&accum, accum_sse); /* Finish off the loop */ goto finish_after_unrolled_loop; } #elif EINSUM_USE_SSE2 && @float64@ /* Use aligned instructions if possible */ if (EINSUM_IS_SSE_ALIGNED(data0) && EINSUM_IS_SSE_ALIGNED(data1)) { /* Unroll the loop by 8 */ while (count >= 8) { count -= 8; _mm_prefetch(data0 + 512, _MM_HINT_T0); _mm_prefetch(data1 + 512, _MM_HINT_T0); /**begin repeat2 * #i = 0, 2, 4, 6# */ /* * NOTE: This accumulation changes the order, so will likely * produce slightly different results. */ a = _mm_mul_pd(_mm_load_pd(data0+@i@), _mm_load_pd(data1+@i@)); accum_sse = _mm_add_pd(accum_sse, a); /**end repeat2**/ data0 += 8; data1 += 8; } /* Add the two SSE2 values and put in accum */ a = _mm_shuffle_pd(accum_sse, accum_sse, _MM_SHUFFLE2(0,1)); accum_sse = _mm_add_pd(a, accum_sse); _mm_store_sd(&accum, accum_sse); /* Finish off the loop */ goto finish_after_unrolled_loop; } #endif /* Unroll the loop by 8 */ while (count >= 8) { count -= 8; #if EINSUM_USE_SSE1 && @float32@ _mm_prefetch(data0 + 512, _MM_HINT_T0); _mm_prefetch(data1 + 512, _MM_HINT_T0); /**begin repeat2 * #i = 0, 4# */ /* * NOTE: This accumulation changes the order, so will likely * produce slightly different results. */ a = _mm_mul_ps(_mm_loadu_ps(data0+@i@), _mm_loadu_ps(data1+@i@)); accum_sse = _mm_add_ps(accum_sse, a); /**end repeat2**/ #elif EINSUM_USE_SSE2 && @float64@ _mm_prefetch(data0 + 512, _MM_HINT_T0); _mm_prefetch(data1 + 512, _MM_HINT_T0); /**begin repeat2 * #i = 0, 2, 4, 6# */ /* * NOTE: This accumulation changes the order, so will likely * produce slightly different results. */ a = _mm_mul_pd(_mm_loadu_pd(data0+@i@), _mm_loadu_pd(data1+@i@)); accum_sse = _mm_add_pd(accum_sse, a); /**end repeat2**/ #else /**begin repeat2 * #i = 0, 1, 2, 3, 4, 5, 6, 7# */ accum += @from@(data0[@i@]) * @from@(data1[@i@]); /**end repeat2**/ #endif data0 += 8; data1 += 8; } #if EINSUM_USE_SSE1 && @float32@ /* Add the four SSE values and put in accum */ a = _mm_shuffle_ps(accum_sse, accum_sse, _MM_SHUFFLE(2,3,0,1)); accum_sse = _mm_add_ps(a, accum_sse); a = _mm_shuffle_ps(accum_sse, accum_sse, _MM_SHUFFLE(1,0,3,2)); accum_sse = _mm_add_ps(a, accum_sse); _mm_store_ss(&accum, accum_sse); #elif EINSUM_USE_SSE2 && @float64@ /* Add the two SSE2 values and put in accum */ a = _mm_shuffle_pd(accum_sse, accum_sse, _MM_SHUFFLE2(0,1)); accum_sse = _mm_add_pd(a, accum_sse); _mm_store_sd(&accum, accum_sse); #endif /* Finish off the loop */ goto finish_after_unrolled_loop; } static void @name@_sum_of_products_stride0_contig_outstride0_two(int nop, char **dataptr, npy_intp *NPY_UNUSED(strides), npy_intp count) { @temptype@ value0 = @from@(*(@type@ *)dataptr[0]); @type@ *data1 = (@type@ *)dataptr[1]; @temptype@ accum = 0; #if EINSUM_USE_SSE1 && @float32@ __m128 a, accum_sse = _mm_setzero_ps(); #endif NPY_EINSUM_DBG_PRINT1("@name@_sum_of_products_stride0_contig_outstride0_two (%d)\n", (int)count); /* This is placed before the main loop to make small counts faster */ finish_after_unrolled_loop: switch (count) { /**begin repeat2 * #i = 6, 5, 4, 3, 2, 1, 0# */ case @i@+1: accum += @from@(data1[@i@]); /**end repeat2**/ case 0: *(@type@ *)dataptr[2] += @to@(value0 * accum); return; } #if EINSUM_USE_SSE1 && @float32@ /* Use aligned instructions if possible */ if (EINSUM_IS_SSE_ALIGNED(data1)) { /* Unroll the loop by 8 */ while (count >= 8) { count -= 8; /**begin repeat2 * #i = 0, 4# */ /* * NOTE: This accumulation changes the order, so will likely * produce slightly different results. */ accum_sse = _mm_add_ps(accum_sse, _mm_load_ps(data1+@i@)); /**end repeat2**/ data1 += 8; } #if EINSUM_USE_SSE1 && @float32@ /* Add the four SSE values and put in accum */ a = _mm_shuffle_ps(accum_sse, accum_sse, _MM_SHUFFLE(2,3,0,1)); accum_sse = _mm_add_ps(a, accum_sse); a = _mm_shuffle_ps(accum_sse, accum_sse, _MM_SHUFFLE(1,0,3,2)); accum_sse = _mm_add_ps(a, accum_sse); _mm_store_ss(&accum, accum_sse); #endif /* Finish off the loop */ goto finish_after_unrolled_loop; } #endif /* Unroll the loop by 8 */ while (count >= 8) { count -= 8; #if EINSUM_USE_SSE1 && @float32@ /**begin repeat2 * #i = 0, 4# */ /* * NOTE: This accumulation changes the order, so will likely * produce slightly different results. */ accum_sse = _mm_add_ps(accum_sse, _mm_loadu_ps(data1+@i@)); /**end repeat2**/ #else /**begin repeat2 * #i = 0, 1, 2, 3, 4, 5, 6, 7# */ accum += @from@(data1[@i@]); /**end repeat2**/ #endif data1 += 8; } #if EINSUM_USE_SSE1 && @float32@ /* Add the four SSE values and put in accum */ a = _mm_shuffle_ps(accum_sse, accum_sse, _MM_SHUFFLE(2,3,0,1)); accum_sse = _mm_add_ps(a, accum_sse); a = _mm_shuffle_ps(accum_sse, accum_sse, _MM_SHUFFLE(1,0,3,2)); accum_sse = _mm_add_ps(a, accum_sse); _mm_store_ss(&accum, accum_sse); #endif /* Finish off the loop */ goto finish_after_unrolled_loop; } static void @name@_sum_of_products_contig_stride0_outstride0_two(int nop, char **dataptr, npy_intp *NPY_UNUSED(strides), npy_intp count) { @type@ *data0 = (@type@ *)dataptr[0]; @temptype@ value1 = @from@(*(@type@ *)dataptr[1]); @temptype@ accum = 0; #if EINSUM_USE_SSE1 && @float32@ __m128 a, accum_sse = _mm_setzero_ps(); #endif NPY_EINSUM_DBG_PRINT1("@name@_sum_of_products_contig_stride0_outstride0_two (%d)\n", (int)count); /* This is placed before the main loop to make small counts faster */ finish_after_unrolled_loop: switch (count) { /**begin repeat2 * #i = 6, 5, 4, 3, 2, 1, 0# */ case @i@+1: accum += @from@(data0[@i@]); /**end repeat2**/ case 0: *(@type@ *)dataptr[2] += @to@(accum * value1); return; } #if EINSUM_USE_SSE1 && @float32@ /* Use aligned instructions if possible */ if (EINSUM_IS_SSE_ALIGNED(data0)) { /* Unroll the loop by 8 */ while (count >= 8) { count -= 8; /**begin repeat2 * #i = 0, 4# */ /* * NOTE: This accumulation changes the order, so will likely * produce slightly different results. */ accum_sse = _mm_add_ps(accum_sse, _mm_load_ps(data0+@i@)); /**end repeat2**/ data0 += 8; } #if EINSUM_USE_SSE1 && @float32@ /* Add the four SSE values and put in accum */ a = _mm_shuffle_ps(accum_sse, accum_sse, _MM_SHUFFLE(2,3,0,1)); accum_sse = _mm_add_ps(a, accum_sse); a = _mm_shuffle_ps(accum_sse, accum_sse, _MM_SHUFFLE(1,0,3,2)); accum_sse = _mm_add_ps(a, accum_sse); _mm_store_ss(&accum, accum_sse); #endif /* Finish off the loop */ goto finish_after_unrolled_loop; } #endif /* Unroll the loop by 8 */ while (count >= 8) { count -= 8; #if EINSUM_USE_SSE1 && @float32@ /**begin repeat2 * #i = 0, 4# */ /* * NOTE: This accumulation changes the order, so will likely * produce slightly different results. */ accum_sse = _mm_add_ps(accum_sse, _mm_loadu_ps(data0+@i@)); /**end repeat2**/ #else /**begin repeat2 * #i = 0, 1, 2, 3, 4, 5, 6, 7# */ accum += @from@(data0[@i@]); /**end repeat2**/ #endif data0 += 8; } #if EINSUM_USE_SSE1 && @float32@ /* Add the four SSE values and put in accum */ a = _mm_shuffle_ps(accum_sse, accum_sse, _MM_SHUFFLE(2,3,0,1)); accum_sse = _mm_add_ps(a, accum_sse); a = _mm_shuffle_ps(accum_sse, accum_sse, _MM_SHUFFLE(1,0,3,2)); accum_sse = _mm_add_ps(a, accum_sse); _mm_store_ss(&accum, accum_sse); #endif /* Finish off the loop */ goto finish_after_unrolled_loop; } #elif @nop@ == 3 && !@complex@ static void @name@_sum_of_products_contig_three(int nop, char **dataptr, npy_intp *NPY_UNUSED(strides), npy_intp count) { @type@ *data0 = (@type@ *)dataptr[0]; @type@ *data1 = (@type@ *)dataptr[1]; @type@ *data2 = (@type@ *)dataptr[2]; @type@ *data_out = (@type@ *)dataptr[3]; /* Unroll the loop by 8 */ while (count >= 8) { count -= 8; /**begin repeat2 * #i = 0, 1, 2, 3, 4, 5, 6, 7# */ data_out[@i@] = @to@(@from@(data0[@i@]) * @from@(data1[@i@]) * @from@(data2[@i@]) + @from@(data_out[@i@])); /**end repeat2**/ data0 += 8; data1 += 8; data2 += 8; data_out += 8; } /* Finish off the loop */ /**begin repeat2 * #i = 0, 1, 2, 3, 4, 5, 6, 7# */ if (count-- == 0) { return; } data_out[@i@] = @to@(@from@(data0[@i@]) * @from@(data1[@i@]) * @from@(data2[@i@]) + @from@(data_out[@i@])); /**end repeat2**/ } #else /* @nop@ > 3 || @complex */ static void @name@_sum_of_products_contig_@noplabel@(int nop, char **dataptr, npy_intp *NPY_UNUSED(strides), npy_intp count) { NPY_EINSUM_DBG_PRINT1("@name@_sum_of_products_contig_@noplabel@ (%d)\n", (int)count); while (count--) { #if !@complex@ @temptype@ temp = @from@(*(@type@ *)dataptr[0]); int i; for (i = 1; i < nop; ++i) { temp *= @from@(*(@type@ *)dataptr[i]); } *(@type@ *)dataptr[nop] = @to@(temp + @from@(*(@type@ *)dataptr[i])); for (i = 0; i <= nop; ++i) { dataptr[i] += sizeof(@type@); } #else /* complex */ # if @nop@ <= 3 # define _SUMPROD_NOP @nop@ # else # define _SUMPROD_NOP nop # endif @temptype@ re, im, tmp; int i; re = ((@temptype@ *)dataptr[0])[0]; im = ((@temptype@ *)dataptr[0])[1]; for (i = 1; i < _SUMPROD_NOP; ++i) { tmp = re * ((@temptype@ *)dataptr[i])[0] - im * ((@temptype@ *)dataptr[i])[1]; im = re * ((@temptype@ *)dataptr[i])[1] + im * ((@temptype@ *)dataptr[i])[0]; re = tmp; } ((@temptype@ *)dataptr[_SUMPROD_NOP])[0] = re + ((@temptype@ *)dataptr[_SUMPROD_NOP])[0]; ((@temptype@ *)dataptr[_SUMPROD_NOP])[1] = im + ((@temptype@ *)dataptr[_SUMPROD_NOP])[1]; for (i = 0; i <= _SUMPROD_NOP; ++i) { dataptr[i] += sizeof(@type@); } # undef _SUMPROD_NOP #endif } } #endif /* functions for various @nop@ */ #if @nop@ == 1 static void @name@_sum_of_products_contig_outstride0_one(int nop, char **dataptr, npy_intp *strides, npy_intp count) { #if @complex@ @temptype@ accum_re = 0, accum_im = 0; @temptype@ *data0 = (@temptype@ *)dataptr[0]; #else @temptype@ accum = 0; @type@ *data0 = (@type@ *)dataptr[0]; #endif #if EINSUM_USE_SSE1 && @float32@ __m128 a, accum_sse = _mm_setzero_ps(); #elif EINSUM_USE_SSE2 && @float64@ __m128d a, accum_sse = _mm_setzero_pd(); #endif NPY_EINSUM_DBG_PRINT1("@name@_sum_of_products_contig_outstride0_one (%d)\n", (int)count); /* This is placed before the main loop to make small counts faster */ finish_after_unrolled_loop: switch (count) { /**begin repeat2 * #i = 6, 5, 4, 3, 2, 1, 0# */ case @i@+1: #if !@complex@ accum += @from@(data0[@i@]); #else /* complex */ accum_re += data0[2*@i@+0]; accum_im += data0[2*@i@+1]; #endif /**end repeat2**/ case 0: #if @complex@ ((@temptype@ *)dataptr[1])[0] += accum_re; ((@temptype@ *)dataptr[1])[1] += accum_im; #else *((@type@ *)dataptr[1]) = @to@(accum + @from@(*((@type@ *)dataptr[1]))); #endif return; } #if EINSUM_USE_SSE1 && @float32@ /* Use aligned instructions if possible */ if (EINSUM_IS_SSE_ALIGNED(data0)) { /* Unroll the loop by 8 */ while (count >= 8) { count -= 8; _mm_prefetch(data0 + 512, _MM_HINT_T0); /**begin repeat2 * #i = 0, 4# */ /* * NOTE: This accumulation changes the order, so will likely * produce slightly different results. */ accum_sse = _mm_add_ps(accum_sse, _mm_load_ps(data0+@i@)); /**end repeat2**/ data0 += 8; } /* Add the four SSE values and put in accum */ a = _mm_shuffle_ps(accum_sse, accum_sse, _MM_SHUFFLE(2,3,0,1)); accum_sse = _mm_add_ps(a, accum_sse); a = _mm_shuffle_ps(accum_sse, accum_sse, _MM_SHUFFLE(1,0,3,2)); accum_sse = _mm_add_ps(a, accum_sse); _mm_store_ss(&accum, accum_sse); /* Finish off the loop */ goto finish_after_unrolled_loop; } #elif EINSUM_USE_SSE2 && @float64@ /* Use aligned instructions if possible */ if (EINSUM_IS_SSE_ALIGNED(data0)) { /* Unroll the loop by 8 */ while (count >= 8) { count -= 8; _mm_prefetch(data0 + 512, _MM_HINT_T0); /**begin repeat2 * #i = 0, 2, 4, 6# */ /* * NOTE: This accumulation changes the order, so will likely * produce slightly different results. */ accum_sse = _mm_add_pd(accum_sse, _mm_load_pd(data0+@i@)); /**end repeat2**/ data0 += 8; } /* Add the two SSE2 values and put in accum */ a = _mm_shuffle_pd(accum_sse, accum_sse, _MM_SHUFFLE2(0,1)); accum_sse = _mm_add_pd(a, accum_sse); _mm_store_sd(&accum, accum_sse); /* Finish off the loop */ goto finish_after_unrolled_loop; } #endif /* Unroll the loop by 8 */ while (count >= 8) { count -= 8; #if EINSUM_USE_SSE1 && @float32@ _mm_prefetch(data0 + 512, _MM_HINT_T0); /**begin repeat2 * #i = 0, 4# */ /* * NOTE: This accumulation changes the order, so will likely * produce slightly different results. */ accum_sse = _mm_add_ps(accum_sse, _mm_loadu_ps(data0+@i@)); /**end repeat2**/ #elif EINSUM_USE_SSE2 && @float64@ _mm_prefetch(data0 + 512, _MM_HINT_T0); /**begin repeat2 * #i = 0, 2, 4, 6# */ /* * NOTE: This accumulation changes the order, so will likely * produce slightly different results. */ accum_sse = _mm_add_pd(accum_sse, _mm_loadu_pd(data0+@i@)); /**end repeat2**/ #else /**begin repeat2 * #i = 0, 1, 2, 3, 4, 5, 6, 7# */ # if !@complex@ accum += @from@(data0[@i@]); # else /* complex */ accum_re += data0[2*@i@+0]; accum_im += data0[2*@i@+1]; # endif /**end repeat2**/ #endif #if !@complex@ data0 += 8; #else data0 += 8*2; #endif } #if EINSUM_USE_SSE1 && @float32@ /* Add the four SSE values and put in accum */ a = _mm_shuffle_ps(accum_sse, accum_sse, _MM_SHUFFLE(2,3,0,1)); accum_sse = _mm_add_ps(a, accum_sse); a = _mm_shuffle_ps(accum_sse, accum_sse, _MM_SHUFFLE(1,0,3,2)); accum_sse = _mm_add_ps(a, accum_sse); _mm_store_ss(&accum, accum_sse); #elif EINSUM_USE_SSE2 && @float64@ /* Add the two SSE2 values and put in accum */ a = _mm_shuffle_pd(accum_sse, accum_sse, _MM_SHUFFLE2(0,1)); accum_sse = _mm_add_pd(a, accum_sse); _mm_store_sd(&accum, accum_sse); #endif /* Finish off the loop */ goto finish_after_unrolled_loop; } #endif /* @nop@ == 1 */ static void @name@_sum_of_products_outstride0_@noplabel@(int nop, char **dataptr, npy_intp *strides, npy_intp count) { #if @complex@ @temptype@ accum_re = 0, accum_im = 0; #else @temptype@ accum = 0; #endif #if (@nop@ == 1) || (@nop@ <= 3 && !@complex@) char *data0 = dataptr[0]; npy_intp stride0 = strides[0]; #endif #if (@nop@ == 2 || @nop@ == 3) && !@complex@ char *data1 = dataptr[1]; npy_intp stride1 = strides[1]; #endif #if (@nop@ == 3) && !@complex@ char *data2 = dataptr[2]; npy_intp stride2 = strides[2]; #endif NPY_EINSUM_DBG_PRINT1("@name@_sum_of_products_outstride0_@noplabel@ (%d)\n", (int)count); while (count--) { #if !@complex@ # if @nop@ == 1 accum += @from@(*(@type@ *)data0); data0 += stride0; # elif @nop@ == 2 accum += @from@(*(@type@ *)data0) * @from@(*(@type@ *)data1); data0 += stride0; data1 += stride1; # elif @nop@ == 3 accum += @from@(*(@type@ *)data0) * @from@(*(@type@ *)data1) * @from@(*(@type@ *)data2); data0 += stride0; data1 += stride1; data2 += stride2; # else @temptype@ temp = @from@(*(@type@ *)dataptr[0]); int i; for (i = 1; i < nop; ++i) { temp *= @from@(*(@type@ *)dataptr[i]); } accum += temp; for (i = 0; i < nop; ++i) { dataptr[i] += strides[i]; } # endif #else /* complex */ # if @nop@ == 1 accum_re += ((@temptype@ *)data0)[0]; accum_im += ((@temptype@ *)data0)[1]; data0 += stride0; # else # if @nop@ <= 3 #define _SUMPROD_NOP @nop@ # else #define _SUMPROD_NOP nop # endif @temptype@ re, im, tmp; int i; re = ((@temptype@ *)dataptr[0])[0]; im = ((@temptype@ *)dataptr[0])[1]; for (i = 1; i < _SUMPROD_NOP; ++i) { tmp = re * ((@temptype@ *)dataptr[i])[0] - im * ((@temptype@ *)dataptr[i])[1]; im = re * ((@temptype@ *)dataptr[i])[1] + im * ((@temptype@ *)dataptr[i])[0]; re = tmp; } accum_re += re; accum_im += im; for (i = 0; i < _SUMPROD_NOP; ++i) { dataptr[i] += strides[i]; } #undef _SUMPROD_NOP # endif #endif } #if @complex@ # if @nop@ <= 3 ((@temptype@ *)dataptr[@nop@])[0] += accum_re; ((@temptype@ *)dataptr[@nop@])[1] += accum_im; # else ((@temptype@ *)dataptr[nop])[0] += accum_re; ((@temptype@ *)dataptr[nop])[1] += accum_im; # endif #else # if @nop@ <= 3 *((@type@ *)dataptr[@nop@]) = @to@(accum + @from@(*((@type@ *)dataptr[@nop@]))); # else *((@type@ *)dataptr[nop]) = @to@(accum + @from@(*((@type@ *)dataptr[nop]))); # endif #endif } /**end repeat1**/ /**end repeat**/ /* Do OR of ANDs for the boolean type */ /**begin repeat * #nop = 1, 2, 3, 1000# * #noplabel = one, two, three, any# */ static void bool_sum_of_products_@noplabel@(int nop, char **dataptr, npy_intp *strides, npy_intp count) { #if (@nop@ <= 3) char *data0 = dataptr[0]; npy_intp stride0 = strides[0]; #endif #if (@nop@ == 2 || @nop@ == 3) char *data1 = dataptr[1]; npy_intp stride1 = strides[1]; #endif #if (@nop@ == 3) char *data2 = dataptr[2]; npy_intp stride2 = strides[2]; #endif #if (@nop@ <= 3) char *data_out = dataptr[@nop@]; npy_intp stride_out = strides[@nop@]; #endif while (count--) { #if @nop@ == 1 *(npy_bool *)data_out = *(npy_bool *)data0 || *(npy_bool *)data_out; data0 += stride0; data_out += stride_out; #elif @nop@ == 2 *(npy_bool *)data_out = (*(npy_bool *)data0 && *(npy_bool *)data1) || *(npy_bool *)data_out; data0 += stride0; data1 += stride1; data_out += stride_out; #elif @nop@ == 3 *(npy_bool *)data_out = (*(npy_bool *)data0 && *(npy_bool *)data1 && *(npy_bool *)data2) || *(npy_bool *)data_out; data0 += stride0; data1 += stride1; data2 += stride2; data_out += stride_out; #else npy_bool temp = *(npy_bool *)dataptr[0]; int i; for (i = 1; i < nop; ++i) { temp = temp && *(npy_bool *)dataptr[i]; } *(npy_bool *)dataptr[nop] = temp || *(npy_bool *)dataptr[i]; for (i = 0; i <= nop; ++i) { dataptr[i] += strides[i]; } #endif } } static void bool_sum_of_products_contig_@noplabel@(int nop, char **dataptr, npy_intp *strides, npy_intp count) { #if (@nop@ <= 3) char *data0 = dataptr[0]; #endif #if (@nop@ == 2 || @nop@ == 3) char *data1 = dataptr[1]; #endif #if (@nop@ == 3) char *data2 = dataptr[2]; #endif #if (@nop@ <= 3) char *data_out = dataptr[@nop@]; #endif #if (@nop@ <= 3) /* This is placed before the main loop to make small counts faster */ finish_after_unrolled_loop: switch (count) { /**begin repeat1 * #i = 6, 5, 4, 3, 2, 1, 0# */ case @i@+1: # if @nop@ == 1 *((npy_bool *)data_out + @i@) = (*((npy_bool *)data0 + @i@)) || (*((npy_bool *)data_out + @i@)); data0 += 8*sizeof(npy_bool); data_out += 8*sizeof(npy_bool); # elif @nop@ == 2 *((npy_bool *)data_out + @i@) = ((*((npy_bool *)data0 + @i@)) && (*((npy_bool *)data1 + @i@))) || (*((npy_bool *)data_out + @i@)); data0 += 8*sizeof(npy_bool); data1 += 8*sizeof(npy_bool); data_out += 8*sizeof(npy_bool); # elif @nop@ == 3 *((npy_bool *)data_out + @i@) = ((*((npy_bool *)data0 + @i@)) && (*((npy_bool *)data1 + @i@)) && (*((npy_bool *)data2 + @i@))) || (*((npy_bool *)data_out + @i@)); data0 += 8*sizeof(npy_bool); data1 += 8*sizeof(npy_bool); data2 += 8*sizeof(npy_bool); data_out += 8*sizeof(npy_bool); # endif /**end repeat1**/ case 0: return; } #endif /* Unroll the loop by 8 for fixed-size nop */ #if (@nop@ <= 3) while (count >= 8) { count -= 8; #else while (count--) { #endif # if @nop@ == 1 /**begin repeat1 * #i = 0, 1, 2, 3, 4, 5, 6, 7# */ *((npy_bool *)data_out + @i@) = (*((npy_bool *)data0 + @i@)) || (*((npy_bool *)data_out + @i@)); /**end repeat1**/ data0 += 8*sizeof(npy_bool); data_out += 8*sizeof(npy_bool); # elif @nop@ == 2 /**begin repeat1 * #i = 0, 1, 2, 3, 4, 5, 6, 7# */ *((npy_bool *)data_out + @i@) = ((*((npy_bool *)data0 + @i@)) && (*((npy_bool *)data1 + @i@))) || (*((npy_bool *)data_out + @i@)); /**end repeat1**/ data0 += 8*sizeof(npy_bool); data1 += 8*sizeof(npy_bool); data_out += 8*sizeof(npy_bool); # elif @nop@ == 3 /**begin repeat1 * #i = 0, 1, 2, 3, 4, 5, 6, 7# */ *((npy_bool *)data_out + @i@) = ((*((npy_bool *)data0 + @i@)) && (*((npy_bool *)data1 + @i@)) && (*((npy_bool *)data2 + @i@))) || (*((npy_bool *)data_out + @i@)); /**end repeat1**/ data0 += 8*sizeof(npy_bool); data1 += 8*sizeof(npy_bool); data2 += 8*sizeof(npy_bool); data_out += 8*sizeof(npy_bool); # else npy_bool temp = *(npy_bool *)dataptr[0]; int i; for (i = 1; i < nop; ++i) { temp = temp && *(npy_bool *)dataptr[i]; } *(npy_bool *)dataptr[nop] = temp || *(npy_bool *)dataptr[i]; for (i = 0; i <= nop; ++i) { dataptr[i] += sizeof(npy_bool); } # endif } /* If the loop was unrolled, we need to finish it off */ #if (@nop@ <= 3) goto finish_after_unrolled_loop; #endif } static void bool_sum_of_products_outstride0_@noplabel@(int nop, char **dataptr, npy_intp *strides, npy_intp count) { npy_bool accum = 0; #if (@nop@ <= 3) char *data0 = dataptr[0]; npy_intp stride0 = strides[0]; #endif #if (@nop@ == 2 || @nop@ == 3) char *data1 = dataptr[1]; npy_intp stride1 = strides[1]; #endif #if (@nop@ == 3) char *data2 = dataptr[2]; npy_intp stride2 = strides[2]; #endif while (count--) { #if @nop@ == 1 accum = *(npy_bool *)data0 || accum; data0 += stride0; #elif @nop@ == 2 accum = (*(npy_bool *)data0 && *(npy_bool *)data1) || accum; data0 += stride0; data1 += stride1; #elif @nop@ == 3 accum = (*(npy_bool *)data0 && *(npy_bool *)data1 && *(npy_bool *)data2) || accum; data0 += stride0; data1 += stride1; data2 += stride2; #else npy_bool temp = *(npy_bool *)dataptr[0]; int i; for (i = 1; i < nop; ++i) { temp = temp && *(npy_bool *)dataptr[i]; } accum = temp || accum; for (i = 0; i <= nop; ++i) { dataptr[i] += strides[i]; } #endif } # if @nop@ <= 3 *((npy_bool *)dataptr[@nop@]) = accum || *((npy_bool *)dataptr[@nop@]); # else *((npy_bool *)dataptr[nop]) = accum || *((npy_bool *)dataptr[nop]); # endif } /**end repeat**/ typedef void (*sum_of_products_fn)(int, char **, npy_intp *, npy_intp); /* These tables need to match up with the type enum */ static sum_of_products_fn _contig_outstride0_unary_specialization_table[NPY_NTYPES] = { /**begin repeat * #name = bool, * byte, ubyte, * short, ushort, * int, uint, * long, ulong, * longlong, ulonglong, * float, double, longdouble, * cfloat, cdouble, clongdouble, * object, string, unicode, void, * datetime, timedelta, half# * #use = 0, * 1, 1, * 1, 1, * 1, 1, * 1, 1, * 1, 1, * 1, 1, 1, * 1, 1, 1, * 0, 0, 0, 0, * 0, 0, 1# */ #if @use@ &@name@_sum_of_products_contig_outstride0_one, #else NULL, #endif /**end repeat**/ }; /* End of _contig_outstride0_unary_specialization_table */ static sum_of_products_fn _binary_specialization_table[NPY_NTYPES][5] = { /**begin repeat * #name = bool, * byte, ubyte, * short, ushort, * int, uint, * long, ulong, * longlong, ulonglong, * float, double, longdouble, * cfloat, cdouble, clongdouble, * object, string, unicode, void, * datetime, timedelta, half# * #use = 0, * 1, 1, * 1, 1, * 1, 1, * 1, 1, * 1, 1, * 1, 1, 1, * 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 1# */ #if @use@ { &@name@_sum_of_products_stride0_contig_outstride0_two, &@name@_sum_of_products_stride0_contig_outcontig_two, &@name@_sum_of_products_contig_stride0_outstride0_two, &@name@_sum_of_products_contig_stride0_outcontig_two, &@name@_sum_of_products_contig_contig_outstride0_two, }, #else {NULL, NULL, NULL, NULL, NULL}, #endif /**end repeat**/ }; /* End of _binary_specialization_table */ static sum_of_products_fn _outstride0_specialized_table[NPY_NTYPES][4] = { /**begin repeat * #name = bool, * byte, ubyte, * short, ushort, * int, uint, * long, ulong, * longlong, ulonglong, * float, double, longdouble, * cfloat, cdouble, clongdouble, * object, string, unicode, void, * datetime, timedelta, half# * #use = 1, * 1, 1, * 1, 1, * 1, 1, * 1, 1, * 1, 1, * 1, 1, 1, * 1, 1, 1, * 0, 0, 0, 0, * 0, 0, 1# */ #if @use@ { &@name@_sum_of_products_outstride0_any, &@name@_sum_of_products_outstride0_one, &@name@_sum_of_products_outstride0_two, &@name@_sum_of_products_outstride0_three }, #else {NULL, NULL, NULL, NULL}, #endif /**end repeat**/ }; /* End of _outstride0_specialized_table */ static sum_of_products_fn _allcontig_specialized_table[NPY_NTYPES][4] = { /**begin repeat * #name = bool, * byte, ubyte, * short, ushort, * int, uint, * long, ulong, * longlong, ulonglong, * float, double, longdouble, * cfloat, cdouble, clongdouble, * object, string, unicode, void, * datetime, timedelta, half# * #use = 1, * 1, 1, * 1, 1, * 1, 1, * 1, 1, * 1, 1, * 1, 1, 1, * 1, 1, 1, * 0, 0, 0, 0, * 0, 0, 1# */ #if @use@ { &@name@_sum_of_products_contig_any, &@name@_sum_of_products_contig_one, &@name@_sum_of_products_contig_two, &@name@_sum_of_products_contig_three }, #else {NULL, NULL, NULL, NULL}, #endif /**end repeat**/ }; /* End of _allcontig_specialized_table */ static sum_of_products_fn _unspecialized_table[NPY_NTYPES][4] = { /**begin repeat * #name = bool, * byte, ubyte, * short, ushort, * int, uint, * long, ulong, * longlong, ulonglong, * float, double, longdouble, * cfloat, cdouble, clongdouble, * object, string, unicode, void, * datetime, timedelta, half# * #use = 1, * 1, 1, * 1, 1, * 1, 1, * 1, 1, * 1, 1, * 1, 1, 1, * 1, 1, 1, * 0, 0, 0, 0, * 0, 0, 1# */ #if @use@ { &@name@_sum_of_products_any, &@name@_sum_of_products_one, &@name@_sum_of_products_two, &@name@_sum_of_products_three }, #else {NULL, NULL, NULL, NULL}, #endif /**end repeat**/ }; /* End of _unnspecialized_table */ static sum_of_products_fn get_sum_of_products_function(int nop, int type_num, npy_intp itemsize, npy_intp *fixed_strides) { int iop; if (type_num >= NPY_NTYPES) { return NULL; } /* contiguous reduction */ if (nop == 1 && fixed_strides[0] == itemsize && fixed_strides[1] == 0) { sum_of_products_fn ret = _contig_outstride0_unary_specialization_table[type_num]; if (ret != NULL) { return ret; } } /* nop of 2 has more specializations */ if (nop == 2) { /* Encode the zero/contiguous strides */ int code; code = (fixed_strides[0] == 0) ? 0 : (fixed_strides[0] == itemsize) ? 2*2*1 : 8; code += (fixed_strides[1] == 0) ? 0 : (fixed_strides[1] == itemsize) ? 2*1 : 8; code += (fixed_strides[2] == 0) ? 0 : (fixed_strides[2] == itemsize) ? 1 : 8; if (code >= 2 && code < 7) { sum_of_products_fn ret = _binary_specialization_table[type_num][code-2]; if (ret != NULL) { return ret; } } } /* Inner loop with an output stride of 0 */ if (fixed_strides[nop] == 0) { return _outstride0_specialized_table[type_num][nop <= 3 ? nop : 0]; } /* Check for all contiguous */ for (iop = 0; iop < nop; ++iop) { if (fixed_strides[iop] != itemsize) { break; } } /* Contiguous loop */ if (iop == nop) { return _allcontig_specialized_table[type_num][nop <= 3 ? nop : 0]; } /* None of the above specializations caught it, general loops */ return _unspecialized_table[type_num][nop <= 3 ? nop : 0]; } /* * Parses the subscripts for one operand into an output * of 'ndim' labels */ static int parse_operand_subscripts(char *subscripts, int length, int ndim, int iop, char *out_labels, char *out_label_counts, int *out_min_label, int *out_max_label, int *out_num_labels, EINSUM_BROADCAST *out_broadcast) { int i, idim, ndim_left, label; int left_labels = 0, right_labels = 0, ellipsis = 0; /* Process the labels from the end until the ellipsis */ idim = ndim-1; for (i = length-1; i >= 0; --i) { label = subscripts[i]; /* A label for an axis */ if (label > 0 && isalpha(label)) { if (idim >= 0) { out_labels[idim--] = label; /* Calculate the min and max labels */ if (label < *out_min_label) { *out_min_label = label; } if (label > *out_max_label) { *out_max_label = label; } /* If it's the first time we see this label, count it */ if (out_label_counts[label] == 0) { (*out_num_labels)++; } out_label_counts[label]++; right_labels = 1; } else { PyErr_Format(PyExc_ValueError, "einstein sum subscripts string contains " "too many subscripts for operand %d", iop); return 0; } } /* The end of the ellipsis */ else if (label == '.') { /* A valid ellipsis */ if (i >= 2 && subscripts[i-1] == '.' && subscripts[i-2] == '.') { ellipsis = 1; length = i-2; break; } else { PyErr_SetString(PyExc_ValueError, "einstein sum subscripts string contains a " "'.' that is not part of an ellipsis ('...')"); return 0; } } else if (label != ' ') { PyErr_Format(PyExc_ValueError, "invalid subscript '%c' in einstein sum " "subscripts string, subscripts must " "be letters", (char)label); return 0; } } if (!ellipsis && idim != -1) { PyErr_Format(PyExc_ValueError, "operand has more dimensions than subscripts " "given in einstein sum, but no '...' ellipsis " "provided to broadcast the extra dimensions."); return 0; } /* Reduce ndim to just the dimensions left to fill at the beginning */ ndim_left = idim+1; idim = 0; /* * If we stopped because of an ellipsis, start again from the beginning. * The length was truncated to end at the ellipsis in this case. */ if (i > 0) { for (i = 0; i < length; ++i) { label = subscripts[i]; /* A label for an axis */ if (label > 0 && isalnum(label)) { if (idim < ndim_left) { out_labels[idim++] = label; /* Calculate the min and max labels */ if (label < *out_min_label) { *out_min_label = label; } if (label > *out_max_label) { *out_max_label = label; } /* If it's the first time we see this label, count it */ if (out_label_counts[label] == 0) { (*out_num_labels)++; } out_label_counts[label]++; left_labels = 1; } else { PyErr_Format(PyExc_ValueError, "einstein sum subscripts string contains " "too many subscripts for operand %d", iop); return 0; } } else if (label != ' ') { PyErr_Format(PyExc_ValueError, "invalid subscript '%c' in einstein sum " "subscripts string, subscripts must " "be letters", (char)label); return 0; } } } /* Set the remaining labels to 0 */ while (idim < ndim_left) { out_labels[idim++] = 0; } /* * Find any labels duplicated for this operand, and turn them * into negative offets to the axis to merge with. * * In C, the char type may be signed or unsigned, but with * twos complement arithmetic the char is ok either way here, and * later where it matters the char is cast to a signed char. */ for (idim = 0; idim < ndim-1; ++idim) { char *next; /* If this is a proper label, find any duplicates of it */ label = out_labels[idim]; if (label > 0) { /* Search for the next matching label */ next = (char *)memchr(out_labels+idim+1, label, ndim-idim-1); while (next != NULL) { /* The offset from next to out_labels[idim] (negative) */ *next = (char)((out_labels+idim)-next); /* Search for the next matching label */ next = (char *)memchr(next+1, label, out_labels+ndim-1-next); } } } 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; } /* * Parses the subscripts for the output operand into an output * that requires 'ndim_broadcast' unlabeled dimensions, returning * the number of output dimensions. Returns -1 if there is an error. */ static int parse_output_subscripts(char *subscripts, int length, int ndim_broadcast, const char *label_counts, char *out_labels, EINSUM_BROADCAST *out_broadcast) { int i, nlabels, label, idim, ndim, ndim_left; int left_labels = 0, right_labels = 0, ellipsis = 0; /* Count the labels, making sure they're all unique and valid */ nlabels = 0; for (i = 0; i < length; ++i) { label = subscripts[i]; if (label > 0 && isalpha(label)) { /* Check if it occurs again */ if (memchr(subscripts+i+1, label, length-i-1) == NULL) { /* Check that it was used in the inputs */ if (label_counts[label] == 0) { PyErr_Format(PyExc_ValueError, "einstein sum subscripts string included " "output subscript '%c' which never appeared " "in an input", (char)label); return -1; } nlabels++; } else { PyErr_Format(PyExc_ValueError, "einstein sum subscripts string includes " "output subscript '%c' multiple times", (char)label); return -1; } } else if (label != '.' && label != ' ') { PyErr_Format(PyExc_ValueError, "invalid subscript '%c' in einstein sum " "subscripts string, subscripts must " "be letters", (char)label); return -1; } } /* The number of output dimensions */ ndim = ndim_broadcast + nlabels; /* Process the labels from the end until the ellipsis */ idim = ndim-1; for (i = length-1; i >= 0; --i) { label = subscripts[i]; /* A label for an axis */ if (label != '.' && label != ' ') { if (idim >= 0) { out_labels[idim--] = label; } else { PyErr_Format(PyExc_ValueError, "einstein sum subscripts string contains " "too many output subscripts"); return -1; } right_labels = 1; } /* The end of the ellipsis */ else if (label == '.') { /* A valid ellipsis */ if (i >= 2 && subscripts[i-1] == '.' && subscripts[i-2] == '.') { ellipsis = 1; length = i-2; break; } else { PyErr_SetString(PyExc_ValueError, "einstein sum subscripts string contains a " "'.' that is not part of an ellipsis ('...')"); return -1; } } } if (!ellipsis && idim != -1) { PyErr_SetString(PyExc_ValueError, "output has more dimensions than subscripts " "given in einstein sum, but no '...' ellipsis " "provided to broadcast the extra dimensions."); return 0; } /* Reduce ndim to just the dimensions left to fill at the beginning */ ndim_left = idim+1; idim = 0; /* * If we stopped because of an ellipsis, start again from the beginning. * The length was truncated to end at the ellipsis in this case. */ if (i > 0) { for (i = 0; i < length; ++i) { label = subscripts[i]; /* A label for an axis */ if (label != '.' && label != ' ') { if (idim < ndim_left) { out_labels[idim++] = label; } else { PyErr_Format(PyExc_ValueError, "einstein sum subscripts string contains " "too many subscripts for the output"); return -1; } left_labels = 1; } else { PyErr_SetString(PyExc_ValueError, "einstein sum subscripts string contains a " "'.' that is not part of an ellipsis ('...')"); return -1; } } } /* Set the remaining output labels to 0 */ while (idim < ndim_left) { 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; } /* * When there's just one operand and no reduction, we * can return a view into op. This calculates the view * if possible. */ static int get_single_op_view(PyArrayObject *op, int iop, char *labels, int ndim_output, char *output_labels, PyArrayObject **ret) { npy_intp new_strides[NPY_MAXDIMS]; npy_intp new_dims[NPY_MAXDIMS]; char *out_label; int label, i, idim, ndim, ibroadcast = 0; ndim = PyArray_NDIM(op); /* Initialize the dimensions and strides to zero */ for (idim = 0; idim < ndim_output; ++idim) { new_dims[idim] = 0; new_strides[idim] = 0; } /* Match the labels in the operand with the output labels */ for (idim = 0; idim < ndim; ++idim) { /* * The char type may be either signed or unsigned, we * need it to be signed here. */ label = (signed char)labels[idim]; /* If this label says to merge axes, get the actual label */ if (label < 0) { label = labels[idim+label]; } /* If the label is 0, it's an unlabeled broadcast dimension */ if (label == 0) { /* The next output label that's a broadcast dimension */ for (; ibroadcast < ndim_output; ++ibroadcast) { if (output_labels[ibroadcast] == 0) { break; } } if (ibroadcast == ndim_output) { PyErr_SetString(PyExc_ValueError, "output had too few broadcast dimensions"); return 0; } new_dims[ibroadcast] = PyArray_DIM(op, idim); new_strides[ibroadcast] = PyArray_STRIDE(op, idim); ++ibroadcast; } else { /* Find the position for this dimension in the output */ out_label = (char *)memchr(output_labels, label, ndim_output); /* If it's not found, reduction -> can't return a view */ if (out_label == NULL) { break; } /* Update the dimensions and strides of the output */ i = out_label - output_labels; if (new_dims[i] != 0 && new_dims[i] != PyArray_DIM(op, idim)) { PyErr_Format(PyExc_ValueError, "dimensions in operand %d for collapsing " "index '%c' don't match (%d != %d)", iop, label, (int)new_dims[i], (int)PyArray_DIM(op, idim)); return 0; } new_dims[i] = PyArray_DIM(op, idim); new_strides[i] += PyArray_STRIDE(op, idim); } } /* If we processed all the input axes, return a view */ if (idim == ndim) { Py_INCREF(PyArray_DESCR(op)); *ret = (PyArrayObject *)PyArray_NewFromDescr( Py_TYPE(op), PyArray_DESCR(op), ndim_output, new_dims, new_strides, PyArray_DATA(op), 0, (PyObject *)op); if (*ret == NULL) { return 0; } if (!PyArray_Check(*ret)) { Py_DECREF(*ret); *ret = NULL; PyErr_SetString(PyExc_RuntimeError, "NewFromDescr failed to return an array"); return 0; } PyArray_UpdateFlags(*ret, NPY_ARRAY_C_CONTIGUOUS| NPY_ARRAY_ALIGNED| NPY_ARRAY_F_CONTIGUOUS); Py_INCREF(op); if (PyArray_SetBaseObject(*ret, (PyObject *)op) < 0) { Py_DECREF(*ret); *ret = NULL; return 0; } return 1; } /* Return success, but that we couldn't make a view */ *ret = NULL; return 1; } static PyArrayObject * get_combined_dims_view(PyArrayObject *op, int iop, char *labels) { npy_intp new_strides[NPY_MAXDIMS]; npy_intp new_dims[NPY_MAXDIMS]; int i, idim, ndim, icombine, combineoffset, label; int icombinemap[NPY_MAXDIMS]; PyArrayObject *ret = NULL; ndim = PyArray_NDIM(op); /* Initialize the dimensions and strides to zero */ for (idim = 0; idim < ndim; ++idim) { new_dims[idim] = 0; new_strides[idim] = 0; } /* Copy the dimensions and strides, except when collapsing */ icombine = 0; for (idim = 0; idim < ndim; ++idim) { /* * The char type may be either signed or unsigned, we * need it to be signed here. */ label = (signed char)labels[idim]; /* If this label says to merge axes, get the actual label */ if (label < 0) { combineoffset = label; label = labels[idim+label]; } else { combineoffset = 0; if (icombine != idim) { labels[icombine] = labels[idim]; } icombinemap[idim] = icombine; } /* If the label is 0, it's an unlabeled broadcast dimension */ if (label == 0) { new_dims[icombine] = PyArray_DIM(op, idim); new_strides[icombine] = PyArray_STRIDE(op, idim); } else { /* Update the combined axis dimensions and strides */ i = idim + combineoffset; if (combineoffset < 0 && new_dims[i] != PyArray_DIM(op, idim)) { PyErr_Format(PyExc_ValueError, "dimensions in operand %d for collapsing " "index '%c' don't match (%d != %d)", iop, label, (int)new_dims[i], (int)PyArray_DIM(op, idim)); return NULL; } i = icombinemap[i]; new_dims[i] = PyArray_DIM(op, idim); new_strides[i] += PyArray_STRIDE(op, idim); } /* If the label didn't say to combine axes, increment dest i */ if (combineoffset == 0) { icombine++; } } /* The compressed number of dimensions */ ndim = icombine; Py_INCREF(PyArray_DESCR(op)); ret = (PyArrayObject *)PyArray_NewFromDescr( Py_TYPE(op), PyArray_DESCR(op), ndim, new_dims, new_strides, PyArray_DATA(op), PyArray_ISWRITEABLE(op) ? NPY_ARRAY_WRITEABLE : 0, (PyObject *)op); if (ret == NULL) { return NULL; } if (!PyArray_Check(ret)) { Py_DECREF(ret); PyErr_SetString(PyExc_RuntimeError, "NewFromDescr failed to return an array"); return NULL; } PyArray_UpdateFlags(ret, NPY_ARRAY_C_CONTIGUOUS| NPY_ARRAY_ALIGNED| NPY_ARRAY_F_CONTIGUOUS); Py_INCREF(op); if (PyArray_SetBaseObject(ret, (PyObject *)op) < 0) { Py_DECREF(ret); return NULL; } return ret; } static int prepare_op_axes(int ndim, int iop, char *labels, int *axes, int ndim_iter, char *iter_labels, EINSUM_BROADCAST broadcast) { 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; } } } } /* 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 (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; } } /* 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; } } } } /* 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; } /* Otherwise use it */ else { axes[i] = match - labels; } } } } return 1; } static int unbuffered_loop_nop1_ndim2(NpyIter *iter) { npy_intp coord, shape[2], strides[2][2]; char *ptrs[2][2], *ptr; sum_of_products_fn sop; #if NPY_EINSUM_DBG_TRACING NpyIter_DebugPrint(iter); #endif NPY_EINSUM_DBG_PRINT("running hand-coded 1-op 2-dim loop\n"); NpyIter_GetShape(iter, shape); memcpy(strides[0], NpyIter_GetAxisStrideArray(iter, 0), 2*sizeof(npy_intp)); memcpy(strides[1], NpyIter_GetAxisStrideArray(iter, 1), 2*sizeof(npy_intp)); memcpy(ptrs[0], NpyIter_GetInitialDataPtrArray(iter), 2*sizeof(char *)); memcpy(ptrs[1], ptrs[0], 2*sizeof(char*)); sop = get_sum_of_products_function(1, NpyIter_GetDescrArray(iter)[0]->type_num, NpyIter_GetDescrArray(iter)[0]->elsize, strides[0]); if (sop == NULL) { PyErr_SetString(PyExc_TypeError, "invalid data type for einsum"); return -1; } /* * Since the iterator wasn't tracking coordinates, the * loop provided by the iterator is in Fortran-order. */ for (coord = shape[1]; coord > 0; --coord) { sop(1, ptrs[0], strides[0], shape[0]); ptr = ptrs[1][0] + strides[1][0]; ptrs[0][0] = ptrs[1][0] = ptr; ptr = ptrs[1][1] + strides[1][1]; ptrs[0][1] = ptrs[1][1] = ptr; } return 0; } static int unbuffered_loop_nop1_ndim3(NpyIter *iter) { npy_intp coords[2], shape[3], strides[3][2]; char *ptrs[3][2], *ptr; sum_of_products_fn sop; #if NPY_EINSUM_DBG_TRACING NpyIter_DebugPrint(iter); #endif NPY_EINSUM_DBG_PRINT("running hand-coded 1-op 3-dim loop\n"); NpyIter_GetShape(iter, shape); memcpy(strides[0], NpyIter_GetAxisStrideArray(iter, 0), 2*sizeof(npy_intp)); memcpy(strides[1], NpyIter_GetAxisStrideArray(iter, 1), 2*sizeof(npy_intp)); memcpy(strides[2], NpyIter_GetAxisStrideArray(iter, 2), 2*sizeof(npy_intp)); memcpy(ptrs[0], NpyIter_GetInitialDataPtrArray(iter), 2*sizeof(char *)); memcpy(ptrs[1], ptrs[0], 2*sizeof(char*)); memcpy(ptrs[2], ptrs[0], 2*sizeof(char*)); sop = get_sum_of_products_function(1, NpyIter_GetDescrArray(iter)[0]->type_num, NpyIter_GetDescrArray(iter)[0]->elsize, strides[0]); if (sop == NULL) { PyErr_SetString(PyExc_TypeError, "invalid data type for einsum"); return -1; } /* * Since the iterator wasn't tracking coordinates, the * loop provided by the iterator is in Fortran-order. */ for (coords[1] = shape[2]; coords[1] > 0; --coords[1]) { for (coords[0] = shape[1]; coords[0] > 0; --coords[0]) { sop(1, ptrs[0], strides[0], shape[0]); ptr = ptrs[1][0] + strides[1][0]; ptrs[0][0] = ptrs[1][0] = ptr; ptr = ptrs[1][1] + strides[1][1]; ptrs[0][1] = ptrs[1][1] = ptr; } ptr = ptrs[2][0] + strides[2][0]; ptrs[0][0] = ptrs[1][0] = ptrs[2][0] = ptr; ptr = ptrs[2][1] + strides[2][1]; ptrs[0][1] = ptrs[1][1] = ptrs[2][1] = ptr; } return 0; } static int unbuffered_loop_nop2_ndim2(NpyIter *iter) { npy_intp coord, shape[2], strides[2][3]; char *ptrs[2][3], *ptr; sum_of_products_fn sop; #if NPY_EINSUM_DBG_TRACING NpyIter_DebugPrint(iter); #endif NPY_EINSUM_DBG_PRINT("running hand-coded 2-op 2-dim loop\n"); NpyIter_GetShape(iter, shape); memcpy(strides[0], NpyIter_GetAxisStrideArray(iter, 0), 3*sizeof(npy_intp)); memcpy(strides[1], NpyIter_GetAxisStrideArray(iter, 1), 3*sizeof(npy_intp)); memcpy(ptrs[0], NpyIter_GetInitialDataPtrArray(iter), 3*sizeof(char *)); memcpy(ptrs[1], ptrs[0], 3*sizeof(char*)); sop = get_sum_of_products_function(2, NpyIter_GetDescrArray(iter)[0]->type_num, NpyIter_GetDescrArray(iter)[0]->elsize, strides[0]); if (sop == NULL) { PyErr_SetString(PyExc_TypeError, "invalid data type for einsum"); return -1; } /* * Since the iterator wasn't tracking coordinates, the * loop provided by the iterator is in Fortran-order. */ for (coord = shape[1]; coord > 0; --coord) { sop(2, ptrs[0], strides[0], shape[0]); ptr = ptrs[1][0] + strides[1][0]; ptrs[0][0] = ptrs[1][0] = ptr; ptr = ptrs[1][1] + strides[1][1]; ptrs[0][1] = ptrs[1][1] = ptr; ptr = ptrs[1][2] + strides[1][2]; ptrs[0][2] = ptrs[1][2] = ptr; } return 0; } static int unbuffered_loop_nop2_ndim3(NpyIter *iter) { npy_intp coords[2], shape[3], strides[3][3]; char *ptrs[3][3], *ptr; sum_of_products_fn sop; #if NPY_EINSUM_DBG_TRACING NpyIter_DebugPrint(iter); #endif NPY_EINSUM_DBG_PRINT("running hand-coded 2-op 3-dim loop\n"); NpyIter_GetShape(iter, shape); memcpy(strides[0], NpyIter_GetAxisStrideArray(iter, 0), 3*sizeof(npy_intp)); memcpy(strides[1], NpyIter_GetAxisStrideArray(iter, 1), 3*sizeof(npy_intp)); memcpy(strides[2], NpyIter_GetAxisStrideArray(iter, 2), 3*sizeof(npy_intp)); memcpy(ptrs[0], NpyIter_GetInitialDataPtrArray(iter), 3*sizeof(char *)); memcpy(ptrs[1], ptrs[0], 3*sizeof(char*)); memcpy(ptrs[2], ptrs[0], 3*sizeof(char*)); sop = get_sum_of_products_function(2, NpyIter_GetDescrArray(iter)[0]->type_num, NpyIter_GetDescrArray(iter)[0]->elsize, strides[0]); if (sop == NULL) { PyErr_SetString(PyExc_TypeError, "invalid data type for einsum"); return -1; } /* * Since the iterator wasn't tracking coordinates, the * loop provided by the iterator is in Fortran-order. */ for (coords[1] = shape[2]; coords[1] > 0; --coords[1]) { for (coords[0] = shape[1]; coords[0] > 0; --coords[0]) { sop(2, ptrs[0], strides[0], shape[0]); ptr = ptrs[1][0] + strides[1][0]; ptrs[0][0] = ptrs[1][0] = ptr; ptr = ptrs[1][1] + strides[1][1]; ptrs[0][1] = ptrs[1][1] = ptr; ptr = ptrs[1][2] + strides[1][2]; ptrs[0][2] = ptrs[1][2] = ptr; } ptr = ptrs[2][0] + strides[2][0]; ptrs[0][0] = ptrs[1][0] = ptrs[2][0] = ptr; ptr = ptrs[2][1] + strides[2][1]; ptrs[0][1] = ptrs[1][1] = ptrs[2][1] = ptr; ptr = ptrs[2][2] + strides[2][2]; ptrs[0][2] = ptrs[1][2] = ptrs[2][2] = ptr; } return 0; } /*NUMPY_API * This function provides summation of array elements according to * the Einstein summation convention. For example: * - trace(a) -> einsum("ii", a) * - transpose(a) -> einsum("ji", a) * - multiply(a,b) -> einsum(",", a, b) * - inner(a,b) -> einsum("i,i", a, b) * - outer(a,b) -> einsum("i,j", a, b) * - matvec(a,b) -> einsum("ij,j", a, b) * - matmat(a,b) -> einsum("ij,jk", a, b) * * subscripts: The string of subscripts for einstein summation. * nop: The number of operands * op_in: The array of operands * dtype: Either NULL, or the data type to force the calculation as. * order: The order for the calculation/the output axes. * casting: What kind of casts should be permitted. * out: Either NULL, or an array into which the output should be placed. * * By default, the labels get placed in alphabetical order * at the end of the output. So, if c = einsum("i,j", a, b) * then c[i,j] == a[i]*b[j], but if c = einsum("j,i", a, b) * then c[i,j] = a[j]*b[i]. * * Alternatively, you can control the output order or prevent * an axis from being summed/force an axis to be summed by providing * indices for the output. This allows us to turn 'trace' into * 'diag', for example. * - diag(a) -> einsum("ii->i", a) * - sum(a, axis=0) -> einsum("i...->", a) * * Subscripts at the beginning and end may be specified by * putting an ellipsis "..." in the middle. For example, * the function einsum("i...i", a) takes the diagonal of * the first and last dimensions of the operand, and * einsum("ij...,jk...->ik...") takes the matrix product using * the first two indices of each operand instead of the last two. * * When there is only one operand, no axes being summed, and * no output parameter, this function returns a view * into the operand instead of making a copy. */ NPY_NO_EXPORT PyArrayObject * PyArray_EinsteinSum(char *subscripts, npy_intp nop, PyArrayObject **op_in, PyArray_Descr *dtype, NPY_ORDER order, NPY_CASTING casting, PyArrayObject *out) { int iop, label, min_label = 127, max_label = 0, num_labels; char label_counts[128]; char op_labels[NPY_MAXARGS][NPY_MAXDIMS]; 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; int op_axes_arrays[NPY_MAXARGS][NPY_MAXDIMS]; int *op_axes[NPY_MAXARGS]; npy_uint32 op_flags[NPY_MAXARGS]; NpyIter *iter; sum_of_products_fn sop; npy_intp fixed_strides[NPY_MAXARGS]; /* nop+1 (+1 is for the output) must fit in NPY_MAXARGS */ if (nop >= NPY_MAXARGS) { PyErr_SetString(PyExc_ValueError, "too many operands provided to einstein sum function"); return NULL; } else if (nop < 1) { PyErr_SetString(PyExc_ValueError, "not enough operands provided to einstein sum function"); return NULL; } /* Parse the subscripts string into label_counts and op_labels */ memset(label_counts, 0, sizeof(label_counts)); num_labels = 0; for (iop = 0; iop < nop; ++iop) { int length = (int)strcspn(subscripts, ",-"); if (iop == nop-1 && subscripts[length] == ',') { PyErr_SetString(PyExc_ValueError, "more operands provided to einstein sum function " "than specified in the subscripts string"); return NULL; } else if(iop < nop-1 && subscripts[length] != ',') { PyErr_SetString(PyExc_ValueError, "fewer operands provided to einstein sum function " "than specified in the subscripts string"); return NULL; } 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])) { return NULL; } /* Move subscripts to the start of the labels for the next op */ subscripts += length; if (iop < nop-1) { subscripts++; } } /* * Find the number of broadcast dimensions, which is the maximum * number of labels == 0 in an op_labels array. */ ndim_broadcast = 0; for (iop = 0; iop < nop; ++iop) { npy_intp count_zeros = 0; int ndim; char *labels = op_labels[iop]; ndim = PyArray_NDIM(op_in[iop]); for (idim = 0; idim < ndim; ++idim) { if (labels[idim] == 0) { ++count_zeros; } } if (count_zeros > ndim_broadcast) { ndim_broadcast = count_zeros; } } /* * If there is no output signature, create one using each label * that appeared once, in alphabetical order */ if (subscripts[0] == '\0') { char outsubscripts[NPY_MAXDIMS + 3]; int length; /* If no output was specified, always broadcast left (like normal) */ outsubscripts[0] = '.'; outsubscripts[1] = '.'; outsubscripts[2] = '.'; length = 3; for (label = min_label; label <= max_label; ++label) { if (label_counts[label] == 1) { if (length < NPY_MAXDIMS-1) { outsubscripts[length++] = label; } else { PyErr_SetString(PyExc_ValueError, "einstein sum subscript string has too many " "distinct labels"); return NULL; } } } /* Parse the output subscript string */ ndim_output = parse_output_subscripts(outsubscripts, length, ndim_broadcast, label_counts, output_labels, &broadcast[nop]); } else { if (subscripts[0] != '-' || subscripts[1] != '>') { PyErr_SetString(PyExc_ValueError, "einstein sum subscript string does not " "contain proper '->' output specified"); return NULL; } subscripts += 2; /* Parse the output subscript string */ ndim_output = parse_output_subscripts(subscripts, strlen(subscripts), ndim_broadcast, label_counts, output_labels, &broadcast[nop]); } if (ndim_output < 0) { return NULL; } if (out != NULL && PyArray_NDIM(out) != ndim_output) { PyErr_Format(PyExc_ValueError, "out parameter does not have the correct number of " "dimensions, has %d but should have %d", (int)PyArray_NDIM(out), (int)ndim_output); return NULL; } /* Set all the op references to NULL */ for (iop = 0; iop < nop; ++iop) { op[iop] = NULL; } /* * Process all the input ops, combining dimensions into their * diagonal where specified. */ for (iop = 0; iop < nop; ++iop) { char *labels = op_labels[iop]; int combine, ndim; ndim = PyArray_NDIM(op_in[iop]); /* * If there's just one operand and no output parameter, * first try remapping the axes to the output to return * a view instead of a copy. */ if (iop == 0 && nop == 1 && out == NULL) { ret = NULL; if (!get_single_op_view(op_in[iop], iop, labels, ndim_output, output_labels, &ret)) { return NULL; } if (ret != NULL) { return ret; } } /* * Check whether any dimensions need to be combined * * The char type may be either signed or unsigned, we * need it to be signed here. */ combine = 0; for (idim = 0; idim < ndim; ++idim) { if ((signed char)labels[idim] < 0) { combine = 1; } } /* If any dimensions are combined, create a view which combines them */ if (combine) { op[iop] = get_combined_dims_view(op_in[iop], iop, labels); if (op[iop] == NULL) { goto fail; } } /* No combining needed */ else { Py_INCREF(op_in[iop]); op[iop] = op_in[iop]; } } /* Set the output op */ op[nop] = out; /* * Set up the labels for the iterator (output + combined labels). * Can just share the output_labels memory, because iter_labels * is output_labels with some more labels appended. */ iter_labels = output_labels; ndim_iter = ndim_output; for (label = min_label; label <= max_label; ++label) { if (label_counts[label] > 0 && memchr(output_labels, label, ndim_output) == NULL) { if (ndim_iter >= NPY_MAXDIMS) { PyErr_SetString(PyExc_ValueError, "too many subscripts in einsum"); goto fail; } iter_labels[ndim_iter++] = label; } } /* Set up the op_axes for the iterator */ for (iop = 0; iop < nop; ++iop) { 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])) { goto fail; } } /* Set up the op_dtypes if dtype was provided */ if (dtype == NULL) { op_dtypes = NULL; } else { op_dtypes = op_dtypes_array; for (iop = 0; iop <= nop; ++iop) { op_dtypes[iop] = dtype; } } /* Set the op_axes for the output */ op_axes[nop] = op_axes_arrays[nop]; for (idim = 0; idim < ndim_output; ++idim) { op_axes[nop][idim] = idim; } for (idim = ndim_output; idim < ndim_iter; ++idim) { op_axes[nop][idim] = -1; } /* Set the iterator per-op flags */ for (iop = 0; iop < nop; ++iop) { op_flags[iop] = NPY_ITER_READONLY| NPY_ITER_NBO| NPY_ITER_ALIGNED; } op_flags[nop] = NPY_ITER_READWRITE| NPY_ITER_NBO| NPY_ITER_ALIGNED| NPY_ITER_ALLOCATE| NPY_ITER_NO_BROADCAST; /* Allocate the iterator */ iter = NpyIter_AdvancedNew(nop+1, op, NPY_ITER_EXTERNAL_LOOP| ((dtype != NULL) ? 0 : NPY_ITER_COMMON_DTYPE)| NPY_ITER_BUFFERED| NPY_ITER_DELAY_BUFALLOC| NPY_ITER_GROWINNER| NPY_ITER_REDUCE_OK| NPY_ITER_REFS_OK| NPY_ITER_ZEROSIZE_OK, order, casting, op_flags, op_dtypes, ndim_iter, op_axes, NULL, 0); if (iter == NULL) { goto fail; } /* Initialize the output to all zeros and reset the iterator */ ret = NpyIter_GetOperandArray(iter)[nop]; Py_INCREF(ret); PyArray_AssignZero(ret, NULL); /***************************/ /* * Acceleration for some specific loop structures. Note * that with axis coalescing, inputs with more dimensions can * be reduced to fit into these patterns. */ if (!NpyIter_RequiresBuffering(iter)) { int ndim = NpyIter_GetNDim(iter); switch (nop) { case 1: if (ndim == 2) { if (unbuffered_loop_nop1_ndim2(iter) < 0) { Py_DECREF(ret); ret = NULL; goto fail; } goto finish; } else if (ndim == 3) { if (unbuffered_loop_nop1_ndim3(iter) < 0) { Py_DECREF(ret); ret = NULL; goto fail; } goto finish; } break; case 2: if (ndim == 2) { if (unbuffered_loop_nop2_ndim2(iter) < 0) { Py_DECREF(ret); ret = NULL; goto fail; } goto finish; } else if (ndim == 3) { if (unbuffered_loop_nop2_ndim3(iter) < 0) { Py_DECREF(ret); ret = NULL; goto fail; } goto finish; } break; } } /***************************/ if (NpyIter_Reset(iter, NULL) != NPY_SUCCEED) { Py_DECREF(ret); goto fail; } /* * Get an inner loop function, specializing it based on * the strides that are fixed for the whole loop. */ NpyIter_GetInnerFixedStrideArray(iter, fixed_strides); sop = get_sum_of_products_function(nop, NpyIter_GetDescrArray(iter)[0]->type_num, NpyIter_GetDescrArray(iter)[0]->elsize, fixed_strides); #if NPY_EINSUM_DBG_TRACING NpyIter_DebugPrint(iter); #endif /* Finally, the main loop */ if (sop == NULL) { PyErr_SetString(PyExc_TypeError, "invalid data type for einsum"); Py_DECREF(ret); ret = NULL; } else if (NpyIter_GetIterSize(iter) != 0) { NpyIter_IterNextFunc *iternext; char **dataptr; npy_intp *stride; npy_intp *countptr; int needs_api = NpyIter_IterationNeedsAPI(iter); NPY_BEGIN_THREADS_DEF; iternext = NpyIter_GetIterNext(iter, NULL); if (iternext == NULL) { NpyIter_Deallocate(iter); Py_DECREF(ret); goto fail; } dataptr = NpyIter_GetDataPtrArray(iter); stride = NpyIter_GetInnerStrideArray(iter); countptr = NpyIter_GetInnerLoopSizePtr(iter); if (!needs_api) { NPY_BEGIN_THREADS; } NPY_EINSUM_DBG_PRINT("Einsum loop\n"); do { sop(nop, dataptr, stride, *countptr); } while(iternext(iter)); if (!needs_api) { NPY_END_THREADS; } /* If the API was needed, it may have thrown an error */ if (needs_api && PyErr_Occurred()) { Py_DECREF(ret); ret = NULL; } } finish: NpyIter_Deallocate(iter); for (iop = 0; iop < nop; ++iop) { Py_DECREF(op[iop]); } return ret; fail: for (iop = 0; iop < nop; ++iop) { Py_XDECREF(op[iop]); } return NULL; } numpy-1.8.2/numpy/core/src/multiarray/mapping.h0000664000175100017510000000240512370216243022711 0ustar vagrantvagrant00000000000000#ifndef _NPY_ARRAYMAPPING_H_ #define _NPY_ARRAYMAPPING_H_ #ifdef NPY_ENABLE_SEPARATE_COMPILATION extern NPY_NO_EXPORT PyMappingMethods array_as_mapping; #else NPY_NO_EXPORT PyMappingMethods array_as_mapping; #endif NPY_NO_EXPORT Py_ssize_t array_length(PyArrayObject *self); NPY_NO_EXPORT PyObject * array_item_asarray(PyArrayObject *self, npy_intp i); NPY_NO_EXPORT PyObject * array_item_asscalar(PyArrayObject *self, npy_intp i); NPY_NO_EXPORT PyObject * array_item(PyArrayObject *self, Py_ssize_t i); NPY_NO_EXPORT PyObject * array_subscript_asarray(PyArrayObject *self, PyObject *op); 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); /* * Prototypes for Mapping calls --- not part of the C-API * because only useful as part of a getitem call. */ NPY_NO_EXPORT void PyArray_MapIterReset(PyArrayMapIterObject *mit); NPY_NO_EXPORT void PyArray_MapIterNext(PyArrayMapIterObject *mit); NPY_NO_EXPORT int PyArray_MapIterBind(PyArrayMapIterObject *, PyArrayObject *); NPY_NO_EXPORT PyObject* PyArray_MapIterNew(PyObject *, int, int); #endif numpy-1.8.2/numpy/core/src/multiarray/calculation.h0000664000175100017510000000372512370216242023561 0ustar vagrantvagrant00000000000000#ifndef _NPY_CALCULATION_H_ #define _NPY_CALCULATION_H_ NPY_NO_EXPORT PyObject* PyArray_ArgMax(PyArrayObject* self, int axis, PyArrayObject *out); NPY_NO_EXPORT PyObject* PyArray_ArgMin(PyArrayObject* self, int axis, PyArrayObject *out); NPY_NO_EXPORT PyObject* PyArray_Max(PyArrayObject* self, int axis, PyArrayObject* out); NPY_NO_EXPORT PyObject* PyArray_Min(PyArrayObject* self, int axis, PyArrayObject* out); NPY_NO_EXPORT PyObject* PyArray_Ptp(PyArrayObject* self, int axis, PyArrayObject* out); NPY_NO_EXPORT PyObject* PyArray_Mean(PyArrayObject* self, int axis, int rtype, PyArrayObject* out); NPY_NO_EXPORT PyObject * PyArray_Round(PyArrayObject *a, int decimals, PyArrayObject *out); NPY_NO_EXPORT PyObject* PyArray_Trace(PyArrayObject* self, int offset, int axis1, int axis2, int rtype, PyArrayObject* out); NPY_NO_EXPORT PyObject* PyArray_Clip(PyArrayObject* self, PyObject* min, PyObject* max, PyArrayObject *out); NPY_NO_EXPORT PyObject* PyArray_Conjugate(PyArrayObject* self, PyArrayObject* out); NPY_NO_EXPORT PyObject* PyArray_Round(PyArrayObject* self, int decimals, PyArrayObject* out); NPY_NO_EXPORT PyObject* PyArray_Std(PyArrayObject* self, int axis, int rtype, PyArrayObject* out, int variance); NPY_NO_EXPORT PyObject * __New_PyArray_Std(PyArrayObject *self, int axis, int rtype, PyArrayObject *out, int variance, int num); NPY_NO_EXPORT PyObject* PyArray_Sum(PyArrayObject* self, int axis, int rtype, PyArrayObject* out); NPY_NO_EXPORT PyObject* PyArray_CumSum(PyArrayObject* self, int axis, int rtype, PyArrayObject* out); NPY_NO_EXPORT PyObject* PyArray_Prod(PyArrayObject* self, int axis, int rtype, PyArrayObject* out); NPY_NO_EXPORT PyObject* PyArray_CumProd(PyArrayObject* self, int axis, int rtype, PyArrayObject* out); NPY_NO_EXPORT PyObject* PyArray_All(PyArrayObject* self, int axis, PyArrayObject* out); NPY_NO_EXPORT PyObject* PyArray_Any(PyArrayObject* self, int axis, PyArrayObject* out); #endif numpy-1.8.2/numpy/core/src/multiarray/buffer.c0000664000175100017510000006400112370216243022522 0ustar vagrantvagrant00000000000000#define PY_SSIZE_T_CLEAN #include #include "structmember.h" #define NPY_NO_DEPRECATED_API NPY_API_VERSION #define _MULTIARRAYMODULE #include "numpy/arrayobject.h" #include "numpy/arrayscalars.h" #include "npy_config.h" #include "npy_pycompat.h" #include "buffer.h" #include "numpyos.h" #include "arrayobject.h" /************************************************************************* **************** Implement Buffer Protocol **************************** *************************************************************************/ /* removed multiple segment interface */ #if !defined(NPY_PY3K) static Py_ssize_t array_getsegcount(PyArrayObject *self, Py_ssize_t *lenp) { if (lenp) { *lenp = PyArray_NBYTES(self); } if (PyArray_ISONESEGMENT(self)) { return 1; } if (lenp) { *lenp = 0; } return 0; } static Py_ssize_t array_getreadbuf(PyArrayObject *self, Py_ssize_t segment, void **ptrptr) { if (segment != 0) { PyErr_SetString(PyExc_ValueError, "accessing non-existing array segment"); return -1; } if (PyArray_ISONESEGMENT(self)) { *ptrptr = PyArray_DATA(self); return PyArray_NBYTES(self); } PyErr_SetString(PyExc_ValueError, "array is not a single segment"); *ptrptr = NULL; return -1; } static Py_ssize_t array_getwritebuf(PyArrayObject *self, Py_ssize_t segment, void **ptrptr) { if (PyArray_FailUnlessWriteable(self, "buffer source array") < 0) { return -1; } return array_getreadbuf(self, segment, (void **) ptrptr); } static Py_ssize_t array_getcharbuf(PyArrayObject *self, Py_ssize_t segment, constchar **ptrptr) { return array_getreadbuf(self, segment, (void **) ptrptr); } #endif /* !defined(NPY_PY3K) */ /************************************************************************* * PEP 3118 buffer protocol * * Implementing PEP 3118 is somewhat convoluted because of the desirata: * * - Don't add new members to ndarray or descr structs, to preserve binary * compatibility. (Also, adding the items is actually not very useful, * since mutability issues prevent an 1 to 1 relationship between arrays * and buffer views.) * * - Don't use bf_releasebuffer, because it prevents PyArg_ParseTuple("s#", ... * from working. Breaking this would cause several backward compatibility * issues already on Python 2.6. * * - Behave correctly when array is reshaped in-place, or it's dtype is * altered. * * The solution taken below is to manually track memory allocated for * Py_buffers. *************************************************************************/ /* * Format string translator * * Translate PyArray_Descr to a PEP 3118 format string. */ /* Fast string 'class' */ typedef struct { char *s; int allocated; int pos; } _tmp_string_t; static int _append_char(_tmp_string_t *s, char c) { char *p; if (s->s == NULL) { s->s = (char*)malloc(16); s->pos = 0; s->allocated = 16; } if (s->pos >= s->allocated) { p = (char*)realloc(s->s, 2*s->allocated); if (p == NULL) { PyErr_SetString(PyExc_MemoryError, "memory allocation failed"); return -1; } s->s = p; s->allocated *= 2; } s->s[s->pos] = c; ++s->pos; return 0; } static int _append_str(_tmp_string_t *s, char *c) { while (*c != '\0') { if (_append_char(s, *c)) return -1; ++c; } return 0; } /* * Return non-zero if a type is aligned in each item in the given array, * AND, the descr element size is a multiple of the alignment, * AND, the array data is positioned to alignment granularity. */ static int _is_natively_aligned_at(PyArray_Descr *descr, PyArrayObject *arr, Py_ssize_t offset) { int k; if ((Py_ssize_t)(PyArray_DATA(arr)) % descr->alignment != 0) { return 0; } if (offset % descr->alignment != 0) { return 0; } if (descr->elsize % descr->alignment) { return 0; } for (k = 0; k < PyArray_NDIM(arr); ++k) { if (PyArray_DIM(arr, k) > 1) { if (PyArray_STRIDE(arr, k) % descr->alignment != 0) { return 0; } } } return 1; } static int _buffer_format_string(PyArray_Descr *descr, _tmp_string_t *str, PyArrayObject* arr, Py_ssize_t *offset, char *active_byteorder) { int k; char _active_byteorder = '@'; Py_ssize_t _offset = 0; if (active_byteorder == NULL) { active_byteorder = &_active_byteorder; } if (offset == NULL) { offset = &_offset; } if (descr->subarray) { PyObject *item, *subarray_tuple; Py_ssize_t total_count = 1; Py_ssize_t dim_size; char buf[128]; int old_offset; int ret; if (PyTuple_Check(descr->subarray->shape)) { subarray_tuple = descr->subarray->shape; Py_INCREF(subarray_tuple); } else { subarray_tuple = Py_BuildValue("(O)", descr->subarray->shape); } _append_char(str, '('); for (k = 0; k < PyTuple_GET_SIZE(subarray_tuple); ++k) { if (k > 0) { _append_char(str, ','); } item = PyTuple_GET_ITEM(subarray_tuple, k); dim_size = PyNumber_AsSsize_t(item, NULL); PyOS_snprintf(buf, sizeof(buf), "%ld", (long)dim_size); _append_str(str, buf); total_count *= dim_size; } _append_char(str, ')'); Py_DECREF(subarray_tuple); old_offset = *offset; ret = _buffer_format_string(descr->subarray->base, str, arr, offset, active_byteorder); *offset = old_offset + (*offset - old_offset) * total_count; return ret; } else if (PyDataType_HASFIELDS(descr)) { int base_offset = *offset; _append_str(str, "T{"); for (k = 0; k < PyTuple_GET_SIZE(descr->names); ++k) { PyObject *name, *item, *offset_obj, *tmp; PyArray_Descr *child; char *p; Py_ssize_t len; int new_offset; name = PyTuple_GET_ITEM(descr->names, k); item = PyDict_GetItem(descr->fields, name); child = (PyArray_Descr*)PyTuple_GetItem(item, 0); offset_obj = PyTuple_GetItem(item, 1); new_offset = base_offset + PyInt_AsLong(offset_obj); /* Insert padding manually */ if (*offset > new_offset) { PyErr_SetString(PyExc_RuntimeError, "This should never happen: Invalid offset in " "buffer format string generation. Please " "report a bug to the Numpy developers."); return -1; } while (*offset < new_offset) { _append_char(str, 'x'); ++*offset; } /* Insert child item */ _buffer_format_string(child, str, arr, offset, active_byteorder); /* Insert field name */ #if defined(NPY_PY3K) /* FIXME: XXX -- should it use UTF-8 here? */ tmp = PyUnicode_AsUTF8String(name); #else tmp = name; #endif if (tmp == NULL || PyBytes_AsStringAndSize(tmp, &p, &len) < 0) { PyErr_SetString(PyExc_ValueError, "invalid field name"); return -1; } _append_char(str, ':'); while (len > 0) { if (*p == ':') { Py_DECREF(tmp); PyErr_SetString(PyExc_ValueError, "':' is not an allowed character in buffer " "field names"); return -1; } _append_char(str, *p); ++p; --len; } _append_char(str, ':'); #if defined(NPY_PY3K) Py_DECREF(tmp); #endif } _append_char(str, '}'); } else { int is_standard_size = 1; int is_native_only_type = (descr->type_num == NPY_LONGDOUBLE || descr->type_num == NPY_CLONGDOUBLE); if (sizeof(npy_longlong) != 8) { is_native_only_type = is_native_only_type || ( descr->type_num == NPY_LONGLONG || descr->type_num == NPY_ULONGLONG); } *offset += descr->elsize; if (descr->byteorder == '=' && _is_natively_aligned_at(descr, arr, *offset)) { /* Prefer native types, to cater for Cython */ is_standard_size = 0; if (*active_byteorder != '@') { _append_char(str, '@'); *active_byteorder = '@'; } } else if (descr->byteorder == '=' && is_native_only_type) { /* Data types that have no standard size */ is_standard_size = 0; if (*active_byteorder != '^') { _append_char(str, '^'); *active_byteorder = '^'; } } else if (descr->byteorder == '<' || descr->byteorder == '>' || descr->byteorder == '=') { is_standard_size = 1; if (*active_byteorder != descr->byteorder) { _append_char(str, descr->byteorder); *active_byteorder = descr->byteorder; } if (is_native_only_type) { /* * It's not possible to express native-only data types * in non-native npy_byte orders */ PyErr_Format(PyExc_ValueError, "cannot expose native-only dtype '%c' in " "non-native byte order '%c' via buffer interface", descr->type, descr->byteorder); return -1; } } switch (descr->type_num) { case NPY_BOOL: if (_append_char(str, '?')) return -1; break; case NPY_BYTE: if (_append_char(str, 'b')) return -1; break; case NPY_UBYTE: if (_append_char(str, 'B')) return -1; break; case NPY_SHORT: if (_append_char(str, 'h')) return -1; break; case NPY_USHORT: if (_append_char(str, 'H')) return -1; break; case NPY_INT: if (_append_char(str, 'i')) return -1; break; case NPY_UINT: if (_append_char(str, 'I')) return -1; break; case NPY_LONG: if (is_standard_size && (NPY_SIZEOF_LONG == 8)) { if (_append_char(str, 'q')) return -1; } else { if (_append_char(str, 'l')) return -1; } break; case NPY_ULONG: if (is_standard_size && (NPY_SIZEOF_LONG == 8)) { if (_append_char(str, 'Q')) return -1; } else { if (_append_char(str, 'L')) return -1; } break; case NPY_LONGLONG: if (_append_char(str, 'q')) return -1; break; case NPY_ULONGLONG: if (_append_char(str, 'Q')) return -1; break; case NPY_HALF: if (_append_char(str, 'e')) return -1; break; case NPY_FLOAT: if (_append_char(str, 'f')) return -1; break; case NPY_DOUBLE: if (_append_char(str, 'd')) return -1; break; case NPY_LONGDOUBLE: if (_append_char(str, 'g')) return -1; break; case NPY_CFLOAT: if (_append_str(str, "Zf")) return -1; break; case NPY_CDOUBLE: if (_append_str(str, "Zd")) return -1; break; case NPY_CLONGDOUBLE: if (_append_str(str, "Zg")) return -1; break; /* XXX: datetime */ /* XXX: timedelta */ case NPY_OBJECT: if (_append_char(str, 'O')) return -1; break; case NPY_STRING: { char buf[128]; PyOS_snprintf(buf, sizeof(buf), "%ds", descr->elsize); if (_append_str(str, buf)) return -1; break; } case NPY_UNICODE: { /* Numpy Unicode is always 4-byte */ char buf[128]; assert(descr->elsize % 4 == 0); PyOS_snprintf(buf, sizeof(buf), "%dw", descr->elsize / 4); if (_append_str(str, buf)) return -1; break; } case NPY_VOID: { /* Insert padding bytes */ char buf[128]; PyOS_snprintf(buf, sizeof(buf), "%dx", descr->elsize); if (_append_str(str, buf)) return -1; break; } default: PyErr_Format(PyExc_ValueError, "cannot include dtype '%c' in a buffer", descr->type); return -1; } } return 0; } /* * Global information about all active buffers * * Note: because for backward compatibility we cannot define bf_releasebuffer, * we must manually keep track of the additional data required by the buffers. */ /* Additional per-array data required for providing the buffer interface */ typedef struct { char *format; int ndim; Py_ssize_t *strides; Py_ssize_t *shape; } _buffer_info_t; /* * { id(array): [list of pointers to _buffer_info_t, the last one is latest] } * * Because shape, strides, and format can be different for different buffers, * we may need to keep track of multiple buffer infos for each array. * * However, when none of them has changed, the same buffer info may be reused. * * Thread-safety is provided by GIL. */ static PyObject *_buffer_info_cache = NULL; /* Fill in the info structure */ static _buffer_info_t* _buffer_info_new(PyArrayObject *arr) { _buffer_info_t *info; _tmp_string_t fmt = {NULL, 0, 0}; int k; info = (_buffer_info_t*)malloc(sizeof(_buffer_info_t)); /* Fill in format */ if (_buffer_format_string(PyArray_DESCR(arr), &fmt, arr, NULL, NULL) != 0) { free(fmt.s); free(info); return NULL; } _append_char(&fmt, '\0'); info->format = fmt.s; /* Fill in shape and strides */ info->ndim = PyArray_NDIM(arr); if (info->ndim == 0) { info->shape = NULL; info->strides = NULL; } else { info->shape = (Py_ssize_t*)malloc(sizeof(Py_ssize_t) * PyArray_NDIM(arr) * 2 + 1); info->strides = info->shape + PyArray_NDIM(arr); for (k = 0; k < PyArray_NDIM(arr); ++k) { info->shape[k] = PyArray_DIMS(arr)[k]; info->strides[k] = PyArray_STRIDES(arr)[k]; } } return info; } /* Compare two info structures */ static Py_ssize_t _buffer_info_cmp(_buffer_info_t *a, _buffer_info_t *b) { Py_ssize_t c; int k; c = strcmp(a->format, b->format); if (c != 0) return c; c = a->ndim - b->ndim; if (c != 0) return c; for (k = 0; k < a->ndim; ++k) { c = a->shape[k] - b->shape[k]; if (c != 0) return c; c = a->strides[k] - b->strides[k]; if (c != 0) return c; } return 0; } static void _buffer_info_free(_buffer_info_t *info) { if (info->format) { free(info->format); } if (info->shape) { free(info->shape); } free(info); } /* Get buffer info from the global dictionary */ static _buffer_info_t* _buffer_get_info(PyObject *arr) { PyObject *key, *item_list, *item; _buffer_info_t *info = NULL, *old_info = NULL; if (_buffer_info_cache == NULL) { _buffer_info_cache = PyDict_New(); if (_buffer_info_cache == NULL) { return NULL; } } /* Compute information */ info = _buffer_info_new((PyArrayObject*)arr); if (info == NULL) { return NULL; } /* Check if it is identical with an old one; reuse old one, if yes */ key = PyLong_FromVoidPtr((void*)arr); item_list = PyDict_GetItem(_buffer_info_cache, key); if (item_list != NULL) { Py_INCREF(item_list); if (PyList_GET_SIZE(item_list) > 0) { item = PyList_GetItem(item_list, PyList_GET_SIZE(item_list) - 1); old_info = (_buffer_info_t*)PyLong_AsVoidPtr(item); if (_buffer_info_cmp(info, old_info) == 0) { _buffer_info_free(info); info = old_info; } } } else { item_list = PyList_New(0); PyDict_SetItem(_buffer_info_cache, key, item_list); } if (info != old_info) { /* Needs insertion */ item = PyLong_FromVoidPtr((void*)info); PyList_Append(item_list, item); Py_DECREF(item); } Py_DECREF(item_list); Py_DECREF(key); return info; } /* Clear buffer info from the global dictionary */ static void _buffer_clear_info(PyObject *arr) { PyObject *key, *item_list, *item; _buffer_info_t *info; int k; if (_buffer_info_cache == NULL) { return; } key = PyLong_FromVoidPtr((void*)arr); item_list = PyDict_GetItem(_buffer_info_cache, key); if (item_list != NULL) { for (k = 0; k < PyList_GET_SIZE(item_list); ++k) { item = PyList_GET_ITEM(item_list, k); info = (_buffer_info_t*)PyLong_AsVoidPtr(item); _buffer_info_free(info); } PyDict_DelItem(_buffer_info_cache, key); } Py_DECREF(key); } /* * Retrieving buffers */ static int array_getbuffer(PyObject *obj, Py_buffer *view, int flags) { PyArrayObject *self; _buffer_info_t *info = NULL; self = (PyArrayObject*)obj; /* Check whether we can provide the wanted properties */ if ((flags & PyBUF_C_CONTIGUOUS) == PyBUF_C_CONTIGUOUS && !PyArray_CHKFLAGS(self, NPY_ARRAY_C_CONTIGUOUS)) { PyErr_SetString(PyExc_ValueError, "ndarray is not C-contiguous"); goto fail; } if ((flags & PyBUF_F_CONTIGUOUS) == PyBUF_F_CONTIGUOUS && !PyArray_CHKFLAGS(self, NPY_ARRAY_F_CONTIGUOUS)) { PyErr_SetString(PyExc_ValueError, "ndarray is not Fortran contiguous"); goto fail; } if ((flags & PyBUF_ANY_CONTIGUOUS) == PyBUF_ANY_CONTIGUOUS && !PyArray_ISONESEGMENT(self)) { PyErr_SetString(PyExc_ValueError, "ndarray is not contiguous"); goto fail; } if ((flags & PyBUF_STRIDES) != PyBUF_STRIDES && !PyArray_CHKFLAGS(self, NPY_ARRAY_C_CONTIGUOUS)) { /* Non-strided N-dim buffers must be C-contiguous */ PyErr_SetString(PyExc_ValueError, "ndarray is not C-contiguous"); goto fail; } if ((flags & PyBUF_WRITEABLE) == PyBUF_WRITEABLE) { if (PyArray_FailUnlessWriteable(self, "buffer source array") < 0) { goto fail; } } /* * If a read-only buffer is requested on a read-write array, we return a * read-write buffer, which is dubious behavior. But that's why this call * is guarded by PyArray_ISWRITEABLE rather than (flags & * PyBUF_WRITEABLE). */ if (PyArray_ISWRITEABLE(self)) { if (array_might_be_written(self) < 0) { goto fail; } } if (view == NULL) { PyErr_SetString(PyExc_ValueError, "NULL view in getbuffer"); goto fail; } /* Fill in information */ info = _buffer_get_info(obj); if (info == NULL) { goto fail; } view->buf = PyArray_DATA(self); view->suboffsets = NULL; view->itemsize = PyArray_ITEMSIZE(self); view->readonly = !PyArray_ISWRITEABLE(self); view->internal = NULL; view->len = PyArray_NBYTES(self); if ((flags & PyBUF_FORMAT) == PyBUF_FORMAT) { view->format = info->format; } else { view->format = NULL; } if ((flags & PyBUF_ND) == PyBUF_ND) { view->ndim = info->ndim; view->shape = info->shape; } else { view->ndim = 0; view->shape = NULL; } if ((flags & PyBUF_STRIDES) == PyBUF_STRIDES) { view->strides = info->strides; } else { view->strides = NULL; } view->obj = (PyObject*)self; Py_INCREF(self); return 0; fail: return -1; } /* * NOTE: for backward compatibility (esp. with PyArg_ParseTuple("s#", ...)) * we do *not* define bf_releasebuffer at all. * * Instead, any extra data allocated with the buffer is released only in * array_dealloc. * * Ensuring that the buffer stays in place is taken care by refcounting; * ndarrays do not reallocate if there are references to them, and a buffer * view holds one reference. */ NPY_NO_EXPORT void _array_dealloc_buffer_info(PyArrayObject *self) { int reset_error_state = 0; PyObject *ptype, *pvalue, *ptraceback; /* This function may be called when processing an exception -- * we need to stash the error state to avoid confusing PyDict */ if (PyErr_Occurred()) { reset_error_state = 1; PyErr_Fetch(&ptype, &pvalue, &ptraceback); } _buffer_clear_info((PyObject*)self); if (reset_error_state) { PyErr_Restore(ptype, pvalue, ptraceback); } } /*************************************************************************/ NPY_NO_EXPORT PyBufferProcs array_as_buffer = { #if !defined(NPY_PY3K) (readbufferproc)array_getreadbuf, /*bf_getreadbuffer*/ (writebufferproc)array_getwritebuf, /*bf_getwritebuffer*/ (segcountproc)array_getsegcount, /*bf_getsegcount*/ (charbufferproc)array_getcharbuf, /*bf_getcharbuffer*/ #endif (getbufferproc)array_getbuffer, (releasebufferproc)0, }; /************************************************************************* * Convert PEP 3118 format string to PyArray_Descr */ static int _descriptor_from_pep3118_format_fast(char *s, PyObject **result); static int _pep3118_letter_to_type(char letter, int native, int complex); NPY_NO_EXPORT PyArray_Descr* _descriptor_from_pep3118_format(char *s) { char *buf, *p; int in_name = 0; int obtained; PyObject *descr; PyObject *str; PyObject *_numpy_internal; if (s == NULL) { return PyArray_DescrNewFromType(NPY_BYTE); } /* Fast path */ obtained = _descriptor_from_pep3118_format_fast(s, &descr); if (obtained) { return (PyArray_Descr*)descr; } /* Strip whitespace, except from field names */ buf = (char*)malloc(strlen(s) + 1); p = buf; while (*s != '\0') { if (*s == ':') { in_name = !in_name; *p = *s; p++; } else if (in_name || !NumPyOS_ascii_isspace(*s)) { *p = *s; p++; } s++; } *p = '\0'; str = PyUString_FromStringAndSize(buf, strlen(buf)); if (str == NULL) { free(buf); return NULL; } /* Convert */ _numpy_internal = PyImport_ImportModule("numpy.core._internal"); if (_numpy_internal == NULL) { Py_DECREF(str); free(buf); return NULL; } descr = PyObject_CallMethod( _numpy_internal, "_dtype_from_pep3118", "O", str); Py_DECREF(str); Py_DECREF(_numpy_internal); 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); free(buf); return NULL; } free(buf); return (PyArray_Descr*)descr; } /* * Fast path for parsing buffer strings corresponding to simple types. * * Currently, this deals only with single-element data types. */ static int _descriptor_from_pep3118_format_fast(char *s, PyObject **result) { PyArray_Descr *descr; int is_standard_size = 0; char byte_order = '='; int is_complex = 0; int type_num = NPY_BYTE; int item_seen = 0; for (; *s != '\0'; ++s) { is_complex = 0; switch (*s) { case '@': case '^': /* ^ means no alignment; doesn't matter for a single element */ byte_order = '='; is_standard_size = 0; break; case '<': byte_order = '<'; is_standard_size = 1; break; case '>': case '!': byte_order = '>'; is_standard_size = 1; break; case '=': byte_order = '='; is_standard_size = 1; break; case 'Z': is_complex = 1; ++s; default: if (item_seen) { /* Not a single-element data type */ return 0; } type_num = _pep3118_letter_to_type(*s, !is_standard_size, is_complex); if (type_num < 0) { /* Something unknown */ return 0; } item_seen = 1; break; } } if (!item_seen) { return 0; } descr = PyArray_DescrFromType(type_num); if (byte_order == '=') { *result = (PyObject*)descr; } else { *result = (PyObject*)PyArray_DescrNewByteorder(descr, byte_order); Py_DECREF(descr); } return 1; } static int _pep3118_letter_to_type(char letter, int native, int complex) { switch (letter) { case '?': return NPY_BOOL; case 'b': return NPY_BYTE; case 'B': return NPY_UBYTE; case 'h': return native ? NPY_SHORT : NPY_INT16; case 'H': return native ? NPY_USHORT : NPY_UINT16; case 'i': return native ? NPY_INT : NPY_INT32; case 'I': return native ? NPY_UINT : NPY_UINT32; case 'l': return native ? NPY_LONG : NPY_INT32; case 'L': return native ? NPY_ULONG : NPY_UINT32; case 'q': return native ? NPY_LONGLONG : NPY_INT64; case 'Q': return native ? NPY_ULONGLONG : NPY_UINT64; case 'e': return NPY_HALF; case 'f': return complex ? NPY_CFLOAT : NPY_FLOAT; case 'd': return complex ? NPY_CDOUBLE : NPY_DOUBLE; case 'g': return native ? (complex ? NPY_CLONGDOUBLE : NPY_LONGDOUBLE) : -1; default: /* Other unhandled cases */ return -1; } return -1; } numpy-1.8.2/numpy/core/src/multiarray/datetime_busday.c0000664000175100017510000012303112370216242024412 0ustar vagrantvagrant00000000000000/* * This file implements business day functionality for NumPy datetime. * * Written by Mark Wiebe (mwwiebe@gmail.com) * Copyright (c) 2011 by Enthought, Inc. * * See LICENSE.txt for the license. */ #define PY_SSIZE_T_CLEAN #include #define NPY_NO_DEPRECATED_API NPY_API_VERSION #define _MULTIARRAYMODULE #include #include "npy_config.h" #include "npy_pycompat.h" #include "numpy/arrayscalars.h" #include "lowlevel_strided_loops.h" #include "_datetime.h" #include "datetime_busday.h" #include "datetime_busdaycal.h" /* Gets the day of the week for a datetime64[D] value */ static int get_day_of_week(npy_datetime date) { int day_of_week; /* Get the day of the week for 'date' (1970-01-05 is Monday) */ day_of_week = (int)((date - 4) % 7); if (day_of_week < 0) { day_of_week += 7; } return day_of_week; } /* * Returns 1 if the date is a holiday (contained in the sorted * list of dates), 0 otherwise. * * The holidays list should be normalized, which means any NaT (not-a-time) * values, duplicates, and dates already excluded by the weekmask should * be removed, and the list should be sorted. */ static int is_holiday(npy_datetime date, npy_datetime *holidays_begin, npy_datetime *holidays_end) { npy_datetime *trial; /* Simple binary search */ while (holidays_begin < holidays_end) { trial = holidays_begin + (holidays_end - holidays_begin) / 2; if (date < *trial) { holidays_end = trial; } else if (date > *trial) { holidays_begin = trial + 1; } else { return 1; } } /* Not found */ return 0; } /* * Finds the earliest holiday which is on or after 'date'. If 'date' does not * appear within the holiday range, returns 'holidays_begin' if 'date' * is before all holidays, or 'holidays_end' if 'date' is after all * holidays. * * To remove all the holidays before 'date' from a holiday range, do: * * holidays_begin = find_holiday_earliest_on_or_after(date, * holidays_begin, holidays_end); * * The holidays list should be normalized, which means any NaT (not-a-time) * values, duplicates, and dates already excluded by the weekmask should * be removed, and the list should be sorted. */ static npy_datetime * find_earliest_holiday_on_or_after(npy_datetime date, npy_datetime *holidays_begin, npy_datetime *holidays_end) { npy_datetime *trial; /* Simple binary search */ while (holidays_begin < holidays_end) { trial = holidays_begin + (holidays_end - holidays_begin) / 2; if (date < *trial) { holidays_end = trial; } else if (date > *trial) { holidays_begin = trial + 1; } else { return trial; } } return holidays_begin; } /* * Finds the earliest holiday which is after 'date'. If 'date' does not * appear within the holiday range, returns 'holidays_begin' if 'date' * is before all holidays, or 'holidays_end' if 'date' is after all * holidays. * * To remove all the holidays after 'date' from a holiday range, do: * * holidays_end = find_holiday_earliest_after(date, * holidays_begin, holidays_end); * * The holidays list should be normalized, which means any NaT (not-a-time) * values, duplicates, and dates already excluded by the weekmask should * be removed, and the list should be sorted. */ static npy_datetime * find_earliest_holiday_after(npy_datetime date, npy_datetime *holidays_begin, npy_datetime *holidays_end) { npy_datetime *trial; /* Simple binary search */ while (holidays_begin < holidays_end) { trial = holidays_begin + (holidays_end - holidays_begin) / 2; if (date < *trial) { holidays_end = trial; } else if (date > *trial) { holidays_begin = trial + 1; } else { return trial + 1; } } return holidays_begin; } /* * Applies the 'roll' strategy to 'date', placing the result in 'out' * and setting 'out_day_of_week' to the day of the week that results. * * Returns 0 on success, -1 on failure. */ static int apply_business_day_roll(npy_datetime date, npy_datetime *out, int *out_day_of_week, NPY_BUSDAY_ROLL roll, npy_bool *weekmask, npy_datetime *holidays_begin, npy_datetime *holidays_end) { int day_of_week; /* Deal with NaT input */ if (date == NPY_DATETIME_NAT) { *out = NPY_DATETIME_NAT; if (roll == NPY_BUSDAY_RAISE) { PyErr_SetString(PyExc_ValueError, "NaT input in busday_offset"); return -1; } else { return 0; } } /* Get the day of the week for 'date' */ day_of_week = get_day_of_week(date); /* Apply the 'roll' if it's not a business day */ if (weekmask[day_of_week] == 0 || is_holiday(date, holidays_begin, holidays_end)) { npy_datetime start_date = date; int start_day_of_week = day_of_week; switch (roll) { case NPY_BUSDAY_FOLLOWING: case NPY_BUSDAY_MODIFIEDFOLLOWING: { do { ++date; if (++day_of_week == 7) { day_of_week = 0; } } while (weekmask[day_of_week] == 0 || is_holiday(date, holidays_begin, holidays_end)); if (roll == NPY_BUSDAY_MODIFIEDFOLLOWING) { /* If we crossed a month boundary, do preceding instead */ if (days_to_month_number(start_date) != days_to_month_number(date)) { date = start_date; day_of_week = start_day_of_week; do { --date; if (--day_of_week == -1) { day_of_week = 6; } } while (weekmask[day_of_week] == 0 || is_holiday(date, holidays_begin, holidays_end)); } } break; } case NPY_BUSDAY_PRECEDING: case NPY_BUSDAY_MODIFIEDPRECEDING: { do { --date; if (--day_of_week == -1) { day_of_week = 6; } } while (weekmask[day_of_week] == 0 || is_holiday(date, holidays_begin, holidays_end)); if (roll == NPY_BUSDAY_MODIFIEDPRECEDING) { /* If we crossed a month boundary, do following instead */ if (days_to_month_number(start_date) != days_to_month_number(date)) { date = start_date; day_of_week = start_day_of_week; do { ++date; if (++day_of_week == 7) { day_of_week = 0; } } while (weekmask[day_of_week] == 0 || is_holiday(date, holidays_begin, holidays_end)); } } break; } case NPY_BUSDAY_NAT: { date = NPY_DATETIME_NAT; break; } case NPY_BUSDAY_RAISE: { *out = NPY_DATETIME_NAT; PyErr_SetString(PyExc_ValueError, "Non-business day date in busday_offset"); return -1; } } } *out = date; *out_day_of_week = day_of_week; return 0; } /* * Applies a single business day offset. See the function * business_day_offset for the meaning of all the parameters. * * Returns 0 on success, -1 on failure. */ static int apply_business_day_offset(npy_datetime date, npy_int64 offset, npy_datetime *out, NPY_BUSDAY_ROLL roll, npy_bool *weekmask, int busdays_in_weekmask, npy_datetime *holidays_begin, npy_datetime *holidays_end) { int day_of_week = 0; npy_datetime *holidays_temp; /* Roll the date to a business day */ if (apply_business_day_roll(date, &date, &day_of_week, roll, weekmask, holidays_begin, holidays_end) < 0) { return -1; } /* If we get a NaT, just return it */ if (date == NPY_DATETIME_NAT) { return 0; } /* Now we're on a valid business day */ if (offset > 0) { /* Remove any earlier holidays */ holidays_begin = find_earliest_holiday_on_or_after(date, holidays_begin, holidays_end); /* Jump by as many weeks as we can */ date += (offset / busdays_in_weekmask) * 7; offset = offset % busdays_in_weekmask; /* Adjust based on the number of holidays we crossed */ holidays_temp = find_earliest_holiday_after(date, holidays_begin, holidays_end); offset += holidays_temp - holidays_begin; holidays_begin = holidays_temp; /* Step until we use up the rest of the offset */ while (offset > 0) { ++date; if (++day_of_week == 7) { day_of_week = 0; } if (weekmask[day_of_week] && !is_holiday(date, holidays_begin, holidays_end)) { offset--; } } } else if (offset < 0) { /* Remove any later holidays */ holidays_end = find_earliest_holiday_after(date, holidays_begin, holidays_end); /* Jump by as many weeks as we can */ date += (offset / busdays_in_weekmask) * 7; offset = offset % busdays_in_weekmask; /* Adjust based on the number of holidays we crossed */ holidays_temp = find_earliest_holiday_on_or_after(date, holidays_begin, holidays_end); offset -= holidays_end - holidays_temp; holidays_end = holidays_temp; /* Step until we use up the rest of the offset */ while (offset < 0) { --date; if (--day_of_week == -1) { day_of_week = 6; } if (weekmask[day_of_week] && !is_holiday(date, holidays_begin, holidays_end)) { offset++; } } } *out = date; return 0; } /* * Applies a single business day count operation. See the function * business_day_count for the meaning of all the parameters. * * Returns 0 on success, -1 on failure. */ static int apply_business_day_count(npy_datetime date_begin, npy_datetime date_end, npy_int64 *out, npy_bool *weekmask, int busdays_in_weekmask, npy_datetime *holidays_begin, npy_datetime *holidays_end) { npy_int64 count, whole_weeks; int day_of_week = 0; int swapped = 0; /* If we get a NaT, raise an error */ if (date_begin == NPY_DATETIME_NAT || date_end == NPY_DATETIME_NAT) { PyErr_SetString(PyExc_ValueError, "Cannot compute a business day count with a NaT (not-a-time) " "date"); return -1; } /* Trivial empty date range */ if (date_begin == date_end) { *out = 0; return 0; } else if (date_begin > date_end) { npy_datetime tmp = date_begin; date_begin = date_end; date_end = tmp; swapped = 1; } /* Remove any earlier holidays */ holidays_begin = find_earliest_holiday_on_or_after(date_begin, holidays_begin, holidays_end); /* Remove any later holidays */ holidays_end = find_earliest_holiday_on_or_after(date_end, holidays_begin, holidays_end); /* Start the count as negative the number of holidays in the range */ count = -(holidays_end - holidays_begin); /* Add the whole weeks between date_begin and date_end */ whole_weeks = (date_end - date_begin) / 7; count += whole_weeks * busdays_in_weekmask; date_begin += whole_weeks * 7; if (date_begin < date_end) { /* Get the day of the week for 'date_begin' */ day_of_week = get_day_of_week(date_begin); /* Count the remaining days one by one */ while (date_begin < date_end) { if (weekmask[day_of_week]) { count++; } ++date_begin; if (++day_of_week == 7) { day_of_week = 0; } } } if (swapped) { count = -count; } *out = count; return 0; } /* * Applies the given offsets in business days to the dates provided. * This is the low-level function which requires already cleaned input * data. * * dates: An array of dates with 'datetime64[D]' data type. * offsets: An array safely convertible into type int64. * out: Either NULL, or an array with 'datetime64[D]' data type * in which to place the resulting dates. * roll: A rule for how to treat non-business day dates. * weekmask: A 7-element boolean mask, 1 for possible business days and 0 * for non-business days. * busdays_in_weekmask: A count of how many 1's there are in weekmask. * holidays_begin/holidays_end: A sorted list of dates matching '[D]' * unit metadata, with any dates falling on a day of the * week without weekmask[i] == 1 already filtered out. * * For each (date, offset) in the broadcasted pair of (dates, offsets), * does the following: * + Applies the 'roll' rule to the date to either produce NaT, raise * an exception, or land on a valid business day. * + Adds 'offset' business days to the valid business day found. * + Sets the value in 'out' if provided, or the allocated output array * otherwise. */ NPY_NO_EXPORT PyArrayObject * business_day_offset(PyArrayObject *dates, PyArrayObject *offsets, PyArrayObject *out, NPY_BUSDAY_ROLL roll, npy_bool *weekmask, int busdays_in_weekmask, npy_datetime *holidays_begin, npy_datetime *holidays_end) { PyArray_DatetimeMetaData temp_meta; PyArray_Descr *dtypes[3] = {NULL, NULL, NULL}; NpyIter *iter = NULL; PyArrayObject *op[3] = {NULL, NULL, NULL}; npy_uint32 op_flags[3], flags; PyArrayObject *ret = NULL; if (busdays_in_weekmask == 0) { PyErr_SetString(PyExc_ValueError, "the business day weekmask must have at least one " "valid business day"); return NULL; } /* First create the data types for dates and offsets */ temp_meta.base = NPY_FR_D; temp_meta.num = 1; dtypes[0] = create_datetime_dtype(NPY_DATETIME, &temp_meta); if (dtypes[0] == NULL) { goto fail; } dtypes[1] = PyArray_DescrFromType(NPY_INT64); if (dtypes[1] == NULL) { goto fail; } dtypes[2] = dtypes[0]; Py_INCREF(dtypes[2]); /* Set up the iterator parameters */ flags = NPY_ITER_EXTERNAL_LOOP| NPY_ITER_BUFFERED| NPY_ITER_ZEROSIZE_OK; op[0] = dates; op_flags[0] = NPY_ITER_READONLY | NPY_ITER_ALIGNED; op[1] = offsets; op_flags[1] = NPY_ITER_READONLY | NPY_ITER_ALIGNED; op[2] = out; op_flags[2] = NPY_ITER_WRITEONLY | NPY_ITER_ALLOCATE | NPY_ITER_ALIGNED; /* Allocate the iterator */ iter = NpyIter_MultiNew(3, op, flags, NPY_KEEPORDER, NPY_SAFE_CASTING, op_flags, dtypes); if (iter == NULL) { goto fail; } /* Loop over all elements */ if (NpyIter_GetIterSize(iter) > 0) { NpyIter_IterNextFunc *iternext; char **dataptr; npy_intp *strideptr, *innersizeptr; iternext = NpyIter_GetIterNext(iter, NULL); if (iternext == NULL) { goto fail; } dataptr = NpyIter_GetDataPtrArray(iter); strideptr = NpyIter_GetInnerStrideArray(iter); innersizeptr = NpyIter_GetInnerLoopSizePtr(iter); do { char *data_dates = dataptr[0]; char *data_offsets = dataptr[1]; char *data_out = dataptr[2]; npy_intp stride_dates = strideptr[0]; npy_intp stride_offsets = strideptr[1]; npy_intp stride_out = strideptr[2]; npy_intp count = *innersizeptr; while (count--) { if (apply_business_day_offset(*(npy_int64 *)data_dates, *(npy_int64 *)data_offsets, (npy_int64 *)data_out, roll, weekmask, busdays_in_weekmask, holidays_begin, holidays_end) < 0) { goto fail; } data_dates += stride_dates; data_offsets += stride_offsets; data_out += stride_out; } } while (iternext(iter)); } /* Get the return object from the iterator */ ret = NpyIter_GetOperandArray(iter)[2]; Py_INCREF(ret); goto finish; fail: Py_XDECREF(ret); ret = NULL; finish: Py_XDECREF(dtypes[0]); Py_XDECREF(dtypes[1]); Py_XDECREF(dtypes[2]); if (iter != NULL) { if (NpyIter_Deallocate(iter) != NPY_SUCCEED) { Py_XDECREF(ret); ret = NULL; } } return ret; } /* * Counts the number of business days between two dates, not including * the end date. This is the low-level function which requires already * cleaned input data. * * If dates_begin is before dates_end, the result is positive. If * dates_begin is after dates_end, it is negative. * * dates_begin: An array of dates with 'datetime64[D]' data type. * dates_end: An array of dates with 'datetime64[D]' data type. * out: Either NULL, or an array with 'int64' data type * in which to place the resulting dates. * weekmask: A 7-element boolean mask, 1 for possible business days and 0 * for non-business days. * busdays_in_weekmask: A count of how many 1's there are in weekmask. * holidays_begin/holidays_end: A sorted list of dates matching '[D]' * unit metadata, with any dates falling on a day of the * week without weekmask[i] == 1 already filtered out. */ NPY_NO_EXPORT PyArrayObject * business_day_count(PyArrayObject *dates_begin, PyArrayObject *dates_end, PyArrayObject *out, npy_bool *weekmask, int busdays_in_weekmask, npy_datetime *holidays_begin, npy_datetime *holidays_end) { PyArray_DatetimeMetaData temp_meta; PyArray_Descr *dtypes[3] = {NULL, NULL, NULL}; NpyIter *iter = NULL; PyArrayObject *op[3] = {NULL, NULL, NULL}; npy_uint32 op_flags[3], flags; PyArrayObject *ret = NULL; if (busdays_in_weekmask == 0) { PyErr_SetString(PyExc_ValueError, "the business day weekmask must have at least one " "valid business day"); return NULL; } /* First create the data types for the dates and the int64 output */ temp_meta.base = NPY_FR_D; temp_meta.num = 1; dtypes[0] = create_datetime_dtype(NPY_DATETIME, &temp_meta); if (dtypes[0] == NULL) { goto fail; } dtypes[1] = dtypes[0]; Py_INCREF(dtypes[1]); dtypes[2] = PyArray_DescrFromType(NPY_INT64); if (dtypes[2] == NULL) { goto fail; } /* Set up the iterator parameters */ flags = NPY_ITER_EXTERNAL_LOOP| NPY_ITER_BUFFERED| NPY_ITER_ZEROSIZE_OK; op[0] = dates_begin; op_flags[0] = NPY_ITER_READONLY | NPY_ITER_ALIGNED; op[1] = dates_end; op_flags[1] = NPY_ITER_READONLY | NPY_ITER_ALIGNED; op[2] = out; op_flags[2] = NPY_ITER_WRITEONLY | NPY_ITER_ALLOCATE | NPY_ITER_ALIGNED; /* Allocate the iterator */ iter = NpyIter_MultiNew(3, op, flags, NPY_KEEPORDER, NPY_SAFE_CASTING, op_flags, dtypes); if (iter == NULL) { goto fail; } /* Loop over all elements */ if (NpyIter_GetIterSize(iter) > 0) { NpyIter_IterNextFunc *iternext; char **dataptr; npy_intp *strideptr, *innersizeptr; iternext = NpyIter_GetIterNext(iter, NULL); if (iternext == NULL) { goto fail; } dataptr = NpyIter_GetDataPtrArray(iter); strideptr = NpyIter_GetInnerStrideArray(iter); innersizeptr = NpyIter_GetInnerLoopSizePtr(iter); do { char *data_dates_begin = dataptr[0]; char *data_dates_end = dataptr[1]; char *data_out = dataptr[2]; npy_intp stride_dates_begin = strideptr[0]; npy_intp stride_dates_end = strideptr[1]; npy_intp stride_out = strideptr[2]; npy_intp count = *innersizeptr; while (count--) { if (apply_business_day_count(*(npy_int64 *)data_dates_begin, *(npy_int64 *)data_dates_end, (npy_int64 *)data_out, weekmask, busdays_in_weekmask, holidays_begin, holidays_end) < 0) { goto fail; } data_dates_begin += stride_dates_begin; data_dates_end += stride_dates_end; data_out += stride_out; } } while (iternext(iter)); } /* Get the return object from the iterator */ ret = NpyIter_GetOperandArray(iter)[2]; Py_INCREF(ret); goto finish; fail: Py_XDECREF(ret); ret = NULL; finish: Py_XDECREF(dtypes[0]); Py_XDECREF(dtypes[1]); Py_XDECREF(dtypes[2]); if (iter != NULL) { if (NpyIter_Deallocate(iter) != NPY_SUCCEED) { Py_XDECREF(ret); ret = NULL; } } return ret; } /* * Returns a boolean array with True for input dates which are valid * business days, and False for dates which are not. This is the * low-level function which requires already cleaned input data. * * dates: An array of dates with 'datetime64[D]' data type. * out: Either NULL, or an array with 'bool' data type * in which to place the resulting dates. * weekmask: A 7-element boolean mask, 1 for possible business days and 0 * for non-business days. * busdays_in_weekmask: A count of how many 1's there are in weekmask. * holidays_begin/holidays_end: A sorted list of dates matching '[D]' * unit metadata, with any dates falling on a day of the * week without weekmask[i] == 1 already filtered out. */ NPY_NO_EXPORT PyArrayObject * is_business_day(PyArrayObject *dates, PyArrayObject *out, npy_bool *weekmask, int busdays_in_weekmask, npy_datetime *holidays_begin, npy_datetime *holidays_end) { PyArray_DatetimeMetaData temp_meta; PyArray_Descr *dtypes[2] = {NULL, NULL}; NpyIter *iter = NULL; PyArrayObject *op[2] = {NULL, NULL}; npy_uint32 op_flags[2], flags; PyArrayObject *ret = NULL; if (busdays_in_weekmask == 0) { PyErr_SetString(PyExc_ValueError, "the business day weekmask must have at least one " "valid business day"); return NULL; } /* First create the data types for the dates and the bool output */ temp_meta.base = NPY_FR_D; temp_meta.num = 1; dtypes[0] = create_datetime_dtype(NPY_DATETIME, &temp_meta); if (dtypes[0] == NULL) { goto fail; } dtypes[1] = PyArray_DescrFromType(NPY_BOOL); if (dtypes[1] == NULL) { goto fail; } /* Set up the iterator parameters */ flags = NPY_ITER_EXTERNAL_LOOP| NPY_ITER_BUFFERED| NPY_ITER_ZEROSIZE_OK; op[0] = dates; op_flags[0] = NPY_ITER_READONLY | NPY_ITER_ALIGNED; op[1] = out; op_flags[1] = NPY_ITER_WRITEONLY | NPY_ITER_ALLOCATE | NPY_ITER_ALIGNED; /* Allocate the iterator */ iter = NpyIter_MultiNew(2, op, flags, NPY_KEEPORDER, NPY_SAFE_CASTING, op_flags, dtypes); if (iter == NULL) { goto fail; } /* Loop over all elements */ if (NpyIter_GetIterSize(iter) > 0) { NpyIter_IterNextFunc *iternext; char **dataptr; npy_intp *strideptr, *innersizeptr; iternext = NpyIter_GetIterNext(iter, NULL); if (iternext == NULL) { goto fail; } dataptr = NpyIter_GetDataPtrArray(iter); strideptr = NpyIter_GetInnerStrideArray(iter); innersizeptr = NpyIter_GetInnerLoopSizePtr(iter); do { char *data_dates = dataptr[0]; char *data_out = dataptr[1]; npy_intp stride_dates = strideptr[0]; npy_intp stride_out = strideptr[1]; npy_intp count = *innersizeptr; npy_datetime date; int day_of_week; while (count--) { /* Check if it's a business day */ date = *(npy_datetime *)data_dates; day_of_week = get_day_of_week(date); *(npy_bool *)data_out = weekmask[day_of_week] && !is_holiday(date, holidays_begin, holidays_end) && date != NPY_DATETIME_NAT; data_dates += stride_dates; data_out += stride_out; } } while (iternext(iter)); } /* Get the return object from the iterator */ ret = NpyIter_GetOperandArray(iter)[1]; Py_INCREF(ret); goto finish; fail: Py_XDECREF(ret); ret = NULL; finish: Py_XDECREF(dtypes[0]); Py_XDECREF(dtypes[1]); if (iter != NULL) { if (NpyIter_Deallocate(iter) != NPY_SUCCEED) { Py_XDECREF(ret); ret = NULL; } } return ret; } static int PyArray_BusDayRollConverter(PyObject *roll_in, NPY_BUSDAY_ROLL *roll) { PyObject *obj = roll_in; char *str; Py_ssize_t len; /* Make obj into an ASCII string */ Py_INCREF(obj); if (PyUnicode_Check(obj)) { /* accept unicode input */ PyObject *obj_str; obj_str = PyUnicode_AsASCIIString(obj); if (obj_str == NULL) { Py_DECREF(obj); return 0; } Py_DECREF(obj); obj = obj_str; } if (PyBytes_AsStringAndSize(obj, &str, &len) < 0) { Py_DECREF(obj); return 0; } /* Use switch statements to quickly isolate the right enum value */ switch (str[0]) { case 'b': if (strcmp(str, "backward") == 0) { *roll = NPY_BUSDAY_BACKWARD; goto finish; } break; case 'f': if (len > 2) switch (str[2]) { case 'r': if (strcmp(str, "forward") == 0) { *roll = NPY_BUSDAY_FORWARD; goto finish; } break; case 'l': if (strcmp(str, "following") == 0) { *roll = NPY_BUSDAY_FOLLOWING; goto finish; } break; } break; case 'm': if (len > 8) switch (str[8]) { case 'f': if (strcmp(str, "modifiedfollowing") == 0) { *roll = NPY_BUSDAY_MODIFIEDFOLLOWING; goto finish; } break; case 'p': if (strcmp(str, "modifiedpreceding") == 0) { *roll = NPY_BUSDAY_MODIFIEDFOLLOWING; goto finish; } break; } break; case 'n': if (strcmp(str, "nat") == 0) { *roll = NPY_BUSDAY_NAT; goto finish; } break; case 'p': if (strcmp(str, "preceding") == 0) { *roll = NPY_BUSDAY_PRECEDING; goto finish; } break; case 'r': if (strcmp(str, "raise") == 0) { *roll = NPY_BUSDAY_RAISE; goto finish; } break; } PyErr_Format(PyExc_ValueError, "Invalid business day roll parameter \"%s\"", str); Py_DECREF(obj); return 0; finish: Py_DECREF(obj); return 1; } /* * This is the 'busday_offset' function exposed for calling * from Python. */ NPY_NO_EXPORT PyObject * array_busday_offset(PyObject *NPY_UNUSED(self), PyObject *args, PyObject *kwds) { char *kwlist[] = {"dates", "offsets", "roll", "weekmask", "holidays", "busdaycal", "out", NULL}; PyObject *dates_in = NULL, *offsets_in = NULL, *out_in = NULL; PyArrayObject *dates = NULL, *offsets = NULL, *out = NULL, *ret; NPY_BUSDAY_ROLL roll = NPY_BUSDAY_RAISE; npy_bool weekmask[7] = {2, 1, 1, 1, 1, 0, 0}; NpyBusDayCalendar *busdaycal = NULL; int i, busdays_in_weekmask; npy_holidayslist holidays = {NULL, NULL}; int allocated_holidays = 1; if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO|O&O&O&O!O:busday_offset", kwlist, &dates_in, &offsets_in, &PyArray_BusDayRollConverter, &roll, &PyArray_WeekMaskConverter, &weekmask[0], &PyArray_HolidaysConverter, &holidays, &NpyBusDayCalendar_Type, &busdaycal, &out_in)) { goto fail; } /* Make sure only one of the weekmask/holidays and busdaycal is supplied */ if (busdaycal != NULL) { if (weekmask[0] != 2 || holidays.begin != NULL) { PyErr_SetString(PyExc_ValueError, "Cannot supply both the weekmask/holidays and the " "busdaycal parameters to busday_offset()"); goto fail; } /* Indicate that the holidays weren't allocated by us */ allocated_holidays = 0; /* Copy the private normalized weekmask/holidays data */ holidays = busdaycal->holidays; busdays_in_weekmask = busdaycal->busdays_in_weekmask; memcpy(weekmask, busdaycal->weekmask, 7); } else { /* * Fix up the weekmask from the uninitialized * signal value to a proper default. */ if (weekmask[0] == 2) { weekmask[0] = 1; } /* Count the number of business days in a week */ busdays_in_weekmask = 0; for (i = 0; i < 7; ++i) { busdays_in_weekmask += weekmask[i]; } /* The holidays list must be normalized before using it */ normalize_holidays_list(&holidays, weekmask); } /* Make 'dates' into an array */ if (PyArray_Check(dates_in)) { dates = (PyArrayObject *)dates_in; Py_INCREF(dates); } else { PyArray_Descr *datetime_dtype; /* Use the datetime dtype with generic units so it fills it in */ datetime_dtype = PyArray_DescrFromType(NPY_DATETIME); if (datetime_dtype == NULL) { goto fail; } /* This steals the datetime_dtype reference */ dates = (PyArrayObject *)PyArray_FromAny(dates_in, datetime_dtype, 0, 0, 0, dates_in); if (dates == NULL) { goto fail; } } /* Make 'offsets' into an array */ offsets = (PyArrayObject *)PyArray_FromAny(offsets_in, PyArray_DescrFromType(NPY_INT64), 0, 0, 0, offsets_in); if (offsets == NULL) { goto fail; } /* Make sure 'out' is an array if it's provided */ if (out_in != NULL) { if (!PyArray_Check(out_in)) { PyErr_SetString(PyExc_ValueError, "busday_offset: must provide a NumPy array for 'out'"); goto fail; } out = (PyArrayObject *)out_in; } ret = business_day_offset(dates, offsets, out, roll, weekmask, busdays_in_weekmask, holidays.begin, holidays.end); Py_DECREF(dates); Py_DECREF(offsets); if (allocated_holidays && holidays.begin != NULL) { PyArray_free(holidays.begin); } return out == NULL ? PyArray_Return(ret) : (PyObject *)ret; fail: Py_XDECREF(dates); Py_XDECREF(offsets); if (allocated_holidays && holidays.begin != NULL) { PyArray_free(holidays.begin); } return NULL; } /* * This is the 'busday_count' function exposed for calling * from Python. */ NPY_NO_EXPORT PyObject * array_busday_count(PyObject *NPY_UNUSED(self), PyObject *args, PyObject *kwds) { char *kwlist[] = {"begindates", "enddates", "weekmask", "holidays", "busdaycal", "out", NULL}; PyObject *dates_begin_in = NULL, *dates_end_in = NULL, *out_in = NULL; PyArrayObject *dates_begin = NULL, *dates_end = NULL, *out = NULL, *ret; npy_bool weekmask[7] = {2, 1, 1, 1, 1, 0, 0}; NpyBusDayCalendar *busdaycal = NULL; int i, busdays_in_weekmask; npy_holidayslist holidays = {NULL, NULL}; int allocated_holidays = 1; if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO|O&O&O!O:busday_count", kwlist, &dates_begin_in, &dates_end_in, &PyArray_WeekMaskConverter, &weekmask[0], &PyArray_HolidaysConverter, &holidays, &NpyBusDayCalendar_Type, &busdaycal, &out_in)) { goto fail; } /* Make sure only one of the weekmask/holidays and busdaycal is supplied */ if (busdaycal != NULL) { if (weekmask[0] != 2 || holidays.begin != NULL) { PyErr_SetString(PyExc_ValueError, "Cannot supply both the weekmask/holidays and the " "busdaycal parameters to busday_count()"); goto fail; } /* Indicate that the holidays weren't allocated by us */ allocated_holidays = 0; /* Copy the private normalized weekmask/holidays data */ holidays = busdaycal->holidays; busdays_in_weekmask = busdaycal->busdays_in_weekmask; memcpy(weekmask, busdaycal->weekmask, 7); } else { /* * Fix up the weekmask from the uninitialized * signal value to a proper default. */ if (weekmask[0] == 2) { weekmask[0] = 1; } /* Count the number of business days in a week */ busdays_in_weekmask = 0; for (i = 0; i < 7; ++i) { busdays_in_weekmask += weekmask[i]; } /* The holidays list must be normalized before using it */ normalize_holidays_list(&holidays, weekmask); } /* Make 'dates_begin' into an array */ if (PyArray_Check(dates_begin_in)) { dates_begin = (PyArrayObject *)dates_begin_in; Py_INCREF(dates_begin); } else { PyArray_Descr *datetime_dtype; /* Use the datetime dtype with generic units so it fills it in */ datetime_dtype = PyArray_DescrFromType(NPY_DATETIME); if (datetime_dtype == NULL) { goto fail; } /* This steals the datetime_dtype reference */ dates_begin = (PyArrayObject *)PyArray_FromAny(dates_begin_in, datetime_dtype, 0, 0, 0, dates_begin_in); if (dates_begin == NULL) { goto fail; } } /* Make 'dates_end' into an array */ if (PyArray_Check(dates_end_in)) { dates_end = (PyArrayObject *)dates_end_in; Py_INCREF(dates_end); } else { PyArray_Descr *datetime_dtype; /* Use the datetime dtype with generic units so it fills it in */ datetime_dtype = PyArray_DescrFromType(NPY_DATETIME); if (datetime_dtype == NULL) { goto fail; } /* This steals the datetime_dtype reference */ dates_end = (PyArrayObject *)PyArray_FromAny(dates_end_in, datetime_dtype, 0, 0, 0, dates_end_in); if (dates_end == NULL) { goto fail; } } /* Make sure 'out' is an array if it's provided */ if (out_in != NULL) { if (!PyArray_Check(out_in)) { PyErr_SetString(PyExc_ValueError, "busday_offset: must provide a NumPy array for 'out'"); goto fail; } out = (PyArrayObject *)out_in; } ret = business_day_count(dates_begin, dates_end, out, weekmask, busdays_in_weekmask, holidays.begin, holidays.end); Py_DECREF(dates_begin); Py_DECREF(dates_end); if (allocated_holidays && holidays.begin != NULL) { PyArray_free(holidays.begin); } return out == NULL ? PyArray_Return(ret) : (PyObject *)ret; fail: Py_XDECREF(dates_begin); Py_XDECREF(dates_end); if (allocated_holidays && holidays.begin != NULL) { PyArray_free(holidays.begin); } return NULL; } /* * This is the 'is_busday' function exposed for calling * from Python. */ NPY_NO_EXPORT PyObject * array_is_busday(PyObject *NPY_UNUSED(self), PyObject *args, PyObject *kwds) { char *kwlist[] = {"dates", "weekmask", "holidays", "busdaycal", "out", NULL}; PyObject *dates_in = NULL, *out_in = NULL; PyArrayObject *dates = NULL,*out = NULL, *ret; npy_bool weekmask[7] = {2, 1, 1, 1, 1, 0, 0}; NpyBusDayCalendar *busdaycal = NULL; int i, busdays_in_weekmask; npy_holidayslist holidays = {NULL, NULL}; int allocated_holidays = 1; if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O&O&O!O:is_busday", kwlist, &dates_in, &PyArray_WeekMaskConverter, &weekmask[0], &PyArray_HolidaysConverter, &holidays, &NpyBusDayCalendar_Type, &busdaycal, &out_in)) { goto fail; } /* Make sure only one of the weekmask/holidays and busdaycal is supplied */ if (busdaycal != NULL) { if (weekmask[0] != 2 || holidays.begin != NULL) { PyErr_SetString(PyExc_ValueError, "Cannot supply both the weekmask/holidays and the " "busdaycal parameters to is_busday()"); goto fail; } /* Indicate that the holidays weren't allocated by us */ allocated_holidays = 0; /* Copy the private normalized weekmask/holidays data */ holidays = busdaycal->holidays; busdays_in_weekmask = busdaycal->busdays_in_weekmask; memcpy(weekmask, busdaycal->weekmask, 7); } else { /* * Fix up the weekmask from the uninitialized * signal value to a proper default. */ if (weekmask[0] == 2) { weekmask[0] = 1; } /* Count the number of business days in a week */ busdays_in_weekmask = 0; for (i = 0; i < 7; ++i) { busdays_in_weekmask += weekmask[i]; } /* The holidays list must be normalized before using it */ normalize_holidays_list(&holidays, weekmask); } /* Make 'dates' into an array */ if (PyArray_Check(dates_in)) { dates = (PyArrayObject *)dates_in; Py_INCREF(dates); } else { PyArray_Descr *datetime_dtype; /* Use the datetime dtype with generic units so it fills it in */ datetime_dtype = PyArray_DescrFromType(NPY_DATETIME); if (datetime_dtype == NULL) { goto fail; } /* This steals the datetime_dtype reference */ dates = (PyArrayObject *)PyArray_FromAny(dates_in, datetime_dtype, 0, 0, 0, dates_in); if (dates == NULL) { goto fail; } } /* Make sure 'out' is an array if it's provided */ if (out_in != NULL) { if (!PyArray_Check(out_in)) { PyErr_SetString(PyExc_ValueError, "busday_offset: must provide a NumPy array for 'out'"); goto fail; } out = (PyArrayObject *)out_in; } ret = is_business_day(dates, out, weekmask, busdays_in_weekmask, holidays.begin, holidays.end); Py_DECREF(dates); if (allocated_holidays && holidays.begin != NULL) { PyArray_free(holidays.begin); } return out == NULL ? PyArray_Return(ret) : (PyObject *)ret; fail: Py_XDECREF(dates); if (allocated_holidays && holidays.begin != NULL) { PyArray_free(holidays.begin); } return NULL; } numpy-1.8.2/numpy/core/src/multiarray/nditer_constr.c0000664000175100017510000033101612370216242024130 0ustar vagrantvagrant00000000000000/* * This file implements the construction, copying, and destruction * aspects of NumPy's nditer. * * Copyright (c) 2010-2011 by Mark Wiebe (mwwiebe@gmail.com) * The Univerity of British Columbia * * Copyright (c) 2011 Enthought, Inc * * See LICENSE.txt for the license. */ #define NPY_NO_DEPRECATED_API NPY_API_VERSION /* Indicate that this .c file is allowed to include the header */ #define NPY_ITERATOR_IMPLEMENTATION_CODE #include "nditer_impl.h" #include "arrayobject.h" #include "scalarmathmodule.h" /* Internal helper functions private to this file */ static int npyiter_check_global_flags(npy_uint32 flags, npy_uint32* itflags); static int npyiter_check_op_axes(int nop, int oa_ndim, int **op_axes, npy_intp *itershape); static int npyiter_calculate_ndim(int nop, PyArrayObject **op_in, int oa_ndim); static int npyiter_check_per_op_flags(npy_uint32 flags, npyiter_opitflags *op_itflags); static int npyiter_prepare_one_operand(PyArrayObject **op, char **op_dataptr, PyArray_Descr *op_request_dtype, PyArray_Descr** op_dtype, npy_uint32 flags, npy_uint32 op_flags, npyiter_opitflags *op_itflags); static int npyiter_prepare_operands(int nop, PyArrayObject **op_in, PyArrayObject **op, char **op_dataptr, PyArray_Descr **op_request_dtypes, PyArray_Descr **op_dtype, npy_uint32 flags, npy_uint32 *op_flags, npyiter_opitflags *op_itflags, npy_int8 *out_maskop); static int npyiter_check_casting(int nop, PyArrayObject **op, PyArray_Descr **op_dtype, NPY_CASTING casting, npyiter_opitflags *op_itflags); static int npyiter_fill_axisdata(NpyIter *iter, npy_uint32 flags, npyiter_opitflags *op_itflags, char **op_dataptr, npy_uint32 *op_flags, int **op_axes, npy_intp *itershape); static void npyiter_replace_axisdata(NpyIter *iter, int iop, PyArrayObject *op, int op_ndim, char *op_dataptr, int *op_axes); static void npyiter_compute_index_strides(NpyIter *iter, npy_uint32 flags); static void npyiter_apply_forced_iteration_order(NpyIter *iter, NPY_ORDER order); static void npyiter_flip_negative_strides(NpyIter *iter); static void npyiter_reverse_axis_ordering(NpyIter *iter); static void npyiter_find_best_axis_ordering(NpyIter *iter); static PyArray_Descr * npyiter_get_common_dtype(int nop, PyArrayObject **op, npyiter_opitflags *op_itflags, PyArray_Descr **op_dtype, PyArray_Descr **op_request_dtypes, int only_inputs); static PyArrayObject * npyiter_new_temp_array(NpyIter *iter, PyTypeObject *subtype, npy_uint32 flags, npyiter_opitflags *op_itflags, int op_ndim, npy_intp *shape, PyArray_Descr *op_dtype, int *op_axes); static int npyiter_allocate_arrays(NpyIter *iter, npy_uint32 flags, PyArray_Descr **op_dtype, PyTypeObject *subtype, npy_uint32 *op_flags, npyiter_opitflags *op_itflags, int **op_axes); static void npyiter_get_priority_subtype(int nop, PyArrayObject **op, npyiter_opitflags *op_itflags, double *subtype_priority, PyTypeObject **subtype); static int npyiter_allocate_transfer_functions(NpyIter *iter); /*NUMPY_API * Allocate a new iterator for multiple array objects, and advanced * options for controlling the broadcasting, shape, and buffer size. */ NPY_NO_EXPORT NpyIter * NpyIter_AdvancedNew(int nop, PyArrayObject **op_in, npy_uint32 flags, NPY_ORDER order, NPY_CASTING casting, npy_uint32 *op_flags, PyArray_Descr **op_request_dtypes, int oa_ndim, int **op_axes, npy_intp *itershape, npy_intp buffersize) { npy_uint32 itflags = NPY_ITFLAG_IDENTPERM; int idim, ndim; int iop; /* The iterator being constructed */ NpyIter *iter; /* Per-operand values */ PyArrayObject **op; PyArray_Descr **op_dtype; npyiter_opitflags *op_itflags; char **op_dataptr; npy_int8 *perm; NpyIter_BufferData *bufferdata = NULL; int any_allocate = 0, any_missing_dtypes = 0, need_subtype = 0; /* The subtype for automatically allocated outputs */ double subtype_priority = NPY_PRIORITY; PyTypeObject *subtype = &PyArray_Type; #if NPY_IT_CONSTRUCTION_TIMING npy_intp c_temp, c_start, c_check_op_axes, c_check_global_flags, c_calculate_ndim, c_malloc, c_prepare_operands, c_fill_axisdata, c_compute_index_strides, c_apply_forced_iteration_order, c_find_best_axis_ordering, c_get_priority_subtype, c_find_output_common_dtype, c_check_casting, c_allocate_arrays, c_coalesce_axes, c_prepare_buffers; #endif NPY_IT_TIME_POINT(c_start); if (nop > NPY_MAXARGS) { PyErr_Format(PyExc_ValueError, "Cannot construct an iterator with more than %d operands " "(%d were requested)", (int)NPY_MAXARGS, (int)nop); return NULL; } /* * Before 1.8, if `oa_ndim == 0`, this meant `op_axes != NULL` was an error. * With 1.8, `oa_ndim == -1` takes this role, while op_axes in that case * enforces a 0-d iterator. Using `oa_ndim == 0` with `op_axes == NULL` * is thus deprecated with version 1.8. */ if ((oa_ndim == 0) && (op_axes == NULL)) { char* mesg = "using `oa_ndim == 0` when `op_axes` is NULL is " "deprecated. Use `oa_ndim == -1` or the MultiNew " "iterator for NumPy <1.8 compatibility"; if (DEPRECATE(mesg) < 0) { return NULL; } oa_ndim = -1; } /* Error check 'oa_ndim' and 'op_axes', which must be used together */ if (!npyiter_check_op_axes(nop, oa_ndim, op_axes, itershape)) { return NULL; } NPY_IT_TIME_POINT(c_check_op_axes); /* Check the global iterator flags */ if (!npyiter_check_global_flags(flags, &itflags)) { return NULL; } NPY_IT_TIME_POINT(c_check_global_flags); /* Calculate how many dimensions the iterator should have */ ndim = npyiter_calculate_ndim(nop, op_in, oa_ndim); NPY_IT_TIME_POINT(c_calculate_ndim); /* Allocate memory for the iterator */ iter = (NpyIter*) PyObject_Malloc(NIT_SIZEOF_ITERATOR(itflags, ndim, nop)); NPY_IT_TIME_POINT(c_malloc); /* Fill in the basic data */ NIT_ITFLAGS(iter) = itflags; NIT_NDIM(iter) = ndim; NIT_NOP(iter) = nop; NIT_MASKOP(iter) = -1; NIT_ITERINDEX(iter) = 0; memset(NIT_BASEOFFSETS(iter), 0, (nop+1)*NPY_SIZEOF_INTP); op = NIT_OPERANDS(iter); op_dtype = NIT_DTYPES(iter); op_itflags = NIT_OPITFLAGS(iter); op_dataptr = NIT_RESETDATAPTR(iter); /* Prepare all the operands */ if (!npyiter_prepare_operands(nop, op_in, op, op_dataptr, op_request_dtypes, op_dtype, flags, op_flags, op_itflags, &NIT_MASKOP(iter))) { PyObject_Free(iter); return NULL; } /* Set resetindex to zero as well (it's just after the resetdataptr) */ op_dataptr[nop] = 0; NPY_IT_TIME_POINT(c_prepare_operands); /* * Initialize buffer data (must set the buffers and transferdata * to NULL before we might deallocate the iterator). */ if (itflags & NPY_ITFLAG_BUFFER) { bufferdata = NIT_BUFFERDATA(iter); NBF_SIZE(bufferdata) = 0; memset(NBF_BUFFERS(bufferdata), 0, nop*NPY_SIZEOF_INTP); memset(NBF_PTRS(bufferdata), 0, nop*NPY_SIZEOF_INTP); memset(NBF_READTRANSFERDATA(bufferdata), 0, nop*NPY_SIZEOF_INTP); memset(NBF_WRITETRANSFERDATA(bufferdata), 0, nop*NPY_SIZEOF_INTP); } /* Fill in the AXISDATA arrays and set the ITERSIZE field */ if (!npyiter_fill_axisdata(iter, flags, op_itflags, op_dataptr, op_flags, op_axes, itershape)) { NpyIter_Deallocate(iter); return NULL; } NPY_IT_TIME_POINT(c_fill_axisdata); if (itflags & NPY_ITFLAG_BUFFER) { /* * If buffering is enabled and no buffersize was given, use a default * chosen to be big enough to get some amortization benefits, but * small enough to be cache-friendly. */ if (buffersize <= 0) { buffersize = NPY_BUFSIZE; } /* No point in a buffer bigger than the iteration size */ if (buffersize > NIT_ITERSIZE(iter)) { 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; } /* * If an index was requested, compute the strides for it. * Note that we must do this before changing the order of the * axes */ npyiter_compute_index_strides(iter, flags); NPY_IT_TIME_POINT(c_compute_index_strides); /* Initialize the perm to the identity */ perm = NIT_PERM(iter); for(idim = 0; idim < ndim; ++idim) { perm[idim] = (npy_int8)idim; } /* * If an iteration order is being forced, apply it. */ npyiter_apply_forced_iteration_order(iter, order); itflags = NIT_ITFLAGS(iter); NPY_IT_TIME_POINT(c_apply_forced_iteration_order); /* Set some flags for allocated outputs */ for (iop = 0; iop < nop; ++iop) { if (op[iop] == NULL) { /* Flag this so later we can avoid flipping axes */ any_allocate = 1; /* If a subtype may be used, indicate so */ if (!(op_flags[iop] & NPY_ITER_NO_SUBTYPE)) { need_subtype = 1; } /* * If the data type wasn't provided, will need to * calculate it. */ if (op_dtype[iop] == NULL) { any_missing_dtypes = 1; } } } /* * If the ordering was not forced, reorder the axes * and flip negative strides to find the best one. */ if (!(itflags & NPY_ITFLAG_FORCEDORDER)) { if (ndim > 1) { npyiter_find_best_axis_ordering(iter); } /* * If there's an output being allocated, we must not negate * any strides. */ if (!any_allocate && !(flags & NPY_ITER_DONT_NEGATE_STRIDES)) { npyiter_flip_negative_strides(iter); } itflags = NIT_ITFLAGS(iter); } NPY_IT_TIME_POINT(c_find_best_axis_ordering); if (need_subtype) { npyiter_get_priority_subtype(nop, op, op_itflags, &subtype_priority, &subtype); } NPY_IT_TIME_POINT(c_get_priority_subtype); /* * If an automatically allocated output didn't have a specified * dtype, we need to figure it out now, before allocating the outputs. */ if (any_missing_dtypes || (flags & NPY_ITER_COMMON_DTYPE)) { PyArray_Descr *dtype; int only_inputs = !(flags & NPY_ITER_COMMON_DTYPE); op = NIT_OPERANDS(iter); op_dtype = NIT_DTYPES(iter); dtype = npyiter_get_common_dtype(nop, op, op_itflags, op_dtype, op_request_dtypes, only_inputs); if (dtype == NULL) { NpyIter_Deallocate(iter); return NULL; } if (flags & NPY_ITER_COMMON_DTYPE) { NPY_IT_DBG_PRINT("Iterator: Replacing all data types\n"); /* Replace all the data types */ for (iop = 0; iop < nop; ++iop) { if (op_dtype[iop] != dtype) { Py_XDECREF(op_dtype[iop]); Py_INCREF(dtype); op_dtype[iop] = dtype; } } } else { NPY_IT_DBG_PRINT("Iterator: Setting unset output data types\n"); /* Replace the NULL data types */ for (iop = 0; iop < nop; ++iop) { if (op_dtype[iop] == NULL) { Py_INCREF(dtype); op_dtype[iop] = dtype; } } } Py_DECREF(dtype); } NPY_IT_TIME_POINT(c_find_output_common_dtype); /* * All of the data types have been settled, so it's time * to check that data type conversions are following the * casting rules. */ if (!npyiter_check_casting(nop, op, op_dtype, casting, op_itflags)) { NpyIter_Deallocate(iter); return NULL; } NPY_IT_TIME_POINT(c_check_casting); /* * At this point, the iteration order has been finalized. so * any allocation of ops that were NULL, or any temporary * copying due to casting/byte order/alignment can be * done now using a memory layout matching the iterator. */ if (!npyiter_allocate_arrays(iter, flags, op_dtype, subtype, op_flags, op_itflags, op_axes)) { NpyIter_Deallocate(iter); return NULL; } NPY_IT_TIME_POINT(c_allocate_arrays); /* * Finally, if a multi-index wasn't requested, * it may be possible to coalesce some axes together. */ if (ndim > 1 && !(itflags & NPY_ITFLAG_HASMULTIINDEX)) { npyiter_coalesce_axes(iter); /* * The operation may have changed the layout, so we have to * get the internal pointers again. */ itflags = NIT_ITFLAGS(iter); ndim = NIT_NDIM(iter); op = NIT_OPERANDS(iter); op_dtype = NIT_DTYPES(iter); op_itflags = NIT_OPITFLAGS(iter); op_dataptr = NIT_RESETDATAPTR(iter); } NPY_IT_TIME_POINT(c_coalesce_axes); /* * Now that the axes are finished, check whether we can apply * the single iteration optimization to the iternext function. */ if (!(itflags & NPY_ITFLAG_BUFFER)) { NpyIter_AxisData *axisdata = NIT_AXISDATA(iter); if (itflags & NPY_ITFLAG_EXLOOP) { if (NIT_ITERSIZE(iter) == NAD_SHAPE(axisdata)) { NIT_ITFLAGS(iter) |= NPY_ITFLAG_ONEITERATION; } } else if (NIT_ITERSIZE(iter) == 1) { NIT_ITFLAGS(iter) |= NPY_ITFLAG_ONEITERATION; } } /* * If REFS_OK was specified, check whether there are any * reference arrays and flag it if so. */ if (flags & NPY_ITER_REFS_OK) { for (iop = 0; iop < nop; ++iop) { PyArray_Descr *rdt = op_dtype[iop]; if ((rdt->flags & (NPY_ITEM_REFCOUNT | NPY_ITEM_IS_POINTER | NPY_NEEDS_PYAPI)) != 0) { /* Iteration needs API access */ NIT_ITFLAGS(iter) |= NPY_ITFLAG_NEEDSAPI; } } } /* If buffering is set without delayed allocation */ if (itflags & NPY_ITFLAG_BUFFER) { if (!npyiter_allocate_transfer_functions(iter)) { NpyIter_Deallocate(iter); return NULL; } if (!(itflags & NPY_ITFLAG_DELAYBUF)) { /* Allocate the buffers */ if (!npyiter_allocate_buffers(iter, NULL)) { NpyIter_Deallocate(iter); return NULL; } /* Prepare the next buffers and set iterend/size */ npyiter_copy_to_buffers(iter, NULL); } } NPY_IT_TIME_POINT(c_prepare_buffers); #if NPY_IT_CONSTRUCTION_TIMING printf("\nIterator construction timing:\n"); NPY_IT_PRINT_TIME_START(c_start); NPY_IT_PRINT_TIME_VAR(c_check_op_axes); NPY_IT_PRINT_TIME_VAR(c_check_global_flags); NPY_IT_PRINT_TIME_VAR(c_calculate_ndim); NPY_IT_PRINT_TIME_VAR(c_malloc); NPY_IT_PRINT_TIME_VAR(c_prepare_operands); NPY_IT_PRINT_TIME_VAR(c_fill_axisdata); NPY_IT_PRINT_TIME_VAR(c_compute_index_strides); NPY_IT_PRINT_TIME_VAR(c_apply_forced_iteration_order); NPY_IT_PRINT_TIME_VAR(c_find_best_axis_ordering); NPY_IT_PRINT_TIME_VAR(c_get_priority_subtype); NPY_IT_PRINT_TIME_VAR(c_find_output_common_dtype); NPY_IT_PRINT_TIME_VAR(c_check_casting); NPY_IT_PRINT_TIME_VAR(c_allocate_arrays); NPY_IT_PRINT_TIME_VAR(c_coalesce_axes); NPY_IT_PRINT_TIME_VAR(c_prepare_buffers); printf("\n"); #endif return iter; } /*NUMPY_API * Allocate a new iterator for more than one array object, using * standard NumPy broadcasting rules and the default buffer size. */ NPY_NO_EXPORT NpyIter * NpyIter_MultiNew(int nop, PyArrayObject **op_in, npy_uint32 flags, NPY_ORDER order, NPY_CASTING casting, npy_uint32 *op_flags, PyArray_Descr **op_request_dtypes) { return NpyIter_AdvancedNew(nop, op_in, flags, order, casting, op_flags, op_request_dtypes, -1, NULL, NULL, 0); } /*NUMPY_API * Allocate a new iterator for one array object. */ NPY_NO_EXPORT NpyIter * NpyIter_New(PyArrayObject *op, npy_uint32 flags, NPY_ORDER order, NPY_CASTING casting, PyArray_Descr* dtype) { /* Split the flags into separate global and op flags */ npy_uint32 op_flags = flags & NPY_ITER_PER_OP_FLAGS; flags &= NPY_ITER_GLOBAL_FLAGS; return NpyIter_AdvancedNew(1, &op, flags, order, casting, &op_flags, &dtype, -1, NULL, NULL, 0); } /*NUMPY_API * Makes a copy of the iterator */ NPY_NO_EXPORT NpyIter * NpyIter_Copy(NpyIter *iter) { npy_uint32 itflags = NIT_ITFLAGS(iter); int ndim = NIT_NDIM(iter); int iop, nop = NIT_NOP(iter); int out_of_memory = 0; npy_intp size; NpyIter *newiter; PyArrayObject **objects; PyArray_Descr **dtypes; /* Allocate memory for the new iterator */ size = NIT_SIZEOF_ITERATOR(itflags, ndim, nop); newiter = (NpyIter*)PyObject_Malloc(size); /* Copy the raw values to the new iterator */ memcpy(newiter, iter, size); /* Take ownership of references to the operands and dtypes */ objects = NIT_OPERANDS(newiter); dtypes = NIT_DTYPES(newiter); for (iop = 0; iop < nop; ++iop) { Py_INCREF(objects[iop]); Py_INCREF(dtypes[iop]); } /* Allocate buffers and make copies of the transfer data if necessary */ if (itflags & NPY_ITFLAG_BUFFER) { NpyIter_BufferData *bufferdata; npy_intp buffersize, itemsize; char **buffers; NpyAuxData **readtransferdata, **writetransferdata; bufferdata = NIT_BUFFERDATA(newiter); buffers = NBF_BUFFERS(bufferdata); readtransferdata = NBF_READTRANSFERDATA(bufferdata); writetransferdata = NBF_WRITETRANSFERDATA(bufferdata); buffersize = NBF_BUFFERSIZE(bufferdata); for (iop = 0; iop < nop; ++iop) { if (buffers[iop] != NULL) { if (out_of_memory) { buffers[iop] = NULL; } else { itemsize = dtypes[iop]->elsize; buffers[iop] = PyArray_malloc(itemsize*buffersize); if (buffers[iop] == NULL) { out_of_memory = 1; } } } if (readtransferdata[iop] != NULL) { if (out_of_memory) { readtransferdata[iop] = NULL; } else { readtransferdata[iop] = NPY_AUXDATA_CLONE(readtransferdata[iop]); if (readtransferdata[iop] == NULL) { out_of_memory = 1; } } } if (writetransferdata[iop] != NULL) { if (out_of_memory) { writetransferdata[iop] = NULL; } else { writetransferdata[iop] = NPY_AUXDATA_CLONE(writetransferdata[iop]); if (writetransferdata[iop] == NULL) { out_of_memory = 1; } } } } /* Initialize the buffers to the current iterindex */ if (!out_of_memory && NBF_SIZE(bufferdata) > 0) { npyiter_goto_iterindex(newiter, NIT_ITERINDEX(newiter)); /* Prepare the next buffers and set iterend/size */ npyiter_copy_to_buffers(newiter, NULL); } } if (out_of_memory) { NpyIter_Deallocate(newiter); PyErr_NoMemory(); return NULL; } return newiter; } /*NUMPY_API * Deallocate an iterator */ NPY_NO_EXPORT int NpyIter_Deallocate(NpyIter *iter) { npy_uint32 itflags; /*int ndim = NIT_NDIM(iter);*/ int iop, nop; PyArray_Descr **dtype; PyArrayObject **object; if (iter == NULL) { return NPY_SUCCEED; } itflags = NIT_ITFLAGS(iter); nop = NIT_NOP(iter); dtype = NIT_DTYPES(iter); object = NIT_OPERANDS(iter); /* Deallocate any buffers and buffering data */ if (itflags & NPY_ITFLAG_BUFFER) { NpyIter_BufferData *bufferdata = NIT_BUFFERDATA(iter); char **buffers; NpyAuxData **transferdata; /* buffers */ buffers = NBF_BUFFERS(bufferdata); for(iop = 0; iop < nop; ++iop, ++buffers) { PyArray_free(*buffers); } /* read bufferdata */ transferdata = NBF_READTRANSFERDATA(bufferdata); for(iop = 0; iop < nop; ++iop, ++transferdata) { if (*transferdata) { NPY_AUXDATA_FREE(*transferdata); } } /* write bufferdata */ transferdata = NBF_WRITETRANSFERDATA(bufferdata); for(iop = 0; iop < nop; ++iop, ++transferdata) { if (*transferdata) { NPY_AUXDATA_FREE(*transferdata); } } } /* Deallocate all the dtypes and objects that were iterated */ for(iop = 0; iop < nop; ++iop, ++dtype, ++object) { Py_XDECREF(*dtype); Py_XDECREF(*object); } /* Deallocate the iterator memory */ PyObject_Free(iter); return NPY_SUCCEED; } /* Checks 'flags' for (C|F)_ORDER_INDEX, MULTI_INDEX, and EXTERNAL_LOOP, * setting the appropriate internal flags in 'itflags'. * * Returns 1 on success, 0 on error. */ static int npyiter_check_global_flags(npy_uint32 flags, npy_uint32* itflags) { if ((flags & NPY_ITER_PER_OP_FLAGS) != 0) { PyErr_SetString(PyExc_ValueError, "A per-operand flag was passed as a global flag " "to the iterator constructor"); return 0; } /* Check for an index */ if (flags & (NPY_ITER_C_INDEX | NPY_ITER_F_INDEX)) { if ((flags & (NPY_ITER_C_INDEX | NPY_ITER_F_INDEX)) == (NPY_ITER_C_INDEX | NPY_ITER_F_INDEX)) { PyErr_SetString(PyExc_ValueError, "Iterator flags C_INDEX and " "F_INDEX cannot both be specified"); return 0; } (*itflags) |= NPY_ITFLAG_HASINDEX; } /* Check if a multi-index was requested */ if (flags & NPY_ITER_MULTI_INDEX) { /* * This flag primarily disables dimension manipulations that * would produce an incorrect multi-index. */ (*itflags) |= NPY_ITFLAG_HASMULTIINDEX; } /* Check if the caller wants to handle inner iteration */ if (flags & NPY_ITER_EXTERNAL_LOOP) { if ((*itflags) & (NPY_ITFLAG_HASINDEX | NPY_ITFLAG_HASMULTIINDEX)) { PyErr_SetString(PyExc_ValueError, "Iterator flag EXTERNAL_LOOP cannot be used " "if an index or multi-index is being tracked"); return 0; } (*itflags) |= NPY_ITFLAG_EXLOOP; } /* Ranged */ if (flags & NPY_ITER_RANGED) { (*itflags) |= NPY_ITFLAG_RANGE; if ((flags & NPY_ITER_EXTERNAL_LOOP) && !(flags & NPY_ITER_BUFFERED)) { PyErr_SetString(PyExc_ValueError, "Iterator flag RANGED cannot be used with " "the flag EXTERNAL_LOOP unless " "BUFFERED is also enabled"); return 0; } } /* Buffering */ if (flags & NPY_ITER_BUFFERED) { (*itflags) |= NPY_ITFLAG_BUFFER; if (flags & NPY_ITER_GROWINNER) { (*itflags) |= NPY_ITFLAG_GROWINNER; } if (flags & NPY_ITER_DELAY_BUFALLOC) { (*itflags) |= NPY_ITFLAG_DELAYBUF; } } return 1; } static int npyiter_check_op_axes(int nop, int oa_ndim, int **op_axes, npy_intp *itershape) { char axes_dupcheck[NPY_MAXDIMS]; int iop, idim; if (oa_ndim < 0) { /* * If `oa_ndim < 0`, `op_axes` and `itershape` are signalled to * be unused and should be NULL. (Before NumPy 1.8 this was * signalled by `oa_ndim == 0`.) */ if (op_axes != NULL || itershape != NULL) { PyErr_Format(PyExc_ValueError, "If 'op_axes' or 'itershape' is not NULL in the iterator " "constructor, 'oa_ndim' must be zero or greater"); return 0; } return 1; } if (oa_ndim > NPY_MAXDIMS) { PyErr_Format(PyExc_ValueError, "Cannot construct an iterator with more than %d dimensions " "(%d were requested for op_axes)", (int)NPY_MAXDIMS, oa_ndim); return 0; } if (op_axes == NULL) { PyErr_Format(PyExc_ValueError, "If 'oa_ndim' is zero or greater in the iterator " "constructor, then op_axes cannot be NULL"); return 0; } /* Check that there are no duplicates in op_axes */ for (iop = 0; iop < nop; ++iop) { int *axes = op_axes[iop]; if (axes != NULL) { memset(axes_dupcheck, 0, NPY_MAXDIMS); for (idim = 0; idim < oa_ndim; ++idim) { npy_intp i = axes[idim]; if (i >= 0) { if (i >= NPY_MAXDIMS) { PyErr_Format(PyExc_ValueError, "The 'op_axes' provided to the iterator " "constructor for operand %d " "contained invalid " "values %d", (int)iop, (int)i); return 0; } else if (axes_dupcheck[i] == 1) { PyErr_Format(PyExc_ValueError, "The 'op_axes' provided to the iterator " "constructor for operand %d " "contained duplicate " "value %d", (int)iop, (int)i); return 0; } else { axes_dupcheck[i] = 1; } } } } } return 1; } static int npyiter_calculate_ndim(int nop, PyArrayObject **op_in, int oa_ndim) { /* If 'op_axes' is being used, force 'ndim' */ if (oa_ndim >= 0 ) { return oa_ndim; } /* Otherwise it's the maximum 'ndim' from the operands */ else { int ndim = 0, iop; for (iop = 0; iop < nop; ++iop) { if (op_in[iop] != NULL) { int ondim = PyArray_NDIM(op_in[iop]); if (ondim > ndim) { ndim = ondim; } } } return ndim; } } /* * Checks the per-operand input flags, and fills in op_itflags. * * Returns 1 on success, 0 on failure. */ static int npyiter_check_per_op_flags(npy_uint32 op_flags, npyiter_opitflags *op_itflags) { if ((op_flags & NPY_ITER_GLOBAL_FLAGS) != 0) { PyErr_SetString(PyExc_ValueError, "A global iterator flag was passed as a per-operand flag " "to the iterator constructor"); return 0; } /* Check the read/write flags */ if (op_flags & NPY_ITER_READONLY) { /* The read/write flags are mutually exclusive */ if (op_flags & (NPY_ITER_READWRITE|NPY_ITER_WRITEONLY)) { PyErr_SetString(PyExc_ValueError, "Only one of the iterator flags READWRITE, " "READONLY, and WRITEONLY may be " "specified for an operand"); return 0; } *op_itflags = NPY_OP_ITFLAG_READ; } else if (op_flags & NPY_ITER_READWRITE) { /* The read/write flags are mutually exclusive */ if (op_flags & NPY_ITER_WRITEONLY) { PyErr_SetString(PyExc_ValueError, "Only one of the iterator flags READWRITE, " "READONLY, and WRITEONLY may be " "specified for an operand"); return 0; } *op_itflags = NPY_OP_ITFLAG_READ|NPY_OP_ITFLAG_WRITE; } else if(op_flags & NPY_ITER_WRITEONLY) { *op_itflags = NPY_OP_ITFLAG_WRITE; } else { PyErr_SetString(PyExc_ValueError, "None of the iterator flags READWRITE, " "READONLY, or WRITEONLY were " "specified for an operand"); return 0; } /* Check the flags for temporary copies */ if (((*op_itflags) & NPY_OP_ITFLAG_WRITE) && (op_flags & (NPY_ITER_COPY | NPY_ITER_UPDATEIFCOPY)) == NPY_ITER_COPY) { PyErr_SetString(PyExc_ValueError, "If an iterator operand is writeable, must use " "the flag UPDATEIFCOPY instead of " "COPY"); return 0; } /* Check the flag for a write masked operands */ if (op_flags & NPY_ITER_WRITEMASKED) { if (!((*op_itflags) & NPY_OP_ITFLAG_WRITE)) { PyErr_SetString(PyExc_ValueError, "The iterator flag WRITEMASKED may only " "be used with READWRITE or WRITEONLY"); return 0; } if ((op_flags & NPY_ITER_ARRAYMASK) != 0) { PyErr_SetString(PyExc_ValueError, "The iterator flag WRITEMASKED may not " "be used together with ARRAYMASK"); return 0; } *op_itflags |= NPY_OP_ITFLAG_WRITEMASKED; } if ((op_flags & NPY_ITER_VIRTUAL) != 0) { if ((op_flags & NPY_ITER_READWRITE) == 0) { PyErr_SetString(PyExc_ValueError, "The iterator flag VIRTUAL should be " "be used together with READWRITE"); return 0; } *op_itflags |= NPY_OP_ITFLAG_VIRTUAL; } return 1; } /* * Prepares a a constructor operand. Assumes a reference to 'op' * is owned, and that 'op' may be replaced. Fills in 'op_dataptr', * 'op_dtype', and may modify 'op_itflags'. * * Returns 1 on success, 0 on failure. */ static int npyiter_prepare_one_operand(PyArrayObject **op, char **op_dataptr, PyArray_Descr *op_request_dtype, PyArray_Descr **op_dtype, npy_uint32 flags, npy_uint32 op_flags, npyiter_opitflags *op_itflags) { /* NULL operands must be automatically allocated outputs */ if (*op == NULL) { /* ALLOCATE or VIRTUAL should be enabled */ if ((op_flags & (NPY_ITER_ALLOCATE|NPY_ITER_VIRTUAL)) == 0) { PyErr_SetString(PyExc_ValueError, "Iterator operand was NULL, but neither the " "ALLOCATE nor the VIRTUAL flag was specified"); return 0; } if (op_flags & NPY_ITER_ALLOCATE) { /* Writing should be enabled */ if (!((*op_itflags) & NPY_OP_ITFLAG_WRITE)) { PyErr_SetString(PyExc_ValueError, "Automatic allocation was requested for an iterator " "operand, but it wasn't flagged for writing"); return 0; } /* * Reading should be disabled if buffering is enabled without * also enabling NPY_ITER_DELAY_BUFALLOC. In all other cases, * the caller may initialize the allocated operand to a value * before beginning iteration. */ if (((flags & (NPY_ITER_BUFFERED | NPY_ITER_DELAY_BUFALLOC)) == NPY_ITER_BUFFERED) && ((*op_itflags) & NPY_OP_ITFLAG_READ)) { PyErr_SetString(PyExc_ValueError, "Automatic allocation was requested for an iterator " "operand, and it was flagged as readable, but " "buffering without delayed allocation was enabled"); return 0; } /* If a requested dtype was provided, use it, otherwise NULL */ Py_XINCREF(op_request_dtype); *op_dtype = op_request_dtype; } else { *op_dtype = NULL; } /* Specify bool if no dtype was requested for the mask */ if (op_flags & NPY_ITER_ARRAYMASK) { if (*op_dtype == NULL) { *op_dtype = PyArray_DescrFromType(NPY_BOOL); if (*op_dtype == NULL) { return 0; } } } *op_dataptr = NULL; return 1; } /* VIRTUAL operands must be NULL */ if (op_flags & NPY_ITER_VIRTUAL) { PyErr_SetString(PyExc_ValueError, "Iterator operand flag VIRTUAL was specified, " "but the operand was not NULL"); return 0; } if (PyArray_Check(*op)) { if ((*op_itflags) & NPY_OP_ITFLAG_WRITE && PyArray_FailUnlessWriteable(*op, "operand array with iterator " "write flag set") < 0) { return 0; } if (!(flags & NPY_ITER_ZEROSIZE_OK) && PyArray_SIZE(*op) == 0) { PyErr_SetString(PyExc_ValueError, "Iteration of zero-sized operands is not enabled"); return 0; } *op_dataptr = PyArray_BYTES(*op); /* PyArray_DESCR does not give us a reference */ *op_dtype = PyArray_DESCR(*op); if (*op_dtype == NULL) { PyErr_SetString(PyExc_ValueError, "Iterator input operand has no dtype descr"); return 0; } Py_INCREF(*op_dtype); /* * If references weren't specifically allowed, make sure there * are no references in the inputs or requested dtypes. */ if (!(flags & NPY_ITER_REFS_OK)) { PyArray_Descr *dt = PyArray_DESCR(*op); if (((dt->flags & (NPY_ITEM_REFCOUNT | NPY_ITEM_IS_POINTER)) != 0) || (dt != *op_dtype && (((*op_dtype)->flags & (NPY_ITEM_REFCOUNT | NPY_ITEM_IS_POINTER))) != 0)) { PyErr_SetString(PyExc_TypeError, "Iterator operand or requested dtype holds " "references, but the REFS_OK flag was not enabled"); return 0; } } /* * Checking whether casts are valid is done later, once the * final data types have been selected. For now, just store the * requested type. */ if (op_request_dtype != NULL) { /* We just have a borrowed reference to op_request_dtype */ Py_INCREF(op_request_dtype); /* If the requested dtype is flexible, adapt it */ PyArray_AdaptFlexibleDType((PyObject *)(*op), PyArray_DESCR(*op), &op_request_dtype); if (op_request_dtype == NULL) { return 0; } /* Store the requested dtype */ Py_DECREF(*op_dtype); *op_dtype = op_request_dtype; } /* Check if the operand is in the byte order requested */ if (op_flags & NPY_ITER_NBO) { /* Check byte order */ if (!PyArray_ISNBO((*op_dtype)->byteorder)) { PyArray_Descr *nbo_dtype; /* Replace with a new descr which is in native byte order */ nbo_dtype = PyArray_DescrNewByteorder(*op_dtype, NPY_NATIVE); Py_DECREF(*op_dtype); *op_dtype = nbo_dtype; NPY_IT_DBG_PRINT("Iterator: Setting NPY_OP_ITFLAG_CAST " "because of NPY_ITER_NBO\n"); /* Indicate that byte order or alignment needs fixing */ *op_itflags |= NPY_OP_ITFLAG_CAST; } } /* Check if the operand is aligned */ if (op_flags & NPY_ITER_ALIGNED) { /* Check alignment */ if (!PyArray_ISALIGNED(*op)) { NPY_IT_DBG_PRINT("Iterator: Setting NPY_OP_ITFLAG_CAST " "because of NPY_ITER_ALIGNED\n"); *op_itflags |= NPY_OP_ITFLAG_CAST; } } /* * The check for NPY_ITER_CONTIG can only be done later, * once the final iteration order is settled. */ } else { PyErr_SetString(PyExc_ValueError, "Iterator inputs must be ndarrays"); return 0; } return 1; } /* * Process all the operands, copying new references so further processing * can replace the arrays if copying is necessary. */ static int npyiter_prepare_operands(int nop, PyArrayObject **op_in, PyArrayObject **op, char **op_dataptr, PyArray_Descr **op_request_dtypes, PyArray_Descr **op_dtype, npy_uint32 flags, npy_uint32 *op_flags, npyiter_opitflags *op_itflags, npy_int8 *out_maskop) { int iop, i; npy_int8 maskop = -1; int any_writemasked_ops = 0; /* * Here we just prepare the provided operands. */ for (iop = 0; iop < nop; ++iop) { op[iop] = op_in[iop]; Py_XINCREF(op[iop]); op_dtype[iop] = NULL; /* Check the readonly/writeonly flags, and fill in op_itflags */ if (!npyiter_check_per_op_flags(op_flags[iop], &op_itflags[iop])) { goto fail_iop; } /* Extract the operand which is for masked iteration */ if ((op_flags[iop] & NPY_ITER_ARRAYMASK) != 0) { if (maskop != -1) { PyErr_SetString(PyExc_ValueError, "Only one iterator operand may receive an " "ARRAYMASK flag"); goto fail_iop; } maskop = iop; *out_maskop = iop; } if (op_flags[iop] & NPY_ITER_WRITEMASKED) { any_writemasked_ops = 1; } /* * Prepare the operand. This produces an op_dtype[iop] reference * on success. */ if (!npyiter_prepare_one_operand(&op[iop], &op_dataptr[iop], op_request_dtypes ? op_request_dtypes[iop] : NULL, &op_dtype[iop], flags, op_flags[iop], &op_itflags[iop])) { goto fail_iop; } } /* If all the operands were NULL, it's an error */ if (op[0] == NULL) { int all_null = 1; for (iop = 1; iop < nop; ++iop) { if (op[iop] != NULL) { all_null = 0; break; } } if (all_null) { PyErr_SetString(PyExc_ValueError, "At least one iterator operand must be non-NULL"); goto fail_nop; } } if (any_writemasked_ops && maskop < 0) { PyErr_SetString(PyExc_ValueError, "An iterator operand was flagged as WRITEMASKED, " "but no ARRAYMASK operand was given to supply " "the mask"); goto fail_nop; } else if (!any_writemasked_ops && maskop >= 0) { PyErr_SetString(PyExc_ValueError, "An iterator operand was flagged as the ARRAYMASK, " "but no WRITEMASKED operands were given to use " "the mask"); goto fail_nop; } return 1; fail_nop: iop = nop; fail_iop: for (i = 0; i < iop; ++i) { Py_XDECREF(op[i]); Py_XDECREF(op_dtype[i]); } return 0; } static const char * npyiter_casting_to_string(NPY_CASTING casting) { switch (casting) { case NPY_NO_CASTING: return "'no'"; case NPY_EQUIV_CASTING: return "'equiv'"; case NPY_SAFE_CASTING: return "'safe'"; case NPY_SAME_KIND_CASTING: return "'same_kind'"; case NPY_UNSAFE_CASTING: return "'unsafe'"; default: return ""; } } static int npyiter_check_casting(int nop, PyArrayObject **op, PyArray_Descr **op_dtype, NPY_CASTING casting, npyiter_opitflags *op_itflags) { int iop; for(iop = 0; iop < nop; ++iop) { NPY_IT_DBG_PRINT1("Iterator: Checking casting for operand %d\n", (int)iop); #if NPY_IT_DBG_TRACING printf("op: "); if (op[iop] != NULL) { PyObject_Print((PyObject *)PyArray_DESCR(op[iop]), stdout, 0); } else { printf(""); } printf(", iter: "); PyObject_Print((PyObject *)op_dtype[iop], stdout, 0); printf("\n"); #endif /* If the types aren't equivalent, a cast is necessary */ if (op[iop] != NULL && !PyArray_EquivTypes(PyArray_DESCR(op[iop]), op_dtype[iop])) { /* Check read (op -> temp) casting */ if ((op_itflags[iop] & NPY_OP_ITFLAG_READ) && !PyArray_CanCastArrayTo(op[iop], op_dtype[iop], casting)) { PyObject *errmsg; errmsg = PyUString_FromFormat( "Iterator operand %d dtype could not be cast from ", (int)iop); PyUString_ConcatAndDel(&errmsg, PyObject_Repr((PyObject *)PyArray_DESCR(op[iop]))); PyUString_ConcatAndDel(&errmsg, PyUString_FromString(" to ")); PyUString_ConcatAndDel(&errmsg, PyObject_Repr((PyObject *)op_dtype[iop])); PyUString_ConcatAndDel(&errmsg, PyUString_FromFormat(" according to the rule %s", npyiter_casting_to_string(casting))); PyErr_SetObject(PyExc_TypeError, errmsg); Py_DECREF(errmsg); return 0; } /* Check write (temp -> op) casting */ if ((op_itflags[iop] & NPY_OP_ITFLAG_WRITE) && !PyArray_CanCastTypeTo(op_dtype[iop], PyArray_DESCR(op[iop]), casting)) { PyObject *errmsg; errmsg = PyUString_FromString( "Iterator requested dtype could not be cast from "); PyUString_ConcatAndDel(&errmsg, PyObject_Repr((PyObject *)op_dtype[iop])); PyUString_ConcatAndDel(&errmsg, PyUString_FromString(" to ")); PyUString_ConcatAndDel(&errmsg, PyObject_Repr((PyObject *)PyArray_DESCR(op[iop]))); PyUString_ConcatAndDel(&errmsg, PyUString_FromFormat(", the operand %d dtype, " "according to the rule %s", (int)iop, npyiter_casting_to_string(casting))); PyErr_SetObject(PyExc_TypeError, errmsg); Py_DECREF(errmsg); return 0; } NPY_IT_DBG_PRINT("Iterator: Setting NPY_OP_ITFLAG_CAST " "because the types aren't equivalent\n"); /* Indicate that this operand needs casting */ op_itflags[iop] |= NPY_OP_ITFLAG_CAST; } } return 1; } /* * Checks that the mask broadcasts to the WRITEMASK REDUCE * operand 'iop', but 'iop' never broadcasts to the mask. * If 'iop' broadcasts to the mask, the result would be more * than one mask value per reduction element, something which * is invalid. * * This check should only be called after all the operands * have been filled in. * * Returns 1 on success, 0 on error. */ static int check_mask_for_writemasked_reduction(NpyIter *iter, int iop) { npy_uint32 itflags = NIT_ITFLAGS(iter); int idim, ndim = NIT_NDIM(iter); int nop = NIT_NOP(iter); int maskop = NIT_MASKOP(iter); NpyIter_AxisData *axisdata; npy_intp sizeof_axisdata; axisdata = NIT_AXISDATA(iter); sizeof_axisdata = NIT_AXISDATA_SIZEOF(itflags, ndim, nop); for(idim = 0; idim < ndim; ++idim) { npy_intp maskstride, istride; istride = NAD_STRIDES(axisdata)[iop]; maskstride = NAD_STRIDES(axisdata)[maskop]; /* * If 'iop' is being broadcast to 'maskop', we have * the invalid situation described above. */ if (maskstride != 0 && istride == 0) { PyErr_SetString(PyExc_ValueError, "Iterator reduction operand is WRITEMASKED, " "but also broadcasts to multiple mask values. " "There can be only one mask value per WRITEMASKED " "element."); return 0; } NIT_ADVANCE_AXISDATA(axisdata, 1); } return 1; } /* * Fills in the AXISDATA for the 'nop' operands, broadcasting * the dimensionas as necessary. Also fills * in the ITERSIZE data member. * * If op_axes is not NULL, it should point to an array of ndim-sized * arrays, one for each op. * * Returns 1 on success, 0 on failure. */ static int npyiter_fill_axisdata(NpyIter *iter, npy_uint32 flags, npyiter_opitflags *op_itflags, char **op_dataptr, npy_uint32 *op_flags, int **op_axes, npy_intp *itershape) { npy_uint32 itflags = NIT_ITFLAGS(iter); int idim, ndim = NIT_NDIM(iter); int iop, nop = NIT_NOP(iter); int maskop = NIT_MASKOP(iter); int ondim; NpyIter_AxisData *axisdata; npy_intp sizeof_axisdata; PyArrayObject **op = NIT_OPERANDS(iter), *op_cur; npy_intp broadcast_shape[NPY_MAXDIMS]; /* First broadcast the shapes together */ if (itershape == NULL) { for (idim = 0; idim < ndim; ++idim) { broadcast_shape[idim] = 1; } } else { for (idim = 0; idim < ndim; ++idim) { broadcast_shape[idim] = itershape[idim]; /* Negative shape entries are deduced from the operands */ if (broadcast_shape[idim] < 0) { broadcast_shape[idim] = 1; } } } for (iop = 0; iop < nop; ++iop) { op_cur = op[iop]; if (op_cur != NULL) { npy_intp *shape = PyArray_DIMS(op_cur); ondim = PyArray_NDIM(op_cur); if (op_axes == NULL || op_axes[iop] == NULL) { /* * Possible if op_axes are being used, but * op_axes[iop] is NULL */ if (ondim > ndim) { PyErr_SetString(PyExc_ValueError, "input operand has more dimensions than allowed " "by the axis remapping"); return 0; } for (idim = 0; idim < ondim; ++idim) { npy_intp bshape = broadcast_shape[idim+ndim-ondim], op_shape = shape[idim]; if (bshape == 1) { broadcast_shape[idim+ndim-ondim] = op_shape; } else if (bshape != op_shape && op_shape != 1) { goto broadcast_error; } } } else { int *axes = op_axes[iop]; for (idim = 0; idim < ndim; ++idim) { int i = axes[idim]; if (i >= 0) { if (i < ondim) { npy_intp bshape = broadcast_shape[idim], op_shape = shape[i]; if (bshape == 1) { broadcast_shape[idim] = op_shape; } else if (bshape != op_shape && op_shape != 1) { goto broadcast_error; } } else { PyErr_Format(PyExc_ValueError, "Iterator input op_axes[%d][%d] (==%d) " "is not a valid axis of op[%d], which " "has %d dimensions ", (int)iop, (int)(ndim-idim-1), (int)i, (int)iop, (int)ondim); return 0; } } } } } } /* * If a shape was provided with a 1 entry, make sure that entry didn't * get expanded by broadcasting. */ if (itershape != NULL) { for (idim = 0; idim < ndim; ++idim) { if (itershape[idim] == 1 && broadcast_shape[idim] != 1) { goto broadcast_error; } } } axisdata = NIT_AXISDATA(iter); sizeof_axisdata = NIT_AXISDATA_SIZEOF(itflags, ndim, nop); if (ndim == 0) { /* Need to fill the first axisdata, even if the iterator is 0-d */ NAD_SHAPE(axisdata) = 1; NAD_INDEX(axisdata) = 0; memcpy(NAD_PTRS(axisdata), op_dataptr, NPY_SIZEOF_INTP*nop); memset(NAD_STRIDES(axisdata), 0, NPY_SIZEOF_INTP*nop); } /* Now process the operands, filling in the axisdata */ for (idim = 0; idim < ndim; ++idim) { npy_intp bshape = broadcast_shape[ndim-idim-1]; npy_intp *strides = NAD_STRIDES(axisdata); NAD_SHAPE(axisdata) = bshape; NAD_INDEX(axisdata) = 0; memcpy(NAD_PTRS(axisdata), op_dataptr, NPY_SIZEOF_INTP*nop); for (iop = 0; iop < nop; ++iop) { op_cur = op[iop]; if (op_axes == NULL || op_axes[iop] == NULL) { if (op_cur == NULL) { strides[iop] = 0; } else { ondim = PyArray_NDIM(op_cur); if (bshape == 1) { strides[iop] = 0; if (idim >= ondim && (op_flags[iop] & NPY_ITER_NO_BROADCAST)) { goto operand_different_than_broadcast; } } else if (idim >= ondim || PyArray_DIM(op_cur, ondim-idim-1) == 1) { strides[iop] = 0; if (op_flags[iop] & NPY_ITER_NO_BROADCAST) { goto operand_different_than_broadcast; } /* If it's writeable, this means a reduction */ if (op_itflags[iop] & NPY_OP_ITFLAG_WRITE) { if (!(flags & NPY_ITER_REDUCE_OK)) { PyErr_SetString(PyExc_ValueError, "output operand requires a " "reduction, but reduction is " "not enabled"); return 0; } if (!(op_itflags[iop] & NPY_OP_ITFLAG_READ)) { PyErr_SetString(PyExc_ValueError, "output operand requires a " "reduction, but is flagged as " "write-only, not read-write"); return 0; } /* * The ARRAYMASK can't be a reduction, because * it would be possible to write back to the * array once when the ARRAYMASK says 'True', * then have the reduction on the ARRAYMASK * later flip to 'False', indicating that the * write back should never have been done, * and violating the strict masking semantics */ if (iop == maskop) { PyErr_SetString(PyExc_ValueError, "output operand requires a " "reduction, but is flagged as " "the ARRAYMASK operand which " "is not permitted to be the " "result of a reduction"); return 0; } NIT_ITFLAGS(iter) |= NPY_ITFLAG_REDUCE; op_itflags[iop] |= NPY_OP_ITFLAG_REDUCE; } } else { strides[iop] = PyArray_STRIDE(op_cur, ondim-idim-1); } } } else { int *axes = op_axes[iop]; int i = axes[ndim-idim-1]; if (i >= 0) { if (bshape == 1 || op_cur == NULL) { strides[iop] = 0; } else if (PyArray_DIM(op_cur, i) == 1) { strides[iop] = 0; if (op_flags[iop] & NPY_ITER_NO_BROADCAST) { goto operand_different_than_broadcast; } /* If it's writeable, this means a reduction */ if (op_itflags[iop] & NPY_OP_ITFLAG_WRITE) { if (!(flags & NPY_ITER_REDUCE_OK)) { PyErr_SetString(PyExc_ValueError, "output operand requires a reduction, but " "reduction is not enabled"); return 0; } if (!(op_itflags[iop] & NPY_OP_ITFLAG_READ)) { PyErr_SetString(PyExc_ValueError, "output operand requires a reduction, but " "is flagged as write-only, not " "read-write"); return 0; } NIT_ITFLAGS(iter) |= NPY_ITFLAG_REDUCE; op_itflags[iop] |= NPY_OP_ITFLAG_REDUCE; } } else { strides[iop] = PyArray_STRIDE(op_cur, i); } } else if (bshape == 1) { strides[iop] = 0; } else { strides[iop] = 0; /* If it's writeable, this means a reduction */ if (op_itflags[iop] & NPY_OP_ITFLAG_WRITE) { if (!(flags & NPY_ITER_REDUCE_OK)) { PyErr_SetString(PyExc_ValueError, "output operand requires a reduction, but " "reduction is not enabled"); return 0; } if (!(op_itflags[iop] & NPY_OP_ITFLAG_READ)) { PyErr_SetString(PyExc_ValueError, "output operand requires a reduction, but " "is flagged as write-only, not " "read-write"); return 0; } NIT_ITFLAGS(iter) |= NPY_ITFLAG_REDUCE; op_itflags[iop] |= NPY_OP_ITFLAG_REDUCE; } } } } NIT_ADVANCE_AXISDATA(axisdata, 1); } /* Now fill in the ITERSIZE member */ NIT_ITERSIZE(iter) = 1; for (idim = 0; idim < ndim; ++idim) { if (npy_mul_with_overflow_intp(&NIT_ITERSIZE(iter), NIT_ITERSIZE(iter), broadcast_shape[idim])) { 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 */ NIT_ITERSTART(iter) = 0; NIT_ITEREND(iter) = NIT_ITERSIZE(iter); return 1; broadcast_error: { PyObject *errmsg, *tmp; npy_intp remdims[NPY_MAXDIMS]; char *tmpstr; if (op_axes == NULL) { errmsg = PyUString_FromString("operands could not be broadcast " "together with shapes "); if (errmsg == NULL) { return 0; } for (iop = 0; iop < nop; ++iop) { if (op[iop] != NULL) { tmp = convert_shape_to_string(PyArray_NDIM(op[iop]), PyArray_DIMS(op[iop]), " "); if (tmp == NULL) { Py_DECREF(errmsg); return 0; } PyUString_ConcatAndDel(&errmsg, tmp); if (errmsg == NULL) { return 0; } } } if (itershape != NULL) { tmp = PyUString_FromString("and requested shape "); if (tmp == NULL) { Py_DECREF(errmsg); return 0; } PyUString_ConcatAndDel(&errmsg, tmp); if (errmsg == NULL) { return 0; } tmp = convert_shape_to_string(ndim, itershape, ""); if (tmp == NULL) { Py_DECREF(errmsg); return 0; } PyUString_ConcatAndDel(&errmsg, tmp); if (errmsg == NULL) { return 0; } } PyErr_SetObject(PyExc_ValueError, errmsg); Py_DECREF(errmsg); } else { errmsg = PyUString_FromString("operands could not be broadcast " "together with remapped shapes " "[original->remapped]: "); for (iop = 0; iop < nop; ++iop) { if (op[iop] != NULL) { int *axes = op_axes[iop]; tmpstr = (axes == NULL) ? " " : "->"; tmp = convert_shape_to_string(PyArray_NDIM(op[iop]), PyArray_DIMS(op[iop]), tmpstr); if (tmp == NULL) { return 0; } PyUString_ConcatAndDel(&errmsg, tmp); if (errmsg == NULL) { return 0; } if (axes != NULL) { for (idim = 0; idim < ndim; ++idim) { npy_intp i = axes[idim]; if (i >= 0 && i < PyArray_NDIM(op[iop])) { remdims[idim] = PyArray_DIM(op[iop], i); } else { remdims[idim] = -1; } } tmp = convert_shape_to_string(ndim, remdims, " "); if (tmp == NULL) { return 0; } PyUString_ConcatAndDel(&errmsg, tmp); if (errmsg == NULL) { return 0; } } } } if (itershape != NULL) { tmp = PyUString_FromString("and requested shape "); if (tmp == NULL) { Py_DECREF(errmsg); return 0; } PyUString_ConcatAndDel(&errmsg, tmp); if (errmsg == NULL) { return 0; } tmp = convert_shape_to_string(ndim, itershape, ""); if (tmp == NULL) { Py_DECREF(errmsg); return 0; } PyUString_ConcatAndDel(&errmsg, tmp); if (errmsg == NULL) { return 0; } } PyErr_SetObject(PyExc_ValueError, errmsg); Py_DECREF(errmsg); } return 0; } operand_different_than_broadcast: { npy_intp remdims[NPY_MAXDIMS]; PyObject *errmsg, *tmp; /* Start of error message */ if (op_flags[iop] & NPY_ITER_READONLY) { errmsg = PyUString_FromString("non-broadcastable operand " "with shape "); } else { errmsg = PyUString_FromString("non-broadcastable output " "operand with shape "); } if (errmsg == NULL) { return 0; } /* Operand shape */ tmp = convert_shape_to_string(PyArray_NDIM(op[iop]), PyArray_DIMS(op[iop]), ""); if (tmp == NULL) { return 0; } PyUString_ConcatAndDel(&errmsg, tmp); if (errmsg == NULL) { return 0; } /* Remapped operand shape */ if (op_axes != NULL && op_axes[iop] != NULL) { int *axes = op_axes[iop]; for (idim = 0; idim < ndim; ++idim) { npy_intp i = axes[ndim-idim-1]; if (i >= 0 && i < PyArray_NDIM(op[iop])) { remdims[idim] = PyArray_DIM(op[iop], i); } else { remdims[idim] = -1; } } tmp = PyUString_FromString(" [remapped to "); if (tmp == NULL) { return 0; } PyUString_ConcatAndDel(&errmsg, tmp); if (errmsg == NULL) { return 0; } tmp = convert_shape_to_string(ndim, remdims, "]"); if (tmp == NULL) { return 0; } PyUString_ConcatAndDel(&errmsg, tmp); if (errmsg == NULL) { return 0; } } tmp = PyUString_FromString(" doesn't match the broadcast shape "); if (tmp == NULL) { return 0; } PyUString_ConcatAndDel(&errmsg, tmp); if (errmsg == NULL) { return 0; } /* Broadcast shape */ tmp = convert_shape_to_string(ndim, broadcast_shape, ""); if (tmp == NULL) { return 0; } PyUString_ConcatAndDel(&errmsg, tmp); if (errmsg == NULL) { return 0; } PyErr_SetObject(PyExc_ValueError, errmsg); Py_DECREF(errmsg); return 0; } } /* * Replaces the AXISDATA for the iop'th operand, broadcasting * the dimensions as necessary. Assumes the replacement array is * exactly the same shape as the original array used when * npy_fill_axisdata was called. * * If op_axes is not NULL, it should point to an ndim-sized * array. */ static void npyiter_replace_axisdata(NpyIter *iter, int iop, PyArrayObject *op, int op_ndim, char *op_dataptr, int *op_axes) { npy_uint32 itflags = NIT_ITFLAGS(iter); int idim, ndim = NIT_NDIM(iter); int nop = NIT_NOP(iter); NpyIter_AxisData *axisdata0, *axisdata; npy_intp sizeof_axisdata; npy_int8 *perm; npy_intp baseoffset = 0; perm = NIT_PERM(iter); axisdata0 = NIT_AXISDATA(iter); sizeof_axisdata = NIT_AXISDATA_SIZEOF(itflags, ndim, nop); /* * Replace just the strides which were non-zero, and compute * the base data address. */ axisdata = axisdata0; if (op_axes != NULL) { for (idim = 0; idim < ndim; ++idim, NIT_ADVANCE_AXISDATA(axisdata, 1)) { npy_int8 p; int i; npy_intp shape; /* Apply the perm to get the original axis */ p = perm[idim]; if (p < 0) { i = op_axes[ndim+p]; } else { i = op_axes[ndim-p-1]; } if (0 <= i && i < op_ndim) { shape = PyArray_DIM(op, i); if (shape != 1) { npy_intp stride = PyArray_STRIDE(op, i); if (p < 0) { /* If the perm entry is negative, flip the axis */ NAD_STRIDES(axisdata)[iop] = -stride; baseoffset += stride*(shape-1); } else { NAD_STRIDES(axisdata)[iop] = stride; } } } } } else { for (idim = 0; idim < ndim; ++idim, NIT_ADVANCE_AXISDATA(axisdata, 1)) { npy_int8 p; int i; npy_intp shape; /* Apply the perm to get the original axis */ p = perm[idim]; if (p < 0) { i = op_ndim+p; } else { i = op_ndim-p-1; } if (i >= 0) { shape = PyArray_DIM(op, i); if (shape != 1) { npy_intp stride = PyArray_STRIDE(op, i); if (p < 0) { /* If the perm entry is negative, flip the axis */ NAD_STRIDES(axisdata)[iop] = -stride; baseoffset += stride*(shape-1); } else { NAD_STRIDES(axisdata)[iop] = stride; } } } } } op_dataptr += baseoffset; /* Now the base data pointer is calculated, set it everywhere it's needed */ NIT_RESETDATAPTR(iter)[iop] = op_dataptr; NIT_BASEOFFSETS(iter)[iop] = baseoffset; axisdata = axisdata0; /* Fill at least one axisdata, for the 0-d case */ NAD_PTRS(axisdata)[iop] = op_dataptr; NIT_ADVANCE_AXISDATA(axisdata, 1); for (idim = 1; idim < ndim; ++idim, NIT_ADVANCE_AXISDATA(axisdata, 1)) { NAD_PTRS(axisdata)[iop] = op_dataptr; } } /* * Computes the iterator's index strides and initializes the index values * to zero. * * This must be called before the axes (i.e. the AXISDATA array) may * be reordered. */ static void npyiter_compute_index_strides(NpyIter *iter, npy_uint32 flags) { npy_uint32 itflags = NIT_ITFLAGS(iter); int idim, ndim = NIT_NDIM(iter); int nop = NIT_NOP(iter); npy_intp indexstride; NpyIter_AxisData *axisdata; npy_intp sizeof_axisdata; /* * If there is only one element being iterated, we just have * to touch the first AXISDATA because nothing will ever be * incremented. This also initializes the data for the 0-d case. */ if (NIT_ITERSIZE(iter) == 1) { if (itflags & NPY_ITFLAG_HASINDEX) { axisdata = NIT_AXISDATA(iter); NAD_PTRS(axisdata)[nop] = 0; } return; } if (flags & NPY_ITER_C_INDEX) { sizeof_axisdata = NIT_AXISDATA_SIZEOF(itflags, ndim, nop); axisdata = NIT_AXISDATA(iter); indexstride = 1; for(idim = 0; idim < ndim; ++idim, NIT_ADVANCE_AXISDATA(axisdata, 1)) { npy_intp shape = NAD_SHAPE(axisdata); if (shape == 1) { NAD_STRIDES(axisdata)[nop] = 0; } else { NAD_STRIDES(axisdata)[nop] = indexstride; } NAD_PTRS(axisdata)[nop] = 0; indexstride *= shape; } } else if (flags & NPY_ITER_F_INDEX) { sizeof_axisdata = NIT_AXISDATA_SIZEOF(itflags, ndim, nop); axisdata = NIT_INDEX_AXISDATA(NIT_AXISDATA(iter), ndim-1); indexstride = 1; for(idim = 0; idim < ndim; ++idim, NIT_ADVANCE_AXISDATA(axisdata, -1)) { npy_intp shape = NAD_SHAPE(axisdata); if (shape == 1) { NAD_STRIDES(axisdata)[nop] = 0; } else { NAD_STRIDES(axisdata)[nop] = indexstride; } NAD_PTRS(axisdata)[nop] = 0; indexstride *= shape; } } } /* * If the order is NPY_KEEPORDER, lets the iterator find the best * iteration order, otherwise forces it. Indicates in the itflags that * whether the iteration order was forced. */ static void npyiter_apply_forced_iteration_order(NpyIter *iter, NPY_ORDER order) { /*npy_uint32 itflags = NIT_ITFLAGS(iter);*/ int ndim = NIT_NDIM(iter); int iop, nop = NIT_NOP(iter); switch (order) { case NPY_CORDER: NIT_ITFLAGS(iter) |= NPY_ITFLAG_FORCEDORDER; break; case NPY_FORTRANORDER: NIT_ITFLAGS(iter) |= NPY_ITFLAG_FORCEDORDER; /* Only need to actually do something if there is more than 1 dim */ if (ndim > 1) { npyiter_reverse_axis_ordering(iter); } break; case NPY_ANYORDER: NIT_ITFLAGS(iter) |= NPY_ITFLAG_FORCEDORDER; /* Only need to actually do something if there is more than 1 dim */ if (ndim > 1) { PyArrayObject **op = NIT_OPERANDS(iter); int forder = 1; /* Check that all the array inputs are fortran order */ for (iop = 0; iop < nop; ++iop, ++op) { if (*op && !PyArray_CHKFLAGS(*op, NPY_ARRAY_F_CONTIGUOUS)) { forder = 0; break; } } if (forder) { npyiter_reverse_axis_ordering(iter); } } break; case NPY_KEEPORDER: /* Don't set the forced order flag here... */ break; } } /* * This function negates any strides in the iterator * which are negative. When iterating more than one * object, it only flips strides when they are all * negative or zero. */ static void npyiter_flip_negative_strides(NpyIter *iter) { npy_uint32 itflags = NIT_ITFLAGS(iter); int idim, ndim = NIT_NDIM(iter); int iop, nop = NIT_NOP(iter); npy_intp istrides, nstrides = NAD_NSTRIDES(); NpyIter_AxisData *axisdata, *axisdata0; npy_intp *baseoffsets; npy_intp sizeof_axisdata = NIT_AXISDATA_SIZEOF(itflags, ndim, nop); int any_flipped = 0; axisdata0 = axisdata = NIT_AXISDATA(iter); baseoffsets = NIT_BASEOFFSETS(iter); for (idim = 0; idim < ndim; ++idim, NIT_ADVANCE_AXISDATA(axisdata, 1)) { npy_intp *strides = NAD_STRIDES(axisdata); int any_negative = 0; /* * Check the signs of all the operand strides. */ for (iop = 0; iop < nop; ++iop) { if (strides[iop] < 0) { any_negative = 1; } else if (strides[iop] != 0) { break; } } /* * If at least one stride is negative and none are positive, * flip all the strides for this dimension. */ if (any_negative && iop == nop) { npy_intp shapem1 = NAD_SHAPE(axisdata) - 1; for (istrides = 0; istrides < nstrides; ++istrides) { npy_intp stride = strides[istrides]; /* Adjust the base pointers to start at the end */ baseoffsets[istrides] += shapem1 * stride; /* Flip the stride */ strides[istrides] = -stride; } /* * Make the perm entry negative so get_multi_index * knows it's flipped */ NIT_PERM(iter)[idim] = -1-NIT_PERM(iter)[idim]; any_flipped = 1; } } /* * If any strides were flipped, the base pointers were adjusted * in the first AXISDATA, and need to be copied to all the rest */ if (any_flipped) { char **resetdataptr = NIT_RESETDATAPTR(iter); for (istrides = 0; istrides < nstrides; ++istrides) { resetdataptr[istrides] += baseoffsets[istrides]; } axisdata = axisdata0; for (idim = 0; idim < ndim; ++idim, NIT_ADVANCE_AXISDATA(axisdata, 1)) { char **ptrs = NAD_PTRS(axisdata); for (istrides = 0; istrides < nstrides; ++istrides) { ptrs[istrides] = resetdataptr[istrides]; } } /* * Indicate that some of the perm entries are negative, * and that it's not (strictly speaking) the identity perm. */ NIT_ITFLAGS(iter) = (NIT_ITFLAGS(iter)|NPY_ITFLAG_NEGPERM) & ~NPY_ITFLAG_IDENTPERM; } } static void npyiter_reverse_axis_ordering(NpyIter *iter) { npy_uint32 itflags = NIT_ITFLAGS(iter); int ndim = NIT_NDIM(iter); int nop = NIT_NOP(iter); npy_intp i, temp, size; npy_intp *first, *last; npy_int8 *perm; size = NIT_AXISDATA_SIZEOF(itflags, ndim, nop)/NPY_SIZEOF_INTP; first = (npy_intp*)NIT_AXISDATA(iter); last = first + (ndim-1)*size; /* This loop reverses the order of the AXISDATA array */ while (first < last) { for (i = 0; i < size; ++i) { temp = first[i]; first[i] = last[i]; last[i] = temp; } first += size; last -= size; } /* Store the perm we applied */ perm = NIT_PERM(iter); for(i = ndim-1; i >= 0; --i, ++perm) { *perm = (npy_int8)i; } NIT_ITFLAGS(iter) &= ~NPY_ITFLAG_IDENTPERM; } static NPY_INLINE npy_intp intp_abs(npy_intp x) { return (x < 0) ? -x : x; } static void npyiter_find_best_axis_ordering(NpyIter *iter) { npy_uint32 itflags = NIT_ITFLAGS(iter); int idim, ndim = NIT_NDIM(iter); int iop, nop = NIT_NOP(iter); npy_intp ax_i0, ax_i1, ax_ipos; npy_int8 ax_j0, ax_j1; npy_int8 *perm; NpyIter_AxisData *axisdata = NIT_AXISDATA(iter); npy_intp sizeof_axisdata = NIT_AXISDATA_SIZEOF(itflags, ndim, nop); int permuted = 0; perm = NIT_PERM(iter); /* * Do a custom stable insertion sort. Note that because * the AXISDATA has been reversed from C order, this * is sorting from smallest stride to biggest stride. */ for (ax_i0 = 1; ax_i0 < ndim; ++ax_i0) { npy_intp *strides0; /* 'ax_ipos' is where perm[ax_i0] will get inserted */ ax_ipos = ax_i0; ax_j0 = perm[ax_i0]; strides0 = NAD_STRIDES(NIT_INDEX_AXISDATA(axisdata, ax_j0)); for (ax_i1 = ax_i0-1; ax_i1 >= 0; --ax_i1) { int ambig = 1, shouldswap = 0; npy_intp *strides1; ax_j1 = perm[ax_i1]; strides1 = NAD_STRIDES(NIT_INDEX_AXISDATA(axisdata, ax_j1)); for (iop = 0; iop < nop; ++iop) { if (strides0[iop] != 0 && strides1[iop] != 0) { if (intp_abs(strides1[iop]) <= intp_abs(strides0[iop])) { /* * Set swap even if it's not ambiguous already, * because in the case of conflicts between * different operands, C-order wins. */ shouldswap = 0; } else { /* Only set swap if it's still ambiguous */ if (ambig) { shouldswap = 1; } } /* * A comparison has been done, so it's * no longer ambiguous */ ambig = 0; } } /* * If the comparison was unambiguous, either shift * 'ax_ipos' to 'ax_i1' or stop looking for an insertion * point */ if (!ambig) { if (shouldswap) { ax_ipos = ax_i1; } else { break; } } } /* Insert perm[ax_i0] into the right place */ if (ax_ipos != ax_i0) { for (ax_i1 = ax_i0; ax_i1 > ax_ipos; --ax_i1) { perm[ax_i1] = perm[ax_i1-1]; } perm[ax_ipos] = ax_j0; permuted = 1; } } /* Apply the computed permutation to the AXISDATA array */ if (permuted == 1) { npy_intp i, size = sizeof_axisdata/NPY_SIZEOF_INTP; NpyIter_AxisData *ad_i; /* Use the index as a flag, set each to 1 */ ad_i = axisdata; for (idim = 0; idim < ndim; ++idim, NIT_ADVANCE_AXISDATA(ad_i, 1)) { NAD_INDEX(ad_i) = 1; } /* Apply the permutation by following the cycles */ for (idim = 0; idim < ndim; ++idim) { ad_i = NIT_INDEX_AXISDATA(axisdata, idim); /* If this axis hasn't been touched yet, process it */ if (NAD_INDEX(ad_i) == 1) { npy_int8 pidim = perm[idim]; npy_intp tmp; NpyIter_AxisData *ad_p, *ad_q; if (pidim != idim) { /* Follow the cycle, copying the data */ for (i = 0; i < size; ++i) { pidim = perm[idim]; ad_q = ad_i; tmp = *((npy_intp*)ad_q + i); while (pidim != idim) { ad_p = NIT_INDEX_AXISDATA(axisdata, pidim); *((npy_intp*)ad_q + i) = *((npy_intp*)ad_p + i); ad_q = ad_p; pidim = perm[(int)pidim]; } *((npy_intp*)ad_q + i) = tmp; } /* Follow the cycle again, marking it as done */ pidim = perm[idim]; while (pidim != idim) { NAD_INDEX(NIT_INDEX_AXISDATA(axisdata, pidim)) = 0; pidim = perm[(int)pidim]; } } NAD_INDEX(ad_i) = 0; } } /* Clear the identity perm flag */ NIT_ITFLAGS(iter) &= ~NPY_ITFLAG_IDENTPERM; } } /* * Calculates a dtype that all the types can be promoted to, using the * ufunc rules. If only_inputs is 1, it leaves any operands that * are not read from out of the calculation. */ static PyArray_Descr * npyiter_get_common_dtype(int nop, PyArrayObject **op, npyiter_opitflags *op_itflags, PyArray_Descr **op_dtype, PyArray_Descr **op_request_dtypes, int only_inputs) { int iop; npy_intp narrs = 0, ndtypes = 0; PyArrayObject *arrs[NPY_MAXARGS]; PyArray_Descr *dtypes[NPY_MAXARGS]; PyArray_Descr *ret; NPY_IT_DBG_PRINT("Iterator: Getting a common data type from operands\n"); for (iop = 0; iop < nop; ++iop) { if (op_dtype[iop] != NULL && (!only_inputs || (op_itflags[iop] & NPY_OP_ITFLAG_READ))) { /* If no dtype was requested and the op is a scalar, pass the op */ if ((op_request_dtypes == NULL || op_request_dtypes[iop] == NULL) && PyArray_NDIM(op[iop]) == 0) { arrs[narrs++] = op[iop]; } /* Otherwise just pass in the dtype */ else { dtypes[ndtypes++] = op_dtype[iop]; } } } if (narrs == 0) { npy_intp i; ret = dtypes[0]; for (i = 1; i < ndtypes; ++i) { if (ret != dtypes[i]) break; } if (i == ndtypes) { if (ndtypes == 1 || PyArray_ISNBO(ret->byteorder)) { Py_INCREF(ret); } else { ret = PyArray_DescrNewByteorder(ret, NPY_NATIVE); } } else { ret = PyArray_ResultType(narrs, arrs, ndtypes, dtypes); } } else { ret = PyArray_ResultType(narrs, arrs, ndtypes, dtypes); } return ret; } /* * Allocates a temporary array which can be used to replace op * in the iteration. Its dtype will be op_dtype. * * The result array has a memory ordering which matches the iterator, * which may or may not match that of op. The parameter 'shape' may be * NULL, in which case it is filled in from the iterator's shape. * * This function must be called before any axes are coalesced. */ static PyArrayObject * npyiter_new_temp_array(NpyIter *iter, PyTypeObject *subtype, npy_uint32 flags, npyiter_opitflags *op_itflags, int op_ndim, npy_intp *shape, PyArray_Descr *op_dtype, int *op_axes) { npy_uint32 itflags = NIT_ITFLAGS(iter); int idim, ndim = NIT_NDIM(iter); int nop = NIT_NOP(iter); npy_int8 *perm = NIT_PERM(iter); npy_intp new_shape[NPY_MAXDIMS], strides[NPY_MAXDIMS], stride = op_dtype->elsize; NpyIter_AxisData *axisdata; npy_intp sizeof_axisdata; npy_intp i; PyArrayObject *ret; /* * There is an interaction with array-dtypes here, which * generally works. Let's say you make an nditer with an * output dtype of a 2-double array. All-scalar inputs * will result in a 1-dimensional output with shape (2). * Everything still works out in the nditer, because the * new dimension is always added on the end, and it cares * about what happens at the beginning. */ /* If it's a scalar, don't need to check the axes */ if (op_ndim == 0) { Py_INCREF(op_dtype); ret = (PyArrayObject *)PyArray_NewFromDescr(subtype, op_dtype, 0, NULL, NULL, NULL, 0, NULL); return ret; } axisdata = NIT_AXISDATA(iter); sizeof_axisdata = NIT_AXISDATA_SIZEOF(itflags, ndim, nop); /* Initialize the strides to invalid values */ for (i = 0; i < NPY_MAXDIMS; ++i) { strides[i] = NPY_MAX_INTP; } if (op_axes != NULL) { for (idim = 0; idim < ndim; ++idim, NIT_ADVANCE_AXISDATA(axisdata, 1)) { npy_int8 p; /* Apply the perm to get the original axis */ p = perm[idim]; if (p < 0) { i = op_axes[ndim+p]; } else { i = op_axes[ndim-p-1]; } if (i >= 0) { NPY_IT_DBG_PRINT3("Iterator: Setting allocated stride %d " "for iterator dimension %d to %d\n", (int)i, (int)idim, (int)stride); strides[i] = stride; if (shape == NULL) { new_shape[i] = NAD_SHAPE(axisdata); stride *= new_shape[i]; if (i >= ndim) { PyErr_SetString(PyExc_ValueError, "automatically allocated output array " "specified with an inconsistent axis mapping"); return NULL; } } else { stride *= shape[i]; } } else { if (shape == NULL) { /* * If deleting this axis produces a reduction, but * reduction wasn't enabled, throw an error */ if (NAD_SHAPE(axisdata) != 1) { if (!(flags & NPY_ITER_REDUCE_OK)) { PyErr_SetString(PyExc_ValueError, "output requires a reduction, but " "reduction is not enabled"); return NULL; } if (!((*op_itflags) & NPY_OP_ITFLAG_READ)) { PyErr_SetString(PyExc_ValueError, "output requires a reduction, but " "is flagged as write-only, not read-write"); return NULL; } NPY_IT_DBG_PRINT("Iterator: Indicating that a " "reduction is occurring\n"); /* Indicate that a reduction is occurring */ NIT_ITFLAGS(iter) |= NPY_ITFLAG_REDUCE; (*op_itflags) |= NPY_OP_ITFLAG_REDUCE; } } } } } else { for (idim = 0; idim < ndim; ++idim, NIT_ADVANCE_AXISDATA(axisdata, 1)) { npy_int8 p; /* Apply the perm to get the original axis */ p = perm[idim]; if (p < 0) { i = op_ndim + p; } else { i = op_ndim - p - 1; } if (i >= 0) { NPY_IT_DBG_PRINT3("Iterator: Setting allocated stride %d " "for iterator dimension %d to %d\n", (int)i, (int)idim, (int)stride); strides[i] = stride; if (shape == NULL) { new_shape[i] = NAD_SHAPE(axisdata); stride *= new_shape[i]; } else { stride *= shape[i]; } } } } /* * If custom axes were specified, some dimensions may not have been used. * Add the REDUCE itflag if this creates a reduction situation. */ if (shape == NULL) { /* Ensure there are no dimension gaps in op_axes, and find op_ndim */ op_ndim = ndim; if (op_axes != NULL) { for (i = 0; i < ndim; ++i) { if (strides[i] == NPY_MAX_INTP) { if (op_ndim == ndim) { op_ndim = i; } } /* * If there's a gap in the array's dimensions, it's an error. * For example, op_axes of [0,2] for the automatically * allocated output. */ else if (op_ndim != ndim) { PyErr_SetString(PyExc_ValueError, "automatically allocated output array " "specified with an inconsistent axis mapping"); return NULL; } } } } else { for (i = 0; i < op_ndim; ++i) { if (strides[i] == NPY_MAX_INTP) { npy_intp factor, new_strides[NPY_MAXDIMS], itemsize; /* Fill in the missing strides in C order */ factor = 1; itemsize = op_dtype->elsize; for (i = op_ndim-1; i >= 0; --i) { if (strides[i] == NPY_MAX_INTP) { new_strides[i] = factor * itemsize; factor *= shape[i]; } } /* * Copy the missing strides, and multiply the existing strides * by the calculated factor. This way, the missing strides * are tighter together in memory, which is good for nested * loops. */ for (i = 0; i < op_ndim; ++i) { if (strides[i] == NPY_MAX_INTP) { strides[i] = new_strides[i]; } else { strides[i] *= factor; } } break; } } } /* If shape was NULL, set it to the shape we calculated */ if (shape == NULL) { shape = new_shape; } /* Allocate the temporary array */ Py_INCREF(op_dtype); ret = (PyArrayObject *)PyArray_NewFromDescr(subtype, op_dtype, op_ndim, shape, strides, NULL, 0, NULL); if (ret == NULL) { return NULL; } /* Make sure all the flags are good */ PyArray_UpdateFlags(ret, NPY_ARRAY_UPDATE_ALL); /* Double-check that the subtype didn't mess with the dimensions */ if (subtype != &PyArray_Type) { if (PyArray_NDIM(ret) != op_ndim || !PyArray_CompareLists(shape, PyArray_DIMS(ret), op_ndim)) { PyErr_SetString(PyExc_RuntimeError, "Iterator automatic output has an array subtype " "which changed the dimensions of the output"); Py_DECREF(ret); return NULL; } } return ret; } static int npyiter_allocate_arrays(NpyIter *iter, npy_uint32 flags, PyArray_Descr **op_dtype, PyTypeObject *subtype, npy_uint32 *op_flags, npyiter_opitflags *op_itflags, int **op_axes) { npy_uint32 itflags = NIT_ITFLAGS(iter); int idim, ndim = NIT_NDIM(iter); int iop, nop = NIT_NOP(iter); int check_writemasked_reductions = 0; NpyIter_BufferData *bufferdata = NULL; PyArrayObject **op = NIT_OPERANDS(iter); if (itflags & NPY_ITFLAG_BUFFER) { bufferdata = NIT_BUFFERDATA(iter); } for (iop = 0; iop < nop; ++iop) { /* * Check whether there are any WRITEMASKED REDUCE operands * which should be validated after all the strides are filled * in. */ if ((op_itflags[iop] & (NPY_OP_ITFLAG_WRITEMASKED | NPY_OP_ITFLAG_REDUCE)) == (NPY_OP_ITFLAG_WRITEMASKED | NPY_OP_ITFLAG_REDUCE)) { check_writemasked_reductions = 1; } /* NULL means an output the iterator should allocate */ if (op[iop] == NULL) { PyArrayObject *out; PyTypeObject *op_subtype; int ondim = ndim; /* Check whether the subtype was disabled */ op_subtype = (op_flags[iop] & NPY_ITER_NO_SUBTYPE) ? &PyArray_Type : subtype; /* Allocate the output array */ out = npyiter_new_temp_array(iter, op_subtype, flags, &op_itflags[iop], ondim, NULL, op_dtype[iop], op_axes ? op_axes[iop] : NULL); if (out == NULL) { return 0; } op[iop] = out; /* * Now we need to replace the pointers and strides with values * from the new array. */ npyiter_replace_axisdata(iter, iop, op[iop], ondim, PyArray_DATA(op[iop]), op_axes ? op_axes[iop] : NULL); /* New arrays are aligned and need no cast */ op_itflags[iop] |= NPY_OP_ITFLAG_ALIGNED; op_itflags[iop] &= ~NPY_OP_ITFLAG_CAST; } /* * If casting is required, the operand is read-only, and * it's an array scalar, make a copy whether or not the * copy flag is enabled. */ else if ((op_itflags[iop] & (NPY_OP_ITFLAG_CAST | NPY_OP_ITFLAG_READ | NPY_OP_ITFLAG_WRITE)) == (NPY_OP_ITFLAG_CAST | NPY_OP_ITFLAG_READ) && PyArray_NDIM(op[iop]) == 0) { PyArrayObject *temp; Py_INCREF(op_dtype[iop]); temp = (PyArrayObject *)PyArray_NewFromDescr( &PyArray_Type, op_dtype[iop], 0, NULL, NULL, NULL, 0, NULL); if (temp == NULL) { return 0; } if (PyArray_CopyInto(temp, op[iop]) != 0) { Py_DECREF(temp); return 0; } Py_DECREF(op[iop]); op[iop] = temp; /* * Now we need to replace the pointers and strides with values * from the temporary array. */ npyiter_replace_axisdata(iter, iop, op[iop], 0, PyArray_DATA(op[iop]), NULL); /* * New arrays are aligned need no cast, and in the case * of scalars, always have stride 0 so never need buffering */ op_itflags[iop] |= (NPY_OP_ITFLAG_ALIGNED | NPY_OP_ITFLAG_BUFNEVER); op_itflags[iop] &= ~NPY_OP_ITFLAG_CAST; if (itflags & NPY_ITFLAG_BUFFER) { NBF_STRIDES(bufferdata)[iop] = 0; } } /* If casting is required and permitted */ else if ((op_itflags[iop] & NPY_OP_ITFLAG_CAST) && (op_flags[iop] & (NPY_ITER_COPY|NPY_ITER_UPDATEIFCOPY))) { PyArrayObject *temp; int ondim = PyArray_NDIM(op[iop]); /* Allocate the temporary array, if possible */ temp = npyiter_new_temp_array(iter, &PyArray_Type, flags, &op_itflags[iop], ondim, PyArray_DIMS(op[iop]), op_dtype[iop], op_axes ? op_axes[iop] : NULL); if (temp == NULL) { return 0; } /* * If the data will be read, copy it into temp. * TODO: It might be possible to do a view into * op[iop]'s mask instead here. */ if (op_itflags[iop] & NPY_OP_ITFLAG_READ) { if (PyArray_CopyInto(temp, op[iop]) != 0) { Py_DECREF(temp); return 0; } } /* If the data will be written to, set UPDATEIFCOPY */ if (op_itflags[iop] & NPY_OP_ITFLAG_WRITE) { Py_INCREF(op[iop]); if (PyArray_SetUpdateIfCopyBase(temp, op[iop]) < 0) { Py_DECREF(temp); return 0; } } Py_DECREF(op[iop]); op[iop] = temp; /* * Now we need to replace the pointers and strides with values * from the temporary array. */ npyiter_replace_axisdata(iter, iop, op[iop], ondim, PyArray_DATA(op[iop]), op_axes ? op_axes[iop] : NULL); /* The temporary copy is aligned and needs no cast */ op_itflags[iop] |= NPY_OP_ITFLAG_ALIGNED; op_itflags[iop] &= ~NPY_OP_ITFLAG_CAST; } else { /* * Buffering must be enabled for casting/conversion if copy * wasn't specified. */ if ((op_itflags[iop] & NPY_OP_ITFLAG_CAST) && !(itflags & NPY_ITFLAG_BUFFER)) { PyErr_SetString(PyExc_TypeError, "Iterator operand required copying or buffering, " "but neither copying nor buffering was enabled"); return 0; } /* * If the operand is aligned, any buffering can use aligned * optimizations. */ if (PyArray_ISALIGNED(op[iop])) { op_itflags[iop] |= NPY_OP_ITFLAG_ALIGNED; } } /* Here we can finally check for contiguous iteration */ if (op_flags[iop] & NPY_ITER_CONTIG) { NpyIter_AxisData *axisdata = NIT_AXISDATA(iter); npy_intp stride = NAD_STRIDES(axisdata)[iop]; if (stride != op_dtype[iop]->elsize) { NPY_IT_DBG_PRINT("Iterator: Setting NPY_OP_ITFLAG_CAST " "because of NPY_ITER_CONTIG\n"); op_itflags[iop] |= NPY_OP_ITFLAG_CAST; if (!(itflags & NPY_ITFLAG_BUFFER)) { PyErr_SetString(PyExc_TypeError, "Iterator operand required buffering, " "to be contiguous as requested, but " "buffering is not enabled"); return 0; } } } /* * If no alignment, byte swap, or casting is needed, * the inner stride of this operand works for the whole * array, we can set NPY_OP_ITFLAG_BUFNEVER. */ if ((itflags & NPY_ITFLAG_BUFFER) && !(op_itflags[iop] & NPY_OP_ITFLAG_CAST)) { NpyIter_AxisData *axisdata = NIT_AXISDATA(iter); if (ndim <= 1) { op_itflags[iop] |= NPY_OP_ITFLAG_BUFNEVER; NBF_STRIDES(bufferdata)[iop] = NAD_STRIDES(axisdata)[iop]; } else if (PyArray_NDIM(op[iop]) > 0) { npy_intp stride, shape, innerstride = 0, innershape; npy_intp sizeof_axisdata = NIT_AXISDATA_SIZEOF(itflags, ndim, nop); /* Find stride of the first non-empty shape */ for (idim = 0; idim < ndim; ++idim) { innershape = NAD_SHAPE(axisdata); if (innershape != 1) { innerstride = NAD_STRIDES(axisdata)[iop]; break; } NIT_ADVANCE_AXISDATA(axisdata, 1); } ++idim; NIT_ADVANCE_AXISDATA(axisdata, 1); /* Check that everything could have coalesced together */ for (; idim < ndim; ++idim) { stride = NAD_STRIDES(axisdata)[iop]; shape = NAD_SHAPE(axisdata); if (shape != 1) { /* * If N times the inner stride doesn't equal this * stride, the multi-dimensionality is needed. */ if (innerstride*innershape != stride) { break; } else { innershape *= shape; } } NIT_ADVANCE_AXISDATA(axisdata, 1); } /* * If we looped all the way to the end, one stride works. * Set that stride, because it may not belong to the first * dimension. */ if (idim == ndim) { op_itflags[iop] |= NPY_OP_ITFLAG_BUFNEVER; NBF_STRIDES(bufferdata)[iop] = innerstride; } } } } if (check_writemasked_reductions) { for (iop = 0; iop < nop; ++iop) { /* * Check whether there are any WRITEMASKED REDUCE operands * which should be validated now that all the strides are filled * in. */ if ((op_itflags[iop] & (NPY_OP_ITFLAG_WRITEMASKED | NPY_OP_ITFLAG_REDUCE)) == (NPY_OP_ITFLAG_WRITEMASKED | NPY_OP_ITFLAG_REDUCE)) { /* * If the ARRAYMASK has 'bigger' dimensions * than this REDUCE WRITEMASKED operand, * the result would be more than one mask * value per reduction element, something which * is invalid. This function provides validation * for that. */ if (!check_mask_for_writemasked_reduction(iter, iop)) { return 0; } } } } return 1; } /* * The __array_priority__ attribute of the inputs determines * the subtype of any output arrays. This function finds the * subtype of the input array with highest priority. */ static void npyiter_get_priority_subtype(int nop, PyArrayObject **op, npyiter_opitflags *op_itflags, double *subtype_priority, PyTypeObject **subtype) { int iop; for (iop = 0; iop < nop; ++iop) { if (op[iop] != NULL && op_itflags[iop] & NPY_OP_ITFLAG_READ) { double priority = PyArray_GetPriority((PyObject *)op[iop], 0.0); if (priority > *subtype_priority) { *subtype_priority = priority; *subtype = Py_TYPE(op[iop]); } } } } static int npyiter_allocate_transfer_functions(NpyIter *iter) { npy_uint32 itflags = NIT_ITFLAGS(iter); /*int ndim = NIT_NDIM(iter);*/ int iop = 0, nop = NIT_NOP(iter); npy_intp i; npyiter_opitflags *op_itflags = NIT_OPITFLAGS(iter); NpyIter_BufferData *bufferdata = NIT_BUFFERDATA(iter); NpyIter_AxisData *axisdata = NIT_AXISDATA(iter); PyArrayObject **op = NIT_OPERANDS(iter); PyArray_Descr **op_dtype = NIT_DTYPES(iter); npy_intp *strides = NAD_STRIDES(axisdata), op_stride; PyArray_StridedUnaryOp **readtransferfn = NBF_READTRANSFERFN(bufferdata), **writetransferfn = NBF_WRITETRANSFERFN(bufferdata); NpyAuxData **readtransferdata = NBF_READTRANSFERDATA(bufferdata), **writetransferdata = NBF_WRITETRANSFERDATA(bufferdata); PyArray_StridedUnaryOp *stransfer = NULL; NpyAuxData *transferdata = NULL; int needs_api = 0; for (iop = 0; iop < nop; ++iop) { npyiter_opitflags flags = op_itflags[iop]; /* * Reduction operands may be buffered with a different stride, * so we must pass NPY_MAX_INTP to the transfer function factory. */ op_stride = (flags & NPY_OP_ITFLAG_REDUCE) ? NPY_MAX_INTP : strides[iop]; /* * If we have determined that a buffer may be needed, * allocate the appropriate transfer functions */ if (!(flags & NPY_OP_ITFLAG_BUFNEVER)) { if (flags & NPY_OP_ITFLAG_READ) { int move_references = 0; if (PyArray_GetDTypeTransferFunction( (flags & NPY_OP_ITFLAG_ALIGNED) != 0, op_stride, op_dtype[iop]->elsize, PyArray_DESCR(op[iop]), op_dtype[iop], move_references, &stransfer, &transferdata, &needs_api) != NPY_SUCCEED) { goto fail; } readtransferfn[iop] = stransfer; readtransferdata[iop] = transferdata; } else { readtransferfn[iop] = NULL; } if (flags & NPY_OP_ITFLAG_WRITE) { int move_references = 1; /* If the operand is WRITEMASKED, use a masked transfer fn */ if (flags & NPY_OP_ITFLAG_WRITEMASKED) { int maskop = NIT_MASKOP(iter); PyArray_Descr *mask_dtype = PyArray_DESCR(op[maskop]); /* * If the mask's stride is contiguous, use it, otherwise * the mask may or may not be buffered, so the stride * could be inconsistent. */ if (PyArray_GetMaskedDTypeTransferFunction( (flags & NPY_OP_ITFLAG_ALIGNED) != 0, op_dtype[iop]->elsize, op_stride, (strides[maskop] == mask_dtype->elsize) ? mask_dtype->elsize : NPY_MAX_INTP, op_dtype[iop], PyArray_DESCR(op[iop]), mask_dtype, move_references, (PyArray_MaskedStridedUnaryOp **)&stransfer, &transferdata, &needs_api) != NPY_SUCCEED) { goto fail; } } else { if (PyArray_GetDTypeTransferFunction( (flags & NPY_OP_ITFLAG_ALIGNED) != 0, op_dtype[iop]->elsize, op_stride, op_dtype[iop], PyArray_DESCR(op[iop]), move_references, &stransfer, &transferdata, &needs_api) != NPY_SUCCEED) { goto fail; } } writetransferfn[iop] = stransfer; writetransferdata[iop] = transferdata; } /* If no write back but there are references make a decref fn */ else if (PyDataType_REFCHK(op_dtype[iop])) { /* * By passing NULL to dst_type and setting move_references * to 1, we get back a function that just decrements the * src references. */ if (PyArray_GetDTypeTransferFunction( (flags & NPY_OP_ITFLAG_ALIGNED) != 0, op_dtype[iop]->elsize, 0, op_dtype[iop], NULL, 1, &stransfer, &transferdata, &needs_api) != NPY_SUCCEED) { goto fail; } writetransferfn[iop] = stransfer; writetransferdata[iop] = transferdata; } else { writetransferfn[iop] = NULL; } } else { readtransferfn[iop] = NULL; writetransferfn[iop] = NULL; } } /* If any of the dtype transfer functions needed the API, flag it */ if (needs_api) { NIT_ITFLAGS(iter) |= NPY_ITFLAG_NEEDSAPI; } return 1; fail: for (i = 0; i < iop; ++i) { if (readtransferdata[iop] != NULL) { NPY_AUXDATA_FREE(readtransferdata[iop]); readtransferdata[iop] = NULL; } if (writetransferdata[iop] != NULL) { NPY_AUXDATA_FREE(writetransferdata[iop]); writetransferdata[iop] = NULL; } } return 0; } #undef NPY_ITERATOR_IMPLEMENTATION_CODE numpy-1.8.2/numpy/core/src/multiarray/nditer_api.c0000664000175100017510000030120612370216242023367 0ustar vagrantvagrant00000000000000/* * This file implements most of the main API functions of NumPy's nditer. * This excludes functions specialized using the templating system. * * Copyright (c) 2010-2011 by Mark Wiebe (mwwiebe@gmail.com) * The Univerity of British Columbia * * Copyright (c) 2011 Enthought, Inc * * See LICENSE.txt for the license. */ #define NPY_NO_DEPRECATED_API NPY_API_VERSION /* 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 npyiter_checkreducesize(NpyIter *iter, npy_intp count, npy_intp *reduce_innersize, npy_intp *reduce_outerdim); /*NUMPY_API * Removes an axis from iteration. This requires that NPY_ITER_MULTI_INDEX * was set for iterator creation, and does not work if buffering is * enabled. This function also resets the iterator to its initial state. * * Returns NPY_SUCCEED or NPY_FAIL. */ NPY_NO_EXPORT int NpyIter_RemoveAxis(NpyIter *iter, int axis) { npy_uint32 itflags = NIT_ITFLAGS(iter); int idim, ndim = NIT_NDIM(iter); int iop, nop = NIT_NOP(iter); int xdim = 0; npy_int8 *perm = NIT_PERM(iter); NpyIter_AxisData *axisdata_del = NIT_AXISDATA(iter), *axisdata; npy_intp sizeof_axisdata = NIT_AXISDATA_SIZEOF(itflags, ndim, nop); npy_intp *baseoffsets = NIT_BASEOFFSETS(iter); char **resetdataptr = NIT_RESETDATAPTR(iter); if (!(itflags&NPY_ITFLAG_HASMULTIINDEX)) { PyErr_SetString(PyExc_RuntimeError, "Iterator RemoveAxis may only be called " "if a multi-index is being tracked"); return NPY_FAIL; } else if (itflags&NPY_ITFLAG_HASINDEX) { PyErr_SetString(PyExc_RuntimeError, "Iterator RemoveAxis may not be called on " "an index is being tracked"); return NPY_FAIL; } else if (itflags&NPY_ITFLAG_BUFFER) { PyErr_SetString(PyExc_RuntimeError, "Iterator RemoveAxis may not be called on " "a buffered iterator"); return NPY_FAIL; } else if (axis < 0 || axis >= ndim) { PyErr_SetString(PyExc_ValueError, "axis out of bounds in iterator RemoveAxis"); return NPY_FAIL; } /* Reverse axis, since the iterator treats them that way */ axis = ndim - 1 - axis; /* First find the axis in question */ for (idim = 0; idim < ndim; ++idim) { /* If this is it, and it's iterated forward, done */ if (perm[idim] == axis) { xdim = idim; break; } /* If this is it, but it's iterated backward, must reverse the axis */ else if (-1 - perm[idim] == axis) { npy_intp *strides = NAD_STRIDES(axisdata_del); npy_intp shape = NAD_SHAPE(axisdata_del), offset; xdim = idim; /* * Adjust baseoffsets and resetbaseptr back to the start of * this axis. */ for (iop = 0; iop < nop; ++iop) { offset = (shape-1)*strides[iop]; baseoffsets[iop] += offset; resetdataptr[iop] += offset; } break; } NIT_ADVANCE_AXISDATA(axisdata_del, 1); } if (idim == ndim) { PyErr_SetString(PyExc_RuntimeError, "internal error in iterator perm"); return NPY_FAIL; } if (NAD_SHAPE(axisdata_del) == 0) { PyErr_SetString(PyExc_ValueError, "cannot remove a zero-sized axis from an iterator"); return NPY_FAIL; } /* Adjust the permutation */ for (idim = 0; idim < ndim-1; ++idim) { npy_int8 p = (idim < xdim) ? perm[idim] : perm[idim+1]; if (p >= 0) { if (p > axis) { --p; } } else if (p <= 0) { if (p < -1-axis) { ++p; } } perm[idim] = p; } /* 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 */ if (ndim == 1) { npy_intp *strides = NAD_STRIDES(axisdata_del); NAD_SHAPE(axisdata_del) = 1; for (iop = 0; iop < nop; ++iop) { strides[iop] = 0; } NIT_ITFLAGS(iter) |= NPY_ITFLAG_ONEITERATION; } return NpyIter_Reset(iter, NULL); } /*NUMPY_API * Removes multi-index support from an iterator. * * Returns NPY_SUCCEED or NPY_FAIL. */ NPY_NO_EXPORT int NpyIter_RemoveMultiIndex(NpyIter *iter) { npy_uint32 itflags; /* Make sure the iterator is reset */ if (NpyIter_Reset(iter, NULL) != NPY_SUCCEED) { return NPY_FAIL; } 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); } return NPY_SUCCEED; } /*NUMPY_API * Removes the inner loop handling (so HasExternalLoop returns true) */ NPY_NO_EXPORT int NpyIter_EnableExternalLoop(NpyIter *iter) { npy_uint32 itflags = NIT_ITFLAGS(iter); /*int ndim = NIT_NDIM(iter);*/ int nop = NIT_NOP(iter); /* Check conditions under which this can be done */ if (itflags&(NPY_ITFLAG_HASINDEX|NPY_ITFLAG_HASMULTIINDEX)) { PyErr_SetString(PyExc_ValueError, "Iterator flag EXTERNAL_LOOP cannot be used " "if an index or multi-index is being tracked"); return NPY_FAIL; } if ((itflags&(NPY_ITFLAG_BUFFER|NPY_ITFLAG_RANGE|NPY_ITFLAG_EXLOOP)) == (NPY_ITFLAG_RANGE|NPY_ITFLAG_EXLOOP)) { PyErr_SetString(PyExc_ValueError, "Iterator flag EXTERNAL_LOOP cannot be used " "with ranged iteration unless buffering is also enabled"); return NPY_FAIL; } /* Set the flag */ if (!(itflags&NPY_ITFLAG_EXLOOP)) { itflags |= NPY_ITFLAG_EXLOOP; NIT_ITFLAGS(iter) = itflags; /* * Check whether we can apply the single iteration * optimization to the iternext function. */ if (!(itflags&NPY_ITFLAG_BUFFER)) { NpyIter_AxisData *axisdata = NIT_AXISDATA(iter); if (NIT_ITERSIZE(iter) == NAD_SHAPE(axisdata)) { NIT_ITFLAGS(iter) |= NPY_ITFLAG_ONEITERATION; } } } /* Reset the iterator */ return NpyIter_Reset(iter, NULL); } /*NUMPY_API * Resets the iterator to its initial state * * If errmsg is non-NULL, it should point to a variable which will * receive the error message, and no Python exception will be set. * This is so that the function can be called from code not holding * the GIL. */ NPY_NO_EXPORT int NpyIter_Reset(NpyIter *iter, char **errmsg) { npy_uint32 itflags = NIT_ITFLAGS(iter); /*int ndim = NIT_NDIM(iter);*/ int nop = NIT_NOP(iter); if (itflags&NPY_ITFLAG_BUFFER) { NpyIter_BufferData *bufferdata; /* If buffer allocation was delayed, do it now */ if (itflags&NPY_ITFLAG_DELAYBUF) { if (!npyiter_allocate_buffers(iter, errmsg)) { return NPY_FAIL; } NIT_ITFLAGS(iter) &= ~NPY_ITFLAG_DELAYBUF; } else { /* * If the iterindex is already right, no need to * do anything */ bufferdata = NIT_BUFFERDATA(iter); if (NIT_ITERINDEX(iter) == NIT_ITERSTART(iter) && NBF_BUFITEREND(bufferdata) <= NIT_ITEREND(iter) && NBF_SIZE(bufferdata) > 0) { return NPY_SUCCEED; } /* Copy any data from the buffers back to the arrays */ npyiter_copy_from_buffers(iter); } } npyiter_goto_iterindex(iter, NIT_ITERSTART(iter)); if (itflags&NPY_ITFLAG_BUFFER) { /* Prepare the next buffers and set iterend/size */ npyiter_copy_to_buffers(iter, NULL); } return NPY_SUCCEED; } /*NUMPY_API * Resets the iterator to its initial state, with new base data pointers. * This function requires great caution. * * If errmsg is non-NULL, it should point to a variable which will * receive the error message, and no Python exception will be set. * This is so that the function can be called from code not holding * the GIL. */ NPY_NO_EXPORT int NpyIter_ResetBasePointers(NpyIter *iter, char **baseptrs, char **errmsg) { npy_uint32 itflags = NIT_ITFLAGS(iter); /*int ndim = NIT_NDIM(iter);*/ int iop, nop = NIT_NOP(iter); char **resetdataptr = NIT_RESETDATAPTR(iter); npy_intp *baseoffsets = NIT_BASEOFFSETS(iter); if (itflags&NPY_ITFLAG_BUFFER) { /* If buffer allocation was delayed, do it now */ if (itflags&NPY_ITFLAG_DELAYBUF) { if (!npyiter_allocate_buffers(iter, errmsg)) { return NPY_FAIL; } NIT_ITFLAGS(iter) &= ~NPY_ITFLAG_DELAYBUF; } else { /* Copy any data from the buffers back to the arrays */ npyiter_copy_from_buffers(iter); } } /* The new data pointers for resetting */ for (iop = 0; iop < nop; ++iop) { resetdataptr[iop] = baseptrs[iop] + baseoffsets[iop]; } npyiter_goto_iterindex(iter, NIT_ITERSTART(iter)); if (itflags&NPY_ITFLAG_BUFFER) { /* Prepare the next buffers and set iterend/size */ npyiter_copy_to_buffers(iter, NULL); } return NPY_SUCCEED; } /*NUMPY_API * Resets the iterator to a new iterator index range * * If errmsg is non-NULL, it should point to a variable which will * receive the error message, and no Python exception will be set. * This is so that the function can be called from code not holding * the GIL. */ NPY_NO_EXPORT int NpyIter_ResetToIterIndexRange(NpyIter *iter, npy_intp istart, npy_intp iend, char **errmsg) { npy_uint32 itflags = NIT_ITFLAGS(iter); /*int ndim = NIT_NDIM(iter);*/ /*int nop = NIT_NOP(iter);*/ if (!(itflags&NPY_ITFLAG_RANGE)) { if (errmsg == NULL) { PyErr_SetString(PyExc_ValueError, "Cannot call ResetToIterIndexRange on an iterator without " "requesting ranged iteration support in the constructor"); } else { *errmsg = "Cannot call ResetToIterIndexRange on an iterator " "without requesting ranged iteration support in the " "constructor"; } return NPY_FAIL; } 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 " "ResetToIterIndexRange", (int)istart, (int)iend); } else { *errmsg = "Out-of-bounds range passed to ResetToIterIndexRange"; } return NPY_FAIL; } else if (iend < istart) { if (errmsg == NULL) { PyErr_Format(PyExc_ValueError, "Invalid range [%d, %d) passed to ResetToIterIndexRange", (int)istart, (int)iend); } else { *errmsg = "Invalid range passed to ResetToIterIndexRange"; } return NPY_FAIL; } NIT_ITERSTART(iter) = istart; NIT_ITEREND(iter) = iend; return NpyIter_Reset(iter, errmsg); } /*NUMPY_API * Sets the iterator to the specified multi-index, which must have the * correct number of entries for 'ndim'. It is only valid * when NPY_ITER_MULTI_INDEX was passed to the constructor. This operation * fails if the multi-index is out of bounds. * * Returns NPY_SUCCEED on success, NPY_FAIL on failure. */ NPY_NO_EXPORT int NpyIter_GotoMultiIndex(NpyIter *iter, npy_intp *multi_index) { npy_uint32 itflags = NIT_ITFLAGS(iter); int idim, ndim = NIT_NDIM(iter); int nop = NIT_NOP(iter); npy_intp iterindex, factor; NpyIter_AxisData *axisdata; npy_intp sizeof_axisdata; npy_int8 *perm; if (!(itflags&NPY_ITFLAG_HASMULTIINDEX)) { PyErr_SetString(PyExc_ValueError, "Cannot call GotoMultiIndex on an iterator without " "requesting a multi-index in the constructor"); return NPY_FAIL; } if (itflags&NPY_ITFLAG_BUFFER) { PyErr_SetString(PyExc_ValueError, "Cannot call GotoMultiIndex on an iterator which " "is buffered"); return NPY_FAIL; } if (itflags&NPY_ITFLAG_EXLOOP) { PyErr_SetString(PyExc_ValueError, "Cannot call GotoMultiIndex on an iterator which " "has the flag EXTERNAL_LOOP"); return NPY_FAIL; } perm = NIT_PERM(iter); axisdata = NIT_AXISDATA(iter); sizeof_axisdata = NIT_AXISDATA_SIZEOF(itflags, ndim, nop); /* Compute the iterindex corresponding to the multi-index */ iterindex = 0; factor = 1; for (idim = 0; idim < ndim; ++idim) { npy_int8 p = perm[idim]; npy_intp i, shape; shape = NAD_SHAPE(axisdata); if (p < 0) { /* If the perm entry is negative, reverse the index */ i = shape - multi_index[ndim+p] - 1; } else { i = multi_index[ndim-p-1]; } /* Bounds-check this index */ if (i >= 0 && i < shape) { iterindex += factor * i; factor *= shape; } else { PyErr_SetString(PyExc_IndexError, "Iterator GotoMultiIndex called with an out-of-bounds " "multi-index"); return NPY_FAIL; } NIT_ADVANCE_AXISDATA(axisdata, 1); } 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"); return NPY_FAIL; } npyiter_goto_iterindex(iter, iterindex); return NPY_SUCCEED; } /*NUMPY_API * If the iterator is tracking an index, sets the iterator * to the specified index. * * Returns NPY_SUCCEED on success, NPY_FAIL on failure. */ NPY_NO_EXPORT int NpyIter_GotoIndex(NpyIter *iter, npy_intp flat_index) { npy_uint32 itflags = NIT_ITFLAGS(iter); int idim, ndim = NIT_NDIM(iter); int nop = NIT_NOP(iter); npy_intp iterindex, factor; NpyIter_AxisData *axisdata; npy_intp sizeof_axisdata; if (!(itflags&NPY_ITFLAG_HASINDEX)) { PyErr_SetString(PyExc_ValueError, "Cannot call GotoIndex on an iterator without " "requesting a C or Fortran index in the constructor"); return NPY_FAIL; } if (itflags&NPY_ITFLAG_BUFFER) { PyErr_SetString(PyExc_ValueError, "Cannot call GotoIndex on an iterator which " "is buffered"); return NPY_FAIL; } if (itflags&NPY_ITFLAG_EXLOOP) { PyErr_SetString(PyExc_ValueError, "Cannot call GotoIndex on an iterator which " "has the flag EXTERNAL_LOOP"); return NPY_FAIL; } if (flat_index < 0 || flat_index >= NIT_ITERSIZE(iter)) { PyErr_SetString(PyExc_IndexError, "Iterator GotoIndex called with an out-of-bounds " "index"); return NPY_FAIL; } axisdata = NIT_AXISDATA(iter); sizeof_axisdata = NIT_AXISDATA_SIZEOF(itflags, ndim, nop); /* Compute the iterindex corresponding to the flat_index */ iterindex = 0; factor = 1; for (idim = 0; idim < ndim; ++idim) { npy_intp i, shape, iterstride; iterstride = NAD_STRIDES(axisdata)[nop]; shape = NAD_SHAPE(axisdata); /* Extract the index from the flat_index */ if (iterstride == 0) { i = 0; } else if (iterstride < 0) { i = shape - (flat_index/(-iterstride))%shape - 1; } else { i = (flat_index/iterstride)%shape; } /* Add its contribution to iterindex */ iterindex += factor * i; factor *= shape; NIT_ADVANCE_AXISDATA(axisdata, 1); } if (iterindex < NIT_ITERSTART(iter) || iterindex >= NIT_ITEREND(iter)) { PyErr_SetString(PyExc_IndexError, "Iterator GotoIndex called with an index outside the " "restricted iteration range."); return NPY_FAIL; } npyiter_goto_iterindex(iter, iterindex); return NPY_SUCCEED; } /*NUMPY_API * Sets the iterator position to the specified iterindex, * which matches the iteration order of the iterator. * * Returns NPY_SUCCEED on success, NPY_FAIL on failure. */ NPY_NO_EXPORT int NpyIter_GotoIterIndex(NpyIter *iter, npy_intp iterindex) { npy_uint32 itflags = NIT_ITFLAGS(iter); /*int ndim = NIT_NDIM(iter);*/ int iop, nop = NIT_NOP(iter); if (itflags&NPY_ITFLAG_EXLOOP) { PyErr_SetString(PyExc_ValueError, "Cannot call GotoIterIndex on an iterator which " "has the flag EXTERNAL_LOOP"); return NPY_FAIL; } 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."); return NPY_FAIL; } if (itflags&NPY_ITFLAG_BUFFER) { NpyIter_BufferData *bufferdata = NIT_BUFFERDATA(iter); npy_intp bufiterend, size; size = NBF_SIZE(bufferdata); bufiterend = NBF_BUFITEREND(bufferdata); /* Check if the new iterindex is already within the buffer */ if (!(itflags&NPY_ITFLAG_REDUCE) && iterindex < bufiterend && iterindex >= bufiterend - size) { npy_intp *strides, delta; char **ptrs; strides = NBF_STRIDES(bufferdata); ptrs = NBF_PTRS(bufferdata); delta = iterindex - NIT_ITERINDEX(iter); for (iop = 0; iop < nop; ++iop) { ptrs[iop] += delta * strides[iop]; } NIT_ITERINDEX(iter) = iterindex; } /* Start the buffer at the provided iterindex */ else { /* Write back to the arrays */ npyiter_copy_from_buffers(iter); npyiter_goto_iterindex(iter, iterindex); /* Prepare the next buffers and set iterend/size */ npyiter_copy_to_buffers(iter, NULL); } } else { npyiter_goto_iterindex(iter, iterindex); } return NPY_SUCCEED; } /*NUMPY_API * Gets the current iteration index */ NPY_NO_EXPORT npy_intp NpyIter_GetIterIndex(NpyIter *iter) { npy_uint32 itflags = NIT_ITFLAGS(iter); int idim, ndim = NIT_NDIM(iter); int nop = NIT_NOP(iter); /* iterindex is only used if NPY_ITER_RANGED or NPY_ITER_BUFFERED was set */ if (itflags&(NPY_ITFLAG_RANGE|NPY_ITFLAG_BUFFER)) { return NIT_ITERINDEX(iter); } else { npy_intp iterindex; NpyIter_AxisData *axisdata; npy_intp sizeof_axisdata; iterindex = 0; if (ndim == 0) { return 0; } sizeof_axisdata = NIT_AXISDATA_SIZEOF(itflags, ndim, nop); axisdata = NIT_INDEX_AXISDATA(NIT_AXISDATA(iter), ndim-1); for (idim = ndim-2; idim >= 0; --idim) { iterindex += NAD_INDEX(axisdata); NIT_ADVANCE_AXISDATA(axisdata, -1); iterindex *= NAD_SHAPE(axisdata); } iterindex += NAD_INDEX(axisdata); return iterindex; } } /*NUMPY_API * Whether the buffer allocation is being delayed */ NPY_NO_EXPORT npy_bool NpyIter_HasDelayedBufAlloc(NpyIter *iter) { return (NIT_ITFLAGS(iter)&NPY_ITFLAG_DELAYBUF) != 0; } /*NUMPY_API * Whether the iterator handles the inner loop */ NPY_NO_EXPORT npy_bool NpyIter_HasExternalLoop(NpyIter *iter) { return (NIT_ITFLAGS(iter)&NPY_ITFLAG_EXLOOP) != 0; } /*NUMPY_API * Whether the iterator is tracking a multi-index */ NPY_NO_EXPORT npy_bool NpyIter_HasMultiIndex(NpyIter *iter) { return (NIT_ITFLAGS(iter)&NPY_ITFLAG_HASMULTIINDEX) != 0; } /*NUMPY_API * Whether the iterator is tracking an index */ NPY_NO_EXPORT npy_bool NpyIter_HasIndex(NpyIter *iter) { return (NIT_ITFLAGS(iter)&NPY_ITFLAG_HASINDEX) != 0; } /*NUMPY_API * Checks to see whether this is the first time the elements * of the specified reduction operand which the iterator points at are * being seen for the first time. The function returns * a reasonable answer for reduction operands and when buffering is * disabled. The answer may be incorrect for buffered non-reduction * operands. * * This function is intended to be used in EXTERNAL_LOOP mode only, * and will produce some wrong answers when that mode is not enabled. * * If this function returns true, the caller should also * check the inner loop stride of the operand, because if * that stride is 0, then only the first element of the innermost * external loop is being visited for the first time. * * WARNING: For performance reasons, 'iop' is not bounds-checked, * it is not confirmed that 'iop' is actually a reduction * operand, and it is not confirmed that EXTERNAL_LOOP * mode is enabled. These checks are the responsibility of * the caller, and should be done outside of any inner loops. */ NPY_NO_EXPORT npy_bool NpyIter_IsFirstVisit(NpyIter *iter, int iop) { npy_uint32 itflags = NIT_ITFLAGS(iter); int idim, ndim = NIT_NDIM(iter); int nop = NIT_NOP(iter); NpyIter_AxisData *axisdata; npy_intp sizeof_axisdata; sizeof_axisdata = NIT_AXISDATA_SIZEOF(itflags, ndim, nop); axisdata = NIT_AXISDATA(iter); for (idim = 0; idim < ndim; ++idim) { npy_intp coord = NAD_INDEX(axisdata); npy_intp stride = NAD_STRIDES(axisdata)[iop]; /* * If this is a reduction dimension and the coordinate * is not at the start, it's definitely not the first visit */ if (stride == 0 && coord != 0) { return 0; } NIT_ADVANCE_AXISDATA(axisdata, 1); } /* * In reduction buffering mode, there's a double loop being * tracked in the buffer part of the iterator data structure. * We only need to check the outer level of this two-level loop, * because of the requirement that EXTERNAL_LOOP be enabled. */ if (itflags&NPY_ITFLAG_BUFFER) { NpyIter_BufferData *bufferdata = NIT_BUFFERDATA(iter); /* The outer reduce loop */ if (NBF_REDUCE_POS(bufferdata) != 0 && NBF_REDUCE_OUTERSTRIDES(bufferdata)[iop] == 0) { return 0; } } return 1; } /*NUMPY_API * Whether the iteration could be done with no buffering. */ NPY_NO_EXPORT npy_bool NpyIter_RequiresBuffering(NpyIter *iter) { npy_uint32 itflags = NIT_ITFLAGS(iter); /*int ndim = NIT_NDIM(iter);*/ int iop, nop = NIT_NOP(iter); npyiter_opitflags *op_itflags; if (!(itflags&NPY_ITFLAG_BUFFER)) { return 0; } op_itflags = NIT_OPITFLAGS(iter); /* If any operand requires a cast, buffering is mandatory */ for (iop = 0; iop < nop; ++iop) { if (op_itflags[iop]&NPY_OP_ITFLAG_CAST) { return 1; } } return 0; } /*NUMPY_API * Whether the iteration loop, and in particular the iternext() * function, needs API access. If this is true, the GIL must * be retained while iterating. */ NPY_NO_EXPORT npy_bool NpyIter_IterationNeedsAPI(NpyIter *iter) { return (NIT_ITFLAGS(iter)&NPY_ITFLAG_NEEDSAPI) != 0; } /*NUMPY_API * Gets the number of dimensions being iterated */ NPY_NO_EXPORT int NpyIter_GetNDim(NpyIter *iter) { return NIT_NDIM(iter); } /*NUMPY_API * Gets the number of operands being iterated */ NPY_NO_EXPORT int NpyIter_GetNOp(NpyIter *iter) { return NIT_NOP(iter); } /*NUMPY_API * Gets the number of elements being iterated */ NPY_NO_EXPORT npy_intp NpyIter_GetIterSize(NpyIter *iter) { return NIT_ITERSIZE(iter); } /*NUMPY_API * Whether the iterator is buffered */ NPY_NO_EXPORT npy_bool NpyIter_IsBuffered(NpyIter *iter) { return (NIT_ITFLAGS(iter)&NPY_ITFLAG_BUFFER) != 0; } /*NUMPY_API * Whether the inner loop can grow if buffering is unneeded */ NPY_NO_EXPORT npy_bool NpyIter_IsGrowInner(NpyIter *iter) { return (NIT_ITFLAGS(iter)&NPY_ITFLAG_GROWINNER) != 0; } /*NUMPY_API * Gets the size of the buffer, or 0 if buffering is not enabled */ NPY_NO_EXPORT npy_intp NpyIter_GetBufferSize(NpyIter *iter) { npy_uint32 itflags = NIT_ITFLAGS(iter); /*int ndim = NIT_NDIM(iter);*/ int nop = NIT_NOP(iter); if (itflags&NPY_ITFLAG_BUFFER) { NpyIter_BufferData *bufferdata = NIT_BUFFERDATA(iter); return NBF_BUFFERSIZE(bufferdata); } else { return 0; } } /*NUMPY_API * Gets the range of iteration indices being iterated */ NPY_NO_EXPORT void NpyIter_GetIterIndexRange(NpyIter *iter, npy_intp *istart, npy_intp *iend) { *istart = NIT_ITERSTART(iter); *iend = NIT_ITEREND(iter); } /*NUMPY_API * Gets the broadcast shape if a multi-index is being tracked by the iterator, * otherwise gets the shape of the iteration as Fortran-order * (fastest-changing index first). * * The reason Fortran-order is returned when a multi-index * is not enabled is that this is providing a direct view into how * the iterator traverses the n-dimensional space. The iterator organizes * its memory from fastest index to slowest index, and when * a multi-index is enabled, it uses a permutation to recover the original * order. * * Returns NPY_SUCCEED or NPY_FAIL. */ NPY_NO_EXPORT int NpyIter_GetShape(NpyIter *iter, npy_intp *outshape) { npy_uint32 itflags = NIT_ITFLAGS(iter); int ndim = NIT_NDIM(iter); int nop = NIT_NOP(iter); int idim, sizeof_axisdata; NpyIter_AxisData *axisdata; npy_int8 *perm; axisdata = NIT_AXISDATA(iter); sizeof_axisdata = NIT_AXISDATA_SIZEOF(itflags, ndim, nop); if (itflags&NPY_ITFLAG_HASMULTIINDEX) { perm = NIT_PERM(iter); for(idim = 0; idim < ndim; ++idim) { npy_int8 p = perm[idim]; if (p < 0) { outshape[ndim+p] = NAD_SHAPE(axisdata); } else { outshape[ndim-p-1] = NAD_SHAPE(axisdata); } NIT_ADVANCE_AXISDATA(axisdata, 1); } } else { for(idim = 0; idim < ndim; ++idim) { outshape[idim] = NAD_SHAPE(axisdata); NIT_ADVANCE_AXISDATA(axisdata, 1); } } return NPY_SUCCEED; } /*NUMPY_API * Builds a set of strides which are the same as the strides of an * output array created using the NPY_ITER_ALLOCATE flag, where NULL * was passed for op_axes. This is for data packed contiguously, * but not necessarily in C or Fortran order. This should be used * together with NpyIter_GetShape and NpyIter_GetNDim. * * A use case for this function is to match the shape and layout of * the iterator and tack on one or more dimensions. For example, * in order to generate a vector per input value for a numerical gradient, * you pass in ndim*itemsize for itemsize, then add another dimension to * the end with size ndim and stride itemsize. To do the Hessian matrix, * you do the same thing but add two dimensions, or take advantage of * the symmetry and pack it into 1 dimension with a particular encoding. * * This function may only be called if the iterator is tracking a multi-index * and if NPY_ITER_DONT_NEGATE_STRIDES was used to prevent an axis from * being iterated in reverse order. * * If an array is created with this method, simply adding 'itemsize' * for each iteration will traverse the new array matching the * iterator. * * Returns NPY_SUCCEED or NPY_FAIL. */ NPY_NO_EXPORT int NpyIter_CreateCompatibleStrides(NpyIter *iter, npy_intp itemsize, npy_intp *outstrides) { npy_uint32 itflags = NIT_ITFLAGS(iter); int idim, ndim = NIT_NDIM(iter); int nop = NIT_NOP(iter); npy_intp sizeof_axisdata; NpyIter_AxisData *axisdata; npy_int8 *perm; if (!(itflags&NPY_ITFLAG_HASMULTIINDEX)) { PyErr_SetString(PyExc_RuntimeError, "Iterator CreateCompatibleStrides may only be called " "if a multi-index is being tracked"); return NPY_FAIL; } axisdata = NIT_AXISDATA(iter); sizeof_axisdata = NIT_AXISDATA_SIZEOF(itflags, ndim, nop); perm = NIT_PERM(iter); for(idim = 0; idim < ndim; ++idim) { npy_int8 p = perm[idim]; if (p < 0) { PyErr_SetString(PyExc_RuntimeError, "Iterator CreateCompatibleStrides may only be called " "if DONT_NEGATE_STRIDES was used to prevent reverse " "iteration of an axis"); return NPY_FAIL; } else { outstrides[ndim-p-1] = itemsize; } itemsize *= NAD_SHAPE(axisdata); NIT_ADVANCE_AXISDATA(axisdata, 1); } return NPY_SUCCEED; } /*NUMPY_API * Get the array of data pointers (1 per object being iterated) * * This function may be safely called without holding the Python GIL. */ NPY_NO_EXPORT char ** NpyIter_GetDataPtrArray(NpyIter *iter) { npy_uint32 itflags = NIT_ITFLAGS(iter); /*int ndim = NIT_NDIM(iter);*/ int nop = NIT_NOP(iter); if (itflags&NPY_ITFLAG_BUFFER) { NpyIter_BufferData *bufferdata = NIT_BUFFERDATA(iter); return NBF_PTRS(bufferdata); } else { NpyIter_AxisData *axisdata = NIT_AXISDATA(iter); return NAD_PTRS(axisdata); } } /*NUMPY_API * Get the array of data pointers (1 per object being iterated), * directly into the arrays (never pointing to a buffer), for starting * unbuffered iteration. This always returns the addresses for the * iterator position as reset to iterator index 0. * * These pointers are different from the pointers accepted by * NpyIter_ResetBasePointers, because the direction along some * axes may have been reversed, requiring base offsets. * * This function may be safely called without holding the Python GIL. */ NPY_NO_EXPORT char ** NpyIter_GetInitialDataPtrArray(NpyIter *iter) { /*npy_uint32 itflags = NIT_ITFLAGS(iter);*/ /*int ndim = NIT_NDIM(iter);*/ int nop = NIT_NOP(iter); return NIT_RESETDATAPTR(iter); } /*NUMPY_API * Get the array of data type pointers (1 per object being iterated) */ NPY_NO_EXPORT PyArray_Descr ** NpyIter_GetDescrArray(NpyIter *iter) { /*npy_uint32 itflags = NIT_ITFLAGS(iter);*/ /*int ndim = NIT_NDIM(iter);*/ /*int nop = NIT_NOP(iter);*/ return NIT_DTYPES(iter); } /*NUMPY_API * Get the array of objects being iterated */ NPY_NO_EXPORT PyArrayObject ** NpyIter_GetOperandArray(NpyIter *iter) { /*npy_uint32 itflags = NIT_ITFLAGS(iter);*/ /*int ndim = NIT_NDIM(iter);*/ int nop = NIT_NOP(iter); return NIT_OPERANDS(iter); } /*NUMPY_API * Returns a view to the i-th object with the iterator's internal axes */ NPY_NO_EXPORT PyArrayObject * NpyIter_GetIterView(NpyIter *iter, npy_intp i) { npy_uint32 itflags = NIT_ITFLAGS(iter); int idim, ndim = NIT_NDIM(iter); int nop = NIT_NOP(iter); npy_intp shape[NPY_MAXDIMS], strides[NPY_MAXDIMS]; PyArrayObject *obj, *view; PyArray_Descr *dtype; char *dataptr; NpyIter_AxisData *axisdata; npy_intp sizeof_axisdata; int writeable; if (i < 0) { PyErr_SetString(PyExc_IndexError, "index provided for an iterator view was out of bounds"); return NULL; } /* Don't provide views if buffering is enabled */ if (itflags&NPY_ITFLAG_BUFFER) { PyErr_SetString(PyExc_ValueError, "cannot provide an iterator view when buffering is enabled"); return NULL; } obj = NIT_OPERANDS(iter)[i]; dtype = PyArray_DESCR(obj); writeable = NIT_OPITFLAGS(iter)[i]&NPY_OP_ITFLAG_WRITE; dataptr = NIT_RESETDATAPTR(iter)[i]; axisdata = NIT_AXISDATA(iter); sizeof_axisdata = NIT_AXISDATA_SIZEOF(itflags, ndim, nop); /* Retrieve the shape and strides from the axisdata */ for (idim = 0; idim < ndim; ++idim) { shape[ndim-idim-1] = NAD_SHAPE(axisdata); strides[ndim-idim-1] = NAD_STRIDES(axisdata)[i]; NIT_ADVANCE_AXISDATA(axisdata, 1); } Py_INCREF(dtype); view = (PyArrayObject *)PyArray_NewFromDescr(&PyArray_Type, dtype, ndim, shape, strides, dataptr, writeable ? NPY_ARRAY_WRITEABLE : 0, NULL); if (view == NULL) { return NULL; } /* Tell the view who owns the data */ Py_INCREF(obj); if (PyArray_SetBaseObject(view, (PyObject *)obj) < 0) { Py_DECREF(view); return NULL; } /* Make sure all the flags are good */ PyArray_UpdateFlags(view, NPY_ARRAY_UPDATE_ALL); return view; } /*NUMPY_API * Get a pointer to the index, if it is being tracked */ NPY_NO_EXPORT npy_intp * NpyIter_GetIndexPtr(NpyIter *iter) { npy_uint32 itflags = NIT_ITFLAGS(iter); /*int ndim = NIT_NDIM(iter);*/ int nop = NIT_NOP(iter); NpyIter_AxisData *axisdata = NIT_AXISDATA(iter); if (itflags&NPY_ITFLAG_HASINDEX) { /* The index is just after the data pointers */ return (npy_intp*)NAD_PTRS(axisdata) + nop; } else { return NULL; } } /*NUMPY_API * Gets an array of read flags (1 per object being iterated) */ NPY_NO_EXPORT void NpyIter_GetReadFlags(NpyIter *iter, char *outreadflags) { /*npy_uint32 itflags = NIT_ITFLAGS(iter);*/ /*int ndim = NIT_NDIM(iter);*/ int iop, nop = NIT_NOP(iter); npyiter_opitflags *op_itflags = NIT_OPITFLAGS(iter); for (iop = 0; iop < nop; ++iop) { outreadflags[iop] = (op_itflags[iop]&NPY_OP_ITFLAG_READ) != 0; } } /*NUMPY_API * Gets an array of write flags (1 per object being iterated) */ NPY_NO_EXPORT void NpyIter_GetWriteFlags(NpyIter *iter, char *outwriteflags) { /*npy_uint32 itflags = NIT_ITFLAGS(iter);*/ /*int ndim = NIT_NDIM(iter);*/ int iop, nop = NIT_NOP(iter); npyiter_opitflags *op_itflags = NIT_OPITFLAGS(iter); for (iop = 0; iop < nop; ++iop) { outwriteflags[iop] = (op_itflags[iop]&NPY_OP_ITFLAG_WRITE) != 0; } } /*NUMPY_API * Get the array of strides for the inner loop (when HasExternalLoop is true) * * This function may be safely called without holding the Python GIL. */ NPY_NO_EXPORT npy_intp * NpyIter_GetInnerStrideArray(NpyIter *iter) { npy_uint32 itflags = NIT_ITFLAGS(iter); /*int ndim = NIT_NDIM(iter);*/ int nop = NIT_NOP(iter); if (itflags&NPY_ITFLAG_BUFFER) { NpyIter_BufferData *data = NIT_BUFFERDATA(iter); return NBF_STRIDES(data); } else { NpyIter_AxisData *axisdata = NIT_AXISDATA(iter); return NAD_STRIDES(axisdata); } } /*NUMPY_API * Gets the array of strides for the specified axis. * If the iterator is tracking a multi-index, gets the strides * for the axis specified, otherwise gets the strides for * the iteration axis as Fortran order (fastest-changing axis first). * * Returns NULL if an error occurs. */ NPY_NO_EXPORT npy_intp * NpyIter_GetAxisStrideArray(NpyIter *iter, int axis) { npy_uint32 itflags = NIT_ITFLAGS(iter); int idim, ndim = NIT_NDIM(iter); int nop = NIT_NOP(iter); npy_int8 *perm = NIT_PERM(iter); NpyIter_AxisData *axisdata = NIT_AXISDATA(iter); npy_intp sizeof_axisdata = NIT_AXISDATA_SIZEOF(itflags, ndim, nop); if (axis < 0 || axis >= ndim) { PyErr_SetString(PyExc_ValueError, "axis out of bounds in iterator GetStrideAxisArray"); return NULL; } if (itflags&NPY_ITFLAG_HASMULTIINDEX) { /* Reverse axis, since the iterator treats them that way */ axis = ndim-1-axis; /* First find the axis in question */ for (idim = 0; idim < ndim; ++idim, NIT_ADVANCE_AXISDATA(axisdata, 1)) { if (perm[idim] == axis || -1 - perm[idim] == axis) { return NAD_STRIDES(axisdata); } } } else { return NAD_STRIDES(NIT_INDEX_AXISDATA(axisdata, axis)); } PyErr_SetString(PyExc_RuntimeError, "internal error in iterator perm"); return NULL; } /*NUMPY_API * Get an array of strides which are fixed. Any strides which may * change during iteration receive the value NPY_MAX_INTP. Once * the iterator is ready to iterate, call this to get the strides * which will always be fixed in the inner loop, then choose optimized * inner loop functions which take advantage of those fixed strides. * * This function may be safely called without holding the Python GIL. */ NPY_NO_EXPORT void NpyIter_GetInnerFixedStrideArray(NpyIter *iter, npy_intp *out_strides) { npy_uint32 itflags = NIT_ITFLAGS(iter); int ndim = NIT_NDIM(iter); int iop, nop = NIT_NOP(iter); NpyIter_AxisData *axisdata0 = NIT_AXISDATA(iter); npy_intp sizeof_axisdata = NIT_AXISDATA_SIZEOF(itflags, ndim, nop); if (itflags&NPY_ITFLAG_BUFFER) { NpyIter_BufferData *data = NIT_BUFFERDATA(iter); npyiter_opitflags *op_itflags = NIT_OPITFLAGS(iter); npy_intp stride, *strides = NBF_STRIDES(data), *ad_strides = NAD_STRIDES(axisdata0); PyArray_Descr **dtypes = NIT_DTYPES(iter); for (iop = 0; iop < nop; ++iop) { stride = strides[iop]; /* * Operands which are always/never buffered have fixed strides, * and everything has fixed strides when ndim is 0 or 1 */ if (ndim <= 1 || (op_itflags[iop]& (NPY_OP_ITFLAG_CAST|NPY_OP_ITFLAG_BUFNEVER))) { out_strides[iop] = stride; } /* If it's a reduction, 0-stride inner loop may have fixed stride */ else if (stride == 0 && (itflags&NPY_ITFLAG_REDUCE)) { /* If it's a reduction operand, definitely fixed stride */ if (op_itflags[iop]&NPY_OP_ITFLAG_REDUCE) { out_strides[iop] = stride; } /* * 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; 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 == ndim) { out_strides[iop] = stride; } else { out_strides[iop] = NPY_MAX_INTP; } } } /* * Inner loop contiguous array means its stride won't change when * switching between buffering and not buffering */ else if (ad_strides[iop] == dtypes[iop]->elsize) { out_strides[iop] = ad_strides[iop]; } /* * Otherwise the strides can change if the operand is sometimes * buffered, sometimes not. */ else { out_strides[iop] = NPY_MAX_INTP; } } } else { /* If there's no buffering, the strides are always fixed */ memcpy(out_strides, NAD_STRIDES(axisdata0), nop*NPY_SIZEOF_INTP); } } /*NUMPY_API * Get a pointer to the size of the inner loop (when HasExternalLoop is true) * * This function may be safely called without holding the Python GIL. */ NPY_NO_EXPORT npy_intp * NpyIter_GetInnerLoopSizePtr(NpyIter *iter) { npy_uint32 itflags = NIT_ITFLAGS(iter); /*int ndim = NIT_NDIM(iter);*/ int nop = NIT_NOP(iter); if (itflags&NPY_ITFLAG_BUFFER) { NpyIter_BufferData *data = NIT_BUFFERDATA(iter); return &NBF_SIZE(data); } else { NpyIter_AxisData *axisdata = NIT_AXISDATA(iter); return &NAD_SHAPE(axisdata); } } /*NUMPY_API * For debugging */ NPY_NO_EXPORT void NpyIter_DebugPrint(NpyIter *iter) { npy_uint32 itflags = NIT_ITFLAGS(iter); int idim, ndim = NIT_NDIM(iter); int iop, nop = NIT_NOP(iter); NpyIter_AxisData *axisdata; npy_intp sizeof_axisdata; NPY_ALLOW_C_API_DEF NPY_ALLOW_C_API printf("\n------ BEGIN ITERATOR DUMP ------\n"); printf("| Iterator Address: %p\n", (void *)iter); printf("| ItFlags: "); if (itflags&NPY_ITFLAG_IDENTPERM) printf("IDENTPERM "); if (itflags&NPY_ITFLAG_NEGPERM) printf("NEGPERM "); if (itflags&NPY_ITFLAG_HASINDEX) printf("HASINDEX "); if (itflags&NPY_ITFLAG_HASMULTIINDEX) printf("HASMULTIINDEX "); if (itflags&NPY_ITFLAG_FORCEDORDER) printf("FORCEDORDER "); if (itflags&NPY_ITFLAG_EXLOOP) printf("EXLOOP "); if (itflags&NPY_ITFLAG_RANGE) printf("RANGE "); if (itflags&NPY_ITFLAG_BUFFER) printf("BUFFER "); if (itflags&NPY_ITFLAG_GROWINNER) printf("GROWINNER "); if (itflags&NPY_ITFLAG_ONEITERATION) printf("ONEITERATION "); if (itflags&NPY_ITFLAG_DELAYBUF) printf("DELAYBUF "); if (itflags&NPY_ITFLAG_NEEDSAPI) printf("NEEDSAPI "); if (itflags&NPY_ITFLAG_REDUCE) printf("REDUCE "); if (itflags&NPY_ITFLAG_REUSE_REDUCE_LOOPS) printf("REUSE_REDUCE_LOOPS "); printf("\n"); printf("| NDim: %d\n", (int)ndim); printf("| NOp: %d\n", (int)nop); if (NIT_MASKOP(iter) >= 0) { printf("| MaskOp: %d\n", (int)NIT_MASKOP(iter)); } printf("| IterSize: %d\n", (int)NIT_ITERSIZE(iter)); printf("| IterStart: %d\n", (int)NIT_ITERSTART(iter)); printf("| IterEnd: %d\n", (int)NIT_ITEREND(iter)); printf("| IterIndex: %d\n", (int)NIT_ITERINDEX(iter)); printf("| Iterator SizeOf: %d\n", (int)NIT_SIZEOF_ITERATOR(itflags, ndim, nop)); printf("| BufferData SizeOf: %d\n", (int)NIT_BUFFERDATA_SIZEOF(itflags, ndim, nop)); printf("| AxisData SizeOf: %d\n", (int)NIT_AXISDATA_SIZEOF(itflags, ndim, nop)); printf("|\n"); printf("| Perm: "); for (idim = 0; idim < ndim; ++idim) { printf("%d ", (int)NIT_PERM(iter)[idim]); } printf("\n"); printf("| DTypes: "); for (iop = 0; iop < nop; ++iop) { printf("%p ", (void *)NIT_DTYPES(iter)[iop]); } printf("\n"); printf("| DTypes: "); for (iop = 0; iop < nop; ++iop) { if (NIT_DTYPES(iter)[iop] != NULL) PyObject_Print((PyObject*)NIT_DTYPES(iter)[iop], stdout, 0); else printf("(nil) "); printf(" "); } printf("\n"); printf("| InitDataPtrs: "); for (iop = 0; iop < nop; ++iop) { printf("%p ", (void *)NIT_RESETDATAPTR(iter)[iop]); } printf("\n"); printf("| BaseOffsets: "); for (iop = 0; iop < nop; ++iop) { printf("%i ", (int)NIT_BASEOFFSETS(iter)[iop]); } printf("\n"); if (itflags&NPY_ITFLAG_HASINDEX) { printf("| InitIndex: %d\n", (int)(npy_intp)NIT_RESETDATAPTR(iter)[nop]); } printf("| Operands: "); for (iop = 0; iop < nop; ++iop) { printf("%p ", (void *)NIT_OPERANDS(iter)[iop]); } printf("\n"); printf("| Operand DTypes: "); for (iop = 0; iop < nop; ++iop) { PyArray_Descr *dtype; if (NIT_OPERANDS(iter)[iop] != NULL) { dtype = PyArray_DESCR(NIT_OPERANDS(iter)[iop]); if (dtype != NULL) PyObject_Print((PyObject *)dtype, stdout, 0); else printf("(nil) "); } else { printf("(op nil) "); } printf(" "); } printf("\n"); printf("| OpItFlags:\n"); for (iop = 0; iop < nop; ++iop) { printf("| Flags[%d]: ", (int)iop); if ((NIT_OPITFLAGS(iter)[iop])&NPY_OP_ITFLAG_READ) printf("READ "); if ((NIT_OPITFLAGS(iter)[iop])&NPY_OP_ITFLAG_WRITE) printf("WRITE "); if ((NIT_OPITFLAGS(iter)[iop])&NPY_OP_ITFLAG_CAST) printf("CAST "); if ((NIT_OPITFLAGS(iter)[iop])&NPY_OP_ITFLAG_BUFNEVER) printf("BUFNEVER "); if ((NIT_OPITFLAGS(iter)[iop])&NPY_OP_ITFLAG_ALIGNED) printf("ALIGNED "); if ((NIT_OPITFLAGS(iter)[iop])&NPY_OP_ITFLAG_REDUCE) printf("REDUCE "); if ((NIT_OPITFLAGS(iter)[iop])&NPY_OP_ITFLAG_VIRTUAL) printf("VIRTUAL "); if ((NIT_OPITFLAGS(iter)[iop])&NPY_OP_ITFLAG_WRITEMASKED) printf("WRITEMASKED "); printf("\n"); } printf("|\n"); if (itflags&NPY_ITFLAG_BUFFER) { NpyIter_BufferData *bufferdata = NIT_BUFFERDATA(iter); printf("| BufferData:\n"); printf("| BufferSize: %d\n", (int)NBF_BUFFERSIZE(bufferdata)); printf("| Size: %d\n", (int)NBF_SIZE(bufferdata)); printf("| BufIterEnd: %d\n", (int)NBF_BUFITEREND(bufferdata)); if (itflags&NPY_ITFLAG_REDUCE) { printf("| REDUCE Pos: %d\n", (int)NBF_REDUCE_POS(bufferdata)); printf("| REDUCE OuterSize: %d\n", (int)NBF_REDUCE_OUTERSIZE(bufferdata)); printf("| REDUCE OuterDim: %d\n", (int)NBF_REDUCE_OUTERDIM(bufferdata)); } printf("| Strides: "); for (iop = 0; iop < nop; ++iop) printf("%d ", (int)NBF_STRIDES(bufferdata)[iop]); printf("\n"); /* Print the fixed strides when there's no inner loop */ if (itflags&NPY_ITFLAG_EXLOOP) { npy_intp fixedstrides[NPY_MAXDIMS]; printf("| Fixed Strides: "); NpyIter_GetInnerFixedStrideArray(iter, fixedstrides); for (iop = 0; iop < nop; ++iop) printf("%d ", (int)fixedstrides[iop]); printf("\n"); } printf("| Ptrs: "); for (iop = 0; iop < nop; ++iop) printf("%p ", (void *)NBF_PTRS(bufferdata)[iop]); printf("\n"); if (itflags&NPY_ITFLAG_REDUCE) { printf("| REDUCE Outer Strides: "); for (iop = 0; iop < nop; ++iop) printf("%d ", (int)NBF_REDUCE_OUTERSTRIDES(bufferdata)[iop]); printf("\n"); printf("| REDUCE Outer Ptrs: "); for (iop = 0; iop < nop; ++iop) printf("%p ", (void *)NBF_REDUCE_OUTERPTRS(bufferdata)[iop]); printf("\n"); } printf("| ReadTransferFn: "); for (iop = 0; iop < nop; ++iop) printf("%p ", (void *)NBF_READTRANSFERFN(bufferdata)[iop]); printf("\n"); printf("| ReadTransferData: "); for (iop = 0; iop < nop; ++iop) printf("%p ", (void *)NBF_READTRANSFERDATA(bufferdata)[iop]); printf("\n"); printf("| WriteTransferFn: "); for (iop = 0; iop < nop; ++iop) printf("%p ", (void *)NBF_WRITETRANSFERFN(bufferdata)[iop]); printf("\n"); printf("| WriteTransferData: "); for (iop = 0; iop < nop; ++iop) printf("%p ", (void *)NBF_WRITETRANSFERDATA(bufferdata)[iop]); printf("\n"); printf("| Buffers: "); for (iop = 0; iop < nop; ++iop) printf("%p ", (void *)NBF_BUFFERS(bufferdata)[iop]); printf("\n"); printf("|\n"); } axisdata = NIT_AXISDATA(iter); sizeof_axisdata = NIT_AXISDATA_SIZEOF(itflags, ndim, nop); for (idim = 0; idim < ndim; ++idim, NIT_ADVANCE_AXISDATA(axisdata, 1)) { printf("| AxisData[%d]:\n", (int)idim); printf("| Shape: %d\n", (int)NAD_SHAPE(axisdata)); printf("| Index: %d\n", (int)NAD_INDEX(axisdata)); printf("| Strides: "); for (iop = 0; iop < nop; ++iop) { printf("%d ", (int)NAD_STRIDES(axisdata)[iop]); } printf("\n"); if (itflags&NPY_ITFLAG_HASINDEX) { printf("| Index Stride: %d\n", (int)NAD_STRIDES(axisdata)[nop]); } printf("| Ptrs: "); for (iop = 0; iop < nop; ++iop) { printf("%p ", (void *)NAD_PTRS(axisdata)[iop]); } printf("\n"); if (itflags&NPY_ITFLAG_HASINDEX) { printf("| Index Value: %d\n", (int)((npy_intp*)NAD_PTRS(axisdata))[nop]); } } printf("------- END ITERATOR DUMP -------\n"); fflush(stdout); NPY_DISABLE_C_API } NPY_NO_EXPORT void npyiter_coalesce_axes(NpyIter *iter) { npy_uint32 itflags = NIT_ITFLAGS(iter); int idim, ndim = NIT_NDIM(iter); int nop = NIT_NOP(iter); npy_intp istrides, nstrides = NAD_NSTRIDES(); NpyIter_AxisData *axisdata = NIT_AXISDATA(iter); npy_intp sizeof_axisdata = NIT_AXISDATA_SIZEOF(itflags, ndim, nop); NpyIter_AxisData *ad_compress; npy_intp new_ndim = 1; /* The HASMULTIINDEX or IDENTPERM flags do not apply after coalescing */ NIT_ITFLAGS(iter) &= ~(NPY_ITFLAG_IDENTPERM|NPY_ITFLAG_HASMULTIINDEX); axisdata = NIT_AXISDATA(iter); ad_compress = axisdata; for (idim = 0; idim < ndim-1; ++idim) { int can_coalesce = 1; npy_intp shape0 = NAD_SHAPE(ad_compress); npy_intp shape1 = NAD_SHAPE(NIT_INDEX_AXISDATA(axisdata, 1)); npy_intp *strides0 = NAD_STRIDES(ad_compress); npy_intp *strides1 = NAD_STRIDES(NIT_INDEX_AXISDATA(axisdata, 1)); /* Check that all the axes can be coalesced */ for (istrides = 0; istrides < nstrides; ++istrides) { if (!((shape0 == 1 && strides0[istrides] == 0) || (shape1 == 1 && strides1[istrides] == 0)) && (strides0[istrides]*shape0 != strides1[istrides])) { can_coalesce = 0; break; } } if (can_coalesce) { npy_intp *strides = NAD_STRIDES(ad_compress); NIT_ADVANCE_AXISDATA(axisdata, 1); NAD_SHAPE(ad_compress) *= NAD_SHAPE(axisdata); for (istrides = 0; istrides < nstrides; ++istrides) { if (strides[istrides] == 0) { strides[istrides] = NAD_STRIDES(axisdata)[istrides]; } } } else { NIT_ADVANCE_AXISDATA(axisdata, 1); NIT_ADVANCE_AXISDATA(ad_compress, 1); if (ad_compress != axisdata) { memcpy(ad_compress, axisdata, sizeof_axisdata); } ++new_ndim; } } /* * If the number of axes shrunk, reset the perm and * compress the data into the new layout. */ if (new_ndim < ndim) { npy_int8 *perm = NIT_PERM(iter); /* Reset to an identity perm */ for (idim = 0; idim < new_ndim; ++idim) { perm[idim] = (npy_int8)idim; } NIT_NDIM(iter) = new_ndim; } } /* * If errmsg is non-NULL, it should point to a variable which will * receive the error message, and no Python exception will be set. * This is so that the function can be called from code not holding * the GIL. */ NPY_NO_EXPORT int npyiter_allocate_buffers(NpyIter *iter, char **errmsg) { /*npy_uint32 itflags = NIT_ITFLAGS(iter);*/ /*int ndim = NIT_NDIM(iter);*/ int iop = 0, nop = NIT_NOP(iter); npy_intp i; npyiter_opitflags *op_itflags = NIT_OPITFLAGS(iter); NpyIter_BufferData *bufferdata = NIT_BUFFERDATA(iter); PyArray_Descr **op_dtype = NIT_DTYPES(iter); npy_intp buffersize = NBF_BUFFERSIZE(bufferdata); char *buffer, **buffers = NBF_BUFFERS(bufferdata); for (iop = 0; iop < nop; ++iop) { npyiter_opitflags flags = op_itflags[iop]; /* * If we have determined that a buffer may be needed, * allocate one. */ if (!(flags&NPY_OP_ITFLAG_BUFNEVER)) { npy_intp itemsize = op_dtype[iop]->elsize; buffer = PyArray_malloc(itemsize*buffersize); if (buffer == NULL) { if (errmsg == NULL) { PyErr_NoMemory(); } else { *errmsg = "out of memory"; } goto fail; } buffers[iop] = buffer; } } return 1; fail: for (i = 0; i < iop; ++i) { if (buffers[i] != NULL) { PyArray_free(buffers[i]); buffers[i] = NULL; } } return 0; } /* * This sets the AXISDATA portion of the iterator to the specified * iterindex, updating the pointers as well. This function does * no error checking. */ NPY_NO_EXPORT void npyiter_goto_iterindex(NpyIter *iter, npy_intp iterindex) { npy_uint32 itflags = NIT_ITFLAGS(iter); int idim, ndim = NIT_NDIM(iter); int nop = NIT_NOP(iter); char **dataptr; NpyIter_AxisData *axisdata; npy_intp sizeof_axisdata; npy_intp istrides, nstrides, i, shape; axisdata = NIT_AXISDATA(iter); sizeof_axisdata = NIT_AXISDATA_SIZEOF(itflags, ndim, nop); nstrides = NAD_NSTRIDES(); NIT_ITERINDEX(iter) = iterindex; ndim = ndim ? ndim : 1; if (iterindex == 0) { dataptr = NIT_RESETDATAPTR(iter); for (idim = 0; idim < ndim; ++idim) { char **ptrs; NAD_INDEX(axisdata) = 0; ptrs = NAD_PTRS(axisdata); for (istrides = 0; istrides < nstrides; ++istrides) { ptrs[istrides] = dataptr[istrides]; } NIT_ADVANCE_AXISDATA(axisdata, 1); } } else { /* * Set the multi-index, from the fastest-changing to the * slowest-changing. */ axisdata = NIT_AXISDATA(iter); shape = NAD_SHAPE(axisdata); i = iterindex; iterindex /= shape; NAD_INDEX(axisdata) = i - iterindex * shape; for (idim = 0; idim < ndim-1; ++idim) { NIT_ADVANCE_AXISDATA(axisdata, 1); shape = NAD_SHAPE(axisdata); i = iterindex; iterindex /= shape; NAD_INDEX(axisdata) = i - iterindex * shape; } dataptr = NIT_RESETDATAPTR(iter); /* * Accumulate the successive pointers with their * offsets in the opposite order, starting from the * original data pointers. */ for (idim = 0; idim < ndim; ++idim) { npy_intp *strides; char **ptrs; strides = NAD_STRIDES(axisdata); ptrs = NAD_PTRS(axisdata); i = NAD_INDEX(axisdata); for (istrides = 0; istrides < nstrides; ++istrides) { ptrs[istrides] = dataptr[istrides] + i*strides[istrides]; } dataptr = ptrs; NIT_ADVANCE_AXISDATA(axisdata, -1); } } } /* * This gets called after the the buffers have been exhausted, and * their data needs to be written back to the arrays. The multi-index * must be positioned for the beginning of the buffer. */ NPY_NO_EXPORT void npyiter_copy_from_buffers(NpyIter *iter) { npy_uint32 itflags = NIT_ITFLAGS(iter); int ndim = NIT_NDIM(iter); int iop, nop = NIT_NOP(iter); int maskop = NIT_MASKOP(iter); npyiter_opitflags *op_itflags = NIT_OPITFLAGS(iter); NpyIter_BufferData *bufferdata = NIT_BUFFERDATA(iter); NpyIter_AxisData *axisdata = NIT_AXISDATA(iter), *reduce_outeraxisdata = NULL; PyArray_Descr **dtypes = NIT_DTYPES(iter); npy_intp transfersize = NBF_SIZE(bufferdata); npy_intp *strides = NBF_STRIDES(bufferdata), *ad_strides = NAD_STRIDES(axisdata); npy_intp sizeof_axisdata = NIT_AXISDATA_SIZEOF(itflags, ndim, nop); char **ad_ptrs = NAD_PTRS(axisdata); char **buffers = NBF_BUFFERS(bufferdata); char *buffer; npy_intp reduce_outerdim = 0; npy_intp *reduce_outerstrides = NULL; PyArray_StridedUnaryOp *stransfer = NULL; NpyAuxData *transferdata = NULL; npy_intp axisdata_incr = NIT_AXISDATA_SIZEOF(itflags, ndim, nop) / NPY_SIZEOF_INTP; /* If we're past the end, nothing to copy */ if (NBF_SIZE(bufferdata) == 0) { return; } NPY_IT_DBG_PRINT("Iterator: Copying buffers to outputs\n"); if (itflags&NPY_ITFLAG_REDUCE) { reduce_outerdim = NBF_REDUCE_OUTERDIM(bufferdata); reduce_outerstrides = NBF_REDUCE_OUTERSTRIDES(bufferdata); reduce_outeraxisdata = NIT_INDEX_AXISDATA(axisdata, reduce_outerdim); transfersize *= NBF_REDUCE_OUTERSIZE(bufferdata); } for (iop = 0; iop < nop; ++iop) { stransfer = NBF_WRITETRANSFERFN(bufferdata)[iop]; transferdata = NBF_WRITETRANSFERDATA(bufferdata)[iop]; buffer = buffers[iop]; /* * Copy the data back to the arrays. If the type has refs, * this function moves them so the buffer's refs are released. * * The flag USINGBUFFER is set when the buffer was used, so * only copy back when this flag is on. */ if ((stransfer != NULL) && (op_itflags[iop]&(NPY_OP_ITFLAG_WRITE|NPY_OP_ITFLAG_USINGBUFFER)) == (NPY_OP_ITFLAG_WRITE|NPY_OP_ITFLAG_USINGBUFFER)) { npy_intp op_transfersize; npy_intp src_stride, *dst_strides, *dst_coords, *dst_shape; int ndim_transfer; NPY_IT_DBG_PRINT1("Iterator: Operand %d was buffered\n", (int)iop); /* * If this operand is being reduced in the inner loop, * its buffering stride was set to zero, and just * one element was copied. */ if (op_itflags[iop]&NPY_OP_ITFLAG_REDUCE) { if (strides[iop] == 0) { if (reduce_outerstrides[iop] == 0) { op_transfersize = 1; src_stride = 0; dst_strides = &src_stride; dst_coords = &NAD_INDEX(reduce_outeraxisdata); dst_shape = &NAD_SHAPE(reduce_outeraxisdata); ndim_transfer = 1; } else { op_transfersize = NBF_REDUCE_OUTERSIZE(bufferdata); src_stride = reduce_outerstrides[iop]; dst_strides = &NAD_STRIDES(reduce_outeraxisdata)[iop]; dst_coords = &NAD_INDEX(reduce_outeraxisdata); dst_shape = &NAD_SHAPE(reduce_outeraxisdata); ndim_transfer = ndim - reduce_outerdim; } } else { if (reduce_outerstrides[iop] == 0) { op_transfersize = NBF_SIZE(bufferdata); src_stride = strides[iop]; dst_strides = &ad_strides[iop]; dst_coords = &NAD_INDEX(axisdata); dst_shape = &NAD_SHAPE(axisdata); ndim_transfer = reduce_outerdim ? reduce_outerdim : 1; } else { op_transfersize = transfersize; src_stride = strides[iop]; dst_strides = &ad_strides[iop]; dst_coords = &NAD_INDEX(axisdata); dst_shape = &NAD_SHAPE(axisdata); ndim_transfer = ndim; } } } else { op_transfersize = transfersize; src_stride = strides[iop]; dst_strides = &ad_strides[iop]; dst_coords = &NAD_INDEX(axisdata); dst_shape = &NAD_SHAPE(axisdata); ndim_transfer = ndim; } NPY_IT_DBG_PRINT2("Iterator: Copying buffer to " "operand %d (%d items)\n", (int)iop, (int)op_transfersize); /* WRITEMASKED operand */ if (op_itflags[iop] & NPY_OP_ITFLAG_WRITEMASKED) { npy_bool *maskptr; /* * The mask pointer may be in the buffer or in * the array, detect which one. */ if ((op_itflags[maskop]&NPY_OP_ITFLAG_USINGBUFFER) != 0) { maskptr = (npy_bool *)buffers[maskop]; } else { maskptr = (npy_bool *)ad_ptrs[maskop]; } PyArray_TransferMaskedStridedToNDim(ndim_transfer, ad_ptrs[iop], dst_strides, axisdata_incr, buffer, src_stride, maskptr, strides[maskop], dst_coords, axisdata_incr, dst_shape, axisdata_incr, op_transfersize, dtypes[iop]->elsize, (PyArray_MaskedStridedUnaryOp *)stransfer, transferdata); } /* Regular operand */ else { PyArray_TransferStridedToNDim(ndim_transfer, ad_ptrs[iop], dst_strides, axisdata_incr, buffer, src_stride, dst_coords, axisdata_incr, dst_shape, axisdata_incr, op_transfersize, dtypes[iop]->elsize, stransfer, transferdata); } } /* If there's no copy back, we may have to decrement refs. In * this case, the transfer function has a 'decsrcref' transfer * function, so we can use it to do the decrement. * * The flag USINGBUFFER is set when the buffer was used, so * only decrement refs when this flag is on. */ else if (stransfer != NULL && (op_itflags[iop]&NPY_OP_ITFLAG_USINGBUFFER) != 0) { NPY_IT_DBG_PRINT1("Iterator: Freeing refs and zeroing buffer " "of operand %d\n", (int)iop); /* Decrement refs */ stransfer(NULL, 0, buffer, dtypes[iop]->elsize, transfersize, dtypes[iop]->elsize, transferdata); /* * Zero out the memory for safety. For instance, * if during iteration some Python code copied an * array pointing into the buffer, it will get None * values for its references after this. */ memset(buffer, 0, dtypes[iop]->elsize*transfersize); } } NPY_IT_DBG_PRINT("Iterator: Finished copying buffers to outputs\n"); } /* * This gets called after the iterator has been positioned to a multi-index * for the start of a buffer. It decides which operands need a buffer, * and copies the data into the buffers. */ NPY_NO_EXPORT void npyiter_copy_to_buffers(NpyIter *iter, char **prev_dataptrs) { npy_uint32 itflags = NIT_ITFLAGS(iter); int ndim = NIT_NDIM(iter); int iop, nop = NIT_NOP(iter); npyiter_opitflags *op_itflags = NIT_OPITFLAGS(iter); NpyIter_BufferData *bufferdata = NIT_BUFFERDATA(iter); NpyIter_AxisData *axisdata = NIT_AXISDATA(iter), *reduce_outeraxisdata = NULL; PyArray_Descr **dtypes = NIT_DTYPES(iter); PyArrayObject **operands = NIT_OPERANDS(iter); npy_intp *strides = NBF_STRIDES(bufferdata), *ad_strides = NAD_STRIDES(axisdata); npy_intp sizeof_axisdata = NIT_AXISDATA_SIZEOF(itflags, ndim, nop); char **ptrs = NBF_PTRS(bufferdata), **ad_ptrs = NAD_PTRS(axisdata); char **buffers = NBF_BUFFERS(bufferdata); npy_intp iterindex, iterend, transfersize, singlestridesize, reduce_innersize = 0, reduce_outerdim = 0; int is_onestride = 0, any_buffered = 0; npy_intp *reduce_outerstrides = NULL; char **reduce_outerptrs = NULL; PyArray_StridedUnaryOp *stransfer = NULL; NpyAuxData *transferdata = NULL; /* * Have to get this flag before npyiter_checkreducesize sets * it for the next iteration. */ npy_bool reuse_reduce_loops = (prev_dataptrs != NULL) && ((itflags&NPY_ITFLAG_REUSE_REDUCE_LOOPS) != 0); npy_intp axisdata_incr = NIT_AXISDATA_SIZEOF(itflags, ndim, nop) / NPY_SIZEOF_INTP; NPY_IT_DBG_PRINT("Iterator: Copying inputs to buffers\n"); /* Calculate the size if using any buffers */ iterindex = NIT_ITERINDEX(iter); iterend = NIT_ITEREND(iter); transfersize = NBF_BUFFERSIZE(bufferdata); if (transfersize > iterend - iterindex) { transfersize = iterend - iterindex; } /* If last time around, the reduce loop structure was full, we reuse it */ if (reuse_reduce_loops) { npy_intp full_transfersize, prev_reduce_outersize; prev_reduce_outersize = NBF_REDUCE_OUTERSIZE(bufferdata); reduce_outerstrides = NBF_REDUCE_OUTERSTRIDES(bufferdata); reduce_outerptrs = NBF_REDUCE_OUTERPTRS(bufferdata); reduce_outerdim = NBF_REDUCE_OUTERDIM(bufferdata); reduce_outeraxisdata = NIT_INDEX_AXISDATA(axisdata, reduce_outerdim); reduce_innersize = NBF_SIZE(bufferdata); NBF_REDUCE_POS(bufferdata) = 0; /* * Try to do make the outersize as big as possible. This allows * it to shrink when processing the last bit of the outer reduce loop, * then grow again at the beginnning of the next outer reduce loop. */ NBF_REDUCE_OUTERSIZE(bufferdata) = (NAD_SHAPE(reduce_outeraxisdata)- NAD_INDEX(reduce_outeraxisdata)); full_transfersize = NBF_REDUCE_OUTERSIZE(bufferdata)*reduce_innersize; /* If the full transfer size doesn't fit in the buffer, truncate it */ if (full_transfersize > NBF_BUFFERSIZE(bufferdata)) { NBF_REDUCE_OUTERSIZE(bufferdata) = transfersize/reduce_innersize; transfersize = NBF_REDUCE_OUTERSIZE(bufferdata)*reduce_innersize; } else { transfersize = full_transfersize; } if (prev_reduce_outersize < NBF_REDUCE_OUTERSIZE(bufferdata)) { /* * If the previous time around less data was copied it may not * be safe to reuse the buffers even if the pointers match. */ reuse_reduce_loops = 0; } NBF_BUFITEREND(bufferdata) = iterindex + reduce_innersize; NPY_IT_DBG_PRINT3("Reused reduce transfersize: %d innersize: %d " "itersize: %d\n", (int)transfersize, (int)reduce_innersize, (int)NpyIter_GetIterSize(iter)); NPY_IT_DBG_PRINT1("Reduced reduce outersize: %d", (int)NBF_REDUCE_OUTERSIZE(bufferdata)); } /* * If there are any reduction operands, we may have to make * the size smaller so we don't copy the same value into * a buffer twice, as the buffering does not have a mechanism * to combine values itself. */ else if (itflags&NPY_ITFLAG_REDUCE) { NPY_IT_DBG_PRINT("Iterator: Calculating reduce loops\n"); transfersize = npyiter_checkreducesize(iter, transfersize, &reduce_innersize, &reduce_outerdim); NPY_IT_DBG_PRINT3("Reduce transfersize: %d innersize: %d " "itersize: %d\n", (int)transfersize, (int)reduce_innersize, (int)NpyIter_GetIterSize(iter)); reduce_outerstrides = NBF_REDUCE_OUTERSTRIDES(bufferdata); reduce_outerptrs = NBF_REDUCE_OUTERPTRS(bufferdata); reduce_outeraxisdata = NIT_INDEX_AXISDATA(axisdata, reduce_outerdim); NBF_SIZE(bufferdata) = reduce_innersize; NBF_REDUCE_POS(bufferdata) = 0; NBF_REDUCE_OUTERDIM(bufferdata) = reduce_outerdim; NBF_BUFITEREND(bufferdata) = iterindex + reduce_innersize; if (reduce_innersize == 0) { NBF_REDUCE_OUTERSIZE(bufferdata) = 0; return; } else { NBF_REDUCE_OUTERSIZE(bufferdata) = transfersize/reduce_innersize; } } else { NBF_SIZE(bufferdata) = transfersize; NBF_BUFITEREND(bufferdata) = iterindex + transfersize; } /* Calculate the maximum size if using a single stride and no buffers */ singlestridesize = NAD_SHAPE(axisdata)-NAD_INDEX(axisdata); if (singlestridesize > iterend - iterindex) { singlestridesize = iterend - iterindex; } if (singlestridesize >= transfersize) { is_onestride = 1; } for (iop = 0; iop < nop; ++iop) { /* * If the buffer is write-only, these two are NULL, and the buffer * pointers will be set up but the read copy won't be done */ stransfer = NBF_READTRANSFERFN(bufferdata)[iop]; transferdata = NBF_READTRANSFERDATA(bufferdata)[iop]; switch (op_itflags[iop]& (NPY_OP_ITFLAG_BUFNEVER| NPY_OP_ITFLAG_CAST| NPY_OP_ITFLAG_REDUCE)) { /* Never need to buffer this operand */ case NPY_OP_ITFLAG_BUFNEVER: ptrs[iop] = ad_ptrs[iop]; if (itflags&NPY_ITFLAG_REDUCE) { reduce_outerstrides[iop] = reduce_innersize * strides[iop]; reduce_outerptrs[iop] = ptrs[iop]; } /* * Should not adjust the stride - ad_strides[iop] * could be zero, but strides[iop] was initialized * to the first non-trivial stride. */ stransfer = NULL; /* The flag NPY_OP_ITFLAG_USINGBUFFER can be ignored here */ break; /* Never need to buffer this operand */ case NPY_OP_ITFLAG_BUFNEVER|NPY_OP_ITFLAG_REDUCE: ptrs[iop] = ad_ptrs[iop]; reduce_outerptrs[iop] = ptrs[iop]; reduce_outerstrides[iop] = 0; /* * Should not adjust the stride - ad_strides[iop] * could be zero, but strides[iop] was initialized * to the first non-trivial stride. */ stransfer = NULL; /* The flag NPY_OP_ITFLAG_USINGBUFFER can be ignored here */ break; /* Just a copy */ case 0: /* Do not reuse buffer if it did not exist */ if (!(op_itflags[iop] & NPY_OP_ITFLAG_USINGBUFFER) && (prev_dataptrs != NULL)) { prev_dataptrs[iop] = NULL; } /* * No copyswap or cast was requested, so all we're * doing is copying the data to fill the buffer and * produce a single stride. If the underlying data * already does that, no need to copy it. */ if (is_onestride) { ptrs[iop] = ad_ptrs[iop]; strides[iop] = ad_strides[iop]; stransfer = NULL; /* Signal that the buffer is not being used */ op_itflags[iop] &= (~NPY_OP_ITFLAG_USINGBUFFER); } /* If some other op is reduced, we have a double reduce loop */ else if ((itflags&NPY_ITFLAG_REDUCE) && (reduce_outerdim == 1) && (transfersize/reduce_innersize <= NAD_SHAPE(reduce_outeraxisdata) - NAD_INDEX(reduce_outeraxisdata))) { ptrs[iop] = ad_ptrs[iop]; reduce_outerptrs[iop] = ptrs[iop]; strides[iop] = ad_strides[iop]; reduce_outerstrides[iop] = NAD_STRIDES(reduce_outeraxisdata)[iop]; stransfer = NULL; /* Signal that the buffer is not being used */ op_itflags[iop] &= (~NPY_OP_ITFLAG_USINGBUFFER); } else { /* In this case, the buffer is being used */ ptrs[iop] = buffers[iop]; strides[iop] = dtypes[iop]->elsize; if (itflags&NPY_ITFLAG_REDUCE) { reduce_outerstrides[iop] = reduce_innersize * strides[iop]; reduce_outerptrs[iop] = ptrs[iop]; } /* Signal that the buffer is being used */ op_itflags[iop] |= NPY_OP_ITFLAG_USINGBUFFER; } break; /* Just a copy, but with a reduction */ case NPY_OP_ITFLAG_REDUCE: /* Do not reuse buffer if it did not exist */ if (!(op_itflags[iop] & NPY_OP_ITFLAG_USINGBUFFER) && (prev_dataptrs != NULL)) { prev_dataptrs[iop] = NULL; } if (ad_strides[iop] == 0) { strides[iop] = 0; /* It's all in one stride in the inner loop dimension */ if (is_onestride) { NPY_IT_DBG_PRINT1("reduce op %d all one stride\n", (int)iop); ptrs[iop] = ad_ptrs[iop]; reduce_outerstrides[iop] = 0; stransfer = NULL; /* Signal that the buffer is not being used */ op_itflags[iop] &= (~NPY_OP_ITFLAG_USINGBUFFER); } /* It's all in one stride in the reduce outer loop */ else if ((reduce_outerdim > 0) && (transfersize/reduce_innersize <= NAD_SHAPE(reduce_outeraxisdata) - NAD_INDEX(reduce_outeraxisdata))) { NPY_IT_DBG_PRINT1("reduce op %d all one outer stride\n", (int)iop); ptrs[iop] = ad_ptrs[iop]; /* Outer reduce loop advances by one item */ reduce_outerstrides[iop] = NAD_STRIDES(reduce_outeraxisdata)[iop]; stransfer = NULL; /* Signal that the buffer is not being used */ op_itflags[iop] &= (~NPY_OP_ITFLAG_USINGBUFFER); } /* In this case, the buffer is being used */ else { NPY_IT_DBG_PRINT1("reduce op %d must buffer\n", (int)iop); ptrs[iop] = buffers[iop]; /* Both outer and inner reduce loops have stride 0 */ if (NAD_STRIDES(reduce_outeraxisdata)[iop] == 0) { reduce_outerstrides[iop] = 0; } /* Outer reduce loop advances by one item */ else { reduce_outerstrides[iop] = dtypes[iop]->elsize; } /* Signal that the buffer is being used */ op_itflags[iop] |= NPY_OP_ITFLAG_USINGBUFFER; } } else if (is_onestride) { NPY_IT_DBG_PRINT1("reduce op %d all one stride in dim 0\n", (int)iop); ptrs[iop] = ad_ptrs[iop]; strides[iop] = ad_strides[iop]; reduce_outerstrides[iop] = 0; stransfer = NULL; /* Signal that the buffer is not being used */ op_itflags[iop] &= (~NPY_OP_ITFLAG_USINGBUFFER); } else { /* It's all in one stride in the reduce outer loop */ if ((reduce_outerdim > 0) && (transfersize/reduce_innersize <= NAD_SHAPE(reduce_outeraxisdata) - NAD_INDEX(reduce_outeraxisdata))) { ptrs[iop] = ad_ptrs[iop]; strides[iop] = ad_strides[iop]; /* Outer reduce loop advances by one item */ reduce_outerstrides[iop] = NAD_STRIDES(reduce_outeraxisdata)[iop]; stransfer = NULL; /* Signal that the buffer is not being used */ op_itflags[iop] &= (~NPY_OP_ITFLAG_USINGBUFFER); } /* In this case, the buffer is being used */ else { ptrs[iop] = buffers[iop]; strides[iop] = dtypes[iop]->elsize; if (NAD_STRIDES(reduce_outeraxisdata)[iop] == 0) { /* Reduction in outer reduce loop */ reduce_outerstrides[iop] = 0; } else { /* Advance to next items in outer reduce loop */ reduce_outerstrides[iop] = reduce_innersize * dtypes[iop]->elsize; } /* Signal that the buffer is being used */ op_itflags[iop] |= NPY_OP_ITFLAG_USINGBUFFER; } } reduce_outerptrs[iop] = ptrs[iop]; break; default: /* In this case, the buffer is always being used */ any_buffered = 1; /* Signal that the buffer is being used */ op_itflags[iop] |= NPY_OP_ITFLAG_USINGBUFFER; if (!(op_itflags[iop]&NPY_OP_ITFLAG_REDUCE)) { ptrs[iop] = buffers[iop]; strides[iop] = dtypes[iop]->elsize; if (itflags&NPY_ITFLAG_REDUCE) { reduce_outerstrides[iop] = reduce_innersize * strides[iop]; reduce_outerptrs[iop] = ptrs[iop]; } } /* The buffer is being used with reduction */ else { ptrs[iop] = buffers[iop]; if (ad_strides[iop] == 0) { NPY_IT_DBG_PRINT1("cast op %d has innermost stride 0\n", (int)iop); strides[iop] = 0; /* Both outer and inner reduce loops have stride 0 */ if (NAD_STRIDES(reduce_outeraxisdata)[iop] == 0) { NPY_IT_DBG_PRINT1("cast op %d has outermost stride 0\n", (int)iop); reduce_outerstrides[iop] = 0; } /* Outer reduce loop advances by one item */ else { NPY_IT_DBG_PRINT1("cast op %d has outermost stride !=0\n", (int)iop); reduce_outerstrides[iop] = dtypes[iop]->elsize; } } else { NPY_IT_DBG_PRINT1("cast op %d has innermost stride !=0\n", (int)iop); strides[iop] = dtypes[iop]->elsize; if (NAD_STRIDES(reduce_outeraxisdata)[iop] == 0) { NPY_IT_DBG_PRINT1("cast op %d has outermost stride 0\n", (int)iop); /* Reduction in outer reduce loop */ reduce_outerstrides[iop] = 0; } else { NPY_IT_DBG_PRINT1("cast op %d has outermost stride !=0\n", (int)iop); /* Advance to next items in outer reduce loop */ reduce_outerstrides[iop] = reduce_innersize * dtypes[iop]->elsize; } } reduce_outerptrs[iop] = ptrs[iop]; } break; } if (stransfer != NULL) { npy_intp src_itemsize; npy_intp op_transfersize; npy_intp dst_stride, *src_strides, *src_coords, *src_shape; int ndim_transfer; npy_bool skip_transfer = 0; src_itemsize = PyArray_DTYPE(operands[iop])->elsize; /* If stransfer wasn't set to NULL, buffering is required */ any_buffered = 1; /* * If this operand is being reduced in the inner loop, * set its buffering stride to zero, and just copy * one element. */ if (op_itflags[iop]&NPY_OP_ITFLAG_REDUCE) { if (ad_strides[iop] == 0) { strides[iop] = 0; if (reduce_outerstrides[iop] == 0) { op_transfersize = 1; dst_stride = 0; src_strides = &dst_stride; src_coords = &NAD_INDEX(reduce_outeraxisdata); src_shape = &NAD_SHAPE(reduce_outeraxisdata); ndim_transfer = 1; /* * When we're reducing a single element, and * it's still the same element, don't overwrite * it even when reuse reduce loops is unset. * This preserves the precision of the * intermediate calculation. */ if (prev_dataptrs && prev_dataptrs[iop] == ad_ptrs[iop]) { NPY_IT_DBG_PRINT1("Iterator: skipping operand %d" " copy because it's a 1-element reduce\n", (int)iop); skip_transfer = 1; } } else { op_transfersize = NBF_REDUCE_OUTERSIZE(bufferdata); dst_stride = reduce_outerstrides[iop]; src_strides = &NAD_STRIDES(reduce_outeraxisdata)[iop]; src_coords = &NAD_INDEX(reduce_outeraxisdata); src_shape = &NAD_SHAPE(reduce_outeraxisdata); ndim_transfer = ndim - reduce_outerdim; } } else { if (reduce_outerstrides[iop] == 0) { op_transfersize = NBF_SIZE(bufferdata); dst_stride = strides[iop]; src_strides = &ad_strides[iop]; src_coords = &NAD_INDEX(axisdata); src_shape = &NAD_SHAPE(axisdata); ndim_transfer = reduce_outerdim ? reduce_outerdim : 1; } else { op_transfersize = transfersize; dst_stride = strides[iop]; src_strides = &ad_strides[iop]; src_coords = &NAD_INDEX(axisdata); src_shape = &NAD_SHAPE(axisdata); ndim_transfer = ndim; } } } else { op_transfersize = transfersize; dst_stride = strides[iop]; src_strides = &ad_strides[iop]; src_coords = &NAD_INDEX(axisdata); src_shape = &NAD_SHAPE(axisdata); ndim_transfer = ndim; } /* * If the whole buffered loop structure remains the same, * and the source pointer for this data didn't change, * we don't have to copy the data again. */ if (reuse_reduce_loops && prev_dataptrs[iop] == ad_ptrs[iop]) { NPY_IT_DBG_PRINT2("Iterator: skipping operands %d " "copy (%d items) because loops are reused and the data " "pointer didn't change\n", (int)iop, (int)op_transfersize); skip_transfer = 1; } /* If the data type requires zero-inititialization */ if (PyDataType_FLAGCHK(dtypes[iop], NPY_NEEDS_INIT)) { NPY_IT_DBG_PRINT("Iterator: Buffer requires init, " "memsetting to 0\n"); memset(ptrs[iop], 0, dtypes[iop]->elsize*op_transfersize); /* Can't skip the transfer in this case */ skip_transfer = 0; } if (!skip_transfer) { NPY_IT_DBG_PRINT2("Iterator: Copying operand %d to " "buffer (%d items)\n", (int)iop, (int)op_transfersize); PyArray_TransferNDimToStrided(ndim_transfer, ptrs[iop], dst_stride, ad_ptrs[iop], src_strides, axisdata_incr, src_coords, axisdata_incr, src_shape, axisdata_incr, op_transfersize, src_itemsize, stransfer, transferdata); } } else if (ptrs[iop] == buffers[iop]) { /* If the data type requires zero-inititialization */ if (PyDataType_FLAGCHK(dtypes[iop], NPY_NEEDS_INIT)) { NPY_IT_DBG_PRINT1("Iterator: Write-only buffer for " "operand %d requires init, " "memsetting to 0\n", (int)iop); memset(ptrs[iop], 0, dtypes[iop]->elsize*transfersize); } } } /* * If buffering wasn't needed, we can grow the inner * loop to as large as possible. * * TODO: Could grow REDUCE loop too with some more logic above. */ if (!any_buffered && (itflags&NPY_ITFLAG_GROWINNER) && !(itflags&NPY_ITFLAG_REDUCE)) { if (singlestridesize > transfersize) { NPY_IT_DBG_PRINT2("Iterator: Expanding inner loop size " "from %d to %d since buffering wasn't needed\n", (int)NBF_SIZE(bufferdata), (int)singlestridesize); NBF_SIZE(bufferdata) = singlestridesize; NBF_BUFITEREND(bufferdata) = iterindex + singlestridesize; } } NPY_IT_DBG_PRINT1("Any buffering needed: %d\n", any_buffered); NPY_IT_DBG_PRINT1("Iterator: Finished copying inputs to buffers " "(buffered size is %d)\n", (int)NBF_SIZE(bufferdata)); } /* * This checks how much space can be buffered without encountering the * same value twice, or for operands whose innermost stride is zero, * without encountering a different value. By reducing the buffered * amount to this size, reductions can be safely buffered. * * Reductions are buffered with two levels of looping, to avoid * frequent copying to the buffers. The return value is the over-all * buffer size, and when the flag NPY_ITFLAG_REDUCE is set, reduce_innersize * receives the size of the inner of the two levels of looping. * * The value placed in reduce_outerdim is the index into the AXISDATA * for where the second level of the double loop begins. * * The return value is always a multiple of the value placed in * reduce_innersize. */ static npy_intp npyiter_checkreducesize(NpyIter *iter, npy_intp count, npy_intp *reduce_innersize, npy_intp *reduce_outerdim) { npy_uint32 itflags = NIT_ITFLAGS(iter); int idim, ndim = NIT_NDIM(iter); int iop, nop = NIT_NOP(iter); NpyIter_AxisData *axisdata; npy_intp sizeof_axisdata; npy_intp coord, shape, *strides; npy_intp reducespace = 1, factor; npy_bool nonzerocoord; npyiter_opitflags *op_itflags = NIT_OPITFLAGS(iter); char stride0op[NPY_MAXARGS]; /* Default to no outer axis */ *reduce_outerdim = 0; /* If there's only one dimension, no need to calculate anything */ if (ndim == 1 || count == 0) { *reduce_innersize = count; return count; } sizeof_axisdata = NIT_AXISDATA_SIZEOF(itflags, ndim, nop); axisdata = NIT_AXISDATA(iter); /* Indicate which REDUCE operands have stride 0 in the inner loop */ strides = NAD_STRIDES(axisdata); for (iop = 0; iop < nop; ++iop) { stride0op[iop] = (op_itflags[iop]&NPY_OP_ITFLAG_REDUCE) && (strides[iop] == 0); NPY_IT_DBG_PRINT2("Iterator: Operand %d has stride 0 in " "the inner loop? %d\n", iop, (int)stride0op[iop]); } shape = NAD_SHAPE(axisdata); coord = NAD_INDEX(axisdata); reducespace += (shape-coord-1); factor = shape; NIT_ADVANCE_AXISDATA(axisdata, 1); /* Initialize nonzerocoord based on the first coordinate */ nonzerocoord = (coord != 0); /* Go forward through axisdata, calculating the space available */ for (idim = 1; idim < ndim && reducespace < count; ++idim, NIT_ADVANCE_AXISDATA(axisdata, 1)) { NPY_IT_DBG_PRINT2("Iterator: inner loop reducespace %d, count %d\n", (int)reducespace, (int)count); strides = NAD_STRIDES(axisdata); for (iop = 0; iop < nop; ++iop) { /* * If a reduce stride switched from zero to non-zero, or * vice versa, that's the point where the data will stop * being the same element or will repeat, and if the * buffer starts with an all zero multi-index up to this * point, gives us the reduce_innersize. */ if((stride0op[iop] && (strides[iop] != 0)) || (!stride0op[iop] && (strides[iop] == 0) && (op_itflags[iop]&NPY_OP_ITFLAG_REDUCE))) { NPY_IT_DBG_PRINT1("Iterator: Reduce operation limits " "buffer to %d\n", (int)reducespace); /* * If we already found more elements than count, or * the starting coordinate wasn't zero, the two-level * looping is unnecessary/can't be done, so return. */ if (count <= reducespace) { *reduce_innersize = count; NIT_ITFLAGS(iter) |= NPY_ITFLAG_REUSE_REDUCE_LOOPS; return count; } else if (nonzerocoord) { if (reducespace < count) { count = reducespace; } *reduce_innersize = count; /* NOTE: This is similar to the (coord != 0) case below. */ NIT_ITFLAGS(iter) &= ~NPY_ITFLAG_REUSE_REDUCE_LOOPS; return count; } else { *reduce_innersize = reducespace; break; } } } /* If we broke out of the loop early, we found reduce_innersize */ if (iop != nop) { NPY_IT_DBG_PRINT2("Iterator: Found first dim not " "reduce (%d of %d)\n", iop, nop); break; } shape = NAD_SHAPE(axisdata); coord = NAD_INDEX(axisdata); if (coord != 0) { nonzerocoord = 1; } reducespace += (shape-coord-1) * factor; factor *= shape; } /* * If there was any non-zero coordinate, the reduction inner * loop doesn't fit in the buffersize, or the reduction inner loop * covered the entire iteration size, can't do the double loop. */ if (nonzerocoord || count < reducespace || idim == ndim) { if (reducespace < count) { count = reducespace; } *reduce_innersize = count; /* In this case, we can't reuse the reduce loops */ NIT_ITFLAGS(iter) &= ~NPY_ITFLAG_REUSE_REDUCE_LOOPS; return count; } coord = NAD_INDEX(axisdata); if (coord != 0) { /* * In this case, it is only safe to reuse the buffer if the amount * of data copied is not more then the current axes, as is the * case when reuse_reduce_loops was active already. * It should be in principle OK when the idim loop returns immidiatly. */ NIT_ITFLAGS(iter) &= ~NPY_ITFLAG_REUSE_REDUCE_LOOPS; } else { /* In this case, we can reuse the reduce loops */ NIT_ITFLAGS(iter) |= NPY_ITFLAG_REUSE_REDUCE_LOOPS; } *reduce_innersize = reducespace; count /= reducespace; NPY_IT_DBG_PRINT2("Iterator: reduce_innersize %d count /ed %d\n", (int)reducespace, (int)count); /* * Continue through the rest of the dimensions. If there are * two separated reduction axes, we may have to cut the buffer * short again. */ *reduce_outerdim = idim; reducespace = 1; factor = 1; /* Indicate which REDUCE operands have stride 0 at the current level */ strides = NAD_STRIDES(axisdata); for (iop = 0; iop < nop; ++iop) { stride0op[iop] = (op_itflags[iop]&NPY_OP_ITFLAG_REDUCE) && (strides[iop] == 0); NPY_IT_DBG_PRINT2("Iterator: Operand %d has stride 0 in " "the outer loop? %d\n", iop, (int)stride0op[iop]); } shape = NAD_SHAPE(axisdata); reducespace += (shape-coord-1) * factor; factor *= shape; NIT_ADVANCE_AXISDATA(axisdata, 1); ++idim; for (; idim < ndim && reducespace < count; ++idim, NIT_ADVANCE_AXISDATA(axisdata, 1)) { NPY_IT_DBG_PRINT2("Iterator: outer loop reducespace %d, count %d\n", (int)reducespace, (int)count); strides = NAD_STRIDES(axisdata); for (iop = 0; iop < nop; ++iop) { /* * If a reduce stride switched from zero to non-zero, or * vice versa, that's the point where the data will stop * being the same element or will repeat, and if the * buffer starts with an all zero multi-index up to this * point, gives us the reduce_innersize. */ if((stride0op[iop] && (strides[iop] != 0)) || (!stride0op[iop] && (strides[iop] == 0) && (op_itflags[iop]&NPY_OP_ITFLAG_REDUCE))) { NPY_IT_DBG_PRINT1("Iterator: Reduce operation limits " "buffer to %d\n", (int)reducespace); /* * This terminates the outer level of our double loop. */ if (count <= reducespace) { return count * (*reduce_innersize); } else { return reducespace * (*reduce_innersize); } } } shape = NAD_SHAPE(axisdata); coord = NAD_INDEX(axisdata); if (coord != 0) { nonzerocoord = 1; } reducespace += (shape-coord-1) * factor; factor *= shape; } if (reducespace < count) { count = reducespace; } return count * (*reduce_innersize); } #undef NPY_ITERATOR_IMPLEMENTATION_CODE numpy-1.8.2/numpy/core/src/multiarray/usertypes.h0000664000175100017510000000114612370216242023321 0ustar vagrantvagrant00000000000000#ifndef _NPY_PRIVATE_USERTYPES_H_ #define _NPY_PRIVATE_USERTYPES_H_ #ifdef NPY_ENABLE_SEPARATE_COMPILATION extern NPY_NO_EXPORT PyArray_Descr **userdescrs; #else NPY_NO_EXPORT PyArray_Descr **userdescrs; #endif NPY_NO_EXPORT void PyArray_InitArrFuncs(PyArray_ArrFuncs *f); NPY_NO_EXPORT int PyArray_RegisterCanCast(PyArray_Descr *descr, int totype, NPY_SCALARKIND scalar); NPY_NO_EXPORT int PyArray_RegisterDataType(PyArray_Descr *descr); NPY_NO_EXPORT int PyArray_RegisterCastFunc(PyArray_Descr *descr, int totype, PyArray_VectorUnaryFunc *castfunc); #endif numpy-1.8.2/numpy/core/src/multiarray/arrayobject.c0000664000175100017510000014463712370216243023574 0ustar vagrantvagrant00000000000000/* Provide multidimensional arrays as a basic object type in python. Based on Original Numeric implementation Copyright (c) 1995, 1996, 1997 Jim Hugunin, hugunin@mit.edu with contributions from many Numeric Python developers 1995-2004 Heavily modified in 2005 with inspiration from Numarray by Travis Oliphant, oliphant@ee.byu.edu Brigham Young Univeristy maintainer email: oliphant.travis@ieee.org Numarray design (which provided guidance) by Space Science Telescope Institute (J. Todd Miller, Perry Greenfield, Rick White) */ #define PY_SSIZE_T_CLEAN #include #include "structmember.h" /*#include */ #define NPY_NO_DEPRECATED_API NPY_API_VERSION #define _MULTIARRAYMODULE #include "numpy/arrayobject.h" #include "numpy/arrayscalars.h" #include "npy_config.h" #include "npy_pycompat.h" #include "common.h" #include "number.h" #include "usertypes.h" #include "arraytypes.h" #include "scalartypes.h" #include "arrayobject.h" #include "ctors.h" #include "methods.h" #include "descriptor.h" #include "iterators.h" #include "mapping.h" #include "getset.h" #include "sequence.h" #include "buffer.h" #include "array_assign.h" /*NUMPY_API Compute the size of an array (in number of items) */ NPY_NO_EXPORT npy_intp PyArray_Size(PyObject *op) { if (PyArray_Check(op)) { return PyArray_SIZE((PyArrayObject *)op); } else { return 0; } } /*NUMPY_API * * Precondition: 'arr' is a copy of 'base' (though possibly with different * strides, ordering, etc.). This function sets the UPDATEIFCOPY flag and the * ->base pointer on 'arr', so that when 'arr' is destructed, it will copy any * changes back to 'base'. * * Steals a reference to 'base'. * * Returns 0 on success, -1 on failure. */ NPY_NO_EXPORT int PyArray_SetUpdateIfCopyBase(PyArrayObject *arr, PyArrayObject *base) { if (base == NULL) { PyErr_SetString(PyExc_ValueError, "Cannot UPDATEIFCOPY to NULL array"); return -1; } if (PyArray_BASE(arr) != NULL) { PyErr_SetString(PyExc_ValueError, "Cannot set array with existing base to UPDATEIFCOPY"); goto fail; } if (PyArray_FailUnlessWriteable(base, "UPDATEIFCOPY base") < 0) { goto fail; } /* * Any writes to 'arr' will magicaly turn into writes to 'base', so we * should warn if necessary. */ if (PyArray_FLAGS(base) & NPY_ARRAY_WARN_ON_WRITE) { PyArray_ENABLEFLAGS(arr, NPY_ARRAY_WARN_ON_WRITE); } /* * Unlike PyArray_SetBaseObject, we do not compress the chain of base * references. */ ((PyArrayObject_fields *)arr)->base = (PyObject *)base; PyArray_ENABLEFLAGS(arr, NPY_ARRAY_UPDATEIFCOPY); PyArray_CLEARFLAGS(base, NPY_ARRAY_WRITEABLE); return 0; fail: Py_DECREF(base); return -1; } /*NUMPY_API * Sets the 'base' attribute of the array. This steals a reference * to 'obj'. * * Returns 0 on success, -1 on failure. */ NPY_NO_EXPORT int PyArray_SetBaseObject(PyArrayObject *arr, PyObject *obj) { if (obj == NULL) { PyErr_SetString(PyExc_ValueError, "Cannot set the NumPy array 'base' " "dependency to NULL after initialization"); return -1; } /* * Allow the base to be set only once. Once the object which * owns the data is set, it doesn't make sense to change it. */ if (PyArray_BASE(arr) != NULL) { Py_DECREF(obj); PyErr_SetString(PyExc_ValueError, "Cannot set the NumPy array 'base' " "dependency more than once"); return -1; } /* * Don't allow infinite chains of views, always set the base * to the first owner of the data. * That is, either the first object which isn't an array, * or the first object which owns its own data. */ while (PyArray_Check(obj) && (PyObject *)arr != obj) { PyArrayObject *obj_arr = (PyArrayObject *)obj; PyObject *tmp; /* Propagate WARN_ON_WRITE through views. */ if (PyArray_FLAGS(obj_arr) & NPY_ARRAY_WARN_ON_WRITE) { PyArray_ENABLEFLAGS(arr, NPY_ARRAY_WARN_ON_WRITE); } /* If this array owns its own data, stop collapsing */ if (PyArray_CHKFLAGS(obj_arr, NPY_ARRAY_OWNDATA)) { break; } tmp = PyArray_BASE(obj_arr); /* If there's no base, stop collapsing */ if (tmp == NULL) { break; } /* Stop the collapse new base when the would not be of the same * type (i.e. different subclass). */ if (Py_TYPE(tmp) != Py_TYPE(arr)) { break; } Py_INCREF(tmp); Py_DECREF(obj); obj = tmp; } /* Disallow circular references */ if ((PyObject *)arr == obj) { Py_DECREF(obj); PyErr_SetString(PyExc_ValueError, "Cannot create a circular NumPy array 'base' dependency"); return -1; } ((PyArrayObject_fields *)arr)->base = obj; return 0; } /*NUMPY_API*/ NPY_NO_EXPORT int PyArray_CopyObject(PyArrayObject *dest, PyObject *src_object) { int ret = 0; PyArrayObject *src; PyArray_Descr *dtype = NULL; int ndim = 0; npy_intp dims[NPY_MAXDIMS]; Py_INCREF(src_object); /* * Special code to mimic Numeric behavior for * character arrays. */ if (PyArray_DESCR(dest)->type == NPY_CHARLTR && PyArray_NDIM(dest) > 0 && PyString_Check(src_object)) { npy_intp n_new, n_old; char *new_string; PyObject *tmp; n_new = PyArray_DIMS(dest)[PyArray_NDIM(dest)-1]; n_old = PyString_Size(src_object); if (n_new > n_old) { new_string = (char *)malloc(n_new); memmove(new_string, PyString_AS_STRING(src_object), n_old); memset(new_string + n_old, ' ', n_new - n_old); tmp = PyString_FromStringAndSize(new_string, n_new); free(new_string); Py_DECREF(src_object); src_object = tmp; } } /* * Get either an array object we can copy from, or its parameters * if there isn't a convenient array available. */ if (PyArray_GetArrayParamsFromObject(src_object, PyArray_DESCR(dest), 0, &dtype, &ndim, dims, &src, NULL) < 0) { Py_DECREF(src_object); return -1; } /* If it's not an array, either assign from a sequence or as a scalar */ if (src == NULL) { /* If the input is scalar */ if (ndim == 0) { /* If there's one dest element and src is a Python scalar */ if (PyArray_IsScalar(src_object, Generic)) { char *value; int retcode; value = scalar_value(src_object, dtype); if (value == NULL) { Py_DECREF(dtype); Py_DECREF(src_object); return -1; } /* TODO: switch to SAME_KIND casting */ retcode = PyArray_AssignRawScalar(dest, dtype, value, NULL, NPY_UNSAFE_CASTING); Py_DECREF(dtype); Py_DECREF(src_object); return retcode; } /* Otherwise use the dtype's setitem function */ else { if (PyArray_SIZE(dest) == 1) { Py_DECREF(dtype); Py_DECREF(src_object); ret = PyArray_DESCR(dest)->f->setitem(src_object, PyArray_DATA(dest), dest); return ret; } else { src = (PyArrayObject *)PyArray_NewFromDescr(&PyArray_Type, dtype, 0, NULL, NULL, NULL, 0, NULL); if (src == NULL) { Py_DECREF(src_object); return -1; } if (PyArray_DESCR(src)->f->setitem(src_object, PyArray_DATA(src), src) < 0) { Py_DECREF(src_object); Py_DECREF(src); return -1; } } } } else { /* * If there are more than enough dims, use AssignFromSequence * because it can handle this style of broadcasting. */ if (ndim >= PyArray_NDIM(dest)) { int res; Py_DECREF(dtype); res = PyArray_AssignFromSequence(dest, src_object); Py_DECREF(src_object); return res; } /* Otherwise convert to an array and do an array-based copy */ src = (PyArrayObject *)PyArray_NewFromDescr(&PyArray_Type, dtype, ndim, dims, NULL, NULL, PyArray_ISFORTRAN(dest), NULL); if (src == NULL) { Py_DECREF(src_object); return -1; } if (PyArray_AssignFromSequence(src, src_object) < 0) { Py_DECREF(src); Py_DECREF(src_object); return -1; } } } /* If it's an array, do a move (handling possible overlapping data) */ ret = PyArray_MoveInto(dest, src); Py_DECREF(src); Py_DECREF(src_object); return ret; } /* returns an Array-Scalar Object of the type of arr from the given pointer to memory -- main Scalar creation function default new method calls this. */ /* Ideally, here the descriptor would contain all the information needed. So, that we simply need the data and the descriptor, and perhaps a flag */ /* Given a string return the type-number for the data-type with that string as the type-object name. Returns NPY_NOTYPE without setting an error if no type can be found. Only works for user-defined data-types. */ /*NUMPY_API */ NPY_NO_EXPORT int PyArray_TypeNumFromName(char *str) { int i; PyArray_Descr *descr; for (i = 0; i < NPY_NUMUSERTYPES; i++) { descr = userdescrs[i]; if (strcmp(descr->typeobj->tp_name, str) == 0) { return descr->type_num; } } return NPY_NOTYPE; } /*********************** end C-API functions **********************/ /* array object functions */ static void array_dealloc(PyArrayObject *self) { PyArrayObject_fields *fa = (PyArrayObject_fields *)self; _array_dealloc_buffer_info(self); if (fa->weakreflist != NULL) { PyObject_ClearWeakRefs((PyObject *)self); } if (fa->base) { /* * UPDATEIFCOPY means that base points to an * array that should be updated with the contents * of this array upon destruction. * fa->base->flags must have been WRITEABLE * (checked previously) and it was locked here * thus, unlock it. */ if (fa->flags & NPY_ARRAY_UPDATEIFCOPY) { PyArray_ENABLEFLAGS(((PyArrayObject *)fa->base), NPY_ARRAY_WRITEABLE); Py_INCREF(self); /* hold on to self in next call */ if (PyArray_CopyAnyInto((PyArrayObject *)fa->base, self) < 0) { PyErr_Print(); PyErr_Clear(); } /* * Don't need to DECREF -- because we are deleting *self already... */ } /* * In any case base is pointing to something that we need * to DECREF -- either a view or a buffer object */ Py_DECREF(fa->base); } if ((fa->flags & NPY_ARRAY_OWNDATA) && fa->data) { /* Free internal references if an Object array */ if (PyDataType_FLAGCHK(fa->descr, NPY_ITEM_REFCOUNT)) { Py_INCREF(self); /*hold on to self */ PyArray_XDECREF(self); /* * Don't need to DECREF -- because we are deleting * self already... */ } PyDataMem_FREE(fa->data); } PyDimMem_FREE(fa->dimensions); Py_DECREF(fa->descr); Py_TYPE(self)->tp_free((PyObject *)self); } static int dump_data(char **string, int *n, int *max_n, char *data, int nd, npy_intp *dimensions, npy_intp *strides, PyArrayObject* self) { PyArray_Descr *descr=PyArray_DESCR(self); PyObject *op, *sp; char *ostring; npy_intp i, N; #define CHECK_MEMORY do { if (*n >= *max_n-16) { \ *max_n *= 2; \ *string = (char *)PyArray_realloc(*string, *max_n); \ }} while (0) if (nd == 0) { if ((op = descr->f->getitem(data, self)) == NULL) { return -1; } sp = PyObject_Repr(op); if (sp == NULL) { Py_DECREF(op); return -1; } ostring = PyString_AsString(sp); N = PyString_Size(sp)*sizeof(char); *n += N; CHECK_MEMORY; memmove(*string + (*n - N), ostring, N); Py_DECREF(sp); Py_DECREF(op); return 0; } else { CHECK_MEMORY; (*string)[*n] = '['; *n += 1; for (i = 0; i < dimensions[0]; i++) { if (dump_data(string, n, max_n, data + (*strides)*i, nd - 1, dimensions + 1, strides + 1, self) < 0) { return -1; } CHECK_MEMORY; if (i < dimensions[0] - 1) { (*string)[*n] = ','; (*string)[*n+1] = ' '; *n += 2; } } CHECK_MEMORY; (*string)[*n] = ']'; *n += 1; return 0; } #undef CHECK_MEMORY } /*NUMPY_API * Prints the raw data of the ndarray in a form useful for debugging * low-level C issues. */ NPY_NO_EXPORT void PyArray_DebugPrint(PyArrayObject *obj) { int i; PyArrayObject_fields *fobj = (PyArrayObject_fields *)obj; printf("-------------------------------------------------------\n"); printf(" Dump of NumPy ndarray at address %p\n", obj); if (obj == NULL) { printf(" It's NULL!\n"); printf("-------------------------------------------------------\n"); fflush(stdout); return; } printf(" ndim : %d\n", fobj->nd); printf(" shape :"); for (i = 0; i < fobj->nd; ++i) { printf(" %d", (int)fobj->dimensions[i]); } printf("\n"); printf(" dtype : "); PyObject_Print((PyObject *)fobj->descr, stdout, 0); printf("\n"); printf(" data : %p\n", fobj->data); printf(" strides:"); for (i = 0; i < fobj->nd; ++i) { printf(" %d", (int)fobj->strides[i]); } printf("\n"); printf(" base : %p\n", fobj->base); printf(" flags :"); if (fobj->flags & NPY_ARRAY_C_CONTIGUOUS) printf(" NPY_C_CONTIGUOUS"); if (fobj->flags & NPY_ARRAY_F_CONTIGUOUS) printf(" NPY_F_CONTIGUOUS"); if (fobj->flags & NPY_ARRAY_OWNDATA) printf(" NPY_OWNDATA"); if (fobj->flags & NPY_ARRAY_ALIGNED) printf(" NPY_ALIGNED"); if (fobj->flags & NPY_ARRAY_WRITEABLE) printf(" NPY_WRITEABLE"); if (fobj->flags & NPY_ARRAY_UPDATEIFCOPY) printf(" NPY_UPDATEIFCOPY"); printf("\n"); if (fobj->base != NULL && PyArray_Check(fobj->base)) { printf("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n"); printf("Dump of array's BASE:\n"); PyArray_DebugPrint((PyArrayObject *)fobj->base); printf(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n"); } printf("-------------------------------------------------------\n"); fflush(stdout); } static PyObject * array_repr_builtin(PyArrayObject *self, int repr) { PyObject *ret; char *string; int n, max_n; max_n = PyArray_NBYTES(self)*4*sizeof(char) + 7; if ((string = (char *)PyArray_malloc(max_n)) == NULL) { return PyErr_NoMemory(); } if (repr) { n = 6; sprintf(string, "array("); } else { n = 0; } if (dump_data(&string, &n, &max_n, PyArray_DATA(self), PyArray_NDIM(self), PyArray_DIMS(self), PyArray_STRIDES(self), self) < 0) { PyArray_free(string); return NULL; } if (repr) { if (PyArray_ISEXTENDED(self)) { char buf[100]; PyOS_snprintf(buf, sizeof(buf), "%d", PyArray_DESCR(self)->elsize); sprintf(string+n, ", '%c%s')", PyArray_DESCR(self)->type, buf); ret = PyUString_FromStringAndSize(string, n + 6 + strlen(buf)); } else { sprintf(string+n, ", '%c')", PyArray_DESCR(self)->type); ret = PyUString_FromStringAndSize(string, n+6); } } else { ret = PyUString_FromStringAndSize(string, n); } PyArray_free(string); return ret; } static PyObject *PyArray_StrFunction = NULL; static PyObject *PyArray_ReprFunction = NULL; /*NUMPY_API * Set the array print function to be a Python function. */ NPY_NO_EXPORT void PyArray_SetStringFunction(PyObject *op, int repr) { if (repr) { /* Dispose of previous callback */ Py_XDECREF(PyArray_ReprFunction); /* Add a reference to new callback */ Py_XINCREF(op); /* Remember new callback */ PyArray_ReprFunction = op; } else { /* Dispose of previous callback */ Py_XDECREF(PyArray_StrFunction); /* Add a reference to new callback */ Py_XINCREF(op); /* Remember new callback */ PyArray_StrFunction = op; } } /*NUMPY_API * This function is scheduled to be removed * * TO BE REMOVED - NOT USED INTERNALLY. */ NPY_NO_EXPORT void PyArray_SetDatetimeParseFunction(PyObject *op) { } static PyObject * array_repr(PyArrayObject *self) { PyObject *s, *arglist; if (PyArray_ReprFunction == NULL) { s = array_repr_builtin(self, 1); } else { arglist = Py_BuildValue("(O)", self); s = PyEval_CallObject(PyArray_ReprFunction, arglist); Py_DECREF(arglist); } return s; } static PyObject * array_str(PyArrayObject *self) { PyObject *s, *arglist; if (PyArray_StrFunction == NULL) { s = array_repr_builtin(self, 0); } else { arglist = Py_BuildValue("(O)", self); s = PyEval_CallObject(PyArray_StrFunction, arglist); Py_DECREF(arglist); } return s; } /*NUMPY_API */ NPY_NO_EXPORT int PyArray_CompareUCS4(npy_ucs4 *s1, npy_ucs4 *s2, size_t len) { npy_ucs4 c1, c2; while(len-- > 0) { c1 = *s1++; c2 = *s2++; if (c1 != c2) { return (c1 < c2) ? -1 : 1; } } return 0; } /*NUMPY_API */ NPY_NO_EXPORT int PyArray_CompareString(char *s1, char *s2, size_t len) { const unsigned char *c1 = (unsigned char *)s1; const unsigned char *c2 = (unsigned char *)s2; size_t i; for(i = 0; i < len; ++i) { if (c1[i] != c2[i]) { return (c1[i] > c2[i]) ? 1 : -1; } } return 0; } /* Call this from contexts where an array might be written to, but we have no * way to tell. (E.g., when converting to a read-write buffer.) */ NPY_NO_EXPORT int array_might_be_written(PyArrayObject *obj) { const char *msg = "Numpy has detected that you (may be) writing to an array returned\n" "by numpy.diagonal or by selecting multiple fields in a record\n" "array. This code will likely break in a future numpy release --\n" "see numpy.diagonal or arrays.indexing reference docs for details.\n" "The quick fix is to make an explicit copy (e.g., do\n" "arr.diagonal().copy() or arr[['f0','f1']].copy())."; if (PyArray_FLAGS(obj) & NPY_ARRAY_WARN_ON_WRITE) { if (DEPRECATE_FUTUREWARNING(msg) < 0) { return -1; } /* Only warn once per array */ while (1) { PyArray_CLEARFLAGS(obj, NPY_ARRAY_WARN_ON_WRITE); if (!PyArray_BASE(obj) || !PyArray_Check(PyArray_BASE(obj))) { break; } obj = (PyArrayObject *)PyArray_BASE(obj); } } return 0; } /*NUMPY_API * * This function does nothing if obj is writeable, and raises an exception * (and returns -1) if obj is not writeable. It may also do other * house-keeping, such as issuing warnings on arrays which are transitioning * to become views. Always call this function at some point before writing to * an array. * * 'name' is a name for the array, used to give better error * messages. Something like "assignment destination", "output array", or even * just "array". */ NPY_NO_EXPORT int PyArray_FailUnlessWriteable(PyArrayObject *obj, const char *name) { if (!PyArray_ISWRITEABLE(obj)) { PyErr_Format(PyExc_ValueError, "%s is read-only", name); return -1; } if (array_might_be_written(obj) < 0) { return -1; } return 0; } /* This also handles possibly mis-aligned data */ /* Compare s1 and s2 which are not necessarily NULL-terminated. s1 is of length len1 s2 is of length len2 If they are NULL terminated, then stop comparison. */ static int _myunincmp(npy_ucs4 *s1, npy_ucs4 *s2, int len1, int len2) { npy_ucs4 *sptr; npy_ucs4 *s1t=s1, *s2t=s2; int val; npy_intp size; int diff; if ((npy_intp)s1 % sizeof(npy_ucs4) != 0) { size = len1*sizeof(npy_ucs4); s1t = malloc(size); memcpy(s1t, s1, size); } if ((npy_intp)s2 % sizeof(npy_ucs4) != 0) { size = len2*sizeof(npy_ucs4); s2t = malloc(size); memcpy(s2t, s2, size); } val = PyArray_CompareUCS4(s1t, s2t, PyArray_MIN(len1,len2)); if ((val != 0) || (len1 == len2)) { goto finish; } if (len2 > len1) { sptr = s2t+len1; val = -1; diff = len2-len1; } else { sptr = s1t+len2; val = 1; diff=len1-len2; } while (diff--) { if (*sptr != 0) { goto finish; } sptr++; } val = 0; finish: if (s1t != s1) { free(s1t); } if (s2t != s2) { free(s2t); } return val; } /* * Compare s1 and s2 which are not necessarily NULL-terminated. * s1 is of length len1 * s2 is of length len2 * If they are NULL terminated, then stop comparison. */ static int _mystrncmp(char *s1, char *s2, int len1, int len2) { char *sptr; int val; int diff; val = memcmp(s1, s2, PyArray_MIN(len1, len2)); if ((val != 0) || (len1 == len2)) { return val; } if (len2 > len1) { sptr = s2 + len1; val = -1; diff = len2 - len1; } else { sptr = s1 + len2; val = 1; diff = len1 - len2; } while (diff--) { if (*sptr != 0) { return val; } sptr++; } return 0; /* Only happens if NULLs are everywhere */ } /* Borrowed from Numarray */ #define SMALL_STRING 2048 #if defined(isspace) #undef isspace #define isspace(c) ((c==' ')||(c=='\t')||(c=='\n')||(c=='\r')||(c=='\v')||(c=='\f')) #endif static void _rstripw(char *s, int n) { int i; for (i = n - 1; i >= 1; i--) { /* Never strip to length 0. */ int c = s[i]; if (!c || isspace(c)) { s[i] = 0; } else { break; } } } static void _unistripw(npy_ucs4 *s, int n) { int i; for (i = n - 1; i >= 1; i--) { /* Never strip to length 0. */ npy_ucs4 c = s[i]; if (!c || isspace(c)) { s[i] = 0; } else { break; } } } static char * _char_copy_n_strip(char *original, char *temp, int nc) { if (nc > SMALL_STRING) { temp = malloc(nc); if (!temp) { PyErr_NoMemory(); return NULL; } } memcpy(temp, original, nc); _rstripw(temp, nc); return temp; } static void _char_release(char *ptr, int nc) { if (nc > SMALL_STRING) { free(ptr); } } static char * _uni_copy_n_strip(char *original, char *temp, int nc) { if (nc*sizeof(npy_ucs4) > SMALL_STRING) { temp = malloc(nc*sizeof(npy_ucs4)); if (!temp) { PyErr_NoMemory(); return NULL; } } memcpy(temp, original, nc*sizeof(npy_ucs4)); _unistripw((npy_ucs4 *)temp, nc); return temp; } static void _uni_release(char *ptr, int nc) { if (nc*sizeof(npy_ucs4) > SMALL_STRING) { free(ptr); } } /* End borrowed from numarray */ #define _rstrip_loop(CMP) { \ void *aptr, *bptr; \ char atemp[SMALL_STRING], btemp[SMALL_STRING]; \ while(size--) { \ aptr = stripfunc(iself->dataptr, atemp, N1); \ if (!aptr) return -1; \ bptr = stripfunc(iother->dataptr, btemp, N2); \ if (!bptr) { \ relfunc(aptr, N1); \ return -1; \ } \ val = compfunc(aptr, bptr, N1, N2); \ *dptr = (val CMP 0); \ PyArray_ITER_NEXT(iself); \ PyArray_ITER_NEXT(iother); \ dptr += 1; \ relfunc(aptr, N1); \ relfunc(bptr, N2); \ } \ } #define _reg_loop(CMP) { \ while(size--) { \ val = compfunc((void *)iself->dataptr, \ (void *)iother->dataptr, \ N1, N2); \ *dptr = (val CMP 0); \ PyArray_ITER_NEXT(iself); \ PyArray_ITER_NEXT(iother); \ dptr += 1; \ } \ } static int _compare_strings(PyArrayObject *result, PyArrayMultiIterObject *multi, int cmp_op, void *func, int rstrip) { PyArrayIterObject *iself, *iother; npy_bool *dptr; npy_intp size; int val; int N1, N2; int (*compfunc)(void *, void *, int, int); void (*relfunc)(char *, int); char* (*stripfunc)(char *, char *, int); compfunc = func; dptr = (npy_bool *)PyArray_DATA(result); iself = multi->iters[0]; iother = multi->iters[1]; size = multi->size; N1 = PyArray_DESCR(iself->ao)->elsize; N2 = PyArray_DESCR(iother->ao)->elsize; if ((void *)compfunc == (void *)_myunincmp) { N1 >>= 2; N2 >>= 2; stripfunc = _uni_copy_n_strip; relfunc = _uni_release; } else { stripfunc = _char_copy_n_strip; relfunc = _char_release; } switch (cmp_op) { case Py_EQ: if (rstrip) { _rstrip_loop(==); } else { _reg_loop(==); } break; case Py_NE: if (rstrip) { _rstrip_loop(!=); } else { _reg_loop(!=); } break; case Py_LT: if (rstrip) { _rstrip_loop(<); } else { _reg_loop(<); } break; case Py_LE: if (rstrip) { _rstrip_loop(<=); } else { _reg_loop(<=); } break; case Py_GT: if (rstrip) { _rstrip_loop(>); } else { _reg_loop(>); } break; case Py_GE: if (rstrip) { _rstrip_loop(>=); } else { _reg_loop(>=); } break; default: PyErr_SetString(PyExc_RuntimeError, "bad comparison operator"); return -1; } return 0; } #undef _reg_loop #undef _rstrip_loop #undef SMALL_STRING NPY_NO_EXPORT PyObject * _strings_richcompare(PyArrayObject *self, PyArrayObject *other, int cmp_op, int rstrip) { PyArrayObject *result; PyArrayMultiIterObject *mit; int val; /* Cast arrays to a common type */ if (PyArray_TYPE(self) != PyArray_DESCR(other)->type_num) { #if defined(NPY_PY3K) /* * Comparison between Bytes and Unicode is not defined in Py3K; * we follow. */ Py_INCREF(Py_NotImplemented); return Py_NotImplemented; #else PyObject *new; if (PyArray_TYPE(self) == NPY_STRING && PyArray_DESCR(other)->type_num == NPY_UNICODE) { PyArray_Descr* unicode = PyArray_DescrNew(PyArray_DESCR(other)); unicode->elsize = PyArray_DESCR(self)->elsize << 2; new = PyArray_FromAny((PyObject *)self, unicode, 0, 0, 0, NULL); if (new == NULL) { return NULL; } Py_INCREF(other); self = (PyArrayObject *)new; } else if (PyArray_TYPE(self) == NPY_UNICODE && PyArray_DESCR(other)->type_num == NPY_STRING) { PyArray_Descr* unicode = PyArray_DescrNew(PyArray_DESCR(self)); unicode->elsize = PyArray_DESCR(other)->elsize << 2; new = PyArray_FromAny((PyObject *)other, unicode, 0, 0, 0, NULL); if (new == NULL) { return NULL; } Py_INCREF(self); other = (PyArrayObject *)new; } else { PyErr_SetString(PyExc_TypeError, "invalid string data-types " "in comparison"); return NULL; } #endif } else { Py_INCREF(self); Py_INCREF(other); } /* Broad-cast the arrays to a common shape */ mit = (PyArrayMultiIterObject *)PyArray_MultiIterNew(2, self, other); Py_DECREF(self); Py_DECREF(other); if (mit == NULL) { return NULL; } result = (PyArrayObject *)PyArray_NewFromDescr(&PyArray_Type, PyArray_DescrFromType(NPY_BOOL), mit->nd, mit->dimensions, NULL, NULL, 0, NULL); if (result == NULL) { goto finish; } if (PyArray_TYPE(self) == NPY_UNICODE) { val = _compare_strings(result, mit, cmp_op, _myunincmp, rstrip); } else { val = _compare_strings(result, mit, cmp_op, _mystrncmp, rstrip); } if (val < 0) { Py_DECREF(result); result = NULL; } finish: Py_DECREF(mit); return (PyObject *)result; } /* * VOID-type arrays can only be compared equal and not-equal * in which case the fields are all compared by extracting the fields * and testing one at a time... * equality testing is performed using logical_ands on all the fields. * in-equality testing is performed using logical_ors on all the fields. * * VOID-type arrays without fields are compared for equality by comparing their * memory at each location directly (using string-code). */ static PyObject * _void_compare(PyArrayObject *self, PyArrayObject *other, int cmp_op) { if (!(cmp_op == Py_EQ || cmp_op == Py_NE)) { PyErr_SetString(PyExc_ValueError, "Void-arrays can only be compared for equality."); return NULL; } if (PyArray_HASFIELDS(self)) { PyObject *res = NULL, *temp, *a, *b; PyObject *key, *value, *temp2; PyObject *op; Py_ssize_t pos = 0; npy_intp result_ndim = PyArray_NDIM(self) > PyArray_NDIM(other) ? PyArray_NDIM(self) : PyArray_NDIM(other); op = (cmp_op == Py_EQ ? n_ops.logical_and : n_ops.logical_or); while (PyDict_Next(PyArray_DESCR(self)->fields, &pos, &key, &value)) { if NPY_TITLE_KEY(key, value) { continue; } a = array_subscript_asarray(self, key); if (a == NULL) { Py_XDECREF(res); return NULL; } b = array_subscript_asarray(other, key); if (b == NULL) { Py_XDECREF(res); Py_DECREF(a); return NULL; } temp = array_richcompare((PyArrayObject *)a,b,cmp_op); Py_DECREF(a); Py_DECREF(b); if (temp == NULL) { Py_XDECREF(res); return NULL; } /* * If the field type has a non-trivial shape, additional * dimensions will have been appended to `a` and `b`. * In that case, reduce them using `op`. */ if (PyArray_Check(temp) && PyArray_NDIM((PyArrayObject *)temp) > result_ndim) { /* If the type was multidimensional, collapse that part to 1-D */ if (PyArray_NDIM((PyArrayObject *)temp) != result_ndim+1) { npy_intp dimensions[NPY_MAXDIMS]; PyArray_Dims newdims; newdims.ptr = dimensions; newdims.len = result_ndim+1; memcpy(dimensions, PyArray_DIMS((PyArrayObject *)temp), sizeof(npy_intp)*result_ndim); dimensions[result_ndim] = -1; temp2 = PyArray_Newshape((PyArrayObject *)temp, &newdims, NPY_ANYORDER); if (temp2 == NULL) { Py_DECREF(temp); Py_XDECREF(res); return NULL; } Py_DECREF(temp); temp = temp2; } /* Reduce the extra dimension of `temp` using `op` */ temp2 = PyArray_GenericReduceFunction((PyArrayObject *)temp, op, result_ndim, NPY_BOOL, NULL); if (temp2 == NULL) { Py_DECREF(temp); Py_XDECREF(res); return NULL; } Py_DECREF(temp); temp = temp2; } if (res == NULL) { res = temp; } else { temp2 = PyObject_CallFunction(op, "OO", res, temp); Py_DECREF(temp); Py_DECREF(res); if (temp2 == NULL) { return NULL; } res = temp2; } } if (res == NULL && !PyErr_Occurred()) { PyErr_SetString(PyExc_ValueError, "No fields found."); } return res; } else { /* * compare as a string. Assumes self and * other have same descr->type */ return _strings_richcompare(self, other, cmp_op, 0); } } NPY_NO_EXPORT PyObject * array_richcompare(PyArrayObject *self, PyObject *other, int cmp_op) { PyArrayObject *array_other; PyObject *result = NULL; switch (cmp_op) { case Py_LT: result = PyArray_GenericBinaryFunction(self, other, n_ops.less); break; case Py_LE: result = PyArray_GenericBinaryFunction(self, other, n_ops.less_equal); break; case Py_EQ: if (other == Py_None) { Py_INCREF(Py_False); return Py_False; } result = PyArray_GenericBinaryFunction(self, (PyObject *)other, n_ops.equal); if (result && result != Py_NotImplemented) break; /* * The ufunc does not support void/structured types, so these * need to be handled specifically. Only a few cases are supported. */ if (PyArray_TYPE(self) == NPY_VOID) { int _res; array_other = (PyArrayObject *)PyArray_FromAny(other, NULL, 0, 0, 0, NULL); /* * If not successful, indicate that the items cannot be compared * this way. */ if (array_other == NULL) { PyErr_Clear(); Py_INCREF(Py_NotImplemented); return Py_NotImplemented; } _res = PyObject_RichCompareBool ((PyObject *)PyArray_DESCR(self), (PyObject *)PyArray_DESCR(array_other), Py_EQ); if (_res < 0) { Py_DECREF(result); Py_DECREF(array_other); return NULL; } if (_res) { Py_DECREF(result); result = _void_compare(self, array_other, cmp_op); } Py_DECREF(array_other); return result; } /* * If the comparison results in NULL, then the * two array objects can not be compared together; * indicate that */ if (result == NULL) { PyErr_Clear(); Py_INCREF(Py_NotImplemented); return Py_NotImplemented; } break; case Py_NE: if (other == Py_None) { Py_INCREF(Py_True); return Py_True; } result = PyArray_GenericBinaryFunction(self, (PyObject *)other, n_ops.not_equal); if (result && result != Py_NotImplemented) break; /* * The ufunc does not support void/structured types, so these * need to be handled specifically. Only a few cases are supported. */ if (PyArray_TYPE(self) == NPY_VOID) { int _res; array_other = (PyArrayObject *)PyArray_FromAny(other, NULL, 0, 0, 0, NULL); /* * If not successful, indicate that the items cannot be compared * this way. */ if (array_other == NULL) { PyErr_Clear(); Py_INCREF(Py_NotImplemented); return Py_NotImplemented; } _res = PyObject_RichCompareBool( (PyObject *)PyArray_DESCR(self), (PyObject *)PyArray_DESCR(array_other), Py_EQ); if (_res < 0) { Py_DECREF(result); Py_DECREF(array_other); return NULL; } if (_res) { Py_DECREF(result); result = _void_compare(self, array_other, cmp_op); Py_DECREF(array_other); } return result; } if (result == NULL) { PyErr_Clear(); Py_INCREF(Py_NotImplemented); return Py_NotImplemented; } break; case Py_GT: result = PyArray_GenericBinaryFunction(self, other, n_ops.greater); break; case Py_GE: result = PyArray_GenericBinaryFunction(self, other, n_ops.greater_equal); break; default: result = Py_NotImplemented; Py_INCREF(result); } if (result == Py_NotImplemented) { /* Try to handle string comparisons */ if (PyArray_TYPE(self) == NPY_OBJECT) { return result; } array_other = (PyArrayObject *)PyArray_FromObject(other, 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 *) array_other, cmp_op, 0); } Py_DECREF(array_other); } return result; } /*NUMPY_API */ NPY_NO_EXPORT int PyArray_ElementStrides(PyObject *obj) { PyArrayObject *arr; int itemsize; int i, ndim; npy_intp *strides; if (!PyArray_Check(obj)) { return 0; } arr = (PyArrayObject *)obj; itemsize = PyArray_ITEMSIZE(arr); ndim = PyArray_NDIM(arr); strides = PyArray_STRIDES(arr); for (i = 0; i < ndim; i++) { if ((strides[i] % itemsize) != 0) { return 0; } } return 1; } /* * This routine checks to see if newstrides (of length nd) will not * ever be able to walk outside of the memory implied numbytes and offset. * * The available memory is assumed to start at -offset and proceed * to numbytes-offset. The strides are checked to ensure * that accessing memory using striding will not try to reach beyond * this memory for any of the axes. * * If numbytes is 0 it will be calculated using the dimensions and * element-size. * * This function checks for walking beyond the beginning and right-end * of the buffer and therefore works for any integer stride (positive * or negative). */ /*NUMPY_API*/ NPY_NO_EXPORT npy_bool PyArray_CheckStrides(int elsize, int nd, npy_intp numbytes, npy_intp offset, npy_intp *dims, npy_intp *newstrides) { npy_intp begin, end; npy_intp lower_offset; npy_intp upper_offset; if (numbytes == 0) { numbytes = PyArray_MultiplyList(dims, nd) * elsize; } begin = -offset; end = numbytes - offset; offset_bounds_from_strides(elsize, nd, dims, newstrides, &lower_offset, &upper_offset); if ((upper_offset > end) || (lower_offset < begin)) { return NPY_FALSE; } return NPY_TRUE; } static PyObject * array_new(PyTypeObject *subtype, PyObject *args, PyObject *kwds) { static char *kwlist[] = {"shape", "dtype", "buffer", "offset", "strides", "order", NULL}; PyArray_Descr *descr = NULL; int itemsize; PyArray_Dims dims = {NULL, 0}; PyArray_Dims strides = {NULL, 0}; PyArray_Chunk buffer; npy_longlong offset = 0; NPY_ORDER order = NPY_CORDER; int is_f_order = 0; PyArrayObject *ret; buffer.ptr = NULL; /* * Usually called with shape and type but can also be called with buffer, * strides, and swapped info For now, let's just use this to create an * empty, contiguous array of a specific type and shape. */ if (!PyArg_ParseTupleAndKeywords(args, kwds, "O&|O&O&LO&O&", kwlist, PyArray_IntpConverter, &dims, PyArray_DescrConverter, &descr, PyArray_BufferConverter, &buffer, &offset, &PyArray_IntpConverter, &strides, &PyArray_OrderConverter, &order)) { goto fail; } if (order == NPY_FORTRANORDER) { is_f_order = 1; } if (descr == NULL) { descr = PyArray_DescrFromType(NPY_DEFAULT_TYPE); } itemsize = descr->elsize; if (itemsize == 0) { PyErr_SetString(PyExc_ValueError, "data-type with unspecified variable length"); goto fail; } if (strides.ptr != NULL) { npy_intp nb, off; if (strides.len != dims.len) { PyErr_SetString(PyExc_ValueError, "strides, if given, must be " \ "the same length as shape"); goto fail; } if (buffer.ptr == NULL) { nb = 0; off = 0; } else { nb = buffer.len; off = (npy_intp) offset; } if (!PyArray_CheckStrides(itemsize, dims.len, nb, off, dims.ptr, strides.ptr)) { PyErr_SetString(PyExc_ValueError, "strides is incompatible " \ "with shape of requested " \ "array and size of buffer"); goto fail; } } if (buffer.ptr == NULL) { ret = (PyArrayObject *) PyArray_NewFromDescr(subtype, descr, (int)dims.len, dims.ptr, strides.ptr, NULL, is_f_order, NULL); if (ret == NULL) { descr = NULL; goto fail; } if (PyDataType_FLAGCHK(descr, NPY_ITEM_HASOBJECT)) { /* place Py_None in object positions */ PyArray_FillObjectArray(ret, Py_None); if (PyErr_Occurred()) { descr = NULL; goto fail; } } } else { /* buffer given -- use it */ if (dims.len == 1 && dims.ptr[0] == -1) { dims.ptr[0] = (buffer.len-(npy_intp)offset) / itemsize; } else if ((strides.ptr == NULL) && (buffer.len < (offset + (((npy_intp)itemsize)* PyArray_MultiplyList(dims.ptr, dims.len))))) { PyErr_SetString(PyExc_TypeError, "buffer is too small for " \ "requested array"); goto fail; } /* get writeable and aligned */ if (is_f_order) { buffer.flags |= NPY_ARRAY_F_CONTIGUOUS; } ret = (PyArrayObject *)\ PyArray_NewFromDescr(subtype, descr, dims.len, dims.ptr, strides.ptr, offset + (char *)buffer.ptr, buffer.flags, NULL); if (ret == NULL) { descr = NULL; goto fail; } PyArray_UpdateFlags(ret, NPY_ARRAY_UPDATE_ALL); Py_INCREF(buffer.base); if (PyArray_SetBaseObject(ret, buffer.base) < 0) { Py_DECREF(ret); ret = NULL; goto fail; } } PyDimMem_FREE(dims.ptr); if (strides.ptr) { PyDimMem_FREE(strides.ptr); } return (PyObject *)ret; fail: Py_XDECREF(descr); if (dims.ptr) { PyDimMem_FREE(dims.ptr); } if (strides.ptr) { PyDimMem_FREE(strides.ptr); } return NULL; } static PyObject * array_iter(PyArrayObject *arr) { if (PyArray_NDIM(arr) == 0) { PyErr_SetString(PyExc_TypeError, "iteration over a 0-d array"); return NULL; } return PySeqIter_New((PyObject *)arr); } static PyObject * array_alloc(PyTypeObject *type, Py_ssize_t NPY_UNUSED(nitems)) { PyObject *obj; /* nitems will always be 0 */ obj = (PyObject *)PyArray_malloc(type->tp_basicsize); PyObject_Init(obj, type); return obj; } NPY_NO_EXPORT PyTypeObject PyArray_Type = { #if defined(NPY_PY3K) PyVarObject_HEAD_INIT(NULL, 0) #else PyObject_HEAD_INIT(NULL) 0, /* ob_size */ #endif "numpy.ndarray", /* tp_name */ NPY_SIZEOF_PYARRAYOBJECT, /* tp_basicsize */ 0, /* tp_itemsize */ /* methods */ (destructor)array_dealloc, /* tp_dealloc */ (printfunc)NULL, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ #if defined(NPY_PY3K) 0, /* tp_reserved */ #else 0, /* tp_compare */ #endif (reprfunc)array_repr, /* tp_repr */ &array_as_number, /* tp_as_number */ &array_as_sequence, /* tp_as_sequence */ &array_as_mapping, /* tp_as_mapping */ (hashfunc)0, /* tp_hash */ (ternaryfunc)0, /* tp_call */ (reprfunc)array_str, /* tp_str */ (getattrofunc)0, /* tp_getattro */ (setattrofunc)0, /* tp_setattro */ &array_as_buffer, /* tp_as_buffer */ (Py_TPFLAGS_DEFAULT #if !defined(NPY_PY3K) | Py_TPFLAGS_CHECKTYPES | Py_TPFLAGS_HAVE_NEWBUFFER #endif | Py_TPFLAGS_BASETYPE), /* tp_flags */ 0, /* tp_doc */ (traverseproc)0, /* tp_traverse */ (inquiry)0, /* tp_clear */ (richcmpfunc)array_richcompare, /* tp_richcompare */ offsetof(PyArrayObject_fields, weakreflist), /* tp_weaklistoffset */ (getiterfunc)array_iter, /* tp_iter */ (iternextfunc)0, /* tp_iternext */ array_methods, /* tp_methods */ 0, /* tp_members */ array_getsetlist, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc)0, /* tp_init */ array_alloc, /* tp_alloc */ (newfunc)array_new, /* 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 */ 0, /* tp_version_tag */ }; numpy-1.8.2/numpy/core/src/multiarray/shape.c0000664000175100017510000007706612370216243022370 0ustar vagrantvagrant00000000000000#define PY_SSIZE_T_CLEAN #include #include "structmember.h" #define NPY_NO_DEPRECATED_API NPY_API_VERSION #define _MULTIARRAYMODULE #include "numpy/arrayobject.h" #include "numpy/arrayscalars.h" #include "numpy/npy_math.h" #include "npy_config.h" #include "npy_pycompat.h" #include "ctors.h" #include "shape.h" static int _fix_unknown_dimension(PyArray_Dims *newshape, npy_intp s_original); static int _attempt_nocopy_reshape(PyArrayObject *self, int newnd, npy_intp* newdims, npy_intp *newstrides, int is_f_order); static void _putzero(char *optr, PyObject *zero, PyArray_Descr *dtype); /*NUMPY_API * Resize (reallocate data). Only works if nothing else is referencing this * array and it is contiguous. If refcheck is 0, then the reference count is * not checked and assumed to be 1. You still must own this data and have no * weak-references and no base object. */ NPY_NO_EXPORT PyObject * PyArray_Resize(PyArrayObject *self, PyArray_Dims *newshape, int refcheck, NPY_ORDER order) { npy_intp oldsize, newsize; int new_nd=newshape->len, k, n, elsize; int refcnt; npy_intp* new_dimensions=newshape->ptr; npy_intp new_strides[NPY_MAXDIMS]; size_t sd; npy_intp *dimptr; char *new_data; npy_intp largest; if (!PyArray_ISONESEGMENT(self)) { PyErr_SetString(PyExc_ValueError, "resize only works on single-segment arrays"); return NULL; } if (PyArray_DESCR(self)->elsize == 0) { PyErr_SetString(PyExc_ValueError, "Bad data-type size."); return NULL; } newsize = 1; largest = NPY_MAX_INTP / PyArray_DESCR(self)->elsize; for(k = 0; k < new_nd; k++) { if (new_dimensions[k] == 0) { break; } if (new_dimensions[k] < 0) { PyErr_SetString(PyExc_ValueError, "negative dimensions not allowed"); return NULL; } newsize *= new_dimensions[k]; if (newsize <= 0 || newsize > largest) { return PyErr_NoMemory(); } } oldsize = PyArray_SIZE(self); if (oldsize != newsize) { if (!(PyArray_FLAGS(self) & NPY_ARRAY_OWNDATA)) { PyErr_SetString(PyExc_ValueError, "cannot resize this array: it does not own its data"); return NULL; } if (refcheck) { refcnt = PyArray_REFCOUNT(self); } else { refcnt = 1; } if ((refcnt > 2) || (PyArray_BASE(self) != NULL) || (((PyArrayObject_fields *)self)->weakreflist != NULL)) { PyErr_SetString(PyExc_ValueError, "cannot resize an array references or is referenced\n"\ "by another array in this way. Use the resize function"); return NULL; } if (newsize == 0) { sd = PyArray_DESCR(self)->elsize; } else { sd = newsize*PyArray_DESCR(self)->elsize; } /* Reallocate space if needed */ new_data = PyDataMem_RENEW(PyArray_DATA(self), sd); if (new_data == NULL) { PyErr_SetString(PyExc_MemoryError, "cannot allocate memory for array"); return NULL; } ((PyArrayObject_fields *)self)->data = new_data; } if ((newsize > oldsize) && PyArray_ISWRITEABLE(self)) { /* Fill new memory with zeros */ elsize = PyArray_DESCR(self)->elsize; if (PyDataType_FLAGCHK(PyArray_DESCR(self), NPY_ITEM_REFCOUNT)) { PyObject *zero = PyInt_FromLong(0); char *optr; optr = PyArray_BYTES(self) + oldsize*elsize; n = newsize - oldsize; for (k = 0; k < n; k++) { _putzero((char *)optr, zero, PyArray_DESCR(self)); optr += elsize; } Py_DECREF(zero); } else{ memset(PyArray_BYTES(self)+oldsize*elsize, 0, (newsize-oldsize)*elsize); } } if (PyArray_NDIM(self) != new_nd) { /* Different number of dimensions. */ ((PyArrayObject_fields *)self)->nd = new_nd; /* Need new dimensions and strides arrays */ dimptr = PyDimMem_RENEW(PyArray_DIMS(self), 3*new_nd); if (dimptr == NULL) { PyErr_SetString(PyExc_MemoryError, "cannot allocate memory for array"); return NULL; } ((PyArrayObject_fields *)self)->dimensions = dimptr; ((PyArrayObject_fields *)self)->strides = dimptr + new_nd; } /* make new_strides variable */ sd = (size_t) PyArray_DESCR(self)->elsize; sd = (size_t) _array_fill_strides(new_strides, new_dimensions, new_nd, sd, PyArray_FLAGS(self), &(((PyArrayObject_fields *)self)->flags)); memmove(PyArray_DIMS(self), new_dimensions, new_nd*sizeof(npy_intp)); memmove(PyArray_STRIDES(self), new_strides, new_nd*sizeof(npy_intp)); Py_INCREF(Py_None); return Py_None; } /* * Returns a new array * with the new shape from the data * in the old array --- order-perspective depends on order argument. * copy-only-if-necessary */ /*NUMPY_API * New shape for an array */ NPY_NO_EXPORT PyObject * PyArray_Newshape(PyArrayObject *self, PyArray_Dims *newdims, NPY_ORDER order) { npy_intp i; npy_intp *dimensions = newdims->ptr; PyArrayObject *ret; int ndim = newdims->len; npy_bool same, incref = NPY_TRUE; npy_intp *strides = NULL; npy_intp newstrides[NPY_MAXDIMS]; int flags; if (order == NPY_ANYORDER) { order = PyArray_ISFORTRAN(self); } else if (order == NPY_KEEPORDER) { PyErr_SetString(PyExc_ValueError, "order 'K' is not permitted for reshaping"); return NULL; } /* Quick check to make sure anything actually needs to be done */ if (ndim == PyArray_NDIM(self)) { same = NPY_TRUE; i = 0; while (same && i < ndim) { if (PyArray_DIM(self,i) != dimensions[i]) { same=NPY_FALSE; } i++; } if (same) { return PyArray_View(self, NULL, NULL); } } /* * fix any -1 dimensions and check new-dimensions against old size */ if (_fix_unknown_dimension(newdims, PyArray_SIZE(self)) < 0) { return NULL; } /* * sometimes we have to create a new copy of the array * in order to get the right orientation and * because we can't just re-use the buffer with the * data in the order it is in. * NPY_RELAXED_STRIDES_CHECKING: size check is unnecessary when set. */ if ((PyArray_SIZE(self) > 1) && ((order == NPY_CORDER && !PyArray_IS_C_CONTIGUOUS(self)) || (order == NPY_FORTRANORDER && !PyArray_IS_F_CONTIGUOUS(self)))) { int success = 0; success = _attempt_nocopy_reshape(self, ndim, dimensions, newstrides, order); if (success) { /* no need to copy the array after all */ strides = newstrides; } else { PyObject *newcopy; newcopy = PyArray_NewCopy(self, order); if (newcopy == NULL) { return NULL; } incref = NPY_FALSE; self = (PyArrayObject *)newcopy; } } /* We always have to interpret the contiguous buffer correctly */ /* Make sure the flags argument is set. */ flags = PyArray_FLAGS(self); if (ndim > 1) { if (order == NPY_FORTRANORDER) { flags &= ~NPY_ARRAY_C_CONTIGUOUS; flags |= NPY_ARRAY_F_CONTIGUOUS; } else { flags &= ~NPY_ARRAY_F_CONTIGUOUS; flags |= NPY_ARRAY_C_CONTIGUOUS; } } Py_INCREF(PyArray_DESCR(self)); ret = (PyArrayObject *)PyArray_NewFromDescr(Py_TYPE(self), PyArray_DESCR(self), ndim, dimensions, strides, PyArray_DATA(self), flags, (PyObject *)self); if (ret == NULL) { goto fail; } if (incref) { Py_INCREF(self); } if (PyArray_SetBaseObject(ret, (PyObject *)self)) { Py_DECREF(ret); return NULL; } PyArray_UpdateFlags(ret, NPY_ARRAY_C_CONTIGUOUS | NPY_ARRAY_F_CONTIGUOUS); return (PyObject *)ret; fail: if (!incref) { Py_DECREF(self); } return NULL; } /* For back-ward compatability -- Not recommended */ /*NUMPY_API * Reshape */ NPY_NO_EXPORT PyObject * PyArray_Reshape(PyArrayObject *self, PyObject *shape) { PyObject *ret; PyArray_Dims newdims; if (!PyArray_IntpConverter(shape, &newdims)) { return NULL; } ret = PyArray_Newshape(self, &newdims, NPY_CORDER); PyDimMem_FREE(newdims.ptr); return ret; } static void _putzero(char *optr, PyObject *zero, PyArray_Descr *dtype) { if (!PyDataType_FLAGCHK(dtype, NPY_ITEM_REFCOUNT)) { memset(optr, 0, dtype->elsize); } else if (PyDataType_HASFIELDS(dtype)) { PyObject *key, *value, *title = NULL; PyArray_Descr *new; int offset; Py_ssize_t pos = 0; while (PyDict_Next(dtype->fields, &pos, &key, &value)) { if NPY_TITLE_KEY(key, value) { continue; } if (!PyArg_ParseTuple(value, "Oi|O", &new, &offset, &title)) { return; } _putzero(optr + offset, zero, new); } } else { Py_INCREF(zero); NPY_COPY_PYOBJECT_PTR(optr, &zero); } return; } /* * attempt to reshape an array without copying data * * This function should correctly handle all reshapes, including * axes of length 1. Zero strides should work but are untested. * * If a copy is needed, returns 0 * If no copy is needed, returns 1 and fills newstrides * with appropriate strides * * The "is_f_order" argument describes how the array should be viewed * during the reshape, not how it is stored in memory (that * information is in PyArray_STRIDES(self)). * * If some output dimensions have length 1, the strides assigned to * them are arbitrary. In the current implementation, they are the * stride of the next-fastest index. */ static int _attempt_nocopy_reshape(PyArrayObject *self, int newnd, npy_intp* newdims, npy_intp *newstrides, int is_f_order) { int oldnd; npy_intp olddims[NPY_MAXDIMS]; npy_intp oldstrides[NPY_MAXDIMS]; npy_intp np, op, last_stride; int oi, oj, ok, ni, nj, nk; oldnd = 0; /* * Remove axes with dimension 1 from the old array. They have no effect * but would need special cases since their strides do not matter. */ for (oi = 0; oi < PyArray_NDIM(self); oi++) { if (PyArray_DIMS(self)[oi]!= 1) { olddims[oldnd] = PyArray_DIMS(self)[oi]; oldstrides[oldnd] = PyArray_STRIDES(self)[oi]; oldnd++; } } /* fprintf(stderr, "_attempt_nocopy_reshape( ("); for (oi=0; oi ("); for (ni=0; ni ni; nk--) { newstrides[nk - 1] = newstrides[nk]*newdims[nk]; } } ni = nj++; oi = oj++; } /* * Set strides corresponding to trailing 1s of the new shape. */ if (ni >= 1) { last_stride = newstrides[ni - 1]; } else { last_stride = PyArray_ITEMSIZE(self); } if (is_f_order) { last_stride *= newdims[ni - 1]; } for (nk = ni; nk < newnd; nk++) { newstrides[nk] = last_stride; } /* fprintf(stderr, "success: _attempt_nocopy_reshape ("); for (oi=0; oi ("); for (ni=0; niptr; n = newshape->len; s_known = 1; i_unknown = -1; for (i = 0; i < n; i++) { if (dimensions[i] < 0) { if (i_unknown == -1) { i_unknown = i; } else { PyErr_SetString(PyExc_ValueError, "can only specify one" \ " unknown dimension"); return -1; } } else { s_known *= dimensions[i]; } } if (i_unknown >= 0) { if ((s_known == 0) || (s_original % s_known != 0)) { PyErr_SetString(PyExc_ValueError, msg); return -1; } dimensions[i_unknown] = s_original/s_known; } else { if (s_original != s_known) { PyErr_SetString(PyExc_ValueError, msg); return -1; } } return 0; } /*NUMPY_API * * return a new view of the array object with all of its unit-length * dimensions squeezed out if needed, otherwise * return the same array. */ NPY_NO_EXPORT PyObject * PyArray_Squeeze(PyArrayObject *self) { PyArrayObject *ret; npy_bool unit_dims[NPY_MAXDIMS]; int idim, ndim, any_ones; npy_intp *shape; ndim = PyArray_NDIM(self); shape = PyArray_SHAPE(self); any_ones = 0; for (idim = 0; idim < ndim; ++idim) { if (shape[idim] == 1) { unit_dims[idim] = 1; any_ones = 1; } else { unit_dims[idim] = 0; } } /* If there were no ones to squeeze out, return the same array */ if (!any_ones) { Py_INCREF(self); return (PyObject *)self; } ret = (PyArrayObject *)PyArray_View(self, NULL, &PyArray_Type); if (ret == NULL) { return NULL; } PyArray_RemoveAxesInPlace(ret, unit_dims); /* * If self isn't not a base class ndarray, call its * __array_wrap__ method */ if (Py_TYPE(self) != &PyArray_Type) { PyArrayObject *tmp = PyArray_SubclassWrap(self, ret); Py_DECREF(ret); ret = tmp; } return (PyObject *)ret; } /* * Just like PyArray_Squeeze, but allows the caller to select * a subset of the size-one dimensions to squeeze out. */ NPY_NO_EXPORT PyObject * PyArray_SqueezeSelected(PyArrayObject *self, npy_bool *axis_flags) { PyArrayObject *ret; int idim, ndim, any_ones; npy_intp *shape; ndim = PyArray_NDIM(self); shape = PyArray_SHAPE(self); /* Verify that the axes requested are all of size one */ any_ones = 0; for (idim = 0; idim < ndim; ++idim) { if (axis_flags[idim] != 0) { if (shape[idim] == 1) { any_ones = 1; } else { PyErr_SetString(PyExc_ValueError, "cannot select an axis to squeeze out " "which has size greater than one"); return NULL; } } } /* If there were no axes to squeeze out, return the same array */ if (!any_ones) { Py_INCREF(self); return (PyObject *)self; } ret = (PyArrayObject *)PyArray_View(self, NULL, &PyArray_Type); if (ret == NULL) { return NULL; } PyArray_RemoveAxesInPlace(ret, axis_flags); /* * If self isn't not a base class ndarray, call its * __array_wrap__ method */ if (Py_TYPE(self) != &PyArray_Type) { PyArrayObject *tmp = PyArray_SubclassWrap(self, ret); Py_DECREF(ret); ret = tmp; } return (PyObject *)ret; } /*NUMPY_API * SwapAxes */ NPY_NO_EXPORT PyObject * PyArray_SwapAxes(PyArrayObject *ap, int a1, int a2) { PyArray_Dims new_axes; npy_intp dims[NPY_MAXDIMS]; int n, i, val; PyObject *ret; if (a1 == a2) { Py_INCREF(ap); return (PyObject *)ap; } n = PyArray_NDIM(ap); if (n <= 1) { Py_INCREF(ap); return (PyObject *)ap; } if (a1 < 0) { a1 += n; } if (a2 < 0) { a2 += n; } if ((a1 < 0) || (a1 >= n)) { PyErr_SetString(PyExc_ValueError, "bad axis1 argument to swapaxes"); return NULL; } if ((a2 < 0) || (a2 >= n)) { PyErr_SetString(PyExc_ValueError, "bad axis2 argument to swapaxes"); return NULL; } new_axes.ptr = dims; new_axes.len = n; for (i = 0; i < n; i++) { if (i == a1) { val = a2; } else if (i == a2) { val = a1; } else { val = i; } new_axes.ptr[i] = val; } ret = PyArray_Transpose(ap, &new_axes); return ret; } /*NUMPY_API * Return Transpose. */ NPY_NO_EXPORT PyObject * PyArray_Transpose(PyArrayObject *ap, PyArray_Dims *permute) { npy_intp *axes, axis; npy_intp i, n; npy_intp permutation[NPY_MAXDIMS], reverse_permutation[NPY_MAXDIMS]; PyArrayObject *ret = NULL; int flags; if (permute == NULL) { n = PyArray_NDIM(ap); for (i = 0; i < n; i++) { permutation[i] = n-1-i; } } else { n = permute->len; axes = permute->ptr; if (n != PyArray_NDIM(ap)) { PyErr_SetString(PyExc_ValueError, "axes don't match array"); return NULL; } for (i = 0; i < n; i++) { reverse_permutation[i] = -1; } for (i = 0; i < n; i++) { axis = axes[i]; if (axis < 0) { axis = PyArray_NDIM(ap) + axis; } if (axis < 0 || axis >= PyArray_NDIM(ap)) { PyErr_SetString(PyExc_ValueError, "invalid axis for this array"); return NULL; } if (reverse_permutation[axis] != -1) { PyErr_SetString(PyExc_ValueError, "repeated axis in transpose"); return NULL; } reverse_permutation[axis] = i; permutation[i] = axis; } } flags = PyArray_FLAGS(ap); /* * this allocates memory for dimensions and strides (but fills them * incorrectly), sets up descr, and points data at PyArray_DATA(ap). */ Py_INCREF(PyArray_DESCR(ap)); ret = (PyArrayObject *) PyArray_NewFromDescr(Py_TYPE(ap), PyArray_DESCR(ap), n, PyArray_DIMS(ap), NULL, PyArray_DATA(ap), flags, (PyObject *)ap); if (ret == NULL) { return NULL; } /* point at true owner of memory: */ Py_INCREF(ap); if (PyArray_SetBaseObject(ret, (PyObject *)ap) < 0) { Py_DECREF(ret); return NULL; } /* fix the dimensions and strides of the return-array */ for (i = 0; i < n; i++) { 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); return (PyObject *)ret; } /* * 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) { npy_intp astride = ((const npy_stride_sort_item *)a)->stride, bstride = ((const npy_stride_sort_item *)b)->stride; /* Sort the absolute value of the strides */ if (astride < 0) { astride = -astride; } if (bstride < 0) { bstride = -bstride; } if (astride == bstride) { /* * Make the qsort stable by next comparing the perm order. * (Note that two perm entries will never be equal) */ npy_intp aperm = ((const npy_stride_sort_item *)a)->perm, bperm = ((const npy_stride_sort_item *)b)->perm; return (aperm < bperm) ? -1 : 1; } if (astride > bstride) { return -1; } return 1; } /*NUMPY_API * * This function populates the first ndim elements * of strideperm with sorted descending by their absolute values. * For example, the stride array (4, -2, 12) becomes * [(2, 12), (0, 4), (1, -2)]. */ NPY_NO_EXPORT void PyArray_CreateSortedStridePerm(int ndim, npy_intp *strides, npy_stride_sort_item *out_strideperm) { int i; /* Set up the strideperm values */ for (i = 0; i < ndim; ++i) { out_strideperm[i].perm = i; out_strideperm[i].stride = strides[i]; } /* Sort them */ qsort(out_strideperm, ndim, sizeof(npy_stride_sort_item), &_npy_stride_sort_item_comparator); } static NPY_INLINE npy_intp s_intp_abs(npy_intp x) { return (x < 0) ? -x : x; } /* * Creates a sorted stride perm matching the KEEPORDER behavior * of the NpyIter object. Because this operates based on multiple * input strides, the 'stride' member of the npy_stride_sort_item * would be useless and we simply argsort a list of indices instead. * * The caller should have already validated that 'ndim' matches for * every array in the arrays list. */ NPY_NO_EXPORT void PyArray_CreateMultiSortedStridePerm(int narrays, PyArrayObject **arrays, int ndim, int *out_strideperm) { int i0, i1, ipos, ax_j0, ax_j1, iarrays; /* Initialize the strideperm values to the identity. */ for (i0 = 0; i0 < ndim; ++i0) { out_strideperm[i0] = i0; } /* * This is the same as the custom stable insertion sort in * the NpyIter object, but sorting in the reverse order as * in the iterator. The iterator sorts from smallest stride * to biggest stride (Fortran order), whereas here we sort * from biggest stride to smallest stride (C order). */ for (i0 = 1; i0 < ndim; ++i0) { ipos = i0; ax_j0 = out_strideperm[i0]; for (i1 = i0 - 1; i1 >= 0; --i1) { int ambig = 1, shouldswap = 0; ax_j1 = out_strideperm[i1]; for (iarrays = 0; iarrays < narrays; ++iarrays) { if (PyArray_SHAPE(arrays[iarrays])[ax_j0] != 1 && PyArray_SHAPE(arrays[iarrays])[ax_j1] != 1) { if (s_intp_abs(PyArray_STRIDES(arrays[iarrays])[ax_j0]) <= s_intp_abs(PyArray_STRIDES(arrays[iarrays])[ax_j1])) { /* * Set swap even if it's not ambiguous already, * because in the case of conflicts between * different operands, C-order wins. */ shouldswap = 0; } else { /* Only set swap if it's still ambiguous */ if (ambig) { shouldswap = 1; } } /* * A comparison has been done, so it's * no longer ambiguous */ ambig = 0; } } /* * If the comparison was unambiguous, either shift * 'ipos' to 'i1' or stop looking for an insertion point */ if (!ambig) { if (shouldswap) { ipos = i1; } else { break; } } } /* Insert out_strideperm[i0] into the right place */ if (ipos != i0) { for (i1 = i0; i1 > ipos; --i1) { out_strideperm[i1] = out_strideperm[i1-1]; } out_strideperm[ipos] = ax_j0; } } } /*NUMPY_API * Ravel * Returns a contiguous array */ NPY_NO_EXPORT PyObject * PyArray_Ravel(PyArrayObject *arr, NPY_ORDER order) { PyArray_Dims newdim = {NULL,1}; npy_intp val[1] = {-1}; newdim.ptr = val; if (order == NPY_ANYORDER) { order = PyArray_ISFORTRAN(arr) ? NPY_FORTRANORDER : NPY_CORDER; } else if (order == NPY_KEEPORDER) { if (PyArray_IS_C_CONTIGUOUS(arr)) { order = NPY_CORDER; } else if (PyArray_IS_F_CONTIGUOUS(arr)) { order = NPY_FORTRANORDER; } } if (order == NPY_CORDER && PyArray_IS_C_CONTIGUOUS(arr)) { return PyArray_Newshape(arr, &newdim, NPY_CORDER); } else if (order == NPY_FORTRANORDER && PyArray_IS_F_CONTIGUOUS(arr)) { return PyArray_Newshape(arr, &newdim, NPY_FORTRANORDER); } /* For KEEPORDER, check if we can make a flattened view */ else if (order == NPY_KEEPORDER) { npy_stride_sort_item strideperm[NPY_MAXDIMS]; npy_intp stride; int i, ndim = PyArray_NDIM(arr); PyArray_CreateSortedStridePerm(PyArray_NDIM(arr), PyArray_STRIDES(arr), strideperm); stride = strideperm[ndim-1].stride; for (i = ndim-1; i >= 0; --i) { if (strideperm[i].stride != stride) { break; } stride *= PyArray_DIM(arr, strideperm[i].perm); } /* If all the strides matched a contiguous layout, return a view */ if (i < 0) { PyArrayObject *ret; stride = strideperm[ndim-1].stride; val[0] = PyArray_SIZE(arr); Py_INCREF(PyArray_DESCR(arr)); ret = (PyArrayObject *)PyArray_NewFromDescr(Py_TYPE(arr), PyArray_DESCR(arr), 1, val, &stride, PyArray_BYTES(arr), PyArray_FLAGS(arr), (PyObject *)arr); if (ret == NULL) { return NULL; } PyArray_UpdateFlags(ret, NPY_ARRAY_C_CONTIGUOUS|NPY_ARRAY_F_CONTIGUOUS); Py_INCREF(arr); if (PyArray_SetBaseObject(ret, (PyObject *)arr) < 0) { Py_DECREF(ret); return NULL; } return (PyObject *)ret; } } return PyArray_Flatten(arr, order); } /*NUMPY_API * Flatten */ NPY_NO_EXPORT PyObject * PyArray_Flatten(PyArrayObject *a, NPY_ORDER order) { PyArrayObject *ret; npy_intp size; if (order == NPY_ANYORDER) { order = PyArray_ISFORTRAN(a) ? NPY_FORTRANORDER : NPY_CORDER; } size = PyArray_SIZE(a); Py_INCREF(PyArray_DESCR(a)); ret = (PyArrayObject *)PyArray_NewFromDescr(Py_TYPE(a), PyArray_DESCR(a), 1, &size, NULL, NULL, 0, (PyObject *)a); if (ret == NULL) { return NULL; } if (PyArray_CopyAsFlat(ret, a, order) < 0) { Py_DECREF(ret); return NULL; } return (PyObject *)ret; } /* See shape.h for parameters documentation */ NPY_NO_EXPORT PyObject * build_shape_string(npy_intp n, npy_intp *vals) { 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("()"); } 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(")"); PyUString_ConcatAndDel(&ret, tmp); return ret; } /*NUMPY_API * * Removes the axes flagged as True from the array, * modifying it in place. If an axis flagged for removal * has a shape entry bigger than one, this effectively selects * index zero for that axis. * * WARNING: If an axis flagged for removal has a shape equal to zero, * the array will point to invalid memory. The caller must * validate this! * If an axis flagged for removal has a shape larger then one, * the aligned flag (and in the future the contiguous flags), * may need explicite update. * (check also NPY_RELAXED_STRIDES_CHECKING) * * For example, this can be used to remove the reduction axes * from a reduction result once its computation is complete. */ NPY_NO_EXPORT void PyArray_RemoveAxesInPlace(PyArrayObject *arr, npy_bool *flags) { PyArrayObject_fields *fa = (PyArrayObject_fields *)arr; npy_intp *shape = fa->dimensions, *strides = fa->strides; int idim, ndim = fa->nd, idim_out = 0; /* Compress the dimensions and strides */ for (idim = 0; idim < ndim; ++idim) { if (!flags[idim]) { shape[idim_out] = shape[idim]; strides[idim_out] = strides[idim]; ++idim_out; } } /* The final number of dimensions */ fa->nd = idim_out; /* May not be necessary for NPY_RELAXED_STRIDES_CHECKING (see comment) */ PyArray_UpdateFlags(arr, NPY_ARRAY_C_CONTIGUOUS | NPY_ARRAY_F_CONTIGUOUS); } numpy-1.8.2/numpy/core/src/multiarray/datetime_strings.c0000664000175100017510000014240312370216242024620 0ustar vagrantvagrant00000000000000/* * This file implements string parsing and creation for NumPy datetime. * * Written by Mark Wiebe (mwwiebe@gmail.com) * Copyright (c) 2011 by Enthought, Inc. * * See LICENSE.txt for the license. */ #define PY_SSIZE_T_CLEAN #include #include #define NPY_NO_DEPRECATED_API NPY_API_VERSION #define _MULTIARRAYMODULE #include #include "npy_config.h" #include "npy_pycompat.h" #include "numpy/arrayscalars.h" #include "methods.h" #include "_datetime.h" #include "datetime_strings.h" /* * Platform-specific time_t typedef. Some platforms use 32 bit, some use 64 bit * and we just use the default with the exception of mingw, where we must use * 64 bit because MSVCRT version 9 does not have the (32 bit) localtime() * symbol, so we need to use the 64 bit version [1]. * * [1] http://thread.gmane.org/gmane.comp.gnu.mingw.user/27011 */ #if defined(NPY_MINGW_USE_CUSTOM_MSVCR) typedef __time64_t NPY_TIME_T; #else typedef time_t NPY_TIME_T; #endif /* * Wraps `localtime` functionality for multiple platforms. This * converts a time value to a time structure in the local timezone. * If size(NPY_TIME_T) == 4, then years must be between 1970 and 2038. If * size(NPY_TIME_T) == 8, then years must be later than 1970. If the years are * not in this range, then get_localtime() will fail on some platforms. * * Returns 0 on success, -1 on failure. * * Notes: * 1) If NPY_TIME_T is 32 bit (i.e. sizeof(NPY_TIME_T) == 4), then the * maximum year it can represent is 2038 (see [1] for more details). Trying * to use a higher date like 2041 in the 32 bit "ts" variable below will * typically result in "ts" being a negative number (corresponding roughly * to a year ~ 1905). If NPY_TIME_T is 64 bit, then there is no such * problem in practice. * 2) If the "ts" argument to localtime() is negative, it represents * years < 1970 both for 32 and 64 bits (for 32 bits the earliest year it can * represent is 1901, while 64 bits can represent much earlier years). * 3) On Linux, localtime() works for negative "ts". On Windows and in Wine, * localtime() as well as the localtime_s() and _localtime64_s() functions * will fail for any negative "ts" and return a nonzero exit number * (localtime_s, _localtime64_s) or NULL (localtime). This behavior is the * same for both 32 and 64 bits. * * From this it follows that get_localtime() is only guaranteed to work * correctly on all platforms for years between 1970 and 2038 for 32bit * NPY_TIME_T and years higher than 1970 for 64bit NPY_TIME_T. For * multiplatform code, get_localtime() should never be used outside of this * range. * * [1] http://en.wikipedia.org/wiki/Year_2038_problem */ static int get_localtime(NPY_TIME_T *ts, struct tm *tms) { char *func_name = ""; #if defined(_WIN32) #if defined(_MSC_VER) && (_MSC_VER >= 1400) if (localtime_s(tms, ts) != 0) { func_name = "localtime_s"; goto fail; } #elif defined(NPY_MINGW_USE_CUSTOM_MSVCR) if (_localtime64_s(tms, ts) != 0) { func_name = "_localtime64_s"; goto fail; } #else struct tm *tms_tmp; tms_tmp = localtime(ts); if (tms_tmp == NULL) { func_name = "localtime"; goto fail; } memcpy(tms, tms_tmp, sizeof(struct tm)); #endif #else if (localtime_r(ts, tms) == NULL) { func_name = "localtime_r"; goto fail; } #endif return 0; fail: PyErr_Format(PyExc_OSError, "Failed to use '%s' to convert " "to a local time", func_name); return -1; } /* * Wraps `gmtime` functionality for multiple platforms. This * converts a time value to a time structure in UTC. * * Returns 0 on success, -1 on failure. */ static int get_gmtime(NPY_TIME_T *ts, struct tm *tms) { char *func_name = ""; #if defined(_WIN32) #if defined(_MSC_VER) && (_MSC_VER >= 1400) if (gmtime_s(tms, ts) != 0) { func_name = "gmtime_s"; goto fail; } #elif defined(NPY_MINGW_USE_CUSTOM_MSVCR) if (_gmtime64_s(tms, ts) != 0) { func_name = "_gmtime64_s"; goto fail; } #else struct tm *tms_tmp; tms_tmp = gmtime(ts); if (tms_tmp == NULL) { func_name = "gmtime"; goto fail; } memcpy(tms, tms_tmp, sizeof(struct tm)); #endif #else if (gmtime_r(ts, tms) == NULL) { func_name = "gmtime_r"; goto fail; } #endif return 0; fail: PyErr_Format(PyExc_OSError, "Failed to use '%s' to convert " "to a UTC time", func_name); return -1; } /* * Wraps `mktime` functionality for multiple platforms. This * converts a local time struct to an UTC value. * * Returns timestamp on success, -1 on failure. */ static NPY_TIME_T get_mktime(struct tm *tms) { char *func_name = ""; NPY_TIME_T ts; #if defined(NPY_MINGW_USE_CUSTOM_MSVCR) ts = _mktime64(tms); if (ts == -1) { func_name = "_mktime64"; goto fail; } #else ts = mktime(tms); if (ts == -1) { func_name = "mktime"; goto fail; } #endif return ts; fail: PyErr_Format(PyExc_OSError, "Failed to use '%s' to convert " "local time to UTC", func_name); return -1; } /* * Converts a datetimestruct in UTC to a datetimestruct in local time, * also returning the timezone offset applied. This function works for any year * > 1970 on all platforms and both 32 and 64 bits. If the year < 1970, then it * will fail on some platforms. * * Returns 0 on success, -1 on failure. */ static int convert_datetimestruct_utc_to_local(npy_datetimestruct *out_dts_local, const npy_datetimestruct *dts_utc, int *out_timezone_offset) { NPY_TIME_T rawtime = 0, localrawtime; struct tm tm_; npy_int64 year_correction = 0; /* Make a copy of the input 'dts' to modify */ *out_dts_local = *dts_utc; /* * For 32 bit NPY_TIME_T, the get_localtime() function does not work for * years later than 2038, see the comments above get_localtime(). So if the * year >= 2038, we instead call get_localtime() for the year 2036 or 2037 * (depending on the leap year) which must work and at the end we add the * 'year_correction' back. */ if (sizeof(NPY_TIME_T) == 4 && out_dts_local->year >= 2038) { if (is_leapyear(out_dts_local->year)) { /* 2036 is a leap year */ year_correction = out_dts_local->year - 2036; out_dts_local->year -= year_correction; /* = 2036 */ } else { /* 2037 is not a leap year */ year_correction = out_dts_local->year - 2037; out_dts_local->year -= year_correction; /* = 2037 */ } } /* * Convert everything in 'dts' to a time_t, to minutes precision. * This is POSIX time, which skips leap-seconds, but because * we drop the seconds value from the npy_datetimestruct, everything * is ok for this operation. */ rawtime = (NPY_TIME_T)get_datetimestruct_days(out_dts_local) * 24 * 60 * 60; rawtime += dts_utc->hour * 60 * 60; rawtime += dts_utc->min * 60; /* localtime converts a 'time_t' into a local 'struct tm' */ if (get_localtime(&rawtime, &tm_) < 0) { /* This should only fail if year < 1970 on some platforms. */ return -1; } /* Copy back all the values except seconds */ out_dts_local->min = tm_.tm_min; out_dts_local->hour = tm_.tm_hour; out_dts_local->day = tm_.tm_mday; out_dts_local->month = tm_.tm_mon + 1; out_dts_local->year = tm_.tm_year + 1900; /* Extract the timezone offset that was applied */ rawtime /= 60; localrawtime = (NPY_TIME_T)get_datetimestruct_days(out_dts_local) * 24 * 60; localrawtime += out_dts_local->hour * 60; localrawtime += out_dts_local->min; *out_timezone_offset = localrawtime - rawtime; /* Reapply the year 2038 year correction */ out_dts_local->year += year_correction; return 0; } /* * Converts a datetimestruct in local time to a datetimestruct in UTC. * * Returns 0 on success, -1 on failure. */ static int convert_datetimestruct_local_to_utc(npy_datetimestruct *out_dts_utc, const npy_datetimestruct *dts_local) { npy_int64 year_correction = 0; /* Make a copy of the input 'dts' to modify */ *out_dts_utc = *dts_local; /* * For 32 bit NPY_TIME_T, the get_mktime()/get_gmtime() functions do not * work for years later than 2038. So if the year >= 2038, we instead call * get_mktime()/get_gmtime() for the year 2036 or 2037 (depending on the * leap year) which must work and at the end we add the 'year_correction' * back. */ if (sizeof(NPY_TIME_T) == 4 && out_dts_utc->year >= 2038) { if (is_leapyear(out_dts_utc->year)) { /* 2036 is a leap year */ year_correction = out_dts_utc->year - 2036; out_dts_utc->year -= year_correction; /* = 2036 */ } else { /* 2037 is not a leap year */ year_correction = out_dts_utc->year - 2037; out_dts_utc->year -= year_correction; /* = 2037 */ } } /* * ISO 8601 states to treat date-times without a timezone offset * or 'Z' for UTC as local time. The C standard libary functions * mktime and gmtime allow us to do this conversion. * * Only do this timezone adjustment for recent and future years. * In this case, "recent" is defined to be 1970 and later, because * on MS Windows, mktime raises an error when given an earlier date. */ if (out_dts_utc->year >= 1970) { NPY_TIME_T rawtime = 0; struct tm tm_; tm_.tm_sec = out_dts_utc->sec; tm_.tm_min = out_dts_utc->min; tm_.tm_hour = out_dts_utc->hour; tm_.tm_mday = out_dts_utc->day; tm_.tm_mon = out_dts_utc->month - 1; tm_.tm_year = out_dts_utc->year - 1900; tm_.tm_isdst = -1; /* mktime converts a local 'struct tm' into a time_t */ rawtime = get_mktime(&tm_); if (rawtime == -1) { return -1; } /* gmtime converts a 'time_t' into a UTC 'struct tm' */ if (get_gmtime(&rawtime, &tm_) < 0) { return -1; } out_dts_utc->sec = tm_.tm_sec; out_dts_utc->min = tm_.tm_min; out_dts_utc->hour = tm_.tm_hour; out_dts_utc->day = tm_.tm_mday; out_dts_utc->month = tm_.tm_mon + 1; out_dts_utc->year = tm_.tm_year + 1900; } /* Reapply the year 2038 year correction */ out_dts_utc->year += year_correction; return 0; } /* * Parses (almost) standard ISO 8601 date strings. The differences are: * * + The date "20100312" is parsed as the year 20100312, not as * equivalent to "2010-03-12". The '-' in the dates are not optional. * + Only seconds may have a decimal point, with up to 18 digits after it * (maximum attoseconds precision). * + Either a 'T' as in ISO 8601 or a ' ' may be used to separate * the date and the time. Both are treated equivalently. * + Doesn't (yet) handle the "YYYY-DDD" or "YYYY-Www" formats. * + Doesn't handle leap seconds (seconds value has 60 in these cases). * + Doesn't handle 24:00:00 as synonym for midnight (00:00:00) tomorrow * + Accepts special values "NaT" (not a time), "Today", (current * day according to local time) and "Now" (current time in UTC). * * 'str' must be a NULL-terminated string, and 'len' must be its length. * 'unit' should contain -1 if the unit is unknown, or the unit * which will be used if it is. * 'casting' controls how the detected unit from the string is allowed * to be cast to the 'unit' parameter. * * 'out' gets filled with the parsed date-time. * 'out_local' gets set to 1 if the parsed time was in local time, * to 0 otherwise. The values 'now' and 'today' don't get counted * as local, and neither do UTC +/-#### timezone offsets, because * they aren't using the computer's local timezone offset. * 'out_bestunit' gives a suggested unit based on the amount of * resolution provided in the string, or -1 for NaT. * 'out_special' gets set to 1 if the parsed time was 'today', * 'now', or ''/'NaT'. For 'today', the unit recommended is * 'D', for 'now', the unit recommended is 's', and for 'NaT' * the unit recommended is 'Y'. * * Returns 0 on success, -1 on failure. */ NPY_NO_EXPORT int parse_iso_8601_datetime(char *str, Py_ssize_t len, NPY_DATETIMEUNIT unit, NPY_CASTING casting, npy_datetimestruct *out, npy_bool *out_local, NPY_DATETIMEUNIT *out_bestunit, npy_bool *out_special) { int year_leap = 0; int i, numdigits; char *substr; Py_ssize_t sublen; NPY_DATETIMEUNIT bestunit; /* Initialize the output to all zeros */ memset(out, 0, sizeof(npy_datetimestruct)); out->month = 1; out->day = 1; /* * Convert the empty string and case-variants of "NaT" to not-a-time. * Tried to use PyOS_stricmp, but that function appears to be broken, * not even matching the strcmp function signature as it should. */ if (len <= 0 || (len == 3 && tolower(str[0]) == 'n' && tolower(str[1]) == 'a' && tolower(str[2]) == 't')) { out->year = NPY_DATETIME_NAT; /* * Indicate that this was a special value, and * recommend generic units. */ if (out_local != NULL) { *out_local = 0; } if (out_bestunit != NULL) { *out_bestunit = NPY_FR_GENERIC; } if (out_special != NULL) { *out_special = 1; } return 0; } if (unit == NPY_FR_GENERIC) { PyErr_SetString(PyExc_ValueError, "Cannot create a NumPy datetime other than NaT " "with generic units"); return -1; } /* * The string "today" means take today's date in local time, and * convert it to a date representation. This date representation, if * forced into a time unit, will be at midnight UTC. * This is perhaps a little weird, but done so that the * 'datetime64[D]' type produces the date you expect, rather than * switching to an adjacent day depending on the current time and your * timezone. */ if (len == 5 && tolower(str[0]) == 't' && tolower(str[1]) == 'o' && tolower(str[2]) == 'd' && tolower(str[3]) == 'a' && tolower(str[4]) == 'y') { NPY_TIME_T rawtime = 0; struct tm tm_; time(&rawtime); if (get_localtime(&rawtime, &tm_) < 0) { return -1; } out->year = tm_.tm_year + 1900; out->month = tm_.tm_mon + 1; out->day = tm_.tm_mday; bestunit = NPY_FR_D; /* * Indicate that this was a special value, and * is a date (unit 'D'). */ if (out_local != NULL) { *out_local = 0; } if (out_bestunit != NULL) { *out_bestunit = bestunit; } if (out_special != NULL) { *out_special = 1; } /* Check the casting rule */ if (unit != -1 && !can_cast_datetime64_units(bestunit, unit, casting)) { PyErr_Format(PyExc_TypeError, "Cannot parse \"%s\" as unit " "'%s' using casting rule %s", str, _datetime_strings[unit], npy_casting_to_string(casting)); return -1; } return 0; } /* The string "now" resolves to the current UTC time */ if (len == 3 && tolower(str[0]) == 'n' && tolower(str[1]) == 'o' && tolower(str[2]) == 'w') { NPY_TIME_T rawtime = 0; PyArray_DatetimeMetaData meta; time(&rawtime); /* Set up a dummy metadata for the conversion */ meta.base = NPY_FR_s; meta.num = 1; bestunit = NPY_FR_s; /* * Indicate that this was a special value, and * use 's' because the time() function has resolution * seconds. */ if (out_local != NULL) { *out_local = 0; } if (out_bestunit != NULL) { *out_bestunit = bestunit; } if (out_special != NULL) { *out_special = 1; } /* Check the casting rule */ if (unit != -1 && !can_cast_datetime64_units(bestunit, unit, casting)) { PyErr_Format(PyExc_TypeError, "Cannot parse \"%s\" as unit " "'%s' using casting rule %s", str, _datetime_strings[unit], npy_casting_to_string(casting)); return -1; } return convert_datetime_to_datetimestruct(&meta, rawtime, out); } /* Anything else isn't a special value */ if (out_special != NULL) { *out_special = 0; } substr = str; sublen = len; /* Skip leading whitespace */ while (sublen > 0 && isspace(*substr)) { ++substr; --sublen; } /* Leading '-' sign for negative year */ if (*substr == '-') { ++substr; --sublen; } if (sublen == 0) { goto parse_error; } /* PARSE THE YEAR (digits until the '-' character) */ out->year = 0; while (sublen > 0 && isdigit(*substr)) { out->year = 10 * out->year + (*substr - '0'); ++substr; --sublen; } /* Negate the year if necessary */ if (str[0] == '-') { out->year = -out->year; } /* Check whether it's a leap-year */ year_leap = is_leapyear(out->year); /* Next character must be a '-' or the end of the string */ if (sublen == 0) { if (out_local != NULL) { *out_local = 0; } bestunit = NPY_FR_Y; goto finish; } else if (*substr == '-') { ++substr; --sublen; } else { goto parse_error; } /* Can't have a trailing '-' */ if (sublen == 0) { goto parse_error; } /* PARSE THE MONTH (2 digits) */ if (sublen >= 2 && isdigit(substr[0]) && isdigit(substr[1])) { out->month = 10 * (substr[0] - '0') + (substr[1] - '0'); if (out->month < 1 || out->month > 12) { PyErr_Format(PyExc_ValueError, "Month out of range in datetime string \"%s\"", str); goto error; } substr += 2; sublen -= 2; } else { goto parse_error; } /* Next character must be a '-' or the end of the string */ if (sublen == 0) { if (out_local != NULL) { *out_local = 0; } bestunit = NPY_FR_M; goto finish; } else if (*substr == '-') { ++substr; --sublen; } else { goto parse_error; } /* Can't have a trailing '-' */ if (sublen == 0) { goto parse_error; } /* PARSE THE DAY (2 digits) */ if (sublen >= 2 && isdigit(substr[0]) && isdigit(substr[1])) { out->day = 10 * (substr[0] - '0') + (substr[1] - '0'); if (out->day < 1 || out->day > _days_per_month_table[year_leap][out->month-1]) { PyErr_Format(PyExc_ValueError, "Day out of range in datetime string \"%s\"", str); goto error; } substr += 2; sublen -= 2; } else { goto parse_error; } /* Next character must be a 'T', ' ', or end of string */ if (sublen == 0) { if (out_local != NULL) { *out_local = 0; } bestunit = NPY_FR_D; goto finish; } else if (*substr != 'T' && *substr != ' ') { goto parse_error; } else { ++substr; --sublen; } /* PARSE THE HOURS (2 digits) */ if (sublen >= 2 && isdigit(substr[0]) && isdigit(substr[1])) { out->hour = 10 * (substr[0] - '0') + (substr[1] - '0'); if (out->hour < 0 || out->hour >= 24) { PyErr_Format(PyExc_ValueError, "Hours out of range in datetime string \"%s\"", str); goto error; } substr += 2; sublen -= 2; } else { goto parse_error; } /* Next character must be a ':' or the end of the string */ if (sublen > 0 && *substr == ':') { ++substr; --sublen; } else { bestunit = NPY_FR_h; goto parse_timezone; } /* Can't have a trailing ':' */ if (sublen == 0) { goto parse_error; } /* PARSE THE MINUTES (2 digits) */ if (sublen >= 2 && isdigit(substr[0]) && isdigit(substr[1])) { out->min = 10 * (substr[0] - '0') + (substr[1] - '0'); if (out->hour < 0 || out->min >= 60) { PyErr_Format(PyExc_ValueError, "Minutes out of range in datetime string \"%s\"", str); goto error; } substr += 2; sublen -= 2; } else { goto parse_error; } /* Next character must be a ':' or the end of the string */ if (sublen > 0 && *substr == ':') { ++substr; --sublen; } else { bestunit = NPY_FR_m; goto parse_timezone; } /* Can't have a trailing ':' */ if (sublen == 0) { goto parse_error; } /* PARSE THE SECONDS (2 digits) */ if (sublen >= 2 && isdigit(substr[0]) && isdigit(substr[1])) { out->sec = 10 * (substr[0] - '0') + (substr[1] - '0'); if (out->sec < 0 || out->sec >= 60) { PyErr_Format(PyExc_ValueError, "Seconds out of range in datetime string \"%s\"", str); goto error; } substr += 2; sublen -= 2; } else { goto parse_error; } /* Next character may be a '.' indicating fractional seconds */ if (sublen > 0 && *substr == '.') { ++substr; --sublen; } else { bestunit = NPY_FR_s; goto parse_timezone; } /* PARSE THE MICROSECONDS (0 to 6 digits) */ numdigits = 0; for (i = 0; i < 6; ++i) { out->us *= 10; if (sublen > 0 && isdigit(*substr)) { out->us += (*substr - '0'); ++substr; --sublen; ++numdigits; } } if (sublen == 0 || !isdigit(*substr)) { if (numdigits > 3) { bestunit = NPY_FR_us; } else { bestunit = NPY_FR_ms; } goto parse_timezone; } /* PARSE THE PICOSECONDS (0 to 6 digits) */ numdigits = 0; for (i = 0; i < 6; ++i) { out->ps *= 10; if (sublen > 0 && isdigit(*substr)) { out->ps += (*substr - '0'); ++substr; --sublen; ++numdigits; } } if (sublen == 0 || !isdigit(*substr)) { if (numdigits > 3) { bestunit = NPY_FR_ps; } else { bestunit = NPY_FR_ns; } goto parse_timezone; } /* PARSE THE ATTOSECONDS (0 to 6 digits) */ numdigits = 0; for (i = 0; i < 6; ++i) { out->as *= 10; if (sublen > 0 && isdigit(*substr)) { out->as += (*substr - '0'); ++substr; --sublen; ++numdigits; } } if (numdigits > 3) { bestunit = NPY_FR_as; } else { bestunit = NPY_FR_fs; } parse_timezone: if (sublen == 0) { if (convert_datetimestruct_local_to_utc(out, out) < 0) { goto error; } /* Since neither "Z" nor a time-zone was specified, it's local */ if (out_local != NULL) { *out_local = 1; } goto finish; } /* UTC specifier */ if (*substr == 'Z') { /* "Z" means not local */ if (out_local != NULL) { *out_local = 0; } if (sublen == 1) { goto finish; } else { ++substr; --sublen; } } /* Time zone offset */ else if (*substr == '-' || *substr == '+') { int offset_neg = 0, offset_hour = 0, offset_minute = 0; /* * Since "local" means local with respect to the current * machine, we say this is non-local. */ if (out_local != NULL) { *out_local = 0; } if (*substr == '-') { offset_neg = 1; } ++substr; --sublen; /* The hours offset */ if (sublen >= 2 && isdigit(substr[0]) && isdigit(substr[1])) { offset_hour = 10 * (substr[0] - '0') + (substr[1] - '0'); substr += 2; sublen -= 2; if (offset_hour >= 24) { PyErr_Format(PyExc_ValueError, "Timezone hours offset out of range " "in datetime string \"%s\"", str); goto error; } } else { goto parse_error; } /* The minutes offset is optional */ if (sublen > 0) { /* Optional ':' */ if (*substr == ':') { ++substr; --sublen; } /* The minutes offset (at the end of the string) */ if (sublen >= 2 && isdigit(substr[0]) && isdigit(substr[1])) { offset_minute = 10 * (substr[0] - '0') + (substr[1] - '0'); substr += 2; sublen -= 2; if (offset_minute >= 60) { PyErr_Format(PyExc_ValueError, "Timezone minutes offset out of range " "in datetime string \"%s\"", str); goto error; } } else { goto parse_error; } } /* Apply the time zone offset */ if (offset_neg) { offset_hour = -offset_hour; offset_minute = -offset_minute; } add_minutes_to_datetimestruct(out, -60 * offset_hour - offset_minute); } /* Skip trailing whitespace */ while (sublen > 0 && isspace(*substr)) { ++substr; --sublen; } if (sublen != 0) { goto parse_error; } finish: if (out_bestunit != NULL) { *out_bestunit = bestunit; } /* Check the casting rule */ if (unit != -1 && !can_cast_datetime64_units(bestunit, unit, casting)) { PyErr_Format(PyExc_TypeError, "Cannot parse \"%s\" as unit " "'%s' using casting rule %s", str, _datetime_strings[unit], npy_casting_to_string(casting)); return -1; } return 0; parse_error: PyErr_Format(PyExc_ValueError, "Error parsing datetime string \"%s\" at position %d", str, (int)(substr-str)); return -1; error: return -1; } /* * Provides a string length to use for converting datetime * objects with the given local and unit settings. */ NPY_NO_EXPORT int get_datetime_iso_8601_strlen(int local, NPY_DATETIMEUNIT base) { int len = 0; /* If no unit is provided, return the maximum length */ if (base == -1) { return NPY_DATETIME_MAX_ISO8601_STRLEN; } switch (base) { /* Generic units can only be used to represent NaT */ case NPY_FR_GENERIC: return 4; case NPY_FR_as: len += 3; /* "###" */ case NPY_FR_fs: len += 3; /* "###" */ case NPY_FR_ps: len += 3; /* "###" */ case NPY_FR_ns: len += 3; /* "###" */ case NPY_FR_us: len += 3; /* "###" */ case NPY_FR_ms: len += 4; /* ".###" */ case NPY_FR_s: len += 3; /* ":##" */ case NPY_FR_m: len += 3; /* ":##" */ case NPY_FR_h: len += 3; /* "T##" */ case NPY_FR_D: case NPY_FR_W: len += 3; /* "-##" */ case NPY_FR_M: len += 3; /* "-##" */ case NPY_FR_Y: len += 21; /* 64-bit year */ break; } if (base >= NPY_FR_h) { if (local) { len += 5; /* "+####" or "-####" */ } else { len += 1; /* "Z" */ } } len += 1; /* NULL terminator */ return len; } /* * Finds the largest unit whose value is nonzero, and for which * the remainder for the rest of the units is zero. */ static NPY_DATETIMEUNIT lossless_unit_from_datetimestruct(npy_datetimestruct *dts) { if (dts->as % 1000 != 0) { return NPY_FR_as; } else if (dts->as != 0) { return NPY_FR_fs; } else if (dts->ps % 1000 != 0) { return NPY_FR_ps; } else if (dts->ps != 0) { return NPY_FR_ns; } else if (dts->us % 1000 != 0) { return NPY_FR_us; } else if (dts->us != 0) { return NPY_FR_ms; } else if (dts->sec != 0) { return NPY_FR_s; } else if (dts->min != 0) { return NPY_FR_m; } else if (dts->hour != 0) { return NPY_FR_h; } else if (dts->day != 1) { return NPY_FR_D; } else if (dts->month != 1) { return NPY_FR_M; } else { return NPY_FR_Y; } } /* * Converts an npy_datetimestruct to an (almost) ISO 8601 * NULL-terminated string. If the string fits in the space exactly, * it leaves out the NULL terminator and returns success. * * The differences from ISO 8601 are the 'NaT' string, and * the number of year digits is >= 4 instead of strictly 4. * * If 'local' is non-zero, it produces a string in local time with * a +-#### timezone offset, otherwise it uses timezone Z (UTC). * * 'base' restricts the output to that unit. Set 'base' to * -1 to auto-detect a base after which all the values are zero. * * 'tzoffset' is used if 'local' is enabled, and 'tzoffset' is * set to a value other than -1. This is a manual override for * the local time zone to use, as an offset in minutes. * * 'casting' controls whether data loss is allowed by truncating * the data to a coarser unit. This interacts with 'local', slightly, * in order to form a date unit string as a local time, the casting * must be unsafe. * * Returns 0 on success, -1 on failure (for example if the output * string was too short). */ NPY_NO_EXPORT int make_iso_8601_datetime(npy_datetimestruct *dts, char *outstr, int outlen, int local, NPY_DATETIMEUNIT base, int tzoffset, NPY_CASTING casting) { npy_datetimestruct dts_local; int timezone_offset = 0; char *substr = outstr, sublen = outlen; int tmplen; /* Handle NaT, and treat a datetime with generic units as NaT */ if (dts->year == NPY_DATETIME_NAT || base == NPY_FR_GENERIC) { if (outlen < 3) { goto string_too_short; } outstr[0] = 'N'; outstr[1] = 'a'; outstr[2] = 'T'; if (outlen > 3) { outstr[3] = '\0'; } return 0; } /* * Only do local time within a reasonable year range. The years * earlier than 1970 are not made local, because the Windows API * raises an error when they are attempted (see the comments above the * get_localtime() function). For consistency, this * restriction is applied to all platforms. * * Note that this only affects how the datetime becomes a string. * The result is still completely unambiguous, it only means * that datetimes outside this range will not include a time zone * when they are printed. */ if ((dts->year < 1970 || dts->year >= 10000) && tzoffset == -1) { local = 0; } /* Automatically detect a good unit */ if (base == -1) { base = lossless_unit_from_datetimestruct(dts); /* * If there's a timezone, use at least minutes precision, * and never split up hours and minutes by default */ if ((base < NPY_FR_m && local) || base == NPY_FR_h) { base = NPY_FR_m; } /* Don't split up dates by default */ else if (base < NPY_FR_D) { base = NPY_FR_D; } } /* * Print weeks with the same precision as days. * * TODO: Could print weeks with YYYY-Www format if the week * epoch is a Monday. */ else if (base == NPY_FR_W) { base = NPY_FR_D; } /* Use the C API to convert from UTC to local time */ if (local && tzoffset == -1) { if (convert_datetimestruct_utc_to_local(&dts_local, dts, &timezone_offset) < 0) { return -1; } /* Set dts to point to our local time instead of the UTC time */ dts = &dts_local; } /* Use the manually provided tzoffset */ else if (local) { /* Make a copy of the npy_datetimestruct we can modify */ dts_local = *dts; dts = &dts_local; /* Set and apply the required timezone offset */ timezone_offset = tzoffset; add_minutes_to_datetimestruct(dts, timezone_offset); } /* * Now the datetimestruct data is in the final form for * the string representation, so ensure that the data * is being cast according to the casting rule. */ if (casting != NPY_UNSAFE_CASTING) { /* Producing a date as a local time is always 'unsafe' */ if (base <= NPY_FR_D && local) { PyErr_SetString(PyExc_TypeError, "Cannot create a local " "timezone-based date string from a NumPy " "datetime without forcing 'unsafe' casting"); return -1; } /* Only 'unsafe' and 'same_kind' allow data loss */ else { NPY_DATETIMEUNIT unitprec; unitprec = lossless_unit_from_datetimestruct(dts); if (casting != NPY_SAME_KIND_CASTING && unitprec > base) { PyErr_Format(PyExc_TypeError, "Cannot create a " "string with unit precision '%s' " "from the NumPy datetime, which has data at " "unit precision '%s', " "requires 'unsafe' or 'same_kind' casting", _datetime_strings[base], _datetime_strings[unitprec]); return -1; } } } /* YEAR */ /* * Can't use PyOS_snprintf, because it always produces a '\0' * character at the end, and NumPy string types are permitted * to have data all the way to the end of the buffer. */ #ifdef _WIN32 tmplen = _snprintf(substr, sublen, "%04" NPY_INT64_FMT, dts->year); #else tmplen = snprintf(substr, sublen, "%04" NPY_INT64_FMT, dts->year); #endif /* If it ran out of space or there isn't space for the NULL terminator */ if (tmplen < 0 || tmplen > sublen) { goto string_too_short; } substr += tmplen; sublen -= tmplen; /* Stop if the unit is years */ if (base == NPY_FR_Y) { if (sublen > 0) { *substr = '\0'; } return 0; } /* MONTH */ if (sublen < 1 ) { goto string_too_short; } substr[0] = '-'; if (sublen < 2 ) { goto string_too_short; } substr[1] = (char)((dts->month / 10) + '0'); if (sublen < 3 ) { goto string_too_short; } substr[2] = (char)((dts->month % 10) + '0'); substr += 3; sublen -= 3; /* Stop if the unit is months */ if (base == NPY_FR_M) { if (sublen > 0) { *substr = '\0'; } return 0; } /* DAY */ if (sublen < 1 ) { goto string_too_short; } substr[0] = '-'; if (sublen < 2 ) { goto string_too_short; } substr[1] = (char)((dts->day / 10) + '0'); if (sublen < 3 ) { goto string_too_short; } substr[2] = (char)((dts->day % 10) + '0'); substr += 3; sublen -= 3; /* Stop if the unit is days */ if (base == NPY_FR_D) { if (sublen > 0) { *substr = '\0'; } return 0; } /* HOUR */ if (sublen < 1 ) { goto string_too_short; } substr[0] = 'T'; if (sublen < 2 ) { goto string_too_short; } substr[1] = (char)((dts->hour / 10) + '0'); if (sublen < 3 ) { goto string_too_short; } substr[2] = (char)((dts->hour % 10) + '0'); substr += 3; sublen -= 3; /* Stop if the unit is hours */ if (base == NPY_FR_h) { goto add_time_zone; } /* MINUTE */ if (sublen < 1 ) { goto string_too_short; } substr[0] = ':'; if (sublen < 2 ) { goto string_too_short; } substr[1] = (char)((dts->min / 10) + '0'); if (sublen < 3 ) { goto string_too_short; } substr[2] = (char)((dts->min % 10) + '0'); substr += 3; sublen -= 3; /* Stop if the unit is minutes */ if (base == NPY_FR_m) { goto add_time_zone; } /* SECOND */ if (sublen < 1 ) { goto string_too_short; } substr[0] = ':'; if (sublen < 2 ) { goto string_too_short; } substr[1] = (char)((dts->sec / 10) + '0'); if (sublen < 3 ) { goto string_too_short; } substr[2] = (char)((dts->sec % 10) + '0'); substr += 3; sublen -= 3; /* Stop if the unit is seconds */ if (base == NPY_FR_s) { goto add_time_zone; } /* MILLISECOND */ if (sublen < 1 ) { goto string_too_short; } substr[0] = '.'; if (sublen < 2 ) { goto string_too_short; } substr[1] = (char)((dts->us / 100000) % 10 + '0'); if (sublen < 3 ) { goto string_too_short; } substr[2] = (char)((dts->us / 10000) % 10 + '0'); if (sublen < 4 ) { goto string_too_short; } substr[3] = (char)((dts->us / 1000) % 10 + '0'); substr += 4; sublen -= 4; /* Stop if the unit is milliseconds */ if (base == NPY_FR_ms) { goto add_time_zone; } /* MICROSECOND */ if (sublen < 1 ) { goto string_too_short; } substr[0] = (char)((dts->us / 100) % 10 + '0'); if (sublen < 2 ) { goto string_too_short; } substr[1] = (char)((dts->us / 10) % 10 + '0'); if (sublen < 3 ) { goto string_too_short; } substr[2] = (char)(dts->us % 10 + '0'); substr += 3; sublen -= 3; /* Stop if the unit is microseconds */ if (base == NPY_FR_us) { goto add_time_zone; } /* NANOSECOND */ if (sublen < 1 ) { goto string_too_short; } substr[0] = (char)((dts->ps / 100000) % 10 + '0'); if (sublen < 2 ) { goto string_too_short; } substr[1] = (char)((dts->ps / 10000) % 10 + '0'); if (sublen < 3 ) { goto string_too_short; } substr[2] = (char)((dts->ps / 1000) % 10 + '0'); substr += 3; sublen -= 3; /* Stop if the unit is nanoseconds */ if (base == NPY_FR_ns) { goto add_time_zone; } /* PICOSECOND */ if (sublen < 1 ) { goto string_too_short; } substr[0] = (char)((dts->ps / 100) % 10 + '0'); if (sublen < 2 ) { goto string_too_short; } substr[1] = (char)((dts->ps / 10) % 10 + '0'); if (sublen < 3 ) { goto string_too_short; } substr[2] = (char)(dts->ps % 10 + '0'); substr += 3; sublen -= 3; /* Stop if the unit is picoseconds */ if (base == NPY_FR_ps) { goto add_time_zone; } /* FEMTOSECOND */ if (sublen < 1 ) { goto string_too_short; } substr[0] = (char)((dts->as / 100000) % 10 + '0'); if (sublen < 2 ) { goto string_too_short; } substr[1] = (char)((dts->as / 10000) % 10 + '0'); if (sublen < 3 ) { goto string_too_short; } substr[2] = (char)((dts->as / 1000) % 10 + '0'); substr += 3; sublen -= 3; /* Stop if the unit is femtoseconds */ if (base == NPY_FR_fs) { goto add_time_zone; } /* ATTOSECOND */ if (sublen < 1 ) { goto string_too_short; } substr[0] = (char)((dts->as / 100) % 10 + '0'); if (sublen < 2 ) { goto string_too_short; } substr[1] = (char)((dts->as / 10) % 10 + '0'); if (sublen < 3 ) { goto string_too_short; } substr[2] = (char)(dts->as % 10 + '0'); substr += 3; sublen -= 3; add_time_zone: if (local) { /* Add the +/- sign */ if (sublen < 1) { goto string_too_short; } if (timezone_offset < 0) { substr[0] = '-'; timezone_offset = -timezone_offset; } else { substr[0] = '+'; } substr += 1; sublen -= 1; /* Add the timezone offset */ if (sublen < 1 ) { goto string_too_short; } substr[0] = (char)((timezone_offset / (10*60)) % 10 + '0'); if (sublen < 2 ) { goto string_too_short; } substr[1] = (char)((timezone_offset / 60) % 10 + '0'); if (sublen < 3 ) { goto string_too_short; } substr[2] = (char)(((timezone_offset % 60) / 10) % 10 + '0'); if (sublen < 4 ) { goto string_too_short; } substr[3] = (char)((timezone_offset % 60) % 10 + '0'); substr += 4; sublen -= 4; } /* UTC "Zulu" time */ else { if (sublen < 1) { goto string_too_short; } substr[0] = 'Z'; substr += 1; sublen -= 1; } /* Add a NULL terminator, and return */ if (sublen > 0) { substr[0] = '\0'; } return 0; string_too_short: PyErr_Format(PyExc_RuntimeError, "The string provided for NumPy ISO datetime formatting " "was too short, with length %d", outlen); return -1; } /* * This is the Python-exposed datetime_as_string function. */ NPY_NO_EXPORT PyObject * array_datetime_as_string(PyObject *NPY_UNUSED(self), PyObject *args, PyObject *kwds) { PyObject *arr_in = NULL, *unit_in = NULL, *timezone_obj = NULL; NPY_DATETIMEUNIT unit; NPY_CASTING casting = NPY_SAME_KIND_CASTING; int local = 0; PyArray_DatetimeMetaData *meta; int strsize; PyArrayObject *ret = NULL; NpyIter *iter = NULL; PyArrayObject *op[2] = {NULL, NULL}; PyArray_Descr *op_dtypes[2] = {NULL, NULL}; npy_uint32 flags, op_flags[2]; static char *kwlist[] = {"arr", "unit", "timezone", "casting", NULL}; if(!PyArg_ParseTupleAndKeywords(args, kwds, "O|OOO&:datetime_as_string", kwlist, &arr_in, &unit_in, &timezone_obj, &PyArray_CastingConverter, &casting)) { return NULL; } /* Claim a reference to timezone for later */ Py_XINCREF(timezone_obj); 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"); goto fail; } /* Get the datetime metadata */ meta = get_datetime_metadata_from_dtype(PyArray_DESCR(op[0])); if (meta == NULL) { goto fail; } /* Use the metadata's unit for printing by default */ unit = meta->base; /* Parse the input unit if provided */ if (unit_in != NULL && unit_in != Py_None) { PyObject *strobj; char *str = NULL; Py_ssize_t len = 0; if (PyUnicode_Check(unit_in)) { strobj = PyUnicode_AsASCIIString(unit_in); if (strobj == NULL) { goto fail; } } else { strobj = unit_in; Py_INCREF(strobj); } if (PyBytes_AsStringAndSize(strobj, &str, &len) < 0) { Py_DECREF(strobj); goto fail; } /* unit == -1 means to autodetect the unit from the datetime data */ if (strcmp(str, "auto") == 0) { unit = -1; } else { unit = parse_datetime_unit_from_string(str, len, NULL); if (unit == -1) { Py_DECREF(strobj); goto fail; } } Py_DECREF(strobj); if (unit != -1 && !can_cast_datetime64_units(meta->base, unit, casting)) { PyErr_Format(PyExc_TypeError, "Cannot create a datetime " "string as units '%s' from a NumPy datetime " "with units '%s' according to the rule %s", _datetime_strings[unit], _datetime_strings[meta->base], npy_casting_to_string(casting)); goto fail; } } /* Get the input time zone */ if (timezone_obj != NULL) { /* Convert to ASCII if it's unicode */ if (PyUnicode_Check(timezone_obj)) { /* accept unicode input */ PyObject *obj_str; obj_str = PyUnicode_AsASCIIString(timezone_obj); if (obj_str == NULL) { goto fail; } Py_DECREF(timezone_obj); timezone_obj = obj_str; } /* Check for the supported string inputs */ if (PyBytes_Check(timezone_obj)) { char *str; Py_ssize_t len; if (PyBytes_AsStringAndSize(timezone_obj, &str, &len) < 0) { goto fail; } if (strcmp(str, "local") == 0) { local = 1; Py_DECREF(timezone_obj); timezone_obj = NULL; } else if (strcmp(str, "UTC") == 0) { local = 0; Py_DECREF(timezone_obj); timezone_obj = NULL; } else { PyErr_Format(PyExc_ValueError, "Unsupported timezone " "input string \"%s\"", str); goto fail; } } /* Otherwise assume it's a Python TZInfo, or acts like one */ else { local = 1; } } /* Get a string size long enough for any datetimes we're given */ strsize = get_datetime_iso_8601_strlen(local, unit); #if defined(NPY_PY3K) /* * For Python3, allocate the output array as a UNICODE array, so * that it will behave as strings properly */ op_dtypes[1] = PyArray_DescrNewFromType(NPY_UNICODE); if (op_dtypes[1] == NULL) { goto fail; } op_dtypes[1]->elsize = strsize * 4; /* This steals the UNICODE dtype reference in op_dtypes[1] */ op[1] = (PyArrayObject *)PyArray_NewLikeArray(op[0], NPY_KEEPORDER, op_dtypes[1], 1); if (op[1] == NULL) { op_dtypes[1] = NULL; goto fail; } #endif /* Create the iteration string data type (always ASCII string) */ op_dtypes[1] = PyArray_DescrNewFromType(NPY_STRING); if (op_dtypes[1] == NULL) { goto fail; } op_dtypes[1]->elsize = strsize; flags = NPY_ITER_ZEROSIZE_OK| NPY_ITER_BUFFERED; op_flags[0] = NPY_ITER_READONLY| NPY_ITER_ALIGNED; op_flags[1] = NPY_ITER_WRITEONLY| NPY_ITER_ALLOCATE; iter = NpyIter_MultiNew(2, op, flags, NPY_KEEPORDER, NPY_UNSAFE_CASTING, op_flags, op_dtypes); if (iter == NULL) { goto fail; } if (NpyIter_GetIterSize(iter) != 0) { NpyIter_IterNextFunc *iternext; char **dataptr; npy_datetime dt; npy_datetimestruct dts; iternext = NpyIter_GetIterNext(iter, NULL); if (iternext == NULL) { goto fail; } dataptr = NpyIter_GetDataPtrArray(iter); do { int tzoffset = -1; /* Get the datetime */ dt = *(npy_datetime *)dataptr[0]; /* Convert it to a struct */ if (convert_datetime_to_datetimestruct(meta, dt, &dts) < 0) { goto fail; } /* Get the tzoffset from the timezone if provided */ if (local && timezone_obj != NULL) { tzoffset = get_tzoffset_from_pytzinfo(timezone_obj, &dts); if (tzoffset == -1) { goto fail; } } /* Zero the destination string completely */ memset(dataptr[1], 0, strsize); /* Convert that into a string */ if (make_iso_8601_datetime(&dts, (char *)dataptr[1], strsize, local, unit, tzoffset, casting) < 0) { goto fail; } } while(iternext(iter)); } ret = NpyIter_GetOperandArray(iter)[1]; Py_INCREF(ret); Py_XDECREF(timezone_obj); Py_XDECREF(op[0]); Py_XDECREF(op[1]); Py_XDECREF(op_dtypes[0]); Py_XDECREF(op_dtypes[1]); if (iter != NULL) { NpyIter_Deallocate(iter); } return PyArray_Return(ret); fail: Py_XDECREF(timezone_obj); Py_XDECREF(op[0]); Py_XDECREF(op[1]); Py_XDECREF(op_dtypes[0]); Py_XDECREF(op_dtypes[1]); if (iter != NULL) { NpyIter_Deallocate(iter); } return NULL; } numpy-1.8.2/numpy/core/src/multiarray/convert_datatype.h0000664000175100017510000000204112370216242024624 0ustar vagrantvagrant00000000000000#ifndef _NPY_ARRAY_CONVERT_DATATYPE_H_ #define _NPY_ARRAY_CONVERT_DATATYPE_H_ NPY_NO_EXPORT PyArray_VectorUnaryFunc * PyArray_GetCastFunc(PyArray_Descr *descr, int type_num); NPY_NO_EXPORT int PyArray_ObjectType(PyObject *op, int minimum_type); NPY_NO_EXPORT PyArrayObject ** PyArray_ConvertToCommonType(PyObject *op, int *retn); NPY_NO_EXPORT int PyArray_ValidType(int type); /* Like PyArray_CanCastArrayTo */ NPY_NO_EXPORT npy_bool can_cast_scalar_to(PyArray_Descr *scal_type, char *scal_data, PyArray_Descr *to, NPY_CASTING casting); /* * This function calls Py_DECREF on flex_dtype, and replaces it with * a new dtype that has been adapted based on the values in data_dtype * and data_obj. If the flex_dtype is not flexible, it leaves it as is. * * The current flexible dtypes include NPY_STRING, NPY_UNICODE, NPY_VOID, * and NPY_DATETIME with generic units. */ NPY_NO_EXPORT void PyArray_AdaptFlexibleDType(PyObject *data_obj, PyArray_Descr *data_dtype, PyArray_Descr **flex_dtype); #endif numpy-1.8.2/numpy/core/src/multiarray/conversion_utils.h0000664000175100017510000000412412370216242024662 0ustar vagrantvagrant00000000000000#ifndef _NPY_PRIVATE_CONVERSION_UTILS_H_ #define _NPY_PRIVATE_CONVERSION_UTILS_H_ #include NPY_NO_EXPORT int PyArray_IntpConverter(PyObject *obj, PyArray_Dims *seq); NPY_NO_EXPORT int PyArray_BufferConverter(PyObject *obj, PyArray_Chunk *buf); NPY_NO_EXPORT int PyArray_BoolConverter(PyObject *object, npy_bool *val); NPY_NO_EXPORT int PyArray_ByteorderConverter(PyObject *obj, char *endian); NPY_NO_EXPORT int PyArray_SortkindConverter(PyObject *obj, NPY_SORTKIND *sortkind); NPY_NO_EXPORT int PyArray_SearchsideConverter(PyObject *obj, void *addr); NPY_NO_EXPORT int PyArray_PyIntAsInt(PyObject *o); NPY_NO_EXPORT npy_intp PyArray_PyIntAsIntp(PyObject *o); NPY_NO_EXPORT npy_intp PyArray_IntpFromIndexSequence(PyObject *seq, npy_intp *vals, npy_intp maxvals); NPY_NO_EXPORT int PyArray_IntpFromSequence(PyObject *seq, npy_intp *vals, int maxvals); NPY_NO_EXPORT int PyArray_TypestrConvert(int itemsize, int gentype); NPY_NO_EXPORT PyObject * PyArray_IntTupleFromIntp(int len, npy_intp *vals); NPY_NO_EXPORT int PyArray_SelectkindConverter(PyObject *obj, NPY_SELECTKIND *selectkind); /* * Converts an axis parameter into an ndim-length C-array of * boolean flags, True for each axis specified. * * If obj is None, everything is set to True. If obj is a tuple, * each axis within the tuple is set to True. If obj is an integer, * just that axis is set to True. */ NPY_NO_EXPORT int PyArray_ConvertMultiAxis(PyObject *axis_in, int ndim, npy_bool *out_axis_flags); /** * WARNING: This flag is a bad idea, but was the only way to both * 1) Support unpickling legacy pickles with object types. * 2) Deprecate (and later disable) usage of O4 and O8 * * The key problem is that the pickled representation unpickles by * directly calling the dtype constructor, which has no way of knowing * that it is in an unpickle context instead of a normal context without * evil global state like we create here. */ #ifdef NPY_ENABLE_SEPARATE_COMPILATION extern NPY_NO_EXPORT int evil_global_disable_warn_O4O8_flag; #else NPY_NO_EXPORT int evil_global_disable_warn_O4O8_flag; #endif #endif numpy-1.8.2/numpy/core/src/multiarray/item_selection.h0000664000175100017510000000163312370216242024262 0ustar vagrantvagrant00000000000000#ifndef _NPY_PRIVATE__ITEM_SELECTION_H_ #define _NPY_PRIVATE__ITEM_SELECTION_H_ /* * Counts the number of True values in a raw boolean array. This * is a low-overhead function which does no heap allocations. * * Returns -1 on error. */ NPY_NO_EXPORT npy_intp count_boolean_trues(int ndim, char *data, npy_intp *ashape, npy_intp *astrides); /* * Gets a single item from the array, based on a single multi-index * array of values, which must be of length PyArray_NDIM(self). */ NPY_NO_EXPORT PyObject * PyArray_MultiIndexGetItem(PyArrayObject *self, npy_intp *multi_index); /* * Sets a single item in the array, based on a single multi-index * array of values, which must be of length PyArray_NDIM(self). * * Returns 0 on success, -1 on failure. */ NPY_NO_EXPORT int PyArray_MultiIndexSetItem(PyArrayObject *self, npy_intp *multi_index, PyObject *obj); #endif numpy-1.8.2/numpy/core/src/multiarray/methods.c0000664000175100017510000021571512370216243022726 0ustar vagrantvagrant00000000000000#define PY_SSIZE_T_CLEAN #include #include #include "structmember.h" #define NPY_NO_DEPRECATED_API NPY_API_VERSION #define _MULTIARRAYMODULE #include "numpy/arrayobject.h" #include "numpy/arrayscalars.h" #include "npy_config.h" #include "npy_pycompat.h" #include "common.h" #include "ctors.h" #include "calculation.h" #include "convert_datatype.h" #include "item_selection.h" #include "conversion_utils.h" #include "shape.h" #include "methods.h" /* NpyArg_ParseKeywords * * Utility function that provides the keyword parsing functionality of * PyArg_ParseTupleAndKeywords without having to have an args argument. * */ static int NpyArg_ParseKeywords(PyObject *keys, const char *format, char **kwlist, ...) { PyObject *args = PyTuple_New(0); int ret; va_list va; if (args == NULL) { PyErr_SetString(PyExc_RuntimeError, "Failed to allocate new tuple"); return 0; } va_start(va, kwlist); ret = PyArg_VaParseTupleAndKeywords(args, keys, format, kwlist, va); va_end(va); Py_DECREF(args); return ret; } static PyObject * get_forwarding_ndarray_method(const char *name) { PyObject *module_methods, *callable; /* Get a reference to the function we're calling */ module_methods = PyImport_ImportModule("numpy.core._methods"); if (module_methods == NULL) { return NULL; } callable = PyDict_GetItemString(PyModule_GetDict(module_methods), name); if (callable == NULL) { Py_DECREF(module_methods); PyErr_Format(PyExc_RuntimeError, "NumPy internal error: could not find function " "numpy.core._methods.%s", name); } Py_INCREF(callable); Py_DECREF(module_methods); return callable; } /* * Forwards an ndarray method to a the Python function * numpy.core._methods.(...) */ static PyObject * forward_ndarray_method(PyArrayObject *self, PyObject *args, PyObject *kwds, PyObject *forwarding_callable) { PyObject *sargs, *ret; int i, n; /* Combine 'self' and 'args' together into one tuple */ n = PyTuple_GET_SIZE(args); sargs = PyTuple_New(n + 1); if (sargs == NULL) { return NULL; } Py_INCREF(self); PyTuple_SET_ITEM(sargs, 0, (PyObject *)self); for (i = 0; i < n; ++i) { PyObject *item = PyTuple_GET_ITEM(args, i); Py_INCREF(item); PyTuple_SET_ITEM(sargs, i+1, item); } /* Call the function and return */ ret = PyObject_Call(forwarding_callable, sargs, kwds); Py_DECREF(sargs); return ret; } /* * Forwards an ndarray method to the function numpy.core._methods.(...), * caching the callable in a local static variable. Note that the * initialization is not thread-safe, but relies on the CPython GIL to * be correct. */ #define NPY_FORWARD_NDARRAY_METHOD(name) \ static PyObject *callable = NULL; \ if (callable == NULL) { \ callable = get_forwarding_ndarray_method(name); \ if (callable == NULL) { \ return NULL; \ } \ } \ return forward_ndarray_method(self, args, kwds, callable) static PyObject * array_take(PyArrayObject *self, PyObject *args, PyObject *kwds) { int dimension = NPY_MAXDIMS; PyObject *indices; PyArrayObject *out = NULL; NPY_CLIPMODE mode = NPY_RAISE; static char *kwlist[] = {"indices", "axis", "out", "mode", NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O&O&O&", kwlist, &indices, PyArray_AxisConverter, &dimension, PyArray_OutputConverter, &out, PyArray_ClipmodeConverter, &mode)) return NULL; return PyArray_Return((PyArrayObject *) PyArray_TakeFrom(self, indices, dimension, out, mode)); } static PyObject * array_fill(PyArrayObject *self, PyObject *args) { PyObject *obj; if (!PyArg_ParseTuple(args, "O", &obj)) { return NULL; } if (PyArray_FillWithScalar(self, obj) < 0) { return NULL; } Py_INCREF(Py_None); return Py_None; } static PyObject * array_put(PyArrayObject *self, PyObject *args, PyObject *kwds) { PyObject *indices, *values; NPY_CLIPMODE mode = NPY_RAISE; static char *kwlist[] = {"indices", "values", "mode", NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO|O&", kwlist, &indices, &values, PyArray_ClipmodeConverter, &mode)) return NULL; return PyArray_PutTo(self, values, indices, mode); } static PyObject * array_reshape(PyArrayObject *self, PyObject *args, PyObject *kwds) { static char *keywords[] = {"order", NULL}; PyArray_Dims newshape; PyObject *ret; NPY_ORDER order = NPY_CORDER; Py_ssize_t n = PyTuple_Size(args); if (!NpyArg_ParseKeywords(kwds, "|O&", keywords, PyArray_OrderConverter, &order)) { return NULL; } if (n <= 1) { if (PyTuple_GET_ITEM(args, 0) == Py_None) { return PyArray_View(self, NULL, NULL); } if (!PyArg_ParseTuple(args, "O&", PyArray_IntpConverter, &newshape)) { return NULL; } } else { if (!PyArray_IntpConverter(args, &newshape)) { if (!PyErr_Occurred()) { PyErr_SetString(PyExc_TypeError, "invalid shape"); } goto fail; } } ret = PyArray_Newshape(self, &newshape, order); PyDimMem_FREE(newshape.ptr); return ret; fail: PyDimMem_FREE(newshape.ptr); return NULL; } static PyObject * array_squeeze(PyArrayObject *self, PyObject *args, PyObject *kwds) { PyObject *axis_in = NULL; npy_bool axis_flags[NPY_MAXDIMS]; static char *kwlist[] = {"axis", NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O", kwlist, &axis_in)) { return NULL; } if (axis_in == NULL || axis_in == Py_None) { return PyArray_Squeeze(self); } else { if (PyArray_ConvertMultiAxis(axis_in, PyArray_NDIM(self), axis_flags) != NPY_SUCCEED) { return NULL; } return PyArray_SqueezeSelected(self, axis_flags); } } static PyObject * array_view(PyArrayObject *self, PyObject *args, PyObject *kwds) { PyObject *out_dtype = NULL; PyObject *out_type = NULL; PyArray_Descr *dtype = NULL; static char *kwlist[] = {"dtype", "type", NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OO", kwlist, &out_dtype, &out_type)) { return NULL; } /* If user specified a positional argument, guess whether it represents a type or a dtype for backward compatibility. */ if (out_dtype) { /* type specified? */ if (PyType_Check(out_dtype) && PyType_IsSubtype((PyTypeObject *)out_dtype, &PyArray_Type)) { if (out_type) { PyErr_SetString(PyExc_ValueError, "Cannot specify output type twice."); return NULL; } out_type = out_dtype; out_dtype = NULL; } } if ((out_type) && (!PyType_Check(out_type) || !PyType_IsSubtype((PyTypeObject *)out_type, &PyArray_Type))) { PyErr_SetString(PyExc_ValueError, "Type must be a sub-type of ndarray type"); return NULL; } if ((out_dtype) && (PyArray_DescrConverter(out_dtype, &dtype) == NPY_FAIL)) { return NULL; } return PyArray_View(self, dtype, (PyTypeObject*)out_type); } static PyObject * array_argmax(PyArrayObject *self, PyObject *args, PyObject *kwds) { int axis = NPY_MAXDIMS; PyArrayObject *out = NULL; static char *kwlist[] = {"axis", "out", NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O&O&", kwlist, PyArray_AxisConverter, &axis, PyArray_OutputConverter, &out)) return NULL; return PyArray_Return((PyArrayObject *)PyArray_ArgMax(self, axis, out)); } static PyObject * array_argmin(PyArrayObject *self, PyObject *args, PyObject *kwds) { int axis = NPY_MAXDIMS; PyArrayObject *out = NULL; static char *kwlist[] = {"axis", "out", NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O&O&", kwlist, PyArray_AxisConverter, &axis, PyArray_OutputConverter, &out)) return NULL; return PyArray_Return((PyArrayObject *)PyArray_ArgMin(self, axis, out)); } static PyObject * array_max(PyArrayObject *self, PyObject *args, PyObject *kwds) { NPY_FORWARD_NDARRAY_METHOD("_amax"); } static PyObject * array_min(PyArrayObject *self, PyObject *args, PyObject *kwds) { NPY_FORWARD_NDARRAY_METHOD("_amin"); } static PyObject * array_ptp(PyArrayObject *self, PyObject *args, PyObject *kwds) { int axis = NPY_MAXDIMS; PyArrayObject *out = NULL; static char *kwlist[] = {"axis", "out", NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O&O&", kwlist, PyArray_AxisConverter, &axis, PyArray_OutputConverter, &out)) return NULL; return PyArray_Ptp(self, axis, out); } static PyObject * array_swapaxes(PyArrayObject *self, PyObject *args) { int axis1, axis2; if (!PyArg_ParseTuple(args, "ii", &axis1, &axis2)) { return NULL; } return PyArray_SwapAxes(self, axis1, axis2); } /* steals typed reference */ /*NUMPY_API Get a subset of bytes from each element of the array */ NPY_NO_EXPORT PyObject * PyArray_GetField(PyArrayObject *self, PyArray_Descr *typed, int offset) { PyObject *ret = NULL; if (offset < 0 || (offset + typed->elsize) > PyArray_DESCR(self)->elsize) { PyErr_Format(PyExc_ValueError, "Need 0 <= offset <= %d for requested type " "but received offset = %d", PyArray_DESCR(self)->elsize-typed->elsize, offset); Py_DECREF(typed); return NULL; } ret = PyArray_NewFromDescr(Py_TYPE(self), typed, PyArray_NDIM(self), PyArray_DIMS(self), PyArray_STRIDES(self), PyArray_BYTES(self) + offset, PyArray_FLAGS(self)&(~NPY_ARRAY_F_CONTIGUOUS), (PyObject *)self); if (ret == NULL) { return NULL; } Py_INCREF(self); if (PyArray_SetBaseObject(((PyArrayObject *)ret), (PyObject *)self) < 0) { Py_DECREF(ret); return NULL; } PyArray_UpdateFlags((PyArrayObject *)ret, NPY_ARRAY_UPDATE_ALL); return ret; } static PyObject * array_getfield(PyArrayObject *self, PyObject *args, PyObject *kwds) { PyArray_Descr *dtype = NULL; int offset = 0; static char *kwlist[] = {"dtype", "offset", 0}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "O&|i", kwlist, PyArray_DescrConverter, &dtype, &offset)) { Py_XDECREF(dtype); return NULL; } return PyArray_GetField(self, dtype, offset); } /*NUMPY_API Set a subset of bytes from each element of the array */ NPY_NO_EXPORT int PyArray_SetField(PyArrayObject *self, PyArray_Descr *dtype, int offset, PyObject *val) { PyObject *ret = NULL; int retval = 0; if (offset < 0 || (offset + dtype->elsize) > PyArray_DESCR(self)->elsize) { PyErr_Format(PyExc_ValueError, "Need 0 <= offset <= %d for requested type " "but received offset = %d", PyArray_DESCR(self)->elsize-dtype->elsize, offset); Py_DECREF(dtype); return -1; } ret = PyArray_NewFromDescr(Py_TYPE(self), dtype, PyArray_NDIM(self), PyArray_DIMS(self), PyArray_STRIDES(self), PyArray_BYTES(self) + offset, PyArray_FLAGS(self), (PyObject *)self); if (ret == NULL) { return -1; } PyArray_UpdateFlags((PyArrayObject *)ret, NPY_ARRAY_UPDATE_ALL); retval = PyArray_CopyObject((PyArrayObject *)ret, val); Py_DECREF(ret); return retval; } static PyObject * array_setfield(PyArrayObject *self, PyObject *args, PyObject *kwds) { PyArray_Descr *dtype = NULL; int offset = 0; PyObject *value; static char *kwlist[] = {"value", "dtype", "offset", 0}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO&|i", kwlist, &value, PyArray_DescrConverter, &dtype, &offset)) { Py_XDECREF(dtype); return NULL; } if (PyDataType_REFCHK(PyArray_DESCR(self))) { PyErr_SetString(PyExc_RuntimeError, "cannot call setfield on an object array"); Py_DECREF(dtype); return NULL; } if (PyArray_SetField(self, dtype, offset, value) < 0) { return NULL; } Py_INCREF(Py_None); return Py_None; } /* This doesn't change the descriptor just the actual data... */ /*NUMPY_API*/ NPY_NO_EXPORT PyObject * PyArray_Byteswap(PyArrayObject *self, npy_bool inplace) { PyArrayObject *ret; npy_intp size; PyArray_CopySwapNFunc *copyswapn; PyArrayIterObject *it; copyswapn = PyArray_DESCR(self)->f->copyswapn; if (inplace) { if (PyArray_FailUnlessWriteable(self, "array to be byte-swapped") < 0) { return NULL; } size = PyArray_SIZE(self); if (PyArray_ISONESEGMENT(self)) { copyswapn(PyArray_DATA(self), PyArray_DESCR(self)->elsize, NULL, -1, size, 1, self); } else { /* Use iterator */ int axis = -1; npy_intp stride; it = (PyArrayIterObject *) \ PyArray_IterAllButAxis((PyObject *)self, &axis); stride = PyArray_STRIDES(self)[axis]; size = PyArray_DIMS(self)[axis]; while (it->index < it->size) { copyswapn(it->dataptr, stride, NULL, -1, size, 1, self); PyArray_ITER_NEXT(it); } Py_DECREF(it); } Py_INCREF(self); return (PyObject *)self; } else { PyObject *new; if ((ret = (PyArrayObject *)PyArray_NewCopy(self,-1)) == NULL) { return NULL; } new = PyArray_Byteswap(ret, NPY_TRUE); Py_DECREF(new); return (PyObject *)ret; } } static PyObject * array_byteswap(PyArrayObject *self, PyObject *args) { npy_bool inplace = NPY_FALSE; if (!PyArg_ParseTuple(args, "|O&", PyArray_BoolConverter, &inplace)) { return NULL; } return PyArray_Byteswap(self, inplace); } static PyObject * array_tolist(PyArrayObject *self, PyObject *args) { if (!PyArg_ParseTuple(args, "")) { return NULL; } return PyArray_ToList(self); } static PyObject * array_tostring(PyArrayObject *self, PyObject *args, PyObject *kwds) { NPY_ORDER order = NPY_CORDER; static char *kwlist[] = {"order", NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O&", kwlist, PyArray_OrderConverter, &order)) { return NULL; } return PyArray_ToString(self, order); } /* This should grow an order= keyword to be consistent */ static PyObject * array_tofile(PyArrayObject *self, PyObject *args, PyObject *kwds) { int own; PyObject *file; FILE *fd; char *sep = ""; char *format = ""; npy_off_t orig_pos; static char *kwlist[] = {"file", "sep", "format", NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|ss", kwlist, &file, &sep, &format)) { return NULL; } if (PyBytes_Check(file) || PyUnicode_Check(file)) { file = npy_PyFile_OpenFile(file, "wb"); if (file == NULL) { return NULL; } own = 1; } else { Py_INCREF(file); own = 0; } fd = npy_PyFile_Dup2(file, "wb", &orig_pos); if (fd == NULL) { PyErr_SetString(PyExc_IOError, "first argument must be a string or open file"); goto fail; } if (PyArray_ToFile(self, fd, sep, format) < 0) { goto fail; } if (npy_PyFile_DupClose2(file, fd, orig_pos) < 0) { goto fail; } if (own && npy_PyFile_CloseFile(file) < 0) { goto fail; } Py_DECREF(file); Py_INCREF(Py_None); return Py_None; fail: Py_DECREF(file); return NULL; } static PyObject * array_toscalar(PyArrayObject *self, PyObject *args) { npy_intp multi_index[NPY_MAXDIMS]; int n = PyTuple_GET_SIZE(args); int idim, ndim = PyArray_NDIM(self); /* If there is a tuple as a single argument, treat it as the argument */ if (n == 1 && PyTuple_Check(PyTuple_GET_ITEM(args, 0))) { args = PyTuple_GET_ITEM(args, 0); n = PyTuple_GET_SIZE(args); } if (n == 0) { if (PyArray_SIZE(self) == 1) { for (idim = 0; idim < ndim; ++idim) { multi_index[idim] = 0; } } else { PyErr_SetString(PyExc_ValueError, "can only convert an array of size 1 to a Python scalar"); return NULL; } } /* Special case of C-order flat indexing... :| */ else if (n == 1 && ndim != 1) { npy_intp *shape = PyArray_SHAPE(self); npy_intp value, size = PyArray_SIZE(self); value = PyArray_PyIntAsIntp(PyTuple_GET_ITEM(args, 0)); if (value == -1 && PyErr_Occurred()) { return NULL; } if (check_and_adjust_index(&value, size, -1) < 0) { return NULL; } /* Convert the flat index into a multi-index */ for (idim = ndim-1; idim >= 0; --idim) { multi_index[idim] = value % shape[idim]; value /= shape[idim]; } } /* A multi-index tuple */ else if (n == ndim) { npy_intp value; for (idim = 0; idim < ndim; ++idim) { value = PyArray_PyIntAsIntp(PyTuple_GET_ITEM(args, idim)); if (value == -1 && PyErr_Occurred()) { return NULL; } multi_index[idim] = value; } } else { PyErr_SetString(PyExc_ValueError, "incorrect number of indices for array"); return NULL; } return PyArray_MultiIndexGetItem(self, multi_index); } static PyObject * array_setscalar(PyArrayObject *self, PyObject *args) { npy_intp multi_index[NPY_MAXDIMS]; int n = PyTuple_GET_SIZE(args) - 1; int idim, ndim = PyArray_NDIM(self); PyObject *obj; if (n < 0) { PyErr_SetString(PyExc_ValueError, "itemset must have at least one argument"); return NULL; } if (PyArray_FailUnlessWriteable(self, "assignment destination") < 0) { return NULL; } obj = PyTuple_GET_ITEM(args, n); /* If there is a tuple as a single argument, treat it as the argument */ if (n == 1 && PyTuple_Check(PyTuple_GET_ITEM(args, 0))) { args = PyTuple_GET_ITEM(args, 0); n = PyTuple_GET_SIZE(args); } if (n == 0) { if (PyArray_SIZE(self) == 1) { for (idim = 0; idim < ndim; ++idim) { multi_index[idim] = 0; } } else { PyErr_SetString(PyExc_ValueError, "can only convert an array of size 1 to a Python scalar"); } } /* Special case of C-order flat indexing... :| */ else if (n == 1 && ndim != 1) { npy_intp *shape = PyArray_SHAPE(self); npy_intp value, size = PyArray_SIZE(self); value = PyArray_PyIntAsIntp(PyTuple_GET_ITEM(args, 0)); if (value == -1 && PyErr_Occurred()) { return NULL; } if (check_and_adjust_index(&value, size, -1) < 0) { return NULL; } /* Convert the flat index into a multi-index */ for (idim = ndim-1; idim >= 0; --idim) { multi_index[idim] = value % shape[idim]; value /= shape[idim]; } } /* A multi-index tuple */ else if (n == ndim) { npy_intp value; for (idim = 0; idim < ndim; ++idim) { value = PyArray_PyIntAsIntp(PyTuple_GET_ITEM(args, idim)); if (value == -1 && PyErr_Occurred()) { return NULL; } multi_index[idim] = value; } } else { PyErr_SetString(PyExc_ValueError, "incorrect number of indices for array"); return NULL; } if (PyArray_MultiIndexSetItem(self, multi_index, obj) < 0) { return NULL; } else { Py_INCREF(Py_None); return Py_None; } } NPY_NO_EXPORT const char * npy_casting_to_string(NPY_CASTING casting) { switch (casting) { case NPY_NO_CASTING: return "'no'"; case NPY_EQUIV_CASTING: return "'equiv'"; case NPY_SAFE_CASTING: return "'safe'"; case NPY_SAME_KIND_CASTING: return "'same_kind'"; case NPY_UNSAFE_CASTING: return "'unsafe'"; default: return ""; } } static PyObject * array_astype(PyArrayObject *self, PyObject *args, PyObject *kwds) { static char *kwlist[] = {"dtype", "order", "casting", "subok", "copy", NULL}; PyArray_Descr *dtype = NULL; /* * TODO: UNSAFE default for compatibility, I think * switching to SAME_KIND by default would be good. */ NPY_CASTING casting = NPY_UNSAFE_CASTING; NPY_ORDER order = NPY_KEEPORDER; int forcecopy = 1, subok = 1; if (!PyArg_ParseTupleAndKeywords(args, kwds, "O&|O&O&ii", kwlist, PyArray_DescrConverter, &dtype, PyArray_OrderConverter, &order, PyArray_CastingConverter, &casting, &subok, &forcecopy)) { Py_XDECREF(dtype); return NULL; } /* * If the memory layout matches and, data types are equivalent, * and it's not a subtype if subok is False, then we * can skip the copy. */ if (!forcecopy && (order == NPY_KEEPORDER || (order == NPY_ANYORDER && (PyArray_IS_C_CONTIGUOUS(self) || PyArray_IS_F_CONTIGUOUS(self))) || (order == NPY_CORDER && PyArray_IS_C_CONTIGUOUS(self)) || (order == NPY_FORTRANORDER && PyArray_IS_F_CONTIGUOUS(self))) && (subok || PyArray_CheckExact(self)) && PyArray_EquivTypes(dtype, PyArray_DESCR(self))) { Py_DECREF(dtype); Py_INCREF(self); return (PyObject *)self; } else if (PyArray_CanCastArrayTo(self, dtype, casting)) { PyArrayObject *ret; /* If the requested dtype is flexible, adapt it */ PyArray_AdaptFlexibleDType((PyObject *)self, PyArray_DESCR(self), &dtype); if (dtype == NULL) { return NULL; } /* This steals the reference to dtype, so no DECREF of dtype */ ret = (PyArrayObject *)PyArray_NewLikeArray( self, order, dtype, subok); if (ret == NULL) { return NULL; } if (PyArray_CopyInto(ret, self) < 0) { Py_DECREF(ret); return NULL; } return (PyObject *)ret; } else { PyObject *errmsg; errmsg = PyUString_FromString("Cannot cast array from "); PyUString_ConcatAndDel(&errmsg, PyObject_Repr((PyObject *)PyArray_DESCR(self))); PyUString_ConcatAndDel(&errmsg, PyUString_FromString(" to ")); PyUString_ConcatAndDel(&errmsg, PyObject_Repr((PyObject *)dtype)); PyUString_ConcatAndDel(&errmsg, PyUString_FromFormat(" according to the rule %s", npy_casting_to_string(casting))); PyErr_SetObject(PyExc_TypeError, errmsg); Py_DECREF(errmsg); Py_DECREF(dtype); return NULL; } } /* default sub-type implementation */ static PyObject * array_wraparray(PyArrayObject *self, PyObject *args) { PyArrayObject *arr, *ret; PyObject *obj; if (PyTuple_Size(args) < 1) { PyErr_SetString(PyExc_TypeError, "only accepts 1 argument"); return NULL; } obj = PyTuple_GET_ITEM(args, 0); if (obj == NULL) { return NULL; } if (!PyArray_Check(obj)) { PyErr_SetString(PyExc_TypeError, "can only be called with ndarray object"); return NULL; } arr = (PyArrayObject *)obj; if (Py_TYPE(self) != Py_TYPE(arr)){ PyArray_Descr *dtype = PyArray_DESCR(arr); Py_INCREF(dtype); ret = (PyArrayObject *)PyArray_NewFromDescr(Py_TYPE(self), dtype, PyArray_NDIM(arr), PyArray_DIMS(arr), PyArray_STRIDES(arr), PyArray_DATA(arr), PyArray_FLAGS(arr), (PyObject *)self); if (ret == NULL) { return NULL; } Py_INCREF(obj); if (PyArray_SetBaseObject(ret, obj) < 0) { Py_DECREF(ret); return NULL; } return (PyObject *)ret; } else { /*The type was set in __array_prepare__*/ Py_INCREF(arr); return (PyObject *)arr; } } static PyObject * array_preparearray(PyArrayObject *self, PyObject *args) { PyObject *obj; PyArrayObject *arr, *ret; PyArray_Descr *dtype; if (PyTuple_Size(args) < 1) { PyErr_SetString(PyExc_TypeError, "only accepts 1 argument"); return NULL; } obj = PyTuple_GET_ITEM(args, 0); if (!PyArray_Check(obj)) { PyErr_SetString(PyExc_TypeError, "can only be called with ndarray object"); return NULL; } arr = (PyArrayObject *)obj; if (Py_TYPE(self) == Py_TYPE(arr)) { /* No need to create a new view */ Py_INCREF(arr); return (PyObject *)arr; } dtype = PyArray_DESCR(arr); Py_INCREF(dtype); ret = (PyArrayObject *)PyArray_NewFromDescr(Py_TYPE(self), dtype, PyArray_NDIM(arr), PyArray_DIMS(arr), PyArray_STRIDES(arr), PyArray_DATA(arr), PyArray_FLAGS(arr), (PyObject *)self); if (ret == NULL) { return NULL; } Py_INCREF(arr); if (PyArray_SetBaseObject(ret, (PyObject *)arr) < 0) { Py_DECREF(ret); return NULL; } return (PyObject *)ret; } static PyObject * array_getarray(PyArrayObject *self, PyObject *args) { PyArray_Descr *newtype = NULL; PyObject *ret; if (!PyArg_ParseTuple(args, "|O&", PyArray_DescrConverter, &newtype)) { Py_XDECREF(newtype); return NULL; } /* convert to PyArray_Type */ if (!PyArray_CheckExact(self)) { PyArrayObject *new; PyTypeObject *subtype = &PyArray_Type; if (!PyType_IsSubtype(Py_TYPE(self), &PyArray_Type)) { subtype = &PyArray_Type; } Py_INCREF(PyArray_DESCR(self)); new = (PyArrayObject *)PyArray_NewFromDescr(subtype, PyArray_DESCR(self), PyArray_NDIM(self), PyArray_DIMS(self), PyArray_STRIDES(self), PyArray_DATA(self), PyArray_FLAGS(self), NULL); if (new == NULL) { return NULL; } Py_INCREF(self); PyArray_SetBaseObject(new, (PyObject *)self); self = new; } else { Py_INCREF(self); } if ((newtype == NULL) || PyArray_EquivTypes(PyArray_DESCR(self), newtype)) { return (PyObject *)self; } else { ret = PyArray_CastToType(self, newtype, 0); Py_DECREF(self); return ret; } } static PyObject * array_copy(PyArrayObject *self, PyObject *args, PyObject *kwds) { NPY_ORDER order = NPY_CORDER; static char *kwlist[] = {"order", NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O&", kwlist, PyArray_OrderConverter, &order)) { return NULL; } return PyArray_NewCopy(self, order); } /* Separate from array_copy to make __copy__ preserve Fortran contiguity. */ static PyObject * array_copy_keeporder(PyArrayObject *self, PyObject *args, PyObject *kwds) { if (!PyArg_ParseTuple(args, "")) { return NULL; } return PyArray_NewCopy(self, NPY_KEEPORDER); } #include static PyObject * array_resize(PyArrayObject *self, PyObject *args, PyObject *kwds) { static char *kwlist[] = {"refcheck", NULL}; Py_ssize_t size = PyTuple_Size(args); int refcheck = 1; PyArray_Dims newshape; PyObject *ret, *obj; if (!NpyArg_ParseKeywords(kwds, "|i", kwlist, &refcheck)) { return NULL; } if (size == 0) { Py_INCREF(Py_None); return Py_None; } else if (size == 1) { obj = PyTuple_GET_ITEM(args, 0); if (obj == Py_None) { Py_INCREF(Py_None); return Py_None; } args = obj; } if (!PyArray_IntpConverter(args, &newshape)) { if (!PyErr_Occurred()) { PyErr_SetString(PyExc_TypeError, "invalid shape"); } return NULL; } ret = PyArray_Resize(self, &newshape, refcheck, NPY_CORDER); PyDimMem_FREE(newshape.ptr); if (ret == NULL) { return NULL; } Py_DECREF(ret); Py_INCREF(Py_None); return Py_None; } static PyObject * array_repeat(PyArrayObject *self, PyObject *args, PyObject *kwds) { PyObject *repeats; int axis = NPY_MAXDIMS; static char *kwlist[] = {"repeats", "axis", NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O&", kwlist, &repeats, PyArray_AxisConverter, &axis)) { return NULL; } return PyArray_Return((PyArrayObject *)PyArray_Repeat(self, repeats, axis)); } static PyObject * array_choose(PyArrayObject *self, PyObject *args, PyObject *kwds) { static char *keywords[] = {"out", "mode", NULL}; PyObject *choices; PyArrayObject *out = NULL; NPY_CLIPMODE clipmode = NPY_RAISE; Py_ssize_t n = PyTuple_Size(args); if (n <= 1) { if (!PyArg_ParseTuple(args, "O", &choices)) { return NULL; } } else { choices = args; } if (!NpyArg_ParseKeywords(kwds, "|O&O&", keywords, PyArray_OutputConverter, &out, PyArray_ClipmodeConverter, &clipmode)) { return NULL; } return PyArray_Return((PyArrayObject *)PyArray_Choose(self, choices, out, clipmode)); } static PyObject * array_sort(PyArrayObject *self, PyObject *args, PyObject *kwds) { int axis=-1; int val; NPY_SORTKIND sortkind = NPY_QUICKSORT; PyObject *order = NULL; PyArray_Descr *saved = NULL; PyArray_Descr *newd; static char *kwlist[] = {"axis", "kind", "order", NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "|iO&O", kwlist, &axis, PyArray_SortkindConverter, &sortkind, &order)) { return NULL; } if (order == Py_None) { order = NULL; } if (order != NULL) { PyObject *new_name; PyObject *_numpy_internal; saved = PyArray_DESCR(self); if (!PyDataType_HASFIELDS(saved)) { PyErr_SetString(PyExc_ValueError, "Cannot specify " \ "order when the array has no fields."); return NULL; } _numpy_internal = PyImport_ImportModule("numpy.core._internal"); if (_numpy_internal == NULL) { return NULL; } new_name = PyObject_CallMethod(_numpy_internal, "_newnames", "OO", saved, order); Py_DECREF(_numpy_internal); if (new_name == NULL) { return NULL; } newd = PyArray_DescrNew(saved); Py_DECREF(newd->names); newd->names = new_name; ((PyArrayObject_fields *)self)->descr = newd; } val = PyArray_Sort(self, axis, sortkind); if (order != NULL) { Py_XDECREF(PyArray_DESCR(self)); ((PyArrayObject_fields *)self)->descr = saved; } if (val < 0) { return NULL; } Py_INCREF(Py_None); return Py_None; } static PyObject * array_partition(PyArrayObject *self, PyObject *args, PyObject *kwds) { int axis=-1; int val; NPY_SELECTKIND sortkind = NPY_INTROSELECT; PyObject *order = NULL; PyArray_Descr *saved = NULL; PyArray_Descr *newd; static char *kwlist[] = {"kth", "axis", "kind", "order", NULL}; PyArrayObject * ktharray; PyObject * kthobj; if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|iO&O", kwlist, &kthobj, &axis, PyArray_SelectkindConverter, &sortkind, &order)) { return NULL; } if (order == Py_None) { order = NULL; } if (order != NULL) { PyObject *new_name; PyObject *_numpy_internal; saved = PyArray_DESCR(self); if (!PyDataType_HASFIELDS(saved)) { PyErr_SetString(PyExc_ValueError, "Cannot specify " \ "order when the array has no fields."); return NULL; } _numpy_internal = PyImport_ImportModule("numpy.core._internal"); if (_numpy_internal == NULL) { return NULL; } new_name = PyObject_CallMethod(_numpy_internal, "_newnames", "OO", saved, order); Py_DECREF(_numpy_internal); if (new_name == NULL) { return NULL; } newd = PyArray_DescrNew(saved); Py_DECREF(newd->names); newd->names = new_name; ((PyArrayObject_fields *)self)->descr = newd; } ktharray = (PyArrayObject *)PyArray_FromAny(kthobj, NULL, 0, 1, NPY_ARRAY_DEFAULT, NULL); if (ktharray == NULL) return NULL; val = PyArray_Partition(self, ktharray, axis, sortkind); Py_DECREF(ktharray); if (order != NULL) { Py_XDECREF(PyArray_DESCR(self)); ((PyArrayObject_fields *)self)->descr = saved; } if (val < 0) { return NULL; } Py_INCREF(Py_None); return Py_None; } static PyObject * array_argsort(PyArrayObject *self, PyObject *args, PyObject *kwds) { int axis = -1; NPY_SORTKIND sortkind = NPY_QUICKSORT; PyObject *order = NULL, *res; PyArray_Descr *newd, *saved=NULL; static char *kwlist[] = {"axis", "kind", "order", NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O&O&O", kwlist, PyArray_AxisConverter, &axis, PyArray_SortkindConverter, &sortkind, &order)) { return NULL; } if (order == Py_None) { order = NULL; } if (order != NULL) { PyObject *new_name; PyObject *_numpy_internal; saved = PyArray_DESCR(self); if (!PyDataType_HASFIELDS(saved)) { PyErr_SetString(PyExc_ValueError, "Cannot specify " "order when the array has no fields."); return NULL; } _numpy_internal = PyImport_ImportModule("numpy.core._internal"); if (_numpy_internal == NULL) { return NULL; } new_name = PyObject_CallMethod(_numpy_internal, "_newnames", "OO", saved, order); Py_DECREF(_numpy_internal); if (new_name == NULL) { return NULL; } newd = PyArray_DescrNew(saved); newd->names = new_name; ((PyArrayObject_fields *)self)->descr = newd; } res = PyArray_ArgSort(self, axis, sortkind); if (order != NULL) { Py_XDECREF(PyArray_DESCR(self)); ((PyArrayObject_fields *)self)->descr = saved; } return PyArray_Return((PyArrayObject *)res); } static PyObject * array_argpartition(PyArrayObject *self, PyObject *args, PyObject *kwds) { int axis = -1; NPY_SELECTKIND sortkind = NPY_INTROSELECT; PyObject *order = NULL, *res; PyArray_Descr *newd, *saved=NULL; static char *kwlist[] = {"kth", "axis", "kind", "order", NULL}; PyObject * kthobj; PyArrayObject * ktharray; if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O&O&O", kwlist, &kthobj, PyArray_AxisConverter, &axis, PyArray_SelectkindConverter, &sortkind, &order)) { return NULL; } if (order == Py_None) { order = NULL; } if (order != NULL) { PyObject *new_name; PyObject *_numpy_internal; saved = PyArray_DESCR(self); if (!PyDataType_HASFIELDS(saved)) { PyErr_SetString(PyExc_ValueError, "Cannot specify " "order when the array has no fields."); return NULL; } _numpy_internal = PyImport_ImportModule("numpy.core._internal"); if (_numpy_internal == NULL) { return NULL; } new_name = PyObject_CallMethod(_numpy_internal, "_newnames", "OO", saved, order); Py_DECREF(_numpy_internal); if (new_name == NULL) { return NULL; } newd = PyArray_DescrNew(saved); newd->names = new_name; ((PyArrayObject_fields *)self)->descr = newd; } ktharray = (PyArrayObject *)PyArray_FromAny(kthobj, NULL, 0, 1, NPY_ARRAY_DEFAULT, NULL); if (ktharray == NULL) return NULL; res = PyArray_ArgPartition(self, ktharray, axis, sortkind); Py_DECREF(ktharray); if (order != NULL) { Py_XDECREF(PyArray_DESCR(self)); ((PyArrayObject_fields *)self)->descr = saved; } return PyArray_Return((PyArrayObject *)res); } static PyObject * array_searchsorted(PyArrayObject *self, PyObject *args, PyObject *kwds) { static char *kwlist[] = {"keys", "side", "sorter", NULL}; PyObject *keys; PyObject *sorter; NPY_SEARCHSIDE side = NPY_SEARCHLEFT; sorter = NULL; if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O&O:searchsorted", kwlist, &keys, PyArray_SearchsideConverter, &side, &sorter)) { return NULL; } if (sorter == Py_None) { sorter = NULL; } return PyArray_Return((PyArrayObject *)PyArray_SearchSorted(self, keys, side, sorter)); } static void _deepcopy_call(char *iptr, char *optr, PyArray_Descr *dtype, PyObject *deepcopy, PyObject *visit) { if (!PyDataType_REFCHK(dtype)) { return; } else if (PyDataType_HASFIELDS(dtype)) { PyObject *key, *value, *title = NULL; PyArray_Descr *new; int offset; Py_ssize_t pos = 0; while (PyDict_Next(dtype->fields, &pos, &key, &value)) { if NPY_TITLE_KEY(key, value) { continue; } if (!PyArg_ParseTuple(value, "Oi|O", &new, &offset, &title)) { return; } _deepcopy_call(iptr + offset, optr + offset, new, deepcopy, visit); } } else { PyObject *itemp, *otemp; PyObject *res; NPY_COPY_PYOBJECT_PTR(&itemp, iptr); NPY_COPY_PYOBJECT_PTR(&otemp, optr); Py_XINCREF(itemp); /* call deepcopy on this argument */ res = PyObject_CallFunctionObjArgs(deepcopy, itemp, visit, NULL); Py_XDECREF(itemp); Py_XDECREF(otemp); NPY_COPY_PYOBJECT_PTR(optr, &res); } } static PyObject * array_deepcopy(PyArrayObject *self, PyObject *args) { PyObject* visit; char *optr; PyArrayIterObject *it; PyObject *copy, *deepcopy; PyArrayObject *ret; if (!PyArg_ParseTuple(args, "O", &visit)) { return NULL; } ret = (PyArrayObject *)PyArray_NewCopy(self, NPY_KEEPORDER); if (PyDataType_REFCHK(PyArray_DESCR(self))) { copy = PyImport_ImportModule("copy"); if (copy == NULL) { return NULL; } deepcopy = PyObject_GetAttrString(copy, "deepcopy"); Py_DECREF(copy); if (deepcopy == NULL) { return NULL; } it = (PyArrayIterObject *)PyArray_IterNew((PyObject *)self); if (it == NULL) { Py_DECREF(deepcopy); return NULL; } optr = PyArray_DATA(ret); while(it->index < it->size) { _deepcopy_call(it->dataptr, optr, PyArray_DESCR(self), deepcopy, visit); optr += PyArray_DESCR(self)->elsize; PyArray_ITER_NEXT(it); } Py_DECREF(deepcopy); Py_DECREF(it); } return PyArray_Return(ret); } /* Convert Array to flat list (using getitem) */ static PyObject * _getlist_pkl(PyArrayObject *self) { PyObject *theobject; PyArrayIterObject *iter = NULL; PyObject *list; PyArray_GetItemFunc *getitem; getitem = PyArray_DESCR(self)->f->getitem; iter = (PyArrayIterObject *)PyArray_IterNew((PyObject *)self); if (iter == NULL) { return NULL; } list = PyList_New(iter->size); if (list == NULL) { Py_DECREF(iter); return NULL; } while (iter->index < iter->size) { theobject = getitem(iter->dataptr, self); PyList_SET_ITEM(list, (int) iter->index, theobject); PyArray_ITER_NEXT(iter); } Py_DECREF(iter); return list; } static int _setlist_pkl(PyArrayObject *self, PyObject *list) { PyObject *theobject; PyArrayIterObject *iter = NULL; PyArray_SetItemFunc *setitem; setitem = PyArray_DESCR(self)->f->setitem; iter = (PyArrayIterObject *)PyArray_IterNew((PyObject *)self); if (iter == NULL) { return -1; } while(iter->index < iter->size) { theobject = PyList_GET_ITEM(list, (int) iter->index); setitem(theobject, iter->dataptr, self); PyArray_ITER_NEXT(iter); } Py_XDECREF(iter); return 0; } static PyObject * array_reduce(PyArrayObject *self, PyObject *NPY_UNUSED(args)) { /* version number of this pickle type. Increment if we need to change the format. Be sure to handle the old versions in array_setstate. */ const int version = 1; PyObject *ret = NULL, *state = NULL, *obj = NULL, *mod = NULL; PyObject *mybool, *thestr = NULL; PyArray_Descr *descr; /* Return a tuple of (callable object, arguments, object's state) */ /* We will put everything in the object's state, so that on UnPickle it can use the string object as memory without a copy */ ret = PyTuple_New(3); if (ret == NULL) { return NULL; } mod = PyImport_ImportModule("numpy.core.multiarray"); if (mod == NULL) { Py_DECREF(ret); return NULL; } obj = PyObject_GetAttrString(mod, "_reconstruct"); Py_DECREF(mod); PyTuple_SET_ITEM(ret, 0, obj); PyTuple_SET_ITEM(ret, 1, Py_BuildValue("ONc", (PyObject *)Py_TYPE(self), Py_BuildValue("(N)", PyInt_FromLong(0)), /* dummy data-type */ 'b')); /* Now fill in object's state. This is a tuple with 5 arguments 1) an integer with the pickle version. 2) a Tuple giving the shape 3) a PyArray_Descr Object (with correct bytorder set) 4) a npy_bool stating if Fortran or not 5) a Python object representing the data (a string, or a list or any user-defined object). Notice because Python does not describe a mechanism to write raw data to the pickle, this performs a copy to a string first */ state = PyTuple_New(5); if (state == NULL) { Py_DECREF(ret); return NULL; } PyTuple_SET_ITEM(state, 0, PyInt_FromLong(version)); PyTuple_SET_ITEM(state, 1, PyObject_GetAttrString((PyObject *)self, "shape")); descr = PyArray_DESCR(self); Py_INCREF(descr); PyTuple_SET_ITEM(state, 2, (PyObject *)descr); mybool = (PyArray_ISFORTRAN(self) ? Py_True : Py_False); Py_INCREF(mybool); PyTuple_SET_ITEM(state, 3, mybool); if (PyDataType_FLAGCHK(PyArray_DESCR(self), NPY_LIST_PICKLE)) { thestr = _getlist_pkl(self); } else { thestr = PyArray_ToString(self, NPY_ANYORDER); } if (thestr == NULL) { Py_DECREF(ret); Py_DECREF(state); return NULL; } PyTuple_SET_ITEM(state, 4, thestr); PyTuple_SET_ITEM(ret, 2, state); return ret; } static PyObject * array_setstate(PyArrayObject *self, PyObject *args) { PyObject *shape; PyArray_Descr *typecode; int version = 1; int is_f_order; PyObject *rawdata = NULL; char *datastr; Py_ssize_t len; npy_intp size, dimensions[NPY_MAXDIMS]; int nd; PyArrayObject_fields *fa = (PyArrayObject_fields *)self; /* This will free any memory associated with a and use the string in setstate as the (writeable) memory. */ if (!PyArg_ParseTuple(args, "(iO!O!iO)", &version, &PyTuple_Type, &shape, &PyArrayDescr_Type, &typecode, &is_f_order, &rawdata)) { PyErr_Clear(); version = 0; if (!PyArg_ParseTuple(args, "(O!O!iO)", &PyTuple_Type, &shape, &PyArrayDescr_Type, &typecode, &is_f_order, &rawdata)) { return NULL; } } /* If we ever need another pickle format, increment the version number. But we should still be able to handle the old versions. We've only got one right now. */ if (version != 1 && version != 0) { PyErr_Format(PyExc_ValueError, "can't handle version %d of numpy.ndarray pickle", version); return NULL; } Py_XDECREF(PyArray_DESCR(self)); fa->descr = typecode; Py_INCREF(typecode); nd = PyArray_IntpFromSequence(shape, dimensions, NPY_MAXDIMS); if (nd < 0) { return NULL; } size = PyArray_MultiplyList(dimensions, nd); if (PyArray_DESCR(self)->elsize == 0) { PyErr_SetString(PyExc_ValueError, "Invalid data-type size."); return NULL; } if (size < 0 || size > NPY_MAX_INTP / PyArray_DESCR(self)->elsize) { PyErr_NoMemory(); return NULL; } if (PyDataType_FLAGCHK(typecode, NPY_LIST_PICKLE)) { if (!PyList_Check(rawdata)) { PyErr_SetString(PyExc_TypeError, "object pickle not returning list"); return NULL; } } else { Py_INCREF(rawdata); #if defined(NPY_PY3K) /* Backward compatibility with Python 2 Numpy pickles */ if (PyUnicode_Check(rawdata)) { PyObject *tmp; tmp = PyUnicode_AsLatin1String(rawdata); Py_DECREF(rawdata); rawdata = tmp; } #endif if (!PyBytes_Check(rawdata)) { PyErr_SetString(PyExc_TypeError, "pickle not returning string"); Py_DECREF(rawdata); return NULL; } if (PyBytes_AsStringAndSize(rawdata, &datastr, &len)) { Py_DECREF(rawdata); return NULL; } if ((len != (PyArray_DESCR(self)->elsize * size))) { PyErr_SetString(PyExc_ValueError, "buffer size does not" \ " match array size"); Py_DECREF(rawdata); return NULL; } } if ((PyArray_FLAGS(self) & NPY_ARRAY_OWNDATA)) { if (PyArray_DATA(self) != NULL) { PyDataMem_FREE(PyArray_DATA(self)); } PyArray_CLEARFLAGS(self, NPY_ARRAY_OWNDATA); } Py_XDECREF(PyArray_BASE(self)); fa->base = NULL; PyArray_CLEARFLAGS(self, NPY_ARRAY_UPDATEIFCOPY); if (PyArray_DIMS(self) != NULL) { PyDimMem_FREE(PyArray_DIMS(self)); fa->dimensions = NULL; } fa->flags = NPY_ARRAY_DEFAULT; fa->nd = nd; 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, PyArray_DESCR(self)->elsize, (is_f_order ? NPY_ARRAY_F_CONTIGUOUS : NPY_ARRAY_C_CONTIGUOUS), &(fa->flags)); } if (!PyDataType_FLAGCHK(typecode, NPY_LIST_PICKLE)) { int swap=!PyArray_ISNOTSWAPPED(self); fa->data = datastr; #ifndef NPY_PY3K /* Check that the string is not interned */ if (!_IsAligned(self) || swap || PyString_CHECK_INTERNED(rawdata)) { #else /* Bytes should always be considered immutable, but we just grab the * pointer if they are large, to save memory. */ if (!_IsAligned(self) || swap || (len <= 1000)) { #endif npy_intp num = PyArray_NBYTES(self); fa->data = PyDataMem_NEW(num); if (PyArray_DATA(self) == NULL) { fa->nd = 0; PyDimMem_FREE(PyArray_DIMS(self)); Py_DECREF(rawdata); return PyErr_NoMemory(); } if (swap) { /* byte-swap on pickle-read */ npy_intp numels = num / PyArray_DESCR(self)->elsize; PyArray_DESCR(self)->f->copyswapn(PyArray_DATA(self), PyArray_DESCR(self)->elsize, datastr, PyArray_DESCR(self)->elsize, numels, 1, self); if (!PyArray_ISEXTENDED(self)) { fa->descr = PyArray_DescrFromType( PyArray_DESCR(self)->type_num); } else { fa->descr = PyArray_DescrNew(typecode); if (PyArray_DESCR(self)->byteorder == NPY_BIG) { PyArray_DESCR(self)->byteorder = NPY_LITTLE; } else if (PyArray_DESCR(self)->byteorder == NPY_LITTLE) { PyArray_DESCR(self)->byteorder = NPY_BIG; } } Py_DECREF(typecode); } else { memcpy(PyArray_DATA(self), datastr, num); } PyArray_ENABLEFLAGS(self, NPY_ARRAY_OWNDATA); fa->base = NULL; Py_DECREF(rawdata); } else { if (PyArray_SetBaseObject(self, rawdata) < 0) { return NULL; } } } else { fa->data = PyDataMem_NEW(PyArray_NBYTES(self)); if (PyArray_DATA(self) == NULL) { fa->nd = 0; fa->data = PyDataMem_NEW(PyArray_DESCR(self)->elsize); if (PyArray_DIMS(self)) { PyDimMem_FREE(PyArray_DIMS(self)); } return PyErr_NoMemory(); } if (PyDataType_FLAGCHK(PyArray_DESCR(self), NPY_NEEDS_INIT)) { memset(PyArray_DATA(self), 0, PyArray_NBYTES(self)); } PyArray_ENABLEFLAGS(self, NPY_ARRAY_OWNDATA); fa->base = NULL; if (_setlist_pkl(self, rawdata) < 0) { return NULL; } } PyArray_UpdateFlags(self, NPY_ARRAY_UPDATE_ALL); Py_INCREF(Py_None); return Py_None; } /*NUMPY_API*/ NPY_NO_EXPORT int PyArray_Dump(PyObject *self, PyObject *file, int protocol) { PyObject *cpick = NULL; PyObject *ret; if (protocol < 0) { protocol = 2; } #if defined(NPY_PY3K) cpick = PyImport_ImportModule("pickle"); #else cpick = PyImport_ImportModule("cPickle"); #endif if (cpick == NULL) { return -1; } if (PyBytes_Check(file) || PyUnicode_Check(file)) { file = npy_PyFile_OpenFile(file, "wb"); if (file == NULL) { return -1; } } else { Py_INCREF(file); } ret = PyObject_CallMethod(cpick, "dump", "OOi", self, file, protocol); Py_XDECREF(ret); Py_DECREF(file); Py_DECREF(cpick); if (PyErr_Occurred()) { return -1; } return 0; } /*NUMPY_API*/ NPY_NO_EXPORT PyObject * PyArray_Dumps(PyObject *self, int protocol) { PyObject *cpick = NULL; PyObject *ret; if (protocol < 0) { protocol = 2; } #if defined(NPY_PY3K) cpick = PyImport_ImportModule("pickle"); #else cpick = PyImport_ImportModule("cPickle"); #endif if (cpick == NULL) { return NULL; } ret = PyObject_CallMethod(cpick, "dumps", "Oi", self, protocol); Py_DECREF(cpick); return ret; } static PyObject * array_dump(PyArrayObject *self, PyObject *args) { PyObject *file = NULL; int ret; if (!PyArg_ParseTuple(args, "O", &file)) { return NULL; } ret = PyArray_Dump((PyObject *)self, file, 2); if (ret < 0) { return NULL; } Py_INCREF(Py_None); return Py_None; } static PyObject * array_dumps(PyArrayObject *self, PyObject *args) { if (!PyArg_ParseTuple(args, "")) { return NULL; } return PyArray_Dumps((PyObject *)self, 2); } static PyObject * array_transpose(PyArrayObject *self, PyObject *args) { PyObject *shape = Py_None; Py_ssize_t n = PyTuple_Size(args); PyArray_Dims permute; PyObject *ret; if (n > 1) { shape = args; } else if (n == 1) { shape = PyTuple_GET_ITEM(args, 0); } if (shape == Py_None) { ret = PyArray_Transpose(self, NULL); } else { if (!PyArray_IntpConverter(shape, &permute)) { return NULL; } ret = PyArray_Transpose(self, &permute); PyDimMem_FREE(permute.ptr); } return ret; } #define _CHKTYPENUM(typ) ((typ) ? (typ)->type_num : NPY_NOTYPE) static PyObject * array_mean(PyArrayObject *self, PyObject *args, PyObject *kwds) { NPY_FORWARD_NDARRAY_METHOD("_mean"); } static PyObject * array_sum(PyArrayObject *self, PyObject *args, PyObject *kwds) { NPY_FORWARD_NDARRAY_METHOD("_sum"); } static PyObject * array_cumsum(PyArrayObject *self, PyObject *args, PyObject *kwds) { int axis = NPY_MAXDIMS; PyArray_Descr *dtype = NULL; PyArrayObject *out = NULL; int rtype; static char *kwlist[] = {"axis", "dtype", "out", NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O&O&O&", kwlist, PyArray_AxisConverter, &axis, PyArray_DescrConverter2, &dtype, PyArray_OutputConverter, &out)) { Py_XDECREF(dtype); return NULL; } rtype = _CHKTYPENUM(dtype); Py_XDECREF(dtype); return PyArray_CumSum(self, axis, rtype, out); } static PyObject * array_prod(PyArrayObject *self, PyObject *args, PyObject *kwds) { NPY_FORWARD_NDARRAY_METHOD("_prod"); } static PyObject * array_cumprod(PyArrayObject *self, PyObject *args, PyObject *kwds) { int axis = NPY_MAXDIMS; PyArray_Descr *dtype = NULL; PyArrayObject *out = NULL; int rtype; static char *kwlist[] = {"axis", "dtype", "out", NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O&O&O&", kwlist, PyArray_AxisConverter, &axis, PyArray_DescrConverter2, &dtype, PyArray_OutputConverter, &out)) { Py_XDECREF(dtype); return NULL; } rtype = _CHKTYPENUM(dtype); Py_XDECREF(dtype); return PyArray_CumProd(self, axis, rtype, out); } static PyObject * array_dot(PyArrayObject *self, PyObject *args, PyObject *kwds) { PyObject *fname, *ret, *b, *out = NULL; static PyObject *numpycore = NULL; char * kwords[] = {"b", "out", NULL }; if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O", kwords, &b, &out)) { return NULL; } /* Since blas-dot is exposed only on the Python side, we need to grab it * from there */ if (numpycore == NULL) { numpycore = PyImport_ImportModule("numpy.core"); if (numpycore == NULL) { return NULL; } } fname = PyUString_FromString("dot"); if (out == NULL) { ret = PyObject_CallMethodObjArgs(numpycore, fname, self, b, NULL); } else { ret = PyObject_CallMethodObjArgs(numpycore, fname, self, b, out, NULL); } Py_DECREF(fname); return ret; } static PyObject * array_any(PyArrayObject *self, PyObject *args, PyObject *kwds) { NPY_FORWARD_NDARRAY_METHOD("_any"); } static PyObject * array_all(PyArrayObject *self, PyObject *args, PyObject *kwds) { NPY_FORWARD_NDARRAY_METHOD("_all"); } static PyObject * array_stddev(PyArrayObject *self, PyObject *args, PyObject *kwds) { NPY_FORWARD_NDARRAY_METHOD("_std"); } static PyObject * array_variance(PyArrayObject *self, PyObject *args, PyObject *kwds) { NPY_FORWARD_NDARRAY_METHOD("_var"); } static PyObject * array_compress(PyArrayObject *self, PyObject *args, PyObject *kwds) { int axis = NPY_MAXDIMS; PyObject *condition; PyArrayObject *out = NULL; static char *kwlist[] = {"condition", "axis", "out", NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O&O&", kwlist, &condition, PyArray_AxisConverter, &axis, PyArray_OutputConverter, &out)) { return NULL; } return PyArray_Return( (PyArrayObject *)PyArray_Compress(self, condition, axis, out)); } static PyObject * array_nonzero(PyArrayObject *self, PyObject *args) { if (!PyArg_ParseTuple(args, "")) { return NULL; } return PyArray_Nonzero(self); } static PyObject * array_trace(PyArrayObject *self, PyObject *args, PyObject *kwds) { int axis1 = 0, axis2 = 1, offset = 0; PyArray_Descr *dtype = NULL; PyArrayObject *out = NULL; int rtype; static char *kwlist[] = {"offset", "axis1", "axis2", "dtype", "out", NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "|iiiO&O&", kwlist, &offset, &axis1, &axis2, PyArray_DescrConverter2, &dtype, PyArray_OutputConverter, &out)) { Py_XDECREF(dtype); return NULL; } rtype = _CHKTYPENUM(dtype); Py_XDECREF(dtype); return PyArray_Return((PyArrayObject *)PyArray_Trace(self, offset, axis1, axis2, rtype, out)); } #undef _CHKTYPENUM static PyObject * array_clip(PyArrayObject *self, PyObject *args, PyObject *kwds) { PyObject *min = NULL, *max = NULL; PyArrayObject *out = NULL; static char *kwlist[] = {"min", "max", "out", NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OOO&", kwlist, &min, &max, PyArray_OutputConverter, &out)) { return NULL; } if (max == NULL && min == NULL) { PyErr_SetString(PyExc_ValueError, "One of max or min must be given."); return NULL; } return PyArray_Return((PyArrayObject *)PyArray_Clip(self, min, max, out)); } static PyObject * array_conjugate(PyArrayObject *self, PyObject *args) { PyArrayObject *out = NULL; if (!PyArg_ParseTuple(args, "|O&", PyArray_OutputConverter, &out)) { return NULL; } return PyArray_Conjugate(self, out); } static PyObject * array_diagonal(PyArrayObject *self, PyObject *args, PyObject *kwds) { int axis1 = 0, axis2 = 1, offset = 0; static char *kwlist[] = {"offset", "axis1", "axis2", NULL}; PyArrayObject *ret; if (!PyArg_ParseTupleAndKeywords(args, kwds, "|iii", kwlist, &offset, &axis1, &axis2)) { return NULL; } ret = (PyArrayObject *)PyArray_Diagonal(self, offset, axis1, axis2); return PyArray_Return(ret); } static PyObject * array_flatten(PyArrayObject *self, PyObject *args, PyObject *kwds) { NPY_ORDER order = NPY_CORDER; static char *kwlist[] = {"order", NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O&", kwlist, PyArray_OrderConverter, &order)) { return NULL; } return PyArray_Flatten(self, order); } static PyObject * array_ravel(PyArrayObject *self, PyObject *args, PyObject *kwds) { NPY_ORDER order = NPY_CORDER; static char *kwlist[] = {"order", NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O&", kwlist, PyArray_OrderConverter, &order)) { return NULL; } return PyArray_Ravel(self, order); } static PyObject * array_round(PyArrayObject *self, PyObject *args, PyObject *kwds) { int decimals = 0; PyArrayObject *out = NULL; static char *kwlist[] = {"decimals", "out", NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "|iO&", kwlist, &decimals, PyArray_OutputConverter, &out)) { return NULL; } return PyArray_Return((PyArrayObject *)PyArray_Round(self, decimals, out)); } static PyObject * array_setflags(PyArrayObject *self, PyObject *args, PyObject *kwds) { static char *kwlist[] = {"write", "align", "uic", NULL}; PyObject *write_flag = Py_None; PyObject *align_flag = Py_None; PyObject *uic = Py_None; int flagback = PyArray_FLAGS(self); PyArrayObject_fields *fa = (PyArrayObject_fields *)self; if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OOO", kwlist, &write_flag, &align_flag, &uic)) return NULL; if (align_flag != Py_None) { if (PyObject_Not(align_flag)) { PyArray_CLEARFLAGS(self, NPY_ARRAY_ALIGNED); } else if (_IsAligned(self)) { PyArray_ENABLEFLAGS(self, NPY_ARRAY_ALIGNED); } else { PyErr_SetString(PyExc_ValueError, "cannot set aligned flag of mis-"\ "aligned array to True"); return NULL; } } if (uic != Py_None) { if (PyObject_IsTrue(uic)) { fa->flags = flagback; PyErr_SetString(PyExc_ValueError, "cannot set UPDATEIFCOPY " \ "flag to True"); return NULL; } else { PyArray_CLEARFLAGS(self, NPY_ARRAY_UPDATEIFCOPY); Py_XDECREF(fa->base); fa->base = NULL; } } if (write_flag != Py_None) { if (PyObject_IsTrue(write_flag)) { if (_IsWriteable(self)) { PyArray_ENABLEFLAGS(self, NPY_ARRAY_WRITEABLE); } else { fa->flags = flagback; PyErr_SetString(PyExc_ValueError, "cannot set WRITEABLE " "flag to True of this " "array"); return NULL; } } else { PyArray_CLEARFLAGS(self, NPY_ARRAY_WRITEABLE); } } Py_INCREF(Py_None); return Py_None; } static PyObject * array_newbyteorder(PyArrayObject *self, PyObject *args) { char endian = NPY_SWAP; PyArray_Descr *new; if (!PyArg_ParseTuple(args, "|O&", PyArray_ByteorderConverter, &endian)) { return NULL; } new = PyArray_DescrNewByteorder(PyArray_DESCR(self), endian); if (!new) { return NULL; } return PyArray_View(self, new, NULL); } NPY_NO_EXPORT PyMethodDef array_methods[] = { /* for subtypes */ {"__array__", (PyCFunction)array_getarray, METH_VARARGS, NULL}, {"__array_prepare__", (PyCFunction)array_preparearray, METH_VARARGS, NULL}, {"__array_wrap__", (PyCFunction)array_wraparray, METH_VARARGS, NULL}, /* for the copy module */ {"__copy__", (PyCFunction)array_copy_keeporder, METH_VARARGS, NULL}, {"__deepcopy__", (PyCFunction)array_deepcopy, METH_VARARGS, NULL}, /* for Pickling */ {"__reduce__", (PyCFunction) array_reduce, METH_VARARGS, NULL}, {"__setstate__", (PyCFunction) array_setstate, METH_VARARGS, NULL}, {"dumps", (PyCFunction) array_dumps, METH_VARARGS, NULL}, {"dump", (PyCFunction) array_dump, METH_VARARGS, NULL}, /* Original and Extended methods added 2005 */ {"all", (PyCFunction)array_all, METH_VARARGS | METH_KEYWORDS, NULL}, {"any", (PyCFunction)array_any, METH_VARARGS | METH_KEYWORDS, NULL}, {"argmax", (PyCFunction)array_argmax, METH_VARARGS | METH_KEYWORDS, NULL}, {"argmin", (PyCFunction)array_argmin, METH_VARARGS | METH_KEYWORDS, NULL}, {"argpartition", (PyCFunction)array_argpartition, METH_VARARGS | METH_KEYWORDS, NULL}, {"argsort", (PyCFunction)array_argsort, METH_VARARGS | METH_KEYWORDS, NULL}, {"astype", (PyCFunction)array_astype, METH_VARARGS | METH_KEYWORDS, NULL}, {"byteswap", (PyCFunction)array_byteswap, METH_VARARGS, NULL}, {"choose", (PyCFunction)array_choose, METH_VARARGS | METH_KEYWORDS, NULL}, {"clip", (PyCFunction)array_clip, METH_VARARGS | METH_KEYWORDS, NULL}, {"compress", (PyCFunction)array_compress, METH_VARARGS | METH_KEYWORDS, NULL}, {"conj", (PyCFunction)array_conjugate, METH_VARARGS, NULL}, {"conjugate", (PyCFunction)array_conjugate, METH_VARARGS, NULL}, {"copy", (PyCFunction)array_copy, METH_VARARGS | METH_KEYWORDS, NULL}, {"cumprod", (PyCFunction)array_cumprod, METH_VARARGS | METH_KEYWORDS, NULL}, {"cumsum", (PyCFunction)array_cumsum, METH_VARARGS | METH_KEYWORDS, NULL}, {"diagonal", (PyCFunction)array_diagonal, METH_VARARGS | METH_KEYWORDS, NULL}, {"dot", (PyCFunction)array_dot, METH_VARARGS | METH_KEYWORDS, NULL}, {"fill", (PyCFunction)array_fill, METH_VARARGS, NULL}, {"flatten", (PyCFunction)array_flatten, METH_VARARGS | METH_KEYWORDS, NULL}, {"getfield", (PyCFunction)array_getfield, METH_VARARGS | METH_KEYWORDS, NULL}, {"item", (PyCFunction)array_toscalar, METH_VARARGS, NULL}, {"itemset", (PyCFunction) array_setscalar, METH_VARARGS, NULL}, {"max", (PyCFunction)array_max, METH_VARARGS | METH_KEYWORDS, NULL}, {"mean", (PyCFunction)array_mean, METH_VARARGS | METH_KEYWORDS, NULL}, {"min", (PyCFunction)array_min, METH_VARARGS | METH_KEYWORDS, NULL}, {"newbyteorder", (PyCFunction)array_newbyteorder, METH_VARARGS, NULL}, {"nonzero", (PyCFunction)array_nonzero, METH_VARARGS, NULL}, {"partition", (PyCFunction)array_partition, METH_VARARGS | METH_KEYWORDS, NULL}, {"prod", (PyCFunction)array_prod, METH_VARARGS | METH_KEYWORDS, NULL}, {"ptp", (PyCFunction)array_ptp, METH_VARARGS | METH_KEYWORDS, NULL}, {"put", (PyCFunction)array_put, METH_VARARGS | METH_KEYWORDS, NULL}, {"ravel", (PyCFunction)array_ravel, METH_VARARGS | METH_KEYWORDS, NULL}, {"repeat", (PyCFunction)array_repeat, METH_VARARGS | METH_KEYWORDS, NULL}, {"reshape", (PyCFunction)array_reshape, METH_VARARGS | METH_KEYWORDS, NULL}, {"resize", (PyCFunction)array_resize, METH_VARARGS | METH_KEYWORDS, NULL}, {"round", (PyCFunction)array_round, METH_VARARGS | METH_KEYWORDS, NULL}, {"searchsorted", (PyCFunction)array_searchsorted, METH_VARARGS | METH_KEYWORDS, NULL}, {"setfield", (PyCFunction)array_setfield, METH_VARARGS | METH_KEYWORDS, NULL}, {"setflags", (PyCFunction)array_setflags, METH_VARARGS | METH_KEYWORDS, NULL}, {"sort", (PyCFunction)array_sort, METH_VARARGS | METH_KEYWORDS, NULL}, {"squeeze", (PyCFunction)array_squeeze, METH_VARARGS | METH_KEYWORDS, NULL}, {"std", (PyCFunction)array_stddev, METH_VARARGS | METH_KEYWORDS, NULL}, {"sum", (PyCFunction)array_sum, METH_VARARGS | METH_KEYWORDS, NULL}, {"swapaxes", (PyCFunction)array_swapaxes, METH_VARARGS, NULL}, {"take", (PyCFunction)array_take, METH_VARARGS | METH_KEYWORDS, NULL}, {"tofile", (PyCFunction)array_tofile, METH_VARARGS | METH_KEYWORDS, NULL}, {"tolist", (PyCFunction)array_tolist, METH_VARARGS, NULL}, {"tostring", (PyCFunction)array_tostring, METH_VARARGS | METH_KEYWORDS, NULL}, {"trace", (PyCFunction)array_trace, METH_VARARGS | METH_KEYWORDS, NULL}, {"transpose", (PyCFunction)array_transpose, METH_VARARGS, NULL}, {"var", (PyCFunction)array_variance, METH_VARARGS | METH_KEYWORDS, NULL}, {"view", (PyCFunction)array_view, METH_VARARGS | METH_KEYWORDS, NULL}, {NULL, NULL, 0, NULL} /* sentinel */ }; numpy-1.8.2/numpy/core/src/multiarray/array_assign_array.c0000664000175100017510000003311112370216243025127 0ustar vagrantvagrant00000000000000/* * This file implements assignment from an ndarray to another ndarray. * * Written by Mark Wiebe (mwwiebe@gmail.com) * Copyright (c) 2011 by Enthought, Inc. * * See LICENSE.txt for the license. */ #define PY_SSIZE_T_CLEAN #include #define NPY_NO_DEPRECATED_API NPY_API_VERSION #define _MULTIARRAYMODULE #include #include "npy_config.h" #include "npy_pycompat.h" #include "convert_datatype.h" #include "methods.h" #include "shape.h" #include "lowlevel_strided_loops.h" #include "array_assign.h" /* * Assigns the array from 'src' to 'dst'. The strides must already have * been broadcast. * * Returns 0 on success, -1 on failure. */ NPY_NO_EXPORT int raw_array_assign_array(int ndim, npy_intp *shape, PyArray_Descr *dst_dtype, char *dst_data, npy_intp *dst_strides, PyArray_Descr *src_dtype, char *src_data, npy_intp *src_strides) { int idim; npy_intp shape_it[NPY_MAXDIMS]; npy_intp dst_strides_it[NPY_MAXDIMS]; npy_intp src_strides_it[NPY_MAXDIMS]; npy_intp coord[NPY_MAXDIMS]; PyArray_StridedUnaryOp *stransfer = NULL; NpyAuxData *transferdata = NULL; int aligned, needs_api = 0; npy_intp src_itemsize = src_dtype->elsize; NPY_BEGIN_THREADS_DEF; /* Check alignment */ aligned = raw_array_is_aligned(ndim, dst_data, dst_strides, dst_dtype->alignment) && raw_array_is_aligned(ndim, src_data, src_strides, src_dtype->alignment); /* Use raw iteration with no heap allocation */ if (PyArray_PrepareTwoRawArrayIter( ndim, shape, dst_data, dst_strides, src_data, src_strides, &ndim, shape_it, &dst_data, dst_strides_it, &src_data, src_strides_it) < 0) { return -1; } /* * Overlap check for the 1D case. Higher dimensional arrays and * opposite strides cause a temporary copy before getting here. */ if (ndim == 1 && src_data < dst_data && src_data + shape_it[0] * src_strides_it[0] > dst_data) { src_data += (shape_it[0] - 1) * src_strides_it[0]; dst_data += (shape_it[0] - 1) * dst_strides_it[0]; src_strides_it[0] = -src_strides_it[0]; dst_strides_it[0] = -dst_strides_it[0]; } /* Get the function to do the casting */ if (PyArray_GetDTypeTransferFunction(aligned, src_strides_it[0], dst_strides_it[0], src_dtype, dst_dtype, 0, &stransfer, &transferdata, &needs_api) != NPY_SUCCEED) { return -1; } if (!needs_api) { NPY_BEGIN_THREADS; } NPY_RAW_ITER_START(idim, ndim, coord, shape_it) { /* Process the innermost dimension */ stransfer(dst_data, dst_strides_it[0], src_data, src_strides_it[0], shape_it[0], src_itemsize, transferdata); } NPY_RAW_ITER_TWO_NEXT(idim, ndim, coord, shape_it, dst_data, dst_strides_it, src_data, src_strides_it); if (!needs_api) { NPY_END_THREADS; } NPY_AUXDATA_FREE(transferdata); return (needs_api && PyErr_Occurred()) ? -1 : 0; } /* * Assigns the array from 'src' to 'dst, whereever the 'wheremask' * value is True. The strides must already have been broadcast. * * Returns 0 on success, -1 on failure. */ NPY_NO_EXPORT int raw_array_wheremasked_assign_array(int ndim, npy_intp *shape, PyArray_Descr *dst_dtype, char *dst_data, npy_intp *dst_strides, PyArray_Descr *src_dtype, char *src_data, npy_intp *src_strides, PyArray_Descr *wheremask_dtype, char *wheremask_data, npy_intp *wheremask_strides) { int idim; npy_intp shape_it[NPY_MAXDIMS]; npy_intp dst_strides_it[NPY_MAXDIMS]; npy_intp src_strides_it[NPY_MAXDIMS]; npy_intp wheremask_strides_it[NPY_MAXDIMS]; npy_intp coord[NPY_MAXDIMS]; PyArray_MaskedStridedUnaryOp *stransfer = NULL; NpyAuxData *transferdata = NULL; int aligned, needs_api = 0; npy_intp src_itemsize = src_dtype->elsize; NPY_BEGIN_THREADS_DEF; /* Check alignment */ aligned = raw_array_is_aligned(ndim, dst_data, dst_strides, dst_dtype->alignment) && raw_array_is_aligned(ndim, src_data, src_strides, src_dtype->alignment); /* Use raw iteration with no heap allocation */ if (PyArray_PrepareThreeRawArrayIter( ndim, shape, dst_data, dst_strides, src_data, src_strides, wheremask_data, wheremask_strides, &ndim, shape_it, &dst_data, dst_strides_it, &src_data, src_strides_it, &wheremask_data, wheremask_strides_it) < 0) { return -1; } /* * Overlap check for the 1D case. Higher dimensional arrays cause * a temporary copy before getting here. */ if (ndim == 1 && src_data < dst_data && src_data + shape_it[0] * src_strides_it[0] > dst_data) { src_data += (shape_it[0] - 1) * src_strides_it[0]; dst_data += (shape_it[0] - 1) * dst_strides_it[0]; wheremask_data += (shape_it[0] - 1) * wheremask_strides_it[0]; src_strides_it[0] = -src_strides_it[0]; dst_strides_it[0] = -dst_strides_it[0]; wheremask_strides_it[0] = -wheremask_strides_it[0]; } /* Get the function to do the casting */ if (PyArray_GetMaskedDTypeTransferFunction(aligned, src_strides_it[0], dst_strides_it[0], wheremask_strides_it[0], src_dtype, dst_dtype, wheremask_dtype, 0, &stransfer, &transferdata, &needs_api) != NPY_SUCCEED) { return -1; } if (!needs_api) { NPY_BEGIN_THREADS; } NPY_RAW_ITER_START(idim, ndim, coord, shape_it) { /* Process the innermost dimension */ stransfer(dst_data, dst_strides_it[0], src_data, src_strides_it[0], (npy_bool *)wheremask_data, wheremask_strides_it[0], shape_it[0], src_itemsize, transferdata); } NPY_RAW_ITER_THREE_NEXT(idim, ndim, coord, shape_it, dst_data, dst_strides_it, src_data, src_strides_it, wheremask_data, wheremask_strides_it); if (!needs_api) { NPY_END_THREADS; } NPY_AUXDATA_FREE(transferdata); return (needs_api && PyErr_Occurred()) ? -1 : 0; } /* * An array assignment function for copying arrays, broadcasting 'src' into * 'dst'. This function makes a temporary copy of 'src' if 'src' and * 'dst' overlap, to be able to handle views of the same data with * different strides. * * dst: The destination array. * src: The source array. * wheremask: If non-NULL, a boolean mask specifying where to copy. * casting: An exception is raised if the copy violates this * casting rule. * * Returns 0 on success, -1 on failure. */ NPY_NO_EXPORT int PyArray_AssignArray(PyArrayObject *dst, PyArrayObject *src, PyArrayObject *wheremask, NPY_CASTING casting) { int copied_src = 0; npy_intp src_strides[NPY_MAXDIMS]; /* Use array_assign_scalar if 'src' NDIM is 0 */ if (PyArray_NDIM(src) == 0) { return PyArray_AssignRawScalar( dst, PyArray_DESCR(src), PyArray_DATA(src), wheremask, casting); } /* * Performance fix for expresions like "a[1000:6000] += x". In this * 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 * np.add(tmp, x, tmp) * a[1000:6000] = tmp # Calls array_ass_sub in mapping.c * * In the assignment the underlying data type, shape, strides, and * data pointers are identical, but src != dst because they are separately * generated slices. By detecting this and skipping the redundant * copy of values to themselves, we potentially give a big speed boost. * * Note that we don't call EquivTypes, because usually the exact same * dtype object will appear, and we don't want to slow things down * with a complicated comparison. The comparisons are ordered to * try and reject this with as little work as possible. */ if (PyArray_DATA(src) == PyArray_DATA(dst) && PyArray_DESCR(src) == PyArray_DESCR(dst) && PyArray_NDIM(src) == PyArray_NDIM(dst) && PyArray_CompareLists(PyArray_DIMS(src), PyArray_DIMS(dst), PyArray_NDIM(src)) && PyArray_CompareLists(PyArray_STRIDES(src), PyArray_STRIDES(dst), PyArray_NDIM(src))) { /*printf("Redundant copy operation detected\n");*/ return 0; } if (PyArray_FailUnlessWriteable(dst, "assignment destination") < 0) { goto fail; } /* Check the casting rule */ if (!PyArray_CanCastTypeTo(PyArray_DESCR(src), PyArray_DESCR(dst), casting)) { PyObject *errmsg; errmsg = PyUString_FromString("Cannot cast scalar from "); PyUString_ConcatAndDel(&errmsg, PyObject_Repr((PyObject *)PyArray_DESCR(src))); PyUString_ConcatAndDel(&errmsg, PyUString_FromString(" to ")); PyUString_ConcatAndDel(&errmsg, PyObject_Repr((PyObject *)PyArray_DESCR(dst))); PyUString_ConcatAndDel(&errmsg, PyUString_FromFormat(" according to the rule %s", npy_casting_to_string(casting))); PyErr_SetObject(PyExc_TypeError, errmsg); Py_DECREF(errmsg); goto fail; } /* * When ndim is 1 and the strides point in the same direction, * the lower-level inner loop handles copying * of overlapping data. For bigger ndim and opposite-strided 1D * data, we make a temporary copy of 'src' if 'src' and 'dst' overlap.' */ if (((PyArray_NDIM(dst) == 1 && PyArray_NDIM(src) >= 1 && PyArray_STRIDES(dst)[0] * PyArray_STRIDES(src)[PyArray_NDIM(src) - 1] < 0) || PyArray_NDIM(dst) > 1) && arrays_overlap(src, dst)) { PyArrayObject *tmp; /* * Allocate a temporary copy array. */ tmp = (PyArrayObject *)PyArray_NewLikeArray(dst, NPY_KEEPORDER, NULL, 0); if (tmp == NULL) { goto fail; } if (PyArray_AssignArray(tmp, src, NULL, NPY_UNSAFE_CASTING) < 0) { Py_DECREF(tmp); goto fail; } src = tmp; copied_src = 1; } /* Broadcast 'src' to 'dst' for raw iteration */ if (PyArray_NDIM(src) > PyArray_NDIM(dst)) { int ndim_tmp = PyArray_NDIM(src); npy_intp *src_shape_tmp = PyArray_DIMS(src); npy_intp *src_strides_tmp = PyArray_STRIDES(src); /* * As a special case for backwards compatibility, strip * away unit dimensions from the left of 'src' */ while (ndim_tmp > PyArray_NDIM(dst) && src_shape_tmp[0] == 1) { --ndim_tmp; ++src_shape_tmp; ++src_strides_tmp; } if (broadcast_strides(PyArray_NDIM(dst), PyArray_DIMS(dst), ndim_tmp, src_shape_tmp, src_strides_tmp, "input array", src_strides) < 0) { goto fail; } } else { if (broadcast_strides(PyArray_NDIM(dst), PyArray_DIMS(dst), PyArray_NDIM(src), PyArray_DIMS(src), PyArray_STRIDES(src), "input array", src_strides) < 0) { goto fail; } } if (wheremask == NULL) { /* A straightforward value assignment */ /* Do the assignment with raw array iteration */ if (raw_array_assign_array(PyArray_NDIM(dst), PyArray_DIMS(dst), PyArray_DESCR(dst), PyArray_DATA(dst), PyArray_STRIDES(dst), PyArray_DESCR(src), PyArray_DATA(src), src_strides) < 0) { goto fail; } } else { npy_intp wheremask_strides[NPY_MAXDIMS]; /* Broadcast the wheremask to 'dst' for raw iteration */ if (broadcast_strides(PyArray_NDIM(dst), PyArray_DIMS(dst), PyArray_NDIM(wheremask), PyArray_DIMS(wheremask), PyArray_STRIDES(wheremask), "where mask", wheremask_strides) < 0) { goto fail; } /* A straightforward where-masked assignment */ /* Do the masked assignment with raw array iteration */ if (raw_array_wheremasked_assign_array( PyArray_NDIM(dst), PyArray_DIMS(dst), PyArray_DESCR(dst), PyArray_DATA(dst), PyArray_STRIDES(dst), PyArray_DESCR(src), PyArray_DATA(src), src_strides, PyArray_DESCR(wheremask), PyArray_DATA(wheremask), wheremask_strides) < 0) { goto fail; } } finish: if (copied_src) { Py_DECREF(src); } return 0; fail: if (copied_src) { Py_DECREF(src); } return -1; } numpy-1.8.2/numpy/core/src/multiarray/iterators.h0000664000175100017510000000132112370216242023265 0ustar vagrantvagrant00000000000000#ifndef _NPY_ARRAYITERATORS_H_ #define _NPY_ARRAYITERATORS_H_ /* * Parses an index that has no fancy indexing. Populates * out_dimensions, out_strides, and out_offset. */ NPY_NO_EXPORT int parse_index(PyArrayObject *self, PyObject *op, npy_intp *out_dimensions, npy_intp *out_strides, npy_intp *out_offset, int check_index); NPY_NO_EXPORT PyObject *iter_subscript(PyArrayIterObject *, PyObject *); NPY_NO_EXPORT int iter_ass_subscript(PyArrayIterObject *, PyObject *, PyObject *); NPY_NO_EXPORT int slice_GetIndices(PySliceObject *r, npy_intp length, npy_intp *start, npy_intp *stop, npy_intp *step, npy_intp *slicelength); #endif numpy-1.8.2/numpy/core/src/multiarray/getset.c0000664000175100017510000006520712370216243022555 0ustar vagrantvagrant00000000000000/* Array Descr Object */ #define PY_SSIZE_T_CLEAN #include #include "structmember.h" #define NPY_NO_DEPRECATED_API NPY_API_VERSION #define _MULTIARRAYMODULE #include "numpy/arrayobject.h" #include "npy_config.h" #include "npy_pycompat.h" #include "common.h" #include "scalartypes.h" #include "descriptor.h" #include "getset.h" #include "arrayobject.h" /******************* array attribute get and set routines ******************/ static PyObject * array_ndim_get(PyArrayObject *self) { return PyInt_FromLong(PyArray_NDIM(self)); } static PyObject * array_flags_get(PyArrayObject *self) { return PyArray_NewFlagsObject((PyObject *)self); } static PyObject * array_shape_get(PyArrayObject *self) { return PyArray_IntTupleFromIntp(PyArray_NDIM(self), PyArray_DIMS(self)); } static int array_shape_set(PyArrayObject *self, PyObject *val) { int nd; PyArrayObject *ret; if (val == NULL) { PyErr_SetString(PyExc_AttributeError, "Cannot delete array shape"); return -1; } /* Assumes C-order */ ret = (PyArrayObject *)PyArray_Reshape(self, val); if (ret == NULL) { return -1; } if (PyArray_DATA(ret) != PyArray_DATA(self)) { Py_DECREF(ret); PyErr_SetString(PyExc_AttributeError, "incompatible shape for a non-contiguous "\ "array"); return -1; } /* Free old dimensions and strides */ PyDimMem_FREE(PyArray_DIMS(self)); nd = PyArray_NDIM(ret); ((PyArrayObject_fields *)self)->nd = nd; if (nd > 0) { /* create new dimensions and strides */ ((PyArrayObject_fields *)self)->dimensions = PyDimMem_NEW(3*nd); if (PyArray_DIMS(self) == NULL) { Py_DECREF(ret); PyErr_SetString(PyExc_MemoryError,""); return -1; } ((PyArrayObject_fields *)self)->strides = PyArray_DIMS(self) + nd; memcpy(PyArray_DIMS(self), PyArray_DIMS(ret), nd*sizeof(npy_intp)); memcpy(PyArray_STRIDES(self), PyArray_STRIDES(ret), nd*sizeof(npy_intp)); } else { ((PyArrayObject_fields *)self)->dimensions = NULL; ((PyArrayObject_fields *)self)->strides = NULL; } Py_DECREF(ret); PyArray_UpdateFlags(self, NPY_ARRAY_C_CONTIGUOUS | NPY_ARRAY_F_CONTIGUOUS); return 0; } static PyObject * array_strides_get(PyArrayObject *self) { return PyArray_IntTupleFromIntp(PyArray_NDIM(self), PyArray_STRIDES(self)); } static int array_strides_set(PyArrayObject *self, PyObject *obj) { PyArray_Dims newstrides = {NULL, 0}; PyArrayObject *new; npy_intp numbytes = 0; npy_intp offset = 0; npy_intp lower_offset = 0; npy_intp upper_offset = 0; Py_ssize_t buf_len; char *buf; if (obj == NULL) { PyErr_SetString(PyExc_AttributeError, "Cannot delete array strides"); return -1; } if (!PyArray_IntpConverter(obj, &newstrides) || newstrides.ptr == NULL) { PyErr_SetString(PyExc_TypeError, "invalid strides"); return -1; } if (newstrides.len != PyArray_NDIM(self)) { PyErr_Format(PyExc_ValueError, "strides must be " \ " same length as shape (%d)", PyArray_NDIM(self)); goto fail; } new = self; while(PyArray_BASE(new) && PyArray_Check(PyArray_BASE(new))) { new = (PyArrayObject *)(PyArray_BASE(new)); } /* * Get the available memory through the buffer interface on * PyArray_BASE(new) or if that fails from the current new */ if (PyArray_BASE(new) && PyObject_AsReadBuffer(PyArray_BASE(new), (const void **)&buf, &buf_len) >= 0) { offset = PyArray_BYTES(self) - buf; numbytes = buf_len + offset; } else { PyErr_Clear(); offset_bounds_from_strides(PyArray_ITEMSIZE(new), PyArray_NDIM(new), PyArray_DIMS(new), PyArray_STRIDES(new), &lower_offset, &upper_offset); offset = PyArray_BYTES(self) - (PyArray_BYTES(new) + lower_offset); numbytes = upper_offset - lower_offset; } /* numbytes == 0 is special here, but the 0-size array case always works */ if (!PyArray_CheckStrides(PyArray_ITEMSIZE(self), PyArray_NDIM(self), numbytes, offset, PyArray_DIMS(self), newstrides.ptr)) { PyErr_SetString(PyExc_ValueError, "strides is not "\ "compatible with available memory"); goto fail; } memcpy(PyArray_STRIDES(self), newstrides.ptr, sizeof(npy_intp)*newstrides.len); PyArray_UpdateFlags(self, NPY_ARRAY_C_CONTIGUOUS | NPY_ARRAY_F_CONTIGUOUS | NPY_ARRAY_ALIGNED); PyDimMem_FREE(newstrides.ptr); return 0; fail: PyDimMem_FREE(newstrides.ptr); return -1; } static PyObject * array_priority_get(PyArrayObject *self) { if (PyArray_CheckExact(self)) { return PyFloat_FromDouble(NPY_PRIORITY); } else { return PyFloat_FromDouble(NPY_PRIORITY); } } static PyObject * array_typestr_get(PyArrayObject *self) { return arraydescr_protocol_typestr_get(PyArray_DESCR(self)); } static PyObject * array_descr_get(PyArrayObject *self) { Py_INCREF(PyArray_DESCR(self)); return (PyObject *)PyArray_DESCR(self); } static PyObject * array_protocol_descr_get(PyArrayObject *self) { PyObject *res; PyObject *dobj; res = arraydescr_protocol_descr_get(PyArray_DESCR(self)); if (res) { return res; } PyErr_Clear(); /* get default */ dobj = PyTuple_New(2); if (dobj == NULL) { return NULL; } PyTuple_SET_ITEM(dobj, 0, PyString_FromString("")); PyTuple_SET_ITEM(dobj, 1, array_typestr_get(self)); res = PyList_New(1); if (res == NULL) { Py_DECREF(dobj); return NULL; } PyList_SET_ITEM(res, 0, dobj); return res; } static PyObject * array_protocol_strides_get(PyArrayObject *self) { if (PyArray_ISCONTIGUOUS(self)) { Py_INCREF(Py_None); return Py_None; } return PyArray_IntTupleFromIntp(PyArray_NDIM(self), PyArray_STRIDES(self)); } static PyObject * array_dataptr_get(PyArrayObject *self) { return Py_BuildValue("NO", PyLong_FromVoidPtr(PyArray_DATA(self)), (PyArray_FLAGS(self) & NPY_ARRAY_WRITEABLE ? Py_False : Py_True)); } static PyObject * array_ctypes_get(PyArrayObject *self) { PyObject *_numpy_internal; PyObject *ret; _numpy_internal = PyImport_ImportModule("numpy.core._internal"); if (_numpy_internal == NULL) { return NULL; } ret = PyObject_CallMethod(_numpy_internal, "_ctypes", "ON", self, PyLong_FromVoidPtr(PyArray_DATA(self))); Py_DECREF(_numpy_internal); return ret; } static PyObject * array_interface_get(PyArrayObject *self) { PyObject *dict; PyObject *obj; dict = PyDict_New(); if (dict == NULL) { return NULL; } if (array_might_be_written(self) < 0) { return NULL; } /* dataptr */ obj = array_dataptr_get(self); PyDict_SetItemString(dict, "data", obj); Py_DECREF(obj); obj = array_protocol_strides_get(self); PyDict_SetItemString(dict, "strides", obj); Py_DECREF(obj); obj = array_protocol_descr_get(self); PyDict_SetItemString(dict, "descr", obj); Py_DECREF(obj); obj = arraydescr_protocol_typestr_get(PyArray_DESCR(self)); PyDict_SetItemString(dict, "typestr", obj); Py_DECREF(obj); obj = array_shape_get(self); PyDict_SetItemString(dict, "shape", obj); Py_DECREF(obj); obj = PyInt_FromLong(3); PyDict_SetItemString(dict, "version", obj); Py_DECREF(obj); return dict; } static PyObject * array_data_get(PyArrayObject *self) { #if defined(NPY_PY3K) return PyMemoryView_FromObject((PyObject *)self); #else npy_intp nbytes; if (!(PyArray_ISONESEGMENT(self))) { PyErr_SetString(PyExc_AttributeError, "cannot get single-"\ "segment buffer for discontiguous array"); return NULL; } nbytes = PyArray_NBYTES(self); if (PyArray_ISWRITEABLE(self)) { return PyBuffer_FromReadWriteObject((PyObject *)self, 0, (Py_ssize_t) nbytes); } else { return PyBuffer_FromObject((PyObject *)self, 0, (Py_ssize_t) nbytes); } #endif } /* * TODO: Given view semantics, I think this function is a really * bad idea, and should be removed! */ static int array_data_set(PyArrayObject *self, PyObject *op) { void *buf; Py_ssize_t buf_len; int writeable=1; if (op == NULL) { PyErr_SetString(PyExc_AttributeError, "Cannot delete array data"); return -1; } if (PyObject_AsWriteBuffer(op, &buf, &buf_len) < 0) { writeable = 0; if (PyObject_AsReadBuffer(op, (const void **)&buf, &buf_len) < 0) { PyErr_SetString(PyExc_AttributeError, "object does not have single-segment " \ "buffer interface"); return -1; } } if (!PyArray_ISONESEGMENT(self)) { PyErr_SetString(PyExc_AttributeError, "cannot set single-" \ "segment buffer for discontiguous array"); return -1; } if (PyArray_NBYTES(self) > buf_len) { PyErr_SetString(PyExc_AttributeError, "not enough data for array"); return -1; } if (PyArray_FLAGS(self) & NPY_ARRAY_OWNDATA) { PyArray_XDECREF(self); PyDataMem_FREE(PyArray_DATA(self)); } if (PyArray_BASE(self)) { if (PyArray_FLAGS(self) & NPY_ARRAY_UPDATEIFCOPY) { PyArray_ENABLEFLAGS((PyArrayObject *)PyArray_BASE(self), NPY_ARRAY_WRITEABLE); PyArray_CLEARFLAGS(self, NPY_ARRAY_UPDATEIFCOPY); } Py_DECREF(PyArray_BASE(self)); ((PyArrayObject_fields *)self)->base = NULL; } Py_INCREF(op); if (PyArray_SetBaseObject(self, op) < 0) { return -1; } ((PyArrayObject_fields *)self)->data = buf; ((PyArrayObject_fields *)self)->flags = NPY_ARRAY_CARRAY; if (!writeable) { PyArray_CLEARFLAGS(self, ~NPY_ARRAY_WRITEABLE); } return 0; } static PyObject * array_itemsize_get(PyArrayObject *self) { return PyInt_FromLong((long) PyArray_DESCR(self)->elsize); } static PyObject * array_size_get(PyArrayObject *self) { npy_intp size=PyArray_SIZE(self); #if NPY_SIZEOF_INTP <= NPY_SIZEOF_LONG return PyInt_FromLong((long) size); #else if (size > NPY_MAX_LONG || size < NPY_MIN_LONG) { return PyLong_FromLongLong(size); } else { return PyInt_FromLong((long) size); } #endif } static PyObject * array_nbytes_get(PyArrayObject *self) { npy_intp nbytes = PyArray_NBYTES(self); #if NPY_SIZEOF_INTP <= NPY_SIZEOF_LONG return PyInt_FromLong((long) nbytes); #else if (nbytes > NPY_MAX_LONG || nbytes < NPY_MIN_LONG) { return PyLong_FromLongLong(nbytes); } else { return PyInt_FromLong((long) nbytes); } #endif } /* * If the type is changed. * Also needing change: strides, itemsize * * Either itemsize is exactly the same or the array is single-segment * (contiguous or fortran) with compatibile dimensions The shape and strides * will be adjusted in that case as well. */ static int array_descr_set(PyArrayObject *self, PyObject *arg) { PyArray_Descr *newtype = NULL; npy_intp newdim; int i; char *msg = "new type not compatible with array."; if (arg == NULL) { PyErr_SetString(PyExc_AttributeError, "Cannot delete array dtype"); return -1; } if (!(PyArray_DescrConverter(arg, &newtype)) || newtype == NULL) { PyErr_SetString(PyExc_TypeError, "invalid data-type for array"); return -1; } if (PyDataType_FLAGCHK(newtype, NPY_ITEM_HASOBJECT) || PyDataType_FLAGCHK(newtype, NPY_ITEM_IS_POINTER) || PyDataType_FLAGCHK(PyArray_DESCR(self), NPY_ITEM_HASOBJECT) || PyDataType_FLAGCHK(PyArray_DESCR(self), NPY_ITEM_IS_POINTER)) { PyErr_SetString(PyExc_TypeError, "Cannot change data-type for object array."); Py_DECREF(newtype); return -1; } if (newtype->elsize == 0) { /* Allow a void view */ if (newtype->type_num == NPY_VOID) { PyArray_DESCR_REPLACE(newtype); if (newtype == NULL) { return -1; } newtype->elsize = PyArray_DESCR(self)->elsize; } /* But no other flexible types */ else { PyErr_SetString(PyExc_TypeError, "data-type must not be 0-sized"); Py_DECREF(newtype); return -1; } } if ((newtype->elsize != PyArray_DESCR(self)->elsize) && (PyArray_NDIM(self) == 0 || !PyArray_ISONESEGMENT(self) || PyDataType_HASSUBARRAY(newtype))) { goto fail; } if (PyArray_ISCONTIGUOUS(self)) { i = PyArray_NDIM(self) - 1; } else { i = 0; } if (newtype->elsize < PyArray_DESCR(self)->elsize) { /* * if it is compatible increase the size of the * dimension at end (or at the front for NPY_ARRAY_F_CONTIGUOUS) */ if (PyArray_DESCR(self)->elsize % newtype->elsize != 0) { goto fail; } newdim = PyArray_DESCR(self)->elsize / newtype->elsize; PyArray_DIMS(self)[i] *= newdim; PyArray_STRIDES(self)[i] = newtype->elsize; } else if (newtype->elsize > PyArray_DESCR(self)->elsize) { /* * Determine if last (or first if NPY_ARRAY_F_CONTIGUOUS) dimension * is compatible */ newdim = PyArray_DIMS(self)[i] * PyArray_DESCR(self)->elsize; if ((newdim % newtype->elsize) != 0) { goto fail; } PyArray_DIMS(self)[i] = newdim / newtype->elsize; PyArray_STRIDES(self)[i] = newtype->elsize; } /* fall through -- adjust type*/ Py_DECREF(PyArray_DESCR(self)); if (PyDataType_HASSUBARRAY(newtype)) { /* * create new array object from data and update * dimensions, strides and descr from it */ PyArrayObject *temp; /* * We would decref newtype here. * temp will steal a reference to it */ temp = (PyArrayObject *) PyArray_NewFromDescr(&PyArray_Type, newtype, PyArray_NDIM(self), PyArray_DIMS(self), PyArray_STRIDES(self), PyArray_DATA(self), PyArray_FLAGS(self), NULL); if (temp == NULL) { return -1; } PyDimMem_FREE(PyArray_DIMS(self)); ((PyArrayObject_fields *)self)->dimensions = PyArray_DIMS(temp); ((PyArrayObject_fields *)self)->nd = PyArray_NDIM(temp); ((PyArrayObject_fields *)self)->strides = PyArray_STRIDES(temp); newtype = PyArray_DESCR(temp); Py_INCREF(PyArray_DESCR(temp)); /* Fool deallocator not to delete these*/ ((PyArrayObject_fields *)temp)->nd = 0; ((PyArrayObject_fields *)temp)->dimensions = NULL; Py_DECREF(temp); } ((PyArrayObject_fields *)self)->descr = newtype; PyArray_UpdateFlags(self, NPY_ARRAY_UPDATE_ALL); return 0; fail: PyErr_SetString(PyExc_ValueError, msg); Py_DECREF(newtype); return -1; } static PyObject * array_struct_get(PyArrayObject *self) { PyArrayInterface *inter; PyObject *ret; if (PyArray_ISWRITEABLE(self)) { if (array_might_be_written(self) < 0) { return NULL; } } inter = (PyArrayInterface *)PyArray_malloc(sizeof(PyArrayInterface)); if (inter==NULL) { return PyErr_NoMemory(); } inter->two = 2; inter->nd = PyArray_NDIM(self); inter->typekind = PyArray_DESCR(self)->kind; inter->itemsize = PyArray_DESCR(self)->elsize; inter->flags = PyArray_FLAGS(self); /* reset unused flags */ inter->flags &= ~(NPY_ARRAY_UPDATEIFCOPY | NPY_ARRAY_OWNDATA); if (PyArray_ISNOTSWAPPED(self)) inter->flags |= NPY_ARRAY_NOTSWAPPED; /* * Copy shape and strides over since these can be reset *when the array is "reshaped". */ if (PyArray_NDIM(self) > 0) { inter->shape = (npy_intp *)PyArray_malloc(2*sizeof(npy_intp)*PyArray_NDIM(self)); if (inter->shape == NULL) { PyArray_free(inter); return PyErr_NoMemory(); } inter->strides = inter->shape + PyArray_NDIM(self); memcpy(inter->shape, PyArray_DIMS(self), sizeof(npy_intp)*PyArray_NDIM(self)); memcpy(inter->strides, PyArray_STRIDES(self), sizeof(npy_intp)*PyArray_NDIM(self)); } else { inter->shape = NULL; inter->strides = NULL; } inter->data = PyArray_DATA(self); if (PyDataType_HASFIELDS(PyArray_DESCR(self))) { inter->descr = arraydescr_protocol_descr_get(PyArray_DESCR(self)); if (inter->descr == NULL) { PyErr_Clear(); } else { inter->flags &= NPY_ARR_HAS_DESCR; } } else { inter->descr = NULL; } Py_INCREF(self); ret = NpyCapsule_FromVoidPtrAndDesc(inter, self, gentype_struct_free); return ret; } static PyObject * array_base_get(PyArrayObject *self) { if (PyArray_BASE(self) == NULL) { Py_INCREF(Py_None); return Py_None; } else { Py_INCREF(PyArray_BASE(self)); return PyArray_BASE(self); } } /* * Create a view of a complex array with an equivalent data-type * except it is real instead of complex. */ static PyArrayObject * _get_part(PyArrayObject *self, int imag) { int float_type_num; PyArray_Descr *type; PyArrayObject *ret; int offset; switch (PyArray_DESCR(self)->type_num) { case NPY_CFLOAT: float_type_num = NPY_FLOAT; break; case NPY_CDOUBLE: float_type_num = NPY_DOUBLE; break; case NPY_CLONGDOUBLE: float_type_num = NPY_LONGDOUBLE; break; default: PyErr_Format(PyExc_ValueError, "Cannot convert complex type number %d to float", PyArray_DESCR(self)->type_num); return NULL; } type = PyArray_DescrFromType(float_type_num); offset = (imag ? type->elsize : 0); if (!PyArray_ISNBO(PyArray_DESCR(self)->byteorder)) { PyArray_Descr *new; new = PyArray_DescrNew(type); new->byteorder = PyArray_DESCR(self)->byteorder; Py_DECREF(type); type = new; } ret = (PyArrayObject *) PyArray_NewFromDescr(Py_TYPE(self), type, PyArray_NDIM(self), PyArray_DIMS(self), PyArray_STRIDES(self), PyArray_BYTES(self) + offset, PyArray_FLAGS(self), (PyObject *)self); if (ret == NULL) { return NULL; } Py_INCREF(self); if (PyArray_SetBaseObject(ret, (PyObject *)self) < 0) { Py_DECREF(ret); return NULL; } PyArray_CLEARFLAGS(ret, NPY_ARRAY_C_CONTIGUOUS | NPY_ARRAY_F_CONTIGUOUS); return ret; } /* For Object arrays, we need to get and set the real part of each element. */ static PyObject * array_real_get(PyArrayObject *self) { PyArrayObject *ret; if (PyArray_ISCOMPLEX(self)) { ret = _get_part(self, 0); return (PyObject *)ret; } else { Py_INCREF(self); return (PyObject *)self; } } static int array_real_set(PyArrayObject *self, PyObject *val) { PyArrayObject *ret; PyArrayObject *new; int retcode; if (val == NULL) { PyErr_SetString(PyExc_AttributeError, "Cannot delete array real part"); return -1; } if (PyArray_ISCOMPLEX(self)) { ret = _get_part(self, 0); if (ret == NULL) { return -1; } } else { Py_INCREF(self); ret = self; } new = (PyArrayObject *)PyArray_FromAny(val, NULL, 0, 0, 0, NULL); if (new == NULL) { Py_DECREF(ret); return -1; } retcode = PyArray_MoveInto(ret, new); Py_DECREF(ret); Py_DECREF(new); return retcode; } /* For Object arrays we need to get and set the imaginary part of each element */ static PyObject * array_imag_get(PyArrayObject *self) { PyArrayObject *ret; if (PyArray_ISCOMPLEX(self)) { ret = _get_part(self, 1); } else { Py_INCREF(PyArray_DESCR(self)); ret = (PyArrayObject *)PyArray_NewFromDescr(Py_TYPE(self), PyArray_DESCR(self), PyArray_NDIM(self), PyArray_DIMS(self), NULL, NULL, PyArray_ISFORTRAN(self), (PyObject *)self); if (ret == NULL) { return NULL; } if (_zerofill(ret) < 0) { return NULL; } PyArray_CLEARFLAGS(ret, NPY_ARRAY_WRITEABLE); } return (PyObject *) ret; } static int array_imag_set(PyArrayObject *self, PyObject *val) { if (val == NULL) { PyErr_SetString(PyExc_AttributeError, "Cannot delete array imaginary part"); return -1; } if (PyArray_ISCOMPLEX(self)) { PyArrayObject *ret; PyArrayObject *new; int retcode; ret = _get_part(self, 1); if (ret == NULL) { return -1; } new = (PyArrayObject *)PyArray_FromAny(val, NULL, 0, 0, 0, NULL); if (new == NULL) { Py_DECREF(ret); return -1; } retcode = PyArray_MoveInto(ret, new); Py_DECREF(ret); Py_DECREF(new); return retcode; } else { PyErr_SetString(PyExc_TypeError, "array does not have imaginary part to set"); return -1; } } static PyObject * array_flat_get(PyArrayObject *self) { return PyArray_IterNew((PyObject *)self); } static int array_flat_set(PyArrayObject *self, PyObject *val) { PyArrayObject *arr = NULL; int retval = -1; PyArrayIterObject *selfit = NULL, *arrit = NULL; PyArray_Descr *typecode; int swap; PyArray_CopySwapFunc *copyswap; if (val == NULL) { PyErr_SetString(PyExc_AttributeError, "Cannot delete array flat iterator"); return -1; } if (PyArray_FailUnlessWriteable(self, "array") < 0) return -1; typecode = PyArray_DESCR(self); Py_INCREF(typecode); arr = (PyArrayObject *)PyArray_FromAny(val, typecode, 0, 0, NPY_ARRAY_FORCECAST | PyArray_FORTRAN_IF(self), NULL); if (arr == NULL) { return -1; } arrit = (PyArrayIterObject *)PyArray_IterNew((PyObject *)arr); if (arrit == NULL) { goto exit; } selfit = (PyArrayIterObject *)PyArray_IterNew((PyObject *)self); if (selfit == NULL) { goto exit; } if (arrit->size == 0) { retval = 0; goto exit; } swap = PyArray_ISNOTSWAPPED(self) != PyArray_ISNOTSWAPPED(arr); copyswap = PyArray_DESCR(self)->f->copyswap; if (PyDataType_REFCHK(PyArray_DESCR(self))) { while (selfit->index < selfit->size) { PyArray_Item_XDECREF(selfit->dataptr, PyArray_DESCR(self)); PyArray_Item_INCREF(arrit->dataptr, PyArray_DESCR(arr)); memmove(selfit->dataptr, arrit->dataptr, sizeof(PyObject **)); if (swap) { copyswap(selfit->dataptr, NULL, swap, self); } PyArray_ITER_NEXT(selfit); PyArray_ITER_NEXT(arrit); if (arrit->index == arrit->size) { PyArray_ITER_RESET(arrit); } } retval = 0; goto exit; } while(selfit->index < selfit->size) { memmove(selfit->dataptr, arrit->dataptr, PyArray_DESCR(self)->elsize); if (swap) { copyswap(selfit->dataptr, NULL, swap, self); } PyArray_ITER_NEXT(selfit); PyArray_ITER_NEXT(arrit); if (arrit->index == arrit->size) { PyArray_ITER_RESET(arrit); } } retval = 0; exit: Py_XDECREF(selfit); Py_XDECREF(arrit); Py_XDECREF(arr); return retval; } static PyObject * array_transpose_get(PyArrayObject *self) { return PyArray_Transpose(self, NULL); } /* If this is None, no function call is made --- default sub-class behavior */ static PyObject * array_finalize_get(PyArrayObject *NPY_UNUSED(self)) { Py_INCREF(Py_None); return Py_None; } NPY_NO_EXPORT PyGetSetDef array_getsetlist[] = { {"ndim", (getter)array_ndim_get, NULL, NULL, NULL}, {"flags", (getter)array_flags_get, NULL, NULL, NULL}, {"shape", (getter)array_shape_get, (setter)array_shape_set, NULL, NULL}, {"strides", (getter)array_strides_get, (setter)array_strides_set, NULL, NULL}, {"data", (getter)array_data_get, (setter)array_data_set, NULL, NULL}, {"itemsize", (getter)array_itemsize_get, NULL, NULL, NULL}, {"size", (getter)array_size_get, NULL, NULL, NULL}, {"nbytes", (getter)array_nbytes_get, NULL, NULL, NULL}, {"base", (getter)array_base_get, NULL, NULL, NULL}, {"dtype", (getter)array_descr_get, (setter)array_descr_set, NULL, NULL}, {"real", (getter)array_real_get, (setter)array_real_set, NULL, NULL}, {"imag", (getter)array_imag_get, (setter)array_imag_set, NULL, NULL}, {"flat", (getter)array_flat_get, (setter)array_flat_set, NULL, NULL}, {"ctypes", (getter)array_ctypes_get, NULL, NULL, NULL}, {"T", (getter)array_transpose_get, NULL, NULL, NULL}, {"__array_interface__", (getter)array_interface_get, NULL, NULL, NULL}, {"__array_struct__", (getter)array_struct_get, NULL, NULL, NULL}, {"__array_priority__", (getter)array_priority_get, NULL, NULL, NULL}, {"__array_finalize__", (getter)array_finalize_get, NULL, NULL, NULL}, {NULL, NULL, NULL, NULL, NULL}, /* Sentinel */ }; /****************** end of attribute get and set routines *******************/ numpy-1.8.2/numpy/core/src/multiarray/mapping.c0000664000175100017510000020720212370216243022706 0ustar vagrantvagrant00000000000000#define PY_SSIZE_T_CLEAN #include #include "structmember.h" /*#include */ #define NPY_NO_DEPRECATED_API NPY_API_VERSION #define _MULTIARRAYMODULE #include "numpy/arrayobject.h" #include "arrayobject.h" #include "npy_config.h" #include "npy_pycompat.h" #include "common.h" #include "iterators.h" #include "mapping.h" #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); /****************************************************************************** *** IMPLEMENT MAPPING PROTOCOL *** *****************************************************************************/ NPY_NO_EXPORT Py_ssize_t array_length(PyArrayObject *self) { if (PyArray_NDIM(self) != 0) { return PyArray_DIMS(self)[0]; } else { PyErr_SetString(PyExc_TypeError, "len() of unsized object"); return -1; } } /* 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) { PyObject *new; int n1, n2, n3, val, bnd; int i; PyArray_Dims permute; npy_intp d[NPY_MAXDIMS]; PyArrayObject *arr; permute.ptr = d; permute.len = mit->nd; /* * arr might not have the right number of dimensions * and need to be reshaped first by pre-pending ones */ arr = *ret; if (PyArray_NDIM(arr) != mit->nd) { for (i = 1; i <= PyArray_NDIM(arr); i++) { permute.ptr[mit->nd-i] = PyArray_DIMS(arr)[PyArray_NDIM(arr)-i]; } for (i = 0; i < mit->nd-PyArray_NDIM(arr); i++) { permute.ptr[i] = 1; } new = PyArray_Newshape(arr, &permute, NPY_ANYORDER); Py_DECREF(arr); *ret = (PyArrayObject *)new; if (new == NULL) { return; } } /* * Setting and getting need to have different permutations. * On the get we are permuting the returned object, but on * setting we are permuting the object-to-be-set. * The set permutation is the inverse of the get permutation. */ /* * For getting the array the tuple for transpose is * (n1,...,n1+n2-1,0,...,n1-1,n1+n2,...,n3-1) * n1 is the number of dimensions of the broadcast index array * n2 is the number of dimensions skipped at the start * n3 is the number of dimensions of the result */ /* * 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; n2 = mit->consec; /* axes to insert at */ n3 = mit->nd; /* use n1 as the boundary if getting but n2 if setting */ bnd = getmap ? n1 : n2; val = bnd; i = 0; while (val < n1 + n2) { permute.ptr[i++] = val++; } val = 0; while (val < bnd) { permute.ptr[i++] = val++; } val = n1 + n2; while (val < n3) { permute.ptr[i++] = val++; } new = PyArray_Transpose(*ret, &permute); Py_DECREF(*ret); *ret = (PyArrayObject *)new; } static PyObject * PyArray_GetMap(PyArrayMapIterObject *mit) { PyArrayObject *ret, *temp; PyArrayIterObject *it; npy_intp counter; int swap; PyArray_CopySwapFunc *copyswap; /* Unbound map iterator --- Bind should have been called */ if (mit->ait == NULL) { return NULL; } /* 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; } /* * Now just iterate through the new array filling it in * with the next object from the original array as * defined by the mapping iterator */ 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); /* check for consecutive axes */ if ((mit->subspace != NULL) && (mit->consec)) { PyArray_MapIterSwapAxes(mit, &ret, 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 ((mit->subspace != NULL) && (mit->consec)) { PyArray_MapIterSwapAxes(mit, &arr, 0); if (arr == NULL) { return -1; } } /* Be sure values array is "broadcastable" to shape of mit->dimensions, mit->nd */ if ((it = (PyArrayIterObject *)\ PyArray_BroadcastToShape((PyObject *)arr, mit->dimensions, mit->nd))==NULL) { Py_DECREF(arr); return -1; } 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); } PyArray_MapIterNext(mit); PyArray_ITER_NEXT(it); } 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); } 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; 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++; } else if (arg == Py_None) { newaxis_count++; } else { break; } } 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; } NPY_NO_EXPORT PyObject * add_new_axes_0d(PyArrayObject *arr, int newaxis_count) { PyArrayObject *ret; npy_intp dimensions[NPY_MAXDIMS]; int i; 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; } Py_INCREF(arr); if (PyArray_SetBaseObject(ret, (PyObject *)arr) < 0) { Py_DECREF(ret); return NULL; } return (PyObject *)ret; } /* This checks the args for any fancy indexing objects */ static int fancy_indexing_check(PyObject *args) { int i, n; int retval = SOBJ_NOTFANCY; 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; } else { retval = SOBJ_BADARRAY; break; } } else if (PySequence_Check(obj)) { retval = SOBJ_ISFANCY; } } } 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; } else { return SOBJ_BADARRAY; } } else if (PySequence_Check(args)) { /* * 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. */ retval = SOBJ_ISFANCY; n = PySequence_Size(args); if (n < 0 || n >= NPY_MAXDIMS) { return SOBJ_ISFANCY; } 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; } } } return retval; } /* * 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). * * There are two situations: * * 1 - the subscript is a standard view and a reference to the * array can be returned * * 2 - the subscript uses Boolean masks or integer indexing and * therefore a new array is created and returned. */ 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)) { value = PyArray_PyIntAsIntp(op); 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(self, value); } } /* Standard (view-based) Indexing */ nd = parse_index(self, op, dimensions, strides, &offset, check_index); if (nd == -1) { return NULL; } /* Create a view using the indexing result */ Py_INCREF(PyArray_DESCR(self)); ret = (PyArrayObject *)PyArray_NewFromDescr(Py_TYPE(self), PyArray_DESCR(self), nd, dimensions, strides, PyArray_BYTES(self) + offset, PyArray_FLAGS(self), (PyObject *)self); if (ret == NULL) { return NULL; } Py_INCREF(self); if (PyArray_SetBaseObject(ret, (PyObject *)self) < 0) { Py_DECREF(ret); return NULL; } PyArray_UpdateFlags(ret, NPY_ARRAY_UPDATE_ALL); return (PyObject *)ret; } /* * Implements boolean indexing. This produces a one-dimensional * array which picks out all of the elements of 'self' for which * the corresponding element of 'op' is True. * * This operation is somewhat unfortunate, because to produce * a one-dimensional output array, it has to choose a particular * iteration order, in the case of NumPy that is always C order even * though this function allows different choices. */ NPY_NO_EXPORT PyArrayObject * array_boolean_subscript(PyArrayObject *self, PyArrayObject *bmask, NPY_ORDER order) { npy_intp size, itemsize; char *ret_data; 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); if (ret == NULL) { return NULL; } itemsize = dtype->elsize; ret_data = PyArray_DATA(ret); /* Create an iterator for the data */ if (size > 0) { NpyIter *iter; PyArrayObject *op[2] = {self, bmask}; npy_uint32 flags, op_flags[2]; npy_intp fixed_strides[3]; PyArray_StridedUnaryOp *stransfer = NULL; NpyAuxData *transferdata = NULL; NpyIter_IterNextFunc *iternext; npy_intp innersize, *innerstrides; char **dataptrs; npy_intp self_stride, bmask_stride, subloopsize; char *self_data; char *bmask_data; /* Set up the iterator */ flags = NPY_ITER_EXTERNAL_LOOP | NPY_ITER_REFS_OK; op_flags[0] = NPY_ITER_READONLY | NPY_ITER_NO_BROADCAST; op_flags[1] = NPY_ITER_READONLY; iter = NpyIter_MultiNew(2, op, flags, order, NPY_NO_CASTING, op_flags, NULL); if (iter == NULL) { Py_DECREF(ret); return NULL; } /* Get a dtype transfer function */ NpyIter_GetInnerFixedStrideArray(iter, fixed_strides); if (PyArray_GetDTypeTransferFunction(PyArray_ISALIGNED(self), fixed_strides[0], itemsize, dtype, dtype, 0, &stransfer, &transferdata, &needs_api) != NPY_SUCCEED) { Py_DECREF(ret); NpyIter_Deallocate(iter); return NULL; } /* Get the values needed for the inner loop */ iternext = NpyIter_GetIterNext(iter, NULL); if (iternext == NULL) { Py_DECREF(ret); NpyIter_Deallocate(iter); NPY_AUXDATA_FREE(transferdata); return NULL; } innerstrides = NpyIter_GetInnerStrideArray(iter); dataptrs = NpyIter_GetDataPtrArray(iter); self_stride = innerstrides[0]; bmask_stride = innerstrides[1]; do { innersize = *NpyIter_GetInnerLoopSizePtr(iter); self_data = dataptrs[0]; bmask_data = dataptrs[1]; while (innersize > 0) { /* Skip masked values */ subloopsize = 0; while (subloopsize < innersize && *bmask_data == 0) { ++subloopsize; bmask_data += bmask_stride; } innersize -= subloopsize; self_data += subloopsize * self_stride; /* Process unmasked values */ subloopsize = 0; while (subloopsize < innersize && *bmask_data != 0) { ++subloopsize; bmask_data += bmask_stride; } stransfer(ret_data, itemsize, self_data, self_stride, subloopsize, itemsize, transferdata); innersize -= subloopsize; self_data += subloopsize * self_stride; ret_data += subloopsize * itemsize; } } while (iternext(iter)); NpyIter_Deallocate(iter); NPY_AUXDATA_FREE(transferdata); } return ret; } /* * Implements boolean indexing assignment. This takes the one-dimensional * array 'v' and assigns its values to all of the elements of 'self' for which * the corresponding element of 'op' is True. * * This operation is somewhat unfortunate, because to match up with * a one-dimensional output array, it has to choose a particular * iteration order, in the case of NumPy that is always C order even * though this function allows different choices. * * Returns 0 on success, -1 on failure. */ NPY_NO_EXPORT int array_ass_boolean_subscript(PyArrayObject *self, PyArrayObject *bmask, PyArrayObject *v, NPY_ORDER order) { npy_intp size, src_itemsize, v_stride; char *v_data; int needs_api = 0; npy_intp bmask_size; if (PyArray_DESCR(bmask)->type_num != NPY_BOOL) { PyErr_SetString(PyExc_TypeError, "NumPy boolean array indexing assignment " "requires a boolean index"); return -1; } if (PyArray_NDIM(v) > 1) { PyErr_Format(PyExc_TypeError, "NumPy boolean array indexing assignment " "requires a 0 or 1-dimensional input, input " "has %d dimensions", PyArray_NDIM(v)); return -1; } 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 -1; } 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; } /* Tweak the strides for 0-dim and broadcasting cases */ if (PyArray_NDIM(v) > 0 && PyArray_DIMS(v)[0] != 1) { if (size != PyArray_DIMS(v)[0]) { PyErr_Format(PyExc_ValueError, "NumPy boolean array indexing assignment " "cannot assign %d input values to " "the %d output values where the mask is true", (int)PyArray_DIMS(v)[0], (int)size); return -1; } v_stride = PyArray_STRIDES(v)[0]; } else { v_stride = 0; } src_itemsize = PyArray_DESCR(v)->elsize; v_data = PyArray_DATA(v); /* Create an iterator for the data */ if (size > 0) { NpyIter *iter; PyArrayObject *op[2] = {self, bmask}; npy_uint32 flags, op_flags[2]; npy_intp fixed_strides[3]; NpyIter_IterNextFunc *iternext; npy_intp innersize, *innerstrides; char **dataptrs; PyArray_StridedUnaryOp *stransfer = NULL; NpyAuxData *transferdata = NULL; npy_intp self_stride, bmask_stride, subloopsize; char *self_data; char *bmask_data; /* Set up the iterator */ flags = NPY_ITER_EXTERNAL_LOOP | NPY_ITER_REFS_OK; op_flags[0] = NPY_ITER_WRITEONLY | NPY_ITER_NO_BROADCAST; op_flags[1] = NPY_ITER_READONLY; iter = NpyIter_MultiNew(2, op, flags, order, NPY_NO_CASTING, op_flags, NULL); if (iter == NULL) { return -1; } /* Get the values needed for the inner loop */ iternext = NpyIter_GetIterNext(iter, NULL); if (iternext == NULL) { NpyIter_Deallocate(iter); return -1; } innerstrides = NpyIter_GetInnerStrideArray(iter); dataptrs = NpyIter_GetDataPtrArray(iter); self_stride = innerstrides[0]; bmask_stride = innerstrides[1]; /* Get a dtype transfer function */ NpyIter_GetInnerFixedStrideArray(iter, fixed_strides); if (PyArray_GetDTypeTransferFunction( PyArray_ISALIGNED(self) && PyArray_ISALIGNED(v), v_stride, fixed_strides[0], PyArray_DESCR(v), PyArray_DESCR(self), 0, &stransfer, &transferdata, &needs_api) != NPY_SUCCEED) { NpyIter_Deallocate(iter); return -1; } do { innersize = *NpyIter_GetInnerLoopSizePtr(iter); self_data = dataptrs[0]; bmask_data = dataptrs[1]; while (innersize > 0) { /* Skip masked values */ subloopsize = 0; while (subloopsize < innersize && *bmask_data == 0) { ++subloopsize; bmask_data += bmask_stride; } innersize -= subloopsize; self_data += subloopsize * self_stride; /* Process unmasked values */ subloopsize = 0; while (subloopsize < innersize && *bmask_data != 0) { ++subloopsize; bmask_data += bmask_stride; } stransfer(self_data, self_stride, v_data, v_stride, subloopsize, src_itemsize, transferdata); innersize -= subloopsize; self_data += subloopsize * self_stride; v_data += subloopsize * v_stride; } } while (iternext(iter)); NPY_AUXDATA_FREE(transferdata); NpyIter_Deallocate(iter); } 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. */ static int _tuple_of_integers(PyObject *seq, npy_intp *vals, int maxvals) { int i; PyObject *obj; npy_intp temp; for(i=0; i 0) || PyList_Check(obj)) { return 0; } temp = PyArray_PyIntAsIntp(obj); if (error_converting(temp)) { PyErr_Clear(); return 0; } vals[i] = temp; } 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++; } } return NPY_FALSE; } NPY_NO_EXPORT PyObject * array_subscript_fancy(PyArrayObject *self, PyObject *op, int fancy) { int oned; PyObject *other; PyArrayMapIterObject *mit; oned = ((PyArray_NDIM(self) == 1) && !(PyTuple_Check(op) && PyTuple_GET_SIZE(op) > 1)); /* 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); return NULL; } rval = iter_subscript(it, mit->indexobj); Py_DECREF(it); Py_DECREF(mit); return rval; } if (PyArray_MapIterBind(mit, self) != 0) { Py_DECREF(mit); return NULL; } 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) { return PyArray_EnsureAnyArray(array_subscript(self, op)); } NPY_NO_EXPORT PyObject * array_subscript_fromobject(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"); return NULL; } else { return array_item(self, (Py_ssize_t) value); } } /* optimization for a tuple of integers */ if (_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; } item += v * strides[idim]; } return PyArray_Scalar(item, PyArray_DESCR(self), (PyObject *)self); } } /* Check for single field access */ 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; } /* 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); } /* * 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; } } /* Check for Ellipsis index */ if (op == Py_Ellipsis) { Py_INCREF(self); return (PyObject *)self; } 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; } 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); } } PyErr_SetString(PyExc_IndexError, "0-dimensional arrays can't be indexed"); return NULL; } fancy = fancy_indexing_check(op); if (fancy != SOBJ_NOTFANCY) { PyObject *ret; ret = array_subscript_fancy(self, op, fancy); if (ret == NULL) { return NULL; } if (PyArray_Check(ret) && PyArray_NDIM((PyArrayObject *)ret) == 0 && !_check_ellipses(op)) { return PyArray_Return((PyArrayObject *)ret); } return ret; } else { return array_subscript_simple(self, op, 1); } } NPY_NO_EXPORT PyObject * array_subscript(PyArrayObject *self, PyObject *op) { int fancy; PyObject *ret = NULL; if (!PyArray_Check(op)) { return array_subscript_fromobject(self, op); } /* 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); } /* 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; } 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); } } return ret; } /* * 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. */ static int array_ass_sub_simple(PyArrayObject *self, PyObject *ind, PyObject *op) { int ret; PyArrayObject *tmp; npy_intp value; 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; } } else { return array_ass_item_object(self, value, op); } /* Rest of standard (view-based) indexing */ if (PyArray_CheckExact(self)) { tmp = (PyArrayObject *)array_subscript_simple(self, ind, 1); if (tmp == NULL) { 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 */ tmp0 = PyObject_GetItem((PyObject *)self, ind); if (tmp0 == NULL) { return -1; } if (!PyArray_Check(tmp0)) { PyErr_SetString(PyExc_RuntimeError, "Getitem not returning array"); Py_DECREF(tmp0); return -1; } tmp = (PyArrayObject *)tmp0; } ret = PyArray_CopyObject(tmp, op); Py_DECREF(tmp); return ret; } static int array_ass_sub_fancy(PyArrayObject *self, PyObject *ind, PyObject *op, int fancy) { 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; 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; } if (PyArray_MapIterBind(mit, self) != 0) { Py_DECREF(mit); return -1; } ret = PyArray_SetMap(mit, op); Py_DECREF(mit); return ret; } static int array_ass_sub(PyArrayObject *self, PyObject *ind, PyObject *op) { int fancy; npy_intp vals[NPY_MAXDIMS]; if (op == NULL) { PyErr_SetString(PyExc_ValueError, "cannot delete array elements"); return -1; } if (PyArray_FailUnlessWriteable(self, "assignment destination") < 0) { 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))) { PyObject *obj; obj = PyDict_GetItem(PyArray_DESCR(self)->fields, ind); if (obj != NULL) { PyArray_Descr *descr; int offset; PyObject *title; if (PyArg_ParseTuple(obj, "Oi|O", &descr, &offset, &title)) { Py_INCREF(descr); return PyArray_SetField(self, descr, offset, op); } } } #if defined(NPY_PY3K) PyErr_Format(PyExc_ValueError, "field named %S not found", ind); #else PyErr_Format(PyExc_ValueError, "field named %s not found", PyString_AsString(ind)); #endif return -1; } /* Ellipsis index */ if (ind == Py_Ellipsis) { /* * Doing "a[...] += 1" triggers assigning an array to itself, * so this check is needed. */ if ((PyObject *)self == op) { return 0; } else { return PyArray_CopyObject(self, op); } } if (PyArray_NDIM(self) == 0) { /* * Several different exceptions to the 0-d no-indexing rule * * 1) 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); } else { /* False: don't do anything */ return 0; } } PyErr_SetString(PyExc_IndexError, "0-dimensional arrays can't be indexed"); return -1; } /* 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); } } /* 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; 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; } } else { op_arr = op; Py_INCREF(op_arr); } if (PyArray_NDIM(op_arr) < 2) { retcode = array_ass_boolean_subscript(self, (PyArrayObject *)ind, op_arr, NPY_CORDER); Py_DECREF(op_arr); return retcode; } /* * Assigning from multi-dimensional 'op' in this case seems * inconsistent, so falling through to old code for backwards * compatibility. */ Py_DECREF(op_arr); } fancy = fancy_indexing_check(ind); if (fancy != SOBJ_NOTFANCY) { return array_ass_sub_fancy(self, ind, op, fancy); } else { return array_ass_sub_simple(self, ind, op); } } NPY_NO_EXPORT PyMappingMethods array_as_mapping = { (lenfunc)array_length, /*mp_length*/ (binaryfunc)array_subscript, /*mp_subscript*/ (objobjargproc)array_ass_sub, /*mp_ass_subscript*/ }; /****************** End of Mapping Protocol ******************************/ /*********************** Subscript Array Iterator ************************* * * * This object handles subscript behavior for array objects. * * It is an iterator object with a next method * * It abstracts the n-dimensional mapping behavior to make the looping * * code more understandable (maybe) * * and so that indexing can be set up ahead of time * */ /* * This function takes a Boolean array and constructs index objects and * iterators as if nonzero(Bool) had been called */ static int _nonzero_indices(PyObject *myBool, PyArrayIterObject **iters) { PyArray_Descr *typecode; PyArrayObject *ba = NULL, *new = NULL; int nd, j; npy_intp size, i, count; npy_bool *ptr; npy_intp coords[NPY_MAXDIMS], dims_m1[NPY_MAXDIMS]; npy_intp *dptr[NPY_MAXDIMS]; typecode=PyArray_DescrFromType(NPY_BOOL); ba = (PyArrayObject *)PyArray_FromAny(myBool, typecode, 0, 0, NPY_ARRAY_CARRAY, NULL); if (ba == NULL) { return -1; } 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; } 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++; } } /* create count-sized index arrays for each dimension */ for (j = 0; j < nd; j++) { new = (PyArrayObject *)PyArray_New(&PyArray_Type, 1, &count, NPY_INTP, NULL, NULL, 0, 0, NULL); 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); 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 */ for (i = 0; i < size; i++) { if (*(ptr++)) { for (j = 0; j < nd; j++) { *(dptr[j]++) = coords[j]; } } /* Borrowed from ITER_NEXT macro */ for (j = nd - 1; j >= 0; j--) { if (coords[j] < dims_m1[j]) { coords[j]++; break; } else { coords[j] = 0; } } } finish: Py_DECREF(ba); return nd; fail: for (j = 0; j < nd; j++) { Py_XDECREF(iters[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; mit->index = 0; if (mit->numiter > 0) { copyswap = PyArray_DESCR(mit->iters[0]->ao)->f->copyswap; } 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); } PyArray_ITER_GOTO(mit->ait, coord); mit->subspace->dataptr = mit->ait->dataptr; mit->dataptr = mit->subspace->dataptr; } 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; } 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 */ NPY_NO_EXPORT void PyArray_MapIterNext(PyArrayMapIterObject *mit) { int i, j; npy_intp coord[NPY_MAXDIMS]; PyArrayIterObject *it; PyArray_CopySwapFunc *copyswap; mit->index += 1; if (mit->index >= mit->size) { return; } if (mit->numiter > 0) { copyswap = PyArray_DESCR(mit->iters[0]->ao)->f->copyswap; } /* 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); } PyArray_ITER_GOTO(mit->ait, coord); mit->subspace->dataptr = mit->ait->dataptr; } 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); } 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. * * Subspace iteration is necessary if: PyArray_NDIM(arr) > mit->numiter * * Need to check for index-errors somewhere. * * Let's do it at bind time and also convert all <0 values to >0 here * as well. */ NPY_NO_EXPORT int PyArray_MapIterBind(PyArrayMapIterObject *mit, 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; } mit->ait = (PyArrayIterObject *)PyArray_IterNew((PyObject *)arr); if (mit->ait == NULL) { return -1; } /* * 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. */ if (PyArray_CheckExact(arr)) { sub = array_subscript_simple(arr, mit->indexobj, 0); } else { Py_INCREF(arr); obj = PyArray_EnsureArray((PyObject *)arr); if (obj == NULL) { return -1; } sub = array_subscript_simple((PyArrayObject *)obj, mit->indexobj, 0); Py_DECREF(obj); } if (sub == NULL) { return -1; } 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; } Py_DECREF(sub); goto finish; } mit->subspace = (PyArrayIterObject *)PyArray_IterNew(sub); Py_DECREF(sub); if (mit->subspace == NULL) { return -1; } 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; } /* Expand dimensions of result */ for (i = 0; i < subnd; i++) { mit->dimensions[mit->nd+i] = PyArray_DIMS(mit->subspace->ao)[i]; } 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 */ 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; /* * Now fill in iteraxes -- remember indexing arrays have been * converted to 0's in mit->indexobj */ 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++) { /* * We need to fill in the starting coordinates for * the subspace */ 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; } } else { npy_intp start = 0; npy_intp stop, step; /* Should be slice object or another Ellipsis */ if (obj == Py_Ellipsis) { mit->bscoord[curraxis] = 0; } 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; } else { mit->bscoord[curraxis] = start; } 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; } 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; } PyArray_ITER_NEXT(it); } PyArray_ITER_RESET(it); } return 0; } 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; if (fancy == SOBJ_BADARRAY) { PyErr_SetString(PyExc_IndexError, "arrays used as indices must be of " "integer (or boolean) type"); return NULL; } if (fancy == SOBJ_TOOMANY) { PyErr_SetString(PyExc_IndexError, "too many indices"); return NULL; } 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); /* initialize mapiter attributes */ mit->consec = 1; if (fancy == SOBJ_LISTTUP) { PyObject *newobj; newobj = PySequence_Tuple(indexobj); if (newobj == NULL) { goto fail; } indexobj = newobj; mit->indexobj = indexobj; } else { Py_INCREF(indexobj); mit->indexobj = indexobj; } if (oned) { return (PyObject *)mit; } /* * 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) { 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; } for (i = 0; i < mit->numiter; i++) { PyTuple_SET_ITEM(mit->indexobj, i, PyInt_FromLong(0)); } } 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) { goto fail; } mit->iters[0] = (PyArrayIterObject *)PyArray_IterNew((PyObject *)arr); if (mit->iters[0] == NULL) { Py_DECREF(arr); 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)); } else { /* must be a tuple */ PyObject *obj; PyArrayIterObject **iterp; PyObject *new; int numiters, j, n2; /* * Make a copy of the tuple -- we will be replacing * index objects with 0's */ n = PyTuple_GET_SIZE(indexobj); n2 = n; new = PyTuple_New(n2); if (new == NULL) { goto fail; } 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); } } Py_DECREF(mit->indexobj); mit->indexobj = new; /* * Store the number of iterators actually converted * These will be mapped to actual axes at bind time */ if (PyArray_Broadcast((PyArrayMultiIterObject *)mit) < 0) { goto fail; } } return (PyObject *)mit; fail: Py_DECREF(mit); return NULL; } /*NUMPY_API */ NPY_NO_EXPORT PyObject * PyArray_MapIterArray(PyArrayObject * a, PyObject * index) { PyArrayMapIterObject * mit; int fancy = fancy_indexing_check(index); /* * 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; mit = (PyArrayMapIterObject *) PyArray_MapIterNew(index, oned, fancy); if (mit == NULL) { return NULL; } if (PyArray_MapIterBind(mit, a) != 0) { Py_DECREF(mit); return NULL; } PyArray_MapIterReset(mit); return mit; } #undef SOBJ_NOTFANCY #undef SOBJ_ISFANCY #undef SOBJ_BADARRAY #undef SOBJ_TOOMANY #undef SOBJ_LISTTUP static void arraymapiter_dealloc(PyArrayMapIterObject *mit) { int i; Py_XDECREF(mit->indexobj); Py_XDECREF(mit->ait); Py_XDECREF(mit->subspace); for (i = 0; i < mit->numiter; i++) { Py_XDECREF(mit->iters[i]); } PyArray_free(mit); } /* * The mapiter object must be created new each time. It does not work * to bind to a new array, and continue. * * 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. */ NPY_NO_EXPORT PyTypeObject PyArrayMapIter_Type = { #if defined(NPY_PY3K) PyVarObject_HEAD_INIT(NULL, 0) #else PyObject_HEAD_INIT(NULL) 0, /* ob_size */ #endif "numpy.mapiter", /* tp_name */ sizeof(PyArrayIterObject), /* tp_basicsize */ 0, /* tp_itemsize */ /* methods */ (destructor)arraymapiter_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ #if defined(NPY_PY3K) 0, /* tp_reserved */ #else 0, /* tp_compare */ #endif 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT, /* tp_flags */ 0, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ 0, /* 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 */ 0, /* tp_init */ 0, /* tp_alloc */ 0, /* 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 */ 0, /* tp_version_tag */ }; /** END of Subscript Iterator **/ numpy-1.8.2/numpy/core/src/multiarray/refcount.c0000664000175100017510000001632412370216243023103 0ustar vagrantvagrant00000000000000/* * This module corresponds to the `Special functions for NPY_OBJECT` * section in the numpy reference for C-API. */ #define PY_SSIZE_T_CLEAN #include #include "structmember.h" #define NPY_NO_DEPRECATED_API NPY_API_VERSION #define _MULTIARRAYMODULE #include "numpy/arrayobject.h" #include "numpy/arrayscalars.h" #include "npy_config.h" #include "npy_pycompat.h" static void _fillobject(char *optr, PyObject *obj, PyArray_Descr *dtype); /* Incref all objects found at this record */ /*NUMPY_API */ NPY_NO_EXPORT void PyArray_Item_INCREF(char *data, PyArray_Descr *descr) { PyObject *temp; if (!PyDataType_REFCHK(descr)) { return; } if (descr->type_num == NPY_OBJECT) { NPY_COPY_PYOBJECT_PTR(&temp, data); Py_XINCREF(temp); } else if (PyDataType_HASFIELDS(descr)) { PyObject *key, *value, *title = NULL; PyArray_Descr *new; int offset; Py_ssize_t pos = 0; while (PyDict_Next(descr->fields, &pos, &key, &value)) { if NPY_TITLE_KEY(key, value) { continue; } if (!PyArg_ParseTuple(value, "Oi|O", &new, &offset, &title)) { return; } PyArray_Item_INCREF(data + offset, new); } } return; } /* XDECREF all objects found at this record */ /*NUMPY_API */ NPY_NO_EXPORT void PyArray_Item_XDECREF(char *data, PyArray_Descr *descr) { PyObject *temp; if (!PyDataType_REFCHK(descr)) { return; } if (descr->type_num == NPY_OBJECT) { NPY_COPY_PYOBJECT_PTR(&temp, data); Py_XDECREF(temp); } else if PyDataType_HASFIELDS(descr) { PyObject *key, *value, *title = NULL; PyArray_Descr *new; int offset; Py_ssize_t pos = 0; while (PyDict_Next(descr->fields, &pos, &key, &value)) { if NPY_TITLE_KEY(key, value) { continue; } if (!PyArg_ParseTuple(value, "Oi|O", &new, &offset, &title)) { return; } PyArray_Item_XDECREF(data + offset, new); } } return; } /* Used for arrays of python objects to increment the reference count of */ /* every python object in the array. */ /*NUMPY_API For object arrays, increment all internal references. */ NPY_NO_EXPORT int PyArray_INCREF(PyArrayObject *mp) { npy_intp i, n; PyObject **data; PyObject *temp; PyArrayIterObject *it; if (!PyDataType_REFCHK(PyArray_DESCR(mp))) { return 0; } if (PyArray_DESCR(mp)->type_num != NPY_OBJECT) { it = (PyArrayIterObject *)PyArray_IterNew((PyObject *)mp); if (it == NULL) { return -1; } while(it->index < it->size) { PyArray_Item_INCREF(it->dataptr, PyArray_DESCR(mp)); PyArray_ITER_NEXT(it); } Py_DECREF(it); return 0; } if (PyArray_ISONESEGMENT(mp)) { data = (PyObject **)PyArray_DATA(mp); n = PyArray_SIZE(mp); if (PyArray_ISALIGNED(mp)) { for (i = 0; i < n; i++, data++) { Py_XINCREF(*data); } } else { for( i = 0; i < n; i++, data++) { NPY_COPY_PYOBJECT_PTR(&temp, data); Py_XINCREF(temp); } } } else { /* handles misaligned data too */ it = (PyArrayIterObject *)PyArray_IterNew((PyObject *)mp); if (it == NULL) { return -1; } while(it->index < it->size) { NPY_COPY_PYOBJECT_PTR(&temp, it->dataptr); Py_XINCREF(temp); PyArray_ITER_NEXT(it); } Py_DECREF(it); } return 0; } /*NUMPY_API Decrement all internal references for object arrays. (or arrays with object fields) */ NPY_NO_EXPORT int PyArray_XDECREF(PyArrayObject *mp) { npy_intp i, n; PyObject **data; PyObject *temp; PyArrayIterObject *it; if (!PyDataType_REFCHK(PyArray_DESCR(mp))) { return 0; } if (PyArray_DESCR(mp)->type_num != NPY_OBJECT) { it = (PyArrayIterObject *)PyArray_IterNew((PyObject *)mp); if (it == NULL) { return -1; } while(it->index < it->size) { PyArray_Item_XDECREF(it->dataptr, PyArray_DESCR(mp)); PyArray_ITER_NEXT(it); } Py_DECREF(it); return 0; } if (PyArray_ISONESEGMENT(mp)) { data = (PyObject **)PyArray_DATA(mp); n = PyArray_SIZE(mp); if (PyArray_ISALIGNED(mp)) { for (i = 0; i < n; i++, data++) Py_XDECREF(*data); } else { for (i = 0; i < n; i++, data++) { NPY_COPY_PYOBJECT_PTR(&temp, data); Py_XDECREF(temp); } } } else { /* handles misaligned data too */ it = (PyArrayIterObject *)PyArray_IterNew((PyObject *)mp); if (it == NULL) { return -1; } while(it->index < it->size) { NPY_COPY_PYOBJECT_PTR(&temp, it->dataptr); Py_XDECREF(temp); PyArray_ITER_NEXT(it); } Py_DECREF(it); } return 0; } /*NUMPY_API * Assumes contiguous */ NPY_NO_EXPORT void PyArray_FillObjectArray(PyArrayObject *arr, PyObject *obj) { npy_intp i,n; n = PyArray_SIZE(arr); if (PyArray_DESCR(arr)->type_num == NPY_OBJECT) { PyObject **optr; optr = (PyObject **)(PyArray_DATA(arr)); n = PyArray_SIZE(arr); if (obj == NULL) { for (i = 0; i < n; i++) { *optr++ = NULL; } } else { for (i = 0; i < n; i++) { Py_INCREF(obj); *optr++ = obj; } } } else { char *optr; optr = PyArray_DATA(arr); for (i = 0; i < n; i++) { _fillobject(optr, obj, PyArray_DESCR(arr)); optr += PyArray_DESCR(arr)->elsize; } } } static void _fillobject(char *optr, PyObject *obj, PyArray_Descr *dtype) { if (!PyDataType_FLAGCHK(dtype, NPY_ITEM_REFCOUNT)) { if ((obj == Py_None) || (PyInt_Check(obj) && PyInt_AsLong(obj)==0)) { return; } else { PyObject *arr; Py_INCREF(dtype); arr = PyArray_NewFromDescr(&PyArray_Type, dtype, 0, NULL, NULL, NULL, 0, NULL); if (arr!=NULL) { dtype->f->setitem(obj, optr, arr); } Py_XDECREF(arr); } } else if (PyDataType_HASFIELDS(dtype)) { PyObject *key, *value, *title = NULL; PyArray_Descr *new; int offset; Py_ssize_t pos = 0; while (PyDict_Next(dtype->fields, &pos, &key, &value)) { if NPY_TITLE_KEY(key, value) { continue; } if (!PyArg_ParseTuple(value, "Oi|O", &new, &offset, &title)) { return; } _fillobject(optr + offset, obj, new); } } else { Py_XINCREF(obj); NPY_COPY_PYOBJECT_PTR(optr, &obj); return; } } numpy-1.8.2/numpy/core/src/multiarray/number.h0000664000175100017510000000344612370216243022554 0ustar vagrantvagrant00000000000000#ifndef _NPY_ARRAY_NUMBER_H_ #define _NPY_ARRAY_NUMBER_H_ typedef struct { PyObject *add; PyObject *subtract; PyObject *multiply; PyObject *divide; PyObject *remainder; PyObject *power; PyObject *square; PyObject *reciprocal; PyObject *_ones_like; PyObject *sqrt; PyObject *negative; PyObject *absolute; PyObject *invert; PyObject *left_shift; PyObject *right_shift; PyObject *bitwise_and; PyObject *bitwise_xor; PyObject *bitwise_or; PyObject *less; PyObject *less_equal; PyObject *equal; PyObject *not_equal; PyObject *greater; PyObject *greater_equal; PyObject *floor_divide; PyObject *true_divide; PyObject *logical_or; PyObject *logical_and; PyObject *floor; PyObject *ceil; PyObject *maximum; PyObject *minimum; PyObject *rint; PyObject *conjugate; } NumericOps; #ifdef NPY_ENABLE_SEPARATE_COMPILATION extern NPY_NO_EXPORT NumericOps n_ops; extern NPY_NO_EXPORT PyNumberMethods array_as_number; #else NPY_NO_EXPORT NumericOps n_ops; NPY_NO_EXPORT PyNumberMethods array_as_number; #endif NPY_NO_EXPORT PyObject * array_int(PyArrayObject *v); NPY_NO_EXPORT int PyArray_SetNumericOps(PyObject *dict); NPY_NO_EXPORT PyObject * PyArray_GetNumericOps(void); NPY_NO_EXPORT PyObject * PyArray_GenericBinaryFunction(PyArrayObject *m1, PyObject *m2, PyObject *op); NPY_NO_EXPORT PyObject * PyArray_GenericUnaryFunction(PyArrayObject *m1, PyObject *op); NPY_NO_EXPORT PyObject * PyArray_GenericReduceFunction(PyArrayObject *m1, PyObject *op, int axis, int rtype, PyArrayObject *out); NPY_NO_EXPORT PyObject * PyArray_GenericAccumulateFunction(PyArrayObject *m1, PyObject *op, int axis, int rtype, PyArrayObject *out); #endif numpy-1.8.2/numpy/core/src/npysort/0000775000175100017510000000000012371375427020444 5ustar vagrantvagrant00000000000000numpy-1.8.2/numpy/core/src/npysort/quicksort.c.src0000664000175100017510000002430112370216243023407 0ustar vagrantvagrant00000000000000/* -*- c -*- */ /* * The purpose of this module is to add faster sort functions * that are type-specific. This is done by altering the * function table for the builtin descriptors. * * These sorting functions are copied almost directly from numarray * with a few modifications (complex comparisons compare the imaginary * part if the real parts are equal, for example), and the names * are changed. * * The original sorting code is due to Charles R. Harris who wrote * it for numarray. */ /* * Quick sort is usually the fastest, but the worst case scenario can * be slower than the merge and heap sorts. The merge sort requires * extra memory and so for large arrays may not be useful. * * The merge sort is *stable*, meaning that equal components * are unmoved from their entry versions, so it can be used to * implement lexigraphic sorting on multiple keys. * * The heap sort is included for completeness. */ #define NPY_NO_DEPRECATED_API NPY_API_VERSION #include #include "npy_sort.h" #include "npysort_common.h" #define NOT_USED NPY_UNUSED(unused) #define PYA_QS_STACK 100 #define SMALL_QUICKSORT 15 #define SMALL_MERGESORT 20 #define SMALL_STRING 16 /* ***************************************************************************** ** NUMERIC SORTS ** ***************************************************************************** */ /**begin repeat * * #TYPE = BOOL, BYTE, UBYTE, SHORT, USHORT, INT, UINT, LONG, ULONG, * LONGLONG, ULONGLONG, HALF, FLOAT, DOUBLE, LONGDOUBLE, * CFLOAT, CDOUBLE, CLONGDOUBLE# * #suff = bool, byte, ubyte, short, ushort, int, uint, long, ulong, * longlong, ulonglong, half, float, double, longdouble, * cfloat, cdouble, clongdouble# * #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# */ int quicksort_@suff@(@type@ *start, npy_intp num, void *NOT_USED) { @type@ vp; @type@ *pl = start; @type@ *pr = start + num - 1; @type@ *stack[PYA_QS_STACK]; @type@ **sptr = stack; @type@ *pm, *pi, *pj, *pk; for (;;) { while ((pr - pl) > SMALL_QUICKSORT) { /* quicksort partition */ pm = pl + ((pr - pl) >> 1); if (@TYPE@_LT(*pm, *pl)) @TYPE@_SWAP(*pm, *pl); if (@TYPE@_LT(*pr, *pm)) @TYPE@_SWAP(*pr, *pm); if (@TYPE@_LT(*pm, *pl)) @TYPE@_SWAP(*pm, *pl); vp = *pm; pi = pl; pj = pr - 1; @TYPE@_SWAP(*pm, *pj); for (;;) { do ++pi; while (@TYPE@_LT(*pi, vp)); do --pj; while (@TYPE@_LT(vp, *pj)); if (pi >= pj) { break; } @TYPE@_SWAP(*pi,*pj); } pk = pr - 1; @TYPE@_SWAP(*pi, *pk); /* push largest partition on stack */ if (pi - pl < pr - pi) { *sptr++ = pi + 1; *sptr++ = pr; pr = pi - 1; } else { *sptr++ = pl; *sptr++ = pi - 1; pl = pi + 1; } } /* insertion sort */ for (pi = pl + 1; pi <= pr; ++pi) { vp = *pi; pj = pi; pk = pi - 1; while (pj > pl && @TYPE@_LT(vp, *pk)) { *pj-- = *pk--; } *pj = vp; } if (sptr == stack) { break; } pr = *(--sptr); pl = *(--sptr); } return 0; } int aquicksort_@suff@(@type@ *v, npy_intp* tosort, npy_intp num, void *NOT_USED) { @type@ vp; npy_intp *pl = tosort; npy_intp *pr = tosort + num - 1; npy_intp *stack[PYA_QS_STACK]; npy_intp **sptr = stack; npy_intp *pm, *pi, *pj, *pk, vi; for (;;) { while ((pr - pl) > SMALL_QUICKSORT) { /* quicksort partition */ pm = pl + ((pr - pl) >> 1); if (@TYPE@_LT(v[*pm],v[*pl])) INTP_SWAP(*pm, *pl); if (@TYPE@_LT(v[*pr],v[*pm])) INTP_SWAP(*pr, *pm); if (@TYPE@_LT(v[*pm],v[*pl])) INTP_SWAP(*pm, *pl); vp = v[*pm]; pi = pl; pj = pr - 1; INTP_SWAP(*pm, *pj); for (;;) { do ++pi; while (@TYPE@_LT(v[*pi], vp)); do --pj; while (@TYPE@_LT(vp, v[*pj])); if (pi >= pj) { break; } INTP_SWAP(*pi, *pj); } pk = pr - 1; INTP_SWAP(*pi,*pk); /* push largest partition on stack */ if (pi - pl < pr - pi) { *sptr++ = pi + 1; *sptr++ = pr; pr = pi - 1; } else { *sptr++ = pl; *sptr++ = pi - 1; pl = pi + 1; } } /* insertion sort */ for (pi = pl + 1; pi <= pr; ++pi) { vi = *pi; vp = v[vi]; pj = pi; pk = pi - 1; while (pj > pl && @TYPE@_LT(vp, v[*pk])) { *pj-- = *pk--; } *pj = vi; } if (sptr == stack) { break; } pr = *(--sptr); pl = *(--sptr); } return 0; } /**end repeat**/ /* ***************************************************************************** ** STRING SORTS ** ***************************************************************************** */ /**begin repeat * * #TYPE = STRING, UNICODE# * #suff = string, unicode# * #type = npy_char, npy_ucs4# */ int quicksort_@suff@(@type@ *start, npy_intp num, PyArrayObject *arr) { const size_t len = PyArray_ITEMSIZE(arr)/sizeof(@type@); @type@ *vp = malloc(PyArray_ITEMSIZE(arr)); @type@ *pl = start; @type@ *pr = start + (num - 1)*len; @type@ *stack[PYA_QS_STACK], **sptr = stack, *pm, *pi, *pj, *pk; for (;;) { while ((size_t)(pr - pl) > SMALL_QUICKSORT*len) { /* quicksort partition */ pm = pl + (((pr - pl)/len) >> 1)*len; if (@TYPE@_LT(pm, pl, len)) @TYPE@_SWAP(pm, pl, len); if (@TYPE@_LT(pr, pm, len)) @TYPE@_SWAP(pr, pm, len); if (@TYPE@_LT(pm, pl, len)) @TYPE@_SWAP(pm, pl, len); @TYPE@_COPY(vp, pm, len); pi = pl; pj = pr - len; @TYPE@_SWAP(pm, pj, len); for (;;) { do pi += len; while (@TYPE@_LT(pi, vp, len)); do pj -= len; while (@TYPE@_LT(vp, pj, len)); if (pi >= pj) { break; } @TYPE@_SWAP(pi, pj, len); } pk = pr - len; @TYPE@_SWAP(pi, pk, len); /* push largest partition on stack */ if (pi - pl < pr - pi) { *sptr++ = pi + len; *sptr++ = pr; pr = pi - len; } else { *sptr++ = pl; *sptr++ = pi - len; pl = pi + len; } } /* insertion sort */ for (pi = pl + len; pi <= pr; pi += len) { @TYPE@_COPY(vp, pi, len); pj = pi; pk = pi - len; while (pj > pl && @TYPE@_LT(vp, pk, len)) { @TYPE@_COPY(pj, pk, len); pj -= len; pk -= len; } @TYPE@_COPY(pj, vp, len); } if (sptr == stack) { break; } pr = *(--sptr); pl = *(--sptr); } free(vp); return 0; } int aquicksort_@suff@(@type@ *v, npy_intp* tosort, npy_intp num, PyArrayObject *arr) { size_t len = PyArray_ITEMSIZE(arr)/sizeof(@type@); @type@ *vp; npy_intp *pl = tosort; npy_intp *pr = tosort + num - 1; npy_intp *stack[PYA_QS_STACK]; npy_intp **sptr=stack; npy_intp *pm, *pi, *pj, *pk, vi; for (;;) { while ((pr - pl) > SMALL_QUICKSORT) { /* quicksort partition */ pm = pl + ((pr - pl) >> 1); if (@TYPE@_LT(v + (*pm)*len, v + (*pl)*len, len)) INTP_SWAP(*pm, *pl); if (@TYPE@_LT(v + (*pr)*len, v + (*pm)*len, len)) INTP_SWAP(*pr, *pm); if (@TYPE@_LT(v + (*pm)*len, v + (*pl)*len, len)) INTP_SWAP(*pm, *pl); vp = v + (*pm)*len; pi = pl; pj = pr - 1; INTP_SWAP(*pm,*pj); for (;;) { do ++pi; while (@TYPE@_LT(v + (*pi)*len, vp, len)); do --pj; while (@TYPE@_LT(vp, v + (*pj)*len, len)); if (pi >= pj) { break; } INTP_SWAP(*pi,*pj); } pk = pr - 1; INTP_SWAP(*pi,*pk); /* push largest partition on stack */ if (pi - pl < pr - pi) { *sptr++ = pi + 1; *sptr++ = pr; pr = pi - 1; } else { *sptr++ = pl; *sptr++ = pi - 1; pl = pi + 1; } } /* insertion sort */ for (pi = pl + 1; pi <= pr; ++pi) { vi = *pi; vp = v + vi*len; pj = pi; pk = pi - 1; while (pj > pl && @TYPE@_LT(vp, v + (*pk)*len, len)) { *pj-- = *pk--; } *pj = vi; } if (sptr == stack) { break; } pr = *(--sptr); pl = *(--sptr); } return 0; } /**end repeat**/ /* ***************************************************************************** ** GENERIC SORT ** ***************************************************************************** */ /* * This sort has almost the same signature as libc qsort and is intended to * supply an error return for compatibility with the other generic sort * kinds. */ int npy_quicksort(void *base, size_t num, size_t size, npy_comparator cmp) { qsort(base, num, size, cmp); return 0; } numpy-1.8.2/numpy/core/src/npysort/heapsort.c.src0000664000175100017510000002126612370216243023217 0ustar vagrantvagrant00000000000000/* -*- c -*- */ /* * The purpose of this module is to add faster sort functions * that are type-specific. This is done by altering the * function table for the builtin descriptors. * * These sorting functions are copied almost directly from numarray * with a few modifications (complex comparisons compare the imaginary * part if the real parts are equal, for example), and the names * are changed. * * The original sorting code is due to Charles R. Harris who wrote * it for numarray. */ /* * Quick sort is usually the fastest, but the worst case scenario can * be slower than the merge and heap sorts. The merge sort requires * extra memory and so for large arrays may not be useful. * * The merge sort is *stable*, meaning that equal components * are unmoved from their entry versions, so it can be used to * implement lexigraphic sorting on multiple keys. * * The heap sort is included for completeness. */ #define NPY_NO_DEPRECATED_API NPY_API_VERSION #include #include "npy_sort.h" #include "npysort_common.h" #define NOT_USED NPY_UNUSED(unused) #define PYA_QS_STACK 100 #define SMALL_QUICKSORT 15 #define SMALL_MERGESORT 20 #define SMALL_STRING 16 /* ***************************************************************************** ** NUMERIC SORTS ** ***************************************************************************** */ /**begin repeat * * #TYPE = BOOL, BYTE, UBYTE, SHORT, USHORT, INT, UINT, LONG, ULONG, * LONGLONG, ULONGLONG, HALF, FLOAT, DOUBLE, LONGDOUBLE, * CFLOAT, CDOUBLE, CLONGDOUBLE# * #suff = bool, byte, ubyte, short, ushort, int, uint, long, ulong, * longlong, ulonglong, half, float, double, longdouble, * cfloat, cdouble, clongdouble# * #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# */ int heapsort_@suff@(@type@ *start, npy_intp n, void *NOT_USED) { @type@ tmp, *a; npy_intp i,j,l; /* The array needs to be offset by one for heapsort indexing */ a = start - 1; for (l = n>>1; l > 0; --l) { tmp = a[l]; for (i = l, j = l<<1; j <= n;) { if (j < n && @TYPE@_LT(a[j], a[j+1])) { j += 1; } if (@TYPE@_LT(tmp, a[j])) { a[i] = a[j]; i = j; j += j; } else { break; } } a[i] = tmp; } for (; n > 1;) { tmp = a[n]; a[n] = a[1]; n -= 1; for (i = 1, j = 2; j <= n;) { if (j < n && @TYPE@_LT(a[j], a[j+1])) { j++; } if (@TYPE@_LT(tmp, a[j])) { a[i] = a[j]; i = j; j += j; } else { break; } } a[i] = tmp; } return 0; } int aheapsort_@suff@(@type@ *v, npy_intp *tosort, npy_intp n, void *NOT_USED) { npy_intp *a, i,j,l, tmp; /* The arrays need to be offset by one for heapsort indexing */ a = tosort - 1; for (l = n>>1; l > 0; --l) { tmp = a[l]; for (i = l, j = l<<1; j <= n;) { if (j < n && @TYPE@_LT(v[a[j]], v[a[j+1]])) { j += 1; } if (@TYPE@_LT(v[tmp], v[a[j]])) { a[i] = a[j]; i = j; j += j; } else { break; } } a[i] = tmp; } for (; n > 1;) { tmp = a[n]; a[n] = a[1]; n -= 1; for (i = 1, j = 2; j <= n;) { if (j < n && @TYPE@_LT(v[a[j]], v[a[j+1]])) { j++; } if (@TYPE@_LT(v[tmp], v[a[j]])) { a[i] = a[j]; i = j; j += j; } else { break; } } a[i] = tmp; } return 0; } /**end repeat**/ /* ***************************************************************************** ** STRING SORTS ** ***************************************************************************** */ /**begin repeat * * #TYPE = STRING, UNICODE# * #suff = string, unicode# * #type = npy_char, npy_ucs4# */ int heapsort_@suff@(@type@ *start, npy_intp n, PyArrayObject *arr) { size_t len = PyArray_ITEMSIZE(arr)/sizeof(@type@); @type@ *tmp = malloc(PyArray_ITEMSIZE(arr)); @type@ *a = start - len; npy_intp i, j, l; for (l = n>>1; l > 0; --l) { @TYPE@_COPY(tmp, a + l*len, len); for (i = l, j = l<<1; j <= n;) { if (j < n && @TYPE@_LT(a + j*len, a + (j+1)*len, len)) j += 1; if (@TYPE@_LT(tmp, a + j*len, len)) { @TYPE@_COPY(a + i*len, a + j*len, len); i = j; j += j; } else { break; } } @TYPE@_COPY(a + i*len, tmp, len); } for (; n > 1;) { @TYPE@_COPY(tmp, a + n*len, len); @TYPE@_COPY(a + n*len, a + len, len); n -= 1; for (i = 1, j = 2; j <= n;) { if (j < n && @TYPE@_LT(a + j*len, a + (j+1)*len, len)) j++; if (@TYPE@_LT(tmp, a + j*len, len)) { @TYPE@_COPY(a + i*len, a + j*len, len); i = j; j += j; } else { break; } } @TYPE@_COPY(a + i*len, tmp, len); } free(tmp); return 0; } int aheapsort_@suff@(@type@ *v, npy_intp *tosort, npy_intp n, PyArrayObject *arr) { size_t len = PyArray_ITEMSIZE(arr)/sizeof(@type@); npy_intp *a, i,j,l, tmp; /* The array needs to be offset by one for heapsort indexing */ a = tosort - 1; for (l = n>>1; l > 0; --l) { tmp = a[l]; for (i = l, j = l<<1; j <= n;) { if (j < n && @TYPE@_LT(v + a[j]*len, v + a[j+1]*len, len)) j += 1; if (@TYPE@_LT(v + tmp*len, v + a[j]*len, len)) { a[i] = a[j]; i = j; j += j; } else { break; } } a[i] = tmp; } for (; n > 1;) { tmp = a[n]; a[n] = a[1]; n -= 1; for (i = 1, j = 2; j <= n;) { if (j < n && @TYPE@_LT(v + a[j]*len, v + a[j+1]*len, len)) j++; if (@TYPE@_LT(v + tmp*len, v + a[j]*len, len)) { a[i] = a[j]; i = j; j += j; } else { break; } } a[i] = tmp; } return 0; } /**end repeat**/ /* ***************************************************************************** ** GENERIC SORT ** ***************************************************************************** */ /* * This sort has almost the same signature as libc qsort and is intended to * provide a heapsort for array types that don't have type specific sorts. * The difference in the signature is an error return, as it might be the * case that a memory allocation fails. */ int npy_heapsort(void *base, size_t num, size_t size, npy_comparator cmp) { char *tmp = (char *) malloc(size); char *a = (char *) base - size; size_t i, j, l; if (tmp == NULL) { return -NPY_ENOMEM; } for (l = num >> 1; l > 0; --l) { GENERIC_COPY(tmp, a + l*size, size); for (i = l, j = l << 1; j <= num;) { if (j < num && GENERIC_LT(a + j*size, a + (j+1)*size, cmp)) j += 1; if (GENERIC_LT(tmp, a + j*size, cmp)) { GENERIC_COPY(a + i*size, a + j*size, size); i = j; j += j; } else { break; } } GENERIC_COPY(a + i*size, tmp, size); } for (; num > 1;) { GENERIC_COPY(tmp, a + num*size, size); GENERIC_COPY(a + num*size, a + size, size); num -= 1; for (i = 1, j = 2; j <= num;) { if (j < num && GENERIC_LT(a + j*size, a + (j+1)*size, cmp)) j++; if (GENERIC_LT(tmp, a + j*size, cmp)) { GENERIC_COPY(a + i*size, a + j*size, size); i = j; j += j; } else { break; } } GENERIC_COPY(a + i*size, tmp, size); } free(tmp); return 0; } numpy-1.8.2/numpy/core/src/npysort/npysort_common.h0000664000175100017510000001604312370216243023674 0ustar vagrantvagrant00000000000000#ifndef __NPY_SORT_COMMON_H__ #define __NPY_SORT_COMMON_H__ #include #include /* ***************************************************************************** ** SWAP MACROS ** ***************************************************************************** */ #define BOOL_SWAP(a,b) {npy_bool tmp = (b); (b)=(a); (a) = tmp;} #define BYTE_SWAP(a,b) {npy_byte tmp = (b); (b)=(a); (a) = tmp;} #define UBYTE_SWAP(a,b) {npy_ubyte tmp = (b); (b)=(a); (a) = tmp;} #define SHORT_SWAP(a,b) {npy_short tmp = (b); (b)=(a); (a) = tmp;} #define USHORT_SWAP(a,b) {npy_ushort tmp = (b); (b)=(a); (a) = tmp;} #define INT_SWAP(a,b) {npy_int tmp = (b); (b)=(a); (a) = tmp;} #define UINT_SWAP(a,b) {npy_uint tmp = (b); (b)=(a); (a) = tmp;} #define LONG_SWAP(a,b) {npy_long tmp = (b); (b)=(a); (a) = tmp;} #define ULONG_SWAP(a,b) {npy_ulong tmp = (b); (b)=(a); (a) = tmp;} #define LONGLONG_SWAP(a,b) {npy_longlong tmp = (b); (b)=(a); (a) = tmp;} #define ULONGLONG_SWAP(a,b) {npy_ulonglong tmp = (b); (b)=(a); (a) = tmp;} #define HALF_SWAP(a,b) {npy_half tmp = (b); (b)=(a); (a) = tmp;} #define FLOAT_SWAP(a,b) {npy_float tmp = (b); (b)=(a); (a) = tmp;} #define DOUBLE_SWAP(a,b) {npy_double tmp = (b); (b)=(a); (a) = tmp;} #define LONGDOUBLE_SWAP(a,b) {npy_longdouble tmp = (b); (b)=(a); (a) = tmp;} #define CFLOAT_SWAP(a,b) {npy_cfloat tmp = (b); (b)=(a); (a) = tmp;} #define CDOUBLE_SWAP(a,b) {npy_cdouble tmp = (b); (b)=(a); (a) = tmp;} #define CLONGDOUBLE_SWAP(a,b) {npy_clongdouble tmp = (b); (b)=(a); (a) = tmp;} /* Need this for the argsort functions */ #define INTP_SWAP(a,b) {npy_intp tmp = (b); (b)=(a); (a) = tmp;} /* ***************************************************************************** ** COMPARISON FUNCTIONS ** ***************************************************************************** */ NPY_INLINE static int BOOL_LT(npy_bool a, npy_bool b) { return a < b; } NPY_INLINE static int BYTE_LT(npy_byte a, npy_byte b) { return a < b; } NPY_INLINE static int UBYTE_LT(npy_ubyte a, npy_ubyte b) { return a < b; } NPY_INLINE static int SHORT_LT(npy_short a, npy_short b) { return a < b; } NPY_INLINE static int USHORT_LT(npy_ushort a, npy_ushort b) { return a < b; } NPY_INLINE static int INT_LT(npy_int a, npy_int b) { return a < b; } NPY_INLINE static int UINT_LT(npy_uint a, npy_uint b) { return a < b; } NPY_INLINE static int LONG_LT(npy_long a, npy_long b) { return a < b; } NPY_INLINE static int ULONG_LT(npy_ulong a, npy_ulong b) { return a < b; } NPY_INLINE static int LONGLONG_LT(npy_longlong a, npy_longlong b) { return a < b; } NPY_INLINE static int ULONGLONG_LT(npy_ulonglong a, npy_ulonglong b) { return a < b; } NPY_INLINE static int FLOAT_LT(npy_float a, npy_float b) { return a < b || (b != b && a == a); } NPY_INLINE static int DOUBLE_LT(npy_double a, npy_double b) { return a < b || (b != b && a == a); } NPY_INLINE static int LONGDOUBLE_LT(npy_longdouble a, npy_longdouble b) { return a < b || (b != b && a == a); } NPY_INLINE static int npy_half_isnan(npy_half h) { return ((h&0x7c00u) == 0x7c00u) && ((h&0x03ffu) != 0x0000u); } NPY_INLINE static int npy_half_lt_nonan(npy_half h1, npy_half h2) { if (h1&0x8000u) { if (h2&0x8000u) { return (h1&0x7fffu) > (h2&0x7fffu); } else { /* Signed zeros are equal, have to check for it */ return (h1 != 0x8000u) || (h2 != 0x0000u); } } else { if (h2&0x8000u) { return 0; } else { return (h1&0x7fffu) < (h2&0x7fffu); } } } NPY_INLINE static int HALF_LT(npy_half a, npy_half b) { int ret; if (npy_half_isnan(b)) { ret = !npy_half_isnan(a); } else { ret = !npy_half_isnan(a) && npy_half_lt_nonan(a, b); } return ret; } /* * For inline functions SUN recommends not using a return in the then part * of an if statement. It's a SUN compiler thing, so assign the return value * to a variable instead. */ NPY_INLINE static int CFLOAT_LT(npy_cfloat a, npy_cfloat b) { int ret; if (a.real < b.real) { ret = a.imag == a.imag || b.imag != b.imag; } else if (a.real > b.real) { ret = b.imag != b.imag && a.imag == a.imag; } else if (a.real == b.real || (a.real != a.real && b.real != b.real)) { ret = a.imag < b.imag || (b.imag != b.imag && a.imag == a.imag); } else { ret = b.real != b.real; } return ret; } NPY_INLINE static int CDOUBLE_LT(npy_cdouble a, npy_cdouble b) { int ret; if (a.real < b.real) { ret = a.imag == a.imag || b.imag != b.imag; } else if (a.real > b.real) { ret = b.imag != b.imag && a.imag == a.imag; } else if (a.real == b.real || (a.real != a.real && b.real != b.real)) { ret = a.imag < b.imag || (b.imag != b.imag && a.imag == a.imag); } else { ret = b.real != b.real; } return ret; } NPY_INLINE static int CLONGDOUBLE_LT(npy_clongdouble a, npy_clongdouble b) { int ret; if (a.real < b.real) { ret = a.imag == a.imag || b.imag != b.imag; } else if (a.real > b.real) { ret = b.imag != b.imag && a.imag == a.imag; } else if (a.real == b.real || (a.real != a.real && b.real != b.real)) { ret = a.imag < b.imag || (b.imag != b.imag && a.imag == a.imag); } else { ret = b.real != b.real; } return ret; } NPY_INLINE static void STRING_COPY(char *s1, char *s2, size_t len) { memcpy(s1, s2, len); } NPY_INLINE static void STRING_SWAP(char *s1, char *s2, size_t len) { while(len--) { const char t = *s1; *s1++ = *s2; *s2++ = t; } } NPY_INLINE static int STRING_LT(char *s1, char *s2, size_t len) { const unsigned char *c1 = (unsigned char *)s1; const unsigned char *c2 = (unsigned char *)s2; size_t i; int ret = 0; for (i = 0; i < len; ++i) { if (c1[i] != c2[i]) { ret = c1[i] < c2[i]; break; } } return ret; } NPY_INLINE static void UNICODE_COPY(npy_ucs4 *s1, npy_ucs4 *s2, size_t len) { while(len--) { *s1++ = *s2++; } } NPY_INLINE static void UNICODE_SWAP(npy_ucs4 *s1, npy_ucs4 *s2, size_t len) { while(len--) { const npy_ucs4 t = *s1; *s1++ = *s2; *s2++ = t; } } NPY_INLINE static int UNICODE_LT(npy_ucs4 *s1, npy_ucs4 *s2, size_t len) { size_t i; int ret = 0; for (i = 0; i < len; ++i) { if (s1[i] != s2[i]) { ret = s1[i] < s2[i]; break; } } return ret; } NPY_INLINE static void GENERIC_COPY(char *a, char *b, size_t len) { memcpy(a, b, len); } NPY_INLINE static void GENERIC_SWAP(char *a, char *b, size_t len) { while(len--) { const char t = *a; *a++ = *b; *b++ = t; } } NPY_INLINE static int GENERIC_LT(char *a, char *b, int (*cmp)(const void *, const void *)) { return cmp(a, b) < 0; } #endif numpy-1.8.2/numpy/core/src/npysort/selection.c.src0000664000175100017510000003160612370216243023356 0ustar vagrantvagrant00000000000000/* -*- c -*- */ /* * * The code is loosely based on the quickselect from * Nicolas Devillard - 1998 public domain * http://ndevilla.free.fr/median/median/ * * Quick select with median of 3 pivot is usually the fastest, * but the worst case scenario can be quadratic complexcity, * e.g. np.roll(np.arange(x), x / 2) * To avoid this if it recurses too much it falls back to the * worst case linear median of median of group 5 pivot strategy. */ #define NPY_NO_DEPRECATED_API NPY_API_VERSION #include "npy_sort.h" #include "npysort_common.h" #include "numpy/npy_math.h" #include "npy_partition.h" #include #define NOT_USED NPY_UNUSED(unused) /* ***************************************************************************** ** NUMERIC SORTS ** ***************************************************************************** */ static NPY_INLINE void store_pivot(npy_intp pivot, npy_intp kth, npy_intp * pivots, npy_intp * npiv) { if (pivots == NULL) { return; } /* * If pivot is the requested kth store it, overwritting other pivots if * required. This must be done so iterative partition can work without * manually shifting lower data offset by kth each time */ if (pivot == kth && *npiv == NPY_MAX_PIVOT_STACK) { pivots[*npiv - 1] = pivot; } /* * we only need pivots larger than current kth, larger pivots are not * useful as partitions on smaller kth would reorder the stored pivots */ else if (pivot >= kth && *npiv < NPY_MAX_PIVOT_STACK) { pivots[*npiv] = pivot; (*npiv) += 1; } } /**begin repeat * * #TYPE = BOOL, BYTE, UBYTE, SHORT, USHORT, INT, UINT, LONG, ULONG, * LONGLONG, ULONGLONG, HALF, FLOAT, DOUBLE, LONGDOUBLE, * CFLOAT, CDOUBLE, CLONGDOUBLE# * #suff = bool, byte, ubyte, short, ushort, int, uint, long, ulong, * longlong, ulonglong, half, float, double, longdouble, * cfloat, cdouble, clongdouble# * #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# */ static npy_intp amedian_of_median5_@suff@(@type@ *v, npy_intp* tosort, const npy_intp num, npy_intp * pivots, npy_intp * npiv); static npy_intp median_of_median5_@suff@(@type@ *v, const npy_intp num, npy_intp * pivots, npy_intp * npiv); /**begin repeat1 * #name = , a# * #idx = , tosort# * #arg = 0, 1# */ #if @arg@ /* helper macros to avoid duplication of direct/indirect selection */ #define IDX(x) tosort[x] #define SORTEE(x) tosort[x] #define SWAP INTP_SWAP #define MEDIAN3_SWAP(v, tosort, low, mid, high) \ amedian3_swap_@suff@(v, tosort, low, mid, high) #define MEDIAN5(v, tosort, subleft) \ amedian5_@suff@(v, tosort + subleft) #define UNGUARDED_PARTITION(v, tosort, pivot, ll, hh) \ aunguarded_partition_@suff@(v, tosort, pivot, ll, hh) #define INTROSELECT(v, tosort, num, kth, pivots, npiv) \ aintroselect_@suff@(v, tosort, nmed, nmed / 2, pivots, npiv, NULL) #define DUMBSELECT(v, tosort, left, num, kth) \ adumb_select_@suff@(v, tosort + left, num, kth) #else #define IDX(x) (x) #define SORTEE(x) v[x] #define SWAP @TYPE@_SWAP #define MEDIAN3_SWAP(v, tosort, low, mid, high) \ median3_swap_@suff@(v, low, mid, high) #define MEDIAN5(v, tosort, subleft) \ median5_@suff@(v + subleft) #define UNGUARDED_PARTITION(v, tosort, pivot, ll, hh) \ unguarded_partition_@suff@(v, pivot, ll, hh) #define INTROSELECT(v, tosort, num, kth, pivots, npiv) \ introselect_@suff@(v, nmed, nmed / 2, pivots, npiv, NULL) #define DUMBSELECT(v, tosort, left, num, kth) \ dumb_select_@suff@(v + left, num, kth) #endif /* * median of 3 pivot strategy * gets min and median and moves median to low and min to low + 1 * for efficient partitioning, see unguarded_partition */ static NPY_INLINE void @name@median3_swap_@suff@(@type@ * v, #if @arg@ npy_intp * tosort, #endif npy_intp low, npy_intp mid, npy_intp high) { if (@TYPE@_LT(v[IDX(high)], v[IDX(mid)])) SWAP(SORTEE(high), SORTEE(mid)); if (@TYPE@_LT(v[IDX(high)], v[IDX(low)])) SWAP(SORTEE(high), SORTEE(low)); /* move pivot to low */ if (@TYPE@_LT(v[IDX(low)], v[IDX(mid)])) SWAP(SORTEE(low), SORTEE(mid)); /* move 3-lowest element to low + 1 */ SWAP(SORTEE(mid), SORTEE(low + 1)); } /* select index of median of five elements */ static npy_intp @name@median5_@suff@( #if @arg@ const @type@ * v, npy_intp * tosort #else @type@ * v #endif ) { /* could be optimized as we only need the index (no swaps) */ if (@TYPE@_LT(v[IDX(1)], v[IDX(0)])) { SWAP(SORTEE(1), SORTEE(0)); } if (@TYPE@_LT(v[IDX(4)], v[IDX(3)])) { SWAP(SORTEE(4), SORTEE(3)); } if (@TYPE@_LT(v[IDX(3)], v[IDX(0)])) { SWAP(SORTEE(3), SORTEE(0)); } if (@TYPE@_LT(v[IDX(4)], v[IDX(1)])) { SWAP(SORTEE(4), SORTEE(1)); } if (@TYPE@_LT(v[IDX(2)], v[IDX(1)])) { SWAP(SORTEE(2), SORTEE(1)); } if (@TYPE@_LT(v[IDX(3)], v[IDX(2)])) { if (@TYPE@_LT(v[IDX(3)], v[IDX(1)])) { return 1; } else { return 3; } } else { if (@TYPE@_LT(v[IDX(2)], v[IDX(1)])) { return 1; } else { return 2; } } } /* * partition and return the index were the pivot belongs * the data must have following property to avoid bound checks: * ll ... hh * lower-than-pivot [x x x x] larger-than-pivot */ static NPY_INLINE void @name@unguarded_partition_@suff@(@type@ * v, #if @arg@ npy_intp * tosort, #endif const @type@ pivot, npy_intp * ll, npy_intp * hh) { for (;;) { do (*ll)++; while (@TYPE@_LT(v[IDX(*ll)], pivot)); do (*hh)--; while (@TYPE@_LT(pivot, v[IDX(*hh)])); if (*hh < *ll) break; SWAP(SORTEE(*ll), SORTEE(*hh)); } } /* * select median of median of blocks of 5 * if used as partition pivot it splits the range into at least 30%/70% * allowing linear time worstcase quickselect */ static npy_intp @name@median_of_median5_@suff@(@type@ *v, #if @arg@ npy_intp* tosort, #endif const npy_intp num, npy_intp * pivots, npy_intp * npiv) { npy_intp i, subleft; npy_intp right = num - 1; npy_intp nmed = (right + 1) / 5; for (i = 0, subleft = 0; i < nmed; i++, subleft += 5) { npy_intp m = MEDIAN5(v, tosort, subleft); SWAP(SORTEE(subleft + m), SORTEE(i)); } if (nmed > 2) INTROSELECT(v, tosort, nmed, nmed / 2, pivots, npiv); return nmed / 2; } /* * N^2 selection, fast only for very small kth * useful for close multiple partitions * (e.g. even element median, interpolating percentile) */ static int @name@dumb_select_@suff@(@type@ *v, #if @arg@ npy_intp * tosort, #endif npy_intp num, npy_intp kth) { npy_intp i; for (i = 0; i <= kth; i++) { npy_intp minidx = i; @type@ minval = v[IDX(i)]; npy_intp k; for (k = i + 1; k < num; k++) { if (@TYPE@_LT(v[IDX(k)], minval)) { minidx = k; minval = v[IDX(k)]; } } SWAP(SORTEE(i), SORTEE(minidx)); } return 0; } /* * iterative median of 3 quickselect with cutoff to median-of-medians-of5 * receives stack of already computed pivots in v to minimize the * partition size were kth is searched in * * area that needs partitioning in [...] * kth 0: [8 7 6 5 4 3 2 1 0] -> med3 partitions elements [4, 2, 0] * 0 1 2 3 4 8 7 5 6 -> pop requested kth -> stack [4, 2] * kth 3: 0 1 2 [3] 4 8 7 5 6 -> stack [4] * kth 5: 0 1 2 3 4 [8 7 5 6] -> stack [6] * kth 8: 0 1 2 3 4 5 6 [8 7] -> stack [] * */ int @name@introselect_@suff@(@type@ *v, #if @arg@ npy_intp* tosort, #endif npy_intp num, npy_intp kth, npy_intp * pivots, npy_intp * npiv, void *NOT_USED) { npy_intp low = 0; npy_intp high = num - 1; npy_intp depth_limit; if (npiv == NULL) pivots = NULL; while (pivots != NULL && *npiv > 0) { if (pivots[*npiv - 1] > kth) { /* pivot larger than kth set it as upper bound */ high = pivots[*npiv - 1] - 1; break; } else if (pivots[*npiv - 1] == kth) { /* kth was already found in a previous iteration -> done */ return 0; } low = pivots[*npiv - 1] + 1; /* pop from stack */ *npiv -= 1; } /* * use a faster O(n*kth) algorithm for very small kth * e.g. for interpolating percentile */ if (kth - low < 3) { DUMBSELECT(v, tosort, low, high - low + 1, kth - low); store_pivot(kth, kth, pivots, npiv); return 0; } /* dumb integer msb, float npy_log2 too slow for small parititions */ { npy_uintp unum = num; depth_limit = 0; while (unum >>= 1) { depth_limit++; } depth_limit *= 2; } /* guarantee three elements */ for (;low + 1 < high;) { npy_intp ll = low + 1; npy_intp hh = high; /* * if we aren't making sufficient progress with median of 3 * fall back to median-of-median5 pivot for linear worst case * med3 for small sizes is required to do unguarded partition */ if (depth_limit > 0 || hh - ll < 5) { const npy_intp mid = low + (high - low) / 2; /* median of 3 pivot strategy, * swapping for efficient partition */ MEDIAN3_SWAP(v, tosort, low, mid, high); } else { npy_intp mid; /* FIXME: always use pivots to optimize this iterative partition */ #if @arg@ mid = ll + amedian_of_median5_@suff@(v, tosort + ll, hh - ll, NULL, NULL); #else mid = ll + median_of_median5_@suff@(v + ll, hh - ll, NULL, NULL); #endif SWAP(SORTEE(mid), SORTEE(low)); /* adapt for the larger partition than med3 pivot */ ll--; hh++; } depth_limit--; /* * find place to put pivot (in low): * previous swapping removes need for bound checks * pivot 3-lowest [x x x] 3-highest */ UNGUARDED_PARTITION(v, tosort, v[IDX(low)], &ll, &hh); /* move pivot into position */ SWAP(SORTEE(low), SORTEE(hh)); /* kth pivot stored later */ if (hh != kth) { store_pivot(hh, kth, pivots, npiv); } if (hh >= kth) high = hh - 1; if (hh <= kth) low = ll; } /* two elements */ if (high == low + 1) { if (@TYPE@_LT(v[IDX(high)], v[IDX(low)])) { SWAP(SORTEE(high), SORTEE(low)) } } store_pivot(kth, kth, pivots, npiv); return 0; } #undef IDX #undef SWAP #undef SORTEE #undef MEDIAN3_SWAP #undef MEDIAN5 #undef UNGUARDED_PARTITION #undef INTROSELECT #undef DUMBSELECT /**end repeat1**/ /**end repeat**/ /* ***************************************************************************** ** STRING SORTS ** ***************************************************************************** */ /**begin repeat * * #TYPE = STRING, UNICODE# * #suff = string, unicode# * #type = npy_char, npy_ucs4# */ int introselect_@suff@(@type@ *start, npy_intp num, npy_intp kth, PyArrayObject *arr) { return quicksort_@suff@(start, num, arr); } int aintroselect_@suff@(@type@ *v, npy_intp* tosort, npy_intp num, npy_intp kth, void *null) { return aquicksort_@suff@(v, tosort, num, null); } /**end repeat**/ /* ***************************************************************************** ** GENERIC SORT ** ***************************************************************************** */ /* * This sort has almost the same signature as libc qsort and is intended to * supply an error return for compatibility with the other generic sort * kinds. */ int npy_introselect(void *base, size_t num, size_t size, size_t kth, npy_comparator cmp) { return npy_quicksort(base, num, size, cmp); } numpy-1.8.2/numpy/core/src/npysort/mergesort.c.src0000664000175100017510000002501412370216243023374 0ustar vagrantvagrant00000000000000/* -*- c -*- */ /* * The purpose of this module is to add faster sort functions * that are type-specific. This is done by altering the * function table for the builtin descriptors. * * These sorting functions are copied almost directly from numarray * with a few modifications (complex comparisons compare the imaginary * part if the real parts are equal, for example), and the names * are changed. * * The original sorting code is due to Charles R. Harris who wrote * it for numarray. */ /* * Quick sort is usually the fastest, but the worst case scenario can * be slower than the merge and heap sorts. The merge sort requires * extra memory and so for large arrays may not be useful. * * The merge sort is *stable*, meaning that equal components * are unmoved from their entry versions, so it can be used to * implement lexigraphic sorting on multiple keys. * * The heap sort is included for completeness. */ #define NPY_NO_DEPRECATED_API NPY_API_VERSION #include #include "npy_sort.h" #include "npysort_common.h" #define NOT_USED NPY_UNUSED(unused) #define PYA_QS_STACK 100 #define SMALL_QUICKSORT 15 #define SMALL_MERGESORT 20 #define SMALL_STRING 16 /* ***************************************************************************** ** NUMERIC SORTS ** ***************************************************************************** */ /**begin repeat * * #TYPE = BOOL, BYTE, UBYTE, SHORT, USHORT, INT, UINT, LONG, ULONG, * LONGLONG, ULONGLONG, HALF, FLOAT, DOUBLE, LONGDOUBLE, * CFLOAT, CDOUBLE, CLONGDOUBLE# * #suff = bool, byte, ubyte, short, ushort, int, uint, long, ulong, * longlong, ulonglong, half, float, double, longdouble, * cfloat, cdouble, clongdouble# * #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# */ static void mergesort0_@suff@(@type@ *pl, @type@ *pr, @type@ *pw) { @type@ vp, *pi, *pj, *pk, *pm; if (pr - pl > SMALL_MERGESORT) { /* merge sort */ pm = pl + ((pr - pl) >> 1); mergesort0_@suff@(pl, pm, pw); mergesort0_@suff@(pm, pr, pw); for (pi = pw, pj = pl; pj < pm;) { *pi++ = *pj++; } pi = pw + (pm - pl); pj = pw; pk = pl; while (pj < pi && pm < pr) { if (@TYPE@_LT(*pm, *pj)) { *pk++ = *pm++; } else { *pk++ = *pj++; } } while(pj < pi) { *pk++ = *pj++; } } else { /* insertion sort */ for (pi = pl + 1; pi < pr; ++pi) { vp = *pi; pj = pi; pk = pi - 1; while (pj > pl && @TYPE@_LT(vp, *pk)) { *pj-- = *pk--; } *pj = vp; } } } int mergesort_@suff@(@type@ *start, npy_intp num, void *NOT_USED) { @type@ *pl, *pr, *pw; pl = start; pr = pl + num; pw = (@type@ *) malloc((num/2) * sizeof(@type@)); if (pw == NULL) { return -NPY_ENOMEM; } mergesort0_@suff@(pl, pr, pw); free(pw); return 0; } static void amergesort0_@suff@(npy_intp *pl, npy_intp *pr, @type@ *v, npy_intp *pw) { @type@ vp; npy_intp vi, *pi, *pj, *pk, *pm; if (pr - pl > SMALL_MERGESORT) { /* merge sort */ pm = pl + ((pr - pl) >> 1); amergesort0_@suff@(pl, pm, v, pw); amergesort0_@suff@(pm, pr, v, pw); for (pi = pw, pj = pl; pj < pm;) { *pi++ = *pj++; } pi = pw + (pm - pl); pj = pw; pk = pl; while (pj < pi && pm < pr) { if (@TYPE@_LT(v[*pm], v[*pj])) { *pk++ = *pm++; } else { *pk++ = *pj++; } } while(pj < pi) { *pk++ = *pj++; } } else { /* insertion sort */ for (pi = pl + 1; pi < pr; ++pi) { vi = *pi; vp = v[vi]; pj = pi; pk = pi - 1; while (pj > pl && @TYPE@_LT(vp, v[*pk])) { *pj-- = *pk--; } *pj = vi; } } } int amergesort_@suff@(@type@ *v, npy_intp *tosort, npy_intp num, void *NOT_USED) { npy_intp *pl, *pr, *pw; pl = tosort; pr = pl + num; pw = (npy_intp *) malloc((num/2) * sizeof(npy_intp)); if (pw == NULL) { return -NPY_ENOMEM; } amergesort0_@suff@(pl, pr, v, pw); free(pw); return 0; } /**end repeat**/ /* ***************************************************************************** ** STRING SORTS ** ***************************************************************************** */ /**begin repeat * * #TYPE = STRING, UNICODE# * #suff = string, unicode# * #type = npy_char, npy_ucs4# */ static void mergesort0_@suff@(@type@ *pl, @type@ *pr, @type@ *pw, @type@ *vp, size_t len) { @type@ *pi, *pj, *pk, *pm; if ((size_t)(pr - pl) > SMALL_MERGESORT*len) { /* merge sort */ pm = pl + (((pr - pl)/len) >> 1)*len; mergesort0_@suff@(pl, pm, pw, vp, len); mergesort0_@suff@(pm, pr, pw, vp, len); @TYPE@_COPY(pw, pl, pm - pl); pi = pw + (pm - pl); pj = pw; pk = pl; while (pj < pi && pm < pr) { if (@TYPE@_LT(pm, pj, len)) { @TYPE@_COPY(pk, pm, len); pm += len; pk += len; } else { @TYPE@_COPY(pk, pj, len); pj += len; pk += len; } } @TYPE@_COPY(pk, pj, pi - pj); } else { /* insertion sort */ for (pi = pl + len; pi < pr; pi += len) { @TYPE@_COPY(vp, pi, len); pj = pi; pk = pi - len; while (pj > pl && @TYPE@_LT(vp, pk, len)) { @TYPE@_COPY(pj, pk, len); pj -= len; pk -= len; } @TYPE@_COPY(pj, vp, len); } } } int mergesort_@suff@(@type@ *start, npy_intp num, PyArrayObject *arr) { size_t elsize = PyArray_ITEMSIZE(arr); size_t len = elsize / sizeof(@type@); @type@ *pl, *pr, *pw, *vp; int err = 0; pl = start; pr = pl + num*len; pw = (@type@ *) malloc((num/2) * elsize); if (pw == NULL) { err = -NPY_ENOMEM; goto fail_0; } vp = (@type@ *) malloc(elsize); if (vp == NULL) { err = -NPY_ENOMEM; goto fail_1; } mergesort0_@suff@(pl, pr, pw, vp, len); free(vp); fail_1: free(pw); fail_0: return err; } static void amergesort0_@suff@(npy_intp *pl, npy_intp *pr, @type@ *v, npy_intp *pw, size_t len) { @type@ *vp; npy_intp vi, *pi, *pj, *pk, *pm; if (pr - pl > SMALL_MERGESORT) { /* merge sort */ pm = pl + ((pr - pl) >> 1); amergesort0_@suff@(pl, pm, v, pw, len); amergesort0_@suff@(pm, pr, v, pw, len); for (pi = pw, pj = pl; pj < pm;) { *pi++ = *pj++; } pi = pw + (pm - pl); pj = pw; pk = pl; while (pj < pi && pm < pr) { if (@TYPE@_LT(v + (*pm)*len, v + (*pj)*len, len)) { *pk++ = *pm++; } else { *pk++ = *pj++; } } while (pj < pi) { *pk++ = *pj++; } } else { /* insertion sort */ for (pi = pl + 1; pi < pr; ++pi) { vi = *pi; vp = v + vi*len; pj = pi; pk = pi - 1; while (pj > pl && @TYPE@_LT(vp, v + (*pk)*len, len)) { *pj-- = *pk--; } *pj = vi; } } } int amergesort_@suff@(@type@ *v, npy_intp *tosort, npy_intp num, PyArrayObject *arr) { size_t elsize = PyArray_ITEMSIZE(arr); size_t len = elsize / sizeof(@type@); npy_intp *pl, *pr, *pw; pl = tosort; pr = pl + num; pw = (npy_intp *) malloc((num/2) * sizeof(npy_intp)); if (pw == NULL) { return -NPY_ENOMEM; } amergesort0_@suff@(pl, pr, v, pw, len); free(pw); return 0; } /**end repeat**/ /* ***************************************************************************** ** GENERIC SORT ** ***************************************************************************** */ static void npy_mergesort0(char *pl, char *pr, char *pw, char *vp, size_t size, npy_comparator cmp) { char *pi, *pj, *pk, *pm; if ((size_t)(pr - pl) > SMALL_MERGESORT*size) { /* merge sort */ pm = pl + (((pr - pl)/size) >> 1)*size; npy_mergesort0(pl, pm, pw, vp, size, cmp); npy_mergesort0(pm, pr, pw, vp, size, cmp); GENERIC_COPY(pw, pl, pm - pl); pi = pw + (pm - pl); pj = pw; pk = pl; while (pj < pi && pm < pr) { if (GENERIC_LT(pm, pj, cmp)) { GENERIC_COPY(pk, pm, size); pm += size; pk += size; } else { GENERIC_COPY(pk, pj, size); pj += size; pk += size; } } GENERIC_COPY(pk, pj, pi - pj); } else { /* insertion sort */ for (pi = pl + size; pi < pr; pi += size) { GENERIC_COPY(vp, pi, size); pj = pi; pk = pi - size; while (pj > pl && GENERIC_LT(vp, pk, cmp)) { GENERIC_COPY(pj, pk, size); pj -= size; pk -= size; } GENERIC_COPY(pj, vp, size); } } } /* * This sort has almost the same signature as libc qsort and is intended to * provide a mergesort for array types that don't have type specific sorts. * The difference in the signature is an error return, as it might be the * case that a memory allocation fails. */ int npy_mergesort(void *base, size_t num, size_t size, npy_comparator cmp) { char *pl, *pr, *pw, *vp; int err = 0; pl = (char *)base; pr = pl + num*size; pw = (char *) malloc((num/2) * size); if (pw == NULL) { err = -NPY_ENOMEM; goto fail_0; } vp = (char *) malloc(size); if (vp == NULL) { err = -NPY_ENOMEM; goto fail_1; } npy_mergesort0(pl, pr, pw, vp, size, cmp); free(vp); fail_1: free(pw); fail_0: return err; } numpy-1.8.2/numpy/core/src/npymath/0000775000175100017510000000000012371375427020406 5ustar vagrantvagrant00000000000000numpy-1.8.2/numpy/core/src/npymath/ieee754.c.src0000664000175100017510000004417612370216243022510 0ustar vagrantvagrant00000000000000/* -*- c -*- */ /* * vim:syntax=c * * Low-level routines related to IEEE-754 format */ #include "npy_math_common.h" #include "npy_math_private.h" #ifndef HAVE_COPYSIGN double npy_copysign(double x, double y) { npy_uint32 hx, hy; GET_HIGH_WORD(hx, x); GET_HIGH_WORD(hy, y); SET_HIGH_WORD(x, (hx & 0x7fffffff) | (hy & 0x80000000)); return x; } #endif /* The below code is provided for compilers which do not yet provide C11 compatibility (gcc 4.5 and older) */ #ifndef LDBL_TRUE_MIN #define LDBL_TRUE_MIN __LDBL_DENORM_MIN__ #endif #if !defined(HAVE_DECL_SIGNBIT) #include "_signbit.c" int _npy_signbit_f(float x) { return _npy_signbit_d((double) x); } int _npy_signbit_ld(long double x) { return _npy_signbit_d((double) x); } #endif /* * FIXME: There is a lot of redundancy between _next* and npy_nextafter*. * refactor this at some point * * p >= 0, returnx x + nulp * p < 0, returnx x - nulp */ double _next(double x, int p) { volatile double t; npy_int32 hx, hy, ix; npy_uint32 lx; EXTRACT_WORDS(hx, lx, x); ix = hx & 0x7fffffff; /* |x| */ if (((ix >= 0x7ff00000) && ((ix - 0x7ff00000) | lx) != 0)) /* x is nan */ return x; if ((ix | lx) == 0) { /* x == 0 */ if (p >= 0) { INSERT_WORDS(x, 0x0, 1); /* return +minsubnormal */ } else { INSERT_WORDS(x, 0x80000000, 1); /* return -minsubnormal */ } t = x * x; if (t == x) return t; else return x; /* raise underflow flag */ } if (p < 0) { /* x -= ulp */ if (lx == 0) hx -= 1; lx -= 1; } else { /* x += ulp */ lx += 1; if (lx == 0) hx += 1; } hy = hx & 0x7ff00000; if (hy >= 0x7ff00000) return x + x; /* overflow */ if (hy < 0x00100000) { /* underflow */ t = x * x; if (t != x) { /* raise underflow flag */ INSERT_WORDS(x, hx, lx); return x; } } INSERT_WORDS(x, hx, lx); return x; } float _nextf(float x, int p) { volatile float t; npy_int32 hx, hy, ix; GET_FLOAT_WORD(hx, x); ix = hx & 0x7fffffff; /* |x| */ if ((ix > 0x7f800000)) /* x is nan */ return x; if (ix == 0) { /* x == 0 */ if (p >= 0) { SET_FLOAT_WORD(x, 0x0 | 1); /* return +minsubnormal */ } else { SET_FLOAT_WORD(x, 0x80000000 | 1); /* return -minsubnormal */ } t = x * x; if (t == x) return t; else return x; /* raise underflow flag */ } if (p < 0) { /* x -= ulp */ hx -= 1; } else { /* x += ulp */ hx += 1; } hy = hx & 0x7f800000; if (hy >= 0x7f800000) return x + x; /* overflow */ if (hy < 0x00800000) { /* underflow */ t = x * x; if (t != x) { /* raise underflow flag */ SET_FLOAT_WORD(x, hx); return x; } } SET_FLOAT_WORD(x, hx); return x; } #ifdef HAVE_LDOUBLE_DOUBLE_DOUBLE_BE /* * FIXME: this is ugly and untested. The asm part only works with gcc, and we * should consolidate the GET_LDOUBLE* / SET_LDOUBLE macros */ #define math_opt_barrier(x) \ ({ __typeof (x) __x = x; __asm ("" : "+m" (__x)); __x; }) #define math_force_eval(x) __asm __volatile ("" : : "m" (x)) /* only works for big endian */ typedef union { npy_longdouble value; struct { npy_uint64 msw; npy_uint64 lsw; } parts64; struct { npy_uint32 w0, w1, w2, w3; } parts32; } ieee854_long_double_shape_type; /* Get two 64 bit ints from a long double. */ #define GET_LDOUBLE_WORDS64(ix0,ix1,d) \ do { \ ieee854_long_double_shape_type qw_u; \ qw_u.value = (d); \ (ix0) = qw_u.parts64.msw; \ (ix1) = qw_u.parts64.lsw; \ } while (0) /* Set a long double from two 64 bit ints. */ #define SET_LDOUBLE_WORDS64(d,ix0,ix1) \ do { \ ieee854_long_double_shape_type qw_u; \ qw_u.parts64.msw = (ix0); \ qw_u.parts64.lsw = (ix1); \ (d) = qw_u.value; \ } while (0) npy_longdouble _nextl(npy_longdouble x, int p) { npy_int64 hx,ihx,ilx; npy_uint64 lx; GET_LDOUBLE_WORDS64(hx, lx, x); ihx = hx & 0x7fffffffffffffffLL; /* |hx| */ ilx = lx & 0x7fffffffffffffffLL; /* |lx| */ if(((ihx & 0x7ff0000000000000LL)==0x7ff0000000000000LL)&& ((ihx & 0x000fffffffffffffLL)!=0)) { return x; /* signal the nan */ } if(ihx == 0 && ilx == 0) { /* x == 0 */ npy_longdouble u; SET_LDOUBLE_WORDS64(x, p, 0ULL);/* return +-minsubnormal */ u = x * x; if (u == x) { return u; } else { return x; /* raise underflow flag */ } } npy_longdouble u; if(p < 0) { /* p < 0, x -= ulp */ if((hx==0xffefffffffffffffLL)&&(lx==0xfc8ffffffffffffeLL)) return x+x; /* overflow, return -inf */ if (hx >= 0x7ff0000000000000LL) { SET_LDOUBLE_WORDS64(u,0x7fefffffffffffffLL,0x7c8ffffffffffffeLL); return u; } if(ihx <= 0x0360000000000000LL) { /* x <= LDBL_MIN */ u = math_opt_barrier (x); x -= LDBL_TRUE_MIN; if (ihx < 0x0360000000000000LL || (hx > 0 && (npy_int64) lx <= 0) || (hx < 0 && (npy_int64) lx > 1)) { u = u * u; math_force_eval (u); /* raise underflow flag */ } return x; } if (ihx < 0x06a0000000000000LL) { /* ulp will denormal */ SET_LDOUBLE_WORDS64(u,(hx&0x7ff0000000000000LL),0ULL); u *= 0x1.0000000000000p-105L; } else SET_LDOUBLE_WORDS64(u,(hx&0x7ff0000000000000LL)-0x0690000000000000LL,0ULL); return x - u; } else { /* p >= 0, x += ulp */ if((hx==0x7fefffffffffffffLL)&&(lx==0x7c8ffffffffffffeLL)) return x+x; /* overflow, return +inf */ if ((npy_uint64) hx >= 0xfff0000000000000ULL) { SET_LDOUBLE_WORDS64(u,0xffefffffffffffffLL,0xfc8ffffffffffffeLL); return u; } if(ihx <= 0x0360000000000000LL) { /* x <= LDBL_MIN */ u = math_opt_barrier (x); x += LDBL_TRUE_MIN; if (ihx < 0x0360000000000000LL || (hx > 0 && (npy_int64) lx < 0 && lx != 0x8000000000000001LL) || (hx < 0 && (npy_int64) lx >= 0)) { u = u * u; math_force_eval (u); /* raise underflow flag */ } if (x == 0.0L) /* handle negative LDBL_TRUE_MIN case */ x = -0.0L; return x; } if (ihx < 0x06a0000000000000LL) { /* ulp will denormal */ SET_LDOUBLE_WORDS64(u,(hx&0x7ff0000000000000LL),0ULL); u *= 0x1.0000000000000p-105L; } else SET_LDOUBLE_WORDS64(u,(hx&0x7ff0000000000000LL)-0x0690000000000000LL,0ULL); return x + u; } } #else npy_longdouble _nextl(npy_longdouble x, int p) { volatile npy_longdouble t; union IEEEl2bitsrep ux; ux.e = x; if ((GET_LDOUBLE_EXP(ux) == 0x7fff && ((GET_LDOUBLE_MANH(ux) & ~LDBL_NBIT) | GET_LDOUBLE_MANL(ux)) != 0)) { return ux.e; /* x is nan */ } if (ux.e == 0.0) { SET_LDOUBLE_MANH(ux, 0); /* return +-minsubnormal */ SET_LDOUBLE_MANL(ux, 1); if (p >= 0) { SET_LDOUBLE_SIGN(ux, 0); } else { SET_LDOUBLE_SIGN(ux, 1); } t = ux.e * ux.e; if (t == ux.e) { return t; } else { return ux.e; /* raise underflow flag */ } } if (p < 0) { /* x -= ulp */ if (GET_LDOUBLE_MANL(ux) == 0) { if ((GET_LDOUBLE_MANH(ux) & ~LDBL_NBIT) == 0) { SET_LDOUBLE_EXP(ux, GET_LDOUBLE_EXP(ux) - 1); } SET_LDOUBLE_MANH(ux, (GET_LDOUBLE_MANH(ux) - 1) | (GET_LDOUBLE_MANH(ux) & LDBL_NBIT)); } SET_LDOUBLE_MANL(ux, GET_LDOUBLE_MANL(ux) - 1); } else { /* x += ulp */ SET_LDOUBLE_MANL(ux, GET_LDOUBLE_MANL(ux) + 1); if (GET_LDOUBLE_MANL(ux) == 0) { SET_LDOUBLE_MANH(ux, (GET_LDOUBLE_MANH(ux) + 1) | (GET_LDOUBLE_MANH(ux) & LDBL_NBIT)); if ((GET_LDOUBLE_MANH(ux) & ~LDBL_NBIT) == 0) { SET_LDOUBLE_EXP(ux, GET_LDOUBLE_EXP(ux) + 1); } } } if (GET_LDOUBLE_EXP(ux) == 0x7fff) { return ux.e + ux.e; /* overflow */ } if (GET_LDOUBLE_EXP(ux) == 0) { /* underflow */ if (LDBL_NBIT) { SET_LDOUBLE_MANH(ux, GET_LDOUBLE_MANH(ux) & ~LDBL_NBIT); } t = ux.e * ux.e; if (t != ux.e) { /* raise underflow flag */ return ux.e; } } return ux.e; } #endif /* * nextafter code taken from BSD math lib, the code contains the following * notice: * * ==================================================== * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. * * Developed at SunPro, a Sun Microsystems, Inc. business. * Permission to use, copy, modify, and distribute this * software is freely granted, provided that this notice * is preserved. * ==================================================== */ #ifndef HAVE_NEXTAFTER double npy_nextafter(double x, double y) { volatile double t; npy_int32 hx, hy, ix, iy; npy_uint32 lx, ly; EXTRACT_WORDS(hx, lx, x); EXTRACT_WORDS(hy, ly, y); ix = hx & 0x7fffffff; /* |x| */ iy = hy & 0x7fffffff; /* |y| */ if (((ix >= 0x7ff00000) && ((ix - 0x7ff00000) | lx) != 0) || /* x is nan */ ((iy >= 0x7ff00000) && ((iy - 0x7ff00000) | ly) != 0)) /* y is nan */ return x + y; if (x == y) return y; /* x=y, return y */ if ((ix | lx) == 0) { /* x == 0 */ INSERT_WORDS(x, hy & 0x80000000, 1); /* return +-minsubnormal */ t = x * x; if (t == x) return t; else return x; /* raise underflow flag */ } if (hx >= 0) { /* x > 0 */ if (hx > hy || ((hx == hy) && (lx > ly))) { /* x > y, x -= ulp */ if (lx == 0) hx -= 1; lx -= 1; } else { /* x < y, x += ulp */ lx += 1; if (lx == 0) hx += 1; } } else { /* x < 0 */ if (hy >= 0 || hx > hy || ((hx == hy) && (lx > ly))) { /* x < y, x -= ulp */ if (lx == 0) hx -= 1; lx -= 1; } else { /* x > y, x += ulp */ lx += 1; if (lx == 0) hx += 1; } } hy = hx & 0x7ff00000; if (hy >= 0x7ff00000) return x + x; /* overflow */ if (hy < 0x00100000) { /* underflow */ t = x * x; if (t != x) { /* raise underflow flag */ INSERT_WORDS(y, hx, lx); return y; } } INSERT_WORDS(x, hx, lx); return x; } #endif #ifndef HAVE_NEXTAFTERF float npy_nextafterf(float x, float y) { volatile float t; npy_int32 hx, hy, ix, iy; GET_FLOAT_WORD(hx, x); GET_FLOAT_WORD(hy, y); ix = hx & 0x7fffffff; /* |x| */ iy = hy & 0x7fffffff; /* |y| */ if ((ix > 0x7f800000) || /* x is nan */ (iy > 0x7f800000)) /* y is nan */ return x + y; if (x == y) return y; /* x=y, return y */ if (ix == 0) { /* x == 0 */ SET_FLOAT_WORD(x, (hy & 0x80000000) | 1); /* return +-minsubnormal */ t = x * x; if (t == x) return t; else return x; /* raise underflow flag */ } if (hx >= 0) { /* x > 0 */ if (hx > hy) { /* x > y, x -= ulp */ hx -= 1; } else { /* x < y, x += ulp */ hx += 1; } } else { /* x < 0 */ if (hy >= 0 || hx > hy) { /* x < y, x -= ulp */ hx -= 1; } else { /* x > y, x += ulp */ hx += 1; } } hy = hx & 0x7f800000; if (hy >= 0x7f800000) return x + x; /* overflow */ if (hy < 0x00800000) { /* underflow */ t = x * x; if (t != x) { /* raise underflow flag */ SET_FLOAT_WORD(y, hx); return y; } } SET_FLOAT_WORD(x, hx); return x; } #endif #ifndef HAVE_NEXTAFTERL npy_longdouble npy_nextafterl(npy_longdouble x, npy_longdouble y) { volatile npy_longdouble t; union IEEEl2bitsrep ux; union IEEEl2bitsrep uy; ux.e = x; uy.e = y; if ((GET_LDOUBLE_EXP(ux) == 0x7fff && ((GET_LDOUBLE_MANH(ux) & ~LDBL_NBIT) | GET_LDOUBLE_MANL(ux)) != 0) || (GET_LDOUBLE_EXP(uy) == 0x7fff && ((GET_LDOUBLE_MANH(uy) & ~LDBL_NBIT) | GET_LDOUBLE_MANL(uy)) != 0)) { return ux.e + uy.e; /* x or y is nan */ } if (ux.e == uy.e) { return uy.e; /* x=y, return y */ } if (ux.e == 0.0) { SET_LDOUBLE_MANH(ux, 0); /* return +-minsubnormal */ SET_LDOUBLE_MANL(ux, 1); SET_LDOUBLE_SIGN(ux, GET_LDOUBLE_SIGN(uy)); t = ux.e * ux.e; if (t == ux.e) { return t; } else { return ux.e; /* raise underflow flag */ } } if ((ux.e > 0.0) ^ (ux.e < uy.e)) { /* x -= ulp */ if (GET_LDOUBLE_MANL(ux) == 0) { if ((GET_LDOUBLE_MANH(ux) & ~LDBL_NBIT) == 0) { SET_LDOUBLE_EXP(ux, GET_LDOUBLE_EXP(ux) - 1); } SET_LDOUBLE_MANH(ux, (GET_LDOUBLE_MANH(ux) - 1) | (GET_LDOUBLE_MANH(ux) & LDBL_NBIT)); } SET_LDOUBLE_MANL(ux, GET_LDOUBLE_MANL(ux) - 1); } else { /* x += ulp */ SET_LDOUBLE_MANL(ux, GET_LDOUBLE_MANL(ux) + 1); if (GET_LDOUBLE_MANL(ux) == 0) { SET_LDOUBLE_MANH(ux, (GET_LDOUBLE_MANH(ux) + 1) | (GET_LDOUBLE_MANH(ux) & LDBL_NBIT)); if ((GET_LDOUBLE_MANH(ux) & ~LDBL_NBIT) == 0) { SET_LDOUBLE_EXP(ux, GET_LDOUBLE_EXP(ux) + 1); } } } if (GET_LDOUBLE_EXP(ux) == 0x7fff) { return ux.e + ux.e; /* overflow */ } if (GET_LDOUBLE_EXP(ux) == 0) { /* underflow */ if (LDBL_NBIT) { SET_LDOUBLE_MANH(ux, GET_LDOUBLE_MANH(ux) & ~LDBL_NBIT); } t = ux.e * ux.e; if (t != ux.e) { /* raise underflow flag */ return ux.e; } } return ux.e; } #endif /**begin repeat * #suff = f,,l# * #SUFF = F,,L# * #type = npy_float, npy_double, npy_longdouble# */ @type@ npy_spacing@suff@(@type@ x) { /* XXX: npy isnan/isinf may be optimized by bit twiddling */ if (npy_isinf(x)) { return NPY_NAN@SUFF@; } return _next@suff@(x, 1) - x; } /**end repeat**/ /* * Decorate all the math functions which are available on the current platform */ #ifdef HAVE_NEXTAFTERF float npy_nextafterf(float x, float y) { return nextafterf(x, y); } #endif #ifdef HAVE_NEXTAFTER double npy_nextafter(double x, double y) { return nextafter(x, y); } #endif #ifdef HAVE_NEXTAFTERL npy_longdouble npy_nextafterl(npy_longdouble x, npy_longdouble y) { return nextafterl(x, y); } #endif /* * Functions to set the floating point status word. */ #if defined(sun) || defined(__BSD__) || defined(__OpenBSD__) || \ (defined(__FreeBSD__) && (__FreeBSD_version < 502114)) || \ defined(__NetBSD__) #include void npy_set_floatstatus_divbyzero(void) { fpsetsticky(FP_X_DZ); } void npy_set_floatstatus_overflow(void) { fpsetsticky(FP_X_OFL); } void npy_set_floatstatus_underflow(void) { fpsetsticky(FP_X_UFL); } void npy_set_floatstatus_invalid(void) { fpsetsticky(FP_X_INV); } #elif defined(__GLIBC__) || defined(__APPLE__) || \ defined(__CYGWIN__) || defined(__MINGW32__) || \ (defined(__FreeBSD__) && (__FreeBSD_version >= 502114)) # if defined(__GLIBC__) || defined(__APPLE__) || \ defined(__MINGW32__) || defined(__FreeBSD__) # include # elif defined(__CYGWIN__) # include "numpy/fenv/fenv.h" # endif void npy_set_floatstatus_divbyzero(void) { feraiseexcept(FE_DIVBYZERO); } void npy_set_floatstatus_overflow(void) { feraiseexcept(FE_OVERFLOW); } void npy_set_floatstatus_underflow(void) { feraiseexcept(FE_UNDERFLOW); } void npy_set_floatstatus_invalid(void) { feraiseexcept(FE_INVALID); } #elif defined(_AIX) #include #include void npy_set_floatstatus_divbyzero(void) { fp_raise_xcp(FP_DIV_BY_ZERO); } void npy_set_floatstatus_overflow(void) { fp_raise_xcp(FP_OVERFLOW); } void npy_set_floatstatus_underflow(void) { fp_raise_xcp(FP_UNDERFLOW); } void npy_set_floatstatus_invalid(void) { fp_raise_xcp(FP_INVALID); } #else /* * By using a volatile floating point value, * the compiler is forced to actually do the requested * operations because of potential concurrency. * * We shouldn't write multiple values to a single * global here, because that would cause * a race condition. */ static volatile double _npy_floatstatus_x, _npy_floatstatus_zero = 0.0, _npy_floatstatus_big = 1e300, _npy_floatstatus_small = 1e-300, _npy_floatstatus_inf; void npy_set_floatstatus_divbyzero(void) { _npy_floatstatus_x = 1.0 / _npy_floatstatus_zero; } void npy_set_floatstatus_overflow(void) { _npy_floatstatus_x = _npy_floatstatus_big * 1e300; } void npy_set_floatstatus_underflow(void) { _npy_floatstatus_x = _npy_floatstatus_small * 1e-300; } void npy_set_floatstatus_invalid(void) { _npy_floatstatus_inf = NPY_INFINITY; _npy_floatstatus_x = _npy_floatstatus_inf - NPY_INFINITY; } #endif numpy-1.8.2/numpy/core/src/npymath/npy_math_common.h0000664000175100017510000000026112370216242023731 0ustar vagrantvagrant00000000000000/* * Common headers needed by every npy math compilation unit */ #include #include #include #include "npy_config.h" #include "numpy/npy_math.h" numpy-1.8.2/numpy/core/src/npymath/npy_math.c.src0000664000175100017510000002603312370216243023150 0ustar vagrantvagrant00000000000000/* * vim:syntax=c * A small module to implement missing C99 math capabilities required by numpy * * Please keep this independant of python ! Only basic types (npy_longdouble) * can be used, otherwise, pure C, without any use of Python facilities * * How to add a function to this section * ------------------------------------- * * Say you want to add `foo`, these are the steps and the reasons for them. * * 1) Add foo to the appropriate list in the configuration system. The * lists can be found in numpy/core/setup.py lines 63-105. Read the * comments that come with them, they are very helpful. * * 2) The configuration system will define a macro HAVE_FOO if your function * can be linked from the math library. The result can depend on the * optimization flags as well as the compiler, so can't be known ahead of * time. If the function can't be linked, then either it is absent, defined * as a macro, or is an intrinsic (hardware) function. * * i) Undefine any possible macros: * * #ifdef foo * #undef foo * #endif * * ii) Avoid as much as possible to declare any function here. Declaring * functions is not portable: some platforms define some function inline * with a non standard identifier, for example, or may put another * idendifier which changes the calling convention of the function. If you * really have to, ALWAYS declare it for the one platform you are dealing * with: * * Not ok: * double exp(double a); * * Ok: * #ifdef SYMBOL_DEFINED_WEIRD_PLATFORM * double exp(double); * #endif * * Some of the code is taken from msun library in FreeBSD, with the following * notice: * * ==================================================== * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. * * Developed at SunPro, a Sun Microsystems, Inc. business. * Permission to use, copy, modify, and distribute this * software is freely granted, provided that this notice * is preserved. * ==================================================== */ #include "npy_math_private.h" /* ***************************************************************************** ** BASIC MATH FUNCTIONS ** ***************************************************************************** */ /* Original code by Konrad Hinsen. */ #ifndef HAVE_EXPM1 double npy_expm1(double x) { if (npy_isinf(x) && x > 0) { return x; } 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 #ifndef HAVE_LOG1P double npy_log1p(double x) { if (npy_isinf(x) && x > 0) { return x; } else { const double u = 1. + x; const double d = u - 1.; if (d == 0) { return x; } else { return npy_log(u) * x / d; } } } #endif /* Taken from FreeBSD mlib, adapted for numpy * * XXX: we could be a bit faster by reusing high/low words for inf/nan * classification instead of calling npy_isinf/npy_isnan: we should have some * macros for this, though, instead of doing it manually */ #ifndef HAVE_ATAN2 /* XXX: we should have this in npy_math.h */ #define NPY_DBL_EPSILON 1.2246467991473531772E-16 double npy_atan2(double y, double x) { npy_int32 k, m, iy, ix, hx, hy; npy_uint32 lx,ly; double z; EXTRACT_WORDS(hx, lx, x); ix = hx & 0x7fffffff; EXTRACT_WORDS(hy, ly, y); iy = hy & 0x7fffffff; /* if x or y is nan, return nan */ if (npy_isnan(x * y)) { return x + y; } if (x == 1.0) { return npy_atan(y); } m = 2 * npy_signbit(x) + npy_signbit(y); if (y == 0.0) { switch(m) { case 0: case 1: return y; /* atan(+-0,+anything)=+-0 */ case 2: return NPY_PI;/* atan(+0,-anything) = pi */ case 3: return -NPY_PI;/* atan(-0,-anything) =-pi */ } } if (x == 0.0) { return y > 0 ? NPY_PI_2 : -NPY_PI_2; } if (npy_isinf(x)) { if (npy_isinf(y)) { switch(m) { case 0: return NPY_PI_4;/* atan(+INF,+INF) */ case 1: return -NPY_PI_4;/* atan(-INF,+INF) */ case 2: return 3.0*NPY_PI_4;/*atan(+INF,-INF)*/ case 3: return -3.0*NPY_PI_4;/*atan(-INF,-INF)*/ } } else { switch(m) { case 0: return NPY_PZERO; /* atan(+...,+INF) */ case 1: return NPY_NZERO; /* atan(-...,+INF) */ case 2: return NPY_PI; /* atan(+...,-INF) */ case 3: return -NPY_PI; /* atan(-...,-INF) */ } } } if (npy_isinf(y)) { return y > 0 ? NPY_PI_2 : -NPY_PI_2; } /* compute y/x */ k = (iy - ix) >> 20; if (k > 60) { /* |y/x| > 2**60 */ z = NPY_PI_2 + 0.5 * NPY_DBL_EPSILON; m &= 1; } else if (hx < 0 && k < -60) { z = 0.0; /* 0 > |y|/x > -2**-60 */ } else { z = npy_atan(npy_fabs(y/x)); /* safe to do y/x */ } switch (m) { case 0: return z ; /* atan(+,+) */ case 1: return -z ; /* atan(-,+) */ case 2: return NPY_PI - (z - NPY_DBL_EPSILON);/* atan(+,-) */ default: /* case 3 */ return (z - NPY_DBL_EPSILON) - NPY_PI;/* atan(-,-) */ } } #endif #ifndef HAVE_HYPOT double npy_hypot(double x, double y) { double yx; if (npy_isinf(x) || npy_isinf(y)) { return NPY_INFINITY; } if (npy_isnan(x) || npy_isnan(y)) { return NPY_NAN; } x = npy_fabs(x); y = npy_fabs(y); if (x < y) { double temp = x; x = y; y = temp; } if (x == 0.) { return 0.; } else { yx = y/x; return x*npy_sqrt(1.+yx*yx); } } #endif #ifndef HAVE_ACOSH double npy_acosh(double x) { return 2*npy_log(npy_sqrt((x + 1.0)/2) + npy_sqrt((x - 1.0)/2)); } #endif #ifndef HAVE_ASINH double npy_asinh(double xx) { double x, d; int sign; if (xx < 0.0) { sign = -1; x = -xx; } else { sign = 1; x = xx; } if (x > 1e8) { d = x; } else { d = npy_sqrt(x*x + 1); } return sign*npy_log1p(x*(1.0 + x/(d+1))); } #endif #ifndef HAVE_ATANH double npy_atanh(double x) { if (x > 0) { return -0.5*npy_log1p(-2.0*x/(1.0 + x)); } else { return 0.5*npy_log1p(2.0*x/(1.0 - x)); } } #endif #ifndef HAVE_RINT double npy_rint(double x) { double y, r; y = npy_floor(x); r = x - y; if (r > 0.5) { y += 1.0; } /* Round to nearest even */ if (r == 0.5) { r = y - 2.0*npy_floor(0.5*y); if (r == 1.0) { y += 1.0; } } return y; } #endif #ifndef HAVE_TRUNC double npy_trunc(double x) { return x < 0 ? npy_ceil(x) : npy_floor(x); } #endif #ifndef HAVE_EXP2 double npy_exp2(double x) { return npy_exp(NPY_LOGE2*x); } #endif #ifndef HAVE_LOG2 double npy_log2(double x) { return NPY_LOG2E*npy_log(x); } #endif /* * if C99 extensions not available then define dummy functions that use the * double versions for * * sin, cos, tan * sinh, cosh, tanh, * fabs, floor, ceil, rint, trunc * sqrt, log10, log, exp, expm1 * asin, acos, atan, * asinh, acosh, atanh * * hypot, atan2, pow, fmod, modf * * We assume the above are always available in their double versions. * * NOTE: some facilities may be available as macro only instead of functions. * For simplicity, we define our own functions and undef the macros. We could * instead test for the macro, but I am lazy to do that for now. */ /**begin repeat * #type = npy_longdouble, npy_float# * #TYPE = NPY_LONGDOUBLE, FLOAT# * #c = l,f# * #C = L,F# */ /**begin repeat1 * #kind = sin,cos,tan,sinh,cosh,tanh,fabs,floor,ceil,rint,trunc,sqrt,log10, * log,exp,expm1,asin,acos,atan,asinh,acosh,atanh,log1p,exp2,log2# * #KIND = SIN,COS,TAN,SINH,COSH,TANH,FABS,FLOOR,CEIL,RINT,TRUNC,SQRT,LOG10, * LOG,EXP,EXPM1,ASIN,ACOS,ATAN,ASINH,ACOSH,ATANH,LOG1P,EXP2,LOG2# */ #ifdef @kind@@c@ #undef @kind@@c@ #endif #ifndef HAVE_@KIND@@C@ @type@ npy_@kind@@c@(@type@ x) { return (@type@) npy_@kind@((double)x); } #endif /**end repeat1**/ /**begin repeat1 * #kind = atan2,hypot,pow,fmod,copysign# * #KIND = ATAN2,HYPOT,POW,FMOD,COPYSIGN# */ #ifdef @kind@@c@ #undef @kind@@c@ #endif #ifndef HAVE_@KIND@@C@ @type@ npy_@kind@@c@(@type@ x, @type@ y) { return (@type@) npy_@kind@((double)x, (double) y); } #endif /**end repeat1**/ #ifdef modf@c@ #undef modf@c@ #endif #ifndef HAVE_MODF@C@ @type@ npy_modf@c@(@type@ x, @type@ *iptr) { double niptr; double y = npy_modf((double)x, &niptr); *iptr = (@type@) niptr; return (@type@) y; } #endif /**end repeat**/ /* * Decorate all the math functions which are available on the current platform */ /**begin repeat * #type = npy_longdouble, npy_double, npy_float# * #c = l,,f# * #C = L,,F# */ /**begin repeat1 * #kind = sin,cos,tan,sinh,cosh,tanh,fabs,floor,ceil,rint,trunc,sqrt,log10, * log,exp,expm1,asin,acos,atan,asinh,acosh,atanh,log1p,exp2,log2# * #KIND = SIN,COS,TAN,SINH,COSH,TANH,FABS,FLOOR,CEIL,RINT,TRUNC,SQRT,LOG10, * LOG,EXP,EXPM1,ASIN,ACOS,ATAN,ASINH,ACOSH,ATANH,LOG1P,EXP2,LOG2# */ #ifdef HAVE_@KIND@@C@ @type@ npy_@kind@@c@(@type@ x) { return @kind@@c@(x); } #endif /**end repeat1**/ /**begin repeat1 * #kind = atan2,hypot,pow,fmod,copysign# * #KIND = ATAN2,HYPOT,POW,FMOD,COPYSIGN# */ #ifdef HAVE_@KIND@@C@ @type@ npy_@kind@@c@(@type@ x, @type@ y) { return @kind@@c@(x, y); } #endif /**end repeat1**/ #ifdef HAVE_MODF@C@ @type@ npy_modf@c@(@type@ x, @type@ *iptr) { return modf@c@(x, iptr); } #endif /**end repeat**/ /* * Non standard functions */ /**begin repeat * #type = npy_float, npy_double, npy_longdouble# * #c = f, ,l# * #C = F, ,L# */ #define LOGE2 NPY_LOGE2@c@ #define LOG2E NPY_LOG2E@c@ #define RAD2DEG (180.0@c@/NPY_PI@c@) #define DEG2RAD (NPY_PI@c@/180.0@c@) @type@ npy_rad2deg@c@(@type@ x) { return x*RAD2DEG; } @type@ npy_deg2rad@c@(@type@ x) { return x*DEG2RAD; } @type@ npy_log2_1p@c@(@type@ x) { return LOG2E*npy_log1p@c@(x); } @type@ npy_exp2_m1@c@(@type@ x) { return npy_expm1@c@(LOGE2*x); } @type@ npy_logaddexp@c@(@type@ x, @type@ y) { const @type@ tmp = x - y; if (tmp > 0) { return x + npy_log1p@c@(npy_exp@c@(-tmp)); } else if (tmp <= 0) { return y + npy_log1p@c@(npy_exp@c@(tmp)); } else { /* NaNs, or infinities of the same sign involved */ return x + y; } } @type@ npy_logaddexp2@c@(@type@ x, @type@ y) { const @type@ tmp = x - y; if (tmp > 0) { return x + npy_log2_1p@c@(npy_exp2@c@(-tmp)); } else if (tmp <= 0) { return y + npy_log2_1p@c@(npy_exp2@c@(tmp)); } else { /* NaNs, or infinities of the same sign involved */ return x + y; } } #undef LOGE2 #undef LOG2E #undef RAD2DEG #undef DEG2RAD /**end repeat**/ numpy-1.8.2/numpy/core/src/npymath/halffloat.c0000664000175100017510000003662712370216242022514 0ustar vagrantvagrant00000000000000#define NPY_NO_DEPRECATED_API NPY_API_VERSION #include "numpy/halffloat.h" /* * This chooses between 'ties to even' and 'ties away from zero'. */ #define NPY_HALF_ROUND_TIES_TO_EVEN 1 /* * If these are 1, the conversions try to trigger underflow, * overflow, and invalid exceptions in the FP system when needed. */ #define NPY_HALF_GENERATE_OVERFLOW 1 #define NPY_HALF_GENERATE_UNDERFLOW 1 #define NPY_HALF_GENERATE_INVALID 1 /* ******************************************************************** * HALF-PRECISION ROUTINES * ******************************************************************** */ float npy_half_to_float(npy_half h) { union { float ret; npy_uint32 retbits; } conv; conv.retbits = npy_halfbits_to_floatbits(h); return conv.ret; } double npy_half_to_double(npy_half h) { union { double ret; npy_uint64 retbits; } conv; conv.retbits = npy_halfbits_to_doublebits(h); return conv.ret; } npy_half npy_float_to_half(float f) { union { float f; npy_uint32 fbits; } conv; conv.f = f; return npy_floatbits_to_halfbits(conv.fbits); } npy_half npy_double_to_half(double d) { union { double d; npy_uint64 dbits; } conv; conv.d = d; return npy_doublebits_to_halfbits(conv.dbits); } int npy_half_iszero(npy_half h) { return (h&0x7fff) == 0; } int npy_half_isnan(npy_half h) { return ((h&0x7c00u) == 0x7c00u) && ((h&0x03ffu) != 0x0000u); } int npy_half_isinf(npy_half h) { return ((h&0x7fffu) == 0x7c00u); } int npy_half_isfinite(npy_half h) { return ((h&0x7c00u) != 0x7c00u); } int npy_half_signbit(npy_half h) { return (h&0x8000u) != 0; } npy_half npy_half_spacing(npy_half h) { npy_half ret; npy_uint16 h_exp = h&0x7c00u; npy_uint16 h_sig = h&0x03ffu; if (h_exp == 0x7c00u) { #if NPY_HALF_GENERATE_INVALID npy_set_floatstatus_invalid(); #endif ret = NPY_HALF_NAN; } else if (h == 0x7bffu) { #if NPY_HALF_GENERATE_OVERFLOW npy_set_floatstatus_overflow(); #endif ret = NPY_HALF_PINF; } else if ((h&0x8000u) && h_sig == 0) { /* Negative boundary case */ if (h_exp > 0x2c00u) { /* If result is normalized */ ret = h_exp - 0x2c00u; } else if(h_exp > 0x0400u) { /* The result is a subnormal, but not the smallest */ ret = 1 << ((h_exp >> 10) - 2); } else { ret = 0x0001u; /* Smallest subnormal half */ } } else if (h_exp > 0x2800u) { /* If result is still normalized */ ret = h_exp - 0x2800u; } else if (h_exp > 0x0400u) { /* The result is a subnormal, but not the smallest */ ret = 1 << ((h_exp >> 10) - 1); } else { ret = 0x0001u; } return ret; } npy_half npy_half_copysign(npy_half x, npy_half y) { return (x&0x7fffu) | (y&0x8000u); } npy_half npy_half_nextafter(npy_half x, npy_half y) { npy_half ret; if (!npy_half_isfinite(x) || npy_half_isnan(y)) { #if NPY_HALF_GENERATE_INVALID npy_set_floatstatus_invalid(); #endif ret = NPY_HALF_NAN; } else if (npy_half_eq_nonan(x, y)) { ret = x; } else if (npy_half_iszero(x)) { ret = (y&0x8000u) + 1; /* Smallest subnormal half */ } else if (!(x&0x8000u)) { /* x > 0 */ if ((npy_int16)x > (npy_int16)y) { /* x > y */ ret = x-1; } else { ret = x+1; } } else { if (!(y&0x8000u) || (x&0x7fffu) > (y&0x7fffu)) { /* x < y */ ret = x-1; } else { ret = x+1; } } #if NPY_HALF_GENERATE_OVERFLOW if (npy_half_isinf(ret)) { npy_set_floatstatus_overflow(); } #endif return ret; } int npy_half_eq_nonan(npy_half h1, npy_half h2) { return (h1 == h2 || ((h1 | h2) & 0x7fff) == 0); } int npy_half_eq(npy_half h1, npy_half h2) { /* * The equality cases are as follows: * - If either value is NaN, never equal. * - If the values are equal, equal. * - If the values are both signed zeros, equal. */ return (!npy_half_isnan(h1) && !npy_half_isnan(h2)) && (h1 == h2 || ((h1 | h2) & 0x7fff) == 0); } int npy_half_ne(npy_half h1, npy_half h2) { return !npy_half_eq(h1, h2); } int npy_half_lt_nonan(npy_half h1, npy_half h2) { if (h1&0x8000u) { if (h2&0x8000u) { return (h1&0x7fffu) > (h2&0x7fffu); } else { /* Signed zeros are equal, have to check for it */ return (h1 != 0x8000u) || (h2 != 0x0000u); } } else { if (h2&0x8000u) { return 0; } else { return (h1&0x7fffu) < (h2&0x7fffu); } } } int npy_half_lt(npy_half h1, npy_half h2) { return (!npy_half_isnan(h1) && !npy_half_isnan(h2)) && npy_half_lt_nonan(h1, h2); } int npy_half_gt(npy_half h1, npy_half h2) { return npy_half_lt(h2, h1); } int npy_half_le_nonan(npy_half h1, npy_half h2) { if (h1&0x8000u) { if (h2&0x8000u) { return (h1&0x7fffu) >= (h2&0x7fffu); } else { return 1; } } else { if (h2&0x8000u) { /* Signed zeros are equal, have to check for it */ return (h1 == 0x0000u) && (h2 == 0x8000u); } else { return (h1&0x7fffu) <= (h2&0x7fffu); } } } int npy_half_le(npy_half h1, npy_half h2) { return (!npy_half_isnan(h1) && !npy_half_isnan(h2)) && npy_half_le_nonan(h1, h2); } int npy_half_ge(npy_half h1, npy_half h2) { return npy_half_le(h2, h1); } /* ******************************************************************** * BIT-LEVEL CONVERSIONS * ******************************************************************** */ npy_uint16 npy_floatbits_to_halfbits(npy_uint32 f) { npy_uint32 f_exp, f_sig; npy_uint16 h_sgn, h_exp, h_sig; h_sgn = (npy_uint16) ((f&0x80000000u) >> 16); f_exp = (f&0x7f800000u); /* Exponent overflow/NaN converts to signed inf/NaN */ if (f_exp >= 0x47800000u) { if (f_exp == 0x7f800000u) { /* Inf or NaN */ f_sig = (f&0x007fffffu); if (f_sig != 0) { /* NaN - propagate the flag in the significand... */ npy_uint16 ret = (npy_uint16) (0x7c00u + (f_sig >> 13)); /* ...but make sure it stays a NaN */ if (ret == 0x7c00u) { ret++; } return h_sgn + ret; } else { /* signed inf */ return (npy_uint16) (h_sgn + 0x7c00u); } } else { /* overflow to signed inf */ #if NPY_HALF_GENERATE_OVERFLOW npy_set_floatstatus_overflow(); #endif return (npy_uint16) (h_sgn + 0x7c00u); } } /* Exponent underflow converts to a subnormal half or signed zero */ if (f_exp <= 0x38000000u) { /* * Signed zeros, subnormal floats, and floats with small * exponents all convert to signed zero halfs. */ if (f_exp < 0x33000000u) { #if NPY_HALF_GENERATE_UNDERFLOW /* If f != 0, it underflowed to 0 */ if ((f&0x7fffffff) != 0) { npy_set_floatstatus_underflow(); } #endif return h_sgn; } /* Make the subnormal significand */ f_exp >>= 23; f_sig = (0x00800000u + (f&0x007fffffu)); #if NPY_HALF_GENERATE_UNDERFLOW /* If it's not exactly represented, it underflowed */ if ((f_sig&(((npy_uint32)1 << (126 - f_exp)) - 1)) != 0) { npy_set_floatstatus_underflow(); } #endif f_sig >>= (113 - f_exp); /* Handle rounding by adding 1 to the bit beyond half precision */ #if NPY_HALF_ROUND_TIES_TO_EVEN /* * If the last bit in the half significand is 0 (already even), and * the remaining bit pattern is 1000...0, then we do not add one * to the bit after the half significand. In all other cases, we do. */ if ((f_sig&0x00003fffu) != 0x00001000u) { f_sig += 0x00001000u; } #else f_sig += 0x00001000u; #endif h_sig = (npy_uint16) (f_sig >> 13); /* * If the rounding causes a bit to spill into h_exp, it will * increment h_exp from zero to one and h_sig will be zero. * This is the correct result. */ return (npy_uint16) (h_sgn + h_sig); } /* Regular case with no overflow or underflow */ h_exp = (npy_uint16) ((f_exp - 0x38000000u) >> 13); /* Handle rounding by adding 1 to the bit beyond half precision */ f_sig = (f&0x007fffffu); #if NPY_HALF_ROUND_TIES_TO_EVEN /* * If the last bit in the half significand is 0 (already even), and * the remaining bit pattern is 1000...0, then we do not add one * to the bit after the half significand. In all other cases, we do. */ if ((f_sig&0x00003fffu) != 0x00001000u) { f_sig += 0x00001000u; } #else f_sig += 0x00001000u; #endif h_sig = (npy_uint16) (f_sig >> 13); /* * If the rounding causes a bit to spill into h_exp, it will * increment h_exp by one and h_sig will be zero. This is the * correct result. h_exp may increment to 15, at greatest, in * which case the result overflows to a signed inf. */ #if NPY_HALF_GENERATE_OVERFLOW h_sig += h_exp; if (h_sig == 0x7c00u) { npy_set_floatstatus_overflow(); } return h_sgn + h_sig; #else return h_sgn + h_exp + h_sig; #endif } npy_uint16 npy_doublebits_to_halfbits(npy_uint64 d) { npy_uint64 d_exp, d_sig; npy_uint16 h_sgn, h_exp, h_sig; h_sgn = (d&0x8000000000000000ULL) >> 48; d_exp = (d&0x7ff0000000000000ULL); /* Exponent overflow/NaN converts to signed inf/NaN */ if (d_exp >= 0x40f0000000000000ULL) { if (d_exp == 0x7ff0000000000000ULL) { /* Inf or NaN */ d_sig = (d&0x000fffffffffffffULL); if (d_sig != 0) { /* NaN - propagate the flag in the significand... */ npy_uint16 ret = (npy_uint16) (0x7c00u + (d_sig >> 42)); /* ...but make sure it stays a NaN */ if (ret == 0x7c00u) { ret++; } return h_sgn + ret; } else { /* signed inf */ return h_sgn + 0x7c00u; } } else { /* overflow to signed inf */ #if NPY_HALF_GENERATE_OVERFLOW npy_set_floatstatus_overflow(); #endif return h_sgn + 0x7c00u; } } /* Exponent underflow converts to subnormal half or signed zero */ if (d_exp <= 0x3f00000000000000ULL) { /* * Signed zeros, subnormal floats, and floats with small * exponents all convert to signed zero halfs. */ if (d_exp < 0x3e60000000000000ULL) { #if NPY_HALF_GENERATE_UNDERFLOW /* If d != 0, it underflowed to 0 */ if ((d&0x7fffffffffffffffULL) != 0) { npy_set_floatstatus_underflow(); } #endif return h_sgn; } /* Make the subnormal significand */ d_exp >>= 52; d_sig = (0x0010000000000000ULL + (d&0x000fffffffffffffULL)); #if NPY_HALF_GENERATE_UNDERFLOW /* If it's not exactly represented, it underflowed */ if ((d_sig&(((npy_uint64)1 << (1051 - d_exp)) - 1)) != 0) { npy_set_floatstatus_underflow(); } #endif d_sig >>= (1009 - d_exp); /* Handle rounding by adding 1 to the bit beyond half precision */ #if NPY_HALF_ROUND_TIES_TO_EVEN /* * If the last bit in the half significand is 0 (already even), and * the remaining bit pattern is 1000...0, then we do not add one * to the bit after the half significand. In all other cases, we do. */ if ((d_sig&0x000007ffffffffffULL) != 0x0000020000000000ULL) { d_sig += 0x0000020000000000ULL; } #else d_sig += 0x0000020000000000ULL; #endif h_sig = (npy_uint16) (d_sig >> 42); /* * If the rounding causes a bit to spill into h_exp, it will * increment h_exp from zero to one and h_sig will be zero. * This is the correct result. */ return h_sgn + h_sig; } /* Regular case with no overflow or underflow */ h_exp = (npy_uint16) ((d_exp - 0x3f00000000000000ULL) >> 42); /* Handle rounding by adding 1 to the bit beyond half precision */ d_sig = (d&0x000fffffffffffffULL); #if NPY_HALF_ROUND_TIES_TO_EVEN /* * If the last bit in the half significand is 0 (already even), and * the remaining bit pattern is 1000...0, then we do not add one * to the bit after the half significand. In all other cases, we do. */ if ((d_sig&0x000007ffffffffffULL) != 0x0000020000000000ULL) { d_sig += 0x0000020000000000ULL; } #else d_sig += 0x0000020000000000ULL; #endif h_sig = (npy_uint16) (d_sig >> 42); /* * If the rounding causes a bit to spill into h_exp, it will * increment h_exp by one and h_sig will be zero. This is the * correct result. h_exp may increment to 15, at greatest, in * which case the result overflows to a signed inf. */ #if NPY_HALF_GENERATE_OVERFLOW h_sig += h_exp; if (h_sig == 0x7c00u) { npy_set_floatstatus_overflow(); } return h_sgn + h_sig; #else return h_sgn + h_exp + h_sig; #endif } npy_uint32 npy_halfbits_to_floatbits(npy_uint16 h) { npy_uint16 h_exp, h_sig; npy_uint32 f_sgn, f_exp, f_sig; h_exp = (h&0x7c00u); f_sgn = ((npy_uint32)h&0x8000u) << 16; switch (h_exp) { case 0x0000u: /* 0 or subnormal */ h_sig = (h&0x03ffu); /* Signed zero */ if (h_sig == 0) { return f_sgn; } /* Subnormal */ h_sig <<= 1; while ((h_sig&0x0400u) == 0) { h_sig <<= 1; h_exp++; } f_exp = ((npy_uint32)(127 - 15 - h_exp)) << 23; f_sig = ((npy_uint32)(h_sig&0x03ffu)) << 13; return f_sgn + f_exp + f_sig; case 0x7c00u: /* inf or NaN */ /* All-ones exponent and a copy of the significand */ return f_sgn + 0x7f800000u + (((npy_uint32)(h&0x03ffu)) << 13); default: /* normalized */ /* Just need to adjust the exponent and shift */ return f_sgn + (((npy_uint32)(h&0x7fffu) + 0x1c000u) << 13); } } npy_uint64 npy_halfbits_to_doublebits(npy_uint16 h) { npy_uint16 h_exp, h_sig; npy_uint64 d_sgn, d_exp, d_sig; h_exp = (h&0x7c00u); d_sgn = ((npy_uint64)h&0x8000u) << 48; switch (h_exp) { case 0x0000u: /* 0 or subnormal */ h_sig = (h&0x03ffu); /* Signed zero */ if (h_sig == 0) { return d_sgn; } /* Subnormal */ h_sig <<= 1; while ((h_sig&0x0400u) == 0) { h_sig <<= 1; h_exp++; } d_exp = ((npy_uint64)(1023 - 15 - h_exp)) << 52; d_sig = ((npy_uint64)(h_sig&0x03ffu)) << 42; return d_sgn + d_exp + d_sig; case 0x7c00u: /* inf or NaN */ /* All-ones exponent and a copy of the significand */ return d_sgn + 0x7ff0000000000000ULL + (((npy_uint64)(h&0x03ffu)) << 42); default: /* normalized */ /* Just need to adjust the exponent and shift */ return d_sgn + (((npy_uint64)(h&0x7fffu) + 0xfc000u) << 42); } } numpy-1.8.2/numpy/core/src/npymath/_signbit.c0000664000175100017510000000066612370216242022344 0ustar vagrantvagrant00000000000000/* Adapted from cephes */ int _npy_signbit_d(double x) { union { double d; short s[4]; int i[2]; } u; u.d = x; #if NPY_SIZEOF_INT == 4 #ifdef WORDS_BIGENDIAN /* defined in pyconfig.h */ return u.i[0] < 0; #else return u.i[1] < 0; #endif #else /* NPY_SIZEOF_INT != 4 */ #ifdef WORDS_BIGENDIAN return u.s[0] < 0; #else return u.s[3] < 0; #endif #endif /* NPY_SIZEOF_INT */ } numpy-1.8.2/numpy/core/src/npymath/npy_math_private.h0000664000175100017510000004023212370216243024116 0ustar vagrantvagrant00000000000000/* * * ==================================================== * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. * * Developed at SunPro, a Sun Microsystems, Inc. business. * Permission to use, copy, modify, and distribute this * software is freely granted, provided that this notice * is preserved. * ==================================================== */ /* * from: @(#)fdlibm.h 5.1 93/09/24 * $FreeBSD$ */ #ifndef _NPY_MATH_PRIVATE_H_ #define _NPY_MATH_PRIVATE_H_ #include #include #include "npy_config.h" #include "npy_fpmath.h" #include "numpy/npy_math.h" #include "numpy/npy_cpu.h" #include "numpy/npy_endian.h" #include "numpy/npy_common.h" /* * The original fdlibm code used statements like: * n0 = ((*(int*)&one)>>29)^1; * index of high word * * ix0 = *(n0+(int*)&x); * high word of x * * ix1 = *((1-n0)+(int*)&x); * low word of x * * to dig two 32 bit words out of the 64 bit IEEE floating point * value. That is non-ANSI, and, moreover, the gcc instruction * scheduler gets it wrong. We instead use the following macros. * Unlike the original code, we determine the endianness at compile * time, not at run time; I don't see much benefit to selecting * endianness at run time. */ /* * A union which permits us to convert between a double and two 32 bit * ints. */ /* XXX: not really, but we already make this assumption elsewhere. Will have to * fix this at some point */ #define IEEE_WORD_ORDER NPY_BYTE_ORDER #if IEEE_WORD_ORDER == NPY_BIG_ENDIAN typedef union { double value; struct { npy_uint32 msw; npy_uint32 lsw; } parts; } ieee_double_shape_type; #endif #if IEEE_WORD_ORDER == NPY_LITTLE_ENDIAN typedef union { double value; struct { npy_uint32 lsw; npy_uint32 msw; } parts; } ieee_double_shape_type; #endif /* Get two 32 bit ints from a double. */ #define EXTRACT_WORDS(ix0,ix1,d) \ do { \ ieee_double_shape_type ew_u; \ ew_u.value = (d); \ (ix0) = ew_u.parts.msw; \ (ix1) = ew_u.parts.lsw; \ } while (0) /* Get the more significant 32 bit int from a double. */ #define GET_HIGH_WORD(i,d) \ do { \ ieee_double_shape_type gh_u; \ gh_u.value = (d); \ (i) = gh_u.parts.msw; \ } while (0) /* Get the less significant 32 bit int from a double. */ #define GET_LOW_WORD(i,d) \ do { \ ieee_double_shape_type gl_u; \ gl_u.value = (d); \ (i) = gl_u.parts.lsw; \ } while (0) /* Set the more significant 32 bits of a double from an int. */ #define SET_HIGH_WORD(d,v) \ do { \ ieee_double_shape_type sh_u; \ sh_u.value = (d); \ sh_u.parts.msw = (v); \ (d) = sh_u.value; \ } while (0) /* Set the less significant 32 bits of a double from an int. */ #define SET_LOW_WORD(d,v) \ do { \ ieee_double_shape_type sl_u; \ sl_u.value = (d); \ sl_u.parts.lsw = (v); \ (d) = sl_u.value; \ } while (0) /* Set a double from two 32 bit ints. */ #define INSERT_WORDS(d,ix0,ix1) \ do { \ ieee_double_shape_type iw_u; \ iw_u.parts.msw = (ix0); \ iw_u.parts.lsw = (ix1); \ (d) = iw_u.value; \ } while (0) /* * A union which permits us to convert between a float and a 32 bit * int. */ typedef union { float value; /* FIXME: Assumes 32 bit int. */ npy_uint32 word; } ieee_float_shape_type; /* Get a 32 bit int from a float. */ #define GET_FLOAT_WORD(i,d) \ do { \ ieee_float_shape_type gf_u; \ gf_u.value = (d); \ (i) = gf_u.word; \ } while (0) /* Set a float from a 32 bit int. */ #define SET_FLOAT_WORD(d,i) \ do { \ ieee_float_shape_type sf_u; \ sf_u.word = (i); \ (d) = sf_u.value; \ } while (0) #ifdef NPY_USE_C99_COMPLEX #include #endif /* * Long double support */ #if defined(HAVE_LDOUBLE_INTEL_EXTENDED_12_BYTES_LE) /* * Intel extended 80 bits precision. Bit representation is * | junk | s |eeeeeeeeeeeeeee|mmmmmmmm................mmmmmmm| * | 16 bits| 1 bit | 15 bits | 64 bits | * | a[2] | a[1] | a[0] | * * 16 stronger bits of a[2] are junk */ typedef npy_uint32 IEEEl2bitsrep_part; union IEEEl2bitsrep { npy_longdouble e; IEEEl2bitsrep_part a[3]; }; #define LDBL_MANL_INDEX 0 #define LDBL_MANL_MASK 0xFFFFFFFF #define LDBL_MANL_SHIFT 0 #define LDBL_MANH_INDEX 1 #define LDBL_MANH_MASK 0xFFFFFFFF #define LDBL_MANH_SHIFT 0 #define LDBL_EXP_INDEX 2 #define LDBL_EXP_MASK 0x7FFF #define LDBL_EXP_SHIFT 0 #define LDBL_SIGN_INDEX 2 #define LDBL_SIGN_MASK 0x8000 #define LDBL_SIGN_SHIFT 15 #define LDBL_NBIT 0x80000000 typedef npy_uint32 ldouble_man_t; typedef npy_uint32 ldouble_exp_t; typedef npy_uint32 ldouble_sign_t; #elif defined(HAVE_LDOUBLE_INTEL_EXTENDED_16_BYTES_LE) /* * Intel extended 80 bits precision, 16 bytes alignment.. Bit representation is * | junk | s |eeeeeeeeeeeeeee|mmmmmmmm................mmmmmmm| * | 16 bits| 1 bit | 15 bits | 64 bits | * | a[2] | a[1] | a[0] | * * a[3] and 16 stronger bits of a[2] are junk */ typedef npy_uint32 IEEEl2bitsrep_part; union IEEEl2bitsrep { npy_longdouble e; IEEEl2bitsrep_part a[4]; }; #define LDBL_MANL_INDEX 0 #define LDBL_MANL_MASK 0xFFFFFFFF #define LDBL_MANL_SHIFT 0 #define LDBL_MANH_INDEX 1 #define LDBL_MANH_MASK 0xFFFFFFFF #define LDBL_MANH_SHIFT 0 #define LDBL_EXP_INDEX 2 #define LDBL_EXP_MASK 0x7FFF #define LDBL_EXP_SHIFT 0 #define LDBL_SIGN_INDEX 2 #define LDBL_SIGN_MASK 0x8000 #define LDBL_SIGN_SHIFT 15 #define LDBL_NBIT 0x800000000 typedef npy_uint32 ldouble_man_t; typedef npy_uint32 ldouble_exp_t; typedef npy_uint32 ldouble_sign_t; #elif defined(HAVE_LDOUBLE_MOTOROLA_EXTENDED_12_BYTES_BE) /* * Motorola extended 80 bits precision. Bit representation is * | s |eeeeeeeeeeeeeee| junk |mmmmmmmm................mmmmmmm| * | 1 bit | 15 bits | 16 bits| 64 bits | * | a[0] | a[1] | a[2] | * * 16 low bits of a[0] are junk */ typedef npy_uint32 IEEEl2bitsrep_part; union IEEEl2bitsrep { npy_longdouble e; IEEEl2bitsrep_part a[3]; }; #define LDBL_MANL_INDEX 2 #define LDBL_MANL_MASK 0xFFFFFFFF #define LDBL_MANL_SHIFT 0 #define LDBL_MANH_INDEX 1 #define LDBL_MANH_MASK 0xFFFFFFFF #define LDBL_MANH_SHIFT 0 #define LDBL_EXP_INDEX 0 #define LDBL_EXP_MASK 0x7FFF0000 #define LDBL_EXP_SHIFT 16 #define LDBL_SIGN_INDEX 0 #define LDBL_SIGN_MASK 0x80000000 #define LDBL_SIGN_SHIFT 31 #define LDBL_NBIT 0x80000000 typedef npy_uint32 ldouble_man_t; typedef npy_uint32 ldouble_exp_t; typedef npy_uint32 ldouble_sign_t; #elif defined(HAVE_LDOUBLE_IEEE_DOUBLE_16_BYTES_BE) || \ defined(HAVE_LDOUBLE_IEEE_DOUBLE_BE) /* 64 bits IEEE double precision aligned on 16 bytes: used by ppc arch on * Mac OS X */ /* * IEEE double precision. Bit representation is * | s |eeeeeeeeeee|mmmmmmmm................mmmmmmm| * |1 bit| 11 bits | 52 bits | * | a[0] | a[1] | */ typedef npy_uint32 IEEEl2bitsrep_part; union IEEEl2bitsrep { npy_longdouble e; IEEEl2bitsrep_part a[2]; }; #define LDBL_MANL_INDEX 1 #define LDBL_MANL_MASK 0xFFFFFFFF #define LDBL_MANL_SHIFT 0 #define LDBL_MANH_INDEX 0 #define LDBL_MANH_MASK 0x000FFFFF #define LDBL_MANH_SHIFT 0 #define LDBL_EXP_INDEX 0 #define LDBL_EXP_MASK 0x7FF00000 #define LDBL_EXP_SHIFT 20 #define LDBL_SIGN_INDEX 0 #define LDBL_SIGN_MASK 0x80000000 #define LDBL_SIGN_SHIFT 31 #define LDBL_NBIT 0 typedef npy_uint32 ldouble_man_t; typedef npy_uint32 ldouble_exp_t; typedef npy_uint32 ldouble_sign_t; #elif defined(HAVE_LDOUBLE_IEEE_DOUBLE_LE) /* 64 bits IEEE double precision, Little Endian. */ /* * IEEE double precision. Bit representation is * | s |eeeeeeeeeee|mmmmmmmm................mmmmmmm| * |1 bit| 11 bits | 52 bits | * | a[1] | a[0] | */ typedef npy_uint32 IEEEl2bitsrep_part; union IEEEl2bitsrep { npy_longdouble e; IEEEl2bitsrep_part a[2]; }; #define LDBL_MANL_INDEX 0 #define LDBL_MANL_MASK 0xFFFFFFFF #define LDBL_MANL_SHIFT 0 #define LDBL_MANH_INDEX 1 #define LDBL_MANH_MASK 0x000FFFFF #define LDBL_MANH_SHIFT 0 #define LDBL_EXP_INDEX 1 #define LDBL_EXP_MASK 0x7FF00000 #define LDBL_EXP_SHIFT 20 #define LDBL_SIGN_INDEX 1 #define LDBL_SIGN_MASK 0x80000000 #define LDBL_SIGN_SHIFT 31 #define LDBL_NBIT 0x00000080 typedef npy_uint32 ldouble_man_t; typedef npy_uint32 ldouble_exp_t; typedef npy_uint32 ldouble_sign_t; #elif defined(HAVE_LDOUBLE_IEEE_QUAD_BE) /* * IEEE quad precision, Big Endian. Bit representation is * | s |eeeeeeeeeee|mmmmmmmm................mmmmmmm| * |1 bit| 15 bits | 112 bits | * | a[0] | a[1] | */ typedef npy_uint64 IEEEl2bitsrep_part; union IEEEl2bitsrep { npy_longdouble e; IEEEl2bitsrep_part a[2]; }; #define LDBL_MANL_INDEX 1 #define LDBL_MANL_MASK 0xFFFFFFFFFFFFFFFF #define LDBL_MANL_SHIFT 0 #define LDBL_MANH_INDEX 0 #define LDBL_MANH_MASK 0x0000FFFFFFFFFFFF #define LDBL_MANH_SHIFT 0 #define LDBL_EXP_INDEX 0 #define LDBL_EXP_MASK 0x7FFF000000000000 #define LDBL_EXP_SHIFT 48 #define LDBL_SIGN_INDEX 0 #define LDBL_SIGN_MASK 0x8000000000000000 #define LDBL_SIGN_SHIFT 63 #define LDBL_NBIT 0 typedef npy_uint64 ldouble_man_t; typedef npy_uint64 ldouble_exp_t; typedef npy_uint32 ldouble_sign_t; #elif defined(HAVE_LDOUBLE_IEEE_QUAD_LE) /* * IEEE quad precision, Little Endian. Bit representation is * | s |eeeeeeeeeee|mmmmmmmm................mmmmmmm| * |1 bit| 15 bits | 112 bits | * | a[1] | a[0] | */ typedef npy_uint64 IEEEl2bitsrep_part; union IEEEl2bitsrep { npy_longdouble e; IEEEl2bitsrep_part a[2]; }; #define LDBL_MANL_INDEX 0 #define LDBL_MANL_MASK 0xFFFFFFFFFFFFFFFF #define LDBL_MANL_SHIFT 0 #define LDBL_MANH_INDEX 1 #define LDBL_MANH_MASK 0x0000FFFFFFFFFFFF #define LDBL_MANH_SHIFT 0 #define LDBL_EXP_INDEX 1 #define LDBL_EXP_MASK 0x7FFF000000000000 #define LDBL_EXP_SHIFT 48 #define LDBL_SIGN_INDEX 1 #define LDBL_SIGN_MASK 0x8000000000000000 #define LDBL_SIGN_SHIFT 63 #define LDBL_NBIT 0 typedef npy_uint64 ldouble_man_t; typedef npy_uint64 ldouble_exp_t; typedef npy_uint32 ldouble_sign_t; #endif #ifndef HAVE_LDOUBLE_DOUBLE_DOUBLE_BE /* 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) /* Set the sign bit of x to v. x should be of type IEEEl2bitsrep */ #define SET_LDOUBLE_SIGN(x, v) \ ((x).a[LDBL_SIGN_INDEX] = \ ((x).a[LDBL_SIGN_INDEX] & ~LDBL_SIGN_MASK) | \ (((IEEEl2bitsrep_part)(v) << LDBL_SIGN_SHIFT) & LDBL_SIGN_MASK)) /* Get the exp bits of x. x should be of type IEEEl2bitsrep */ #define GET_LDOUBLE_EXP(x) \ (((x).a[LDBL_EXP_INDEX] & LDBL_EXP_MASK) >> LDBL_EXP_SHIFT) /* Set the exp bit of x to v. x should be of type IEEEl2bitsrep */ #define SET_LDOUBLE_EXP(x, v) \ ((x).a[LDBL_EXP_INDEX] = \ ((x).a[LDBL_EXP_INDEX] & ~LDBL_EXP_MASK) | \ (((IEEEl2bitsrep_part)(v) << LDBL_EXP_SHIFT) & LDBL_EXP_MASK)) /* Get the manl bits of x. x should be of type IEEEl2bitsrep */ #define GET_LDOUBLE_MANL(x) \ (((x).a[LDBL_MANL_INDEX] & LDBL_MANL_MASK) >> LDBL_MANL_SHIFT) /* Set the manl bit of x to v. x should be of type IEEEl2bitsrep */ #define SET_LDOUBLE_MANL(x, v) \ ((x).a[LDBL_MANL_INDEX] = \ ((x).a[LDBL_MANL_INDEX] & ~LDBL_MANL_MASK) | \ (((IEEEl2bitsrep_part)(v) << LDBL_MANL_SHIFT) & LDBL_MANL_MASK)) /* Get the manh bits of x. x should be of type IEEEl2bitsrep */ #define GET_LDOUBLE_MANH(x) \ (((x).a[LDBL_MANH_INDEX] & LDBL_MANH_MASK) >> LDBL_MANH_SHIFT) /* Set the manh bit of x to v. x should be of type IEEEl2bitsrep */ #define SET_LDOUBLE_MANH(x, v) \ ((x).a[LDBL_MANH_INDEX] = \ ((x).a[LDBL_MANH_INDEX] & ~LDBL_MANH_MASK) | \ (((IEEEl2bitsrep_part)(v) << LDBL_MANH_SHIFT) & LDBL_MANH_MASK)) #endif /* #ifndef HAVE_LDOUBLE_DOUBLE_DOUBLE_BE */ /* * Those unions are used to convert a pointer of npy_cdouble to native C99 * complex or our own complex type independently on whether C99 complex * support is available */ #ifdef NPY_USE_C99_COMPLEX typedef union { npy_cdouble npy_z; complex double c99_z; } __npy_cdouble_to_c99_cast; typedef union { npy_cfloat npy_z; complex float c99_z; } __npy_cfloat_to_c99_cast; typedef union { npy_clongdouble npy_z; complex long double c99_z; } __npy_clongdouble_to_c99_cast; #else typedef union { npy_cdouble npy_z; npy_cdouble c99_z; } __npy_cdouble_to_c99_cast; typedef union { npy_cfloat npy_z; npy_cfloat c99_z; } __npy_cfloat_to_c99_cast; typedef union { npy_clongdouble npy_z; npy_clongdouble c99_z; } __npy_clongdouble_to_c99_cast; #endif #endif /* !_NPY_MATH_PRIVATE_H_ */ numpy-1.8.2/numpy/core/src/npymath/npy_math_complex.c.src0000664000175100017510000001677712370216242024714 0ustar vagrantvagrant00000000000000/* * Implement some C99-compatible complex math functions * * Most of the code is taken from the msun library in FreeBSD (HEAD @ 30th June * 2009), under the following license: * * Copyright (c) 2007 David Schultz * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "npy_math_common.h" #include "npy_math_private.h" /*========================================================== * Custom implementation of missing complex C99 functions *=========================================================*/ /**begin repeat * #type = npy_float, npy_double, npy_longdouble# * #ctype = npy_cfloat,npy_cdouble,npy_clongdouble# * #c = f, , l# * #C = F, , L# * #TMAX = FLT_MAX, DBL_MAX, LDBL_MAX# */ #ifndef HAVE_CABS@C@ @type@ npy_cabs@c@(@ctype@ z) { return npy_hypot@c@(npy_creal@c@(z), npy_cimag@c@(z)); } #endif #ifndef HAVE_CARG@C@ @type@ npy_carg@c@(@ctype@ z) { return npy_atan2@c@(npy_cimag@c@(z), npy_creal@c@(z)); } #endif #ifndef HAVE_CEXP@C@ @ctype@ npy_cexp@c@(@ctype@ z) { @type@ x, c, s; @type@ r, i; @ctype@ ret; r = npy_creal@c@(z); i = npy_cimag@c@(z); if (npy_isfinite(r)) { x = npy_exp@c@(r); c = npy_cos@c@(i); s = npy_sin@c@(i); if (npy_isfinite(i)) { ret = npy_cpack@c@(x * c, x * s); } else { ret = npy_cpack@c@(NPY_NAN, npy_copysign@c@(NPY_NAN, i)); } } else if (npy_isnan(r)) { /* r is nan */ if (i == 0) { ret = npy_cpack@c@(r, 0); } else { ret = npy_cpack@c@(r, npy_copysign@c@(NPY_NAN, i)); } } else { /* r is +- inf */ if (r > 0) { if (i == 0) { ret = npy_cpack@c@(r, i); } else if (npy_isfinite(i)) { c = npy_cos@c@(i); s = npy_sin@c@(i); ret = npy_cpack@c@(r * c, r * s); } else { /* x = +inf, y = +-inf | nan */ ret = npy_cpack@c@(r, NPY_NAN); } } else { if (npy_isfinite(i)) { x = npy_exp@c@(r); c = npy_cos@c@(i); s = npy_sin@c@(i); ret = npy_cpack@c@(x * c, x * s); } else { /* x = -inf, y = nan | +i inf */ ret = npy_cpack@c@(0, 0); } } } return ret; } #endif #ifndef HAVE_CLOG@C@ @ctype@ npy_clog@c@(@ctype@ z) { return npy_cpack@c@(npy_log@c@ (npy_cabs@c@ (z)), npy_carg@c@ (z)); } #endif #ifndef HAVE_CSQRT@C@ /* We risk spurious overflow for components >= DBL_MAX / (1 + sqrt(2)). */ #define THRESH (@TMAX@ / (1 + NPY_SQRT2@c@)) @ctype@ npy_csqrt@c@(@ctype@ z) { @ctype@ result; @type@ a, b; @type@ t; int scale; a = npy_creal@c@(z); b = npy_cimag@c@(z); /* Handle special cases. */ if (a == 0 && b == 0) return (npy_cpack@c@(0, b)); if (npy_isinf(b)) return (npy_cpack@c@(NPY_INFINITY, b)); if (npy_isnan(a)) { t = (b - b) / (b - b); /* raise invalid if b is not a NaN */ return (npy_cpack@c@(a, t)); /* return NaN + NaN i */ } if (npy_isinf(a)) { /* * csqrt(inf + NaN i) = inf + NaN i * csqrt(inf + y i) = inf + 0 i * csqrt(-inf + NaN i) = NaN +- inf i * csqrt(-inf + y i) = 0 + inf i */ if (npy_signbit(a)) return (npy_cpack@c@(npy_fabs@c@(b - b), npy_copysign@c@(a, b))); else return (npy_cpack@c@(a, npy_copysign@c@(b - b, b))); } /* * The remaining special case (b is NaN) is handled just fine by * the normal code path below. */ /* Scale to avoid overflow. */ if (npy_fabs@c@(a) >= THRESH || npy_fabs@c@(b) >= THRESH) { a *= 0.25; b *= 0.25; scale = 1; } else { scale = 0; } /* Algorithm 312, CACM vol 10, Oct 1967. */ if (a >= 0) { t = npy_sqrt@c@((a + npy_hypot@c@(a, b)) * 0.5); result = npy_cpack@c@(t, b / (2 * t)); } else { t = npy_sqrt@c@((-a + npy_hypot@c@(a, b)) * 0.5); result = npy_cpack@c@(npy_fabs@c@(b) / (2 * t), npy_copysign@c@(t, b)); } /* Rescale. */ if (scale) return (npy_cpack@c@(npy_creal@c@(result) * 2, npy_cimag@c@(result))); else return (result); } #undef THRESH #endif #ifndef HAVE_CPOW@C@ @ctype@ npy_cpow@c@ (@ctype@ x, @ctype@ y) { @ctype@ b; @type@ br, bi, yr, yi; yr = npy_creal@c@(y); yi = npy_cimag@c@(y); b = npy_clog@c@(x); br = npy_creal@c@(b); bi = npy_cimag@c@(b); return npy_cexp@c@(npy_cpack@c@(br * yr - bi * yi, br * yi + bi * yr)); } #endif #ifndef HAVE_CCOS@C@ @ctype@ npy_ccos@c@(@ctype@ z) { @type@ x, y; x = npy_creal@c@(z); y = npy_cimag@c@(z); return npy_cpack@c@(npy_cos@c@(x) * npy_cosh@c@(y), -(npy_sin@c@(x) * npy_sinh@c@(y))); } #endif #ifndef HAVE_CSIN@C@ @ctype@ npy_csin@c@(@ctype@ z) { @type@ x, y; x = npy_creal@c@(z); y = npy_cimag@c@(z); return npy_cpack@c@(npy_sin@c@(x) * npy_cosh@c@(y), npy_cos@c@(x) * npy_sinh@c@(y)); } #endif /**end repeat**/ /*========================================================== * Decorate all the functions which are available natively *=========================================================*/ /**begin repeat * #type = npy_float, npy_double, npy_longdouble# * #ctype = npy_cfloat, npy_cdouble, npy_clongdouble# * #c = f, , l# * #C = F, , L# */ /**begin repeat1 * #kind = cabs,carg# * #KIND = CABS,CARG# */ #ifdef HAVE_@KIND@@C@ @type@ npy_@kind@@c@(@ctype@ z) { __@ctype@_to_c99_cast z1 = {z}; return @kind@@c@(z1.c99_z); } #endif /**end repeat1**/ /**begin repeat1 * #kind = cexp,clog,csqrt,ccos,csin# * #KIND = CEXP,CLOG,CSQRT,CCOS,CSIN# */ #ifdef HAVE_@KIND@@C@ @ctype@ npy_@kind@@c@(@ctype@ z) { __@ctype@_to_c99_cast z1 = {z}; __@ctype@_to_c99_cast ret; ret.c99_z = @kind@@c@(z1.c99_z); return ret.npy_z; } #endif /**end repeat1**/ /**begin repeat1 * #kind = cpow# * #KIND = CPOW# */ #ifdef HAVE_@KIND@@C@ @ctype@ npy_@kind@@c@(@ctype@ x, @ctype@ y) { __@ctype@_to_c99_cast xcast = {x}; __@ctype@_to_c99_cast ycast = {y}; __@ctype@_to_c99_cast ret; ret.c99_z = @kind@@c@(xcast.c99_z, ycast.c99_z); return ret.npy_z; } #endif /**end repeat1**/ /**end repeat**/ numpy-1.8.2/numpy/core/src/private/0000775000175100017510000000000012371375427020400 5ustar vagrantvagrant00000000000000numpy-1.8.2/numpy/core/src/private/npy_sort.h0000664000175100017510000002217512370216243022422 0ustar vagrantvagrant00000000000000#ifndef __NPY_SORT_H__ #define __NPY_SORT_H__ /* Python include is for future object sorts */ #include #include #include #define NPY_ENOMEM 1 #define NPY_ECOMP 2 typedef int (*npy_comparator)(const void *, const void *); int quicksort_bool(npy_bool *vec, npy_intp cnt, void *null); int heapsort_bool(npy_bool *vec, npy_intp cnt, void *null); int mergesort_bool(npy_bool *vec, npy_intp cnt, void *null); int aquicksort_bool(npy_bool *vec, npy_intp *ind, npy_intp cnt, void *null); int aheapsort_bool(npy_bool *vec, npy_intp *ind, npy_intp cnt, void *null); int amergesort_bool(npy_bool *vec, npy_intp *ind, npy_intp cnt, void *null); int quicksort_byte(npy_byte *vec, npy_intp cnt, void *null); int heapsort_byte(npy_byte *vec, npy_intp cnt, void *null); int mergesort_byte(npy_byte *vec, npy_intp cnt, void *null); int aquicksort_byte(npy_byte *vec, npy_intp *ind, npy_intp cnt, void *null); int aheapsort_byte(npy_byte *vec, npy_intp *ind, npy_intp cnt, void *null); int amergesort_byte(npy_byte *vec, npy_intp *ind, npy_intp cnt, void *null); int quicksort_ubyte(npy_ubyte *vec, npy_intp cnt, void *null); int heapsort_ubyte(npy_ubyte *vec, npy_intp cnt, void *null); int mergesort_ubyte(npy_ubyte *vec, npy_intp cnt, void *null); int aquicksort_ubyte(npy_ubyte *vec, npy_intp *ind, npy_intp cnt, void *null); int aheapsort_ubyte(npy_ubyte *vec, npy_intp *ind, npy_intp cnt, void *null); int amergesort_ubyte(npy_ubyte *vec, npy_intp *ind, npy_intp cnt, void *null); int quicksort_short(npy_short *vec, npy_intp cnt, void *null); int heapsort_short(npy_short *vec, npy_intp cnt, void *null); int mergesort_short(npy_short *vec, npy_intp cnt, void *null); int aquicksort_short(npy_short *vec, npy_intp *ind, npy_intp cnt, void *null); int aheapsort_short(npy_short *vec, npy_intp *ind, npy_intp cnt, void *null); int amergesort_short(npy_short *vec, npy_intp *ind, npy_intp cnt, void *null); int quicksort_ushort(npy_ushort *vec, npy_intp cnt, void *null); int heapsort_ushort(npy_ushort *vec, npy_intp cnt, void *null); int mergesort_ushort(npy_ushort *vec, npy_intp cnt, void *null); int aquicksort_ushort(npy_ushort *vec, npy_intp *ind, npy_intp cnt, void *null); int aheapsort_ushort(npy_ushort *vec, npy_intp *ind, npy_intp cnt, void *null); int amergesort_ushort(npy_ushort *vec, npy_intp *ind, npy_intp cnt, void *null); int quicksort_int(npy_int *vec, npy_intp cnt, void *null); int heapsort_int(npy_int *vec, npy_intp cnt, void *null); int mergesort_int(npy_int *vec, npy_intp cnt, void *null); int aquicksort_int(npy_int *vec, npy_intp *ind, npy_intp cnt, void *null); int aheapsort_int(npy_int *vec, npy_intp *ind, npy_intp cnt, void *null); int amergesort_int(npy_int *vec, npy_intp *ind, npy_intp cnt, void *null); int quicksort_uint(npy_uint *vec, npy_intp cnt, void *null); int heapsort_uint(npy_uint *vec, npy_intp cnt, void *null); int mergesort_uint(npy_uint *vec, npy_intp cnt, void *null); int aquicksort_uint(npy_uint *vec, npy_intp *ind, npy_intp cnt, void *null); int aheapsort_uint(npy_uint *vec, npy_intp *ind, npy_intp cnt, void *null); int amergesort_uint(npy_uint *vec, npy_intp *ind, npy_intp cnt, void *null); int quicksort_long(npy_long *vec, npy_intp cnt, void *null); int heapsort_long(npy_long *vec, npy_intp cnt, void *null); int mergesort_long(npy_long *vec, npy_intp cnt, void *null); int aquicksort_long(npy_long *vec, npy_intp *ind, npy_intp cnt, void *null); int aheapsort_long(npy_long *vec, npy_intp *ind, npy_intp cnt, void *null); int amergesort_long(npy_long *vec, npy_intp *ind, npy_intp cnt, void *null); int quicksort_ulong(npy_ulong *vec, npy_intp cnt, void *null); int heapsort_ulong(npy_ulong *vec, npy_intp cnt, void *null); int mergesort_ulong(npy_ulong *vec, npy_intp cnt, void *null); int aquicksort_ulong(npy_ulong *vec, npy_intp *ind, npy_intp cnt, void *null); int aheapsort_ulong(npy_ulong *vec, npy_intp *ind, npy_intp cnt, void *null); int amergesort_ulong(npy_ulong *vec, npy_intp *ind, npy_intp cnt, void *null); int quicksort_longlong(npy_longlong *vec, npy_intp cnt, void *null); int heapsort_longlong(npy_longlong *vec, npy_intp cnt, void *null); int mergesort_longlong(npy_longlong *vec, npy_intp cnt, void *null); int aquicksort_longlong(npy_longlong *vec, npy_intp *ind, npy_intp cnt, void *null); int aheapsort_longlong(npy_longlong *vec, npy_intp *ind, npy_intp cnt, void *null); int amergesort_longlong(npy_longlong *vec, npy_intp *ind, npy_intp cnt, void *null); int quicksort_ulonglong(npy_ulonglong *vec, npy_intp cnt, void *null); int heapsort_ulonglong(npy_ulonglong *vec, npy_intp cnt, void *null); int mergesort_ulonglong(npy_ulonglong *vec, npy_intp cnt, void *null); int aquicksort_ulonglong(npy_ulonglong *vec, npy_intp *ind, npy_intp cnt, void *null); int aheapsort_ulonglong(npy_ulonglong *vec, npy_intp *ind, npy_intp cnt, void *null); int amergesort_ulonglong(npy_ulonglong *vec, npy_intp *ind, npy_intp cnt, void *null); int quicksort_half(npy_ushort *vec, npy_intp cnt, void *null); int heapsort_half(npy_ushort *vec, npy_intp cnt, void *null); int mergesort_half(npy_ushort *vec, npy_intp cnt, void *null); int aquicksort_half(npy_ushort *vec, npy_intp *ind, npy_intp cnt, void *null); int aheapsort_half(npy_ushort *vec, npy_intp *ind, npy_intp cnt, void *null); int amergesort_half(npy_ushort *vec, npy_intp *ind, npy_intp cnt, void *null); int quicksort_float(npy_float *vec, npy_intp cnt, void *null); int heapsort_float(npy_float *vec, npy_intp cnt, void *null); int mergesort_float(npy_float *vec, npy_intp cnt, void *null); int aquicksort_float(npy_float *vec, npy_intp *ind, npy_intp cnt, void *null); int aheapsort_float(npy_float *vec, npy_intp *ind, npy_intp cnt, void *null); int amergesort_float(npy_float *vec, npy_intp *ind, npy_intp cnt, void *null); int quicksort_double(npy_double *vec, npy_intp cnt, void *null); int heapsort_double(npy_double *vec, npy_intp cnt, void *null); int mergesort_double(npy_double *vec, npy_intp cnt, void *null); int aquicksort_double(npy_double *vec, npy_intp *ind, npy_intp cnt, void *null); int aheapsort_double(npy_double *vec, npy_intp *ind, npy_intp cnt, void *null); int amergesort_double(npy_double *vec, npy_intp *ind, npy_intp cnt, void *null); int quicksort_longdouble(npy_longdouble *vec, npy_intp cnt, void *null); int heapsort_longdouble(npy_longdouble *vec, npy_intp cnt, void *null); int mergesort_longdouble(npy_longdouble *vec, npy_intp cnt, void *null); int aquicksort_longdouble(npy_longdouble *vec, npy_intp *ind, npy_intp cnt, void *null); int aheapsort_longdouble(npy_longdouble *vec, npy_intp *ind, npy_intp cnt, void *null); int amergesort_longdouble(npy_longdouble *vec, npy_intp *ind, npy_intp cnt, void *null); int quicksort_cfloat(npy_cfloat *vec, npy_intp cnt, void *null); int heapsort_cfloat(npy_cfloat *vec, npy_intp cnt, void *null); int mergesort_cfloat(npy_cfloat *vec, npy_intp cnt, void *null); int aquicksort_cfloat(npy_cfloat *vec, npy_intp *ind, npy_intp cnt, void *null); int aheapsort_cfloat(npy_cfloat *vec, npy_intp *ind, npy_intp cnt, void *null); int amergesort_cfloat(npy_cfloat *vec, npy_intp *ind, npy_intp cnt, void *null); int quicksort_cdouble(npy_cdouble *vec, npy_intp cnt, void *null); int heapsort_cdouble(npy_cdouble *vec, npy_intp cnt, void *null); int mergesort_cdouble(npy_cdouble *vec, npy_intp cnt, void *null); int aquicksort_cdouble(npy_cdouble *vec, npy_intp *ind, npy_intp cnt, void *null); int aheapsort_cdouble(npy_cdouble *vec, npy_intp *ind, npy_intp cnt, void *null); int amergesort_cdouble(npy_cdouble *vec, npy_intp *ind, npy_intp cnt, void *null); int quicksort_clongdouble(npy_clongdouble *vec, npy_intp cnt, void *null); int heapsort_clongdouble(npy_clongdouble *vec, npy_intp cnt, void *null); int mergesort_clongdouble(npy_clongdouble *vec, npy_intp cnt, void *null); int aquicksort_clongdouble(npy_clongdouble *vec, npy_intp *ind, npy_intp cnt, void *null); int aheapsort_clongdouble(npy_clongdouble *vec, npy_intp *ind, npy_intp cnt, void *null); int amergesort_clongdouble(npy_clongdouble *vec, npy_intp *ind, npy_intp cnt, void *null); int quicksort_string(npy_char *vec, npy_intp cnt, PyArrayObject *arr); int heapsort_string(npy_char *vec, npy_intp cnt, PyArrayObject *arr); int mergesort_string(npy_char *vec, npy_intp cnt, PyArrayObject *arr); int aquicksort_string(npy_char *vec, npy_intp *ind, npy_intp cnt, PyArrayObject *arr); int aheapsort_string(npy_char *vec, npy_intp *ind, npy_intp cnt, PyArrayObject *arr); int amergesort_string(npy_char *vec, npy_intp *ind, npy_intp cnt, PyArrayObject *arr); int quicksort_unicode(npy_ucs4 *vec, npy_intp cnt, PyArrayObject *arr); int heapsort_unicode(npy_ucs4 *vec, npy_intp cnt, PyArrayObject *arr); int mergesort_unicode(npy_ucs4 *vec, npy_intp cnt, PyArrayObject *arr); int aquicksort_unicode(npy_ucs4 *vec, npy_intp *ind, npy_intp cnt, PyArrayObject *arr); int aheapsort_unicode(npy_ucs4 *vec, npy_intp *ind, npy_intp cnt, PyArrayObject *arr); int amergesort_unicode(npy_ucs4 *vec, npy_intp *ind, npy_intp cnt, PyArrayObject *arr); int npy_quicksort(void *base, size_t num, size_t size, npy_comparator cmp); int npy_heapsort(void *base, size_t num, size_t size, npy_comparator cmp); int npy_mergesort(void *base, size_t num, size_t size, npy_comparator cmp); #endif numpy-1.8.2/numpy/core/src/private/scalarmathmodule.h.src0000664000175100017510000000210712370216242024650 0ustar vagrantvagrant00000000000000/* * some overflow checking integer arithmetic */ #include #ifndef __NPY_SCALARMATHMODULE_H__ #define __NPY_SCALARMATHMODULE_H__ /**begin repeat * #name = int, uint, long, ulong, * longlong, ulonglong, intp# * #type = npy_int, npy_uint, npy_long, npy_ulong, * npy_longlong, npy_ulonglong, npy_intp# * #MAX = NPY_MAX_INT, NPY_MAX_UINT, NPY_MAX_LONG, NPY_MAX_ULONG, * NPY_MAX_LONGLONG, NPY_MAX_ULONGLONG, NPY_MAX_INTP# */ /* * writes result of a * b into r * returns 1 if a * b overflowed else returns 0 */ static NPY_INLINE int npy_mul_with_overflow_@name@(@type@ * r, @type@ a, @type@ b) { const @type@ half_sz = (((@type@)1 << (sizeof(a) * 8 / 2)) - 1); *r = a * b; /* * avoid expensive division on common no overflow case * could be improved via compiler intrinsics e.g. via clang * __builtin_mul_with_overflow, gcc __int128 or cpu overflow flags */ if (NPY_UNLIKELY((a | b) >= half_sz) && a != 0 && b > @MAX@ / a) { return 1; } return 0; } /**end repeat**/ #endif numpy-1.8.2/numpy/core/src/private/npy_pycompat.h0000664000175100017510000000016012370216242023254 0ustar vagrantvagrant00000000000000#ifndef _NPY_PYCOMPAT_H_ #define _NPY_PYCOMPAT_H_ #include "numpy/npy_3kcompat.h" #endif /* _NPY_COMPAT_H_ */ numpy-1.8.2/numpy/core/src/private/npy_config.h0000664000175100017510000000115012370216243022666 0ustar vagrantvagrant00000000000000#ifndef _NPY_NPY_CONFIG_H_ #define _NPY_NPY_CONFIG_H_ #include "config.h" #include "numpy/numpyconfig.h" /* Disable broken MS math functions */ #if defined(_MSC_VER) || defined(__MINGW32_VERSION) #undef HAVE_ATAN2 #undef HAVE_HYPOT #endif /* 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 #define HAVE_LDEXPL 1 #endif #ifdef HAVE_FREXP #define HAVE_FREXPL 1 #endif #endif /* Disable broken Sun Workshop Pro math functions */ #ifdef __SUNPRO_C #undef HAVE_ATAN2 #endif #endif numpy-1.8.2/numpy/core/src/private/npy_fpmath.h0000664000175100017510000000325412370216243022707 0ustar vagrantvagrant00000000000000#ifndef _NPY_NPY_FPMATH_H_ #define _NPY_NPY_FPMATH_H_ #include "npy_config.h" #include "numpy/npy_os.h" #include "numpy/npy_cpu.h" #include "numpy/npy_common.h" #ifdef NPY_OS_DARWIN /* This hardcoded logic is fragile, but universal builds makes it * difficult to detect arch-specific features */ /* MAC OS X < 10.4 and gcc < 4 does not support proper long double, and * is the same as double on those platforms */ #if NPY_BITSOF_LONGDOUBLE == NPY_BITSOF_DOUBLE /* This assumes that FPU and ALU have the same endianness */ #if NPY_BYTE_ORDER == NPY_LITTLE_ENDIAN #define HAVE_LDOUBLE_IEEE_DOUBLE_LE #elif NPY_BYTE_ORDER == NPY_BIG_ENDIAN #define HAVE_LDOUBLE_IEEE_DOUBLE_BE #else #error Endianness undefined ? #endif #else #if defined(NPY_CPU_X86) #define HAVE_LDOUBLE_INTEL_EXTENDED_12_BYTES_LE #elif defined(NPY_CPU_AMD64) #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 #endif #endif #endif #if !(defined(HAVE_LDOUBLE_IEEE_QUAD_BE) || \ defined(HAVE_LDOUBLE_IEEE_QUAD_LE) || \ defined(HAVE_LDOUBLE_IEEE_DOUBLE_LE) || \ defined(HAVE_LDOUBLE_IEEE_DOUBLE_BE) || \ defined(HAVE_LDOUBLE_IEEE_DOUBLE_16_BYTES_BE) || \ 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)) #error No long double representation defined #endif #endif numpy-1.8.2/numpy/core/src/private/lowlevel_strided_loops.h0000664000175100017510000007245012370216243025331 0ustar vagrantvagrant00000000000000#ifndef __LOWLEVEL_STRIDED_LOOPS_H #define __LOWLEVEL_STRIDED_LOOPS_H #include "common.h" #include /* * NOTE: This API should remain private for the time being, to allow * for further refinement. I think the 'aligned' mechanism * needs changing, for example. */ /* * This function pointer is for unary operations that input an * arbitrarily strided one-dimensional array segment and output * an arbitrarily strided array segment of the same size. * It may be a fully general function, or a specialized function * when the strides or item size have particular known values. * * Examples of unary operations are a straight copy, a byte-swap, * and a casting operation, * * The 'transferdata' parameter is slightly special, following a * generic auxiliary data pattern defined in ndarraytypes.h * Use NPY_AUXDATA_CLONE and NPY_AUXDATA_FREE to deal with this data. * */ typedef void (PyArray_StridedUnaryOp)(char *dst, npy_intp dst_stride, char *src, npy_intp src_stride, npy_intp N, npy_intp src_itemsize, NpyAuxData *transferdata); /* * This is for pointers to functions which behave exactly as * for PyArray_StridedUnaryOp, but with an additional mask controlling * which values are transformed. * * In particular, the 'i'-th element is operated on if and only if * mask[i*mask_stride] is true. */ typedef void (PyArray_MaskedStridedUnaryOp)(char *dst, npy_intp dst_stride, char *src, npy_intp src_stride, npy_bool *mask, npy_intp mask_stride, npy_intp N, npy_intp src_itemsize, NpyAuxData *transferdata); /* * This function pointer is for binary operations that input two * arbitrarily strided one-dimensional array segments and output * an arbitrarily strided array segment of the same size. * It may be a fully general function, or a specialized function * when the strides or item size have particular known values. * * Examples of binary operations are the basic arithmetic operations, * logical operators AND, OR, and many others. * * The 'transferdata' parameter is slightly special, following a * generic auxiliary data pattern defined in ndarraytypes.h * Use NPY_AUXDATA_CLONE and NPY_AUXDATA_FREE to deal with this data. * */ typedef void (PyArray_StridedBinaryOp)(char *dst, npy_intp dst_stride, char *src0, npy_intp src0_stride, char *src1, npy_intp src1_stride, npy_intp N, NpyAuxData *transferdata); /* * Gives back a function pointer to a specialized function for copying * strided memory. Returns NULL if there is a problem with the inputs. * * aligned: * Should be 1 if the src and dst pointers are always aligned, * 0 otherwise. * src_stride: * Should be the src stride if it will always be the same, * NPY_MAX_INTP otherwise. * dst_stride: * Should be the dst stride if it will always be the same, * NPY_MAX_INTP otherwise. * itemsize: * Should be the item size if it will always be the same, 0 otherwise. * */ NPY_NO_EXPORT PyArray_StridedUnaryOp * PyArray_GetStridedCopyFn(int aligned, npy_intp src_stride, npy_intp dst_stride, npy_intp itemsize); /* * Gives back a function pointer to a specialized function for copying * and swapping strided memory. This assumes each element is a single * value to be swapped. * * For information on the 'aligned', 'src_stride' and 'dst_stride' parameters * see above. * * Parameters are as for PyArray_GetStridedCopyFn. */ NPY_NO_EXPORT PyArray_StridedUnaryOp * PyArray_GetStridedCopySwapFn(int aligned, npy_intp src_stride, npy_intp dst_stride, npy_intp itemsize); /* * Gives back a function pointer to a specialized function for copying * and swapping strided memory. This assumes each element is a pair * of values, each of which needs to be swapped. * * For information on the 'aligned', 'src_stride' and 'dst_stride' parameters * see above. * * Parameters are as for PyArray_GetStridedCopyFn. */ NPY_NO_EXPORT PyArray_StridedUnaryOp * PyArray_GetStridedCopySwapPairFn(int aligned, npy_intp src_stride, npy_intp dst_stride, npy_intp itemsize); /* * Gives back a transfer function and transfer data pair which copies * the data from source to dest, truncating it if the data doesn't * fit, and padding with zero bytes if there's too much space. * * For information on the 'aligned', 'src_stride' and 'dst_stride' parameters * see above. * * Returns NPY_SUCCEED or NPY_FAIL */ NPY_NO_EXPORT int PyArray_GetStridedZeroPadCopyFn(int aligned, npy_intp src_stride, npy_intp dst_stride, npy_intp src_itemsize, npy_intp dst_itemsize, PyArray_StridedUnaryOp **outstransfer, NpyAuxData **outtransferdata); /* * For casts between built-in numeric types, * this produces a function pointer for casting from src_type_num * to dst_type_num. If a conversion is unsupported, returns NULL * without setting a Python exception. */ NPY_NO_EXPORT PyArray_StridedUnaryOp * PyArray_GetStridedNumericCastFn(int aligned, npy_intp src_stride, npy_intp dst_stride, int src_type_num, int dst_type_num); /* * Gets an operation which copies elements of the given dtype, * swapping if the dtype isn't in NBO. * * Returns NPY_SUCCEED or NPY_FAIL */ NPY_NO_EXPORT int PyArray_GetDTypeCopySwapFn(int aligned, npy_intp src_stride, npy_intp dst_stride, PyArray_Descr *dtype, PyArray_StridedUnaryOp **outstransfer, NpyAuxData **outtransferdata); /* * If it's possible, gives back a transfer function which casts and/or * byte swaps data with the dtype 'src_dtype' into data with the dtype * 'dst_dtype'. If the outtransferdata is populated with a non-NULL value, * it must be deallocated with the NPY_AUXDATA_FREE * function when the transfer function is no longer required. * * aligned: * Should be 1 if the src and dst pointers are always aligned, * 0 otherwise. * src_stride: * Should be the src stride if it will always be the same, * NPY_MAX_INTP otherwise. * dst_stride: * Should be the dst stride if it will always be the same, * NPY_MAX_INTP otherwise. * src_dtype: * The data type of source data. If this is NULL, a transfer * function which sets the destination to zeros is produced. * dst_dtype: * The data type of destination data. If this is NULL and * move_references is 1, a transfer function which decrements * source data references is produced. * move_references: * If 0, the destination data gets new reference ownership. * If 1, the references from the source data are moved to * the destination data. * out_stransfer: * The resulting transfer function is placed here. * out_transferdata: * The auxiliary data for the transfer function is placed here. * When finished with the transfer function, the caller must call * NPY_AUXDATA_FREE on this data. * out_needs_api: * If this is non-NULL, and the transfer function produced needs * to call into the (Python) API, this gets set to 1. This * remains untouched if no API access is required. * * WARNING: If you set move_references to 1, it is best that src_stride is * never zero when calling the transfer function. Otherwise, the * first destination reference will get the value and all the rest * will get NULL. * * Returns NPY_SUCCEED or NPY_FAIL. */ NPY_NO_EXPORT int PyArray_GetDTypeTransferFunction(int aligned, npy_intp src_stride, npy_intp dst_stride, PyArray_Descr *src_dtype, PyArray_Descr *dst_dtype, int move_references, PyArray_StridedUnaryOp **out_stransfer, NpyAuxData **out_transferdata, int *out_needs_api); /* * This is identical to PyArray_GetDTypeTransferFunction, but returns a * transfer function which also takes a mask as a parameter. The mask is used * to determine which values to copy, and data is transfered exactly when * mask[i*mask_stride] is true. * * If move_references is true, values which are not copied to the * destination will still have their source reference decremented. * * If mask_dtype is NPY_BOOL or NPY_UINT8, each full element is either * transferred or not according to the mask as described above. If * dst_dtype and mask_dtype are both struct dtypes, their names must * match exactly, and the dtype of each leaf field in mask_dtype must * be either NPY_BOOL or NPY_UINT8. */ NPY_NO_EXPORT int PyArray_GetMaskedDTypeTransferFunction(int aligned, npy_intp src_stride, npy_intp dst_stride, npy_intp mask_stride, PyArray_Descr *src_dtype, PyArray_Descr *dst_dtype, PyArray_Descr *mask_dtype, int move_references, PyArray_MaskedStridedUnaryOp **out_stransfer, NpyAuxData **out_transferdata, int *out_needs_api); /* * Casts the specified number of elements from 'src' with data type * 'src_dtype' to 'dst' with 'dst_dtype'. See * PyArray_GetDTypeTransferFunction for more details. * * Returns NPY_SUCCEED or NPY_FAIL. */ NPY_NO_EXPORT int PyArray_CastRawArrays(npy_intp count, char *src, char *dst, npy_intp src_stride, npy_intp dst_stride, PyArray_Descr *src_dtype, PyArray_Descr *dst_dtype, int move_references); /* * These two functions copy or convert the data of an n-dimensional array * to/from a 1-dimensional strided buffer. These functions will only call * 'stransfer' with the provided dst_stride/src_stride and * dst_strides[0]/src_strides[0], so the caller can use those values to * specialize the function. * Note that even if ndim == 0, everything needs to be set as if ndim == 1. * * The return value is the number of elements it couldn't copy. A return value * of 0 means all elements were copied, a larger value means the end of * the n-dimensional array was reached before 'count' elements were copied. * * ndim: * The number of dimensions of the n-dimensional array. * dst/src/mask: * The destination, source or mask starting pointer. * dst_stride/src_stride/mask_stride: * The stride of the 1-dimensional strided buffer * dst_strides/src_strides: * The strides of the n-dimensional array. * dst_strides_inc/src_strides_inc: * How much to add to the ..._strides pointer to get to the next stride. * coords: * The starting coordinates in the n-dimensional array. * coords_inc: * How much to add to the coords pointer to get to the next coordinate. * shape: * The shape of the n-dimensional array. * shape_inc: * How much to add to the shape pointer to get to the next shape entry. * count: * How many elements to transfer * src_itemsize: * How big each element is. If transfering between elements of different * sizes, for example a casting operation, the 'stransfer' function * should be specialized for that, in which case 'stransfer' will use * this parameter as the source item size. * stransfer: * The strided transfer function. * transferdata: * An auxiliary data pointer passed to the strided transfer function. * This follows the conventions of NpyAuxData objects. */ NPY_NO_EXPORT npy_intp PyArray_TransferNDimToStrided(npy_intp ndim, char *dst, npy_intp dst_stride, char *src, npy_intp *src_strides, npy_intp src_strides_inc, npy_intp *coords, npy_intp coords_inc, npy_intp *shape, npy_intp shape_inc, npy_intp count, npy_intp src_itemsize, PyArray_StridedUnaryOp *stransfer, NpyAuxData *transferdata); NPY_NO_EXPORT npy_intp PyArray_TransferStridedToNDim(npy_intp ndim, char *dst, npy_intp *dst_strides, npy_intp dst_strides_inc, char *src, npy_intp src_stride, npy_intp *coords, npy_intp coords_inc, npy_intp *shape, npy_intp shape_inc, npy_intp count, npy_intp src_itemsize, PyArray_StridedUnaryOp *stransfer, NpyAuxData *transferdata); NPY_NO_EXPORT npy_intp PyArray_TransferMaskedStridedToNDim(npy_intp ndim, char *dst, npy_intp *dst_strides, npy_intp dst_strides_inc, char *src, npy_intp src_stride, npy_bool *mask, npy_intp mask_stride, npy_intp *coords, npy_intp coords_inc, npy_intp *shape, npy_intp shape_inc, npy_intp count, npy_intp src_itemsize, PyArray_MaskedStridedUnaryOp *stransfer, NpyAuxData *data); /* * Prepares shape and strides for a simple raw array iteration. * This sorts the strides into FORTRAN order, reverses any negative * strides, then coalesces axes where possible. The results are * filled in the output parameters. * * This is intended for simple, lightweight iteration over arrays * where no buffering of any kind is needed, and the array may * not be stored as a PyArrayObject. * * You can use this together with NPY_RAW_ITER_START and * NPY_RAW_ITER_ONE_NEXT to handle the looping boilerplate of everything * but the innermost loop (which is for idim == 0). * * Returns 0 on success, -1 on failure. */ NPY_NO_EXPORT int PyArray_PrepareOneRawArrayIter(int ndim, npy_intp *shape, char *data, npy_intp *strides, int *out_ndim, npy_intp *out_shape, char **out_data, npy_intp *out_strides); /* * The same as PyArray_PrepareOneRawArrayIter, but for two * operands instead of one. Any broadcasting of the two operands * should have already been done before calling this function, * as the ndim and shape is only specified once for both operands. * * Only the strides of the first operand are used to reorder * the dimensions, no attempt to consider all the strides together * is made, as is done in the NpyIter object. * * You can use this together with NPY_RAW_ITER_START and * NPY_RAW_ITER_TWO_NEXT to handle the looping boilerplate of everything * but the innermost loop (which is for idim == 0). * * Returns 0 on success, -1 on failure. */ NPY_NO_EXPORT int PyArray_PrepareTwoRawArrayIter(int ndim, npy_intp *shape, char *dataA, npy_intp *stridesA, char *dataB, npy_intp *stridesB, int *out_ndim, npy_intp *out_shape, char **out_dataA, npy_intp *out_stridesA, char **out_dataB, npy_intp *out_stridesB); /* * The same as PyArray_PrepareOneRawArrayIter, but for three * operands instead of one. Any broadcasting of the three operands * should have already been done before calling this function, * as the ndim and shape is only specified once for all operands. * * Only the strides of the first operand are used to reorder * the dimensions, no attempt to consider all the strides together * is made, as is done in the NpyIter object. * * You can use this together with NPY_RAW_ITER_START and * NPY_RAW_ITER_THREE_NEXT to handle the looping boilerplate of everything * but the innermost loop (which is for idim == 0). * * Returns 0 on success, -1 on failure. */ NPY_NO_EXPORT int PyArray_PrepareThreeRawArrayIter(int ndim, npy_intp *shape, char *dataA, npy_intp *stridesA, char *dataB, npy_intp *stridesB, char *dataC, npy_intp *stridesC, int *out_ndim, npy_intp *out_shape, char **out_dataA, npy_intp *out_stridesA, char **out_dataB, npy_intp *out_stridesB, char **out_dataC, npy_intp *out_stridesC); /* * Return number of elements that must be peeled from * the start of 'addr' with 'nvals' elements of size 'esize' * in order to reach 'alignment'. * alignment must be a power of two. * see npy_blocked_end for an example */ static NPY_INLINE npy_uintp npy_aligned_block_offset(const void * addr, const npy_uintp esize, const npy_uintp alignment, const npy_uintp nvals) { const npy_uintp offset = (npy_uintp)addr & (alignment - 1); npy_uintp peel = offset ? (alignment - offset) / esize : 0; peel = nvals < peel ? nvals : peel; return peel; } /* * Return upper loop bound for an array of 'nvals' elements * of size 'esize' peeled by 'offset' elements and blocking to * a vector size of 'vsz' in bytes * * example usage: * npy_intp i; * double v[101]; * npy_intp esize = sizeof(v[0]); * npy_intp peel = npy_aligned_block_offset(v, esize, 16, n); * // peel to alignment 16 * for (i = 0; i < peel; i++) * * // simd vectorized operation * for (; i < npy_blocked_end(peel, esize, 16, n); i += 16 / esize) * * // handle scalar rest * for(; i < n; i++) * */ static NPY_INLINE npy_uintp npy_blocked_end(const npy_uintp offset, const npy_uintp esize, const npy_uintp vsz, const npy_uintp nvals) { return nvals - offset - (nvals - offset) % (vsz / esize); } /* byte swapping functions */ static NPY_INLINE npy_uint16 npy_bswap2(npy_uint16 x) { return ((x & 0xffu) << 8) | (x >> 8); } /* * treat as int16 and byteswap unaligned memory, * some cpus don't support unaligned access */ static NPY_INLINE void npy_bswap2_unaligned(char * x) { char a = x[0]; x[0] = x[1]; x[1] = a; } static NPY_INLINE npy_uint32 npy_bswap4(npy_uint32 x) { #ifdef HAVE___BUILTIN_BSWAP32 return __builtin_bswap32(x); #else return ((x & 0xffu) << 24) | ((x & 0xff00u) << 8) | ((x & 0xff0000u) >> 8) | (x >> 24); #endif } static NPY_INLINE void npy_bswap4_unaligned(char * x) { char a = x[0]; x[0] = x[3]; x[3] = a; a = x[1]; x[1] = x[2]; x[2] = a; } static NPY_INLINE npy_uint64 npy_bswap8(npy_uint64 x) { #ifdef HAVE___BUILTIN_BSWAP64 return __builtin_bswap64(x); #else return ((x & 0xffULL) << 56) | ((x & 0xff00ULL) << 40) | ((x & 0xff0000ULL) << 24) | ((x & 0xff000000ULL) << 8) | ((x & 0xff00000000ULL) >> 8) | ((x & 0xff0000000000ULL) >> 24) | ((x & 0xff000000000000ULL) >> 40) | ( x >> 56); #endif } static NPY_INLINE void npy_bswap8_unaligned(char * x) { char a = x[0]; x[0] = x[7]; x[7] = a; a = x[1]; x[1] = x[6]; x[6] = a; a = x[2]; x[2] = x[5]; x[5] = a; a = x[3]; x[3] = x[4]; x[4] = a; } /* Start raw iteration */ #define NPY_RAW_ITER_START(idim, ndim, coord, shape) \ memset((coord), 0, (ndim) * sizeof(coord[0])); \ do { /* Increment to the next n-dimensional coordinate for one raw array */ #define NPY_RAW_ITER_ONE_NEXT(idim, ndim, coord, shape, data, strides) \ for ((idim) = 1; (idim) < (ndim); ++(idim)) { \ if (++(coord)[idim] == (shape)[idim]) { \ (coord)[idim] = 0; \ (data) -= ((shape)[idim] - 1) * (strides)[idim]; \ } \ else { \ (data) += (strides)[idim]; \ break; \ } \ } \ } while ((idim) < (ndim)) /* Increment to the next n-dimensional coordinate for two raw arrays */ #define NPY_RAW_ITER_TWO_NEXT(idim, ndim, coord, shape, \ dataA, stridesA, dataB, stridesB) \ for ((idim) = 1; (idim) < (ndim); ++(idim)) { \ if (++(coord)[idim] == (shape)[idim]) { \ (coord)[idim] = 0; \ (dataA) -= ((shape)[idim] - 1) * (stridesA)[idim]; \ (dataB) -= ((shape)[idim] - 1) * (stridesB)[idim]; \ } \ else { \ (dataA) += (stridesA)[idim]; \ (dataB) += (stridesB)[idim]; \ break; \ } \ } \ } while ((idim) < (ndim)) /* Increment to the next n-dimensional coordinate for three raw arrays */ #define NPY_RAW_ITER_THREE_NEXT(idim, ndim, coord, shape, \ dataA, stridesA, \ dataB, stridesB, \ dataC, stridesC) \ for ((idim) = 1; (idim) < (ndim); ++(idim)) { \ if (++(coord)[idim] == (shape)[idim]) { \ (coord)[idim] = 0; \ (dataA) -= ((shape)[idim] - 1) * (stridesA)[idim]; \ (dataB) -= ((shape)[idim] - 1) * (stridesB)[idim]; \ (dataC) -= ((shape)[idim] - 1) * (stridesC)[idim]; \ } \ else { \ (dataA) += (stridesA)[idim]; \ (dataB) += (stridesB)[idim]; \ (dataC) += (stridesC)[idim]; \ break; \ } \ } \ } while ((idim) < (ndim)) /* Increment to the next n-dimensional coordinate for four raw arrays */ #define NPY_RAW_ITER_FOUR_NEXT(idim, ndim, coord, shape, \ dataA, stridesA, \ dataB, stridesB, \ dataC, stridesC, \ dataD, stridesD) \ for ((idim) = 1; (idim) < (ndim); ++(idim)) { \ if (++(coord)[idim] == (shape)[idim]) { \ (coord)[idim] = 0; \ (dataA) -= ((shape)[idim] - 1) * (stridesA)[idim]; \ (dataB) -= ((shape)[idim] - 1) * (stridesB)[idim]; \ (dataC) -= ((shape)[idim] - 1) * (stridesC)[idim]; \ (dataD) -= ((shape)[idim] - 1) * (stridesD)[idim]; \ } \ else { \ (dataA) += (stridesA)[idim]; \ (dataB) += (stridesB)[idim]; \ (dataC) += (stridesC)[idim]; \ (dataD) += (stridesD)[idim]; \ break; \ } \ } \ } while ((idim) < (ndim)) /* * TRIVIAL ITERATION * * In some cases when the iteration order isn't important, iteration over * arrays is trivial. This is the case when: * * The array has 0 or 1 dimensions. * * The array is C or Fortran contiguous. * Use of an iterator can be skipped when this occurs. These macros assist * in detecting and taking advantage of the situation. Note that it may * be worthwhile to further check if the stride is a contiguous stride * and take advantage of that. * * Here is example code for a single array: * * if (PyArray_TRIVIALLY_ITERABLE(self) { * char *data; * npy_intp count, stride; * * PyArray_PREPARE_TRIVIAL_ITERATION(self, count, data, stride); * * while (count--) { * // Use the data pointer * * data += stride; * } * } * else { * // Create iterator, etc... * } * * Here is example code for a pair of arrays: * * if (PyArray_TRIVIALLY_ITERABLE_PAIR(a1, a2) { * char *data1, *data2; * npy_intp count, stride1, stride2; * * PyArray_PREPARE_TRIVIAL_PAIR_ITERATION(a1, a2, count, * data1, data2, stride1, stride2); * * while (count--) { * // Use the data1 and data2 pointers * * data1 += stride1; * data2 += stride2; * } * } * else { * // Create iterator, etc... * } */ /* * Note: Equivalently iterable macro requires one of arr1 or arr2 be * trivially iterable to be valid. */ #define PyArray_EQUIVALENTLY_ITERABLE(arr1, arr2) ( \ PyArray_NDIM(arr1) == PyArray_NDIM(arr2) && \ PyArray_CompareLists(PyArray_DIMS(arr1), \ PyArray_DIMS(arr2), \ PyArray_NDIM(arr1)) && \ (PyArray_FLAGS(arr1)&(NPY_ARRAY_C_CONTIGUOUS| \ NPY_ARRAY_F_CONTIGUOUS)) == \ (PyArray_FLAGS(arr2)&(NPY_ARRAY_C_CONTIGUOUS| \ NPY_ARRAY_F_CONTIGUOUS)) \ ) #define PyArray_TRIVIALLY_ITERABLE(arr) ( \ PyArray_NDIM(arr) <= 1 || \ PyArray_CHKFLAGS(arr, NPY_ARRAY_C_CONTIGUOUS) || \ PyArray_CHKFLAGS(arr, NPY_ARRAY_F_CONTIGUOUS) \ ) #define PyArray_PREPARE_TRIVIAL_ITERATION(arr, count, data, stride) \ 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))) \ #define PyArray_TRIVIALLY_ITERABLE_PAIR(arr1, arr2) (\ PyArray_TRIVIALLY_ITERABLE(arr1) && \ (PyArray_NDIM(arr2) == 0 || \ PyArray_EQUIVALENTLY_ITERABLE(arr1, arr2) || \ (PyArray_NDIM(arr1) == 0 && \ PyArray_TRIVIALLY_ITERABLE(arr2) \ ) \ ) \ ) #define PyArray_PREPARE_TRIVIAL_PAIR_ITERATION(arr1, arr2, \ count, \ data1, data2, \ stride1, stride2) { \ npy_intp size1 = PyArray_SIZE(arr1); \ npy_intp size2 = PyArray_SIZE(arr2); \ count = ((size1 > size2) || size1 == 0) ? size1 : size2; \ data1 = PyArray_BYTES(arr1); \ data2 = PyArray_BYTES(arr2); \ stride1 = (size1 == 1 ? 0 : ((PyArray_NDIM(arr1) == 1) ? \ PyArray_STRIDE(arr1, 0) : \ PyArray_ITEMSIZE(arr1))); \ stride2 = (size2 == 1 ? 0 : ((PyArray_NDIM(arr2) == 1) ? \ PyArray_STRIDE(arr2, 0) : \ PyArray_ITEMSIZE(arr2))); \ } #define PyArray_TRIVIALLY_ITERABLE_TRIPLE(arr1, arr2, arr3) (\ PyArray_TRIVIALLY_ITERABLE(arr1) && \ ((PyArray_NDIM(arr2) == 0 && \ (PyArray_NDIM(arr3) == 0 || \ PyArray_EQUIVALENTLY_ITERABLE(arr1, arr3) \ ) \ ) || \ (PyArray_EQUIVALENTLY_ITERABLE(arr1, arr2) && \ (PyArray_NDIM(arr3) == 0 || \ PyArray_EQUIVALENTLY_ITERABLE(arr1, arr3) \ ) \ ) || \ (PyArray_NDIM(arr1) == 0 && \ PyArray_TRIVIALLY_ITERABLE(arr2) && \ (PyArray_NDIM(arr3) == 0 || \ PyArray_EQUIVALENTLY_ITERABLE(arr2, arr3) \ ) \ ) \ ) \ ) #define PyArray_PREPARE_TRIVIAL_TRIPLE_ITERATION(arr1, arr2, arr3, \ count, \ data1, data2, data3, \ stride1, stride2, stride3) { \ npy_intp size1 = PyArray_SIZE(arr1); \ npy_intp size2 = PyArray_SIZE(arr2); \ npy_intp size3 = PyArray_SIZE(arr3); \ count = ((size1 > size2) || size1 == 0) ? size1 : size2; \ count = ((size3 > count) || size3 == 0) ? size3 : count; \ data1 = PyArray_BYTES(arr1); \ data2 = PyArray_BYTES(arr2); \ data3 = PyArray_BYTES(arr3); \ stride1 = (size1 == 1 ? 0 : ((PyArray_NDIM(arr1) == 1) ? \ PyArray_STRIDE(arr1, 0) : \ PyArray_ITEMSIZE(arr1))); \ stride2 = (size2 == 1 ? 0 : ((PyArray_NDIM(arr2) == 1) ? \ PyArray_STRIDE(arr2, 0) : \ PyArray_ITEMSIZE(arr2))); \ stride3 = (size3 == 1 ? 0 : ((PyArray_NDIM(arr3) == 1) ? \ PyArray_STRIDE(arr3, 0) : \ PyArray_ITEMSIZE(arr3))); \ } #endif numpy-1.8.2/numpy/core/src/private/npy_partition.h.src0000664000175100017510000001016012370216243024221 0ustar vagrantvagrant00000000000000/* ***************************************************************************** ** IMPORTANT NOTE for npy_partition.h.src -> npy_partition.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 * $ python numpy/distutils/conv_template.py numpy/core/src/private/npy_partition.h.src * $ */ #ifndef __NPY_PARTITION_H__ #define __NPY_PARTITION_H__ #include "npy_sort.h" /* Python include is for future object sorts */ #include #include #include #define NPY_MAX_PIVOT_STACK 50 /**begin repeat * * #TYPE = BOOL, BYTE, UBYTE, SHORT, USHORT, INT, UINT, LONG, ULONG, * LONGLONG, ULONGLONG, HALF, FLOAT, DOUBLE, LONGDOUBLE, * CFLOAT, CDOUBLE, CLONGDOUBLE# * #suff = bool, byte, ubyte, short, ushort, int, uint, long, ulong, * longlong, ulonglong, half, float, double, longdouble, * cfloat, cdouble, clongdouble# * #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# */ 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); /**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); 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); int npy_introselect(void *base, size_t num, size_t size, size_t kth, npy_comparator cmp); typedef struct { enum NPY_TYPES typenum; PyArray_PartitionFunc * part[NPY_NSELECTS]; PyArray_ArgPartitionFunc * argpart[NPY_NSELECTS]; } part_map; static part_map _part_map[] = { /**begin repeat * * #TYPE = BOOL, BYTE, UBYTE, SHORT, USHORT, INT, UINT, LONG, ULONG, * LONGLONG, ULONGLONG, HALF, FLOAT, DOUBLE, LONGDOUBLE, * CFLOAT, CDOUBLE, CLONGDOUBLE# * #suff = bool, byte, ubyte, short, ushort, int, uint, long, ulong, * longlong, ulonglong, half, float, double, longdouble, * cfloat, cdouble, clongdouble# * #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_@TYPE@, { (PyArray_PartitionFunc *)&introselect_@suff@, }, { (PyArray_ArgPartitionFunc *)&aintroselect_@suff@, } }, /**end repeat**/ }; static NPY_INLINE PyArray_PartitionFunc * get_partition_func(int type, NPY_SELECTKIND which) { npy_intp i; if (which >= NPY_NSELECTS) { return NULL; } for (i = 0; i < sizeof(_part_map)/sizeof(_part_map[0]); i++) { if (type == _part_map[i].typenum) { return _part_map[i].part[which]; } } return NULL; } static NPY_INLINE PyArray_ArgPartitionFunc * get_argpartition_func(int type, NPY_SELECTKIND which) { npy_intp i; if (which >= NPY_NSELECTS) { return NULL; } for (i = 0; i < sizeof(_part_map)/sizeof(_part_map[0]); i++) { if (type == _part_map[i].typenum) { return _part_map[i].argpart[which]; } } return NULL; } #endif numpy-1.8.2/numpy/core/code_generators/0000775000175100017510000000000012371375427021302 5ustar vagrantvagrant00000000000000numpy-1.8.2/numpy/core/code_generators/generate_ufunc_api.py0000664000175100017510000001232112370216243025463 0ustar vagrantvagrant00000000000000from __future__ import division, print_function import os import genapi import numpy_api from genapi import \ TypeApi, GlobalVarApi, FunctionApi, BoolValuesApi h_template = r""" #ifdef _UMATHMODULE #ifdef NPY_ENABLE_SEPARATE_COMPILATION extern NPY_NO_EXPORT PyTypeObject PyUFunc_Type; #else NPY_NO_EXPORT PyTypeObject PyUFunc_Type; #endif %s #else #if defined(PY_UFUNC_UNIQUE_SYMBOL) #define PyUFunc_API PY_UFUNC_UNIQUE_SYMBOL #endif #if defined(NO_IMPORT) || defined(NO_IMPORT_UFUNC) extern void **PyUFunc_API; #else #if defined(PY_UFUNC_UNIQUE_SYMBOL) void **PyUFunc_API; #else static void **PyUFunc_API=NULL; #endif #endif %s static int _import_umath(void) { PyObject *numpy = PyImport_ImportModule("numpy.core.umath"); PyObject *c_api = NULL; if (numpy == NULL) { PyErr_SetString(PyExc_ImportError, "numpy.core.umath failed to import"); return -1; } c_api = PyObject_GetAttrString(numpy, "_UFUNC_API"); Py_DECREF(numpy); if (c_api == NULL) { PyErr_SetString(PyExc_AttributeError, "_UFUNC_API not found"); return -1; } #if PY_VERSION_HEX >= 0x03000000 if (!PyCapsule_CheckExact(c_api)) { PyErr_SetString(PyExc_RuntimeError, "_UFUNC_API is not PyCapsule object"); Py_DECREF(c_api); return -1; } PyUFunc_API = (void **)PyCapsule_GetPointer(c_api, NULL); #else if (!PyCObject_Check(c_api)) { PyErr_SetString(PyExc_RuntimeError, "_UFUNC_API is not PyCObject object"); Py_DECREF(c_api); return -1; } PyUFunc_API = (void **)PyCObject_AsVoidPtr(c_api); #endif Py_DECREF(c_api); if (PyUFunc_API == NULL) { PyErr_SetString(PyExc_RuntimeError, "_UFUNC_API is NULL pointer"); return -1; } return 0; } #if PY_VERSION_HEX >= 0x03000000 #define NUMPY_IMPORT_UMATH_RETVAL NULL #else #define NUMPY_IMPORT_UMATH_RETVAL #endif #define import_umath() \ do {\ UFUNC_NOFPE\ if (_import_umath() < 0) {\ PyErr_Print();\ PyErr_SetString(PyExc_ImportError,\ "numpy.core.umath failed to import");\ return NUMPY_IMPORT_UMATH_RETVAL;\ }\ } while(0) #define import_umath1(ret) \ do {\ UFUNC_NOFPE\ if (_import_umath() < 0) {\ PyErr_Print();\ PyErr_SetString(PyExc_ImportError,\ "numpy.core.umath failed to import");\ return ret;\ }\ } while(0) #define import_umath2(ret, msg) \ do {\ UFUNC_NOFPE\ if (_import_umath() < 0) {\ PyErr_Print();\ PyErr_SetString(PyExc_ImportError, msg);\ return ret;\ }\ } while(0) #define import_ufunc() \ do {\ UFUNC_NOFPE\ if (_import_umath() < 0) {\ PyErr_Print();\ PyErr_SetString(PyExc_ImportError,\ "numpy.core.umath failed to import");\ }\ } while(0) #endif """ c_template = r""" /* These pointers will be stored in the C-object for use in other extension modules */ void *PyUFunc_API[] = { %s }; """ def generate_api(output_dir, force=False): basename = 'ufunc_api' h_file = os.path.join(output_dir, '__%s.h' % basename) c_file = os.path.join(output_dir, '__%s.c' % basename) d_file = os.path.join(output_dir, '%s.txt' % basename) targets = (h_file, c_file, d_file) sources = ['ufunc_api_order.txt'] if (not force and not genapi.should_rebuild(targets, sources + [__file__])): return targets else: do_generate_api(targets, sources) return targets def do_generate_api(targets, sources): header_file = targets[0] c_file = targets[1] doc_file = targets[2] ufunc_api_index = genapi.merge_api_dicts(( numpy_api.ufunc_funcs_api, numpy_api.ufunc_types_api)) genapi.check_api_dict(ufunc_api_index) ufunc_api_list = genapi.get_api_functions('UFUNC_API', numpy_api.ufunc_funcs_api) # Create dict name -> *Api instance ufunc_api_dict = {} 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) for name, index in numpy_api.ufunc_types_api.items(): ufunc_api_dict[name] = TypeApi(name, index, 'PyTypeObject', api_name) # set up object API module_list = [] extension_list = [] init_list = [] for name, index in genapi.order_dict(ufunc_api_index): api_item = ufunc_api_dict[name] extension_list.append(api_item.define_from_array_api_string()) init_list.append(api_item.array_api_define()) module_list.append(api_item.internal_define()) # Write to header fid = open(header_file, 'w') s = h_template % ('\n'.join(module_list), '\n'.join(extension_list)) fid.write(s) fid.close() # Write to c-code fid = open(c_file, 'w') s = c_template % ',\n'.join(init_list) fid.write(s) fid.close() # Write to documentation fid = open(doc_file, 'w') fid.write(''' ================= Numpy Ufunc C-API ================= ''') for func in ufunc_api_list: fid.write(func.to_ReST()) fid.write('\n\n') fid.close() return targets numpy-1.8.2/numpy/core/code_generators/generate_numpy_api.py0000664000175100017510000001645112370216243025523 0ustar vagrantvagrant00000000000000from __future__ import division, print_function import os import genapi from genapi import \ TypeApi, GlobalVarApi, FunctionApi, BoolValuesApi import numpy_api h_template = r""" #ifdef _MULTIARRAYMODULE typedef struct { PyObject_HEAD npy_bool obval; } PyBoolScalarObject; #ifdef NPY_ENABLE_SEPARATE_COMPILATION extern NPY_NO_EXPORT PyTypeObject PyArrayMapIter_Type; extern NPY_NO_EXPORT PyTypeObject PyArrayNeighborhoodIter_Type; extern NPY_NO_EXPORT PyBoolScalarObject _PyArrayScalar_BoolValues[2]; #else NPY_NO_EXPORT PyTypeObject PyArrayMapIter_Type; NPY_NO_EXPORT PyTypeObject PyArrayNeighborhoodIter_Type; NPY_NO_EXPORT PyBoolScalarObject _PyArrayScalar_BoolValues[2]; #endif %s #else #if defined(PY_ARRAY_UNIQUE_SYMBOL) #define PyArray_API PY_ARRAY_UNIQUE_SYMBOL #endif #if defined(NO_IMPORT) || defined(NO_IMPORT_ARRAY) extern void **PyArray_API; #else #if defined(PY_ARRAY_UNIQUE_SYMBOL) void **PyArray_API; #else static void **PyArray_API=NULL; #endif #endif %s #if !defined(NO_IMPORT_ARRAY) && !defined(NO_IMPORT) static int _import_array(void) { int st; PyObject *numpy = PyImport_ImportModule("numpy.core.multiarray"); PyObject *c_api = NULL; if (numpy == NULL) { PyErr_SetString(PyExc_ImportError, "numpy.core.multiarray failed to import"); return -1; } c_api = PyObject_GetAttrString(numpy, "_ARRAY_API"); Py_DECREF(numpy); if (c_api == NULL) { PyErr_SetString(PyExc_AttributeError, "_ARRAY_API not found"); return -1; } #if PY_VERSION_HEX >= 0x03000000 if (!PyCapsule_CheckExact(c_api)) { PyErr_SetString(PyExc_RuntimeError, "_ARRAY_API is not PyCapsule object"); Py_DECREF(c_api); return -1; } PyArray_API = (void **)PyCapsule_GetPointer(c_api, NULL); #else if (!PyCObject_Check(c_api)) { PyErr_SetString(PyExc_RuntimeError, "_ARRAY_API is not PyCObject object"); Py_DECREF(c_api); return -1; } PyArray_API = (void **)PyCObject_AsVoidPtr(c_api); #endif Py_DECREF(c_api); if (PyArray_API == NULL) { PyErr_SetString(PyExc_RuntimeError, "_ARRAY_API is NULL pointer"); return -1; } /* Perform runtime check of C API version */ if (NPY_VERSION != PyArray_GetNDArrayCVersion()) { PyErr_Format(PyExc_RuntimeError, "module compiled against "\ "ABI version %%x but this version of numpy is %%x", \ (int) NPY_VERSION, (int) PyArray_GetNDArrayCVersion()); return -1; } if (NPY_FEATURE_VERSION > PyArray_GetNDArrayCFeatureVersion()) { PyErr_Format(PyExc_RuntimeError, "module compiled against "\ "API version %%x but this version of numpy is %%x", \ (int) NPY_FEATURE_VERSION, (int) PyArray_GetNDArrayCFeatureVersion()); return -1; } /* * Perform runtime check of endianness and check it matches the one set by * the headers (npy_endian.h) as a safeguard */ st = PyArray_GetEndianness(); if (st == NPY_CPU_UNKNOWN_ENDIAN) { PyErr_Format(PyExc_RuntimeError, "FATAL: module compiled as unknown endian"); return -1; } #if NPY_BYTE_ORDER == NPY_BIG_ENDIAN if (st != NPY_CPU_BIG) { PyErr_Format(PyExc_RuntimeError, "FATAL: module compiled as "\ "big endian, but detected different endianness at runtime"); return -1; } #elif NPY_BYTE_ORDER == NPY_LITTLE_ENDIAN if (st != NPY_CPU_LITTLE) { PyErr_Format(PyExc_RuntimeError, "FATAL: module compiled as "\ "little endian, but detected different endianness at runtime"); return -1; } #endif return 0; } #if PY_VERSION_HEX >= 0x03000000 #define NUMPY_IMPORT_ARRAY_RETVAL NULL #else #define NUMPY_IMPORT_ARRAY_RETVAL #endif #define import_array() {if (_import_array() < 0) {PyErr_Print(); PyErr_SetString(PyExc_ImportError, "numpy.core.multiarray failed to import"); return NUMPY_IMPORT_ARRAY_RETVAL; } } #define import_array1(ret) {if (_import_array() < 0) {PyErr_Print(); PyErr_SetString(PyExc_ImportError, "numpy.core.multiarray failed to import"); return ret; } } #define import_array2(msg, ret) {if (_import_array() < 0) {PyErr_Print(); PyErr_SetString(PyExc_ImportError, msg); return ret; } } #endif #endif """ c_template = r""" /* These pointers will be stored in the C-object for use in other extension modules */ void *PyArray_API[] = { %s }; """ c_api_header = """ =========== Numpy C-API =========== """ def generate_api(output_dir, force=False): basename = 'multiarray_api' h_file = os.path.join(output_dir, '__%s.h' % basename) c_file = os.path.join(output_dir, '__%s.c' % basename) d_file = os.path.join(output_dir, '%s.txt' % basename) targets = (h_file, c_file, d_file) sources = numpy_api.multiarray_api if (not force and not genapi.should_rebuild(targets, [numpy_api.__file__, __file__])): return targets else: do_generate_api(targets, sources) return targets def do_generate_api(targets, sources): header_file = targets[0] c_file = targets[1] 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] # Remove global_vars_type: not a api dict multiarray_api = sources[:1] + sources[2:] module_list = [] extension_list = [] init_list = [] # Check multiarray api indexes multiarray_api_index = genapi.merge_api_dicts(multiarray_api) genapi.check_api_dict(multiarray_api_index) numpyapi_list = genapi.get_api_functions('NUMPY_API', multiarray_funcs) ordered_funcs_api = genapi.order_dict(multiarray_funcs) # Create dict name -> *Api instance api_name = 'PyArray_API' 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, f.args, api_name) for name, index in global_vars.items(): type = global_vars_types[name] multiarray_api_dict[name] = GlobalVarApi(name, index, type, api_name) for name, index in scalar_bool_values.items(): multiarray_api_dict[name] = BoolValuesApi(name, index, api_name) for name, index in types_api.items(): multiarray_api_dict[name] = TypeApi(name, index, 'PyTypeObject', api_name) if len(multiarray_api_dict) != len(multiarray_api_index): raise AssertionError("Multiarray API size mismatch %d %d" % (len(multiarray_api_dict), len(multiarray_api_index))) extension_list = [] for name, index in genapi.order_dict(multiarray_api_index): api_item = multiarray_api_dict[name] extension_list.append(api_item.define_from_array_api_string()) init_list.append(api_item.array_api_define()) module_list.append(api_item.internal_define()) # Write to header fid = open(header_file, 'w') s = h_template % ('\n'.join(module_list), '\n'.join(extension_list)) fid.write(s) fid.close() # Write to c-code fid = open(c_file, 'w') s = c_template % ',\n'.join(init_list) fid.write(s) fid.close() # write to documentation fid = open(doc_file, 'w') fid.write(c_api_header) for func in numpyapi_list: fid.write(func.to_ReST()) fid.write('\n\n') fid.close() return targets numpy-1.8.2/numpy/core/code_generators/cversions.py0000664000175100017510000000057212370216243023660 0ustar vagrantvagrant00000000000000"""Simple script to compute the api hash of the current API. The API has is defined by numpy_api_order and ufunc_api_order. """ from __future__ import division, absolute_import, print_function from os.path import dirname from genapi import fullapi_hash import numpy_api if __name__ == '__main__': curdir = dirname(__file__) print(fullapi_hash(numpy_api.full_api)) numpy-1.8.2/numpy/core/code_generators/genapi.py0000664000175100017510000003737212370216243023120 0ustar vagrantvagrant00000000000000""" Get API information encoded in C files. See ``find_function`` for how functions should be formatted, and ``read_order`` for how the order of the functions should be specified. """ from __future__ import division, absolute_import, print_function import sys, os, re try: import hashlib md5new = hashlib.md5 except ImportError: import md5 md5new = md5.new import textwrap 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'), join('multiarray', 'array_assign_scalar.c'), join('multiarray', 'arrayobject.c'), join('multiarray', 'arraytypes.c.src'), join('multiarray', 'buffer.c'), join('multiarray', 'calculation.c'), join('multiarray', 'conversion_utils.c'), join('multiarray', 'convert.c'), join('multiarray', 'convert_datatype.c'), join('multiarray', 'ctors.c'), join('multiarray', 'datetime.c'), join('multiarray', 'datetime_busday.c'), join('multiarray', 'datetime_busdaycal.c'), join('multiarray', 'datetime_strings.c'), join('multiarray', 'descriptor.c'), join('multiarray', 'einsum.c.src'), join('multiarray', 'flagsobject.c'), join('multiarray', 'getset.c'), join('multiarray', 'item_selection.c'), join('multiarray', 'iterators.c'), join('multiarray', 'mapping.c'), join('multiarray', 'methods.c'), join('multiarray', 'multiarraymodule.c'), join('multiarray', 'nditer_api.c'), join('multiarray', 'nditer_constr.c'), join('multiarray', 'nditer_pywrap.c'), join('multiarray', 'nditer_templ.c.src'), join('multiarray', 'number.c'), join('multiarray', 'refcount.c'), join('multiarray', 'scalartypes.c.src'), join('multiarray', 'scalarapi.c'), join('multiarray', 'sequence.c'), join('multiarray', 'shape.c'), join('multiarray', 'usertypes.c'), join('umath', 'loops.c.src'), join('umath', 'ufunc_object.c'), join('umath', 'ufunc_type_resolution.c'), join('umath', 'reduction.c'), ] THIS_DIR = os.path.dirname(__file__) API_FILES = [os.path.join(THIS_DIR, '..', 'src', a) for a in API_FILES] def file_in_this_dir(filename): return os.path.join(THIS_DIR, filename) def remove_whitespace(s): return ''.join(s.split()) def _repl(str): return str.replace('Bool', 'npy_bool') class Function(object): def __init__(self, name, return_type, args, doc=''): self.name = name self.return_type = _repl(return_type) self.args = args self.doc = doc def _format_arg(self, typename, name): if typename.endswith('*'): return typename + name else: return typename + ' ' + name def __str__(self): argstr = ', '.join([self._format_arg(*a) for a in self.args]) if self.doc: doccomment = '/* %s */\n' % self.doc else: doccomment = '' return '%s%s %s(%s)' % (doccomment, self.return_type, self.name, argstr) def to_ReST(self): lines = ['::', '', ' ' + self.return_type] argstr = ',\000'.join([self._format_arg(*a) for a in self.args]) name = ' %s' % (self.name,) s = textwrap.wrap('(%s)' % (argstr,), width=72, initial_indent=name, subsequent_indent=' ' * (len(name)+1), break_long_words=False) for l in s: lines.append(l.replace('\000', ' ').rstrip()) lines.append('') if self.doc: lines.append(textwrap.dedent(self.doc)) return '\n'.join(lines) def api_hash(self): m = md5new() m.update(remove_whitespace(self.return_type)) m.update('\000') m.update(self.name) m.update('\000') for typename, name in self.args: m.update(remove_whitespace(typename)) m.update('\000') return m.hexdigest()[:8] class ParseError(Exception): def __init__(self, filename, lineno, msg): self.filename = filename self.lineno = lineno self.msg = msg def __str__(self): return '%s:%s:%s' % (self.filename, self.lineno, self.msg) def skip_brackets(s, lbrac, rbrac): count = 0 for i, c in enumerate(s): if c == lbrac: count += 1 elif c == rbrac: count -= 1 if count == 0: return i raise ValueError("no match '%s' for '%s' (%r)" % (lbrac, rbrac, s)) def split_arguments(argstr): arguments = [] bracket_counts = {'(': 0, '[': 0} current_argument = [] state = 0 i = 0 def finish_arg(): if current_argument: argstr = ''.join(current_argument).strip() m = re.match(r'(.*(\s+|[*]))(\w+)$', argstr) if m: typename = m.group(1).strip() name = m.group(3) else: typename = argstr name = '' arguments.append((typename, name)) del current_argument[:] while i < len(argstr): c = argstr[i] if c == ',': finish_arg() elif c == '(': p = skip_brackets(argstr[i:], '(', ')') current_argument += argstr[i:i+p] i += p-1 else: current_argument += c i += 1 finish_arg() return arguments def find_functions(filename, tag='API'): """ Scan the file, looking for tagged functions. Assuming ``tag=='API'``, a tagged function looks like:: /*API*/ static returntype* function_name(argtype1 arg1, argtype2 arg2) { } where the return type must be on a separate line, the function name must start the line, and the opening ``{`` must start the line. An optional documentation comment in ReST format may follow the tag, as in:: /*API This function does foo... */ """ fo = open(filename, 'r') functions = [] return_type = None function_name = None function_args = [] doclist = [] SCANNING, STATE_DOC, STATE_RETTYPE, STATE_NAME, STATE_ARGS = list(range(5)) state = SCANNING tagcomment = '/*' + tag for lineno, line in enumerate(fo): try: line = line.strip() if state == SCANNING: if line.startswith(tagcomment): if line.endswith('*/'): state = STATE_RETTYPE else: state = STATE_DOC elif state == STATE_DOC: if line.startswith('*/'): state = STATE_RETTYPE else: line = line.lstrip(' *') doclist.append(line) elif state == STATE_RETTYPE: # first line of declaration with return type m = re.match(r'NPY_NO_EXPORT\s+(.*)$', line) if m: line = m.group(1) return_type = line state = STATE_NAME elif state == STATE_NAME: # second line, with function name m = re.match(r'(\w+)\s*\(', line) if m: function_name = m.group(1) else: raise ParseError(filename, lineno+1, 'could not find function name') function_args.append(line[m.end():]) state = STATE_ARGS elif state == STATE_ARGS: if line.startswith('{'): # finished fargs_str = ' '.join(function_args).rstrip(' )') fargs = split_arguments(fargs_str) f = Function(function_name, return_type, fargs, '\n'.join(doclist)) functions.append(f) return_type = None function_name = None function_args = [] doclist = [] state = SCANNING else: function_args.append(line) except: print(filename, lineno + 1) raise fo.close() return functions def should_rebuild(targets, source_files): from distutils.dep_util import newer_group for t in targets: if not os.path.exists(t): return True sources = API_FILES + list(source_files) + [__file__] if newer_group(sources, targets[0], missing='newer'): return True return False # Those *Api classes instances know how to output strings for the generated code class TypeApi(object): def __init__(self, name, index, ptr_cast, api_name): self.index = index self.name = name self.ptr_cast = ptr_cast self.api_name = api_name def define_from_array_api_string(self): return "#define %s (*(%s *)%s[%d])" % (self.name, self.ptr_cast, self.api_name, self.index) def array_api_define(self): return " (void *) &%s" % self.name def internal_define(self): astr = """\ #ifdef NPY_ENABLE_SEPARATE_COMPILATION extern NPY_NO_EXPORT PyTypeObject %(type)s; #else NPY_NO_EXPORT PyTypeObject %(type)s; #endif """ % {'type': self.name} return astr class GlobalVarApi(object): def __init__(self, name, index, type, api_name): self.name = name self.index = index self.type = type self.api_name = api_name def define_from_array_api_string(self): return "#define %s (*(%s *)%s[%d])" % (self.name, self.type, self.api_name, self.index) def array_api_define(self): return " (%s *) &%s" % (self.type, self.name) def internal_define(self): astr = """\ #ifdef NPY_ENABLE_SEPARATE_COMPILATION extern NPY_NO_EXPORT %(type)s %(name)s; #else NPY_NO_EXPORT %(type)s %(name)s; #endif """ % {'type': self.type, 'name': self.name} return astr # Dummy to be able to consistently use *Api instances for all items in the # array api class BoolValuesApi(object): def __init__(self, name, index, api_name): self.name = name self.index = index self.type = 'PyBoolScalarObject' self.api_name = api_name def define_from_array_api_string(self): return "#define %s ((%s *)%s[%d])" % (self.name, self.type, self.api_name, self.index) def array_api_define(self): return " (void *) &%s" % self.name def internal_define(self): astr = """\ #ifdef NPY_ENABLE_SEPARATE_COMPILATION extern NPY_NO_EXPORT PyBoolScalarObject _PyArrayScalar_BoolValues[2]; #else NPY_NO_EXPORT PyBoolScalarObject _PyArrayScalar_BoolValues[2]; #endif """ return astr class FunctionApi(object): def __init__(self, name, index, return_type, args, api_name): self.name = name self.index = index self.return_type = return_type self.args = args self.api_name = api_name def _argtypes_string(self): if not self.args: return 'void' argstr = ', '.join([_repl(a[0]) for a in self.args]) return argstr def define_from_array_api_string(self): define = """\ #define %s \\\n (*(%s (*)(%s)) \\ %s[%d])""" % (self.name, self.return_type, self._argtypes_string(), self.api_name, self.index) return define def array_api_define(self): return " (void *) %s" % self.name def internal_define(self): astr = """\ NPY_NO_EXPORT %s %s \\\n (%s);""" % (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 sorted(o, key=_key) def merge_api_dicts(dicts): ret = {} for d in dicts: for k, v in d.items(): ret[k] = v return ret def check_api_dict(d): """Check that an api dict is valid (does not use the same index twice).""" # We have if a same index is used twice: we 'revert' the dict so that index # become keys. If the length is different, it means one index has been used # at least twice revert_dict = dict([(v, k) for k, v in d.items()]) if not len(revert_dict) == len(d): # We compute a dict index -> list of associated items doubled = {} for name, index in d.items(): try: doubled[index].append(name) except KeyError: doubled[index] = [name] msg = """\ Same index has been used twice in api definition: %s """ % ['index %d -> %s' % (index, names) for index, names in doubled.items() \ if len(names) != 1] raise ValueError(msg) # No 'hole' in the indexes may be allowed, and it must starts at 0 indexes = set(d.values()) expected = set(range(len(indexes))) if not indexes == expected: diff = expected.symmetric_difference(indexes) msg = "There are some holes in the API indexing: " \ "(symmetric diff is %s)" % diff raise ValueError(msg) def get_api_functions(tagname, api_dict): """Parse source files to get functions tagged by the given tag.""" functions = [] for f in API_FILES: functions.extend(find_functions(f, tagname)) dfunctions = [] for func in functions: o = api_dict[func.name] dfunctions.append( (o, func) ) dfunctions.sort() return [a[1] for a in dfunctions] def fullapi_hash(api_dicts): """Given a list of api dicts defining the numpy C API, compute a checksum 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): a.extend(name) a.extend(str(index)) return md5new(''.join(a).encode('ascii')).hexdigest() # To parse strings like 'hex = checksum' where hex is e.g. 0x1234567F and # checksum a 128 bits md5 checksum (hex format as well) VERRE = re.compile('(^0x[\da-f]{8})\s*=\s*([\da-f]{32})') def get_versions_hash(): d = [] file = os.path.join(os.path.dirname(__file__), 'cversions.txt') fid = open(file, 'r') try: for line in fid: m = VERRE.match(line) if m: d.append((int(m.group(1), 16), m.group(2))) finally: fid.close() return dict(d) def main(): tagname = sys.argv[1] order_file = sys.argv[2] functions = get_api_functions(tagname, order_file) m = md5new(tagname) for func in functions: print(func) ah = func.api_hash() m.update(ah) print(hex(int(ah, 16))) print(hex(int(m.hexdigest()[:8], 16))) if __name__ == '__main__': main() numpy-1.8.2/numpy/core/code_generators/numpy_api.py0000664000175100017510000004352612370216243023654 0ustar vagrantvagrant00000000000000"""Here we define the exported functions, types, etc... which need to be exported through a global C pointer. Each dictionary contains name -> index pair. Whenever you change one index, you break the ABI (and the ABI version number should be incremented). Whenever you add an item to one of the dict, the API needs to be updated. When adding a function, make sure to use the next integer not used as an index (in case you use an existing index or jump, the build will stop and raise an 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, } multiarray_global_vars_types = { 'NPY_NUMUSERTYPES': 'int', 'NPY_DEFAULT_ASSIGN_CASTING': 'NPY_CASTING', } multiarray_scalar_bool_values = { '_PyArrayScalar_BoolValues': 9 } 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, # End 1.5 API 'PyTimeIntegerArrType_Type': 214, 'PyDatetimeArrType_Type': 215, 'PyTimedeltaArrType_Type': 216, 'PyHalfArrType_Type': 217, 'NpyIter_Type': 218, # End 1.6 API } #define NPY_NUMUSERTYPES (*(int *)PyArray_API[6]) #define PyBoolArrType_Type (*(PyTypeObject *)PyArray_API[7]) #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, # End 1.5 API '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, # '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, # 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, # End 1.7 API 'PyArray_Partition': 296, 'PyArray_ArgPartition': 297, 'PyArray_SelectkindConverter': 298, 'PyDataMem_NEW_ZEROED': 299, # End 1.8 API } ufunc_types_api = { '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, # 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, # End 1.6 API 'PyUFunc_DefaultTypeResolver': 39, 'PyUFunc_ValidateCasting': 40, # End 1.7 API 'PyUFunc_RegisterLoopForDescr': 41, # End 1.8 API } # List of all the dicts which define the C 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, ) ufunc_api = ( ufunc_funcs_api, ufunc_types_api ) full_api = multiarray_api + ufunc_api numpy-1.8.2/numpy/core/code_generators/generate_umath.py0000664000175100017510000007141112370216243024635 0ustar vagrantvagrant00000000000000from __future__ import division, print_function import os import re import struct import sys import textwrap sys.path.insert(0, os.path.dirname(__file__)) import ufunc_docstrings as docstrings sys.path.pop(0) Zero = "PyUFunc_Zero" One = "PyUFunc_One" None_ = "PyUFunc_None" ReorderableNone = "PyUFunc_ReorderableNone" # Sentinel value to specify using the full type description in the # function name class FullTypeDescr(object): pass class TypeDescription(object): """Type signature for a ufunc. Attributes ---------- type : str Character representing the nominal type. func_data : str or None or FullTypeDescr, optional The string representing the expression to insert into the data array, if any. in_ : str or None, optional The typecode(s) of the inputs. out : str or None, optional The typecode(s) of the outputs. astype : dict or None, optional If astype['x'] is 'y', uses PyUFunc_x_x_As_y_y/PyUFunc_xx_x_As_yy_y instead of PyUFunc_x_x/PyUFunc_xx_x. """ def __init__(self, type, f=None, in_=None, out=None, astype=None): self.type = type self.func_data = f if astype is None: astype = {} self.astype_dict = astype if in_ is not None: in_ = in_.replace('P', type) self.in_ = in_ if out is not None: out = out.replace('P', type) self.out = out def finish_signature(self, nin, nout): if self.in_ is None: self.in_ = self.type * nin assert len(self.in_) == nin if self.out is None: self.out = self.type * nout assert len(self.out) == nout self.astype = self.astype_dict.get(self.type, None) _fdata_map = dict(e='npy_%sf', f='npy_%sf', d='npy_%s', g='npy_%sl', F='nc_%sf', D='nc_%s', G='nc_%sl') def build_func_data(types, f): func_data = [] for t in types: d = _fdata_map.get(t, '%s') % (f,) func_data.append(d) return func_data def TD(types, f=None, astype=None, in_=None, out=None): if f is not None: if isinstance(f, str): func_data = build_func_data(types, f) else: assert len(f) == len(types) func_data = f else: func_data = (None,) * len(types) if isinstance(in_, str): in_ = (in_,) * len(types) elif in_ is None: in_ = (None,) * len(types) if isinstance(out, str): out = (out,) * len(types) elif out is None: out = (None,) * len(types) tds = [] for t, fd, i, o in zip(types, func_data, in_, out): tds.append(TypeDescription(t, f=fd, in_=i, out=o, astype=astype)) return tds class Ufunc(object): """Description of a ufunc. Attributes ---------- nin : number of input arguments nout : number of output arguments identity : identity element for a two-argument function docstring : docstring for the ufunc type_descriptions : list of TypeDescription objects """ def __init__(self, nin, nout, identity, docstring, typereso, *type_descriptions): self.nin = nin self.nout = nout if identity is None: identity = None_ self.identity = identity self.docstring = docstring self.typereso = typereso self.type_descriptions = [] for td in type_descriptions: self.type_descriptions.extend(td) for td in self.type_descriptions: td.finish_signature(self.nin, self.nout) # String-handling utilities to avoid locale-dependence. import string if sys.version_info[0] < 3: UPPER_TABLE = string.maketrans(string.ascii_lowercase, string.ascii_uppercase) else: UPPER_TABLE = bytes.maketrans(bytes(string.ascii_lowercase, "ascii"), bytes(string.ascii_uppercase, "ascii")) def english_upper(s): """ Apply English case rules to convert ASCII strings to all upper case. This is an internal utility function to replace calls to str.upper() such that we can avoid changing behavior with changing locales. In particular, Turkish has distinct dotted and dotless variants of the Latin letter "I" in both lowercase and uppercase. Thus, "i".upper() != "I" in a "tr" locale. Parameters ---------- s : str Returns ------- uppered : str Examples -------- >>> from numpy.lib.utils import english_upper >>> english_upper('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_') 'ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_' >>> english_upper('') '' """ uppered = s.translate(UPPER_TABLE) return uppered #each entry in defdict is a Ufunc object. #name: [string of chars for which it is defined, # string of characters using func interface, # tuple of strings giving funcs for data, # (in, out), or (instr, outstr) giving the signature as character codes, # identity, # docstring, # output specification (optional) # ] chartoname = {'?': 'bool', 'b': 'byte', 'B': 'ubyte', 'h': 'short', 'H': 'ushort', 'i': 'int', 'I': 'uint', 'l': 'long', 'L': 'ulong', 'q': 'longlong', 'Q': 'ulonglong', 'e': 'half', 'f': 'float', 'd': 'double', 'g': 'longdouble', 'F': 'cfloat', 'D': 'cdouble', 'G': 'clongdouble', 'M': 'datetime', 'm': 'timedelta', 'O': 'OBJECT', # '.' is like 'O', but calls a method of the object instead # of a function 'P': 'OBJECT', } all = '?bBhHiIlLqQefdgFDGOMm' O = 'O' P = 'P' ints = 'bBhHiIlLqQ' times = 'Mm' timedeltaonly = 'm' intsO = ints + O bints = '?' + ints bintsO = bints + O flts = 'efdg' fltsO = flts + O fltsP = flts + P cmplx = 'FDG' cmplxO = cmplx + O cmplxP = cmplx + P inexact = flts + cmplx inexactvec = 'fd' noint = inexact+O nointP = inexact+P allP = bints+times+flts+cmplxP nobool = all[1:] noobj = all[:-3]+all[-2:] nobool_or_obj = all[1:-3]+all[-2:] nobool_or_datetime = all[1:-2]+all[-1:] intflt = ints+flts intfltcmplx = ints+flts+cmplx nocmplx = bints+times+flts nocmplxO = nocmplx+O nocmplxP = nocmplx+P notimes_or_obj = bints + inexact nodatetime_or_obj = bints + inexact # Find which code corresponds to int64. int64 = '' uint64 = '' for code in 'bhilq': if struct.calcsize(code) == 8: int64 = code uint64 = english_upper(code) break # This dictionary describes all the ufunc implementations, generating # all the function names and their corresponding ufunc signatures. TD is # an object which expands a list of character codes into an array of # TypeDescriptions. defdict = { 'add': Ufunc(2, 1, Zero, docstrings.get('numpy.core.umath.add'), 'PyUFunc_AdditionTypeResolver', TD(notimes_or_obj), [TypeDescription('M', FullTypeDescr, 'Mm', 'M'), TypeDescription('m', FullTypeDescr, 'mm', 'm'), TypeDescription('M', FullTypeDescr, 'mM', 'M'), ], TD(O, f='PyNumber_Add'), ), 'subtract': Ufunc(2, 1, None, # Zero is only a unit to the right, not the left docstrings.get('numpy.core.umath.subtract'), 'PyUFunc_SubtractionTypeResolver', TD(notimes_or_obj), [TypeDescription('M', FullTypeDescr, 'Mm', 'M'), TypeDescription('m', FullTypeDescr, 'mm', 'm'), TypeDescription('M', FullTypeDescr, 'MM', 'm'), ], TD(O, f='PyNumber_Subtract'), ), 'multiply': Ufunc(2, 1, One, docstrings.get('numpy.core.umath.multiply'), 'PyUFunc_MultiplicationTypeResolver', TD(notimes_or_obj), [TypeDescription('m', FullTypeDescr, 'mq', 'm'), TypeDescription('m', FullTypeDescr, 'qm', 'm'), TypeDescription('m', FullTypeDescr, 'md', 'm'), TypeDescription('m', FullTypeDescr, 'dm', 'm'), ], TD(O, f='PyNumber_Multiply'), ), 'divide': Ufunc(2, 1, None, # One is only a unit to the right, not the left docstrings.get('numpy.core.umath.divide'), 'PyUFunc_DivisionTypeResolver', TD(intfltcmplx), [TypeDescription('m', FullTypeDescr, 'mq', 'm'), TypeDescription('m', FullTypeDescr, 'md', 'm'), TypeDescription('m', FullTypeDescr, 'mm', 'd'), ], TD(O, f='PyNumber_Divide'), ), 'floor_divide': Ufunc(2, 1, None, # One is only a unit to the right, not the left docstrings.get('numpy.core.umath.floor_divide'), 'PyUFunc_DivisionTypeResolver', TD(intfltcmplx), [TypeDescription('m', FullTypeDescr, 'mq', 'm'), TypeDescription('m', FullTypeDescr, 'md', 'm'), #TypeDescription('m', FullTypeDescr, 'mm', 'd'), ], TD(O, f='PyNumber_FloorDivide'), ), 'true_divide': Ufunc(2, 1, None, # One is only a unit to the right, not the left docstrings.get('numpy.core.umath.true_divide'), 'PyUFunc_DivisionTypeResolver', TD('bBhH', out='d'), TD('iIlLqQ', out='d'), TD(flts+cmplx), [TypeDescription('m', FullTypeDescr, 'mq', 'm'), TypeDescription('m', FullTypeDescr, 'md', 'm'), TypeDescription('m', FullTypeDescr, 'mm', 'd'), ], TD(O, f='PyNumber_TrueDivide'), ), 'conjugate': Ufunc(1, 1, None, docstrings.get('numpy.core.umath.conjugate'), None, TD(ints+flts+cmplx), TD(P, f='conjugate'), ), 'fmod': Ufunc(2, 1, None, docstrings.get('numpy.core.umath.fmod'), None, TD(ints), TD(flts, f='fmod', astype={'e':'f'}), TD(P, f='fmod'), ), 'square': Ufunc(1, 1, None, docstrings.get('numpy.core.umath.square'), None, TD(ints+inexact), TD(O, f='Py_square'), ), 'reciprocal': Ufunc(1, 1, None, docstrings.get('numpy.core.umath.reciprocal'), None, TD(ints+inexact), TD(O, f='Py_reciprocal'), ), # This is no longer used as numpy.ones_like, however it is # still used by some internal calls. '_ones_like': Ufunc(1, 1, None, docstrings.get('numpy.core.umath._ones_like'), 'PyUFunc_OnesLikeTypeResolver', TD(noobj), TD(O, f='Py_get_one'), ), 'power': Ufunc(2, 1, None, docstrings.get('numpy.core.umath.power'), None, TD(ints), TD(inexact, f='pow', astype={'e':'f'}), TD(O, f='npy_ObjectPower'), ), 'absolute': Ufunc(1, 1, None, docstrings.get('numpy.core.umath.absolute'), 'PyUFunc_AbsoluteTypeResolver', TD(bints+flts+timedeltaonly), TD(cmplx, out=('f', 'd', 'g')), TD(O, f='PyNumber_Absolute'), ), '_arg': Ufunc(1, 1, None, docstrings.get('numpy.core.umath._arg'), None, TD(cmplx, out=('f', 'd', 'g')), ), 'negative': Ufunc(1, 1, None, docstrings.get('numpy.core.umath.negative'), 'PyUFunc_SimpleUnaryOperationTypeResolver', TD(bints+flts+timedeltaonly), TD(cmplx, f='neg'), TD(O, f='PyNumber_Negative'), ), 'sign': Ufunc(1, 1, None, docstrings.get('numpy.core.umath.sign'), 'PyUFunc_SimpleUnaryOperationTypeResolver', TD(nobool_or_datetime), ), 'greater': Ufunc(2, 1, None, docstrings.get('numpy.core.umath.greater'), 'PyUFunc_SimpleBinaryComparisonTypeResolver', TD(all, out='?'), ), 'greater_equal': Ufunc(2, 1, None, docstrings.get('numpy.core.umath.greater_equal'), 'PyUFunc_SimpleBinaryComparisonTypeResolver', TD(all, out='?'), ), 'less': Ufunc(2, 1, None, docstrings.get('numpy.core.umath.less'), 'PyUFunc_SimpleBinaryComparisonTypeResolver', TD(all, out='?'), ), 'less_equal': Ufunc(2, 1, None, docstrings.get('numpy.core.umath.less_equal'), 'PyUFunc_SimpleBinaryComparisonTypeResolver', TD(all, out='?'), ), 'equal': Ufunc(2, 1, None, docstrings.get('numpy.core.umath.equal'), 'PyUFunc_SimpleBinaryComparisonTypeResolver', TD(all, out='?'), ), 'not_equal': Ufunc(2, 1, None, docstrings.get('numpy.core.umath.not_equal'), 'PyUFunc_SimpleBinaryComparisonTypeResolver', TD(all, out='?'), ), 'logical_and': Ufunc(2, 1, One, docstrings.get('numpy.core.umath.logical_and'), 'PyUFunc_SimpleBinaryComparisonTypeResolver', TD(nodatetime_or_obj, out='?'), TD(O, f='npy_ObjectLogicalAnd'), ), 'logical_not': Ufunc(1, 1, None, docstrings.get('numpy.core.umath.logical_not'), None, TD(nodatetime_or_obj, out='?'), TD(O, f='npy_ObjectLogicalNot'), ), 'logical_or': Ufunc(2, 1, Zero, docstrings.get('numpy.core.umath.logical_or'), 'PyUFunc_SimpleBinaryComparisonTypeResolver', TD(nodatetime_or_obj, out='?'), TD(O, f='npy_ObjectLogicalOr'), ), 'logical_xor': Ufunc(2, 1, None, docstrings.get('numpy.core.umath.logical_xor'), 'PyUFunc_SimpleBinaryComparisonTypeResolver', TD(nodatetime_or_obj, out='?'), TD(P, f='logical_xor'), ), 'maximum': Ufunc(2, 1, ReorderableNone, docstrings.get('numpy.core.umath.maximum'), 'PyUFunc_SimpleBinaryOperationTypeResolver', TD(noobj), TD(O, f='npy_ObjectMax') ), 'minimum': Ufunc(2, 1, ReorderableNone, docstrings.get('numpy.core.umath.minimum'), 'PyUFunc_SimpleBinaryOperationTypeResolver', TD(noobj), TD(O, f='npy_ObjectMin') ), 'fmax': Ufunc(2, 1, ReorderableNone, docstrings.get('numpy.core.umath.fmax'), 'PyUFunc_SimpleBinaryOperationTypeResolver', TD(noobj), TD(O, f='npy_ObjectMax') ), 'fmin': Ufunc(2, 1, ReorderableNone, docstrings.get('numpy.core.umath.fmin'), 'PyUFunc_SimpleBinaryOperationTypeResolver', TD(noobj), TD(O, f='npy_ObjectMin') ), 'logaddexp': Ufunc(2, 1, None, docstrings.get('numpy.core.umath.logaddexp'), None, TD(flts, f="logaddexp", astype={'e':'f'}) ), 'logaddexp2': Ufunc(2, 1, None, docstrings.get('numpy.core.umath.logaddexp2'), None, TD(flts, f="logaddexp2", astype={'e':'f'}) ), 'bitwise_and': Ufunc(2, 1, One, docstrings.get('numpy.core.umath.bitwise_and'), None, TD(bints), TD(O, f='PyNumber_And'), ), 'bitwise_or': Ufunc(2, 1, Zero, docstrings.get('numpy.core.umath.bitwise_or'), None, TD(bints), TD(O, f='PyNumber_Or'), ), 'bitwise_xor': Ufunc(2, 1, None, docstrings.get('numpy.core.umath.bitwise_xor'), None, TD(bints), TD(O, f='PyNumber_Xor'), ), 'invert': Ufunc(1, 1, None, docstrings.get('numpy.core.umath.invert'), None, TD(bints), TD(O, f='PyNumber_Invert'), ), 'left_shift': Ufunc(2, 1, None, docstrings.get('numpy.core.umath.left_shift'), None, TD(ints), TD(O, f='PyNumber_Lshift'), ), 'right_shift': Ufunc(2, 1, None, docstrings.get('numpy.core.umath.right_shift'), None, TD(ints), TD(O, f='PyNumber_Rshift'), ), 'degrees': Ufunc(1, 1, None, docstrings.get('numpy.core.umath.degrees'), None, TD(fltsP, f='degrees', astype={'e':'f'}), ), 'rad2deg': Ufunc(1, 1, None, docstrings.get('numpy.core.umath.rad2deg'), None, TD(fltsP, f='rad2deg', astype={'e':'f'}), ), 'radians': Ufunc(1, 1, None, docstrings.get('numpy.core.umath.radians'), None, TD(fltsP, f='radians', astype={'e':'f'}), ), 'deg2rad': Ufunc(1, 1, None, docstrings.get('numpy.core.umath.deg2rad'), None, TD(fltsP, f='deg2rad', astype={'e':'f'}), ), 'arccos': Ufunc(1, 1, None, docstrings.get('numpy.core.umath.arccos'), None, TD(inexact, f='acos', astype={'e':'f'}), TD(P, f='arccos'), ), 'arccosh': Ufunc(1, 1, None, docstrings.get('numpy.core.umath.arccosh'), None, TD(inexact, f='acosh', astype={'e':'f'}), TD(P, f='arccosh'), ), 'arcsin': Ufunc(1, 1, None, docstrings.get('numpy.core.umath.arcsin'), None, TD(inexact, f='asin', astype={'e':'f'}), TD(P, f='arcsin'), ), 'arcsinh': Ufunc(1, 1, None, docstrings.get('numpy.core.umath.arcsinh'), None, TD(inexact, f='asinh', astype={'e':'f'}), TD(P, f='arcsinh'), ), 'arctan': Ufunc(1, 1, None, docstrings.get('numpy.core.umath.arctan'), None, TD(inexact, f='atan', astype={'e':'f'}), TD(P, f='arctan'), ), 'arctanh': Ufunc(1, 1, None, docstrings.get('numpy.core.umath.arctanh'), None, TD(inexact, f='atanh', astype={'e':'f'}), TD(P, f='arctanh'), ), 'cos': Ufunc(1, 1, None, docstrings.get('numpy.core.umath.cos'), None, TD(inexact, f='cos', astype={'e':'f'}), TD(P, f='cos'), ), 'sin': Ufunc(1, 1, None, docstrings.get('numpy.core.umath.sin'), None, TD(inexact, f='sin', astype={'e':'f'}), TD(P, f='sin'), ), 'tan': Ufunc(1, 1, None, docstrings.get('numpy.core.umath.tan'), None, TD(inexact, f='tan', astype={'e':'f'}), TD(P, f='tan'), ), 'cosh': Ufunc(1, 1, None, docstrings.get('numpy.core.umath.cosh'), None, TD(inexact, f='cosh', astype={'e':'f'}), TD(P, f='cosh'), ), 'sinh': Ufunc(1, 1, None, docstrings.get('numpy.core.umath.sinh'), None, TD(inexact, f='sinh', astype={'e':'f'}), TD(P, f='sinh'), ), 'tanh': Ufunc(1, 1, None, docstrings.get('numpy.core.umath.tanh'), None, TD(inexact, f='tanh', astype={'e':'f'}), TD(P, f='tanh'), ), 'exp': Ufunc(1, 1, None, docstrings.get('numpy.core.umath.exp'), None, TD(inexact, f='exp', astype={'e':'f'}), TD(P, f='exp'), ), 'exp2': Ufunc(1, 1, None, docstrings.get('numpy.core.umath.exp2'), None, TD(inexact, f='exp2', astype={'e':'f'}), TD(P, f='exp2'), ), 'expm1': Ufunc(1, 1, None, docstrings.get('numpy.core.umath.expm1'), None, TD(inexact, f='expm1', astype={'e':'f'}), TD(P, f='expm1'), ), 'log': Ufunc(1, 1, None, docstrings.get('numpy.core.umath.log'), None, TD(inexact, f='log', astype={'e':'f'}), TD(P, f='log'), ), 'log2': Ufunc(1, 1, None, docstrings.get('numpy.core.umath.log2'), None, TD(inexact, f='log2', astype={'e':'f'}), TD(P, f='log2'), ), 'log10': Ufunc(1, 1, None, docstrings.get('numpy.core.umath.log10'), None, TD(inexact, f='log10', astype={'e':'f'}), TD(P, f='log10'), ), 'log1p': Ufunc(1, 1, None, docstrings.get('numpy.core.umath.log1p'), None, TD(inexact, f='log1p', astype={'e':'f'}), TD(P, f='log1p'), ), 'sqrt': Ufunc(1, 1, None, docstrings.get('numpy.core.umath.sqrt'), None, TD(inexactvec), TD(inexact, f='sqrt', astype={'e':'f'}), TD(P, f='sqrt'), ), 'ceil': Ufunc(1, 1, None, docstrings.get('numpy.core.umath.ceil'), None, TD(flts, f='ceil', astype={'e':'f'}), TD(P, f='ceil'), ), 'trunc': Ufunc(1, 1, None, docstrings.get('numpy.core.umath.trunc'), None, TD(flts, f='trunc', astype={'e':'f'}), TD(P, f='trunc'), ), 'fabs': Ufunc(1, 1, None, docstrings.get('numpy.core.umath.fabs'), None, TD(flts, f='fabs', astype={'e':'f'}), TD(P, f='fabs'), ), 'floor': Ufunc(1, 1, None, docstrings.get('numpy.core.umath.floor'), None, TD(flts, f='floor', astype={'e':'f'}), TD(P, f='floor'), ), 'rint': Ufunc(1, 1, None, docstrings.get('numpy.core.umath.rint'), None, TD(inexact, f='rint', astype={'e':'f'}), TD(P, f='rint'), ), 'arctan2': Ufunc(2, 1, None, docstrings.get('numpy.core.umath.arctan2'), None, TD(flts, f='atan2', astype={'e':'f'}), TD(P, f='arctan2'), ), 'remainder': Ufunc(2, 1, None, docstrings.get('numpy.core.umath.remainder'), None, TD(intflt), TD(O, f='PyNumber_Remainder'), ), 'hypot': Ufunc(2, 1, None, docstrings.get('numpy.core.umath.hypot'), None, TD(flts, f='hypot', astype={'e':'f'}), TD(P, f='hypot'), ), 'isnan': Ufunc(1, 1, None, docstrings.get('numpy.core.umath.isnan'), None, TD(inexact, out='?'), ), 'isinf': Ufunc(1, 1, None, docstrings.get('numpy.core.umath.isinf'), None, TD(inexact, out='?'), ), 'isfinite': Ufunc(1, 1, None, docstrings.get('numpy.core.umath.isfinite'), None, TD(inexact, out='?'), ), 'signbit': Ufunc(1, 1, None, docstrings.get('numpy.core.umath.signbit'), None, TD(flts, out='?'), ), 'copysign': Ufunc(2, 1, None, docstrings.get('numpy.core.umath.copysign'), None, TD(flts), ), 'nextafter': Ufunc(2, 1, None, docstrings.get('numpy.core.umath.nextafter'), None, TD(flts), ), 'spacing': Ufunc(1, 1, None, docstrings.get('numpy.core.umath.spacing'), None, TD(flts), ), 'modf': Ufunc(1, 2, None, docstrings.get('numpy.core.umath.modf'), None, TD(flts), ), } if sys.version_info[0] >= 3: # Will be aliased to true_divide in umathmodule.c.src:InitOtherOperators del defdict['divide'] def indent(st, spaces): indention = ' '*spaces indented = indention + st.replace('\n', '\n'+indention) # trim off any trailing spaces indented = re.sub(r' +$', r'', indented) return indented chartotype1 = {'e': 'e_e', 'f': 'f_f', 'd': 'd_d', 'g': 'g_g', 'F': 'F_F', 'D': 'D_D', 'G': 'G_G', 'O': 'O_O', 'P': 'O_O_method'} chartotype2 = {'e': 'ee_e', 'f': 'ff_f', 'd': 'dd_d', 'g': 'gg_g', 'F': 'FF_F', 'D': 'DD_D', 'G': 'GG_G', 'O': 'OO_O', 'P': 'OO_O_method'} #for each name # 1) create functions, data, and signature # 2) fill in functions and data in InitOperators # 3) add function. def make_arrays(funcdict): # functions array contains an entry for every type implemented # NULL should be placed where PyUfunc_ style function will be filled in later # code1list = [] code2list = [] names = sorted(funcdict.keys()) for name in names: uf = funcdict[name] funclist = [] datalist = [] siglist = [] k = 0 sub = 0 if uf.nin > 1: assert uf.nin == 2 thedict = chartotype2 # two inputs and one output else: thedict = chartotype1 # one input and one output for t in uf.type_descriptions: if t.func_data not in (None, FullTypeDescr): funclist.append('NULL') astype = '' if not t.astype is None: astype = '_As_%s' % thedict[t.astype] astr = '%s_functions[%d] = PyUFunc_%s%s;' % \ (name, k, thedict[t.type], astype) code2list.append(astr) if t.type == 'O': astr = '%s_data[%d] = (void *) %s;' % \ (name, k, t.func_data) code2list.append(astr) datalist.append('(void *)NULL') elif t.type == 'P': datalist.append('(void *)"%s"' % t.func_data) else: astr = '%s_data[%d] = (void *) %s;' % \ (name, k, t.func_data) code2list.append(astr) datalist.append('(void *)NULL') #datalist.append('(void *)%s' % t.func_data) sub += 1 elif t.func_data is FullTypeDescr: tname = english_upper(chartoname[t.type]) datalist.append('(void *)NULL') funclist.append('%s_%s_%s_%s' % (tname, t.in_, t.out, name)) else: datalist.append('(void *)NULL') tname = english_upper(chartoname[t.type]) funclist.append('%s_%s' % (tname, name)) for x in t.in_ + t.out: siglist.append('NPY_%s' % (english_upper(chartoname[x]),)) k += 1 funcnames = ', '.join(funclist) signames = ', '.join(siglist) datanames = ', '.join(datalist) code1list.append("static PyUFuncGenericFunction %s_functions[] = { %s };" \ % (name, funcnames)) code1list.append("static void * %s_data[] = { %s };" \ % (name, datanames)) code1list.append("static char %s_signatures[] = { %s };" \ % (name, signames)) return "\n".join(code1list), "\n".join(code2list) def make_ufuncs(funcdict): code3list = [] names = sorted(funcdict.keys()) for name in names: uf = funcdict[name] mlist = [] docstring = textwrap.dedent(uf.docstring).strip() if sys.version_info[0] < 3: docstring = docstring.encode('string-escape') docstring = docstring.replace(r'"', r'\"') else: docstring = docstring.encode('unicode-escape').decode('ascii') docstring = docstring.replace(r'"', r'\"') # XXX: I don't understand why the following replace is not # necessary in the python 2 case. docstring = docstring.replace(r"'", r"\'") # Split the docstring because some compilers (like MS) do not like big # string literal in C code. We split at endlines because textwrap.wrap # do not play well with \n docstring = '\\n\"\"'.join(docstring.split(r"\n")) mlist.append(\ r"""f = PyUFunc_FromFuncAndData(%s_functions, %s_data, %s_signatures, %d, %d, %d, %s, "%s", "%s", 0);""" % (name, name, name, len(uf.type_descriptions), uf.nin, uf.nout, uf.identity, name, docstring)) if uf.typereso != None: mlist.append( r"((PyUFuncObject *)f)->type_resolver = &%s;" % uf.typereso) mlist.append(r"""PyDict_SetItemString(dictionary, "%s", f);""" % name) mlist.append(r"""Py_DECREF(f);""") code3list.append('\n'.join(mlist)) return '\n'.join(code3list) def make_code(funcdict, filename): code1, code2 = make_arrays(funcdict) code3 = make_ufuncs(funcdict) code2 = indent(code2, 4) code3 = indent(code3, 4) code = r""" /** Warning this file is autogenerated!!! Please make changes to the code generator program (%s) **/ %s static void InitOperators(PyObject *dictionary) { PyObject *f; %s %s } """ % (filename, code1, code2, code3) return code; if __name__ == "__main__": filename = __file__ fid = open('__umath_generated.c', 'w') code = make_code(defdict, filename) fid.write(code) fid.close() numpy-1.8.2/numpy/core/code_generators/__init__.py0000664000175100017510000000010112370216242023367 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function numpy-1.8.2/numpy/core/code_generators/cversions.txt0000664000175100017510000000206712370216243024050 0ustar vagrantvagrant00000000000000# Hash below were defined from numpy_api_order.txt and ufunc_api_order.txt # When adding a new version here for a new minor release, also add the same # version as NPY_x_y_API_VERSION in numpyconfig.h 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 numpy-1.8.2/numpy/core/code_generators/ufunc_docstrings.py0000664000175100017510000025713212370216243025232 0ustar vagrantvagrant00000000000000""" Docstrings for generated ufuncs The syntax is designed to look like the function add_newdoc is being called from numpy.lib, but in this file add_newdoc puts the docstrings in a dictionary. This dictionary is used in numpy/core/code_generators/generate_umath.py to generate the docstrings for the ufuncs in numpy.core at the C level when the ufuncs are created at compile time. """ from __future__ import division, absolute_import, print_function docdict = {} def get(name): return docdict.get(name) def add_newdoc(place, name, doc): docdict['.'.join((place, name))] = doc add_newdoc('numpy.core.umath', 'absolute', """ Calculate the absolute value element-wise. Parameters ---------- x : array_like Input array. Returns ------- absolute : ndarray An ndarray containing the absolute value of each element in `x`. For complex input, ``a + ib``, the absolute value is :math:`\\sqrt{ a^2 + b^2 }`. Examples -------- >>> x = np.array([-1.2, 1.2]) >>> np.absolute(x) array([ 1.2, 1.2]) >>> np.absolute(1.2 + 1j) 1.5620499351813308 Plot the function over ``[-10, 10]``: >>> import matplotlib.pyplot as plt >>> x = np.linspace(start=-10, stop=10, num=101) >>> plt.plot(x, np.absolute(x)) >>> plt.show() Plot the function over the complex plane: >>> xx = x + 1j * x[:, np.newaxis] >>> plt.imshow(np.abs(xx), extent=[-10, 10, -10, 10]) >>> plt.show() """) add_newdoc('numpy.core.umath', 'add', """ Add arguments element-wise. Parameters ---------- x1, x2 : array_like The arrays to be added. If ``x1.shape != x2.shape``, they must be broadcastable to a common shape (which may be the shape of one or the other). Returns ------- add : ndarray or scalar The sum of `x1` and `x2`, element-wise. Returns a scalar if both `x1` and `x2` are scalars. Notes ----- Equivalent to `x1` + `x2` in terms of array broadcasting. Examples -------- >>> np.add(1.0, 4.0) 5.0 >>> x1 = np.arange(9.0).reshape((3, 3)) >>> x2 = np.arange(3.0) >>> np.add(x1, x2) array([[ 0., 2., 4.], [ 3., 5., 7.], [ 6., 8., 10.]]) """) add_newdoc('numpy.core.umath', 'arccos', """ Trigonometric inverse cosine, element-wise. The inverse of `cos` so that, if ``y = cos(x)``, then ``x = arccos(y)``. Parameters ---------- x : array_like `x`-coordinate on the unit circle. For real arguments, the domain is [-1, 1]. out : ndarray, optional Array of the same shape as `a`, to store results in. See `doc.ufuncs` (Section "Output arguments") for more details. Returns ------- angle : ndarray The angle of the ray intersecting the unit circle at the given `x`-coordinate in radians [0, pi]. If `x` is a scalar then a scalar is returned, otherwise an array of the same shape as `x` is returned. See Also -------- cos, arctan, arcsin, emath.arccos Notes ----- `arccos` is a multivalued function: for each `x` there are infinitely many numbers `z` such that `cos(z) = x`. The convention is to return the angle `z` whose real part lies in `[0, pi]`. For real-valued input data types, `arccos` 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, `arccos` is a complex analytic function that has branch cuts `[-inf, -1]` and `[1, inf]` and is continuous from above on the former and from below on the latter. The inverse `cos` is also known as `acos` or cos^-1. References ---------- M. Abramowitz and I.A. Stegun, "Handbook of Mathematical Functions", 10th printing, 1964, pp. 79. http://www.math.sfu.ca/~cbm/aands/ Examples -------- We expect the arccos of 1 to be 0, and of -1 to be pi: >>> np.arccos([1, -1]) array([ 0. , 3.14159265]) Plot arccos: >>> import matplotlib.pyplot as plt >>> x = np.linspace(-1, 1, num=100) >>> plt.plot(x, np.arccos(x)) >>> plt.axis('tight') >>> plt.show() """) add_newdoc('numpy.core.umath', 'arccosh', """ Inverse hyperbolic cosine, element-wise. Parameters ---------- x : array_like Input array. out : ndarray, optional Array of the same shape as `x`, to store results in. See `doc.ufuncs` (Section "Output arguments") for details. Returns ------- arccosh : ndarray Array of the same shape as `x`. See Also -------- cosh, arcsinh, sinh, arctanh, tanh Notes ----- `arccosh` is a multivalued function: for each `x` there are infinitely many numbers `z` such that `cosh(z) = x`. The convention is to return the `z` whose imaginary part lies in `[-pi, pi]` and the real part in ``[0, inf]``. For real-valued input data types, `arccosh` 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, `arccosh` is a complex analytical function that has a branch cut `[-inf, 1]` and is continuous from above on it. References ---------- .. [1] M. Abramowitz and I.A. Stegun, "Handbook of Mathematical Functions", 10th printing, 1964, pp. 86. http://www.math.sfu.ca/~cbm/aands/ .. [2] Wikipedia, "Inverse hyperbolic function", http://en.wikipedia.org/wiki/Arccosh Examples -------- >>> np.arccosh([np.e, 10.0]) array([ 1.65745445, 2.99322285]) >>> np.arccosh(1) 0.0 """) add_newdoc('numpy.core.umath', 'arcsin', """ Inverse sine, element-wise. Parameters ---------- x : array_like `y`-coordinate on the unit circle. out : ndarray, optional Array of the same shape as `x`, in which to store the results. See `doc.ufuncs` (Section "Output arguments") for more details. Returns ------- angle : ndarray The inverse sine of each element in `x`, in radians and in the closed interval ``[-pi/2, pi/2]``. If `x` is a scalar, a scalar is returned, otherwise an array. See Also -------- sin, cos, arccos, tan, arctan, arctan2, emath.arcsin Notes ----- `arcsin` is a multivalued function: for each `x` there are infinitely many numbers `z` such that :math:`sin(z) = x`. The convention is to return the angle `z` whose real part lies in [-pi/2, pi/2]. For real-valued input data types, *arcsin* 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, `arcsin` is a complex analytic function that has, by convention, the branch cuts [-inf, -1] and [1, inf] and is continuous from above on the former and from below on the latter. The inverse sine is also known as `asin` or sin^{-1}. References ---------- Abramowitz, M. and Stegun, I. A., *Handbook of Mathematical Functions*, 10th printing, New York: Dover, 1964, pp. 79ff. http://www.math.sfu.ca/~cbm/aands/ Examples -------- >>> np.arcsin(1) # pi/2 1.5707963267948966 >>> np.arcsin(-1) # -pi/2 -1.5707963267948966 >>> np.arcsin(0) 0.0 """) add_newdoc('numpy.core.umath', 'arcsinh', """ Inverse hyperbolic sine element-wise. Parameters ---------- x : array_like Input array. 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`. Returns ------- out : ndarray Array of of the same shape as `x`. Notes ----- `arcsinh` is a multivalued function: for each `x` there are infinitely many numbers `z` such that `sinh(z) = x`. The convention is to return the `z` whose imaginary part lies in `[-pi/2, pi/2]`. For real-valued input data types, `arcsinh` always returns real output. For each value that cannot be expressed as a real number or infinity, it returns ``nan`` and sets the `invalid` floating point error flag. For complex-valued input, `arccos` is a complex analytical function that has branch cuts `[1j, infj]` and `[-1j, -infj]` and is continuous from the right on the former and from the left on the latter. The inverse hyperbolic sine is also known as `asinh` or ``sinh^-1``. References ---------- .. [1] M. Abramowitz and I.A. Stegun, "Handbook of Mathematical Functions", 10th printing, 1964, pp. 86. http://www.math.sfu.ca/~cbm/aands/ .. [2] Wikipedia, "Inverse hyperbolic function", http://en.wikipedia.org/wiki/Arcsinh Examples -------- >>> np.arcsinh(np.array([np.e, 10.0])) array([ 1.72538256, 2.99822295]) """) add_newdoc('numpy.core.umath', 'arctan', """ Trigonometric inverse tangent, element-wise. The inverse of tan, so that if ``y = tan(x)`` then ``x = arctan(y)``. Parameters ---------- x : array_like Input values. `arctan` is applied to each element of `x`. Returns ------- out : ndarray Out has the same shape as `x`. Its real part is in ``[-pi/2, pi/2]`` (``arctan(+/-inf)`` returns ``+/-pi/2``). It is a scalar if `x` is a scalar. See Also -------- arctan2 : The "four quadrant" arctan of the angle formed by (`x`, `y`) and the positive `x`-axis. angle : Argument of complex values. Notes ----- `arctan` is a multi-valued function: for each `x` there are infinitely many numbers `z` such that tan(`z`) = `x`. The convention is to return the angle `z` whose real part lies in [-pi/2, pi/2]. For real-valued input data types, `arctan` 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, `arctan` is a complex analytic function that has [`1j, infj`] and [`-1j, -infj`] as branch cuts, and is continuous from the left on the former and from the right on the latter. The inverse tangent is also known as `atan` or tan^{-1}. References ---------- Abramowitz, M. and Stegun, I. A., *Handbook of Mathematical Functions*, 10th printing, New York: Dover, 1964, pp. 79. http://www.math.sfu.ca/~cbm/aands/ Examples -------- We expect the arctan of 0 to be 0, and of 1 to be pi/4: >>> np.arctan([0, 1]) array([ 0. , 0.78539816]) >>> np.pi/4 0.78539816339744828 Plot arctan: >>> import matplotlib.pyplot as plt >>> x = np.linspace(-10, 10) >>> plt.plot(x, np.arctan(x)) >>> plt.axis('tight') >>> plt.show() """) add_newdoc('numpy.core.umath', 'arctan2', """ Element-wise arc tangent of ``x1/x2`` choosing the quadrant correctly. The quadrant (i.e., branch) is chosen so that ``arctan2(x1, x2)`` is the signed angle in radians between the ray ending at the origin and passing through the point (1,0), and the ray ending at the origin and passing through the point (`x2`, `x1`). (Note the role reversal: the "`y`-coordinate" is the first function parameter, the "`x`-coordinate" is the second.) By IEEE convention, this function is defined for `x2` = +/-0 and for either or both of `x1` and `x2` = +/-inf (see Notes for specific values). This function is not defined for complex-valued arguments; for the so-called argument of complex values, use `angle`. Parameters ---------- x1 : array_like, real-valued `y`-coordinates. x2 : array_like, real-valued `x`-coordinates. `x2` must be broadcastable to match the shape of `x1` or vice versa. Returns ------- angle : ndarray Array of angles in radians, in the range ``[-pi, pi]``. See Also -------- arctan, tan, angle Notes ----- *arctan2* is identical to the `atan2` function of the underlying C library. The following special values are defined in the C standard: [1]_ ====== ====== ================ `x1` `x2` `arctan2(x1,x2)` ====== ====== ================ +/- 0 +0 +/- 0 +/- 0 -0 +/- pi > 0 +/-inf +0 / +pi < 0 +/-inf -0 / -pi +/-inf +inf +/- (pi/4) +/-inf -inf +/- (3*pi/4) ====== ====== ================ Note that +0 and -0 are distinct floating point numbers, as are +inf and -inf. References ---------- .. [1] ISO/IEC standard 9899:1999, "Programming language C." Examples -------- Consider four points in different quadrants: >>> x = np.array([-1, +1, +1, -1]) >>> y = np.array([-1, -1, +1, +1]) >>> np.arctan2(y, x) * 180 / np.pi array([-135., -45., 45., 135.]) Note the order of the parameters. `arctan2` is defined also when `x2` = 0 and at several other special points, obtaining values in the range ``[-pi, pi]``: >>> np.arctan2([1., -1.], [0., 0.]) array([ 1.57079633, -1.57079633]) >>> np.arctan2([0., 0., np.inf], [+0., -0., np.inf]) array([ 0. , 3.14159265, 0.78539816]) """) add_newdoc('numpy.core.umath', '_arg', """ DO NOT USE, ONLY FOR TESTING """) add_newdoc('numpy.core.umath', 'arctanh', """ Inverse hyperbolic tangent element-wise. Parameters ---------- x : array_like Input array. Returns ------- out : ndarray Array of the same shape as `x`. See Also -------- emath.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]`. 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 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``. References ---------- .. [1] M. Abramowitz and I.A. Stegun, "Handbook of Mathematical Functions", 10th printing, 1964, pp. 86. http://www.math.sfu.ca/~cbm/aands/ .. [2] Wikipedia, "Inverse hyperbolic function", http://en.wikipedia.org/wiki/Arctanh Examples -------- >>> np.arctanh([0, -0.5]) array([ 0. , -0.54930614]) """) add_newdoc('numpy.core.umath', 'bitwise_and', """ Compute the bit-wise AND of two arrays element-wise. Computes the bit-wise AND of the underlying binary representation of the integers in the input arrays. This ufunc implements the C/Python operator ``&``. Parameters ---------- x1, x2 : array_like Only integer and boolean types are handled. Returns ------- out : array_like Result. See Also -------- logical_and bitwise_or bitwise_xor binary_repr : Return the binary representation of the input number as a string. Examples -------- The number 13 is represented by ``00001101``. Likewise, 17 is represented by ``00010001``. The bit-wise AND of 13 and 17 is therefore ``000000001``, or 1: >>> np.bitwise_and(13, 17) 1 >>> np.bitwise_and(14, 13) 12 >>> np.binary_repr(12) '1100' >>> np.bitwise_and([14,3], 13) array([12, 1]) >>> np.bitwise_and([11,7], [4,25]) array([0, 1]) >>> np.bitwise_and(np.array([2,5,255]), np.array([3,14,16])) array([ 2, 4, 16]) >>> np.bitwise_and([True, True], [False, True]) array([False, True], dtype=bool) """) add_newdoc('numpy.core.umath', 'bitwise_or', """ Compute the bit-wise OR of two arrays element-wise. Computes the bit-wise OR of the underlying binary representation of the integers in the input arrays. This ufunc implements the C/Python operator ``|``. Parameters ---------- x1, x2 : array_like 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. Returns ------- out : array_like Result. See Also -------- logical_or bitwise_and bitwise_xor binary_repr : Return the binary representation of the input number as a string. Examples -------- The number 13 has the binaray representation ``00001101``. Likewise, 16 is represented by ``00010000``. The bit-wise OR of 13 and 16 is then ``000111011``, or 29: >>> np.bitwise_or(13, 16) 29 >>> np.binary_repr(29) '11101' >>> np.bitwise_or(32, 2) 34 >>> np.bitwise_or([33, 4], 1) array([33, 5]) >>> np.bitwise_or([33, 4], [1, 2]) array([33, 6]) >>> np.bitwise_or(np.array([2, 5, 255]), np.array([4, 4, 4])) array([ 6, 5, 255]) >>> np.array([2, 5, 255]) | np.array([4, 4, 4]) array([ 6, 5, 255]) >>> np.bitwise_or(np.array([2, 5, 255, 2147483647L], dtype=np.int32), ... np.array([4, 4, 4, 2147483647L], dtype=np.int32)) array([ 6, 5, 255, 2147483647]) >>> np.bitwise_or([True, True], [False, True]) array([ True, True], dtype=bool) """) add_newdoc('numpy.core.umath', 'bitwise_xor', """ Compute the bit-wise XOR of two arrays element-wise. Computes the bit-wise XOR of the underlying binary representation of the integers in the input arrays. This ufunc implements the C/Python operator ``^``. Parameters ---------- x1, x2 : array_like Only integer and boolean types are handled. Returns ------- out : array_like Result. See Also -------- logical_xor bitwise_and bitwise_or binary_repr : Return the binary representation of the input number as a string. Examples -------- The number 13 is represented by ``00001101``. Likewise, 17 is represented by ``00010001``. The bit-wise XOR of 13 and 17 is therefore ``00011100``, or 28: >>> np.bitwise_xor(13, 17) 28 >>> np.binary_repr(28) '11100' >>> np.bitwise_xor(31, 5) 26 >>> np.bitwise_xor([31,3], 5) array([26, 6]) >>> np.bitwise_xor([31,3], [5,6]) array([26, 5]) >>> np.bitwise_xor([True, True], [False, True]) array([ True, False], dtype=bool) """) add_newdoc('numpy.core.umath', 'ceil', """ Return the ceiling of the input, element-wise. The ceil of the scalar `x` is the smallest integer `i`, such that `i >= x`. It is often denoted as :math:`\\lceil x \\rceil`. Parameters ---------- x : array_like Input data. Returns ------- y : {ndarray, scalar} The ceiling of each element in `x`, with `float` dtype. See Also -------- floor, trunc, rint Examples -------- >>> a = np.array([-1.7, -1.5, -0.2, 0.2, 1.5, 1.7, 2.0]) >>> np.ceil(a) array([-1., -1., -0., 1., 2., 2., 2.]) """) add_newdoc('numpy.core.umath', 'trunc', """ Return the truncated value of the input, element-wise. The truncated value of the scalar `x` is the nearest integer `i` which is closer to zero than `x` is. In short, the fractional part of the signed number `x` is discarded. Parameters ---------- x : array_like Input data. Returns ------- y : {ndarray, scalar} The truncated value of each element in `x`. See Also -------- ceil, floor, rint Notes ----- .. versionadded:: 1.3.0 Examples -------- >>> a = np.array([-1.7, -1.5, -0.2, 0.2, 1.5, 1.7, 2.0]) >>> np.trunc(a) array([-1., -1., -0., 0., 1., 1., 2.]) """) add_newdoc('numpy.core.umath', 'conjugate', """ Return the complex conjugate, element-wise. The complex conjugate of a complex number is obtained by changing the sign of its imaginary part. Parameters ---------- x : array_like Input value. Returns ------- y : ndarray The complex conjugate of `x`, with same dtype as `y`. Examples -------- >>> np.conjugate(1+2j) (1-2j) >>> x = np.eye(2) + 1j * np.eye(2) >>> np.conjugate(x) array([[ 1.-1.j, 0.-0.j], [ 0.-0.j, 1.-1.j]]) """) add_newdoc('numpy.core.umath', 'cos', """ Cosine element-wise. Parameters ---------- x : array_like Input array in radians. out : ndarray, optional Output array of same shape as `x`. Returns ------- y : ndarray The corresponding cosine values. Raises ------ ValueError: invalid return array shape if `out` is provided and `out.shape` != `x.shape` (See Examples) Notes ----- If `out` is provided, the function writes the result into it, and returns a reference to `out`. (See Examples) References ---------- M. Abramowitz and I. A. Stegun, Handbook of Mathematical Functions. New York, NY: Dover, 1972. Examples -------- >>> np.cos(np.array([0, np.pi/2, np.pi])) array([ 1.00000000e+00, 6.12303177e-17, -1.00000000e+00]) >>> >>> # Example of providing the optional output parameter >>> out2 = np.cos([0.1], out1) >>> out2 is out1 True >>> >>> # Example of ValueError due to provision of shape mis-matched `out` >>> np.cos(np.zeros((3,3)),np.zeros((2,2))) Traceback (most recent call last): File "", line 1, in ValueError: invalid return array shape """) add_newdoc('numpy.core.umath', 'cosh', """ Hyperbolic cosine, element-wise. Equivalent to ``1/2 * (np.exp(x) + np.exp(-x))`` and ``np.cos(1j*x)``. Parameters ---------- x : array_like Input array. Returns ------- out : ndarray Output array of same shape as `x`. Examples -------- >>> np.cosh(0) 1.0 The hyperbolic cosine describes the shape of a hanging cable: >>> import matplotlib.pyplot as plt >>> x = np.linspace(-4, 4, 1000) >>> plt.plot(x, np.cosh(x)) >>> plt.show() """) add_newdoc('numpy.core.umath', 'degrees', """ Convert angles from radians to degrees. Parameters ---------- x : array_like Input array in radians. out : ndarray, optional Output array of same shape as x. Returns ------- y : ndarray of floats The corresponding degree values; if `out` was supplied this is a reference to it. See Also -------- rad2deg : equivalent function Examples -------- Convert a radian array to degrees >>> rad = np.arange(12.)*np.pi/6 >>> np.degrees(rad) array([ 0., 30., 60., 90., 120., 150., 180., 210., 240., 270., 300., 330.]) >>> out = np.zeros((rad.shape)) >>> r = degrees(rad, out) >>> np.all(r == out) True """) add_newdoc('numpy.core.umath', 'rad2deg', """ Convert angles from radians to degrees. Parameters ---------- x : array_like Angle in radians. 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. Returns ------- y : ndarray The corresponding angle in degrees. See Also -------- deg2rad : Convert angles from degrees to radians. unwrap : Remove large jumps in angle by wrapping. Notes ----- .. versionadded:: 1.3.0 rad2deg(x) is ``180 * x / pi``. Examples -------- >>> np.rad2deg(np.pi/2) 90.0 """) add_newdoc('numpy.core.umath', 'divide', """ Divide arguments element-wise. Parameters ---------- x1 : array_like Dividend array. x2 : array_like Divisor array. 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. Returns ------- y : {ndarray, scalar} The quotient `x1/x2`, element-wise. Returns a scalar if both `x1` and `x2` are scalars. See Also -------- seterr : Set whether to raise or warn on overflow, underflow and division by zero. Notes ----- Equivalent to `x1` / `x2` in terms of array-broadcasting. Behavior on division by zero can be changed using `seterr`. When both `x1` and `x2` are of an integer type, `divide` will return integers and throw away the fractional part. Moreover, division by zero always yields zero in integer arithmetic. Examples -------- >>> np.divide(2.0, 4.0) 0.5 >>> x1 = np.arange(9.0).reshape((3, 3)) >>> x2 = np.arange(3.0) >>> np.divide(x1, x2) array([[ NaN, 1. , 1. ], [ Inf, 4. , 2.5], [ Inf, 7. , 4. ]]) Note the behavior with integer types: >>> np.divide(2, 4) 0 >>> np.divide(2, 4.) 0.5 Division by zero always yields zero in integer arithmetic, and does not raise an exception or a warning: >>> np.divide(np.array([0, 1], dtype=int), np.array([0, 0], dtype=int)) array([0, 0]) Division by zero can, however, be caught using `seterr`: >>> old_err_state = np.seterr(divide='raise') >>> np.divide(1, 0) Traceback (most recent call last): File "", line 1, in FloatingPointError: divide by zero encountered in divide >>> ignored_states = np.seterr(**old_err_state) >>> np.divide(1, 0) 0 """) add_newdoc('numpy.core.umath', 'equal', """ Return (x1 == x2) element-wise. Parameters ---------- x1, x2 : array_like Input arrays of the same shape. Returns ------- out : {ndarray, bool} Output array of bools, or a single bool if x1 and x2 are scalars. See Also -------- not_equal, greater_equal, less_equal, greater, less Examples -------- >>> np.equal([0, 1, 3], np.arange(3)) array([ True, True, False], dtype=bool) What is compared are values, not types. So an int (1) and an array of length one can evaluate as True: >>> np.equal(1, np.ones(1)) array([ True], dtype=bool) """) add_newdoc('numpy.core.umath', 'exp', """ Calculate the exponential of all elements in the input array. Parameters ---------- x : array_like Input values. Returns ------- out : ndarray Output array, element-wise exponential of `x`. See Also -------- expm1 : Calculate ``exp(x) - 1`` for all elements in the array. exp2 : Calculate ``2**x`` for all elements in the array. Notes ----- The irrational number ``e`` is also known as Euler's number. It is approximately 2.718281, and is the base of the natural logarithm, ``ln`` (this means that, if :math:`x = \\ln y = \\log_e y`, then :math:`e^x = y`. For real input, ``exp(x)`` is always positive. 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. References ---------- .. [1] Wikipedia, "Exponential function", http://en.wikipedia.org/wiki/Exponential_function .. [2] M. Abramovitz and I. A. Stegun, "Handbook of Mathematical Functions with Formulas, Graphs, and Mathematical Tables," Dover, 1964, p. 69, http://www.math.sfu.ca/~cbm/aands/page_69.htm Examples -------- Plot the magnitude and phase of ``exp(x)`` in the complex plane: >>> import matplotlib.pyplot as plt >>> x = np.linspace(-2*np.pi, 2*np.pi, 100) >>> xx = x + 1j * x[:, np.newaxis] # a + ib over complex plane >>> out = np.exp(xx) >>> plt.subplot(121) >>> plt.imshow(np.abs(out), ... extent=[-2*np.pi, 2*np.pi, -2*np.pi, 2*np.pi]) >>> plt.title('Magnitude of exp(x)') >>> plt.subplot(122) >>> plt.imshow(np.angle(out), ... extent=[-2*np.pi, 2*np.pi, -2*np.pi, 2*np.pi]) >>> plt.title('Phase (angle) of exp(x)') >>> plt.show() """) add_newdoc('numpy.core.umath', 'exp2', """ Calculate `2**p` for all `p` in the input array. Parameters ---------- x : array_like Input values. out : ndarray, optional Array to insert results into. Returns ------- out : ndarray Element-wise 2 to the power `x`. See Also -------- power Notes ----- .. versionadded:: 1.3.0 Examples -------- >>> np.exp2([2, 3]) array([ 4., 8.]) """) add_newdoc('numpy.core.umath', 'expm1', """ Calculate ``exp(x) - 1`` for all elements in the array. Parameters ---------- x : array_like Input values. Returns ------- out : ndarray Element-wise exponential minus one: ``out = exp(x) - 1``. See Also -------- log1p : ``log(1 + x)``, the inverse of expm1. Notes ----- This function provides greater precision than ``exp(x) - 1`` for small values of ``x``. Examples -------- The true value of ``exp(1e-10) - 1`` is ``1.00000000005e-10`` to about 32 significant digits. This example shows the superiority of expm1 in this case. >>> np.expm1(1e-10) 1.00000000005e-10 >>> np.exp(1e-10) - 1 1.000000082740371e-10 """) add_newdoc('numpy.core.umath', 'fabs', """ 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 absolute values of complex data. Parameters ---------- x : array_like The array of numbers for which the absolute values are required. If `x` is a scalar, the result `y` will also be a scalar. 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. Returns ------- y : {ndarray, scalar} The absolute values of `x`, the returned values are always floats. See Also -------- absolute : Absolute values including `complex` types. Examples -------- >>> np.fabs(-1) 1.0 >>> np.fabs([-1.2, 1.2]) array([ 1.2, 1.2]) """) add_newdoc('numpy.core.umath', 'floor', """ Return the floor of the input, element-wise. The floor of the scalar `x` is the largest integer `i`, such that `i <= x`. It is often denoted as :math:`\\lfloor x \\rfloor`. Parameters ---------- x : array_like Input data. Returns ------- y : {ndarray, scalar} The floor of each element in `x`. See Also -------- ceil, trunc, rint Notes ----- Some spreadsheet programs calculate the "floor-towards-zero", in other words ``floor(-2.5) == -2``. NumPy instead uses the definition of `floor` where `floor(-2.5) == -3`. Examples -------- >>> a = np.array([-1.7, -1.5, -0.2, 0.2, 1.5, 1.7, 2.0]) >>> np.floor(a) array([-2., -2., -1., 0., 1., 1., 2.]) """) add_newdoc('numpy.core.umath', 'floor_divide', """ Return the largest integer smaller or equal to the division of the inputs. Parameters ---------- x1 : array_like Numerator. x2 : array_like Denominator. Returns ------- y : ndarray y = floor(`x1`/`x2`) See Also -------- divide : Standard division. floor : Round a number to the nearest integer toward minus infinity. ceil : Round a number to the nearest integer toward infinity. Examples -------- >>> np.floor_divide(7,3) 2 >>> np.floor_divide([1., 2., 3., 4.], 2.5) array([ 0., 0., 1., 1.]) """) add_newdoc('numpy.core.umath', 'fmod', """ Return the element-wise remainder of division. 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 ---------- x1 : array_like Dividend. x2 : array_like Divisor. Returns ------- y : array_like The remainder of the division of `x1` by `x2`. See Also -------- remainder : Equivalent to the Python ``%`` operator. divide Notes ----- 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 -------- >>> np.fmod([-3, -2, -1, 1, 2, 3], 2) array([-1, 0, -1, 1, 0, 1]) >>> np.remainder([-3, -2, -1, 1, 2, 3], 2) array([1, 0, 1, 1, 0, 1]) >>> np.fmod([5, 3], [2, 2.]) array([ 1., 1.]) >>> a = np.arange(-3, 3).reshape(3, 2) >>> a array([[-3, -2], [-1, 0], [ 1, 2]]) >>> np.fmod(a, [2,2]) array([[-1, 0], [-1, 0], [ 1, 0]]) """) add_newdoc('numpy.core.umath', 'greater', """ Return the truth value of (x1 > x2) element-wise. Parameters ---------- x1, x2 : array_like Input arrays. If ``x1.shape != x2.shape``, they must be broadcastable to a common shape (which may be the shape of one or the other). Returns ------- out : bool or ndarray of bool Array of bools, or a single bool if `x1` and `x2` are scalars. See Also -------- greater_equal, less, less_equal, equal, not_equal Examples -------- >>> np.greater([4,2],[2,2]) array([ True, False], dtype=bool) If the inputs are ndarrays, then np.greater is equivalent to '>'. >>> a = np.array([4,2]) >>> b = np.array([2,2]) >>> a > b array([ True, False], dtype=bool) """) add_newdoc('numpy.core.umath', 'greater_equal', """ Return the truth value of (x1 >= x2) element-wise. Parameters ---------- x1, x2 : array_like Input arrays. If ``x1.shape != x2.shape``, they must be broadcastable to a common shape (which may be the shape of one or the other). Returns ------- out : bool or ndarray of bool Array of bools, or a single bool if `x1` and `x2` are scalars. See Also -------- greater, less, less_equal, equal, not_equal Examples -------- >>> np.greater_equal([4, 2, 1], [2, 2, 2]) array([ True, True, False], dtype=bool) """) add_newdoc('numpy.core.umath', 'hypot', """ Given the "legs" of a right triangle, return its hypotenuse. Equivalent to ``sqrt(x1**2 + x2**2)``, element-wise. If `x1` or `x2` is scalar_like (i.e., unambiguously cast-able to a scalar type), it is broadcast for use with each element of the other argument. (See Examples) Parameters ---------- x1, x2 : array_like Leg of the triangle(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. Returns ------- z : ndarray The hypotenuse of the triangle(s). Examples -------- >>> np.hypot(3*np.ones((3, 3)), 4*np.ones((3, 3))) array([[ 5., 5., 5.], [ 5., 5., 5.], [ 5., 5., 5.]]) Example showing broadcast of scalar_like argument: >>> np.hypot(3*np.ones((3, 3)), [4]) array([[ 5., 5., 5.], [ 5., 5., 5.], [ 5., 5., 5.]]) """) add_newdoc('numpy.core.umath', 'invert', """ Compute bit-wise inversion, or bit-wise NOT, element-wise. Computes the bit-wise NOT of the underlying binary representation of 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 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 :math:`-2^{N-1}` to :math:`+2^{N-1}-1`. Parameters ---------- x1 : array_like Only integer and boolean types are handled. Returns ------- out : array_like Result. See Also -------- bitwise_and, bitwise_or, bitwise_xor logical_not binary_repr : Return the binary representation of the input number as a string. Notes ----- `bitwise_not` is an alias for `invert`: >>> np.bitwise_not is np.invert True References ---------- .. [1] Wikipedia, "Two's complement", http://en.wikipedia.org/wiki/Two's_complement Examples -------- We've seen that 13 is represented by ``00001101``. The invert or bit-wise NOT of 13 is then: >>> np.invert(np.array([13], dtype=uint8)) array([242], dtype=uint8) >>> np.binary_repr(x, width=8) '00001101' >>> np.binary_repr(242, width=8) '11110010' The result depends on the bit-width: >>> np.invert(np.array([13], dtype=uint16)) array([65522], dtype=uint16) >>> np.binary_repr(x, width=16) '0000000000001101' >>> np.binary_repr(65522, width=16) '1111111111110010' When using signed integer types the result is the two's complement of the result for the unsigned type: >>> np.invert(np.array([13], dtype=int8)) array([-14], dtype=int8) >>> np.binary_repr(-14, width=8) '11110010' Booleans are accepted as well: >>> np.invert(array([True, False])) array([False, True], dtype=bool) """) add_newdoc('numpy.core.umath', 'isfinite', """ Test element-wise for finiteness (not infinity or not Not a Number). The result is returned as a boolean array. Parameters ---------- x : array_like Input values. 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`. Returns ------- y : ndarray, bool For scalar input, the result is a new boolean with value True if the input is finite; otherwise the value is False (input is 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). See Also -------- isinf, isneginf, isposinf, isnan Notes ----- Not a Number, positive infinity and negative infinity are considered to be non-finite. 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. Examples -------- >>> np.isfinite(1) True >>> np.isfinite(0) True >>> np.isfinite(np.nan) False >>> np.isfinite(np.inf) False >>> np.isfinite(np.NINF) False >>> np.isfinite([np.log(-1.),1.,np.log(0)]) array([False, True, False], dtype=bool) >>> x = np.array([-np.inf, 0., np.inf]) >>> y = np.array([2, 2, 2]) >>> np.isfinite(x, y) array([0, 1, 0]) >>> y array([0, 1, 0]) """) add_newdoc('numpy.core.umath', 'isinf', """ Test element-wise for positive or negative infinity. Returns a boolean array of the same shape as `x`, True where ``x == +/-inf``, otherwise False. Parameters ---------- x : array_like Input values out : array_like, optional An array with the same shape as `x` to store the result. Returns ------- 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. See Also -------- isneginf, isposinf, isnan, isfinite Notes ----- Numpy uses the IEEE Standard for Binary Floating-Point for Arithmetic (IEEE 754). Errors result if the second argument is supplied when the first argument is a scalar, or if the first and second arguments have different shapes. Examples -------- >>> np.isinf(np.inf) True >>> np.isinf(np.nan) False >>> np.isinf(np.NINF) True >>> np.isinf([np.inf, -np.inf, 1.0, np.nan]) array([ True, True, False, False], dtype=bool) >>> x = np.array([-np.inf, 0., np.inf]) >>> y = np.array([2, 2, 2]) >>> np.isinf(x, y) array([1, 0, 1]) >>> y array([1, 0, 1]) """) add_newdoc('numpy.core.umath', 'isnan', """ Test element-wise for NaN and return result as a boolean array. Parameters ---------- x : array_like Input array. 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 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 -------- isinf, isneginf, isposinf, isfinite Notes ----- Numpy uses the IEEE Standard for Binary Floating-Point for Arithmetic (IEEE 754). This means that Not a Number is not equivalent to infinity. Examples -------- >>> np.isnan(np.nan) True >>> np.isnan(np.inf) False >>> np.isnan([np.log(-1.),1.,np.log(0)]) array([ True, False, False], dtype=bool) """) add_newdoc('numpy.core.umath', 'left_shift', """ Shift the bits of an integer to the left. Bits are shifted to the left by appending `x2` 0s at the right of `x1`. Since the internal representation of numbers is in binary format, this operation is equivalent to multiplying `x1` by ``2**x2``. Parameters ---------- x1 : array_like of integer type Input values. x2 : array_like of integer type Number of zeros to append to `x1`. Has to be non-negative. Returns ------- out : array of integer type Return `x1` with bits shifted `x2` times to the left. See Also -------- right_shift : Shift the bits of an integer to the right. binary_repr : Return the binary representation of the input number as a string. Examples -------- >>> np.binary_repr(5) '101' >>> np.left_shift(5, 2) 20 >>> np.binary_repr(20) '10100' >>> np.left_shift(5, [1,2,3]) array([10, 20, 40]) """) add_newdoc('numpy.core.umath', 'less', """ Return the truth value of (x1 < x2) element-wise. Parameters ---------- x1, x2 : array_like Input arrays. If ``x1.shape != x2.shape``, they must be broadcastable to a common shape (which may be the shape of one or the other). Returns ------- out : bool or ndarray of bool Array of bools, or a single bool if `x1` and `x2` are scalars. See Also -------- greater, less_equal, greater_equal, equal, not_equal Examples -------- >>> np.less([1, 2], [2, 2]) array([ True, False], dtype=bool) """) add_newdoc('numpy.core.umath', 'less_equal', """ Return the truth value of (x1 =< x2) element-wise. Parameters ---------- x1, x2 : array_like Input arrays. If ``x1.shape != x2.shape``, they must be broadcastable to a common shape (which may be the shape of one or the other). Returns ------- out : bool or ndarray of bool Array of bools, or a single bool if `x1` and `x2` are scalars. See Also -------- greater, less, greater_equal, equal, not_equal Examples -------- >>> np.less_equal([4, 2, 1], [2, 2, 2]) array([False, True, True], dtype=bool) """) 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`. Parameters ---------- x : array_like Input value. Returns ------- y : ndarray The natural logarithm of `x`, element-wise. See Also -------- log10, log2, log1p, emath.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]`. 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 yields ``nan`` and sets the `invalid` floating point error flag. For complex-valued input, `log` is a complex analytical function that has a branch cut `[-inf, 0]` and is continuous from above on it. `log` handles the floating-point negative zero as an infinitesimal negative number, conforming to the C99 standard. References ---------- .. [1] M. Abramowitz and I.A. Stegun, "Handbook of Mathematical Functions", 10th printing, 1964, pp. 67. http://www.math.sfu.ca/~cbm/aands/ .. [2] Wikipedia, "Logarithm". http://en.wikipedia.org/wiki/Logarithm Examples -------- >>> np.log([1, np.e, np.e**2, 0]) array([ 0., 1., 2., -Inf]) """) add_newdoc('numpy.core.umath', 'log10', """ Return the base 10 logarithm of the input array, element-wise. Parameters ---------- x : array_like Input values. Returns ------- y : ndarray The logarithm to the base 10 of `x`, element-wise. NaNs are returned where x is negative. See Also -------- emath.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]`. 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. References ---------- .. [1] M. Abramowitz and I.A. Stegun, "Handbook of Mathematical Functions", 10th printing, 1964, pp. 67. http://www.math.sfu.ca/~cbm/aands/ .. [2] Wikipedia, "Logarithm". http://en.wikipedia.org/wiki/Logarithm Examples -------- >>> np.log10([1e-15, -3.]) array([-15., NaN]) """) add_newdoc('numpy.core.umath', 'log2', """ Base-2 logarithm of `x`. Parameters ---------- x : array_like Input values. Returns ------- y : ndarray Base-2 logarithm of `x`. See Also -------- log, log10, log1p, emath.log2 Notes ----- .. versionadded:: 1.3.0 Logarithm is a multivalued function: for each `x` there is an infinite 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 complex-valued input, `log2` is a complex analytical function that has a branch cut `[-inf, 0]` and is continuous from above on it. `log2` handles the floating-point negative zero as an infinitesimal negative number, conforming to the C99 standard. Examples -------- >>> x = np.array([0, 1, 2, 2**4]) >>> np.log2(x) array([-Inf, 0., 1., 4.]) >>> xi = np.array([0+1.j, 1, 2+0.j, 4.j]) >>> np.log2(xi) array([ 0.+2.26618007j, 0.+0.j , 1.+0.j , 2.+2.26618007j]) """) add_newdoc('numpy.core.umath', 'logaddexp', """ Logarithm of the sum of exponentiations of the inputs. Calculates ``log(exp(x1) + exp(x2))``. This function is useful in statistics where the calculated probabilities of events may be so small as to exceed the range of normal floating point numbers. In such cases the logarithm of the calculated probability is stored. This function allows adding probabilities stored in such a fashion. Parameters ---------- x1, x2 : array_like Input values. Returns ------- result : ndarray Logarithm of ``exp(x1) + exp(x2)``. See Also -------- logaddexp2: Logarithm of the sum of exponentiations of inputs in base 2. Notes ----- .. versionadded:: 1.3.0 Examples -------- >>> prob1 = np.log(1e-50) >>> prob2 = np.log(2.5e-50) >>> prob12 = np.logaddexp(prob1, prob2) >>> prob12 -113.87649168120691 >>> np.exp(prob12) 3.5000000000000057e-50 """) 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 the base-2 logarithm of the calculated probability can be used instead. This function allows adding probabilities stored in such a fashion. Parameters ---------- x1, x2 : array_like Input values. out : ndarray, optional Array to store results in. Returns ------- result : ndarray Base-2 logarithm of ``2**x1 + 2**x2``. See Also -------- logaddexp: Logarithm of the sum of exponentiations of the inputs. Notes ----- .. versionadded:: 1.3.0 Examples -------- >>> prob1 = np.log2(1e-50) >>> prob2 = np.log2(2.5e-50) >>> prob12 = np.logaddexp2(prob1, prob2) >>> prob1, prob2, prob12 (-166.09640474436813, -164.77447664948076, -164.28904982231052) >>> 2**prob12 3.4999999999999914e-50 """) add_newdoc('numpy.core.umath', 'log1p', """ Return the natural logarithm of one plus the input array, element-wise. Calculates ``log(1 + x)``. Parameters ---------- x : array_like Input values. Returns ------- y : ndarray Natural logarithm of `1 + x`, element-wise. See Also -------- expm1 : ``exp(x) - 1``, the inverse of `log1p`. Notes ----- For real-valued input, `log1p` is accurate also for `x` so small that `1 + x == 1` in floating-point accuracy. Logarithm is a multivalued function: for each `x` there is an infinite 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 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. References ---------- .. [1] M. Abramowitz and I.A. Stegun, "Handbook of Mathematical Functions", 10th printing, 1964, pp. 67. http://www.math.sfu.ca/~cbm/aands/ .. [2] Wikipedia, "Logarithm". http://en.wikipedia.org/wiki/Logarithm Examples -------- >>> np.log1p(1e-99) 1e-99 >>> np.log(1 + 1e-99) 0.0 """) add_newdoc('numpy.core.umath', 'logical_and', """ Compute the truth value of x1 AND x2 element-wise. Parameters ---------- x1, x2 : array_like Input arrays. `x1` and `x2` must be of the same shape. Returns ------- y : {ndarray, bool} Boolean result with the same shape as `x1` and `x2` of the logical AND operation on corresponding elements of `x1` and `x2`. See Also -------- logical_or, logical_not, logical_xor bitwise_and Examples -------- >>> np.logical_and(True, False) False >>> np.logical_and([True, False], [False, False]) array([False, False], dtype=bool) >>> x = np.arange(5) >>> np.logical_and(x>1, x<4) array([False, False, True, True, False], dtype=bool) """) add_newdoc('numpy.core.umath', 'logical_not', """ Compute the truth value of NOT x element-wise. Parameters ---------- x : array_like Logical NOT is applied to the elements of `x`. Returns ------- y : bool or ndarray of bool Boolean result with the same shape as `x` of the NOT operation on elements of `x`. See Also -------- logical_and, logical_or, logical_xor Examples -------- >>> np.logical_not(3) False >>> np.logical_not([True, False, 0, 1]) array([False, True, True, False], dtype=bool) >>> x = np.arange(5) >>> np.logical_not(x<3) array([False, False, False, True, True], dtype=bool) """) add_newdoc('numpy.core.umath', 'logical_or', """ Compute the truth value of x1 OR x2 element-wise. Parameters ---------- x1, x2 : array_like Logical OR is applied to the elements of `x1` and `x2`. They have to be of the same shape. Returns ------- y : {ndarray, bool} Boolean result with the same shape as `x1` and `x2` of the logical OR operation on elements of `x1` and `x2`. See Also -------- logical_and, logical_not, logical_xor bitwise_or Examples -------- >>> np.logical_or(True, False) True >>> np.logical_or([True, False], [False, False]) array([ True, False], dtype=bool) >>> x = np.arange(5) >>> np.logical_or(x < 1, x > 3) array([ True, False, False, False, True], dtype=bool) """) add_newdoc('numpy.core.umath', 'logical_xor', """ Compute the truth value of x1 XOR x2, element-wise. Parameters ---------- x1, x2 : array_like Logical XOR is applied to the elements of `x1` and `x2`. They must be broadcastable to the same shape. Returns ------- y : bool or ndarray of bool Boolean result of the logical XOR operation applied to the elements of `x1` and `x2`; the shape is determined by whether or not broadcasting of one or both arrays was required. See Also -------- logical_and, logical_or, logical_not, bitwise_xor Examples -------- >>> np.logical_xor(True, False) True >>> np.logical_xor([True, True, False, False], [True, False, True, False]) array([False, True, True, False], dtype=bool) >>> x = np.arange(5) >>> np.logical_xor(x < 1, x > 3) array([ True, False, False, False, True], dtype=bool) Simple example showing support of broadcasting >>> np.logical_xor(0, np.eye(2)) array([[ True, False], [False, True]], dtype=bool) """) 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. Parameters ---------- x1, x2 : array_like The arrays holding the elements to be compared. They must have the same shape, or shapes that can be broadcast to a single shape. Returns ------- y : {ndarray, scalar} The maximum of `x1` and `x2`, element-wise. Returns scalar if both `x1` and `x2` are scalars. See Also -------- minimum : Element-wise minimum of two arrays, propagates NaNs. fmax : Element-wise maximum of two arrays, ignores NaNs. amax : The maximum value of an array along a given axis, propagates NaNs. nanmax : 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. Examples -------- >>> np.maximum([2, 3, 4], [1, 5, 2]) array([2, 5, 4]) >>> np.maximum(np.eye(2), [0.5, 2]) # broadcasting array([[ 1. , 2. ], [ 0.5, 2. ]]) >>> np.maximum([np.nan, 0, np.nan], [0, np.nan, np.nan]) array([ NaN, NaN, NaN]) >>> np.maximum(np.Inf, 1) inf """) 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. Parameters ---------- x1, x2 : array_like The arrays holding the elements to be compared. They must have the same shape, or shapes that can be broadcast to a single shape. Returns ------- y : {ndarray, scalar} The minimum of `x1` and `x2`, element-wise. Returns scalar if both `x1` and `x2` are scalars. See Also -------- maximum : Element-wise maximum of two arrays, propagates NaNs. fmin : Element-wise minimum of two arrays, ignores NaNs. amin : The minimum value of an array along a given axis, propagates NaNs. nanmin : 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. Examples -------- >>> np.minimum([2, 3, 4], [1, 5, 2]) array([1, 3, 2]) >>> np.minimum(np.eye(2), [0.5, 2]) # broadcasting array([[ 0.5, 0. ], [ 0. , 1. ]]) >>> np.minimum([np.nan, 0, np.nan],[0, np.nan, np.nan]) array([ NaN, NaN, NaN]) >>> np.minimum(-np.Inf, 1) -inf """) 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. Parameters ---------- x1, x2 : array_like The arrays holding the elements to be compared. They must have the same shape. Returns ------- y : {ndarray, scalar} The minimum of `x1` and `x2`, element-wise. Returns scalar if both `x1` and `x2` are scalars. See Also -------- fmin : Element-wise minimum of two arrays, ignores NaNs. maximum : Element-wise maximum of two arrays, propagates NaNs. amax : The maximum value of an array along a given axis, propagates NaNs. nanmax : The maximum value of an array along a given axis, ignores NaNs. minimum, amin, nanmin Notes ----- .. 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. Examples -------- >>> np.fmax([2, 3, 4], [1, 5, 2]) array([ 2., 5., 4.]) >>> np.fmax(np.eye(2), [0.5, 2]) array([[ 1. , 2. ], [ 0.5, 2. ]]) >>> np.fmax([np.nan, 0, np.nan],[0, np.nan, np.nan]) array([ 0., 0., NaN]) """) 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. Parameters ---------- x1, x2 : array_like The arrays holding the elements to be compared. They must have the same shape. Returns ------- y : {ndarray, scalar} The minimum of `x1` and `x2`, element-wise. Returns scalar if both `x1` and `x2` are scalars. See Also -------- fmax : Element-wise maximum of two arrays, ignores NaNs. minimum : Element-wise minimum of two arrays, propagates NaNs. amin : The minimum value of an array along a given axis, propagates NaNs. nanmin : The minimum value of an array along a given axis, ignores NaNs. maximum, amax, nanmax Notes ----- .. 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. Examples -------- >>> np.fmin([2, 3, 4], [1, 5, 2]) array([2, 5, 4]) >>> np.fmin(np.eye(2), [0.5, 2]) array([[ 1. , 2. ], [ 0.5, 2. ]]) >>> np.fmin([np.nan, 0, np.nan],[0, np.nan, np.nan]) array([ 0., 0., NaN]) """) add_newdoc('numpy.core.umath', 'modf', """ Return the fractional and integral parts of an array, element-wise. The fractional and integral parts are negative if the given number is negative. Parameters ---------- x : array_like Input array. Returns ------- y1 : ndarray Fractional part of `x`. y2 : ndarray Integral part of `x`. Notes ----- For integer input the return values are floats. Examples -------- >>> np.modf([0, 3.5]) (array([ 0. , 0.5]), array([ 0., 3.])) >>> np.modf(-0.5) (-0.5, -0) """) add_newdoc('numpy.core.umath', 'multiply', """ Multiply arguments element-wise. Parameters ---------- x1, x2 : array_like Input arrays to be multiplied. Returns ------- y : ndarray The product of `x1` and `x2`, element-wise. Returns a scalar if both `x1` and `x2` are scalars. Notes ----- Equivalent to `x1` * `x2` in terms of array broadcasting. Examples -------- >>> np.multiply(2.0, 4.0) 8.0 >>> x1 = np.arange(9.0).reshape((3, 3)) >>> x2 = np.arange(3.0) >>> np.multiply(x1, x2) array([[ 0., 1., 4.], [ 0., 4., 10.], [ 0., 7., 16.]]) """) add_newdoc('numpy.core.umath', 'negative', """ Numerical negative, element-wise. Parameters ---------- x : array_like or scalar Input array. Returns ------- y : ndarray or scalar Returned array or scalar: `y = -x`. Examples -------- >>> np.negative([1.,-1.]) array([-1., 1.]) """) add_newdoc('numpy.core.umath', 'not_equal', """ Return (x1 != x2) element-wise. Parameters ---------- x1, x2 : array_like Input arrays. out : ndarray, optional A placeholder the same shape as `x1` to store the result. See `doc.ufuncs` (Section "Output arguments") for more details. Returns ------- not_equal : ndarray bool, scalar bool For each element in `x1, x2`, return True if `x1` is not equal to `x2` and False otherwise. See Also -------- equal, greater, greater_equal, less, less_equal Examples -------- >>> np.not_equal([1.,2.], [1., 3.]) array([False, True], dtype=bool) >>> np.not_equal([1, 2], [[1, 3],[1, 4]]) array([[False, True], [False, True]], dtype=bool) """) 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. See Also -------- ones_like """) add_newdoc('numpy.core.umath', 'power', """ First array elements raised to powers from second array, element-wise. Raise each base in `x1` to the positionally-corresponding power in `x2`. `x1` and `x2` must be broadcastable to the same shape. Parameters ---------- x1 : array_like The bases. x2 : array_like The exponents. Returns ------- y : ndarray The bases in `x1` raised to the exponents in `x2`. Examples -------- Cube each element in a list. >>> x1 = range(6) >>> x1 [0, 1, 2, 3, 4, 5] >>> np.power(x1, 3) array([ 0, 1, 8, 27, 64, 125]) Raise the bases to different exponents. >>> x2 = [1.0, 2.0, 3.0, 3.0, 2.0, 1.0] >>> np.power(x1, x2) array([ 0., 1., 8., 27., 16., 5.]) The effect of broadcasting. >>> x2 = np.array([[1, 2, 3, 3, 2, 1], [1, 2, 3, 3, 2, 1]]) >>> x2 array([[1, 2, 3, 3, 2, 1], [1, 2, 3, 3, 2, 1]]) >>> np.power(x1, x2) array([[ 0, 1, 8, 27, 16, 5], [ 0, 1, 8, 27, 16, 5]]) """) add_newdoc('numpy.core.umath', 'radians', """ Convert angles from degrees to radians. Parameters ---------- x : array_like Input array in degrees. out : ndarray, optional Output array of same shape as `x`. Returns ------- y : ndarray The corresponding radian values. See Also -------- deg2rad : equivalent function Examples -------- Convert a degree array to radians >>> deg = np.arange(12.) * 30. >>> np.radians(deg) array([ 0. , 0.52359878, 1.04719755, 1.57079633, 2.0943951 , 2.61799388, 3.14159265, 3.66519143, 4.1887902 , 4.71238898, 5.23598776, 5.75958653]) >>> out = np.zeros((deg.shape)) >>> ret = np.radians(deg, out) >>> ret is out True """) add_newdoc('numpy.core.umath', 'deg2rad', """ Convert angles from degrees to radians. Parameters ---------- x : array_like Angles in degrees. Returns ------- y : ndarray The corresponding angle in radians. See Also -------- rad2deg : Convert angles from radians to degrees. unwrap : Remove large jumps in angle by wrapping. Notes ----- .. versionadded:: 1.3.0 ``deg2rad(x)`` is ``x * pi / 180``. Examples -------- >>> np.deg2rad(180) 3.1415926535897931 """) add_newdoc('numpy.core.umath', 'reciprocal', """ Return the reciprocal of the argument, element-wise. Calculates ``1/x``. Parameters ---------- x : array_like Input array. Returns ------- y : ndarray Return array. Notes ----- .. note:: 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. Examples -------- >>> np.reciprocal(2.) 0.5 >>> np.reciprocal([1, 2., 3.33]) array([ 1. , 0.5 , 0.3003003]) """) add_newdoc('numpy.core.umath', 'remainder', """ Return element-wise remainder of division. 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 ---------- x1 : array_like Dividend array. x2 : array_like Divisor array. 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. Returns ------- y : ndarray 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. Examples -------- >>> np.remainder([4, 7], [2, 3]) array([0, 1]) >>> np.remainder(np.arange(7), 5) array([0, 1, 2, 3, 4, 0, 1]) """) add_newdoc('numpy.core.umath', 'right_shift', """ Shift the bits of an integer to the right. 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 ---------- x1 : array_like, int Input values. x2 : array_like, int Number of bits to remove at the right of `x1`. Returns ------- out : ndarray, int Return `x1` with bits shifted `x2` times to the right. See Also -------- left_shift : Shift the bits of an integer to the left. binary_repr : Return the binary representation of the input number as a string. Examples -------- >>> np.binary_repr(10) '1010' >>> np.right_shift(10, 1) 5 >>> np.binary_repr(5) '101' >>> np.right_shift(10, [1,2,3]) array([5, 2, 1]) """) add_newdoc('numpy.core.umath', 'rint', """ Round elements of the array to the nearest integer. Parameters ---------- x : array_like Input array. Returns ------- out : {ndarray, scalar} Output array is same shape and type as `x`. See Also -------- ceil, floor, trunc Examples -------- >>> a = np.array([-1.7, -1.5, -0.2, 0.2, 1.5, 1.7, 2.0]) >>> np.rint(a) array([-2., -2., -0., 0., 2., 2., 2.]) """) add_newdoc('numpy.core.umath', 'sign', """ Returns an element-wise indication of the sign of a number. The `sign` function returns ``-1 if x < 0, 0 if x==0, 1 if x > 0``. Parameters ---------- x : array_like Input values. Returns ------- y : ndarray The sign of `x`. Examples -------- >>> np.sign([-5., 4.5]) array([-1., 1.]) >>> np.sign(0) 0 """) add_newdoc('numpy.core.umath', 'signbit', """ Returns element-wise True where signbit is set (less than zero). Parameters ---------- 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`. Returns ------- result : ndarray of bool Output array, or reference to `out` if that was supplied. Examples -------- >>> np.signbit(-1.2) True >>> np.signbit(np.array([1, -2.3, 2.1])) array([False, True, False], dtype=bool) """) add_newdoc('numpy.core.umath', 'copysign', """ Change the sign of x1 to that of x2, element-wise. If both arguments are arrays or sequences, they have to be of the same length. If `x2` is a scalar, its sign will be copied to all elements of `x1`. Parameters ---------- x1 : array_like Values to change the sign of. x2 : array_like The sign of `x2` is copied to `x1`. 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. Returns ------- out : array_like The values of `x1` with the sign of `x2`. Examples -------- >>> np.copysign(1.3, -1) -1.3 >>> 1/np.copysign(0, 1) inf >>> 1/np.copysign(0, -1) -inf >>> np.copysign([-1, 0, 1], -1.1) array([-1., -0., -1.]) >>> np.copysign([-1, 0, 1], np.arange(3)-1) array([-1., 0., 1.]) """) add_newdoc('numpy.core.umath', 'nextafter', """ Return the next floating-point value after x1 towards x2, element-wise. Parameters ---------- x1 : array_like Values to find the next representable value of. x2 : array_like The direction where to look for the next representable value of `x1`. 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`. Returns ------- out : array_like The next representable values of `x1` in the direction of `x2`. Examples -------- >>> eps = np.finfo(np.float64).eps >>> np.nextafter(1, 2) == eps + 1 True >>> np.nextafter([1, 2], [2, 1]) == [eps + 1, 2 - eps] array([ True, True], dtype=bool) """) add_newdoc('numpy.core.umath', 'spacing', """ Return the distance between x and the nearest adjacent number. Parameters ---------- x1 : array_like Values to find the spacing of. Returns ------- out : array_like The spacing of values of `x1`. Notes ----- It can be considered as a generalization of EPS: ``spacing(np.float64(1)) == np.finfo(np.float64).eps``, and there should not be any representable number between ``x + spacing(x)`` and x for any finite x. Spacing of +- inf and NaN is NaN. Examples -------- >>> np.spacing(1) == np.finfo(np.float64).eps True """) add_newdoc('numpy.core.umath', 'sin', """ Trigonometric sine, element-wise. Parameters ---------- x : array_like Angle, in radians (:math:`2 \\pi` rad equals 360 degrees). Returns ------- y : array_like The sine of each element of x. See Also -------- arcsin, sinh, cos 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. Examples -------- Print sine of one angle: >>> np.sin(np.pi/2.) 1.0 Print sines of an array of angles given in degrees: >>> np.sin(np.array((0., 30., 45., 60., 90.)) * np.pi / 180. ) array([ 0. , 0.5 , 0.70710678, 0.8660254 , 1. ]) Plot the sine function: >>> import matplotlib.pylab as plt >>> x = np.linspace(-np.pi, np.pi, 201) >>> plt.plot(x, np.sin(x)) >>> plt.xlabel('Angle [rad]') >>> plt.ylabel('sin(x)') >>> plt.axis('tight') >>> plt.show() """) add_newdoc('numpy.core.umath', 'sinh', """ Hyperbolic sine, element-wise. Equivalent to ``1/2 * (np.exp(x) - np.exp(-x))`` or ``-1j * np.sin(1j*x)``. Parameters ---------- x : array_like Input array. out : ndarray, optional Output array of same shape as `x`. Returns ------- y : ndarray The corresponding hyperbolic sine values. Raises ------ ValueError: invalid return array shape if `out` is provided and `out.shape` != `x.shape` (See Examples) Notes ----- If `out` is provided, the function writes the result into it, and returns a reference to `out`. (See Examples) References ---------- M. Abramowitz and I. A. Stegun, Handbook of Mathematical Functions. New York, NY: Dover, 1972, pg. 83. Examples -------- >>> np.sinh(0) 0.0 >>> np.sinh(np.pi*1j/2) 1j >>> np.sinh(np.pi*1j) # (exact value is 0) 1.2246063538223773e-016j >>> # Discrepancy due to vagaries of floating point arithmetic. >>> # Example of providing the optional output parameter >>> out2 = np.sinh([0.1], out1) >>> out2 is out1 True >>> # Example of ValueError due to provision of shape mis-matched `out` >>> np.sinh(np.zeros((3,3)),np.zeros((2,2))) Traceback (most recent call last): File "", line 1, in ValueError: invalid return array shape """) add_newdoc('numpy.core.umath', 'sqrt', """ Return the positive square-root of an array, element-wise. Parameters ---------- x : array_like The values whose square-roots are required. out : ndarray, optional Alternate array object in which to put the result; if provided, it must have the same shape as `x` Returns ------- y : ndarray An array of the same shape as `x`, containing the positive square-root of each element in `x`. If any element in `x` is complex, a complex array is returned (and the square-roots of negative reals are calculated). If all of the elements in `x` are real, so is `y`, with negative elements returning ``nan``. If `out` was provided, `y` is a reference to it. See Also -------- lib.scimath.sqrt A version which returns complex numbers when given negative reals. Notes ----- *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. Examples -------- >>> np.sqrt([1,4,9]) array([ 1., 2., 3.]) >>> np.sqrt([4, -1, -3+4J]) array([ 2.+0.j, 0.+1.j, 1.+2.j]) >>> np.sqrt([4, -1, numpy.inf]) array([ 2., NaN, Inf]) """) add_newdoc('numpy.core.umath', 'square', """ Return the element-wise square of the input. Parameters ---------- x : array_like Input data. Returns ------- out : ndarray Element-wise `x*x`, of the same shape and dtype as `x`. Returns scalar if `x` is a scalar. See Also -------- numpy.linalg.matrix_power sqrt power Examples -------- >>> np.square([-1j, 1]) array([-1.-0.j, 1.+0.j]) """) add_newdoc('numpy.core.umath', 'subtract', """ Subtract arguments, element-wise. Parameters ---------- x1, x2 : array_like The arrays to be subtracted from each other. Returns ------- y : ndarray The difference of `x1` and `x2`, element-wise. Returns a scalar if both `x1` and `x2` are scalars. Notes ----- Equivalent to ``x1 - x2`` in terms of array broadcasting. Examples -------- >>> np.subtract(1.0, 4.0) -3.0 >>> x1 = np.arange(9.0).reshape((3, 3)) >>> x2 = np.arange(3.0) >>> np.subtract(x1, x2) array([[ 0., 0., 0.], [ 3., 3., 3.], [ 6., 6., 6.]]) """) add_newdoc('numpy.core.umath', 'tan', """ Compute tangent element-wise. Equivalent to ``np.sin(x)/np.cos(x)`` element-wise. Parameters ---------- x : array_like Input array. out : ndarray, optional Output array of same shape as `x`. Returns ------- y : ndarray The corresponding tangent values. Raises ------ ValueError: invalid return array shape if `out` is provided and `out.shape` != `x.shape` (See Examples) Notes ----- If `out` is provided, the function writes the result into it, and returns a reference to `out`. (See Examples) References ---------- M. Abramowitz and I. A. Stegun, Handbook of Mathematical Functions. New York, NY: Dover, 1972. Examples -------- >>> from math import pi >>> np.tan(np.array([-pi,pi/2,pi])) array([ 1.22460635e-16, 1.63317787e+16, -1.22460635e-16]) >>> >>> # Example of providing the optional output parameter illustrating >>> # that what is returned is a reference to said parameter >>> out2 = np.cos([0.1], out1) >>> out2 is out1 True >>> >>> # Example of ValueError due to provision of shape mis-matched `out` >>> np.cos(np.zeros((3,3)),np.zeros((2,2))) Traceback (most recent call last): File "", line 1, in ValueError: invalid return array shape """) 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)``. Parameters ---------- x : array_like Input array. out : ndarray, optional Output array of same shape as `x`. Returns ------- y : ndarray The corresponding hyperbolic tangent values. Raises ------ ValueError: invalid return array shape if `out` is provided and `out.shape` != `x.shape` (See Examples) Notes ----- If `out` is provided, the function writes the result into it, and returns a reference to `out`. (See Examples) References ---------- .. [1] M. Abramowitz and I. A. Stegun, Handbook of Mathematical Functions. New York, NY: Dover, 1972, pg. 83. http://www.math.sfu.ca/~cbm/aands/ .. [2] Wikipedia, "Hyperbolic function", http://en.wikipedia.org/wiki/Hyperbolic_function Examples -------- >>> np.tanh((0, np.pi*1j, np.pi*1j/2)) array([ 0. +0.00000000e+00j, 0. -1.22460635e-16j, 0. +1.63317787e+16j]) >>> # Example of providing the optional output parameter illustrating >>> # that what is returned is a reference to said parameter >>> out2 = np.tanh([0.1], out1) >>> out2 is out1 True >>> # Example of ValueError due to provision of shape mis-matched `out` >>> np.tanh(np.zeros((3,3)),np.zeros((2,2))) Traceback (most recent call last): File "", line 1, in ValueError: invalid return array shape """) add_newdoc('numpy.core.umath', 'true_divide', """ Returns a true division of the inputs, element-wise. Instead of the Python traditional 'floor division', this returns a true division. True division adjusts the output type to present the best answer, regardless of input types. Parameters ---------- x1 : array_like Dividend array. x2 : array_like Divisor array. Returns ------- out : ndarray Result is scalar if both inputs are scalar, ndarray otherwise. 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``. In Python 3.0, ``//`` is the floor division operator and ``/`` the true division operator. The ``true_divide(x1, x2)`` function is equivalent to true division in Python. Examples -------- >>> x = np.arange(5) >>> np.true_divide(x, 4) array([ 0. , 0.25, 0.5 , 0.75, 1. ]) >>> x/4 array([0, 0, 0, 0, 1]) >>> x//4 array([0, 0, 0, 0, 1]) >>> from __future__ import division >>> x/4 array([ 0. , 0.25, 0.5 , 0.75, 1. ]) >>> x//4 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.]) """) numpy-1.8.2/numpy/core/defchararray.py0000664000175100017510000020453412370216242021140 0ustar vagrantvagrant00000000000000""" This module contains a set of functions for vectorized string operations and methods. .. note:: The `chararray` class exists for backwards compatibility with Numarray, it is not recommended for new development. Starting from numpy 1.4, if one needs arrays of strings, it is recommended to use arrays of `dtype` `object_`, `string_` or `unicode_`, and use the free functions in the `numpy.char` module for fast vectorized string operations. Some methods will only be available if the corresponding string method is available in your version of Python. The preferred alias for `defchararray` is `numpy.char`. """ from __future__ import division, absolute_import, print_function import sys from .numerictypes import string_, unicode_, integer, object_, bool_, character from .numeric import ndarray, compare_chararrays from .numeric import array as narray from numpy.core.multiarray import _vec_string from numpy.compat import asbytes, long import numpy __all__ = ['chararray', 'equal', 'not_equal', 'greater_equal', 'less_equal', 'greater', 'less', 'str_len', 'add', 'multiply', 'mod', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill', 'isnumeric', 'isdecimal', 'array', 'asarray'] _globalvar = 0 if sys.version_info[0] >= 3: _unicode = str _bytes = bytes else: _unicode = unicode _bytes = str _len = len def _use_unicode(*args): """ Helper function for determining the output type of some string operations. For an operation on two ndarrays, if at least one is unicode, the result should be unicode. """ for x in args: if (isinstance(x, _unicode) or issubclass(numpy.asarray(x).dtype.type, unicode_)): return unicode_ return string_ def _to_string_or_unicode_array(result): """ Helper function to cast a result back into a string or unicode array if an object array must be used as an intermediary. """ return numpy.asarray(result.tolist()) def _clean_args(*args): """ Helper function for delegating arguments to Python string functions. Many of the Python string operations that have optional arguments do not use 'None' to indicate a default value. In these cases, we need to remove all `None` arguments, and those following them. """ newargs = [] for chk in args: if chk is None: break newargs.append(chk) return newargs def _get_num_chars(a): """ Helper function that returns the number of characters per field in a string or unicode array. This is to abstract out the fact that for a unicode array this is itemsize / 4. """ if issubclass(a.dtype.type, unicode_): return a.itemsize // 4 return a.itemsize def equal(x1, x2): """ Return (x1 == x2) element-wise. Unlike `numpy.equal`, this comparison is performed by first stripping whitespace characters from the end of the string. This behavior is provided for backward-compatibility with numarray. Parameters ---------- x1, x2 : array_like of str or unicode Input arrays of the same shape. Returns ------- out : {ndarray, bool} Output array of bools, or a single bool if x1 and x2 are scalars. See Also -------- not_equal, greater_equal, less_equal, greater, less """ return compare_chararrays(x1, x2, '==', True) def not_equal(x1, x2): """ Return (x1 != x2) element-wise. Unlike `numpy.not_equal`, this comparison is performed by first stripping whitespace characters from the end of the string. This behavior is provided for backward-compatibility with numarray. Parameters ---------- x1, x2 : array_like of str or unicode Input arrays of the same shape. Returns ------- out : {ndarray, bool} Output array of bools, or a single bool if x1 and x2 are scalars. See Also -------- equal, greater_equal, less_equal, greater, less """ return compare_chararrays(x1, x2, '!=', True) def greater_equal(x1, x2): """ Return (x1 >= x2) element-wise. Unlike `numpy.greater_equal`, this comparison is performed by first stripping whitespace characters from the end of the string. This behavior is provided for backward-compatibility with numarray. Parameters ---------- x1, x2 : array_like of str or unicode Input arrays of the same shape. Returns ------- out : {ndarray, bool} Output array of bools, or a single bool if x1 and x2 are scalars. See Also -------- equal, not_equal, less_equal, greater, less """ return compare_chararrays(x1, x2, '>=', True) def less_equal(x1, x2): """ Return (x1 <= x2) element-wise. Unlike `numpy.less_equal`, this comparison is performed by first stripping whitespace characters from the end of the string. This behavior is provided for backward-compatibility with numarray. Parameters ---------- x1, x2 : array_like of str or unicode Input arrays of the same shape. Returns ------- out : {ndarray, bool} Output array of bools, or a single bool if x1 and x2 are scalars. See Also -------- equal, not_equal, greater_equal, greater, less """ return compare_chararrays(x1, x2, '<=', True) def greater(x1, x2): """ Return (x1 > x2) element-wise. Unlike `numpy.greater`, this comparison is performed by first stripping whitespace characters from the end of the string. This behavior is provided for backward-compatibility with numarray. Parameters ---------- x1, x2 : array_like of str or unicode Input arrays of the same shape. Returns ------- out : {ndarray, bool} Output array of bools, or a single bool if x1 and x2 are scalars. See Also -------- equal, not_equal, greater_equal, less_equal, less """ return compare_chararrays(x1, x2, '>', True) def less(x1, x2): """ Return (x1 < x2) element-wise. Unlike `numpy.greater`, this comparison is performed by first stripping whitespace characters from the end of the string. This behavior is provided for backward-compatibility with numarray. Parameters ---------- x1, x2 : array_like of str or unicode Input arrays of the same shape. Returns ------- out : {ndarray, bool} Output array of bools, or a single bool if x1 and x2 are scalars. See Also -------- equal, not_equal, greater_equal, less_equal, greater """ return compare_chararrays(x1, x2, '<', True) def str_len(a): """ Return len(a) element-wise. Parameters ---------- a : array_like of str or unicode Returns ------- out : ndarray Output array of integers See also -------- __builtin__.len """ return _vec_string(a, integer, '__len__') def add(x1, x2): """ Return element-wise string concatenation for two arrays of str or unicode. Arrays `x1` and `x2` must have the same shape. Parameters ---------- x1 : array_like of str or unicode Input array. x2 : array_like of str or unicode Input array. Returns ------- add : ndarray Output array of `string_` or `unicode_`, depending on input types of the same shape as `x1` and `x2`. """ arr1 = numpy.asarray(x1) arr2 = numpy.asarray(x2) out_size = _get_num_chars(arr1) + _get_num_chars(arr2) dtype = _use_unicode(arr1, arr2) return _vec_string(arr1, (dtype, out_size), '__add__', (arr2,)) def multiply(a, i): """ Return (a * i), that is string multiple concatenation, element-wise. Values in `i` of less than 0 are treated as 0 (which yields an empty string). Parameters ---------- a : array_like of str or unicode i : array_like of ints Returns ------- out : ndarray Output array of str or unicode, depending on input types """ a_arr = numpy.asarray(a) i_arr = numpy.asarray(i) if not issubclass(i_arr.dtype.type, integer): raise ValueError("Can only multiply by integers") out_size = _get_num_chars(a_arr) * max(long(i_arr.max()), 0) return _vec_string( a_arr, (a_arr.dtype.type, out_size), '__mul__', (i_arr,)) def mod(a, values): """ Return (a % i), that is pre-Python 2.6 string formatting (iterpolation), element-wise for a pair of array_likes of str or unicode. Parameters ---------- a : array_like of str or unicode values : array_like of values These values will be element-wise interpolated into the string. Returns ------- out : ndarray Output array of str or unicode, depending on input types See also -------- str.__mod__ """ return _to_string_or_unicode_array( _vec_string(a, object_, '__mod__', (values,))) def capitalize(a): """ Return a copy of `a` with only the first character of each element capitalized. Calls `str.capitalize` element-wise. For 8-bit strings, this method is locale-dependent. Parameters ---------- a : array_like of str or unicode Input array of strings to capitalize. Returns ------- out : ndarray Output array of str or unicode, depending on input types See also -------- str.capitalize Examples -------- >>> c = np.array(['a1b2','1b2a','b2a1','2a1b'],'S4'); c array(['a1b2', '1b2a', 'b2a1', '2a1b'], dtype='|S4') >>> np.char.capitalize(c) array(['A1b2', '1b2a', 'B2a1', '2a1b'], dtype='|S4') """ a_arr = numpy.asarray(a) return _vec_string(a_arr, a_arr.dtype, 'capitalize') def center(a, width, fillchar=' '): """ Return a copy of `a` with its elements centered in a string of length `width`. Calls `str.center` element-wise. Parameters ---------- a : array_like of str or unicode width : int The length of the resulting strings fillchar : str or unicode, optional The padding character to use (default is space). Returns ------- out : ndarray Output array of str or unicode, depending on input types See also -------- str.center """ a_arr = numpy.asarray(a) width_arr = numpy.asarray(width) size = long(numpy.max(width_arr.flat)) if numpy.issubdtype(a_arr.dtype, numpy.string_): fillchar = asbytes(fillchar) return _vec_string( a_arr, (a_arr.dtype.type, size), 'center', (width_arr, fillchar)) def count(a, sub, start=0, end=None): """ Returns an array with the number of non-overlapping occurrences of substring `sub` in the range [`start`, `end`]. Calls `str.count` element-wise. Parameters ---------- a : array_like of str or unicode sub : str or unicode The substring to search for. start, end : int, optional Optional arguments `start` and `end` are interpreted as slice notation to specify the range in which to count. Returns ------- out : ndarray Output array of ints. See also -------- str.count Examples -------- >>> c = np.array(['aAaAaA', ' aA ', 'abBABba']) >>> c array(['aAaAaA', ' aA ', 'abBABba'], dtype='|S7') >>> np.char.count(c, 'A') array([3, 1, 1]) >>> np.char.count(c, 'aA') array([3, 1, 0]) >>> np.char.count(c, 'A', start=1, end=4) array([2, 1, 1]) >>> np.char.count(c, 'A', start=1, end=3) array([1, 0, 0]) """ return _vec_string(a, integer, 'count', [sub, start] + _clean_args(end)) def decode(a, encoding=None, errors=None): """ Calls `str.decode` element-wise. The set of available codecs comes from the Python standard library, and may be extended at runtime. For more information, see the :mod:`codecs` module. Parameters ---------- a : array_like of str or unicode encoding : str, optional The name of an encoding errors : str, optional Specifies how to handle encoding errors Returns ------- out : ndarray See also -------- str.decode Notes ----- The type of the result will depend on the encoding specified. Examples -------- >>> c = np.array(['aAaAaA', ' aA ', 'abBABba']) >>> c array(['aAaAaA', ' aA ', 'abBABba'], dtype='|S7') >>> np.char.encode(c, encoding='cp037') array(['\\x81\\xc1\\x81\\xc1\\x81\\xc1', '@@\\x81\\xc1@@', '\\x81\\x82\\xc2\\xc1\\xc2\\x82\\x81'], dtype='|S7') """ return _to_string_or_unicode_array( _vec_string(a, object_, 'decode', _clean_args(encoding, errors))) def encode(a, encoding=None, errors=None): """ Calls `str.encode` element-wise. The set of available codecs comes from the Python standard library, and may be extended at runtime. For more information, see the codecs module. Parameters ---------- a : array_like of str or unicode encoding : str, optional The name of an encoding errors : str, optional Specifies how to handle encoding errors Returns ------- out : ndarray See also -------- str.encode Notes ----- The type of the result will depend on the encoding specified. """ return _to_string_or_unicode_array( _vec_string(a, object_, 'encode', _clean_args(encoding, errors))) def endswith(a, suffix, start=0, end=None): """ Returns a boolean array which is `True` where the string element in `a` ends with `suffix`, otherwise `False`. Calls `str.endswith` element-wise. Parameters ---------- a : array_like of str or unicode suffix : str start, end : int, optional With optional `start`, test beginning at that position. With optional `end`, stop comparing at that position. Returns ------- out : ndarray Outputs an array of bools. See also -------- str.endswith Examples -------- >>> s = np.array(['foo', 'bar']) >>> s[0] = 'foo' >>> s[1] = 'bar' >>> s array(['foo', 'bar'], dtype='|S3') >>> np.char.endswith(s, 'ar') array([False, True], dtype=bool) >>> np.char.endswith(s, 'a', start=1, end=2) array([False, True], dtype=bool) """ return _vec_string( a, bool_, 'endswith', [suffix, start] + _clean_args(end)) def expandtabs(a, tabsize=8): """ Return a copy of each string element where all tab characters are replaced by one or more spaces. Calls `str.expandtabs` element-wise. Return a copy of each string element where all tab characters are replaced by one or more spaces, depending on the current column and the given `tabsize`. The column number is reset to zero after each newline occurring in the string. This doesn't understand other non-printing characters or escape sequences. Parameters ---------- a : array_like of str or unicode Input array tabsize : int, optional Replace tabs with `tabsize` number of spaces. If not given defaults to 8 spaces. Returns ------- out : ndarray Output array of str or unicode, depending on input type See also -------- str.expandtabs """ return _to_string_or_unicode_array( _vec_string(a, object_, 'expandtabs', (tabsize,))) def find(a, sub, start=0, end=None): """ For each element, return the lowest index in the string where substring `sub` is found. Calls `str.find` element-wise. For each element, return the lowest index in the string where substring `sub` is found, such that `sub` is contained in the range [`start`, `end`]. Parameters ---------- a : array_like of str or unicode sub : str or unicode start, end : int, optional Optional arguments `start` and `end` are interpreted as in slice notation. Returns ------- out : ndarray or int Output array of ints. Returns -1 if `sub` is not found. See also -------- str.find """ return _vec_string( a, integer, 'find', [sub, start] + _clean_args(end)) def index(a, sub, start=0, end=None): """ Like `find`, but raises `ValueError` when the substring is not found. Calls `str.index` element-wise. Parameters ---------- a : array_like of str or unicode sub : str or unicode start, end : int, optional Returns ------- out : ndarray Output array of ints. Returns -1 if `sub` is not found. See also -------- find, str.find """ return _vec_string( a, integer, 'index', [sub, start] + _clean_args(end)) def isalnum(a): """ Returns true for each element if all characters in the string are alphanumeric and there is at least one character, false otherwise. Calls `str.isalnum` element-wise. For 8-bit strings, this method is locale-dependent. Parameters ---------- a : array_like of str or unicode Returns ------- out : ndarray Output array of str or unicode, depending on input type See also -------- str.isalnum """ return _vec_string(a, bool_, 'isalnum') def isalpha(a): """ Returns true for each element if all characters in the string are alphabetic and there is at least one character, false otherwise. Calls `str.isalpha` element-wise. For 8-bit strings, this method is locale-dependent. Parameters ---------- a : array_like of str or unicode Returns ------- out : ndarray Output array of bools See also -------- str.isalpha """ return _vec_string(a, bool_, 'isalpha') def isdigit(a): """ Returns true for each element if all characters in the string are digits and there is at least one character, false otherwise. Calls `str.isdigit` element-wise. For 8-bit strings, this method is locale-dependent. Parameters ---------- a : array_like of str or unicode Returns ------- out : ndarray Output array of bools See also -------- str.isdigit """ return _vec_string(a, bool_, 'isdigit') def islower(a): """ Returns true for each element if all cased characters in the string are lowercase and there is at least one cased character, false otherwise. Calls `str.islower` element-wise. For 8-bit strings, this method is locale-dependent. Parameters ---------- a : array_like of str or unicode Returns ------- out : ndarray Output array of bools See also -------- str.islower """ return _vec_string(a, bool_, 'islower') def isspace(a): """ Returns true for each element if there are only whitespace characters in the string and there is at least one character, false otherwise. Calls `str.isspace` element-wise. For 8-bit strings, this method is locale-dependent. Parameters ---------- a : array_like of str or unicode Returns ------- out : ndarray Output array of bools See also -------- str.isspace """ return _vec_string(a, bool_, 'isspace') def istitle(a): """ Returns true for each element if the element is a titlecased string and there is at least one character, false otherwise. Call `str.istitle` element-wise. For 8-bit strings, this method is locale-dependent. Parameters ---------- a : array_like of str or unicode Returns ------- out : ndarray Output array of bools See also -------- str.istitle """ return _vec_string(a, bool_, 'istitle') def isupper(a): """ Returns true for each element if all cased characters in the string are uppercase and there is at least one character, false otherwise. Call `str.isupper` element-wise. For 8-bit strings, this method is locale-dependent. Parameters ---------- a : array_like of str or unicode Returns ------- out : ndarray Output array of bools See also -------- str.isupper """ return _vec_string(a, bool_, 'isupper') def join(sep, seq): """ Return a string which is the concatenation of the strings in the sequence `seq`. Calls `str.join` element-wise. Parameters ---------- sep : array_like of str or unicode seq : array_like of str or unicode Returns ------- out : ndarray Output array of str or unicode, depending on input types See also -------- str.join """ return _to_string_or_unicode_array( _vec_string(sep, object_, 'join', (seq,))) def ljust(a, width, fillchar=' '): """ Return an array with the elements of `a` left-justified in a string of length `width`. Calls `str.ljust` element-wise. Parameters ---------- a : array_like of str or unicode width : int The length of the resulting strings fillchar : str or unicode, optional The character to use for padding Returns ------- out : ndarray Output array of str or unicode, depending on input type See also -------- str.ljust """ a_arr = numpy.asarray(a) width_arr = numpy.asarray(width) size = long(numpy.max(width_arr.flat)) if numpy.issubdtype(a_arr.dtype, numpy.string_): fillchar = asbytes(fillchar) return _vec_string( a_arr, (a_arr.dtype.type, size), 'ljust', (width_arr, fillchar)) def lower(a): """ Return an array with the elements converted to lowercase. Call `str.lower` element-wise. For 8-bit strings, this method is locale-dependent. Parameters ---------- a : array_like, {str, unicode} Input array. Returns ------- out : ndarray, {str, unicode} Output array of str or unicode, depending on input type See also -------- str.lower Examples -------- >>> c = np.array(['A1B C', '1BCA', 'BCA1']); c array(['A1B C', '1BCA', 'BCA1'], dtype='|S5') >>> np.char.lower(c) array(['a1b c', '1bca', 'bca1'], dtype='|S5') """ a_arr = numpy.asarray(a) return _vec_string(a_arr, a_arr.dtype, 'lower') def lstrip(a, chars=None): """ For each element in `a`, return a copy with the leading characters removed. Calls `str.lstrip` element-wise. Parameters ---------- a : array-like, {str, unicode} Input array. chars : {str, unicode}, optional The `chars` argument is a string specifying the set of characters to be removed. If omitted or None, the `chars` argument defaults to removing whitespace. The `chars` argument is not a prefix; rather, all combinations of its values are stripped. Returns ------- out : ndarray, {str, unicode} Output array of str or unicode, depending on input type See also -------- str.lstrip Examples -------- >>> c = np.array(['aAaAaA', ' aA ', 'abBABba']) >>> c array(['aAaAaA', ' aA ', 'abBABba'], dtype='|S7') The 'a' variable is unstripped from c[1] because whitespace leading. >>> np.char.lstrip(c, 'a') array(['AaAaA', ' aA ', 'bBABba'], dtype='|S7') >>> np.char.lstrip(c, 'A') # leaves c unchanged array(['aAaAaA', ' aA ', 'abBABba'], dtype='|S7') >>> (np.char.lstrip(c, ' ') == np.char.lstrip(c, '')).all() ... # XXX: is this a regression? this line now returns False ... # np.char.lstrip(c,'') does not modify c at all. True >>> (np.char.lstrip(c, ' ') == np.char.lstrip(c, None)).all() True """ a_arr = numpy.asarray(a) return _vec_string(a_arr, a_arr.dtype, 'lstrip', (chars,)) def partition(a, sep): """ Partition each element in `a` around `sep`. Calls `str.partition` element-wise. For each element in `a`, split the element as the first occurrence of `sep`, and return 3 strings containing the part before the separator, the separator itself, and the part after the separator. If the separator is not found, return 3 strings containing the string itself, followed by two empty strings. Parameters ---------- a : array_like, {str, unicode} Input array sep : {str, unicode} Separator to split each string element in `a`. Returns ------- out : ndarray, {str, unicode} Output array of str or unicode, depending on input type. The output array will have an extra dimension with 3 elements per input element. See also -------- str.partition """ return _to_string_or_unicode_array( _vec_string(a, object_, 'partition', (sep,))) def replace(a, old, new, count=None): """ For each element in `a`, return a copy of the string with all occurrences of substring `old` replaced by `new`. Calls `str.replace` element-wise. Parameters ---------- a : array-like of str or unicode old, new : str or unicode count : int, optional If the optional argument `count` is given, only the first `count` occurrences are replaced. Returns ------- out : ndarray Output array of str or unicode, depending on input type See also -------- str.replace """ return _to_string_or_unicode_array( _vec_string( a, object_, 'replace', [old, new] +_clean_args(count))) def rfind(a, sub, start=0, end=None): """ For each element in `a`, return the highest index in the string where substring `sub` is found, such that `sub` is contained within [`start`, `end`]. Calls `str.rfind` element-wise. Parameters ---------- a : array-like of str or unicode sub : str or unicode start, end : int, optional Optional arguments `start` and `end` are interpreted as in slice notation. Returns ------- out : ndarray Output array of ints. Return -1 on failure. See also -------- str.rfind """ return _vec_string( a, integer, 'rfind', [sub, start] + _clean_args(end)) def rindex(a, sub, start=0, end=None): """ Like `rfind`, but raises `ValueError` when the substring `sub` is not found. Calls `str.rindex` element-wise. Parameters ---------- a : array-like of str or unicode sub : str or unicode start, end : int, optional Returns ------- out : ndarray Output array of ints. See also -------- rfind, str.rindex """ return _vec_string( a, integer, 'rindex', [sub, start] + _clean_args(end)) def rjust(a, width, fillchar=' '): """ Return an array with the elements of `a` right-justified in a string of length `width`. Calls `str.rjust` element-wise. Parameters ---------- a : array_like of str or unicode width : int The length of the resulting strings fillchar : str or unicode, optional The character to use for padding Returns ------- out : ndarray Output array of str or unicode, depending on input type See also -------- str.rjust """ a_arr = numpy.asarray(a) width_arr = numpy.asarray(width) size = long(numpy.max(width_arr.flat)) if numpy.issubdtype(a_arr.dtype, numpy.string_): fillchar = asbytes(fillchar) return _vec_string( a_arr, (a_arr.dtype.type, size), 'rjust', (width_arr, fillchar)) def rpartition(a, sep): """ Partition (split) each element around the right-most separator. Calls `str.rpartition` element-wise. For each element in `a`, split the element as the last occurrence of `sep`, and return 3 strings containing the part before the separator, the separator itself, and the part after the separator. If the separator is not found, return 3 strings containing the string itself, followed by two empty strings. Parameters ---------- a : array_like of str or unicode Input array sep : str or unicode Right-most separator to split each element in array. Returns ------- out : ndarray Output array of string or unicode, depending on input type. The output array will have an extra dimension with 3 elements per input element. See also -------- str.rpartition """ return _to_string_or_unicode_array( _vec_string(a, object_, 'rpartition', (sep,))) def rsplit(a, sep=None, maxsplit=None): """ For each element in `a`, return a list of the words in the string, using `sep` as the delimiter string. Calls `str.rsplit` element-wise. Except for splitting from the right, `rsplit` behaves like `split`. Parameters ---------- a : array_like of str or unicode sep : str or unicode, optional If `sep` is not specified or `None`, any whitespace string is a separator. maxsplit : int, optional If `maxsplit` is given, at most `maxsplit` splits are done, the rightmost ones. Returns ------- out : ndarray Array of list objects See also -------- str.rsplit, split """ # This will return an array of lists of different sizes, so we # leave it as an object array return _vec_string( a, object_, 'rsplit', [sep] + _clean_args(maxsplit)) def rstrip(a, chars=None): """ For each element in `a`, return a copy with the trailing characters removed. Calls `str.rstrip` element-wise. Parameters ---------- a : array-like of str or unicode chars : str or unicode, optional The `chars` argument is a string specifying the set of characters to be removed. If omitted or None, the `chars` argument defaults to removing whitespace. The `chars` argument is not a suffix; rather, all combinations of its values are stripped. Returns ------- out : ndarray Output array of str or unicode, depending on input type See also -------- str.rstrip Examples -------- >>> c = np.array(['aAaAaA', 'abBABba'], dtype='S7'); c array(['aAaAaA', 'abBABba'], dtype='|S7') >>> np.char.rstrip(c, 'a') array(['aAaAaA', 'abBABb'], dtype='|S7') >>> np.char.rstrip(c, 'A') array(['aAaAa', 'abBABba'], dtype='|S7') """ a_arr = numpy.asarray(a) return _vec_string(a_arr, a_arr.dtype, 'rstrip', (chars,)) def split(a, sep=None, maxsplit=None): """ For each element in `a`, return a list of the words in the string, using `sep` as the delimiter string. Calls `str.rsplit` element-wise. Parameters ---------- a : array_like of str or unicode sep : str or unicode, optional If `sep` is not specified or `None`, any whitespace string is a separator. maxsplit : int, optional If `maxsplit` is given, at most `maxsplit` splits are done. Returns ------- out : ndarray Array of list objects See also -------- str.split, rsplit """ # This will return an array of lists of different sizes, so we # leave it as an object array return _vec_string( a, object_, 'split', [sep] + _clean_args(maxsplit)) def splitlines(a, keepends=None): """ For each element in `a`, return a list of the lines in the element, breaking at line boundaries. Calls `str.splitlines` element-wise. Parameters ---------- a : array_like of str or unicode keepends : bool, optional Line breaks are not included in the resulting list unless keepends is given and true. Returns ------- out : ndarray Array of list objects See also -------- str.splitlines """ return _vec_string( a, object_, 'splitlines', _clean_args(keepends)) def startswith(a, prefix, start=0, end=None): """ Returns a boolean array which is `True` where the string element in `a` starts with `prefix`, otherwise `False`. Calls `str.startswith` element-wise. Parameters ---------- a : array_like of str or unicode prefix : str start, end : int, optional With optional `start`, test beginning at that position. With optional `end`, stop comparing at that position. Returns ------- out : ndarray Array of booleans See also -------- str.startswith """ return _vec_string( a, bool_, 'startswith', [prefix, start] + _clean_args(end)) def strip(a, chars=None): """ For each element in `a`, return a copy with the leading and trailing characters removed. Calls `str.rstrip` element-wise. Parameters ---------- a : array-like of str or unicode chars : str or unicode, optional The `chars` argument is a string specifying the set of characters to be removed. If omitted or None, the `chars` argument defaults to removing whitespace. The `chars` argument is not a prefix or suffix; rather, all combinations of its values are stripped. Returns ------- out : ndarray Output array of str or unicode, depending on input type See also -------- str.strip Examples -------- >>> c = np.array(['aAaAaA', ' aA ', 'abBABba']) >>> c array(['aAaAaA', ' aA ', 'abBABba'], dtype='|S7') >>> np.char.strip(c) array(['aAaAaA', 'aA', 'abBABba'], dtype='|S7') >>> np.char.strip(c, 'a') # 'a' unstripped from c[1] because whitespace leads array(['AaAaA', ' aA ', 'bBABb'], dtype='|S7') >>> np.char.strip(c, 'A') # 'A' unstripped from c[1] because (unprinted) ws trails array(['aAaAa', ' aA ', 'abBABba'], dtype='|S7') """ a_arr = numpy.asarray(a) return _vec_string(a_arr, a_arr.dtype, 'strip', _clean_args(chars)) def swapcase(a): """ Return element-wise a copy of the string with uppercase characters converted to lowercase and vice versa. Calls `str.swapcase` element-wise. For 8-bit strings, this method is locale-dependent. Parameters ---------- a : array_like, {str, unicode} Input array. Returns ------- out : ndarray, {str, unicode} Output array of str or unicode, depending on input type See also -------- str.swapcase Examples -------- >>> c=np.array(['a1B c','1b Ca','b Ca1','cA1b'],'S5'); c array(['a1B c', '1b Ca', 'b Ca1', 'cA1b'], dtype='|S5') >>> np.char.swapcase(c) array(['A1b C', '1B cA', 'B cA1', 'Ca1B'], dtype='|S5') """ a_arr = numpy.asarray(a) return _vec_string(a_arr, a_arr.dtype, 'swapcase') def title(a): """ Return element-wise title cased version of string or unicode. Title case words start with uppercase characters, all remaining cased characters are lowercase. Calls `str.title` element-wise. For 8-bit strings, this method is locale-dependent. Parameters ---------- a : array_like, {str, unicode} Input array. Returns ------- out : ndarray Output array of str or unicode, depending on input type See also -------- str.title Examples -------- >>> c=np.array(['a1b c','1b ca','b ca1','ca1b'],'S5'); c array(['a1b c', '1b ca', 'b ca1', 'ca1b'], dtype='|S5') >>> np.char.title(c) array(['A1B C', '1B Ca', 'B Ca1', 'Ca1B'], dtype='|S5') """ a_arr = numpy.asarray(a) return _vec_string(a_arr, a_arr.dtype, 'title') def translate(a, table, deletechars=None): """ For each element in `a`, return a copy of the string where all characters occurring in the optional argument `deletechars` are removed, and the remaining characters have been mapped through the given translation table. Calls `str.translate` element-wise. Parameters ---------- a : array-like of str or unicode table : str of length 256 deletechars : str Returns ------- out : ndarray Output array of str or unicode, depending on input type See also -------- str.translate """ a_arr = numpy.asarray(a) if issubclass(a_arr.dtype.type, unicode_): return _vec_string( a_arr, a_arr.dtype, 'translate', (table,)) else: return _vec_string( a_arr, a_arr.dtype, 'translate', [table] + _clean_args(deletechars)) def upper(a): """ Return an array with the elements converted to uppercase. Calls `str.upper` element-wise. For 8-bit strings, this method is locale-dependent. Parameters ---------- a : array_like, {str, unicode} Input array. Returns ------- out : ndarray, {str, unicode} Output array of str or unicode, depending on input type See also -------- str.upper Examples -------- >>> c = np.array(['a1b c', '1bca', 'bca1']); c array(['a1b c', '1bca', 'bca1'], dtype='|S5') >>> np.char.upper(c) array(['A1B C', '1BCA', 'BCA1'], dtype='|S5') """ a_arr = numpy.asarray(a) return _vec_string(a_arr, a_arr.dtype, 'upper') def zfill(a, width): """ Return the numeric string left-filled with zeros Calls `str.zfill` element-wise. Parameters ---------- a : array_like, {str, unicode} Input array. width : int Width of string to left-fill elements in `a`. Returns ------- out : ndarray, {str, unicode} Output array of str or unicode, depending on input type See also -------- str.zfill """ a_arr = numpy.asarray(a) width_arr = numpy.asarray(width) size = long(numpy.max(width_arr.flat)) return _vec_string( a_arr, (a_arr.dtype.type, size), 'zfill', (width_arr,)) def isnumeric(a): """ For each element, return True if there are only numeric characters in the element. Calls `unicode.isnumeric` element-wise. Numeric characters include digit characters, and all characters that have the Unicode numeric value property, e.g. ``U+2155, VULGAR FRACTION ONE FIFTH``. Parameters ---------- a : array_like, unicode Input array. Returns ------- out : ndarray, bool Array of booleans of same shape as `a`. See also -------- unicode.isnumeric """ if _use_unicode(a) != unicode_: raise TypeError("isnumeric is only available for Unicode strings and arrays") return _vec_string(a, bool_, 'isnumeric') def isdecimal(a): """ For each element, return True if there are only decimal characters in the element. Calls `unicode.isdecimal` element-wise. Decimal characters include digit characters, and all characters that that can be used to form decimal-radix numbers, e.g. ``U+0660, ARABIC-INDIC DIGIT ZERO``. Parameters ---------- a : array_like, unicode Input array. Returns ------- out : ndarray, bool Array of booleans identical in shape to `a`. See also -------- unicode.isdecimal """ if _use_unicode(a) != unicode_: raise TypeError("isnumeric is only available for Unicode strings and arrays") return _vec_string(a, bool_, 'isdecimal') class chararray(ndarray): """ chararray(shape, itemsize=1, unicode=False, buffer=None, offset=0, strides=None, order=None) Provides a convenient view on arrays of string and unicode values. .. note:: The `chararray` class exists for backwards compatibility with Numarray, it is not recommended for new development. Starting from numpy 1.4, if one needs arrays of strings, it is recommended to use arrays of `dtype` `object_`, `string_` or `unicode_`, and use the free functions in the `numpy.char` module for fast vectorized string operations. Versus a regular Numpy array of type `str` or `unicode`, this class adds the following functionality: 1) values automatically have whitespace removed from the end when indexed 2) comparison operators automatically remove whitespace from the end when comparing values 3) vectorized string operations are provided as methods (e.g. `.endswith`) and infix operators (e.g. ``"+", "*", "%"``) chararrays should be created using `numpy.char.array` or `numpy.char.asarray`, rather than this constructor directly. This constructor creates the array, using `buffer` (with `offset` and `strides`) if it is not ``None``. If `buffer` is ``None``, then constructs a new array with `strides` in "C order", unless both ``len(shape) >= 2`` and ``order='Fortran'``, in which case `strides` is in "Fortran order". Methods ------- astype argsort copy count decode dump dumps encode endswith expandtabs fill find flatten getfield index isalnum isalpha isdecimal isdigit islower isnumeric isspace istitle isupper item join ljust lower lstrip nonzero put ravel repeat replace reshape resize rfind rindex rjust rsplit rstrip searchsorted setfield setflags sort split splitlines squeeze startswith strip swapaxes swapcase take title tofile tolist tostring translate transpose upper view zfill Parameters ---------- shape : tuple Shape of the array. itemsize : int, optional Length of each array element, in number of characters. Default is 1. unicode : bool, optional Are the array elements of type unicode (True) or string (False). Default is False. buffer : int, optional Memory address of the start of the array data. Default is None, in which case a new array is created. offset : int, optional Fixed stride displacement from the beginning of an axis? Default is 0. Needs to be >=0. strides : array_like of ints, optional Strides for the array (see `ndarray.strides` for full description). Default is None. order : {'C', 'F'}, optional The order in which the array data is stored in memory: 'C' -> "row major" order (the default), 'F' -> "column major" (Fortran) order. Examples -------- >>> charar = np.chararray((3, 3)) >>> charar[:] = 'a' >>> charar chararray([['a', 'a', 'a'], ['a', 'a', 'a'], ['a', 'a', 'a']], dtype='|S1') >>> charar = np.chararray(charar.shape, itemsize=5) >>> charar[:] = 'abc' >>> charar chararray([['abc', 'abc', 'abc'], ['abc', 'abc', 'abc'], ['abc', 'abc', 'abc']], dtype='|S5') """ def __new__(subtype, shape, itemsize=1, unicode=False, buffer=None, offset=0, strides=None, order='C'): global _globalvar if unicode: dtype = unicode_ else: dtype = string_ # force itemsize to be a Python long, since using Numpy integer # types results in itemsize.itemsize being used as the size of # strings in the new array. itemsize = long(itemsize) if sys.version_info[0] >= 3 and isinstance(buffer, _unicode): # On Py3, unicode objects do not have the buffer interface filler = buffer buffer = None else: filler = None _globalvar = 1 if buffer is None: self = ndarray.__new__(subtype, shape, (dtype, itemsize), order=order) else: self = ndarray.__new__(subtype, shape, (dtype, itemsize), buffer=buffer, offset=offset, strides=strides, order=order) if filler is not None: self[...] = filler _globalvar = 0 return self def __array_finalize__(self, obj): # The b is a special case because it is used for reconstructing. if not _globalvar and self.dtype.char not in 'SUbc': raise ValueError("Can only create a chararray from string data.") def __getitem__(self, obj): val = ndarray.__getitem__(self, obj) if issubclass(val.dtype.type, character) and not _len(val) == 0: temp = val.rstrip() if _len(temp) == 0: val = '' else: val = temp return val # IMPLEMENTATION NOTE: Most of the methods of this class are # direct delegations to the free functions in this module. # However, those that return an array of strings should instead # return a chararray, so some extra wrapping is required. def __eq__(self, other): """ Return (self == other) element-wise. See also -------- equal """ return equal(self, other) def __ne__(self, other): """ Return (self != other) element-wise. See also -------- not_equal """ return not_equal(self, other) def __ge__(self, other): """ Return (self >= other) element-wise. See also -------- greater_equal """ return greater_equal(self, other) def __le__(self, other): """ Return (self <= other) element-wise. See also -------- less_equal """ return less_equal(self, other) def __gt__(self, other): """ Return (self > other) element-wise. See also -------- greater """ return greater(self, other) def __lt__(self, other): """ Return (self < other) element-wise. See also -------- less """ return less(self, other) def __add__(self, other): """ Return (self + other), that is string concatenation, element-wise for a pair of array_likes of str or unicode. See also -------- add """ return asarray(add(self, other)) def __radd__(self, other): """ Return (other + self), that is string concatenation, element-wise for a pair of array_likes of `string_` or `unicode_`. See also -------- add """ return asarray(add(numpy.asarray(other), self)) def __mul__(self, i): """ Return (self * i), that is string multiple concatenation, element-wise. See also -------- multiply """ return asarray(multiply(self, i)) def __rmul__(self, i): """ Return (self * i), that is string multiple concatenation, element-wise. See also -------- multiply """ return asarray(multiply(self, i)) def __mod__(self, i): """ Return (self % i), that is pre-Python 2.6 string formatting (iterpolation), element-wise for a pair of array_likes of `string_` or `unicode_`. See also -------- mod """ return asarray(mod(self, i)) def __rmod__(self, other): return NotImplemented def argsort(self, axis=-1, kind='quicksort', order=None): """ Return the indices that sort the array lexicographically. For full documentation see `numpy.argsort`, for which this method is in fact merely a "thin wrapper." Examples -------- >>> c = np.array(['a1b c', '1b ca', 'b ca1', 'Ca1b'], 'S5') >>> c = c.view(np.chararray); c chararray(['a1b c', '1b ca', 'b ca1', 'Ca1b'], dtype='|S5') >>> c[c.argsort()] chararray(['1b ca', 'Ca1b', 'a1b c', 'b ca1'], dtype='|S5') """ return self.__array__().argsort(axis, kind, order) argsort.__doc__ = ndarray.argsort.__doc__ def capitalize(self): """ Return a copy of `self` with only the first character of each element capitalized. See also -------- char.capitalize """ return asarray(capitalize(self)) def center(self, width, fillchar=' '): """ Return a copy of `self` with its elements centered in a string of length `width`. See also -------- center """ return asarray(center(self, width, fillchar)) def count(self, sub, start=0, end=None): """ Returns an array with the number of non-overlapping occurrences of substring `sub` in the range [`start`, `end`]. See also -------- char.count """ return count(self, sub, start, end) def decode(self, encoding=None, errors=None): """ Calls `str.decode` element-wise. See also -------- char.decode """ return decode(self, encoding, errors) def encode(self, encoding=None, errors=None): """ Calls `str.encode` element-wise. See also -------- char.encode """ return encode(self, encoding, errors) def endswith(self, suffix, start=0, end=None): """ Returns a boolean array which is `True` where the string element in `self` ends with `suffix`, otherwise `False`. See also -------- char.endswith """ return endswith(self, suffix, start, end) def expandtabs(self, tabsize=8): """ Return a copy of each string element where all tab characters are replaced by one or more spaces. See also -------- char.expandtabs """ return asarray(expandtabs(self, tabsize)) def find(self, sub, start=0, end=None): """ For each element, return the lowest index in the string where substring `sub` is found. See also -------- char.find """ return find(self, sub, start, end) def index(self, sub, start=0, end=None): """ Like `find`, but raises `ValueError` when the substring is not found. See also -------- char.index """ return index(self, sub, start, end) def isalnum(self): """ Returns true for each element if all characters in the string are alphanumeric and there is at least one character, false otherwise. See also -------- char.isalnum """ return isalnum(self) def isalpha(self): """ Returns true for each element if all characters in the string are alphabetic and there is at least one character, false otherwise. See also -------- char.isalpha """ return isalpha(self) def isdigit(self): """ Returns true for each element if all characters in the string are digits and there is at least one character, false otherwise. See also -------- char.isdigit """ return isdigit(self) def islower(self): """ Returns true for each element if all cased characters in the string are lowercase and there is at least one cased character, false otherwise. See also -------- char.islower """ return islower(self) def isspace(self): """ Returns true for each element if there are only whitespace characters in the string and there is at least one character, false otherwise. See also -------- char.isspace """ return isspace(self) def istitle(self): """ Returns true for each element if the element is a titlecased string and there is at least one character, false otherwise. See also -------- char.istitle """ return istitle(self) def isupper(self): """ Returns true for each element if all cased characters in the string are uppercase and there is at least one character, false otherwise. See also -------- char.isupper """ return isupper(self) def join(self, seq): """ Return a string which is the concatenation of the strings in the sequence `seq`. See also -------- char.join """ return join(self, seq) def ljust(self, width, fillchar=' '): """ Return an array with the elements of `self` left-justified in a string of length `width`. See also -------- char.ljust """ return asarray(ljust(self, width, fillchar)) def lower(self): """ Return an array with the elements of `self` converted to lowercase. See also -------- char.lower """ return asarray(lower(self)) def lstrip(self, chars=None): """ For each element in `self`, return a copy with the leading characters removed. See also -------- char.lstrip """ return asarray(lstrip(self, chars)) def partition(self, sep): """ Partition each element in `self` around `sep`. See also -------- partition """ return asarray(partition(self, sep)) def replace(self, old, new, count=None): """ For each element in `self`, return a copy of the string with all occurrences of substring `old` replaced by `new`. See also -------- char.replace """ return asarray(replace(self, old, new, count)) def rfind(self, sub, start=0, end=None): """ For each element in `self`, return the highest index in the string where substring `sub` is found, such that `sub` is contained within [`start`, `end`]. See also -------- char.rfind """ return rfind(self, sub, start, end) def rindex(self, sub, start=0, end=None): """ Like `rfind`, but raises `ValueError` when the substring `sub` is not found. See also -------- char.rindex """ return rindex(self, sub, start, end) def rjust(self, width, fillchar=' '): """ Return an array with the elements of `self` right-justified in a string of length `width`. See also -------- char.rjust """ return asarray(rjust(self, width, fillchar)) def rpartition(self, sep): """ Partition each element in `self` around `sep`. See also -------- rpartition """ return asarray(rpartition(self, sep)) def rsplit(self, sep=None, maxsplit=None): """ For each element in `self`, return a list of the words in the string, using `sep` as the delimiter string. See also -------- char.rsplit """ return rsplit(self, sep, maxsplit) def rstrip(self, chars=None): """ For each element in `self`, return a copy with the trailing characters removed. See also -------- char.rstrip """ return asarray(rstrip(self, chars)) def split(self, sep=None, maxsplit=None): """ For each element in `self`, return a list of the words in the string, using `sep` as the delimiter string. See also -------- char.split """ return split(self, sep, maxsplit) def splitlines(self, keepends=None): """ For each element in `self`, return a list of the lines in the element, breaking at line boundaries. See also -------- char.splitlines """ return splitlines(self, keepends) def startswith(self, prefix, start=0, end=None): """ Returns a boolean array which is `True` where the string element in `self` starts with `prefix`, otherwise `False`. See also -------- char.startswith """ return startswith(self, prefix, start, end) def strip(self, chars=None): """ For each element in `self`, return a copy with the leading and trailing characters removed. See also -------- char.strip """ return asarray(strip(self, chars)) def swapcase(self): """ For each element in `self`, return a copy of the string with uppercase characters converted to lowercase and vice versa. See also -------- char.swapcase """ return asarray(swapcase(self)) def title(self): """ For each element in `self`, return a titlecased version of the string: words start with uppercase characters, all remaining cased characters are lowercase. See also -------- char.title """ return asarray(title(self)) def translate(self, table, deletechars=None): """ For each element in `self`, return a copy of the string where all characters occurring in the optional argument `deletechars` are removed, and the remaining characters have been mapped through the given translation table. See also -------- char.translate """ return asarray(translate(self, table, deletechars)) def upper(self): """ Return an array with the elements of `self` converted to uppercase. See also -------- char.upper """ return asarray(upper(self)) def zfill(self, width): """ Return the numeric string left-filled with zeros in a string of length `width`. See also -------- char.zfill """ return asarray(zfill(self, width)) def isnumeric(self): """ For each element in `self`, return True if there are only numeric characters in the element. See also -------- char.isnumeric """ return isnumeric(self) def isdecimal(self): """ For each element in `self`, return True if there are only decimal characters in the element. See also -------- char.isdecimal """ return isdecimal(self) def array(obj, itemsize=None, copy=True, unicode=None, order=None): """ Create a `chararray`. .. note:: This class is provided for numarray backward-compatibility. New code (not concerned with numarray compatibility) should use arrays of type `string_` or `unicode_` and use the free functions in :mod:`numpy.char ` for fast vectorized string operations instead. Versus a regular Numpy array of type `str` or `unicode`, this class adds the following functionality: 1) values automatically have whitespace removed from the end when indexed 2) comparison operators automatically remove whitespace from the end when comparing values 3) vectorized string operations are provided as methods (e.g. `str.endswith`) and infix operators (e.g. ``+, *, %``) Parameters ---------- obj : array of str or unicode-like itemsize : int, optional `itemsize` is the number of characters per scalar in the resulting array. If `itemsize` is None, and `obj` is an object array or a Python list, the `itemsize` will be automatically determined. If `itemsize` is provided and `obj` is of type str or unicode, then the `obj` string will be chunked into `itemsize` pieces. copy : bool, optional If true (default), then the object is copied. Otherwise, a copy will only be made if __array__ returns a copy, if obj is a nested sequence, or if a copy is needed to satisfy any of the other requirements (`itemsize`, unicode, `order`, etc.). unicode : bool, optional When true, the resulting `chararray` can contain Unicode characters, when false only 8-bit characters. If unicode is `None` and `obj` is one of the following: - a `chararray`, - an ndarray of type `str` or `unicode` - a Python str or unicode object, then the unicode setting of the output array will be automatically determined. order : {'C', 'F', 'A'}, optional Specify the order of the array. If order is 'C' (default), then the array will be in C-contiguous order (last-index varies the fastest). If order is 'F', then the returned array will be in Fortran-contiguous order (first-index varies the fastest). If order is 'A', then the returned array may be in any order (either C-, Fortran-contiguous, or even discontiguous). """ if isinstance(obj, (_bytes, _unicode)): if unicode is None: if isinstance(obj, _unicode): unicode = True else: unicode = False if itemsize is None: itemsize = _len(obj) shape = _len(obj) // itemsize if unicode: if sys.maxunicode == 0xffff: # On a narrow Python build, the buffer for Unicode # strings is UCS2, which doesn't match the buffer for # Numpy Unicode types, which is ALWAYS UCS4. # Therefore, we need to convert the buffer. On Python # 2.6 and later, we can use the utf_32 codec. Earlier # versions don't have that codec, so we convert to a # numerical array that matches the input buffer, and # then use Numpy to convert it to UCS4. All of this # should happen in native endianness. if sys.hexversion >= 0x2060000: obj = obj.encode('utf_32') else: if isinstance(obj, str): ascii = numpy.frombuffer(obj, 'u1') ucs4 = numpy.array(ascii, 'u4') obj = ucs4.data else: ucs2 = numpy.frombuffer(obj, 'u2') ucs4 = numpy.array(ucs2, 'u4') obj = ucs4.data else: obj = _unicode(obj) else: # Let the default Unicode -> string encoding (if any) take # precedence. obj = _bytes(obj) return chararray(shape, itemsize=itemsize, unicode=unicode, buffer=obj, order=order) if isinstance(obj, (list, tuple)): obj = numpy.asarray(obj) if isinstance(obj, ndarray) and issubclass(obj.dtype.type, character): # If we just have a vanilla chararray, create a chararray # view around it. if not isinstance(obj, chararray): obj = obj.view(chararray) if itemsize is None: itemsize = obj.itemsize # itemsize is in 8-bit chars, so for Unicode, we need # to divide by the size of a single Unicode character, # which for Numpy is always 4 if issubclass(obj.dtype.type, unicode_): itemsize //= 4 if unicode is None: if issubclass(obj.dtype.type, unicode_): unicode = True else: unicode = False if unicode: dtype = unicode_ else: dtype = string_ if order is not None: obj = numpy.asarray(obj, order=order) if (copy or (itemsize != obj.itemsize) or (not unicode and isinstance(obj, unicode_)) or (unicode and isinstance(obj, string_))): obj = obj.astype((dtype, long(itemsize))) return obj if isinstance(obj, ndarray) and issubclass(obj.dtype.type, object): if itemsize is None: # Since no itemsize was specified, convert the input array to # a list so the ndarray constructor will automatically # determine the itemsize for us. obj = obj.tolist() # Fall through to the default case if unicode: dtype = unicode_ else: dtype = string_ if itemsize is None: val = narray(obj, dtype=dtype, order=order, subok=True) else: val = narray(obj, dtype=(dtype, itemsize), order=order, subok=True) return val.view(chararray) def asarray(obj, itemsize=None, unicode=None, order=None): """ Convert the input to a `chararray`, copying the data only if necessary. Versus a regular Numpy array of type `str` or `unicode`, this class adds the following functionality: 1) values automatically have whitespace removed from the end when indexed 2) comparison operators automatically remove whitespace from the end when comparing values 3) vectorized string operations are provided as methods (e.g. `str.endswith`) and infix operators (e.g. +, *, %) Parameters ---------- obj : array of str or unicode-like itemsize : int, optional `itemsize` is the number of characters per scalar in the resulting array. If `itemsize` is None, and `obj` is an object array or a Python list, the `itemsize` will be automatically determined. If `itemsize` is provided and `obj` is of type str or unicode, then the `obj` string will be chunked into `itemsize` pieces. unicode : bool, optional When true, the resulting `chararray` can contain Unicode characters, when false only 8-bit characters. If unicode is `None` and `obj` is one of the following: - a `chararray`, - an ndarray of type `str` or 'unicode` - a Python str or unicode object, then the unicode setting of the output array will be automatically determined. order : {'C', 'F'}, optional Specify the order of the array. If order is 'C' (default), then the array will be in C-contiguous order (last-index varies the fastest). If order is 'F', then the returned array will be in Fortran-contiguous order (first-index varies the fastest). """ return array(obj, itemsize, copy=False, unicode=unicode, order=order) numpy-1.8.2/numpy/core/machar.py0000664000175100017510000002461112370216242017734 0ustar vagrantvagrant00000000000000""" Machine arithmetics - determine the parameters of the floating-point arithmetic system Author: Pearu Peterson, September 2003 """ from __future__ import division, absolute_import, print_function __all__ = ['MachAr'] from numpy.core.fromnumeric import any from numpy.core.numeric import errstate # Need to speed this up...especially for longfloat class MachAr(object): """ Diagnosing machine parameters. Attributes ---------- ibeta : int Radix in which numbers are represented. it : int Number of base-`ibeta` digits in the floating point mantissa M. machep : int Exponent of the smallest (most negative) power of `ibeta` that, added to 1.0, gives something different from 1.0 eps : float Floating-point number ``beta**machep`` (floating point precision) negep : int Exponent of the smallest power of `ibeta` that, substracted from 1.0, gives something different from 1.0. epsneg : float Floating-point number ``beta**negep``. iexp : int Number of bits in the exponent (including its sign and bias). minexp : int Smallest (most negative) power of `ibeta` consistent with there being no leading zeros in the mantissa. xmin : float Floating point number ``beta**minexp`` (the smallest [in magnitude] usable floating value). maxexp : int Smallest (positive) power of `ibeta` that causes overflow. xmax : float ``(1-epsneg) * beta**maxexp`` (the largest [in magnitude] usable floating value). irnd : int In ``range(6)``, information on what kind of rounding is done in addition, and on how underflow is handled. ngrd : int Number of 'guard digits' used when truncating the product of two mantissas to fit the representation. epsilon : float Same as `eps`. tiny : float Same as `xmin`. huge : float Same as `xmax`. precision : float ``- int(-log10(eps))`` resolution : float ``- 10**(-precision)`` Parameters ---------- float_conv : function, optional Function that converts an integer or integer array to a float or float array. Default is `float`. int_conv : function, optional Function that converts a float or float array to an integer or integer array. Default is `int`. float_to_float : function, optional Function that converts a float array to float. Default is `float`. Note that this does not seem to do anything useful in the current implementation. float_to_str : function, optional Function that converts a single float to a string. Default is ``lambda v:'%24.16e' %v``. title : str, optional Title that is printed in the string representation of `MachAr`. See Also -------- finfo : Machine limits for floating point types. iinfo : Machine limits for integer types. References ---------- .. [1] Press, Teukolsky, Vetterling and Flannery, "Numerical Recipes in C++," 2nd ed, Cambridge University Press, 2002, p. 31. """ def __init__(self, float_conv=float,int_conv=int, float_to_float=float, float_to_str = lambda v:'%24.16e' % v, title = 'Python floating point number'): """ float_conv - convert integer to float (array) int_conv - convert float (array) to integer float_to_float - convert float array to float float_to_str - convert array float to str title - description of used floating point numbers """ # We ignore all errors here because we are purposely triggering # underflow to detect the properties of the runninng arch. with errstate(under='ignore'): self._do_init(float_conv, int_conv, float_to_float, float_to_str, title) def _do_init(self, float_conv, int_conv, float_to_float, float_to_str, title): max_iterN = 10000 msg = "Did not converge after %d tries with %s" one = float_conv(1) two = one + one zero = one - one # Do we really need to do this? Aren't they 2 and 2.0? # Determine ibeta and beta a = one for _ in range(max_iterN): a = a + a temp = a + one temp1 = temp - a if any(temp1 - one != zero): break else: raise RuntimeError(msg % (_, one.dtype)) b = one for _ in range(max_iterN): b = b + b temp = a + b itemp = int_conv(temp-a) if any(itemp != 0): break else: raise RuntimeError(msg % (_, one.dtype)) ibeta = itemp beta = float_conv(ibeta) # Determine it and irnd it = -1 b = one for _ in range(max_iterN): it = it + 1 b = b * beta temp = b + one temp1 = temp - b if any(temp1 - one != zero): break else: raise RuntimeError(msg % (_, one.dtype)) betah = beta / two a = one for _ in range(max_iterN): a = a + a temp = a + one temp1 = temp - a if any(temp1 - one != zero): break else: raise RuntimeError(msg % (_, one.dtype)) temp = a + betah irnd = 0 if any(temp-a != zero): irnd = 1 tempa = a + beta temp = tempa + betah if irnd==0 and any(temp-tempa != zero): irnd = 2 # Determine negep and epsneg negep = it + 3 betain = one / beta a = one for i in range(negep): a = a * betain b = a for _ in range(max_iterN): temp = one - a if any(temp-one != zero): break a = a * beta negep = negep - 1 # Prevent infinite loop on PPC with gcc 4.0: if negep < 0: raise RuntimeError("could not determine machine tolerance " "for 'negep', locals() -> %s" % (locals())) else: raise RuntimeError(msg % (_, one.dtype)) negep = -negep epsneg = a # Determine machep and eps machep = - it - 3 a = b for _ in range(max_iterN): temp = one + a if any(temp-one != zero): break a = a * beta machep = machep + 1 else: raise RuntimeError(msg % (_, one.dtype)) eps = a # Determine ngrd ngrd = 0 temp = one + eps if irnd==0 and any(temp*one - one != zero): ngrd = 1 # Determine iexp i = 0 k = 1 z = betain t = one + eps nxres = 0 for _ in range(max_iterN): y = z z = y*y a = z*one # Check here for underflow temp = z*t if any(a+a == zero) or any(abs(z)>=y): break temp1 = temp * betain if any(temp1*beta == z): break i = i + 1 k = k + k else: raise RuntimeError(msg % (_, one.dtype)) if ibeta != 10: iexp = i + 1 mx = k + k else: iexp = 2 iz = ibeta while k >= iz: iz = iz * ibeta iexp = iexp + 1 mx = iz + iz - 1 # Determine minexp and xmin for _ in range(max_iterN): xmin = y y = y * betain a = y * one temp = y * t if any(a+a != zero) and any(abs(y) < xmin): k = k + 1 temp1 = temp * betain if any(temp1*beta == y) and any(temp != y): nxres = 3 xmin = y break else: break else: raise RuntimeError(msg % (_, one.dtype)) minexp = -k # Determine maxexp, xmax if mx <= k + k - 3 and ibeta != 10: mx = mx + mx iexp = iexp + 1 maxexp = mx + minexp irnd = irnd + nxres if irnd >= 2: maxexp = maxexp - 2 i = maxexp + minexp if ibeta == 2 and not i: maxexp = maxexp - 1 if i > 20: maxexp = maxexp - 1 if any(a != y): maxexp = maxexp - 2 xmax = one - epsneg if any(xmax*one != xmax): xmax = one - beta*epsneg xmax = xmax / (xmin*beta*beta*beta) i = maxexp + minexp + 3 for j in range(i): if ibeta==2: xmax = xmax + xmax else: xmax = xmax * beta self.ibeta = ibeta self.it = it self.negep = negep self.epsneg = float_to_float(epsneg) self._str_epsneg = float_to_str(epsneg) self.machep = machep self.eps = float_to_float(eps) self._str_eps = float_to_str(eps) self.ngrd = ngrd self.iexp = iexp self.minexp = minexp self.xmin = float_to_float(xmin) self._str_xmin = float_to_str(xmin) self.maxexp = maxexp self.xmax = float_to_float(xmax) self._str_xmax = float_to_str(xmax) self.irnd = irnd self.title = title # Commonly used parameters self.epsilon = self.eps self.tiny = self.xmin self.huge = self.xmax import math self.precision = int(-math.log10(float_to_float(self.eps))) ten = two + two + two + two + two resolution = ten ** (-self.precision) self.resolution = float_to_float(resolution) self._str_resolution = float_to_str(resolution) def __str__(self): return '''\ Machine parameters for %(title)s --------------------------------------------------------------------- ibeta=%(ibeta)s it=%(it)s iexp=%(iexp)s ngrd=%(ngrd)s irnd=%(irnd)s machep=%(machep)s eps=%(_str_eps)s (beta**machep == epsilon) negep =%(negep)s epsneg=%(_str_epsneg)s (beta**epsneg) minexp=%(minexp)s xmin=%(_str_xmin)s (beta**minexp == tiny) maxexp=%(maxexp)s xmax=%(_str_xmax)s ((1-epsneg)*beta**maxexp == huge) --------------------------------------------------------------------- ''' % self.__dict__ if __name__ == '__main__': print(MachAr()) numpy-1.8.2/numpy/core/info.py0000664000175100017510000001112212370216242017425 0ustar vagrantvagrant00000000000000"""Defines a multi-dimensional array and useful procedures for Numerical computation. Functions - array - NumPy Array construction - zeros - Return an array of all zeros - empty - Return an unitialized array - shape - Return shape of sequence or array - rank - Return number of dimensions - size - Return number of elements in entire array or a certain dimension - fromstring - Construct array from (byte) string - take - Select sub-arrays using sequence of indices - put - Set sub-arrays using sequence of 1-D indices - putmask - Set portion of arrays using a mask - reshape - Return array with new shape - repeat - Repeat elements of array - choose - Construct new array from indexed array tuple - correlate - Correlate two 1-d arrays - searchsorted - Search for element in 1-d array - sum - Total sum over a specified dimension - average - Average, possibly weighted, over axis or array. - cumsum - Cumulative sum over a specified dimension - product - Total product over a specified dimension - cumproduct - Cumulative product over a specified dimension - alltrue - Logical and over an entire axis - sometrue - Logical or over an entire axis - allclose - Tests if sequences are essentially equal More Functions: - arange - Return regularly spaced array - asarray - Guarantee NumPy array - convolve - Convolve two 1-d arrays - swapaxes - Exchange axes - concatenate - Join arrays together - transpose - Permute axes - sort - Sort elements of array - argsort - Indices of sorted array - argmax - Index of largest value - argmin - Index of smallest value - inner - Innerproduct of two arrays - dot - Dot product (matrix multiplication) - outer - Outerproduct of two arrays - resize - Return array with arbitrary new shape - indices - Tuple of indices - fromfunction - Construct array from universal function - diagonal - Return diagonal array - trace - Trace of array - dump - Dump array to file object (pickle) - dumps - Return pickled string representing data - load - Return array stored in file object - loads - Return array from pickled string - ravel - Return array as 1-D - nonzero - Indices of nonzero elements for 1-D array - shape - Shape of array - where - Construct array from binary result - compress - Elements of array where condition is true - clip - Clip array between two values - ones - Array of all ones - identity - 2-D identity array (matrix) (Universal) Math Functions add logical_or exp subtract logical_xor log multiply logical_not log10 divide maximum sin divide_safe minimum sinh conjugate bitwise_and sqrt power bitwise_or tan absolute bitwise_xor tanh negative invert ceil greater left_shift fabs greater_equal right_shift floor less arccos arctan2 less_equal arcsin fmod equal arctan hypot not_equal cos around logical_and cosh sign arccosh arcsinh arctanh """ from __future__ import division, absolute_import, print_function depends = ['testing'] global_symbols = ['*'] numpy-1.8.2/numpy/core/setup.py0000664000175100017510000012222012370216243017635 0ustar vagrantvagrant00000000000000from __future__ import division, print_function import imp import os import sys import shutil import pickle import copy import warnings import re from os.path import join from numpy.distutils import log from distutils.dep_util import newer from distutils.sysconfig import get_config_var from setup_common import * # Set to True to enable multiple file compilations (experimental) ENABLE_SEPARATE_COMPILATION = (os.environ.get('NPY_SEPARATE_COMPILATION', "1") != "0") # Set to True to enable relaxed strides checking. This (mostly) means # that `strides[dim]` is ignored if `shape[dim] == 1` when setting flags. NPY_RELAXED_STRIDES_CHECKING = (os.environ.get('NPY_RELAXED_STRIDES_CHECKING', "0") != "0") # XXX: ugly, we use a class to avoid calling twice some expensive functions in # config.h/numpyconfig.h. I don't see a better way because distutils force # config.h generation inside an Extension class, and as such sharing # configuration informations between extensions is not easy. # Using a pickled-based memoize does not work because config_cmd is an instance # method, which cPickle does not like. # # Use pickle in all cases, as cPickle is gone in python3 and the difference # in time is only in build. -- Charles Harris, 2013-03-30 class CallOnceOnly(object): def __init__(self): self._check_types = None self._check_ieee_macros = None self._check_complex = None def check_types(self, *a, **kw): if self._check_types is None: out = check_types(*a, **kw) self._check_types = pickle.dumps(out) else: out = copy.deepcopy(pickle.loads(self._check_types)) return out def check_ieee_macros(self, *a, **kw): if self._check_ieee_macros is None: out = check_ieee_macros(*a, **kw) self._check_ieee_macros = pickle.dumps(out) else: out = copy.deepcopy(pickle.loads(self._check_ieee_macros)) return out def check_complex(self, *a, **kw): if self._check_complex is None: out = check_complex(*a, **kw) self._check_complex = pickle.dumps(out) else: out = copy.deepcopy(pickle.loads(self._check_complex)) return out PYTHON_HAS_UNICODE_WIDE = True def pythonlib_dir(): """return path where libpython* is.""" if sys.platform == 'win32': return os.path.join(sys.prefix, "libs") else: return get_config_var('LIBDIR') def is_npy_no_signal(): """Return True if the NPY_NO_SIGNAL symbol must be defined in configuration header.""" return sys.platform == 'win32' def is_npy_no_smp(): """Return True if the NPY_NO_SMP symbol must be defined in public header (when SMP support cannot be reliably enabled).""" # Python 2.3 causes a segfault when # trying to re-acquire the thread-state # which is done in error-handling # ufunc code. NPY_ALLOW_C_API and friends # cause the segfault. So, we disable threading # for now. if sys.version[:5] < '2.4.2': nosmp = 1 else: # Perhaps a fancier check is in order here. # so that threads are only enabled if there # are actually multiple CPUS? -- but # threaded code can be nice even on a single # CPU so that long-calculating code doesn't # block. try: nosmp = os.environ['NPY_NOSMP'] nosmp = 1 except KeyError: nosmp = 0 return nosmp == 1 def win32_checks(deflist): from numpy.distutils.misc_util import get_build_architecture a = get_build_architecture() # Distutils hack on AMD64 on windows print('BUILD_ARCHITECTURE: %r, os.name=%r, sys.platform=%r' % (a, os.name, sys.platform)) if a == 'AMD64': deflist.append('DISTUTILS_USE_SDK') # On win32, force long double format string to be 'g', not # 'Lg', since the MS runtime does not support long double whose # size is > sizeof(double) if a == "Intel" or a == "AMD64": deflist.append('FORCE_NO_LONG_DOUBLE_FORMATTING') def check_math_capabilities(config, moredefs, mathlibs): def check_func(func_name): return config.check_func(func_name, libraries=mathlibs, decl=True, call=True) def check_funcs_once(funcs_name): decl = dict([(f, True) for f in funcs_name]) st = config.check_funcs_once(funcs_name, libraries=mathlibs, decl=decl, call=decl) if st: moredefs.extend([(fname2def(f), 1) for f in funcs_name]) return st def check_funcs(funcs_name): # Use check_funcs_once first, and if it does not work, test func per # func. Return success only if all the functions are available if not check_funcs_once(funcs_name): # Global check failed, check func per func for f in funcs_name: if check_func(f): moredefs.append((fname2def(f), 1)) return 0 else: return 1 #use_msvc = config.check_decl("_MSC_VER") if not check_funcs_once(MANDATORY_FUNCS): raise SystemError("One of the required function to build numpy is not" " available (the list is %s)." % str(MANDATORY_FUNCS)) # Standard functions which may not be available and for which we have a # replacement implementation. Note that some of these are C99 functions. # XXX: hack to circumvent cpp pollution from python: python put its # config.h in the public namespace, so we have a clash for the common # functions we test. We remove every function tested by python's # autoconf, hoping their own test are correct for f in OPTIONAL_STDFUNCS_MAYBE: if config.check_decl(fname2def(f), headers=["Python.h", "math.h"]): OPTIONAL_STDFUNCS.remove(f) check_funcs(OPTIONAL_STDFUNCS) for h in OPTIONAL_HEADERS: if config.check_func("", decl=False, call=False, headers=[h]): moredefs.append((fname2def(h).replace(".", "_"), 1)) for tup in OPTIONAL_INTRINSICS: headers = None if len(tup) == 2: f, args = tup else: f, args, headers = tup[0], tup[1], [tup[2]] if config.check_func(f, decl=False, call=True, call_args=args, 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): moredefs.append((fname2def(fn), 1)) # C99 functions: float and long double versions check_funcs(C99_FUNCS_SINGLE) check_funcs(C99_FUNCS_EXTENDED) def check_complex(config, mathlibs): priv = [] pub = [] try: if os.uname()[0] == "Interix": warnings.warn("Disabling broken complex support. See #1365") return priv, pub except: # os.uname not available on all platforms. blanket except ugly but safe pass # Check for complex support st = config.check_header('complex.h') if st: priv.append(('HAVE_COMPLEX_H', 1)) pub.append(('NPY_USE_C99_COMPLEX', 1)) for t in C99_COMPLEX_TYPES: st = config.check_type(t, headers=["complex.h"]) if st: pub.append(('NPY_HAVE_%s' % type2def(t), 1)) def check_prec(prec): flist = [f + prec for f in C99_COMPLEX_FUNCS] decl = dict([(f, True) for f in flist]) if not config.check_funcs_once(flist, call=decl, decl=decl, libraries=mathlibs): for f in flist: if config.check_func(f, call=True, decl=True, libraries=mathlibs): priv.append((fname2def(f), 1)) else: priv.extend([(fname2def(f), 1) for f in flist]) check_prec('') check_prec('f') check_prec('l') return priv, pub def check_ieee_macros(config): priv = [] pub = [] macros = [] def _add_decl(f): priv.append(fname2def("decl_%s" % f)) pub.append('NPY_%s' % fname2def("decl_%s" % f)) # XXX: hack to circumvent cpp pollution from python: python put its # config.h in the public namespace, so we have a clash for the common # functions we test. We remove every function tested by python's # autoconf, hoping their own test are correct _macros = ["isnan", "isinf", "signbit", "isfinite"] for f in _macros: py_symbol = fname2def("decl_%s" % f) already_declared = config.check_decl(py_symbol, headers=["Python.h", "math.h"]) if already_declared: if config.check_macro_true(py_symbol, headers=["Python.h", "math.h"]): pub.append('NPY_%s' % fname2def("decl_%s" % f)) else: macros.append(f) # Normally, isnan and isinf are macro (C99), but some platforms only have # func, or both func and macro version. Check for macro only, and define # replacement ones if not found. # Note: including Python.h is necessary because it modifies some math.h # definitions for f in macros: st = config.check_decl(f, headers = ["Python.h", "math.h"]) if st: _add_decl(f) return priv, pub def check_types(config_cmd, ext, build_dir): private_defines = [] public_defines = [] # Expected size (in number of bytes) for each type. This is an # optimization: those are only hints, and an exhaustive search for the size # is done if the hints are wrong. expected = {} expected['short'] = [2] expected['int'] = [4] expected['long'] = [8, 4] expected['float'] = [4] expected['double'] = [8] expected['long double'] = [8, 12, 16] expected['Py_intptr_t'] = [4, 8] expected['PY_LONG_LONG'] = [8] expected['long long'] = [8] expected['off_t'] = [4, 8] # Check we have the python header (-dev* packages on Linux) result = config_cmd.check_header('Python.h') if not result: raise SystemError( "Cannot compile 'Python.h'. Perhaps you need to "\ "install python-dev|python-devel.") res = config_cmd.check_header("endian.h") if res: private_defines.append(('HAVE_ENDIAN_H', 1)) public_defines.append(('NPY_HAVE_ENDIAN_H', 1)) # Check basic types sizes for type in ('short', 'int', 'long'): res = config_cmd.check_decl("SIZEOF_%s" % sym2def(type), headers = ["Python.h"]) if res: public_defines.append(('NPY_SIZEOF_%s' % sym2def(type), "SIZEOF_%s" % sym2def(type))) else: res = config_cmd.check_type_size(type, expected=expected[type]) if res >= 0: public_defines.append(('NPY_SIZEOF_%s' % sym2def(type), '%d' % res)) else: raise SystemError("Checking sizeof (%s) failed !" % type) for type in ('float', 'double', 'long double'): already_declared = config_cmd.check_decl("SIZEOF_%s" % sym2def(type), headers = ["Python.h"]) res = config_cmd.check_type_size(type, expected=expected[type]) if res >= 0: public_defines.append(('NPY_SIZEOF_%s' % sym2def(type), '%d' % res)) if not already_declared and not type == 'long double': private_defines.append(('SIZEOF_%s' % sym2def(type), '%d' % res)) else: raise SystemError("Checking sizeof (%s) failed !" % type) # Compute size of corresponding complex type: used to check that our # definition is binary compatible with C99 complex type (check done at # build time in npy_common.h) complex_def = "struct {%s __x; %s __y;}" % (type, type) res = config_cmd.check_type_size(complex_def, expected=2*expected[type]) if res >= 0: public_defines.append(('NPY_SIZEOF_COMPLEX_%s' % sym2def(type), '%d' % res)) else: raise SystemError("Checking sizeof (%s) failed !" % complex_def) for type in ('Py_intptr_t', 'off_t'): res = config_cmd.check_type_size(type, headers=["Python.h"], library_dirs=[pythonlib_dir()], expected=expected[type]) if res >= 0: private_defines.append(('SIZEOF_%s' % sym2def(type), '%d' % res)) public_defines.append(('NPY_SIZEOF_%s' % sym2def(type), '%d' % res)) else: raise SystemError("Checking sizeof (%s) failed !" % type) # We check declaration AND type because that's how distutils does it. if config_cmd.check_decl('PY_LONG_LONG', headers=['Python.h']): res = config_cmd.check_type_size('PY_LONG_LONG', headers=['Python.h'], library_dirs=[pythonlib_dir()], expected=expected['PY_LONG_LONG']) if res >= 0: private_defines.append(('SIZEOF_%s' % sym2def('PY_LONG_LONG'), '%d' % res)) public_defines.append(('NPY_SIZEOF_%s' % sym2def('PY_LONG_LONG'), '%d' % res)) else: raise SystemError("Checking sizeof (%s) failed !" % 'PY_LONG_LONG') res = config_cmd.check_type_size('long long', expected=expected['long long']) if res >= 0: #private_defines.append(('SIZEOF_%s' % sym2def('long long'), '%d' % res)) public_defines.append(('NPY_SIZEOF_%s' % sym2def('long long'), '%d' % res)) else: raise SystemError("Checking sizeof (%s) failed !" % 'long long') if not config_cmd.check_decl('CHAR_BIT', headers=['Python.h']): raise RuntimeError( "Config wo CHAR_BIT is not supported"\ ", please contact the maintainers") return private_defines, public_defines def check_mathlib(config_cmd): # Testing the C math library mathlibs = [] mathlibs_choices = [[], ['m'], ['cpml']] mathlib = os.environ.get('MATHLIB') if mathlib: mathlibs_choices.insert(0, mathlib.split(',')) for libs in mathlibs_choices: if config_cmd.check_func("exp", libraries=libs, decl=True, call=True): mathlibs = libs break else: raise EnvironmentError("math library missing; rerun " "setup.py after setting the " "MATHLIB env variable") return mathlibs def visibility_define(config): """Return the define value to use for NPY_VISIBILITY_HIDDEN (may be empty string).""" if config.check_compiler_gcc4(): return '__attribute__((visibility("hidden")))' else: return '' def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration, dot_join from numpy.distutils.system_info import get_info, default_lib_dirs config = Configuration('core', parent_package, top_path) local_dir = config.local_path codegen_dir = join(local_dir, 'code_generators') if is_released(config): warnings.simplefilter('error', MismatchCAPIWarning) # Check whether we have a mismatch between the set C API VERSION and the # actual C API VERSION check_api_version(C_API_VERSION, codegen_dir) generate_umath_py = join(codegen_dir, 'generate_umath.py') n = dot_join(config.name, 'generate_umath') generate_umath = imp.load_module('_'.join(n.split('.')), open(generate_umath_py, 'U'), generate_umath_py, ('.py', 'U', 1)) header_dir = 'include/numpy' # this is relative to config.path_in_package cocache = CallOnceOnly() def generate_config_h(ext, build_dir): target = join(build_dir, header_dir, 'config.h') d = os.path.dirname(target) if not os.path.exists(d): os.makedirs(d) if newer(__file__, target): config_cmd = config.get_config_cmd() log.info('Generating %s', target) # Check sizeof moredefs, ignored = cocache.check_types(config_cmd, ext, build_dir) # Check math library and C99 math funcs availability mathlibs = check_mathlib(config_cmd) moredefs.append(('MATHLIB', ','.join(mathlibs))) check_math_capabilities(config_cmd, moredefs, mathlibs) moredefs.extend(cocache.check_ieee_macros(config_cmd)[0]) moredefs.extend(cocache.check_complex(config_cmd, mathlibs)[0]) # Signal check if is_npy_no_signal(): moredefs.append('__NPY_PRIVATE_NO_SIGNAL') # Windows checks if sys.platform=='win32' or os.name=='nt': win32_checks(moredefs) # Inline check inline = config_cmd.check_inline() # Check whether we need our own wide character support if not config_cmd.check_decl('Py_UNICODE_WIDE', headers=['Python.h']): PYTHON_HAS_UNICODE_WIDE = True else: PYTHON_HAS_UNICODE_WIDE = False if ENABLE_SEPARATE_COMPILATION: moredefs.append(('ENABLE_SEPARATE_COMPILATION', 1)) if NPY_RELAXED_STRIDES_CHECKING: moredefs.append(('NPY_RELAXED_STRIDES_CHECKING', 1)) # Get long double representation if sys.platform != 'darwin': rep = check_long_double_representation(config_cmd) if rep in ['INTEL_EXTENDED_12_BYTES_LE', 'INTEL_EXTENDED_16_BYTES_LE', 'MOTOROLA_EXTENDED_12_BYTES_BE', 'IEEE_QUAD_LE', 'IEEE_QUAD_BE', 'IEEE_DOUBLE_LE', 'IEEE_DOUBLE_BE', 'DOUBLE_DOUBLE_BE']: moredefs.append(('HAVE_LDOUBLE_%s' % rep, 1)) else: raise ValueError("Unrecognized long double format: %s" % rep) # Py3K check if sys.version_info[0] == 3: moredefs.append(('NPY_PY3K', 1)) # Generate the config.h file from moredefs target_f = open(target, 'w') for d in moredefs: if isinstance(d, str): target_f.write('#define %s\n' % (d)) else: target_f.write('#define %s %s\n' % (d[0], d[1])) # define inline to our keyword, or nothing target_f.write('#ifndef __cplusplus\n') if inline == 'inline': target_f.write('/* #undef inline */\n') else: target_f.write('#define inline %s\n' % inline) target_f.write('#endif\n') # add the guard to make sure config.h is never included directly, # but always through npy_config.h target_f.write(""" #ifndef _NPY_NPY_CONFIG_H_ #error config.h should never be included directly, include npy_config.h instead #endif """) target_f.close() print('File:', target) target_f = open(target) print(target_f.read()) target_f.close() print('EOF') else: mathlibs = [] target_f = open(target) for line in target_f: s = '#define MATHLIB' if line.startswith(s): value = line[len(s):].strip() if value: mathlibs.extend(value.split(',')) target_f.close() # Ugly: this can be called within a library and not an extension, # in which case there is no libraries attributes (and none is # needed). if hasattr(ext, 'libraries'): ext.libraries.extend(mathlibs) incl_dir = os.path.dirname(target) if incl_dir not in config.numpy_include_dirs: config.numpy_include_dirs.append(incl_dir) return target def generate_numpyconfig_h(ext, build_dir): """Depends on config.h: generate_config_h has to be called before !""" # put private include directory in build_dir on search path # allows using code generation in headers headers config.add_include_dirs(join(build_dir, "src", "private")) target = join(build_dir, header_dir, '_numpyconfig.h') d = os.path.dirname(target) if not os.path.exists(d): os.makedirs(d) if newer(__file__, target): config_cmd = config.get_config_cmd() log.info('Generating %s', target) # Check sizeof ignored, moredefs = cocache.check_types(config_cmd, ext, build_dir) if is_npy_no_signal(): moredefs.append(('NPY_NO_SIGNAL', 1)) if is_npy_no_smp(): moredefs.append(('NPY_NO_SMP', 1)) else: moredefs.append(('NPY_NO_SMP', 0)) mathlibs = check_mathlib(config_cmd) moredefs.extend(cocache.check_ieee_macros(config_cmd)[1]) moredefs.extend(cocache.check_complex(config_cmd, mathlibs)[1]) if ENABLE_SEPARATE_COMPILATION: moredefs.append(('NPY_ENABLE_SEPARATE_COMPILATION', 1)) if NPY_RELAXED_STRIDES_CHECKING: moredefs.append(('NPY_RELAXED_STRIDES_CHECKING', 1)) # Check wether we can use inttypes (C99) formats if config_cmd.check_decl('PRIdPTR', headers = ['inttypes.h']): moredefs.append(('NPY_USE_C99_FORMATS', 1)) # visibility check hidden_visibility = visibility_define(config_cmd) moredefs.append(('NPY_VISIBILITY_HIDDEN', hidden_visibility)) # Add the C API/ABI versions moredefs.append(('NPY_ABI_VERSION', '0x%.8X' % C_ABI_VERSION)) moredefs.append(('NPY_API_VERSION', '0x%.8X' % C_API_VERSION)) # Add moredefs to header target_f = open(target, 'w') for d in moredefs: if isinstance(d, str): target_f.write('#define %s\n' % (d)) else: target_f.write('#define %s %s\n' % (d[0], d[1])) # Define __STDC_FORMAT_MACROS target_f.write(""" #ifndef __STDC_FORMAT_MACROS #define __STDC_FORMAT_MACROS 1 #endif """) target_f.close() # Dump the numpyconfig.h header to stdout print('File: %s' % target) target_f = open(target) print(target_f.read()) target_f.close() print('EOF') config.add_data_files((header_dir, target)) return target def generate_api_func(module_name): def generate_api(ext, build_dir): script = join(codegen_dir, module_name + '.py') sys.path.insert(0, codegen_dir) try: m = __import__(module_name) log.info('executing %s', script) h_file, c_file, doc_file = m.generate_api(os.path.join(build_dir, header_dir)) finally: del sys.path[0] config.add_data_files((header_dir, h_file), (header_dir, doc_file)) return (h_file,) return generate_api generate_numpy_api = generate_api_func('generate_numpy_api') generate_ufunc_api = generate_api_func('generate_ufunc_api') config.add_include_dirs(join(local_dir, "src", "private")) config.add_include_dirs(join(local_dir, "src")) config.add_include_dirs(join(local_dir)) config.add_data_files('include/numpy/*.h') config.add_include_dirs(join('src', 'npymath')) config.add_include_dirs(join('src', 'multiarray')) config.add_include_dirs(join('src', 'umath')) 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')) deps = [join('src', 'npymath', '_signbit.c'), join('include', 'numpy', '*object.h'), 'include/numpy/fenv/fenv.c', 'include/numpy/fenv/fenv.h', join(codegen_dir, 'genapi.py'), ] # Don't install fenv unless we need them. if sys.platform == 'cygwin': config.add_data_dir('include/numpy/fenv') ####################################################################### # dummy module # ####################################################################### # npymath needs the config.h and numpyconfig.h files to be generated, but # build_clib cannot handle generate_config_h and generate_numpyconfig_h # (don't ask). Because clib are generated before extensions, we have to # explicitly add an extension which has generate_config_h and # generate_numpyconfig_h as sources *before* adding npymath. config.add_extension('_dummy', sources = [join('src', 'dummymodule.c'), generate_config_h, generate_numpyconfig_h, generate_numpy_api] ) ####################################################################### # npymath library # ####################################################################### subst_dict = dict([("sep", os.path.sep), ("pkgname", "numpy.core")]) def get_mathlib_info(*args): # Another ugly hack: the mathlib info is known once build_src is run, # but we cannot use add_installed_pkg_config here either, so we only # update the substition dictionary during npymath build config_cmd = config.get_config_cmd() # Check that the toolchain works, to fail early if it doesn't # (avoid late errors with MATHLIB which are confusing if the # compiler does not work). st = config_cmd.try_link('int main(void) { return 0;}') if not st: raise RuntimeError("Broken toolchain: cannot link a simple C program") mlibs = check_mathlib(config_cmd) posix_mlib = ' '.join(['-l%s' % l for l in mlibs]) msvc_mlib = ' '.join(['%s.lib' % l for l in mlibs]) subst_dict["posix_mathlib"] = posix_mlib subst_dict["msvc_mathlib"] = msvc_mlib npymath_sources = [join('src', 'npymath', 'npy_math.c.src'), join('src', 'npymath', 'ieee754.c.src'), join('src', 'npymath', 'npy_math_complex.c.src'), join('src', 'npymath', 'halffloat.c')] config.add_installed_library('npymath', sources=npymath_sources + [get_mathlib_info], install_dir='lib') config.add_npy_pkg_config("npymath.ini.in", "lib/npy-pkg-config", subst_dict) config.add_npy_pkg_config("mlib.ini.in", "lib/npy-pkg-config", subst_dict) ####################################################################### # npysort library # ####################################################################### # This library is created for the build but it is not installed 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'), ] config.add_library('npysort', sources=npysort_sources, include_dirs=[]) ####################################################################### # multiarray module # ####################################################################### # Multiarray version: this function is needed to build foo.c from foo.c.src # when foo.c is included in another file and as such not in the src # argument of build_ext command def generate_multiarray_templated_sources(ext, build_dir): from numpy.distutils.misc_util import get_cmd subpath = join('src', 'multiarray') sources = [join(local_dir, subpath, 'scalartypes.c.src'), join(local_dir, subpath, 'arraytypes.c.src'), join(local_dir, subpath, 'nditer_templ.c.src'), join(local_dir, subpath, 'lowlevel_strided_loops.c.src'), join(local_dir, subpath, 'einsum.c.src')] # numpy.distutils generate .c from .c.src in weird directories, we have # to add them there as they depend on the build_dir config.add_include_dirs(join(build_dir, subpath)) cmd = get_cmd('build_src') cmd.ensure_finalized() cmd.template_sources(sources, ext) multiarray_deps = [ join('src', 'multiarray', 'arrayobject.h'), join('src', 'multiarray', 'arraytypes.h'), join('src', 'multiarray', 'array_assign.h'), join('src', 'multiarray', 'buffer.h'), join('src', 'multiarray', 'calculation.h'), join('src', 'multiarray', 'common.h'), join('src', 'multiarray', 'convert_datatype.h'), join('src', 'multiarray', 'convert.h'), join('src', 'multiarray', 'conversion_utils.h'), join('src', 'multiarray', 'ctors.h'), join('src', 'multiarray', 'descriptor.h'), join('src', 'multiarray', 'getset.h'), join('src', 'multiarray', 'hashdescr.h'), join('src', 'multiarray', 'iterators.h'), join('src', 'multiarray', 'mapping.h'), join('src', 'multiarray', 'methods.h'), join('src', 'multiarray', 'multiarraymodule.h'), join('src', 'multiarray', 'nditer_impl.h'), join('src', 'multiarray', 'numpymemoryview.h'), join('src', 'multiarray', 'number.h'), join('src', 'multiarray', 'numpyos.h'), join('src', 'multiarray', 'refcount.h'), join('src', 'multiarray', 'scalartypes.h'), join('src', 'multiarray', 'sequence.h'), join('src', 'multiarray', 'shape.h'), join('src', 'multiarray', 'ucsnarrow.h'), join('src', 'multiarray', 'usertypes.h'), join('src', 'private', 'lowlevel_strided_loops.h'), join('include', 'numpy', 'arrayobject.h'), join('include', 'numpy', '_neighborhood_iterator_imp.h'), join('include', 'numpy', 'npy_endian.h'), join('include', 'numpy', 'arrayscalars.h'), join('include', 'numpy', 'noprefix.h'), join('include', 'numpy', 'npy_interrupt.h'), join('include', 'numpy', 'oldnumeric.h'), join('include', 'numpy', 'npy_3kcompat.h'), join('include', 'numpy', 'npy_math.h'), join('include', 'numpy', 'halffloat.h'), join('include', 'numpy', 'npy_common.h'), join('include', 'numpy', 'npy_os.h'), join('include', 'numpy', 'utils.h'), join('include', 'numpy', 'ndarrayobject.h'), join('include', 'numpy', 'npy_cpu.h'), join('include', 'numpy', 'numpyconfig.h'), join('include', 'numpy', 'ndarraytypes.h'), join('include', 'numpy', 'npy_1_7_deprecated_api.h'), join('include', 'numpy', '_numpyconfig.h.in'), # add library sources as distuils does not consider libraries # dependencies ] + npysort_sources + npymath_sources multiarray_src = [ join('src', 'multiarray', 'arrayobject.c'), join('src', 'multiarray', 'arraytypes.c.src'), join('src', 'multiarray', 'array_assign.c'), join('src', 'multiarray', 'array_assign_scalar.c'), join('src', 'multiarray', 'array_assign_array.c'), join('src', 'multiarray', 'buffer.c'), join('src', 'multiarray', 'calculation.c'), join('src', 'multiarray', 'common.c'), join('src', 'multiarray', 'convert.c'), join('src', 'multiarray', 'convert_datatype.c'), join('src', 'multiarray', 'conversion_utils.c'), join('src', 'multiarray', 'ctors.c'), join('src', 'multiarray', 'datetime.c'), join('src', 'multiarray', 'datetime_strings.c'), join('src', 'multiarray', 'datetime_busday.c'), join('src', 'multiarray', 'datetime_busdaycal.c'), join('src', 'multiarray', 'descriptor.c'), join('src', 'multiarray', 'dtype_transfer.c'), join('src', 'multiarray', 'einsum.c.src'), join('src', 'multiarray', 'flagsobject.c'), join('src', 'multiarray', 'getset.c'), join('src', 'multiarray', 'hashdescr.c'), join('src', 'multiarray', 'item_selection.c'), join('src', 'multiarray', 'iterators.c'), join('src', 'multiarray', 'lowlevel_strided_loops.c.src'), join('src', 'multiarray', 'mapping.c'), join('src', 'multiarray', 'methods.c'), join('src', 'multiarray', 'multiarraymodule.c'), join('src', 'multiarray', 'nditer_templ.c.src'), join('src', 'multiarray', 'nditer_api.c'), join('src', 'multiarray', 'nditer_constr.c'), join('src', 'multiarray', 'nditer_pywrap.c'), join('src', 'multiarray', 'number.c'), join('src', 'multiarray', 'numpymemoryview.c'), join('src', 'multiarray', 'numpyos.c'), join('src', 'multiarray', 'refcount.c'), join('src', 'multiarray', 'sequence.c'), join('src', 'multiarray', 'shape.c'), join('src', 'multiarray', 'scalarapi.c'), join('src', 'multiarray', 'scalartypes.c.src'), join('src', 'multiarray', 'usertypes.c'), join('src', 'multiarray', 'ucsnarrow.c')] if not ENABLE_SEPARATE_COMPILATION: multiarray_deps.extend(multiarray_src) multiarray_src = [join('src', 'multiarray', 'multiarraymodule_onefile.c')] multiarray_src.append(generate_multiarray_templated_sources) config.add_extension('multiarray', sources = multiarray_src + [generate_config_h, generate_numpyconfig_h, generate_numpy_api, join(codegen_dir, 'generate_numpy_api.py'), join('*.py')], depends = deps + multiarray_deps, libraries = ['npymath', 'npysort']) ####################################################################### # umath module # ####################################################################### # umath version: this function is needed to build foo.c from foo.c.src # when foo.c is included in another file and as such not in the src # argument of build_ext command def generate_umath_templated_sources(ext, build_dir): 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.c.src'), join(local_dir, subpath, 'simd.inc.src')] # numpy.distutils generate .c from .c.src in weird directories, we have # to add them there as they depend on the build_dir config.add_include_dirs(join(build_dir, subpath)) cmd = get_cmd('build_src') cmd.ensure_finalized() cmd.template_sources(sources, ext) def generate_umath_c(ext, build_dir): target = join(build_dir, header_dir, '__umath_generated.c') dir = os.path.dirname(target) if not os.path.exists(dir): os.makedirs(dir) script = generate_umath_py if newer(script, target): f = open(target, 'w') f.write(generate_umath.make_code(generate_umath.defdict, generate_umath.__file__)) f.close() return [] umath_src = [ join('src', 'umath', 'umathmodule.c'), join('src', 'umath', 'reduction.c'), join('src', 'umath', 'funcs.inc.src'), join('src', 'umath', 'simd.inc.src'), join('src', 'umath', 'loops.c.src'), join('src', 'umath', 'ufunc_object.c'), join('src', 'umath', 'ufunc_type_resolution.c')] umath_deps = [ generate_umath_py, join('src', 'multiarray', 'common.h'), join('src', 'umath', 'simd.inc.src'), join(codegen_dir, 'generate_ufunc_api.py'),] + npymath_sources if not ENABLE_SEPARATE_COMPILATION: umath_deps.extend(umath_src) umath_src = [join('src', 'umath', 'umathmodule_onefile.c')] umath_src.append(generate_umath_templated_sources) umath_src.append(join('src', 'umath', 'funcs.inc.src')) umath_src.append(join('src', 'umath', 'simd.inc.src')) config.add_extension('umath', sources = umath_src + [generate_config_h, generate_numpyconfig_h, generate_umath_c, generate_ufunc_api], depends = deps + umath_deps, libraries = ['npymath'], ) ####################################################################### # scalarmath module # ####################################################################### config.add_extension('scalarmath', sources = [join('src', 'scalarmathmodule.c.src'), join('src', 'private', 'scalarmathmodule.h.src'), generate_config_h, generate_numpyconfig_h, generate_numpy_api, generate_ufunc_api], depends = deps + npymath_sources, libraries = ['npymath'], ) ####################################################################### # _dotblas module # ####################################################################### # Configure blasdot blas_info = get_info('blas_opt', 0) #blas_info = {} def get_dotblas_sources(ext, build_dir): if blas_info: if ('NO_ATLAS_INFO', 1) in blas_info.get('define_macros', []): return None # dotblas needs ATLAS, Fortran compiled blas will not be sufficient. return ext.depends[:1] return None # no extension module will be built config.add_extension('_dotblas', sources = [get_dotblas_sources], depends = [join('blasdot', '_dotblas.c'), join('blasdot', 'cblas.h'), ], include_dirs = ['blasdot'], extra_info = blas_info ) ####################################################################### # umath_tests module # ####################################################################### config.add_extension('umath_tests', sources = [join('src', 'umath', 'umath_tests.c.src')]) ####################################################################### # custom rational dtype module # ####################################################################### config.add_extension('test_rational', sources = [join('src', 'umath', 'test_rational.c.src')]) ####################################################################### # struct_ufunc_test module # ####################################################################### config.add_extension('struct_ufunc_test', sources = [join('src', 'umath', 'struct_ufunc_test.c.src')]) ####################################################################### # multiarray_tests module # ####################################################################### config.add_extension('multiarray_tests', sources = [join('src', 'multiarray', 'multiarray_tests.c.src')]) ####################################################################### # operand_flag_tests module # ####################################################################### config.add_extension('operand_flag_tests', sources = [join('src', 'umath', 'operand_flag_tests.c.src')]) config.add_data_dir('tests') config.add_data_dir('tests/data') config.make_svn_version_py() return config if __name__=='__main__': from numpy.distutils.core import setup setup(configuration=configuration) numpy-1.8.2/numpy/core/include/0000775000175100017510000000000012371375427017562 5ustar vagrantvagrant00000000000000numpy-1.8.2/numpy/core/include/numpy/0000775000175100017510000000000012371375427020732 5ustar vagrantvagrant00000000000000numpy-1.8.2/numpy/core/include/numpy/_neighborhood_iterator_imp.h0000664000175100017510000000350512370216242026456 0ustar vagrantvagrant00000000000000#ifndef _NPY_INCLUDE_NEIGHBORHOOD_IMP #error You should not include this header directly #endif /* * Private API (here for inline) */ static NPY_INLINE int _PyArrayNeighborhoodIter_IncrCoord(PyArrayNeighborhoodIterObject* iter); /* * Update to next item of the iterator * * Note: this simply increment the coordinates vector, last dimension * incremented first , i.e, for dimension 3 * ... * -1, -1, -1 * -1, -1, 0 * -1, -1, 1 * .... * -1, 0, -1 * -1, 0, 0 * .... * 0, -1, -1 * 0, -1, 0 * .... */ #define _UPDATE_COORD_ITER(c) \ wb = iter->coordinates[c] < iter->bounds[c][1]; \ if (wb) { \ iter->coordinates[c] += 1; \ return 0; \ } \ else { \ iter->coordinates[c] = iter->bounds[c][0]; \ } static NPY_INLINE int _PyArrayNeighborhoodIter_IncrCoord(PyArrayNeighborhoodIterObject* iter) { npy_intp i, wb; for (i = iter->nd - 1; i >= 0; --i) { _UPDATE_COORD_ITER(i) } return 0; } /* * Version optimized for 2d arrays, manual loop unrolling */ static NPY_INLINE int _PyArrayNeighborhoodIter_IncrCoord2D(PyArrayNeighborhoodIterObject* iter) { npy_intp wb; _UPDATE_COORD_ITER(1) _UPDATE_COORD_ITER(0) return 0; } #undef _UPDATE_COORD_ITER /* * Advance to the next neighbour */ static NPY_INLINE int PyArrayNeighborhoodIter_Next(PyArrayNeighborhoodIterObject* iter) { _PyArrayNeighborhoodIter_IncrCoord (iter); iter->dataptr = iter->translate((PyArrayIterObject*)iter, iter->coordinates); return 0; } /* * Reset functions */ static NPY_INLINE int PyArrayNeighborhoodIter_Reset(PyArrayNeighborhoodIterObject* iter) { npy_intp i; for (i = 0; i < iter->nd; ++i) { iter->coordinates[i] = iter->bounds[i][0]; } iter->dataptr = iter->translate((PyArrayIterObject*)iter, iter->coordinates); return 0; } numpy-1.8.2/numpy/core/include/numpy/fenv/0000775000175100017510000000000012371375427021670 5ustar vagrantvagrant00000000000000numpy-1.8.2/numpy/core/include/numpy/fenv/fenv.h0000664000175100017510000001301212370216242022760 0ustar vagrantvagrant00000000000000/*- * Copyright (c) 2004 David Schultz * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * $FreeBSD$ */ #ifndef _FENV_H_ #define _FENV_H_ #include #include typedef struct { __uint32_t __control; __uint32_t __status; __uint32_t __tag; char __other[16]; } fenv_t; typedef __uint16_t fexcept_t; /* Exception flags */ #define FE_INVALID 0x01 #define FE_DENORMAL 0x02 #define FE_DIVBYZERO 0x04 #define FE_OVERFLOW 0x08 #define FE_UNDERFLOW 0x10 #define FE_INEXACT 0x20 #define FE_ALL_EXCEPT (FE_DIVBYZERO | FE_DENORMAL | FE_INEXACT | \ FE_INVALID | FE_OVERFLOW | FE_UNDERFLOW) /* Rounding modes */ #define FE_TONEAREST 0x0000 #define FE_DOWNWARD 0x0400 #define FE_UPWARD 0x0800 #define FE_TOWARDZERO 0x0c00 #define _ROUND_MASK (FE_TONEAREST | FE_DOWNWARD | \ FE_UPWARD | FE_TOWARDZERO) __BEGIN_DECLS /* Default floating-point environment */ extern const fenv_t npy__fe_dfl_env; #define FE_DFL_ENV (&npy__fe_dfl_env) #define __fldcw(__cw) __asm __volatile("fldcw %0" : : "m" (__cw)) #define __fldenv(__env) __asm __volatile("fldenv %0" : : "m" (__env)) #define __fnclex() __asm __volatile("fnclex") #define __fnstenv(__env) __asm __volatile("fnstenv %0" : "=m" (*(__env))) #define __fnstcw(__cw) __asm __volatile("fnstcw %0" : "=m" (*(__cw))) #define __fnstsw(__sw) __asm __volatile("fnstsw %0" : "=am" (*(__sw))) #define __fwait() __asm __volatile("fwait") static __inline int feclearexcept(int __excepts) { fenv_t __env; if (__excepts == FE_ALL_EXCEPT) { __fnclex(); } else { __fnstenv(&__env); __env.__status &= ~__excepts; __fldenv(__env); } return (0); } static __inline int fegetexceptflag(fexcept_t *__flagp, int __excepts) { __uint16_t __status; __fnstsw(&__status); *__flagp = __status & __excepts; return (0); } static __inline int fesetexceptflag(const fexcept_t *__flagp, int __excepts) { fenv_t __env; __fnstenv(&__env); __env.__status &= ~__excepts; __env.__status |= *__flagp & __excepts; __fldenv(__env); return (0); } static __inline int feraiseexcept(int __excepts) { fexcept_t __ex = __excepts; fesetexceptflag(&__ex, __excepts); __fwait(); return (0); } static __inline int fetestexcept(int __excepts) { __uint16_t __status; __fnstsw(&__status); return (__status & __excepts); } static __inline int fegetround(void) { int __control; __fnstcw(&__control); return (__control & _ROUND_MASK); } static __inline int fesetround(int __round) { int __control; if (__round & ~_ROUND_MASK) return (-1); __fnstcw(&__control); __control &= ~_ROUND_MASK; __control |= __round; __fldcw(__control); return (0); } static __inline int fegetenv(fenv_t *__envp) { int __control; /* * fnstenv masks all exceptions, so we need to save and * restore the control word to avoid this side effect. */ __fnstcw(&__control); __fnstenv(__envp); __fldcw(__control); return (0); } static __inline int feholdexcept(fenv_t *__envp) { __fnstenv(__envp); __fnclex(); return (0); } static __inline int fesetenv(const fenv_t *__envp) { __fldenv(*__envp); return (0); } static __inline int feupdateenv(const fenv_t *__envp) { __uint16_t __status; __fnstsw(&__status); __fldenv(*__envp); feraiseexcept(__status & FE_ALL_EXCEPT); return (0); } #if __BSD_VISIBLE static __inline int fesetmask(int __mask) { int __control; __fnstcw(&__control); __mask = (__control | FE_ALL_EXCEPT) & ~__mask; __fldcw(__mask); return (~__control & FE_ALL_EXCEPT); } static __inline int fegetmask(void) { int __control; __fnstcw(&__control); return (~__control & FE_ALL_EXCEPT); } #endif /* __BSD_VISIBLE */ __END_DECLS #endif /* !_FENV_H_ */ numpy-1.8.2/numpy/core/include/numpy/fenv/fenv.c0000664000175100017510000000315512370216242022762 0ustar vagrantvagrant00000000000000/*- * Copyright (c) 2004 David Schultz * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * $FreeBSD$ */ #include #include "fenv.h" const fenv_t npy__fe_dfl_env = { 0xffff0000, 0xffff0000, 0xffffffff, { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff } }; numpy-1.8.2/numpy/core/include/numpy/ufuncobject.h0000664000175100017510000004077312370216243023412 0ustar vagrantvagrant00000000000000#ifndef Py_UFUNCOBJECT_H #define Py_UFUNCOBJECT_H #include #ifdef __cplusplus extern "C" { #endif /* * The legacy generic inner loop for a standard element-wise or * generalized ufunc. */ typedef void (*PyUFuncGenericFunction) (char **args, npy_intp *dimensions, npy_intp *strides, void *innerloopdata); /* * The most generic one-dimensional inner loop for * a standard element-wise ufunc. This typedef is also * more consistent with the other NumPy function pointer typedefs * than PyUFuncGenericFunction. */ typedef void (PyUFunc_StridedInnerLoopFunc)( char **dataptrs, npy_intp *strides, npy_intp count, NpyAuxData *innerloopdata); /* * The most generic one-dimensional inner loop for * a masked standard element-wise ufunc. "Masked" here means that it skips * doing calculations on any items for which the maskptr array has a true * value. */ typedef void (PyUFunc_MaskedStridedInnerLoopFunc)( char **dataptrs, npy_intp *strides, char *maskptr, npy_intp mask_stride, npy_intp count, NpyAuxData *innerloopdata); /* Forward declaration for the type resolver and loop selector typedefs */ struct _tagPyUFuncObject; /* * Given the operands for calling a ufunc, should determine the * calculation input and output data types and return an inner loop function. * This function should validate that the casting rule is being followed, * and fail if it is not. * * For backwards compatibility, the regular type resolution function does not * support auxiliary data with object semantics. The type resolution call * which returns a masked generic function returns a standard NpyAuxData * object, for which the NPY_AUXDATA_FREE and NPY_AUXDATA_CLONE macros * work. * * ufunc: The ufunc object. * casting: The 'casting' parameter provided to the ufunc. * operands: An array of length (ufunc->nin + ufunc->nout), * with the output parameters possibly NULL. * type_tup: Either NULL, or the type_tup passed to the ufunc. * out_dtypes: An array which should be populated with new * references to (ufunc->nin + ufunc->nout) new * dtypes, one for each input and output. These * dtypes should all be in native-endian format. * * Should return 0 on success, -1 on failure (with exception set), * or -2 if Py_NotImplemented should be returned. */ typedef int (PyUFunc_TypeResolutionFunc)( struct _tagPyUFuncObject *ufunc, NPY_CASTING casting, PyArrayObject **operands, PyObject *type_tup, PyArray_Descr **out_dtypes); /* * Given an array of DTypes as returned by the PyUFunc_TypeResolutionFunc, * and an array of fixed strides (the array will contain NPY_MAX_INTP for * strides which are not necessarily fixed), returns an inner loop * with associated auxiliary data. * * For backwards compatibility, there is a variant of the inner loop * selection which returns an inner loop irrespective of the strides, * and with a void* static auxiliary data instead of an NpyAuxData * * dynamically allocatable auxiliary data. * * ufunc: The ufunc object. * dtypes: An array which has been populated with dtypes, * in most cases by the type resolution funciton * for the same ufunc. * fixed_strides: For each input/output, either the stride that * will be used every time the function is called * or NPY_MAX_INTP if the stride might change or * is not known ahead of time. The loop selection * function may use this stride to pick inner loops * which are optimized for contiguous or 0-stride * cases. * out_innerloop: Should be populated with the correct ufunc inner * loop for the given type. * out_innerloopdata: Should be populated with the void* data to * be passed into the out_innerloop function. * out_needs_api: If the inner loop needs to use the Python API, * should set the to 1, otherwise should leave * this untouched. */ typedef int (PyUFunc_LegacyInnerLoopSelectionFunc)( struct _tagPyUFuncObject *ufunc, PyArray_Descr **dtypes, PyUFuncGenericFunction *out_innerloop, void **out_innerloopdata, int *out_needs_api); typedef int (PyUFunc_InnerLoopSelectionFunc)( struct _tagPyUFuncObject *ufunc, PyArray_Descr **dtypes, npy_intp *fixed_strides, PyUFunc_StridedInnerLoopFunc **out_innerloop, NpyAuxData **out_innerloopdata, int *out_needs_api); typedef int (PyUFunc_MaskedInnerLoopSelectionFunc)( struct _tagPyUFuncObject *ufunc, PyArray_Descr **dtypes, PyArray_Descr *mask_dtype, npy_intp *fixed_strides, npy_intp fixed_mask_stride, PyUFunc_MaskedStridedInnerLoopFunc **out_innerloop, NpyAuxData **out_innerloopdata, int *out_needs_api); typedef struct _tagPyUFuncObject { PyObject_HEAD /* * nin: Number of inputs * nout: Number of outputs * nargs: Always nin + nout (Why is it stored?) */ int nin, nout, nargs; /* Identity for reduction, either PyUFunc_One or PyUFunc_Zero */ int identity; /* Array of one-dimensional core loops */ PyUFuncGenericFunction *functions; /* Array of funcdata that gets passed into the functions */ void **data; /* The number of elements in 'functions' and 'data' */ int ntypes; /* Does not appear to be used */ int check_return; /* The name of the ufunc */ char *name; /* Array of type numbers, of size ('nargs' * 'ntypes') */ char *types; /* Documentation string */ char *doc; void *ptr; PyObject *obj; PyObject *userloops; /* generalized ufunc parameters */ /* 0 for scalar ufunc; 1 for generalized ufunc */ int core_enabled; /* number of distinct dimension names in signature */ int core_num_dim_ix; /* * dimension indices of input/output argument k are stored in * core_dim_ixs[core_offsets[k]..core_offsets[k]+core_num_dims[k]-1] */ /* numbers of core dimensions of each argument */ int *core_num_dims; /* * dimension indices in a flatted form; indices * are in the range of [0,core_num_dim_ix) */ int *core_dim_ixs; /* * positions of 1st core dimensions of each * argument in core_dim_ixs */ int *core_offsets; /* signature string for printing purpose */ char *core_signature; /* * A function which resolves the types and fills an array * with the dtypes for the inputs and outputs. */ PyUFunc_TypeResolutionFunc *type_resolver; /* * A function which returns an inner loop written for * NumPy 1.6 and earlier ufuncs. This is for backwards * compatibility, and may be NULL if inner_loop_selector * is specified. */ PyUFunc_LegacyInnerLoopSelectionFunc *legacy_inner_loop_selector; /* * A function which returns an inner loop for the new mechanism * in NumPy 1.7 and later. If provided, this is used, otherwise * if NULL the legacy_inner_loop_selector is used instead. */ PyUFunc_InnerLoopSelectionFunc *inner_loop_selector; /* * A function which returns a masked inner loop for the ufunc. */ PyUFunc_MaskedInnerLoopSelectionFunc *masked_inner_loop_selector; /* * List of flags for each operand when ufunc is called by nditer object. * These flags will be used in addition to the default flags for each * operand set by nditer object. */ npy_uint32 *op_flags; /* * List of global flags used when ufunc is called by nditer object. * These flags will be used in addition to the default global flags * set by nditer object. */ npy_uint32 iter_flags; } PyUFuncObject; #include "arrayobject.h" #define UFUNC_ERR_IGNORE 0 #define UFUNC_ERR_WARN 1 #define UFUNC_ERR_RAISE 2 #define UFUNC_ERR_CALL 3 #define UFUNC_ERR_PRINT 4 #define UFUNC_ERR_LOG 5 /* Python side integer mask */ #define UFUNC_MASK_DIVIDEBYZERO 0x07 #define UFUNC_MASK_OVERFLOW 0x3f #define UFUNC_MASK_UNDERFLOW 0x1ff #define UFUNC_MASK_INVALID 0xfff #define UFUNC_SHIFT_DIVIDEBYZERO 0 #define UFUNC_SHIFT_OVERFLOW 3 #define UFUNC_SHIFT_UNDERFLOW 6 #define UFUNC_SHIFT_INVALID 9 /* platform-dependent code translates floating point status to an integer sum of these values */ #define UFUNC_FPE_DIVIDEBYZERO 1 #define UFUNC_FPE_OVERFLOW 2 #define UFUNC_FPE_UNDERFLOW 4 #define UFUNC_FPE_INVALID 8 /* Error mode that avoids look-up (no checking) */ #define UFUNC_ERR_DEFAULT 0 #define UFUNC_OBJ_ISOBJECT 1 #define UFUNC_OBJ_NEEDS_API 2 /* Default user error mode */ #define UFUNC_ERR_DEFAULT2 \ (UFUNC_ERR_WARN << UFUNC_SHIFT_DIVIDEBYZERO) + \ (UFUNC_ERR_WARN << UFUNC_SHIFT_OVERFLOW) + \ (UFUNC_ERR_WARN << UFUNC_SHIFT_INVALID) #if NPY_ALLOW_THREADS #define NPY_LOOP_BEGIN_THREADS do {if (!(loop->obj & UFUNC_OBJ_NEEDS_API)) _save = PyEval_SaveThread();} while (0); #define NPY_LOOP_END_THREADS do {if (!(loop->obj & UFUNC_OBJ_NEEDS_API)) PyEval_RestoreThread(_save);} while (0); #else #define NPY_LOOP_BEGIN_THREADS #define NPY_LOOP_END_THREADS #endif /* * UFunc has unit of 1, and the order of operations can be reordered * This case allows reduction with multiple axes at once. */ #define PyUFunc_One 1 /* * UFunc has unit of 0, and the order of operations can be reordered * This case allows reduction with multiple axes at once. */ #define PyUFunc_Zero 0 /* * UFunc has no unit, and the order of operations cannot be reordered. * This case does not allow reduction with multiple axes at once. */ #define PyUFunc_None -1 /* * UFunc has no unit, and the order of operations can be reordered * This case allows reduction with multiple axes at once. */ #define PyUFunc_ReorderableNone -2 #define UFUNC_REDUCE 0 #define UFUNC_ACCUMULATE 1 #define UFUNC_REDUCEAT 2 #define UFUNC_OUTER 3 typedef struct { int nin; int nout; PyObject *callable; } PyUFunc_PyFuncData; /* A linked-list of function information for user-defined 1-d loops. */ typedef struct _loop1d_info { PyUFuncGenericFunction func; void *data; int *arg_types; struct _loop1d_info *next; int nargs; PyArray_Descr **arg_dtypes; } PyUFunc_Loop1d; #include "__ufunc_api.h" #define UFUNC_PYVALS_NAME "UFUNC_PYVALS" #define UFUNC_CHECK_ERROR(arg) \ do {if ((((arg)->obj & UFUNC_OBJ_NEEDS_API) && PyErr_Occurred()) || \ ((arg)->errormask && \ PyUFunc_checkfperr((arg)->errormask, \ (arg)->errobj, \ &(arg)->first))) \ goto fail;} while (0) /* This code checks the IEEE status flags in a platform-dependent way */ /* Adapted from Numarray */ #if (defined(__unix__) || defined(unix)) && !defined(USG) #include #endif /* OSF/Alpha (Tru64) ---------------------------------------------*/ #if defined(__osf__) && defined(__alpha) #include #define UFUNC_CHECK_STATUS(ret) { \ unsigned long fpstatus; \ \ fpstatus = ieee_get_fp_control(); \ /* clear status bits as well as disable exception mode if on */ \ ieee_set_fp_control( 0 ); \ ret = ((IEEE_STATUS_DZE & fpstatus) ? UFUNC_FPE_DIVIDEBYZERO : 0) \ | ((IEEE_STATUS_OVF & fpstatus) ? UFUNC_FPE_OVERFLOW : 0) \ | ((IEEE_STATUS_UNF & fpstatus) ? UFUNC_FPE_UNDERFLOW : 0) \ | ((IEEE_STATUS_INV & fpstatus) ? UFUNC_FPE_INVALID : 0); \ } /* MS Windows -----------------------------------------------------*/ #elif defined(_MSC_VER) #include /* Clear the floating point exception default of Borland C++ */ #if defined(__BORLANDC__) #define UFUNC_NOFPE _control87(MCW_EM, MCW_EM); #endif #if defined(_WIN64) #define UFUNC_CHECK_STATUS(ret) { \ int fpstatus = (int) _clearfp(); \ \ ret = ((SW_ZERODIVIDE & fpstatus) ? UFUNC_FPE_DIVIDEBYZERO : 0) \ | ((SW_OVERFLOW & fpstatus) ? UFUNC_FPE_OVERFLOW : 0) \ | ((SW_UNDERFLOW & fpstatus) ? UFUNC_FPE_UNDERFLOW : 0) \ | ((SW_INVALID & fpstatus) ? UFUNC_FPE_INVALID : 0); \ } #else /* windows enables sse on 32 bit, so check both flags */ #define UFUNC_CHECK_STATUS(ret) { \ int fpstatus, fpstatus2; \ _statusfp2(&fpstatus, &fpstatus2); \ _clearfp(); \ fpstatus |= fpstatus2; \ \ ret = ((SW_ZERODIVIDE & fpstatus) ? UFUNC_FPE_DIVIDEBYZERO : 0) \ | ((SW_OVERFLOW & fpstatus) ? UFUNC_FPE_OVERFLOW : 0) \ | ((SW_UNDERFLOW & fpstatus) ? UFUNC_FPE_UNDERFLOW : 0) \ | ((SW_INVALID & fpstatus) ? UFUNC_FPE_INVALID : 0); \ } #endif /* Solaris --------------------------------------------------------*/ /* --------ignoring SunOS ieee_flags approach, someone else can ** deal with that! */ #elif defined(sun) || defined(__BSD__) || defined(__OpenBSD__) || \ (defined(__FreeBSD__) && (__FreeBSD_version < 502114)) || \ defined(__NetBSD__) #include #define UFUNC_CHECK_STATUS(ret) { \ int fpstatus; \ \ fpstatus = (int) fpgetsticky(); \ ret = ((FP_X_DZ & fpstatus) ? UFUNC_FPE_DIVIDEBYZERO : 0) \ | ((FP_X_OFL & fpstatus) ? UFUNC_FPE_OVERFLOW : 0) \ | ((FP_X_UFL & fpstatus) ? UFUNC_FPE_UNDERFLOW : 0) \ | ((FP_X_INV & fpstatus) ? UFUNC_FPE_INVALID : 0); \ (void) fpsetsticky(0); \ } #elif defined(__GLIBC__) || defined(__APPLE__) || \ defined(__CYGWIN__) || defined(__MINGW32__) || \ (defined(__FreeBSD__) && (__FreeBSD_version >= 502114)) #if defined(__GLIBC__) || defined(__APPLE__) || \ defined(__MINGW32__) || defined(__FreeBSD__) #include #elif defined(__CYGWIN__) #include "numpy/fenv/fenv.h" #endif #define UFUNC_CHECK_STATUS(ret) { \ int fpstatus = (int) fetestexcept(FE_DIVBYZERO | FE_OVERFLOW | \ FE_UNDERFLOW | FE_INVALID); \ ret = ((FE_DIVBYZERO & fpstatus) ? UFUNC_FPE_DIVIDEBYZERO : 0) \ | ((FE_OVERFLOW & fpstatus) ? UFUNC_FPE_OVERFLOW : 0) \ | ((FE_UNDERFLOW & fpstatus) ? UFUNC_FPE_UNDERFLOW : 0) \ | ((FE_INVALID & fpstatus) ? UFUNC_FPE_INVALID : 0); \ (void) feclearexcept(FE_DIVBYZERO | FE_OVERFLOW | \ FE_UNDERFLOW | FE_INVALID); \ } #elif defined(_AIX) #include #include #define UFUNC_CHECK_STATUS(ret) { \ fpflag_t fpstatus; \ \ fpstatus = fp_read_flag(); \ ret = ((FP_DIV_BY_ZERO & fpstatus) ? UFUNC_FPE_DIVIDEBYZERO : 0) \ | ((FP_OVERFLOW & fpstatus) ? UFUNC_FPE_OVERFLOW : 0) \ | ((FP_UNDERFLOW & fpstatus) ? UFUNC_FPE_UNDERFLOW : 0) \ | ((FP_INVALID & fpstatus) ? UFUNC_FPE_INVALID : 0); \ fp_swap_flag(0); \ } #else #define NO_FLOATING_POINT_SUPPORT #define UFUNC_CHECK_STATUS(ret) { \ ret = 0; \ } #endif /* * THESE MACROS ARE DEPRECATED. * Use npy_set_floatstatus_* in the npymath library. */ #define generate_divbyzero_error() npy_set_floatstatus_divbyzero() #define generate_overflow_error() npy_set_floatstatus_overflow() /* Make sure it gets defined if it isn't already */ #ifndef UFUNC_NOFPE #define UFUNC_NOFPE #endif #ifdef __cplusplus } #endif #endif /* !Py_UFUNCOBJECT_H */ numpy-1.8.2/numpy/core/include/numpy/npy_math.h0000664000175100017510000003436712370216243022724 0ustar vagrantvagrant00000000000000#ifndef __NPY_MATH_C99_H_ #define __NPY_MATH_C99_H_ #ifdef __cplusplus extern "C" { #endif #include #ifdef __SUNPRO_CC #include #endif #ifdef HAVE_NPY_CONFIG_H #include #endif #include /* * NAN and INFINITY like macros (same behavior as glibc for NAN, same as C99 * for INFINITY) * * XXX: I should test whether INFINITY and NAN are available on the platform */ NPY_INLINE static float __npy_inff(void) { const union { npy_uint32 __i; float __f;} __bint = {0x7f800000UL}; return __bint.__f; } NPY_INLINE static float __npy_nanf(void) { const union { npy_uint32 __i; float __f;} __bint = {0x7fc00000UL}; return __bint.__f; } NPY_INLINE static float __npy_pzerof(void) { const union { npy_uint32 __i; float __f;} __bint = {0x00000000UL}; return __bint.__f; } NPY_INLINE static float __npy_nzerof(void) { const union { npy_uint32 __i; float __f;} __bint = {0x80000000UL}; return __bint.__f; } #define NPY_INFINITYF __npy_inff() #define NPY_NANF __npy_nanf() #define NPY_PZEROF __npy_pzerof() #define NPY_NZEROF __npy_nzerof() #define NPY_INFINITY ((npy_double)NPY_INFINITYF) #define NPY_NAN ((npy_double)NPY_NANF) #define NPY_PZERO ((npy_double)NPY_PZEROF) #define NPY_NZERO ((npy_double)NPY_NZEROF) #define NPY_INFINITYL ((npy_longdouble)NPY_INFINITYF) #define NPY_NANL ((npy_longdouble)NPY_NANF) #define NPY_PZEROL ((npy_longdouble)NPY_PZEROF) #define NPY_NZEROL ((npy_longdouble)NPY_NZEROF) /* * Useful constants */ #define NPY_E 2.718281828459045235360287471352662498 /* e */ #define NPY_LOG2E 1.442695040888963407359924681001892137 /* log_2 e */ #define NPY_LOG10E 0.434294481903251827651128918916605082 /* log_10 e */ #define NPY_LOGE2 0.693147180559945309417232121458176568 /* log_e 2 */ #define NPY_LOGE10 2.302585092994045684017991454684364208 /* log_e 10 */ #define NPY_PI 3.141592653589793238462643383279502884 /* pi */ #define NPY_PI_2 1.570796326794896619231321691639751442 /* pi/2 */ #define NPY_PI_4 0.785398163397448309615660845819875721 /* pi/4 */ #define NPY_1_PI 0.318309886183790671537767526745028724 /* 1/pi */ #define NPY_2_PI 0.636619772367581343075535053490057448 /* 2/pi */ #define NPY_EULER 0.577215664901532860606512090082402431 /* Euler constant */ #define NPY_SQRT2 1.414213562373095048801688724209698079 /* sqrt(2) */ #define NPY_SQRT1_2 0.707106781186547524400844362104849039 /* 1/sqrt(2) */ #define NPY_Ef 2.718281828459045235360287471352662498F /* e */ #define NPY_LOG2Ef 1.442695040888963407359924681001892137F /* log_2 e */ #define NPY_LOG10Ef 0.434294481903251827651128918916605082F /* log_10 e */ #define NPY_LOGE2f 0.693147180559945309417232121458176568F /* log_e 2 */ #define NPY_LOGE10f 2.302585092994045684017991454684364208F /* log_e 10 */ #define NPY_PIf 3.141592653589793238462643383279502884F /* pi */ #define NPY_PI_2f 1.570796326794896619231321691639751442F /* pi/2 */ #define NPY_PI_4f 0.785398163397448309615660845819875721F /* pi/4 */ #define NPY_1_PIf 0.318309886183790671537767526745028724F /* 1/pi */ #define NPY_2_PIf 0.636619772367581343075535053490057448F /* 2/pi */ #define NPY_EULERf 0.577215664901532860606512090082402431F /* Euler constan*/ #define NPY_SQRT2f 1.414213562373095048801688724209698079F /* sqrt(2) */ #define NPY_SQRT1_2f 0.707106781186547524400844362104849039F /* 1/sqrt(2) */ #define NPY_El 2.718281828459045235360287471352662498L /* e */ #define NPY_LOG2El 1.442695040888963407359924681001892137L /* log_2 e */ #define NPY_LOG10El 0.434294481903251827651128918916605082L /* log_10 e */ #define NPY_LOGE2l 0.693147180559945309417232121458176568L /* log_e 2 */ #define NPY_LOGE10l 2.302585092994045684017991454684364208L /* log_e 10 */ #define NPY_PIl 3.141592653589793238462643383279502884L /* pi */ #define NPY_PI_2l 1.570796326794896619231321691639751442L /* pi/2 */ #define NPY_PI_4l 0.785398163397448309615660845819875721L /* pi/4 */ #define NPY_1_PIl 0.318309886183790671537767526745028724L /* 1/pi */ #define NPY_2_PIl 0.636619772367581343075535053490057448L /* 2/pi */ #define NPY_EULERl 0.577215664901532860606512090082402431L /* Euler constan*/ #define NPY_SQRT2l 1.414213562373095048801688724209698079L /* sqrt(2) */ #define NPY_SQRT1_2l 0.707106781186547524400844362104849039L /* 1/sqrt(2) */ /* * C99 double math funcs */ double npy_sin(double x); double npy_cos(double x); double npy_tan(double x); double npy_sinh(double x); double npy_cosh(double x); double npy_tanh(double x); double npy_asin(double x); double npy_acos(double x); double npy_atan(double x); double npy_aexp(double x); double npy_alog(double x); double npy_asqrt(double x); double npy_afabs(double x); double npy_log(double x); double npy_log10(double x); double npy_exp(double x); double npy_sqrt(double x); double npy_fabs(double x); double npy_ceil(double x); double npy_fmod(double x, double y); double npy_floor(double x); double npy_expm1(double x); double npy_log1p(double x); double npy_hypot(double x, double y); double npy_acosh(double x); double npy_asinh(double xx); double npy_atanh(double x); double npy_rint(double x); double npy_trunc(double x); double npy_exp2(double x); double npy_log2(double x); double npy_atan2(double x, double y); double npy_pow(double x, double y); double npy_modf(double x, double* y); double npy_copysign(double x, double y); double npy_nextafter(double x, double y); double npy_spacing(double x); /* * IEEE 754 fpu handling. Those are guaranteed to be macros */ /* use builtins to avoid function calls in tight loops * only available if npy_config.h is available (= numpys own build) */ #if HAVE___BUILTIN_ISNAN #define npy_isnan(x) __builtin_isnan(x) #else #ifndef NPY_HAVE_DECL_ISNAN #define npy_isnan(x) ((x) != (x)) #else #ifdef _MSC_VER #define npy_isnan(x) _isnan((x)) #else #define npy_isnan(x) isnan(x) #endif #endif #endif /* only available if npy_config.h is available (= numpys own build) */ #if HAVE___BUILTIN_ISFINITE #define npy_isfinite(x) __builtin_isfinite(x) #else #ifndef NPY_HAVE_DECL_ISFINITE #ifdef _MSC_VER #define npy_isfinite(x) _finite((x)) #else #define npy_isfinite(x) !npy_isnan((x) + (-x)) #endif #else #define npy_isfinite(x) isfinite((x)) #endif #endif /* only available if npy_config.h is available (= numpys own build) */ #if HAVE___BUILTIN_ISINF #define npy_isinf(x) __builtin_isinf(x) #else #ifndef NPY_HAVE_DECL_ISINF #define npy_isinf(x) (!npy_isfinite(x) && !npy_isnan(x)) #else #ifdef _MSC_VER #define npy_isinf(x) (!_finite((x)) && !_isnan((x))) #else #define npy_isinf(x) isinf((x)) #endif #endif #endif #ifndef NPY_HAVE_DECL_SIGNBIT int _npy_signbit_f(float x); int _npy_signbit_d(double x); int _npy_signbit_ld(long double x); #define npy_signbit(x) \ (sizeof (x) == sizeof (long double) ? _npy_signbit_ld (x) \ : sizeof (x) == sizeof (double) ? _npy_signbit_d (x) \ : _npy_signbit_f (x)) #else #define npy_signbit(x) signbit((x)) #endif /* * float C99 math functions */ float npy_sinf(float x); float npy_cosf(float x); float npy_tanf(float x); float npy_sinhf(float x); float npy_coshf(float x); float npy_tanhf(float x); float npy_fabsf(float x); float npy_floorf(float x); float npy_ceilf(float x); float npy_rintf(float x); float npy_truncf(float x); float npy_sqrtf(float x); float npy_log10f(float x); float npy_logf(float x); float npy_expf(float x); float npy_expm1f(float x); float npy_asinf(float x); float npy_acosf(float x); float npy_atanf(float x); float npy_asinhf(float x); float npy_acoshf(float x); float npy_atanhf(float x); float npy_log1pf(float x); float npy_exp2f(float x); float npy_log2f(float x); float npy_atan2f(float x, float y); float npy_hypotf(float x, float y); float npy_powf(float x, float y); float npy_fmodf(float x, float y); float npy_modff(float x, float* y); float npy_copysignf(float x, float y); float npy_nextafterf(float x, float y); float npy_spacingf(float x); /* * float C99 math functions */ npy_longdouble npy_sinl(npy_longdouble x); npy_longdouble npy_cosl(npy_longdouble x); npy_longdouble npy_tanl(npy_longdouble x); npy_longdouble npy_sinhl(npy_longdouble x); npy_longdouble npy_coshl(npy_longdouble x); npy_longdouble npy_tanhl(npy_longdouble x); npy_longdouble npy_fabsl(npy_longdouble x); npy_longdouble npy_floorl(npy_longdouble x); npy_longdouble npy_ceill(npy_longdouble x); npy_longdouble npy_rintl(npy_longdouble x); npy_longdouble npy_truncl(npy_longdouble x); npy_longdouble npy_sqrtl(npy_longdouble x); npy_longdouble npy_log10l(npy_longdouble x); npy_longdouble npy_logl(npy_longdouble x); npy_longdouble npy_expl(npy_longdouble x); npy_longdouble npy_expm1l(npy_longdouble x); npy_longdouble npy_asinl(npy_longdouble x); npy_longdouble npy_acosl(npy_longdouble x); npy_longdouble npy_atanl(npy_longdouble x); npy_longdouble npy_asinhl(npy_longdouble x); npy_longdouble npy_acoshl(npy_longdouble x); npy_longdouble npy_atanhl(npy_longdouble x); npy_longdouble npy_log1pl(npy_longdouble x); npy_longdouble npy_exp2l(npy_longdouble x); npy_longdouble npy_log2l(npy_longdouble x); npy_longdouble npy_atan2l(npy_longdouble x, npy_longdouble y); npy_longdouble npy_hypotl(npy_longdouble x, npy_longdouble y); npy_longdouble npy_powl(npy_longdouble x, npy_longdouble y); npy_longdouble npy_fmodl(npy_longdouble x, npy_longdouble y); npy_longdouble npy_modfl(npy_longdouble x, npy_longdouble* y); npy_longdouble npy_copysignl(npy_longdouble x, npy_longdouble y); npy_longdouble npy_nextafterl(npy_longdouble x, npy_longdouble y); npy_longdouble npy_spacingl(npy_longdouble x); /* * Non standard functions */ double npy_deg2rad(double x); double npy_rad2deg(double x); double npy_logaddexp(double x, double y); double npy_logaddexp2(double x, double y); float npy_deg2radf(float x); float npy_rad2degf(float x); float npy_logaddexpf(float x, float y); float npy_logaddexp2f(float x, float y); npy_longdouble npy_deg2radl(npy_longdouble x); npy_longdouble npy_rad2degl(npy_longdouble x); npy_longdouble npy_logaddexpl(npy_longdouble x, npy_longdouble y); npy_longdouble npy_logaddexp2l(npy_longdouble x, npy_longdouble y); #define npy_degrees npy_rad2deg #define npy_degreesf npy_rad2degf #define npy_degreesl npy_rad2degl #define npy_radians npy_deg2rad #define npy_radiansf npy_deg2radf #define npy_radiansl npy_deg2radl /* * Complex declarations */ /* * C99 specifies that complex numbers have the same representation as * an array of two elements, where the first element is the real part * and the second element is the imaginary part. */ #define __NPY_CPACK_IMP(x, y, type, ctype) \ union { \ ctype z; \ type a[2]; \ } z1;; \ \ z1.a[0] = (x); \ z1.a[1] = (y); \ \ return z1.z; static NPY_INLINE npy_cdouble npy_cpack(double x, double y) { __NPY_CPACK_IMP(x, y, double, npy_cdouble); } static NPY_INLINE npy_cfloat npy_cpackf(float x, float y) { __NPY_CPACK_IMP(x, y, float, npy_cfloat); } static NPY_INLINE npy_clongdouble npy_cpackl(npy_longdouble x, npy_longdouble y) { __NPY_CPACK_IMP(x, y, npy_longdouble, npy_clongdouble); } #undef __NPY_CPACK_IMP /* * Same remark as above, but in the other direction: extract first/second * member of complex number, assuming a C99-compatible representation * * Those are defineds as static inline, and such as a reasonable compiler would * most likely compile this to one or two instructions (on CISC at least) */ #define __NPY_CEXTRACT_IMP(z, index, type, ctype) \ union { \ ctype z; \ type a[2]; \ } __z_repr; \ __z_repr.z = z; \ \ return __z_repr.a[index]; static NPY_INLINE double npy_creal(npy_cdouble z) { __NPY_CEXTRACT_IMP(z, 0, double, npy_cdouble); } static NPY_INLINE double npy_cimag(npy_cdouble z) { __NPY_CEXTRACT_IMP(z, 1, double, npy_cdouble); } static NPY_INLINE float npy_crealf(npy_cfloat z) { __NPY_CEXTRACT_IMP(z, 0, float, npy_cfloat); } static NPY_INLINE float npy_cimagf(npy_cfloat z) { __NPY_CEXTRACT_IMP(z, 1, float, npy_cfloat); } static NPY_INLINE npy_longdouble npy_creall(npy_clongdouble z) { __NPY_CEXTRACT_IMP(z, 0, npy_longdouble, npy_clongdouble); } static NPY_INLINE npy_longdouble npy_cimagl(npy_clongdouble z) { __NPY_CEXTRACT_IMP(z, 1, npy_longdouble, npy_clongdouble); } #undef __NPY_CEXTRACT_IMP /* * Double precision complex functions */ double npy_cabs(npy_cdouble z); double npy_carg(npy_cdouble z); npy_cdouble npy_cexp(npy_cdouble z); npy_cdouble npy_clog(npy_cdouble z); npy_cdouble npy_cpow(npy_cdouble x, npy_cdouble y); npy_cdouble npy_csqrt(npy_cdouble z); npy_cdouble npy_ccos(npy_cdouble z); npy_cdouble npy_csin(npy_cdouble z); /* * Single precision complex functions */ float npy_cabsf(npy_cfloat z); float npy_cargf(npy_cfloat z); npy_cfloat npy_cexpf(npy_cfloat z); npy_cfloat npy_clogf(npy_cfloat z); npy_cfloat npy_cpowf(npy_cfloat x, npy_cfloat y); npy_cfloat npy_csqrtf(npy_cfloat z); npy_cfloat npy_ccosf(npy_cfloat z); npy_cfloat npy_csinf(npy_cfloat z); /* * Extended precision complex functions */ npy_longdouble npy_cabsl(npy_clongdouble z); npy_longdouble npy_cargl(npy_clongdouble z); npy_clongdouble npy_cexpl(npy_clongdouble z); npy_clongdouble npy_clogl(npy_clongdouble z); npy_clongdouble npy_cpowl(npy_clongdouble x, npy_clongdouble y); npy_clongdouble npy_csqrtl(npy_clongdouble z); npy_clongdouble npy_ccosl(npy_clongdouble z); npy_clongdouble npy_csinl(npy_clongdouble z); /* * Functions that set the floating point error * status word. */ void npy_set_floatstatus_divbyzero(void); void npy_set_floatstatus_overflow(void); void npy_set_floatstatus_underflow(void); void npy_set_floatstatus_invalid(void); #ifdef __cplusplus } #endif #endif numpy-1.8.2/numpy/core/include/numpy/utils.h0000664000175100017510000000116412370216242022231 0ustar vagrantvagrant00000000000000#ifndef __NUMPY_UTILS_HEADER__ #define __NUMPY_UTILS_HEADER__ #ifndef __COMP_NPY_UNUSED #if defined(__GNUC__) #define __COMP_NPY_UNUSED __attribute__ ((__unused__)) # elif defined(__ICC) #define __COMP_NPY_UNUSED __attribute__ ((__unused__)) #else #define __COMP_NPY_UNUSED #endif #endif /* Use this to tag a variable as not used. It will remove unused variable * warning on support platforms (see __COM_NPY_UNUSED) and mangle the variable * to avoid accidental use */ #define NPY_UNUSED(x) (__NPY_UNUSED_TAGGED ## x) __COMP_NPY_UNUSED #endif numpy-1.8.2/numpy/core/include/numpy/npy_no_deprecated_api.h0000664000175100017510000000106712370216242025406 0ustar vagrantvagrant00000000000000/* * This include file is provided for inclusion in Cython *.pyd files where * one would like to define the NPY_NO_DEPRECATED_API macro. It can be * included by * * cdef extern from "npy_no_deprecated_api.h": pass * */ #ifndef NPY_NO_DEPRECATED_API /* put this check here since there may be multiple includes in C extensions. */ #if defined(NDARRAYTYPES_H) || defined(_NPY_DEPRECATED_API_H) || \ defined(OLD_DEFINES_H) #error "npy_no_deprecated_api.h" must be first among numpy includes. #else #define NPY_NO_DEPRECATED_API NPY_API_VERSION #endif #endif numpy-1.8.2/numpy/core/include/numpy/oldnumeric.h0000664000175100017510000000125012370216242023226 0ustar vagrantvagrant00000000000000#include "arrayobject.h" #ifndef REFCOUNT # define REFCOUNT NPY_REFCOUNT # define MAX_ELSIZE 16 #endif #define PyArray_UNSIGNED_TYPES #define PyArray_SBYTE NPY_BYTE #define PyArray_CopyArray PyArray_CopyInto #define _PyArray_multiply_list PyArray_MultiplyIntList #define PyArray_ISSPACESAVER(m) NPY_FALSE #define PyScalarArray_Check PyArray_CheckScalar #define CONTIGUOUS NPY_CONTIGUOUS #define OWN_DIMENSIONS 0 #define OWN_STRIDES 0 #define OWN_DATA NPY_OWNDATA #define SAVESPACE 0 #define SAVESPACEBIT 0 #undef import_array #define import_array() { if (_import_array() < 0) {PyErr_Print(); PyErr_SetString(PyExc_ImportError, "numpy.core.multiarray failed to import"); } } numpy-1.8.2/numpy/core/include/numpy/halffloat.h0000664000175100017510000000342112370216242023027 0ustar vagrantvagrant00000000000000#ifndef __NPY_HALFFLOAT_H__ #define __NPY_HALFFLOAT_H__ #include #include #ifdef __cplusplus extern "C" { #endif /* * Half-precision routines */ /* Conversions */ float npy_half_to_float(npy_half h); double npy_half_to_double(npy_half h); npy_half npy_float_to_half(float f); npy_half npy_double_to_half(double d); /* Comparisons */ int npy_half_eq(npy_half h1, npy_half h2); int npy_half_ne(npy_half h1, npy_half h2); int npy_half_le(npy_half h1, npy_half h2); int npy_half_lt(npy_half h1, npy_half h2); int npy_half_ge(npy_half h1, npy_half h2); int npy_half_gt(npy_half h1, npy_half h2); /* faster *_nonan variants for when you know h1 and h2 are not NaN */ int npy_half_eq_nonan(npy_half h1, npy_half h2); int npy_half_lt_nonan(npy_half h1, npy_half h2); int npy_half_le_nonan(npy_half h1, npy_half h2); /* Miscellaneous functions */ int npy_half_iszero(npy_half h); int npy_half_isnan(npy_half h); int npy_half_isinf(npy_half h); int npy_half_isfinite(npy_half h); int npy_half_signbit(npy_half h); npy_half npy_half_copysign(npy_half x, npy_half y); npy_half npy_half_spacing(npy_half h); npy_half npy_half_nextafter(npy_half x, npy_half y); /* * Half-precision constants */ #define NPY_HALF_ZERO (0x0000u) #define NPY_HALF_PZERO (0x0000u) #define NPY_HALF_NZERO (0x8000u) #define NPY_HALF_ONE (0x3c00u) #define NPY_HALF_NEGONE (0xbc00u) #define NPY_HALF_PINF (0x7c00u) #define NPY_HALF_NINF (0xfc00u) #define NPY_HALF_NAN (0x7e00u) #define NPY_MAX_HALF (0x7bffu) /* * Bit-level conversions */ npy_uint16 npy_floatbits_to_halfbits(npy_uint32 f); npy_uint16 npy_doublebits_to_halfbits(npy_uint64 d); npy_uint32 npy_halfbits_to_floatbits(npy_uint16 h); npy_uint64 npy_halfbits_to_doublebits(npy_uint16 h); #ifdef __cplusplus } #endif #endif numpy-1.8.2/numpy/core/include/numpy/npy_interrupt.h0000664000175100017510000000655712370216242024026 0ustar vagrantvagrant00000000000000 /* Signal handling: This header file defines macros that allow your code to handle interrupts received during processing. Interrupts that could reasonably be handled: SIGINT, SIGABRT, SIGALRM, SIGSEGV ****Warning*************** Do not allow code that creates temporary memory or increases reference counts of Python objects to be interrupted unless you handle it differently. ************************** The mechanism for handling interrupts is conceptually simple: - replace the signal handler with our own home-grown version and store the old one. - run the code to be interrupted -- if an interrupt occurs the handler should basically just cause a return to the calling function for finish work. - restore the old signal handler Of course, every code that allows interrupts must account for returning via the interrupt and handle clean-up correctly. But, even still, the simple paradigm is complicated by at least three factors. 1) platform portability (i.e. Microsoft says not to use longjmp to return from signal handling. They have a __try and __except extension to C instead but what about mingw?). 2) how to handle threads: apparently whether signals are delivered to every thread of the process or the "invoking" thread is platform dependent. --- we don't handle threads for now. 3) do we need to worry about re-entrance. For now, assume the code will not call-back into itself. Ideas: 1) Start by implementing an approach that works on platforms that can use setjmp and longjmp functionality and does nothing on other platforms. 2) Ignore threads --- i.e. do not mix interrupt handling and threads 3) Add a default signal_handler function to the C-API but have the rest use macros. Simple Interface: In your C-extension: around a block of code you want to be interruptable with a SIGINT NPY_SIGINT_ON [code] NPY_SIGINT_OFF In order for this to work correctly, the [code] block must not allocate any memory or alter the reference count of any Python objects. In other words [code] must be interruptible so that continuation after NPY_SIGINT_OFF will only be "missing some computations" Interrupt handling does not work well with threads. */ /* Add signal handling macros Make the global variable and signal handler part of the C-API */ #ifndef NPY_INTERRUPT_H #define NPY_INTERRUPT_H #ifndef NPY_NO_SIGNAL #include #include #ifndef sigsetjmp #define NPY_SIGSETJMP(arg1, arg2) setjmp(arg1) #define NPY_SIGLONGJMP(arg1, arg2) longjmp(arg1, arg2) #define NPY_SIGJMP_BUF jmp_buf #else #define NPY_SIGSETJMP(arg1, arg2) sigsetjmp(arg1, arg2) #define NPY_SIGLONGJMP(arg1, arg2) siglongjmp(arg1, arg2) #define NPY_SIGJMP_BUF sigjmp_buf #endif # define NPY_SIGINT_ON { \ PyOS_sighandler_t _npy_sig_save; \ _npy_sig_save = PyOS_setsig(SIGINT, _PyArray_SigintHandler); \ if (NPY_SIGSETJMP(*((NPY_SIGJMP_BUF *)_PyArray_GetSigintBuf()), \ 1) == 0) { \ # define NPY_SIGINT_OFF } \ PyOS_setsig(SIGINT, _npy_sig_save); \ } #else /* NPY_NO_SIGNAL */ #define NPY_SIGINT_ON #define NPY_SIGINT_OFF #endif /* HAVE_SIGSETJMP */ #endif /* NPY_INTERRUPT_H */ numpy-1.8.2/numpy/core/include/numpy/arrayobject.h0000664000175100017510000000024412370216242023374 0ustar vagrantvagrant00000000000000#ifndef Py_ARRAYOBJECT_H #define Py_ARRAYOBJECT_H #include "ndarrayobject.h" #include "npy_interrupt.h" #ifdef NPY_NO_PREFIX #include "noprefix.h" #endif #endif numpy-1.8.2/numpy/core/include/numpy/numpyconfig.h0000664000175100017510000000163712370216243023435 0ustar vagrantvagrant00000000000000#ifndef _NPY_NUMPYCONFIG_H_ #define _NPY_NUMPYCONFIG_H_ #include "_numpyconfig.h" /* * On Mac OS X, because there is only one configuration stage for all the archs * in universal builds, any macro which depends on the arch needs to be * harcoded */ #ifdef __APPLE__ #undef NPY_SIZEOF_LONG #undef NPY_SIZEOF_PY_INTPTR_T #ifdef __LP64__ #define NPY_SIZEOF_LONG 8 #define NPY_SIZEOF_PY_INTPTR_T 8 #else #define NPY_SIZEOF_LONG 4 #define NPY_SIZEOF_PY_INTPTR_T 4 #endif #endif /** * To help with the NPY_NO_DEPRECATED_API macro, we include API version * numbers for specific versions of NumPy. To exclude all API that was * deprecated as of 1.7, add the following before #including any NumPy * headers: * #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION */ #define NPY_1_7_API_VERSION 0x00000007 #define NPY_1_8_API_VERSION 0x00000008 #endif numpy-1.8.2/numpy/core/include/numpy/arrayscalars.h0000664000175100017510000000666512370216242023573 0ustar vagrantvagrant00000000000000#ifndef _NPY_ARRAYSCALARS_H_ #define _NPY_ARRAYSCALARS_H_ #ifndef _MULTIARRAYMODULE typedef struct { PyObject_HEAD npy_bool obval; } PyBoolScalarObject; #endif typedef struct { PyObject_HEAD signed char obval; } PyByteScalarObject; typedef struct { PyObject_HEAD short obval; } PyShortScalarObject; typedef struct { PyObject_HEAD int obval; } PyIntScalarObject; typedef struct { PyObject_HEAD long obval; } PyLongScalarObject; typedef struct { PyObject_HEAD npy_longlong obval; } PyLongLongScalarObject; typedef struct { PyObject_HEAD unsigned char obval; } PyUByteScalarObject; typedef struct { PyObject_HEAD unsigned short obval; } PyUShortScalarObject; typedef struct { PyObject_HEAD unsigned int obval; } PyUIntScalarObject; typedef struct { PyObject_HEAD unsigned long obval; } PyULongScalarObject; typedef struct { PyObject_HEAD npy_ulonglong obval; } PyULongLongScalarObject; typedef struct { PyObject_HEAD npy_half obval; } PyHalfScalarObject; typedef struct { PyObject_HEAD float obval; } PyFloatScalarObject; typedef struct { PyObject_HEAD double obval; } PyDoubleScalarObject; typedef struct { PyObject_HEAD npy_longdouble obval; } PyLongDoubleScalarObject; typedef struct { PyObject_HEAD npy_cfloat obval; } PyCFloatScalarObject; typedef struct { PyObject_HEAD npy_cdouble obval; } PyCDoubleScalarObject; typedef struct { PyObject_HEAD npy_clongdouble obval; } PyCLongDoubleScalarObject; typedef struct { PyObject_HEAD PyObject * obval; } PyObjectScalarObject; typedef struct { PyObject_HEAD npy_datetime obval; PyArray_DatetimeMetaData obmeta; } PyDatetimeScalarObject; typedef struct { PyObject_HEAD npy_timedelta obval; PyArray_DatetimeMetaData obmeta; } PyTimedeltaScalarObject; typedef struct { PyObject_HEAD char obval; } PyScalarObject; #define PyStringScalarObject PyStringObject #define PyUnicodeScalarObject PyUnicodeObject typedef struct { PyObject_VAR_HEAD char *obval; PyArray_Descr *descr; int flags; PyObject *base; } PyVoidScalarObject; /* Macros PyScalarObject PyArrType_Type are defined in ndarrayobject.h */ #define PyArrayScalar_False ((PyObject *)(&(_PyArrayScalar_BoolValues[0]))) #define PyArrayScalar_True ((PyObject *)(&(_PyArrayScalar_BoolValues[1]))) #define PyArrayScalar_FromLong(i) \ ((PyObject *)(&(_PyArrayScalar_BoolValues[((i)!=0)]))) #define PyArrayScalar_RETURN_BOOL_FROM_LONG(i) \ return Py_INCREF(PyArrayScalar_FromLong(i)), \ PyArrayScalar_FromLong(i) #define PyArrayScalar_RETURN_FALSE \ return Py_INCREF(PyArrayScalar_False), \ PyArrayScalar_False #define PyArrayScalar_RETURN_TRUE \ return Py_INCREF(PyArrayScalar_True), \ PyArrayScalar_True #define PyArrayScalar_New(cls) \ Py##cls##ArrType_Type.tp_alloc(&Py##cls##ArrType_Type, 0) #define PyArrayScalar_VAL(obj, cls) \ ((Py##cls##ScalarObject *)obj)->obval #define PyArrayScalar_ASSIGN(obj, cls, val) \ PyArrayScalar_VAL(obj, cls) = val #endif numpy-1.8.2/numpy/core/include/numpy/npy_os.h0000664000175100017510000000146112370216242022400 0ustar vagrantvagrant00000000000000#ifndef _NPY_OS_H_ #define _NPY_OS_H_ #if defined(linux) || defined(__linux) || defined(__linux__) #define NPY_OS_LINUX #elif defined(__FreeBSD__) || defined(__NetBSD__) || \ defined(__OpenBSD__) || defined(__DragonFly__) #define NPY_OS_BSD #ifdef __FreeBSD__ #define NPY_OS_FREEBSD #elif defined(__NetBSD__) #define NPY_OS_NETBSD #elif defined(__OpenBSD__) #define NPY_OS_OPENBSD #elif defined(__DragonFly__) #define NPY_OS_DRAGONFLY #endif #elif defined(sun) || defined(__sun) #define NPY_OS_SOLARIS #elif defined(__CYGWIN__) #define NPY_OS_CYGWIN #elif defined(_WIN32) || defined(__WIN32__) || defined(WIN32) #define NPY_OS_WIN32 #elif defined(__APPLE__) #define NPY_OS_DARWIN #else #define NPY_OS_UNKNOWN #endif #endif numpy-1.8.2/numpy/core/include/numpy/ndarraytypes.h0000664000175100017510000017124612370216243023630 0ustar vagrantvagrant00000000000000#ifndef NDARRAYTYPES_H #define NDARRAYTYPES_H #include "npy_common.h" #include "npy_endian.h" #include "npy_cpu.h" #include "utils.h" #ifdef NPY_ENABLE_SEPARATE_COMPILATION #define NPY_NO_EXPORT NPY_VISIBILITY_HIDDEN #else #define NPY_NO_EXPORT static #endif /* Only use thread if configured in config and python supports it */ #if defined WITH_THREAD && !NPY_NO_SMP #define NPY_ALLOW_THREADS 1 #else #define NPY_ALLOW_THREADS 0 #endif /* * There are several places in the code where an array of dimensions * is allocated statically. This is the size of that static * allocation. * * The array creation itself could have arbitrary dimensions but all * the places where static allocation is used would need to be changed * to dynamic (including inside of several structures) */ #define NPY_MAXDIMS 32 #define NPY_MAXARGS 32 /* Used for Converter Functions "O&" code in ParseTuple */ #define NPY_FAIL 0 #define NPY_SUCCEED 1 /* * Binary compatibility version number. This number is increased * whenever the C-API is changed such that binary compatibility is * broken, i.e. whenever a recompile of extension modules is needed. */ #define NPY_VERSION NPY_ABI_VERSION /* * Minor API version. This number is increased whenever a change is * made to the C-API -- whether it breaks binary compatibility or not. * Some changes, such as adding a function pointer to the end of the * function table, can be made without breaking binary compatibility. * In this case, only the NPY_FEATURE_VERSION (*not* NPY_VERSION) * would be increased. Whenever binary compatibility is broken, both * NPY_VERSION and NPY_FEATURE_VERSION should be increased. */ #define NPY_FEATURE_VERSION NPY_API_VERSION enum NPY_TYPES { NPY_BOOL=0, NPY_BYTE, NPY_UBYTE, NPY_SHORT, NPY_USHORT, NPY_INT, NPY_UINT, NPY_LONG, NPY_ULONG, NPY_LONGLONG, NPY_ULONGLONG, NPY_FLOAT, NPY_DOUBLE, NPY_LONGDOUBLE, NPY_CFLOAT, NPY_CDOUBLE, NPY_CLONGDOUBLE, NPY_OBJECT=17, NPY_STRING, NPY_UNICODE, NPY_VOID, /* * New 1.6 types appended, may be integrated * into the above in 2.0. */ NPY_DATETIME, NPY_TIMEDELTA, NPY_HALF, NPY_NTYPES, NPY_NOTYPE, NPY_CHAR, /* special flag */ NPY_USERDEF=256, /* leave room for characters */ /* The number of types not including the new 1.6 types */ NPY_NTYPES_ABI_COMPATIBLE=21 }; /* basetype array priority */ #define NPY_PRIORITY 0.0 /* default subtype priority */ #define NPY_SUBTYPE_PRIORITY 1.0 /* default scalar priority */ #define NPY_SCALAR_PRIORITY -1000000.0 /* How many floating point types are there (excluding half) */ #define NPY_NUM_FLOATTYPE 3 /* * These characters correspond to the array type and the struct * module */ enum NPY_TYPECHAR { NPY_BOOLLTR = '?', NPY_BYTELTR = 'b', NPY_UBYTELTR = 'B', NPY_SHORTLTR = 'h', NPY_USHORTLTR = 'H', NPY_INTLTR = 'i', NPY_UINTLTR = 'I', NPY_LONGLTR = 'l', NPY_ULONGLTR = 'L', NPY_LONGLONGLTR = 'q', NPY_ULONGLONGLTR = 'Q', NPY_HALFLTR = 'e', NPY_FLOATLTR = 'f', NPY_DOUBLELTR = 'd', NPY_LONGDOUBLELTR = 'g', NPY_CFLOATLTR = 'F', NPY_CDOUBLELTR = 'D', NPY_CLONGDOUBLELTR = 'G', NPY_OBJECTLTR = 'O', NPY_STRINGLTR = 'S', NPY_STRINGLTR2 = 'a', NPY_UNICODELTR = 'U', NPY_VOIDLTR = 'V', NPY_DATETIMELTR = 'M', NPY_TIMEDELTALTR = 'm', NPY_CHARLTR = 'c', /* * No Descriptor, just a define -- this let's * Python users specify an array of integers * large enough to hold a pointer on the * platform */ NPY_INTPLTR = 'p', NPY_UINTPLTR = 'P', /* * These are for dtype 'kinds', not dtype 'typecodes' * as the above are for. */ NPY_GENBOOLLTR ='b', NPY_SIGNEDLTR = 'i', NPY_UNSIGNEDLTR = 'u', NPY_FLOATINGLTR = 'f', NPY_COMPLEXLTR = 'c' }; typedef enum { NPY_QUICKSORT=0, NPY_HEAPSORT=1, NPY_MERGESORT=2 } NPY_SORTKIND; #define NPY_NSORTS (NPY_MERGESORT + 1) typedef enum { NPY_INTROSELECT=0, } NPY_SELECTKIND; #define NPY_NSELECTS (NPY_INTROSELECT + 1) typedef enum { NPY_SEARCHLEFT=0, NPY_SEARCHRIGHT=1 } NPY_SEARCHSIDE; #define NPY_NSEARCHSIDES (NPY_SEARCHRIGHT + 1) typedef enum { NPY_NOSCALAR=-1, NPY_BOOL_SCALAR, NPY_INTPOS_SCALAR, NPY_INTNEG_SCALAR, NPY_FLOAT_SCALAR, NPY_COMPLEX_SCALAR, NPY_OBJECT_SCALAR } NPY_SCALARKIND; #define NPY_NSCALARKINDS (NPY_OBJECT_SCALAR + 1) /* For specifying array memory layout or iteration order */ typedef enum { /* Fortran order if inputs are all Fortran, C otherwise */ NPY_ANYORDER=-1, /* C order */ NPY_CORDER=0, /* Fortran order */ NPY_FORTRANORDER=1, /* An order as close to the inputs as possible */ NPY_KEEPORDER=2 } NPY_ORDER; /* For specifying allowed casting in operations which support it */ typedef enum { /* Only allow identical types */ NPY_NO_CASTING=0, /* Allow identical and byte swapped types */ NPY_EQUIV_CASTING=1, /* Only allow safe casts */ NPY_SAFE_CASTING=2, /* Allow safe casts or casts within the same kind */ NPY_SAME_KIND_CASTING=3, /* Allow any casts */ NPY_UNSAFE_CASTING=4, /* * Temporary internal definition only, will be removed in upcoming * release, see below * */ NPY_INTERNAL_UNSAFE_CASTING_BUT_WARN_UNLESS_SAME_KIND = 100, } NPY_CASTING; typedef enum { NPY_CLIP=0, NPY_WRAP=1, NPY_RAISE=2 } NPY_CLIPMODE; /* The special not-a-time (NaT) value */ #define NPY_DATETIME_NAT NPY_MIN_INT64 /* * Upper bound on the length of a DATETIME ISO 8601 string * YEAR: 21 (64-bit year) * MONTH: 3 * DAY: 3 * HOURS: 3 * MINUTES: 3 * SECONDS: 3 * ATTOSECONDS: 1 + 3*6 * TIMEZONE: 5 * NULL TERMINATOR: 1 */ #define NPY_DATETIME_MAX_ISO8601_STRLEN (21+3*5+1+3*6+6+1) typedef enum { NPY_FR_Y = 0, /* Years */ NPY_FR_M = 1, /* Months */ NPY_FR_W = 2, /* Weeks */ /* Gap where 1.6 NPY_FR_B (value 3) was */ NPY_FR_D = 4, /* Days */ NPY_FR_h = 5, /* hours */ NPY_FR_m = 6, /* minutes */ NPY_FR_s = 7, /* seconds */ NPY_FR_ms = 8, /* milliseconds */ NPY_FR_us = 9, /* microseconds */ NPY_FR_ns = 10,/* nanoseconds */ NPY_FR_ps = 11,/* picoseconds */ NPY_FR_fs = 12,/* femtoseconds */ NPY_FR_as = 13,/* attoseconds */ NPY_FR_GENERIC = 14 /* Generic, unbound units, can convert to anything */ } NPY_DATETIMEUNIT; /* * NOTE: With the NPY_FR_B gap for 1.6 ABI compatibility, NPY_DATETIME_NUMUNITS * is technically one more than the actual number of units. */ #define NPY_DATETIME_NUMUNITS (NPY_FR_GENERIC + 1) #define NPY_DATETIME_DEFAULTUNIT NPY_FR_GENERIC /* * Business day conventions for mapping invalid business * days to valid business days. */ typedef enum { /* Go forward in time to the following business day. */ NPY_BUSDAY_FORWARD, NPY_BUSDAY_FOLLOWING = NPY_BUSDAY_FORWARD, /* Go backward in time to the preceding business day. */ NPY_BUSDAY_BACKWARD, NPY_BUSDAY_PRECEDING = NPY_BUSDAY_BACKWARD, /* * Go forward in time to the following business day, unless it * crosses a month boundary, in which case go backward */ NPY_BUSDAY_MODIFIEDFOLLOWING, /* * Go backward in time to the preceding business day, unless it * crosses a month boundary, in which case go forward. */ NPY_BUSDAY_MODIFIEDPRECEDING, /* Produce a NaT for non-business days. */ NPY_BUSDAY_NAT, /* Raise an exception for non-business days. */ NPY_BUSDAY_RAISE } NPY_BUSDAY_ROLL; /************************************************************ * NumPy Auxiliary Data for inner loops, sort functions, etc. ************************************************************/ /* * When creating an auxiliary data struct, this should always appear * as the first member, like this: * * typedef struct { * NpyAuxData base; * double constant; * } constant_multiplier_aux_data; */ typedef struct NpyAuxData_tag NpyAuxData; /* Function pointers for freeing or cloning auxiliary data */ typedef void (NpyAuxData_FreeFunc) (NpyAuxData *); typedef NpyAuxData *(NpyAuxData_CloneFunc) (NpyAuxData *); struct NpyAuxData_tag { NpyAuxData_FreeFunc *free; NpyAuxData_CloneFunc *clone; /* To allow for a bit of expansion without breaking the ABI */ void *reserved[2]; }; /* Macros to use for freeing and cloning auxiliary data */ #define NPY_AUXDATA_FREE(auxdata) \ do { \ if ((auxdata) != NULL) { \ (auxdata)->free(auxdata); \ } \ } while(0) #define NPY_AUXDATA_CLONE(auxdata) \ ((auxdata)->clone(auxdata)) #define NPY_ERR(str) fprintf(stderr, #str); fflush(stderr); #define NPY_ERR2(str) fprintf(stderr, str); fflush(stderr); #define NPY_STRINGIFY(x) #x #define NPY_TOSTRING(x) NPY_STRINGIFY(x) /* * Macros to define how array, and dimension/strides data is * allocated. */ /* Data buffer - PyDataMem_NEW/FREE/RENEW are in multiarraymodule.c */ #define NPY_USE_PYMEM 1 #if NPY_USE_PYMEM == 1 #define PyArray_malloc PyMem_Malloc #define PyArray_free PyMem_Free #define PyArray_realloc PyMem_Realloc #else #define PyArray_malloc malloc #define PyArray_free free #define PyArray_realloc realloc #endif /* Dimensions and strides */ #define PyDimMem_NEW(size) \ ((npy_intp *)PyArray_malloc(size*sizeof(npy_intp))) #define PyDimMem_FREE(ptr) PyArray_free(ptr) #define PyDimMem_RENEW(ptr,size) \ ((npy_intp *)PyArray_realloc(ptr,size*sizeof(npy_intp))) /* forward declaration */ struct _PyArray_Descr; /* These must deal with unaligned and swapped data if necessary */ typedef PyObject * (PyArray_GetItemFunc) (void *, void *); typedef int (PyArray_SetItemFunc)(PyObject *, void *, void *); typedef void (PyArray_CopySwapNFunc)(void *, npy_intp, void *, npy_intp, npy_intp, int, void *); typedef void (PyArray_CopySwapFunc)(void *, void *, int, void *); typedef npy_bool (PyArray_NonzeroFunc)(void *, void *); /* * These assume aligned and notswapped data -- a buffer will be used * before or contiguous data will be obtained */ typedef int (PyArray_CompareFunc)(const void *, const void *, void *); typedef int (PyArray_ArgFunc)(void*, npy_intp, npy_intp*, void *); typedef void (PyArray_DotFunc)(void *, npy_intp, void *, npy_intp, void *, npy_intp, void *); typedef void (PyArray_VectorUnaryFunc)(void *, void *, npy_intp, void *, void *); /* * XXX the ignore argument should be removed next time the API version * is bumped. It used to be the separator. */ typedef int (PyArray_ScanFunc)(FILE *fp, void *dptr, char *ignore, struct _PyArray_Descr *); typedef int (PyArray_FromStrFunc)(char *s, void *dptr, char **endptr, struct _PyArray_Descr *); typedef int (PyArray_FillFunc)(void *, npy_intp, void *); typedef int (PyArray_SortFunc)(void *, npy_intp, void *); typedef int (PyArray_ArgSortFunc)(void *, npy_intp *, npy_intp, void *); typedef int (PyArray_PartitionFunc)(void *, npy_intp, npy_intp, npy_intp *, npy_intp *, void *); typedef int (PyArray_ArgPartitionFunc)(void *, npy_intp *, npy_intp, npy_intp, npy_intp *, npy_intp *, void *); typedef int (PyArray_FillWithScalarFunc)(void *, npy_intp, void *, void *); typedef int (PyArray_ScalarKindFunc)(void *); typedef void (PyArray_FastClipFunc)(void *in, npy_intp n_in, void *min, void *max, void *out); typedef void (PyArray_FastPutmaskFunc)(void *in, void *mask, npy_intp n_in, void *values, npy_intp nv); typedef int (PyArray_FastTakeFunc)(void *dest, void *src, npy_intp *indarray, npy_intp nindarray, npy_intp n_outer, npy_intp m_middle, npy_intp nelem, NPY_CLIPMODE clipmode); typedef struct { npy_intp *ptr; int len; } PyArray_Dims; typedef struct { /* * Functions to cast to most other standard types * Can have some NULL entries. The types * DATETIME, TIMEDELTA, and HALF go into the castdict * even though they are built-in. */ PyArray_VectorUnaryFunc *cast[NPY_NTYPES_ABI_COMPATIBLE]; /* The next four functions *cannot* be NULL */ /* * Functions to get and set items with standard Python types * -- not array scalars */ PyArray_GetItemFunc *getitem; PyArray_SetItemFunc *setitem; /* * Copy and/or swap data. Memory areas may not overlap * Use memmove first if they might */ PyArray_CopySwapNFunc *copyswapn; PyArray_CopySwapFunc *copyswap; /* * Function to compare items * Can be NULL */ PyArray_CompareFunc *compare; /* * Function to select largest * Can be NULL */ PyArray_ArgFunc *argmax; /* * Function to compute dot product * Can be NULL */ PyArray_DotFunc *dotfunc; /* * Function to scan an ASCII file and * place a single value plus possible separator * Can be NULL */ PyArray_ScanFunc *scanfunc; /* * Function to read a single value from a string * and adjust the pointer; Can be NULL */ PyArray_FromStrFunc *fromstr; /* * Function to determine if data is zero or not * If NULL a default version is * used at Registration time. */ PyArray_NonzeroFunc *nonzero; /* * Used for arange. * Can be NULL. */ PyArray_FillFunc *fill; /* * Function to fill arrays with scalar values * Can be NULL */ PyArray_FillWithScalarFunc *fillwithscalar; /* * Sorting functions * Can be NULL */ PyArray_SortFunc *sort[NPY_NSORTS]; PyArray_ArgSortFunc *argsort[NPY_NSORTS]; /* * Dictionary of additional casting functions * PyArray_VectorUnaryFuncs * which can be populated to support casting * to other registered types. Can be NULL */ PyObject *castdict; /* * Functions useful for generalizing * the casting rules. * Can be NULL; */ PyArray_ScalarKindFunc *scalarkind; int **cancastscalarkindto; int *cancastto; PyArray_FastClipFunc *fastclip; PyArray_FastPutmaskFunc *fastputmask; PyArray_FastTakeFunc *fasttake; /* * Function to select smallest * Can be NULL */ PyArray_ArgFunc *argmin; } PyArray_ArrFuncs; /* The item must be reference counted when it is inserted or extracted. */ #define NPY_ITEM_REFCOUNT 0x01 /* Same as needing REFCOUNT */ #define NPY_ITEM_HASOBJECT 0x01 /* Convert to list for pickling */ #define NPY_LIST_PICKLE 0x02 /* The item is a POINTER */ #define NPY_ITEM_IS_POINTER 0x04 /* memory needs to be initialized for this data-type */ #define NPY_NEEDS_INIT 0x08 /* operations need Python C-API so don't give-up thread. */ #define NPY_NEEDS_PYAPI 0x10 /* Use f.getitem when extracting elements of this data-type */ #define NPY_USE_GETITEM 0x20 /* Use f.setitem when setting creating 0-d array from this data-type.*/ #define NPY_USE_SETITEM 0x40 /* A sticky flag specifically for structured arrays */ #define NPY_ALIGNED_STRUCT 0x80 /* *These are inherited for global data-type if any data-types in the * field have them */ #define NPY_FROM_FIELDS (NPY_NEEDS_INIT | NPY_LIST_PICKLE | \ NPY_ITEM_REFCOUNT | NPY_NEEDS_PYAPI) #define NPY_OBJECT_DTYPE_FLAGS (NPY_LIST_PICKLE | NPY_USE_GETITEM | \ NPY_ITEM_IS_POINTER | NPY_ITEM_REFCOUNT | \ NPY_NEEDS_INIT | NPY_NEEDS_PYAPI) #define PyDataType_FLAGCHK(dtype, flag) \ (((dtype)->flags & (flag)) == (flag)) #define PyDataType_REFCHK(dtype) \ PyDataType_FLAGCHK(dtype, NPY_ITEM_REFCOUNT) typedef struct _PyArray_Descr { PyObject_HEAD /* * the type object representing an * instance of this type -- should not * be two type_numbers with the same type * object. */ PyTypeObject *typeobj; /* kind for this type */ char kind; /* unique-character representing this type */ char type; /* * '>' (big), '<' (little), '|' * (not-applicable), or '=' (native). */ char byteorder; /* flags describing data type */ char flags; /* number representing this type */ int type_num; /* element size (itemsize) for this type */ int elsize; /* alignment needed for this type */ int alignment; /* * Non-NULL if this type is * is an array (C-contiguous) * of some other type */ struct _arr_descr *subarray; /* * The fields dictionary for this type * For statically defined descr this * is always Py_None */ PyObject *fields; /* * An ordered tuple of field names or NULL * if no fields are defined */ PyObject *names; /* * a table of functions specific for each * basic data descriptor */ PyArray_ArrFuncs *f; /* Metadata about this dtype */ PyObject *metadata; /* * Metadata specific to the C implementation * of the particular dtype. This was added * for NumPy 1.7.0. */ NpyAuxData *c_metadata; } PyArray_Descr; typedef struct _arr_descr { PyArray_Descr *base; PyObject *shape; /* a tuple */ } PyArray_ArrayDescr; /* * The main array object structure. * * It has been recommended to use the inline functions defined below * (PyArray_DATA and friends) to access fields here for a number of * releases. Direct access to the members themselves is deprecated. * To ensure that your code does not use deprecated access, * #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION * (or NPY_1_8_API_VERSION or higher as required). */ /* This struct will be moved to a private header in a future release */ typedef struct tagPyArrayObject_fields { PyObject_HEAD /* Pointer to the raw data buffer */ char *data; /* The number of dimensions, also called 'ndim' */ int nd; /* The size in each dimension, also called 'shape' */ npy_intp *dimensions; /* * Number of bytes to jump to get to the * next element in each dimension */ npy_intp *strides; /* * This object is decref'd upon * deletion of array. Except in the * case of UPDATEIFCOPY which has * special handling. * * For views it points to the original * array, collapsed so no chains of * views occur. * * For creation from buffer object it * points to an object that shold be * decref'd on deletion * * For UPDATEIFCOPY flag this is an * array to-be-updated upon deletion * of this one */ PyObject *base; /* Pointer to type structure */ PyArray_Descr *descr; /* Flags describing array -- see below */ int flags; /* For weak references */ PyObject *weakreflist; } PyArrayObject_fields; /* * To hide the implementation details, we only expose * the Python struct HEAD. */ #if !defined(NPY_NO_DEPRECATED_API) || \ (NPY_NO_DEPRECATED_API < NPY_1_7_API_VERSION) /* * Can't put this in npy_deprecated_api.h like the others. * PyArrayObject field access is deprecated as of NumPy 1.7. */ typedef PyArrayObject_fields PyArrayObject; #else typedef struct tagPyArrayObject { PyObject_HEAD } PyArrayObject; #endif #define NPY_SIZEOF_PYARRAYOBJECT (sizeof(PyArrayObject_fields)) /* Array Flags Object */ typedef struct PyArrayFlagsObject { PyObject_HEAD PyObject *arr; int flags; } PyArrayFlagsObject; /* Mirrors buffer object to ptr */ typedef struct { PyObject_HEAD PyObject *base; void *ptr; npy_intp len; int flags; } PyArray_Chunk; typedef struct { NPY_DATETIMEUNIT base; int num; } PyArray_DatetimeMetaData; typedef struct { NpyAuxData base; PyArray_DatetimeMetaData meta; } PyArray_DatetimeDTypeMetaData; /* * This structure contains an exploded view of a date-time value. * NaT is represented by year == NPY_DATETIME_NAT. */ typedef struct { npy_int64 year; npy_int32 month, day, hour, min, sec, us, ps, as; } npy_datetimestruct; /* This is not used internally. */ typedef struct { npy_int64 day; npy_int32 sec, us, ps, as; } npy_timedeltastruct; typedef int (PyArray_FinalizeFunc)(PyArrayObject *, PyObject *); /* * Means c-style contiguous (last index varies the fastest). The data * elements right after each other. * * This flag may be requested in constructor functions. * This flag may be tested for in PyArray_FLAGS(arr). */ #define NPY_ARRAY_C_CONTIGUOUS 0x0001 /* * Set if array is a contiguous Fortran array: the first index varies * the fastest in memory (strides array is reverse of C-contiguous * array) * * This flag may be requested in constructor functions. * This flag may be tested for in PyArray_FLAGS(arr). */ #define NPY_ARRAY_F_CONTIGUOUS 0x0002 /* * Note: all 0-d arrays are C_CONTIGUOUS and F_CONTIGUOUS. If a * 1-d array is C_CONTIGUOUS it is also F_CONTIGUOUS. Arrays with * more then one dimension can be C_CONTIGUOUS and F_CONTIGUOUS * at the same time if they have either zero or one element. * If NPY_RELAXED_STRIDES_CHECKING is set, a higher dimensional * array is always C_CONTIGUOUS and F_CONTIGUOUS if it has zero elements * and the array is contiguous if ndarray.squeeze() is contiguous. * I.e. dimensions for which `ndarray.shape[dimension] == 1` are * ignored. */ /* * If set, the array owns the data: it will be free'd when the array * is deleted. * * This flag may be tested for in PyArray_FLAGS(arr). */ #define NPY_ARRAY_OWNDATA 0x0004 /* * An array never has the next four set; they're only used as parameter * flags to the the various FromAny functions * * This flag may be requested in constructor functions. */ /* Cause a cast to occur regardless of whether or not it is safe. */ #define NPY_ARRAY_FORCECAST 0x0010 /* * Always copy the array. Returned arrays are always CONTIGUOUS, * ALIGNED, and WRITEABLE. * * This flag may be requested in constructor functions. */ #define NPY_ARRAY_ENSURECOPY 0x0020 /* * Make sure the returned array is a base-class ndarray * * This flag may be requested in constructor functions. */ #define NPY_ARRAY_ENSUREARRAY 0x0040 /* * Make sure that the strides are in units of the element size Needed * for some operations with record-arrays. * * This flag may be requested in constructor functions. */ #define NPY_ARRAY_ELEMENTSTRIDES 0x0080 /* * Array data is aligned on the appropiate memory address for the type * stored according to how the compiler would align things (e.g., an * array of integers (4 bytes each) starts on a memory address that's * a multiple of 4) * * This flag may be requested in constructor functions. * This flag may be tested for in PyArray_FLAGS(arr). */ #define NPY_ARRAY_ALIGNED 0x0100 /* * Array data has the native endianness * * This flag may be requested in constructor functions. */ #define NPY_ARRAY_NOTSWAPPED 0x0200 /* * Array data is writeable * * This flag may be requested in constructor functions. * This flag may be tested for in PyArray_FLAGS(arr). */ #define NPY_ARRAY_WRITEABLE 0x0400 /* * If this flag is set, then base contains a pointer to an array of * the same size that should be updated with the current contents of * this array when this array is deallocated * * This flag may be requested in constructor functions. * This flag may be tested for in PyArray_FLAGS(arr). */ #define NPY_ARRAY_UPDATEIFCOPY 0x1000 /* * NOTE: there are also internal flags defined in multiarray/arrayobject.h, * which start at bit 31 and work down. */ #define NPY_ARRAY_BEHAVED (NPY_ARRAY_ALIGNED | \ NPY_ARRAY_WRITEABLE) #define NPY_ARRAY_BEHAVED_NS (NPY_ARRAY_ALIGNED | \ NPY_ARRAY_WRITEABLE | \ NPY_ARRAY_NOTSWAPPED) #define NPY_ARRAY_CARRAY (NPY_ARRAY_C_CONTIGUOUS | \ NPY_ARRAY_BEHAVED) #define NPY_ARRAY_CARRAY_RO (NPY_ARRAY_C_CONTIGUOUS | \ NPY_ARRAY_ALIGNED) #define NPY_ARRAY_FARRAY (NPY_ARRAY_F_CONTIGUOUS | \ NPY_ARRAY_BEHAVED) #define NPY_ARRAY_FARRAY_RO (NPY_ARRAY_F_CONTIGUOUS | \ NPY_ARRAY_ALIGNED) #define NPY_ARRAY_DEFAULT (NPY_ARRAY_CARRAY) #define NPY_ARRAY_IN_ARRAY (NPY_ARRAY_CARRAY_RO) #define NPY_ARRAY_OUT_ARRAY (NPY_ARRAY_CARRAY) #define NPY_ARRAY_INOUT_ARRAY (NPY_ARRAY_CARRAY | \ NPY_ARRAY_UPDATEIFCOPY) #define NPY_ARRAY_IN_FARRAY (NPY_ARRAY_FARRAY_RO) #define NPY_ARRAY_OUT_FARRAY (NPY_ARRAY_FARRAY) #define NPY_ARRAY_INOUT_FARRAY (NPY_ARRAY_FARRAY | \ NPY_ARRAY_UPDATEIFCOPY) #define NPY_ARRAY_UPDATE_ALL (NPY_ARRAY_C_CONTIGUOUS | \ NPY_ARRAY_F_CONTIGUOUS | \ NPY_ARRAY_ALIGNED) /* This flag is for the array interface, not PyArrayObject */ #define NPY_ARR_HAS_DESCR 0x0800 /* * Size of internal buffers used for alignment Make BUFSIZE a multiple * of sizeof(npy_cdouble) -- usually 16 so that ufunc buffers are aligned */ #define NPY_MIN_BUFSIZE ((int)sizeof(npy_cdouble)) #define NPY_MAX_BUFSIZE (((int)sizeof(npy_cdouble))*1000000) #define NPY_BUFSIZE 8192 /* buffer stress test size: */ /*#define NPY_BUFSIZE 17*/ #define PyArray_MAX(a,b) (((a)>(b))?(a):(b)) #define PyArray_MIN(a,b) (((a)<(b))?(a):(b)) #define PyArray_CLT(p,q) ((((p).real==(q).real) ? ((p).imag < (q).imag) : \ ((p).real < (q).real))) #define PyArray_CGT(p,q) ((((p).real==(q).real) ? ((p).imag > (q).imag) : \ ((p).real > (q).real))) #define PyArray_CLE(p,q) ((((p).real==(q).real) ? ((p).imag <= (q).imag) : \ ((p).real <= (q).real))) #define PyArray_CGE(p,q) ((((p).real==(q).real) ? ((p).imag >= (q).imag) : \ ((p).real >= (q).real))) #define PyArray_CEQ(p,q) (((p).real==(q).real) && ((p).imag == (q).imag)) #define PyArray_CNE(p,q) (((p).real!=(q).real) || ((p).imag != (q).imag)) /* * C API: consists of Macros and functions. The MACROS are defined * here. */ #define PyArray_ISCONTIGUOUS(m) PyArray_CHKFLAGS(m, NPY_ARRAY_C_CONTIGUOUS) #define PyArray_ISWRITEABLE(m) PyArray_CHKFLAGS(m, NPY_ARRAY_WRITEABLE) #define PyArray_ISALIGNED(m) PyArray_CHKFLAGS(m, NPY_ARRAY_ALIGNED) #define PyArray_IS_C_CONTIGUOUS(m) PyArray_CHKFLAGS(m, NPY_ARRAY_C_CONTIGUOUS) #define PyArray_IS_F_CONTIGUOUS(m) PyArray_CHKFLAGS(m, NPY_ARRAY_F_CONTIGUOUS) #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_BEGIN_THREADS_THRESHOLDED(loop_size) do { if (loop_size > 500) \ { _save = PyEval_SaveThread();} } while (0); #define NPY_BEGIN_THREADS_DESCR(dtype) \ do {if (!(PyDataType_FLAGCHK(dtype, NPY_NEEDS_PYAPI))) \ NPY_BEGIN_THREADS;} while (0); #define NPY_END_THREADS_DESCR(dtype) \ do {if (!(PyDataType_FLAGCHK(dtype, NPY_NEEDS_PYAPI))) \ NPY_END_THREADS; } while (0); #define NPY_ALLOW_C_API_DEF PyGILState_STATE __save__; #define NPY_ALLOW_C_API do {__save__ = PyGILState_Ensure();} while (0); #define NPY_DISABLE_C_API do {PyGILState_Release(__save__);} while (0); #else #define NPY_BEGIN_ALLOW_THREADS #define NPY_END_ALLOW_THREADS #define NPY_BEGIN_THREADS_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 #define NPY_ALLOW_C_API #define NPY_DISABLE_C_API #endif /********************************** * The nditer object, added in 1.6 **********************************/ /* The actual structure of the iterator is an internal detail */ typedef struct NpyIter_InternalOnly NpyIter; /* Iterator function pointers that may be specialized */ typedef int (NpyIter_IterNextFunc)(NpyIter *iter); typedef void (NpyIter_GetMultiIndexFunc)(NpyIter *iter, npy_intp *outcoords); /*** Global flags that may be passed to the iterator constructors ***/ /* Track an index representing C order */ #define NPY_ITER_C_INDEX 0x00000001 /* Track an index representing Fortran order */ #define NPY_ITER_F_INDEX 0x00000002 /* Track a multi-index */ #define NPY_ITER_MULTI_INDEX 0x00000004 /* User code external to the iterator does the 1-dimensional innermost loop */ #define NPY_ITER_EXTERNAL_LOOP 0x00000008 /* Convert all the operands to a common data type */ #define NPY_ITER_COMMON_DTYPE 0x00000010 /* Operands may hold references, requiring API access during iteration */ #define NPY_ITER_REFS_OK 0x00000020 /* Zero-sized operands should be permitted, iteration checks IterSize for 0 */ #define NPY_ITER_ZEROSIZE_OK 0x00000040 /* Permits reductions (size-0 stride with dimension size > 1) */ #define NPY_ITER_REDUCE_OK 0x00000080 /* Enables sub-range iteration */ #define NPY_ITER_RANGED 0x00000100 /* Enables buffering */ #define NPY_ITER_BUFFERED 0x00000200 /* When buffering is enabled, grows the inner loop if possible */ #define NPY_ITER_GROWINNER 0x00000400 /* Delay allocation of buffers until first Reset* call */ #define NPY_ITER_DELAY_BUFALLOC 0x00000800 /* When NPY_KEEPORDER is specified, disable reversing negative-stride axes */ #define NPY_ITER_DONT_NEGATE_STRIDES 0x00001000 /*** Per-operand flags that may be passed to the iterator constructors ***/ /* The operand will be read from and written to */ #define NPY_ITER_READWRITE 0x00010000 /* The operand will only be read from */ #define NPY_ITER_READONLY 0x00020000 /* The operand will only be written to */ #define NPY_ITER_WRITEONLY 0x00040000 /* The operand's data must be in native byte order */ #define NPY_ITER_NBO 0x00080000 /* The operand's data must be aligned */ #define NPY_ITER_ALIGNED 0x00100000 /* The operand's data must be contiguous (within the inner loop) */ #define NPY_ITER_CONTIG 0x00200000 /* The operand may be copied to satisfy requirements */ #define NPY_ITER_COPY 0x00400000 /* The operand may be copied with UPDATEIFCOPY to satisfy requirements */ #define NPY_ITER_UPDATEIFCOPY 0x00800000 /* Allocate the operand if it is NULL */ #define NPY_ITER_ALLOCATE 0x01000000 /* If an operand is allocated, don't use any subtype */ #define NPY_ITER_NO_SUBTYPE 0x02000000 /* This is a virtual array slot, operand is NULL but temporary data is there */ #define NPY_ITER_VIRTUAL 0x04000000 /* Require that the dimension match the iterator dimensions exactly */ #define NPY_ITER_NO_BROADCAST 0x08000000 /* A mask is being used on this array, affects buffer -> array copy */ #define NPY_ITER_WRITEMASKED 0x10000000 /* This array is the mask for all WRITEMASKED operands */ #define NPY_ITER_ARRAYMASK 0x20000000 #define NPY_ITER_GLOBAL_FLAGS 0x0000ffff #define NPY_ITER_PER_OP_FLAGS 0xffff0000 /***************************** * Basic iterator object *****************************/ /* FWD declaration */ typedef struct PyArrayIterObject_tag PyArrayIterObject; /* * type of the function which translates a set of coordinates to a * pointer to the data */ typedef char* (*npy_iter_get_dataptr_t)(PyArrayIterObject* iter, npy_intp*); struct PyArrayIterObject_tag { PyObject_HEAD int nd_m1; /* number of dimensions - 1 */ npy_intp index, size; npy_intp coordinates[NPY_MAXDIMS];/* N-dimensional loop */ npy_intp dims_m1[NPY_MAXDIMS]; /* ao->dimensions - 1 */ npy_intp strides[NPY_MAXDIMS]; /* ao->strides or fake */ npy_intp backstrides[NPY_MAXDIMS];/* how far to jump back */ npy_intp factors[NPY_MAXDIMS]; /* shape factors */ PyArrayObject *ao; char *dataptr; /* pointer to current item*/ npy_bool contiguous; npy_intp bounds[NPY_MAXDIMS][2]; npy_intp limits[NPY_MAXDIMS][2]; npy_intp limits_sizes[NPY_MAXDIMS]; npy_iter_get_dataptr_t translate; } ; /* Iterator API */ #define PyArrayIter_Check(op) PyObject_TypeCheck(op, &PyArrayIter_Type) #define _PyAIT(it) ((PyArrayIterObject *)(it)) #define PyArray_ITER_RESET(it) do { \ _PyAIT(it)->index = 0; \ _PyAIT(it)->dataptr = PyArray_BYTES(_PyAIT(it)->ao); \ memset(_PyAIT(it)->coordinates, 0, \ (_PyAIT(it)->nd_m1+1)*sizeof(npy_intp)); \ } while (0) #define _PyArray_ITER_NEXT1(it) do { \ (it)->dataptr += _PyAIT(it)->strides[0]; \ (it)->coordinates[0]++; \ } while (0) #define _PyArray_ITER_NEXT2(it) do { \ if ((it)->coordinates[1] < (it)->dims_m1[1]) { \ (it)->coordinates[1]++; \ (it)->dataptr += (it)->strides[1]; \ } \ else { \ (it)->coordinates[1] = 0; \ (it)->coordinates[0]++; \ (it)->dataptr += (it)->strides[0] - \ (it)->backstrides[1]; \ } \ } while (0) #define _PyArray_ITER_NEXT3(it) do { \ if ((it)->coordinates[2] < (it)->dims_m1[2]) { \ (it)->coordinates[2]++; \ (it)->dataptr += (it)->strides[2]; \ } \ else { \ (it)->coordinates[2] = 0; \ (it)->dataptr -= (it)->backstrides[2]; \ if ((it)->coordinates[1] < (it)->dims_m1[1]) { \ (it)->coordinates[1]++; \ (it)->dataptr += (it)->strides[1]; \ } \ else { \ (it)->coordinates[1] = 0; \ (it)->coordinates[0]++; \ (it)->dataptr += (it)->strides[0] \ (it)->backstrides[1]; \ } \ } \ } while (0) #define PyArray_ITER_NEXT(it) do { \ _PyAIT(it)->index++; \ if (_PyAIT(it)->nd_m1 == 0) { \ _PyArray_ITER_NEXT1(_PyAIT(it)); \ } \ else if (_PyAIT(it)->contiguous) \ _PyAIT(it)->dataptr += PyArray_DESCR(_PyAIT(it)->ao)->elsize; \ else if (_PyAIT(it)->nd_m1 == 1) { \ _PyArray_ITER_NEXT2(_PyAIT(it)); \ } \ else { \ int __npy_i; \ for (__npy_i=_PyAIT(it)->nd_m1; __npy_i >= 0; __npy_i--) { \ if (_PyAIT(it)->coordinates[__npy_i] < \ _PyAIT(it)->dims_m1[__npy_i]) { \ _PyAIT(it)->coordinates[__npy_i]++; \ _PyAIT(it)->dataptr += \ _PyAIT(it)->strides[__npy_i]; \ break; \ } \ else { \ _PyAIT(it)->coordinates[__npy_i] = 0; \ _PyAIT(it)->dataptr -= \ _PyAIT(it)->backstrides[__npy_i]; \ } \ } \ } \ } while (0) #define PyArray_ITER_GOTO(it, destination) do { \ int __npy_i; \ _PyAIT(it)->index = 0; \ _PyAIT(it)->dataptr = PyArray_BYTES(_PyAIT(it)->ao); \ for (__npy_i = _PyAIT(it)->nd_m1; __npy_i>=0; __npy_i--) { \ if (destination[__npy_i] < 0) { \ destination[__npy_i] += \ _PyAIT(it)->dims_m1[__npy_i]+1; \ } \ _PyAIT(it)->dataptr += destination[__npy_i] * \ _PyAIT(it)->strides[__npy_i]; \ _PyAIT(it)->coordinates[__npy_i] = \ destination[__npy_i]; \ _PyAIT(it)->index += destination[__npy_i] * \ ( __npy_i==_PyAIT(it)->nd_m1 ? 1 : \ _PyAIT(it)->dims_m1[__npy_i+1]+1) ; \ } \ } while (0) #define PyArray_ITER_GOTO1D(it, ind) do { \ int __npy_i; \ npy_intp __npy_ind = (npy_intp) (ind); \ if (__npy_ind < 0) __npy_ind += _PyAIT(it)->size; \ _PyAIT(it)->index = __npy_ind; \ if (_PyAIT(it)->nd_m1 == 0) { \ _PyAIT(it)->dataptr = PyArray_BYTES(_PyAIT(it)->ao) + \ __npy_ind * _PyAIT(it)->strides[0]; \ } \ else if (_PyAIT(it)->contiguous) \ _PyAIT(it)->dataptr = PyArray_BYTES(_PyAIT(it)->ao) + \ __npy_ind * PyArray_DESCR(_PyAIT(it)->ao)->elsize; \ else { \ _PyAIT(it)->dataptr = PyArray_BYTES(_PyAIT(it)->ao); \ for (__npy_i = 0; __npy_i<=_PyAIT(it)->nd_m1; \ __npy_i++) { \ _PyAIT(it)->dataptr += \ (__npy_ind / _PyAIT(it)->factors[__npy_i]) \ * _PyAIT(it)->strides[__npy_i]; \ __npy_ind %= _PyAIT(it)->factors[__npy_i]; \ } \ } \ } while (0) #define PyArray_ITER_DATA(it) ((void *)(_PyAIT(it)->dataptr)) #define PyArray_ITER_NOTDONE(it) (_PyAIT(it)->index < _PyAIT(it)->size) /* * Any object passed to PyArray_Broadcast must be binary compatible * with this structure. */ typedef struct { PyObject_HEAD int numiter; /* number of iters */ npy_intp size; /* broadcasted size */ npy_intp index; /* current index */ int nd; /* number of dims */ npy_intp dimensions[NPY_MAXDIMS]; /* dimensions */ PyArrayIterObject *iters[NPY_MAXARGS]; /* iterators */ } PyArrayMultiIterObject; #define _PyMIT(m) ((PyArrayMultiIterObject *)(m)) #define PyArray_MultiIter_RESET(multi) do { \ int __npy_mi; \ _PyMIT(multi)->index = 0; \ for (__npy_mi=0; __npy_mi < _PyMIT(multi)->numiter; __npy_mi++) { \ PyArray_ITER_RESET(_PyMIT(multi)->iters[__npy_mi]); \ } \ } while (0) #define PyArray_MultiIter_NEXT(multi) do { \ int __npy_mi; \ _PyMIT(multi)->index++; \ for (__npy_mi=0; __npy_mi < _PyMIT(multi)->numiter; __npy_mi++) { \ PyArray_ITER_NEXT(_PyMIT(multi)->iters[__npy_mi]); \ } \ } while (0) #define PyArray_MultiIter_GOTO(multi, dest) do { \ int __npy_mi; \ for (__npy_mi=0; __npy_mi < _PyMIT(multi)->numiter; __npy_mi++) { \ PyArray_ITER_GOTO(_PyMIT(multi)->iters[__npy_mi], dest); \ } \ _PyMIT(multi)->index = _PyMIT(multi)->iters[0]->index; \ } while (0) #define PyArray_MultiIter_GOTO1D(multi, ind) do { \ int __npy_mi; \ for (__npy_mi=0; __npy_mi < _PyMIT(multi)->numiter; __npy_mi++) { \ PyArray_ITER_GOTO1D(_PyMIT(multi)->iters[__npy_mi], ind); \ } \ _PyMIT(multi)->index = _PyMIT(multi)->iters[0]->index; \ } while (0) #define PyArray_MultiIter_DATA(multi, i) \ ((void *)(_PyMIT(multi)->iters[i]->dataptr)) #define PyArray_MultiIter_NEXTi(multi, i) \ PyArray_ITER_NEXT(_PyMIT(multi)->iters[i]) #define PyArray_MultiIter_NOTDONE(multi) \ (_PyMIT(multi)->index < _PyMIT(multi)->size) /* Store the information needed for fancy-indexing over an array */ typedef struct { PyObject_HEAD /* * Multi-iterator portion --- needs to be present in this * order to work with PyArray_Broadcast */ int numiter; /* number of index-array iterators */ npy_intp size; /* size of broadcasted result */ npy_intp index; /* current index */ int nd; /* number of dims */ npy_intp dimensions[NPY_MAXDIMS]; /* dimensions */ PyArrayIterObject *iters[NPY_MAXDIMS]; /* index object iterators */ PyArrayIterObject *ait; /* flat Iterator for underlying array */ /* flat iterator for subspace (when numiter < nd) */ PyArrayIterObject *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]; PyObject *indexobj; /* creating obj */ /* * consec is first used to indicate wether fancy indices are * consecutive and then denotes at which axis they are inserted */ int consec; char *dataptr; } PyArrayMapIterObject; enum { NPY_NEIGHBORHOOD_ITER_ZERO_PADDING, NPY_NEIGHBORHOOD_ITER_ONE_PADDING, NPY_NEIGHBORHOOD_ITER_CONSTANT_PADDING, NPY_NEIGHBORHOOD_ITER_CIRCULAR_PADDING, NPY_NEIGHBORHOOD_ITER_MIRROR_PADDING }; typedef struct { PyObject_HEAD /* * PyArrayIterObject part: keep this in this exact order */ int nd_m1; /* number of dimensions - 1 */ npy_intp index, size; npy_intp coordinates[NPY_MAXDIMS];/* N-dimensional loop */ npy_intp dims_m1[NPY_MAXDIMS]; /* ao->dimensions - 1 */ npy_intp strides[NPY_MAXDIMS]; /* ao->strides or fake */ npy_intp backstrides[NPY_MAXDIMS];/* how far to jump back */ npy_intp factors[NPY_MAXDIMS]; /* shape factors */ PyArrayObject *ao; char *dataptr; /* pointer to current item*/ npy_bool contiguous; npy_intp bounds[NPY_MAXDIMS][2]; npy_intp limits[NPY_MAXDIMS][2]; npy_intp limits_sizes[NPY_MAXDIMS]; npy_iter_get_dataptr_t translate; /* * New members */ npy_intp nd; /* Dimensions is the dimension of the array */ npy_intp dimensions[NPY_MAXDIMS]; /* * Neighborhood points coordinates are computed relatively to the * point pointed by _internal_iter */ PyArrayIterObject* _internal_iter; /* * To keep a reference to the representation of the constant value * for constant padding */ char* constant; int mode; } PyArrayNeighborhoodIterObject; /* * Neighborhood iterator API */ /* General: those work for any mode */ static NPY_INLINE int PyArrayNeighborhoodIter_Reset(PyArrayNeighborhoodIterObject* iter); static NPY_INLINE int PyArrayNeighborhoodIter_Next(PyArrayNeighborhoodIterObject* iter); #if 0 static NPY_INLINE int PyArrayNeighborhoodIter_Next2D(PyArrayNeighborhoodIterObject* iter); #endif /* * Include inline implementations - functions defined there are not * considered public API */ #define _NPY_INCLUDE_NEIGHBORHOOD_IMP #include "_neighborhood_iterator_imp.h" #undef _NPY_INCLUDE_NEIGHBORHOOD_IMP /* The default array type */ #define NPY_DEFAULT_TYPE NPY_DOUBLE /* * All sorts of useful ways to look into a PyArrayObject. It is recommended * to use PyArrayObject * objects instead of always casting from PyObject *, * for improved type checking. * * In many cases here the macro versions of the accessors are deprecated, * but can't be immediately changed to inline functions because the * preexisting macros accept PyObject * and do automatic casts. Inline * functions accepting PyArrayObject * provides for some compile-time * checking of correctness when working with these objects in C. */ #define PyArray_ISONESEGMENT(m) (PyArray_NDIM(m) == 0 || \ PyArray_CHKFLAGS(m, NPY_ARRAY_C_CONTIGUOUS) || \ PyArray_CHKFLAGS(m, NPY_ARRAY_F_CONTIGUOUS)) #define PyArray_ISFORTRAN(m) (PyArray_CHKFLAGS(m, NPY_ARRAY_F_CONTIGUOUS) && \ (!PyArray_CHKFLAGS(m, NPY_ARRAY_C_CONTIGUOUS))) #define PyArray_FORTRAN_IF(m) ((PyArray_CHKFLAGS(m, NPY_ARRAY_F_CONTIGUOUS) ? \ NPY_ARRAY_F_CONTIGUOUS : 0)) #if (defined(NPY_NO_DEPRECATED_API) && (NPY_1_7_API_VERSION <= NPY_NO_DEPRECATED_API)) /* * Changing access macros into functions, to allow for future hiding * of the internal memory layout. This later hiding will allow the 2.x series * to change the internal representation of arrays without affecting * ABI compatibility. */ static NPY_INLINE int PyArray_NDIM(const PyArrayObject *arr) { return ((PyArrayObject_fields *)arr)->nd; } static NPY_INLINE void * PyArray_DATA(PyArrayObject *arr) { return ((PyArrayObject_fields *)arr)->data; } static NPY_INLINE char * PyArray_BYTES(PyArrayObject *arr) { return ((PyArrayObject_fields *)arr)->data; } static NPY_INLINE npy_intp * PyArray_DIMS(PyArrayObject *arr) { return ((PyArrayObject_fields *)arr)->dimensions; } static NPY_INLINE npy_intp * PyArray_STRIDES(PyArrayObject *arr) { return ((PyArrayObject_fields *)arr)->strides; } static NPY_INLINE npy_intp PyArray_DIM(const PyArrayObject *arr, int idim) { return ((PyArrayObject_fields *)arr)->dimensions[idim]; } static NPY_INLINE npy_intp PyArray_STRIDE(const PyArrayObject *arr, int istride) { return ((PyArrayObject_fields *)arr)->strides[istride]; } static NPY_INLINE PyObject * PyArray_BASE(PyArrayObject *arr) { return ((PyArrayObject_fields *)arr)->base; } static NPY_INLINE PyArray_Descr * PyArray_DESCR(PyArrayObject *arr) { return ((PyArrayObject_fields *)arr)->descr; } static NPY_INLINE int PyArray_FLAGS(const PyArrayObject *arr) { return ((PyArrayObject_fields *)arr)->flags; } static NPY_INLINE npy_intp PyArray_ITEMSIZE(const PyArrayObject *arr) { return ((PyArrayObject_fields *)arr)->descr->elsize; } static NPY_INLINE int PyArray_TYPE(const PyArrayObject *arr) { return ((PyArrayObject_fields *)arr)->descr->type_num; } static NPY_INLINE int PyArray_CHKFLAGS(const PyArrayObject *arr, int flags) { return (PyArray_FLAGS(arr) & flags) == flags; } static NPY_INLINE PyObject * PyArray_GETITEM(const PyArrayObject *arr, const char *itemptr) { return ((PyArrayObject_fields *)arr)->descr->f->getitem( (void *)itemptr, (PyArrayObject *)arr); } static NPY_INLINE int PyArray_SETITEM(PyArrayObject *arr, char *itemptr, PyObject *v) { return ((PyArrayObject_fields *)arr)->descr->f->setitem( v, itemptr, arr); } #else /* These macros are deprecated as of NumPy 1.7. */ #define PyArray_NDIM(obj) (((PyArrayObject_fields *)(obj))->nd) #define PyArray_BYTES(obj) (((PyArrayObject_fields *)(obj))->data) #define PyArray_DATA(obj) ((void *)((PyArrayObject_fields *)(obj))->data) #define PyArray_DIMS(obj) (((PyArrayObject_fields *)(obj))->dimensions) #define PyArray_STRIDES(obj) (((PyArrayObject_fields *)(obj))->strides) #define PyArray_DIM(obj,n) (PyArray_DIMS(obj)[n]) #define PyArray_STRIDE(obj,n) (PyArray_STRIDES(obj)[n]) #define PyArray_BASE(obj) (((PyArrayObject_fields *)(obj))->base) #define PyArray_DESCR(obj) (((PyArrayObject_fields *)(obj))->descr) #define PyArray_FLAGS(obj) (((PyArrayObject_fields *)(obj))->flags) #define PyArray_CHKFLAGS(m, FLAGS) \ ((((PyArrayObject_fields *)(m))->flags & (FLAGS)) == (FLAGS)) #define PyArray_ITEMSIZE(obj) \ (((PyArrayObject_fields *)(obj))->descr->elsize) #define PyArray_TYPE(obj) \ (((PyArrayObject_fields *)(obj))->descr->type_num) #define PyArray_GETITEM(obj,itemptr) \ PyArray_DESCR(obj)->f->getitem((char *)(itemptr), \ (PyArrayObject *)(obj)) #define PyArray_SETITEM(obj,itemptr,v) \ PyArray_DESCR(obj)->f->setitem((PyObject *)(v), \ (char *)(itemptr), \ (PyArrayObject *)(obj)) #endif static NPY_INLINE PyArray_Descr * PyArray_DTYPE(PyArrayObject *arr) { return ((PyArrayObject_fields *)arr)->descr; } static NPY_INLINE npy_intp * PyArray_SHAPE(PyArrayObject *arr) { return ((PyArrayObject_fields *)arr)->dimensions; } /* * Enables the specified array flags. Does no checking, * assumes you know what you're doing. */ static NPY_INLINE void PyArray_ENABLEFLAGS(PyArrayObject *arr, int flags) { ((PyArrayObject_fields *)arr)->flags |= flags; } /* * Clears the specified array flags. Does no checking, * assumes you know what you're doing. */ static NPY_INLINE void PyArray_CLEARFLAGS(PyArrayObject *arr, int flags) { ((PyArrayObject_fields *)arr)->flags &= ~flags; } #define PyTypeNum_ISBOOL(type) ((type) == NPY_BOOL) #define PyTypeNum_ISUNSIGNED(type) (((type) == NPY_UBYTE) || \ ((type) == NPY_USHORT) || \ ((type) == NPY_UINT) || \ ((type) == NPY_ULONG) || \ ((type) == NPY_ULONGLONG)) #define PyTypeNum_ISSIGNED(type) (((type) == NPY_BYTE) || \ ((type) == NPY_SHORT) || \ ((type) == NPY_INT) || \ ((type) == NPY_LONG) || \ ((type) == NPY_LONGLONG)) #define PyTypeNum_ISINTEGER(type) (((type) >= NPY_BYTE) && \ ((type) <= NPY_ULONGLONG)) #define PyTypeNum_ISFLOAT(type) ((((type) >= NPY_FLOAT) && \ ((type) <= NPY_LONGDOUBLE)) || \ ((type) == NPY_HALF)) #define PyTypeNum_ISNUMBER(type) (((type) <= NPY_CLONGDOUBLE) || \ ((type) == NPY_HALF)) #define PyTypeNum_ISSTRING(type) (((type) == NPY_STRING) || \ ((type) == NPY_UNICODE)) #define PyTypeNum_ISCOMPLEX(type) (((type) >= NPY_CFLOAT) && \ ((type) <= NPY_CLONGDOUBLE)) #define PyTypeNum_ISPYTHON(type) (((type) == NPY_LONG) || \ ((type) == NPY_DOUBLE) || \ ((type) == NPY_CDOUBLE) || \ ((type) == NPY_BOOL) || \ ((type) == NPY_OBJECT )) #define PyTypeNum_ISFLEXIBLE(type) (((type) >=NPY_STRING) && \ ((type) <=NPY_VOID)) #define PyTypeNum_ISDATETIME(type) (((type) >=NPY_DATETIME) && \ ((type) <=NPY_TIMEDELTA)) #define PyTypeNum_ISUSERDEF(type) (((type) >= NPY_USERDEF) && \ ((type) < NPY_USERDEF+ \ NPY_NUMUSERTYPES)) #define PyTypeNum_ISEXTENDED(type) (PyTypeNum_ISFLEXIBLE(type) || \ PyTypeNum_ISUSERDEF(type)) #define PyTypeNum_ISOBJECT(type) ((type) == NPY_OBJECT) #define PyDataType_ISBOOL(obj) PyTypeNum_ISBOOL(_PyADt(obj)) #define PyDataType_ISUNSIGNED(obj) PyTypeNum_ISUNSIGNED(((PyArray_Descr*)(obj))->type_num) #define PyDataType_ISSIGNED(obj) PyTypeNum_ISSIGNED(((PyArray_Descr*)(obj))->type_num) #define PyDataType_ISINTEGER(obj) PyTypeNum_ISINTEGER(((PyArray_Descr*)(obj))->type_num ) #define PyDataType_ISFLOAT(obj) PyTypeNum_ISFLOAT(((PyArray_Descr*)(obj))->type_num) #define PyDataType_ISNUMBER(obj) PyTypeNum_ISNUMBER(((PyArray_Descr*)(obj))->type_num) #define PyDataType_ISSTRING(obj) PyTypeNum_ISSTRING(((PyArray_Descr*)(obj))->type_num) #define PyDataType_ISCOMPLEX(obj) PyTypeNum_ISCOMPLEX(((PyArray_Descr*)(obj))->type_num) #define PyDataType_ISPYTHON(obj) PyTypeNum_ISPYTHON(((PyArray_Descr*)(obj))->type_num) #define PyDataType_ISFLEXIBLE(obj) PyTypeNum_ISFLEXIBLE(((PyArray_Descr*)(obj))->type_num) #define PyDataType_ISDATETIME(obj) PyTypeNum_ISDATETIME(((PyArray_Descr*)(obj))->type_num) #define PyDataType_ISUSERDEF(obj) PyTypeNum_ISUSERDEF(((PyArray_Descr*)(obj))->type_num) #define PyDataType_ISEXTENDED(obj) PyTypeNum_ISEXTENDED(((PyArray_Descr*)(obj))->type_num) #define PyDataType_ISOBJECT(obj) PyTypeNum_ISOBJECT(((PyArray_Descr*)(obj))->type_num) #define PyDataType_HASFIELDS(obj) (((PyArray_Descr *)(obj))->names != NULL) #define PyDataType_HASSUBARRAY(dtype) ((dtype)->subarray != NULL) #define PyArray_ISBOOL(obj) PyTypeNum_ISBOOL(PyArray_TYPE(obj)) #define PyArray_ISUNSIGNED(obj) PyTypeNum_ISUNSIGNED(PyArray_TYPE(obj)) #define PyArray_ISSIGNED(obj) PyTypeNum_ISSIGNED(PyArray_TYPE(obj)) #define PyArray_ISINTEGER(obj) PyTypeNum_ISINTEGER(PyArray_TYPE(obj)) #define PyArray_ISFLOAT(obj) PyTypeNum_ISFLOAT(PyArray_TYPE(obj)) #define PyArray_ISNUMBER(obj) PyTypeNum_ISNUMBER(PyArray_TYPE(obj)) #define PyArray_ISSTRING(obj) PyTypeNum_ISSTRING(PyArray_TYPE(obj)) #define PyArray_ISCOMPLEX(obj) PyTypeNum_ISCOMPLEX(PyArray_TYPE(obj)) #define PyArray_ISPYTHON(obj) PyTypeNum_ISPYTHON(PyArray_TYPE(obj)) #define PyArray_ISFLEXIBLE(obj) PyTypeNum_ISFLEXIBLE(PyArray_TYPE(obj)) #define PyArray_ISDATETIME(obj) PyTypeNum_ISDATETIME(PyArray_TYPE(obj)) #define PyArray_ISUSERDEF(obj) PyTypeNum_ISUSERDEF(PyArray_TYPE(obj)) #define PyArray_ISEXTENDED(obj) PyTypeNum_ISEXTENDED(PyArray_TYPE(obj)) #define PyArray_ISOBJECT(obj) PyTypeNum_ISOBJECT(PyArray_TYPE(obj)) #define PyArray_HASFIELDS(obj) PyDataType_HASFIELDS(PyArray_DESCR(obj)) /* * FIXME: This should check for a flag on the data-type that * states whether or not it is variable length. Because the * ISFLEXIBLE check is hard-coded to the built-in data-types. */ #define PyArray_ISVARIABLE(obj) PyTypeNum_ISFLEXIBLE(PyArray_TYPE(obj)) #define PyArray_SAFEALIGNEDCOPY(obj) (PyArray_ISALIGNED(obj) && !PyArray_ISVARIABLE(obj)) #define NPY_LITTLE '<' #define NPY_BIG '>' #define NPY_NATIVE '=' #define NPY_SWAP 's' #define NPY_IGNORE '|' #if NPY_BYTE_ORDER == NPY_BIG_ENDIAN #define NPY_NATBYTE NPY_BIG #define NPY_OPPBYTE NPY_LITTLE #else #define NPY_NATBYTE NPY_LITTLE #define NPY_OPPBYTE NPY_BIG #endif #define PyArray_ISNBO(arg) ((arg) != NPY_OPPBYTE) #define PyArray_IsNativeByteOrder PyArray_ISNBO #define PyArray_ISNOTSWAPPED(m) PyArray_ISNBO(PyArray_DESCR(m)->byteorder) #define PyArray_ISBYTESWAPPED(m) (!PyArray_ISNOTSWAPPED(m)) #define PyArray_FLAGSWAP(m, flags) (PyArray_CHKFLAGS(m, flags) && \ PyArray_ISNOTSWAPPED(m)) #define PyArray_ISCARRAY(m) PyArray_FLAGSWAP(m, NPY_ARRAY_CARRAY) #define PyArray_ISCARRAY_RO(m) PyArray_FLAGSWAP(m, NPY_ARRAY_CARRAY_RO) #define PyArray_ISFARRAY(m) PyArray_FLAGSWAP(m, NPY_ARRAY_FARRAY) #define PyArray_ISFARRAY_RO(m) PyArray_FLAGSWAP(m, NPY_ARRAY_FARRAY_RO) #define PyArray_ISBEHAVED(m) PyArray_FLAGSWAP(m, NPY_ARRAY_BEHAVED) #define PyArray_ISBEHAVED_RO(m) PyArray_FLAGSWAP(m, NPY_ARRAY_ALIGNED) #define PyDataType_ISNOTSWAPPED(d) PyArray_ISNBO(((PyArray_Descr *)(d))->byteorder) #define PyDataType_ISBYTESWAPPED(d) (!PyDataType_ISNOTSWAPPED(d)) /************************************************************ * A struct used by PyArray_CreateSortedStridePerm, new in 1.7. ************************************************************/ typedef struct { npy_intp perm, stride; } npy_stride_sort_item; /************************************************************ * This is the form of the struct that's returned pointed by the * PyCObject attribute of an array __array_struct__. See * http://docs.scipy.org/doc/numpy/reference/arrays.interface.html for the full * documentation. ************************************************************/ typedef struct { int two; /* * contains the integer 2 as a sanity * check */ int nd; /* number of dimensions */ char typekind; /* * kind in array --- character code of * typestr */ int itemsize; /* size of each element */ int flags; /* * how should be data interpreted. Valid * flags are CONTIGUOUS (1), F_CONTIGUOUS (2), * ALIGNED (0x100), NOTSWAPPED (0x200), and * WRITEABLE (0x400). ARR_HAS_DESCR (0x800) * states that arrdescr field is present in * structure */ npy_intp *shape; /* * A length-nd array of shape * information */ npy_intp *strides; /* A length-nd array of stride information */ void *data; /* A pointer to the first element of the array */ PyObject *descr; /* * A list of fields or NULL (ignored if flags * does not have ARR_HAS_DESCR flag set) */ } PyArrayInterface; /* * This is a function for hooking into the PyDataMem_NEW/FREE/RENEW functions. * See the documentation for PyDataMem_SetEventHook. */ typedef void (PyDataMem_EventHookFunc)(void *inp, void *outp, size_t size, void *user_data); /* * Use the keyword NPY_DEPRECATED_INCLUDES to ensure that the header files * npy_*_*_deprecated_api.h are only included from here and nowhere else. */ #ifdef NPY_DEPRECATED_INCLUDES #error "Do not use the reserved keyword NPY_DEPRECATED_INCLUDES." #endif #define NPY_DEPRECATED_INCLUDES #if !defined(NPY_NO_DEPRECATED_API) || \ (NPY_NO_DEPRECATED_API < NPY_1_7_API_VERSION) #include "npy_1_7_deprecated_api.h" #endif /* * There is no file npy_1_8_deprecated_api.h since there are no additional * deprecated API features in NumPy 1.8. * * Note to maintainers: insert code like the following in future NumPy * versions. * * #if !defined(NPY_NO_DEPRECATED_API) || \ * (NPY_NO_DEPRECATED_API < NPY_1_9_API_VERSION) * #include "npy_1_9_deprecated_api.h" * #endif */ #undef NPY_DEPRECATED_INCLUDES #endif /* NPY_ARRAYTYPES_H */ numpy-1.8.2/numpy/core/include/numpy/noprefix.h0000664000175100017510000001506112370216242022724 0ustar vagrantvagrant00000000000000#ifndef NPY_NOPREFIX_H #define NPY_NOPREFIX_H /* * You can directly include noprefix.h as a backward * compatibility measure */ #ifndef NPY_NO_PREFIX #include "ndarrayobject.h" #include "npy_interrupt.h" #endif #define SIGSETJMP NPY_SIGSETJMP #define SIGLONGJMP NPY_SIGLONGJMP #define SIGJMP_BUF NPY_SIGJMP_BUF #define MAX_DIMS NPY_MAXDIMS #define longlong npy_longlong #define ulonglong npy_ulonglong #define Bool npy_bool #define longdouble npy_longdouble #define byte npy_byte #ifndef _BSD_SOURCE #define ushort npy_ushort #define uint npy_uint #define ulong npy_ulong #endif #define ubyte npy_ubyte #define ushort npy_ushort #define uint npy_uint #define ulong npy_ulong #define cfloat npy_cfloat #define cdouble npy_cdouble #define clongdouble npy_clongdouble #define Int8 npy_int8 #define UInt8 npy_uint8 #define Int16 npy_int16 #define UInt16 npy_uint16 #define Int32 npy_int32 #define UInt32 npy_uint32 #define Int64 npy_int64 #define UInt64 npy_uint64 #define Int128 npy_int128 #define UInt128 npy_uint128 #define Int256 npy_int256 #define UInt256 npy_uint256 #define Float16 npy_float16 #define Complex32 npy_complex32 #define Float32 npy_float32 #define Complex64 npy_complex64 #define Float64 npy_float64 #define Complex128 npy_complex128 #define Float80 npy_float80 #define Complex160 npy_complex160 #define Float96 npy_float96 #define Complex192 npy_complex192 #define Float128 npy_float128 #define Complex256 npy_complex256 #define intp npy_intp #define uintp npy_uintp #define datetime npy_datetime #define timedelta npy_timedelta #define SIZEOF_LONGLONG NPY_SIZEOF_LONGLONG #define SIZEOF_INTP NPY_SIZEOF_INTP #define SIZEOF_UINTP NPY_SIZEOF_UINTP #define SIZEOF_HALF NPY_SIZEOF_HALF #define SIZEOF_LONGDOUBLE NPY_SIZEOF_LONGDOUBLE #define SIZEOF_DATETIME NPY_SIZEOF_DATETIME #define SIZEOF_TIMEDELTA NPY_SIZEOF_TIMEDELTA #define LONGLONG_FMT NPY_LONGLONG_FMT #define ULONGLONG_FMT NPY_ULONGLONG_FMT #define LONGLONG_SUFFIX NPY_LONGLONG_SUFFIX #define ULONGLONG_SUFFIX NPY_ULONGLONG_SUFFIX #define MAX_INT8 127 #define MIN_INT8 -128 #define MAX_UINT8 255 #define MAX_INT16 32767 #define MIN_INT16 -32768 #define MAX_UINT16 65535 #define MAX_INT32 2147483647 #define MIN_INT32 (-MAX_INT32 - 1) #define MAX_UINT32 4294967295U #define MAX_INT64 LONGLONG_SUFFIX(9223372036854775807) #define MIN_INT64 (-MAX_INT64 - LONGLONG_SUFFIX(1)) #define MAX_UINT64 ULONGLONG_SUFFIX(18446744073709551615) #define MAX_INT128 LONGLONG_SUFFIX(85070591730234615865843651857942052864) #define MIN_INT128 (-MAX_INT128 - LONGLONG_SUFFIX(1)) #define MAX_UINT128 ULONGLONG_SUFFIX(170141183460469231731687303715884105728) #define MAX_INT256 LONGLONG_SUFFIX(57896044618658097711785492504343953926634992332820282019728792003956564819967) #define MIN_INT256 (-MAX_INT256 - LONGLONG_SUFFIX(1)) #define MAX_UINT256 ULONGLONG_SUFFIX(115792089237316195423570985008687907853269984665640564039457584007913129639935) #define MAX_BYTE NPY_MAX_BYTE #define MIN_BYTE NPY_MIN_BYTE #define MAX_UBYTE NPY_MAX_UBYTE #define MAX_SHORT NPY_MAX_SHORT #define MIN_SHORT NPY_MIN_SHORT #define MAX_USHORT NPY_MAX_USHORT #define MAX_INT NPY_MAX_INT #define MIN_INT NPY_MIN_INT #define MAX_UINT NPY_MAX_UINT #define MAX_LONG NPY_MAX_LONG #define MIN_LONG NPY_MIN_LONG #define MAX_ULONG NPY_MAX_ULONG #define MAX_LONGLONG NPY_MAX_LONGLONG #define MIN_LONGLONG NPY_MIN_LONGLONG #define MAX_ULONGLONG NPY_MAX_ULONGLONG #define MIN_DATETIME NPY_MIN_DATETIME #define MAX_DATETIME NPY_MAX_DATETIME #define MIN_TIMEDELTA NPY_MIN_TIMEDELTA #define MAX_TIMEDELTA NPY_MAX_TIMEDELTA #define BITSOF_BOOL NPY_BITSOF_BOOL #define BITSOF_CHAR NPY_BITSOF_CHAR #define BITSOF_SHORT NPY_BITSOF_SHORT #define BITSOF_INT NPY_BITSOF_INT #define BITSOF_LONG NPY_BITSOF_LONG #define BITSOF_LONGLONG NPY_BITSOF_LONGLONG #define BITSOF_HALF NPY_BITSOF_HALF #define BITSOF_FLOAT NPY_BITSOF_FLOAT #define BITSOF_DOUBLE NPY_BITSOF_DOUBLE #define BITSOF_LONGDOUBLE NPY_BITSOF_LONGDOUBLE #define BITSOF_DATETIME NPY_BITSOF_DATETIME #define BITSOF_TIMEDELTA NPY_BITSOF_TIMEDELTA #define _pya_malloc PyArray_malloc #define _pya_free PyArray_free #define _pya_realloc PyArray_realloc #define BEGIN_THREADS_DEF NPY_BEGIN_THREADS_DEF #define BEGIN_THREADS NPY_BEGIN_THREADS #define END_THREADS NPY_END_THREADS #define ALLOW_C_API_DEF NPY_ALLOW_C_API_DEF #define ALLOW_C_API NPY_ALLOW_C_API #define DISABLE_C_API NPY_DISABLE_C_API #define PY_FAIL NPY_FAIL #define PY_SUCCEED NPY_SUCCEED #ifndef TRUE #define TRUE NPY_TRUE #endif #ifndef FALSE #define FALSE NPY_FALSE #endif #define LONGDOUBLE_FMT NPY_LONGDOUBLE_FMT #define CONTIGUOUS NPY_CONTIGUOUS #define C_CONTIGUOUS NPY_C_CONTIGUOUS #define FORTRAN NPY_FORTRAN #define F_CONTIGUOUS NPY_F_CONTIGUOUS #define OWNDATA NPY_OWNDATA #define FORCECAST NPY_FORCECAST #define ENSURECOPY NPY_ENSURECOPY #define ENSUREARRAY NPY_ENSUREARRAY #define ELEMENTSTRIDES NPY_ELEMENTSTRIDES #define ALIGNED NPY_ALIGNED #define NOTSWAPPED NPY_NOTSWAPPED #define WRITEABLE NPY_WRITEABLE #define UPDATEIFCOPY NPY_UPDATEIFCOPY #define ARR_HAS_DESCR NPY_ARR_HAS_DESCR #define BEHAVED NPY_BEHAVED #define BEHAVED_NS NPY_BEHAVED_NS #define CARRAY NPY_CARRAY #define CARRAY_RO NPY_CARRAY_RO #define FARRAY NPY_FARRAY #define FARRAY_RO NPY_FARRAY_RO #define DEFAULT NPY_DEFAULT #define IN_ARRAY NPY_IN_ARRAY #define OUT_ARRAY NPY_OUT_ARRAY #define INOUT_ARRAY NPY_INOUT_ARRAY #define IN_FARRAY NPY_IN_FARRAY #define OUT_FARRAY NPY_OUT_FARRAY #define INOUT_FARRAY NPY_INOUT_FARRAY #define UPDATE_ALL NPY_UPDATE_ALL #define OWN_DATA NPY_OWNDATA #define BEHAVED_FLAGS NPY_BEHAVED #define BEHAVED_FLAGS_NS NPY_BEHAVED_NS #define CARRAY_FLAGS_RO NPY_CARRAY_RO #define CARRAY_FLAGS NPY_CARRAY #define FARRAY_FLAGS NPY_FARRAY #define FARRAY_FLAGS_RO NPY_FARRAY_RO #define DEFAULT_FLAGS NPY_DEFAULT #define UPDATE_ALL_FLAGS NPY_UPDATE_ALL_FLAGS #ifndef MIN #define MIN PyArray_MIN #endif #ifndef MAX #define MAX PyArray_MAX #endif #define MAX_INTP NPY_MAX_INTP #define MIN_INTP NPY_MIN_INTP #define MAX_UINTP NPY_MAX_UINTP #define INTP_FMT NPY_INTP_FMT #define REFCOUNT PyArray_REFCOUNT #define MAX_ELSIZE NPY_MAX_ELSIZE #endif numpy-1.8.2/numpy/core/include/numpy/ndarrayobject.h0000664000175100017510000002306512370216242023724 0ustar vagrantvagrant00000000000000/* * DON'T INCLUDE THIS DIRECTLY. */ #ifndef NPY_NDARRAYOBJECT_H #define NPY_NDARRAYOBJECT_H #ifdef __cplusplus #define CONFUSE_EMACS { #define CONFUSE_EMACS2 } extern "C" CONFUSE_EMACS #undef CONFUSE_EMACS #undef CONFUSE_EMACS2 /* ... otherwise a semi-smart identer (like emacs) tries to indent everything when you're typing */ #endif #include "ndarraytypes.h" /* Includes the "function" C-API -- these are all stored in a list of pointers --- one for each file The two lists are concatenated into one in multiarray. They are available as import_array() */ #include "__multiarray_api.h" /* C-API that requries previous API to be defined */ #define PyArray_DescrCheck(op) (((PyObject*)(op))->ob_type==&PyArrayDescr_Type) #define PyArray_Check(op) PyObject_TypeCheck(op, &PyArray_Type) #define PyArray_CheckExact(op) (((PyObject*)(op))->ob_type == &PyArray_Type) #define PyArray_HasArrayInterfaceType(op, type, context, out) \ ((((out)=PyArray_FromStructInterface(op)) != Py_NotImplemented) || \ (((out)=PyArray_FromInterface(op)) != Py_NotImplemented) || \ (((out)=PyArray_FromArrayAttr(op, type, context)) != \ Py_NotImplemented)) #define PyArray_HasArrayInterface(op, out) \ PyArray_HasArrayInterfaceType(op, NULL, NULL, out) #define PyArray_IsZeroDim(op) (PyArray_Check(op) && \ (PyArray_NDIM((PyArrayObject *)op) == 0)) #define PyArray_IsScalar(obj, cls) \ (PyObject_TypeCheck(obj, &Py##cls##ArrType_Type)) #define PyArray_CheckScalar(m) (PyArray_IsScalar(m, Generic) || \ PyArray_IsZeroDim(m)) #define PyArray_IsPythonNumber(obj) \ (PyInt_Check(obj) || PyFloat_Check(obj) || PyComplex_Check(obj) || \ PyLong_Check(obj) || PyBool_Check(obj)) #define PyArray_IsPythonScalar(obj) \ (PyArray_IsPythonNumber(obj) || PyString_Check(obj) || \ PyUnicode_Check(obj)) #define PyArray_IsAnyScalar(obj) \ (PyArray_IsScalar(obj, Generic) || PyArray_IsPythonScalar(obj)) #define PyArray_CheckAnyScalar(obj) (PyArray_IsPythonScalar(obj) || \ PyArray_CheckScalar(obj)) #define PyArray_IsIntegerScalar(obj) (PyInt_Check(obj) \ || PyLong_Check(obj) \ || PyArray_IsScalar((obj), Integer)) #define PyArray_GETCONTIGUOUS(m) (PyArray_ISCONTIGUOUS(m) ? \ Py_INCREF(m), (m) : \ (PyArrayObject *)(PyArray_Copy(m))) #define PyArray_SAMESHAPE(a1,a2) ((PyArray_NDIM(a1) == PyArray_NDIM(a2)) && \ PyArray_CompareLists(PyArray_DIMS(a1), \ PyArray_DIMS(a2), \ PyArray_NDIM(a1))) #define PyArray_SIZE(m) PyArray_MultiplyList(PyArray_DIMS(m), PyArray_NDIM(m)) #define PyArray_NBYTES(m) (PyArray_ITEMSIZE(m) * PyArray_SIZE(m)) #define PyArray_FROM_O(m) PyArray_FromAny(m, NULL, 0, 0, 0, NULL) #define PyArray_FROM_OF(m,flags) PyArray_CheckFromAny(m, NULL, 0, 0, flags, \ NULL) #define PyArray_FROM_OT(m,type) PyArray_FromAny(m, \ PyArray_DescrFromType(type), 0, 0, 0, NULL); #define PyArray_FROM_OTF(m, type, flags) \ PyArray_FromAny(m, PyArray_DescrFromType(type), 0, 0, \ (((flags) & NPY_ARRAY_ENSURECOPY) ? \ ((flags) | NPY_ARRAY_DEFAULT) : (flags)), NULL) #define PyArray_FROMANY(m, type, min, max, flags) \ PyArray_FromAny(m, PyArray_DescrFromType(type), min, max, \ (((flags) & NPY_ARRAY_ENSURECOPY) ? \ (flags) | NPY_ARRAY_DEFAULT : (flags)), NULL) #define PyArray_ZEROS(m, dims, type, is_f_order) \ PyArray_Zeros(m, dims, PyArray_DescrFromType(type), is_f_order) #define PyArray_EMPTY(m, dims, type, is_f_order) \ PyArray_Empty(m, dims, PyArray_DescrFromType(type), is_f_order) #define PyArray_FILLWBYTE(obj, val) memset(PyArray_DATA(obj), val, \ PyArray_NBYTES(obj)) #define PyArray_REFCOUNT(obj) (((PyObject *)(obj))->ob_refcnt) #define NPY_REFCOUNT PyArray_REFCOUNT #define NPY_MAX_ELSIZE (2 * NPY_SIZEOF_LONGDOUBLE) #define PyArray_ContiguousFromAny(op, type, min_depth, max_depth) \ PyArray_FromAny(op, PyArray_DescrFromType(type), min_depth, \ max_depth, NPY_ARRAY_DEFAULT, NULL) #define PyArray_EquivArrTypes(a1, a2) \ PyArray_EquivTypes(PyArray_DESCR(a1), PyArray_DESCR(a2)) #define PyArray_EquivByteorders(b1, b2) \ (((b1) == (b2)) || (PyArray_ISNBO(b1) == PyArray_ISNBO(b2))) #define PyArray_SimpleNew(nd, dims, typenum) \ PyArray_New(&PyArray_Type, nd, dims, typenum, NULL, NULL, 0, 0, NULL) #define PyArray_SimpleNewFromData(nd, dims, typenum, data) \ PyArray_New(&PyArray_Type, nd, dims, typenum, NULL, \ data, 0, NPY_ARRAY_CARRAY, NULL) #define PyArray_SimpleNewFromDescr(nd, dims, descr) \ PyArray_NewFromDescr(&PyArray_Type, descr, nd, dims, \ NULL, NULL, 0, NULL) #define PyArray_ToScalar(data, arr) \ PyArray_Scalar(data, PyArray_DESCR(arr), (PyObject *)arr) /* These might be faster without the dereferencing of obj going on inside -- of course an optimizing compiler should inline the constants inside a for loop making it a moot point */ #define PyArray_GETPTR1(obj, i) ((void *)(PyArray_BYTES(obj) + \ (i)*PyArray_STRIDES(obj)[0])) #define PyArray_GETPTR2(obj, i, j) ((void *)(PyArray_BYTES(obj) + \ (i)*PyArray_STRIDES(obj)[0] + \ (j)*PyArray_STRIDES(obj)[1])) #define PyArray_GETPTR3(obj, i, j, k) ((void *)(PyArray_BYTES(obj) + \ (i)*PyArray_STRIDES(obj)[0] + \ (j)*PyArray_STRIDES(obj)[1] + \ (k)*PyArray_STRIDES(obj)[2])) #define PyArray_GETPTR4(obj, i, j, k, l) ((void *)(PyArray_BYTES(obj) + \ (i)*PyArray_STRIDES(obj)[0] + \ (j)*PyArray_STRIDES(obj)[1] + \ (k)*PyArray_STRIDES(obj)[2] + \ (l)*PyArray_STRIDES(obj)[3])) static NPY_INLINE void PyArray_XDECREF_ERR(PyArrayObject *arr) { if (arr != NULL) { if (PyArray_FLAGS(arr) & NPY_ARRAY_UPDATEIFCOPY) { PyArrayObject *base = (PyArrayObject *)PyArray_BASE(arr); PyArray_ENABLEFLAGS(base, NPY_ARRAY_WRITEABLE); PyArray_CLEARFLAGS(arr, NPY_ARRAY_UPDATEIFCOPY); } Py_DECREF(arr); } } #define PyArray_DESCR_REPLACE(descr) do { \ PyArray_Descr *_new_; \ _new_ = PyArray_DescrNew(descr); \ Py_XDECREF(descr); \ descr = _new_; \ } while(0) /* Copy should always return contiguous array */ #define PyArray_Copy(obj) PyArray_NewCopy(obj, NPY_CORDER) #define PyArray_FromObject(op, type, min_depth, max_depth) \ PyArray_FromAny(op, PyArray_DescrFromType(type), min_depth, \ max_depth, NPY_ARRAY_BEHAVED | \ NPY_ARRAY_ENSUREARRAY, NULL) #define PyArray_ContiguousFromObject(op, type, min_depth, max_depth) \ PyArray_FromAny(op, PyArray_DescrFromType(type), min_depth, \ max_depth, NPY_ARRAY_DEFAULT | \ NPY_ARRAY_ENSUREARRAY, NULL) #define PyArray_CopyFromObject(op, type, min_depth, max_depth) \ PyArray_FromAny(op, PyArray_DescrFromType(type), min_depth, \ max_depth, NPY_ARRAY_ENSURECOPY | \ NPY_ARRAY_DEFAULT | \ NPY_ARRAY_ENSUREARRAY, NULL) #define PyArray_Cast(mp, type_num) \ PyArray_CastToType(mp, PyArray_DescrFromType(type_num), 0) #define PyArray_Take(ap, items, axis) \ PyArray_TakeFrom(ap, items, axis, NULL, NPY_RAISE) #define PyArray_Put(ap, items, values) \ PyArray_PutTo(ap, items, values, NPY_RAISE) /* Compatibility with old Numeric stuff -- don't use in new code */ #define PyArray_FromDimsAndData(nd, d, type, data) \ PyArray_FromDimsAndDataAndDescr(nd, d, PyArray_DescrFromType(type), \ data) /* Check to see if this key in the dictionary is the "title" entry of the tuple (i.e. a duplicate dictionary entry in the fields dict. */ #define NPY_TITLE_KEY(key, value) ((PyTuple_GET_SIZE((value))==3) && \ (PyTuple_GET_ITEM((value), 2) == (key))) #define DEPRECATE(msg) PyErr_WarnEx(PyExc_DeprecationWarning,msg,1) #define DEPRECATE_FUTUREWARNING(msg) PyErr_WarnEx(PyExc_FutureWarning,msg,1) #ifdef __cplusplus } #endif #endif /* NPY_NDARRAYOBJECT_H */ numpy-1.8.2/numpy/core/include/numpy/_numpyconfig.h.in0000664000175100017510000000312712370216243024175 0ustar vagrantvagrant00000000000000#ifndef _NPY_NUMPYCONFIG_H_ #error this header should not be included directly, always include numpyconfig.h instead #endif #define NPY_SIZEOF_SHORT @SIZEOF_SHORT@ #define NPY_SIZEOF_INT @SIZEOF_INT@ #define NPY_SIZEOF_LONG @SIZEOF_LONG@ #define NPY_SIZEOF_FLOAT @SIZEOF_FLOAT@ #define NPY_SIZEOF_DOUBLE @SIZEOF_DOUBLE@ #define NPY_SIZEOF_LONGDOUBLE @SIZEOF_LONG_DOUBLE@ #define NPY_SIZEOF_PY_INTPTR_T @SIZEOF_PY_INTPTR_T@ #define NPY_SIZEOF_OFF_T @SIZEOF_OFF_T@ #define NPY_SIZEOF_COMPLEX_FLOAT @SIZEOF_COMPLEX_FLOAT@ #define NPY_SIZEOF_COMPLEX_DOUBLE @SIZEOF_COMPLEX_DOUBLE@ #define NPY_SIZEOF_COMPLEX_LONGDOUBLE @SIZEOF_COMPLEX_LONG_DOUBLE@ @DEFINE_NPY_HAVE_DECL_ISNAN@ @DEFINE_NPY_HAVE_DECL_ISINF@ @DEFINE_NPY_HAVE_DECL_ISFINITE@ @DEFINE_NPY_HAVE_DECL_SIGNBIT@ @DEFINE_NPY_NO_SIGNAL@ #define NPY_NO_SMP @NPY_NO_SMP@ /* XXX: this has really nothing to do in a config file... */ #define NPY_MATHLIB @MATHLIB@ @DEFINE_NPY_SIZEOF_LONGLONG@ @DEFINE_NPY_SIZEOF_PY_LONG_LONG@ @DEFINE_NPY_ENABLE_SEPARATE_COMPILATION@ #define NPY_VISIBILITY_HIDDEN @VISIBILITY_HIDDEN@ @DEFINE_NPY_USE_C99_FORMATS@ @DEFINE_NPY_HAVE_COMPLEX_DOUBLE@ @DEFINE_NPY_HAVE_COMPLEX_FLOAT@ @DEFINE_NPY_HAVE_COMPLEX_LONG_DOUBLE@ @DEFINE_NPY_USE_C99_COMPLEX@ #define NPY_ABI_VERSION @NPY_ABI_VERSION@ #define NPY_API_VERSION @NPY_API_VERSION@ @DEFINE_NPY_HAVE_ENDIAN_H@ /* Ugly, but we can't test this in a proper manner without requiring a C++ * compiler at the configuration stage of numpy ? */ #ifndef __STDC_FORMAT_MACROS #define __STDC_FORMAT_MACROS 1 #endif numpy-1.8.2/numpy/core/include/numpy/npy_3kcompat.h0000664000175100017510000002731012370216243023502 0ustar vagrantvagrant00000000000000/* * This is a convenience header file providing compatibility utilities * for supporting Python 2 and Python 3 in the same code base. * * If you want to use this for your own projects, it's recommended to make a * copy of it. Although the stuff below is unlikely to change, we don't provide * strong backwards compatibility guarantees at the moment. */ #ifndef _NPY_3KCOMPAT_H_ #define _NPY_3KCOMPAT_H_ #include #include #if PY_VERSION_HEX >= 0x03000000 #ifndef NPY_PY3K #define NPY_PY3K 1 #endif #endif #include "numpy/npy_common.h" #include "numpy/ndarrayobject.h" #ifdef __cplusplus extern "C" { #endif /* * PyInt -> PyLong */ #if defined(NPY_PY3K) /* Return True only if the long fits in a C long */ static NPY_INLINE int PyInt_Check(PyObject *op) { int overflow = 0; if (!PyLong_Check(op)) { return 0; } PyLong_AsLongAndOverflow(op, &overflow); return (overflow == 0); } #define PyInt_FromLong PyLong_FromLong #define PyInt_AsLong PyLong_AsLong #define PyInt_AS_LONG PyLong_AsLong #define PyInt_AsSsize_t PyLong_AsSsize_t /* NOTE: * * Since the PyLong type is very different from the fixed-range PyInt, * we don't define PyInt_Type -> PyLong_Type. */ #endif /* NPY_PY3K */ /* * PyString -> PyBytes */ #if defined(NPY_PY3K) #define PyString_Type PyBytes_Type #define PyString_Check PyBytes_Check #define PyStringObject PyBytesObject #define PyString_FromString PyBytes_FromString #define PyString_FromStringAndSize PyBytes_FromStringAndSize #define PyString_AS_STRING PyBytes_AS_STRING #define PyString_AsStringAndSize PyBytes_AsStringAndSize #define PyString_FromFormat PyBytes_FromFormat #define PyString_Concat PyBytes_Concat #define PyString_ConcatAndDel PyBytes_ConcatAndDel #define PyString_AsString PyBytes_AsString #define PyString_GET_SIZE PyBytes_GET_SIZE #define PyString_Size PyBytes_Size #define PyUString_Type PyUnicode_Type #define PyUString_Check PyUnicode_Check #define PyUStringObject PyUnicodeObject #define PyUString_FromString PyUnicode_FromString #define PyUString_FromStringAndSize PyUnicode_FromStringAndSize #define PyUString_FromFormat PyUnicode_FromFormat #define PyUString_Concat PyUnicode_Concat2 #define PyUString_ConcatAndDel PyUnicode_ConcatAndDel #define PyUString_GET_SIZE PyUnicode_GET_SIZE #define PyUString_Size PyUnicode_Size #define PyUString_InternFromString PyUnicode_InternFromString #define PyUString_Format PyUnicode_Format #else #define PyBytes_Type PyString_Type #define PyBytes_Check PyString_Check #define PyBytesObject PyStringObject #define PyBytes_FromString PyString_FromString #define PyBytes_FromStringAndSize PyString_FromStringAndSize #define PyBytes_AS_STRING PyString_AS_STRING #define PyBytes_AsStringAndSize PyString_AsStringAndSize #define PyBytes_FromFormat PyString_FromFormat #define PyBytes_Concat PyString_Concat #define PyBytes_ConcatAndDel PyString_ConcatAndDel #define PyBytes_AsString PyString_AsString #define PyBytes_GET_SIZE PyString_GET_SIZE #define PyBytes_Size PyString_Size #define PyUString_Type PyString_Type #define PyUString_Check PyString_Check #define PyUStringObject PyStringObject #define PyUString_FromString PyString_FromString #define PyUString_FromStringAndSize PyString_FromStringAndSize #define PyUString_FromFormat PyString_FromFormat #define PyUString_Concat PyString_Concat #define PyUString_ConcatAndDel PyString_ConcatAndDel #define PyUString_GET_SIZE PyString_GET_SIZE #define PyUString_Size PyString_Size #define PyUString_InternFromString PyString_InternFromString #define PyUString_Format PyString_Format #endif /* NPY_PY3K */ static NPY_INLINE void PyUnicode_ConcatAndDel(PyObject **left, PyObject *right) { PyObject *newobj; newobj = PyUnicode_Concat(*left, right); Py_DECREF(*left); Py_DECREF(right); *left = newobj; } static NPY_INLINE void PyUnicode_Concat2(PyObject **left, PyObject *right) { PyObject *newobj; newobj = PyUnicode_Concat(*left, right); Py_DECREF(*left); *left = newobj; } /* * PyFile_* compatibility */ #if defined(NPY_PY3K) /* * Get a FILE* handle to the file represented by the Python object */ static NPY_INLINE FILE* npy_PyFile_Dup2(PyObject *file, char *mode, npy_off_t *orig_pos) { int fd, fd2; PyObject *ret, *os; npy_off_t pos; FILE *handle; /* Flush first to ensure things end up in the file in the correct order */ ret = PyObject_CallMethod(file, "flush", ""); if (ret == NULL) { return NULL; } Py_DECREF(ret); fd = PyObject_AsFileDescriptor(file); if (fd == -1) { return NULL; } /* The handle needs to be dup'd because we have to call fclose at the end */ os = PyImport_ImportModule("os"); if (os == NULL) { return NULL; } ret = PyObject_CallMethod(os, "dup", "i", fd); Py_DECREF(os); if (ret == NULL) { return NULL; } fd2 = PyNumber_AsSsize_t(ret, NULL); Py_DECREF(ret); /* Convert to FILE* handle */ #ifdef _WIN32 handle = _fdopen(fd2, mode); #else handle = fdopen(fd2, mode); #endif if (handle == NULL) { PyErr_SetString(PyExc_IOError, "Getting a FILE* from a Python file object failed"); } /* Record the original raw file handle position */ *orig_pos = npy_ftell(handle); if (*orig_pos == -1) { PyErr_SetString(PyExc_IOError, "obtaining file position failed"); fclose(handle); return NULL; } /* Seek raw handle to the Python-side position */ ret = PyObject_CallMethod(file, "tell", ""); if (ret == NULL) { fclose(handle); return NULL; } pos = PyLong_AsLongLong(ret); Py_DECREF(ret); if (PyErr_Occurred()) { fclose(handle); return NULL; } if (npy_fseek(handle, pos, SEEK_SET) == -1) { PyErr_SetString(PyExc_IOError, "seeking file failed"); fclose(handle); return NULL; } return handle; } /* * Close the dup-ed file handle, and seek the Python one to the current position */ static NPY_INLINE int npy_PyFile_DupClose2(PyObject *file, FILE* handle, npy_off_t orig_pos) { int fd; PyObject *ret; npy_off_t position; position = npy_ftell(handle); /* Close the FILE* handle */ fclose(handle); /* Restore original file handle position, in order to not confuse Python-side data structures */ fd = PyObject_AsFileDescriptor(file); if (fd == -1) { return -1; } if (npy_lseek(fd, orig_pos, SEEK_SET) == -1) { PyErr_SetString(PyExc_IOError, "seeking file failed"); return -1; } if (position == -1) { PyErr_SetString(PyExc_IOError, "obtaining file position failed"); return -1; } /* Seek Python-side handle to the FILE* handle position */ ret = PyObject_CallMethod(file, "seek", NPY_OFF_T_PYFMT "i", position, 0); if (ret == NULL) { return -1; } Py_DECREF(ret); return 0; } static NPY_INLINE int npy_PyFile_Check(PyObject *file) { int fd; fd = PyObject_AsFileDescriptor(file); if (fd == -1) { PyErr_Clear(); return 0; } return 1; } /* * DEPRECATED DO NOT USE * use npy_PyFile_Dup2 instead * this function will mess ups 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); } /* * 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 /* DEPRECATED DO NOT USE */ #define npy_PyFile_Dup(file, mode) PyFile_AsFile(file) #define npy_PyFile_DupClose(file, handle) (0) /* use these */ #define npy_PyFile_Dup2(file, mode, orig_pos_p) PyFile_AsFile(file) #define npy_PyFile_DupClose2(file, handle, orig_pos) (0) #define npy_PyFile_Check PyFile_Check #endif static NPY_INLINE PyObject* npy_PyFile_OpenFile(PyObject *filename, const char *mode) { PyObject *open; open = PyDict_GetItemString(PyEval_GetBuiltins(), "open"); if (open == NULL) { return NULL; } return PyObject_CallFunction(open, "Os", filename, mode); } static NPY_INLINE int npy_PyFile_CloseFile(PyObject *file) { PyObject *ret; ret = PyObject_CallMethod(file, "close", NULL); if (ret == NULL) { return -1; } Py_DECREF(ret); return 0; } /* * PyObject_Cmp */ #if defined(NPY_PY3K) static NPY_INLINE int PyObject_Cmp(PyObject *i1, PyObject *i2, int *cmp) { int v; v = PyObject_RichCompareBool(i1, i2, Py_LT); if (v == 0) { *cmp = -1; return 1; } else if (v == -1) { return -1; } v = PyObject_RichCompareBool(i1, i2, Py_GT); if (v == 0) { *cmp = 1; return 1; } else if (v == -1) { return -1; } v = PyObject_RichCompareBool(i1, i2, Py_EQ); if (v == 0) { *cmp = 0; return 1; } else { *cmp = 0; return -1; } } #endif /* * PyCObject functions adapted to PyCapsules. * * The main job here is to get rid of the improved error handling * of PyCapsules. It's a shame... */ #if PY_VERSION_HEX >= 0x03000000 static NPY_INLINE PyObject * NpyCapsule_FromVoidPtr(void *ptr, void (*dtor)(PyObject *)) { PyObject *ret = PyCapsule_New(ptr, NULL, dtor); if (ret == NULL) { PyErr_Clear(); } return ret; } static NPY_INLINE PyObject * NpyCapsule_FromVoidPtrAndDesc(void *ptr, void* context, void (*dtor)(PyObject *)) { PyObject *ret = NpyCapsule_FromVoidPtr(ptr, dtor); if (ret != NULL && PyCapsule_SetContext(ret, context) != 0) { PyErr_Clear(); Py_DECREF(ret); ret = NULL; } return ret; } static NPY_INLINE void * NpyCapsule_AsVoidPtr(PyObject *obj) { void *ret = PyCapsule_GetPointer(obj, NULL); if (ret == NULL) { PyErr_Clear(); } return ret; } static NPY_INLINE void * NpyCapsule_GetDesc(PyObject *obj) { return PyCapsule_GetContext(obj); } static NPY_INLINE int NpyCapsule_Check(PyObject *ptr) { return PyCapsule_CheckExact(ptr); } static NPY_INLINE void simple_capsule_dtor(PyObject *cap) { PyArray_free(PyCapsule_GetPointer(cap, NULL)); } #else static NPY_INLINE PyObject * NpyCapsule_FromVoidPtr(void *ptr, void (*dtor)(void *)) { return PyCObject_FromVoidPtr(ptr, dtor); } static NPY_INLINE PyObject * NpyCapsule_FromVoidPtrAndDesc(void *ptr, void* context, void (*dtor)(void *, void *)) { return PyCObject_FromVoidPtrAndDesc(ptr, context, dtor); } static NPY_INLINE void * NpyCapsule_AsVoidPtr(PyObject *ptr) { return PyCObject_AsVoidPtr(ptr); } static NPY_INLINE void * NpyCapsule_GetDesc(PyObject *obj) { return PyCObject_GetDesc(obj); } static NPY_INLINE int NpyCapsule_Check(PyObject *ptr) { return PyCObject_Check(ptr); } static NPY_INLINE void simple_capsule_dtor(void *ptr) { PyArray_free(ptr); } #endif /* * Hash value compatibility. * As of Python 3.2 hash values are of type Py_hash_t. * Previous versions use C long. */ #if PY_VERSION_HEX < 0x03020000 typedef long npy_hash_t; #define NPY_SIZEOF_HASH_T NPY_SIZEOF_LONG #else typedef Py_hash_t npy_hash_t; #define NPY_SIZEOF_HASH_T NPY_SIZEOF_INTP #endif #ifdef __cplusplus } #endif #endif /* _NPY_3KCOMPAT_H_ */ numpy-1.8.2/numpy/core/include/numpy/npy_endian.h0000664000175100017510000000255312370216243023221 0ustar vagrantvagrant00000000000000#ifndef _NPY_ENDIAN_H_ #define _NPY_ENDIAN_H_ /* * NPY_BYTE_ORDER is set to the same value as BYTE_ORDER set by glibc in * endian.h */ #ifdef NPY_HAVE_ENDIAN_H /* Use endian.h if available */ #include #define NPY_BYTE_ORDER __BYTE_ORDER #define NPY_LITTLE_ENDIAN __LITTLE_ENDIAN #define NPY_BIG_ENDIAN __BIG_ENDIAN #else /* Set endianness info using target CPU */ #include "npy_cpu.h" #define NPY_LITTLE_ENDIAN 1234 #define NPY_BIG_ENDIAN 4321 #if defined(NPY_CPU_X86) \ || defined(NPY_CPU_AMD64) \ || defined(NPY_CPU_IA64) \ || defined(NPY_CPU_ALPHA) \ || defined(NPY_CPU_ARMEL) \ || defined(NPY_CPU_AARCH64) \ || defined(NPY_CPU_SH_LE) \ || defined(NPY_CPU_MIPSEL) #define NPY_BYTE_ORDER NPY_LITTLE_ENDIAN #elif defined(NPY_CPU_PPC) \ || defined(NPY_CPU_SPARC) \ || defined(NPY_CPU_S390) \ || defined(NPY_CPU_HPPA) \ || defined(NPY_CPU_PPC64) \ || defined(NPY_CPU_ARMEB) \ || defined(NPY_CPU_SH_BE) \ || defined(NPY_CPU_MIPSEB) \ || defined(NPY_CPU_M68K) #define NPY_BYTE_ORDER NPY_BIG_ENDIAN #else #error Unknown CPU: can not set endianness #endif #endif #endif numpy-1.8.2/numpy/core/include/numpy/npy_1_7_deprecated_api.h0000664000175100017510000001077412370216242025365 0ustar vagrantvagrant00000000000000#ifndef _NPY_1_7_DEPRECATED_API_H #define _NPY_1_7_DEPRECATED_API_H #ifndef NPY_DEPRECATED_INCLUDES #error "Should never include npy_*_*_deprecated_api directly." #endif #if defined(_WIN32) #define _WARN___STR2__(x) #x #define _WARN___STR1__(x) _WARN___STR2__(x) #define _WARN___LOC__ __FILE__ "(" _WARN___STR1__(__LINE__) ") : Warning Msg: " #pragma message(_WARN___LOC__"Using deprecated NumPy API, disable it by " \ "#defining NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION") #elif defined(__GNUC__) #warning "Using deprecated NumPy API, disable it by " \ "#defining NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION" #endif /* TODO: How to do this warning message for other compilers? */ /* * This header exists to collect all dangerous/deprecated NumPy API * as of NumPy 1.7. * * This is an attempt to remove bad API, the proliferation of macros, * and namespace pollution currently produced by the NumPy headers. */ /* These array flags are deprecated as of NumPy 1.7 */ #define NPY_CONTIGUOUS NPY_ARRAY_C_CONTIGUOUS #define NPY_FORTRAN NPY_ARRAY_F_CONTIGUOUS /* * The consistent NPY_ARRAY_* names which don't pollute the NPY_* * namespace were added in NumPy 1.7. * * These versions of the carray flags are deprecated, but * probably should only be removed after two releases instead of one. */ #define NPY_C_CONTIGUOUS NPY_ARRAY_C_CONTIGUOUS #define NPY_F_CONTIGUOUS NPY_ARRAY_F_CONTIGUOUS #define NPY_OWNDATA NPY_ARRAY_OWNDATA #define NPY_FORCECAST NPY_ARRAY_FORCECAST #define NPY_ENSURECOPY NPY_ARRAY_ENSURECOPY #define NPY_ENSUREARRAY NPY_ARRAY_ENSUREARRAY #define NPY_ELEMENTSTRIDES NPY_ARRAY_ELEMENTSTRIDES #define NPY_ALIGNED NPY_ARRAY_ALIGNED #define NPY_NOTSWAPPED NPY_ARRAY_NOTSWAPPED #define NPY_WRITEABLE NPY_ARRAY_WRITEABLE #define NPY_UPDATEIFCOPY NPY_ARRAY_UPDATEIFCOPY #define NPY_BEHAVED NPY_ARRAY_BEHAVED #define NPY_BEHAVED_NS NPY_ARRAY_BEHAVED_NS #define NPY_CARRAY NPY_ARRAY_CARRAY #define NPY_CARRAY_RO NPY_ARRAY_CARRAY_RO #define NPY_FARRAY NPY_ARRAY_FARRAY #define NPY_FARRAY_RO NPY_ARRAY_FARRAY_RO #define NPY_DEFAULT NPY_ARRAY_DEFAULT #define NPY_IN_ARRAY NPY_ARRAY_IN_ARRAY #define NPY_OUT_ARRAY NPY_ARRAY_OUT_ARRAY #define NPY_INOUT_ARRAY NPY_ARRAY_INOUT_ARRAY #define NPY_IN_FARRAY NPY_ARRAY_IN_FARRAY #define NPY_OUT_FARRAY NPY_ARRAY_OUT_FARRAY #define NPY_INOUT_FARRAY NPY_ARRAY_INOUT_FARRAY #define NPY_UPDATE_ALL NPY_ARRAY_UPDATE_ALL /* This way of accessing the default type is deprecated as of NumPy 1.7 */ #define PyArray_DEFAULT NPY_DEFAULT_TYPE /* These DATETIME bits aren't used internally */ #if PY_VERSION_HEX >= 0x03000000 #define PyDataType_GetDatetimeMetaData(descr) \ ((descr->metadata == NULL) ? NULL : \ ((PyArray_DatetimeMetaData *)(PyCapsule_GetPointer( \ PyDict_GetItemString( \ descr->metadata, NPY_METADATA_DTSTR), NULL)))) #else #define PyDataType_GetDatetimeMetaData(descr) \ ((descr->metadata == NULL) ? NULL : \ ((PyArray_DatetimeMetaData *)(PyCObject_AsVoidPtr( \ PyDict_GetItemString(descr->metadata, NPY_METADATA_DTSTR))))) #endif /* * Deprecated as of NumPy 1.7, this kind of shortcut doesn't * belong in the public API. */ #define NPY_AO PyArrayObject /* * Deprecated as of NumPy 1.7, an all-lowercase macro doesn't * belong in the public API. */ #define fortran fortran_ /* * Deprecated as of NumPy 1.7, as it is a namespace-polluting * macro. */ #define FORTRAN_IF PyArray_FORTRAN_IF /* Deprecated as of NumPy 1.7, datetime64 uses c_metadata instead */ #define NPY_METADATA_DTSTR "__timeunit__" /* * Deprecated as of NumPy 1.7. * The reasoning: * - These are for datetime, but there's no datetime "namespace". * - They just turn NPY_STR_ into "", which is just * making something simple be indirected. */ #define NPY_STR_Y "Y" #define NPY_STR_M "M" #define NPY_STR_W "W" #define NPY_STR_D "D" #define NPY_STR_h "h" #define NPY_STR_m "m" #define NPY_STR_s "s" #define NPY_STR_ms "ms" #define NPY_STR_us "us" #define NPY_STR_ns "ns" #define NPY_STR_ps "ps" #define NPY_STR_fs "fs" #define NPY_STR_as "as" /* * The macros in old_defines.h are Deprecated as of NumPy 1.7 and will be * removed in the next major release. */ #include "old_defines.h" #endif numpy-1.8.2/numpy/core/include/numpy/npy_common.h0000664000175100017510000010464212370216243023255 0ustar vagrantvagrant00000000000000#ifndef _NPY_COMMON_H_ #define _NPY_COMMON_H_ /* numpconfig.h is auto-generated */ #include "numpyconfig.h" #ifdef HAVE_NPY_CONFIG_H #include #endif /* * gcc does not unroll even with -O3 * use with care, unrolling on modern cpus rarely speeds things up */ #ifdef HAVE_ATTRIBUTE_OPTIMIZE_UNROLL_LOOPS #define NPY_GCC_UNROLL_LOOPS \ __attribute__((optimize("unroll-loops"))) #else #define NPY_GCC_UNROLL_LOOPS #endif #if defined HAVE_XMMINTRIN_H && defined HAVE__MM_LOAD_PS #define NPY_HAVE_SSE_INTRINSICS #endif #if defined HAVE_EMMINTRIN_H && defined HAVE__MM_LOAD_PD #define NPY_HAVE_SSE2_INTRINSICS #endif /* * give a hint to the compiler which branch is more likely or unlikely * to occur, e.g. rare error cases: * * if (NPY_UNLIKELY(failure == 0)) * return NULL; * * the double !! is to cast the expression (e.g. NULL) to a boolean required by * the intrinsic */ #ifdef HAVE___BUILTIN_EXPECT #define NPY_LIKELY(x) __builtin_expect(!!(x), 1) #define NPY_UNLIKELY(x) __builtin_expect(!!(x), 0) #else #define NPY_LIKELY(x) (x) #define NPY_UNLIKELY(x) (x) #endif #if defined(_MSC_VER) #define NPY_INLINE __inline #elif defined(__GNUC__) #if defined(__STRICT_ANSI__) #define NPY_INLINE __inline__ #else #define NPY_INLINE inline #endif #else #define NPY_INLINE #endif /* 64 bit file position support, also on win-amd64. Ticket #1660 */ #if defined(_MSC_VER) && defined(_WIN64) && (_MSC_VER > 1400) || \ defined(__MINGW32__) || defined(__MINGW64__) #include /* mingw based on 3.4.5 has lseek but not ftell/fseek */ #if defined(__MINGW32__) || defined(__MINGW64__) extern int __cdecl _fseeki64(FILE *, long long, int); extern long long __cdecl _ftelli64(FILE *); #endif #define npy_fseek _fseeki64 #define npy_ftell _ftelli64 #define npy_lseek _lseeki64 #define npy_off_t npy_int64 #if NPY_SIZEOF_INT == 8 #define NPY_OFF_T_PYFMT "i" #elif NPY_SIZEOF_LONG == 8 #define NPY_OFF_T_PYFMT "l" #elif NPY_SIZEOF_LONGLONG == 8 #define NPY_OFF_T_PYFMT "L" #else #error Unsupported size for type off_t #endif #else #ifdef HAVE_FSEEKO #define npy_fseek fseeko #else #define npy_fseek fseek #endif #ifdef HAVE_FTELLO #define npy_ftell ftello #else #define npy_ftell ftell #endif #define npy_lseek lseek #define npy_off_t off_t #if NPY_SIZEOF_OFF_T == NPY_SIZEOF_SHORT #define NPY_OFF_T_PYFMT "h" #elif NPY_SIZEOF_OFF_T == NPY_SIZEOF_INT #define NPY_OFF_T_PYFMT "i" #elif NPY_SIZEOF_OFF_T == NPY_SIZEOF_LONG #define NPY_OFF_T_PYFMT "l" #elif NPY_SIZEOF_OFF_T == NPY_SIZEOF_LONGLONG #define NPY_OFF_T_PYFMT "L" #else #error Unsupported size for type off_t #endif #endif /* enums for detected endianness */ enum { NPY_CPU_UNKNOWN_ENDIAN, NPY_CPU_LITTLE, NPY_CPU_BIG }; /* * This is to typedef npy_intp to the appropriate pointer size for this * platform. Py_intptr_t, Py_uintptr_t are defined in pyport.h. */ typedef Py_intptr_t npy_intp; typedef Py_uintptr_t npy_uintp; /* * Define sizes that were not defined in numpyconfig.h. */ #define NPY_SIZEOF_CHAR 1 #define NPY_SIZEOF_BYTE 1 #define NPY_SIZEOF_DATETIME 8 #define NPY_SIZEOF_TIMEDELTA 8 #define NPY_SIZEOF_INTP NPY_SIZEOF_PY_INTPTR_T #define NPY_SIZEOF_UINTP NPY_SIZEOF_PY_INTPTR_T #define NPY_SIZEOF_HALF 2 #define NPY_SIZEOF_CFLOAT NPY_SIZEOF_COMPLEX_FLOAT #define NPY_SIZEOF_CDOUBLE NPY_SIZEOF_COMPLEX_DOUBLE #define NPY_SIZEOF_CLONGDOUBLE NPY_SIZEOF_COMPLEX_LONGDOUBLE #ifdef constchar #undef constchar #endif #define NPY_SSIZE_T_PYFMT "n" #define constchar char /* NPY_INTP_FMT Note: * Unlike the other NPY_*_FMT macros which are used with * PyOS_snprintf, NPY_INTP_FMT is used with PyErr_Format and * PyString_Format. These functions use different formatting * codes which are portably specified according to the Python * documentation. See ticket #1795. * * On Windows x64, the LONGLONG formatter should be used, but * in Python 2.6 the %lld formatter is not supported. In this * case we work around the problem by using the %zd formatter. */ #if NPY_SIZEOF_PY_INTPTR_T == NPY_SIZEOF_INT #define NPY_INTP NPY_INT #define NPY_UINTP NPY_UINT #define PyIntpArrType_Type PyIntArrType_Type #define PyUIntpArrType_Type PyUIntArrType_Type #define NPY_MAX_INTP NPY_MAX_INT #define NPY_MIN_INTP NPY_MIN_INT #define NPY_MAX_UINTP NPY_MAX_UINT #define NPY_INTP_FMT "d" #elif NPY_SIZEOF_PY_INTPTR_T == NPY_SIZEOF_LONG #define NPY_INTP NPY_LONG #define NPY_UINTP NPY_ULONG #define PyIntpArrType_Type PyLongArrType_Type #define PyUIntpArrType_Type PyULongArrType_Type #define NPY_MAX_INTP NPY_MAX_LONG #define NPY_MIN_INTP NPY_MIN_LONG #define NPY_MAX_UINTP NPY_MAX_ULONG #define NPY_INTP_FMT "ld" #elif defined(PY_LONG_LONG) && (NPY_SIZEOF_PY_INTPTR_T == NPY_SIZEOF_LONGLONG) #define NPY_INTP NPY_LONGLONG #define NPY_UINTP NPY_ULONGLONG #define PyIntpArrType_Type PyLongLongArrType_Type #define PyUIntpArrType_Type PyULongLongArrType_Type #define NPY_MAX_INTP NPY_MAX_LONGLONG #define NPY_MIN_INTP NPY_MIN_LONGLONG #define NPY_MAX_UINTP NPY_MAX_ULONGLONG #if (PY_VERSION_HEX >= 0x02070000) #define NPY_INTP_FMT "lld" #else #define NPY_INTP_FMT "zd" #endif #endif /* * We can only use C99 formats for npy_int_p if it is the same as * intp_t, hence the condition on HAVE_UNITPTR_T */ #if (NPY_USE_C99_FORMATS) == 1 \ && (defined HAVE_UINTPTR_T) \ && (defined HAVE_INTTYPES_H) #include #undef NPY_INTP_FMT #define NPY_INTP_FMT PRIdPTR #endif /* * Some platforms don't define bool, long long, or long double. * Handle that here. */ #define NPY_BYTE_FMT "hhd" #define NPY_UBYTE_FMT "hhu" #define NPY_SHORT_FMT "hd" #define NPY_USHORT_FMT "hu" #define NPY_INT_FMT "d" #define NPY_UINT_FMT "u" #define NPY_LONG_FMT "ld" #define NPY_ULONG_FMT "lu" #define NPY_HALF_FMT "g" #define NPY_FLOAT_FMT "g" #define NPY_DOUBLE_FMT "g" #ifdef PY_LONG_LONG typedef PY_LONG_LONG npy_longlong; typedef unsigned PY_LONG_LONG npy_ulonglong; # ifdef _MSC_VER # define NPY_LONGLONG_FMT "I64d" # define NPY_ULONGLONG_FMT "I64u" # elif defined(__APPLE__) || defined(__FreeBSD__) /* "%Ld" only parses 4 bytes -- "L" is floating modifier on MacOS X/BSD */ # define NPY_LONGLONG_FMT "lld" # define NPY_ULONGLONG_FMT "llu" /* another possible variant -- *quad_t works on *BSD, but is deprecated: #define LONGLONG_FMT "qd" #define ULONGLONG_FMT "qu" */ # else # define NPY_LONGLONG_FMT "Ld" # define NPY_ULONGLONG_FMT "Lu" # endif # ifdef _MSC_VER # define NPY_LONGLONG_SUFFIX(x) (x##i64) # define NPY_ULONGLONG_SUFFIX(x) (x##Ui64) # else # define NPY_LONGLONG_SUFFIX(x) (x##LL) # define NPY_ULONGLONG_SUFFIX(x) (x##ULL) # endif #else typedef long npy_longlong; typedef unsigned long npy_ulonglong; # define NPY_LONGLONG_SUFFIX(x) (x##L) # define NPY_ULONGLONG_SUFFIX(x) (x##UL) #endif typedef unsigned char npy_bool; #define NPY_FALSE 0 #define NPY_TRUE 1 #if NPY_SIZEOF_LONGDOUBLE == NPY_SIZEOF_DOUBLE typedef double npy_longdouble; #define NPY_LONGDOUBLE_FMT "g" #else typedef long double npy_longdouble; #define NPY_LONGDOUBLE_FMT "Lg" #endif #ifndef Py_USING_UNICODE #error Must use Python with unicode enabled. #endif typedef signed char npy_byte; typedef unsigned char npy_ubyte; typedef unsigned short npy_ushort; typedef unsigned int npy_uint; typedef unsigned long npy_ulong; /* These are for completeness */ typedef char npy_char; typedef short npy_short; typedef int npy_int; typedef long npy_long; typedef float npy_float; typedef double npy_double; /* * Disabling C99 complex usage: a lot of C code in numpy/scipy rely on being * able to do .real/.imag. Will have to convert code first. */ #if 0 #if defined(NPY_USE_C99_COMPLEX) && defined(NPY_HAVE_COMPLEX_DOUBLE) typedef complex npy_cdouble; #else typedef struct { double real, imag; } npy_cdouble; #endif #if defined(NPY_USE_C99_COMPLEX) && defined(NPY_HAVE_COMPLEX_FLOAT) typedef complex float npy_cfloat; #else typedef struct { float real, imag; } npy_cfloat; #endif #if defined(NPY_USE_C99_COMPLEX) && defined(NPY_HAVE_COMPLEX_LONG_DOUBLE) typedef complex long double npy_clongdouble; #else typedef struct {npy_longdouble real, imag;} npy_clongdouble; #endif #endif #if NPY_SIZEOF_COMPLEX_DOUBLE != 2 * NPY_SIZEOF_DOUBLE #error npy_cdouble definition is not compatible with C99 complex definition ! \ Please contact Numpy maintainers and give detailed information about your \ compiler and platform #endif typedef struct { double real, imag; } npy_cdouble; #if NPY_SIZEOF_COMPLEX_FLOAT != 2 * NPY_SIZEOF_FLOAT #error npy_cfloat definition is not compatible with C99 complex definition ! \ Please contact Numpy maintainers and give detailed information about your \ compiler and platform #endif typedef struct { float real, imag; } npy_cfloat; #if NPY_SIZEOF_COMPLEX_LONGDOUBLE != 2 * NPY_SIZEOF_LONGDOUBLE #error npy_clongdouble definition is not compatible with C99 complex definition ! \ Please contact Numpy maintainers and give detailed information about your \ compiler and platform #endif typedef struct { npy_longdouble real, imag; } npy_clongdouble; /* * numarray-style bit-width typedefs */ #define NPY_MAX_INT8 127 #define NPY_MIN_INT8 -128 #define NPY_MAX_UINT8 255 #define NPY_MAX_INT16 32767 #define NPY_MIN_INT16 -32768 #define NPY_MAX_UINT16 65535 #define NPY_MAX_INT32 2147483647 #define NPY_MIN_INT32 (-NPY_MAX_INT32 - 1) #define NPY_MAX_UINT32 4294967295U #define NPY_MAX_INT64 NPY_LONGLONG_SUFFIX(9223372036854775807) #define NPY_MIN_INT64 (-NPY_MAX_INT64 - NPY_LONGLONG_SUFFIX(1)) #define NPY_MAX_UINT64 NPY_ULONGLONG_SUFFIX(18446744073709551615) #define NPY_MAX_INT128 NPY_LONGLONG_SUFFIX(85070591730234615865843651857942052864) #define NPY_MIN_INT128 (-NPY_MAX_INT128 - NPY_LONGLONG_SUFFIX(1)) #define NPY_MAX_UINT128 NPY_ULONGLONG_SUFFIX(170141183460469231731687303715884105728) #define NPY_MAX_INT256 NPY_LONGLONG_SUFFIX(57896044618658097711785492504343953926634992332820282019728792003956564819967) #define NPY_MIN_INT256 (-NPY_MAX_INT256 - NPY_LONGLONG_SUFFIX(1)) #define NPY_MAX_UINT256 NPY_ULONGLONG_SUFFIX(115792089237316195423570985008687907853269984665640564039457584007913129639935) #define NPY_MIN_DATETIME NPY_MIN_INT64 #define NPY_MAX_DATETIME NPY_MAX_INT64 #define NPY_MIN_TIMEDELTA NPY_MIN_INT64 #define NPY_MAX_TIMEDELTA NPY_MAX_INT64 /* Need to find the number of bits for each type and make definitions accordingly. C states that sizeof(char) == 1 by definition So, just using the sizeof keyword won't help. It also looks like Python itself uses sizeof(char) quite a bit, which by definition should be 1 all the time. Idea: Make Use of CHAR_BIT which should tell us how many BITS per CHARACTER */ /* Include platform definitions -- These are in the C89/90 standard */ #include #define NPY_MAX_BYTE SCHAR_MAX #define NPY_MIN_BYTE SCHAR_MIN #define NPY_MAX_UBYTE UCHAR_MAX #define NPY_MAX_SHORT SHRT_MAX #define NPY_MIN_SHORT SHRT_MIN #define NPY_MAX_USHORT USHRT_MAX #define NPY_MAX_INT INT_MAX #ifndef INT_MIN #define INT_MIN (-INT_MAX - 1) #endif #define NPY_MIN_INT INT_MIN #define NPY_MAX_UINT UINT_MAX #define NPY_MAX_LONG LONG_MAX #define NPY_MIN_LONG LONG_MIN #define NPY_MAX_ULONG ULONG_MAX #define NPY_BITSOF_BOOL (sizeof(npy_bool) * CHAR_BIT) #define NPY_BITSOF_CHAR CHAR_BIT #define NPY_BITSOF_BYTE (NPY_SIZEOF_BYTE * CHAR_BIT) #define NPY_BITSOF_SHORT (NPY_SIZEOF_SHORT * CHAR_BIT) #define NPY_BITSOF_INT (NPY_SIZEOF_INT * CHAR_BIT) #define NPY_BITSOF_LONG (NPY_SIZEOF_LONG * CHAR_BIT) #define NPY_BITSOF_LONGLONG (NPY_SIZEOF_LONGLONG * CHAR_BIT) #define NPY_BITSOF_INTP (NPY_SIZEOF_INTP * CHAR_BIT) #define NPY_BITSOF_HALF (NPY_SIZEOF_HALF * CHAR_BIT) #define NPY_BITSOF_FLOAT (NPY_SIZEOF_FLOAT * CHAR_BIT) #define NPY_BITSOF_DOUBLE (NPY_SIZEOF_DOUBLE * CHAR_BIT) #define NPY_BITSOF_LONGDOUBLE (NPY_SIZEOF_LONGDOUBLE * CHAR_BIT) #define NPY_BITSOF_CFLOAT (NPY_SIZEOF_CFLOAT * CHAR_BIT) #define NPY_BITSOF_CDOUBLE (NPY_SIZEOF_CDOUBLE * CHAR_BIT) #define NPY_BITSOF_CLONGDOUBLE (NPY_SIZEOF_CLONGDOUBLE * CHAR_BIT) #define NPY_BITSOF_DATETIME (NPY_SIZEOF_DATETIME * CHAR_BIT) #define NPY_BITSOF_TIMEDELTA (NPY_SIZEOF_TIMEDELTA * CHAR_BIT) #if NPY_BITSOF_LONG == 8 #define NPY_INT8 NPY_LONG #define NPY_UINT8 NPY_ULONG typedef long npy_int8; typedef unsigned long npy_uint8; #define PyInt8ScalarObject PyLongScalarObject #define PyInt8ArrType_Type PyLongArrType_Type #define PyUInt8ScalarObject PyULongScalarObject #define PyUInt8ArrType_Type PyULongArrType_Type #define NPY_INT8_FMT NPY_LONG_FMT #define NPY_UINT8_FMT NPY_ULONG_FMT #elif NPY_BITSOF_LONG == 16 #define NPY_INT16 NPY_LONG #define NPY_UINT16 NPY_ULONG typedef long npy_int16; typedef unsigned long npy_uint16; #define PyInt16ScalarObject PyLongScalarObject #define PyInt16ArrType_Type PyLongArrType_Type #define PyUInt16ScalarObject PyULongScalarObject #define PyUInt16ArrType_Type PyULongArrType_Type #define NPY_INT16_FMT NPY_LONG_FMT #define NPY_UINT16_FMT NPY_ULONG_FMT #elif NPY_BITSOF_LONG == 32 #define NPY_INT32 NPY_LONG #define NPY_UINT32 NPY_ULONG typedef long npy_int32; typedef unsigned long npy_uint32; typedef unsigned long npy_ucs4; #define PyInt32ScalarObject PyLongScalarObject #define PyInt32ArrType_Type PyLongArrType_Type #define PyUInt32ScalarObject PyULongScalarObject #define PyUInt32ArrType_Type PyULongArrType_Type #define NPY_INT32_FMT NPY_LONG_FMT #define NPY_UINT32_FMT NPY_ULONG_FMT #elif NPY_BITSOF_LONG == 64 #define NPY_INT64 NPY_LONG #define NPY_UINT64 NPY_ULONG typedef long npy_int64; typedef unsigned long npy_uint64; #define PyInt64ScalarObject PyLongScalarObject #define PyInt64ArrType_Type PyLongArrType_Type #define PyUInt64ScalarObject PyULongScalarObject #define PyUInt64ArrType_Type PyULongArrType_Type #define NPY_INT64_FMT NPY_LONG_FMT #define NPY_UINT64_FMT NPY_ULONG_FMT #define MyPyLong_FromInt64 PyLong_FromLong #define MyPyLong_AsInt64 PyLong_AsLong #elif NPY_BITSOF_LONG == 128 #define NPY_INT128 NPY_LONG #define NPY_UINT128 NPY_ULONG typedef long npy_int128; typedef unsigned long npy_uint128; #define PyInt128ScalarObject PyLongScalarObject #define PyInt128ArrType_Type PyLongArrType_Type #define PyUInt128ScalarObject PyULongScalarObject #define PyUInt128ArrType_Type PyULongArrType_Type #define NPY_INT128_FMT NPY_LONG_FMT #define NPY_UINT128_FMT NPY_ULONG_FMT #endif #if NPY_BITSOF_LONGLONG == 8 # ifndef NPY_INT8 # define NPY_INT8 NPY_LONGLONG # define NPY_UINT8 NPY_ULONGLONG typedef npy_longlong npy_int8; typedef npy_ulonglong npy_uint8; # define PyInt8ScalarObject PyLongLongScalarObject # define PyInt8ArrType_Type PyLongLongArrType_Type # define PyUInt8ScalarObject PyULongLongScalarObject # define PyUInt8ArrType_Type PyULongLongArrType_Type #define NPY_INT8_FMT NPY_LONGLONG_FMT #define NPY_UINT8_FMT NPY_ULONGLONG_FMT # endif # define NPY_MAX_LONGLONG NPY_MAX_INT8 # define NPY_MIN_LONGLONG NPY_MIN_INT8 # define NPY_MAX_ULONGLONG NPY_MAX_UINT8 #elif NPY_BITSOF_LONGLONG == 16 # ifndef NPY_INT16 # define NPY_INT16 NPY_LONGLONG # define NPY_UINT16 NPY_ULONGLONG typedef npy_longlong npy_int16; typedef npy_ulonglong npy_uint16; # define PyInt16ScalarObject PyLongLongScalarObject # define PyInt16ArrType_Type PyLongLongArrType_Type # define PyUInt16ScalarObject PyULongLongScalarObject # define PyUInt16ArrType_Type PyULongLongArrType_Type #define NPY_INT16_FMT NPY_LONGLONG_FMT #define NPY_UINT16_FMT NPY_ULONGLONG_FMT # endif # define NPY_MAX_LONGLONG NPY_MAX_INT16 # define NPY_MIN_LONGLONG NPY_MIN_INT16 # define NPY_MAX_ULONGLONG NPY_MAX_UINT16 #elif NPY_BITSOF_LONGLONG == 32 # ifndef NPY_INT32 # define NPY_INT32 NPY_LONGLONG # define NPY_UINT32 NPY_ULONGLONG typedef npy_longlong npy_int32; typedef npy_ulonglong npy_uint32; typedef npy_ulonglong npy_ucs4; # define PyInt32ScalarObject PyLongLongScalarObject # define PyInt32ArrType_Type PyLongLongArrType_Type # define PyUInt32ScalarObject PyULongLongScalarObject # define PyUInt32ArrType_Type PyULongLongArrType_Type #define NPY_INT32_FMT NPY_LONGLONG_FMT #define NPY_UINT32_FMT NPY_ULONGLONG_FMT # endif # define NPY_MAX_LONGLONG NPY_MAX_INT32 # define NPY_MIN_LONGLONG NPY_MIN_INT32 # define NPY_MAX_ULONGLONG NPY_MAX_UINT32 #elif NPY_BITSOF_LONGLONG == 64 # ifndef NPY_INT64 # define NPY_INT64 NPY_LONGLONG # define NPY_UINT64 NPY_ULONGLONG typedef npy_longlong npy_int64; typedef npy_ulonglong npy_uint64; # define PyInt64ScalarObject PyLongLongScalarObject # define PyInt64ArrType_Type PyLongLongArrType_Type # define PyUInt64ScalarObject PyULongLongScalarObject # define PyUInt64ArrType_Type PyULongLongArrType_Type #define NPY_INT64_FMT NPY_LONGLONG_FMT #define NPY_UINT64_FMT NPY_ULONGLONG_FMT # define MyPyLong_FromInt64 PyLong_FromLongLong # define MyPyLong_AsInt64 PyLong_AsLongLong # endif # define NPY_MAX_LONGLONG NPY_MAX_INT64 # define NPY_MIN_LONGLONG NPY_MIN_INT64 # define NPY_MAX_ULONGLONG NPY_MAX_UINT64 #elif NPY_BITSOF_LONGLONG == 128 # ifndef NPY_INT128 # define NPY_INT128 NPY_LONGLONG # define NPY_UINT128 NPY_ULONGLONG typedef npy_longlong npy_int128; typedef npy_ulonglong npy_uint128; # define PyInt128ScalarObject PyLongLongScalarObject # define PyInt128ArrType_Type PyLongLongArrType_Type # define PyUInt128ScalarObject PyULongLongScalarObject # define PyUInt128ArrType_Type PyULongLongArrType_Type #define NPY_INT128_FMT NPY_LONGLONG_FMT #define NPY_UINT128_FMT NPY_ULONGLONG_FMT # endif # define NPY_MAX_LONGLONG NPY_MAX_INT128 # define NPY_MIN_LONGLONG NPY_MIN_INT128 # define NPY_MAX_ULONGLONG NPY_MAX_UINT128 #elif NPY_BITSOF_LONGLONG == 256 # define NPY_INT256 NPY_LONGLONG # define NPY_UINT256 NPY_ULONGLONG typedef npy_longlong npy_int256; typedef npy_ulonglong npy_uint256; # define PyInt256ScalarObject PyLongLongScalarObject # define PyInt256ArrType_Type PyLongLongArrType_Type # define PyUInt256ScalarObject PyULongLongScalarObject # define PyUInt256ArrType_Type PyULongLongArrType_Type #define NPY_INT256_FMT NPY_LONGLONG_FMT #define NPY_UINT256_FMT NPY_ULONGLONG_FMT # define NPY_MAX_LONGLONG NPY_MAX_INT256 # define NPY_MIN_LONGLONG NPY_MIN_INT256 # define NPY_MAX_ULONGLONG NPY_MAX_UINT256 #endif #if NPY_BITSOF_INT == 8 #ifndef NPY_INT8 #define NPY_INT8 NPY_INT #define NPY_UINT8 NPY_UINT typedef int npy_int8; typedef unsigned int npy_uint8; # define PyInt8ScalarObject PyIntScalarObject # define PyInt8ArrType_Type PyIntArrType_Type # define PyUInt8ScalarObject PyUIntScalarObject # define PyUInt8ArrType_Type PyUIntArrType_Type #define NPY_INT8_FMT NPY_INT_FMT #define NPY_UINT8_FMT NPY_UINT_FMT #endif #elif NPY_BITSOF_INT == 16 #ifndef NPY_INT16 #define NPY_INT16 NPY_INT #define NPY_UINT16 NPY_UINT typedef int npy_int16; typedef unsigned int npy_uint16; # define PyInt16ScalarObject PyIntScalarObject # define PyInt16ArrType_Type PyIntArrType_Type # define PyUInt16ScalarObject PyIntUScalarObject # define PyUInt16ArrType_Type PyIntUArrType_Type #define NPY_INT16_FMT NPY_INT_FMT #define NPY_UINT16_FMT NPY_UINT_FMT #endif #elif NPY_BITSOF_INT == 32 #ifndef NPY_INT32 #define NPY_INT32 NPY_INT #define NPY_UINT32 NPY_UINT typedef int npy_int32; typedef unsigned int npy_uint32; typedef unsigned int npy_ucs4; # define PyInt32ScalarObject PyIntScalarObject # define PyInt32ArrType_Type PyIntArrType_Type # define PyUInt32ScalarObject PyUIntScalarObject # define PyUInt32ArrType_Type PyUIntArrType_Type #define NPY_INT32_FMT NPY_INT_FMT #define NPY_UINT32_FMT NPY_UINT_FMT #endif #elif NPY_BITSOF_INT == 64 #ifndef NPY_INT64 #define NPY_INT64 NPY_INT #define NPY_UINT64 NPY_UINT typedef int npy_int64; typedef unsigned int npy_uint64; # define PyInt64ScalarObject PyIntScalarObject # define PyInt64ArrType_Type PyIntArrType_Type # define PyUInt64ScalarObject PyUIntScalarObject # define PyUInt64ArrType_Type PyUIntArrType_Type #define NPY_INT64_FMT NPY_INT_FMT #define NPY_UINT64_FMT NPY_UINT_FMT # define MyPyLong_FromInt64 PyLong_FromLong # define MyPyLong_AsInt64 PyLong_AsLong #endif #elif NPY_BITSOF_INT == 128 #ifndef NPY_INT128 #define NPY_INT128 NPY_INT #define NPY_UINT128 NPY_UINT typedef int npy_int128; typedef unsigned int npy_uint128; # define PyInt128ScalarObject PyIntScalarObject # define PyInt128ArrType_Type PyIntArrType_Type # define PyUInt128ScalarObject PyUIntScalarObject # define PyUInt128ArrType_Type PyUIntArrType_Type #define NPY_INT128_FMT NPY_INT_FMT #define NPY_UINT128_FMT NPY_UINT_FMT #endif #endif #if NPY_BITSOF_SHORT == 8 #ifndef NPY_INT8 #define NPY_INT8 NPY_SHORT #define NPY_UINT8 NPY_USHORT typedef short npy_int8; typedef unsigned short npy_uint8; # define PyInt8ScalarObject PyShortScalarObject # define PyInt8ArrType_Type PyShortArrType_Type # define PyUInt8ScalarObject PyUShortScalarObject # define PyUInt8ArrType_Type PyUShortArrType_Type #define NPY_INT8_FMT NPY_SHORT_FMT #define NPY_UINT8_FMT NPY_USHORT_FMT #endif #elif NPY_BITSOF_SHORT == 16 #ifndef NPY_INT16 #define NPY_INT16 NPY_SHORT #define NPY_UINT16 NPY_USHORT typedef short npy_int16; typedef unsigned short npy_uint16; # define PyInt16ScalarObject PyShortScalarObject # define PyInt16ArrType_Type PyShortArrType_Type # define PyUInt16ScalarObject PyUShortScalarObject # define PyUInt16ArrType_Type PyUShortArrType_Type #define NPY_INT16_FMT NPY_SHORT_FMT #define NPY_UINT16_FMT NPY_USHORT_FMT #endif #elif NPY_BITSOF_SHORT == 32 #ifndef NPY_INT32 #define NPY_INT32 NPY_SHORT #define NPY_UINT32 NPY_USHORT typedef short npy_int32; typedef unsigned short npy_uint32; typedef unsigned short npy_ucs4; # define PyInt32ScalarObject PyShortScalarObject # define PyInt32ArrType_Type PyShortArrType_Type # define PyUInt32ScalarObject PyUShortScalarObject # define PyUInt32ArrType_Type PyUShortArrType_Type #define NPY_INT32_FMT NPY_SHORT_FMT #define NPY_UINT32_FMT NPY_USHORT_FMT #endif #elif NPY_BITSOF_SHORT == 64 #ifndef NPY_INT64 #define NPY_INT64 NPY_SHORT #define NPY_UINT64 NPY_USHORT typedef short npy_int64; typedef unsigned short npy_uint64; # define PyInt64ScalarObject PyShortScalarObject # define PyInt64ArrType_Type PyShortArrType_Type # define PyUInt64ScalarObject PyUShortScalarObject # define PyUInt64ArrType_Type PyUShortArrType_Type #define NPY_INT64_FMT NPY_SHORT_FMT #define NPY_UINT64_FMT NPY_USHORT_FMT # define MyPyLong_FromInt64 PyLong_FromLong # define MyPyLong_AsInt64 PyLong_AsLong #endif #elif NPY_BITSOF_SHORT == 128 #ifndef NPY_INT128 #define NPY_INT128 NPY_SHORT #define NPY_UINT128 NPY_USHORT typedef short npy_int128; typedef unsigned short npy_uint128; # define PyInt128ScalarObject PyShortScalarObject # define PyInt128ArrType_Type PyShortArrType_Type # define PyUInt128ScalarObject PyUShortScalarObject # define PyUInt128ArrType_Type PyUShortArrType_Type #define NPY_INT128_FMT NPY_SHORT_FMT #define NPY_UINT128_FMT NPY_USHORT_FMT #endif #endif #if NPY_BITSOF_CHAR == 8 #ifndef NPY_INT8 #define NPY_INT8 NPY_BYTE #define NPY_UINT8 NPY_UBYTE typedef signed char npy_int8; typedef unsigned char npy_uint8; # define PyInt8ScalarObject PyByteScalarObject # define PyInt8ArrType_Type PyByteArrType_Type # define PyUInt8ScalarObject PyUByteScalarObject # define PyUInt8ArrType_Type PyUByteArrType_Type #define NPY_INT8_FMT NPY_BYTE_FMT #define NPY_UINT8_FMT NPY_UBYTE_FMT #endif #elif NPY_BITSOF_CHAR == 16 #ifndef NPY_INT16 #define NPY_INT16 NPY_BYTE #define NPY_UINT16 NPY_UBYTE typedef signed char npy_int16; typedef unsigned char npy_uint16; # define PyInt16ScalarObject PyByteScalarObject # define PyInt16ArrType_Type PyByteArrType_Type # define PyUInt16ScalarObject PyUByteScalarObject # define PyUInt16ArrType_Type PyUByteArrType_Type #define NPY_INT16_FMT NPY_BYTE_FMT #define NPY_UINT16_FMT NPY_UBYTE_FMT #endif #elif NPY_BITSOF_CHAR == 32 #ifndef NPY_INT32 #define NPY_INT32 NPY_BYTE #define NPY_UINT32 NPY_UBYTE typedef signed char npy_int32; typedef unsigned char npy_uint32; typedef unsigned char npy_ucs4; # define PyInt32ScalarObject PyByteScalarObject # define PyInt32ArrType_Type PyByteArrType_Type # define PyUInt32ScalarObject PyUByteScalarObject # define PyUInt32ArrType_Type PyUByteArrType_Type #define NPY_INT32_FMT NPY_BYTE_FMT #define NPY_UINT32_FMT NPY_UBYTE_FMT #endif #elif NPY_BITSOF_CHAR == 64 #ifndef NPY_INT64 #define NPY_INT64 NPY_BYTE #define NPY_UINT64 NPY_UBYTE typedef signed char npy_int64; typedef unsigned char npy_uint64; # define PyInt64ScalarObject PyByteScalarObject # define PyInt64ArrType_Type PyByteArrType_Type # define PyUInt64ScalarObject PyUByteScalarObject # define PyUInt64ArrType_Type PyUByteArrType_Type #define NPY_INT64_FMT NPY_BYTE_FMT #define NPY_UINT64_FMT NPY_UBYTE_FMT # define MyPyLong_FromInt64 PyLong_FromLong # define MyPyLong_AsInt64 PyLong_AsLong #endif #elif NPY_BITSOF_CHAR == 128 #ifndef NPY_INT128 #define NPY_INT128 NPY_BYTE #define NPY_UINT128 NPY_UBYTE typedef signed char npy_int128; typedef unsigned char npy_uint128; # define PyInt128ScalarObject PyByteScalarObject # define PyInt128ArrType_Type PyByteArrType_Type # define PyUInt128ScalarObject PyUByteScalarObject # define PyUInt128ArrType_Type PyUByteArrType_Type #define NPY_INT128_FMT NPY_BYTE_FMT #define NPY_UINT128_FMT NPY_UBYTE_FMT #endif #endif #if NPY_BITSOF_DOUBLE == 32 #ifndef NPY_FLOAT32 #define NPY_FLOAT32 NPY_DOUBLE #define NPY_COMPLEX64 NPY_CDOUBLE typedef double npy_float32; typedef npy_cdouble npy_complex64; # define PyFloat32ScalarObject PyDoubleScalarObject # define PyComplex64ScalarObject PyCDoubleScalarObject # define PyFloat32ArrType_Type PyDoubleArrType_Type # define PyComplex64ArrType_Type PyCDoubleArrType_Type #define NPY_FLOAT32_FMT NPY_DOUBLE_FMT #define NPY_COMPLEX64_FMT NPY_CDOUBLE_FMT #endif #elif NPY_BITSOF_DOUBLE == 64 #ifndef NPY_FLOAT64 #define NPY_FLOAT64 NPY_DOUBLE #define NPY_COMPLEX128 NPY_CDOUBLE typedef double npy_float64; typedef npy_cdouble npy_complex128; # define PyFloat64ScalarObject PyDoubleScalarObject # define PyComplex128ScalarObject PyCDoubleScalarObject # define PyFloat64ArrType_Type PyDoubleArrType_Type # define PyComplex128ArrType_Type PyCDoubleArrType_Type #define NPY_FLOAT64_FMT NPY_DOUBLE_FMT #define NPY_COMPLEX128_FMT NPY_CDOUBLE_FMT #endif #elif NPY_BITSOF_DOUBLE == 80 #ifndef NPY_FLOAT80 #define NPY_FLOAT80 NPY_DOUBLE #define NPY_COMPLEX160 NPY_CDOUBLE typedef double npy_float80; typedef npy_cdouble npy_complex160; # define PyFloat80ScalarObject PyDoubleScalarObject # define PyComplex160ScalarObject PyCDoubleScalarObject # define PyFloat80ArrType_Type PyDoubleArrType_Type # define PyComplex160ArrType_Type PyCDoubleArrType_Type #define NPY_FLOAT80_FMT NPY_DOUBLE_FMT #define NPY_COMPLEX160_FMT NPY_CDOUBLE_FMT #endif #elif NPY_BITSOF_DOUBLE == 96 #ifndef NPY_FLOAT96 #define NPY_FLOAT96 NPY_DOUBLE #define NPY_COMPLEX192 NPY_CDOUBLE typedef double npy_float96; typedef npy_cdouble npy_complex192; # define PyFloat96ScalarObject PyDoubleScalarObject # define PyComplex192ScalarObject PyCDoubleScalarObject # define PyFloat96ArrType_Type PyDoubleArrType_Type # define PyComplex192ArrType_Type PyCDoubleArrType_Type #define NPY_FLOAT96_FMT NPY_DOUBLE_FMT #define NPY_COMPLEX192_FMT NPY_CDOUBLE_FMT #endif #elif NPY_BITSOF_DOUBLE == 128 #ifndef NPY_FLOAT128 #define NPY_FLOAT128 NPY_DOUBLE #define NPY_COMPLEX256 NPY_CDOUBLE typedef double npy_float128; typedef npy_cdouble npy_complex256; # define PyFloat128ScalarObject PyDoubleScalarObject # define PyComplex256ScalarObject PyCDoubleScalarObject # define PyFloat128ArrType_Type PyDoubleArrType_Type # define PyComplex256ArrType_Type PyCDoubleArrType_Type #define NPY_FLOAT128_FMT NPY_DOUBLE_FMT #define NPY_COMPLEX256_FMT NPY_CDOUBLE_FMT #endif #endif #if NPY_BITSOF_FLOAT == 32 #ifndef NPY_FLOAT32 #define NPY_FLOAT32 NPY_FLOAT #define NPY_COMPLEX64 NPY_CFLOAT typedef float npy_float32; typedef npy_cfloat npy_complex64; # define PyFloat32ScalarObject PyFloatScalarObject # define PyComplex64ScalarObject PyCFloatScalarObject # define PyFloat32ArrType_Type PyFloatArrType_Type # define PyComplex64ArrType_Type PyCFloatArrType_Type #define NPY_FLOAT32_FMT NPY_FLOAT_FMT #define NPY_COMPLEX64_FMT NPY_CFLOAT_FMT #endif #elif NPY_BITSOF_FLOAT == 64 #ifndef NPY_FLOAT64 #define NPY_FLOAT64 NPY_FLOAT #define NPY_COMPLEX128 NPY_CFLOAT typedef float npy_float64; typedef npy_cfloat npy_complex128; # define PyFloat64ScalarObject PyFloatScalarObject # define PyComplex128ScalarObject PyCFloatScalarObject # define PyFloat64ArrType_Type PyFloatArrType_Type # define PyComplex128ArrType_Type PyCFloatArrType_Type #define NPY_FLOAT64_FMT NPY_FLOAT_FMT #define NPY_COMPLEX128_FMT NPY_CFLOAT_FMT #endif #elif NPY_BITSOF_FLOAT == 80 #ifndef NPY_FLOAT80 #define NPY_FLOAT80 NPY_FLOAT #define NPY_COMPLEX160 NPY_CFLOAT typedef float npy_float80; typedef npy_cfloat npy_complex160; # define PyFloat80ScalarObject PyFloatScalarObject # define PyComplex160ScalarObject PyCFloatScalarObject # define PyFloat80ArrType_Type PyFloatArrType_Type # define PyComplex160ArrType_Type PyCFloatArrType_Type #define NPY_FLOAT80_FMT NPY_FLOAT_FMT #define NPY_COMPLEX160_FMT NPY_CFLOAT_FMT #endif #elif NPY_BITSOF_FLOAT == 96 #ifndef NPY_FLOAT96 #define NPY_FLOAT96 NPY_FLOAT #define NPY_COMPLEX192 NPY_CFLOAT typedef float npy_float96; typedef npy_cfloat npy_complex192; # define PyFloat96ScalarObject PyFloatScalarObject # define PyComplex192ScalarObject PyCFloatScalarObject # define PyFloat96ArrType_Type PyFloatArrType_Type # define PyComplex192ArrType_Type PyCFloatArrType_Type #define NPY_FLOAT96_FMT NPY_FLOAT_FMT #define NPY_COMPLEX192_FMT NPY_CFLOAT_FMT #endif #elif NPY_BITSOF_FLOAT == 128 #ifndef NPY_FLOAT128 #define NPY_FLOAT128 NPY_FLOAT #define NPY_COMPLEX256 NPY_CFLOAT typedef float npy_float128; typedef npy_cfloat npy_complex256; # define PyFloat128ScalarObject PyFloatScalarObject # define PyComplex256ScalarObject PyCFloatScalarObject # define PyFloat128ArrType_Type PyFloatArrType_Type # define PyComplex256ArrType_Type PyCFloatArrType_Type #define NPY_FLOAT128_FMT NPY_FLOAT_FMT #define NPY_COMPLEX256_FMT NPY_CFLOAT_FMT #endif #endif /* half/float16 isn't a floating-point type in C */ #define NPY_FLOAT16 NPY_HALF typedef npy_uint16 npy_half; typedef npy_half npy_float16; #if NPY_BITSOF_LONGDOUBLE == 32 #ifndef NPY_FLOAT32 #define NPY_FLOAT32 NPY_LONGDOUBLE #define NPY_COMPLEX64 NPY_CLONGDOUBLE typedef npy_longdouble npy_float32; typedef npy_clongdouble npy_complex64; # define PyFloat32ScalarObject PyLongDoubleScalarObject # define PyComplex64ScalarObject PyCLongDoubleScalarObject # define PyFloat32ArrType_Type PyLongDoubleArrType_Type # define PyComplex64ArrType_Type PyCLongDoubleArrType_Type #define NPY_FLOAT32_FMT NPY_LONGDOUBLE_FMT #define NPY_COMPLEX64_FMT NPY_CLONGDOUBLE_FMT #endif #elif NPY_BITSOF_LONGDOUBLE == 64 #ifndef NPY_FLOAT64 #define NPY_FLOAT64 NPY_LONGDOUBLE #define NPY_COMPLEX128 NPY_CLONGDOUBLE typedef npy_longdouble npy_float64; typedef npy_clongdouble npy_complex128; # define PyFloat64ScalarObject PyLongDoubleScalarObject # define PyComplex128ScalarObject PyCLongDoubleScalarObject # define PyFloat64ArrType_Type PyLongDoubleArrType_Type # define PyComplex128ArrType_Type PyCLongDoubleArrType_Type #define NPY_FLOAT64_FMT NPY_LONGDOUBLE_FMT #define NPY_COMPLEX128_FMT NPY_CLONGDOUBLE_FMT #endif #elif NPY_BITSOF_LONGDOUBLE == 80 #ifndef NPY_FLOAT80 #define NPY_FLOAT80 NPY_LONGDOUBLE #define NPY_COMPLEX160 NPY_CLONGDOUBLE typedef npy_longdouble npy_float80; typedef npy_clongdouble npy_complex160; # define PyFloat80ScalarObject PyLongDoubleScalarObject # define PyComplex160ScalarObject PyCLongDoubleScalarObject # define PyFloat80ArrType_Type PyLongDoubleArrType_Type # define PyComplex160ArrType_Type PyCLongDoubleArrType_Type #define NPY_FLOAT80_FMT NPY_LONGDOUBLE_FMT #define NPY_COMPLEX160_FMT NPY_CLONGDOUBLE_FMT #endif #elif NPY_BITSOF_LONGDOUBLE == 96 #ifndef NPY_FLOAT96 #define NPY_FLOAT96 NPY_LONGDOUBLE #define NPY_COMPLEX192 NPY_CLONGDOUBLE typedef npy_longdouble npy_float96; typedef npy_clongdouble npy_complex192; # define PyFloat96ScalarObject PyLongDoubleScalarObject # define PyComplex192ScalarObject PyCLongDoubleScalarObject # define PyFloat96ArrType_Type PyLongDoubleArrType_Type # define PyComplex192ArrType_Type PyCLongDoubleArrType_Type #define NPY_FLOAT96_FMT NPY_LONGDOUBLE_FMT #define NPY_COMPLEX192_FMT NPY_CLONGDOUBLE_FMT #endif #elif NPY_BITSOF_LONGDOUBLE == 128 #ifndef NPY_FLOAT128 #define NPY_FLOAT128 NPY_LONGDOUBLE #define NPY_COMPLEX256 NPY_CLONGDOUBLE typedef npy_longdouble npy_float128; typedef npy_clongdouble npy_complex256; # define PyFloat128ScalarObject PyLongDoubleScalarObject # define PyComplex256ScalarObject PyCLongDoubleScalarObject # define PyFloat128ArrType_Type PyLongDoubleArrType_Type # define PyComplex256ArrType_Type PyCLongDoubleArrType_Type #define NPY_FLOAT128_FMT NPY_LONGDOUBLE_FMT #define NPY_COMPLEX256_FMT NPY_CLONGDOUBLE_FMT #endif #elif NPY_BITSOF_LONGDOUBLE == 256 #define NPY_FLOAT256 NPY_LONGDOUBLE #define NPY_COMPLEX512 NPY_CLONGDOUBLE typedef npy_longdouble npy_float256; typedef npy_clongdouble npy_complex512; # define PyFloat256ScalarObject PyLongDoubleScalarObject # define PyComplex512ScalarObject PyCLongDoubleScalarObject # define PyFloat256ArrType_Type PyLongDoubleArrType_Type # define PyComplex512ArrType_Type PyCLongDoubleArrType_Type #define NPY_FLOAT256_FMT NPY_LONGDOUBLE_FMT #define NPY_COMPLEX512_FMT NPY_CLONGDOUBLE_FMT #endif /* datetime typedefs */ typedef npy_int64 npy_timedelta; typedef npy_int64 npy_datetime; #define NPY_DATETIME_FMT NPY_INT64_FMT #define NPY_TIMEDELTA_FMT NPY_INT64_FMT /* End of typedefs for numarray style bit-width names */ #endif numpy-1.8.2/numpy/core/include/numpy/npy_cpu.h0000664000175100017510000000735412370216243022556 0ustar vagrantvagrant00000000000000/* * This set (target) cpu specific macros: * - Possible values: * NPY_CPU_X86 * NPY_CPU_AMD64 * NPY_CPU_PPC * NPY_CPU_PPC64 * NPY_CPU_SPARC * NPY_CPU_S390 * NPY_CPU_IA64 * NPY_CPU_HPPA * NPY_CPU_ALPHA * NPY_CPU_ARMEL * NPY_CPU_ARMEB * NPY_CPU_SH_LE * NPY_CPU_SH_BE */ #ifndef _NPY_CPUARCH_H_ #define _NPY_CPUARCH_H_ #include "numpyconfig.h" #if defined( __i386__ ) || defined(i386) || defined(_M_IX86) /* * __i386__ is defined by gcc and Intel compiler on Linux, * _M_IX86 by VS compiler, * i386 by Sun compilers on opensolaris at least */ #define NPY_CPU_X86 #elif defined(__x86_64__) || defined(__amd64__) || defined(__x86_64) || defined(_M_AMD64) /* * both __x86_64__ and __amd64__ are defined by gcc * __x86_64 defined by sun compiler on opensolaris at least * _M_AMD64 defined by MS compiler */ #define NPY_CPU_AMD64 #elif defined(__ppc__) || defined(__powerpc__) || defined(_ARCH_PPC) /* * __ppc__ is defined by gcc, I remember having seen __powerpc__ once, * but can't find it ATM * _ARCH_PPC is used by at least gcc on AIX */ #define NPY_CPU_PPC #elif defined(__ppc64__) #define NPY_CPU_PPC64 #elif defined(__sparc__) || defined(__sparc) /* __sparc__ is defined by gcc and Forte (e.g. Sun) compilers */ #define NPY_CPU_SPARC #elif defined(__s390__) #define NPY_CPU_S390 #elif defined(__ia64) #define NPY_CPU_IA64 #elif defined(__hppa) #define NPY_CPU_HPPA #elif defined(__alpha__) #define NPY_CPU_ALPHA #elif defined(__arm__) && defined(__ARMEL__) #define NPY_CPU_ARMEL #elif defined(__arm__) && defined(__ARMEB__) #define NPY_CPU_ARMEB #elif defined(__sh__) && defined(__LITTLE_ENDIAN__) #define NPY_CPU_SH_LE #elif defined(__sh__) && defined(__BIG_ENDIAN__) #define NPY_CPU_SH_BE #elif defined(__MIPSEL__) #define NPY_CPU_MIPSEL #elif defined(__MIPSEB__) #define NPY_CPU_MIPSEB #elif defined(__aarch64__) #define NPY_CPU_AARCH64 #elif defined(__mc68000__) #define NPY_CPU_M68K #else #error Unknown CPU, please report this to numpy maintainers with \ information about your platform (OS, CPU and compiler) #endif /* This "white-lists" the architectures that we know don't require pointer alignment. We white-list, since the memcpy version will work everywhere, whereas assignment will only work where pointer dereferencing doesn't require alignment. TODO: There may be more architectures we can white list. */ #if defined(NPY_CPU_X86) || defined(NPY_CPU_AMD64) #define NPY_COPY_PYOBJECT_PTR(dst, src) (*((PyObject **)(dst)) = *((PyObject **)(src))) #else #if NPY_SIZEOF_PY_INTPTR_T == 4 #define NPY_COPY_PYOBJECT_PTR(dst, src) \ ((char*)(dst))[0] = ((char*)(src))[0]; \ ((char*)(dst))[1] = ((char*)(src))[1]; \ ((char*)(dst))[2] = ((char*)(src))[2]; \ ((char*)(dst))[3] = ((char*)(src))[3]; #elif NPY_SIZEOF_PY_INTPTR_T == 8 #define NPY_COPY_PYOBJECT_PTR(dst, src) \ ((char*)(dst))[0] = ((char*)(src))[0]; \ ((char*)(dst))[1] = ((char*)(src))[1]; \ ((char*)(dst))[2] = ((char*)(src))[2]; \ ((char*)(dst))[3] = ((char*)(src))[3]; \ ((char*)(dst))[4] = ((char*)(src))[4]; \ ((char*)(dst))[5] = ((char*)(src))[5]; \ ((char*)(dst))[6] = ((char*)(src))[6]; \ ((char*)(dst))[7] = ((char*)(src))[7]; #else #error Unknown architecture, please report this to numpy maintainers with \ information about your platform (OS, CPU and compiler) #endif #endif #endif numpy-1.8.2/numpy/core/include/numpy/old_defines.h0000664000175100017510000001424212370216242023345 0ustar vagrantvagrant00000000000000/* This header is deprecated as of NumPy 1.7 */ #ifndef OLD_DEFINES_H #define OLD_DEFINES_H #if defined(NPY_NO_DEPRECATED_API) && NPY_NO_DEPRECATED_API >= NPY_1_7_API_VERSION #error The header "old_defines.h" is deprecated as of NumPy 1.7. #endif #define NDARRAY_VERSION NPY_VERSION #define PyArray_MIN_BUFSIZE NPY_MIN_BUFSIZE #define PyArray_MAX_BUFSIZE NPY_MAX_BUFSIZE #define PyArray_BUFSIZE NPY_BUFSIZE #define PyArray_PRIORITY NPY_PRIORITY #define PyArray_SUBTYPE_PRIORITY NPY_PRIORITY #define PyArray_NUM_FLOATTYPE NPY_NUM_FLOATTYPE #define NPY_MAX PyArray_MAX #define NPY_MIN PyArray_MIN #define PyArray_TYPES NPY_TYPES #define PyArray_BOOL NPY_BOOL #define PyArray_BYTE NPY_BYTE #define PyArray_UBYTE NPY_UBYTE #define PyArray_SHORT NPY_SHORT #define PyArray_USHORT NPY_USHORT #define PyArray_INT NPY_INT #define PyArray_UINT NPY_UINT #define PyArray_LONG NPY_LONG #define PyArray_ULONG NPY_ULONG #define PyArray_LONGLONG NPY_LONGLONG #define PyArray_ULONGLONG NPY_ULONGLONG #define PyArray_HALF NPY_HALF #define PyArray_FLOAT NPY_FLOAT #define PyArray_DOUBLE NPY_DOUBLE #define PyArray_LONGDOUBLE NPY_LONGDOUBLE #define PyArray_CFLOAT NPY_CFLOAT #define PyArray_CDOUBLE NPY_CDOUBLE #define PyArray_CLONGDOUBLE NPY_CLONGDOUBLE #define PyArray_OBJECT NPY_OBJECT #define PyArray_STRING NPY_STRING #define PyArray_UNICODE NPY_UNICODE #define PyArray_VOID NPY_VOID #define PyArray_DATETIME NPY_DATETIME #define PyArray_TIMEDELTA NPY_TIMEDELTA #define PyArray_NTYPES NPY_NTYPES #define PyArray_NOTYPE NPY_NOTYPE #define PyArray_CHAR NPY_CHAR #define PyArray_USERDEF NPY_USERDEF #define PyArray_NUMUSERTYPES NPY_NUMUSERTYPES #define PyArray_INTP NPY_INTP #define PyArray_UINTP NPY_UINTP #define PyArray_INT8 NPY_INT8 #define PyArray_UINT8 NPY_UINT8 #define PyArray_INT16 NPY_INT16 #define PyArray_UINT16 NPY_UINT16 #define PyArray_INT32 NPY_INT32 #define PyArray_UINT32 NPY_UINT32 #ifdef NPY_INT64 #define PyArray_INT64 NPY_INT64 #define PyArray_UINT64 NPY_UINT64 #endif #ifdef NPY_INT128 #define PyArray_INT128 NPY_INT128 #define PyArray_UINT128 NPY_UINT128 #endif #ifdef NPY_FLOAT16 #define PyArray_FLOAT16 NPY_FLOAT16 #define PyArray_COMPLEX32 NPY_COMPLEX32 #endif #ifdef NPY_FLOAT80 #define PyArray_FLOAT80 NPY_FLOAT80 #define PyArray_COMPLEX160 NPY_COMPLEX160 #endif #ifdef NPY_FLOAT96 #define PyArray_FLOAT96 NPY_FLOAT96 #define PyArray_COMPLEX192 NPY_COMPLEX192 #endif #ifdef NPY_FLOAT128 #define PyArray_FLOAT128 NPY_FLOAT128 #define PyArray_COMPLEX256 NPY_COMPLEX256 #endif #define PyArray_FLOAT32 NPY_FLOAT32 #define PyArray_COMPLEX64 NPY_COMPLEX64 #define PyArray_FLOAT64 NPY_FLOAT64 #define PyArray_COMPLEX128 NPY_COMPLEX128 #define PyArray_TYPECHAR NPY_TYPECHAR #define PyArray_BOOLLTR NPY_BOOLLTR #define PyArray_BYTELTR NPY_BYTELTR #define PyArray_UBYTELTR NPY_UBYTELTR #define PyArray_SHORTLTR NPY_SHORTLTR #define PyArray_USHORTLTR NPY_USHORTLTR #define PyArray_INTLTR NPY_INTLTR #define PyArray_UINTLTR NPY_UINTLTR #define PyArray_LONGLTR NPY_LONGLTR #define PyArray_ULONGLTR NPY_ULONGLTR #define PyArray_LONGLONGLTR NPY_LONGLONGLTR #define PyArray_ULONGLONGLTR NPY_ULONGLONGLTR #define PyArray_HALFLTR NPY_HALFLTR #define PyArray_FLOATLTR NPY_FLOATLTR #define PyArray_DOUBLELTR NPY_DOUBLELTR #define PyArray_LONGDOUBLELTR NPY_LONGDOUBLELTR #define PyArray_CFLOATLTR NPY_CFLOATLTR #define PyArray_CDOUBLELTR NPY_CDOUBLELTR #define PyArray_CLONGDOUBLELTR NPY_CLONGDOUBLELTR #define PyArray_OBJECTLTR NPY_OBJECTLTR #define PyArray_STRINGLTR NPY_STRINGLTR #define PyArray_STRINGLTR2 NPY_STRINGLTR2 #define PyArray_UNICODELTR NPY_UNICODELTR #define PyArray_VOIDLTR NPY_VOIDLTR #define PyArray_DATETIMELTR NPY_DATETIMELTR #define PyArray_TIMEDELTALTR NPY_TIMEDELTALTR #define PyArray_CHARLTR NPY_CHARLTR #define PyArray_INTPLTR NPY_INTPLTR #define PyArray_UINTPLTR NPY_UINTPLTR #define PyArray_GENBOOLLTR NPY_GENBOOLLTR #define PyArray_SIGNEDLTR NPY_SIGNEDLTR #define PyArray_UNSIGNEDLTR NPY_UNSIGNEDLTR #define PyArray_FLOATINGLTR NPY_FLOATINGLTR #define PyArray_COMPLEXLTR NPY_COMPLEXLTR #define PyArray_QUICKSORT NPY_QUICKSORT #define PyArray_HEAPSORT NPY_HEAPSORT #define PyArray_MERGESORT NPY_MERGESORT #define PyArray_SORTKIND NPY_SORTKIND #define PyArray_NSORTS NPY_NSORTS #define PyArray_NOSCALAR NPY_NOSCALAR #define PyArray_BOOL_SCALAR NPY_BOOL_SCALAR #define PyArray_INTPOS_SCALAR NPY_INTPOS_SCALAR #define PyArray_INTNEG_SCALAR NPY_INTNEG_SCALAR #define PyArray_FLOAT_SCALAR NPY_FLOAT_SCALAR #define PyArray_COMPLEX_SCALAR NPY_COMPLEX_SCALAR #define PyArray_OBJECT_SCALAR NPY_OBJECT_SCALAR #define PyArray_SCALARKIND NPY_SCALARKIND #define PyArray_NSCALARKINDS NPY_NSCALARKINDS #define PyArray_ANYORDER NPY_ANYORDER #define PyArray_CORDER NPY_CORDER #define PyArray_FORTRANORDER NPY_FORTRANORDER #define PyArray_ORDER NPY_ORDER #define PyDescr_ISBOOL PyDataType_ISBOOL #define PyDescr_ISUNSIGNED PyDataType_ISUNSIGNED #define PyDescr_ISSIGNED PyDataType_ISSIGNED #define PyDescr_ISINTEGER PyDataType_ISINTEGER #define PyDescr_ISFLOAT PyDataType_ISFLOAT #define PyDescr_ISNUMBER PyDataType_ISNUMBER #define PyDescr_ISSTRING PyDataType_ISSTRING #define PyDescr_ISCOMPLEX PyDataType_ISCOMPLEX #define PyDescr_ISPYTHON PyDataType_ISPYTHON #define PyDescr_ISFLEXIBLE PyDataType_ISFLEXIBLE #define PyDescr_ISUSERDEF PyDataType_ISUSERDEF #define PyDescr_ISEXTENDED PyDataType_ISEXTENDED #define PyDescr_ISOBJECT PyDataType_ISOBJECT #define PyDescr_HASFIELDS PyDataType_HASFIELDS #define PyArray_LITTLE NPY_LITTLE #define PyArray_BIG NPY_BIG #define PyArray_NATIVE NPY_NATIVE #define PyArray_SWAP NPY_SWAP #define PyArray_IGNORE NPY_IGNORE #define PyArray_NATBYTE NPY_NATBYTE #define PyArray_OPPBYTE NPY_OPPBYTE #define PyArray_MAX_ELSIZE NPY_MAX_ELSIZE #define PyArray_USE_PYMEM NPY_USE_PYMEM #define PyArray_RemoveLargest PyArray_RemoveSmallest #define PyArray_UCS4 npy_ucs4 #endif numpy-1.8.2/numpy/core/memmap.py0000664000175100017510000002341312370216243017755 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function __all__ = ['memmap'] import warnings import sys import numpy as np from .numeric import uint8, ndarray, dtype from numpy.compat import long, basestring dtypedescr = dtype valid_filemodes = ["r", "c", "r+", "w+"] writeable_filemodes = ["r+", "w+"] mode_equivalents = { "readonly":"r", "copyonwrite":"c", "readwrite":"r+", "write":"w+" } class memmap(ndarray): """ Create a memory-map to an array stored in a *binary* file on disk. Memory-mapped files are used for accessing small segments of large files on disk, without reading the entire file into memory. Numpy's memmap's are array-like objects. This differs from Python's ``mmap`` module, which uses file-like objects. This subclass of ndarray has some unpleasant interactions with some operations, because it doesn't quite fit properly as a subclass. An alternative to using this subclass is to create the ``mmap`` object yourself, then create an ndarray with ndarray.__new__ directly, passing the object created in its 'buffer=' parameter. This class may at some point be turned into a factory function which returns a view into an mmap buffer. Parameters ---------- filename : str or file-like object The file name or file object to be used as the array data buffer. dtype : data-type, optional The data-type used to interpret the file contents. Default is `uint8`. mode : {'r+', 'r', 'w+', 'c'}, optional The file is opened in this mode: +------+-------------------------------------------------------------+ | 'r' | Open existing file for reading only. | +------+-------------------------------------------------------------+ | 'r+' | Open existing file for reading and writing. | +------+-------------------------------------------------------------+ | 'w+' | Create or overwrite existing file for reading and writing. | +------+-------------------------------------------------------------+ | 'c' | Copy-on-write: assignments affect data in memory, but | | | changes are not saved to disk. The file on disk is | | | read-only. | +------+-------------------------------------------------------------+ Default is 'r+'. offset : int, optional In the file, array data starts at this offset. Since `offset` is measured in bytes, it should normally be a multiple of the byte-size of `dtype`. When ``mode != 'r'``, even positive offsets beyond end of file are valid; The file will be extended to accommodate the additional data. The default offset is 0. shape : tuple, optional The desired shape of the array. If ``mode == 'r'`` and the number of remaining bytes after `offset` is not a multiple of the byte-size of `dtype`, you must specify `shape`. By default, the returned array will be 1-D with the number of elements determined by file size and data-type. order : {'C', 'F'}, optional Specify the order of the ndarray memory layout: C (row-major) or Fortran (column-major). This only has an effect if the shape is greater than 1-D. The default order is 'C'. Attributes ---------- filename : str Path to the mapped file. offset : int Offset position in the file. mode : str File mode. 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 changes to disk before removing the object. Notes ----- The memmap object can be used anywhere an ndarray is accepted. Given a memmap ``fp``, ``isinstance(fp, numpy.ndarray)`` returns ``True``. Memory-mapped arrays use the Python memory-map object which (prior to Python 2.5) does not allow files to be larger than a certain size depending on the platform. This size is always < 2GB even on 64-bit systems. Examples -------- >>> data = np.arange(12, dtype='float32') >>> data.resize((3,4)) This example uses a temporary file so that doctest doesn't write files to your directory. You would use a 'normal' filename. >>> from tempfile import mkdtemp >>> import os.path as path >>> filename = path.join(mkdtemp(), 'newfile.dat') Create a memmap with dtype and shape that matches our data: >>> fp = np.memmap(filename, dtype='float32', mode='w+', shape=(3,4)) >>> fp memmap([[ 0., 0., 0., 0.], [ 0., 0., 0., 0.], [ 0., 0., 0., 0.]], dtype=float32) Write data to memmap array: >>> fp[:] = data[:] >>> fp memmap([[ 0., 1., 2., 3.], [ 4., 5., 6., 7.], [ 8., 9., 10., 11.]], dtype=float32) >>> fp.filename == path.abspath(filename) True Deletion flushes memory changes to disk before removing the object: >>> del fp Load the memmap and verify data was stored: >>> newfp = np.memmap(filename, dtype='float32', mode='r', shape=(3,4)) >>> newfp memmap([[ 0., 1., 2., 3.], [ 4., 5., 6., 7.], [ 8., 9., 10., 11.]], dtype=float32) Read-only memmap: >>> fpr = np.memmap(filename, dtype='float32', mode='r', shape=(3,4)) >>> fpr.flags.writeable False Copy-on-write memmap: >>> fpc = np.memmap(filename, dtype='float32', mode='c', shape=(3,4)) >>> fpc.flags.writeable True It's possible to assign to copy-on-write array, but values are only written into the memory copy of the array, and not written to disk: >>> fpc memmap([[ 0., 1., 2., 3.], [ 4., 5., 6., 7.], [ 8., 9., 10., 11.]], dtype=float32) >>> fpc[0,:] = 0 >>> fpc memmap([[ 0., 0., 0., 0.], [ 4., 5., 6., 7.], [ 8., 9., 10., 11.]], dtype=float32) File on disk is unchanged: >>> fpr memmap([[ 0., 1., 2., 3.], [ 4., 5., 6., 7.], [ 8., 9., 10., 11.]], dtype=float32) Offset into a memmap: >>> fpo = np.memmap(filename, dtype='float32', mode='r', offset=16) >>> fpo memmap([ 4., 5., 6., 7., 8., 9., 10., 11.], dtype=float32) """ __array_priority__ = -100.0 def __new__(subtype, filename, dtype=uint8, mode='r+', offset=0, shape=None, order='C'): # Import here to minimize 'import numpy' overhead import mmap import os.path try: mode = mode_equivalents[mode] except KeyError: if mode not in valid_filemodes: raise ValueError("mode must be one of %s" % (valid_filemodes + list(mode_equivalents.keys()))) if hasattr(filename, 'read'): fid = filename own_file = False else: fid = open(filename, (mode == 'c' and 'r' or mode)+'b') own_file = True if (mode == 'w+') and shape is None: raise ValueError("shape must be given") fid.seek(0, 2) flen = fid.tell() descr = dtypedescr(dtype) _dbytes = descr.itemsize if shape is None: bytes = flen - offset if (bytes % _dbytes): fid.close() raise ValueError("Size of available data is not a " "multiple of the data-type size.") size = bytes // _dbytes shape = (size,) else: if not isinstance(shape, tuple): shape = (shape,) size = 1 for k in shape: size *= k bytes = long(offset + size*_dbytes) if mode == 'w+' or (mode == 'r+' and flen < bytes): fid.seek(bytes - 1, 0) fid.write(np.compat.asbytes('\0')) fid.flush() if mode == 'c': acc = mmap.ACCESS_COPY elif mode == 'r': acc = mmap.ACCESS_READ else: acc = mmap.ACCESS_WRITE start = offset - offset % mmap.ALLOCATIONGRANULARITY bytes -= start offset -= start mm = mmap.mmap(fid.fileno(), bytes, access=acc, offset=start) self = ndarray.__new__(subtype, shape, dtype=descr, buffer=mm, offset=offset, order=order) self._mmap = mm self.offset = offset self.mode = mode if isinstance(filename, basestring): self.filename = os.path.abspath(filename) # py3 returns int for TemporaryFile().name elif (hasattr(filename, "name") and isinstance(filename.name, basestring)): self.filename = os.path.abspath(filename.name) # same as memmap copies (e.g. memmap + 1) else: self.filename = None if own_file: fid.close() return self def __array_finalize__(self, obj): if hasattr(obj, '_mmap') and np.may_share_memory(self, obj): self._mmap = obj._mmap self.filename = obj.filename self.offset = obj.offset self.mode = obj.mode else: self._mmap = None self.filename = None self.offset = None self.mode = None def flush(self): """ Write any changes in the array to the file on disk. For further information, see `memmap`. Parameters ---------- None See Also -------- memmap """ if self.base is not None and hasattr(self.base, 'flush'): self.base.flush() numpy-1.8.2/numpy/core/tests/0000775000175100017510000000000012371375430017273 5ustar vagrantvagrant00000000000000numpy-1.8.2/numpy/core/tests/test_scalarprint.py0000664000175100017510000000162512370216242023224 0ustar vagrantvagrant00000000000000# -*- coding: utf-8 -*- """ Test printing of scalar types. """ from __future__ import division, absolute_import, print_function import numpy as np from numpy.testing import TestCase, assert_, run_module_suite class TestRealScalars(TestCase): def test_str(self): svals = [0.0, -0.0, 1, -1, np.inf, -np.inf, np.nan] styps = [np.float16, np.float32, np.float64, np.longdouble] actual = [str(f(c)) for c in svals for f in styps] wanted = [ '0.0', '0.0', '0.0', '0.0', '-0.0', '-0.0', '-0.0', '-0.0', '1.0', '1.0', '1.0', '1.0', '-1.0', '-1.0', '-1.0', '-1.0', 'inf', 'inf', 'inf', 'inf', '-inf', '-inf', '-inf', '-inf', 'nan', 'nan', 'nan', 'nan'] for res, val in zip(actual, wanted): assert_(res == val) if __name__ == "__main__": run_module_suite() numpy-1.8.2/numpy/core/tests/test_records.py0000664000175100017510000001424412370216242022344 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function from os import path import numpy as np from numpy.testing import * from numpy.compat import asbytes, asunicode import warnings import collections import pickle class TestFromrecords(TestCase): def test_fromrecords(self): r = np.rec.fromrecords([[456, 'dbe', 1.2], [2, 'de', 1.3]], names='col1,col2,col3') assert_equal(r[0].item(), (456, 'dbe', 1.2)) def test_method_array(self): r = np.rec.array(asbytes('abcdefg') * 100, formats='i2,a3,i4', shape=3, byteorder='big') assert_equal(r[1].item(), (25444, asbytes('efg'), 1633837924)) def test_method_array2(self): r = np.rec.array([(1, 11, 'a'), (2, 22, 'b'), (3, 33, 'c'), (4, 44, 'd'), (5, 55, 'ex'), (6, 66, 'f'), (7, 77, 'g')], formats='u1,f4,a1') assert_equal(r[1].item(), (2, 22.0, asbytes('b'))) def test_recarray_slices(self): r = np.rec.array([(1, 11, 'a'), (2, 22, 'b'), (3, 33, 'c'), (4, 44, 'd'), (5, 55, 'ex'), (6, 66, 'f'), (7, 77, 'g')], formats='u1,f4,a1') assert_equal(r[1::2][1].item(), (4, 44.0, asbytes('d'))) def test_recarray_fromarrays(self): x1 = np.array([1, 2, 3, 4]) x2 = np.array(['a', 'dd', 'xyz', '12']) x3 = np.array([1.1, 2, 3, 4]) r = np.rec.fromarrays([x1, x2, x3], names='a,b,c') assert_equal(r[1].item(), (2, 'dd', 2.0)) x1[1] = 34 assert_equal(r.a, np.array([1, 2, 3, 4])) def test_recarray_fromfile(self): data_dir = path.join(path.dirname(__file__), 'data') filename = path.join(data_dir, 'recarray_from_file.fits') fd = open(filename, 'rb') fd.seek(2880 * 2) r = np.rec.fromfile(fd, formats='f8,i4,a5', shape=3, byteorder='big') fd.seek(2880 * 2) r = np.rec.array(fd, formats='f8,i4,a5', shape=3, byteorder='big') fd.close() def test_recarray_from_obj(self): count = 10 a = np.zeros(count, dtype='O') b = np.zeros(count, dtype='f8') c = np.zeros(count, dtype='f8') for i in range(len(a)): a[i] = list(range(1, 10)) mine = np.rec.fromarrays([a, b, c], names='date,data1,data2') for i in range(len(a)): assert_((mine.date[i] == list(range(1, 10)))) assert_((mine.data1[i] == 0.0)) assert_((mine.data2[i] == 0.0)) def test_recarray_from_repr(self): x = np.rec.array([ (1, 2)], dtype=[('a', np.int8), ('b', np.int8)]) y = eval("np." + repr(x)) assert_(isinstance(y, np.recarray)) assert_equal(y, x) def test_recarray_from_names(self): ra = np.rec.array([ (1, 'abc', 3.7000002861022949, 0), (2, 'xy', 6.6999998092651367, 1), (0, ' ', 0.40000000596046448, 0)], names='c1, c2, c3, c4') pa = np.rec.fromrecords([ (1, 'abc', 3.7000002861022949, 0), (2, 'xy', 6.6999998092651367, 1), (0, ' ', 0.40000000596046448, 0)], names='c1, c2, c3, c4') assert_(ra.dtype == pa.dtype) assert_(ra.shape == pa.shape) for k in range(len(ra)): assert_(ra[k].item() == pa[k].item()) def test_recarray_conflict_fields(self): ra = np.rec.array([(1, 'abc', 2.3), (2, 'xyz', 4.2), (3, 'wrs', 1.3)], names='field, shape, mean') ra.mean = [1.1, 2.2, 3.3] assert_array_almost_equal(ra['mean'], [1.1, 2.2, 3.3]) assert_(type(ra.mean) is type(ra.var)) ra.shape = (1, 3) assert_(ra.shape == (1, 3)) ra.shape = ['A', 'B', 'C'] assert_array_equal(ra['shape'], [['A', 'B', 'C']]) ra.field = 5 assert_array_equal(ra['field'], [[5, 5, 5]]) assert_(isinstance(ra.field, collections.Callable)) def test_fromrecords_with_explicit_dtype(self): a = np.rec.fromrecords([(1, 'a'), (2, 'bbb')], dtype=[('a', int), ('b', np.object)]) assert_equal(a.a, [1, 2]) assert_equal(a[0].a, 1) assert_equal(a.b, ['a', 'bbb']) assert_equal(a[-1].b, 'bbb') # ndtype = np.dtype([('a', int), ('b', np.object)]) a = np.rec.fromrecords([(1, 'a'), (2, 'bbb')], dtype=ndtype) assert_equal(a.a, [1, 2]) assert_equal(a[0].a, 1) assert_equal(a.b, ['a', 'bbb']) assert_equal(a[-1].b, 'bbb') class TestRecord(TestCase): def setUp(self): self.data = np.rec.fromrecords([(1, 2, 3), (4, 5, 6)], dtype=[("col1", "= (2, 7, 5): # This test fails for earlier versions of Python. # Evidently a bug got fixed in 2.7.5. dat = np.array(_buffer('1.0'), dtype=np.float64) assert_equal(dat, [49.0, 46.0, 48.0]) assert_(dat.dtype.type is np.float64) dat = np.array(_buffer(b'1.0')) assert_equal(dat, [49, 46, 48]) assert_(dat.dtype.type is np.uint8) # test memoryview, new version of buffer _memoryview = builtins.get("memoryview") if _memoryview: dat = np.array(_memoryview(b'1.0'), dtype=np.float64) assert_equal(dat, [49.0, 46.0, 48.0]) assert_(dat.dtype.type is np.float64) dat = np.array(_memoryview(b'1.0')) assert_equal(dat, [49, 46, 48]) assert_(dat.dtype.type is np.uint8) # test array interface a = np.array(100.0, dtype=np.float64) o = type("o", (object,), dict(__array_interface__=a.__array_interface__)) assert_equal(np.array(o, dtype=np.float64), a) # test array_struct interface a = np.array([(1, 4.0, 'Hello'), (2, 6.0, 'World')], dtype=[('f0', int), ('f1', float), ('f2', str)]) o = type("o", (object,), dict(__array_struct__=a.__array_struct__)) ## wasn't what I expected... is np.array(o) supposed to equal a ? ## instead we get a array([...], dtype=">V18") assert_equal(str(np.array(o).data), str(a.data)) # test array o = type("o", (object,), dict(__array__=lambda *x: np.array(100.0, dtype=np.float64)))() assert_equal(np.array(o, dtype=np.float64), np.array(100.0, np.float64)) # test recursion nested = 1.5 for i in range(np.MAXDIMS): nested = [nested] # no error np.array(nested) # Exceeds recursion limit assert_raises(ValueError, np.array, [nested], dtype=np.float64) # Try with lists... assert_equal(np.array([None] * 10, dtype=np.float64), np.empty((10,), dtype=np.float64) + np.nan) assert_equal(np.array([[None]] * 10, dtype=np.float64), np.empty((10, 1), dtype=np.float64) + np.nan) assert_equal(np.array([[None] * 10], dtype=np.float64), np.empty((1, 10), dtype=np.float64) + np.nan) assert_equal(np.array([[None] * 10] * 10, dtype=np.float64), np.empty((10, 10), dtype=np.float64) + np.nan) assert_equal(np.array([1.0] * 10, dtype=np.float64), np.ones((10,), dtype=np.float64)) assert_equal(np.array([[1.0]] * 10, dtype=np.float64), np.ones((10, 1), dtype=np.float64)) assert_equal(np.array([[1.0] * 10], dtype=np.float64), np.ones((1, 10), dtype=np.float64)) assert_equal(np.array([[1.0] * 10] * 10, dtype=np.float64), np.ones((10, 10), dtype=np.float64)) # Try with tuples assert_equal(np.array((None,) * 10, dtype=np.float64), np.empty((10,), dtype=np.float64) + np.nan) assert_equal(np.array([(None,)] * 10, dtype=np.float64), np.empty((10, 1), dtype=np.float64) + np.nan) assert_equal(np.array([(None,) * 10], dtype=np.float64), np.empty((1, 10), dtype=np.float64) + np.nan) assert_equal(np.array([(None,) * 10] * 10, dtype=np.float64), np.empty((10, 10), dtype=np.float64) + np.nan) assert_equal(np.array((1.0,) * 10, dtype=np.float64), np.ones((10,), dtype=np.float64)) assert_equal(np.array([(1.0,)] * 10, dtype=np.float64), np.ones((10, 1), dtype=np.float64)) assert_equal(np.array([(1.0,) * 10], dtype=np.float64), np.ones((1, 10), dtype=np.float64)) assert_equal(np.array([(1.0,) * 10] * 10, dtype=np.float64), np.ones((10, 10), dtype=np.float64)) def test_fastCopyAndTranspose(): # 0D array a = np.array(2) b = np.fastCopyAndTranspose(a) assert_equal(b, a.T) assert_(b.flags.owndata) # 1D array a = np.array([3, 2, 7, 0]) b = np.fastCopyAndTranspose(a) assert_equal(b, a.T) assert_(b.flags.owndata) # 2D array a = np.arange(6).reshape(2, 3) b = np.fastCopyAndTranspose(a) assert_equal(b, a.T) assert_(b.flags.owndata) def test_array_astype(): a = np.arange(6, dtype='f4').reshape(2, 3) # Default behavior: allows unsafe casts, keeps memory layout, # always copies. b = a.astype('i4') assert_equal(a, b) assert_equal(b.dtype, np.dtype('i4')) assert_equal(a.strides, b.strides) b = a.T.astype('i4') assert_equal(a.T, b) assert_equal(b.dtype, np.dtype('i4')) assert_equal(a.T.strides, b.strides) b = a.astype('f4') assert_equal(a, b) assert_(not (a is b)) # copy=False parameter can sometimes skip a copy b = a.astype('f4', copy=False) assert_(a is b) # order parameter allows overriding of the memory layout, # forcing a copy if the layout is wrong b = a.astype('f4', order='F', copy=False) assert_equal(a, b) assert_(not (a is b)) assert_(b.flags.f_contiguous) b = a.astype('f4', order='C', copy=False) assert_equal(a, b) assert_(a is b) assert_(b.flags.c_contiguous) # casting parameter allows catching bad casts b = a.astype('c8', casting='safe') assert_equal(a, b) assert_equal(b.dtype, np.dtype('c8')) assert_raises(TypeError, a.astype, 'i4', casting='safe') # subok=False passes through a non-subclassed array b = a.astype('f4', subok=0, copy=False) assert_(a is b) a = np.matrix([[0, 1, 2], [3, 4, 5]], dtype='f4') # subok=True passes through a matrix b = a.astype('f4', subok=True, copy=False) assert_(a is b) # subok=True is default, and creates a subtype on a cast b = a.astype('i4', copy=False) assert_equal(a, b) assert_equal(type(b), np.matrix) # subok=False never returns a matrix b = a.astype('f4', subok=False, copy=False) assert_equal(a, b) assert_(not (a is b)) assert_(type(b) is not np.matrix) # Make sure converting from string object to fixed length string # does not truncate. a = np.array([b'a'*100], dtype='O') b = a.astype('S') assert_equal(a, b) assert_equal(b.dtype, np.dtype('S100')) a = np.array([sixu('a')*100], dtype='O') b = a.astype('U') assert_equal(a, b) assert_equal(b.dtype, np.dtype('U100')) # Same test as above but for strings shorter than 64 characters a = np.array([b'a'*10], dtype='O') b = a.astype('S') assert_equal(a, b) assert_equal(b.dtype, np.dtype('S10')) a = np.array([sixu('a')*10], dtype='O') b = a.astype('U') assert_equal(a, b) assert_equal(b.dtype, np.dtype('U10')) a = np.array(123456789012345678901234567890, dtype='O').astype('S') assert_array_equal(a, np.array(b'1234567890' * 3, dtype='S30')) a = np.array(123456789012345678901234567890, dtype='O').astype('U') assert_array_equal(a, np.array(sixu('1234567890' * 3), dtype='U30')) a = np.array([123456789012345678901234567890], dtype='O').astype('S') assert_array_equal(a, np.array(b'1234567890' * 3, dtype='S30')) a = np.array([123456789012345678901234567890], dtype='O').astype('U') assert_array_equal(a, np.array(sixu('1234567890' * 3), dtype='U30')) a = np.array(123456789012345678901234567890, dtype='S') assert_array_equal(a, np.array(b'1234567890' * 3, dtype='S30')) a = np.array(123456789012345678901234567890, dtype='U') assert_array_equal(a, np.array(sixu('1234567890' * 3), dtype='U30')) a = np.array(sixu('a\u0140'), dtype='U') b = np.ndarray(buffer=a, dtype='uint32', shape=2) assert_(b.size == 2) def test_copyto_fromscalar(): a = np.arange(6, dtype='f4').reshape(2, 3) # Simple copy np.copyto(a, 1.5) assert_equal(a, 1.5) np.copyto(a.T, 2.5) assert_equal(a, 2.5) # Where-masked copy mask = np.array([[0, 1, 0], [0, 0, 1]], dtype='?') np.copyto(a, 3.5, where=mask) assert_equal(a, [[2.5, 3.5, 2.5], [2.5, 2.5, 3.5]]) mask = np.array([[0, 1], [1, 1], [1, 0]], dtype='?') np.copyto(a.T, 4.5, where=mask) assert_equal(a, [[2.5, 4.5, 4.5], [4.5, 4.5, 3.5]]) def test_copyto(): a = np.arange(6, dtype='i4').reshape(2, 3) # Simple copy np.copyto(a, [[3, 1, 5], [6, 2, 1]]) assert_equal(a, [[3, 1, 5], [6, 2, 1]]) # Overlapping copy should work np.copyto(a[:, :2], a[::-1, 1::-1]) assert_equal(a, [[2, 6, 5], [1, 3, 1]]) # Defaults to 'same_kind' casting assert_raises(TypeError, np.copyto, a, 1.5) # Force a copy with 'unsafe' casting, truncating 1.5 to 1 np.copyto(a, 1.5, casting='unsafe') assert_equal(a, 1) # Copying with a mask np.copyto(a, 3, where=[True, False, True]) assert_equal(a, [[3, 1, 3], [3, 1, 3]]) # Casting rule still applies with a mask assert_raises(TypeError, np.copyto, a, 3.5, where=[True, False, True]) # Lists of integer 0's and 1's is ok too np.copyto(a, 4.0, casting='unsafe', where=[[0, 1, 1], [1, 0, 0]]) assert_equal(a, [[3, 4, 4], [4, 1, 3]]) # Overlapping copy with mask should work np.copyto(a[:, :2], a[::-1, 1::-1], where=[[0, 1], [1, 1]]) assert_equal(a, [[3, 4, 4], [4, 3, 3]]) # 'dst' must be an array assert_raises(TypeError, np.copyto, [1, 2, 3], [2, 3, 4]) def test_copy_order(): a = np.arange(24).reshape(2, 1, 3, 4) b = a.copy(order='F') c = np.arange(24).reshape(2, 1, 4, 3).swapaxes(2, 3) def check_copy_result(x, y, ccontig, fcontig, strides=False): assert_(not (x is y)) assert_equal(x, y) assert_equal(res.flags.c_contiguous, ccontig) assert_equal(res.flags.f_contiguous, fcontig) # This check is impossible only because # NPY_RELAXED_STRIDES_CHECKING changes the strides actively if not NPY_RELAXED_STRIDES_CHECKING: if strides: assert_equal(x.strides, y.strides) else: assert_(x.strides != y.strides) # Validate the initial state of a, b, and c assert_(a.flags.c_contiguous) assert_(not a.flags.f_contiguous) assert_(not b.flags.c_contiguous) assert_(b.flags.f_contiguous) assert_(not c.flags.c_contiguous) assert_(not c.flags.f_contiguous) # Copy with order='C' res = a.copy(order='C') check_copy_result(res, a, ccontig=True, fcontig=False, strides=True) res = b.copy(order='C') check_copy_result(res, b, ccontig=True, fcontig=False, strides=False) res = c.copy(order='C') check_copy_result(res, c, ccontig=True, fcontig=False, strides=False) res = np.copy(a, order='C') check_copy_result(res, a, ccontig=True, fcontig=False, strides=True) res = np.copy(b, order='C') check_copy_result(res, b, ccontig=True, fcontig=False, strides=False) res = np.copy(c, order='C') check_copy_result(res, c, ccontig=True, fcontig=False, strides=False) # Copy with order='F' res = a.copy(order='F') check_copy_result(res, a, ccontig=False, fcontig=True, strides=False) res = b.copy(order='F') check_copy_result(res, b, ccontig=False, fcontig=True, strides=True) res = c.copy(order='F') check_copy_result(res, c, ccontig=False, fcontig=True, strides=False) res = np.copy(a, order='F') check_copy_result(res, a, ccontig=False, fcontig=True, strides=False) res = np.copy(b, order='F') check_copy_result(res, b, ccontig=False, fcontig=True, strides=True) res = np.copy(c, order='F') check_copy_result(res, c, ccontig=False, fcontig=True, strides=False) # Copy with order='K' res = a.copy(order='K') check_copy_result(res, a, ccontig=True, fcontig=False, strides=True) res = b.copy(order='K') check_copy_result(res, b, ccontig=False, fcontig=True, strides=True) res = c.copy(order='K') check_copy_result(res, c, ccontig=False, fcontig=False, strides=True) res = np.copy(a, order='K') check_copy_result(res, a, ccontig=True, fcontig=False, strides=True) res = np.copy(b, order='K') check_copy_result(res, b, ccontig=False, fcontig=True, strides=True) res = np.copy(c, order='K') check_copy_result(res, c, ccontig=False, fcontig=False, strides=True) def test_contiguous_flags(): a = np.ones((4, 4, 1))[::2,:,:] if NPY_RELAXED_STRIDES_CHECKING: a.strides = a.strides[:2] + (-123,) b = np.ones((2, 2, 1, 2, 2)).swapaxes(3, 4) def check_contig(a, ccontig, fcontig): assert_(a.flags.c_contiguous == ccontig) assert_(a.flags.f_contiguous == fcontig) # Check if new arrays are correct: check_contig(a, False, False) check_contig(b, False, False) if NPY_RELAXED_STRIDES_CHECKING: check_contig(np.empty((2, 2, 0, 2, 2)), True, True) check_contig(np.array([[[1], [2]]], order='F'), True, True) else: check_contig(np.empty((2, 2, 0, 2, 2)), True, False) check_contig(np.array([[[1], [2]]], order='F'), False, True) check_contig(np.empty((2, 2)), True, False) check_contig(np.empty((2, 2), order='F'), False, True) # Check that np.array creates correct contiguous flags: check_contig(np.array(a, copy=False), False, False) check_contig(np.array(a, copy=False, order='C'), True, False) check_contig(np.array(a, ndmin=4, copy=False, order='F'), False, True) if NPY_RELAXED_STRIDES_CHECKING: # Check slicing update of flags and : check_contig(a[0], True, True) check_contig(a[None, ::4, ..., None], True, True) check_contig(b[0, 0, ...], False, True) check_contig(b[:,:, 0:0,:,:], True, True) else: # Check slicing update of flags: check_contig(a[0], True, False) # Would be nice if this was C-Contiguous: check_contig(a[None, 0, ..., None], False, False) check_contig(b[0, 0, 0, ...], False, True) # Test ravel and squeeze. check_contig(a.ravel(), True, True) check_contig(np.ones((1, 3, 1)).squeeze(), True, True) def test_broadcast_arrays(): # Test user defined dtypes a = np.array([(1, 2, 3)], dtype='u4,u4,u4') b = np.array([(1, 2, 3), (4, 5, 6), (7, 8, 9)], dtype='u4,u4,u4') result = np.broadcast_arrays(a, b) assert_equal(result[0], np.array([(1, 2, 3), (1, 2, 3), (1, 2, 3)], dtype='u4,u4,u4')) assert_equal(result[1], np.array([(1, 2, 3), (4, 5, 6), (7, 8, 9)], dtype='u4,u4,u4')) if __name__ == "__main__": run_module_suite() numpy-1.8.2/numpy/core/tests/test_numerictypes.py0000664000175100017510000003450512370216243023435 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function import sys from numpy.testing import * from numpy.compat import asbytes, asunicode import numpy as np # This is the structure of the table used for plain objects: # # +-+-+-+ # |x|y|z| # +-+-+-+ # Structure of a plain array description: Pdescr = [ ('x', 'i4', (2,)), ('y', 'f8', (2, 2)), ('z', 'u1')] # A plain list of tuples with values for testing: PbufferT = [ # x y z ([3, 2], [[6., 4.], [6., 4.]], 8), ([4, 3], [[7., 5.], [7., 5.]], 9), ] # This is the structure of the table used for nested objects (DON'T PANIC!): # # +-+---------------------------------+-----+----------+-+-+ # |x|Info |color|info |y|z| # | +-----+--+----------------+----+--+ +----+-----+ | | # | |value|y2|Info2 |name|z2| |Name|Value| | | # | | | +----+-----+--+--+ | | | | | | | # | | | |name|value|y3|z3| | | | | | | | # +-+-----+--+----+-----+--+--+----+--+-----+----+-----+-+-+ # # The corresponding nested array description: Ndescr = [ ('x', 'i4', (2,)), ('Info', [ ('value', 'c16'), ('y2', 'f8'), ('Info2', [ ('name', 'S2'), ('value', 'c16', (2,)), ('y3', 'f8', (2,)), ('z3', 'u4', (2,))]), ('name', 'S2'), ('z2', 'b1')]), ('color', 'S2'), ('info', [ ('Name', 'U8'), ('Value', 'c16')]), ('y', 'f8', (2, 2)), ('z', 'u1')] NbufferT = [ # x Info color info y z # value y2 Info2 name z2 Name Value # name value y3 z3 ([3, 2], (6j, 6., (asbytes('nn'), [6j, 4j], [6., 4.], [1, 2]), asbytes('NN'), True), asbytes('cc'), (asunicode('NN'), 6j), [[6., 4.], [6., 4.]], 8), ([4, 3], (7j, 7., (asbytes('oo'), [7j, 5j], [7., 5.], [2, 1]), asbytes('OO'), False), asbytes('dd'), (asunicode('OO'), 7j), [[7., 5.], [7., 5.]], 9), ] byteorder = {'little':'<', 'big':'>'}[sys.byteorder] def normalize_descr(descr): "Normalize a description adding the platform byteorder." out = [] for item in descr: dtype = item[1] if isinstance(dtype, str): if dtype[0] not in ['|', '<', '>']: onebyte = dtype[1:] == "1" if onebyte or dtype[0] in ['S', 'V', 'b']: dtype = "|" + dtype else: dtype = byteorder + dtype if len(item) > 2 and np.prod(item[2]) > 1: nitem = (item[0], dtype, item[2]) else: nitem = (item[0], dtype) out.append(nitem) elif isinstance(item[1], list): l = [] for j in normalize_descr(item[1]): l.append(j) out.append((item[0], l)) else: raise ValueError("Expected a str or list and got %s" % \ (type(item))) return out ############################################################ # Creation tests ############################################################ class create_zeros(object): """Check the creation of heterogeneous arrays zero-valued""" def test_zeros0D(self): """Check creation of 0-dimensional objects""" h = np.zeros((), dtype=self._descr) self.assertTrue(normalize_descr(self._descr) == h.dtype.descr) self.assertTrue(h.dtype.fields['x'][0].name[:4] == 'void') self.assertTrue(h.dtype.fields['x'][0].char == 'V') self.assertTrue(h.dtype.fields['x'][0].type == np.void) # A small check that data is ok assert_equal(h['z'], np.zeros((), dtype='u1')) def test_zerosSD(self): """Check creation of single-dimensional objects""" h = np.zeros((2,), dtype=self._descr) self.assertTrue(normalize_descr(self._descr) == h.dtype.descr) self.assertTrue(h.dtype['y'].name[:4] == 'void') self.assertTrue(h.dtype['y'].char == 'V') self.assertTrue(h.dtype['y'].type == np.void) # A small check that data is ok assert_equal(h['z'], np.zeros((2,), dtype='u1')) def test_zerosMD(self): """Check creation of multi-dimensional objects""" h = np.zeros((2, 3), dtype=self._descr) self.assertTrue(normalize_descr(self._descr) == h.dtype.descr) self.assertTrue(h.dtype['z'].name == 'uint8') self.assertTrue(h.dtype['z'].char == 'B') self.assertTrue(h.dtype['z'].type == np.uint8) # A small check that data is ok assert_equal(h['z'], np.zeros((2, 3), dtype='u1')) class test_create_zeros_plain(create_zeros, TestCase): """Check the creation of heterogeneous arrays zero-valued (plain)""" _descr = Pdescr class test_create_zeros_nested(create_zeros, TestCase): """Check the creation of heterogeneous arrays zero-valued (nested)""" _descr = Ndescr class create_values(object): """Check the creation of heterogeneous arrays with values""" def test_tuple(self): """Check creation from tuples""" h = np.array(self._buffer, dtype=self._descr) self.assertTrue(normalize_descr(self._descr) == h.dtype.descr) if self.multiple_rows: self.assertTrue(h.shape == (2,)) else: self.assertTrue(h.shape == ()) def test_list_of_tuple(self): """Check creation from list of tuples""" h = np.array([self._buffer], dtype=self._descr) self.assertTrue(normalize_descr(self._descr) == h.dtype.descr) if self.multiple_rows: self.assertTrue(h.shape == (1, 2)) else: self.assertTrue(h.shape == (1,)) def test_list_of_list_of_tuple(self): """Check creation from list of list of tuples""" h = np.array([[self._buffer]], dtype=self._descr) self.assertTrue(normalize_descr(self._descr) == h.dtype.descr) if self.multiple_rows: self.assertTrue(h.shape == (1, 1, 2)) else: self.assertTrue(h.shape == (1, 1)) class test_create_values_plain_single(create_values, TestCase): """Check the creation of heterogeneous arrays (plain, single row)""" _descr = Pdescr multiple_rows = 0 _buffer = PbufferT[0] class test_create_values_plain_multiple(create_values, TestCase): """Check the creation of heterogeneous arrays (plain, multiple rows)""" _descr = Pdescr multiple_rows = 1 _buffer = PbufferT class test_create_values_nested_single(create_values, TestCase): """Check the creation of heterogeneous arrays (nested, single row)""" _descr = Ndescr multiple_rows = 0 _buffer = NbufferT[0] class test_create_values_nested_multiple(create_values, TestCase): """Check the creation of heterogeneous arrays (nested, multiple rows)""" _descr = Ndescr multiple_rows = 1 _buffer = NbufferT ############################################################ # Reading tests ############################################################ class read_values_plain(object): """Check the reading of values in heterogeneous arrays (plain)""" def test_access_fields(self): h = np.array(self._buffer, dtype=self._descr) if not self.multiple_rows: self.assertTrue(h.shape == ()) assert_equal(h['x'], np.array(self._buffer[0], dtype='i4')) assert_equal(h['y'], np.array(self._buffer[1], dtype='f8')) assert_equal(h['z'], np.array(self._buffer[2], dtype='u1')) else: self.assertTrue(len(h) == 2) assert_equal(h['x'], np.array([self._buffer[0][0], self._buffer[1][0]], dtype='i4')) assert_equal(h['y'], np.array([self._buffer[0][1], self._buffer[1][1]], dtype='f8')) assert_equal(h['z'], np.array([self._buffer[0][2], self._buffer[1][2]], dtype='u1')) class test_read_values_plain_single(read_values_plain, TestCase): """Check the creation of heterogeneous arrays (plain, single row)""" _descr = Pdescr multiple_rows = 0 _buffer = PbufferT[0] class test_read_values_plain_multiple(read_values_plain, TestCase): """Check the values of heterogeneous arrays (plain, multiple rows)""" _descr = Pdescr multiple_rows = 1 _buffer = PbufferT class read_values_nested(object): """Check the reading of values in heterogeneous arrays (nested)""" def test_access_top_fields(self): """Check reading the top fields of a nested array""" h = np.array(self._buffer, dtype=self._descr) if not self.multiple_rows: self.assertTrue(h.shape == ()) assert_equal(h['x'], np.array(self._buffer[0], dtype='i4')) assert_equal(h['y'], np.array(self._buffer[4], dtype='f8')) assert_equal(h['z'], np.array(self._buffer[5], dtype='u1')) else: self.assertTrue(len(h) == 2) assert_equal(h['x'], np.array([self._buffer[0][0], self._buffer[1][0]], dtype='i4')) assert_equal(h['y'], np.array([self._buffer[0][4], self._buffer[1][4]], dtype='f8')) assert_equal(h['z'], np.array([self._buffer[0][5], self._buffer[1][5]], dtype='u1')) def test_nested1_acessors(self): """Check reading the nested fields of a nested array (1st level)""" h = np.array(self._buffer, dtype=self._descr) if not self.multiple_rows: assert_equal(h['Info']['value'], np.array(self._buffer[1][0], dtype='c16')) assert_equal(h['Info']['y2'], np.array(self._buffer[1][1], dtype='f8')) assert_equal(h['info']['Name'], np.array(self._buffer[3][0], dtype='U2')) assert_equal(h['info']['Value'], np.array(self._buffer[3][1], dtype='c16')) else: assert_equal(h['Info']['value'], np.array([self._buffer[0][1][0], self._buffer[1][1][0]], dtype='c16')) assert_equal(h['Info']['y2'], np.array([self._buffer[0][1][1], self._buffer[1][1][1]], dtype='f8')) assert_equal(h['info']['Name'], np.array([self._buffer[0][3][0], self._buffer[1][3][0]], dtype='U2')) assert_equal(h['info']['Value'], np.array([self._buffer[0][3][1], self._buffer[1][3][1]], dtype='c16')) def test_nested2_acessors(self): """Check reading the nested fields of a nested array (2nd level)""" h = np.array(self._buffer, dtype=self._descr) if not self.multiple_rows: assert_equal(h['Info']['Info2']['value'], np.array(self._buffer[1][2][1], dtype='c16')) assert_equal(h['Info']['Info2']['z3'], np.array(self._buffer[1][2][3], dtype='u4')) else: assert_equal(h['Info']['Info2']['value'], np.array([self._buffer[0][1][2][1], self._buffer[1][1][2][1]], dtype='c16')) assert_equal(h['Info']['Info2']['z3'], np.array([self._buffer[0][1][2][3], self._buffer[1][1][2][3]], dtype='u4')) def test_nested1_descriptor(self): """Check access nested descriptors of a nested array (1st level)""" h = np.array(self._buffer, dtype=self._descr) self.assertTrue(h.dtype['Info']['value'].name == 'complex128') self.assertTrue(h.dtype['Info']['y2'].name == 'float64') if sys.version_info[0] >= 3: self.assertTrue(h.dtype['info']['Name'].name == 'str256') else: self.assertTrue(h.dtype['info']['Name'].name == 'unicode256') self.assertTrue(h.dtype['info']['Value'].name == 'complex128') def test_nested2_descriptor(self): """Check access nested descriptors of a nested array (2nd level)""" h = np.array(self._buffer, dtype=self._descr) self.assertTrue(h.dtype['Info']['Info2']['value'].name == 'void256') self.assertTrue(h.dtype['Info']['Info2']['z3'].name == 'void64') class test_read_values_nested_single(read_values_nested, TestCase): """Check the values of heterogeneous arrays (nested, single row)""" _descr = Ndescr multiple_rows = False _buffer = NbufferT[0] class test_read_values_nested_multiple(read_values_nested, TestCase): """Check the values of heterogeneous arrays (nested, multiple rows)""" _descr = Ndescr multiple_rows = True _buffer = NbufferT class TestEmptyField(TestCase): def test_assign(self): a = np.arange(10, dtype=np.float32) a.dtype = [("int", "<0i4"), ("float", "<2f4")] assert_(a['int'].shape == (5, 0)) assert_(a['float'].shape == (5, 2)) class TestCommonType(TestCase): def test_scalar_loses1(self): res = np.find_common_type(['f4', 'f4', 'i2'], ['f8']) assert_(res == 'f4') def test_scalar_loses2(self): res = np.find_common_type(['f4', 'f4'], ['i8']) assert_(res == 'f4') def test_scalar_wins(self): res = np.find_common_type(['f4', 'f4', 'i2'], ['c8']) assert_(res == 'c8') def test_scalar_wins2(self): res = np.find_common_type(['u4', 'i4', 'i4'], ['f4']) assert_(res == 'f8') def test_scalar_wins3(self): # doesn't go up to 'f16' on purpose res = np.find_common_type(['u8', 'i8', 'i8'], ['f8']) assert_(res == 'f8') class TestMultipleFields(TestCase): def setUp(self): self.ary = np.array([(1, 2, 3, 4), (5, 6, 7, 8)], dtype='i4,f4,i2,c8') def _bad_call(self): return self.ary['f0', 'f1'] def test_no_tuple(self): self.assertRaises(ValueError, self._bad_call) def test_return(self): res = self.ary[['f0', 'f2']].tolist() assert_(res == [(1, 3), (5, 7)]) if __name__ == "__main__": run_module_suite() numpy-1.8.2/numpy/core/tests/test_errstate.py0000664000175100017510000000306312370216242022531 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function import platform import numpy as np from numpy.testing import TestCase, assert_, run_module_suite, dec class TestErrstate(TestCase): @dec.skipif(platform.machine() == "armv5tel", "See gh-413.") def test_invalid(self): with np.errstate(all='raise', under='ignore'): a = -np.arange(3) # This should work with np.errstate(invalid='ignore'): np.sqrt(a) # While this should fail! try: np.sqrt(a) except FloatingPointError: pass else: self.fail("Did not raise an invalid error") def test_divide(self): with np.errstate(all='raise', under='ignore'): a = -np.arange(3) # This should work with np.errstate(divide='ignore'): a // 0 # While this should fail! try: a // 0 except FloatingPointError: pass else: self.fail("Did not raise divide by zero error") def test_errcall(self): def foo(*args): print(args) olderrcall = np.geterrcall() with np.errstate(call=foo): assert_(np.geterrcall() is foo, 'call is not foo') with np.errstate(call=None): assert_(np.geterrcall() is None, 'call is not None') assert_(np.geterrcall() is olderrcall, 'call is not olderrcall') if __name__ == "__main__": run_module_suite() numpy-1.8.2/numpy/core/tests/test_getlimits.py0000664000175100017510000000533412370216242022704 0ustar vagrantvagrant00000000000000""" Test functions for limits module. """ from __future__ import division, absolute_import, print_function from numpy.testing import * from numpy.core import finfo, iinfo from numpy import half, single, double, longdouble import numpy as np ################################################## class TestPythonFloat(TestCase): def test_singleton(self): ftype = finfo(float) ftype2 = finfo(float) assert_equal(id(ftype), id(ftype2)) class TestHalf(TestCase): def test_singleton(self): ftype = finfo(half) ftype2 = finfo(half) assert_equal(id(ftype), id(ftype2)) class TestSingle(TestCase): def test_singleton(self): ftype = finfo(single) ftype2 = finfo(single) assert_equal(id(ftype), id(ftype2)) class TestDouble(TestCase): def test_singleton(self): ftype = finfo(double) ftype2 = finfo(double) assert_equal(id(ftype), id(ftype2)) class TestLongdouble(TestCase): def test_singleton(self,level=2): ftype = finfo(longdouble) ftype2 = finfo(longdouble) assert_equal(id(ftype), id(ftype2)) class TestIinfo(TestCase): def test_basic(self): dts = list(zip(['i1', 'i2', 'i4', 'i8', 'u1', 'u2', 'u4', 'u8'], [np.int8, np.int16, np.int32, np.int64, np.uint8, np.uint16, np.uint32, np.uint64])) for dt1, dt2 in dts: assert_equal(iinfo(dt1).min, iinfo(dt2).min) assert_equal(iinfo(dt1).max, iinfo(dt2).max) self.assertRaises(ValueError, iinfo, 'f4') def test_unsigned_max(self): types = np.sctypes['uint'] for T in types: assert_equal(iinfo(T).max, T(-1)) class TestRepr(TestCase): def test_iinfo_repr(self): expected = "iinfo(min=-32768, max=32767, dtype=int16)" assert_equal(repr(np.iinfo(np.int16)), expected) def test_finfo_repr(self): expected = "finfo(resolution=1e-06, min=-3.4028235e+38," + \ " max=3.4028235e+38, dtype=float32)" # Python 2.5 float formatting on Windows adds an extra 0 to the # exponent. So test for both. Once 2.5 compatibility is dropped, this # can simply use `assert_equal(repr(np.finfo(np.float32)), expected)`. expected_win25 = "finfo(resolution=1e-006, min=-3.4028235e+038," + \ " max=3.4028235e+038, dtype=float32)" actual = repr(np.finfo(np.float32)) if not actual == expected: if not actual == expected_win25: msg = build_err_msg([actual, desired], verbose=True) raise AssertionError(msg) def test_instances(): iinfo(10) finfo(3.0) if __name__ == "__main__": run_module_suite() numpy-1.8.2/numpy/core/tests/test_dtype.py0000664000175100017510000005022112371375326022035 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function import sys import numpy as np from numpy.testing import * def assert_dtype_equal(a, b): assert_equal(a, b) assert_equal(hash(a), hash(b), "two equivalent types do not hash to the same value !") def assert_dtype_not_equal(a, b): assert_(a != b) assert_(hash(a) != hash(b), "two different types hash to the same value !") class TestBuiltin(TestCase): def test_run(self): """Only test hash runs at all.""" for t in [np.int, np.float, np.complex, np.int32, np.str, np.object, np.unicode]: dt = np.dtype(t) hash(dt) def test_dtype(self): # Make sure equivalent byte order char hash the same (e.g. < and = on # little endian) for t in [np.int, np.float]: dt = np.dtype(t) dt2 = dt.newbyteorder("<") dt3 = dt.newbyteorder(">") if dt == dt2: self.assertTrue(dt.byteorder != dt2.byteorder, "bogus test") assert_dtype_equal(dt, dt2) else: self.assertTrue(dt.byteorder != dt3.byteorder, "bogus test") assert_dtype_equal(dt, dt3) def test_equivalent_dtype_hashing(self): # Make sure equivalent dtypes with different type num hash equal uintp = np.dtype(np.uintp) if uintp.itemsize == 4: left = uintp right = np.dtype(np.uint32) else: left = uintp right = np.dtype(np.ulonglong) self.assertTrue(left == right) self.assertTrue(hash(left) == hash(right)) def test_invalid_types(self): # Make sure invalid type strings raise a warning. # For now, display a deprecation warning for invalid # type sizes. In the future this should be changed # to an exception. assert_warns(DeprecationWarning, np.dtype, 'O3') assert_warns(DeprecationWarning, np.dtype, 'O5') assert_warns(DeprecationWarning, np.dtype, 'O7') assert_warns(DeprecationWarning, np.dtype, 'b3') assert_warns(DeprecationWarning, np.dtype, 'h4') assert_warns(DeprecationWarning, np.dtype, 'I5') assert_warns(DeprecationWarning, np.dtype, 'e3') assert_warns(DeprecationWarning, np.dtype, 'f5') if np.dtype('g').itemsize == 8 or np.dtype('g').itemsize == 16: assert_warns(DeprecationWarning, np.dtype, 'g12') elif np.dtype('g').itemsize == 12: assert_warns(DeprecationWarning, np.dtype, 'g16') if np.dtype('l').itemsize == 8: assert_warns(DeprecationWarning, np.dtype, 'l4') assert_warns(DeprecationWarning, np.dtype, 'L4') else: assert_warns(DeprecationWarning, np.dtype, 'l8') assert_warns(DeprecationWarning, np.dtype, 'L8') if np.dtype('q').itemsize == 8: assert_warns(DeprecationWarning, np.dtype, 'q4') assert_warns(DeprecationWarning, np.dtype, 'Q4') else: assert_warns(DeprecationWarning, np.dtype, 'q8') assert_warns(DeprecationWarning, np.dtype, 'Q8') def test_bad_param(self): # Can't give a size that's too small assert_raises(ValueError, np.dtype, {'names':['f0', 'f1'], 'formats':['i4', 'i1'], 'offsets':[0, 4], 'itemsize':4}) # If alignment is enabled, the alignment (4) must divide the itemsize assert_raises(ValueError, np.dtype, {'names':['f0', 'f1'], 'formats':['i4', 'i1'], 'offsets':[0, 4], 'itemsize':9}, align=True) # If alignment is enabled, the individual fields must be aligned assert_raises(ValueError, np.dtype, {'names':['f0', 'f1'], 'formats':['i1', 'f4'], 'offsets':[0, 2]}, align=True) class TestRecord(TestCase): def test_equivalent_record(self): """Test whether equivalent record dtypes hash the same.""" a = np.dtype([('yo', np.int)]) b = np.dtype([('yo', np.int)]) assert_dtype_equal(a, b) def test_different_names(self): # In theory, they may hash the same (collision) ? a = np.dtype([('yo', np.int)]) b = np.dtype([('ye', np.int)]) assert_dtype_not_equal(a, b) def test_different_titles(self): # In theory, they may hash the same (collision) ? a = np.dtype({'names': ['r', 'b'], 'formats': ['u1', 'u1'], 'titles': ['Red pixel', 'Blue pixel']}) b = np.dtype({'names': ['r', 'b'], 'formats': ['u1', 'u1'], 'titles': ['RRed pixel', 'Blue pixel']}) assert_dtype_not_equal(a, b) def test_not_lists(self): """Test if an appropriate exception is raised when passing bad values to the dtype constructor. """ self.assertRaises(TypeError, np.dtype, dict(names=set(['A', 'B']), formats=['f8', 'i4'])) self.assertRaises(TypeError, np.dtype, dict(names=['A', 'B'], formats=set(['f8', 'i4']))) def test_aligned_size(self): # Check that structured dtypes get padded to an aligned size dt = np.dtype('i4, i1', align=True) assert_equal(dt.itemsize, 8) dt = np.dtype([('f0', 'i4'), ('f1', 'i1')], align=True) assert_equal(dt.itemsize, 8) dt = np.dtype({'names':['f0', 'f1'], 'formats':['i4', 'u1'], 'offsets':[0, 4]}, align=True) assert_equal(dt.itemsize, 8) dt = np.dtype({'f0': ('i4', 0), 'f1':('u1', 4)}, align=True) assert_equal(dt.itemsize, 8) # Nesting should preserve that alignment dt1 = np.dtype([('f0', 'i4'), ('f1', [('f1', 'i1'), ('f2', 'i4'), ('f3', 'i1')]), ('f2', 'i1')], align=True) assert_equal(dt1.itemsize, 20) dt2 = np.dtype({'names':['f0', 'f1', 'f2'], 'formats':['i4', [('f1', 'i1'), ('f2', 'i4'), ('f3', 'i1')], 'i1'], 'offsets':[0, 4, 16]}, align=True) assert_equal(dt2.itemsize, 20) dt3 = np.dtype({'f0': ('i4', 0), 'f1': ([('f1', 'i1'), ('f2', 'i4'), ('f3', 'i1')], 4), 'f2': ('i1', 16)}, align=True) assert_equal(dt3.itemsize, 20) assert_equal(dt1, dt2) assert_equal(dt2, dt3) # Nesting should preserve packing dt1 = np.dtype([('f0', 'i4'), ('f1', [('f1', 'i1'), ('f2', 'i4'), ('f3', 'i1')]), ('f2', 'i1')], align=False) assert_equal(dt1.itemsize, 11) dt2 = np.dtype({'names':['f0', 'f1', 'f2'], 'formats':['i4', [('f1', 'i1'), ('f2', 'i4'), ('f3', 'i1')], 'i1'], 'offsets':[0, 4, 10]}, align=False) assert_equal(dt2.itemsize, 11) dt3 = np.dtype({'f0': ('i4', 0), 'f1': ([('f1', 'i1'), ('f2', 'i4'), ('f3', 'i1')], 4), 'f2': ('i1', 10)}, align=False) assert_equal(dt3.itemsize, 11) assert_equal(dt1, dt2) assert_equal(dt2, dt3) def test_union_struct(self): # Should be able to create union dtypes dt = np.dtype({'names':['f0', 'f1', 'f2'], 'formats':['f4', (64, 64)), (1,)), ('rtile', '>f4', (64, 36))], (3,)), ('bottom', [('bleft', ('>f4', (8, 64)), (1,)), ('bright', '>f4', (8, 36))])]) assert_equal(str(dt), "[('top', [('tiles', ('>f4', (64, 64)), (1,)), " "('rtile', '>f4', (64, 36))], (3,)), " "('bottom', [('bleft', ('>f4', (8, 64)), (1,)), " "('bright', '>f4', (8, 36))])]") # If the sticky aligned flag is set to True, it makes the # str() function use a dict representation with an 'aligned' flag dt = np.dtype([('top', [('tiles', ('>f4', (64, 64)), (1,)), ('rtile', '>f4', (64, 36))], (3,)), ('bottom', [('bleft', ('>f4', (8, 64)), (1,)), ('bright', '>f4', (8, 36))])], align=True) assert_equal(str(dt), "{'names':['top','bottom'], " "'formats':[([('tiles', ('>f4', (64, 64)), (1,)), " "('rtile', '>f4', (64, 36))], (3,))," "[('bleft', ('>f4', (8, 64)), (1,)), " "('bright', '>f4', (8, 36))]], " "'offsets':[0,76800], " "'itemsize':80000, " "'aligned':True}") assert_equal(np.dtype(eval(str(dt))), dt) dt = np.dtype({'names': ['r', 'g', 'b'], 'formats': ['u1', 'u1', 'u1'], 'offsets': [0, 1, 2], 'titles': ['Red pixel', 'Green pixel', 'Blue pixel']}) assert_equal(str(dt), "[(('Red pixel', 'r'), 'u1'), " "(('Green pixel', 'g'), 'u1'), " "(('Blue pixel', 'b'), 'u1')]") dt = np.dtype({'names': ['rgba', 'r', 'g', 'b'], 'formats': ['f4', (64, 64)), (1,)), ('rtile', '>f4', (64, 36))], (3,)), ('bottom', [('bleft', ('>f4', (8, 64)), (1,)), ('bright', '>f4', (8, 36))])]) assert_equal(repr(dt), "dtype([('top', [('tiles', ('>f4', (64, 64)), (1,)), " "('rtile', '>f4', (64, 36))], (3,)), " "('bottom', [('bleft', ('>f4', (8, 64)), (1,)), " "('bright', '>f4', (8, 36))])])") dt = np.dtype({'names': ['r', 'g', 'b'], 'formats': ['u1', 'u1', 'u1'], 'offsets': [0, 1, 2], 'titles': ['Red pixel', 'Green pixel', 'Blue pixel']}, align=True) assert_equal(repr(dt), "dtype([(('Red pixel', 'r'), 'u1'), " "(('Green pixel', 'g'), 'u1'), " "(('Blue pixel', 'b'), 'u1')], align=True)") dt = np.dtype({'names': ['rgba', 'r', 'g', 'b'], 'formats': ['= 3) def test_dtype_str_with_long_in_shape(self): # Pull request #376 dt = np.dtype('(1L,)i4') def test_base_dtype_with_object_type(self): # 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): dt = np.dtype(np.double) attr = ["subdtype", "descr", "str", "name", "base", "shape", "isbuiltin", "isnative", "isalignedstruct", "fields", "metadata", "hasobject"] if sys.version[:3] == '2.4': error = TypeError else: error = AttributeError for s in attr: assert_raises(error, delattr, dt, s) def test_dtype_writable_attributes_deletion(self): dt = np.dtype(np.double) attr = ["names"] for s in attr: assert_raises(AttributeError, delattr, dt, s) if __name__ == "__main__": run_module_suite() numpy-1.8.2/numpy/core/tests/test_blasdot.py0000664000175100017510000001255312370216243022335 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function import numpy as np import sys from numpy.core import zeros, float64 from numpy.testing import dec, TestCase, assert_almost_equal, assert_, \ assert_raises, assert_array_equal, assert_allclose, assert_equal from numpy.core.multiarray import inner as inner_ DECPREC = 14 class TestInner(TestCase): def test_vecself(self): """Ticket 844.""" # Inner product of a vector with itself segfaults or give meaningless # result a = zeros(shape = (1, 80), dtype = float64) p = inner_(a, a) assert_almost_equal(p, 0, decimal = DECPREC) try: import numpy.core._dotblas as _dotblas except ImportError: _dotblas = None @dec.skipif(_dotblas is None, "Numpy is not compiled with _dotblas") def test_blasdot_used(): from numpy.core import dot, vdot, inner, alterdot, restoredot assert_(dot is _dotblas.dot) assert_(vdot is _dotblas.vdot) assert_(inner is _dotblas.inner) assert_(alterdot is _dotblas.alterdot) assert_(restoredot is _dotblas.restoredot) def test_dot_2args(): from numpy.core import dot a = np.array([[1, 2], [3, 4]], dtype=float) b = np.array([[1, 0], [1, 1]], dtype=float) c = np.array([[3, 2], [7, 4]], dtype=float) d = dot(a, b) assert_allclose(c, d) def test_dot_3args(): np.random.seed(22) f = np.random.random_sample((1024, 16)) v = np.random.random_sample((16, 32)) r = np.empty((1024, 32)) for i in range(12): np.dot(f, v, r) assert_equal(sys.getrefcount(r), 2) r2 = np.dot(f, v, out=None) assert_array_equal(r2, r) assert_(r is np.dot(f, v, out=r)) v = v[:, 0].copy() # v.shape == (16,) r = r[:, 0].copy() # r.shape == (1024,) r2 = np.dot(f, v) assert_(r is np.dot(f, v, r)) assert_array_equal(r2, r) def test_dot_3args_errors(): np.random.seed(22) f = np.random.random_sample((1024, 16)) v = np.random.random_sample((16, 32)) r = np.empty((1024, 31)) assert_raises(ValueError, np.dot, f, v, r) r = np.empty((1024,)) assert_raises(ValueError, np.dot, f, v, r) r = np.empty((32,)) assert_raises(ValueError, np.dot, f, v, r) r = np.empty((32, 1024)) assert_raises(ValueError, np.dot, f, v, r) assert_raises(ValueError, np.dot, f, v, r.T) r = np.empty((1024, 64)) assert_raises(ValueError, np.dot, f, v, r[:, ::2]) assert_raises(ValueError, np.dot, f, v, r[:, :32]) r = np.empty((1024, 32), dtype=np.float32) assert_raises(ValueError, np.dot, f, v, r) r = np.empty((1024, 32), dtype=int) assert_raises(ValueError, np.dot, f, v, r) def test_dot_array_order(): """ Test numpy dot with different order C, F Comparing results with multiarray dot. Double and single precisions array are compared using relative precision of 7 and 5 decimals respectively. Use 30 decimal when comparing exact operations like: (a.b)' = b'.a' """ _dot = np.core.multiarray.dot a_dim, b_dim, c_dim = 10, 4, 7 orders = ["C", "F"] dtypes_prec = {np.float64: 7, np.float32: 5} np.random.seed(7) for arr_type, prec in dtypes_prec.items(): for a_order in orders: a = np.asarray(np.random.randn(a_dim, a_dim), dtype=arr_type, order=a_order) assert_array_equal(np.dot(a, a), a.dot(a)) # (a.a)' = a'.a', note that mse~=1e-31 needs almost_equal assert_almost_equal(a.dot(a), a.T.dot(a.T).T, decimal=prec) # # Check with making explicit copy # a_T = a.T.copy(order=a_order) assert_almost_equal(a_T.dot(a_T), a.T.dot(a.T), decimal=prec) assert_almost_equal(a.dot(a_T), a.dot(a.T), decimal=prec) assert_almost_equal(a_T.dot(a), a.T.dot(a), decimal=prec) # # Compare with multiarray dot # assert_almost_equal(a.dot(a), _dot(a, a), decimal=prec) assert_almost_equal(a.T.dot(a), _dot(a.T, a), decimal=prec) assert_almost_equal(a.dot(a.T), _dot(a, a.T), decimal=prec) assert_almost_equal(a.T.dot(a.T), _dot(a.T, a.T), decimal=prec) for res in a.dot(a), a.T.dot(a), a.dot(a.T), a.T.dot(a.T): assert res.flags.c_contiguous for b_order in orders: b = np.asarray(np.random.randn(a_dim, b_dim), dtype=arr_type, order=b_order) b_T = b.T.copy(order=b_order) assert_almost_equal(a_T.dot(b), a.T.dot(b), decimal=prec) assert_almost_equal(b_T.dot(a), b.T.dot(a), decimal=prec) # (b'.a)' = a'.b assert_almost_equal(b.T.dot(a), a.T.dot(b).T, decimal=prec) assert_almost_equal(a.dot(b), _dot(a, b), decimal=prec) assert_almost_equal(b.T.dot(a), _dot(b.T, a), decimal=prec) for c_order in orders: c = np.asarray(np.random.randn(b_dim, c_dim), dtype=arr_type, order=c_order) c_T = c.T.copy(order=c_order) assert_almost_equal(c.T.dot(b.T), c_T.dot(b_T), decimal=prec) assert_almost_equal(c.T.dot(b.T).T, b.dot(c), decimal=prec) assert_almost_equal(b.dot(c), _dot(b, c), decimal=prec) assert_almost_equal(c.T.dot(b.T), _dot(c.T, b.T), decimal=prec) numpy-1.8.2/numpy/core/tests/test_indexing.py0000664000175100017510000005475312370216243022522 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function import numpy as np from itertools import product from numpy.compat import asbytes from numpy.testing import * import sys, warnings, gc class TestIndexing(TestCase): def test_none_index(self): # `None` index adds newaxis a = np.array([1, 2, 3]) assert_equal(a[None], a[np.newaxis]) assert_equal(a[None].ndim, a.ndim + 1) def test_empty_tuple_index(self): # Empty tuple index creates a view a = np.array([1, 2, 3]) assert_equal(a[()], a) assert_(a[()].base is a) a = np.array(0) assert_(isinstance(a[()], np.int_)) 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() 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_)) # 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)) # 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_empty_fancy_index(self): # Empty list index creates an empty array # with the same dtype (but with weird shape) a = np.array([1, 2, 3]) assert_equal(a[[]], []) assert_equal(a[[]].dtype, a.dtype) b = np.array([], dtype=np.intp) assert_equal(a[[]], []) assert_equal(a[[]].dtype, a.dtype) b = np.array([]) assert_raises(IndexError, a.__getitem__, b) def test_ellipsis_index(self): # Ellipsis index does not create a view a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) assert_equal(a[...], a) assert_(a[...] is a) # Slicing with ellipsis can skip an # arbitrary number of dimensions assert_equal(a[0, ...], a[0]) assert_equal(a[0, ...], a[0,:]) assert_equal(a[..., 0], a[:, 0]) # Slicing with ellipsis always results # in an array, not a scalar assert_equal(a[0, ..., 1], np.array(2)) def test_single_int_index(self): # Single integer index selects one row a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) assert_equal(a[0], [1, 2, 3]) assert_equal(a[-1], [7, 8, 9]) # Index out of bounds produces IndexError assert_raises(IndexError, a.__getitem__, 1<<30) # Index overflow produces IndexError assert_raises(IndexError, a.__getitem__, 1<<64) def test_single_bool_index(self): # Single boolean index a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) # Python boolean converts to integer # These are being deprecated (and test in test_deprecations) #assert_equal(a[True], a[1]) #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]) def test_boolean_indexing_onedim(self): # Indexing a 2-dimensional array with # boolean array of length one a = np.array([[ 0., 0., 0.]]) b = np.array([ True], dtype=bool) assert_equal(a[b], a) # boolean assignment 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) a = np.arange(4) def f(a, v): a[a > -1] = v assert_raises(ValueError, f, a, []) 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 a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) b = np.array([[ True, False, True], [False, True, False], [ True, False, True]]) assert_equal(a[b], [1, 3, 5, 7, 9]) assert_equal(a[b[1]], [[4, 5, 6]]) assert_equal(a[b[0]], a[b[2]]) # boolean assignment a[b] = 0 assert_equal(a, [[0, 2, 0], [4, 0, 6], [0, 8, 0]]) 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 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 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. (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 will usually not be the same one. They are *not* tested. """ def setUp(self): self.a = np.arange(np.prod([3, 1, 5, 6])).reshape(3, 1, 5, 6) self.b = np.empty((3, 0, 5, 6)) self.complex_indices = ['skip', Ellipsis, 0, # Boolean indices, up to 3-d for some special cases of eating up # dimensions, also need to test all False np.array(False), np.array([True, False, False]), np.array([[True, False], [False, True]]), np.array([[[False, False], [False, False]]]), # Some slices: slice(-5, 5, 2), slice(1, 1, 100), slice(4, -1, -2), slice(None, None, -3), # Some Fancy indexes: np.empty((0, 1, 1), dtype=np.intp), # empty broadcastable np.array([0, 1, -2]), np.array([[2], [0], [1]]), np.array([[0, -1], [0, 1]]), np.array([2, -1]), np.zeros([1]*31, dtype=int), # trigger too large array. np.array([0., 1.])] # invalid datatype # Some simpler indices that still cover a bit more self.simple_indices = [Ellipsis, None, -1, [1], np.array([True]), 'skip'] # Very simple ones to fill the rest: self.fill_indices = [slice(None, None), 0] def _get_multi_index(self, arr, indices): """Mimic multi dimensional indexing. Parameters ---------- arr : ndarray Array to be indexed. indices : tuple of index objects Returns ------- out : ndarray An array equivalent to the indexing operation (but always a copy). `arr[indices]` should be identical. no_copy : bool Whether the indexing operation requires a copy. If this is `True`, `np.may_share_memory(arr, arr[indicies])` should be `True` (with some exceptions for scalars and possibly 0-d arrays). Notes ----- While the function may mostly match the errors of normal indexing this is generally not the case. """ in_indices = list(indices) indices = [] # if False, this is a fancy or boolean index no_copy = True # number of fancy/scalar indexes that are not consecutive num_fancy = 0 # number of dimensions indexed by a "fancy" index 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. # This variable is to catch that case. error_unless_broadcast_to_empty = False # We need to handle Ellipsis and make arrays from indices, also # check if this is fancy indexing (set no_copy). ndim = 0 ellipsis_pos = None # define here mostly to replace all but first. for i, indx in enumerate(in_indices): if indx is None: continue if isinstance(indx, np.ndarray) and indx.dtype == bool: no_copy = False if indx.ndim == 0: raise IndexError # boolean indices can have higher dimensions ndim += indx.ndim fancy_dim += indx.ndim continue if indx is Ellipsis: if ellipsis_pos is None: ellipsis_pos = i continue # do not increment ndim counter in_indices[i] = slice(None, None) ndim += 1 continue if isinstance(indx, slice): ndim += 1 continue if not isinstance(indx, np.ndarray): # This could be open for changes in numpy. # numpy should maybe raise an error if casting to intp # is not safe. It rejects np.array([1., 2.]) but not # [1., 2.] as index (same for ie. np.take). # (Note the importance of empty lists if changing this here) indx = np.array(indx, dtype=np.intp) in_indices[i] = indx elif indx.dtype.kind != 'b' and indx.dtype.kind != 'i': raise IndexError('arrays used as indices must be of integer (or boolean) type') if indx.ndim != 0: no_copy = False ndim += 1 fancy_dim += 1 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. raise IndexError if ndim == 0 and not None in in_indices: # Well we have no indexes or one Ellipsis. This is legal. return arr.copy(), no_copy if ellipsis_pos is not None: in_indices[ellipsis_pos:ellipsis_pos+1] = [slice(None, None)] * (arr.ndim - ndim) for ax, indx in enumerate(in_indices): if isinstance(indx, slice): # convert to an index array anways: indx = np.arange(*indx.indices(arr.shape[ax])) indices.append(['s', indx]) continue elif indx is None: # this is like taking a slice with one element from a new axis: indices.append(['n', np.array([0], dtype=np.intp)]) arr = arr.reshape((arr.shape[:ax] + (1,) + arr.shape[ax:])) continue if isinstance(indx, np.ndarray) and indx.dtype == bool: # This may be open for improvement in numpy. # numpy should probably cast boolean lists to boolean indices # instead of intp! # Numpy supports for a boolean index with # non-matching shape as long as the True values are not # out of bounds. Numpy maybe should maybe not allow this, # (at least not array that are larger then the original one). try: flat_indx = np.ravel_multi_index(np.nonzero(indx), arr.shape[ax:ax+indx.ndim], mode='raise') except: error_unless_broadcast_to_empty = True # fill with 0s instead, and raise error later flat_indx = np.array([0]*indx.sum(), dtype=np.intp) # concatenate axis into a single one: if indx.ndim != 0: arr = arr.reshape((arr.shape[:ax] + (np.prod(arr.shape[ax:ax+indx.ndim]),) + arr.shape[ax+indx.ndim:])) indx = flat_indx else: # This could be changed, a 0-d boolean index can # make sense (even outide the 0-d indexed array case) # Note that originally this is could be interpreted as # integer in the full integer special case. 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. indices[-1].append(indx) else: # We have a fancy index that is not after an existing one. # NOTE: A 0-d array triggers this as well, while # one may expect it to not trigger it, since a scalar # would not be considered fancy indexing. num_fancy += 1 indices.append(['f', indx]) if num_fancy > 1 and not no_copy: # We have to flush the fancy indexes left new_indices = indices[:] axes = list(range(arr.ndim)) fancy_axes = [] new_indices.insert(0, ['f']) ni = 0 ai = 0 for indx in indices: ni += 1 if indx[0] == 'f': new_indices[0].extend(indx[1:]) del new_indices[ni] ni -= 1 for ax in range(ai, ai + len(indx[1:])): fancy_axes.append(ax) axes.remove(ax) ai += len(indx) - 1 # axis we are at indices = new_indices # and now we need to transpose arr: arr = arr.transpose(*(fancy_axes + axes)) # We only have one 'f' index now and arr is transposed accordingly. # Now handle newaxes by reshaping... ax = 0 for indx in indices: if indx[0] == 'f': if len(indx) == 1: continue # First of all, reshape arr to combine fancy axes into one: orig_shape = arr.shape orig_slice = orig_shape[ax:ax + len(indx[1:])] arr = arr.reshape((arr.shape[:ax] + (np.prod(orig_slice).astype(int),) + arr.shape[ax + len(indx[1:]):])) # Check if broadcasting works if len(indx[1:]) != 1: res = np.broadcast(*indx[1:]) # raises ValueError... else: res = indx[1] # unfortunatly 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: if error_unless_broadcast_to_empty: raise IndexError for _indx, _size in zip(indx[1:], orig_slice): if _indx.size == 0: continue if np.any(_indx >= _size) or np.any(_indx < -_size): raise IndexError if len(indx[1:]) == len(orig_slice): if np.product(orig_slice) == 0: # Work around for a crash or IndexError with 'wrap' # in some 0-sized cases. try: mi = np.ravel_multi_index(indx[1:], orig_slice, mode='raise') except: # This happens with 0-sized orig_slice (sometimes?) # here it is a ValueError, but indexing gives a: raise IndexError('invalid index into 0-sized') else: mi = np.ravel_multi_index(indx[1:], orig_slice, mode='wrap') else: # Maybe never happens... raise ValueError arr = arr.take(mi.ravel(), axis=ax) arr = arr.reshape((arr.shape[:ax] + mi.shape + arr.shape[ax+1:])) ax += mi.ndim continue # If we are here, we have a 1D array for take: arr = arr.take(indx[1], axis=ax) ax += 1 return arr, no_copy def _check_multi_index(self, arr, index): """Check a multi index item getting and simple setting. Parameters ---------- arr : ndarray Array to be indexed, must be a reshaped arange. index : tuple of indexing objects Index being tested. """ # Test item getting try: mimic_get, no_copy = self._get_multi_index(arr, index) except Exception as e: prev_refcount = sys.getrefcount(arr) assert_raises(Exception, arr.__getitem__, index) assert_raises(Exception, arr.__setitem__, index, 0) assert_equal(prev_refcount, sys.getrefcount(arr)) return self._compare_index_result(arr, index, mimic_get, no_copy) def _check_single_index(self, arr, index): """Check a single index item getting and simple setting. Parameters ---------- arr : ndarray Array to be indexed, must be an arange. index : indexing object Index being tested. Must be a single index and not a tuple of indexing objects (see also `_check_multi_index`). """ try: mimic_get, no_copy = self._get_multi_index(arr, (index,)) except Exception as e: prev_refcount = sys.getrefcount(arr) assert_raises(Exception, arr.__getitem__, index) assert_raises(Exception, arr.__setitem__, index, 0) assert_equal(prev_refcount, sys.getrefcount(arr)) return self._compare_index_result(arr, index, mimic_get, no_copy) def _compare_index_result(self, arr, index, mimic_get, no_copy): """Compare mimicked result to indexing result. """ arr = arr.copy() indexed_arr = arr[index] assert_array_equal(indexed_arr, mimic_get) # Check if we got a view, unless its a 0-sized or 0-d array. # (then its not a view, and that does not matter) if indexed_arr.size != 0 and indexed_arr.ndim != 0: assert_(np.may_share_memory(indexed_arr, arr) == no_copy) # Check reference count of the original array if no_copy: # refcount increases by one: assert_equal(sys.getrefcount(arr), 3) else: assert_equal(sys.getrefcount(arr), 2) # Test non-broadcast setitem: b = arr.copy() b[index] = mimic_get + 1000 if b.size == 0: return # nothing to compare here... if no_copy and indexed_arr.ndim != 0: # change indexed_arr in-place to manipulate original: indexed_arr += 1000 assert_array_equal(arr, b) return # Use the fact that the array is originally an arange: arr.flat[indexed_arr.ravel()] += 1000 assert_array_equal(arr, b) def test_boolean(self): a = np.array(5) assert_equal(a[np.array(True)], 5) a[np.array(True)] = 1 assert_equal(a, 1) # NOTE: This is different from normal broadcasting, as # arr[boolean_array] works like in a multi index. Which means # it is aligned to the left. This is probably correct for # consistency with arr[boolean_array,] also no broadcasting # is done at all self._check_multi_index(self.a, (np.zeros_like(self.a, dtype=bool),)) self._check_multi_index(self.a, (np.zeros_like(self.a, dtype=bool)[..., 0],)) self._check_multi_index(self.a, (np.zeros_like(self.a, dtype=bool)[None, ...],)) def test_multidim(self): # Automatically test combinations with complex indexes on 2nd (or 1st) # 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. warnings.filterwarnings('error', '', DeprecationWarning) for simple_pos in [0, 2, 3]: tocheck = [self.fill_indices, self.complex_indices, self.fill_indices, self.fill_indices] tocheck[simple_pos] = self.simple_indices for index in product(*tocheck): index = tuple(i for i in index if i != 'skip') self._check_multi_index(self.a, index) self._check_multi_index(self.b, index) # Check very simple item getting: self._check_multi_index(self.a, (0, 0, 0, 0)) self._check_multi_index(self.b, (0, 0, 0, 0)) # Also check (simple cases of) too many indices: assert_raises(IndexError, self.a.__getitem__, (0, 0, 0, 0, 0)) assert_raises(IndexError, self.a.__setitem__, (0, 0, 0, 0, 0), 0) assert_raises(IndexError, self.a.__getitem__, (0, 0, [1], 0, 0)) assert_raises(IndexError, self.a.__setitem__, (0, 0, [1], 0, 0), 0) def test_1d(self): a = np.arange(10) with warnings.catch_warnings(): warnings.filterwarnings('error', '', DeprecationWarning) for index in self.complex_indices: self._check_single_index(a, index) if __name__ == "__main__": run_module_suite() numpy-1.8.2/numpy/core/tests/test_multiarray.py0000664000175100017510000043354412370216243023105 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function import tempfile import sys import os import shutil import warnings import io from decimal import Decimal import numpy as np from nose import SkipTest from numpy.core import * from numpy.compat import asbytes, getexception, strchar, sixu from test_print import in_foreign_locale from numpy.core.multiarray_tests import ( test_neighborhood_iterator, test_neighborhood_iterator_oob, test_pydatamem_seteventhook_start, test_pydatamem_seteventhook_end, test_inplace_increment, get_buffer_info ) from numpy.testing import ( TestCase, run_module_suite, assert_, assert_raises, assert_equal, assert_almost_equal, assert_array_equal, assert_array_almost_equal, assert_allclose, assert_array_less, runstring, dec ) # Need to test an object that does not fully implement math interface from datetime import timedelta if sys.version_info[:2] > (3, 2): # In Python 3.3 the representation of empty shape, strides and suboffsets # is an empty tuple instead of None. # http://docs.python.org/dev/whatsnew/3.3.html#api-changes EMPTY = () else: EMPTY = None class TestFlags(TestCase): def setUp(self): self.a = arange(10) def test_writeable(self): mydict = locals() self.a.flags.writeable = False self.assertRaises(ValueError, runstring, 'self.a[0] = 3', mydict) self.assertRaises(ValueError, runstring, 'self.a[0:1].itemset(3)', mydict) self.a.flags.writeable = True self.a[0] = 5 self.a[0] = 0 def test_otherflags(self): assert_equal(self.a.flags.carray, True) assert_equal(self.a.flags.farray, False) assert_equal(self.a.flags.behaved, True) assert_equal(self.a.flags.fnc, False) assert_equal(self.a.flags.forc, True) assert_equal(self.a.flags.owndata, True) assert_equal(self.a.flags.writeable, True) assert_equal(self.a.flags.aligned, True) assert_equal(self.a.flags.updateifcopy, False) class TestHash(TestCase): # see #3793 def test_int(self): for st, ut, s in [(np.int8, np.uint8, 8), (np.int16, np.uint16, 16), (np.int32, np.uint32, 32), (np.int64, np.uint64, 64)]: for i in range(1, s): assert_equal(hash(st(-2**i)), hash(-2**i), err_msg="%r: -2**%d" % (st, i)) assert_equal(hash(st(2**(i - 1))), hash(2**(i - 1)), err_msg="%r: 2**%d" % (st, i - 1)) assert_equal(hash(st(2**i - 1)), hash(2**i - 1), err_msg="%r: 2**%d - 1" % (st, i)) i = max(i - 1, 1) assert_equal(hash(ut(2**(i - 1))), hash(2**(i - 1)), err_msg="%r: 2**%d" % (ut, i - 1)) assert_equal(hash(ut(2**i - 1)), hash(2**i - 1), err_msg="%r: 2**%d - 1" % (ut, i)) class TestAttributes(TestCase): def setUp(self): self.one = arange(10) self.two = arange(20).reshape(4, 5) self.three = arange(60, dtype=float64).reshape(2, 5, 6) def test_attributes(self): assert_equal(self.one.shape, (10,)) assert_equal(self.two.shape, (4, 5)) assert_equal(self.three.shape, (2, 5, 6)) self.three.shape = (10, 3, 2) assert_equal(self.three.shape, (10, 3, 2)) self.three.shape = (2, 5, 6) assert_equal(self.one.strides, (self.one.itemsize,)) num = self.two.itemsize assert_equal(self.two.strides, (5*num, num)) num = self.three.itemsize assert_equal(self.three.strides, (30*num, 6*num, num)) assert_equal(self.one.ndim, 1) assert_equal(self.two.ndim, 2) assert_equal(self.three.ndim, 3) num = self.two.itemsize assert_equal(self.two.size, 20) assert_equal(self.two.nbytes, 20*num) assert_equal(self.two.itemsize, self.two.dtype.itemsize) assert_equal(self.two.base, arange(20)) def test_dtypeattr(self): assert_equal(self.one.dtype, dtype(int_)) assert_equal(self.three.dtype, dtype(float_)) assert_equal(self.one.dtype.char, 'l') assert_equal(self.three.dtype.char, 'd') self.assertTrue(self.three.dtype.str[0] in '<>') assert_equal(self.one.dtype.str[1], 'i') assert_equal(self.three.dtype.str[1], 'f') def test_int_subclassing(self): # Regression test for https://github.com/numpy/numpy/pull/3526 numpy_int = np.int_(0) if sys.version_info[0] >= 3: # On Py3k int_ should not inherit from int, because it's not fixed-width anymore assert_equal(isinstance(numpy_int, int), False) else: # Otherwise, it should inherit from int... assert_equal(isinstance(numpy_int, int), True) # ... and fast-path checks on C-API level should also work from numpy.core.multiarray_tests import test_int_subclass assert_equal(test_int_subclass(numpy_int), True) def test_stridesattr(self): x = self.one def make_array(size, offset, strides): return ndarray(size, buffer=x, dtype=int, offset=offset*x.itemsize, strides=strides*x.itemsize) assert_equal(make_array(4, 4, -1), array([4, 3, 2, 1])) self.assertRaises(ValueError, make_array, 4, 4, -2) self.assertRaises(ValueError, make_array, 4, 2, -1) self.assertRaises(ValueError, make_array, 8, 3, 1) assert_equal(make_array(8, 3, 0), np.array([3]*8)) # Check behavior reported in gh-2503: self.assertRaises(ValueError, make_array, (2, 3), 5, array([-2, -3])) make_array(0, 0, 10) def test_set_stridesattr(self): x = self.one def make_array(size, offset, strides): try: r = ndarray([size], dtype=int, buffer=x, offset=offset*x.itemsize) except: raise RuntimeError(getexception()) r.strides = strides=strides*x.itemsize return r assert_equal(make_array(4, 4, -1), array([4, 3, 2, 1])) assert_equal(make_array(7, 3, 1), array([3, 4, 5, 6, 7, 8, 9])) self.assertRaises(ValueError, make_array, 4, 4, -2) self.assertRaises(ValueError, make_array, 4, 2, -1) self.assertRaises(RuntimeError, make_array, 8, 3, 1) # Check that the true extent of the array is used. # Test relies on as_strided base not exposing a buffer. x = np.lib.stride_tricks.as_strided(arange(1), (10, 10), (0, 0)) def set_strides(arr, strides): arr.strides = strides self.assertRaises(ValueError, set_strides, x, (10*x.itemsize, x.itemsize)) # Test for offset calculations: x = np.lib.stride_tricks.as_strided(np.arange(10, dtype=np.int8)[-1], shape=(10,), strides=(-1,)) self.assertRaises(ValueError, set_strides, x[::-1], -1) a = x[::-1] a.strides = 1 a[::2].strides = 2 def test_fill(self): for t in "?bhilqpBHILQPfdgFDGO": x = empty((3, 2, 1), t) y = empty((3, 2, 1), t) x.fill(1) y[...] = 1 assert_equal(x, y) def test_fill_struct_array(self): # Filling from a scalar x = array([(0, 0.0), (1, 1.0)], dtype='i4,f8') x.fill(x[0]) assert_equal(x['f1'][1], x['f1'][0]) # Filling from a tuple that can be converted # to a scalar x = np.zeros(2, dtype=[('a', 'f8'), ('b', 'i4')]) x.fill((3.5, -2)) assert_array_equal(x['a'], [3.5, 3.5]) assert_array_equal(x['b'], [-2, -2]) class TestAssignment(TestCase): def test_assignment_broadcasting(self): a = np.arange(6).reshape(2, 3) # Broadcasting the input to the output a[...] = np.arange(3) assert_equal(a, [[0, 1, 2], [0, 1, 2]]) a[...] = np.arange(2).reshape(2, 1) assert_equal(a, [[0, 0, 0], [1, 1, 1]]) # For compatibility with <= 1.5, a limited version of broadcasting # the output to the input. # # This behavior is inconsistent with NumPy broadcasting # in general, because it only uses one of the two broadcasting # rules (adding a new "1" dimension to the left of the shape), # applied to the output instead of an input. In NumPy 2.0, this kind # of broadcasting assignment will likely be disallowed. a[...] = np.arange(6)[::-1].reshape(1, 2, 3) assert_equal(a, [[5, 4, 3], [2, 1, 0]]) # The other type of broadcasting would require a reduction operation. def assign(a, b): a[...] = b assert_raises(ValueError, assign, a, np.arange(12).reshape(2, 2, 3)) class TestDtypedescr(TestCase): def test_construction(self): d1 = dtype('i4') assert_equal(d1, dtype(int32)) d2 = dtype('f8') assert_equal(d2, dtype(float64)) class TestZeroRank(TestCase): def setUp(self): self.d = array(0), array('x', object) def test_ellipsis_subscript(self): a, b = self.d self.assertEqual(a[...], 0) self.assertEqual(b[...], 'x') self.assertTrue(a[...] is a) self.assertTrue(b[...] is b) def test_empty_subscript(self): a, b = self.d self.assertEqual(a[()], 0) self.assertEqual(b[()], 'x') self.assertTrue(type(a[()]) is a.dtype.type) self.assertTrue(type(b[()]) is str) def test_invalid_subscript(self): a, b = self.d self.assertRaises(IndexError, lambda x: x[0], a) self.assertRaises(IndexError, lambda x: x[0], b) self.assertRaises(IndexError, lambda x: x[array([], int)], a) self.assertRaises(IndexError, lambda x: x[array([], int)], b) def test_ellipsis_subscript_assignment(self): a, b = self.d a[...] = 42 self.assertEqual(a, 42) b[...] = '' self.assertEqual(b.item(), '') def test_empty_subscript_assignment(self): a, b = self.d a[()] = 42 self.assertEqual(a, 42) b[()] = '' self.assertEqual(b.item(), '') def test_invalid_subscript_assignment(self): a, b = self.d def assign(x, i, v): x[i] = v self.assertRaises(IndexError, assign, a, 0, 42) self.assertRaises(IndexError, assign, b, 0, '') self.assertRaises(ValueError, assign, a, (), '') def test_newaxis(self): a, b = self.d self.assertEqual(a[newaxis].shape, (1,)) self.assertEqual(a[..., newaxis].shape, (1,)) self.assertEqual(a[newaxis, ...].shape, (1,)) self.assertEqual(a[..., newaxis].shape, (1,)) self.assertEqual(a[newaxis, ..., newaxis].shape, (1, 1)) self.assertEqual(a[..., newaxis, newaxis].shape, (1, 1)) self.assertEqual(a[newaxis, newaxis, ...].shape, (1, 1)) self.assertEqual(a[(newaxis,)*10].shape, (1,)*10) def test_invalid_newaxis(self): a, b = self.d def subscript(x, i): x[i] self.assertRaises(IndexError, subscript, a, (newaxis, 0)) self.assertRaises(IndexError, subscript, a, (newaxis,)*50) def test_constructor(self): x = ndarray(()) x[()] = 5 self.assertEqual(x[()], 5) y = ndarray((), buffer=x) y[()] = 6 self.assertEqual(x[()], 6) def test_output(self): x = array(2) self.assertRaises(ValueError, add, x, [1], x) class TestScalarIndexing(TestCase): def setUp(self): self.d = array([0, 1])[0] def test_ellipsis_subscript(self): a = self.d self.assertEqual(a[...], 0) self.assertEqual(a[...].shape, ()) def test_empty_subscript(self): a = self.d self.assertEqual(a[()], 0) self.assertEqual(a[()].shape, ()) def test_invalid_subscript(self): a = self.d self.assertRaises(IndexError, lambda x: x[0], a) self.assertRaises(IndexError, lambda x: x[array([], int)], a) def test_invalid_subscript_assignment(self): a = self.d def assign(x, i, v): x[i] = v self.assertRaises(TypeError, assign, a, 0, 42) def test_newaxis(self): a = self.d self.assertEqual(a[newaxis].shape, (1,)) self.assertEqual(a[..., newaxis].shape, (1,)) self.assertEqual(a[newaxis, ...].shape, (1,)) self.assertEqual(a[..., newaxis].shape, (1,)) self.assertEqual(a[newaxis, ..., newaxis].shape, (1, 1)) self.assertEqual(a[..., newaxis, newaxis].shape, (1, 1)) self.assertEqual(a[newaxis, newaxis, ...].shape, (1, 1)) self.assertEqual(a[(newaxis,)*10].shape, (1,)*10) def test_invalid_newaxis(self): a = self.d def subscript(x, i): x[i] self.assertRaises(IndexError, subscript, a, (newaxis, 0)) self.assertRaises(IndexError, subscript, a, (newaxis,)*50) def test_overlapping_assignment(self): # With positive strides a = np.arange(4) a[:-1] = a[1:] assert_equal(a, [1, 2, 3, 3]) a = np.arange(4) a[1:] = a[:-1] assert_equal(a, [0, 0, 1, 2]) # With positive and negative strides a = np.arange(4) a[:] = a[::-1] assert_equal(a, [3, 2, 1, 0]) a = np.arange(6).reshape(2, 3) a[::-1,:] = a[:, ::-1] assert_equal(a, [[5, 4, 3], [2, 1, 0]]) a = np.arange(6).reshape(2, 3) a[::-1, ::-1] = a[:, ::-1] assert_equal(a, [[3, 4, 5], [0, 1, 2]]) # With just one element overlapping a = np.arange(5) a[:3] = a[2:] assert_equal(a, [2, 3, 4, 3, 4]) a = np.arange(5) a[2:] = a[:3] assert_equal(a, [0, 1, 0, 1, 2]) a = np.arange(5) a[2::-1] = a[2:] assert_equal(a, [4, 3, 2, 3, 4]) a = np.arange(5) a[2:] = a[2::-1] assert_equal(a, [0, 1, 2, 1, 0]) a = np.arange(5) a[2::-1] = a[:1:-1] assert_equal(a, [2, 3, 4, 3, 4]) a = np.arange(5) a[:1:-1] = a[2::-1] assert_equal(a, [0, 1, 0, 1, 2]) class TestCreation(TestCase): def test_from_attribute(self): class x(object): def __array__(self, dtype=None): pass self.assertRaises(ValueError, array, x()) def test_from_string(self) : types = np.typecodes['AllInteger'] + np.typecodes['Float'] nstr = ['123', '123'] result = array([123, 123], dtype=int) for type in types : msg = 'String conversion for %s' % type assert_equal(array(nstr, dtype=type), result, err_msg=msg) def test_void(self): arr = np.array([], dtype='V') assert_equal(arr.dtype.kind, 'V') def test_zeros(self): types = np.typecodes['AllInteger'] + np.typecodes['AllFloat'] for dt in types: d = np.zeros((13,), dtype=dt) assert_equal(np.count_nonzero(d), 0) # true for ieee floats assert_equal(d.sum(), 0) assert_(not d.any()) d = np.zeros(2, dtype='(2,4)i4') assert_equal(np.count_nonzero(d), 0) assert_equal(d.sum(), 0) assert_(not d.any()) d = np.zeros(2, dtype='4i4') assert_equal(np.count_nonzero(d), 0) assert_equal(d.sum(), 0) assert_(not d.any()) d = np.zeros(2, dtype='(2,4)i4, (2,4)i4') assert_equal(np.count_nonzero(d), 0) @dec.slow def test_zeros_big(self): # test big array as they might be allocated different by the sytem types = np.typecodes['AllInteger'] + np.typecodes['AllFloat'] for dt in types: d = np.zeros((30 * 1024**2,), dtype=dt) assert_(not d.any()) def test_zeros_obj(self): # test initialization from PyLong(0) d = np.zeros((13,), dtype=object) assert_array_equal(d, [0] * 13) assert_equal(np.count_nonzero(d), 0) def test_non_sequence_sequence(self): """Should not segfault. Class Fail breaks the sequence protocol for new style classes, i.e., those derived from object. Class Map is a mapping type indicated by raising a ValueError. At some point we may raise a warning instead of an error in the Fail case. """ class Fail(object): def __len__(self): return 1 def __getitem__(self, index): raise ValueError() class Map(object): def __len__(self): return 1 def __getitem__(self, index): raise KeyError() a = np.array([Map()]) assert_(a.shape == (1,)) assert_(a.dtype == np.dtype(object)) assert_raises(ValueError, np.array, [Fail()]) class TestStructured(TestCase): def test_subarray_field_access(self): 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'])) # In Fortran order, the subarray gets appended # like in all other cases, not prepended as a special case b = a.copy(order='F') assert_equal(a['a'].shape, b['a'].shape) assert_equal(a.T['a'].shape, a.T.copy()['a'].shape) def test_subarray_comparison(self): # Check that comparisons between record arrays with # multi-dimensional field types work properly a = np.rec.fromrecords( [([1, 2, 3], 'a', [[1, 2], [3, 4]]), ([3, 3, 3], 'b', [[0, 0], [0, 0]])], dtype=[('a', ('f4', 3)), ('b', np.object), ('c', ('i4', (2, 2)))]) b = a.copy() assert_equal(a==b, [True, True]) assert_equal(a!=b, [False, False]) b[1].b = 'c' assert_equal(a==b, [True, False]) assert_equal(a!=b, [False, True]) for i in range(3): b[0].a = a[0].a b[0].a[i] = 5 assert_equal(a==b, [False, False]) assert_equal(a!=b, [True, True]) for i in range(2): for j in range(2): b = a.copy() b[0].c[i, j] = 10 assert_equal(a==b, [False, True]) assert_equal(a!=b, [True, False]) # Check that broadcasting with a subarray works a = np.array([[(0,)], [(1,)]], dtype=[('a', 'f8')]) b = np.array([(0,), (0,), (1,)], dtype=[('a', 'f8')]) assert_equal(a==b, [[True, True, False], [False, False, True]]) assert_equal(b==a, [[True, True, False], [False, False, True]]) a = np.array([[(0,)], [(1,)]], dtype=[('a', 'f8', (1,))]) b = np.array([(0,), (0,), (1,)], dtype=[('a', 'f8', (1,))]) assert_equal(a==b, [[True, True, False], [False, False, True]]) assert_equal(b==a, [[True, True, False], [False, False, True]]) a = np.array([[([0, 0],)], [([1, 1],)]], dtype=[('a', 'f8', (2,))]) b = np.array([([0, 0],), ([0, 1],), ([1, 1],)], dtype=[('a', 'f8', (2,))]) assert_equal(a==b, [[True, False, False], [False, False, True]]) assert_equal(b==a, [[True, False, False], [False, False, True]]) # Check that broadcasting Fortran-style arrays with a subarray work a = np.array([[([0, 0],)], [([1, 1],)]], dtype=[('a', 'f8', (2,))], order='F') b = np.array([([0, 0],), ([0, 1],), ([1, 1],)], dtype=[('a', 'f8', (2,))]) assert_equal(a==b, [[True, False, False], [False, False, True]]) assert_equal(b==a, [[True, False, False], [False, False, True]]) # Check that incompatible sub-array shapes don't result to broadcasting x = np.zeros((1,), dtype=[('a', ('f4', (1, 2))), ('b', 'i1')]) y = np.zeros((1,), dtype=[('a', ('f4', (2,))), ('b', 'i1')]) assert_equal(x == y, False) x = np.zeros((1,), dtype=[('a', ('f4', (2, 1))), ('b', 'i1')]) y = np.zeros((1,), dtype=[('a', ('f4', (2,))), ('b', 'i1')]) assert_equal(x == y, False) class TestBool(TestCase): def test_test_interning(self): a0 = bool_(0) b0 = bool_(False) self.assertTrue(a0 is b0) a1 = bool_(1) b1 = bool_(True) self.assertTrue(a1 is b1) self.assertTrue(array([True])[0] is a1) self.assertTrue(array(True)[()] is a1) class TestMethods(TestCase): def test_test_round(self): assert_equal(array([1.2, 1.5]).round(), [1, 2]) assert_equal(array(1.5).round(), 2) assert_equal(array([12.2, 15.5]).round(-1), [10, 20]) assert_equal(array([12.15, 15.51]).round(1), [12.2, 15.5]) def test_transpose(self): a = array([[1, 2], [3, 4]]) assert_equal(a.transpose(), [[1, 3], [2, 4]]) self.assertRaises(ValueError, lambda: a.transpose(0)) self.assertRaises(ValueError, lambda: a.transpose(0, 0)) self.assertRaises(ValueError, lambda: a.transpose(0, 1, 2)) def test_sort(self): # test ordering for floats and complex containing nans. It is only # necessary to check the lessthan comparison, so sorts that # only follow the insertion sort path are sufficient. We only # test doubles and complex doubles as the logic is the same. # check doubles msg = "Test real sort order with nans" a = np.array([np.nan, 1, 0]) b = sort(a) assert_equal(b, a[::-1], msg) # check complex msg = "Test complex sort order with nans" a = np.zeros(9, dtype=np.complex128) a.real += [np.nan, np.nan, np.nan, 1, 0, 1, 1, 0, 0] a.imag += [np.nan, 1, 0, np.nan, np.nan, 1, 0, 1, 0] b = sort(a) assert_equal(b, a[::-1], msg) # all c scalar sorts use the same code with different types # so it suffices to run a quick check with one type. The number # of sorted items must be greater than ~50 to check the actual # algorithm because quick and merge sort fall over to insertion # sort for small arrays. a = np.arange(101) b = a[::-1].copy() for kind in ['q', 'm', 'h'] : msg = "scalar sort, kind=%s" % kind c = a.copy(); c.sort(kind=kind) assert_equal(c, a, msg) c = b.copy(); c.sort(kind=kind) assert_equal(c, a, msg) # test complex sorts. These use the same code as the scalars # but the compare fuction differs. ai = a*1j + 1 bi = b*1j + 1 for kind in ['q', 'm', 'h'] : msg = "complex sort, real part == 1, kind=%s" % kind c = ai.copy(); c.sort(kind=kind) assert_equal(c, ai, msg) c = bi.copy(); c.sort(kind=kind) assert_equal(c, ai, msg) ai = a + 1j bi = b + 1j for kind in ['q', 'm', 'h'] : msg = "complex sort, imag part == 1, kind=%s" % kind c = ai.copy(); c.sort(kind=kind) assert_equal(c, ai, msg) c = bi.copy(); c.sort(kind=kind) assert_equal(c, ai, msg) # test string sorts. s = 'aaaaaaaa' a = np.array([s + chr(i) for i in range(101)]) b = a[::-1].copy() for kind in ['q', 'm', 'h'] : msg = "string sort, kind=%s" % kind c = a.copy(); c.sort(kind=kind) assert_equal(c, a, msg) c = b.copy(); c.sort(kind=kind) assert_equal(c, a, msg) # test unicode sorts. s = 'aaaaaaaa' a = np.array([s + chr(i) for i in range(101)], dtype=np.unicode) b = a[::-1].copy() for kind in ['q', 'm', 'h'] : msg = "unicode sort, kind=%s" % kind c = a.copy(); c.sort(kind=kind) assert_equal(c, a, msg) c = b.copy(); c.sort(kind=kind) assert_equal(c, a, msg) # test object array sorts. a = np.empty((101,), dtype=np.object) a[:] = list(range(101)) b = a[::-1] for kind in ['q', 'h', 'm'] : msg = "object sort, kind=%s" % kind c = a.copy(); c.sort(kind=kind) assert_equal(c, a, msg) c = b.copy(); c.sort(kind=kind) assert_equal(c, a, msg) # test record array sorts. dt = np.dtype([('f', float), ('i', int)]) a = array([(i, i) for i in range(101)], dtype = dt) b = a[::-1] for kind in ['q', 'h', 'm'] : msg = "object sort, kind=%s" % kind c = a.copy(); c.sort(kind=kind) assert_equal(c, a, msg) c = b.copy(); c.sort(kind=kind) assert_equal(c, a, msg) # test datetime64 sorts. a = np.arange(0, 101, dtype='datetime64[D]') b = a[::-1] for kind in ['q', 'h', 'm'] : msg = "datetime64 sort, kind=%s" % kind c = a.copy(); c.sort(kind=kind) assert_equal(c, a, msg) c = b.copy(); c.sort(kind=kind) assert_equal(c, a, msg) # test timedelta64 sorts. a = np.arange(0, 101, dtype='timedelta64[D]') b = a[::-1] for kind in ['q', 'h', 'm'] : msg = "timedelta64 sort, kind=%s" % kind c = a.copy(); c.sort(kind=kind) assert_equal(c, a, msg) c = b.copy(); c.sort(kind=kind) assert_equal(c, a, msg) # check axis handling. This should be the same for all type # specific sorts, so we only check it for one type and one kind a = np.array([[3, 2], [1, 0]]) b = np.array([[1, 0], [3, 2]]) c = np.array([[2, 3], [0, 1]]) d = a.copy() d.sort(axis=0) assert_equal(d, b, "test sort with axis=0") d = a.copy() d.sort(axis=1) assert_equal(d, c, "test sort with axis=1") d = a.copy() d.sort() assert_equal(d, c, "test sort with default axis") def test_copy(self): def assert_fortran(arr): assert_(arr.flags.fortran) assert_(arr.flags.f_contiguous) assert_(not arr.flags.c_contiguous) def assert_c(arr): assert_(not arr.flags.fortran) assert_(not arr.flags.f_contiguous) assert_(arr.flags.c_contiguous) a = np.empty((2, 2), order='F') # Test copying a Fortran array assert_c(a.copy()) assert_c(a.copy('C')) assert_fortran(a.copy('F')) assert_fortran(a.copy('A')) # Now test starting with a C array. a = np.empty((2, 2), order='C') assert_c(a.copy()) assert_c(a.copy('C')) assert_fortran(a.copy('F')) assert_c(a.copy('A')) def test_sort_order(self): # Test sorting an array with fields x1=np.array([21, 32, 14]) x2=np.array(['my', 'first', 'name']) x3=np.array([3.1, 4.5, 6.2]) r=np.rec.fromarrays([x1, x2, x3], names='id,word,number') r.sort(order=['id']) assert_equal(r.id, array([14, 21, 32])) assert_equal(r.word, array(['name', 'my', 'first'])) assert_equal(r.number, array([6.2, 3.1, 4.5])) r.sort(order=['word']) assert_equal(r.id, array([32, 21, 14])) assert_equal(r.word, array(['first', 'my', 'name'])) assert_equal(r.number, array([4.5, 3.1, 6.2])) r.sort(order=['number']) assert_equal(r.id, array([21, 32, 14])) assert_equal(r.word, array(['my', 'first', 'name'])) assert_equal(r.number, array([3.1, 4.5, 6.2])) if sys.byteorder == 'little': strtype = '>i2' else: strtype = ' p[:, i]).all(), msg="%d: %r < %r" % (i, p[:, i], p[:, i + 1:].T)) aae(p, d1[np.arange(d1.shape[0])[:, None], np.argpartition(d1, i, axis=1, kind=k)]) p = np.partition(d0, i, axis=0, kind=k) aae(p[i,:], np.array([i] * d1.shape[0], dtype=dt)) # array_less does not seem to work right at((p[:i,:] <= p[i,:]).all(), msg="%d: %r <= %r" % (i, p[i,:], p[:i,:])) at((p[i + 1:,:] > p[i,:]).all(), msg="%d: %r < %r" % (i, p[i,:], p[:, i + 1:])) aae(p, d0[np.argpartition(d0, i, axis=0, kind=k), np.arange(d0.shape[1])[None,:]]) # check inplace dc = d.copy() dc.partition(i, kind=k) assert_equal(dc, np.partition(d, i, kind=k)) dc = d0.copy() dc.partition(i, axis=0, kind=k) assert_equal(dc, np.partition(d0, i, axis=0, kind=k)) dc = d1.copy() dc.partition(i, axis=1, kind=k) assert_equal(dc, np.partition(d1, i, axis=1, kind=k)) def assert_partitioned(self, d, kth): prev = 0 for k in np.sort(kth): assert_array_less(d[prev:k], d[k], err_msg='kth %d' % k) assert_((d[k:] >= d[k]).all(), msg="kth %d, %r not greater equal %d" % (k, d[k:], d[k])) prev = k + 1 def test_partition_iterative(self): d = np.arange(17) kth = (0, 1, 2, 429, 231) assert_raises(ValueError, d.partition, kth) assert_raises(ValueError, d.argpartition, kth) d = np.arange(10).reshape((2, 5)) assert_raises(ValueError, d.partition, kth, axis=0) assert_raises(ValueError, d.partition, kth, axis=1) assert_raises(ValueError, np.partition, d, kth, axis=1) assert_raises(ValueError, np.partition, d, kth, axis=None) d = np.array([3, 4, 2, 1]) p = np.partition(d, (0, 3)) self.assert_partitioned(p, (0, 3)) self.assert_partitioned(d[np.argpartition(d, (0, 3))], (0, 3)) assert_array_equal(p, np.partition(d, (-3, -1))) assert_array_equal(p, d[np.argpartition(d, (-3, -1))]) d = np.arange(17) np.random.shuffle(d) d.partition(range(d.size)) assert_array_equal(np.arange(17), d) np.random.shuffle(d) assert_array_equal(np.arange(17), d[d.argpartition(range(d.size))]) # test unsorted kth d = np.arange(17) np.random.shuffle(d) keys = np.array([1, 3, 8, -2]) np.random.shuffle(d) p = np.partition(d, keys) self.assert_partitioned(p, keys) p = d[np.argpartition(d, keys)] self.assert_partitioned(p, keys) np.random.shuffle(keys) assert_array_equal(np.partition(d, keys), p) assert_array_equal(d[np.argpartition(d, keys)], p) # equal kth d = np.arange(20)[::-1] self.assert_partitioned(np.partition(d, [5]*4), [5]) self.assert_partitioned(np.partition(d, [5]*4 + [6, 13]), [5]*4 + [6, 13]) self.assert_partitioned(d[np.argpartition(d, [5]*4)], [5]) self.assert_partitioned(d[np.argpartition(d, [5]*4 + [6, 13])], [5]*4 + [6, 13]) d = np.arange(12) np.random.shuffle(d) d1 = np.tile(np.arange(12), (4, 1)) map(np.random.shuffle, d1) d0 = np.transpose(d1) kth = (1, 6, 7, -1) p = np.partition(d1, kth, axis=1) pa = d1[np.arange(d1.shape[0])[:, None], d1.argpartition(kth, axis=1)] assert_array_equal(p, pa) for i in range(d1.shape[0]): self.assert_partitioned(p[i,:], kth) p = np.partition(d0, kth, axis=0) pa = d0[np.argpartition(d0, kth, axis=0), np.arange(d0.shape[1])[None,:]] assert_array_equal(p, pa) for i in range(d0.shape[1]): self.assert_partitioned(p[:, i], kth) def test_partition_cdtype(self): d = array([('Galahad', 1.7, 38), ('Arthur', 1.8, 41), ('Lancelot', 1.9, 38)], dtype=[('name', '|S10'), ('height', '= 3: return loads(obj, encoding='latin1') else: return loads(obj) # version 0 pickles, using protocol=2 to pickle # version 0 doesn't have a version field def test_version0_int8(self): s = '\x80\x02cnumpy.core._internal\n_reconstruct\nq\x01cnumpy\nndarray\nq\x02K\x00\x85U\x01b\x87Rq\x03(K\x04\x85cnumpy\ndtype\nq\x04U\x02i1K\x00K\x01\x87Rq\x05(U\x01|NNJ\xff\xff\xff\xffJ\xff\xff\xff\xfftb\x89U\x04\x01\x02\x03\x04tb.' a = array([1, 2, 3, 4], dtype=int8) p = self._loads(asbytes(s)) assert_equal(a, p) def test_version0_float32(self): s = '\x80\x02cnumpy.core._internal\n_reconstruct\nq\x01cnumpy\nndarray\nq\x02K\x00\x85U\x01b\x87Rq\x03(K\x04\x85cnumpy\ndtype\nq\x04U\x02f4K\x00K\x01\x87Rq\x05(U\x01= g2, [g1[i] >= g2[i] for i in [0, 1, 2]]) assert_array_equal(g1 < g2, [g1[i] < g2[i] for i in [0, 1, 2]]) assert_array_equal(g1 > g2, [g1[i] > g2[i] for i in [0, 1, 2]]) def test_mixed(self): g1 = array(["spam", "spa", "spammer", "and eggs"]) g2 = "spam" assert_array_equal(g1 == g2, [x == g2 for x in g1]) assert_array_equal(g1 != g2, [x != g2 for x in g1]) assert_array_equal(g1 < g2, [x < g2 for x in g1]) assert_array_equal(g1 > g2, [x > g2 for x in g1]) assert_array_equal(g1 <= g2, [x <= g2 for x in g1]) assert_array_equal(g1 >= g2, [x >= g2 for x in g1]) def test_unicode(self): g1 = array([sixu("This"), sixu("is"), sixu("example")]) g2 = array([sixu("This"), sixu("was"), sixu("example")]) assert_array_equal(g1 == g2, [g1[i] == g2[i] for i in [0, 1, 2]]) assert_array_equal(g1 != g2, [g1[i] != g2[i] for i in [0, 1, 2]]) assert_array_equal(g1 <= g2, [g1[i] <= g2[i] for i in [0, 1, 2]]) assert_array_equal(g1 >= g2, [g1[i] >= g2[i] for i in [0, 1, 2]]) assert_array_equal(g1 < g2, [g1[i] < g2[i] for i in [0, 1, 2]]) assert_array_equal(g1 > g2, [g1[i] > g2[i] for i in [0, 1, 2]]) class TestArgmax(TestCase): nan_arr = [ ([0, 1, 2, 3, np.nan], 4), ([0, 1, 2, np.nan, 3], 3), ([np.nan, 0, 1, 2, 3], 0), ([np.nan, 0, np.nan, 2, 3], 0), ([0, 1, 2, 3, complex(0, np.nan)], 4), ([0, 1, 2, 3, complex(np.nan, 0)], 4), ([0, 1, 2, complex(np.nan, 0), 3], 3), ([0, 1, 2, complex(0, np.nan), 3], 3), ([complex(0, np.nan), 0, 1, 2, 3], 0), ([complex(np.nan, np.nan), 0, 1, 2, 3], 0), ([complex(np.nan, 0), complex(np.nan, 2), complex(np.nan, 1)], 0), ([complex(np.nan, np.nan), complex(np.nan, 2), complex(np.nan, 1)], 0), ([complex(np.nan, 0), complex(np.nan, 2), complex(np.nan, np.nan)], 0), ([complex(0, 0), complex(0, 2), complex(0, 1)], 1), ([complex(1, 0), complex(0, 2), complex(0, 1)], 0), ([complex(1, 0), complex(0, 2), complex(1, 1)], 2), ([np.datetime64('1923-04-14T12:43:12'), np.datetime64('1994-06-21T14:43:15'), np.datetime64('2001-10-15T04:10:32'), np.datetime64('1995-11-25T16:02:16'), np.datetime64('2005-01-04T03:14:12'), np.datetime64('2041-12-03T14:05:03')], 5), ([np.datetime64('1935-09-14T04:40:11'), np.datetime64('1949-10-12T12:32:11'), np.datetime64('2010-01-03T05:14:12'), np.datetime64('2015-11-20T12:20:59'), np.datetime64('1932-09-23T10:10:13'), np.datetime64('2014-10-10T03:50:30')], 3), ([np.datetime64('2059-03-14T12:43:12'), np.datetime64('1996-09-21T14:43:15'), np.datetime64('2001-10-15T04:10:32'), np.datetime64('2022-12-25T16:02:16'), np.datetime64('1963-10-04T03:14:12'), np.datetime64('2013-05-08T18:15:23')], 0), ([timedelta(days=5, seconds=14), timedelta(days=2, seconds=35), timedelta(days=-1, seconds=23)], 0), ([timedelta(days=1, seconds=43), timedelta(days=10, seconds=5), timedelta(days=5, seconds=14)], 1), ([timedelta(days=10, seconds=24), timedelta(days=10, seconds=5), timedelta(days=10, seconds=43)], 2), # Can't reduce a "flexible type" #(['a', 'z', 'aa', 'zz'], 3), #(['zz', 'a', 'aa', 'a'], 0), #(['aa', 'z', 'zz', 'a'], 2), ] def test_all(self): a = np.random.normal(0, 1, (4, 5, 6, 7, 8)) for i in range(a.ndim): amax = a.max(i) aargmax = a.argmax(i) axes = list(range(a.ndim)) axes.remove(i) assert_(all(amax == aargmax.choose(*a.transpose(i,*axes)))) def test_combinations(self): for arr, pos in self.nan_arr: assert_equal(np.argmax(arr), pos, err_msg="%r"%arr) assert_equal(arr[np.argmax(arr)], np.max(arr), err_msg="%r"%arr) class TestArgmin(TestCase): nan_arr = [ ([0, 1, 2, 3, np.nan], 4), ([0, 1, 2, np.nan, 3], 3), ([np.nan, 0, 1, 2, 3], 0), ([np.nan, 0, np.nan, 2, 3], 0), ([0, 1, 2, 3, complex(0, np.nan)], 4), ([0, 1, 2, 3, complex(np.nan, 0)], 4), ([0, 1, 2, complex(np.nan, 0), 3], 3), ([0, 1, 2, complex(0, np.nan), 3], 3), ([complex(0, np.nan), 0, 1, 2, 3], 0), ([complex(np.nan, np.nan), 0, 1, 2, 3], 0), ([complex(np.nan, 0), complex(np.nan, 2), complex(np.nan, 1)], 0), ([complex(np.nan, np.nan), complex(np.nan, 2), complex(np.nan, 1)], 0), ([complex(np.nan, 0), complex(np.nan, 2), complex(np.nan, np.nan)], 0), ([complex(0, 0), complex(0, 2), complex(0, 1)], 0), ([complex(1, 0), complex(0, 2), complex(0, 1)], 2), ([complex(1, 0), complex(0, 2), complex(1, 1)], 1), ([np.datetime64('1923-04-14T12:43:12'), np.datetime64('1994-06-21T14:43:15'), np.datetime64('2001-10-15T04:10:32'), np.datetime64('1995-11-25T16:02:16'), np.datetime64('2005-01-04T03:14:12'), np.datetime64('2041-12-03T14:05:03')], 0), ([np.datetime64('1935-09-14T04:40:11'), np.datetime64('1949-10-12T12:32:11'), np.datetime64('2010-01-03T05:14:12'), np.datetime64('2014-11-20T12:20:59'), np.datetime64('2015-09-23T10:10:13'), np.datetime64('1932-10-10T03:50:30')], 5), ([np.datetime64('2059-03-14T12:43:12'), np.datetime64('1996-09-21T14:43:15'), np.datetime64('2001-10-15T04:10:32'), np.datetime64('2022-12-25T16:02:16'), np.datetime64('1963-10-04T03:14:12'), np.datetime64('2013-05-08T18:15:23')], 4), ([timedelta(days=5, seconds=14), timedelta(days=2, seconds=35), timedelta(days=-1, seconds=23)], 2), ([timedelta(days=1, seconds=43), timedelta(days=10, seconds=5), timedelta(days=5, seconds=14)], 0), ([timedelta(days=10, seconds=24), timedelta(days=10, seconds=5), timedelta(days=10, seconds=43)], 1), # Can't reduce a "flexible type" #(['a', 'z', 'aa', 'zz'], 0), #(['zz', 'a', 'aa', 'a'], 1), #(['aa', 'z', 'zz', 'a'], 3), ] def test_all(self): a = np.random.normal(0, 1, (4, 5, 6, 7, 8)) for i in range(a.ndim): amin = a.min(i) aargmin = a.argmin(i) axes = list(range(a.ndim)) axes.remove(i) assert_(all(amin == aargmin.choose(*a.transpose(i,*axes)))) def test_combinations(self): for arr, pos in self.nan_arr: assert_equal(np.argmin(arr), pos, err_msg="%r"%arr) assert_equal(arr[np.argmin(arr)], np.min(arr), err_msg="%r"%arr) def test_minimum_signed_integers(self): a = np.array([1, -2**7, -2**7 + 1], dtype=np.int8) assert_equal(np.argmin(a), 1) a = np.array([1, -2**15, -2**15 + 1], dtype=np.int16) assert_equal(np.argmin(a), 1) a = np.array([1, -2**31, -2**31 + 1], dtype=np.int32) assert_equal(np.argmin(a), 1) a = np.array([1, -2**63, -2**63 + 1], dtype=np.int64) assert_equal(np.argmin(a), 1) class TestMinMax(TestCase): def test_scalar(self): assert_raises(ValueError, np.amax, 1, 1) assert_raises(ValueError, np.amin, 1, 1) assert_equal(np.amax(1, axis=0), 1) assert_equal(np.amin(1, axis=0), 1) assert_equal(np.amax(1, axis=None), 1) assert_equal(np.amin(1, axis=None), 1) def test_axis(self): assert_raises(ValueError, np.amax, [1, 2, 3], 1000) assert_equal(np.amax([[1, 2, 3]], axis=1), 3) class TestNewaxis(TestCase): def test_basic(self): sk = array([0, -0.1, 0.1]) res = 250*sk[:, newaxis] assert_almost_equal(res.ravel(), 250*sk) class TestClip(TestCase): def _check_range(self, x, cmin, cmax): assert_(np.all(x >= cmin)) assert_(np.all(x <= cmax)) def _clip_type(self,type_group,array_max, clip_min,clip_max,inplace=False, expected_min=None,expected_max=None): if expected_min is None: expected_min = clip_min if expected_max is None: expected_max = clip_max for T in np.sctypes[type_group]: if sys.byteorder == 'little': byte_orders = ['=', '>'] else: byte_orders = ['<', '='] for byteorder in byte_orders: dtype = np.dtype(T).newbyteorder(byteorder) x = (np.random.random(1000) * array_max).astype(dtype) if inplace: x.clip(clip_min, clip_max, x) else: x = x.clip(clip_min, clip_max) byteorder = '=' if x.dtype.byteorder == '|': byteorder = '|' assert_equal(x.dtype.byteorder, byteorder) self._check_range(x, expected_min, expected_max) return x def test_basic(self): for inplace in [False, True]: self._clip_type('float', 1024, -12.8, 100.2, inplace=inplace) self._clip_type('float', 1024, 0, 0, inplace=inplace) self._clip_type('int', 1024, -120, 100.5, inplace=inplace) self._clip_type('int', 1024, 0, 0, inplace=inplace) x = self._clip_type('uint', 1024, -120, 100, expected_min=0, inplace=inplace) x = self._clip_type('uint', 1024, 0, 0, inplace=inplace) def test_record_array(self): rec = np.array([(-5, 2.0, 3.0), (5.0, 4.0, 3.0)], dtype=[('x', '= 3)) x = val.clip(min=3) assert_(np.all(x >= 3)) x = val.clip(max=4) assert_(np.all(x <= 4)) class TestPutmask(object): def tst_basic(self, x, T, mask, val): np.putmask(x, mask, val) assert_(np.all(x[mask] == T(val))) assert_(x.dtype == T) def test_ip_types(self): unchecked_types = [str, unicode, np.void, object] x = np.random.random(1000)*100 mask = x < 40 for val in [-100, 0, 15]: for types in np.sctypes.values(): for T in types: if T not in unchecked_types: yield self.tst_basic, x.copy().astype(T), T, mask, val def test_mask_size(self): assert_raises(ValueError, np.putmask, np.array([1, 2, 3]), [True], 5) def tst_byteorder(self, dtype): x = np.array([1, 2, 3], dtype) np.putmask(x, [True, False, True], -1) assert_array_equal(x, [-1, 2, -1]) def test_ip_byteorder(self): for dtype in ('>i4', 'f8'), ('z', 'i4', 'f8'), ('z', ' 1 minute on mechanical hard drive def test_big_binary(self): """Test workarounds for 32-bit limited fwrite, fseek, and ftell calls in windows. These normally would hang doing something like this. See http://projects.scipy.org/numpy/ticket/1660""" if sys.platform != 'win32': return try: # before workarounds, only up to 2**32-1 worked fourgbplus = 2**32 + 2**16 testbytes = np.arange(8, dtype=np.int8) n = len(testbytes) flike = tempfile.NamedTemporaryFile() f = flike.file np.tile(testbytes, fourgbplus // testbytes.nbytes).tofile(f) flike.seek(0) a = np.fromfile(f, dtype=np.int8) flike.close() assert_(len(a) == fourgbplus) # check only start and end for speed: assert_((a[:n] == testbytes).all()) assert_((a[-n:] == testbytes).all()) except (MemoryError, ValueError): pass def test_string(self): self._check_from('1,2,3,4', [1., 2., 3., 4.], sep=',') def test_counted_string(self): self._check_from('1,2,3,4', [1., 2., 3., 4.], count=4, sep=',') self._check_from('1,2,3,4', [1., 2., 3.], count=3, sep=',') self._check_from('1,2,3,4', [1., 2., 3., 4.], count=-1, sep=',') def test_string_with_ws(self): self._check_from('1 2 3 4 ', [1, 2, 3, 4], dtype=int, sep=' ') def test_counted_string_with_ws(self): self._check_from('1 2 3 4 ', [1, 2, 3], count=3, dtype=int, sep=' ') def test_ascii(self): self._check_from('1 , 2 , 3 , 4', [1., 2., 3., 4.], sep=',') self._check_from('1,2,3,4', [1., 2., 3., 4.], dtype=float, sep=',') def test_malformed(self): self._check_from('1.234 1,234', [1.234, 1.], sep=' ') def test_long_sep(self): self._check_from('1_x_3_x_4_x_5', [1, 3, 4, 5], sep='_x_') def test_dtype(self): v = np.array([1, 2, 3, 4], dtype=np.int_) self._check_from('1,2,3,4', v, sep=',', dtype=np.int_) def test_dtype_bool(self): # can't use _check_from because fromstring can't handle True/False v = np.array([True, False, True, False], dtype=np.bool_) s = '1,0,-2.3,0' f = open(self.filename, 'wb') f.write(asbytes(s)) f.close() y = np.fromfile(self.filename, sep=',', dtype=np.bool_) assert_(y.dtype == '?') assert_array_equal(y, v) def test_tofile_sep(self): x = np.array([1.51, 2, 3.51, 4], dtype=float) f = open(self.filename, 'w') x.tofile(f, sep=',') f.close() f = open(self.filename, 'r') s = f.read() f.close() assert_equal(s, '1.51,2.0,3.51,4.0') def test_tofile_format(self): x = np.array([1.51, 2, 3.51, 4], dtype=float) f = open(self.filename, 'w') x.tofile(f, sep=',', format='%.2f') f.close() f = open(self.filename, 'r') s = f.read() f.close() assert_equal(s, '1.51,2.00,3.51,4.00') def test_locale(self): in_foreign_locale(self.test_numbers)() in_foreign_locale(self.test_nan)() in_foreign_locale(self.test_inf)() in_foreign_locale(self.test_counted_string)() in_foreign_locale(self.test_ascii)() in_foreign_locale(self.test_malformed)() in_foreign_locale(self.test_tofile_sep)() in_foreign_locale(self.test_tofile_format)() class TestFromBuffer(object): def tst_basic(self, buffer, expected, kwargs): assert_array_equal(np.frombuffer(buffer,**kwargs), expected) def test_ip_basic(self): for byteorder in ['<', '>']: for dtype in [float, int, np.complex]: dt = np.dtype(dtype).newbyteorder(byteorder) x = (np.random.random((4, 7))*5).astype(dt) buf = x.tostring() yield self.tst_basic, buf, x.flat, {'dtype':dt} def test_empty(self): yield self.tst_basic, asbytes(''), np.array([]), {} class TestFlat(TestCase): def setUp(self): a0 = arange(20.0) a = a0.reshape(4, 5) a0.shape = (4, 5) a.flags.writeable = False self.a = a self.b = a[::2, ::2] self.a0 = a0 self.b0 = a0[::2, ::2] def test_contiguous(self): testpassed = False try: self.a.flat[12] = 100.0 except ValueError: testpassed = True assert testpassed assert self.a.flat[12] == 12.0 def test_discontiguous(self): testpassed = False try: self.b.flat[4] = 100.0 except ValueError: testpassed = True assert testpassed assert self.b.flat[4] == 12.0 def test___array__(self): c = self.a.flat.__array__() d = self.b.flat.__array__() e = self.a0.flat.__array__() f = self.b0.flat.__array__() assert c.flags.writeable is False assert d.flags.writeable is False assert e.flags.writeable is True assert f.flags.writeable is True assert c.flags.updateifcopy is False assert d.flags.updateifcopy is False assert e.flags.updateifcopy is False assert f.flags.updateifcopy is True assert f.base is self.b0 class TestResize(TestCase): def test_basic(self): x = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]]) x.resize((5, 5)) assert_array_equal(x.flat[:9], np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]]).flat) assert_array_equal(x[9:].flat, 0) def test_check_reference(self): x = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]]) y = x self.assertRaises(ValueError, x.resize, (5, 1)) def test_int_shape(self): x = np.eye(3) x.resize(3) assert_array_equal(x, np.eye(3)[0,:]) def test_none_shape(self): x = np.eye(3) x.resize(None) assert_array_equal(x, np.eye(3)) x.resize() assert_array_equal(x, np.eye(3)) def test_invalid_arguements(self): self.assertRaises(TypeError, np.eye(3).resize, 'hi') self.assertRaises(ValueError, np.eye(3).resize, -1) self.assertRaises(TypeError, np.eye(3).resize, order=1) self.assertRaises(TypeError, np.eye(3).resize, refcheck='hi') def test_freeform_shape(self): x = np.eye(3) x.resize(3, 2, 1) assert_(x.shape == (3, 2, 1)) def test_zeros_appended(self): x = np.eye(3) x.resize(2, 3, 3) assert_array_equal(x[0], np.eye(3)) assert_array_equal(x[1], np.zeros((3, 3))) class TestRecord(TestCase): def test_field_rename(self): dt = np.dtype([('f', float), ('i', int)]) dt.names = ['p', 'q'] assert_equal(dt.names, ['p', 'q']) if sys.version_info[0] >= 3: def test_bytes_fields(self): # Bytes are not allowed in field names and not recognized in titles # on Py3 assert_raises(TypeError, np.dtype, [(asbytes('a'), int)]) assert_raises(TypeError, np.dtype, [(('b', asbytes('a')), int)]) dt = np.dtype([((asbytes('a'), 'b'), int)]) assert_raises(ValueError, dt.__getitem__, asbytes('a')) x = np.array([(1,), (2,), (3,)], dtype=dt) assert_raises(ValueError, x.__getitem__, asbytes('a')) y = x[0] assert_raises(IndexError, y.__getitem__, asbytes('a')) else: def test_unicode_field_titles(self): # Unicode field titles are added to field dict on Py2 title = unicode('b') dt = np.dtype([((title, 'a'), int)]) dt[title] dt['a'] x = np.array([(1,), (2,), (3,)], dtype=dt) x[title] x['a'] y = x[0] y[title] y['a'] def test_unicode_field_names(self): # Unicode field names are not allowed on Py2 title = unicode('b') assert_raises(TypeError, np.dtype, [(title, int)]) assert_raises(TypeError, np.dtype, [(('a', title), int)]) def test_field_names(self): # Test unicode and 8-bit / byte strings can be used a = np.zeros((1,), dtype=[('f1', 'i4'), ('f2', 'i4'), ('f3', [('sf1', 'i4')])]) is_py3 = sys.version_info[0] >= 3 if is_py3: funcs = (str,) # 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')) else: funcs = (str, unicode) for func in funcs: b = a.copy() fn1 = func('f1') b[fn1] = 1 assert_equal(b[fn1], 1) fnn = func('not at all') assert_raises(ValueError, b.__setitem__, fnn, 1) assert_raises(ValueError, b.__getitem__, fnn) b[0][fn1] = 2 assert_equal(b[fn1], 2) # Subfield assert_raises(IndexError, b[0].__setitem__, fnn, 1) assert_raises(IndexError, b[0].__getitem__, fnn) # Subfield fn3 = func('f3') sfn1 = func('sf1') b[fn3][sfn1] = 1 assert_equal(b[fn3][sfn1], 1) assert_raises(ValueError, b[fn3].__setitem__, fnn, 1) assert_raises(ValueError, b[fn3].__getitem__, fnn) # multiple Subfields fn2 = func('f2') b[fn2] = 3 assert_equal(b[['f1', 'f2']][0].tolist(), (2, 3)) assert_equal(b[['f2', 'f1']][0].tolist(), (3, 2)) assert_equal(b[['f1', 'f3']][0].tolist(), (2, (1,))) # view of subfield view/copy assert_equal(b[['f1', 'f2']][0].view(('i4', 2)).tolist(), (2, 3)) assert_equal(b[['f2', 'f1']][0].view(('i4', 2)).tolist(), (3, 2)) view_dtype=[('f1', 'i4'), ('f3', [('', 'i4')])] assert_equal(b[['f1', 'f3']][0].view(view_dtype).tolist(), (2, (1,))) # non-ascii unicode field indexing is well behaved if not is_py3: raise SkipTest('non ascii unicode field indexing skipped; ' 'raises segfault on python 2.x') else: assert_raises(ValueError, a.__setitem__, sixu('\u03e0'), 1) assert_raises(ValueError, a.__getitem__, sixu('\u03e0')) def test_field_names_deprecation(self): def collect_warning_types(f, *args, **kwargs): with warnings.catch_warnings(record=True) as log: warnings.simplefilter("always") f(*args, **kwargs) return [w.category for w in log] a = np.zeros((1,), dtype=[('f1', 'i4'), ('f2', 'i4'), ('f3', [('sf1', 'i4')])]) a['f1'][0] = 1 a['f2'][0] = 2 a['f3'][0] = (3,) b = np.zeros((1,), dtype=[('f1', 'i4'), ('f2', 'i4'), ('f3', [('sf1', 'i4')])]) b['f1'][0] = 1 b['f2'][0] = 2 b['f3'][0] = (3,) # All the different functions raise a warning, but not an error, and # 'a' is not modified: assert_equal(collect_warning_types(a[['f1', 'f2']].__setitem__, 0, (10, 20)), [FutureWarning]) assert_equal(a, b) # Views also warn subset = a[['f1', 'f2']] subset_view = subset.view() assert_equal(collect_warning_types(subset_view['f1'].__setitem__, 0, 10), [FutureWarning]) # But the write goes through: assert_equal(subset['f1'][0], 10) # Only one warning per multiple field indexing, though (even if there are # multiple views involved): assert_equal(collect_warning_types(subset['f1'].__setitem__, 0, 10), []) def test_record_hash(self): a = np.array([(1, 2), (1, 2)], dtype='i1,i2') a.flags.writeable = False b = np.array([(1, 2), (3, 4)], dtype=[('num1', 'i1'), ('num2', 'i2')]) b.flags.writeable = False c = np.array([(1, 2), (3, 4)], dtype='i1,i2') c.flags.writeable = False self.assertTrue(hash(a[0]) == hash(a[1])) self.assertTrue(hash(a[0]) == hash(b[0])) self.assertTrue(hash(a[0]) != hash(b[1])) self.assertTrue(hash(c[0]) == hash(a[0]) and c[0] == a[0]) def test_record_no_hash(self): a = np.array([(1, 2), (1, 2)], dtype='i1,i2') self.assertRaises(TypeError, hash, a[0]) class TestView(TestCase): def test_basic(self): x = np.array([(1, 2, 3, 4), (5, 6, 7, 8)], dtype=[('r', np.int8), ('g', np.int8), ('b', np.int8), ('a', np.int8)]) # We must be specific about the endianness here: y = x.view(dtype=' 0) assert_(issubclass(w[0].category, RuntimeWarning)) def test_empty(self): A = np.zeros((0, 3)) for f in self.funcs: for axis in [0, None]: with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') assert_(np.isnan(f(A, axis=axis)).all()) assert_(len(w) > 0) assert_(issubclass(w[0].category, RuntimeWarning)) for axis in [1]: with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') assert_equal(f(A, axis=axis), np.zeros([])) def test_mean_values(self): 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] assert_almost_equal(res, tgt) for axis in [None]: tgt = mat.sum(axis=axis) res = _mean(mat, axis=axis) * np.prod(mat.shape) assert_almost_equal(res, tgt) def test_var_values(self): 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.conjugate() res = _var(mat, axis=axis) assert_almost_equal(res, tgt) def test_std_values(self): 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) assert_almost_equal(res, tgt) def test_subclass(self): class TestArray(np.ndarray): def __new__(cls, data, info): result = np.array(data) result = result.view(cls) result.info = info return result def __array_finalize__(self, obj): self.info = getattr(obj, "info", '') dat = TestArray([[1, 2, 3, 4], [5, 6, 7, 8]], 'jubba') res = dat.mean(1) assert_(res.info == dat.info) res = dat.std(1) assert_(res.info == dat.info) res = dat.var(1) assert_(res.info == dat.info) class TestDot(TestCase): def test_dot_2args(self): from numpy.core.multiarray import dot a = np.array([[1, 2], [3, 4]], dtype=float) b = np.array([[1, 0], [1, 1]], dtype=float) c = np.array([[3, 2], [7, 4]], dtype=float) d = dot(a, b) assert_allclose(c, d) def test_dot_3args(self): from numpy.core.multiarray import dot np.random.seed(22) f = np.random.random_sample((1024, 16)) v = np.random.random_sample((16, 32)) r = np.empty((1024, 32)) for i in range(12): dot(f, v, r) assert_equal(sys.getrefcount(r), 2) r2 = dot(f, v, out=None) assert_array_equal(r2, r) assert_(r is dot(f, v, out=r)) v = v[:, 0].copy() # v.shape == (16,) r = r[:, 0].copy() # r.shape == (1024,) r2 = dot(f, v) assert_(r is dot(f, v, r)) assert_array_equal(r2, r) def test_dot_3args_errors(self): from numpy.core.multiarray import dot np.random.seed(22) f = np.random.random_sample((1024, 16)) v = np.random.random_sample((16, 32)) r = np.empty((1024, 31)) assert_raises(ValueError, dot, f, v, r) r = np.empty((1024,)) assert_raises(ValueError, dot, f, v, r) r = np.empty((32,)) assert_raises(ValueError, dot, f, v, r) r = np.empty((32, 1024)) assert_raises(ValueError, dot, f, v, r) assert_raises(ValueError, dot, f, v, r.T) r = np.empty((1024, 64)) assert_raises(ValueError, dot, f, v, r[:, ::2]) assert_raises(ValueError, dot, f, v, r[:, :32]) r = np.empty((1024, 32), dtype=np.float32) assert_raises(ValueError, dot, f, v, r) 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): A = np.arange(1001) strA = '[ 0 1 2 ..., 998 999 1000]' assert_(str(A) == strA) reprA = 'array([ 0, 1, 2, ..., 998, 999, 1000])' assert_(repr(A) == reprA) def test_2d(self): A = np.arange(1002).reshape(2, 501) strA = '[[ 0 1 2 ..., 498 499 500]\n' \ ' [ 501 502 503 ..., 999 1000 1001]]' assert_(str(A) == strA) reprA = 'array([[ 0, 1, 2, ..., 498, 499, 500],\n' \ ' [ 501, 502, 503, ..., 999, 1000, 1001]])' assert_(repr(A) == reprA) class TestChoose(TestCase): def setUp(self): self.x = 2*ones((3,), dtype=int) self.y = 3*ones((3,), dtype=int) self.x2 = 2*ones((2, 3), dtype=int) self.y2 = 3*ones((2, 3), dtype=int) self.ind = [0, 0, 1] def test_basic(self): A = np.choose(self.ind, (self.x, self.y)) assert_equal(A, [2, 2, 3]) def test_broadcast1(self): A = np.choose(self.ind, (self.x2, self.y2)) assert_equal(A, [[2, 2, 3], [2, 2, 3]]) def test_broadcast2(self): A = np.choose(self.ind, (self.x, self.y2)) assert_equal(A, [[2, 2, 3], [2, 2, 3]]) # TODO: test for multidimensional NEIGH_MODE = {'zero': 0, 'one': 1, 'constant': 2, 'circular': 3, 'mirror': 4} class TestNeighborhoodIter(TestCase): # Simple, 2d tests def _test_simple2d(self, dt): # Test zero and one padding for simple data type x = np.array([[0, 1], [2, 3]], dtype=dt) r = [np.array([[0, 0, 0], [0, 0, 1]], dtype=dt), np.array([[0, 0, 0], [0, 1, 0]], dtype=dt), np.array([[0, 0, 1], [0, 2, 3]], dtype=dt), np.array([[0, 1, 0], [2, 3, 0]], dtype=dt)] l = test_neighborhood_iterator(x, [-1, 0, -1, 1], x[0], NEIGH_MODE['zero']) assert_array_equal(l, r) r = [np.array([[1, 1, 1], [1, 0, 1]], dtype=dt), np.array([[1, 1, 1], [0, 1, 1]], dtype=dt), np.array([[1, 0, 1], [1, 2, 3]], dtype=dt), np.array([[0, 1, 1], [2, 3, 1]], dtype=dt)] l = test_neighborhood_iterator(x, [-1, 0, -1, 1], x[0], NEIGH_MODE['one']) assert_array_equal(l, r) r = [np.array([[4, 4, 4], [4, 0, 1]], dtype=dt), np.array([[4, 4, 4], [0, 1, 4]], dtype=dt), np.array([[4, 0, 1], [4, 2, 3]], dtype=dt), np.array([[0, 1, 4], [2, 3, 4]], dtype=dt)] l = test_neighborhood_iterator(x, [-1, 0, -1, 1], 4, NEIGH_MODE['constant']) assert_array_equal(l, r) def test_simple2d(self): self._test_simple2d(np.float) def test_simple2d_object(self): self._test_simple2d(Decimal) def _test_mirror2d(self, dt): x = np.array([[0, 1], [2, 3]], dtype=dt) r = [np.array([[0, 0, 1], [0, 0, 1]], dtype=dt), np.array([[0, 1, 1], [0, 1, 1]], dtype=dt), np.array([[0, 0, 1], [2, 2, 3]], dtype=dt), np.array([[0, 1, 1], [2, 3, 3]], dtype=dt)] l = test_neighborhood_iterator(x, [-1, 0, -1, 1], x[0], NEIGH_MODE['mirror']) assert_array_equal(l, r) def test_mirror2d(self): self._test_mirror2d(np.float) def test_mirror2d_object(self): self._test_mirror2d(Decimal) # Simple, 1d tests def _test_simple(self, dt): # Test padding with constant values x = np.linspace(1, 5, 5).astype(dt) r = [[0, 1, 2], [1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 0]] l = test_neighborhood_iterator(x, [-1, 1], x[0], NEIGH_MODE['zero']) assert_array_equal(l, r) r = [[1, 1, 2], [1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 1]] l = test_neighborhood_iterator(x, [-1, 1], x[0], NEIGH_MODE['one']) assert_array_equal(l, r) r = [[x[4], 1, 2], [1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, x[4]]] l = test_neighborhood_iterator(x, [-1, 1], x[4], NEIGH_MODE['constant']) assert_array_equal(l, r) def test_simple_float(self): self._test_simple(np.float) def test_simple_object(self): self._test_simple(Decimal) # Test mirror modes def _test_mirror(self, dt): x = np.linspace(1, 5, 5).astype(dt) r = np.array([[2, 1, 1, 2, 3], [1, 1, 2, 3, 4], [1, 2, 3, 4, 5], [2, 3, 4, 5, 5], [3, 4, 5, 5, 4]], dtype=dt) l = test_neighborhood_iterator(x, [-2, 2], x[1], NEIGH_MODE['mirror']) self.assertTrue([i.dtype == dt for i in l]) assert_array_equal(l, r) def test_mirror(self): self._test_mirror(np.float) def test_mirror_object(self): self._test_mirror(Decimal) # Circular mode def _test_circular(self, dt): x = np.linspace(1, 5, 5).astype(dt) r = np.array([[4, 5, 1, 2, 3], [5, 1, 2, 3, 4], [1, 2, 3, 4, 5], [2, 3, 4, 5, 1], [3, 4, 5, 1, 2]], dtype=dt) l = test_neighborhood_iterator(x, [-2, 2], x[0], NEIGH_MODE['circular']) assert_array_equal(l, r) def test_circular(self): self._test_circular(np.float) def test_circular_object(self): self._test_circular(Decimal) # Test stacking neighborhood iterators class TestStackedNeighborhoodIter(TestCase): # Simple, 1d test: stacking 2 constant-padded neigh iterators def test_simple_const(self): dt = np.float64 # Test zero and one padding for simple data type x = np.array([1, 2, 3], dtype=dt) r = [np.array([0], dtype=dt), np.array([0], dtype=dt), np.array([1], dtype=dt), np.array([2], dtype=dt), np.array([3], dtype=dt), np.array([0], dtype=dt), np.array([0], dtype=dt)] l = test_neighborhood_iterator_oob(x, [-2, 4], NEIGH_MODE['zero'], [0, 0], NEIGH_MODE['zero']) assert_array_equal(l, r) r = [np.array([1, 0, 1], dtype=dt), np.array([0, 1, 2], dtype=dt), np.array([1, 2, 3], dtype=dt), np.array([2, 3, 0], dtype=dt), np.array([3, 0, 1], dtype=dt)] l = test_neighborhood_iterator_oob(x, [-1, 3], NEIGH_MODE['zero'], [-1, 1], NEIGH_MODE['one']) assert_array_equal(l, r) # 2nd simple, 1d test: stacking 2 neigh iterators, mixing const padding and # mirror padding def test_simple_mirror(self): dt = np.float64 # Stacking zero on top of mirror x = np.array([1, 2, 3], dtype=dt) r = [np.array([0, 1, 1], dtype=dt), np.array([1, 1, 2], dtype=dt), np.array([1, 2, 3], dtype=dt), np.array([2, 3, 3], dtype=dt), np.array([3, 3, 0], dtype=dt)] l = test_neighborhood_iterator_oob(x, [-1, 3], NEIGH_MODE['mirror'], [-1, 1], NEIGH_MODE['zero']) assert_array_equal(l, r) # Stacking mirror on top of zero x = np.array([1, 2, 3], dtype=dt) r = [np.array([1, 0, 0], dtype=dt), np.array([0, 0, 1], dtype=dt), np.array([0, 1, 2], dtype=dt), np.array([1, 2, 3], dtype=dt), np.array([2, 3, 0], dtype=dt)] l = test_neighborhood_iterator_oob(x, [-1, 3], NEIGH_MODE['zero'], [-2, 0], NEIGH_MODE['mirror']) assert_array_equal(l, r) # Stacking mirror on top of zero: 2nd x = np.array([1, 2, 3], dtype=dt) r = [np.array([0, 1, 2], dtype=dt), np.array([1, 2, 3], dtype=dt), np.array([2, 3, 0], dtype=dt), np.array([3, 0, 0], dtype=dt), np.array([0, 0, 3], dtype=dt)] l = test_neighborhood_iterator_oob(x, [-1, 3], NEIGH_MODE['zero'], [0, 2], NEIGH_MODE['mirror']) assert_array_equal(l, r) # Stacking mirror on top of zero: 3rd x = np.array([1, 2, 3], dtype=dt) r = [np.array([1, 0, 0, 1, 2], dtype=dt), np.array([0, 0, 1, 2, 3], dtype=dt), np.array([0, 1, 2, 3, 0], dtype=dt), np.array([1, 2, 3, 0, 0], dtype=dt), np.array([2, 3, 0, 0, 3], dtype=dt)] l = test_neighborhood_iterator_oob(x, [-1, 3], NEIGH_MODE['zero'], [-2, 2], NEIGH_MODE['mirror']) assert_array_equal(l, r) # 3rd simple, 1d test: stacking 2 neigh iterators, mixing const padding and # circular padding def test_simple_circular(self): dt = np.float64 # Stacking zero on top of mirror x = np.array([1, 2, 3], dtype=dt) r = [np.array([0, 3, 1], dtype=dt), np.array([3, 1, 2], dtype=dt), np.array([1, 2, 3], dtype=dt), np.array([2, 3, 1], dtype=dt), np.array([3, 1, 0], dtype=dt)] l = test_neighborhood_iterator_oob(x, [-1, 3], NEIGH_MODE['circular'], [-1, 1], NEIGH_MODE['zero']) assert_array_equal(l, r) # Stacking mirror on top of zero x = np.array([1, 2, 3], dtype=dt) r = [np.array([3, 0, 0], dtype=dt), np.array([0, 0, 1], dtype=dt), np.array([0, 1, 2], dtype=dt), np.array([1, 2, 3], dtype=dt), np.array([2, 3, 0], dtype=dt)] l = test_neighborhood_iterator_oob(x, [-1, 3], NEIGH_MODE['zero'], [-2, 0], NEIGH_MODE['circular']) assert_array_equal(l, r) # Stacking mirror on top of zero: 2nd x = np.array([1, 2, 3], dtype=dt) r = [np.array([0, 1, 2], dtype=dt), np.array([1, 2, 3], dtype=dt), np.array([2, 3, 0], dtype=dt), np.array([3, 0, 0], dtype=dt), np.array([0, 0, 1], dtype=dt)] l = test_neighborhood_iterator_oob(x, [-1, 3], NEIGH_MODE['zero'], [0, 2], NEIGH_MODE['circular']) assert_array_equal(l, r) # Stacking mirror on top of zero: 3rd x = np.array([1, 2, 3], dtype=dt) r = [np.array([3, 0, 0, 1, 2], dtype=dt), np.array([0, 0, 1, 2, 3], dtype=dt), np.array([0, 1, 2, 3, 0], dtype=dt), np.array([1, 2, 3, 0, 0], dtype=dt), np.array([2, 3, 0, 0, 1], dtype=dt)] l = test_neighborhood_iterator_oob(x, [-1, 3], NEIGH_MODE['zero'], [-2, 2], NEIGH_MODE['circular']) assert_array_equal(l, r) # 4th simple, 1d test: stacking 2 neigh iterators, but with lower iterator # being strictly within the array def test_simple_strict_within(self): dt = np.float64 # Stacking zero on top of zero, first neighborhood strictly inside the # array x = np.array([1, 2, 3], dtype=dt) r = [np.array([1, 2, 3, 0], dtype=dt)] l = test_neighborhood_iterator_oob(x, [1, 1], NEIGH_MODE['zero'], [-1, 2], NEIGH_MODE['zero']) assert_array_equal(l, r) # Stacking mirror on top of zero, first neighborhood strictly inside the # array x = np.array([1, 2, 3], dtype=dt) r = [np.array([1, 2, 3, 3], dtype=dt)] l = test_neighborhood_iterator_oob(x, [1, 1], NEIGH_MODE['zero'], [-1, 2], NEIGH_MODE['mirror']) assert_array_equal(l, r) # Stacking mirror on top of zero, first neighborhood strictly inside the # array x = np.array([1, 2, 3], dtype=dt) r = [np.array([1, 2, 3, 1], dtype=dt)] l = test_neighborhood_iterator_oob(x, [1, 1], NEIGH_MODE['zero'], [-1, 2], NEIGH_MODE['circular']) assert_array_equal(l, r) class TestWarnings(object): def test_complex_warning(self): x = np.array([1, 2]) y = np.array([1-2j, 1+2j]) with warnings.catch_warnings(): warnings.simplefilter("error", np.ComplexWarning) assert_raises(np.ComplexWarning, x.__setitem__, slice(None), y) assert_equal(x, [1, 2]) class TestMinScalarType(object): def test_usigned_shortshort(self): dt = np.min_scalar_type(2**8-1) wanted = np.dtype('uint8') assert_equal(wanted, dt) def test_usigned_short(self): dt = np.min_scalar_type(2**16-1) wanted = np.dtype('uint16') assert_equal(wanted, dt) def test_usigned_int(self): dt = np.min_scalar_type(2**32-1) wanted = np.dtype('uint32') assert_equal(wanted, dt) def test_usigned_longlong(self): dt = np.min_scalar_type(2**63-1) wanted = np.dtype('uint64') assert_equal(wanted, dt) def test_object(self): dt = np.min_scalar_type(2**64) wanted = np.dtype('O') assert_equal(wanted, dt) if sys.version_info[:2] == (2, 6): from numpy.core.multiarray import memorysimpleview as memoryview from numpy.core._internal import _dtype_from_pep3118 class TestPEP3118Dtype(object): def _check(self, spec, wanted): dt = np.dtype(wanted) if isinstance(wanted, list) and isinstance(wanted[-1], tuple): if wanted[-1][0] == '': names = list(dt.names) names[-1] = '' dt.names = tuple(names) assert_equal(_dtype_from_pep3118(spec), dt, err_msg="spec %r != dtype %r" % (spec, wanted)) def test_native_padding(self): align = np.dtype('i').alignment for j in range(8): if j == 0: s = 'bi' else: s = 'b%dxi' % j self._check('@'+s, {'f0': ('i1', 0), 'f1': ('i', align*(1 + j//align))}) self._check('='+s, {'f0': ('i1', 0), 'f1': ('i', 1+j)}) def test_native_padding_2(self): # Native padding should work also for structs and sub-arrays self._check('x3T{xi}', {'f0': (({'f0': ('i', 4)}, (3,)), 4)}) self._check('^x3T{xi}', {'f0': (({'f0': ('i', 1)}, (3,)), 1)}) def test_trailing_padding(self): # Trailing padding should be included, *and*, the item size # should match the alignment if in aligned mode align = np.dtype('i').alignment def VV(n): return 'V%d' % (align*(1 + (n-1)//align)) self._check('ix', [('f0', 'i'), ('', VV(1))]) self._check('ixx', [('f0', 'i'), ('', VV(2))]) self._check('ixxx', [('f0', 'i'), ('', VV(3))]) self._check('ixxxx', [('f0', 'i'), ('', VV(4))]) self._check('i7x', [('f0', 'i'), ('', VV(7))]) self._check('^ix', [('f0', 'i'), ('', 'V1')]) self._check('^ixx', [('f0', 'i'), ('', 'V2')]) self._check('^ixxx', [('f0', 'i'), ('', 'V3')]) self._check('^ixxxx', [('f0', 'i'), ('', 'V4')]) self._check('^i7x', [('f0', 'i'), ('', 'V7')]) def test_native_padding_3(self): dt = np.dtype( [('a', 'b'), ('b', 'i'), ('sub', np.dtype('b,i')), ('c', 'i')], align=True) self._check("T{b:a:xxxi:b:T{b:f0:=i:f1:}:sub:xxxi:c:}", dt) dt = np.dtype( [('a', 'b'), ('b', 'i'), ('c', 'b'), ('d', 'b'), ('e', 'b'), ('sub', np.dtype('b,i', align=True))]) self._check("T{b:a:=i:b:b:c:b:d:b:e:T{b:f0:xxxi:f1:}:sub:}", dt) def test_padding_with_array_inside_struct(self): dt = np.dtype( [('a', 'b'), ('b', 'i'), ('c', 'b', (3,)), ('d', 'i')], align=True) self._check("T{b:a:xxxi:b:3b:c:xi:d:}", dt) def test_byteorder_inside_struct(self): # The byte order after @T{=i} should be '=', not '@'. # Check this by noting the absence of native alignment. self._check('@T{^i}xi', {'f0': ({'f0': ('i', 0)}, 0), 'f1': ('i', 5)}) def test_intra_padding(self): # Natively aligned sub-arrays may require some internal padding align = np.dtype('i').alignment def VV(n): return 'V%d' % (align*(1 + (n-1)//align)) self._check('(3)T{ix}', ({'f0': ('i', 0), '': (VV(1), 4)}, (3,))) class TestNewBufferProtocol(object): def _check_roundtrip(self, obj): obj = np.asarray(obj) x = memoryview(obj) y = np.asarray(x) y2 = np.array(x) assert_(not y.flags.owndata) assert_(y2.flags.owndata) assert_equal(y.dtype, obj.dtype) assert_array_equal(obj, y) assert_equal(y2.dtype, obj.dtype) assert_array_equal(obj, y2) def test_roundtrip(self): x = np.array([1, 2, 3, 4, 5], dtype='i4') self._check_roundtrip(x) x = np.array([[1, 2], [3, 4]], dtype=np.float64) self._check_roundtrip(x) x = np.zeros((3, 3, 3), dtype=np.float32)[:, 0,:] self._check_roundtrip(x) dt = [('a', 'b'), ('b', 'h'), ('c', 'i'), ('d', 'l'), ('dx', 'q'), ('e', 'B'), ('f', 'H'), ('g', 'I'), ('h', 'L'), ('hx', 'Q'), ('i', np.single), ('j', np.double), ('k', np.longdouble), ('ix', np.csingle), ('jx', np.cdouble), ('kx', np.clongdouble), ('l', 'S4'), ('m', 'U4'), ('n', 'V3'), ('o', '?'), ('p', np.half), ] x = np.array( [(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, asbytes('aaaa'), 'bbbb', asbytes('xxx'), True, 1.0)], dtype=dt) self._check_roundtrip(x) x = np.array(([[1, 2], [3, 4]],), dtype=[('a', (int, (2, 2)))]) self._check_roundtrip(x) x = np.array([1, 2, 3], dtype='>i2') self._check_roundtrip(x) x = np.array([1, 2, 3], dtype='') x = np.zeros(4, dtype=dt) self._check_roundtrip(x) def test_export_simple_1d(self): x = np.array([1, 2, 3, 4, 5], dtype='i') y = memoryview(x) assert_equal(y.format, 'i') assert_equal(y.shape, (5,)) assert_equal(y.ndim, 1) assert_equal(y.strides, (4,)) assert_equal(y.suboffsets, EMPTY) assert_equal(y.itemsize, 4) def test_export_simple_nd(self): x = np.array([[1, 2], [3, 4]], dtype=np.float64) y = memoryview(x) assert_equal(y.format, 'd') assert_equal(y.shape, (2, 2)) assert_equal(y.ndim, 2) assert_equal(y.strides, (16, 8)) assert_equal(y.suboffsets, EMPTY) assert_equal(y.itemsize, 8) def test_export_discontiguous(self): x = np.zeros((3, 3, 3), dtype=np.float32)[:, 0,:] y = memoryview(x) assert_equal(y.format, 'f') assert_equal(y.shape, (3, 3)) assert_equal(y.ndim, 2) assert_equal(y.strides, (36, 4)) assert_equal(y.suboffsets, EMPTY) assert_equal(y.itemsize, 4) def test_export_record(self): dt = [('a', 'b'), ('b', 'h'), ('c', 'i'), ('d', 'l'), ('dx', 'q'), ('e', 'B'), ('f', 'H'), ('g', 'I'), ('h', 'L'), ('hx', 'Q'), ('i', np.single), ('j', np.double), ('k', np.longdouble), ('ix', np.csingle), ('jx', np.cdouble), ('kx', np.clongdouble), ('l', 'S4'), ('m', 'U4'), ('n', 'V3'), ('o', '?'), ('p', np.half), ] x = np.array( [(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, asbytes('aaaa'), 'bbbb', asbytes(' '), True, 1.0)], dtype=dt) y = memoryview(x) assert_equal(y.shape, (1,)) assert_equal(y.ndim, 1) assert_equal(y.suboffsets, EMPTY) sz = sum([dtype(b).itemsize for a, b in dt]) if dtype('l').itemsize == 4: assert_equal(y.format, 'T{b:a:=h:b:i:c:l:d:q:dx:B:e:@H:f:=I:g:L:h:Q:hx:f:i:d:j:^g:k:=Zf:ix:Zd:jx:^Zg:kx:4s:l:=4w:m:3x:n:?:o:@e:p:}') else: assert_equal(y.format, 'T{b:a:=h:b:i:c:q:d:q:dx:B:e:@H:f:=I:g:Q:h:Q:hx:f:i:d:j:^g:k:=Zf:ix:Zd:jx:^Zg:kx:4s:l:=4w:m:3x:n:?:o:@e:p:}') # Cannot test if NPY_RELAXED_STRIDES_CHECKING changes the strides if not (np.ones(1).strides[0] == np.iinfo(np.intp).max): assert_equal(y.strides, (sz,)) assert_equal(y.itemsize, sz) def test_export_subarray(self): x = np.array(([[1, 2], [3, 4]],), dtype=[('a', ('i', (2, 2)))]) y = memoryview(x) assert_equal(y.format, 'T{(2,2)i:a:}') assert_equal(y.shape, EMPTY) assert_equal(y.ndim, 0) assert_equal(y.strides, EMPTY) assert_equal(y.suboffsets, EMPTY) assert_equal(y.itemsize, 16) def test_export_endian(self): x = np.array([1, 2, 3], dtype='>i') y = memoryview(x) if sys.byteorder == 'little': assert_equal(y.format, '>i') else: assert_equal(y.format, 'i') x = np.array([1, 2, 3], dtype=' array) def __le__(self, array): if isinstance(array, PriorityNdarray): array = array.array return PriorityNdarray(self.array <= array) def __ge__(self, array): if isinstance(array, PriorityNdarray): array = array.array return PriorityNdarray(self.array >= array) def __eq__(self, array): if isinstance(array, PriorityNdarray): array = array.array return PriorityNdarray(self.array == array) def __ne__(self, array): if isinstance(array, PriorityNdarray): array = array.array return PriorityNdarray(self.array != array) class TestArrayPriority(TestCase): def test_lt(self): l = np.asarray([0., -1., 1.], dtype=dtype) r = np.asarray([0., 1., -1.], dtype=dtype) lp = PriorityNdarray(l) rp = PriorityNdarray(r) res1 = l < r res2 = l < rp res3 = lp < r res4 = lp < rp assert_array_equal(res1, res2.array) assert_array_equal(res1, res3.array) assert_array_equal(res1, res4.array) assert_(isinstance(res1, np.ndarray)) assert_(isinstance(res2, PriorityNdarray)) assert_(isinstance(res3, PriorityNdarray)) assert_(isinstance(res4, PriorityNdarray)) def test_gt(self): l = np.asarray([0., -1., 1.], dtype=dtype) r = np.asarray([0., 1., -1.], dtype=dtype) lp = PriorityNdarray(l) rp = PriorityNdarray(r) res1 = l > r res2 = l > rp res3 = lp > r res4 = lp > rp assert_array_equal(res1, res2.array) assert_array_equal(res1, res3.array) assert_array_equal(res1, res4.array) assert_(isinstance(res1, np.ndarray)) assert_(isinstance(res2, PriorityNdarray)) assert_(isinstance(res3, PriorityNdarray)) assert_(isinstance(res4, PriorityNdarray)) def test_le(self): l = np.asarray([0., -1., 1.], dtype=dtype) r = np.asarray([0., 1., -1.], dtype=dtype) lp = PriorityNdarray(l) rp = PriorityNdarray(r) res1 = l <= r res2 = l <= rp res3 = lp <= r res4 = lp <= rp assert_array_equal(res1, res2.array) assert_array_equal(res1, res3.array) assert_array_equal(res1, res4.array) assert_(isinstance(res1, np.ndarray)) assert_(isinstance(res2, PriorityNdarray)) assert_(isinstance(res3, PriorityNdarray)) assert_(isinstance(res4, PriorityNdarray)) def test_ge(self): l = np.asarray([0., -1., 1.], dtype=dtype) r = np.asarray([0., 1., -1.], dtype=dtype) lp = PriorityNdarray(l) rp = PriorityNdarray(r) res1 = l >= r res2 = l >= rp res3 = lp >= r res4 = lp >= rp assert_array_equal(res1, res2.array) assert_array_equal(res1, res3.array) assert_array_equal(res1, res4.array) assert_(isinstance(res1, np.ndarray)) assert_(isinstance(res2, PriorityNdarray)) assert_(isinstance(res3, PriorityNdarray)) assert_(isinstance(res4, PriorityNdarray)) def test_eq(self): l = np.asarray([0., -1., 1.], dtype=dtype) r = np.asarray([0., 1., -1.], dtype=dtype) lp = PriorityNdarray(l) rp = PriorityNdarray(r) res1 = l == r res2 = l == rp res3 = lp == r res4 = lp == rp assert_array_equal(res1, res2.array) assert_array_equal(res1, res3.array) assert_array_equal(res1, res4.array) assert_(isinstance(res1, np.ndarray)) assert_(isinstance(res2, PriorityNdarray)) assert_(isinstance(res3, PriorityNdarray)) assert_(isinstance(res4, PriorityNdarray)) def test_ne(self): l = np.asarray([0., -1., 1.], dtype=dtype) r = np.asarray([0., 1., -1.], dtype=dtype) lp = PriorityNdarray(l) rp = PriorityNdarray(r) res1 = l != r res2 = l != rp res3 = lp != r res4 = lp != rp assert_array_equal(res1, res2.array) assert_array_equal(res1, res3.array) assert_array_equal(res1, res4.array) assert_(isinstance(res1, np.ndarray)) assert_(isinstance(res2, PriorityNdarray)) assert_(isinstance(res3, PriorityNdarray)) assert_(isinstance(res4, PriorityNdarray)) if __name__ == "__main__": run_module_suite() numpy-1.8.2/numpy/core/tests/test_numeric.py0000664000175100017510000020044212370216243022343 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function import sys import platform from decimal import Decimal import warnings import itertools import numpy as np from numpy.core import * from numpy.random import rand, randint, randn from numpy.testing import * from numpy.core.multiarray import dot as dot_ class Vec(object): def __init__(self,sequence=None): if sequence is None: sequence=[] self.array=array(sequence) def __add__(self, other): out=Vec() out.array=self.array+other.array return out def __sub__(self, other): out=Vec() out.array=self.array-other.array return out def __mul__(self, other): # with scalar out=Vec(self.array.copy()) out.array*=other return out def __rmul__(self, other): return self*other class TestDot(TestCase): def setUp(self): self.A = rand(10, 8) self.b1 = rand(8, 1) self.b2 = rand(8) self.b3 = rand(1, 8) self.b4 = rand(10) self.N = 14 def test_matmat(self): A = self.A c1 = dot(A.transpose(), A) c2 = dot_(A.transpose(), A) assert_almost_equal(c1, c2, decimal=self.N) def test_matvec(self): A, b1 = self.A, self.b1 c1 = dot(A, b1) c2 = dot_(A, b1) assert_almost_equal(c1, c2, decimal=self.N) def test_matvec2(self): A, b2 = self.A, self.b2 c1 = dot(A, b2) c2 = dot_(A, b2) assert_almost_equal(c1, c2, decimal=self.N) def test_vecmat(self): A, b4 = self.A, self.b4 c1 = dot(b4, A) c2 = dot_(b4, A) assert_almost_equal(c1, c2, decimal=self.N) def test_vecmat2(self): b3, A = self.b3, self.A c1 = dot(b3, A.transpose()) c2 = dot_(b3, A.transpose()) assert_almost_equal(c1, c2, decimal=self.N) def test_vecmat3(self): A, b4 = self.A, self.b4 c1 = dot(A.transpose(), b4) c2 = dot_(A.transpose(), b4) assert_almost_equal(c1, c2, decimal=self.N) def test_vecvecouter(self): b1, b3 = self.b1, self.b3 c1 = dot(b1, b3) c2 = dot_(b1, b3) assert_almost_equal(c1, c2, decimal=self.N) def test_vecvecinner(self): b1, b3 = self.b1, self.b3 c1 = dot(b3, b1) c2 = dot_(b3, b1) assert_almost_equal(c1, c2, decimal=self.N) def test_columnvect1(self): b1 = ones((3, 1)) b2 = [5.3] c1 = dot(b1, b2) c2 = dot_(b1, b2) assert_almost_equal(c1, c2, decimal=self.N) def test_columnvect2(self): b1 = ones((3, 1)).transpose() b2 = [6.2] c1 = dot(b2, b1) c2 = dot_(b2, b1) assert_almost_equal(c1, c2, decimal=self.N) def test_vecscalar(self): b1 = rand(1, 1) b2 = rand(1, 8) c1 = dot(b1, b2) c2 = dot_(b1, b2) assert_almost_equal(c1, c2, decimal=self.N) def test_vecscalar2(self): b1 = rand(8, 1) b2 = rand(1, 1) c1 = dot(b1, b2) c2 = dot_(b1, b2) assert_almost_equal(c1, c2, decimal=self.N) def test_all(self): dims = [(), (1,), (1, 1)] for dim1 in dims: for dim2 in dims: arg1 = rand(*dim1) arg2 = rand(*dim2) c1 = dot(arg1, arg2) c2 = dot_(arg1, arg2) assert_(c1.shape == c2.shape) assert_almost_equal(c1, c2, decimal=self.N) def test_vecobject(self): U_non_cont = transpose([[1., 1.], [1., 2.]]) U_cont = ascontiguousarray(U_non_cont) x = array([Vec([1., 0.]), Vec([0., 1.])]) zeros = array([Vec([0., 0.]), Vec([0., 0.])]) zeros_test = dot(U_cont, x) - dot(U_non_cont, x) assert_equal(zeros[0].array, zeros_test[0].array) assert_equal(zeros[1].array, zeros_test[1].array) class TestResize(TestCase): def test_copies(self): A = array([[1, 2], [3, 4]]) Ar1 = array([[1, 2, 3, 4], [1, 2, 3, 4]]) assert_equal(resize(A, (2, 4)), Ar1) Ar2 = array([[1, 2], [3, 4], [1, 2], [3, 4]]) assert_equal(resize(A, (4, 2)), Ar2) Ar3 = array([[1, 2, 3], [4, 1, 2], [3, 4, 1], [2, 3, 4]]) assert_equal(resize(A, (4, 3)), Ar3) def test_zeroresize(self): A = array([[1, 2], [3, 4]]) Ar = resize(A, (0,)) assert_equal(Ar, array([])) class TestNonarrayArgs(TestCase): # check that non-array arguments to functions wrap them in arrays def test_squeeze(self): A = [[[1, 1, 1], [2, 2, 2], [3, 3, 3]]] assert_(squeeze(A).shape == (3, 3)) def test_cumproduct(self): A = [[1, 2, 3], [4, 5, 6]] assert_(all(cumproduct(A) == array([1, 2, 6, 24, 120, 720]))) def test_size(self): A = [[1, 2, 3], [4, 5, 6]] assert_(size(A) == 6) assert_(size(A, 0) == 2) assert_(size(A, 1) == 3) def test_mean(self): A = [[1, 2, 3], [4, 5, 6]] assert_(mean(A) == 3.5) assert_(all(mean(A, 0) == array([2.5, 3.5, 4.5]))) assert_(all(mean(A, 1) == array([2., 5.]))) with warnings.catch_warnings(record=True) as w: warnings.filterwarnings('always', '', RuntimeWarning) assert_(isnan(mean([]))) assert_(w[0].category is RuntimeWarning) def test_std(self): A = [[1, 2, 3], [4, 5, 6]] assert_almost_equal(std(A), 1.707825127659933) assert_almost_equal(std(A, 0), array([1.5, 1.5, 1.5])) assert_almost_equal(std(A, 1), array([0.81649658, 0.81649658])) with warnings.catch_warnings(record=True) as w: warnings.filterwarnings('always', '', RuntimeWarning) assert_(isnan(std([]))) assert_(w[0].category is RuntimeWarning) def test_var(self): A = [[1, 2, 3], [4, 5, 6]] assert_almost_equal(var(A), 2.9166666666666665) assert_almost_equal(var(A, 0), array([2.25, 2.25, 2.25])) assert_almost_equal(var(A, 1), array([0.66666667, 0.66666667])) with warnings.catch_warnings(record=True) as w: warnings.filterwarnings('always', '', RuntimeWarning) assert_(isnan(var([]))) assert_(w[0].category is RuntimeWarning) class TestBoolScalar(TestCase): def test_logical(self): f = False_ t = True_ s = "xyz" self.assertTrue((t and s) is s) self.assertTrue((f and s) is f) def test_bitwise_or(self): f = False_ t = True_ self.assertTrue((t | t) is t) self.assertTrue((f | t) is t) self.assertTrue((t | f) is t) self.assertTrue((f | f) is f) def test_bitwise_and(self): f = False_ t = True_ self.assertTrue((t & t) is t) self.assertTrue((f & t) is f) self.assertTrue((t & f) is f) self.assertTrue((f & f) is f) def test_bitwise_xor(self): f = False_ t = True_ self.assertTrue((t ^ t) is f) self.assertTrue((f ^ t) is t) self.assertTrue((t ^ f) is t) self.assertTrue((f ^ f) is f) class TestBoolArray(TestCase): def setUp(self): # offset for simd tests self.t = array([True] * 41, dtype=np.bool)[1::] self.f = array([False] * 41, dtype=np.bool)[1::] self.o = array([False] * 42, dtype=np.bool)[2::] self.nm = self.f.copy() self.im = self.t.copy() self.nm[3] = True self.nm[-2] = True self.im[3] = False self.im[-2] = False def test_all_any(self): self.assertTrue(self.t.all()) self.assertTrue(self.t.any()) self.assertFalse(self.f.all()) self.assertFalse(self.f.any()) self.assertTrue(self.nm.any()) self.assertTrue(self.im.any()) self.assertFalse(self.nm.all()) self.assertFalse(self.im.all()) # check bad element in all positions for i in range(256 - 7): d = array([False] * 256, dtype=np.bool)[7::] d[i] = True self.assertTrue(np.any(d)) e = array([True] * 256, dtype=np.bool)[7::] e[i] = False self.assertFalse(np.all(e)) assert_array_equal(e, ~d) # big array test for blocked libc loops for i in list(range(9, 6000, 507)) + [7764, 90021, -10]: d = array([False] * 100043, dtype=np.bool) d[i] = True self.assertTrue(np.any(d), msg="%r" % i) e = array([True] * 100043, dtype=np.bool) e[i] = False self.assertFalse(np.all(e), msg="%r" % i) def test_logical_not_abs(self): assert_array_equal(~self.t, self.f) assert_array_equal(np.abs(~self.t), self.f) assert_array_equal(np.abs(~self.f), self.t) assert_array_equal(np.abs(self.f), self.f) assert_array_equal(~np.abs(self.f), self.t) assert_array_equal(~np.abs(self.t), self.f) assert_array_equal(np.abs(~self.nm), self.im) np.logical_not(self.t, out=self.o) assert_array_equal(self.o, self.f) np.abs(self.t, out=self.o) assert_array_equal(self.o, self.t) def test_logical_and_or_xor(self): assert_array_equal(self.t | self.t, self.t) assert_array_equal(self.f | self.f, self.f) assert_array_equal(self.t | self.f, self.t) assert_array_equal(self.f | self.t, self.t) np.logical_or(self.t, self.t, out=self.o) assert_array_equal(self.o, self.t) assert_array_equal(self.t & self.t, self.t) assert_array_equal(self.f & self.f, self.f) assert_array_equal(self.t & self.f, self.f) assert_array_equal(self.f & self.t, self.f) np.logical_and(self.t, self.t, out=self.o) assert_array_equal(self.o, self.t) assert_array_equal(self.t ^ self.t, self.f) assert_array_equal(self.f ^ self.f, self.f) assert_array_equal(self.t ^ self.f, self.t) assert_array_equal(self.f ^ self.t, self.t) np.logical_xor(self.t, self.t, out=self.o) assert_array_equal(self.o, self.f) assert_array_equal(self.nm & self.t, self.nm) assert_array_equal(self.im & self.f, False) assert_array_equal(self.nm & True, self.nm) assert_array_equal(self.im & False, self.f) assert_array_equal(self.nm | self.t, self.t) assert_array_equal(self.im | self.f, self.im) assert_array_equal(self.nm | True, self.t) assert_array_equal(self.im | False, self.im) assert_array_equal(self.nm ^ self.t, self.im) assert_array_equal(self.im ^ self.f, self.im) assert_array_equal(self.nm ^ True, self.im) assert_array_equal(self.im ^ False, self.im) class TestBoolCmp(TestCase): def setUp(self): self.f = ones(256, dtype=np.float32) self.ef = ones(self.f.size, dtype=np.bool) self.d = ones(128, dtype=np.float64) self.ed = ones(self.d.size, dtype=np.bool) # generate values for all permutation of 256bit simd vectors s = 0 for i in range(32): self.f[s:s+8] = [i & 2**x for x in range(8)] self.ef[s:s+8] = [(i & 2**x) != 0 for x in range(8)] s += 8 s = 0 for i in range(16): self.d[s:s+4] = [i & 2**x for x in range(4)] self.ed[s:s+4] = [(i & 2**x) != 0 for x in range(4)] s += 4 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:]) 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:]) 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:]) class TestSeterr(TestCase): def test_default(self): err = geterr() self.assertEqual(err, dict( divide='warn', invalid='warn', over='warn', under='ignore', )) def test_set(self): with np.errstate(): err = seterr() old = seterr(divide='print') self.assertTrue(err == old) new = seterr() self.assertTrue(new['divide'] == 'print') seterr(over='raise') self.assertTrue(geterr()['over'] == 'raise') self.assertTrue(new['divide'] == 'print') seterr(**old) self.assertTrue(geterr() == old) @dec.skipif(platform.machine() == "armv5tel", "See gh-413.") def test_divide_err(self): with errstate(divide='raise'): try: array([1.]) / array([0.]) except FloatingPointError: pass else: self.fail() seterr(divide='ignore') array([1.]) / array([0.]) class TestFloatExceptions(TestCase): def assert_raises_fpe(self, fpeerr, flop, x, y): ftype = type(x) try: flop(x, y) assert_(False, "Type %s did not raise fpe error '%s'." % (ftype, fpeerr)) except FloatingPointError as exc: assert_(str(exc).find(fpeerr) >= 0, "Type %s raised wrong fpe error '%s'." % (ftype, exc)) def assert_op_raises_fpe(self, fpeerr, flop, sc1, sc2): # Check that fpe exception is raised. # # Given a floating operation `flop` and two scalar values, check that # the operation raises the floating point exception specified by #`fpeerr`. Tests all variants with 0-d array scalars as well. self.assert_raises_fpe(fpeerr, flop, sc1, sc2); self.assert_raises_fpe(fpeerr, flop, sc1[()], sc2); self.assert_raises_fpe(fpeerr, flop, sc1, sc2[()]); self.assert_raises_fpe(fpeerr, flop, sc1[()], sc2[()]); @dec.knownfailureif(True, "See ticket 1755") def test_floating_exceptions(self): # Test basic arithmetic function errors with np.errstate(all='raise'): # Test for all real and complex float types for typecode in np.typecodes['AllFloat']: ftype = np.obj2sctype(typecode) if np.dtype(ftype).kind == 'f': # Get some extreme values for the type fi = np.finfo(ftype) ft_tiny = fi.tiny ft_max = fi.max ft_eps = fi.eps underflow = 'underflow' divbyzero = 'divide by zero' else: # 'c', complex, corresponding real dtype rtype = type(ftype(0).real) fi = np.finfo(rtype) ft_tiny = ftype(fi.tiny) ft_max = ftype(fi.max) ft_eps = ftype(fi.eps) # The complex types raise different exceptions underflow = '' divbyzero = '' overflow = 'overflow' invalid = 'invalid' self.assert_raises_fpe(underflow, lambda a, b:a/b, ft_tiny, ft_max) self.assert_raises_fpe(underflow, lambda a, b:a*b, ft_tiny, ft_tiny) self.assert_raises_fpe(overflow, lambda a, b:a*b, ft_max, ftype(2)) self.assert_raises_fpe(overflow, lambda a, b:a/b, ft_max, ftype(0.5)) self.assert_raises_fpe(overflow, lambda a, b:a+b, ft_max, ft_max*ft_eps) self.assert_raises_fpe(overflow, lambda a, b:a-b, -ft_max, ft_max*ft_eps) self.assert_raises_fpe(overflow, np.power, ftype(2), ftype(2**fi.nexp)) self.assert_raises_fpe(divbyzero, lambda a, b:a/b, ftype(1), ftype(0)) self.assert_raises_fpe(invalid, lambda a, b:a/b, ftype(np.inf), ftype(np.inf)) self.assert_raises_fpe(invalid, lambda a, b:a/b, ftype(0), ftype(0)) self.assert_raises_fpe(invalid, lambda a, b:a-b, ftype(np.inf), ftype(np.inf)) self.assert_raises_fpe(invalid, lambda a, b:a+b, ftype(np.inf), ftype(-np.inf)) self.assert_raises_fpe(invalid, lambda a, b:a*b, ftype(0), ftype(np.inf)) class TestTypes(TestCase): def check_promotion_cases(self, promote_func): #Tests that the scalars get coerced correctly. b = np.bool_(0) i8, i16, i32, i64 = int8(0), int16(0), int32(0), int64(0) u8, u16, u32, u64 = uint8(0), uint16(0), uint32(0), uint64(0) f32, f64, fld = float32(0), float64(0), longdouble(0) c64, c128, cld = complex64(0), complex128(0), clongdouble(0) # coercion within the same kind assert_equal(promote_func(i8, i16), np.dtype(int16)) assert_equal(promote_func(i32, i8), np.dtype(int32)) assert_equal(promote_func(i16, i64), np.dtype(int64)) assert_equal(promote_func(u8, u32), np.dtype(uint32)) assert_equal(promote_func(f32, f64), np.dtype(float64)) assert_equal(promote_func(fld, f32), np.dtype(longdouble)) assert_equal(promote_func(f64, fld), np.dtype(longdouble)) assert_equal(promote_func(c128, c64), np.dtype(complex128)) assert_equal(promote_func(cld, c128), np.dtype(clongdouble)) assert_equal(promote_func(c64, fld), np.dtype(clongdouble)) # coercion between kinds assert_equal(promote_func(b, i32), np.dtype(int32)) assert_equal(promote_func(b, u8), np.dtype(uint8)) assert_equal(promote_func(i8, u8), np.dtype(int16)) assert_equal(promote_func(u8, i32), np.dtype(int32)) assert_equal(promote_func(i64, u32), np.dtype(int64)) assert_equal(promote_func(u64, i32), np.dtype(float64)) assert_equal(promote_func(i32, f32), np.dtype(float64)) assert_equal(promote_func(i64, f32), np.dtype(float64)) assert_equal(promote_func(f32, i16), np.dtype(float32)) assert_equal(promote_func(f32, u32), np.dtype(float64)) assert_equal(promote_func(f32, c64), np.dtype(complex64)) assert_equal(promote_func(c128, f32), np.dtype(complex128)) assert_equal(promote_func(cld, f64), np.dtype(clongdouble)) # coercion between scalars and 1-D arrays assert_equal(promote_func(array([b]), i8), np.dtype(int8)) assert_equal(promote_func(array([b]), u8), np.dtype(uint8)) assert_equal(promote_func(array([b]), i32), np.dtype(int32)) assert_equal(promote_func(array([b]), u32), np.dtype(uint32)) assert_equal(promote_func(array([i8]), i64), np.dtype(int8)) assert_equal(promote_func(u64, array([i32])), np.dtype(int32)) assert_equal(promote_func(i64, array([u32])), np.dtype(uint32)) assert_equal(promote_func(int32(-1), array([u64])), np.dtype(float64)) assert_equal(promote_func(f64, array([f32])), np.dtype(float32)) assert_equal(promote_func(fld, array([f32])), np.dtype(float32)) assert_equal(promote_func(array([f64]), fld), np.dtype(float64)) assert_equal(promote_func(fld, array([c64])), np.dtype(complex64)) assert_equal(promote_func(c64, array([f64])), np.dtype(complex128)) assert_equal(promote_func(complex64(3j), array([f64])), np.dtype(complex128)) # coercion between scalars and 1-D arrays, where # the scalar has greater kind than the array assert_equal(promote_func(array([b]), f64), np.dtype(float64)) assert_equal(promote_func(array([b]), i64), np.dtype(int64)) assert_equal(promote_func(array([b]), u64), np.dtype(uint64)) assert_equal(promote_func(array([i8]), f64), np.dtype(float64)) assert_equal(promote_func(array([u16]), f64), np.dtype(float64)) # uint and int are treated as the same "kind" for # the purposes of array-scalar promotion. assert_equal(promote_func(array([u16]), i32), np.dtype(uint16)) # float and complex are treated as the same "kind" for # the purposes of array-scalar promotion, so that you can do # (0j + float32array) to get a complex64 array instead of # a complex128 array. assert_equal(promote_func(array([f32]), c128), np.dtype(complex64)) def test_coercion(self): def res_type(a, b): return np.add(a, b).dtype self.check_promotion_cases(res_type) # Use-case: float/complex scalar * bool/int8 array # shouldn't narrow the float/complex type for a in [np.array([True, False]), np.array([-3, 12], dtype=np.int8)]: b = 1.234 * a assert_equal(b.dtype, np.dtype('f8'), "array type %s" % a.dtype) b = np.longdouble(1.234) * a assert_equal(b.dtype, np.dtype(np.longdouble), "array type %s" % a.dtype) b = np.float64(1.234) * a assert_equal(b.dtype, np.dtype('f8'), "array type %s" % a.dtype) b = np.float32(1.234) * a assert_equal(b.dtype, np.dtype('f4'), "array type %s" % a.dtype) b = np.float16(1.234) * a assert_equal(b.dtype, np.dtype('f2'), "array type %s" % a.dtype) b = 1.234j * a assert_equal(b.dtype, np.dtype('c16'), "array type %s" % a.dtype) b = np.clongdouble(1.234j) * a assert_equal(b.dtype, np.dtype(np.clongdouble), "array type %s" % a.dtype) b = np.complex128(1.234j) * a assert_equal(b.dtype, np.dtype('c16'), "array type %s" % a.dtype) b = np.complex64(1.234j) * a assert_equal(b.dtype, np.dtype('c8'), "array type %s" % a.dtype) # The following use-case is problematic, and to resolve its # tricky side-effects requires more changes. # ## Use-case: (1-t)*a, where 't' is a boolean array and 'a' is ## a float32, shouldn't promote to float64 #a = np.array([1.0, 1.5], dtype=np.float32) #t = np.array([True, False]) #b = t*a #assert_equal(b, [1.0, 0.0]) #assert_equal(b.dtype, np.dtype('f4')) #b = (1-t)*a #assert_equal(b, [0.0, 1.5]) #assert_equal(b.dtype, np.dtype('f4')) ## Probably ~t (bitwise negation) is more proper to use here, ## but this is arguably less intuitive to understand at a glance, and ## would fail if 't' is actually an integer array instead of boolean: #b = (~t)*a #assert_equal(b, [0.0, 1.5]) #assert_equal(b.dtype, np.dtype('f4')) def test_result_type(self): self.check_promotion_cases(np.result_type) assert_(np.result_type(None) == np.dtype(None)) def test_promote_types_endian(self): # promote_types should always return native-endian types 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('U16', '>i8'), np.dtype('U16')) assert_equal(np.promote_types('S5', '>U8'), np.dtype('U8')) assert_equal(np.promote_types('U8', '>S5'), np.dtype('U8')) assert_equal(np.promote_types('U8', '>U5'), np.dtype('U8')) assert_equal(np.promote_types('M8', '>M8'), np.dtype('M8')) assert_equal(np.promote_types('m8', '>m8'), np.dtype('m8')) def test_can_cast(self): assert_(np.can_cast(np.int32, np.int64)) assert_(np.can_cast(np.float64, np.complex)) assert_(not np.can_cast(np.complex, np.float)) assert_(np.can_cast('i8', 'f8')) assert_(not np.can_cast('i8', 'f4')) assert_(np.can_cast('i4', 'S4')) assert_(np.can_cast('i8', 'i8', 'no')) assert_(not np.can_cast('i8', 'no')) assert_(np.can_cast('i8', 'equiv')) assert_(not np.can_cast('i8', 'equiv')) assert_(np.can_cast('i8', 'safe')) assert_(not np.can_cast('i4', 'safe')) assert_(np.can_cast('i4', 'same_kind')) assert_(not np.can_cast('u4', 'same_kind')) assert_(np.can_cast('u4', 'unsafe')) assert_raises(TypeError, np.can_cast, 'i4', None) assert_raises(TypeError, np.can_cast, None, 'i4') # Custom exception class to test exception propagation in fromiter class NIterError(Exception): pass class TestFromiter(TestCase): def makegen(self): for x in range(24): yield x**2 def test_types(self): ai32 = fromiter(self.makegen(), int32) ai64 = fromiter(self.makegen(), int64) af = fromiter(self.makegen(), float) self.assertTrue(ai32.dtype == dtype(int32)) self.assertTrue(ai64.dtype == dtype(int64)) self.assertTrue(af.dtype == dtype(float)) def test_lengths(self): expected = array(list(self.makegen())) a = fromiter(self.makegen(), int) a20 = fromiter(self.makegen(), int, 20) self.assertTrue(len(a) == len(expected)) self.assertTrue(len(a20) == 20) self.assertRaises(ValueError, fromiter, self.makegen(), int, len(expected) + 10) def test_values(self): expected = array(list(self.makegen())) a = fromiter(self.makegen(), int) a20 = fromiter(self.makegen(), int, 20) self.assertTrue(alltrue(a == expected, axis=0)) self.assertTrue(alltrue(a20 == expected[:20], axis=0)) def load_data(self, n, eindex): # Utility method for the issue 2592 tests. # Raise an exception at the desired index in the iterator. for e in range(n): if e == eindex: raise NIterError('error at index %s' % eindex) yield e def test_2592(self): # Test iteration exceptions are correctly raised. count, eindex = 10, 5 self.assertRaises(NIterError, np.fromiter, self.load_data(count, eindex), dtype=int, count=count) def test_2592_edge(self): # Test iter. exceptions, edge case (exception at end of iterator). count = 10 eindex = count-1 self.assertRaises(NIterError, np.fromiter, self.load_data(count, eindex), dtype=int, count=count) class TestNonzero(TestCase): def test_nonzero_trivial(self): assert_equal(np.count_nonzero(array([])), 0) assert_equal(np.count_nonzero(array([], dtype='?')), 0) assert_equal(np.nonzero(array([])), ([],)) assert_equal(np.count_nonzero(array(0)), 0) assert_equal(np.count_nonzero(array(0, dtype='?')), 0) assert_equal(np.nonzero(array(0)), ([],)) assert_equal(np.count_nonzero(array(1)), 1) assert_equal(np.count_nonzero(array(1, dtype='?')), 1) assert_equal(np.nonzero(array(1)), ([0],)) def test_nonzero_onedim(self): x = array([1, 0, 2, -1, 0, 0, 8]) assert_equal(np.count_nonzero(x), 4) assert_equal(np.count_nonzero(x), 4) assert_equal(np.nonzero(x), ([0, 2, 3, 6],)) x = array([(1, 2), (0, 0), (1, 1), (-1, 3), (0, 7)], dtype=[('a', 'i4'), ('b', 'i2')]) assert_equal(np.count_nonzero(x['a']), 3) assert_equal(np.count_nonzero(x['b']), 4) assert_equal(np.nonzero(x['a']), ([0, 2, 3],)) assert_equal(np.nonzero(x['b']), ([0, 2, 3, 4],)) def test_nonzero_twodim(self): x = array([[0, 1, 0], [2, 0, 3]]) assert_equal(np.count_nonzero(x), 3) assert_equal(np.nonzero(x), ([0, 1, 1], [1, 0, 2])) x = np.eye(3) assert_equal(np.count_nonzero(x), 3) assert_equal(np.nonzero(x), ([0, 1, 2], [0, 1, 2])) x = array([[(0, 1), (0, 0), (1, 11)], [(1, 1), (1, 0), (0, 0)], [(0, 0), (1, 5), (0, 1)]], dtype=[('a', 'f4'), ('b', 'u1')]) assert_equal(np.count_nonzero(x['a']), 4) assert_equal(np.count_nonzero(x['b']), 5) assert_equal(np.nonzero(x['a']), ([0, 1, 1, 2], [2, 0, 1, 1])) assert_equal(np.nonzero(x['b']), ([0, 0, 1, 2, 2], [0, 2, 0, 1, 2])) assert_equal(np.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])) class TestIndex(TestCase): def test_boolean(self): a = rand(3, 5, 8) V = rand(5, 8) g1 = randint(0, 5, size=15) g2 = randint(0, 8, size=15) V[g1, g2] = -V[g1, g2] assert_((array([a[0][V>0], a[1][V>0], a[2][V>0]]) == a[:, V>0]).all()) def test_boolean_edgecase(self): a = np.array([], dtype='int32') b = np.array([], dtype='bool') c = a[b] assert_equal(c, []) assert_equal(c.dtype, np.dtype('int32')) class TestBinaryRepr(TestCase): def test_zero(self): assert_equal(binary_repr(0), '0') def test_large(self): assert_equal(binary_repr(10736848), '101000111101010011010000') def test_negative(self): assert_equal(binary_repr(-1), '-1') assert_equal(binary_repr(-1, width=8), '11111111') class TestBaseRepr(TestCase): def test_base3(self): assert_equal(base_repr(3**5, 3), '100000') def test_positive(self): assert_equal(base_repr(12, 10), '12') assert_equal(base_repr(12, 10, 4), '000012') assert_equal(base_repr(12, 4), '30') assert_equal(base_repr(3731624803700888, 36), '10QR0ROFCEW') def test_negative(self): assert_equal(base_repr(-12, 10), '-12') assert_equal(base_repr(-12, 10, 4), '-000012') assert_equal(base_repr(-12, 4), '-30') class TestArrayComparisons(TestCase): def test_array_equal(self): res = array_equal(array([1, 2]), array([1, 2])) assert_(res) assert_(type(res) is bool) res = array_equal(array([1, 2]), array([1, 2, 3])) assert_(not res) assert_(type(res) is bool) res = array_equal(array([1, 2]), array([3, 4])) assert_(not res) assert_(type(res) is bool) res = array_equal(array([1, 2]), array([1, 3])) assert_(not res) assert_(type(res) is bool) res = array_equal(array(['a'], dtype='S1'), array(['a'], dtype='S1')) assert_(res) assert_(type(res) is bool) res = array_equal(array([('a', 1)], dtype='S1,u4'), array([('a', 1)], dtype='S1,u4')) assert_(res) assert_(type(res) is bool) def test_array_equiv(self): res = array_equiv(array([1, 2]), array([1, 2])) assert_(res) assert_(type(res) is bool) res = array_equiv(array([1, 2]), array([1, 2, 3])) assert_(not res) assert_(type(res) is bool) res = array_equiv(array([1, 2]), array([3, 4])) assert_(not res) assert_(type(res) is bool) res = array_equiv(array([1, 2]), array([1, 3])) assert_(not res) assert_(type(res) is bool) res = array_equiv(array([1, 1]), array([1])) assert_(res) assert_(type(res) is bool) res = array_equiv(array([1, 1]), array([[1], [1]])) assert_(res) assert_(type(res) is bool) res = array_equiv(array([1, 2]), array([2])) assert_(not res) assert_(type(res) is bool) res = array_equiv(array([1, 2]), array([[1], [2]])) assert_(not res) assert_(type(res) is bool) res = array_equiv(array([1, 2]), array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])) assert_(not res) assert_(type(res) is bool) def assert_array_strict_equal(x, y): assert_array_equal(x, y) # Check flags assert_(x.flags == y.flags) # check endianness assert_(x.dtype.isnative == y.dtype.isnative) class TestClip(TestCase): def setUp(self): self.nr = 5 self.nc = 3 def fastclip(self, a, m, M, out=None): if out is None: return a.clip(m, M) else: return a.clip(m, M, out) def clip(self, a, m, M, out=None): # use slow-clip selector = less(a, m)+2*greater(a, M) return selector.choose((a, m, M), out=out) # Handy functions def _generate_data(self, n, m): return randn(n, m) def _generate_data_complex(self, n, m): return randn(n, m) + 1.j *rand(n, m) def _generate_flt_data(self, n, m): return (randn(n, m)).astype(float32) def _neg_byteorder(self, a): a = asarray(a) if sys.byteorder == 'little': a = a.astype(a.dtype.newbyteorder('>')) else: a = a.astype(a.dtype.newbyteorder('<')) return a def _generate_non_native_data(self, n, m): data = randn(n, m) data = self._neg_byteorder(data) assert_(not data.dtype.isnative) return data def _generate_int_data(self, n, m): return (10 * rand(n, m)).astype(int64) def _generate_int32_data(self, n, m): return (10 * rand(n, m)).astype(int32) # Now the real test cases def test_simple_double(self): #Test native double input with scalar min/max. a = self._generate_data(self.nr, self.nc) m = 0.1 M = 0.6 ac = self.fastclip(a, m, M) act = self.clip(a, m, M) assert_array_strict_equal(ac, act) def test_simple_int(self): #Test native int input with scalar min/max. a = self._generate_int_data(self.nr, self.nc) a = a.astype(int) m = -2 M = 4 ac = self.fastclip(a, m, M) act = self.clip(a, m, M) assert_array_strict_equal(ac, act) def test_array_double(self): #Test native double input with array min/max. a = self._generate_data(self.nr, self.nc) m = zeros(a.shape) M = m + 0.5 ac = self.fastclip(a, m, M) act = self.clip(a, m, M) assert_array_strict_equal(ac, act) def test_simple_nonnative(self): #Test non native double input with scalar min/max. #Test native double input with non native double scalar min/max. a = self._generate_non_native_data(self.nr, self.nc) m = -0.5 M = 0.6 ac = self.fastclip(a, m, M) act = self.clip(a, m, M) assert_array_equal(ac, act) #Test native double input with non native double scalar min/max. a = self._generate_data(self.nr, self.nc) m = -0.5 M = self._neg_byteorder(0.6) assert_(not M.dtype.isnative) ac = self.fastclip(a, m, M) act = self.clip(a, m, M) assert_array_equal(ac, act) def test_simple_complex(self): #Test native complex input with native double scalar min/max. #Test native input with complex double scalar min/max. a = 3 * self._generate_data_complex(self.nr, self.nc) m = -0.5 M = 1. ac = self.fastclip(a, m, M) act = self.clip(a, m, M) assert_array_strict_equal(ac, act) #Test native input with complex double scalar min/max. a = 3 * self._generate_data(self.nr, self.nc) m = -0.5 + 1.j M = 1. + 2.j ac = self.fastclip(a, m, M) act = self.clip(a, m, M) assert_array_strict_equal(ac, act) def test_clip_non_contig(self): #Test clip for non contiguous native input and native scalar min/max. a = self._generate_data(self.nr * 2, self.nc * 3) a = a[::2, ::3] assert_(not a.flags['F_CONTIGUOUS']) assert_(not a.flags['C_CONTIGUOUS']) ac = self.fastclip(a, -1.6, 1.7) act = self.clip(a, -1.6, 1.7) assert_array_strict_equal(ac, act) def test_simple_out(self): #Test native double input with scalar min/max. a = self._generate_data(self.nr, self.nc) m = -0.5 M = 0.6 ac = zeros(a.shape) act = zeros(a.shape) self.fastclip(a, m, M, ac) self.clip(a, m, M, act) assert_array_strict_equal(ac, act) def test_simple_int32_inout(self): #Test native int32 input with double min/max and int32 out. a = self._generate_int32_data(self.nr, self.nc) m = float64(0) M = float64(2) ac = zeros(a.shape, dtype = int32) act = ac.copy() self.fastclip(a, m, M, ac) self.clip(a, m, M, act) assert_array_strict_equal(ac, act) def test_simple_int64_out(self): #Test native int32 input with int32 scalar min/max and int64 out. a = self._generate_int32_data(self.nr, self.nc) m = int32(-1) M = int32(1) ac = zeros(a.shape, dtype = int64) act = ac.copy() self.fastclip(a, m, M, ac) self.clip(a, m, M, act) assert_array_strict_equal(ac, act) def test_simple_int64_inout(self): #Test native int32 input with double array min/max and int32 out. a = self._generate_int32_data(self.nr, self.nc) m = zeros(a.shape, float64) M = float64(1) ac = zeros(a.shape, dtype = int32) act = ac.copy() self.fastclip(a, m, M, ac) self.clip(a, m, M, act) assert_array_strict_equal(ac, act) def test_simple_int32_out(self): #Test native double input with scalar min/max and int out. a = self._generate_data(self.nr, self.nc) m = -1.0 M = 2.0 ac = zeros(a.shape, dtype = int32) act = ac.copy() self.fastclip(a, m, M, ac) self.clip(a, m, M, act) assert_array_strict_equal(ac, act) def test_simple_inplace_01(self): #Test native double input with array min/max in-place. a = self._generate_data(self.nr, self.nc) ac = a.copy() m = zeros(a.shape) M = 1.0 self.fastclip(a, m, M, a) self.clip(a, m, M, ac) assert_array_strict_equal(a, ac) def test_simple_inplace_02(self): #Test native double input with scalar min/max in-place. a = self._generate_data(self.nr, self.nc) ac = a.copy() m = -0.5 M = 0.6 self.fastclip(a, m, M, a) self.clip(a, m, M, ac) assert_array_strict_equal(a, ac) def test_noncontig_inplace(self): #Test non contiguous double input with double scalar min/max in-place. a = self._generate_data(self.nr * 2, self.nc * 3) a = a[::2, ::3] assert_(not a.flags['F_CONTIGUOUS']) assert_(not a.flags['C_CONTIGUOUS']) ac = a.copy() m = -0.5 M = 0.6 self.fastclip(a, m, M, a) self.clip(a, m, M, ac) assert_array_equal(a, ac) def test_type_cast_01(self): #Test native double input with scalar min/max. a = self._generate_data(self.nr, self.nc) m = -0.5 M = 0.6 ac = self.fastclip(a, m, M) act = self.clip(a, m, M) assert_array_strict_equal(ac, act) def test_type_cast_02(self): #Test native int32 input with int32 scalar min/max. a = self._generate_int_data(self.nr, self.nc) a = a.astype(int32) m = -2 M = 4 ac = self.fastclip(a, m, M) act = self.clip(a, m, M) assert_array_strict_equal(ac, act) def test_type_cast_03(self): #Test native int32 input with float64 scalar min/max. a = self._generate_int32_data(self.nr, self.nc) m = -2 M = 4 ac = self.fastclip(a, float64(m), float64(M)) act = self.clip(a, float64(m), float64(M)) assert_array_strict_equal(ac, act) def test_type_cast_04(self): #Test native int32 input with float32 scalar min/max. a = self._generate_int32_data(self.nr, self.nc) m = float32(-2) M = float32(4) act = self.fastclip(a, m, M) ac = self.clip(a, m, M) assert_array_strict_equal(ac, act) def test_type_cast_05(self): #Test native int32 with double arrays min/max. a = self._generate_int_data(self.nr, self.nc) m = -0.5 M = 1. ac = self.fastclip(a, m * zeros(a.shape), M) act = self.clip(a, m * zeros(a.shape), M) assert_array_strict_equal(ac, act) def test_type_cast_06(self): #Test native with NON native scalar min/max. a = self._generate_data(self.nr, self.nc) m = 0.5 m_s = self._neg_byteorder(m) M = 1. act = self.clip(a, m_s, M) ac = self.fastclip(a, m_s, M) assert_array_strict_equal(ac, act) def test_type_cast_07(self): #Test NON native with native array min/max. a = self._generate_data(self.nr, self.nc) m = -0.5 * ones(a.shape) M = 1. a_s = self._neg_byteorder(a) assert_(not a_s.dtype.isnative) act = a_s.clip(m, M) ac = self.fastclip(a_s, m, M) assert_array_strict_equal(ac, act) def test_type_cast_08(self): #Test NON native with native scalar min/max. a = self._generate_data(self.nr, self.nc) m = -0.5 M = 1. a_s = self._neg_byteorder(a) assert_(not a_s.dtype.isnative) ac = self.fastclip(a_s, m, M) act = a_s.clip(m, M) assert_array_strict_equal(ac, act) def test_type_cast_09(self): #Test native with NON native array min/max. a = self._generate_data(self.nr, self.nc) m = -0.5 * ones(a.shape) M = 1. m_s = self._neg_byteorder(m) assert_(not m_s.dtype.isnative) ac = self.fastclip(a, m_s, M) act = self.clip(a, m_s, M) assert_array_strict_equal(ac, act) def test_type_cast_10(self): #Test native int32 with float min/max and float out for output argument. a = self._generate_int_data(self.nr, self.nc) b = zeros(a.shape, dtype = float32) m = float32(-0.5) M = float32(1) act = self.clip(a, m, M, out = b) ac = self.fastclip(a, m, M, out = b) assert_array_strict_equal(ac, act) def test_type_cast_11(self): #Test non native with native scalar, min/max, out non native a = self._generate_non_native_data(self.nr, self.nc) b = a.copy() b = b.astype(b.dtype.newbyteorder('>')) bt = b.copy() m = -0.5 M = 1. self.fastclip(a, m, M, out = b) self.clip(a, m, M, out = bt) assert_array_strict_equal(b, bt) def test_type_cast_12(self): #Test native int32 input and min/max and float out a = self._generate_int_data(self.nr, self.nc) b = zeros(a.shape, dtype = float32) m = int32(0) M = int32(1) act = self.clip(a, m, M, out = b) ac = self.fastclip(a, m, M, out = b) assert_array_strict_equal(ac, act) def test_clip_with_out_simple(self): #Test native double input with scalar min/max a = self._generate_data(self.nr, self.nc) m = -0.5 M = 0.6 ac = zeros(a.shape) act = zeros(a.shape) self.fastclip(a, m, M, ac) self.clip(a, m, M, act) assert_array_strict_equal(ac, act) def test_clip_with_out_simple2(self): #Test native int32 input with double min/max and int32 out a = self._generate_int32_data(self.nr, self.nc) m = float64(0) M = float64(2) ac = zeros(a.shape, dtype = int32) act = ac.copy() self.fastclip(a, m, M, ac) self.clip(a, m, M, act) assert_array_strict_equal(ac, act) def test_clip_with_out_simple_int32(self): #Test native int32 input with int32 scalar min/max and int64 out a = self._generate_int32_data(self.nr, self.nc) m = int32(-1) M = int32(1) ac = zeros(a.shape, dtype = int64) act = ac.copy() self.fastclip(a, m, M, ac) self.clip(a, m, M, act) assert_array_strict_equal(ac, act) def test_clip_with_out_array_int32(self): #Test native int32 input with double array min/max and int32 out a = self._generate_int32_data(self.nr, self.nc) m = zeros(a.shape, float64) M = float64(1) ac = zeros(a.shape, dtype = int32) act = ac.copy() self.fastclip(a, m, M, ac) self.clip(a, m, M, act) assert_array_strict_equal(ac, act) def test_clip_with_out_array_outint32(self): #Test native double input with scalar min/max and int out a = self._generate_data(self.nr, self.nc) m = -1.0 M = 2.0 ac = zeros(a.shape, dtype = int32) act = ac.copy() self.fastclip(a, m, M, ac) self.clip(a, m, M, act) assert_array_strict_equal(ac, act) def test_clip_inplace_array(self): #Test native double input with array min/max a = self._generate_data(self.nr, self.nc) ac = a.copy() m = zeros(a.shape) M = 1.0 self.fastclip(a, m, M, a) self.clip(a, m, M, ac) assert_array_strict_equal(a, ac) def test_clip_inplace_simple(self): #Test native double input with scalar min/max a = self._generate_data(self.nr, self.nc) ac = a.copy() m = -0.5 M = 0.6 self.fastclip(a, m, M, a) self.clip(a, m, M, ac) assert_array_strict_equal(a, ac) def test_clip_func_takes_out(self): # Ensure that the clip() function takes an out= argument. a = self._generate_data(self.nr, self.nc) ac = a.copy() m = -0.5 M = 0.6 a2 = clip(a, m, M, out=a) self.clip(a, m, M, ac) assert_array_strict_equal(a2, ac) self.assertTrue(a2 is a) class TestAllclose(object): rtol = 1e-5 atol = 1e-8 def setUp(self): self.olderr = np.seterr(invalid='ignore') def tearDown(self): np.seterr(**self.olderr) def tst_allclose(self, x, y): assert_(allclose(x, y), "%s and %s not close" % (x, y)) def tst_not_allclose(self, x, y): assert_(not allclose(x, y), "%s and %s shouldn't be close" % (x, y)) def test_ip_allclose(self): #Parametric test factory. arr = array([100, 1000]) aran = arange(125).reshape((5, 5, 5)) atol = self.atol rtol = self.rtol data = [([1, 0], [1, 0]), ([atol], [0]), ([1], [1+rtol+atol]), (arr, arr + arr*rtol), (arr, arr + arr*rtol + atol*2), (aran, aran + aran*rtol), (inf, inf), (inf, [inf])] for (x, y) in data: yield (self.tst_allclose, x, y) def test_ip_not_allclose(self): #Parametric test factory. aran = arange(125).reshape((5, 5, 5)) atol = self.atol rtol = self.rtol data = [([inf, 0], [1, inf]), ([inf, 0], [1, 0]), ([inf, inf], [1, inf]), ([inf, inf], [1, 0]), ([-inf, 0], [inf, 0]), ([nan, 0], [nan, 0]), ([atol*2], [0]), ([1], [1+rtol+atol*2]), (aran, aran + aran*atol + atol*2), (array([inf, 1]), array([0, inf]))] for (x, y) in data: yield (self.tst_not_allclose, x, y) def test_no_parameter_modification(self): x = array([inf, 1]) y = array([0, inf]) allclose(x, y) assert_array_equal(x, array([inf, 1])) assert_array_equal(y, array([0, inf])) class TestIsclose(object): rtol = 1e-5 atol = 1e-8 def setup(self): atol = self.atol rtol = self.rtol arr = array([100, 1000]) aran = arange(125).reshape((5, 5, 5)) self.all_close_tests = [ ([1, 0], [1, 0]), ([atol], [0]), ([1], [1 + rtol + atol]), (arr, arr + arr*rtol), (arr, arr + arr*rtol + atol), (aran, aran + aran*rtol), (inf, inf), (inf, [inf]), ([inf, -inf], [inf, -inf]), ] self.none_close_tests = [ ([inf, 0], [1, inf]), ([inf, -inf], [1, 0]), ([inf, inf], [1, -inf]), ([inf, inf], [1, 0]), ([nan, 0], [nan, -inf]), ([atol*2], [0]), ([1], [1 + rtol + atol*2]), (aran, aran + rtol*1.1*aran + atol*1.1), (array([inf, 1]), array([0, inf])), ] self.some_close_tests = [ ([inf, 0], [inf, atol*2]), ([atol, 1, 1e6*(1 + 2*rtol) + atol], [0, nan, 1e6]), (arange(3), [0, 1, 2.1]), (nan, [nan, nan, nan]), ([0], [atol, inf, -inf, nan]), (0, [atol, inf, -inf, nan]), ] self.some_close_results = [ [True, False], [True, False, False], [True, True, False], [False, False, False], [True, False, False, False], [True, False, False, False], ] def test_ip_isclose(self): self.setup() tests = self.some_close_tests results = self.some_close_results for (x, y), result in zip(tests, results): yield (assert_array_equal, isclose(x, y), result) def tst_all_isclose(self, x, y): assert_(all(isclose(x, y)), "%s and %s not close" % (x, y)) def tst_none_isclose(self, x, y): msg = "%s and %s shouldn't be close" assert_(not any(isclose(x, y)), msg % (x, y)) def tst_isclose_allclose(self, x, y): msg = "isclose.all() and allclose aren't same for %s and %s" assert_array_equal(isclose(x, y).all(), allclose(x, y), msg % (x, y)) def test_ip_all_isclose(self): self.setup() for (x, y) in self.all_close_tests: yield (self.tst_all_isclose, x, y) def test_ip_none_isclose(self): self.setup() for (x, y) in self.none_close_tests: yield (self.tst_none_isclose, x, y) def test_ip_isclose_allclose(self): self.setup() tests = (self.all_close_tests + self.none_close_tests + self.some_close_tests) for (x, y) in tests: yield (self.tst_isclose_allclose, x, y) def test_equal_nan(self): assert_array_equal(isclose(nan, nan, equal_nan=True), [True]) arr = array([1.0, nan]) assert_array_equal(isclose(arr, arr, equal_nan=True), [True, True]) def test_masked_arrays(self): x = np.ma.masked_where([True, True, False], np.arange(3)) assert_(type(x) is type(isclose(2, x))) x = np.ma.masked_where([True, True, False], [nan, inf, nan]) assert_(type(x) is type(isclose(inf, x))) x = np.ma.masked_where([True, True, False], [nan, nan, nan]) y = isclose(nan, x, equal_nan=True) assert_(type(x) is type(y)) # Ensure that the mask isn't modified... assert_array_equal([True, True, False], y.mask) def test_scalar_return(self): assert_(isscalar(isclose(1, 1))) def test_no_parameter_modification(self): x = array([inf, 1]) y = array([0, inf]) isclose(x, y) assert_array_equal(x, array([inf, 1])) assert_array_equal(y, array([0, inf])) class TestStdVar(TestCase): def setUp(self): self.A = array([1, -1, 1, -1]) self.real_var = 1 def test_basic(self): assert_almost_equal(var(self.A), self.real_var) assert_almost_equal(std(self.A)**2, self.real_var) def test_scalars(self): assert_equal(var(1), 0) assert_equal(std(1), 0) def test_ddof1(self): assert_almost_equal(var(self.A, ddof=1), self.real_var*len(self.A)/float(len(self.A)-1)) assert_almost_equal(std(self.A, ddof=1)**2, self.real_var*len(self.A)/float(len(self.A)-1)) def test_ddof2(self): assert_almost_equal(var(self.A, ddof=2), self.real_var*len(self.A)/float(len(self.A)-2)) assert_almost_equal(std(self.A, ddof=2)**2, self.real_var*len(self.A)/float(len(self.A)-2)) class TestStdVarComplex(TestCase): def test_basic(self): A = array([1, 1.j, -1, -1.j]) real_var = 1 assert_almost_equal(var(A), real_var) assert_almost_equal(std(A)**2, real_var) def test_scalars(self): assert_equal(var(1j), 0) assert_equal(std(1j), 0) class TestCreationFuncs(TestCase): #Test ones, zeros, empty and filled def setUp(self): self.dtypes = ('b', 'i', 'u', 'f', 'c', 'S', 'a', 'U', 'V') self.orders = {'C': 'c_contiguous', 'F': 'f_contiguous'} self.ndims = 10 def check_function(self, func, fill_value=None): par = ( (0, 1, 2), range(self.ndims), self.orders, self.dtypes, 2**np.arange(9) ) fill_kwarg = {} if fill_value is not None: fill_kwarg = {'fill_value': fill_value} with warnings.catch_warnings(): warnings.simplefilter('ignore', DeprecationWarning) for size, ndims, order, type, bytes in itertools.product(*par): shape = ndims * [size] try: dtype = np.dtype('{0}{1}'.format(type, bytes)) except TypeError: # dtype combination does not exist continue else: # do not fill void type if fill_value is not None and type in 'V': continue arr = func(shape, order=order, dtype=dtype, **fill_kwarg) assert_(arr.dtype == dtype) assert_(getattr(arr.flags, self.orders[order])) if fill_value is not None: if dtype.str.startswith('|S'): val = str(fill_value) else: val = fill_value assert_equal(arr, dtype.type(val)) def test_zeros(self): self.check_function(np.zeros) def test_ones(self): self.check_function(np.zeros) def test_empty(self): self.check_function(np.empty) def test_filled(self): self.check_function(np.full, 0) self.check_function(np.full, 1) def test_for_reference_leak(self): # Make sure we have an object for reference dim = 1 beg = sys.getrefcount(dim) np.zeros([dim]*10) assert_(sys.getrefcount(dim) == beg) np.ones([dim]*10) assert_(sys.getrefcount(dim) == beg) np.empty([dim]*10) assert_(sys.getrefcount(dim) == beg) np.full([dim]*10, 0) assert_(sys.getrefcount(dim) == beg) class TestLikeFuncs(TestCase): '''Test ones_like, zeros_like, empty_like and full_like''' def setUp(self): self.data = [ # Array scalars (array(3.), None), (array(3), 'f8'), # 1D arrays (arange(6, dtype='f4'), None), (arange(6), 'c16'), # 2D C-layout arrays (arange(6).reshape(2, 3), None), (arange(6).reshape(3, 2), 'i1'), # 2D F-layout arrays (arange(6).reshape((2, 3), order='F'), None), (arange(6).reshape((3, 2), order='F'), 'i1'), # 3D C-layout arrays (arange(24).reshape(2, 3, 4), None), (arange(24).reshape(4, 3, 2), 'f4'), # 3D F-layout arrays (arange(24).reshape((2, 3, 4), order='F'), None), (arange(24).reshape((4, 3, 2), order='F'), 'f4'), # 3D non-C/F-layout arrays (arange(24).reshape(2, 3, 4).swapaxes(0, 1), None), (arange(24).reshape(4, 3, 2).swapaxes(0, 1), '?'), ] def compare_array_value(self, dz, value, fill_value): if value is not None: if fill_value: try: z = dz.dtype.type(value) except OverflowError: pass else: assert_(all(dz == z)) else: assert_(all(dz == value)) def check_like_function(self, like_function, value, fill_value=False): if fill_value: fill_kwarg = {'fill_value': value} else: fill_kwarg = {} for d, dtype in self.data: # default (K) order, dtype dz = like_function(d, dtype=dtype, **fill_kwarg) assert_equal(dz.shape, d.shape) assert_equal(array(dz.strides)*d.dtype.itemsize, array(d.strides)*dz.dtype.itemsize) assert_equal(d.flags.c_contiguous, dz.flags.c_contiguous) assert_equal(d.flags.f_contiguous, dz.flags.f_contiguous) if dtype is None: assert_equal(dz.dtype, d.dtype) else: assert_equal(dz.dtype, np.dtype(dtype)) self.compare_array_value(dz, value, fill_value) # C order, default dtype dz = like_function(d, order='C', dtype=dtype, **fill_kwarg) assert_equal(dz.shape, d.shape) assert_(dz.flags.c_contiguous) if dtype is None: assert_equal(dz.dtype, d.dtype) else: assert_equal(dz.dtype, np.dtype(dtype)) self.compare_array_value(dz, value, fill_value) # F order, default dtype dz = like_function(d, order='F', dtype=dtype, **fill_kwarg) assert_equal(dz.shape, d.shape) assert_(dz.flags.f_contiguous) if dtype is None: assert_equal(dz.dtype, d.dtype) else: assert_equal(dz.dtype, np.dtype(dtype)) self.compare_array_value(dz, value, fill_value) # A order dz = like_function(d, order='A', dtype=dtype, **fill_kwarg) assert_equal(dz.shape, d.shape) if d.flags.f_contiguous: assert_(dz.flags.f_contiguous) else: assert_(dz.flags.c_contiguous) if dtype is None: assert_equal(dz.dtype, d.dtype) else: assert_equal(dz.dtype, np.dtype(dtype)) self.compare_array_value(dz, value, fill_value) # Test the 'subok' parameter a = np.matrix([[1, 2], [3, 4]]) b = like_function(a, **fill_kwarg) assert_(type(b) is np.matrix) b = like_function(a, subok=False, **fill_kwarg) assert_(type(b) is not np.matrix) def test_ones_like(self): self.check_like_function(np.ones_like, 1) def test_zeros_like(self): self.check_like_function(np.zeros_like, 0) def test_empty_like(self): self.check_like_function(np.empty_like, None) def test_filled_like(self): self.check_like_function(np.full_like, 0, True) self.check_like_function(np.full_like, 1, True) self.check_like_function(np.full_like, 1000, True) self.check_like_function(np.full_like, 123.456, True) self.check_like_function(np.full_like, np.inf, True) class _TestCorrelate(TestCase): def _setup(self, dt): self.x = np.array([1, 2, 3, 4, 5], dtype=dt) self.y = np.array([-1, -2, -3], dtype=dt) self.z1 = np.array([ -3., -8., -14., -20., -26., -14., -5.], dtype=dt) self.z2 = np.array([ -5., -14., -26., -20., -14., -8., -3.], dtype=dt) def test_float(self): self._setup(np.float) z = np.correlate(self.x, self.y, 'full', old_behavior=self.old_behavior) assert_array_almost_equal(z, self.z1) z = np.correlate(self.y, self.x, 'full', old_behavior=self.old_behavior) assert_array_almost_equal(z, self.z2) def test_object(self): self._setup(Decimal) z = np.correlate(self.x, self.y, 'full', old_behavior=self.old_behavior) assert_array_almost_equal(z, self.z1) z = np.correlate(self.y, self.x, 'full', old_behavior=self.old_behavior) assert_array_almost_equal(z, self.z2) class TestCorrelate(_TestCorrelate): old_behavior = True def _setup(self, dt): # correlate uses an unconventional definition so that correlate(a, b) # == correlate(b, a), so force the corresponding outputs to be the same # as well _TestCorrelate._setup(self, dt) self.z2 = self.z1 @dec.deprecated() def test_complex(self): x = np.array([1, 2, 3, 4+1j], dtype=np.complex) y = np.array([-1, -2j, 3+1j], dtype=np.complex) r_z = np.array([3+1j, 6, 8-1j, 9+1j, -1-8j, -4-1j], dtype=np.complex) z = np.correlate(x, y, 'full', old_behavior=self.old_behavior) assert_array_almost_equal(z, r_z) @dec.deprecated() def test_float(self): _TestCorrelate.test_float(self) @dec.deprecated() def test_object(self): _TestCorrelate.test_object(self) class TestCorrelateNew(_TestCorrelate): old_behavior = False def test_complex(self): x = np.array([1, 2, 3, 4+1j], dtype=np.complex) y = np.array([-1, -2j, 3+1j], dtype=np.complex) r_z = np.array([3-1j, 6, 8+1j, 11+5j, -5+8j, -4-1j], dtype=np.complex) #z = np.acorrelate(x, y, 'full') #assert_array_almost_equal(z, r_z) r_z = r_z[::-1].conjugate() z = np.correlate(y, x, 'full', old_behavior=self.old_behavior) assert_array_almost_equal(z, r_z) class TestArgwhere(object): def test_2D(self): x = np.arange(6).reshape((2, 3)) assert_array_equal(np.argwhere(x > 1), [[0, 2], [1, 0], [1, 1], [1, 2]]) def test_list(self): assert_equal(np.argwhere([4, 0, 2, 1, 3]), [[0], [2], [3], [4]]) class TestStringFunction(object): def test_set_string_function(self): a = np.array([1]) np.set_string_function(lambda x: "FOO", repr=True) assert_equal(repr(a), "FOO") np.set_string_function(None, repr=True) assert_equal(repr(a), "array([1])") np.set_string_function(lambda x: "FOO", repr=False) assert_equal(str(a), "FOO") np.set_string_function(None, repr=False) assert_equal(str(a), "[1]") class TestRoll(TestCase): def test_roll1d(self): x = np.arange(10) xr = np.roll(x, 2) assert_equal(xr, np.array([8, 9, 0, 1, 2, 3, 4, 5, 6, 7])) def test_roll2d(self): x2 = np.reshape(np.arange(10), (2, 5)) x2r = np.roll(x2, 1) assert_equal(x2r, np.array([[9, 0, 1, 2, 3], [4, 5, 6, 7, 8]])) x2r = np.roll(x2, 1, axis=0) assert_equal(x2r, np.array([[5, 6, 7, 8, 9], [0, 1, 2, 3, 4]])) x2r = np.roll(x2, 1, axis=1) assert_equal(x2r, np.array([[4, 0, 1, 2, 3], [9, 5, 6, 7, 8]])) def test_roll_empty(self): x = np.array([]) assert_equal(np.roll(x, 1), np.array([])) if __name__ == "__main__": run_module_suite() numpy-1.8.2/numpy/core/tests/test_umath.py0000664000175100017510000014066312370216243022027 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function import sys import platform from numpy.testing import * from numpy.testing.utils import _gen_alignment_data import numpy.core.umath as ncu import numpy as np def on_powerpc(): """ True if we are running on a Power PC platform.""" return platform.processor() == 'powerpc' or \ platform.machine().startswith('ppc') class _FilterInvalids(object): def setUp(self): self.olderr = np.seterr(invalid='ignore') def tearDown(self): np.seterr(**self.olderr) class TestConstants(TestCase): def test_pi(self): assert_allclose(ncu.pi, 3.141592653589793, 1e-15) def test_e(self): assert_allclose(ncu.e, 2.718281828459045, 1e-15) def test_euler_gamma(self): assert_allclose(ncu.euler_gamma, 0.5772156649015329, 1e-15) class TestDivision(TestCase): def test_division_int(self): # int division should follow Python x = np.array([5, 10, 90, 100, -5, -10, -90, -100, -120]) if 5 / 10 == 0.5: assert_equal(x / 100, [0.05, 0.1, 0.9, 1, -0.05, -0.1, -0.9, -1, -1.2]) else: assert_equal(x / 100, [0, 0, 0, 1, -1, -1, -1, -1, -2]) assert_equal(x // 100, [0, 0, 0, 1, -1, -1, -1, -1, -2]) assert_equal(x % 100, [5, 10, 90, 0, 95, 90, 10, 0, 80]) def test_division_complex(self): # check that implementation is correct msg = "Complex division implementation check" x = np.array([1. + 1.*1j, 1. + .5*1j, 1. + 2.*1j], dtype=np.complex128) assert_almost_equal(x**2/x, x, err_msg=msg) # check overflow, underflow msg = "Complex division overflow/underflow check" x = np.array([1.e+110, 1.e-110], dtype=np.complex128) y = x**2/x assert_almost_equal(y/x, [1, 1], err_msg=msg) def test_zero_division_complex(self): with np.errstate(invalid="ignore", divide="ignore"): x = np.array([0.0], dtype=np.complex128) y = 1.0/x assert_(np.isinf(y)[0]) y = complex(np.inf, np.nan)/x assert_(np.isinf(y)[0]) y = complex(np.nan, np.inf)/x assert_(np.isinf(y)[0]) y = complex(np.inf, np.inf)/x assert_(np.isinf(y)[0]) y = 0.0/x assert_(np.isnan(y)[0]) def test_floor_division_complex(self): # check that implementation is correct msg = "Complex floor division implementation check" x = np.array([.9 + 1j, -.1 + 1j, .9 + .5*1j, .9 + 2.*1j], dtype=np.complex128) y = np.array([0., -1., 0., 0.], dtype=np.complex128) assert_equal(np.floor_divide(x**2, x), y, err_msg=msg) # check overflow, underflow msg = "Complex floor division overflow/underflow check" x = np.array([1.e+110, 1.e-110], dtype=np.complex128) y = np.floor_divide(x**2, x) assert_equal(y, [1.e+110, 0], err_msg=msg) class TestPower(TestCase): def test_power_float(self): x = np.array([1., 2., 3.]) assert_equal(x**0, [1., 1., 1.]) assert_equal(x**1, x) assert_equal(x**2, [1., 4., 9.]) y = x.copy() y **= 2 assert_equal(y, [1., 4., 9.]) assert_almost_equal(x**(-1), [1., 0.5, 1./3]) assert_almost_equal(x**(0.5), [1., ncu.sqrt(2), ncu.sqrt(3)]) for out, inp, msg in _gen_alignment_data(dtype=np.float32, type='unary'): exp = [ncu.sqrt(i) for i in inp] assert_almost_equal(inp**(0.5), exp, err_msg=msg) np.sqrt(inp, out=out) assert_equal(out, exp, err_msg=msg) for out, inp, msg in _gen_alignment_data(dtype=np.float64, type='unary'): exp = [ncu.sqrt(i) for i in inp] assert_almost_equal(inp**(0.5), exp, err_msg=msg) np.sqrt(inp, out=out) assert_equal(out, exp, err_msg=msg) def test_power_complex(self): x = np.array([1+2j, 2+3j, 3+4j]) assert_equal(x**0, [1., 1., 1.]) assert_equal(x**1, x) assert_almost_equal(x**2, [-3+4j, -5+12j, -7+24j]) assert_almost_equal(x**3, [(1+2j)**3, (2+3j)**3, (3+4j)**3]) assert_almost_equal(x**4, [(1+2j)**4, (2+3j)**4, (3+4j)**4]) assert_almost_equal(x**(-1), [1/(1+2j), 1/(2+3j), 1/(3+4j)]) assert_almost_equal(x**(-2), [1/(1+2j)**2, 1/(2+3j)**2, 1/(3+4j)**2]) assert_almost_equal(x**(-3), [(-11+2j)/125, (-46-9j)/2197, (-117-44j)/15625]) assert_almost_equal(x**(0.5), [ncu.sqrt(1+2j), ncu.sqrt(2+3j), ncu.sqrt(3+4j)]) norm = 1./((x**14)[0]) assert_almost_equal(x**14 * norm, [i * norm for i in [-76443+16124j, 23161315+58317492j, 5583548873 + 2465133864j]]) # Ticket #836 def assert_complex_equal(x, y): assert_array_equal(x.real, y.real) assert_array_equal(x.imag, y.imag) for z in [complex(0, np.inf), complex(1, np.inf)]: z = np.array([z], dtype=np.complex_) with np.errstate(invalid="ignore"): assert_complex_equal(z**1, z) assert_complex_equal(z**2, z*z) assert_complex_equal(z**3, z*z*z) def test_power_zero(self): # ticket #1271 zero = np.array([0j]) one = np.array([1+0j]) cinf = np.array([complex(np.inf, 0)]) cnan = np.array([complex(np.nan, np.nan)]) def assert_complex_equal(x, y): x, y = np.asarray(x), np.asarray(y) assert_array_equal(x.real, y.real) assert_array_equal(x.imag, y.imag) # positive powers for p in [0.33, 0.5, 1, 1.5, 2, 3, 4, 5, 6.6]: assert_complex_equal(np.power(zero, p), zero) # zero power assert_complex_equal(np.power(zero, 0), one) with np.errstate(invalid="ignore"): assert_complex_equal(np.power(zero, 0+1j), cnan) # negative power for p in [0.33, 0.5, 1, 1.5, 2, 3, 4, 5, 6.6]: assert_complex_equal(np.power(zero, -p), cnan) assert_complex_equal(np.power(zero, -1+0.2j), cnan) def test_fast_power(self): x = np.array([1, 2, 3], np.int16) 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] y = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] for dt in ['f', 'd', 'g'] : xf = np.array(x, dtype=dt) yf = np.array(y, dtype=dt) assert_almost_equal(np.log2(xf), yf) class TestExp2(TestCase): def test_exp2_values(self) : x = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024] y = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] for dt in ['f', 'd', 'g'] : xf = np.array(x, dtype=dt) yf = np.array(y, dtype=dt) assert_almost_equal(np.exp2(yf), xf) class TestLogAddExp2(_FilterInvalids): # Need test for intermediate precisions def test_logaddexp2_values(self) : x = [1, 2, 3, 4, 5] y = [5, 4, 3, 2, 1] z = [6, 6, 6, 6, 6] for dt, dec in zip(['f', 'd', 'g'], [6, 15, 15]) : xf = np.log2(np.array(x, dtype=dt)) yf = np.log2(np.array(y, dtype=dt)) zf = np.log2(np.array(z, dtype=dt)) assert_almost_equal(np.logaddexp2(xf, yf), zf, decimal=dec) def test_logaddexp2_range(self) : x = [1000000, -1000000, 1000200, -1000200] y = [1000200, -1000200, 1000000, -1000000] z = [1000200, -1000000, 1000200, -1000000] for dt in ['f', 'd', 'g'] : logxf = np.array(x, dtype=dt) logyf = np.array(y, dtype=dt) logzf = np.array(z, dtype=dt) assert_almost_equal(np.logaddexp2(logxf, logyf), logzf) def test_inf(self) : inf = np.inf x = [inf, -inf, inf, -inf, inf, 1, -inf, 1] y = [inf, inf, -inf, -inf, 1, inf, 1, -inf] z = [inf, inf, inf, -inf, inf, inf, 1, 1] with np.errstate(invalid='ignore'): for dt in ['f', 'd', 'g'] : logxf = np.array(x, dtype=dt) logyf = np.array(y, dtype=dt) logzf = np.array(z, dtype=dt) assert_equal(np.logaddexp2(logxf, logyf), logzf) def test_nan(self): assert_(np.isnan(np.logaddexp2(np.nan, np.inf))) assert_(np.isnan(np.logaddexp2(np.inf, np.nan))) assert_(np.isnan(np.logaddexp2(np.nan, 0))) assert_(np.isnan(np.logaddexp2(0, np.nan))) assert_(np.isnan(np.logaddexp2(np.nan, np.nan))) class TestLog(TestCase): def test_log_values(self) : x = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024] y = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] for dt in ['f', 'd', 'g'] : log2_ = 0.69314718055994530943 xf = np.array(x, dtype=dt) yf = np.array(y, dtype=dt)*log2_ assert_almost_equal(np.log(xf), yf) class TestExp(TestCase): def test_exp_values(self) : x = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024] y = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] for dt in ['f', 'd', 'g'] : log2_ = 0.69314718055994530943 xf = np.array(x, dtype=dt) yf = np.array(y, dtype=dt)*log2_ assert_almost_equal(np.exp(yf), xf) class TestLogAddExp(_FilterInvalids): def test_logaddexp_values(self) : x = [1, 2, 3, 4, 5] y = [5, 4, 3, 2, 1] z = [6, 6, 6, 6, 6] for dt, dec in zip(['f', 'd', 'g'], [6, 15, 15]) : xf = np.log(np.array(x, dtype=dt)) yf = np.log(np.array(y, dtype=dt)) zf = np.log(np.array(z, dtype=dt)) assert_almost_equal(np.logaddexp(xf, yf), zf, decimal=dec) def test_logaddexp_range(self) : x = [1000000, -1000000, 1000200, -1000200] y = [1000200, -1000200, 1000000, -1000000] z = [1000200, -1000000, 1000200, -1000000] for dt in ['f', 'd', 'g'] : logxf = np.array(x, dtype=dt) logyf = np.array(y, dtype=dt) logzf = np.array(z, dtype=dt) assert_almost_equal(np.logaddexp(logxf, logyf), logzf) def test_inf(self) : inf = np.inf x = [inf, -inf, inf, -inf, inf, 1, -inf, 1] y = [inf, inf, -inf, -inf, 1, inf, 1, -inf] z = [inf, inf, inf, -inf, inf, inf, 1, 1] with np.errstate(invalid='ignore'): for dt in ['f', 'd', 'g'] : logxf = np.array(x, dtype=dt) logyf = np.array(y, dtype=dt) logzf = np.array(z, dtype=dt) assert_equal(np.logaddexp(logxf, logyf), logzf) def test_nan(self): assert_(np.isnan(np.logaddexp(np.nan, np.inf))) assert_(np.isnan(np.logaddexp(np.inf, np.nan))) assert_(np.isnan(np.logaddexp(np.nan, 0))) assert_(np.isnan(np.logaddexp(0, np.nan))) assert_(np.isnan(np.logaddexp(np.nan, np.nan))) class TestLog1p(TestCase): def test_log1p(self): assert_almost_equal(ncu.log1p(0.2), ncu.log(1.2)) assert_almost_equal(ncu.log1p(1e-6), ncu.log(1+1e-6)) def test_special(self): 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): assert_almost_equal(ncu.hypot(1, 1), ncu.sqrt(2)) assert_almost_equal(ncu.hypot(0, 0), 0) def assert_hypot_isnan(x, y): with np.errstate(invalid='ignore'): assert_(np.isnan(ncu.hypot(x, y)), "hypot(%s, %s) is %s, not nan" % (x, y, ncu.hypot(x, y))) def assert_hypot_isinf(x, y): with np.errstate(invalid='ignore'): assert_(np.isinf(ncu.hypot(x, y)), "hypot(%s, %s) is %s, not inf" % (x, y, ncu.hypot(x, y))) class TestHypotSpecialValues(TestCase): def test_nan_outputs(self): assert_hypot_isnan(np.nan, np.nan) assert_hypot_isnan(np.nan, 1) def test_nan_outputs2(self): assert_hypot_isinf(np.nan, np.inf) assert_hypot_isinf(np.inf, np.nan) assert_hypot_isinf(np.inf, 0) assert_hypot_isinf(0, np.inf) assert_hypot_isinf(np.inf, np.inf) assert_hypot_isinf(np.inf, 23.0) def test_no_fpe(self): assert_no_warnings(ncu.hypot, np.inf, 0) def assert_arctan2_isnan(x, y): assert_(np.isnan(ncu.arctan2(x, y)), "arctan(%s, %s) is %s, not nan" % (x, y, ncu.arctan2(x, y))) def assert_arctan2_ispinf(x, y): assert_((np.isinf(ncu.arctan2(x, y)) and ncu.arctan2(x, y) > 0), "arctan(%s, %s) is %s, not +inf" % (x, y, ncu.arctan2(x, y))) def assert_arctan2_isninf(x, y): assert_((np.isinf(ncu.arctan2(x, y)) and ncu.arctan2(x, y) < 0), "arctan(%s, %s) is %s, not -inf" % (x, y, ncu.arctan2(x, y))) def assert_arctan2_ispzero(x, y): assert_((ncu.arctan2(x, y) == 0 and not np.signbit(ncu.arctan2(x, y))), "arctan(%s, %s) is %s, not +0" % (x, y, ncu.arctan2(x, y))) def assert_arctan2_isnzero(x, y): assert_((ncu.arctan2(x, y) == 0 and np.signbit(ncu.arctan2(x, y))), "arctan(%s, %s) is %s, not -0" % (x, y, ncu.arctan2(x, y))) class TestArctan2SpecialValues(TestCase): def test_one_one(self): # atan2(1, 1) returns pi/4. assert_almost_equal(ncu.arctan2(1, 1), 0.25 * np.pi) assert_almost_equal(ncu.arctan2(-1, 1), -0.25 * np.pi) assert_almost_equal(ncu.arctan2(1, -1), 0.75 * np.pi) def test_zero_nzero(self): # atan2(+-0, -0) returns +-pi. assert_almost_equal(ncu.arctan2(np.PZERO, np.NZERO), np.pi) assert_almost_equal(ncu.arctan2(np.NZERO, np.NZERO), -np.pi) def test_zero_pzero(self): # atan2(+-0, +0) returns +-0. assert_arctan2_ispzero(np.PZERO, np.PZERO) assert_arctan2_isnzero(np.NZERO, np.PZERO) def test_zero_negative(self): # atan2(+-0, x) returns +-pi for x < 0. assert_almost_equal(ncu.arctan2(np.PZERO, -1), np.pi) assert_almost_equal(ncu.arctan2(np.NZERO, -1), -np.pi) def test_zero_positive(self): # atan2(+-0, x) returns +-0 for x > 0. assert_arctan2_ispzero(np.PZERO, 1) assert_arctan2_isnzero(np.NZERO, 1) def test_positive_zero(self): # atan2(y, +-0) returns +pi/2 for y > 0. assert_almost_equal(ncu.arctan2(1, np.PZERO), 0.5 * np.pi) assert_almost_equal(ncu.arctan2(1, np.NZERO), 0.5 * np.pi) def test_negative_zero(self): # atan2(y, +-0) returns -pi/2 for y < 0. assert_almost_equal(ncu.arctan2(-1, np.PZERO), -0.5 * np.pi) assert_almost_equal(ncu.arctan2(-1, np.NZERO), -0.5 * np.pi) def test_any_ninf(self): # atan2(+-y, -infinity) returns +-pi for finite y > 0. assert_almost_equal(ncu.arctan2(1, np.NINF), np.pi) assert_almost_equal(ncu.arctan2(-1, np.NINF), -np.pi) def test_any_pinf(self): # atan2(+-y, +infinity) returns +-0 for finite y > 0. assert_arctan2_ispzero(1, np.inf) assert_arctan2_isnzero(-1, np.inf) def test_inf_any(self): # atan2(+-infinity, x) returns +-pi/2 for finite x. assert_almost_equal(ncu.arctan2( np.inf, 1), 0.5 * np.pi) assert_almost_equal(ncu.arctan2(-np.inf, 1), -0.5 * np.pi) def test_inf_ninf(self): # atan2(+-infinity, -infinity) returns +-3*pi/4. assert_almost_equal(ncu.arctan2( np.inf, -np.inf), 0.75 * np.pi) assert_almost_equal(ncu.arctan2(-np.inf, -np.inf), -0.75 * np.pi) def test_inf_pinf(self): # atan2(+-infinity, +infinity) returns +-pi/4. assert_almost_equal(ncu.arctan2( np.inf, np.inf), 0.25 * np.pi) assert_almost_equal(ncu.arctan2(-np.inf, np.inf), -0.25 * np.pi) def test_nan_any(self): # atan2(nan, x) returns nan for any x, including inf assert_arctan2_isnan(np.nan, np.inf) assert_arctan2_isnan(np.inf, np.nan) assert_arctan2_isnan(np.nan, np.nan) class TestLdexp(TestCase): def _check_ldexp(self, tp): assert_almost_equal(ncu.ldexp(np.array(2., np.float32), np.array(3, tp)), 16.) assert_almost_equal(ncu.ldexp(np.array(2., np.float64), np.array(3, tp)), 16.) assert_almost_equal(ncu.ldexp(np.array(2., np.longdouble), np.array(3, tp)), 16.) def test_ldexp(self): # The default Python int type should work assert_almost_equal(ncu.ldexp(2., 3), 16.) # The following int types should all be accepted self._check_ldexp(np.int8) self._check_ldexp(np.int16) self._check_ldexp(np.int32) self._check_ldexp('i') self._check_ldexp('l') def test_ldexp_overflow(self): # silence warning emitted on overflow with np.errstate(over="ignore"): imax = np.iinfo(np.dtype('l')).max imin = np.iinfo(np.dtype('l')).min assert_equal(ncu.ldexp(2., imax), np.inf) assert_equal(ncu.ldexp(2., imin), 0) class TestMaximum(_FilterInvalids): def test_reduce(self): dflt = np.typecodes['AllFloat'] dint = np.typecodes['AllInteger'] seq1 = np.arange(11) seq2 = seq1[::-1] func = np.maximum.reduce for dt in dint: tmp1 = seq1.astype(dt) tmp2 = seq2.astype(dt) assert_equal(func(tmp1), 10) assert_equal(func(tmp2), 10) for dt in dflt: tmp1 = seq1.astype(dt) tmp2 = seq2.astype(dt) assert_equal(func(tmp1), 10) assert_equal(func(tmp2), 10) tmp1[::2] = np.nan tmp2[::2] = np.nan assert_equal(func(tmp1), np.nan) assert_equal(func(tmp2), np.nan) def test_reduce_complex(self): assert_equal(np.maximum.reduce([1, 2j]), 1) assert_equal(np.maximum.reduce([1+3j, 2j]), 1+3j) def test_float_nans(self): nan = np.nan arg1 = np.array([0, nan, nan]) arg2 = np.array([nan, 0, nan]) out = np.array([nan, nan, nan]) assert_equal(np.maximum(arg1, arg2), out) def test_complex_nans(self): nan = np.nan for cnan in [complex(nan, 0), complex(0, nan), complex(nan, nan)] : arg1 = np.array([0, cnan, cnan], dtype=np.complex) arg2 = np.array([cnan, 0, cnan], dtype=np.complex) out = np.array([nan, nan, nan], dtype=np.complex) assert_equal(np.maximum(arg1, arg2), out) def test_object_array(self): arg1 = np.arange(5, dtype=np.object) arg2 = arg1 + 1 assert_equal(np.maximum(arg1, arg2), arg2) class TestMinimum(_FilterInvalids): def test_reduce(self): dflt = np.typecodes['AllFloat'] dint = np.typecodes['AllInteger'] seq1 = np.arange(11) seq2 = seq1[::-1] func = np.minimum.reduce for dt in dint: tmp1 = seq1.astype(dt) tmp2 = seq2.astype(dt) assert_equal(func(tmp1), 0) assert_equal(func(tmp2), 0) for dt in dflt: tmp1 = seq1.astype(dt) tmp2 = seq2.astype(dt) assert_equal(func(tmp1), 0) assert_equal(func(tmp2), 0) tmp1[::2] = np.nan tmp2[::2] = np.nan assert_equal(func(tmp1), np.nan) assert_equal(func(tmp2), np.nan) def test_reduce_complex(self): assert_equal(np.minimum.reduce([1, 2j]), 2j) assert_equal(np.minimum.reduce([1+3j, 2j]), 2j) def test_float_nans(self): nan = np.nan arg1 = np.array([0, nan, nan]) arg2 = np.array([nan, 0, nan]) out = np.array([nan, nan, nan]) assert_equal(np.minimum(arg1, arg2), out) def test_complex_nans(self): nan = np.nan for cnan in [complex(nan, 0), complex(0, nan), complex(nan, nan)] : arg1 = np.array([0, cnan, cnan], dtype=np.complex) arg2 = np.array([cnan, 0, cnan], dtype=np.complex) out = np.array([nan, nan, nan], dtype=np.complex) assert_equal(np.minimum(arg1, arg2), out) def test_object_array(self): arg1 = np.arange(5, dtype=np.object) arg2 = arg1 + 1 assert_equal(np.minimum(arg1, arg2), arg1) class TestFmax(_FilterInvalids): def test_reduce(self): dflt = np.typecodes['AllFloat'] dint = np.typecodes['AllInteger'] seq1 = np.arange(11) seq2 = seq1[::-1] func = np.fmax.reduce for dt in dint: tmp1 = seq1.astype(dt) tmp2 = seq2.astype(dt) assert_equal(func(tmp1), 10) assert_equal(func(tmp2), 10) for dt in dflt: tmp1 = seq1.astype(dt) tmp2 = seq2.astype(dt) assert_equal(func(tmp1), 10) assert_equal(func(tmp2), 10) tmp1[::2] = np.nan tmp2[::2] = np.nan assert_equal(func(tmp1), 9) assert_equal(func(tmp2), 9) def test_reduce_complex(self): assert_equal(np.fmax.reduce([1, 2j]), 1) assert_equal(np.fmax.reduce([1+3j, 2j]), 1+3j) def test_float_nans(self): nan = np.nan arg1 = np.array([0, nan, nan]) arg2 = np.array([nan, 0, nan]) out = np.array([0, 0, nan]) assert_equal(np.fmax(arg1, arg2), out) def test_complex_nans(self): nan = np.nan for cnan in [complex(nan, 0), complex(0, nan), complex(nan, nan)] : arg1 = np.array([0, cnan, cnan], dtype=np.complex) arg2 = np.array([cnan, 0, cnan], dtype=np.complex) out = np.array([0, 0, nan], dtype=np.complex) assert_equal(np.fmax(arg1, arg2), out) class TestFmin(_FilterInvalids): def test_reduce(self): dflt = np.typecodes['AllFloat'] dint = np.typecodes['AllInteger'] seq1 = np.arange(11) seq2 = seq1[::-1] func = np.fmin.reduce for dt in dint: tmp1 = seq1.astype(dt) tmp2 = seq2.astype(dt) assert_equal(func(tmp1), 0) assert_equal(func(tmp2), 0) for dt in dflt: tmp1 = seq1.astype(dt) tmp2 = seq2.astype(dt) assert_equal(func(tmp1), 0) assert_equal(func(tmp2), 0) tmp1[::2] = np.nan tmp2[::2] = np.nan assert_equal(func(tmp1), 1) assert_equal(func(tmp2), 1) def test_reduce_complex(self): assert_equal(np.fmin.reduce([1, 2j]), 2j) assert_equal(np.fmin.reduce([1+3j, 2j]), 2j) def test_float_nans(self): nan = np.nan arg1 = np.array([0, nan, nan]) arg2 = np.array([nan, 0, nan]) out = np.array([0, 0, nan]) assert_equal(np.fmin(arg1, arg2), out) def test_complex_nans(self): nan = np.nan for cnan in [complex(nan, 0), complex(0, nan), complex(nan, nan)] : arg1 = np.array([0, cnan, cnan], dtype=np.complex) arg2 = np.array([cnan, 0, cnan], dtype=np.complex) out = np.array([0, 0, nan], dtype=np.complex) assert_equal(np.fmin(arg1, arg2), out) class TestFloatingPoint(TestCase): def test_floating_point(self): assert_equal(ncu.FLOATING_POINT_SUPPORT, 1) class TestDegrees(TestCase): def test_degrees(self): assert_almost_equal(ncu.degrees(np.pi), 180.0) assert_almost_equal(ncu.degrees(-0.5*np.pi), -90.0) class TestRadians(TestCase): def test_radians(self): assert_almost_equal(ncu.radians(180.0), np.pi) assert_almost_equal(ncu.radians(-90.0), -0.5*np.pi) class TestSign(TestCase): def test_sign(self): a = np.array([np.inf, -np.inf, np.nan, 0.0, 3.0, -3.0]) out = np.zeros(a.shape) tgt = np.array([1., -1., np.nan, 0.0, 1.0, -1.0]) with np.errstate(invalid='ignore'): res = ncu.sign(a) assert_equal(res, tgt) res = ncu.sign(a, out) assert_equal(res, tgt) assert_equal(out, tgt) class TestMinMax(TestCase): def test_minmax_blocked(self): "simd tests on max/min" for dt in [np.float32, np.float64]: for out, inp, msg in _gen_alignment_data(dtype=dt, type='unary', max_size=17): for i in range(inp.size): inp[:] = np.arange(inp.size, dtype=dt) inp[i] = np.nan self.assertTrue(np.isnan(inp.max()), msg=repr(inp) + '\n' + msg) self.assertTrue(np.isnan(inp.min()), msg=repr(inp) + '\n' + msg) inp[i] = 1e10 assert_equal(inp.max(), 1e10, err_msg=msg) inp[i] = -1e10 assert_equal(inp.min(), -1e10, err_msg=msg) def test_lower_align(self): # check data that is not aligned to element size # i.e doubles are aligned to 4 bytes on i386 d = np.zeros(23 * 8, dtype=np.int8)[4:-4].view(np.float64) assert_equal(d.max(), d[0]) assert_equal(d.min(), d[0]) class TestAbsolute(TestCase): def test_abs_blocked(self): "simd tests on abs" for dt in [np.float32, np.float64]: for out, inp, msg in _gen_alignment_data(dtype=dt, type='unary', max_size=17): tgt = [ncu.absolute(i) for i in inp] np.absolute(inp, out=out) assert_equal(out, tgt, err_msg=msg) self.assertTrue((out >= 0).all()) # will throw invalid flag depending on compiler optimizations with np.errstate(invalid='ignore'): for v in [np.nan, -np.inf, np.inf]: for i in range(inp.size): d = np.arange(inp.size, dtype=dt) inp[:] = -d inp[i] = v d[i] = -v if v == -np.inf else v assert_array_equal(np.abs(inp), d, err_msg=msg) np.abs(inp, out=out) assert_array_equal(out, d, err_msg=msg) assert_array_equal(-inp, -1*inp, err_msg=msg) np.negative(inp, out=out) assert_array_equal(out, -1*inp, err_msg=msg) def test_lower_align(self): # check data that is not aligned to element size # i.e doubles are aligned to 4 bytes on i386 d = np.zeros(23 * 8, dtype=np.int8)[4:-4].view(np.float64) assert_equal(np.abs(d), d) assert_equal(np.negative(d), -d) np.negative(d, out=d) np.negative(np.ones_like(d), out=d) np.abs(d, out=d) np.abs(np.ones_like(d), out=d) class TestSpecialMethods(TestCase): def test_wrap(self): class with_wrap(object): def __array__(self): return np.zeros(1) def __array_wrap__(self, arr, context): r = with_wrap() r.arr = arr r.context = context return r a = with_wrap() x = ncu.minimum(a, a) assert_equal(x.arr, np.zeros(1)) func, args, i = x.context self.assertTrue(func is ncu.minimum) self.assertEqual(len(args), 2) assert_equal(args[0], a) assert_equal(args[1], a) self.assertEqual(i, 0) def test_wrap_with_iterable(self): # test fix for bug #1026: class with_wrap(np.ndarray): __array_priority__ = 10 def __new__(cls): return np.asarray(1).view(cls).copy() def __array_wrap__(self, arr, context): return arr.view(type(self)) a = with_wrap() x = ncu.multiply(a, (1, 2, 3)) self.assertTrue(isinstance(x, with_wrap)) assert_array_equal(x, np.array((1, 2, 3))) def test_priority_with_scalar(self): # test fix for bug #826: class A(np.ndarray): __array_priority__ = 10 def __new__(cls): return np.asarray(1.0, 'float64').view(cls).copy() a = A() x = np.float64(1)*a self.assertTrue(isinstance(x, A)) assert_array_equal(x, np.array(1)) def test_old_wrap(self): class with_wrap(object): def __array__(self): return np.zeros(1) def __array_wrap__(self, arr): r = with_wrap() r.arr = arr return r a = with_wrap() x = ncu.minimum(a, a) assert_equal(x.arr, np.zeros(1)) def test_priority(self): class A(object): def __array__(self): return np.zeros(1) def __array_wrap__(self, arr, context): r = type(self)() r.arr = arr r.context = context return r class B(A): __array_priority__ = 20. class C(A): __array_priority__ = 40. x = np.zeros(1) a = A() b = B() c = C() f = ncu.minimum self.assertTrue(type(f(x, x)) is np.ndarray) self.assertTrue(type(f(x, a)) is A) self.assertTrue(type(f(x, b)) is B) self.assertTrue(type(f(x, c)) is C) self.assertTrue(type(f(a, x)) is A) self.assertTrue(type(f(b, x)) is B) self.assertTrue(type(f(c, x)) is C) self.assertTrue(type(f(a, a)) is A) self.assertTrue(type(f(a, b)) is B) self.assertTrue(type(f(b, a)) is B) self.assertTrue(type(f(b, b)) is B) self.assertTrue(type(f(b, c)) is C) self.assertTrue(type(f(c, b)) is C) self.assertTrue(type(f(c, c)) is C) self.assertTrue(type(ncu.exp(a) is A)) self.assertTrue(type(ncu.exp(b) is B)) self.assertTrue(type(ncu.exp(c) is C)) def test_failing_wrap(self): class A(object): def __array__(self): return np.zeros(1) def __array_wrap__(self, arr, context): raise RuntimeError a = A() self.assertRaises(RuntimeError, ncu.maximum, a, a) def test_default_prepare(self): class with_wrap(object): __array_priority__ = 10 def __array__(self): return np.zeros(1) def __array_wrap__(self, arr, context): return arr a = with_wrap() x = ncu.minimum(a, a) assert_equal(x, np.zeros(1)) assert_equal(type(x), np.ndarray) def test_prepare(self): class with_prepare(np.ndarray): __array_priority__ = 10 def __array_prepare__(self, arr, context): # make sure we can return a new return np.array(arr).view(type=with_prepare) a = np.array(1).view(type=with_prepare) x = np.add(a, a) assert_equal(x, np.array(2)) assert_equal(type(x), with_prepare) def test_failing_prepare(self): class A(object): def __array__(self): return np.zeros(1) def __array_prepare__(self, arr, context=None): raise RuntimeError a = A() self.assertRaises(RuntimeError, ncu.maximum, a, a) def test_array_with_context(self): class A(object): def __array__(self, dtype=None, context=None): func, args, i = context self.func = func self.args = args self.i = i return np.zeros(1) class B(object): def __array__(self, dtype=None): return np.zeros(1, dtype) class C(object): def __array__(self): return np.zeros(1) a = A() ncu.maximum(np.zeros(1), a) self.assertTrue(a.func is ncu.maximum) assert_equal(a.args[0], 0) self.assertTrue(a.args[1] is a) self.assertTrue(a.i == 1) assert_equal(ncu.maximum(a, B()), 0) assert_equal(ncu.maximum(a, C()), 0) class TestChoose(TestCase): def test_mixed(self): c = np.array([True, True]) a = np.array([True, True]) assert_equal(np.choose(c, (a, 1)), np.array([1, 1])) def is_longdouble_finfo_bogus(): info = np.finfo(np.longcomplex) return not np.isfinite(np.log10(info.tiny/info.eps)) class TestComplexFunctions(object): funcs = [np.arcsin, np.arccos, np.arctan, np.arcsinh, np.arccosh, np.arctanh, np.sin, np.cos, np.tan, np.exp, np.exp2, np.log, np.sqrt, np.log10, np.log2, np.log1p] def test_it(self): for f in self.funcs: if f is np.arccosh : x = 1.5 else : x = .5 fr = f(x) fz = f(np.complex(x)) assert_almost_equal(fz.real, fr, err_msg='real part %s'%f) assert_almost_equal(fz.imag, 0., err_msg='imag part %s'%f) def test_precisions_consistent(self) : z = 1 + 1j for f in self.funcs : fcf = f(np.csingle(z)) fcd = f(np.cdouble(z)) fcl = f(np.clongdouble(z)) assert_almost_equal(fcf, fcd, decimal=6, err_msg='fch-fcd %s'%f) assert_almost_equal(fcl, fcd, decimal=15, err_msg='fch-fcl %s'%f) def test_branch_cuts(self): # check branch cuts and continuity on them yield _check_branch_cut, np.log, -0.5, 1j, 1, -1 yield _check_branch_cut, np.log2, -0.5, 1j, 1, -1 yield _check_branch_cut, np.log10, -0.5, 1j, 1, -1 yield _check_branch_cut, np.log1p, -1.5, 1j, 1, -1 yield _check_branch_cut, np.sqrt, -0.5, 1j, 1, -1 yield _check_branch_cut, np.arcsin, [ -2, 2], [1j, -1j], 1, -1 yield _check_branch_cut, np.arccos, [ -2, 2], [1j, -1j], 1, -1 yield _check_branch_cut, np.arctan, [-2j, 2j], [1, -1 ], -1, 1 yield _check_branch_cut, np.arcsinh, [-2j, 2j], [-1, 1], -1, 1 yield _check_branch_cut, np.arccosh, [ -1, 0.5], [1j, 1j], 1, -1 yield _check_branch_cut, np.arctanh, [ -2, 2], [1j, -1j], 1, -1 # check against bogus branch cuts: assert continuity between quadrants yield _check_branch_cut, np.arcsin, [-2j, 2j], [ 1, 1], 1, 1 yield _check_branch_cut, np.arccos, [-2j, 2j], [ 1, 1], 1, 1 yield _check_branch_cut, np.arctan, [ -2, 2], [1j, 1j], 1, 1 yield _check_branch_cut, np.arcsinh, [ -2, 2, 0], [1j, 1j, 1 ], 1, 1 yield _check_branch_cut, np.arccosh, [-2j, 2j, 2], [1, 1, 1j], 1, 1 yield _check_branch_cut, np.arctanh, [-2j, 2j, 0], [1, 1, 1j], 1, 1 @dec.knownfailureif(True, "These branch cuts are known to fail") def test_branch_cuts_failing(self): # XXX: signed zero not OK with ICC on 64-bit platform for log, see # http://permalink.gmane.org/gmane.comp.python.numeric.general/25335 yield _check_branch_cut, np.log, -0.5, 1j, 1, -1, True yield _check_branch_cut, np.log2, -0.5, 1j, 1, -1, True yield _check_branch_cut, np.log10, -0.5, 1j, 1, -1, True yield _check_branch_cut, np.log1p, -1.5, 1j, 1, -1, True # XXX: signed zeros are not OK for sqrt or for the arc* functions yield _check_branch_cut, np.sqrt, -0.5, 1j, 1, -1, True yield _check_branch_cut, np.arcsin, [ -2, 2], [1j, -1j], 1, -1, True yield _check_branch_cut, np.arccos, [ -2, 2], [1j, -1j], 1, -1, True yield _check_branch_cut, np.arctan, [-2j, 2j], [1, -1 ], -1, 1, True yield _check_branch_cut, np.arcsinh, [-2j, 2j], [-1, 1], -1, 1, True yield _check_branch_cut, np.arccosh, [ -1, 0.5], [1j, 1j], 1, -1, True yield _check_branch_cut, np.arctanh, [ -2, 2], [1j, -1j], 1, -1, True def test_against_cmath(self): import cmath, sys points = [-1-1j, -1+1j, +1-1j, +1+1j] name_map = {'arcsin': 'asin', 'arccos': 'acos', 'arctan': 'atan', 'arcsinh': 'asinh', 'arccosh': 'acosh', 'arctanh': 'atanh'} atol = 4*np.finfo(np.complex).eps for func in self.funcs: fname = func.__name__.split('.')[-1] cname = name_map.get(fname, fname) try: cfunc = getattr(cmath, cname) except AttributeError: continue for p in points: a = complex(func(np.complex_(p))) b = cfunc(p) assert_(abs(a - b) < atol, "%s %s: %s; cmath: %s"%(fname, p, a, b)) def check_loss_of_precision(self, dtype): """Check loss of precision in complex arc* functions""" # Check against known-good functions info = np.finfo(dtype) real_dtype = dtype(0.).real.dtype eps = info.eps def check(x, rtol): x = x.astype(real_dtype) z = x.astype(dtype) d = np.absolute(np.arcsinh(x)/np.arcsinh(z).real - 1) assert_(np.all(d < rtol), (np.argmax(d), x[np.argmax(d)], d.max(), 'arcsinh')) z = (1j*x).astype(dtype) d = np.absolute(np.arcsinh(x)/np.arcsin(z).imag - 1) assert_(np.all(d < rtol), (np.argmax(d), x[np.argmax(d)], d.max(), 'arcsin')) z = x.astype(dtype) d = np.absolute(np.arctanh(x)/np.arctanh(z).real - 1) assert_(np.all(d < rtol), (np.argmax(d), x[np.argmax(d)], d.max(), 'arctanh')) z = (1j*x).astype(dtype) d = np.absolute(np.arctanh(x)/np.arctan(z).imag - 1) assert_(np.all(d < rtol), (np.argmax(d), x[np.argmax(d)], d.max(), 'arctan')) # The switchover was chosen as 1e-3; hence there can be up to # ~eps/1e-3 of relative cancellation error before it x_series = np.logspace(-20, -3.001, 200) x_basic = np.logspace(-2.999, 0, 10, endpoint=False) if dtype is np.longcomplex: # It's not guaranteed that the system-provided arc functions # are accurate down to a few epsilons. (Eg. on Linux 64-bit) # So, give more leeway for long complex tests here: check(x_series, 50*eps) else: check(x_series, 2*eps) check(x_basic, 2*eps/1e-3) # Check a few points z = np.array([1e-5*(1+1j)], dtype=dtype) p = 9.999999999333333333e-6 + 1.000000000066666666e-5j d = np.absolute(1-np.arctanh(z)/p) assert_(np.all(d < 1e-15)) p = 1.0000000000333333333e-5 + 9.999999999666666667e-6j d = np.absolute(1-np.arcsinh(z)/p) assert_(np.all(d < 1e-15)) p = 9.999999999333333333e-6j + 1.000000000066666666e-5 d = np.absolute(1-np.arctan(z)/p) assert_(np.all(d < 1e-15)) p = 1.0000000000333333333e-5j + 9.999999999666666667e-6 d = np.absolute(1-np.arcsin(z)/p) assert_(np.all(d < 1e-15)) # Check continuity across switchover points def check(func, z0, d=1): z0 = np.asarray(z0, dtype=dtype) zp = z0 + abs(z0) * d * eps * 2 zm = z0 - abs(z0) * d * eps * 2 assert_(np.all(zp != zm), (zp, zm)) # NB: the cancellation error at the switchover is at least eps good = (abs(func(zp) - func(zm)) < 2*eps) assert_(np.all(good), (func, z0[~good])) for func in (np.arcsinh, np.arcsinh, np.arcsin, np.arctanh, np.arctan): pts = [rp+1j*ip for rp in (-1e-3, 0, 1e-3) for ip in(-1e-3, 0, 1e-3) if rp != 0 or ip != 0] check(func, pts, 1) check(func, pts, 1j) check(func, pts, 1+1j) def test_loss_of_precision(self): for dtype in [np.complex64, np.complex_]: yield self.check_loss_of_precision, dtype @dec.knownfailureif(is_longdouble_finfo_bogus(), "Bogus long double finfo") def test_loss_of_precision_longcomplex(self): self.check_loss_of_precision(np.longcomplex) class TestAttributes(TestCase): def test_attributes(self): add = ncu.add assert_equal(add.__name__, 'add') assert_(add.__doc__.startswith('add(x1, x2[, out])\n\n')) self.assertTrue(add.ntypes >= 18) # don't fail if types added self.assertTrue('ii->i' in add.types) assert_equal(add.nin, 2) assert_equal(add.nout, 1) assert_equal(add.identity, 0) class TestSubclass(TestCase): def test_subclass_op(self): class simple(np.ndarray): def __new__(subtype, shape): self = np.ndarray.__new__(subtype, shape, dtype=object) self.fill(0) return self a = simple((3, 4)) assert_equal(a+a, a) def _check_branch_cut(f, x0, dx, re_sign=1, im_sign=-1, sig_zero_ok=False, dtype=np.complex): """ Check for a branch cut in a function. Assert that `x0` lies on a branch cut of function `f` and `f` is continuous from the direction `dx`. Parameters ---------- f : func Function to check x0 : array-like Point on branch cut dx : array-like Direction to check continuity in re_sign, im_sign : {1, -1} Change of sign of the real or imaginary part expected sig_zero_ok : bool Whether to check if the branch cut respects signed zero (if applicable) dtype : dtype Dtype to check (should be complex) """ x0 = np.atleast_1d(x0).astype(dtype) dx = np.atleast_1d(dx).astype(dtype) scale = np.finfo(dtype).eps * 1e3 atol = 1e-4 y0 = f(x0) yp = f(x0 + dx*scale*np.absolute(x0)/np.absolute(dx)) ym = f(x0 - dx*scale*np.absolute(x0)/np.absolute(dx)) assert_(np.all(np.absolute(y0.real - yp.real) < atol), (y0, yp)) assert_(np.all(np.absolute(y0.imag - yp.imag) < atol), (y0, yp)) assert_(np.all(np.absolute(y0.real - ym.real*re_sign) < atol), (y0, ym)) assert_(np.all(np.absolute(y0.imag - ym.imag*im_sign) < atol), (y0, ym)) if sig_zero_ok: # check that signed zeros also work as a displacement jr = (x0.real == 0) & (dx.real != 0) ji = (x0.imag == 0) & (dx.imag != 0) x = -x0 x.real[jr] = 0.*dx.real x.imag[ji] = 0.*dx.imag x = -x ym = f(x) ym = ym[jr | ji] y0 = y0[jr | ji] assert_(np.all(np.absolute(y0.real - ym.real*re_sign) < atol), (y0, ym)) assert_(np.all(np.absolute(y0.imag - ym.imag*im_sign) < atol), (y0, ym)) def test_copysign(): assert_(np.copysign(1, -1) == -1) with np.errstate(divide="ignore"): assert_(1 / np.copysign(0, -1) < 0) assert_(1 / np.copysign(0, 1) > 0) assert_(np.signbit(np.copysign(np.nan, -1))) assert_(not np.signbit(np.copysign(np.nan, 1))) def _test_nextafter(t): one = t(1) two = t(2) zero = t(0) eps = np.finfo(t).eps assert_(np.nextafter(one, two) - one == eps) assert_(np.nextafter(one, zero) - one < 0) assert_(np.isnan(np.nextafter(np.nan, one))) assert_(np.isnan(np.nextafter(one, np.nan))) assert_(np.nextafter(one, one) == one) def test_nextafter(): return _test_nextafter(np.float64) def test_nextafterf(): return _test_nextafter(np.float32) @dec.knownfailureif(sys.platform == 'win32' or on_powerpc(), "Long double support buggy on win32 and PPC, ticket 1664.") def test_nextafterl(): return _test_nextafter(np.longdouble) def _test_spacing(t): one = t(1) eps = np.finfo(t).eps nan = t(np.nan) inf = t(np.inf) with np.errstate(invalid='ignore'): assert_(np.spacing(one) == eps) assert_(np.isnan(np.spacing(nan))) assert_(np.isnan(np.spacing(inf))) assert_(np.isnan(np.spacing(-inf))) assert_(np.spacing(t(1e30)) != 0) def test_spacing(): return _test_spacing(np.float64) def test_spacingf(): return _test_spacing(np.float32) @dec.knownfailureif(sys.platform == 'win32' or on_powerpc(), "Long double support buggy on win32 and PPC, ticket 1664.") def test_spacingl(): return _test_spacing(np.longdouble) def test_spacing_gfortran(): # Reference from this fortran file, built with gfortran 4.3.3 on linux # 32bits: # PROGRAM test_spacing # INTEGER, PARAMETER :: SGL = SELECTED_REAL_KIND(p=6, r=37) # INTEGER, PARAMETER :: DBL = SELECTED_REAL_KIND(p=13, r=200) # # WRITE(*,*) spacing(0.00001_DBL) # WRITE(*,*) spacing(1.0_DBL) # WRITE(*,*) spacing(1000._DBL) # WRITE(*,*) spacing(10500._DBL) # # WRITE(*,*) spacing(0.00001_SGL) # WRITE(*,*) spacing(1.0_SGL) # WRITE(*,*) spacing(1000._SGL) # WRITE(*,*) spacing(10500._SGL) # END PROGRAM ref = {} ref[np.float64] = [1.69406589450860068E-021, 2.22044604925031308E-016, 1.13686837721616030E-013, 1.81898940354585648E-012] ref[np.float32] = [ 9.09494702E-13, 1.19209290E-07, 6.10351563E-05, 9.76562500E-04] for dt, dec in zip([np.float32, np.float64], (10, 20)): x = np.array([1e-5, 1, 1000, 10500], dtype=dt) assert_array_almost_equal(np.spacing(x), ref[dt], decimal=dec) def test_nextafter_vs_spacing(): # XXX: spacing does not handle long double yet for t in [np.float32, np.float64]: for _f in [1, 1e-5, 1000]: f = t(_f) f1 = t(_f + 1) assert_(np.nextafter(f, f1) - f == np.spacing(f)) def test_pos_nan(): """Check np.nan is a positive nan.""" assert_(np.signbit(np.nan) == 0) def test_reduceat(): """Test bug in reduceat when structured arrays are not copied.""" db = np.dtype([('name', 'S11'), ('time', np.int64), ('value', np.float32)]) a = np.empty([100], dtype=db) a['name'] = 'Simple' a['time'] = 10 a['value'] = 100 indx = [0, 7, 15, 25] h2 = [] val1 = indx[0] for val2 in indx[1:]: h2.append(np.add.reduce(a['value'][val1:val2])) val1 = val2 h2.append(np.add.reduce(a['value'][val1:])) h2 = np.array(h2) # test buffered -- this should work h1 = np.add.reduceat(a['value'], indx) assert_array_almost_equal(h1, h2) # This is when the error occurs. # test no buffer res = np.setbufsize(32) h1 = np.add.reduceat(a['value'], indx) np.setbufsize(np.UFUNC_BUFSIZE_DEFAULT) assert_array_almost_equal(h1, h2) def test_reduceat_empty(): """Reduceat should work with empty arrays""" indices = np.array([], 'i4') x = np.array([], 'f8') result = np.add.reduceat(x, indices) assert_equal(result.dtype, x.dtype) assert_equal(result.shape, (0,)) # Another case with a slightly different zero-sized shape x = np.ones((5, 2)) result = np.add.reduceat(x, [], axis=0) assert_equal(result.dtype, x.dtype) assert_equal(result.shape, (0, 2)) result = np.add.reduceat(x, [], axis=1) assert_equal(result.dtype, x.dtype) assert_equal(result.shape, (5, 0)) def test_complex_nan_comparisons(): nans = [complex(np.nan, 0), complex(0, np.nan), complex(np.nan, np.nan)] fins = [complex(1, 0), complex(-1, 0), complex(0, 1), complex(0, -1), complex(1, 1), complex(-1, -1), complex(0, 0)] with np.errstate(invalid='ignore'): for x in nans + fins: x = np.array([x]) for y in nans + fins: y = np.array([y]) if np.isfinite(x) and np.isfinite(y): continue assert_equal(x < y, False, err_msg="%r < %r" % (x, y)) assert_equal(x > y, False, err_msg="%r > %r" % (x, y)) assert_equal(x <= y, False, err_msg="%r <= %r" % (x, y)) assert_equal(x >= y, False, err_msg="%r >= %r" % (x, y)) assert_equal(x == y, False, err_msg="%r == %r" % (x, y)) if __name__ == "__main__": run_module_suite() numpy-1.8.2/numpy/core/tests/data/0000775000175100017510000000000012371375430020204 5ustar vagrantvagrant00000000000000numpy-1.8.2/numpy/core/tests/data/astype_copy.pkl0000664000175100017510000000131412370216242023244 0ustar vagrantvagrant00000000000000€cnumpy.core.multiarray _reconstruct qcnumpy ndarray qK…Ub‡Rq(KKI…cnumpy dtype qUf8KK‡Rq(KU>«È7@`-³WÃ7@§ÎÞ£êÃ7@ì®b—Â7@½ò½…°Â7@]·W6Â7@Øñ®ÜGÁ7@ŸþP/3À7@0ìÍnh¿7@M-‚±!¾7@ѵÍ—¼7@£\òÈF®7@ïP;®—7@ð¨€Ý%‹7@EÕÂ?˜7@Hâ•8§7@ÌEUaп7@9¹jOgÎ7@W‰–Ô7@•2nà"Ô7@XuJÔ7@•€¬`Ô7@¥£WÕ7@í9Ò7@ï‚›ŸõÞ7@{jSá7@ÃÉ$ÕÚã7@K¬)©å7@W6†å7@¨ûÙÝ ä7@/eVlä7@aˆ«?ä7@¼Z)Žïã7@0tÿkSã7@½Ñx¬á7@0ìÍnÎ7@C¬¯Lƒ¾7@im|bì¼7@¼øÜÎ4Á7@Œ„ÝbáÞ7@)á’ é7@É_‚ÊÑñ7@Kr61üï7@íŸö½Âå7@ËrzsÑ7@èFºÑ7@%Ö”ÇÖ7@õh«WÙ7@M¾­\Ú7@þIÛ7@Ø Bˆ>Ü7@(V3X^Ý7@udæÇÕÞ7@ù­œøôß7@L‹æ)"ã7@,›ˆàôõ7@tb.numpy-1.8.2/numpy/core/tests/data/recarray_from_file.fits0000664000175100017510000002070012370216242024716 0ustar vagrantvagrant00000000000000SIMPLE = T / file does conform to FITS standard BITPIX = 16 / number of bits per data pixel NAXIS = 0 / number of data axes EXTEND = T / FITS dataset may contain extensions COMMENT FITS (Flexible Image Transport System) format defined in Astronomy andCOMMENT Astrophysics Supplement Series v44/p363, v44/p371, v73/p359, v73/p365.COMMENT Contact the NASA Science Office of Standards and Technology for the COMMENT FITS Definition document #100 and other FITS information. ORIGIN = 'STScI-STSDAS/TABLES' / Tables version 1999-09-07 FILENAME= 'tb.fits ' / name of file NEXTEND = 1 / number of extensions in file END XTENSION= 'BINTABLE' / binary table extension BITPIX = 8 / 8-bit bytes NAXIS = 2 / 2-dimensional binary table NAXIS1 = 17 / width of table in bytes NAXIS2 = 3 PCOUNT = 0 / size of special data area GCOUNT = 1 / one data group (required keyword) TFIELDS = 3 TTYPE1 = 'a ' / label for field 1 TFORM1 = '1D ' / data format of field: 8-byte DOUBLE TTYPE2 = 'b ' / label for field 2 TFORM2 = '1J ' / data format of field: 4-byte INTEGER TTYPE3 = 'c ' / label for field 3 TFORM3 = '5A ' / data format of field: ASCII Character TDISP1 = 'G25.16 ' / display format TDISP2 = 'I11 ' / display format TNULL2 = -2147483647 / undefined value for column TDISP3 = 'A5 ' / display format HISTORY Created Fri 16:25:07 22-Jun-2001 END @fffffg=abcde@ÌÌÌÌÌÍ>fghij@333334?kl numpy-1.8.2/numpy/core/tests/test_unicode.py0000664000175100017510000003046212370216242022331 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function import sys from numpy.testing import * from numpy.core import * from numpy.compat import asbytes, sixu # Guess the UCS length for this python interpreter if sys.version_info[:2] >= (3, 3): # Python 3.3 uses a flexible string representation ucs4 = False def buffer_length(arr): if isinstance(arr, unicode): arr = str(arr) return (sys.getsizeof(arr+"a") - sys.getsizeof(arr)) * len(arr) v = memoryview(arr) if v.shape is None: return len(v) * v.itemsize else: return prod(v.shape) * v.itemsize elif sys.version_info[0] >= 3: import array as _array ucs4 = (_array.array('u').itemsize == 4) def buffer_length(arr): if isinstance(arr, unicode): return _array.array('u').itemsize * len(arr) v = memoryview(arr) if v.shape is None: return len(v) * v.itemsize else: return prod(v.shape) * v.itemsize else: if len(buffer(sixu('u'))) == 4: ucs4 = True else: ucs4 = False def buffer_length(arr): if isinstance(arr, ndarray): return len(arr.data) return len(buffer(arr)) # In both cases below we need to make sure that the byte swapped value (as # UCS4) is still a valid unicode: # Value that can be represented in UCS2 interpreters ucs2_value = sixu('\u0900') # Value that cannot be represented in UCS2 interpreters (but can in UCS4) ucs4_value = sixu('\U00100900') ############################################################ # Creation tests ############################################################ class create_zeros(object): """Check the creation of zero-valued arrays""" def content_check(self, ua, ua_scalar, nbytes): # Check the length of the unicode base type self.assertTrue(int(ua.dtype.str[2:]) == self.ulen) # Check the length of the data buffer self.assertTrue(buffer_length(ua) == nbytes) # Small check that data in array element is ok self.assertTrue(ua_scalar == sixu('')) # Encode to ascii and double check self.assertTrue(ua_scalar.encode('ascii') == asbytes('')) # Check buffer lengths for scalars if ucs4: self.assertTrue(buffer_length(ua_scalar) == 0) else: self.assertTrue(buffer_length(ua_scalar) == 0) def test_zeros0D(self): """Check creation of 0-dimensional objects""" ua = zeros((), dtype='U%s' % self.ulen) self.content_check(ua, ua[()], 4*self.ulen) def test_zerosSD(self): """Check creation of single-dimensional objects""" ua = zeros((2,), dtype='U%s' % self.ulen) self.content_check(ua, ua[0], 4*self.ulen*2) self.content_check(ua, ua[1], 4*self.ulen*2) def test_zerosMD(self): """Check creation of multi-dimensional objects""" ua = zeros((2, 3, 4), dtype='U%s' % self.ulen) self.content_check(ua, ua[0, 0, 0], 4*self.ulen*2*3*4) self.content_check(ua, ua[-1, -1, -1], 4*self.ulen*2*3*4) class test_create_zeros_1(create_zeros, TestCase): """Check the creation of zero-valued arrays (size 1)""" ulen = 1 class test_create_zeros_2(create_zeros, TestCase): """Check the creation of zero-valued arrays (size 2)""" ulen = 2 class test_create_zeros_1009(create_zeros, TestCase): """Check the creation of zero-valued arrays (size 1009)""" ulen = 1009 class create_values(object): """Check the creation of unicode arrays with values""" def content_check(self, ua, ua_scalar, nbytes): # Check the length of the unicode base type self.assertTrue(int(ua.dtype.str[2:]) == self.ulen) # Check the length of the data buffer self.assertTrue(buffer_length(ua) == nbytes) # Small check that data in array element is ok self.assertTrue(ua_scalar == self.ucs_value*self.ulen) # Encode to UTF-8 and double check self.assertTrue(ua_scalar.encode('utf-8') == \ (self.ucs_value*self.ulen).encode('utf-8')) # Check buffer lengths for scalars if ucs4: self.assertTrue(buffer_length(ua_scalar) == 4*self.ulen) else: if self.ucs_value == ucs4_value: # In UCS2, the \U0010FFFF will be represented using a # surrogate *pair* self.assertTrue(buffer_length(ua_scalar) == 2*2*self.ulen) else: # In UCS2, the \uFFFF will be represented using a # regular 2-byte word self.assertTrue(buffer_length(ua_scalar) == 2*self.ulen) def test_values0D(self): """Check creation of 0-dimensional objects with values""" ua = array(self.ucs_value*self.ulen, dtype='U%s' % self.ulen) self.content_check(ua, ua[()], 4*self.ulen) def test_valuesSD(self): """Check creation of single-dimensional objects with values""" ua = array([self.ucs_value*self.ulen]*2, dtype='U%s' % self.ulen) self.content_check(ua, ua[0], 4*self.ulen*2) self.content_check(ua, ua[1], 4*self.ulen*2) def test_valuesMD(self): """Check creation of multi-dimensional objects with values""" ua = array([[[self.ucs_value*self.ulen]*2]*3]*4, dtype='U%s' % self.ulen) self.content_check(ua, ua[0, 0, 0], 4*self.ulen*2*3*4) self.content_check(ua, ua[-1, -1, -1], 4*self.ulen*2*3*4) class test_create_values_1_ucs2(create_values, TestCase): """Check the creation of valued arrays (size 1, UCS2 values)""" ulen = 1 ucs_value = ucs2_value class test_create_values_1_ucs4(create_values, TestCase): """Check the creation of valued arrays (size 1, UCS4 values)""" ulen = 1 ucs_value = ucs4_value class test_create_values_2_ucs2(create_values, TestCase): """Check the creation of valued arrays (size 2, UCS2 values)""" ulen = 2 ucs_value = ucs2_value class test_create_values_2_ucs4(create_values, TestCase): """Check the creation of valued arrays (size 2, UCS4 values)""" ulen = 2 ucs_value = ucs4_value class test_create_values_1009_ucs2(create_values, TestCase): """Check the creation of valued arrays (size 1009, UCS2 values)""" ulen = 1009 ucs_value = ucs2_value class test_create_values_1009_ucs4(create_values, TestCase): """Check the creation of valued arrays (size 1009, UCS4 values)""" ulen = 1009 ucs_value = ucs4_value ############################################################ # Assignment tests ############################################################ class assign_values(object): """Check the assignment of unicode arrays with values""" def content_check(self, ua, ua_scalar, nbytes): # Check the length of the unicode base type self.assertTrue(int(ua.dtype.str[2:]) == self.ulen) # Check the length of the data buffer self.assertTrue(buffer_length(ua) == nbytes) # Small check that data in array element is ok self.assertTrue(ua_scalar == self.ucs_value*self.ulen) # Encode to UTF-8 and double check self.assertTrue(ua_scalar.encode('utf-8') == \ (self.ucs_value*self.ulen).encode('utf-8')) # Check buffer lengths for scalars if ucs4: self.assertTrue(buffer_length(ua_scalar) == 4*self.ulen) else: if self.ucs_value == ucs4_value: # In UCS2, the \U0010FFFF will be represented using a # surrogate *pair* self.assertTrue(buffer_length(ua_scalar) == 2*2*self.ulen) else: # In UCS2, the \uFFFF will be represented using a # regular 2-byte word self.assertTrue(buffer_length(ua_scalar) == 2*self.ulen) def test_values0D(self): """Check assignment of 0-dimensional objects with values""" ua = zeros((), dtype='U%s' % self.ulen) ua[()] = self.ucs_value*self.ulen self.content_check(ua, ua[()], 4*self.ulen) def test_valuesSD(self): """Check assignment of single-dimensional objects with values""" ua = zeros((2,), dtype='U%s' % self.ulen) ua[0] = self.ucs_value*self.ulen self.content_check(ua, ua[0], 4*self.ulen*2) ua[1] = self.ucs_value*self.ulen self.content_check(ua, ua[1], 4*self.ulen*2) def test_valuesMD(self): """Check assignment of multi-dimensional objects with values""" ua = zeros((2, 3, 4), dtype='U%s' % self.ulen) ua[0, 0, 0] = self.ucs_value*self.ulen self.content_check(ua, ua[0, 0, 0], 4*self.ulen*2*3*4) ua[-1, -1, -1] = self.ucs_value*self.ulen self.content_check(ua, ua[-1, -1, -1], 4*self.ulen*2*3*4) class test_assign_values_1_ucs2(assign_values, TestCase): """Check the assignment of valued arrays (size 1, UCS2 values)""" ulen = 1 ucs_value = ucs2_value class test_assign_values_1_ucs4(assign_values, TestCase): """Check the assignment of valued arrays (size 1, UCS4 values)""" ulen = 1 ucs_value = ucs4_value class test_assign_values_2_ucs2(assign_values, TestCase): """Check the assignment of valued arrays (size 2, UCS2 values)""" ulen = 2 ucs_value = ucs2_value class test_assign_values_2_ucs4(assign_values, TestCase): """Check the assignment of valued arrays (size 2, UCS4 values)""" ulen = 2 ucs_value = ucs4_value class test_assign_values_1009_ucs2(assign_values, TestCase): """Check the assignment of valued arrays (size 1009, UCS2 values)""" ulen = 1009 ucs_value = ucs2_value class test_assign_values_1009_ucs4(assign_values, TestCase): """Check the assignment of valued arrays (size 1009, UCS4 values)""" ulen = 1009 ucs_value = ucs4_value ############################################################ # Byteorder tests ############################################################ class byteorder_values: """Check the byteorder of unicode arrays in round-trip conversions""" def test_values0D(self): """Check byteorder of 0-dimensional objects""" ua = array(self.ucs_value*self.ulen, dtype='U%s' % self.ulen) ua2 = ua.newbyteorder() # This changes the interpretation of the data region (but not the # actual data), therefore the returned scalars are not # the same (they are byte-swapped versions of each other). self.assertTrue(ua[()] != ua2[()]) ua3 = ua2.newbyteorder() # Arrays must be equal after the round-trip assert_equal(ua, ua3) def test_valuesSD(self): """Check byteorder of single-dimensional objects""" ua = array([self.ucs_value*self.ulen]*2, dtype='U%s' % self.ulen) ua2 = ua.newbyteorder() self.assertTrue(ua[0] != ua2[0]) self.assertTrue(ua[-1] != ua2[-1]) ua3 = ua2.newbyteorder() # Arrays must be equal after the round-trip assert_equal(ua, ua3) def test_valuesMD(self): """Check byteorder of multi-dimensional objects""" ua = array([[[self.ucs_value*self.ulen]*2]*3]*4, dtype='U%s' % self.ulen) ua2 = ua.newbyteorder() self.assertTrue(ua[0, 0, 0] != ua2[0, 0, 0]) self.assertTrue(ua[-1, -1, -1] != ua2[-1, -1, -1]) ua3 = ua2.newbyteorder() # Arrays must be equal after the round-trip assert_equal(ua, ua3) class test_byteorder_1_ucs2(byteorder_values, TestCase): """Check the byteorder in unicode (size 1, UCS2 values)""" ulen = 1 ucs_value = ucs2_value class test_byteorder_1_ucs4(byteorder_values, TestCase): """Check the byteorder in unicode (size 1, UCS4 values)""" ulen = 1 ucs_value = ucs4_value class test_byteorder_2_ucs2(byteorder_values, TestCase): """Check the byteorder in unicode (size 2, UCS2 values)""" ulen = 2 ucs_value = ucs2_value class test_byteorder_2_ucs4(byteorder_values, TestCase): """Check the byteorder in unicode (size 2, UCS4 values)""" ulen = 2 ucs_value = ucs4_value class test_byteorder_1009_ucs2(byteorder_values, TestCase): """Check the byteorder in unicode (size 1009, UCS2 values)""" ulen = 1009 ucs_value = ucs2_value class test_byteorder_1009_ucs4(byteorder_values, TestCase): """Check the byteorder in unicode (size 1009, UCS4 values)""" ulen = 1009 ucs_value = ucs4_value if __name__ == "__main__": run_module_suite() numpy-1.8.2/numpy/core/tests/test_print.py0000664000175100017510000001773712370216242022051 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function import numpy as np from numpy.testing import * import nose import locale import sys if sys.version_info[0] >= 3: from io import StringIO else: from StringIO import StringIO _REF = {np.inf: 'inf', -np.inf: '-inf', np.nan: 'nan'} def check_float_type(tp): for x in [0, 1, -1, 1e20] : assert_equal(str(tp(x)), str(float(x)), err_msg='Failed str formatting for type %s' % tp) if tp(1e10).itemsize > 4: assert_equal(str(tp(1e10)), str(float('1e10')), err_msg='Failed str formatting for type %s' % tp) else: ref = '1e+10' assert_equal(str(tp(1e10)), ref, err_msg='Failed str formatting for type %s' % tp) def test_float_types(): """ Check formatting. This is only for the str function, and only for simple types. The precision of np.float and np.longdouble aren't the same as the python float precision. """ for t in [np.float32, np.double, np.longdouble] : yield check_float_type, t def check_nan_inf_float(tp): for x in [np.inf, -np.inf, np.nan]: assert_equal(str(tp(x)), _REF[x], err_msg='Failed str formatting for type %s' % tp) def test_nan_inf_float(): """ Check formatting of nan & inf. This is only for the str function, and only for simple types. The precision of np.float and np.longdouble aren't the same as the python float precision. """ for t in [np.float32, np.double, np.longdouble] : yield check_nan_inf_float, t def check_complex_type(tp): for x in [0, 1, -1, 1e20] : assert_equal(str(tp(x)), str(complex(x)), err_msg='Failed str formatting for type %s' % tp) assert_equal(str(tp(x*1j)), str(complex(x*1j)), err_msg='Failed str formatting for type %s' % tp) assert_equal(str(tp(x + x*1j)), str(complex(x + x*1j)), err_msg='Failed str formatting for type %s' % tp) if tp(1e10).itemsize > 8: assert_equal(str(tp(1e10)), str(complex(1e10)), err_msg='Failed str formatting for type %s' % tp) else: ref = '(1e+10+0j)' assert_equal(str(tp(1e10)), ref, err_msg='Failed str formatting for type %s' % tp) def test_complex_types(): """Check formatting of complex types. This is only for the str function, and only for simple types. The precision of np.float and np.longdouble aren't the same as the python float precision. """ for t in [np.complex64, np.cdouble, np.clongdouble] : yield check_complex_type, t def test_complex_inf_nan(): """Check inf/nan formatting of complex types.""" TESTS = { complex(np.inf, 0): "(inf+0j)", complex(0, np.inf): "inf*j", complex(-np.inf, 0): "(-inf+0j)", complex(0, -np.inf): "-inf*j", complex(np.inf, 1): "(inf+1j)", complex(1, np.inf): "(1+inf*j)", complex(-np.inf, 1): "(-inf+1j)", complex(1, -np.inf): "(1-inf*j)", complex(np.nan, 0): "(nan+0j)", complex(0, np.nan): "nan*j", complex(-np.nan, 0): "(nan+0j)", complex(0, -np.nan): "nan*j", complex(np.nan, 1): "(nan+1j)", complex(1, np.nan): "(1+nan*j)", complex(-np.nan, 1): "(nan+1j)", complex(1, -np.nan): "(1+nan*j)", } for tp in [np.complex64, np.cdouble, np.clongdouble]: for c, s in TESTS.items(): yield _check_complex_inf_nan, c, s, tp def _check_complex_inf_nan(c, s, dtype): assert_equal(str(dtype(c)), s) # print tests def _test_redirected_print(x, tp, ref=None): file = StringIO() file_tp = StringIO() stdout = sys.stdout try: sys.stdout = file_tp print(tp(x)) sys.stdout = file if ref: print(ref) else: print(x) finally: sys.stdout = stdout assert_equal(file.getvalue(), file_tp.getvalue(), err_msg='print failed for type%s' % tp) def check_float_type_print(tp): for x in [0, 1, -1, 1e20]: _test_redirected_print(float(x), tp) for x in [np.inf, -np.inf, np.nan]: _test_redirected_print(float(x), tp, _REF[x]) if tp(1e10).itemsize > 4: _test_redirected_print(float(1e10), tp) else: ref = '1e+10' _test_redirected_print(float(1e10), tp, ref) def check_complex_type_print(tp): # We do not create complex with inf/nan directly because the feature is # missing in python < 2.6 for x in [0, 1, -1, 1e20]: _test_redirected_print(complex(x), tp) if tp(1e10).itemsize > 8: _test_redirected_print(complex(1e10), tp) else: ref = '(1e+10+0j)' _test_redirected_print(complex(1e10), tp, ref) _test_redirected_print(complex(np.inf, 1), tp, '(inf+1j)') _test_redirected_print(complex(-np.inf, 1), tp, '(-inf+1j)') _test_redirected_print(complex(-np.nan, 1), tp, '(nan+1j)') def test_float_type_print(): """Check formatting when using print """ for t in [np.float32, np.double, np.longdouble] : yield check_float_type_print, t def test_complex_type_print(): """Check formatting when using print """ for t in [np.complex64, np.cdouble, np.clongdouble] : yield check_complex_type_print, t def test_scalar_format(): """Test the str.format method with NumPy scalar types""" tests = [('{0}', True, np.bool_), ('{0}', False, np.bool_), ('{0:d}', 130, np.uint8), ('{0:d}', 50000, np.uint16), ('{0:d}', 3000000000, np.uint32), ('{0:d}', 15000000000000000000, np.uint64), ('{0:d}', -120, np.int8), ('{0:d}', -30000, np.int16), ('{0:d}', -2000000000, np.int32), ('{0:d}', -7000000000000000000, np.int64), ('{0:g}', 1.5, np.float16), ('{0:g}', 1.5, np.float32), ('{0:g}', 1.5, np.float64), ('{0:g}', 1.5, np.longdouble)] # Python 2.6 doesn't implement complex.__format__ if sys.version_info[:2] > (2, 6): tests += [('{0:g}', 1.5+0.5j, np.complex64), ('{0:g}', 1.5+0.5j, np.complex128), ('{0:g}', 1.5+0.5j, np.clongdouble)] for (fmat, val, valtype) in tests: try: assert_equal(fmat.format(val), fmat.format(valtype(val)), "failed with val %s, type %s" % (val, valtype)) except ValueError as e: assert_(False, "format raised exception (fmt='%s', val=%s, type=%s, exc='%s')" % (fmat, repr(val), repr(valtype), str(e))) # Locale tests: scalar types formatting should be independent of the locale def in_foreign_locale(func): """ Swap LC_NUMERIC locale to one in which the decimal point is ',' and not '.' If not possible, raise nose.SkipTest """ if sys.platform == 'win32': locales = ['FRENCH'] else: locales = ['fr_FR', 'fr_FR.UTF-8', 'fi_FI', 'fi_FI.UTF-8'] def wrapper(*args, **kwargs): curloc = locale.getlocale(locale.LC_NUMERIC) try: for loc in locales: try: locale.setlocale(locale.LC_NUMERIC, loc) break except locale.Error: pass else: raise nose.SkipTest("Skipping locale test, because " "French locale not found") return func(*args, **kwargs) finally: locale.setlocale(locale.LC_NUMERIC, locale=curloc) return nose.tools.make_decorator(func)(wrapper) @in_foreign_locale def test_locale_single(): assert_equal(str(np.float32(1.2)), str(float(1.2))) @in_foreign_locale def test_locale_double(): assert_equal(str(np.double(1.2)), str(float(1.2))) @in_foreign_locale def test_locale_longdouble(): assert_equal(str(np.longdouble(1.2)), str(float(1.2))) if __name__ == "__main__": run_module_suite() numpy-1.8.2/numpy/core/tests/test_function_base.py0000664000175100017510000000616112370216243023522 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function from numpy.testing import * from numpy import logspace, linspace, array class TestLogspace(TestCase): def test_basic(self): y = logspace(0, 6) assert_(len(y) == 50) y = logspace(0, 6, num=100) assert_(y[-1] == 10 ** 6) y = logspace(0, 6, endpoint=0) assert_(y[-1] < 10 ** 6) y = logspace(0, 6, num=7) assert_array_equal(y, [1, 10, 100, 1e3, 1e4, 1e5, 1e6]) class TestLinspace(TestCase): def test_basic(self): y = linspace(0, 10) assert_(len(y) == 50) y = linspace(2, 10, num=100) assert_(y[-1] == 10) y = linspace(2, 10, endpoint=0) assert_(y[-1] < 10) def test_corner(self): y = list(linspace(0, 1, 1)) assert_(y == [0.0], y) y = list(linspace(0, 1, 2.5)) assert_(y == [0.0, 1.0]) def test_type(self): t1 = linspace(0, 1, 0).dtype t2 = linspace(0, 1, 1).dtype t3 = linspace(0, 1, 2).dtype assert_equal(t1, t2) assert_equal(t2, t3) 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)) numpy-1.8.2/numpy/core/tests/test_umath_complex.py0000664000175100017510000004671412370216242023557 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function import sys import platform from numpy.testing import * import numpy.core.umath as ncu import numpy as np # TODO: branch cuts (use Pauli code) # TODO: conj 'symmetry' # TODO: FPU exceptions # At least on Windows the results of many complex functions are not conforming # to the C99 standard. See ticket 1574. # Ditto for Solaris (ticket 1642) and OS X on PowerPC. with np.errstate(all='ignore'): functions_seem_flaky = ((np.exp(complex(np.inf, 0)).imag != 0) or (np.log(complex(np.NZERO, 0)).imag != np.pi)) # TODO: replace with a check on whether platform-provided C99 funcs are used skip_complex_tests = (not sys.platform.startswith('linux') or functions_seem_flaky) def platform_skip(func): return dec.skipif(skip_complex_tests, "Numpy is using complex functions (e.g. sqrt) provided by your" "platform's C library. However, they do not seem to behave according" "to C99 -- so C99 tests are skipped.")(func) class TestCexp(object): def test_simple(self): check = check_complex_value f = np.exp yield check, f, 1, 0, np.exp(1), 0, False yield check, f, 0, 1, np.cos(1), np.sin(1), False ref = np.exp(1) * np.complex(np.cos(1), np.sin(1)) yield check, f, 1, 1, ref.real, ref.imag, False @platform_skip def test_special_values(self): # C99: Section G 6.3.1 check = check_complex_value f = np.exp # cexp(+-0 + 0i) is 1 + 0i yield check, f, np.PZERO, 0, 1, 0, False yield check, f, np.NZERO, 0, 1, 0, False # cexp(x + infi) is nan + nani for finite x and raises 'invalid' FPU # exception yield check, f, 1, np.inf, np.nan, np.nan yield check, f, -1, np.inf, np.nan, np.nan yield check, f, 0, np.inf, np.nan, np.nan # cexp(inf + 0i) is inf + 0i yield check, f, np.inf, 0, np.inf, 0 # cexp(-inf + yi) is +0 * (cos(y) + i sin(y)) for finite y ref = np.complex(np.cos(1.), np.sin(1.)) yield check, f, -np.inf, 1, np.PZERO, np.PZERO ref = np.complex(np.cos(np.pi * 0.75), np.sin(np.pi * 0.75)) yield check, f, -np.inf, 0.75 * np.pi, np.NZERO, np.PZERO # cexp(inf + yi) is +inf * (cos(y) + i sin(y)) for finite y ref = np.complex(np.cos(1.), np.sin(1.)) yield check, f, np.inf, 1, np.inf, np.inf ref = np.complex(np.cos(np.pi * 0.75), np.sin(np.pi * 0.75)) yield check, f, np.inf, 0.75 * np.pi, -np.inf, np.inf # cexp(-inf + inf i) is +-0 +- 0i (signs unspecified) def _check_ninf_inf(dummy): msgform = "cexp(-inf, inf) is (%f, %f), expected (+-0, +-0)" with np.errstate(invalid='ignore'): z = f(np.array(np.complex(-np.inf, np.inf))) if z.real != 0 or z.imag != 0: raise AssertionError(msgform %(z.real, z.imag)) yield _check_ninf_inf, None # cexp(inf + inf i) is +-inf + NaNi and raised invalid FPU ex. def _check_inf_inf(dummy): msgform = "cexp(inf, inf) is (%f, %f), expected (+-inf, nan)" with np.errstate(invalid='ignore'): z = f(np.array(np.complex(np.inf, np.inf))) if not np.isinf(z.real) or not np.isnan(z.imag): raise AssertionError(msgform % (z.real, z.imag)) yield _check_inf_inf, None # cexp(-inf + nan i) is +-0 +- 0i def _check_ninf_nan(dummy): msgform = "cexp(-inf, nan) is (%f, %f), expected (+-0, +-0)" with np.errstate(invalid='ignore'): z = f(np.array(np.complex(-np.inf, np.nan))) if z.real != 0 or z.imag != 0: raise AssertionError(msgform % (z.real, z.imag)) yield _check_ninf_nan, None # cexp(inf + nan i) is +-inf + nan def _check_inf_nan(dummy): msgform = "cexp(-inf, nan) is (%f, %f), expected (+-inf, nan)" with np.errstate(invalid='ignore'): z = f(np.array(np.complex(np.inf, np.nan))) if not np.isinf(z.real) or not np.isnan(z.imag): raise AssertionError(msgform % (z.real, z.imag)) yield _check_inf_nan, None # cexp(nan + yi) is nan + nani for y != 0 (optional: raises invalid FPU # ex) yield check, f, np.nan, 1, np.nan, np.nan yield check, f, np.nan, -1, np.nan, np.nan yield check, f, np.nan, np.inf, np.nan, np.nan yield check, f, np.nan, -np.inf, np.nan, np.nan # cexp(nan + nani) is nan + nani yield check, f, np.nan, np.nan, np.nan, np.nan @dec.knownfailureif(True, "cexp(nan + 0I) is wrong on most implementations") def test_special_values2(self): # XXX: most implementations get it wrong here (including glibc <= 2.10) # cexp(nan + 0i) is nan + 0i yield check, f, np.nan, 0, np.nan, 0 class TestClog(TestCase): def test_simple(self): x = np.array([1+0j, 1+2j]) y_r = np.log(np.abs(x)) + 1j * np.angle(x) y = np.log(x) for i in range(len(x)): assert_almost_equal(y[i], y_r[i]) @platform_skip @dec.skipif(platform.machine() == "armv5tel", "See gh-413.") def test_special_values(self): xl = [] yl = [] # From C99 std (Sec 6.3.2) # XXX: check exceptions raised # --- raise for invalid fails. # clog(-0 + i0) returns -inf + i pi and raises the 'divide-by-zero' # floating-point exception. with np.errstate(divide='raise'): x = np.array([np.NZERO], dtype=np.complex) y = np.complex(-np.inf, np.pi) self.assertRaises(FloatingPointError, np.log, x) with np.errstate(divide='ignore'): assert_almost_equal(np.log(x), y) xl.append(x) yl.append(y) # clog(+0 + i0) returns -inf + i0 and raises the 'divide-by-zero' # floating-point exception. with np.errstate(divide='raise'): x = np.array([0], dtype=np.complex) y = np.complex(-np.inf, 0) self.assertRaises(FloatingPointError, np.log, x) with np.errstate(divide='ignore'): assert_almost_equal(np.log(x), y) xl.append(x) yl.append(y) # clog(x + i inf returns +inf + i pi /2, for finite x. x = np.array([complex(1, np.inf)], dtype=np.complex) y = np.complex(np.inf, 0.5 * np.pi) assert_almost_equal(np.log(x), y) xl.append(x) yl.append(y) x = np.array([complex(-1, np.inf)], dtype=np.complex) assert_almost_equal(np.log(x), y) xl.append(x) yl.append(y) # clog(x + iNaN) returns NaN + iNaN and optionally raises the # 'invalid' floating- point exception, for finite x. with np.errstate(invalid='raise'): x = np.array([complex(1., np.nan)], dtype=np.complex) y = np.complex(np.nan, np.nan) #self.assertRaises(FloatingPointError, np.log, x) with np.errstate(invalid='ignore'): assert_almost_equal(np.log(x), y) xl.append(x) yl.append(y) with np.errstate(invalid='raise'): x = np.array([np.inf + 1j * np.nan], dtype=np.complex) #self.assertRaises(FloatingPointError, np.log, x) with np.errstate(invalid='ignore'): assert_almost_equal(np.log(x), y) xl.append(x) yl.append(y) # clog(- inf + iy) returns +inf + ipi , for finite positive-signed y. x = np.array([-np.inf + 1j], dtype=np.complex) y = np.complex(np.inf, np.pi) assert_almost_equal(np.log(x), y) xl.append(x) yl.append(y) # clog(+ inf + iy) returns +inf + i0, for finite positive-signed y. x = np.array([np.inf + 1j], dtype=np.complex) y = np.complex(np.inf, 0) assert_almost_equal(np.log(x), y) xl.append(x) yl.append(y) # clog(- inf + i inf) returns +inf + i3pi /4. x = np.array([complex(-np.inf, np.inf)], dtype=np.complex) y = np.complex(np.inf, 0.75 * np.pi) assert_almost_equal(np.log(x), y) xl.append(x) yl.append(y) # clog(+ inf + i inf) returns +inf + ipi /4. x = np.array([complex(np.inf, np.inf)], dtype=np.complex) y = np.complex(np.inf, 0.25 * np.pi) assert_almost_equal(np.log(x), y) xl.append(x) yl.append(y) # clog(+/- inf + iNaN) returns +inf + iNaN. x = np.array([complex(np.inf, np.nan)], dtype=np.complex) y = np.complex(np.inf, np.nan) assert_almost_equal(np.log(x), y) xl.append(x) yl.append(y) x = np.array([complex(-np.inf, np.nan)], dtype=np.complex) assert_almost_equal(np.log(x), y) xl.append(x) yl.append(y) # clog(NaN + iy) returns NaN + iNaN and optionally raises the # 'invalid' floating-point exception, for finite y. x = np.array([complex(np.nan, 1)], dtype=np.complex) y = np.complex(np.nan, np.nan) assert_almost_equal(np.log(x), y) xl.append(x) yl.append(y) # clog(NaN + i inf) returns +inf + iNaN. x = np.array([complex(np.nan, np.inf)], dtype=np.complex) y = np.complex(np.inf, np.nan) assert_almost_equal(np.log(x), y) xl.append(x) yl.append(y) # clog(NaN + iNaN) returns NaN + iNaN. x = np.array([complex(np.nan, np.nan)], dtype=np.complex) y = np.complex(np.nan, np.nan) assert_almost_equal(np.log(x), y) xl.append(x) yl.append(y) # clog(conj(z)) = conj(clog(z)). xa = np.array(xl, dtype=np.complex) ya = np.array(yl, dtype=np.complex) with np.errstate(divide='ignore'): for i in range(len(xa)): assert_almost_equal(np.log(np.conj(xa[i])), np.conj(np.log(xa[i]))) class TestCsqrt(object): def test_simple(self): # sqrt(1) yield check_complex_value, np.sqrt, 1, 0, 1, 0 # sqrt(1i) yield check_complex_value, np.sqrt, 0, 1, 0.5*np.sqrt(2), 0.5*np.sqrt(2), False # sqrt(-1) yield check_complex_value, np.sqrt, -1, 0, 0, 1 def test_simple_conjugate(self): ref = np.conj(np.sqrt(np.complex(1, 1))) def f(z): return np.sqrt(np.conj(z)) yield check_complex_value, f, 1, 1, ref.real, ref.imag, False #def test_branch_cut(self): # _check_branch_cut(f, -1, 0, 1, -1) @platform_skip def test_special_values(self): check = check_complex_value f = np.sqrt # C99: Sec G 6.4.2 x, y = [], [] # csqrt(+-0 + 0i) is 0 + 0i yield check, f, np.PZERO, 0, 0, 0 yield check, f, np.NZERO, 0, 0, 0 # csqrt(x + infi) is inf + infi for any x (including NaN) yield check, f, 1, np.inf, np.inf, np.inf yield check, f, -1, np.inf, np.inf, np.inf yield check, f, np.PZERO, np.inf, np.inf, np.inf yield check, f, np.NZERO, np.inf, np.inf, np.inf yield check, f, np.inf, np.inf, np.inf, np.inf yield check, f, -np.inf, np.inf, np.inf, np.inf yield check, f, -np.nan, np.inf, np.inf, np.inf # csqrt(x + nani) is nan + nani for any finite x yield check, f, 1, np.nan, np.nan, np.nan yield check, f, -1, np.nan, np.nan, np.nan yield check, f, 0, np.nan, np.nan, np.nan # csqrt(-inf + yi) is +0 + infi for any finite y > 0 yield check, f, -np.inf, 1, np.PZERO, np.inf # csqrt(inf + yi) is +inf + 0i for any finite y > 0 yield check, f, np.inf, 1, np.inf, np.PZERO # csqrt(-inf + nani) is nan +- infi (both +i infi are valid) def _check_ninf_nan(dummy): msgform = "csqrt(-inf, nan) is (%f, %f), expected (nan, +-inf)" z = np.sqrt(np.array(np.complex(-np.inf, np.nan))) #Fixme: ugly workaround for isinf bug. with np.errstate(invalid='ignore'): if not (np.isnan(z.real) and np.isinf(z.imag)): raise AssertionError(msgform % (z.real, z.imag)) yield _check_ninf_nan, None # csqrt(+inf + nani) is inf + nani yield check, f, np.inf, np.nan, np.inf, np.nan # csqrt(nan + yi) is nan + nani for any finite y (infinite handled in x # + nani) yield check, f, np.nan, 0, np.nan, np.nan yield check, f, np.nan, 1, np.nan, np.nan yield check, f, np.nan, np.nan, np.nan, np.nan # XXX: check for conj(csqrt(z)) == csqrt(conj(z)) (need to fix branch # cuts first) class TestCpow(TestCase): def setUp(self): self.olderr = np.seterr(invalid='ignore') def tearDown(self): np.seterr(**self.olderr) def test_simple(self): x = np.array([1+1j, 0+2j, 1+2j, np.inf, np.nan]) y_r = x ** 2 y = np.power(x, 2) for i in range(len(x)): assert_almost_equal(y[i], y_r[i]) def test_scalar(self): x = np.array([1, 1j, 2, 2.5+.37j, np.inf, np.nan]) y = np.array([1, 1j, -0.5+1.5j, -0.5+1.5j, 2, 3]) lx = list(range(len(x))) # Compute the values for complex type in python p_r = [complex(x[i]) ** complex(y[i]) for i in lx] # Substitute a result allowed by C99 standard p_r[4] = complex(np.inf, np.nan) # Do the same with numpy complex scalars n_r = [x[i] ** y[i] for i in lx] for i in lx: assert_almost_equal(n_r[i], p_r[i], err_msg='Loop %d\n' % i) def test_array(self): x = np.array([1, 1j, 2, 2.5+.37j, np.inf, np.nan]) y = np.array([1, 1j, -0.5+1.5j, -0.5+1.5j, 2, 3]) lx = list(range(len(x))) # Compute the values for complex type in python p_r = [complex(x[i]) ** complex(y[i]) for i in lx] # Substitute a result allowed by C99 standard p_r[4] = complex(np.inf, np.nan) # Do the same with numpy arrays n_r = x ** y for i in lx: assert_almost_equal(n_r[i], p_r[i], err_msg='Loop %d\n' % i) class TestCabs(object): def setUp(self): self.olderr = np.seterr(invalid='ignore') def tearDown(self): np.seterr(**self.olderr) def test_simple(self): x = np.array([1+1j, 0+2j, 1+2j, np.inf, np.nan]) y_r = np.array([np.sqrt(2.), 2, np.sqrt(5), np.inf, np.nan]) y = np.abs(x) for i in range(len(x)): assert_almost_equal(y[i], y_r[i]) def test_fabs(self): # Test that np.abs(x +- 0j) == np.abs(x) (as mandated by C99 for cabs) x = np.array([1+0j], dtype=np.complex) assert_array_equal(np.abs(x), np.real(x)) x = np.array([complex(1, np.NZERO)], dtype=np.complex) assert_array_equal(np.abs(x), np.real(x)) x = np.array([complex(np.inf, np.NZERO)], dtype=np.complex) assert_array_equal(np.abs(x), np.real(x)) x = np.array([complex(np.nan, np.NZERO)], dtype=np.complex) assert_array_equal(np.abs(x), np.real(x)) def test_cabs_inf_nan(self): x, y = [], [] # cabs(+-nan + nani) returns nan x.append(np.nan) y.append(np.nan) yield check_real_value, np.abs, np.nan, np.nan, np.nan x.append(np.nan) y.append(-np.nan) yield check_real_value, np.abs, -np.nan, np.nan, np.nan # According to C99 standard, if exactly one of the real/part is inf and # the other nan, then cabs should return inf x.append(np.inf) y.append(np.nan) yield check_real_value, np.abs, np.inf, np.nan, np.inf x.append(-np.inf) y.append(np.nan) yield check_real_value, np.abs, -np.inf, np.nan, np.inf # cabs(conj(z)) == conj(cabs(z)) (= cabs(z)) def f(a): return np.abs(np.conj(a)) def g(a, b): return np.abs(np.complex(a, b)) xa = np.array(x, dtype=np.complex) for i in range(len(xa)): ref = g(x[i], y[i]) yield check_real_value, f, x[i], y[i], ref class TestCarg(object): def test_simple(self): check_real_value(ncu._arg, 1, 0, 0, False) check_real_value(ncu._arg, 0, 1, 0.5*np.pi, False) check_real_value(ncu._arg, 1, 1, 0.25*np.pi, False) check_real_value(ncu._arg, np.PZERO, np.PZERO, np.PZERO) @dec.knownfailureif(True, "Complex arithmetic with signed zero is buggy on most implementation") def test_zero(self): # carg(-0 +- 0i) returns +- pi yield check_real_value, ncu._arg, np.NZERO, np.PZERO, np.pi, False yield check_real_value, ncu._arg, np.NZERO, np.NZERO, -np.pi, False # carg(+0 +- 0i) returns +- 0 yield check_real_value, ncu._arg, np.PZERO, np.PZERO, np.PZERO yield check_real_value, ncu._arg, np.PZERO, np.NZERO, np.NZERO # carg(x +- 0i) returns +- 0 for x > 0 yield check_real_value, ncu._arg, 1, np.PZERO, np.PZERO, False yield check_real_value, ncu._arg, 1, np.NZERO, np.NZERO, False # carg(x +- 0i) returns +- pi for x < 0 yield check_real_value, ncu._arg, -1, np.PZERO, np.pi, False yield check_real_value, ncu._arg, -1, np.NZERO, -np.pi, False # carg(+- 0 + yi) returns pi/2 for y > 0 yield check_real_value, ncu._arg, np.PZERO, 1, 0.5 * np.pi, False yield check_real_value, ncu._arg, np.NZERO, 1, 0.5 * np.pi, False # carg(+- 0 + yi) returns -pi/2 for y < 0 yield check_real_value, ncu._arg, np.PZERO, -1, 0.5 * np.pi, False yield check_real_value, ncu._arg, np.NZERO, -1, -0.5 * np.pi, False #def test_branch_cuts(self): # _check_branch_cut(ncu._arg, -1, 1j, -1, 1) def test_special_values(self): # carg(-np.inf +- yi) returns +-pi for finite y > 0 yield check_real_value, ncu._arg, -np.inf, 1, np.pi, False yield check_real_value, ncu._arg, -np.inf, -1, -np.pi, False # carg(np.inf +- yi) returns +-0 for finite y > 0 yield check_real_value, ncu._arg, np.inf, 1, np.PZERO, False yield check_real_value, ncu._arg, np.inf, -1, np.NZERO, False # carg(x +- np.infi) returns +-pi/2 for finite x yield check_real_value, ncu._arg, 1, np.inf, 0.5 * np.pi, False yield check_real_value, ncu._arg, 1, -np.inf, -0.5 * np.pi, False # carg(-np.inf +- np.infi) returns +-3pi/4 yield check_real_value, ncu._arg, -np.inf, np.inf, 0.75 * np.pi, False yield check_real_value, ncu._arg, -np.inf, -np.inf, -0.75 * np.pi, False # carg(np.inf +- np.infi) returns +-pi/4 yield check_real_value, ncu._arg, np.inf, np.inf, 0.25 * np.pi, False yield check_real_value, ncu._arg, np.inf, -np.inf, -0.25 * np.pi, False # carg(x + yi) returns np.nan if x or y is nan yield check_real_value, ncu._arg, np.nan, 0, np.nan, False yield check_real_value, ncu._arg, 0, np.nan, np.nan, False yield check_real_value, ncu._arg, np.nan, np.inf, np.nan, False yield check_real_value, ncu._arg, np.inf, np.nan, np.nan, False def check_real_value(f, x1, y1, x, exact=True): z1 = np.array([complex(x1, y1)]) if exact: assert_equal(f(z1), x) else: assert_almost_equal(f(z1), x) def check_complex_value(f, x1, y1, x2, y2, exact=True): z1 = np.array([complex(x1, y1)]) z2 = np.complex(x2, y2) with np.errstate(invalid='ignore'): if exact: assert_equal(f(z1), z2) else: assert_almost_equal(f(z1), z2) if __name__ == "__main__": run_module_suite() numpy-1.8.2/numpy/core/tests/test_regression.py0000664000175100017510000021211112370216243023055 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function import pickle import sys import platform import gc import copy import warnings import tempfile from os import path from io import BytesIO import numpy as np from numpy.testing import ( run_module_suite, TestCase, assert_, assert_equal, assert_almost_equal, assert_array_equal, assert_array_almost_equal, assert_raises, assert_warns, dec ) from numpy.testing.utils import _assert_valid_refcount from numpy.compat import asbytes, asunicode, asbytes_nested, long, sixu rlevel = 1 class TestRegression(TestCase): def test_invalid_round(self,level=rlevel): """Ticket #3""" v = 4.7599999999999998 assert_array_equal(np.array([v]), np.array(v)) def test_mem_empty(self,level=rlevel): """Ticket #7""" np.empty((1,), dtype=[('x', np.int64)]) def test_pickle_transposed(self,level=rlevel): """Ticket #16""" a = np.transpose(np.array([[2, 9], [7, 0], [3, 8]])) f = BytesIO() pickle.dump(a, f) f.seek(0) b = pickle.load(f) f.close() assert_array_equal(a, b) def test_typeNA(self,level=rlevel): """Ticket #31""" assert_equal(np.typeNA[np.int64], 'Int64') assert_equal(np.typeNA[np.uint64], 'UInt64') def test_dtype_names(self,level=rlevel): """Ticket #35""" dt = np.dtype([(('name', 'label'), np.int32, 3)]) def test_reduce(self,level=rlevel): """Ticket #40""" assert_almost_equal(np.add.reduce([1., .5], dtype=None), 1.5) def test_zeros_order(self,level=rlevel): """Ticket #43""" np.zeros([3], int, 'C') np.zeros([3], order='C') np.zeros([3], int, order='C') def test_asarray_with_order(self,level=rlevel): """Check that nothing is done when order='F' and array C/F-contiguous""" a = np.ones(2) assert_(a is np.asarray(a, order='F')) def test_ravel_with_order(self,level=rlevel): """Check that ravel works when order='F' and array C/F-contiguous""" a = np.ones(2) assert_(not a.ravel('F').flags.owndata) def test_sort_bigendian(self,level=rlevel): """Ticket #47""" a = np.linspace(0, 10, 11) c = a.astype(np.dtype('= 3) or (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): """Ticket #99""" i_width = np.int_(0).nbytes*2 - 1 np.intp('0x' + 'f'*i_width, 16) self.assertRaises(OverflowError, np.intp, '0x' + 'f'*(i_width+1), 16) self.assertRaises(ValueError, np.intp, '0x1', 32) assert_equal(255, np.intp('0xFF', 16)) assert_equal(1024, np.intp(1024)) def test_endian_bool_indexing(self,level=rlevel): """Ticket #105""" a = np.arange(10., dtype='>f8') b = np.arange(10., dtype='2) & (a<6)) xb = np.where((b>2) & (b<6)) ya = ((a>2) & (a<6)) yb = ((b>2) & (b<6)) assert_array_almost_equal(xa, ya.nonzero()) assert_array_almost_equal(xb, yb.nonzero()) assert_(np.all(a[ya] > 0.5)) assert_(np.all(b[yb] > 0.5)) def test_endian_where(self,level=rlevel): """GitHuB issue #369""" net = np.zeros(3, dtype='>f4') net[1] = 0.00458849 net[2] = 0.605202 max_net = net.max() test = np.where(net <= 0., max_net, net) correct = np.array([ 0.60520202, 0.00458849, 0.60520202]) assert_array_almost_equal(test, correct) def test_endian_recarray(self,level=rlevel): """Ticket #2185""" dt = np.dtype([ ('head', '>u4'), ('data', '>u4', 2), ]) buf = np.recarray(1, dtype=dt) buf[0]['head'] = 1 buf[0]['data'][:] = [1, 1] h = buf[0]['head'] d = buf[0]['data'][0] buf[0]['head'] = h buf[0]['data'][0] = d assert_(buf[0]['head'] == 1) def test_mem_dot(self,level=rlevel): """Ticket #106""" x = np.random.randn(0, 1) y = np.random.randn(10, 1) # Dummy array to detect bad memory access: _z = np.ones(10) _dummy = np.empty((0, 10)) z = np.lib.stride_tricks.as_strided(_z, _dummy.shape, _dummy.strides) np.dot(x, np.transpose(y), out=z) assert_equal(_z, np.ones(10)) # Do the same for the built-in dot: np.core.multiarray.dot(x, np.transpose(y), out=z) assert_equal(_z, np.ones(10)) def test_arange_endian(self,level=rlevel): """Ticket #111""" ref = np.arange(10) x = np.arange(10, dtype=' 8: # a = np.exp(np.array([1000],dtype=np.longfloat)) # assert_(str(a)[1:9] == str(a[0])[:8]) def test_argmax(self,level=rlevel): """Ticket #119""" a = np.random.normal(0, 1, (4, 5, 6, 7, 8)) for i in range(a.ndim): aargmax = a.argmax(i) def test_mem_divmod(self,level=rlevel): """Ticket #126""" for i in range(10): divmod(np.array([i])[0], 10) def test_hstack_invalid_dims(self,level=rlevel): """Ticket #128""" x = np.arange(9).reshape((3, 3)) y = np.array([0, 0, 0]) self.assertRaises(ValueError, np.hstack, (x, y)) def test_squeeze_type(self,level=rlevel): """Ticket #133""" a = np.array([3]) b = np.array(3) assert_(type(a.squeeze()) is np.ndarray) assert_(type(b.squeeze()) is np.ndarray) def test_add_identity(self,level=rlevel): """Ticket #143""" assert_equal(0, np.add.identity) def test_numpy_float_python_long_addition(self): # Check that numpy float and python longs can be added correctly. a = np.float_(23.) + 2**135 assert_equal(a, 23. + 2**135) def test_binary_repr_0(self,level=rlevel): """Ticket #151""" assert_equal('0', np.binary_repr(0)) def test_rec_iterate(self,level=rlevel): """Ticket #160""" descr = np.dtype([('i', int), ('f', float), ('s', '|S3')]) x = np.rec.array([(1, 1.1, '1.0'), (2, 2.2, '2.0')], dtype=descr) x[0].tolist() [i for i in x[0]] def test_unicode_string_comparison(self,level=rlevel): """Ticket #190""" a = np.array('hello', np.unicode_) b = np.array('world') a == b def test_tostring_FORTRANORDER_discontiguous(self,level=rlevel): """Fix in r2836""" # Create discontiguous Fortran-ordered array x = np.array(np.random.rand(3, 3), order='F')[:, :2] assert_array_almost_equal(x.ravel(), np.fromstring(x.tostring())) def test_flat_assignment(self,level=rlevel): """Correct behaviour of ticket #194""" x = np.empty((3, 1)) x.flat = np.arange(3) assert_array_almost_equal(x, [[0], [1], [2]]) x.flat = np.arange(3, dtype=float) assert_array_almost_equal(x, [[0], [1], [2]]) def test_broadcast_flat_assignment(self,level=rlevel): """Ticket #194""" x = np.empty((3, 1)) def bfa(): x[:] = np.arange(3) def bfb(): x[:] = np.arange(3, dtype=float) self.assertRaises(ValueError, bfa) self.assertRaises(ValueError, bfb) def test_nonarray_assignment(self): # See also Issue gh-2870, test for nonarray assignment # and equivalent unsafe casted array assignment a = np.arange(10) b = np.ones(10, dtype=bool) r = np.arange(10) def assign(a, b, c): a[b] = c assert_raises(ValueError, assign, a, b, np.nan) a[b] = np.array(np.nan) # but not this. assert_raises(ValueError, assign, a, r, np.nan) a[r] = np.array(np.nan) def test_unpickle_dtype_with_object(self,level=rlevel): """Implemented in r2840""" dt = np.dtype([('x', int), ('y', np.object_), ('z', 'O')]) f = BytesIO() pickle.dump(dt, f) f.seek(0) dt_ = pickle.load(f) f.close() assert_equal(dt, dt_) def test_mem_array_creation_invalid_specification(self,level=rlevel): """Ticket #196""" dt = np.dtype([('x', int), ('y', np.object_)]) # Wrong way self.assertRaises(ValueError, np.array, [1, 'object'], dt) # Correct way np.array([(1, 'object')], dt) def test_recarray_single_element(self,level=rlevel): """Ticket #202""" a = np.array([1, 2, 3], dtype=np.int32) b = a.copy() r = np.rec.array(a, shape=1, formats=['3i4'], names=['d']) assert_array_equal(a, b) assert_equal(a, r[0][0]) def test_zero_sized_array_indexing(self,level=rlevel): """Ticket #205""" tmp = np.array([]) def index_tmp(): tmp[np.array(10)] self.assertRaises(IndexError, index_tmp) def test_chararray_rstrip(self,level=rlevel): """Ticket #222""" x = np.chararray((1,), 5) x[0] = asbytes('a ') x = x.rstrip() assert_equal(x[0], asbytes('a')) def test_object_array_shape(self,level=rlevel): """Ticket #239""" assert_equal(np.array([[1, 2], 3, 4], dtype=object).shape, (3,)) assert_equal(np.array([[1, 2], [3, 4]], dtype=object).shape, (2, 2)) assert_equal(np.array([(1, 2), (3, 4)], dtype=object).shape, (2, 2)) assert_equal(np.array([], dtype=object).shape, (0,)) assert_equal(np.array([[], [], []], dtype=object).shape, (3, 0)) assert_equal(np.array([[3, 4], [5, 6], None], dtype=object).shape, (3,)) def test_mem_around(self,level=rlevel): """Ticket #243""" x = np.zeros((1,)) y = [0] decimal = 6 np.around(abs(x-y), decimal) <= 10.0**(-decimal) def test_character_array_strip(self,level=rlevel): """Ticket #246""" x = np.char.array(("x", "x ", "x ")) for c in x: assert_equal(c, "x") def test_lexsort(self,level=rlevel): """Lexsort memory error""" v = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) assert_equal(np.lexsort(v), 0) def test_lexsort_invalid_sequence(self): # Issue gh-4123 class BuggySequence(object): def __len__(self): return 4 def __getitem__(self, key): raise KeyError assert_raises(KeyError, np.lexsort, BuggySequence()) def test_pickle_dtype(self,level=rlevel): """Ticket #251""" pickle.dumps(np.float) def test_swap_real(self, level=rlevel): """Ticket #265""" assert_equal(np.arange(4, dtype='>c8').imag.max(), 0.0) assert_equal(np.arange(4, dtype=' 1 and x['two'] > 2) def test_method_args(self, level=rlevel): # Make sure methods and functions have same default axis # keyword and arguments funcs1= ['argmax', 'argmin', 'sum', ('product', 'prod'), ('sometrue', 'any'), ('alltrue', 'all'), 'cumsum', ('cumproduct', 'cumprod'), 'ptp', 'cumprod', 'prod', 'std', 'var', 'mean', 'round', 'min', 'max', 'argsort', 'sort'] funcs2 = ['compress', 'take', 'repeat'] for func in funcs1: arr = np.random.rand(8, 7) arr2 = arr.copy() if isinstance(func, tuple): func_meth = func[1] func = func[0] else: func_meth = func res1 = getattr(arr, func_meth)() res2 = getattr(np, func)(arr2) if res1 is None: assert_(abs(arr-res2).max() < 1e-8, func) else: assert_(abs(res1-res2).max() < 1e-8, func) for func in funcs2: arr1 = np.random.rand(8, 7) arr2 = np.random.rand(8, 7) res1 = None if func == 'compress': arr1 = arr1.ravel() res1 = getattr(arr2, func)(arr1) else: arr2 = (15*arr2).astype(int).ravel() if res1 is None: res1 = getattr(arr1, func)(arr2) res2 = getattr(np, func)(arr1, arr2) assert_(abs(res1-res2).max() < 1e-8, func) def test_mem_lexsort_strings(self, level=rlevel): """Ticket #298""" lst = ['abc', 'cde', 'fgh'] np.lexsort((lst,)) def test_fancy_index(self, level=rlevel): """Ticket #302""" x = np.array([1, 2])[np.array([0])] assert_equal(x.shape, (1,)) def test_recarray_copy(self, level=rlevel): """Ticket #312""" dt = [('x', np.int16), ('y', np.float64)] ra = np.array([(1, 2.3)], dtype=dt) rb = np.rec.array(ra, dtype=dt) rb['x'] = 2. assert_(ra['x'] != rb['x']) def test_rec_fromarray(self, level=rlevel): """Ticket #322""" x1 = np.array([[1, 2], [3, 4], [5, 6]]) x2 = np.array(['a', 'dd', 'xyz']) x3 = np.array([1.1, 2, 3]) np.rec.fromarrays([x1, x2, x3], formats="(2,)i4,a3,f8") def test_object_array_assign(self, level=rlevel): x = np.empty((2, 2), object) x.flat[2] = (1, 2, 3) assert_equal(x.flat[2], (1, 2, 3)) def test_ndmin_float64(self, level=rlevel): """Ticket #324""" x = np.array([1, 2, 3], dtype=np.float64) assert_equal(np.array(x, dtype=np.float32, ndmin=2).ndim, 2) assert_equal(np.array(x, dtype=np.float64, ndmin=2).ndim, 2) def test_ndmin_order(self, level=rlevel): """Issue #465 and related checks""" assert_(np.array([1, 2], order='C', ndmin=3).flags.c_contiguous) assert_(np.array([1, 2], order='F', ndmin=3).flags.f_contiguous) assert_(np.array(np.ones((2, 2), order='F'), ndmin=3).flags.f_contiguous) assert_(np.array(np.ones((2, 2), order='C'), ndmin=3).flags.c_contiguous) def test_mem_axis_minimization(self, level=rlevel): """Ticket #327""" data = np.arange(5) data = np.add.outer(data, data) def test_mem_float_imag(self, level=rlevel): """Ticket #330""" np.float64(1.0).imag def test_dtype_tuple(self, level=rlevel): """Ticket #334""" assert_(np.dtype('i4') == np.dtype(('i4', ()))) def test_dtype_posttuple(self, level=rlevel): """Ticket #335""" np.dtype([('col1', '()i4')]) def test_numeric_carray_compare(self, level=rlevel): """Ticket #341""" assert_equal(np.array(['X'], 'c'), asbytes('X')) def test_string_array_size(self, level=rlevel): """Ticket #342""" self.assertRaises(ValueError, np.array, [['X'], ['X', 'X', 'X']], '|S1') def test_dtype_repr(self, level=rlevel): """Ticket #344""" dt1=np.dtype(('uint32', 2)) dt2=np.dtype(('uint32', (2,))) assert_equal(dt1.__repr__(), dt2.__repr__()) def test_reshape_order(self, level=rlevel): """Make sure reshape order works.""" a = np.arange(6).reshape(2, 3, order='F') assert_equal(a, [[0, 2, 4], [1, 3, 5]]) a = np.array([[1, 2], [3, 4], [5, 6], [7, 8]]) b = a[:, 1] assert_equal(b.reshape(2, 2, order='F'), [[2, 6], [4, 8]]) def test_reshape_zero_strides(self, level=rlevel): """Issue #380, test reshaping of zero strided arrays""" a = np.ones(1) a = np.lib.stride_tricks.as_strided(a, shape=(5,), strides=(0,)) assert_(a.reshape(5, 1).strides[0] == 0) def test_reshape_zero_size(self, level=rlevel): """Github Issue #2700, setting shape failed for 0-sized arrays""" a = np.ones((0, 2)) a.shape = (-1, 2) # Cannot test if NPY_RELAXED_STRIDES_CHECKING changes the strides. # 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 a = np.zeros(12, dtype=np.int32)[::2] # not contiguous strides_c = (16, 8, 8, 8) strides_f = (8, 24, 48, 48) assert_equal(a.reshape(3, 2, 1, 1).strides, strides_c) assert_equal(a.reshape(3, 2, 1, 1, order='F').strides, strides_f) assert_equal(np.array(0, dtype=np.int32).reshape(1, 1).strides, (4, 4)) def test_repeat_discont(self, level=rlevel): """Ticket #352""" a = np.arange(12).reshape(4, 3)[:, 2] assert_equal(a.repeat(3), [2, 2, 2, 5, 5, 5, 8, 8, 8, 11, 11, 11]) def test_array_index(self, level=rlevel): """Make sure optimization is not called in this case.""" a = np.array([1, 2, 3]) a2 = np.array([[1, 2, 3]]) assert_equal(a[np.where(a==3)], a2[np.where(a2==3)]) def test_object_argmax(self, level=rlevel): a = np.array([1, 2, 3], dtype=object) assert_(a.argmax() == 2) def test_recarray_fields(self, level=rlevel): """Ticket #372""" dt0 = np.dtype([('f0', 'i4'), ('f1', 'i4')]) dt1 = np.dtype([('f0', 'i8'), ('f1', 'i8')]) for a in [np.array([(1, 2), (3, 4)], "i4,i4"), np.rec.array([(1, 2), (3, 4)], "i4,i4"), np.rec.array([(1, 2), (3, 4)]), np.rec.fromarrays([(1, 2), (3, 4)], "i4,i4"), np.rec.fromarrays([(1, 2), (3, 4)])]: assert_(a.dtype in [dt0, dt1]) def test_random_shuffle(self, level=rlevel): """Ticket #374""" a = np.arange(5).reshape((5, 1)) b = a.copy() np.random.shuffle(b) assert_equal(np.sort(b, axis=0), a) def test_refcount_vdot(self, level=rlevel): """Changeset #3443""" _assert_valid_refcount(np.vdot) def test_startswith(self, level=rlevel): ca = np.char.array(['Hi', 'There']) assert_equal(ca.startswith('H'), [True, False]) def test_noncommutative_reduce_accumulate(self, level=rlevel): """Ticket #413""" tosubtract = np.arange(5) todivide = np.array([2.0, 0.5, 0.25]) assert_equal(np.subtract.reduce(tosubtract), -10) assert_equal(np.divide.reduce(todivide), 16.0) assert_array_equal(np.subtract.accumulate(tosubtract), np.array([0, -1, -3, -6, -10])) assert_array_equal(np.divide.accumulate(todivide), np.array([2., 4., 16.])) def test_convolve_empty(self, level=rlevel): """Convolve should raise an error for empty input array.""" self.assertRaises(ValueError, np.convolve, [], [1]) self.assertRaises(ValueError, np.convolve, [1], []) def test_multidim_byteswap(self, level=rlevel): """Ticket #449""" r=np.array([(1, (0, 1, 2))], dtype="i2,3i2") assert_array_equal(r.byteswap(), np.array([(256, (0, 256, 512))], r.dtype)) def test_string_NULL(self, level=rlevel): """Changeset 3557""" assert_equal(np.array("a\x00\x0b\x0c\x00").item(), 'a\x00\x0b\x0c') def test_junk_in_string_fields_of_recarray(self, level=rlevel): """Ticket #483""" r = np.array([[asbytes('abc')]], dtype=[('var1', '|S20')]) assert_(asbytes(r['var1'][0][0]) == asbytes('abc')) def test_take_output(self, level=rlevel): """Ensure that 'take' honours output parameter.""" x = np.arange(12).reshape((3, 4)) a = np.take(x, [0, 2], axis=1) b = np.zeros_like(a) np.take(x, [0, 2], axis=1, out=b) assert_array_equal(a, b) def test_take_object_fail(self): # Issue gh-3001 d = 123. a = np.array([d, 1], dtype=object) ref_d = sys.getrefcount(d) try: a.take([0, 100]) except IndexError: pass assert_(ref_d == sys.getrefcount(d)) def test_array_str_64bit(self, level=rlevel): """Ticket #501""" s = np.array([1, np.nan], dtype=np.float64) with np.errstate(all='raise'): sstr = np.array_str(s) def test_frompyfunc_endian(self, level=rlevel): """Ticket #503""" from math import radians uradians = np.frompyfunc(radians, 1, 1) big_endian = np.array([83.4, 83.5], dtype='>f8') little_endian = np.array([83.4, 83.5], dtype=' object # casting succeeds def rs(): x = np.ones([484, 286]) y = np.zeros([484, 286]) x |= y self.assertRaises(TypeError, rs) def test_unicode_scalar(self, level=rlevel): """Ticket #600""" x = np.array(["DROND", "DROND1"], dtype="U6") el = x[1] new = pickle.loads(pickle.dumps(el)) assert_equal(new, el) def test_arange_non_native_dtype(self, level=rlevel): """Ticket #616""" for T in ('>f4', '0)]=v self.assertRaises(ValueError, ia, x, s, np.zeros(9, dtype=float)) self.assertRaises(ValueError, ia, x, s, np.zeros(11, dtype=float)) def test_mem_scalar_indexing(self, level=rlevel): """Ticket #603""" x = np.array([0], dtype=float) index = np.array(0, dtype=np.int32) x[index] def test_binary_repr_0_width(self, level=rlevel): assert_equal(np.binary_repr(0, width=3), '000') def test_fromstring(self, level=rlevel): assert_equal(np.fromstring("12:09:09", dtype=int, sep=":"), [12, 9, 9]) def test_searchsorted_variable_length(self, level=rlevel): x = np.array(['a', 'aa', 'b']) y = np.array(['d', 'e']) assert_equal(x.searchsorted(y), [3, 3]) def test_string_argsort_with_zeros(self, level=rlevel): """Check argsort for strings containing zeros.""" x = np.fromstring("\x00\x02\x00\x01", dtype="|S2") assert_array_equal(x.argsort(kind='m'), np.array([1, 0])) assert_array_equal(x.argsort(kind='q'), np.array([1, 0])) def test_string_sort_with_zeros(self, level=rlevel): """Check sort for strings containing zeros.""" x = np.fromstring("\x00\x02\x00\x01", dtype="|S2") y = np.fromstring("\x00\x01\x00\x02", dtype="|S2") assert_array_equal(np.sort(x, kind="q"), y) def test_copy_detection_zero_dim(self, level=rlevel): """Ticket #658""" np.indices((0, 3, 4)).T.reshape(-1, 3) def test_flat_byteorder(self, level=rlevel): """Ticket #657""" x = np.arange(10) assert_array_equal(x.astype('>i4'), x.astype('i4').flat[:], x.astype('i4')): x = np.array([-1, 0, 1], dtype=dt) assert_equal(x.flat[0].dtype, x[0].dtype) def test_copy_detection_corner_case(self, level=rlevel): """Ticket #658""" np.indices((0, 3, 4)).T.reshape(-1, 3) # Cannot test if NPY_RELAXED_STRIDES_CHECKING changes the strides. # With NPY_RELAXED_STRIDES_CHECKING the test becomes superfluous, # 0-sized reshape itself is tested elsewhere. @dec.skipif(np.ones(1).strides[0] == np.iinfo(np.intp).max) def test_copy_detection_corner_case2(self, level=rlevel): """Ticket #771: strides are not set correctly when reshaping 0-sized arrays""" b = np.indices((0, 3, 4)).T.reshape(-1, 3) assert_equal(b.strides, (3 * b.itemsize, b.itemsize)) def test_object_array_refcounting(self, level=rlevel): """Ticket #633""" if not hasattr(sys, 'getrefcount'): return # NB. this is probably CPython-specific cnt = sys.getrefcount a = object() b = object() c = object() cnt0_a = cnt(a) cnt0_b = cnt(b) cnt0_c = cnt(c) # -- 0d -> 1d broadcasted slice assignment arr = np.zeros(5, dtype=np.object_) arr[:] = a assert_equal(cnt(a), cnt0_a + 5) arr[:] = b assert_equal(cnt(a), cnt0_a) assert_equal(cnt(b), cnt0_b + 5) arr[:2] = c assert_equal(cnt(b), cnt0_b + 3) assert_equal(cnt(c), cnt0_c + 2) del arr # -- 1d -> 2d broadcasted slice assignment arr = np.zeros((5, 2), dtype=np.object_) arr0 = np.zeros(2, dtype=np.object_) arr0[0] = a assert_(cnt(a) == cnt0_a + 1) arr0[1] = b assert_(cnt(b) == cnt0_b + 1) arr[:,:] = arr0 assert_(cnt(a) == cnt0_a + 6) assert_(cnt(b) == cnt0_b + 6) arr[:, 0] = None assert_(cnt(a) == cnt0_a + 1) del arr, arr0 # -- 2d copying + flattening arr = np.zeros((5, 2), dtype=np.object_) arr[:, 0] = a arr[:, 1] = b assert_(cnt(a) == cnt0_a + 5) assert_(cnt(b) == cnt0_b + 5) arr2 = arr.copy() assert_(cnt(a) == cnt0_a + 10) assert_(cnt(b) == cnt0_b + 10) arr2 = arr[:, 0].copy() assert_(cnt(a) == cnt0_a + 10) assert_(cnt(b) == cnt0_b + 5) arr2 = arr.flatten() assert_(cnt(a) == cnt0_a + 10) assert_(cnt(b) == cnt0_b + 10) del arr, arr2 # -- concatenate, repeat, take, choose arr1 = np.zeros((5, 1), dtype=np.object_) arr2 = np.zeros((5, 1), dtype=np.object_) arr1[...] = a arr2[...] = b assert_(cnt(a) == cnt0_a + 5) assert_(cnt(b) == cnt0_b + 5) arr3 = np.concatenate((arr1, arr2)) assert_(cnt(a) == cnt0_a + 5 + 5) assert_(cnt(b) == cnt0_b + 5 + 5) arr3 = arr1.repeat(3, axis=0) assert_(cnt(a) == cnt0_a + 5 + 3*5) arr3 = arr1.take([1, 2, 3], axis=0) assert_(cnt(a) == cnt0_a + 5 + 3) x = np.array([[0], [1], [0], [1], [1]], int) arr3 = x.choose(arr1, arr2) assert_(cnt(a) == cnt0_a + 5 + 2) assert_(cnt(b) == cnt0_b + 5 + 3) def test_mem_custom_float_to_array(self, level=rlevel): """Ticket 702""" class MyFloat(object): def __float__(self): return 1.0 tmp = np.atleast_1d([MyFloat()]) tmp2 = tmp.astype(float) def test_object_array_refcount_self_assign(self, level=rlevel): """Ticket #711""" class VictimObject(object): deleted = False def __del__(self): self.deleted = True d = VictimObject() arr = np.zeros(5, dtype=np.object_) arr[:] = d del d arr[:] = arr # refcount of 'd' might hit zero here assert_(not arr[0].deleted) arr[:] = arr # trying to induce a segfault by doing it again... assert_(not arr[0].deleted) def test_mem_fromiter_invalid_dtype_string(self, level=rlevel): x = [1, 2, 3] self.assertRaises(ValueError, np.fromiter, [xi for xi in x], dtype='S') def test_reduce_big_object_array(self, level=rlevel): """Ticket #713""" oldsize = np.setbufsize(10*16) a = np.array([None]*161, object) assert_(not np.any(a)) np.setbufsize(oldsize) def test_mem_0d_array_index(self, level=rlevel): """Ticket #714""" np.zeros(10)[np.array(0)] def test_floats_from_string(self, level=rlevel): """Ticket #640, floats from string""" fsingle = np.single('1.234') fdouble = np.double('1.234') flongdouble = np.longdouble('1.234') assert_almost_equal(fsingle, 1.234) assert_almost_equal(fdouble, 1.234) assert_almost_equal(flongdouble, 1.234) def test_nonnative_endian_fill(self, level=rlevel): """ Non-native endian arrays were incorrectly filled with scalars before r5034. """ if sys.byteorder == 'little': dtype = np.dtype('>i4') else: dtype = np.dtype('= 3: f = open(filename, 'rb') xp = pickle.load(f, encoding='latin1') f.close() else: f = open(filename) xp = pickle.load(f) f.close() xpd = xp.astype(np.float64) assert_((xp.__array_interface__['data'][0] != xpd.__array_interface__['data'][0])) def test_compress_small_type(self, level=rlevel): """Ticket #789, changeset 5217. """ # compress with out argument segfaulted if cannot cast safely import numpy as np a = np.array([[1, 2], [3, 4]]) 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 "\ "successfully") except TypeError: pass def test_attributes(self, level=rlevel): """Ticket #791 """ class TestArray(np.ndarray): def __new__(cls, data, info): result = np.array(data) result = result.view(cls) result.info = info return result def __array_finalize__(self, obj): self.info = getattr(obj, 'info', '') dat = TestArray([[1, 2, 3, 4], [5, 6, 7, 8]], 'jubba') assert_(dat.info == 'jubba') dat.resize((4, 2)) assert_(dat.info == 'jubba') dat.sort() assert_(dat.info == 'jubba') dat.fill(2) assert_(dat.info == 'jubba') dat.put([2, 3, 4], [6, 3, 4]) assert_(dat.info == 'jubba') dat.setfield(4, np.int32, 0) assert_(dat.info == 'jubba') dat.setflags() assert_(dat.info == 'jubba') assert_(dat.all(1).info == 'jubba') assert_(dat.any(1).info == 'jubba') assert_(dat.argmax(1).info == 'jubba') assert_(dat.argmin(1).info == 'jubba') assert_(dat.argsort(1).info == 'jubba') assert_(dat.astype(TestArray).info == 'jubba') assert_(dat.byteswap().info == 'jubba') assert_(dat.clip(2, 7).info == 'jubba') assert_(dat.compress([0, 1, 1]).info == 'jubba') assert_(dat.conj().info == 'jubba') assert_(dat.conjugate().info == 'jubba') assert_(dat.copy().info == 'jubba') dat2 = TestArray([2, 3, 1, 0], 'jubba') choices = [[0, 1, 2, 3], [10, 11, 12, 13], [20, 21, 22, 23], [30, 31, 32, 33]] assert_(dat2.choose(choices).info == 'jubba') assert_(dat.cumprod(1).info == 'jubba') assert_(dat.cumsum(1).info == 'jubba') assert_(dat.diagonal().info == 'jubba') assert_(dat.flatten().info == 'jubba') assert_(dat.getfield(np.int32, 0).info == 'jubba') assert_(dat.imag.info == 'jubba') assert_(dat.max(1).info == 'jubba') assert_(dat.mean(1).info == 'jubba') assert_(dat.min(1).info == 'jubba') assert_(dat.newbyteorder().info == 'jubba') assert_(dat.nonzero()[0].info == 'jubba') assert_(dat.nonzero()[1].info == 'jubba') assert_(dat.prod(1).info == 'jubba') assert_(dat.ptp(1).info == 'jubba') assert_(dat.ravel().info == 'jubba') assert_(dat.real.info == 'jubba') assert_(dat.repeat(2).info == 'jubba') assert_(dat.reshape((2, 4)).info == 'jubba') assert_(dat.round().info == 'jubba') assert_(dat.squeeze().info == 'jubba') assert_(dat.std(1).info == 'jubba') assert_(dat.sum(1).info == 'jubba') assert_(dat.swapaxes(0, 1).info == 'jubba') assert_(dat.take([2, 3, 5]).info == 'jubba') assert_(dat.transpose().info == 'jubba') assert_(dat.T.info == 'jubba') assert_(dat.var(1).info == 'jubba') assert_(dat.view(TestArray).info == 'jubba') def test_recarray_tolist(self, level=rlevel): """Ticket #793, changeset r5215 """ # Comparisons fail for NaN, so we can't use random memory # for the test. buf = np.zeros(40, dtype=np.int8) a = np.recarray(2, formats="i4,f8,f8", names="id,x,y", buf=buf) b = a.tolist() assert_( a[0].tolist() == b[0]) assert_( a[1].tolist() == b[1]) def test_nonscalar_item_method(self): # Make sure that .item() fails graciously when it should a = np.arange(5) assert_raises(ValueError, a.item) def test_char_array_creation(self, level=rlevel): a = np.array('123', dtype='c') b = np.array(asbytes_nested(['1', '2', '3'])) assert_equal(a, b) def test_unaligned_unicode_access(self, level=rlevel) : """Ticket #825""" for i in range(1, 9) : msg = 'unicode offset: %d chars'%i t = np.dtype([('a', 'S%d'%i), ('b', 'U2')]) x = np.array([(asbytes('a'), sixu('b'))], dtype=t) if sys.version_info[0] >= 3: assert_equal(str(x), "[(b'a', 'b')]", err_msg=msg) else: assert_equal(str(x), "[('a', u'b')]", err_msg=msg) def test_sign_for_complex_nan(self, level=rlevel): """Ticket 794.""" with np.errstate(invalid='ignore'): C = np.array([-np.inf, -2+1j, 0, 2-1j, np.inf, np.nan]) have = np.sign(C) want = np.array([-1+0j, -1+0j, 0+0j, 1+0j, 1+0j, np.nan]) assert_equal(have, want) def test_for_equal_names(self, level=rlevel): """Ticket #674""" dt = np.dtype([('foo', float), ('bar', float)]) a = np.zeros(10, dt) b = list(a.dtype.names) b[0] = "notfoo" a.dtype.names = b assert_(a.dtype.names[0] == "notfoo") assert_(a.dtype.names[1] == "bar") def test_for_object_scalar_creation(self, level=rlevel): """Ticket #816""" a = np.object_() b = np.object_(3) b2 = np.object_(3.0) c = np.object_([4, 5]) d = np.object_([None, {}, []]) assert_(a is None) assert_(type(b) is int) assert_(type(b2) is float) assert_(type(c) is np.ndarray) assert_(c.dtype == object) assert_(d.dtype == object) def test_array_resize_method_system_error(self): """Ticket #840 - order should be an invalid keyword.""" x = np.array([[0, 1], [2, 3]]) self.assertRaises(TypeError, x.resize, (2, 2), order='C') def test_for_zero_length_in_choose(self, level=rlevel): "Ticket #882" a = np.array(1) self.assertRaises(ValueError, lambda x: x.choose([]), a) def test_array_ndmin_overflow(self): "Ticket #947." self.assertRaises(ValueError, lambda: np.array([1], ndmin=33)) def test_errobj_reference_leak(self, level=rlevel): """Ticket #955""" with np.errstate(all="ignore"): z = int(0) p = np.int32(-1) gc.collect() n_before = len(gc.get_objects()) z**p # this shouldn't leak a reference to errobj gc.collect() n_after = len(gc.get_objects()) assert_(n_before >= n_after, (n_before, n_after)) def test_void_scalar_with_titles(self, level=rlevel): """No ticket""" data = [('john', 4), ('mary', 5)] dtype1 = [(('source:yy', 'name'), 'O'), (('source:xx', 'id'), int)] arr = np.array(data, dtype=dtype1) assert_(arr[0][0] == 'john') assert_(arr[0][1] == 4) def test_void_scalar_constructor(self): #Issue #1550 #Create test string data, construct void scalar from data and assert #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()) assert_(test_string_void_scalar.view(test_string.dtype) == test_string) #Create record scalar, construct from data and assert that #reconstructed scalar is correct. test_record = np.ones((), "i,i") test_record_void_scalar = np.core.multiarray.scalar( test_record.dtype, test_record.tostring()) assert_(test_record_void_scalar == test_record) #Test pickle and unpickle of void and record scalars assert_(pickle.loads(pickle.dumps(test_string)) == test_string) assert_(pickle.loads(pickle.dumps(test_record)) == test_record) def test_blasdot_uninitialized_memory(self): """Ticket #950""" for m in [0, 1, 2]: for n in [0, 1, 2]: for k in range(3): # Try to ensure that x->data contains non-zero floats x = np.array([123456789e199], dtype=np.float64) x.resize((m, 0)) y = np.array([123456789e199], dtype=np.float64) y.resize((0, n)) # `dot` should just return zero (m,n) matrix z = np.dot(x, y) assert_(np.all(z == 0)) assert_(z.shape == (m, n)) def test_zeros(self): """Regression test for #1061.""" # Set a size which cannot fit into a 64 bits signed integer sz = 2 ** 64 good = 'Maximum allowed dimension exceeded' try: np.empty(sz) except ValueError as e: if not str(e) == good: self.fail("Got msg '%s', expected '%s'" % (e, good)) except Exception as e: self.fail("Got exception of type %s instead of ValueError" % type(e)) def test_huge_arange(self): """Regression test for #1062.""" # Set a size which cannot fit into a 64 bits signed integer sz = 2 ** 64 good = 'Maximum allowed size exceeded' try: a = np.arange(sz) self.assertTrue(np.size == sz) except ValueError as e: if not str(e) == good: self.fail("Got msg '%s', expected '%s'" % (e, good)) except Exception as e: self.fail("Got exception of type %s instead of ValueError" % type(e)) def test_fromiter_bytes(self): """Ticket #1058""" a = np.fromiter(list(range(10)), dtype='b') b = np.fromiter(list(range(10)), dtype='B') assert_(np.alltrue(a == np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]))) assert_(np.alltrue(b == np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]))) def test_array_from_sequence_scalar_array(self): """Ticket #1078: segfaults when creating an array with a sequence of 0d arrays.""" a = np.array((np.ones(2), np.array(2))) assert_equal(a.shape, (2,)) assert_equal(a.dtype, np.dtype(object)) assert_equal(a[0], np.ones(2)) assert_equal(a[1], np.array(2)) a = np.array(((1,), np.array(1))) assert_equal(a.shape, (2,)) assert_equal(a.dtype, np.dtype(object)) assert_equal(a[0], (1,)) assert_equal(a[1], np.array(1)) def test_array_from_sequence_scalar_array2(self): """Ticket #1081: weird array with strange input...""" t = np.array([np.array([]), np.array(0, object)]) assert_equal(t.shape, (2,)) assert_equal(t.dtype, np.dtype(object)) def test_array_too_big(self): """Ticket #1080.""" assert_raises(ValueError, np.zeros, [975]*7, np.int8) assert_raises(ValueError, np.zeros, [26244]*5, np.int8) def test_dtype_keyerrors_(self): """Ticket #1106.""" dt = np.dtype([('f1', np.uint)]) assert_raises(KeyError, dt.__getitem__, "f2") assert_raises(IndexError, dt.__getitem__, 1) assert_raises(ValueError, dt.__getitem__, 0.0) def test_lexsort_buffer_length(self): """Ticket #1217, don't segfault.""" a = np.ones(100, dtype=np.int8) b = np.ones(100, dtype=np.int32) i = np.lexsort((a[::-1], b)) assert_equal(i, np.arange(100, dtype=np.int)) def test_object_array_to_fixed_string(self): """Ticket #1235.""" a = np.array(['abcdefgh', 'ijklmnop'], dtype=np.object_) b = np.array(a, dtype=(np.str_, 8)) assert_equal(a, b) c = np.array(a, dtype=(np.str_, 5)) assert_equal(c, np.array(['abcde', 'ijklm'])) d = np.array(a, dtype=(np.str_, 12)) assert_equal(a, d) e = np.empty((2, ), dtype=(np.str_, 8)) e[:] = a[:] assert_equal(a, e) def test_unicode_to_string_cast(self): """Ticket #1240.""" a = np.array( [ [sixu('abc'), sixu('\u03a3')], [sixu('asdf'), sixu('erw')] ], dtype='U') def fail(): b = np.array(a, 'S4') self.assertRaises(UnicodeEncodeError, fail) def test_mixed_string_unicode_array_creation(self): a = np.array(['1234', sixu('123')]) assert_(a.itemsize == 16) a = np.array([sixu('123'), '1234']) assert_(a.itemsize == 16) a = np.array(['1234', sixu('123'), '12345']) assert_(a.itemsize == 20) a = np.array([sixu('123'), '1234', sixu('12345')]) assert_(a.itemsize == 20) a = np.array([sixu('123'), '1234', sixu('1234')]) assert_(a.itemsize == 16) def test_misaligned_objects_segfault(self): """Ticket #1198 and #1267""" a1 = np.zeros((10,), dtype='O,c') a2 = np.array(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'], 'S10') a1['f0'] = a2 r = repr(a1) np.argmax(a1['f0']) a1['f0'][1] = "FOO" a1['f0'] = "FOO" a3 = np.array(a1['f0'], dtype='S') np.nonzero(a1['f0']) a1.sort() a4 = copy.deepcopy(a1) def test_misaligned_scalars_segfault(self): """Ticket #1267""" s1 = np.array(('a', 'Foo'), dtype='c,O') s2 = np.array(('b', 'Bar'), dtype='c,O') s1['f1'] = s2['f1'] s1['f1'] = 'Baz' def test_misaligned_dot_product_objects(self): """Ticket #1267""" # This didn't require a fix, but it's worth testing anyway, because # it may fail if .dot stops enforcing the arrays to be BEHAVED a = np.array([[(1, 'a'), (0, 'a')], [(0, 'a'), (1, 'a')]], dtype='O,c') b = np.array([[(4, 'a'), (1, 'a')], [(2, 'a'), (2, 'a')]], dtype='O,c') np.dot(a['f0'], b['f0']) def test_byteswap_complex_scalar(self): """Ticket #1259 and gh-441""" for dtype in [np.dtype('<'+t) for t in np.typecodes['Complex']]: z = np.array([2.2-1.1j], dtype) x = z[0] # always native-endian y = x.byteswap() if x.dtype.byteorder == z.dtype.byteorder: # little-endian machine assert_equal(x, np.fromstring(y.tostring(), dtype=dtype.newbyteorder())) else: # big-endian machine assert_equal(x, np.fromstring(y.tostring(), dtype=dtype)) # double check real and imaginary parts: assert_equal(x.real, y.real.byteswap()) assert_equal(x.imag, y.imag.byteswap()) def test_structured_arrays_with_objects1(self): """Ticket #1299""" stra = 'aaaa' strb = 'bbbb' x = np.array([[(0, stra), (1, strb)]], 'i8,O') x[x.nonzero()] = x.ravel()[:1] assert_(x[0, 1] == x[0, 0]) def test_structured_arrays_with_objects2(self): """Ticket #1299 second test""" stra = 'aaaa' strb = 'bbbb' numb = sys.getrefcount(strb) numa = sys.getrefcount(stra) x = np.array([[(0, stra), (1, strb)]], 'i8,O') x[x.nonzero()] = x.ravel()[:1] assert_(sys.getrefcount(strb) == numb) assert_(sys.getrefcount(stra) == numa + 2) def test_duplicate_title_and_name(self): """Ticket #1254""" def func(): x = np.dtype([(('a', 'a'), 'i'), ('b', 'i')]) self.assertRaises(ValueError, func) def test_signed_integer_division_overflow(self): """Ticket #1317.""" def test_type(t): min = np.array([np.iinfo(t).min]) min //= -1 with np.errstate(divide="ignore"): for t in (np.int8, np.int16, np.int32, np.int64, np.int, np.long): test_type(t) def test_buffer_hashlib(self): try: from hashlib import md5 except ImportError: from md5 import new as md5 x = np.array([1, 2, 3], dtype=np.dtype('c') def test_log1p_compiler_shenanigans(self): # Check if log1p is behaving on 32 bit intel systems. assert_(np.isfinite(np.log1p(np.exp2(-53)))) def test_fromiter_comparison(self, level=rlevel): a = np.fromiter(list(range(10)), dtype='b') b = np.fromiter(list(range(10)), dtype='B') assert_(np.alltrue(a == np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]))) assert_(np.alltrue(b == np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]))) def test_fromstring_crash(self): # Ticket #1345: the following should not cause a crash np.fromstring(asbytes('aa, aa, 1.0'), sep=',') def test_ticket_1539(self): dtypes = [x for x in np.typeDict.values() if (issubclass(x, np.number) and not issubclass(x, np.timedelta64))] a = np.array([], dtypes[0]) failures = [] # ignore complex warnings with warnings.catch_warnings(): warnings.simplefilter('ignore', np.ComplexWarning) for x in dtypes: b = a.astype(x) for y in dtypes: c = a.astype(y) try: np.dot(b, c) except TypeError as e: failures.append((x, y)) if failures: raise AssertionError("Failures: %r" % failures) def test_ticket_1538(self): x = np.finfo(np.float32) for name in 'eps epsneg max min resolution tiny'.split(): assert_equal(type(getattr(x, name)), np.float32, err_msg=name) def test_ticket_1434(self): # Check that the out= argument in var and std has an effect data = np.array(((1, 2, 3), (4, 5, 6), (7, 8, 9))) out = np.zeros((3,)) ret = data.var(axis=1, out=out) assert_(ret is out) assert_array_equal(ret, data.var(axis=1)) ret = data.std(axis=1, out=out) assert_(ret is out) assert_array_equal(ret, data.std(axis=1)) def test_complex_nan_maximum(self): cnan = complex(0, np.nan) assert_equal(np.maximum(1, cnan), cnan) def test_subclass_int_tuple_assignment(self): # ticket #1563 class Subclass(np.ndarray): def __new__(cls, i): return np.ones((i,)).view(cls) x = Subclass(5) x[(0,)] = 2 # shouldn't raise an exception assert_equal(x[0], 2) def test_ufunc_no_unnecessary_views(self): # ticket #1548 class Subclass(np.ndarray): pass x = np.array([1, 2, 3]).view(Subclass) y = np.add(x, x, x) assert_equal(id(x), id(y)) def test_take_refcount(self): # ticket #939 a = np.arange(16, dtype=np.float) a.shape = (4, 4) lut = np.ones((5 + 3, 4), np.float) rgba = np.empty(shape=a.shape + (4,), dtype=lut.dtype) c1 = sys.getrefcount(rgba) try: lut.take(a, axis=0, mode='clip', out=rgba) except TypeError: pass c2 = sys.getrefcount(rgba) assert_equal(c1, c2) def test_fromfile_tofile_seeks(self): # On Python 3, tofile/fromfile used to get (#1610) the Python # file handle out of sync f0 = tempfile.NamedTemporaryFile() f = f0.file f.write(np.arange(255, dtype='u1').tostring()) f.seek(20) ret = np.fromfile(f, count=4, dtype='u1') assert_equal(ret, np.array([20, 21, 22, 23], dtype='u1')) assert_equal(f.tell(), 24) f.seek(40) np.array([1, 2, 3], dtype='u1').tofile(f) assert_equal(f.tell(), 43) f.seek(40) data = f.read(3) assert_equal(data, asbytes("\x01\x02\x03")) f.seek(80) f.read(4) data = np.fromfile(f, dtype='u1', count=4) assert_equal(data, np.array([84, 85, 86, 87], dtype='u1')) f.close() def test_complex_scalar_warning(self): for tp in [np.csingle, np.cdouble, np.clongdouble]: x = tp(1+2j) assert_warns(np.ComplexWarning, float, x) with warnings.catch_warnings(): warnings.simplefilter('ignore') assert_equal(float(x), float(x.real)) def test_complex_scalar_complex_cast(self): for tp in [np.csingle, np.cdouble, np.clongdouble]: x = tp(1+2j) assert_equal(complex(x), 1+2j) def test_complex_boolean_cast(self): """Ticket #2218""" for tp in [np.csingle, np.cdouble, np.clongdouble]: x = np.array([0, 0+0.5j, 0.5+0j], dtype=tp) assert_equal(x.astype(bool), np.array([0, 1, 1], dtype=bool)) assert_(np.any(x)) assert_(np.all(x[1:])) def test_uint_int_conversion(self): x = 2**64 - 1 assert_equal(int(np.uint64(x)), x) def test_duplicate_field_names_assign(self): ra = np.fromiter(((i*3, i*2) for i in range(10)), dtype='i8,f8') ra.dtype.names = ('f1', 'f2') rep = repr(ra) # should not cause a segmentation fault assert_raises(ValueError, setattr, ra.dtype, 'names', ('f1', 'f1')) def test_eq_string_and_object_array(self): # From e-mail thread "__eq__ with str and object" (Keith Goodman) a1 = np.array(['a', 'b'], dtype=object) a2 = np.array(['a', 'c']) assert_array_equal(a1 == a2, [True, False]) assert_array_equal(a2 == a1, [True, False]) def test_nonzero_byteswap(self): a = np.array([0x80000000, 0x00000080, 0], dtype=np.uint32) a.dtype = np.float32 assert_equal(a.nonzero()[0], [1]) a = a.byteswap().newbyteorder() assert_equal(a.nonzero()[0], [1]) # [0] if nonzero() ignores swap def test_find_common_type_boolean(self): # Ticket #1695 assert_(np.find_common_type([], ['?', '?']) == '?') def test_empty_mul(self): a = np.array([1.]) a[1:1] *= 2 assert_equal(a, [1.]) def test_array_side_effect(self): assert_equal(np.dtype('S10').itemsize, 10) A = np.array([['abc', 2], ['long ', '0123456789']], dtype=np.string_) # This was throwing an exception because in ctors.c, # discover_itemsize was calling PyObject_Length without checking # the return code. This failed to get the length of the number 2, # and the exception hung around until something checked # PyErr_Occurred() and returned an error. assert_equal(np.dtype('S10').itemsize, 10) def test_any_float(self): # all and any for floats a = np.array([0.1, 0.9]) assert_(np.any(a)) assert_(np.all(a)) def test_large_float_sum(self): a = np.arange(10000, dtype='f') assert_equal(a.sum(dtype='d'), a.astype('d').sum()) def test_ufunc_casting_out(self): a = np.array(1.0, dtype=np.float32) b = np.array(1.0, dtype=np.float64) c = np.array(1.0, dtype=np.float32) np.add(a, b, out=c) assert_equal(c, 2.0) def test_array_scalar_contiguous(self): # Array scalars are both C and Fortran contiguous assert_(np.array(1.0).flags.c_contiguous) assert_(np.array(1.0).flags.f_contiguous) assert_(np.array(np.float32(1.0)).flags.c_contiguous) assert_(np.array(np.float32(1.0)).flags.f_contiguous) def test_squeeze_contiguous(self): """Similar to GitHub issue #387""" a = np.zeros((1, 2)).squeeze() b = np.zeros((2, 2, 2), order='F')[:,:, ::2].squeeze() assert_(a.flags.c_contiguous) assert_(a.flags.f_contiguous) assert_(b.flags.f_contiguous) def test_reduce_contiguous(self): """GitHub issue #387""" a = np.add.reduce(np.zeros((2, 1, 2)), (0, 1)) b = np.add.reduce(np.zeros((2, 1, 2)), 1) assert_(a.flags.c_contiguous) assert_(a.flags.f_contiguous) assert_(b.flags.c_contiguous) def test_object_array_self_reference(self): # Object arrays with references to themselves can cause problems a = np.array(0, dtype=object) a[()] = a assert_raises(TypeError, int, a) assert_raises(TypeError, long, a) assert_raises(TypeError, float, a) assert_raises(TypeError, oct, a) assert_raises(TypeError, hex, a) # This was causing a to become like the above a = np.array(0, dtype=object) a[...] += 1 assert_equal(a, 1) def test_object_array_self_copy(self): # An object array being copied into itself DECREF'ed before INCREF'ing # causing segmentation faults (gh-3787) a = np.array(object(), dtype=object) np.copyto(a, a) assert_equal(sys.getrefcount(a[()]), 2) a[()].__class__ # will segfault if object was deleted def test_zerosize_accumulate(self): "Ticket #1733" x = np.array([[42, 0]], dtype=np.uint32) assert_equal(np.add.accumulate(x[:-1, 0]), []) def test_objectarray_setfield(self): # Setfield directly manipulates the raw array data, # so is invalid for object arrays. x = np.array([1, 2, 3], dtype=object) assert_raises(RuntimeError, x.setfield, 4, np.int32, 0) def test_setting_rank0_string(self): "Ticket #1736" s1 = asbytes("hello1") s2 = asbytes("hello2") a = np.zeros((), dtype="S10") a[()] = s1 assert_equal(a, np.array(s1)) a[()] = np.array(s2) assert_equal(a, np.array(s2)) a = np.zeros((), dtype='f4') a[()] = 3 assert_equal(a, np.array(3)) a[()] = np.array(4) assert_equal(a, np.array(4)) def test_string_astype(self): "Ticket #1748" s1 = asbytes('black') s2 = asbytes('white') s3 = asbytes('other') a = np.array([[s1], [s2], [s3]]) assert_equal(a.dtype, np.dtype('S5')) b = a.astype(np.dtype('S0')) assert_equal(b.dtype, np.dtype('S5')) def test_ticket_1756(self): """Ticket #1756 """ s = asbytes('0123456789abcdef') a = np.array([s]*5) for i in range(1, 17): a1 = np.array(a, "|S%d"%i) a2 = np.array([s[:i]]*5) assert_equal(a1, a2) def test_fields_strides(self): "Ticket #1760" r=np.fromstring('abcdefghijklmnop'*4*3, dtype='i4,(2,3)u2') assert_equal(r[0:3:2]['f1'], r['f1'][0:3:2]) assert_equal(r[0:3:2]['f1'][0], r[0:3:2][0]['f1']) assert_equal(r[0:3:2]['f1'][0][()], r[0:3:2][0]['f1'][()]) assert_equal(r[0:3:2]['f1'][0].strides, r[0:3:2][0]['f1'].strides) def test_alignment_update(self): """Check that alignment flag is updated on stride setting""" a = np.arange(10) assert_(a.flags.aligned) a.strides = 3 assert_(not a.flags.aligned) def test_ticket_1770(self): "Should not segfault on python 3k" import numpy as np try: a = np.zeros((1,), dtype=[('f1', 'f')]) a['f1'] = 1 a['f2'] = 1 except ValueError: pass except: raise AssertionError def test_ticket_1608(self): "x.flat shouldn't modify data" x = np.array([[1, 2], [3, 4]]).T y = np.array(x.flat) assert_equal(x, [[1, 3], [2, 4]]) def test_pickle_string_overwrite(self): import re data = np.array([1], dtype='b') blob = pickle.dumps(data, protocol=1) data = pickle.loads(blob) # Check that loads does not clobber interned strings s = re.sub("a(.)", "\x01\\1", "a_") assert_equal(s[0], "\x01") data[0] = 0xbb s = re.sub("a(.)", "\x01\\1", "a_") assert_equal(s[0], "\x01") def test_pickle_bytes_overwrite(self): if sys.version_info[0] >= 3: data = np.array([1], dtype='b') data = pickle.loads(pickle.dumps(data)) data[0] = 0xdd bytestring = "\x01 ".encode('ascii') assert_equal(bytestring[0:1], '\x01'.encode('ascii')) def test_structured_type_to_object(self): a_rec = np.array([(0, 1), (3, 2)], dtype='i4,i8') a_obj = np.empty((2,), dtype=object) a_obj[0] = (0, 1) a_obj[1] = (3, 2) # astype records -> object assert_equal(a_rec.astype(object), a_obj) # '=' records -> object b = np.empty_like(a_obj) b[...] = a_rec assert_equal(b, a_obj) # '=' object -> records b = np.empty_like(a_rec) b[...] = a_obj assert_equal(b, a_rec) def test_assign_obj_listoflists(self): # Ticket # 1870 # The inner list should get assigned to the object elements a = np.zeros(4, dtype=object) b = a.copy() a[0] = [1] a[1] = [2] a[2] = [3] a[3] = [4] b[...] = [[1], [2], [3], [4]] assert_equal(a, b) # The first dimension should get broadcast a = np.zeros((2, 2), dtype=object) a[...] = [[1, 2]] assert_equal(a, [[1, 2], [1, 2]]) def test_memoryleak(self): # Ticket #1917 - ensure that array data doesn't leak for i in range(1000): # 100MB times 1000 would give 100GB of memory usage if it leaks a = np.empty((100000000,), dtype='i1') del a def test_ufunc_reduce_memoryleak(self): a = np.arange(6) acnt = sys.getrefcount(a) res = np.add.reduce(a) assert_equal(sys.getrefcount(a), acnt) def test_search_sorted_invalid_arguments(self): # Ticket #2021, should not segfault. x = np.arange(0, 4, dtype='datetime64[D]') assert_raises(TypeError, x.searchsorted, 1) def test_string_truncation(self): # Ticket #1990 - Data can be truncated in creation of an array from a # mixed sequence of numeric values and strings for val in [True, 1234, 123.4, complex(1, 234)]: for tostr in [asunicode, asbytes]: b = np.array([val, tostr('xx')]) assert_equal(tostr(b[0]), tostr(val)) b = np.array([tostr('xx'), val]) assert_equal(tostr(b[1]), tostr(val)) # test also with longer strings b = np.array([val, tostr('xxxxxxxxxx')]) assert_equal(tostr(b[0]), tostr(val)) b = np.array([tostr('xxxxxxxxxx'), val]) assert_equal(tostr(b[1]), tostr(val)) def test_string_truncation_ucs2(self): # Ticket #2081. Python compiled with two byte unicode # can lead to truncation if itemsize is not properly # adjusted for Numpy's four byte unicode. if sys.version_info[0] >= 3: a = np.array(['abcd']) else: a = np.array([sixu('abcd')]) assert_equal(a.dtype.itemsize, 16) def test_unique_stable(self): # Ticket #2063 must always choose stable sort for argsort to # get consistent results v = np.array(([0]*5 + [1]*6 + [2]*6)*4) res = np.unique(v, return_index=True) tgt = (np.array([0, 1, 2]), np.array([ 0, 5, 11])) assert_equal(res, tgt) def test_unicode_alloc_dealloc_match(self): # Ticket #1578, the mismatch only showed up when running # python-debug for python versions >= 2.7, and then as # a core dump and error message. a = np.array(['abc'], dtype=np.unicode)[0] del a def test_refcount_error_in_clip(self): # Ticket #1588 a = np.zeros((2,), dtype='>i2').clip(min=0) x = a + a # This used to segfault: y = str(x) # Check the final string: assert_(y == "[0 0]") def test_searchsorted_wrong_dtype(self): # Ticket #2189, it used to segfault, so we check that it raises the # proper exception. a = np.array([('a', 1)], dtype='S1, int') assert_raises(TypeError, np.searchsorted, a, 1.2) # Ticket #2066, similar problem: dtype = np.format_parser(['i4', 'i4'], [], []) a = np.recarray((2, ), dtype) assert_raises(TypeError, np.searchsorted, a, 1) def test_complex64_alignment(self): # Issue gh-2668 (trac 2076), segfault on sparc due to misalignment dtt = np.complex64 arr = np.arange(10, dtype=dtt) # 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_back = np.ndarray(arr2.shape, arr2.dtype, buffer=data_str, order='F') assert_array_equal(arr2, data_back) def test_structured_count_nonzero(self): arr = np.array([0, 1]).astype('i4, (2)i4')[:1] count = np.count_nonzero(arr) assert_equal(count, 0) def test_copymodule_preserves_f_contiguity(self): a = np.empty((2, 2), order='F') b = copy.copy(a) c = copy.deepcopy(a) assert_(b.flags.fortran) assert_(b.flags.f_contiguous) assert_(c.flags.fortran) assert_(c.flags.f_contiguous) def test_fortran_order_buffer(self): import numpy as np a = np.array([['Hello', 'Foob']], dtype='U5', order='F') arr = np.ndarray(shape=[1, 2, 5], dtype='U1', buffer=a) arr2 = np.array([[[sixu('H'), sixu('e'), sixu('l'), sixu('l'), sixu('o')], [sixu('F'), sixu('o'), sixu('o'), sixu('b'), sixu('')]]]) assert_array_equal(arr, arr2) def test_assign_from_sequence_error(self): # Ticket #4024. arr = np.array([1, 2, 3]) assert_raises(ValueError, arr.__setitem__, slice(None), [9, 9]) 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', '= 3: assert_raises(TypeError, f, lhs, rhs) else: f(lhs, rhs) assert_(not op.eq(lhs, rhs)) assert_(op.ne(lhs, rhs)) if __name__ == "__main__": run_module_suite() numpy-1.8.2/numpy/core/tests/test_memmap.py0000664000175100017510000001016012370216242022150 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function import sys from tempfile import NamedTemporaryFile, TemporaryFile, mktemp, mkdtemp import os import shutil from numpy import memmap from numpy import arange, allclose, asarray 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) self.data.resize(self.shape) def tearDown(self): self.tmpfp.close() shutil.rmtree(self.tempdir) def test_roundtrip(self): # Write data to file fp = memmap(self.tmpfp, dtype=self.dtype, mode='w+', shape=self.shape) fp[:] = self.data[:] del fp # Test __del__ machinery, which handles cleanup # Read data back from file newfp = memmap(self.tmpfp, dtype=self.dtype, mode='r', shape=self.shape) assert_(allclose(self.data, newfp)) assert_array_equal(self.data, newfp) def test_open_with_filename(self): tmpname = mktemp('', 'mmap', dir=self.tempdir) fp = memmap(tmpname, dtype=self.dtype, mode='w+', shape=self.shape) fp[:] = self.data[:] del fp def test_unnamed_file(self): with TemporaryFile() as f: fp = memmap(f, dtype=self.dtype, shape=self.shape) del fp def test_attributes(self): offset = 1 mode = "w+" fp = memmap(self.tmpfp, dtype=self.dtype, mode=mode, shape=self.shape, offset=offset) self.assertEqual(offset, fp.offset) self.assertEqual(mode, fp.mode) del fp def test_filename(self): tmpname = mktemp('', 'mmap', dir=self.tempdir) fp = memmap(tmpname, dtype=self.dtype, mode='w+', shape=self.shape) abspath = os.path.abspath(tmpname) fp[:] = self.data[:] self.assertEqual(abspath, fp.filename) b = fp[:1] self.assertEqual(abspath, b.filename) del b del fp def test_filename_fileobj(self): fp = memmap(self.tmpfp, dtype=self.dtype, mode="w+", shape=self.shape) self.assertEqual(fp.filename, self.tmpfp.name) @dec.knownfailureif(sys.platform=='gnu0', "This test is known to fail on hurd") def test_flush(self): fp = memmap(self.tmpfp, dtype=self.dtype, mode='w+', shape=self.shape) fp[:] = self.data[:] assert_equal(fp[0], self.data[0]) fp.flush() def test_del(self): # Make sure a view does not delete the underlying mmap fp_base = memmap(self.tmpfp, dtype=self.dtype, mode='w+', shape=self.shape) fp_base[0] = 5 fp_view = fp_base[0:1] assert_equal(fp_view[0], 5) del fp_view # Should still be able to access and assign values after # deleting the view assert_equal(fp_base[0], 5) fp_base[0] = 6 assert_equal(fp_base[0], 6) def test_arithmetic_drops_references(self): fp = memmap(self.tmpfp, dtype=self.dtype, mode='w+', shape=self.shape) tmp = (fp + 10) if isinstance(tmp, memmap): assert tmp._mmap is not fp._mmap def test_indexing_drops_references(self): fp = memmap(self.tmpfp, dtype=self.dtype, mode='w+', shape=self.shape) tmp = fp[[(1, 2), (2, 3)]] if isinstance(tmp, memmap): assert tmp._mmap is not fp._mmap def test_slicing_keeps_references(self): fp = memmap(self.tmpfp, dtype=self.dtype, mode='w+', shape=self.shape) assert fp[:2, :2]._mmap is fp._mmap def test_view(self): fp = memmap(self.tmpfp, dtype=self.dtype, shape=self.shape) new1 = fp.view() new2 = new1.view() assert(new1.base is fp) assert(new2.base is fp) new_array = asarray(fp) assert(new_array.base is fp) if __name__ == "__main__": run_module_suite() numpy-1.8.2/numpy/core/tests/test_defchararray.py0000664000175100017510000006245412370216243023345 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function from numpy.testing import * from numpy.core import * import numpy as np import sys from numpy.core.multiarray import _vec_string from numpy.compat import asbytes, asbytes_nested, sixu kw_unicode_true = {'unicode': True} # make 2to3 work properly kw_unicode_false = {'unicode': False} class TestBasic(TestCase): def test_from_object_array(self): A = np.array([['abc', 2], ['long ', '0123456789']], dtype='O') B = np.char.array(A) assert_equal(B.dtype.itemsize, 10) assert_array_equal(B, asbytes_nested([['abc', '2'], ['long', '0123456789']])) def test_from_object_array_unicode(self): A = np.array([['abc', sixu('Sigma \u03a3')], ['long ', '0123456789']], dtype='O') self.assertRaises(ValueError, np.char.array, (A,)) B = np.char.array(A, **kw_unicode_true) assert_equal(B.dtype.itemsize, 10 * np.array('a', 'U').dtype.itemsize) assert_array_equal(B, [['abc', sixu('Sigma \u03a3')], ['long', '0123456789']]) def test_from_string_array(self): A = np.array(asbytes_nested([['abc', 'foo'], ['long ', '0123456789']])) assert_equal(A.dtype.type, np.string_) B = np.char.array(A) assert_array_equal(B, A) assert_equal(B.dtype, A.dtype) assert_equal(B.shape, A.shape) B[0, 0] = 'changed' assert_(B[0, 0] != A[0, 0]) C = np.char.asarray(A) assert_array_equal(C, A) assert_equal(C.dtype, A.dtype) C[0, 0] = 'changed again' assert_(C[0, 0] != B[0, 0]) assert_(C[0, 0] == A[0, 0]) def test_from_unicode_array(self): A = np.array([['abc', sixu('Sigma \u03a3')], ['long ', '0123456789']]) assert_equal(A.dtype.type, np.unicode_) B = np.char.array(A) assert_array_equal(B, A) assert_equal(B.dtype, A.dtype) assert_equal(B.shape, A.shape) B = np.char.array(A, **kw_unicode_true) assert_array_equal(B, A) assert_equal(B.dtype, A.dtype) assert_equal(B.shape, A.shape) def fail(): B = np.char.array(A, **kw_unicode_false) self.assertRaises(UnicodeEncodeError, fail) def test_unicode_upconvert(self): A = np.char.array(['abc']) B = np.char.array([sixu('\u03a3')]) assert_(issubclass((A + B).dtype.type, np.unicode_)) def test_from_string(self): A = np.char.array(asbytes('abc')) assert_equal(len(A), 1) assert_equal(len(A[0]), 3) assert_(issubclass(A.dtype.type, np.string_)) def test_from_unicode(self): A = np.char.array(sixu('\u03a3')) assert_equal(len(A), 1) assert_equal(len(A[0]), 1) assert_equal(A.itemsize, 4) assert_(issubclass(A.dtype.type, np.unicode_)) class TestVecString(TestCase): def test_non_existent_method(self): def fail(): _vec_string('a', np.string_, 'bogus') self.assertRaises(AttributeError, fail) def test_non_string_array(self): def fail(): _vec_string(1, np.string_, 'strip') self.assertRaises(TypeError, fail) def test_invalid_args_tuple(self): def fail(): _vec_string(['a'], np.string_, 'strip', 1) self.assertRaises(TypeError, fail) def test_invalid_type_descr(self): def fail(): _vec_string(['a'], 'BOGUS', 'strip') self.assertRaises(TypeError, fail) def test_invalid_function_args(self): def fail(): _vec_string(['a'], np.string_, 'strip', (1,)) self.assertRaises(TypeError, fail) def test_invalid_result_type(self): def fail(): _vec_string(['a'], np.integer, 'strip') self.assertRaises(TypeError, fail) def test_broadcast_error(self): def fail(): _vec_string([['abc', 'def']], np.integer, 'find', (['a', 'd', 'j'],)) self.assertRaises(ValueError, fail) class TestWhitespace(TestCase): def setUp(self): self.A = np.array([['abc ', '123 '], ['789 ', 'xyz ']]).view(np.chararray) self.B = np.array([['abc', '123'], ['789', 'xyz']]).view(np.chararray) def test1(self): 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))) class TestChar(TestCase): def setUp(self): self.A = np.array('abc1', dtype='c').view(np.chararray) def test_it(self): assert_equal(self.A.shape, (4,)) assert_equal(self.A.upper()[:2].tostring(), asbytes('AB')) class TestComparisons(TestCase): def setUp(self): self.A = np.array([['abc', '123'], ['789', 'xyz']]).view(np.chararray) self.B = np.array([['efg', '123 '], ['051', 'tuv']]).view(np.chararray) def test_not_equal(self): assert_array_equal((self.A != self.B), [[True, False], [True, True]]) def test_equal(self): assert_array_equal((self.A == self.B), [[False, True], [False, False]]) def test_greater_equal(self): assert_array_equal((self.A >= self.B), [[False, True], [True, True]]) def test_less_equal(self): assert_array_equal((self.A <= self.B), [[True, True], [False, False]]) def test_greater(self): assert_array_equal((self.A > self.B), [[False, False], [True, True]]) def test_less(self): assert_array_equal((self.A < self.B), [[True, False], [False, False]]) class TestComparisonsMixed1(TestComparisons): """Ticket #1276""" def setUp(self): TestComparisons.setUp(self) self.B = np.array([['efg', '123 '], ['051', 'tuv']], np.unicode_).view(np.chararray) class TestComparisonsMixed2(TestComparisons): """Ticket #1276""" def setUp(self): TestComparisons.setUp(self) self.A = np.array([['abc', '123'], ['789', 'xyz']], np.unicode_).view(np.chararray) class TestInformation(TestCase): def setUp(self): self.A = np.array([[' abc ', ''], ['12345', 'MixedCase'], ['123 \t 345 \0 ', 'UPPER']]).view(np.chararray) self.B = np.array([[sixu(' \u03a3 '), sixu('')], [sixu('12345'), sixu('MixedCase')], [sixu('123 \t 345 \0 '), sixu('UPPER')]]).view(np.chararray) def test_len(self): assert_(issubclass(np.char.str_len(self.A).dtype.type, np.integer)) assert_array_equal(np.char.str_len(self.A), [[5, 0], [5, 9], [12, 5]]) assert_array_equal(np.char.str_len(self.B), [[3, 0], [5, 9], [12, 5]]) def test_count(self): assert_(issubclass(self.A.count('').dtype.type, np.integer)) assert_array_equal(self.A.count('a'), [[1, 0], [0, 1], [0, 0]]) assert_array_equal(self.A.count('123'), [[0, 0], [1, 0], [1, 0]]) # Python doesn't seem to like counting NULL characters # assert_array_equal(self.A.count('\0'), [[0, 0], [0, 0], [1, 0]]) assert_array_equal(self.A.count('a', 0, 2), [[1, 0], [0, 0], [0, 0]]) assert_array_equal(self.B.count('a'), [[0, 0], [0, 1], [0, 0]]) assert_array_equal(self.B.count('123'), [[0, 0], [1, 0], [1, 0]]) # assert_array_equal(self.B.count('\0'), [[0, 0], [0, 0], [1, 0]]) def test_endswith(self): assert_(issubclass(self.A.endswith('').dtype.type, np.bool_)) assert_array_equal(self.A.endswith(' '), [[1, 0], [0, 0], [1, 0]]) assert_array_equal(self.A.endswith('3', 0, 3), [[0, 0], [1, 0], [1, 0]]) def fail(): self.A.endswith('3', 'fdjk') self.assertRaises(TypeError, fail) def test_find(self): assert_(issubclass(self.A.find('a').dtype.type, np.integer)) assert_array_equal(self.A.find('a'), [[1, -1], [-1, 6], [-1, -1]]) assert_array_equal(self.A.find('3'), [[-1, -1], [2, -1], [2, -1]]) assert_array_equal(self.A.find('a', 0, 2), [[1, -1], [-1, -1], [-1, -1]]) assert_array_equal(self.A.find(['1', 'P']), [[-1, -1], [0, -1], [0, 1]]) def test_index(self): def fail(): self.A.index('a') self.assertRaises(ValueError, fail) assert_(np.char.index('abcba', 'b') == 1) assert_(issubclass(np.char.index('abcba', 'b').dtype.type, np.integer)) def test_isalnum(self): assert_(issubclass(self.A.isalnum().dtype.type, np.bool_)) assert_array_equal(self.A.isalnum(), [[False, False], [True, True], [False, True]]) def test_isalpha(self): assert_(issubclass(self.A.isalpha().dtype.type, np.bool_)) assert_array_equal(self.A.isalpha(), [[False, False], [False, True], [False, True]]) def test_isdigit(self): assert_(issubclass(self.A.isdigit().dtype.type, np.bool_)) assert_array_equal(self.A.isdigit(), [[False, False], [True, False], [False, False]]) def test_islower(self): assert_(issubclass(self.A.islower().dtype.type, np.bool_)) assert_array_equal(self.A.islower(), [[True, False], [False, False], [False, False]]) def test_isspace(self): assert_(issubclass(self.A.isspace().dtype.type, np.bool_)) assert_array_equal(self.A.isspace(), [[False, False], [False, False], [False, False]]) def test_istitle(self): assert_(issubclass(self.A.istitle().dtype.type, np.bool_)) assert_array_equal(self.A.istitle(), [[False, False], [False, False], [False, False]]) def test_isupper(self): assert_(issubclass(self.A.isupper().dtype.type, np.bool_)) assert_array_equal(self.A.isupper(), [[False, False], [False, False], [False, True]]) def test_rfind(self): assert_(issubclass(self.A.rfind('a').dtype.type, np.integer)) assert_array_equal(self.A.rfind('a'), [[1, -1], [-1, 6], [-1, -1]]) assert_array_equal(self.A.rfind('3'), [[-1, -1], [2, -1], [6, -1]]) assert_array_equal(self.A.rfind('a', 0, 2), [[1, -1], [-1, -1], [-1, -1]]) assert_array_equal(self.A.rfind(['1', 'P']), [[-1, -1], [0, -1], [0, 2]]) def test_rindex(self): def fail(): self.A.rindex('a') self.assertRaises(ValueError, fail) assert_(np.char.rindex('abcba', 'b') == 3) assert_(issubclass(np.char.rindex('abcba', 'b').dtype.type, np.integer)) def test_startswith(self): assert_(issubclass(self.A.startswith('').dtype.type, np.bool_)) assert_array_equal(self.A.startswith(' '), [[1, 0], [0, 0], [0, 0]]) assert_array_equal(self.A.startswith('1', 0, 3), [[0, 0], [1, 0], [1, 0]]) def fail(): self.A.startswith('3', 'fdjk') self.assertRaises(TypeError, fail) class TestMethods(TestCase): def setUp(self): self.A = np.array([[' abc ', ''], ['12345', 'MixedCase'], ['123 \t 345 \0 ', 'UPPER']], dtype='S').view(np.chararray) self.B = np.array([[sixu(' \u03a3 '), sixu('')], [sixu('12345'), sixu('MixedCase')], [sixu('123 \t 345 \0 '), sixu('UPPER')]]).view(np.chararray) def test_capitalize(self): assert_(issubclass(self.A.capitalize().dtype.type, np.string_)) assert_array_equal(self.A.capitalize(), asbytes_nested([ [' abc ', ''], ['12345', 'Mixedcase'], ['123 \t 345 \0 ', 'Upper']])) assert_(issubclass(self.B.capitalize().dtype.type, np.unicode_)) assert_array_equal(self.B.capitalize(), [ [sixu(' \u03c3 '), ''], ['12345', 'Mixedcase'], ['123 \t 345 \0 ', 'Upper']]) def test_center(self): assert_(issubclass(self.A.center(10).dtype.type, np.string_)) widths = np.array([[10, 20]]) C = self.A.center([10, 20]) assert_array_equal(np.char.str_len(C), [[10, 20], [10, 20], [12, 20]]) C = self.A.center(20, asbytes('#')) assert_(np.all(C.startswith(asbytes('#')))) assert_(np.all(C.endswith(asbytes('#')))) C = np.char.center(asbytes('FOO'), [[10, 20], [15, 8]]) assert_(issubclass(C.dtype.type, np.string_)) assert_array_equal(C, asbytes_nested([ [' FOO ', ' FOO '], [' FOO ', ' FOO ']])) def test_decode(self): if sys.version_info[0] >= 3: A = np.char.array([asbytes('\\u03a3')]) assert_(A.decode('unicode-escape')[0] == '\u03a3') else: A = np.char.array(['736563726574206d657373616765']) assert_(A.decode('hex_codec')[0] == 'secret message') def test_encode(self): B = self.B.encode('unicode_escape') assert_(B[0][0] == str(' \\u03a3 ').encode('latin1')) def test_expandtabs(self): T = self.A.expandtabs() assert_(T[2][0] == asbytes('123 345')) def test_join(self): if sys.version_info[0] >= 3: # NOTE: list(b'123') == [49, 50, 51] # so that b','.join(b'123') results to an error on Py3 A0 = self.A.decode('ascii') else: A0 = self.A A = np.char.join([',', '#'], A0) if sys.version_info[0] >= 3: assert_(issubclass(A.dtype.type, np.unicode_)) else: assert_(issubclass(A.dtype.type, np.string_)) assert_array_equal(np.char.join([',', '#'], A0), [ [' ,a,b,c, ', ''], ['1,2,3,4,5', 'M#i#x#e#d#C#a#s#e'], ['1,2,3, ,\t, ,3,4,5, ,\x00, ', 'U#P#P#E#R']]) def test_ljust(self): assert_(issubclass(self.A.ljust(10).dtype.type, np.string_)) widths = np.array([[10, 20]]) C = self.A.ljust([10, 20]) assert_array_equal(np.char.str_len(C), [[10, 20], [10, 20], [12, 20]]) C = self.A.ljust(20, asbytes('#')) assert_array_equal(C.startswith(asbytes('#')), [ [False, True], [False, False], [False, False]]) assert_(np.all(C.endswith(asbytes('#')))) C = np.char.ljust(asbytes('FOO'), [[10, 20], [15, 8]]) assert_(issubclass(C.dtype.type, np.string_)) assert_array_equal(C, asbytes_nested([ ['FOO ', 'FOO '], ['FOO ', 'FOO ']])) def test_lower(self): assert_(issubclass(self.A.lower().dtype.type, np.string_)) assert_array_equal(self.A.lower(), asbytes_nested([ [' abc ', ''], ['12345', 'mixedcase'], ['123 \t 345 \0 ', 'upper']])) assert_(issubclass(self.B.lower().dtype.type, np.unicode_)) assert_array_equal(self.B.lower(), [ [sixu(' \u03c3 '), sixu('')], [sixu('12345'), sixu('mixedcase')], [sixu('123 \t 345 \0 '), sixu('upper')]]) def test_lstrip(self): assert_(issubclass(self.A.lstrip().dtype.type, np.string_)) assert_array_equal(self.A.lstrip(), asbytes_nested([ ['abc ', ''], ['12345', 'MixedCase'], ['123 \t 345 \0 ', 'UPPER']])) assert_array_equal(self.A.lstrip(asbytes_nested(['1', 'M'])), asbytes_nested([ [' abc', ''], ['2345', 'ixedCase'], ['23 \t 345 \x00', 'UPPER']])) assert_(issubclass(self.B.lstrip().dtype.type, np.unicode_)) assert_array_equal(self.B.lstrip(), [ [sixu('\u03a3 '), ''], ['12345', 'MixedCase'], ['123 \t 345 \0 ', 'UPPER']]) def test_partition(self): P = self.A.partition(asbytes_nested(['3', 'M'])) assert_(issubclass(P.dtype.type, np.string_)) assert_array_equal(P, asbytes_nested([ [(' abc ', '', ''), ('', '', '')], [('12', '3', '45'), ('', 'M', 'ixedCase')], [('12', '3', ' \t 345 \0 '), ('UPPER', '', '')]])) def test_replace(self): R = self.A.replace(asbytes_nested(['3', 'a']), asbytes_nested(['##########', '@'])) assert_(issubclass(R.dtype.type, np.string_)) assert_array_equal(R, asbytes_nested([ [' abc ', ''], ['12##########45', 'MixedC@se'], ['12########## \t ##########45 \x00', 'UPPER']])) if sys.version_info[0] < 3: # NOTE: b'abc'.replace(b'a', 'b') is not allowed on Py3 R = self.A.replace(asbytes('a'), sixu('\u03a3')) assert_(issubclass(R.dtype.type, np.unicode_)) assert_array_equal(R, [ [sixu(' \u03a3bc '), ''], ['12345', sixu('MixedC\u03a3se')], ['123 \t 345 \x00', 'UPPER']]) def test_rjust(self): assert_(issubclass(self.A.rjust(10).dtype.type, np.string_)) widths = np.array([[10, 20]]) C = self.A.rjust([10, 20]) assert_array_equal(np.char.str_len(C), [[10, 20], [10, 20], [12, 20]]) C = self.A.rjust(20, asbytes('#')) assert_(np.all(C.startswith(asbytes('#')))) assert_array_equal(C.endswith(asbytes('#')), [[False, True], [False, False], [False, False]]) C = np.char.rjust(asbytes('FOO'), [[10, 20], [15, 8]]) assert_(issubclass(C.dtype.type, np.string_)) assert_array_equal(C, asbytes_nested([ [' FOO', ' FOO'], [' FOO', ' FOO']])) def test_rpartition(self): P = self.A.rpartition(asbytes_nested(['3', 'M'])) assert_(issubclass(P.dtype.type, np.string_)) assert_array_equal(P, asbytes_nested([ [('', '', ' abc '), ('', '', '')], [('12', '3', '45'), ('', 'M', 'ixedCase')], [('123 \t ', '3', '45 \0 '), ('', '', 'UPPER')]])) def test_rsplit(self): A = self.A.rsplit(asbytes('3')) assert_(issubclass(A.dtype.type, np.object_)) assert_equal(A.tolist(), asbytes_nested([ [[' abc '], ['']], [['12', '45'], ['MixedCase']], [['12', ' \t ', '45 \x00 '], ['UPPER']]])) def test_rstrip(self): assert_(issubclass(self.A.rstrip().dtype.type, np.string_)) assert_array_equal(self.A.rstrip(), asbytes_nested([ [' abc', ''], ['12345', 'MixedCase'], ['123 \t 345', 'UPPER']])) assert_array_equal(self.A.rstrip(asbytes_nested(['5', 'ER'])), asbytes_nested([ [' abc ', ''], ['1234', 'MixedCase'], ['123 \t 345 \x00', 'UPP']])) assert_(issubclass(self.B.rstrip().dtype.type, np.unicode_)) assert_array_equal(self.B.rstrip(), [ [sixu(' \u03a3'), ''], ['12345', 'MixedCase'], ['123 \t 345', 'UPPER']]) def test_strip(self): assert_(issubclass(self.A.strip().dtype.type, np.string_)) assert_array_equal(self.A.strip(), asbytes_nested([ ['abc', ''], ['12345', 'MixedCase'], ['123 \t 345', 'UPPER']])) assert_array_equal(self.A.strip(asbytes_nested(['15', 'EReM'])), asbytes_nested([ [' abc ', ''], ['234', 'ixedCas'], ['23 \t 345 \x00', 'UPP']])) assert_(issubclass(self.B.strip().dtype.type, np.unicode_)) assert_array_equal(self.B.strip(), [ [sixu('\u03a3'), ''], ['12345', 'MixedCase'], ['123 \t 345', 'UPPER']]) def test_split(self): A = self.A.split(asbytes('3')) assert_(issubclass(A.dtype.type, np.object_)) assert_equal(A.tolist(), asbytes_nested([ [[' abc '], ['']], [['12', '45'], ['MixedCase']], [['12', ' \t ', '45 \x00 '], ['UPPER']]])) def test_splitlines(self): A = np.char.array(['abc\nfds\nwer']).splitlines() assert_(issubclass(A.dtype.type, np.object_)) assert_(A.shape == (1,)) assert_(len(A[0]) == 3) def test_swapcase(self): assert_(issubclass(self.A.swapcase().dtype.type, np.string_)) assert_array_equal(self.A.swapcase(), asbytes_nested([ [' ABC ', ''], ['12345', 'mIXEDcASE'], ['123 \t 345 \0 ', 'upper']])) assert_(issubclass(self.B.swapcase().dtype.type, np.unicode_)) assert_array_equal(self.B.swapcase(), [ [sixu(' \u03c3 '), sixu('')], [sixu('12345'), sixu('mIXEDcASE')], [sixu('123 \t 345 \0 '), sixu('upper')]]) def test_title(self): assert_(issubclass(self.A.title().dtype.type, np.string_)) assert_array_equal(self.A.title(), asbytes_nested([ [' Abc ', ''], ['12345', 'Mixedcase'], ['123 \t 345 \0 ', 'Upper']])) assert_(issubclass(self.B.title().dtype.type, np.unicode_)) assert_array_equal(self.B.title(), [ [sixu(' \u03a3 '), sixu('')], [sixu('12345'), sixu('Mixedcase')], [sixu('123 \t 345 \0 '), sixu('Upper')]]) def test_upper(self): assert_(issubclass(self.A.upper().dtype.type, np.string_)) assert_array_equal(self.A.upper(), asbytes_nested([ [' ABC ', ''], ['12345', 'MIXEDCASE'], ['123 \t 345 \0 ', 'UPPER']])) assert_(issubclass(self.B.upper().dtype.type, np.unicode_)) assert_array_equal(self.B.upper(), [ [sixu(' \u03a3 '), sixu('')], [sixu('12345'), sixu('MIXEDCASE')], [sixu('123 \t 345 \0 '), sixu('UPPER')]]) def test_isnumeric(self): def fail(): self.A.isnumeric() self.assertRaises(TypeError, fail) assert_(issubclass(self.B.isnumeric().dtype.type, np.bool_)) assert_array_equal(self.B.isnumeric(), [ [False, False], [True, False], [False, False]]) def test_isdecimal(self): def fail(): self.A.isdecimal() self.assertRaises(TypeError, fail) assert_(issubclass(self.B.isdecimal().dtype.type, np.bool_)) assert_array_equal(self.B.isdecimal(), [ [False, False], [True, False], [False, False]]) class TestOperations(TestCase): def setUp(self): self.A = np.array([['abc', '123'], ['789', 'xyz']]).view(np.chararray) self.B = np.array([['efg', '456'], ['051', 'tuv']]).view(np.chararray) def test_add(self): AB = np.array([['abcefg', '123456'], ['789051', 'xyztuv']]).view(np.chararray) assert_array_equal(AB, (self.A + self.B)) assert_(len((self.A + self.B)[0][0]) == 6) def test_radd(self): QA = np.array([['qabc', 'q123'], ['q789', 'qxyz']]).view(np.chararray) assert_array_equal(QA, ('q' + self.A)) def test_mul(self): A = self.A for r in (2, 3, 5, 7, 197): Ar = np.array([[A[0, 0]*r, A[0, 1]*r], [A[1, 0]*r, A[1, 1]*r]]).view(np.chararray) assert_array_equal(Ar, (self.A * r)) for ob in [object(), 'qrs']: try: A * ob except ValueError: pass else: self.fail("chararray can only be multiplied by integers") def test_rmul(self): A = self.A for r in (2, 3, 5, 7, 197): Ar = np.array([[A[0, 0]*r, A[0, 1]*r], [A[1, 0]*r, A[1, 1]*r]]).view(np.chararray) assert_array_equal(Ar, (r * self.A)) for ob in [object(), 'qrs']: try: ob * A except ValueError: pass else: self.fail("chararray can only be multiplied by integers") def test_mod(self): """Ticket #856""" F = np.array([['%d', '%f'], ['%s', '%r']]).view(np.chararray) C = np.array([[3, 7], [19, 1]]) FC = np.array([['3', '7.000000'], ['19', '1']]).view(np.chararray) assert_array_equal(FC, F % C) A = np.array([['%.3f', '%d'], ['%s', '%r']]).view(np.chararray) A1 = np.array([['1.000', '1'], ['1', '1']]).view(np.chararray) assert_array_equal(A1, (A % 1)) A2 = np.array([['1.000', '2'], ['3', '4']]).view(np.chararray) assert_array_equal(A2, (A % [[1, 2], [3, 4]])) def test_rmod(self): assert_(("%s" % self.A) == str(self.A)) assert_(("%r" % self.A) == repr(self.A)) for ob in [42, object()]: try: ob % self.A except TypeError: pass else: self.fail("chararray __rmod__ should fail with " \ "non-string objects") def test_empty_indexing(): """Regression test for ticket 1948.""" # Check that indexing a chararray with an empty list/array returns an # empty chararray instead of a chararray with a single empty string in it. s = np.chararray((4,)) assert_(s[[]].size == 0) if __name__ == "__main__": run_module_suite() numpy-1.8.2/numpy/core/tests/test_scalarmath.py0000664000175100017510000001706612370216243023030 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function import sys from numpy.testing import * from numpy.testing.utils import _gen_alignment_data import numpy as np types = [np.bool_, np.byte, np.ubyte, np.short, np.ushort, np.intc, np.uintc, np.int_, np.uint, np.longlong, np.ulonglong, np.single, np.double, np.longdouble, np.csingle, np.cdouble, np.clongdouble] # This compares scalarmath against ufuncs. class TestTypes(TestCase): def test_types(self, level=1): for atype in types: a = atype(1) assert_(a == 1, "error with %r: got %r" % (atype, a)) def test_type_add(self, level=1): # list of types for k, atype in enumerate(types): a_scalar = atype(3) a_array = np.array([3], dtype=atype) for l, btype in enumerate(types): b_scalar = btype(1) b_array = np.array([1], dtype=btype) c_scalar = a_scalar + b_scalar c_array = a_array + b_array # It was comparing the type numbers, but the new ufunc # function-finding mechanism finds the lowest function # to which both inputs can be cast - which produces 'l' # when you do 'q' + 'b'. The old function finding mechanism # skipped ahead based on the first argument, but that # does not produce properly symmetric results... assert_equal(c_scalar.dtype, c_array.dtype, "error with types (%d/'%c' + %d/'%c')" % (k, np.dtype(atype).char, l, np.dtype(btype).char)) def test_type_create(self, level=1): for k, atype in enumerate(types): a = np.array([1, 2, 3], atype) b = atype([1, 2, 3]) assert_equal(a, b) class TestBaseMath(TestCase): def test_blocked(self): #test alignments offsets for simd instructions for dt in [np.float32, np.float64]: for out, inp1, inp2, msg in _gen_alignment_data(dtype=dt, type='binary', max_size=12): exp1 = np.ones_like(inp1) inp1[...] = np.ones_like(inp1) inp2[...] = np.zeros_like(inp2) assert_almost_equal(np.add(inp1, inp2), exp1, err_msg=msg) assert_almost_equal(np.add(inp1, 1), exp1 + 1, err_msg=msg) assert_almost_equal(np.add(1, inp2), exp1, err_msg=msg) np.add(inp1, inp2, out=out) assert_almost_equal(out, exp1, err_msg=msg) inp2[...] += np.arange(inp2.size, dtype=dt) + 1 assert_almost_equal(np.square(inp2), np.multiply(inp2, inp2), err_msg=msg) assert_almost_equal(np.reciprocal(inp2), np.divide(1, inp2), err_msg=msg) inp1[...] = np.ones_like(inp1) inp2[...] = np.zeros_like(inp2) np.add(inp1, 1, out=out) assert_almost_equal(out, exp1 + 1, err_msg=msg) np.add(1, inp2, out=out) assert_almost_equal(out, exp1, err_msg=msg) def test_lower_align(self): # check data that is not aligned to element size # i.e doubles are aligned to 4 bytes on i386 d = np.zeros(23 * 8, dtype=np.int8)[4:-4].view(np.float64) o = np.zeros(23 * 8, dtype=np.int8)[4:-4].view(np.float64) assert_almost_equal(d + d, d * 2) np.add(d, d, out=o) np.add(np.ones_like(d), d, out=o) np.add(d, np.ones_like(d), out=o) np.add(np.ones_like(d), d) np.add(d, np.ones_like(d)) class TestPower(TestCase): def test_small_types(self): for t in [np.int8, np.int16, np.float16]: a = t(3) b = a ** 4 assert_(b == 81, "error with %r: got %r" % (t, b)) def test_large_types(self): for t in [np.int32, np.int64, np.float32, np.float64, np.longdouble]: a = t(51) b = a ** 4 msg = "error with %r: got %r" % (t, b) if np.issubdtype(t, np.integer): assert_(b == 6765201, msg) else: assert_almost_equal(b, 6765201, err_msg=msg) def test_mixed_types(self): typelist = [np.int8, np.int16, np.float16, np.float32, np.float64, np.int8, np.int16, np.int32, np.int64] for t1 in typelist: for t2 in typelist: a = t1(3) b = t2(2) result = a**b msg = ("error with %r and %r:" "got %r, expected %r") % (t1, t2, result, 9) if np.issubdtype(np.dtype(result), np.integer): assert_(result == 9, msg) else: assert_almost_equal(result, 9, err_msg=msg) class TestComplexDivision(TestCase): def test_zero_division(self): with np.errstate(all="ignore"): for t in [np.complex64, np.complex128]: a = t(0.0) b = t(1.0) assert_(np.isinf(b/a)) b = t(complex(np.inf, np.inf)) assert_(np.isinf(b/a)) b = t(complex(np.inf, np.nan)) assert_(np.isinf(b/a)) b = t(complex(np.nan, np.inf)) assert_(np.isinf(b/a)) b = t(complex(np.nan, np.nan)) assert_(np.isnan(b/a)) b = t(0.) assert_(np.isnan(b/a)) class TestConversion(TestCase): def test_int_from_long(self): l = [1e6, 1e12, 1e18, -1e6, -1e12, -1e18] li = [10**6, 10**12, 10**18, -10**6, -10**12, -10**18] for T in [None, np.float64, np.int64]: a = np.array(l, dtype=T) assert_equal([int(_m) for _m in a], li) a = np.array(l[:3], dtype=np.uint64) assert_equal([int(_m) for _m in a], li[:3]) #class TestRepr(TestCase): # def test_repr(self): # for t in types: # val = t(1197346475.0137341) # val_repr = repr(val) # val2 = eval(val_repr) # assert_equal( val, val2 ) class TestRepr(object): def _test_type_repr(self, t): finfo=np.finfo(t) last_fraction_bit_idx = finfo.nexp + finfo.nmant last_exponent_bit_idx = finfo.nexp storage_bytes = np.dtype(t).itemsize*8 # could add some more types to the list below for which in ['small denorm', 'small norm']: # Values from http://en.wikipedia.org/wiki/IEEE_754 constr = np.array([0x00]*storage_bytes, dtype=np.uint8) if which == 'small denorm': byte = last_fraction_bit_idx // 8 bytebit = 7-(last_fraction_bit_idx % 8) constr[byte] = 1< rc_a) assert_(sys.getrefcount(dt) > rc_dt) it = None assert_equal(sys.getrefcount(a), rc_a) assert_equal(sys.getrefcount(dt), rc_dt) # With a copy a = arange(6, dtype='f4') dt = np.dtype('f4') rc_a = sys.getrefcount(a) rc_dt = sys.getrefcount(dt) it = nditer(a, [], [['readwrite']], op_dtypes=[dt]) rc2_a = sys.getrefcount(a) rc2_dt = sys.getrefcount(dt) it2 = it.copy() assert_(sys.getrefcount(a) > rc2_a) assert_(sys.getrefcount(dt) > rc2_dt) it = None assert_equal(sys.getrefcount(a), rc2_a) assert_equal(sys.getrefcount(dt), rc2_dt) it2 = None assert_equal(sys.getrefcount(a), rc_a) assert_equal(sys.getrefcount(dt), rc_dt) def test_iter_best_order(): # The iterator should always find the iteration order # with increasing memory addresses # Test the ordering for 1-D to 5-D shapes for shape in [(5,), (3, 4), (2, 3, 4), (2, 3, 4, 3), (2, 3, 2, 2, 3)]: a = arange(np.prod(shape)) # Test each combination of positive and negative strides for dirs in range(2**len(shape)): dirs_index = [slice(None)]*len(shape) for bit in range(len(shape)): if ((2**bit)&dirs): dirs_index[bit] = slice(None, None, -1) dirs_index = tuple(dirs_index) aview = a.reshape(shape)[dirs_index] # C-order i = nditer(aview, [], [['readonly']]) assert_equal([x for x in i], a) # Fortran-order i = nditer(aview.T, [], [['readonly']]) assert_equal([x for x in i], a) # Other order if len(shape) > 2: i = nditer(aview.swapaxes(0, 1), [], [['readonly']]) assert_equal([x for x in i], a) def test_iter_c_order(): # Test forcing C order # Test the ordering for 1-D to 5-D shapes for shape in [(5,), (3, 4), (2, 3, 4), (2, 3, 4, 3), (2, 3, 2, 2, 3)]: a = arange(np.prod(shape)) # Test each combination of positive and negative strides for dirs in range(2**len(shape)): dirs_index = [slice(None)]*len(shape) for bit in range(len(shape)): if ((2**bit)&dirs): dirs_index[bit] = slice(None, None, -1) dirs_index = tuple(dirs_index) aview = a.reshape(shape)[dirs_index] # C-order i = nditer(aview, order='C') assert_equal([x for x in i], aview.ravel(order='C')) # Fortran-order i = nditer(aview.T, order='C') assert_equal([x for x in i], aview.T.ravel(order='C')) # Other order if len(shape) > 2: i = nditer(aview.swapaxes(0, 1), order='C') assert_equal([x for x in i], aview.swapaxes(0, 1).ravel(order='C')) def test_iter_f_order(): # Test forcing F order # Test the ordering for 1-D to 5-D shapes for shape in [(5,), (3, 4), (2, 3, 4), (2, 3, 4, 3), (2, 3, 2, 2, 3)]: a = arange(np.prod(shape)) # Test each combination of positive and negative strides for dirs in range(2**len(shape)): dirs_index = [slice(None)]*len(shape) for bit in range(len(shape)): if ((2**bit)&dirs): dirs_index[bit] = slice(None, None, -1) dirs_index = tuple(dirs_index) aview = a.reshape(shape)[dirs_index] # C-order i = nditer(aview, order='F') assert_equal([x for x in i], aview.ravel(order='F')) # Fortran-order i = nditer(aview.T, order='F') assert_equal([x for x in i], aview.T.ravel(order='F')) # Other order if len(shape) > 2: i = nditer(aview.swapaxes(0, 1), order='F') assert_equal([x for x in i], aview.swapaxes(0, 1).ravel(order='F')) def test_iter_c_or_f_order(): # Test forcing any contiguous (C or F) order # Test the ordering for 1-D to 5-D shapes for shape in [(5,), (3, 4), (2, 3, 4), (2, 3, 4, 3), (2, 3, 2, 2, 3)]: a = arange(np.prod(shape)) # Test each combination of positive and negative strides for dirs in range(2**len(shape)): dirs_index = [slice(None)]*len(shape) for bit in range(len(shape)): if ((2**bit)&dirs): dirs_index[bit] = slice(None, None, -1) dirs_index = tuple(dirs_index) aview = a.reshape(shape)[dirs_index] # C-order i = nditer(aview, order='A') assert_equal([x for x in i], aview.ravel(order='A')) # Fortran-order i = nditer(aview.T, order='A') assert_equal([x for x in i], aview.T.ravel(order='A')) # Other order if len(shape) > 2: i = nditer(aview.swapaxes(0, 1), order='A') assert_equal([x for x in i], aview.swapaxes(0, 1).ravel(order='A')) def test_iter_best_order_multi_index_1d(): # The multi-indices should be correct with any reordering a = arange(4) # 1D order i = nditer(a, ['multi_index'], [['readonly']]) assert_equal(iter_multi_index(i), [(0,), (1,), (2,), (3,)]) # 1D reversed order i = nditer(a[::-1], ['multi_index'], [['readonly']]) assert_equal(iter_multi_index(i), [(3,), (2,), (1,), (0,)]) def test_iter_best_order_multi_index_2d(): # The multi-indices should be correct with any reordering a = arange(6) # 2D C-order i = nditer(a.reshape(2, 3), ['multi_index'], [['readonly']]) assert_equal(iter_multi_index(i), [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2)]) # 2D Fortran-order i = nditer(a.reshape(2, 3).copy(order='F'), ['multi_index'], [['readonly']]) assert_equal(iter_multi_index(i), [(0, 0), (1, 0), (0, 1), (1, 1), (0, 2), (1, 2)]) # 2D reversed C-order i = nditer(a.reshape(2, 3)[::-1], ['multi_index'], [['readonly']]) assert_equal(iter_multi_index(i), [(1, 0), (1, 1), (1, 2), (0, 0), (0, 1), (0, 2)]) i = nditer(a.reshape(2, 3)[:, ::-1], ['multi_index'], [['readonly']]) assert_equal(iter_multi_index(i), [(0, 2), (0, 1), (0, 0), (1, 2), (1, 1), (1, 0)]) i = nditer(a.reshape(2, 3)[::-1, ::-1], ['multi_index'], [['readonly']]) assert_equal(iter_multi_index(i), [(1, 2), (1, 1), (1, 0), (0, 2), (0, 1), (0, 0)]) # 2D reversed Fortran-order i = nditer(a.reshape(2, 3).copy(order='F')[::-1], ['multi_index'], [['readonly']]) assert_equal(iter_multi_index(i), [(1, 0), (0, 0), (1, 1), (0, 1), (1, 2), (0, 2)]) i = nditer(a.reshape(2, 3).copy(order='F')[:, ::-1], ['multi_index'], [['readonly']]) assert_equal(iter_multi_index(i), [(0, 2), (1, 2), (0, 1), (1, 1), (0, 0), (1, 0)]) i = nditer(a.reshape(2, 3).copy(order='F')[::-1, ::-1], ['multi_index'], [['readonly']]) assert_equal(iter_multi_index(i), [(1, 2), (0, 2), (1, 1), (0, 1), (1, 0), (0, 0)]) def test_iter_best_order_multi_index_3d(): # The multi-indices should be correct with any reordering a = arange(12) # 3D C-order i = nditer(a.reshape(2, 3, 2), ['multi_index'], [['readonly']]) assert_equal(iter_multi_index(i), [(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), (0, 2, 0), (0, 2, 1), (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1), (1, 2, 0), (1, 2, 1)]) # 3D Fortran-order i = nditer(a.reshape(2, 3, 2).copy(order='F'), ['multi_index'], [['readonly']]) assert_equal(iter_multi_index(i), [(0, 0, 0), (1, 0, 0), (0, 1, 0), (1, 1, 0), (0, 2, 0), (1, 2, 0), (0, 0, 1), (1, 0, 1), (0, 1, 1), (1, 1, 1), (0, 2, 1), (1, 2, 1)]) # 3D reversed C-order i = nditer(a.reshape(2, 3, 2)[::-1], ['multi_index'], [['readonly']]) assert_equal(iter_multi_index(i), [(1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1), (1, 2, 0), (1, 2, 1), (0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), (0, 2, 0), (0, 2, 1)]) i = nditer(a.reshape(2, 3, 2)[:, ::-1], ['multi_index'], [['readonly']]) assert_equal(iter_multi_index(i), [(0, 2, 0), (0, 2, 1), (0, 1, 0), (0, 1, 1), (0, 0, 0), (0, 0, 1), (1, 2, 0), (1, 2, 1), (1, 1, 0), (1, 1, 1), (1, 0, 0), (1, 0, 1)]) i = nditer(a.reshape(2, 3, 2)[:,:, ::-1], ['multi_index'], [['readonly']]) assert_equal(iter_multi_index(i), [(0, 0, 1), (0, 0, 0), (0, 1, 1), (0, 1, 0), (0, 2, 1), (0, 2, 0), (1, 0, 1), (1, 0, 0), (1, 1, 1), (1, 1, 0), (1, 2, 1), (1, 2, 0)]) # 3D reversed Fortran-order i = nditer(a.reshape(2, 3, 2).copy(order='F')[::-1], ['multi_index'], [['readonly']]) assert_equal(iter_multi_index(i), [(1, 0, 0), (0, 0, 0), (1, 1, 0), (0, 1, 0), (1, 2, 0), (0, 2, 0), (1, 0, 1), (0, 0, 1), (1, 1, 1), (0, 1, 1), (1, 2, 1), (0, 2, 1)]) i = nditer(a.reshape(2, 3, 2).copy(order='F')[:, ::-1], ['multi_index'], [['readonly']]) assert_equal(iter_multi_index(i), [(0, 2, 0), (1, 2, 0), (0, 1, 0), (1, 1, 0), (0, 0, 0), (1, 0, 0), (0, 2, 1), (1, 2, 1), (0, 1, 1), (1, 1, 1), (0, 0, 1), (1, 0, 1)]) i = nditer(a.reshape(2, 3, 2).copy(order='F')[:,:, ::-1], ['multi_index'], [['readonly']]) assert_equal(iter_multi_index(i), [(0, 0, 1), (1, 0, 1), (0, 1, 1), (1, 1, 1), (0, 2, 1), (1, 2, 1), (0, 0, 0), (1, 0, 0), (0, 1, 0), (1, 1, 0), (0, 2, 0), (1, 2, 0)]) def test_iter_best_order_c_index_1d(): # The C index should be correct with any reordering a = arange(4) # 1D order i = nditer(a, ['c_index'], [['readonly']]) assert_equal(iter_indices(i), [0, 1, 2, 3]) # 1D reversed order i = nditer(a[::-1], ['c_index'], [['readonly']]) assert_equal(iter_indices(i), [3, 2, 1, 0]) def test_iter_best_order_c_index_2d(): # The C index should be correct with any reordering a = arange(6) # 2D C-order i = nditer(a.reshape(2, 3), ['c_index'], [['readonly']]) assert_equal(iter_indices(i), [0, 1, 2, 3, 4, 5]) # 2D Fortran-order i = nditer(a.reshape(2, 3).copy(order='F'), ['c_index'], [['readonly']]) assert_equal(iter_indices(i), [0, 3, 1, 4, 2, 5]) # 2D reversed C-order i = nditer(a.reshape(2, 3)[::-1], ['c_index'], [['readonly']]) assert_equal(iter_indices(i), [3, 4, 5, 0, 1, 2]) i = nditer(a.reshape(2, 3)[:, ::-1], ['c_index'], [['readonly']]) assert_equal(iter_indices(i), [2, 1, 0, 5, 4, 3]) i = nditer(a.reshape(2, 3)[::-1, ::-1], ['c_index'], [['readonly']]) assert_equal(iter_indices(i), [5, 4, 3, 2, 1, 0]) # 2D reversed Fortran-order i = nditer(a.reshape(2, 3).copy(order='F')[::-1], ['c_index'], [['readonly']]) assert_equal(iter_indices(i), [3, 0, 4, 1, 5, 2]) i = nditer(a.reshape(2, 3).copy(order='F')[:, ::-1], ['c_index'], [['readonly']]) assert_equal(iter_indices(i), [2, 5, 1, 4, 0, 3]) i = nditer(a.reshape(2, 3).copy(order='F')[::-1, ::-1], ['c_index'], [['readonly']]) assert_equal(iter_indices(i), [5, 2, 4, 1, 3, 0]) def test_iter_best_order_c_index_3d(): # The C index should be correct with any reordering a = arange(12) # 3D C-order i = nditer(a.reshape(2, 3, 2), ['c_index'], [['readonly']]) assert_equal(iter_indices(i), [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]) # 3D Fortran-order i = nditer(a.reshape(2, 3, 2).copy(order='F'), ['c_index'], [['readonly']]) assert_equal(iter_indices(i), [0, 6, 2, 8, 4, 10, 1, 7, 3, 9, 5, 11]) # 3D reversed C-order i = nditer(a.reshape(2, 3, 2)[::-1], ['c_index'], [['readonly']]) assert_equal(iter_indices(i), [6, 7, 8, 9, 10, 11, 0, 1, 2, 3, 4, 5]) i = nditer(a.reshape(2, 3, 2)[:, ::-1], ['c_index'], [['readonly']]) assert_equal(iter_indices(i), [4, 5, 2, 3, 0, 1, 10, 11, 8, 9, 6, 7]) i = nditer(a.reshape(2, 3, 2)[:,:, ::-1], ['c_index'], [['readonly']]) assert_equal(iter_indices(i), [1, 0, 3, 2, 5, 4, 7, 6, 9, 8, 11, 10]) # 3D reversed Fortran-order i = nditer(a.reshape(2, 3, 2).copy(order='F')[::-1], ['c_index'], [['readonly']]) assert_equal(iter_indices(i), [6, 0, 8, 2, 10, 4, 7, 1, 9, 3, 11, 5]) i = nditer(a.reshape(2, 3, 2).copy(order='F')[:, ::-1], ['c_index'], [['readonly']]) assert_equal(iter_indices(i), [4, 10, 2, 8, 0, 6, 5, 11, 3, 9, 1, 7]) i = nditer(a.reshape(2, 3, 2).copy(order='F')[:,:, ::-1], ['c_index'], [['readonly']]) assert_equal(iter_indices(i), [1, 7, 3, 9, 5, 11, 0, 6, 2, 8, 4, 10]) def test_iter_best_order_f_index_1d(): # The Fortran index should be correct with any reordering a = arange(4) # 1D order i = nditer(a, ['f_index'], [['readonly']]) assert_equal(iter_indices(i), [0, 1, 2, 3]) # 1D reversed order i = nditer(a[::-1], ['f_index'], [['readonly']]) assert_equal(iter_indices(i), [3, 2, 1, 0]) def test_iter_best_order_f_index_2d(): # The Fortran index should be correct with any reordering a = arange(6) # 2D C-order i = nditer(a.reshape(2, 3), ['f_index'], [['readonly']]) assert_equal(iter_indices(i), [0, 2, 4, 1, 3, 5]) # 2D Fortran-order i = nditer(a.reshape(2, 3).copy(order='F'), ['f_index'], [['readonly']]) assert_equal(iter_indices(i), [0, 1, 2, 3, 4, 5]) # 2D reversed C-order i = nditer(a.reshape(2, 3)[::-1], ['f_index'], [['readonly']]) assert_equal(iter_indices(i), [1, 3, 5, 0, 2, 4]) i = nditer(a.reshape(2, 3)[:, ::-1], ['f_index'], [['readonly']]) assert_equal(iter_indices(i), [4, 2, 0, 5, 3, 1]) i = nditer(a.reshape(2, 3)[::-1, ::-1], ['f_index'], [['readonly']]) assert_equal(iter_indices(i), [5, 3, 1, 4, 2, 0]) # 2D reversed Fortran-order i = nditer(a.reshape(2, 3).copy(order='F')[::-1], ['f_index'], [['readonly']]) assert_equal(iter_indices(i), [1, 0, 3, 2, 5, 4]) i = nditer(a.reshape(2, 3).copy(order='F')[:, ::-1], ['f_index'], [['readonly']]) assert_equal(iter_indices(i), [4, 5, 2, 3, 0, 1]) i = nditer(a.reshape(2, 3).copy(order='F')[::-1, ::-1], ['f_index'], [['readonly']]) assert_equal(iter_indices(i), [5, 4, 3, 2, 1, 0]) def test_iter_best_order_f_index_3d(): # The Fortran index should be correct with any reordering a = arange(12) # 3D C-order i = nditer(a.reshape(2, 3, 2), ['f_index'], [['readonly']]) assert_equal(iter_indices(i), [0, 6, 2, 8, 4, 10, 1, 7, 3, 9, 5, 11]) # 3D Fortran-order i = nditer(a.reshape(2, 3, 2).copy(order='F'), ['f_index'], [['readonly']]) assert_equal(iter_indices(i), [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]) # 3D reversed C-order i = nditer(a.reshape(2, 3, 2)[::-1], ['f_index'], [['readonly']]) assert_equal(iter_indices(i), [1, 7, 3, 9, 5, 11, 0, 6, 2, 8, 4, 10]) i = nditer(a.reshape(2, 3, 2)[:, ::-1], ['f_index'], [['readonly']]) assert_equal(iter_indices(i), [4, 10, 2, 8, 0, 6, 5, 11, 3, 9, 1, 7]) i = nditer(a.reshape(2, 3, 2)[:,:, ::-1], ['f_index'], [['readonly']]) assert_equal(iter_indices(i), [6, 0, 8, 2, 10, 4, 7, 1, 9, 3, 11, 5]) # 3D reversed Fortran-order i = nditer(a.reshape(2, 3, 2).copy(order='F')[::-1], ['f_index'], [['readonly']]) assert_equal(iter_indices(i), [1, 0, 3, 2, 5, 4, 7, 6, 9, 8, 11, 10]) i = nditer(a.reshape(2, 3, 2).copy(order='F')[:, ::-1], ['f_index'], [['readonly']]) assert_equal(iter_indices(i), [4, 5, 2, 3, 0, 1, 10, 11, 8, 9, 6, 7]) i = nditer(a.reshape(2, 3, 2).copy(order='F')[:,:, ::-1], ['f_index'], [['readonly']]) assert_equal(iter_indices(i), [6, 7, 8, 9, 10, 11, 0, 1, 2, 3, 4, 5]) def test_iter_no_inner_full_coalesce(): # Check no_inner iterators which coalesce into a single inner loop for shape in [(5,), (3, 4), (2, 3, 4), (2, 3, 4, 3), (2, 3, 2, 2, 3)]: size = np.prod(shape) a = arange(size) # Test each combination of forward and backwards indexing for dirs in range(2**len(shape)): dirs_index = [slice(None)]*len(shape) for bit in range(len(shape)): if ((2**bit)&dirs): dirs_index[bit] = slice(None, None, -1) dirs_index = tuple(dirs_index) aview = a.reshape(shape)[dirs_index] # C-order i = nditer(aview, ['external_loop'], [['readonly']]) assert_equal(i.ndim, 1) assert_equal(i[0].shape, (size,)) # Fortran-order i = nditer(aview.T, ['external_loop'], [['readonly']]) assert_equal(i.ndim, 1) assert_equal(i[0].shape, (size,)) # Other order if len(shape) > 2: i = nditer(aview.swapaxes(0, 1), ['external_loop'], [['readonly']]) assert_equal(i.ndim, 1) assert_equal(i[0].shape, (size,)) def test_iter_no_inner_dim_coalescing(): # Check no_inner iterators whose dimensions may not coalesce completely # Skipping the last element in a dimension prevents coalescing # with the next-bigger dimension a = arange(24).reshape(2, 3, 4)[:,:, :-1] i = nditer(a, ['external_loop'], [['readonly']]) assert_equal(i.ndim, 2) assert_equal(i[0].shape, (3,)) a = arange(24).reshape(2, 3, 4)[:, :-1,:] i = nditer(a, ['external_loop'], [['readonly']]) assert_equal(i.ndim, 2) assert_equal(i[0].shape, (8,)) a = arange(24).reshape(2, 3, 4)[:-1,:,:] i = nditer(a, ['external_loop'], [['readonly']]) assert_equal(i.ndim, 1) assert_equal(i[0].shape, (12,)) # Even with lots of 1-sized dimensions, should still coalesce a = arange(24).reshape(1, 1, 2, 1, 1, 3, 1, 1, 4, 1, 1) i = nditer(a, ['external_loop'], [['readonly']]) assert_equal(i.ndim, 1) assert_equal(i[0].shape, (24,)) def test_iter_dim_coalescing(): # Check that the correct number of dimensions are coalesced # Tracking a multi-index disables coalescing a = arange(24).reshape(2, 3, 4) i = nditer(a, ['multi_index'], [['readonly']]) assert_equal(i.ndim, 3) # A tracked index can allow coalescing if it's compatible with the array a3d = arange(24).reshape(2, 3, 4) i = nditer(a3d, ['c_index'], [['readonly']]) assert_equal(i.ndim, 1) i = nditer(a3d.swapaxes(0, 1), ['c_index'], [['readonly']]) assert_equal(i.ndim, 3) i = nditer(a3d.T, ['c_index'], [['readonly']]) assert_equal(i.ndim, 3) i = nditer(a3d.T, ['f_index'], [['readonly']]) assert_equal(i.ndim, 1) i = nditer(a3d.T.swapaxes(0, 1), ['f_index'], [['readonly']]) assert_equal(i.ndim, 3) # When C or F order is forced, coalescing may still occur a3d = arange(24).reshape(2, 3, 4) i = nditer(a3d, order='C') assert_equal(i.ndim, 1) i = nditer(a3d.T, order='C') assert_equal(i.ndim, 3) i = nditer(a3d, order='F') assert_equal(i.ndim, 3) i = nditer(a3d.T, order='F') assert_equal(i.ndim, 1) i = nditer(a3d, order='A') assert_equal(i.ndim, 1) i = nditer(a3d.T, order='A') assert_equal(i.ndim, 1) def test_iter_broadcasting(): # Standard NumPy broadcasting rules # 1D with scalar i = nditer([arange(6), np.int32(2)], ['multi_index'], [['readonly']]*2) assert_equal(i.itersize, 6) assert_equal(i.shape, (6,)) # 2D with scalar i = nditer([arange(6).reshape(2, 3), np.int32(2)], ['multi_index'], [['readonly']]*2) assert_equal(i.itersize, 6) assert_equal(i.shape, (2, 3)) # 2D with 1D i = nditer([arange(6).reshape(2, 3), arange(3)], ['multi_index'], [['readonly']]*2) assert_equal(i.itersize, 6) assert_equal(i.shape, (2, 3)) i = nditer([arange(2).reshape(2, 1), arange(3)], ['multi_index'], [['readonly']]*2) assert_equal(i.itersize, 6) assert_equal(i.shape, (2, 3)) # 2D with 2D i = nditer([arange(2).reshape(2, 1), arange(3).reshape(1, 3)], ['multi_index'], [['readonly']]*2) assert_equal(i.itersize, 6) assert_equal(i.shape, (2, 3)) # 3D with scalar i = nditer([np.int32(2), arange(24).reshape(4, 2, 3)], ['multi_index'], [['readonly']]*2) assert_equal(i.itersize, 24) assert_equal(i.shape, (4, 2, 3)) # 3D with 1D i = nditer([arange(3), arange(24).reshape(4, 2, 3)], ['multi_index'], [['readonly']]*2) assert_equal(i.itersize, 24) assert_equal(i.shape, (4, 2, 3)) i = nditer([arange(3), arange(8).reshape(4, 2, 1)], ['multi_index'], [['readonly']]*2) assert_equal(i.itersize, 24) assert_equal(i.shape, (4, 2, 3)) # 3D with 2D i = nditer([arange(6).reshape(2, 3), arange(24).reshape(4, 2, 3)], ['multi_index'], [['readonly']]*2) assert_equal(i.itersize, 24) assert_equal(i.shape, (4, 2, 3)) i = nditer([arange(2).reshape(2, 1), arange(24).reshape(4, 2, 3)], ['multi_index'], [['readonly']]*2) assert_equal(i.itersize, 24) assert_equal(i.shape, (4, 2, 3)) i = nditer([arange(3).reshape(1, 3), arange(8).reshape(4, 2, 1)], ['multi_index'], [['readonly']]*2) assert_equal(i.itersize, 24) assert_equal(i.shape, (4, 2, 3)) # 3D with 3D i = nditer([arange(2).reshape(1, 2, 1), arange(3).reshape(1, 1, 3), arange(4).reshape(4, 1, 1)], ['multi_index'], [['readonly']]*3) assert_equal(i.itersize, 24) assert_equal(i.shape, (4, 2, 3)) i = nditer([arange(6).reshape(1, 2, 3), arange(4).reshape(4, 1, 1)], ['multi_index'], [['readonly']]*2) assert_equal(i.itersize, 24) assert_equal(i.shape, (4, 2, 3)) i = nditer([arange(24).reshape(4, 2, 3), arange(12).reshape(4, 1, 3)], ['multi_index'], [['readonly']]*2) assert_equal(i.itersize, 24) assert_equal(i.shape, (4, 2, 3)) def test_iter_itershape(): # Check that allocated outputs work with a specified shape a = np.arange(6, dtype='i2').reshape(2, 3) i = nditer([a, None], [], [['readonly'], ['writeonly', 'allocate']], op_axes=[[0, 1, None], None], itershape=(-1, -1, 4)) assert_equal(i.operands[1].shape, (2, 3, 4)) assert_equal(i.operands[1].strides, (24, 8, 2)) i = nditer([a.T, None], [], [['readonly'], ['writeonly', 'allocate']], op_axes=[[0, 1, None], None], itershape=(-1, -1, 4)) assert_equal(i.operands[1].shape, (3, 2, 4)) assert_equal(i.operands[1].strides, (8, 24, 2)) i = nditer([a.T, None], [], [['readonly'], ['writeonly', 'allocate']], order='F', op_axes=[[0, 1, None], None], itershape=(-1, -1, 4)) assert_equal(i.operands[1].shape, (3, 2, 4)) assert_equal(i.operands[1].strides, (2, 6, 12)) # If we specify 1 in the itershape, it shouldn't allow broadcasting # of that dimension to a bigger value assert_raises(ValueError, nditer, [a, None], [], [['readonly'], ['writeonly', 'allocate']], op_axes=[[0, 1, None], None], itershape=(-1, 1, 4)) # Test bug that for no op_axes but itershape, they are NULLed correctly i = np.nditer([np.ones(2), None, None], itershape=(2,)) def test_iter_broadcasting_errors(): # Check that errors are thrown for bad broadcasting shapes # 1D with 1D assert_raises(ValueError, nditer, [arange(2), arange(3)], [], [['readonly']]*2) # 2D with 1D assert_raises(ValueError, nditer, [arange(6).reshape(2, 3), arange(2)], [], [['readonly']]*2) # 2D with 2D assert_raises(ValueError, nditer, [arange(6).reshape(2, 3), arange(9).reshape(3, 3)], [], [['readonly']]*2) assert_raises(ValueError, nditer, [arange(6).reshape(2, 3), arange(4).reshape(2, 2)], [], [['readonly']]*2) # 3D with 3D assert_raises(ValueError, nditer, [arange(36).reshape(3, 3, 4), arange(24).reshape(2, 3, 4)], [], [['readonly']]*2) assert_raises(ValueError, nditer, [arange(8).reshape(2, 4, 1), arange(24).reshape(2, 3, 4)], [], [['readonly']]*2) # Verify that the error message mentions the right shapes try: i = nditer([arange(2).reshape(1, 2, 1), arange(3).reshape(1, 3), arange(6).reshape(2, 3)], [], [['readonly'], ['readonly'], ['writeonly', 'no_broadcast']]) assert_(False, 'Should have raised a broadcast error') except ValueError as e: msg = str(e) # The message should contain the shape of the 3rd operand assert_(msg.find('(2,3)') >= 0, 'Message "%s" doesn\'t contain operand shape (2,3)' % msg) # The message should contain the broadcast shape assert_(msg.find('(1,2,3)') >= 0, 'Message "%s" doesn\'t contain broadcast shape (1,2,3)' % msg) try: i = nditer([arange(6).reshape(2, 3), arange(2)], [], [['readonly'], ['readonly']], op_axes=[[0, 1], [0, np.newaxis]], itershape=(4, 3)) assert_(False, 'Should have raised a broadcast error') except ValueError as e: msg = str(e) # 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, ('Message "%s" doesn\'t contain remapped operand shape' + '(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) try: i = nditer([np.zeros((2, 1, 1)), np.zeros((2,))], [], [['writeonly', 'no_broadcast'], ['readonly']]) assert_(False, 'Should have raised a broadcast error') except ValueError as e: msg = str(e) # The message should contain the shape of the bad operand assert_(msg.find('(2,1,1)') >= 0, 'Message "%s" doesn\'t contain operand shape (2,1,1)' % msg) # The message should contain the broadcast shape assert_(msg.find('(2,1,2)') >= 0, 'Message "%s" doesn\'t contain the broadcast shape (2,1,2)' % msg) def test_iter_flags_errors(): # Check that bad combinations of flags produce errors a = arange(6) # Not enough operands assert_raises(ValueError, nditer, [], [], []) # Too many operands assert_raises(ValueError, nditer, [a]*100, [], [['readonly']]*100) # Bad global flag assert_raises(ValueError, nditer, [a], ['bad flag'], [['readonly']]) # Bad op flag assert_raises(ValueError, nditer, [a], [], [['readonly', 'bad flag']]) # Bad order parameter assert_raises(ValueError, nditer, [a], [], [['readonly']], order='G') # Bad casting parameter assert_raises(ValueError, nditer, [a], [], [['readonly']], casting='noon') # op_flags must match ops assert_raises(ValueError, nditer, [a]*3, [], [['readonly']]*2) # Cannot track both a C and an F index assert_raises(ValueError, nditer, a, ['c_index', 'f_index'], [['readonly']]) # Inner iteration and multi-indices/indices are incompatible assert_raises(ValueError, nditer, a, ['external_loop', 'multi_index'], [['readonly']]) assert_raises(ValueError, nditer, a, ['external_loop', 'c_index'], [['readonly']]) assert_raises(ValueError, nditer, a, ['external_loop', 'f_index'], [['readonly']]) # Must specify exactly one of readwrite/readonly/writeonly per operand assert_raises(ValueError, nditer, a, [], [[]]) assert_raises(ValueError, nditer, a, [], [['readonly', 'writeonly']]) assert_raises(ValueError, nditer, a, [], [['readonly', 'readwrite']]) assert_raises(ValueError, nditer, a, [], [['writeonly', 'readwrite']]) assert_raises(ValueError, nditer, a, [], [['readonly', 'writeonly', 'readwrite']]) # Python scalars are always readonly assert_raises(TypeError, nditer, 1.5, [], [['writeonly']]) assert_raises(TypeError, nditer, 1.5, [], [['readwrite']]) # Array scalars are always readonly assert_raises(TypeError, nditer, np.int32(1), [], [['writeonly']]) assert_raises(TypeError, nditer, np.int32(1), [], [['readwrite']]) # Check readonly array a.flags.writeable = False assert_raises(ValueError, nditer, a, [], [['writeonly']]) assert_raises(ValueError, nditer, a, [], [['readwrite']]) a.flags.writeable = True # Multi-indices available only with the multi_index flag i = nditer(arange(6), [], [['readonly']]) assert_raises(ValueError, lambda i:i.multi_index, i) # Index available only with an index flag assert_raises(ValueError, lambda i:i.index, i) # GotoCoords and GotoIndex incompatible with buffering or no_inner def assign_multi_index(i): i.multi_index = (0,) def assign_index(i): i.index = 0 def assign_iterindex(i): i.iterindex = 0; def assign_iterrange(i): i.iterrange = (0, 1); i = nditer(arange(6), ['external_loop']) assert_raises(ValueError, assign_multi_index, i) assert_raises(ValueError, assign_index, i) assert_raises(ValueError, assign_iterindex, i) assert_raises(ValueError, assign_iterrange, i) i = nditer(arange(6), ['buffered']) assert_raises(ValueError, assign_multi_index, i) assert_raises(ValueError, assign_index, i) assert_raises(ValueError, assign_iterrange, i) # Can't iterate if size is zero assert_raises(ValueError, nditer, np.array([])) def test_iter_slice(): a, b, c = np.arange(3), np.arange(3), np.arange(3.) i = nditer([a, b, c], [], ['readwrite']) i[0:2] = (3, 3) assert_equal(a, [3, 1, 2]) assert_equal(b, [3, 1, 2]) assert_equal(c, [0, 1, 2]) i[1] = 12 assert_equal(i[0:2], [3, 12]) def test_iter_nbo_align_contig(): # Check that byte order, alignment, and contig changes work # Byte order change by requesting a specific dtype a = np.arange(6, dtype='f4') au = a.byteswap().newbyteorder() assert_(a.dtype.byteorder != au.dtype.byteorder) i = nditer(au, [], [['readwrite', 'updateifcopy']], casting='equiv', op_dtypes=[np.dtype('f4')]) assert_equal(i.dtypes[0].byteorder, a.dtype.byteorder) assert_equal(i.operands[0].dtype.byteorder, a.dtype.byteorder) assert_equal(i.operands[0], a) i.operands[0][:] = 2 i = None assert_equal(au, [2]*6) # Byte order change by requesting NBO a = np.arange(6, dtype='f4') au = a.byteswap().newbyteorder() assert_(a.dtype.byteorder != au.dtype.byteorder) i = nditer(au, [], [['readwrite', 'updateifcopy', 'nbo']], casting='equiv') assert_equal(i.dtypes[0].byteorder, a.dtype.byteorder) assert_equal(i.operands[0].dtype.byteorder, a.dtype.byteorder) assert_equal(i.operands[0], a) i.operands[0][:] = 2 i = None assert_equal(au, [2]*6) # Unaligned input a = np.zeros((6*4+1,), dtype='i1')[1:] a.dtype = 'f4' a[:] = np.arange(6, dtype='f4') assert_(not a.flags.aligned) # Without 'aligned', shouldn't copy i = nditer(a, [], [['readonly']]) assert_(not i.operands[0].flags.aligned) assert_equal(i.operands[0], a); # With 'aligned', should make a copy i = nditer(a, [], [['readwrite', 'updateifcopy', 'aligned']]) assert_(i.operands[0].flags.aligned) assert_equal(i.operands[0], a); i.operands[0][:] = 3 i = None assert_equal(a, [3]*6) # Discontiguous input a = arange(12) # If it is contiguous, shouldn't copy i = nditer(a[:6], [], [['readonly']]) assert_(i.operands[0].flags.contiguous) assert_equal(i.operands[0], a[:6]); # If it isn't contiguous, should buffer i = nditer(a[::2], ['buffered', 'external_loop'], [['readonly', 'contig']], buffersize=10) assert_(i[0].flags.contiguous) assert_equal(i[0], a[::2]) def test_iter_array_cast(): # Check that arrays are cast as requested # No cast 'f4' -> 'f4' a = np.arange(6, dtype='f4').reshape(2, 3) i = nditer(a, [], [['readwrite']], op_dtypes=[np.dtype('f4')]) assert_equal(i.operands[0], a) assert_equal(i.operands[0].dtype, np.dtype('f4')) # Byte-order cast ' '>f4' a = np.arange(6, dtype='f4')]) assert_equal(i.operands[0], a) assert_equal(i.operands[0].dtype, np.dtype('>f4')) # Safe case 'f4' -> 'f8' a = np.arange(24, dtype='f4').reshape(2, 3, 4).swapaxes(1, 2) i = nditer(a, [], [['readonly', 'copy']], casting='safe', op_dtypes=[np.dtype('f8')]) assert_equal(i.operands[0], a) assert_equal(i.operands[0].dtype, np.dtype('f8')) # The memory layout of the temporary should match a (a is (48,4,16)) # except negative strides get flipped to positive strides. assert_equal(i.operands[0].strides, (96, 8, 32)) a = a[::-1,:, ::-1] i = nditer(a, [], [['readonly', 'copy']], casting='safe', op_dtypes=[np.dtype('f8')]) assert_equal(i.operands[0], a) assert_equal(i.operands[0].dtype, np.dtype('f8')) assert_equal(i.operands[0].strides, (96, 8, 32)) # Same-kind cast 'f8' -> 'f4' -> 'f8' a = np.arange(24, dtype='f8').reshape(2, 3, 4).T i = nditer(a, [], [['readwrite', 'updateifcopy']], casting='same_kind', op_dtypes=[np.dtype('f4')]) assert_equal(i.operands[0], a) assert_equal(i.operands[0].dtype, np.dtype('f4')) assert_equal(i.operands[0].strides, (4, 16, 48)) # Check that UPDATEIFCOPY is activated i.operands[0][2, 1, 1] = -12.5 assert_(a[2, 1, 1] != -12.5) i = None assert_equal(a[2, 1, 1], -12.5) a = np.arange(6, dtype='i4')[::-2] i = nditer(a, [], [['writeonly', 'updateifcopy']], casting='unsafe', op_dtypes=[np.dtype('f4')]) assert_equal(i.operands[0].dtype, np.dtype('f4')) # Even though the stride was negative in 'a', it # becomes positive in the temporary assert_equal(i.operands[0].strides, (4,)) i.operands[0][:] = [1, 2, 3] i = None assert_equal(a, [1, 2, 3]) def test_iter_array_cast_errors(): # Check that invalid casts are caught # Need to enable copying for casts to occur assert_raises(TypeError, nditer, arange(2, dtype='f4'), [], [['readonly']], op_dtypes=[np.dtype('f8')]) # Also need to allow casting for casts to occur assert_raises(TypeError, nditer, arange(2, dtype='f4'), [], [['readonly', 'copy']], casting='no', op_dtypes=[np.dtype('f8')]) assert_raises(TypeError, nditer, arange(2, dtype='f4'), [], [['readonly', 'copy']], casting='equiv', op_dtypes=[np.dtype('f8')]) assert_raises(TypeError, nditer, arange(2, dtype='f8'), [], [['writeonly', 'updateifcopy']], casting='no', op_dtypes=[np.dtype('f4')]) assert_raises(TypeError, nditer, arange(2, dtype='f8'), [], [['writeonly', 'updateifcopy']], casting='equiv', op_dtypes=[np.dtype('f4')]) # ' '>f4' should not work with casting='no' assert_raises(TypeError, nditer, arange(2, dtype='f4')]) # 'f4' -> 'f8' is a safe cast, but 'f8' -> 'f4' isn't assert_raises(TypeError, nditer, arange(2, dtype='f4'), [], [['readwrite', 'updateifcopy']], casting='safe', op_dtypes=[np.dtype('f8')]) assert_raises(TypeError, nditer, arange(2, dtype='f8'), [], [['readwrite', 'updateifcopy']], casting='safe', op_dtypes=[np.dtype('f4')]) # 'f4' -> 'i4' is neither a safe nor a same-kind cast assert_raises(TypeError, nditer, arange(2, dtype='f4'), [], [['readonly', 'copy']], casting='same_kind', op_dtypes=[np.dtype('i4')]) assert_raises(TypeError, nditer, arange(2, dtype='i4'), [], [['writeonly', 'updateifcopy']], casting='same_kind', op_dtypes=[np.dtype('f4')]) def test_iter_scalar_cast(): # Check that scalars are cast as requested # No cast 'f4' -> 'f4' i = nditer(np.float32(2.5), [], [['readonly']], op_dtypes=[np.dtype('f4')]) assert_equal(i.dtypes[0], np.dtype('f4')) assert_equal(i.value.dtype, np.dtype('f4')) assert_equal(i.value, 2.5) # Safe cast 'f4' -> 'f8' i = nditer(np.float32(2.5), [], [['readonly', 'copy']], casting='safe', op_dtypes=[np.dtype('f8')]) assert_equal(i.dtypes[0], np.dtype('f8')) assert_equal(i.value.dtype, np.dtype('f8')) assert_equal(i.value, 2.5) # Same-kind cast 'f8' -> 'f4' i = nditer(np.float64(2.5), [], [['readonly', 'copy']], casting='same_kind', op_dtypes=[np.dtype('f4')]) assert_equal(i.dtypes[0], np.dtype('f4')) assert_equal(i.value.dtype, np.dtype('f4')) assert_equal(i.value, 2.5) # Unsafe cast 'f8' -> 'i4' i = nditer(np.float64(3.0), [], [['readonly', 'copy']], casting='unsafe', op_dtypes=[np.dtype('i4')]) assert_equal(i.dtypes[0], np.dtype('i4')) assert_equal(i.value.dtype, np.dtype('i4')) assert_equal(i.value, 3) # Readonly scalars may be cast even without setting COPY or BUFFERED i = nditer(3, [], [['readonly']], op_dtypes=[np.dtype('f8')]) assert_equal(i[0].dtype, np.dtype('f8')) assert_equal(i[0], 3.) def test_iter_scalar_cast_errors(): # Check that invalid casts are caught # Need to allow copying/buffering for write casts of scalars to occur assert_raises(TypeError, nditer, np.float32(2), [], [['readwrite']], op_dtypes=[np.dtype('f8')]) assert_raises(TypeError, nditer, 2.5, [], [['readwrite']], op_dtypes=[np.dtype('f4')]) # 'f8' -> 'f4' isn't a safe cast if the value would overflow assert_raises(TypeError, nditer, np.float64(1e60), [], [['readonly']], casting='safe', op_dtypes=[np.dtype('f4')]) # 'f4' -> 'i4' is neither a safe nor a same-kind cast assert_raises(TypeError, nditer, np.float32(2), [], [['readonly']], casting='same_kind', op_dtypes=[np.dtype('i4')]) def test_iter_object_arrays_basic(): # Check that object arrays work obj = {'a':3,'b':'d'} a = np.array([[1, 2, 3], None, obj, None], dtype='O') rc = sys.getrefcount(obj) # Need to allow references for object arrays assert_raises(TypeError, nditer, a) assert_equal(sys.getrefcount(obj), rc) i = nditer(a, ['refs_ok'], ['readonly']) vals = [x[()] for x in i] assert_equal(np.array(vals, dtype='O'), a) vals, i, x = [None]*3 assert_equal(sys.getrefcount(obj), rc) i = nditer(a.reshape(2, 2).T, ['refs_ok', 'buffered'], ['readonly'], order='C') assert_(i.iterationneedsapi) vals = [x[()] for x in i] assert_equal(np.array(vals, dtype='O'), a.reshape(2, 2).ravel(order='F')) vals, i, x = [None]*3 assert_equal(sys.getrefcount(obj), rc) i = nditer(a.reshape(2, 2).T, ['refs_ok', 'buffered'], ['readwrite'], order='C') for x in i: x[...] = None vals, i, x = [None]*3 assert_equal(sys.getrefcount(obj), rc-1) assert_equal(a, np.array([None]*4, dtype='O')) def test_iter_object_arrays_conversions(): # Conversions to/from objects a = np.arange(6, dtype='O') i = nditer(a, ['refs_ok', 'buffered'], ['readwrite'], casting='unsafe', op_dtypes='i4') for x in i: x[...] += 1 assert_equal(a, np.arange(6)+1) a = np.arange(6, dtype='i4') i = nditer(a, ['refs_ok', 'buffered'], ['readwrite'], casting='unsafe', op_dtypes='O') for x in i: x[...] += 1 assert_equal(a, np.arange(6)+1) # Non-contiguous object array a = np.zeros((6,), dtype=[('p', 'i1'), ('a', 'O')]) a = a['a'] a[:] = np.arange(6) i = nditer(a, ['refs_ok', 'buffered'], ['readwrite'], casting='unsafe', op_dtypes='i4') for x in i: x[...] += 1 assert_equal(a, np.arange(6)+1) #Non-contiguous value array a = np.zeros((6,), dtype=[('p', 'i1'), ('a', 'i4')]) a = a['a'] a[:] = np.arange(6) + 98172488 i = nditer(a, ['refs_ok', 'buffered'], ['readwrite'], casting='unsafe', op_dtypes='O') ob = i[0][()] rc = sys.getrefcount(ob) for x in i: x[...] += 1 assert_equal(sys.getrefcount(ob), rc-1) assert_equal(a, np.arange(6)+98172489) def test_iter_common_dtype(): # Check that the iterator finds a common data type correctly i = nditer([array([3], dtype='f4'), array([0], dtype='f8')], ['common_dtype'], [['readonly', 'copy']]*2, casting='safe') assert_equal(i.dtypes[0], np.dtype('f8')); assert_equal(i.dtypes[1], np.dtype('f8')); i = nditer([array([3], dtype='i4'), array([0], dtype='f4')], ['common_dtype'], [['readonly', 'copy']]*2, casting='safe') assert_equal(i.dtypes[0], np.dtype('f8')); assert_equal(i.dtypes[1], np.dtype('f8')); i = nditer([array([3], dtype='f4'), array(0, dtype='f8')], ['common_dtype'], [['readonly', 'copy']]*2, casting='same_kind') assert_equal(i.dtypes[0], np.dtype('f4')); assert_equal(i.dtypes[1], np.dtype('f4')); i = nditer([array([3], dtype='u4'), array(0, dtype='i4')], ['common_dtype'], [['readonly', 'copy']]*2, casting='safe') assert_equal(i.dtypes[0], np.dtype('u4')); assert_equal(i.dtypes[1], np.dtype('u4')); i = nditer([array([3], dtype='u4'), array(-12, dtype='i4')], ['common_dtype'], [['readonly', 'copy']]*2, casting='safe') assert_equal(i.dtypes[0], np.dtype('i8')); assert_equal(i.dtypes[1], np.dtype('i8')); i = nditer([array([3], dtype='u4'), array(-12, dtype='i4'), array([2j], dtype='c8'), array([9], dtype='f8')], ['common_dtype'], [['readonly', 'copy']]*4, casting='safe') assert_equal(i.dtypes[0], np.dtype('c16')); assert_equal(i.dtypes[1], np.dtype('c16')); assert_equal(i.dtypes[2], np.dtype('c16')); assert_equal(i.dtypes[3], np.dtype('c16')); assert_equal(i.value, (3, -12, 2j, 9)) # When allocating outputs, other outputs aren't factored in i = nditer([array([3], dtype='i4'), None, array([2j], dtype='c16')], [], [['readonly', 'copy'], ['writeonly', 'allocate'], ['writeonly']], casting='safe') assert_equal(i.dtypes[0], np.dtype('i4')); assert_equal(i.dtypes[1], np.dtype('i4')); assert_equal(i.dtypes[2], np.dtype('c16')); # But, if common data types are requested, they are i = nditer([array([3], dtype='i4'), None, array([2j], dtype='c16')], ['common_dtype'], [['readonly', 'copy'], ['writeonly', 'allocate'], ['writeonly']], casting='safe') assert_equal(i.dtypes[0], np.dtype('c16')); assert_equal(i.dtypes[1], np.dtype('c16')); assert_equal(i.dtypes[2], np.dtype('c16')); def test_iter_op_axes(): # Check that custom axes work # Reverse the axes a = arange(6).reshape(2, 3) i = nditer([a, a.T], [], [['readonly']]*2, op_axes=[[0, 1], [1, 0]]) assert_(all([x==y for (x, y) in i])) a = arange(24).reshape(2, 3, 4) i = nditer([a.T, a], [], [['readonly']]*2, op_axes=[[2, 1, 0], None]) assert_(all([x==y for (x, y) in i])) # Broadcast 1D to any dimension a = arange(1, 31).reshape(2, 3, 5) b = arange(1, 3) i = nditer([a, b], [], [['readonly']]*2, op_axes=[None, [0, -1, -1]]) assert_equal([x*y for (x, y) in i], (a*b.reshape(2, 1, 1)).ravel()) b = arange(1, 4) i = nditer([a, b], [], [['readonly']]*2, op_axes=[None, [-1, 0, -1]]) assert_equal([x*y for (x, y) in i], (a*b.reshape(1, 3, 1)).ravel()) b = arange(1, 6) i = nditer([a, b], [], [['readonly']]*2, op_axes=[None, [np.newaxis, np.newaxis, 0]]) assert_equal([x*y for (x, y) in i], (a*b.reshape(1, 1, 5)).ravel()) # Inner product-style broadcasting a = arange(24).reshape(2, 3, 4) b = arange(40).reshape(5, 2, 4) i = nditer([a, b], ['multi_index'], [['readonly']]*2, op_axes=[[0, 1, -1, -1], [-1, -1, 0, 1]]) assert_equal(i.shape, (2, 3, 5, 2)) # Matrix product-style broadcasting a = arange(12).reshape(3, 4) b = arange(20).reshape(4, 5) i = nditer([a, b], ['multi_index'], [['readonly']]*2, op_axes=[[0, -1], [-1, 1]]) assert_equal(i.shape, (3, 5)) def test_iter_op_axes_errors(): # Check that custom axes throws errors for bad inputs # Wrong number of items in op_axes a = arange(6).reshape(2, 3) assert_raises(ValueError, nditer, [a, a], [], [['readonly']]*2, op_axes=[[0], [1], [0]]) # Out of bounds items in op_axes assert_raises(ValueError, nditer, [a, a], [], [['readonly']]*2, op_axes=[[2, 1], [0, 1]]) assert_raises(ValueError, nditer, [a, a], [], [['readonly']]*2, op_axes=[[0, 1], [2, -1]]) # Duplicate items in op_axes assert_raises(ValueError, nditer, [a, a], [], [['readonly']]*2, op_axes=[[0, 0], [0, 1]]) assert_raises(ValueError, nditer, [a, a], [], [['readonly']]*2, op_axes=[[0, 1], [1, 1]]) # Different sized arrays in op_axes assert_raises(ValueError, nditer, [a, a], [], [['readonly']]*2, op_axes=[[0, 1], [0, 1, 0]]) # Non-broadcastable dimensions in the result assert_raises(ValueError, nditer, [a, a], [], [['readonly']]*2, op_axes=[[0, 1], [1, 0]]) def test_iter_copy(): # Check that copying the iterator works correctly a = arange(24).reshape(2, 3, 4) # Simple iterator i = nditer(a) j = i.copy() assert_equal([x[()] for x in i], [x[()] for x in j]) i.iterindex = 3 j = i.copy() assert_equal([x[()] for x in i], [x[()] for x in j]) # Buffered iterator i = nditer(a, ['buffered', 'ranged'], order='F', buffersize=3) j = i.copy() assert_equal([x[()] for x in i], [x[()] for x in j]) i.iterindex = 3 j = i.copy() assert_equal([x[()] for x in i], [x[()] for x in j]) i.iterrange = (3, 9) j = i.copy() assert_equal([x[()] for x in i], [x[()] for x in j]) i.iterrange = (2, 18) next(i) next(i) j = i.copy() assert_equal([x[()] for x in i], [x[()] for x in j]) # Casting iterator i = nditer(a, ['buffered'], order='F', casting='unsafe', op_dtypes='f8', buffersize=5) j = i.copy() i = None assert_equal([x[()] for x in j], a.ravel(order='F')) a = arange(24, dtype='cast->swap a = np.arange(10, dtype='f4').newbyteorder().byteswap() i = nditer(a, ['buffered', 'external_loop'], [['readwrite', 'nbo', 'aligned']], casting='same_kind', op_dtypes=[np.dtype('f8').newbyteorder()], buffersize=3) for v in i: v[...] *= 2 assert_equal(a, 2*np.arange(10, dtype='f4')) try: warnings.simplefilter("ignore", np.ComplexWarning) a = np.arange(10, dtype='f8').newbyteorder().byteswap() i = nditer(a, ['buffered', 'external_loop'], [['readwrite', 'nbo', 'aligned']], casting='unsafe', op_dtypes=[np.dtype('c8').newbyteorder()], buffersize=3) for v in i: v[...] *= 2 assert_equal(a, 2*np.arange(10, dtype='f8')) finally: warnings.simplefilter("default", np.ComplexWarning) def test_iter_buffered_cast_byteswapped_complex(): # Test that buffering can handle a cast which requires swap->cast->copy a = np.arange(10, dtype='c8').newbyteorder().byteswap() a += 2j i = nditer(a, ['buffered', 'external_loop'], [['readwrite', 'nbo', 'aligned']], casting='same_kind', op_dtypes=[np.dtype('c16')], buffersize=3) for v in i: v[...] *= 2 assert_equal(a, 2*np.arange(10, dtype='c8') + 4j) a = np.arange(10, dtype='c8') a += 2j i = nditer(a, ['buffered', 'external_loop'], [['readwrite', 'nbo', 'aligned']], casting='same_kind', op_dtypes=[np.dtype('c16').newbyteorder()], buffersize=3) for v in i: v[...] *= 2 assert_equal(a, 2*np.arange(10, dtype='c8') + 4j) a = np.arange(10, dtype=np.clongdouble).newbyteorder().byteswap() a += 2j i = nditer(a, ['buffered', 'external_loop'], [['readwrite', 'nbo', 'aligned']], casting='same_kind', op_dtypes=[np.dtype('c16')], buffersize=3) for v in i: v[...] *= 2 assert_equal(a, 2*np.arange(10, dtype=np.clongdouble) + 4j) a = np.arange(10, dtype=np.longdouble).newbyteorder().byteswap() i = nditer(a, ['buffered', 'external_loop'], [['readwrite', 'nbo', 'aligned']], casting='same_kind', op_dtypes=[np.dtype('f4')], buffersize=7) for v in i: v[...] *= 2 assert_equal(a, 2*np.arange(10, dtype=np.longdouble)) def test_iter_buffered_cast_structured_type(): # Tests buffering of structured types # simple -> struct type (duplicates the value) sdt = [('a', 'f4'), ('b', 'i8'), ('c', 'c8', (2, 3)), ('d', 'O')] a = np.arange(3, dtype='f4') + 0.5 i = nditer(a, ['buffered', 'refs_ok'], ['readonly'], casting='unsafe', op_dtypes=sdt) vals = [np.array(x) for x in i] assert_equal(vals[0]['a'], 0.5) assert_equal(vals[0]['b'], 0) assert_equal(vals[0]['c'], [[(0.5)]*3]*2) assert_equal(vals[0]['d'], 0.5) assert_equal(vals[1]['a'], 1.5) assert_equal(vals[1]['b'], 1) assert_equal(vals[1]['c'], [[(1.5)]*3]*2) assert_equal(vals[1]['d'], 1.5) assert_equal(vals[0].dtype, np.dtype(sdt)) # object -> struct type sdt = [('a', 'f4'), ('b', 'i8'), ('c', 'c8', (2, 3)), ('d', 'O')] a = np.zeros((3,), dtype='O') a[0] = (0.5, 0.5, [[0.5, 0.5, 0.5], [0.5, 0.5, 0.5]], 0.5) a[1] = (1.5, 1.5, [[1.5, 1.5, 1.5], [1.5, 1.5, 1.5]], 1.5) a[2] = (2.5, 2.5, [[2.5, 2.5, 2.5], [2.5, 2.5, 2.5]], 2.5) rc = sys.getrefcount(a[0]) i = nditer(a, ['buffered', 'refs_ok'], ['readonly'], casting='unsafe', op_dtypes=sdt) vals = [x.copy() for x in i] assert_equal(vals[0]['a'], 0.5) assert_equal(vals[0]['b'], 0) assert_equal(vals[0]['c'], [[(0.5)]*3]*2) assert_equal(vals[0]['d'], 0.5) assert_equal(vals[1]['a'], 1.5) assert_equal(vals[1]['b'], 1) assert_equal(vals[1]['c'], [[(1.5)]*3]*2) assert_equal(vals[1]['d'], 1.5) assert_equal(vals[0].dtype, np.dtype(sdt)) vals, i, x = [None]*3 assert_equal(sys.getrefcount(a[0]), rc) # struct type -> simple (takes the first value) sdt = [('a', 'f4'), ('b', 'i8'), ('d', 'O')] a = np.array([(5.5, 7, 'test'), (8, 10, 11)], dtype=sdt) i = nditer(a, ['buffered', 'refs_ok'], ['readonly'], casting='unsafe', op_dtypes='i4') assert_equal([x[()] for x in i], [5, 8]) # struct type -> struct type (field-wise copy) sdt1 = [('a', 'f4'), ('b', 'i8'), ('d', 'O')] sdt2 = [('d', 'u2'), ('a', 'O'), ('b', 'f8')] a = np.array([(1, 2, 3), (4, 5, 6)], dtype=sdt1) i = nditer(a, ['buffered', 'refs_ok'], ['readonly'], casting='unsafe', op_dtypes=sdt2) assert_equal(i[0].dtype, np.dtype(sdt2)) assert_equal([np.array(x) for x in i], [np.array((3, 1, 2), dtype=sdt2), np.array((6, 4, 5), dtype=sdt2)]) # struct type -> struct type (field gets discarded) sdt1 = [('a', 'f4'), ('b', 'i8'), ('d', 'O')] sdt2 = [('b', 'O'), ('a', 'f8')] a = np.array([(1, 2, 3), (4, 5, 6)], dtype=sdt1) i = nditer(a, ['buffered', 'refs_ok'], ['readwrite'], casting='unsafe', op_dtypes=sdt2) assert_equal(i[0].dtype, np.dtype(sdt2)) vals = [] for x in i: vals.append(np.array(x)) x['a'] = x['b']+3 assert_equal(vals, [np.array((2, 1), dtype=sdt2), np.array((5, 4), dtype=sdt2)]) assert_equal(a, np.array([(5, 2, None), (8, 5, None)], dtype=sdt1)) # struct type -> struct type (structured field gets discarded) sdt1 = [('a', 'f4'), ('b', 'i8'), ('d', [('a', 'i2'), ('b', 'i4')])] sdt2 = [('b', 'O'), ('a', 'f8')] a = np.array([(1, 2, (0, 9)), (4, 5, (20, 21))], dtype=sdt1) i = nditer(a, ['buffered', 'refs_ok'], ['readwrite'], casting='unsafe', op_dtypes=sdt2) assert_equal(i[0].dtype, np.dtype(sdt2)) vals = [] for x in i: vals.append(np.array(x)) x['a'] = x['b']+3 assert_equal(vals, [np.array((2, 1), dtype=sdt2), np.array((5, 4), dtype=sdt2)]) assert_equal(a, np.array([(5, 2, (0, 0)), (8, 5, (0, 0))], dtype=sdt1)) # struct type -> struct type (structured field w/ ref gets discarded) sdt1 = [('a', 'f4'), ('b', 'i8'), ('d', [('a', 'i2'), ('b', 'O')])] sdt2 = [('b', 'O'), ('a', 'f8')] a = np.array([(1, 2, (0, 9)), (4, 5, (20, 21))], dtype=sdt1) i = nditer(a, ['buffered', 'refs_ok'], ['readwrite'], casting='unsafe', op_dtypes=sdt2) assert_equal(i[0].dtype, np.dtype(sdt2)) vals = [] for x in i: vals.append(np.array(x)) x['a'] = x['b']+3 assert_equal(vals, [np.array((2, 1), dtype=sdt2), np.array((5, 4), dtype=sdt2)]) assert_equal(a, np.array([(5, 2, (0, None)), (8, 5, (0, None))], dtype=sdt1)) # struct type -> struct type back (structured field w/ ref gets discarded) sdt1 = [('b', 'O'), ('a', 'f8')] sdt2 = [('a', 'f4'), ('b', 'i8'), ('d', [('a', 'i2'), ('b', 'O')])] a = np.array([(1, 2), (4, 5)], dtype=sdt1) i = nditer(a, ['buffered', 'refs_ok'], ['readwrite'], casting='unsafe', op_dtypes=sdt2) assert_equal(i[0].dtype, np.dtype(sdt2)) vals = [] for x in i: vals.append(np.array(x)) assert_equal(x['d'], np.array((0, None), dtype=[('a', 'i2'), ('b', 'O')])) x['a'] = x['b']+3 assert_equal(vals, [np.array((2, 1, (0, None)), dtype=sdt2), np.array((5, 4, (0, None)), dtype=sdt2)]) assert_equal(a, np.array([(1, 4), (4, 7)], dtype=sdt1)) def test_iter_buffered_cast_subarray(): # Tests buffering of subarrays # one element -> many (copies it to all) sdt1 = [('a', 'f4')] sdt2 = [('a', 'f8', (3, 2, 2))] a = np.zeros((6,), dtype=sdt1) a['a'] = np.arange(6) i = nditer(a, ['buffered', 'refs_ok'], ['readonly'], casting='unsafe', op_dtypes=sdt2) assert_equal(i[0].dtype, np.dtype(sdt2)) for x, count in zip(i, list(range(6))): assert_(np.all(x['a'] == count)) # one element -> many -> back (copies it to all) sdt1 = [('a', 'O', (1, 1))] sdt2 = [('a', 'O', (3, 2, 2))] a = np.zeros((6,), dtype=sdt1) a['a'][:, 0, 0] = np.arange(6) i = nditer(a, ['buffered', 'refs_ok'], ['readwrite'], casting='unsafe', op_dtypes=sdt2) assert_equal(i[0].dtype, np.dtype(sdt2)) count = 0 for x in i: assert_(np.all(x['a'] == count)) x['a'][0] += 2 count += 1 assert_equal(a['a'], np.arange(6).reshape(6, 1, 1)+2) # many -> one element -> back (copies just element 0) sdt1 = [('a', 'O', (3, 2, 2))] sdt2 = [('a', 'O', (1,))] a = np.zeros((6,), dtype=sdt1) a['a'][:, 0, 0, 0] = np.arange(6) i = nditer(a, ['buffered', 'refs_ok'], ['readwrite'], casting='unsafe', op_dtypes=sdt2) assert_equal(i[0].dtype, np.dtype(sdt2)) count = 0 for x in i: assert_equal(x['a'], count) x['a'] += 2 count += 1 assert_equal(a['a'], np.arange(6).reshape(6, 1, 1, 1)*np.ones((1, 3, 2, 2))+2) # many -> one element -> back (copies just element 0) sdt1 = [('a', 'f8', (3, 2, 2))] sdt2 = [('a', 'O', (1,))] a = np.zeros((6,), dtype=sdt1) a['a'][:, 0, 0, 0] = np.arange(6) i = nditer(a, ['buffered', 'refs_ok'], ['readonly'], casting='unsafe', op_dtypes=sdt2) assert_equal(i[0].dtype, np.dtype(sdt2)) count = 0 for x in i: assert_equal(x['a'], count) count += 1 # many -> one element (copies just element 0) sdt1 = [('a', 'O', (3, 2, 2))] sdt2 = [('a', 'f4', (1,))] a = np.zeros((6,), dtype=sdt1) a['a'][:, 0, 0, 0] = np.arange(6) i = nditer(a, ['buffered', 'refs_ok'], ['readonly'], casting='unsafe', op_dtypes=sdt2) assert_equal(i[0].dtype, np.dtype(sdt2)) count = 0 for x in i: assert_equal(x['a'], count) count += 1 # many -> matching shape (straightforward copy) sdt1 = [('a', 'O', (3, 2, 2))] sdt2 = [('a', 'f4', (3, 2, 2))] a = np.zeros((6,), dtype=sdt1) a['a'] = np.arange(6*3*2*2).reshape(6, 3, 2, 2) i = nditer(a, ['buffered', 'refs_ok'], ['readonly'], casting='unsafe', op_dtypes=sdt2) assert_equal(i[0].dtype, np.dtype(sdt2)) count = 0 for x in i: assert_equal(x['a'], a[count]['a']) count += 1 # vector -> smaller vector (truncates) sdt1 = [('a', 'f8', (6,))] sdt2 = [('a', 'f4', (2,))] a = np.zeros((6,), dtype=sdt1) a['a'] = np.arange(6*6).reshape(6, 6) i = nditer(a, ['buffered', 'refs_ok'], ['readonly'], casting='unsafe', op_dtypes=sdt2) assert_equal(i[0].dtype, np.dtype(sdt2)) count = 0 for x in i: assert_equal(x['a'], a[count]['a'][:2]) count += 1 # vector -> bigger vector (pads with zeros) sdt1 = [('a', 'f8', (2,))] sdt2 = [('a', 'f4', (6,))] a = np.zeros((6,), dtype=sdt1) a['a'] = np.arange(6*2).reshape(6, 2) i = nditer(a, ['buffered', 'refs_ok'], ['readonly'], casting='unsafe', op_dtypes=sdt2) assert_equal(i[0].dtype, np.dtype(sdt2)) count = 0 for x in i: assert_equal(x['a'][:2], a[count]['a']) assert_equal(x['a'][2:], [0, 0, 0, 0]) count += 1 # vector -> matrix (broadcasts) sdt1 = [('a', 'f8', (2,))] sdt2 = [('a', 'f4', (2, 2))] a = np.zeros((6,), dtype=sdt1) a['a'] = np.arange(6*2).reshape(6, 2) i = nditer(a, ['buffered', 'refs_ok'], ['readonly'], casting='unsafe', op_dtypes=sdt2) assert_equal(i[0].dtype, np.dtype(sdt2)) count = 0 for x in i: assert_equal(x['a'][0], a[count]['a']) assert_equal(x['a'][1], a[count]['a']) count += 1 # vector -> matrix (broadcasts and zero-pads) sdt1 = [('a', 'f8', (2, 1))] sdt2 = [('a', 'f4', (3, 2))] a = np.zeros((6,), dtype=sdt1) a['a'] = np.arange(6*2).reshape(6, 2, 1) i = nditer(a, ['buffered', 'refs_ok'], ['readonly'], casting='unsafe', op_dtypes=sdt2) assert_equal(i[0].dtype, np.dtype(sdt2)) count = 0 for x in i: assert_equal(x['a'][:2, 0], a[count]['a'][:, 0]) assert_equal(x['a'][:2, 1], a[count]['a'][:, 0]) assert_equal(x['a'][2,:], [0, 0]) count += 1 # matrix -> matrix (truncates and zero-pads) sdt1 = [('a', 'f8', (2, 3))] sdt2 = [('a', 'f4', (3, 2))] a = np.zeros((6,), dtype=sdt1) a['a'] = np.arange(6*2*3).reshape(6, 2, 3) i = nditer(a, ['buffered', 'refs_ok'], ['readonly'], casting='unsafe', op_dtypes=sdt2) assert_equal(i[0].dtype, np.dtype(sdt2)) count = 0 for x in i: assert_equal(x['a'][:2, 0], a[count]['a'][:, 0]) assert_equal(x['a'][:2, 1], a[count]['a'][:, 1]) assert_equal(x['a'][2,:], [0, 0]) count += 1 def test_iter_buffering_badwriteback(): # Writing back from a buffer cannot combine elements # a needs write buffering, but had a broadcast dimension a = np.arange(6).reshape(2, 3, 1) b = np.arange(12).reshape(2, 3, 2) assert_raises(ValueError, nditer, [a, b], ['buffered', 'external_loop'], [['readwrite'], ['writeonly']], order='C') # But if a is readonly, it's fine i = nditer([a, b], ['buffered', 'external_loop'], [['readonly'], ['writeonly']], order='C') # If a has just one element, it's fine too (constant 0 stride, a reduction) a = np.arange(1).reshape(1, 1, 1) i = nditer([a, b], ['buffered', 'external_loop', 'reduce_ok'], [['readwrite'], ['writeonly']], order='C') # check that it fails on other dimensions too a = np.arange(6).reshape(1, 3, 2) assert_raises(ValueError, nditer, [a, b], ['buffered', 'external_loop'], [['readwrite'], ['writeonly']], order='C') a = np.arange(4).reshape(2, 1, 2) assert_raises(ValueError, nditer, [a, b], ['buffered', 'external_loop'], [['readwrite'], ['writeonly']], order='C') def test_iter_buffering_string(): # Safe casting disallows shrinking strings a = np.array(['abc', 'a', 'abcd'], dtype=np.bytes_) assert_equal(a.dtype, np.dtype('S4')); assert_raises(TypeError, nditer, a, ['buffered'], ['readonly'], op_dtypes='S2') i = nditer(a, ['buffered'], ['readonly'], op_dtypes='S6') assert_equal(i[0], asbytes('abc')) assert_equal(i[0].dtype, np.dtype('S6')) a = np.array(['abc', 'a', 'abcd'], dtype=np.unicode) assert_equal(a.dtype, np.dtype('U4')); assert_raises(TypeError, nditer, a, ['buffered'], ['readonly'], op_dtypes='U2') i = nditer(a, ['buffered'], ['readonly'], op_dtypes='U6') assert_equal(i[0], sixu('abc')) assert_equal(i[0].dtype, np.dtype('U6')) def test_iter_buffering_growinner(): # Test that the inner loop grows when no buffering is needed a = np.arange(30) i = nditer(a, ['buffered', 'growinner', 'external_loop'], buffersize=5) # Should end up with just one inner loop here assert_equal(i[0].size, a.size) @dec.slow def test_iter_buffered_reduce_reuse(): # large enough array for all views, including negative strides. a = np.arange(2*3**5)[3**5:3**5+1] flags = ['buffered', 'delay_bufalloc', 'multi_index', 'reduce_ok', 'refs_ok'] op_flags = [('readonly',), ('readwrite', 'allocate')] op_axes_list = [[(0, 1, 2), (0, 1, -1)], [(0, 1, 2), (0, -1, -1)]] # wrong dtype to force buffering op_dtypes = [np.float, a.dtype] def get_params(): for xs in range(-3**2, 3**2 + 1): for ys in range(xs, 3**2 + 1): for op_axes in op_axes_list: # last stride is reduced and because of that not # important for this test, as it is the inner stride. strides = (xs * a.itemsize, ys * a.itemsize, a.itemsize) arr = np.lib.stride_tricks.as_strided(a, (3, 3, 3), strides) for skip in [0, 1]: yield arr, op_axes, skip for arr, op_axes, skip in get_params(): nditer2 = np.nditer([arr.copy(), None], op_axes=op_axes, flags=flags, op_flags=op_flags, op_dtypes=op_dtypes) nditer2.operands[-1][...] = 0 nditer2.reset() nditer2.iterindex = skip for (a2_in, b2_in) in nditer2: b2_in += a2_in.astype(np.int_) comp_res = nditer2.operands[-1] for bufsize in range(0, 3**3): nditer1 = np.nditer([arr, None], op_axes=op_axes, flags=flags, op_flags=op_flags, buffersize=bufsize, op_dtypes=op_dtypes) nditer1.operands[-1][...] = 0 nditer1.reset() nditer1.iterindex = skip for (a1_in, b1_in) in nditer1: b1_in += a1_in.astype(np.int_) res = nditer1.operands[-1] assert_array_equal(res, comp_res) def test_iter_no_broadcast(): # Test that the no_broadcast flag works a = np.arange(24).reshape(2, 3, 4) b = np.arange(6).reshape(2, 3, 1) c = np.arange(12).reshape(3, 4) i = nditer([a, b, c], [], [['readonly', 'no_broadcast'], ['readonly'], ['readonly']]) assert_raises(ValueError, nditer, [a, b, c], [], [['readonly'], ['readonly', 'no_broadcast'], ['readonly']]) assert_raises(ValueError, nditer, [a, b, c], [], [['readonly'], ['readonly'], ['readonly', 'no_broadcast']]) def test_iter_nested_iters_basic(): # Test nested iteration basic usage a = arange(12).reshape(2, 3, 2) i, j = np.nested_iters(a, [[0], [1, 2]]) vals = [] for x in i: vals.append([y for y in j]) assert_equal(vals, [[0, 1, 2, 3, 4, 5], [6, 7, 8, 9, 10, 11]]) i, j = np.nested_iters(a, [[0, 1], [2]]) vals = [] for x in i: vals.append([y for y in j]) assert_equal(vals, [[0, 1], [2, 3], [4, 5], [6, 7], [8, 9], [10, 11]]) i, j = np.nested_iters(a, [[0, 2], [1]]) vals = [] for x in i: vals.append([y for y in j]) assert_equal(vals, [[0, 2, 4], [1, 3, 5], [6, 8, 10], [7, 9, 11]]) def test_iter_nested_iters_reorder(): # Test nested iteration basic usage a = arange(12).reshape(2, 3, 2) # In 'K' order (default), it gets reordered i, j = np.nested_iters(a, [[0], [2, 1]]) vals = [] for x in i: vals.append([y for y in j]) assert_equal(vals, [[0, 1, 2, 3, 4, 5], [6, 7, 8, 9, 10, 11]]) i, j = np.nested_iters(a, [[1, 0], [2]]) vals = [] for x in i: vals.append([y for y in j]) assert_equal(vals, [[0, 1], [2, 3], [4, 5], [6, 7], [8, 9], [10, 11]]) i, j = np.nested_iters(a, [[2, 0], [1]]) vals = [] for x in i: vals.append([y for y in j]) assert_equal(vals, [[0, 2, 4], [1, 3, 5], [6, 8, 10], [7, 9, 11]]) # In 'C' order, it doesn't i, j = np.nested_iters(a, [[0], [2, 1]], order='C') vals = [] for x in i: vals.append([y for y in j]) assert_equal(vals, [[0, 2, 4, 1, 3, 5], [6, 8, 10, 7, 9, 11]]) i, j = np.nested_iters(a, [[1, 0], [2]], order='C') vals = [] for x in i: vals.append([y for y in j]) assert_equal(vals, [[0, 1], [6, 7], [2, 3], [8, 9], [4, 5], [10, 11]]) i, j = np.nested_iters(a, [[2, 0], [1]], order='C') vals = [] for x in i: vals.append([y for y in j]) assert_equal(vals, [[0, 2, 4], [6, 8, 10], [1, 3, 5], [7, 9, 11]]) def test_iter_nested_iters_flip_axes(): # Test nested iteration with negative axes a = arange(12).reshape(2, 3, 2)[::-1, ::-1, ::-1] # In 'K' order (default), the axes all get flipped i, j = np.nested_iters(a, [[0], [1, 2]]) vals = [] for x in i: vals.append([y for y in j]) assert_equal(vals, [[0, 1, 2, 3, 4, 5], [6, 7, 8, 9, 10, 11]]) i, j = np.nested_iters(a, [[0, 1], [2]]) vals = [] for x in i: vals.append([y for y in j]) assert_equal(vals, [[0, 1], [2, 3], [4, 5], [6, 7], [8, 9], [10, 11]]) i, j = np.nested_iters(a, [[0, 2], [1]]) vals = [] for x in i: vals.append([y for y in j]) assert_equal(vals, [[0, 2, 4], [1, 3, 5], [6, 8, 10], [7, 9, 11]]) # In 'C' order, flipping axes is disabled i, j = np.nested_iters(a, [[0], [1, 2]], order='C') vals = [] for x in i: vals.append([y for y in j]) assert_equal(vals, [[11, 10, 9, 8, 7, 6], [5, 4, 3, 2, 1, 0]]) i, j = np.nested_iters(a, [[0, 1], [2]], order='C') vals = [] for x in i: vals.append([y for y in j]) assert_equal(vals, [[11, 10], [9, 8], [7, 6], [5, 4], [3, 2], [1, 0]]) i, j = np.nested_iters(a, [[0, 2], [1]], order='C') vals = [] for x in i: vals.append([y for y in j]) assert_equal(vals, [[11, 9, 7], [10, 8, 6], [5, 3, 1], [4, 2, 0]]) def test_iter_nested_iters_broadcast(): # Test nested iteration with broadcasting a = arange(2).reshape(2, 1) b = arange(3).reshape(1, 3) i, j = np.nested_iters([a, b], [[0], [1]]) vals = [] for x in i: vals.append([y for y in j]) assert_equal(vals, [[[0, 0], [0, 1], [0, 2]], [[1, 0], [1, 1], [1, 2]]]) i, j = np.nested_iters([a, b], [[1], [0]]) vals = [] for x in i: vals.append([y for y in j]) assert_equal(vals, [[[0, 0], [1, 0]], [[0, 1], [1, 1]], [[0, 2], [1, 2]]]) def test_iter_nested_iters_dtype_copy(): # Test nested iteration with a copy to change dtype # copy a = arange(6, dtype='i4').reshape(2, 3) i, j = np.nested_iters(a, [[0], [1]], op_flags=['readonly', 'copy'], op_dtypes='f8') assert_equal(j[0].dtype, np.dtype('f8')) vals = [] for x in i: vals.append([y for y in j]) assert_equal(vals, [[0, 1, 2], [3, 4, 5]]) vals = None # updateifcopy a = arange(6, dtype='f4').reshape(2, 3) i, j = np.nested_iters(a, [[0], [1]], op_flags=['readwrite', 'updateifcopy'], casting='same_kind', op_dtypes='f8') assert_equal(j[0].dtype, np.dtype('f8')) for x in i: for y in j: y[...] += 1 assert_equal(a, [[0, 1, 2], [3, 4, 5]]) i, j, x, y = (None,)*4 # force the updateifcopy assert_equal(a, [[1, 2, 3], [4, 5, 6]]) def test_iter_nested_iters_dtype_buffered(): # Test nested iteration with buffering to change dtype a = arange(6, dtype='f4').reshape(2, 3) i, j = np.nested_iters(a, [[0], [1]], flags=['buffered'], op_flags=['readwrite'], casting='same_kind', op_dtypes='f8') assert_equal(j[0].dtype, np.dtype('f8')) for x in i: for y in j: y[...] += 1 assert_equal(a, [[1, 2, 3], [4, 5, 6]]) def test_iter_reduction_error(): a = np.arange(6) assert_raises(ValueError, nditer, [a, None], [], [['readonly'], ['readwrite', 'allocate']], op_axes=[[0], [-1]]) a = np.arange(6).reshape(2, 3) assert_raises(ValueError, nditer, [a, None], ['external_loop'], [['readonly'], ['readwrite', 'allocate']], op_axes=[[0, 1], [-1, -1]]) def test_iter_reduction(): # Test doing reductions with the iterator a = np.arange(6) i = nditer([a, None], ['reduce_ok'], [['readonly'], ['readwrite', 'allocate']], op_axes=[[0], [-1]]) # Need to initialize the output operand to the addition unit i.operands[1][...] = 0 # Do the reduction for x, y in i: y[...] += x # Since no axes were specified, should have allocated a scalar assert_equal(i.operands[1].ndim, 0) assert_equal(i.operands[1], np.sum(a)) a = np.arange(6).reshape(2, 3) i = nditer([a, None], ['reduce_ok', 'external_loop'], [['readonly'], ['readwrite', 'allocate']], op_axes=[[0, 1], [-1, -1]]) # Need to initialize the output operand to the addition unit i.operands[1][...] = 0 # Reduction shape/strides for the output assert_equal(i[1].shape, (6,)) assert_equal(i[1].strides, (0,)) # Do the reduction for x, y in i: y[...] += x # Since no axes were specified, should have allocated a scalar assert_equal(i.operands[1].ndim, 0) assert_equal(i.operands[1], np.sum(a)) # This is a tricky reduction case for the buffering double loop # to handle a = np.ones((2, 3, 5)) it1 = nditer([a, None], ['reduce_ok', 'external_loop'], [['readonly'], ['readwrite', 'allocate']], op_axes=[None, [0, -1, 1]]) it2 = nditer([a, None], ['reduce_ok', 'external_loop', 'buffered', 'delay_bufalloc'], [['readonly'], ['readwrite', 'allocate']], op_axes=[None, [0, -1, 1]], buffersize=10) it1.operands[1].fill(0) it2.operands[1].fill(0) it2.reset() for x in it1: x[1][...] += x[0] for x in it2: x[1][...] += x[0] assert_equal(it1.operands[1], it2.operands[1]) assert_equal(it2.operands[1].sum(), a.size) def test_iter_buffering_reduction(): # Test doing buffered reductions with the iterator a = np.arange(6) b = np.array(0., dtype='f8').byteswap().newbyteorder() i = nditer([a, b], ['reduce_ok', 'buffered'], [['readonly'], ['readwrite', 'nbo']], op_axes=[[0], [-1]]) assert_equal(i[1].dtype, np.dtype('f8')) assert_(i[1].dtype != b.dtype) # Do the reduction for x, y in i: y[...] += x # Since no axes were specified, should have allocated a scalar assert_equal(b, np.sum(a)) a = np.arange(6).reshape(2, 3) b = np.array([0, 0], dtype='f8').byteswap().newbyteorder() i = nditer([a, b], ['reduce_ok', 'external_loop', 'buffered'], [['readonly'], ['readwrite', 'nbo']], op_axes=[[0, 1], [0, -1]]) # Reduction shape/strides for the output assert_equal(i[1].shape, (3,)) assert_equal(i[1].strides, (0,)) # Do the reduction for x, y in i: y[...] += x assert_equal(b, np.sum(a, axis=1)) # Iterator inner double loop was wrong on this one p = np.arange(2) + 1 it = np.nditer([p, None], ['delay_bufalloc', 'reduce_ok', 'buffered', 'external_loop'], [['readonly'], ['readwrite', 'allocate']], op_axes=[[-1, 0], [-1, -1]], itershape=(2, 2)) it.operands[1].fill(0) it.reset() assert_equal(it[0], [1, 2, 1, 2]) def test_iter_buffering_reduction_reuse_reduce_loops(): # There was a bug triggering reuse of the reduce loop inappropriately, # which caused processing to happen in unnecessarily small chunks # and overran the buffer. a = np.zeros((2, 7)) b = np.zeros((1, 7)) it = np.nditer([a, b], flags=['reduce_ok', 'external_loop', 'buffered'], op_flags=[['readonly'], ['readwrite']], buffersize = 5) bufsizes = [] for x, y in it: bufsizes.append(x.shape[0]) assert_equal(bufsizes, [5, 2, 5, 2]) assert_equal(sum(bufsizes), a.size) def test_iter_writemasked_badinput(): a = np.zeros((2, 3)) b = np.zeros((3,)) m = np.array([[True, True, False], [False, True, False]]) m2 = np.array([True, True, False]) m3 = np.array([0, 1, 1], dtype='u1') mbad1 = np.array([0, 1, 1], dtype='i1') mbad2 = np.array([0, 1, 1], dtype='f4') # Need an 'arraymask' if any operand is 'writemasked' assert_raises(ValueError, nditer, [a, m], [], [['readwrite', 'writemasked'], ['readonly']]) # A 'writemasked' operand must not be readonly assert_raises(ValueError, nditer, [a, m], [], [['readonly', 'writemasked'], ['readonly', 'arraymask']]) # 'writemasked' and 'arraymask' may not be used together assert_raises(ValueError, nditer, [a, m], [], [['readonly'], ['readwrite', 'arraymask', 'writemasked']]) # 'arraymask' may only be specified once assert_raises(ValueError, nditer, [a, m, m2], [], [['readwrite', 'writemasked'], ['readonly', 'arraymask'], ['readonly', 'arraymask']]) # An 'arraymask' with nothing 'writemasked' also doesn't make sense assert_raises(ValueError, nditer, [a, m], [], [['readwrite'], ['readonly', 'arraymask']]) # A writemasked reduction requires a similarly smaller mask assert_raises(ValueError, nditer, [a, b, m], ['reduce_ok'], [['readonly'], ['readwrite', 'writemasked'], ['readonly', 'arraymask']]) # But this should work with a smaller/equal mask to the reduction operand np.nditer([a, b, m2], ['reduce_ok'], [['readonly'], ['readwrite', 'writemasked'], ['readonly', 'arraymask']]) # The arraymask itself cannot be a reduction assert_raises(ValueError, nditer, [a, b, m2], ['reduce_ok'], [['readonly'], ['readwrite', 'writemasked'], ['readwrite', 'arraymask']]) # A uint8 mask is ok too np.nditer([a, m3], ['buffered'], [['readwrite', 'writemasked'], ['readonly', 'arraymask']], op_dtypes=['f4', None], casting='same_kind') # An int8 mask isn't ok assert_raises(TypeError, np.nditer, [a, mbad1], ['buffered'], [['readwrite', 'writemasked'], ['readonly', 'arraymask']], op_dtypes=['f4', None], casting='same_kind') # A float32 mask isn't ok assert_raises(TypeError, np.nditer, [a, mbad2], ['buffered'], [['readwrite', 'writemasked'], ['readonly', 'arraymask']], op_dtypes=['f4', None], casting='same_kind') def test_iter_writemasked(): a = np.zeros((3,), dtype='f8') msk = np.array([True, True, False]) # When buffering is unused, 'writemasked' effectively does nothing. # It's up to the user of the iterator to obey the requested semantics. it = np.nditer([a, msk], [], [['readwrite', 'writemasked'], ['readonly', 'arraymask']]) for x, m in it: x[...] = 1 # Because we violated the semantics, all the values became 1 assert_equal(a, [1, 1, 1]) # Even if buffering is enabled, we still may be accessing the array # directly. it = np.nditer([a, msk], ['buffered'], [['readwrite', 'writemasked'], ['readonly', 'arraymask']]) for x, m in it: x[...] = 2.5 # Because we violated the semantics, all the values became 2.5 assert_equal(a, [2.5, 2.5, 2.5]) # If buffering will definitely happening, for instance because of # a cast, only the items selected by the mask will be copied back from # the buffer. it = np.nditer([a, msk], ['buffered'], [['readwrite', 'writemasked'], ['readonly', 'arraymask']], op_dtypes=['i8', None], casting='unsafe') for x, m in it: x[...] = 3 # Even though we violated the semantics, only the selected values # were copied back assert_equal(a, [3, 3, 2.5]) def test_iter_non_writable_attribute_deletion(): it = np.nditer(np.ones(2)) attr = ["value", "shape", "operands", "itviews", "has_delayed_bufalloc", "iterationneedsapi", "has_multi_index", "has_index", "dtypes", "ndim", "nop", "itersize", "finished"] if sys.version[:3] == '2.4': error = TypeError else: error = AttributeError for s in attr: assert_raises(error, delattr, it, s) def test_iter_writable_attribute_deletion(): it = np.nditer(np.ones(2)) attr = [ "multi_index", "index", "iterrange", "iterindex"] for s in attr: assert_raises(AttributeError, delattr, it, s) def test_iter_element_deletion(): it = np.nditer(np.ones(3)) try: del it[1] del it[1:2] except TypeError: pass except: raise AssertionError def test_iter_allocated_array_dtypes(): # If the dtype of an allocated output has a shape, the shape gets # tacked onto the end of the result. it = np.nditer(([1, 3, 20], None), op_dtypes=[None, ('i4', (2,))]) for a, b in it: b[0] = a - 1 b[1] = a + 1 assert_equal(it.operands[1], [[0, 2], [2, 4], [19, 21]]) # Make sure this works for scalars too it = np.nditer((10, 2, None), op_dtypes=[None, None, ('i4', (2, 2))]) for a, b, c in it: c[0, 0] = a - b c[0, 1] = a + b c[1, 0] = a * b c[1, 1] = a / b assert_equal(it.operands[2], [[8, 12], [20, 5]]) def test_0d_iter(): # Basic test for iteration of 0-d arrays: i = nditer([2, 3], ['multi_index'], [['readonly']]*2) assert_equal(i.ndim, 0) assert_equal(next(i), (2, 3)) assert_equal(i.multi_index, ()) assert_equal(i.iterindex, 0) assert_raises(StopIteration, next, i) # test reset: i.reset() assert_equal(next(i), (2, 3)) assert_raises(StopIteration, next, i) # test forcing to 0-d i = nditer(np.arange(5), ['multi_index'], [['readonly']], op_axes=[()]) assert_equal(i.ndim, 0) assert_equal(len(i), 1) # note that itershape=(), still behaves like None due to the conversions # Test a more complex buffered casting case (same as another test above) sdt = [('a', 'f4'), ('b', 'i8'), ('c', 'c8', (2, 3)), ('d', 'O')] a = np.array(0.5, dtype='f4') i = nditer(a, ['buffered', 'refs_ok'], ['readonly'], casting='unsafe', op_dtypes=sdt) vals = next(i) assert_equal(vals['a'], 0.5) assert_equal(vals['b'], 0) assert_equal(vals['c'], [[(0.5)]*3]*2) assert_equal(vals['d'], 0.5) def test_0d_nested_iter(): a = np.arange(12).reshape(2, 3, 2) i, j = np.nested_iters(a, [[], [1, 0, 2]]) vals = [] for x in i: vals.append([y for y in j]) assert_equal(vals, [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]]) i, j = np.nested_iters(a, [[1, 0, 2], []]) vals = [] for x in i: vals.append([y for y in j]) assert_equal(vals, [[0], [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11]]) i, j, k = np.nested_iters(a, [[2, 0], [], [1]]) vals = [] for x in i: for y in j: vals.append([z for z in k]) assert_equal(vals, [[0, 2, 4], [1, 3, 5], [6, 8, 10], [7, 9, 11]]) def test_iter_too_large(): # The total size of the iterator must not exceed the maximum intp due # to broadcasting. Dividing by 1024 will keep it small enough to # give a legal array. 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__": run_module_suite() numpy-1.8.2/numpy/core/tests/test_shape_base.py0000664000175100017510000002005012370216243022766 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function import warnings import numpy as np from numpy.testing import (TestCase, assert_, assert_raises, assert_array_equal, assert_equal, run_module_suite) from numpy.core import (array, arange, atleast_1d, atleast_2d, atleast_3d, vstack, hstack, newaxis, concatenate) from numpy.compat import long class TestAtleast1d(TestCase): def test_0D_array(self): a = array(1) b = array(2) res = [atleast_1d(a), atleast_1d(b)] desired = [array([1]), array([2])] assert_array_equal(res, desired) def test_1D_array(self): a = array([1, 2]) b = array([2, 3]) res = [atleast_1d(a), atleast_1d(b)] desired = [array([1, 2]), array([2, 3])] assert_array_equal(res, desired) def test_2D_array(self): a = array([[1, 2], [1, 2]]) b = array([[2, 3], [2, 3]]) res = [atleast_1d(a), atleast_1d(b)] desired = [a, b] assert_array_equal(res, desired) def test_3D_array(self): a = array([[1, 2], [1, 2]]) b = array([[2, 3], [2, 3]]) a = array([a, a]) b = array([b, b]) res = [atleast_1d(a), atleast_1d(b)] desired = [a, b] assert_array_equal(res, desired) def test_r1array(self): """ Test to make sure equivalent Travis O's r1array function """ assert_(atleast_1d(3).shape == (1,)) assert_(atleast_1d(3j).shape == (1,)) assert_(atleast_1d(long(3)).shape == (1,)) assert_(atleast_1d(3.0).shape == (1,)) assert_(atleast_1d([[2, 3], [4, 5]]).shape == (2, 2)) class TestAtleast2d(TestCase): def test_0D_array(self): a = array(1) b = array(2) res = [atleast_2d(a), atleast_2d(b)] desired = [array([[1]]), array([[2]])] assert_array_equal(res, desired) def test_1D_array(self): a = array([1, 2]) b = array([2, 3]) res = [atleast_2d(a), atleast_2d(b)] desired = [array([[1, 2]]), array([[2, 3]])] assert_array_equal(res, desired) def test_2D_array(self): a = array([[1, 2], [1, 2]]) b = array([[2, 3], [2, 3]]) res = [atleast_2d(a), atleast_2d(b)] desired = [a, b] assert_array_equal(res, desired) def test_3D_array(self): a = array([[1, 2], [1, 2]]) b = array([[2, 3], [2, 3]]) a = array([a, a]) b = array([b, b]) res = [atleast_2d(a), atleast_2d(b)] desired = [a, b] assert_array_equal(res, desired) def test_r2array(self): """ Test to make sure equivalent Travis O's r2array function """ assert_(atleast_2d(3).shape == (1, 1)) assert_(atleast_2d([3j, 1]).shape == (1, 2)) assert_(atleast_2d([[[3, 1], [4, 5]], [[3, 5], [1, 2]]]).shape == (2, 2, 2)) class TestAtleast3d(TestCase): def test_0D_array(self): a = array(1) b = array(2) res = [atleast_3d(a), atleast_3d(b)] desired = [array([[[1]]]), array([[[2]]])] assert_array_equal(res, desired) def test_1D_array(self): a = array([1, 2]) b = array([2, 3]) res = [atleast_3d(a), atleast_3d(b)] desired = [array([[[1], [2]]]), array([[[2], [3]]])] assert_array_equal(res, desired) def test_2D_array(self): a = array([[1, 2], [1, 2]]) b = array([[2, 3], [2, 3]]) res = [atleast_3d(a), atleast_3d(b)] desired = [a[:,:, newaxis], b[:,:, newaxis]] assert_array_equal(res, desired) def test_3D_array(self): a = array([[1, 2], [1, 2]]) b = array([[2, 3], [2, 3]]) a = array([a, a]) b = array([b, b]) res = [atleast_3d(a), atleast_3d(b)] desired = [a, b] assert_array_equal(res, desired) class TestHstack(TestCase): def test_0D_array(self): a = array(1) b = array(2) res=hstack([a, b]) desired = array([1, 2]) assert_array_equal(res, desired) def test_1D_array(self): a = array([1]) b = array([2]) res=hstack([a, b]) desired = array([1, 2]) assert_array_equal(res, desired) def test_2D_array(self): a = array([[1], [2]]) b = array([[1], [2]]) res=hstack([a, b]) desired = array([[1, 1], [2, 2]]) assert_array_equal(res, desired) class TestVstack(TestCase): def test_0D_array(self): a = array(1) b = array(2) res=vstack([a, b]) desired = array([[1], [2]]) assert_array_equal(res, desired) def test_1D_array(self): a = array([1]) b = array([2]) res=vstack([a, b]) desired = array([[1], [2]]) assert_array_equal(res, desired) def test_2D_array(self): a = array([[1], [2]]) b = array([[1], [2]]) res=vstack([a, b]) desired = array([[1], [2], [1], [2]]) assert_array_equal(res, desired) def test_2D_array2(self): a = array([1, 2]) b = array([1, 2]) res=vstack([a, b]) desired = array([[1, 2], [1, 2]]) assert_array_equal(res, desired) def test_concatenate_axis_None(): a = np.arange(4, dtype=np.float64).reshape((2, 2)) b = list(range(3)) c = ['x'] r = np.concatenate((a, a), axis=None) assert_equal(r.dtype, a.dtype) assert_equal(r.ndim, 1) r = np.concatenate((a, b), 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', '0', '1', '2', 'x']) assert_array_equal(r, d) def test_concatenate(): # Test concatenate function # No arrays raise ValueError assert_raises(ValueError, concatenate, ()) # Scalars cannot be concatenated assert_raises(ValueError, concatenate, (0,)) assert_raises(ValueError, concatenate, (array(0),)) # One sequence returns unmodified (but as array) r4 = list(range(4)) assert_array_equal(concatenate((r4,)), r4) # Any sequence assert_array_equal(concatenate((tuple(r4),)), r4) assert_array_equal(concatenate((array(r4),)), r4) # 1D default concatenation r3 = list(range(3)) assert_array_equal(concatenate((r4, r3)), r4 + r3) # Mixed sequence types assert_array_equal(concatenate((tuple(r4), r3)), r4 + r3) assert_array_equal(concatenate((array(r4), r3)), r4 + r3) # Explicit axis specification assert_array_equal(concatenate((r4, r3), 0), r4 + r3) # Including negative assert_array_equal(concatenate((r4, r3), -1), r4 + r3) # 2D a23 = array([[10, 11, 12], [13, 14, 15]]) a13 = array([[0, 1, 2]]) res = array([[10, 11, 12], [13, 14, 15], [0, 1, 2]]) assert_array_equal(concatenate((a23, a13)), res) assert_array_equal(concatenate((a23, a13), 0), res) assert_array_equal(concatenate((a23.T, a13.T), 1), res.T) assert_array_equal(concatenate((a23.T, a13.T), -1), res.T) # Arrays much match shape assert_raises(ValueError, concatenate, (a23.T, a13.T), 0) # 3D res = arange(2 * 3 * 7).reshape((2, 3, 7)) a0 = res[..., :4] a1 = res[..., 4:6] a2 = res[..., 6:] assert_array_equal(concatenate((a0, a1, a2), 2), res) assert_array_equal(concatenate((a0, a1, a2), -1), res) assert_array_equal(concatenate((a0.T, a1.T, a2.T), 0), res.T) def test_concatenate_sloppy0(): # Versions of numpy < 1.7.0 ignored axis argument value for 1D arrays. We # allow this for now, but in due course we will raise an error r4 = list(range(4)) r3 = list(range(3)) assert_array_equal(concatenate((r4, r3), 0), r4 + r3) with warnings.catch_warnings(): warnings.simplefilter('ignore', DeprecationWarning) assert_array_equal(concatenate((r4, r3), -10), r4 + r3) assert_array_equal(concatenate((r4, r3), 10), r4 + r3) # Confirm DeprecationWarning raised warnings.simplefilter('error', DeprecationWarning) assert_raises(DeprecationWarning, concatenate, (r4, r3), 10) if __name__ == "__main__": run_module_suite() numpy-1.8.2/numpy/core/tests/test_arrayprint.py0000664000175100017510000001531212370216242023073 0ustar vagrantvagrant00000000000000#!/usr/bin/python # -*- coding: utf-8 -*- from __future__ import division, absolute_import, print_function import sys import numpy as np from numpy.testing import * from numpy.compat import sixu class TestArrayRepr(object): def test_nan_inf(self): x = np.array([np.nan, np.inf]) assert_equal(repr(x), 'array([ nan, inf])') class TestComplexArray(TestCase): def test_str(self): rvals = [0, 1, -1, np.inf, -np.inf, np.nan] cvals = [complex(rp, ip) for rp in rvals for ip in rvals] dtypes = [np.complex64, np.cdouble, np.clongdouble] actual = [str(np.array([c], dt)) for c in cvals for dt in dtypes] wanted = [ '[ 0.+0.j]', '[ 0.+0.j]', '[ 0.0+0.0j]', '[ 0.+1.j]', '[ 0.+1.j]', '[ 0.0+1.0j]', '[ 0.-1.j]', '[ 0.-1.j]', '[ 0.0-1.0j]', '[ 0.+infj]', '[ 0.+infj]', '[ 0.0+infj]', '[ 0.-infj]', '[ 0.-infj]', '[ 0.0-infj]', '[ 0.+nanj]', '[ 0.+nanj]', '[ 0.0+nanj]', '[ 1.+0.j]', '[ 1.+0.j]', '[ 1.0+0.0j]', '[ 1.+1.j]', '[ 1.+1.j]', '[ 1.0+1.0j]', '[ 1.-1.j]', '[ 1.-1.j]', '[ 1.0-1.0j]', '[ 1.+infj]', '[ 1.+infj]', '[ 1.0+infj]', '[ 1.-infj]', '[ 1.-infj]', '[ 1.0-infj]', '[ 1.+nanj]', '[ 1.+nanj]', '[ 1.0+nanj]', '[-1.+0.j]', '[-1.+0.j]', '[-1.0+0.0j]', '[-1.+1.j]', '[-1.+1.j]', '[-1.0+1.0j]', '[-1.-1.j]', '[-1.-1.j]', '[-1.0-1.0j]', '[-1.+infj]', '[-1.+infj]', '[-1.0+infj]', '[-1.-infj]', '[-1.-infj]', '[-1.0-infj]', '[-1.+nanj]', '[-1.+nanj]', '[-1.0+nanj]', '[ inf+0.j]', '[ inf+0.j]', '[ inf+0.0j]', '[ inf+1.j]', '[ inf+1.j]', '[ inf+1.0j]', '[ inf-1.j]', '[ inf-1.j]', '[ inf-1.0j]', '[ inf+infj]', '[ inf+infj]', '[ inf+infj]', '[ inf-infj]', '[ inf-infj]', '[ inf-infj]', '[ inf+nanj]', '[ inf+nanj]', '[ inf+nanj]', '[-inf+0.j]', '[-inf+0.j]', '[-inf+0.0j]', '[-inf+1.j]', '[-inf+1.j]', '[-inf+1.0j]', '[-inf-1.j]', '[-inf-1.j]', '[-inf-1.0j]', '[-inf+infj]', '[-inf+infj]', '[-inf+infj]', '[-inf-infj]', '[-inf-infj]', '[-inf-infj]', '[-inf+nanj]', '[-inf+nanj]', '[-inf+nanj]', '[ nan+0.j]', '[ nan+0.j]', '[ nan+0.0j]', '[ nan+1.j]', '[ nan+1.j]', '[ nan+1.0j]', '[ nan-1.j]', '[ nan-1.j]', '[ nan-1.0j]', '[ nan+infj]', '[ nan+infj]', '[ nan+infj]', '[ nan-infj]', '[ nan-infj]', '[ nan-infj]', '[ nan+nanj]', '[ nan+nanj]', '[ nan+nanj]'] for res, val in zip(actual, wanted): assert_(res == val) class TestArray2String(TestCase): def test_basic(self): """Basic test of array2string.""" a = np.arange(3) assert_(np.array2string(a) == '[0 1 2]') assert_(np.array2string(a, max_line_width=4) == '[0 1\n 2]') def test_style_keyword(self): """This should only apply to 0-D arrays. See #1218.""" stylestr = np.array2string(np.array(1.5), style=lambda x: "Value in 0-D array: " + str(x)) assert_(stylestr == 'Value in 0-D array: 1.5') def test_format_function(self): """Test custom format function for each element in array.""" def _format_function(x): if np.abs(x) < 1: return '.' elif np.abs(x) < 2: return 'o' else: return 'O' x = np.arange(3) if sys.version_info[0] >= 3: x_hex = "[0x0 0x1 0x2]" x_oct = "[0o0 0o1 0o2]" else: x_hex = "[0x0L 0x1L 0x2L]" x_oct = "[0L 01L 02L]" assert_(np.array2string(x, formatter={'all':_format_function}) == \ "[. o O]") assert_(np.array2string(x, formatter={'int_kind':_format_function}) ==\ "[. o O]") assert_(np.array2string(x, formatter={'all':lambda x: "%.4f" % x}) == \ "[0.0000 1.0000 2.0000]") assert_equal(np.array2string(x, formatter={'int':lambda x: hex(x)}), \ x_hex) assert_equal(np.array2string(x, formatter={'int':lambda x: oct(x)}), \ x_oct) x = np.arange(3.) assert_(np.array2string(x, formatter={'float_kind':lambda x: "%.2f" % x}) == \ "[0.00 1.00 2.00]") assert_(np.array2string(x, formatter={'float':lambda x: "%.2f" % x}) == \ "[0.00 1.00 2.00]") s = np.array(['abc', 'def']) assert_(np.array2string(s, formatter={'numpystr':lambda s: s*2}) == \ '[abcabc defdef]') class TestPrintOptions: """Test getting and setting global print options.""" def setUp(self): self.oldopts = np.get_printoptions() def tearDown(self): np.set_printoptions(**self.oldopts) def test_basic(self): x = np.array([1.5, 0, 1.234567890]) assert_equal(repr(x), "array([ 1.5 , 0. , 1.23456789])") np.set_printoptions(precision=4) assert_equal(repr(x), "array([ 1.5 , 0. , 1.2346])") def test_formatter(self): x = np.arange(3) np.set_printoptions(formatter={'all':lambda x: str(x-1)}) assert_equal(repr(x), "array([-1, 0, 1])") def test_formatter_reset(self): x = np.arange(3) np.set_printoptions(formatter={'all':lambda x: str(x-1)}) assert_equal(repr(x), "array([-1, 0, 1])") np.set_printoptions(formatter={'int':None}) assert_equal(repr(x), "array([0, 1, 2])") np.set_printoptions(formatter={'all':lambda x: str(x-1)}) assert_equal(repr(x), "array([-1, 0, 1])") np.set_printoptions(formatter={'all':None}) assert_equal(repr(x), "array([0, 1, 2])") np.set_printoptions(formatter={'int':lambda x: str(x-1)}) assert_equal(repr(x), "array([-1, 0, 1])") np.set_printoptions(formatter={'int_kind':None}) assert_equal(repr(x), "array([0, 1, 2])") x = np.arange(3.) np.set_printoptions(formatter={'float':lambda x: str(x-1)}) assert_equal(repr(x), "array([-1.0, 0.0, 1.0])") np.set_printoptions(formatter={'float_kind':None}) assert_equal(repr(x), "array([ 0., 1., 2.])") def test_unicode_object_array(): import sys if sys.version_info[0] >= 3: expected = "array(['é'], dtype=object)" else: expected = "array([u'\\xe9'], dtype=object)" x = np.array([sixu('\xe9')], dtype=object) assert_equal(repr(x), expected) if __name__ == "__main__": run_module_suite() numpy-1.8.2/numpy/core/tests/test_item_selection.py0000664000175100017510000000533612370216243023711 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function import numpy as np from numpy.testing import * import sys, warnings class TestTake(TestCase): def test_simple(self): a = [[1, 2], [3, 4]] a_str = [[b'1', b'2'], [b'3', b'4']] modes = ['raise', 'wrap', 'clip'] indices = [-1, 4] index_arrays = [np.empty(0, dtype=np.intp), np.empty(tuple(), dtype=np.intp), np.empty((1, 1), dtype=np.intp)] real_indices = {} real_indices['raise'] = {-1:1, 4:IndexError} real_indices['wrap'] = {-1:1, 4:0} real_indices['clip'] = {-1:0, 4:1} # Currently all types but object, use the same function generation. # So it should not be necessary to test all. However test also a non # refcounted struct on top of object. types = np.int, np.object, np.dtype([('', 'i', 2)]) for t in types: # ta works, even if the array may be odd if buffer interface is used ta = np.array(a if np.issubdtype(t, np.number) else a_str, dtype=t) tresult = list(ta.T.copy()) for index_array in index_arrays: if index_array.size != 0: tresult[0].shape = (2,) + index_array.shape tresult[1].shape = (2,) + index_array.shape for mode in modes: for index in indices: real_index = real_indices[mode][index] if real_index is IndexError and index_array.size != 0: index_array.put(0, index) assert_raises(IndexError, ta.take, index_array, mode=mode, axis=1) elif index_array.size != 0: index_array.put(0, index) res = ta.take(index_array, mode=mode, axis=1) assert_array_equal(res, tresult[real_index]) else: res = ta.take(index_array, mode=mode, axis=1) assert_(res.shape == (2,) + index_array.shape) def test_refcounting(self): objects = [object() for i in range(10)] for mode in ('raise', 'clip', 'wrap'): a = np.array(objects) b = np.array([2, 2, 4, 5, 3, 5]) a.take(b, out=a[:6]) del a assert_(all(sys.getrefcount(o) == 3 for o in objects)) # not contiguous, example: a = np.array(objects * 2)[::2] a.take(b, out=a[:6]) del a assert_(all(sys.getrefcount(o) == 3 for o in objects)) if __name__ == "__main__": run_module_suite() numpy-1.8.2/numpy/core/tests/test_machar.py0000664000175100017510000000175412370216242022140 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function from numpy.testing import * from numpy.core.machar import MachAr import numpy.core.numerictypes as ntypes from numpy import errstate, array class TestMachAr(TestCase): def _run_machar_highprec(self): # Instanciate MachAr instance with high enough precision to cause # underflow try: hiprec = ntypes.float96 machar = MachAr(lambda v:array([v], hiprec)) except AttributeError: "Skipping test: no nyptes.float96 available on this platform." def test_underlow(self): """Regression testing for #759: instanciating MachAr for dtype = np.float96 raises spurious warning.""" with errstate(all='raise'): try: self._run_machar_highprec() except FloatingPointError as e: self.fail("Caught %s exception, should not have been raised." % e) if __name__ == "__main__": run_module_suite() numpy-1.8.2/numpy/core/tests/test_indexerrors.py0000664000175100017510000001155412370216242023250 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function import numpy as np from numpy.testing import TestCase, run_module_suite, assert_raises, assert_equal, assert_ import sys class TestIndexErrors(TestCase): '''Tests to exercise indexerrors not covered by other tests.''' def test_arraytypes_fasttake(self): 'take from a 0-length dimension' x = np.empty((2, 3, 0, 4)) assert_raises(IndexError, x.take, [0], axis=2) assert_raises(IndexError, x.take, [1], axis=2) assert_raises(IndexError, x.take, [0], axis=2, mode='wrap') assert_raises(IndexError, x.take, [0], axis=2, mode='clip') def test_take_from_object(self): # Check exception taking from object array d = np.zeros(5, dtype=object) assert_raises(IndexError, d.take, [6]) # Check exception taking from 0-d array d = np.zeros((5, 0), dtype=object) assert_raises(IndexError, d.take, [1], axis=1) assert_raises(IndexError, d.take, [0], axis=1) assert_raises(IndexError, d.take, [0]) assert_raises(IndexError, d.take, [0], mode='wrap') assert_raises(IndexError, d.take, [0], mode='clip') def test_multiindex_exceptions(self): a = np.empty(5, dtype=object) assert_raises(IndexError, a.item, 20) a = np.empty((5, 0), dtype=object) assert_raises(IndexError, a.item, (0, 0)) a = np.empty(5, dtype=object) assert_raises(IndexError, a.itemset, 20, 0) a = np.empty((5, 0), dtype=object) assert_raises(IndexError, a.itemset, (0, 0), 0) def test_put_exceptions(self): a = np.zeros((5, 5)) assert_raises(IndexError, a.put, 100, 0) a = np.zeros((5, 5), dtype=object) assert_raises(IndexError, a.put, 100, 0) a = np.zeros((5, 5, 0)) assert_raises(IndexError, a.put, 100, 0) a = np.zeros((5, 5, 0), dtype=object) assert_raises(IndexError, a.put, 100, 0) def test_iterators_exceptions(self): "cases in iterators.c" def assign(obj, ind, val): obj[ind] = val a = np.zeros([1, 2, 3]) assert_raises(IndexError, lambda: a[0, 5, None, 2]) assert_raises(IndexError, lambda: a[0, 5, 0, 2]) assert_raises(IndexError, lambda: assign(a, (0, 5, None, 2), 1)) assert_raises(IndexError, lambda: assign(a, (0, 5, 0, 2), 1)) a = np.zeros([1, 0, 3]) assert_raises(IndexError, lambda: a[0, 0, None, 2]) assert_raises(IndexError, lambda: assign(a, (0, 0, None, 2), 1)) a = np.zeros([1, 2, 3]) assert_raises(IndexError, lambda: a.flat[10]) assert_raises(IndexError, lambda: assign(a.flat, 10, 5)) a = np.zeros([1, 0, 3]) assert_raises(IndexError, lambda: a.flat[10]) assert_raises(IndexError, lambda: assign(a.flat, 10, 5)) a = np.zeros([1, 2, 3]) assert_raises(IndexError, lambda: a.flat[np.array(10)]) assert_raises(IndexError, lambda: assign(a.flat, np.array(10), 5)) a = np.zeros([1, 0, 3]) assert_raises(IndexError, lambda: a.flat[np.array(10)]) assert_raises(IndexError, lambda: assign(a.flat, np.array(10), 5)) a = np.zeros([1, 2, 3]) assert_raises(IndexError, lambda: a.flat[np.array([10])]) assert_raises(IndexError, lambda: assign(a.flat, np.array([10]), 5)) a = np.zeros([1, 0, 3]) assert_raises(IndexError, lambda: a.flat[np.array([10])]) assert_raises(IndexError, lambda: assign(a.flat, np.array([10]), 5)) def test_mapping(self): "cases from mapping.c" def assign(obj, ind, val): obj[ind] = val a = np.zeros((0, 10)) assert_raises(IndexError, lambda: a[12]) a = np.zeros((3, 5)) assert_raises(IndexError, lambda: a[(10, 20)]) assert_raises(IndexError, lambda: assign(a, (10, 20), 1)) a = np.zeros((3, 0)) assert_raises(IndexError, lambda: a[(1, 0)]) assert_raises(IndexError, lambda: assign(a, (1, 0), 1)) a = np.zeros((10,)) assert_raises(IndexError, lambda: assign(a, 10, 1)) a = np.zeros((0,)) assert_raises(IndexError, lambda: assign(a, 10, 1)) a = np.zeros((3, 5)) assert_raises(IndexError, lambda: a[(1, [1, 20])]) assert_raises(IndexError, lambda: assign(a, (1, [1, 20]), 1)) a = np.zeros((3, 0)) assert_raises(IndexError, lambda: a[(1, [0, 1])]) assert_raises(IndexError, lambda: assign(a, (1, [0, 1]), 1)) def test_methods(self): "cases from methods.c" a = np.zeros((3, 3)) assert_raises(IndexError, lambda: a.item(100)) assert_raises(IndexError, lambda: a.itemset(100, 1)) a = np.zeros((0, 3)) assert_raises(IndexError, lambda: a.item(100)) assert_raises(IndexError, lambda: a.itemset(100, 1)) if __name__ == "__main__": run_module_suite() numpy-1.8.2/numpy/core/tests/test_half.py0000664000175100017510000004420012370216242021610 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function import platform import numpy as np from numpy import uint16, float16, float32, float64 from numpy.testing import TestCase, run_module_suite, assert_, assert_equal, \ dec def assert_raises_fpe(strmatch, callable, *args, **kwargs): try: callable(*args, **kwargs) except FloatingPointError as exc: assert_(str(exc).find(strmatch) >= 0, "Did not raise floating point %s error" % strmatch) else: assert_(False, "Did not raise floating point %s error" % strmatch) class TestHalf(TestCase): def setUp(self): # An array of all possible float16 values self.all_f16 = np.arange(0x10000, dtype=uint16) self.all_f16.dtype = float16 self.all_f32 = np.array(self.all_f16, dtype=float32) self.all_f64 = np.array(self.all_f16, dtype=float64) # An array of all non-NaN float16 values, in sorted order self.nonan_f16 = np.concatenate( (np.arange(0xfc00, 0x7fff, -1, dtype=uint16), np.arange(0x0000, 0x7c01, 1, dtype=uint16)) ) self.nonan_f16.dtype = float16 self.nonan_f32 = np.array(self.nonan_f16, dtype=float32) self.nonan_f64 = np.array(self.nonan_f16, dtype=float64) # An array of all finite float16 values, in sorted order self.finite_f16 = self.nonan_f16[1:-1] self.finite_f32 = self.nonan_f32[1:-1] self.finite_f64 = self.nonan_f64[1:-1] def test_half_conversions(self): """Checks that all 16-bit values survive conversion to/from 32-bit and 64-bit float""" # Because the underlying routines preserve the NaN bits, every # value is preserved when converting to/from other floats. # Convert from float32 back to float16 b = np.array(self.all_f32, dtype=float16) assert_equal(self.all_f16.view(dtype=uint16), b.view(dtype=uint16)) # Convert from float64 back to float16 b = np.array(self.all_f64, dtype=float16) assert_equal(self.all_f16.view(dtype=uint16), b.view(dtype=uint16)) # Convert float16 to longdouble and back # This doesn't necessarily preserve the extra NaN bits, # so exclude NaNs. a_ld = np.array(self.nonan_f16, dtype=np.longdouble) b = np.array(a_ld, dtype=float16) assert_equal(self.nonan_f16.view(dtype=uint16), b.view(dtype=uint16)) # Check the range for which all integers can be represented i_int = np.arange(-2048, 2049) i_f16 = np.array(i_int, dtype=float16) j = np.array(i_f16, dtype=np.int) assert_equal(i_int, j) def test_nans_infs(self): with np.errstate(all='ignore'): # Check some of the ufuncs assert_equal(np.isnan(self.all_f16), np.isnan(self.all_f32)) assert_equal(np.isinf(self.all_f16), np.isinf(self.all_f32)) assert_equal(np.isfinite(self.all_f16), np.isfinite(self.all_f32)) assert_equal(np.signbit(self.all_f16), np.signbit(self.all_f32)) assert_equal(np.spacing(float16(65504)), np.inf) # Check comparisons of all values with NaN nan = float16(np.nan) assert_(not (self.all_f16 == nan).any()) assert_(not (nan == self.all_f16).any()) assert_((self.all_f16 != nan).all()) assert_((nan != self.all_f16).all()) assert_(not (self.all_f16 < nan).any()) assert_(not (nan < self.all_f16).any()) assert_(not (self.all_f16 <= nan).any()) assert_(not (nan <= self.all_f16).any()) assert_(not (self.all_f16 > nan).any()) assert_(not (nan > self.all_f16).any()) assert_(not (self.all_f16 >= nan).any()) assert_(not (nan >= self.all_f16).any()) def test_half_values(self): """Confirms a small number of known half values""" a = np.array([1.0, -1.0, 2.0, -2.0, 0.0999755859375, 0.333251953125, # 1/10, 1/3 65504, -65504, # Maximum magnitude 2.0**(-14), -2.0**(-14), # Minimum normal 2.0**(-24), -2.0**(-24), # Minimum subnormal 0, -1/1e1000, # Signed zeros np.inf, -np.inf]) b = np.array([0x3c00, 0xbc00, 0x4000, 0xc000, 0x2e66, 0x3555, 0x7bff, 0xfbff, 0x0400, 0x8400, 0x0001, 0x8001, 0x0000, 0x8000, 0x7c00, 0xfc00], dtype=uint16) b.dtype = float16 assert_equal(a, b) def test_half_rounding(self): """Checks that rounding when converting to half is correct""" a = np.array([2.0**-25 + 2.0**-35, # Rounds to minimum subnormal 2.0**-25, # Underflows to zero (nearest even mode) 2.0**-26, # Underflows to zero 1.0+2.0**-11 + 2.0**-16, # rounds to 1.0+2**(-10) 1.0+2.0**-11, # rounds to 1.0 (nearest even mode) 1.0+2.0**-12, # rounds to 1.0 65519, # rounds to 65504 65520], # rounds to inf dtype=float64) rounded = [2.0**-24, 0.0, 0.0, 1.0+2.0**(-10), 1.0, 1.0, 65504, np.inf] # Check float64->float16 rounding b = np.array(a, dtype=float16) assert_equal(b, rounded) # Check float32->float16 rounding a = np.array(a, dtype=float32) b = np.array(a, dtype=float16) assert_equal(b, rounded) def test_half_correctness(self): """Take every finite float16, and check the casting functions with a manual conversion.""" # Create an array of all finite float16s a_f16 = self.finite_f16 a_bits = a_f16.view(dtype=uint16) # Convert to 64-bit float manually a_sgn = (-1.0)**((a_bits&0x8000) >> 15) a_exp = np.array((a_bits&0x7c00) >> 10, dtype=np.int32) - 15 a_man = (a_bits&0x03ff) * 2.0**(-10) # Implicit bit of normalized floats a_man[a_exp!=-15] += 1 # Denormalized exponent is -14 a_exp[a_exp==-15] = -14 a_manual = a_sgn * a_man * 2.0**a_exp a32_fail = np.nonzero(self.finite_f32 != a_manual)[0] if len(a32_fail) != 0: bad_index = a32_fail[0] assert_equal(self.finite_f32, a_manual, "First non-equal is half value %x -> %g != %g" % (a[bad_index], self.finite_f32[bad_index], a_manual[bad_index])) a64_fail = np.nonzero(self.finite_f64 != a_manual)[0] if len(a64_fail) != 0: bad_index = a64_fail[0] assert_equal(self.finite_f64, a_manual, "First non-equal is half value %x -> %g != %g" % (a[bad_index], self.finite_f64[bad_index], a_manual[bad_index])) def test_half_ordering(self): """Make sure comparisons are working right""" # All non-NaN float16 values in reverse order a = self.nonan_f16[::-1].copy() # 32-bit float copy b = np.array(a, dtype=float32) # Should sort the same a.sort() b.sort() assert_equal(a, b) # Comparisons should work assert_((a[:-1] <= a[1:]).all()) assert_(not (a[:-1] > a[1:]).any()) assert_((a[1:] >= a[:-1]).all()) assert_(not (a[1:] < a[:-1]).any()) # All != except for +/-0 assert_equal(np.nonzero(a[:-1] < a[1:])[0].size, a.size-2) assert_equal(np.nonzero(a[1:] > a[:-1])[0].size, a.size-2) def test_half_funcs(self): """Test the various ArrFuncs""" # fill assert_equal(np.arange(10, dtype=float16), np.arange(10, dtype=float32)) # fillwithscalar a = np.zeros((5,), dtype=float16) a.fill(1) assert_equal(a, np.ones((5,), dtype=float16)) # nonzero and copyswap a = np.array([0, 0, -1, -1/1e20, 0, 2.0**-24, 7.629e-6], dtype=float16) assert_equal(a.nonzero()[0], [2, 5, 6]) a = a.byteswap().newbyteorder() assert_equal(a.nonzero()[0], [2, 5, 6]) # dot a = np.arange(0, 10, 0.5, dtype=float16) b = np.ones((20,), dtype=float16) assert_equal(np.dot(a, b), 95) # argmax a = np.array([0, -np.inf, -2, 0.5, 12.55, 7.3, 2.1, 12.4], dtype=float16) assert_equal(a.argmax(), 4) a = np.array([0, -np.inf, -2, np.inf, 12.55, np.nan, 2.1, 12.4], dtype=float16) assert_equal(a.argmax(), 5) # getitem a = np.arange(10, dtype=float16) for i in range(10): assert_equal(a.item(i), i) def test_spacing_nextafter(self): """Test np.spacing and np.nextafter""" # All non-negative finite #'s a = np.arange(0x7c00, dtype=uint16) hinf = np.array((np.inf,), dtype=float16) a_f16 = a.view(dtype=float16) assert_equal(np.spacing(a_f16[:-1]), a_f16[1:]-a_f16[:-1]) assert_equal(np.nextafter(a_f16[:-1], hinf), a_f16[1:]) assert_equal(np.nextafter(a_f16[0], -hinf), -a_f16[1]) assert_equal(np.nextafter(a_f16[1:], -hinf), a_f16[:-1]) # switch to negatives a |= 0x8000 assert_equal(np.spacing(a_f16[0]), np.spacing(a_f16[1])) assert_equal(np.spacing(a_f16[1:]), a_f16[:-1]-a_f16[1:]) assert_equal(np.nextafter(a_f16[0], hinf), -a_f16[1]) assert_equal(np.nextafter(a_f16[1:], hinf), a_f16[:-1]) assert_equal(np.nextafter(a_f16[:-1], -hinf), a_f16[1:]) def test_half_ufuncs(self): """Test the various ufuncs""" a = np.array([0, 1, 2, 4, 2], dtype=float16) b = np.array([-2, 5, 1, 4, 3], dtype=float16) c = np.array([0, -1, -np.inf, np.nan, 6], dtype=float16) assert_equal(np.add(a, b), [-2, 6, 3, 8, 5]) assert_equal(np.subtract(a, b), [2, -4, 1, 0, -1]) assert_equal(np.multiply(a, b), [0, 5, 2, 16, 6]) assert_equal(np.divide(a, b), [0, 0.199951171875, 2, 1, 0.66650390625]) assert_equal(np.equal(a, b), [False, False, False, True, False]) assert_equal(np.not_equal(a, b), [True, True, True, False, True]) assert_equal(np.less(a, b), [False, True, False, False, True]) assert_equal(np.less_equal(a, b), [False, True, False, True, True]) assert_equal(np.greater(a, b), [True, False, True, False, False]) assert_equal(np.greater_equal(a, b), [True, False, True, True, False]) assert_equal(np.logical_and(a, b), [False, True, True, True, True]) assert_equal(np.logical_or(a, b), [True, True, True, True, True]) assert_equal(np.logical_xor(a, b), [True, False, False, False, False]) assert_equal(np.logical_not(a), [True, False, False, False, False]) assert_equal(np.isnan(c), [False, False, False, True, False]) assert_equal(np.isinf(c), [False, False, True, False, False]) assert_equal(np.isfinite(c), [True, True, False, False, True]) assert_equal(np.signbit(b), [True, False, False, False, False]) assert_equal(np.copysign(b, a), [2, 5, 1, 4, 3]) assert_equal(np.maximum(a, b), [0, 5, 2, 4, 3]) x = np.maximum(b, c) assert_(np.isnan(x[3])) x[3] = 0 assert_equal(x, [0, 5, 1, 0, 6]) assert_equal(np.minimum(a, b), [-2, 1, 1, 4, 2]) x = np.minimum(b, c) assert_(np.isnan(x[3])) x[3] = 0 assert_equal(x, [-2, -1, -np.inf, 0, 3]) assert_equal(np.fmax(a, b), [0, 5, 2, 4, 3]) assert_equal(np.fmax(b, c), [0, 5, 1, 4, 6]) assert_equal(np.fmin(a, b), [-2, 1, 1, 4, 2]) assert_equal(np.fmin(b, c), [-2, -1, -np.inf, 4, 3]) assert_equal(np.floor_divide(a, b), [0, 0, 2, 1, 0]) assert_equal(np.remainder(a, b), [0, 1, 0, 0, 2]) assert_equal(np.square(b), [4, 25, 1, 16, 9]) assert_equal(np.reciprocal(b), [-0.5, 0.199951171875, 1, 0.25, 0.333251953125]) assert_equal(np.ones_like(b), [1, 1, 1, 1, 1]) assert_equal(np.conjugate(b), b) assert_equal(np.absolute(b), [2, 5, 1, 4, 3]) assert_equal(np.negative(b), [2, -5, -1, -4, -3]) assert_equal(np.sign(b), [-1, 1, 1, 1, 1]) assert_equal(np.modf(b), ([0, 0, 0, 0, 0], b)) assert_equal(np.frexp(b), ([-0.5, 0.625, 0.5, 0.5, 0.75], [2, 3, 1, 3, 2])) assert_equal(np.ldexp(b, [0, 1, 2, 4, 2]), [-2, 10, 4, 64, 12]) def test_half_coercion(self): """Test that half gets coerced properly with the other types""" a16 = np.array((1,), dtype=float16) a32 = np.array((1,), dtype=float32) b16 = float16(1) b32 = float32(1) assert_equal(np.power(a16, 2).dtype, float16) assert_equal(np.power(a16, 2.0).dtype, float16) assert_equal(np.power(a16, b16).dtype, float16) assert_equal(np.power(a16, b32).dtype, float16) assert_equal(np.power(a16, a16).dtype, float16) assert_equal(np.power(a16, a32).dtype, float32) assert_equal(np.power(b16, 2).dtype, float64) assert_equal(np.power(b16, 2.0).dtype, float64) assert_equal(np.power(b16, b16).dtype, float16) assert_equal(np.power(b16, b32).dtype, float32) assert_equal(np.power(b16, a16).dtype, float16) assert_equal(np.power(b16, a32).dtype, float32) assert_equal(np.power(a32, a16).dtype, float32) assert_equal(np.power(a32, b16).dtype, float32) assert_equal(np.power(b32, a16).dtype, float16) assert_equal(np.power(b32, b16).dtype, float32) @dec.skipif(platform.machine() == "armv5tel", "See gh-413.") def test_half_fpe(self): with np.errstate(all='raise'): sx16 = np.array((1e-4,), dtype=float16) bx16 = np.array((1e4,), dtype=float16) sy16 = float16(1e-4) by16 = float16(1e4) # Underflow errors assert_raises_fpe('underflow', lambda a, b:a*b, sx16, sx16) assert_raises_fpe('underflow', lambda a, b:a*b, sx16, sy16) assert_raises_fpe('underflow', lambda a, b:a*b, sy16, sx16) assert_raises_fpe('underflow', lambda a, b:a*b, sy16, sy16) assert_raises_fpe('underflow', lambda a, b:a/b, sx16, bx16) assert_raises_fpe('underflow', lambda a, b:a/b, sx16, by16) assert_raises_fpe('underflow', lambda a, b:a/b, sy16, bx16) assert_raises_fpe('underflow', lambda a, b:a/b, sy16, by16) assert_raises_fpe('underflow', lambda a, b:a/b, float16(2.**-14), float16(2**11)) assert_raises_fpe('underflow', lambda a, b:a/b, float16(-2.**-14), float16(2**11)) assert_raises_fpe('underflow', lambda a, b:a/b, float16(2.**-14+2**-24), float16(2)) assert_raises_fpe('underflow', lambda a, b:a/b, float16(-2.**-14-2**-24), float16(2)) assert_raises_fpe('underflow', lambda a, b:a/b, float16(2.**-14+2**-23), float16(4)) # Overflow errors assert_raises_fpe('overflow', lambda a, b:a*b, bx16, bx16) assert_raises_fpe('overflow', lambda a, b:a*b, bx16, by16) assert_raises_fpe('overflow', lambda a, b:a*b, by16, bx16) assert_raises_fpe('overflow', lambda a, b:a*b, by16, by16) assert_raises_fpe('overflow', lambda a, b:a/b, bx16, sx16) assert_raises_fpe('overflow', lambda a, b:a/b, bx16, sy16) assert_raises_fpe('overflow', lambda a, b:a/b, by16, sx16) assert_raises_fpe('overflow', lambda a, b:a/b, by16, sy16) assert_raises_fpe('overflow', lambda a, b:a+b, float16(65504), float16(17)) assert_raises_fpe('overflow', lambda a, b:a-b, float16(-65504), float16(17)) assert_raises_fpe('overflow', np.nextafter, float16(65504), float16(np.inf)) assert_raises_fpe('overflow', np.nextafter, float16(-65504), float16(-np.inf)) assert_raises_fpe('overflow', np.spacing, float16(65504)) # Invalid value errors assert_raises_fpe('invalid', np.divide, float16(np.inf), float16(np.inf)) assert_raises_fpe('invalid', np.spacing, float16(np.inf)) assert_raises_fpe('invalid', np.spacing, float16(np.nan)) assert_raises_fpe('invalid', np.nextafter, float16(np.inf), float16(0)) assert_raises_fpe('invalid', np.nextafter, float16(-np.inf), float16(0)) assert_raises_fpe('invalid', np.nextafter, float16(0), float16(np.nan)) # These should not raise float16(65472)+float16(32) float16(2**-13)/float16(2) float16(2**-14)/float16(2**10) np.spacing(float16(-65504)) np.nextafter(float16(65504), float16(-np.inf)) np.nextafter(float16(-65504), float16(np.inf)) float16(2**-14)/float16(2**10) float16(-2**-14)/float16(2**10) float16(2**-14+2**-23)/float16(2) float16(-2**-14-2**-23)/float16(2) def test_half_array_interface(self): """Test that half is compatible with __array_interface__""" class Dummy: pass a = np.ones((1,), dtype=float16) b = Dummy() b.__array_interface__ = a.__array_interface__ c = np.array(b) assert_(c.dtype == float16) assert_equal(a, c) if __name__ == "__main__": run_module_suite() numpy-1.8.2/numpy/core/tests/test_deprecations.py0000664000175100017510000002745212370216243023371 0ustar vagrantvagrant00000000000000""" Tests related to deprecation warnings. Also a convenient place to document how deprecations should eventually be turned into errors. """ from __future__ import division, absolute_import, print_function import sys import operator import warnings from nose.plugins.skip import SkipTest import numpy as np from numpy.testing import dec, run_module_suite, assert_raises class _DeprecationTestCase(object): # Just as warning: warnings uses re.match, so the start of this message # must match. message = '' def setUp(self): self.warn_ctx = warnings.catch_warnings(record=True) self.log = self.warn_ctx.__enter__() # Do *not* ignore other DeprecationWarnings. Ignoring warnings # can give very confusing results because of # http://bugs.python.org/issue4180 and it is probably simplest to # try to keep the tests cleanly giving only the right warning type. # (While checking them set to "error" those are ignored anyway) # We still have them show up, because otherwise they would be raised warnings.filterwarnings("always", category=DeprecationWarning) warnings.filterwarnings("always", message=self.message, category=DeprecationWarning) def tearDown(self): self.warn_ctx.__exit__() def assert_deprecated(self, function, num=1, ignore_others=False, function_fails=False, exceptions=(DeprecationWarning,), args=(), kwargs={}): """Test if DeprecationWarnings are given and raised. This first checks if the function when called gives `num` DeprecationWarnings, after that it tries to raise these DeprecationWarnings and compares them with `exceptions`. The exceptions can be different for cases where this code path is simply not anticipated and the exception is replaced. Parameters ---------- f : callable The function to test num : int Number of DeprecationWarnings to expect. This should normally be 1. ignore_other : bool Whether warnings of the wrong type should be ignored (note that the message is not checked) function_fails : bool If the function would normally fail, setting this will check for warnings inside a try/except block. exceptions : Exception or tuple of Exceptions Exception to expect when turning the warnings into an error. The default checks for DeprecationWarnings. If exceptions is empty the function is expected to run successfull. args : tuple Arguments for `f` kwargs : dict Keyword arguments for `f` """ # reset the log self.log[:] = [] try: function(*args, **kwargs) except (Exception if function_fails else tuple()): pass # just in case, clear the registry num_found = 0 for warning in self.log: if warning.category is DeprecationWarning: num_found += 1 elif not ignore_others: raise AssertionError("expected DeprecationWarning but %s given" % warning.category) if num_found != num: raise AssertionError("%i warnings found but %i expected" % (len(self.log), num)) with warnings.catch_warnings(): warnings.filterwarnings("error", message=self.message, category=DeprecationWarning) try: function(*args, **kwargs) if exceptions != tuple(): raise AssertionError("No error raised during function call") except exceptions: if exceptions == tuple(): raise AssertionError("Error raised during function call") def assert_not_deprecated(self, function, args=(), kwargs={}): """Test if DeprecationWarnings are given and raised. This is just a shorthand for: self.assert_deprecated(function, num=0, ignore_others=True, exceptions=tuple(), args=args, kwargs=kwargs) """ self.assert_deprecated(function, num=0, ignore_others=True, exceptions=tuple(), args=args, kwargs=kwargs) class TestFloatNonIntegerArgumentDeprecation(_DeprecationTestCase): """ These test that ``DeprecationWarning`` is given when you try to use non-integers as arguments to for indexing and slicing e.g. ``a[0.0:5]`` and ``a[0.5]``, or other functions like ``array.reshape(1., -1)``. After deprecation, changes need to be done inside conversion_utils.c in PyArray_PyIntAsIntp and possibly PyArray_IntpConverter. In iterators.c the function slice_GetIndices could be removed in favor of its python equivalent and in mapping.c the function _tuple_of_integers can be simplified (if ``np.array([1]).__index__()`` is also deprecated). As for the deprecation time-frame: via Ralf Gommers, "Hard to put that as a version number, since we don't know if the version after 1.8 will be 6 months or 2 years after. I'd say 2 years is reasonable." I interpret this to mean 2 years after the 1.8 release. Possibly giving a PendingDeprecationWarning before that (which is visible by default) """ message = "using a non-integer number instead of an integer " \ "will result in an error in the future" def test_indexing(self): a = np.array([[[5]]]) def assert_deprecated(*args, **kwargs): self.assert_deprecated(*args, exceptions=(IndexError,), **kwargs) assert_deprecated(lambda: a[0.0]) assert_deprecated(lambda: a[0, 0.0]) assert_deprecated(lambda: a[0.0, 0]) assert_deprecated(lambda: a[0.0,:]) assert_deprecated(lambda: a[:, 0.0]) assert_deprecated(lambda: a[:, 0.0,:]) assert_deprecated(lambda: a[0.0,:,:], num=2) # [1] assert_deprecated(lambda: a[0, 0, 0.0]) assert_deprecated(lambda: a[0.0, 0, 0]) assert_deprecated(lambda: a[0, 0.0, 0]) assert_deprecated(lambda: a[-1.4]) assert_deprecated(lambda: a[0, -1.4]) assert_deprecated(lambda: a[-1.4, 0]) assert_deprecated(lambda: a[-1.4,:]) assert_deprecated(lambda: a[:, -1.4]) assert_deprecated(lambda: a[:, -1.4,:]) assert_deprecated(lambda: a[-1.4,:,:], num=2) # [1] assert_deprecated(lambda: a[0, 0, -1.4]) assert_deprecated(lambda: a[-1.4, 0, 0]) assert_deprecated(lambda: a[0, -1.4, 0]) # [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. assert_deprecated(lambda: a[0.0:, 0.0], num=2) assert_deprecated(lambda: a[0.0:, 0.0,:], num=2) def test_valid_indexing(self): a = np.array([[[5]]]) assert_not_deprecated = self.assert_not_deprecated assert_not_deprecated(lambda: a[np.array([0])]) assert_not_deprecated(lambda: a[[0, 0]]) assert_not_deprecated(lambda: a[:, [0, 0]]) assert_not_deprecated(lambda: a[:, 0,:]) assert_not_deprecated(lambda: a[:,:,:]) def test_slicing(self): a = np.array([[5]]) def assert_deprecated(*args, **kwargs): self.assert_deprecated(*args, exceptions=(IndexError,), **kwargs) # start as float. assert_deprecated(lambda: a[0.0:]) assert_deprecated(lambda: a[0:, 0.0:2]) assert_deprecated(lambda: a[0.0::2, :0]) assert_deprecated(lambda: a[0.0:1:2,:]) assert_deprecated(lambda: a[:, 0.0:]) # stop as float. assert_deprecated(lambda: a[:0.0]) assert_deprecated(lambda: a[:0, 1:2.0]) assert_deprecated(lambda: a[:0.0:2, :0]) assert_deprecated(lambda: a[:0.0,:]) assert_deprecated(lambda: a[:, 0:4.0:2]) # step as float. assert_deprecated(lambda: a[::1.0]) assert_deprecated(lambda: a[0:, :2:2.0]) assert_deprecated(lambda: a[1::4.0, :0]) assert_deprecated(lambda: a[::5.0,:]) assert_deprecated(lambda: a[:, 0:4:2.0]) # mixed. assert_deprecated(lambda: a[1.0:2:2.0], num=2) assert_deprecated(lambda: a[1.0::2.0], num=2) assert_deprecated(lambda: a[0:, :2.0:2.0], num=2) assert_deprecated(lambda: a[1.0:1:4.0, :0], num=2) assert_deprecated(lambda: a[1.0:5.0:5.0,:], num=3) assert_deprecated(lambda: a[:, 0.4:4.0:2.0], num=3) # should still get the DeprecationWarning if step = 0. assert_deprecated(lambda: a[::0.0], function_fails=True) def test_valid_slicing(self): a = np.array([[[5]]]) assert_not_deprecated = self.assert_not_deprecated assert_not_deprecated(lambda: a[::]) assert_not_deprecated(lambda: a[0:]) assert_not_deprecated(lambda: a[:2]) assert_not_deprecated(lambda: a[0:2]) assert_not_deprecated(lambda: a[::2]) assert_not_deprecated(lambda: a[1::2]) assert_not_deprecated(lambda: a[:2:2]) assert_not_deprecated(lambda: a[1:2:2]) def test_non_integer_argument_deprecations(self): a = np.array([[5]]) self.assert_deprecated(np.reshape, args=(a, (1., 1., -1)), num=2) self.assert_deprecated(np.reshape, args=(a, (np.array(1.), -1))) self.assert_deprecated(np.take, args=(a, [0], 1.)) self.assert_deprecated(np.take, args=(a, [0], np.float64(1.))) class TestBooleanArgumentDeprecation(_DeprecationTestCase): """This tests that using a boolean as integer argument/indexing is deprecated. This should be kept in sync with TestFloatNonIntegerArgumentDeprecation and like it is handled in PyArray_PyIntAsIntp. """ message = "using a boolean instead of an integer " \ "will result in an error in the future" def test_bool_as_int_argument(self): a = np.array([[[1]]]) self.assert_deprecated(np.reshape, args=(a, (True, -1))) self.assert_deprecated(np.reshape, args=(a, (np.bool_(True), -1))) # Note that operator.index(np.array(True)) does not work, a boolean # array is thus also deprecated, but not with the same message: assert_raises(TypeError, operator.index, np.array(True)) self.assert_deprecated(np.take, args=(a, [0], False)) self.assert_deprecated(lambda: a[False:True:True], exceptions=IndexError, num=3) self.assert_deprecated(lambda: a[False, 0], exceptions=IndexError) self.assert_deprecated(lambda: a[False, 0, 0], exceptions=IndexError) class TestArrayToIndexDeprecation(_DeprecationTestCase): """This tests that creating an an index from an array is deprecated if the array is not 0d. This can probably be deprecated somewhat faster then the integer deprecations. The deprecation period started with NumPy 1.8. For deprecation this needs changing of array_index in number.c """ message = "converting an array with ndim \> 0 to an index will result " \ "in an error in the future" def test_array_to_index_deprecation(self): # This drops into the non-integer deprecation, which is ignored here, # so no exception is expected. The raising is effectively tested above. a = np.array([[[1]]]) self.assert_deprecated(operator.index, args=(np.array([1]),)) self.assert_deprecated(np.reshape, args=(a, (a, -1)), exceptions=()) self.assert_deprecated(np.take, args=(a, [0], a), exceptions=()) # Check slicing. Normal indexing checks arrays specifically. self.assert_deprecated(lambda: a[a:a:a], exceptions=(), num=3) if __name__ == "__main__": run_module_suite() numpy-1.8.2/numpy/core/tests/test_ufunc.py0000664000175100017510000011777712370216243022043 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function import sys import numpy as np from numpy.testing import * import numpy.core.umath_tests as umt import numpy.core.operand_flag_tests as opflag_tests from numpy.compat import asbytes from numpy.core.test_rational import * class TestUfunc(TestCase): def test_pickle(self): import pickle assert pickle.loads(pickle.dumps(np.sin)) is np.sin def test_pickle_withstring(self): import pickle astring = asbytes("cnumpy.core\n_ufunc_reconstruct\np0\n" "(S'numpy.core.umath'\np1\nS'cos'\np2\ntp3\nRp4\n.") assert pickle.loads(astring) is np.cos def test_reduceat_shifting_sum(self) : L = 6 x = np.arange(L) idx = np.array(list(zip(np.arange(L - 2), np.arange(L - 2) + 2))).ravel() assert_array_equal(np.add.reduceat(x, idx)[::2], [1, 3, 5, 7]) def test_generic_loops(self) : """Test generic loops. The loops to be tested are: PyUFunc_ff_f_As_dd_d PyUFunc_ff_f PyUFunc_dd_d PyUFunc_gg_g PyUFunc_FF_F_As_DD_D PyUFunc_DD_D PyUFunc_FF_F PyUFunc_GG_G PyUFunc_OO_O PyUFunc_OO_O_method PyUFunc_f_f_As_d_d PyUFunc_d_d PyUFunc_f_f PyUFunc_g_g PyUFunc_F_F_As_D_D PyUFunc_F_F PyUFunc_D_D PyUFunc_G_G PyUFunc_O_O PyUFunc_O_O_method PyUFunc_On_Om Where: f -- float d -- double g -- long double F -- complex float D -- complex double G -- complex long double O -- python object It is difficult to assure that each of these loops is entered from the Python level as the special cased loops are a moving target and the corresponding types are architecture dependent. We probably need to define C level testing ufuncs to get at them. For the time being, I've just looked at the signatures registered in the build directory to find relevant functions. Fixme, currently untested: PyUFunc_ff_f_As_dd_d PyUFunc_FF_F_As_DD_D PyUFunc_f_f_As_d_d PyUFunc_F_F_As_D_D PyUFunc_On_Om """ fone = np.exp ftwo = lambda x, y : x**y fone_val = 1 ftwo_val = 1 # check unary PyUFunc_f_f. msg = "PyUFunc_f_f" x = np.zeros(10, dtype=np.single)[0::2] assert_almost_equal(fone(x), fone_val, err_msg=msg) # check unary PyUFunc_d_d. msg = "PyUFunc_d_d" x = np.zeros(10, dtype=np.double)[0::2] assert_almost_equal(fone(x), fone_val, err_msg=msg) # check unary PyUFunc_g_g. msg = "PyUFunc_g_g" x = np.zeros(10, dtype=np.longdouble)[0::2] assert_almost_equal(fone(x), fone_val, err_msg=msg) # check unary PyUFunc_F_F. msg = "PyUFunc_F_F" x = np.zeros(10, dtype=np.csingle)[0::2] assert_almost_equal(fone(x), fone_val, err_msg=msg) # check unary PyUFunc_D_D. msg = "PyUFunc_D_D" x = np.zeros(10, dtype=np.cdouble)[0::2] assert_almost_equal(fone(x), fone_val, err_msg=msg) # check unary PyUFunc_G_G. msg = "PyUFunc_G_G" x = np.zeros(10, dtype=np.clongdouble)[0::2] assert_almost_equal(fone(x), fone_val, err_msg=msg) # check binary PyUFunc_ff_f. msg = "PyUFunc_ff_f" x = np.ones(10, dtype=np.single)[0::2] assert_almost_equal(ftwo(x, x), ftwo_val, err_msg=msg) # check binary PyUFunc_dd_d. msg = "PyUFunc_dd_d" x = np.ones(10, dtype=np.double)[0::2] assert_almost_equal(ftwo(x, x), ftwo_val, err_msg=msg) # check binary PyUFunc_gg_g. msg = "PyUFunc_gg_g" x = np.ones(10, dtype=np.longdouble)[0::2] assert_almost_equal(ftwo(x, x), ftwo_val, err_msg=msg) # check binary PyUFunc_FF_F. msg = "PyUFunc_FF_F" x = np.ones(10, dtype=np.csingle)[0::2] assert_almost_equal(ftwo(x, x), ftwo_val, err_msg=msg) # check binary PyUFunc_DD_D. msg = "PyUFunc_DD_D" x = np.ones(10, dtype=np.cdouble)[0::2] assert_almost_equal(ftwo(x, x), ftwo_val, err_msg=msg) # check binary PyUFunc_GG_G. msg = "PyUFunc_GG_G" x = np.ones(10, dtype=np.clongdouble)[0::2] assert_almost_equal(ftwo(x, x), ftwo_val, err_msg=msg) # class to use in testing object method loops class foo(object): def conjugate(self) : return np.bool_(1) def logical_xor(self, obj) : return np.bool_(1) # check unary PyUFunc_O_O msg = "PyUFunc_O_O" x = np.ones(10, dtype=np.object)[0::2] assert_(np.all(np.abs(x) == 1), msg) # check unary PyUFunc_O_O_method msg = "PyUFunc_O_O_method" x = np.zeros(10, dtype=np.object)[0::2] for i in range(len(x)) : x[i] = foo() assert_(np.all(np.conjugate(x) == True), msg) # check binary PyUFunc_OO_O msg = "PyUFunc_OO_O" x = np.ones(10, dtype=np.object)[0::2] assert_(np.all(np.add(x, x) == 2), msg) # check binary PyUFunc_OO_O_method msg = "PyUFunc_OO_O_method" x = np.zeros(10, dtype=np.object)[0::2] for i in range(len(x)) : x[i] = foo() assert_(np.all(np.logical_xor(x, x)), msg) # check PyUFunc_On_Om # fixme -- I don't know how to do this yet def test_all_ufunc(self) : """Try to check presence and results of all ufuncs. The list of ufuncs comes from generate_umath.py and is as follows: ===== ==== ============= =============== ======================== done args function types notes ===== ==== ============= =============== ======================== n 1 conjugate nums + O n 1 absolute nums + O complex -> real n 1 negative nums + O n 1 sign nums + O -> int n 1 invert bool + ints + O flts raise an error n 1 degrees real + M cmplx raise an error n 1 radians real + M cmplx raise an error n 1 arccos flts + M n 1 arccosh flts + M n 1 arcsin flts + M n 1 arcsinh flts + M n 1 arctan flts + M n 1 arctanh flts + M n 1 cos flts + M n 1 sin flts + M n 1 tan flts + M n 1 cosh flts + M n 1 sinh flts + M n 1 tanh flts + M n 1 exp flts + M n 1 expm1 flts + M n 1 log flts + M n 1 log10 flts + M n 1 log1p flts + M n 1 sqrt flts + M real x < 0 raises error n 1 ceil real + M n 1 trunc real + M n 1 floor real + M n 1 fabs real + M n 1 rint flts + M n 1 isnan flts -> bool n 1 isinf flts -> bool n 1 isfinite flts -> bool n 1 signbit real -> bool n 1 modf real -> (frac, int) n 1 logical_not bool + nums + M -> bool n 2 left_shift ints + O flts raise an error n 2 right_shift ints + O flts raise an error n 2 add bool + nums + O boolean + is || n 2 subtract bool + nums + O boolean - is ^ n 2 multiply bool + nums + O boolean * is & n 2 divide nums + O n 2 floor_divide nums + O n 2 true_divide nums + O bBhH -> f, iIlLqQ -> d n 2 fmod nums + M n 2 power nums + O n 2 greater bool + nums + O -> bool n 2 greater_equal bool + nums + O -> bool n 2 less bool + nums + O -> bool n 2 less_equal bool + nums + O -> bool n 2 equal bool + nums + O -> bool n 2 not_equal bool + nums + O -> bool n 2 logical_and bool + nums + M -> bool n 2 logical_or bool + nums + M -> bool n 2 logical_xor bool + nums + M -> bool n 2 maximum bool + nums + O n 2 minimum bool + nums + O n 2 bitwise_and bool + ints + O flts raise an error n 2 bitwise_or bool + ints + O flts raise an error n 2 bitwise_xor bool + ints + O flts raise an error n 2 arctan2 real + M n 2 remainder ints + real + O n 2 hypot real + M ===== ==== ============= =============== ======================== Types other than those listed will be accepted, but they are cast to the smallest compatible type for which the function is defined. The casting rules are: bool -> int8 -> float32 ints -> double """ pass def test_signature(self): # the arguments to test_signature are: nin, nout, core_signature # pass assert_equal(umt.test_signature(2, 1, "(i),(i)->()"), 1) # pass. empty core signature; treat as plain ufunc (with trivial core) assert_equal(umt.test_signature(2, 1, "(),()->()"), 0) # in the following calls, a ValueError should be raised because # of error in core signature # error: extra parenthesis msg = "core_sig: extra parenthesis" try: ret = umt.test_signature(2, 1, "((i)),(i)->()") assert_equal(ret, None, err_msg=msg) except ValueError: None # error: parenthesis matching msg = "core_sig: parenthesis matching" try: ret = umt.test_signature(2, 1, "(i),)i(->()") assert_equal(ret, None, err_msg=msg) except ValueError: None # error: incomplete signature. letters outside of parenthesis are ignored msg = "core_sig: incomplete signature" try: ret = umt.test_signature(2, 1, "(i),->()") assert_equal(ret, None, err_msg=msg) except ValueError: None # error: incomplete signature. 2 output arguments are specified msg = "core_sig: incomplete signature" try: ret = umt.test_signature(2, 2, "(i),(i)->()") assert_equal(ret, None, err_msg=msg) except ValueError: None # more complicated names for variables assert_equal(umt.test_signature(2, 1, "(i1,i2),(J_1)->(_kAB)"), 1) def test_get_signature(self): assert_equal(umt.inner1d.signature, "(i),(i)->()") def test_forced_sig(self): a = 0.5*np.arange(3, dtype='f8') assert_equal(np.add(a, 0.5), [0.5, 1, 1.5]) assert_equal(np.add(a, 0.5, sig='i', casting='unsafe'), [0, 0, 1]) assert_equal(np.add(a, 0.5, sig='ii->i', casting='unsafe'), [0, 0, 1]) assert_equal(np.add(a, 0.5, sig=('i4',), casting='unsafe'), [0, 0, 1]) assert_equal(np.add(a, 0.5, sig=('i4', 'i4', 'i4'), casting='unsafe'), [0, 0, 1]) b = np.zeros((3,), dtype='f8') np.add(a, 0.5, out=b) assert_equal(b, [0.5, 1, 1.5]) b[:] = 0 np.add(a, 0.5, sig='i', out=b, casting='unsafe') assert_equal(b, [0, 0, 1]) b[:] = 0 np.add(a, 0.5, sig='ii->i', out=b, casting='unsafe') assert_equal(b, [0, 0, 1]) b[:] = 0 np.add(a, 0.5, sig=('i4',), out=b, casting='unsafe') assert_equal(b, [0, 0, 1]) b[:] = 0 np.add(a, 0.5, sig=('i4', 'i4', 'i4'), out=b, casting='unsafe') assert_equal(b, [0, 0, 1]) def test_inner1d(self): a = np.arange(6).reshape((2, 3)) assert_array_equal(umt.inner1d(a, a), np.sum(a*a, axis=-1)) a = np.arange(6) assert_array_equal(umt.inner1d(a, a), np.sum(a*a)) def test_broadcast(self): msg = "broadcast" a = np.arange(4).reshape((2, 1, 2)) b = np.arange(4).reshape((1, 2, 2)) assert_array_equal(umt.inner1d(a, b), np.sum(a*b, axis=-1), err_msg=msg) msg = "extend & broadcast loop dimensions" b = np.arange(4).reshape((2, 2)) assert_array_equal(umt.inner1d(a, b), np.sum(a*b, axis=-1), err_msg=msg) msg = "broadcast in core dimensions" a = np.arange(8).reshape((4, 2)) b = np.arange(4).reshape((4, 1)) assert_array_equal(umt.inner1d(a, b), np.sum(a*b, axis=-1), err_msg=msg) msg = "extend & broadcast core and loop dimensions" a = np.arange(8).reshape((4, 2)) b = np.array(7) assert_array_equal(umt.inner1d(a, b), np.sum(a*b, axis=-1), err_msg=msg) msg = "broadcast should fail" a = np.arange(2).reshape((2, 1, 1)) b = np.arange(3).reshape((3, 1, 1)) try: ret = umt.inner1d(a, b) assert_equal(ret, None, err_msg=msg) except ValueError: None def test_type_cast(self): msg = "type cast" a = np.arange(6, dtype='short').reshape((2, 3)) assert_array_equal(umt.inner1d(a, a), np.sum(a*a, axis=-1), err_msg=msg) msg = "type cast on one argument" a = np.arange(6).reshape((2, 3)) b = a+0.1 assert_array_almost_equal(umt.inner1d(a, a), np.sum(a*a, axis=-1), err_msg=msg) def test_endian(self): msg = "big endian" a = np.arange(6, dtype='>i4').reshape((2, 3)) assert_array_equal(umt.inner1d(a, a), np.sum(a*a, axis=-1), err_msg=msg) msg = "little endian" a = np.arange(6, dtype=' 0, m > 0: fine # n = 0, m > 0: fine, doing 0 reductions of m-element arrays # n > 0, m = 0: can't reduce a 0-element array, ValueError # n = 0, m = 0: can't reduce a 0-element array, ValueError (for # consistency with the above case) # This test doesn't actually look at return values, it just checks to # make sure that error we get an error in exactly those cases where we # expect one, and assumes the calculations themselves are done # correctly. def ok(f, *args, **kwargs): f(*args, **kwargs) def err(f, *args, **kwargs): assert_raises(ValueError, f, *args, **kwargs) def t(expect, func, n, m): expect(func, np.zeros((n, m)), axis=1) expect(func, np.zeros((m, n)), axis=0) expect(func, np.zeros((n // 2, n // 2, m)), axis=2) expect(func, np.zeros((n // 2, m, n // 2)), axis=1) expect(func, np.zeros((n, m // 2, m // 2)), axis=(1, 2)) expect(func, np.zeros((m // 2, n, m // 2)), axis=(0, 2)) expect(func, np.zeros((m // 3, m // 3, m // 3, n // 2, n //2)), axis=(0, 1, 2)) # Check what happens if the inner (resp. outer) dimensions are a # mix of zero and non-zero: expect(func, np.zeros((10, m, n)), axis=(0, 1)) expect(func, np.zeros((10, n, m)), axis=(0, 2)) expect(func, np.zeros((m, 10, n)), axis=0) expect(func, np.zeros((10, m, n)), axis=1) expect(func, np.zeros((10, n, m)), axis=2) # np.maximum is just an arbitrary ufunc with no reduction identity assert_equal(np.maximum.identity, None) t(ok, np.maximum.reduce, 30, 30) t(ok, np.maximum.reduce, 0, 30) t(err, np.maximum.reduce, 30, 0) t(err, np.maximum.reduce, 0, 0) err(np.maximum.reduce, []) np.maximum.reduce(np.zeros((0, 0)), axis=()) # all of the combinations are fine for a reduction that has an # identity t(ok, np.add.reduce, 30, 30) t(ok, np.add.reduce, 0, 30) t(ok, np.add.reduce, 30, 0) t(ok, np.add.reduce, 0, 0) np.add.reduce([]) np.add.reduce(np.zeros((0, 0)), axis=()) # OTOH, accumulate always makes sense for any combination of n and m, # because it maps an m-element array to an m-element array. These # tests are simpler because accumulate doesn't accept multiple axes. for uf in (np.maximum, np.add): uf.accumulate(np.zeros((30, 0)), axis=0) uf.accumulate(np.zeros((0, 30)), axis=0) uf.accumulate(np.zeros((30, 30)), axis=0) uf.accumulate(np.zeros((0, 0)), axis=0) def test_safe_casting(self): # In old versions of numpy, in-place operations used the 'unsafe' # casting rules. In some future version, 'same_kind' will become the # default. a = np.array([1, 2, 3], dtype=int) # Non-in-place addition is fine assert_array_equal(assert_no_warnings(np.add, a, 1.1), [2.1, 3.1, 4.1]) assert_warns(DeprecationWarning, np.add, a, 1.1, out=a) assert_array_equal(a, [2, 3, 4]) def add_inplace(a, b): a += b assert_warns(DeprecationWarning, add_inplace, a, 1.1) assert_array_equal(a, [3, 4, 5]) # Make sure that explicitly overriding the warning is allowed: assert_no_warnings(np.add, a, 1.1, out=a, casting="unsafe") assert_array_equal(a, [4, 5, 6]) # There's no way to propagate exceptions from the place where we issue # this deprecation warning, so we must throw the exception away # entirely rather than cause it to be raised at some other point, or # trigger some other unsuspecting if (PyErr_Occurred()) { ...} at some # other location entirely. import warnings import sys if sys.version_info[0] >= 3: from io import StringIO else: from StringIO import StringIO with warnings.catch_warnings(): warnings.simplefilter("error") old_stderr = sys.stderr try: sys.stderr = StringIO() # No error, but dumps to stderr a += 1.1 # No error on the next bit of code executed either 1 + 1 assert_("Implicitly casting" in sys.stderr.getvalue()) finally: sys.stderr = old_stderr def test_ufunc_custom_out(self): # Test ufunc with built in input types and custom output type a = np.array([0, 1, 2], dtype='i8') b = np.array([0, 1, 2], dtype='i8') c = np.empty(3, dtype=rational) # Output must be specified so numpy knows what # ufunc signature to look for result = test_add(a, b, c) assert_equal(result, np.array([0, 2, 4], dtype=rational)) # no output type should raise TypeError assert_raises(TypeError, test_add, a, b) def test_operand_flags(self): a = np.arange(16, dtype='l').reshape(4, 4) b = np.arange(9, dtype='l').reshape(3, 3) opflag_tests.inplace_add(a[:-1, :-1], b) assert_equal(a, np.array([[0, 2, 4, 3], [7, 9, 11, 7], [14, 16, 18, 11], [12, 13, 14, 15]], dtype='l')) a = np.array(0) opflag_tests.inplace_add(a, 3) assert_equal(a, 3) opflag_tests.inplace_add(a, [3, 4]) assert_equal(a, 10) def test_struct_ufunc(self): import numpy.core.struct_ufunc_test as struct_ufunc a = np.array([(1, 2, 3)], dtype='u8,u8,u8') b = np.array([(1, 2, 3)], dtype='u8,u8,u8') result = struct_ufunc.add_triplet(a, b) assert_equal(result, np.array([(2, 4, 6)], dtype='u8,u8,u8')) def test_custom_ufunc(self): a = np.array([rational(1, 2), rational(1, 3), rational(1, 4)], dtype=rational); b = np.array([rational(1, 2), rational(1, 3), rational(1, 4)], dtype=rational); result = test_add_rationals(a, b) expected = np.array([rational(1), rational(2, 3), rational(1, 2)], dtype=rational); assert_equal(result, expected); def test_custom_array_like(self): class MyThing(object): __array_priority__ = 1000 rmul_count = 0 getitem_count = 0 def __init__(self, shape): self.shape = shape def __len__(self): return self.shape[0] def __getitem__(self, i): MyThing.getitem_count += 1 if not isinstance(i, tuple): i = (i,) if len(i) > len(self.shape): raise IndexError("boo") return MyThing(self.shape[len(i):]) def __rmul__(self, other): MyThing.rmul_count += 1 return self np.float64(5)*MyThing((3, 3)) assert_(MyThing.rmul_count == 1, MyThing.rmul_count) assert_(MyThing.getitem_count <= 2, MyThing.getitem_count) def test_inplace_fancy_indexing(self): a = np.arange(10) np.add.at(a, [2, 5, 2], 1) assert_equal(a, [0, 1, 4, 3, 4, 6, 6, 7, 8, 9]) a = np.arange(10) b = np.array([100, 100, 100]) np.add.at(a, [2, 5, 2], b) assert_equal(a, [0, 1, 202, 3, 4, 105, 6, 7, 8, 9]) a = np.arange(9).reshape(3, 3) b = np.array([[100, 100, 100], [200, 200, 200], [300, 300, 300]]) np.add.at(a, (slice(None), [1, 2, 1]), b) assert_equal(a, [[0, 201, 102], [3, 404, 205], [6, 607, 308]]) a = np.arange(27).reshape(3, 3, 3) b = np.array([100, 200, 300]) np.add.at(a, (slice(None), slice(None), [1, 2, 1]), b) assert_equal(a, [[[0, 401, 202], [3, 404, 205], [6, 407, 208]], [[9, 410, 211], [12, 413, 214], [15, 416, 217]], [[18, 419, 220], [21, 422, 223], [24, 425, 226]]]) a = np.arange(9).reshape(3, 3) b = np.array([[100, 100, 100], [200, 200, 200], [300, 300, 300]]) np.add.at(a, ([1, 2, 1], slice(None)), b) assert_equal(a, [[0, 1, 2], [403, 404, 405], [206, 207, 208]]) a = np.arange(27).reshape(3, 3, 3) b = np.array([100, 200, 300]) np.add.at(a, (slice(None), [1, 2, 1], slice(None)), b) assert_equal(a, [[[0, 1, 2 ], [203, 404, 605], [106, 207, 308]], [[9, 10, 11 ], [212, 413, 614], [115, 216, 317]], [[18, 19, 20 ], [221, 422, 623], [124, 225, 326]]]) a = np.arange(9).reshape(3, 3) b = np.array([100, 200, 300]) np.add.at(a, (0, [1, 2, 1]), b) assert_equal(a, [[0, 401, 202], [3, 4, 5], [6, 7, 8]]) a = np.arange(27).reshape(3, 3, 3) b = np.array([100, 200, 300]) np.add.at(a, ([1, 2, 1], 0, slice(None)), b) assert_equal(a, [[[0, 1, 2], [3, 4, 5], [6, 7, 8]], [[209, 410, 611], [12, 13, 14], [15, 16, 17]], [[118, 219, 320], [21, 22, 23], [24, 25, 26]]]) a = np.arange(27).reshape(3, 3, 3) b = np.array([100, 200, 300]) np.add.at(a, (slice(None), slice(None), slice(None)), b) assert_equal(a, [[[100, 201, 302], [103, 204, 305], [106, 207, 308]], [[109, 210, 311], [112, 213, 314], [115, 216, 317]], [[118, 219, 320], [121, 222, 323], [124, 225, 326]]]) a = np.arange(10) np.negative.at(a, [2, 5, 2]) assert_equal(a, [0, 1, 2, 3, 4, -5, 6, 7, 8, 9]) # Test 0-dim array a = np.array(0) np.add.at(a, (), 1) assert_equal(a, 1) assert_raises(IndexError, np.add.at, a, 0, 1) assert_raises(IndexError, np.add.at, a, [], 1) # Test mixed dtypes a = np.arange(10) np.power.at(a, [1, 2, 3, 2], 3.5) assert_equal(a, np.array([0, 1, 4414, 46, 4, 5, 6, 7, 8, 9])) # Test boolean indexing and boolean ufuncs a = np.arange(10) index = a % 2 == 0 np.equal.at(a, index, [0, 2, 4, 6, 8]) assert_equal(a, [1, 1, 1, 3, 1, 5, 1, 7, 1, 9]) # Test unary operator a = np.arange(10, dtype='u4') np.invert.at(a, [2, 5, 2]) assert_equal(a, [0, 1, 2, 3, 4, 5 ^ 0xffffffff, 6, 7, 8, 9]) # Test empty subspace orig = np.arange(4) a = orig[:, None][:, 0:0] np.add.at(a, [0, 1], 3) assert_array_equal(orig, np.arange(4)) # Test with swapped byte order index = np.array([1, 2, 1], np.dtype('i').newbyteorder()) values = np.array([1, 2, 3, 4], np.dtype('f').newbyteorder()) np.add.at(values, index, 3) assert_array_equal(values, [1, 8, 6, 4]) # Test exception thrown values = np.array(['a', 1], dtype=np.object) self.assertRaises(TypeError, np.add.at, values, [0, 1], 1) assert_array_equal(values, np.array(['a', 1], dtype=np.object)) if __name__ == "__main__": run_module_suite() numpy-1.8.2/numpy/core/tests/test_datetime.py0000664000175100017510000024525012370216242022502 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function import os, pickle import numpy import numpy as np from numpy.testing import * from numpy.compat import asbytes import datetime # Use pytz to test out various time zones if available try: from pytz import timezone as tz _has_pytz = True except ImportError: _has_pytz = False class TestDateTime(TestCase): def test_datetime_dtype_creation(self): for unit in ['Y', 'M', 'W', 'D', 'h', 'm', 's', 'ms', 'us', 'ns', 'ps', 'fs', 'as']: dt1 = np.dtype('M8[750%s]'%unit) assert_(dt1 == np.dtype('datetime64[750%s]' % unit)) dt2 = np.dtype('m8[%s]' % unit) assert_(dt2 == np.dtype('timedelta64[%s]' % unit)) # Generic units shouldn't add [] to the end assert_equal(str(np.dtype("M8")), "datetime64") # Should be possible to specify the endianness assert_equal(np.dtype("=M8"), np.dtype("M8")) assert_equal(np.dtype("=M8[s]"), np.dtype("M8[s]")) assert_(np.dtype(">M8") == np.dtype("M8") or np.dtype("M8[D]") == np.dtype("M8[D]") or np.dtype("M8") != np.dtype("m8") == np.dtype("m8") or np.dtype("m8[D]") == np.dtype("m8[D]") or np.dtype("m8") != np.dtype(" Scalars assert_equal(np.datetime64(b, '[s]'), np.datetime64('NaT', '[s]')) assert_equal(np.datetime64(b, '[ms]'), np.datetime64('NaT', '[ms]')) assert_equal(np.datetime64(b, '[M]'), np.datetime64('NaT', '[M]')) assert_equal(np.datetime64(b, '[Y]'), np.datetime64('NaT', '[Y]')) assert_equal(np.datetime64(b, '[W]'), np.datetime64('NaT', '[W]')) # Arrays -> Scalars assert_equal(np.datetime64(a, '[s]'), np.datetime64('NaT', '[s]')) assert_equal(np.datetime64(a, '[ms]'), np.datetime64('NaT', '[ms]')) assert_equal(np.datetime64(a, '[M]'), np.datetime64('NaT', '[M]')) assert_equal(np.datetime64(a, '[Y]'), np.datetime64('NaT', '[Y]')) assert_equal(np.datetime64(a, '[W]'), np.datetime64('NaT', '[W]')) def test_days_creation(self): assert_equal(np.array('1599', dtype='M8[D]').astype('i8'), (1600-1970)*365 - (1972-1600)/4 + 3 - 365) assert_equal(np.array('1600', dtype='M8[D]').astype('i8'), (1600-1970)*365 - (1972-1600)/4 + 3) assert_equal(np.array('1601', dtype='M8[D]').astype('i8'), (1600-1970)*365 - (1972-1600)/4 + 3 + 366) assert_equal(np.array('1900', dtype='M8[D]').astype('i8'), (1900-1970)*365 - (1970-1900)//4) assert_equal(np.array('1901', dtype='M8[D]').astype('i8'), (1900-1970)*365 - (1970-1900)//4 + 365) assert_equal(np.array('1967', dtype='M8[D]').astype('i8'), -3*365 - 1) assert_equal(np.array('1968', dtype='M8[D]').astype('i8'), -2*365 - 1) assert_equal(np.array('1969', dtype='M8[D]').astype('i8'), -1*365) assert_equal(np.array('1970', dtype='M8[D]').astype('i8'), 0*365) assert_equal(np.array('1971', dtype='M8[D]').astype('i8'), 1*365) assert_equal(np.array('1972', dtype='M8[D]').astype('i8'), 2*365) assert_equal(np.array('1973', dtype='M8[D]').astype('i8'), 3*365 + 1) assert_equal(np.array('1974', dtype='M8[D]').astype('i8'), 4*365 + 1) assert_equal(np.array('2000', dtype='M8[D]').astype('i8'), (2000 - 1970)*365 + (2000 - 1972)//4) assert_equal(np.array('2001', dtype='M8[D]').astype('i8'), (2000 - 1970)*365 + (2000 - 1972)//4 + 366) assert_equal(np.array('2400', dtype='M8[D]').astype('i8'), (2400 - 1970)*365 + (2400 - 1972)//4 - 3) assert_equal(np.array('2401', dtype='M8[D]').astype('i8'), (2400 - 1970)*365 + (2400 - 1972)//4 - 3 + 366) assert_equal(np.array('1600-02-29', dtype='M8[D]').astype('i8'), (1600-1970)*365 - (1972-1600)//4 + 3 + 31 + 28) assert_equal(np.array('1600-03-01', dtype='M8[D]').astype('i8'), (1600-1970)*365 - (1972-1600)//4 + 3 + 31 + 29) assert_equal(np.array('2000-02-29', dtype='M8[D]').astype('i8'), (2000 - 1970)*365 + (2000 - 1972)//4 + 31 + 28) assert_equal(np.array('2000-03-01', dtype='M8[D]').astype('i8'), (2000 - 1970)*365 + (2000 - 1972)//4 + 31 + 29) assert_equal(np.array('2001-03-22', dtype='M8[D]').astype('i8'), (2000 - 1970)*365 + (2000 - 1972)//4 + 366 + 31 + 28 + 21) def test_days_to_pydate(self): assert_equal(np.array('1599', dtype='M8[D]').astype('O'), datetime.date(1599, 1, 1)) assert_equal(np.array('1600', dtype='M8[D]').astype('O'), datetime.date(1600, 1, 1)) assert_equal(np.array('1601', dtype='M8[D]').astype('O'), datetime.date(1601, 1, 1)) assert_equal(np.array('1900', dtype='M8[D]').astype('O'), datetime.date(1900, 1, 1)) assert_equal(np.array('1901', dtype='M8[D]').astype('O'), datetime.date(1901, 1, 1)) assert_equal(np.array('2000', dtype='M8[D]').astype('O'), datetime.date(2000, 1, 1)) assert_equal(np.array('2001', dtype='M8[D]').astype('O'), datetime.date(2001, 1, 1)) assert_equal(np.array('1600-02-29', dtype='M8[D]').astype('O'), datetime.date(1600, 2, 29)) assert_equal(np.array('1600-03-01', dtype='M8[D]').astype('O'), datetime.date(1600, 3, 1)) assert_equal(np.array('2001-03-22', dtype='M8[D]').astype('O'), datetime.date(2001, 3, 22)) def test_dtype_comparison(self): assert_(not (np.dtype('M8[us]') == np.dtype('M8[ms]'))) assert_(np.dtype('M8[us]') != np.dtype('M8[ms]')) assert_(np.dtype('M8[2D]') != np.dtype('M8[D]')) assert_(np.dtype('M8[D]') != np.dtype('M8[2D]')) def test_pydatetime_creation(self): a = np.array(['1960-03-12', datetime.date(1960, 3, 12)], dtype='M8[D]') assert_equal(a[0], a[1]) a = np.array(['1999-12-31', datetime.date(1999, 12, 31)], dtype='M8[D]') assert_equal(a[0], a[1]) a = np.array(['2000-01-01', datetime.date(2000, 1, 1)], dtype='M8[D]') assert_equal(a[0], a[1]) # Will fail if the date changes during the exact right moment a = np.array(['today', datetime.date.today()], dtype='M8[D]') assert_equal(a[0], a[1]) # datetime.datetime.now() returns local time, not UTC #a = np.array(['now', datetime.datetime.now()], dtype='M8[s]') #assert_equal(a[0], a[1]) # A datetime.date will raise if you try to give it time units assert_raises(TypeError, np.array, datetime.date(1960, 3, 12), dtype='M8[s]') def test_datetime_string_conversion(self): a = ['2011-03-16', '1920-01-01', '2013-05-19'] str_a = np.array(a, dtype='S') dt_a = np.array(a, dtype='M') str_b = np.empty_like(str_a) dt_b = np.empty_like(dt_a) # String to datetime assert_equal(dt_a, str_a.astype('M')) assert_equal(dt_a.dtype, str_a.astype('M').dtype) dt_b[...] = str_a assert_equal(dt_a, dt_b) # Datetime to string assert_equal(str_a, dt_a.astype('S0')) str_b[...] = dt_a assert_equal(str_a, str_b) # Convert the 'S' to 'U' str_a = str_a.astype('U') str_b = str_b.astype('U') # Unicode to datetime assert_equal(dt_a, str_a.astype('M')) assert_equal(dt_a.dtype, str_a.astype('M').dtype) dt_b[...] = str_a assert_equal(dt_a, dt_b) # Datetime to unicode assert_equal(str_a, dt_a.astype('U')) str_b[...] = dt_a assert_equal(str_a, str_b) def test_datetime_array_str(self): a = np.array(['2011-03-16', '1920-01-01', '2013-05-19'], dtype='M') assert_equal(str(a), "['2011-03-16' '1920-01-01' '2013-05-19']") a = np.array(['2011-03-16T13:55Z', '1920-01-01T03:12Z'], dtype='M') assert_equal(np.array2string(a, separator=', ', formatter={'datetime': lambda x : "'%s'" % np.datetime_as_string(x, timezone='UTC')}), "['2011-03-16T13:55Z', '1920-01-01T03:12Z']") # Check that one NaT doesn't corrupt subsequent entries a = np.array(['2010', 'NaT', '2030']).astype('M') assert_equal(str(a), "['2010' 'NaT' '2030']") def test_pickle(self): # Check that pickle roundtripping works dt = np.dtype('M8[7D]') assert_equal(pickle.loads(pickle.dumps(dt)), dt) dt = np.dtype('M8[W]') assert_equal(pickle.loads(pickle.dumps(dt)), dt) # Check that loading pickles from 1.6 works pkl = "cnumpy\ndtype\np0\n(S'M8'\np1\nI0\nI1\ntp2\nRp3\n" + \ "(I4\nS'<'\np4\nNNNI-1\nI-1\nI0\n((dp5\n(S'D'\np6\n" + \ "I7\nI1\nI1\ntp7\ntp8\ntp9\nb." assert_equal(pickle.loads(asbytes(pkl)), np.dtype(''\np4\nNNNI-1\nI-1\nI0\n((dp5\n(S'us'\np6\n" + \ "I1\nI1\nI1\ntp7\ntp8\ntp9\nb." assert_equal(pickle.loads(asbytes(pkl)), np.dtype('>M8[us]')) def test_setstate(self): "Verify that datetime dtype __setstate__ can handle bad arguments" dt = np.dtype('>M8[us]') assert_raises(ValueError, dt.__setstate__, (4, '>', None, None, None, -1, -1, 0, 1)) assert (dt.__reduce__()[2] == np.dtype('>M8[us]').__reduce__()[2]) assert_raises(TypeError, dt.__setstate__, (4, '>', None, None, None, -1, -1, 0, ({}, 'xxx'))) assert (dt.__reduce__()[2] == np.dtype('>M8[us]').__reduce__()[2]) def test_dtype_promotion(self): # datetime datetime computes the metadata gcd # timedelta timedelta computes the metadata gcd for mM in ['m', 'M']: assert_equal( np.promote_types(np.dtype(mM+'8[2Y]'), np.dtype(mM+'8[2Y]')), np.dtype(mM+'8[2Y]')) assert_equal( np.promote_types(np.dtype(mM+'8[12Y]'), np.dtype(mM+'8[15Y]')), np.dtype(mM+'8[3Y]')) assert_equal( np.promote_types(np.dtype(mM+'8[62M]'), np.dtype(mM+'8[24M]')), np.dtype(mM+'8[2M]')) assert_equal( np.promote_types(np.dtype(mM+'8[1W]'), np.dtype(mM+'8[2D]')), np.dtype(mM+'8[1D]')) assert_equal( np.promote_types(np.dtype(mM+'8[W]'), np.dtype(mM+'8[13s]')), np.dtype(mM+'8[s]')) assert_equal( np.promote_types(np.dtype(mM+'8[13W]'), np.dtype(mM+'8[49s]')), np.dtype(mM+'8[7s]')) # timedelta timedelta raises when there is no reasonable gcd assert_raises(TypeError, np.promote_types, np.dtype('m8[Y]'), np.dtype('m8[D]')) assert_raises(TypeError, np.promote_types, np.dtype('m8[M]'), np.dtype('m8[W]')) # timedelta timedelta may overflow with big unit ranges assert_raises(OverflowError, np.promote_types, np.dtype('m8[W]'), np.dtype('m8[fs]')) 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("..j", [0, 0]) assert_raises(ValueError, np.einsum, "j->.j...", [0, 0]) # invalid subscript character assert_raises(ValueError, np.einsum, "i%...", [0, 0]) assert_raises(ValueError, np.einsum, "...j$", [0, 0]) assert_raises(ValueError, np.einsum, "i->&", [0, 0]) # output subscripts must appear in input assert_raises(ValueError, np.einsum, "i->ij", [0, 0]) # output subscripts may only be specified once assert_raises(ValueError, np.einsum, "ij->jij", [[0, 0], [0, 0]]) # dimensions much match when being collapsed assert_raises(ValueError, np.einsum, "ii", np.arange(6).reshape(2, 3)) assert_raises(ValueError, np.einsum, "ii->i", np.arange(6).reshape(2, 3)) # broadcasting to new dimensions must be enabled explicitly assert_raises(ValueError, np.einsum, "i", np.arange(6).reshape(2, 3)) assert_raises(ValueError, np.einsum, "i->i", [[0, 1], [0, 1]], out=np.arange(4).reshape(2, 2)) def test_einsum_views(self): # pass-through a = np.arange(6) a.shape = (2, 3) b = np.einsum("...", a) assert_(b.base is a) b = np.einsum(a, [Ellipsis]) assert_(b.base is a) b = np.einsum("ij", a) assert_(b.base is a) assert_equal(b, a) b = np.einsum(a, [0, 1]) assert_(b.base is a) assert_equal(b, a) # transpose a = np.arange(6) a.shape = (2, 3) b = np.einsum("ji", a) assert_(b.base is a) assert_equal(b, a.T) b = np.einsum(a, [1, 0]) assert_(b.base is a) assert_equal(b, a.T) # diagonal a = np.arange(9) a.shape = (3, 3) b = np.einsum("ii->i", a) assert_(b.base is a) assert_equal(b, [a[i, i] for i in range(3)]) b = np.einsum(a, [0, 0], [0]) assert_(b.base is a) assert_equal(b, [a[i, i] for i in range(3)]) # diagonal with various ways of broadcasting an additional dimension a = np.arange(27) a.shape = (3, 3, 3) b = np.einsum("...ii->...i", a) assert_(b.base is a) assert_equal(b, [[x[i, i] for i in range(3)] for x in a]) b = np.einsum(a, [Ellipsis, 0, 0], [Ellipsis, 0]) assert_(b.base is a) assert_equal(b, [[x[i, i] for i in range(3)] for x in a]) b = np.einsum("ii...->...i", a) assert_(b.base is a) assert_equal(b, [[x[i, i] for i in range(3)] for x in a.transpose(2, 0, 1)]) b = np.einsum(a, [0, 0, Ellipsis], [Ellipsis, 0]) assert_(b.base is a) assert_equal(b, [[x[i, i] for i in range(3)] for x in a.transpose(2, 0, 1)]) b = np.einsum("...ii->i...", a) assert_(b.base is a) assert_equal(b, [a[:, i, i] for i in range(3)]) b = np.einsum(a, [Ellipsis, 0, 0], [0, Ellipsis]) assert_(b.base is a) assert_equal(b, [a[:, i, i] for i in range(3)]) b = np.einsum("jii->ij", a) assert_(b.base is a) assert_equal(b, [a[:, i, i] for i in range(3)]) b = np.einsum(a, [1, 0, 0], [0, 1]) assert_(b.base is a) assert_equal(b, [a[:, i, i] for i in range(3)]) b = np.einsum("ii...->i...", a) assert_(b.base is a) assert_equal(b, [a.transpose(2, 0, 1)[:, i, i] for i in range(3)]) b = np.einsum(a, [0, 0, Ellipsis], [0, Ellipsis]) assert_(b.base is a) assert_equal(b, [a.transpose(2, 0, 1)[:, i, i] for i in range(3)]) b = np.einsum("i...i->i...", a) assert_(b.base is a) assert_equal(b, [a.transpose(1, 0, 2)[:, i, i] for i in range(3)]) b = np.einsum(a, [0, Ellipsis, 0], [0, Ellipsis]) assert_(b.base is a) assert_equal(b, [a.transpose(1, 0, 2)[:, i, i] for i in range(3)]) b = np.einsum("i...i->...i", a) assert_(b.base is a) assert_equal(b, [[x[i, i] for i in range(3)] for x in a.transpose(1, 0, 2)]) b = np.einsum(a, [0, Ellipsis, 0], [Ellipsis, 0]) assert_(b.base is a) assert_equal(b, [[x[i, i] for i in range(3)] for x in a.transpose(1, 0, 2)]) # triple diagonal a = np.arange(27) a.shape = (3, 3, 3) b = np.einsum("iii->i", a) assert_(b.base is a) assert_equal(b, [a[i, i, i] for i in range(3)]) b = np.einsum(a, [0, 0, 0], [0]) assert_(b.base is a) assert_equal(b, [a[i, i, i] for i in range(3)]) # swap axes a = np.arange(24) a.shape = (2, 3, 4) b = np.einsum("ijk->jik", a) assert_(b.base is a) assert_equal(b, a.swapaxes(0, 1)) b = np.einsum(a, [0, 1, 2], [1, 0, 2]) assert_(b.base is a) assert_equal(b, a.swapaxes(0, 1)) def check_einsum_sums(self, dtype): # Check various sums. Does many sizes to exercise unrolled loops. # sum(a, axis=-1) for n in range(1, 17): a = np.arange(n, dtype=dtype) assert_equal(np.einsum("i->", a), np.sum(a, axis=-1).astype(dtype)) assert_equal(np.einsum(a, [0], []), np.sum(a, axis=-1).astype(dtype)) for n in range(1, 17): a = np.arange(2*3*n, dtype=dtype).reshape(2, 3, n) assert_equal(np.einsum("...i->...", a), np.sum(a, axis=-1).astype(dtype)) assert_equal(np.einsum(a, [Ellipsis, 0], [Ellipsis]), np.sum(a, axis=-1).astype(dtype)) # sum(a, axis=0) for n in range(1, 17): a = np.arange(2*n, dtype=dtype).reshape(2, n) assert_equal(np.einsum("i...->...", a), np.sum(a, axis=0).astype(dtype)) assert_equal(np.einsum(a, [0, Ellipsis], [Ellipsis]), np.sum(a, axis=0).astype(dtype)) for n in range(1, 17): a = np.arange(2*3*n, dtype=dtype).reshape(2, 3, n) assert_equal(np.einsum("i...->...", a), np.sum(a, axis=0).astype(dtype)) assert_equal(np.einsum(a, [0, Ellipsis], [Ellipsis]), np.sum(a, axis=0).astype(dtype)) # trace(a) for n in range(1, 17): a = np.arange(n*n, dtype=dtype).reshape(n, n) assert_equal(np.einsum("ii", a), np.trace(a).astype(dtype)) assert_equal(np.einsum(a, [0, 0]), np.trace(a).astype(dtype)) # multiply(a, b) assert_equal(np.einsum("..., ...", 3, 4), 12) # scalar case for n in range(1, 17): a = np.arange(3*n, dtype=dtype).reshape(3, n) b = np.arange(2*3*n, dtype=dtype).reshape(2, 3, n) assert_equal(np.einsum("..., ...", a, b), np.multiply(a, b)) assert_equal(np.einsum(a, [Ellipsis], b, [Ellipsis]), np.multiply(a, b)) # inner(a,b) for n in range(1, 17): a = np.arange(2*3*n, dtype=dtype).reshape(2, 3, n) b = np.arange(n, dtype=dtype) assert_equal(np.einsum("...i, ...i", a, b), np.inner(a, b)) assert_equal(np.einsum(a, [Ellipsis, 0], b, [Ellipsis, 0]), np.inner(a, b)) for n in range(1, 11): a = np.arange(n*3*2, dtype=dtype).reshape(n, 3, 2) b = np.arange(n, dtype=dtype) assert_equal(np.einsum("i..., i...", a, b), np.inner(a.T, b.T).T) assert_equal(np.einsum(a, [0, Ellipsis], b, [0, Ellipsis]), np.inner(a.T, b.T).T) # outer(a,b) for n in range(1, 17): a = np.arange(3, dtype=dtype)+1 b = np.arange(n, dtype=dtype)+1 assert_equal(np.einsum("i,j", a, b), np.outer(a, b)) assert_equal(np.einsum(a, [0], b, [1]), np.outer(a, b)) # Suppress the complex warnings for the 'as f8' tests with warnings.catch_warnings(): warnings.simplefilter('ignore', np.ComplexWarning) # matvec(a,b) / a.dot(b) where a is matrix, b is vector for n in range(1, 17): a = np.arange(4*n, dtype=dtype).reshape(4, n) b = np.arange(n, dtype=dtype) assert_equal(np.einsum("ij, j", a, b), np.dot(a, b)) assert_equal(np.einsum(a, [0, 1], b, [1]), np.dot(a, b)) c = np.arange(4, dtype=dtype) np.einsum("ij,j", a, b, out=c, dtype='f8', casting='unsafe') assert_equal(c, np.dot(a.astype('f8'), b.astype('f8')).astype(dtype)) c[...] = 0 np.einsum(a, [0, 1], b, [1], out=c, dtype='f8', casting='unsafe') assert_equal(c, np.dot(a.astype('f8'), b.astype('f8')).astype(dtype)) for n in range(1, 17): a = np.arange(4*n, dtype=dtype).reshape(4, n) b = np.arange(n, dtype=dtype) assert_equal(np.einsum("ji,j", a.T, b.T), np.dot(b.T, a.T)) assert_equal(np.einsum(a.T, [1, 0], b.T, [1]), np.dot(b.T, a.T)) c = np.arange(4, dtype=dtype) np.einsum("ji,j", a.T, b.T, out=c, dtype='f8', casting='unsafe') assert_equal(c, np.dot(b.T.astype('f8'), a.T.astype('f8')).astype(dtype)) c[...] = 0 np.einsum(a.T, [1, 0], b.T, [1], out=c, dtype='f8', casting='unsafe') assert_equal(c, np.dot(b.T.astype('f8'), a.T.astype('f8')).astype(dtype)) # matmat(a,b) / a.dot(b) where a is matrix, b is matrix for n in range(1, 17): if n < 8 or dtype != 'f2': a = np.arange(4*n, dtype=dtype).reshape(4, n) b = np.arange(n*6, dtype=dtype).reshape(n, 6) assert_equal(np.einsum("ij,jk", a, b), np.dot(a, b)) assert_equal(np.einsum(a, [0, 1], b, [1, 2]), np.dot(a, b)) for n in range(1, 17): a = np.arange(4*n, dtype=dtype).reshape(4, n) b = np.arange(n*6, dtype=dtype).reshape(n, 6) c = np.arange(24, dtype=dtype).reshape(4, 6) np.einsum("ij,jk", a, b, out=c, dtype='f8', casting='unsafe') assert_equal(c, np.dot(a.astype('f8'), b.astype('f8')).astype(dtype)) c[...] = 0 np.einsum(a, [0, 1], b, [1, 2], out=c, dtype='f8', casting='unsafe') assert_equal(c, np.dot(a.astype('f8'), b.astype('f8')).astype(dtype)) # matrix triple product (note this is not currently an efficient # way to multiply 3 matrices) a = np.arange(12, dtype=dtype).reshape(3, 4) b = np.arange(20, dtype=dtype).reshape(4, 5) c = np.arange(30, dtype=dtype).reshape(5, 6) if dtype != 'f2': assert_equal(np.einsum("ij,jk,kl", a, b, c), a.dot(b).dot(c)) assert_equal(np.einsum(a, [0, 1], b, [1, 2], c, [2, 3]), a.dot(b).dot(c)) d = np.arange(18, dtype=dtype).reshape(3, 6) np.einsum("ij,jk,kl", a, b, c, out=d, dtype='f8', casting='unsafe') assert_equal(d, a.astype('f8').dot(b.astype('f8') ).dot(c.astype('f8')).astype(dtype)) d[...] = 0 np.einsum(a, [0, 1], b, [1, 2], c, [2, 3], out=d, dtype='f8', casting='unsafe') assert_equal(d, a.astype('f8').dot(b.astype('f8') ).dot(c.astype('f8')).astype(dtype)) # tensordot(a, b) if np.dtype(dtype) != np.dtype('f2'): a = np.arange(60, dtype=dtype).reshape(3, 4, 5) b = np.arange(24, dtype=dtype).reshape(4, 3, 2) assert_equal(np.einsum("ijk, jil -> kl", a, b), np.tensordot(a, b, axes=([1, 0], [0, 1]))) assert_equal(np.einsum(a, [0, 1, 2], b, [1, 0, 3], [2, 3]), np.tensordot(a, b, axes=([1, 0], [0, 1]))) c = np.arange(10, dtype=dtype).reshape(5, 2) np.einsum("ijk,jil->kl", a, b, out=c, dtype='f8', casting='unsafe') assert_equal(c, np.tensordot(a.astype('f8'), b.astype('f8'), axes=([1, 0], [0, 1])).astype(dtype)) c[...] = 0 np.einsum(a, [0, 1, 2], b, [1, 0, 3], [2, 3], out=c, dtype='f8', casting='unsafe') assert_equal(c, np.tensordot(a.astype('f8'), b.astype('f8'), axes=([1, 0], [0, 1])).astype(dtype)) # logical_and(logical_and(a!=0, b!=0), c!=0) a = np.array([1, 3, -2, 0, 12, 13, 0, 1], dtype=dtype) b = np.array([0, 3.5, 0., -2, 0, 1, 3, 12], dtype=dtype) c = np.array([True, True, False, True, True, False, True, True]) assert_equal(np.einsum("i,i,i->i", a, b, c, dtype='?', casting='unsafe'), np.logical_and(np.logical_and(a!=0, b!=0), c!=0)) assert_equal(np.einsum(a, [0], b, [0], c, [0], [0], dtype='?', casting='unsafe'), np.logical_and(np.logical_and(a!=0, b!=0), c!=0)) a = np.arange(9, dtype=dtype) assert_equal(np.einsum(",i->", 3, a), 3*np.sum(a)) assert_equal(np.einsum(3, [], a, [0], []), 3*np.sum(a)) assert_equal(np.einsum("i,->", a, 3), 3*np.sum(a)) assert_equal(np.einsum(a, [0], 3, [], []), 3*np.sum(a)) # Various stride0, contiguous, and SSE aligned variants for n in range(1, 25): a = np.arange(n, dtype=dtype) if np.dtype(dtype).itemsize > 1: assert_equal(np.einsum("...,...", a, a), np.multiply(a, a)) assert_equal(np.einsum("i,i", a, a), np.dot(a, a)) assert_equal(np.einsum("i,->i", a, 2), 2*a) assert_equal(np.einsum(",i->i", 2, a), 2*a) assert_equal(np.einsum("i,->", a, 2), 2*np.sum(a)) assert_equal(np.einsum(",i->", 2, a), 2*np.sum(a)) assert_equal(np.einsum("...,...", a[1:], a[:-1]), np.multiply(a[1:], a[:-1])) assert_equal(np.einsum("i,i", a[1:], a[:-1]), np.dot(a[1:], a[:-1])) assert_equal(np.einsum("i,->i", a[1:], 2), 2*a[1:]) assert_equal(np.einsum(",i->i", 2, a[1:]), 2*a[1:]) assert_equal(np.einsum("i,->", a[1:], 2), 2*np.sum(a[1:])) assert_equal(np.einsum(",i->", 2, a[1:]), 2*np.sum(a[1:])) # An object array, summed as the data type a = np.arange(9, dtype=object) b = np.einsum("i->", a, dtype=dtype, casting='unsafe') assert_equal(b, np.sum(a)) assert_equal(b.dtype, np.dtype(dtype)) b = np.einsum(a, [0], [], dtype=dtype, casting='unsafe') assert_equal(b, np.sum(a)) assert_equal(b.dtype, np.dtype(dtype)) # A case which was failing (ticket #1885) p = np.arange(2) + 1 q = np.arange(4).reshape(2, 2) + 3 r = np.arange(4).reshape(2, 2) + 7 assert_equal(np.einsum('z,mz,zm->', p, q, r), 253) def test_einsum_sums_int8(self): self.check_einsum_sums('i1'); def test_einsum_sums_uint8(self): self.check_einsum_sums('u1'); def test_einsum_sums_int16(self): self.check_einsum_sums('i2'); def test_einsum_sums_uint16(self): self.check_einsum_sums('u2'); def test_einsum_sums_int32(self): self.check_einsum_sums('i4'); def test_einsum_sums_uint32(self): self.check_einsum_sums('u4'); def test_einsum_sums_int64(self): self.check_einsum_sums('i8'); def test_einsum_sums_uint64(self): self.check_einsum_sums('u8'); def test_einsum_sums_float16(self): self.check_einsum_sums('f2'); def test_einsum_sums_float32(self): self.check_einsum_sums('f4'); def test_einsum_sums_float64(self): self.check_einsum_sums('f8'); def test_einsum_sums_longdouble(self): self.check_einsum_sums(np.longdouble); def test_einsum_sums_cfloat64(self): self.check_einsum_sums('c8'); def test_einsum_sums_cfloat128(self): self.check_einsum_sums('c16'); def test_einsum_sums_clongdouble(self): self.check_einsum_sums(np.clongdouble); def test_einsum_misc(self): # This call used to crash because of a bug in # PyArray_AssignZero a = np.ones((1, 2)) b = np.ones((2, 2, 1)) assert_equal(np.einsum('ij...,j...->i...', a, b), [[[2], [2]]]) # The iterator had an issue with buffering this reduction a = np.ones((5, 12, 4, 2, 3), np.int64) b = np.ones((5, 12, 11), np.int64) assert_equal(np.einsum('ijklm,ijn,ijn->', a, b, b), np.einsum('ijklm,ijn->', a, b)) # Issue #2027, was a problem in the contiguous 3-argument # inner loop implementation a = np.arange(1, 3) b = np.arange(1, 5).reshape(2, 2) c = np.arange(1, 9).reshape(4, 2) assert_equal(np.einsum('x,yx,zx->xzy', a, b, c), [[[1, 3], [3, 9], [5, 15], [7, 21]], [[8, 16], [16, 32], [24, 48], [32, 64]]]) 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() numpy-1.8.2/numpy/core/records.py0000664000175100017510000006467112370216242020154 0ustar vagrantvagrant00000000000000""" Record Arrays ============= Record arrays expose the fields of structured arrays as properties. Most commonly, ndarrays contain elements of a single type, e.g. floats, integers, bools etc. However, it is possible for elements to be combinations of these, such as:: >>> a = np.array([(1, 2.0), (1, 2.0)], dtype=[('x', int), ('y', float)]) >>> a array([(1, 2.0), (1, 2.0)], dtype=[('x', '>> a['x'] array([1, 1]) >>> a['y'] array([ 2., 2.]) Record arrays allow us to access fields as properties:: >>> ar = a.view(np.recarray) >>> ar.x array([1, 1]) >>> ar.y array([ 2., 2.]) """ from __future__ import division, absolute_import, print_function import sys import os from . import numeric as sb from .defchararray import chararray from . import numerictypes as nt from numpy.compat import isfileobj, bytes, long # All of the functions allow formats to be a dtype __all__ = ['record', 'recarray', 'format_parser'] ndarray = sb.ndarray _byteorderconv = {'b':'>', 'l':'<', 'n':'=', 'B':'>', 'L':'<', 'N':'=', 'S':'s', 's':'s', '>':'>', '<':'<', '=':'=', '|':'|', 'I':'|', 'i':'|'} # formats regular expression # allows multidimension spec with a tuple syntax in front # of the letter code '(2,3)f4' and ' ( 2 , 3 ) f4 ' # are equally allowed numfmt = nt.typeDict _typestr = nt._typestr def find_duplicate(list): """Find duplication in a list, return a list of duplicated elements""" dup = [] for i in range(len(list)): if (list[i] in list[i + 1:]): if (list[i] not in dup): dup.append(list[i]) return dup class format_parser: """ Class to convert formats, names, titles description to a dtype. After constructing the format_parser object, the dtype attribute is the converted data-type: ``dtype = format_parser(formats, names, titles).dtype`` Attributes ---------- dtype : dtype The converted data-type. Parameters ---------- formats : str or list of str The format description, either specified as a string with comma-separated format descriptions in the form ``'f8, i4, a5'``, or a list of format description strings in the form ``['f8', 'i4', 'a5']``. names : str or list/tuple of str The field names, either specified as a comma-separated string in the form ``'col1, col2, col3'``, or as a list or tuple of strings in the form ``['col1', 'col2', 'col3']``. An empty list can be used, in that case default field names ('f0', 'f1', ...) are used. titles : sequence Sequence of title strings. An empty list can be used to leave titles out. aligned : bool, optional If True, align the fields by padding as the C-compiler would. Default is False. byteorder : str, optional If specified, all the fields will be changed to the provided byte-order. Otherwise, the default byte-order is used. For all available string specifiers, see `dtype.newbyteorder`. See Also -------- dtype, typename, sctype2char Examples -------- >>> np.format_parser(['f8', 'i4', 'a5'], ['col1', 'col2', 'col3'], ... ['T1', 'T2', 'T3']).dtype dtype([(('T1', 'col1'), '>> np.format_parser(['f8', 'i4', 'a5'], ['col1', 'col2', 'col3'], ... []).dtype dtype([('col1', '>> np.format_parser(['f8', 'i4', 'a5'], [], []).dtype dtype([('f0', ' len(titles)): self._titles += [None] * (self._nfields - len(titles)) def _createdescr(self, byteorder): descr = sb.dtype({'names':self._names, 'formats':self._f_formats, 'offsets':self._offsets, 'titles':self._titles}) if (byteorder is not None): byteorder = _byteorderconv[byteorder[0]] descr = descr.newbyteorder(byteorder) self._descr = descr class record(nt.void): """A data-type scalar that allows field access as attribute lookup. """ def __repr__(self): return self.__str__() def __str__(self): return str(self.item()) def __getattribute__(self, attr): if attr in ['setfield', 'getfield', 'dtype']: return nt.void.__getattribute__(self, attr) try: return nt.void.__getattribute__(self, attr) except AttributeError: pass fielddict = nt.void.__getattribute__(self, 'dtype').fields res = fielddict.get(attr, None) if res: obj = self.getfield(*res[:2]) # if it has fields return a recarray, # if it's a string ('SU') return a chararray # otherwise return the object try: dt = obj.dtype except AttributeError: return obj if dt.fields: return obj.view(obj.__class__) if dt.char in 'SU': return obj.view(chararray) return obj else: raise AttributeError("'record' object has no " "attribute '%s'" % attr) def __setattr__(self, attr, val): if attr in ['setfield', 'getfield', 'dtype']: raise AttributeError("Cannot set '%s' attribute" % attr) fielddict = nt.void.__getattribute__(self, 'dtype').fields res = fielddict.get(attr, None) if res: return self.setfield(val, *res[:2]) else: if getattr(self, attr, None): return nt.void.__setattr__(self, attr, val) else: raise AttributeError("'record' object has no " "attribute '%s'" % attr) def pprint(self): """Pretty-print all fields.""" # pretty-print all fields names = self.dtype.names maxlen = max([len(name) for name in names]) rows = [] fmt = '%% %ds: %%s' % maxlen for name in names: rows.append(fmt % (name, getattr(self, name))) return "\n".join(rows) # The recarray is almost identical to a standard array (which supports # named fields already) The biggest difference is that it can use # attribute-lookup to find the fields and it is constructed using # a record. # If byteorder is given it forces a particular byteorder on all # the fields (and any subfields) class recarray(ndarray): """ Construct an ndarray that allows field access using attributes. Arrays may have a data-types containing fields, analogous to columns in a spread sheet. An example is ``[(x, int), (y, float)]``, where each entry in the array is a pair of ``(int, float)``. Normally, these attributes are accessed using dictionary lookups such as ``arr['x']`` and ``arr['y']``. Record arrays allow the fields to be accessed as members of the array, using ``arr.x`` and ``arr.y``. Parameters ---------- shape : tuple Shape of output array. dtype : data-type, optional The desired data-type. By default, the data-type is determined from `formats`, `names`, `titles`, `aligned` and `byteorder`. formats : list of data-types, optional A list containing the data-types for the different columns, e.g. ``['i4', 'f8', 'i4']``. `formats` does *not* support the new convention of using types directly, i.e. ``(int, float, int)``. Note that `formats` must be a list, not a tuple. Given that `formats` is somewhat limited, we recommend specifying `dtype` instead. names : tuple of str, optional The name of each column, e.g. ``('x', 'y', 'z')``. buf : buffer, optional By default, a new array is created of the given shape and data-type. If `buf` is specified and is an object exposing the buffer interface, the array will use the memory from the existing buffer. In this case, the `offset` and `strides` keywords are available. Other Parameters ---------------- titles : tuple of str, optional Aliases for column names. For example, if `names` were ``('x', 'y', 'z')`` and `titles` is ``('x_coordinate', 'y_coordinate', 'z_coordinate')``, then ``arr['x']`` is equivalent to both ``arr.x`` and ``arr.x_coordinate``. byteorder : {'<', '>', '='}, optional Byte-order for all fields. aligned : bool, optional Align the fields in memory as the C-compiler would. strides : tuple of ints, optional Buffer (`buf`) is interpreted according to these strides (strides define how many bytes each array element, row, column, etc. occupy in memory). offset : int, optional Start reading buffer (`buf`) from this offset onwards. order : {'C', 'F'}, optional Row-major or column-major order. Returns ------- rec : recarray Empty array of the given shape and type. See Also -------- rec.fromrecords : Construct a record array from data. record : fundamental data-type for `recarray`. format_parser : determine a data-type from formats, names, titles. Notes ----- This constructor can be compared to ``empty``: it creates a new record array but does not fill it with data. To create a record array from data, use one of the following methods: 1. Create a standard ndarray and convert it to a record array, using ``arr.view(np.recarray)`` 2. Use the `buf` keyword. 3. Use `np.rec.fromrecords`. Examples -------- Create an array with two fields, ``x`` and ``y``: >>> x = np.array([(1.0, 2), (3.0, 4)], dtype=[('x', float), ('y', int)]) >>> x array([(1.0, 2), (3.0, 4)], dtype=[('x', '>> x['x'] array([ 1., 3.]) View the array as a record array: >>> x = x.view(np.recarray) >>> x.x array([ 1., 3.]) >>> x.y array([2, 4]) Create a new, empty record array: >>> np.recarray((2,), ... dtype=[('x', int), ('y', float), ('z', int)]) #doctest: +SKIP rec.array([(-1073741821, 1.2249118382103472e-301, 24547520), (3471280, 1.2134086255804012e-316, 0)], dtype=[('x', '>> x1=np.array([1,2,3,4]) >>> x2=np.array(['a','dd','xyz','12']) >>> x3=np.array([1.1,2,3,4]) >>> r = np.core.records.fromarrays([x1,x2,x3],names='a,b,c') >>> print r[1] (2, 'dd', 2.0) >>> x1[1]=34 >>> r.a array([1, 2, 3, 4]) """ arrayList = [sb.asarray(x) for x in arrayList] if shape is None or shape == 0: shape = arrayList[0].shape if isinstance(shape, int): shape = (shape,) if formats is None and dtype is None: # go through each object in the list to see if it is an ndarray # and determine the formats. formats = '' for obj in arrayList: if not isinstance(obj, ndarray): raise ValueError("item in the array list must be an ndarray.") formats += _typestr[obj.dtype.type] if issubclass(obj.dtype.type, nt.flexible): formats += repr(obj.itemsize) formats += ',' formats = formats[:-1] if dtype is not None: descr = sb.dtype(dtype) _names = descr.names else: parsed = format_parser(formats, names, titles, aligned, byteorder) _names = parsed._names descr = parsed._descr # Determine shape from data-type. if len(descr) != len(arrayList): raise ValueError("mismatch between the number of fields " "and the number of arrays") d0 = descr[0].shape nn = len(d0) if nn > 0: shape = shape[:-nn] for k, obj in enumerate(arrayList): nn = len(descr[k].shape) testshape = obj.shape[:len(obj.shape) - nn] if testshape != shape: raise ValueError("array-shape mismatch in array %d" % k) _array = recarray(shape, descr) # populate the record array (makes a copy) for i in range(len(arrayList)): _array[_names[i]] = arrayList[i] return _array # shape must be 1-d if you use list of lists... def fromrecords(recList, dtype=None, shape=None, formats=None, names=None, titles=None, aligned=False, byteorder=None): """ create a recarray from a list of records in text form The data in the same field can be heterogeneous, they will be promoted to the highest data type. This method is intended for creating smaller record arrays. If used to create large array without formats defined r=fromrecords([(2,3.,'abc')]*100000) it can be slow. If formats is None, then this will auto-detect formats. Use list of tuples rather than list of lists for faster processing. >>> r=np.core.records.fromrecords([(456,'dbe',1.2),(2,'de',1.3)], ... names='col1,col2,col3') >>> print r[0] (456, 'dbe', 1.2) >>> r.col1 array([456, 2]) >>> r.col2 chararray(['dbe', 'de'], dtype='|S3') >>> import pickle >>> print pickle.loads(pickle.dumps(r)) [(456, 'dbe', 1.2) (2, 'de', 1.3)] """ nfields = len(recList[0]) if formats is None and dtype is None: # slower obj = sb.array(recList, dtype=object) arrlist = [sb.array(obj[..., i].tolist()) for i in range(nfields)] return fromarrays(arrlist, formats=formats, shape=shape, names=names, titles=titles, aligned=aligned, byteorder=byteorder) if dtype is not None: descr = sb.dtype((record, dtype)) else: descr = format_parser(formats, names, titles, aligned, byteorder)._descr try: retval = sb.array(recList, dtype=descr) except TypeError: # list of lists instead of list of tuples if (shape is None or shape == 0): shape = len(recList) if isinstance(shape, (int, long)): shape = (shape,) if len(shape) > 1: raise ValueError("Can only deal with 1-d array.") _array = recarray(shape, descr) for k in range(_array.size): _array[k] = tuple(recList[k]) return _array else: if shape is not None and retval.shape != shape: retval.shape = shape res = retval.view(recarray) return res def fromstring(datastring, dtype=None, shape=None, offset=0, formats=None, names=None, titles=None, aligned=False, byteorder=None): """ create a (read-only) record array from binary data contained in a string""" if dtype is None and formats is None: raise ValueError("Must have dtype= or formats=") if dtype is not None: descr = sb.dtype(dtype) else: descr = format_parser(formats, names, titles, aligned, byteorder)._descr itemsize = descr.itemsize if (shape is None or shape == 0 or shape == -1): shape = (len(datastring) - offset) / itemsize _array = recarray(shape, descr, buf=datastring, offset=offset) return _array def get_remaining_size(fd): try: fn = fd.fileno() except AttributeError: return os.path.getsize(fd.name) - fd.tell() st = os.fstat(fn) size = st.st_size - fd.tell() return size def fromfile(fd, dtype=None, shape=None, offset=0, formats=None, names=None, titles=None, aligned=False, byteorder=None): """Create an array from binary file data If file is a string then that file is opened, else it is assumed to be a file object. >>> from tempfile import TemporaryFile >>> a = np.empty(10,dtype='f8,i4,a5') >>> a[5] = (0.5,10,'abcde') >>> >>> fd=TemporaryFile() >>> a = a.newbyteorder('<') >>> a.tofile(fd) >>> >>> fd.seek(0) >>> r=np.core.records.fromfile(fd, formats='f8,i4,a5', shape=10, ... byteorder='<') >>> print r[5] (0.5, 10, 'abcde') >>> r.shape (10,) """ if (shape is None or shape == 0): shape = (-1,) elif isinstance(shape, (int, long)): shape = (shape,) name = 0 if isinstance(fd, str): name = 1 fd = open(fd, 'rb') if (offset > 0): fd.seek(offset, 1) size = get_remaining_size(fd) if dtype is not None: descr = sb.dtype(dtype) else: descr = format_parser(formats, names, titles, aligned, byteorder)._descr itemsize = descr.itemsize shapeprod = sb.array(shape).prod() shapesize = shapeprod * itemsize if shapesize < 0: shape = list(shape) shape[ shape.index(-1) ] = size / -shapesize shape = tuple(shape) shapeprod = sb.array(shape).prod() nbytes = shapeprod * itemsize if nbytes > size: raise ValueError( "Not enough bytes left in file for specified shape and type") # create the array _array = recarray(shape, descr) nbytesread = fd.readinto(_array.data) if nbytesread != nbytes: raise IOError("Didn't read as many bytes as expected") if name: fd.close() return _array def array(obj, dtype=None, shape=None, offset=0, strides=None, formats=None, names=None, titles=None, aligned=False, byteorder=None, copy=True): """Construct a record array from a wide-variety of objects. """ if (isinstance(obj, (type(None), str)) or isfileobj(obj)) \ and (formats is None) \ and (dtype is None): raise ValueError("Must define formats (or dtype) if object is "\ "None, string, or an open file") kwds = {} if dtype is not None: dtype = sb.dtype(dtype) elif formats is not None: dtype = format_parser(formats, names, titles, aligned, byteorder)._descr else: kwds = {'formats': formats, 'names' : names, 'titles' : titles, 'aligned' : aligned, 'byteorder' : byteorder } if obj is None: if shape is None: raise ValueError("Must define a shape if obj is None") return recarray(shape, dtype, buf=obj, offset=offset, strides=strides) elif isinstance(obj, bytes): return fromstring(obj, dtype, shape=shape, offset=offset, **kwds) elif isinstance(obj, (list, tuple)): if isinstance(obj[0], (tuple, list)): return fromrecords(obj, dtype=dtype, shape=shape, **kwds) else: return fromarrays(obj, dtype=dtype, shape=shape, **kwds) elif isinstance(obj, recarray): if dtype is not None and (obj.dtype != dtype): new = obj.view(dtype) else: new = obj if copy: new = new.copy() return new elif isfileobj(obj): return fromfile(obj, dtype=dtype, shape=shape, offset=offset) elif isinstance(obj, ndarray): if dtype is not None and (obj.dtype != dtype): new = obj.view(dtype) else: new = obj if copy: new = new.copy() res = new.view(recarray) if issubclass(res.dtype.type, nt.void): res.dtype = sb.dtype((record, res.dtype)) return res else: interface = getattr(obj, "__array_interface__", None) if interface is None or not isinstance(interface, dict): raise ValueError("Unknown input type") obj = sb.array(obj) if dtype is not None and (obj.dtype != dtype): obj = obj.view(dtype) res = obj.view(recarray) if issubclass(res.dtype.type, nt.void): res.dtype = sb.dtype((record, res.dtype)) return res numpy-1.8.2/numpy/core/__init__.py0000664000175100017510000000360512370216243020241 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function from .info import __doc__ from numpy.version import version as __version__ from . import multiarray from . import umath from . import _internal # for freeze programs from . import numerictypes as nt multiarray.set_typeDict(nt.sctypeDict) from . import numeric from .numeric import * from . import fromnumeric from .fromnumeric import * from . import defchararray as char from . import records as rec from .records import * from .memmap import * from .defchararray import chararray from . import scalarmath from . import function_base from .function_base import * from . import machar from .machar import * from . import getlimits from .getlimits import * from . import shape_base from .shape_base import * del nt from .fromnumeric import amax as max, amin as min, \ round_ as round from .numeric import absolute as abs __all__ = ['char', 'rec', 'memmap'] __all__ += numeric.__all__ __all__ += fromnumeric.__all__ __all__ += rec.__all__ __all__ += ['chararray'] __all__ += function_base.__all__ __all__ += machar.__all__ __all__ += getlimits.__all__ __all__ += shape_base.__all__ from numpy.testing import Tester test = Tester().test bench = Tester().bench # Make it possible so that ufuncs can be pickled # Here are the loading and unloading functions # The name numpy.core._ufunc_reconstruct must be # available for unpickling to work. def _ufunc_reconstruct(module, name): mod = __import__(module) return getattr(mod, name) def _ufunc_reduce(func): from pickle import whichmodule name = func.__name__ return _ufunc_reconstruct, (whichmodule(func, name), name) import sys if sys.version_info[0] >= 3: import copyreg else: import copy_reg as copyreg copyreg.pickle(ufunc, _ufunc_reduce, _ufunc_reconstruct) # Unclutter namespace (must keep _ufunc_reconstruct for unpickling) del copyreg del sys del _ufunc_reduce numpy-1.8.2/numpy/core/numeric.py0000664000175100017510000023324012370216243020144 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function import sys import warnings import collections from . import multiarray from . import umath from .umath import * from . import numerictypes from .numerictypes import * if sys.version_info[0] >= 3: import pickle basestring = str else: import cPickle as pickle loads = pickle.loads __all__ = ['newaxis', 'ndarray', 'flatiter', 'nditer', 'nested_iters', 'ufunc', 'arange', 'array', 'zeros', 'count_nonzero', 'empty', 'broadcast', 'dtype', 'fromstring', 'fromfile', 'frombuffer', 'int_asbuffer', 'where', 'argwhere', 'copyto', 'concatenate', 'fastCopyAndTranspose', 'lexsort', 'set_numeric_ops', 'can_cast', 'promote_types', 'min_scalar_type', 'result_type', 'asarray', 'asanyarray', 'ascontiguousarray', 'asfortranarray', 'isfortran', 'empty_like', 'zeros_like', 'ones_like', 'correlate', 'convolve', 'inner', 'dot', 'einsum', 'outer', 'vdot', 'alterdot', 'restoredot', 'roll', 'rollaxis', 'cross', 'tensordot', 'array2string', 'get_printoptions', 'set_printoptions', 'array_repr', 'array_str', 'set_string_function', 'little_endian', 'require', 'fromiter', 'array_equal', 'array_equiv', 'indices', 'fromfunction', 'isclose', 'load', 'loads', 'isscalar', 'binary_repr', 'base_repr', 'ones', 'identity', 'allclose', 'compare_chararrays', 'putmask', 'seterr', 'geterr', 'setbufsize', 'getbufsize', 'seterrcall', 'geterrcall', 'errstate', 'flatnonzero', 'Inf', 'inf', 'infty', 'Infinity', 'nan', 'NaN', 'False_', 'True_', 'bitwise_not', 'CLIP', 'RAISE', 'WRAP', 'MAXDIMS', 'BUFSIZE', 'ALLOW_THREADS', 'ComplexWarning', 'may_share_memory', 'full', 'full_like'] if sys.version_info[0] < 3: __all__.extend(['getbuffer', 'newbuffer']) class ComplexWarning(RuntimeWarning): """ The warning raised when casting a complex dtype to a real dtype. As implemented, casting a complex number to a real discards its imaginary part, but this behavior may not be what the user actually wants. """ pass bitwise_not = invert CLIP = multiarray.CLIP WRAP = multiarray.WRAP RAISE = multiarray.RAISE MAXDIMS = multiarray.MAXDIMS ALLOW_THREADS = multiarray.ALLOW_THREADS BUFSIZE = multiarray.BUFSIZE ndarray = multiarray.ndarray flatiter = multiarray.flatiter nditer = multiarray.nditer nested_iters = multiarray.nested_iters broadcast = multiarray.broadcast dtype = multiarray.dtype copyto = multiarray.copyto ufunc = type(sin) def zeros_like(a, dtype=None, order='K', subok=True): """ Return an array of zeros with the same shape and type as a given array. Parameters ---------- a : array_like The shape and data-type of `a` define these same attributes of the returned array. dtype : data-type, optional .. versionadded:: 1.6.0 Overrides the data type of the result. order : {'C', 'F', 'A', or 'K'}, optional .. versionadded:: 1.6.0 Overrides the memory layout of the result. 'C' means C-order, 'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous, 'C' otherwise. 'K' means match the layout of `a` as closely as possible. subok : bool, optional. If True, then the newly created array will use the sub-class type of 'a', otherwise it will be a base-class array. Defaults to True. Returns ------- out : ndarray Array of zeros with the same shape and type as `a`. See Also -------- ones_like : Return an array of ones with shape and type of input. empty_like : Return an empty array with shape and type of input. zeros : Return a new array setting values to zero. ones : Return a new array setting values to one. empty : Return a new uninitialized array. Examples -------- >>> x = np.arange(6) >>> x = x.reshape((2, 3)) >>> x array([[0, 1, 2], [3, 4, 5]]) >>> np.zeros_like(x) array([[0, 0, 0], [0, 0, 0]]) >>> y = np.arange(3, dtype=np.float) >>> y array([ 0., 1., 2.]) >>> np.zeros_like(y) array([ 0., 0., 0.]) """ res = empty_like(a, dtype=dtype, order=order, subok=subok) multiarray.copyto(res, 0, casting='unsafe') return res def ones(shape, dtype=None, order='C'): """ Return a new array of given shape and type, filled with ones. Parameters ---------- shape : int or sequence of ints Shape of the new array, e.g., ``(2, 3)`` or ``2``. dtype : data-type, optional The desired data-type for the array, e.g., `numpy.int8`. Default is `numpy.float64`. order : {'C', 'F'}, optional Whether to store multidimensional data in C- or Fortran-contiguous (row- or column-wise) order in memory. Returns ------- out : ndarray Array of ones with the given shape, dtype, and order. See Also -------- zeros, ones_like Examples -------- >>> np.ones(5) array([ 1., 1., 1., 1., 1.]) >>> np.ones((5,), dtype=np.int) array([1, 1, 1, 1, 1]) >>> np.ones((2, 1)) array([[ 1.], [ 1.]]) >>> s = (2,2) >>> np.ones(s) array([[ 1., 1.], [ 1., 1.]]) """ a = empty(shape, dtype, order) multiarray.copyto(a, 1, casting='unsafe') return a def ones_like(a, dtype=None, order='K', subok=True): """ Return an array of ones with the same shape and type as a given array. Parameters ---------- a : array_like The shape and data-type of `a` define these same attributes of the returned array. dtype : data-type, optional .. versionadded:: 1.6.0 Overrides the data type of the result. order : {'C', 'F', 'A', or 'K'}, optional .. versionadded:: 1.6.0 Overrides the memory layout of the result. 'C' means C-order, 'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous, 'C' otherwise. 'K' means match the layout of `a` as closely as possible. subok : bool, optional. If True, then the newly created array will use the sub-class type of 'a', otherwise it will be a base-class array. Defaults to True. Returns ------- out : ndarray Array of ones with the same shape and type as `a`. See Also -------- zeros_like : Return an array of zeros with shape and type of input. empty_like : Return an empty array with shape and type of input. zeros : Return a new array setting values to zero. ones : Return a new array setting values to one. empty : Return a new uninitialized array. Examples -------- >>> x = np.arange(6) >>> x = x.reshape((2, 3)) >>> x array([[0, 1, 2], [3, 4, 5]]) >>> np.ones_like(x) array([[1, 1, 1], [1, 1, 1]]) >>> y = np.arange(3, dtype=np.float) >>> y array([ 0., 1., 2.]) >>> np.ones_like(y) array([ 1., 1., 1.]) """ res = empty_like(a, dtype=dtype, order=order, subok=subok) multiarray.copyto(res, 1, casting='unsafe') return res def full(shape, fill_value, dtype=None, order='C'): """ Return a new array of given shape and type, filled with `fill_value`. Parameters ---------- shape : int or sequence of ints Shape of the new array, e.g., ``(2, 3)`` or ``2``. fill_value : scalar Fill value. dtype : data-type, optional The desired data-type for the array, e.g., `numpy.int8`. Default is is chosen as `np.array(fill_value).dtype`. order : {'C', 'F'}, optional Whether to store multidimensional data in C- or Fortran-contiguous (row- or column-wise) order in memory. Returns ------- out : ndarray Array of `fill_value` with the given shape, dtype, and order. See Also -------- zeros_like : Return an array of zeros with shape and type of input. ones_like : Return an array of ones with shape and type of input. empty_like : Return an empty array with shape and type of input. full_like : Fill an array with shape and type of input. zeros : Return a new array setting values to zero. ones : Return a new array setting values to one. empty : Return a new uninitialized array. Examples -------- >>> np.full((2, 2), np.inf) array([[ inf, inf], [ inf, inf]]) >>> np.full((2, 2), 10, dtype=np.int) array([[10, 10], [10, 10]]) """ a = empty(shape, dtype, order) multiarray.copyto(a, fill_value, casting='unsafe') return a def full_like(a, fill_value, dtype=None, order='K', subok=True): """ Return a full array with the same shape and type as a given array. Parameters ---------- a : array_like The shape and data-type of `a` define these same attributes of the returned array. fill_value : scalar Fill value. dtype : data-type, optional Overrides the data type of the result. order : {'C', 'F', 'A', or 'K'}, optional Overrides the memory layout of the result. 'C' means C-order, 'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous, 'C' otherwise. 'K' means match the layout of `a` as closely as possible. subok : bool, optional. If True, then the newly created array will use the sub-class type of 'a', otherwise it will be a base-class array. Defaults to True. Returns ------- out : ndarray Array of `fill_value` with the same shape and type as `a`. See Also -------- zeros_like : Return an array of zeros with shape and type of input. ones_like : Return an array of ones with shape and type of input. empty_like : Return an empty array with shape and type of input. zeros : Return a new array setting values to zero. ones : Return a new array setting values to one. empty : Return a new uninitialized array. full : Fill a new array. Examples -------- >>> x = np.arange(6, dtype=np.int) >>> np.full_like(x, 1) array([1, 1, 1, 1, 1, 1]) >>> np.full_like(x, 0.1) array([0, 0, 0, 0, 0, 0]) >>> np.full_like(x, 0.1, dtype=np.double) array([ 0.1, 0.1, 0.1, 0.1, 0.1, 0.1]) >>> np.full_like(x, np.nan, dtype=np.double) array([ nan, nan, nan, nan, nan, nan]) >>> y = np.arange(6, dtype=np.double) >>> np.full_like(y, 0.1) array([ 0.1, 0.1, 0.1, 0.1, 0.1, 0.1]) """ res = empty_like(a, dtype=dtype, order=order, subok=subok) multiarray.copyto(res, fill_value, casting='unsafe') return res def extend_all(module): adict = {} for a in __all__: adict[a] = 1 try: mall = getattr(module, '__all__') except AttributeError: mall = [k for k in module.__dict__.keys() if not k.startswith('_')] for a in mall: if a not in adict: __all__.append(a) extend_all(umath) extend_all(numerictypes) newaxis = None arange = multiarray.arange array = multiarray.array zeros = multiarray.zeros count_nonzero = multiarray.count_nonzero empty = multiarray.empty empty_like = multiarray.empty_like fromstring = multiarray.fromstring fromiter = multiarray.fromiter fromfile = multiarray.fromfile frombuffer = multiarray.frombuffer may_share_memory = multiarray.may_share_memory if sys.version_info[0] < 3: newbuffer = multiarray.newbuffer getbuffer = multiarray.getbuffer int_asbuffer = multiarray.int_asbuffer where = multiarray.where concatenate = multiarray.concatenate fastCopyAndTranspose = multiarray._fastCopyAndTranspose set_numeric_ops = multiarray.set_numeric_ops can_cast = multiarray.can_cast promote_types = multiarray.promote_types min_scalar_type = multiarray.min_scalar_type result_type = multiarray.result_type lexsort = multiarray.lexsort compare_chararrays = multiarray.compare_chararrays putmask = multiarray.putmask einsum = multiarray.einsum def asarray(a, dtype=None, order=None): """ Convert the input to an array. Parameters ---------- a : array_like Input data, in any form that can be converted to an array. This includes lists, lists of tuples, tuples, tuples of tuples, tuples of lists and ndarrays. dtype : data-type, optional By default, the data-type is inferred from the input data. order : {'C', 'F'}, optional Whether to use row-major ('C') or column-major ('F' for FORTRAN) memory representation. Defaults to 'C'. Returns ------- out : ndarray Array interpretation of `a`. No copy is performed if the input is already an ndarray. If `a` is a subclass of ndarray, a base class ndarray is returned. See Also -------- asanyarray : Similar function which passes through subclasses. ascontiguousarray : Convert input to a contiguous array. asfarray : Convert input to a floating point ndarray. asfortranarray : Convert input to an ndarray with column-major memory order. asarray_chkfinite : Similar function which checks input for NaNs and Infs. fromiter : Create an array from an iterator. fromfunction : Construct an array by executing a function on grid positions. Examples -------- Convert a list into an array: >>> a = [1, 2] >>> np.asarray(a) array([1, 2]) Existing arrays are not copied: >>> a = np.array([1, 2]) >>> np.asarray(a) is a True If `dtype` is set, array is copied only if dtype does not match: >>> a = np.array([1, 2], dtype=np.float32) >>> np.asarray(a, dtype=np.float32) is a True >>> np.asarray(a, dtype=np.float64) is a False Contrary to `asanyarray`, ndarray subclasses are not passed through: >>> issubclass(np.matrix, np.ndarray) True >>> a = np.matrix([[1, 2]]) >>> np.asarray(a) is a False >>> np.asanyarray(a) is a True """ return array(a, dtype, copy=False, order=order) def asanyarray(a, dtype=None, order=None): """ Convert the input to an ndarray, but pass ndarray subclasses through. Parameters ---------- a : array_like Input data, in any form that can be converted to an array. This includes scalars, lists, lists of tuples, tuples, tuples of tuples, tuples of lists, and ndarrays. dtype : data-type, optional By default, the data-type is inferred from the input data. order : {'C', 'F'}, optional Whether to use row-major ('C') or column-major ('F') memory representation. Defaults to 'C'. Returns ------- out : ndarray or an ndarray subclass Array interpretation of `a`. If `a` is an ndarray or a subclass of ndarray, it is returned as-is and no copy is performed. See Also -------- asarray : Similar function which always returns ndarrays. ascontiguousarray : Convert input to a contiguous array. asfarray : Convert input to a floating point ndarray. asfortranarray : Convert input to an ndarray with column-major memory order. asarray_chkfinite : Similar function which checks input for NaNs and Infs. fromiter : Create an array from an iterator. fromfunction : Construct an array by executing a function on grid positions. Examples -------- Convert a list into an array: >>> a = [1, 2] >>> np.asanyarray(a) array([1, 2]) Instances of `ndarray` subclasses are passed through as-is: >>> a = np.matrix([1, 2]) >>> np.asanyarray(a) is a True """ return array(a, dtype, copy=False, order=order, subok=True) def ascontiguousarray(a, dtype=None): """ Return a contiguous array in memory (C order). Parameters ---------- a : array_like Input array. dtype : str or dtype object, optional Data-type of returned array. Returns ------- out : ndarray Contiguous array of same shape and content as `a`, with type `dtype` if specified. See Also -------- asfortranarray : Convert input to an ndarray with column-major memory order. require : Return an ndarray that satisfies requirements. ndarray.flags : Information about the memory layout of the array. Examples -------- >>> x = np.arange(6).reshape(2,3) >>> np.ascontiguousarray(x, dtype=np.float32) array([[ 0., 1., 2.], [ 3., 4., 5.]], dtype=float32) >>> x.flags['C_CONTIGUOUS'] True """ return array(a, dtype, copy=False, order='C', ndmin=1) def asfortranarray(a, dtype=None): """ Return an array laid out in Fortran order in memory. Parameters ---------- a : array_like Input array. dtype : str or dtype object, optional By default, the data-type is inferred from the input data. Returns ------- out : ndarray The input `a` in Fortran, or column-major, order. See Also -------- ascontiguousarray : Convert input to a contiguous (C order) array. asanyarray : Convert input to an ndarray with either row or column-major memory order. require : Return an ndarray that satisfies requirements. ndarray.flags : Information about the memory layout of the array. Examples -------- >>> x = np.arange(6).reshape(2,3) >>> y = np.asfortranarray(x) >>> x.flags['F_CONTIGUOUS'] False >>> y.flags['F_CONTIGUOUS'] True """ return array(a, dtype, copy=False, order='F', ndmin=1) def require(a, dtype=None, requirements=None): """ Return an ndarray of the provided type that satisfies requirements. This function is useful to be sure that an array with the correct flags is returned for passing to compiled code (perhaps through ctypes). Parameters ---------- a : array_like The object to be converted to a type-and-requirement-satisfying array. dtype : data-type The required data-type, the default data-type is float64). requirements : str or list of str The requirements list can be any of the following * 'F_CONTIGUOUS' ('F') - ensure a Fortran-contiguous array * 'C_CONTIGUOUS' ('C') - ensure a C-contiguous array * 'ALIGNED' ('A') - ensure a data-type aligned array * 'WRITEABLE' ('W') - ensure a writable array * 'OWNDATA' ('O') - ensure an array that owns its own data See Also -------- asarray : Convert input to an ndarray. asanyarray : Convert to an ndarray, but pass through ndarray subclasses. ascontiguousarray : Convert input to a contiguous array. asfortranarray : Convert input to an ndarray with column-major memory order. ndarray.flags : Information about the memory layout of the array. Notes ----- The returned array will be guaranteed to have the listed requirements by making a copy if needed. Examples -------- >>> x = np.arange(6).reshape(2,3) >>> x.flags C_CONTIGUOUS : True F_CONTIGUOUS : False OWNDATA : False WRITEABLE : True ALIGNED : True UPDATEIFCOPY : False >>> y = np.require(x, dtype=np.float32, requirements=['A', 'O', 'W', 'F']) >>> y.flags C_CONTIGUOUS : False F_CONTIGUOUS : True OWNDATA : True WRITEABLE : True ALIGNED : True UPDATEIFCOPY : False """ if requirements is None: requirements = [] else: requirements = [x.upper() for x in requirements] if not requirements: return asanyarray(a, dtype=dtype) if 'ENSUREARRAY' in requirements or 'E' in requirements: subok = False else: subok = True arr = array(a, dtype=dtype, copy=False, subok=subok) copychar = 'A' if 'FORTRAN' in requirements or \ 'F_CONTIGUOUS' in requirements or \ 'F' in requirements: copychar = 'F' elif 'CONTIGUOUS' in requirements or \ 'C_CONTIGUOUS' in requirements or \ 'C' in requirements: copychar = 'C' for prop in requirements: if not arr.flags[prop]: arr = arr.copy(copychar) break return arr def isfortran(a): """ Returns True if array is arranged in Fortran-order in memory and not C-order. Parameters ---------- a : ndarray Input array. Examples -------- np.array allows to specify whether the array is written in C-contiguous order (last index varies the fastest), or FORTRAN-contiguous order in memory (first index varies the fastest). >>> a = np.array([[1, 2, 3], [4, 5, 6]], order='C') >>> a array([[1, 2, 3], [4, 5, 6]]) >>> np.isfortran(a) False >>> b = np.array([[1, 2, 3], [4, 5, 6]], order='FORTRAN') >>> b array([[1, 2, 3], [4, 5, 6]]) >>> np.isfortran(b) True The transpose of a C-ordered array is a FORTRAN-ordered array. >>> a = np.array([[1, 2, 3], [4, 5, 6]], order='C') >>> a array([[1, 2, 3], [4, 5, 6]]) >>> np.isfortran(a) False >>> b = a.T >>> b array([[1, 4], [2, 5], [3, 6]]) >>> np.isfortran(b) True C-ordered arrays evaluate as False even if they are also FORTRAN-ordered. >>> np.isfortran(np.array([1, 2], order='FORTRAN')) False """ return a.flags.fnc def argwhere(a): """ Find the indices of array elements that are non-zero, grouped by element. Parameters ---------- a : array_like Input data. Returns ------- index_array : ndarray Indices of elements that are non-zero. Indices are grouped by element. See Also -------- where, nonzero Notes ----- ``np.argwhere(a)`` is the same as ``np.transpose(np.nonzero(a))``. The output of ``argwhere`` is not suitable for indexing arrays. For this purpose use ``where(a)`` instead. Examples -------- >>> x = np.arange(6).reshape(2,3) >>> x array([[0, 1, 2], [3, 4, 5]]) >>> np.argwhere(x>1) array([[0, 2], [1, 0], [1, 1], [1, 2]]) """ return transpose(asanyarray(a).nonzero()) def flatnonzero(a): """ Return indices that are non-zero in the flattened version of a. This is equivalent to a.ravel().nonzero()[0]. Parameters ---------- a : ndarray Input array. Returns ------- res : ndarray Output array, containing the indices of the elements of `a.ravel()` that are non-zero. See Also -------- nonzero : Return the indices of the non-zero elements of the input array. ravel : Return a 1-D array containing the elements of the input array. Examples -------- >>> x = np.arange(-2, 3) >>> x array([-2, -1, 0, 1, 2]) >>> np.flatnonzero(x) array([0, 1, 3, 4]) Use the indices of the non-zero elements as an index array to extract these elements: >>> x.ravel()[np.flatnonzero(x)] array([-2, -1, 1, 2]) """ return a.ravel().nonzero()[0] _mode_from_name_dict = {'v': 0, 's' : 1, 'f' : 2} def _mode_from_name(mode): if isinstance(mode, basestring): return _mode_from_name_dict[mode.lower()[0]] return mode def correlate(a, v, mode='valid', old_behavior=False): """ Cross-correlation of two 1-dimensional sequences. This function computes the correlation as generally defined in signal processing texts:: z[k] = sum_n a[n] * conj(v[n+k]) with a and v sequences being zero-padded where necessary and conj being the conjugate. Parameters ---------- a, v : array_like Input sequences. mode : {'valid', 'same', 'full'}, optional Refer to the `convolve` docstring. Note that the default is `valid`, unlike `convolve`, which uses `full`. old_behavior : bool If True, uses the old behavior from Numeric, (correlate(a,v) == correlate(v,a), and the conjugate is not taken for complex arrays). If False, uses the conventional signal processing definition. See Also -------- convolve : Discrete, linear convolution of two one-dimensional sequences. Examples -------- >>> np.correlate([1, 2, 3], [0, 1, 0.5]) array([ 3.5]) >>> np.correlate([1, 2, 3], [0, 1, 0.5], "same") array([ 2. , 3.5, 3. ]) >>> np.correlate([1, 2, 3], [0, 1, 0.5], "full") array([ 0.5, 2. , 3.5, 3. , 0. ]) """ mode = _mode_from_name(mode) # the old behavior should be made available under a different name, see thread # http://thread.gmane.org/gmane.comp.python.numeric.general/12609/focus=12630 if old_behavior: warnings.warn(""" The old behavior of correlate was deprecated for 1.4.0, and will be completely removed for NumPy 2.0. The new behavior fits the conventional definition of correlation: inputs are never swapped, and the second argument is conjugated for complex arrays.""", DeprecationWarning) return multiarray.correlate(a, v, mode) else: return multiarray.correlate2(a, v, mode) def convolve(a,v,mode='full'): """ Returns the discrete, linear convolution of two one-dimensional sequences. The convolution operator is often seen in signal processing, where it models the effect of a linear time-invariant system on a signal [1]_. In probability theory, the sum of two independent random variables is distributed according to the convolution of their individual distributions. Parameters ---------- a : (N,) array_like First one-dimensional input array. v : (M,) array_like Second one-dimensional input array. mode : {'full', 'valid', 'same'}, optional 'full': By default, mode is 'full'. This returns the convolution at each point of overlap, with an output shape of (N+M-1,). At the end-points of the convolution, the signals do not overlap completely, and boundary effects may be seen. 'same': Mode `same` returns output of length ``max(M, N)``. Boundary effects are still visible. 'valid': Mode `valid` returns output of length ``max(M, N) - min(M, N) + 1``. The convolution product is only given for points where the signals overlap completely. Values outside the signal boundary have no effect. Returns ------- out : ndarray Discrete, linear convolution of `a` and `v`. See Also -------- scipy.signal.fftconvolve : Convolve two arrays using the Fast Fourier Transform. scipy.linalg.toeplitz : Used to construct the convolution operator. Notes ----- The discrete convolution operation is defined as .. math:: (f * g)[n] = \\sum_{m = -\\infty}^{\\infty} f[m] g[n - m] It can be shown that a convolution :math:`x(t) * y(t)` in time/space is equivalent to the multiplication :math:`X(f) Y(f)` in the Fourier domain, after appropriate padding (padding is necessary to prevent circular convolution). Since multiplication is more efficient (faster) than convolution, the function `scipy.signal.fftconvolve` exploits the FFT to calculate the convolution of large data-sets. References ---------- .. [1] Wikipedia, "Convolution", http://en.wikipedia.org/wiki/Convolution. Examples -------- Note how the convolution operator flips the second array before "sliding" the two across one another: >>> np.convolve([1, 2, 3], [0, 1, 0.5]) array([ 0. , 1. , 2.5, 4. , 1.5]) Only return the middle values of the convolution. Contains boundary effects, where zeros are taken into account: >>> np.convolve([1,2,3],[0,1,0.5], 'same') array([ 1. , 2.5, 4. ]) The two arrays are of the same length, so there is only one position where they completely overlap: >>> np.convolve([1,2,3],[0,1,0.5], 'valid') array([ 2.5]) """ a, v = array(a, ndmin=1), array(v, ndmin=1) if (len(v) > len(a)): a, v = v, a if len(a) == 0 : raise ValueError('a cannot be empty') if len(v) == 0 : raise ValueError('v cannot be empty') mode = _mode_from_name(mode) return multiarray.correlate(a, v[::-1], mode) def outer(a, b): """ Compute the outer product of two vectors. Given two vectors, ``a = [a0, a1, ..., aM]`` and ``b = [b0, b1, ..., bN]``, the outer product [1]_ is:: [[a0*b0 a0*b1 ... a0*bN ] [a1*b0 . [ ... . [aM*b0 aM*bN ]] Parameters ---------- a : (M,) array_like First input vector. Input is flattened if not already 1-dimensional. b : (N,) array_like Second input vector. Input is flattened if not already 1-dimensional. Returns ------- out : (M, N) ndarray ``out[i, j] = a[i] * b[j]`` See also -------- inner, einsum References ---------- .. [1] : G. H. Golub and C. F. van Loan, *Matrix Computations*, 3rd ed., Baltimore, MD, Johns Hopkins University Press, 1996, pg. 8. Examples -------- Make a (*very* coarse) grid for computing a Mandelbrot set: >>> rl = np.outer(np.ones((5,)), np.linspace(-2, 2, 5)) >>> rl array([[-2., -1., 0., 1., 2.], [-2., -1., 0., 1., 2.], [-2., -1., 0., 1., 2.], [-2., -1., 0., 1., 2.], [-2., -1., 0., 1., 2.]]) >>> im = np.outer(1j*np.linspace(2, -2, 5), np.ones((5,))) >>> im array([[ 0.+2.j, 0.+2.j, 0.+2.j, 0.+2.j, 0.+2.j], [ 0.+1.j, 0.+1.j, 0.+1.j, 0.+1.j, 0.+1.j], [ 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j], [ 0.-1.j, 0.-1.j, 0.-1.j, 0.-1.j, 0.-1.j], [ 0.-2.j, 0.-2.j, 0.-2.j, 0.-2.j, 0.-2.j]]) >>> grid = rl + im >>> grid array([[-2.+2.j, -1.+2.j, 0.+2.j, 1.+2.j, 2.+2.j], [-2.+1.j, -1.+1.j, 0.+1.j, 1.+1.j, 2.+1.j], [-2.+0.j, -1.+0.j, 0.+0.j, 1.+0.j, 2.+0.j], [-2.-1.j, -1.-1.j, 0.-1.j, 1.-1.j, 2.-1.j], [-2.-2.j, -1.-2.j, 0.-2.j, 1.-2.j, 2.-2.j]]) An example using a "vector" of letters: >>> x = np.array(['a', 'b', 'c'], dtype=object) >>> np.outer(x, [1, 2, 3]) array([[a, aa, aaa], [b, bb, bbb], [c, cc, ccc]], dtype=object) """ a = asarray(a) b = asarray(b) return a.ravel()[:, newaxis]*b.ravel()[newaxis,:] # try to import blas optimized dot if available try: # importing this changes the dot function for basic 4 types # to blas-optimized versions. from ._dotblas import dot, vdot, inner, alterdot, restoredot except ImportError: # docstrings are in add_newdocs.py inner = multiarray.inner dot = multiarray.dot def vdot(a, b): return dot(asarray(a).ravel().conj(), asarray(b).ravel()) def alterdot(): pass def restoredot(): pass def tensordot(a, b, axes=2): """ Compute tensor dot product along specified axes for arrays >= 1-D. Given two tensors (arrays of dimension greater than or equal to one), `a` and `b`, and an array_like object containing two array_like objects, ``(a_axes, b_axes)``, sum the products of `a`'s and `b`'s elements (components) over the axes specified by ``a_axes`` and ``b_axes``. The third argument can be a single non-negative integer_like scalar, ``N``; if it is such, then the last ``N`` dimensions of `a` and the first ``N`` dimensions of `b` are summed over. Parameters ---------- a, b : array_like, len(shape) >= 1 Tensors to "dot". axes : variable type * integer_like scalar Number of axes to sum over (applies to both arrays); or * (2,) array_like, both elements array_like of the same length List of axes to be summed over, first sequence applying to `a`, second to `b`. See Also -------- dot, einsum Notes ----- When there is more than one axis to sum over - and they are not the last (first) axes of `a` (`b`) - the argument `axes` should consist of two sequences of the same length, with the first axis to sum over given first in both sequences, the second axis second, and so forth. Examples -------- A "traditional" example: >>> a = np.arange(60.).reshape(3,4,5) >>> b = np.arange(24.).reshape(4,3,2) >>> c = np.tensordot(a,b, axes=([1,0],[0,1])) >>> c.shape (5, 2) >>> c array([[ 4400., 4730.], [ 4532., 4874.], [ 4664., 5018.], [ 4796., 5162.], [ 4928., 5306.]]) >>> # A slower but equivalent way of computing the same... >>> d = np.zeros((5,2)) >>> for i in range(5): ... for j in range(2): ... for k in range(3): ... for n in range(4): ... d[i,j] += a[k,n,i] * b[n,k,j] >>> c == d array([[ True, True], [ True, True], [ True, True], [ True, True], [ True, True]], dtype=bool) An extended example taking advantage of the overloading of + and \\*: >>> a = np.array(range(1, 9)) >>> a.shape = (2, 2, 2) >>> A = np.array(('a', 'b', 'c', 'd'), dtype=object) >>> A.shape = (2, 2) >>> a; A array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]]) array([[a, b], [c, d]], dtype=object) >>> np.tensordot(a, A) # third argument default is 2 array([abbcccdddd, aaaaabbbbbbcccccccdddddddd], dtype=object) >>> np.tensordot(a, A, 1) array([[[acc, bdd], [aaacccc, bbbdddd]], [[aaaaacccccc, bbbbbdddddd], [aaaaaaacccccccc, bbbbbbbdddddddd]]], dtype=object) >>> np.tensordot(a, A, 0) # "Left for reader" (result too long to incl.) array([[[[[a, b], [c, d]], ... >>> np.tensordot(a, A, (0, 1)) array([[[abbbbb, cddddd], [aabbbbbb, ccdddddd]], [[aaabbbbbbb, cccddddddd], [aaaabbbbbbbb, ccccdddddddd]]], dtype=object) >>> np.tensordot(a, A, (2, 1)) array([[[abb, cdd], [aaabbbb, cccdddd]], [[aaaaabbbbbb, cccccdddddd], [aaaaaaabbbbbbbb, cccccccdddddddd]]], dtype=object) >>> np.tensordot(a, A, ((0, 1), (0, 1))) array([abbbcccccddddddd, aabbbbccccccdddddddd], dtype=object) >>> np.tensordot(a, A, ((2, 1), (1, 0))) array([acccbbdddd, aaaaacccccccbbbbbbdddddddd], dtype=object) """ try: iter(axes) except: axes_a = list(range(-axes, 0)) axes_b = list(range(0, axes)) else: axes_a, axes_b = axes try: na = len(axes_a) axes_a = list(axes_a) except TypeError: axes_a = [axes_a] na = 1 try: nb = len(axes_b) axes_b = list(axes_b) except TypeError: axes_b = [axes_b] nb = 1 a, b = asarray(a), asarray(b) as_ = a.shape nda = len(a.shape) bs = b.shape ndb = len(b.shape) equal = True if (na != nb): equal = False else: for k in range(na): if as_[axes_a[k]] != bs[axes_b[k]]: equal = False break if axes_a[k] < 0: axes_a[k] += nda if axes_b[k] < 0: axes_b[k] += ndb if not equal: raise ValueError("shape-mismatch for sum") # Move the axes to sum over to the end of "a" # and to the front of "b" notin = [k for k in range(nda) if k not in axes_a] newaxes_a = notin + axes_a N2 = 1 for axis in axes_a: N2 *= as_[axis] newshape_a = (-1, N2) olda = [as_[axis] for axis in notin] notin = [k for k in range(ndb) if k not in axes_b] newaxes_b = axes_b + notin N2 = 1 for axis in axes_b: N2 *= bs[axis] newshape_b = (N2, -1) oldb = [bs[axis] for axis in notin] at = a.transpose(newaxes_a).reshape(newshape_a) bt = b.transpose(newaxes_b).reshape(newshape_b) res = dot(at, bt) return res.reshape(olda + oldb) def roll(a, shift, axis=None): """ Roll array elements along a given axis. Elements that roll beyond the last position are re-introduced at the first. Parameters ---------- a : array_like Input array. shift : int The number of places by which elements are shifted. axis : int, optional The axis along which elements are shifted. By default, the array is flattened before shifting, after which the original shape is restored. Returns ------- res : ndarray Output array, with the same shape as `a`. See Also -------- rollaxis : Roll the specified axis backwards, until it lies in a given position. Examples -------- >>> x = np.arange(10) >>> np.roll(x, 2) array([8, 9, 0, 1, 2, 3, 4, 5, 6, 7]) >>> x2 = np.reshape(x, (2,5)) >>> x2 array([[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]) >>> np.roll(x2, 1) array([[9, 0, 1, 2, 3], [4, 5, 6, 7, 8]]) >>> np.roll(x2, 1, axis=0) array([[5, 6, 7, 8, 9], [0, 1, 2, 3, 4]]) >>> np.roll(x2, 1, axis=1) array([[4, 0, 1, 2, 3], [9, 5, 6, 7, 8]]) """ a = asanyarray(a) if axis is None: n = a.size reshape = True else: try: n = a.shape[axis] except IndexError: raise ValueError('axis must be >= 0 and < %d' % a.ndim) reshape = False if n == 0: return a shift %= n indexes = concatenate((arange(n - shift, n), arange(n - shift))) res = a.take(indexes, axis) if reshape: res = res.reshape(a.shape) return res def rollaxis(a, axis, start=0): """ Roll the specified axis backwards, until it lies in a given position. Parameters ---------- a : ndarray Input array. axis : int The axis to roll backwards. The positions of the other axes do not change relative to one another. start : int, optional The axis is rolled until it lies before this position. The default, 0, results in a "complete" roll. Returns ------- res : ndarray Output array. See Also -------- roll : Roll the elements of an array by a number of positions along a given axis. Examples -------- >>> a = np.ones((3,4,5,6)) >>> np.rollaxis(a, 3, 1).shape (3, 6, 4, 5) >>> np.rollaxis(a, 2).shape (5, 3, 4, 6) >>> np.rollaxis(a, 1, 4).shape (3, 5, 6, 4) """ n = a.ndim if axis < 0: axis += n if start < 0: start += n msg = 'rollaxis: %s (%d) must be >=0 and < %d' if not (0 <= axis < n): raise ValueError(msg % ('axis', axis, n)) if not (0 <= start < n+1): raise ValueError(msg % ('start', start, n+1)) if (axis < start): # it's been removed start -= 1 if axis==start: return a axes = list(range(0, n)) axes.remove(axis) axes.insert(start, axis) return a.transpose(axes) # fix hack in scipy which imports this function def _move_axis_to_0(a, axis): return rollaxis(a, axis, 0) def cross(a, b, axisa=-1, axisb=-1, axisc=-1, axis=None): """ Return the cross product of two (arrays of) vectors. The cross product of `a` and `b` in :math:`R^3` is a vector perpendicular to both `a` and `b`. If `a` and `b` are arrays of vectors, the vectors are defined by the last axis of `a` and `b` by default, and these axes can have dimensions 2 or 3. Where the dimension of either `a` or `b` is 2, the third component of the input vector is assumed to be zero and the cross product calculated accordingly. In cases where both input vectors have dimension 2, the z-component of the cross product is returned. Parameters ---------- a : array_like Components of the first vector(s). b : array_like Components of the second vector(s). axisa : int, optional Axis of `a` that defines the vector(s). By default, the last axis. axisb : int, optional Axis of `b` that defines the vector(s). By default, the last axis. axisc : int, optional Axis of `c` containing the cross product vector(s). By default, the last axis. axis : int, optional If defined, the axis of `a`, `b` and `c` that defines the vector(s) and cross product(s). Overrides `axisa`, `axisb` and `axisc`. Returns ------- c : ndarray Vector cross product(s). Raises ------ ValueError When the dimension of the vector(s) in `a` and/or `b` does not equal 2 or 3. See Also -------- inner : Inner product outer : Outer product. ix_ : Construct index arrays. Examples -------- Vector cross-product. >>> x = [1, 2, 3] >>> y = [4, 5, 6] >>> np.cross(x, y) array([-3, 6, -3]) One vector with dimension 2. >>> x = [1, 2] >>> y = [4, 5, 6] >>> np.cross(x, y) array([12, -6, -3]) Equivalently: >>> x = [1, 2, 0] >>> y = [4, 5, 6] >>> np.cross(x, y) array([12, -6, -3]) Both vectors with dimension 2. >>> x = [1,2] >>> y = [4,5] >>> np.cross(x, y) -3 Multiple vector cross-products. Note that the direction of the cross product vector is defined by the `right-hand rule`. >>> x = np.array([[1,2,3], [4,5,6]]) >>> y = np.array([[4,5,6], [1,2,3]]) >>> np.cross(x, y) array([[-3, 6, -3], [ 3, -6, 3]]) The orientation of `c` can be changed using the `axisc` keyword. >>> np.cross(x, y, axisc=0) array([[-3, 3], [ 6, -6], [-3, 3]]) Change the vector definition of `x` and `y` using `axisa` and `axisb`. >>> x = np.array([[1,2,3], [4,5,6], [7, 8, 9]]) >>> y = np.array([[7, 8, 9], [4,5,6], [1,2,3]]) >>> np.cross(x, y) array([[ -6, 12, -6], [ 0, 0, 0], [ 6, -12, 6]]) >>> np.cross(x, y, axisa=0, axisb=0) array([[-24, 48, -24], [-30, 60, -30], [-36, 72, -36]]) """ 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]): raise ValueError(msg) if a.shape[0] == 2: if (b.shape[0] == 2): cp = a[0]*b[1] - a[1]*b[0] if cp.ndim == 0: return cp else: return cp.swapaxes(0, 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] 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]) if cp.ndim == 1: return cp else: return cp.swapaxes(0, axisc) #Use numarray's printing function from .arrayprint import array2string, get_printoptions, set_printoptions _typelessdata = [int_, float_, complex_] if issubclass(intc, int): _typelessdata.append(intc) if issubclass(longlong, int): _typelessdata.append(longlong) def array_repr(arr, max_line_width=None, precision=None, suppress_small=None): """ Return the string representation of an array. Parameters ---------- arr : ndarray Input array. max_line_width : int, optional The maximum number of columns the string should span. Newline characters split the string appropriately after array elements. precision : int, optional Floating point precision. Default is the current printing precision (usually 8), which can be altered using `set_printoptions`. suppress_small : bool, optional Represent very small numbers as zero, default is False. Very small is defined by `precision`, if the precision is 8 then numbers smaller than 5e-9 are represented as zero. Returns ------- string : str The string representation of an array. See Also -------- array_str, array2string, set_printoptions Examples -------- >>> np.array_repr(np.array([1,2])) 'array([1, 2])' >>> np.array_repr(np.ma.array([0.])) 'MaskedArray([ 0.])' >>> np.array_repr(np.array([], np.int32)) 'array([], dtype=int32)' >>> x = np.array([1e-6, 4e-7, 2, 3]) >>> np.array_repr(x, precision=6, suppress_small=True) 'array([ 0.000001, 0. , 2. , 3. ])' """ if arr.size > 0 or arr.shape==(0,): lst = array2string(arr, max_line_width, precision, suppress_small, ', ', "array(") else: # show zero-length shape unless it is (0,) lst = "[], shape=%s" % (repr(arr.shape),) if arr.__class__ is not ndarray: cName= arr.__class__.__name__ else: cName = "array" skipdtype = (arr.dtype.type in _typelessdata) and arr.size > 0 if skipdtype: return "%s(%s)" % (cName, lst) else: typename = arr.dtype.name # Quote typename in the output if it is "complex". if typename and not (typename[0].isalpha() and typename.isalnum()): typename = "'%s'" % typename lf = '' if issubclass(arr.dtype.type, flexible): if arr.dtype.names: typename = "%s" % str(arr.dtype) else: typename = "'%s'" % str(arr.dtype) lf = '\n'+' '*len("array(") return cName + "(%s, %sdtype=%s)" % (lst, lf, typename) def array_str(a, max_line_width=None, precision=None, suppress_small=None): """ Return a string representation of the data in an array. The data in the array is returned as a single string. This function is similar to `array_repr`, the difference being that `array_repr` also returns information on the kind of array and its data type. Parameters ---------- a : ndarray Input array. max_line_width : int, optional Inserts newlines if text is longer than `max_line_width`. The default is, indirectly, 75. precision : int, optional Floating point precision. Default is the current printing precision (usually 8), which can be altered using `set_printoptions`. suppress_small : bool, optional Represent numbers "very close" to zero as zero; default is False. Very close is defined by precision: if the precision is 8, e.g., numbers smaller (in absolute value) than 5e-9 are represented as zero. See Also -------- array2string, array_repr, set_printoptions Examples -------- >>> np.array_str(np.arange(3)) '[0 1 2]' """ return array2string(a, max_line_width, precision, suppress_small, ' ', "", str) def set_string_function(f, repr=True): """ Set a Python function to be used when pretty printing arrays. Parameters ---------- f : function or None Function to be used to pretty print arrays. The function should expect a single array argument and return a string of the representation of the array. If None, the function is reset to the default NumPy function to print arrays. repr : bool, optional If True (default), the function for pretty printing (``__repr__``) is set, if False the function that returns the default string representation (``__str__``) is set. See Also -------- set_printoptions, get_printoptions Examples -------- >>> def pprint(arr): ... return 'HA! - What are you going to do now?' ... >>> np.set_string_function(pprint) >>> a = np.arange(10) >>> a HA! - What are you going to do now? >>> print a [0 1 2 3 4 5 6 7 8 9] We can reset the function to the default: >>> np.set_string_function(None) >>> a array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) `repr` affects either pretty printing or normal string representation. Note that ``__repr__`` is still affected by setting ``__str__`` because the width of each array element in the returned string becomes equal to the length of the result of ``__str__()``. >>> x = np.arange(4) >>> np.set_string_function(lambda x:'random', repr=False) >>> x.__str__() 'random' >>> x.__repr__() 'array([ 0, 1, 2, 3])' """ if f is None: if repr: return multiarray.set_string_function(array_repr, 1) else: return multiarray.set_string_function(array_str, 0) else: return multiarray.set_string_function(f, repr) set_string_function(array_str, 0) set_string_function(array_repr, 1) little_endian = (sys.byteorder == 'little') def indices(dimensions, dtype=int): """ Return an array representing the indices of a grid. Compute an array where the subarrays contain index values 0,1,... varying only along the corresponding axis. Parameters ---------- dimensions : sequence of ints The shape of the grid. dtype : dtype, optional Data type of the result. Returns ------- grid : ndarray The array of grid indices, ``grid.shape = (len(dimensions),) + tuple(dimensions)``. See Also -------- mgrid, meshgrid Notes ----- The output shape is obtained by prepending the number of dimensions in front of the tuple of dimensions, i.e. if `dimensions` is a tuple ``(r0, ..., rN-1)`` of length ``N``, the output shape is ``(N,r0,...,rN-1)``. The subarrays ``grid[k]`` contains the N-D array of indices along the ``k-th`` axis. Explicitly:: grid[k,i0,i1,...,iN-1] = ik Examples -------- >>> grid = np.indices((2, 3)) >>> grid.shape (2, 2, 3) >>> grid[0] # row indices array([[0, 0, 0], [1, 1, 1]]) >>> grid[1] # column indices array([[0, 1, 2], [0, 1, 2]]) The indices can be used as an index into an array. >>> x = np.arange(20).reshape(5, 4) >>> row, col = np.indices((2, 3)) >>> x[row, col] array([[0, 1, 2], [4, 5, 6]]) Note that it would be more straightforward in the above example to extract the required elements directly with ``x[:2, :3]``. """ dimensions = tuple(dimensions) N = len(dimensions) if N == 0: return array([], dtype=dtype) res = empty((N,)+dimensions, dtype=dtype) for i, dim in enumerate(dimensions): tmp = arange(dim, dtype=dtype) tmp.shape = (1,)*i + (dim,)+(1,)*(N-i-1) newdim = dimensions[:i] + (1,)+ dimensions[i+1:] val = zeros(newdim, dtype) add(tmp, val, res[i]) return res def fromfunction(function, shape, **kwargs): """ Construct an array by executing a function over each coordinate. The resulting array therefore has a value ``fn(x, y, z)`` at coordinate ``(x, y, z)``. Parameters ---------- function : callable The function is called with N parameters, where N is the rank of `shape`. Each parameter represents the coordinates of the array varying along a specific axis. For example, if `shape` were ``(2, 2)``, then the parameters in turn be (0, 0), (0, 1), (1, 0), (1, 1). shape : (N,) tuple of ints Shape of the output array, which also determines the shape of the coordinate arrays passed to `function`. dtype : data-type, optional Data-type of the coordinate arrays passed to `function`. By default, `dtype` is float. Returns ------- fromfunction : any The result of the call to `function` is passed back directly. Therefore the shape of `fromfunction` is completely determined by `function`. If `function` returns a scalar value, the shape of `fromfunction` would match the `shape` parameter. See Also -------- indices, meshgrid Notes ----- Keywords other than `dtype` are passed to `function`. Examples -------- >>> np.fromfunction(lambda i, j: i == j, (3, 3), dtype=int) array([[ True, False, False], [False, True, False], [False, False, True]], dtype=bool) >>> np.fromfunction(lambda i, j: i + j, (3, 3), dtype=int) array([[0, 1, 2], [1, 2, 3], [2, 3, 4]]) """ dtype = kwargs.pop('dtype', float) args = indices(shape, dtype=dtype) return function(*args,**kwargs) def isscalar(num): """ Returns True if the type of `num` is a scalar type. Parameters ---------- num : any Input argument, can be of any type and shape. Returns ------- val : bool True if `num` is a scalar type, False if it is not. Examples -------- >>> np.isscalar(3.1) True >>> np.isscalar([3.1]) False >>> np.isscalar(False) True """ if isinstance(num, generic): return True else: return type(num) in ScalarType _lkup = { '0':'0000', '1':'0001', '2':'0010', '3':'0011', '4':'0100', '5':'0101', '6':'0110', '7':'0111', '8':'1000', '9':'1001', 'a':'1010', 'b':'1011', 'c':'1100', 'd':'1101', 'e':'1110', 'f':'1111', 'A':'1010', 'B':'1011', 'C':'1100', 'D':'1101', 'E':'1110', 'F':'1111', 'L':''} def binary_repr(num, width=None): """ Return the binary representation of the input number as a string. For negative numbers, if width is not given, a minus sign is added to the front. If width is given, the two's complement of the number is returned, with respect to that width. 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 :math:`-2^{N-1}` to :math:`+2^{N-1}-1`. Parameters ---------- num : int Only an integer decimal number can be used. width : int, optional The length of the returned string if `num` is positive, the length of the two's complement if `num` is negative. Returns ------- bin : str Binary representation of `num` or two's complement of `num`. See Also -------- base_repr: Return a string representation of a number in the given base system. Notes ----- `binary_repr` is equivalent to using `base_repr` with base 2, but about 25x faster. References ---------- .. [1] Wikipedia, "Two's complement", http://en.wikipedia.org/wiki/Two's_complement Examples -------- >>> np.binary_repr(3) '11' >>> np.binary_repr(-3) '-11' >>> np.binary_repr(3, width=4) '0011' The two's complement is returned when the input number is negative and width is specified: >>> np.binary_repr(-3, width=4) '1101' """ # ' <-- unbreak Emacs fontification sign = '' if num < 0: if width is None: sign = '-' num = -num else: # replace num with its 2-complement num = 2**width + num elif num == 0: return '0'*(width or 1) ostr = hex(num) bin = ''.join([_lkup[ch] for ch in ostr[2:]]) bin = bin.lstrip('0') if width is not None: bin = bin.zfill(width) return sign + bin def base_repr(number, base=2, padding=0): """ Return a string representation of a number in the given base system. Parameters ---------- number : int The value to convert. Only positive values are handled. base : int, optional Convert `number` to the `base` number system. The valid range is 2-36, the default value is 2. padding : int, optional Number of zeros padded on the left. Default is 0 (no padding). Returns ------- out : str String representation of `number` in `base` system. See Also -------- binary_repr : Faster version of `base_repr` for base 2. Examples -------- >>> np.base_repr(5) '101' >>> np.base_repr(6, 5) '11' >>> np.base_repr(7, base=5, padding=3) '00012' >>> np.base_repr(10, base=16) 'A' >>> np.base_repr(32, base=16) '20' """ digits = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ' if base > len(digits): raise ValueError("Bases greater than 36 not handled in base_repr.") num = abs(number) res = [] while num: res.append(digits[num % base]) num //= base if padding: res.append('0' * padding) if number < 0: res.append('-') return ''.join(reversed(res or '0')) def load(file): """ Wrapper around cPickle.load which accepts either a file-like object or a filename. Note that the NumPy binary format is not based on pickle/cPickle anymore. For details on the preferred way of loading and saving files, see `load` and `save`. See Also -------- load, save """ if isinstance(file, type("")): file = open(file, "rb") return pickle.load(file) # These are all essentially abbreviations # These might wind up in a special abbreviations module def _maketup(descr, val): dt = dtype(descr) # Place val in all scalar tuples: fields = dt.fields if fields is None: return val else: res = [_maketup(fields[name][0], val) for name in dt.names] return tuple(res) def identity(n, dtype=None): """ Return the identity array. The identity array is a square array with ones on the main diagonal. Parameters ---------- n : int Number of rows (and columns) in `n` x `n` output. dtype : data-type, optional Data-type of the output. Defaults to ``float``. Returns ------- out : ndarray `n` x `n` array with its main diagonal set to one, and all other elements 0. Examples -------- >>> np.identity(3) array([[ 1., 0., 0.], [ 0., 1., 0.], [ 0., 0., 1.]]) """ from numpy import eye return eye(n, dtype=dtype) def allclose(a, b, rtol=1.e-5, atol=1.e-8): """ Returns True if two arrays are element-wise equal within a tolerance. The tolerance values are positive, typically very small numbers. The relative difference (`rtol` * abs(`b`)) and the absolute difference `atol` are added together to compare against the absolute difference between `a` and `b`. If either array contains one or more NaNs, False is returned. Infs are treated as equal if they are in the same place and of the same sign in both arrays. Parameters ---------- a, b : array_like Input arrays to compare. rtol : float The relative tolerance parameter (see Notes). atol : float The absolute tolerance parameter (see Notes). Returns ------- allclose : bool Returns True if the two arrays are equal within the given tolerance; False otherwise. See Also -------- isclose, all, any Notes ----- If the following equation is element-wise True, then allclose returns True. absolute(`a` - `b`) <= (`atol` + `rtol` * absolute(`b`)) The above equation is not symmetric in `a` and `b`, so that `allclose(a, b)` might be different from `allclose(b, a)` in some rare cases. Examples -------- >>> np.allclose([1e10,1e-7], [1.00001e10,1e-8]) False >>> np.allclose([1e10,1e-8], [1.00001e10,1e-9]) True >>> np.allclose([1e10,1e-8], [1.0001e10,1e-9]) False >>> np.allclose([1.0, np.nan], [1.0, np.nan]) False """ x = array(a, copy=False, ndmin=1) y = array(b, copy=False, ndmin=1) xinf = isinf(x) yinf = isinf(y) if any(xinf) or any(yinf): # Check that x and y have inf's only in the same positions if not all(xinf == yinf): return False # Check that sign of inf's in x and y is the same if not all(x[xinf] == y[xinf]): return False x = x[~xinf] y = y[~xinf] # ignore invalid fpe's with errstate(invalid='ignore'): r = all(less_equal(abs(x-y), atol + rtol * abs(y))) return r def isclose(a, b, rtol=1.e-5, atol=1.e-8, equal_nan=False): """ Returns a boolean array where two arrays are element-wise equal within a tolerance. The tolerance values are positive, typically very small numbers. The relative difference (`rtol` * abs(`b`)) and the absolute difference `atol` are added together to compare against the absolute difference between `a` and `b`. Parameters ---------- a, b : array_like Input arrays to compare. rtol : float The relative tolerance parameter (see Notes). atol : float The absolute tolerance parameter (see Notes). equal_nan : bool Whether to compare NaN's as equal. If True, NaN's in `a` will be considered equal to NaN's in `b` in the output array. Returns ------- y : array_like Returns a boolean array of where `a` and `b` are equal within the given tolerance. If both `a` and `b` are scalars, returns a single boolean value. See Also -------- allclose Notes ----- .. versionadded:: 1.7.0 For finite values, isclose uses the following equation to test whether two floating point values are equivalent. absolute(`a` - `b`) <= (`atol` + `rtol` * absolute(`b`)) The above equation is not symmetric in `a` and `b`, so that `isclose(a, b)` might be different from `isclose(b, a)` in some rare cases. Examples -------- >>> np.isclose([1e10,1e-7], [1.00001e10,1e-8]) array([True, False]) >>> np.isclose([1e10,1e-8], [1.00001e10,1e-9]) array([True, True]) >>> np.isclose([1e10,1e-8], [1.0001e10,1e-9]) array([False, True]) >>> np.isclose([1.0, np.nan], [1.0, np.nan]) array([True, False]) >>> np.isclose([1.0, np.nan], [1.0, np.nan], equal_nan=True) array([True, True]) """ def within_tol(x, y, atol, rtol): with errstate(invalid='ignore'): result = less_equal(abs(x-y), atol + rtol * abs(y)) if isscalar(a) and isscalar(b): result = bool(result) return result x = array(a, copy=False, subok=True, ndmin=1) y = array(b, copy=False, subok=True, ndmin=1) xfin = isfinite(x) yfin = isfinite(y) if all(xfin) and all(yfin): return within_tol(x, y, atol, rtol) else: finite = xfin & yfin cond = zeros_like(finite, subok=True) # Because we're using boolean indexing, x & y must be the same shape. # Ideally, we'd just do x, y = broadcast_arrays(x, y). It's in # lib.stride_tricks, though, so we can't import it here. x = x * ones_like(cond) y = y * ones_like(cond) # Avoid subtraction with infinite/nan values... cond[finite] = within_tol(x[finite], y[finite], atol, rtol) # Check for equality of infinite values... cond[~finite] = (x[~finite] == y[~finite]) if equal_nan: # Make NaN == NaN cond[isnan(x) & isnan(y)] = True return cond def array_equal(a1, a2): """ True if two arrays have the same shape and elements, False otherwise. Parameters ---------- a1, a2 : array_like Input arrays. Returns ------- b : bool Returns True if the arrays are equal. See Also -------- allclose: Returns True if two arrays are element-wise equal within a tolerance. array_equiv: Returns True if input arrays are shape consistent and all elements equal. Examples -------- >>> np.array_equal([1, 2], [1, 2]) True >>> np.array_equal(np.array([1, 2]), np.array([1, 2])) True >>> np.array_equal([1, 2], [1, 2, 3]) False >>> np.array_equal([1, 2], [1, 4]) False """ try: a1, a2 = asarray(a1), asarray(a2) except: return False if a1.shape != a2.shape: return False return bool(asarray(a1 == a2).all()) def array_equiv(a1, a2): """ Returns True if input arrays are shape consistent and all elements equal. Shape consistent means they are either the same shape, or one input array can be broadcasted to create the same shape as the other one. Parameters ---------- a1, a2 : array_like Input arrays. Returns ------- out : bool True if equivalent, False otherwise. Examples -------- >>> np.array_equiv([1, 2], [1, 2]) True >>> np.array_equiv([1, 2], [1, 3]) False Showing the shape equivalence: >>> np.array_equiv([1, 2], [[1, 2], [1, 2]]) True >>> np.array_equiv([1, 2], [[1, 2, 1, 2], [1, 2, 1, 2]]) False >>> np.array_equiv([1, 2], [[1, 2], [1, 3]]) False """ try: a1, a2 = asarray(a1), asarray(a2) except: return False try: return bool(asarray(a1 == a2).all()) except ValueError: return False _errdict = {"ignore":ERR_IGNORE, "warn":ERR_WARN, "raise":ERR_RAISE, "call":ERR_CALL, "print":ERR_PRINT, "log":ERR_LOG} _errdict_rev = {} for key in _errdict.keys(): _errdict_rev[_errdict[key]] = key del key def seterr(all=None, divide=None, over=None, under=None, invalid=None): """ Set how floating-point errors are handled. Note that operations on integer scalar types (such as `int16`) are handled like floating point, and are affected by these settings. Parameters ---------- all : {'ignore', 'warn', 'raise', 'call', 'print', 'log'}, optional Set treatment for all types of floating-point errors at once: - ignore: Take no action when the exception occurs. - warn: Print a `RuntimeWarning` (via the Python `warnings` module). - raise: Raise a `FloatingPointError`. - call: Call a function specified using the `seterrcall` function. - print: Print a warning directly to ``stdout``. - log: Record error in a Log object specified by `seterrcall`. The default is not to change the current behavior. divide : {'ignore', 'warn', 'raise', 'call', 'print', 'log'}, optional Treatment for division by zero. over : {'ignore', 'warn', 'raise', 'call', 'print', 'log'}, optional Treatment for floating-point overflow. under : {'ignore', 'warn', 'raise', 'call', 'print', 'log'}, optional Treatment for floating-point underflow. invalid : {'ignore', 'warn', 'raise', 'call', 'print', 'log'}, optional Treatment for invalid floating-point operation. Returns ------- old_settings : dict Dictionary containing the old settings. See also -------- seterrcall : Set a callback function for the 'call' mode. geterr, geterrcall, errstate Notes ----- The floating-point exceptions are defined in the IEEE 754 standard [1]: - Division by zero: infinite result obtained from finite numbers. - Overflow: result too large to be expressed. - Underflow: result so close to zero that some precision was lost. - Invalid operation: result is not an expressible number, typically indicates that a NaN was produced. .. [1] http://en.wikipedia.org/wiki/IEEE_754 Examples -------- >>> old_settings = np.seterr(all='ignore') #seterr to known value >>> np.seterr(over='raise') {'over': 'ignore', 'divide': 'ignore', 'invalid': 'ignore', 'under': 'ignore'} >>> np.seterr(**old_settings) # reset to default {'over': 'raise', 'divide': 'ignore', 'invalid': 'ignore', 'under': 'ignore'} >>> np.int16(32000) * np.int16(3) 30464 >>> old_settings = np.seterr(all='warn', over='raise') >>> np.int16(32000) * np.int16(3) Traceback (most recent call last): File "", line 1, in FloatingPointError: overflow encountered in short_scalars >>> old_settings = np.seterr(all='print') >>> np.geterr() {'over': 'print', 'divide': 'print', 'invalid': 'print', 'under': 'print'} >>> np.int16(32000) * np.int16(3) Warning: overflow encountered in short_scalars 30464 """ pyvals = umath.geterrobj() old = geterr() if divide is None: divide = all or old['divide'] if over is None: over = all or old['over'] if under is None: under = all or old['under'] if invalid is None: invalid = all or old['invalid'] maskvalue = ((_errdict[divide] << SHIFT_DIVIDEBYZERO) + (_errdict[over] << SHIFT_OVERFLOW ) + (_errdict[under] << SHIFT_UNDERFLOW) + (_errdict[invalid] << SHIFT_INVALID)) pyvals[1] = maskvalue umath.seterrobj(pyvals) return old def geterr(): """ Get the current way of handling floating-point errors. Returns ------- res : dict A dictionary with keys "divide", "over", "under", and "invalid", whose values are from the strings "ignore", "print", "log", "warn", "raise", and "call". The keys represent possible floating-point exceptions, and the values define how these exceptions are handled. See Also -------- geterrcall, seterr, seterrcall Notes ----- For complete documentation of the types of floating-point exceptions and treatment options, see `seterr`. Examples -------- >>> np.geterr() {'over': 'warn', 'divide': 'warn', 'invalid': 'warn', 'under': 'ignore'} >>> np.arange(3.) / np.arange(3.) array([ NaN, 1., 1.]) >>> oldsettings = np.seterr(all='warn', over='raise') >>> np.geterr() {'over': 'raise', 'divide': 'warn', 'invalid': 'warn', 'under': 'warn'} >>> np.arange(3.) / np.arange(3.) __main__:1: RuntimeWarning: invalid value encountered in divide array([ NaN, 1., 1.]) """ maskvalue = umath.geterrobj()[1] mask = 7 res = {} val = (maskvalue >> SHIFT_DIVIDEBYZERO) & mask res['divide'] = _errdict_rev[val] val = (maskvalue >> SHIFT_OVERFLOW) & mask res['over'] = _errdict_rev[val] val = (maskvalue >> SHIFT_UNDERFLOW) & mask res['under'] = _errdict_rev[val] val = (maskvalue >> SHIFT_INVALID) & mask res['invalid'] = _errdict_rev[val] return res def setbufsize(size): """ Set the size of the buffer used in ufuncs. Parameters ---------- size : int Size of buffer. """ if size > 10e6: raise ValueError("Buffer size, %s, is too big." % size) if size < 5: raise ValueError("Buffer size, %s, is too small." %size) if size % 16 != 0: raise ValueError("Buffer size, %s, is not a multiple of 16." %size) pyvals = umath.geterrobj() old = getbufsize() pyvals[0] = size umath.seterrobj(pyvals) return old def getbufsize(): """ Return the size of the buffer used in ufuncs. Returns ------- getbufsize : int Size of ufunc buffer in bytes. """ return umath.geterrobj()[0] def seterrcall(func): """ Set the floating-point error callback function or log object. There are two ways to capture floating-point error messages. The first is to set the error-handler to 'call', using `seterr`. Then, set the function to call using this function. The second is to set the error-handler to 'log', using `seterr`. Floating-point errors then trigger a call to the 'write' method of the provided object. Parameters ---------- func : callable f(err, flag) or object with write method Function to call upon floating-point errors ('call'-mode) or object whose 'write' method is used to log such message ('log'-mode). The call function takes two arguments. The first is the type of error (one of "divide", "over", "under", or "invalid"), and the second is the status flag. The flag is a byte, whose least-significant bits indicate the status:: [0 0 0 0 invalid over under invalid] In other words, ``flags = divide + 2*over + 4*under + 8*invalid``. If an object is provided, its write method should take one argument, a string. Returns ------- h : callable, log instance or None The old error handler. See Also -------- seterr, geterr, geterrcall Examples -------- Callback upon error: >>> def err_handler(type, flag): ... print "Floating point error (%s), with flag %s" % (type, flag) ... >>> saved_handler = np.seterrcall(err_handler) >>> save_err = np.seterr(all='call') >>> np.array([1, 2, 3]) / 0.0 Floating point error (divide by zero), with flag 1 array([ Inf, Inf, Inf]) >>> np.seterrcall(saved_handler) >>> np.seterr(**save_err) {'over': 'call', 'divide': 'call', 'invalid': 'call', 'under': 'call'} Log error message: >>> class Log(object): ... def write(self, msg): ... print "LOG: %s" % msg ... >>> log = Log() >>> saved_handler = np.seterrcall(log) >>> save_err = np.seterr(all='log') >>> np.array([1, 2, 3]) / 0.0 LOG: Warning: divide by zero encountered in divide array([ Inf, Inf, Inf]) >>> np.seterrcall(saved_handler) <__main__.Log object at 0x...> >>> np.seterr(**save_err) {'over': 'log', 'divide': 'log', 'invalid': 'log', 'under': 'log'} """ if func is not None and not isinstance(func, collections.Callable): if not hasattr(func, 'write') or not isinstance(func.write, collections.Callable): raise ValueError("Only callable can be used as callback") pyvals = umath.geterrobj() old = geterrcall() pyvals[2] = func umath.seterrobj(pyvals) return old def geterrcall(): """ Return the current callback function used on floating-point errors. When the error handling for a floating-point error (one of "divide", "over", "under", or "invalid") is set to 'call' or 'log', the function that is called or the log instance that is written to is returned by `geterrcall`. This function or log instance has been set with `seterrcall`. Returns ------- errobj : callable, log instance or None The current error handler. If no handler was set through `seterrcall`, ``None`` is returned. See Also -------- seterrcall, seterr, geterr Notes ----- For complete documentation of the types of floating-point exceptions and treatment options, see `seterr`. Examples -------- >>> np.geterrcall() # we did not yet set a handler, returns None >>> oldsettings = np.seterr(all='call') >>> def err_handler(type, flag): ... print "Floating point error (%s), with flag %s" % (type, flag) >>> oldhandler = np.seterrcall(err_handler) >>> np.array([1, 2, 3]) / 0.0 Floating point error (divide by zero), with flag 1 array([ Inf, Inf, Inf]) >>> cur_handler = np.geterrcall() >>> cur_handler is err_handler True """ return umath.geterrobj()[2] class _unspecified(object): pass _Unspecified = _unspecified() class errstate(object): """ errstate(**kwargs) Context manager for floating-point error handling. Using an instance of `errstate` as a context manager allows statements in that context to execute with a known error handling behavior. Upon entering the context the error handling is set with `seterr` and `seterrcall`, and upon exiting it is reset to what it was before. Parameters ---------- kwargs : {divide, over, under, invalid} Keyword arguments. The valid keywords are the possible floating-point exceptions. Each keyword should have a string value that defines the treatment for the particular error. Possible values are {'ignore', 'warn', 'raise', 'call', 'print', 'log'}. See Also -------- seterr, geterr, seterrcall, geterrcall Notes ----- The ``with`` statement was introduced in Python 2.5, and can only be used there by importing it: ``from __future__ import with_statement``. In earlier Python versions the ``with`` statement is not available. For complete documentation of the types of floating-point exceptions and treatment options, see `seterr`. Examples -------- >>> from __future__ import with_statement # use 'with' in Python 2.5 >>> olderr = np.seterr(all='ignore') # Set error handling to known state. >>> np.arange(3) / 0. array([ NaN, Inf, Inf]) >>> with np.errstate(divide='warn'): ... np.arange(3) / 0. ... __main__:2: RuntimeWarning: divide by zero encountered in divide array([ NaN, Inf, Inf]) >>> np.sqrt(-1) nan >>> with np.errstate(invalid='raise'): ... np.sqrt(-1) Traceback (most recent call last): File "", line 2, in FloatingPointError: invalid value encountered in sqrt Outside the context the error handling behavior has not changed: >>> np.geterr() {'over': 'warn', 'divide': 'warn', 'invalid': 'warn', 'under': 'ignore'} """ # Note that we don't want to run the above doctests because they will fail # without a from __future__ import with_statement def __init__(self, **kwargs): self.call = kwargs.pop('call', _Unspecified) self.kwargs = kwargs def __enter__(self): self.oldstate = seterr(**self.kwargs) if self.call is not _Unspecified: self.oldcall = seterrcall(self.call) def __exit__(self, *exc_info): seterr(**self.oldstate) if self.call is not _Unspecified: seterrcall(self.oldcall) def _setdef(): defval = [UFUNC_BUFSIZE_DEFAULT, ERR_DEFAULT2, None] umath.seterrobj(defval) # set the default values _setdef() Inf = inf = infty = Infinity = PINF nan = NaN = NAN False_ = bool_(False) True_ = bool_(True) from . import fromnumeric from .fromnumeric import * extend_all(fromnumeric) numpy-1.8.2/numpy/core/setup_common.py0000664000175100017510000002763412370216243021222 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function # Code common to build tools import sys from os.path import join import warnings import copy import binascii from distutils.ccompiler import CompileError #------------------- # Versioning support #------------------- # How to change C_API_VERSION ? # - increase C_API_VERSION value # - record the hash for the new C API with the script cversions.py # and add the hash to cversions.txt # The hash values are used to remind developers when the C API number was not # updated - generates a MismatchCAPIWarning warning which is turned into an # exception for released version. # Binary compatibility version number. This number is increased whenever the # C-API is changed such that binary compatibility is broken, i.e. whenever a # recompile of extension modules is needed. C_ABI_VERSION = 0x01000009 # Minor API version. This number is increased whenever a change is made to the # C-API -- whether it breaks binary compatibility or not. Some changes, such # as adding a function pointer to the end of the function table, can be made # without breaking binary compatibility. In this case, only the C_API_VERSION # (*not* C_ABI_VERSION) would be increased. Whenever binary compatibility is # broken, both C_API_VERSION and C_ABI_VERSION should be increased. # # 0x00000008 - 1.7.x # 0x00000009 - 1.8.x C_API_VERSION = 0x00000009 class MismatchCAPIWarning(Warning): pass def is_released(config): """Return True if a released version of numpy is detected.""" from distutils.version import LooseVersion v = config.get_version('../version.py') if v is None: raise ValueError("Could not get version") pv = LooseVersion(vstring=v).version if len(pv) > 3: return False return True def get_api_versions(apiversion, codegen_dir): """Return current C API checksum and the recorded checksum for the given version of the C API version.""" api_files = [join(codegen_dir, 'numpy_api_order.txt'), join(codegen_dir, 'ufunc_api_order.txt')] # Compute the hash of the current API as defined in the .txt files in # code_generators sys.path.insert(0, codegen_dir) try: m = __import__('genapi') numpy_api = __import__('numpy_api') curapi_hash = m.fullapi_hash(numpy_api.full_api) apis_hash = m.get_versions_hash() finally: del sys.path[0] return curapi_hash, apis_hash[apiversion] def check_api_version(apiversion, codegen_dir): """Emits a MismacthCAPIWarning if the C API version needs updating.""" curapi_hash, api_hash = get_api_versions(apiversion, codegen_dir) # If different hash, it means that the api .txt files in # codegen_dir have been updated without the API version being # updated. Any modification in those .txt files should be reflected # in the api and eventually abi versions. # To compute the checksum of the current API, use # code_generators/cversions.py script if not curapi_hash == api_hash: msg = "API mismatch detected, the C API version " \ "numbers have to be updated. Current C api version is %d, " \ "with checksum %s, but recorded checksum for C API version %d in " \ "codegen_dir/cversions.txt is %s. If functions were added in the " \ "C API, you have to update C_API_VERSION in %s." warnings.warn(msg % (apiversion, curapi_hash, apiversion, api_hash, __file__), MismatchCAPIWarning) # Mandatory functions: if not found, fail the build MANDATORY_FUNCS = ["sin", "cos", "tan", "sinh", "cosh", "tanh", "fabs", "floor", "ceil", "sqrt", "log10", "log", "exp", "asin", "acos", "atan", "fmod", 'modf', 'frexp', 'ldexp'] # Standard functions which may not be available and for which we have a # 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", "ftello", "fseeko"] OPTIONAL_HEADERS = [ # sse headers only enabled automatically on amd64/x32 builds "xmmintrin.h", # SSE "emmintrin.h", # SSE2 ] # optional gcc compiler builtins and their call arguments and optional a # required header # call arguments are required as the compiler will do strict signature checking OPTIONAL_INTRINSICS = [("__builtin_isnan", '5.'), ("__builtin_isinf", '5.'), ("__builtin_isfinite", '5.'), ("__builtin_bswap32", '5u'), ("__builtin_bswap64", '5u'), ("__builtin_expect", '5, 0'), ("_mm_load_ps", '(float*)0', "xmmintrin.h"), # SSE ("_mm_load_pd", '(double*)0', "emmintrin.h"), # SSE2 ] # gcc function attributes # (attribute as understood by gcc, function name), # function name will be converted to HAVE_ preprocessor macro OPTIONAL_GCC_ATTRIBUTES = [('__attribute__((optimize("unroll-loops")))', 'attribute_optimize_unroll_loops'), ] # Subset of OPTIONAL_STDFUNCS which may alreay have HAVE_* defined by Python.h OPTIONAL_STDFUNCS_MAYBE = ["expm1", "log1p", "acosh", "atanh", "asinh", "hypot", "copysign", "ftello", "fseeko"] # C99 functions: float and long double versions C99_FUNCS = ["sin", "cos", "tan", "sinh", "cosh", "tanh", "fabs", "floor", "ceil", "rint", "trunc", "sqrt", "log10", "log", "log1p", "exp", "expm1", "asin", "acos", "atan", "asinh", "acosh", "atanh", "hypot", "atan2", "pow", "fmod", "modf", 'frexp', 'ldexp', "exp2", "log2", "copysign", "nextafter"] C99_FUNCS_SINGLE = [f + 'f' for f in C99_FUNCS] C99_FUNCS_EXTENDED = [f + 'l' for f in C99_FUNCS] C99_COMPLEX_TYPES = ['complex double', 'complex float', 'complex long double'] C99_COMPLEX_FUNCS = ['creal', 'cimag', 'cabs', 'carg', 'cexp', 'csqrt', 'clog', 'ccos', 'csin', 'cpow'] def fname2def(name): return "HAVE_%s" % name.upper() def sym2def(symbol): define = symbol.replace(' ', '') return define.upper() def type2def(symbol): define = symbol.replace(' ', '_') return define.upper() # Code to detect long double representation taken from MPFR m4 macro def check_long_double_representation(cmd): cmd._check_compiler() body = LONG_DOUBLE_REPRESENTATION_SRC % {'type': 'long double'} # We need to use _compile because we need the object filename src, object = cmd._compile(body, None, None, 'c') try: type = long_double_representation(pyod(object)) return type finally: cmd._clean() LONG_DOUBLE_REPRESENTATION_SRC = r""" /* "before" is 16 bytes to ensure there's no padding between it and "x". * We're not expecting any "long double" bigger than 16 bytes or with * alignment requirements stricter than 16 bytes. */ typedef %(type)s test_type; struct { char before[16]; test_type x; char after[8]; } foo = { { '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\001', '\043', '\105', '\147', '\211', '\253', '\315', '\357' }, -123456789.0, { '\376', '\334', '\272', '\230', '\166', '\124', '\062', '\020' } }; """ def pyod(filename): """Python implementation of the od UNIX utility (od -b, more exactly). Parameters ---------- filename : str name of the file to get the dump from. Returns ------- out : seq list of lines of od output Note ---- We only implement enough to get the necessary information for long double representation, this is not intended as a compatible replacement for od. """ def _pyod2(): out = [] fid = open(filename, 'rb') try: yo = [int(oct(int(binascii.b2a_hex(o), 16))) for o in fid.read()] for i in range(0, len(yo), 16): line = ['%07d' % int(oct(i))] line.extend(['%03d' % c for c in yo[i:i+16]]) out.append(" ".join(line)) return out finally: fid.close() def _pyod3(): out = [] fid = open(filename, 'rb') try: yo2 = [oct(o)[2:] for o in fid.read()] for i in range(0, len(yo2), 16): line = ['%07d' % int(oct(i)[2:])] line.extend(['%03d' % int(c) for c in yo2[i:i+16]]) out.append(" ".join(line)) return out finally: fid.close() if sys.version_info[0] < 3: return _pyod2() else: return _pyod3() _BEFORE_SEQ = ['000', '000', '000', '000', '000', '000', '000', '000', '001', '043', '105', '147', '211', '253', '315', '357'] _AFTER_SEQ = ['376', '334', '272', '230', '166', '124', '062', '020'] _IEEE_DOUBLE_BE = ['301', '235', '157', '064', '124', '000', '000', '000'] _IEEE_DOUBLE_LE = _IEEE_DOUBLE_BE[::-1] _INTEL_EXTENDED_12B = ['000', '000', '000', '000', '240', '242', '171', '353', '031', '300', '000', '000'] _INTEL_EXTENDED_16B = ['000', '000', '000', '000', '240', '242', '171', '353', '031', '300', '000', '000', '000', '000', '000', '000'] _MOTOROLA_EXTENDED_12B = ['300', '031', '000', '000', '353', '171', '242', '240', '000', '000', '000', '000'] _IEEE_QUAD_PREC_BE = ['300', '031', '326', '363', '105', '100', '000', '000', '000', '000', '000', '000', '000', '000', '000', '000'] _IEEE_QUAD_PREC_LE = _IEEE_QUAD_PREC_BE[::-1] _DOUBLE_DOUBLE_BE = ['301', '235', '157', '064', '124', '000', '000', '000'] + \ ['000'] * 8 def long_double_representation(lines): """Given a binary dump as given by GNU od -b, look for long double representation.""" # Read contains a list of 32 items, each item is a byte (in octal # representation, as a string). We 'slide' over the output until read is of # the form before_seq + content + after_sequence, where content is the long double # representation: # - content is 12 bytes: 80 bits Intel representation # - content is 16 bytes: 80 bits Intel representation (64 bits) or quad precision # - content is 8 bytes: same as double (not implemented yet) read = [''] * 32 saw = None for line in lines: # we skip the first word, as od -b output an index at the beginning of # each line for w in line.split()[1:]: read.pop(0) read.append(w) # If the end of read is equal to the after_sequence, read contains # the long double if read[-8:] == _AFTER_SEQ: saw = copy.copy(read) if read[:12] == _BEFORE_SEQ[4:]: if read[12:-8] == _INTEL_EXTENDED_12B: return 'INTEL_EXTENDED_12_BYTES_LE' if read[12:-8] == _MOTOROLA_EXTENDED_12B: return 'MOTOROLA_EXTENDED_12_BYTES_BE' elif read[:8] == _BEFORE_SEQ[8:]: if read[8:-8] == _INTEL_EXTENDED_16B: return 'INTEL_EXTENDED_16_BYTES_LE' elif read[8:-8] == _IEEE_QUAD_PREC_BE: return 'IEEE_QUAD_BE' elif read[8:-8] == _IEEE_QUAD_PREC_LE: return 'IEEE_QUAD_LE' elif read[8:-8] == _DOUBLE_DOUBLE_BE: return 'DOUBLE_DOUBLE_BE' elif read[:16] == _BEFORE_SEQ: if read[16:-8] == _IEEE_DOUBLE_LE: return 'IEEE_DOUBLE_LE' elif read[16:-8] == _IEEE_DOUBLE_BE: return 'IEEE_DOUBLE_BE' if saw is not None: raise ValueError("Unrecognized format (%s)" % saw) else: # We never detected the after_sequence raise ValueError("Could not lock sequences (%s)" % saw) numpy-1.8.2/numpy/core/mlib.ini.in0000664000175100017510000000025012370216242020151 0ustar vagrantvagrant00000000000000[meta] Name = mlib Description = Math library used with this version of numpy Version = 1.0 [default] Libs=@posix_mathlib@ Cflags= [msvc] Libs=@msvc_mathlib@ Cflags= numpy-1.8.2/numpy/core/numerictypes.py0000664000175100017510000007053612370216243021240 0ustar vagrantvagrant00000000000000""" numerictypes: Define the numeric type objects This module is designed so "from numerictypes import \\*" is safe. Exported symbols include: Dictionary with all registered number types (including aliases): typeDict Type objects (not all will be available, depends on platform): see variable sctypes for which ones you have Bit-width names int8 int16 int32 int64 int128 uint8 uint16 uint32 uint64 uint128 float16 float32 float64 float96 float128 float256 complex32 complex64 complex128 complex192 complex256 complex512 datetime64 timedelta64 c-based names bool_ object_ void, str_, unicode_ byte, ubyte, short, ushort intc, uintc, intp, uintp, int_, uint, longlong, ulonglong, single, csingle, float_, complex_, longfloat, clongfloat, As part of the type-hierarchy: xx -- is bit-width generic +-> bool_ (kind=b) +-> number (kind=i) | integer | signedinteger (intxx) | byte | short | intc | intp int0 | int_ | longlong +-> unsignedinteger (uintxx) (kind=u) | ubyte | ushort | uintc | uintp uint0 | uint_ | ulonglong +-> inexact | +-> floating (floatxx) (kind=f) | | half | | single | | float_ (double) | | longfloat | \\-> complexfloating (complexxx) (kind=c) | csingle (singlecomplex) | complex_ (cfloat, cdouble) | clongfloat (longcomplex) +-> flexible | character | void (kind=V) | | str_ (string_, bytes_) (kind=S) [Python 2] | unicode_ (kind=U) [Python 2] | | bytes_ (string_) (kind=S) [Python 3] | str_ (unicode_) (kind=U) [Python 3] | \\-> object_ (not used much) (kind=O) """ from __future__ import division, absolute_import, print_function # we add more at the bottom __all__ = ['sctypeDict', 'sctypeNA', 'typeDict', 'typeNA', 'sctypes', 'ScalarType', 'obj2sctype', 'cast', 'nbytes', 'sctype2char', 'maximum_sctype', 'issctype', 'typecodes', 'find_common_type', 'issubdtype', 'datetime_data', 'datetime_as_string', 'busday_offset', 'busday_count', 'is_busday', 'busdaycalendar', ] from numpy.core.multiarray import ( typeinfo, ndarray, array, empty, dtype, datetime_data, datetime_as_string, busday_offset, busday_count, is_busday, busdaycalendar ) import types as _types import sys from numpy.compat import bytes, long # we don't export these for import *, but we do want them accessible # as numerictypes.bool, etc. if sys.version_info[0] >= 3: from builtins import bool, int, float, complex, object, str unicode = str else: from __builtin__ import bool, int, float, complex, object, unicode, str # String-handling utilities to avoid locale-dependence. # "import string" is costly to import! # Construct the translation tables directly # "A" = chr(65), "a" = chr(97) _all_chars = [chr(_m) for _m in range(256)] _ascii_upper = _all_chars[65:65+26] _ascii_lower = _all_chars[97:97+26] LOWER_TABLE="".join(_all_chars[:65] + _ascii_lower + _all_chars[65+26:]) UPPER_TABLE="".join(_all_chars[:97] + _ascii_upper + _all_chars[97+26:]) #import string # assert (string.maketrans(string.ascii_uppercase, string.ascii_lowercase) == \ # LOWER_TABLE) # assert (string.maketrnas(string_ascii_lowercase, string.ascii_uppercase) == \ # UPPER_TABLE) #LOWER_TABLE = string.maketrans(string.ascii_uppercase, string.ascii_lowercase) #UPPER_TABLE = string.maketrans(string.ascii_lowercase, string.ascii_uppercase) def english_lower(s): """ Apply English case rules to convert ASCII strings to all lower case. This is an internal utility function to replace calls to str.lower() such that we can avoid changing behavior with changing locales. In particular, Turkish has distinct dotted and dotless variants of the Latin letter "I" in both lowercase and uppercase. Thus, "I".lower() != "i" in a "tr" locale. Parameters ---------- s : str Returns ------- lowered : str Examples -------- >>> from numpy.core.numerictypes import english_lower >>> english_lower('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_') 'abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz0123456789_' >>> english_lower('') '' """ lowered = s.translate(LOWER_TABLE) return lowered def english_upper(s): """ Apply English case rules to convert ASCII strings to all upper case. This is an internal utility function to replace calls to str.upper() such that we can avoid changing behavior with changing locales. In particular, Turkish has distinct dotted and dotless variants of the Latin letter "I" in both lowercase and uppercase. Thus, "i".upper() != "I" in a "tr" locale. Parameters ---------- s : str Returns ------- uppered : str Examples -------- >>> from numpy.core.numerictypes import english_upper >>> english_upper('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_') 'ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_' >>> english_upper('') '' """ uppered = s.translate(UPPER_TABLE) return uppered def english_capitalize(s): """ Apply English case rules to convert the first character of an ASCII string to upper case. This is an internal utility function to replace calls to str.capitalize() such that we can avoid changing behavior with changing locales. Parameters ---------- s : str Returns ------- capitalized : str Examples -------- >>> from numpy.core.numerictypes import english_capitalize >>> english_capitalize('int8') 'Int8' >>> english_capitalize('Int8') 'Int8' >>> english_capitalize('') '' """ if s: return english_upper(s[0]) + s[1:] else: return s sctypeDict = {} # Contains all leaf-node scalar types with aliases sctypeNA = {} # Contails all leaf-node types -> numarray type equivalences allTypes = {} # Collect the types we will add to the module here def _evalname(name): k = 0 for ch in name: if ch in '0123456789': break k += 1 try: bits = int(name[k:]) except ValueError: bits = 0 base = name[:k] return base, bits def bitname(obj): """Return a bit-width name for a given type object""" name = obj.__name__ base = '' char = '' try: if name[-1] == '_': newname = name[:-1] else: newname = name info = typeinfo[english_upper(newname)] assert(info[-1] == obj) # sanity check bits = info[2] except KeyError: # bit-width name base, bits = _evalname(name) char = base[0] if name == 'bool_': char = 'b' base = 'bool' elif name=='void': char = 'V' base = 'void' elif name=='object_': char = 'O' base = 'object' bits = 0 elif name=='datetime64': char = 'M' elif name=='timedelta64': char = 'm' if sys.version_info[0] >= 3: if name=='bytes_': char = 'S' base = 'bytes' elif name=='str_': char = 'U' base = 'str' else: if name=='string_': char = 'S' base = 'string' elif name=='unicode_': char = 'U' base = 'unicode' bytes = bits // 8 if char != '' and bytes != 0: char = "%s%d" % (char, bytes) return base, bits, char def _add_types(): for a in typeinfo.keys(): name = english_lower(a) if isinstance(typeinfo[a], tuple): typeobj = typeinfo[a][-1] # define C-name and insert typenum and typechar references also allTypes[name] = typeobj sctypeDict[name] = typeobj sctypeDict[typeinfo[a][0]] = typeobj sctypeDict[typeinfo[a][1]] = typeobj else: # generic class allTypes[name] = typeinfo[a] _add_types() def _add_aliases(): for a in typeinfo.keys(): name = english_lower(a) if not isinstance(typeinfo[a], tuple): continue typeobj = typeinfo[a][-1] # insert bit-width version for this class (if relevant) base, bit, char = bitname(typeobj) if base[-3:] == 'int' or char[0] in 'ui': continue if base != '': myname = "%s%d" % (base, bit) if (name != 'longdouble' and name != 'clongdouble') or \ myname not in allTypes.keys(): allTypes[myname] = typeobj sctypeDict[myname] = typeobj if base == 'complex': na_name = '%s%d' % (english_capitalize(base), bit//2) elif base == 'bool': na_name = english_capitalize(base) sctypeDict[na_name] = typeobj else: na_name = "%s%d" % (english_capitalize(base), bit) sctypeDict[na_name] = typeobj sctypeNA[na_name] = typeobj sctypeDict[na_name] = typeobj sctypeNA[typeobj] = na_name sctypeNA[typeinfo[a][0]] = na_name if char != '': sctypeDict[char] = typeobj sctypeNA[char] = na_name _add_aliases() # Integers handled so that # The int32, int64 types should agree exactly with # PyArray_INT32, PyArray_INT64 in C # We need to enforce the same checking as is done # in arrayobject.h where the order of getting a # bit-width match is: # long, longlong, int, short, char # for int8, int16, int32, int64, int128 def _add_integer_aliases(): _ctypes = ['LONG', 'LONGLONG', 'INT', 'SHORT', 'BYTE'] for ctype in _ctypes: val = typeinfo[ctype] bits = val[2] charname = 'i%d' % (bits//8,) ucharname = 'u%d' % (bits//8,) intname = 'int%d' % bits UIntname = 'UInt%d' % bits Intname = 'Int%d' % bits uval = typeinfo['U'+ctype] typeobj = val[-1] utypeobj = uval[-1] if intname not in allTypes.keys(): uintname = 'uint%d' % bits allTypes[intname] = typeobj allTypes[uintname] = utypeobj sctypeDict[intname] = typeobj sctypeDict[uintname] = utypeobj sctypeDict[Intname] = typeobj sctypeDict[UIntname] = utypeobj sctypeDict[charname] = typeobj sctypeDict[ucharname] = utypeobj sctypeNA[Intname] = typeobj sctypeNA[UIntname] = utypeobj sctypeNA[charname] = typeobj sctypeNA[ucharname] = utypeobj sctypeNA[typeobj] = Intname sctypeNA[utypeobj] = UIntname sctypeNA[val[0]] = Intname sctypeNA[uval[0]] = UIntname _add_integer_aliases() # We use these later void = allTypes['void'] generic = allTypes['generic'] # # Rework the Python names (so that float and complex and int are consistent # with Python usage) # def _set_up_aliases(): type_pairs = [('complex_', 'cdouble'), ('int0', 'intp'), ('uint0', 'uintp'), ('single', 'float'), ('csingle', 'cfloat'), ('singlecomplex', 'cfloat'), ('float_', 'double'), ('intc', 'int'), ('uintc', 'uint'), ('int_', 'long'), ('uint', 'ulong'), ('cfloat', 'cdouble'), ('longfloat', 'longdouble'), ('clongfloat', 'clongdouble'), ('longcomplex', 'clongdouble'), ('bool_', 'bool'), ('unicode_', 'unicode'), ('object_', 'object')] if sys.version_info[0] >= 3: type_pairs.extend([('bytes_', 'string'), ('str_', 'unicode'), ('string_', 'string')]) else: type_pairs.extend([('str_', 'string'), ('string_', 'string'), ('bytes_', 'string')]) for alias, t in type_pairs: allTypes[alias] = allTypes[t] sctypeDict[alias] = sctypeDict[t] # Remove aliases overriding python types and modules to_remove = ['ulong', 'object', 'unicode', 'int', 'long', 'float', 'complex', 'bool', 'string', 'datetime', 'timedelta'] if sys.version_info[0] >= 3: # Py3K to_remove.append('bytes') to_remove.append('str') to_remove.remove('unicode') to_remove.remove('long') for t in to_remove: try: del allTypes[t] del sctypeDict[t] except KeyError: pass _set_up_aliases() # Now, construct dictionary to lookup character codes from types _sctype2char_dict = {} def _construct_char_code_lookup(): for name in typeinfo.keys(): tup = typeinfo[name] if isinstance(tup, tuple): if tup[0] not in ['p', 'P']: _sctype2char_dict[tup[-1]] = tup[0] _construct_char_code_lookup() sctypes = {'int': [], 'uint':[], 'float':[], 'complex':[], 'others':[bool, object, str, unicode, void]} def _add_array_type(typename, bits): try: t = allTypes['%s%d' % (typename, bits)] except KeyError: pass else: sctypes[typename].append(t) def _set_array_types(): ibytes = [1, 2, 4, 8, 16, 32, 64] fbytes = [2, 4, 8, 10, 12, 16, 32, 64] for bytes in ibytes: bits = 8*bytes _add_array_type('int', bits) _add_array_type('uint', bits) for bytes in fbytes: bits = 8*bytes _add_array_type('float', bits) _add_array_type('complex', 2*bits) _gi = dtype('p') if _gi.type not in sctypes['int']: indx = 0 sz = _gi.itemsize _lst = sctypes['int'] while (indx < len(_lst) and sz >= _lst[indx](0).itemsize): indx += 1 sctypes['int'].insert(indx, _gi.type) sctypes['uint'].insert(indx, dtype('P').type) _set_array_types() genericTypeRank = ['bool', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64', 'int128', 'uint128', 'float16', 'float32', 'float64', 'float80', 'float96', 'float128', 'float256', 'complex32', 'complex64', 'complex128', 'complex160', 'complex192', 'complex256', 'complex512', 'object'] def maximum_sctype(t): """ Return the scalar type of highest precision of the same kind as the input. Parameters ---------- t : dtype or dtype specifier The input data type. This can be a `dtype` object or an object that is convertible to a `dtype`. Returns ------- out : dtype The highest precision data type of the same kind (`dtype.kind`) as `t`. See Also -------- obj2sctype, mintypecode, sctype2char dtype Examples -------- >>> np.maximum_sctype(np.int) >>> np.maximum_sctype(np.uint8) >>> np.maximum_sctype(np.complex) >>> np.maximum_sctype(str) >>> np.maximum_sctype('i2') >>> np.maximum_sctype('f4') """ g = obj2sctype(t) if g is None: return t t = g name = t.__name__ base, bits = _evalname(name) if bits == 0: return t else: return sctypes[base][-1] try: buffer_type = _types.BufferType except AttributeError: # Py3K buffer_type = memoryview _python_types = {int: 'int_', float: 'float_', complex: 'complex_', bool: 'bool_', bytes: 'bytes_', unicode: 'unicode_', buffer_type: 'void', } if sys.version_info[0] >= 3: def _python_type(t): """returns the type corresponding to a certain Python type""" if not isinstance(t, type): t = type(t) return allTypes[_python_types.get(t, 'object_')] else: def _python_type(t): """returns the type corresponding to a certain Python type""" if not isinstance(t, _types.TypeType): t = type(t) return allTypes[_python_types.get(t, 'object_')] def issctype(rep): """ Determines whether the given object represents a scalar data-type. Parameters ---------- rep : any If `rep` is an instance of a scalar dtype, True is returned. If not, False is returned. Returns ------- out : bool Boolean result of check whether `rep` is a scalar dtype. See Also -------- issubsctype, issubdtype, obj2sctype, sctype2char Examples -------- >>> np.issctype(np.int32) True >>> np.issctype(list) False >>> np.issctype(1.1) False Strings are also a scalar type: >>> np.issctype(np.dtype('str')) True """ if not isinstance(rep, (type, dtype)): return False try: res = obj2sctype(rep) if res and res != object_: return True return False except: return False def obj2sctype(rep, default=None): """ Return the scalar dtype or NumPy equivalent of Python type of an object. Parameters ---------- rep : any The object of which the type is returned. default : any, optional If given, this is returned for objects whose types can not be determined. If not given, None is returned for those objects. Returns ------- dtype : dtype or Python type The data type of `rep`. See Also -------- sctype2char, issctype, issubsctype, issubdtype, maximum_sctype Examples -------- >>> np.obj2sctype(np.int32) >>> np.obj2sctype(np.array([1., 2.])) >>> np.obj2sctype(np.array([1.j])) >>> np.obj2sctype(dict) >>> np.obj2sctype('string') >>> np.obj2sctype(1, default=list) """ try: if issubclass(rep, generic): return rep except TypeError: pass if isinstance(rep, dtype): return rep.type if isinstance(rep, type): return _python_type(rep) if isinstance(rep, ndarray): return rep.dtype.type try: res = dtype(rep) except: return default return res.type def issubclass_(arg1, arg2): """ Determine if a class is a subclass of a second class. `issubclass_` is equivalent to the Python built-in ``issubclass``, except that it returns False instead of raising a TypeError is one of the arguments is not a class. Parameters ---------- arg1 : class Input class. True is returned if `arg1` is a subclass of `arg2`. arg2 : class or tuple of classes. Input class. If a tuple of classes, True is returned if `arg1` is a subclass of any of the tuple elements. Returns ------- out : bool Whether `arg1` is a subclass of `arg2` or not. See Also -------- issubsctype, issubdtype, issctype Examples -------- >>> np.issubclass_(np.int32, np.int) True >>> np.issubclass_(np.int32, np.float) False """ try: return issubclass(arg1, arg2) except TypeError: return False def issubsctype(arg1, arg2): """ Determine if the first argument is a subclass of the second argument. Parameters ---------- arg1, arg2 : dtype or dtype specifier Data-types. Returns ------- out : bool The result. See Also -------- issctype, issubdtype,obj2sctype Examples -------- >>> np.issubsctype('S8', str) True >>> np.issubsctype(np.array([1]), np.int) True >>> np.issubsctype(np.array([1]), np.float) False """ return issubclass(obj2sctype(arg1), obj2sctype(arg2)) def issubdtype(arg1, arg2): """ Returns True if first argument is a typecode lower/equal in type hierarchy. Parameters ---------- arg1, arg2 : dtype_like dtype or string representing a typecode. Returns ------- out : bool See Also -------- issubsctype, issubclass_ numpy.core.numerictypes : Overview of numpy type hierarchy. Examples -------- >>> np.issubdtype('S1', str) True >>> np.issubdtype(np.float64, np.float32) False """ if issubclass_(arg2, generic): return issubclass(dtype(arg1).type, arg2) mro = dtype(arg2).type.mro() if len(mro) > 1: val = mro[1] else: val = mro[0] return issubclass(dtype(arg1).type, val) # This dictionary allows look up based on any alias for an array data-type class _typedict(dict): """ Base object for a dictionary for look-up with any alias for an array dtype. Instances of `_typedict` can not be used as dictionaries directly, first they have to be populated. """ def __getitem__(self, obj): return dict.__getitem__(self, obj2sctype(obj)) nbytes = _typedict() _alignment = _typedict() _maxvals = _typedict() _minvals = _typedict() def _construct_lookups(): for name, val in typeinfo.items(): if not isinstance(val, tuple): continue obj = val[-1] nbytes[obj] = val[2] // 8 _alignment[obj] = val[3] if (len(val) > 5): _maxvals[obj] = val[4] _minvals[obj] = val[5] else: _maxvals[obj] = None _minvals[obj] = None _construct_lookups() def sctype2char(sctype): """ Return the string representation of a scalar dtype. Parameters ---------- sctype : scalar dtype or object If a scalar dtype, the corresponding string character is returned. If an object, `sctype2char` tries to infer its scalar type and then return the corresponding string character. Returns ------- typechar : str The string character corresponding to the scalar type. Raises ------ ValueError If `sctype` is an object for which the type can not be inferred. See Also -------- obj2sctype, issctype, issubsctype, mintypecode Examples -------- >>> for sctype in [np.int32, np.float, np.complex, np.string_, np.ndarray]: ... print np.sctype2char(sctype) l d D S O >>> x = np.array([1., 2-1.j]) >>> np.sctype2char(x) 'D' >>> np.sctype2char(list) 'O' """ sctype = obj2sctype(sctype) if sctype is None: raise ValueError("unrecognized type") return _sctype2char_dict[sctype] # Create dictionary of casting functions that wrap sequences # indexed by type or type character cast = _typedict() try: ScalarType = [_types.IntType, _types.FloatType, _types.ComplexType, _types.LongType, _types.BooleanType, _types.StringType, _types.UnicodeType, _types.BufferType] except AttributeError: # Py3K ScalarType = [int, float, complex, int, bool, bytes, str, memoryview] ScalarType.extend(_sctype2char_dict.keys()) ScalarType = tuple(ScalarType) for key in _sctype2char_dict.keys(): cast[key] = lambda x, k=key : array(x, copy=False).astype(k) # Create the typestring lookup dictionary _typestr = _typedict() for key in _sctype2char_dict.keys(): if issubclass(key, allTypes['flexible']): _typestr[key] = _sctype2char_dict[key] else: _typestr[key] = empty((1,), key).dtype.str[1:] # Make sure all typestrings are in sctypeDict for key, val in _typestr.items(): if val not in sctypeDict: sctypeDict[val] = key # Add additional strings to the sctypeDict if sys.version_info[0] >= 3: _toadd = ['int', 'float', 'complex', 'bool', 'object', 'str', 'bytes', 'object', ('a', allTypes['bytes_'])] else: _toadd = ['int', 'float', 'complex', 'bool', 'object', 'string', ('str', allTypes['string_']), 'unicode', 'object', ('a', allTypes['string_'])] for name in _toadd: if isinstance(name, tuple): sctypeDict[name[0]] = name[1] else: sctypeDict[name] = allTypes['%s_' % name] del _toadd, name # Now add the types we've determined to this module for key in allTypes: globals()[key] = allTypes[key] __all__.append(key) del key typecodes = {'Character':'c', 'Integer':'bhilqp', 'UnsignedInteger':'BHILQP', 'Float':'efdg', 'Complex':'FDG', 'AllInteger':'bBhHiIlLqQpP', 'AllFloat':'efdgFDG', 'Datetime': 'Mm', 'All':'?bhilqpBHILQPefdgFDGSUVOMm'} # backwards compatibility --- deprecated name typeDict = sctypeDict typeNA = sctypeNA # b -> boolean # u -> unsigned integer # i -> signed integer # f -> floating point # c -> complex # M -> datetime # m -> timedelta # S -> string # U -> Unicode string # V -> record # O -> Python object _kind_list = ['b', 'u', 'i', 'f', 'c', 'S', 'U', 'V', 'O', 'M', 'm'] __test_types = '?'+typecodes['AllInteger'][:-2]+typecodes['AllFloat']+'O' __len_test_types = len(__test_types) # Keep incrementing until a common type both can be coerced to # is found. Otherwise, return None def _find_common_coerce(a, b): if a > b: return a try: thisind = __test_types.index(a.char) except ValueError: return None return _can_coerce_all([a, b], start=thisind) # Find a data-type that all data-types in a list can be coerced to def _can_coerce_all(dtypelist, start=0): N = len(dtypelist) if N == 0: return None if N == 1: return dtypelist[0] thisind = start while thisind < __len_test_types: newdtype = dtype(__test_types[thisind]) numcoerce = len([x for x in dtypelist if newdtype >= x]) if numcoerce == N: return newdtype thisind += 1 return None def find_common_type(array_types, scalar_types): """ Determine common type following standard coercion rules. Parameters ---------- array_types : sequence A list of dtypes or dtype convertible objects representing arrays. scalar_types : sequence A list of dtypes or dtype convertible objects representing scalars. Returns ------- datatype : dtype The common data type, which is the maximum of `array_types` ignoring `scalar_types`, unless the maximum of `scalar_types` is of a different kind (`dtype.kind`). If the kind is not understood, then None is returned. See Also -------- dtype, common_type, can_cast, mintypecode Examples -------- >>> np.find_common_type([], [np.int64, np.float32, np.complex]) dtype('complex128') >>> np.find_common_type([np.int64, np.float32], []) dtype('float64') The standard casting rules ensure that a scalar cannot up-cast an array unless the scalar is of a fundamentally different kind of data (i.e. under a different hierarchy in the data type hierarchy) then the array: >>> np.find_common_type([np.float32], [np.int64, np.float64]) dtype('float32') Complex is of a different type, so it up-casts the float in the `array_types` argument: >>> np.find_common_type([np.float32], [np.complex]) dtype('complex128') Type specifier strings are convertible to dtypes and can therefore be used instead of dtypes: >>> np.find_common_type(['f4', 'f4', 'i4'], ['c8']) dtype('complex128') """ array_types = [dtype(x) for x in array_types] scalar_types = [dtype(x) for x in scalar_types] maxa = _can_coerce_all(array_types) maxsc = _can_coerce_all(scalar_types) if maxa is None: return maxsc if maxsc is None: return maxa try: index_a = _kind_list.index(maxa.kind) index_sc = _kind_list.index(maxsc.kind) except ValueError: return None if index_sc > index_a: return _find_common_coerce(maxsc, maxa) else: return maxa numpy-1.8.2/numpy/core/shape_base.py0000664000175100017510000001541312370216242020573 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function __all__ = ['atleast_1d', 'atleast_2d', 'atleast_3d', 'vstack', 'hstack'] from . import numeric as _nx from .numeric import array, asanyarray, newaxis def atleast_1d(*arys): """ Convert inputs to arrays with at least one dimension. Scalar inputs are converted to 1-dimensional arrays, whilst higher-dimensional inputs are preserved. Parameters ---------- arys1, arys2, ... : array_like One or more input arrays. Returns ------- ret : ndarray An array, or sequence of arrays, each with ``a.ndim >= 1``. Copies are made only if necessary. See Also -------- atleast_2d, atleast_3d Examples -------- >>> np.atleast_1d(1.0) array([ 1.]) >>> x = np.arange(9.0).reshape(3,3) >>> np.atleast_1d(x) array([[ 0., 1., 2.], [ 3., 4., 5.], [ 6., 7., 8.]]) >>> np.atleast_1d(x) is x True >>> np.atleast_1d(1, [3, 4]) [array([1]), array([3, 4])] """ res = [] for ary in arys: ary = asanyarray(ary) if len(ary.shape) == 0 : result = ary.reshape(1) else : result = ary res.append(result) if len(res) == 1: return res[0] else: return res def atleast_2d(*arys): """ View inputs as arrays with at least two dimensions. Parameters ---------- arys1, arys2, ... : array_like One or more array-like sequences. Non-array inputs are converted to arrays. Arrays that already have two or more dimensions are preserved. Returns ------- res, res2, ... : ndarray An array, or tuple of arrays, each with ``a.ndim >= 2``. Copies are avoided where possible, and views with two or more dimensions are returned. See Also -------- atleast_1d, atleast_3d Examples -------- >>> np.atleast_2d(3.0) array([[ 3.]]) >>> x = np.arange(3.0) >>> np.atleast_2d(x) array([[ 0., 1., 2.]]) >>> np.atleast_2d(x).base is x True >>> np.atleast_2d(1, [1, 2], [[1, 2]]) [array([[1]]), array([[1, 2]]), array([[1, 2]])] """ res = [] for ary in arys: ary = asanyarray(ary) if len(ary.shape) == 0 : result = ary.reshape(1, 1) elif len(ary.shape) == 1 : result = ary[newaxis,:] else : result = ary res.append(result) if len(res) == 1: return res[0] else: return res def atleast_3d(*arys): """ View inputs as arrays with at least three dimensions. Parameters ---------- arys1, arys2, ... : array_like One or more array-like sequences. Non-array inputs are converted to arrays. Arrays that already have three or more dimensions are preserved. Returns ------- res1, res2, ... : ndarray An array, or tuple of arrays, each with ``a.ndim >= 3``. Copies are avoided where possible, and views with three or more dimensions are returned. For example, a 1-D array of shape ``(N,)`` becomes a view of shape ``(1, N, 1)``, and a 2-D array of shape ``(M, N)`` becomes a view of shape ``(M, N, 1)``. See Also -------- atleast_1d, atleast_2d Examples -------- >>> np.atleast_3d(3.0) array([[[ 3.]]]) >>> x = np.arange(3.0) >>> np.atleast_3d(x).shape (1, 3, 1) >>> x = np.arange(12.0).reshape(4,3) >>> np.atleast_3d(x).shape (4, 3, 1) >>> np.atleast_3d(x).base is x True >>> for arr in np.atleast_3d([1, 2], [[1, 2]], [[[1, 2]]]): ... print arr, arr.shape ... [[[1] [2]]] (1, 2, 1) [[[1] [2]]] (1, 2, 1) [[[1 2]]] (1, 1, 2) """ res = [] for ary in arys: ary = asanyarray(ary) if len(ary.shape) == 0: result = ary.reshape(1, 1, 1) elif len(ary.shape) == 1: result = ary[newaxis,:, newaxis] elif len(ary.shape) == 2: result = ary[:,:, newaxis] else: result = ary res.append(result) if len(res) == 1: return res[0] else: return res def vstack(tup): """ Stack arrays in sequence vertically (row wise). Take a sequence of arrays and stack them vertically to make a single array. Rebuild arrays divided by `vsplit`. Parameters ---------- tup : sequence of ndarrays Tuple containing arrays to be stacked. The arrays must have the same shape along all but the first axis. Returns ------- stacked : ndarray The array formed by stacking the given arrays. See Also -------- hstack : Stack arrays in sequence horizontally (column wise). dstack : Stack arrays in sequence depth wise (along third dimension). concatenate : Join a sequence of arrays together. vsplit : Split array into a list of multiple sub-arrays vertically. Notes ----- Equivalent to ``np.concatenate(tup, axis=0)`` if `tup` contains arrays that are at least 2-dimensional. Examples -------- >>> a = np.array([1, 2, 3]) >>> b = np.array([2, 3, 4]) >>> np.vstack((a,b)) array([[1, 2, 3], [2, 3, 4]]) >>> a = np.array([[1], [2], [3]]) >>> b = np.array([[2], [3], [4]]) >>> np.vstack((a,b)) array([[1], [2], [3], [2], [3], [4]]) """ return _nx.concatenate([atleast_2d(_m) for _m in tup], 0) def hstack(tup): """ Stack arrays in sequence horizontally (column wise). Take a sequence of arrays and stack them horizontally to make a single array. Rebuild arrays divided by `hsplit`. Parameters ---------- tup : sequence of ndarrays All arrays must have the same shape along all but the second axis. Returns ------- stacked : ndarray The array formed by stacking the given arrays. See Also -------- vstack : Stack arrays in sequence vertically (row wise). dstack : Stack arrays in sequence depth wise (along third axis). concatenate : Join a sequence of arrays together. hsplit : Split array along second axis. Notes ----- Equivalent to ``np.concatenate(tup, axis=1)`` Examples -------- >>> a = np.array((1,2,3)) >>> b = np.array((2,3,4)) >>> np.hstack((a,b)) array([1, 2, 3, 2, 3, 4]) >>> a = np.array([[1],[2],[3]]) >>> b = np.array([[2],[3],[4]]) >>> np.hstack((a,b)) array([[1, 2], [2, 3], [3, 4]]) """ arrs = [atleast_1d(_m) for _m in tup] # As a special case, dimension 0 of 1-dimensional arrays is "horizontal" if arrs[0].ndim == 1: return _nx.concatenate(arrs, 0) else: return _nx.concatenate(arrs, 1) numpy-1.8.2/numpy/__init__.py0000664000175100017510000001352212370216243017310 0ustar vagrantvagrant00000000000000""" NumPy ===== Provides 1. An array object of arbitrary homogeneous items 2. Fast mathematical operations over arrays 3. Linear Algebra, Fourier Transforms, Random Number Generation How to use the documentation ---------------------------- Documentation is available in two forms: docstrings provided with the code, and a loose standing reference guide, available from `the NumPy homepage `_. We recommend exploring the docstrings using `IPython `_, an advanced Python shell with TAB-completion and introspection capabilities. See below for further instructions. The docstring examples assume that `numpy` has been imported as `np`:: >>> import numpy as np Code snippets are indicated by three greater-than signs:: >>> x = 42 >>> x = x + 1 Use the built-in ``help`` function to view a function's docstring:: >>> help(np.sort) ... # doctest: +SKIP For some objects, ``np.info(obj)`` may provide additional help. This is particularly true if you see the line "Help on ufunc object:" at the top of the help() page. Ufuncs are implemented in C, not Python, for speed. The native Python help() does not know how to view their help, but our np.info() function does. To search for documents containing a keyword, do:: >>> np.lookfor('keyword') ... # doctest: +SKIP General-purpose documents like a glossary and help on the basic concepts of numpy are available under the ``doc`` sub-module:: >>> from numpy import doc >>> help(doc) ... # doctest: +SKIP Available subpackages --------------------- doc Topical documentation on broadcasting, indexing, etc. lib Basic functions used by several sub-packages. random Core Random Tools linalg Core Linear Algebra Tools fft Core FFT routines polynomial Polynomial tools testing Numpy testing tools f2py Fortran to Python Interface Generator. distutils Enhancements to distutils with support for Fortran compilers support and more. Utilities --------- test Run numpy unittests show_config Show numpy build configuration dual Overwrite certain functions with high-performance Scipy tools matlib Make everything matrices. __version__ Numpy version string Viewing documentation using IPython ----------------------------------- Start IPython with the NumPy profile (``ipython -p numpy``), which will import `numpy` under the alias `np`. Then, use the ``cpaste`` command to paste examples into the shell. To see which functions are available in `numpy`, type ``np.`` (where ```` refers to the TAB key), or use ``np.*cos*?`` (where ```` refers to the ENTER key) to narrow down the list. To view the docstring for a function, use ``np.cos?`` (to view the docstring) and ``np.cos??`` (to view the source code). Copies vs. in-place operation ----------------------------- Most of the functions in `numpy` return a copy of the array argument (e.g., `np.sort`). In-place versions of these functions are often available as array methods, i.e. ``x = np.array([1,2,3]); x.sort()``. Exceptions to this rule are documented. """ from __future__ import division, absolute_import, print_function import sys class ModuleDeprecationWarning(DeprecationWarning): """Module deprecation warning. The nose tester turns ordinary Deprecation warnings into test failures. That makes it hard to deprecate whole modules, because they get imported by default. So this is a special Deprecation warning that the nose tester will let pass without making tests fail. """ pass # We first need to detect if we're being called as part of the numpy setup # procedure itself in a reliable manner. try: __NUMPY_SETUP__ except NameError: __NUMPY_SETUP__ = False if __NUMPY_SETUP__: import sys as _sys _sys.stderr.write('Running from numpy source directory.\n') del _sys else: try: from numpy.__config__ import show as show_config 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.""" raise ImportError(msg) from .version import git_revision as __git_revision__ from .version import version as __version__ from ._import_tools import PackageLoader def pkgload(*packages, **options): loader = PackageLoader(infunc=True) return loader(*packages, **options) from . import add_newdocs __all__ = ['add_newdocs', 'ModuleDeprecationWarning'] pkgload.__doc__ = PackageLoader.__call__.__doc__ from .testing import Tester test = Tester().test bench = Tester().bench from . import core from .core import * from . import compat from . import lib from .lib import * from . import linalg from . import fft from . import polynomial from . import random from . import ctypeslib from . import ma from . import matrixlib as _mat from .matrixlib import * from .compat import long # Make these accessible from numpy name-space # but not imported in from numpy import * if sys.version_info[0] >= 3: from builtins import bool, int, float, complex, object, str unicode = str else: from __builtin__ import bool, int, float, complex, object, unicode, str from .core import round, abs, max, min __all__.extend(['__version__', 'pkgload', 'PackageLoader', 'show_config']) __all__.extend(core.__all__) __all__.extend(_mat.__all__) __all__.extend(lib.__all__) __all__.extend(['linalg', 'fft', 'random', 'ctypeslib', 'ma']) # Filter annoying Cython warnings that serve no good purpose. import warnings warnings.filterwarnings("ignore", message="numpy.dtype size changed") warnings.filterwarnings("ignore", message="numpy.ufunc size changed") numpy-1.8.2/numpy/matrixlib/0000775000175100017510000000000012371375430017174 5ustar vagrantvagrant00000000000000numpy-1.8.2/numpy/matrixlib/defmatrix.py0000664000175100017510000007105012370216243021527 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function __all__ = ['matrix', 'bmat', 'mat', 'asmatrix'] import sys import numpy.core.numeric as N from numpy.core.numeric import concatenate, isscalar, binary_repr, identity, asanyarray from numpy.core.numerictypes import issubdtype # make translation table _numchars = '0123456789.-+jeEL' if sys.version_info[0] >= 3: class _NumCharTable: def __getitem__(self, i): if chr(i) in _numchars: return chr(i) else: return None _table = _NumCharTable() def _eval(astr): str_ = astr.translate(_table) if not str_: raise TypeError("Invalid data string supplied: " + astr) else: return eval(str_) else: _table = [None]*256 for k in range(256): _table[k] = chr(k) _table = ''.join(_table) _todelete = [] for k in _table: if k not in _numchars: _todelete.append(k) _todelete = ''.join(_todelete) del k def _eval(astr): str_ = astr.translate(_table, _todelete) if not str_: raise TypeError("Invalid data string supplied: " + astr) else: return eval(str_) def _convert_from_string(data): rows = data.split(';') newdata = [] count = 0 for row in rows: trow = row.split(',') newrow = [] for col in trow: temp = col.split() newrow.extend(map(_eval, temp)) if count == 0: Ncols = len(newrow) elif len(newrow) != Ncols: raise ValueError("Rows not the same size.") count += 1 newdata.append(newrow) return newdata def asmatrix(data, dtype=None): """ Interpret the input as a matrix. Unlike `matrix`, `asmatrix` does not make a copy if the input is already a matrix or an ndarray. Equivalent to ``matrix(data, copy=False)``. Parameters ---------- data : array_like Input data. Returns ------- mat : matrix `data` interpreted as a matrix. Examples -------- >>> x = np.array([[1, 2], [3, 4]]) >>> m = np.asmatrix(x) >>> x[0,0] = 5 >>> m matrix([[5, 2], [3, 4]]) """ return matrix(data, dtype=dtype, copy=False) def matrix_power(M, n): """ Raise a square matrix to the (integer) power `n`. For positive integers `n`, the power is computed by repeated matrix squarings and matrix multiplications. If ``n == 0``, the identity matrix of the same shape as M is returned. If ``n < 0``, the inverse is computed and then raised to the ``abs(n)``. Parameters ---------- M : ndarray or matrix object Matrix to be "powered." Must be square, i.e. ``M.shape == (m, m)``, with `m` a positive integer. n : int The exponent can be any integer or long integer, positive, negative, or zero. Returns ------- M**n : ndarray or matrix object The return value is the same shape and type as `M`; if the exponent is positive or zero then the type of the elements is the same as those of `M`. If the exponent is negative the elements are floating-point. Raises ------ LinAlgError If the matrix is not numerically invertible. See Also -------- matrix Provides an equivalent function as the exponentiation operator (``**``, not ``^``). Examples -------- >>> from numpy import linalg as LA >>> i = np.array([[0, 1], [-1, 0]]) # matrix equiv. of the imaginary unit >>> LA.matrix_power(i, 3) # should = -i array([[ 0, -1], [ 1, 0]]) >>> LA.matrix_power(np.matrix(i), 3) # matrix arg returns matrix matrix([[ 0, -1], [ 1, 0]]) >>> LA.matrix_power(i, 0) array([[1, 0], [0, 1]]) >>> LA.matrix_power(i, -3) # should = 1/(-i) = i, but w/ f.p. elements array([[ 0., 1.], [-1., 0.]]) Somewhat more sophisticated example >>> q = np.zeros((4, 4)) >>> q[0:2, 0:2] = -i >>> q[2:4, 2:4] = i >>> q # one of the three quarternion units not equal to 1 array([[ 0., -1., 0., 0.], [ 1., 0., 0., 0.], [ 0., 0., 0., 1.], [ 0., 0., -1., 0.]]) >>> LA.matrix_power(q, 2) # = -np.eye(4) array([[-1., 0., 0., 0.], [ 0., -1., 0., 0.], [ 0., 0., -1., 0.], [ 0., 0., 0., -1.]]) """ M = asanyarray(M) if len(M.shape) != 2 or M.shape[0] != M.shape[1]: raise ValueError("input must be a square array") if not issubdtype(type(n), int): raise TypeError("exponent must be an integer") from numpy.linalg import inv if n==0: M = M.copy() M[:] = identity(M.shape[0]) return M elif n<0: M = inv(M) n *= -1 result = M if n <= 3: for _ in range(n-1): result=N.dot(result, M) return result # binary decomposition to reduce the number of Matrix # multiplications for n > 3. beta = binary_repr(n) Z, q, t = M, 0, len(beta) while beta[t-q-1] == '0': Z = N.dot(Z, Z) q += 1 result = Z for k in range(q+1, t): Z = N.dot(Z, Z) if beta[t-k-1] == '1': result = N.dot(result, Z) return result class matrix(N.ndarray): """ matrix(data, dtype=None, copy=True) Returns a matrix from an array-like object, or from a string of data. A matrix is a specialized 2-D array that retains its 2-D nature through operations. It has certain special operators, such as ``*`` (matrix multiplication) and ``**`` (matrix power). Parameters ---------- data : array_like or string If `data` is a string, it is interpreted as a matrix with commas or spaces separating columns, and semicolons separating rows. dtype : data-type Data-type of the output matrix. copy : bool If `data` is already an `ndarray`, then this flag determines whether the data is copied (the default), or whether a view is constructed. See Also -------- array Examples -------- >>> a = np.matrix('1 2; 3 4') >>> print a [[1 2] [3 4]] >>> np.matrix([[1, 2], [3, 4]]) matrix([[1, 2], [3, 4]]) """ __array_priority__ = 10.0 def __new__(subtype, data, dtype=None, copy=True): if isinstance(data, matrix): dtype2 = data.dtype if (dtype is None): dtype = dtype2 if (dtype2 == dtype) and (not copy): return data return data.astype(dtype) if isinstance(data, N.ndarray): if dtype is None: intype = data.dtype else: intype = N.dtype(dtype) new = data.view(subtype) if intype != data.dtype: return new.astype(intype) if copy: return new.copy() else: return new if isinstance(data, str): data = _convert_from_string(data) # now convert data to an array arr = N.array(data, dtype=dtype, copy=copy) ndim = arr.ndim shape = arr.shape if (ndim > 2): raise ValueError("matrix must be 2-dimensional") elif ndim == 0: shape = (1, 1) elif ndim == 1: shape = (1, shape[0]) order = False if (ndim == 2) and arr.flags.fortran: order = True if not (order or arr.flags.contiguous): arr = arr.copy() ret = N.ndarray.__new__(subtype, shape, arr.dtype, buffer=arr, order=order) return ret def __array_finalize__(self, obj): self._getitem = False if (isinstance(obj, matrix) and obj._getitem): return ndim = self.ndim if (ndim == 2): return if (ndim > 2): newshape = tuple([x for x in self.shape if x > 1]) ndim = len(newshape) if ndim == 2: self.shape = newshape return elif (ndim > 2): raise ValueError("shape too large to be a matrix.") else: newshape = self.shape if ndim == 0: self.shape = (1, 1) elif ndim == 1: self.shape = (1, newshape[0]) return def __getitem__(self, index): self._getitem = True try: out = N.ndarray.__getitem__(self, index) finally: self._getitem = False if not isinstance(out, N.ndarray): return out if out.ndim == 0: return out[()] if out.ndim == 1: sh = out.shape[0] # Determine when we should have a column array try: n = len(index) except: n = 0 if n > 1 and isscalar(index[1]): out.shape = (sh, 1) else: out.shape = (1, sh) return out def __mul__(self, other): if isinstance(other, (N.ndarray, list, tuple)) : # This promotes 1-D vectors to row vectors return N.dot(self, asmatrix(other)) if isscalar(other) or not hasattr(other, '__rmul__') : return N.dot(self, other) return NotImplemented def __rmul__(self, other): return N.dot(other, self) def __imul__(self, other): self[:] = self * other return self def __pow__(self, other): return matrix_power(self, other) def __ipow__(self, other): self[:] = self ** other return self def __rpow__(self, other): return NotImplemented def __repr__(self): s = repr(self.__array__()).replace('array', 'matrix') # now, 'matrix' has 6 letters, and 'array' 5, so the columns don't # line up anymore. We need to add a space. l = s.splitlines() for i in range(1, len(l)): if l[i]: l[i] = ' ' + l[i] return '\n'.join(l) def __str__(self): return str(self.__array__()) def _align(self, axis): """A convenience function for operations that need to preserve axis orientation. """ if axis is None: return self[0, 0] elif axis==0: return self elif axis==1: return self.transpose() else: raise ValueError("unsupported axis") def _collapse(self, axis): """A convenience function for operations that want to collapse to a scalar like _align, but are using keepdims=True """ if axis is None: return self[0, 0] else: return self # Necessary because base-class tolist expects dimension # reduction by x[0] def tolist(self): """ Return the matrix as a (possibly nested) list. See `ndarray.tolist` for full documentation. See Also -------- ndarray.tolist Examples -------- >>> x = np.matrix(np.arange(12).reshape((3,4))); x matrix([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]]) >>> x.tolist() [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]] """ return self.__array__().tolist() # To preserve orientation of result... def sum(self, axis=None, dtype=None, out=None): """ Returns the sum of the matrix elements, along the given axis. Refer to `numpy.sum` for full documentation. See Also -------- numpy.sum Notes ----- This is the same as `ndarray.sum`, except that where an `ndarray` would be returned, a `matrix` object is returned instead. Examples -------- >>> x = np.matrix([[1, 2], [4, 3]]) >>> x.sum() 10 >>> x.sum(axis=1) matrix([[3], [7]]) >>> x.sum(axis=1, dtype='float') matrix([[ 3.], [ 7.]]) >>> out = np.zeros((1, 2), dtype='float') >>> x.sum(axis=1, dtype='float', out=out) matrix([[ 3.], [ 7.]]) """ return N.ndarray.sum(self, axis, dtype, out, keepdims=True)._collapse(axis) def mean(self, axis=None, dtype=None, out=None): """ Returns the average of the matrix elements along the given axis. Refer to `numpy.mean` for full documentation. See Also -------- numpy.mean Notes ----- Same as `ndarray.mean` except that, where that returns an `ndarray`, this returns a `matrix` object. Examples -------- >>> x = np.matrix(np.arange(12).reshape((3, 4))) >>> x matrix([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]]) >>> x.mean() 5.5 >>> x.mean(0) matrix([[ 4., 5., 6., 7.]]) >>> x.mean(1) matrix([[ 1.5], [ 5.5], [ 9.5]]) """ return N.ndarray.mean(self, axis, dtype, out, keepdims=True)._collapse(axis) def std(self, axis=None, dtype=None, out=None, ddof=0): """ Return the standard deviation of the array elements along the given axis. Refer to `numpy.std` for full documentation. See Also -------- numpy.std Notes ----- This is the same as `ndarray.std`, except that where an `ndarray` would be returned, a `matrix` object is returned instead. Examples -------- >>> x = np.matrix(np.arange(12).reshape((3, 4))) >>> x matrix([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]]) >>> x.std() 3.4520525295346629 >>> x.std(0) matrix([[ 3.26598632, 3.26598632, 3.26598632, 3.26598632]]) >>> x.std(1) matrix([[ 1.11803399], [ 1.11803399], [ 1.11803399]]) """ return N.ndarray.std(self, axis, dtype, out, ddof, keepdims=True)._collapse(axis) def var(self, axis=None, dtype=None, out=None, ddof=0): """ Returns the variance of the matrix elements, along the given axis. Refer to `numpy.var` for full documentation. See Also -------- numpy.var Notes ----- This is the same as `ndarray.var`, except that where an `ndarray` would be returned, a `matrix` object is returned instead. Examples -------- >>> x = np.matrix(np.arange(12).reshape((3, 4))) >>> x matrix([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]]) >>> x.var() 11.916666666666666 >>> x.var(0) matrix([[ 10.66666667, 10.66666667, 10.66666667, 10.66666667]]) >>> x.var(1) matrix([[ 1.25], [ 1.25], [ 1.25]]) """ return N.ndarray.var(self, axis, dtype, out, ddof, keepdims=True)._collapse(axis) def prod(self, axis=None, dtype=None, out=None): """ Return the product of the array elements over the given axis. Refer to `prod` for full documentation. See Also -------- prod, ndarray.prod Notes ----- Same as `ndarray.prod`, except, where that returns an `ndarray`, this returns a `matrix` object instead. Examples -------- >>> x = np.matrix(np.arange(12).reshape((3,4))); x matrix([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]]) >>> x.prod() 0 >>> x.prod(0) matrix([[ 0, 45, 120, 231]]) >>> x.prod(1) matrix([[ 0], [ 840], [7920]]) """ return N.ndarray.prod(self, axis, dtype, out, keepdims=True)._collapse(axis) def any(self, axis=None, out=None): """ Test whether any array element along a given axis evaluates to True. Refer to `numpy.any` for full documentation. Parameters ---------- axis : int, optional Axis along which logical OR is performed out : ndarray, optional Output to existing array instead of creating new one, must have same shape as expected output Returns ------- any : bool, ndarray Returns a single bool if `axis` is ``None``; otherwise, returns `ndarray` """ return N.ndarray.any(self, axis, out, keepdims=True)._collapse(axis) def all(self, axis=None, out=None): """ Test whether all matrix elements along a given axis evaluate to True. Parameters ---------- See `numpy.all` for complete descriptions See Also -------- numpy.all Notes ----- This is the same as `ndarray.all`, but it returns a `matrix` object. Examples -------- >>> x = np.matrix(np.arange(12).reshape((3,4))); x matrix([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]]) >>> y = x[0]; y matrix([[0, 1, 2, 3]]) >>> (x == y) matrix([[ True, True, True, True], [False, False, False, False], [False, False, False, False]], dtype=bool) >>> (x == y).all() False >>> (x == y).all(0) matrix([[False, False, False, False]], dtype=bool) >>> (x == y).all(1) matrix([[ True], [False], [False]], dtype=bool) """ return N.ndarray.all(self, axis, out, keepdims=True)._collapse(axis) def max(self, axis=None, out=None): """ Return the maximum value along an axis. Parameters ---------- See `amax` for complete descriptions See Also -------- amax, ndarray.max Notes ----- This is the same as `ndarray.max`, but returns a `matrix` object where `ndarray.max` would return an ndarray. Examples -------- >>> x = np.matrix(np.arange(12).reshape((3,4))); x matrix([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]]) >>> x.max() 11 >>> x.max(0) matrix([[ 8, 9, 10, 11]]) >>> x.max(1) matrix([[ 3], [ 7], [11]]) """ return N.ndarray.max(self, axis, out, keepdims=True)._collapse(axis) def argmax(self, axis=None, out=None): """ Indices of the maximum values along an axis. Parameters ---------- See `numpy.argmax` for complete descriptions See Also -------- numpy.argmax Notes ----- This is the same as `ndarray.argmax`, but returns a `matrix` object where `ndarray.argmax` would return an `ndarray`. Examples -------- >>> x = np.matrix(np.arange(12).reshape((3,4))); x matrix([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]]) >>> x.argmax() 11 >>> x.argmax(0) matrix([[2, 2, 2, 2]]) >>> x.argmax(1) matrix([[3], [3], [3]]) """ return N.ndarray.argmax(self, axis, out)._align(axis) def min(self, axis=None, out=None): """ Return the minimum value along an axis. Parameters ---------- See `amin` for complete descriptions. See Also -------- amin, ndarray.min Notes ----- This is the same as `ndarray.min`, but returns a `matrix` object where `ndarray.min` would return an ndarray. Examples -------- >>> x = -np.matrix(np.arange(12).reshape((3,4))); x matrix([[ 0, -1, -2, -3], [ -4, -5, -6, -7], [ -8, -9, -10, -11]]) >>> x.min() -11 >>> x.min(0) matrix([[ -8, -9, -10, -11]]) >>> x.min(1) matrix([[ -3], [ -7], [-11]]) """ return N.ndarray.min(self, axis, out, keepdims=True)._collapse(axis) def argmin(self, axis=None, out=None): """ Return the indices of the minimum values along an axis. Parameters ---------- See `numpy.argmin` for complete descriptions. See Also -------- numpy.argmin Notes ----- This is the same as `ndarray.argmin`, but returns a `matrix` object where `ndarray.argmin` would return an `ndarray`. Examples -------- >>> x = -np.matrix(np.arange(12).reshape((3,4))); x matrix([[ 0, -1, -2, -3], [ -4, -5, -6, -7], [ -8, -9, -10, -11]]) >>> x.argmin() 11 >>> x.argmin(0) matrix([[2, 2, 2, 2]]) >>> x.argmin(1) matrix([[3], [3], [3]]) """ return N.ndarray.argmin(self, axis, out)._align(axis) def ptp(self, axis=None, out=None): """ Peak-to-peak (maximum - minimum) value along the given axis. Refer to `numpy.ptp` for full documentation. See Also -------- numpy.ptp Notes ----- Same as `ndarray.ptp`, except, where that would return an `ndarray` object, this returns a `matrix` object. Examples -------- >>> x = np.matrix(np.arange(12).reshape((3,4))); x matrix([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]]) >>> x.ptp() 11 >>> x.ptp(0) matrix([[8, 8, 8, 8]]) >>> x.ptp(1) matrix([[3], [3], [3]]) """ return N.ndarray.ptp(self, axis, out)._align(axis) def getI(self): """ Returns the (multiplicative) inverse of invertible `self`. Parameters ---------- None Returns ------- ret : matrix object If `self` is non-singular, `ret` is such that ``ret * self`` == ``self * ret`` == ``np.matrix(np.eye(self[0,:].size)`` all return ``True``. Raises ------ numpy.linalg.LinAlgError: Singular matrix If `self` is singular. See Also -------- linalg.inv Examples -------- >>> m = np.matrix('[1, 2; 3, 4]'); m matrix([[1, 2], [3, 4]]) >>> m.getI() matrix([[-2. , 1. ], [ 1.5, -0.5]]) >>> m.getI() * m matrix([[ 1., 0.], [ 0., 1.]]) """ M, N = self.shape if M == N: from numpy.dual import inv as func else: from numpy.dual import pinv as func return asmatrix(func(self)) def getA(self): """ Return `self` as an `ndarray` object. Equivalent to ``np.asarray(self)``. Parameters ---------- None Returns ------- ret : ndarray `self` as an `ndarray` Examples -------- >>> x = np.matrix(np.arange(12).reshape((3,4))); x matrix([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]]) >>> x.getA() array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]]) """ return self.__array__() def getA1(self): """ Return `self` as a flattened `ndarray`. Equivalent to ``np.asarray(x).ravel()`` Parameters ---------- None Returns ------- ret : ndarray `self`, 1-D, as an `ndarray` Examples -------- >>> x = np.matrix(np.arange(12).reshape((3,4))); x matrix([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]]) >>> x.getA1() array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]) """ return self.__array__().ravel() def getT(self): """ Returns the transpose of the matrix. Does *not* conjugate! For the complex conjugate transpose, use `getH`. Parameters ---------- None Returns ------- ret : matrix object The (non-conjugated) transpose of the matrix. See Also -------- transpose, getH Examples -------- >>> m = np.matrix('[1, 2; 3, 4]') >>> m matrix([[1, 2], [3, 4]]) >>> m.getT() matrix([[1, 3], [2, 4]]) """ return self.transpose() def getH(self): """ Returns the (complex) conjugate transpose of `self`. Equivalent to ``np.transpose(self)`` if `self` is real-valued. Parameters ---------- None Returns ------- ret : matrix object complex conjugate transpose of `self` Examples -------- >>> x = np.matrix(np.arange(12).reshape((3,4))) >>> z = x - 1j*x; z matrix([[ 0. +0.j, 1. -1.j, 2. -2.j, 3. -3.j], [ 4. -4.j, 5. -5.j, 6. -6.j, 7. -7.j], [ 8. -8.j, 9. -9.j, 10.-10.j, 11.-11.j]]) >>> z.getH() matrix([[ 0. +0.j, 4. +4.j, 8. +8.j], [ 1. +1.j, 5. +5.j, 9. +9.j], [ 2. +2.j, 6. +6.j, 10.+10.j], [ 3. +3.j, 7. +7.j, 11.+11.j]]) """ if issubclass(self.dtype.type, N.complexfloating): return self.transpose().conjugate() else: return self.transpose() T = property(getT, None, doc="transpose") A = property(getA, None, doc="base array") A1 = property(getA1, None, doc="1-d base array") H = property(getH, None, doc="hermitian (conjugate) transpose") I = property(getI, None, doc="inverse") def _from_string(str, gdict, ldict): rows = str.split(';') rowtup = [] for row in rows: trow = row.split(',') newrow = [] for x in trow: newrow.extend(x.split()) trow = newrow coltup = [] for col in trow: col = col.strip() try: thismat = ldict[col] except KeyError: try: thismat = gdict[col] except KeyError: raise KeyError("%s not found" % (col,)) coltup.append(thismat) rowtup.append(concatenate(coltup, axis=-1)) return concatenate(rowtup, axis=0) def bmat(obj, ldict=None, gdict=None): """ Build a matrix object from a string, nested sequence, or array. Parameters ---------- obj : str or array_like Input data. Names of variables in the current scope may be referenced, even if `obj` is a string. Returns ------- out : matrix Returns a matrix object, which is a specialized 2-D array. See Also -------- matrix Examples -------- >>> A = np.mat('1 1; 1 1') >>> B = np.mat('2 2; 2 2') >>> C = np.mat('3 4; 5 6') >>> D = np.mat('7 8; 9 0') All the following expressions construct the same block matrix: >>> np.bmat([[A, B], [C, D]]) matrix([[1, 1, 2, 2], [1, 1, 2, 2], [3, 4, 7, 8], [5, 6, 9, 0]]) >>> np.bmat(np.r_[np.c_[A, B], np.c_[C, D]]) matrix([[1, 1, 2, 2], [1, 1, 2, 2], [3, 4, 7, 8], [5, 6, 9, 0]]) >>> np.bmat('A,B; C,D') matrix([[1, 1, 2, 2], [1, 1, 2, 2], [3, 4, 7, 8], [5, 6, 9, 0]]) """ if isinstance(obj, str): if gdict is None: # get previous frame frame = sys._getframe().f_back glob_dict = frame.f_globals loc_dict = frame.f_locals else: glob_dict = gdict loc_dict = ldict return matrix(_from_string(obj, glob_dict, loc_dict)) if isinstance(obj, (tuple, list)): # [[A,B],[C,D]] arr_rows = [] for row in obj: if isinstance(row, N.ndarray): # not 2-d return matrix(concatenate(obj, axis=-1)) else: arr_rows.append(concatenate(row, axis=-1)) return matrix(concatenate(arr_rows, axis=0)) if isinstance(obj, N.ndarray): return matrix(obj) mat = asmatrix numpy-1.8.2/numpy/matrixlib/setup.py0000664000175100017510000000070012370216242020675 0ustar vagrantvagrant00000000000000#!/usr/bin/env python from __future__ import division, print_function import os def configuration(parent_package='', top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('matrixlib', parent_package, top_path) config.add_data_dir('tests') return config if __name__ == "__main__": from numpy.distutils.core import setup config = configuration(top_path='').todict() setup(**config) numpy-1.8.2/numpy/matrixlib/tests/0000775000175100017510000000000012371375430020336 5ustar vagrantvagrant00000000000000numpy-1.8.2/numpy/matrixlib/tests/test_multiarray.py0000664000175100017510000000111612370216242024131 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function import numpy as np from numpy.testing import * class TestView(TestCase): def test_type(self): x = np.array([1, 2, 3]) assert_(isinstance(x.view(np.matrix), np.matrix)) def test_keywords(self): x = np.array([(1, 2)], dtype=[('a', np.int8), ('b', np.int8)]) # We must be specific about the endianness here: y = x.view(dtype='= mA)) assert_(all(mB >= mB)) assert_(not any(mB > mB)) assert_(all(mA == mA)) assert_(not any(mA == mB)) assert_(all(mB != mA)) assert_(not all(abs(mA) > 0)) assert_(all(abs(mB > 0))) def test_asmatrix(self): A = arange(100).reshape(10, 10) mA = asmatrix(A) A[0, 0] = -10 assert_(A[0, 0] == mA[0, 0]) def test_noaxis(self): A = matrix([[1, 0], [0, 1]]) assert_(A.sum() == matrix(2)) assert_(A.mean() == matrix(0.5)) def test_repr(self): A = matrix([[1, 0], [0, 1]]) assert_(repr(A) == "matrix([[1, 0],\n [0, 1]])") class TestCasting(TestCase): def test_basic(self): A = arange(100).reshape(10, 10) mA = matrix(A) mB = mA.copy() O = ones((10, 10), float64) * 0.1 mB = mB + O assert_(mB.dtype.type == float64) assert_(all(mA != mB)) assert_(all(mB == mA+0.1)) mC = mA.copy() O = ones((10, 10), complex128) mC = mC * O assert_(mC.dtype.type == complex128) assert_(all(mA != mB)) class TestAlgebra(TestCase): def test_basic(self): import numpy.linalg as linalg A = array([[1., 2.], [3., 4.]]) mA = matrix(A) B = identity(2) for i in range(6): assert_(allclose((mA ** i).A, B)) B = dot(B, A) Ainv = linalg.inv(A) B = identity(2) for i in range(6): assert_(allclose((mA ** -i).A, B)) B = dot(B, Ainv) assert_(allclose((mA * mA).A, dot(A, A))) assert_(allclose((mA + mA).A, (A + A))) assert_(allclose((3*mA).A, (3*A))) mA2 = matrix(A) mA2 *= 3 assert_(allclose(mA2.A, 3*A)) def test_pow(self): """Test raising a matrix to an integer power works as expected.""" m = matrix("1. 2.; 3. 4.") m2 = m.copy() m2 **= 2 mi = m.copy() mi **= -1 m4 = m2.copy() m4 **= 2 assert_array_almost_equal(m2, m**2) assert_array_almost_equal(m4, np.dot(m2, m2)) assert_array_almost_equal(np.dot(mi, m), np.eye(2)) def test_notimplemented(self): '''Check that 'not implemented' operations produce a failure.''' A = matrix([[1., 2.], [3., 4.]]) # __rpow__ try: 1.0**A except TypeError: pass else: self.fail("matrix.__rpow__ doesn't raise a TypeError") # __mul__ with something not a list, ndarray, tuple, or scalar try: A*object() except TypeError: pass else: self.fail("matrix.__mul__ with non-numeric object doesn't raise" "a TypeError") class TestMatrixReturn(TestCase): def test_instance_methods(self): a = matrix([1.0], dtype='f8') methodargs = { 'astype': ('intc',), 'clip': (0.0, 1.0), 'compress': ([1],), 'repeat': (1,), 'reshape': (1,), 'swapaxes': (0, 0), 'dot': np.array([1.0]), } excluded_methods = [ 'argmin', 'choose', 'dump', 'dumps', 'fill', 'getfield', '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', 'prod', 'std', 'ctypes', 'itemset', 'setasflat' ] for attrib in dir(a): if attrib.startswith('_') or attrib in excluded_methods: continue f = getattr(a, attrib) if isinstance(f, collections.Callable): # reset contents of a a.astype('f8') a.fill(1.0) if attrib in methodargs: args = methodargs[attrib] else: args = () b = f(*args) assert_(type(b) is matrix, "%s" % attrib) assert_(type(a.real) is matrix) assert_(type(a.imag) is matrix) c, d = matrix([0.0]).nonzero() assert_(type(c) is matrix) assert_(type(d) is matrix) class TestIndexing(TestCase): def test_basic(self): x = asmatrix(zeros((3, 2), float)) y = zeros((3, 1), float) y[:, 0] = [0.8, 0.2, 0.3] x[:, 1] = y>0.5 assert_equal(x, [[0, 1], [0, 0], [0, 0]]) class TestNewScalarIndexing(TestCase): def setUp(self): self.a = matrix([[1, 2], [3, 4]]) def test_dimesions(self): a = self.a x = a[0] assert_equal(x.ndim, 2) def test_array_from_matrix_list(self): a = self.a x = array([a, a]) assert_equal(x.shape, [2, 2, 2]) def test_array_to_list(self): a = self.a assert_equal(a.tolist(), [[1, 2], [3, 4]]) def test_fancy_indexing(self): a = self.a x = a[1, [0, 1, 0]] assert_(isinstance(x, matrix)) assert_equal(x, matrix([[3, 4, 3]])) x = a[[1, 0]] assert_(isinstance(x, matrix)) assert_equal(x, matrix([[3, 4], [1, 2]])) x = a[[[1], [0]], [[1, 0], [0, 1]]] assert_(isinstance(x, matrix)) assert_equal(x, matrix([[4, 3], [1, 2]])) def test_matrix_element(self): x = matrix([[1, 2, 3], [4, 5, 6]]) assert_equal(x[0][0], matrix([[1, 2, 3]])) assert_equal(x[0][0].shape, (1, 3)) assert_equal(x[0].shape, (1, 3)) assert_equal(x[:, 0].shape, (2, 1)) x = matrix(0) assert_equal(x[0, 0], 0) assert_equal(x[0], 0) assert_equal(x[:, 0].shape, x.shape) def test_scalar_indexing(self): x = asmatrix(zeros((3, 2), float)) assert_equal(x[0, 0], x[0][0]) def test_row_column_indexing(self): x = asmatrix(np.eye(2)) assert_array_equal(x[0,:], [[1, 0]]) assert_array_equal(x[1,:], [[0, 1]]) assert_array_equal(x[:, 0], [[1], [0]]) assert_array_equal(x[:, 1], [[0], [1]]) def test_boolean_indexing(self): A = arange(6) A.shape = (3, 2) x = asmatrix(A) assert_array_equal(x[:, array([True, False])], x[:, 0]) assert_array_equal(x[array([True, False, False]),:], x[0,:]) def test_list_indexing(self): A = arange(6) A.shape = (3, 2) x = asmatrix(A) assert_array_equal(x[:, [1, 0]], x[:, ::-1]) assert_array_equal(x[[2, 1, 0],:], x[::-1,:]) class TestPower(TestCase): def test_returntype(self): a = array([[0, 1], [0, 0]]) assert_(type(matrix_power(a, 2)) is ndarray) a = mat(a) assert_(type(matrix_power(a, 2)) is matrix) def test_list(self): assert_array_equal(matrix_power([[0, 1], [0, 0]], 2), [[0, 0], [0, 0]]) if __name__ == "__main__": run_module_suite() numpy-1.8.2/numpy/matrixlib/tests/test_regression.py0000664000175100017510000000204412370216242024121 0ustar vagrantvagrant00000000000000from __future__ import division, absolute_import, print_function from numpy.testing import * import numpy as np rlevel = 1 class TestRegression(TestCase): def test_kron_matrix(self,level=rlevel): """Ticket #71""" x = np.matrix('[1 0; 1 0]') assert_equal(type(np.kron(x, x)), type(x)) def test_matrix_properties(self,level=rlevel): """Ticket #125""" a = np.matrix([1.0], dtype=float) assert_(type(a.real) is np.matrix) assert_(type(a.imag) is np.matrix) c, d = np.matrix([0.0]).nonzero() assert_(type(c) is np.matrix) assert_(type(d) is np.matrix) def test_matrix_multiply_by_1d_vector(self, level=rlevel) : """Ticket #473""" def mul() : np.mat(np.eye(2))*np.ones(2) self.assertRaises(ValueError, mul) def test_matrix_std_argmax(self,level=rlevel): """Ticket #83""" x = np.asmatrix(np.random.uniform(0, 1, (3, 3))) self.assertEqual(x.std().shape, ()) self.assertEqual(x.argmax().shape, ()) numpy-1.8.2/numpy/matrixlib/__init__.py0000664000175100017510000000041512370216242021277 0ustar vagrantvagrant00000000000000"""Sub-package containing the matrix class and related functions. """ from __future__ import division, absolute_import, print_function from .defmatrix import * __all__ = defmatrix.__all__ from numpy.testing import Tester test = Tester().test bench = Tester().bench numpy-1.8.2/numpy/compat/0000775000175100017510000000000012371375427016472 5ustar vagrantvagrant00000000000000numpy-1.8.2/numpy/compat/_inspect.py0000664000175100017510000002170112370216242020635 0ustar vagrantvagrant00000000000000"""Subset of inspect module from upstream python We use this instead of upstream because upstream inspect is slow to import, and significanly contributes to numpy import times. Importing this copy has almost no overhead. """ from __future__ import division, absolute_import, print_function import types __all__ = ['getargspec', 'formatargspec'] # ----------------------------------------------------------- type-checking def ismethod(object): """Return true if the object is an instance method. Instance method objects provide these attributes: __doc__ documentation string __name__ name with which this method was defined im_class class object in which this method belongs im_func function object containing implementation of method im_self instance to which this method is bound, or None""" return isinstance(object, types.MethodType) def isfunction(object): """Return true if the object is a user-defined function. Function objects provide these attributes: __doc__ documentation string __name__ name with which this function was defined func_code code object containing compiled function bytecode func_defaults tuple of any default values for arguments func_doc (same as __doc__) func_globals global namespace in which this function was defined func_name (same as __name__)""" return isinstance(object, types.FunctionType) def iscode(object): """Return true if the object is a code object. Code objects provide these attributes: co_argcount number of arguments (not including * or ** args) co_code string of raw compiled bytecode co_consts tuple of constants used in the bytecode co_filename name of file in which this code object was created co_firstlineno number of first line in Python source code co_flags bitmap: 1=optimized | 2=newlocals | 4=*arg | 8=**arg co_lnotab encoded mapping of line numbers to bytecode indices co_name name with which this code object was defined co_names tuple of names of local variables co_nlocals number of local variables co_stacksize virtual machine stack space required co_varnames tuple of names of arguments and local variables""" return isinstance(object, types.CodeType) # ------------------------------------------------ argument list extraction # These constants are from Python's compile.h. CO_OPTIMIZED, CO_NEWLOCALS, CO_VARARGS, CO_VARKEYWORDS = 1, 2, 4, 8 def getargs(co): """Get information about the arguments accepted by a code object. Three things are returned: (args, varargs, varkw), where 'args' is a list of argument names (possibly containing nested lists), and 'varargs' and 'varkw' are the names of the * and ** arguments or None.""" if not iscode(co): raise TypeError('arg is not a code object') code = co.co_code nargs = co.co_argcount names = co.co_varnames args = list(names[:nargs]) step = 0 # The following acrobatics are for anonymous (tuple) arguments. for i in range(nargs): if args[i][:1] in ['', '.']: stack, remain, count = [], [], [] while step < len(code): op = ord(code[step]) step = step + 1 if op >= dis.HAVE_ARGUMENT: opname = dis.opname[op] value = ord(code[step]) + ord(code[step+1])*256 step = step + 2 if opname in ['UNPACK_TUPLE', 'UNPACK_SEQUENCE']: remain.append(value) count.append(value) elif opname == 'STORE_FAST': stack.append(names[value]) # Special case for sublists of length 1: def foo((bar)) # doesn't generate the UNPACK_TUPLE bytecode, so if # `remain` is empty here, we have such a sublist. if not remain: stack[0] = [stack[0]] break else: remain[-1] = remain[-1] - 1 while remain[-1] == 0: remain.pop() size = count.pop() stack[-size:] = [stack[-size:]] if not remain: break remain[-1] = remain[-1] - 1 if not remain: break args[i] = stack[0] varargs = None if co.co_flags & CO_VARARGS: varargs = co.co_varnames[nargs] nargs = nargs + 1 varkw = None if co.co_flags & CO_VARKEYWORDS: varkw = co.co_varnames[nargs] return args, varargs, varkw def getargspec(func): """Get the names and default values of a function's arguments. A tuple of four things is returned: (args, varargs, varkw, defaults). 'args' is a list of the argument names (it may contain nested lists). 'varargs' and 'varkw' are the names of the * and ** arguments or None. 'defaults' is an n-tuple of the default values of the last n arguments. """ if ismethod(func): func = func.__func__ if not isfunction(func): raise TypeError('arg is not a Python function') args, varargs, varkw = getargs(func.__code__) return args, varargs, varkw, func.__defaults__ def getargvalues(frame): """Get information about arguments passed into a particular frame. A tuple of four things is returned: (args, varargs, varkw, locals). 'args' is a list of the argument names (it may contain nested lists). 'varargs' and 'varkw' are the names of the * and ** arguments or None. 'locals' is the locals dictionary of the given frame.""" args, varargs, varkw = getargs(frame.f_code) return args, varargs, varkw, frame.f_locals def joinseq(seq): if len(seq) == 1: return '(' + seq[0] + ',)' else: return '(' + ', '.join(seq) + ')' def strseq(object, convert, join=joinseq): """Recursively walk a sequence, stringifying each element.""" if type(object) in [list, tuple]: return join([strseq(_o, convert, join) for _o in object]) else: return convert(object) def formatargspec(args, varargs=None, varkw=None, defaults=None, formatarg=str, formatvarargs=lambda name: '*' + name, formatvarkw=lambda name: '**' + name, formatvalue=lambda value: '=' + repr(value), join=joinseq): """Format an argument spec from the 4 values returned by getargspec. The first four arguments are (args, varargs, varkw, defaults). The other four arguments are the corresponding optional formatting functions that are called to turn names and values into strings. The ninth argument is an optional function to format the sequence of arguments.""" specs = [] if defaults: firstdefault = len(args) - len(defaults) for i in range(len(args)): spec = strseq(args[i], formatarg, join) if defaults and i >= firstdefault: spec = spec + formatvalue(defaults[i - firstdefault]) specs.append(spec) if varargs is not None: specs.append(formatvarargs(varargs)) if varkw is not None: specs.append(formatvarkw(varkw)) return '(' + ', '.join(specs) + ')' def formatargvalues(args, varargs, varkw, locals, formatarg=str, formatvarargs=lambda name: '*' + name, formatvarkw=lambda name: '**' + name, formatvalue=lambda value: '=' + repr(value), join=joinseq): """Format an argument spec from the 4 values returned by getargvalues. The first four arguments are (args, varargs, varkw, locals). The next four arguments are the corresponding optional formatting functions that are called to turn names and values into strings. The ninth argument is an optional function to format the sequence of arguments.""" def convert(name, locals=locals, formatarg=formatarg, formatvalue=formatvalue): return formatarg(name) + formatvalue(locals[name]) specs = [] for i in range(len(args)): specs.append(strseq(args[i], convert, join)) if varargs: specs.append(formatvarargs(varargs) + formatvalue(locals[varargs])) if varkw: specs.append(formatvarkw(varkw) + formatvalue(locals[varkw])) return '(' + string.join(specs, ', ') + ')' if __name__ == '__main__': import inspect def foo(x, y, z=None): return None print(inspect.getargs(foo.__code__)) print(getargs(foo.__code__)) print(inspect.getargspec(foo)) print(getargspec(foo)) print(inspect.formatargspec(*inspect.getargspec(foo))) print(formatargspec(*getargspec(foo))) numpy-1.8.2/numpy/compat/py3k.py0000664000175100017510000000370612370216243017725 0ustar vagrantvagrant00000000000000""" Python 3 compatibility tools. """ from __future__ import division, absolute_import, print_function __all__ = ['bytes', 'asbytes', 'isfileobj', 'getexception', 'strchar', 'unicode', 'asunicode', 'asbytes_nested', 'asunicode_nested', 'asstr', 'open_latin1', 'long', 'basestring', 'sixu', 'integer_types'] import sys if sys.version_info[0] >= 3: import io long = int integer_types = (int,) basestring = str unicode = str bytes = bytes def asunicode(s): if isinstance(s, bytes): return s.decode('latin1') return str(s) def asbytes(s): if isinstance(s, bytes): return s return str(s).encode('latin1') def asstr(s): if isinstance(s, bytes): return s.decode('latin1') return str(s) def isfileobj(f): return isinstance(f, (io.FileIO, io.BufferedReader)) def open_latin1(filename, mode='r'): return open(filename, mode=mode, encoding='iso-8859-1') def sixu(s): return s strchar = 'U' else: bytes = str long = long basestring = basestring unicode = unicode integer_types = (int, long) asbytes = str asstr = str strchar = 'S' def isfileobj(f): return isinstance(f, file) def asunicode(s): if isinstance(s, unicode): return s return str(s).decode('ascii') def open_latin1(filename, mode='r'): return open(filename, mode=mode) def sixu(s): return unicode(s, 'unicode_escape') def getexception(): return sys.exc_info()[1] def asbytes_nested(x): if hasattr(x, '__iter__') and not isinstance(x, (bytes, unicode)): return [asbytes_nested(y) for y in x] else: return asbytes(x) def asunicode_nested(x): if hasattr(x, '__iter__') and not isinstance(x, (bytes, unicode)): return [asunicode_nested(y) for y in x] else: return asunicode(x) numpy-1.8.2/numpy/compat/setup.py0000664000175100017510000000057012370216242020172 0ustar vagrantvagrant00000000000000#!/usr/bin/env python from __future__ import division, print_function def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('compat', parent_package, top_path) return config if __name__ == '__main__': from numpy.distutils.core import setup setup(configuration=configuration) numpy-1.8.2/numpy/compat/__init__.py0000664000175100017510000000076212370216242020574 0ustar vagrantvagrant00000000000000""" Compatibility module. This module contains duplicated code from Python itself or 3rd party extensions, which may be included for the following reasons: * compatibility * we may only need a small subset of the copied library/module """ from __future__ import division, absolute_import, print_function from . import _inspect from . import py3k from ._inspect import getargspec, formatargspec from .py3k import * __all__ = [] __all__.extend(_inspect.__all__) __all__.extend(py3k.__all__) numpy-1.8.2/numpy/version.py0000664000175100017510000000034412371375427017247 0ustar vagrantvagrant00000000000000 # THIS FILE IS GENERATED FROM NUMPY SETUP.PY short_version = '1.8.2' version = '1.8.2' full_version = '1.8.2' git_revision = '4563730a2d036307f1b67b2856d749aabdd8d546' release = True if not release: version = full_version numpy-1.8.2/setup.py0000775000175100017510000001706112371375346015561 0ustar vagrantvagrant00000000000000#!/usr/bin/env python """NumPy: array processing for numbers, strings, records, and objects. NumPy is a general-purpose array-processing package designed to efficiently manipulate large multi-dimensional arrays of arbitrary records without sacrificing too much speed for small multi-dimensional arrays. NumPy is built on the Numeric code base and adds features introduced by numarray as well as an extended C-API and the ability to create arrays of arbitrary type which also makes NumPy suitable for interfacing with general-purpose data-base applications. There are also basic facilities for discrete fourier transform, basic linear algebra and random number generation. """ from __future__ import division, print_function DOCLINES = __doc__.split("\n") import os import sys import subprocess if sys.version_info[:2] < (2, 6) or (3, 0) <= sys.version_info[0:2] < (3, 2): raise RuntimeError("Python version 2.6, 2.7 or >= 3.2 required.") if sys.version_info[0] >= 3: import builtins else: import __builtin__ as builtins CLASSIFIERS = """\ Development Status :: 5 - Production/Stable Intended Audience :: Science/Research Intended Audience :: Developers License :: OSI Approved Programming Language :: C Programming Language :: Python Programming Language :: Python :: 3 Topic :: Software Development Topic :: Scientific/Engineering Operating System :: Microsoft :: Windows Operating System :: POSIX Operating System :: Unix Operating System :: MacOS """ MAJOR = 1 MINOR = 8 MICRO = 2 ISRELEASED = True VERSION = '%d.%d.%d' % (MAJOR, MINOR, MICRO) # Return the git revision as a string def git_version(): def _minimal_ext_cmd(cmd): # construct minimal environment env = {} for k in ['SYSTEMROOT', 'PATH']: v = os.environ.get(k) if v is not None: env[k] = v # LANGUAGE is used on win32 env['LANGUAGE'] = 'C' env['LANG'] = 'C' env['LC_ALL'] = 'C' out = subprocess.Popen(cmd, stdout = subprocess.PIPE, env=env).communicate()[0] return out try: out = _minimal_ext_cmd(['git', 'rev-parse', 'HEAD']) GIT_REVISION = out.strip().decode('ascii') except OSError: GIT_REVISION = "Unknown" return GIT_REVISION # BEFORE importing distutils, remove MANIFEST. distutils doesn't properly # update it when the contents of directories change. if os.path.exists('MANIFEST'): os.remove('MANIFEST') # This is a bit hackish: we are setting a global variable so that the main # numpy __init__ can detect if it is being loaded by the setup routine, to # avoid attempting to load components that aren't built yet. While ugly, it's # a lot more robust than what was previously being used. builtins.__NUMPY_SETUP__ = True def get_version_info(): # Adding the git rev number needs to be done inside write_version_py(), # otherwise the import of numpy.version messes up the build under Python 3. FULLVERSION = VERSION if os.path.exists('.git'): GIT_REVISION = git_version() elif os.path.exists('numpy/version.py'): # must be a source distribution, use existing version file try: from numpy.version import git_revision as GIT_REVISION except ImportError: raise ImportError("Unable to import git_revision. Try removing " \ "numpy/version.py and the build directory " \ "before building.") else: GIT_REVISION = "Unknown" if not ISRELEASED: FULLVERSION += '.dev-' + GIT_REVISION[:7] return FULLVERSION, GIT_REVISION def write_version_py(filename='numpy/version.py'): cnt = """ # THIS FILE IS GENERATED FROM NUMPY SETUP.PY short_version = '%(version)s' version = '%(version)s' full_version = '%(full_version)s' git_revision = '%(git_revision)s' release = %(isrelease)s if not release: version = full_version """ FULLVERSION, GIT_REVISION = get_version_info() a = open(filename, 'w') try: a.write(cnt % {'version': VERSION, 'full_version' : FULLVERSION, 'git_revision' : GIT_REVISION, 'isrelease': str(ISRELEASED)}) finally: a.close() def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration(None, parent_package, top_path) config.set_options(ignore_setup_xxx_py=True, assume_default_configuration=True, delegate_options_to_subpackages=True, quiet=True) config.add_subpackage('numpy') config.get_version('numpy/version.py') # sets config.version return config def check_submodules(): """ verify that the submodules are checked out and clean use `git submodule update --init`; on failure """ if not os.path.exists('.git'): return with open('.gitmodules') as f: for l in f: if 'path' in l: p = l.split('=')[-1].strip() if not os.path.exists(p): raise ValueError('Submodule %s missing' % p) proc = subprocess.Popen(['git', 'submodule', 'status'], stdout=subprocess.PIPE) status, _ = proc.communicate() status = status.decode("ascii", "replace") for line in status.splitlines(): if line.startswith('-') or line.startswith('+'): raise ValueError('Submodule not clean: %s' % line) from distutils.command.sdist import sdist class sdist_checked(sdist): """ check submodules on sdist to prevent incomplete tarballs """ def run(self): check_submodules() sdist.run(self) def setup_package(): src_path = os.path.dirname(os.path.abspath(sys.argv[0])) old_path = os.getcwd() os.chdir(src_path) sys.path.insert(0, src_path) # Rewrite the version file everytime write_version_py() metadata = dict( name = 'numpy', maintainer = "NumPy Developers", maintainer_email = "numpy-discussion@scipy.org", description = DOCLINES[0], long_description = "\n".join(DOCLINES[2:]), url = "http://www.numpy.org", author = "Travis E. Oliphant et al.", download_url = "http://sourceforge.net/projects/numpy/files/NumPy/", license = 'BSD', classifiers=[_f for _f in CLASSIFIERS.split('\n') if _f], platforms = ["Windows", "Linux", "Solaris", "Mac OS-X", "Unix"], test_suite='nose.collector', cmdclass={"sdist": sdist_checked}, ) # Run build if len(sys.argv) >= 2 and ('--help' in sys.argv[1:] or sys.argv[1] in ('--help-commands', 'egg_info', '--version', 'clean')): # Use setuptools for these commands (they don't work well or at all # with distutils). For normal builds use distutils. try: from setuptools import setup except ImportError: from distutils.core import setup FULLVERSION, GIT_REVISION = get_version_info() metadata['version'] = FULLVERSION elif len(sys.argv) >= 2 and sys.argv[1] == 'bdist_wheel': # bdist_wheel needs setuptools import setuptools from numpy.distutils.core import setup metadata['configuration'] = configuration else: from numpy.distutils.core import setup metadata['configuration'] = configuration try: setup(**metadata) finally: del sys.path[0] os.chdir(old_path) return if __name__ == '__main__': setup_package() numpy-1.8.2/THANKS.txt0000664000175100017510000000626312370216242015563 0ustar vagrantvagrant00000000000000Travis Oliphant for the NumPy core, the NumPy guide, various bug-fixes and code contributions. Paul Dubois, who implemented the original Masked Arrays. Pearu Peterson for f2py, numpy.distutils and help with code organization. Robert Kern for mtrand, bug fixes, help with distutils, code organization, strided tricks and much more. Eric Jones for planning and code contributions. Fernando Perez for code snippets, ideas, bugfixes, and testing. Ed Schofield for matrix.py patches, bugfixes, testing, and docstrings. Robert Cimrman for array set operations and numpy.distutils help. John Hunter for code snippets from matplotlib. Chris Hanley for help with records.py, testing, and bug fixes. Travis Vaught for administration, community coordination and marketing. Joe Cooper, Jeff Strunk for administration. Eric Firing for bugfixes. Arnd Baecker for 64-bit testing. David Cooke for many code improvements including the auto-generated C-API, and optimizations. Andrew Straw for help with the web-page, documentation, packaging and testing. Alexander Belopolsky (Sasha) for Masked array bug-fixes and tests, rank-0 array improvements, scalar math help and other code additions. Francesc Altet for unicode, work on nested record arrays, and bug-fixes. Tim Hochberg for getting the build working on MSVC, optimization improvements, and code review. Charles (Chuck) Harris for the sorting code originally written for Numarray and for improvements to polyfit, many bug fixes, delving into the C code, release management, and documentation. David Huard for histogram improvements including 2-D and d-D code and other bug-fixes. Stefan van der Walt for numerous bug-fixes, testing and documentation. Albert Strasheim for documentation, bug-fixes, regression tests and Valgrind expertise. David Cournapeau for build support, doc-and-bug fixes, and code contributions including fast_clipping. Jarrod Millman for release management, community coordination, and code clean up. Chris Burns for work on memory mapped arrays and bug-fixes. Pauli Virtanen for documentation, bug-fixes, lookfor and the documentation editor. A.M. Archibald for no-copy-reshape code, strided array tricks, documentation and bug-fixes. Pierre Gerard-Marchant for rewriting masked array functionality. Roberto de Almeida for the buffered array iterator. Alan McIntyre for updating the NumPy test framework to use nose, improve the test coverage, and enhancing the test system documentation. Joe Harrington for administering the 2008 Documentation Sprint. Mark Wiebe for the new NumPy iterator, the float16 data type, improved low-level data type operations, and other NumPy core improvements. NumPy is based on the Numeric (Jim Hugunin, Paul Dubois, Konrad Hinsen, and David Ascher) and NumArray (Perry Greenfield, J Todd Miller, Rick White and Paul Barrett) projects. We thank them for paving the way ahead. Institutions ------------ Enthought for providing resources and finances for development of NumPy. UC Berkeley for providing travel money and hosting numerous sprints. The University of Central Florida for funding the 2008 Documentation Marathon. The University of Stellenbosch for hosting the buildbot. numpy-1.8.2/COMPATIBILITY0000664000175100017510000000312412370216242015757 0ustar vagrantvagrant00000000000000 X.flat returns an indexable 1-D iterator (mostly similar to an array but always 1-d) --- only has .copy and .__array__ attributes of an array!!! .typecode() --> .dtype.char .iscontiguous() --> .flags['CONTIGUOUS'] or .flags.contiguous .byteswapped() -> .byteswap() .itemsize() -> .itemsize .toscalar() -> .item() If you used typecode characters: 'c' -> 'S1' or 'c' 'b' -> 'B' '1' -> 'b' 's' -> 'h' 'w' -> 'H' 'u' -> 'I' C -level some API calls that used to take PyObject * now take PyArrayObject * (this should only cause warnings during compile and not actual problems). PyArray_Take These commands now return a buffer that must be freed once it is used using PyMemData_FREE(ptr); a->descr->zero --> PyArray_Zero(a) a->descr->one --> PyArray_One(a) Numeric/arrayobject.h --> numpy/oldnumeric.h # These will actually work and are defines for PyArray_BYTE, # but you really should change it in your code PyArray_CHAR --> PyArray_CHAR (or PyArray_STRING which is more flexible) PyArray_SBYTE --> PyArray_BYTE Any uses of character codes will need adjusting.... use PyArray_XXXLTR where XXX is the name of the type. If you used function pointers directly (why did you do that?), the arguments have changed. Everything that was an int is now an intp. Also, arrayobjects should be passed in at the end. a->descr->cast[i](fromdata, fromstep, todata, tostep, n) a->descr->cast[i](fromdata, todata, n, PyArrayObject *in, PyArrayObject *out) anything but single-stepping is not supported by this function use the PyArray_CastXXXX functions. numpy-1.8.2/site.cfg.example0000664000175100017510000001434212370216243017107 0ustar vagrantvagrant00000000000000# This file provides configuration information about non-Python dependencies for # numpy.distutils-using packages. Create a file like this called "site.cfg" next # to your package's setup.py file and fill in the appropriate sections. Not all # packages will use all sections so you should leave out sections that your # package does not use. # To assist automatic installation like easy_install, the user's home directory # will also be checked for the file ~/.numpy-site.cfg . # The format of the file is that of the standard library's ConfigParser module. # # http://www.python.org/doc/current/lib/module-ConfigParser.html # # Each section defines settings that apply to one particular dependency. Some of # the settings are general and apply to nearly any section and are defined here. # Settings specific to a particular section will be defined near their section. # # libraries # Comma-separated list of library names to add to compile the extension # with. Note that these should be just the names, not the filenames. For # example, the file "libfoo.so" would become simply "foo". # libraries = lapack,f77blas,cblas,atlas # # library_dirs # List of directories to add to the library search path when compiling # extensions with this dependency. Use the character given by os.pathsep # to separate the items in the list. Note that this character is known to # vary on some unix-like systems; if a colon does not work, try a comma. # This also applies to include_dirs and src_dirs (see below). # On UN*X-type systems (OS X, most BSD and Linux systems): # library_dirs = /usr/lib:/usr/local/lib # On Windows: # library_dirs = c:\mingw\lib,c:\atlas\lib # On some BSD and Linux systems: # library_dirs = /usr/lib,/usr/local/lib # # include_dirs # List of directories to add to the header file earch path. # include_dirs = /usr/include:/usr/local/include # # src_dirs # List of directories that contain extracted source code for the # dependency. For some dependencies, numpy.distutils will be able to build # them from source if binaries cannot be found. The FORTRAN BLAS and # LAPACK libraries are one example. However, most dependencies are more # complicated and require actual installation that you need to do # yourself. # src_dirs = /home/rkern/src/BLAS_SRC:/home/rkern/src/LAPACK_SRC # # search_static_first # Boolean (one of (0, false, no, off) for False or (1, true, yes, on) for # True) to tell numpy.distutils to prefer static libraries (.a) over # shared libraries (.so). It is turned off by default. # search_static_first = false # Defaults # ======== # The settings given here will apply to all other sections if not overridden. # This is a good place to add general library and include directories like # /usr/local/{lib,include} # #[DEFAULT] #library_dirs = /usr/local/lib #include_dirs = /usr/local/include # Atlas # ----- # Atlas is an open source optimized implementation of the BLAS and Lapack # routines. Numpy will try to build against Atlas by default when available in # the system library dirs. To build numpy against a custom installation of # Atlas you can add an explicit section such as the following. Here we assume # that Atlas was configured with ``prefix=/opt/atlas``. # # [atlas] # library_dirs = /opt/atlas/lib # include_dirs = /opt/atlas/include # OpenBLAS # -------- # OpenBLAS is another open source optimized implementation of BLAS and Lapack # and can be seen as an alternative to Atlas. To build numpy against OpenBLAS # instead of Atlas, use this section instead of the above, adjusting as needed # for your configuration (in the following example we installed OpenBLAS with # ``make install PREFIX=/opt/OpenBLAS``. # # **Warning**: OpenBLAS, by default, is built in multithreaded mode. Due to the # way Python's multiprocessing is implemented, a multithreaded OpenBLAS can # cause programs using both to hang as soon as a worker process is forked on # POSIX systems (Linux, Mac). # This is fixed in Openblas 0.2.9 for the pthread build, the OpenMP build using # GNU openmp is as of gcc-4.9 not fixed yet. # Python 3.4 will introduce a new feature in multiprocessing, called the # "forkserver", which solves this problem. For older versions, make sure # OpenBLAS is built using pthreads or use Python threads instead of # multiprocessing. # (This problem does not exist with multithreaded ATLAS.) # # http://docs.python.org/3.4/library/multiprocessing.html#contexts-and-start-methods # https://github.com/xianyi/OpenBLAS/issues/294 # # [openblas] # libraries = openblas # library_dirs = /opt/OpenBLAS/lib # include_dirs = /opt/OpenBLAS/include # MKL #---- # MKL is Intel's very optimized yet proprietary implementation of BLAS and # Lapack. # For recent (9.0.21, for example) mkl, you need to change the names of the # lapack library. Assuming you installed the mkl in /opt, for a 32 bits cpu: # [mkl] # library_dirs = /opt/intel/mkl/9.1.023/lib/32/ # lapack_libs = mkl_lapack # # For 10.*, on 32 bits machines: # [mkl] # library_dirs = /opt/intel/mkl/10.0.1.014/lib/32/ # lapack_libs = mkl_lapack # mkl_libs = mkl, guide # UMFPACK # ------- # The UMFPACK library is used in scikits.umfpack to factor large sparse matrices. # It, in turn, depends on the AMD library for reordering the matrices for # better performance. Note that the AMD library has nothing to do with AMD # (Advanced Micro Devices), the CPU company. # # UMFPACK is not needed for numpy or scipy. # # http://www.cise.ufl.edu/research/sparse/umfpack/ # http://www.cise.ufl.edu/research/sparse/amd/ # http://scikits.appspot.com/umfpack # #[amd] #amd_libs = amd # #[umfpack] #umfpack_libs = umfpack # FFT libraries # ------------- # There are two FFT libraries that we can configure here: FFTW (2 and 3) and djbfft. # Note that these libraries are not needed for numpy or scipy. # # http://fftw.org/ # http://cr.yp.to/djbfft.html # # Given only this section, numpy.distutils will try to figure out which version # of FFTW you are using. #[fftw] #libraries = fftw3 # # For djbfft, numpy.distutils will look for either djbfft.a or libdjbfft.a . #[djbfft] #include_dirs = /usr/local/djbfft/include #library_dirs = /usr/local/djbfft/lib numpy-1.8.2/DEV_README.txt0000664000175100017510000000124712370216242016223 0ustar vagrantvagrant00000000000000Thank you for your willingness to help make NumPy the best array system available. We have a few simple rules: * try hard to keep the Git repository in a buildable state and to not indiscriminately muck with what others have contributed. * Simple changes (including bug fixes) and obvious improvements are always welcome. Changes that fundamentally change behavior need discussion on numpy-discussions@scipy.org before anything is done. * Please add meaningful comments when you check changes in. These comments form the basis of the change-log. * Add unit tests to exercise new code, and regression tests whenever you fix a bug. numpy-1.8.2/INSTALL.txt0000664000175100017510000001061112370216242015671 0ustar vagrantvagrant00000000000000.. -*- rest -*- .. vim:syntax=rest .. NB! Keep this document a valid restructured document. Building and installing NumPy +++++++++++++++++++++++++++++ :Authors: Numpy Developers :Discussions to: numpy-discussion@scipy.org .. Contents:: PREREQUISITES ============= Building NumPy requires the following software installed: 1) For Python 2, Python__ 2.6.x or newer. For Python 3, Python__ 3.2.x or newer. On Debian and derivative (Ubuntu): python python-dev On Windows: the official python installer on Python__ is enough Make sure that the Python package distutils is installed before continuing. For example, in Debian GNU/Linux, distutils is included in the python-dev package. Python must also be compiled with the zlib module enabled. 2) nose__ (optional) 0.10.3 or later This is required for testing numpy, but not for using it. Python__ http://www.python.org nose__ http://somethingaboutorange.com/mrl/projects/nose/ Fortran ABI mismatch ==================== The two most popular open source fortran compilers are g77 and gfortran. Unfortunately, they are not ABI compatible, which means that concretely you should avoid mixing libraries built with one with another. In particular, if your blas/lapack/atlas is built with g77, you *must* use g77 when building numpy and scipy; on the contrary, if your atlas is built with gfortran, you *must* build numpy/scipy with gfortran. Choosing the fortran compiler ----------------------------- To build with g77: python setup.py build --fcompiler=gnu To build with gfortran: python setup.py build --fcompiler=gnu95 How to check the ABI of blas/lapack/atlas ----------------------------------------- One relatively simple and reliable way to check for the compiler used to build a library is to use ldd on the library. If libg2c.so is a dependency, this means that g77 has been used. If libgfortran.so is a dependency, gfortran has been used. If both are dependencies, this means both have been used, which is almost always a very bad idea. Building with ATLAS support =========================== Ubuntu 8.10 (Intrepid) ---------------------- You can install the necessary packages for optimized ATLAS with this command: sudo apt-get install libatlas-base-dev If you have a recent CPU with SIMD support (SSE, SSE2, etc...), you should also install the corresponding package for optimal performance. For example, for SSE2: sudo apt-get install libatlas3gf-sse2 *NOTE*: if you build your own atlas, Intrepid changed its default fortran compiler to gfortran. So you should rebuild everything from scratch, including lapack, to use it on Intrepid. Ubuntu 8.04 and lower --------------------- You can install the necessary packages for optimized ATLAS with this command: sudo apt-get install atlas3-base-dev If you have a recent CPU with SIMD support (SSE, SSE2, etc...), you should also install the corresponding package for optimal performance. For example, for SSE2: sudo apt-get install atlas3-sse2 Windows 64 bits notes ===================== Note: only AMD64 is supported (IA64 is not) - AMD64 is the version most people want. Free compilers (mingw-w64) -------------------------- http://mingw-w64.sourceforge.net/ To use the free compilers (mingw-w64), you need to build your own toolchain, as the mingw project only distribute cross-compilers (cross-compilation is not supported by numpy). Since this toolchain is still being worked on, serious compiler bugs can be expected. binutil 2.19 + gcc 4.3.3 + mingw-w64 runtime gives you a working C compiler (but the C++ is broken). gcc 4.4 will hopefully be able to run natively. This is the only tested way to get a numpy with a FULL blas/lapack (scipy does not work because of C++). MS compilers ------------ If you are familiar with MS tools, that's obviously the easiest path, and the compilers are hopefully more mature (although in my experience, they are quite fragile, and often segfault on invalid C code). The main drawback is that no fortran compiler + MS compiler combination has been tested - mingw-w64 gfortran + MS compiler does not work at all (it is unclear whether it ever will). For python 2.6, you need VS 2008. The freely available version does not contains 64 bits compilers (you also need the PSDK, v6.1). It is crucial to use the right MS compiler version. For python 2.6, you must use version 15. You can check the compiler version with cl.exe /?.